diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/artifacts/_list_artifact_meta.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/artifacts/_list_artifact_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..a70c96af4bab3e65595f5c4d9fd13d5a8065bcc5 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/artifacts/_list_artifact_meta.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +from optuna.artifacts._upload import ArtifactMeta +from optuna.artifacts._upload import ARTIFACTS_ATTR_PREFIX +from optuna.study import Study +from optuna.trial import FrozenTrial +from optuna.trial import Trial + + +if TYPE_CHECKING: + from optuna.storages import BaseStorage + + +def get_all_artifact_meta( + study_or_trial: Trial | FrozenTrial | Study, *, storage: BaseStorage | None = None +) -> list[ArtifactMeta]: + """List the associated artifact information of the provided trial or study. + + Args: + study_or_trial: + A :class:`~optuna.trial.Trial` object, a :class:`~optuna.trial.FrozenTrial`, or + a :class:`~optuna.study.Study` object. + storage: + A storage object. This argument is required only if ``study_or_trial`` is + :class:`~optuna.trial.FrozenTrial`. + + Example: + An example where this function is useful: + + .. code:: + + import os + + import optuna + + + # Get the storage that contains the study of interest. + storage = optuna.storages.get_storage(storage=...) + + # Instantiate the artifact store used for the study. + # Optuna does not provide the API that stores the used artifact store information, so + # please manage the information in the user side. + artifact_store = ... + + # Load study that contains the artifacts of interest. + study = optuna.load_study(study_name=..., storage=storage) + + # Fetch the best trial. + best_trial = study.best_trial + + # Fetch all the artifact meta connected to the best trial. + artifact_metas = optuna.artifacts.get_all_artifact_meta(best_trial, storage=storage) + + download_dir_path = "./best_trial_artifacts/" + os.makedirs(download_dir_path, exist_ok=True) + + for artifact_meta in artifact_metas: + download_file_path = os.path.join(download_dir_path, artifact_meta.filename) + # Download the artifacts to ``download_file_path``. + optuna.artifacts.download_artifact( + artifact_store=artifact_store, + artifact_id=artifact_meta.artifact_id, + file_path=download_file_path, + ) + + Returns: + The list of artifact meta in the trial or study. + Each artifact meta includes ``artifact_id``, ``filename``, ``mimetype``, and ``encoding``. + Note that if :class:`~optuna.study.Study` is provided, we return the information of the + artifacts uploaded to ``study``, but not to all the trials in the study. + """ + if isinstance(study_or_trial, Trial) and storage is None: + storage = study_or_trial.storage + elif isinstance(study_or_trial, Study) and storage is None: + storage = study_or_trial._storage + + if storage is None: + raise ValueError("storage is required for FrozenTrial.") + + if isinstance(study_or_trial, (Trial, FrozenTrial)): + system_attrs = storage.get_trial_system_attrs(study_or_trial._trial_id) + else: + system_attrs = storage.get_study_system_attrs(study_or_trial._study_id) + + artifact_meta_list: list[ArtifactMeta] = [] + for attr_key, attr_json_string in system_attrs.items(): + if not attr_key.startswith(ARTIFACTS_ATTR_PREFIX): + continue + + attr_content = json.loads(attr_json_string) + artifact_meta = ArtifactMeta( + artifact_id=attr_content["artifact_id"], + filename=attr_content["filename"], + mimetype=attr_content["mimetype"], + encoding=attr_content["encoding"], + ) + artifact_meta_list.append(artifact_meta) + + return artifact_meta_list diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b59b211b297f17f0cbcdf4830d9b1485390ed494 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__init__.py @@ -0,0 +1,110 @@ +from __future__ import annotations + +from collections.abc import Callable + +from optuna._experimental import warn_experimental_argument +from optuna.importance._base import BaseImportanceEvaluator +from optuna.importance._fanova import FanovaImportanceEvaluator +from optuna.importance._mean_decrease_impurity import MeanDecreaseImpurityImportanceEvaluator +from optuna.importance._ped_anova import PedAnovaImportanceEvaluator +from optuna.study import Study +from optuna.trial import FrozenTrial + + +__all__ = [ + "BaseImportanceEvaluator", + "FanovaImportanceEvaluator", + "MeanDecreaseImpurityImportanceEvaluator", + "PedAnovaImportanceEvaluator", + "get_param_importances", +] + + +def get_param_importances( + study: Study, + *, + evaluator: BaseImportanceEvaluator | None = None, + params: list[str] | None = None, + target: Callable[[FrozenTrial], float] | None = None, + normalize: bool = True, +) -> dict[str, float]: + """Evaluate parameter importances based on completed trials in the given study. + + The parameter importances are returned as a dictionary where the keys consist of parameter + names and their values importances. + The importances are represented by non-negative floating point numbers, where higher values + mean that the parameters are more important. + The returned dictionary is ordered by its values in a descending order. + By default, the sum of the importance values are normalized to 1.0. + + If ``params`` is :obj:`None`, all parameter that are present in all of the completed trials are + assessed. + This implies that conditional parameters will be excluded from the evaluation. + To assess the importances of conditional parameters, a :obj:`list` of parameter names can be + specified via ``params``. + If specified, only completed trials that contain all of the parameters will be considered. + If no such trials are found, an error will be raised. + + If the given study does not contain completed trials, an error will be raised. + + .. note:: + + If ``params`` is specified as an empty list, an empty dictionary is returned. + + .. seealso:: + + See :func:`~optuna.visualization.plot_param_importances` to plot importances. + + Args: + study: + An optimized study. + evaluator: + An importance evaluator object that specifies which algorithm to base the importance + assessment on. + Defaults to + :class:`~optuna.importance.FanovaImportanceEvaluator`. + params: + A list of names of parameters to assess. + If :obj:`None`, all parameters that are present in all of the completed trials are + assessed. + target: + A function to specify the value to evaluate importances. + If it is :obj:`None` and ``study`` is being used for single-objective optimization, + the objective values are used. ``target`` must be specified if ``study`` is being + used for multi-objective optimization. + + .. note:: + Specify this argument if ``study`` is being used for multi-objective + optimization. For example, to get the hyperparameter importance of the first + objective, use ``target=lambda t: t.values[0]`` for the target parameter. + normalize: + A boolean option to specify whether the sum of the importance values should be + normalized to 1.0. + Defaults to :obj:`True`. + + .. note:: + Added in v3.0.0 as an experimental feature. The interface may change in newer + versions without prior notice. See + https://github.com/optuna/optuna/releases/tag/v3.0.0. + + Returns: + A :obj:`dict` where the keys are parameter names and the values are assessed importances. + + """ + if evaluator is None: + evaluator = FanovaImportanceEvaluator() + + if not isinstance(evaluator, BaseImportanceEvaluator): + raise TypeError("Evaluator must be a subclass of BaseImportanceEvaluator.") + + res = evaluator.evaluate(study, params=params, target=target) + if normalize: + s = sum(res.values()) + if s == 0.0: + n_params = len(res) + return dict((param, 1.0 / n_params) for param in res.keys()) + else: + return dict((param, value / s) for (param, value) in res.items()) + else: + warn_experimental_argument("normalize") + return res diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1ec65907d3f2d43b44c04d512b2f343715ea88a Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_base.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4904e4ecfc170eb7ebc6995a3ab526821fae8737 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_base.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_mean_decrease_impurity.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_mean_decrease_impurity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6f63c4740d66c27f54f7c7f786f21902335ca56 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/__pycache__/_mean_decrease_impurity.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3976c06ae2452b09fe628db9e339984906ac6d7 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__init__.py @@ -0,0 +1,4 @@ +from optuna.importance._fanova._evaluator import FanovaImportanceEvaluator + + +__all__ = ["FanovaImportanceEvaluator"] diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccb1d0f38eee499766d5270dafe4157f797d86ba Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/_tree.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/_tree.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47bcba8021db06d04af0dadee5852a2ed6cd0a24 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/__pycache__/_tree.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/_fanova.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/_fanova.py new file mode 100644 index 0000000000000000000000000000000000000000..122e12bbda75a7076b9e8f78314c83cec25b23b4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_fanova/_fanova.py @@ -0,0 +1,108 @@ +"""An implementation of `An Efficient Approach for Assessing Hyperparameter Importance`. + +See http://proceedings.mlr.press/v32/hutter14.pdf and https://automl.github.io/fanova/cite.html +for how to cite the original work. + +This implementation is inspired by the efficient algorithm in +`fanova` (https://github.com/automl/fanova) and +`pyrfr` (https://github.com/automl/random_forest_run) by the original authors. + +Differences include relying on scikit-learn to fit random forests +(`sklearn.ensemble.RandomForestRegressor`) and that it is otherwise written entirely in Python. +This stands in contrast to the original implementation which is partially written in C++. +Since Python runtime overhead may become noticeable, included are instead several +optimizations, e.g. vectorized NumPy functions to compute the marginals, instead of keeping all +running statistics. Known cases include assessing categorical features with a larger +number of choices since each choice is given a unique one-hot encoded raw feature. +""" + +from __future__ import annotations + +import numpy as np + +from optuna._imports import try_import +from optuna.importance._fanova._tree import _FanovaTree + + +with try_import() as _imports: + from sklearn.ensemble import RandomForestRegressor + + +class _Fanova: + def __init__( + self, + n_trees: int, + max_depth: int, + min_samples_split: int | float, + min_samples_leaf: int | float, + seed: int | None, + ) -> None: + _imports.check() + + self._forest = RandomForestRegressor( + n_estimators=n_trees, + max_depth=max_depth, + min_samples_split=min_samples_split, + min_samples_leaf=min_samples_leaf, + random_state=seed, + ) + self._trees: list[_FanovaTree] | None = None + self._variances: dict[int, np.ndarray] | None = None + self._column_to_encoded_columns: list[np.ndarray] | None = None + + def fit( + self, + X: np.ndarray, + y: np.ndarray, + search_spaces: np.ndarray, + column_to_encoded_columns: list[np.ndarray], + ) -> None: + assert X.shape[0] == y.shape[0] + assert X.shape[1] == search_spaces.shape[0] + assert search_spaces.shape[1] == 2 + + self._forest.fit(X, y) + + self._trees = [_FanovaTree(e.tree_, search_spaces) for e in self._forest.estimators_] + self._column_to_encoded_columns = column_to_encoded_columns + self._variances = {} + + if all(tree.variance == 0 for tree in self._trees): + # If all trees have 0 variance, we cannot assess any importances. + # This could occur if for instance `X.shape[0] == 1`. + raise RuntimeError("Encountered zero total variance in all trees.") + + def get_importance(self, feature: int) -> tuple[float, float]: + # Assert that `fit` has been called. + assert self._trees is not None + assert self._variances is not None + + self._compute_variances(feature) + + fractions: list[float] | np.ndarray = [] + + for tree_index, tree in enumerate(self._trees): + tree_variance = tree.variance + if tree_variance > 0.0: + fraction = self._variances[feature][tree_index] / tree_variance + fractions = np.append(fractions, fraction) + + fractions = np.asarray(fractions) + + return float(fractions.mean()), float(fractions.std()) + + def _compute_variances(self, feature: int) -> None: + assert self._trees is not None + assert self._variances is not None + assert self._column_to_encoded_columns is not None + + if feature in self._variances: + return + + raw_features = self._column_to_encoded_columns[feature] + variances = np.empty(len(self._trees), dtype=np.float64) + + for tree_index, tree in enumerate(self._trees): + marginal_variance = tree.get_marginal_variance(raw_features) + variances[tree_index] = np.clip(marginal_variance, 0.0, None) + self._variances[feature] = variances diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1e0c1c57844b80a76f1432d2f7bedeb540b457 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__init__.py @@ -0,0 +1,4 @@ +from optuna.importance._ped_anova.evaluator import PedAnovaImportanceEvaluator + + +__all__ = ["PedAnovaImportanceEvaluator"] diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71cd22a2cd1db9daba1a7462dbc08bfeefdcca9e Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/evaluator.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/evaluator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..147ab3f6c7e745b8f2cde3582809c152bae7b622 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/evaluator.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/scott_parzen_estimator.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/scott_parzen_estimator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a70bbd18d4530bd93154935d8c481903ac888d4 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/__pycache__/scott_parzen_estimator.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/evaluator.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..22fce6593392a51bfc8f7883ffb16a47067751bb --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/evaluator.py @@ -0,0 +1,227 @@ +from __future__ import annotations + +from collections.abc import Callable +import warnings + +import numpy as np + +from optuna._experimental import experimental_class +from optuna.distributions import BaseDistribution +from optuna.importance._base import _get_distributions +from optuna.importance._base import _get_filtered_trials +from optuna.importance._base import _sort_dict_by_importance +from optuna.importance._base import BaseImportanceEvaluator +from optuna.importance._ped_anova.scott_parzen_estimator import _build_parzen_estimator +from optuna.logging import get_logger +from optuna.study import Study +from optuna.study import StudyDirection +from optuna.trial import FrozenTrial + + +_logger = get_logger(__name__) + + +class _QuantileFilter: + def __init__( + self, + quantile: float, + is_lower_better: bool, + min_n_top_trials: int, + target: Callable[[FrozenTrial], float] | None, + ): + assert 0 <= quantile <= 1, "quantile must be in [0, 1]." + assert min_n_top_trials > 0, "min_n_top_trials must be positive." + + self._quantile = quantile + self._is_lower_better = is_lower_better + self._min_n_top_trials = min_n_top_trials + self._target = target + + def filter(self, trials: list[FrozenTrial]) -> list[FrozenTrial]: + target, min_n_top_trials = self._target, self._min_n_top_trials + sign = 1.0 if self._is_lower_better else -1.0 + loss_values = sign * np.asarray([t.value if target is None else target(t) for t in trials]) + err_msg = "len(trials) must be larger than or equal to min_n_top_trials" + assert min_n_top_trials <= loss_values.size, err_msg + + def _quantile(v: np.ndarray, q: float) -> float: + cutoff_index = int(np.ceil(q * loss_values.size)) - 1 + return float(np.partition(loss_values, cutoff_index)[cutoff_index]) + + cutoff_val = max( + np.partition(loss_values, min_n_top_trials - 1)[min_n_top_trials - 1], + # TODO(nabenabe0928): After dropping Python3.10, replace below with + # np.quantile(loss_values, self._quantile, method="inverted_cdf"). + _quantile(loss_values, self._quantile), + ) + should_keep_trials = loss_values <= cutoff_val + return [t for t, should_keep in zip(trials, should_keep_trials) if should_keep] + + +@experimental_class("3.6.0") +class PedAnovaImportanceEvaluator(BaseImportanceEvaluator): + """PED-ANOVA importance evaluator. + + Implements the PED-ANOVA hyperparameter importance evaluation algorithm. + + PED-ANOVA fits Parzen estimators of :class:`~optuna.trial.TrialState.COMPLETE` trials better + than a user-specified baseline. Users can specify the baseline by a quantile. + The importance can be interpreted as how important each hyperparameter is to get + the performance better than baseline. + + For further information about PED-ANOVA algorithm, please refer to the following paper: + + - `PED-ANOVA: Efficiently Quantifying Hyperparameter Importance in Arbitrary Subspaces + `__ + + .. note:: + + The performance of PED-ANOVA depends on how many trials to consider above baseline. + To stabilize the analysis, it is preferable to include at least 5 trials above baseline. + + .. note:: + + Please refer to `the original work `__. + + Args: + baseline_quantile: + Compute the importance of achieving top-``baseline_quantile`` quantile objective value. + For example, ``baseline_quantile=0.1`` means that the importances give the information + of which parameters were important to achieve the top-10% performance during + optimization. + evaluate_on_local: + Whether we measure the importance in the local or global space. + If :obj:`True`, the importances imply how importance each parameter is during + optimization. Meanwhile, ``evaluate_on_local=False`` gives the importances in the + specified search_space. ``evaluate_on_local=True`` is especially useful when users + modify search space during optimization. + + Example: + An example of using PED-ANOVA is as follows: + + .. testcode:: + + import optuna + from optuna.importance import PedAnovaImportanceEvaluator + + + def objective(trial): + x1 = trial.suggest_float("x1", -10, 10) + x2 = trial.suggest_float("x2", -10, 10) + return x1 + x2 / 1000 + + + study = optuna.create_study() + study.optimize(objective, n_trials=100) + evaluator = PedAnovaImportanceEvaluator() + importance = optuna.importance.get_param_importances(study, evaluator=evaluator) + + """ + + def __init__( + self, + *, + baseline_quantile: float = 0.1, + evaluate_on_local: bool = True, + ): + assert 0.0 <= baseline_quantile <= 1.0, "baseline_quantile must be in [0, 1]." + self._baseline_quantile = baseline_quantile + self._evaluate_on_local = evaluate_on_local + + # Advanced Setups. + # Discretize a domain [low, high] as `np.linspace(low, high, n_steps)`. + self._n_steps: int = 50 + # Control the regularization effect by prior. + self._prior_weight = 1.0 + # How many `trials` must be included in `top_trials`. + self._min_n_top_trials = 2 + + def _get_top_trials( + self, + study: Study, + trials: list[FrozenTrial], + params: list[str], + target: Callable[[FrozenTrial], float] | None, + ) -> list[FrozenTrial]: + is_lower_better = study.directions[0] == StudyDirection.MINIMIZE + if target is not None: + warnings.warn( + f"{self.__class__.__name__} computes the importances of params to achieve " + "low `target` values. If this is not what you want, " + "please modify target, e.g., by multiplying the output by -1." + ) + is_lower_better = True + + top_trials = _QuantileFilter( + self._baseline_quantile, is_lower_better, self._min_n_top_trials, target + ).filter(trials) + + if len(trials) == len(top_trials): + _logger.warning("All trials are in top trials, which gives equal importances.") + + return top_trials + + def _compute_pearson_divergence( + self, + param_name: str, + dist: BaseDistribution, + top_trials: list[FrozenTrial], + all_trials: list[FrozenTrial], + ) -> float: + # When pdf_all == pdf_top, i.e. all_trials == top_trials, this method will give 0.0. + prior_weight = self._prior_weight + pe_top = _build_parzen_estimator(param_name, dist, top_trials, self._n_steps, prior_weight) + # NOTE: pe_top.n_steps could be different from self._n_steps. + grids = np.arange(pe_top.n_steps) + pdf_top = pe_top.pdf(grids) + 1e-12 + + if self._evaluate_on_local: # The importance of param during the study. + pe_local = _build_parzen_estimator( + param_name, dist, all_trials, self._n_steps, prior_weight + ) + pdf_local = pe_local.pdf(grids) + 1e-12 + else: # The importance of param in the search space. + pdf_local = np.full(pe_top.n_steps, 1.0 / pe_top.n_steps) + + return float(pdf_local @ ((pdf_top / pdf_local - 1) ** 2)) + + def evaluate( + self, + study: Study, + params: list[str] | None = None, + *, + target: Callable[[FrozenTrial], float] | None = None, + ) -> dict[str, float]: + dists = _get_distributions(study, params=params) + if params is None: + params = list(dists.keys()) + + assert params is not None + # PED-ANOVA does not support parameter distributions with a single value, + # because the importance of such params become zero. + non_single_dists = {name: dist for name, dist in dists.items() if not dist.single()} + single_dists = {name: dist for name, dist in dists.items() if dist.single()} + if len(non_single_dists) == 0: + return {} + + trials = _get_filtered_trials(study, params=params, target=target) + n_params = len(non_single_dists) + # The following should be tested at _get_filtered_trials. + assert target is not None or max([len(t.values) for t in trials], default=1) == 1 + if len(trials) <= self._min_n_top_trials: + param_importances = {k: 1.0 / n_params for k in non_single_dists} + param_importances.update({k: 0.0 for k in single_dists}) + return {k: 0.0 for k in param_importances} + + top_trials = self._get_top_trials(study, trials, params, target) + quantile = len(top_trials) / len(trials) + importance_sum = 0.0 + param_importances = {} + for param_name, dist in non_single_dists.items(): + param_importances[param_name] = quantile * self._compute_pearson_divergence( + param_name, dist, top_trials=top_trials, all_trials=trials + ) + importance_sum += param_importances[param_name] + + param_importances.update({k: 0.0 for k in single_dists}) + return _sort_dict_by_importance(param_importances) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/scott_parzen_estimator.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/scott_parzen_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..51abf97f26643e7006983c57876d5098065b3d57 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/importance/_ped_anova/scott_parzen_estimator.py @@ -0,0 +1,157 @@ +from __future__ import annotations + +import numpy as np + +from optuna.distributions import BaseDistribution +from optuna.distributions import CategoricalDistribution +from optuna.distributions import FloatDistribution +from optuna.distributions import IntDistribution +from optuna.samplers._tpe.parzen_estimator import _ParzenEstimator +from optuna.samplers._tpe.parzen_estimator import _ParzenEstimatorParameters +from optuna.samplers._tpe.probability_distributions import _BatchedDiscreteTruncNormDistributions +from optuna.samplers._tpe.probability_distributions import _BatchedDistributions +from optuna.trial import FrozenTrial + + +class _ScottParzenEstimator(_ParzenEstimator): + """1D ParzenEstimator using the bandwidth selection by Scott's rule.""" + + def __init__( + self, + param_name: str, + dist: IntDistribution | CategoricalDistribution, + counts: np.ndarray, + prior_weight: float, + ): + assert isinstance(dist, (CategoricalDistribution, IntDistribution)) + assert not isinstance(dist, IntDistribution) or dist.low == 0 + n_choices = dist.high + 1 if isinstance(dist, IntDistribution) else len(dist.choices) + assert len(counts) == n_choices, counts + + self._n_steps = len(counts) + self._param_name = param_name + self._counts = counts.copy() + super().__init__( + observations={param_name: np.arange(self._n_steps)[counts > 0.0]}, + search_space={param_name: dist}, + parameters=_ParzenEstimatorParameters( + prior_weight=prior_weight, + consider_magic_clip=False, + consider_endpoints=False, + weights=lambda x: np.empty(0), + multivariate=True, + categorical_distance_func={}, + ), + predetermined_weights=counts[counts > 0.0], + ) + + def _calculate_numerical_distributions( + self, + observations: np.ndarray, + low: float, # The type is actually int, but typing follows the original. + high: float, # The type is actually int, but typing follows the original. + step: float | None, + parameters: _ParzenEstimatorParameters, + ) -> _BatchedDistributions: + # NOTE: The Optuna TPE bandwidth selection is too wide for this analysis. + # So use the Scott's rule by Scott, D.W. (1992), + # Multivariate Density Estimation: Theory, Practice, and Visualization. + assert step is not None and np.isclose(step, 1.0), "MyPy redefinition." + + n_trials = np.sum(self._counts) + counts_non_zero = self._counts[self._counts > 0] + weights = counts_non_zero / n_trials + mus = np.arange(self.n_steps)[self._counts > 0] + mean_est = mus @ weights + sigma_est = np.sqrt((mus - mean_est) ** 2 @ counts_non_zero / max(1, n_trials - 1)) + + count_cum = np.cumsum(counts_non_zero) + idx_q25 = np.searchsorted(count_cum, n_trials // 4, side="left") + idx_q75 = np.searchsorted(count_cum, n_trials * 3 // 4, side="right") + interquantile_range = mus[min(mus.size - 1, idx_q75)] - mus[idx_q25] + sigma_est = 1.059 * min(interquantile_range / 1.34, sigma_est) * n_trials ** (-0.2) + # To avoid numerical errors. 0.5/1.64 means 1.64sigma (=90%) will fit in the target grid. + sigma_min = 0.5 / 1.64 + sigmas = np.full_like(mus, max(sigma_est, sigma_min), dtype=np.float64) + mus = np.append(mus, [0.5 * (low + high)]) + sigmas = np.append(sigmas, [1.0 * (high - low + 1)]) + + return _BatchedDiscreteTruncNormDistributions( + mu=mus, sigma=sigmas, low=0, high=self.n_steps - 1, step=1 + ) + + @property + def n_steps(self) -> int: + return self._n_steps + + def pdf(self, samples: np.ndarray) -> np.ndarray: + return np.exp(self.log_pdf({self._param_name: samples})) + + +def _get_grids_and_grid_indices_of_trials( + param_name: str, + dist: IntDistribution | FloatDistribution, + trials: list[FrozenTrial], + n_steps: int, +) -> tuple[int, np.ndarray]: + assert isinstance(dist, (FloatDistribution, IntDistribution)), "Unexpected distribution." + if isinstance(dist, IntDistribution) and dist.log: + log2_domain_size = int(np.ceil(np.log(dist.high - dist.low + 1) / np.log(2))) + 1 + n_steps = min(log2_domain_size, n_steps) + elif dist.step is not None: + assert not dist.log, "log must be False when step is not None." + n_steps = min(round((dist.high - dist.low) / dist.step) + 1, n_steps) + + scaler = np.log if dist.log else np.asarray + grids = np.linspace(scaler(dist.low), scaler(dist.high), n_steps) + params = scaler([t.params[param_name] for t in trials]) + step_size = grids[1] - grids[0] + # grids[indices[n] - 1] < param - step_size / 2 <= grids[indices[n]] + indices = np.searchsorted(grids, params - step_size / 2) + return grids.size, indices + + +def _count_numerical_param_in_grid( + param_name: str, + dist: IntDistribution | FloatDistribution, + trials: list[FrozenTrial], + n_steps: int, +) -> np.ndarray: + n_grids, grid_indices_of_trials = _get_grids_and_grid_indices_of_trials( + param_name, dist, trials, n_steps + ) + unique_vals, counts_in_unique = np.unique(grid_indices_of_trials, return_counts=True) + counts = np.zeros(n_grids, dtype=np.int32) + counts[unique_vals] += counts_in_unique + return counts + + +def _count_categorical_param_in_grid( + param_name: str, dist: CategoricalDistribution, trials: list[FrozenTrial] +) -> np.ndarray: + cat_indices = [int(dist.to_internal_repr(t.params[param_name])) for t in trials] + unique_vals, counts_in_unique = np.unique(cat_indices, return_counts=True) + counts = np.zeros(len(dist.choices), dtype=np.int32) + counts[unique_vals] += counts_in_unique + return counts + + +def _build_parzen_estimator( + param_name: str, + dist: BaseDistribution, + trials: list[FrozenTrial], + n_steps: int, + prior_weight: float, +) -> _ScottParzenEstimator: + rounded_dist: IntDistribution | CategoricalDistribution + if isinstance(dist, (IntDistribution, FloatDistribution)): + counts = _count_numerical_param_in_grid(param_name, dist, trials, n_steps) + rounded_dist = IntDistribution(low=0, high=counts.size - 1) + elif isinstance(dist, CategoricalDistribution): + counts = _count_categorical_param_in_grid(param_name, dist, trials) + rounded_dist = dist + else: + assert False, f"Got an unknown dist with the type {type(dist)}." + + # counts.astype(float) is necessary for weight calculation in ParzenEstimator. + return _ScottParzenEstimator(param_name, rounded_dist, counts.astype(np.float64), prior_weight) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c7f7abb8361daeab07e76af475fc3dd44d0cc97b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__init__.py @@ -0,0 +1,12 @@ +from optuna.search_space.group_decomposed import _GroupDecomposedSearchSpace +from optuna.search_space.group_decomposed import _SearchSpaceGroup +from optuna.search_space.intersection import intersection_search_space +from optuna.search_space.intersection import IntersectionSearchSpace + + +__all__ = [ + "_GroupDecomposedSearchSpace", + "_SearchSpaceGroup", + "IntersectionSearchSpace", + "intersection_search_space", +] diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__pycache__/group_decomposed.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__pycache__/group_decomposed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0847be96eba2b89a30b77a0128e2271690ec8ef Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/search_space/__pycache__/group_decomposed.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..825d43afaf5b8d90459eebcc3e6528fb8c437e19 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__init__.py @@ -0,0 +1,28 @@ +from optuna.terminator.callback import TerminatorCallback +from optuna.terminator.erroreval import BaseErrorEvaluator +from optuna.terminator.erroreval import CrossValidationErrorEvaluator +from optuna.terminator.erroreval import report_cross_validation_scores +from optuna.terminator.erroreval import StaticErrorEvaluator +from optuna.terminator.improvement.emmr import EMMREvaluator +from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator +from optuna.terminator.improvement.evaluator import BestValueStagnationEvaluator +from optuna.terminator.improvement.evaluator import RegretBoundEvaluator +from optuna.terminator.median_erroreval import MedianErrorEvaluator +from optuna.terminator.terminator import BaseTerminator +from optuna.terminator.terminator import Terminator + + +__all__ = [ + "TerminatorCallback", + "BaseErrorEvaluator", + "CrossValidationErrorEvaluator", + "report_cross_validation_scores", + "StaticErrorEvaluator", + "MedianErrorEvaluator", + "BaseImprovementEvaluator", + "BestValueStagnationEvaluator", + "RegretBoundEvaluator", + "EMMREvaluator", + "BaseTerminator", + "Terminator", +] diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17d4b59b52b42a9b287734caf5cf27a7a063ad85 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/callback.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/callback.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7a49a74494e0f9dc515e5fdcf23ec7108c0f2cd Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/callback.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/erroreval.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/erroreval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..224166af7d0a070f12822f77a847fa10fc9b503b Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/erroreval.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/median_erroreval.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/median_erroreval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aff8adcc61e3eda781684373d8a728167715eaa5 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/median_erroreval.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/terminator.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/terminator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e784eb46458d211df186834759546e58f3a5b6c0 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/__pycache__/terminator.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/callback.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..ae9ec2ab64f6558df9ab827e2475329eb63ff4a7 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/callback.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from optuna._experimental import experimental_class +from optuna.logging import get_logger +from optuna.study.study import Study +from optuna.terminator.terminator import BaseTerminator +from optuna.terminator.terminator import Terminator +from optuna.trial import FrozenTrial + + +_logger = get_logger(__name__) + + +@experimental_class("3.2.0") +class TerminatorCallback: + """A callback that terminates the optimization using Terminator. + + This class implements a callback which wraps :class:`~optuna.terminator.Terminator` + so that it can be used with the :func:`~optuna.study.Study.optimize` method. + + Args: + terminator: + A terminator object which determines whether to terminate the optimization by + assessing the room for optimization and statistical error. Defaults to a + :class:`~optuna.terminator.Terminator` object with default + ``improvement_evaluator`` and ``error_evaluator``. + + Example: + + .. testcode:: + + from sklearn.datasets import load_wine + from sklearn.ensemble import RandomForestClassifier + from sklearn.model_selection import cross_val_score + from sklearn.model_selection import KFold + + import optuna + from optuna.terminator import TerminatorCallback + from optuna.terminator import report_cross_validation_scores + + + def objective(trial): + X, y = load_wine(return_X_y=True) + + clf = RandomForestClassifier( + max_depth=trial.suggest_int("max_depth", 2, 32), + min_samples_split=trial.suggest_float("min_samples_split", 0, 1), + criterion=trial.suggest_categorical("criterion", ("gini", "entropy")), + ) + + scores = cross_val_score(clf, X, y, cv=KFold(n_splits=5, shuffle=True)) + report_cross_validation_scores(trial, scores) + return scores.mean() + + + study = optuna.create_study(direction="maximize") + terminator = TerminatorCallback() + study.optimize(objective, n_trials=50, callbacks=[terminator]) + + .. seealso:: + Please refer to :class:`~optuna.terminator.Terminator` for the details of + the terminator mechanism. + """ + + def __init__(self, terminator: BaseTerminator | None = None) -> None: + self._terminator = terminator or Terminator() + + def __call__(self, study: Study, trial: FrozenTrial) -> None: + should_terminate = self._terminator.should_terminate(study=study) + + if should_terminate: + _logger.info("The study has been stopped by the terminator.") + study.stop() diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/erroreval.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/erroreval.py new file mode 100644 index 0000000000000000000000000000000000000000..c7f78f1b7b2ff0c59251d3bb47f659d9152cb3d4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/erroreval.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import abc +from typing import cast + +import numpy as np + +from optuna._experimental import experimental_class +from optuna.study import StudyDirection +from optuna.trial import FrozenTrial +from optuna.trial import Trial +from optuna.trial._state import TrialState + + +_CROSS_VALIDATION_SCORES_KEY = "terminator:cv_scores" + + +class BaseErrorEvaluator(metaclass=abc.ABCMeta): + """Base class for error evaluators.""" + + @abc.abstractmethod + def evaluate( + self, + trials: list[FrozenTrial], + study_direction: StudyDirection, + ) -> float: + pass + + +@experimental_class("3.2.0") +class CrossValidationErrorEvaluator(BaseErrorEvaluator): + """An error evaluator for objective functions based on cross-validation. + + This evaluator evaluates the objective function's statistical error, which comes from the + randomness of dataset. This evaluator assumes that the objective function is the average of + the cross-validation and uses the scaled variance of the cross-validation scores in the best + trial at the moment as the statistical error. + + """ + + def evaluate( + self, + trials: list[FrozenTrial], + study_direction: StudyDirection, + ) -> float: + """Evaluate the statistical error of the objective function based on cross-validation. + + Args: + trials: + A list of trials to consider. The best trial in ``trials`` is used to compute the + statistical error. + + study_direction: + The direction of the study. + + Returns: + A float representing the statistical error of the objective function. + + """ + trials = [trial for trial in trials if trial.state == TrialState.COMPLETE] + assert len(trials) > 0 + + if study_direction == StudyDirection.MAXIMIZE: + best_trial = max(trials, key=lambda t: cast(float, t.value)) + else: + best_trial = min(trials, key=lambda t: cast(float, t.value)) + + best_trial_attrs = best_trial.system_attrs + if _CROSS_VALIDATION_SCORES_KEY in best_trial_attrs: + cv_scores = best_trial_attrs[_CROSS_VALIDATION_SCORES_KEY] + else: + raise ValueError( + "Cross-validation scores have not been reported. Please call " + "`report_cross_validation_scores(trial, scores)` during a trial and pass the " + "list of scores as `scores`." + ) + + k = len(cv_scores) + assert k > 1, "Should be guaranteed by `report_cross_validation_scores`." + scale = 1 / k + 1 / (k - 1) + + var = scale * np.var(cv_scores) + std = np.sqrt(var) + + return float(std) + + +@experimental_class("3.2.0") +def report_cross_validation_scores(trial: Trial, scores: list[float]) -> None: + """A function to report cross-validation scores of a trial. + + This function should be called within the objective function to report the cross-validation + scores. The reported scores are used to evaluate the statistical error for termination + judgement. + + Args: + trial: + A :class:`~optuna.trial.Trial` object to report the cross-validation scores. + scores: + The cross-validation scores of the trial. + + """ + if len(scores) <= 1: + raise ValueError("The length of `scores` is expected to be greater than one.") + trial.storage.set_trial_system_attr(trial._trial_id, _CROSS_VALIDATION_SCORES_KEY, scores) + + +@experimental_class("3.2.0") +class StaticErrorEvaluator(BaseErrorEvaluator): + """An error evaluator that always returns a constant value. + + This evaluator can be used to terminate the optimization when the evaluated improvement + potential is below the fixed threshold. + + Args: + constant: + A user-specified constant value to always return as an error estimate. + + """ + + def __init__(self, constant: float) -> None: + self._constant = constant + + def evaluate( + self, + trials: list[FrozenTrial], + study_direction: StudyDirection, + ) -> float: + return self._constant diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91c99943ec97e469adea5970866aa721593136ae Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/emmr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/emmr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45ffaa8efc98fed18092a0154b5c5dd3d00ef477 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/emmr.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/evaluator.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/evaluator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce3ea284238e8563748ba3067df6ba1ad1af37a4 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/__pycache__/evaluator.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/emmr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/emmr.py new file mode 100644 index 0000000000000000000000000000000000000000..d92d5f6e58733c92a7e380b4e1348078e5047ef2 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/emmr.py @@ -0,0 +1,354 @@ +from __future__ import annotations + +import math +import sys +from typing import cast +from typing import TYPE_CHECKING +import warnings + +import numpy as np + +from optuna._experimental import experimental_class +from optuna.samplers._lazy_random_state import LazyRandomState +from optuna.search_space import intersection_search_space +from optuna.study import StudyDirection +from optuna.terminator.improvement.evaluator import _compute_standardized_regret_bound +from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator +from optuna.trial import FrozenTrial +from optuna.trial import TrialState + + +if TYPE_CHECKING: + import scipy.stats as scipy_stats + import torch + + from optuna._gp import acqf as acqf_module + from optuna._gp import gp + from optuna._gp import prior + from optuna._gp import search_space as gp_search_space +else: + from optuna._imports import _LazyImport + + torch = _LazyImport("torch") + gp = _LazyImport("optuna._gp.gp") + acqf_module = _LazyImport("optuna._gp.acqf") + prior = _LazyImport("optuna._gp.prior") + gp_search_space = _LazyImport("optuna._gp.search_space") + scipy_stats = _LazyImport("scipy.stats") + +MARGIN_FOR_NUMARICAL_STABILITY = 0.1 + + +@experimental_class("4.0.0") +class EMMREvaluator(BaseImprovementEvaluator): + """Evaluates a kind of regrets, called the Expected Minimum Model Regret(EMMR). + + EMMR is an upper bound of "expected minimum simple regret" in the optimization process. + + Expected minimum simple regret is a quantity that converges to zero only if the + optimization process has found the global optima. + + For further information about expected minimum simple regret and the algorithm, + please refer to the following paper: + + - `A stopping criterion for Bayesian optimization by the gap of expected minimum simple + regrets `__ + + Also, there is our blog post explaining this evaluator: + + - `Introducing A New Terminator: Early Termination of Black-box Optimization Based on + Expected Minimum Model Regret + `__ + + Args: + deterministic_objective: + A boolean value which indicates whether the objective function is deterministic. + Default is :obj:`False`. + delta: + A float number related to the criterion for termination. Default to 0.1. + For further information about this parameter, please see the aforementioned paper. + min_n_trials: + A minimum number of complete trials to compute the criterion. Default to 2. + seed: + A random seed for EMMREvaluator. + + Example: + + .. testcode:: + + import optuna + from optuna.terminator import EMMREvaluator + from optuna.terminator import MedianErrorEvaluator + from optuna.terminator import Terminator + + sampler = optuna.samplers.TPESampler(seed=0) + study = optuna.create_study(sampler=sampler, direction="minimize") + emmr_improvement_evaluator = EMMREvaluator() + median_error_evaluator = MedianErrorEvaluator(emmr_improvement_evaluator) + terminator = Terminator( + improvement_evaluator=emmr_improvement_evaluator, + error_evaluator=median_error_evaluator, + ) + + + for i in range(1000): + trial = study.ask() + + ys = [trial.suggest_float(f"x{i}", -10.0, 10.0) for i in range(5)] + value = sum(ys[i] ** 2 for i in range(5)) + + study.tell(trial, value) + + if terminator.should_terminate(study): + # Terminated by Optuna Terminator! + break + + """ + + def __init__( + self, + deterministic_objective: bool = False, + delta: float = 0.1, + min_n_trials: int = 2, + seed: int | None = None, + ) -> None: + if min_n_trials <= 1 or not np.isfinite(min_n_trials): + raise ValueError("`min_n_trials` is expected to be a finite integer more than one.") + + self._deterministic = deterministic_objective + self._delta = delta + self.min_n_trials = min_n_trials + self._rng = LazyRandomState(seed) + + def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float: + + optuna_search_space = intersection_search_space(trials) + complete_trials = [t for t in trials if t.state == TrialState.COMPLETE] + + if len(complete_trials) < self.min_n_trials: + return sys.float_info.max * MARGIN_FOR_NUMARICAL_STABILITY # Do not terminate. + + search_space = gp_search_space.SearchSpace(optuna_search_space) + normalized_params = search_space.get_normalized_params(complete_trials) + if not search_space.dim: + warnings.warn( + f"{self.__class__.__name__} cannot consider any search space." + "Termination will never occur in this study." + ) + return sys.float_info.max * MARGIN_FOR_NUMARICAL_STABILITY # Do not terminate. + + len_trials = len(complete_trials) + assert normalized_params.shape == (len_trials, search_space.dim) + + # _gp module assumes that optimization direction is maximization + sign = -1 if study_direction == StudyDirection.MINIMIZE else 1 + score_vals = np.array([cast(float, t.value) for t in complete_trials]) * sign + score_vals = gp.warn_and_convert_inf(score_vals) + standarized_score_vals = (score_vals - score_vals.mean()) / max( + sys.float_info.min, score_vals.std() + ) + + assert len(standarized_score_vals) == len(normalized_params) + + gpr_t1 = gp.fit_kernel_params( # Fit kernel with up to (t-1)-th observation + X=normalized_params[..., :-1, :], + Y=standarized_score_vals[:-1], + is_categorical=search_space.is_categorical, + log_prior=prior.default_log_prior, + minimum_noise=prior.DEFAULT_MINIMUM_NOISE_VAR, + gpr_cache=None, + deterministic_objective=self._deterministic, + ) + + gpr_t = gp.fit_kernel_params( # Fit kernel with up to t-th observation + X=normalized_params, + Y=standarized_score_vals, + is_categorical=search_space.is_categorical, + log_prior=prior.default_log_prior, + minimum_noise=prior.DEFAULT_MINIMUM_NOISE_VAR, + gpr_cache=gpr_t1, + deterministic_objective=self._deterministic, + ) + + theta_t_star_index = int(np.argmax(standarized_score_vals)) + theta_t1_star_index = int(np.argmax(standarized_score_vals[:-1])) + theta_t_star = normalized_params[theta_t_star_index, :] + theta_t1_star = normalized_params[theta_t1_star_index, :] + + cov_t_between_theta_t_star_and_theta_t1_star = _compute_gp_posterior_cov_two_thetas( + search_space, + normalized_params, + standarized_score_vals, + gpr_t, + theta_t_star_index, + theta_t1_star_index, + ) + + mu_t1_theta_t_with_nu_t, variance_t1_theta_t_with_nu_t = _compute_gp_posterior( + search_space, + normalized_params[:-1, :], + standarized_score_vals[:-1], + normalized_params[-1, :], + gpr_t, + # Use gpr_t instead of gpr_t1. + # Use "t" under the assumption that "t" and "t1" are approximately the same. + # This is because kernel should same when computing KLD. + # For detailed information, please see section 4.4 of the paper: + # https://proceedings.mlr.press/v206/ishibashi23a/ishibashi23a.pdf + ) + _, variance_t_theta_t1_star = _compute_gp_posterior( + search_space, + normalized_params, + standarized_score_vals, + theta_t1_star, + gpr_t, + ) + mu_t_theta_t_star, variance_t_theta_t_star = _compute_gp_posterior( + search_space, + normalized_params, + standarized_score_vals, + theta_t_star, + gpr_t, + ) + mu_t1_theta_t1_star, _ = _compute_gp_posterior( + search_space, + normalized_params[:-1, :], + standarized_score_vals[:-1], + theta_t1_star, + gpr_t1, + ) + + y_t = standarized_score_vals[-1] + kappa_t1 = _compute_standardized_regret_bound( + gpr_t1, + search_space, + normalized_params[:-1, :], + standarized_score_vals[:-1], + self._delta, + rng=self._rng.rng, + ) + + theorem1_delta_mu_t_star = mu_t1_theta_t1_star - mu_t_theta_t_star + + alg1_delta_r_tilde_t_term1 = theorem1_delta_mu_t_star + + theorem1_v = math.sqrt( + max( + 1e-10, + variance_t_theta_t_star + - 2.0 * cov_t_between_theta_t_star_and_theta_t1_star + + variance_t_theta_t1_star, + ) + ) + theorem1_g = (mu_t_theta_t_star - mu_t1_theta_t1_star) / theorem1_v + + alg1_delta_r_tilde_t_term2 = theorem1_v * scipy_stats.norm.pdf(theorem1_g) + alg1_delta_r_tilde_t_term3 = theorem1_v * theorem1_g * scipy_stats.norm.cdf(theorem1_g) + + _lambda = prior.DEFAULT_MINIMUM_NOISE_VAR**-1 + eq4_rhs_term1 = 0.5 * math.log(1.0 + _lambda * variance_t1_theta_t_with_nu_t) + eq4_rhs_term2 = ( + -0.5 * variance_t1_theta_t_with_nu_t / (variance_t1_theta_t_with_nu_t + _lambda**-1) + ) + eq4_rhs_term3 = ( + 0.5 + * variance_t1_theta_t_with_nu_t + * (y_t - mu_t1_theta_t_with_nu_t) ** 2 + / (variance_t1_theta_t_with_nu_t + _lambda**-1) ** 2 + ) + + alg1_delta_r_tilde_t_term4 = kappa_t1 * math.sqrt( + 0.5 * (eq4_rhs_term1 + eq4_rhs_term2 + eq4_rhs_term3) + ) + + return min( + sys.float_info.max * 0.5, + alg1_delta_r_tilde_t_term1 + + alg1_delta_r_tilde_t_term2 + + alg1_delta_r_tilde_t_term3 + + alg1_delta_r_tilde_t_term4, + ) + + +def _compute_gp_posterior( + search_space: gp_search_space.SearchSpace, + X: np.ndarray, + Y: np.ndarray, + x_params: np.ndarray, + gpr: gp.GPRegressor, +) -> tuple[float, float]: # mean, var + mean_tensor, var_tensor = gpr.posterior( + torch.from_numpy(x_params), # best_params or normalized_params[..., -1, :]), + ) + mean = mean_tensor.detach().numpy().flatten() + var = var_tensor.detach().numpy().flatten() + assert len(mean) == 1 and len(var) == 1 + return float(mean[0]), float(var[0]) + + +def _posterior_of_batched_theta( + gpr: gp.GPRegressor, + X: torch.Tensor, # [len(trials), len(params)] + cov_Y_Y_inv: torch.Tensor, # [len(trials), len(trials)] + cov_Y_Y_inv_Y: torch.Tensor, # [len(trials)] + theta: torch.Tensor, # [batch, len(params)] +) -> tuple[torch.Tensor, torch.Tensor]: # (mean: [(batch,)], var: [(batch,batch)]) + + assert len(X.shape) == 2 + len_trials, len_params = X.shape + assert len(theta.shape) == 2 + len_batch = theta.shape[0] + assert theta.shape == (len_batch, len_params) + assert cov_Y_Y_inv.shape == (len_trials, len_trials) + assert cov_Y_Y_inv_Y.shape == (len_trials,) + + cov_ftheta_fX = gpr.kernel(theta[..., None, :], X)[..., 0, :] + assert cov_ftheta_fX.shape == (len_batch, len_trials) + cov_ftheta_ftheta = gpr.kernel(theta[..., None, :], theta)[..., 0, :] + assert cov_ftheta_ftheta.shape == (len_batch, len_batch) + + assert torch.allclose(cov_ftheta_ftheta.diag(), gpr.kernel_scale) + assert torch.allclose(cov_ftheta_ftheta, cov_ftheta_ftheta.T) + + mean = cov_ftheta_fX @ cov_Y_Y_inv_Y + assert mean.shape == (len_batch,) + var = cov_ftheta_ftheta - cov_ftheta_fX @ cov_Y_Y_inv @ cov_ftheta_fX.T + assert var.shape == (len_batch, len_batch) + + # We need to clamp the variance to avoid negative values due to numerical errors. + return mean, torch.clamp(var, min=0.0) + + +def _compute_gp_posterior_cov_two_thetas( + search_space: gp_search_space.SearchSpace, + normalized_params: np.ndarray, + standarized_score_vals: np.ndarray, + gpr: gp.GPRegressor, + theta1_index: int, + theta2_index: int, +) -> float: # cov + + if theta1_index == theta2_index: + return _compute_gp_posterior( + search_space, + normalized_params, + standarized_score_vals, + normalized_params[theta1_index], + gpr, + )[1] + + assert normalized_params.shape[0] == standarized_score_vals.shape[0] + + cov_Y_Y_inv = gpr._cov_Y_Y_inv + cov_Y_Y_inv_Y = gpr._cov_Y_Y_inv_Y + assert cov_Y_Y_inv is not None and cov_Y_Y_inv_Y is not None + _, var = _posterior_of_batched_theta( + gpr, + gpr._X_train, + cov_Y_Y_inv, + cov_Y_Y_inv_Y, + torch.from_numpy(normalized_params[[theta1_index, theta2_index]]), + ) + assert var.shape == (2, 2) + var = var.detach().numpy()[0, 1] + return float(var) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/evaluator.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/evaluator.py new file mode 100644 index 0000000000000000000000000000000000000000..a29637be6ee810e56f6c3b6dd41cbe3cc82b57c9 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/improvement/evaluator.py @@ -0,0 +1,238 @@ +from __future__ import annotations + +import abc +from typing import TYPE_CHECKING + +import numpy as np + +from optuna._experimental import experimental_class +from optuna.distributions import BaseDistribution +from optuna.samplers._lazy_random_state import LazyRandomState +from optuna.search_space import intersection_search_space +from optuna.study import StudyDirection +from optuna.trial import FrozenTrial +from optuna.trial import TrialState + + +if TYPE_CHECKING: + + from optuna._gp import acqf as acqf_module + from optuna._gp import gp + from optuna._gp import optim_sample + from optuna._gp import prior + from optuna._gp import search_space as gp_search_space +else: + from optuna._imports import _LazyImport + + gp = _LazyImport("optuna._gp.gp") + optim_sample = _LazyImport("optuna._gp.optim_sample") + acqf_module = _LazyImport("optuna._gp.acqf") + prior = _LazyImport("optuna._gp.prior") + gp_search_space = _LazyImport("optuna._gp.search_space") + +DEFAULT_TOP_TRIALS_RATIO = 0.5 +DEFAULT_MIN_N_TRIALS = 20 + + +def _get_beta(n_params: int, n_trials: int, delta: float = 0.1) -> float: + # TODO(nabenabe0928): Check the original implementation to verify. + # Especially, |D| seems to be the domain size, but not the dimension based on Theorem 1. + beta = 2 * np.log(n_params * n_trials**2 * np.pi**2 / 6 / delta) + + # The following div is according to the original paper: "We then further scale it down + # by a factor of 5 as defined in the experiments in + # `Srinivas et al. (2010) `__" + beta /= 5 + + return beta + + +def _compute_standardized_regret_bound( + gpr: gp.GPRegressor, + search_space: gp_search_space.SearchSpace, + normalized_top_n_params: np.ndarray, + standarized_top_n_values: np.ndarray, + delta: float = 0.1, + optimize_n_samples: int = 2048, + rng: np.random.RandomState | None = None, +) -> float: + """ + # In the original paper, f(x) was intended to be minimized, but here we would like to + # maximize f(x). Hence, the following changes happen: + # 1. min(ucb) over top trials becomes max(lcb) over top trials, and + # 2. min(lcb) over the search space becomes max(ucb) over the search space, and + # 3. Regret bound becomes max(ucb) over the search space minus max(lcb) over top trials. + """ + + n_trials, n_params = normalized_top_n_params.shape + + # calculate max_ucb + beta = _get_beta(n_params, n_trials, delta) + ucb_acqf = acqf_module.UCB(gpr, search_space, beta) + # UCB over the search space. (Original: LCB over the search space. See Change 1 above.) + standardized_ucb_value = max( + ucb_acqf.eval_acqf_no_grad(normalized_top_n_params).max(), + optim_sample.optimize_acqf_sample(ucb_acqf, n_samples=optimize_n_samples, rng=rng)[1], + ) + + # calculate min_lcb + lcb_acqf = acqf_module.LCB(gpr=gpr, search_space=search_space, beta=beta) + # LCB over the top trials. (Original: UCB over the top trials. See Change 2 above.) + standardized_lcb_value = np.max(lcb_acqf.eval_acqf_no_grad(normalized_top_n_params)) + + # max(UCB) - max(LCB). (Original: min(UCB) - min(LCB). See Change 3 above.) + return standardized_ucb_value - standardized_lcb_value # standardized regret bound + + +@experimental_class("3.2.0") +class BaseImprovementEvaluator(metaclass=abc.ABCMeta): + """Base class for improvement evaluators.""" + + @abc.abstractmethod + def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float: + pass + + +@experimental_class("3.2.0") +class RegretBoundEvaluator(BaseImprovementEvaluator): + """An error evaluator for upper bound on the regret with high-probability confidence. + + This evaluator evaluates the regret of current best solution, which defined as the difference + between the objective value of the best solution and of the global optimum. To be specific, + this evaluator calculates the upper bound on the regret based on the fact that empirical + estimator of the objective function is bounded by lower and upper confidence bounds with + high probability under the Gaussian process model assumption. + + Args: + top_trials_ratio: + A ratio of top trials to be considered when estimating the regret. Default to 0.5. + min_n_trials: + A minimum number of complete trials to estimate the regret. Default to 20. + seed: + Seed for random number generator. + + For further information about this evaluator, please refer to the following paper: + + - `Automatic Termination for Hyperparameter Optimization `__ + """ # NOQA: E501 + + def __init__( + self, + top_trials_ratio: float = DEFAULT_TOP_TRIALS_RATIO, + min_n_trials: int = DEFAULT_MIN_N_TRIALS, + seed: int | None = None, + ) -> None: + self._top_trials_ratio = top_trials_ratio + self._min_n_trials = min_n_trials + self._log_prior = prior.default_log_prior + self._minimum_noise = prior.DEFAULT_MINIMUM_NOISE_VAR + self._optimize_n_samples = 2048 + self._rng = LazyRandomState(seed) + + def _get_top_n( + self, normalized_params: np.ndarray, values: np.ndarray + ) -> tuple[np.ndarray, np.ndarray]: + assert len(normalized_params) == len(values) + n_trials = len(normalized_params) + top_n = np.clip(int(n_trials * self._top_trials_ratio), self._min_n_trials, n_trials) + top_n_val = np.partition(values, n_trials - top_n)[n_trials - top_n] + top_n_mask = values >= top_n_val + return normalized_params[top_n_mask], values[top_n_mask] + + def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float: + optuna_search_space = intersection_search_space(trials) + self._validate_input(trials, optuna_search_space) + + complete_trials = [t for t in trials if t.state == TrialState.COMPLETE] + + # _gp module assumes that optimization direction is maximization + sign = -1 if study_direction == StudyDirection.MINIMIZE else 1 + values = np.array([t.value for t in complete_trials]) * sign + search_space = gp_search_space.SearchSpace(optuna_search_space) + normalized_params = search_space.get_normalized_params(complete_trials) + normalized_top_n_params, top_n_values = self._get_top_n(normalized_params, values) + top_n_values_mean = top_n_values.mean() + top_n_values_std = max(1e-10, top_n_values.std()) + standarized_top_n_values = (top_n_values - top_n_values_mean) / top_n_values_std + + gpr = gp.fit_kernel_params( + X=normalized_top_n_params, + Y=standarized_top_n_values, + is_categorical=search_space.is_categorical, + log_prior=self._log_prior, + minimum_noise=self._minimum_noise, + # TODO(contramundum53): Add option to specify this. + deterministic_objective=False, + # TODO(y0z): Add `kernel_params_cache` to speedup. + gpr_cache=None, + ) + + standardized_regret_bound = _compute_standardized_regret_bound( + gpr, + search_space, + normalized_top_n_params, + standarized_top_n_values, + rng=self._rng.rng, + ) + return standardized_regret_bound * top_n_values_std # regret bound + + @classmethod + def _validate_input( + cls, trials: list[FrozenTrial], search_space: dict[str, BaseDistribution] + ) -> None: + if len([t for t in trials if t.state == TrialState.COMPLETE]) == 0: + raise ValueError( + "Because no trial has been completed yet, the regret bound cannot be evaluated." + ) + + if len(search_space) == 0: + raise ValueError( + "The intersection search space is empty. This condition is not supported by " + f"{cls.__name__}." + ) + + +@experimental_class("3.4.0") +class BestValueStagnationEvaluator(BaseImprovementEvaluator): + """Evaluates the stagnation period of the best value in an optimization process. + + This class is initialized with a maximum stagnation period (``max_stagnation_trials``) + and is designed to evaluate the remaining trials before reaching this maximum period + of allowed stagnation. If this remaining trials reach zero, the trial terminates. + Therefore, the default error evaluator is instantiated by ``StaticErrorEvaluator(const=0)``. + + Args: + max_stagnation_trials: + The maximum number of trials allowed for stagnation. + """ + + def __init__(self, max_stagnation_trials: int = 30) -> None: + if max_stagnation_trials < 0: + raise ValueError("The maximum number of stagnant trials must not be negative.") + self._max_stagnation_trials = max_stagnation_trials + + def evaluate(self, trials: list[FrozenTrial], study_direction: StudyDirection) -> float: + self._validate_input(trials) + is_maximize_direction = True if (study_direction == StudyDirection.MAXIMIZE) else False + trials = [t for t in trials if t.state == TrialState.COMPLETE] + current_step = len(trials) - 1 + + best_step = 0 + for i, trial in enumerate(trials): + best_value = trials[best_step].value + current_value = trial.value + assert best_value is not None + assert current_value is not None + if is_maximize_direction and (best_value < current_value): + best_step = i + elif (not is_maximize_direction) and (best_value > current_value): + best_step = i + + return self._max_stagnation_trials - (current_step - best_step) + + @classmethod + def _validate_input(cls, trials: list[FrozenTrial]) -> None: + if len([t for t in trials if t.state == TrialState.COMPLETE]) == 0: + raise ValueError( + "Because no trial has been completed yet, the improvement cannot be evaluated." + ) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/median_erroreval.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/median_erroreval.py new file mode 100644 index 0000000000000000000000000000000000000000..d956945fe0129f047e38d5c9441ab393558b0434 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/median_erroreval.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import sys + +import numpy as np + +from optuna._experimental import experimental_class +from optuna.study import StudyDirection +from optuna.terminator.erroreval import BaseErrorEvaluator +from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator +from optuna.trial import FrozenTrial +from optuna.trial._state import TrialState + + +@experimental_class("4.0.0") +class MedianErrorEvaluator(BaseErrorEvaluator): + """An error evaluator that returns the ratio to initial median. + + This error evaluator is introduced as a heuristics in the following paper: + + - `A stopping criterion for Bayesian optimization by the gap of expected minimum simple + regrets `__ + + Args: + paired_improvement_evaluator: + The ``improvement_evaluator`` instance which is set with this ``error_evaluator``. + warm_up_trials: + A parameter specifies the number of initial trials to be discarded before + the calculation of median. Default to 10. + In optuna, the first 10 trials are often random sampling. + The ``warm_up_trials`` can exclude them from the calculation. + n_initial_trials: + A parameter specifies the number of initial trials considered in the calculation of + median after ``warm_up_trials``. Default to 20. + threshold_ratio: + A parameter specifies the ratio between the threshold and initial median. + Default to 0.01. + """ + + def __init__( + self, + paired_improvement_evaluator: BaseImprovementEvaluator, + warm_up_trials: int = 10, + n_initial_trials: int = 20, + threshold_ratio: float = 0.01, + ) -> None: + if warm_up_trials < 0: + raise ValueError("`warm_up_trials` is expected to be a non-negative integer.") + if n_initial_trials <= 0: + raise ValueError("`n_initial_trials` is expected to be a positive integer.") + if threshold_ratio <= 0.0 or not np.isfinite(threshold_ratio): + raise ValueError("`threshold_ratio_to_initial_median` is expected to be a positive.") + + self._paired_improvement_evaluator = paired_improvement_evaluator + self._warm_up_trials = warm_up_trials + self._n_initial_trials = n_initial_trials + self._threshold_ratio = threshold_ratio + self._threshold: float | None = None + + def evaluate( + self, + trials: list[FrozenTrial], + study_direction: StudyDirection, + ) -> float: + + if self._threshold is not None: + return self._threshold + + trials = [trial for trial in trials if trial.state == TrialState.COMPLETE] + if len(trials) < (self._warm_up_trials + self._n_initial_trials): + return ( + -sys.float_info.min + ) # Do not terminate. It assumes that improvement must non-negative. + trials.sort(key=lambda trial: trial.number) + criteria = [] + for i in range(1, self._n_initial_trials + 1): + criteria.append( + self._paired_improvement_evaluator.evaluate( + trials[self._warm_up_trials : self._warm_up_trials + i], study_direction + ) + ) + criteria.sort() + self._threshold = criteria[len(criteria) // 2] + assert self._threshold is not None + self._threshold = min(sys.float_info.max, self._threshold * self._threshold_ratio) + return self._threshold diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/terminator.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/terminator.py new file mode 100644 index 0000000000000000000000000000000000000000..ac145910e31768df9d59198ca0b74e1ca9d23b1b --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/terminator/terminator.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import abc + +from optuna._experimental import experimental_class +from optuna.study.study import Study +from optuna.terminator.erroreval import BaseErrorEvaluator +from optuna.terminator.erroreval import CrossValidationErrorEvaluator +from optuna.terminator.erroreval import StaticErrorEvaluator +from optuna.terminator.improvement.evaluator import BaseImprovementEvaluator +from optuna.terminator.improvement.evaluator import BestValueStagnationEvaluator +from optuna.terminator.improvement.evaluator import DEFAULT_MIN_N_TRIALS +from optuna.terminator.improvement.evaluator import RegretBoundEvaluator +from optuna.trial import TrialState + + +class BaseTerminator(metaclass=abc.ABCMeta): + """Base class for terminators.""" + + @abc.abstractmethod + def should_terminate(self, study: Study) -> bool: + pass + + +@experimental_class("3.2.0") +class Terminator(BaseTerminator): + """Automatic stopping mechanism for Optuna studies. + + This class implements an automatic stopping mechanism for Optuna studies, aiming to prevent + unnecessary computation. The study is terminated when the statistical error, e.g. + cross-validation error, exceeds the room left for optimization. + + For further information about the algorithm, please refer to the following paper: + + - `A. Makarova et al. Automatic termination for hyperparameter optimization. + `__ + + Args: + improvement_evaluator: + An evaluator object for assessing the room left for optimization. Defaults to a + :class:`~optuna.terminator.improvement.evaluator.RegretBoundEvaluator` object. + error_evaluator: + An evaluator for calculating the statistical error, e.g. cross-validation error. + Defaults to a :class:`~optuna.terminator.CrossValidationErrorEvaluator` + object. + min_n_trials: + The minimum number of trials before termination is considered. Defaults to ``20``. + + Raises: + ValueError: If ``min_n_trials`` is not a positive integer. + + Example: + + .. testcode:: + + import logging + import sys + + from sklearn.datasets import load_wine + from sklearn.ensemble import RandomForestClassifier + from sklearn.model_selection import cross_val_score + from sklearn.model_selection import KFold + + import optuna + from optuna.terminator import Terminator + from optuna.terminator import report_cross_validation_scores + + + study = optuna.create_study(direction="maximize") + terminator = Terminator() + min_n_trials = 20 + + while True: + trial = study.ask() + + X, y = load_wine(return_X_y=True) + + clf = RandomForestClassifier( + max_depth=trial.suggest_int("max_depth", 2, 32), + min_samples_split=trial.suggest_float("min_samples_split", 0, 1), + criterion=trial.suggest_categorical("criterion", ("gini", "entropy")), + ) + + scores = cross_val_score(clf, X, y, cv=KFold(n_splits=5, shuffle=True)) + report_cross_validation_scores(trial, scores) + + value = scores.mean() + logging.info(f"Trial #{trial.number} finished with value {value}.") + study.tell(trial, value) + + if trial.number > min_n_trials and terminator.should_terminate(study): + logging.info("Terminated by Optuna Terminator!") + break + + .. seealso:: + Please refer to :class:`~optuna.terminator.TerminatorCallback` for how to use + the terminator mechanism with the :func:`~optuna.study.Study.optimize` method. + + """ + + def __init__( + self, + improvement_evaluator: BaseImprovementEvaluator | None = None, + error_evaluator: BaseErrorEvaluator | None = None, + min_n_trials: int = DEFAULT_MIN_N_TRIALS, + ) -> None: + if min_n_trials <= 0: + raise ValueError("`min_n_trials` is expected to be a positive integer.") + + self._improvement_evaluator = improvement_evaluator or RegretBoundEvaluator() + self._error_evaluator = error_evaluator or self._initialize_error_evaluator() + self._min_n_trials = min_n_trials + + def _initialize_error_evaluator(self) -> BaseErrorEvaluator: + if isinstance(self._improvement_evaluator, BestValueStagnationEvaluator): + return StaticErrorEvaluator(constant=0) + return CrossValidationErrorEvaluator() + + def should_terminate(self, study: Study) -> bool: + """Judge whether the study should be terminated based on the reported values.""" + trials = study.get_trials(states=[TrialState.COMPLETE]) + + if len(trials) < self._min_n_trials: + return False + + improvement = self._improvement_evaluator.evaluate( + trials=study.trials, + study_direction=study.direction, + ) + + error = self._error_evaluator.evaluate( + trials=study.trials, study_direction=study.direction + ) + + should_terminate = improvement < error + return should_terminate diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/objectives.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/objectives.py new file mode 100644 index 0000000000000000000000000000000000000000..c98c1cf2bcfa0d74054c9be064e2ffbf4f393623 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/objectives.py @@ -0,0 +1,10 @@ +from optuna import TrialPruned +from optuna.trial import Trial + + +def fail_objective(_: Trial) -> float: + raise ValueError() + + +def pruned_objective(trial: Trial) -> float: + raise TrialPruned() diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/pruners.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/pruners.py new file mode 100644 index 0000000000000000000000000000000000000000..ad78ab8d03083e9ea2a807bd8cbf88e5fea8ff17 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/pruners.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +import optuna + + +class DeterministicPruner(optuna.pruners.BasePruner): + def __init__(self, is_pruning: bool) -> None: + self.is_pruning = is_pruning + + def prune(self, study: "optuna.study.Study", trial: "optuna.trial.FrozenTrial") -> bool: + return self.is_pruning diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/samplers.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f87875174350a188dcdfdb3132fdf6ff1e7d34 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/samplers.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import Any + +import optuna +from optuna.distributions import BaseDistribution + + +class DeterministicSampler(optuna.samplers.BaseSampler): + def __init__(self, params: dict[str, Any]) -> None: + self.params = params + + def infer_relative_search_space( + self, study: "optuna.study.Study", trial: "optuna.trial.FrozenTrial" + ) -> dict[str, BaseDistribution]: + return {} + + def sample_relative( + self, + study: "optuna.study.Study", + trial: "optuna.trial.FrozenTrial", + search_space: dict[str, BaseDistribution], + ) -> dict[str, Any]: + return {} + + def sample_independent( + self, + study: "optuna.study.Study", + trial: "optuna.trial.FrozenTrial", + param_name: str, + param_distribution: BaseDistribution, + ) -> Any: + param_value = self.params[param_name] + assert param_distribution._contains(param_distribution.to_internal_repr(param_value)) + return param_value diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/storages.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/storages.py new file mode 100644 index 0000000000000000000000000000000000000000..e2395450d4ac6db8f65740baf063e6623eae3bbf --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/storages.py @@ -0,0 +1,189 @@ +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from contextlib import AbstractContextManager +from contextlib import contextmanager +import os +import socket +import sys +import threading +from types import TracebackType +from typing import Any +from typing import Generator +from typing import IO +from typing import TYPE_CHECKING + +import fakeredis + +import optuna +from optuna.storages import BaseStorage +from optuna.storages import GrpcStorageProxy +from optuna.storages.journal import JournalFileBackend +from optuna.testing.tempfile_pool import NamedTemporaryFilePool + + +if TYPE_CHECKING: + import grpc +else: + from optuna._imports import _LazyImport + + grpc = _LazyImport("grpc") + + +STORAGE_MODES: list[Any] = [ + "inmemory", + "sqlite", + "cached_sqlite", + "journal", + "journal_redis", + "grpc_rdb", + "grpc_journal_file", +] + + +STORAGE_MODES_HEARTBEAT = [ + "sqlite", + "cached_sqlite", +] + +SQLITE3_TIMEOUT = 300 + + +@contextmanager +def _lock_to_search_for_free_port() -> Generator[None, None, None]: + if sys.platform == "win32": + lock_path = os.path.join( + os.environ.get("PROGRAMDATA", "C:\\ProgramData"), + "optuna", + "optuna_find_free_port.lock", + ) + else: + lock_path = "/tmp/optuna_find_free_port.lock" + + os.makedirs(os.path.dirname(lock_path), exist_ok=True) + lockfile = open(lock_path, "w") + if sys.platform == "win32": + import msvcrt + + msvcrt.locking(lockfile.fileno(), msvcrt.LK_LOCK, 1) + yield + msvcrt.locking(lockfile.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + + fcntl.flock(lockfile, fcntl.LOCK_EX) + yield + fcntl.flock(lockfile, fcntl.LOCK_UN) + + lockfile.close() + + +class StorageSupplier(AbstractContextManager): + def __init__(self, storage_specifier: str, **kwargs: Any) -> None: + self.storage_specifier = storage_specifier + self.extra_args = kwargs + self.tempfile: IO[Any] | None = None + self.server: grpc.Server | None = None + self.thread: threading.Thread | None = None + self.proxy: GrpcStorageProxy | None = None + + def __enter__( + self, + ) -> ( + optuna.storages.InMemoryStorage + | optuna.storages._CachedStorage + | optuna.storages.RDBStorage + | optuna.storages.JournalStorage + | optuna.storages.GrpcStorageProxy + ): + if self.storage_specifier == "inmemory": + if len(self.extra_args) > 0: + raise ValueError("InMemoryStorage does not accept any arguments!") + return optuna.storages.InMemoryStorage() + elif "sqlite" in self.storage_specifier: + self.tempfile = NamedTemporaryFilePool().tempfile() + url = "sqlite:///{}".format(self.tempfile.name) + rdb_storage = optuna.storages.RDBStorage( + url, + engine_kwargs={"connect_args": {"timeout": SQLITE3_TIMEOUT}}, + **self.extra_args, + ) + return ( + optuna.storages._CachedStorage(rdb_storage) + if "cached" in self.storage_specifier + else rdb_storage + ) + elif self.storage_specifier == "journal_redis": + journal_redis_storage = optuna.storages.journal.JournalRedisBackend( + "redis://localhost" + ) + journal_redis_storage._redis = self.extra_args.get( + "redis", fakeredis.FakeStrictRedis() + ) + return optuna.storages.JournalStorage(journal_redis_storage) + elif self.storage_specifier == "grpc_journal_file": + self.tempfile = self.extra_args.get("file", NamedTemporaryFilePool().tempfile()) + assert self.tempfile is not None + storage = optuna.storages.JournalStorage( + optuna.storages.journal.JournalFileBackend(self.tempfile.name) + ) + return self._create_proxy(storage, thread_pool=self.extra_args.get("thread_pool")) + elif "journal" in self.storage_specifier: + self.tempfile = self.extra_args.get("file", NamedTemporaryFilePool().tempfile()) + assert self.tempfile is not None + file_storage = JournalFileBackend(self.tempfile.name) + return optuna.storages.JournalStorage(file_storage) + elif self.storage_specifier == "grpc_rdb": + self.tempfile = NamedTemporaryFilePool().tempfile() + url = "sqlite:///{}".format(self.tempfile.name) + return self._create_proxy(optuna.storages.RDBStorage(url)) + elif self.storage_specifier == "grpc_proxy": + assert "base_storage" in self.extra_args + return self._create_proxy(self.extra_args["base_storage"]) + else: + assert False + + def _create_proxy( + self, storage: BaseStorage, thread_pool: ThreadPoolExecutor | None = None + ) -> GrpcStorageProxy: + with _lock_to_search_for_free_port(): + port = _find_free_port() + self.server = optuna.storages._grpc.server.make_server( + storage, "localhost", port, thread_pool=thread_pool + ) + self.thread = threading.Thread(target=self.server.start) + self.thread.start() + self.proxy = GrpcStorageProxy(host="localhost", port=port) + self.proxy.wait_server_ready(timeout=60) + return self.proxy + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.tempfile: + self.tempfile.close() + + if self.proxy: + self.proxy.close() + self.proxy = None + + if self.server: + assert self.thread is not None + self.server.stop(5).wait() + self.thread.join() + self.server = None + self.thread = None + + +def _find_free_port() -> int: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + for port in range(13000, 13100): + try: + sock.bind(("localhost", port)) + return port + except OSError: + continue + assert False, "must not reach here" diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/tempfile_pool.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/tempfile_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..eec71279b2db9f7ae3230d254b99ef6c74409d97 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/tempfile_pool.py @@ -0,0 +1,46 @@ +# On Windows, temporary file shold delete "after" storage was deleted +# NamedTemporaryFilePool ensures tempfile delete after tests. + +from __future__ import annotations + +import atexit +import gc +import os +import tempfile +from types import TracebackType +from typing import Any +from typing import IO + + +class NamedTemporaryFilePool: + tempfile_pool: list[IO[Any]] = [] + + def __new__(cls, **kwargs: Any) -> "NamedTemporaryFilePool": + if not hasattr(cls, "_instance"): + cls._instance = super(NamedTemporaryFilePool, cls).__new__(cls) + atexit.register(cls._instance.cleanup) + return cls._instance + + def __init__(self, **kwargs: Any) -> None: + self.kwargs = kwargs + + def tempfile(self) -> IO[Any]: + self._tempfile = tempfile.NamedTemporaryFile(delete=False, **self.kwargs) + self.tempfile_pool.append(self._tempfile) + return self._tempfile + + def cleanup(self) -> None: + gc.collect() + for i in self.tempfile_pool: + os.unlink(i.name) + + def __enter__(self) -> IO[Any]: + return self.tempfile() + + def __exit__( + self, + exc_type: type[BaseException], + exc_val: BaseException, + exc_tb: TracebackType, + ) -> None: + self._tempfile.close() diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/threading.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/threading.py new file mode 100644 index 0000000000000000000000000000000000000000..1facbe97daeb54fa63b51615ce6794125cbddf74 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/threading.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from collections.abc import Callable +import threading +from typing import Any + + +class _TestableThread(threading.Thread): + def __init__(self, target: Callable[..., Any], args: tuple): + threading.Thread.__init__(self, target=target, args=args) + self.exc: BaseException | None = None + + def run(self) -> None: + try: + threading.Thread.run(self) + except BaseException as e: + self.exc = e + + def join(self, timeout: float | None = None) -> None: + super(_TestableThread, self).join(timeout) + if self.exc: + raise self.exc diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/trials.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/trials.py new file mode 100644 index 0000000000000000000000000000000000000000..6f060192630e138e23d8cc01781f7d1d4aba8e03 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/trials.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +import optuna +from optuna.distributions import BaseDistribution +from optuna.samplers._base import _CONSTRAINTS_KEY +from optuna.trial import FrozenTrial +from optuna.trial import TrialState + + +def _create_frozen_trial( + number: int = 0, + values: Sequence[float] | None = None, + constraints: Sequence[float] | None = None, + params: dict[str, Any] | None = None, + param_distributions: dict[str, BaseDistribution] | None = None, + state: TrialState = TrialState.COMPLETE, +) -> optuna.trial.FrozenTrial: + return FrozenTrial( + number=number, + value=1.0 if values is None else None, + values=values, + state=state, + user_attrs={}, + system_attrs={} if constraints is None else {_CONSTRAINTS_KEY: list(constraints)}, + params=params or {}, + distributions=param_distributions or {}, + intermediate_values={}, + datetime_start=None, + datetime_complete=None, + trial_id=number, + ) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/visualization.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..d462a31adce568495810115efb8e346515f20d7c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/testing/visualization.py @@ -0,0 +1,67 @@ +from optuna import Study +from optuna.distributions import FloatDistribution +from optuna.study import create_study +from optuna.trial import create_trial + + +def prepare_study_with_trials( + n_objectives: int = 1, + direction: str = "minimize", + value_for_first_trial: float = 0.0, +) -> Study: + """Return a dummy study object for tests. + + This function is added to reduce the code to set up dummy study object in each test case. + However, you can only use this function for unit tests that are loosely coupled with the + dummy study object. Unit tests that are tightly coupled with the study become difficult to + read because of + `Mystery Guest `__ and/or + `Eager Test `__ anti-patterns. + + Args: + n_objectives: Number of objective values. + direction: Study's optimization direction. + value_for_first_trial: Objective value in first trial. This value will be broadcasted + to all objectives in multi-objective optimization. + + Returns: + :class:`~optuna.study.Study` + + """ + + study = create_study(directions=[direction] * n_objectives) + study.add_trial( + create_trial( + values=[value_for_first_trial] * n_objectives, + params={"param_a": 1.0, "param_b": 2.0, "param_c": 3.0, "param_d": 4.0}, + distributions={ + "param_a": FloatDistribution(0.0, 3.0), + "param_b": FloatDistribution(0.0, 3.0), + "param_c": FloatDistribution(2.0, 5.0), + "param_d": FloatDistribution(2.0, 5.0), + }, + ) + ) + study.add_trial( + create_trial( + values=[2.0] * n_objectives, + params={"param_b": 0.0, "param_d": 4.0}, + distributions={ + "param_b": FloatDistribution(0.0, 3.0), + "param_d": FloatDistribution(2.0, 5.0), + }, + ) + ) + study.add_trial( + create_trial( + values=[1.0] * n_objectives, + params={"param_a": 2.5, "param_b": 1.0, "param_c": 4.5, "param_d": 2.0}, + distributions={ + "param_a": FloatDistribution(0.0, 3.0), + "param_b": FloatDistribution(0.0, 3.0), + "param_c": FloatDistribution(2.0, 5.0), + "param_d": FloatDistribution(2.0, 5.0), + }, + ) + ) + return study diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ae8278c922130b7a5df0ab1721d315e8a2634407 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__init__.py @@ -0,0 +1,16 @@ +from optuna.trial._base import BaseTrial +from optuna.trial._fixed import FixedTrial +from optuna.trial._frozen import create_trial +from optuna.trial._frozen import FrozenTrial +from optuna.trial._state import TrialState +from optuna.trial._trial import Trial + + +__all__ = [ + "BaseTrial", + "FixedTrial", + "FrozenTrial", + "Trial", + "TrialState", + "create_trial", +] diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27c0b6d31b0a58c1f6607262032de8e476a6b62c Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_fixed.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_fixed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c5d14f93c739bd5fbccf973075f283b8151c257 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_fixed.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_frozen.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_frozen.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..796598621e84eeba399e8fc5c5edd73253e79385 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_frozen.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_state.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d52b9c4e3f570084fdec9ff361c07febfa0fbce Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_state.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_trial.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_trial.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b6454d18d812684794fdf9f8edcf8900170bdfc Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/__pycache__/_trial.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_base.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..0f08ae3e2408f452addb61df95fb0c3ec7ba027c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_base.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import abc +from collections.abc import Sequence +import datetime +from typing import Any +from typing import overload + +from optuna._deprecated import deprecated_func +from optuna.distributions import BaseDistribution +from optuna.distributions import CategoricalChoiceType + + +_SUGGEST_INT_POSITIONAL_ARGS = ["self", "name", "low", "high", "step", "log"] + + +class BaseTrial(abc.ABC): + """Base class for trials. + + Note that this class is not supposed to be directly accessed by library users. + """ + + @abc.abstractmethod + def suggest_float( + self, + name: str, + low: float, + high: float, + *, + step: float | None = None, + log: bool = False, + ) -> float: + raise NotImplementedError + + @deprecated_func("3.0.0", "6.0.0") + @abc.abstractmethod + def suggest_uniform(self, name: str, low: float, high: float) -> float: + raise NotImplementedError + + @deprecated_func("3.0.0", "6.0.0") + @abc.abstractmethod + def suggest_loguniform(self, name: str, low: float, high: float) -> float: + raise NotImplementedError + + @deprecated_func("3.0.0", "6.0.0") + @abc.abstractmethod + def suggest_discrete_uniform(self, name: str, low: float, high: float, q: float) -> float: + raise NotImplementedError + + @abc.abstractmethod + def suggest_int( + self, name: str, low: int, high: int, *, step: int = 1, log: bool = False + ) -> int: + raise NotImplementedError + + @overload + @abc.abstractmethod + def suggest_categorical(self, name: str, choices: Sequence[None]) -> None: ... + + @overload + @abc.abstractmethod + def suggest_categorical(self, name: str, choices: Sequence[bool]) -> bool: ... + + @overload + @abc.abstractmethod + def suggest_categorical(self, name: str, choices: Sequence[int]) -> int: ... + + @overload + @abc.abstractmethod + def suggest_categorical(self, name: str, choices: Sequence[float]) -> float: ... + + @overload + @abc.abstractmethod + def suggest_categorical(self, name: str, choices: Sequence[str]) -> str: ... + + @overload + @abc.abstractmethod + def suggest_categorical( + self, name: str, choices: Sequence[CategoricalChoiceType] + ) -> CategoricalChoiceType: ... + + @abc.abstractmethod + def suggest_categorical( + self, name: str, choices: Sequence[CategoricalChoiceType] + ) -> CategoricalChoiceType: + raise NotImplementedError + + @abc.abstractmethod + def report(self, value: float, step: int) -> None: + raise NotImplementedError + + @abc.abstractmethod + def should_prune(self) -> bool: + raise NotImplementedError + + @abc.abstractmethod + def set_user_attr(self, key: str, value: Any) -> None: + raise NotImplementedError + + @abc.abstractmethod + @deprecated_func("3.1.0", "5.0.0") + def set_system_attr(self, key: str, value: Any) -> None: + raise NotImplementedError + + @property + @abc.abstractmethod + def params(self) -> dict[str, Any]: + raise NotImplementedError + + @property + @abc.abstractmethod + def distributions(self) -> dict[str, BaseDistribution]: + raise NotImplementedError + + @property + @abc.abstractmethod + def user_attrs(self) -> dict[str, Any]: + raise NotImplementedError + + @property + @abc.abstractmethod + def system_attrs(self) -> dict[str, Any]: + raise NotImplementedError + + @property + @abc.abstractmethod + def datetime_start(self) -> datetime.datetime | None: + raise NotImplementedError + + @property + def number(self) -> int: + raise NotImplementedError diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_fixed.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_fixed.py new file mode 100644 index 0000000000000000000000000000000000000000..295254c272b5428879909d0d455b07b24649d4f4 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_fixed.py @@ -0,0 +1,187 @@ +from __future__ import annotations + +from collections.abc import Sequence +import datetime +from typing import Any +from typing import overload +import warnings + +from optuna import distributions +from optuna._convert_positional_args import convert_positional_args +from optuna._deprecated import deprecated_func +from optuna.distributions import BaseDistribution +from optuna.distributions import CategoricalChoiceType +from optuna.distributions import CategoricalDistribution +from optuna.distributions import FloatDistribution +from optuna.distributions import IntDistribution +from optuna.trial._base import _SUGGEST_INT_POSITIONAL_ARGS +from optuna.trial._base import BaseTrial + + +_suggest_deprecated_msg = "Use suggest_float{args} instead." + + +class FixedTrial(BaseTrial): + """A trial class which suggests a fixed value for each parameter. + + This object has the same methods as :class:`~optuna.trial.Trial`, and it suggests pre-defined + parameter values. The parameter values can be determined at the construction of the + :class:`~optuna.trial.FixedTrial` object. In contrast to :class:`~optuna.trial.Trial`, + :class:`~optuna.trial.FixedTrial` does not depend on :class:`~optuna.study.Study`, and it is + useful for deploying optimization results. + + Example: + + Evaluate an objective function with parameter values given by a user. + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", -100, 100) + y = trial.suggest_categorical("y", [-1, 0, 1]) + return x**2 + y + + + assert objective(optuna.trial.FixedTrial({"x": 1, "y": 0})) == 1 + + + .. note:: + Please refer to :class:`~optuna.trial.Trial` for details of methods and properties. + + Args: + params: + A dictionary containing all parameters. + number: + A trial number. Defaults to ``0``. + + """ + + def __init__(self, params: dict[str, Any], number: int = 0) -> None: + self._params = params + self._suggested_params: dict[str, Any] = {} + self._distributions: dict[str, BaseDistribution] = {} + self._user_attrs: dict[str, Any] = {} + self._system_attrs: dict[str, Any] = {} + self._datetime_start = datetime.datetime.now() + self._number = number + + def suggest_float( + self, + name: str, + low: float, + high: float, + *, + step: float | None = None, + log: bool = False, + ) -> float: + return self._suggest(name, FloatDistribution(low, high, log=log, step=step)) + + @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="")) + def suggest_uniform(self, name: str, low: float, high: float) -> float: + return self.suggest_float(name, low, high) + + @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="(..., log=True)")) + def suggest_loguniform(self, name: str, low: float, high: float) -> float: + return self.suggest_float(name, low, high, log=True) + + @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="(..., step=...)")) + def suggest_discrete_uniform(self, name: str, low: float, high: float, q: float) -> float: + return self.suggest_float(name, low, high, step=q) + + @convert_positional_args( + previous_positional_arg_names=_SUGGEST_INT_POSITIONAL_ARGS, + deprecated_version="3.5.0", + removed_version="5.0.0", + ) + def suggest_int( + self, name: str, low: int, high: int, *, step: int = 1, log: bool = False + ) -> int: + return int(self._suggest(name, IntDistribution(low, high, log=log, step=step))) + + @overload + def suggest_categorical(self, name: str, choices: Sequence[None]) -> None: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[bool]) -> bool: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[int]) -> int: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[float]) -> float: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[str]) -> str: ... + + @overload + def suggest_categorical( + self, name: str, choices: Sequence[CategoricalChoiceType] + ) -> CategoricalChoiceType: ... + + def suggest_categorical( + self, name: str, choices: Sequence[CategoricalChoiceType] + ) -> CategoricalChoiceType: + return self._suggest(name, CategoricalDistribution(choices=choices)) + + def report(self, value: float, step: int) -> None: + pass + + def should_prune(self) -> bool: + return False + + def set_user_attr(self, key: str, value: Any) -> None: + self._user_attrs[key] = value + + @deprecated_func("3.1.0", "5.0.0") + def set_system_attr(self, key: str, value: Any) -> None: + self._system_attrs[key] = value + + def _suggest(self, name: str, distribution: BaseDistribution) -> Any: + if name not in self._params: + raise ValueError( + "The value of the parameter '{}' is not found. Please set it at " + "the construction of the FixedTrial object.".format(name) + ) + + value = self._params[name] + param_value_in_internal_repr = distribution.to_internal_repr(value) + if not distribution._contains(param_value_in_internal_repr): + warnings.warn( + "The value {} of the parameter '{}' is out of " + "the range of the distribution {}.".format(value, name, distribution) + ) + + if name in self._distributions: + distributions.check_distribution_compatibility(self._distributions[name], distribution) + + self._suggested_params[name] = value + self._distributions[name] = distribution + + return value + + @property + def params(self) -> dict[str, Any]: + return self._suggested_params + + @property + def distributions(self) -> dict[str, BaseDistribution]: + return self._distributions + + @property + def user_attrs(self) -> dict[str, Any]: + return self._user_attrs + + @property + def system_attrs(self) -> dict[str, Any]: + return self._system_attrs + + @property + def datetime_start(self) -> datetime.datetime | None: + return self._datetime_start + + @property + def number(self) -> int: + return self._number diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_frozen.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_frozen.py new file mode 100644 index 0000000000000000000000000000000000000000..8df49f2e96d1c4d3431e454864026e64a4a5d15d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_frozen.py @@ -0,0 +1,597 @@ +from __future__ import annotations + +from collections.abc import Mapping +from collections.abc import Sequence +import datetime +import math +from typing import Any +from typing import cast +from typing import Dict +from typing import overload +import warnings + +from optuna import distributions +from optuna import logging +from optuna._convert_positional_args import convert_positional_args +from optuna._deprecated import deprecated_func +from optuna._typing import JSONSerializable +from optuna.distributions import _convert_old_distribution_to_new_distribution +from optuna.distributions import BaseDistribution +from optuna.distributions import CategoricalChoiceType +from optuna.distributions import CategoricalDistribution +from optuna.distributions import FloatDistribution +from optuna.distributions import IntDistribution +from optuna.trial._base import _SUGGEST_INT_POSITIONAL_ARGS +from optuna.trial._base import BaseTrial +from optuna.trial._state import TrialState + + +_logger = logging.get_logger(__name__) +_suggest_deprecated_msg = "Use suggest_float{args} instead." + + +class FrozenTrial(BaseTrial): + """Status and results of a :class:`~optuna.trial.Trial`. + + An object of this class has the same methods as :class:`~optuna.trial.Trial`, but is not + associated with, nor has any references to a :class:`~optuna.study.Study`. + + It is therefore not possible to make persistent changes to a storage from this object by + itself, for instance by using :func:`~optuna.trial.FrozenTrial.set_user_attr`. + + It will suggest the parameter values stored in :attr:`params` and will not sample values from + any distributions. + + It can be passed to objective functions (see :func:`~optuna.study.Study.optimize`) and is + useful for deploying optimization results. + + Example: + + Re-evaluate an objective function with parameter values optimized study. + + .. testcode:: + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", -1, 1) + return x**2 + + + study = optuna.create_study() + study.optimize(objective, n_trials=3) + + assert objective(study.best_trial) == study.best_value + + .. note:: + Instances are mutable, despite the name. + For instance, :func:`~optuna.trial.FrozenTrial.set_user_attr` will update user attributes + of objects in-place. + + + Example: + + Overwritten attributes. + + .. testcode:: + + import copy + import datetime + + import optuna + + + def objective(trial): + x = trial.suggest_float("x", -1, 1) + + # this user attribute always differs + trial.set_user_attr("evaluation time", datetime.datetime.now()) + + return x**2 + + + study = optuna.create_study() + study.optimize(objective, n_trials=3) + + best_trial = study.best_trial + best_trial_copy = copy.deepcopy(best_trial) + + # re-evaluate + objective(best_trial) + + # the user attribute is overwritten by re-evaluation + assert best_trial.user_attrs != best_trial_copy.user_attrs + + .. note:: + Please refer to :class:`~optuna.trial.Trial` for details of methods and properties. + + + Attributes: + number: + Unique and consecutive number of :class:`~optuna.trial.Trial` for each + :class:`~optuna.study.Study`. Note that this field uses zero-based numbering. + state: + :class:`TrialState` of the :class:`~optuna.trial.Trial`. + value: + Objective value of the :class:`~optuna.trial.Trial`. + ``value`` and ``values`` must not be specified at the same time. + values: + Sequence of objective values of the :class:`~optuna.trial.Trial`. + The length is greater than 1 if the problem is multi-objective optimization. + ``value`` and ``values`` must not be specified at the same time. + datetime_start: + Datetime where the :class:`~optuna.trial.Trial` started. + datetime_complete: + Datetime where the :class:`~optuna.trial.Trial` finished. + params: + Dictionary that contains suggested parameters. + distributions: + Dictionary that contains the distributions of :attr:`params`. + user_attrs: + Dictionary that contains the attributes of the :class:`~optuna.trial.Trial` set with + :func:`optuna.trial.Trial.set_user_attr`. + system_attrs: + Dictionary that contains the attributes of the :class:`~optuna.trial.Trial` set with + :func:`optuna.trial.Trial.set_system_attr`. + intermediate_values: + Intermediate objective values set with :func:`optuna.trial.Trial.report`. + """ + + def __init__( + self, + number: int, + state: TrialState, + value: float | None, + datetime_start: datetime.datetime | None, + datetime_complete: datetime.datetime | None, + params: dict[str, Any], + distributions: dict[str, BaseDistribution], + user_attrs: dict[str, Any], + system_attrs: dict[str, Any], + intermediate_values: dict[int, float], + trial_id: int, + *, + values: Sequence[float] | None = None, + ) -> None: + self._number = number + self.state = state + self._values: list[float] | None = None + if value is not None and values is not None: + raise ValueError("Specify only one of `value` and `values`.") + elif value is not None: + self._values = [value] + elif values is not None: + self._values = list(values) + self._datetime_start = datetime_start + self.datetime_complete = datetime_complete + self._params = params + self._user_attrs = user_attrs + self._system_attrs = system_attrs + self.intermediate_values = intermediate_values + self._distributions = distributions + self._trial_id = trial_id + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, FrozenTrial): + return NotImplemented + return other.__dict__ == self.__dict__ + + def __lt__(self, other: Any) -> bool: + if not isinstance(other, FrozenTrial): + return NotImplemented + + return self.number < other.number + + def __le__(self, other: Any) -> bool: + if not isinstance(other, FrozenTrial): + return NotImplemented + + return self.number <= other.number + + def __hash__(self) -> int: + return hash(tuple(getattr(self, field) for field in self.__dict__)) + + def __repr__(self) -> str: + return "{cls}({kwargs})".format( + cls=self.__class__.__name__, + kwargs=", ".join( + "{field}={value}".format( + field=field if not field.startswith("_") else field[1:], + value=repr(getattr(self, field)), + ) + for field in self.__dict__ + ) + + ", value=None", + ) + + def suggest_float( + self, + name: str, + low: float, + high: float, + *, + step: float | None = None, + log: bool = False, + ) -> float: + return self._suggest(name, FloatDistribution(low, high, log=log, step=step)) + + @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="")) + def suggest_uniform(self, name: str, low: float, high: float) -> float: + return self.suggest_float(name, low, high) + + @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="(..., log=True)")) + def suggest_loguniform(self, name: str, low: float, high: float) -> float: + return self.suggest_float(name, low, high, log=True) + + @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="(..., step=...)")) + def suggest_discrete_uniform(self, name: str, low: float, high: float, q: float) -> float: + return self.suggest_float(name, low, high, step=q) + + @convert_positional_args( + previous_positional_arg_names=_SUGGEST_INT_POSITIONAL_ARGS, + deprecated_version="3.5.0", + removed_version="5.0.0", + ) + def suggest_int( + self, name: str, low: int, high: int, *, step: int = 1, log: bool = False + ) -> int: + return int(self._suggest(name, IntDistribution(low, high, log=log, step=step))) + + @overload + def suggest_categorical(self, name: str, choices: Sequence[None]) -> None: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[bool]) -> bool: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[int]) -> int: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[float]) -> float: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[str]) -> str: ... + + @overload + def suggest_categorical( + self, name: str, choices: Sequence[CategoricalChoiceType] + ) -> CategoricalChoiceType: ... + + def suggest_categorical( + self, name: str, choices: Sequence[CategoricalChoiceType] + ) -> CategoricalChoiceType: + return self._suggest(name, CategoricalDistribution(choices=choices)) + + def report(self, value: float, step: int) -> None: + """Interface of report function. + + Since :class:`~optuna.trial.FrozenTrial` is not pruned, + this report function does nothing. + + .. seealso:: + Please refer to :func:`~optuna.trial.FrozenTrial.should_prune`. + + Args: + value: + A value returned from the objective function. + step: + Step of the trial (e.g., Epoch of neural network training). Note that pruners + assume that ``step`` starts at zero. For example, + :class:`~optuna.pruners.MedianPruner` simply checks if ``step`` is less than + ``n_warmup_steps`` as the warmup mechanism. + """ + + pass + + def should_prune(self) -> bool: + """Suggest whether the trial should be pruned or not. + + The suggestion is always :obj:`False` regardless of a pruning algorithm. + + .. note:: + :class:`~optuna.trial.FrozenTrial` only samples one combination of parameters. + + Returns: + :obj:`False`. + """ + + return False + + def set_user_attr(self, key: str, value: Any) -> None: + self._user_attrs[key] = value + + @deprecated_func("3.1.0", "5.0.0") + def set_system_attr(self, key: str, value: Any) -> None: + self._system_attrs[key] = value + + def _validate(self) -> None: + if self.state != TrialState.WAITING and self.datetime_start is None: + raise ValueError( + "`datetime_start` is supposed to be set when the trial state is not waiting." + ) + + if self.state.is_finished(): + if self.datetime_complete is None: + raise ValueError("`datetime_complete` is supposed to be set for a finished trial.") + else: + if self.datetime_complete is not None: + raise ValueError( + "`datetime_complete` is supposed to be None for an unfinished trial." + ) + + if self.state == TrialState.FAIL and self._values is not None: + raise ValueError(f"values should be None for a failed trial, but got {self._values}.") + if self.state == TrialState.COMPLETE: + if self._values is None: + raise ValueError("values should be set for a complete trial.") + elif any(math.isnan(x) for x in self._values): + raise ValueError("values should not contain NaN.") + + if set(self.params.keys()) != set(self.distributions.keys()): + raise ValueError( + "Inconsistent parameters {} and distributions {}.".format( + set(self.params.keys()), set(self.distributions.keys()) + ) + ) + + for param_name, param_value in self.params.items(): + distribution = self.distributions[param_name] + + param_value_in_internal_repr = distribution.to_internal_repr(param_value) + if not distribution._contains(param_value_in_internal_repr): + raise ValueError( + "The value {} of parameter '{}' isn't contained in the distribution " + "{}.".format(param_value, param_name, distribution) + ) + + def _suggest(self, name: str, distribution: BaseDistribution) -> Any: + if name not in self._params: + raise ValueError( + "The value of the parameter '{}' is not found. Please set it at " + "the construction of the FrozenTrial object.".format(name) + ) + + value = self._params[name] + param_value_in_internal_repr = distribution.to_internal_repr(value) + if not distribution._contains(param_value_in_internal_repr): + warnings.warn( + "The value {} of the parameter '{}' is out of " + "the range of the distribution {}.".format(value, name, distribution) + ) + + if name in self._distributions: + distributions.check_distribution_compatibility(self._distributions[name], distribution) + + self._distributions[name] = distribution + + return value + + @property + def number(self) -> int: + return self._number + + @number.setter + def number(self, value: int) -> None: + self._number = value + + @property + def value(self) -> float | None: + if self._values is not None: + if len(self._values) > 1: + raise RuntimeError( + "This attribute is not available during multi-objective optimization." + ) + return self._values[0] + return None + + @value.setter + def value(self, v: float | None) -> None: + if self._values is not None: + if len(self._values) > 1: + raise RuntimeError( + "This attribute is not available during multi-objective optimization." + ) + + if v is not None: + self._values = [v] + else: + self._values = None + + # These `_get_values`, `_set_values`, and `values = property(_get_values, _set_values)` are + # defined to pass the mypy. + # See https://github.com/python/mypy/issues/3004#issuecomment-726022329. + def _get_values(self) -> list[float] | None: + return self._values + + def _set_values(self, v: Sequence[float] | None) -> None: + if v is not None: + self._values = list(v) + else: + self._values = None + + values = property(_get_values, _set_values) + + @property + def datetime_start(self) -> datetime.datetime | None: + return self._datetime_start + + @datetime_start.setter + def datetime_start(self, value: datetime.datetime | None) -> None: + self._datetime_start = value + + @property + def params(self) -> dict[str, Any]: + return self._params + + @params.setter + def params(self, params: dict[str, Any]) -> None: + self._params = params + + @property + def distributions(self) -> dict[str, BaseDistribution]: + return self._distributions + + @distributions.setter + def distributions(self, value: dict[str, BaseDistribution]) -> None: + self._distributions = value + + @property + def user_attrs(self) -> dict[str, Any]: + return self._user_attrs + + @user_attrs.setter + def user_attrs(self, value: dict[str, Any]) -> None: + self._user_attrs = value + + @property + def system_attrs(self) -> dict[str, Any]: + return self._system_attrs + + @system_attrs.setter + def system_attrs(self, value: Mapping[str, JSONSerializable]) -> None: + self._system_attrs = cast(Dict[str, Any], value) + + @property + def last_step(self) -> int | None: + """Return the maximum step of :attr:`intermediate_values` in the trial. + + Returns: + The maximum step of intermediates. + """ + + if len(self.intermediate_values) == 0: + return None + else: + return max(self.intermediate_values.keys()) + + @property + def duration(self) -> datetime.timedelta | None: + """Return the elapsed time taken to complete the trial. + + Returns: + The duration. + """ + + if self.datetime_start and self.datetime_complete: + return self.datetime_complete - self.datetime_start + else: + return None + + +def create_trial( + *, + state: TrialState = TrialState.COMPLETE, + value: float | None = None, + values: Sequence[float] | None = None, + params: dict[str, Any] | None = None, + distributions: dict[str, BaseDistribution] | None = None, + user_attrs: dict[str, Any] | None = None, + system_attrs: dict[str, Any] | None = None, + intermediate_values: dict[int, float] | None = None, +) -> FrozenTrial: + """Create a new :class:`~optuna.trial.FrozenTrial`. + + Example: + + .. testcode:: + + import optuna + from optuna.distributions import CategoricalDistribution + from optuna.distributions import FloatDistribution + + trial = optuna.trial.create_trial( + params={"x": 1.0, "y": 0}, + distributions={ + "x": FloatDistribution(0, 10), + "y": CategoricalDistribution([-1, 0, 1]), + }, + value=5.0, + ) + + assert isinstance(trial, optuna.trial.FrozenTrial) + assert trial.value == 5.0 + assert trial.params == {"x": 1.0, "y": 0} + + .. seealso:: + + See :func:`~optuna.study.Study.add_trial` for how this function can be used to create a + study from existing trials. + + .. note:: + + Please note that this is a low-level API. In general, trials that are passed to objective + functions are created inside :func:`~optuna.study.Study.optimize`. + + .. note:: + When ``state`` is :class:`TrialState.COMPLETE`, the following parameters are + required: + + * ``params`` + * ``distributions`` + * ``value`` or ``values`` + + Args: + state: + Trial state. + value: + Trial objective value. Must be specified if ``state`` is :class:`TrialState.COMPLETE`. + ``value`` and ``values`` must not be specified at the same time. + values: + Sequence of the trial objective values. The length is greater than 1 if the problem is + multi-objective optimization. + Must be specified if ``state`` is :class:`TrialState.COMPLETE`. + ``value`` and ``values`` must not be specified at the same time. + params: + Dictionary with suggested parameters of the trial. + distributions: + Dictionary with parameter distributions of the trial. + user_attrs: + Dictionary with user attributes. + system_attrs: + Dictionary with system attributes. Should not have to be used for most users. + intermediate_values: + Dictionary with intermediate objective values of the trial. + + Returns: + Created trial. + """ + + params = params or {} + distributions = distributions or {} + distributions = { + key: _convert_old_distribution_to_new_distribution(dist) + for key, dist in distributions.items() + } + user_attrs = user_attrs or {} + system_attrs = system_attrs or {} + intermediate_values = intermediate_values or {} + + if state == TrialState.WAITING: + datetime_start = None + else: + datetime_start = datetime.datetime.now() + + if state.is_finished(): + datetime_complete: datetime.datetime | None = datetime_start + else: + datetime_complete = None + + trial = FrozenTrial( + number=-1, + trial_id=-1, + state=state, + value=value, + values=values, + datetime_start=datetime_start, + datetime_complete=datetime_complete, + params=params, + distributions=distributions, + user_attrs=user_attrs, + system_attrs=system_attrs, + intermediate_values=intermediate_values, + ) + + trial._validate() + + return trial diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_state.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_state.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a77131102af73c457596fed305d5125e069207 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_state.py @@ -0,0 +1,36 @@ +import enum + + +class TrialState(enum.IntEnum): + """State of a :class:`~optuna.trial.Trial`. + + Attributes: + RUNNING: + The :class:`~optuna.trial.Trial` is running. + WAITING: + The :class:`~optuna.trial.Trial` is waiting and unfinished. + COMPLETE: + The :class:`~optuna.trial.Trial` has been finished without any error. + PRUNED: + The :class:`~optuna.trial.Trial` has been pruned with + :class:`~optuna.exceptions.TrialPruned`. + FAIL: + The :class:`~optuna.trial.Trial` has failed due to an uncaught error. + """ + + RUNNING = 0 + COMPLETE = 1 + PRUNED = 2 + FAIL = 3 + WAITING = 4 + + def __repr__(self) -> str: + return str(self) + + def is_finished(self) -> bool: + """Return a bool value to represent whether the trial state is unfinished or not. + + The unfinished state is either ``RUNNING`` or ``WAITING``. + """ + + return self != TrialState.RUNNING and self != TrialState.WAITING diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_trial.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_trial.py new file mode 100644 index 0000000000000000000000000000000000000000..f0bf752ea369d441f964e7636315cd8e6e63cad6 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/trial/_trial.py @@ -0,0 +1,772 @@ +from __future__ import annotations + +from collections import UserDict +from collections.abc import Sequence +import copy +import datetime +from typing import Any +from typing import overload +import warnings + +import optuna +from optuna import distributions +from optuna import logging +from optuna import pruners +from optuna._convert_positional_args import convert_positional_args +from optuna._deprecated import deprecated_func +from optuna.distributions import BaseDistribution +from optuna.distributions import CategoricalChoiceType +from optuna.distributions import CategoricalDistribution +from optuna.distributions import FloatDistribution +from optuna.distributions import IntDistribution +from optuna.trial import FrozenTrial +from optuna.trial._base import _SUGGEST_INT_POSITIONAL_ARGS +from optuna.trial._base import BaseTrial + + +_logger = logging.get_logger(__name__) +_suggest_deprecated_msg = "Use suggest_float{args} instead." + + +class Trial(BaseTrial): + """A trial is a process of evaluating an objective function. + + This object is passed to an objective function and provides interfaces to get parameter + suggestion, manage the trial's state, and set/get user-defined attributes of the trial. + + Note that the direct use of this constructor is not recommended. + This object is seamlessly instantiated and passed to the objective function behind + the :func:`optuna.study.Study.optimize()` method; hence library users do not care about + instantiation of this object. + + Args: + study: + A :class:`~optuna.study.Study` object. + trial_id: + A trial ID that is automatically generated. + + """ + + def __init__(self, study: "optuna.study.Study", trial_id: int) -> None: + self.study = study + self._trial_id = trial_id + + self.storage = self.study._storage + + self._cached_frozen_trial = self.storage.get_trial(self._trial_id) + study = pruners._filter_study(self.study, self._cached_frozen_trial) + + self.study.sampler.before_trial(study, self._cached_frozen_trial) + + self.relative_search_space = self.study.sampler.infer_relative_search_space( + study, self._cached_frozen_trial + ) + self._relative_params: dict[str, Any] | None = None + self._fixed_params = self._cached_frozen_trial.system_attrs.get("fixed_params", {}) + + @property + def relative_params(self) -> dict[str, Any]: + if self._relative_params is None: + study = pruners._filter_study(self.study, self._cached_frozen_trial) + self._relative_params = self.study.sampler.sample_relative( + study, self._cached_frozen_trial, self.relative_search_space + ) + return self._relative_params + + def suggest_float( + self, + name: str, + low: float, + high: float, + *, + step: float | None = None, + log: bool = False, + ) -> float: + """Suggest a value for the floating point parameter. + + Example: + + Suggest a momentum, learning rate and scaling factor of learning rate + for neural network training. + + .. testcode:: + + import numpy as np + from sklearn.datasets import load_iris + from sklearn.model_selection import train_test_split + from sklearn.neural_network import MLPClassifier + + import optuna + + X, y = load_iris(return_X_y=True) + X_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state=0) + + + def objective(trial): + momentum = trial.suggest_float("momentum", 0.0, 1.0) + learning_rate_init = trial.suggest_float( + "learning_rate_init", 1e-5, 1e-3, log=True + ) + power_t = trial.suggest_float("power_t", 0.2, 0.8, step=0.1) + clf = MLPClassifier( + hidden_layer_sizes=(100, 50), + momentum=momentum, + learning_rate_init=learning_rate_init, + solver="sgd", + random_state=0, + power_t=power_t, + ) + clf.fit(X_train, y_train) + + return clf.score(X_valid, y_valid) + + + study = optuna.create_study(direction="maximize") + study.optimize(objective, n_trials=3) + + Args: + name: + A parameter name. + low: + Lower endpoint of the range of suggested values. ``low`` is included in the range. + ``low`` must be less than or equal to ``high``. If ``log`` is :obj:`True`, + ``low`` must be larger than 0. + high: + Upper endpoint of the range of suggested values. ``high`` is included in the range. + ``high`` must be greater than or equal to ``low``. + step: + A step of discretization. + + .. note:: + The ``step`` and ``log`` arguments cannot be used at the same time. To set + the ``step`` argument to a float number, set the ``log`` argument to + :obj:`False`. + log: + A flag to sample the value from the log domain or not. + If ``log`` is true, the value is sampled from the range in the log domain. + Otherwise, the value is sampled from the range in the linear domain. + + .. note:: + The ``step`` and ``log`` arguments cannot be used at the same time. To set + the ``log`` argument to :obj:`True`, set the ``step`` argument to :obj:`None`. + + Returns: + A suggested float value. + + .. seealso:: + :ref:`configurations` tutorial describes more details and flexible usages. + """ + + distribution = FloatDistribution(low, high, log=log, step=step) + suggested_value = self._suggest(name, distribution) + self._check_distribution(name, distribution) + return suggested_value + + @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="")) + def suggest_uniform(self, name: str, low: float, high: float) -> float: + """Suggest a value for the continuous parameter. + + The value is sampled from the range :math:`[\\mathsf{low}, \\mathsf{high})` + in the linear domain. When :math:`\\mathsf{low} = \\mathsf{high}`, the value of + :math:`\\mathsf{low}` will be returned. + + Args: + name: + A parameter name. + low: + Lower endpoint of the range of suggested values. ``low`` is included in the range. + high: + Upper endpoint of the range of suggested values. ``high`` is included in the range. + + Returns: + A suggested float value. + """ + + return self.suggest_float(name, low, high) + + @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="(..., log=True)")) + def suggest_loguniform(self, name: str, low: float, high: float) -> float: + """Suggest a value for the continuous parameter. + + The value is sampled from the range :math:`[\\mathsf{low}, \\mathsf{high})` + in the log domain. When :math:`\\mathsf{low} = \\mathsf{high}`, the value of + :math:`\\mathsf{low}` will be returned. + + Args: + name: + A parameter name. + low: + Lower endpoint of the range of suggested values. ``low`` is included in the range. + high: + Upper endpoint of the range of suggested values. ``high`` is included in the range. + + Returns: + A suggested float value. + """ + + return self.suggest_float(name, low, high, log=True) + + @deprecated_func("3.0.0", "6.0.0", text=_suggest_deprecated_msg.format(args="(..., step=...)")) + def suggest_discrete_uniform(self, name: str, low: float, high: float, q: float) -> float: + """Suggest a value for the discrete parameter. + + The value is sampled from the range :math:`[\\mathsf{low}, \\mathsf{high}]`, + and the step of discretization is :math:`q`. More specifically, + this method returns one of the values in the sequence + :math:`\\mathsf{low}, \\mathsf{low} + q, \\mathsf{low} + 2 q, \\dots, + \\mathsf{low} + k q \\le \\mathsf{high}`, + where :math:`k` denotes an integer. Note that :math:`high` may be changed due to round-off + errors if :math:`q` is not an integer. Please check warning messages to find the changed + values. + + Args: + name: + A parameter name. + low: + Lower endpoint of the range of suggested values. ``low`` is included in the range. + high: + Upper endpoint of the range of suggested values. ``high`` is included in the range. + q: + A step of discretization. + + Returns: + A suggested float value. + """ + + return self.suggest_float(name, low, high, step=q) + + @convert_positional_args( + previous_positional_arg_names=_SUGGEST_INT_POSITIONAL_ARGS, + deprecated_version="3.5.0", + removed_version="5.0.0", + ) + def suggest_int( + self, name: str, low: int, high: int, *, step: int = 1, log: bool = False + ) -> int: + """Suggest a value for the integer parameter. + + The value is sampled from the integers in :math:`[\\mathsf{low}, \\mathsf{high}]`. + + Example: + + Suggest the number of trees in `RandomForestClassifier `__. + + .. testcode:: + + import numpy as np + from sklearn.datasets import load_iris + from sklearn.ensemble import RandomForestClassifier + from sklearn.model_selection import train_test_split + + import optuna + + X, y = load_iris(return_X_y=True) + X_train, X_valid, y_train, y_valid = train_test_split(X, y) + + + def objective(trial): + n_estimators = trial.suggest_int("n_estimators", 50, 400) + clf = RandomForestClassifier(n_estimators=n_estimators, random_state=0) + clf.fit(X_train, y_train) + return clf.score(X_valid, y_valid) + + + study = optuna.create_study(direction="maximize") + study.optimize(objective, n_trials=3) + + Args: + name: + A parameter name. + low: + Lower endpoint of the range of suggested values. ``low`` is included in the range. + ``low`` must be less than or equal to ``high``. If ``log`` is :obj:`True`, + ``low`` must be larger than 0. + high: + Upper endpoint of the range of suggested values. ``high`` is included in the range. + ``high`` must be greater than or equal to ``low``. + step: + A step of discretization. + + .. note:: + Note that :math:`\\mathsf{high}` is modified if the range is not divisible by + :math:`\\mathsf{step}`. Please check the warning messages to find the changed + values. + + .. note:: + The method returns one of the values in the sequence + :math:`\\mathsf{low}, \\mathsf{low} + \\mathsf{step}, \\mathsf{low} + 2 * + \\mathsf{step}, \\dots, \\mathsf{low} + k * \\mathsf{step} \\le + \\mathsf{high}`, where :math:`k` denotes an integer. + + .. note:: + The ``step != 1`` and ``log`` arguments cannot be used at the same time. + To set the ``step`` argument :math:`\\mathsf{step} \\ge 2`, set the + ``log`` argument to :obj:`False`. + log: + A flag to sample the value from the log domain or not. + + .. note:: + If ``log`` is true, at first, the range of suggested values is divided into + grid points of width 1. The range of suggested values is then converted to + a log domain, from which a value is sampled. The uniformly sampled + value is re-converted to the original domain and rounded to the nearest grid + point that we just split, and the suggested value is determined. + For example, if `low = 2` and `high = 8`, then the range of suggested values is + `[2, 3, 4, 5, 6, 7, 8]` and lower values tend to be more sampled than higher + values. + + .. note:: + The ``step != 1`` and ``log`` arguments cannot be used at the same time. + To set the ``log`` argument to :obj:`True`, set the ``step`` argument to 1. + + .. seealso:: + :ref:`configurations` tutorial describes more details and flexible usages. + """ + + distribution = IntDistribution(low=low, high=high, log=log, step=step) + suggested_value = int(self._suggest(name, distribution)) + self._check_distribution(name, distribution) + return suggested_value + + @overload + def suggest_categorical(self, name: str, choices: Sequence[None]) -> None: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[bool]) -> bool: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[int]) -> int: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[float]) -> float: ... + + @overload + def suggest_categorical(self, name: str, choices: Sequence[str]) -> str: ... + + @overload + def suggest_categorical( + self, name: str, choices: Sequence[CategoricalChoiceType] + ) -> CategoricalChoiceType: ... + + def suggest_categorical( + self, name: str, choices: Sequence[CategoricalChoiceType] + ) -> CategoricalChoiceType: + """Suggest a value for the categorical parameter. + + The value is sampled from ``choices``. + + Example: + + Suggest a kernel function of `SVC `__. + + .. testcode:: + + import numpy as np + from sklearn.datasets import load_iris + from sklearn.model_selection import train_test_split + from sklearn.svm import SVC + + import optuna + + X, y = load_iris(return_X_y=True) + X_train, X_valid, y_train, y_valid = train_test_split(X, y) + + + def objective(trial): + kernel = trial.suggest_categorical("kernel", ["linear", "poly", "rbf"]) + clf = SVC(kernel=kernel, gamma="scale", random_state=0) + clf.fit(X_train, y_train) + return clf.score(X_valid, y_valid) + + + study = optuna.create_study(direction="maximize") + study.optimize(objective, n_trials=3) + + + Args: + name: + A parameter name. + choices: + Parameter value candidates. + + .. seealso:: + :class:`~optuna.distributions.CategoricalDistribution`. + + Returns: + A suggested value. + + .. seealso:: + :ref:`configurations` tutorial describes more details and flexible usages. + """ + # There is no need to call self._check_distribution because + # CategoricalDistribution does not support dynamic value space. + + return self._suggest(name, CategoricalDistribution(choices=choices)) + + def report(self, value: float, step: int) -> None: + """Report an objective function value for a given step. + + The reported values are used by the pruners to determine whether this trial should be + pruned. + + .. seealso:: + Please refer to :class:`~optuna.pruners.BasePruner`. + + .. note:: + The reported value is converted to ``float`` type by applying ``float()`` + function internally. Thus, it accepts all float-like types (e.g., ``numpy.float32``). + If the conversion fails, a ``TypeError`` is raised. + + .. note:: + If this method is called multiple times at the same ``step`` in a trial, + the reported ``value`` only the first time is stored and the reported values + from the second time are ignored. + + .. note:: + :func:`~optuna.trial.Trial.report` does not support multi-objective + optimization. + + Example: + + Report intermediate scores of `SGDClassifier `__ training. + + .. testcode:: + + import numpy as np + from sklearn.datasets import load_iris + from sklearn.linear_model import SGDClassifier + from sklearn.model_selection import train_test_split + + import optuna + + X, y = load_iris(return_X_y=True) + X_train, X_valid, y_train, y_valid = train_test_split(X, y) + + + def objective(trial): + clf = SGDClassifier(random_state=0) + for step in range(100): + clf.partial_fit(X_train, y_train, np.unique(y)) + intermediate_value = clf.score(X_valid, y_valid) + trial.report(intermediate_value, step=step) + if trial.should_prune(): + raise optuna.TrialPruned() + + return clf.score(X_valid, y_valid) + + + study = optuna.create_study(direction="maximize") + study.optimize(objective, n_trials=3) + + + Args: + value: + A value returned from the objective function. + step: + Step of the trial (e.g., Epoch of neural network training). Note that pruners + assume that ``step`` starts at zero. For example, + :class:`~optuna.pruners.MedianPruner` simply checks if ``step`` is less than + ``n_warmup_steps`` as the warmup mechanism. + ``step`` must be a positive integer. + """ + + if len(self.study.directions) > 1: + raise NotImplementedError( + "Trial.report is not supported for multi-objective optimization." + ) + + try: + # For convenience, we allow users to report a value that can be cast to `float`. + value = float(value) + except (TypeError, ValueError): + message = ( + f"The `value` argument is of type '{type(value)}' but supposed to be a float." + ) + raise TypeError(message) from None + + try: + step = int(step) + except (TypeError, ValueError): + message = f"The `step` argument is of type '{type(step)}' but supposed to be an int." + raise TypeError(message) from None + + if step < 0: + raise ValueError(f"The `step` argument is {step} but cannot be negative.") + + if step in self._cached_frozen_trial.intermediate_values: + # Do nothing if already reported. + warnings.warn( + f"The reported value is ignored because this `step` {step} is already reported." + ) + return + + self.storage.set_trial_intermediate_value(self._trial_id, step, value) + self._cached_frozen_trial.intermediate_values[step] = value + + def should_prune(self) -> bool: + """Suggest whether the trial should be pruned or not. + + The suggestion is made by a pruning algorithm associated with the trial and is based on + previously reported values. The algorithm can be specified when constructing a + :class:`~optuna.study.Study`. + + .. note:: + If no values have been reported, the algorithm cannot make meaningful suggestions. + Similarly, if this method is called multiple times with the exact same set of reported + values, the suggestions will be the same. + + .. seealso:: + Please refer to the example code in :func:`optuna.trial.Trial.report`. + + .. note:: + :func:`~optuna.trial.Trial.should_prune` does not support multi-objective + optimization. + + Returns: + A boolean value. If :obj:`True`, the trial should be pruned according to the + configured pruning algorithm. Otherwise, the trial should continue. + """ + + if len(self.study.directions) > 1: + raise NotImplementedError( + "Trial.should_prune is not supported for multi-objective optimization." + ) + + trial = self._get_latest_trial() + return self.study.pruner.prune(self.study, trial) + + def set_user_attr(self, key: str, value: Any) -> None: + """Set user attributes to the trial. + + The user attributes in the trial can be access via :func:`optuna.trial.Trial.user_attrs`. + + .. seealso:: + + See the recipe on :ref:`attributes`. + + Example: + + Save fixed hyperparameters of neural network training. + + .. testcode:: + + import numpy as np + from sklearn.datasets import load_iris + from sklearn.model_selection import train_test_split + from sklearn.neural_network import MLPClassifier + + import optuna + + X, y = load_iris(return_X_y=True) + X_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state=0) + + + def objective(trial): + trial.set_user_attr("BATCHSIZE", 128) + momentum = trial.suggest_float("momentum", 0, 1.0) + clf = MLPClassifier( + hidden_layer_sizes=(100, 50), + batch_size=trial.user_attrs["BATCHSIZE"], + momentum=momentum, + solver="sgd", + random_state=0, + ) + clf.fit(X_train, y_train) + + return clf.score(X_valid, y_valid) + + + study = optuna.create_study(direction="maximize") + study.optimize(objective, n_trials=3) + assert "BATCHSIZE" in study.best_trial.user_attrs.keys() + assert study.best_trial.user_attrs["BATCHSIZE"] == 128 + + + Args: + key: + A key string of the attribute. + value: + A value of the attribute. The value should be JSON serializable. + """ + + self.storage.set_trial_user_attr(self._trial_id, key, value) + self._cached_frozen_trial.user_attrs[key] = value + + @deprecated_func("3.1.0", "5.0.0") + def set_system_attr(self, key: str, value: Any) -> None: + """Set system attributes to the trial. + + Note that Optuna internally uses this method to save system messages such as failure + reason of trials. Please use :func:`~optuna.trial.Trial.set_user_attr` to set users' + attributes. + + Args: + key: + A key string of the attribute. + value: + A value of the attribute. The value should be JSON serializable. + """ + + self.storage.set_trial_system_attr(self._trial_id, key, value) + self._cached_frozen_trial.system_attrs[key] = value + + def _suggest(self, name: str, distribution: BaseDistribution) -> Any: + storage = self.storage + trial_id = self._trial_id + + trial = self._get_latest_trial() + + if name in trial.distributions: + # No need to sample if already suggested. + distributions.check_distribution_compatibility(trial.distributions[name], distribution) + param_value = trial.params[name] + else: + if self._is_fixed_param(name, distribution): + param_value = self._fixed_params[name] + elif distribution.single(): + param_value = distributions._get_single_value(distribution) + elif self._is_relative_param(name, distribution): + param_value = self.relative_params[name] + else: + study = pruners._filter_study(self.study, trial) + param_value = self.study.sampler.sample_independent( + study, trial, name, distribution + ) + + # `param_value` is validated here (invalid value like `np.nan` raises ValueError). + param_value_in_internal_repr = distribution.to_internal_repr(param_value) + storage.set_trial_param(trial_id, name, param_value_in_internal_repr, distribution) + + self._cached_frozen_trial.distributions[name] = distribution + self._cached_frozen_trial.params[name] = param_value + return param_value + + def _is_fixed_param(self, name: str, distribution: BaseDistribution) -> bool: + if name not in self._fixed_params: + return False + + param_value = self._fixed_params[name] + param_value_in_internal_repr = distribution.to_internal_repr(param_value) + + contained = distribution._contains(param_value_in_internal_repr) + if not contained: + warnings.warn( + "Fixed parameter '{}' with value {} is out of range " + "for distribution {}.".format(name, param_value, distribution) + ) + return True + + def _is_relative_param(self, name: str, distribution: BaseDistribution) -> bool: + if name not in self.relative_params: + return False + + if name not in self.relative_search_space: + raise ValueError( + "The parameter '{}' was sampled by `sample_relative` method " + "but it is not contained in the relative search space.".format(name) + ) + + relative_distribution = self.relative_search_space[name] + distributions.check_distribution_compatibility(relative_distribution, distribution) + + param_value = self.relative_params[name] + param_value_in_internal_repr = distribution.to_internal_repr(param_value) + return distribution._contains(param_value_in_internal_repr) + + def _check_distribution(self, name: str, distribution: BaseDistribution) -> None: + old_distribution = self._cached_frozen_trial.distributions.get(name, distribution) + if old_distribution != distribution: + warnings.warn( + 'Inconsistent parameter values for distribution with name "{}"! ' + "This might be a configuration mistake. " + "Optuna allows to call the same distribution with the same " + "name more than once in a trial. " + "When the parameter values are inconsistent optuna only " + "uses the values of the first call and ignores all following. " + "Using these values: {}".format(name, old_distribution._asdict()), + RuntimeWarning, + ) + + def _get_latest_trial(self) -> FrozenTrial: + # TODO(eukaryo): Remove this method after `system_attrs` property is removed. + latest_trial = copy.copy(self._cached_frozen_trial) + latest_trial.system_attrs = _LazyTrialSystemAttrs(self._trial_id, self.storage) + return latest_trial + + @property + def params(self) -> dict[str, Any]: + """Return parameters to be optimized. + + Returns: + A dictionary containing all parameters. + """ + + return copy.deepcopy(self._cached_frozen_trial.params) + + @property + def distributions(self) -> dict[str, BaseDistribution]: + """Return distributions of parameters to be optimized. + + Returns: + A dictionary containing all distributions. + """ + + return copy.deepcopy(self._cached_frozen_trial.distributions) + + @property + def user_attrs(self) -> dict[str, Any]: + """Return user attributes. + + Returns: + A dictionary containing all user attributes. + """ + + return copy.deepcopy(self._cached_frozen_trial.user_attrs) + + @property + @deprecated_func("3.1.0", "5.0.0") + def system_attrs(self) -> dict[str, Any]: + """Return system attributes. + + Returns: + A dictionary containing all system attributes. + """ + + return copy.deepcopy(self.storage.get_trial_system_attrs(self._trial_id)) + + @property + def datetime_start(self) -> datetime.datetime | None: + """Return start datetime. + + Returns: + Datetime where the :class:`~optuna.trial.Trial` started. + """ + return self._cached_frozen_trial.datetime_start + + @property + def number(self) -> int: + """Return trial's number which is consecutive and unique in a study. + + Returns: + A trial number. + """ + + return self._cached_frozen_trial.number + + +class _LazyTrialSystemAttrs(UserDict): + def __init__(self, trial_id: int, storage: optuna.storages.BaseStorage) -> None: + super().__init__() + self._trial_id = trial_id + self._storage = storage + self._initialized = False + + def __getattribute__(self, key: str) -> Any: + if key == "data": + if not self._initialized: + self._initialized = True + super().update(self._storage.get_trial_system_attrs(self._trial_id)) + return super().__getattribute__(key) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/visualization/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/visualization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2478c2e81956a477bca80041028fae2fc7814001 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/optuna/visualization/__init__.py @@ -0,0 +1,32 @@ +from optuna.visualization import matplotlib +from optuna.visualization._contour import plot_contour +from optuna.visualization._edf import plot_edf +from optuna.visualization._hypervolume_history import plot_hypervolume_history +from optuna.visualization._intermediate_values import plot_intermediate_values +from optuna.visualization._optimization_history import plot_optimization_history +from optuna.visualization._parallel_coordinate import plot_parallel_coordinate +from optuna.visualization._param_importances import plot_param_importances +from optuna.visualization._pareto_front import plot_pareto_front +from optuna.visualization._rank import plot_rank +from optuna.visualization._slice import plot_slice +from optuna.visualization._terminator_improvement import plot_terminator_improvement +from optuna.visualization._timeline import plot_timeline +from optuna.visualization._utils import is_available + + +__all__ = [ + "is_available", + "matplotlib", + "plot_contour", + "plot_edf", + "plot_hypervolume_history", + "plot_intermediate_values", + "plot_optimization_history", + "plot_parallel_coordinate", + "plot_param_importances", + "plot_pareto_front", + "plot_slice", + "plot_rank", + "plot_terminator_improvement", + "plot_timeline", +] diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2140970015d099763797d60a98a3a3b6f4b5f219 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__init__.py @@ -0,0 +1,14 @@ +""" +Module containing private utility functions +=========================================== + +The ``scipy._lib`` namespace is empty (for now). Tests for all +utilities in submodules of ``_lib`` can be run with:: + + from scipy import _lib + _lib.test() + +""" +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a5293cfec64c0a876fe2921a8cb375c68e5bb44 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19713f406a7ad63cd0483a32b8a386ee8483129c Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..350cc0a6c401470e3a745e77bfc4bbcc755861f0 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c52d8b1c31dec183d03cefd8ebe52cf9feb6987 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db6e064e5fd7e1d07008c778769b9c58aa797996 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85ebf1fc26fb6515e188484e63c4ad6497413bc2 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f93a94081781be95db60598b0606c98722af398b Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecbf30ef65783f1fadfb1eff9cec99174fb5ea6b Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..531b8c23c66f6accd657eb2b094b124ca08eccf2 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ec0ab92c477cff8ac967daf2cfe18163e0f7e0a Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..073dd2d4ceb577da7c49fac69123296bd605cee5 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8b47e71c89ef51a2238ed24c41963bd2d645a1c Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..066d7c4f514c0e12fa5202defc4b194cc9d98649 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22bb9bca4580ce527ba3ef05631e062f391b6e68 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17cf96c05a5ac0ea11e19817aecb77ee39f90634 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..591a1ad142f91fefad4a3fb0cde135551d822567 Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py new file mode 100644 index 0000000000000000000000000000000000000000..8b4094d88c75d93367c481f5c3f603424cd6c13c --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api.py @@ -0,0 +1,606 @@ +"""Utility functions to use Python Array API compatible libraries. + +For the context about the Array API see: +https://data-apis.org/array-api/latest/purpose_and_scope.html + +The SciPy use case of the Array API is described on the following page: +https://data-apis.org/array-api/latest/use_cases.html#use-case-scipy +""" +import os + +from types import ModuleType +from typing import Any, Literal, TypeAlias + +import numpy as np +import numpy.typing as npt + +from scipy._lib import array_api_compat +from scipy._lib.array_api_compat import ( + is_array_api_obj, + size as xp_size, + numpy as np_compat, + device as xp_device, + is_numpy_namespace as is_numpy, + is_cupy_namespace as is_cupy, + is_torch_namespace as is_torch, + is_jax_namespace as is_jax, + is_array_api_strict_namespace as is_array_api_strict +) + +__all__ = [ + '_asarray', 'array_namespace', 'assert_almost_equal', 'assert_array_almost_equal', + 'get_xp_devices', + 'is_array_api_strict', 'is_complex', 'is_cupy', 'is_jax', 'is_numpy', 'is_torch', + 'SCIPY_ARRAY_API', 'SCIPY_DEVICE', 'scipy_namespace_for', + 'xp_assert_close', 'xp_assert_equal', 'xp_assert_less', + 'xp_copy', 'xp_copysign', 'xp_device', + 'xp_moveaxis_to_end', 'xp_ravel', 'xp_real', 'xp_sign', 'xp_size', + 'xp_take_along_axis', 'xp_unsupported_param_msg', 'xp_vector_norm', +] + + +# To enable array API and strict array-like input validation +SCIPY_ARRAY_API: str | bool = os.environ.get("SCIPY_ARRAY_API", False) +# To control the default device - for use in the test suite only +SCIPY_DEVICE = os.environ.get("SCIPY_DEVICE", "cpu") + +_GLOBAL_CONFIG = { + "SCIPY_ARRAY_API": SCIPY_ARRAY_API, + "SCIPY_DEVICE": SCIPY_DEVICE, +} + + +Array: TypeAlias = Any # To be changed to a Protocol later (see array-api#589) +ArrayLike: TypeAlias = Array | npt.ArrayLike + + +def _compliance_scipy(arrays): + """Raise exceptions on known-bad subclasses. + + The following subclasses are not supported and raise and error: + - `numpy.ma.MaskedArray` + - `numpy.matrix` + - NumPy arrays which do not have a boolean or numerical dtype + - Any array-like which is neither array API compatible nor coercible by NumPy + - Any array-like which is coerced by NumPy to an unsupported dtype + """ + for i in range(len(arrays)): + array = arrays[i] + + from scipy.sparse import issparse + # this comes from `_util._asarray_validated` + if issparse(array): + msg = ('Sparse arrays/matrices are not supported by this function. ' + 'Perhaps one of the `scipy.sparse.linalg` functions ' + 'would work instead.') + raise ValueError(msg) + + if isinstance(array, np.ma.MaskedArray): + raise TypeError("Inputs of type `numpy.ma.MaskedArray` are not supported.") + elif isinstance(array, np.matrix): + raise TypeError("Inputs of type `numpy.matrix` are not supported.") + if isinstance(array, np.ndarray | np.generic): + dtype = array.dtype + if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)): + raise TypeError(f"An argument has dtype `{dtype!r}`; " + f"only boolean and numerical dtypes are supported.") + elif not is_array_api_obj(array): + try: + array = np.asanyarray(array) + except TypeError: + raise TypeError("An argument is neither array API compatible nor " + "coercible by NumPy.") + dtype = array.dtype + if not (np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.bool_)): + message = ( + f"An argument was coerced to an unsupported dtype `{dtype!r}`; " + f"only boolean and numerical dtypes are supported." + ) + raise TypeError(message) + arrays[i] = array + return arrays + + +def _check_finite(array: Array, xp: ModuleType) -> None: + """Check for NaNs or Infs.""" + msg = "array must not contain infs or NaNs" + try: + if not xp.all(xp.isfinite(array)): + raise ValueError(msg) + except TypeError: + raise ValueError(msg) + + +def array_namespace(*arrays: Array) -> ModuleType: + """Get the array API compatible namespace for the arrays xs. + + Parameters + ---------- + *arrays : sequence of array_like + Arrays used to infer the common namespace. + + Returns + ------- + namespace : module + Common namespace. + + Notes + ----- + Thin wrapper around `array_api_compat.array_namespace`. + + 1. Check for the global switch: SCIPY_ARRAY_API. This can also be accessed + dynamically through ``_GLOBAL_CONFIG['SCIPY_ARRAY_API']``. + 2. `_compliance_scipy` raise exceptions on known-bad subclasses. See + its definition for more details. + + When the global switch is False, it defaults to the `numpy` namespace. + In that case, there is no compliance check. This is a convenience to + ease the adoption. Otherwise, arrays must comply with the new rules. + """ + if not _GLOBAL_CONFIG["SCIPY_ARRAY_API"]: + # here we could wrap the namespace if needed + return np_compat + + _arrays = [array for array in arrays if array is not None] + + _arrays = _compliance_scipy(_arrays) + + return array_api_compat.array_namespace(*_arrays) + + +def _asarray( + array: ArrayLike, + dtype: Any = None, + order: Literal['K', 'A', 'C', 'F'] | None = None, + copy: bool | None = None, + *, + xp: ModuleType | None = None, + check_finite: bool = False, + subok: bool = False, + ) -> Array: + """SciPy-specific replacement for `np.asarray` with `order`, `check_finite`, and + `subok`. + + Memory layout parameter `order` is not exposed in the Array API standard. + `order` is only enforced if the input array implementation + is NumPy based, otherwise `order` is just silently ignored. + + `check_finite` is also not a keyword in the array API standard; included + here for convenience rather than that having to be a separate function + call inside SciPy functions. + + `subok` is included to allow this function to preserve the behaviour of + `np.asanyarray` for NumPy based inputs. + """ + if xp is None: + xp = array_namespace(array) + if is_numpy(xp): + # Use NumPy API to support order + if copy is True: + array = np.array(array, order=order, dtype=dtype, subok=subok) + elif subok: + array = np.asanyarray(array, order=order, dtype=dtype) + else: + array = np.asarray(array, order=order, dtype=dtype) + else: + try: + array = xp.asarray(array, dtype=dtype, copy=copy) + except TypeError: + coerced_xp = array_namespace(xp.asarray(3)) + array = coerced_xp.asarray(array, dtype=dtype, copy=copy) + + if check_finite: + _check_finite(array, xp) + + return array + + +def xp_copy(x: Array, *, xp: ModuleType | None = None) -> Array: + """ + Copies an array. + + Parameters + ---------- + x : array + + xp : array_namespace + + Returns + ------- + copy : array + Copied array + + Notes + ----- + This copy function does not offer all the semantics of `np.copy`, i.e. the + `subok` and `order` keywords are not used. + """ + # Note: for older NumPy versions, `np.asarray` did not support the `copy` kwarg, + # so this uses our other helper `_asarray`. + if xp is None: + xp = array_namespace(x) + + return _asarray(x, copy=True, xp=xp) + + +def _strict_check(actual, desired, xp, *, + check_namespace=True, check_dtype=True, check_shape=True, + check_0d=True): + __tracebackhide__ = True # Hide traceback for py.test + if check_namespace: + _assert_matching_namespace(actual, desired) + + # only NumPy distinguishes between scalars and arrays; we do if check_0d=True. + # do this first so we can then cast to array (and thus use the array API) below. + if is_numpy(xp) and check_0d: + _msg = ("Array-ness does not match:\n Actual: " + f"{type(actual)}\n Desired: {type(desired)}") + assert ((xp.isscalar(actual) and xp.isscalar(desired)) + or (not xp.isscalar(actual) and not xp.isscalar(desired))), _msg + + actual = xp.asarray(actual) + desired = xp.asarray(desired) + + if check_dtype: + _msg = f"dtypes do not match.\nActual: {actual.dtype}\nDesired: {desired.dtype}" + assert actual.dtype == desired.dtype, _msg + + if check_shape: + _msg = f"Shapes do not match.\nActual: {actual.shape}\nDesired: {desired.shape}" + assert actual.shape == desired.shape, _msg + + desired = xp.broadcast_to(desired, actual.shape) + return actual, desired + + +def _assert_matching_namespace(actual, desired): + __tracebackhide__ = True # Hide traceback for py.test + actual = actual if isinstance(actual, tuple) else (actual,) + desired_space = array_namespace(desired) + for arr in actual: + arr_space = array_namespace(arr) + _msg = (f"Namespaces do not match.\n" + f"Actual: {arr_space.__name__}\n" + f"Desired: {desired_space.__name__}") + assert arr_space == desired_space, _msg + + +def xp_assert_equal(actual, desired, *, check_namespace=True, check_dtype=True, + check_shape=True, check_0d=True, err_msg='', xp=None): + __tracebackhide__ = True # Hide traceback for py.test + if xp is None: + xp = array_namespace(actual) + + actual, desired = _strict_check( + actual, desired, xp, check_namespace=check_namespace, + check_dtype=check_dtype, check_shape=check_shape, + check_0d=check_0d + ) + + if is_cupy(xp): + return xp.testing.assert_array_equal(actual, desired, err_msg=err_msg) + elif is_torch(xp): + # PyTorch recommends using `rtol=0, atol=0` like this + # to test for exact equality + err_msg = None if err_msg == '' else err_msg + return xp.testing.assert_close(actual, desired, rtol=0, atol=0, equal_nan=True, + check_dtype=False, msg=err_msg) + # JAX uses `np.testing` + return np.testing.assert_array_equal(actual, desired, err_msg=err_msg) + + +def xp_assert_close(actual, desired, *, rtol=None, atol=0, check_namespace=True, + check_dtype=True, check_shape=True, check_0d=True, + err_msg='', xp=None): + __tracebackhide__ = True # Hide traceback for py.test + if xp is None: + xp = array_namespace(actual) + + actual, desired = _strict_check( + actual, desired, xp, + check_namespace=check_namespace, check_dtype=check_dtype, + check_shape=check_shape, check_0d=check_0d + ) + + floating = xp.isdtype(actual.dtype, ('real floating', 'complex floating')) + if rtol is None and floating: + # multiplier of 4 is used as for `np.float64` this puts the default `rtol` + # roughly half way between sqrt(eps) and the default for + # `numpy.testing.assert_allclose`, 1e-7 + rtol = xp.finfo(actual.dtype).eps**0.5 * 4 + elif rtol is None: + rtol = 1e-7 + + if is_cupy(xp): + return xp.testing.assert_allclose(actual, desired, rtol=rtol, + atol=atol, err_msg=err_msg) + elif is_torch(xp): + err_msg = None if err_msg == '' else err_msg + return xp.testing.assert_close(actual, desired, rtol=rtol, atol=atol, + equal_nan=True, check_dtype=False, msg=err_msg) + # JAX uses `np.testing` + return np.testing.assert_allclose(actual, desired, rtol=rtol, + atol=atol, err_msg=err_msg) + + +def xp_assert_less(actual, desired, *, check_namespace=True, check_dtype=True, + check_shape=True, check_0d=True, err_msg='', verbose=True, xp=None): + __tracebackhide__ = True # Hide traceback for py.test + if xp is None: + xp = array_namespace(actual) + + actual, desired = _strict_check( + actual, desired, xp, check_namespace=check_namespace, + check_dtype=check_dtype, check_shape=check_shape, + check_0d=check_0d + ) + + if is_cupy(xp): + return xp.testing.assert_array_less(actual, desired, + err_msg=err_msg, verbose=verbose) + elif is_torch(xp): + if actual.device.type != 'cpu': + actual = actual.cpu() + if desired.device.type != 'cpu': + desired = desired.cpu() + # JAX uses `np.testing` + return np.testing.assert_array_less(actual, desired, + err_msg=err_msg, verbose=verbose) + + +def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) + + +def assert_almost_equal(actual, desired, decimal=7, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) + + +def xp_unsupported_param_msg(param: Any) -> str: + return f'Providing {param!r} is only supported for numpy arrays.' + + +def is_complex(x: Array, xp: ModuleType) -> bool: + return xp.isdtype(x.dtype, 'complex floating') + + +def get_xp_devices(xp: ModuleType) -> list[str] | list[None]: + """Returns a list of available devices for the given namespace.""" + devices: list[str] = [] + if is_torch(xp): + devices += ['cpu'] + import torch # type: ignore[import] + num_cuda = torch.cuda.device_count() + for i in range(0, num_cuda): + devices += [f'cuda:{i}'] + if torch.backends.mps.is_available(): + devices += ['mps'] + return devices + elif is_cupy(xp): + import cupy # type: ignore[import] + num_cuda = cupy.cuda.runtime.getDeviceCount() + for i in range(0, num_cuda): + devices += [f'cuda:{i}'] + return devices + elif is_jax(xp): + import jax # type: ignore[import] + num_cpu = jax.device_count(backend='cpu') + for i in range(0, num_cpu): + devices += [f'cpu:{i}'] + num_gpu = jax.device_count(backend='gpu') + for i in range(0, num_gpu): + devices += [f'gpu:{i}'] + num_tpu = jax.device_count(backend='tpu') + for i in range(0, num_tpu): + devices += [f'tpu:{i}'] + return devices + + # given namespace is not known to have a list of available devices; + # return `[None]` so that one can use this in tests for `device=None`. + return [None] + + +def scipy_namespace_for(xp: ModuleType) -> ModuleType | None: + """Return the `scipy`-like namespace of a non-NumPy backend + + That is, return the namespace corresponding with backend `xp` that contains + `scipy` sub-namespaces like `linalg` and `special`. If no such namespace + exists, return ``None``. Useful for dispatching. + """ + + if is_cupy(xp): + import cupyx # type: ignore[import-not-found,import-untyped] + return cupyx.scipy + + if is_jax(xp): + import jax # type: ignore[import-not-found] + return jax.scipy + + if is_torch(xp): + return xp + + return None + + +# temporary substitute for xp.moveaxis, which is not yet in all backends +# or covered by array_api_compat. +def xp_moveaxis_to_end( + x: Array, + source: int, + /, *, + xp: ModuleType | None = None) -> Array: + xp = array_namespace(xp) if xp is None else xp + axes = list(range(x.ndim)) + temp = axes.pop(source) + axes = axes + [temp] + return xp.permute_dims(x, axes) + + +# temporary substitute for xp.copysign, which is not yet in all backends +# or covered by array_api_compat. +def xp_copysign(x1: Array, x2: Array, /, *, xp: ModuleType | None = None) -> Array: + # no attempt to account for special cases + xp = array_namespace(x1, x2) if xp is None else xp + abs_x1 = xp.abs(x1) + return xp.where(x2 >= 0, abs_x1, -abs_x1) + + +# partial substitute for xp.sign, which does not cover the NaN special case +# that I need. (https://github.com/data-apis/array-api-compat/issues/136) +def xp_sign(x: Array, /, *, xp: ModuleType | None = None) -> Array: + xp = array_namespace(x) if xp is None else xp + if is_numpy(xp): # only NumPy implements the special cases correctly + return xp.sign(x) + sign = xp.zeros_like(x) + one = xp.asarray(1, dtype=x.dtype) + sign = xp.where(x > 0, one, sign) + sign = xp.where(x < 0, -one, sign) + sign = xp.where(xp.isnan(x), xp.nan*one, sign) + return sign + +# maybe use `scipy.linalg` if/when array API support is added +def xp_vector_norm(x: Array, /, *, + axis: int | tuple[int] | None = None, + keepdims: bool = False, + ord: int | float = 2, + xp: ModuleType | None = None) -> Array: + xp = array_namespace(x) if xp is None else xp + + if SCIPY_ARRAY_API: + # check for optional `linalg` extension + if hasattr(xp, 'linalg'): + return xp.linalg.vector_norm(x, axis=axis, keepdims=keepdims, ord=ord) + else: + if ord != 2: + raise ValueError( + "only the Euclidean norm (`ord=2`) is currently supported in " + "`xp_vector_norm` for backends not implementing the `linalg` " + "extension." + ) + # return (x @ x)**0.5 + # or to get the right behavior with nd, complex arrays + return xp.sum(xp.conj(x) * x, axis=axis, keepdims=keepdims)**0.5 + else: + # to maintain backwards compatibility + return np.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims) + + +def xp_ravel(x: Array, /, *, xp: ModuleType | None = None) -> Array: + # Equivalent of np.ravel written in terms of array API + # Even though it's one line, it comes up so often that it's worth having + # this function for readability + xp = array_namespace(x) if xp is None else xp + return xp.reshape(x, (-1,)) + + +def xp_real(x: Array, /, *, xp: ModuleType | None = None) -> Array: + # Convenience wrapper of xp.real that allows non-complex input; + # see data-apis/array-api#824 + xp = array_namespace(x) if xp is None else xp + return xp.real(x) if xp.isdtype(x.dtype, 'complex floating') else x + + +def xp_take_along_axis(arr: Array, + indices: Array, /, *, + axis: int = -1, + xp: ModuleType | None = None) -> Array: + # Dispatcher for np.take_along_axis for backends that support it; + # see data-apis/array-api/pull#816 + xp = array_namespace(arr) if xp is None else xp + if is_torch(xp): + return xp.take_along_dim(arr, indices, dim=axis) + elif is_array_api_strict(xp): + raise NotImplementedError("Array API standard does not define take_along_axis") + else: + return xp.take_along_axis(arr, indices, axis) + + +# utility to broadcast arrays and promote to common dtype +def xp_broadcast_promote(*args, ensure_writeable=False, force_floating=False, xp=None): + xp = array_namespace(*args) if xp is None else xp + + args = [(_asarray(arg, subok=True) if arg is not None else arg) for arg in args] + args_not_none = [arg for arg in args if arg is not None] + + # determine minimum dtype + default_float = xp.asarray(1.).dtype + dtypes = [arg.dtype for arg in args_not_none] + try: # follow library's prefered mixed promotion rules + dtype = xp.result_type(*dtypes) + if force_floating and xp.isdtype(dtype, 'integral'): + # If we were to add `default_float` before checking whether the result + # type is otherwise integral, we risk promotion from lower float. + dtype = xp.result_type(dtype, default_float) + except TypeError: # mixed type promotion isn't defined + float_dtypes = [dtype for dtype in dtypes + if not xp.isdtype(dtype, 'integral')] + if float_dtypes: + dtype = xp.result_type(*float_dtypes, default_float) + elif force_floating: + dtype = default_float + else: + dtype = xp.result_type(*dtypes) + + # determine result shape + shapes = {arg.shape for arg in args_not_none} + try: + shape = (np.broadcast_shapes(*shapes) if len(shapes) != 1 + else args_not_none[0].shape) + except ValueError as e: + message = "Array shapes are incompatible for broadcasting." + raise ValueError(message) from e + + out = [] + for arg in args: + if arg is None: + out.append(arg) + continue + + # broadcast only if needed + # Even if two arguments need broadcasting, this is faster than + # `broadcast_arrays`, especially since we've already determined `shape` + if arg.shape != shape: + kwargs = {'subok': True} if is_numpy(xp) else {} + arg = xp.broadcast_to(arg, shape, **kwargs) + + # convert dtype/copy only if needed + if (arg.dtype != dtype) or ensure_writeable: + arg = xp.astype(arg, dtype, copy=True) + out.append(arg) + + return out + + +def xp_float_to_complex(arr: Array, xp: ModuleType | None = None) -> Array: + xp = array_namespace(arr) if xp is None else xp + arr_dtype = arr.dtype + # The standard float dtypes are float32 and float64. + # Convert float32 to complex64, + # and float64 (and non-standard real dtypes) to complex128 + if xp.isdtype(arr_dtype, xp.float32): + arr = xp.astype(arr, xp.complex64) + elif xp.isdtype(arr_dtype, 'real floating'): + arr = xp.astype(arr, xp.complex128) + + return arr + + +def xp_default_dtype(xp): + """Query the namespace-dependent default floating-point dtype. + """ + if is_torch(xp): + # historically, we allow pytorch to keep its default of float32 + return xp.get_default_dtype() + else: + # we default to float64 + return xp.float64 diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api_no_0d.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api_no_0d.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b6fe1affd172eea620760a20f185f192d37b69 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_array_api_no_0d.py @@ -0,0 +1,103 @@ +""" +Extra testing functions that forbid 0d-input, see #21044 + +While the xp_assert_* functions generally aim to follow the conventions of the +underlying `xp` library, NumPy in particular is inconsistent in its handling +of scalars vs. 0d-arrays, see https://github.com/numpy/numpy/issues/24897. + +For example, this means that the following operations (as of v2.0.1) currently +return scalars, even though a 0d-array would often be more appropriate: + + import numpy as np + np.array(0) * 2 # scalar, not 0d array + - np.array(0) # scalar, not 0d-array + np.sin(np.array(0)) # scalar, not 0d array + np.mean([1, 2, 3]) # scalar, not 0d array + +Libraries like CuPy tend to return a 0d-array in scenarios like those above, +and even `xp.asarray(0)[()]` remains a 0d-array there. To deal with the reality +of the inconsistencies present in NumPy, as well as 20+ years of code on top, +the `xp_assert_*` functions here enforce consistency in the only way that +doesn't go against the tide, i.e. by forbidding 0d-arrays as the return type. + +However, when scalars are not generally the expected NumPy return type, +it remains preferable to use the assert functions from +the `scipy._lib._array_api` module, which have less surprising behaviour. +""" +from scipy._lib._array_api import array_namespace, is_numpy +from scipy._lib._array_api import (xp_assert_close as xp_assert_close_base, + xp_assert_equal as xp_assert_equal_base, + xp_assert_less as xp_assert_less_base) + +__all__: list[str] = [] + + +def _check_scalar(actual, desired, *, xp=None, **kwargs): + __tracebackhide__ = True # Hide traceback for py.test + + if xp is None: + xp = array_namespace(actual) + + # necessary to handle non-numpy scalars, e.g. bare `0.0` has no shape + desired = xp.asarray(desired) + + # Only NumPy distinguishes between scalars and arrays; + # shape check in xp_assert_* is sufficient except for shape == () + if not (is_numpy(xp) and desired.shape == ()): + return + + _msg = ("Result is a NumPy 0d-array. Many SciPy functions intend to follow " + "the convention of many NumPy functions, returning a scalar when a " + "0d-array would be correct. The specialized `xp_assert_*` functions " + "in the `scipy._lib._array_api_no_0d` module err on the side of " + "caution and do not accept 0d-arrays by default. If the correct " + "result may legitimately be a 0d-array, pass `check_0d=True`, " + "or use the `xp_assert_*` functions from `scipy._lib._array_api`.") + assert xp.isscalar(actual), _msg + + +def xp_assert_equal(actual, desired, *, check_0d=False, **kwargs): + # in contrast to xp_assert_equal_base, this defaults to check_0d=False, + # but will do an extra check in that case, which forbids 0d-arrays for `actual` + __tracebackhide__ = True # Hide traceback for py.test + + # array-ness (check_0d == True) is taken care of by the *_base functions + if not check_0d: + _check_scalar(actual, desired, **kwargs) + return xp_assert_equal_base(actual, desired, check_0d=check_0d, **kwargs) + + +def xp_assert_close(actual, desired, *, check_0d=False, **kwargs): + # as for xp_assert_equal + __tracebackhide__ = True + + if not check_0d: + _check_scalar(actual, desired, **kwargs) + return xp_assert_close_base(actual, desired, check_0d=check_0d, **kwargs) + + +def xp_assert_less(actual, desired, *, check_0d=False, **kwargs): + # as for xp_assert_equal + __tracebackhide__ = True + + if not check_0d: + _check_scalar(actual, desired, **kwargs) + return xp_assert_less_base(actual, desired, check_0d=check_0d, **kwargs) + + +def assert_array_almost_equal(actual, desired, decimal=6, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) + + +def assert_almost_equal(actual, desired, decimal=7, *args, **kwds): + """Backwards compatible replacement. In new code, use xp_assert_close instead. + """ + rtol, atol = 0, 1.5*10**(-decimal) + return xp_assert_close(actual, desired, + atol=atol, rtol=rtol, check_dtype=False, check_shape=False, + *args, **kwds) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py new file mode 100644 index 0000000000000000000000000000000000000000..bb562e4348f46dc1137afe3d3ce50f1149c85376 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_bunch.py @@ -0,0 +1,225 @@ +import sys as _sys +from keyword import iskeyword as _iskeyword + + +def _validate_names(typename, field_names, extra_field_names): + """ + Ensure that all the given names are valid Python identifiers that + do not start with '_'. Also check that there are no duplicates + among field_names + extra_field_names. + """ + for name in [typename] + field_names + extra_field_names: + if not isinstance(name, str): + raise TypeError('typename and all field names must be strings') + if not name.isidentifier(): + raise ValueError('typename and all field names must be valid ' + f'identifiers: {name!r}') + if _iskeyword(name): + raise ValueError('typename and all field names cannot be a ' + f'keyword: {name!r}') + + seen = set() + for name in field_names + extra_field_names: + if name.startswith('_'): + raise ValueError('Field names cannot start with an underscore: ' + f'{name!r}') + if name in seen: + raise ValueError(f'Duplicate field name: {name!r}') + seen.add(name) + + +# Note: This code is adapted from CPython:Lib/collections/__init__.py +def _make_tuple_bunch(typename, field_names, extra_field_names=None, + module=None): + """ + Create a namedtuple-like class with additional attributes. + + This function creates a subclass of tuple that acts like a namedtuple + and that has additional attributes. + + The additional attributes are listed in `extra_field_names`. The + values assigned to these attributes are not part of the tuple. + + The reason this function exists is to allow functions in SciPy + that currently return a tuple or a namedtuple to returned objects + that have additional attributes, while maintaining backwards + compatibility. + + This should only be used to enhance *existing* functions in SciPy. + New functions are free to create objects as return values without + having to maintain backwards compatibility with an old tuple or + namedtuple return value. + + Parameters + ---------- + typename : str + The name of the type. + field_names : list of str + List of names of the values to be stored in the tuple. These names + will also be attributes of instances, so the values in the tuple + can be accessed by indexing or as attributes. At least one name + is required. See the Notes for additional restrictions. + extra_field_names : list of str, optional + List of names of values that will be stored as attributes of the + object. See the notes for additional restrictions. + + Returns + ------- + cls : type + The new class. + + Notes + ----- + There are restrictions on the names that may be used in `field_names` + and `extra_field_names`: + + * The names must be unique--no duplicates allowed. + * The names must be valid Python identifiers, and must not begin with + an underscore. + * The names must not be Python keywords (e.g. 'def', 'and', etc., are + not allowed). + + Examples + -------- + >>> from scipy._lib._bunch import _make_tuple_bunch + + Create a class that acts like a namedtuple with length 2 (with field + names `x` and `y`) that will also have the attributes `w` and `beta`: + + >>> Result = _make_tuple_bunch('Result', ['x', 'y'], ['w', 'beta']) + + `Result` is the new class. We call it with keyword arguments to create + a new instance with given values. + + >>> result1 = Result(x=1, y=2, w=99, beta=0.5) + >>> result1 + Result(x=1, y=2, w=99, beta=0.5) + + `result1` acts like a tuple of length 2: + + >>> len(result1) + 2 + >>> result1[:] + (1, 2) + + The values assigned when the instance was created are available as + attributes: + + >>> result1.y + 2 + >>> result1.beta + 0.5 + """ + if len(field_names) == 0: + raise ValueError('field_names must contain at least one name') + + if extra_field_names is None: + extra_field_names = [] + _validate_names(typename, field_names, extra_field_names) + + typename = _sys.intern(str(typename)) + field_names = tuple(map(_sys.intern, field_names)) + extra_field_names = tuple(map(_sys.intern, extra_field_names)) + + all_names = field_names + extra_field_names + arg_list = ', '.join(field_names) + full_list = ', '.join(all_names) + repr_fmt = ''.join(('(', + ', '.join(f'{name}=%({name})r' for name in all_names), + ')')) + tuple_new = tuple.__new__ + _dict, _tuple, _zip = dict, tuple, zip + + # Create all the named tuple methods to be added to the class namespace + + s = f"""\ +def __new__(_cls, {arg_list}, **extra_fields): + return _tuple_new(_cls, ({arg_list},)) + +def __init__(self, {arg_list}, **extra_fields): + for key in self._extra_fields: + if key not in extra_fields: + raise TypeError("missing keyword argument '%s'" % (key,)) + for key, val in extra_fields.items(): + if key not in self._extra_fields: + raise TypeError("unexpected keyword argument '%s'" % (key,)) + self.__dict__[key] = val + +def __setattr__(self, key, val): + if key in {repr(field_names)}: + raise AttributeError("can't set attribute %r of class %r" + % (key, self.__class__.__name__)) + else: + self.__dict__[key] = val +""" + del arg_list + namespace = {'_tuple_new': tuple_new, + '__builtins__': dict(TypeError=TypeError, + AttributeError=AttributeError), + '__name__': f'namedtuple_{typename}'} + exec(s, namespace) + __new__ = namespace['__new__'] + __new__.__doc__ = f'Create new instance of {typename}({full_list})' + __init__ = namespace['__init__'] + __init__.__doc__ = f'Instantiate instance of {typename}({full_list})' + __setattr__ = namespace['__setattr__'] + + def __repr__(self): + 'Return a nicely formatted representation string' + return self.__class__.__name__ + repr_fmt % self._asdict() + + def _asdict(self): + 'Return a new dict which maps field names to their values.' + out = _dict(_zip(self._fields, self)) + out.update(self.__dict__) + return out + + def __getnewargs_ex__(self): + 'Return self as a plain tuple. Used by copy and pickle.' + return _tuple(self), self.__dict__ + + # Modify function metadata to help with introspection and debugging + for method in (__new__, __repr__, _asdict, __getnewargs_ex__): + method.__qualname__ = f'{typename}.{method.__name__}' + + # Build-up the class namespace dictionary + # and use type() to build the result class + class_namespace = { + '__doc__': f'{typename}({full_list})', + '_fields': field_names, + '__new__': __new__, + '__init__': __init__, + '__repr__': __repr__, + '__setattr__': __setattr__, + '_asdict': _asdict, + '_extra_fields': extra_field_names, + '__getnewargs_ex__': __getnewargs_ex__, + } + for index, name in enumerate(field_names): + + def _get(self, index=index): + return self[index] + class_namespace[name] = property(_get) + for name in extra_field_names: + + def _get(self, name=name): + return self.__dict__[name] + class_namespace[name] = property(_get) + + result = type(typename, (tuple,), class_namespace) + + # For pickling to work, the __module__ variable needs to be set to the + # frame where the named tuple is created. Bypass this step in environments + # where sys._getframe is not defined (Jython for example) or sys._getframe + # is not defined for arguments greater than 0 (IronPython), or where the + # user has specified a particular module. + if module is None: + try: + module = _sys._getframe(1).f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + pass + if module is not None: + result.__module__ = module + __new__.__module__ = module + + return result diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_ccallback.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_ccallback.py new file mode 100644 index 0000000000000000000000000000000000000000..1980d06f5489e6633fb611c35bfb56903bd63e7f --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_ccallback.py @@ -0,0 +1,251 @@ +from . import _ccallback_c + +import ctypes + +PyCFuncPtr = ctypes.CFUNCTYPE(ctypes.c_void_p).__bases__[0] + +ffi = None + +class CData: + pass + +def _import_cffi(): + global ffi, CData + + if ffi is not None: + return + + try: + import cffi + ffi = cffi.FFI() + CData = ffi.CData + except ImportError: + ffi = False + + +class LowLevelCallable(tuple): + """ + Low-level callback function. + + Some functions in SciPy take as arguments callback functions, which + can either be python callables or low-level compiled functions. Using + compiled callback functions can improve performance somewhat by + avoiding wrapping data in Python objects. + + Such low-level functions in SciPy are wrapped in `LowLevelCallable` + objects, which can be constructed from function pointers obtained from + ctypes, cffi, Cython, or contained in Python `PyCapsule` objects. + + .. seealso:: + + Functions accepting low-level callables: + + `scipy.integrate.quad`, `scipy.ndimage.generic_filter`, + `scipy.ndimage.generic_filter1d`, `scipy.ndimage.geometric_transform` + + Usage examples: + + :ref:`ndimage-ccallbacks`, :ref:`quad-callbacks` + + Parameters + ---------- + function : {PyCapsule, ctypes function pointer, cffi function pointer} + Low-level callback function. + user_data : {PyCapsule, ctypes void pointer, cffi void pointer} + User data to pass on to the callback function. + signature : str, optional + Signature of the function. If omitted, determined from *function*, + if possible. + + Attributes + ---------- + function + Callback function given. + user_data + User data given. + signature + Signature of the function. + + Methods + ------- + from_cython + Class method for constructing callables from Cython C-exported + functions. + + Notes + ----- + The argument ``function`` can be one of: + + - PyCapsule, whose name contains the C function signature + - ctypes function pointer + - cffi function pointer + + The signature of the low-level callback must match one of those expected + by the routine it is passed to. + + If constructing low-level functions from a PyCapsule, the name of the + capsule must be the corresponding signature, in the format:: + + return_type (arg1_type, arg2_type, ...) + + For example:: + + "void (double)" + "double (double, int *, void *)" + + The context of a PyCapsule passed in as ``function`` is used as ``user_data``, + if an explicit value for ``user_data`` was not given. + + """ + + # Make the class immutable + __slots__ = () + + def __new__(cls, function, user_data=None, signature=None): + # We need to hold a reference to the function & user data, + # to prevent them going out of scope + item = cls._parse_callback(function, user_data, signature) + return tuple.__new__(cls, (item, function, user_data)) + + def __repr__(self): + return f"LowLevelCallable({self.function!r}, {self.user_data!r})" + + @property + def function(self): + return tuple.__getitem__(self, 1) + + @property + def user_data(self): + return tuple.__getitem__(self, 2) + + @property + def signature(self): + return _ccallback_c.get_capsule_signature(tuple.__getitem__(self, 0)) + + def __getitem__(self, idx): + raise ValueError() + + @classmethod + def from_cython(cls, module, name, user_data=None, signature=None): + """ + Create a low-level callback function from an exported Cython function. + + Parameters + ---------- + module : module + Cython module where the exported function resides + name : str + Name of the exported function + user_data : {PyCapsule, ctypes void pointer, cffi void pointer}, optional + User data to pass on to the callback function. + signature : str, optional + Signature of the function. If omitted, determined from *function*. + + """ + try: + function = module.__pyx_capi__[name] + except AttributeError as e: + message = "Given module is not a Cython module with __pyx_capi__ attribute" + raise ValueError(message) from e + except KeyError as e: + message = f"No function {name!r} found in __pyx_capi__ of the module" + raise ValueError(message) from e + return cls(function, user_data, signature) + + @classmethod + def _parse_callback(cls, obj, user_data=None, signature=None): + _import_cffi() + + if isinstance(obj, LowLevelCallable): + func = tuple.__getitem__(obj, 0) + elif isinstance(obj, PyCFuncPtr): + func, signature = _get_ctypes_func(obj, signature) + elif isinstance(obj, CData): + func, signature = _get_cffi_func(obj, signature) + elif _ccallback_c.check_capsule(obj): + func = obj + else: + raise ValueError("Given input is not a callable or a " + "low-level callable (pycapsule/ctypes/cffi)") + + if isinstance(user_data, ctypes.c_void_p): + context = _get_ctypes_data(user_data) + elif isinstance(user_data, CData): + context = _get_cffi_data(user_data) + elif user_data is None: + context = 0 + elif _ccallback_c.check_capsule(user_data): + context = user_data + else: + raise ValueError("Given user data is not a valid " + "low-level void* pointer (pycapsule/ctypes/cffi)") + + return _ccallback_c.get_raw_capsule(func, signature, context) + + +# +# ctypes helpers +# + +def _get_ctypes_func(func, signature=None): + # Get function pointer + func_ptr = ctypes.cast(func, ctypes.c_void_p).value + + # Construct function signature + if signature is None: + signature = _typename_from_ctypes(func.restype) + " (" + for j, arg in enumerate(func.argtypes): + if j == 0: + signature += _typename_from_ctypes(arg) + else: + signature += ", " + _typename_from_ctypes(arg) + signature += ")" + + return func_ptr, signature + + +def _typename_from_ctypes(item): + if item is None: + return "void" + elif item is ctypes.c_void_p: + return "void *" + + name = item.__name__ + + pointer_level = 0 + while name.startswith("LP_"): + pointer_level += 1 + name = name[3:] + + if name.startswith('c_'): + name = name[2:] + + if pointer_level > 0: + name += " " + "*"*pointer_level + + return name + + +def _get_ctypes_data(data): + # Get voidp pointer + return ctypes.cast(data, ctypes.c_void_p).value + + +# +# CFFI helpers +# + +def _get_cffi_func(func, signature=None): + # Get function pointer + func_ptr = ffi.cast('uintptr_t', func) + + # Get signature + if signature is None: + signature = ffi.getctype(ffi.typeof(func)).replace('(*)', ' ') + + return func_ptr, signature + + +def _get_cffi_data(data): + # Get pointer + return ffi.cast('uintptr_t', data) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py new file mode 100644 index 0000000000000000000000000000000000000000..683c5c8e518705e710212dafc01363f92a2f947d --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_disjoint_set.py @@ -0,0 +1,254 @@ +""" +Disjoint set data structure +""" + + +class DisjointSet: + """ Disjoint set data structure for incremental connectivity queries. + + .. versionadded:: 1.6.0 + + Attributes + ---------- + n_subsets : int + The number of subsets. + + Methods + ------- + add + merge + connected + subset + subset_size + subsets + __getitem__ + + Notes + ----- + This class implements the disjoint set [1]_, also known as the *union-find* + or *merge-find* data structure. The *find* operation (implemented in + `__getitem__`) implements the *path halving* variant. The *merge* method + implements the *merge by size* variant. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Disjoint-set_data_structure + + Examples + -------- + >>> from scipy.cluster.hierarchy import DisjointSet + + Initialize a disjoint set: + + >>> disjoint_set = DisjointSet([1, 2, 3, 'a', 'b']) + + Merge some subsets: + + >>> disjoint_set.merge(1, 2) + True + >>> disjoint_set.merge(3, 'a') + True + >>> disjoint_set.merge('a', 'b') + True + >>> disjoint_set.merge('b', 'b') + False + + Find root elements: + + >>> disjoint_set[2] + 1 + >>> disjoint_set['b'] + 3 + + Test connectivity: + + >>> disjoint_set.connected(1, 2) + True + >>> disjoint_set.connected(1, 'b') + False + + List elements in disjoint set: + + >>> list(disjoint_set) + [1, 2, 3, 'a', 'b'] + + Get the subset containing 'a': + + >>> disjoint_set.subset('a') + {'a', 3, 'b'} + + Get the size of the subset containing 'a' (without actually instantiating + the subset): + + >>> disjoint_set.subset_size('a') + 3 + + Get all subsets in the disjoint set: + + >>> disjoint_set.subsets() + [{1, 2}, {'a', 3, 'b'}] + """ + def __init__(self, elements=None): + self.n_subsets = 0 + self._sizes = {} + self._parents = {} + # _nbrs is a circular linked list which links connected elements. + self._nbrs = {} + # _indices tracks the element insertion order in `__iter__`. + self._indices = {} + if elements is not None: + for x in elements: + self.add(x) + + def __iter__(self): + """Returns an iterator of the elements in the disjoint set. + + Elements are ordered by insertion order. + """ + return iter(self._indices) + + def __len__(self): + return len(self._indices) + + def __contains__(self, x): + return x in self._indices + + def __getitem__(self, x): + """Find the root element of `x`. + + Parameters + ---------- + x : hashable object + Input element. + + Returns + ------- + root : hashable object + Root element of `x`. + """ + if x not in self._indices: + raise KeyError(x) + + # find by "path halving" + parents = self._parents + while self._indices[x] != self._indices[parents[x]]: + parents[x] = parents[parents[x]] + x = parents[x] + return x + + def add(self, x): + """Add element `x` to disjoint set + """ + if x in self._indices: + return + + self._sizes[x] = 1 + self._parents[x] = x + self._nbrs[x] = x + self._indices[x] = len(self._indices) + self.n_subsets += 1 + + def merge(self, x, y): + """Merge the subsets of `x` and `y`. + + The smaller subset (the child) is merged into the larger subset (the + parent). If the subsets are of equal size, the root element which was + first inserted into the disjoint set is selected as the parent. + + Parameters + ---------- + x, y : hashable object + Elements to merge. + + Returns + ------- + merged : bool + True if `x` and `y` were in disjoint sets, False otherwise. + """ + xr = self[x] + yr = self[y] + if self._indices[xr] == self._indices[yr]: + return False + + sizes = self._sizes + if (sizes[xr], self._indices[yr]) < (sizes[yr], self._indices[xr]): + xr, yr = yr, xr + self._parents[yr] = xr + self._sizes[xr] += self._sizes[yr] + self._nbrs[xr], self._nbrs[yr] = self._nbrs[yr], self._nbrs[xr] + self.n_subsets -= 1 + return True + + def connected(self, x, y): + """Test whether `x` and `y` are in the same subset. + + Parameters + ---------- + x, y : hashable object + Elements to test. + + Returns + ------- + result : bool + True if `x` and `y` are in the same set, False otherwise. + """ + return self._indices[self[x]] == self._indices[self[y]] + + def subset(self, x): + """Get the subset containing `x`. + + Parameters + ---------- + x : hashable object + Input element. + + Returns + ------- + result : set + Subset containing `x`. + """ + if x not in self._indices: + raise KeyError(x) + + result = [x] + nxt = self._nbrs[x] + while self._indices[nxt] != self._indices[x]: + result.append(nxt) + nxt = self._nbrs[nxt] + return set(result) + + def subset_size(self, x): + """Get the size of the subset containing `x`. + + Note that this method is faster than ``len(self.subset(x))`` because + the size is directly read off an internal field, without the need to + instantiate the full subset. + + Parameters + ---------- + x : hashable object + Input element. + + Returns + ------- + result : int + Size of the subset containing `x`. + """ + return self._sizes[self[x]] + + def subsets(self): + """Get all the subsets in the disjoint set. + + Returns + ------- + result : list + Subsets in the disjoint set. + """ + result = [] + visited = set() + for x in self: + if x not in visited: + xset = self.subset(x) + visited.update(xset) + result.append(xset) + return result diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py new file mode 100644 index 0000000000000000000000000000000000000000..f345539efe76b9f9439957a78e5ebdc1ec2bf517 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_docscrape.py @@ -0,0 +1,761 @@ +# copied from numpydoc/docscrape.py, commit 97a6026508e0dd5382865672e9563a72cc113bd2 +"""Extract reference documentation from the NumPy source tree.""" + +import copy +import inspect +import pydoc +import re +import sys +import textwrap +from collections import namedtuple +from collections.abc import Callable, Mapping +from functools import cached_property +from warnings import warn + + +def strip_blank_lines(l): + "Remove leading and trailing blank lines from a list of lines" + while l and not l[0].strip(): + del l[0] + while l and not l[-1].strip(): + del l[-1] + return l + + +class Reader: + """A line-based string reader.""" + + def __init__(self, data): + """ + Parameters + ---------- + data : str + String with lines separated by '\\n'. + + """ + if isinstance(data, list): + self._str = data + else: + self._str = data.split("\n") # store string as list of lines + + self.reset() + + def __getitem__(self, n): + return self._str[n] + + def reset(self): + self._l = 0 # current line nr + + def read(self): + if not self.eof(): + out = self[self._l] + self._l += 1 + return out + else: + return "" + + def seek_next_non_empty_line(self): + for l in self[self._l :]: + if l.strip(): + break + else: + self._l += 1 + + def eof(self): + return self._l >= len(self._str) + + def read_to_condition(self, condition_func): + start = self._l + for line in self[start:]: + if condition_func(line): + return self[start : self._l] + self._l += 1 + if self.eof(): + return self[start : self._l + 1] + return [] + + def read_to_next_empty_line(self): + self.seek_next_non_empty_line() + + def is_empty(line): + return not line.strip() + + return self.read_to_condition(is_empty) + + def read_to_next_unindented_line(self): + def is_unindented(line): + return line.strip() and (len(line.lstrip()) == len(line)) + + return self.read_to_condition(is_unindented) + + def peek(self, n=0): + if self._l + n < len(self._str): + return self[self._l + n] + else: + return "" + + def is_empty(self): + return not "".join(self._str).strip() + + +class ParseError(Exception): + def __str__(self): + message = self.args[0] + if hasattr(self, "docstring"): + message = f"{message} in {self.docstring!r}" + return message + + +Parameter = namedtuple("Parameter", ["name", "type", "desc"]) + + +class NumpyDocString(Mapping): + """Parses a numpydoc string to an abstract representation + + Instances define a mapping from section title to structured data. + + """ + + sections = { + "Signature": "", + "Summary": [""], + "Extended Summary": [], + "Parameters": [], + "Attributes": [], + "Methods": [], + "Returns": [], + "Yields": [], + "Receives": [], + "Other Parameters": [], + "Raises": [], + "Warns": [], + "Warnings": [], + "See Also": [], + "Notes": [], + "References": "", + "Examples": "", + "index": {}, + } + + def __init__(self, docstring, config=None): + orig_docstring = docstring + docstring = textwrap.dedent(docstring).split("\n") + + self._doc = Reader(docstring) + self._parsed_data = copy.deepcopy(self.sections) + + try: + self._parse() + except ParseError as e: + e.docstring = orig_docstring + raise + + def __getitem__(self, key): + return self._parsed_data[key] + + def __setitem__(self, key, val): + if key not in self._parsed_data: + self._error_location(f"Unknown section {key}", error=False) + else: + self._parsed_data[key] = val + + def __iter__(self): + return iter(self._parsed_data) + + def __len__(self): + return len(self._parsed_data) + + def _is_at_section(self): + self._doc.seek_next_non_empty_line() + + if self._doc.eof(): + return False + + l1 = self._doc.peek().strip() # e.g. Parameters + + if l1.startswith(".. index::"): + return True + + l2 = self._doc.peek(1).strip() # ---------- or ========== + if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1): + snip = "\n".join(self._doc._str[:2]) + "..." + self._error_location( + f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}", + error=False, + ) + return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1)) + + def _strip(self, doc): + i = 0 + j = 0 + for i, line in enumerate(doc): + if line.strip(): + break + + for j, line in enumerate(doc[::-1]): + if line.strip(): + break + + return doc[i : len(doc) - j] + + def _read_to_next_section(self): + section = self._doc.read_to_next_empty_line() + + while not self._is_at_section() and not self._doc.eof(): + if not self._doc.peek(-1).strip(): # previous line was empty + section += [""] + + section += self._doc.read_to_next_empty_line() + + return section + + def _read_sections(self): + while not self._doc.eof(): + data = self._read_to_next_section() + name = data[0].strip() + + if name.startswith(".."): # index section + yield name, data[1:] + elif len(data) < 2: + yield StopIteration + else: + yield name, self._strip(data[2:]) + + def _parse_param_list(self, content, single_element_is_type=False): + content = dedent_lines(content) + r = Reader(content) + params = [] + while not r.eof(): + header = r.read().strip() + if " : " in header: + arg_name, arg_type = header.split(" : ", maxsplit=1) + else: + # NOTE: param line with single element should never have a + # a " :" before the description line, so this should probably + # warn. + if header.endswith(" :"): + header = header[:-2] + if single_element_is_type: + arg_name, arg_type = "", header + else: + arg_name, arg_type = header, "" + + desc = r.read_to_next_unindented_line() + desc = dedent_lines(desc) + desc = strip_blank_lines(desc) + + params.append(Parameter(arg_name, arg_type, desc)) + + return params + + # See also supports the following formats. + # + # + # SPACE* COLON SPACE+ SPACE* + # ( COMMA SPACE+ )+ (COMMA | PERIOD)? SPACE* + # ( COMMA SPACE+ )* SPACE* COLON SPACE+ SPACE* + + # is one of + # + # COLON COLON BACKTICK BACKTICK + # where + # is a legal function name, and + # is any nonempty sequence of word characters. + # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j` + # is a string describing the function. + + _role = r":(?P(py:)?\w+):" + _funcbacktick = r"`(?P(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`" + _funcplain = r"(?P[a-zA-Z0-9_\.-]+)" + _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")" + _funcnamenext = _funcname.replace("role", "rolenext") + _funcnamenext = _funcnamenext.replace("name", "namenext") + _description = r"(?P\s*:(\s+(?P\S+.*))?)?\s*$" + _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*") + _line_rgx = re.compile( + r"^\s*" + + r"(?P" + + _funcname # group for all function names + + r"(?P([,]\s+" + + _funcnamenext + + r")*)" + + r")" + + r"(?P[,\.])?" # end of "allfuncs" + + _description # Some function lists have a trailing comma (or period) '\s*' + ) + + # Empty elements are replaced with '..' + empty_description = ".." + + def _parse_see_also(self, content): + """ + func_name : Descriptive text + continued text + another_func_name : Descriptive text + func_name1, func_name2, :meth:`func_name`, func_name3 + + """ + + content = dedent_lines(content) + + items = [] + + def parse_item_name(text): + """Match ':role:`name`' or 'name'.""" + m = self._func_rgx.match(text) + if not m: + self._error_location(f"Error parsing See Also entry {line!r}") + role = m.group("role") + name = m.group("name") if role else m.group("name2") + return name, role, m.end() + + rest = [] + for line in content: + if not line.strip(): + continue + + line_match = self._line_rgx.match(line) + description = None + if line_match: + description = line_match.group("desc") + if line_match.group("trailing") and description: + self._error_location( + "Unexpected comma or period after function list at index %d of " + 'line "%s"' % (line_match.end("trailing"), line), + error=False, + ) + if not description and line.startswith(" "): + rest.append(line.strip()) + elif line_match: + funcs = [] + text = line_match.group("allfuncs") + while True: + if not text.strip(): + break + name, role, match_end = parse_item_name(text) + funcs.append((name, role)) + text = text[match_end:].strip() + if text and text[0] == ",": + text = text[1:].strip() + rest = list(filter(None, [description])) + items.append((funcs, rest)) + else: + self._error_location(f"Error parsing See Also entry {line!r}") + return items + + def _parse_index(self, section, content): + """ + .. index:: default + :refguide: something, else, and more + + """ + + def strip_each_in(lst): + return [s.strip() for s in lst] + + out = {} + section = section.split("::") + if len(section) > 1: + out["default"] = strip_each_in(section[1].split(","))[0] + for line in content: + line = line.split(":") + if len(line) > 2: + out[line[1]] = strip_each_in(line[2].split(",")) + return out + + def _parse_summary(self): + """Grab signature (if given) and summary""" + if self._is_at_section(): + return + + # If several signatures present, take the last one + while True: + summary = self._doc.read_to_next_empty_line() + summary_str = " ".join([s.strip() for s in summary]).strip() + compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$") + if compiled.match(summary_str): + self["Signature"] = summary_str + if not self._is_at_section(): + continue + break + + if summary is not None: + self["Summary"] = summary + + if not self._is_at_section(): + self["Extended Summary"] = self._read_to_next_section() + + def _parse(self): + self._doc.reset() + self._parse_summary() + + sections = list(self._read_sections()) + section_names = {section for section, content in sections} + + has_yields = "Yields" in section_names + # We could do more tests, but we are not. Arbitrarily. + if not has_yields and "Receives" in section_names: + msg = "Docstring contains a Receives section but not Yields." + raise ValueError(msg) + + for section, content in sections: + if not section.startswith(".."): + section = (s.capitalize() for s in section.split(" ")) + section = " ".join(section) + if self.get(section): + self._error_location( + "The section %s appears twice in %s" + % (section, "\n".join(self._doc._str)) + ) + + if section in ("Parameters", "Other Parameters", "Attributes", "Methods"): + self[section] = self._parse_param_list(content) + elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"): + self[section] = self._parse_param_list( + content, single_element_is_type=True + ) + elif section.startswith(".. index::"): + self["index"] = self._parse_index(section, content) + elif section == "See Also": + self["See Also"] = self._parse_see_also(content) + else: + self[section] = content + + @property + def _obj(self): + if hasattr(self, "_cls"): + return self._cls + elif hasattr(self, "_f"): + return self._f + return None + + def _error_location(self, msg, error=True): + if self._obj is not None: + # we know where the docs came from: + try: + filename = inspect.getsourcefile(self._obj) + except TypeError: + filename = None + # Make UserWarning more descriptive via object introspection. + # Skip if introspection fails + name = getattr(self._obj, "__name__", None) + if name is None: + name = getattr(getattr(self._obj, "__class__", None), "__name__", None) + if name is not None: + msg += f" in the docstring of {name}" + msg += f" in {filename}." if filename else "" + if error: + raise ValueError(msg) + else: + warn(msg, stacklevel=3) + + # string conversion routines + + def _str_header(self, name, symbol="-"): + return [name, len(name) * symbol] + + def _str_indent(self, doc, indent=4): + return [" " * indent + line for line in doc] + + def _str_signature(self): + if self["Signature"]: + return [self["Signature"].replace("*", r"\*")] + [""] + return [""] + + def _str_summary(self): + if self["Summary"]: + return self["Summary"] + [""] + return [] + + def _str_extended_summary(self): + if self["Extended Summary"]: + return self["Extended Summary"] + [""] + return [] + + def _str_param_list(self, name): + out = [] + if self[name]: + out += self._str_header(name) + for param in self[name]: + parts = [] + if param.name: + parts.append(param.name) + if param.type: + parts.append(param.type) + out += [" : ".join(parts)] + if param.desc and "".join(param.desc).strip(): + out += self._str_indent(param.desc) + out += [""] + return out + + def _str_section(self, name): + out = [] + if self[name]: + out += self._str_header(name) + out += self[name] + out += [""] + return out + + def _str_see_also(self, func_role): + if not self["See Also"]: + return [] + out = [] + out += self._str_header("See Also") + out += [""] + last_had_desc = True + for funcs, desc in self["See Also"]: + assert isinstance(funcs, list) + links = [] + for func, role in funcs: + if role: + link = f":{role}:`{func}`" + elif func_role: + link = f":{func_role}:`{func}`" + else: + link = f"`{func}`_" + links.append(link) + link = ", ".join(links) + out += [link] + if desc: + out += self._str_indent([" ".join(desc)]) + last_had_desc = True + else: + last_had_desc = False + out += self._str_indent([self.empty_description]) + + if last_had_desc: + out += [""] + out += [""] + return out + + def _str_index(self): + idx = self["index"] + out = [] + output_index = False + default_index = idx.get("default", "") + if default_index: + output_index = True + out += [f".. index:: {default_index}"] + for section, references in idx.items(): + if section == "default": + continue + output_index = True + out += [f" :{section}: {', '.join(references)}"] + if output_index: + return out + return "" + + def __str__(self, func_role=""): + out = [] + out += self._str_signature() + out += self._str_summary() + out += self._str_extended_summary() + out += self._str_param_list("Parameters") + for param_list in ("Attributes", "Methods"): + out += self._str_param_list(param_list) + for param_list in ( + "Returns", + "Yields", + "Receives", + "Other Parameters", + "Raises", + "Warns", + ): + out += self._str_param_list(param_list) + out += self._str_section("Warnings") + out += self._str_see_also(func_role) + for s in ("Notes", "References", "Examples"): + out += self._str_section(s) + out += self._str_index() + return "\n".join(out) + + +def dedent_lines(lines): + """Deindent a list of lines maximally""" + return textwrap.dedent("\n".join(lines)).split("\n") + + +class FunctionDoc(NumpyDocString): + def __init__(self, func, role="func", doc=None, config=None): + self._f = func + self._role = role # e.g. "func" or "meth" + + if doc is None: + if func is None: + raise ValueError("No function or docstring given") + doc = inspect.getdoc(func) or "" + if config is None: + config = {} + NumpyDocString.__init__(self, doc, config) + + def get_func(self): + func_name = getattr(self._f, "__name__", self.__class__.__name__) + if inspect.isclass(self._f): + func = getattr(self._f, "__call__", self._f.__init__) + else: + func = self._f + return func, func_name + + def __str__(self): + out = "" + + func, func_name = self.get_func() + + roles = {"func": "function", "meth": "method"} + + if self._role: + if self._role not in roles: + print(f"Warning: invalid role {self._role}") + out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n" + + out += super().__str__(func_role=self._role) + return out + + +class ObjDoc(NumpyDocString): + def __init__(self, obj, doc=None, config=None): + self._f = obj + if config is None: + config = {} + NumpyDocString.__init__(self, doc, config=config) + + +class ClassDoc(NumpyDocString): + extra_public_methods = ["__call__"] + + def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None): + if not inspect.isclass(cls) and cls is not None: + raise ValueError(f"Expected a class or None, but got {cls!r}") + self._cls = cls + + if "sphinx" in sys.modules: + from sphinx.ext.autodoc import ALL + else: + ALL = object() + + if config is None: + config = {} + self.show_inherited_members = config.get("show_inherited_class_members", True) + + if modulename and not modulename.endswith("."): + modulename += "." + self._mod = modulename + + if doc is None: + if cls is None: + raise ValueError("No class or documentation string given") + doc = pydoc.getdoc(cls) + + NumpyDocString.__init__(self, doc) + + _members = config.get("members", []) + if _members is ALL: + _members = None + _exclude = config.get("exclude-members", []) + + if config.get("show_class_members", True) and _exclude is not ALL: + + def splitlines_x(s): + if not s: + return [] + else: + return s.splitlines() + + for field, items in [ + ("Methods", self.methods), + ("Attributes", self.properties), + ]: + if not self[field]: + doc_list = [] + for name in sorted(items): + if name in _exclude or (_members and name not in _members): + continue + try: + doc_item = pydoc.getdoc(getattr(self._cls, name)) + doc_list.append(Parameter(name, "", splitlines_x(doc_item))) + except AttributeError: + pass # method doesn't exist + self[field] = doc_list + + @property + def methods(self): + if self._cls is None: + return [] + return [ + name + for name, func in inspect.getmembers(self._cls) + if ( + (not name.startswith("_") or name in self.extra_public_methods) + and isinstance(func, Callable) + and self._is_show_member(name) + ) + ] + + @property + def properties(self): + if self._cls is None: + return [] + return [ + name + for name, func in inspect.getmembers(self._cls) + if ( + not name.startswith("_") + and not self._should_skip_member(name, self._cls) + and ( + func is None + or isinstance(func, (property, cached_property)) + or inspect.isdatadescriptor(func) + ) + and self._is_show_member(name) + ) + ] + + @staticmethod + def _should_skip_member(name, klass): + return ( + # Namedtuples should skip everything in their ._fields as the + # docstrings for each of the members is: "Alias for field number X" + issubclass(klass, tuple) + and hasattr(klass, "_asdict") + and hasattr(klass, "_fields") + and name in klass._fields + ) + + def _is_show_member(self, name): + return ( + # show all class members + self.show_inherited_members + # or class member is not inherited + or name in self._cls.__dict__ + ) + + +def get_doc_object( + obj, + what=None, + doc=None, + config=None, + class_doc=ClassDoc, + func_doc=FunctionDoc, + obj_doc=ObjDoc, +): + if what is None: + if inspect.isclass(obj): + what = "class" + elif inspect.ismodule(obj): + what = "module" + elif isinstance(obj, Callable): + what = "function" + else: + what = "object" + if config is None: + config = {} + + if what == "class": + return class_doc(obj, func_doc=func_doc, doc=doc, config=config) + elif what in ("function", "method"): + return func_doc(obj, doc=doc, config=config) + else: + if doc is None: + doc = pydoc.getdoc(obj) + return obj_doc(obj, doc, config=config) \ No newline at end of file diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py new file mode 100644 index 0000000000000000000000000000000000000000..05efe86d31c137e7d780ebc438ec587df4e911dd --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_elementwise_iterative_method.py @@ -0,0 +1,357 @@ +# `_elementwise_iterative_method.py` includes tools for writing functions that +# - are vectorized to work elementwise on arrays, +# - implement non-trivial, iterative algorithms with a callback interface, and +# - return rich objects with iteration count, termination status, etc. +# +# Examples include: +# `scipy.optimize._chandrupatla._chandrupatla for scalar rootfinding, +# `scipy.optimize._chandrupatla._chandrupatla_minimize for scalar minimization, +# `scipy.optimize._differentiate._differentiate for numerical differentiation, +# `scipy.optimize._bracket._bracket_root for finding rootfinding brackets, +# `scipy.optimize._bracket._bracket_minimize for finding minimization brackets, +# `scipy.integrate._tanhsinh._tanhsinh` for numerical quadrature, +# `scipy.differentiate.derivative` for finite difference based differentiation. + +import math +import numpy as np +from ._util import _RichResult, _call_callback_maybe_halt +from ._array_api import array_namespace, xp_size + +_ESIGNERR = -1 +_ECONVERR = -2 +_EVALUEERR = -3 +_ECALLBACK = -4 +_EINPUTERR = -5 +_ECONVERGED = 0 +_EINPROGRESS = 1 + +def _initialize(func, xs, args, complex_ok=False, preserve_shape=None, xp=None): + """Initialize abscissa, function, and args arrays for elementwise function + + Parameters + ---------- + func : callable + An elementwise function with signature + + func(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with ``x``. + xs : tuple of arrays + Finite real abscissa arrays. Must be broadcastable. + args : tuple, optional + Additional positional arguments to be passed to `func`. + preserve_shape : bool, default:False + When ``preserve_shape=False`` (default), `func` may be passed + arguments of any shape; `_scalar_optimization_loop` is permitted + to reshape and compress arguments at will. When + ``preserve_shape=False``, arguments passed to `func` must have shape + `shape` or ``shape + (n,)``, where ``n`` is any integer. + xp : namespace + Namespace of array arguments in `xs`. + + Returns + ------- + xs, fs, args : tuple of arrays + Broadcasted, writeable, 1D abscissa and function value arrays (or + NumPy floats, if appropriate). The dtypes of the `xs` and `fs` are + `xfat`; the dtype of the `args` are unchanged. + shape : tuple of ints + Original shape of broadcasted arrays. + xfat : NumPy dtype + Result dtype of abscissae, function values, and args determined using + `np.result_type`, except integer types are promoted to `np.float64`. + + Raises + ------ + ValueError + If the result dtype is not that of a real scalar + + Notes + ----- + Useful for initializing the input of SciPy functions that accept + an elementwise callable, abscissae, and arguments; e.g. + `scipy.optimize._chandrupatla`. + """ + nx = len(xs) + xp = array_namespace(*xs) if xp is None else xp + + # Try to preserve `dtype`, but we need to ensure that the arguments are at + # least floats before passing them into the function; integers can overflow + # and cause failure. + # There might be benefit to combining the `xs` into a single array and + # calling `func` once on the combined array. For now, keep them separate. + xas = xp.broadcast_arrays(*xs, *args) # broadcast and rename + xat = xp.result_type(*[xa.dtype for xa in xas]) + xat = xp.asarray(1.).dtype if xp.isdtype(xat, "integral") else xat + xs, args = xas[:nx], xas[nx:] + xs = [xp.asarray(x, dtype=xat) for x in xs] # use copy=False when implemented + fs = [xp.asarray(func(x, *args)) for x in xs] + shape = xs[0].shape + fshape = fs[0].shape + + if preserve_shape: + # bind original shape/func now to avoid late-binding gotcha + def func(x, *args, shape=shape, func=func, **kwargs): + i = (0,)*(len(fshape) - len(shape)) + return func(x[i], *args, **kwargs) + shape = np.broadcast_shapes(fshape, shape) # just shapes; use of NumPy OK + xs = [xp.broadcast_to(x, shape) for x in xs] + args = [xp.broadcast_to(arg, shape) for arg in args] + + message = ("The shape of the array returned by `func` must be the same as " + "the broadcasted shape of `x` and all other `args`.") + if preserve_shape is not None: # only in tanhsinh for now + message = f"When `preserve_shape=False`, {message.lower()}" + shapes_equal = [f.shape == shape for f in fs] + if not all(shapes_equal): # use Python all to reduce overhead + raise ValueError(message) + + # These algorithms tend to mix the dtypes of the abscissae and function + # values, so figure out what the result will be and convert them all to + # that type from the outset. + xfat = xp.result_type(*([f.dtype for f in fs] + [xat])) + if not complex_ok and not xp.isdtype(xfat, "real floating"): + raise ValueError("Abscissae and function output must be real numbers.") + xs = [xp.asarray(x, dtype=xfat, copy=True) for x in xs] + fs = [xp.asarray(f, dtype=xfat, copy=True) for f in fs] + + # To ensure that we can do indexing, we'll work with at least 1d arrays, + # but remember the appropriate shape of the output. + xs = [xp.reshape(x, (-1,)) for x in xs] + fs = [xp.reshape(f, (-1,)) for f in fs] + args = [xp.reshape(xp.asarray(arg, copy=True), (-1,)) for arg in args] + return func, xs, fs, args, shape, xfat, xp + + +def _loop(work, callback, shape, maxiter, func, args, dtype, pre_func_eval, + post_func_eval, check_termination, post_termination_check, + customize_result, res_work_pairs, xp, preserve_shape=False): + """Main loop of a vectorized scalar optimization algorithm + + Parameters + ---------- + work : _RichResult + All variables that need to be retained between iterations. Must + contain attributes `nit`, `nfev`, and `success`. All arrays are + subject to being "compressed" if `preserve_shape is False`; nest + arrays that should not be compressed inside another object (e.g. + `dict` or `_RichResult`). + callback : callable + User-specified callback function + shape : tuple of ints + The shape of all output arrays + maxiter : + Maximum number of iterations of the algorithm + func : callable + The user-specified callable that is being optimized or solved + args : tuple + Additional positional arguments to be passed to `func`. + dtype : NumPy dtype + The common dtype of all abscissae and function values + pre_func_eval : callable + A function that accepts `work` and returns `x`, the active elements + of `x` at which `func` will be evaluated. May modify attributes + of `work` with any algorithmic steps that need to happen + at the beginning of an iteration, before `func` is evaluated, + post_func_eval : callable + A function that accepts `x`, `func(x)`, and `work`. May modify + attributes of `work` with any algorithmic steps that need to happen + in the middle of an iteration, after `func` is evaluated but before + the termination check. + check_termination : callable + A function that accepts `work` and returns `stop`, a boolean array + indicating which of the active elements have met a termination + condition. + post_termination_check : callable + A function that accepts `work`. May modify `work` with any algorithmic + steps that need to happen after the termination check and before the + end of the iteration. + customize_result : callable + A function that accepts `res` and `shape` and returns `shape`. May + modify `res` (in-place) according to preferences (e.g. rearrange + elements between attributes) and modify `shape` if needed. + res_work_pairs : list of (str, str) + Identifies correspondence between attributes of `res` and attributes + of `work`; i.e., attributes of active elements of `work` will be + copied to the appropriate indices of `res` when appropriate. The order + determines the order in which _RichResult attributes will be + pretty-printed. + preserve_shape : bool, default: False + Whether to compress the attributes of `work` (to avoid unnecessary + computation on elements that have already converged). + + Returns + ------- + res : _RichResult + The final result object + + Notes + ----- + Besides providing structure, this framework provides several important + services for a vectorized optimization algorithm. + + - It handles common tasks involving iteration count, function evaluation + count, a user-specified callback, and associated termination conditions. + - It compresses the attributes of `work` to eliminate unnecessary + computation on elements that have already converged. + + """ + if xp is None: + raise NotImplementedError("Must provide xp.") + + cb_terminate = False + + # Initialize the result object and active element index array + n_elements = math.prod(shape) + active = xp.arange(n_elements) # in-progress element indices + res_dict = {i: xp.zeros(n_elements, dtype=dtype) for i, j in res_work_pairs} + res_dict['success'] = xp.zeros(n_elements, dtype=xp.bool) + res_dict['status'] = xp.full(n_elements, xp.asarray(_EINPROGRESS), dtype=xp.int32) + res_dict['nit'] = xp.zeros(n_elements, dtype=xp.int32) + res_dict['nfev'] = xp.zeros(n_elements, dtype=xp.int32) + res = _RichResult(res_dict) + work.args = args + + active = _check_termination(work, res, res_work_pairs, active, + check_termination, preserve_shape, xp) + + if callback is not None: + temp = _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + if _call_callback_maybe_halt(callback, temp): + cb_terminate = True + + while work.nit < maxiter and xp_size(active) and not cb_terminate and n_elements: + x = pre_func_eval(work) + + if work.args and work.args[0].ndim != x.ndim: + # `x` always starts as 1D. If the SciPy function that uses + # _loop added dimensions to `x`, we need to + # add them to the elements of `args`. + args = [] + for arg in work.args: + n_new_dims = x.ndim - arg.ndim + new_shape = arg.shape + (1,)*n_new_dims + args.append(xp.reshape(arg, new_shape)) + work.args = args + + x_shape = x.shape + if preserve_shape: + x = xp.reshape(x, (shape + (-1,))) + f = func(x, *work.args) + f = xp.asarray(f, dtype=dtype) + if preserve_shape: + x = xp.reshape(x, x_shape) + f = xp.reshape(f, x_shape) + work.nfev += 1 if x.ndim == 1 else x.shape[-1] + + post_func_eval(x, f, work) + + work.nit += 1 + active = _check_termination(work, res, res_work_pairs, active, + check_termination, preserve_shape, xp) + + if callback is not None: + temp = _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + if _call_callback_maybe_halt(callback, temp): + cb_terminate = True + break + if xp_size(active) == 0: + break + + post_termination_check(work) + + work.status[:] = _ECALLBACK if cb_terminate else _ECONVERR + return _prepare_result(work, res, res_work_pairs, active, shape, + customize_result, preserve_shape, xp) + + +def _check_termination(work, res, res_work_pairs, active, check_termination, + preserve_shape, xp): + # Checks termination conditions, updates elements of `res` with + # corresponding elements of `work`, and compresses `work`. + + stop = check_termination(work) + + if xp.any(stop): + # update the active elements of the result object with the active + # elements for which a termination condition has been met + _update_active(work, res, res_work_pairs, active, stop, preserve_shape, xp) + + if preserve_shape: + stop = stop[active] + + proceed = ~stop + active = active[proceed] + + if not preserve_shape: + # compress the arrays to avoid unnecessary computation + for key, val in work.items(): + # Need to find a better way than these try/excepts + # Somehow need to keep compressible numerical args separate + if key == 'args': + continue + try: + work[key] = val[proceed] + except (IndexError, TypeError, KeyError): # not a compressible array + work[key] = val + work.args = [arg[proceed] for arg in work.args] + + return active + + +def _update_active(work, res, res_work_pairs, active, mask, preserve_shape, xp): + # Update `active` indices of the arrays in result object `res` with the + # contents of the scalars and arrays in `update_dict`. When provided, + # `mask` is a boolean array applied both to the arrays in `update_dict` + # that are to be used and to the arrays in `res` that are to be updated. + update_dict = {key1: work[key2] for key1, key2 in res_work_pairs} + update_dict['success'] = work.status == 0 + + if mask is not None: + if preserve_shape: + active_mask = xp.zeros_like(mask) + active_mask[active] = 1 + active_mask = active_mask & mask + for key, val in update_dict.items(): + try: + res[key][active_mask] = val[active_mask] + except (IndexError, TypeError, KeyError): + res[key][active_mask] = val + else: + active_mask = active[mask] + for key, val in update_dict.items(): + try: + res[key][active_mask] = val[mask] + except (IndexError, TypeError, KeyError): + res[key][active_mask] = val + else: + for key, val in update_dict.items(): + if preserve_shape: + try: + val = val[active] + except (IndexError, TypeError, KeyError): + pass + res[key][active] = val + + +def _prepare_result(work, res, res_work_pairs, active, shape, customize_result, + preserve_shape, xp): + # Prepare the result object `res` by creating a copy, copying the latest + # data from work, running the provided result customization function, + # and reshaping the data to the original shapes. + res = res.copy() + _update_active(work, res, res_work_pairs, active, None, preserve_shape, xp) + + shape = customize_result(res, shape) + + for key, val in res.items(): + # this looks like it won't work for xp != np if val is not numeric + temp = xp.reshape(val, shape) + res[key] = temp[()] if temp.ndim == 0 else temp + + res['_order_keys'] = ['success'] + [i for i, j in res_work_pairs] + return _RichResult(**res) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py new file mode 100644 index 0000000000000000000000000000000000000000..506057b48b3f49244e1ed6cd755fad8ad43d8739 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_finite_differences.py @@ -0,0 +1,145 @@ +from numpy import arange, newaxis, hstack, prod, array + + +def _central_diff_weights(Np, ndiv=1): + """ + Return weights for an Np-point central derivative. + + Assumes equally-spaced function points. + + If weights are in the vector w, then + derivative is w[0] * f(x-ho*dx) + ... + w[-1] * f(x+h0*dx) + + Parameters + ---------- + Np : int + Number of points for the central derivative. + ndiv : int, optional + Number of divisions. Default is 1. + + Returns + ------- + w : ndarray + Weights for an Np-point central derivative. Its size is `Np`. + + Notes + ----- + Can be inaccurate for a large number of points. + + Examples + -------- + We can calculate a derivative value of a function. + + >>> def f(x): + ... return 2 * x**2 + 3 + >>> x = 3.0 # derivative point + >>> h = 0.1 # differential step + >>> Np = 3 # point number for central derivative + >>> weights = _central_diff_weights(Np) # weights for first derivative + >>> vals = [f(x + (i - Np/2) * h) for i in range(Np)] + >>> sum(w * v for (w, v) in zip(weights, vals))/h + 11.79999999999998 + + This value is close to the analytical solution: + f'(x) = 4x, so f'(3) = 12 + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Finite_difference + + """ + if Np < ndiv + 1: + raise ValueError( + "Number of points must be at least the derivative order + 1." + ) + if Np % 2 == 0: + raise ValueError("The number of points must be odd.") + from scipy import linalg + + ho = Np >> 1 + x = arange(-ho, ho + 1.0) + x = x[:, newaxis] + X = x**0.0 + for k in range(1, Np): + X = hstack([X, x**k]) + w = prod(arange(1, ndiv + 1), axis=0) * linalg.inv(X)[ndiv] + return w + + +def _derivative(func, x0, dx=1.0, n=1, args=(), order=3): + """ + Find the nth derivative of a function at a point. + + Given a function, use a central difference formula with spacing `dx` to + compute the nth derivative at `x0`. + + Parameters + ---------- + func : function + Input function. + x0 : float + The point at which the nth derivative is found. + dx : float, optional + Spacing. + n : int, optional + Order of the derivative. Default is 1. + args : tuple, optional + Arguments + order : int, optional + Number of points to use, must be odd. + + Notes + ----- + Decreasing the step size too small can result in round-off error. + + Examples + -------- + >>> def f(x): + ... return x**3 + x**2 + >>> _derivative(f, 1.0, dx=1e-6) + 4.9999999999217337 + + """ + if order < n + 1: + raise ValueError( + "'order' (the number of points used to compute the derivative), " + "must be at least the derivative order 'n' + 1." + ) + if order % 2 == 0: + raise ValueError( + "'order' (the number of points used to compute the derivative) " + "must be odd." + ) + # pre-computed for n=1 and 2 and low-order for speed. + if n == 1: + if order == 3: + weights = array([-1, 0, 1]) / 2.0 + elif order == 5: + weights = array([1, -8, 0, 8, -1]) / 12.0 + elif order == 7: + weights = array([-1, 9, -45, 0, 45, -9, 1]) / 60.0 + elif order == 9: + weights = array([3, -32, 168, -672, 0, 672, -168, 32, -3]) / 840.0 + else: + weights = _central_diff_weights(order, 1) + elif n == 2: + if order == 3: + weights = array([1, -2.0, 1]) + elif order == 5: + weights = array([-1, 16, -30, 16, -1]) / 12.0 + elif order == 7: + weights = array([2, -27, 270, -490, 270, -27, 2]) / 180.0 + elif order == 9: + weights = ( + array([-9, 128, -1008, 8064, -14350, 8064, -1008, 128, -9]) + / 5040.0 + ) + else: + weights = _central_diff_weights(order, 2) + else: + weights = _central_diff_weights(order, n) + val = 0.0 + ho = order >> 1 + for k in range(order): + val += weights[k] * func(x0 + (k - ho) * dx, *args) + return val / prod((dx,) * n, axis=0) diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3a443899bde3481ed6c1359eff4ef9696f6c8e4d Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_fpumode.cpython-310-x86_64-linux-gnu.so differ diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py new file mode 100644 index 0000000000000000000000000000000000000000..854ae36228614f3eb8849e9f95abf0dd387b5d35 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_gcutils.py @@ -0,0 +1,105 @@ +""" +Module for testing automatic garbage collection of objects + +.. autosummary:: + :toctree: generated/ + + set_gc_state - enable or disable garbage collection + gc_state - context manager for given state of garbage collector + assert_deallocated - context manager to check for circular references on object + +""" +import weakref +import gc + +from contextlib import contextmanager +from platform import python_implementation + +__all__ = ['set_gc_state', 'gc_state', 'assert_deallocated'] + + +IS_PYPY = python_implementation() == 'PyPy' + + +class ReferenceError(AssertionError): + pass + + +def set_gc_state(state): + """ Set status of garbage collector """ + if gc.isenabled() == state: + return + if state: + gc.enable() + else: + gc.disable() + + +@contextmanager +def gc_state(state): + """ Context manager to set state of garbage collector to `state` + + Parameters + ---------- + state : bool + True for gc enabled, False for disabled + + Examples + -------- + >>> with gc_state(False): + ... assert not gc.isenabled() + >>> with gc_state(True): + ... assert gc.isenabled() + """ + orig_state = gc.isenabled() + set_gc_state(state) + yield + set_gc_state(orig_state) + + +@contextmanager +def assert_deallocated(func, *args, **kwargs): + """Context manager to check that object is deallocated + + This is useful for checking that an object can be freed directly by + reference counting, without requiring gc to break reference cycles. + GC is disabled inside the context manager. + + This check is not available on PyPy. + + Parameters + ---------- + func : callable + Callable to create object to check + \\*args : sequence + positional arguments to `func` in order to create object to check + \\*\\*kwargs : dict + keyword arguments to `func` in order to create object to check + + Examples + -------- + >>> class C: pass + >>> with assert_deallocated(C) as c: + ... # do something + ... del c + + >>> class C: + ... def __init__(self): + ... self._circular = self # Make circular reference + >>> with assert_deallocated(C) as c: #doctest: +IGNORE_EXCEPTION_DETAIL + ... # do something + ... del c + Traceback (most recent call last): + ... + ReferenceError: Remaining reference(s) to object + """ + if IS_PYPY: + raise RuntimeError("assert_deallocated is unavailable on PyPy") + + with gc_state(False): + obj = func(*args, **kwargs) + ref = weakref.ref(obj) + yield obj + del obj + if ref() is not None: + raise ReferenceError("Remaining reference(s) to object") diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py new file mode 100644 index 0000000000000000000000000000000000000000..d546e32a0349461a0aab76bfb4636ebf25227ca0 --- /dev/null +++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_pep440.py @@ -0,0 +1,487 @@ +"""Utility to compare pep440 compatible version strings. + +The LooseVersion and StrictVersion classes that distutils provides don't +work; they don't recognize anything like alpha/beta/rc/dev versions. +""" + +# Copyright (c) Donald Stufft and individual contributors. +# All rights reserved. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: + +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. + +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. + +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import collections +import itertools +import re + + +__all__ = [ + "parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN", +] + + +# BEGIN packaging/_structures.py + + +class Infinity: + def __repr__(self): + return "Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return False + + def __le__(self, other): + return False + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return True + + def __ge__(self, other): + return True + + def __neg__(self): + return NegativeInfinity + + +Infinity = Infinity() + + +class NegativeInfinity: + def __repr__(self): + return "-Infinity" + + def __hash__(self): + return hash(repr(self)) + + def __lt__(self, other): + return True + + def __le__(self, other): + return True + + def __eq__(self, other): + return isinstance(other, self.__class__) + + def __ne__(self, other): + return not isinstance(other, self.__class__) + + def __gt__(self, other): + return False + + def __ge__(self, other): + return False + + def __neg__(self): + return Infinity + + +# BEGIN packaging/version.py + + +NegativeInfinity = NegativeInfinity() + +_Version = collections.namedtuple( + "_Version", + ["epoch", "release", "dev", "pre", "post", "local"], +) + + +def parse(version): + """ + Parse the given version string and return either a :class:`Version` object + or a :class:`LegacyVersion` object depending on if the given version is + a valid PEP 440 version or a legacy version. + """ + try: + return Version(version) + except InvalidVersion: + return LegacyVersion(version) + + +class InvalidVersion(ValueError): + """ + An invalid version was found, users should refer to PEP 440. + """ + + +class _BaseVersion: + + def __hash__(self): + return hash(self._key) + + def __lt__(self, other): + return self._compare(other, lambda s, o: s < o) + + def __le__(self, other): + return self._compare(other, lambda s, o: s <= o) + + def __eq__(self, other): + return self._compare(other, lambda s, o: s == o) + + def __ge__(self, other): + return self._compare(other, lambda s, o: s >= o) + + def __gt__(self, other): + return self._compare(other, lambda s, o: s > o) + + def __ne__(self, other): + return self._compare(other, lambda s, o: s != o) + + def _compare(self, other, method): + if not isinstance(other, _BaseVersion): + return NotImplemented + + return method(self._key, other._key) + + +class LegacyVersion(_BaseVersion): + + def __init__(self, version): + self._version = str(version) + self._key = _legacy_cmpkey(self._version) + + def __str__(self): + return self._version + + def __repr__(self): + return f"" + + @property + def public(self): + return self._version + + @property + def base_version(self): + return self._version + + @property + def local(self): + return None + + @property + def is_prerelease(self): + return False + + @property + def is_postrelease(self): + return False + + +_legacy_version_component_re = re.compile( + r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE, +) + +_legacy_version_replacement_map = { + "pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@", +} + + +def _parse_version_parts(s): + for part in _legacy_version_component_re.split(s): + part = _legacy_version_replacement_map.get(part, part) + + if not part or part == ".": + continue + + if part[:1] in "0123456789": + # pad for numeric comparison + yield part.zfill(8) + else: + yield "*" + part + + # ensure that alpha/beta/candidate are before final + yield "*final" + + +def _legacy_cmpkey(version): + # We hardcode an epoch of -1 here. A PEP 440 version can only have an epoch + # greater than or equal to 0. This will effectively put the LegacyVersion, + # which uses the defacto standard originally implemented by setuptools, + # as before all PEP 440 versions. + epoch = -1 + + # This scheme is taken from pkg_resources.parse_version setuptools prior to + # its adoption of the packaging library. + parts = [] + for part in _parse_version_parts(version.lower()): + if part.startswith("*"): + # remove "-" before a prerelease tag + if part < "*final": + while parts and parts[-1] == "*final-": + parts.pop() + + # remove trailing zeros from each series of numeric parts + while parts and parts[-1] == "00000000": + parts.pop() + + parts.append(part) + parts = tuple(parts) + + return epoch, parts + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse +VERSION_PATTERN = r""" + v? + (?: + (?:(?P[0-9]+)!)? # epoch + (?P[0-9]+(?:\.[0-9]+)*) # release segment + (?P
                                          # pre-release
+            [-_\.]?
+            (?P(a|b|c|rc|alpha|beta|pre|preview))
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [-_\.]?
+                (?Ppost|rev|r)
+                [-_\.]?
+                (?P[0-9]+)?
+            )
+        )?
+        (?P                                          # dev release
+            [-_\.]?
+            (?Pdev)
+            [-_\.]?
+            (?P[0-9]+)?
+        )?
+    )
+    (?:\+(?P[a-z0-9]+(?:[-_\.][a-z0-9]+)*))?       # local version
+"""
+
+
+class Version(_BaseVersion):
+
+    _regex = re.compile(
+        r"^\s*" + VERSION_PATTERN + r"\s*$",
+        re.VERBOSE | re.IGNORECASE,
+    )
+
+    def __init__(self, version):
+        # Validate the version and parse it into pieces
+        match = self._regex.search(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: '{version}'")
+
+        # Store the parsed out pieces of the version
+        self._version = _Version(
+            epoch=int(match.group("epoch")) if match.group("epoch") else 0,
+            release=tuple(int(i) for i in match.group("release").split(".")),
+            pre=_parse_letter_version(
+                match.group("pre_l"),
+                match.group("pre_n"),
+            ),
+            post=_parse_letter_version(
+                match.group("post_l"),
+                match.group("post_n1") or match.group("post_n2"),
+            ),
+            dev=_parse_letter_version(
+                match.group("dev_l"),
+                match.group("dev_n"),
+            ),
+            local=_parse_local_version(match.group("local")),
+        )
+
+        # Generate a key which will be used for sorting
+        self._key = _cmpkey(
+            self._version.epoch,
+            self._version.release,
+            self._version.pre,
+            self._version.post,
+            self._version.dev,
+            self._version.local,
+        )
+
+    def __repr__(self):
+        return f""
+
+    def __str__(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append(f"{self._version.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        # Pre-release
+        if self._version.pre is not None:
+            parts.append("".join(str(x) for x in self._version.pre))
+
+        # Post-release
+        if self._version.post is not None:
+            parts.append(f".post{self._version.post[1]}")
+
+        # Development release
+        if self._version.dev is not None:
+            parts.append(f".dev{self._version.dev[1]}")
+
+        # Local version segment
+        if self._version.local is not None:
+            parts.append(
+                "+{}".format(".".join(str(x) for x in self._version.local))
+            )
+
+        return "".join(parts)
+
+    @property
+    def public(self):
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self):
+        parts = []
+
+        # Epoch
+        if self._version.epoch != 0:
+            parts.append(f"{self._version.epoch}!")
+
+        # Release segment
+        parts.append(".".join(str(x) for x in self._version.release))
+
+        return "".join(parts)
+
+    @property
+    def local(self):
+        version_string = str(self)
+        if "+" in version_string:
+            return version_string.split("+", 1)[1]
+
+    @property
+    def is_prerelease(self):
+        return bool(self._version.dev or self._version.pre)
+
+    @property
+    def is_postrelease(self):
+        return bool(self._version.post)
+
+
+def _parse_letter_version(letter, number):
+    if letter:
+        # We assume there is an implicit 0 in a pre-release if there is
+        # no numeral associated with it.
+        if number is None:
+            number = 0
+
+        # We normalize any letters to their lower-case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        if letter == "alpha":
+            letter = "a"
+        elif letter == "beta":
+            letter = "b"
+        elif letter in ["c", "pre", "preview"]:
+            letter = "rc"
+        elif letter in ["rev", "r"]:
+            letter = "post"
+
+        return letter, int(number)
+    if not letter and number:
+        # We assume that if we are given a number but not given a letter,
+        # then this is using the implicit post release syntax (e.g., 1.0-1)
+        letter = "post"
+
+        return letter, int(number)
+
+
+_local_version_seperators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local):
+    """
+    Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_seperators.split(local)
+        )
+
+
+def _cmpkey(epoch, release, pre, post, dev, local):
+    # When we compare a release version, we want to compare it with all of the
+    # trailing zeros removed. So we'll use a reverse the list, drop all the now
+    # leading zeros until we come to something non-zero, then take the rest,
+    # re-reverse it back into the correct order, and make it a tuple and use
+    # that for our sorting key.
+    release = tuple(
+        reversed(list(
+            itertools.dropwhile(
+                lambda x: x == 0,
+                reversed(release),
+            )
+        ))
+    )
+
+    # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
+    # We'll do this by abusing the pre-segment, but we _only_ want to do this
+    # if there is no pre- or a post-segment. If we have one of those, then
+    # the normal sorting rules will handle this case correctly.
+    if pre is None and post is None and dev is not None:
+        pre = -Infinity
+    # Versions without a pre-release (except as noted above) should sort after
+    # those with one.
+    elif pre is None:
+        pre = Infinity
+
+    # Versions without a post-segment should sort before those with one.
+    if post is None:
+        post = -Infinity
+
+    # Versions without a development segment should sort after those with one.
+    if dev is None:
+        dev = Infinity
+
+    if local is None:
+        # Versions without a local segment should sort before those with one.
+        local = -Infinity
+    else:
+        # Versions with a local segment need that segment parsed to implement
+        # the sorting rules in PEP440.
+        # - Alphanumeric segments sort before numeric segments
+        # - Alphanumeric segments sort lexicographically
+        # - Numeric segments sort numerically
+        # - Shorter versions sort before longer versions when the prefixes
+        #   match exactly
+        local = tuple(
+            (i, "") if isinstance(i, int) else (-Infinity, i)
+            for i in local
+        )
+
+    return epoch, release, pre, post, dev, local
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..3bd017197577d973e5c77c3c51ad966a015b890b
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_test_ccallback.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..34c0e024dcd5924c7287e6ce8105975c4d9ab7f5
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_call.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_def.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_def.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..60dc2423372bf2fb24dece8ab51b1f9b7f26d7eb
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_test_deprecation_def.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8da7e403dec5de5cb7d9a98d8c69a2c49e377c6a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_testutils.py
@@ -0,0 +1,369 @@
+"""
+Generic test utilities.
+
+"""
+
+import inspect
+import os
+import re
+import shutil
+import subprocess
+import sys
+import sysconfig
+import threading
+from importlib.util import module_from_spec, spec_from_file_location
+
+import numpy as np
+import scipy
+
+try:
+    # Need type: ignore[import-untyped] for mypy >= 1.6
+    import cython  # type: ignore[import-untyped]
+    from Cython.Compiler.Version import (  # type: ignore[import-untyped]
+        version as cython_version,
+    )
+except ImportError:
+    cython = None
+else:
+    from scipy._lib import _pep440
+    required_version = '3.0.8'
+    if _pep440.parse(cython_version) < _pep440.Version(required_version):
+        # too old or wrong cython, skip Cython API tests
+        cython = None
+
+
+__all__ = ['PytestTester', 'check_free_memory', '_TestPythranFunc', 'IS_MUSL']
+
+
+IS_MUSL = False
+# alternate way is
+# from packaging.tags import sys_tags
+#     _tags = list(sys_tags())
+#     if 'musllinux' in _tags[0].platform:
+_v = sysconfig.get_config_var('HOST_GNU_TYPE') or ''
+if 'musl' in _v:
+    IS_MUSL = True
+
+
+IS_EDITABLE = 'editable' in scipy.__path__[0]
+
+
+class FPUModeChangeWarning(RuntimeWarning):
+    """Warning about FPU mode change"""
+    pass
+
+
+class PytestTester:
+    """
+    Run tests for this namespace
+
+    ``scipy.test()`` runs tests for all of SciPy, with the default settings.
+    When used from a submodule (e.g., ``scipy.cluster.test()``, only the tests
+    for that namespace are run.
+
+    Parameters
+    ----------
+    label : {'fast', 'full'}, optional
+        Whether to run only the fast tests, or also those marked as slow.
+        Default is 'fast'.
+    verbose : int, optional
+        Test output verbosity. Default is 1.
+    extra_argv : list, optional
+        Arguments to pass through to Pytest.
+    doctests : bool, optional
+        Whether to run doctests or not. Default is False.
+    coverage : bool, optional
+        Whether to run tests with code coverage measurements enabled.
+        Default is False.
+    tests : list of str, optional
+        List of module names to run tests for. By default, uses the module
+        from which the ``test`` function is called.
+    parallel : int, optional
+        Run tests in parallel with pytest-xdist, if number given is larger than
+        1. Default is 1.
+
+    """
+    def __init__(self, module_name):
+        self.module_name = module_name
+
+    def __call__(self, label="fast", verbose=1, extra_argv=None, doctests=False,
+                 coverage=False, tests=None, parallel=None):
+        import pytest
+
+        module = sys.modules[self.module_name]
+        module_path = os.path.abspath(module.__path__[0])
+
+        pytest_args = ['--showlocals', '--tb=short']
+
+        if extra_argv:
+            pytest_args += list(extra_argv)
+
+        if verbose and int(verbose) > 1:
+            pytest_args += ["-" + "v"*(int(verbose)-1)]
+
+        if coverage:
+            pytest_args += ["--cov=" + module_path]
+
+        if label == "fast":
+            pytest_args += ["-m", "not slow"]
+        elif label != "full":
+            pytest_args += ["-m", label]
+
+        if tests is None:
+            tests = [self.module_name]
+
+        if parallel is not None and parallel > 1:
+            if _pytest_has_xdist():
+                pytest_args += ['-n', str(parallel)]
+            else:
+                import warnings
+                warnings.warn('Could not run tests in parallel because '
+                              'pytest-xdist plugin is not available.',
+                              stacklevel=2)
+
+        pytest_args += ['--pyargs'] + list(tests)
+
+        try:
+            code = pytest.main(pytest_args)
+        except SystemExit as exc:
+            code = exc.code
+
+        return (code == 0)
+
+
+class _TestPythranFunc:
+    '''
+    These are situations that can be tested in our pythran tests:
+    - A function with multiple array arguments and then
+      other positional and keyword arguments.
+    - A function with array-like keywords (e.g. `def somefunc(x0, x1=None)`.
+    Note: list/tuple input is not yet tested!
+
+    `self.arguments`: A dictionary which key is the index of the argument,
+                      value is tuple(array value, all supported dtypes)
+    `self.partialfunc`: A function used to freeze some non-array argument
+                        that of no interests in the original function
+    '''
+    ALL_INTEGER = [np.int8, np.int16, np.int32, np.int64, np.intc, np.intp]
+    ALL_FLOAT = [np.float32, np.float64]
+    ALL_COMPLEX = [np.complex64, np.complex128]
+
+    def setup_method(self):
+        self.arguments = {}
+        self.partialfunc = None
+        self.expected = None
+
+    def get_optional_args(self, func):
+        # get optional arguments with its default value,
+        # used for testing keywords
+        signature = inspect.signature(func)
+        optional_args = {}
+        for k, v in signature.parameters.items():
+            if v.default is not inspect.Parameter.empty:
+                optional_args[k] = v.default
+        return optional_args
+
+    def get_max_dtype_list_length(self):
+        # get the max supported dtypes list length in all arguments
+        max_len = 0
+        for arg_idx in self.arguments:
+            cur_len = len(self.arguments[arg_idx][1])
+            if cur_len > max_len:
+                max_len = cur_len
+        return max_len
+
+    def get_dtype(self, dtype_list, dtype_idx):
+        # get the dtype from dtype_list via index
+        # if the index is out of range, then return the last dtype
+        if dtype_idx > len(dtype_list)-1:
+            return dtype_list[-1]
+        else:
+            return dtype_list[dtype_idx]
+
+    def test_all_dtypes(self):
+        for type_idx in range(self.get_max_dtype_list_length()):
+            args_array = []
+            for arg_idx in self.arguments:
+                new_dtype = self.get_dtype(self.arguments[arg_idx][1],
+                                           type_idx)
+                args_array.append(self.arguments[arg_idx][0].astype(new_dtype))
+            self.pythranfunc(*args_array)
+
+    def test_views(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(self.arguments[arg_idx][0][::-1][::-1])
+        self.pythranfunc(*args_array)
+
+    def test_strided(self):
+        args_array = []
+        for arg_idx in self.arguments:
+            args_array.append(np.repeat(self.arguments[arg_idx][0],
+                                        2, axis=0)[::2])
+        self.pythranfunc(*args_array)
+
+
+def _pytest_has_xdist():
+    """
+    Check if the pytest-xdist plugin is installed, providing parallel tests
+    """
+    # Check xdist exists without importing, otherwise pytests emits warnings
+    from importlib.util import find_spec
+    return find_spec('xdist') is not None
+
+
+def check_free_memory(free_mb):
+    """
+    Check *free_mb* of memory is available, otherwise do pytest.skip
+    """
+    import pytest
+
+    try:
+        mem_free = _parse_size(os.environ['SCIPY_AVAILABLE_MEM'])
+        msg = '{} MB memory required, but environment SCIPY_AVAILABLE_MEM={}'.format(
+            free_mb, os.environ['SCIPY_AVAILABLE_MEM'])
+    except KeyError:
+        mem_free = _get_mem_available()
+        if mem_free is None:
+            pytest.skip("Could not determine available memory; set SCIPY_AVAILABLE_MEM "
+                        "variable to free memory in MB to run the test.")
+        msg = f'{free_mb} MB memory required, but {mem_free/1e6} MB available'
+
+    if mem_free < free_mb * 1e6:
+        pytest.skip(msg)
+
+
+def _parse_size(size_str):
+    suffixes = {'': 1e6,
+                'b': 1.0,
+                'k': 1e3, 'M': 1e6, 'G': 1e9, 'T': 1e12,
+                'kb': 1e3, 'Mb': 1e6, 'Gb': 1e9, 'Tb': 1e12,
+                'kib': 1024.0, 'Mib': 1024.0**2, 'Gib': 1024.0**3, 'Tib': 1024.0**4}
+    m = re.match(r'^\s*(\d+)\s*({})\s*$'.format('|'.join(suffixes.keys())),
+                 size_str,
+                 re.I)
+    if not m or m.group(2) not in suffixes:
+        raise ValueError("Invalid size string")
+
+    return float(m.group(1)) * suffixes[m.group(2)]
+
+
+def _get_mem_available():
+    """
+    Get information about memory available, not counting swap.
+    """
+    try:
+        import psutil
+        return psutil.virtual_memory().available
+    except (ImportError, AttributeError):
+        pass
+
+    if sys.platform.startswith('linux'):
+        info = {}
+        with open('/proc/meminfo') as f:
+            for line in f:
+                p = line.split()
+                info[p[0].strip(':').lower()] = float(p[1]) * 1e3
+
+        if 'memavailable' in info:
+            # Linux >= 3.14
+            return info['memavailable']
+        else:
+            return info['memfree'] + info['cached']
+
+    return None
+
+def _test_cython_extension(tmp_path, srcdir):
+    """
+    Helper function to test building and importing Cython modules that
+    make use of the Cython APIs for BLAS, LAPACK, optimize, and special.
+    """
+    import pytest
+    try:
+        subprocess.check_call(["meson", "--version"])
+    except FileNotFoundError:
+        pytest.skip("No usable 'meson' found")
+
+    # Make safe for being called by multiple threads within one test
+    tmp_path = tmp_path / str(threading.get_ident())
+
+    # build the examples in a temporary directory
+    mod_name = os.path.split(srcdir)[1]
+    shutil.copytree(srcdir, tmp_path / mod_name)
+    build_dir = tmp_path / mod_name / 'tests' / '_cython_examples'
+    target_dir = build_dir / 'build'
+    os.makedirs(target_dir, exist_ok=True)
+
+    # Ensure we use the correct Python interpreter even when `meson` is
+    # installed in a different Python environment (see numpy#24956)
+    native_file = str(build_dir / 'interpreter-native-file.ini')
+    with open(native_file, 'w') as f:
+        f.write("[binaries]\n")
+        f.write(f"python = '{sys.executable}'")
+
+    if sys.platform == "win32":
+        subprocess.check_call(["meson", "setup",
+                               "--buildtype=release",
+                               "--native-file", native_file,
+                               "--vsenv", str(build_dir)],
+                              cwd=target_dir,
+                              )
+    else:
+        subprocess.check_call(["meson", "setup",
+                               "--native-file", native_file, str(build_dir)],
+                              cwd=target_dir
+                              )
+    subprocess.check_call(["meson", "compile", "-vv"], cwd=target_dir)
+
+    # import without adding the directory to sys.path
+    suffix = sysconfig.get_config_var('EXT_SUFFIX')
+
+    def load(modname):
+        so = (target_dir / modname).with_suffix(suffix)
+        spec = spec_from_file_location(modname, so)
+        mod = module_from_spec(spec)
+        spec.loader.exec_module(mod)
+        return mod
+
+    # test that the module can be imported
+    return load("extending"), load("extending_cpp")
+
+
+def _run_concurrent_barrier(n_workers, fn, *args, **kwargs):
+    """
+    Run a given function concurrently across a given number of threads.
+
+    This is equivalent to using a ThreadPoolExecutor, but using the threading
+    primitives instead. This function ensures that the closure passed by
+    parameter gets called concurrently by setting up a barrier before it gets
+    called before any of the threads.
+
+    Arguments
+    ---------
+    n_workers: int
+        Number of concurrent threads to spawn.
+    fn: callable
+        Function closure to execute concurrently. Its first argument will
+        be the thread id.
+    *args: tuple
+        Variable number of positional arguments to pass to the function.
+    **kwargs: dict
+        Keyword arguments to pass to the function.
+    """
+    barrier = threading.Barrier(n_workers)
+
+    def closure(i, *args, **kwargs):
+        barrier.wait()
+        fn(i, *args, **kwargs)
+
+    workers = []
+    for i in range(0, n_workers):
+        workers.append(threading.Thread(
+            target=closure,
+            args=(i,) + args, kwargs=kwargs))
+
+    for worker in workers:
+        worker.start()
+
+    for worker in workers:
+        worker.join()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py
new file mode 100644
index 0000000000000000000000000000000000000000..530339ec7075dafdb81e9fa0ff5447952af77497
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_threadsafety.py
@@ -0,0 +1,58 @@
+import threading
+
+import scipy._lib.decorator
+
+
+__all__ = ['ReentrancyError', 'ReentrancyLock', 'non_reentrant']
+
+
+class ReentrancyError(RuntimeError):
+    pass
+
+
+class ReentrancyLock:
+    """
+    Threading lock that raises an exception for reentrant calls.
+
+    Calls from different threads are serialized, and nested calls from the
+    same thread result to an error.
+
+    The object can be used as a context manager or to decorate functions
+    via the decorate() method.
+
+    """
+
+    def __init__(self, err_msg):
+        self._rlock = threading.RLock()
+        self._entered = False
+        self._err_msg = err_msg
+
+    def __enter__(self):
+        self._rlock.acquire()
+        if self._entered:
+            self._rlock.release()
+            raise ReentrancyError(self._err_msg)
+        self._entered = True
+
+    def __exit__(self, type, value, traceback):
+        self._entered = False
+        self._rlock.release()
+
+    def decorate(self, func):
+        def caller(func, *a, **kw):
+            with self:
+                return func(*a, **kw)
+        return scipy._lib.decorator.decorate(func, caller)
+
+
+def non_reentrant(err_msg=None):
+    """
+    Decorate a function with a threading lock and prevent reentrant calls.
+    """
+    def decorator(func):
+        msg = err_msg
+        if msg is None:
+            msg = f"{func.__name__} is not re-entrant"
+        lock = ReentrancyLock(msg)
+        return lock.decorate(func)
+    return decorator
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f9fd546a9d2ae3e9a20c0684f79eb0b3d61ee92
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_tmpdirs.py
@@ -0,0 +1,86 @@
+''' Contexts for *with* statement providing temporary directories
+'''
+import os
+from contextlib import contextmanager
+from shutil import rmtree
+from tempfile import mkdtemp
+
+
+@contextmanager
+def tempdir():
+    """Create and return a temporary directory. This has the same
+    behavior as mkdtemp but can be used as a context manager.
+
+    Upon exiting the context, the directory and everything contained
+    in it are removed.
+
+    Examples
+    --------
+    >>> import os
+    >>> with tempdir() as tmpdir:
+    ...     fname = os.path.join(tmpdir, 'example_file.txt')
+    ...     with open(fname, 'wt') as fobj:
+    ...         _ = fobj.write('a string\\n')
+    >>> os.path.exists(tmpdir)
+    False
+    """
+    d = mkdtemp()
+    yield d
+    rmtree(d)
+
+
+@contextmanager
+def in_tempdir():
+    ''' Create, return, and change directory to a temporary directory
+
+    Examples
+    --------
+    >>> import os
+    >>> my_cwd = os.getcwd()
+    >>> with in_tempdir() as tmpdir:
+    ...     _ = open('test.txt', 'wt').write('some text')
+    ...     assert os.path.isfile('test.txt')
+    ...     assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
+    >>> os.path.exists(tmpdir)
+    False
+    >>> os.getcwd() == my_cwd
+    True
+    '''
+    pwd = os.getcwd()
+    d = mkdtemp()
+    os.chdir(d)
+    yield d
+    os.chdir(pwd)
+    rmtree(d)
+
+
+@contextmanager
+def in_dir(dir=None):
+    """ Change directory to given directory for duration of ``with`` block
+
+    Useful when you want to use `in_tempdir` for the final test, but
+    you are still debugging. For example, you may want to do this in the end:
+
+    >>> with in_tempdir() as tmpdir:
+    ...     # do something complicated which might break
+    ...     pass
+
+    But, indeed, the complicated thing does break, and meanwhile, the
+    ``in_tempdir`` context manager wiped out the directory with the
+    temporary files that you wanted for debugging. So, while debugging, you
+    replace with something like:
+
+    >>> with in_dir() as tmpdir: # Use working directory by default
+    ...     # do something complicated which might break
+    ...     pass
+
+    You can then look at the temporary file outputs to debug what is happening,
+    fix, and finally replace ``in_dir`` with ``in_tempdir`` again.
+    """
+    cwd = os.getcwd()
+    if dir is None:
+        yield cwd
+        return
+    os.chdir(dir)
+    yield dir
+    os.chdir(cwd)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..5f2b90a026aaecbdc090b3d3234954ab29fce8ae
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE
@@ -0,0 +1,29 @@
+BSD 3-Clause License
+
+Copyright (c) 2018, Quansight-Labs
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+  this list of conditions and the following disclaimer in the documentation
+  and/or other materials provided with the distribution.
+
+* Neither the name of the copyright holder nor the names of its
+  contributors may be used to endorse or promote products derived from
+  this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..91afdcedb180599a41758cdd8c03416cf6c20d76
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py
@@ -0,0 +1,116 @@
+"""
+.. note:
+    If you are looking for overrides for NumPy-specific methods, see the
+    documentation for :obj:`unumpy`. This page explains how to write
+    back-ends and multimethods.
+
+``uarray`` is built around a back-end protocol, and overridable multimethods.
+It is necessary to define multimethods for back-ends to be able to override them.
+See the documentation of :obj:`generate_multimethod` on how to write multimethods.
+
+
+
+Let's start with the simplest:
+
+``__ua_domain__`` defines the back-end *domain*. The domain consists of period-
+separated string consisting of the modules you extend plus the submodule. For
+example, if a submodule ``module2.submodule`` extends ``module1``
+(i.e., it exposes dispatchables marked as types available in ``module1``),
+then the domain string should be ``"module1.module2.submodule"``.
+
+
+For the purpose of this demonstration, we'll be creating an object and setting
+its attributes directly. However, note that you can use a module or your own type
+as a backend as well.
+
+>>> class Backend: pass
+>>> be = Backend()
+>>> be.__ua_domain__ = "ua_examples"
+
+It might be useful at this point to sidetrack to the documentation of
+:obj:`generate_multimethod` to find out how to generate a multimethod
+overridable by :obj:`uarray`. Needless to say, writing a backend and
+creating multimethods are mostly orthogonal activities, and knowing
+one doesn't necessarily require knowledge of the other, although it
+is certainly helpful. We expect core API designers/specifiers to write the
+multimethods, and implementors to override them. But, as is often the case,
+similar people write both.
+
+Without further ado, here's an example multimethod:
+
+>>> import uarray as ua
+>>> from uarray import Dispatchable
+>>> def override_me(a, b):
+...   return Dispatchable(a, int),
+>>> def override_replacer(args, kwargs, dispatchables):
+...     return (dispatchables[0], args[1]), {}
+>>> overridden_me = ua.generate_multimethod(
+...     override_me, override_replacer, "ua_examples"
+... )
+
+Next comes the part about overriding the multimethod. This requires
+the ``__ua_function__`` protocol, and the ``__ua_convert__``
+protocol. The ``__ua_function__`` protocol has the signature
+``(method, args, kwargs)`` where ``method`` is the passed
+multimethod, ``args``/``kwargs`` specify the arguments and ``dispatchables``
+is the list of converted dispatchables passed in.
+
+>>> def __ua_function__(method, args, kwargs):
+...     return method.__name__, args, kwargs
+>>> be.__ua_function__ = __ua_function__
+
+The other protocol of interest is the ``__ua_convert__`` protocol. It has the
+signature ``(dispatchables, coerce)``. When ``coerce`` is ``False``, conversion
+between the formats should ideally be an ``O(1)`` operation, but it means that
+no memory copying should be involved, only views of the existing data.
+
+>>> def __ua_convert__(dispatchables, coerce):
+...     for d in dispatchables:
+...         if d.type is int:
+...             if coerce and d.coercible:
+...                 yield str(d.value)
+...             else:
+...                 yield d.value
+>>> be.__ua_convert__ = __ua_convert__
+
+Now that we have defined the backend, the next thing to do is to call the multimethod.
+
+>>> with ua.set_backend(be):
+...      overridden_me(1, "2")
+('override_me', (1, '2'), {})
+
+Note that the marked type has no effect on the actual type of the passed object.
+We can also coerce the type of the input.
+
+>>> with ua.set_backend(be, coerce=True):
+...     overridden_me(1, "2")
+...     overridden_me(1.0, "2")
+('override_me', ('1', '2'), {})
+('override_me', ('1.0', '2'), {})
+
+Another feature is that if you remove ``__ua_convert__``, the arguments are not
+converted at all and it's up to the backend to handle that.
+
+>>> del be.__ua_convert__
+>>> with ua.set_backend(be):
+...     overridden_me(1, "2")
+('override_me', (1, '2'), {})
+
+You also have the option to return ``NotImplemented``, in which case processing moves on
+to the next back-end, which in this case, doesn't exist. The same applies to
+``__ua_convert__``.
+
+>>> be.__ua_function__ = lambda *a, **kw: NotImplemented
+>>> with ua.set_backend(be):
+...     overridden_me(1, "2")
+Traceback (most recent call last):
+    ...
+uarray.BackendNotImplementedError: ...
+
+The last possibility is if we don't have ``__ua_convert__``, in which case the job is
+left up to ``__ua_function__``, but putting things back into arrays after conversion
+will not be possible.
+"""
+
+from ._backend import *
+__version__ = '0.8.8.dev0+aa94c5a4.scipy'
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52f58b496a21e74c6903de7ab6e8545495abad7a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d84c83579048dbaf2c8a3e8ae8f5d35f924f27e7
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/__pycache__/_backend.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ea71965761ca6916485828ee23d3402bfb1b7d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py
@@ -0,0 +1,707 @@
+import typing
+import types
+import inspect
+import functools
+from . import _uarray
+import copyreg
+import pickle
+import contextlib
+import threading
+
+from ._uarray import (  # type: ignore
+    BackendNotImplementedError,
+    _Function,
+    _SkipBackendContext,
+    _SetBackendContext,
+    _BackendState,
+)
+
+__all__ = [
+    "set_backend",
+    "set_global_backend",
+    "skip_backend",
+    "register_backend",
+    "determine_backend",
+    "determine_backend_multi",
+    "clear_backends",
+    "create_multimethod",
+    "generate_multimethod",
+    "_Function",
+    "BackendNotImplementedError",
+    "Dispatchable",
+    "wrap_single_convertor",
+    "wrap_single_convertor_instance",
+    "all_of_type",
+    "mark_as",
+    "set_state",
+    "get_state",
+    "reset_state",
+    "_BackendState",
+    "_SkipBackendContext",
+    "_SetBackendContext",
+]
+
+ArgumentExtractorType = typing.Callable[..., tuple["Dispatchable", ...]]
+ArgumentReplacerType = typing.Callable[
+    [tuple, dict, tuple], tuple[tuple, dict]
+]
+
+def unpickle_function(mod_name, qname, self_):
+    import importlib
+
+    try:
+        module = importlib.import_module(mod_name)
+        qname = qname.split(".")
+        func = module
+        for q in qname:
+            func = getattr(func, q)
+
+        if self_ is not None:
+            func = types.MethodType(func, self_)
+
+        return func
+    except (ImportError, AttributeError) as e:
+        from pickle import UnpicklingError
+
+        raise UnpicklingError from e
+
+
+def pickle_function(func):
+    mod_name = getattr(func, "__module__", None)
+    qname = getattr(func, "__qualname__", None)
+    self_ = getattr(func, "__self__", None)
+
+    try:
+        test = unpickle_function(mod_name, qname, self_)
+    except pickle.UnpicklingError:
+        test = None
+
+    if test is not func:
+        raise pickle.PicklingError(
+            f"Can't pickle {func}: it's not the same object as {test}"
+        )
+
+    return unpickle_function, (mod_name, qname, self_)
+
+
+def pickle_state(state):
+    return _uarray._BackendState._unpickle, state._pickle()
+
+
+def pickle_set_backend_context(ctx):
+    return _SetBackendContext, ctx._pickle()
+
+
+def pickle_skip_backend_context(ctx):
+    return _SkipBackendContext, ctx._pickle()
+
+
+copyreg.pickle(_Function, pickle_function)
+copyreg.pickle(_uarray._BackendState, pickle_state)
+copyreg.pickle(_SetBackendContext, pickle_set_backend_context)
+copyreg.pickle(_SkipBackendContext, pickle_skip_backend_context)
+
+
+def get_state():
+    """
+    Returns an opaque object containing the current state of all the backends.
+
+    Can be used for synchronization between threads/processes.
+
+    See Also
+    --------
+    set_state
+        Sets the state returned by this function.
+    """
+    return _uarray.get_state()
+
+
+@contextlib.contextmanager
+def reset_state():
+    """
+    Returns a context manager that resets all state once exited.
+
+    See Also
+    --------
+    set_state
+        Context manager that sets the backend state.
+    get_state
+        Gets a state to be set by this context manager.
+    """
+    with set_state(get_state()):
+        yield
+
+
+@contextlib.contextmanager
+def set_state(state):
+    """
+    A context manager that sets the state of the backends to one returned by :obj:`get_state`.
+
+    See Also
+    --------
+    get_state
+        Gets a state to be set by this context manager.
+    """  # noqa: E501
+    old_state = get_state()
+    _uarray.set_state(state)
+    try:
+        yield
+    finally:
+        _uarray.set_state(old_state, True)
+
+
+def create_multimethod(*args, **kwargs):
+    """
+    Creates a decorator for generating multimethods.
+
+    This function creates a decorator that can be used with an argument
+    extractor in order to generate a multimethod. Other than for the
+    argument extractor, all arguments are passed on to
+    :obj:`generate_multimethod`.
+
+    See Also
+    --------
+    generate_multimethod
+        Generates a multimethod.
+    """
+
+    def wrapper(a):
+        return generate_multimethod(a, *args, **kwargs)
+
+    return wrapper
+
+
+def generate_multimethod(
+    argument_extractor: ArgumentExtractorType,
+    argument_replacer: ArgumentReplacerType,
+    domain: str,
+    default: typing.Callable | None = None,
+):
+    """
+    Generates a multimethod.
+
+    Parameters
+    ----------
+    argument_extractor : ArgumentExtractorType
+        A callable which extracts the dispatchable arguments. Extracted arguments
+        should be marked by the :obj:`Dispatchable` class. It has the same signature
+        as the desired multimethod.
+    argument_replacer : ArgumentReplacerType
+        A callable with the signature (args, kwargs, dispatchables), which should also
+        return an (args, kwargs) pair with the dispatchables replaced inside the
+        args/kwargs.
+    domain : str
+        A string value indicating the domain of this multimethod.
+    default: Optional[Callable], optional
+        The default implementation of this multimethod, where ``None`` (the default)
+        specifies there is no default implementation.
+
+    Examples
+    --------
+    In this example, ``a`` is to be dispatched over, so we return it, while marking it
+    as an ``int``.
+    The trailing comma is needed because the args have to be returned as an iterable.
+
+    >>> def override_me(a, b):
+    ...   return Dispatchable(a, int),
+
+    Next, we define the argument replacer that replaces the dispatchables inside
+    args/kwargs with the supplied ones.
+
+    >>> def override_replacer(args, kwargs, dispatchables):
+    ...     return (dispatchables[0], args[1]), {}
+
+    Next, we define the multimethod.
+
+    >>> overridden_me = generate_multimethod(
+    ...     override_me, override_replacer, "ua_examples"
+    ... )
+
+    Notice that there's no default implementation, unless you supply one.
+
+    >>> overridden_me(1, "a")
+    Traceback (most recent call last):
+        ...
+    uarray.BackendNotImplementedError: ...
+
+    >>> overridden_me2 = generate_multimethod(
+    ...     override_me, override_replacer, "ua_examples", default=lambda x, y: (x, y)
+    ... )
+    >>> overridden_me2(1, "a")
+    (1, 'a')
+
+    See Also
+    --------
+    uarray
+        See the module documentation for how to override the method by creating
+        backends.
+    """
+    kw_defaults, arg_defaults, opts = get_defaults(argument_extractor)
+    ua_func = _Function(
+        argument_extractor,
+        argument_replacer,
+        domain,
+        arg_defaults,
+        kw_defaults,
+        default,
+    )
+
+    return functools.update_wrapper(ua_func, argument_extractor)
+
+
+def set_backend(backend, coerce=False, only=False):
+    """
+    A context manager that sets the preferred backend.
+
+    Parameters
+    ----------
+    backend
+        The backend to set.
+    coerce
+        Whether or not to coerce to a specific backend's types. Implies ``only``.
+    only
+        Whether or not this should be the last backend to try.
+
+    See Also
+    --------
+    skip_backend: A context manager that allows skipping of backends.
+    set_global_backend: Set a single, global backend for a domain.
+    """
+    tid = threading.get_native_id()
+    try:
+        return backend.__ua_cache__[tid, "set", coerce, only]
+    except AttributeError:
+        backend.__ua_cache__ = {}
+    except KeyError:
+        pass
+
+    ctx = _SetBackendContext(backend, coerce, only)
+    backend.__ua_cache__[tid, "set", coerce, only] = ctx
+    return ctx
+
+
+def skip_backend(backend):
+    """
+    A context manager that allows one to skip a given backend from processing
+    entirely. This allows one to use another backend's code in a library that
+    is also a consumer of the same backend.
+
+    Parameters
+    ----------
+    backend
+        The backend to skip.
+
+    See Also
+    --------
+    set_backend: A context manager that allows setting of backends.
+    set_global_backend: Set a single, global backend for a domain.
+    """
+    tid = threading.get_native_id()
+    try:
+        return backend.__ua_cache__[tid, "skip"]
+    except AttributeError:
+        backend.__ua_cache__ = {}
+    except KeyError:
+        pass
+
+    ctx = _SkipBackendContext(backend)
+    backend.__ua_cache__[tid, "skip"] = ctx
+    return ctx
+
+
+def get_defaults(f):
+    sig = inspect.signature(f)
+    kw_defaults = {}
+    arg_defaults = []
+    opts = set()
+    for k, v in sig.parameters.items():
+        if v.default is not inspect.Parameter.empty:
+            kw_defaults[k] = v.default
+        if v.kind in (
+            inspect.Parameter.POSITIONAL_ONLY,
+            inspect.Parameter.POSITIONAL_OR_KEYWORD,
+        ):
+            arg_defaults.append(v.default)
+        opts.add(k)
+
+    return kw_defaults, tuple(arg_defaults), opts
+
+
+def set_global_backend(backend, coerce=False, only=False, *, try_last=False):
+    """
+    This utility method replaces the default backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend. This will be the first tried
+    backend outside the :obj:`set_backend` context manager.
+
+    Note that this method is not thread-safe.
+
+    .. warning::
+        We caution library authors against using this function in
+        their code. We do *not* support this use-case. This function
+        is meant to be used only by users themselves, or by a reference
+        implementation, if one exists.
+
+    Parameters
+    ----------
+    backend
+        The backend to register.
+    coerce : bool
+        Whether to coerce input types when trying this backend.
+    only : bool
+        If ``True``, no more backends will be tried if this fails.
+        Implied by ``coerce=True``.
+    try_last : bool
+        If ``True``, the global backend is tried after registered backends.
+
+    See Also
+    --------
+    set_backend: A context manager that allows setting of backends.
+    skip_backend: A context manager that allows skipping of backends.
+    """
+    _uarray.set_global_backend(backend, coerce, only, try_last)
+
+
+def register_backend(backend):
+    """
+    This utility method sets registers backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend.
+
+    Note that this method is not thread-safe.
+
+    Parameters
+    ----------
+    backend
+        The backend to register.
+    """
+    _uarray.register_backend(backend)
+
+
+def clear_backends(domain, registered=True, globals=False):
+    """
+    This utility method clears registered backends.
+
+    .. warning::
+        We caution library authors against using this function in
+        their code. We do *not* support this use-case. This function
+        is meant to be used only by users themselves.
+
+    .. warning::
+        Do NOT use this method inside a multimethod call, or the
+        program is likely to crash.
+
+    Parameters
+    ----------
+    domain : Optional[str]
+        The domain for which to de-register backends. ``None`` means
+        de-register for all domains.
+    registered : bool
+        Whether or not to clear registered backends. See :obj:`register_backend`.
+    globals : bool
+        Whether or not to clear global backends. See :obj:`set_global_backend`.
+
+    See Also
+    --------
+    register_backend : Register a backend globally.
+    set_global_backend : Set a global backend.
+    """
+    _uarray.clear_backends(domain, registered, globals)
+
+
+class Dispatchable:
+    """
+    A utility class which marks an argument with a specific dispatch type.
+
+
+    Attributes
+    ----------
+    value
+        The value of the Dispatchable.
+
+    type
+        The type of the Dispatchable.
+
+    Examples
+    --------
+    >>> x = Dispatchable(1, str)
+    >>> x
+    , value=1>
+
+    See Also
+    --------
+    all_of_type
+        Marks all unmarked parameters of a function.
+
+    mark_as
+        Allows one to create a utility function to mark as a given type.
+    """
+
+    def __init__(self, value, dispatch_type, coercible=True):
+        self.value = value
+        self.type = dispatch_type
+        self.coercible = coercible
+
+    def __getitem__(self, index):
+        return (self.type, self.value)[index]
+
+    def __str__(self):
+        return f"<{type(self).__name__}: type={self.type!r}, value={self.value!r}>"
+
+    __repr__ = __str__
+
+
+def mark_as(dispatch_type):
+    """
+    Creates a utility function to mark something as a specific type.
+
+    Examples
+    --------
+    >>> mark_int = mark_as(int)
+    >>> mark_int(1)
+    , value=1>
+    """
+    return functools.partial(Dispatchable, dispatch_type=dispatch_type)
+
+
+def all_of_type(arg_type):
+    """
+    Marks all unmarked arguments as a given type.
+
+    Examples
+    --------
+    >>> @all_of_type(str)
+    ... def f(a, b):
+    ...     return a, Dispatchable(b, int)
+    >>> f('a', 1)
+    (, value='a'>,
+     , value=1>)
+    """
+
+    def outer(func):
+        @functools.wraps(func)
+        def inner(*args, **kwargs):
+            extracted_args = func(*args, **kwargs)
+            return tuple(
+                Dispatchable(arg, arg_type)
+                if not isinstance(arg, Dispatchable)
+                else arg
+                for arg in extracted_args
+            )
+
+        return inner
+
+    return outer
+
+
+def wrap_single_convertor(convert_single):
+    """
+    Wraps a ``__ua_convert__`` defined for a single element to all elements.
+    If any of them return ``NotImplemented``, the operation is assumed to be
+    undefined.
+
+    Accepts a signature of (value, type, coerce).
+    """
+
+    @functools.wraps(convert_single)
+    def __ua_convert__(dispatchables, coerce):
+        converted = []
+        for d in dispatchables:
+            c = convert_single(d.value, d.type, coerce and d.coercible)
+
+            if c is NotImplemented:
+                return NotImplemented
+
+            converted.append(c)
+
+        return converted
+
+    return __ua_convert__
+
+
+def wrap_single_convertor_instance(convert_single):
+    """
+    Wraps a ``__ua_convert__`` defined for a single element to all elements.
+    If any of them return ``NotImplemented``, the operation is assumed to be
+    undefined.
+
+    Accepts a signature of (value, type, coerce).
+    """
+
+    @functools.wraps(convert_single)
+    def __ua_convert__(self, dispatchables, coerce):
+        converted = []
+        for d in dispatchables:
+            c = convert_single(self, d.value, d.type, coerce and d.coercible)
+
+            if c is NotImplemented:
+                return NotImplemented
+
+            converted.append(c)
+
+        return converted
+
+    return __ua_convert__
+
+
+def determine_backend(value, dispatch_type, *, domain, only=True, coerce=False):
+    """Set the backend to the first active backend that supports ``value``
+
+    This is useful for functions that call multimethods without any dispatchable
+    arguments. You can use :func:`determine_backend` to ensure the same backend
+    is used everywhere in a block of multimethod calls.
+
+    Parameters
+    ----------
+    value
+        The value being tested
+    dispatch_type
+        The dispatch type associated with ``value``, aka
+        ":ref:`marking `".
+    domain: string
+        The domain to query for backends and set.
+    coerce: bool
+        Whether or not to allow coercion to the backend's types. Implies ``only``.
+    only: bool
+        Whether or not this should be the last backend to try.
+
+    See Also
+    --------
+    set_backend: For when you know which backend to set
+
+    Notes
+    -----
+
+    Support is determined by the ``__ua_convert__`` protocol. Backends not
+    supporting the type must return ``NotImplemented`` from their
+    ``__ua_convert__`` if they don't support input of that type.
+
+    Examples
+    --------
+
+    Suppose we have two backends ``BackendA`` and ``BackendB`` each supporting
+    different types, ``TypeA`` and ``TypeB``. Neither supporting the other type:
+
+    >>> with ua.set_backend(ex.BackendA):
+    ...     ex.call_multimethod(ex.TypeB(), ex.TypeB())
+    Traceback (most recent call last):
+        ...
+    uarray.BackendNotImplementedError: ...
+
+    Now consider a multimethod that creates a new object of ``TypeA``, or
+    ``TypeB`` depending on the active backend.
+
+    >>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, ex.TypeA())
+    Traceback (most recent call last):
+        ...
+    uarray.BackendNotImplementedError: ...
+
+    ``res`` is an object of ``TypeB`` because ``BackendB`` is set in the
+    innermost with statement. So, ``call_multimethod`` fails since the types
+    don't match.
+
+    Instead, we need to first find a backend suitable for all of our objects.
+
+    >>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
+    ...     x = ex.TypeA()
+    ...     with ua.determine_backend(x, "mark", domain="ua_examples"):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, x)
+    TypeA
+
+    """
+    dispatchables = (Dispatchable(value, dispatch_type, coerce),)
+    backend = _uarray.determine_backend(domain, dispatchables, coerce)
+
+    return set_backend(backend, coerce=coerce, only=only)
+
+
+def determine_backend_multi(
+    dispatchables, *, domain, only=True, coerce=False, **kwargs
+):
+    """Set a backend supporting all ``dispatchables``
+
+    This is useful for functions that call multimethods without any dispatchable
+    arguments. You can use :func:`determine_backend_multi` to ensure the same
+    backend is used everywhere in a block of multimethod calls involving
+    multiple arrays.
+
+    Parameters
+    ----------
+    dispatchables: Sequence[Union[uarray.Dispatchable, Any]]
+        The dispatchables that must be supported
+    domain: string
+        The domain to query for backends and set.
+    coerce: bool
+        Whether or not to allow coercion to the backend's types. Implies ``only``.
+    only: bool
+        Whether or not this should be the last backend to try.
+    dispatch_type: Optional[Any]
+        The default dispatch type associated with ``dispatchables``, aka
+        ":ref:`marking `".
+
+    See Also
+    --------
+    determine_backend: For a single dispatch value
+    set_backend: For when you know which backend to set
+
+    Notes
+    -----
+
+    Support is determined by the ``__ua_convert__`` protocol. Backends not
+    supporting the type must return ``NotImplemented`` from their
+    ``__ua_convert__`` if they don't support input of that type.
+
+    Examples
+    --------
+
+    :func:`determine_backend` allows the backend to be set from a single
+    object. :func:`determine_backend_multi` allows multiple objects to be
+    checked simultaneously for support in the backend. Suppose we have a
+    ``BackendAB`` which supports ``TypeA`` and ``TypeB`` in the same call,
+    and a ``BackendBC`` that doesn't support ``TypeA``.
+
+    >>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
+    ...     a, b = ex.TypeA(), ex.TypeB()
+    ...     with ua.determine_backend_multi(
+    ...         [ua.Dispatchable(a, "mark"), ua.Dispatchable(b, "mark")],
+    ...         domain="ua_examples"
+    ...     ):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, a, b)
+    TypeA
+
+    This won't call ``BackendBC`` because it doesn't support ``TypeA``.
+
+    We can also use leave out the ``ua.Dispatchable`` if we specify the
+    default ``dispatch_type`` for the ``dispatchables`` argument.
+
+    >>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
+    ...     a, b = ex.TypeA(), ex.TypeB()
+    ...     with ua.determine_backend_multi(
+    ...         [a, b], dispatch_type="mark", domain="ua_examples"
+    ...     ):
+    ...         res = ex.creation_multimethod()
+    ...         ex.call_multimethod(res, a, b)
+    TypeA
+
+    """
+    if "dispatch_type" in kwargs:
+        disp_type = kwargs.pop("dispatch_type")
+        dispatchables = tuple(
+            d if isinstance(d, Dispatchable) else Dispatchable(d, disp_type)
+            for d in dispatchables
+        )
+    else:
+        dispatchables = tuple(dispatchables)
+        if not all(isinstance(d, Dispatchable) for d in dispatchables):
+            raise TypeError("dispatchables must be instances of uarray.Dispatchable")
+
+    if len(kwargs) != 0:
+        raise TypeError(f"Received unexpected keyword arguments: {kwargs}")
+
+    backend = _uarray.determine_backend(domain, dispatchables, coerce)
+
+    return set_backend(backend, coerce=coerce, only=only)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_util.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d16072007395221fdf7a1f5352fd2838fd7a6ec
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/_util.py
@@ -0,0 +1,1179 @@
+import re
+from contextlib import contextmanager
+import functools
+import operator
+import warnings
+import numbers
+from collections import namedtuple
+import inspect
+import math
+from typing import TypeAlias, TypeVar
+
+import numpy as np
+from scipy._lib._array_api import array_namespace, is_numpy, xp_size
+from scipy._lib._docscrape import FunctionDoc, Parameter
+
+
+AxisError: type[Exception]
+ComplexWarning: type[Warning]
+VisibleDeprecationWarning: type[Warning]
+
+if np.lib.NumpyVersion(np.__version__) >= '1.25.0':
+    from numpy.exceptions import (
+        AxisError, ComplexWarning, VisibleDeprecationWarning,
+        DTypePromotionError
+    )
+else:
+    from numpy import (  # type: ignore[attr-defined, no-redef]
+        AxisError, ComplexWarning, VisibleDeprecationWarning  # noqa: F401
+    )
+    DTypePromotionError = TypeError  # type: ignore
+
+np_long: type
+np_ulong: type
+
+if np.lib.NumpyVersion(np.__version__) >= "2.0.0.dev0":
+    try:
+        with warnings.catch_warnings():
+            warnings.filterwarnings(
+                "ignore",
+                r".*In the future `np\.long` will be defined as.*",
+                FutureWarning,
+            )
+            np_long = np.long  # type: ignore[attr-defined]
+            np_ulong = np.ulong  # type: ignore[attr-defined]
+    except AttributeError:
+            np_long = np.int_
+            np_ulong = np.uint
+else:
+    np_long = np.int_
+    np_ulong = np.uint
+
+IntNumber = int | np.integer
+DecimalNumber = float | np.floating | np.integer
+
+copy_if_needed: bool | None
+
+if np.lib.NumpyVersion(np.__version__) >= "2.0.0":
+    copy_if_needed = None
+elif np.lib.NumpyVersion(np.__version__) < "1.28.0":
+    copy_if_needed = False
+else:
+    # 2.0.0 dev versions, handle cases where copy may or may not exist
+    try:
+        np.array([1]).__array__(copy=None)  # type: ignore[call-overload]
+        copy_if_needed = None
+    except TypeError:
+        copy_if_needed = False
+
+
+_RNG: TypeAlias = np.random.Generator | np.random.RandomState
+SeedType: TypeAlias = IntNumber | _RNG | None
+
+GeneratorType = TypeVar("GeneratorType", bound=_RNG)
+
+# Since Generator was introduced in numpy 1.17, the following condition is needed for
+# backward compatibility
+try:
+    from numpy.random import Generator as Generator
+except ImportError:
+    class Generator:  # type: ignore[no-redef]
+        pass
+
+
+def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):
+    """Return elements chosen from two possibilities depending on a condition
+
+    Equivalent to ``f(*arrays) if cond else fillvalue`` performed elementwise.
+
+    Parameters
+    ----------
+    cond : array
+        The condition (expressed as a boolean array).
+    arrays : tuple of array
+        Arguments to `f` (and `f2`). Must be broadcastable with `cond`.
+    f : callable
+        Where `cond` is True, output will be ``f(arr1[cond], arr2[cond], ...)``
+    fillvalue : object
+        If provided, value with which to fill output array where `cond` is
+        not True.
+    f2 : callable
+        If provided, output will be ``f2(arr1[cond], arr2[cond], ...)`` where
+        `cond` is not True.
+
+    Returns
+    -------
+    out : array
+        An array with elements from the output of `f` where `cond` is True
+        and `fillvalue` (or elements from the output of `f2`) elsewhere. The
+        returned array has data type determined by Type Promotion Rules
+        with the output of `f` and `fillvalue` (or the output of `f2`).
+
+    Notes
+    -----
+    ``xp.where(cond, x, fillvalue)`` requires explicitly forming `x` even where
+    `cond` is False. This function evaluates ``f(arr1[cond], arr2[cond], ...)``
+    onle where `cond` ``is True.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
+    >>> def f(a, b):
+    ...     return a*b
+    >>> _lazywhere(a > 2, (a, b), f, np.nan)
+    array([ nan,  nan,  21.,  32.])
+
+    """
+    xp = array_namespace(cond, *arrays)
+
+    if (f2 is fillvalue is None) or (f2 is not None and fillvalue is not None):
+        raise ValueError("Exactly one of `fillvalue` or `f2` must be given.")
+
+    args = xp.broadcast_arrays(cond, *arrays)
+    bool_dtype = xp.asarray([True]).dtype  # numpy 1.xx doesn't have `bool`
+    cond, arrays = xp.astype(args[0], bool_dtype, copy=False), args[1:]
+
+    temp1 = xp.asarray(f(*(arr[cond] for arr in arrays)))
+
+    if f2 is None:
+        # If `fillvalue` is a Python scalar and we convert to `xp.asarray`, it gets the
+        # default `int` or `float` type of `xp`, so `result_type` could be wrong.
+        # `result_type` should/will handle mixed array/Python scalars;
+        # remove this special logic when it does.
+        if type(fillvalue) in {bool, int, float, complex}:
+            with np.errstate(invalid='ignore'):
+                dtype = (temp1 * fillvalue).dtype
+        else:
+           dtype = xp.result_type(temp1.dtype, fillvalue)
+        out = xp.full(cond.shape, dtype=dtype,
+                      fill_value=xp.asarray(fillvalue, dtype=dtype))
+    else:
+        ncond = ~cond
+        temp2 = xp.asarray(f2(*(arr[ncond] for arr in arrays)))
+        dtype = xp.result_type(temp1, temp2)
+        out = xp.empty(cond.shape, dtype=dtype)
+        out[ncond] = temp2
+
+    out[cond] = temp1
+
+    return out
+
+
+def _lazyselect(condlist, choicelist, arrays, default=0):
+    """
+    Mimic `np.select(condlist, choicelist)`.
+
+    Notice, it assumes that all `arrays` are of the same shape or can be
+    broadcasted together.
+
+    All functions in `choicelist` must accept array arguments in the order
+    given in `arrays` and must return an array of the same shape as broadcasted
+    `arrays`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> x = np.arange(6)
+    >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
+    array([  0,   1,   4,   0,  64, 125])
+
+    >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
+    array([   0.,    1.,    4.,   0.,   64.,  125.])
+
+    >>> a = -np.ones_like(x)
+    >>> _lazyselect([x < 3, x > 3],
+    ...             [lambda x, a: x**2, lambda x, a: a * x**3],
+    ...             (x, a), default=np.nan)
+    array([   0.,    1.,    4.,   nan,  -64., -125.])
+
+    """
+    arrays = np.broadcast_arrays(*arrays)
+    tcode = np.mintypecode([a.dtype.char for a in arrays])
+    out = np.full(np.shape(arrays[0]), fill_value=default, dtype=tcode)
+    for func, cond in zip(choicelist, condlist):
+        if np.all(cond is False):
+            continue
+        cond, _ = np.broadcast_arrays(cond, arrays[0])
+        temp = tuple(np.extract(cond, arr) for arr in arrays)
+        np.place(out, cond, func(*temp))
+    return out
+
+
+def _aligned_zeros(shape, dtype=float, order="C", align=None):
+    """Allocate a new ndarray with aligned memory.
+
+    Primary use case for this currently is working around a f2py issue
+    in NumPy 1.9.1, where dtype.alignment is such that np.zeros() does
+    not necessarily create arrays aligned up to it.
+
+    """
+    dtype = np.dtype(dtype)
+    if align is None:
+        align = dtype.alignment
+    if not hasattr(shape, '__len__'):
+        shape = (shape,)
+    size = functools.reduce(operator.mul, shape) * dtype.itemsize
+    buf = np.empty(size + align + 1, np.uint8)
+    offset = buf.__array_interface__['data'][0] % align
+    if offset != 0:
+        offset = align - offset
+    # Note: slices producing 0-size arrays do not necessarily change
+    # data pointer --- so we use and allocate size+1
+    buf = buf[offset:offset+size+1][:-1]
+    data = np.ndarray(shape, dtype, buf, order=order)
+    data.fill(0)
+    return data
+
+
+def _prune_array(array):
+    """Return an array equivalent to the input array. If the input
+    array is a view of a much larger array, copy its contents to a
+    newly allocated array. Otherwise, return the input unchanged.
+    """
+    if array.base is not None and array.size < array.base.size // 2:
+        return array.copy()
+    return array
+
+
+def float_factorial(n: int) -> float:
+    """Compute the factorial and return as a float
+
+    Returns infinity when result is too large for a double
+    """
+    return float(math.factorial(n)) if n < 171 else np.inf
+
+
+_rng_desc = (
+    r"""If `rng` is passed by keyword, types other than `numpy.random.Generator` are
+    passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+    If `rng` is already a ``Generator`` instance, then the provided instance is
+    used. Specify `rng` for repeatable function behavior.
+
+    If this argument is passed by position or `{old_name}` is passed by keyword,
+    legacy behavior for the argument `{old_name}` applies:
+
+    - If `{old_name}` is None (or `numpy.random`), the `numpy.random.RandomState`
+      singleton is used.
+    - If `{old_name}` is an int, a new ``RandomState`` instance is used,
+      seeded with `{old_name}`.
+    - If `{old_name}` is already a ``Generator`` or ``RandomState`` instance then
+      that instance is used.
+
+    .. versionchanged:: 1.15.0
+        As part of the `SPEC-007 `_
+        transition from use of `numpy.random.RandomState` to
+        `numpy.random.Generator`, this keyword was changed from `{old_name}` to `rng`.
+        For an interim period, both keywords will continue to work, although only one
+        may be specified at a time. After the interim period, function calls using the
+        `{old_name}` keyword will emit warnings. The behavior of both `{old_name}` and
+        `rng` are outlined above, but only the `rng` keyword should be used in new code.
+        """
+)
+
+
+# SPEC 7
+def _transition_to_rng(old_name, *, position_num=None, end_version=None,
+                       replace_doc=True):
+    """Example decorator to transition from old PRNG usage to new `rng` behavior
+
+    Suppose the decorator is applied to a function that used to accept parameter
+    `old_name='random_state'` either by keyword or as a positional argument at
+    `position_num=1`. At the time of application, the name of the argument in the
+    function signature is manually changed to the new name, `rng`. If positional
+    use was allowed before, this is not changed.*
+
+    - If the function is called with both `random_state` and `rng`, the decorator
+      raises an error.
+    - If `random_state` is provided as a keyword argument, the decorator passes
+      `random_state` to the function's `rng` argument as a keyword. If `end_version`
+      is specified, the decorator will emit a `DeprecationWarning` about the
+      deprecation of keyword `random_state`.
+    - If `random_state` is provided as a positional argument, the decorator passes
+      `random_state` to the function's `rng` argument by position. If `end_version`
+      is specified, the decorator will emit a `FutureWarning` about the changing
+      interpretation of the argument.
+    - If `rng` is provided as a keyword argument, the decorator validates `rng` using
+      `numpy.random.default_rng` before passing it to the function.
+    - If `end_version` is specified and neither `random_state` nor `rng` is provided
+      by the user, the decorator checks whether `np.random.seed` has been used to set
+      the global seed. If so, it emits a `FutureWarning`, noting that usage of
+      `numpy.random.seed` will eventually have no effect. Either way, the decorator
+      calls the function without explicitly passing the `rng` argument.
+
+    If `end_version` is specified, a user must pass `rng` as a keyword to avoid
+    warnings.
+
+    After the deprecation period, the decorator can be removed, and the function
+    can simply validate the `rng` argument by calling `np.random.default_rng(rng)`.
+
+    * A `FutureWarning` is emitted when the PRNG argument is used by
+      position. It indicates that the "Hinsen principle" (same
+      code yielding different results in two versions of the software)
+      will be violated, unless positional use is deprecated. Specifically:
+
+      - If `None` is passed by position and `np.random.seed` has been used,
+        the function will change from being seeded to being unseeded.
+      - If an integer is passed by position, the random stream will change.
+      - If `np.random` or an instance of `RandomState` is passed by position,
+        an error will be raised.
+
+      We suggest that projects consider deprecating positional use of
+      `random_state`/`rng` (i.e., change their function signatures to
+      ``def my_func(..., *, rng=None)``); that might not make sense
+      for all projects, so this SPEC does not make that
+      recommendation, neither does this decorator enforce it.
+
+    Parameters
+    ----------
+    old_name : str
+        The old name of the PRNG argument (e.g. `seed` or `random_state`).
+    position_num : int, optional
+        The (0-indexed) position of the old PRNG argument (if accepted by position).
+        Maintainers are welcome to eliminate this argument and use, for example,
+        `inspect`, if preferred.
+    end_version : str, optional
+        The full version number of the library when the behavior described in
+        `DeprecationWarning`s and `FutureWarning`s will take effect. If left
+        unspecified, no warnings will be emitted by the decorator.
+    replace_doc : bool, default: True
+        Whether the decorator should replace the documentation for parameter `rng` with
+        `_rng_desc` (defined above), which documents both new `rng` keyword behavior
+        and typical legacy `random_state`/`seed` behavior. If True, manually replace
+        the first paragraph of the function's old `random_state`/`seed` documentation
+        with the desired *final* `rng` documentation; this way, no changes to
+        documentation are needed when the decorator is removed. Documentation of `rng`
+        after the first blank line is preserved. Use False if the function's old
+        `random_state`/`seed` behavior does not match that described by `_rng_desc`.
+
+    """
+    NEW_NAME = "rng"
+
+    cmn_msg = (
+        "To silence this warning and ensure consistent behavior in SciPy "
+        f"{end_version}, control the RNG using argument `{NEW_NAME}`. Arguments passed "
+        f"to keyword `{NEW_NAME}` will be validated by `np.random.default_rng`, so the "
+        "behavior corresponding with a given value may change compared to use of "
+        f"`{old_name}`. For example, "
+        "1) `None` will result in unpredictable random numbers, "
+        "2) an integer will result in a different stream of random numbers, (with the "
+        "same distribution), and "
+        "3) `np.random` or `RandomState` instances will result in an error. "
+        "See the documentation of `default_rng` for more information."
+    )
+
+    def decorator(fun):
+        @functools.wraps(fun)
+        def wrapper(*args, **kwargs):
+            # Determine how PRNG was passed
+            as_old_kwarg = old_name in kwargs
+            as_new_kwarg = NEW_NAME in kwargs
+            as_pos_arg = position_num is not None and len(args) >= position_num + 1
+            emit_warning = end_version is not None
+
+            # Can only specify PRNG one of the three ways
+            if int(as_old_kwarg) + int(as_new_kwarg) + int(as_pos_arg) > 1:
+                message = (
+                    f"{fun.__name__}() got multiple values for "
+                    f"argument now known as `{NEW_NAME}`. Specify one of "
+                    f"`{NEW_NAME}` or `{old_name}`."
+                )
+                raise TypeError(message)
+
+            # Check whether global random state has been set
+            global_seed_set = np.random.mtrand._rand._bit_generator._seed_seq is None
+
+            if as_old_kwarg:  # warn about deprecated use of old kwarg
+                kwargs[NEW_NAME] = kwargs.pop(old_name)
+                if emit_warning:
+                    message = (
+                        f"Use of keyword argument `{old_name}` is "
+                        f"deprecated and replaced by `{NEW_NAME}`.  "
+                        f"Support for `{old_name}` will be removed "
+                        f"in SciPy {end_version}. "
+                    ) + cmn_msg
+                    warnings.warn(message, DeprecationWarning, stacklevel=2)
+
+            elif as_pos_arg:
+                # Warn about changing meaning of positional arg
+
+                # Note that this decorator does not deprecate positional use of the
+                # argument; it only warns that the behavior will change in the future.
+                # Simultaneously transitioning to keyword-only use is another option.
+
+                arg = args[position_num]
+                # If the argument is None and the global seed wasn't set, or if the
+                # argument is one of a few new classes, the user will not notice change
+                # in behavior.
+                ok_classes = (
+                    np.random.Generator,
+                    np.random.SeedSequence,
+                    np.random.BitGenerator,
+                )
+                if (arg is None and not global_seed_set) or isinstance(arg, ok_classes):
+                    pass
+                elif emit_warning:
+                    message = (
+                        f"Positional use of `{NEW_NAME}` (formerly known as "
+                        f"`{old_name}`) is still allowed, but the behavior is "
+                        "changing: the argument will be normalized using "
+                        f"`np.random.default_rng` beginning in SciPy {end_version}, "
+                        "and the resulting `Generator` will be used to generate "
+                        "random numbers."
+                    ) + cmn_msg
+                    warnings.warn(message, FutureWarning, stacklevel=2)
+
+            elif as_new_kwarg:  # no warnings; this is the preferred use
+                # After the removal of the decorator, normalization with
+                # np.random.default_rng will be done inside the decorated function
+                kwargs[NEW_NAME] = np.random.default_rng(kwargs[NEW_NAME])
+
+            elif global_seed_set and emit_warning:
+                # Emit FutureWarning if `np.random.seed` was used and no PRNG was passed
+                message = (
+                    "The NumPy global RNG was seeded by calling "
+                    f"`np.random.seed`. Beginning in {end_version}, this "
+                    "function will no longer use the global RNG."
+                ) + cmn_msg
+                warnings.warn(message, FutureWarning, stacklevel=2)
+
+            return fun(*args, **kwargs)
+
+        if replace_doc:
+            doc = FunctionDoc(wrapper)
+            parameter_names = [param.name for param in doc['Parameters']]
+            if 'rng' in parameter_names:
+                _type = "{None, int, `numpy.random.Generator`}, optional"
+                _desc = _rng_desc.replace("{old_name}", old_name)
+                old_doc = doc['Parameters'][parameter_names.index('rng')].desc
+                old_doc_keep = old_doc[old_doc.index("") + 1:] if "" in old_doc else []
+                new_doc = [_desc] + old_doc_keep
+                _rng_parameter_doc = Parameter('rng', _type, new_doc)
+                doc['Parameters'][parameter_names.index('rng')] = _rng_parameter_doc
+                doc = str(doc).split("\n", 1)[1]  # remove signature
+                wrapper.__doc__ = str(doc)
+        return wrapper
+
+    return decorator
+
+
+# copy-pasted from scikit-learn utils/validation.py
+def check_random_state(seed):
+    """Turn `seed` into a `np.random.RandomState` instance.
+
+    Parameters
+    ----------
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    Returns
+    -------
+    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
+        Random number generator.
+
+    """
+    if seed is None or seed is np.random:
+        return np.random.mtrand._rand
+    if isinstance(seed, numbers.Integral | np.integer):
+        return np.random.RandomState(seed)
+    if isinstance(seed, np.random.RandomState | np.random.Generator):
+        return seed
+
+    raise ValueError(f"'{seed}' cannot be used to seed a numpy.random.RandomState"
+                     " instance")
+
+
+def _asarray_validated(a, check_finite=True,
+                       sparse_ok=False, objects_ok=False, mask_ok=False,
+                       as_inexact=False):
+    """
+    Helper function for SciPy argument validation.
+
+    Many SciPy linear algebra functions do support arbitrary array-like
+    input arguments. Examples of commonly unsupported inputs include
+    matrices containing inf/nan, sparse matrix representations, and
+    matrices with complicated elements.
+
+    Parameters
+    ----------
+    a : array_like
+        The array-like input.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default: True
+    sparse_ok : bool, optional
+        True if scipy sparse matrices are allowed.
+    objects_ok : bool, optional
+        True if arrays with dype('O') are allowed.
+    mask_ok : bool, optional
+        True if masked arrays are allowed.
+    as_inexact : bool, optional
+        True to convert the input array to a np.inexact dtype.
+
+    Returns
+    -------
+    ret : ndarray
+        The converted validated array.
+
+    """
+    if not sparse_ok:
+        import scipy.sparse
+        if scipy.sparse.issparse(a):
+            msg = ('Sparse arrays/matrices are not supported by this function. '
+                   'Perhaps one of the `scipy.sparse.linalg` functions '
+                   'would work instead.')
+            raise ValueError(msg)
+    if not mask_ok:
+        if np.ma.isMaskedArray(a):
+            raise ValueError('masked arrays are not supported')
+    toarray = np.asarray_chkfinite if check_finite else np.asarray
+    a = toarray(a)
+    if not objects_ok:
+        if a.dtype is np.dtype('O'):
+            raise ValueError('object arrays are not supported')
+    if as_inexact:
+        if not np.issubdtype(a.dtype, np.inexact):
+            a = toarray(a, dtype=np.float64)
+    return a
+
+
+def _validate_int(k, name, minimum=None):
+    """
+    Validate a scalar integer.
+
+    This function can be used to validate an argument to a function
+    that expects the value to be an integer.  It uses `operator.index`
+    to validate the value (so, for example, k=2.0 results in a
+    TypeError).
+
+    Parameters
+    ----------
+    k : int
+        The value to be validated.
+    name : str
+        The name of the parameter.
+    minimum : int, optional
+        An optional lower bound.
+    """
+    try:
+        k = operator.index(k)
+    except TypeError:
+        raise TypeError(f'{name} must be an integer.') from None
+    if minimum is not None and k < minimum:
+        raise ValueError(f'{name} must be an integer not less '
+                         f'than {minimum}') from None
+    return k
+
+
+# Add a replacement for inspect.getfullargspec()/
+# The version below is borrowed from Django,
+# https://github.com/django/django/pull/4846.
+
+# Note an inconsistency between inspect.getfullargspec(func) and
+# inspect.signature(func). If `func` is a bound method, the latter does *not*
+# list `self` as a first argument, while the former *does*.
+# Hence, cook up a common ground replacement: `getfullargspec_no_self` which
+# mimics `inspect.getfullargspec` but does not list `self`.
+#
+# This way, the caller code does not need to know whether it uses a legacy
+# .getfullargspec or a bright and shiny .signature.
+
+FullArgSpec = namedtuple('FullArgSpec',
+                         ['args', 'varargs', 'varkw', 'defaults',
+                          'kwonlyargs', 'kwonlydefaults', 'annotations'])
+
+
+def getfullargspec_no_self(func):
+    """inspect.getfullargspec replacement using inspect.signature.
+
+    If func is a bound method, do not list the 'self' parameter.
+
+    Parameters
+    ----------
+    func : callable
+        A callable to inspect
+
+    Returns
+    -------
+    fullargspec : FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                              kwonlydefaults, annotations)
+
+        NOTE: if the first argument of `func` is self, it is *not*, I repeat
+        *not*, included in fullargspec.args.
+        This is done for consistency between inspect.getargspec() under
+        Python 2.x, and inspect.signature() under Python 3.x.
+
+    """
+    sig = inspect.signature(func)
+    args = [
+        p.name for p in sig.parameters.values()
+        if p.kind in [inspect.Parameter.POSITIONAL_OR_KEYWORD,
+                      inspect.Parameter.POSITIONAL_ONLY]
+    ]
+    varargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_POSITIONAL
+    ]
+    varargs = varargs[0] if varargs else None
+    varkw = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.VAR_KEYWORD
+    ]
+    varkw = varkw[0] if varkw else None
+    defaults = tuple(
+        p.default for p in sig.parameters.values()
+        if (p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD and
+            p.default is not p.empty)
+    ) or None
+    kwonlyargs = [
+        p.name for p in sig.parameters.values()
+        if p.kind == inspect.Parameter.KEYWORD_ONLY
+    ]
+    kwdefaults = {p.name: p.default for p in sig.parameters.values()
+                  if p.kind == inspect.Parameter.KEYWORD_ONLY and
+                  p.default is not p.empty}
+    annotations = {p.name: p.annotation for p in sig.parameters.values()
+                   if p.annotation is not p.empty}
+    return FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
+                       kwdefaults or None, annotations)
+
+
+class _FunctionWrapper:
+    """
+    Object to wrap user's function, allowing picklability
+    """
+    def __init__(self, f, args):
+        self.f = f
+        self.args = [] if args is None else args
+
+    def __call__(self, x):
+        return self.f(x, *self.args)
+
+
+class MapWrapper:
+    """
+    Parallelisation wrapper for working with map-like callables, such as
+    `multiprocessing.Pool.map`.
+
+    Parameters
+    ----------
+    pool : int or map-like callable
+        If `pool` is an integer, then it specifies the number of threads to
+        use for parallelization. If ``int(pool) == 1``, then no parallel
+        processing is used and the map builtin is used.
+        If ``pool == -1``, then the pool will utilize all available CPUs.
+        If `pool` is a map-like callable that follows the same
+        calling sequence as the built-in map function, then this callable is
+        used for parallelization.
+    """
+    def __init__(self, pool=1):
+        self.pool = None
+        self._mapfunc = map
+        self._own_pool = False
+
+        if callable(pool):
+            self.pool = pool
+            self._mapfunc = self.pool
+        else:
+            from multiprocessing import Pool
+            # user supplies a number
+            if int(pool) == -1:
+                # use as many processors as possible
+                self.pool = Pool()
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            elif int(pool) == 1:
+                pass
+            elif int(pool) > 1:
+                # use the number of processors requested
+                self.pool = Pool(processes=int(pool))
+                self._mapfunc = self.pool.map
+                self._own_pool = True
+            else:
+                raise RuntimeError("Number of workers specified must be -1,"
+                                   " an int >= 1, or an object with a 'map' "
+                                   "method")
+
+    def __enter__(self):
+        return self
+
+    def terminate(self):
+        if self._own_pool:
+            self.pool.terminate()
+
+    def join(self):
+        if self._own_pool:
+            self.pool.join()
+
+    def close(self):
+        if self._own_pool:
+            self.pool.close()
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        if self._own_pool:
+            self.pool.close()
+            self.pool.terminate()
+
+    def __call__(self, func, iterable):
+        # only accept one iterable because that's all Pool.map accepts
+        try:
+            return self._mapfunc(func, iterable)
+        except TypeError as e:
+            # wrong number of arguments
+            raise TypeError("The map-like callable must be of the"
+                            " form f(func, iterable)") from e
+
+
+def rng_integers(gen, low, high=None, size=None, dtype='int64',
+                 endpoint=False):
+    """
+    Return random integers from low (inclusive) to high (exclusive), or if
+    endpoint=True, low (inclusive) to high (inclusive). Replaces
+    `RandomState.randint` (with endpoint=False) and
+    `RandomState.random_integers` (with endpoint=True).
+
+    Return random integers from the "discrete uniform" distribution of the
+    specified dtype. If high is None (the default), then results are from
+    0 to low.
+
+    Parameters
+    ----------
+    gen : {None, np.random.RandomState, np.random.Generator}
+        Random number generator. If None, then the np.random.RandomState
+        singleton is used.
+    low : int or array-like of ints
+        Lowest (signed) integers to be drawn from the distribution (unless
+        high=None, in which case this parameter is 0 and this value is used
+        for high).
+    high : int or array-like of ints
+        If provided, one above the largest (signed) integer to be drawn from
+        the distribution (see above for behavior if high=None). If array-like,
+        must contain integer values.
+    size : array-like of ints, optional
+        Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
+        samples are drawn. Default is None, in which case a single value is
+        returned.
+    dtype : {str, dtype}, optional
+        Desired dtype of the result. All dtypes are determined by their name,
+        i.e., 'int64', 'int', etc, so byteorder is not available and a specific
+        precision may have different C types depending on the platform.
+        The default value is 'int64'.
+    endpoint : bool, optional
+        If True, sample from the interval [low, high] instead of the default
+        [low, high) Defaults to False.
+
+    Returns
+    -------
+    out: int or ndarray of ints
+        size-shaped array of random integers from the appropriate distribution,
+        or a single such random int if size not provided.
+    """
+    if isinstance(gen, Generator):
+        return gen.integers(low, high=high, size=size, dtype=dtype,
+                            endpoint=endpoint)
+    else:
+        if gen is None:
+            # default is RandomState singleton used by np.random.
+            gen = np.random.mtrand._rand
+        if endpoint:
+            # inclusive of endpoint
+            # remember that low and high can be arrays, so don't modify in
+            # place
+            if high is None:
+                return gen.randint(low + 1, size=size, dtype=dtype)
+            if high is not None:
+                return gen.randint(low, high=high + 1, size=size, dtype=dtype)
+
+        # exclusive
+        return gen.randint(low, high=high, size=size, dtype=dtype)
+
+
+@contextmanager
+def _fixed_default_rng(seed=1638083107694713882823079058616272161):
+    """Context with a fixed np.random.default_rng seed."""
+    orig_fun = np.random.default_rng
+    np.random.default_rng = lambda seed=seed: orig_fun(seed)
+    try:
+        yield
+    finally:
+        np.random.default_rng = orig_fun
+
+
+def _rng_html_rewrite(func):
+    """Rewrite the HTML rendering of ``np.random.default_rng``.
+
+    This is intended to decorate
+    ``numpydoc.docscrape_sphinx.SphinxDocString._str_examples``.
+
+    Examples are only run by Sphinx when there are plot involved. Even so,
+    it does not change the result values getting printed.
+    """
+    # hexadecimal or number seed, case-insensitive
+    pattern = re.compile(r'np.random.default_rng\((0x[0-9A-F]+|\d+)\)', re.I)
+
+    def _wrapped(*args, **kwargs):
+        res = func(*args, **kwargs)
+        lines = [
+            re.sub(pattern, 'np.random.default_rng()', line)
+            for line in res
+        ]
+        return lines
+
+    return _wrapped
+
+
+def _argmin(a, keepdims=False, axis=None):
+    """
+    argmin with a `keepdims` parameter.
+
+    See https://github.com/numpy/numpy/issues/8710
+
+    If axis is not None, a.shape[axis] must be greater than 0.
+    """
+    res = np.argmin(a, axis=axis)
+    if keepdims and axis is not None:
+        res = np.expand_dims(res, axis=axis)
+    return res
+
+
+def _first_nonnan(a, axis):
+    """
+    Return the first non-nan value along the given axis.
+
+    If a slice is all nan, nan is returned for that slice.
+
+    The shape of the return value corresponds to ``keepdims=True``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> nan = np.nan
+    >>> a = np.array([[ 3.,  3., nan,  3.],
+                      [ 1., nan,  2.,  4.],
+                      [nan, nan,  9., -1.],
+                      [nan,  5.,  4.,  3.],
+                      [ 2.,  2.,  2.,  2.],
+                      [nan, nan, nan, nan]])
+    >>> _first_nonnan(a, axis=0)
+    array([[3., 3., 2., 3.]])
+    >>> _first_nonnan(a, axis=1)
+    array([[ 3.],
+           [ 1.],
+           [ 9.],
+           [ 5.],
+           [ 2.],
+           [nan]])
+    """
+    k = _argmin(np.isnan(a), axis=axis, keepdims=True)
+    return np.take_along_axis(a, k, axis=axis)
+
+
+def _nan_allsame(a, axis, keepdims=False):
+    """
+    Determine if the values along an axis are all the same.
+
+    nan values are ignored.
+
+    `a` must be a numpy array.
+
+    `axis` is assumed to be normalized; that is, 0 <= axis < a.ndim.
+
+    For an axis of length 0, the result is True.  That is, we adopt the
+    convention that ``allsame([])`` is True. (There are no values in the
+    input that are different.)
+
+    `True` is returned for slices that are all nan--not because all the
+    values are the same, but because this is equivalent to ``allsame([])``.
+
+    Examples
+    --------
+    >>> from numpy import nan, array
+    >>> a = array([[ 3.,  3., nan,  3.],
+    ...            [ 1., nan,  2.,  4.],
+    ...            [nan, nan,  9., -1.],
+    ...            [nan,  5.,  4.,  3.],
+    ...            [ 2.,  2.,  2.,  2.],
+    ...            [nan, nan, nan, nan]])
+    >>> _nan_allsame(a, axis=1, keepdims=True)
+    array([[ True],
+           [False],
+           [False],
+           [False],
+           [ True],
+           [ True]])
+    """
+    if axis is None:
+        if a.size == 0:
+            return True
+        a = a.ravel()
+        axis = 0
+    else:
+        shp = a.shape
+        if shp[axis] == 0:
+            shp = shp[:axis] + (1,)*keepdims + shp[axis + 1:]
+            return np.full(shp, fill_value=True, dtype=bool)
+    a0 = _first_nonnan(a, axis=axis)
+    return ((a0 == a) | np.isnan(a)).all(axis=axis, keepdims=keepdims)
+
+
+def _contains_nan(a, nan_policy='propagate', policies=None, *,
+                  xp_omit_okay=False, xp=None):
+    # Regarding `xp_omit_okay`: Temporarily, while `_axis_nan_policy` does not
+    # handle non-NumPy arrays, most functions that call `_contains_nan` want
+    # it to raise an error if `nan_policy='omit'` and `xp` is not `np`.
+    # Some functions support `nan_policy='omit'` natively, so setting this to
+    # `True` prevents the error from being raised.
+    if xp is None:
+        xp = array_namespace(a)
+    not_numpy = not is_numpy(xp)
+
+    if policies is None:
+        policies = {'propagate', 'raise', 'omit'}
+    if nan_policy not in policies:
+        raise ValueError(f"nan_policy must be one of {set(policies)}.")
+
+    if xp_size(a) == 0:
+        contains_nan = False
+    elif xp.isdtype(a.dtype, "real floating"):
+        # Faster and less memory-intensive than xp.any(xp.isnan(a)), and unlike other
+        # reductions, `max`/`min` won't return NaN unless there is a NaN in the data.
+        contains_nan = xp.isnan(xp.max(a))
+    elif xp.isdtype(a.dtype, "complex floating"):
+        # Typically `real` and `imag` produce views; otherwise, `xp.any(xp.isnan(a))`
+        # would be more efficient.
+        contains_nan = xp.isnan(xp.max(xp.real(a))) | xp.isnan(xp.max(xp.imag(a)))
+    elif is_numpy(xp) and np.issubdtype(a.dtype, object):
+        contains_nan = False
+        for el in a.ravel():
+            # isnan doesn't work on non-numeric elements
+            if np.issubdtype(type(el), np.number) and np.isnan(el):
+                contains_nan = True
+                break
+    else:
+        # Only `object` and `inexact` arrays can have NaNs
+        contains_nan = False
+
+    if contains_nan and nan_policy == 'raise':
+        raise ValueError("The input contains nan values")
+
+    if not xp_omit_okay and not_numpy and contains_nan and nan_policy=='omit':
+        message = "`nan_policy='omit' is incompatible with non-NumPy arrays."
+        raise ValueError(message)
+
+    return contains_nan, nan_policy
+
+
+def _rename_parameter(old_name, new_name, dep_version=None):
+    """
+    Generate decorator for backward-compatible keyword renaming.
+
+    Apply the decorator generated by `_rename_parameter` to functions with a
+    recently renamed parameter to maintain backward-compatibility.
+
+    After decoration, the function behaves as follows:
+    If only the new parameter is passed into the function, behave as usual.
+    If only the old parameter is passed into the function (as a keyword), raise
+    a DeprecationWarning if `dep_version` is provided, and behave as usual
+    otherwise.
+    If both old and new parameters are passed into the function, raise a
+    DeprecationWarning if `dep_version` is provided, and raise the appropriate
+    TypeError (function got multiple values for argument).
+
+    Parameters
+    ----------
+    old_name : str
+        Old name of parameter
+    new_name : str
+        New name of parameter
+    dep_version : str, optional
+        Version of SciPy in which old parameter was deprecated in the format
+        'X.Y.Z'. If supplied, the deprecation message will indicate that
+        support for the old parameter will be removed in version 'X.Y+2.Z'
+
+    Notes
+    -----
+    Untested with functions that accept *args. Probably won't work as written.
+
+    """
+    def decorator(fun):
+        @functools.wraps(fun)
+        def wrapper(*args, **kwargs):
+            if old_name in kwargs:
+                if dep_version:
+                    end_version = dep_version.split('.')
+                    end_version[1] = str(int(end_version[1]) + 2)
+                    end_version = '.'.join(end_version)
+                    message = (f"Use of keyword argument `{old_name}` is "
+                               f"deprecated and replaced by `{new_name}`.  "
+                               f"Support for `{old_name}` will be removed "
+                               f"in SciPy {end_version}.")
+                    warnings.warn(message, DeprecationWarning, stacklevel=2)
+                if new_name in kwargs:
+                    message = (f"{fun.__name__}() got multiple values for "
+                               f"argument now known as `{new_name}`")
+                    raise TypeError(message)
+                kwargs[new_name] = kwargs.pop(old_name)
+            return fun(*args, **kwargs)
+        return wrapper
+    return decorator
+
+
+def _rng_spawn(rng, n_children):
+    # spawns independent RNGs from a parent RNG
+    bg = rng._bit_generator
+    ss = bg._seed_seq
+    child_rngs = [np.random.Generator(type(bg)(child_ss))
+                  for child_ss in ss.spawn(n_children)]
+    return child_rngs
+
+
+def _get_nan(*data, xp=None):
+    xp = array_namespace(*data) if xp is None else xp
+    # Get NaN of appropriate dtype for data
+    data = [xp.asarray(item) for item in data]
+    try:
+        min_float = getattr(xp, 'float16', xp.float32)
+        dtype = xp.result_type(*data, min_float)  # must be at least a float
+    except DTypePromotionError:
+        # fallback to float64
+        dtype = xp.float64
+    return xp.asarray(xp.nan, dtype=dtype)[()]
+
+
+def normalize_axis_index(axis, ndim):
+    # Check if `axis` is in the correct range and normalize it
+    if axis < -ndim or axis >= ndim:
+        msg = f"axis {axis} is out of bounds for array of dimension {ndim}"
+        raise AxisError(msg)
+
+    if axis < 0:
+        axis = axis + ndim
+    return axis
+
+
+def _call_callback_maybe_halt(callback, res):
+    """Call wrapped callback; return True if algorithm should stop.
+
+    Parameters
+    ----------
+    callback : callable or None
+        A user-provided callback wrapped with `_wrap_callback`
+    res : OptimizeResult
+        Information about the current iterate
+
+    Returns
+    -------
+    halt : bool
+        True if minimization should stop
+
+    """
+    if callback is None:
+        return False
+    try:
+        callback(res)
+        return False
+    except StopIteration:
+        callback.stop_iteration = True
+        return True
+
+
+class _RichResult(dict):
+    """ Container for multiple outputs with pretty-printing """
+    def __getattr__(self, name):
+        try:
+            return self[name]
+        except KeyError as e:
+            raise AttributeError(name) from e
+
+    __setattr__ = dict.__setitem__  # type: ignore[assignment]
+    __delattr__ = dict.__delitem__  # type: ignore[assignment]
+
+    def __repr__(self):
+        order_keys = ['message', 'success', 'status', 'fun', 'funl', 'x', 'xl',
+                      'col_ind', 'nit', 'lower', 'upper', 'eqlin', 'ineqlin',
+                      'converged', 'flag', 'function_calls', 'iterations',
+                      'root']
+        order_keys = getattr(self, '_order_keys', order_keys)
+        # 'slack', 'con' are redundant with residuals
+        # 'crossover_nit' is probably not interesting to most users
+        omit_keys = {'slack', 'con', 'crossover_nit', '_order_keys'}
+
+        def key(item):
+            try:
+                return order_keys.index(item[0].lower())
+            except ValueError:  # item not in list
+                return np.inf
+
+        def omit_redundant(items):
+            for item in items:
+                if item[0] in omit_keys:
+                    continue
+                yield item
+
+        def item_sorter(d):
+            return sorted(omit_redundant(d.items()), key=key)
+
+        if self.keys():
+            return _dict_formatter(self, sorter=item_sorter)
+        else:
+            return self.__class__.__name__ + "()"
+
+    def __dir__(self):
+        return list(self.keys())
+
+
+def _indenter(s, n=0):
+    """
+    Ensures that lines after the first are indented by the specified amount
+    """
+    split = s.split("\n")
+    indent = " "*n
+    return ("\n" + indent).join(split)
+
+
+def _float_formatter_10(x):
+    """
+    Returns a string representation of a float with exactly ten characters
+    """
+    if np.isposinf(x):
+        return "       inf"
+    elif np.isneginf(x):
+        return "      -inf"
+    elif np.isnan(x):
+        return "       nan"
+    return np.format_float_scientific(x, precision=3, pad_left=2, unique=False)
+
+
+def _dict_formatter(d, n=0, mplus=1, sorter=None):
+    """
+    Pretty printer for dictionaries
+
+    `n` keeps track of the starting indentation;
+    lines are indented by this much after a line break.
+    `mplus` is additional left padding applied to keys
+    """
+    if isinstance(d, dict):
+        m = max(map(len, list(d.keys()))) + mplus  # width to print keys
+        s = '\n'.join([k.rjust(m) + ': ' +  # right justified, width m
+                       _indenter(_dict_formatter(v, m+n+2, 0, sorter), m+2)
+                       for k, v in sorter(d)])  # +2 for ': '
+    else:
+        # By default, NumPy arrays print with linewidth=76. `n` is
+        # the indent at which a line begins printing, so it is subtracted
+        # from the default to avoid exceeding 76 characters total.
+        # `edgeitems` is the number of elements to include before and after
+        # ellipses when arrays are not shown in full.
+        # `threshold` is the maximum number of elements for which an
+        # array is shown in full.
+        # These values tend to work well for use with OptimizeResult.
+        with np.printoptions(linewidth=76-n, edgeitems=2, threshold=12,
+                             formatter={'float_kind': _float_formatter_10}):
+            s = str(d)
+    return s
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..30b1d852db016240f06f8a6dfb163b2e3edafba0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__init__.py
@@ -0,0 +1,22 @@
+"""
+NumPy Array API compatibility library
+
+This is a small wrapper around NumPy and CuPy that is compatible with the
+Array API standard https://data-apis.org/array-api/latest/. See also NEP 47
+https://numpy.org/neps/nep-0047-array-api-standard.html.
+
+Unlike array_api_strict, this is not a strict minimal implementation of the
+Array API, but rather just an extension of the main NumPy namespace with
+changes needed to be compliant with the Array API. See
+https://numpy.org/doc/stable/reference/array_api.html for a full list of
+changes. In particular, unlike array_api_strict, this package does not use a
+separate Array object, but rather just uses numpy.ndarray directly.
+
+Library authors using the Array API may wish to test against array_api_strict
+to ensure they are not using functionality outside of the standard, but prefer
+this implementation for the default when working with NumPy arrays.
+
+"""
+__version__ = '1.9.1'
+
+from .common import *  # noqa: F401, F403
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9270d29fba8640c366e0507c208abcd007778f12
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..810fa26446688c80ea400a19b9e9725281e08ce9
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/__pycache__/_internal.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/_internal.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/_internal.py
new file mode 100644
index 0000000000000000000000000000000000000000..170a1ff9e6459a8cd76f8f6f9b4bca1e894e9883
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/_internal.py
@@ -0,0 +1,46 @@
+"""
+Internal helpers
+"""
+
+from functools import wraps
+from inspect import signature
+
+def get_xp(xp):
+    """
+    Decorator to automatically replace xp with the corresponding array module.
+
+    Use like
+
+    import numpy as np
+
+    @get_xp(np)
+    def func(x, /, xp, kwarg=None):
+        return xp.func(x, kwarg=kwarg)
+
+    Note that xp must be a keyword argument and come after all non-keyword
+    arguments.
+
+    """
+
+    def inner(f):
+        @wraps(f)
+        def wrapped_f(*args, **kwargs):
+            return f(*args, xp=xp, **kwargs)
+
+        sig = signature(f)
+        new_sig = sig.replace(
+            parameters=[sig.parameters[i] for i in sig.parameters if i != "xp"]
+        )
+
+        if wrapped_f.__doc__ is None:
+            wrapped_f.__doc__ = f"""\
+Array API compatibility wrapper for {f.__name__}.
+
+See the corresponding documentation in NumPy/CuPy and/or the array API
+specification for more details.
+
+"""
+        wrapped_f.__signature__ = new_sig
+        return wrapped_f
+
+    return inner
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..91ab1c405e1d700e2bab5a87fc70196a34871e7d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__init__.py
@@ -0,0 +1 @@
+from ._helpers import * # noqa: F403
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d22492978132cc8623d0a3f8c8f2e7b789e44ed6
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ee4acc8b4425b035c3ecce33c9e83e57bbbd626
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99c0c47daa62f89b9abe66ecdf18e4eb23d23fe0
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_fft.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d07af1e807c53ca1c1fcb85c8e2772d007691b5
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_helpers.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df4d9eae38aff3eab9427ad6767ef178035f1438
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/__pycache__/_linalg.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a90f44424d81f25e54babb79b09fef7d1b05660
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_aliases.py
@@ -0,0 +1,555 @@
+"""
+These are functions that are just aliases of existing functions in NumPy.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Sequence, Tuple, Union
+    from ._typing import ndarray, Device, Dtype
+
+from typing import NamedTuple
+import inspect
+
+from ._helpers import array_namespace, _check_device, device, is_torch_array, is_cupy_namespace
+
+# These functions are modified from the NumPy versions.
+
+# Creation functions add the device keyword (which does nothing for NumPy)
+
+def arange(
+    start: Union[int, float],
+    /,
+    stop: Optional[Union[int, float]] = None,
+    step: Union[int, float] = 1,
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.arange(start, stop=stop, step=step, dtype=dtype, **kwargs)
+
+def empty(
+    shape: Union[int, Tuple[int, ...]],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.empty(shape, dtype=dtype, **kwargs)
+
+def empty_like(
+    x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
+    **kwargs
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.empty_like(x, dtype=dtype, **kwargs)
+
+def eye(
+    n_rows: int,
+    n_cols: Optional[int] = None,
+    /,
+    *,
+    xp,
+    k: int = 0,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.eye(n_rows, M=n_cols, k=k, dtype=dtype, **kwargs)
+
+def full(
+    shape: Union[int, Tuple[int, ...]],
+    fill_value: Union[int, float],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.full(shape, fill_value, dtype=dtype, **kwargs)
+
+def full_like(
+    x: ndarray,
+    /,
+    fill_value: Union[int, float],
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.full_like(x, fill_value, dtype=dtype, **kwargs)
+
+def linspace(
+    start: Union[int, float],
+    stop: Union[int, float],
+    /,
+    num: int,
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    endpoint: bool = True,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.linspace(start, stop, num, dtype=dtype, endpoint=endpoint, **kwargs)
+
+def ones(
+    shape: Union[int, Tuple[int, ...]],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.ones(shape, dtype=dtype, **kwargs)
+
+def ones_like(
+    x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.ones_like(x, dtype=dtype, **kwargs)
+
+def zeros(
+    shape: Union[int, Tuple[int, ...]],
+    xp,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.zeros(shape, dtype=dtype, **kwargs)
+
+def zeros_like(
+    x: ndarray, /, xp, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None,
+    **kwargs,
+) -> ndarray:
+    _check_device(xp, device)
+    return xp.zeros_like(x, dtype=dtype, **kwargs)
+
+# np.unique() is split into four functions in the array API:
+# unique_all, unique_counts, unique_inverse, and unique_values (this is done
+# to remove polymorphic return types).
+
+# The functions here return namedtuples (np.unique() returns a normal
+# tuple).
+
+# Note that these named tuples aren't actually part of the standard namespace,
+# but I don't see any issue with exporting the names here regardless.
+class UniqueAllResult(NamedTuple):
+    values: ndarray
+    indices: ndarray
+    inverse_indices: ndarray
+    counts: ndarray
+
+
+class UniqueCountsResult(NamedTuple):
+    values: ndarray
+    counts: ndarray
+
+
+class UniqueInverseResult(NamedTuple):
+    values: ndarray
+    inverse_indices: ndarray
+
+
+def _unique_kwargs(xp):
+    # Older versions of NumPy and CuPy do not have equal_nan. Rather than
+    # trying to parse version numbers, just check if equal_nan is in the
+    # signature.
+    s = inspect.signature(xp.unique)
+    if 'equal_nan' in s.parameters:
+        return {'equal_nan': False}
+    return {}
+
+def unique_all(x: ndarray, /, xp) -> UniqueAllResult:
+    kwargs = _unique_kwargs(xp)
+    values, indices, inverse_indices, counts = xp.unique(
+        x,
+        return_counts=True,
+        return_index=True,
+        return_inverse=True,
+        **kwargs,
+    )
+    # np.unique() flattens inverse indices, but they need to share x's shape
+    # See https://github.com/numpy/numpy/issues/20638
+    inverse_indices = inverse_indices.reshape(x.shape)
+    return UniqueAllResult(
+        values,
+        indices,
+        inverse_indices,
+        counts,
+    )
+
+
+def unique_counts(x: ndarray, /, xp) -> UniqueCountsResult:
+    kwargs = _unique_kwargs(xp)
+    res = xp.unique(
+        x,
+        return_counts=True,
+        return_index=False,
+        return_inverse=False,
+        **kwargs
+    )
+
+    return UniqueCountsResult(*res)
+
+
+def unique_inverse(x: ndarray, /, xp) -> UniqueInverseResult:
+    kwargs = _unique_kwargs(xp)
+    values, inverse_indices = xp.unique(
+        x,
+        return_counts=False,
+        return_index=False,
+        return_inverse=True,
+        **kwargs,
+    )
+    # xp.unique() flattens inverse indices, but they need to share x's shape
+    # See https://github.com/numpy/numpy/issues/20638
+    inverse_indices = inverse_indices.reshape(x.shape)
+    return UniqueInverseResult(values, inverse_indices)
+
+
+def unique_values(x: ndarray, /, xp) -> ndarray:
+    kwargs = _unique_kwargs(xp)
+    return xp.unique(
+        x,
+        return_counts=False,
+        return_index=False,
+        return_inverse=False,
+        **kwargs,
+    )
+
+def astype(x: ndarray, dtype: Dtype, /, *, copy: bool = True) -> ndarray:
+    if not copy and dtype == x.dtype:
+        return x
+    return x.astype(dtype=dtype, copy=copy)
+
+# These functions have different keyword argument names
+
+def std(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    correction: Union[int, float] = 0.0, # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs,
+) -> ndarray:
+    return xp.std(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
+
+def var(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    correction: Union[int, float] = 0.0, # correction instead of ddof
+    keepdims: bool = False,
+    **kwargs,
+) -> ndarray:
+    return xp.var(x, axis=axis, ddof=correction, keepdims=keepdims, **kwargs)
+
+# cumulative_sum is renamed from cumsum, and adds the include_initial keyword
+# argument
+
+def cumulative_sum(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    axis: Optional[int] = None,
+    dtype: Optional[Dtype] = None,
+    include_initial: bool = False,
+    **kwargs
+) -> ndarray:
+    wrapped_xp = array_namespace(x)
+
+    # TODO: The standard is not clear about what should happen when x.ndim == 0.
+    if axis is None:
+        if x.ndim > 1:
+            raise ValueError("axis must be specified in cumulative_sum for more than one dimension")
+        axis = 0
+
+    res = xp.cumsum(x, axis=axis, dtype=dtype, **kwargs)
+
+    # np.cumsum does not support include_initial
+    if include_initial:
+        initial_shape = list(x.shape)
+        initial_shape[axis] = 1
+        res = xp.concatenate(
+            [wrapped_xp.zeros(shape=initial_shape, dtype=res.dtype, device=device(res)), res],
+            axis=axis,
+        )
+    return res
+
+# The min and max argument names in clip are different and not optional in numpy, and type
+# promotion behavior is different.
+def clip(
+    x: ndarray,
+    /,
+    min: Optional[Union[int, float, ndarray]] = None,
+    max: Optional[Union[int, float, ndarray]] = None,
+    *,
+    xp,
+    # TODO: np.clip has other ufunc kwargs
+    out: Optional[ndarray] = None,
+) -> ndarray:
+    def _isscalar(a):
+        return isinstance(a, (int, float, type(None)))
+    min_shape = () if _isscalar(min) else min.shape
+    max_shape = () if _isscalar(max) else max.shape
+
+    wrapped_xp = array_namespace(x)
+
+    result_shape = xp.broadcast_shapes(x.shape, min_shape, max_shape)
+
+    # np.clip does type promotion but the array API clip requires that the
+    # output have the same dtype as x. We do this instead of just downcasting
+    # the result of xp.clip() to handle some corner cases better (e.g.,
+    # avoiding uint64 -> float64 promotion).
+
+    # Note: cases where min or max overflow (integer) or round (float) in the
+    # wrong direction when downcasting to x.dtype are unspecified. This code
+    # just does whatever NumPy does when it downcasts in the assignment, but
+    # other behavior could be preferred, especially for integers. For example,
+    # this code produces:
+
+    # >>> clip(asarray(0, dtype=int8), asarray(128, dtype=int16), None)
+    # -128
+
+    # but an answer of 0 might be preferred. See
+    # https://github.com/numpy/numpy/issues/24976 for more discussion on this issue.
+
+
+    # At least handle the case of Python integers correctly (see
+    # https://github.com/numpy/numpy/pull/26892).
+    if type(min) is int and min <= wrapped_xp.iinfo(x.dtype).min:
+        min = None
+    if type(max) is int and max >= wrapped_xp.iinfo(x.dtype).max:
+        max = None
+
+    if out is None:
+        out = wrapped_xp.asarray(xp.broadcast_to(x, result_shape),
+                                 copy=True, device=device(x))
+    if min is not None:
+        if is_torch_array(x) and x.dtype == xp.float64 and _isscalar(min):
+            # Avoid loss of precision due to torch defaulting to float32
+            min = wrapped_xp.asarray(min, dtype=xp.float64)
+        a = xp.broadcast_to(wrapped_xp.asarray(min, device=device(x)), result_shape)
+        ia = (out < a) | xp.isnan(a)
+        # torch requires an explicit cast here
+        out[ia] = wrapped_xp.astype(a[ia], out.dtype)
+    if max is not None:
+        if is_torch_array(x) and x.dtype == xp.float64 and _isscalar(max):
+            max = wrapped_xp.asarray(max, dtype=xp.float64)
+        b = xp.broadcast_to(wrapped_xp.asarray(max, device=device(x)), result_shape)
+        ib = (out > b) | xp.isnan(b)
+        out[ib] = wrapped_xp.astype(b[ib], out.dtype)
+    # Return a scalar for 0-D
+    return out[()]
+
+# Unlike transpose(), the axes argument to permute_dims() is required.
+def permute_dims(x: ndarray, /, axes: Tuple[int, ...], xp) -> ndarray:
+    return xp.transpose(x, axes)
+
+# np.reshape calls the keyword argument 'newshape' instead of 'shape'
+def reshape(x: ndarray,
+            /,
+            shape: Tuple[int, ...],
+            xp, copy: Optional[bool] = None,
+            **kwargs) -> ndarray:
+    if copy is True:
+        x = x.copy()
+    elif copy is False:
+        y = x.view()
+        y.shape = shape
+        return y
+    return xp.reshape(x, shape, **kwargs)
+
+# The descending keyword is new in sort and argsort, and 'kind' replaced with
+# 'stable'
+def argsort(
+    x: ndarray, /, xp, *, axis: int = -1, descending: bool = False, stable: bool = True,
+    **kwargs,
+) -> ndarray:
+    # Note: this keyword argument is different, and the default is different.
+    # We set it in kwargs like this because numpy.sort uses kind='quicksort'
+    # as the default whereas cupy.sort uses kind=None.
+    if stable:
+        kwargs['kind'] = "stable"
+    if not descending:
+        res = xp.argsort(x, axis=axis, **kwargs)
+    else:
+        # As NumPy has no native descending sort, we imitate it here. Note that
+        # simply flipping the results of xp.argsort(x, ...) would not
+        # respect the relative order like it would in native descending sorts.
+        res = xp.flip(
+            xp.argsort(xp.flip(x, axis=axis), axis=axis, **kwargs),
+            axis=axis,
+        )
+        # Rely on flip()/argsort() to validate axis
+        normalised_axis = axis if axis >= 0 else x.ndim + axis
+        max_i = x.shape[normalised_axis] - 1
+        res = max_i - res
+    return res
+
+def sort(
+    x: ndarray, /, xp, *, axis: int = -1, descending: bool = False, stable: bool = True,
+    **kwargs,
+) -> ndarray:
+    # Note: this keyword argument is different, and the default is different.
+    # We set it in kwargs like this because numpy.sort uses kind='quicksort'
+    # as the default whereas cupy.sort uses kind=None.
+    if stable:
+        kwargs['kind'] = "stable"
+    res = xp.sort(x, axis=axis, **kwargs)
+    if descending:
+        res = xp.flip(res, axis=axis)
+    return res
+
+# nonzero should error for zero-dimensional arrays
+def nonzero(x: ndarray, /, xp, **kwargs) -> Tuple[ndarray, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return xp.nonzero(x, **kwargs)
+
+# ceil, floor, and trunc return integers for integer inputs
+
+def ceil(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.ceil(x, **kwargs)
+
+def floor(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.floor(x, **kwargs)
+
+def trunc(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if xp.issubdtype(x.dtype, xp.integer):
+        return x
+    return xp.trunc(x, **kwargs)
+
+# linear algebra functions
+
+def matmul(x1: ndarray, x2: ndarray, /, xp, **kwargs) -> ndarray:
+    return xp.matmul(x1, x2, **kwargs)
+
+# Unlike transpose, matrix_transpose only transposes the last two axes.
+def matrix_transpose(x: ndarray, /, xp) -> ndarray:
+    if x.ndim < 2:
+        raise ValueError("x must be at least 2-dimensional for matrix_transpose")
+    return xp.swapaxes(x, -1, -2)
+
+def tensordot(x1: ndarray,
+              x2: ndarray,
+              /,
+              xp,
+              *,
+              axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2,
+              **kwargs,
+) -> ndarray:
+    return xp.tensordot(x1, x2, axes=axes, **kwargs)
+
+def vecdot(x1: ndarray, x2: ndarray, /, xp, *, axis: int = -1) -> ndarray:
+    if x1.shape[axis] != x2.shape[axis]:
+        raise ValueError("x1 and x2 must have the same size along the given axis")
+
+    if hasattr(xp, 'broadcast_tensors'):
+        _broadcast = xp.broadcast_tensors
+    else:
+        _broadcast = xp.broadcast_arrays
+
+    x1_ = xp.moveaxis(x1, axis, -1)
+    x2_ = xp.moveaxis(x2, axis, -1)
+    x1_, x2_ = _broadcast(x1_, x2_)
+
+    res = x1_[..., None, :] @ x2_[..., None]
+    return res[..., 0, 0]
+
+# isdtype is a new function in the 2022.12 array API specification.
+
+def isdtype(
+    dtype: Dtype, kind: Union[Dtype, str, Tuple[Union[Dtype, str], ...]], xp,
+    *, _tuple=True, # Disallow nested tuples
+) -> bool:
+    """
+    Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
+
+    Note that outside of this function, this compat library does not yet fully
+    support complex numbers.
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
+    for more details
+    """
+    if isinstance(kind, tuple) and _tuple:
+        return any(isdtype(dtype, k, xp, _tuple=False) for k in kind)
+    elif isinstance(kind, str):
+        if kind == 'bool':
+            return dtype == xp.bool_
+        elif kind == 'signed integer':
+            return xp.issubdtype(dtype, xp.signedinteger)
+        elif kind == 'unsigned integer':
+            return xp.issubdtype(dtype, xp.unsignedinteger)
+        elif kind == 'integral':
+            return xp.issubdtype(dtype, xp.integer)
+        elif kind == 'real floating':
+            return xp.issubdtype(dtype, xp.floating)
+        elif kind == 'complex floating':
+            return xp.issubdtype(dtype, xp.complexfloating)
+        elif kind == 'numeric':
+            return xp.issubdtype(dtype, xp.number)
+        else:
+            raise ValueError(f"Unrecognized data type kind: {kind!r}")
+    else:
+        # This will allow things that aren't required by the spec, like
+        # isdtype(np.float64, float) or isdtype(np.int64, 'l'). Should we be
+        # more strict here to match the type annotation? Note that the
+        # array_api_strict implementation will be very strict.
+        return dtype == kind
+
+# unstack is a new function in the 2023.12 array API standard
+def unstack(x: ndarray, /, xp, *, axis: int = 0) -> Tuple[ndarray, ...]:
+    if x.ndim == 0:
+        raise ValueError("Input array must be at least 1-d.")
+    return tuple(xp.moveaxis(x, axis, 0))
+
+# numpy 1.26 does not use the standard definition for sign on complex numbers
+
+def sign(x: ndarray, /, xp, **kwargs) -> ndarray:
+    if isdtype(x.dtype, 'complex floating', xp=xp):
+        out = (x/xp.abs(x, **kwargs))[...]
+        # sign(0) = 0 but the above formula would give nan
+        out[x == 0+0j] = 0+0j
+    else:
+        out = xp.sign(x, **kwargs)
+    # CuPy sign() does not propagate nans. See
+    # https://github.com/data-apis/array-api-compat/issues/136
+    if is_cupy_namespace(xp) and isdtype(x.dtype, 'real floating', xp=xp):
+        out[xp.isnan(x)] = xp.nan
+    return out[()]
+
+__all__ = ['arange', 'empty', 'empty_like', 'eye', 'full', 'full_like',
+           'linspace', 'ones', 'ones_like', 'zeros', 'zeros_like',
+           'UniqueAllResult', 'UniqueCountsResult', 'UniqueInverseResult',
+           'unique_all', 'unique_counts', 'unique_inverse', 'unique_values',
+           'astype', 'std', 'var', 'cumulative_sum', 'clip', 'permute_dims',
+           'reshape', 'argsort', 'sort', 'nonzero', 'ceil', 'floor', 'trunc',
+           'matmul', 'matrix_transpose', 'tensordot', 'vecdot', 'isdtype',
+           'unstack', 'sign']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..666b0b1f84211052ac23be8a2a3009457b3b19d2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_fft.py
@@ -0,0 +1,183 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Union, Optional, Literal
+
+if TYPE_CHECKING:
+    from ._typing import Device, ndarray
+    from collections.abc import Sequence
+
+# Note: NumPy fft functions improperly upcast float32 and complex64 to
+# complex128, which is why we require wrapping them all here.
+
+def fft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.fft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def ifft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.ifft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def fftn(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.fftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def ifftn(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.ifftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def rfft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.rfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype == xp.float32:
+        return res.astype(xp.complex64)
+    return res
+
+def irfft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.irfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype == xp.complex64:
+        return res.astype(xp.float32)
+    return res
+
+def rfftn(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.rfftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype == xp.float32:
+        return res.astype(xp.complex64)
+    return res
+
+def irfftn(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.irfftn(x, s=s, axes=axes, norm=norm)
+    if x.dtype == xp.complex64:
+        return res.astype(xp.float32)
+    return res
+
+def hfft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.hfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.float32)
+    return res
+
+def ihfft(
+    x: ndarray,
+    /,
+    xp,
+    *,
+    n: Optional[int] = None,
+    axis: int = -1,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+) -> ndarray:
+    res = xp.fft.ihfft(x, n=n, axis=axis, norm=norm)
+    if x.dtype in [xp.float32, xp.complex64]:
+        return res.astype(xp.complex64)
+    return res
+
+def fftfreq(n: int, /, xp, *, d: float = 1.0, device: Optional[Device] = None) -> ndarray:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    return xp.fft.fftfreq(n, d=d)
+
+def rfftfreq(n: int, /, xp, *, d: float = 1.0, device: Optional[Device] = None) -> ndarray:
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device {device!r}")
+    return xp.fft.rfftfreq(n, d=d)
+
+def fftshift(x: ndarray, /, xp, *, axes: Union[int, Sequence[int]] = None) -> ndarray:
+    return xp.fft.fftshift(x, axes=axes)
+
+def ifftshift(x: ndarray, /, xp, *, axes: Union[int, Sequence[int]] = None) -> ndarray:
+    return xp.fft.ifftshift(x, axes=axes)
+
+__all__ = [
+    "fft",
+    "ifft",
+    "fftn",
+    "ifftn",
+    "rfft",
+    "irfft",
+    "rfftn",
+    "irfftn",
+    "hfft",
+    "ihfft",
+    "fftfreq",
+    "rfftfreq",
+    "fftshift",
+    "ifftshift",
+]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_helpers.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..91056e249a30bf1d0f14341c31286d64dad0b676
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_helpers.py
@@ -0,0 +1,825 @@
+"""
+Various helper functions which are not part of the spec.
+
+Functions which start with an underscore are for internal use only but helpers
+that are in __all__ are intended as additional helper functions for use by end
+users of the compat library.
+"""
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from typing import Optional, Union, Any
+    from ._typing import Array, Device
+
+import sys
+import math
+import inspect
+import warnings
+
+def _is_jax_zero_gradient_array(x):
+    """Return True if `x` is a zero-gradient array.
+
+    These arrays are a design quirk of Jax that may one day be removed.
+    See https://github.com/google/jax/issues/20620.
+    """
+    if 'numpy' not in sys.modules or 'jax' not in sys.modules:
+        return False
+
+    import numpy as np
+    import jax
+
+    return isinstance(x, np.ndarray) and x.dtype == jax.float0
+
+def is_numpy_array(x):
+    """
+    Return True if `x` is a NumPy array.
+
+    This function does not import NumPy if it has not already been imported
+    and is therefore cheap to use.
+
+    This also returns True for `ndarray` subclasses and NumPy scalar objects.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing NumPy if it isn't already
+    if 'numpy' not in sys.modules:
+        return False
+
+    import numpy as np
+
+    # TODO: Should we reject ndarray subclasses?
+    return (isinstance(x, (np.ndarray, np.generic))
+            and not _is_jax_zero_gradient_array(x))
+
+def is_cupy_array(x):
+    """
+    Return True if `x` is a CuPy array.
+
+    This function does not import CuPy if it has not already been imported
+    and is therefore cheap to use.
+
+    This also returns True for `cupy.ndarray` subclasses and CuPy scalar objects.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing CuPy if it isn't already
+    if 'cupy' not in sys.modules:
+        return False
+
+    import cupy as cp
+
+    # TODO: Should we reject ndarray subclasses?
+    return isinstance(x, (cp.ndarray, cp.generic))
+
+def is_torch_array(x):
+    """
+    Return True if `x` is a PyTorch tensor.
+
+    This function does not import PyTorch if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing torch if it isn't already
+    if 'torch' not in sys.modules:
+        return False
+
+    import torch
+
+    # TODO: Should we reject ndarray subclasses?
+    return isinstance(x, torch.Tensor)
+
+def is_ndonnx_array(x):
+    """
+    Return True if `x` is a ndonnx Array.
+
+    This function does not import ndonnx if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing torch if it isn't already
+    if 'ndonnx' not in sys.modules:
+        return False
+
+    import ndonnx as ndx
+
+    return isinstance(x, ndx.Array)
+
+def is_dask_array(x):
+    """
+    Return True if `x` is a dask.array Array.
+
+    This function does not import dask if it has not already been imported
+    and is therefore cheap to use.
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_jax_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing dask if it isn't already
+    if 'dask.array' not in sys.modules:
+        return False
+
+    import dask.array
+
+    return isinstance(x, dask.array.Array)
+
+def is_jax_array(x):
+    """
+    Return True if `x` is a JAX array.
+
+    This function does not import JAX if it has not already been imported
+    and is therefore cheap to use.
+
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_pydata_sparse_array
+    """
+    # Avoid importing jax if it isn't already
+    if 'jax' not in sys.modules:
+        return False
+
+    import jax
+
+    return isinstance(x, jax.Array) or _is_jax_zero_gradient_array(x)
+
+def is_pydata_sparse_array(x) -> bool:
+    """
+    Return True if `x` is an array from the `sparse` package.
+
+    This function does not import `sparse` if it has not already been imported
+    and is therefore cheap to use.
+
+
+    See Also
+    --------
+
+    array_namespace
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    """
+    # Avoid importing jax if it isn't already
+    if 'sparse' not in sys.modules:
+        return False
+
+    import sparse
+
+    # TODO: Account for other backends.
+    return isinstance(x, sparse.SparseArray)
+
+def is_array_api_obj(x):
+    """
+    Return True if `x` is an array API compatible array object.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_ndonnx_array
+    is_dask_array
+    is_jax_array
+    """
+    return is_numpy_array(x) \
+        or is_cupy_array(x) \
+        or is_torch_array(x) \
+        or is_dask_array(x) \
+        or is_jax_array(x) \
+        or is_pydata_sparse_array(x) \
+        or hasattr(x, '__array_namespace__')
+
+def _compat_module_name():
+    assert __name__.endswith('.common._helpers')
+    return __name__.removesuffix('.common._helpers')
+
+def is_numpy_namespace(xp) -> bool:
+    """
+    Returns True if `xp` is a NumPy namespace.
+
+    This includes both NumPy itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'numpy', _compat_module_name() + '.numpy'}
+
+def is_cupy_namespace(xp) -> bool:
+    """
+    Returns True if `xp` is a CuPy namespace.
+
+    This includes both CuPy itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'cupy', _compat_module_name() + '.cupy'}
+
+def is_torch_namespace(xp) -> bool:
+    """
+    Returns True if `xp` is a PyTorch namespace.
+
+    This includes both PyTorch itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'torch', _compat_module_name() + '.torch'}
+
+
+def is_ndonnx_namespace(xp):
+    """
+    Returns True if `xp` is an NDONNX namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ == 'ndonnx'
+
+def is_dask_namespace(xp):
+    """
+    Returns True if `xp` is a Dask namespace.
+
+    This includes both ``dask.array`` itself and the version wrapped by array-api-compat.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'dask.array', _compat_module_name() + '.dask.array'}
+
+def is_jax_namespace(xp):
+    """
+    Returns True if `xp` is a JAX namespace.
+
+    This includes ``jax.numpy`` and ``jax.experimental.array_api`` which existed in
+    older versions of JAX.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_pydata_sparse_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ in {'jax.numpy', 'jax.experimental.array_api'}
+
+def is_pydata_sparse_namespace(xp):
+    """
+    Returns True if `xp` is a pydata/sparse namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_array_api_strict_namespace
+    """
+    return xp.__name__ == 'sparse'
+
+def is_array_api_strict_namespace(xp):
+    """
+    Returns True if `xp` is an array-api-strict namespace.
+
+    See Also
+    --------
+
+    array_namespace
+    is_numpy_namespace
+    is_cupy_namespace
+    is_torch_namespace
+    is_ndonnx_namespace
+    is_dask_namespace
+    is_jax_namespace
+    is_pydata_sparse_namespace
+    """
+    return xp.__name__ == 'array_api_strict'
+
+def _check_api_version(api_version):
+    if api_version in ['2021.12', '2022.12']:
+        warnings.warn(f"The {api_version} version of the array API specification was requested but the returned namespace is actually version 2023.12")
+    elif api_version is not None and api_version not in ['2021.12', '2022.12',
+                                                         '2023.12']:
+        raise ValueError("Only the 2023.12 version of the array API specification is currently supported")
+
+def array_namespace(*xs, api_version=None, use_compat=None):
+    """
+    Get the array API compatible namespace for the arrays `xs`.
+
+    Parameters
+    ----------
+    xs: arrays
+        one or more arrays.
+
+    api_version: str
+        The newest version of the spec that you need support for (currently
+        the compat library wrapped APIs support v2023.12).
+
+    use_compat: bool or None
+        If None (the default), the native namespace will be returned if it is
+        already array API compatible, otherwise a compat wrapper is used. If
+        True, the compat library wrapped library will be returned. If False,
+        the native library namespace is returned.
+
+    Returns
+    -------
+
+    out: namespace
+        The array API compatible namespace corresponding to the arrays in `xs`.
+
+    Raises
+    ------
+    TypeError
+        If `xs` contains arrays from different array libraries or contains a
+        non-array.
+
+
+    Typical usage is to pass the arguments of a function to
+    `array_namespace()` at the top of a function to get the corresponding
+    array API namespace:
+
+    .. code:: python
+
+       def your_function(x, y):
+           xp = array_api_compat.array_namespace(x, y)
+           # Now use xp as the array library namespace
+           return xp.mean(x, axis=0) + 2*xp.std(y, axis=0)
+
+
+    Wrapped array namespaces can also be imported directly. For example,
+    `array_namespace(np.array(...))` will return `array_api_compat.numpy`.
+    This function will also work for any array library not wrapped by
+    array-api-compat if it explicitly defines `__array_namespace__
+    `__
+    (the wrapped namespace is always preferred if it exists).
+
+    See Also
+    --------
+
+    is_array_api_obj
+    is_numpy_array
+    is_cupy_array
+    is_torch_array
+    is_dask_array
+    is_jax_array
+    is_pydata_sparse_array
+
+    """
+    if use_compat not in [None, True, False]:
+        raise ValueError("use_compat must be None, True, or False")
+
+    _use_compat = use_compat in [None, True]
+
+    namespaces = set()
+    for x in xs:
+        if is_numpy_array(x):
+            from .. import numpy as numpy_namespace
+            import numpy as np
+            if use_compat is True:
+                _check_api_version(api_version)
+                namespaces.add(numpy_namespace)
+            elif use_compat is False:
+                namespaces.add(np)
+            else:
+                # numpy 2.0+ have __array_namespace__, however, they are not yet fully array API
+                # compatible.
+                namespaces.add(numpy_namespace)
+        elif is_cupy_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from .. import cupy as cupy_namespace
+                namespaces.add(cupy_namespace)
+            else:
+                import cupy as cp
+                namespaces.add(cp)
+        elif is_torch_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from .. import torch as torch_namespace
+                namespaces.add(torch_namespace)
+            else:
+                import torch
+                namespaces.add(torch)
+        elif is_dask_array(x):
+            if _use_compat:
+                _check_api_version(api_version)
+                from ..dask import array as dask_namespace
+                namespaces.add(dask_namespace)
+            else:
+                import dask.array as da
+                namespaces.add(da)
+        elif is_jax_array(x):
+            if use_compat is True:
+                _check_api_version(api_version)
+                raise ValueError("JAX does not have an array-api-compat wrapper")
+            elif use_compat is False:
+                import jax.numpy as jnp
+            else:
+                # JAX v0.4.32 and newer implements the array API directly in jax.numpy.
+                # For older JAX versions, it is available via jax.experimental.array_api.
+                import jax.numpy
+                if hasattr(jax.numpy, "__array_api_version__"):
+                    jnp = jax.numpy
+                else:
+                    import jax.experimental.array_api as jnp
+            namespaces.add(jnp)
+        elif is_pydata_sparse_array(x):
+            if use_compat is True:
+                _check_api_version(api_version)
+                raise ValueError("`sparse` does not have an array-api-compat wrapper")
+            else:
+                import sparse
+            # `sparse` is already an array namespace. We do not have a wrapper
+            # submodule for it.
+            namespaces.add(sparse)
+        elif hasattr(x, '__array_namespace__'):
+            if use_compat is True:
+                raise ValueError("The given array does not have an array-api-compat wrapper")
+            namespaces.add(x.__array_namespace__(api_version=api_version))
+        else:
+            # TODO: Support Python scalars?
+            raise TypeError(f"{type(x).__name__} is not a supported array type")
+
+    if not namespaces:
+        raise TypeError("Unrecognized array input")
+
+    if len(namespaces) != 1:
+        raise TypeError(f"Multiple namespaces for array inputs: {namespaces}")
+
+    xp, = namespaces
+
+    return xp
+
+# backwards compatibility alias
+get_namespace = array_namespace
+
+def _check_device(xp, device):
+    if xp == sys.modules.get('numpy'):
+        if device not in ["cpu", None]:
+            raise ValueError(f"Unsupported device for NumPy: {device!r}")
+
+# Placeholder object to represent the dask device
+# when the array backend is not the CPU.
+# (since it is not easy to tell which device a dask array is on)
+class _dask_device:
+    def __repr__(self):
+        return "DASK_DEVICE"
+
+_DASK_DEVICE = _dask_device()
+
+# device() is not on numpy.ndarray or dask.array and to_device() is not on numpy.ndarray
+# or cupy.ndarray. They are not included in array objects of this library
+# because this library just reuses the respective ndarray classes without
+# wrapping or subclassing them. These helper functions can be used instead of
+# the wrapper functions for libraries that need to support both NumPy/CuPy and
+# other libraries that use devices.
+def device(x: Array, /) -> Device:
+    """
+    Hardware device the array data resides on.
+
+    This is equivalent to `x.device` according to the `standard
+    `__.
+    This helper is included because some array libraries either do not have
+    the `device` attribute or include it with an incompatible API.
+
+    Parameters
+    ----------
+    x: array
+        array instance from an array API compatible library.
+
+    Returns
+    -------
+    out: device
+        a ``device`` object (see the `Device Support `__
+        section of the array API specification).
+
+    Notes
+    -----
+
+    For NumPy the device is always `"cpu"`. For Dask, the device is always a
+    special `DASK_DEVICE` object.
+
+    See Also
+    --------
+
+    to_device : Move array data to a different device.
+
+    """
+    if is_numpy_array(x):
+        return "cpu"
+    elif is_dask_array(x):
+        # Peek at the metadata of the jax array to determine type
+        try:
+            import numpy as np
+            if isinstance(x._meta, np.ndarray):
+                # Must be on CPU since backed by numpy
+                return "cpu"
+        except ImportError:
+            pass
+        return _DASK_DEVICE
+    elif is_jax_array(x):
+        # JAX has .device() as a method, but it is being deprecated so that it
+        # can become a property, in accordance with the standard. In order for
+        # this function to not break when JAX makes the flip, we check for
+        # both here.
+        if inspect.ismethod(x.device):
+            return x.device()
+        else:
+            return x.device
+    elif is_pydata_sparse_array(x):
+        # `sparse` will gain `.device`, so check for this first.
+        x_device = getattr(x, 'device', None)
+        if x_device is not None:
+            return x_device
+        # Everything but DOK has this attr.
+        try:
+            inner = x.data
+        except AttributeError:
+            return "cpu"
+        # Return the device of the constituent array
+        return device(inner)
+    return x.device
+
+# Prevent shadowing, used below
+_device = device
+
+# Based on cupy.array_api.Array.to_device
+def _cupy_to_device(x, device, /, stream=None):
+    import cupy as cp
+    from cupy.cuda import Device as _Device
+    from cupy.cuda import stream as stream_module
+    from cupy_backends.cuda.api import runtime
+
+    if device == x.device:
+        return x
+    elif device == "cpu":
+        # allowing us to use `to_device(x, "cpu")`
+        # is useful for portable test swapping between
+        # host and device backends
+        return x.get()
+    elif not isinstance(device, _Device):
+        raise ValueError(f"Unsupported device {device!r}")
+    else:
+        # see cupy/cupy#5985 for the reason how we handle device/stream here
+        prev_device = runtime.getDevice()
+        prev_stream: stream_module.Stream = None
+        if stream is not None:
+            prev_stream = stream_module.get_current_stream()
+            # stream can be an int as specified in __dlpack__, or a CuPy stream
+            if isinstance(stream, int):
+                stream = cp.cuda.ExternalStream(stream)
+            elif isinstance(stream, cp.cuda.Stream):
+                pass
+            else:
+                raise ValueError('the input stream is not recognized')
+            stream.use()
+        try:
+            runtime.setDevice(device.id)
+            arr = x.copy()
+        finally:
+            runtime.setDevice(prev_device)
+            if stream is not None:
+                prev_stream.use()
+        return arr
+
+def _torch_to_device(x, device, /, stream=None):
+    if stream is not None:
+        raise NotImplementedError
+    return x.to(device)
+
+def to_device(x: Array, device: Device, /, *, stream: Optional[Union[int, Any]] = None) -> Array:
+    """
+    Copy the array from the device on which it currently resides to the specified ``device``.
+
+    This is equivalent to `x.to_device(device, stream=stream)` according to
+    the `standard
+    `__.
+    This helper is included because some array libraries do not have the
+    `to_device` method.
+
+    Parameters
+    ----------
+
+    x: array
+        array instance from an array API compatible library.
+
+    device: device
+        a ``device`` object (see the `Device Support `__
+        section of the array API specification).
+
+    stream: Optional[Union[int, Any]]
+        stream object to use during copy. In addition to the types supported
+        in ``array.__dlpack__``, implementations may choose to support any
+        library-specific stream object with the caveat that any code using
+        such an object would not be portable.
+
+    Returns
+    -------
+
+    out: array
+        an array with the same data and data type as ``x`` and located on the
+        specified ``device``.
+
+    Notes
+    -----
+
+    For NumPy, this function effectively does nothing since the only supported
+    device is the CPU. For CuPy, this method supports CuPy CUDA
+    :external+cupy:class:`Device ` and
+    :external+cupy:class:`Stream ` objects. For PyTorch,
+    this is the same as :external+torch:meth:`x.to(device) `
+    (the ``stream`` argument is not supported in PyTorch).
+
+    See Also
+    --------
+
+    device : Hardware device the array data resides on.
+
+    """
+    if is_numpy_array(x):
+        if stream is not None:
+            raise ValueError("The stream argument to to_device() is not supported")
+        if device == 'cpu':
+            return x
+        raise ValueError(f"Unsupported device {device!r}")
+    elif is_cupy_array(x):
+        # cupy does not yet have to_device
+        return _cupy_to_device(x, device, stream=stream)
+    elif is_torch_array(x):
+        return _torch_to_device(x, device, stream=stream)
+    elif is_dask_array(x):
+        if stream is not None:
+            raise ValueError("The stream argument to to_device() is not supported")
+        # TODO: What if our array is on the GPU already?
+        if device == 'cpu':
+            return x
+        raise ValueError(f"Unsupported device {device!r}")
+    elif is_jax_array(x):
+        if not hasattr(x, "__array_namespace__"):
+            # In JAX v0.4.31 and older, this import adds to_device method to x.
+            import jax.experimental.array_api # noqa: F401
+        return x.to_device(device, stream=stream)
+    elif is_pydata_sparse_array(x) and device == _device(x):
+        # Perform trivial check to return the same array if
+        # device is same instead of err-ing.
+        return x
+    return x.to_device(device, stream=stream)
+
+def size(x):
+    """
+    Return the total number of elements of x.
+
+    This is equivalent to `x.size` according to the `standard
+    `__.
+    This helper is included because PyTorch defines `size` in an
+    :external+torch:meth:`incompatible way `.
+
+    """
+    if None in x.shape:
+        return None
+    return math.prod(x.shape)
+
+__all__ = [
+    "array_namespace",
+    "device",
+    "get_namespace",
+    "is_array_api_obj",
+    "is_array_api_strict_namespace",
+    "is_cupy_array",
+    "is_cupy_namespace",
+    "is_dask_array",
+    "is_dask_namespace",
+    "is_jax_array",
+    "is_jax_namespace",
+    "is_numpy_array",
+    "is_numpy_namespace",
+    "is_torch_array",
+    "is_torch_namespace",
+    "is_ndonnx_array",
+    "is_ndonnx_namespace",
+    "is_pydata_sparse_array",
+    "is_pydata_sparse_namespace",
+    "size",
+    "to_device",
+]
+
+_all_ignore = ['sys', 'math', 'inspect', 'warnings']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..bfa1f1b937fddc5c2f95ef3a22850403ffd4b955
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_linalg.py
@@ -0,0 +1,156 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, NamedTuple
+if TYPE_CHECKING:
+    from typing import Literal, Optional, Tuple, Union
+    from ._typing import ndarray
+
+import math
+
+import numpy as np
+if np.__version__[0] == "2":
+    from numpy.lib.array_utils import normalize_axis_tuple
+else:
+    from numpy.core.numeric import normalize_axis_tuple
+
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot, isdtype
+from .._internal import get_xp
+
+# These are in the main NumPy namespace but not in numpy.linalg
+def cross(x1: ndarray, x2: ndarray, /, xp, *, axis: int = -1, **kwargs) -> ndarray:
+    return xp.cross(x1, x2, axis=axis, **kwargs)
+
+def outer(x1: ndarray, x2: ndarray, /, xp, **kwargs) -> ndarray:
+    return xp.outer(x1, x2, **kwargs)
+
+class EighResult(NamedTuple):
+    eigenvalues: ndarray
+    eigenvectors: ndarray
+
+class QRResult(NamedTuple):
+    Q: ndarray
+    R: ndarray
+
+class SlogdetResult(NamedTuple):
+    sign: ndarray
+    logabsdet: ndarray
+
+class SVDResult(NamedTuple):
+    U: ndarray
+    S: ndarray
+    Vh: ndarray
+
+# These functions are the same as their NumPy counterparts except they return
+# a namedtuple.
+def eigh(x: ndarray, /, xp, **kwargs) -> EighResult:
+    return EighResult(*xp.linalg.eigh(x, **kwargs))
+
+def qr(x: ndarray, /, xp, *, mode: Literal['reduced', 'complete'] = 'reduced',
+       **kwargs) -> QRResult:
+    return QRResult(*xp.linalg.qr(x, mode=mode, **kwargs))
+
+def slogdet(x: ndarray, /, xp, **kwargs) -> SlogdetResult:
+    return SlogdetResult(*xp.linalg.slogdet(x, **kwargs))
+
+def svd(x: ndarray, /, xp, *, full_matrices: bool = True, **kwargs) -> SVDResult:
+    return SVDResult(*xp.linalg.svd(x, full_matrices=full_matrices, **kwargs))
+
+# These functions have additional keyword arguments
+
+# The upper keyword argument is new from NumPy
+def cholesky(x: ndarray, /, xp, *, upper: bool = False, **kwargs) -> ndarray:
+    L = xp.linalg.cholesky(x, **kwargs)
+    if upper:
+        U = get_xp(xp)(matrix_transpose)(L)
+        if get_xp(xp)(isdtype)(U.dtype, 'complex floating'):
+            U = xp.conj(U)
+        return U
+    return L
+
+# The rtol keyword argument of matrix_rank() and pinv() is new from NumPy.
+# Note that it has a different semantic meaning from tol and rcond.
+def matrix_rank(x: ndarray,
+                /,
+                xp,
+                *,
+                rtol: Optional[Union[float, ndarray]] = None,
+                **kwargs) -> ndarray:
+    # this is different from xp.linalg.matrix_rank, which supports 1
+    # dimensional arrays.
+    if x.ndim < 2:
+        raise xp.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional")
+    S = get_xp(xp)(svdvals)(x, **kwargs)
+    if rtol is None:
+        tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * xp.finfo(S.dtype).eps
+    else:
+        # this is different from xp.linalg.matrix_rank, which does not
+        # multiply the tolerance by the largest singular value.
+        tol = S.max(axis=-1, keepdims=True)*xp.asarray(rtol)[..., xp.newaxis]
+    return xp.count_nonzero(S > tol, axis=-1)
+
+def pinv(x: ndarray, /, xp, *, rtol: Optional[Union[float, ndarray]] = None, **kwargs) -> ndarray:
+    # this is different from xp.linalg.pinv, which does not multiply the
+    # default tolerance by max(M, N).
+    if rtol is None:
+        rtol = max(x.shape[-2:]) * xp.finfo(x.dtype).eps
+    return xp.linalg.pinv(x, rcond=rtol, **kwargs)
+
+# These functions are new in the array API spec
+
+def matrix_norm(x: ndarray, /, xp, *, keepdims: bool = False, ord: Optional[Union[int, float, Literal['fro', 'nuc']]] = 'fro') -> ndarray:
+    return xp.linalg.norm(x, axis=(-2, -1), keepdims=keepdims, ord=ord)
+
+# svdvals is not in NumPy (but it is in SciPy). It is equivalent to
+# xp.linalg.svd(compute_uv=False).
+def svdvals(x: ndarray, /, xp) -> Union[ndarray, Tuple[ndarray, ...]]:
+    return xp.linalg.svd(x, compute_uv=False)
+
+def vector_norm(x: ndarray, /, xp, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> ndarray:
+    # xp.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or
+    # when axis=None and the input is 2-D, so to force a vector norm, we make
+    # it so the input is 1-D (for axis=None), or reshape so that norm is done
+    # on a single dimension.
+    if axis is None:
+        # Note: xp.linalg.norm() doesn't handle 0-D arrays
+        _x = x.ravel()
+        _axis = 0
+    elif isinstance(axis, tuple):
+        # Note: The axis argument supports any number of axes, whereas
+        # xp.linalg.norm() only supports a single axis for vector norm.
+        normalized_axis = normalize_axis_tuple(axis, x.ndim)
+        rest = tuple(i for i in range(x.ndim) if i not in normalized_axis)
+        newshape = axis + rest
+        _x = xp.transpose(x, newshape).reshape(
+            (math.prod([x.shape[i] for i in axis]), *[x.shape[i] for i in rest]))
+        _axis = 0
+    else:
+        _x = x
+        _axis = axis
+
+    res = xp.linalg.norm(_x, axis=_axis, ord=ord)
+
+    if keepdims:
+        # We can't reuse xp.linalg.norm(keepdims) because of the reshape hacks
+        # above to avoid matrix norm logic.
+        shape = list(x.shape)
+        _axis = normalize_axis_tuple(range(x.ndim) if axis is None else axis, x.ndim)
+        for i in _axis:
+            shape[i] = 1
+        res = xp.reshape(res, tuple(shape))
+
+    return res
+
+# xp.diagonal and xp.trace operate on the first two axes whereas these
+# operates on the last two
+
+def diagonal(x: ndarray, /, xp, *, offset: int = 0, **kwargs) -> ndarray:
+    return xp.diagonal(x, offset=offset, axis1=-2, axis2=-1, **kwargs)
+
+def trace(x: ndarray, /, xp, *, offset: int = 0, dtype=None, **kwargs) -> ndarray:
+    return xp.asarray(xp.trace(x, offset=offset, dtype=dtype, axis1=-2, axis2=-1, **kwargs))
+
+__all__ = ['cross', 'matmul', 'outer', 'tensordot', 'EighResult',
+           'QRResult', 'SlogdetResult', 'SVDResult', 'eigh', 'qr', 'slogdet',
+           'svd', 'cholesky', 'matrix_rank', 'pinv', 'matrix_norm',
+           'matrix_transpose', 'svdvals', 'vecdot', 'vector_norm', 'diagonal',
+           'trace']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..07f3850d21fade94814f9fe1e638286c72a1c552
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/common/_typing.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+__all__ = [
+    "NestedSequence",
+    "SupportsBufferProtocol",
+]
+
+from typing import (
+    Any,
+    TypeVar,
+    Protocol,
+)
+
+_T_co = TypeVar("_T_co", covariant=True)
+
+class NestedSequence(Protocol[_T_co]):
+    def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ...
+    def __len__(self, /) -> int: ...
+
+SupportsBufferProtocol = Any
+
+Array = Any
+Device = Any
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d86857618458bf422e7f16dab302b179e5d520d8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/__init__.py
@@ -0,0 +1,16 @@
+from cupy import * # noqa: F403
+
+# from cupy import * doesn't overwrite these builtin names
+from cupy import abs, max, min, round # noqa: F401
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+
+__import__(__package__ + '.fft')
+
+from ..common._helpers import * # noqa: F401,F403
+
+__array_api_version__ = '2023.12'
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..3627fb6b97820c292c86d26b9aabcefd899cfed1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_aliases.py
@@ -0,0 +1,136 @@
+from __future__ import annotations
+
+import cupy as cp
+
+from ..common import _aliases
+from .._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Union
+    from ._typing import ndarray, Device, Dtype, NestedSequence, SupportsBufferProtocol
+
+bool = cp.bool_
+
+# Basic renames
+acos = cp.arccos
+acosh = cp.arccosh
+asin = cp.arcsin
+asinh = cp.arcsinh
+atan = cp.arctan
+atan2 = cp.arctan2
+atanh = cp.arctanh
+bitwise_left_shift = cp.left_shift
+bitwise_invert = cp.invert
+bitwise_right_shift = cp.right_shift
+concat = cp.concatenate
+pow = cp.power
+
+arange = get_xp(cp)(_aliases.arange)
+empty = get_xp(cp)(_aliases.empty)
+empty_like = get_xp(cp)(_aliases.empty_like)
+eye = get_xp(cp)(_aliases.eye)
+full = get_xp(cp)(_aliases.full)
+full_like = get_xp(cp)(_aliases.full_like)
+linspace = get_xp(cp)(_aliases.linspace)
+ones = get_xp(cp)(_aliases.ones)
+ones_like = get_xp(cp)(_aliases.ones_like)
+zeros = get_xp(cp)(_aliases.zeros)
+zeros_like = get_xp(cp)(_aliases.zeros_like)
+UniqueAllResult = get_xp(cp)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(cp)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(cp)(_aliases.UniqueInverseResult)
+unique_all = get_xp(cp)(_aliases.unique_all)
+unique_counts = get_xp(cp)(_aliases.unique_counts)
+unique_inverse = get_xp(cp)(_aliases.unique_inverse)
+unique_values = get_xp(cp)(_aliases.unique_values)
+astype = _aliases.astype
+std = get_xp(cp)(_aliases.std)
+var = get_xp(cp)(_aliases.var)
+cumulative_sum = get_xp(cp)(_aliases.cumulative_sum)
+clip = get_xp(cp)(_aliases.clip)
+permute_dims = get_xp(cp)(_aliases.permute_dims)
+reshape = get_xp(cp)(_aliases.reshape)
+argsort = get_xp(cp)(_aliases.argsort)
+sort = get_xp(cp)(_aliases.sort)
+nonzero = get_xp(cp)(_aliases.nonzero)
+ceil = get_xp(cp)(_aliases.ceil)
+floor = get_xp(cp)(_aliases.floor)
+trunc = get_xp(cp)(_aliases.trunc)
+matmul = get_xp(cp)(_aliases.matmul)
+matrix_transpose = get_xp(cp)(_aliases.matrix_transpose)
+tensordot = get_xp(cp)(_aliases.tensordot)
+sign = get_xp(cp)(_aliases.sign)
+
+_copy_default = object()
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: Union[
+        ndarray,
+        bool,
+        int,
+        float,
+        NestedSequence[bool | int | float],
+        SupportsBufferProtocol,
+    ],
+    /,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    copy: Optional[bool] = _copy_default,
+    **kwargs,
+) -> ndarray:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    with cp.cuda.Device(device):
+        # cupy is like NumPy 1.26 (except without _CopyMode). See the comments
+        # in asarray in numpy/_aliases.py.
+        if copy is not _copy_default:
+            # A future version of CuPy will change the meaning of copy=False
+            # to mean no-copy. We don't know for certain what version it will
+            # be yet, so to avoid breaking that version, we use a different
+            # default value for copy so asarray(obj) with no copy kwarg will
+            # always do the copy-if-needed behavior.
+
+            # This will still need to be updated to remove the
+            # NotImplementedError for copy=False, but at least this won't
+            # break the default or existing behavior.
+            if copy is None:
+                copy = False
+            elif copy is False:
+                raise NotImplementedError("asarray(copy=False) is not yet supported in cupy")
+            kwargs['copy'] = copy
+
+        return cp.array(obj, dtype=dtype, **kwargs)
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(cp, 'vecdot'):
+    vecdot = cp.vecdot
+else:
+    vecdot = get_xp(cp)(_aliases.vecdot)
+
+if hasattr(cp, 'isdtype'):
+    isdtype = cp.isdtype
+else:
+    isdtype = get_xp(cp)(_aliases.isdtype)
+
+if hasattr(cp, 'unstack'):
+    unstack = cp.unstack
+else:
+    unstack = get_xp(cp)(_aliases.unstack)
+
+__all__ = _aliases.__all__ + ['__array_namespace_info__', 'asarray', 'bool',
+                              'acos', 'acosh', 'asin', 'asinh', 'atan',
+                              'atan2', 'atanh', 'bitwise_left_shift',
+                              'bitwise_invert', 'bitwise_right_shift',
+                              'concat', 'pow', 'sign']
+
+_all_ignore = ['cp', 'get_xp']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_info.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..4440807d2240fb4125229b68a4af8b562b636753
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_info.py
@@ -0,0 +1,326 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from cupy import (
+    dtype,
+    cuda,
+    bool_ as bool,
+    intp,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+    complex64,
+    complex128,
+)
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for CuPy.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for CuPy.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': cupy.float64,
+     'complex floating': cupy.complex128,
+     'integral': cupy.int64,
+     'indexing': cupy.int64}
+
+    """
+
+    __module__ = 'cupy'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for CuPy.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          CuPy.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new CuPy arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : str
+            The default device used for new CuPy arrays.
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_device()
+        Device(0)
+
+        """
+        return cuda.Device(0)
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new CuPy arrays.
+
+        For CuPy, this always returns the following dictionary:
+
+        - **"real floating"**: ``cupy.float64``
+        - **"complex floating"**: ``cupy.complex128``
+        - **"integral"**: ``cupy.intp``
+        - **"indexing"**: ``cupy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new CuPy
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': cupy.float64,
+         'complex floating': cupy.complex128,
+         'integral': cupy.int64,
+         'indexing': cupy.int64}
+
+        """
+        # TODO: Does this depend on device?
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by CuPy.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            CuPy data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = xp.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': cupy.int8,
+         'int16': cupy.int16,
+         'int32': cupy.int32,
+         'int64': cupy.int64}
+
+        """
+        # TODO: Does this depend on device?
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self):
+        """
+        The devices supported by CuPy.
+
+        Returns
+        -------
+        devices : list of str
+            The devices supported by CuPy.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        """
+        return [cuda.Device(i) for i in range(cuda.runtime.getDeviceCount())]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3d9aab67e52f3300cd96c3d0e701d1604eaccbb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/_typing.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+__all__ = [
+    "ndarray",
+    "Device",
+    "Dtype",
+]
+
+import sys
+from typing import (
+    Union,
+    TYPE_CHECKING,
+)
+
+from cupy import (
+    ndarray,
+    dtype,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+)
+
+from cupy.cuda.device import Device
+
+if TYPE_CHECKING or sys.version_info >= (3, 9):
+    Dtype = dtype[Union[
+        int8,
+        int16,
+        int32,
+        int64,
+        uint8,
+        uint16,
+        uint32,
+        uint64,
+        float32,
+        float64,
+    ]]
+else:
+    Dtype = dtype
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/fft.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..307e0f7277710693063ef8c4d2cd7893275ad44a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/fft.py
@@ -0,0 +1,36 @@
+from cupy.fft import * # noqa: F403
+# cupy.fft doesn't have __all__. If it is added, replace this with
+#
+# from cupy.fft import __all__ as linalg_all
+_n = {}
+exec('from cupy.fft import *', _n)
+del _n['__builtins__']
+fft_all = list(_n)
+del _n
+
+from ..common import _fft
+from .._internal import get_xp
+
+import cupy as cp
+
+fft = get_xp(cp)(_fft.fft)
+ifft = get_xp(cp)(_fft.ifft)
+fftn = get_xp(cp)(_fft.fftn)
+ifftn = get_xp(cp)(_fft.ifftn)
+rfft = get_xp(cp)(_fft.rfft)
+irfft = get_xp(cp)(_fft.irfft)
+rfftn = get_xp(cp)(_fft.rfftn)
+irfftn = get_xp(cp)(_fft.irfftn)
+hfft = get_xp(cp)(_fft.hfft)
+ihfft = get_xp(cp)(_fft.ihfft)
+fftfreq = get_xp(cp)(_fft.fftfreq)
+rfftfreq = get_xp(cp)(_fft.rfftfreq)
+fftshift = get_xp(cp)(_fft.fftshift)
+ifftshift = get_xp(cp)(_fft.ifftshift)
+
+__all__ = fft_all + _fft.__all__
+
+del get_xp
+del cp
+del fft_all
+del _fft
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fcdd498e0073ada094a20a9ae423e01cb0f8ceb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/cupy/linalg.py
@@ -0,0 +1,49 @@
+from cupy.linalg import * # noqa: F403
+# cupy.linalg doesn't have __all__. If it is added, replace this with
+#
+# from cupy.linalg import __all__ as linalg_all
+_n = {}
+exec('from cupy.linalg import *', _n)
+del _n['__builtins__']
+linalg_all = list(_n)
+del _n
+
+from ..common import _linalg
+from .._internal import get_xp
+
+import cupy as cp
+
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot # noqa: F401
+
+cross = get_xp(cp)(_linalg.cross)
+outer = get_xp(cp)(_linalg.outer)
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+eigh = get_xp(cp)(_linalg.eigh)
+qr = get_xp(cp)(_linalg.qr)
+slogdet = get_xp(cp)(_linalg.slogdet)
+svd = get_xp(cp)(_linalg.svd)
+cholesky = get_xp(cp)(_linalg.cholesky)
+matrix_rank = get_xp(cp)(_linalg.matrix_rank)
+pinv = get_xp(cp)(_linalg.pinv)
+matrix_norm = get_xp(cp)(_linalg.matrix_norm)
+svdvals = get_xp(cp)(_linalg.svdvals)
+diagonal = get_xp(cp)(_linalg.diagonal)
+trace = get_xp(cp)(_linalg.trace)
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(cp.linalg, 'vector_norm'):
+    vector_norm = cp.linalg.vector_norm
+else:
+    vector_norm = get_xp(cp)(_linalg.vector_norm)
+
+__all__ = linalg_all + _linalg.__all__
+
+del get_xp
+del cp
+del linalg_all
+del _linalg
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b49be6cf38f1d905c75278fdb857692f11adcdea
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/__init__.py
@@ -0,0 +1,9 @@
+from dask.array import * # noqa: F403
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+__array_api_version__ = '2023.12'
+
+__import__(__package__ + '.linalg')
+__import__(__package__ + '.fft')
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee2d88c048b29f603e54818319cb7f7163d43b36
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_aliases.py
@@ -0,0 +1,217 @@
+from __future__ import annotations
+
+from ...common import _aliases
+from ...common._helpers import _check_device
+
+from ..._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+import numpy as np
+from numpy import (
+    # Dtypes
+    iinfo,
+    finfo,
+    bool_ as bool,
+    float32,
+    float64,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    complex64,
+    complex128,
+    can_cast,
+    result_type,
+)
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Union
+
+    from ...common._typing import Device, Dtype, Array, NestedSequence, SupportsBufferProtocol
+
+import dask.array as da
+
+isdtype = get_xp(np)(_aliases.isdtype)
+unstack = get_xp(da)(_aliases.unstack)
+astype = _aliases.astype
+
+# Common aliases
+
+# This arange func is modified from the common one to
+# not pass stop/step as keyword arguments, which will cause
+# an error with dask
+
+# TODO: delete the xp stuff, it shouldn't be necessary
+def _dask_arange(
+    start: Union[int, float],
+    /,
+    stop: Optional[Union[int, float]] = None,
+    step: Union[int, float] = 1,
+    *,
+    xp,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    **kwargs,
+) -> Array:
+    _check_device(xp, device)
+    args = [start]
+    if stop is not None:
+        args.append(stop)
+    else:
+        # stop is None, so start is actually stop
+        # prepend the default value for start which is 0
+        args.insert(0, 0)
+    args.append(step)
+    return xp.arange(*args, dtype=dtype, **kwargs)
+
+arange = get_xp(da)(_dask_arange)
+eye = get_xp(da)(_aliases.eye)
+
+linspace = get_xp(da)(_aliases.linspace)
+eye = get_xp(da)(_aliases.eye)
+UniqueAllResult = get_xp(da)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(da)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(da)(_aliases.UniqueInverseResult)
+unique_all = get_xp(da)(_aliases.unique_all)
+unique_counts = get_xp(da)(_aliases.unique_counts)
+unique_inverse = get_xp(da)(_aliases.unique_inverse)
+unique_values = get_xp(da)(_aliases.unique_values)
+permute_dims = get_xp(da)(_aliases.permute_dims)
+std = get_xp(da)(_aliases.std)
+var = get_xp(da)(_aliases.var)
+cumulative_sum = get_xp(da)(_aliases.cumulative_sum)
+empty = get_xp(da)(_aliases.empty)
+empty_like = get_xp(da)(_aliases.empty_like)
+full = get_xp(da)(_aliases.full)
+full_like = get_xp(da)(_aliases.full_like)
+ones = get_xp(da)(_aliases.ones)
+ones_like = get_xp(da)(_aliases.ones_like)
+zeros = get_xp(da)(_aliases.zeros)
+zeros_like = get_xp(da)(_aliases.zeros_like)
+reshape = get_xp(da)(_aliases.reshape)
+matrix_transpose = get_xp(da)(_aliases.matrix_transpose)
+vecdot = get_xp(da)(_aliases.vecdot)
+
+nonzero = get_xp(da)(_aliases.nonzero)
+ceil = get_xp(np)(_aliases.ceil)
+floor = get_xp(np)(_aliases.floor)
+trunc = get_xp(np)(_aliases.trunc)
+matmul = get_xp(np)(_aliases.matmul)
+tensordot = get_xp(np)(_aliases.tensordot)
+sign = get_xp(np)(_aliases.sign)
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+def asarray(
+    obj: Union[
+        Array,
+        bool,
+        int,
+        float,
+        NestedSequence[bool | int | float],
+        SupportsBufferProtocol,
+    ],
+    /,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    copy: "Optional[Union[bool, np._CopyMode]]" = None,
+    **kwargs,
+) -> Array:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    if copy is False:
+        # copy=False is not yet implemented in dask
+        raise NotImplementedError("copy=False is not yet implemented")
+    elif copy is True:
+        if isinstance(obj, da.Array) and dtype is None:
+            return obj.copy()
+        # Go through numpy, since dask copy is no-op by default
+        obj = np.array(obj, dtype=dtype, copy=True)
+        return da.array(obj, dtype=dtype)
+    else:
+        if not isinstance(obj, da.Array) or dtype is not None and obj.dtype != dtype:
+            obj = np.asarray(obj, dtype=dtype)
+            return da.from_array(obj)
+        return obj
+
+    return da.asarray(obj, dtype=dtype, **kwargs)
+
+from dask.array import (
+    # Element wise aliases
+    arccos as acos,
+    arccosh as acosh,
+    arcsin as asin,
+    arcsinh as asinh,
+    arctan as atan,
+    arctan2 as atan2,
+    arctanh as atanh,
+    left_shift as bitwise_left_shift,
+    right_shift as bitwise_right_shift,
+    invert as bitwise_invert,
+    power as pow,
+    # Other
+    concatenate as concat,
+)
+
+# dask.array.clip does not work unless all three arguments are provided.
+# Furthermore, the masking workaround in common._aliases.clip cannot work with
+# dask (meaning uint64 promoting to float64 is going to just be unfixed for
+# now).
+@get_xp(da)
+def clip(
+    x: Array,
+    /,
+    min: Optional[Union[int, float, Array]] = None,
+    max: Optional[Union[int, float, Array]] = None,
+    *,
+    xp,
+) -> Array:
+    def _isscalar(a):
+        return isinstance(a, (int, float, type(None)))
+    min_shape = () if _isscalar(min) else min.shape
+    max_shape = () if _isscalar(max) else max.shape
+
+    # TODO: This won't handle dask unknown shapes
+    import numpy as np
+    result_shape = np.broadcast_shapes(x.shape, min_shape, max_shape)
+
+    if min is not None:
+        min = xp.broadcast_to(xp.asarray(min), result_shape)
+    if max is not None:
+        max = xp.broadcast_to(xp.asarray(max), result_shape)
+
+    if min is None and max is None:
+        return xp.positive(x)
+
+    if min is None:
+        return astype(xp.minimum(x, max), x.dtype)
+    if max is None:
+        return astype(xp.maximum(x, min), x.dtype)
+
+    return astype(xp.minimum(xp.maximum(x, min), max), x.dtype)
+
+# exclude these from all since dask.array has no sorting functions
+_da_unsupported = ['sort', 'argsort']
+
+_common_aliases = [alias for alias in _aliases.__all__ if alias not in _da_unsupported]
+
+__all__ = _common_aliases + ['__array_namespace_info__', 'asarray', 'acos',
+                    'acosh', 'asin', 'asinh', 'atan', 'atan2',
+                    'atanh', 'bitwise_left_shift', 'bitwise_invert',
+                    'bitwise_right_shift', 'concat', 'pow', 'iinfo', 'finfo', 'can_cast',
+                    'result_type', 'bool', 'float32', 'float64', 'int8', 'int16', 'int32', 'int64',
+                    'uint8', 'uint16', 'uint32', 'uint64',
+                    'complex64', 'complex128', 'iinfo', 'finfo',
+                    'can_cast', 'result_type']
+
+_all_ignore = ["get_xp", "da", "np"]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3b12dc960f5a7a5d5a8dfb3345c0ad1f4d470e7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/_info.py
@@ -0,0 +1,345 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from numpy import (
+    dtype,
+    bool_ as bool,
+    intp,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+    complex64,
+    complex128,
+)
+
+from ...common._helpers import _DASK_DEVICE
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for Dask.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for Dask.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': dask.float64,
+     'complex floating': dask.complex128,
+     'integral': dask.int64,
+     'indexing': dask.int64}
+
+    """
+
+    __module__ = 'dask.array'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``False`` for Dask.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``False`` for
+          Dask.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True}
+
+        """
+        return {
+            "boolean indexing": False,
+            "data-dependent shapes": False,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new Dask arrays.
+
+        For Dask, this always returns ``'cpu'``.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : str
+            The default device used for new Dask arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return "cpu"
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new Dask arrays.
+
+        For Dask, this always returns the following dictionary:
+
+        - **"real floating"**: ``numpy.float64``
+        - **"complex floating"**: ``numpy.complex128``
+        - **"integral"**: ``numpy.intp``
+        - **"indexing"**: ``numpy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new Dask
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': dask.float64,
+         'complex floating': dask.complex128,
+         'integral': dask.int64,
+         'indexing': dask.int64}
+
+        """
+        if device not in ["cpu", _DASK_DEVICE, None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" or _DASK_DEVICE is allowed, but received:'
+                f' {device}'
+            )
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by Dask.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            Dask data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': dask.int8,
+         'int16': dask.int16,
+         'int32': dask.int32,
+         'int64': dask.int64}
+
+        """
+        if device not in ["cpu", _DASK_DEVICE, None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" or _DASK_DEVICE is allowed, but received:'
+                f' {device}'
+            )
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self):
+        """
+        The devices supported by Dask.
+
+        For Dask, this always returns ``['cpu', DASK_DEVICE]``.
+
+        Returns
+        -------
+        devices : list of str
+            The devices supported by Dask.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.devices()
+        ['cpu', DASK_DEVICE]
+
+        """
+        return ["cpu", _DASK_DEVICE]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..aebd86f7b201d9eb7cd707b25ab3fae117f2d6e5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/fft.py
@@ -0,0 +1,24 @@
+from dask.array.fft import * # noqa: F403
+# dask.array.fft doesn't have __all__. If it is added, replace this with
+#
+# from dask.array.fft import __all__ as linalg_all
+_n = {}
+exec('from dask.array.fft import *', _n)
+del _n['__builtins__']
+fft_all = list(_n)
+del _n
+
+from ...common import _fft
+from ..._internal import get_xp
+
+import dask.array as da
+
+fftfreq = get_xp(da)(_fft.fftfreq)
+rfftfreq = get_xp(da)(_fft.rfftfreq)
+
+__all__ = [elem for elem in fft_all if elem != "annotations"] + ["fftfreq", "rfftfreq"]
+
+del get_xp
+del da
+del fft_all
+del _fft
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..49c26d8b819f88e226e34e02947a1ecf50c4895e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/dask/array/linalg.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from ...common import _linalg
+from ..._internal import get_xp
+
+# Exports
+from dask.array.linalg import * # noqa: F403
+from dask.array import outer
+
+# These functions are in both the main and linalg namespaces
+from dask.array import matmul, tensordot
+from ._aliases import matrix_transpose, vecdot
+
+import dask.array as da
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from ...common._typing import Array
+    from typing import Literal
+
+# dask.array.linalg doesn't have __all__. If it is added, replace this with
+#
+# from dask.array.linalg import __all__ as linalg_all
+_n = {}
+exec('from dask.array.linalg import *', _n)
+del _n['__builtins__']
+if 'annotations' in _n:
+    del _n['annotations']
+linalg_all = list(_n)
+del _n
+
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+# TODO: use the QR wrapper once dask
+# supports the mode keyword on QR
+# https://github.com/dask/dask/issues/10388
+#qr = get_xp(da)(_linalg.qr)
+def qr(x: Array, mode: Literal['reduced', 'complete'] = 'reduced',
+       **kwargs) -> QRResult:
+    if mode != "reduced":
+        raise ValueError("dask arrays only support using mode='reduced'")
+    return QRResult(*da.linalg.qr(x, **kwargs))
+trace = get_xp(da)(_linalg.trace)
+cholesky = get_xp(da)(_linalg.cholesky)
+matrix_rank = get_xp(da)(_linalg.matrix_rank)
+matrix_norm = get_xp(da)(_linalg.matrix_norm)
+
+
+# Wrap the svd functions to not pass full_matrices to dask
+# when full_matrices=False (as that is the default behavior for dask),
+# and dask doesn't have the full_matrices keyword
+def svd(x: Array, full_matrices: bool = True, **kwargs) -> SVDResult:
+    if full_matrices:
+        raise ValueError("full_matrics=True is not supported by dask.")
+    return da.linalg.svd(x, coerce_signs=False, **kwargs)
+
+def svdvals(x: Array) -> Array:
+    # TODO: can't avoid computing U or V for dask
+    _, s, _ =  svd(x)
+    return s
+
+vector_norm = get_xp(da)(_linalg.vector_norm)
+diagonal = get_xp(da)(_linalg.diagonal)
+
+__all__ = linalg_all + ["trace", "outer", "matmul", "tensordot",
+                        "matrix_transpose", "vecdot", "EighResult",
+                        "QRResult", "SlogdetResult", "SVDResult", "qr",
+                        "cholesky", "matrix_rank", "matrix_norm", "svdvals",
+                        "vector_norm", "diagonal"]
+
+_all_ignore = ['get_xp', 'da', 'linalg_all']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bdbf31293d480f8a8a266dd096e6aa92e1cc48e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__init__.py
@@ -0,0 +1,30 @@
+from numpy import * # noqa: F403
+
+# from numpy import * doesn't overwrite these builtin names
+from numpy import abs, max, min, round # noqa: F401
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# Don't know why, but we have to do an absolute import to import linalg. If we
+# instead do
+#
+# from . import linalg
+#
+# It doesn't overwrite np.linalg from above. The import is generated
+# dynamically so that the library can be vendored.
+__import__(__package__ + '.linalg')
+
+__import__(__package__ + '.fft')
+
+from .linalg import matrix_transpose, vecdot # noqa: F401
+
+from ..common._helpers import * # noqa: F403
+
+try:
+    # Used in asarray(). Not present in older versions.
+    from numpy import _CopyMode # noqa: F401
+except ImportError:
+    pass
+
+__array_api_version__ = '2023.12'
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31eb6c051b212c7072cb8a67eeecc82b0fd826f7
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f78e8e85a15d18f10fa85809435b62a74042054b
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_aliases.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c911b69088f02eb9f974cb8bf16d594d6a5106a6
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/_info.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9dc5aba7cdc0d815b8e4f6fcf064e00b8d40f48b
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/fft.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e50cd2e14892b1c71f3a589ce768907baaeec9b0
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/__pycache__/linalg.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bfc98ff7ba4082a3986652b85dc15fdd85350ad
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_aliases.py
@@ -0,0 +1,141 @@
+from __future__ import annotations
+
+from ..common import _aliases
+
+from .._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import Optional, Union
+    from ._typing import ndarray, Device, Dtype, NestedSequence, SupportsBufferProtocol
+
+import numpy as np
+bool = np.bool_
+
+# Basic renames
+acos = np.arccos
+acosh = np.arccosh
+asin = np.arcsin
+asinh = np.arcsinh
+atan = np.arctan
+atan2 = np.arctan2
+atanh = np.arctanh
+bitwise_left_shift = np.left_shift
+bitwise_invert = np.invert
+bitwise_right_shift = np.right_shift
+concat = np.concatenate
+pow = np.power
+
+arange = get_xp(np)(_aliases.arange)
+empty = get_xp(np)(_aliases.empty)
+empty_like = get_xp(np)(_aliases.empty_like)
+eye = get_xp(np)(_aliases.eye)
+full = get_xp(np)(_aliases.full)
+full_like = get_xp(np)(_aliases.full_like)
+linspace = get_xp(np)(_aliases.linspace)
+ones = get_xp(np)(_aliases.ones)
+ones_like = get_xp(np)(_aliases.ones_like)
+zeros = get_xp(np)(_aliases.zeros)
+zeros_like = get_xp(np)(_aliases.zeros_like)
+UniqueAllResult = get_xp(np)(_aliases.UniqueAllResult)
+UniqueCountsResult = get_xp(np)(_aliases.UniqueCountsResult)
+UniqueInverseResult = get_xp(np)(_aliases.UniqueInverseResult)
+unique_all = get_xp(np)(_aliases.unique_all)
+unique_counts = get_xp(np)(_aliases.unique_counts)
+unique_inverse = get_xp(np)(_aliases.unique_inverse)
+unique_values = get_xp(np)(_aliases.unique_values)
+astype = _aliases.astype
+std = get_xp(np)(_aliases.std)
+var = get_xp(np)(_aliases.var)
+cumulative_sum = get_xp(np)(_aliases.cumulative_sum)
+clip = get_xp(np)(_aliases.clip)
+permute_dims = get_xp(np)(_aliases.permute_dims)
+reshape = get_xp(np)(_aliases.reshape)
+argsort = get_xp(np)(_aliases.argsort)
+sort = get_xp(np)(_aliases.sort)
+nonzero = get_xp(np)(_aliases.nonzero)
+ceil = get_xp(np)(_aliases.ceil)
+floor = get_xp(np)(_aliases.floor)
+trunc = get_xp(np)(_aliases.trunc)
+matmul = get_xp(np)(_aliases.matmul)
+matrix_transpose = get_xp(np)(_aliases.matrix_transpose)
+tensordot = get_xp(np)(_aliases.tensordot)
+sign = get_xp(np)(_aliases.sign)
+
+def _supports_buffer_protocol(obj):
+    try:
+        memoryview(obj)
+    except TypeError:
+        return False
+    return True
+
+# asarray also adds the copy keyword, which is not present in numpy 1.0.
+# asarray() is different enough between numpy, cupy, and dask, the logic
+# complicated enough that it's easier to define it separately for each module
+# rather than trying to combine everything into one function in common/
+def asarray(
+    obj: Union[
+        ndarray,
+        bool,
+        int,
+        float,
+        NestedSequence[bool | int | float],
+        SupportsBufferProtocol,
+    ],
+    /,
+    *,
+    dtype: Optional[Dtype] = None,
+    device: Optional[Device] = None,
+    copy: "Optional[Union[bool, np._CopyMode]]" = None,
+    **kwargs,
+) -> ndarray:
+    """
+    Array API compatibility wrapper for asarray().
+
+    See the corresponding documentation in the array library and/or the array API
+    specification for more details.
+    """
+    if device not in ["cpu", None]:
+        raise ValueError(f"Unsupported device for NumPy: {device!r}")
+
+    if hasattr(np, '_CopyMode'):
+        if copy is None:
+            copy = np._CopyMode.IF_NEEDED
+        elif copy is False:
+            copy = np._CopyMode.NEVER
+        elif copy is True:
+            copy = np._CopyMode.ALWAYS
+    else:
+        # Not present in older NumPys. In this case, we cannot really support
+        # copy=False.
+        if copy is False:
+            raise NotImplementedError("asarray(copy=False) requires a newer version of NumPy.")
+
+    return np.array(obj, copy=copy, dtype=dtype, **kwargs)
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(np, 'vecdot'):
+    vecdot = np.vecdot
+else:
+    vecdot = get_xp(np)(_aliases.vecdot)
+
+if hasattr(np, 'isdtype'):
+    isdtype = np.isdtype
+else:
+    isdtype = get_xp(np)(_aliases.isdtype)
+
+if hasattr(np, 'unstack'):
+    unstack = np.unstack
+else:
+    unstack = get_xp(np)(_aliases.unstack)
+
+__all__ = _aliases.__all__ + ['__array_namespace_info__', 'asarray', 'bool',
+                              'acos', 'acosh', 'asin', 'asinh', 'atan',
+                              'atan2', 'atanh', 'bitwise_left_shift',
+                              'bitwise_invert', 'bitwise_right_shift',
+                              'concat', 'pow']
+
+_all_ignore = ['np', 'get_xp']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_info.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..62f7ae62ca242cc17def5703b4412823aa31abcd
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_info.py
@@ -0,0 +1,346 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+from numpy import (
+    dtype,
+    bool_ as bool,
+    intp,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+    complex64,
+    complex128,
+)
+
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for NumPy.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for NumPy.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': numpy.float64,
+     'complex floating': numpy.complex128,
+     'integral': numpy.int64,
+     'indexing': numpy.int64}
+
+    """
+
+    __module__ = 'numpy'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for NumPy.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          NumPy.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new NumPy arrays.
+
+        For NumPy, this always returns ``'cpu'``.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : str
+            The default device used for new NumPy arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return "cpu"
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new NumPy arrays.
+
+        For NumPy, this always returns the following dictionary:
+
+        - **"real floating"**: ``numpy.float64``
+        - **"complex floating"**: ``numpy.complex128``
+        - **"integral"**: ``numpy.intp``
+        - **"indexing"**: ``numpy.intp``
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for. For NumPy, only
+            ``'cpu'`` is allowed.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new NumPy
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': numpy.float64,
+         'complex floating': numpy.complex128,
+         'integral': numpy.int64,
+         'indexing': numpy.int64}
+
+        """
+        if device not in ["cpu", None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" is allowed, but received:'
+                f' {device}'
+            )
+        return {
+            "real floating": dtype(float64),
+            "complex floating": dtype(complex128),
+            "integral": dtype(intp),
+            "indexing": dtype(intp),
+        }
+
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by NumPy.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for. For NumPy, only ``'cpu'`` is
+            allowed.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            NumPy data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': numpy.int8,
+         'int16': numpy.int16,
+         'int32': numpy.int32,
+         'int64': numpy.int64}
+
+        """
+        if device not in ["cpu", None]:
+            raise ValueError(
+                'Device not understood. Only "cpu" is allowed, but received:'
+                f' {device}'
+            )
+        if kind is None:
+            return {
+                "bool": dtype(bool),
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "integral":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+            }
+        if kind == "real floating":
+            return {
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if kind == "numeric":
+            return {
+                "int8": dtype(int8),
+                "int16": dtype(int16),
+                "int32": dtype(int32),
+                "int64": dtype(int64),
+                "uint8": dtype(uint8),
+                "uint16": dtype(uint16),
+                "uint32": dtype(uint32),
+                "uint64": dtype(uint64),
+                "float32": dtype(float32),
+                "float64": dtype(float64),
+                "complex64": dtype(complex64),
+                "complex128": dtype(complex128),
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    def devices(self):
+        """
+        The devices supported by NumPy.
+
+        For NumPy, this always returns ``['cpu']``.
+
+        Returns
+        -------
+        devices : list of str
+            The devices supported by NumPy.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.devices()
+        ['cpu']
+
+        """
+        return ["cpu"]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5ebb5abb987572be625ee864a37e61126d36d8b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/_typing.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+__all__ = [
+    "ndarray",
+    "Device",
+    "Dtype",
+]
+
+import sys
+from typing import (
+    Literal,
+    Union,
+    TYPE_CHECKING,
+)
+
+from numpy import (
+    ndarray,
+    dtype,
+    int8,
+    int16,
+    int32,
+    int64,
+    uint8,
+    uint16,
+    uint32,
+    uint64,
+    float32,
+    float64,
+)
+
+Device = Literal["cpu"]
+if TYPE_CHECKING or sys.version_info >= (3, 9):
+    Dtype = dtype[Union[
+        int8,
+        int16,
+        int32,
+        int64,
+        uint8,
+        uint16,
+        uint32,
+        uint64,
+        float32,
+        float64,
+    ]]
+else:
+    Dtype = dtype
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/fft.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..286675946e0fbb0aa18105d25db08ebbbd2e4d0c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/fft.py
@@ -0,0 +1,29 @@
+from numpy.fft import * # noqa: F403
+from numpy.fft import __all__ as fft_all
+
+from ..common import _fft
+from .._internal import get_xp
+
+import numpy as np
+
+fft = get_xp(np)(_fft.fft)
+ifft = get_xp(np)(_fft.ifft)
+fftn = get_xp(np)(_fft.fftn)
+ifftn = get_xp(np)(_fft.ifftn)
+rfft = get_xp(np)(_fft.rfft)
+irfft = get_xp(np)(_fft.irfft)
+rfftn = get_xp(np)(_fft.rfftn)
+irfftn = get_xp(np)(_fft.irfftn)
+hfft = get_xp(np)(_fft.hfft)
+ihfft = get_xp(np)(_fft.ihfft)
+fftfreq = get_xp(np)(_fft.fftfreq)
+rfftfreq = get_xp(np)(_fft.rfftfreq)
+fftshift = get_xp(np)(_fft.fftshift)
+ifftshift = get_xp(np)(_fft.ifftshift)
+
+__all__ = fft_all + _fft.__all__
+
+del get_xp
+del np
+del fft_all
+del _fft
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f01593bd0ae619b3bea471980b4eeabfc29f319
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/numpy/linalg.py
@@ -0,0 +1,90 @@
+from numpy.linalg import * # noqa: F403
+from numpy.linalg import __all__ as linalg_all
+import numpy as _np
+
+from ..common import _linalg
+from .._internal import get_xp
+
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot, vecdot # noqa: F401
+
+import numpy as np
+
+cross = get_xp(np)(_linalg.cross)
+outer = get_xp(np)(_linalg.outer)
+EighResult = _linalg.EighResult
+QRResult = _linalg.QRResult
+SlogdetResult = _linalg.SlogdetResult
+SVDResult = _linalg.SVDResult
+eigh = get_xp(np)(_linalg.eigh)
+qr = get_xp(np)(_linalg.qr)
+slogdet = get_xp(np)(_linalg.slogdet)
+svd = get_xp(np)(_linalg.svd)
+cholesky = get_xp(np)(_linalg.cholesky)
+matrix_rank = get_xp(np)(_linalg.matrix_rank)
+pinv = get_xp(np)(_linalg.pinv)
+matrix_norm = get_xp(np)(_linalg.matrix_norm)
+svdvals = get_xp(np)(_linalg.svdvals)
+diagonal = get_xp(np)(_linalg.diagonal)
+trace = get_xp(np)(_linalg.trace)
+
+# Note: unlike np.linalg.solve, the array API solve() only accepts x2 as a
+# vector when it is exactly 1-dimensional. All other cases treat x2 as a stack
+# of matrices. The np.linalg.solve behavior of allowing stacks of both
+# matrices and vectors is ambiguous c.f.
+# https://github.com/numpy/numpy/issues/15349 and
+# https://github.com/data-apis/array-api/issues/285.
+
+# To workaround this, the below is the code from np.linalg.solve except
+# only calling solve1 in the exactly 1D case.
+
+# This code is here instead of in common because it is numpy specific. Also
+# note that CuPy's solve() does not currently support broadcasting (see
+# https://github.com/cupy/cupy/blob/main/cupy/cublas.py#L43).
+def solve(x1: _np.ndarray, x2: _np.ndarray, /) -> _np.ndarray:
+    try:
+        from numpy.linalg._linalg import (
+        _makearray, _assert_stacked_2d, _assert_stacked_square,
+        _commonType, isComplexType, _raise_linalgerror_singular
+        )
+    except ImportError:
+        from numpy.linalg.linalg import (
+        _makearray, _assert_stacked_2d, _assert_stacked_square,
+        _commonType, isComplexType, _raise_linalgerror_singular
+        )
+    from numpy.linalg import _umath_linalg
+
+    x1, _ = _makearray(x1)
+    _assert_stacked_2d(x1)
+    _assert_stacked_square(x1)
+    x2, wrap = _makearray(x2)
+    t, result_t = _commonType(x1, x2)
+
+    # This part is different from np.linalg.solve
+    if x2.ndim == 1:
+        gufunc = _umath_linalg.solve1
+    else:
+        gufunc = _umath_linalg.solve
+
+    # This does nothing currently but is left in because it will be relevant
+    # when complex dtype support is added to the spec in 2022.
+    signature = 'DD->D' if isComplexType(t) else 'dd->d'
+    with _np.errstate(call=_raise_linalgerror_singular, invalid='call',
+                      over='ignore', divide='ignore', under='ignore'):
+        r = gufunc(x1, x2, signature=signature)
+
+    return wrap(r.astype(result_t, copy=False))
+
+# These functions are completely new here. If the library already has them
+# (i.e., numpy 2.0), use the library version instead of our wrapper.
+if hasattr(np.linalg, 'vector_norm'):
+    vector_norm = np.linalg.vector_norm
+else:
+    vector_norm = get_xp(np)(_linalg.vector_norm)
+
+__all__ = linalg_all + _linalg.__all__ + ['solve']
+
+del get_xp
+del np
+del linalg_all
+del _linalg
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfa3acf8945a84c8e3fcdc892edc19d4f674cd30
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/__init__.py
@@ -0,0 +1,24 @@
+from torch import * # noqa: F403
+
+# Several names are not included in the above import *
+import torch
+for n in dir(torch):
+    if (n.startswith('_')
+        or n.endswith('_')
+        or 'cuda' in n
+        or 'cpu' in n
+        or 'backward' in n):
+        continue
+    exec(n + ' = torch.' + n)
+
+# These imports may overwrite names from the import * above.
+from ._aliases import * # noqa: F403
+
+# See the comment in the numpy __init__.py
+__import__(__package__ + '.linalg')
+
+__import__(__package__ + '.fft')
+
+from ..common._helpers import * # noqa: F403
+
+__array_api_version__ = '2023.12'
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ac66bcb17e6f13a51bd6c7fd345bee23c16140f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_aliases.py
@@ -0,0 +1,752 @@
+from __future__ import annotations
+
+from functools import wraps as _wraps
+from builtins import all as _builtin_all, any as _builtin_any
+
+from ..common._aliases import (matrix_transpose as _aliases_matrix_transpose,
+                               vecdot as _aliases_vecdot,
+                               clip as _aliases_clip,
+                               unstack as _aliases_unstack,
+                               cumulative_sum as _aliases_cumulative_sum,
+                               )
+from .._internal import get_xp
+
+from ._info import __array_namespace_info__
+
+import torch
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    from typing import List, Optional, Sequence, Tuple, Union
+    from ..common._typing import Device
+    from torch import dtype as Dtype
+
+    array = torch.Tensor
+
+_int_dtypes = {
+    torch.uint8,
+    torch.int8,
+    torch.int16,
+    torch.int32,
+    torch.int64,
+}
+
+_array_api_dtypes = {
+    torch.bool,
+    *_int_dtypes,
+    torch.float32,
+    torch.float64,
+    torch.complex64,
+    torch.complex128,
+}
+
+_promotion_table  = {
+    # bool
+    (torch.bool, torch.bool): torch.bool,
+    # ints
+    (torch.int8, torch.int8): torch.int8,
+    (torch.int8, torch.int16): torch.int16,
+    (torch.int8, torch.int32): torch.int32,
+    (torch.int8, torch.int64): torch.int64,
+    (torch.int16, torch.int8): torch.int16,
+    (torch.int16, torch.int16): torch.int16,
+    (torch.int16, torch.int32): torch.int32,
+    (torch.int16, torch.int64): torch.int64,
+    (torch.int32, torch.int8): torch.int32,
+    (torch.int32, torch.int16): torch.int32,
+    (torch.int32, torch.int32): torch.int32,
+    (torch.int32, torch.int64): torch.int64,
+    (torch.int64, torch.int8): torch.int64,
+    (torch.int64, torch.int16): torch.int64,
+    (torch.int64, torch.int32): torch.int64,
+    (torch.int64, torch.int64): torch.int64,
+    # uints
+    (torch.uint8, torch.uint8): torch.uint8,
+    # ints and uints (mixed sign)
+    (torch.int8, torch.uint8): torch.int16,
+    (torch.int16, torch.uint8): torch.int16,
+    (torch.int32, torch.uint8): torch.int32,
+    (torch.int64, torch.uint8): torch.int64,
+    (torch.uint8, torch.int8): torch.int16,
+    (torch.uint8, torch.int16): torch.int16,
+    (torch.uint8, torch.int32): torch.int32,
+    (torch.uint8, torch.int64): torch.int64,
+    # floats
+    (torch.float32, torch.float32): torch.float32,
+    (torch.float32, torch.float64): torch.float64,
+    (torch.float64, torch.float32): torch.float64,
+    (torch.float64, torch.float64): torch.float64,
+    # complexes
+    (torch.complex64, torch.complex64): torch.complex64,
+    (torch.complex64, torch.complex128): torch.complex128,
+    (torch.complex128, torch.complex64): torch.complex128,
+    (torch.complex128, torch.complex128): torch.complex128,
+    # Mixed float and complex
+    (torch.float32, torch.complex64): torch.complex64,
+    (torch.float32, torch.complex128): torch.complex128,
+    (torch.float64, torch.complex64): torch.complex128,
+    (torch.float64, torch.complex128): torch.complex128,
+}
+
+
+def _two_arg(f):
+    @_wraps(f)
+    def _f(x1, x2, /, **kwargs):
+        x1, x2 = _fix_promotion(x1, x2)
+        return f(x1, x2, **kwargs)
+    if _f.__doc__ is None:
+        _f.__doc__ = f"""\
+Array API compatibility wrapper for torch.{f.__name__}.
+
+See the corresponding PyTorch documentation and/or the array API specification
+for more details.
+
+"""
+    return _f
+
+def _fix_promotion(x1, x2, only_scalar=True):
+    if not isinstance(x1, torch.Tensor) or not isinstance(x2, torch.Tensor):
+        return x1, x2
+    if x1.dtype not in _array_api_dtypes or x2.dtype not in _array_api_dtypes:
+        return x1, x2
+    # If an argument is 0-D pytorch downcasts the other argument
+    if not only_scalar or x1.shape == ():
+        dtype = result_type(x1, x2)
+        x2 = x2.to(dtype)
+    if not only_scalar or x2.shape == ():
+        dtype = result_type(x1, x2)
+        x1 = x1.to(dtype)
+    return x1, x2
+
+def result_type(*arrays_and_dtypes: Union[array, Dtype]) -> Dtype:
+    if len(arrays_and_dtypes) == 0:
+        raise TypeError("At least one array or dtype must be provided")
+    if len(arrays_and_dtypes) == 1:
+        x = arrays_and_dtypes[0]
+        if isinstance(x, torch.dtype):
+            return x
+        return x.dtype
+    if len(arrays_and_dtypes) > 2:
+        return result_type(arrays_and_dtypes[0], result_type(*arrays_and_dtypes[1:]))
+
+    x, y = arrays_and_dtypes
+    xdt = x.dtype if not isinstance(x, torch.dtype) else x
+    ydt = y.dtype if not isinstance(y, torch.dtype) else y
+
+    if (xdt, ydt) in _promotion_table:
+        return _promotion_table[xdt, ydt]
+
+    # This doesn't result_type(dtype, dtype) for non-array API dtypes
+    # because torch.result_type only accepts tensors. This does however, allow
+    # cross-kind promotion.
+    x = torch.tensor([], dtype=x) if isinstance(x, torch.dtype) else x
+    y = torch.tensor([], dtype=y) if isinstance(y, torch.dtype) else y
+    return torch.result_type(x, y)
+
+def can_cast(from_: Union[Dtype, array], to: Dtype, /) -> bool:
+    if not isinstance(from_, torch.dtype):
+        from_ = from_.dtype
+    return torch.can_cast(from_, to)
+
+# Basic renames
+bitwise_invert = torch.bitwise_not
+newaxis = None
+# torch.conj sets the conjugation bit, which breaks conversion to other
+# libraries. See https://github.com/data-apis/array-api-compat/issues/173
+conj = torch.conj_physical
+
+# Two-arg elementwise functions
+# These require a wrapper to do the correct type promotion on 0-D tensors
+add = _two_arg(torch.add)
+atan2 = _two_arg(torch.atan2)
+bitwise_and = _two_arg(torch.bitwise_and)
+bitwise_left_shift = _two_arg(torch.bitwise_left_shift)
+bitwise_or = _two_arg(torch.bitwise_or)
+bitwise_right_shift = _two_arg(torch.bitwise_right_shift)
+bitwise_xor = _two_arg(torch.bitwise_xor)
+copysign = _two_arg(torch.copysign)
+divide = _two_arg(torch.divide)
+# Also a rename. torch.equal does not broadcast
+equal = _two_arg(torch.eq)
+floor_divide = _two_arg(torch.floor_divide)
+greater = _two_arg(torch.greater)
+greater_equal = _two_arg(torch.greater_equal)
+hypot = _two_arg(torch.hypot)
+less = _two_arg(torch.less)
+less_equal = _two_arg(torch.less_equal)
+logaddexp = _two_arg(torch.logaddexp)
+# logical functions are not included here because they only accept bool in the
+# spec, so type promotion is irrelevant.
+maximum = _two_arg(torch.maximum)
+minimum = _two_arg(torch.minimum)
+multiply = _two_arg(torch.multiply)
+not_equal = _two_arg(torch.not_equal)
+pow = _two_arg(torch.pow)
+remainder = _two_arg(torch.remainder)
+subtract = _two_arg(torch.subtract)
+
+# These wrappers are mostly based on the fact that pytorch uses 'dim' instead
+# of 'axis'.
+
+# torch.min and torch.max return a tuple and don't support multiple axes https://github.com/pytorch/pytorch/issues/58745
+def max(x: array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False) -> array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    return torch.amax(x, axis, keepdims=keepdims)
+
+def min(x: array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False) -> array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    return torch.amin(x, axis, keepdims=keepdims)
+
+clip = get_xp(torch)(_aliases_clip)
+unstack = get_xp(torch)(_aliases_unstack)
+cumulative_sum = get_xp(torch)(_aliases_cumulative_sum)
+
+# torch.sort also returns a tuple
+# https://github.com/pytorch/pytorch/issues/70921
+def sort(x: array, /, *, axis: int = -1, descending: bool = False, stable: bool = True, **kwargs) -> array:
+    return torch.sort(x, dim=axis, descending=descending, stable=stable, **kwargs).values
+
+def _normalize_axes(axis, ndim):
+    axes = []
+    if ndim == 0 and axis:
+        # Better error message in this case
+        raise IndexError(f"Dimension out of range: {axis[0]}")
+    lower, upper = -ndim, ndim - 1
+    for a in axis:
+        if a < lower or a > upper:
+            # Match torch error message (e.g., from sum())
+            raise IndexError(f"Dimension out of range (expected to be in range of [{lower}, {upper}], but got {a}")
+        if a < 0:
+            a = a + ndim
+        if a in axes:
+            # Use IndexError instead of RuntimeError, and "axis" instead of "dim"
+            raise IndexError(f"Axis {a} appears multiple times in the list of axes")
+        axes.append(a)
+    return sorted(axes)
+
+def _axis_none_keepdims(x, ndim, keepdims):
+    # Apply keepdims when axis=None
+    # (https://github.com/pytorch/pytorch/issues/71209)
+    # Note that this is only valid for the axis=None case.
+    if keepdims:
+        for i in range(ndim):
+            x = torch.unsqueeze(x, 0)
+    return x
+
+def _reduce_multiple_axes(f, x, axis, keepdims=False, **kwargs):
+    # Some reductions don't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    axes = _normalize_axes(axis, x.ndim)
+    for a in reversed(axes):
+        x = torch.movedim(x, a, -1)
+    x = torch.flatten(x, -len(axes))
+
+    out = f(x, -1, **kwargs)
+
+    if keepdims:
+        for a in axes:
+            out = torch.unsqueeze(out, a)
+    return out
+
+def prod(x: array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         dtype: Optional[Dtype] = None,
+         keepdims: bool = False,
+         **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+
+    # https://github.com/pytorch/pytorch/issues/29137. Separate from the logic
+    # below because it still needs to upcast.
+    if axis == ():
+        if dtype is None:
+            # We can't upcast uint8 according to the spec because there is no
+            # torch.uint64, so at least upcast to int64 which is what sum does
+            # when axis=None.
+            if x.dtype in [torch.int8, torch.int16, torch.int32, torch.uint8]:
+                return x.to(torch.int64)
+            return x.clone()
+        return x.to(dtype)
+
+    # torch.prod doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        return _reduce_multiple_axes(torch.prod, x, axis, keepdims=keepdims, dtype=dtype, **kwargs)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.prod(x, dtype=dtype, **kwargs)
+        res = _axis_none_keepdims(res, ndim, keepdims)
+        return res
+
+    return torch.prod(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+
+def sum(x: array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         dtype: Optional[Dtype] = None,
+         keepdims: bool = False,
+         **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+
+    # https://github.com/pytorch/pytorch/issues/29137.
+    # Make sure it upcasts.
+    if axis == ():
+        if dtype is None:
+            # We can't upcast uint8 according to the spec because there is no
+            # torch.uint64, so at least upcast to int64 which is what sum does
+            # when axis=None.
+            if x.dtype in [torch.int8, torch.int16, torch.int32, torch.uint8]:
+                return x.to(torch.int64)
+            return x.clone()
+        return x.to(dtype)
+
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.sum(x, dtype=dtype, **kwargs)
+        res = _axis_none_keepdims(res, ndim, keepdims)
+        return res
+
+    return torch.sum(x, axis, dtype=dtype, keepdims=keepdims, **kwargs)
+
+def any(x: array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+    if axis == ():
+        return x.to(torch.bool)
+    # torch.any doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        res = _reduce_multiple_axes(torch.any, x, axis, keepdims=keepdims, **kwargs)
+        return res.to(torch.bool)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.any(x, **kwargs)
+        res = _axis_none_keepdims(res, ndim, keepdims)
+        return res.to(torch.bool)
+
+    # torch.any doesn't return bool for uint8
+    return torch.any(x, axis, keepdims=keepdims).to(torch.bool)
+
+def all(x: array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    x = torch.asarray(x)
+    ndim = x.ndim
+    if axis == ():
+        return x.to(torch.bool)
+    # torch.all doesn't support multiple axes
+    # (https://github.com/pytorch/pytorch/issues/56586).
+    if isinstance(axis, tuple):
+        res = _reduce_multiple_axes(torch.all, x, axis, keepdims=keepdims, **kwargs)
+        return res.to(torch.bool)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.all(x, **kwargs)
+        res = _axis_none_keepdims(res, ndim, keepdims)
+        return res.to(torch.bool)
+
+    # torch.all doesn't return bool for uint8
+    return torch.all(x, axis, keepdims=keepdims).to(torch.bool)
+
+def mean(x: array,
+         /,
+         *,
+         axis: Optional[Union[int, Tuple[int, ...]]] = None,
+         keepdims: bool = False,
+         **kwargs) -> array:
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.clone(x)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.mean(x, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.mean(x, axis, keepdims=keepdims, **kwargs)
+
+def std(x: array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        correction: Union[int, float] = 0.0,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    # Note, float correction is not supported
+    # https://github.com/pytorch/pytorch/issues/61492. We don't try to
+    # implement it here for now.
+
+    if isinstance(correction, float):
+        _correction = int(correction)
+        if correction != _correction:
+            raise NotImplementedError("float correction in torch std() is not yet supported")
+    else:
+        _correction = correction
+
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.zeros_like(x)
+    if isinstance(axis, int):
+        axis = (axis,)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.std(x, tuple(range(x.ndim)), correction=_correction, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.std(x, axis, correction=_correction, keepdims=keepdims, **kwargs)
+
+def var(x: array,
+        /,
+        *,
+        axis: Optional[Union[int, Tuple[int, ...]]] = None,
+        correction: Union[int, float] = 0.0,
+        keepdims: bool = False,
+        **kwargs) -> array:
+    # Note, float correction is not supported
+    # https://github.com/pytorch/pytorch/issues/61492. We don't try to
+    # implement it here for now.
+
+    # if isinstance(correction, float):
+    #     correction = int(correction)
+
+    # https://github.com/pytorch/pytorch/issues/29137
+    if axis == ():
+        return torch.zeros_like(x)
+    if isinstance(axis, int):
+        axis = (axis,)
+    if axis is None:
+        # torch doesn't support keepdims with axis=None
+        # (https://github.com/pytorch/pytorch/issues/71209)
+        res = torch.var(x, tuple(range(x.ndim)), correction=correction, **kwargs)
+        res = _axis_none_keepdims(res, x.ndim, keepdims)
+        return res
+    return torch.var(x, axis, correction=correction, keepdims=keepdims, **kwargs)
+
+# torch.concat doesn't support dim=None
+# https://github.com/pytorch/pytorch/issues/70925
+def concat(arrays: Union[Tuple[array, ...], List[array]],
+           /,
+           *,
+           axis: Optional[int] = 0,
+           **kwargs) -> array:
+    if axis is None:
+        arrays = tuple(ar.flatten() for ar in arrays)
+        axis = 0
+    return torch.concat(arrays, axis, **kwargs)
+
+# torch.squeeze only accepts int dim and doesn't require it
+# https://github.com/pytorch/pytorch/issues/70924. Support for tuple dim was
+# added at https://github.com/pytorch/pytorch/pull/89017.
+def squeeze(x: array, /, axis: Union[int, Tuple[int, ...]]) -> array:
+    if isinstance(axis, int):
+        axis = (axis,)
+    for a in axis:
+        if x.shape[a] != 1:
+            raise ValueError("squeezed dimensions must be equal to 1")
+    axes = _normalize_axes(axis, x.ndim)
+    # Remove this once pytorch 1.14 is released with the above PR #89017.
+    sequence = [a - i for i, a in enumerate(axes)]
+    for a in sequence:
+        x = torch.squeeze(x, a)
+    return x
+
+# torch.broadcast_to uses size instead of shape
+def broadcast_to(x: array, /, shape: Tuple[int, ...], **kwargs) -> array:
+    return torch.broadcast_to(x, shape, **kwargs)
+
+# torch.permute uses dims instead of axes
+def permute_dims(x: array, /, axes: Tuple[int, ...]) -> array:
+    return torch.permute(x, axes)
+
+# The axis parameter doesn't work for flip() and roll()
+# https://github.com/pytorch/pytorch/issues/71210. Also torch.flip() doesn't
+# accept axis=None
+def flip(x: array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, **kwargs) -> array:
+    if axis is None:
+        axis = tuple(range(x.ndim))
+    # torch.flip doesn't accept dim as an int but the method does
+    # https://github.com/pytorch/pytorch/issues/18095
+    return x.flip(axis, **kwargs)
+
+def roll(x: array, /, shift: Union[int, Tuple[int, ...]], *, axis: Optional[Union[int, Tuple[int, ...]]] = None, **kwargs) -> array:
+    return torch.roll(x, shift, axis, **kwargs)
+
+def nonzero(x: array, /, **kwargs) -> Tuple[array, ...]:
+    if x.ndim == 0:
+        raise ValueError("nonzero() does not support zero-dimensional arrays")
+    return torch.nonzero(x, as_tuple=True, **kwargs)
+
+def where(condition: array, x1: array, x2: array, /) -> array:
+    x1, x2 = _fix_promotion(x1, x2)
+    return torch.where(condition, x1, x2)
+
+# torch.reshape doesn't have the copy keyword
+def reshape(x: array,
+            /,
+            shape: Tuple[int, ...],
+            copy: Optional[bool] = None,
+            **kwargs) -> array:
+    if copy is not None:
+        raise NotImplementedError("torch.reshape doesn't yet support the copy keyword")
+    return torch.reshape(x, shape, **kwargs)
+
+# torch.arange doesn't support returning empty arrays
+# (https://github.com/pytorch/pytorch/issues/70915), and doesn't support some
+# keyword argument combinations
+# (https://github.com/pytorch/pytorch/issues/70914)
+def arange(start: Union[int, float],
+           /,
+           stop: Optional[Union[int, float]] = None,
+           step: Union[int, float] = 1,
+           *,
+           dtype: Optional[Dtype] = None,
+           device: Optional[Device] = None,
+           **kwargs) -> array:
+    if stop is None:
+        start, stop = 0, start
+    if step > 0 and stop <= start or step < 0 and stop >= start:
+        if dtype is None:
+            if _builtin_all(isinstance(i, int) for i in [start, stop, step]):
+                dtype = torch.int64
+            else:
+                dtype = torch.float32
+        return torch.empty(0, dtype=dtype, device=device, **kwargs)
+    return torch.arange(start, stop, step, dtype=dtype, device=device, **kwargs)
+
+# torch.eye does not accept None as a default for the second argument and
+# doesn't support off-diagonals (https://github.com/pytorch/pytorch/issues/70910)
+def eye(n_rows: int,
+        n_cols: Optional[int] = None,
+        /,
+        *,
+        k: int = 0,
+        dtype: Optional[Dtype] = None,
+        device: Optional[Device] = None,
+        **kwargs) -> array:
+    if n_cols is None:
+        n_cols = n_rows
+    z = torch.zeros(n_rows, n_cols, dtype=dtype, device=device, **kwargs)
+    if abs(k) <= n_rows + n_cols:
+        z.diagonal(k).fill_(1)
+    return z
+
+# torch.linspace doesn't have the endpoint parameter
+def linspace(start: Union[int, float],
+             stop: Union[int, float],
+             /,
+             num: int,
+             *,
+             dtype: Optional[Dtype] = None,
+             device: Optional[Device] = None,
+             endpoint: bool = True,
+             **kwargs) -> array:
+    if not endpoint:
+        return torch.linspace(start, stop, num+1, dtype=dtype, device=device, **kwargs)[:-1]
+    return torch.linspace(start, stop, num, dtype=dtype, device=device, **kwargs)
+
+# torch.full does not accept an int size
+# https://github.com/pytorch/pytorch/issues/70906
+def full(shape: Union[int, Tuple[int, ...]],
+         fill_value: Union[bool, int, float, complex],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    if isinstance(shape, int):
+        shape = (shape,)
+
+    return torch.full(shape, fill_value, dtype=dtype, device=device, **kwargs)
+
+# ones, zeros, and empty do not accept shape as a keyword argument
+def ones(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    return torch.ones(shape, dtype=dtype, device=device, **kwargs)
+
+def zeros(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    return torch.zeros(shape, dtype=dtype, device=device, **kwargs)
+
+def empty(shape: Union[int, Tuple[int, ...]],
+         *,
+         dtype: Optional[Dtype] = None,
+         device: Optional[Device] = None,
+         **kwargs) -> array:
+    return torch.empty(shape, dtype=dtype, device=device, **kwargs)
+
+# tril and triu do not call the keyword argument k
+
+def tril(x: array, /, *, k: int = 0) -> array:
+    return torch.tril(x, k)
+
+def triu(x: array, /, *, k: int = 0) -> array:
+    return torch.triu(x, k)
+
+# Functions that aren't in torch https://github.com/pytorch/pytorch/issues/58742
+def expand_dims(x: array, /, *, axis: int = 0) -> array:
+    return torch.unsqueeze(x, axis)
+
+def astype(x: array, dtype: Dtype, /, *, copy: bool = True) -> array:
+    return x.to(dtype, copy=copy)
+
+def broadcast_arrays(*arrays: array) -> List[array]:
+    shape = torch.broadcast_shapes(*[a.shape for a in arrays])
+    return [torch.broadcast_to(a, shape) for a in arrays]
+
+# Note that these named tuples aren't actually part of the standard namespace,
+# but I don't see any issue with exporting the names here regardless.
+from ..common._aliases import (UniqueAllResult, UniqueCountsResult,
+                               UniqueInverseResult)
+
+# https://github.com/pytorch/pytorch/issues/70920
+def unique_all(x: array) -> UniqueAllResult:
+    # torch.unique doesn't support returning indices.
+    # https://github.com/pytorch/pytorch/issues/36748. The workaround
+    # suggested in that issue doesn't actually function correctly (it relies
+    # on non-deterministic behavior of scatter()).
+    raise NotImplementedError("unique_all() not yet implemented for pytorch (see https://github.com/pytorch/pytorch/issues/36748)")
+
+    # values, inverse_indices, counts = torch.unique(x, return_counts=True, return_inverse=True)
+    # # torch.unique incorrectly gives a 0 count for nan values.
+    # # https://github.com/pytorch/pytorch/issues/94106
+    # counts[torch.isnan(values)] = 1
+    # return UniqueAllResult(values, indices, inverse_indices, counts)
+
+def unique_counts(x: array) -> UniqueCountsResult:
+    values, counts = torch.unique(x, return_counts=True)
+
+    # torch.unique incorrectly gives a 0 count for nan values.
+    # https://github.com/pytorch/pytorch/issues/94106
+    counts[torch.isnan(values)] = 1
+    return UniqueCountsResult(values, counts)
+
+def unique_inverse(x: array) -> UniqueInverseResult:
+    values, inverse = torch.unique(x, return_inverse=True)
+    return UniqueInverseResult(values, inverse)
+
+def unique_values(x: array) -> array:
+    return torch.unique(x)
+
+def matmul(x1: array, x2: array, /, **kwargs) -> array:
+    # torch.matmul doesn't type promote (but differently from _fix_promotion)
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return torch.matmul(x1, x2, **kwargs)
+
+matrix_transpose = get_xp(torch)(_aliases_matrix_transpose)
+_vecdot = get_xp(torch)(_aliases_vecdot)
+
+def vecdot(x1: array, x2: array, /, *, axis: int = -1) -> array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return _vecdot(x1, x2, axis=axis)
+
+# torch.tensordot uses dims instead of axes
+def tensordot(x1: array, x2: array, /, *, axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2, **kwargs) -> array:
+    # Note: torch.tensordot fails with integer dtypes when there is only 1
+    # element in the axis (https://github.com/pytorch/pytorch/issues/84530).
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    return torch.tensordot(x1, x2, dims=axes, **kwargs)
+
+
+def isdtype(
+    dtype: Dtype, kind: Union[Dtype, str, Tuple[Union[Dtype, str], ...]],
+    *, _tuple=True, # Disallow nested tuples
+) -> bool:
+    """
+    Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``.
+
+    Note that outside of this function, this compat library does not yet fully
+    support complex numbers.
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html
+    for more details
+    """
+    if isinstance(kind, tuple) and _tuple:
+        return _builtin_any(isdtype(dtype, k, _tuple=False) for k in kind)
+    elif isinstance(kind, str):
+        if kind == 'bool':
+            return dtype == torch.bool
+        elif kind == 'signed integer':
+            return dtype in _int_dtypes and dtype.is_signed
+        elif kind == 'unsigned integer':
+            return dtype in _int_dtypes and not dtype.is_signed
+        elif kind == 'integral':
+            return dtype in _int_dtypes
+        elif kind == 'real floating':
+            return dtype.is_floating_point
+        elif kind == 'complex floating':
+            return dtype.is_complex
+        elif kind == 'numeric':
+            return isdtype(dtype, ('integral', 'real floating', 'complex floating'))
+        else:
+            raise ValueError(f"Unrecognized data type kind: {kind!r}")
+    else:
+        return dtype == kind
+
+def take(x: array, indices: array, /, *, axis: Optional[int] = None, **kwargs) -> array:
+    if axis is None:
+        if x.ndim != 1:
+            raise ValueError("axis must be specified when ndim > 1")
+        axis = 0
+    return torch.index_select(x, axis, indices, **kwargs)
+
+def sign(x: array, /) -> array:
+    # torch sign() does not support complex numbers and does not propagate
+    # nans. See https://github.com/data-apis/array-api-compat/issues/136
+    if x.dtype.is_complex:
+        out = x/torch.abs(x)
+        # sign(0) = 0 but the above formula would give nan
+        out[x == 0+0j] = 0+0j
+        return out
+    else:
+        out = torch.sign(x)
+        if x.dtype.is_floating_point:
+            out[torch.isnan(x)] = torch.nan
+        return out
+
+
+__all__ = ['__array_namespace_info__', 'result_type', 'can_cast',
+           'permute_dims', 'bitwise_invert', 'newaxis', 'conj', 'add',
+           'atan2', 'bitwise_and', 'bitwise_left_shift', 'bitwise_or',
+           'bitwise_right_shift', 'bitwise_xor', 'copysign', 'divide',
+           'equal', 'floor_divide', 'greater', 'greater_equal', 'hypot',
+           'less', 'less_equal', 'logaddexp', 'maximum', 'minimum',
+           'multiply', 'not_equal', 'pow', 'remainder', 'subtract', 'max',
+           'min', 'clip', 'unstack', 'cumulative_sum', 'sort', 'prod', 'sum',
+           'any', 'all', 'mean', 'std', 'var', 'concat', 'squeeze',
+           'broadcast_to', 'flip', 'roll', 'nonzero', 'where', 'reshape',
+           'arange', 'eye', 'linspace', 'full', 'ones', 'zeros', 'empty',
+           'tril', 'triu', 'expand_dims', 'astype', 'broadcast_arrays',
+           'UniqueAllResult', 'UniqueCountsResult', 'UniqueInverseResult',
+           'unique_all', 'unique_counts', 'unique_inverse', 'unique_values',
+           'matmul', 'matrix_transpose', 'vecdot', 'tensordot', 'isdtype',
+           'take', 'sign']
+
+_all_ignore = ['torch', 'get_xp']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_info.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_info.py
new file mode 100644
index 0000000000000000000000000000000000000000..264caa9e5fbbe9da3d9b9594b8d11f313d8536ef
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/_info.py
@@ -0,0 +1,358 @@
+"""
+Array API Inspection namespace
+
+This is the namespace for inspection functions as defined by the array API
+standard. See
+https://data-apis.org/array-api/latest/API_specification/inspection.html for
+more details.
+
+"""
+import torch
+
+from functools import cache
+
+class __array_namespace_info__:
+    """
+    Get the array API inspection namespace for PyTorch.
+
+    The array API inspection namespace defines the following functions:
+
+    - capabilities()
+    - default_device()
+    - default_dtypes()
+    - dtypes()
+    - devices()
+
+    See
+    https://data-apis.org/array-api/latest/API_specification/inspection.html
+    for more details.
+
+    Returns
+    -------
+    info : ModuleType
+        The array API inspection namespace for PyTorch.
+
+    Examples
+    --------
+    >>> info = np.__array_namespace_info__()
+    >>> info.default_dtypes()
+    {'real floating': numpy.float64,
+     'complex floating': numpy.complex128,
+     'integral': numpy.int64,
+     'indexing': numpy.int64}
+
+    """
+
+    __module__ = 'torch'
+
+    def capabilities(self):
+        """
+        Return a dictionary of array API library capabilities.
+
+        The resulting dictionary has the following keys:
+
+        - **"boolean indexing"**: boolean indicating whether an array library
+          supports boolean indexing. Always ``True`` for PyTorch.
+
+        - **"data-dependent shapes"**: boolean indicating whether an array
+          library supports data-dependent output shapes. Always ``True`` for
+          PyTorch.
+
+        See
+        https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
+        for more details.
+
+        See Also
+        --------
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        capabilities : dict
+            A dictionary of array API library capabilities.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.capabilities()
+        {'boolean indexing': True,
+         'data-dependent shapes': True}
+
+        """
+        return {
+            "boolean indexing": True,
+            "data-dependent shapes": True,
+            # 'max rank' will be part of the 2024.12 standard
+            # "max rank": 64,
+        }
+
+    def default_device(self):
+        """
+        The default device used for new PyTorch arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Returns
+        -------
+        device : str
+            The default device used for new PyTorch arrays.
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_device()
+        'cpu'
+
+        """
+        return torch.device("cpu")
+
+    def default_dtypes(self, *, device=None):
+        """
+        The default data types used for new PyTorch arrays.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the default data types for. For PyTorch, only
+            ``'cpu'`` is allowed.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary describing the default data types used for new PyTorch
+            arrays.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.default_dtypes()
+        {'real floating': torch.float32,
+         'complex floating': torch.complex64,
+         'integral': torch.int64,
+         'indexing': torch.int64}
+
+        """
+        # Note: if the default is set to float64, the devices like MPS that
+        # don't support float64 will error. We still return the default_dtype
+        # value here because this error doesn't represent a different default
+        # per-device.
+        default_floating = torch.get_default_dtype()
+        default_complex = torch.complex64 if default_floating == torch.float32 else torch.complex128
+        default_integral = torch.int64
+        return {
+            "real floating": default_floating,
+            "complex floating": default_complex,
+            "integral": default_integral,
+            "indexing": default_integral,
+        }
+
+
+    def _dtypes(self, kind):
+        bool = torch.bool
+        int8 = torch.int8
+        int16 = torch.int16
+        int32 = torch.int32
+        int64 = torch.int64
+        uint8 = torch.uint8
+        # uint16, uint32, and uint64 are present in newer versions of pytorch,
+        # but they aren't generally supported by the array API functions, so
+        # we omit them from this function.
+        float32 = torch.float32
+        float64 = torch.float64
+        complex64 = torch.complex64
+        complex128 = torch.complex128
+
+        if kind is None:
+            return {
+                "bool": bool,
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+                "float32": float32,
+                "float64": float64,
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if kind == "bool":
+            return {"bool": bool}
+        if kind == "signed integer":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+            }
+        if kind == "unsigned integer":
+            return {
+                "uint8": uint8,
+            }
+        if kind == "integral":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+            }
+        if kind == "real floating":
+            return {
+                "float32": float32,
+                "float64": float64,
+            }
+        if kind == "complex floating":
+            return {
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if kind == "numeric":
+            return {
+                "int8": int8,
+                "int16": int16,
+                "int32": int32,
+                "int64": int64,
+                "uint8": uint8,
+                "float32": float32,
+                "float64": float64,
+                "complex64": complex64,
+                "complex128": complex128,
+            }
+        if isinstance(kind, tuple):
+            res = {}
+            for k in kind:
+                res.update(self.dtypes(kind=k))
+            return res
+        raise ValueError(f"unsupported kind: {kind!r}")
+
+    @cache
+    def dtypes(self, *, device=None, kind=None):
+        """
+        The array API data types supported by PyTorch.
+
+        Note that this function only returns data types that are defined by
+        the array API.
+
+        Parameters
+        ----------
+        device : str, optional
+            The device to get the data types for.
+        kind : str or tuple of str, optional
+            The kind of data types to return. If ``None``, all data types are
+            returned. If a string, only data types of that kind are returned.
+            If a tuple, a dictionary containing the union of the given kinds
+            is returned. The following kinds are supported:
+
+            - ``'bool'``: boolean data types (i.e., ``bool``).
+            - ``'signed integer'``: signed integer data types (i.e., ``int8``,
+              ``int16``, ``int32``, ``int64``).
+            - ``'unsigned integer'``: unsigned integer data types (i.e.,
+              ``uint8``, ``uint16``, ``uint32``, ``uint64``).
+            - ``'integral'``: integer data types. Shorthand for ``('signed
+              integer', 'unsigned integer')``.
+            - ``'real floating'``: real-valued floating-point data types
+              (i.e., ``float32``, ``float64``).
+            - ``'complex floating'``: complex floating-point data types (i.e.,
+              ``complex64``, ``complex128``).
+            - ``'numeric'``: numeric data types. Shorthand for ``('integral',
+              'real floating', 'complex floating')``.
+
+        Returns
+        -------
+        dtypes : dict
+            A dictionary mapping the names of data types to the corresponding
+            PyTorch data types.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.devices
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.dtypes(kind='signed integer')
+        {'int8': numpy.int8,
+         'int16': numpy.int16,
+         'int32': numpy.int32,
+         'int64': numpy.int64}
+
+        """
+        res = self._dtypes(kind)
+        for k, v in res.copy().items():
+            try:
+                torch.empty((0,), dtype=v, device=device)
+            except:
+                del res[k]
+        return res
+
+    @cache
+    def devices(self):
+        """
+        The devices supported by PyTorch.
+
+        Returns
+        -------
+        devices : list of str
+            The devices supported by PyTorch.
+
+        See Also
+        --------
+        __array_namespace_info__.capabilities,
+        __array_namespace_info__.default_device,
+        __array_namespace_info__.default_dtypes,
+        __array_namespace_info__.dtypes
+
+        Examples
+        --------
+        >>> info = np.__array_namespace_info__()
+        >>> info.devices()
+        [device(type='cpu'), device(type='mps', index=0), device(type='meta')]
+
+        """
+        # Torch doesn't have a straightforward way to get the list of all
+        # currently supported devices. To do this, we first parse the error
+        # message of torch.device to get the list of all possible types of
+        # device:
+        try:
+            torch.device('notadevice')
+        except RuntimeError as e:
+            # The error message is something like:
+            # "Expected one of cpu, cuda, ipu, xpu, mkldnn, opengl, opencl, ideep, hip, ve, fpga, ort, xla, lazy, vulkan, mps, meta, hpu, mtia, privateuseone device type at start of device string: notadevice"
+            devices_names = e.args[0].split('Expected one of ')[1].split(' device type')[0].split(', ')
+
+        # Next we need to check for different indices for different devices.
+        # device(device_name, index=index) doesn't actually check if the
+        # device name or index is valid. We have to try to create a tensor
+        # with it (which is why this function is cached).
+        devices = []
+        for device_name in devices_names:
+            i = 0
+            while True:
+                try:
+                    a = torch.empty((0,), device=torch.device(device_name, index=i))
+                    if a.device in devices:
+                        break
+                    devices.append(a.device)
+                except:
+                    break
+                i += 1
+
+        return devices
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/fft.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c9117ee57d3534e3e72329d740632c02e936200
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/fft.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    import torch
+    array = torch.Tensor
+    from typing import Union, Sequence, Literal
+
+from torch.fft import * # noqa: F403
+import torch.fft
+
+# Several torch fft functions do not map axes to dim
+
+def fftn(
+    x: array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> array:
+    return torch.fft.fftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def ifftn(
+    x: array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> array:
+    return torch.fft.ifftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def rfftn(
+    x: array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> array:
+    return torch.fft.rfftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def irfftn(
+    x: array,
+    /,
+    *,
+    s: Sequence[int] = None,
+    axes: Sequence[int] = None,
+    norm: Literal["backward", "ortho", "forward"] = "backward",
+    **kwargs,
+) -> array:
+    return torch.fft.irfftn(x, s=s, dim=axes, norm=norm, **kwargs)
+
+def fftshift(
+    x: array,
+    /,
+    *,
+    axes: Union[int, Sequence[int]] = None,
+    **kwargs,
+) -> array:
+    return torch.fft.fftshift(x, dim=axes, **kwargs)
+
+def ifftshift(
+    x: array,
+    /,
+    *,
+    axes: Union[int, Sequence[int]] = None,
+    **kwargs,
+) -> array:
+    return torch.fft.ifftshift(x, dim=axes, **kwargs)
+
+
+__all__ = torch.fft.__all__ + [
+    "fftn",
+    "ifftn",
+    "rfftn",
+    "irfftn",
+    "fftshift",
+    "ifftshift",
+]
+
+_all_ignore = ['torch']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/linalg.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/linalg.py
new file mode 100644
index 0000000000000000000000000000000000000000..e26198b9b562ed307206dd08dd9de7c8aa2a918b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_compat/torch/linalg.py
@@ -0,0 +1,121 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+if TYPE_CHECKING:
+    import torch
+    array = torch.Tensor
+    from torch import dtype as Dtype
+    from typing import Optional, Union, Tuple, Literal
+    inf = float('inf')
+
+from ._aliases import _fix_promotion, sum
+
+from torch.linalg import * # noqa: F403
+
+# torch.linalg doesn't define __all__
+# from torch.linalg import __all__ as linalg_all
+from torch import linalg as torch_linalg
+linalg_all = [i for i in dir(torch_linalg) if not i.startswith('_')]
+
+# outer is implemented in torch but aren't in the linalg namespace
+from torch import outer
+# These functions are in both the main and linalg namespaces
+from ._aliases import matmul, matrix_transpose, tensordot
+
+# Note: torch.linalg.cross does not default to axis=-1 (it defaults to the
+# first axis with size 3), see https://github.com/pytorch/pytorch/issues/58743
+
+# torch.cross also does not support broadcasting when it would add new
+# dimensions https://github.com/pytorch/pytorch/issues/39656
+def cross(x1: array, x2: array, /, *, axis: int = -1) -> array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    if not (-min(x1.ndim, x2.ndim) <= axis < max(x1.ndim, x2.ndim)):
+        raise ValueError(f"axis {axis} out of bounds for cross product of arrays with shapes {x1.shape} and {x2.shape}")
+    if not (x1.shape[axis] == x2.shape[axis] == 3):
+        raise ValueError(f"cross product axis must have size 3, got {x1.shape[axis]} and {x2.shape[axis]}")
+    x1, x2 = torch.broadcast_tensors(x1, x2)
+    return torch_linalg.cross(x1, x2, dim=axis)
+
+def vecdot(x1: array, x2: array, /, *, axis: int = -1, **kwargs) -> array:
+    from ._aliases import isdtype
+
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+
+    # torch.linalg.vecdot incorrectly allows broadcasting along the contracted dimension
+    if x1.shape[axis] != x2.shape[axis]:
+        raise ValueError("x1 and x2 must have the same size along the given axis")
+
+    # torch.linalg.vecdot doesn't support integer dtypes
+    if isdtype(x1.dtype, 'integral') or isdtype(x2.dtype, 'integral'):
+        if kwargs:
+            raise RuntimeError("vecdot kwargs not supported for integral dtypes")
+
+        x1_ = torch.moveaxis(x1, axis, -1)
+        x2_ = torch.moveaxis(x2, axis, -1)
+        x1_, x2_ = torch.broadcast_tensors(x1_, x2_)
+
+        res = x1_[..., None, :] @ x2_[..., None]
+        return res[..., 0, 0]
+    return torch.linalg.vecdot(x1, x2, dim=axis, **kwargs)
+
+def solve(x1: array, x2: array, /, **kwargs) -> array:
+    x1, x2 = _fix_promotion(x1, x2, only_scalar=False)
+    # Torch tries to emulate NumPy 1 solve behavior by using batched 1-D solve
+    # whenever
+    # 1. x1.ndim - 1 == x2.ndim
+    # 2. x1.shape[:-1] == x2.shape
+    #
+    # See linalg_solve_is_vector_rhs in
+    # aten/src/ATen/native/LinearAlgebraUtils.h and
+    # TORCH_META_FUNC(_linalg_solve_ex) in
+    # aten/src/ATen/native/BatchLinearAlgebra.cpp in the PyTorch source code.
+    #
+    # The easiest way to work around this is to prepend a size 1 dimension to
+    # x2, since x2 is already one dimension less than x1.
+    #
+    # See https://github.com/pytorch/pytorch/issues/52915
+    if x2.ndim != 1 and x1.ndim - 1 == x2.ndim and x1.shape[:-1] == x2.shape:
+        x2 = x2[None]
+    return torch.linalg.solve(x1, x2, **kwargs)
+
+# torch.trace doesn't support the offset argument and doesn't support stacking
+def trace(x: array, /, *, offset: int = 0, dtype: Optional[Dtype] = None) -> array:
+    # Use our wrapped sum to make sure it does upcasting correctly
+    return sum(torch.diagonal(x, offset=offset, dim1=-2, dim2=-1), axis=-1, dtype=dtype)
+
+def vector_norm(
+    x: array,
+    /,
+    *,
+    axis: Optional[Union[int, Tuple[int, ...]]] = None,
+    keepdims: bool = False,
+    ord: Union[int, float, Literal[inf, -inf]] = 2,
+    **kwargs,
+) -> array:
+    # torch.vector_norm incorrectly treats axis=() the same as axis=None
+    if axis == ():
+        out = kwargs.get('out')
+        if out is None:
+            dtype = None
+            if x.dtype == torch.complex64:
+                dtype = torch.float32
+            elif x.dtype == torch.complex128:
+                dtype = torch.float64
+
+            out = torch.zeros_like(x, dtype=dtype)
+
+        # The norm of a single scalar works out to abs(x) in every case except
+        # for ord=0, which is x != 0.
+        if ord == 0:
+            out[:] = (x != 0)
+        else:
+            out[:] = torch.abs(x)
+        return out
+    return torch.linalg.vector_norm(x, ord=ord, axis=axis, keepdim=keepdims, **kwargs)
+
+__all__ = linalg_all + ['outer', 'matmul', 'matrix_transpose', 'tensordot',
+                        'cross', 'vecdot', 'solve', 'trace', 'vector_norm']
+
+_all_ignore = ['torch_linalg', 'sum']
+
+del linalg_all
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2062f7d5d6a4d9f5a3556164720a6abc4da456bc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__init__.py
@@ -0,0 +1,15 @@
+from __future__ import annotations
+
+from ._funcs import atleast_nd, cov, create_diagonal, expand_dims, kron, sinc
+
+__version__ = "0.2.0"
+
+__all__ = [
+    "__version__",
+    "atleast_nd",
+    "cov",
+    "create_diagonal",
+    "expand_dims",
+    "kron",
+    "sinc",
+]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1335217d0d26c5f66a06a890fd3ab6096d3ff64
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_funcs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_funcs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..123ce7e3f96ea6c075f2da5d1d993fbac674a810
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/__pycache__/_funcs.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_funcs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_funcs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce800189b46d25316c3123a22ce4ff2e7e1e81ce
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_funcs.py
@@ -0,0 +1,484 @@
+from __future__ import annotations
+
+import warnings
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from ._typing import Array, ModuleType
+
+__all__ = ["atleast_nd", "cov", "create_diagonal", "expand_dims", "kron", "sinc"]
+
+
+def atleast_nd(x: Array, /, *, ndim: int, xp: ModuleType) -> Array:
+    """
+    Recursively expand the dimension of an array to at least `ndim`.
+
+    Parameters
+    ----------
+    x : array
+    ndim : int
+        The minimum number of dimensions for the result.
+    xp : array_namespace
+        The standard-compatible namespace for `x`.
+
+    Returns
+    -------
+    res : array
+        An array with ``res.ndim`` >= `ndim`.
+        If ``x.ndim`` >= `ndim`, `x` is returned.
+        If ``x.ndim`` < `ndim`, `x` is expanded by prepending new axes
+        until ``res.ndim`` equals `ndim`.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.asarray([1])
+    >>> xpx.atleast_nd(x, ndim=3, xp=xp)
+    Array([[[1]]], dtype=array_api_strict.int64)
+
+    >>> x = xp.asarray([[[1, 2],
+    ...                  [3, 4]]])
+    >>> xpx.atleast_nd(x, ndim=1, xp=xp) is x
+    True
+
+    """
+    if x.ndim < ndim:
+        x = xp.expand_dims(x, axis=0)
+        x = atleast_nd(x, ndim=ndim, xp=xp)
+    return x
+
+
+def cov(m: Array, /, *, xp: ModuleType) -> Array:
+    """
+    Estimate a covariance matrix.
+
+    Covariance indicates the level to which two variables vary together.
+    If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
+    then the covariance matrix element :math:`C_{ij}` is the covariance of
+    :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
+    of :math:`x_i`.
+
+    This provides a subset of the functionality of ``numpy.cov``.
+
+    Parameters
+    ----------
+    m : array
+        A 1-D or 2-D array containing multiple variables and observations.
+        Each row of `m` represents a variable, and each column a single
+        observation of all those variables.
+    xp : array_namespace
+        The standard-compatible namespace for `m`.
+
+    Returns
+    -------
+    res : array
+        The covariance matrix of the variables.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+
+    Consider two variables, :math:`x_0` and :math:`x_1`, which
+    correlate perfectly, but in opposite directions:
+
+    >>> x = xp.asarray([[0, 2], [1, 1], [2, 0]]).T
+    >>> x
+    Array([[0, 1, 2],
+           [2, 1, 0]], dtype=array_api_strict.int64)
+
+    Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
+    matrix shows this clearly:
+
+    >>> xpx.cov(x, xp=xp)
+    Array([[ 1., -1.],
+           [-1.,  1.]], dtype=array_api_strict.float64)
+
+
+    Note that element :math:`C_{0,1}`, which shows the correlation between
+    :math:`x_0` and :math:`x_1`, is negative.
+
+    Further, note how `x` and `y` are combined:
+
+    >>> x = xp.asarray([-2.1, -1,  4.3])
+    >>> y = xp.asarray([3,  1.1,  0.12])
+    >>> X = xp.stack((x, y), axis=0)
+    >>> xpx.cov(X, xp=xp)
+    Array([[11.71      , -4.286     ],
+           [-4.286     ,  2.14413333]], dtype=array_api_strict.float64)
+
+    >>> xpx.cov(x, xp=xp)
+    Array(11.71, dtype=array_api_strict.float64)
+
+    >>> xpx.cov(y, xp=xp)
+    Array(2.14413333, dtype=array_api_strict.float64)
+
+    """
+    m = xp.asarray(m, copy=True)
+    dtype = (
+        xp.float64 if xp.isdtype(m.dtype, "integral") else xp.result_type(m, xp.float64)
+    )
+
+    m = atleast_nd(m, ndim=2, xp=xp)
+    m = xp.astype(m, dtype)
+
+    avg = _mean(m, axis=1, xp=xp)
+    fact = m.shape[1] - 1
+
+    if fact <= 0:
+        warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning, stacklevel=2)
+        fact = 0.0
+
+    m -= avg[:, None]
+    m_transpose = m.T
+    if xp.isdtype(m_transpose.dtype, "complex floating"):
+        m_transpose = xp.conj(m_transpose)
+    c = m @ m_transpose
+    c /= fact
+    axes = tuple(axis for axis, length in enumerate(c.shape) if length == 1)
+    return xp.squeeze(c, axis=axes)
+
+
+def create_diagonal(x: Array, /, *, offset: int = 0, xp: ModuleType) -> Array:
+    """
+    Construct a diagonal array.
+
+    Parameters
+    ----------
+    x : array
+        A 1-D array
+    offset : int, optional
+        Offset from the leading diagonal (default is ``0``).
+        Use positive ints for diagonals above the leading diagonal,
+        and negative ints for diagonals below the leading diagonal.
+    xp : array_namespace
+        The standard-compatible namespace for `x`.
+
+    Returns
+    -------
+    res : array
+        A 2-D array with `x` on the diagonal (offset by `offset`).
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.asarray([2, 4, 8])
+
+    >>> xpx.create_diagonal(x, xp=xp)
+    Array([[2, 0, 0],
+           [0, 4, 0],
+           [0, 0, 8]], dtype=array_api_strict.int64)
+
+    >>> xpx.create_diagonal(x, offset=-2, xp=xp)
+    Array([[0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0],
+           [2, 0, 0, 0, 0],
+           [0, 4, 0, 0, 0],
+           [0, 0, 8, 0, 0]], dtype=array_api_strict.int64)
+
+    """
+    if x.ndim != 1:
+        err_msg = "`x` must be 1-dimensional."
+        raise ValueError(err_msg)
+    n = x.shape[0] + abs(offset)
+    diag = xp.zeros(n**2, dtype=x.dtype)
+    i = offset if offset >= 0 else abs(offset) * n
+    diag[i : min(n * (n - offset), diag.shape[0]) : n + 1] = x
+    return xp.reshape(diag, (n, n))
+
+
+def _mean(
+    x: Array,
+    /,
+    *,
+    axis: int | tuple[int, ...] | None = None,
+    keepdims: bool = False,
+    xp: ModuleType,
+) -> Array:
+    """
+    Complex mean, https://github.com/data-apis/array-api/issues/846.
+    """
+    if xp.isdtype(x.dtype, "complex floating"):
+        x_real = xp.real(x)
+        x_imag = xp.imag(x)
+        mean_real = xp.mean(x_real, axis=axis, keepdims=keepdims)
+        mean_imag = xp.mean(x_imag, axis=axis, keepdims=keepdims)
+        return mean_real + (mean_imag * xp.asarray(1j))
+    return xp.mean(x, axis=axis, keepdims=keepdims)
+
+
+def expand_dims(
+    a: Array, /, *, axis: int | tuple[int, ...] = (0,), xp: ModuleType
+) -> Array:
+    """
+    Expand the shape of an array.
+
+    Insert (a) new axis/axes that will appear at the position(s) specified by
+    `axis` in the expanded array shape.
+
+    This is ``xp.expand_dims`` for `axis` an int *or a tuple of ints*.
+    Roughly equivalent to ``numpy.expand_dims`` for NumPy arrays.
+
+    Parameters
+    ----------
+    a : array
+    axis : int or tuple of ints, optional
+        Position(s) in the expanded axes where the new axis (or axes) is/are placed.
+        If multiple positions are provided, they should be unique (note that a position
+        given by a positive index could also be referred to by a negative index -
+        that will also result in an error).
+        Default: ``(0,)``.
+    xp : array_namespace
+        The standard-compatible namespace for `a`.
+
+    Returns
+    -------
+    res : array
+        `a` with an expanded shape.
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.asarray([1, 2])
+    >>> x.shape
+    (2,)
+
+    The following is equivalent to ``x[xp.newaxis, :]`` or ``x[xp.newaxis]``:
+
+    >>> y = xpx.expand_dims(x, axis=0, xp=xp)
+    >>> y
+    Array([[1, 2]], dtype=array_api_strict.int64)
+    >>> y.shape
+    (1, 2)
+
+    The following is equivalent to ``x[:, xp.newaxis]``:
+
+    >>> y = xpx.expand_dims(x, axis=1, xp=xp)
+    >>> y
+    Array([[1],
+           [2]], dtype=array_api_strict.int64)
+    >>> y.shape
+    (2, 1)
+
+    ``axis`` may also be a tuple:
+
+    >>> y = xpx.expand_dims(x, axis=(0, 1), xp=xp)
+    >>> y
+    Array([[[1, 2]]], dtype=array_api_strict.int64)
+
+    >>> y = xpx.expand_dims(x, axis=(2, 0), xp=xp)
+    >>> y
+    Array([[[1],
+            [2]]], dtype=array_api_strict.int64)
+
+    """
+    if not isinstance(axis, tuple):
+        axis = (axis,)
+    ndim = a.ndim + len(axis)
+    if axis != () and (min(axis) < -ndim or max(axis) >= ndim):
+        err_msg = (
+            f"a provided axis position is out of bounds for array of dimension {a.ndim}"
+        )
+        raise IndexError(err_msg)
+    axis = tuple(dim % ndim for dim in axis)
+    if len(set(axis)) != len(axis):
+        err_msg = "Duplicate dimensions specified in `axis`."
+        raise ValueError(err_msg)
+    for i in sorted(axis):
+        a = xp.expand_dims(a, axis=i)
+    return a
+
+
+def kron(a: Array, b: Array, /, *, xp: ModuleType) -> Array:
+    """
+    Kronecker product of two arrays.
+
+    Computes the Kronecker product, a composite array made of blocks of the
+    second array scaled by the first.
+
+    Equivalent to ``numpy.kron`` for NumPy arrays.
+
+    Parameters
+    ----------
+    a, b : array
+    xp : array_namespace
+        The standard-compatible namespace for `a` and `b`.
+
+    Returns
+    -------
+    res : array
+        The Kronecker product of `a` and `b`.
+
+    Notes
+    -----
+    The function assumes that the number of dimensions of `a` and `b`
+    are the same, if necessary prepending the smallest with ones.
+    If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``,
+    the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``.
+    The elements are products of elements from `a` and `b`, organized
+    explicitly by::
+
+        kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
+
+    where::
+
+        kt = it * st + jt,  t = 0,...,N
+
+    In the common 2-D case (N=1), the block structure can be visualized::
+
+        [[ a[0,0]*b,   a[0,1]*b,  ... , a[0,-1]*b  ],
+         [  ...                              ...   ],
+         [ a[-1,0]*b,  a[-1,1]*b, ... , a[-1,-1]*b ]]
+
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> xpx.kron(xp.asarray([1, 10, 100]), xp.asarray([5, 6, 7]), xp=xp)
+    Array([  5,   6,   7,  50,  60,  70, 500,
+           600, 700], dtype=array_api_strict.int64)
+
+    >>> xpx.kron(xp.asarray([5, 6, 7]), xp.asarray([1, 10, 100]), xp=xp)
+    Array([  5,  50, 500,   6,  60, 600,   7,
+            70, 700], dtype=array_api_strict.int64)
+
+    >>> xpx.kron(xp.eye(2), xp.ones((2, 2)), xp=xp)
+    Array([[1., 1., 0., 0.],
+           [1., 1., 0., 0.],
+           [0., 0., 1., 1.],
+           [0., 0., 1., 1.]], dtype=array_api_strict.float64)
+
+
+    >>> a = xp.reshape(xp.arange(100), (2, 5, 2, 5))
+    >>> b = xp.reshape(xp.arange(24), (2, 3, 4))
+    >>> c = xpx.kron(a, b, xp=xp)
+    >>> c.shape
+    (2, 10, 6, 20)
+    >>> I = (1, 3, 0, 2)
+    >>> J = (0, 2, 1)
+    >>> J1 = (0,) + J             # extend to ndim=4
+    >>> S1 = (1,) + b.shape
+    >>> K = tuple(xp.asarray(I) * xp.asarray(S1) + xp.asarray(J1))
+    >>> c[K] == a[I]*b[J]
+    Array(True, dtype=array_api_strict.bool)
+
+    """
+
+    b = xp.asarray(b)
+    singletons = (1,) * (b.ndim - a.ndim)
+    a = xp.broadcast_to(xp.asarray(a), singletons + a.shape)
+
+    nd_b, nd_a = b.ndim, a.ndim
+    nd_max = max(nd_b, nd_a)
+    if nd_a == 0 or nd_b == 0:
+        return xp.multiply(a, b)
+
+    a_shape = a.shape
+    b_shape = b.shape
+
+    # Equalise the shapes by prepending smaller one with 1s
+    a_shape = (1,) * max(0, nd_b - nd_a) + a_shape
+    b_shape = (1,) * max(0, nd_a - nd_b) + b_shape
+
+    # Insert empty dimensions
+    a_arr = expand_dims(a, axis=tuple(range(nd_b - nd_a)), xp=xp)
+    b_arr = expand_dims(b, axis=tuple(range(nd_a - nd_b)), xp=xp)
+
+    # Compute the product
+    a_arr = expand_dims(a_arr, axis=tuple(range(1, nd_max * 2, 2)), xp=xp)
+    b_arr = expand_dims(b_arr, axis=tuple(range(0, nd_max * 2, 2)), xp=xp)
+    result = xp.multiply(a_arr, b_arr)
+
+    # Reshape back and return
+    a_shape = xp.asarray(a_shape)
+    b_shape = xp.asarray(b_shape)
+    return xp.reshape(result, tuple(xp.multiply(a_shape, b_shape)))
+
+
+def sinc(x: Array, /, *, xp: ModuleType) -> Array:
+    r"""
+    Return the normalized sinc function.
+
+    The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument
+    :math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not
+    only everywhere continuous but also infinitely differentiable.
+
+    .. note::
+
+        Note the normalization factor of ``pi`` used in the definition.
+        This is the most commonly used definition in signal processing.
+        Use ``sinc(x / xp.pi)`` to obtain the unnormalized sinc function
+        :math:`\sin(x)/x` that is more common in mathematics.
+
+    Parameters
+    ----------
+    x : array
+        Array (possibly multi-dimensional) of values for which to calculate
+        ``sinc(x)``. Must have a real floating point dtype.
+    xp : array_namespace
+        The standard-compatible namespace for `x`.
+
+    Returns
+    -------
+    res : array
+        ``sinc(x)`` calculated elementwise, which has the same shape as the input.
+
+    Notes
+    -----
+    The name sinc is short for "sine cardinal" or "sinus cardinalis".
+
+    The sinc function is used in various signal processing applications,
+    including in anti-aliasing, in the construction of a Lanczos resampling
+    filter, and in interpolation.
+
+    For bandlimited interpolation of discrete-time signals, the ideal
+    interpolation kernel is proportional to the sinc function.
+
+    References
+    ----------
+    .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
+           Resource. https://mathworld.wolfram.com/SincFunction.html
+    .. [2] Wikipedia, "Sinc function",
+           https://en.wikipedia.org/wiki/Sinc_function
+
+    Examples
+    --------
+    >>> import array_api_strict as xp
+    >>> import array_api_extra as xpx
+    >>> x = xp.linspace(-4, 4, 41)
+    >>> xpx.sinc(x, xp=xp)
+    Array([-3.89817183e-17, -4.92362781e-02,
+           -8.40918587e-02, -8.90384387e-02,
+           -5.84680802e-02,  3.89817183e-17,
+            6.68206631e-02,  1.16434881e-01,
+            1.26137788e-01,  8.50444803e-02,
+           -3.89817183e-17, -1.03943254e-01,
+           -1.89206682e-01, -2.16236208e-01,
+           -1.55914881e-01,  3.89817183e-17,
+            2.33872321e-01,  5.04551152e-01,
+            7.56826729e-01,  9.35489284e-01,
+            1.00000000e+00,  9.35489284e-01,
+            7.56826729e-01,  5.04551152e-01,
+            2.33872321e-01,  3.89817183e-17,
+           -1.55914881e-01, -2.16236208e-01,
+           -1.89206682e-01, -1.03943254e-01,
+           -3.89817183e-17,  8.50444803e-02,
+            1.26137788e-01,  1.16434881e-01,
+            6.68206631e-02,  3.89817183e-17,
+           -5.84680802e-02, -8.90384387e-02,
+           -8.40918587e-02, -4.92362781e-02,
+           -3.89817183e-17], dtype=array_api_strict.float64)
+
+    """
+    if not xp.isdtype(x.dtype, "real floating"):
+        err_msg = "`x` must have a real floating data type."
+        raise ValueError(err_msg)
+    # no scalars in `where` - array-api#807
+    y = xp.pi * xp.where(
+        x, x, xp.asarray(xp.finfo(x.dtype).smallest_normal, dtype=x.dtype)
+    )
+    return xp.sin(y) / y
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_typing.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ffa13f23fc8c52abf5c65206ec1ff5a8481832c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/array_api_extra/_typing.py
@@ -0,0 +1,8 @@
+from __future__ import annotations
+
+from types import ModuleType
+from typing import Any
+
+Array = Any  # To be changed to a Protocol later (see array-api#589)
+
+__all__ = ["Array", "ModuleType"]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2418395425d7ecce9e1a4da68985c8fde93bc1c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/__init__.py
@@ -0,0 +1,20 @@
+from .main import minimize
+from .utils import show_versions
+
+# PEP0440 compatible formatted version, see:
+# https://www.python.org/dev/peps/pep-0440/
+#
+# Final release markers:
+#   X.Y.0   # For first release after an increment in Y
+#   X.Y.Z   # For bugfix releases
+#
+# Admissible pre-release markers:
+#   X.YaN   # Alpha release
+#   X.YbN   # Beta release
+#   X.YrcN  # Release Candidate
+#
+# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
+# 'X.Y.dev0' is the canonical version of 'X.Y.dev'.
+__version__ = "1.1.2"
+
+__all__ = ["minimize", "show_versions"]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/framework.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/framework.py
new file mode 100644
index 0000000000000000000000000000000000000000..9afea66281067e27a486ff317a4bffa03ec3e68b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/framework.py
@@ -0,0 +1,1240 @@
+import warnings
+
+import numpy as np
+from scipy.optimize import lsq_linear
+
+from .models import Models, Quadratic
+from .settings import Options, Constants
+from .subsolvers import (
+    cauchy_geometry,
+    spider_geometry,
+    normal_byrd_omojokun,
+    tangential_byrd_omojokun,
+    constrained_tangential_byrd_omojokun,
+)
+from .subsolvers.optim import qr_tangential_byrd_omojokun
+from .utils import get_arrays_tol
+
+
+TINY = np.finfo(float).tiny
+EPS = np.finfo(float).eps
+
+
+class TrustRegion:
+    """
+    Trust-region framework.
+    """
+
+    def __init__(self, pb, options, constants):
+        """
+        Initialize the trust-region framework.
+
+        Parameters
+        ----------
+        pb : `cobyqa.problem.Problem`
+            Problem to solve.
+        options : dict
+            Options of the solver.
+        constants : dict
+            Constants of the solver.
+
+        Raises
+        ------
+        `cobyqa.utils.MaxEvalError`
+            If the maximum number of evaluations is reached.
+        `cobyqa.utils.TargetSuccess`
+            If a nearly feasible point has been found with an objective
+            function value below the target.
+        `cobyqa.utils.FeasibleSuccess`
+            If a feasible point has been found for a feasibility problem.
+        `numpy.linalg.LinAlgError`
+            If the initial interpolation system is ill-defined.
+        """
+        # Set the initial penalty parameter.
+        self._penalty = 0.0
+
+        # Initialize the models.
+        self._pb = pb
+        self._models = Models(self._pb, options, self.penalty)
+        self._constants = constants
+
+        # Set the index of the best interpolation point.
+        self._best_index = 0
+        self.set_best_index()
+
+        # Set the initial Lagrange multipliers.
+        self._lm_linear_ub = np.zeros(self.m_linear_ub)
+        self._lm_linear_eq = np.zeros(self.m_linear_eq)
+        self._lm_nonlinear_ub = np.zeros(self.m_nonlinear_ub)
+        self._lm_nonlinear_eq = np.zeros(self.m_nonlinear_eq)
+        self.set_multipliers(self.x_best)
+
+        # Set the initial trust-region radius and the resolution.
+        self._resolution = options[Options.RHOBEG]
+        self._radius = self.resolution
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self._pb.n
+
+    @property
+    def m_linear_ub(self):
+        """
+        Number of linear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear inequality constraints.
+        """
+        return self._pb.m_linear_ub
+
+    @property
+    def m_linear_eq(self):
+        """
+        Number of linear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear equality constraints.
+        """
+        return self._pb.m_linear_eq
+
+    @property
+    def m_nonlinear_ub(self):
+        """
+        Number of nonlinear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear inequality constraints.
+        """
+        return self._pb.m_nonlinear_ub
+
+    @property
+    def m_nonlinear_eq(self):
+        """
+        Number of nonlinear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear equality constraints.
+        """
+        return self._pb.m_nonlinear_eq
+
+    @property
+    def radius(self):
+        """
+        Trust-region radius.
+
+        Returns
+        -------
+        float
+            Trust-region radius.
+        """
+        return self._radius
+
+    @radius.setter
+    def radius(self, radius):
+        """
+        Set the trust-region radius.
+
+        Parameters
+        ----------
+        radius : float
+            New trust-region radius.
+        """
+        self._radius = radius
+        if (
+            self.radius
+            <= self._constants[Constants.DECREASE_RADIUS_THRESHOLD]
+            * self.resolution
+        ):
+            self._radius = self.resolution
+
+    @property
+    def resolution(self):
+        """
+        Resolution of the trust-region framework.
+
+        The resolution is a lower bound on the trust-region radius.
+
+        Returns
+        -------
+        float
+            Resolution of the trust-region framework.
+        """
+        return self._resolution
+
+    @resolution.setter
+    def resolution(self, resolution):
+        """
+        Set the resolution of the trust-region framework.
+
+        Parameters
+        ----------
+        resolution : float
+            New resolution of the trust-region framework.
+        """
+        self._resolution = resolution
+
+    @property
+    def penalty(self):
+        """
+        Penalty parameter.
+
+        Returns
+        -------
+        float
+            Penalty parameter.
+        """
+        return self._penalty
+
+    @property
+    def models(self):
+        """
+        Models of the objective function and constraints.
+
+        Returns
+        -------
+        `cobyqa.models.Models`
+            Models of the objective function and constraints.
+        """
+        return self._models
+
+    @property
+    def best_index(self):
+        """
+        Index of the best interpolation point.
+
+        Returns
+        -------
+        int
+            Index of the best interpolation point.
+        """
+        return self._best_index
+
+    @property
+    def x_best(self):
+        """
+        Best interpolation point.
+
+        Its value is interpreted as relative to the origin, not the base point.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Best interpolation point.
+        """
+        return self.models.interpolation.point(self.best_index)
+
+    @property
+    def fun_best(self):
+        """
+        Value of the objective function at `x_best`.
+
+        Returns
+        -------
+        float
+            Value of the objective function at `x_best`.
+        """
+        return self.models.fun_val[self.best_index]
+
+    @property
+    def cub_best(self):
+        """
+        Values of the nonlinear inequality constraints at `x_best`.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Values of the nonlinear inequality constraints at `x_best`.
+        """
+        return self.models.cub_val[self.best_index, :]
+
+    @property
+    def ceq_best(self):
+        """
+        Values of the nonlinear equality constraints at `x_best`.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Values of the nonlinear equality constraints at `x_best`.
+        """
+        return self.models.ceq_val[self.best_index, :]
+
+    def lag_model(self, x):
+        """
+        Evaluate the Lagrangian model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the Lagrangian model is evaluated.
+
+        Returns
+        -------
+        float
+            Value of the Lagrangian model at `x`.
+        """
+        return (
+            self.models.fun(x)
+            + self._lm_linear_ub
+            @ (self._pb.linear.a_ub @ x - self._pb.linear.b_ub)
+            + self._lm_linear_eq
+            @ (self._pb.linear.a_eq @ x - self._pb.linear.b_eq)
+            + self._lm_nonlinear_ub @ self.models.cub(x)
+            + self._lm_nonlinear_eq @ self.models.ceq(x)
+        )
+
+    def lag_model_grad(self, x):
+        """
+        Evaluate the gradient of the Lagrangian model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the gradient of the Lagrangian model is evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the Lagrangian model at `x`.
+        """
+        return (
+            self.models.fun_grad(x)
+            + self._lm_linear_ub @ self._pb.linear.a_ub
+            + self._lm_linear_eq @ self._pb.linear.a_eq
+            + self._lm_nonlinear_ub @ self.models.cub_grad(x)
+            + self._lm_nonlinear_eq @ self.models.ceq_grad(x)
+        )
+
+    def lag_model_hess(self):
+        """
+        Evaluate the Hessian matrix of the Lagrangian model at a given point.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, n)
+            Hessian matrix of the Lagrangian model at `x`.
+        """
+        hess = self.models.fun_hess()
+        if self.m_nonlinear_ub > 0:
+            hess += self._lm_nonlinear_ub @ self.models.cub_hess()
+        if self.m_nonlinear_eq > 0:
+            hess += self._lm_nonlinear_eq @ self.models.ceq_hess()
+        return hess
+
+    def lag_model_hess_prod(self, v):
+        """
+        Evaluate the right product of the Hessian matrix of the Lagrangian
+        model with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrix of the Lagrangian model is
+            multiplied from the right.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Right product of the Hessian matrix of the Lagrangian model with
+            `v`.
+        """
+        return (
+            self.models.fun_hess_prod(v)
+            + self._lm_nonlinear_ub @ self.models.cub_hess_prod(v)
+            + self._lm_nonlinear_eq @ self.models.ceq_hess_prod(v)
+        )
+
+    def lag_model_curv(self, v):
+        """
+        Evaluate the curvature of the Lagrangian model along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the Lagrangian model is
+            evaluated.
+
+        Returns
+        -------
+        float
+            Curvature of the Lagrangian model along `v`.
+        """
+        return (
+            self.models.fun_curv(v)
+            + self._lm_nonlinear_ub @ self.models.cub_curv(v)
+            + self._lm_nonlinear_eq @ self.models.ceq_curv(v)
+        )
+
+    def sqp_fun(self, step):
+        """
+        Evaluate the objective function of the SQP subproblem.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Step along which the objective function of the SQP subproblem is
+            evaluated.
+
+        Returns
+        -------
+        float
+            Value of the objective function of the SQP subproblem along `step`.
+        """
+        return step @ (
+            self.models.fun_grad(self.x_best)
+            + 0.5 * self.lag_model_hess_prod(step)
+        )
+
+    def sqp_cub(self, step):
+        """
+        Evaluate the linearization of the nonlinear inequality constraints.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Step along which the linearization of the nonlinear inequality
+            constraints is evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Value of the linearization of the nonlinear inequality constraints
+            along `step`.
+        """
+        return (
+            self.models.cub(self.x_best)
+            + self.models.cub_grad(self.x_best) @ step
+        )
+
+    def sqp_ceq(self, step):
+        """
+        Evaluate the linearization of the nonlinear equality constraints.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Step along which the linearization of the nonlinear equality
+            constraints is evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Value of the linearization of the nonlinear equality constraints
+            along `step`.
+        """
+        return (
+            self.models.ceq(self.x_best)
+            + self.models.ceq_grad(self.x_best) @ step
+        )
+
+    def merit(self, x, fun_val=None, cub_val=None, ceq_val=None):
+        """
+        Evaluate the merit function at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the merit function is evaluated.
+        fun_val : float, optional
+            Value of the objective function at `x`. If not provided, the
+            objective function is evaluated at `x`.
+        cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Values of the nonlinear inequality constraints. If not provided,
+            the nonlinear inequality constraints are evaluated at `x`.
+        ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Values of the nonlinear equality constraints. If not provided,
+            the nonlinear equality constraints are evaluated at `x`.
+
+        Returns
+        -------
+        float
+            Value of the merit function at `x`.
+        """
+        if fun_val is None or cub_val is None or ceq_val is None:
+            fun_val, cub_val, ceq_val = self._pb(x, self.penalty)
+        m_val = fun_val
+        if self._penalty > 0.0:
+            c_val = self._pb.violation(x, cub_val=cub_val, ceq_val=ceq_val)
+            if np.count_nonzero(c_val):
+                m_val += self._penalty * np.linalg.norm(c_val)
+        return m_val
+
+    def get_constraint_linearizations(self, x):
+        """
+        Get the linearizations of the constraints at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the linearizations of the constraints are evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_linear_ub + m_nonlinear_ub, n)
+            Left-hand side matrix of the linearized inequality constraints.
+        `numpy.ndarray`, shape (m_linear_ub + m_nonlinear_ub,)
+            Right-hand side vector of the linearized inequality constraints.
+        `numpy.ndarray`, shape (m_linear_eq + m_nonlinear_eq, n)
+            Left-hand side matrix of the linearized equality constraints.
+        `numpy.ndarray`, shape (m_linear_eq + m_nonlinear_eq,)
+            Right-hand side vector of the linearized equality constraints.
+        """
+        aub = np.block(
+            [
+                [self._pb.linear.a_ub],
+                [self.models.cub_grad(x)],
+            ]
+        )
+        bub = np.block(
+            [
+                self._pb.linear.b_ub - self._pb.linear.a_ub @ x,
+                -self.models.cub(x),
+            ]
+        )
+        aeq = np.block(
+            [
+                [self._pb.linear.a_eq],
+                [self.models.ceq_grad(x)],
+            ]
+        )
+        beq = np.block(
+            [
+                self._pb.linear.b_eq - self._pb.linear.a_eq @ x,
+                -self.models.ceq(x),
+            ]
+        )
+        return aub, bub, aeq, beq
+
+    def get_trust_region_step(self, options):
+        """
+        Get the trust-region step.
+
+        The trust-region step is computed by solving the derivative-free
+        trust-region SQP subproblem using a Byrd-Omojokun composite-step
+        approach. For more details, see Section 5.2.3 of [1]_.
+
+        Parameters
+        ----------
+        options : dict
+            Options of the solver.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Normal step.
+        `numpy.ndarray`, shape (n,)
+            Tangential step.
+
+        References
+        ----------
+        .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization
+           Methods and Software*. PhD thesis, Department of Applied
+           Mathematics, The Hong Kong Polytechnic University, Hong Kong, China,
+           2022. URL: https://theses.lib.polyu.edu.hk/handle/200/12294.
+        """
+        # Evaluate the linearizations of the constraints.
+        aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best)
+        xl = self._pb.bounds.xl - self.x_best
+        xu = self._pb.bounds.xu - self.x_best
+
+        # Evaluate the normal step.
+        radius = self._constants[Constants.BYRD_OMOJOKUN_FACTOR] * self.radius
+        normal_step = normal_byrd_omojokun(
+            aub,
+            bub,
+            aeq,
+            beq,
+            xl,
+            xu,
+            radius,
+            options[Options.DEBUG],
+            **self._constants,
+        )
+        if options[Options.DEBUG]:
+            tol = get_arrays_tol(xl, xu)
+            if (np.any(normal_step + tol < xl)
+                    or np.any(xu < normal_step - tol)):
+                warnings.warn(
+                    "the normal step does not respect the bound constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+            if np.linalg.norm(normal_step) > 1.1 * radius:
+                warnings.warn(
+                    "the normal step does not respect the trust-region "
+                    "constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+
+        # Evaluate the tangential step.
+        radius = np.sqrt(self.radius**2.0 - normal_step @ normal_step)
+        xl -= normal_step
+        xu -= normal_step
+        bub = np.maximum(bub - aub @ normal_step, 0.0)
+        g_best = self.models.fun_grad(self.x_best) + self.lag_model_hess_prod(
+            normal_step
+        )
+        if self._pb.type in ["unconstrained", "bound-constrained"]:
+            tangential_step = tangential_byrd_omojokun(
+                g_best,
+                self.lag_model_hess_prod,
+                xl,
+                xu,
+                radius,
+                options[Options.DEBUG],
+                **self._constants,
+            )
+        else:
+            tangential_step = constrained_tangential_byrd_omojokun(
+                g_best,
+                self.lag_model_hess_prod,
+                xl,
+                xu,
+                aub,
+                bub,
+                aeq,
+                radius,
+                options["debug"],
+                **self._constants,
+            )
+        if options[Options.DEBUG]:
+            tol = get_arrays_tol(xl, xu)
+            if np.any(tangential_step + tol < xl) or np.any(
+                xu < tangential_step - tol
+            ):
+                warnings.warn(
+                    "The tangential step does not respect the bound "
+                    "constraints.",
+                    RuntimeWarning,
+                    2,
+                )
+            if (
+                np.linalg.norm(normal_step + tangential_step)
+                > 1.1 * np.sqrt(2.0) * self.radius
+            ):
+                warnings.warn(
+                    "The trial step does not respect the trust-region "
+                    "constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+        return normal_step, tangential_step
+
+    def get_geometry_step(self, k_new, options):
+        """
+        Get the geometry-improving step.
+
+        Three different geometry-improving steps are computed and the best one
+        is returned. For more details, see Section 5.2.7 of [1]_.
+
+        Parameters
+        ----------
+        k_new : int
+            Index of the interpolation point to be modified.
+        options : dict
+            Options of the solver.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Geometry-improving step.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the computation of a determinant fails.
+
+        References
+        ----------
+        .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization
+           Methods and Software*. PhD thesis, Department of Applied
+           Mathematics, The Hong Kong Polytechnic University, Hong Kong, China,
+           2022. URL: https://theses.lib.polyu.edu.hk/handle/200/12294.
+        """
+        if options[Options.DEBUG]:
+            assert (
+                k_new != self.best_index
+            ), "The index `k_new` must be different from the best index."
+
+        # Build the k_new-th Lagrange polynomial.
+        coord_vec = np.squeeze(np.eye(1, self.models.npt, k_new))
+        lag = Quadratic(
+            self.models.interpolation,
+            coord_vec,
+            options[Options.DEBUG],
+        )
+        g_lag = lag.grad(self.x_best, self.models.interpolation)
+
+        # Compute a simple constrained Cauchy step.
+        xl = self._pb.bounds.xl - self.x_best
+        xu = self._pb.bounds.xu - self.x_best
+        step = cauchy_geometry(
+            0.0,
+            g_lag,
+            lambda v: lag.curv(v, self.models.interpolation),
+            xl,
+            xu,
+            self.radius,
+            options[Options.DEBUG],
+        )
+        sigma = self.models.determinants(self.x_best + step, k_new)
+
+        # Compute the solution on the straight lines joining the interpolation
+        # points to the k-th one, and choose it if it provides a larger value
+        # of the determinant of the interpolation system in absolute value.
+        xpt = (
+            self.models.interpolation.xpt
+            - self.models.interpolation.xpt[:, self.best_index, np.newaxis]
+        )
+        xpt[:, [0, self.best_index]] = xpt[:, [self.best_index, 0]]
+        step_alt = spider_geometry(
+            0.0,
+            g_lag,
+            lambda v: lag.curv(v, self.models.interpolation),
+            xpt[:, 1:],
+            xl,
+            xu,
+            self.radius,
+            options[Options.DEBUG],
+        )
+        sigma_alt = self.models.determinants(self.x_best + step_alt, k_new)
+        if abs(sigma_alt) > abs(sigma):
+            step = step_alt
+            sigma = sigma_alt
+
+        # Compute a Cauchy step on the tangent space of the active constraints.
+        if self._pb.type in [
+            "linearly constrained",
+            "nonlinearly constrained",
+        ]:
+            aub, bub, aeq, beq = (
+                self.get_constraint_linearizations(self.x_best))
+            tol_bd = get_arrays_tol(xl, xu)
+            tol_ub = get_arrays_tol(bub)
+            free_xl = xl <= -tol_bd
+            free_xu = xu >= tol_bd
+            free_ub = bub >= tol_ub
+
+            # Compute the Cauchy step.
+            n_act, q = qr_tangential_byrd_omojokun(
+                aub,
+                aeq,
+                free_xl,
+                free_xu,
+                free_ub,
+            )
+            g_lag_proj = q[:, n_act:] @ (q[:, n_act:].T @ g_lag)
+            norm_g_lag_proj = np.linalg.norm(g_lag_proj)
+            if 0 < n_act < self._pb.n and norm_g_lag_proj > TINY * self.radius:
+                step_alt = (self.radius / norm_g_lag_proj) * g_lag_proj
+                if lag.curv(step_alt, self.models.interpolation) < 0.0:
+                    step_alt = -step_alt
+
+                # Evaluate the constraint violation at the Cauchy step.
+                cbd = np.block([xl - step_alt, step_alt - xu])
+                cub = aub @ step_alt - bub
+                ceq = aeq @ step_alt - beq
+                maxcv_val = max(
+                    np.max(array, initial=0.0)
+                    for array in [cbd, cub, np.abs(ceq)]
+                )
+
+                # Accept the new step if it is nearly feasible and do not
+                # drastically worsen the determinant of the interpolation
+                # system in absolute value.
+                tol = np.max(np.abs(step_alt[~free_xl]), initial=0.0)
+                tol = np.max(np.abs(step_alt[~free_xu]), initial=tol)
+                tol = np.max(np.abs(aub[~free_ub, :] @ step_alt), initial=tol)
+                tol = min(10.0 * tol, 1e-2 * np.linalg.norm(step_alt))
+                if maxcv_val <= tol:
+                    sigma_alt = self.models.determinants(
+                        self.x_best + step_alt, k_new
+                    )
+                    if abs(sigma_alt) >= 0.1 * abs(sigma):
+                        step = np.clip(step_alt, xl, xu)
+
+        if options[Options.DEBUG]:
+            tol = get_arrays_tol(xl, xu)
+            if np.any(step + tol < xl) or np.any(xu < step - tol):
+                warnings.warn(
+                    "The geometry step does not respect the bound "
+                    "constraints.",
+                    RuntimeWarning,
+                    2,
+                )
+            if np.linalg.norm(step) > 1.1 * self.radius:
+                warnings.warn(
+                    "The geometry step does not respect the "
+                    "trust-region constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+        return step
+
+    def get_second_order_correction_step(self, step, options):
+        """
+        Get the second-order correction step.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Trust-region step.
+        options : dict
+            Options of the solver.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Second-order correction step.
+        """
+        # Evaluate the linearizations of the constraints.
+        aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best)
+        xl = self._pb.bounds.xl - self.x_best
+        xu = self._pb.bounds.xu - self.x_best
+        radius = np.linalg.norm(step)
+        soc_step = normal_byrd_omojokun(
+            aub,
+            bub,
+            aeq,
+            beq,
+            xl,
+            xu,
+            radius,
+            options[Options.DEBUG],
+            **self._constants,
+        )
+        if options[Options.DEBUG]:
+            tol = get_arrays_tol(xl, xu)
+            if np.any(soc_step + tol < xl) or np.any(xu < soc_step - tol):
+                warnings.warn(
+                    "The second-order correction step does not "
+                    "respect the bound constraints.",
+                    RuntimeWarning,
+                    2,
+                )
+            if np.linalg.norm(soc_step) > 1.1 * radius:
+                warnings.warn(
+                    "The second-order correction step does not "
+                    "respect the trust-region constraint.",
+                    RuntimeWarning,
+                    2,
+                )
+        return soc_step
+
+    def get_reduction_ratio(self, step, fun_val, cub_val, ceq_val):
+        """
+        Get the reduction ratio.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Trust-region step.
+        fun_val : float
+            Objective function value at the trial point.
+        cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Nonlinear inequality constraint values at the trial point.
+        ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Nonlinear equality constraint values at the trial point.
+
+        Returns
+        -------
+        float
+            Reduction ratio.
+        """
+        merit_old = self.merit(
+            self.x_best,
+            self.fun_best,
+            self.cub_best,
+            self.ceq_best,
+        )
+        merit_new = self.merit(self.x_best + step, fun_val, cub_val, ceq_val)
+        merit_model_old = self.merit(
+            self.x_best,
+            0.0,
+            self.models.cub(self.x_best),
+            self.models.ceq(self.x_best),
+        )
+        merit_model_new = self.merit(
+            self.x_best + step,
+            self.sqp_fun(step),
+            self.sqp_cub(step),
+            self.sqp_ceq(step),
+        )
+        if abs(merit_model_old - merit_model_new) > TINY * abs(
+            merit_old - merit_new
+        ):
+            return (merit_old - merit_new) / abs(
+                merit_model_old - merit_model_new
+            )
+        else:
+            return -1.0
+
+    def increase_penalty(self, step):
+        """
+        Increase the penalty parameter.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Trust-region step.
+        """
+        aub, bub, aeq, beq = self.get_constraint_linearizations(self.x_best)
+        viol_diff = max(
+            np.linalg.norm(
+                np.block(
+                    [
+                        np.maximum(0.0, -bub),
+                        beq,
+                    ]
+                )
+            )
+            - np.linalg.norm(
+                np.block(
+                    [
+                        np.maximum(0.0, aub @ step - bub),
+                        aeq @ step - beq,
+                    ]
+                )
+            ),
+            0.0,
+        )
+        sqp_val = self.sqp_fun(step)
+
+        threshold = np.linalg.norm(
+            np.block(
+                [
+                    self._lm_linear_ub,
+                    self._lm_linear_eq,
+                    self._lm_nonlinear_ub,
+                    self._lm_nonlinear_eq,
+                ]
+            )
+        )
+        if abs(viol_diff) > TINY * abs(sqp_val):
+            threshold = max(threshold, sqp_val / viol_diff)
+        best_index_save = self.best_index
+        if (
+            self._penalty
+            <= self._constants[Constants.PENALTY_INCREASE_THRESHOLD]
+                * threshold
+        ):
+            self._penalty = max(
+                self._constants[Constants.PENALTY_INCREASE_FACTOR] * threshold,
+                1.0,
+            )
+            self.set_best_index()
+        return best_index_save == self.best_index
+
+    def decrease_penalty(self):
+        """
+        Decrease the penalty parameter.
+        """
+        self._penalty = min(self._penalty, self._get_low_penalty())
+        self.set_best_index()
+
+    def set_best_index(self):
+        """
+        Set the index of the best point.
+        """
+        best_index = self.best_index
+        m_best = self.merit(
+            self.x_best,
+            self.models.fun_val[best_index],
+            self.models.cub_val[best_index, :],
+            self.models.ceq_val[best_index, :],
+        )
+        r_best = self._pb.maxcv(
+            self.x_best,
+            self.models.cub_val[best_index, :],
+            self.models.ceq_val[best_index, :],
+        )
+        tol = (
+            10.0
+            * EPS
+            * max(self.models.n, self.models.npt)
+            * max(abs(m_best), 1.0)
+        )
+        for k in range(self.models.npt):
+            if k != self.best_index:
+                x_val = self.models.interpolation.point(k)
+                m_val = self.merit(
+                    x_val,
+                    self.models.fun_val[k],
+                    self.models.cub_val[k, :],
+                    self.models.ceq_val[k, :],
+                )
+                r_val = self._pb.maxcv(
+                    x_val,
+                    self.models.cub_val[k, :],
+                    self.models.ceq_val[k, :],
+                )
+                if m_val < m_best or (m_val < m_best + tol and r_val < r_best):
+                    best_index = k
+                    m_best = m_val
+                    r_best = r_val
+        self._best_index = best_index
+
+    def get_index_to_remove(self, x_new=None):
+        """
+        Get the index of the interpolation point to remove.
+
+        If `x_new` is not provided, the index returned should be used during
+        the geometry-improvement phase. Otherwise, the index returned is the
+        best index for included `x_new` in the interpolation set.
+
+        Parameters
+        ----------
+        x_new : `numpy.ndarray`, shape (n,), optional
+            New point to be included in the interpolation set.
+
+        Returns
+        -------
+        int
+            Index of the interpolation point to remove.
+        float
+            Distance between `x_best` and the removed point.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the computation of a determinant fails.
+        """
+        dist_sq = np.sum(
+            (
+                self.models.interpolation.xpt
+                - self.models.interpolation.xpt[:, self.best_index, np.newaxis]
+            )
+            ** 2.0,
+            axis=0,
+        )
+        if x_new is None:
+            sigma = 1.0
+            weights = dist_sq
+        else:
+            sigma = self.models.determinants(x_new)
+            weights = (
+                np.maximum(
+                    1.0,
+                    dist_sq
+                    / max(
+                        self._constants[Constants.LOW_RADIUS_FACTOR]
+                        * self.radius,
+                        self.resolution,
+                    )
+                    ** 2.0,
+                )
+                ** 3.0
+            )
+            weights[self.best_index] = -1.0  # do not remove the best point
+        k_max = np.argmax(weights * np.abs(sigma))
+        return k_max, np.sqrt(dist_sq[k_max])
+
+    def update_radius(self, step, ratio):
+        """
+        Update the trust-region radius.
+
+        Parameters
+        ----------
+        step : `numpy.ndarray`, shape (n,)
+            Trust-region step.
+        ratio : float
+            Reduction ratio.
+        """
+        s_norm = np.linalg.norm(step)
+        if ratio <= self._constants[Constants.LOW_RATIO]:
+            self.radius *= self._constants[Constants.DECREASE_RADIUS_FACTOR]
+        elif ratio <= self._constants[Constants.HIGH_RATIO]:
+            self.radius = max(
+                self._constants[Constants.DECREASE_RADIUS_FACTOR]
+                * self.radius,
+                s_norm,
+            )
+        else:
+            self.radius = min(
+                self._constants[Constants.INCREASE_RADIUS_FACTOR]
+                * self.radius,
+                max(
+                    self._constants[Constants.DECREASE_RADIUS_FACTOR]
+                    * self.radius,
+                    self._constants[Constants.INCREASE_RADIUS_THRESHOLD]
+                    * s_norm,
+                ),
+            )
+
+    def enhance_resolution(self, options):
+        """
+        Enhance the resolution of the trust-region framework.
+
+        Parameters
+        ----------
+        options : dict
+            Options of the solver.
+        """
+        if (
+            self._constants[Constants.LARGE_RESOLUTION_THRESHOLD]
+            * options[Options.RHOEND]
+            < self.resolution
+        ):
+            self.resolution *= self._constants[
+                Constants.DECREASE_RESOLUTION_FACTOR
+            ]
+        elif (
+            self._constants[Constants.MODERATE_RESOLUTION_THRESHOLD]
+            * options[Options.RHOEND]
+            < self.resolution
+        ):
+            self.resolution = np.sqrt(self.resolution
+                                      * options[Options.RHOEND])
+        else:
+            self.resolution = options[Options.RHOEND]
+
+        # Reduce the trust-region radius.
+        self._radius = max(
+            self._constants[Constants.DECREASE_RADIUS_FACTOR] * self._radius,
+            self.resolution,
+        )
+
+    def shift_x_base(self, options):
+        """
+        Shift the base point to `x_best`.
+
+        Parameters
+        ----------
+        options : dict
+            Options of the solver.
+        """
+        self.models.shift_x_base(np.copy(self.x_best), options)
+
+    def set_multipliers(self, x):
+        """
+        Set the Lagrange multipliers.
+
+        This method computes and set the Lagrange multipliers of the linear and
+        nonlinear constraints to be the QP multipliers.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the Lagrange multipliers are computed.
+        """
+        # Build the constraints of the least-squares problem.
+        incl_linear_ub = self._pb.linear.a_ub @ x >= self._pb.linear.b_ub
+        incl_nonlinear_ub = self.cub_best >= 0.0
+        incl_xl = self._pb.bounds.xl >= x
+        incl_xu = self._pb.bounds.xu <= x
+        m_linear_ub = np.count_nonzero(incl_linear_ub)
+        m_nonlinear_ub = np.count_nonzero(incl_nonlinear_ub)
+        m_xl = np.count_nonzero(incl_xl)
+        m_xu = np.count_nonzero(incl_xu)
+
+        if (
+            m_linear_ub + m_nonlinear_ub + self.m_linear_eq
+                + self.m_nonlinear_eq > 0
+        ):
+            identity = np.eye(self._pb.n)
+            c_jac = np.r_[
+                -identity[incl_xl, :],
+                identity[incl_xu, :],
+                self._pb.linear.a_ub[incl_linear_ub, :],
+                self.models.cub_grad(x, incl_nonlinear_ub),
+                self._pb.linear.a_eq,
+                self.models.ceq_grad(x),
+            ]
+
+            # Solve the least-squares problem.
+            g_best = self.models.fun_grad(x)
+            xl_lm = np.full(c_jac.shape[0], -np.inf)
+            xl_lm[: m_xl + m_xu + m_linear_ub + m_nonlinear_ub] = 0.0
+            res = lsq_linear(
+                c_jac.T,
+                -g_best,
+                bounds=(xl_lm, np.inf),
+                method="bvls",
+            )
+
+            # Extract the Lagrange multipliers.
+            self._lm_linear_ub[incl_linear_ub] = res.x[
+                m_xl + m_xu:m_xl + m_xu + m_linear_ub
+            ]
+            self._lm_linear_ub[~incl_linear_ub] = 0.0
+            self._lm_nonlinear_ub[incl_nonlinear_ub] = res.x[
+                m_xl
+                + m_xu
+                + m_linear_ub:m_xl
+                + m_xu
+                + m_linear_ub
+                + m_nonlinear_ub
+            ]
+            self._lm_nonlinear_ub[~incl_nonlinear_ub] = 0.0
+            self._lm_linear_eq[:] = res.x[
+                m_xl
+                + m_xu
+                + m_linear_ub
+                + m_nonlinear_ub:m_xl
+                + m_xu
+                + m_linear_ub
+                + m_nonlinear_ub
+                + self.m_linear_eq
+            ]
+            self._lm_nonlinear_eq[:] = res.x[
+                m_xl + m_xu + m_linear_ub + m_nonlinear_ub + self.m_linear_eq:
+            ]
+
+    def _get_low_penalty(self):
+        r_val_ub = np.c_[
+            (
+                self.models.interpolation.x_base[np.newaxis, :]
+                + self.models.interpolation.xpt.T
+            )
+            @ self._pb.linear.a_ub.T
+            - self._pb.linear.b_ub[np.newaxis, :],
+            self.models.cub_val,
+        ]
+        r_val_eq = (
+            self.models.interpolation.x_base[np.newaxis, :]
+            + self.models.interpolation.xpt.T
+        ) @ self._pb.linear.a_eq.T - self._pb.linear.b_eq[np.newaxis, :]
+        r_val_eq = np.block(
+            [
+                r_val_eq,
+                -r_val_eq,
+                self.models.ceq_val,
+                -self.models.ceq_val,
+            ]
+        )
+        r_val = np.block([r_val_ub, r_val_eq])
+        c_min = np.nanmin(r_val, axis=0)
+        c_max = np.nanmax(r_val, axis=0)
+        indices = (
+            c_min
+            < self._constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] * c_max
+        )
+        if np.any(indices):
+            f_min = np.nanmin(self.models.fun_val)
+            f_max = np.nanmax(self.models.fun_val)
+            c_min_neg = np.minimum(0.0, c_min[indices])
+            c_diff = np.min(c_max[indices] - c_min_neg)
+            if c_diff > TINY * (f_max - f_min):
+                penalty = (f_max - f_min) / c_diff
+            else:
+                penalty = np.inf
+        else:
+            penalty = 0.0
+        return penalty
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/main.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/main.py
new file mode 100644
index 0000000000000000000000000000000000000000..01e5159e0dfebed9a78c6948cb99bfb1d744b6c7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/main.py
@@ -0,0 +1,1506 @@
+import warnings
+
+import numpy as np
+from scipy.optimize import (
+    Bounds,
+    LinearConstraint,
+    NonlinearConstraint,
+    OptimizeResult,
+)
+
+from .framework import TrustRegion
+from .problem import (
+    ObjectiveFunction,
+    BoundConstraints,
+    LinearConstraints,
+    NonlinearConstraints,
+    Problem,
+)
+from .utils import (
+    MaxEvalError,
+    TargetSuccess,
+    CallbackSuccess,
+    FeasibleSuccess,
+    exact_1d_array,
+)
+from .settings import (
+    ExitStatus,
+    Options,
+    Constants,
+    DEFAULT_OPTIONS,
+    DEFAULT_CONSTANTS,
+    PRINT_OPTIONS,
+)
+
+
+def minimize(
+    fun,
+    x0,
+    args=(),
+    bounds=None,
+    constraints=(),
+    callback=None,
+    options=None,
+    **kwargs,
+):
+    r"""
+    Minimize a scalar function using the COBYQA method.
+
+    The Constrained Optimization BY Quadratic Approximations (COBYQA) method is
+    a derivative-free optimization method designed to solve general nonlinear
+    optimization problems. A complete description of COBYQA is given in [3]_.
+
+    Parameters
+    ----------
+    fun : {callable, None}
+        Objective function to be minimized.
+
+            ``fun(x, *args) -> float``
+
+        where ``x`` is an array with shape (n,) and `args` is a tuple. If `fun`
+        is ``None``, the objective function is assumed to be the zero function,
+        resulting in a feasibility problem.
+    x0 : array_like, shape (n,)
+        Initial guess.
+    args : tuple, optional
+        Extra arguments passed to the objective function.
+    bounds : {`scipy.optimize.Bounds`, array_like, shape (n, 2)}, optional
+        Bound constraints of the problem. It can be one of the cases below.
+
+        #. An instance of `scipy.optimize.Bounds`. For the time being, the
+           argument ``keep_feasible`` is disregarded, and all the constraints
+           are considered unrelaxable and will be enforced.
+        #. An array with shape (n, 2). The bound constraints for ``x[i]`` are
+           ``bounds[i][0] <= x[i] <= bounds[i][1]``. Set ``bounds[i][0]`` to
+           :math:`-\infty` if there is no lower bound, and set ``bounds[i][1]``
+           to :math:`\infty` if there is no upper bound.
+
+        The COBYQA method always respect the bound constraints.
+    constraints : {Constraint, list}, optional
+        General constraints of the problem. It can be one of the cases below.
+
+        #. An instance of `scipy.optimize.LinearConstraint`. The argument
+           ``keep_feasible`` is disregarded.
+        #. An instance of `scipy.optimize.NonlinearConstraint`. The arguments
+           ``jac``, ``hess``, ``keep_feasible``, ``finite_diff_rel_step``, and
+           ``finite_diff_jac_sparsity`` are disregarded.
+
+        #. A list, each of whose elements are described in the cases above.
+
+    callback : callable, optional
+        A callback executed at each objective function evaluation. The method
+        terminates if a ``StopIteration`` exception is raised by the callback
+        function. Its signature can be one of the following:
+
+            ``callback(intermediate_result)``
+
+        where ``intermediate_result`` is a keyword parameter that contains an
+        instance of `scipy.optimize.OptimizeResult`, with attributes ``x``
+        and ``fun``, being the point at which the objective function is
+        evaluated and the value of the objective function, respectively. The
+        name of the parameter must be ``intermediate_result`` for the callback
+        to be passed an instance of `scipy.optimize.OptimizeResult`.
+
+        Alternatively, the callback function can have the signature:
+
+            ``callback(xk)``
+
+        where ``xk`` is the point at which the objective function is evaluated.
+        Introspection is used to determine which of the signatures to invoke.
+    options : dict, optional
+        Options passed to the solver. Accepted keys are:
+
+            disp : bool, optional
+                Whether to print information about the optimization procedure.
+                Default is ``False``.
+            maxfev : int, optional
+                Maximum number of function evaluations. Default is ``500 * n``.
+            maxiter : int, optional
+                Maximum number of iterations. Default is ``1000 * n``.
+            target : float, optional
+                Target on the objective function value. The optimization
+                procedure is terminated when the objective function value of a
+                feasible point is less than or equal to this target. Default is
+                ``-numpy.inf``.
+            feasibility_tol : float, optional
+                Tolerance on the constraint violation. If the maximum
+                constraint violation at a point is less than or equal to this
+                tolerance, the point is considered feasible. Default is
+                ``numpy.sqrt(numpy.finfo(float).eps)``.
+            radius_init : float, optional
+                Initial trust-region radius. Typically, this value should be in
+                the order of one tenth of the greatest expected change to `x0`.
+                Default is ``1.0``.
+            radius_final : float, optional
+                Final trust-region radius. It should indicate the accuracy
+                required in the final values of the variables. Default is
+                ``1e-6``.
+            nb_points : int, optional
+                Number of interpolation points used to build the quadratic
+                models of the objective and constraint functions. Default is
+                ``2 * n + 1``.
+            scale : bool, optional
+                Whether to scale the variables according to the bounds. Default
+                is ``False``.
+            filter_size : int, optional
+                Maximum number of points in the filter. The filter is used to
+                select the best point returned by the optimization procedure.
+                Default is ``sys.maxsize``.
+            store_history : bool, optional
+                Whether to store the history of the function evaluations.
+                Default is ``False``.
+            history_size : int, optional
+                Maximum number of function evaluations to store in the history.
+                Default is ``sys.maxsize``.
+            debug : bool, optional
+                Whether to perform additional checks during the optimization
+                procedure. This option should be used only for debugging
+                purposes and is highly discouraged to general users. Default is
+                ``False``.
+
+        Other constants (from the keyword arguments) are described below. They
+        are not intended to be changed by general users. They should only be
+        changed by users with a deep understanding of the algorithm, who want
+        to experiment with different settings.
+
+    Returns
+    -------
+    `scipy.optimize.OptimizeResult`
+        Result of the optimization procedure, with the following fields:
+
+            message : str
+                Description of the cause of the termination.
+            success : bool
+                Whether the optimization procedure terminated successfully.
+            status : int
+                Termination status of the optimization procedure.
+            x : `numpy.ndarray`, shape (n,)
+                Solution point.
+            fun : float
+                Objective function value at the solution point.
+            maxcv : float
+                Maximum constraint violation at the solution point.
+            nfev : int
+                Number of function evaluations.
+            nit : int
+                Number of iterations.
+
+        If ``store_history`` is True, the result also has the following fields:
+
+            fun_history : `numpy.ndarray`, shape (nfev,)
+                History of the objective function values.
+            maxcv_history : `numpy.ndarray`, shape (nfev,)
+                History of the maximum constraint violations.
+
+        A description of the termination statuses is given below.
+
+        .. list-table::
+            :widths: 25 75
+            :header-rows: 1
+
+            * - Exit status
+              - Description
+            * - 0
+              - The lower bound for the trust-region radius has been reached.
+            * - 1
+              - The target objective function value has been reached.
+            * - 2
+              - All variables are fixed by the bound constraints.
+            * - 3
+              - The callback requested to stop the optimization procedure.
+            * - 4
+              - The feasibility problem received has been solved successfully.
+            * - 5
+              - The maximum number of function evaluations has been exceeded.
+            * - 6
+              - The maximum number of iterations has been exceeded.
+            * - -1
+              - The bound constraints are infeasible.
+            * - -2
+              - A linear algebra error occurred.
+
+    Other Parameters
+    ----------------
+    decrease_radius_factor : float, optional
+        Factor by which the trust-region radius is reduced when the reduction
+        ratio is low or negative. Default is ``0.5``.
+    increase_radius_factor : float, optional
+        Factor by which the trust-region radius is increased when the reduction
+        ratio is large. Default is ``numpy.sqrt(2.0)``.
+    increase_radius_threshold : float, optional
+        Threshold that controls the increase of the trust-region radius when
+        the reduction ratio is large. Default is ``2.0``.
+    decrease_radius_threshold : float, optional
+        Threshold used to determine whether the trust-region radius should be
+        reduced to the resolution. Default is ``1.4``.
+    decrease_resolution_factor : float, optional
+        Factor by which the resolution is reduced when the current value is far
+        from its final value. Default is ``0.1``.
+    large_resolution_threshold : float, optional
+        Threshold used to determine whether the resolution is far from its
+        final value. Default is ``250.0``.
+    moderate_resolution_threshold : float, optional
+        Threshold used to determine whether the resolution is close to its
+        final value. Default is ``16.0``.
+    low_ratio : float, optional
+        Threshold used to determine whether the reduction ratio is low. Default
+        is ``0.1``.
+    high_ratio : float, optional
+        Threshold used to determine whether the reduction ratio is high.
+        Default is ``0.7``.
+    very_low_ratio : float, optional
+        Threshold used to determine whether the reduction ratio is very low.
+        This is used to determine whether the models should be reset. Default
+        is ``0.01``.
+    penalty_increase_threshold : float, optional
+        Threshold used to determine whether the penalty parameter should be
+        increased. Default is ``1.5``.
+    penalty_increase_factor : float, optional
+        Factor by which the penalty parameter is increased. Default is ``2.0``.
+    short_step_threshold : float, optional
+        Factor used to determine whether the trial step is too short. Default
+        is ``0.5``.
+    low_radius_factor : float, optional
+        Factor used to determine which interpolation point should be removed
+        from the interpolation set at each iteration. Default is ``0.1``.
+    byrd_omojokun_factor : float, optional
+        Factor by which the trust-region radius is reduced for the computations
+        of the normal step in the Byrd-Omojokun composite-step approach.
+        Default is ``0.8``.
+    threshold_ratio_constraints : float, optional
+        Threshold used to determine which constraints should be taken into
+        account when decreasing the penalty parameter. Default is ``2.0``.
+    large_shift_factor : float, optional
+        Factor used to determine whether the point around which the quadratic
+        models are built should be updated. Default is ``10.0``.
+    large_gradient_factor : float, optional
+        Factor used to determine whether the models should be reset. Default is
+        ``10.0``.
+    resolution_factor : float, optional
+        Factor by which the resolution is decreased. Default is ``2.0``.
+    improve_tcg : bool, optional
+        Whether to improve the steps computed by the truncated conjugate
+        gradient method when the trust-region boundary is reached. Default is
+        ``True``.
+
+    References
+    ----------
+    .. [1] J. Nocedal and S. J. Wright. *Numerical Optimization*. Springer Ser.
+       Oper. Res. Financ. Eng. Springer, New York, NY, USA, second edition,
+       2006. `doi:10.1007/978-0-387-40065-5
+       `_.
+    .. [2] M. J. D. Powell. A direct search optimization method that models the
+       objective and constraint functions by linear interpolation. In S. Gomez
+       and J.-P. Hennart, editors, *Advances in Optimization and Numerical
+       Analysis*, volume 275 of Math. Appl., pages 51--67. Springer, Dordrecht,
+       Netherlands, 1994. `doi:10.1007/978-94-015-8330-5_4
+       `_.
+    .. [3] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
+       and Software*. PhD thesis, Department of Applied Mathematics, The Hong
+       Kong Polytechnic University, Hong Kong, China, 2022. URL:
+       https://theses.lib.polyu.edu.hk/handle/200/12294.
+
+    Examples
+    --------
+    To demonstrate how to use `minimize`, we first minimize the Rosenbrock
+    function implemented in `scipy.optimize` in an unconstrained setting.
+
+    .. testsetup::
+
+        import numpy as np
+        np.set_printoptions(precision=3, suppress=True)
+
+    >>> from cobyqa import minimize
+    >>> from scipy.optimize import rosen
+
+    To solve the problem using COBYQA, run:
+
+    >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
+    >>> res = minimize(rosen, x0)
+    >>> res.x
+    array([1., 1., 1., 1., 1.])
+
+    To see how bound and constraints are handled using `minimize`, we solve
+    Example 16.4 of [1]_, defined as
+
+    .. math::
+
+        \begin{aligned}
+            \min_{x \in \mathbb{R}^2}   & \quad (x_1 - 1)^2 + (x_2 - 2.5)^2\\
+            \text{s.t.}                 & \quad -x_1 + 2x_2 \le 2,\\
+                                        & \quad x_1 + 2x_2 \le 6,\\
+                                        & \quad x_1 - 2x_2 \le 2,\\
+                                        & \quad x_1 \ge 0,\\
+                                        & \quad x_2 \ge 0.
+        \end{aligned}
+
+    >>> import numpy as np
+    >>> from scipy.optimize import Bounds, LinearConstraint
+
+    Its objective function can be implemented as:
+
+    >>> def fun(x):
+    ...     return (x[0] - 1.0)**2 + (x[1] - 2.5)**2
+
+    This problem can be solved using `minimize` as:
+
+    >>> x0 = [2.0, 0.0]
+    >>> bounds = Bounds([0.0, 0.0], np.inf)
+    >>> constraints = LinearConstraint([
+    ...     [-1.0, 2.0],
+    ...     [1.0, 2.0],
+    ...     [1.0, -2.0],
+    ... ], -np.inf, [2.0, 6.0, 2.0])
+    >>> res = minimize(fun, x0, bounds=bounds, constraints=constraints)
+    >>> res.x
+    array([1.4, 1.7])
+
+    To see how nonlinear constraints are handled, we solve Problem (F) of [2]_,
+    defined as
+
+    .. math::
+
+        \begin{aligned}
+            \min_{x \in \mathbb{R}^2}   & \quad -x_1 - x_2\\
+            \text{s.t.}                 & \quad x_1^2 - x_2 \le 0,\\
+                                        & \quad x_1^2 + x_2^2 \le 1.
+        \end{aligned}
+
+    >>> from scipy.optimize import NonlinearConstraint
+
+    Its objective and constraint functions can be implemented as:
+
+    >>> def fun(x):
+    ...     return -x[0] - x[1]
+    >>>
+    >>> def cub(x):
+    ...     return [x[0]**2 - x[1], x[0]**2 + x[1]**2]
+
+    This problem can be solved using `minimize` as:
+
+    >>> x0 = [1.0, 1.0]
+    >>> constraints = NonlinearConstraint(cub, -np.inf, [0.0, 1.0])
+    >>> res = minimize(fun, x0, constraints=constraints)
+    >>> res.x
+    array([0.707, 0.707])
+
+    Finally, to see how to supply linear and nonlinear constraints
+    simultaneously, we solve Problem (G) of [2]_, defined as
+
+    .. math::
+
+        \begin{aligned}
+            \min_{x \in \mathbb{R}^3}   & \quad x_3\\
+            \text{s.t.}                 & \quad 5x_1 - x_2 + x_3 \ge 0,\\
+                                        & \quad -5x_1 - x_2 + x_3 \ge 0,\\
+                                        & \quad x_1^2 + x_2^2 + 4x_2 \le x_3.
+        \end{aligned}
+
+    Its objective and nonlinear constraint functions can be implemented as:
+
+    >>> def fun(x):
+    ...     return x[2]
+    >>>
+    >>> def cub(x):
+    ...     return x[0]**2 + x[1]**2 + 4.0*x[1] - x[2]
+
+    This problem can be solved using `minimize` as:
+
+    >>> x0 = [1.0, 1.0, 1.0]
+    >>> constraints = [
+    ...     LinearConstraint(
+    ...         [[5.0, -1.0, 1.0], [-5.0, -1.0, 1.0]],
+    ...         [0.0, 0.0],
+    ...         np.inf,
+    ...     ),
+    ...     NonlinearConstraint(cub, -np.inf, 0.0),
+    ... ]
+    >>> res = minimize(fun, x0, constraints=constraints)
+    >>> res.x
+    array([ 0., -3., -3.])
+    """
+    # Get basic options that are needed for the initialization.
+    if options is None:
+        options = {}
+    else:
+        options = dict(options)
+    verbose = options.get(Options.VERBOSE, DEFAULT_OPTIONS[Options.VERBOSE])
+    verbose = bool(verbose)
+    feasibility_tol = options.get(
+        Options.FEASIBILITY_TOL,
+        DEFAULT_OPTIONS[Options.FEASIBILITY_TOL],
+    )
+    feasibility_tol = float(feasibility_tol)
+    scale = options.get(Options.SCALE, DEFAULT_OPTIONS[Options.SCALE])
+    scale = bool(scale)
+    store_history = options.get(
+        Options.STORE_HISTORY,
+        DEFAULT_OPTIONS[Options.STORE_HISTORY],
+    )
+    store_history = bool(store_history)
+    if Options.HISTORY_SIZE in options and options[Options.HISTORY_SIZE] <= 0:
+        raise ValueError("The size of the history must be positive.")
+    history_size = options.get(
+        Options.HISTORY_SIZE,
+        DEFAULT_OPTIONS[Options.HISTORY_SIZE],
+    )
+    history_size = int(history_size)
+    if Options.FILTER_SIZE in options and options[Options.FILTER_SIZE] <= 0:
+        raise ValueError("The size of the filter must be positive.")
+    filter_size = options.get(
+        Options.FILTER_SIZE,
+        DEFAULT_OPTIONS[Options.FILTER_SIZE],
+    )
+    filter_size = int(filter_size)
+    debug = options.get(Options.DEBUG, DEFAULT_OPTIONS[Options.DEBUG])
+    debug = bool(debug)
+
+    # Initialize the objective function.
+    if not isinstance(args, tuple):
+        args = (args,)
+    obj = ObjectiveFunction(fun, verbose, debug, *args)
+
+    # Initialize the bound constraints.
+    if not hasattr(x0, "__len__"):
+        x0 = [x0]
+    n_orig = len(x0)
+    bounds = BoundConstraints(_get_bounds(bounds, n_orig))
+
+    # Initialize the constraints.
+    linear_constraints, nonlinear_constraints = _get_constraints(constraints)
+    linear = LinearConstraints(linear_constraints, n_orig, debug)
+    nonlinear = NonlinearConstraints(nonlinear_constraints, verbose, debug)
+
+    # Initialize the problem (and remove the fixed variables).
+    pb = Problem(
+        obj,
+        x0,
+        bounds,
+        linear,
+        nonlinear,
+        callback,
+        feasibility_tol,
+        scale,
+        store_history,
+        history_size,
+        filter_size,
+        debug,
+    )
+
+    # Set the default options.
+    _set_default_options(options, pb.n)
+    constants = _set_default_constants(**kwargs)
+
+    # Initialize the models and skip the computations whenever possible.
+    if not pb.bounds.is_feasible:
+        # The bound constraints are infeasible.
+        return _build_result(
+            pb,
+            0.0,
+            False,
+            ExitStatus.INFEASIBLE_ERROR,
+            0,
+            options,
+        )
+    elif pb.n == 0:
+        # All variables are fixed by the bound constraints.
+        return _build_result(
+            pb,
+            0.0,
+            True,
+            ExitStatus.FIXED_SUCCESS,
+            0,
+            options,
+        )
+    if verbose:
+        print("Starting the optimization procedure.")
+        print(f"Initial trust-region radius: {options[Options.RHOBEG]}.")
+        print(f"Final trust-region radius: {options[Options.RHOEND]}.")
+        print(
+            f"Maximum number of function evaluations: "
+            f"{options[Options.MAX_EVAL]}."
+        )
+        print(f"Maximum number of iterations: {options[Options.MAX_ITER]}.")
+        print()
+    try:
+        framework = TrustRegion(pb, options, constants)
+    except TargetSuccess:
+        # The target on the objective function value has been reached
+        return _build_result(
+            pb,
+            0.0,
+            True,
+            ExitStatus.TARGET_SUCCESS,
+            0,
+            options,
+        )
+    except CallbackSuccess:
+        # The callback raised a StopIteration exception.
+        return _build_result(
+            pb,
+            0.0,
+            True,
+            ExitStatus.CALLBACK_SUCCESS,
+            0,
+            options,
+        )
+    except FeasibleSuccess:
+        # The feasibility problem has been solved successfully.
+        return _build_result(
+            pb,
+            0.0,
+            True,
+            ExitStatus.FEASIBLE_SUCCESS,
+            0,
+            options,
+        )
+    except MaxEvalError:
+        # The maximum number of function evaluations has been exceeded.
+        return _build_result(
+            pb,
+            0.0,
+            False,
+            ExitStatus.MAX_ITER_WARNING,
+            0,
+            options,
+        )
+    except np.linalg.LinAlgError:
+        # The construction of the initial interpolation set failed.
+        return _build_result(
+            pb,
+            0.0,
+            False,
+            ExitStatus.LINALG_ERROR,
+            0,
+            options,
+        )
+
+    # Start the optimization procedure.
+    success = False
+    n_iter = 0
+    k_new = None
+    n_short_steps = 0
+    n_very_short_steps = 0
+    n_alt_models = 0
+    while True:
+        # Stop the optimization procedure if the maximum number of iterations
+        # has been exceeded. We do not write the main loop as a for loop
+        # because we want to access the number of iterations outside the loop.
+        if n_iter >= options[Options.MAX_ITER]:
+            status = ExitStatus.MAX_ITER_WARNING
+            break
+        n_iter += 1
+
+        # Update the point around which the quadratic models are built.
+        if (
+            np.linalg.norm(
+                framework.x_best - framework.models.interpolation.x_base
+            )
+            >= constants[Constants.LARGE_SHIFT_FACTOR] * framework.radius
+        ):
+            framework.shift_x_base(options)
+
+        # Evaluate the trial step.
+        radius_save = framework.radius
+        normal_step, tangential_step = framework.get_trust_region_step(options)
+        step = normal_step + tangential_step
+        s_norm = np.linalg.norm(step)
+
+        # If the trial step is too short, we do not attempt to evaluate the
+        # objective and constraint functions. Instead, we reduce the
+        # trust-region radius and check whether the resolution should be
+        # enhanced and whether the geometry of the interpolation set should be
+        # improved. Otherwise, we entertain a classical iteration. The
+        # criterion for performing an exceptional jump is taken from NEWUOA.
+        if (
+            s_norm
+            <= constants[Constants.SHORT_STEP_THRESHOLD] * framework.resolution
+        ):
+            framework.radius *= constants[Constants.DECREASE_RESOLUTION_FACTOR]
+            if radius_save > framework.resolution:
+                n_short_steps = 0
+                n_very_short_steps = 0
+            else:
+                n_short_steps += 1
+                n_very_short_steps += 1
+                if s_norm > 0.1 * framework.resolution:
+                    n_very_short_steps = 0
+            enhance_resolution = n_short_steps >= 5 or n_very_short_steps >= 3
+            if enhance_resolution:
+                n_short_steps = 0
+                n_very_short_steps = 0
+                improve_geometry = False
+            else:
+                try:
+                    k_new, dist_new = framework.get_index_to_remove()
+                except np.linalg.LinAlgError:
+                    status = ExitStatus.LINALG_ERROR
+                    break
+                improve_geometry = dist_new > max(
+                    framework.radius,
+                    constants[Constants.RESOLUTION_FACTOR]
+                    * framework.resolution,
+                )
+        else:
+            # Increase the penalty parameter if necessary.
+            same_best_point = framework.increase_penalty(step)
+            if same_best_point:
+                # Evaluate the objective and constraint functions.
+                try:
+                    fun_val, cub_val, ceq_val = _eval(
+                        pb,
+                        framework,
+                        step,
+                        options,
+                    )
+                except TargetSuccess:
+                    status = ExitStatus.TARGET_SUCCESS
+                    success = True
+                    break
+                except FeasibleSuccess:
+                    status = ExitStatus.FEASIBLE_SUCCESS
+                    success = True
+                    break
+                except CallbackSuccess:
+                    status = ExitStatus.CALLBACK_SUCCESS
+                    success = True
+                    break
+                except MaxEvalError:
+                    status = ExitStatus.MAX_EVAL_WARNING
+                    break
+
+                # Perform a second-order correction step if necessary.
+                merit_old = framework.merit(
+                    framework.x_best,
+                    framework.fun_best,
+                    framework.cub_best,
+                    framework.ceq_best,
+                )
+                merit_new = framework.merit(
+                    framework.x_best + step, fun_val, cub_val, ceq_val
+                )
+                if (
+                    pb.type == "nonlinearly constrained"
+                    and merit_new > merit_old
+                    and np.linalg.norm(normal_step)
+                    > constants[Constants.BYRD_OMOJOKUN_FACTOR] ** 2.0
+                    * framework.radius
+                ):
+                    soc_step = framework.get_second_order_correction_step(
+                        step, options
+                    )
+                    if np.linalg.norm(soc_step) > 0.0:
+                        step += soc_step
+
+                        # Evaluate the objective and constraint functions.
+                        try:
+                            fun_val, cub_val, ceq_val = _eval(
+                                pb,
+                                framework,
+                                step,
+                                options,
+                            )
+                        except TargetSuccess:
+                            status = ExitStatus.TARGET_SUCCESS
+                            success = True
+                            break
+                        except FeasibleSuccess:
+                            status = ExitStatus.FEASIBLE_SUCCESS
+                            success = True
+                            break
+                        except CallbackSuccess:
+                            status = ExitStatus.CALLBACK_SUCCESS
+                            success = True
+                            break
+                        except MaxEvalError:
+                            status = ExitStatus.MAX_EVAL_WARNING
+                            break
+
+                # Calculate the reduction ratio.
+                ratio = framework.get_reduction_ratio(
+                    step,
+                    fun_val,
+                    cub_val,
+                    ceq_val,
+                )
+
+                # Choose an interpolation point to remove.
+                try:
+                    k_new = framework.get_index_to_remove(
+                        framework.x_best + step
+                    )[0]
+                except np.linalg.LinAlgError:
+                    status = ExitStatus.LINALG_ERROR
+                    break
+
+                # Update the interpolation set.
+                try:
+                    ill_conditioned = framework.models.update_interpolation(
+                        k_new, framework.x_best + step, fun_val, cub_val,
+                        ceq_val
+                    )
+                except np.linalg.LinAlgError:
+                    status = ExitStatus.LINALG_ERROR
+                    break
+                framework.set_best_index()
+
+                # Update the trust-region radius.
+                framework.update_radius(step, ratio)
+
+                # Attempt to replace the models by the alternative ones.
+                if framework.radius <= framework.resolution:
+                    if ratio >= constants[Constants.VERY_LOW_RATIO]:
+                        n_alt_models = 0
+                    else:
+                        n_alt_models += 1
+                        grad = framework.models.fun_grad(framework.x_best)
+                        try:
+                            grad_alt = framework.models.fun_alt_grad(
+                                framework.x_best
+                            )
+                        except np.linalg.LinAlgError:
+                            status = ExitStatus.LINALG_ERROR
+                            break
+                        if np.linalg.norm(grad) < constants[
+                            Constants.LARGE_GRADIENT_FACTOR
+                        ] * np.linalg.norm(grad_alt):
+                            n_alt_models = 0
+                        if n_alt_models >= 3:
+                            try:
+                                framework.models.reset_models()
+                            except np.linalg.LinAlgError:
+                                status = ExitStatus.LINALG_ERROR
+                                break
+                            n_alt_models = 0
+
+                # Update the Lagrange multipliers.
+                framework.set_multipliers(framework.x_best + step)
+
+                # Check whether the resolution should be enhanced.
+                try:
+                    k_new, dist_new = framework.get_index_to_remove()
+                except np.linalg.LinAlgError:
+                    status = ExitStatus.LINALG_ERROR
+                    break
+                improve_geometry = (
+                    ill_conditioned
+                    or ratio <= constants[Constants.LOW_RATIO]
+                    and dist_new
+                    > max(
+                        framework.radius,
+                        constants[Constants.RESOLUTION_FACTOR]
+                        * framework.resolution,
+                    )
+                )
+                enhance_resolution = (
+                    radius_save <= framework.resolution
+                    and ratio <= constants[Constants.LOW_RATIO]
+                    and not improve_geometry
+                )
+            else:
+                # When increasing the penalty parameter, the best point so far
+                # may change. In this case, we restart the iteration.
+                enhance_resolution = False
+                improve_geometry = False
+
+        # Reduce the resolution if necessary.
+        if enhance_resolution:
+            if framework.resolution <= options[Options.RHOEND]:
+                success = True
+                status = ExitStatus.RADIUS_SUCCESS
+                break
+            framework.enhance_resolution(options)
+            framework.decrease_penalty()
+
+            if verbose:
+                maxcv_val = pb.maxcv(
+                    framework.x_best, framework.cub_best, framework.ceq_best
+                )
+                _print_step(
+                    f"New trust-region radius: {framework.resolution}",
+                    pb,
+                    pb.build_x(framework.x_best),
+                    framework.fun_best,
+                    maxcv_val,
+                    pb.n_eval,
+                    n_iter,
+                )
+                print()
+
+        # Improve the geometry of the interpolation set if necessary.
+        if improve_geometry:
+            try:
+                step = framework.get_geometry_step(k_new, options)
+            except np.linalg.LinAlgError:
+                status = ExitStatus.LINALG_ERROR
+                break
+
+            # Evaluate the objective and constraint functions.
+            try:
+                fun_val, cub_val, ceq_val = _eval(pb, framework, step, options)
+            except TargetSuccess:
+                status = ExitStatus.TARGET_SUCCESS
+                success = True
+                break
+            except FeasibleSuccess:
+                status = ExitStatus.FEASIBLE_SUCCESS
+                success = True
+                break
+            except CallbackSuccess:
+                status = ExitStatus.CALLBACK_SUCCESS
+                success = True
+                break
+            except MaxEvalError:
+                status = ExitStatus.MAX_EVAL_WARNING
+                break
+
+            # Update the interpolation set.
+            try:
+                framework.models.update_interpolation(
+                    k_new,
+                    framework.x_best + step,
+                    fun_val,
+                    cub_val,
+                    ceq_val,
+                )
+            except np.linalg.LinAlgError:
+                status = ExitStatus.LINALG_ERROR
+                break
+            framework.set_best_index()
+
+    return _build_result(
+        pb,
+        framework.penalty,
+        success,
+        status,
+        n_iter,
+        options,
+    )
+
+
+def _get_bounds(bounds, n):
+    """
+    Uniformize the bounds.
+    """
+    if bounds is None:
+        return Bounds(np.full(n, -np.inf), np.full(n, np.inf))
+    elif isinstance(bounds, Bounds):
+        if bounds.lb.shape != (n,) or bounds.ub.shape != (n,):
+            raise ValueError(f"The bounds must have {n} elements.")
+        return Bounds(bounds.lb, bounds.ub)
+    elif hasattr(bounds, "__len__"):
+        bounds = np.asarray(bounds)
+        if bounds.shape != (n, 2):
+            raise ValueError(
+                "The shape of the bounds is not compatible with "
+                "the number of variables."
+            )
+        return Bounds(bounds[:, 0], bounds[:, 1])
+    else:
+        raise TypeError(
+            "The bounds must be an instance of "
+            "scipy.optimize.Bounds or an array-like object."
+        )
+
+
+def _get_constraints(constraints):
+    """
+    Extract the linear and nonlinear constraints.
+    """
+    if isinstance(constraints, dict) or not hasattr(constraints, "__len__"):
+        constraints = (constraints,)
+
+    # Extract the linear and nonlinear constraints.
+    linear_constraints = []
+    nonlinear_constraints = []
+    for constraint in constraints:
+        if isinstance(constraint, LinearConstraint):
+            lb = exact_1d_array(
+                constraint.lb,
+                "The lower bound of the linear constraints must be a vector.",
+            )
+            ub = exact_1d_array(
+                constraint.ub,
+                "The upper bound of the linear constraints must be a vector.",
+            )
+            linear_constraints.append(
+                LinearConstraint(
+                    constraint.A,
+                    *np.broadcast_arrays(lb, ub),
+                )
+            )
+        elif isinstance(constraint, NonlinearConstraint):
+            lb = exact_1d_array(
+                constraint.lb,
+                "The lower bound of the "
+                "nonlinear constraints must be a "
+                "vector.",
+            )
+            ub = exact_1d_array(
+                constraint.ub,
+                "The upper bound of the "
+                "nonlinear constraints must be a "
+                "vector.",
+            )
+            nonlinear_constraints.append(
+                NonlinearConstraint(
+                    constraint.fun,
+                    *np.broadcast_arrays(lb, ub),
+                )
+            )
+        elif isinstance(constraint, dict):
+            if "type" not in constraint or constraint["type"] not in (
+                "eq",
+                "ineq",
+            ):
+                raise ValueError('The constraint type must be "eq" or "ineq".')
+            if "fun" not in constraint or not callable(constraint["fun"]):
+                raise ValueError("The constraint function must be callable.")
+            nonlinear_constraints.append(
+                {
+                    "fun": constraint["fun"],
+                    "type": constraint["type"],
+                    "args": constraint.get("args", ()),
+                }
+            )
+        else:
+            raise TypeError(
+                "The constraints must be instances of "
+                "scipy.optimize.LinearConstraint, "
+                "scipy.optimize.NonlinearConstraint, or dict."
+            )
+    return linear_constraints, nonlinear_constraints
+
+
+def _set_default_options(options, n):
+    """
+    Set the default options.
+    """
+    if Options.RHOBEG in options and options[Options.RHOBEG] <= 0.0:
+        raise ValueError("The initial trust-region radius must be positive.")
+    if Options.RHOEND in options and options[Options.RHOEND] < 0.0:
+        raise ValueError("The final trust-region radius must be nonnegative.")
+    if Options.RHOBEG in options and Options.RHOEND in options:
+        if options[Options.RHOBEG] < options[Options.RHOEND]:
+            raise ValueError(
+                "The initial trust-region radius must be greater "
+                "than or equal to the final trust-region radius."
+            )
+    elif Options.RHOBEG in options:
+        options[Options.RHOEND.value] = np.min(
+            [
+                DEFAULT_OPTIONS[Options.RHOEND],
+                options[Options.RHOBEG],
+            ]
+        )
+    elif Options.RHOEND in options:
+        options[Options.RHOBEG.value] = np.max(
+            [
+                DEFAULT_OPTIONS[Options.RHOBEG],
+                options[Options.RHOEND],
+            ]
+        )
+    else:
+        options[Options.RHOBEG.value] = DEFAULT_OPTIONS[Options.RHOBEG]
+        options[Options.RHOEND.value] = DEFAULT_OPTIONS[Options.RHOEND]
+    options[Options.RHOBEG.value] = float(options[Options.RHOBEG])
+    options[Options.RHOEND.value] = float(options[Options.RHOEND])
+    if Options.NPT in options and options[Options.NPT] <= 0:
+        raise ValueError("The number of interpolation points must be "
+                         "positive.")
+    if (
+        Options.NPT in options
+        and options[Options.NPT] > ((n + 1) * (n + 2)) // 2
+    ):
+        raise ValueError(
+            f"The number of interpolation points must be at most "
+            f"{((n + 1) * (n + 2)) // 2}."
+        )
+    options.setdefault(Options.NPT.value, DEFAULT_OPTIONS[Options.NPT](n))
+    options[Options.NPT.value] = int(options[Options.NPT])
+    if Options.MAX_EVAL in options and options[Options.MAX_EVAL] <= 0:
+        raise ValueError(
+            "The maximum number of function evaluations must be positive."
+        )
+    options.setdefault(
+        Options.MAX_EVAL.value,
+        np.max(
+            [
+                DEFAULT_OPTIONS[Options.MAX_EVAL](n),
+                options[Options.NPT] + 1,
+            ]
+        ),
+    )
+    options[Options.MAX_EVAL.value] = int(options[Options.MAX_EVAL])
+    if Options.MAX_ITER in options and options[Options.MAX_ITER] <= 0:
+        raise ValueError("The maximum number of iterations must be positive.")
+    options.setdefault(
+        Options.MAX_ITER.value,
+        DEFAULT_OPTIONS[Options.MAX_ITER](n),
+    )
+    options[Options.MAX_ITER.value] = int(options[Options.MAX_ITER])
+    options.setdefault(Options.TARGET.value, DEFAULT_OPTIONS[Options.TARGET])
+    options[Options.TARGET.value] = float(options[Options.TARGET])
+    options.setdefault(
+        Options.FEASIBILITY_TOL.value,
+        DEFAULT_OPTIONS[Options.FEASIBILITY_TOL],
+    )
+    options[Options.FEASIBILITY_TOL.value] = float(
+        options[Options.FEASIBILITY_TOL]
+    )
+    options.setdefault(Options.VERBOSE.value, DEFAULT_OPTIONS[Options.VERBOSE])
+    options[Options.VERBOSE.value] = bool(options[Options.VERBOSE])
+    options.setdefault(Options.SCALE.value, DEFAULT_OPTIONS[Options.SCALE])
+    options[Options.SCALE.value] = bool(options[Options.SCALE])
+    options.setdefault(
+        Options.FILTER_SIZE.value,
+        DEFAULT_OPTIONS[Options.FILTER_SIZE],
+    )
+    options[Options.FILTER_SIZE.value] = int(options[Options.FILTER_SIZE])
+    options.setdefault(
+        Options.STORE_HISTORY.value,
+        DEFAULT_OPTIONS[Options.STORE_HISTORY],
+    )
+    options[Options.STORE_HISTORY.value] = bool(options[Options.STORE_HISTORY])
+    options.setdefault(
+        Options.HISTORY_SIZE.value,
+        DEFAULT_OPTIONS[Options.HISTORY_SIZE],
+    )
+    options[Options.HISTORY_SIZE.value] = int(options[Options.HISTORY_SIZE])
+    options.setdefault(Options.DEBUG.value, DEFAULT_OPTIONS[Options.DEBUG])
+    options[Options.DEBUG.value] = bool(options[Options.DEBUG])
+
+    # Check whether they are any unknown options.
+    for key in options:
+        if key not in Options.__members__.values():
+            warnings.warn(f"Unknown option: {key}.", RuntimeWarning, 3)
+
+
+def _set_default_constants(**kwargs):
+    """
+    Set the default constants.
+    """
+    constants = dict(kwargs)
+    constants.setdefault(
+        Constants.DECREASE_RADIUS_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_FACTOR],
+    )
+    constants[Constants.DECREASE_RADIUS_FACTOR.value] = float(
+        constants[Constants.DECREASE_RADIUS_FACTOR]
+    )
+    if (
+        constants[Constants.DECREASE_RADIUS_FACTOR] <= 0.0
+        or constants[Constants.DECREASE_RADIUS_FACTOR] >= 1.0
+    ):
+        raise ValueError(
+            "The constant decrease_radius_factor must be in the interval "
+            "(0, 1)."
+        )
+    constants.setdefault(
+        Constants.INCREASE_RADIUS_THRESHOLD.value,
+        DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_THRESHOLD],
+    )
+    constants[Constants.INCREASE_RADIUS_THRESHOLD.value] = float(
+        constants[Constants.INCREASE_RADIUS_THRESHOLD]
+    )
+    if constants[Constants.INCREASE_RADIUS_THRESHOLD] <= 1.0:
+        raise ValueError(
+            "The constant increase_radius_threshold must be greater than 1."
+        )
+    if (
+        Constants.INCREASE_RADIUS_FACTOR in constants
+        and constants[Constants.INCREASE_RADIUS_FACTOR] <= 1.0
+    ):
+        raise ValueError(
+            "The constant increase_radius_factor must be greater than 1."
+        )
+    if (
+        Constants.DECREASE_RADIUS_THRESHOLD in constants
+        and constants[Constants.DECREASE_RADIUS_THRESHOLD] <= 1.0
+    ):
+        raise ValueError(
+            "The constant decrease_radius_threshold must be greater than 1."
+        )
+    if (
+        Constants.INCREASE_RADIUS_FACTOR in constants
+        and Constants.DECREASE_RADIUS_THRESHOLD in constants
+    ):
+        if (
+            constants[Constants.DECREASE_RADIUS_THRESHOLD]
+            >= constants[Constants.INCREASE_RADIUS_FACTOR]
+        ):
+            raise ValueError(
+                "The constant decrease_radius_threshold must be "
+                "less than increase_radius_factor."
+            )
+    elif Constants.INCREASE_RADIUS_FACTOR in constants:
+        constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = np.min(
+            [
+                DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD],
+                0.5 * (1.0 + constants[Constants.INCREASE_RADIUS_FACTOR]),
+            ]
+        )
+    elif Constants.DECREASE_RADIUS_THRESHOLD in constants:
+        constants[Constants.INCREASE_RADIUS_FACTOR.value] = np.max(
+            [
+                DEFAULT_CONSTANTS[Constants.INCREASE_RADIUS_FACTOR],
+                2.0 * constants[Constants.DECREASE_RADIUS_THRESHOLD],
+            ]
+        )
+    else:
+        constants[Constants.INCREASE_RADIUS_FACTOR.value] = DEFAULT_CONSTANTS[
+            Constants.INCREASE_RADIUS_FACTOR
+        ]
+        constants[Constants.DECREASE_RADIUS_THRESHOLD.value] = (
+            DEFAULT_CONSTANTS[Constants.DECREASE_RADIUS_THRESHOLD])
+    constants.setdefault(
+        Constants.DECREASE_RESOLUTION_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.DECREASE_RESOLUTION_FACTOR],
+    )
+    constants[Constants.DECREASE_RESOLUTION_FACTOR.value] = float(
+        constants[Constants.DECREASE_RESOLUTION_FACTOR]
+    )
+    if (
+        constants[Constants.DECREASE_RESOLUTION_FACTOR] <= 0.0
+        or constants[Constants.DECREASE_RESOLUTION_FACTOR] >= 1.0
+    ):
+        raise ValueError(
+            "The constant decrease_resolution_factor must be in the interval "
+            "(0, 1)."
+        )
+    if (
+        Constants.LARGE_RESOLUTION_THRESHOLD in constants
+        and constants[Constants.LARGE_RESOLUTION_THRESHOLD] <= 1.0
+    ):
+        raise ValueError(
+            "The constant large_resolution_threshold must be greater than 1."
+        )
+    if (
+        Constants.MODERATE_RESOLUTION_THRESHOLD in constants
+        and constants[Constants.MODERATE_RESOLUTION_THRESHOLD] <= 1.0
+    ):
+        raise ValueError(
+            "The constant moderate_resolution_threshold must be greater than "
+            "1."
+        )
+    if (
+        Constants.LARGE_RESOLUTION_THRESHOLD in constants
+        and Constants.MODERATE_RESOLUTION_THRESHOLD in constants
+    ):
+        if (
+            constants[Constants.MODERATE_RESOLUTION_THRESHOLD]
+            > constants[Constants.LARGE_RESOLUTION_THRESHOLD]
+        ):
+            raise ValueError(
+                "The constant moderate_resolution_threshold "
+                "must be at most large_resolution_threshold."
+            )
+    elif Constants.LARGE_RESOLUTION_THRESHOLD in constants:
+        constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = np.min(
+            [
+                DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD],
+                constants[Constants.LARGE_RESOLUTION_THRESHOLD],
+            ]
+        )
+    elif Constants.MODERATE_RESOLUTION_THRESHOLD in constants:
+        constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = np.max(
+            [
+                DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD],
+                constants[Constants.MODERATE_RESOLUTION_THRESHOLD],
+            ]
+        )
+    else:
+        constants[Constants.LARGE_RESOLUTION_THRESHOLD.value] = (
+            DEFAULT_CONSTANTS[Constants.LARGE_RESOLUTION_THRESHOLD]
+        )
+        constants[Constants.MODERATE_RESOLUTION_THRESHOLD.value] = (
+            DEFAULT_CONSTANTS[Constants.MODERATE_RESOLUTION_THRESHOLD]
+        )
+    if Constants.LOW_RATIO in constants and (
+        constants[Constants.LOW_RATIO] <= 0.0
+        or constants[Constants.LOW_RATIO] >= 1.0
+    ):
+        raise ValueError(
+            "The constant low_ratio must be in the interval (0, 1)."
+        )
+    if Constants.HIGH_RATIO in constants and (
+        constants[Constants.HIGH_RATIO] <= 0.0
+        or constants[Constants.HIGH_RATIO] >= 1.0
+    ):
+        raise ValueError(
+            "The constant high_ratio must be in the interval (0, 1)."
+        )
+    if Constants.LOW_RATIO in constants and Constants.HIGH_RATIO in constants:
+        if constants[Constants.LOW_RATIO] > constants[Constants.HIGH_RATIO]:
+            raise ValueError(
+                "The constant low_ratio must be at most high_ratio."
+            )
+    elif Constants.LOW_RATIO in constants:
+        constants[Constants.HIGH_RATIO.value] = np.max(
+            [
+                DEFAULT_CONSTANTS[Constants.HIGH_RATIO],
+                constants[Constants.LOW_RATIO],
+            ]
+        )
+    elif Constants.HIGH_RATIO in constants:
+        constants[Constants.LOW_RATIO.value] = np.min(
+            [
+                DEFAULT_CONSTANTS[Constants.LOW_RATIO],
+                constants[Constants.HIGH_RATIO],
+            ]
+        )
+    else:
+        constants[Constants.LOW_RATIO.value] = DEFAULT_CONSTANTS[
+            Constants.LOW_RATIO
+        ]
+        constants[Constants.HIGH_RATIO.value] = DEFAULT_CONSTANTS[
+            Constants.HIGH_RATIO
+        ]
+    constants.setdefault(
+        Constants.VERY_LOW_RATIO.value,
+        DEFAULT_CONSTANTS[Constants.VERY_LOW_RATIO],
+    )
+    constants[Constants.VERY_LOW_RATIO.value] = float(
+        constants[Constants.VERY_LOW_RATIO]
+    )
+    if (
+        constants[Constants.VERY_LOW_RATIO] <= 0.0
+        or constants[Constants.VERY_LOW_RATIO] >= 1.0
+    ):
+        raise ValueError(
+            "The constant very_low_ratio must be in the interval (0, 1)."
+        )
+    if (
+        Constants.PENALTY_INCREASE_THRESHOLD in constants
+        and constants[Constants.PENALTY_INCREASE_THRESHOLD] < 1.0
+    ):
+        raise ValueError(
+            "The constant penalty_increase_threshold must be "
+            "greater than or equal to 1."
+        )
+    if (
+        Constants.PENALTY_INCREASE_FACTOR in constants
+        and constants[Constants.PENALTY_INCREASE_FACTOR] <= 1.0
+    ):
+        raise ValueError(
+            "The constant penalty_increase_factor must be greater than 1."
+        )
+    if (
+        Constants.PENALTY_INCREASE_THRESHOLD in constants
+        and Constants.PENALTY_INCREASE_FACTOR in constants
+    ):
+        if (
+            constants[Constants.PENALTY_INCREASE_FACTOR]
+            < constants[Constants.PENALTY_INCREASE_THRESHOLD]
+        ):
+            raise ValueError(
+                "The constant penalty_increase_factor must be "
+                "greater than or equal to "
+                "penalty_increase_threshold."
+            )
+    elif Constants.PENALTY_INCREASE_THRESHOLD in constants:
+        constants[Constants.PENALTY_INCREASE_FACTOR.value] = np.max(
+            [
+                DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_FACTOR],
+                constants[Constants.PENALTY_INCREASE_THRESHOLD],
+            ]
+        )
+    elif Constants.PENALTY_INCREASE_FACTOR in constants:
+        constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = np.min(
+            [
+                DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD],
+                constants[Constants.PENALTY_INCREASE_FACTOR],
+            ]
+        )
+    else:
+        constants[Constants.PENALTY_INCREASE_THRESHOLD.value] = (
+            DEFAULT_CONSTANTS[Constants.PENALTY_INCREASE_THRESHOLD]
+        )
+        constants[Constants.PENALTY_INCREASE_FACTOR.value] = DEFAULT_CONSTANTS[
+            Constants.PENALTY_INCREASE_FACTOR
+        ]
+    constants.setdefault(
+        Constants.SHORT_STEP_THRESHOLD.value,
+        DEFAULT_CONSTANTS[Constants.SHORT_STEP_THRESHOLD],
+    )
+    constants[Constants.SHORT_STEP_THRESHOLD.value] = float(
+        constants[Constants.SHORT_STEP_THRESHOLD]
+    )
+    if (
+        constants[Constants.SHORT_STEP_THRESHOLD] <= 0.0
+        or constants[Constants.SHORT_STEP_THRESHOLD] >= 1.0
+    ):
+        raise ValueError(
+            "The constant short_step_threshold must be in the interval (0, 1)."
+        )
+    constants.setdefault(
+        Constants.LOW_RADIUS_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.LOW_RADIUS_FACTOR],
+    )
+    constants[Constants.LOW_RADIUS_FACTOR.value] = float(
+        constants[Constants.LOW_RADIUS_FACTOR]
+    )
+    if (
+        constants[Constants.LOW_RADIUS_FACTOR] <= 0.0
+        or constants[Constants.LOW_RADIUS_FACTOR] >= 1.0
+    ):
+        raise ValueError(
+            "The constant low_radius_factor must be in the interval (0, 1)."
+        )
+    constants.setdefault(
+        Constants.BYRD_OMOJOKUN_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.BYRD_OMOJOKUN_FACTOR],
+    )
+    constants[Constants.BYRD_OMOJOKUN_FACTOR.value] = float(
+        constants[Constants.BYRD_OMOJOKUN_FACTOR]
+    )
+    if (
+        constants[Constants.BYRD_OMOJOKUN_FACTOR] <= 0.0
+        or constants[Constants.BYRD_OMOJOKUN_FACTOR] >= 1.0
+    ):
+        raise ValueError(
+            "The constant byrd_omojokun_factor must be in the interval (0, 1)."
+        )
+    constants.setdefault(
+        Constants.THRESHOLD_RATIO_CONSTRAINTS.value,
+        DEFAULT_CONSTANTS[Constants.THRESHOLD_RATIO_CONSTRAINTS],
+    )
+    constants[Constants.THRESHOLD_RATIO_CONSTRAINTS.value] = float(
+        constants[Constants.THRESHOLD_RATIO_CONSTRAINTS]
+    )
+    if constants[Constants.THRESHOLD_RATIO_CONSTRAINTS] <= 1.0:
+        raise ValueError(
+            "The constant threshold_ratio_constraints must be greater than 1."
+        )
+    constants.setdefault(
+        Constants.LARGE_SHIFT_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.LARGE_SHIFT_FACTOR],
+    )
+    constants[Constants.LARGE_SHIFT_FACTOR.value] = float(
+        constants[Constants.LARGE_SHIFT_FACTOR]
+    )
+    if constants[Constants.LARGE_SHIFT_FACTOR] < 0.0:
+        raise ValueError("The constant large_shift_factor must be "
+                         "nonnegative.")
+    constants.setdefault(
+        Constants.LARGE_GRADIENT_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.LARGE_GRADIENT_FACTOR],
+    )
+    constants[Constants.LARGE_GRADIENT_FACTOR.value] = float(
+        constants[Constants.LARGE_GRADIENT_FACTOR]
+    )
+    if constants[Constants.LARGE_GRADIENT_FACTOR] <= 1.0:
+        raise ValueError(
+            "The constant large_gradient_factor must be greater than 1."
+        )
+    constants.setdefault(
+        Constants.RESOLUTION_FACTOR.value,
+        DEFAULT_CONSTANTS[Constants.RESOLUTION_FACTOR],
+    )
+    constants[Constants.RESOLUTION_FACTOR.value] = float(
+        constants[Constants.RESOLUTION_FACTOR]
+    )
+    if constants[Constants.RESOLUTION_FACTOR] <= 1.0:
+        raise ValueError(
+            "The constant resolution_factor must be greater than 1."
+        )
+    constants.setdefault(
+        Constants.IMPROVE_TCG.value,
+        DEFAULT_CONSTANTS[Constants.IMPROVE_TCG],
+    )
+    constants[Constants.IMPROVE_TCG.value] = bool(
+        constants[Constants.IMPROVE_TCG]
+    )
+
+    # Check whether they are any unknown options.
+    for key in kwargs:
+        if key not in Constants.__members__.values():
+            warnings.warn(f"Unknown constant: {key}.", RuntimeWarning, 3)
+    return constants
+
+
+def _eval(pb, framework, step, options):
+    """
+    Evaluate the objective and constraint functions.
+    """
+    if pb.n_eval >= options[Options.MAX_EVAL]:
+        raise MaxEvalError
+    x_eval = framework.x_best + step
+    fun_val, cub_val, ceq_val = pb(x_eval, framework.penalty)
+    r_val = pb.maxcv(x_eval, cub_val, ceq_val)
+    if (
+        fun_val <= options[Options.TARGET]
+        and r_val <= options[Options.FEASIBILITY_TOL]
+    ):
+        raise TargetSuccess
+    if pb.is_feasibility and r_val <= options[Options.FEASIBILITY_TOL]:
+        raise FeasibleSuccess
+    return fun_val, cub_val, ceq_val
+
+
+def _build_result(pb, penalty, success, status, n_iter, options):
+    """
+    Build the result of the optimization process.
+    """
+    # Build the result.
+    x, fun, maxcv = pb.best_eval(penalty)
+    success = success and np.isfinite(fun) and np.isfinite(maxcv)
+    if status not in [ExitStatus.TARGET_SUCCESS, ExitStatus.FEASIBLE_SUCCESS]:
+        success = success and maxcv <= options[Options.FEASIBILITY_TOL]
+    result = OptimizeResult()
+    result.message = {
+        ExitStatus.RADIUS_SUCCESS: "The lower bound for the trust-region "
+                                   "radius has been reached",
+        ExitStatus.TARGET_SUCCESS: "The target objective function value has "
+                                   "been reached",
+        ExitStatus.FIXED_SUCCESS: "All variables are fixed by the bound "
+                                  "constraints",
+        ExitStatus.CALLBACK_SUCCESS: "The callback requested to stop the "
+                                     "optimization procedure",
+        ExitStatus.FEASIBLE_SUCCESS: "The feasibility problem received has "
+                                     "been solved successfully",
+        ExitStatus.MAX_EVAL_WARNING: "The maximum number of function "
+                                     "evaluations has been exceeded",
+        ExitStatus.MAX_ITER_WARNING: "The maximum number of iterations has "
+                                     "been exceeded",
+        ExitStatus.INFEASIBLE_ERROR: "The bound constraints are infeasible",
+        ExitStatus.LINALG_ERROR: "A linear algebra error occurred",
+    }.get(status, "Unknown exit status")
+    result.success = success
+    result.status = status.value
+    result.x = pb.build_x(x)
+    result.fun = fun
+    result.maxcv = maxcv
+    result.nfev = pb.n_eval
+    result.nit = n_iter
+    if options[Options.STORE_HISTORY]:
+        result.fun_history = pb.fun_history
+        result.maxcv_history = pb.maxcv_history
+
+    # Print the result if requested.
+    if options[Options.VERBOSE]:
+        _print_step(
+            result.message,
+            pb,
+            result.x,
+            result.fun,
+            result.maxcv,
+            result.nfev,
+            result.nit,
+        )
+    return result
+
+
+def _print_step(message, pb, x, fun_val, r_val, n_eval, n_iter):
+    """
+    Print information about the current state of the optimization process.
+    """
+    print()
+    print(f"{message}.")
+    print(f"Number of function evaluations: {n_eval}.")
+    print(f"Number of iterations: {n_iter}.")
+    if not pb.is_feasibility:
+        print(f"Least value of {pb.fun_name}: {fun_val}.")
+    print(f"Maximum constraint violation: {r_val}.")
+    with np.printoptions(**PRINT_OPTIONS):
+        print(f"Corresponding point: {x}.")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/models.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..4891b074bfd6dd3f7d43fa95b0b845a764cac114
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/models.py
@@ -0,0 +1,1529 @@
+import warnings
+
+import numpy as np
+from scipy.linalg import eigh
+
+from .settings import Options
+from .utils import MaxEvalError, TargetSuccess, FeasibleSuccess
+
+
+EPS = np.finfo(float).eps
+
+
+class Interpolation:
+    """
+    Interpolation set.
+
+    This class stores a base point around which the models are expanded and the
+    interpolation points. The coordinates of the interpolation points are
+    relative to the base point.
+    """
+
+    def __init__(self, pb, options):
+        """
+        Initialize the interpolation set.
+
+        Parameters
+        ----------
+        pb : `cobyqa.problem.Problem`
+            Problem to be solved.
+        options : dict
+            Options of the solver.
+        """
+        # Reduce the initial trust-region radius if necessary.
+        self._debug = options[Options.DEBUG]
+        max_radius = 0.5 * np.min(pb.bounds.xu - pb.bounds.xl)
+        if options[Options.RHOBEG] > max_radius:
+            options[Options.RHOBEG.value] = max_radius
+            options[Options.RHOEND.value] = np.min(
+                [
+                    options[Options.RHOEND],
+                    max_radius,
+                ]
+            )
+
+        # Set the initial point around which the models are expanded.
+        self._x_base = np.copy(pb.x0)
+        very_close_xl_idx = (
+            self.x_base <= pb.bounds.xl + 0.5 * options[Options.RHOBEG]
+        )
+        self.x_base[very_close_xl_idx] = pb.bounds.xl[very_close_xl_idx]
+        close_xl_idx = (
+            pb.bounds.xl + 0.5 * options[Options.RHOBEG] < self.x_base
+        ) & (self.x_base <= pb.bounds.xl + options[Options.RHOBEG])
+        self.x_base[close_xl_idx] = np.minimum(
+            pb.bounds.xl[close_xl_idx] + options[Options.RHOBEG],
+            pb.bounds.xu[close_xl_idx],
+        )
+        very_close_xu_idx = (
+            self.x_base >= pb.bounds.xu - 0.5 * options[Options.RHOBEG]
+        )
+        self.x_base[very_close_xu_idx] = pb.bounds.xu[very_close_xu_idx]
+        close_xu_idx = (
+            self.x_base < pb.bounds.xu - 0.5 * options[Options.RHOBEG]
+        ) & (pb.bounds.xu - options[Options.RHOBEG] <= self.x_base)
+        self.x_base[close_xu_idx] = np.maximum(
+            pb.bounds.xu[close_xu_idx] - options[Options.RHOBEG],
+            pb.bounds.xl[close_xu_idx],
+        )
+
+        # Set the initial interpolation set.
+        self._xpt = np.zeros((pb.n, options[Options.NPT]))
+        for k in range(1, options[Options.NPT]):
+            if k <= pb.n:
+                if very_close_xu_idx[k - 1]:
+                    self.xpt[k - 1, k] = -options[Options.RHOBEG]
+                else:
+                    self.xpt[k - 1, k] = options[Options.RHOBEG]
+            elif k <= 2 * pb.n:
+                if very_close_xl_idx[k - pb.n - 1]:
+                    self.xpt[k - pb.n - 1, k] = 2.0 * options[Options.RHOBEG]
+                elif very_close_xu_idx[k - pb.n - 1]:
+                    self.xpt[k - pb.n - 1, k] = -2.0 * options[Options.RHOBEG]
+                else:
+                    self.xpt[k - pb.n - 1, k] = -options[Options.RHOBEG]
+            else:
+                spread = (k - pb.n - 1) // pb.n
+                k1 = k - (1 + spread) * pb.n - 1
+                k2 = (k1 + spread) % pb.n
+                self.xpt[k1, k] = self.xpt[k1, k1 + 1]
+                self.xpt[k2, k] = self.xpt[k2, k2 + 1]
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self.xpt.shape[0]
+
+    @property
+    def npt(self):
+        """
+        Number of interpolation points.
+
+        Returns
+        -------
+        int
+            Number of interpolation points.
+        """
+        return self.xpt.shape[1]
+
+    @property
+    def xpt(self):
+        """
+        Interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, npt)
+            Interpolation points.
+        """
+        return self._xpt
+
+    @xpt.setter
+    def xpt(self, xpt):
+        """
+        Set the interpolation points.
+
+        Parameters
+        ----------
+        xpt : `numpy.ndarray`, shape (n, npt)
+            New interpolation points.
+        """
+        if self._debug:
+            assert xpt.shape == (
+                self.n,
+                self.npt,
+            ), "The shape of `xpt` is not valid."
+        self._xpt = xpt
+
+    @property
+    def x_base(self):
+        """
+        Base point around which the models are expanded.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Base point around which the models are expanded.
+        """
+        return self._x_base
+
+    @x_base.setter
+    def x_base(self, x_base):
+        """
+        Set the base point around which the models are expanded.
+
+        Parameters
+        ----------
+        x_base : `numpy.ndarray`, shape (n,)
+            New base point around which the models are expanded.
+        """
+        if self._debug:
+            assert x_base.shape == (
+                self.n,
+            ), "The shape of `x_base` is not valid."
+        self._x_base = x_base
+
+    def point(self, k):
+        """
+        Get the `k`-th interpolation point.
+
+        The return point is relative to the origin.
+
+        Parameters
+        ----------
+        k : int
+            Index of the interpolation point.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            `k`-th interpolation point.
+        """
+        if self._debug:
+            assert 0 <= k < self.npt, "The index `k` is not valid."
+        return self.x_base + self.xpt[:, k]
+
+
+_cache = {"xpt": None, "a": None, "right_scaling": None, "eigh": None}
+
+
+def build_system(interpolation):
+    """
+    Build the left-hand side matrix of the interpolation system. The
+    matrix below stores W * diag(right_scaling),
+    where W is the theoretical matrix of the interpolation system. The
+    right scaling matrices is chosen to keep the elements in
+    the matrix well-balanced.
+
+    Parameters
+    ----------
+    interpolation : `cobyqa.models.Interpolation`
+        Interpolation set.
+    """
+
+    # Compute the scaled directions from the base point to the
+    # interpolation points. We scale the directions to avoid numerical
+    # difficulties.
+    if _cache["xpt"] is not None and np.array_equal(
+        interpolation.xpt, _cache["xpt"]
+    ):
+        return _cache["a"], _cache["right_scaling"], _cache["eigh"]
+
+    scale = np.max(np.linalg.norm(interpolation.xpt, axis=0), initial=EPS)
+    xpt_scale = interpolation.xpt / scale
+
+    n, npt = xpt_scale.shape
+    a = np.zeros((npt + n + 1, npt + n + 1))
+    a[:npt, :npt] = 0.5 * (xpt_scale.T @ xpt_scale) ** 2.0
+    a[:npt, npt] = 1.0
+    a[:npt, npt + 1:] = xpt_scale.T
+    a[npt, :npt] = 1.0
+    a[npt + 1:, :npt] = xpt_scale
+
+    # Build the left and right scaling diagonal matrices.
+    right_scaling = np.empty(npt + n + 1)
+    right_scaling[:npt] = 1.0 / scale**2.0
+    right_scaling[npt] = scale**2.0
+    right_scaling[npt + 1:] = scale
+
+    eig_values, eig_vectors = eigh(a, check_finite=False)
+
+    _cache["xpt"] = np.copy(interpolation.xpt)
+    _cache["a"] = np.copy(a)
+    _cache["right_scaling"] = np.copy(right_scaling)
+    _cache["eigh"] = (eig_values, eig_vectors)
+
+    return a, right_scaling, (eig_values, eig_vectors)
+
+
+class Quadratic:
+    """
+    Quadratic model.
+
+    This class stores the Hessian matrix of the quadratic model using the
+    implicit/explicit representation designed by Powell for NEWUOA [1]_.
+
+    References
+    ----------
+    .. [1] M. J. D. Powell. The NEWUOA software for unconstrained optimization
+       without derivatives. In G. Di Pillo and M. Roma, editors, *Large-Scale
+       Nonlinear Optimization*, volume 83 of Nonconvex Optim. Appl., pages
+       255--297. Springer, Boston, MA, USA, 2006. `doi:10.1007/0-387-30065-1_16
+       `_.
+    """
+
+    def __init__(self, interpolation, values, debug):
+        """
+        Initialize the quadratic model.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+        values : `numpy.ndarray`, shape (npt,)
+            Values of the interpolated function at the interpolation points.
+        debug : bool
+            Whether to make debugging tests during the execution.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        self._debug = debug
+        if self._debug:
+            assert values.shape == (
+                interpolation.npt,
+            ), "The shape of `values` is not valid."
+        if interpolation.npt < interpolation.n + 1:
+            raise ValueError(
+                f"The number of interpolation points must be at least "
+                f"{interpolation.n + 1}."
+            )
+        self._const, self._grad, self._i_hess, _ = self._get_model(
+            interpolation,
+            values,
+        )
+        self._e_hess = np.zeros((self.n, self.n))
+
+    def __call__(self, x, interpolation):
+        """
+        Evaluate the quadratic model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the quadratic model is evaluated.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        float
+            Value of the quadratic model at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        x_diff = x - interpolation.x_base
+        return (
+            self._const
+            + self._grad @ x_diff
+            + 0.5
+            * (
+                self._i_hess @ (interpolation.xpt.T @ x_diff) ** 2.0
+                + x_diff @ self._e_hess @ x_diff
+            )
+        )
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self._grad.size
+
+    @property
+    def npt(self):
+        """
+        Number of interpolation points used to define the quadratic model.
+
+        Returns
+        -------
+        int
+            Number of interpolation points used to define the quadratic model.
+        """
+        return self._i_hess.size
+
+    def grad(self, x, interpolation):
+        """
+        Evaluate the gradient of the quadratic model at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which the gradient of the quadratic model is evaluated.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the quadratic model at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        x_diff = x - interpolation.x_base
+        return self._grad + self.hess_prod(x_diff, interpolation)
+
+    def hess(self, interpolation):
+        """
+        Evaluate the Hessian matrix of the quadratic model.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, n)
+            Hessian matrix of the quadratic model.
+        """
+        return self._e_hess + interpolation.xpt @ (
+            self._i_hess[:, np.newaxis] * interpolation.xpt.T
+        )
+
+    def hess_prod(self, v, interpolation):
+        """
+        Evaluate the right product of the Hessian matrix of the quadratic model
+        with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrix of the quadratic model is
+            multiplied from the right.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Right product of the Hessian matrix of the quadratic model with
+            `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return self._e_hess @ v + interpolation.xpt @ (
+            self._i_hess * (interpolation.xpt.T @ v)
+        )
+
+    def curv(self, v, interpolation):
+        """
+        Evaluate the curvature of the quadratic model along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic model is
+            evaluated.
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+
+        Returns
+        -------
+        float
+            Curvature of the quadratic model along `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return (
+            v @ self._e_hess @ v
+            + self._i_hess @ (interpolation.xpt.T @ v) ** 2.0
+        )
+
+    def update(self, interpolation, k_new, dir_old, values_diff):
+        """
+        Update the quadratic model.
+
+        This method applies the derivative-free symmetric Broyden update to the
+        quadratic model. The `knew`-th interpolation point must be updated
+        before calling this method.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Updated interpolation set.
+        k_new : int
+            Index of the updated interpolation point.
+        dir_old : `numpy.ndarray`, shape (n,)
+            Value of ``interpolation.xpt[:, k_new]`` before the update.
+        values_diff : `numpy.ndarray`, shape (npt,)
+            Differences between the values of the interpolated nonlinear
+            function and the previous quadratic model at the updated
+            interpolation points.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        if self._debug:
+            assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
+            assert dir_old.shape == (
+                self.n,
+            ), "The shape of `dir_old` is not valid."
+            assert values_diff.shape == (
+                self.npt,
+            ), "The shape of `values_diff` is not valid."
+
+        # Forward the k_new-th element of the implicit Hessian matrix to the
+        # explicit Hessian matrix. This must be done because the implicit
+        # Hessian matrix is related to the interpolation points, and the
+        # k_new-th interpolation point is modified.
+        self._e_hess += self._i_hess[k_new] * np.outer(dir_old, dir_old)
+        self._i_hess[k_new] = 0.0
+
+        # Update the quadratic model.
+        const, grad, i_hess, ill_conditioned = self._get_model(
+            interpolation,
+            values_diff,
+        )
+        self._const += const
+        self._grad += grad
+        self._i_hess += i_hess
+        return ill_conditioned
+
+    def shift_x_base(self, interpolation, new_x_base):
+        """
+        Shift the point around which the quadratic model is defined.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Previous interpolation set.
+        new_x_base : `numpy.ndarray`, shape (n,)
+            Point that will replace ``interpolation.x_base``.
+        """
+        if self._debug:
+            assert new_x_base.shape == (
+                self.n,
+            ), "The shape of `new_x_base` is not valid."
+        self._const = self(new_x_base, interpolation)
+        self._grad = self.grad(new_x_base, interpolation)
+        shift = new_x_base - interpolation.x_base
+        update = np.outer(
+            shift,
+            (interpolation.xpt - 0.5 * shift[:, np.newaxis]) @ self._i_hess,
+        )
+        self._e_hess += update + update.T
+
+    @staticmethod
+    def solve_systems(interpolation, rhs):
+        """
+        Solve the interpolation systems.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+        rhs : `numpy.ndarray`, shape (npt + n + 1, m)
+            Right-hand side vectors of the ``m`` interpolation systems.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt + n + 1, m)
+            Solutions of the interpolation systems.
+        `numpy.ndarray`, shape (m, )
+            Whether the interpolation systems are ill-conditioned.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation systems are ill-defined.
+        """
+        n, npt = interpolation.xpt.shape
+        assert (
+            rhs.ndim == 2 and rhs.shape[0] == npt + n + 1
+        ), "The shape of `rhs` is not valid."
+
+        # Build the left-hand side matrix of the interpolation system. The
+        # matrix below stores diag(left_scaling) * W * diag(right_scaling),
+        # where W is the theoretical matrix of the interpolation system. The
+        # left and right scaling matrices are chosen to keep the elements in
+        # the matrix well-balanced.
+        a, right_scaling, eig = build_system(interpolation)
+
+        # Build the solution. After a discussion with Mike Saunders and Alexis
+        # Montoison during their visit to the Hong Kong Polytechnic University
+        # in 2024, we decided to use the eigendecomposition of the symmetric
+        # matrix a. This is more stable than the previously employed LBL
+        # decomposition, and allows us to directly detect ill-conditioning of
+        # the system and to build the least-squares solution if necessary.
+        # Numerical experiments have shown that this strategy improves the
+        # performance of the solver.
+        rhs_scaled = rhs * right_scaling[:, np.newaxis]
+        if not (np.all(np.isfinite(a)) and np.all(np.isfinite(rhs_scaled))):
+            raise np.linalg.LinAlgError(
+                "The interpolation system is ill-defined."
+            )
+
+        # calculated in build_system
+        eig_values, eig_vectors = eig
+
+        large_eig_values = np.abs(eig_values) > EPS
+        eig_vectors = eig_vectors[:, large_eig_values]
+        inv_eig_values = 1.0 / eig_values[large_eig_values]
+        ill_conditioned = ~np.all(large_eig_values, 0)
+        left_scaled_solutions = eig_vectors @ (
+            (eig_vectors.T @ rhs_scaled) * inv_eig_values[:, np.newaxis]
+        )
+        return (
+            left_scaled_solutions * right_scaling[:, np.newaxis],
+            ill_conditioned,
+        )
+
+    @staticmethod
+    def _get_model(interpolation, values):
+        """
+        Solve the interpolation system.
+
+        Parameters
+        ----------
+        interpolation : `cobyqa.models.Interpolation`
+            Interpolation set.
+        values : `numpy.ndarray`, shape (npt,)
+            Values of the interpolated function at the interpolation points.
+
+        Returns
+        -------
+        float
+            Constant term of the quadratic model.
+        `numpy.ndarray`, shape (n,)
+            Gradient of the quadratic model at ``interpolation.x_base``.
+        `numpy.ndarray`, shape (npt,)
+            Implicit Hessian matrix of the quadratic model.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        assert values.shape == (
+            interpolation.npt,
+        ), "The shape of `values` is not valid."
+        n, npt = interpolation.xpt.shape
+        x, ill_conditioned = Quadratic.solve_systems(
+            interpolation,
+            np.block(
+                [
+                    [
+                        values,
+                        np.zeros(n + 1),
+                    ]
+                ]
+            ).T,
+        )
+        return x[npt, 0], x[npt + 1:, 0], x[:npt, 0], ill_conditioned
+
+
+class Models:
+    """
+    Models for a nonlinear optimization problem.
+    """
+
+    def __init__(self, pb, options, penalty):
+        """
+        Initialize the models.
+
+        Parameters
+        ----------
+        pb : `cobyqa.problem.Problem`
+            Problem to be solved.
+        options : dict
+            Options of the solver.
+        penalty : float
+            Penalty parameter used to select the point in the filter to forward
+            to the callback function.
+
+        Raises
+        ------
+        `cobyqa.utils.MaxEvalError`
+            If the maximum number of evaluations is reached.
+        `cobyqa.utils.TargetSuccess`
+            If a nearly feasible point has been found with an objective
+            function value below the target.
+        `cobyqa.utils.FeasibleSuccess`
+            If a feasible point has been found for a feasibility problem.
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        # Set the initial interpolation set.
+        self._debug = options[Options.DEBUG]
+        self._interpolation = Interpolation(pb, options)
+
+        # Evaluate the nonlinear functions at the initial interpolation points.
+        x_eval = self.interpolation.point(0)
+        fun_init, cub_init, ceq_init = pb(x_eval, penalty)
+        self._fun_val = np.full(options[Options.NPT], np.nan)
+        self._cub_val = np.full((options[Options.NPT], cub_init.size), np.nan)
+        self._ceq_val = np.full((options[Options.NPT], ceq_init.size), np.nan)
+        for k in range(options[Options.NPT]):
+            if k >= options[Options.MAX_EVAL]:
+                raise MaxEvalError
+            if k == 0:
+                self.fun_val[k] = fun_init
+                self.cub_val[k, :] = cub_init
+                self.ceq_val[k, :] = ceq_init
+            else:
+                x_eval = self.interpolation.point(k)
+                self.fun_val[k], self.cub_val[k, :], self.ceq_val[k, :] = pb(
+                    x_eval,
+                    penalty,
+                )
+
+            # Stop the iterations if the problem is a feasibility problem and
+            # the current interpolation point is feasible.
+            if (
+                pb.is_feasibility
+                and pb.maxcv(
+                    self.interpolation.point(k),
+                    self.cub_val[k, :],
+                    self.ceq_val[k, :],
+                )
+                <= options[Options.FEASIBILITY_TOL]
+            ):
+                raise FeasibleSuccess
+
+            # Stop the iterations if the current interpolation point is nearly
+            # feasible and has an objective function value below the target.
+            if (
+                self._fun_val[k] <= options[Options.TARGET]
+                and pb.maxcv(
+                    self.interpolation.point(k),
+                    self.cub_val[k, :],
+                    self.ceq_val[k, :],
+                )
+                <= options[Options.FEASIBILITY_TOL]
+            ):
+                raise TargetSuccess
+
+        # Build the initial quadratic models.
+        self._fun = Quadratic(
+            self.interpolation,
+            self._fun_val,
+            options[Options.DEBUG],
+        )
+        self._cub = np.empty(self.m_nonlinear_ub, dtype=Quadratic)
+        self._ceq = np.empty(self.m_nonlinear_eq, dtype=Quadratic)
+        for i in range(self.m_nonlinear_ub):
+            self._cub[i] = Quadratic(
+                self.interpolation,
+                self.cub_val[:, i],
+                options[Options.DEBUG],
+            )
+        for i in range(self.m_nonlinear_eq):
+            self._ceq[i] = Quadratic(
+                self.interpolation,
+                self.ceq_val[:, i],
+                options[Options.DEBUG],
+            )
+        if self._debug:
+            self._check_interpolation_conditions()
+
+    @property
+    def n(self):
+        """
+        Dimension of the problem.
+
+        Returns
+        -------
+        int
+            Dimension of the problem.
+        """
+        return self.interpolation.n
+
+    @property
+    def npt(self):
+        """
+        Number of interpolation points.
+
+        Returns
+        -------
+        int
+            Number of interpolation points.
+        """
+        return self.interpolation.npt
+
+    @property
+    def m_nonlinear_ub(self):
+        """
+        Number of nonlinear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear inequality constraints.
+        """
+        return self.cub_val.shape[1]
+
+    @property
+    def m_nonlinear_eq(self):
+        """
+        Number of nonlinear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear equality constraints.
+        """
+        return self.ceq_val.shape[1]
+
+    @property
+    def interpolation(self):
+        """
+        Interpolation set.
+
+        Returns
+        -------
+        `cobyqa.models.Interpolation`
+            Interpolation set.
+        """
+        return self._interpolation
+
+    @property
+    def fun_val(self):
+        """
+        Values of the objective function at the interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt,)
+            Values of the objective function at the interpolation points.
+        """
+        return self._fun_val
+
+    @property
+    def cub_val(self):
+        """
+        Values of the nonlinear inequality constraint functions at the
+        interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt, m_nonlinear_ub)
+            Values of the nonlinear inequality constraint functions at the
+            interpolation points.
+        """
+        return self._cub_val
+
+    @property
+    def ceq_val(self):
+        """
+        Values of the nonlinear equality constraint functions at the
+        interpolation points.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (npt, m_nonlinear_eq)
+            Values of the nonlinear equality constraint functions at the
+            interpolation points.
+        """
+        return self._ceq_val
+
+    def fun(self, x):
+        """
+        Evaluate the quadratic model of the objective function at a given
+        point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the quadratic model of the objective
+            function.
+
+        Returns
+        -------
+        float
+            Value of the quadratic model of the objective function at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        return self._fun(x, self.interpolation)
+
+    def fun_grad(self, x):
+        """
+        Evaluate the gradient of the quadratic model of the objective function
+        at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradient of the quadratic model of
+            the objective function.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the quadratic model of the objective function at `x`.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        return self._fun.grad(x, self.interpolation)
+
+    def fun_hess(self):
+        """
+        Evaluate the Hessian matrix of the quadratic model of the objective
+        function.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n, n)
+            Hessian matrix of the quadratic model of the objective function.
+        """
+        return self._fun.hess(self.interpolation)
+
+    def fun_hess_prod(self, v):
+        """
+        Evaluate the right product of the Hessian matrix of the quadratic model
+        of the objective function with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrix of the quadratic model of the
+            objective function is multiplied from the right.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Right product of the Hessian matrix of the quadratic model of the
+            objective function with `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return self._fun.hess_prod(v, self.interpolation)
+
+    def fun_curv(self, v):
+        """
+        Evaluate the curvature of the quadratic model of the objective function
+        along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic model of the
+            objective function is evaluated.
+
+        Returns
+        -------
+        float
+            Curvature of the quadratic model of the objective function along
+            `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+        return self._fun.curv(v, self.interpolation)
+
+    def fun_alt_grad(self, x):
+        """
+        Evaluate the gradient of the alternative quadratic model of the
+        objective function at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradient of the alternative
+            quadratic model of the objective function.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Gradient of the alternative quadratic model of the objective
+            function at `x`.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+        model = Quadratic(self.interpolation, self.fun_val, self._debug)
+        return model.grad(x, self.interpolation)
+
+    def cub(self, x, mask=None):
+        """
+        Evaluate the quadratic models of the nonlinear inequality functions at
+        a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the quadratic models of the nonlinear
+            inequality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Values of the quadratic model of the nonlinear inequality
+            functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model(x, self.interpolation) for model in self._get_cub(mask)]
+        )
+
+    def cub_grad(self, x, mask=None):
+        """
+        Evaluate the gradients of the quadratic models of the nonlinear
+        inequality functions at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradients of the quadratic models of
+            the nonlinear inequality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Gradients of the quadratic model of the nonlinear inequality
+            functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.grad(x, self.interpolation)
+             for model in self._get_cub(mask)],
+            (-1, self.n),
+        )
+
+    def cub_hess(self, mask=None):
+        """
+        Evaluate the Hessian matrices of the quadratic models of the nonlinear
+        inequality functions.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Hessian matrices of the quadratic models of the nonlinear
+            inequality functions.
+        """
+        if self._debug:
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.hess(self.interpolation) for model in self._get_cub(mask)],
+            (-1, self.n, self.n),
+        )
+
+    def cub_hess_prod(self, v, mask=None):
+        """
+        Evaluate the right product of the Hessian matrices of the quadratic
+        models of the nonlinear inequality functions with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrices of the quadratic models of
+            the nonlinear inequality functions are multiplied from the right.
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Right products of the Hessian matrices of the quadratic models of
+            the nonlinear inequality functions with `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [
+                model.hess_prod(v, self.interpolation)
+                for model in self._get_cub(mask)
+            ],
+            (-1, self.n),
+        )
+
+    def cub_curv(self, v, mask=None):
+        """
+        Evaluate the curvature of the quadratic models of the nonlinear
+        inequality functions along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic models of the
+            nonlinear inequality functions is evaluated.
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Curvature of the quadratic models of the nonlinear inequality
+            functions along `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model.curv(v, self.interpolation)
+             for model in self._get_cub(mask)]
+        )
+
+    def ceq(self, x, mask=None):
+        """
+        Evaluate the quadratic models of the nonlinear equality functions at a
+        given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the quadratic models of the nonlinear
+            equality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Values of the quadratic model of the nonlinear equality functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model(x, self.interpolation) for model in self._get_ceq(mask)]
+        )
+
+    def ceq_grad(self, x, mask=None):
+        """
+        Evaluate the gradients of the quadratic models of the nonlinear
+        equality functions at a given point.
+
+        Parameters
+        ----------
+        x : `numpy.ndarray`, shape (n,)
+            Point at which to evaluate the gradients of the quadratic models of
+            the nonlinear equality functions.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Gradients of the quadratic model of the nonlinear equality
+            functions.
+        """
+        if self._debug:
+            assert x.shape == (self.n,), "The shape of `x` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.grad(x, self.interpolation)
+             for model in self._get_ceq(mask)],
+            (-1, self.n),
+        )
+
+    def ceq_hess(self, mask=None):
+        """
+        Evaluate the Hessian matrices of the quadratic models of the nonlinear
+        equality functions.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Hessian matrices of the quadratic models of the nonlinear equality
+            functions.
+        """
+        if self._debug:
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [model.hess(self.interpolation) for model in self._get_ceq(mask)],
+            (-1, self.n, self.n),
+        )
+
+    def ceq_hess_prod(self, v, mask=None):
+        """
+        Evaluate the right product of the Hessian matrices of the quadratic
+        models of the nonlinear equality functions with a given vector.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Vector with which the Hessian matrices of the quadratic models of
+            the nonlinear equality functions are multiplied from the right.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Right products of the Hessian matrices of the quadratic models of
+            the nonlinear equality functions with `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.reshape(
+            [
+                model.hess_prod(v, self.interpolation)
+                for model in self._get_ceq(mask)
+            ],
+            (-1, self.n),
+        )
+
+    def ceq_curv(self, v, mask=None):
+        """
+        Evaluate the curvature of the quadratic models of the nonlinear
+        equality functions along a given direction.
+
+        Parameters
+        ----------
+        v : `numpy.ndarray`, shape (n,)
+            Direction along which the curvature of the quadratic models of the
+            nonlinear equality functions is evaluated.
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to consider.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Curvature of the quadratic models of the nonlinear equality
+            functions along `v`.
+        """
+        if self._debug:
+            assert v.shape == (self.n,), "The shape of `v` is not valid."
+            assert mask is None or mask.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `mask` is not valid."
+        return np.array(
+            [model.curv(v, self.interpolation)
+             for model in self._get_ceq(mask)]
+        )
+
+    def reset_models(self):
+        """
+        Set the quadratic models of the objective function, nonlinear
+        inequality constraints, and nonlinear equality constraints to the
+        alternative quadratic models.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        self._fun = Quadratic(self.interpolation, self.fun_val, self._debug)
+        for i in range(self.m_nonlinear_ub):
+            self._cub[i] = Quadratic(
+                self.interpolation,
+                self.cub_val[:, i],
+                self._debug,
+            )
+        for i in range(self.m_nonlinear_eq):
+            self._ceq[i] = Quadratic(
+                self.interpolation,
+                self.ceq_val[:, i],
+                self._debug,
+            )
+        if self._debug:
+            self._check_interpolation_conditions()
+
+    def update_interpolation(self, k_new, x_new, fun_val, cub_val, ceq_val):
+        """
+        Update the interpolation set.
+
+        This method updates the interpolation set by replacing the `knew`-th
+        interpolation point with `xnew`. It also updates the function values
+        and the quadratic models.
+
+        Parameters
+        ----------
+        k_new : int
+            Index of the updated interpolation point.
+        x_new : `numpy.ndarray`, shape (n,)
+            New interpolation point. Its value is interpreted as relative to
+            the origin, not the base point.
+        fun_val : float
+            Value of the objective function at `x_new`.
+            Objective function value at `x_new`.
+        cub_val : `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Values of the nonlinear inequality constraints at `x_new`.
+        ceq_val : `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Values of the nonlinear equality constraints at `x_new`.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+        """
+        if self._debug:
+            assert 0 <= k_new < self.npt, "The index `k_new` is not valid."
+            assert x_new.shape == (self.n,), \
+                "The shape of `x_new` is not valid."
+            assert isinstance(fun_val, float), \
+                "The function value is not valid."
+            assert cub_val.shape == (
+                self.m_nonlinear_ub,
+            ), "The shape of `cub_val` is not valid."
+            assert ceq_val.shape == (
+                self.m_nonlinear_eq,
+            ), "The shape of `ceq_val` is not valid."
+
+        # Compute the updates in the interpolation conditions.
+        fun_diff = np.zeros(self.npt)
+        cub_diff = np.zeros(self.cub_val.shape)
+        ceq_diff = np.zeros(self.ceq_val.shape)
+        fun_diff[k_new] = fun_val - self.fun(x_new)
+        cub_diff[k_new, :] = cub_val - self.cub(x_new)
+        ceq_diff[k_new, :] = ceq_val - self.ceq(x_new)
+
+        # Update the function values.
+        self.fun_val[k_new] = fun_val
+        self.cub_val[k_new, :] = cub_val
+        self.ceq_val[k_new, :] = ceq_val
+
+        # Update the interpolation set.
+        dir_old = np.copy(self.interpolation.xpt[:, k_new])
+        self.interpolation.xpt[:, k_new] = x_new - self.interpolation.x_base
+
+        # Update the quadratic models.
+        ill_conditioned = self._fun.update(
+            self.interpolation,
+            k_new,
+            dir_old,
+            fun_diff,
+        )
+        for i in range(self.m_nonlinear_ub):
+            ill_conditioned = ill_conditioned or self._cub[i].update(
+                self.interpolation,
+                k_new,
+                dir_old,
+                cub_diff[:, i],
+            )
+        for i in range(self.m_nonlinear_eq):
+            ill_conditioned = ill_conditioned or self._ceq[i].update(
+                self.interpolation,
+                k_new,
+                dir_old,
+                ceq_diff[:, i],
+            )
+        if self._debug:
+            self._check_interpolation_conditions()
+        return ill_conditioned
+
+    def determinants(self, x_new, k_new=None):
+        """
+        Compute the normalized determinants of the new interpolation systems.
+
+        Parameters
+        ----------
+        x_new : `numpy.ndarray`, shape (n,)
+            New interpolation point. Its value is interpreted as relative to
+            the origin, not the base point.
+        k_new : int, optional
+            Index of the updated interpolation point. If `k_new` is not
+            specified, all the possible determinants are computed.
+
+        Returns
+        -------
+        {float, `numpy.ndarray`, shape (npt,)}
+            Determinant(s) of the new interpolation system.
+
+        Raises
+        ------
+        `numpy.linalg.LinAlgError`
+            If the interpolation system is ill-defined.
+
+        Notes
+        -----
+        The determinants are normalized by the determinant of the current
+        interpolation system. For stability reasons, the calculations are done
+        using the formula (2.12) in [1]_.
+
+        References
+        ----------
+        .. [1] M. J. D. Powell. On updating the inverse of a KKT matrix.
+           Technical Report DAMTP 2004/NA01, Department of Applied Mathematics
+           and Theoretical Physics, University of Cambridge, Cambridge, UK,
+           2004.
+        """
+        if self._debug:
+            assert x_new.shape == (self.n,), \
+                "The shape of `x_new` is not valid."
+            assert (
+                k_new is None or 0 <= k_new < self.npt
+            ), "The index `k_new` is not valid."
+
+        # Compute the values independent of k_new.
+        shift = x_new - self.interpolation.x_base
+        new_col = np.empty((self.npt + self.n + 1, 1))
+        new_col[: self.npt, 0] = (
+                0.5 * (self.interpolation.xpt.T @ shift) ** 2.0)
+        new_col[self.npt, 0] = 1.0
+        new_col[self.npt + 1:, 0] = shift
+        inv_new_col = Quadratic.solve_systems(self.interpolation, new_col)[0]
+        beta = 0.5 * (shift @ shift) ** 2.0 - new_col[:, 0] @ inv_new_col[:, 0]
+
+        # Compute the values that depend on k.
+        if k_new is None:
+            coord_vec = np.eye(self.npt + self.n + 1, self.npt)
+            alpha = np.diag(
+                Quadratic.solve_systems(
+                    self.interpolation,
+                    coord_vec,
+                )[0]
+            )
+            tau = inv_new_col[: self.npt, 0]
+        else:
+            coord_vec = np.eye(self.npt + self.n + 1, 1, -k_new)
+            alpha = Quadratic.solve_systems(
+                self.interpolation,
+                coord_vec,
+            )[
+                0
+            ][k_new, 0]
+            tau = inv_new_col[k_new, 0]
+        return alpha * beta + tau**2.0
+
+    def shift_x_base(self, new_x_base, options):
+        """
+        Shift the base point without changing the interpolation set.
+
+        Parameters
+        ----------
+        new_x_base : `numpy.ndarray`, shape (n,)
+            New base point.
+        options : dict
+            Options of the solver.
+        """
+        if self._debug:
+            assert new_x_base.shape == (
+                self.n,
+            ), "The shape of `new_x_base` is not valid."
+
+        # Update the models.
+        self._fun.shift_x_base(self.interpolation, new_x_base)
+        for model in self._cub:
+            model.shift_x_base(self.interpolation, new_x_base)
+        for model in self._ceq:
+            model.shift_x_base(self.interpolation, new_x_base)
+
+        # Update the base point and the interpolation points.
+        shift = new_x_base - self.interpolation.x_base
+        self.interpolation.x_base += shift
+        self.interpolation.xpt -= shift[:, np.newaxis]
+        if options[Options.DEBUG]:
+            self._check_interpolation_conditions()
+
+    def _get_cub(self, mask=None):
+        """
+        Get the quadratic models of the nonlinear inequality constraints.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_ub,), optional
+            Mask of the quadratic models to return.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Quadratic models of the nonlinear inequality constraints.
+        """
+        return self._cub if mask is None else self._cub[mask]
+
+    def _get_ceq(self, mask=None):
+        """
+        Get the quadratic models of the nonlinear equality constraints.
+
+        Parameters
+        ----------
+        mask : `numpy.ndarray`, shape (m_nonlinear_eq,), optional
+            Mask of the quadratic models to return.
+
+        Returns
+        -------
+        `numpy.ndarray`
+            Quadratic models of the nonlinear equality constraints.
+        """
+        return self._ceq if mask is None else self._ceq[mask]
+
+    def _check_interpolation_conditions(self):
+        """
+        Check the interpolation conditions of all quadratic models.
+        """
+        error_fun = 0.0
+        error_cub = 0.0
+        error_ceq = 0.0
+        for k in range(self.npt):
+            error_fun = np.max(
+                [
+                    error_fun,
+                    np.abs(
+                        self.fun(self.interpolation.point(k)) - self.fun_val[k]
+                    ),
+                ]
+            )
+            error_cub = np.max(
+                np.abs(
+                    self.cub(self.interpolation.point(k)) - self.cub_val[k, :]
+                ),
+                initial=error_cub,
+            )
+            error_ceq = np.max(
+                np.abs(
+                    self.ceq(self.interpolation.point(k)) - self.ceq_val[k, :]
+                ),
+                initial=error_ceq,
+            )
+        tol = 10.0 * np.sqrt(EPS) * max(self.n, self.npt)
+        if error_fun > tol * np.max(np.abs(self.fun_val), initial=1.0):
+            warnings.warn(
+                "The interpolation conditions for the objective function are "
+                "not satisfied.",
+                RuntimeWarning,
+                2,
+            )
+        if error_cub > tol * np.max(np.abs(self.cub_val), initial=1.0):
+            warnings.warn(
+                "The interpolation conditions for the inequality constraint "
+                "function are not satisfied.",
+                RuntimeWarning,
+                2,
+            )
+        if error_ceq > tol * np.max(np.abs(self.ceq_val), initial=1.0):
+            warnings.warn(
+                "The interpolation conditions for the equality constraint "
+                "function are not satisfied.",
+                RuntimeWarning,
+                2,
+            )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/problem.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/problem.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dbebce3a48067e97da2b75bd2cdd609e01029b2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/problem.py
@@ -0,0 +1,1296 @@
+from contextlib import suppress
+from inspect import signature
+import copy
+
+import numpy as np
+from scipy.optimize import (
+    Bounds,
+    LinearConstraint,
+    NonlinearConstraint,
+    OptimizeResult,
+)
+from scipy.optimize._constraints import PreparedConstraint
+
+
+from .settings import PRINT_OPTIONS, BARRIER
+from .utils import CallbackSuccess, get_arrays_tol
+from .utils import exact_1d_array
+
+
+class ObjectiveFunction:
+    """
+    Real-valued objective function.
+    """
+
+    def __init__(self, fun, verbose, debug, *args):
+        """
+        Initialize the objective function.
+
+        Parameters
+        ----------
+        fun : {callable, None}
+            Function to evaluate, or None.
+
+                ``fun(x, *args) -> float``
+
+            where ``x`` is an array with shape (n,) and `args` is a tuple.
+        verbose : bool
+            Whether to print the function evaluations.
+        debug : bool
+            Whether to make debugging tests during the execution.
+        *args : tuple
+            Additional arguments to be passed to the function.
+        """
+        if debug:
+            assert fun is None or callable(fun)
+            assert isinstance(verbose, bool)
+            assert isinstance(debug, bool)
+
+        self._fun = fun
+        self._verbose = verbose
+        self._args = args
+        self._n_eval = 0
+
+    def __call__(self, x):
+        """
+        Evaluate the objective function.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the objective function is evaluated.
+
+        Returns
+        -------
+        float
+            Function value at `x`.
+        """
+        x = np.array(x, dtype=float)
+        if self._fun is None:
+            f = 0.0
+        else:
+            f = float(np.squeeze(self._fun(x, *self._args)))
+            self._n_eval += 1
+            if self._verbose:
+                with np.printoptions(**PRINT_OPTIONS):
+                    print(f"{self.name}({x}) = {f}")
+        return f
+
+    @property
+    def n_eval(self):
+        """
+        Number of function evaluations.
+
+        Returns
+        -------
+        int
+            Number of function evaluations.
+        """
+        return self._n_eval
+
+    @property
+    def name(self):
+        """
+        Name of the objective function.
+
+        Returns
+        -------
+        str
+            Name of the objective function.
+        """
+        name = ""
+        if self._fun is not None:
+            try:
+                name = self._fun.__name__
+            except AttributeError:
+                name = "fun"
+        return name
+
+
+class BoundConstraints:
+    """
+    Bound constraints ``xl <= x <= xu``.
+    """
+
+    def __init__(self, bounds):
+        """
+        Initialize the bound constraints.
+
+        Parameters
+        ----------
+        bounds : scipy.optimize.Bounds
+            Bound constraints.
+        """
+        self._xl = np.array(bounds.lb, float)
+        self._xu = np.array(bounds.ub, float)
+
+        # Remove the ill-defined bounds.
+        self.xl[np.isnan(self.xl)] = -np.inf
+        self.xu[np.isnan(self.xu)] = np.inf
+
+        self.is_feasible = (
+            np.all(self.xl <= self.xu)
+            and np.all(self.xl < np.inf)
+            and np.all(self.xu > -np.inf)
+        )
+        self.m = np.count_nonzero(self.xl > -np.inf) + np.count_nonzero(
+            self.xu < np.inf
+        )
+        self.pcs = PreparedConstraint(bounds, np.ones(bounds.lb.size))
+
+    @property
+    def xl(self):
+        """
+        Lower bound.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Lower bound.
+        """
+        return self._xl
+
+    @property
+    def xu(self):
+        """
+        Upper bound.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Upper bound.
+        """
+        return self._xu
+
+    def maxcv(self, x):
+        """
+        Evaluate the maximum constraint violation.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the maximum constraint violation is evaluated.
+
+        Returns
+        -------
+        float
+            Maximum constraint violation at `x`.
+        """
+        x = np.asarray(x, dtype=float)
+        return self.violation(x)
+
+    def violation(self, x):
+        # shortcut for no bounds
+        if self.is_feasible:
+            return np.array([0])
+        else:
+            return self.pcs.violation(x)
+
+    def project(self, x):
+        """
+        Project a point onto the feasible set.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point to be projected.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Projection of `x` onto the feasible set.
+        """
+        return np.clip(x, self.xl, self.xu) if self.is_feasible else x
+
+
+class LinearConstraints:
+    """
+    Linear constraints ``a_ub @ x <= b_ub`` and ``a_eq @ x == b_eq``.
+    """
+
+    def __init__(self, constraints, n, debug):
+        """
+        Initialize the linear constraints.
+
+        Parameters
+        ----------
+        constraints : list of LinearConstraint
+            Linear constraints.
+        n : int
+            Number of variables.
+        debug : bool
+            Whether to make debugging tests during the execution.
+        """
+        if debug:
+            assert isinstance(constraints, list)
+            for constraint in constraints:
+                assert isinstance(constraint, LinearConstraint)
+            assert isinstance(debug, bool)
+
+        self._a_ub = np.empty((0, n))
+        self._b_ub = np.empty(0)
+        self._a_eq = np.empty((0, n))
+        self._b_eq = np.empty(0)
+        for constraint in constraints:
+            is_equality = np.abs(
+                constraint.ub - constraint.lb
+            ) <= get_arrays_tol(constraint.lb, constraint.ub)
+            if np.any(is_equality):
+                self._a_eq = np.vstack((self.a_eq, constraint.A[is_equality]))
+                self._b_eq = np.concatenate(
+                    (
+                        self.b_eq,
+                        0.5
+                        * (
+                            constraint.lb[is_equality]
+                            + constraint.ub[is_equality]
+                        ),
+                    )
+                )
+            if not np.all(is_equality):
+                self._a_ub = np.vstack(
+                    (
+                        self.a_ub,
+                        constraint.A[~is_equality],
+                        -constraint.A[~is_equality],
+                    )
+                )
+                self._b_ub = np.concatenate(
+                    (
+                        self.b_ub,
+                        constraint.ub[~is_equality],
+                        -constraint.lb[~is_equality],
+                    )
+                )
+
+        # Remove the ill-defined constraints.
+        self.a_ub[np.isnan(self.a_ub)] = 0.0
+        self.a_eq[np.isnan(self.a_eq)] = 0.0
+        undef_ub = np.isnan(self.b_ub) | np.isinf(self.b_ub)
+        undef_eq = np.isnan(self.b_eq)
+        self._a_ub = self.a_ub[~undef_ub, :]
+        self._b_ub = self.b_ub[~undef_ub]
+        self._a_eq = self.a_eq[~undef_eq, :]
+        self._b_eq = self.b_eq[~undef_eq]
+        self.pcs = [
+            PreparedConstraint(c, np.ones(n)) for c in constraints if c.A.size
+        ]
+
+    @property
+    def a_ub(self):
+        """
+        Left-hand side matrix of the linear inequality constraints.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m, n)
+            Left-hand side matrix of the linear inequality constraints.
+        """
+        return self._a_ub
+
+    @property
+    def b_ub(self):
+        """
+        Right-hand side vector of the linear inequality constraints.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m, n)
+            Right-hand side vector of the linear inequality constraints.
+        """
+        return self._b_ub
+
+    @property
+    def a_eq(self):
+        """
+        Left-hand side matrix of the linear equality constraints.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m, n)
+            Left-hand side matrix of the linear equality constraints.
+        """
+        return self._a_eq
+
+    @property
+    def b_eq(self):
+        """
+        Right-hand side vector of the linear equality constraints.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m, n)
+            Right-hand side vector of the linear equality constraints.
+        """
+        return self._b_eq
+
+    @property
+    def m_ub(self):
+        """
+        Number of linear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear inequality constraints.
+        """
+        return self.b_ub.size
+
+    @property
+    def m_eq(self):
+        """
+        Number of linear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear equality constraints.
+        """
+        return self.b_eq.size
+
+    def maxcv(self, x):
+        """
+        Evaluate the maximum constraint violation.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the maximum constraint violation is evaluated.
+
+        Returns
+        -------
+        float
+            Maximum constraint violation at `x`.
+        """
+        return np.max(self.violation(x), initial=0.0)
+
+    def violation(self, x):
+        if len(self.pcs):
+            return np.concatenate([pc.violation(x) for pc in self.pcs])
+        return np.array([])
+
+
+class NonlinearConstraints:
+    """
+    Nonlinear constraints ``c_ub(x) <= 0`` and ``c_eq(x) == b_eq``.
+    """
+
+    def __init__(self, constraints, verbose, debug):
+        """
+        Initialize the nonlinear constraints.
+
+        Parameters
+        ----------
+        constraints : list
+            Nonlinear constraints.
+        verbose : bool
+            Whether to print the function evaluations.
+        debug : bool
+            Whether to make debugging tests during the execution.
+        """
+        if debug:
+            assert isinstance(constraints, list)
+            for constraint in constraints:
+                assert isinstance(constraint, NonlinearConstraint)
+            assert isinstance(verbose, bool)
+            assert isinstance(debug, bool)
+
+        self._constraints = constraints
+        self.pcs = []
+        self._verbose = verbose
+
+        # map of indexes for equality and inequality constraints
+        self._map_ub = None
+        self._map_eq = None
+        self._m_ub = self._m_eq = None
+
+    def __call__(self, x):
+        """
+        Calculates the residual (slack) for the constraints.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the constraints are evaluated.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Nonlinear inequality constraint slack values.
+        `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Nonlinear equality constraint slack values.
+        """
+        if not len(self._constraints):
+            self._m_eq = self._m_ub = 0
+            return np.array([]), np.array([])
+
+        x = np.array(x, dtype=float)
+        # first time around the constraints haven't been prepared
+        if not len(self.pcs):
+            self._map_ub = []
+            self._map_eq = []
+            self._m_eq = 0
+            self._m_ub = 0
+
+            for constraint in self._constraints:
+                if not callable(constraint.jac):
+                    # having a callable constraint function prevents
+                    # constraint.fun from being evaluated when preparing
+                    # constraint
+                    c = copy.copy(constraint)
+                    c.jac = lambda x0: x0
+                    c.hess = lambda x0, v: 0.0
+                    pc = PreparedConstraint(c, x)
+                else:
+                    pc = PreparedConstraint(constraint, x)
+                # we're going to be using the same x value again immediately
+                # after this initialisation
+                pc.fun.f_updated = True
+
+                self.pcs.append(pc)
+                idx = np.arange(pc.fun.m)
+
+                # figure out equality and inequality maps
+                lb, ub = pc.bounds[0], pc.bounds[1]
+                arr_tol = get_arrays_tol(lb, ub)
+                is_equality = np.abs(ub - lb) <= arr_tol
+                self._map_eq.append(idx[is_equality])
+                self._map_ub.append(idx[~is_equality])
+
+                # these values will be corrected to their proper values later
+                self._m_eq += np.count_nonzero(is_equality)
+                self._m_ub += np.count_nonzero(~is_equality)
+
+        c_ub = []
+        c_eq = []
+        for i, pc in enumerate(self.pcs):
+            val = pc.fun.fun(x)
+            if self._verbose:
+                with np.printoptions(**PRINT_OPTIONS):
+                    with suppress(AttributeError):
+                        fun_name = self._constraints[i].fun.__name__
+                        print(f"{fun_name}({x}) = {val}")
+
+            # separate violations into c_eq and c_ub
+            eq_idx = self._map_eq[i]
+            ub_idx = self._map_ub[i]
+
+            ub_val = val[ub_idx]
+            if len(ub_idx):
+                xl = pc.bounds[0][ub_idx]
+                xu = pc.bounds[1][ub_idx]
+
+                # calculate slack within lower bound
+                finite_xl = xl > -np.inf
+                _v = xl[finite_xl] - ub_val[finite_xl]
+                c_ub.append(_v)
+
+                # calculate slack within lower bound
+                finite_xu = xu < np.inf
+                _v = ub_val[finite_xu] - xu[finite_xu]
+                c_ub.append(_v)
+
+            # equality constraints taken from midpoint between lb and ub
+            eq_val = val[eq_idx]
+            if len(eq_idx):
+                midpoint = 0.5 * (pc.bounds[1][eq_idx] + pc.bounds[0][eq_idx])
+                eq_val -= midpoint
+            c_eq.append(eq_val)
+
+        if self._m_eq:
+            c_eq = np.concatenate(c_eq)
+        else:
+            c_eq = np.array([])
+
+        if self._m_ub:
+            c_ub = np.concatenate(c_ub)
+        else:
+            c_ub = np.array([])
+
+        self._m_ub = c_ub.size
+        self._m_eq = c_eq.size
+
+        return c_ub, c_eq
+
+    @property
+    def m_ub(self):
+        """
+        Number of nonlinear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear inequality constraints.
+
+        Raises
+        ------
+        ValueError
+            If the number of nonlinear inequality constraints is unknown.
+        """
+        if self._m_ub is None:
+            raise ValueError(
+                "The number of nonlinear inequality constraints is unknown."
+            )
+        else:
+            return self._m_ub
+
+    @property
+    def m_eq(self):
+        """
+        Number of nonlinear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear equality constraints.
+
+        Raises
+        ------
+        ValueError
+            If the number of nonlinear equality constraints is unknown.
+        """
+        if self._m_eq is None:
+            raise ValueError(
+                "The number of nonlinear equality constraints is unknown."
+            )
+        else:
+            return self._m_eq
+
+    @property
+    def n_eval(self):
+        """
+        Number of function evaluations.
+
+        Returns
+        -------
+        int
+            Number of function evaluations.
+        """
+        if len(self.pcs):
+            return self.pcs[0].fun.nfev
+        else:
+            return 0
+
+    def maxcv(self, x, cub_val=None, ceq_val=None):
+        """
+        Evaluate the maximum constraint violation.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the maximum constraint violation is evaluated.
+        cub_val : array_like, shape (m_nonlinear_ub,), optional
+            Values of the nonlinear inequality constraints. If not provided,
+            the nonlinear inequality constraints are evaluated at `x`.
+        ceq_val : array_like, shape (m_nonlinear_eq,), optional
+            Values of the nonlinear equality constraints. If not provided,
+            the nonlinear equality constraints are evaluated at `x`.
+
+        Returns
+        -------
+        float
+            Maximum constraint violation at `x`.
+        """
+        return np.max(
+            self.violation(x, cub_val=cub_val, ceq_val=ceq_val), initial=0.0
+        )
+
+    def violation(self, x, cub_val=None, ceq_val=None):
+        return np.concatenate([pc.violation(x) for pc in self.pcs])
+
+
+class Problem:
+    """
+    Optimization problem.
+    """
+
+    def __init__(
+        self,
+        obj,
+        x0,
+        bounds,
+        linear,
+        nonlinear,
+        callback,
+        feasibility_tol,
+        scale,
+        store_history,
+        history_size,
+        filter_size,
+        debug,
+    ):
+        """
+        Initialize the nonlinear problem.
+
+        The problem is preprocessed to remove all the variables that are fixed
+        by the bound constraints.
+
+        Parameters
+        ----------
+        obj : ObjectiveFunction
+            Objective function.
+        x0 : array_like, shape (n,)
+            Initial guess.
+        bounds : BoundConstraints
+            Bound constraints.
+        linear : LinearConstraints
+            Linear constraints.
+        nonlinear : NonlinearConstraints
+            Nonlinear constraints.
+        callback : {callable, None}
+            Callback function.
+        feasibility_tol : float
+            Tolerance on the constraint violation.
+        scale : bool
+            Whether to scale the problem according to the bounds.
+        store_history : bool
+            Whether to store the function evaluations.
+        history_size : int
+            Maximum number of function evaluations to store.
+        filter_size : int
+            Maximum number of points in the filter.
+        debug : bool
+            Whether to make debugging tests during the execution.
+        """
+        if debug:
+            assert isinstance(obj, ObjectiveFunction)
+            assert isinstance(bounds, BoundConstraints)
+            assert isinstance(linear, LinearConstraints)
+            assert isinstance(nonlinear, NonlinearConstraints)
+            assert isinstance(feasibility_tol, float)
+            assert isinstance(scale, bool)
+            assert isinstance(store_history, bool)
+            assert isinstance(history_size, int)
+            if store_history:
+                assert history_size > 0
+            assert isinstance(filter_size, int)
+            assert filter_size > 0
+            assert isinstance(debug, bool)
+
+        self._obj = obj
+        self._linear = linear
+        self._nonlinear = nonlinear
+        if callback is not None:
+            if not callable(callback):
+                raise TypeError("The callback must be a callable function.")
+        self._callback = callback
+
+        # Check the consistency of the problem.
+        x0 = exact_1d_array(x0, "The initial guess must be a vector.")
+        n = x0.size
+        if bounds.xl.size != n:
+            raise ValueError(f"The bounds must have {n} elements.")
+        if linear.a_ub.shape[1] != n:
+            raise ValueError(
+                f"The left-hand side matrices of the linear constraints must "
+                f"have {n} columns."
+            )
+
+        # Check which variables are fixed.
+        tol = get_arrays_tol(bounds.xl, bounds.xu)
+        self._fixed_idx = (bounds.xl <= bounds.xu) & (
+            np.abs(bounds.xl - bounds.xu) < tol
+        )
+        self._fixed_val = 0.5 * (
+            bounds.xl[self._fixed_idx] + bounds.xu[self._fixed_idx]
+        )
+        self._fixed_val = np.clip(
+            self._fixed_val,
+            bounds.xl[self._fixed_idx],
+            bounds.xu[self._fixed_idx],
+        )
+
+        # Set the bound constraints.
+        self._orig_bounds = bounds
+        self._bounds = BoundConstraints(
+            Bounds(bounds.xl[~self._fixed_idx], bounds.xu[~self._fixed_idx])
+        )
+
+        # Set the initial guess.
+        self._x0 = self._bounds.project(x0[~self._fixed_idx])
+
+        # Set the linear constraints.
+        b_eq = linear.b_eq - linear.a_eq[:, self._fixed_idx] @ self._fixed_val
+        self._linear = LinearConstraints(
+            [
+                LinearConstraint(
+                    linear.a_ub[:, ~self._fixed_idx],
+                    -np.inf,
+                    linear.b_ub
+                    - linear.a_ub[:, self._fixed_idx] @ self._fixed_val,
+                ),
+                LinearConstraint(linear.a_eq[:, ~self._fixed_idx], b_eq, b_eq),
+            ],
+            self.n,
+            debug,
+        )
+
+        # Scale the problem if necessary.
+        scale = (
+            scale
+            and self._bounds.is_feasible
+            and np.all(np.isfinite(self._bounds.xl))
+            and np.all(np.isfinite(self._bounds.xu))
+        )
+        if scale:
+            self._scaling_factor = 0.5 * (self._bounds.xu - self._bounds.xl)
+            self._scaling_shift = 0.5 * (self._bounds.xu + self._bounds.xl)
+            self._bounds = BoundConstraints(
+                Bounds(-np.ones(self.n), np.ones(self.n))
+            )
+            b_eq = self._linear.b_eq - self._linear.a_eq @ self._scaling_shift
+            self._linear = LinearConstraints(
+                [
+                    LinearConstraint(
+                        self._linear.a_ub @ np.diag(self._scaling_factor),
+                        -np.inf,
+                        self._linear.b_ub
+                        - self._linear.a_ub @ self._scaling_shift,
+                    ),
+                    LinearConstraint(
+                        self._linear.a_eq @ np.diag(self._scaling_factor),
+                        b_eq,
+                        b_eq,
+                    ),
+                ],
+                self.n,
+                debug,
+            )
+            self._x0 = (self._x0 - self._scaling_shift) / self._scaling_factor
+        else:
+            self._scaling_factor = np.ones(self.n)
+            self._scaling_shift = np.zeros(self.n)
+
+        # Set the initial filter.
+        self._feasibility_tol = feasibility_tol
+        self._filter_size = filter_size
+        self._fun_filter = []
+        self._maxcv_filter = []
+        self._x_filter = []
+
+        # Set the initial history.
+        self._store_history = store_history
+        self._history_size = history_size
+        self._fun_history = []
+        self._maxcv_history = []
+        self._x_history = []
+
+    def __call__(self, x, penalty=0.0):
+        """
+        Evaluate the objective and nonlinear constraint functions.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the functions are evaluated.
+        penalty : float, optional
+            Penalty parameter used to select the point in the filter to forward
+            to the callback function.
+
+        Returns
+        -------
+        float
+            Objective function value.
+        `numpy.ndarray`, shape (m_nonlinear_ub,)
+            Nonlinear inequality constraint function values.
+        `numpy.ndarray`, shape (m_nonlinear_eq,)
+            Nonlinear equality constraint function values.
+
+        Raises
+        ------
+        `cobyqa.utils.CallbackSuccess`
+            If the callback function raises a ``StopIteration``.
+        """
+        # Evaluate the objective and nonlinear constraint functions.
+        x = np.asarray(x, dtype=float)
+        x_full = self.build_x(x)
+        fun_val = self._obj(x_full)
+        cub_val, ceq_val = self._nonlinear(x_full)
+        maxcv_val = self.maxcv(x, cub_val, ceq_val)
+        if self._store_history:
+            self._fun_history.append(fun_val)
+            self._maxcv_history.append(maxcv_val)
+            self._x_history.append(x)
+            if len(self._fun_history) > self._history_size:
+                self._fun_history.pop(0)
+                self._maxcv_history.pop(0)
+                self._x_history.pop(0)
+
+        # Add the point to the filter if it is not dominated by any point.
+        if np.isnan(fun_val) and np.isnan(maxcv_val):
+            include_point = len(self._fun_filter) == 0
+        elif np.isnan(fun_val):
+            include_point = all(
+                np.isnan(fun_filter)
+                and maxcv_val < maxcv_filter
+                or np.isnan(maxcv_filter)
+                for fun_filter, maxcv_filter in zip(
+                    self._fun_filter,
+                    self._maxcv_filter,
+                )
+            )
+        elif np.isnan(maxcv_val):
+            include_point = all(
+                np.isnan(maxcv_filter)
+                and fun_val < fun_filter
+                or np.isnan(fun_filter)
+                for fun_filter, maxcv_filter in zip(
+                    self._fun_filter,
+                    self._maxcv_filter,
+                )
+            )
+        else:
+            include_point = all(
+                fun_val < fun_filter or maxcv_val < maxcv_filter
+                for fun_filter, maxcv_filter in zip(
+                    self._fun_filter,
+                    self._maxcv_filter,
+                )
+            )
+        if include_point:
+            self._fun_filter.append(fun_val)
+            self._maxcv_filter.append(maxcv_val)
+            self._x_filter.append(x)
+
+            # Remove the points in the filter that are dominated by the new
+            # point. We must iterate in reverse order to avoid problems when
+            # removing elements from the list.
+            for k in range(len(self._fun_filter) - 2, -1, -1):
+                if np.isnan(fun_val):
+                    remove_point = np.isnan(self._fun_filter[k])
+                elif np.isnan(maxcv_val):
+                    remove_point = np.isnan(self._maxcv_filter[k])
+                else:
+                    remove_point = (
+                        np.isnan(self._fun_filter[k])
+                        or np.isnan(self._maxcv_filter[k])
+                        or fun_val <= self._fun_filter[k]
+                        and maxcv_val <= self._maxcv_filter[k]
+                    )
+                if remove_point:
+                    self._fun_filter.pop(k)
+                    self._maxcv_filter.pop(k)
+                    self._x_filter.pop(k)
+
+            # Keep only the most recent points in the filter.
+            if len(self._fun_filter) > self._filter_size:
+                self._fun_filter.pop(0)
+                self._maxcv_filter.pop(0)
+                self._x_filter.pop(0)
+
+        # Evaluate the callback function after updating the filter to ensure
+        # that the current point can be returned by the method.
+        if self._callback is not None:
+            sig = signature(self._callback)
+            try:
+                x_best, fun_best, _ = self.best_eval(penalty)
+                x_best = self.build_x(x_best)
+                if set(sig.parameters) == {"intermediate_result"}:
+                    intermediate_result = OptimizeResult(
+                        x=x_best,
+                        fun=fun_best,
+                        # maxcv=maxcv_best,
+                    )
+                    self._callback(intermediate_result=intermediate_result)
+                else:
+                    self._callback(x_best)
+            except StopIteration as exc:
+                raise CallbackSuccess from exc
+
+        # Apply the extreme barriers and return.
+        if np.isnan(fun_val):
+            fun_val = BARRIER
+        cub_val[np.isnan(cub_val)] = BARRIER
+        ceq_val[np.isnan(ceq_val)] = BARRIER
+        fun_val = max(min(fun_val, BARRIER), -BARRIER)
+        cub_val = np.maximum(np.minimum(cub_val, BARRIER), -BARRIER)
+        ceq_val = np.maximum(np.minimum(ceq_val, BARRIER), -BARRIER)
+        return fun_val, cub_val, ceq_val
+
+    @property
+    def n(self):
+        """
+        Number of variables.
+
+        Returns
+        -------
+        int
+            Number of variables.
+        """
+        return self.x0.size
+
+    @property
+    def n_orig(self):
+        """
+        Number of variables in the original problem (with fixed variables).
+
+        Returns
+        -------
+        int
+            Number of variables in the original problem (with fixed variables).
+        """
+        return self._fixed_idx.size
+
+    @property
+    def x0(self):
+        """
+        Initial guess.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Initial guess.
+        """
+        return self._x0
+
+    @property
+    def n_eval(self):
+        """
+        Number of function evaluations.
+
+        Returns
+        -------
+        int
+            Number of function evaluations.
+        """
+        return self._obj.n_eval
+
+    @property
+    def fun_name(self):
+        """
+        Name of the objective function.
+
+        Returns
+        -------
+        str
+            Name of the objective function.
+        """
+        return self._obj.name
+
+    @property
+    def bounds(self):
+        """
+        Bound constraints.
+
+        Returns
+        -------
+        BoundConstraints
+            Bound constraints.
+        """
+        return self._bounds
+
+    @property
+    def linear(self):
+        """
+        Linear constraints.
+
+        Returns
+        -------
+        LinearConstraints
+            Linear constraints.
+        """
+        return self._linear
+
+    @property
+    def m_bounds(self):
+        """
+        Number of bound constraints.
+
+        Returns
+        -------
+        int
+            Number of bound constraints.
+        """
+        return self.bounds.m
+
+    @property
+    def m_linear_ub(self):
+        """
+        Number of linear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear inequality constraints.
+        """
+        return self.linear.m_ub
+
+    @property
+    def m_linear_eq(self):
+        """
+        Number of linear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of linear equality constraints.
+        """
+        return self.linear.m_eq
+
+    @property
+    def m_nonlinear_ub(self):
+        """
+        Number of nonlinear inequality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear inequality constraints.
+
+        Raises
+        ------
+        ValueError
+            If the number of nonlinear inequality constraints is not known.
+        """
+        return self._nonlinear.m_ub
+
+    @property
+    def m_nonlinear_eq(self):
+        """
+        Number of nonlinear equality constraints.
+
+        Returns
+        -------
+        int
+            Number of nonlinear equality constraints.
+
+        Raises
+        ------
+        ValueError
+            If the number of nonlinear equality constraints is not known.
+        """
+        return self._nonlinear.m_eq
+
+    @property
+    def fun_history(self):
+        """
+        History of objective function evaluations.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n_eval,)
+            History of objective function evaluations.
+        """
+        return np.array(self._fun_history, dtype=float)
+
+    @property
+    def maxcv_history(self):
+        """
+        History of maximum constraint violations.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n_eval,)
+            History of maximum constraint violations.
+        """
+        return np.array(self._maxcv_history, dtype=float)
+
+    @property
+    def type(self):
+        """
+        Type of the problem.
+
+        The problem can be either 'unconstrained', 'bound-constrained',
+        'linearly constrained', or 'nonlinearly constrained'.
+
+        Returns
+        -------
+        str
+            Type of the problem.
+        """
+        try:
+            if self.m_nonlinear_ub > 0 or self.m_nonlinear_eq > 0:
+                return "nonlinearly constrained"
+            elif self.m_linear_ub > 0 or self.m_linear_eq > 0:
+                return "linearly constrained"
+            elif self.m_bounds > 0:
+                return "bound-constrained"
+            else:
+                return "unconstrained"
+        except ValueError:
+            # The number of nonlinear constraints is not known. It may be zero
+            # if the user provided a nonlinear inequality and/or equality
+            # constraint function that returns an empty array. However, as this
+            # is not known before the first call to the function, we assume
+            # that the problem is nonlinearly constrained.
+            return "nonlinearly constrained"
+
+    @property
+    def is_feasibility(self):
+        """
+        Whether the problem is a feasibility problem.
+
+        Returns
+        -------
+        bool
+            Whether the problem is a feasibility problem.
+        """
+        return self.fun_name == ""
+
+    def build_x(self, x):
+        """
+        Build the full vector of variables from the reduced vector.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Reduced vector of variables.
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n_orig,)
+            Full vector of variables.
+        """
+        x_full = np.empty(self.n_orig)
+        x_full[self._fixed_idx] = self._fixed_val
+        x_full[~self._fixed_idx] = (x * self._scaling_factor
+                                    + self._scaling_shift)
+        return self._orig_bounds.project(x_full)
+
+    def maxcv(self, x, cub_val=None, ceq_val=None):
+        """
+        Evaluate the maximum constraint violation.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Point at which the maximum constraint violation is evaluated.
+        cub_val : array_like, shape (m_nonlinear_ub,), optional
+            Values of the nonlinear inequality constraints. If not provided,
+            the nonlinear inequality constraints are evaluated at `x`.
+        ceq_val : array_like, shape (m_nonlinear_eq,), optional
+            Values of the nonlinear equality constraints. If not provided,
+            the nonlinear equality constraints are evaluated at `x`.
+
+        Returns
+        -------
+        float
+            Maximum constraint violation at `x`.
+        """
+        violation = self.violation(x, cub_val=cub_val, ceq_val=ceq_val)
+        if np.count_nonzero(violation):
+            return np.max(violation, initial=0.0)
+        else:
+            return 0.0
+
+    def violation(self, x, cub_val=None, ceq_val=None):
+        violation = []
+        if not self.bounds.is_feasible:
+            b = self.bounds.violation(x)
+            violation.append(b)
+
+        if len(self.linear.pcs):
+            lc = self.linear.violation(x)
+            violation.append(lc)
+        if len(self._nonlinear.pcs):
+            nlc = self._nonlinear.violation(x, cub_val, ceq_val)
+            violation.append(nlc)
+
+        if len(violation):
+            return np.concatenate(violation)
+
+    def best_eval(self, penalty):
+        """
+        Return the best point in the filter and the corresponding objective and
+        nonlinear constraint function evaluations.
+
+        Parameters
+        ----------
+        penalty : float
+            Penalty parameter
+
+        Returns
+        -------
+        `numpy.ndarray`, shape (n,)
+            Best point.
+        float
+            Corresponding objective function value.
+        float
+            Corresponding maximum constraint violation.
+        """
+        # If the filter is empty, i.e., if no function evaluation has been
+        # performed, we evaluate the objective and nonlinear constraint
+        # functions at the initial guess.
+        if len(self._fun_filter) == 0:
+            self(self.x0)
+
+        # Find the best point in the filter.
+        fun_filter = np.array(self._fun_filter)
+        maxcv_filter = np.array(self._maxcv_filter)
+        x_filter = np.array(self._x_filter)
+        finite_idx = np.isfinite(maxcv_filter)
+        if np.any(finite_idx):
+            # At least one point has a finite maximum constraint violation.
+            feasible_idx = maxcv_filter <= self._feasibility_tol
+            if np.any(feasible_idx) and not np.all(
+                np.isnan(fun_filter[feasible_idx])
+            ):
+                # At least one point is feasible and has a well-defined
+                # objective function value. We select the point with the least
+                # objective function value. If there is a tie, we select the
+                # point with the least maximum constraint violation. If there
+                # is still a tie, we select the most recent point.
+                fun_min_idx = feasible_idx & (
+                    fun_filter <= np.nanmin(fun_filter[feasible_idx])
+                )
+                if np.count_nonzero(fun_min_idx) > 1:
+                    fun_min_idx &= maxcv_filter <= np.min(
+                        maxcv_filter[fun_min_idx]
+                    )
+                i = np.flatnonzero(fun_min_idx)[-1]
+            elif np.any(feasible_idx):
+                # At least one point is feasible but no feasible point has a
+                # well-defined objective function value. We select the most
+                # recent feasible point.
+                i = np.flatnonzero(feasible_idx)[-1]
+            else:
+                # No point is feasible. We first compute the merit function
+                # value for each point.
+                merit_filter = np.full_like(fun_filter, np.nan)
+                merit_filter[finite_idx] = (
+                    fun_filter[finite_idx] + penalty * maxcv_filter[finite_idx]
+                )
+                if np.all(np.isnan(merit_filter)):
+                    # No point has a well-defined merit function value. In
+                    # other words, among the points with a well-defined maximum
+                    # constraint violation, none has a well-defined objective
+                    # function value. We select the point with the least
+                    # maximum constraint violation. If there is a tie, we
+                    # select the most recent point.
+                    min_maxcv_idx = maxcv_filter <= np.nanmin(maxcv_filter)
+                    i = np.flatnonzero(min_maxcv_idx)[-1]
+                else:
+                    # At least one point has a well-defined merit function
+                    # value. We select the point with the least merit function
+                    # value. If there is a tie, we select the point with the
+                    # least maximum constraint violation. If there is still a
+                    # tie, we select the point with the least objective
+                    # function value. If there is still a tie, we select the
+                    # most recent point.
+                    merit_min_idx = merit_filter <= np.nanmin(merit_filter)
+                    if np.count_nonzero(merit_min_idx) > 1:
+                        merit_min_idx &= maxcv_filter <= np.min(
+                            maxcv_filter[merit_min_idx]
+                        )
+
+                    if np.count_nonzero(merit_min_idx) > 1:
+                        merit_min_idx &= fun_filter <= np.min(
+                            fun_filter[merit_min_idx]
+                        )
+                    i = np.flatnonzero(merit_min_idx)[-1]
+        elif not np.all(np.isnan(fun_filter)):
+            # No maximum constraint violation is well-defined but at least one
+            # point has a well-defined objective function value. We select the
+            # point with the least objective function value. If there is a tie,
+            # we select the most recent point.
+            fun_min_idx = fun_filter <= np.nanmin(fun_filter)
+            i = np.flatnonzero(fun_min_idx)[-1]
+        else:
+            # No point has a well-defined maximum constraint violation or
+            # objective function value. We select the most recent point.
+            i = len(fun_filter) - 1
+        return (
+            self.bounds.project(x_filter[i, :]),
+            fun_filter[i],
+            maxcv_filter[i],
+        )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/settings.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/settings.py
new file mode 100644
index 0000000000000000000000000000000000000000..6394822826e094a803a485556a298e342bf260ac
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/settings.py
@@ -0,0 +1,132 @@
+import sys
+from enum import Enum
+
+import numpy as np
+
+
+# Exit status.
+class ExitStatus(Enum):
+    """
+    Exit statuses.
+    """
+
+    RADIUS_SUCCESS = 0
+    TARGET_SUCCESS = 1
+    FIXED_SUCCESS = 2
+    CALLBACK_SUCCESS = 3
+    FEASIBLE_SUCCESS = 4
+    MAX_EVAL_WARNING = 5
+    MAX_ITER_WARNING = 6
+    INFEASIBLE_ERROR = -1
+    LINALG_ERROR = -2
+
+
+class Options(str, Enum):
+    """
+    Options.
+    """
+
+    DEBUG = "debug"
+    FEASIBILITY_TOL = "feasibility_tol"
+    FILTER_SIZE = "filter_size"
+    HISTORY_SIZE = "history_size"
+    MAX_EVAL = "maxfev"
+    MAX_ITER = "maxiter"
+    NPT = "nb_points"
+    RHOBEG = "radius_init"
+    RHOEND = "radius_final"
+    SCALE = "scale"
+    STORE_HISTORY = "store_history"
+    TARGET = "target"
+    VERBOSE = "disp"
+
+
+class Constants(str, Enum):
+    """
+    Constants.
+    """
+
+    DECREASE_RADIUS_FACTOR = "decrease_radius_factor"
+    INCREASE_RADIUS_FACTOR = "increase_radius_factor"
+    INCREASE_RADIUS_THRESHOLD = "increase_radius_threshold"
+    DECREASE_RADIUS_THRESHOLD = "decrease_radius_threshold"
+    DECREASE_RESOLUTION_FACTOR = "decrease_resolution_factor"
+    LARGE_RESOLUTION_THRESHOLD = "large_resolution_threshold"
+    MODERATE_RESOLUTION_THRESHOLD = "moderate_resolution_threshold"
+    LOW_RATIO = "low_ratio"
+    HIGH_RATIO = "high_ratio"
+    VERY_LOW_RATIO = "very_low_ratio"
+    PENALTY_INCREASE_THRESHOLD = "penalty_increase_threshold"
+    PENALTY_INCREASE_FACTOR = "penalty_increase_factor"
+    SHORT_STEP_THRESHOLD = "short_step_threshold"
+    LOW_RADIUS_FACTOR = "low_radius_factor"
+    BYRD_OMOJOKUN_FACTOR = "byrd_omojokun_factor"
+    THRESHOLD_RATIO_CONSTRAINTS = "threshold_ratio_constraints"
+    LARGE_SHIFT_FACTOR = "large_shift_factor"
+    LARGE_GRADIENT_FACTOR = "large_gradient_factor"
+    RESOLUTION_FACTOR = "resolution_factor"
+    IMPROVE_TCG = "improve_tcg"
+
+
+# Default options.
+DEFAULT_OPTIONS = {
+    Options.DEBUG.value: False,
+    Options.FEASIBILITY_TOL.value: np.sqrt(np.finfo(float).eps),
+    Options.FILTER_SIZE.value: sys.maxsize,
+    Options.HISTORY_SIZE.value: sys.maxsize,
+    Options.MAX_EVAL.value: lambda n: 500 * n,
+    Options.MAX_ITER.value: lambda n: 1000 * n,
+    Options.NPT.value: lambda n: 2 * n + 1,
+    Options.RHOBEG.value: 1.0,
+    Options.RHOEND.value: 1e-6,
+    Options.SCALE.value: False,
+    Options.STORE_HISTORY.value: False,
+    Options.TARGET.value: -np.inf,
+    Options.VERBOSE.value: False,
+}
+
+# Default constants.
+DEFAULT_CONSTANTS = {
+    Constants.DECREASE_RADIUS_FACTOR.value: 0.5,
+    Constants.INCREASE_RADIUS_FACTOR.value: np.sqrt(2.0),
+    Constants.INCREASE_RADIUS_THRESHOLD.value: 2.0,
+    Constants.DECREASE_RADIUS_THRESHOLD.value: 1.4,
+    Constants.DECREASE_RESOLUTION_FACTOR.value: 0.1,
+    Constants.LARGE_RESOLUTION_THRESHOLD.value: 250.0,
+    Constants.MODERATE_RESOLUTION_THRESHOLD.value: 16.0,
+    Constants.LOW_RATIO.value: 0.1,
+    Constants.HIGH_RATIO.value: 0.7,
+    Constants.VERY_LOW_RATIO.value: 0.01,
+    Constants.PENALTY_INCREASE_THRESHOLD.value: 1.5,
+    Constants.PENALTY_INCREASE_FACTOR.value: 2.0,
+    Constants.SHORT_STEP_THRESHOLD.value: 0.5,
+    Constants.LOW_RADIUS_FACTOR.value: 0.1,
+    Constants.BYRD_OMOJOKUN_FACTOR.value: 0.8,
+    Constants.THRESHOLD_RATIO_CONSTRAINTS.value: 2.0,
+    Constants.LARGE_SHIFT_FACTOR.value: 10.0,
+    Constants.LARGE_GRADIENT_FACTOR.value: 10.0,
+    Constants.RESOLUTION_FACTOR.value: 2.0,
+    Constants.IMPROVE_TCG.value: True,
+}
+
+# Printing options.
+PRINT_OPTIONS = {
+    "threshold": 6,
+    "edgeitems": 2,
+    "linewidth": sys.maxsize,
+    "formatter": {
+        "float_kind": lambda x: np.format_float_scientific(
+            x,
+            precision=3,
+            unique=False,
+            pad_left=2,
+        )
+    },
+}
+
+# Constants.
+BARRIER = 2.0 ** min(
+    100,
+    np.finfo(float).maxexp // 2,
+    -np.finfo(float).minexp // 2,
+)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01a1ad3c6f4cb5c0c9b99d1ce35fea92e7618ff5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/__init__.py
@@ -0,0 +1,14 @@
+from .geometry import cauchy_geometry, spider_geometry
+from .optim import (
+    tangential_byrd_omojokun,
+    constrained_tangential_byrd_omojokun,
+    normal_byrd_omojokun,
+)
+
+__all__ = [
+    "cauchy_geometry",
+    "spider_geometry",
+    "tangential_byrd_omojokun",
+    "constrained_tangential_byrd_omojokun",
+    "normal_byrd_omojokun",
+]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b67fd7c813ee493b18720d1daf71324d72330b6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/geometry.py
@@ -0,0 +1,387 @@
+import inspect
+
+import numpy as np
+
+from ..utils import get_arrays_tol
+
+
+TINY = np.finfo(float).tiny
+
+
+def cauchy_geometry(const, grad, curv, xl, xu, delta, debug):
+    r"""
+    Maximize approximately the absolute value of a quadratic function subject
+    to bound constraints in a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s +
+        \frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u,\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    by maximizing the objective function along the constrained Cauchy
+    direction.
+
+    Parameters
+    ----------
+    const : float
+        Constant :math:`c` as shown above.
+    grad : `numpy.ndarray`, shape (n,)
+        Gradient :math:`g` as shown above.
+    curv : callable
+        Curvature of :math:`H` along any vector.
+
+            ``curv(s) -> float``
+
+        returns :math:`s^{\mathsf{T}} H s`.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Notes
+    -----
+    This function is described as the first alternative in Section 6.5 of [1]_.
+    It is assumed that the origin is feasible with respect to the bound
+    constraints and that `delta` is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
+       and Software*. PhD thesis, Department of Applied Mathematics, The Hong
+       Kong Polytechnic University, Hong Kong, China, 2022. URL:
+       https://theses.lib.polyu.edu.hk/handle/200/12294.
+    """
+    if debug:
+        assert isinstance(const, float)
+        assert isinstance(grad, np.ndarray) and grad.ndim == 1
+        assert inspect.signature(curv).bind(grad)
+        assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
+        assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+
+    # To maximize the absolute value of a quadratic function, we maximize the
+    # function itself or its negative, and we choose the solution that provides
+    # the largest function value.
+    step1, q_val1 = _cauchy_geom(const, grad, curv, xl, xu, delta, debug)
+    step2, q_val2 = _cauchy_geom(
+        -const,
+        -grad,
+        lambda x: -curv(x),
+        xl,
+        xu,
+        delta,
+        debug,
+    )
+    step = step1 if abs(q_val1) >= abs(q_val2) else step2
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def spider_geometry(const, grad, curv, xpt, xl, xu, delta, debug):
+    r"""
+    Maximize approximately the absolute value of a quadratic function subject
+    to bound constraints in a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \max_{s \in \mathbb{R}^n} \quad \bigg\lvert c + g^{\mathsf{T}} s +
+        \frac{1}{2} s^{\mathsf{T}} H s \bigg\rvert \quad \text{s.t.} \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u,\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    by maximizing the objective function along given straight lines.
+
+    Parameters
+    ----------
+    const : float
+        Constant :math:`c` as shown above.
+    grad : `numpy.ndarray`, shape (n,)
+        Gradient :math:`g` as shown above.
+    curv : callable
+        Curvature of :math:`H` along any vector.
+
+            ``curv(s) -> float``
+
+        returns :math:`s^{\mathsf{T}} H s`.
+    xpt : `numpy.ndarray`, shape (n, npt)
+        Points defining the straight lines. The straight lines considered are
+        the ones passing through the origin and the points in `xpt`.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Notes
+    -----
+    This function is described as the second alternative in Section 6.5 of
+    [1]_. It is assumed that the origin is feasible with respect to the bound
+    constraints and that `delta` is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
+       and Software*. PhD thesis, Department of Applied Mathematics, The Hong
+       Kong Polytechnic University, Hong Kong, China, 2022. URL:
+       https://theses.lib.polyu.edu.hk/handle/200/12294.
+    """
+    if debug:
+        assert isinstance(const, float)
+        assert isinstance(grad, np.ndarray) and grad.ndim == 1
+        assert inspect.signature(curv).bind(grad)
+        assert (
+            isinstance(xpt, np.ndarray)
+            and xpt.ndim == 2
+            and xpt.shape[0] == grad.size
+        )
+        assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
+        assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+
+    # Iterate through the straight lines.
+    step = np.zeros_like(grad)
+    q_val = const
+    s_norm = np.linalg.norm(xpt, axis=0)
+
+    # Set alpha_xl to the step size for the lower-bound constraint and
+    # alpha_xu to the step size for the upper-bound constraint.
+
+    # xl.shape = (N,)
+    # xpt.shape = (N, M)
+    # i_xl_pos.shape = (M, N)
+    i_xl_pos = (xl > -np.inf) & (xpt.T > -TINY * xl)
+    i_xl_neg = (xl > -np.inf) & (xpt.T < TINY * xl)
+    i_xu_pos = (xu < np.inf) & (xpt.T > TINY * xu)
+    i_xu_neg = (xu < np.inf) & (xpt.T < -TINY * xu)
+
+    # (M, N)
+    alpha_xl_pos = np.atleast_2d(
+        np.broadcast_to(xl, i_xl_pos.shape)[i_xl_pos] / xpt.T[i_xl_pos]
+    )
+    # (M,)
+    alpha_xl_pos = np.max(alpha_xl_pos, axis=1, initial=-np.inf)
+    # make sure it's (M,)
+    alpha_xl_pos = np.broadcast_to(np.atleast_1d(alpha_xl_pos), xpt.shape[1])
+
+    alpha_xl_neg = np.atleast_2d(
+        np.broadcast_to(xl, i_xl_neg.shape)[i_xl_neg] / xpt.T[i_xl_neg]
+    )
+    alpha_xl_neg = np.max(alpha_xl_neg, axis=1, initial=np.inf)
+    alpha_xl_neg = np.broadcast_to(np.atleast_1d(alpha_xl_neg), xpt.shape[1])
+
+    alpha_xu_neg = np.atleast_2d(
+        np.broadcast_to(xu, i_xu_neg.shape)[i_xu_neg] / xpt.T[i_xu_neg]
+    )
+    alpha_xu_neg = np.max(alpha_xu_neg, axis=1, initial=-np.inf)
+    alpha_xu_neg = np.broadcast_to(np.atleast_1d(alpha_xu_neg), xpt.shape[1])
+
+    alpha_xu_pos = np.atleast_2d(
+        np.broadcast_to(xu, i_xu_pos.shape)[i_xu_pos] / xpt.T[i_xu_pos]
+    )
+    alpha_xu_pos = np.max(alpha_xu_pos, axis=1, initial=np.inf)
+    alpha_xu_pos = np.broadcast_to(np.atleast_1d(alpha_xu_pos), xpt.shape[1])
+
+    for k in range(xpt.shape[1]):
+        # Set alpha_tr to the step size for the trust-region constraint.
+        if s_norm[k] > TINY * delta:
+            alpha_tr = max(delta / s_norm[k], 0.0)
+        else:
+            # The current straight line is basically zero.
+            continue
+
+        alpha_bd_pos = max(min(alpha_xu_pos[k], alpha_xl_neg[k]), 0.0)
+        alpha_bd_neg = min(max(alpha_xl_pos[k], alpha_xu_neg[k]), 0.0)
+
+        # Set alpha_quad_pos and alpha_quad_neg to the step size to the extrema
+        # of the quadratic function along the positive and negative directions.
+        grad_step = grad @ xpt[:, k]
+        curv_step = curv(xpt[:, k])
+        if (
+            grad_step >= 0.0
+            and curv_step < -TINY * grad_step
+            or grad_step <= 0.0
+            and curv_step > -TINY * grad_step
+        ):
+            alpha_quad_pos = max(-grad_step / curv_step, 0.0)
+        else:
+            alpha_quad_pos = np.inf
+        if (
+            grad_step >= 0.0
+            and curv_step > TINY * grad_step
+            or grad_step <= 0.0
+            and curv_step < TINY * grad_step
+        ):
+            alpha_quad_neg = min(-grad_step / curv_step, 0.0)
+        else:
+            alpha_quad_neg = -np.inf
+
+        # Select the step that provides the largest value of the objective
+        # function if it improves the current best. The best positive step is
+        # either the one that reaches the constraints or the one that reaches
+        # the extremum of the objective function along the current direction
+        # (only possible if the resulting step is feasible). We test both, and
+        # we perform similar calculations along the negative step.
+        # N.B.: we select the largest possible step among all the ones that
+        # maximize the objective function. This is to avoid returning the zero
+        # step in some extreme cases.
+        alpha_pos = min(alpha_tr, alpha_bd_pos)
+        alpha_neg = max(-alpha_tr, alpha_bd_neg)
+        q_val_pos = (
+            const + alpha_pos * grad_step + 0.5 * alpha_pos**2.0 * curv_step
+        )
+        q_val_neg = (
+            const + alpha_neg * grad_step + 0.5 * alpha_neg**2.0 * curv_step
+        )
+        if alpha_quad_pos < alpha_pos:
+            q_val_quad_pos = (
+                const
+                + alpha_quad_pos * grad_step
+                + 0.5 * alpha_quad_pos**2.0 * curv_step
+            )
+            if abs(q_val_quad_pos) > abs(q_val_pos):
+                alpha_pos = alpha_quad_pos
+                q_val_pos = q_val_quad_pos
+        if alpha_quad_neg > alpha_neg:
+            q_val_quad_neg = (
+                const
+                + alpha_quad_neg * grad_step
+                + 0.5 * alpha_quad_neg**2.0 * curv_step
+            )
+            if abs(q_val_quad_neg) > abs(q_val_neg):
+                alpha_neg = alpha_quad_neg
+                q_val_neg = q_val_quad_neg
+        if abs(q_val_pos) >= abs(q_val_neg) and abs(q_val_pos) > abs(q_val):
+            step = np.clip(alpha_pos * xpt[:, k], xl, xu)
+            q_val = q_val_pos
+        elif abs(q_val_neg) > abs(q_val_pos) and abs(q_val_neg) > abs(q_val):
+            step = np.clip(alpha_neg * xpt[:, k], xl, xu)
+            q_val = q_val_neg
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def _cauchy_geom(const, grad, curv, xl, xu, delta, debug):
+    """
+    Same as `bound_constrained_cauchy_step` without the absolute value.
+    """
+    # Calculate the initial active set.
+    fixed_xl = (xl < 0.0) & (grad > 0.0)
+    fixed_xu = (xu > 0.0) & (grad < 0.0)
+
+    # Calculate the Cauchy step.
+    cauchy_step = np.zeros_like(grad)
+    cauchy_step[fixed_xl] = xl[fixed_xl]
+    cauchy_step[fixed_xu] = xu[fixed_xu]
+    if np.linalg.norm(cauchy_step) > delta:
+        working = fixed_xl | fixed_xu
+        while True:
+            # Calculate the Cauchy step for the directions in the working set.
+            g_norm = np.linalg.norm(grad[working])
+            delta_reduced = np.sqrt(
+                delta**2.0 - cauchy_step[~working] @ cauchy_step[~working]
+            )
+            if g_norm > TINY * abs(delta_reduced):
+                mu = max(delta_reduced / g_norm, 0.0)
+            else:
+                break
+            cauchy_step[working] = mu * grad[working]
+
+            # Update the working set.
+            fixed_xl = working & (cauchy_step < xl)
+            fixed_xu = working & (cauchy_step > xu)
+            if not np.any(fixed_xl) and not np.any(fixed_xu):
+                # Stop the calculations as the Cauchy step is now feasible.
+                break
+            cauchy_step[fixed_xl] = xl[fixed_xl]
+            cauchy_step[fixed_xu] = xu[fixed_xu]
+            working = working & ~(fixed_xl | fixed_xu)
+
+    # Calculate the step that maximizes the quadratic along the Cauchy step.
+    grad_step = grad @ cauchy_step
+    if grad_step >= 0.0:
+        # Set alpha_tr to the step size for the trust-region constraint.
+        s_norm = np.linalg.norm(cauchy_step)
+        if s_norm > TINY * delta:
+            alpha_tr = max(delta / s_norm, 0.0)
+        else:
+            # The Cauchy step is basically zero.
+            alpha_tr = 0.0
+
+        # Set alpha_quad to the step size for the maximization problem.
+        curv_step = curv(cauchy_step)
+        if curv_step < -TINY * grad_step:
+            alpha_quad = max(-grad_step / curv_step, 0.0)
+        else:
+            alpha_quad = np.inf
+
+        # Set alpha_bd to the step size for the bound constraints.
+        i_xl = (xl > -np.inf) & (cauchy_step < TINY * xl)
+        i_xu = (xu < np.inf) & (cauchy_step > TINY * xu)
+        alpha_xl = np.min(xl[i_xl] / cauchy_step[i_xl], initial=np.inf)
+        alpha_xu = np.min(xu[i_xu] / cauchy_step[i_xu], initial=np.inf)
+        alpha_bd = min(alpha_xl, alpha_xu)
+
+        # Calculate the solution and the corresponding function value.
+        alpha = min(alpha_tr, alpha_quad, alpha_bd)
+        step = np.clip(alpha * cauchy_step, xl, xu)
+        q_val = const + alpha * grad_step + 0.5 * alpha**2.0 * curv_step
+    else:
+        # This case is never reached in exact arithmetic. It prevents this
+        # function to return a step that decreases the objective function.
+        step = np.zeros_like(grad)
+        q_val = const
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step, q_val
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4a960396fb2e992cf76bac0baf171b5af9b7717
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/subsolvers/optim.py
@@ -0,0 +1,1203 @@
+import inspect
+
+import numpy as np
+from scipy.linalg import qr
+
+from ..utils import get_arrays_tol
+
+
+TINY = np.finfo(float).tiny
+EPS = np.finfo(float).eps
+
+
+def tangential_byrd_omojokun(grad, hess_prod, xl, xu, delta, debug, **kwargs):
+    r"""
+    Minimize approximately a quadratic function subject to bound constraints in
+    a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \min_{s \in \mathbb{R}^n} \quad g^{\mathsf{T}} s + \frac{1}{2}
+        s^{\mathsf{T}} H s \quad \text{s.t.} \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    using an active-set variation of the truncated conjugate gradient method.
+
+    Parameters
+    ----------
+    grad : `numpy.ndarray`, shape (n,)
+        Gradient :math:`g` as shown above.
+    hess_prod : callable
+        Product of the Hessian matrix :math:`H` with any vector.
+
+            ``hess_prod(s) -> `numpy.ndarray`, shape (n,)``
+
+        returns the product :math:`H s`.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Other Parameters
+    ----------------
+    improve_tcg : bool, optional
+        If True, a solution generated by the truncated conjugate gradient
+        method that is on the boundary of the trust region is improved by
+        moving around the trust-region boundary on the two-dimensional space
+        spanned by the solution and the gradient of the quadratic function at
+        the solution (default is True).
+
+    Notes
+    -----
+    This function implements Algorithm 6.2 of [1]_. It is assumed that the
+    origin is feasible with respect to the bound constraints and that `delta`
+    is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
+       and Software*. PhD thesis, Department of Applied Mathematics, The Hong
+       Kong Polytechnic University, Hong Kong, China, 2022. URL:
+       https://theses.lib.polyu.edu.hk/handle/200/12294.
+    """
+    if debug:
+        assert isinstance(grad, np.ndarray) and grad.ndim == 1
+        assert inspect.signature(hess_prod).bind(grad)
+        assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
+        assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+
+    # Copy the arrays that may be modified by the code below.
+    n = grad.size
+    grad = np.copy(grad)
+    grad_orig = np.copy(grad)
+
+    # Calculate the initial active set.
+    free_bd = ((xl < 0.0) | (grad < 0.0)) & ((xu > 0.0) | (grad > 0.0))
+
+    # Set the initial iterate and the initial search direction.
+    step = np.zeros_like(grad)
+    sd = np.zeros_like(step)
+    sd[free_bd] = -grad[free_bd]
+
+    k = 0
+    reduct = 0.0
+    boundary_reached = False
+    while k < np.count_nonzero(free_bd):
+        # Stop the computations if sd is not a descent direction.
+        grad_sd = grad @ sd
+        if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)):
+            break
+
+        # Set alpha_tr to the step size for the trust-region constraint.
+        try:
+            alpha_tr = _alpha_tr(step, sd, delta)
+        except ZeroDivisionError:
+            break
+
+        # Stop the computations if a step along sd is expected to give a
+        # relatively small reduction in the objective function.
+        if -alpha_tr * grad_sd <= 1e-8 * reduct:
+            break
+
+        # Set alpha_quad to the step size for the minimization problem.
+        hess_sd = hess_prod(sd)
+        curv_sd = sd @ hess_sd
+        if curv_sd > TINY * abs(grad_sd):
+            alpha_quad = max(-grad_sd / curv_sd, 0.0)
+        else:
+            alpha_quad = np.inf
+
+        # Stop the computations if the reduction in the objective function
+        # provided by an unconstrained step is small.
+        alpha = min(alpha_tr, alpha_quad)
+        if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct:
+            break
+
+        # Set alpha_bd to the step size for the bound constraints.
+        i_xl = (xl > -np.inf) & (sd < -TINY * np.abs(xl - step))
+        i_xu = (xu < np.inf) & (sd > TINY * np.abs(xu - step))
+        all_alpha_xl = np.full_like(step, np.inf)
+        all_alpha_xu = np.full_like(step, np.inf)
+        all_alpha_xl[i_xl] = np.maximum(
+            (xl[i_xl] - step[i_xl]) / sd[i_xl],
+            0.0,
+        )
+        all_alpha_xu[i_xu] = np.maximum(
+            (xu[i_xu] - step[i_xu]) / sd[i_xu],
+            0.0,
+        )
+        alpha_xl = np.min(all_alpha_xl)
+        alpha_xu = np.min(all_alpha_xu)
+        alpha_bd = min(alpha_xl, alpha_xu)
+
+        # Update the iterate.
+        alpha = min(alpha, alpha_bd)
+        if alpha > 0.0:
+            step[free_bd] = np.clip(
+                step[free_bd] + alpha * sd[free_bd],
+                xl[free_bd],
+                xu[free_bd],
+            )
+            grad += alpha * hess_sd
+            reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd)
+
+        if alpha < min(alpha_tr, alpha_bd):
+            # The current iteration is a conjugate gradient iteration. Update
+            # the search direction so that it is conjugate (with respect to H)
+            # to all the previous search directions.
+            beta = (grad[free_bd] @ hess_sd[free_bd]) / curv_sd
+            sd[free_bd] = beta * sd[free_bd] - grad[free_bd]
+            sd[~free_bd] = 0.0
+            k += 1
+        elif alpha < alpha_tr:
+            # The iterate is restricted by a bound constraint. Add this bound
+            # constraint to the active set, and restart the calculations.
+            if alpha_xl <= alpha:
+                i_new = np.argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+            else:
+                i_new = np.argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+            free_bd[i_new] = False
+            sd[free_bd] = -grad[free_bd]
+            sd[~free_bd] = 0.0
+            k = 0
+        else:
+            # The current iterate is on the trust-region boundary. Add all the
+            # active bounds to the working set to prepare for the improvement
+            # of the solution, and stop the iterations.
+            if alpha_xl <= alpha:
+                i_new = _argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_bd[i_new] = False
+            if alpha_xu <= alpha:
+                i_new = _argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_bd[i_new] = False
+            boundary_reached = True
+            break
+
+    # Attempt to improve the solution on the trust-region boundary.
+    if kwargs.get("improve_tcg", True) and boundary_reached:
+        step_base = np.copy(step)
+        step_comparator = grad_orig @ step_base + 0.5 * step_base @ hess_prod(
+            step_base
+        )
+
+        while np.count_nonzero(free_bd) > 0:
+            # Check whether a substantial reduction in the objective function
+            # is possible, and set the search direction.
+            step_sq = step[free_bd] @ step[free_bd]
+            grad_sq = grad[free_bd] @ grad[free_bd]
+            grad_step = grad[free_bd] @ step[free_bd]
+            grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0))
+            sd[free_bd] = grad_step * step[free_bd] - step_sq * grad[free_bd]
+            sd[~free_bd] = 0.0
+            if grad_sd >= -1e-8 * reduct or np.any(
+                grad_sd >= -TINY * np.abs(sd[free_bd])
+            ):
+                break
+            sd[free_bd] /= -grad_sd
+
+            # Calculate an upper bound for the tangent of half the angle theta
+            # of this alternative iteration. The step will be updated as:
+            # step = cos(theta) * step + sin(theta) * sd.
+            temp_xl = np.zeros(n)
+            temp_xu = np.zeros(n)
+            temp_xl[free_bd] = (
+                step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xl[free_bd] ** 2.0
+            )
+            temp_xu[free_bd] = (
+                step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xu[free_bd] ** 2.0
+            )
+            temp_xl[temp_xl > 0.0] = (
+                np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0]
+            )
+            temp_xu[temp_xu > 0.0] = (
+                np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0]
+            )
+            dist_xl = np.maximum(step - xl, 0.0)
+            dist_xu = np.maximum(xu - step, 0.0)
+            i_xl = temp_xl > TINY * dist_xl
+            i_xu = temp_xu > TINY * dist_xu
+            all_t_xl = np.ones(n)
+            all_t_xu = np.ones(n)
+            all_t_xl[i_xl] = np.minimum(
+                all_t_xl[i_xl],
+                dist_xl[i_xl] / temp_xl[i_xl],
+            )
+            all_t_xu[i_xu] = np.minimum(
+                all_t_xu[i_xu],
+                dist_xu[i_xu] / temp_xu[i_xu],
+            )
+            t_xl = np.min(all_t_xl)
+            t_xu = np.min(all_t_xu)
+            t_bd = min(t_xl, t_xu)
+
+            # Calculate some curvature information.
+            hess_step = hess_prod(step)
+            hess_sd = hess_prod(sd)
+            curv_step = step @ hess_step
+            curv_sd = sd @ hess_sd
+            curv_step_sd = step @ hess_sd
+
+            # For a range of equally spaced values of tan(0.5 * theta),
+            # calculate the reduction in the objective function that would be
+            # obtained by accepting the corresponding angle.
+            n_samples = 20
+            n_samples = int((n_samples - 3) * t_bd + 3)
+            t_samples = np.linspace(t_bd / n_samples, t_bd, n_samples)
+            sin_values = 2.0 * t_samples / (1.0 + t_samples**2.0)
+            all_reduct = sin_values * (
+                grad_step * t_samples
+                - grad_sd
+                - t_samples * curv_step
+                + sin_values
+                * (t_samples * curv_step_sd - 0.5 * (curv_sd - curv_step))
+            )
+            if np.all(all_reduct <= 0.0):
+                # No reduction in the objective function is obtained.
+                break
+
+            # Accept the angle that provides the largest reduction in the
+            # objective function, and update the iterate.
+            i_max = np.argmax(all_reduct)
+            cos_value = (1.0 - t_samples[i_max] ** 2.0) / (
+                1.0 + t_samples[i_max] ** 2.0
+            )
+            step[free_bd] = (
+                cos_value * step[free_bd] + sin_values[i_max] * sd[free_bd]
+            )
+            grad += (cos_value - 1.0) * hess_step + sin_values[i_max] * hess_sd
+            reduct += all_reduct[i_max]
+
+            # If the above angle is restricted by bound constraints, add them
+            # to the working set, and restart the alternative iteration.
+            # Otherwise, the calculations are terminated.
+            if t_bd < 1.0 and i_max == n_samples - 1:
+                if t_xl <= t_bd:
+                    i_new = _argmin(all_t_xl)
+                    step[i_new] = xl[i_new]
+                    free_bd[i_new] = False
+                if t_xu <= t_bd:
+                    i_new = _argmin(all_t_xu)
+                    step[i_new] = xu[i_new]
+                    free_bd[i_new] = False
+            else:
+                break
+
+        # Ensure that the alternative iteration improves the objective
+        # function.
+        if grad_orig @ step + 0.5 * step @ hess_prod(step) > step_comparator:
+            step = step_base
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def constrained_tangential_byrd_omojokun(
+    grad,
+    hess_prod,
+    xl,
+    xu,
+    aub,
+    bub,
+    aeq,
+    delta,
+    debug,
+    **kwargs,
+):
+    r"""
+    Minimize approximately a quadratic function subject to bound and linear
+    constraints in a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \min_{s \in \mathbb{R}^n} \quad g^{\mathsf{T}} s + \frac{1}{2}
+        s^{\mathsf{T}} H s \quad \text{s.t.} \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u,\\
+            A_{\scriptscriptstyle I} s \le b_{\scriptscriptstyle I},\\
+            A_{\scriptscriptstyle E} s = 0,\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    using an active-set variation of the truncated conjugate gradient method.
+
+    Parameters
+    ----------
+    grad : `numpy.ndarray`, shape (n,)
+        Gradient :math:`g` as shown above.
+    hess_prod : callable
+        Product of the Hessian matrix :math:`H` with any vector.
+
+            ``hess_prod(s) -> `numpy.ndarray`, shape (n,)``
+
+        returns the product :math:`H s`.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    aub : `numpy.ndarray`, shape (m_linear_ub, n)
+        Coefficient matrix :math:`A_{\scriptscriptstyle I}` as shown above.
+    bub : `numpy.ndarray`, shape (m_linear_ub,)
+        Right-hand side :math:`b_{\scriptscriptstyle I}` as shown above.
+    aeq : `numpy.ndarray`, shape (m_linear_eq, n)
+        Coefficient matrix :math:`A_{\scriptscriptstyle E}` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Other Parameters
+    ----------------
+    improve_tcg : bool, optional
+        If True, a solution generated by the truncated conjugate gradient
+        method that is on the boundary of the trust region is improved by
+        moving around the trust-region boundary on the two-dimensional space
+        spanned by the solution and the gradient of the quadratic function at
+        the solution (default is True).
+
+    Notes
+    -----
+    This function implements Algorithm 6.3 of [1]_. It is assumed that the
+    origin is feasible with respect to the bound and linear constraints, and
+    that `delta` is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
+       and Software*. PhD thesis, Department of Applied Mathematics, The Hong
+       Kong Polytechnic University, Hong Kong, China, 2022. URL:
+       https://theses.lib.polyu.edu.hk/handle/200/12294.
+    """
+    if debug:
+        assert isinstance(grad, np.ndarray) and grad.ndim == 1
+        assert inspect.signature(hess_prod).bind(grad)
+        assert isinstance(xl, np.ndarray) and xl.shape == grad.shape
+        assert isinstance(xu, np.ndarray) and xu.shape == grad.shape
+        assert (
+            isinstance(aub, np.ndarray)
+            and aub.ndim == 2
+            and aub.shape[1] == grad.size
+        )
+        assert (
+            isinstance(bub, np.ndarray)
+            and bub.ndim == 1
+            and bub.size == aub.shape[0]
+        )
+        assert (
+            isinstance(aeq, np.ndarray)
+            and aeq.ndim == 2
+            and aeq.shape[1] == grad.size
+        )
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.all(bub >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+    bub = np.maximum(bub, 0.0)
+
+    # Copy the arrays that may be modified by the code below.
+    n = grad.size
+    grad = np.copy(grad)
+    grad_orig = np.copy(grad)
+
+    # Calculate the initial active set.
+    free_xl = (xl < 0.0) | (grad < 0.0)
+    free_xu = (xu > 0.0) | (grad > 0.0)
+    free_ub = (bub > 0.0) | (aub @ grad > 0.0)
+    n_act, q = qr_tangential_byrd_omojokun(aub, aeq, free_xl, free_xu, free_ub)
+
+    # Set the initial iterate and the initial search direction.
+    step = np.zeros_like(grad)
+    sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
+    resid = np.copy(bub)
+
+    k = 0
+    reduct = 0.0
+    boundary_reached = False
+    while k < n - n_act:
+        # Stop the computations if sd is not a descent direction.
+        grad_sd = grad @ sd
+        if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)):
+            break
+
+        # Set alpha_tr to the step size for the trust-region constraint.
+        try:
+            alpha_tr = _alpha_tr(step, sd, delta)
+        except ZeroDivisionError:
+            break
+
+        # Stop the computations if a step along sd is expected to give a
+        # relatively small reduction in the objective function.
+        if -alpha_tr * grad_sd <= 1e-8 * reduct:
+            break
+
+        # Set alpha_quad to the step size for the minimization problem.
+        hess_sd = hess_prod(sd)
+        curv_sd = sd @ hess_sd
+        if curv_sd > TINY * abs(grad_sd):
+            alpha_quad = max(-grad_sd / curv_sd, 0.0)
+        else:
+            alpha_quad = np.inf
+
+        # Stop the computations if the reduction in the objective function
+        # provided by an unconstrained step is small.
+        alpha = min(alpha_tr, alpha_quad)
+        if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct:
+            break
+
+        # Set alpha_bd to the step size for the bound constraints.
+        i_xl = free_xl & (xl > -np.inf) & (sd < -TINY * np.abs(xl - step))
+        i_xu = free_xu & (xu < np.inf) & (sd > TINY * np.abs(xu - step))
+        all_alpha_xl = np.full_like(step, np.inf)
+        all_alpha_xu = np.full_like(step, np.inf)
+        all_alpha_xl[i_xl] = np.maximum(
+            (xl[i_xl] - step[i_xl]) / sd[i_xl],
+            0.0,
+        )
+        all_alpha_xu[i_xu] = np.maximum(
+            (xu[i_xu] - step[i_xu]) / sd[i_xu],
+            0.0,
+        )
+        alpha_xl = np.min(all_alpha_xl)
+        alpha_xu = np.min(all_alpha_xu)
+        alpha_bd = min(alpha_xl, alpha_xu)
+
+        # Set alpha_ub to the step size for the linear constraints.
+        aub_sd = aub @ sd
+        i_ub = free_ub & (aub_sd > TINY * np.abs(resid))
+        all_alpha_ub = np.full_like(bub, np.inf)
+        all_alpha_ub[i_ub] = resid[i_ub] / aub_sd[i_ub]
+        alpha_ub = np.min(all_alpha_ub, initial=np.inf)
+
+        # Update the iterate.
+        alpha = min(alpha, alpha_bd, alpha_ub)
+        if alpha > 0.0:
+            step = np.clip(step + alpha * sd, xl, xu)
+            grad += alpha * hess_sd
+            resid = np.maximum(0.0, resid - alpha * aub_sd)
+            reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd)
+
+        if alpha < min(alpha_tr, alpha_bd, alpha_ub):
+            # The current iteration is a conjugate gradient iteration. Update
+            # the search direction so that it is conjugate (with respect to H)
+            # to all the previous search directions.
+            grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            beta = (grad_proj @ hess_sd) / curv_sd
+            sd = beta * sd - grad_proj
+            k += 1
+        elif alpha < alpha_tr:
+            # The iterate is restricted by a bound/linear constraint. Add this
+            # constraint to the active set, and restart the calculations.
+            if alpha_xl <= alpha:
+                i_new = np.argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_xl[i_new] = False
+            elif alpha_xu <= alpha:
+                i_new = np.argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_xu[i_new] = False
+            else:
+                i_new = np.argmin(all_alpha_ub)
+                free_ub[i_new] = False
+            n_act, q = qr_tangential_byrd_omojokun(
+                aub,
+                aeq,
+                free_xl,
+                free_xu,
+                free_ub,
+            )
+            sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            k = 0
+        else:
+            # The current iterate is on the trust-region boundary. Add all the
+            # active bound/linear constraints to the working set to prepare for
+            # the improvement of the solution, and stop the iterations.
+            if alpha_xl <= alpha:
+                i_new = _argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_xl[i_new] = False
+            if alpha_xu <= alpha:
+                i_new = _argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_xu[i_new] = False
+            if alpha_ub <= alpha:
+                i_new = _argmin(all_alpha_ub)
+                free_ub[i_new] = False
+            n_act, q = qr_tangential_byrd_omojokun(
+                aub,
+                aeq,
+                free_xl,
+                free_xu,
+                free_ub,
+            )
+            boundary_reached = True
+            break
+
+    # Attempt to improve the solution on the trust-region boundary.
+    if kwargs.get("improve_tcg", True) and boundary_reached and n_act < n:
+        step_base = np.copy(step)
+        while n_act < n:
+            # Check whether a substantial reduction in the objective function
+            # is possible, and set the search direction.
+            step_proj = q[:, n_act:] @ (q[:, n_act:].T @ step)
+            grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            step_sq = step_proj @ step_proj
+            grad_sq = grad_proj @ grad_proj
+            grad_step = grad_proj @ step_proj
+            grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0))
+            sd = q[:, n_act:] @ (
+                q[:, n_act:].T @ (grad_step * step - step_sq * grad)
+            )
+            if grad_sd >= -1e-8 * reduct or np.any(
+                grad_sd >= -TINY * np.abs(sd)
+            ):
+                break
+            sd /= -grad_sd
+
+            # Calculate an upper bound for the tangent of half the angle theta
+            # of this alternative iteration for the bound constraints. The step
+            # will be updated as:
+            # step += (cos(theta) - 1) * step_proj + sin(theta) * sd.
+            temp_xl = np.zeros(n)
+            temp_xu = np.zeros(n)
+            dist_xl = np.maximum(step - xl, 0.0)
+            dist_xu = np.maximum(xu - step, 0.0)
+            temp_xl[free_xl] = sd[free_xl] ** 2.0 - dist_xl[free_xl] * (
+                dist_xl[free_xl] - 2.0 * step_proj[free_xl]
+            )
+            temp_xu[free_xu] = sd[free_xu] ** 2.0 - dist_xu[free_xu] * (
+                dist_xu[free_xu] + 2.0 * step_proj[free_xu]
+            )
+            temp_xl[temp_xl > 0.0] = (
+                np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0]
+            )
+            temp_xu[temp_xu > 0.0] = (
+                np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0]
+            )
+            i_xl = temp_xl > TINY * dist_xl
+            i_xu = temp_xu > TINY * dist_xu
+            all_t_xl = np.ones(n)
+            all_t_xu = np.ones(n)
+            all_t_xl[i_xl] = np.minimum(
+                all_t_xl[i_xl],
+                dist_xl[i_xl] / temp_xl[i_xl],
+            )
+            all_t_xu[i_xu] = np.minimum(
+                all_t_xu[i_xu],
+                dist_xu[i_xu] / temp_xu[i_xu],
+            )
+            t_xl = np.min(all_t_xl)
+            t_xu = np.min(all_t_xu)
+            t_bd = min(t_xl, t_xu)
+
+            # Calculate an upper bound for the tangent of half the angle theta
+            # of this alternative iteration for the linear constraints.
+            temp_ub = np.zeros_like(resid)
+            aub_step = aub @ step_proj
+            aub_sd = aub @ sd
+            temp_ub[free_ub] = aub_sd[free_ub] ** 2.0 - resid[free_ub] * (
+                resid[free_ub] + 2.0 * aub_step[free_ub]
+            )
+            temp_ub[temp_ub > 0.0] = (
+                np.sqrt(temp_ub[temp_ub > 0.0]) + aub_sd[temp_ub > 0.0]
+            )
+            i_ub = temp_ub > TINY * resid
+            all_t_ub = np.ones_like(resid)
+            all_t_ub[i_ub] = np.minimum(
+                all_t_ub[i_ub],
+                resid[i_ub] / temp_ub[i_ub],
+            )
+            t_ub = np.min(all_t_ub, initial=1.0)
+            t_min = min(t_bd, t_ub)
+
+            # Calculate some curvature information.
+            hess_step = hess_prod(step_proj)
+            hess_sd = hess_prod(sd)
+            curv_step = step_proj @ hess_step
+            curv_sd = sd @ hess_sd
+            curv_step_sd = step_proj @ hess_sd
+
+            # For a range of equally spaced values of tan(0.5 * theta),
+            # calculate the reduction in the objective function that would be
+            # obtained by accepting the corresponding angle.
+            n_samples = 20
+            n_samples = int((n_samples - 3) * t_min + 3)
+            t_samples = np.linspace(t_min / n_samples, t_min, n_samples)
+            sin_values = 2.0 * t_samples / (1.0 + t_samples**2.0)
+            all_reduct = sin_values * (
+                grad_step * t_samples
+                - grad_sd
+                - sin_values
+                * (
+                    0.5 * t_samples**2.0 * curv_step
+                    - 2.0 * t_samples * curv_step_sd
+                    + 0.5 * curv_sd
+                )
+            )
+            if np.all(all_reduct <= 0.0):
+                # No reduction in the objective function is obtained.
+                break
+
+            # Accept the angle that provides the largest reduction in the
+            # objective function, and update the iterate.
+            i_max = np.argmax(all_reduct)
+            cos_value = (1.0 - t_samples[i_max] ** 2.0) / (
+                1.0 + t_samples[i_max] ** 2.0
+            )
+            step = np.clip(
+                step + (cos_value - 1.0) * step_proj + sin_values[i_max] * sd,
+                xl,
+                xu,
+            )
+            grad += (cos_value - 1.0) * hess_step + sin_values[i_max] * hess_sd
+            resid = np.maximum(
+                0.0,
+                resid
+                - (cos_value - 1.0) * aub_step
+                - sin_values[i_max] * aub_sd,
+            )
+            reduct += all_reduct[i_max]
+
+            # If the above angle is restricted by bound constraints, add them
+            # to the working set, and restart the alternative iteration.
+            # Otherwise, the calculations are terminated.
+            if t_min < 1.0 and i_max == n_samples - 1:
+                if t_xl <= t_min:
+                    i_new = _argmin(all_t_xl)
+                    step[i_new] = xl[i_new]
+                    free_xl[i_new] = False
+                if t_xu <= t_min:
+                    i_new = _argmin(all_t_xu)
+                    step[i_new] = xu[i_new]
+                    free_xl[i_new] = False
+                if t_ub <= t_min:
+                    i_new = _argmin(all_t_ub)
+                    free_ub[i_new] = False
+                n_act, q = qr_tangential_byrd_omojokun(
+                    aub,
+                    aeq,
+                    free_xl,
+                    free_xu,
+                    free_ub,
+                )
+            else:
+                break
+
+        # Ensure that the alternative iteration improves the objective
+        # function.
+        if grad_orig @ step + 0.5 * step @ hess_prod(
+            step
+        ) > grad_orig @ step_base + 0.5 * step_base @ hess_prod(step_base):
+            step = step_base
+
+    if debug:
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.all(aub @ step <= bub + tol)
+        assert np.all(np.abs(aeq @ step) <= tol)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def normal_byrd_omojokun(aub, bub, aeq, beq, xl, xu, delta, debug, **kwargs):
+    r"""
+    Minimize approximately a linear constraint violation subject to bound
+    constraints in a trust region.
+
+    This function solves approximately
+
+    .. math::
+
+        \min_{s \in \mathbb{R}^n} \quad \frac{1}{2} \big( \lVert \max \{
+        A_{\scriptscriptstyle I} s - b_{\scriptscriptstyle I}, 0 \} \rVert^2 +
+        \lVert A_{\scriptscriptstyle E} s - b_{\scriptscriptstyle E} \rVert^2
+        \big) \quad \text{s.t.}
+        \quad
+        \left\{ \begin{array}{l}
+            l \le s \le u,\\
+            \lVert s \rVert \le \Delta,
+        \end{array} \right.
+
+    using a variation of the truncated conjugate gradient method.
+
+    Parameters
+    ----------
+    aub : `numpy.ndarray`, shape (m_linear_ub, n)
+        Matrix :math:`A_{\scriptscriptstyle I}` as shown above.
+    bub : `numpy.ndarray`, shape (m_linear_ub,)
+        Vector :math:`b_{\scriptscriptstyle I}` as shown above.
+    aeq : `numpy.ndarray`, shape (m_linear_eq, n)
+        Matrix :math:`A_{\scriptscriptstyle E}` as shown above.
+    beq : `numpy.ndarray`, shape (m_linear_eq,)
+        Vector :math:`b_{\scriptscriptstyle E}` as shown above.
+    xl : `numpy.ndarray`, shape (n,)
+        Lower bounds :math:`l` as shown above.
+    xu : `numpy.ndarray`, shape (n,)
+        Upper bounds :math:`u` as shown above.
+    delta : float
+        Trust-region radius :math:`\Delta` as shown above.
+    debug : bool
+        Whether to make debugging tests during the execution.
+
+    Returns
+    -------
+    `numpy.ndarray`, shape (n,)
+        Approximate solution :math:`s`.
+
+    Other Parameters
+    ----------------
+    improve_tcg : bool, optional
+        If True, a solution generated by the truncated conjugate gradient
+        method that is on the boundary of the trust region is improved by
+        moving around the trust-region boundary on the two-dimensional space
+        spanned by the solution and the gradient of the quadratic function at
+        the solution (default is True).
+
+    Notes
+    -----
+    This function implements Algorithm 6.4 of [1]_. It is assumed that the
+    origin is feasible with respect to the bound constraints and that `delta`
+    is finite and positive.
+
+    References
+    ----------
+    .. [1] T. M. Ragonneau. *Model-Based Derivative-Free Optimization Methods
+       and Software*. PhD thesis, Department of Applied Mathematics, The Hong
+       Kong Polytechnic University, Hong Kong, China, 2022. URL:
+       https://theses.lib.polyu.edu.hk/handle/200/12294.
+    """
+    if debug:
+        assert isinstance(aub, np.ndarray) and aub.ndim == 2
+        assert (
+            isinstance(bub, np.ndarray)
+            and bub.ndim == 1
+            and bub.size == aub.shape[0]
+        )
+        assert (
+            isinstance(aeq, np.ndarray)
+            and aeq.ndim == 2
+            and aeq.shape[1] == aub.shape[1]
+        )
+        assert (
+            isinstance(beq, np.ndarray)
+            and beq.ndim == 1
+            and beq.size == aeq.shape[0]
+        )
+        assert isinstance(xl, np.ndarray) and xl.shape == (aub.shape[1],)
+        assert isinstance(xu, np.ndarray) and xu.shape == (aub.shape[1],)
+        assert isinstance(delta, float)
+        assert isinstance(debug, bool)
+        tol = get_arrays_tol(xl, xu)
+        assert np.all(xl <= tol)
+        assert np.all(xu >= -tol)
+        assert np.isfinite(delta) and delta > 0.0
+    xl = np.minimum(xl, 0.0)
+    xu = np.maximum(xu, 0.0)
+
+    # Calculate the initial active set.
+    m_linear_ub, n = aub.shape
+    grad = np.r_[aeq.T @ -beq, np.maximum(0.0, -bub)]
+    free_xl = (xl < 0.0) | (grad[:n] < 0.0)
+    free_xu = (xu > 0.0) | (grad[:n] > 0.0)
+    free_slack = bub < 0.0
+    free_ub = (bub > 0.0) | (aub @ grad[:n] - grad[n:] > 0.0)
+    n_act, q = qr_normal_byrd_omojokun(
+        aub,
+        free_xl,
+        free_xu,
+        free_slack,
+        free_ub,
+    )
+
+    # Calculate an upper bound on the norm of the slack variables. It is not
+    # used in the original algorithm, but it may prevent undesired behaviors
+    # engendered by computer rounding errors.
+    delta_slack = np.sqrt(beq @ beq + grad[n:] @ grad[n:])
+
+    # Set the initial iterate and the initial search direction.
+    step = np.zeros(n)
+    sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
+    resid = bub + grad[n:]
+
+    k = 0
+    reduct = 0.0
+    boundary_reached = False
+    while k < n + m_linear_ub - n_act:
+        # Stop the computations if sd is not a descent direction.
+        grad_sd = grad @ sd
+        if grad_sd >= -10.0 * EPS * n * max(1.0, np.linalg.norm(grad)):
+            break
+
+        # Set alpha_tr to the step size for the trust-region constraint.
+        try:
+            alpha_tr = _alpha_tr(step, sd[:n], delta)
+        except ZeroDivisionError:
+            alpha_tr = np.inf
+
+        # Prevent undesired behaviors engendered by computer rounding errors by
+        # considering the trust-region constraint on the slack variables.
+        try:
+            alpha_tr = min(alpha_tr, _alpha_tr(grad[n:], sd[n:], delta_slack))
+        except ZeroDivisionError:
+            pass
+
+        # Stop the computations if a step along sd is expected to give a
+        # relatively small reduction in the objective function.
+        if -alpha_tr * grad_sd <= 1e-8 * reduct:
+            break
+
+        # Set alpha_quad to the step size for the minimization problem.
+        hess_sd = np.r_[aeq.T @ (aeq @ sd[:n]), sd[n:]]
+        curv_sd = sd @ hess_sd
+        if curv_sd > TINY * abs(grad_sd):
+            alpha_quad = max(-grad_sd / curv_sd, 0.0)
+        else:
+            alpha_quad = np.inf
+
+        # Stop the computations if the reduction in the objective function
+        # provided by an unconstrained step is small.
+        alpha = min(alpha_tr, alpha_quad)
+        if -alpha * (grad_sd + 0.5 * alpha * curv_sd) <= 1e-8 * reduct:
+            break
+
+        # Set alpha_bd to the step size for the bound constraints.
+        i_xl = free_xl & (xl > -np.inf) & (sd[:n] < -TINY * np.abs(xl - step))
+        i_xu = free_xu & (xu < np.inf) & (sd[:n] > TINY * np.abs(xu - step))
+        i_slack = free_slack & (sd[n:] < -TINY * np.abs(grad[n:]))
+        all_alpha_xl = np.full_like(step, np.inf)
+        all_alpha_xu = np.full_like(step, np.inf)
+        all_alpha_slack = np.full_like(bub, np.inf)
+        all_alpha_xl[i_xl] = np.maximum(
+            (xl[i_xl] - step[i_xl]) / sd[:n][i_xl],
+            0.0,
+        )
+        all_alpha_xu[i_xu] = np.maximum(
+            (xu[i_xu] - step[i_xu]) / sd[:n][i_xu],
+            0.0,
+        )
+        all_alpha_slack[i_slack] = np.maximum(
+            -grad[n:][i_slack] / sd[n:][i_slack],
+            0.0,
+        )
+        alpha_xl = np.min(all_alpha_xl)
+        alpha_xu = np.min(all_alpha_xu)
+        alpha_slack = np.min(all_alpha_slack, initial=np.inf)
+        alpha_bd = min(alpha_xl, alpha_xu, alpha_slack)
+
+        # Set alpha_ub to the step size for the linear constraints.
+        aub_sd = aub @ sd[:n] - sd[n:]
+        i_ub = free_ub & (aub_sd > TINY * np.abs(resid))
+        all_alpha_ub = np.full_like(bub, np.inf)
+        all_alpha_ub[i_ub] = resid[i_ub] / aub_sd[i_ub]
+        alpha_ub = np.min(all_alpha_ub, initial=np.inf)
+
+        # Update the iterate.
+        alpha = min(alpha, alpha_bd, alpha_ub)
+        if alpha > 0.0:
+            step = np.clip(step + alpha * sd[:n], xl, xu)
+            grad += alpha * hess_sd
+            resid = np.maximum(0.0, resid - alpha * aub_sd)
+            reduct -= alpha * (grad_sd + 0.5 * alpha * curv_sd)
+
+        if alpha < min(alpha_tr, alpha_bd, alpha_ub):
+            # The current iteration is a conjugate gradient iteration. Update
+            # the search direction so that it is conjugate (with respect to H)
+            # to all the previous search directions.
+            grad_proj = q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            beta = (grad_proj @ hess_sd) / curv_sd
+            sd = beta * sd - grad_proj
+            k += 1
+        elif alpha < alpha_tr:
+            # The iterate is restricted by a bound/linear constraint. Add this
+            # constraint to the active set, and restart the calculations.
+            if alpha_xl <= alpha:
+                i_new = np.argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_xl[i_new] = False
+            elif alpha_xu <= alpha:
+                i_new = np.argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_xu[i_new] = False
+            elif alpha_slack <= alpha:
+                i_new = np.argmin(all_alpha_slack)
+                free_slack[i_new] = False
+            else:
+                i_new = np.argmin(all_alpha_ub)
+                free_ub[i_new] = False
+            n_act, q = qr_normal_byrd_omojokun(
+                aub, free_xl, free_xu, free_slack, free_ub
+            )
+            sd = -q[:, n_act:] @ (q[:, n_act:].T @ grad)
+            k = 0
+        else:
+            # The current iterate is on the trust-region boundary. Add all the
+            # active bound constraints to the working set to prepare for the
+            # improvement of the solution, and stop the iterations.
+            if alpha_xl <= alpha:
+                i_new = _argmin(all_alpha_xl)
+                step[i_new] = xl[i_new]
+                free_xl[i_new] = False
+            if alpha_xu <= alpha:
+                i_new = _argmin(all_alpha_xu)
+                step[i_new] = xu[i_new]
+                free_xu[i_new] = False
+            boundary_reached = True
+            break
+
+    # Attempt to improve the solution on the trust-region boundary.
+    if kwargs.get("improve_tcg", True) and boundary_reached:
+        step_base = np.copy(step)
+        free_bd = free_xl & free_xu
+        grad = aub.T @ np.maximum(aub @ step - bub, 0.0) + aeq.T @ (
+            aeq @ step - beq
+        )
+        sd = np.zeros(n)
+        while np.count_nonzero(free_bd) > 0:
+            # Check whether a substantial reduction in the objective function
+            # is possible, and set the search direction.
+            step_sq = step[free_bd] @ step[free_bd]
+            grad_sq = grad[free_bd] @ grad[free_bd]
+            grad_step = grad[free_bd] @ step[free_bd]
+            grad_sd = -np.sqrt(max(step_sq * grad_sq - grad_step**2.0, 0.0))
+            sd[free_bd] = grad_step * step[free_bd] - step_sq * grad[free_bd]
+            sd[~free_bd] = 0.0
+            if grad_sd >= -1e-8 * reduct or np.any(
+                grad_sd >= -TINY * np.abs(sd[free_bd])
+            ):
+                break
+            sd[free_bd] /= -grad_sd
+
+            # Calculate an upper bound for the tangent of half the angle theta
+            # of this alternative iteration. The step will be updated as:
+            # step = cos(theta) * step + sin(theta) * sd.
+            temp_xl = np.zeros(n)
+            temp_xu = np.zeros(n)
+            temp_xl[free_bd] = (
+                step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xl[free_bd] ** 2.0
+            )
+            temp_xu[free_bd] = (
+                step[free_bd] ** 2.0 + sd[free_bd] ** 2.0 - xu[free_bd] ** 2.0
+            )
+            temp_xl[temp_xl > 0.0] = (
+                np.sqrt(temp_xl[temp_xl > 0.0]) - sd[temp_xl > 0.0]
+            )
+            temp_xu[temp_xu > 0.0] = (
+                np.sqrt(temp_xu[temp_xu > 0.0]) + sd[temp_xu > 0.0]
+            )
+            dist_xl = np.maximum(step - xl, 0.0)
+            dist_xu = np.maximum(xu - step, 0.0)
+            i_xl = temp_xl > TINY * dist_xl
+            i_xu = temp_xu > TINY * dist_xu
+            all_t_xl = np.ones(n)
+            all_t_xu = np.ones(n)
+            all_t_xl[i_xl] = np.minimum(
+                all_t_xl[i_xl],
+                dist_xl[i_xl] / temp_xl[i_xl],
+            )
+            all_t_xu[i_xu] = np.minimum(
+                all_t_xu[i_xu],
+                dist_xu[i_xu] / temp_xu[i_xu],
+            )
+            t_xl = np.min(all_t_xl)
+            t_xu = np.min(all_t_xu)
+            t_bd = min(t_xl, t_xu)
+
+            # For a range of equally spaced values of tan(0.5 * theta),
+            # calculate the reduction in the objective function that would be
+            # obtained by accepting the corresponding angle.
+            n_samples = 20
+            n_samples = int((n_samples - 3) * t_bd + 3)
+            t_samples = np.linspace(t_bd / n_samples, t_bd, n_samples)
+            resid_ub = np.maximum(aub @ step - bub, 0.0)
+            resid_eq = aeq @ step - beq
+            step_proj = np.copy(step)
+            step_proj[~free_bd] = 0.0
+            all_reduct = np.empty(n_samples)
+            for i in range(n_samples):
+                sin_value = 2.0 * t_samples[i] / (1.0 + t_samples[i] ** 2.0)
+                step_alt = np.clip(
+                    step + sin_value * (sd - t_samples[i] * step_proj),
+                    xl,
+                    xu,
+                )
+                resid_ub_alt = np.maximum(aub @ step_alt - bub, 0.0)
+                resid_eq_alt = aeq @ step_alt - beq
+                all_reduct[i] = 0.5 * (
+                    resid_ub @ resid_ub
+                    + resid_eq @ resid_eq
+                    - resid_ub_alt @ resid_ub_alt
+                    - resid_eq_alt @ resid_eq_alt
+                )
+            if np.all(all_reduct <= 0.0):
+                # No reduction in the objective function is obtained.
+                break
+
+            # Accept the angle that provides the largest reduction in the
+            # objective function, and update the iterate.
+            i_max = np.argmax(all_reduct)
+            cos_value = (1.0 - t_samples[i_max] ** 2.0) / (
+                1.0 + t_samples[i_max] ** 2.0
+            )
+            sin_value = (2.0 * t_samples[i_max]
+                         / (1.0 + t_samples[i_max] ** 2.0))
+            step[free_bd] = cos_value * step[free_bd] + sin_value * sd[free_bd]
+            grad = aub.T @ np.maximum(aub @ step - bub, 0.0) + aeq.T @ (
+                aeq @ step - beq
+            )
+            reduct += all_reduct[i_max]
+
+            # If the above angle is restricted by bound constraints, add them
+            # to the working set, and restart the alternative iteration.
+            # Otherwise, the calculations are terminated.
+            if t_bd < 1.0 and i_max == n_samples - 1:
+                if t_xl <= t_bd:
+                    i_new = _argmin(all_t_xl)
+                    step[i_new] = xl[i_new]
+                    free_bd[i_new] = False
+                if t_xu <= t_bd:
+                    i_new = _argmin(all_t_xu)
+                    step[i_new] = xu[i_new]
+                    free_bd[i_new] = False
+            else:
+                break
+
+        # Ensure that the alternative iteration improves the objective
+        # function.
+        resid_ub = np.maximum(aub @ step - bub, 0.0)
+        resid_ub_base = np.maximum(aub @ step_base - bub, 0.0)
+        resid_eq = aeq @ step - beq
+        resid_eq_base = aeq @ step_base - beq
+        if (
+            resid_ub @ resid_ub + resid_eq @ resid_eq
+            > resid_ub_base @ resid_ub_base + resid_eq_base @ resid_eq_base
+        ):
+            step = step_base
+
+    if debug:
+        assert np.all(xl <= step)
+        assert np.all(step <= xu)
+        assert np.linalg.norm(step) < 1.1 * delta
+    return step
+
+
+def qr_tangential_byrd_omojokun(aub, aeq, free_xl, free_xu, free_ub):
+    n = free_xl.size
+    identity = np.eye(n)
+    q, r, _ = qr(
+        np.block(
+            [
+                [aeq],
+                [aub[~free_ub, :]],
+                [-identity[~free_xl, :]],
+                [identity[~free_xu, :]],
+            ]
+        ).T,
+        pivoting=True,
+    )
+    n_act = np.count_nonzero(
+        np.abs(np.diag(r))
+        >= 10.0
+        * EPS
+        * n
+        * np.linalg.norm(r[: np.min(r.shape), : np.min(r.shape)], axis=0)
+    )
+    return n_act, q
+
+
+def qr_normal_byrd_omojokun(aub, free_xl, free_xu, free_slack, free_ub):
+    m_linear_ub, n = aub.shape
+    identity_n = np.eye(n)
+    identity_m = np.eye(m_linear_ub)
+    q, r, _ = qr(
+        np.block(
+            [
+                [
+                    aub[~free_ub, :],
+                    -identity_m[~free_ub, :],
+                ],
+                [
+                    np.zeros((m_linear_ub - np.count_nonzero(free_slack), n)),
+                    -identity_m[~free_slack, :],
+                ],
+                [
+                    -identity_n[~free_xl, :],
+                    np.zeros((n - np.count_nonzero(free_xl), m_linear_ub)),
+                ],
+                [
+                    identity_n[~free_xu, :],
+                    np.zeros((n - np.count_nonzero(free_xu), m_linear_ub)),
+                ],
+            ]
+        ).T,
+        pivoting=True,
+    )
+    n_act = np.count_nonzero(
+        np.abs(np.diag(r))
+        >= 10.0
+        * EPS
+        * (n + m_linear_ub)
+        * np.linalg.norm(r[: np.min(r.shape), : np.min(r.shape)], axis=0)
+    )
+    return n_act, q
+
+
+def _alpha_tr(step, sd, delta):
+    step_sd = step @ sd
+    sd_sq = sd @ sd
+    dist_tr_sq = delta**2.0 - step @ step
+    temp = np.sqrt(max(step_sd**2.0 + sd_sq * dist_tr_sq, 0.0))
+    if step_sd <= 0.0 and sd_sq > TINY * abs(temp - step_sd):
+        alpha_tr = max((temp - step_sd) / sd_sq, 0.0)
+    elif abs(temp + step_sd) > TINY * dist_tr_sq:
+        alpha_tr = max(dist_tr_sq / (temp + step_sd), 0.0)
+    else:
+        raise ZeroDivisionError
+    return alpha_tr
+
+
+def _argmax(x):
+    return np.flatnonzero(x >= np.max(x))
+
+
+def _argmin(x):
+    return np.flatnonzero(x <= np.min(x))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe6b4841ddff3a04bda5cbff744e30681b6963b9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/__init__.py
@@ -0,0 +1,18 @@
+from .exceptions import (
+    MaxEvalError,
+    TargetSuccess,
+    CallbackSuccess,
+    FeasibleSuccess,
+)
+from .math import get_arrays_tol, exact_1d_array
+from .versions import show_versions
+
+__all__ = [
+    "MaxEvalError",
+    "TargetSuccess",
+    "CallbackSuccess",
+    "FeasibleSuccess",
+    "get_arrays_tol",
+    "exact_1d_array",
+    "show_versions",
+]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/exceptions.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..c85094894f378a8e3934ad109ea6166e33e4366b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/exceptions.py
@@ -0,0 +1,22 @@
+class MaxEvalError(Exception):
+    """
+    Exception raised when the maximum number of evaluations is reached.
+    """
+
+
+class TargetSuccess(Exception):
+    """
+    Exception raised when the target value is reached.
+    """
+
+
+class CallbackSuccess(StopIteration):
+    """
+    Exception raised when the callback function raises a ``StopIteration``.
+    """
+
+
+class FeasibleSuccess(Exception):
+    """
+    Exception raised when a feasible point of a feasible problem is found.
+    """
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/math.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/math.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b16ae98a0df38752815f5a69d56da20f856f9f9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/math.py
@@ -0,0 +1,77 @@
+import numpy as np
+
+
+EPS = np.finfo(float).eps
+
+
+def get_arrays_tol(*arrays):
+    """
+    Get a relative tolerance for a set of arrays.
+
+    Parameters
+    ----------
+    *arrays: tuple
+        Set of `numpy.ndarray` to get the tolerance for.
+
+    Returns
+    -------
+    float
+        Relative tolerance for the set of arrays.
+
+    Raises
+    ------
+    ValueError
+        If no array is provided.
+    """
+    if len(arrays) == 0:
+        raise ValueError("At least one array must be provided.")
+    size = max(array.size for array in arrays)
+    weight = max(
+        np.max(np.abs(array[np.isfinite(array)]), initial=1.0)
+        for array in arrays
+    )
+    return 10.0 * EPS * max(size, 1.0) * weight
+
+
+def exact_1d_array(x, message):
+    """
+    Preprocess a 1-dimensional array.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to be preprocessed.
+    message : str
+        Error message if `x` cannot be interpreter as a 1-dimensional array.
+
+    Returns
+    -------
+    `numpy.ndarray`
+        Preprocessed array.
+    """
+    x = np.atleast_1d(np.squeeze(x)).astype(float)
+    if x.ndim != 1:
+        raise ValueError(message)
+    return x
+
+
+def exact_2d_array(x, message):
+    """
+    Preprocess a 2-dimensional array.
+
+    Parameters
+    ----------
+    x : array_like
+        Array to be preprocessed.
+    message : str
+        Error message if `x` cannot be interpreter as a 2-dimensional array.
+
+    Returns
+    -------
+    `numpy.ndarray`
+        Preprocessed array.
+    """
+    x = np.atleast_2d(x).astype(float)
+    if x.ndim != 2:
+        raise ValueError(message)
+    return x
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/versions.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/versions.py
new file mode 100644
index 0000000000000000000000000000000000000000..94a0f8f5cef626354f40901cbe06a84287291c1c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/cobyqa/utils/versions.py
@@ -0,0 +1,67 @@
+import os
+import platform
+import sys
+from importlib.metadata import PackageNotFoundError, version
+
+
+def _get_sys_info():
+    """
+    Get useful system information.
+
+    Returns
+    -------
+    dict
+        Useful system information.
+    """
+    return {
+        "python": sys.version.replace(os.linesep, " "),
+        "executable": sys.executable,
+        "machine": platform.platform(),
+    }
+
+
+def _get_deps_info():
+    """
+    Get the versions of the dependencies.
+
+    Returns
+    -------
+    dict
+        Versions of the dependencies.
+    """
+    deps = ["cobyqa", "numpy", "scipy", "setuptools", "pip"]
+    deps_info = {}
+    for module in deps:
+        try:
+            deps_info[module] = version(module)
+        except PackageNotFoundError:
+            deps_info[module] = None
+    return deps_info
+
+
+def show_versions():
+    """
+    Display useful system and dependencies information.
+
+    When reporting issues, please include this information.
+    """
+    print("System settings")
+    print("---------------")
+    sys_info = _get_sys_info()
+    print(
+        "\n".join(
+            f"{k:>{max(map(len, sys_info.keys())) + 1}}: {v}"
+            for k, v in sys_info.items()
+        )
+    )
+
+    print()
+    print("Python dependencies")
+    print("-------------------")
+    deps_info = _get_deps_info()
+    print(
+        "\n".join(
+            f"{k:>{max(map(len, deps_info.keys())) + 1}}: {v}"
+            for k, v in deps_info.items()
+        )
+    )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/decorator.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c4ab90e3d52db448b6381bc7860f55ac8789c9c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/decorator.py
@@ -0,0 +1,399 @@
+# #########################     LICENSE     ############################ #
+
+# Copyright (c) 2005-2015, Michele Simionato
+# All rights reserved.
+
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+
+#   Redistributions of source code must retain the above copyright
+#   notice, this list of conditions and the following disclaimer.
+#   Redistributions in bytecode form must reproduce the above copyright
+#   notice, this list of conditions and the following disclaimer in
+#   the documentation and/or other materials provided with the
+#   distribution.
+
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+# DAMAGE.
+
+"""
+Decorator module, see https://pypi.python.org/pypi/decorator
+for the documentation.
+"""
+import re
+import sys
+import inspect
+import operator
+import itertools
+import collections
+
+from inspect import getfullargspec
+
+__version__ = '4.0.5'
+
+
+def get_init(cls):
+    return cls.__init__
+
+
+# getargspec has been deprecated in Python 3.5
+ArgSpec = collections.namedtuple(
+    'ArgSpec', 'args varargs varkw defaults')
+
+
+def getargspec(f):
+    """A replacement for inspect.getargspec"""
+    spec = getfullargspec(f)
+    return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
+
+
+DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(')
+
+
+# basic functionality
+class FunctionMaker:
+    """
+    An object with the ability to create functions with a given signature.
+    It has attributes name, doc, module, signature, defaults, dict, and
+    methods update and make.
+    """
+
+    # Atomic get-and-increment provided by the GIL
+    _compile_count = itertools.count()
+
+    def __init__(self, func=None, name=None, signature=None,
+                 defaults=None, doc=None, module=None, funcdict=None):
+        self.shortsignature = signature
+        if func:
+            # func can be a class or a callable, but not an instance method
+            self.name = func.__name__
+            if self.name == '':  # small hack for lambda functions
+                self.name = '_lambda_'
+            self.doc = func.__doc__
+            self.module = func.__module__
+            if inspect.isfunction(func):
+                argspec = getfullargspec(func)
+                self.annotations = getattr(func, '__annotations__', {})
+                for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
+                          'kwonlydefaults'):
+                    setattr(self, a, getattr(argspec, a))
+                for i, arg in enumerate(self.args):
+                    setattr(self, 'arg%d' % i, arg)
+                allargs = list(self.args)
+                allshortargs = list(self.args)
+                if self.varargs:
+                    allargs.append('*' + self.varargs)
+                    allshortargs.append('*' + self.varargs)
+                elif self.kwonlyargs:
+                    allargs.append('*')  # single star syntax
+                for a in self.kwonlyargs:
+                    allargs.append(f'{a}=None')
+                    allshortargs.append(f'{a}={a}')
+                if self.varkw:
+                    allargs.append('**' + self.varkw)
+                    allshortargs.append('**' + self.varkw)
+                self.signature = ', '.join(allargs)
+                self.shortsignature = ', '.join(allshortargs)
+                self.dict = func.__dict__.copy()
+        # func=None happens when decorating a caller
+        if name:
+            self.name = name
+        if signature is not None:
+            self.signature = signature
+        if defaults:
+            self.defaults = defaults
+        if doc:
+            self.doc = doc
+        if module:
+            self.module = module
+        if funcdict:
+            self.dict = funcdict
+        # check existence required attributes
+        assert hasattr(self, 'name')
+        if not hasattr(self, 'signature'):
+            raise TypeError(f'You are decorating a non-function: {func}')
+
+    def update(self, func, **kw):
+        "Update the signature of func with the data in self"
+        func.__name__ = self.name
+        func.__doc__ = getattr(self, 'doc', None)
+        func.__dict__ = getattr(self, 'dict', {})
+        func.__defaults__ = getattr(self, 'defaults', ())
+        func.__kwdefaults__ = getattr(self, 'kwonlydefaults', None)
+        func.__annotations__ = getattr(self, 'annotations', None)
+        try:
+            frame = sys._getframe(3)
+        except AttributeError:  # for IronPython and similar implementations
+            callermodule = '?'
+        else:
+            callermodule = frame.f_globals.get('__name__', '?')
+        func.__module__ = getattr(self, 'module', callermodule)
+        func.__dict__.update(kw)
+
+    def make(self, src_templ, evaldict=None, addsource=False, **attrs):
+        "Make a new function from a given template and update the signature"
+        src = src_templ % vars(self)  # expand name and signature
+        evaldict = evaldict or {}
+        mo = DEF.match(src)
+        if mo is None:
+            raise SyntaxError(f'not a valid function template\n{src}')
+        name = mo.group(1)  # extract the function name
+        names = set([name] + [arg.strip(' *') for arg in
+                              self.shortsignature.split(',')])
+        for n in names:
+            if n in ('_func_', '_call_'):
+                raise NameError(f'{n} is overridden in\n{src}')
+        if not src.endswith('\n'):  # add a newline just for safety
+            src += '\n'  # this is needed in old versions of Python
+
+        # Ensure each generated function has a unique filename for profilers
+        # (such as cProfile) that depend on the tuple of (,
+        # , ) being unique.
+        filename = '' % (next(self._compile_count),)
+        try:
+            code = compile(src, filename, 'single')
+            exec(code, evaldict)
+        except:  # noqa: E722
+            print('Error in generated code:', file=sys.stderr)
+            print(src, file=sys.stderr)
+            raise
+        func = evaldict[name]
+        if addsource:
+            attrs['__source__'] = src
+        self.update(func, **attrs)
+        return func
+
+    @classmethod
+    def create(cls, obj, body, evaldict, defaults=None,
+               doc=None, module=None, addsource=True, **attrs):
+        """
+        Create a function from the strings name, signature, and body.
+        evaldict is the evaluation dictionary. If addsource is true, an
+        attribute __source__ is added to the result. The attributes attrs
+        are added, if any.
+        """
+        if isinstance(obj, str):  # "name(signature)"
+            name, rest = obj.strip().split('(', 1)
+            signature = rest[:-1]  # strip a right parens
+            func = None
+        else:  # a function
+            name = None
+            signature = None
+            func = obj
+        self = cls(func, name, signature, defaults, doc, module)
+        ibody = '\n'.join('    ' + line for line in body.splitlines())
+        return self.make('def %(name)s(%(signature)s):\n' + ibody,
+                         evaldict, addsource, **attrs)
+
+
+def decorate(func, caller):
+    """
+    decorate(func, caller) decorates a function using a caller.
+    """
+    evaldict = func.__globals__.copy()
+    evaldict['_call_'] = caller
+    evaldict['_func_'] = func
+    fun = FunctionMaker.create(
+        func, "return _call_(_func_, %(shortsignature)s)",
+        evaldict, __wrapped__=func)
+    if hasattr(func, '__qualname__'):
+        fun.__qualname__ = func.__qualname__
+    return fun
+
+
+def decorator(caller, _func=None):
+    """decorator(caller) converts a caller function into a decorator"""
+    if _func is not None:  # return a decorated function
+        # this is obsolete behavior; you should use decorate instead
+        return decorate(_func, caller)
+    # else return a decorator function
+    if inspect.isclass(caller):
+        name = caller.__name__.lower()
+        callerfunc = get_init(caller)
+        doc = (f'decorator({caller.__name__}) converts functions/generators into ' 
+               f'factories of {caller.__name__} objects')
+    elif inspect.isfunction(caller):
+        if caller.__name__ == '':
+            name = '_lambda_'
+        else:
+            name = caller.__name__
+        callerfunc = caller
+        doc = caller.__doc__
+    else:  # assume caller is an object with a __call__ method
+        name = caller.__class__.__name__.lower()
+        callerfunc = caller.__call__.__func__
+        doc = caller.__call__.__doc__
+    evaldict = callerfunc.__globals__.copy()
+    evaldict['_call_'] = caller
+    evaldict['_decorate_'] = decorate
+    return FunctionMaker.create(
+        f'{name}(func)', 'return _decorate_(func, _call_)',
+        evaldict, doc=doc, module=caller.__module__,
+        __wrapped__=caller)
+
+
+# ####################### contextmanager ####################### #
+
+try:  # Python >= 3.2
+    from contextlib import _GeneratorContextManager
+except ImportError:  # Python >= 2.5
+    from contextlib import GeneratorContextManager as _GeneratorContextManager
+
+
+class ContextManager(_GeneratorContextManager):
+    def __call__(self, func):
+        """Context manager decorator"""
+        return FunctionMaker.create(
+            func, "with _self_: return _func_(%(shortsignature)s)",
+            dict(_self_=self, _func_=func), __wrapped__=func)
+
+
+init = getfullargspec(_GeneratorContextManager.__init__)
+n_args = len(init.args)
+if n_args == 2 and not init.varargs:  # (self, genobj) Python 2.7
+    def __init__(self, g, *a, **k):
+        return _GeneratorContextManager.__init__(self, g(*a, **k))
+    ContextManager.__init__ = __init__
+elif n_args == 2 and init.varargs:  # (self, gen, *a, **k) Python 3.4
+    pass
+elif n_args == 4:  # (self, gen, args, kwds) Python 3.5
+    def __init__(self, g, *a, **k):
+        return _GeneratorContextManager.__init__(self, g, a, k)
+    ContextManager.__init__ = __init__
+
+contextmanager = decorator(ContextManager)
+
+
+# ############################ dispatch_on ############################ #
+
+def append(a, vancestors):
+    """
+    Append ``a`` to the list of the virtual ancestors, unless it is already
+    included.
+    """
+    add = True
+    for j, va in enumerate(vancestors):
+        if issubclass(va, a):
+            add = False
+            break
+        if issubclass(a, va):
+            vancestors[j] = a
+            add = False
+    if add:
+        vancestors.append(a)
+
+
+# inspired from simplegeneric by P.J. Eby and functools.singledispatch
+def dispatch_on(*dispatch_args):
+    """
+    Factory of decorators turning a function into a generic function
+    dispatching on the given arguments.
+    """
+    assert dispatch_args, 'No dispatch args passed'
+    dispatch_str = f"({', '.join(dispatch_args)},)"
+
+    def check(arguments, wrong=operator.ne, msg=''):
+        """Make sure one passes the expected number of arguments"""
+        if wrong(len(arguments), len(dispatch_args)):
+            raise TypeError(f'Expected {len(dispatch_args)} arguments, '
+                            'got {len(arguments)}{msg}')
+
+    def gen_func_dec(func):
+        """Decorator turning a function into a generic function"""
+
+        # first check the dispatch arguments
+        argset = set(getfullargspec(func).args)
+        if not set(dispatch_args) <= argset:
+            raise NameError(f'Unknown dispatch arguments {dispatch_str}')
+
+        typemap = {}
+
+        def vancestors(*types):
+            """
+            Get a list of sets of virtual ancestors for the given types
+            """
+            check(types)
+            ras = [[] for _ in range(len(dispatch_args))]
+            for types_ in typemap:
+                for t, type_, ra in zip(types, types_, ras):
+                    if issubclass(t, type_) and type_ not in t.__mro__:
+                        append(type_, ra)
+            return [set(ra) for ra in ras]
+
+        def ancestors(*types):
+            """
+            Get a list of virtual MROs, one for each type
+            """
+            check(types)
+            lists = []
+            for t, vas in zip(types, vancestors(*types)):
+                n_vas = len(vas)
+                if n_vas > 1:
+                    raise RuntimeError(
+                        f'Ambiguous dispatch for {t}: {vas}')
+                elif n_vas == 1:
+                    va, = vas
+                    mro = type('t', (t, va), {}).__mro__[1:]
+                else:
+                    mro = t.__mro__
+                lists.append(mro[:-1])  # discard t and object
+            return lists
+
+        def register(*types):
+            """
+            Decorator to register an implementation for the given types
+            """
+            check(types)
+
+            def dec(f):
+                check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__)
+                typemap[types] = f
+                return f
+            return dec
+
+        def dispatch_info(*types):
+            """
+            An utility to introspect the dispatch algorithm
+            """
+            check(types)
+            lst = [tuple(a.__name__ for a in anc)
+                   for anc in itertools.product(*ancestors(*types))]
+            return lst
+
+        def _dispatch(dispatch_args, *args, **kw):
+            types = tuple(type(arg) for arg in dispatch_args)
+            try:  # fast path
+                f = typemap[types]
+            except KeyError:
+                pass
+            else:
+                return f(*args, **kw)
+            combinations = itertools.product(*ancestors(*types))
+            next(combinations)  # the first one has been already tried
+            for types_ in combinations:
+                f = typemap.get(types_)
+                if f is not None:
+                    return f(*args, **kw)
+
+            # else call the default implementation
+            return func(*args, **kw)
+
+        return FunctionMaker.create(
+            func, f'return _f_({dispatch_str}, %%(shortsignature)s)',
+            dict(_f_=_dispatch), register=register, default=func,
+            typemap=typemap, vancestors=vancestors, ancestors=ancestors,
+            dispatch_info=dispatch_info, __wrapped__=func)
+
+    gen_func_dec.__name__ = 'dispatch_on' + dispatch_str
+    return gen_func_dec
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/deprecation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..82a6ef8f39ba764b46fdc01de9281cdbf72f4736
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/deprecation.py
@@ -0,0 +1,274 @@
+from inspect import Parameter, signature
+import functools
+import warnings
+from importlib import import_module
+from scipy._lib._docscrape import FunctionDoc
+
+
+__all__ = ["_deprecated"]
+
+
+# Object to use as default value for arguments to be deprecated. This should
+# be used over 'None' as the user could parse 'None' as a positional argument
+_NoValue = object()
+
+def _sub_module_deprecation(*, sub_package, module, private_modules, all,
+                            attribute, correct_module=None, dep_version="1.16.0"):
+    """Helper function for deprecating modules that are public but were
+    intended to be private.
+
+    Parameters
+    ----------
+    sub_package : str
+        Subpackage the module belongs to eg. stats
+    module : str
+        Public but intended private module to deprecate
+    private_modules : list
+        Private replacement(s) for `module`; should contain the
+        content of ``all``, possibly spread over several modules.
+    all : list
+        ``__all__`` belonging to `module`
+    attribute : str
+        The attribute in `module` being accessed
+    correct_module : str, optional
+        Module in `sub_package` that `attribute` should be imported from.
+        Default is that `attribute` should be imported from ``scipy.sub_package``.
+    dep_version : str, optional
+        Version in which deprecated attributes will be removed.
+    """
+    if correct_module is not None:
+        correct_import = f"scipy.{sub_package}.{correct_module}"
+    else:
+        correct_import = f"scipy.{sub_package}"
+
+    if attribute not in all:
+        raise AttributeError(
+            f"`scipy.{sub_package}.{module}` has no attribute `{attribute}`; "
+            f"furthermore, `scipy.{sub_package}.{module}` is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+
+    attr = getattr(import_module(correct_import), attribute, None)
+
+    if attr is not None:
+        message = (
+            f"Please import `{attribute}` from the `{correct_import}` namespace; "
+            f"the `scipy.{sub_package}.{module}` namespace is deprecated "
+            f"and will be removed in SciPy 2.0.0."
+        )
+    else:
+        message = (
+            f"`scipy.{sub_package}.{module}.{attribute}` is deprecated along with "
+            f"the `scipy.{sub_package}.{module}` namespace. "
+            f"`scipy.{sub_package}.{module}.{attribute}` will be removed "
+            f"in SciPy {dep_version}, and the `scipy.{sub_package}.{module}` namespace "
+            f"will be removed in SciPy 2.0.0."
+        )
+
+    warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+    for module in private_modules:
+        try:
+            return getattr(import_module(f"scipy.{sub_package}.{module}"), attribute)
+        except AttributeError as e:
+            # still raise an error if the attribute isn't in any of the expected
+            # private modules
+            if module == private_modules[-1]:
+                raise e
+            continue
+    
+
+def _deprecated(msg, stacklevel=2):
+    """Deprecate a function by emitting a warning on use."""
+    def wrap(fun):
+        if isinstance(fun, type):
+            warnings.warn(
+                f"Trying to deprecate class {fun!r}",
+                category=RuntimeWarning, stacklevel=2)
+            return fun
+
+        @functools.wraps(fun)
+        def call(*args, **kwargs):
+            warnings.warn(msg, category=DeprecationWarning,
+                          stacklevel=stacklevel)
+            return fun(*args, **kwargs)
+        call.__doc__ = fun.__doc__
+        return call
+
+    return wrap
+
+
+class _DeprecationHelperStr:
+    """
+    Helper class used by deprecate_cython_api
+    """
+    def __init__(self, content, message):
+        self._content = content
+        self._message = message
+
+    def __hash__(self):
+        return hash(self._content)
+
+    def __eq__(self, other):
+        res = (self._content == other)
+        if res:
+            warnings.warn(self._message, category=DeprecationWarning,
+                          stacklevel=2)
+        return res
+
+
+def deprecate_cython_api(module, routine_name, new_name=None, message=None):
+    """
+    Deprecate an exported cdef function in a public Cython API module.
+
+    Only functions can be deprecated; typedefs etc. cannot.
+
+    Parameters
+    ----------
+    module : module
+        Public Cython API module (e.g. scipy.linalg.cython_blas).
+    routine_name : str
+        Name of the routine to deprecate. May also be a fused-type
+        routine (in which case its all specializations are deprecated).
+    new_name : str
+        New name to include in the deprecation warning message
+    message : str
+        Additional text in the deprecation warning message
+
+    Examples
+    --------
+    Usually, this function would be used in the top-level of the
+    module ``.pyx`` file:
+
+    >>> from scipy._lib.deprecation import deprecate_cython_api
+    >>> import scipy.linalg.cython_blas as mod
+    >>> deprecate_cython_api(mod, "dgemm", "dgemm_new",
+    ...                      message="Deprecated in Scipy 1.5.0")
+    >>> del deprecate_cython_api, mod
+
+    After this, Cython modules that use the deprecated function emit a
+    deprecation warning when they are imported.
+
+    """
+    old_name = f"{module.__name__}.{routine_name}"
+
+    if new_name is None:
+        depdoc = f"`{old_name}` is deprecated!"
+    else:
+        depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!"
+
+    if message is not None:
+        depdoc += "\n" + message
+
+    d = module.__pyx_capi__
+
+    # Check if the function is a fused-type function with a mangled name
+    j = 0
+    has_fused = False
+    while True:
+        fused_name = f"__pyx_fuse_{j}{routine_name}"
+        if fused_name in d:
+            has_fused = True
+            d[_DeprecationHelperStr(fused_name, depdoc)] = d.pop(fused_name)
+            j += 1
+        else:
+            break
+
+    # If not, apply deprecation to the named routine
+    if not has_fused:
+        d[_DeprecationHelperStr(routine_name, depdoc)] = d.pop(routine_name)
+
+
+# taken from scikit-learn, see
+# https://github.com/scikit-learn/scikit-learn/blob/1.3.0/sklearn/utils/validation.py#L38
+def _deprecate_positional_args(func=None, *, version=None,
+                               deprecated_args=None, custom_message=""):
+    """Decorator for methods that issues warnings for positional arguments.
+
+    Using the keyword-only argument syntax in pep 3102, arguments after the
+    * will issue a warning when passed as a positional argument.
+
+    Parameters
+    ----------
+    func : callable, default=None
+        Function to check arguments on.
+    version : callable, default=None
+        The version when positional arguments will result in error.
+    deprecated_args : set of str, optional
+        Arguments to deprecate - whether passed by position or keyword.
+    custom_message : str, optional
+        Custom message to add to deprecation warning and documentation.
+    """
+    if version is None:
+        msg = "Need to specify a version where signature will be changed"
+        raise ValueError(msg)
+
+    deprecated_args = set() if deprecated_args is None else set(deprecated_args)
+
+    def _inner_deprecate_positional_args(f):
+        sig = signature(f)
+        kwonly_args = []
+        all_args = []
+
+        for name, param in sig.parameters.items():
+            if param.kind == Parameter.POSITIONAL_OR_KEYWORD:
+                all_args.append(name)
+            elif param.kind == Parameter.KEYWORD_ONLY:
+                kwonly_args.append(name)
+
+        def warn_deprecated_args(kwargs):
+            intersection = deprecated_args.intersection(kwargs)
+            if intersection:
+                message = (f"Arguments {intersection} are deprecated, whether passed "
+                           "by position or keyword. They will be removed in SciPy "
+                           f"{version}. ")
+                message += custom_message
+                warnings.warn(message, category=DeprecationWarning, stacklevel=3)
+
+        @functools.wraps(f)
+        def inner_f(*args, **kwargs):
+
+            extra_args = len(args) - len(all_args)
+            if extra_args <= 0:
+                warn_deprecated_args(kwargs)
+                return f(*args, **kwargs)
+
+            # extra_args > 0
+            kwonly_extra_args = set(kwonly_args[:extra_args]) - deprecated_args
+            args_msg = ", ".join(kwonly_extra_args)
+            warnings.warn(
+                (
+                    f"You are passing as positional arguments: {args_msg}. "
+                    "Please change your invocation to use keyword arguments. "
+                    f"From SciPy {version}, passing these as positional "
+                    "arguments will result in an error."
+                ),
+                DeprecationWarning,
+                stacklevel=2,
+            )
+            kwargs.update(zip(sig.parameters, args))
+            warn_deprecated_args(kwargs)
+            return f(**kwargs)
+
+        doc = FunctionDoc(inner_f)
+        kwonly_extra_args = set(kwonly_args) - deprecated_args
+        admonition = f"""
+.. deprecated:: {version}
+    Use of argument(s) ``{kwonly_extra_args}`` by position is deprecated; beginning in 
+    SciPy {version}, these will be keyword-only. """
+        if deprecated_args:
+            admonition += (f"Argument(s) ``{deprecated_args}`` are deprecated, whether "
+                           "passed by position or keyword; they will be removed in "
+                           f"SciPy {version}. ")
+        admonition += custom_message
+        doc['Extended Summary'] += [admonition]
+
+        doc = str(doc).split("\n", 1)[1]  # remove signature
+        inner_f.__doc__ = str(doc)
+
+        return inner_f
+
+    if func is not None:
+        return _inner_deprecate_positional_args(func)
+
+    return _inner_deprecate_positional_args
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/doccer.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..538b83c482caba1d4a8a2f64e1ad56da1862e286
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/doccer.py
@@ -0,0 +1,372 @@
+"""Utilities to allow inserting docstring fragments for common
+parameters into function and method docstrings."""
+
+from collections.abc import Callable, Iterable, Mapping
+from typing import Protocol, TypeVar
+import sys
+
+__all__ = [
+    "docformat",
+    "inherit_docstring_from",
+    "indentcount_lines",
+    "filldoc",
+    "unindent_dict",
+    "unindent_string",
+    "extend_notes_in_docstring",
+    "replace_notes_in_docstring",
+    "doc_replace",
+]
+
+_F = TypeVar("_F", bound=Callable[..., object])
+
+
+class Decorator(Protocol):
+    """A decorator of a function."""
+
+    def __call__(self, func: _F, /) -> _F: ...
+
+
+def docformat(docstring: str, docdict: Mapping[str, str] | None = None) -> str:
+    """Fill a function docstring from variables in dictionary.
+
+    Adapt the indent of the inserted docs
+
+    Parameters
+    ----------
+    docstring : str
+        A docstring from a function, possibly with dict formatting strings.
+    docdict : dict[str, str], optional
+        A dictionary with keys that match the dict formatting strings
+        and values that are docstring fragments to be inserted. The
+        indentation of the inserted docstrings is set to match the
+        minimum indentation of the ``docstring`` by adding this
+        indentation to all lines of the inserted string, except the
+        first.
+
+    Returns
+    -------
+    docstring : str
+        string with requested ``docdict`` strings inserted.
+
+    Examples
+    --------
+    >>> docformat(' Test string with %(value)s', {'value':'inserted value'})
+    ' Test string with inserted value'
+    >>> docstring = 'First line\\n    Second line\\n    %(value)s'
+    >>> inserted_string = "indented\\nstring"
+    >>> docdict = {'value': inserted_string}
+    >>> docformat(docstring, docdict)
+    'First line\\n    Second line\\n    indented\\n    string'
+    """
+    if not docstring:
+        return docstring
+    if docdict is None:
+        docdict = {}
+    if not docdict:
+        return docstring
+    lines = docstring.expandtabs().splitlines()
+    # Find the minimum indent of the main docstring, after first line
+    if len(lines) < 2:
+        icount = 0
+    else:
+        icount = indentcount_lines(lines[1:])
+    indent = " " * icount
+    # Insert this indent to dictionary docstrings
+    indented = {}
+    for name, dstr in docdict.items():
+        lines = dstr.expandtabs().splitlines()
+        try:
+            newlines = [lines[0]]
+            for line in lines[1:]:
+                newlines.append(indent + line)
+            indented[name] = "\n".join(newlines)
+        except IndexError:
+            indented[name] = dstr
+    return docstring % indented
+
+
+def inherit_docstring_from(cls: object) -> Decorator:
+    """This decorator modifies the decorated function's docstring by
+    replacing occurrences of '%(super)s' with the docstring of the
+    method of the same name from the class `cls`.
+
+    If the decorated method has no docstring, it is simply given the
+    docstring of `cls`s method.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces '%(super)s' in the
+        docstring of the decorated method.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+
+    Examples
+    --------
+    In the following, the docstring for Bar.func created using the
+    docstring of `Foo.func`.
+
+    >>> class Foo:
+    ...     def func(self):
+    ...         '''Do something useful.'''
+    ...         return
+    ...
+    >>> class Bar(Foo):
+    ...     @inherit_docstring_from(Foo)
+    ...     def func(self):
+    ...         '''%(super)s
+    ...         Do it fast.
+    ...         '''
+    ...         return
+    ...
+    >>> b = Bar()
+    >>> b.func.__doc__
+    'Do something useful.\n        Do it fast.\n        '
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        func_docstring = func.__doc__
+        if func_docstring is None:
+            func.__doc__ = cls_docstring
+        else:
+            new_docstring = func_docstring % dict(super=cls_docstring)
+            func.__doc__ = new_docstring
+        return func
+
+    return _doc
+
+
+def extend_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It extends the 'Notes' section of that docstring to include
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        Additional notes to append to the 'Notes' section of the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[:end_of_notes] + notes + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def replace_notes_in_docstring(cls: object, notes: str) -> Decorator:
+    """This decorator replaces the decorated function's docstring
+    with the docstring from corresponding method in `cls`.
+    It replaces the 'Notes' section of that docstring with
+    the given `notes`.
+
+    Parameters
+    ----------
+    cls : type or object
+        A class with a method with the same name as the decorated method.
+        The docstring of the method in this class replaces the docstring of the
+        decorated method.
+    notes : str
+        The notes to replace the existing 'Notes' section with.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that modifies the __doc__ attribute
+        of its argument.
+    """
+
+    def _doc(func: _F) -> _F:
+        cls_docstring = getattr(cls, func.__name__).__doc__
+        notes_header = "        Notes\n        -----\n"
+        # If python is called with -OO option,
+        # there is no docstring
+        if cls_docstring is None:
+            return func
+        start_of_notes = cls_docstring.find(notes_header)
+        end_of_notes = cls_docstring.find("        References\n")
+        if end_of_notes == -1:
+            end_of_notes = cls_docstring.find("        Examples\n")
+            if end_of_notes == -1:
+                end_of_notes = len(cls_docstring)
+        func.__doc__ = (
+            cls_docstring[: start_of_notes + len(notes_header)]
+            + notes
+            + cls_docstring[end_of_notes:]
+        )
+        return func
+
+    return _doc
+
+
+def indentcount_lines(lines: Iterable[str]) -> int:
+    """Minimum indent for all lines in line list
+
+    Parameters
+    ----------
+    lines : Iterable[str]
+        The lines to find the minimum indent of.
+
+    Returns
+    -------
+    indent : int
+        The minimum indent.
+
+
+    Examples
+    --------
+    >>> lines = [' one', '  two', '   three']
+    >>> indentcount_lines(lines)
+    1
+    >>> lines = []
+    >>> indentcount_lines(lines)
+    0
+    >>> lines = [' one']
+    >>> indentcount_lines(lines)
+    1
+    >>> indentcount_lines(['    '])
+    0
+    """
+    indentno = sys.maxsize
+    for line in lines:
+        stripped = line.lstrip()
+        if stripped:
+            indentno = min(indentno, len(line) - len(stripped))
+    if indentno == sys.maxsize:
+        return 0
+    return indentno
+
+
+def filldoc(docdict: Mapping[str, str], unindent_params: bool = True) -> Decorator:
+    """Return docstring decorator using docdict variable dictionary.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary containing name, docstring fragment pairs.
+    unindent_params : bool, optional
+        If True, strip common indentation from all parameters in docdict.
+        Default is False.
+
+    Returns
+    -------
+    decfunc : function
+        The decorator function that applies dictionary to its
+        argument's __doc__ attribute.
+    """
+    if unindent_params:
+        docdict = unindent_dict(docdict)
+
+    def decorate(func: _F) -> _F:
+        # __doc__ may be None for optimized Python (-OO)
+        doc = func.__doc__ or ""
+        func.__doc__ = docformat(doc, docdict)
+        return func
+
+    return decorate
+
+
+def unindent_dict(docdict: Mapping[str, str]) -> dict[str, str]:
+    """Unindent all strings in a docdict.
+
+    Parameters
+    ----------
+    docdict : dict[str, str]
+        A dictionary with string values to unindent.
+
+    Returns
+    -------
+    docdict : dict[str, str]
+        The `docdict` dictionary but each of its string values are unindented.
+    """
+    can_dict: dict[str, str] = {}
+    for name, dstr in docdict.items():
+        can_dict[name] = unindent_string(dstr)
+    return can_dict
+
+
+def unindent_string(docstring: str) -> str:
+    """Set docstring to minimum indent for all lines, including first.
+
+    Parameters
+    ----------
+    docstring : str
+        The input docstring to unindent.
+
+    Returns
+    -------
+    docstring : str
+        The unindented docstring.
+
+    Examples
+    --------
+    >>> unindent_string(' two')
+    'two'
+    >>> unindent_string('  two\\n   three')
+    'two\\n three'
+    """
+    lines = docstring.expandtabs().splitlines()
+    icount = indentcount_lines(lines)
+    if icount == 0:
+        return docstring
+    return "\n".join([line[icount:] for line in lines])
+
+
+def doc_replace(obj: object, oldval: str, newval: str) -> Decorator:
+    """Decorator to take the docstring from obj, with oldval replaced by newval
+
+    Equivalent to ``func.__doc__ = obj.__doc__.replace(oldval, newval)``
+
+    Parameters
+    ----------
+    obj : object
+        A class or object whose docstring will be used as the basis for the
+        replacement operation.
+    oldval : str
+        The string to search for in the docstring.
+    newval : str
+        The string to replace `oldval` with in the docstring.
+
+    Returns
+    -------
+    decfunc : function
+        A decorator function that replaces occurrences of `oldval` with `newval`
+        in the docstring of the decorated function.
+    """
+    # __doc__ may be None for optimized Python (-OO)
+    doc = (obj.__doc__ or "").replace(oldval, newval)
+
+    def inner(func: _F) -> _F:
+        func.__doc__ = doc
+        return func
+
+    return inner
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/messagestream.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/messagestream.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..8601000890aa60527e6ec7f43e36a66dc0cb5c2d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/messagestream.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__gcutils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__gcutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e397af4fb7e9bc69f31d1e39aa80716469d5470
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__gcutils.py
@@ -0,0 +1,110 @@
+""" Test for assert_deallocated context manager and gc utilities
+"""
+import gc
+from threading import Lock
+
+from scipy._lib._gcutils import (set_gc_state, gc_state, assert_deallocated,
+                                 ReferenceError, IS_PYPY)
+
+from numpy.testing import assert_equal
+
+import pytest
+
+
+@pytest.fixture
+def gc_lock():
+    return Lock()
+
+
+def test_set_gc_state(gc_lock):
+    with gc_lock:
+        gc_status = gc.isenabled()
+        try:
+            for state in (True, False):
+                gc.enable()
+                set_gc_state(state)
+                assert_equal(gc.isenabled(), state)
+                gc.disable()
+                set_gc_state(state)
+                assert_equal(gc.isenabled(), state)
+        finally:
+            if gc_status:
+                gc.enable()
+
+
+def test_gc_state(gc_lock):
+    # Test gc_state context manager
+    with gc_lock:
+        gc_status = gc.isenabled()
+        try:
+            for pre_state in (True, False):
+                set_gc_state(pre_state)
+                for with_state in (True, False):
+                    # Check the gc state is with_state in with block
+                    with gc_state(with_state):
+                        assert_equal(gc.isenabled(), with_state)
+                    # And returns to previous state outside block
+                    assert_equal(gc.isenabled(), pre_state)
+                    # Even if the gc state is set explicitly within the block
+                    with gc_state(with_state):
+                        assert_equal(gc.isenabled(), with_state)
+                        set_gc_state(not with_state)
+                    assert_equal(gc.isenabled(), pre_state)
+        finally:
+            if gc_status:
+                gc.enable()
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_assert_deallocated(gc_lock):
+    # Ordinary use
+    class C:
+        def __init__(self, arg0, arg1, name='myname'):
+            self.name = name
+    with gc_lock:
+        for gc_current in (True, False):
+            with gc_state(gc_current):
+                # We are deleting from with-block context, so that's OK
+                with assert_deallocated(C, 0, 2, 'another name') as c:
+                    assert_equal(c.name, 'another name')
+                    del c
+                # Or not using the thing in with-block context, also OK
+                with assert_deallocated(C, 0, 2, name='third name'):
+                    pass
+                assert_equal(gc.isenabled(), gc_current)
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_assert_deallocated_nodel():
+    class C:
+        pass
+    with pytest.raises(ReferenceError):
+        # Need to delete after using if in with-block context
+        # Note: assert_deallocated(C) needs to be assigned for the test
+        # to function correctly.  It is assigned to _, but _ itself is
+        # not referenced in the body of the with, it is only there for
+        # the refcount.
+        with assert_deallocated(C) as _:
+            pass
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_assert_deallocated_circular():
+    class C:
+        def __init__(self):
+            self._circular = self
+    with pytest.raises(ReferenceError):
+        # Circular reference, no automatic garbage collection
+        with assert_deallocated(C) as c:
+            del c
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_assert_deallocated_circular2():
+    class C:
+        def __init__(self):
+            self._circular = self
+    with pytest.raises(ReferenceError):
+        # Still circular reference, no automatic garbage collection
+        with assert_deallocated(C):
+            pass
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__pep440.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__pep440.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5b71c8f1e13b42de2e8e612a005dec409fc025
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__pep440.py
@@ -0,0 +1,67 @@
+from pytest import raises as assert_raises
+from scipy._lib._pep440 import Version, parse
+
+
+def test_main_versions():
+    assert Version('1.8.0') == Version('1.8.0')
+    for ver in ['1.9.0', '2.0.0', '1.8.1']:
+        assert Version('1.8.0') < Version(ver)
+
+    for ver in ['1.7.0', '1.7.1', '0.9.9']:
+        assert Version('1.8.0') > Version(ver)
+
+
+def test_version_1_point_10():
+    # regression test for gh-2998.
+    assert Version('1.9.0') < Version('1.10.0')
+    assert Version('1.11.0') < Version('1.11.1')
+    assert Version('1.11.0') == Version('1.11.0')
+    assert Version('1.99.11') < Version('1.99.12')
+
+
+def test_alpha_beta_rc():
+    assert Version('1.8.0rc1') == Version('1.8.0rc1')
+    for ver in ['1.8.0', '1.8.0rc2']:
+        assert Version('1.8.0rc1') < Version(ver)
+
+    for ver in ['1.8.0a2', '1.8.0b3', '1.7.2rc4']:
+        assert Version('1.8.0rc1') > Version(ver)
+
+    assert Version('1.8.0b1') > Version('1.8.0a2')
+
+
+def test_dev_version():
+    assert Version('1.9.0.dev+Unknown') < Version('1.9.0')
+    for ver in ['1.9.0', '1.9.0a1', '1.9.0b2', '1.9.0b2.dev+ffffffff', '1.9.0.dev1']:
+        assert Version('1.9.0.dev+f16acvda') < Version(ver)
+
+    assert Version('1.9.0.dev+f16acvda') == Version('1.9.0.dev+f16acvda')
+
+
+def test_dev_a_b_rc_mixed():
+    assert Version('1.9.0a2.dev+f16acvda') == Version('1.9.0a2.dev+f16acvda')
+    assert Version('1.9.0a2.dev+6acvda54') < Version('1.9.0a2')
+
+
+def test_dev0_version():
+    assert Version('1.9.0.dev0+Unknown') < Version('1.9.0')
+    for ver in ['1.9.0', '1.9.0a1', '1.9.0b2', '1.9.0b2.dev0+ffffffff']:
+        assert Version('1.9.0.dev0+f16acvda') < Version(ver)
+
+    assert Version('1.9.0.dev0+f16acvda') == Version('1.9.0.dev0+f16acvda')
+
+
+def test_dev0_a_b_rc_mixed():
+    assert Version('1.9.0a2.dev0+f16acvda') == Version('1.9.0a2.dev0+f16acvda')
+    assert Version('1.9.0a2.dev0+6acvda54') < Version('1.9.0a2')
+
+
+def test_raises():
+    for ver in ['1,9.0', '1.7.x']:
+        assert_raises(ValueError, Version, ver)
+
+def test_legacy_version():
+    # Non-PEP-440 version identifiers always compare less. For NumPy this only
+    # occurs on dev builds prior to 1.10.0 which are unsupported anyway.
+    assert parse('invalid') < Version('0.0.0')
+    assert parse('1.9.0-f16acvda') < Version('1.0.0')
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__testutils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..88db113d6d5a35c96ecc0a6a36ab42d74be49153
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__testutils.py
@@ -0,0 +1,32 @@
+import sys
+from scipy._lib._testutils import _parse_size, _get_mem_available
+import pytest
+
+
+def test__parse_size():
+    expected = {
+        '12': 12e6,
+        '12 b': 12,
+        '12k': 12e3,
+        '  12  M  ': 12e6,
+        '  12  G  ': 12e9,
+        ' 12Tb ': 12e12,
+        '12  Mib ': 12 * 1024.0**2,
+        '12Tib': 12 * 1024.0**4,
+    }
+
+    for inp, outp in sorted(expected.items()):
+        if outp is None:
+            with pytest.raises(ValueError):
+                _parse_size(inp)
+        else:
+            assert _parse_size(inp) == outp
+
+
+def test__mem_available():
+    # May return None on non-Linux platforms
+    available = _get_mem_available()
+    if sys.platform.startswith('linux'):
+        assert available >= 0
+    else:
+        assert available is None or available >= 0
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__threadsafety.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__threadsafety.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ae85ef318da2b8bb104c4a87faa4e4021c01d5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__threadsafety.py
@@ -0,0 +1,51 @@
+import threading
+import time
+import traceback
+
+from numpy.testing import assert_
+from pytest import raises as assert_raises
+
+from scipy._lib._threadsafety import ReentrancyLock, non_reentrant, ReentrancyError
+
+
+def test_parallel_threads():
+    # Check that ReentrancyLock serializes work in parallel threads.
+    #
+    # The test is not fully deterministic, and may succeed falsely if
+    # the timings go wrong.
+
+    lock = ReentrancyLock("failure")
+
+    failflag = [False]
+    exceptions_raised = []
+
+    def worker(k):
+        try:
+            with lock:
+                assert_(not failflag[0])
+                failflag[0] = True
+                time.sleep(0.1 * k)
+                assert_(failflag[0])
+                failflag[0] = False
+        except Exception:
+            exceptions_raised.append(traceback.format_exc(2))
+
+    threads = [threading.Thread(target=lambda k=k: worker(k))
+               for k in range(3)]
+    for t in threads:
+        t.start()
+    for t in threads:
+        t.join()
+
+    exceptions_raised = "\n".join(exceptions_raised)
+    assert_(not exceptions_raised, exceptions_raised)
+
+
+def test_reentering():
+    # Check that ReentrancyLock prevents re-entering from the same thread.
+
+    @non_reentrant()
+    def func(x):
+        return func(x)
+
+    assert_raises(ReentrancyError, func, 0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__util.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__util.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a4d22ce468ec951355961cb77dda15b56899818
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test__util.py
@@ -0,0 +1,657 @@
+from multiprocessing import Pool
+from multiprocessing.pool import Pool as PWL
+import re
+import math
+from fractions import Fraction
+
+import numpy as np
+from numpy.testing import assert_equal, assert_
+import pytest
+from pytest import raises as assert_raises
+import hypothesis.extra.numpy as npst
+from hypothesis import given, strategies, reproduce_failure  # noqa: F401
+from scipy.conftest import array_api_compatible, skip_xp_invalid_arg
+
+from scipy._lib._array_api import (xp_assert_equal, xp_assert_close, is_numpy,
+                                   xp_copy, is_array_api_strict)
+from scipy._lib._util import (_aligned_zeros, check_random_state, MapWrapper,
+                              getfullargspec_no_self, FullArgSpec,
+                              rng_integers, _validate_int, _rename_parameter,
+                              _contains_nan, _rng_html_rewrite, _lazywhere)
+from scipy import cluster, interpolate, linalg, optimize, sparse, spatial, stats
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@pytest.mark.slow
+def test__aligned_zeros():
+    niter = 10
+
+    def check(shape, dtype, order, align):
+        err_msg = repr((shape, dtype, order, align))
+        x = _aligned_zeros(shape, dtype, order, align=align)
+        if align is None:
+            align = np.dtype(dtype).alignment
+        assert_equal(x.__array_interface__['data'][0] % align, 0)
+        if hasattr(shape, '__len__'):
+            assert_equal(x.shape, shape, err_msg)
+        else:
+            assert_equal(x.shape, (shape,), err_msg)
+        assert_equal(x.dtype, dtype)
+        if order == "C":
+            assert_(x.flags.c_contiguous, err_msg)
+        elif order == "F":
+            if x.size > 0:
+                # Size-0 arrays get invalid flags on NumPy 1.5
+                assert_(x.flags.f_contiguous, err_msg)
+        elif order is None:
+            assert_(x.flags.c_contiguous, err_msg)
+        else:
+            raise ValueError()
+
+    # try various alignments
+    for align in [1, 2, 3, 4, 8, 16, 32, 64, None]:
+        for n in [0, 1, 3, 11]:
+            for order in ["C", "F", None]:
+                for dtype in [np.uint8, np.float64]:
+                    for shape in [n, (1, 2, 3, n)]:
+                        for j in range(niter):
+                            check(shape, dtype, order, align)
+
+
+def test_check_random_state():
+    # If seed is None, return the RandomState singleton used by np.random.
+    # If seed is an int, return a new RandomState instance seeded with seed.
+    # If seed is already a RandomState instance, return it.
+    # Otherwise raise ValueError.
+    rsi = check_random_state(1)
+    assert_equal(type(rsi), np.random.RandomState)
+    rsi = check_random_state(rsi)
+    assert_equal(type(rsi), np.random.RandomState)
+    rsi = check_random_state(None)
+    assert_equal(type(rsi), np.random.RandomState)
+    assert_raises(ValueError, check_random_state, 'a')
+    rg = np.random.Generator(np.random.PCG64())
+    rsi = check_random_state(rg)
+    assert_equal(type(rsi), np.random.Generator)
+
+
+def test_getfullargspec_no_self():
+    p = MapWrapper(1)
+    argspec = getfullargspec_no_self(p.__init__)
+    assert_equal(argspec, FullArgSpec(['pool'], None, None, (1,), [],
+                                      None, {}))
+    argspec = getfullargspec_no_self(p.__call__)
+    assert_equal(argspec, FullArgSpec(['func', 'iterable'], None, None, None,
+                                      [], None, {}))
+
+    class _rv_generic:
+        def _rvs(self, a, b=2, c=3, *args, size=None, **kwargs):
+            return None
+
+    rv_obj = _rv_generic()
+    argspec = getfullargspec_no_self(rv_obj._rvs)
+    assert_equal(argspec, FullArgSpec(['a', 'b', 'c'], 'args', 'kwargs',
+                                      (2, 3), ['size'], {'size': None}, {}))
+
+
+def test_mapwrapper_serial():
+    in_arg = np.arange(10.)
+    out_arg = np.sin(in_arg)
+
+    p = MapWrapper(1)
+    assert_(p._mapfunc is map)
+    assert_(p.pool is None)
+    assert_(p._own_pool is False)
+    out = list(p(np.sin, in_arg))
+    assert_equal(out, out_arg)
+
+    with assert_raises(RuntimeError):
+        p = MapWrapper(0)
+
+
+def test_pool():
+    with Pool(2) as p:
+        p.map(math.sin, [1, 2, 3, 4])
+
+
+def test_mapwrapper_parallel():
+    in_arg = np.arange(10.)
+    out_arg = np.sin(in_arg)
+
+    with MapWrapper(2) as p:
+        out = p(np.sin, in_arg)
+        assert_equal(list(out), out_arg)
+
+        assert_(p._own_pool is True)
+        assert_(isinstance(p.pool, PWL))
+        assert_(p._mapfunc is not None)
+
+    # the context manager should've closed the internal pool
+    # check that it has by asking it to calculate again.
+    with assert_raises(Exception) as excinfo:
+        p(np.sin, in_arg)
+
+    assert_(excinfo.type is ValueError)
+
+    # can also set a PoolWrapper up with a map-like callable instance
+    with Pool(2) as p:
+        q = MapWrapper(p.map)
+
+        assert_(q._own_pool is False)
+        q.close()
+
+        # closing the PoolWrapper shouldn't close the internal pool
+        # because it didn't create it
+        out = p.map(np.sin, in_arg)
+        assert_equal(list(out), out_arg)
+
+
+def test_rng_integers():
+    rng = np.random.RandomState()
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # now try with np.random.Generator
+    try:
+        rng = np.random.default_rng()
+    except AttributeError:
+        return
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are inclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=True)
+    assert np.max(arr) == 5
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=2, high=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 2
+    assert arr.shape == (100, )
+
+    # test that numbers are exclusive of high point
+    arr = rng_integers(rng, low=5, size=100, endpoint=False)
+    assert np.max(arr) == 4
+    assert np.min(arr) == 0
+    assert arr.shape == (100, )
+
+
+class TestValidateInt:
+
+    @pytest.mark.parametrize('n', [4, np.uint8(4), np.int16(4), np.array(4)])
+    def test_validate_int(self, n):
+        n = _validate_int(n, 'n')
+        assert n == 4
+
+    @pytest.mark.parametrize('n', [4.0, np.array([4]), Fraction(4, 1)])
+    def test_validate_int_bad(self, n):
+        with pytest.raises(TypeError, match='n must be an integer'):
+            _validate_int(n, 'n')
+
+    def test_validate_int_below_min(self):
+        with pytest.raises(ValueError, match='n must be an integer not '
+                                             'less than 0'):
+            _validate_int(-1, 'n', 0)
+
+
+class TestRenameParameter:
+    # check that wrapper `_rename_parameter` for backward-compatible
+    # keyword renaming works correctly
+
+    # Example method/function that still accepts keyword `old`
+    @_rename_parameter("old", "new")
+    def old_keyword_still_accepted(self, new):
+        return new
+
+    # Example method/function for which keyword `old` is deprecated
+    @_rename_parameter("old", "new", dep_version="1.9.0")
+    def old_keyword_deprecated(self, new):
+        return new
+
+    def test_old_keyword_still_accepted(self):
+        # positional argument and both keyword work identically
+        res1 = self.old_keyword_still_accepted(10)
+        res2 = self.old_keyword_still_accepted(new=10)
+        res3 = self.old_keyword_still_accepted(old=10)
+        assert res1 == res2 == res3 == 10
+
+        # unexpected keyword raises an error
+        message = re.escape("old_keyword_still_accepted() got an unexpected")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(unexpected=10)
+
+        # multiple values for the same parameter raises an error
+        message = re.escape("old_keyword_still_accepted() got multiple")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(10, new=10)
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(10, old=10)
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_still_accepted(new=10, old=10)
+
+    @pytest.fixture
+    def kwarg_lock(self):
+        from threading import Lock
+        return Lock()
+
+    def test_old_keyword_deprecated(self, kwarg_lock):
+        # positional argument and both keyword work identically,
+        # but use of old keyword results in DeprecationWarning
+        dep_msg = "Use of keyword argument `old` is deprecated"
+        res1 = self.old_keyword_deprecated(10)
+        res2 = self.old_keyword_deprecated(new=10)
+        # pytest warning filter is not thread-safe, enforce serialization
+        with kwarg_lock:
+            with pytest.warns(DeprecationWarning, match=dep_msg):
+                    res3 = self.old_keyword_deprecated(old=10)
+        assert res1 == res2 == res3 == 10
+
+        # unexpected keyword raises an error
+        message = re.escape("old_keyword_deprecated() got an unexpected")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_deprecated(unexpected=10)
+
+        # multiple values for the same parameter raises an error and,
+        # if old keyword is used, results in DeprecationWarning
+        message = re.escape("old_keyword_deprecated() got multiple")
+        with pytest.raises(TypeError, match=message):
+            self.old_keyword_deprecated(10, new=10)
+        with kwarg_lock:
+            with pytest.raises(TypeError, match=message), \
+                    pytest.warns(DeprecationWarning, match=dep_msg):
+                    # breakpoint()
+                    self.old_keyword_deprecated(10, old=10)
+        with kwarg_lock:
+            with pytest.raises(TypeError, match=message), \
+                    pytest.warns(DeprecationWarning, match=dep_msg):
+                    self.old_keyword_deprecated(new=10, old=10)
+
+
+class TestContainsNaNTest:
+
+    def test_policy(self):
+        data = np.array([1, 2, 3, np.nan])
+
+        contains_nan, nan_policy = _contains_nan(data, nan_policy="propagate")
+        assert contains_nan
+        assert nan_policy == "propagate"
+
+        contains_nan, nan_policy = _contains_nan(data, nan_policy="omit")
+        assert contains_nan
+        assert nan_policy == "omit"
+
+        msg = "The input contains nan values"
+        with pytest.raises(ValueError, match=msg):
+            _contains_nan(data, nan_policy="raise")
+
+        msg = "nan_policy must be one of"
+        with pytest.raises(ValueError, match=msg):
+            _contains_nan(data, nan_policy="nan")
+
+    def test_contains_nan(self):
+        data1 = np.array([1, 2, 3])
+        assert not _contains_nan(data1)[0]
+
+        data2 = np.array([1, 2, 3, np.nan])
+        assert _contains_nan(data2)[0]
+
+        data3 = np.array([np.nan, 2, 3, np.nan])
+        assert _contains_nan(data3)[0]
+
+        data4 = np.array([[1, 2], [3, 4]])
+        assert not _contains_nan(data4)[0]
+
+        data5 = np.array([[1, 2], [3, np.nan]])
+        assert _contains_nan(data5)[0]
+
+    @skip_xp_invalid_arg
+    def test_contains_nan_with_strings(self):
+        data1 = np.array([1, 2, "3", np.nan])  # converted to string "nan"
+        assert not _contains_nan(data1)[0]
+
+        data2 = np.array([1, 2, "3", np.nan], dtype='object')
+        assert _contains_nan(data2)[0]
+
+        data3 = np.array([["1", 2], [3, np.nan]])  # converted to string "nan"
+        assert not _contains_nan(data3)[0]
+
+        data4 = np.array([["1", 2], [3, np.nan]], dtype='object')
+        assert _contains_nan(data4)[0]
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    @pytest.mark.parametrize("nan_policy", ['propagate', 'omit', 'raise'])
+    def test_array_api(self, xp, nan_policy):
+        rng = np.random.default_rng(932347235892482)
+        x0 = rng.random(size=(2, 3, 4))
+        x = xp.asarray(x0)
+        x_nan = xp_copy(x, xp=xp)
+        x_nan[1, 2, 1] = np.nan
+
+        contains_nan, nan_policy_out = _contains_nan(x, nan_policy=nan_policy)
+        assert not contains_nan
+        assert nan_policy_out == nan_policy
+
+        if nan_policy == 'raise':
+            message = 'The input contains...'
+            with pytest.raises(ValueError, match=message):
+                _contains_nan(x_nan, nan_policy=nan_policy)
+        elif nan_policy == 'omit' and not is_numpy(xp):
+            message = "`nan_policy='omit' is incompatible..."
+            with pytest.raises(ValueError, match=message):
+                _contains_nan(x_nan, nan_policy=nan_policy)
+        elif nan_policy == 'propagate':
+            contains_nan, nan_policy_out = _contains_nan(
+                x_nan, nan_policy=nan_policy)
+            assert contains_nan
+            assert nan_policy_out == nan_policy
+
+
+def test__rng_html_rewrite():
+    def mock_str():
+        lines = [
+            'np.random.default_rng(8989843)',
+            'np.random.default_rng(seed)',
+            'np.random.default_rng(0x9a71b21474694f919882289dc1559ca)',
+            ' bob ',
+        ]
+        return lines
+
+    res = _rng_html_rewrite(mock_str)()
+    ref = [
+        'np.random.default_rng()',
+        'np.random.default_rng(seed)',
+        'np.random.default_rng()',
+        ' bob ',
+    ]
+
+    assert res == ref
+
+
+class TestTransitionToRNG:
+    def kmeans(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return cluster.vq.kmeans2(rng.random(size=(20, 3)), 3, **kwargs)
+
+    def kmeans2(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return cluster.vq.kmeans2(rng.random(size=(20, 3)), 3, **kwargs)
+
+    def barycentric(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x1, x2, y1 = rng.random((3, 10))
+        f = interpolate.BarycentricInterpolator(x1, y1, **kwargs)
+        return f(x2)
+
+    def clarkson_woodruff_transform(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return linalg.clarkson_woodruff_transform(rng.random((10, 10)), 3, **kwargs)
+
+    def basinhopping(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        return optimize.basinhopping(optimize.rosen, rng.random(3), **kwargs).x
+
+    def opt(self, fun, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        bounds = optimize.Bounds(-rng.random(3) * 10, rng.random(3) * 10)
+        return fun(optimize.rosen, bounds, **kwargs).x
+
+    def differential_evolution(self, **kwargs):
+        return self.opt(optimize.differential_evolution, **kwargs)
+
+    def dual_annealing(self, **kwargs):
+        return self.opt(optimize.dual_annealing, **kwargs)
+
+    def check_grad(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x = rng.random(3)
+        return optimize.check_grad(optimize.rosen, optimize.rosen_der, x,
+                                   direction='random', **kwargs)
+
+    def random_array(self, **kwargs):
+        return sparse.random_array((10, 10), density=1.0, **kwargs).toarray()
+
+    def random(self, **kwargs):
+        return sparse.random(10, 10, density=1.0, **kwargs).toarray()
+
+    def rand(self, **kwargs):
+        return sparse.rand(10, 10, density=1.0, **kwargs).toarray()
+
+    def svds(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        A = rng.random((10, 10))
+        return sparse.linalg.svds(A, **kwargs)
+
+    def random_rotation(self, **kwargs):
+        return spatial.transform.Rotation.random(3, **kwargs).as_matrix()
+
+    def goodness_of_fit(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = rng.random(100)
+        return stats.goodness_of_fit(stats.laplace, data, **kwargs).pvalue
+
+    def permutation_test(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        def statistic(x, y, axis): return np.mean(x, axis=axis) - np.mean(y, axis=axis)
+        return stats.permutation_test(data, statistic, **kwargs).pvalue
+
+    def bootstrap(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = (rng.random(100),)
+        return stats.bootstrap(data, np.mean, **kwargs).confidence_interval
+
+    def dunnett(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        x, y, control = rng.random((3, 100))
+        return stats.dunnett(x, y, control=control, **kwargs).pvalue
+
+    def sobol_indices(self, **kwargs):
+        def f_ishigami(x): return (np.sin(x[0]) + 7 * np.sin(x[1]) ** 2
+                                   + 0.1 * (x[2] ** 4) * np.sin(x[0]))
+        dists = [stats.uniform(loc=-np.pi, scale=2 * np.pi),
+                 stats.uniform(loc=-np.pi, scale=2 * np.pi),
+                 stats.uniform(loc=-np.pi, scale=2 * np.pi)]
+        res = stats.sobol_indices(func=f_ishigami, n=1024, dists=dists, **kwargs)
+        return res.first_order
+
+    def qmc_engine(self, engine, **kwargs):
+        qrng = engine(d=1, **kwargs)
+        return qrng.random(4)
+
+    def halton(self, **kwargs):
+        return self.qmc_engine(stats.qmc.Halton, **kwargs)
+
+    def sobol(self, **kwargs):
+        return self.qmc_engine(stats.qmc.Sobol, **kwargs)
+
+    def latin_hypercube(self, **kwargs):
+        return self.qmc_engine(stats.qmc.LatinHypercube, **kwargs)
+
+    def poisson_disk(self, **kwargs):
+        return self.qmc_engine(stats.qmc.PoissonDisk, **kwargs)
+
+    def multivariate_normal_qmc(self, **kwargs):
+        X = stats.qmc.MultivariateNormalQMC([0], **kwargs)
+        return X.random(4)
+
+    def multinomial_qmc(self, **kwargs):
+        X = stats.qmc.MultinomialQMC([0.5, 0.5], 4, **kwargs)
+        return X.random(4)
+
+    def permutation_method(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        method = stats.PermutationMethod(**kwargs)
+        return stats.pearsonr(*data, method=method).pvalue
+
+    def bootstrap_method(self, **kwargs):
+        rng = np.random.default_rng(3458934594269824562)
+        data = tuple(rng.random((2, 100)))
+        res = stats.pearsonr(*data)
+        method = stats.BootstrapMethod(**kwargs)
+        return res.confidence_interval(method=method)
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.slow
+    @pytest.mark.parametrize("method, arg_name", [
+        (kmeans, "seed"),
+        (kmeans2, "seed"),
+        (barycentric, "random_state"),
+        (clarkson_woodruff_transform, "seed"),
+        (basinhopping, "seed"),
+        (differential_evolution, "seed"),
+        (dual_annealing, "seed"),
+        (check_grad, "seed"),
+        (random_array, 'random_state'),
+        (random, 'random_state'),
+        (rand, 'random_state'),
+        (svds, "random_state"),
+        (random_rotation, "random_state"),
+        (goodness_of_fit, "random_state"),
+        (permutation_test, "random_state"),
+        (bootstrap, "random_state"),
+        (permutation_method, "random_state"),
+        (bootstrap_method, "random_state"),
+        (dunnett, "random_state"),
+        (sobol_indices, "random_state"),
+        (halton, "seed"),
+        (sobol, "seed"),
+        (latin_hypercube, "seed"),
+        (poisson_disk, "seed"),
+        (multivariate_normal_qmc, "seed"),
+        (multinomial_qmc, "seed"),
+    ])
+    def test_rng_deterministic(self, method, arg_name):
+        np.random.seed(None)
+        seed = 2949672964
+
+        rng = np.random.default_rng(seed)
+        message = "got multiple values for argument now known as `rng`"
+        with pytest.raises(TypeError, match=message):
+            method(self, **{'rng': rng, arg_name: seed})
+
+        rng = np.random.default_rng(seed)
+        res1 = method(self, rng=rng)
+        res2 = method(self, rng=seed)
+        assert_equal(res2, res1)
+
+        if method.__name__ in {"dunnett", "sobol_indices"}:
+            # the two kwargs have essentially the same behavior for these functions
+            res3 = method(self, **{arg_name: seed})
+            assert_equal(res3, res1)
+            return
+
+        rng = np.random.RandomState(seed)
+        res1 = method(self, **{arg_name: rng})
+        res2 = method(self, **{arg_name: seed})
+
+        if method.__name__ in {"halton", "sobol", "latin_hypercube", "poisson_disk",
+                               "multivariate_normal_qmc", "multinomial_qmc"}:
+            # For these, passing `random_state=RandomState(seed)` is not the same as
+            # passing integer `seed`.
+            res1b = method(self, **{arg_name: np.random.RandomState(seed)})
+            assert_equal(res1b, res1)
+            res2b = method(self, **{arg_name: seed})
+            assert_equal(res2b, res2)
+            return
+
+        np.random.seed(seed)
+        res3 = method(self, **{arg_name: None})
+        assert_equal(res2, res1)
+        assert_equal(res3, res1)
+
+
+class TestLazywhere:
+    n_arrays = strategies.integers(min_value=1, max_value=3)
+    rng_seed = strategies.integers(min_value=1000000000, max_value=9999999999)
+    dtype = strategies.sampled_from((np.float32, np.float64))
+    p = strategies.floats(min_value=0, max_value=1)
+    data = strategies.data()
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.filterwarnings('ignore::RuntimeWarning')  # overflows, etc.
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    @given(n_arrays=n_arrays, rng_seed=rng_seed, dtype=dtype, p=p, data=data)
+    @pytest.mark.thread_unsafe
+    def test_basic(self, n_arrays, rng_seed, dtype, p, data, xp):
+        mbs = npst.mutually_broadcastable_shapes(num_shapes=n_arrays+1,
+                                                 min_side=0)
+        input_shapes, result_shape = data.draw(mbs)
+        cond_shape, *shapes = input_shapes
+        elements = {'allow_subnormal': False}  # cupy/cupy#8382
+        fillvalue = xp.asarray(data.draw(npst.arrays(dtype=dtype, shape=tuple(),
+                                                     elements=elements)))
+        float_fillvalue = float(fillvalue)
+        arrays = [xp.asarray(data.draw(npst.arrays(dtype=dtype, shape=shape)))
+                  for shape in shapes]
+
+        def f(*args):
+            return sum(arg for arg in args)
+
+        def f2(*args):
+            return sum(arg for arg in args) / 2
+
+        rng = np.random.default_rng(rng_seed)
+        cond = xp.asarray(rng.random(size=cond_shape) > p)
+
+        res1 = _lazywhere(cond, arrays, f, fillvalue)
+        res2 = _lazywhere(cond, arrays, f, f2=f2)
+        if not is_array_api_strict(xp):
+            res3 = _lazywhere(cond, arrays, f, float_fillvalue)
+
+        # Ensure arrays are at least 1d to follow sane type promotion rules.
+        # This can be removed when minimum supported NumPy is 2.0
+        if xp == np:
+            cond, fillvalue, *arrays = np.atleast_1d(cond, fillvalue, *arrays)
+
+        ref1 = xp.where(cond, f(*arrays), fillvalue)
+        ref2 = xp.where(cond, f(*arrays), f2(*arrays))
+        if not is_array_api_strict(xp):
+            # Array API standard doesn't currently define behavior when fillvalue is a
+            # Python scalar. When it does, test can be run with array_api_strict, too.
+            ref3 = xp.where(cond, f(*arrays), float_fillvalue)
+
+        if xp == np:  # because we ensured arrays are at least 1d
+            ref1 = ref1.reshape(result_shape)
+            ref2 = ref2.reshape(result_shape)
+            ref3 = ref3.reshape(result_shape)
+
+        xp_assert_close(res1, ref1, rtol=2e-16)
+        xp_assert_equal(res2, ref2)
+        if not is_array_api_strict(xp):
+            xp_assert_equal(res3, ref3)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_array_api.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_array_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..f425eb4327fe042a3cf8eb79cf3402f23b526ae7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_array_api.py
@@ -0,0 +1,191 @@
+import numpy as np
+import pytest
+
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import (
+    _GLOBAL_CONFIG, array_namespace, _asarray, xp_copy, xp_assert_equal, is_numpy,
+    np_compat, xp_default_dtype
+)
+from scipy._lib._array_api_no_0d import xp_assert_equal as xp_assert_equal_no_0d
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@pytest.mark.skipif(not _GLOBAL_CONFIG["SCIPY_ARRAY_API"],
+        reason="Array API test; set environment variable SCIPY_ARRAY_API=1 to run it")
+class TestArrayAPI:
+
+    def test_array_namespace(self):
+        x, y = np.array([0, 1, 2]), np.array([0, 1, 2])
+        xp = array_namespace(x, y)
+        assert 'array_api_compat.numpy' in xp.__name__
+
+        _GLOBAL_CONFIG["SCIPY_ARRAY_API"] = False
+        xp = array_namespace(x, y)
+        assert 'array_api_compat.numpy' in xp.__name__
+        _GLOBAL_CONFIG["SCIPY_ARRAY_API"] = True
+
+    @array_api_compatible
+    def test_asarray(self, xp):
+        x, y = _asarray([0, 1, 2], xp=xp), _asarray(np.arange(3), xp=xp)
+        ref = xp.asarray([0, 1, 2])
+        xp_assert_equal(x, ref)
+        xp_assert_equal(y, ref)
+
+    @pytest.mark.filterwarnings("ignore: the matrix subclass")
+    def test_raises(self):
+        msg = "of type `numpy.ma.MaskedArray` are not supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace(np.ma.array(1), np.array(1))
+
+        msg = "of type `numpy.matrix` are not supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace(np.array(1), np.matrix(1))
+
+        msg = "only boolean and numerical dtypes are supported"
+        with pytest.raises(TypeError, match=msg):
+            array_namespace([object()])
+        with pytest.raises(TypeError, match=msg):
+            array_namespace('abc')
+
+    def test_array_likes(self):
+        # should be no exceptions
+        array_namespace([0, 1, 2])
+        array_namespace(1, 2, 3)
+        array_namespace(1)
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_copy(self, xp):
+        for _xp in [xp, None]:
+            x = xp.asarray([1, 2, 3])
+            y = xp_copy(x, xp=_xp)
+            # with numpy we'd want to use np.shared_memory, but that's not specified
+            # in the array-api
+            x[0] = 10
+            x[1] = 11
+            x[2] = 12
+
+            assert x[0] != y[0]
+            assert x[1] != y[1]
+            assert x[2] != y[2]
+            assert id(x) != id(y)
+
+    @array_api_compatible
+    @pytest.mark.parametrize('dtype', ['int32', 'int64', 'float32', 'float64'])
+    @pytest.mark.parametrize('shape', [(), (3,)])
+    def test_strict_checks(self, xp, dtype, shape):
+        # Check that `_strict_check` behaves as expected
+        dtype = getattr(xp, dtype)
+        x = xp.broadcast_to(xp.asarray(1, dtype=dtype), shape)
+        x = x if shape else x[()]
+        y = np_compat.asarray(1)[()]
+
+        kwarg_names = ["check_namespace", "check_dtype", "check_shape", "check_0d"]
+        options = dict(zip(kwarg_names, [True, False, False, False]))
+        if xp == np:
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="Namespaces do not match."):
+                xp_assert_equal(x, y, **options)
+
+        options = dict(zip(kwarg_names, [False, True, False, False]))
+        if y.dtype.name in str(x.dtype):
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="dtypes do not match."):
+                xp_assert_equal(x, y, **options)
+
+        options = dict(zip(kwarg_names, [False, False, True, False]))
+        if x.shape == y.shape:
+            xp_assert_equal(x, y, **options)
+        else:
+            with pytest.raises(AssertionError, match="Shapes do not match."):
+                xp_assert_equal(x, xp.asarray(y), **options)
+
+        options = dict(zip(kwarg_names, [False, False, False, True]))
+        if is_numpy(xp) and x.shape == y.shape:
+            xp_assert_equal(x, y, **options)
+        elif is_numpy(xp):
+            with pytest.raises(AssertionError, match="Array-ness does not match."):
+                xp_assert_equal(x, y, **options)
+
+
+    @array_api_compatible
+    def test_check_scalar(self, xp):
+        if not is_numpy(xp):
+            pytest.skip("Scalars only exist in NumPy")
+
+        # identity always passes
+        xp_assert_equal(xp.float64(0), xp.float64(0))
+        xp_assert_equal(xp.asarray(0.), xp.asarray(0.))
+        xp_assert_equal(xp.float64(0), xp.float64(0), check_0d=False)
+        xp_assert_equal(xp.asarray(0.), xp.asarray(0.), check_0d=False)
+
+        # Check default convention: 0d-arrays are distinguished from scalars
+        message = "Array-ness does not match:.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.asarray(0.), xp.float64(0))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.float64(0), xp.asarray(0.))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.asarray(42), xp.int64(42))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal(xp.int64(42), xp.asarray(42))
+
+        # with `check_0d=False`, scalars-vs-0d passes (if values match)
+        xp_assert_equal(xp.asarray(0.), xp.float64(0), check_0d=False)
+        xp_assert_equal(xp.float64(0), xp.asarray(0.), check_0d=False)
+        # also with regular python objects
+        xp_assert_equal(xp.asarray(0.), 0., check_0d=False)
+        xp_assert_equal(0., xp.asarray(0.), check_0d=False)
+        xp_assert_equal(xp.asarray(42), 42, check_0d=False)
+        xp_assert_equal(42, xp.asarray(42), check_0d=False)
+
+        # as an alternative to `check_0d=False`, explicitly expect scalar
+        xp_assert_equal(xp.float64(0), xp.asarray(0.)[()])
+
+
+    @array_api_compatible
+    def test_check_scalar_no_0d(self, xp):
+        if not is_numpy(xp):
+            pytest.skip("Scalars only exist in NumPy")
+
+        # identity passes, if first argument is not 0d (or check_0d=True)
+        xp_assert_equal_no_0d(xp.float64(0), xp.float64(0))
+        xp_assert_equal_no_0d(xp.float64(0), xp.float64(0), check_0d=True)
+        xp_assert_equal_no_0d(xp.asarray(0.), xp.asarray(0.), check_0d=True)
+
+        # by default, 0d values are forbidden as the first argument
+        message = "Result is a NumPy 0d-array.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.asarray(0.))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.float64(0))
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(42), xp.int64(42))
+
+        # Check default convention: 0d-arrays are NOT distinguished from scalars
+        xp_assert_equal_no_0d(xp.float64(0), xp.asarray(0.))
+        xp_assert_equal_no_0d(xp.int64(42), xp.asarray(42))
+
+        # opt in to 0d-check remains possible
+        message = "Array-ness does not match:.*"
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(0.), xp.float64(0), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.float64(0), xp.asarray(0.), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.asarray(42), xp.int64(0), check_0d=True)
+        with pytest.raises(AssertionError, match=message):
+            xp_assert_equal_no_0d(xp.int64(0), xp.asarray(42), check_0d=True)
+
+        # scalars-vs-0d passes (if values match) also with regular python objects
+        xp_assert_equal_no_0d(0., xp.asarray(0.))
+        xp_assert_equal_no_0d(42, xp.asarray(42))
+
+    @array_api_compatible
+    def test_default_dtype(self, xp):
+        assert xp_default_dtype(xp) == xp.asarray(1.).dtype
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_bunch.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_bunch.py
new file mode 100644
index 0000000000000000000000000000000000000000..f19ca377129b925cad732dd25bf3089c646f923f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_bunch.py
@@ -0,0 +1,162 @@
+import pytest
+import pickle
+from numpy.testing import assert_equal
+from scipy._lib._bunch import _make_tuple_bunch
+
+
+# `Result` is defined at the top level of the module so it can be
+# used to test pickling.
+Result = _make_tuple_bunch('Result', ['x', 'y', 'z'], ['w', 'beta'])
+
+
+class TestMakeTupleBunch:
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Tests with Result
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    def setup_method(self):
+        # Set up an instance of Result.
+        self.result = Result(x=1, y=2, z=3, w=99, beta=0.5)
+
+    def test_attribute_access(self):
+        assert_equal(self.result.x, 1)
+        assert_equal(self.result.y, 2)
+        assert_equal(self.result.z, 3)
+        assert_equal(self.result.w, 99)
+        assert_equal(self.result.beta, 0.5)
+
+    def test_indexing(self):
+        assert_equal(self.result[0], 1)
+        assert_equal(self.result[1], 2)
+        assert_equal(self.result[2], 3)
+        assert_equal(self.result[-1], 3)
+        with pytest.raises(IndexError, match='index out of range'):
+            self.result[3]
+
+    def test_unpacking(self):
+        x0, y0, z0 = self.result
+        assert_equal((x0, y0, z0), (1, 2, 3))
+        assert_equal(self.result, (1, 2, 3))
+
+    def test_slice(self):
+        assert_equal(self.result[1:], (2, 3))
+        assert_equal(self.result[::2], (1, 3))
+        assert_equal(self.result[::-1], (3, 2, 1))
+
+    def test_len(self):
+        assert_equal(len(self.result), 3)
+
+    def test_repr(self):
+        s = repr(self.result)
+        assert_equal(s, 'Result(x=1, y=2, z=3, w=99, beta=0.5)')
+
+    def test_hash(self):
+        assert_equal(hash(self.result), hash((1, 2, 3)))
+
+    def test_pickle(self):
+        s = pickle.dumps(self.result)
+        obj = pickle.loads(s)
+        assert isinstance(obj, Result)
+        assert_equal(obj.x, self.result.x)
+        assert_equal(obj.y, self.result.y)
+        assert_equal(obj.z, self.result.z)
+        assert_equal(obj.w, self.result.w)
+        assert_equal(obj.beta, self.result.beta)
+
+    def test_read_only_existing(self):
+        with pytest.raises(AttributeError, match="can't set attribute"):
+            self.result.x = -1
+
+    def test_read_only_new(self):
+        self.result.plate_of_shrimp = "lattice of coincidence"
+        assert self.result.plate_of_shrimp == "lattice of coincidence"
+
+    def test_constructor_missing_parameter(self):
+        with pytest.raises(TypeError, match='missing'):
+            # `w` is missing.
+            Result(x=1, y=2, z=3, beta=0.75)
+
+    def test_constructor_incorrect_parameter(self):
+        with pytest.raises(TypeError, match='unexpected'):
+            # `foo` is not an existing field.
+            Result(x=1, y=2, z=3, w=123, beta=0.75, foo=999)
+
+    def test_module(self):
+        m = 'scipy._lib.tests.test_bunch'
+        assert_equal(Result.__module__, m)
+        assert_equal(self.result.__module__, m)
+
+    def test_extra_fields_per_instance(self):
+        # This test exists to ensure that instances of the same class
+        # store their own values for the extra fields. That is, the values
+        # are stored per instance and not in the class.
+        result1 = Result(x=1, y=2, z=3, w=-1, beta=0.0)
+        result2 = Result(x=4, y=5, z=6, w=99, beta=1.0)
+        assert_equal(result1.w, -1)
+        assert_equal(result1.beta, 0.0)
+        # The rest of these checks aren't essential, but let's check
+        # them anyway.
+        assert_equal(result1[:], (1, 2, 3))
+        assert_equal(result2.w, 99)
+        assert_equal(result2.beta, 1.0)
+        assert_equal(result2[:], (4, 5, 6))
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Other tests
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    def test_extra_field_names_is_optional(self):
+        Square = _make_tuple_bunch('Square', ['width', 'height'])
+        sq = Square(width=1, height=2)
+        assert_equal(sq.width, 1)
+        assert_equal(sq.height, 2)
+        s = repr(sq)
+        assert_equal(s, 'Square(width=1, height=2)')
+
+    def test_tuple_like(self):
+        Tup = _make_tuple_bunch('Tup', ['a', 'b'])
+        tu = Tup(a=1, b=2)
+        assert isinstance(tu, tuple)
+        assert isinstance(tu + (1,), tuple)
+
+    def test_explicit_module(self):
+        m = 'some.module.name'
+        Foo = _make_tuple_bunch('Foo', ['x'], ['a', 'b'], module=m)
+        foo = Foo(x=1, a=355, b=113)
+        assert_equal(Foo.__module__, m)
+        assert_equal(foo.__module__, m)
+
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+    # Argument validation
+    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+
+    @pytest.mark.parametrize('args', [('123', ['a'], ['b']),
+                                      ('Foo', ['-3'], ['x']),
+                                      ('Foo', ['a'], ['+-*/'])])
+    def test_identifiers_not_allowed(self, args):
+        with pytest.raises(ValueError, match='identifiers'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['a', 'b', 'a'], ['x']),
+                                      ('Foo', ['a', 'b'], ['b', 'x'])])
+    def test_repeated_field_names(self, args):
+        with pytest.raises(ValueError, match='Duplicate'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['_a'], ['x']),
+                                      ('Foo', ['a'], ['_x'])])
+    def test_leading_underscore_not_allowed(self, args):
+        with pytest.raises(ValueError, match='underscore'):
+            _make_tuple_bunch(*args)
+
+    @pytest.mark.parametrize('args', [('Foo', ['def'], ['x']),
+                                      ('Foo', ['a'], ['or']),
+                                      ('and', ['a'], ['x'])])
+    def test_keyword_not_allowed_in_fields(self, args):
+        with pytest.raises(ValueError, match='keyword'):
+            _make_tuple_bunch(*args)
+
+    def test_at_least_one_field_name_required(self):
+        with pytest.raises(ValueError, match='at least one name'):
+            _make_tuple_bunch('Qwerty', [], ['a', 'b'])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py
new file mode 100644
index 0000000000000000000000000000000000000000..82021775c294c7b881b9458b57d16deaac483cc7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py
@@ -0,0 +1,204 @@
+from numpy.testing import assert_equal, assert_
+from pytest import raises as assert_raises
+
+import time
+import pytest
+import ctypes
+import threading
+from scipy._lib import _ccallback_c as _test_ccallback_cython
+from scipy._lib import _test_ccallback
+from scipy._lib._ccallback import LowLevelCallable
+
+try:
+    import cffi
+    HAVE_CFFI = True
+except ImportError:
+    HAVE_CFFI = False
+
+
+ERROR_VALUE = 2.0
+
+
+def callback_python(a, user_data=None):
+    if a == ERROR_VALUE:
+        raise ValueError("bad value")
+
+    if user_data is None:
+        return a + 1
+    else:
+        return a + user_data
+
+def _get_cffi_func(base, signature):
+    if not HAVE_CFFI:
+        pytest.skip("cffi not installed")
+
+    # Get function address
+    voidp = ctypes.cast(base, ctypes.c_void_p)
+    address = voidp.value
+
+    # Create corresponding cffi handle
+    ffi = cffi.FFI()
+    func = ffi.cast(signature, address)
+    return func
+
+
+def _get_ctypes_data():
+    value = ctypes.c_double(2.0)
+    return ctypes.cast(ctypes.pointer(value), ctypes.c_voidp)
+
+
+def _get_cffi_data():
+    if not HAVE_CFFI:
+        pytest.skip("cffi not installed")
+    ffi = cffi.FFI()
+    return ffi.new('double *', 2.0)
+
+
+CALLERS = {
+    'simple': _test_ccallback.test_call_simple,
+    'nodata': _test_ccallback.test_call_nodata,
+    'nonlocal': _test_ccallback.test_call_nonlocal,
+    'cython': _test_ccallback_cython.test_call_cython,
+}
+
+# These functions have signatures known to the callers
+FUNCS = {
+    'python': lambda: callback_python,
+    'capsule': lambda: _test_ccallback.test_get_plus1_capsule(),
+    'cython': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                   "plus1_cython"),
+    'ctypes': lambda: _test_ccallback_cython.plus1_ctypes,
+    'cffi': lambda: _get_cffi_func(_test_ccallback_cython.plus1_ctypes,
+                                   'double (*)(double, int *, void *)'),
+    'capsule_b': lambda: _test_ccallback.test_get_plus1b_capsule(),
+    'cython_b': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                     "plus1b_cython"),
+    'ctypes_b': lambda: _test_ccallback_cython.plus1b_ctypes,
+    'cffi_b': lambda: _get_cffi_func(_test_ccallback_cython.plus1b_ctypes,
+                                     'double (*)(double, double, int *, void *)'),
+}
+
+# These functions have signatures the callers don't know
+BAD_FUNCS = {
+    'capsule_bc': lambda: _test_ccallback.test_get_plus1bc_capsule(),
+    'cython_bc': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
+                                                      "plus1bc_cython"),
+    'ctypes_bc': lambda: _test_ccallback_cython.plus1bc_ctypes,
+    'cffi_bc': lambda: _get_cffi_func(
+        _test_ccallback_cython.plus1bc_ctypes,
+        'double (*)(double, double, double, int *, void *)'
+    ),
+}
+
+USER_DATAS = {
+    'ctypes': _get_ctypes_data,
+    'cffi': _get_cffi_data,
+    'capsule': _test_ccallback.test_get_data_capsule,
+}
+
+
+def test_callbacks():
+    def check(caller, func, user_data):
+        caller = CALLERS[caller]
+        func = FUNCS[func]()
+        user_data = USER_DATAS[user_data]()
+
+        if func is callback_python:
+            def func2(x):
+                return func(x, 2.0)
+        else:
+            func2 = LowLevelCallable(func, user_data)
+            func = LowLevelCallable(func)
+
+        # Test basic call
+        assert_equal(caller(func, 1.0), 2.0)
+
+        # Test 'bad' value resulting to an error
+        assert_raises(ValueError, caller, func, ERROR_VALUE)
+
+        # Test passing in user_data
+        assert_equal(caller(func2, 1.0), 3.0)
+
+    for caller in sorted(CALLERS.keys()):
+        for func in sorted(FUNCS.keys()):
+            for user_data in sorted(USER_DATAS.keys()):
+                check(caller, func, user_data)
+
+
+def test_bad_callbacks():
+    def check(caller, func, user_data):
+        caller = CALLERS[caller]
+        user_data = USER_DATAS[user_data]()
+        func = BAD_FUNCS[func]()
+
+        if func is callback_python:
+            def func2(x):
+                return func(x, 2.0)
+        else:
+            func2 = LowLevelCallable(func, user_data)
+            func = LowLevelCallable(func)
+
+        # Test that basic call fails
+        assert_raises(ValueError, caller, LowLevelCallable(func), 1.0)
+
+        # Test that passing in user_data also fails
+        assert_raises(ValueError, caller, func2, 1.0)
+
+        # Test error message
+        llfunc = LowLevelCallable(func)
+        try:
+            caller(llfunc, 1.0)
+        except ValueError as err:
+            msg = str(err)
+            assert_(llfunc.signature in msg, msg)
+            assert_('double (double, double, int *, void *)' in msg, msg)
+
+    for caller in sorted(CALLERS.keys()):
+        for func in sorted(BAD_FUNCS.keys()):
+            for user_data in sorted(USER_DATAS.keys()):
+                check(caller, func, user_data)
+
+
+def test_signature_override():
+    caller = _test_ccallback.test_call_simple
+    func = _test_ccallback.test_get_plus1_capsule()
+
+    llcallable = LowLevelCallable(func, signature="bad signature")
+    assert_equal(llcallable.signature, "bad signature")
+    assert_raises(ValueError, caller, llcallable, 3)
+
+    llcallable = LowLevelCallable(func, signature="double (double, int *, void *)")
+    assert_equal(llcallable.signature, "double (double, int *, void *)")
+    assert_equal(caller(llcallable, 3), 4)
+
+
+def test_threadsafety():
+    def callback(a, caller):
+        if a <= 0:
+            return 1
+        else:
+            res = caller(lambda x: callback(x, caller), a - 1)
+            return 2*res
+
+    def check(caller):
+        caller = CALLERS[caller]
+
+        results = []
+
+        count = 10
+
+        def run():
+            time.sleep(0.01)
+            r = caller(lambda x: callback(x, caller), count)
+            results.append(r)
+
+        threads = [threading.Thread(target=run) for j in range(20)]
+        for thread in threads:
+            thread.start()
+        for thread in threads:
+            thread.join()
+
+        assert_equal(results, [2.0**count]*len(threads))
+
+    for caller in CALLERS.keys():
+        check(caller)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_config.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..794e365c0d8a5ce337765fc669d688e80240d540
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_config.py
@@ -0,0 +1,45 @@
+"""
+Check the SciPy config is valid.
+"""
+import scipy
+import pytest
+from unittest.mock import patch
+
+pytestmark = pytest.mark.skipif(
+    not hasattr(scipy.__config__, "_built_with_meson"),
+    reason="Requires Meson builds",
+)
+
+
+class TestSciPyConfigs:
+    REQUIRED_CONFIG_KEYS = [
+        "Compilers",
+        "Machine Information",
+        "Python Information",
+    ]
+
+    @pytest.mark.thread_unsafe
+    @patch("scipy.__config__._check_pyyaml")
+    def test_pyyaml_not_found(self, mock_yaml_importer):
+        mock_yaml_importer.side_effect = ModuleNotFoundError()
+        with pytest.warns(UserWarning):
+            scipy.show_config()
+
+    def test_dict_mode(self):
+        config = scipy.show_config(mode="dicts")
+
+        assert isinstance(config, dict)
+        assert all([key in config for key in self.REQUIRED_CONFIG_KEYS]), (
+            "Required key missing,"
+            " see index of `False` with `REQUIRED_CONFIG_KEYS`"
+        )
+
+    def test_invalid_mode(self):
+        with pytest.raises(AttributeError):
+            scipy.show_config(mode="foo")
+
+    def test_warn_to_add_tests(self):
+        assert len(scipy.__config__.DisplayModes) == 2, (
+            "New mode detected,"
+            " please add UT if applicable and increment this count"
+        )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_deprecation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..667e6ab94346fc8b22c0ea4d4624acf33124c8c0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_deprecation.py
@@ -0,0 +1,10 @@
+import pytest
+
+@pytest.mark.thread_unsafe
+def test_cython_api_deprecation():
+    match = ("`scipy._lib._test_deprecation_def.foo_deprecated` "
+             "is deprecated, use `foo` instead!\n"
+             "Deprecated in Scipy 42.0.0")
+    with pytest.warns(DeprecationWarning, match=match):
+        from .. import _test_deprecation_call
+    assert _test_deprecation_call.call() == (1, 1)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_doccer.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..176a69698b10bd1d0d23fc57f8e8a99ce7209f0f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_doccer.py
@@ -0,0 +1,143 @@
+''' Some tests for the documenting decorator and support functions '''
+
+import sys
+import pytest
+from numpy.testing import assert_equal, suppress_warnings
+
+from scipy._lib import doccer
+
+# python -OO strips docstrings
+DOCSTRINGS_STRIPPED = sys.flags.optimize > 1
+
+docstring = \
+"""Docstring
+    %(strtest1)s
+        %(strtest2)s
+     %(strtest3)s
+"""
+param_doc1 = \
+"""Another test
+   with some indent"""
+
+param_doc2 = \
+"""Another test, one line"""
+
+param_doc3 = \
+"""    Another test
+       with some indent"""
+
+doc_dict = {'strtest1':param_doc1,
+            'strtest2':param_doc2,
+            'strtest3':param_doc3}
+
+filled_docstring = \
+"""Docstring
+    Another test
+       with some indent
+        Another test, one line
+     Another test
+       with some indent
+"""
+
+
+def test_unindent():
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        assert_equal(doccer.unindent_string(param_doc1), param_doc1)
+        assert_equal(doccer.unindent_string(param_doc2), param_doc2)
+        assert_equal(doccer.unindent_string(param_doc3), param_doc1)
+
+
+def test_unindent_dict():
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        d2 = doccer.unindent_dict(doc_dict)
+    assert_equal(d2['strtest1'], doc_dict['strtest1'])
+    assert_equal(d2['strtest2'], doc_dict['strtest2'])
+    assert_equal(d2['strtest3'], doc_dict['strtest1'])
+
+
+def test_docformat():
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        udd = doccer.unindent_dict(doc_dict)
+        formatted = doccer.docformat(docstring, udd)
+        assert_equal(formatted, filled_docstring)
+        single_doc = 'Single line doc %(strtest1)s'
+        formatted = doccer.docformat(single_doc, doc_dict)
+        # Note - initial indent of format string does not
+        # affect subsequent indent of inserted parameter
+        assert_equal(formatted, """Single line doc Another test
+   with some indent""")
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
+def test_decorator():
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        # with unindentation of parameters
+        decorator = doccer.filldoc(doc_dict, True)
+
+        @decorator
+        def func():
+            """ Docstring
+            %(strtest3)s
+            """
+
+        def expected():
+            """ Docstring
+            Another test
+               with some indent
+            """
+        assert_equal(func.__doc__, expected.__doc__)
+
+        # without unindentation of parameters
+
+        # The docstring should be unindented for Python 3.13+
+        # because of https://github.com/python/cpython/issues/81283
+        decorator = doccer.filldoc(doc_dict, False if \
+                                   sys.version_info < (3, 13) else True)
+
+        @decorator
+        def func():
+            """ Docstring
+            %(strtest3)s
+            """
+        def expected():
+            """ Docstring
+                Another test
+                   with some indent
+            """
+        assert_equal(func.__doc__, expected.__doc__)
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
+def test_inherit_docstring_from():
+
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+
+        class Foo:
+            def func(self):
+                '''Do something useful.'''
+                return
+
+            def func2(self):
+                '''Something else.'''
+
+        class Bar(Foo):
+            @doccer.inherit_docstring_from(Foo)
+            def func(self):
+                '''%(super)sABC'''
+                return
+
+            @doccer.inherit_docstring_from(Foo)
+            def func2(self):
+                # No docstring.
+                return
+
+    assert_equal(Bar.func.__doc__, Foo.func.__doc__ + 'ABC')
+    assert_equal(Bar.func2.__doc__, Foo.func2.__doc__)
+    bar = Bar()
+    assert_equal(bar.func.__doc__, Foo.func.__doc__ + 'ABC')
+    assert_equal(bar.func2.__doc__, Foo.func2.__doc__)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_import_cycles.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_import_cycles.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a35800a8198af8215e0b5624738f9ac45b0bb96
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_import_cycles.py
@@ -0,0 +1,18 @@
+import pytest
+import sys
+import subprocess
+
+from .test_public_api import PUBLIC_MODULES
+
+# Regression tests for gh-6793.
+# Check that all modules are importable in a new Python process.
+# This is not necessarily true if there are import cycles present.
+
+@pytest.mark.fail_slow(40)
+@pytest.mark.slow
+@pytest.mark.thread_unsafe
+def test_public_modules_importable():
+    pids = [subprocess.Popen([sys.executable, '-c', f'import {module}'])
+            for module in PUBLIC_MODULES]
+    for i, pid in enumerate(pids):
+        assert pid.wait() == 0, f'Failed to import {PUBLIC_MODULES[i]}'
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..5332107cd21cdd2b6e40cc545c87138cee04ff97
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py
@@ -0,0 +1,469 @@
+"""
+This test script is adopted from:
+    https://github.com/numpy/numpy/blob/main/numpy/tests/test_public_api.py
+"""
+
+import pkgutil
+import types
+import importlib
+import warnings
+from importlib import import_module
+
+import pytest
+
+import numpy as np
+import scipy
+
+from scipy.conftest import xp_available_backends
+
+
+def test_dir_testing():
+    """Assert that output of dir has only one "testing/tester"
+    attribute without duplicate"""
+    assert len(dir(scipy)) == len(set(dir(scipy)))
+
+
+# Historically SciPy has not used leading underscores for private submodules
+# much.  This has resulted in lots of things that look like public modules
+# (i.e. things that can be imported as `import scipy.somesubmodule.somefile`),
+# but were never intended to be public.  The PUBLIC_MODULES list contains
+# modules that are either public because they were meant to be, or because they
+# contain public functions/objects that aren't present in any other namespace
+# for whatever reason and therefore should be treated as public.
+PUBLIC_MODULES = ["scipy." + s for s in [
+    "cluster",
+    "cluster.vq",
+    "cluster.hierarchy",
+    "constants",
+    "datasets",
+    "differentiate",
+    "fft",
+    "fftpack",
+    "integrate",
+    "interpolate",
+    "io",
+    "io.arff",
+    "io.matlab",
+    "io.wavfile",
+    "linalg",
+    "linalg.blas",
+    "linalg.cython_blas",
+    "linalg.lapack",
+    "linalg.cython_lapack",
+    "linalg.interpolative",
+    "ndimage",
+    "odr",
+    "optimize",
+    "optimize.elementwise",
+    "signal",
+    "signal.windows",
+    "sparse",
+    "sparse.linalg",
+    "sparse.csgraph",
+    "spatial",
+    "spatial.distance",
+    "spatial.transform",
+    "special",
+    "stats",
+    "stats.contingency",
+    "stats.distributions",
+    "stats.mstats",
+    "stats.qmc",
+    "stats.sampling"
+]]
+
+# The PRIVATE_BUT_PRESENT_MODULES list contains modules that lacked underscores
+# in their name and hence looked public, but weren't meant to be. All these
+# namespace were deprecated in the 1.8.0 release - see "clear split between
+# public and private API" in the 1.8.0 release notes.
+# These private modules support will be removed in SciPy v2.0.0, as the
+# deprecation messages emitted by each of these modules say.
+PRIVATE_BUT_PRESENT_MODULES = [
+    'scipy.constants.codata',
+    'scipy.constants.constants',
+    'scipy.fftpack.basic',
+    'scipy.fftpack.convolve',
+    'scipy.fftpack.helper',
+    'scipy.fftpack.pseudo_diffs',
+    'scipy.fftpack.realtransforms',
+    'scipy.integrate.dop',
+    'scipy.integrate.lsoda',
+    'scipy.integrate.odepack',
+    'scipy.integrate.quadpack',
+    'scipy.integrate.vode',
+    'scipy.interpolate.dfitpack',
+    'scipy.interpolate.fitpack',
+    'scipy.interpolate.fitpack2',
+    'scipy.interpolate.interpnd',
+    'scipy.interpolate.interpolate',
+    'scipy.interpolate.ndgriddata',
+    'scipy.interpolate.polyint',
+    'scipy.interpolate.rbf',
+    'scipy.io.arff.arffread',
+    'scipy.io.harwell_boeing',
+    'scipy.io.idl',
+    'scipy.io.matlab.byteordercodes',
+    'scipy.io.matlab.mio',
+    'scipy.io.matlab.mio4',
+    'scipy.io.matlab.mio5',
+    'scipy.io.matlab.mio5_params',
+    'scipy.io.matlab.mio5_utils',
+    'scipy.io.matlab.mio_utils',
+    'scipy.io.matlab.miobase',
+    'scipy.io.matlab.streams',
+    'scipy.io.mmio',
+    'scipy.io.netcdf',
+    'scipy.linalg.basic',
+    'scipy.linalg.decomp',
+    'scipy.linalg.decomp_cholesky',
+    'scipy.linalg.decomp_lu',
+    'scipy.linalg.decomp_qr',
+    'scipy.linalg.decomp_schur',
+    'scipy.linalg.decomp_svd',
+    'scipy.linalg.matfuncs',
+    'scipy.linalg.misc',
+    'scipy.linalg.special_matrices',
+    'scipy.misc',
+    'scipy.misc.common',
+    'scipy.misc.doccer',
+    'scipy.ndimage.filters',
+    'scipy.ndimage.fourier',
+    'scipy.ndimage.interpolation',
+    'scipy.ndimage.measurements',
+    'scipy.ndimage.morphology',
+    'scipy.odr.models',
+    'scipy.odr.odrpack',
+    'scipy.optimize.cobyla',
+    'scipy.optimize.cython_optimize',
+    'scipy.optimize.lbfgsb',
+    'scipy.optimize.linesearch',
+    'scipy.optimize.minpack',
+    'scipy.optimize.minpack2',
+    'scipy.optimize.moduleTNC',
+    'scipy.optimize.nonlin',
+    'scipy.optimize.optimize',
+    'scipy.optimize.slsqp',
+    'scipy.optimize.tnc',
+    'scipy.optimize.zeros',
+    'scipy.signal.bsplines',
+    'scipy.signal.filter_design',
+    'scipy.signal.fir_filter_design',
+    'scipy.signal.lti_conversion',
+    'scipy.signal.ltisys',
+    'scipy.signal.signaltools',
+    'scipy.signal.spectral',
+    'scipy.signal.spline',
+    'scipy.signal.waveforms',
+    'scipy.signal.wavelets',
+    'scipy.signal.windows.windows',
+    'scipy.sparse.base',
+    'scipy.sparse.bsr',
+    'scipy.sparse.compressed',
+    'scipy.sparse.construct',
+    'scipy.sparse.coo',
+    'scipy.sparse.csc',
+    'scipy.sparse.csr',
+    'scipy.sparse.data',
+    'scipy.sparse.dia',
+    'scipy.sparse.dok',
+    'scipy.sparse.extract',
+    'scipy.sparse.lil',
+    'scipy.sparse.linalg.dsolve',
+    'scipy.sparse.linalg.eigen',
+    'scipy.sparse.linalg.interface',
+    'scipy.sparse.linalg.isolve',
+    'scipy.sparse.linalg.matfuncs',
+    'scipy.sparse.sparsetools',
+    'scipy.sparse.spfuncs',
+    'scipy.sparse.sputils',
+    'scipy.spatial.ckdtree',
+    'scipy.spatial.kdtree',
+    'scipy.spatial.qhull',
+    'scipy.spatial.transform.rotation',
+    'scipy.special.add_newdocs',
+    'scipy.special.basic',
+    'scipy.special.cython_special',
+    'scipy.special.orthogonal',
+    'scipy.special.sf_error',
+    'scipy.special.specfun',
+    'scipy.special.spfun_stats',
+    'scipy.stats.biasedurn',
+    'scipy.stats.kde',
+    'scipy.stats.morestats',
+    'scipy.stats.mstats_basic',
+    'scipy.stats.mstats_extras',
+    'scipy.stats.mvn',
+    'scipy.stats.stats',
+]
+
+
+def is_unexpected(name):
+    """Check if this needs to be considered."""
+    if '._' in name or '.tests' in name or '.setup' in name:
+        return False
+
+    if name in PUBLIC_MODULES:
+        return False
+
+    if name in PRIVATE_BUT_PRESENT_MODULES:
+        return False
+
+    return True
+
+
+SKIP_LIST = [
+    'scipy.conftest',
+    'scipy.version',
+    'scipy.special.libsf_error_state'
+]
+
+
+# XXX: this test does more than it says on the tin - in using `pkgutil.walk_packages`,
+# it will raise if it encounters any exceptions which are not handled by `ignore_errors`
+# while attempting to import each discovered package.
+# For now, `ignore_errors` only ignores what is necessary, but this could be expanded -
+# for example, to all errors from private modules or git subpackages - if desired.
+@pytest.mark.thread_unsafe
+def test_all_modules_are_expected():
+    """
+    Test that we don't add anything that looks like a new public module by
+    accident.  Check is based on filenames.
+    """
+
+    def ignore_errors(name):
+        # if versions of other array libraries are installed which are incompatible
+        # with the installed NumPy version, there can be errors on importing
+        # `array_api_compat`. This should only raise if SciPy is configured with
+        # that library as an available backend.
+        backends = {'cupy', 'torch', 'dask.array'}
+        for backend in backends:
+            path = f'array_api_compat.{backend}'
+            if path in name and backend not in xp_available_backends:
+                return
+        raise
+
+    modnames = []
+
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(DeprecationWarning,"scipy.misc")
+        for _, modname, _ in pkgutil.walk_packages(path=scipy.__path__,
+                                                   prefix=scipy.__name__ + '.',
+                                                   onerror=ignore_errors):
+            if is_unexpected(modname) and modname not in SKIP_LIST:
+                # We have a name that is new.  If that's on purpose, add it to
+                # PUBLIC_MODULES.  We don't expect to have to add anything to
+                # PRIVATE_BUT_PRESENT_MODULES.  Use an underscore in the name!
+                modnames.append(modname)
+
+    if modnames:
+        raise AssertionError(f'Found unexpected modules: {modnames}')
+
+
+# Stuff that clearly shouldn't be in the API and is detected by the next test
+# below
+SKIP_LIST_2 = [
+    'scipy.char',
+    'scipy.rec',
+    'scipy.emath',
+    'scipy.math',
+    'scipy.random',
+    'scipy.ctypeslib',
+    'scipy.ma'
+]
+
+
+def test_all_modules_are_expected_2():
+    """
+    Method checking all objects. The pkgutil-based method in
+    `test_all_modules_are_expected` does not catch imports into a namespace,
+    only filenames.
+    """
+
+    def find_unexpected_members(mod_name):
+        members = []
+        module = importlib.import_module(mod_name)
+        if hasattr(module, '__all__'):
+            objnames = module.__all__
+        else:
+            objnames = dir(module)
+
+        for objname in objnames:
+            if not objname.startswith('_'):
+                fullobjname = mod_name + '.' + objname
+                if isinstance(getattr(module, objname), types.ModuleType):
+                    if is_unexpected(fullobjname) and fullobjname not in SKIP_LIST_2:
+                        members.append(fullobjname)
+
+        return members
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(DeprecationWarning, "scipy.misc")
+        unexpected_members = find_unexpected_members("scipy")
+
+    for modname in PUBLIC_MODULES:
+        unexpected_members.extend(find_unexpected_members(modname))
+
+    if unexpected_members:
+        raise AssertionError("Found unexpected object(s) that look like "
+                             f"modules: {unexpected_members}")
+
+
+def test_api_importable():
+    """
+    Check that all submodules listed higher up in this file can be imported
+    Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may
+    simply need to be removed from the list (deprecation may or may not be
+    needed - apply common sense).
+    """
+    def check_importable(module_name):
+        try:
+            importlib.import_module(module_name)
+        except (ImportError, AttributeError):
+            return False
+
+        return True
+
+    module_names = []
+    for module_name in PUBLIC_MODULES:
+        if not check_importable(module_name):
+            module_names.append(module_name)
+
+    if module_names:
+        raise AssertionError("Modules in the public API that cannot be "
+                             f"imported: {module_names}")
+
+    with warnings.catch_warnings(record=True):
+        warnings.filterwarnings('always', category=DeprecationWarning)
+        warnings.filterwarnings('always', category=ImportWarning)
+        for module_name in PRIVATE_BUT_PRESENT_MODULES:
+            if not check_importable(module_name):
+                module_names.append(module_name)
+
+    if module_names:
+        raise AssertionError("Modules that are not really public but looked "
+                             "public and can not be imported: "
+                             f"{module_names}")
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.parametrize(("module_name", "correct_module"),
+                         [('scipy.constants.codata', None),
+                          ('scipy.constants.constants', None),
+                          ('scipy.fftpack.basic', None),
+                          ('scipy.fftpack.helper', None),
+                          ('scipy.fftpack.pseudo_diffs', None),
+                          ('scipy.fftpack.realtransforms', None),
+                          ('scipy.integrate.dop', None),
+                          ('scipy.integrate.lsoda', None),
+                          ('scipy.integrate.odepack', None),
+                          ('scipy.integrate.quadpack', None),
+                          ('scipy.integrate.vode', None),
+                          ('scipy.interpolate.fitpack', None),
+                          ('scipy.interpolate.fitpack2', None),
+                          ('scipy.interpolate.interpolate', None),
+                          ('scipy.interpolate.ndgriddata', None),
+                          ('scipy.interpolate.polyint', None),
+                          ('scipy.interpolate.rbf', None),
+                          ('scipy.io.harwell_boeing', None),
+                          ('scipy.io.idl', None),
+                          ('scipy.io.mmio', None),
+                          ('scipy.io.netcdf', None),
+                          ('scipy.io.arff.arffread', 'arff'),
+                          ('scipy.io.matlab.byteordercodes', 'matlab'),
+                          ('scipy.io.matlab.mio_utils', 'matlab'),
+                          ('scipy.io.matlab.mio', 'matlab'),
+                          ('scipy.io.matlab.mio4', 'matlab'),
+                          ('scipy.io.matlab.mio5_params', 'matlab'),
+                          ('scipy.io.matlab.mio5_utils', 'matlab'),
+                          ('scipy.io.matlab.mio5', 'matlab'),
+                          ('scipy.io.matlab.miobase', 'matlab'),
+                          ('scipy.io.matlab.streams', 'matlab'),
+                          ('scipy.linalg.basic', None),
+                          ('scipy.linalg.decomp', None),
+                          ('scipy.linalg.decomp_cholesky', None),
+                          ('scipy.linalg.decomp_lu', None),
+                          ('scipy.linalg.decomp_qr', None),
+                          ('scipy.linalg.decomp_schur', None),
+                          ('scipy.linalg.decomp_svd', None),
+                          ('scipy.linalg.matfuncs', None),
+                          ('scipy.linalg.misc', None),
+                          ('scipy.linalg.special_matrices', None),
+                          ('scipy.ndimage.filters', None),
+                          ('scipy.ndimage.fourier', None),
+                          ('scipy.ndimage.interpolation', None),
+                          ('scipy.ndimage.measurements', None),
+                          ('scipy.ndimage.morphology', None),
+                          ('scipy.odr.models', None),
+                          ('scipy.odr.odrpack', None),
+                          ('scipy.optimize.cobyla', None),
+                          ('scipy.optimize.lbfgsb', None),
+                          ('scipy.optimize.linesearch', None),
+                          ('scipy.optimize.minpack', None),
+                          ('scipy.optimize.minpack2', None),
+                          ('scipy.optimize.moduleTNC', None),
+                          ('scipy.optimize.nonlin', None),
+                          ('scipy.optimize.optimize', None),
+                          ('scipy.optimize.slsqp', None),
+                          ('scipy.optimize.tnc', None),
+                          ('scipy.optimize.zeros', None),
+                          ('scipy.signal.bsplines', None),
+                          ('scipy.signal.filter_design', None),
+                          ('scipy.signal.fir_filter_design', None),
+                          ('scipy.signal.lti_conversion', None),
+                          ('scipy.signal.ltisys', None),
+                          ('scipy.signal.signaltools', None),
+                          ('scipy.signal.spectral', None),
+                          ('scipy.signal.waveforms', None),
+                          ('scipy.signal.wavelets', None),
+                          ('scipy.signal.windows.windows', 'windows'),
+                          ('scipy.sparse.lil', None),
+                          ('scipy.sparse.linalg.dsolve', 'linalg'),
+                          ('scipy.sparse.linalg.eigen', 'linalg'),
+                          ('scipy.sparse.linalg.interface', 'linalg'),
+                          ('scipy.sparse.linalg.isolve', 'linalg'),
+                          ('scipy.sparse.linalg.matfuncs', 'linalg'),
+                          ('scipy.sparse.sparsetools', None),
+                          ('scipy.sparse.spfuncs', None),
+                          ('scipy.sparse.sputils', None),
+                          ('scipy.spatial.ckdtree', None),
+                          ('scipy.spatial.kdtree', None),
+                          ('scipy.spatial.qhull', None),
+                          ('scipy.spatial.transform.rotation', 'transform'),
+                          ('scipy.special.add_newdocs', None),
+                          ('scipy.special.basic', None),
+                          ('scipy.special.orthogonal', None),
+                          ('scipy.special.sf_error', None),
+                          ('scipy.special.specfun', None),
+                          ('scipy.special.spfun_stats', None),
+                          ('scipy.stats.biasedurn', None),
+                          ('scipy.stats.kde', None),
+                          ('scipy.stats.morestats', None),
+                          ('scipy.stats.mstats_basic', 'mstats'),
+                          ('scipy.stats.mstats_extras', 'mstats'),
+                          ('scipy.stats.mvn', None),
+                          ('scipy.stats.stats', None)])
+def test_private_but_present_deprecation(module_name, correct_module):
+    # gh-18279, gh-17572, gh-17771 noted that deprecation warnings
+    # for imports from private modules
+    # were misleading. Check that this is resolved.
+    module = import_module(module_name)
+    if correct_module is None:
+        import_name = f'scipy.{module_name.split(".")[1]}'
+    else:
+        import_name = f'scipy.{module_name.split(".")[1]}.{correct_module}'
+
+    correct_import = import_module(import_name)
+
+    # Attributes that were formerly in `module_name` can still be imported from
+    # `module_name`, albeit with a deprecation warning.
+    for attr_name in module.__all__:
+        # ensure attribute is present where the warning is pointing
+        assert getattr(correct_import, attr_name, None) is not None
+        message = f"Please import `{attr_name}` from the `{import_name}`..."
+        with pytest.deprecated_call(match=message):
+            getattr(module, attr_name)
+
+    # Attributes that were not in `module_name` get an error notifying the user
+    # that the attribute is not in `module_name` and that `module_name` is deprecated.
+    message = f"`{module_name}` is deprecated..."
+    with pytest.raises(AttributeError, match=message):
+        getattr(module, "ekki")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_scipy_version.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_scipy_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..68e1a43c3fb329b6a4274ba76b53a215738da6ad
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_scipy_version.py
@@ -0,0 +1,28 @@
+import re
+
+import scipy
+import scipy.version
+
+
+def test_valid_scipy_version():
+    # Verify that the SciPy version is a valid one (no .post suffix or other
+    # nonsense). See NumPy issue gh-6431 for an issue caused by an invalid
+    # version.
+    version_pattern = r"^[0-9]+\.[0-9]+\.[0-9]+(|a[0-9]|b[0-9]|rc[0-9])"
+    dev_suffix = r"((.dev0)|(\.dev0+\+git[0-9]{8}.[0-9a-f]{7}))"
+    if scipy.version.release:
+        res = re.match(version_pattern, scipy.__version__)
+    else:
+        res = re.match(version_pattern + dev_suffix, scipy.__version__)
+
+    assert res is not None
+    assert scipy.__version__
+
+
+def test_version_submodule_members():
+    """`scipy.version` may not be quite public, but we install it.
+
+    So check that we don't silently change its contents.
+    """
+    for attr in ('version', 'full_version', 'short_version', 'git_revision', 'release'):
+        assert hasattr(scipy.version, attr)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_tmpdirs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_tmpdirs.py
new file mode 100644
index 0000000000000000000000000000000000000000..292e7ab1739e663979f9f0b9647fb2c7c95d625c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_tmpdirs.py
@@ -0,0 +1,48 @@
+""" Test tmpdirs module """
+from os import getcwd
+from os.path import realpath, abspath, dirname, isfile, join as pjoin, exists
+
+from scipy._lib._tmpdirs import tempdir, in_tempdir, in_dir
+
+from numpy.testing import assert_, assert_equal
+
+import pytest
+
+
+MY_PATH = abspath(__file__)
+MY_DIR = dirname(MY_PATH)
+
+
+@pytest.mark.thread_unsafe
+def test_tempdir():
+    with tempdir() as tmpdir:
+        fname = pjoin(tmpdir, 'example_file.txt')
+        with open(fname, "w") as fobj:
+            fobj.write('a string\\n')
+    assert_(not exists(tmpdir))
+
+
+@pytest.mark.thread_unsafe
+def test_in_tempdir():
+    my_cwd = getcwd()
+    with in_tempdir() as tmpdir:
+        with open('test.txt', "w") as f:
+            f.write('some text')
+        assert_(isfile('test.txt'))
+        assert_(isfile(pjoin(tmpdir, 'test.txt')))
+    assert_(not exists(tmpdir))
+    assert_equal(getcwd(), my_cwd)
+
+
+@pytest.mark.thread_unsafe
+def test_given_directory():
+    # Test InGivenDirectory
+    cwd = getcwd()
+    with in_dir() as tmpdir:
+        assert_equal(tmpdir, abspath(cwd))
+        assert_equal(tmpdir, abspath(getcwd()))
+    with in_dir(MY_DIR) as tmpdir:
+        assert_equal(tmpdir, MY_DIR)
+        assert_equal(realpath(MY_DIR), realpath(abspath(getcwd())))
+    # We were deleting the given directory! Check not so now.
+    assert_(isfile(MY_PATH))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_warnings.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..f200b1a6e9756b17c96e5b8368271bbf61878d72
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/tests/test_warnings.py
@@ -0,0 +1,137 @@
+"""
+Tests which scan for certain occurrences in the code, they may not find
+all of these occurrences but should catch almost all. This file was adapted
+from NumPy.
+"""
+
+
+import os
+from pathlib import Path
+import ast
+import tokenize
+
+import scipy
+
+import pytest
+
+
+class ParseCall(ast.NodeVisitor):
+    def __init__(self):
+        self.ls = []
+
+    def visit_Attribute(self, node):
+        ast.NodeVisitor.generic_visit(self, node)
+        self.ls.append(node.attr)
+
+    def visit_Name(self, node):
+        self.ls.append(node.id)
+
+
+class FindFuncs(ast.NodeVisitor):
+    def __init__(self, filename):
+        super().__init__()
+        self.__filename = filename
+        self.bad_filters = []
+        self.bad_stacklevels = []
+
+    def visit_Call(self, node):
+        p = ParseCall()
+        p.visit(node.func)
+        ast.NodeVisitor.generic_visit(self, node)
+
+        if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
+            # get first argument of the `args` node of the filter call
+            match node.args[0]:
+                case ast.Constant() as c:
+                    argtext = c.value
+                case ast.JoinedStr() as js:
+                    # if we get an f-string, discard the templated pieces, which
+                    # are likely the type or specific message; we're interested
+                    # in the action, which is less likely to use a template
+                    argtext = "".join(
+                        x.value for x in js.values if isinstance(x, ast.Constant)
+                    )
+                case _:
+                    raise ValueError("unknown ast node type")
+            # check if filter is set to ignore
+            if argtext == "ignore":
+                self.bad_filters.append(
+                    f"{self.__filename}:{node.lineno}")
+
+        if p.ls[-1] == 'warn' and (
+                len(p.ls) == 1 or p.ls[-2] == 'warnings'):
+
+            if self.__filename == "_lib/tests/test_warnings.py":
+                # This file
+                return
+
+            # See if stacklevel exists:
+            if len(node.args) == 3:
+                return
+            args = {kw.arg for kw in node.keywords}
+            if "stacklevel" not in args:
+                self.bad_stacklevels.append(
+                    f"{self.__filename}:{node.lineno}")
+
+
+@pytest.fixture(scope="session")
+def warning_calls():
+    # combined "ignore" and stacklevel error
+    base = Path(scipy.__file__).parent
+
+    bad_filters = []
+    bad_stacklevels = []
+
+    for path in base.rglob("*.py"):
+        # use tokenize to auto-detect encoding on systems where no
+        # default encoding is defined (e.g., LANG='C')
+        with tokenize.open(str(path)) as file:
+            tree = ast.parse(file.read(), filename=str(path))
+            finder = FindFuncs(path.relative_to(base))
+            finder.visit(tree)
+            bad_filters.extend(finder.bad_filters)
+            bad_stacklevels.extend(finder.bad_stacklevels)
+
+    return bad_filters, bad_stacklevels
+
+
+@pytest.mark.fail_slow(40)
+@pytest.mark.slow
+def test_warning_calls_filters(warning_calls):
+    bad_filters, bad_stacklevels = warning_calls
+
+    # We try not to add filters in the code base, because those filters aren't
+    # thread-safe. We aim to only filter in tests with
+    # np.testing.suppress_warnings. However, in some cases it may prove
+    # necessary to filter out warnings, because we can't (easily) fix the root
+    # cause for them and we don't want users to see some warnings when they use
+    # SciPy correctly. So we list exceptions here.  Add new entries only if
+    # there's a good reason.
+    allowed_filters = (
+        os.path.join('datasets', '_fetchers.py'),
+        os.path.join('datasets', '__init__.py'),
+        os.path.join('optimize', '_optimize.py'),
+        os.path.join('optimize', '_constraints.py'),
+        os.path.join('optimize', '_nnls.py'),
+        os.path.join('signal', '_ltisys.py'),
+        os.path.join('sparse', '__init__.py'),  # np.matrix pending-deprecation
+        os.path.join('special', '_basic.py'),  # gh-21801
+        os.path.join('stats', '_discrete_distns.py'),  # gh-14901
+        os.path.join('stats', '_continuous_distns.py'),
+        os.path.join('stats', '_binned_statistic.py'),  # gh-19345
+        os.path.join('stats', '_stats_py.py'),  # gh-20743
+        os.path.join('stats', 'tests', 'test_axis_nan_policy.py'),  # gh-20694
+        os.path.join('_lib', '_util.py'),  # gh-19341
+        os.path.join('sparse', 'linalg', '_dsolve', 'linsolve.py'),  # gh-17924
+        "conftest.py",
+    )
+    bad_filters = [item for item in bad_filters if item.split(':')[0] not in
+                   allowed_filters]
+
+    if bad_filters:
+        raise AssertionError(
+            "warning ignore filter should not be used, instead, use\n"
+            "numpy.testing.suppress_warnings (in tests only);\n"
+            "found in:\n    {}".format(
+                "\n    ".join(bad_filters)))
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/uarray.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/uarray.py
new file mode 100644
index 0000000000000000000000000000000000000000..b29fc713efb3e836cc179ac87ce41f87b51870ef
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/_lib/uarray.py
@@ -0,0 +1,31 @@
+"""`uarray` provides functions for generating multimethods that dispatch to
+multiple different backends
+
+This should be imported, rather than `_uarray` so that an installed version could
+be used instead, if available. This means that users can call
+`uarray.set_backend` directly instead of going through SciPy.
+
+"""
+
+
+# Prefer an installed version of uarray, if available
+try:
+    import uarray as _uarray
+except ImportError:
+    _has_uarray = False
+else:
+    from scipy._lib._pep440 import Version as _Version
+
+    _has_uarray = _Version(_uarray.__version__) >= _Version("0.8")
+    del _uarray
+    del _Version
+
+
+if _has_uarray:
+    from uarray import *  # noqa: F403
+    from uarray import _Function
+else:
+    from ._uarray import *  # noqa: F403
+    from ._uarray import _Function  # noqa: F401
+
+del _has_uarray
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdf939b249c17256b622c2f2756a5f34c4a128cc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__init__.py
@@ -0,0 +1,358 @@
+r"""
+==================================
+Constants (:mod:`scipy.constants`)
+==================================
+
+.. currentmodule:: scipy.constants
+
+Physical and mathematical constants and units.
+
+
+Mathematical constants
+======================
+
+================  =================================================================
+``pi``            Pi
+``golden``        Golden ratio
+``golden_ratio``  Golden ratio
+================  =================================================================
+
+
+Physical constants
+==================
+The following physical constants are available as attributes of `scipy.constants`.
+All units are `SI `_.
+
+===========================  ================================================================  ===============
+Attribute                    Quantity                                                          Units
+===========================  ================================================================  ===============
+``c``                        speed of light in vacuum                                          m s^-1
+``speed_of_light``           speed of light in vacuum                                          m s^-1
+``mu_0``                     the magnetic constant :math:`\mu_0`                               N A^-2
+``epsilon_0``                the electric constant (vacuum permittivity), :math:`\epsilon_0`   F m^-1
+``h``                        the Planck constant :math:`h`                                     J Hz^-1
+``Planck``                   the Planck constant :math:`h`                                     J Hz^-1
+``hbar``                     the reduced Planck constant, :math:`\hbar = h/(2\pi)`             J s
+``G``                        Newtonian constant of gravitation                                 m^3 kg^-1 s^-2
+``gravitational_constant``   Newtonian constant of gravitation                                 m^3 kg^-1 s^-2
+``g``                        standard acceleration of gravity                                  m s^-2
+``e``                        elementary charge                                                 C
+``elementary_charge``        elementary charge                                                 C
+``R``                        molar gas constant                                                J mol^-1 K^-1
+``gas_constant``             molar gas constant                                                J mol^-1 K^-1
+``alpha``                    fine-structure constant                                           (unitless)
+``fine_structure``           fine-structure constant                                           (unitless)
+``N_A``                      Avogadro constant                                                 mol^-1
+``Avogadro``                 Avogadro constant                                                 mol^-1
+``k``                        Boltzmann constant                                                J K^-1
+``Boltzmann``                Boltzmann constant                                                J K^-1
+``sigma``                    Stefan-Boltzmann constant :math:`\sigma`                          W m^-2 K^-4
+``Stefan_Boltzmann``         Stefan-Boltzmann constant :math:`\sigma`                          W m^-2 K^-4
+``Wien``                     Wien wavelength displacement law constant                         m K
+``Rydberg``                  Rydberg constant                                                  m^-1
+``m_e``                      electron mass                                                     kg
+``electron_mass``            electron mass                                                     kg
+``m_p``                      proton mass                                                       kg
+``proton_mass``              proton mass                                                       kg
+``m_n``                      neutron mass                                                      kg
+``neutron_mass``             neutron mass                                                      kg
+===========================  ================================================================  ===============
+
+
+Constants database
+------------------
+
+In addition to the above variables, :mod:`scipy.constants` also contains the
+2022 CODATA recommended values [CODATA2022]_ database containing more physical
+constants.
+
+.. autosummary::
+   :toctree: generated/
+
+   value      -- Value in physical_constants indexed by key
+   unit       -- Unit in physical_constants indexed by key
+   precision  -- Relative precision in physical_constants indexed by key
+   find       -- Return list of physical_constant keys with a given string
+   ConstantWarning -- Constant sought not in newest CODATA data set
+
+.. data:: physical_constants
+
+   Dictionary of physical constants, of the format
+   ``physical_constants[name] = (value, unit, uncertainty)``.
+   The CODATA database uses ellipses to indicate that a value is defined
+   (exactly) in terms of others but cannot be represented exactly with the
+   allocated number of digits. In these cases, SciPy calculates the derived
+   value and reports it to the full precision of a Python ``float``. Although 
+   ``physical_constants`` lists the uncertainty as ``0.0`` to indicate that
+   the CODATA value is exact, the value in ``physical_constants`` is still
+   subject to the truncation error inherent in double-precision representation.
+
+Available constants:
+
+======================================================================  ====
+%(constant_names)s
+======================================================================  ====
+
+
+Units
+=====
+
+SI prefixes
+-----------
+
+============  =================================================================
+``quetta``    :math:`10^{30}`
+``ronna``     :math:`10^{27}`
+``yotta``     :math:`10^{24}`
+``zetta``     :math:`10^{21}`
+``exa``       :math:`10^{18}`
+``peta``      :math:`10^{15}`
+``tera``      :math:`10^{12}`
+``giga``      :math:`10^{9}`
+``mega``      :math:`10^{6}`
+``kilo``      :math:`10^{3}`
+``hecto``     :math:`10^{2}`
+``deka``      :math:`10^{1}`
+``deci``      :math:`10^{-1}`
+``centi``     :math:`10^{-2}`
+``milli``     :math:`10^{-3}`
+``micro``     :math:`10^{-6}`
+``nano``      :math:`10^{-9}`
+``pico``      :math:`10^{-12}`
+``femto``     :math:`10^{-15}`
+``atto``      :math:`10^{-18}`
+``zepto``     :math:`10^{-21}`
+``yocto``     :math:`10^{-24}`
+``ronto``     :math:`10^{-27}`
+``quecto``    :math:`10^{-30}`
+============  =================================================================
+
+Binary prefixes
+---------------
+
+============  =================================================================
+``kibi``      :math:`2^{10}`
+``mebi``      :math:`2^{20}`
+``gibi``      :math:`2^{30}`
+``tebi``      :math:`2^{40}`
+``pebi``      :math:`2^{50}`
+``exbi``      :math:`2^{60}`
+``zebi``      :math:`2^{70}`
+``yobi``      :math:`2^{80}`
+============  =================================================================
+
+Mass
+----
+
+=================  ============================================================
+``gram``           :math:`10^{-3}` kg
+``metric_ton``     :math:`10^{3}` kg
+``grain``          one grain in kg
+``lb``             one pound (avoirdupous) in kg
+``pound``          one pound (avoirdupous) in kg
+``blob``           one inch version of a slug in kg (added in 1.0.0)
+``slinch``         one inch version of a slug in kg (added in 1.0.0)
+``slug``           one slug in kg (added in 1.0.0)
+``oz``             one ounce in kg
+``ounce``          one ounce in kg
+``stone``          one stone in kg
+``grain``          one grain in kg
+``long_ton``       one long ton in kg
+``short_ton``      one short ton in kg
+``troy_ounce``     one Troy ounce in kg
+``troy_pound``     one Troy pound in kg
+``carat``          one carat in kg
+``m_u``            atomic mass constant (in kg)
+``u``              atomic mass constant (in kg)
+``atomic_mass``    atomic mass constant (in kg)
+=================  ============================================================
+
+Angle
+-----
+
+=================  ============================================================
+``degree``         degree in radians
+``arcmin``         arc minute in radians
+``arcminute``      arc minute in radians
+``arcsec``         arc second in radians
+``arcsecond``      arc second in radians
+=================  ============================================================
+
+
+Time
+----
+
+=================  ============================================================
+``minute``         one minute in seconds
+``hour``           one hour in seconds
+``day``            one day in seconds
+``week``           one week in seconds
+``year``           one year (365 days) in seconds
+``Julian_year``    one Julian year (365.25 days) in seconds
+=================  ============================================================
+
+
+Length
+------
+
+=====================  ============================================================
+``inch``               one inch in meters
+``foot``               one foot in meters
+``yard``               one yard in meters
+``mile``               one mile in meters
+``mil``                one mil in meters
+``pt``                 one point in meters
+``point``              one point in meters
+``survey_foot``        one survey foot in meters
+``survey_mile``        one survey mile in meters
+``nautical_mile``      one nautical mile in meters
+``fermi``              one Fermi in meters
+``angstrom``           one Angstrom in meters
+``micron``             one micron in meters
+``au``                 one astronomical unit in meters
+``astronomical_unit``  one astronomical unit in meters
+``light_year``         one light year in meters
+``parsec``             one parsec in meters
+=====================  ============================================================
+
+Pressure
+--------
+
+=================  ============================================================
+``atm``            standard atmosphere in pascals
+``atmosphere``     standard atmosphere in pascals
+``bar``            one bar in pascals
+``torr``           one torr (mmHg) in pascals
+``mmHg``           one torr (mmHg) in pascals
+``psi``            one psi in pascals
+=================  ============================================================
+
+Area
+----
+
+=================  ============================================================
+``hectare``        one hectare in square meters
+``acre``           one acre in square meters
+=================  ============================================================
+
+
+Volume
+------
+
+===================    ========================================================
+``liter``              one liter in cubic meters
+``litre``              one liter in cubic meters
+``gallon``             one gallon (US) in cubic meters
+``gallon_US``          one gallon (US) in cubic meters
+``gallon_imp``         one gallon (UK) in cubic meters
+``fluid_ounce``        one fluid ounce (US) in cubic meters
+``fluid_ounce_US``     one fluid ounce (US) in cubic meters
+``fluid_ounce_imp``    one fluid ounce (UK) in cubic meters
+``bbl``                one barrel in cubic meters
+``barrel``             one barrel in cubic meters
+===================    ========================================================
+
+Speed
+-----
+
+==================    ==========================================================
+``kmh``               kilometers per hour in meters per second
+``mph``               miles per hour in meters per second
+``mach``              one Mach (approx., at 15 C, 1 atm) in meters per second
+``speed_of_sound``    one Mach (approx., at 15 C, 1 atm) in meters per second
+``knot``              one knot in meters per second
+==================    ==========================================================
+
+
+Temperature
+-----------
+
+=====================  =======================================================
+``zero_Celsius``       zero of Celsius scale in Kelvin
+``degree_Fahrenheit``  one Fahrenheit (only differences) in Kelvins
+=====================  =======================================================
+
+.. autosummary::
+   :toctree: generated/
+
+   convert_temperature
+
+Energy
+------
+
+====================  =======================================================
+``eV``                one electron volt in Joules
+``electron_volt``     one electron volt in Joules
+``calorie``           one calorie (thermochemical) in Joules
+``calorie_th``        one calorie (thermochemical) in Joules
+``calorie_IT``        one calorie (International Steam Table calorie, 1956) in Joules
+``erg``               one erg in Joules
+``Btu``               one British thermal unit (International Steam Table) in Joules
+``Btu_IT``            one British thermal unit (International Steam Table) in Joules
+``Btu_th``            one British thermal unit (thermochemical) in Joules
+``ton_TNT``           one ton of TNT in Joules
+====================  =======================================================
+
+Power
+-----
+
+====================  =======================================================
+``hp``                one horsepower in watts
+``horsepower``        one horsepower in watts
+====================  =======================================================
+
+Force
+-----
+
+====================  =======================================================
+``dyn``               one dyne in newtons
+``dyne``              one dyne in newtons
+``lbf``               one pound force in newtons
+``pound_force``       one pound force in newtons
+``kgf``               one kilogram force in newtons
+``kilogram_force``    one kilogram force in newtons
+====================  =======================================================
+
+Optics
+------
+
+.. autosummary::
+   :toctree: generated/
+
+   lambda2nu
+   nu2lambda
+
+References
+==========
+
+.. [CODATA2022] CODATA Recommended Values of the Fundamental
+   Physical Constants 2022.
+
+   https://physics.nist.gov/cuu/Constants/
+
+"""  # noqa: E501
+# Modules contributed by BasSw (wegwerp@gmail.com)
+from ._codata import *
+from ._constants import *
+from ._codata import _obsolete_constants, physical_constants
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import codata, constants
+
+_constant_names_list = [(_k.lower(), _k, _v)
+                        for _k, _v in physical_constants.items()
+                        if _k not in _obsolete_constants]
+_constant_names = "\n".join(["``{}``{}  {} {}".format(_x[1], " "*(66-len(_x[1])),
+                                                  _x[2][0], _x[2][1])
+                             for _x in sorted(_constant_names_list)])
+if __doc__:
+    __doc__ = __doc__ % dict(constant_names=_constant_names)
+
+del _constant_names
+del _constant_names_list
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3616d03535d5e219f8a4225e0b2dccd3c6caad45
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b342febf101afe790cc3a68d7f14a0fe111b2b0
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/_constants.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6f75f544d33f975f5fc1d927fa1b3a560f91aed
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/codata.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7273768af62983ec3dfd0c2379b62985392d0e1
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/__pycache__/constants.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/_codata.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..4457a8089d9c4b7ba159519e6ec1606fb7b74070
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/_codata.py
@@ -0,0 +1,2266 @@
+"""
+Fundamental Physical Constants
+------------------------------
+
+These constants are taken from CODATA Recommended Values of the Fundamental
+Physical Constants 2022.
+
+Object
+------
+physical_constants : dict
+    A dictionary containing physical constants. Keys are the names of physical
+    constants, values are tuples (value, units, precision).
+
+Functions
+---------
+value(key):
+    Returns the value of the physical constant(key).
+unit(key):
+    Returns the units of the physical constant(key).
+precision(key):
+    Returns the relative precision of the physical constant(key).
+find(sub):
+    Prints or returns list of keys containing the string sub, default is all.
+
+Source
+------
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set. Also available is an introduction to the
+constants for non-experts at
+
+https://physics.nist.gov/cuu/Constants/introduction.html
+
+References
+----------
+Theoretical and experimental publications relevant to the fundamental constants
+and closely related precision measurements published since the mid 1980s, but
+also including many older papers of particular interest, some of which date
+back to the 1800s. To search the bibliography, visit
+
+https://physics.nist.gov/cuu/Constants/
+
+"""
+
+# Compiled by Charles Harris, dated October 3, 2002
+# updated to 2002 values by BasSw, 2006
+# Updated to 2006 values by Vincent Davis June 2010
+# Updated to 2014 values by Joseph Booker, 2015
+# Updated to 2018 values by Jakob Jakobson, 2019
+# Updated to 2022 values by Jakob Jakobson, 2024
+
+import warnings
+import math
+
+from typing import Any
+from collections.abc import Callable
+
+__all__ = ['physical_constants', 'value', 'unit', 'precision', 'find',
+           'ConstantWarning']
+
+"""
+Source:  https://physics.nist.gov/cuu/Constants/
+
+The values of the constants provided at this site are recommended for
+international use by CODATA and are the latest available. Termed the "2018
+CODATA recommended values," they are generally recognized worldwide for use in
+all fields of science and technology. The values became available on 20 May
+2019 and replaced the 2014 CODATA set.
+"""
+
+#
+# Source:  https://physics.nist.gov/cuu/Constants/
+#
+
+# Quantity                                             Value                 Uncertainty          Unit
+# ---------------------------------------------------- --------------------- -------------------- -------------
+txt2002 = """\
+Wien displacement law constant                         2.897 7685e-3         0.000 0051e-3         m K
+atomic unit of 1st hyperpolarizablity                  3.206 361 51e-53      0.000 000 28e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizablity                  6.235 3808e-65        0.000 0011e-65        C^4 m^4 J^-3
+atomic unit of electric dipole moment                  8.478 353 09e-30      0.000 000 73e-30      C m
+atomic unit of electric polarizablity                  1.648 777 274e-41     0.000 000 016e-41     C^2 m^2 J^-1
+atomic unit of electric quadrupole moment              4.486 551 24e-40      0.000 000 39e-40      C m^2
+atomic unit of magn. dipole moment                     1.854 801 90e-23      0.000 000 16e-23      J T^-1
+atomic unit of magn. flux density                      2.350 517 42e5        0.000 000 20e5        T
+deuteron magn. moment                                  0.433 073 482e-26     0.000 000 038e-26     J T^-1
+deuteron magn. moment to Bohr magneton ratio           0.466 975 4567e-3     0.000 000 0050e-3
+deuteron magn. moment to nuclear magneton ratio        0.857 438 2329        0.000 000 0092
+deuteron-electron magn. moment ratio                   -4.664 345 548e-4     0.000 000 050e-4
+deuteron-proton magn. moment ratio                     0.307 012 2084        0.000 000 0045
+deuteron-neutron magn. moment ratio                    -0.448 206 52         0.000 000 11
+electron gyromagn. ratio                               1.760 859 74e11       0.000 000 15e11       s^-1 T^-1
+electron gyromagn. ratio over 2 pi                     28 024.9532           0.0024                MHz T^-1
+electron magn. moment                                  -928.476 412e-26      0.000 080e-26         J T^-1
+electron magn. moment to Bohr magneton ratio           -1.001 159 652 1859   0.000 000 000 0038
+electron magn. moment to nuclear magneton ratio        -1838.281 971 07      0.000 000 85
+electron magn. moment anomaly                          1.159 652 1859e-3     0.000 000 0038e-3
+electron to shielded proton magn. moment ratio         -658.227 5956         0.000 0071
+electron to shielded helion magn. moment ratio         864.058 255           0.000 010
+electron-deuteron magn. moment ratio                   -2143.923 493         0.000 023
+electron-muon magn. moment ratio                       206.766 9894          0.000 0054
+electron-neutron magn. moment ratio                    960.920 50            0.000 23
+electron-proton magn. moment ratio                     -658.210 6862         0.000 0066
+magn. constant                                         12.566 370 614...e-7  (exact)               N A^-2
+magn. flux quantum                                     2.067 833 72e-15      0.000 000 18e-15      Wb
+muon magn. moment                                      -4.490 447 99e-26     0.000 000 40e-26      J T^-1
+muon magn. moment to Bohr magneton ratio               -4.841 970 45e-3      0.000 000 13e-3
+muon magn. moment to nuclear magneton ratio            -8.890 596 98         0.000 000 23
+muon-proton magn. moment ratio                         -3.183 345 118        0.000 000 089
+neutron gyromagn. ratio                                1.832 471 83e8        0.000 000 46e8        s^-1 T^-1
+neutron gyromagn. ratio over 2 pi                      29.164 6950           0.000 0073            MHz T^-1
+neutron magn. moment                                   -0.966 236 45e-26     0.000 000 24e-26      J T^-1
+neutron magn. moment to Bohr magneton ratio            -1.041 875 63e-3      0.000 000 25e-3
+neutron magn. moment to nuclear magneton ratio         -1.913 042 73         0.000 000 45
+neutron to shielded proton magn. moment ratio          -0.684 996 94         0.000 000 16
+neutron-electron magn. moment ratio                    1.040 668 82e-3       0.000 000 25e-3
+neutron-proton magn. moment ratio                      -0.684 979 34         0.000 000 16
+proton gyromagn. ratio                                 2.675 222 05e8        0.000 000 23e8        s^-1 T^-1
+proton gyromagn. ratio over 2 pi                       42.577 4813           0.000 0037            MHz T^-1
+proton magn. moment                                    1.410 606 71e-26      0.000 000 12e-26      J T^-1
+proton magn. moment to Bohr magneton ratio             1.521 032 206e-3      0.000 000 015e-3
+proton magn. moment to nuclear magneton ratio          2.792 847 351         0.000 000 028
+proton magn. shielding correction                      25.689e-6             0.015e-6
+proton-neutron magn. moment ratio                      -1.459 898 05         0.000 000 34
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded helion magn. moment                           -1.074 553 024e-26    0.000 000 093e-26     J T^-1
+shielded helion magn. moment to Bohr magneton ratio    -1.158 671 474e-3     0.000 000 014e-3
+shielded helion magn. moment to nuclear magneton ratio -2.127 497 723        0.000 000 025
+shielded helion to proton magn. moment ratio           -0.761 766 562        0.000 000 012
+shielded helion to shielded proton magn. moment ratio  -0.761 786 1313       0.000 000 0033
+shielded helion gyromagn. ratio                        2.037 894 70e8        0.000 000 18e8        s^-1 T^-1
+shielded helion gyromagn. ratio over 2 pi              32.434 1015           0.000 0028            MHz T^-1
+shielded proton magn. moment                           1.410 570 47e-26      0.000 000 12e-26      J T^-1
+shielded proton magn. moment to Bohr magneton ratio    1.520 993 132e-3      0.000 000 016e-3
+shielded proton magn. moment to nuclear magneton ratio 2.792 775 604         0.000 000 030
+{220} lattice spacing of silicon                       192.015 5965e-12      0.000 0070e-12        m"""
+
+
+def exact2002(exact):
+    replace = {
+        'magn. constant': 4e-7 * math.pi,
+    }
+    return replace
+
+
+txt2006 = """\
+lattice spacing of silicon                             192.015 5762 e-12     0.000 0050 e-12       m
+alpha particle-electron mass ratio                     7294.299 5365         0.000 0031
+alpha particle mass                                    6.644 656 20 e-27     0.000 000 33 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 17 e-10     0.000 000 30 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 109          0.000 093             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 51      0.000 000 000 41
+Angstrom star                                          1.000 014 98 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 028           0.000 023             MeV
+atomic mass unit-electron volt relationship            931.494 028 e6        0.000 023 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 7149 e7     0.000 000 0049 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7369 e23    0.000 000 0032 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 671 e14     0.000 000 011 e14     m^-1
+atomic mass unit-joule relationship                    1.492 417 830 e-10    0.000 000 074 e-10    J
+atomic mass unit-kelvin relationship                   1.080 9527 e13        0.000 0019 e13        K
+atomic mass unit-kilogram relationship                 1.660 538 782 e-27    0.000 000 083 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 533 e-53    0.000 000 081 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 95 e-65     0.000 000 31 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 628 e-34    0.000 000 053 e-34    J s
+atomic unit of charge                                  1.602 176 487 e-19    0.000 000 040 e-19    C
+atomic unit of charge density                          1.081 202 300 e12     0.000 000 027 e12     C m^-3
+atomic unit of current                                 6.623 617 63 e-3      0.000 000 17 e-3      A
+atomic unit of electric dipole mom.                    8.478 352 81 e-30     0.000 000 21 e-30     C m
+atomic unit of electric field                          5.142 206 32 e11      0.000 000 13 e11      V m^-1
+atomic unit of electric field gradient                 9.717 361 66 e21      0.000 000 24 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2536 e-41   0.000 000 0034 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 383 86         0.000 000 68          V
+atomic unit of electric quadrupole mom.                4.486 551 07 e-40     0.000 000 11 e-40     C m^2
+atomic unit of energy                                  4.359 743 94 e-18     0.000 000 22 e-18     J
+atomic unit of force                                   8.238 722 06 e-8      0.000 000 41 e-8      N
+atomic unit of length                                  0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 830 e-23    0.000 000 046 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 382 e5      0.000 000 059 e5      T
+atomic unit of magnetizability                         7.891 036 433 e-29    0.000 000 027 e-29    J T^-2
+atomic unit of mass                                    9.109 382 15 e-31     0.000 000 45 e-31     kg
+atomic unit of momentum                                1.992 851 565 e-24    0.000 000 099 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 505 e-17 0.000 000 000 016 e-17 s
+atomic unit of velocity                                2.187 691 2541 e6     0.000 000 0015 e6     m s^-1
+Avogadro constant                                      6.022 141 79 e23      0.000 000 30 e23      mol^-1
+Bohr magneton                                          927.400 915 e-26      0.000 023 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 7555 e-5    0.000 000 0079 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 246 04 e9      0.000 000 35 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4515           0.000 0012            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 7131            0.000 0012            K T^-1
+Bohr radius                                            0.529 177 208 59 e-10 0.000 000 000 36 e-10 m
+Boltzmann constant                                     1.380 6504 e-23       0.000 0024 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 343 e-5         0.000 015 e-5         eV K^-1
+Boltzmann constant in Hz/K                             2.083 6644 e10        0.000 0036 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 56             0.000 12              m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 2894 e-15   0.000 000 0058 e-15   m
+Compton wavelength                                     2.426 310 2175 e-12   0.000 000 0033 e-12   m
+Compton wavelength over 2 pi                           386.159 264 59 e-15   0.000 000 53 e-15     m
+conductance quantum                                    7.748 091 7004 e-5    0.000 000 0053 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 99 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9654         0.000 0016
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 465 e-26    0.000 000 011 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 20 e-27     0.000 000 17 e-27     kg
+deuteron mass energy equivalent                        3.005 062 72 e-10     0.000 000 15 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 793          0.000 047             MeV
+deuteron mass in u                                     2.013 553 212 724     0.000 000 000 078     u
+deuteron molar mass                                    2.013 553 212 724 e-3 0.000 000 000 078 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 501 08      0.000 000 000 22
+deuteron rms charge radius                             2.1402 e-15           0.0028 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 150 e11    0.000 000 044 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1093 e-4    0.000 000 0012 e-4
+electron g factor                                      -2.002 319 304 3622   0.000 000 000 0015
+electron gyromag. ratio                                1.760 859 770 e11     0.000 000 044 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.953 64         0.000 70              MHz T^-1
+electron mag. mom.                                     -928.476 377 e-26     0.000 023 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 181 11 e-3  0.000 000 000 74 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 181 11 0.000 000 000 000 74
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 92      0.000 000 80
+electron mass                                          9.109 382 15 e-31     0.000 000 45 e-31     kg
+electron mass energy equivalent                        8.187 104 38 e-14     0.000 000 41 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 910         0.000 000 013         MeV
+electron mass in u                                     5.485 799 0943 e-4    0.000 000 0023 e-4    u
+electron molar mass                                    5.485 799 0943 e-7    0.000 000 0023 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9877          0.000 0052
+electron-muon mass ratio                               4.836 331 71 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4459 e-4    0.000 000 0033 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2177 e-4    0.000 000 0024 e-4
+electron-tau mass ratio                                2.875 64 e-4          0.000 47 e-4
+electron to alpha particle mass ratio                  1.370 933 555 70 e-4  0.000 000 000 58 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron volt                                          1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 188 e-9     0.000 000 027 e-9     u
+electron volt-hartree relationship                     3.674 932 540 e-2     0.000 000 092 e-2     E_h
+electron volt-hertz relationship                       2.417 989 454 e14     0.000 000 060 e14     Hz
+electron volt-inverse meter relationship               8.065 544 65 e5       0.000 000 20 e5       m^-1
+electron volt-joule relationship                       1.602 176 487 e-19    0.000 000 040 e-19    J
+electron volt-kelvin relationship                      1.160 4505 e4         0.000 0020 e4         K
+electron volt-kilogram relationship                    1.782 661 758 e-36    0.000 000 044 e-36    kg
+elementary charge                                      1.602 176 487 e-19    0.000 000 040 e-19    C
+elementary charge over h                               2.417 989 454 e14     0.000 000 060 e14     A J^-1
+Faraday constant                                       96 485.3399           0.0024                C mol^-1
+Faraday constant for conventional electric current     96 485.3401           0.0048                C_90 mol^-1
+Fermi coupling constant                                1.166 37 e-5          0.000 01 e-5          GeV^-2
+fine-structure constant                                7.297 352 5376 e-3    0.000 000 0050 e-3
+first radiation constant                               3.741 771 18 e-16     0.000 000 19 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 759 e-16    0.000 000 059 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 2986 e-8    0.000 000 0042 e-8    u
+hartree-electron volt relationship                     27.211 383 86         0.000 000 68          eV
+Hartree energy                                         4.359 743 94 e-18     0.000 000 22 e-18     J
+Hartree energy in eV                                   27.211 383 86         0.000 000 68          eV
+hartree-hertz relationship                             6.579 683 920 722 e15 0.000 000 000 044 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 705 e7  0.000 000 000 015 e7  m^-1
+hartree-joule relationship                             4.359 743 94 e-18     0.000 000 22 e-18     J
+hartree-kelvin relationship                            3.157 7465 e5         0.000 0055 e5         K
+hartree-kilogram relationship                          4.850 869 34 e-35     0.000 000 24 e-35     kg
+helion-electron mass ratio                             5495.885 2765         0.000 0052
+helion mass                                            5.006 411 92 e-27     0.000 000 25 e-27     kg
+helion mass energy equivalent                          4.499 538 64 e-10     0.000 000 22 e-10     J
+helion mass energy equivalent in MeV                   2808.391 383          0.000 070             MeV
+helion mass in u                                       3.014 932 2473        0.000 000 0026        u
+helion molar mass                                      3.014 932 2473 e-3    0.000 000 0026 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6713        0.000 000 0026
+hertz-atomic mass unit relationship                    4.439 821 6294 e-24   0.000 000 0064 e-24   u
+hertz-electron volt relationship                       4.135 667 33 e-15     0.000 000 10 e-15     eV
+hertz-hartree relationship                             1.519 829 846 006 e-16 0.000 000 000010e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 068 96 e-34     0.000 000 33 e-34     J
+hertz-kelvin relationship                              4.799 2374 e-11       0.000 0084 e-11       K
+hertz-kilogram relationship                            7.372 496 00 e-51     0.000 000 37 e-51     kg
+inverse fine-structure constant                        137.035 999 679       0.000 000 094
+inverse meter-atomic mass unit relationship            1.331 025 0394 e-15   0.000 000 0019 e-15   u
+inverse meter-electron volt relationship               1.239 841 875 e-6     0.000 000 031 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 760 e-8 0.000 000 000 030 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 501 e-25    0.000 000 099 e-25    J
+inverse meter-kelvin relationship                      1.438 7752 e-2        0.000 0025 e-2        K
+inverse meter-kilogram relationship                    2.210 218 70 e-42     0.000 000 11 e-42     kg
+inverse of conductance quantum                         12 906.403 7787       0.000 0088            ohm
+Josephson constant                                     483 597.891 e9        0.012 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 536 41 e9       0.000 000 33 e9       u
+joule-electron volt relationship                       6.241 509 65 e18      0.000 000 16 e18      eV
+joule-hartree relationship                             2.293 712 69 e17      0.000 000 11 e17      E_h
+joule-hertz relationship                               1.509 190 450 e33     0.000 000 075 e33     Hz
+joule-inverse meter relationship                       5.034 117 47 e24      0.000 000 25 e24      m^-1
+joule-kelvin relationship                              7.242 963 e22         0.000 013 e22         K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 098 e-14        0.000 016 e-14        u
+kelvin-electron volt relationship                      8.617 343 e-5         0.000 015 e-5         eV
+kelvin-hartree relationship                            3.166 8153 e-6        0.000 0055 e-6        E_h
+kelvin-hertz relationship                              2.083 6644 e10        0.000 0036 e10        Hz
+kelvin-inverse meter relationship                      69.503 56             0.000 12              m^-1
+kelvin-joule relationship                              1.380 6504 e-23       0.000 0024 e-23       J
+kelvin-kilogram relationship                           1.536 1807 e-40       0.000 0027 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 79 e26      0.000 000 30 e26      u
+kilogram-electron volt relationship                    5.609 589 12 e35      0.000 000 14 e35      eV
+kilogram-hartree relationship                          2.061 486 16 e34      0.000 000 10 e34      E_h
+kilogram-hertz relationship                            1.356 392 733 e50     0.000 000 068 e50     Hz
+kilogram-inverse meter relationship                    4.524 439 15 e41      0.000 000 23 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 651 e39         0.000 011 e39         K
+lattice parameter of silicon                           543.102 064 e-12      0.000 014 e-12        m
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7774 e25        0.000 0047 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 667 e-15    0.000 000 052 e-15    Wb
+molar gas constant                                     8.314 472             0.000 015             J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 6821 e-10   0.000 000 0057 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 564 72      0.000 000 000 17      J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 981 e-3        0.000 040 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 996 e-3        0.000 039 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 8349 e-6       0.000 0011 e-6        m^3 mol^-1
+Mo x unit                                              1.002 099 55 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 04 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 295 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2823          0.000 0052
+muon g factor                                          -2.002 331 8414       0.000 000 0012
+muon mag. mom.                                         -4.490 447 86 e-26    0.000 000 16 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 69 e-3      0.000 000 60 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 49 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 23
+muon mass                                              1.883 531 30 e-28     0.000 000 11 e-28     kg
+muon mass energy equivalent                            1.692 833 510 e-11    0.000 000 095 e-11    J
+muon mass energy equivalent in MeV                     105.658 3668          0.000 0038            MeV
+muon mass in u                                         0.113 428 9256        0.000 000 0029        u
+muon molar mass                                        0.113 428 9256 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0029
+muon-proton mag. mom. ratio                            -3.183 345 137        0.000 000 085
+muon-proton mass ratio                                 0.112 609 5261        0.000 000 0029
+muon-tau mass ratio                                    5.945 92 e-2          0.000 97 e-2
+natural unit of action                                 1.054 571 628 e-34    0.000 000 053 e-34    J s
+natural unit of action in eV s                         6.582 118 99 e-16     0.000 000 16 e-16     eV s
+natural unit of energy                                 8.187 104 38 e-14     0.000 000 41 e-14     J
+natural unit of energy in MeV                          0.510 998 910         0.000 000 013         MeV
+natural unit of length                                 386.159 264 59 e-15   0.000 000 53 e-15     m
+natural unit of mass                                   9.109 382 15 e-31     0.000 000 45 e-31     kg
+natural unit of momentum                               2.730 924 06 e-22     0.000 000 14 e-22     kg m s^-1
+natural unit of momentum in MeV/c                      0.510 998 910         0.000 000 013         MeV/c
+natural unit of time                                   1.288 088 6570 e-21   0.000 000 0018 e-21   s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 8951 e-15   0.000 000 0020 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 413 82 e-15 0.000 000 000 31 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 85 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6954           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 41 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 211 e-27    0.000 000 084 e-27    kg
+neutron mass energy equivalent                         1.505 349 505 e-10    0.000 000 075 e-10    J
+neutron mass energy equivalent in MeV                  939.565 346           0.000 023             MeV
+neutron mass in u                                      1.008 664 915 97      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 915 97 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 09          0.000 000 23
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass ratio                              1.001 378 419 18      0.000 000 000 46
+neutron-tau mass ratio                                 0.528 740             0.000 086
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 28 e-11         0.000 67 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 81 e-39         0.000 67 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 24 e-27     0.000 000 13 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2326 e-8    0.000 000 0045 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 616 e-2     0.000 000 064 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2637 e-4        0.000 0064 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 84          0.000 000 19          MHz T^-1
+Planck constant                                        6.626 068 96 e-34     0.000 000 33 e-34     J s
+Planck constant in eV s                                4.135 667 33 e-15     0.000 000 10 e-15     eV s
+Planck constant over 2 pi                              1.054 571 628 e-34    0.000 000 053 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 118 99 e-16     0.000 000 16 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9631          0.000 0049            MeV fm
+Planck length                                          1.616 252 e-35        0.000 081 e-35        m
+Planck mass                                            2.176 44 e-8          0.000 11 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 892 e19         0.000 061 e19         GeV
+Planck temperature                                     1.416 785 e32         0.000 071 e32         K
+Planck time                                            5.391 24 e-44         0.000 27 e-44         s
+proton charge to mass quotient                         9.578 833 92 e7       0.000 000 24 e7       C kg^-1
+proton Compton wavelength                              1.321 409 8446 e-15   0.000 000 0019 e-15   m
+proton Compton wavelength over 2 pi                    0.210 308 908 61 e-15 0.000 000 000 30 e-15 m
+proton-electron mass ratio                             1836.152 672 47       0.000 000 80
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 099 e8      0.000 000 070 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4821           0.000 0011            MHz T^-1
+proton mag. mom.                                       1.410 606 662 e-26    0.000 000 037 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 209 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 637 e-27    0.000 000 083 e-27    kg
+proton mass energy equivalent                          1.503 277 359 e-10    0.000 000 075 e-10    J
+proton mass energy equivalent in MeV                   938.272 013           0.000 023             MeV
+proton mass in u                                       1.007 276 466 77      0.000 000 000 10      u
+proton molar mass                                      1.007 276 466 77 e-3  0.000 000 000 10 e-3  kg mol^-1
+proton-muon mass ratio                                 8.880 243 39          0.000 000 23
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 24      0.000 000 000 46
+proton rms charge radius                               0.8768 e-15           0.0069 e-15           m
+proton-tau mass ratio                                  0.528 012             0.000 086
+quantum of circulation                                 3.636 947 5199 e-4    0.000 000 0050 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 040 e-4     0.000 000 010 e-4     m^2 s^-1
+Rydberg constant                                       10 973 731.568 527    0.000 073             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 361 e15 0.000 000 000 022 e15 Hz
+Rydberg constant times hc in eV                        13.605 691 93         0.000 000 34          eV
+Rydberg constant times hc in J                         2.179 871 97 e-18     0.000 000 11 e-18     J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7047           0.000 0044
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8677           0.000 0044
+second radiation constant                              1.438 7752 e-2        0.000 0025 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 730 e8      0.000 000 056 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 101 98         0.000 000 90          MHz T^-1
+shielded helion mag. mom.                              -1.074 552 982 e-26   0.000 000 030 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 362 e8      0.000 000 073 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3881           0.000 0012            MHz T^-1
+shielded proton mag. mom.                              1.410 570 419 e-26    0.000 000 038 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 400 e-8         0.000 040 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 72 e-15         0.000 11 e-15         m
+tau Compton wavelength over 2 pi                       0.111 046 e-15        0.000 018 e-15        m
+tau-electron mass ratio                                3477.48               0.57
+tau mass                                               3.167 77 e-27         0.000 52 e-27         kg
+tau mass energy equivalent                             2.847 05 e-10         0.000 46 e-10         J
+tau mass energy equivalent in MeV                      1776.99               0.29                  MeV
+tau mass in u                                          1.907 68              0.000 31              u
+tau molar mass                                         1.907 68 e-3          0.000 31 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8183               0.0027
+tau-neutron mass ratio                                 1.891 29              0.000 31
+tau-proton mass ratio                                  1.893 90              0.000 31
+Thomson cross section                                  0.665 245 8558 e-28   0.000 000 0027 e-28   m^2
+triton-electron mag. mom. ratio                        -1.620 514 423 e-3    0.000 000 021 e-3
+triton-electron mass ratio                             5496.921 5269         0.000 0051
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 361 e-26    0.000 000 042 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 355 88 e-27     0.000 000 25 e-27     kg
+triton mass energy equivalent                          4.500 387 03 e-10     0.000 000 22 e-10     J
+triton mass energy equivalent in MeV                   2808.920 906          0.000 070             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-neutron mag. mom. ratio                         -1.557 185 53         0.000 000 37
+triton-proton mag. mom. ratio                          1.066 639 908         0.000 000 010
+triton-proton mass ratio                               2.993 717 0309        0.000 000 0025
+unified atomic mass unit                               1.660 538 782 e-27    0.000 000 083 e-27    kg
+von Klitzing constant                                  25 812.807 557        0.000 018             ohm
+weak mixing angle                                      0.222 55              0.000 56
+Wien frequency displacement law constant               5.878 933 e10         0.000 010 e10         Hz K^-1
+Wien wavelength displacement law constant              2.897 7685 e-3        0.000 0051 e-3        m K"""
+
+
+def exact2006(exact):
+    mu0 = 4e-7 * math.pi
+    c = exact['speed of light in vacuum']
+    epsilon0 = 1 / (mu0 * c**2)
+    replace = {
+        'mag. constant': mu0,
+        'electric constant': epsilon0,
+        'atomic unit of permittivity': 4*math.pi*epsilon0,
+        'characteristic impedance of vacuum': math.sqrt(mu0 / epsilon0),
+        'hertz-inverse meter relationship': 1/c,
+        'joule-kilogram relationship': 1/c**2,
+        'kilogram-joule relationship': c**2,
+    }
+    return replace
+
+
+txt2010 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 5361         0.000 0029
+alpha particle mass                                    6.644 656 75 e-27     0.000 000 29 e-27     kg
+alpha particle mass energy equivalent                  5.971 919 67 e-10     0.000 000 26 e-10     J
+alpha particle mass energy equivalent in MeV           3727.379 240          0.000 082             MeV
+alpha particle mass in u                               4.001 506 179 125     0.000 000 000 062     u
+alpha particle molar mass                              4.001 506 179 125 e-3 0.000 000 000 062 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 33      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic mass constant energy equivalent                 1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 061           0.000 021             MeV
+atomic mass unit-electron volt relationship            931.494 061 e6        0.000 021 e6          eV
+atomic mass unit-hartree relationship                  3.423 177 6845 e7     0.000 000 0024 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7168 e23    0.000 000 0016 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6042 e14    0.000 000 0053 e14    m^-1
+atomic mass unit-joule relationship                    1.492 417 954 e-10    0.000 000 066 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 08 e13      0.000 000 98 e13      K
+atomic mass unit-kilogram relationship                 1.660 538 921 e-27    0.000 000 073 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 449 e-53    0.000 000 071 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 54 e-65     0.000 000 28 e-65     C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 726 e-34    0.000 000 047 e-34    J s
+atomic unit of charge                                  1.602 176 565 e-19    0.000 000 035 e-19    C
+atomic unit of charge density                          1.081 202 338 e12     0.000 000 024 e12     C m^-3
+atomic unit of current                                 6.623 617 95 e-3      0.000 000 15 e-3      A
+atomic unit of electric dipole mom.                    8.478 353 26 e-30     0.000 000 19 e-30     C m
+atomic unit of electric field                          5.142 206 52 e11      0.000 000 11 e11      V m^-1
+atomic unit of electric field gradient                 9.717 362 00 e21      0.000 000 21 e21      V m^-2
+atomic unit of electric polarizability                 1.648 777 2754 e-41   0.000 000 0016 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 385 05         0.000 000 60          V
+atomic unit of electric quadrupole mom.                4.486 551 331 e-40    0.000 000 099 e-40    C m^2
+atomic unit of energy                                  4.359 744 34 e-18     0.000 000 19 e-18     J
+atomic unit of force                                   8.238 722 78 e-8      0.000 000 36 e-8      N
+atomic unit of length                                  0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 936 e-23    0.000 000 041 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 464 e5      0.000 000 052 e5      T
+atomic unit of magnetizability                         7.891 036 607 e-29    0.000 000 013 e-29    J T^-2
+atomic unit of mass                                    9.109 382 91 e-31     0.000 000 40 e-31     kg
+atomic unit of mom.um                                  1.992 851 740 e-24    0.000 000 088 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326 502e-17 0.000 000 000 012e-17 s
+atomic unit of velocity                                2.187 691 263 79 e6   0.000 000 000 71 e6   m s^-1
+Avogadro constant                                      6.022 141 29 e23      0.000 000 27 e23      mol^-1
+Bohr magneton                                          927.400 968 e-26      0.000 020 e-26        J T^-1
+Bohr magneton in eV/T                                  5.788 381 8066 e-5    0.000 000 0038 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 55 e9      0.000 000 31 e9       Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 4498           0.000 0010            m^-1 T^-1
+Bohr magneton in K/T                                   0.671 713 88          0.000 000 61          K T^-1
+Bohr radius                                            0.529 177 210 92 e-10 0.000 000 000 17 e-10 m
+Boltzmann constant                                     1.380 6488 e-23       0.000 0013 e-23       J K^-1
+Boltzmann constant in eV/K                             8.617 3324 e-5        0.000 0078 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6618 e10        0.000 0019 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 476            0.000 063             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3267 e-15   0.000 000 0027 e-15   m
+Compton wavelength                                     2.426 310 2389 e-12   0.000 000 0016 e-12   m
+Compton wavelength over 2 pi                           386.159 268 00 e-15   0.000 000 25 e-15     m
+conductance quantum                                    7.748 091 7346 e-5    0.000 000 0025 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 537 e-4    0.000 000 039 e-4
+deuteron-electron mass ratio                           3670.482 9652         0.000 0015
+deuteron g factor                                      0.857 438 2308        0.000 000 0072
+deuteron mag. mom.                                     0.433 073 489 e-26    0.000 000 010 e-26    J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4556 e-3    0.000 000 0039 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2308        0.000 000 0072
+deuteron mass                                          3.343 583 48 e-27     0.000 000 15 e-27     kg
+deuteron mass energy equivalent                        3.005 062 97 e-10     0.000 000 13 e-10     J
+deuteron mass energy equivalent in MeV                 1875.612 859          0.000 041             MeV
+deuteron mass in u                                     2.013 553 212 712     0.000 000 000 077     u
+deuteron molar mass                                    2.013 553 212 712 e-3 0.000 000 000 077 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2070        0.000 000 0024
+deuteron-proton mass ratio                             1.999 007 500 97      0.000 000 000 18
+deuteron rms charge radius                             2.1424 e-15           0.0021 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 088 e11    0.000 000 039 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 498         0.000 018
+electron-deuteron mass ratio                           2.724 437 1095 e-4    0.000 000 0011 e-4
+electron g factor                                      -2.002 319 304 361 53 0.000 000 000 000 53
+electron gyromag. ratio                                1.760 859 708 e11     0.000 000 039 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.952 66         0.000 62              MHz T^-1
+electron-helion mass ratio                             1.819 543 0761 e-4    0.000 000 0017 e-4
+electron mag. mom.                                     -928.476 430 e-26     0.000 021 e-26        J T^-1
+electron mag. mom. anomaly                             1.159 652 180 76 e-3  0.000 000 000 27 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 76 0.000 000 000 000 27
+electron mag. mom. to nuclear magneton ratio           -1838.281 970 90      0.000 000 75
+electron mass                                          9.109 382 91 e-31     0.000 000 40 e-31     kg
+electron mass energy equivalent                        8.187 105 06 e-14     0.000 000 36 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 928         0.000 000 011         MeV
+electron mass in u                                     5.485 799 0946 e-4    0.000 000 0022 e-4    u
+electron molar mass                                    5.485 799 0946 e-7    0.000 000 0022 e-7    kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9896          0.000 0052
+electron-muon mass ratio                               4.836 331 66 e-3      0.000 000 12 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4461 e-4    0.000 000 0032 e-4
+electron-proton mag. mom. ratio                        -658.210 6848         0.000 0054
+electron-proton mass ratio                             5.446 170 2178 e-4    0.000 000 0022 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 555 78 e-4  0.000 000 000 55 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 0653 e-4    0.000 000 0017 e-4
+electron volt                                          1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-atomic mass unit relationship            1.073 544 150 e-9     0.000 000 024 e-9     u
+electron volt-hartree relationship                     3.674 932 379 e-2     0.000 000 081 e-2     E_h
+electron volt-hertz relationship                       2.417 989 348 e14     0.000 000 053 e14     Hz
+electron volt-inverse meter relationship               8.065 544 29 e5       0.000 000 18 e5       m^-1
+electron volt-joule relationship                       1.602 176 565 e-19    0.000 000 035 e-19    J
+electron volt-kelvin relationship                      1.160 4519 e4         0.000 0011 e4         K
+electron volt-kilogram relationship                    1.782 661 845 e-36    0.000 000 039 e-36    kg
+elementary charge                                      1.602 176 565 e-19    0.000 000 035 e-19    C
+elementary charge over h                               2.417 989 348 e14     0.000 000 053 e14     A J^-1
+Faraday constant                                       96 485.3365           0.0021                C mol^-1
+Faraday constant for conventional electric current     96 485.3321           0.0043                C_90 mol^-1
+Fermi coupling constant                                1.166 364 e-5         0.000 005 e-5         GeV^-2
+fine-structure constant                                7.297 352 5698 e-3    0.000 000 0024 e-3
+first radiation constant                               3.741 771 53 e-16     0.000 000 17 e-16     W m^2
+first radiation constant for spectral radiance         1.191 042 869 e-16    0.000 000 053 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3246 e-8    0.000 000 0021 e-8    u
+hartree-electron volt relationship                     27.211 385 05         0.000 000 60          eV
+Hartree energy                                         4.359 744 34 e-18     0.000 000 19 e-18     J
+Hartree energy in eV                                   27.211 385 05         0.000 000 60          eV
+hartree-hertz relationship                             6.579 683 920 729 e15 0.000 000 000 033 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 708 e7  0.000 000 000 011 e7  m^-1
+hartree-joule relationship                             4.359 744 34 e-18     0.000 000 19 e-18     J
+hartree-kelvin relationship                            3.157 7504 e5         0.000 0029 e5         K
+hartree-kilogram relationship                          4.850 869 79 e-35     0.000 000 21 e-35     kg
+helion-electron mass ratio                             5495.885 2754         0.000 0050
+helion g factor                                        -4.255 250 613        0.000 000 050
+helion mag. mom.                                       -1.074 617 486 e-26   0.000 000 027 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 306        0.000 000 025
+helion mass                                            5.006 412 34 e-27     0.000 000 22 e-27     kg
+helion mass energy equivalent                          4.499 539 02 e-10     0.000 000 20 e-10     J
+helion mass energy equivalent in MeV                   2808.391 482          0.000 062             MeV
+helion mass in u                                       3.014 932 2468        0.000 000 0025        u
+helion molar mass                                      3.014 932 2468 e-3    0.000 000 0025 e-3    kg mol^-1
+helion-proton mass ratio                               2.993 152 6707        0.000 000 0025
+hertz-atomic mass unit relationship                    4.439 821 6689 e-24   0.000 000 0031 e-24   u
+hertz-electron volt relationship                       4.135 667 516 e-15    0.000 000 091 e-15    eV
+hertz-hartree relationship                             1.519 829 8460045e-16 0.000 000 0000076e-16 E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 069 57 e-34     0.000 000 29 e-34     J
+hertz-kelvin relationship                              4.799 2434 e-11       0.000 0044 e-11       K
+hertz-kilogram relationship                            7.372 496 68 e-51     0.000 000 33 e-51     kg
+inverse fine-structure constant                        137.035 999 074       0.000 000 044
+inverse meter-atomic mass unit relationship            1.331 025 051 20 e-15 0.000 000 000 94 e-15 u
+inverse meter-electron volt relationship               1.239 841 930 e-6     0.000 000 027 e-6     eV
+inverse meter-hartree relationship                     4.556 335 252 755 e-8 0.000 000 000 023 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 684 e-25    0.000 000 088 e-25    J
+inverse meter-kelvin relationship                      1.438 7770 e-2        0.000 0013 e-2        K
+inverse meter-kilogram relationship                    2.210 218 902 e-42    0.000 000 098 e-42    kg
+inverse of conductance quantum                         12 906.403 7217       0.000 0042            ohm
+Josephson constant                                     483 597.870 e9        0.011 e9              Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 85 e9       0.000 000 30 e9       u
+joule-electron volt relationship                       6.241 509 34 e18      0.000 000 14 e18      eV
+joule-hartree relationship                             2.293 712 48 e17      0.000 000 10 e17      E_h
+joule-hertz relationship                               1.509 190 311 e33     0.000 000 067 e33     Hz
+joule-inverse meter relationship                       5.034 117 01 e24      0.000 000 22 e24      m^-1
+joule-kelvin relationship                              7.242 9716 e22        0.000 0066 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0868 e-14       0.000 0084 e-14       u
+kelvin-electron volt relationship                      8.617 3324 e-5        0.000 0078 e-5        eV
+kelvin-hartree relationship                            3.166 8114 e-6        0.000 0029 e-6        E_h
+kelvin-hertz relationship                              2.083 6618 e10        0.000 0019 e10        Hz
+kelvin-inverse meter relationship                      69.503 476            0.000 063             m^-1
+kelvin-joule relationship                              1.380 6488 e-23       0.000 0013 e-23       J
+kelvin-kilogram relationship                           1.536 1790 e-40       0.000 0014 e-40       kg
+kilogram-atomic mass unit relationship                 6.022 141 29 e26      0.000 000 27 e26      u
+kilogram-electron volt relationship                    5.609 588 85 e35      0.000 000 12 e35      eV
+kilogram-hartree relationship                          2.061 485 968 e34     0.000 000 091 e34     E_h
+kilogram-hertz relationship                            1.356 392 608 e50     0.000 000 060 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 73 e41      0.000 000 20 e41      m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6582 e39        0.000 0059 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6462 e25        0.000 0024 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7805 e25        0.000 0024 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 758 e-15    0.000 000 046 e-15    Wb
+molar gas constant                                     8.314 4621            0.000 0075            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7176 e-10   0.000 000 0028 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 779     0.000 000 000 084     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 953 e-3        0.000 021 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 968 e-3        0.000 020 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 833 01 e-6     0.000 000 80 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 03 e-15    0.000 000 30 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 294 e-15    0.000 000 047 e-15    m
+muon-electron mass ratio                               206.768 2843          0.000 0052
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 07 e-26    0.000 000 15 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 91 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 44 e-3     0.000 000 12 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 596 97         0.000 000 22
+muon mass                                              1.883 531 475 e-28    0.000 000 096 e-28    kg
+muon mass energy equivalent                            1.692 833 667 e-11    0.000 000 086 e-11    J
+muon mass energy equivalent in MeV                     105.658 3715          0.000 0035            MeV
+muon mass in u                                         0.113 428 9267        0.000 000 0029        u
+muon molar mass                                        0.113 428 9267 e-3    0.000 000 0029 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5177        0.000 000 0028
+muon-proton mag. mom. ratio                            -3.183 345 107        0.000 000 084
+muon-proton mass ratio                                 0.112 609 5272        0.000 000 0028
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 726 e-34    0.000 000 047 e-34    J s
+natural unit of action in eV s                         6.582 119 28 e-16     0.000 000 15 e-16     eV s
+natural unit of energy                                 8.187 105 06 e-14     0.000 000 36 e-14     J
+natural unit of energy in MeV                          0.510 998 928         0.000 000 011         MeV
+natural unit of length                                 386.159 268 00 e-15   0.000 000 25 e-15     m
+natural unit of mass                                   9.109 382 91 e-31     0.000 000 40 e-31     kg
+natural unit of mom.um                                 2.730 924 29 e-22     0.000 000 12 e-22     kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 928         0.000 000 011         MeV/c
+natural unit of time                                   1.288 088 668 33 e-21 0.000 000 000 83 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 9068 e-15   0.000 000 0011 e-15   m
+neutron Compton wavelength over 2 pi                   0.210 019 415 68 e-15 0.000 000 000 17 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 6605         0.000 0011
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 79 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6943           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 47 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 72         0.000 000 45
+neutron mass                                           1.674 927 351 e-27    0.000 000 074 e-27    kg
+neutron mass energy equivalent                         1.505 349 631 e-10    0.000 000 066 e-10    J
+neutron mass energy equivalent in MeV                  939.565 379           0.000 021             MeV
+neutron mass in u                                      1.008 664 916 00      0.000 000 000 43      u
+neutron molar mass                                     1.008 664 916 00 e-3  0.000 000 000 43 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 00          0.000 000 22
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 92 e-30     0.000 000 76 e-30
+neutron-proton mass difference energy equivalent       2.072 146 50 e-13     0.000 000 68 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 17          0.000 000 42
+neutron-proton mass difference in u                    0.001 388 449 19      0.000 000 000 45
+neutron-proton mass ratio                              1.001 378 419 17      0.000 000 000 45
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.673 84 e-11         0.000 80 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 37 e-39         0.000 80 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 53 e-27     0.000 000 11 e-27     J T^-1
+nuclear magneton in eV/T                               3.152 451 2605 e-8    0.000 000 0022 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 527 e-2     0.000 000 056 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2682 e-4        0.000 0033 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 57          0.000 000 17          MHz T^-1
+Planck constant                                        6.626 069 57 e-34     0.000 000 29 e-34     J s
+Planck constant in eV s                                4.135 667 516 e-15    0.000 000 091 e-15    eV s
+Planck constant over 2 pi                              1.054 571 726 e-34    0.000 000 047 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 28 e-16     0.000 000 15 e-16     eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9718          0.000 0044            MeV fm
+Planck length                                          1.616 199 e-35        0.000 097 e-35        m
+Planck mass                                            2.176 51 e-8          0.000 13 e-8          kg
+Planck mass energy equivalent in GeV                   1.220 932 e19         0.000 073 e19         GeV
+Planck temperature                                     1.416 833 e32         0.000 085 e32         K
+Planck time                                            5.391 06 e-44         0.000 32 e-44         s
+proton charge to mass quotient                         9.578 833 58 e7       0.000 000 21 e7       C kg^-1
+proton Compton wavelength                              1.321 409 856 23 e-15 0.000 000 000 94 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308 910 47 e-15 0.000 000 000 15 e-15 m
+proton-electron mass ratio                             1836.152 672 45       0.000 000 75
+proton g factor                                        5.585 694 713         0.000 000 046
+proton gyromag. ratio                                  2.675 222 005 e8      0.000 000 063 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 4806           0.000 0010            MHz T^-1
+proton mag. mom.                                       1.410 606 743 e-26    0.000 000 033 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 210 e-3     0.000 000 012 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 356         0.000 000 023
+proton mag. shielding correction                       25.694 e-6            0.014 e-6
+proton mass                                            1.672 621 777 e-27    0.000 000 074 e-27    kg
+proton mass energy equivalent                          1.503 277 484 e-10    0.000 000 066 e-10    J
+proton mass energy equivalent in MeV                   938.272 046           0.000 021             MeV
+proton mass in u                                       1.007 276 466 812     0.000 000 000 090     u
+proton molar mass                                      1.007 276 466 812 e-3 0.000 000 000 090 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 31          0.000 000 22
+proton-neutron mag. mom. ratio                         -1.459 898 06         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 26      0.000 000 000 45
+proton rms charge radius                               0.8775 e-15           0.0051 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5520 e-4    0.000 000 0024 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 1040 e-4    0.000 000 0047 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 539    0.000 055             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 364 e15 0.000 000 000 017 e15 Hz
+Rydberg constant times hc in eV                        13.605 692 53         0.000 000 30          eV
+Rydberg constant times hc in J                         2.179 872 171 e-18    0.000 000 096 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7078           0.000 0023
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8708           0.000 0023
+second radiation constant                              1.438 7770 e-2        0.000 0013 e-2        m K
+shielded helion gyromag. ratio                         2.037 894 659 e8      0.000 000 051 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 100 84         0.000 000 81          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 044 e-26   0.000 000 027 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 718        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 558        0.000 000 011
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 268 e8      0.000 000 066 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 3866           0.000 0010            MHz T^-1
+shielded proton mag. mom.                              1.410 570 499 e-26    0.000 000 035 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 598         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 373 e-8         0.000 021 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 8734 e-28   0.000 000 0013 e-28   m^2
+triton-electron mass ratio                             5496.921 5267         0.000 0050
+triton g factor                                        5.957 924 896         0.000 000 076
+triton mag. mom.                                       1.504 609 447 e-26    0.000 000 038 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 657 e-3     0.000 000 021 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 448         0.000 000 038
+triton mass                                            5.007 356 30 e-27     0.000 000 22 e-27     kg
+triton mass energy equivalent                          4.500 387 41 e-10     0.000 000 20 e-10     J
+triton mass energy equivalent in MeV                   2808.921 005          0.000 062             MeV
+triton mass in u                                       3.015 500 7134        0.000 000 0025        u
+triton molar mass                                      3.015 500 7134 e-3    0.000 000 0025 e-3    kg mol^-1
+triton-proton mass ratio                               2.993 717 0308        0.000 000 0025
+unified atomic mass unit                               1.660 538 921 e-27    0.000 000 073 e-27    kg
+von Klitzing constant                                  25 812.807 4434       0.000 0084            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9254 e10        0.000 0053 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7721 e-3        0.000 0026 e-3        m K"""
+
+
+exact2010 = exact2006
+
+
+txt2014 = """\
+{220} lattice spacing of silicon                       192.015 5714 e-12     0.000 0032 e-12       m
+alpha particle-electron mass ratio                     7294.299 541 36       0.000 000 24
+alpha particle mass                                    6.644 657 230 e-27    0.000 000 082 e-27    kg
+alpha particle mass energy equivalent                  5.971 920 097 e-10    0.000 000 073 e-10    J
+alpha particle mass energy equivalent in MeV           3727.379 378          0.000 023             MeV
+alpha particle mass in u                               4.001 506 179 127     0.000 000 000 063     u
+alpha particle molar mass                              4.001 506 179 127 e-3 0.000 000 000 063 e-3 kg mol^-1
+alpha particle-proton mass ratio                       3.972 599 689 07      0.000 000 000 36
+Angstrom star                                          1.000 014 95 e-10     0.000 000 90 e-10     m
+atomic mass constant                                   1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic mass constant energy equivalent                 1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass constant energy equivalent in MeV          931.494 0954          0.000 0057            MeV
+atomic mass unit-electron volt relationship            931.494 0954 e6       0.000 0057 e6         eV
+atomic mass unit-hartree relationship                  3.423 177 6902 e7     0.000 000 0016 e7     E_h
+atomic mass unit-hertz relationship                    2.252 342 7206 e23    0.000 000 0010 e23    Hz
+atomic mass unit-inverse meter relationship            7.513 006 6166 e14    0.000 000 0034 e14    m^-1
+atomic mass unit-joule relationship                    1.492 418 062 e-10    0.000 000 018 e-10    J
+atomic mass unit-kelvin relationship                   1.080 954 38 e13      0.000 000 62 e13      K
+atomic mass unit-kilogram relationship                 1.660 539 040 e-27    0.000 000 020 e-27    kg
+atomic unit of 1st hyperpolarizability                 3.206 361 329 e-53    0.000 000 020 e-53    C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                 6.235 380 085 e-65    0.000 000 077 e-65    C^4 m^4 J^-3
+atomic unit of action                                  1.054 571 800 e-34    0.000 000 013 e-34    J s
+atomic unit of charge                                  1.602 176 6208 e-19   0.000 000 0098 e-19   C
+atomic unit of charge density                          1.081 202 3770 e12    0.000 000 0067 e12    C m^-3
+atomic unit of current                                 6.623 618 183 e-3     0.000 000 041 e-3     A
+atomic unit of electric dipole mom.                    8.478 353 552 e-30    0.000 000 052 e-30    C m
+atomic unit of electric field                          5.142 206 707 e11     0.000 000 032 e11     V m^-1
+atomic unit of electric field gradient                 9.717 362 356 e21     0.000 000 060 e21     V m^-2
+atomic unit of electric polarizability                 1.648 777 2731 e-41   0.000 000 0011 e-41   C^2 m^2 J^-1
+atomic unit of electric potential                      27.211 386 02         0.000 000 17          V
+atomic unit of electric quadrupole mom.                4.486 551 484 e-40    0.000 000 028 e-40    C m^2
+atomic unit of energy                                  4.359 744 650 e-18    0.000 000 054 e-18    J
+atomic unit of force                                   8.238 723 36 e-8      0.000 000 10 e-8      N
+atomic unit of length                                  0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+atomic unit of mag. dipole mom.                        1.854 801 999 e-23    0.000 000 011 e-23    J T^-1
+atomic unit of mag. flux density                       2.350 517 550 e5      0.000 000 014 e5      T
+atomic unit of magnetizability                         7.891 036 5886 e-29   0.000 000 0090 e-29   J T^-2
+atomic unit of mass                                    9.109 383 56 e-31     0.000 000 11 e-31     kg
+atomic unit of mom.um                                  1.992 851 882 e-24    0.000 000 024 e-24    kg m s^-1
+atomic unit of permittivity                            1.112 650 056... e-10 (exact)               F m^-1
+atomic unit of time                                    2.418 884 326509e-17  0.000 000 000014e-17  s
+atomic unit of velocity                                2.187 691 262 77 e6   0.000 000 000 50 e6   m s^-1
+Avogadro constant                                      6.022 140 857 e23     0.000 000 074 e23     mol^-1
+Bohr magneton                                          927.400 9994 e-26     0.000 0057 e-26       J T^-1
+Bohr magneton in eV/T                                  5.788 381 8012 e-5    0.000 000 0026 e-5    eV T^-1
+Bohr magneton in Hz/T                                  13.996 245 042 e9     0.000 000 086 e9      Hz T^-1
+Bohr magneton in inverse meters per tesla              46.686 448 14         0.000 000 29          m^-1 T^-1
+Bohr magneton in K/T                                   0.671 714 05          0.000 000 39          K T^-1
+Bohr radius                                            0.529 177 210 67 e-10 0.000 000 000 12 e-10 m
+Boltzmann constant                                     1.380 648 52 e-23     0.000 000 79 e-23     J K^-1
+Boltzmann constant in eV/K                             8.617 3303 e-5        0.000 0050 e-5        eV K^-1
+Boltzmann constant in Hz/K                             2.083 6612 e10        0.000 0012 e10        Hz K^-1
+Boltzmann constant in inverse meters per kelvin        69.503 457            0.000 040             m^-1 K^-1
+characteristic impedance of vacuum                     376.730 313 461...    (exact)               ohm
+classical electron radius                              2.817 940 3227 e-15   0.000 000 0019 e-15   m
+Compton wavelength                                     2.426 310 2367 e-12   0.000 000 0011 e-12   m
+Compton wavelength over 2 pi                           386.159 267 64 e-15   0.000 000 18 e-15     m
+conductance quantum                                    7.748 091 7310 e-5    0.000 000 0018 e-5    S
+conventional value of Josephson constant               483 597.9 e9          (exact)               Hz V^-1
+conventional value of von Klitzing constant            25 812.807            (exact)               ohm
+Cu x unit                                              1.002 076 97 e-13     0.000 000 28 e-13     m
+deuteron-electron mag. mom. ratio                      -4.664 345 535 e-4    0.000 000 026 e-4
+deuteron-electron mass ratio                           3670.482 967 85       0.000 000 13
+deuteron g factor                                      0.857 438 2311        0.000 000 0048
+deuteron mag. mom.                                     0.433 073 5040 e-26   0.000 000 0036 e-26   J T^-1
+deuteron mag. mom. to Bohr magneton ratio              0.466 975 4554 e-3    0.000 000 0026 e-3
+deuteron mag. mom. to nuclear magneton ratio           0.857 438 2311        0.000 000 0048
+deuteron mass                                          3.343 583 719 e-27    0.000 000 041 e-27    kg
+deuteron mass energy equivalent                        3.005 063 183 e-10    0.000 000 037 e-10    J
+deuteron mass energy equivalent in MeV                 1875.612 928          0.000 012             MeV
+deuteron mass in u                                     2.013 553 212 745     0.000 000 000 040     u
+deuteron molar mass                                    2.013 553 212 745 e-3 0.000 000 000 040 e-3 kg mol^-1
+deuteron-neutron mag. mom. ratio                       -0.448 206 52         0.000 000 11
+deuteron-proton mag. mom. ratio                        0.307 012 2077        0.000 000 0015
+deuteron-proton mass ratio                             1.999 007 500 87      0.000 000 000 19
+deuteron rms charge radius                             2.1413 e-15           0.0025 e-15           m
+electric constant                                      8.854 187 817... e-12 (exact)               F m^-1
+electron charge to mass quotient                       -1.758 820 024 e11    0.000 000 011 e11     C kg^-1
+electron-deuteron mag. mom. ratio                      -2143.923 499         0.000 012
+electron-deuteron mass ratio                           2.724 437 107 484 e-4 0.000 000 000 096 e-4
+electron g factor                                      -2.002 319 304 361 82 0.000 000 000 000 52
+electron gyromag. ratio                                1.760 859 644 e11     0.000 000 011 e11     s^-1 T^-1
+electron gyromag. ratio over 2 pi                      28 024.951 64         0.000 17              MHz T^-1
+electron-helion mass ratio                             1.819 543 074 854 e-4 0.000 000 000 088 e-4
+electron mag. mom.                                     -928.476 4620 e-26    0.000 0057 e-26       J T^-1
+electron mag. mom. anomaly                             1.159 652 180 91 e-3  0.000 000 000 26 e-3
+electron mag. mom. to Bohr magneton ratio              -1.001 159 652 180 91 0.000 000 000 000 26
+electron mag. mom. to nuclear magneton ratio           -1838.281 972 34      0.000 000 17
+electron mass                                          9.109 383 56 e-31     0.000 000 11 e-31     kg
+electron mass energy equivalent                        8.187 105 65 e-14     0.000 000 10 e-14     J
+electron mass energy equivalent in MeV                 0.510 998 9461        0.000 000 0031        MeV
+electron mass in u                                     5.485 799 090 70 e-4  0.000 000 000 16 e-4  u
+electron molar mass                                    5.485 799 090 70 e-7  0.000 000 000 16 e-7  kg mol^-1
+electron-muon mag. mom. ratio                          206.766 9880          0.000 0046
+electron-muon mass ratio                               4.836 331 70 e-3      0.000 000 11 e-3
+electron-neutron mag. mom. ratio                       960.920 50            0.000 23
+electron-neutron mass ratio                            5.438 673 4428 e-4    0.000 000 0027 e-4
+electron-proton mag. mom. ratio                        -658.210 6866         0.000 0020
+electron-proton mass ratio                             5.446 170 213 52 e-4  0.000 000 000 52 e-4
+electron-tau mass ratio                                2.875 92 e-4          0.000 26 e-4
+electron to alpha particle mass ratio                  1.370 933 554 798 e-4 0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio            864.058 257           0.000 010
+electron to shielded proton mag. mom. ratio            -658.227 5971         0.000 0072
+electron-triton mass ratio                             1.819 200 062 203 e-4 0.000 000 000 084 e-4
+electron volt                                          1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-atomic mass unit relationship            1.073 544 1105 e-9    0.000 000 0066 e-9    u
+electron volt-hartree relationship                     3.674 932 248 e-2     0.000 000 023 e-2     E_h
+electron volt-hertz relationship                       2.417 989 262 e14     0.000 000 015 e14     Hz
+electron volt-inverse meter relationship               8.065 544 005 e5      0.000 000 050 e5      m^-1
+electron volt-joule relationship                       1.602 176 6208 e-19   0.000 000 0098 e-19   J
+electron volt-kelvin relationship                      1.160 452 21 e4       0.000 000 67 e4       K
+electron volt-kilogram relationship                    1.782 661 907 e-36    0.000 000 011 e-36    kg
+elementary charge                                      1.602 176 6208 e-19   0.000 000 0098 e-19   C
+elementary charge over h                               2.417 989 262 e14     0.000 000 015 e14     A J^-1
+Faraday constant                                       96 485.332 89         0.000 59              C mol^-1
+Faraday constant for conventional electric current     96 485.3251           0.0012                C_90 mol^-1
+Fermi coupling constant                                1.166 3787 e-5        0.000 0006 e-5        GeV^-2
+fine-structure constant                                7.297 352 5664 e-3    0.000 000 0017 e-3
+first radiation constant                               3.741 771 790 e-16    0.000 000 046 e-16    W m^2
+first radiation constant for spectral radiance         1.191 042 953 e-16    0.000 000 015 e-16    W m^2 sr^-1
+hartree-atomic mass unit relationship                  2.921 262 3197 e-8    0.000 000 0013 e-8    u
+hartree-electron volt relationship                     27.211 386 02         0.000 000 17          eV
+Hartree energy                                         4.359 744 650 e-18    0.000 000 054 e-18    J
+Hartree energy in eV                                   27.211 386 02         0.000 000 17          eV
+hartree-hertz relationship                             6.579 683 920 711 e15 0.000 000 000 039 e15 Hz
+hartree-inverse meter relationship                     2.194 746 313 702 e7  0.000 000 000 013 e7  m^-1
+hartree-joule relationship                             4.359 744 650 e-18    0.000 000 054 e-18    J
+hartree-kelvin relationship                            3.157 7513 e5         0.000 0018 e5         K
+hartree-kilogram relationship                          4.850 870 129 e-35    0.000 000 060 e-35    kg
+helion-electron mass ratio                             5495.885 279 22       0.000 000 27
+helion g factor                                        -4.255 250 616        0.000 000 050
+helion mag. mom.                                       -1.074 617 522 e-26   0.000 000 014 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                -1.158 740 958 e-3    0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio             -2.127 625 308        0.000 000 025
+helion mass                                            5.006 412 700 e-27    0.000 000 062 e-27    kg
+helion mass energy equivalent                          4.499 539 341 e-10    0.000 000 055 e-10    J
+helion mass energy equivalent in MeV                   2808.391 586          0.000 017             MeV
+helion mass in u                                       3.014 932 246 73      0.000 000 000 12      u
+helion molar mass                                      3.014 932 246 73 e-3  0.000 000 000 12 e-3  kg mol^-1
+helion-proton mass ratio                               2.993 152 670 46      0.000 000 000 29
+hertz-atomic mass unit relationship                    4.439 821 6616 e-24   0.000 000 0020 e-24   u
+hertz-electron volt relationship                       4.135 667 662 e-15    0.000 000 025 e-15    eV
+hertz-hartree relationship                             1.5198298460088 e-16  0.0000000000090e-16   E_h
+hertz-inverse meter relationship                       3.335 640 951... e-9  (exact)               m^-1
+hertz-joule relationship                               6.626 070 040 e-34    0.000 000 081 e-34    J
+hertz-kelvin relationship                              4.799 2447 e-11       0.000 0028 e-11       K
+hertz-kilogram relationship                            7.372 497 201 e-51    0.000 000 091 e-51    kg
+inverse fine-structure constant                        137.035 999 139       0.000 000 031
+inverse meter-atomic mass unit relationship            1.331 025 049 00 e-15 0.000 000 000 61 e-15 u
+inverse meter-electron volt relationship               1.239 841 9739 e-6    0.000 000 0076 e-6    eV
+inverse meter-hartree relationship                     4.556 335 252 767 e-8 0.000 000 000 027 e-8 E_h
+inverse meter-hertz relationship                       299 792 458           (exact)               Hz
+inverse meter-joule relationship                       1.986 445 824 e-25    0.000 000 024 e-25    J
+inverse meter-kelvin relationship                      1.438 777 36 e-2      0.000 000 83 e-2      K
+inverse meter-kilogram relationship                    2.210 219 057 e-42    0.000 000 027 e-42    kg
+inverse of conductance quantum                         12 906.403 7278       0.000 0029            ohm
+Josephson constant                                     483 597.8525 e9       0.0030 e9             Hz V^-1
+joule-atomic mass unit relationship                    6.700 535 363 e9      0.000 000 082 e9      u
+joule-electron volt relationship                       6.241 509 126 e18     0.000 000 038 e18     eV
+joule-hartree relationship                             2.293 712 317 e17     0.000 000 028 e17     E_h
+joule-hertz relationship                               1.509 190 205 e33     0.000 000 019 e33     Hz
+joule-inverse meter relationship                       5.034 116 651 e24     0.000 000 062 e24     m^-1
+joule-kelvin relationship                              7.242 9731 e22        0.000 0042 e22        K
+joule-kilogram relationship                            1.112 650 056... e-17 (exact)               kg
+kelvin-atomic mass unit relationship                   9.251 0842 e-14       0.000 0053 e-14       u
+kelvin-electron volt relationship                      8.617 3303 e-5        0.000 0050 e-5        eV
+kelvin-hartree relationship                            3.166 8105 e-6        0.000 0018 e-6        E_h
+kelvin-hertz relationship                              2.083 6612 e10        0.000 0012 e10        Hz
+kelvin-inverse meter relationship                      69.503 457            0.000 040             m^-1
+kelvin-joule relationship                              1.380 648 52 e-23     0.000 000 79 e-23     J
+kelvin-kilogram relationship                           1.536 178 65 e-40     0.000 000 88 e-40     kg
+kilogram-atomic mass unit relationship                 6.022 140 857 e26     0.000 000 074 e26     u
+kilogram-electron volt relationship                    5.609 588 650 e35     0.000 000 034 e35     eV
+kilogram-hartree relationship                          2.061 485 823 e34     0.000 000 025 e34     E_h
+kilogram-hertz relationship                            1.356 392 512 e50     0.000 000 017 e50     Hz
+kilogram-inverse meter relationship                    4.524 438 411 e41     0.000 000 056 e41     m^-1
+kilogram-joule relationship                            8.987 551 787... e16  (exact)               J
+kilogram-kelvin relationship                           6.509 6595 e39        0.000 0037 e39        K
+lattice parameter of silicon                           543.102 0504 e-12     0.000 0089 e-12       m
+Loschmidt constant (273.15 K, 100 kPa)                 2.651 6467 e25        0.000 0015 e25        m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)             2.686 7811 e25        0.000 0015 e25        m^-3
+mag. constant                                          12.566 370 614... e-7 (exact)               N A^-2
+mag. flux quantum                                      2.067 833 831 e-15    0.000 000 013 e-15    Wb
+molar gas constant                                     8.314 4598            0.000 0048            J mol^-1 K^-1
+molar mass constant                                    1 e-3                 (exact)               kg mol^-1
+molar mass of carbon-12                                12 e-3                (exact)               kg mol^-1
+molar Planck constant                                  3.990 312 7110 e-10   0.000 000 0018 e-10   J s mol^-1
+molar Planck constant times c                          0.119 626 565 582     0.000 000 000 054     J m mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)          22.710 947 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)      22.413 962 e-3        0.000 013 e-3         m^3 mol^-1
+molar volume of silicon                                12.058 832 14 e-6     0.000 000 61 e-6      m^3 mol^-1
+Mo x unit                                              1.002 099 52 e-13     0.000 000 53 e-13     m
+muon Compton wavelength                                11.734 441 11 e-15    0.000 000 26 e-15     m
+muon Compton wavelength over 2 pi                      1.867 594 308 e-15    0.000 000 042 e-15    m
+muon-electron mass ratio                               206.768 2826          0.000 0046
+muon g factor                                          -2.002 331 8418       0.000 000 0013
+muon mag. mom.                                         -4.490 448 26 e-26    0.000 000 10 e-26     J T^-1
+muon mag. mom. anomaly                                 1.165 920 89 e-3      0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                  -4.841 970 48 e-3     0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio               -8.890 597 05         0.000 000 20
+muon mass                                              1.883 531 594 e-28    0.000 000 048 e-28    kg
+muon mass energy equivalent                            1.692 833 774 e-11    0.000 000 043 e-11    J
+muon mass energy equivalent in MeV                     105.658 3745          0.000 0024            MeV
+muon mass in u                                         0.113 428 9257        0.000 000 0025        u
+muon molar mass                                        0.113 428 9257 e-3    0.000 000 0025 e-3    kg mol^-1
+muon-neutron mass ratio                                0.112 454 5167        0.000 000 0025
+muon-proton mag. mom. ratio                            -3.183 345 142        0.000 000 071
+muon-proton mass ratio                                 0.112 609 5262        0.000 000 0025
+muon-tau mass ratio                                    5.946 49 e-2          0.000 54 e-2
+natural unit of action                                 1.054 571 800 e-34    0.000 000 013 e-34    J s
+natural unit of action in eV s                         6.582 119 514 e-16    0.000 000 040 e-16    eV s
+natural unit of energy                                 8.187 105 65 e-14     0.000 000 10 e-14     J
+natural unit of energy in MeV                          0.510 998 9461        0.000 000 0031        MeV
+natural unit of length                                 386.159 267 64 e-15   0.000 000 18 e-15     m
+natural unit of mass                                   9.109 383 56 e-31     0.000 000 11 e-31     kg
+natural unit of mom.um                                 2.730 924 488 e-22    0.000 000 034 e-22    kg m s^-1
+natural unit of mom.um in MeV/c                        0.510 998 9461        0.000 000 0031        MeV/c
+natural unit of time                                   1.288 088 667 12 e-21 0.000 000 000 58 e-21 s
+natural unit of velocity                               299 792 458           (exact)               m s^-1
+neutron Compton wavelength                             1.319 590 904 81 e-15 0.000 000 000 88 e-15 m
+neutron Compton wavelength over 2 pi                   0.210 019 415 36 e-15 0.000 000 000 14 e-15 m
+neutron-electron mag. mom. ratio                       1.040 668 82 e-3      0.000 000 25 e-3
+neutron-electron mass ratio                            1838.683 661 58       0.000 000 90
+neutron g factor                                       -3.826 085 45         0.000 000 90
+neutron gyromag. ratio                                 1.832 471 72 e8       0.000 000 43 e8       s^-1 T^-1
+neutron gyromag. ratio over 2 pi                       29.164 6933           0.000 0069            MHz T^-1
+neutron mag. mom.                                      -0.966 236 50 e-26    0.000 000 23 e-26     J T^-1
+neutron mag. mom. to Bohr magneton ratio               -1.041 875 63 e-3     0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio            -1.913 042 73         0.000 000 45
+neutron mass                                           1.674 927 471 e-27    0.000 000 021 e-27    kg
+neutron mass energy equivalent                         1.505 349 739 e-10    0.000 000 019 e-10    J
+neutron mass energy equivalent in MeV                  939.565 4133          0.000 0058            MeV
+neutron mass in u                                      1.008 664 915 88      0.000 000 000 49      u
+neutron molar mass                                     1.008 664 915 88 e-3  0.000 000 000 49 e-3  kg mol^-1
+neutron-muon mass ratio                                8.892 484 08          0.000 000 20
+neutron-proton mag. mom. ratio                         -0.684 979 34         0.000 000 16
+neutron-proton mass difference                         2.305 573 77 e-30     0.000 000 85 e-30
+neutron-proton mass difference energy equivalent       2.072 146 37 e-13     0.000 000 76 e-13
+neutron-proton mass difference energy equivalent in MeV 1.293 332 05         0.000 000 48
+neutron-proton mass difference in u                    0.001 388 449 00      0.000 000 000 51
+neutron-proton mass ratio                              1.001 378 418 98      0.000 000 000 51
+neutron-tau mass ratio                                 0.528 790             0.000 048
+neutron to shielded proton mag. mom. ratio             -0.684 996 94         0.000 000 16
+Newtonian constant of gravitation                      6.674 08 e-11         0.000 31 e-11         m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c         6.708 61 e-39         0.000 31 e-39         (GeV/c^2)^-2
+nuclear magneton                                       5.050 783 699 e-27    0.000 000 031 e-27    J T^-1
+nuclear magneton in eV/T                               3.152 451 2550 e-8    0.000 000 0015 e-8    eV T^-1
+nuclear magneton in inverse meters per tesla           2.542 623 432 e-2     0.000 000 016 e-2     m^-1 T^-1
+nuclear magneton in K/T                                3.658 2690 e-4        0.000 0021 e-4        K T^-1
+nuclear magneton in MHz/T                              7.622 593 285         0.000 000 047         MHz T^-1
+Planck constant                                        6.626 070 040 e-34    0.000 000 081 e-34    J s
+Planck constant in eV s                                4.135 667 662 e-15    0.000 000 025 e-15    eV s
+Planck constant over 2 pi                              1.054 571 800 e-34    0.000 000 013 e-34    J s
+Planck constant over 2 pi in eV s                      6.582 119 514 e-16    0.000 000 040 e-16    eV s
+Planck constant over 2 pi times c in MeV fm            197.326 9788          0.000 0012            MeV fm
+Planck length                                          1.616 229 e-35        0.000 038 e-35        m
+Planck mass                                            2.176 470 e-8         0.000 051 e-8         kg
+Planck mass energy equivalent in GeV                   1.220 910 e19         0.000 029 e19         GeV
+Planck temperature                                     1.416 808 e32         0.000 033 e32         K
+Planck time                                            5.391 16 e-44         0.000 13 e-44         s
+proton charge to mass quotient                         9.578 833 226 e7      0.000 000 059 e7      C kg^-1
+proton Compton wavelength                              1.321 409 853 96 e-15 0.000 000 000 61 e-15 m
+proton Compton wavelength over 2 pi                    0.210 308910109e-15   0.000 000 000097e-15  m
+proton-electron mass ratio                             1836.152 673 89       0.000 000 17
+proton g factor                                        5.585 694 702         0.000 000 017
+proton gyromag. ratio                                  2.675 221 900 e8      0.000 000 018 e8      s^-1 T^-1
+proton gyromag. ratio over 2 pi                        42.577 478 92         0.000 000 29          MHz T^-1
+proton mag. mom.                                       1.410 606 7873 e-26   0.000 000 0097 e-26   J T^-1
+proton mag. mom. to Bohr magneton ratio                1.521 032 2053 e-3    0.000 000 0046 e-3
+proton mag. mom. to nuclear magneton ratio             2.792 847 3508        0.000 000 0085
+proton mag. shielding correction                       25.691 e-6            0.011 e-6
+proton mass                                            1.672 621 898 e-27    0.000 000 021 e-27    kg
+proton mass energy equivalent                          1.503 277 593 e-10    0.000 000 018 e-10    J
+proton mass energy equivalent in MeV                   938.272 0813          0.000 0058            MeV
+proton mass in u                                       1.007 276 466 879     0.000 000 000 091     u
+proton molar mass                                      1.007 276 466 879 e-3 0.000 000 000 091 e-3 kg mol^-1
+proton-muon mass ratio                                 8.880 243 38          0.000 000 20
+proton-neutron mag. mom. ratio                         -1.459 898 05         0.000 000 34
+proton-neutron mass ratio                              0.998 623 478 44      0.000 000 000 51
+proton rms charge radius                               0.8751 e-15           0.0061 e-15           m
+proton-tau mass ratio                                  0.528 063             0.000 048
+quantum of circulation                                 3.636 947 5486 e-4    0.000 000 0017 e-4    m^2 s^-1
+quantum of circulation times 2                         7.273 895 0972 e-4    0.000 000 0033 e-4    m^2 s^-1
+Rydberg constant                                       10 973 731.568 508    0.000 065             m^-1
+Rydberg constant times c in Hz                         3.289 841 960 355 e15 0.000 000 000 019 e15 Hz
+Rydberg constant times hc in eV                        13.605 693 009        0.000 000 084         eV
+Rydberg constant times hc in J                         2.179 872 325 e-18    0.000 000 027 e-18    J
+Sackur-Tetrode constant (1 K, 100 kPa)                 -1.151 7084           0.000 0014
+Sackur-Tetrode constant (1 K, 101.325 kPa)             -1.164 8714           0.000 0014
+second radiation constant                              1.438 777 36 e-2      0.000 000 83 e-2      m K
+shielded helion gyromag. ratio                         2.037 894 585 e8      0.000 000 027 e8      s^-1 T^-1
+shielded helion gyromag. ratio over 2 pi               32.434 099 66         0.000 000 43          MHz T^-1
+shielded helion mag. mom.                              -1.074 553 080 e-26   0.000 000 014 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio       -1.158 671 471 e-3    0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio    -2.127 497 720        0.000 000 025
+shielded helion to proton mag. mom. ratio              -0.761 766 5603       0.000 000 0092
+shielded helion to shielded proton mag. mom. ratio     -0.761 786 1313       0.000 000 0033
+shielded proton gyromag. ratio                         2.675 153 171 e8      0.000 000 033 e8      s^-1 T^-1
+shielded proton gyromag. ratio over 2 pi               42.576 385 07         0.000 000 53          MHz T^-1
+shielded proton mag. mom.                              1.410 570 547 e-26    0.000 000 018 e-26    J T^-1
+shielded proton mag. mom. to Bohr magneton ratio       1.520 993 128 e-3     0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio    2.792 775 600         0.000 000 030
+speed of light in vacuum                               299 792 458           (exact)               m s^-1
+standard acceleration of gravity                       9.806 65              (exact)               m s^-2
+standard atmosphere                                    101 325               (exact)               Pa
+standard-state pressure                                100 000               (exact)               Pa
+Stefan-Boltzmann constant                              5.670 367 e-8         0.000 013 e-8         W m^-2 K^-4
+tau Compton wavelength                                 0.697 787 e-15        0.000 063 e-15        m
+tau Compton wavelength over 2 pi                       0.111 056 e-15        0.000 010 e-15        m
+tau-electron mass ratio                                3477.15               0.31
+tau mass                                               3.167 47 e-27         0.000 29 e-27         kg
+tau mass energy equivalent                             2.846 78 e-10         0.000 26 e-10         J
+tau mass energy equivalent in MeV                      1776.82               0.16                  MeV
+tau mass in u                                          1.907 49              0.000 17              u
+tau molar mass                                         1.907 49 e-3          0.000 17 e-3          kg mol^-1
+tau-muon mass ratio                                    16.8167               0.0015
+tau-neutron mass ratio                                 1.891 11              0.000 17
+tau-proton mass ratio                                  1.893 72              0.000 17
+Thomson cross section                                  0.665 245 871 58 e-28 0.000 000 000 91 e-28 m^2
+triton-electron mass ratio                             5496.921 535 88       0.000 000 26
+triton g factor                                        5.957 924 920         0.000 000 028
+triton mag. mom.                                       1.504 609 503 e-26    0.000 000 012 e-26    J T^-1
+triton mag. mom. to Bohr magneton ratio                1.622 393 6616 e-3    0.000 000 0076 e-3
+triton mag. mom. to nuclear magneton ratio             2.978 962 460         0.000 000 014
+triton mass                                            5.007 356 665 e-27    0.000 000 062 e-27    kg
+triton mass energy equivalent                          4.500 387 735 e-10    0.000 000 055 e-10    J
+triton mass energy equivalent in MeV                   2808.921 112          0.000 017             MeV
+triton mass in u                                       3.015 500 716 32      0.000 000 000 11      u
+triton molar mass                                      3.015 500 716 32 e-3  0.000 000 000 11 e-3  kg mol^-1
+triton-proton mass ratio                               2.993 717 033 48      0.000 000 000 22
+unified atomic mass unit                               1.660 539 040 e-27    0.000 000 020 e-27    kg
+von Klitzing constant                                  25 812.807 4555       0.000 0059            ohm
+weak mixing angle                                      0.2223                0.0021
+Wien frequency displacement law constant               5.878 9238 e10        0.000 0034 e10        Hz K^-1
+Wien wavelength displacement law constant              2.897 7729 e-3        0.000 0017 e-3        m K"""
+
+
+exact2014 = exact2010
+
+
+txt2018 = """\
+alpha particle-electron mass ratio                          7294.299 541 42          0.000 000 24
+alpha particle mass                                         6.644 657 3357 e-27      0.000 000 0020 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1914 e-10      0.000 000 0018 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4066            0.000 0011               MeV
+alpha particle mass in u                                    4.001 506 179 127        0.000 000 000 063        u
+alpha particle molar mass                                   4.001 506 1777 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 09         0.000 000 000 22
+alpha particle relative atomic mass                         4.001 506 179 127        0.000 000 000 063
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 102 42           0.000 000 28             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0242 e8        0.000 000 0028 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6874 e7        0.000 000 0010 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 718 71 e23     0.000 000 000 68 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6104 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 085 60 e-10    0.000 000 000 45 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 019 16 e13     0.000 000 000 33 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 3061 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9905 e-65      0.000 000 0038 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 384 57 e12     0.000 000 000 49 e12     C m^-3
+atomic unit of current                                      6.623 618 237 510 e-3    0.000 000 000 013 e-3    A
+atomic unit of electric dipole mom.                         8.478 353 6255 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 747 63 e11     0.000 000 000 78 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4292 e21       0.000 000 0029 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 274 36 e-41    0.000 000 000 50 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 988       0.000 000 000 053        V
+atomic unit of electric quadrupole mom.                     4.486 551 5246 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+atomic unit of force                                        8.238 723 4983 e-8       0.000 000 0012 e-8       N
+atomic unit of length                                       5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 015 66 e-23    0.000 000 000 56 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 567 58 e5      0.000 000 000 71 e5      T
+atomic unit of magnetizability                              7.891 036 6008 e-29      0.000 000 0048 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 914 10 e-24    0.000 000 000 30 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 055 45 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5857 e-17  0.000 000 000 0047 e-17  s
+atomic unit of velocity                                     2.187 691 263 64 e6      0.000 000 000 33 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0783 e-24      0.000 000 0028 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 8060 e-5       0.000 000 0017 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 493 61 e10     0.000 000 000 42 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 783           0.000 000 014            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 815 63         0.000 000 000 20         K T^-1
+Bohr radius                                                 5.291 772 109 03 e-11    0.000 000 000 80 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 668          0.000 000 057            ohm
+classical electron radius                                   2.817 940 3262 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 238 67 e-12    0.000 000 000 73 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Cu x unit                                                   1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 551 e-4       0.000 000 012 e-4
+deuteron-electron mass ratio                                3670.482 967 88          0.000 000 13
+deuteron g factor                                           0.857 438 2338           0.000 000 0022
+deuteron mag. mom.                                          4.330 735 094 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 570 e-4        0.000 000 012 e-4
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2338           0.000 000 0022
+deuteron mass                                               3.343 583 7724 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 231 02 e-10    0.000 000 000 91 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 942 57          0.000 000 57             MeV
+deuteron mass in u                                          2.013 553 212 745        0.000 000 000 040        u
+deuteron molar mass                                         2.013 553 212 05 e-3     0.000 000 000 61 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 53            0.000 000 11
+deuteron-proton mag. mom. ratio                             0.307 012 209 39         0.000 000 000 79
+deuteron-proton mass ratio                                  1.999 007 501 39         0.000 000 000 11
+deuteron relative atomic mass                               2.013 553 212 745        0.000 000 000 040
+deuteron rms charge radius                                  2.127 99 e-15            0.000 74 e-15            m
+electron charge to mass quotient                            -1.758 820 010 76 e11    0.000 000 000 53 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4915           0.000 0056
+electron-deuteron mass ratio                                2.724 437 107 462 e-4    0.000 000 000 096 e-4
+electron g factor                                           -2.002 319 304 362 56    0.000 000 000 000 35
+electron gyromag. ratio                                     1.760 859 630 23 e11     0.000 000 000 53 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 4242          0.000 0085               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 573 e-4    0.000 000 000 079 e-4
+electron mag. mom.                                          -9.284 764 7043 e-24     0.000 000 0028 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 181 28 e-3     0.000 000 000 18 e-3
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 181 28    0.000 000 000 000 18
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 88         0.000 000 11
+electron mass                                               9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7769 e-14      0.000 000 0025 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 00         0.000 000 000 15         MeV
+electron mass in u                                          5.485 799 090 65 e-4     0.000 000 000 16 e-4     u
+electron molar mass                                         5.485 799 0888 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9883             0.000 0046
+electron-muon mass ratio                                    4.836 331 69 e-3         0.000 000 11 e-3
+electron-neutron mag. mom. ratio                            960.920 50               0.000 23
+electron-neutron mass ratio                                 5.438 673 4424 e-4       0.000 000 0026 e-4
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 20
+electron-proton mass ratio                                  5.446 170 214 87 e-4     0.000 000 000 33 e-4
+electron relative atomic mass                               5.485 799 090 65 e-4     0.000 000 000 16 e-4
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4
+electron to alpha particle mass ratio                       1.370 933 554 787 e-4    0.000 000 000 045 e-4
+electron to shielded helion mag. mom. ratio                 864.058 257              0.000 010
+electron to shielded proton mag. mom. ratio                 -658.227 5971            0.000 0072
+electron-triton mass ratio                                  1.819 200 062 251 e-4    0.000 000 000 090 e-4
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 102 33 e-9     0.000 000 000 32 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5655 e-2   0.000 000 000 0071 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5693 e-3       0.000 000 0011 e-3
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 322 05 e-8     0.000 000 000 88 e-8     u
+hartree-electron volt relationship                          27.211 386 245 988       0.000 000 000 053        eV
+Hartree energy                                              4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+Hartree energy in eV                                        27.211 386 245 988       0.000 000 000 053        eV
+hartree-hertz relationship                                  6.579 683 920 502 e15    0.000 000 000 013 e15    Hz
+hartree-inverse meter relationship                          2.194 746 313 6320 e7    0.000 000 000 0043 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2071 e-18  0.000 000 000 0085 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0407 e5    0.000 000 000 0061 e5    K
+hartree-kilogram relationship                               4.850 870 209 5432 e-35  0.000 000 000 0094 e-35  kg
+helion-electron mass ratio                                  5495.885 280 07          0.000 000 24
+helion g factor                                             -4.255 250 615           0.000 000 050
+helion mag. mom.                                            -1.074 617 532 e-26      0.000 000 013 e-26       J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 958 e-3       0.000 000 014 e-3
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 307           0.000 000 025
+helion mass                                                 5.006 412 7796 e-27      0.000 000 0015 e-27      kg
+helion mass energy equivalent                               4.499 539 4125 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 607 43          0.000 000 85             MeV
+helion mass in u                                            3.014 932 247 175        0.000 000 000 097        u
+helion molar mass                                           3.014 932 246 13 e-3     0.000 000 000 91 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 67         0.000 000 000 13
+helion relative atomic mass                                 3.014 932 247 175        0.000 000 000 097
+helion shielding shift                                      5.996 743 e-5            0.000 010 e-5
+hertz-atomic mass unit relationship                         4.439 821 6652 e-24      0.000 000 0013 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0570 e-16  0.000 000 000 0029 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 084          0.000 000 021
+inverse meter-atomic mass unit relationship                 1.331 025 050 10 e-15    0.000 000 000 40 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9120 e-8   0.000 000 000 0088 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2565 e9        0.000 000 0020 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3963 e17   0.000 000 000 0045 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 3014 e-14      0.000 000 0028 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4556 e-6   0.000 000 000 0061 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7621 e26       0.000 000 0018 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7409 e34   0.000 000 000 0040 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         0.999 999 999 65 e-3     0.000 000 000 30 e-3     kg mol^-1
+molar mass of carbon-12                                     11.999 999 9958 e-3      0.000 000 0036 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Mo x unit                                                   1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2830             0.000 0046
+muon g factor                                               -2.002 331 8418          0.000 000 0013
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 89 e-3         0.000 000 63 e-3
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 47 e-3        0.000 000 11 e-3
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 03            0.000 000 20
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9259           0.000 000 0025           u
+muon molar mass                                             1.134 289 259 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5170           0.000 000 0025
+muon-proton mag. mom. ratio                                 -3.183 345 142           0.000 000 071
+muon-proton mass ratio                                      0.112 609 5264           0.000 000 0025
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7769 e-14      0.000 000 0025 e-14      J
+natural unit of energy in MeV                               0.510 998 950 00         0.000 000 000 15         MeV
+natural unit of length                                      3.861 592 6796 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7015 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 530 75 e-22    0.000 000 000 82 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 00         0.000 000 000 15         MeV/c
+natural unit of time                                        1.288 088 668 19 e-21    0.000 000 000 39 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 905 81 e-15    0.000 000 000 75 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 82 e-3         0.000 000 25 e-3
+neutron-electron mass ratio                                 1838.683 661 73          0.000 000 89
+neutron g factor                                            -3.826 085 45            0.000 000 90
+neutron gyromag. ratio                                      1.832 471 71 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6931              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3651 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 63 e-3        0.000 000 25 e-3
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 73            0.000 000 45
+neutron mass                                                1.674 927 498 04 e-27    0.000 000 000 95 e-27    kg
+neutron mass energy equivalent                              1.505 349 762 87 e-10    0.000 000 000 86 e-10    J
+neutron mass energy equivalent in MeV                       939.565 420 52           0.000 000 54             MeV
+neutron mass in u                                           1.008 664 915 95         0.000 000 000 49         u
+neutron molar mass                                          1.008 664 915 60 e-3     0.000 000 000 57 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 06             0.000 000 20
+neutron-proton mag. mom. ratio                              -0.684 979 34            0.000 000 16
+neutron-proton mass difference                              2.305 574 35 e-30        0.000 000 82 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 146 89 e-13        0.000 000 74 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 36             0.000 000 46             MeV
+neutron-proton mass difference in u                         1.388 449 33 e-3         0.000 000 49 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 31         0.000 000 000 49
+neutron relative atomic mass                                1.008 664 915 95         0.000 000 000 49
+neutron-tau mass ratio                                      0.528 779                0.000 036
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7461 e-27      0.000 000 0015 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 258 44 e-8     0.000 000 000 96 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 413 53 e-2     0.000 000 000 78 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7756 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2291           0.000 000 0023           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1560 e7        0.000 000 0029 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 855 39 e-15    0.000 000 000 40 e-15    m
+proton-electron mass ratio                                  1836.152 673 43          0.000 000 11
+proton g factor                                             5.585 694 6893           0.000 000 0016
+proton gyromag. ratio                                       2.675 221 8744 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 518           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 797 36 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 46 e-3
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82
+proton mag. shielding correction                            2.5689 e-5               0.0011 e-5
+proton mass                                                 1.672 621 923 69 e-27    0.000 000 000 51 e-27    kg
+proton mass energy equivalent                               1.503 277 615 98 e-10    0.000 000 000 46 e-10    J
+proton mass energy equivalent in MeV                        938.272 088 16           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 621        0.000 000 000 053        u
+proton molar mass                                           1.007 276 466 27 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 37             0.000 000 20
+proton-neutron mag. mom. ratio                              -1.459 898 05            0.000 000 34
+proton-neutron mass ratio                                   0.998 623 478 12         0.000 000 000 49
+proton relative atomic mass                                 1.007 276 466 621        0.000 000 000 053
+proton rms charge radius                                    8.414 e-16               0.019 e-16               m
+proton-tau mass ratio                                       0.528 051                0.000 036
+quantum of circulation                                      3.636 947 5516 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 1032 e-4       0.000 000 0022 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6796 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1552 e-16      0.000 000 0012 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 103 36 e-16    0.000 000 000 64 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 160       0.000 021                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2508 e15   0.000 000 000 0064 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 994       0.000 000 000 026        eV
+Rydberg constant times hc in J                              2.179 872 361 1035 e-18  0.000 000 000 0042 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 537 06        0.000 000 000 45
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 523 58        0.000 000 000 45
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 569 e8         0.000 000 024 e8         s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 099 42            0.000 000 38             MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 090 e-26      0.000 000 013 e-26       J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 471 e-3       0.000 000 014 e-3
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 719           0.000 000 025
+shielded helion to proton mag. mom. ratio                   -0.761 766 5618          0.000 000 0089
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1313          0.000 000 0033
+shielded proton gyromag. ratio                              2.675 153 151 e8         0.000 000 029 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 384 74            0.000 000 46             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 560 e-26       0.000 000 015 e-26       J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 128 e-3        0.000 000 017 e-3
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 599            0.000 000 030
+shielding difference of d and p in HD                       2.0200 e-8               0.0020 e-8
+shielding difference of t and p in HT                       2.4140 e-8               0.0020 e-8
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011
+tau-neutron mass ratio                                      1.891 15                 0.000 13
+tau-proton mass ratio                                       1.893 76                 0.000 13
+Thomson cross section                                       6.652 458 7321 e-29      0.000 000 0060 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 73          0.000 000 27
+triton g factor                                             5.957 924 931            0.000 000 012
+triton mag. mom.                                            1.504 609 5202 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6651 e-3       0.000 000 0032 e-3
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4656           0.000 000 0059
+triton mass                                                 5.007 356 7446 e-27      0.000 000 0015 e-27      kg
+triton mass energy equivalent                               4.500 387 8060 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 132 98          0.000 000 85             MeV
+triton mass in u                                            3.015 500 716 21         0.000 000 000 12         u
+triton molar mass                                           3.015 500 715 17 e-3     0.000 000 000 92 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 14         0.000 000 000 15
+triton relative atomic mass                                 3.015 500 716 21         0.000 000 000 12
+triton to proton mag. mom. ratio                            1.066 639 9191           0.000 000 0021
+unified atomic mass unit                                    1.660 539 066 60 e-27    0.000 000 000 50 e-27    kg
+vacuum electric permittivity                                8.854 187 8128 e-12      0.000 000 0013 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 062 12 e-6     0.000 000 000 19 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.222 90                 0.000 30
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 53                 0.000 17                   """
+
+
+def exact2018(exact):
+    # SI base constants
+    c = exact['speed of light in vacuum']
+    h = exact['Planck constant']
+    e = exact['elementary charge']
+    k = exact['Boltzmann constant']
+    N_A = exact['Avogadro constant']
+
+    # Other useful constants
+    R = N_A * k
+    hbar = h / (2*math.pi)
+    G_0 = 2 * e**2 / h
+
+    # Wien law numerical constants: https://en.wikipedia.org/wiki/Wien%27s_displacement_law
+    # (alpha - 3)*exp(alpha) + 3 = 0
+    # (x - 5)*exp(x) + 5 = 0
+    alpha_W = 2.821439372122078893403  # 3 + lambertw(-3 * exp(-3))
+    x_W = 4.965114231744276303699  # 5 + lambertw(-5 * exp(-5))
+
+    # Conventional electrical unit
+    # See https://en.wikipedia.org/wiki/Conventional_electrical_unit
+    K_J90 = exact['conventional value of Josephson constant']
+    K_J = 2 * e / h
+    R_K90 = exact['conventional value of von Klitzing constant']
+    R_K = h / e**2
+    V_90 = K_J90 / K_J
+    ohm_90 = R_K / R_K90
+    A_90 = V_90 / ohm_90
+
+    replace = {
+        'atomic unit of action': hbar,
+        'Boltzmann constant in eV/K': k / e,
+        'Boltzmann constant in Hz/K': k / h,
+        'Boltzmann constant in inverse meter per kelvin': k / (h * c),
+        'conductance quantum': G_0,
+        'conventional value of ampere-90': A_90,
+        'conventional value of coulomb-90': A_90,
+        'conventional value of farad-90': 1 / ohm_90,
+        'conventional value of henry-90': ohm_90,
+        'conventional value of ohm-90': ohm_90,
+        'conventional value of volt-90': V_90,
+        'conventional value of watt-90': V_90**2 / ohm_90,
+        'electron volt-hertz relationship': e / h,
+        'electron volt-inverse meter relationship': e / (h * c),
+        'electron volt-kelvin relationship': e / k,
+        'electron volt-kilogram relationship': e / c**2,
+        'elementary charge over h-bar': e / hbar,
+        'Faraday constant': e * N_A,
+        'first radiation constant': 2 * math.pi * h * c**2,
+        'first radiation constant for spectral radiance': 2 * h * c**2,
+        'hertz-electron volt relationship': h / e,
+        'hertz-inverse meter relationship': 1 / c,
+        'hertz-kelvin relationship': h / k,
+        'hertz-kilogram relationship': h / c**2,
+        'inverse meter-electron volt relationship': (h * c) / e,
+        'inverse meter-joule relationship': h * c,
+        'inverse meter-kelvin relationship': h * c / k,
+        'inverse meter-kilogram relationship': h / c,
+        'inverse of conductance quantum': 1 / G_0,
+        'Josephson constant': K_J,
+        'joule-electron volt relationship': 1 / e,
+        'joule-hertz relationship': 1 / h,
+        'joule-inverse meter relationship': 1 / (h * c),
+        'joule-kelvin relationship': 1 / k,
+        'joule-kilogram relationship': 1 / c**2,
+        'kelvin-electron volt relationship': k / e,
+        'kelvin-hertz relationship': k / h,
+        'kelvin-inverse meter relationship': k / (h * c),
+        'kelvin-kilogram relationship': k / c**2,
+        'kilogram-electron volt relationship': c**2 / e,
+        'kilogram-hertz relationship': c**2 / h,
+        'kilogram-inverse meter relationship': c / h,
+        'kilogram-joule relationship': c**2,
+        'kilogram-kelvin relationship': c**2 / k,
+        'Loschmidt constant (273.15 K, 100 kPa)': 100e3 / 273.15 / k,
+        'Loschmidt constant (273.15 K, 101.325 kPa)': 101.325e3 / 273.15 / k,
+        'mag. flux quantum': h / (2 * e),
+        'molar gas constant': R,
+        'molar Planck constant': h * N_A,
+        'molar volume of ideal gas (273.15 K, 100 kPa)': R * 273.15 / 100e3,
+        'molar volume of ideal gas (273.15 K, 101.325 kPa)': R * 273.15 / 101.325e3,
+        'natural unit of action': hbar,
+        'natural unit of action in eV s': hbar / e,
+        'Planck constant in eV/Hz': h / e,
+        'reduced Planck constant': hbar,
+        'reduced Planck constant in eV s': hbar / e,
+        'reduced Planck constant times c in MeV fm': hbar * c / (e * 1e6 * 1e-15),
+        'second radiation constant': h * c / k,
+        'Stefan-Boltzmann constant': 2 * math.pi**5 * k**4 / (15 * h**3 * c**2),
+        'von Klitzing constant': R_K,
+        'Wien frequency displacement law constant': alpha_W * k / h,
+        'Wien wavelength displacement law constant': h * c / (x_W * k),
+    }
+    return replace
+
+
+txt2022 = """\
+alpha particle-electron mass ratio                          7294.299 541 71          0.000 000 17             
+alpha particle mass                                         6.644 657 3450 e-27      0.000 000 0021 e-27      kg
+alpha particle mass energy equivalent                       5.971 920 1997 e-10      0.000 000 0019 e-10      J
+alpha particle mass energy equivalent in MeV                3727.379 4118            0.000 0012               MeV
+alpha particle mass in u                                    4.001 506 179 129        0.000 000 000 062        u
+alpha particle molar mass                                   4.001 506 1833 e-3       0.000 000 0012 e-3       kg mol^-1
+alpha particle-proton mass ratio                            3.972 599 690 252        0.000 000 000 070        
+alpha particle relative atomic mass                         4.001 506 179 129        0.000 000 000 062        
+alpha particle rms charge radius                            1.6785 e-15              0.0021 e-15              m
+Angstrom star                                               1.000 014 95 e-10        0.000 000 90 e-10        m
+atomic mass constant                                        1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic mass constant energy equivalent                      1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass constant energy equivalent in MeV               931.494 103 72           0.000 000 29             MeV
+atomic mass unit-electron volt relationship                 9.314 941 0372 e8        0.000 000 0029 e8        eV
+atomic mass unit-hartree relationship                       3.423 177 6922 e7        0.000 000 0011 e7        E_h
+atomic mass unit-hertz relationship                         2.252 342 721 85 e23     0.000 000 000 70 e23     Hz
+atomic mass unit-inverse meter relationship                 7.513 006 6209 e14       0.000 000 0023 e14       m^-1
+atomic mass unit-joule relationship                         1.492 418 087 68 e-10    0.000 000 000 46 e-10    J
+atomic mass unit-kelvin relationship                        1.080 954 020 67 e13     0.000 000 000 34 e13     K
+atomic mass unit-kilogram relationship                      1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+atomic unit of 1st hyperpolarizability                      3.206 361 2996 e-53      0.000 000 0015 e-53      C^3 m^3 J^-2
+atomic unit of 2nd hyperpolarizability                      6.235 379 9735 e-65      0.000 000 0039 e-65      C^4 m^4 J^-3
+atomic unit of action                                       1.054 571 817... e-34    (exact)                  J s
+atomic unit of charge                                       1.602 176 634 e-19       (exact)                  C
+atomic unit of charge density                               1.081 202 386 77 e12     0.000 000 000 51 e12     C m^-3
+atomic unit of current                                      6.623 618 237 5082 e-3   0.000 000 000 0072 e-3   A
+atomic unit of electric dipole mom.                         8.478 353 6198 e-30      0.000 000 0013 e-30      C m
+atomic unit of electric field                               5.142 206 751 12 e11     0.000 000 000 80 e11     V m^-1
+atomic unit of electric field gradient                      9.717 362 4424 e21       0.000 000 0030 e21       V m^-2
+atomic unit of electric polarizability                      1.648 777 272 12 e-41    0.000 000 000 51 e-41    C^2 m^2 J^-1
+atomic unit of electric potential                           27.211 386 245 981       0.000 000 000 030        V
+atomic unit of electric quadrupole mom.                     4.486 551 5185 e-40      0.000 000 0014 e-40      C m^2
+atomic unit of energy                                       4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+atomic unit of force                                        8.238 723 5038 e-8       0.000 000 0013 e-8       N
+atomic unit of length                                       5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+atomic unit of mag. dipole mom.                             1.854 802 013 15 e-23    0.000 000 000 58 e-23    J T^-1
+atomic unit of mag. flux density                            2.350 517 570 77 e5      0.000 000 000 73 e5      T
+atomic unit of magnetizability                              7.891 036 5794 e-29      0.000 000 0049 e-29      J T^-2
+atomic unit of mass                                         9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+atomic unit of momentum                                     1.992 851 915 45 e-24    0.000 000 000 31 e-24    kg m s^-1
+atomic unit of permittivity                                 1.112 650 056 20 e-10    0.000 000 000 17 e-10    F m^-1
+atomic unit of time                                         2.418 884 326 5864 e-17  0.000 000 000 0026 e-17  s
+atomic unit of velocity                                     2.187 691 262 16 e6      0.000 000 000 34 e6      m s^-1
+Avogadro constant                                           6.022 140 76 e23         (exact)                  mol^-1
+Bohr magneton                                               9.274 010 0657 e-24      0.000 000 0029 e-24      J T^-1
+Bohr magneton in eV/T                                       5.788 381 7982 e-5       0.000 000 0018 e-5       eV T^-1
+Bohr magneton in Hz/T                                       1.399 624 491 71 e10     0.000 000 000 44 e10     Hz T^-1
+Bohr magneton in inverse meter per tesla                    46.686 447 719           0.000 000 015            m^-1 T^-1
+Bohr magneton in K/T                                        0.671 713 814 72         0.000 000 000 21         K T^-1
+Bohr radius                                                 5.291 772 105 44 e-11    0.000 000 000 82 e-11    m
+Boltzmann constant                                          1.380 649 e-23           (exact)                  J K^-1
+Boltzmann constant in eV/K                                  8.617 333 262... e-5     (exact)                  eV K^-1
+Boltzmann constant in Hz/K                                  2.083 661 912... e10     (exact)                  Hz K^-1
+Boltzmann constant in inverse meter per kelvin              69.503 480 04...         (exact)                  m^-1 K^-1
+characteristic impedance of vacuum                          376.730 313 412          0.000 000 059            ohm
+classical electron radius                                   2.817 940 3205 e-15      0.000 000 0013 e-15      m
+Compton wavelength                                          2.426 310 235 38 e-12    0.000 000 000 76 e-12    m
+conductance quantum                                         7.748 091 729... e-5     (exact)                  S
+conventional value of ampere-90                             1.000 000 088 87...      (exact)                  A
+conventional value of coulomb-90                            1.000 000 088 87...      (exact)                  C
+conventional value of farad-90                              0.999 999 982 20...      (exact)                  F
+conventional value of henry-90                              1.000 000 017 79...      (exact)                  H
+conventional value of Josephson constant                    483 597.9 e9             (exact)                  Hz V^-1
+conventional value of ohm-90                                1.000 000 017 79...      (exact)                  ohm
+conventional value of volt-90                               1.000 000 106 66...      (exact)                  V
+conventional value of von Klitzing constant                 25 812.807               (exact)                  ohm
+conventional value of watt-90                               1.000 000 195 53...      (exact)                  W
+Copper x unit                                               1.002 076 97 e-13        0.000 000 28 e-13        m
+deuteron-electron mag. mom. ratio                           -4.664 345 550 e-4       0.000 000 012 e-4        
+deuteron-electron mass ratio                                3670.482 967 655         0.000 000 063            
+deuteron g factor                                           0.857 438 2335           0.000 000 0022           
+deuteron mag. mom.                                          4.330 735 087 e-27       0.000 000 011 e-27       J T^-1
+deuteron mag. mom. to Bohr magneton ratio                   4.669 754 568 e-4        0.000 000 012 e-4        
+deuteron mag. mom. to nuclear magneton ratio                0.857 438 2335           0.000 000 0022           
+deuteron mass                                               3.343 583 7768 e-27      0.000 000 0010 e-27      kg
+deuteron mass energy equivalent                             3.005 063 234 91 e-10    0.000 000 000 94 e-10    J
+deuteron mass energy equivalent in MeV                      1875.612 945 00          0.000 000 58             MeV
+deuteron mass in u                                          2.013 553 212 544        0.000 000 000 015        u
+deuteron molar mass                                         2.013 553 214 66 e-3     0.000 000 000 63 e-3     kg mol^-1
+deuteron-neutron mag. mom. ratio                            -0.448 206 52            0.000 000 11             
+deuteron-proton mag. mom. ratio                             0.307 012 209 30         0.000 000 000 79         
+deuteron-proton mass ratio                                  1.999 007 501 2699       0.000 000 000 0084       
+deuteron relative atomic mass                               2.013 553 212 544        0.000 000 000 015        
+deuteron rms charge radius                                  2.127 78 e-15            0.000 27 e-15            m
+electron charge to mass quotient                            -1.758 820 008 38 e11    0.000 000 000 55 e11     C kg^-1
+electron-deuteron mag. mom. ratio                           -2143.923 4921           0.000 0056               
+electron-deuteron mass ratio                                2.724 437 107 629 e-4    0.000 000 000 047 e-4    
+electron g factor                                           -2.002 319 304 360 92    0.000 000 000 000 36     
+electron gyromag. ratio                                     1.760 859 627 84 e11     0.000 000 000 55 e11     s^-1 T^-1
+electron gyromag. ratio in MHz/T                            28 024.951 3861          0.000 0087               MHz T^-1
+electron-helion mass ratio                                  1.819 543 074 649 e-4    0.000 000 000 053 e-4    
+electron mag. mom.                                          -9.284 764 6917 e-24     0.000 000 0029 e-24      J T^-1
+electron mag. mom. anomaly                                  1.159 652 180 46 e-3     0.000 000 000 18 e-3     
+electron mag. mom. to Bohr magneton ratio                   -1.001 159 652 180 46    0.000 000 000 000 18     
+electron mag. mom. to nuclear magneton ratio                -1838.281 971 877        0.000 000 032            
+electron mass                                               9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+electron mass energy equivalent                             8.187 105 7880 e-14      0.000 000 0026 e-14      J
+electron mass energy equivalent in MeV                      0.510 998 950 69         0.000 000 000 16         MeV
+electron mass in u                                          5.485 799 090 441 e-4    0.000 000 000 097 e-4    u
+electron molar mass                                         5.485 799 0962 e-7       0.000 000 0017 e-7       kg mol^-1
+electron-muon mag. mom. ratio                               206.766 9881             0.000 0046               
+electron-muon mass ratio                                    4.836 331 70 e-3         0.000 000 11 e-3         
+electron-neutron mag. mom. ratio                            960.920 48               0.000 23                 
+electron-neutron mass ratio                                 5.438 673 4416 e-4       0.000 000 0022 e-4       
+electron-proton mag. mom. ratio                             -658.210 687 89          0.000 000 19             
+electron-proton mass ratio                                  5.446 170 214 889 e-4    0.000 000 000 094 e-4    
+electron relative atomic mass                               5.485 799 090 441 e-4    0.000 000 000 097 e-4    
+electron-tau mass ratio                                     2.875 85 e-4             0.000 19 e-4             
+electron to alpha particle mass ratio                       1.370 933 554 733 e-4    0.000 000 000 032 e-4    
+electron to shielded helion mag. mom. ratio                 864.058 239 86           0.000 000 70             
+electron to shielded proton mag. mom. ratio                 -658.227 5856            0.000 0027               
+electron-triton mass ratio                                  1.819 200 062 327 e-4    0.000 000 000 068 e-4    
+electron volt                                               1.602 176 634 e-19       (exact)                  J
+electron volt-atomic mass unit relationship                 1.073 544 100 83 e-9     0.000 000 000 33 e-9     u
+electron volt-hartree relationship                          3.674 932 217 5665 e-2   0.000 000 000 0040 e-2   E_h
+electron volt-hertz relationship                            2.417 989 242... e14     (exact)                  Hz
+electron volt-inverse meter relationship                    8.065 543 937... e5      (exact)                  m^-1
+electron volt-joule relationship                            1.602 176 634 e-19       (exact)                  J
+electron volt-kelvin relationship                           1.160 451 812... e4      (exact)                  K
+electron volt-kilogram relationship                         1.782 661 921... e-36    (exact)                  kg
+elementary charge                                           1.602 176 634 e-19       (exact)                  C
+elementary charge over h-bar                                1.519 267 447... e15     (exact)                  A J^-1
+Faraday constant                                            96 485.332 12...         (exact)                  C mol^-1
+Fermi coupling constant                                     1.166 3787 e-5           0.000 0006 e-5           GeV^-2
+fine-structure constant                                     7.297 352 5643 e-3       0.000 000 0011 e-3       
+first radiation constant                                    3.741 771 852... e-16    (exact)                  W m^2
+first radiation constant for spectral radiance              1.191 042 972... e-16    (exact)                  W m^2 sr^-1
+hartree-atomic mass unit relationship                       2.921 262 317 97 e-8     0.000 000 000 91 e-8     u
+hartree-electron volt relationship                          27.211 386 245 981       0.000 000 000 030        eV
+Hartree energy                                              4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+Hartree energy in eV                                        27.211 386 245 981       0.000 000 000 030        eV
+hartree-hertz relationship                                  6.579 683 920 4999 e15   0.000 000 000 0072 e15   Hz
+hartree-inverse meter relationship                          2.194 746 313 6314 e7    0.000 000 000 0024 e7    m^-1
+hartree-joule relationship                                  4.359 744 722 2060 e-18  0.000 000 000 0048 e-18  J
+hartree-kelvin relationship                                 3.157 750 248 0398 e5    0.000 000 000 0034 e5    K
+hartree-kilogram relationship                               4.850 870 209 5419 e-35  0.000 000 000 0053 e-35  kg
+helion-electron mass ratio                                  5495.885 279 84          0.000 000 16             
+helion g factor                                             -4.255 250 6995          0.000 000 0034           
+helion mag. mom.                                            -1.074 617 551 98 e-26   0.000 000 000 93 e-26    J T^-1
+helion mag. mom. to Bohr magneton ratio                     -1.158 740 980 83 e-3    0.000 000 000 94 e-3     
+helion mag. mom. to nuclear magneton ratio                  -2.127 625 3498          0.000 000 0017           
+helion mass                                                 5.006 412 7862 e-27      0.000 000 0016 e-27      kg
+helion mass energy equivalent                               4.499 539 4185 e-10      0.000 000 0014 e-10      J
+helion mass energy equivalent in MeV                        2808.391 611 12          0.000 000 88             MeV
+helion mass in u                                            3.014 932 246 932        0.000 000 000 074        u
+helion molar mass                                           3.014 932 250 10 e-3     0.000 000 000 94 e-3     kg mol^-1
+helion-proton mass ratio                                    2.993 152 671 552        0.000 000 000 070        
+helion relative atomic mass                                 3.014 932 246 932        0.000 000 000 074        
+helion shielding shift                                      5.996 7029 e-5           0.000 0023 e-5           
+hertz-atomic mass unit relationship                         4.439 821 6590 e-24      0.000 000 0014 e-24      u
+hertz-electron volt relationship                            4.135 667 696... e-15    (exact)                  eV
+hertz-hartree relationship                                  1.519 829 846 0574 e-16  0.000 000 000 0017 e-16  E_h
+hertz-inverse meter relationship                            3.335 640 951... e-9     (exact)                  m^-1
+hertz-joule relationship                                    6.626 070 15 e-34        (exact)                  J
+hertz-kelvin relationship                                   4.799 243 073... e-11    (exact)                  K
+hertz-kilogram relationship                                 7.372 497 323... e-51    (exact)                  kg
+hyperfine transition frequency of Cs-133                    9 192 631 770            (exact)                  Hz
+inverse fine-structure constant                             137.035 999 177          0.000 000 021            
+inverse meter-atomic mass unit relationship                 1.331 025 048 24 e-15    0.000 000 000 41 e-15    u
+inverse meter-electron volt relationship                    1.239 841 984... e-6     (exact)                  eV
+inverse meter-hartree relationship                          4.556 335 252 9132 e-8   0.000 000 000 0050 e-8   E_h
+inverse meter-hertz relationship                            299 792 458              (exact)                  Hz
+inverse meter-joule relationship                            1.986 445 857... e-25    (exact)                  J
+inverse meter-kelvin relationship                           1.438 776 877... e-2     (exact)                  K
+inverse meter-kilogram relationship                         2.210 219 094... e-42    (exact)                  kg
+inverse of conductance quantum                              12 906.403 72...         (exact)                  ohm
+Josephson constant                                          483 597.848 4... e9      (exact)                  Hz V^-1
+joule-atomic mass unit relationship                         6.700 535 2471 e9        0.000 000 0021 e9        u
+joule-electron volt relationship                            6.241 509 074... e18     (exact)                  eV
+joule-hartree relationship                                  2.293 712 278 3969 e17   0.000 000 000 0025 e17   E_h
+joule-hertz relationship                                    1.509 190 179... e33     (exact)                  Hz
+joule-inverse meter relationship                            5.034 116 567... e24     (exact)                  m^-1
+joule-kelvin relationship                                   7.242 970 516... e22     (exact)                  K
+joule-kilogram relationship                                 1.112 650 056... e-17    (exact)                  kg
+kelvin-atomic mass unit relationship                        9.251 087 2884 e-14      0.000 000 0029 e-14      u
+kelvin-electron volt relationship                           8.617 333 262... e-5     (exact)                  eV
+kelvin-hartree relationship                                 3.166 811 563 4564 e-6   0.000 000 000 0035 e-6   E_h
+kelvin-hertz relationship                                   2.083 661 912... e10     (exact)                  Hz
+kelvin-inverse meter relationship                           69.503 480 04...         (exact)                  m^-1
+kelvin-joule relationship                                   1.380 649 e-23           (exact)                  J
+kelvin-kilogram relationship                                1.536 179 187... e-40    (exact)                  kg
+kilogram-atomic mass unit relationship                      6.022 140 7537 e26       0.000 000 0019 e26       u
+kilogram-electron volt relationship                         5.609 588 603... e35     (exact)                  eV
+kilogram-hartree relationship                               2.061 485 788 7415 e34   0.000 000 000 0022 e34   E_h
+kilogram-hertz relationship                                 1.356 392 489... e50     (exact)                  Hz
+kilogram-inverse meter relationship                         4.524 438 335... e41     (exact)                  m^-1
+kilogram-joule relationship                                 8.987 551 787... e16     (exact)                  J
+kilogram-kelvin relationship                                6.509 657 260... e39     (exact)                  K
+lattice parameter of silicon                                5.431 020 511 e-10       0.000 000 089 e-10       m
+lattice spacing of ideal Si (220)                           1.920 155 716 e-10       0.000 000 032 e-10       m
+Loschmidt constant (273.15 K, 100 kPa)                      2.651 645 804... e25     (exact)                  m^-3
+Loschmidt constant (273.15 K, 101.325 kPa)                  2.686 780 111... e25     (exact)                  m^-3
+luminous efficacy                                           683                      (exact)                  lm W^-1
+mag. flux quantum                                           2.067 833 848... e-15    (exact)                  Wb
+molar gas constant                                          8.314 462 618...         (exact)                  J mol^-1 K^-1
+molar mass constant                                         1.000 000 001 05 e-3     0.000 000 000 31 e-3     kg mol^-1
+molar mass of carbon-12                                     12.000 000 0126 e-3      0.000 000 0037 e-3       kg mol^-1
+molar Planck constant                                       3.990 312 712... e-10    (exact)                  J Hz^-1 mol^-1
+molar volume of ideal gas (273.15 K, 100 kPa)               22.710 954 64... e-3     (exact)                  m^3 mol^-1
+molar volume of ideal gas (273.15 K, 101.325 kPa)           22.413 969 54... e-3     (exact)                  m^3 mol^-1
+molar volume of silicon                                     1.205 883 199 e-5        0.000 000 060 e-5        m^3 mol^-1
+Molybdenum x unit                                           1.002 099 52 e-13        0.000 000 53 e-13        m
+muon Compton wavelength                                     1.173 444 110 e-14       0.000 000 026 e-14       m
+muon-electron mass ratio                                    206.768 2827             0.000 0046               
+muon g factor                                               -2.002 331 841 23        0.000 000 000 82         
+muon mag. mom.                                              -4.490 448 30 e-26       0.000 000 10 e-26        J T^-1
+muon mag. mom. anomaly                                      1.165 920 62 e-3         0.000 000 41 e-3         
+muon mag. mom. to Bohr magneton ratio                       -4.841 970 48 e-3        0.000 000 11 e-3         
+muon mag. mom. to nuclear magneton ratio                    -8.890 597 04            0.000 000 20             
+muon mass                                                   1.883 531 627 e-28       0.000 000 042 e-28       kg
+muon mass energy equivalent                                 1.692 833 804 e-11       0.000 000 038 e-11       J
+muon mass energy equivalent in MeV                          105.658 3755             0.000 0023               MeV
+muon mass in u                                              0.113 428 9257           0.000 000 0025           u
+muon molar mass                                             1.134 289 258 e-4        0.000 000 025 e-4        kg mol^-1
+muon-neutron mass ratio                                     0.112 454 5168           0.000 000 0025           
+muon-proton mag. mom. ratio                                 -3.183 345 146           0.000 000 071            
+muon-proton mass ratio                                      0.112 609 5262           0.000 000 0025           
+muon-tau mass ratio                                         5.946 35 e-2             0.000 40 e-2             
+natural unit of action                                      1.054 571 817... e-34    (exact)                  J s
+natural unit of action in eV s                              6.582 119 569... e-16    (exact)                  eV s
+natural unit of energy                                      8.187 105 7880 e-14      0.000 000 0026 e-14      J
+natural unit of energy in MeV                               0.510 998 950 69         0.000 000 000 16         MeV
+natural unit of length                                      3.861 592 6744 e-13      0.000 000 0012 e-13      m
+natural unit of mass                                        9.109 383 7139 e-31      0.000 000 0028 e-31      kg
+natural unit of momentum                                    2.730 924 534 46 e-22    0.000 000 000 85 e-22    kg m s^-1
+natural unit of momentum in MeV/c                           0.510 998 950 69         0.000 000 000 16         MeV/c
+natural unit of time                                        1.288 088 666 44 e-21    0.000 000 000 40 e-21    s
+natural unit of velocity                                    299 792 458              (exact)                  m s^-1
+neutron Compton wavelength                                  1.319 590 903 82 e-15    0.000 000 000 67 e-15    m
+neutron-electron mag. mom. ratio                            1.040 668 84 e-3         0.000 000 24 e-3         
+neutron-electron mass ratio                                 1838.683 662 00          0.000 000 74             
+neutron g factor                                            -3.826 085 52            0.000 000 90             
+neutron gyromag. ratio                                      1.832 471 74 e8          0.000 000 43 e8          s^-1 T^-1
+neutron gyromag. ratio in MHz/T                             29.164 6935              0.000 0069               MHz T^-1
+neutron mag. mom.                                           -9.662 3653 e-27         0.000 0023 e-27          J T^-1
+neutron mag. mom. to Bohr magneton ratio                    -1.041 875 65 e-3        0.000 000 25 e-3         
+neutron mag. mom. to nuclear magneton ratio                 -1.913 042 76            0.000 000 45             
+neutron mass                                                1.674 927 500 56 e-27    0.000 000 000 85 e-27    kg
+neutron mass energy equivalent                              1.505 349 765 14 e-10    0.000 000 000 76 e-10    J
+neutron mass energy equivalent in MeV                       939.565 421 94           0.000 000 48             MeV
+neutron mass in u                                           1.008 664 916 06         0.000 000 000 40         u
+neutron molar mass                                          1.008 664 917 12 e-3     0.000 000 000 51 e-3     kg mol^-1
+neutron-muon mass ratio                                     8.892 484 08             0.000 000 20             
+neutron-proton mag. mom. ratio                              -0.684 979 35            0.000 000 16             
+neutron-proton mass difference                              2.305 574 61 e-30        0.000 000 67 e-30        kg
+neutron-proton mass difference energy equivalent            2.072 147 12 e-13        0.000 000 60 e-13        J
+neutron-proton mass difference energy equivalent in MeV     1.293 332 51             0.000 000 38             MeV
+neutron-proton mass difference in u                         1.388 449 48 e-3         0.000 000 40 e-3         u
+neutron-proton mass ratio                                   1.001 378 419 46         0.000 000 000 40         
+neutron relative atomic mass                                1.008 664 916 06         0.000 000 000 40         
+neutron-tau mass ratio                                      0.528 779                0.000 036                
+neutron to shielded proton mag. mom. ratio                  -0.684 996 94            0.000 000 16             
+Newtonian constant of gravitation                           6.674 30 e-11            0.000 15 e-11            m^3 kg^-1 s^-2
+Newtonian constant of gravitation over h-bar c              6.708 83 e-39            0.000 15 e-39            (GeV/c^2)^-2
+nuclear magneton                                            5.050 783 7393 e-27      0.000 000 0016 e-27      J T^-1
+nuclear magneton in eV/T                                    3.152 451 254 17 e-8     0.000 000 000 98 e-8     eV T^-1
+nuclear magneton in inverse meter per tesla                 2.542 623 410 09 e-2     0.000 000 000 79 e-2     m^-1 T^-1
+nuclear magneton in K/T                                     3.658 267 7706 e-4       0.000 000 0011 e-4       K T^-1
+nuclear magneton in MHz/T                                   7.622 593 2188           0.000 000 0024           MHz T^-1
+Planck constant                                             6.626 070 15 e-34        (exact)                  J Hz^-1
+Planck constant in eV/Hz                                    4.135 667 696... e-15    (exact)                  eV Hz^-1
+Planck length                                               1.616 255 e-35           0.000 018 e-35           m
+Planck mass                                                 2.176 434 e-8            0.000 024 e-8            kg
+Planck mass energy equivalent in GeV                        1.220 890 e19            0.000 014 e19            GeV
+Planck temperature                                          1.416 784 e32            0.000 016 e32            K
+Planck time                                                 5.391 247 e-44           0.000 060 e-44           s
+proton charge to mass quotient                              9.578 833 1430 e7        0.000 000 0030 e7        C kg^-1
+proton Compton wavelength                                   1.321 409 853 60 e-15    0.000 000 000 41 e-15    m
+proton-electron mass ratio                                  1836.152 673 426         0.000 000 032            
+proton g factor                                             5.585 694 6893           0.000 000 0016           
+proton gyromag. ratio                                       2.675 221 8708 e8        0.000 000 0011 e8        s^-1 T^-1
+proton gyromag. ratio in MHz/T                              42.577 478 461           0.000 000 018            MHz T^-1
+proton mag. mom.                                            1.410 606 795 45 e-26    0.000 000 000 60 e-26    J T^-1
+proton mag. mom. to Bohr magneton ratio                     1.521 032 202 30 e-3     0.000 000 000 45 e-3     
+proton mag. mom. to nuclear magneton ratio                  2.792 847 344 63         0.000 000 000 82         
+proton mag. shielding correction                            2.567 15 e-5             0.000 41 e-5             
+proton mass                                                 1.672 621 925 95 e-27    0.000 000 000 52 e-27    kg
+proton mass energy equivalent                               1.503 277 618 02 e-10    0.000 000 000 47 e-10    J
+proton mass energy equivalent in MeV                        938.272 089 43           0.000 000 29             MeV
+proton mass in u                                            1.007 276 466 5789       0.000 000 000 0083       u
+proton molar mass                                           1.007 276 467 64 e-3     0.000 000 000 31 e-3     kg mol^-1
+proton-muon mass ratio                                      8.880 243 38             0.000 000 20             
+proton-neutron mag. mom. ratio                              -1.459 898 02            0.000 000 34             
+proton-neutron mass ratio                                   0.998 623 477 97         0.000 000 000 40         
+proton relative atomic mass                                 1.007 276 466 5789       0.000 000 000 0083       
+proton rms charge radius                                    8.4075 e-16              0.0064 e-16              m
+proton-tau mass ratio                                       0.528 051                0.000 036                
+quantum of circulation                                      3.636 947 5467 e-4       0.000 000 0011 e-4       m^2 s^-1
+quantum of circulation times 2                              7.273 895 0934 e-4       0.000 000 0023 e-4       m^2 s^-1
+reduced Compton wavelength                                  3.861 592 6744 e-13      0.000 000 0012 e-13      m
+reduced muon Compton wavelength                             1.867 594 306 e-15       0.000 000 042 e-15       m
+reduced neutron Compton wavelength                          2.100 194 1520 e-16      0.000 000 0011 e-16      m
+reduced Planck constant                                     1.054 571 817... e-34    (exact)                  J s
+reduced Planck constant in eV s                             6.582 119 569... e-16    (exact)                  eV s
+reduced Planck constant times c in MeV fm                   197.326 980 4...         (exact)                  MeV fm
+reduced proton Compton wavelength                           2.103 089 100 51 e-16    0.000 000 000 66 e-16    m
+reduced tau Compton wavelength                              1.110 538 e-16           0.000 075 e-16           m
+Rydberg constant                                            10 973 731.568 157       0.000 012                m^-1
+Rydberg constant times c in Hz                              3.289 841 960 2500 e15   0.000 000 000 0036 e15   Hz
+Rydberg constant times hc in eV                             13.605 693 122 990       0.000 000 000 015        eV
+Rydberg constant times hc in J                              2.179 872 361 1030 e-18  0.000 000 000 0024 e-18  J
+Sackur-Tetrode constant (1 K, 100 kPa)                      -1.151 707 534 96        0.000 000 000 47         
+Sackur-Tetrode constant (1 K, 101.325 kPa)                  -1.164 870 521 49        0.000 000 000 47         
+second radiation constant                                   1.438 776 877... e-2     (exact)                  m K
+shielded helion gyromag. ratio                              2.037 894 6078 e8        0.000 000 0018 e8        s^-1 T^-1
+shielded helion gyromag. ratio in MHz/T                     32.434 100 033           0.000 000 028            MHz T^-1
+shielded helion mag. mom.                                   -1.074 553 110 35 e-26   0.000 000 000 93 e-26    J T^-1
+shielded helion mag. mom. to Bohr magneton ratio            -1.158 671 494 57 e-3    0.000 000 000 94 e-3     
+shielded helion mag. mom. to nuclear magneton ratio         -2.127 497 7624          0.000 000 0017           
+shielded helion to proton mag. mom. ratio                   -0.761 766 577 21        0.000 000 000 66         
+shielded helion to shielded proton mag. mom. ratio          -0.761 786 1334          0.000 000 0031           
+shielded proton gyromag. ratio                              2.675 153 194 e8         0.000 000 011 e8         s^-1 T^-1
+shielded proton gyromag. ratio in MHz/T                     42.576 385 43            0.000 000 17             MHz T^-1
+shielded proton mag. mom.                                   1.410 570 5830 e-26      0.000 000 0058 e-26      J T^-1
+shielded proton mag. mom. to Bohr magneton ratio            1.520 993 1551 e-3       0.000 000 0062 e-3       
+shielded proton mag. mom. to nuclear magneton ratio         2.792 775 648            0.000 000 011            
+shielding difference of d and p in HD                       1.987 70 e-8             0.000 10 e-8             
+shielding difference of t and p in HT                       2.394 50 e-8             0.000 20 e-8             
+speed of light in vacuum                                    299 792 458              (exact)                  m s^-1
+standard acceleration of gravity                            9.806 65                 (exact)                  m s^-2
+standard atmosphere                                         101 325                  (exact)                  Pa
+standard-state pressure                                     100 000                  (exact)                  Pa
+Stefan-Boltzmann constant                                   5.670 374 419... e-8     (exact)                  W m^-2 K^-4
+tau Compton wavelength                                      6.977 71 e-16            0.000 47 e-16            m
+tau-electron mass ratio                                     3477.23                  0.23                     
+tau energy equivalent                                       1776.86                  0.12                     MeV
+tau mass                                                    3.167 54 e-27            0.000 21 e-27            kg
+tau mass energy equivalent                                  2.846 84 e-10            0.000 19 e-10            J
+tau mass in u                                               1.907 54                 0.000 13                 u
+tau molar mass                                              1.907 54 e-3             0.000 13 e-3             kg mol^-1
+tau-muon mass ratio                                         16.8170                  0.0011                   
+tau-neutron mass ratio                                      1.891 15                 0.000 13                 
+tau-proton mass ratio                                       1.893 76                 0.000 13                 
+Thomson cross section                                       6.652 458 7051 e-29      0.000 000 0062 e-29      m^2
+triton-electron mass ratio                                  5496.921 535 51          0.000 000 21             
+triton g factor                                             5.957 924 930            0.000 000 012            
+triton mag. mom.                                            1.504 609 5178 e-26      0.000 000 0030 e-26      J T^-1
+triton mag. mom. to Bohr magneton ratio                     1.622 393 6648 e-3       0.000 000 0032 e-3       
+triton mag. mom. to nuclear magneton ratio                  2.978 962 4650           0.000 000 0059           
+triton mass                                                 5.007 356 7512 e-27      0.000 000 0016 e-27      kg
+triton mass energy equivalent                               4.500 387 8119 e-10      0.000 000 0014 e-10      J
+triton mass energy equivalent in MeV                        2808.921 136 68          0.000 000 88             MeV
+triton mass in u                                            3.015 500 715 97         0.000 000 000 10         u
+triton molar mass                                           3.015 500 719 13 e-3     0.000 000 000 94 e-3     kg mol^-1
+triton-proton mass ratio                                    2.993 717 034 03         0.000 000 000 10         
+triton relative atomic mass                                 3.015 500 715 97         0.000 000 000 10         
+triton to proton mag. mom. ratio                            1.066 639 9189           0.000 000 0021           
+unified atomic mass unit                                    1.660 539 068 92 e-27    0.000 000 000 52 e-27    kg
+vacuum electric permittivity                                8.854 187 8188 e-12      0.000 000 0014 e-12      F m^-1
+vacuum mag. permeability                                    1.256 637 061 27 e-6     0.000 000 000 20 e-6     N A^-2
+von Klitzing constant                                       25 812.807 45...         (exact)                  ohm
+weak mixing angle                                           0.223 05                 0.000 23                 
+Wien frequency displacement law constant                    5.878 925 757... e10     (exact)                  Hz K^-1
+Wien wavelength displacement law constant                   2.897 771 955... e-3     (exact)                  m K
+W to Z mass ratio                                           0.881 45                 0.000 13                    """
+
+
+exact2022 = exact2018
+
+
+# -----------------------------------------------------------------------------
+
+
+def parse_constants_2002to2014(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:55].rstrip()
+        val = float(line[55:77].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[55:77]
+        is_exact = '(exact)' in line[77:99]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[77:99].replace(' ', '').replace('(exact)', '0'))
+        units = line[99:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def parse_constants_2018toXXXX(
+    d: str, exact_func: Callable[[Any], Any]
+) -> dict[str, tuple[float, str, float]]:
+    constants: dict[str, tuple[float, str, float]] = {}
+    exact: dict[str, float] = {}
+    need_replace = set()
+    for line in d.split('\n'):
+        name = line[:60].rstrip()
+        val = float(line[60:85].replace(' ', '').replace('...', ''))
+        is_truncated = '...' in line[60:85]
+        is_exact = '(exact)' in line[85:110]
+        if is_truncated and is_exact:
+            # missing decimals, use computed exact value
+            need_replace.add(name)
+        elif is_exact:
+            exact[name] = val
+        else:
+            assert not is_truncated
+        uncert = float(line[85:110].replace(' ', '').replace('(exact)', '0'))
+        units = line[110:].rstrip()
+        constants[name] = (val, units, uncert)
+    replace = exact_func(exact)
+    replace_exact(constants, need_replace, replace)
+    return constants
+
+
+def replace_exact(d, to_replace, exact):
+    for name in to_replace:
+        assert name in exact, f'Missing exact value: {name}'
+        assert abs(exact[name]/d[name][0] - 1) <= 1e-9, \
+            f'Bad exact value: {name}: { exact[name]}, {d[name][0]}'
+        d[name] = (exact[name],) + d[name][1:]
+    assert set(exact.keys()) == set(to_replace)
+
+
+_physical_constants_2002 = parse_constants_2002to2014(txt2002, exact2002)
+_physical_constants_2006 = parse_constants_2002to2014(txt2006, exact2006)
+_physical_constants_2010 = parse_constants_2002to2014(txt2010, exact2010)
+_physical_constants_2014 = parse_constants_2002to2014(txt2014, exact2014)
+_physical_constants_2018 = parse_constants_2018toXXXX(txt2018, exact2018)
+_physical_constants_2022 = parse_constants_2018toXXXX(txt2022, exact2022)
+
+physical_constants: dict[str, tuple[float, str, float]] = {}
+physical_constants.update(_physical_constants_2002)
+physical_constants.update(_physical_constants_2006)
+physical_constants.update(_physical_constants_2010)
+physical_constants.update(_physical_constants_2014)
+physical_constants.update(_physical_constants_2018)
+physical_constants.update(_physical_constants_2022)
+_current_constants = _physical_constants_2022
+_current_codata = "CODATA 2022"
+
+# check obsolete values
+_obsolete_constants = {}
+for k in physical_constants:
+    if k not in _current_constants:
+        _obsolete_constants[k] = True
+
+# generate some additional aliases
+_aliases = {}
+for k in _physical_constants_2002:
+    if 'magn.' in k:
+        _aliases[k] = k.replace('magn.', 'mag.')
+for k in _physical_constants_2006:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2018:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')
+for k in _physical_constants_2022:
+    if 'momentum' in k:
+        _aliases[k] = k.replace('momentum', 'mom.um')        
+
+# CODATA 2018 and 2022: renamed and no longer exact; use as aliases
+_aliases['mag. constant'] = 'vacuum mag. permeability'
+_aliases['electric constant'] = 'vacuum electric permittivity'
+
+
+_extra_alias_keys = ['natural unit of velocity',
+                     'natural unit of action',
+                     'natural unit of action in eV s',
+                     'natural unit of mass',
+                     'natural unit of energy',
+                     'natural unit of energy in MeV',
+                     'natural unit of mom.um',
+                     'natural unit of mom.um in MeV/c',
+                     'natural unit of length',
+                     'natural unit of time']
+
+# finally, insert aliases for values
+for k, v in list(_aliases.items()):
+    if v in _current_constants or v in _extra_alias_keys:
+        physical_constants[k] = physical_constants[v]
+    else:
+        del _aliases[k]
+
+
+class ConstantWarning(DeprecationWarning):
+    """Accessing a constant no longer in current CODATA data set"""
+    pass
+
+
+def _check_obsolete(key: str) -> None:
+    if key in _obsolete_constants and key not in _aliases:
+        warnings.warn(f"Constant '{key}' is not in current {_current_codata} data set",
+                      ConstantWarning, stacklevel=3)
+
+
+def value(key: str) -> float:
+    """
+    Value in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    value : float
+        Value in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.value('elementary charge')
+    1.602176634e-19
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][0]
+
+
+def unit(key: str) -> str:
+    """
+    Unit in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    unit : Python string
+        Unit in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.unit('proton mass')
+    'kg'
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][1]
+
+
+def precision(key: str) -> float:
+    """
+    Relative precision in physical_constants indexed by key
+
+    Parameters
+    ----------
+    key : Python string
+        Key in dictionary `physical_constants`
+
+    Returns
+    -------
+    prec : float
+        Relative precision in `physical_constants` corresponding to `key`
+
+    Examples
+    --------
+    >>> from scipy import constants
+    >>> constants.precision('proton mass')
+    5.1e-37
+
+    """
+    _check_obsolete(key)
+    return physical_constants[key][2] / physical_constants[key][0]
+
+
+def find(sub: str | None = None, disp: bool = False) -> Any:
+    """
+    Return list of physical_constant keys containing a given string.
+
+    Parameters
+    ----------
+    sub : str
+        Sub-string to search keys for. By default, return all keys.
+    disp : bool
+        If True, print the keys that are found and return None.
+        Otherwise, return the list of keys without printing anything.
+
+    Returns
+    -------
+    keys : list or None
+        If `disp` is False, the list of keys is returned.
+        Otherwise, None is returned.
+
+    Examples
+    --------
+    >>> from scipy.constants import find, physical_constants
+
+    Which keys in the ``physical_constants`` dictionary contain 'boltzmann'?
+
+    >>> find('boltzmann')
+    ['Boltzmann constant',
+     'Boltzmann constant in Hz/K',
+     'Boltzmann constant in eV/K',
+     'Boltzmann constant in inverse meter per kelvin',
+     'Stefan-Boltzmann constant']
+
+    Get the constant called 'Boltzmann constant in Hz/K':
+
+    >>> physical_constants['Boltzmann constant in Hz/K']
+    (20836619120.0, 'Hz K^-1', 0.0)
+
+    Find constants with 'radius' in the key:
+
+    >>> find('radius')
+    ['Bohr radius',
+     'alpha particle rms charge radius',
+     'classical electron radius',
+     'deuteron rms charge radius',
+     'proton rms charge radius']
+    >>> physical_constants['classical electron radius']
+    (2.8179403262e-15, 'm', 1.3e-24)
+
+    """
+    if sub is None:
+        result = list(_current_constants.keys())
+    else:
+        result = [key for key in _current_constants
+                  if sub.lower() in key.lower()]
+
+    result.sort()
+    if disp:
+        for key in result:
+            print(key)
+        return
+    else:
+        return result
+
+# This is not used here, but it must be defined to pass
+# scipy/_lib/tests/test_public_api.py::test_private_but_present_deprecation
+c = value('speed of light in vacuum')
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/_constants.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3a098d5469bb7195202a638022b1120ec0969bd
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/_constants.py
@@ -0,0 +1,366 @@
+"""
+Collection of physical constants and conversion factors.
+
+Most constants are in SI units, so you can do
+print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots'
+
+The list is not meant to be comprehensive, but just convenient for everyday use.
+"""
+
+import math as _math
+from typing import TYPE_CHECKING, Any
+
+from ._codata import value as _cd
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+from scipy._lib._array_api import array_namespace, _asarray
+
+
+"""
+BasSw 2006
+physical constants: imported from CODATA
+unit conversion: see e.g., NIST special publication 811
+Use at own risk: double-check values before calculating your Mars orbit-insertion burn.
+Some constants exist in a few variants, which are marked with suffixes.
+The ones without any suffix should be the most common ones.
+"""
+
+__all__ = [
+    'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
+    'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
+    'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
+    'angstrom', 'arcmin', 'arcminute', 'arcsec',
+    'arcsecond', 'astronomical_unit', 'atm',
+    'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
+    'barrel', 'bbl', 'blob', 'c', 'calorie',
+    'calorie_IT', 'calorie_th', 'carat', 'centi',
+    'convert_temperature', 'day', 'deci', 'degree',
+    'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
+    'eV', 'electron_mass', 'electron_volt',
+    'elementary_charge', 'epsilon_0', 'erg',
+    'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
+    'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
+    'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
+    'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
+    'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
+    'hectare', 'hecto', 'horsepower', 'hour', 'hp',
+    'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
+    'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
+    'light_year', 'liter', 'litre', 'long_ton', 'm_e',
+    'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
+    'metric_ton', 'micro', 'micron', 'mil', 'mile',
+    'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
+    'nautical_mile', 'neutron_mass', 'nu2lambda',
+    'ounce', 'oz', 'parsec', 'pebi', 'peta',
+    'pi', 'pico', 'point', 'pound', 'pound_force',
+    'proton_mass', 'psi', 'pt', 'quecto', 'quetta', 'ronna', 'ronto',
+    'short_ton', 'sigma', 'slinch', 'slug', 'speed_of_light',
+    'speed_of_sound', 'stone', 'survey_foot',
+    'survey_mile', 'tebi', 'tera', 'ton_TNT',
+    'torr', 'troy_ounce', 'troy_pound', 'u',
+    'week', 'yard', 'year', 'yobi', 'yocto',
+    'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
+]
+
+
+# mathematical constants
+pi = _math.pi
+golden = golden_ratio = (1 + _math.sqrt(5)) / 2
+
+# SI prefixes
+quetta = 1e30
+ronna = 1e27
+yotta = 1e24
+zetta = 1e21
+exa = 1e18
+peta = 1e15
+tera = 1e12
+giga = 1e9
+mega = 1e6
+kilo = 1e3
+hecto = 1e2
+deka = 1e1
+deci = 1e-1
+centi = 1e-2
+milli = 1e-3
+micro = 1e-6
+nano = 1e-9
+pico = 1e-12
+femto = 1e-15
+atto = 1e-18
+zepto = 1e-21
+yocto = 1e-24
+ronto = 1e-27
+quecto = 1e-30
+
+# binary prefixes
+kibi = 2**10
+mebi = 2**20
+gibi = 2**30
+tebi = 2**40
+pebi = 2**50
+exbi = 2**60
+zebi = 2**70
+yobi = 2**80
+
+# physical constants
+c = speed_of_light = _cd('speed of light in vacuum')
+mu_0 = _cd('vacuum mag. permeability')
+epsilon_0 = _cd('vacuum electric permittivity')
+h = Planck = _cd('Planck constant')
+hbar = _cd('reduced Planck constant')
+G = gravitational_constant = _cd('Newtonian constant of gravitation')
+g = _cd('standard acceleration of gravity')
+e = elementary_charge = _cd('elementary charge')
+R = gas_constant = _cd('molar gas constant')
+alpha = fine_structure = _cd('fine-structure constant')
+N_A = Avogadro = _cd('Avogadro constant')
+k = Boltzmann = _cd('Boltzmann constant')
+sigma = Stefan_Boltzmann = _cd('Stefan-Boltzmann constant')
+Wien = _cd('Wien wavelength displacement law constant')
+Rydberg = _cd('Rydberg constant')
+
+# mass in kg
+gram = 1e-3
+metric_ton = 1e3
+grain = 64.79891e-6
+lb = pound = 7000 * grain  # avoirdupois
+blob = slinch = pound * g / 0.0254  # lbf*s**2/in (added in 1.0.0)
+slug = blob / 12  # lbf*s**2/foot (added in 1.0.0)
+oz = ounce = pound / 16
+stone = 14 * pound
+long_ton = 2240 * pound
+short_ton = 2000 * pound
+
+troy_ounce = 480 * grain  # only for metals / gems
+troy_pound = 12 * troy_ounce
+carat = 200e-6
+
+m_e = electron_mass = _cd('electron mass')
+m_p = proton_mass = _cd('proton mass')
+m_n = neutron_mass = _cd('neutron mass')
+m_u = u = atomic_mass = _cd('atomic mass constant')
+
+# angle in rad
+degree = pi / 180
+arcmin = arcminute = degree / 60
+arcsec = arcsecond = arcmin / 60
+
+# time in second
+minute = 60.0
+hour = 60 * minute
+day = 24 * hour
+week = 7 * day
+year = 365 * day
+Julian_year = 365.25 * day
+
+# length in meter
+inch = 0.0254
+foot = 12 * inch
+yard = 3 * foot
+mile = 1760 * yard
+mil = inch / 1000
+pt = point = inch / 72  # typography
+survey_foot = 1200.0 / 3937
+survey_mile = 5280 * survey_foot
+nautical_mile = 1852.0
+fermi = 1e-15
+angstrom = 1e-10
+micron = 1e-6
+au = astronomical_unit = 149597870700.0
+light_year = Julian_year * c
+parsec = au / arcsec
+
+# pressure in pascal
+atm = atmosphere = _cd('standard atmosphere')
+bar = 1e5
+torr = mmHg = atm / 760
+psi = pound * g / (inch * inch)
+
+# area in meter**2
+hectare = 1e4
+acre = 43560 * foot**2
+
+# volume in meter**3
+litre = liter = 1e-3
+gallon = gallon_US = 231 * inch**3  # US
+# pint = gallon_US / 8
+fluid_ounce = fluid_ounce_US = gallon_US / 128
+bbl = barrel = 42 * gallon_US  # for oil
+
+gallon_imp = 4.54609e-3  # UK
+fluid_ounce_imp = gallon_imp / 160
+
+# speed in meter per second
+kmh = 1e3 / hour
+mph = mile / hour
+# approx value of mach at 15 degrees in 1 atm. Is this a common value?
+mach = speed_of_sound = 340.5
+knot = nautical_mile / hour
+
+# temperature in kelvin
+zero_Celsius = 273.15
+degree_Fahrenheit = 1/1.8  # only for differences
+
+# energy in joule
+eV = electron_volt = elementary_charge  # * 1 Volt
+calorie = calorie_th = 4.184
+calorie_IT = 4.1868
+erg = 1e-7
+Btu_th = pound * degree_Fahrenheit * calorie_th / gram
+Btu = Btu_IT = pound * degree_Fahrenheit * calorie_IT / gram
+ton_TNT = 1e9 * calorie_th
+# Wh = watt_hour
+
+# power in watt
+hp = horsepower = 550 * foot * pound * g
+
+# force in newton
+dyn = dyne = 1e-5
+lbf = pound_force = pound * g
+kgf = kilogram_force = g  # * 1 kg
+
+# functions for conversions that are not linear
+
+
+def convert_temperature(
+    val: "npt.ArrayLike",
+    old_scale: str,
+    new_scale: str,
+) -> Any:
+    """
+    Convert from a temperature scale to another one among Celsius, Kelvin,
+    Fahrenheit, and Rankine scales.
+
+    Parameters
+    ----------
+    val : array_like
+        Value(s) of the temperature(s) to be converted expressed in the
+        original scale.
+    old_scale : str
+        Specifies as a string the original scale from which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+    new_scale : str
+        Specifies as a string the new scale to which the temperature
+        value(s) will be converted. Supported scales are Celsius ('Celsius',
+        'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
+        Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
+        ('Rankine', 'rankine', 'R', 'r').
+
+    Returns
+    -------
+    res : float or array of floats
+        Value(s) of the converted temperature(s) expressed in the new scale.
+
+    Notes
+    -----
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    >>> from scipy.constants import convert_temperature
+    >>> import numpy as np
+    >>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin')
+    array([ 233.15,  313.15])
+
+    """
+    xp = array_namespace(val)
+    _val = _asarray(val, xp=xp, subok=True)
+    # Convert from `old_scale` to Kelvin
+    if old_scale.lower() in ['celsius', 'c']:
+        tempo = _val + zero_Celsius
+    elif old_scale.lower() in ['kelvin', 'k']:
+        tempo = _val
+    elif old_scale.lower() in ['fahrenheit', 'f']:
+        tempo = (_val - 32) * 5 / 9 + zero_Celsius
+    elif old_scale.lower() in ['rankine', 'r']:
+        tempo = _val * 5 / 9
+    else:
+        raise NotImplementedError(f"{old_scale=} is unsupported: supported scales "
+                                   "are Celsius, Kelvin, Fahrenheit, and "
+                                   "Rankine")
+    # and from Kelvin to `new_scale`.
+    if new_scale.lower() in ['celsius', 'c']:
+        res = tempo - zero_Celsius
+    elif new_scale.lower() in ['kelvin', 'k']:
+        res = tempo
+    elif new_scale.lower() in ['fahrenheit', 'f']:
+        res = (tempo - zero_Celsius) * 9 / 5 + 32
+    elif new_scale.lower() in ['rankine', 'r']:
+        res = tempo * 9 / 5
+    else:
+        raise NotImplementedError(f"{new_scale=} is unsupported: supported "
+                                   "scales are 'Celsius', 'Kelvin', "
+                                   "'Fahrenheit', and 'Rankine'")
+
+    return res
+
+
+# optics
+
+
+def lambda2nu(lambda_: "npt.ArrayLike") -> Any:
+    """
+    Convert wavelength to optical frequency
+
+    Parameters
+    ----------
+    lambda_ : array_like
+        Wavelength(s) to be converted.
+
+    Returns
+    -------
+    nu : float or array of floats
+        Equivalent optical frequency.
+
+    Notes
+    -----
+    Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import lambda2nu, speed_of_light
+    >>> import numpy as np
+    >>> lambda2nu(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(lambda_)
+    return c / _asarray(lambda_, xp=xp, subok=True)
+
+
+def nu2lambda(nu: "npt.ArrayLike") -> Any:
+    """
+    Convert optical frequency to wavelength.
+
+    Parameters
+    ----------
+    nu : array_like
+        Optical frequency to be converted.
+
+    Returns
+    -------
+    lambda : float or array of floats
+        Equivalent wavelength(s).
+
+    Notes
+    -----
+    Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the
+    (vacuum) speed of light in meters/second.
+
+    Examples
+    --------
+    >>> from scipy.constants import nu2lambda, speed_of_light
+    >>> import numpy as np
+    >>> nu2lambda(np.array((1, speed_of_light)))
+    array([  2.99792458e+08,   1.00000000e+00])
+
+    """
+    xp = array_namespace(nu)
+    return c / _asarray(nu, xp=xp, subok=True)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/codata.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..912e0bbf7c4f14d23ced4546b6704f7789996d97
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/codata.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.constants` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'physical_constants', 'value', 'unit', 'precision', 'find',
+    'ConstantWarning', 'k', 'c',
+
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="constants", module="codata",
+                                   private_modules=["_codata"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/constants.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..855901ba802881090b99b7e8972de741331c7ab9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/constants.py
@@ -0,0 +1,53 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.constants` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
+    'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
+    'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
+    'angstrom', 'arcmin', 'arcminute', 'arcsec',
+    'arcsecond', 'astronomical_unit', 'atm',
+    'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
+    'barrel', 'bbl', 'blob', 'c', 'calorie',
+    'calorie_IT', 'calorie_th', 'carat', 'centi',
+    'convert_temperature', 'day', 'deci', 'degree',
+    'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
+    'eV', 'electron_mass', 'electron_volt',
+    'elementary_charge', 'epsilon_0', 'erg',
+    'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
+    'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
+    'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
+    'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
+    'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
+    'hectare', 'hecto', 'horsepower', 'hour', 'hp',
+    'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
+    'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
+    'light_year', 'liter', 'litre', 'long_ton', 'm_e',
+    'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
+    'metric_ton', 'micro', 'micron', 'mil', 'mile',
+    'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
+    'nautical_mile', 'neutron_mass', 'nu2lambda',
+    'ounce', 'oz', 'parsec', 'pebi', 'peta',
+    'pi', 'pico', 'point', 'pound', 'pound_force',
+    'proton_mass', 'psi', 'pt', 'short_ton',
+    'sigma', 'slinch', 'slug', 'speed_of_light',
+    'speed_of_sound', 'stone', 'survey_foot',
+    'survey_mile', 'tebi', 'tera', 'ton_TNT',
+    'torr', 'troy_ounce', 'troy_pound', 'u',
+    'week', 'yard', 'year', 'yobi', 'yocto',
+    'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="constants", module="constants",
+                                   private_modules=["_constants"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..51b77c491344963c648fef90cdeaa5adac5d9a6f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_codata.py
@@ -0,0 +1,78 @@
+from scipy.constants import find, value, c, speed_of_light, precision
+from numpy.testing import assert_equal, assert_, assert_almost_equal
+import scipy.constants._codata as _cd
+from scipy import constants
+
+
+def test_find():
+    keys = find('weak mixing', disp=False)
+    assert_equal(keys, ['weak mixing angle'])
+
+    keys = find('qwertyuiop', disp=False)
+    assert_equal(keys, [])
+
+    keys = find('natural unit', disp=False)
+    assert_equal(keys, sorted(['natural unit of velocity',
+                                'natural unit of action',
+                                'natural unit of action in eV s',
+                                'natural unit of mass',
+                                'natural unit of energy',
+                                'natural unit of energy in MeV',
+                                'natural unit of momentum',
+                                'natural unit of momentum in MeV/c',
+                                'natural unit of length',
+                                'natural unit of time']))
+
+
+def test_basic_table_parse():
+    c_s = 'speed of light in vacuum'
+    assert_equal(value(c_s), c)
+    assert_equal(value(c_s), speed_of_light)
+
+
+def test_basic_lookup():
+    assert_equal('%d %s' % (_cd.value('speed of light in vacuum'),
+                            _cd.unit('speed of light in vacuum')),
+                 '299792458 m s^-1')
+
+
+def test_find_all():
+    assert_(len(find(disp=False)) > 300)
+
+
+def test_find_single():
+    assert_equal(find('Wien freq', disp=False)[0],
+                 'Wien frequency displacement law constant')
+
+
+def test_2002_vs_2006():
+    assert_almost_equal(value('magn. flux quantum'),
+                        value('mag. flux quantum'))
+
+
+def test_exact_values():
+    # Check that updating stored values with exact ones worked.
+    exact = dict((k, v[0]) for k, v in _cd._physical_constants_2018.items())
+    replace = _cd.exact2018(exact)
+    for key, val in replace.items():
+        assert_equal(val, value(key))
+        assert precision(key) == 0
+
+
+def test_gh11341():
+    # gh-11341 noted that these three constants should exist (for backward
+    # compatibility) and should always have the same value:
+    a = constants.epsilon_0
+    b = constants.physical_constants['electric constant'][0]
+    c = constants.physical_constants['vacuum electric permittivity'][0]
+    assert a == b == c
+
+
+def test_gh14467():
+    # gh-14467 noted that some physical constants in CODATA are rounded
+    # to only ten significant figures even though they are supposed to be
+    # exact. Check that (at least) the case mentioned in the issue is resolved.
+    res = constants.physical_constants['Boltzmann constant in eV/K'][0]
+    ref = (constants.physical_constants['Boltzmann constant'][0]
+           / constants.physical_constants['elementary charge'][0])
+    assert res == ref
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b9dcd3b5355063cffb3b7a144937a95aab77955
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/constants/tests/test_constants.py
@@ -0,0 +1,90 @@
+import pytest
+
+import scipy.constants as sc
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close
+from numpy.testing import assert_allclose
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+class TestConvertTemperature:
+    def test_convert_temperature(self, xp):
+        xp_assert_equal(sc.convert_temperature(xp.asarray(32.), 'f', 'Celsius'),
+                        xp.asarray(0.0))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]),
+                                               'celsius', 'Kelvin'),
+                        xp.asarray([273.15, 273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'kelvin', 'c'),
+                        xp.asarray([-273.15, -273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([32., 32.]), 'f', 'k'),
+                        xp.asarray([273.15, 273.15]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([273.15, 273.15]),
+                                               'kelvin', 'F'),
+                        xp.asarray([32., 32.]))
+        xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'C', 'fahrenheit'),
+                        xp.asarray([32., 32.]))
+        xp_assert_close(sc.convert_temperature(xp.asarray([0., 0.], dtype=xp.float64),
+                                               'c', 'r'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+                                                        dtype=xp.float64),
+                                               'Rankine', 'C'),
+                        xp.asarray([0., 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+                                                        dtype=xp.float64),
+                                               'r', 'F'),
+                        xp.asarray([32., 32.], dtype=xp.float64), rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([32., 32.], dtype=xp.float64),
+                                               'fahrenheit', 'R'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([273.15, 273.15],
+                                                        dtype=xp.float64),
+                                               'K', 'R'),
+                        xp.asarray([491.67, 491.67], dtype=xp.float64),
+                        rtol=0., atol=1e-13)
+        xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 0.],
+                                                          dtype=xp.float64),
+                                               'rankine', 'kelvin'),
+                        xp.asarray([273.15, 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_convert_temperature_array_like(self):
+        assert_allclose(sc.convert_temperature([491.67, 0.], 'rankine', 'kelvin'),
+                        [273.15, 0.], rtol=0., atol=1e-13)
+
+
+    @skip_xp_backends(np_only=True, reason='Python int input uses NumPy backend')
+    def test_convert_temperature_errors(self, xp):
+        with pytest.raises(NotImplementedError, match="old_scale="):
+            sc.convert_temperature(1, old_scale="cheddar", new_scale="kelvin")
+        with pytest.raises(NotImplementedError, match="new_scale="):
+            sc.convert_temperature(1, old_scale="kelvin", new_scale="brie")
+
+
+class TestLambdaToNu:
+    def test_lambda_to_nu(self, xp):
+        xp_assert_equal(sc.lambda2nu(xp.asarray([sc.speed_of_light, 1])),
+                        xp.asarray([1, sc.speed_of_light]))
+
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_lambda_to_nu_array_like(self, xp):
+        assert_allclose(sc.lambda2nu([sc.speed_of_light, 1]),
+                        [1, sc.speed_of_light])
+
+
+class TestNuToLambda:
+    def test_nu_to_lambda(self, xp):
+        xp_assert_equal(sc.nu2lambda(xp.asarray([sc.speed_of_light, 1])),
+                        xp.asarray([1, sc.speed_of_light]))
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_nu_to_lambda_array_like(self, xp):
+        assert_allclose(sc.nu2lambda([sc.speed_of_light, 1]),
+                        [1, sc.speed_of_light])
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdd4ffebec4c57f6d399a0f76df2b66056f0b225
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/__init__.py
@@ -0,0 +1,90 @@
+"""
+================================
+Datasets (:mod:`scipy.datasets`)
+================================
+
+.. currentmodule:: scipy.datasets
+
+Dataset Methods
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   ascent
+   face
+   electrocardiogram
+
+Utility Methods
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   download_all    -- Download all the dataset files to specified path.
+   clear_cache     -- Clear cached dataset directory.
+
+
+Usage of Datasets
+=================
+
+SciPy dataset methods can be simply called as follows: ``'()'``
+This downloads the dataset files over the network once, and saves the cache,
+before returning a `numpy.ndarray` object representing the dataset.
+
+Note that the return data structure and data type might be different for
+different dataset methods. For a more detailed example on usage, please look
+into the particular dataset method documentation above.
+
+
+How dataset retrieval and storage works
+=======================================
+
+SciPy dataset files are stored within individual GitHub repositories under the
+SciPy GitHub organization, following a naming convention as
+``'dataset-'``, for example `scipy.datasets.face` files live at
+https://github.com/scipy/dataset-face.  The `scipy.datasets` submodule utilizes
+and depends on `Pooch `_, a Python
+package built to simplify fetching data files. Pooch uses these repos to
+retrieve the respective dataset files when calling the dataset function.
+
+A registry of all the datasets, essentially a mapping of filenames with their
+SHA256 hash and repo urls are maintained, which Pooch uses to handle and verify
+the downloads on function call. After downloading the dataset once, the files
+are saved in the system cache directory under ``'scipy-data'``.
+
+Dataset cache locations may vary on different platforms.
+
+For macOS::
+
+    '~/Library/Caches/scipy-data'
+
+For Linux and other Unix-like platforms::
+
+    '~/.cache/scipy-data'  # or the value of the XDG_CACHE_HOME env var, if defined
+
+For Windows::
+
+    'C:\\Users\\\\AppData\\Local\\\\scipy-data\\Cache'
+
+
+In environments with constrained network connectivity for various security
+reasons or on systems without continuous internet connections, one may manually
+load the cache of the datasets by placing the contents of the dataset repo in
+the above mentioned cache directory to avoid fetching dataset errors without
+the internet connectivity.
+
+"""
+
+
+from ._fetchers import face, ascent, electrocardiogram
+from ._download_all import download_all
+from ._utils import clear_cache
+
+__all__ = ['ascent', 'electrocardiogram', 'face',
+           'download_all', 'clear_cache']
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py
new file mode 100644
index 0000000000000000000000000000000000000000..255fdcaf22950848f458a7ed9ada183e0a2e630e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_download_all.py
@@ -0,0 +1,57 @@
+"""
+Platform independent script to download all the
+`scipy.datasets` module data files.
+This doesn't require a full scipy build.
+
+Run: python _download_all.py 
+"""
+
+import argparse
+try:
+    import pooch
+except ImportError:
+    pooch = None
+
+
+if __package__ is None or __package__ == '':
+    # Running as python script, use absolute import
+    import _registry  # type: ignore
+else:
+    # Running as python module, use relative import
+    from . import _registry
+
+
+def download_all(path=None):
+    """
+    Utility method to download all the dataset files
+    for `scipy.datasets` module.
+
+    Parameters
+    ----------
+    path : str, optional
+        Directory path to download all the dataset files.
+        If None, default to the system cache_dir detected by pooch.
+    """
+    if pooch is None:
+        raise ImportError("Missing optional dependency 'pooch' required "
+                          "for scipy.datasets module. Please use pip or "
+                          "conda to install 'pooch'.")
+    if path is None:
+        path = pooch.os_cache('scipy-data')
+    for dataset_name, dataset_hash in _registry.registry.items():
+        pooch.retrieve(url=_registry.registry_urls[dataset_name],
+                       known_hash=dataset_hash,
+                       fname=dataset_name, path=path)
+
+
+def main():
+    parser = argparse.ArgumentParser(description='Download SciPy data files.')
+    parser.add_argument("path", nargs='?', type=str,
+                        default=pooch.os_cache('scipy-data'),
+                        help="Directory path to download all the data files.")
+    args = parser.parse_args()
+    download_all(args.path)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py
new file mode 100644
index 0000000000000000000000000000000000000000..57bb2fa6a12e753eb07a1f359ac04a29bd5c77e5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_fetchers.py
@@ -0,0 +1,219 @@
+from numpy import array, frombuffer, load
+from ._registry import registry, registry_urls
+
+try:
+    import pooch
+except ImportError:
+    pooch = None
+    data_fetcher = None
+else:
+    data_fetcher = pooch.create(
+        # Use the default cache folder for the operating system
+        # Pooch uses appdirs (https://github.com/ActiveState/appdirs) to
+        # select an appropriate directory for the cache on each platform.
+        path=pooch.os_cache("scipy-data"),
+
+        # The remote data is on Github
+        # base_url is a required param, even though we override this
+        # using individual urls in the registry.
+        base_url="https://github.com/scipy/",
+        registry=registry,
+        urls=registry_urls
+    )
+
+
+def fetch_data(dataset_name, data_fetcher=data_fetcher):
+    if data_fetcher is None:
+        raise ImportError("Missing optional dependency 'pooch' required "
+                          "for scipy.datasets module. Please use pip or "
+                          "conda to install 'pooch'.")
+    # The "fetch" method returns the full path to the downloaded data file.
+    return data_fetcher.fetch(dataset_name)
+
+
+def ascent():
+    """
+    Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
+    use in demos.
+
+    The image is derived from
+    https://pixnio.com/people/accent-to-the-top
+
+    Parameters
+    ----------
+    None
+
+    Returns
+    -------
+    ascent : ndarray
+       convenient image to use for testing and demonstration
+
+    Examples
+    --------
+    >>> import scipy.datasets
+    >>> ascent = scipy.datasets.ascent()
+    >>> ascent.shape
+    (512, 512)
+    >>> ascent.max()
+    np.uint8(255)
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.gray()
+    >>> plt.imshow(ascent)
+    >>> plt.show()
+
+    """
+    import pickle
+
+    # The file will be downloaded automatically the first time this is run,
+    # returning the path to the downloaded file. Afterwards, Pooch finds
+    # it in the local cache and doesn't repeat the download.
+    fname = fetch_data("ascent.dat")
+    # Now we just need to load it with our standard Python tools.
+    with open(fname, 'rb') as f:
+        ascent = array(pickle.load(f))
+    return ascent
+
+
+def electrocardiogram():
+    """
+    Load an electrocardiogram as an example for a 1-D signal.
+
+    The returned signal is a 5 minute long electrocardiogram (ECG), a medical
+    recording of the heart's electrical activity, sampled at 360 Hz.
+
+    Returns
+    -------
+    ecg : ndarray
+        The electrocardiogram in millivolt (mV) sampled at 360 Hz.
+
+    Notes
+    -----
+    The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
+    (lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
+    PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
+    heartbeats as well as pathological changes.
+
+    .. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
+
+    .. versionadded:: 1.1.0
+
+    References
+    ----------
+    .. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
+           IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
+           (PMID: 11446209); :doi:`10.13026/C2F305`
+    .. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
+           Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
+           PhysioToolkit, and PhysioNet: Components of a New Research Resource
+           for Complex Physiologic Signals. Circulation 101(23):e215-e220;
+           :doi:`10.1161/01.CIR.101.23.e215`
+
+    Examples
+    --------
+    >>> from scipy.datasets import electrocardiogram
+    >>> ecg = electrocardiogram()
+    >>> ecg
+    array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385], shape=(108000,))
+    >>> ecg.shape, ecg.mean(), ecg.std()
+    ((108000,), -0.16510875, 0.5992473991177294)
+
+    As stated the signal features several areas with a different morphology.
+    E.g., the first few seconds show the electrical activity of a heart in
+    normal sinus rhythm as seen below.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> fs = 360
+    >>> time = np.arange(ecg.size) / fs
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(9, 10.2)
+    >>> plt.ylim(-1, 1.5)
+    >>> plt.show()
+
+    After second 16, however, the first premature ventricular contractions,
+    also called extrasystoles, appear. These have a different morphology
+    compared to typical heartbeats. The difference can easily be observed
+    in the following plot.
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(46.5, 50)
+    >>> plt.ylim(-2, 1.5)
+    >>> plt.show()
+
+    At several points large artifacts disturb the recording, e.g.:
+
+    >>> plt.plot(time, ecg)
+    >>> plt.xlabel("time in s")
+    >>> plt.ylabel("ECG in mV")
+    >>> plt.xlim(207, 215)
+    >>> plt.ylim(-2, 3.5)
+    >>> plt.show()
+
+    Finally, examining the power spectrum reveals that most of the biosignal is
+    made up of lower frequencies. At 60 Hz the noise induced by the mains
+    electricity can be clearly observed.
+
+    >>> from scipy.signal import welch
+    >>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
+    >>> plt.semilogy(f, Pxx)
+    >>> plt.xlabel("Frequency in Hz")
+    >>> plt.ylabel("Power spectrum of the ECG in mV**2")
+    >>> plt.xlim(f[[0, -1]])
+    >>> plt.show()
+    """
+    fname = fetch_data("ecg.dat")
+    with load(fname) as file:
+        ecg = file["ecg"].astype(int)  # np.uint16 -> int
+    # Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
+    ecg = (ecg - 1024) / 200.0
+    return ecg
+
+
+def face(gray=False):
+    """
+    Get a 1024 x 768, color image of a raccoon face.
+
+    The image is derived from
+    https://pixnio.com/fauna-animals/raccoons/raccoon-procyon-lotor
+
+    Parameters
+    ----------
+    gray : bool, optional
+        If True return 8-bit grey-scale image, otherwise return a color image
+
+    Returns
+    -------
+    face : ndarray
+        image of a raccoon face
+
+    Examples
+    --------
+    >>> import scipy.datasets
+    >>> face = scipy.datasets.face()
+    >>> face.shape
+    (768, 1024, 3)
+    >>> face.max()
+    np.uint8(255)
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.gray()
+    >>> plt.imshow(face)
+    >>> plt.show()
+
+    """
+    import bz2
+    fname = fetch_data("face.dat")
+    with open(fname, 'rb') as f:
+        rawdata = f.read()
+    face_data = bz2.decompress(rawdata)
+    face = frombuffer(face_data, dtype='uint8')
+    face.shape = (768, 1024, 3)
+    if gray is True:
+        face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
+                0.07 * face[:, :, 2]).astype('uint8')
+    return face
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_registry.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..969384ad9843159e766100bfa9755aed8102dd09
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_registry.py
@@ -0,0 +1,26 @@
+##########################################################################
+# This file serves as the dataset registry for SciPy Datasets SubModule.
+##########################################################################
+
+
+# To generate the SHA256 hash, use the command
+# openssl sha256 
+registry = {
+    "ascent.dat": "03ce124c1afc880f87b55f6b061110e2e1e939679184f5614e38dacc6c1957e2",
+    "ecg.dat": "f20ad3365fb9b7f845d0e5c48b6fe67081377ee466c3a220b7f69f35c8958baf",
+    "face.dat": "9d8b0b4d081313e2b485748c770472e5a95ed1738146883d84c7030493e82886"
+}
+
+registry_urls = {
+    "ascent.dat": "https://raw.githubusercontent.com/scipy/dataset-ascent/main/ascent.dat",
+    "ecg.dat": "https://raw.githubusercontent.com/scipy/dataset-ecg/main/ecg.dat",
+    "face.dat": "https://raw.githubusercontent.com/scipy/dataset-face/main/face.dat"
+}
+
+# dataset method mapping with their associated filenames
+#  : ["filename1", "filename2", ...]
+method_files_map = {
+    "ascent": ["ascent.dat"],
+    "electrocardiogram": ["ecg.dat"],
+    "face": ["face.dat"]
+}
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_utils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f644f8797d6e3256a16ec2c509eec725c726300
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/_utils.py
@@ -0,0 +1,81 @@
+import os
+import shutil
+from ._registry import method_files_map
+
+try:
+    import platformdirs
+except ImportError:
+    platformdirs = None  # type: ignore[assignment]
+
+
+def _clear_cache(datasets, cache_dir=None, method_map=None):
+    if method_map is None:
+        # Use SciPy Datasets method map
+        method_map = method_files_map
+    if cache_dir is None:
+        # Use default cache_dir path
+        if platformdirs is None:
+            # platformdirs is pooch dependency
+            raise ImportError("Missing optional dependency 'pooch' required "
+                              "for scipy.datasets module. Please use pip or "
+                              "conda to install 'pooch'.")
+        cache_dir = platformdirs.user_cache_dir("scipy-data")
+
+    if not os.path.exists(cache_dir):
+        print(f"Cache Directory {cache_dir} doesn't exist. Nothing to clear.")
+        return
+
+    if datasets is None:
+        print(f"Cleaning the cache directory {cache_dir}!")
+        shutil.rmtree(cache_dir)
+    else:
+        if not isinstance(datasets, (list, tuple)):
+            # single dataset method passed should be converted to list
+            datasets = [datasets, ]
+        for dataset in datasets:
+            assert callable(dataset)
+            dataset_name = dataset.__name__  # Name of the dataset method
+            if dataset_name not in method_map:
+                raise ValueError(f"Dataset method {dataset_name} doesn't "
+                                 "exist. Please check if the passed dataset "
+                                 "is a subset of the following dataset "
+                                 f"methods: {list(method_map.keys())}")
+
+            data_files = method_map[dataset_name]
+            data_filepaths = [os.path.join(cache_dir, file)
+                              for file in data_files]
+            for data_filepath in data_filepaths:
+                if os.path.exists(data_filepath):
+                    print("Cleaning the file "
+                          f"{os.path.split(data_filepath)[1]} "
+                          f"for dataset {dataset_name}")
+                    os.remove(data_filepath)
+                else:
+                    print(f"Path {data_filepath} doesn't exist. "
+                          "Nothing to clear.")
+
+
+def clear_cache(datasets=None):
+    """
+    Cleans the scipy datasets cache directory.
+
+    If a scipy.datasets method or a list/tuple of the same is
+    provided, then clear_cache removes all the data files
+    associated to the passed dataset method callable(s).
+
+    By default, it removes all the cached data files.
+
+    Parameters
+    ----------
+    datasets : callable or list/tuple of callable or None
+
+    Examples
+    --------
+    >>> from scipy import datasets
+    >>> ascent_array = datasets.ascent()
+    >>> ascent_array.shape
+    (512, 512)
+    >>> datasets.clear_cache([datasets.ascent])
+    Cleaning the file ascent.dat for dataset ascent
+    """
+    _clear_cache(datasets)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..243176bd89b7b6f16406d66293d1872ac2712252
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/datasets/tests/test_data.py
@@ -0,0 +1,128 @@
+from scipy.datasets._registry import registry
+from scipy.datasets._fetchers import data_fetcher
+from scipy.datasets._utils import _clear_cache
+from scipy.datasets import ascent, face, electrocardiogram, download_all
+from numpy.testing import assert_equal, assert_almost_equal
+import os
+from threading import get_ident
+import pytest
+
+try:
+    import pooch
+except ImportError:
+    raise ImportError("Missing optional dependency 'pooch' required "
+                      "for scipy.datasets module. Please use pip or "
+                      "conda to install 'pooch'.")
+
+
+data_dir = data_fetcher.path  # type: ignore
+
+
+def _has_hash(path, expected_hash):
+    """Check if the provided path has the expected hash."""
+    if not os.path.exists(path):
+        return False
+    return pooch.file_hash(path) == expected_hash
+
+
+class TestDatasets:
+
+    @pytest.fixture(scope='module', autouse=True)
+    def test_download_all(self):
+        # This fixture requires INTERNET CONNECTION
+
+        # test_setup phase
+        download_all()
+
+        yield
+
+    @pytest.mark.fail_slow(10)
+    def test_existence_all(self):
+        assert len(os.listdir(data_dir)) >= len(registry)
+
+    def test_ascent(self):
+        assert_equal(ascent().shape, (512, 512))
+
+        # hash check
+        assert _has_hash(os.path.join(data_dir, "ascent.dat"),
+                         registry["ascent.dat"])
+
+    def test_face(self):
+        assert_equal(face().shape, (768, 1024, 3))
+
+        # hash check
+        assert _has_hash(os.path.join(data_dir, "face.dat"),
+                         registry["face.dat"])
+
+    def test_electrocardiogram(self):
+        # Test shape, dtype and stats of signal
+        ecg = electrocardiogram()
+        assert_equal(ecg.dtype, float)
+        assert_equal(ecg.shape, (108000,))
+        assert_almost_equal(ecg.mean(), -0.16510875)
+        assert_almost_equal(ecg.std(), 0.5992473991177294)
+
+        # hash check
+        assert _has_hash(os.path.join(data_dir, "ecg.dat"),
+                         registry["ecg.dat"])
+
+
+def test_clear_cache(tmp_path):
+    # Note: `tmp_path` is a pytest fixture, it handles cleanup
+    thread_basepath = tmp_path / str(get_ident())
+    thread_basepath.mkdir()
+
+    dummy_basepath = thread_basepath / "dummy_cache_dir"
+    dummy_basepath.mkdir()
+
+    # Create three dummy dataset files for dummy dataset methods
+    dummy_method_map = {}
+    for i in range(4):
+        dummy_method_map[f"data{i}"] = [f"data{i}.dat"]
+        data_filepath = dummy_basepath / f"data{i}.dat"
+        data_filepath.write_text("")
+
+    # clear files associated to single dataset method data0
+    # also test callable argument instead of list of callables
+    def data0():
+        pass
+    _clear_cache(datasets=data0, cache_dir=dummy_basepath,
+                 method_map=dummy_method_map)
+    assert not os.path.exists(dummy_basepath/"data0.dat")
+
+    # clear files associated to multiple dataset methods "data3" and "data4"
+    def data1():
+        pass
+
+    def data2():
+        pass
+    _clear_cache(datasets=[data1, data2], cache_dir=dummy_basepath,
+                 method_map=dummy_method_map)
+    assert not os.path.exists(dummy_basepath/"data1.dat")
+    assert not os.path.exists(dummy_basepath/"data2.dat")
+
+    # clear multiple dataset files "data3_0.dat" and "data3_1.dat"
+    # associated with dataset method "data3"
+    def data4():
+        pass
+    # create files
+    (dummy_basepath / "data4_0.dat").write_text("")
+    (dummy_basepath / "data4_1.dat").write_text("")
+
+    dummy_method_map["data4"] = ["data4_0.dat", "data4_1.dat"]
+    _clear_cache(datasets=[data4], cache_dir=dummy_basepath,
+                 method_map=dummy_method_map)
+    assert not os.path.exists(dummy_basepath/"data4_0.dat")
+    assert not os.path.exists(dummy_basepath/"data4_1.dat")
+
+    # wrong dataset method should raise ValueError since it
+    # doesn't exist in the dummy_method_map
+    def data5():
+        pass
+    with pytest.raises(ValueError):
+        _clear_cache(datasets=[data5], cache_dir=dummy_basepath,
+                     method_map=dummy_method_map)
+
+    # remove all dataset cache
+    _clear_cache(datasets=None, cache_dir=dummy_basepath)
+    assert not os.path.exists(dummy_basepath)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3a7ccc4b33f27dbae7958641a89106cf9580326
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/__init__.py
@@ -0,0 +1,27 @@
+"""
+==============================================================
+Finite Difference Differentiation (:mod:`scipy.differentiate`)
+==============================================================
+
+.. currentmodule:: scipy.differentiate
+
+SciPy ``differentiate`` provides functions for performing finite difference
+numerical differentiation of black-box functions.
+
+.. autosummary::
+   :toctree: generated/
+
+   derivative
+   jacobian
+   hessian
+
+"""
+
+
+from ._differentiate import *
+
+__all__ = ['derivative', 'jacobian', 'hessian']
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/_differentiate.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e104a071055161b69f62cec317e8a07b4466653
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/_differentiate.py
@@ -0,0 +1,1129 @@
+# mypy: disable-error-code="attr-defined"
+import warnings
+import numpy as np
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import array_namespace, xp_sign, xp_copy, xp_take_along_axis
+
+_EERRORINCREASE = -1  # used in derivative
+
+def _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
+                   step_factor, step_direction, preserve_shape, callback):
+    # Input validation for `derivative`
+    xp = array_namespace(x)
+
+    if not callable(f):
+        raise ValueError('`f` must be callable.')
+
+    if not np.iterable(args):
+        args = (args,)
+
+    tolerances = {} if tolerances is None else tolerances
+    atol = tolerances.get('atol', None)
+    rtol = tolerances.get('rtol', None)
+
+    # tolerances are floats, not arrays; OK to use NumPy
+    message = 'Tolerances and step parameters must be non-negative scalars.'
+    tols = np.asarray([atol if atol is not None else 1,
+                       rtol if rtol is not None else 1,
+                       step_factor])
+    if (not np.issubdtype(tols.dtype, np.number) or np.any(tols < 0)
+            or np.any(np.isnan(tols)) or tols.shape != (3,)):
+        raise ValueError(message)
+    step_factor = float(tols[2])
+
+    maxiter_int = int(maxiter)
+    if maxiter != maxiter_int or maxiter <= 0:
+        raise ValueError('`maxiter` must be a positive integer.')
+
+    order_int = int(order)
+    if order_int != order or order <= 0:
+        raise ValueError('`order` must be a positive integer.')
+
+    step_direction = xp.asarray(step_direction)
+    initial_step = xp.asarray(initial_step)
+    temp = xp.broadcast_arrays(x, step_direction, initial_step)
+    x, step_direction, initial_step = temp
+
+    message = '`preserve_shape` must be True or False.'
+    if preserve_shape not in {True, False}:
+        raise ValueError(message)
+
+    if callback is not None and not callable(callback):
+        raise ValueError('`callback` must be callable.')
+
+    return (f, x, args, atol, rtol, maxiter_int, order_int, initial_step,
+            step_factor, step_direction, preserve_shape, callback)
+
+
+def derivative(f, x, *, args=(), tolerances=None, maxiter=10,
+               order=8, initial_step=0.5, step_factor=2.0,
+               step_direction=0, preserve_shape=False, callback=None):
+    """Evaluate the derivative of a elementwise, real scalar function numerically.
+
+    For each element of the output of `f`, `derivative` approximates the first
+    derivative of `f` at the corresponding element of `x` using finite difference
+    differentiation.
+
+    This function works elementwise when `x`, `step_direction`, and `args` contain
+    (broadcastable) arrays.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose derivative is desired. The signature must be::
+
+            f(xi: ndarray, *argsi) -> ndarray
+
+        where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable with
+        ``xi``. `f` must be an elementwise function: each scalar element ``f(xi)[j]``
+        must equal ``f(xi[j])`` for valid indices ``j``. It must not mutate the array
+        ``xi`` or the arrays in ``argsi``.
+    x : float array_like
+        Abscissae at which to evaluate the derivative. Must be broadcastable with
+        `args` and `step_direction`.
+    args : tuple of array_like, optional
+        Additional positional array arguments to be passed to `f`. Arrays
+        must be broadcastable with one another and the arrays of `init`.
+        If the callable for which the root is desired requires arguments that are
+        not broadcastable with `x`, wrap that callable with `f` such that `f`
+        accepts only `x` and broadcastable ``*args``.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float array_like, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+    step_direction : integer array_like
+        An array representing the direction of the finite difference steps (for
+        use when `x` lies near to the boundary of the domain of the function.)
+        Must be broadcastable with `x` and all `args`.
+        Where 0 (default), central differences are used; where negative (e.g.
+        -1), steps are non-positive; and where positive (e.g. 1), all steps are
+        non-negative.
+    preserve_shape : bool, default: False
+        In the following, "arguments of `f`" refers to the array ``xi`` and
+        any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
+        of `x` and all elements of `args` (which is conceptually
+        distinct from ``xi` and ``argsi`` passed into `f`).
+
+        - When ``preserve_shape=False`` (default), `f` must accept arguments
+          of *any* broadcastable shapes.
+
+        - When ``preserve_shape=True``, `f` must accept arguments of shape
+          ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
+          abscissae at which the function is being evaluated.
+
+        In either case, for each scalar element ``xi[j]`` within ``xi``, the array
+        returned by `f` must include the scalar ``f(xi[j])`` at the same index.
+        Consequently, the shape of the output is always the shape of the input
+        ``xi``.
+
+        See Examples.
+    callback : callable, optional
+        An optional user-supplied function to be called before the first
+        iteration and after each iteration.
+        Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+        similar to that returned by `derivative` (but containing the current
+        iterate's values of all variables). If `callback` raises a
+        ``StopIteration``, the algorithm will terminate immediately and
+        `derivative` will return a result. `callback` must not mutate
+        `res` or its attributes.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.
+
+        success : bool array
+            ``True`` where the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : The error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+            - ``-4`` : Iteration was terminated by `callback`.
+            - ``1`` : The algorithm is proceeding normally (in `callback` only).
+
+        df : float array
+            The derivative of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the derivative and the estimate in the
+            previous iteration.
+        nit : int array
+            The number of iterations of the algorithm that were performed.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+        x : float array
+            The value at which the derivative of `f` was evaluated
+            (after broadcasting with `args` and `step_direction`).
+
+    See Also
+    --------
+    jacobian, hessian
+
+    Notes
+    -----
+    The implementation was inspired by jacobi [1]_, numdifftools [2]_, and
+    DERIVEST [3]_, but the implementation follows the theory of Taylor series
+    more straightforwardly (and arguably naively so).
+    In the first iteration, the derivative is estimated using a finite
+    difference formula of order `order` with maximum step size `initial_step`.
+    Each subsequent iteration, the maximum step size is reduced by
+    `step_factor`, and the derivative is estimated again until a termination
+    condition is reached. The error estimate is the magnitude of the difference
+    between the current derivative approximation and that of the previous
+    iteration.
+
+    The stencils of the finite difference formulae are designed such that
+    abscissae are "nested": after `f` is evaluated at ``order + 1``
+    points in the first iteration, `f` is evaluated at only two new points
+    in each subsequent iteration; ``order - 1`` previously evaluated function
+    values required by the finite difference formula are reused, and two
+    function values (evaluations at the points furthest from `x`) are unused.
+
+    Step sizes are absolute. When the step size is small relative to the
+    magnitude of `x`, precision is lost; for example, if `x` is ``1e20``, the
+    default initial step size of ``0.5`` cannot be resolved. Accordingly,
+    consider using larger initial step sizes for large magnitudes of `x`.
+
+    The default tolerances are challenging to satisfy at points where the
+    true derivative is exactly zero. If the derivative may be exactly zero,
+    consider specifying an absolute tolerance (e.g. ``atol=1e-12``) to
+    improve convergence.
+
+    References
+    ----------
+    .. [1] Hans Dembinski (@HDembinski). jacobi.
+           https://github.com/HDembinski/jacobi
+    .. [2] Per A. Brodtkorb and John D'Errico. numdifftools.
+           https://numdifftools.readthedocs.io/en/latest/
+    .. [3] John D'Errico. DERIVEST: Adaptive Robust Numerical Differentiation.
+           https://www.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation
+    .. [4] Numerical Differentition. Wikipedia.
+           https://en.wikipedia.org/wiki/Numerical_differentiation
+
+    Examples
+    --------
+    Evaluate the derivative of ``np.exp`` at several points ``x``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import derivative
+    >>> f = np.exp
+    >>> df = np.exp  # true derivative
+    >>> x = np.linspace(1, 2, 5)
+    >>> res = derivative(f, x)
+    >>> res.df  # approximation of the derivative
+    array([2.71828183, 3.49034296, 4.48168907, 5.75460268, 7.3890561 ])
+    >>> res.error  # estimate of the error
+    array([7.13740178e-12, 9.16600129e-12, 1.17594823e-11, 1.51061386e-11,
+           1.94262384e-11])
+    >>> abs(res.df - df(x))  # true error
+    array([2.53130850e-14, 3.55271368e-14, 5.77315973e-14, 5.59552404e-14,
+           6.92779167e-14])
+
+    Show the convergence of the approximation as the step size is reduced.
+    Each iteration, the step size is reduced by `step_factor`, so for
+    sufficiently small initial step, each iteration reduces the error by a
+    factor of ``1/step_factor**order`` until finite precision arithmetic
+    inhibits further improvement.
+
+    >>> import matplotlib.pyplot as plt
+    >>> iter = list(range(1, 12))  # maximum iterations
+    >>> hfac = 2  # step size reduction per iteration
+    >>> hdir = [-1, 0, 1]  # compare left-, central-, and right- steps
+    >>> order = 4  # order of differentiation formula
+    >>> x = 1
+    >>> ref = df(x)
+    >>> errors = []  # true error
+    >>> for i in iter:
+    ...     res = derivative(f, x, maxiter=i, step_factor=hfac,
+    ...                      step_direction=hdir, order=order,
+    ...                      # prevent early termination
+    ...                      tolerances=dict(atol=0, rtol=0))
+    ...     errors.append(abs(res.df - ref))
+    >>> errors = np.array(errors)
+    >>> plt.semilogy(iter, errors[:, 0], label='left differences')
+    >>> plt.semilogy(iter, errors[:, 1], label='central differences')
+    >>> plt.semilogy(iter, errors[:, 2], label='right differences')
+    >>> plt.xlabel('iteration')
+    >>> plt.ylabel('error')
+    >>> plt.legend()
+    >>> plt.show()
+    >>> (errors[1, 1] / errors[0, 1], 1 / hfac**order)
+    (0.06215223140159822, 0.0625)
+
+    The implementation is vectorized over `x`, `step_direction`, and `args`.
+    The function is evaluated once before the first iteration to perform input
+    validation and standardization, and once per iteration thereafter.
+
+    >>> def f(x, p):
+    ...     f.nit += 1
+    ...     return x**p
+    >>> f.nit = 0
+    >>> def df(x, p):
+    ...     return p*x**(p-1)
+    >>> x = np.arange(1, 5)
+    >>> p = np.arange(1, 6).reshape((-1, 1))
+    >>> hdir = np.arange(-1, 2).reshape((-1, 1, 1))
+    >>> res = derivative(f, x, args=(p,), step_direction=hdir, maxiter=1)
+    >>> np.allclose(res.df, df(x, p))
+    True
+    >>> res.df.shape
+    (3, 5, 4)
+    >>> f.nit
+    2
+
+    By default, `preserve_shape` is False, and therefore the callable
+    `f` may be called with arrays of any broadcastable shapes.
+    For example:
+
+    >>> shapes = []
+    >>> def f(x, c):
+    ...    shape = np.broadcast_shapes(x.shape, c.shape)
+    ...    shapes.append(shape)
+    ...    return np.sin(c*x)
+    >>>
+    >>> c = [1, 5, 10, 20]
+    >>> res = derivative(f, 0, args=(c,))
+    >>> shapes
+    [(4,), (4, 8), (4, 2), (3, 2), (2, 2), (1, 2)]
+
+    To understand where these shapes are coming from - and to better
+    understand how `derivative` computes accurate results - note that
+    higher values of ``c`` correspond with higher frequency sinusoids.
+    The higher frequency sinusoids make the function's derivative change
+    faster, so more function evaluations are required to achieve the target
+    accuracy:
+
+    >>> res.nfev
+    array([11, 13, 15, 17], dtype=int32)
+
+    The initial ``shape``, ``(4,)``, corresponds with evaluating the
+    function at a single abscissa and all four frequencies; this is used
+    for input validation and to determine the size and dtype of the arrays
+    that store results. The next shape corresponds with evaluating the
+    function at an initial grid of abscissae and all four frequencies.
+    Successive calls to the function evaluate the function at two more
+    abscissae, increasing the effective order of the approximation by two.
+    However, in later function evaluations, the function is evaluated at
+    fewer frequencies because the corresponding derivative has already
+    converged to the required tolerance. This saves function evaluations to
+    improve performance, but it requires the function to accept arguments of
+    any shape.
+
+    "Vector-valued" functions are unlikely to satisfy this requirement.
+    For example, consider
+
+    >>> def f(x):
+    ...    return [x, np.sin(3*x), x+np.sin(10*x), np.sin(20*x)*(x-1)**2]
+
+    This integrand is not compatible with `derivative` as written; for instance,
+    the shape of the output will not be the same as the shape of ``x``. Such a
+    function *could* be converted to a compatible form with the introduction of
+    additional parameters, but this would be inconvenient. In such cases,
+    a simpler solution would be to use `preserve_shape`.
+
+    >>> shapes = []
+    >>> def f(x):
+    ...     shapes.append(x.shape)
+    ...     x0, x1, x2, x3 = x
+    ...     return [x0, np.sin(3*x1), x2+np.sin(10*x2), np.sin(20*x3)*(x3-1)**2]
+    >>>
+    >>> x = np.zeros(4)
+    >>> res = derivative(f, x, preserve_shape=True)
+    >>> shapes
+    [(4,), (4, 8), (4, 2), (4, 2), (4, 2), (4, 2)]
+
+    Here, the shape of ``x`` is ``(4,)``. With ``preserve_shape=True``, the
+    function may be called with argument ``x`` of shape ``(4,)`` or ``(4, n)``,
+    and this is what we observe.
+
+    """
+    # TODO (followup):
+    #  - investigate behavior at saddle points
+    #  - multivariate functions?
+    #  - relative steps?
+    #  - show example of `np.vectorize`
+
+    res = _derivative_iv(f, x, args, tolerances, maxiter, order, initial_step,
+                            step_factor, step_direction, preserve_shape, callback)
+    (func, x, args, atol, rtol, maxiter, order,
+     h0, fac, hdir, preserve_shape, callback) = res
+
+    # Initialization
+    # Since f(x) (no step) is not needed for central differences, it may be
+    # possible to eliminate this function evaluation. However, it's useful for
+    # input validation and standardization, and everything else is designed to
+    # reduce function calls, so let's keep it simple.
+    temp = eim._initialize(func, (x,), args, preserve_shape=preserve_shape)
+    func, xs, fs, args, shape, dtype, xp = temp
+
+    finfo = xp.finfo(dtype)
+    atol = finfo.smallest_normal if atol is None else atol
+    rtol = finfo.eps**0.5 if rtol is None else rtol  # keep same as `hessian`
+
+    x, f = xs[0], fs[0]
+    df = xp.full_like(f, xp.nan)
+
+    # Ideally we'd broadcast the shape of `hdir` in `_elementwise_algo_init`, but
+    # it's simpler to do it here than to generalize `_elementwise_algo_init` further.
+    # `hdir` and `x` are already broadcasted in `_derivative_iv`, so we know
+    # that `hdir` can be broadcasted to the final shape. Same with `h0`.
+    hdir = xp.broadcast_to(hdir, shape)
+    hdir = xp.reshape(hdir, (-1,))
+    hdir = xp.astype(xp_sign(hdir), dtype)
+    h0 = xp.broadcast_to(h0, shape)
+    h0 = xp.reshape(h0, (-1,))
+    h0 = xp.astype(h0, dtype)
+    h0[h0 <= 0] = xp.asarray(xp.nan, dtype=dtype)
+
+    status = xp.full_like(x, eim._EINPROGRESS, dtype=xp.int32)  # in progress
+    nit, nfev = 0, 1  # one function evaluations performed above
+    # Boolean indices of left, central, right, and (all) one-sided steps
+    il = hdir < 0
+    ic = hdir == 0
+    ir = hdir > 0
+    io = il | ir
+
+    # Most of these attributes are reasonably obvious, but:
+    # - `fs` holds all the function values of all active `x`. The zeroth
+    #   axis corresponds with active points `x`, the first axis corresponds
+    #   with the different steps (in the order described in
+    #   `_derivative_weights`).
+    # - `terms` (which could probably use a better name) is half the `order`,
+    #   which is always even.
+    work = _RichResult(x=x, df=df, fs=f[:, xp.newaxis], error=xp.nan, h=h0,
+                       df_last=xp.nan, error_last=xp.nan, fac=fac,
+                       atol=atol, rtol=rtol, nit=nit, nfev=nfev,
+                       status=status, dtype=dtype, terms=(order+1)//2,
+                       hdir=hdir, il=il, ic=ic, ir=ir, io=io,
+                       # Store the weights in an object so they can't get compressed
+                       # Using RichResult to allow dot notation, but a dict would work
+                       diff_state=_RichResult(central=[], right=[], fac=None))
+
+    # This is the correspondence between terms in the `work` object and the
+    # final result. In this case, the mapping is trivial. Note that `success`
+    # is prepended automatically.
+    res_work_pairs = [('status', 'status'), ('df', 'df'), ('error', 'error'),
+                      ('nit', 'nit'), ('nfev', 'nfev'), ('x', 'x')]
+
+    def pre_func_eval(work):
+        """Determine the abscissae at which the function needs to be evaluated.
+
+        See `_derivative_weights` for a description of the stencil (pattern
+        of the abscissae).
+
+        In the first iteration, there is only one stored function value in
+        `work.fs`, `f(x)`, so we need to evaluate at `order` new points. In
+        subsequent iterations, we evaluate at two new points. Note that
+        `work.x` is always flattened into a 1D array after broadcasting with
+        all `args`, so we add a new axis at the end and evaluate all point
+        in one call to the function.
+
+        For improvement:
+        - Consider measuring the step size actually taken, since ``(x + h) - x``
+          is not identically equal to `h` with floating point arithmetic.
+        - Adjust the step size automatically if `x` is too big to resolve the
+          step.
+        - We could probably save some work if there are no central difference
+          steps or no one-sided steps.
+        """
+        n = work.terms  # half the order
+        h = work.h[:, xp.newaxis]  # step size
+        c = work.fac  # step reduction factor
+        d = c**0.5  # square root of step reduction factor (one-sided stencil)
+        # Note - no need to be careful about dtypes until we allocate `x_eval`
+
+        if work.nit == 0:
+            hc = h / c**xp.arange(n, dtype=work.dtype)
+            hc = xp.concat((-xp.flip(hc, axis=-1), hc), axis=-1)
+        else:
+            hc = xp.concat((-h, h), axis=-1) / c**(n-1)
+
+        if work.nit == 0:
+            hr = h / d**xp.arange(2*n, dtype=work.dtype)
+        else:
+            hr = xp.concat((h, h/d), axis=-1) / c**(n-1)
+
+        n_new = 2*n if work.nit == 0 else 2  # number of new abscissae
+        x_eval = xp.zeros((work.hdir.shape[0], n_new), dtype=work.dtype)
+        il, ic, ir = work.il, work.ic, work.ir
+        x_eval[ir] = work.x[ir][:, xp.newaxis] + hr[ir]
+        x_eval[ic] = work.x[ic][:, xp.newaxis] + hc[ic]
+        x_eval[il] = work.x[il][:, xp.newaxis] - hr[il]
+        return x_eval
+
+    def post_func_eval(x, f, work):
+        """ Estimate the derivative and error from the function evaluations
+
+        As in `pre_func_eval`: in the first iteration, there is only one stored
+        function value in `work.fs`, `f(x)`, so we need to add the `order` new
+        points. In subsequent iterations, we add two new points. The tricky
+        part is getting the order to match that of the weights, which is
+        described in `_derivative_weights`.
+
+        For improvement:
+        - Change the order of the weights (and steps in `pre_func_eval`) to
+          simplify `work_fc` concatenation and eliminate `fc` concatenation.
+        - It would be simple to do one-step Richardson extrapolation with `df`
+          and `df_last` to increase the order of the estimate and/or improve
+          the error estimate.
+        - Process the function evaluations in a more numerically favorable
+          way. For instance, combining the pairs of central difference evals
+          into a second-order approximation and using Richardson extrapolation
+          to produce a higher order approximation seemed to retain accuracy up
+          to very high order.
+        - Alternatively, we could use `polyfit` like Jacobi. An advantage of
+          fitting polynomial to more points than necessary is improved noise
+          tolerance.
+        """
+        n = work.terms
+        n_new = n if work.nit == 0 else 1
+        il, ic, io = work.il, work.ic, work.io
+
+        # Central difference
+        # `work_fc` is *all* the points at which the function has been evaluated
+        # `fc` is the points we're using *this iteration* to produce the estimate
+        work_fc = (f[ic][:, :n_new], work.fs[ic], f[ic][:, -n_new:])
+        work_fc = xp.concat(work_fc, axis=-1)
+        if work.nit == 0:
+            fc = work_fc
+        else:
+            fc = (work_fc[:, :n], work_fc[:, n:n+1], work_fc[:, -n:])
+            fc = xp.concat(fc, axis=-1)
+
+        # One-sided difference
+        work_fo = xp.concat((work.fs[io], f[io]), axis=-1)
+        if work.nit == 0:
+            fo = work_fo
+        else:
+            fo = xp.concat((work_fo[:, 0:1], work_fo[:, -2*n:]), axis=-1)
+
+        work.fs = xp.zeros((ic.shape[0], work.fs.shape[-1] + 2*n_new), dtype=work.dtype)
+        work.fs[ic] = work_fc
+        work.fs[io] = work_fo
+
+        wc, wo = _derivative_weights(work, n, xp)
+        work.df_last = xp.asarray(work.df, copy=True)
+        work.df[ic] = fc @ wc / work.h[ic]
+        work.df[io] = fo @ wo / work.h[io]
+        work.df[il] *= -1
+
+        work.h /= work.fac
+        work.error_last = work.error
+        # Simple error estimate - the difference in derivative estimates between
+        # this iteration and the last. This is typically conservative because if
+        # convergence has begin, the true error is much closer to the difference
+        # between the current estimate and the *next* error estimate. However,
+        # we could use Richarson extrapolation to produce an error estimate that
+        # is one order higher, and take the difference between that and
+        # `work.df` (which would just be constant factor that depends on `fac`.)
+        work.error = xp.abs(work.df - work.df_last)
+
+    def check_termination(work):
+        """Terminate due to convergence, non-finite values, or error increase"""
+        stop = xp.astype(xp.zeros_like(work.df), xp.bool)
+
+        i = work.error < work.atol + work.rtol*abs(work.df)
+        work.status[i] = eim._ECONVERGED
+        stop[i] = True
+
+        if work.nit > 0:
+            i = ~((xp.isfinite(work.x) & xp.isfinite(work.df)) | stop)
+            work.df[i], work.status[i] = xp.nan, eim._EVALUEERR
+            stop[i] = True
+
+        # With infinite precision, there is a step size below which
+        # all smaller step sizes will reduce the error. But in floating point
+        # arithmetic, catastrophic cancellation will begin to cause the error
+        # to increase again. This heuristic tries to avoid step sizes that are
+        # too small. There may be more theoretically sound approaches for
+        # detecting a step size that minimizes the total error, but this
+        # heuristic seems simple and effective.
+        i = (work.error > work.error_last*10) & ~stop
+        work.status[i] = _EERRORINCREASE
+        stop[i] = True
+
+        return stop
+
+    def post_termination_check(work):
+        return
+
+    def customize_result(res, shape):
+        return shape
+
+    return eim._loop(work, callback, shape, maxiter, func, args, dtype,
+                     pre_func_eval, post_func_eval, check_termination,
+                     post_termination_check, customize_result, res_work_pairs,
+                     xp, preserve_shape)
+
+
+def _derivative_weights(work, n, xp):
+    # This produces the weights of the finite difference formula for a given
+    # stencil. In experiments, use of a second-order central difference formula
+    # with Richardson extrapolation was more accurate numerically, but it was
+    # more complicated, and it would have become even more complicated when
+    # adding support for one-sided differences. However, now that all the
+    # function evaluation values are stored, they can be processed in whatever
+    # way is desired to produce the derivative estimate. We leave alternative
+    # approaches to future work. To be more self-contained, here is the theory
+    # for deriving the weights below.
+    #
+    # Recall that the Taylor expansion of a univariate, scalar-values function
+    # about a point `x` may be expressed as:
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # Suppose we evaluate f(x), f(x+h), and f(x-h).  We have:
+    #      f(x)      =     f(x)
+    #      f(x + h)  =     f(x) + f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    #      f(x - h)  =     f(x) - f'(x)*h + f''(x)/2!*h**2  + O(h**3)
+    # We can solve for weights `wi` such that:
+    #   w1*f(x)      = w1*(f(x))
+    # + w2*f(x + h)  = w2*(f(x) + f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    # + w3*f(x - h)  = w3*(f(x) - f'(x)*h + f''(x)/2!*h**2) + O(h**3)
+    #                =     0    + f'(x)*h + 0               + O(h**3)
+    # Then
+    #     f'(x) ~ (w1*f(x) + w2*f(x+h) + w3*f(x-h))/h
+    # is a finite difference derivative approximation with error O(h**2),
+    # and so it is said to be a "second-order" approximation. Under certain
+    # conditions (e.g. well-behaved function, `h` sufficiently small), the
+    # error in the approximation will decrease with h**2; that is, if `h` is
+    # reduced by a factor of 2, the error is reduced by a factor of 4.
+    #
+    # By default, we use eighth-order formulae. Our central-difference formula
+    # uses abscissae:
+    #   x-h/c**3, x-h/c**2, x-h/c, x-h, x, x+h, x+h/c, x+h/c**2, x+h/c**3
+    # where `c` is the step factor. (Typically, the step factor is greater than
+    # one, so the outermost points - as written above - are actually closest to
+    # `x`.) This "stencil" is chosen so that each iteration, the step can be
+    # reduced by the factor `c`, and most of the function evaluations can be
+    # reused with the new step size. For example, in the next iteration, we
+    # will have:
+    #   x-h/c**4, x-h/c**3, x-h/c**2, x-h/c, x, x+h/c, x+h/c**2, x+h/c**3, x+h/c**4
+    # We do not reuse `x-h` and `x+h` for the new derivative estimate.
+    # While this would increase the order of the formula and thus the
+    # theoretical convergence rate, it is also less stable numerically.
+    # (As noted above, there are other ways of processing the values that are
+    # more stable. Thus, even now we store `f(x-h)` and `f(x+h)` in `work.fs`
+    # to simplify future development of this sort of improvement.)
+    #
+    # The (right) one-sided formula is produced similarly using abscissae
+    #   x, x+h, x+h/d, x+h/d**2, ..., x+h/d**6, x+h/d**7, x+h/d**7
+    # where `d` is the square root of `c`. (The left one-sided formula simply
+    # uses -h.) When the step size is reduced by factor `c = d**2`, we have
+    # abscissae:
+    #   x, x+h/d**2, x+h/d**3..., x+h/d**8, x+h/d**9, x+h/d**9
+    # `d` is chosen as the square root of `c` so that the rate of the step-size
+    # reduction is the same per iteration as in the central difference case.
+    # Note that because the central difference formulas are inherently of even
+    # order, for simplicity, we use only even-order formulas for one-sided
+    # differences, too.
+
+    # It's possible for the user to specify `fac` in, say, double precision but
+    # `x` and `args` in single precision. `fac` gets converted to single
+    # precision, but we should always use double precision for the intermediate
+    # calculations here to avoid additional error in the weights.
+    fac = float(work.fac)
+
+    # Note that if the user switches back to floating point precision with
+    # `x` and `args`, then `fac` will not necessarily equal the (lower
+    # precision) cached `_derivative_weights.fac`, and the weights will
+    # need to be recalculated. This could be fixed, but it's late, and of
+    # low consequence.
+
+    diff_state = work.diff_state
+    if fac != diff_state.fac:
+        diff_state.central = []
+        diff_state.right = []
+        diff_state.fac = fac
+
+    if len(diff_state.central) != 2*n + 1:
+        # Central difference weights. Consider refactoring this; it could
+        # probably be more compact.
+        # Note: Using NumPy here is OK; we convert to xp-type at the end
+        i = np.arange(-n, n + 1)
+        p = np.abs(i) - 1.  # center point has power `p` -1, but sign `s` is 0
+        s = np.sign(i)
+
+        h = s / fac ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2*n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        # Enforce identities to improve accuracy
+        weights[n] = 0
+        for i in range(n):
+            weights[-i-1] = -weights[i]
+
+        # Cache the weights. We only need to calculate them once unless
+        # the step factor changes.
+        diff_state.central = weights
+
+        # One-sided difference weights. The left one-sided weights (with
+        # negative steps) are simply the negative of the right one-sided
+        # weights, so no need to compute them separately.
+        i = np.arange(2*n + 1)
+        p = i - 1.
+        s = np.sign(i)
+
+        h = s / np.sqrt(fac) ** p
+        A = np.vander(h, increasing=True).T
+        b = np.zeros(2 * n + 1)
+        b[1] = 1
+        weights = np.linalg.solve(A, b)
+
+        diff_state.right = weights
+
+    return (xp.asarray(diff_state.central, dtype=work.dtype),
+            xp.asarray(diff_state.right, dtype=work.dtype))
+
+
+def jacobian(f, x, *, tolerances=None, maxiter=10, order=8, initial_step=0.5,
+             step_factor=2.0, step_direction=0):
+    r"""Evaluate the Jacobian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Jacobian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `jacobian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Jacobian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float array_like, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation. Must be broadcastable with `x` and `step_direction`.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    step_direction : integer array_like
+        An array representing the direction of the finite difference steps (e.g.
+        for use when `x` lies near to the boundary of the domain of the function.)
+        Must be broadcastable with `x` and `initial_step`.
+        Where 0 (default), central differences are used; where negative (e.g.
+        -1), steps are non-positive; and where positive (e.g. 1), all steps are
+        non-negative.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.
+
+        success : bool array
+            ``True`` where the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : The error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+
+        df : float array
+            The Jacobian of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the Jacobian and the estimate in the
+            previous iteration.
+        nit : int array
+            The number of iterations of the algorithm that were performed.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+        Each element of an attribute is associated with the corresponding
+        element of `df`. For instance, element ``i`` of `nfev` is the
+        number of points at which `f` was evaluated for the sake of
+        computing element ``i`` of `df`.
+
+    See Also
+    --------
+    derivative, hessian
+
+    Notes
+    -----
+    Suppose we wish to evaluate the Jacobian of a function
+    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}^n`. Assign to variables
+    ``m`` and ``n`` the positive integer values of :math:`m` and :math:`n`,
+    respectively, and let ``...`` represent an arbitrary tuple of integers.
+    If we wish to evaluate the Jacobian at a single point, then:
+
+    - argument `x` must be an array of shape ``(m,)``
+    - argument `f` must be vectorized to accept an array of shape ``(m, ...)``.
+      The first axis represents the :math:`m` inputs of :math:`f`; the remainder
+      are for evaluating the function at multiple points in a single call.
+    - argument `f` must return an array of shape ``(n, ...)``. The first
+      axis represents the :math:`n` outputs of :math:`f`; the remainder
+      are for the result of evaluating the function at multiple points.
+    - attribute ``df`` of the result object will be an array of shape ``(n, m)``,
+      the Jacobian.
+
+    This function is also vectorized in the sense that the Jacobian can be
+    evaluated at ``k`` points in a single call. In this case, `x` would be an
+    array of shape ``(m, k)``, `f` would accept an array of shape
+    ``(m, k, ...)`` and return an array of shape ``(n, k, ...)``, and the ``df``
+    attribute of the result would have shape ``(n, m, k)``.
+
+    Suppose the desired callable ``f_not_vectorized`` is not vectorized; it can
+    only accept an array of shape ``(m,)``. A simple solution to satisfy the required
+    interface is to wrap ``f_not_vectorized`` as follows::
+
+        def f(x):
+            return np.apply_along_axis(f_not_vectorized, axis=0, arr=x)
+
+    Alternatively, suppose the desired callable ``f_vec_q`` is vectorized, but
+    only for 2-D arrays of shape ``(m, q)``. To satisfy the required interface,
+    consider::
+
+        def f(x):
+            m, batch = x.shape[0], x.shape[1:]  # x.shape is (m, ...)
+            x = np.reshape(x, (m, -1))  # `-1` is short for q = prod(batch)
+            res = f_vec_q(x)  # pass shape (m, q) to function
+            n = res.shape[0]
+            return np.reshape(res, (n,) + batch)  # return shape (n, ...)
+
+    Then pass the wrapped callable ``f`` as the first argument of `jacobian`.
+
+    References
+    ----------
+    .. [1] Jacobian matrix and determinant, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant
+
+    Examples
+    --------
+    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
+    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
+    array of shape ``(m, p)`` and return an array of shape ``p``. Suppose we wish
+    to evaluate the Jacobian (AKA the gradient because the function returns a scalar)
+    at ``[0.5, 0.5, 0.5]``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import jacobian
+    >>> from scipy.optimize import rosen, rosen_der
+    >>> m = 3
+    >>> x = np.full(m, 0.5)
+    >>> res = jacobian(rosen, x)
+    >>> ref = rosen_der(x)  # reference value of the gradient
+    >>> res.df, ref
+    (array([-51.,  -1.,  50.]), array([-51.,  -1.,  50.]))
+
+    As an example of a function with multiple outputs, consider Example 4
+    from [1]_.
+
+    >>> def f(x):
+    ...     x1, x2, x3 = x
+    ...     return [x1, 5*x3, 4*x2**2 - 2*x3, x3*np.sin(x1)]
+
+    The true Jacobian is given by:
+
+    >>> def df(x):
+    ...         x1, x2, x3 = x
+    ...         one = np.ones_like(x1)
+    ...         return [[one, 0*one, 0*one],
+    ...                 [0*one, 0*one, 5*one],
+    ...                 [0*one, 8*x2, -2*one],
+    ...                 [x3*np.cos(x1), 0*one, np.sin(x1)]]
+
+    Evaluate the Jacobian at an arbitrary point.
+
+    >>> rng = np.random.default_rng(389252938452)
+    >>> x = rng.random(size=3)
+    >>> res = jacobian(f, x)
+    >>> ref = df(x)
+    >>> res.df.shape == (4, 3)
+    True
+    >>> np.allclose(res.df, ref)
+    True
+
+    Evaluate the Jacobian at 10 arbitrary points in a single call.
+
+    >>> x = rng.random(size=(3, 10))
+    >>> res = jacobian(f, x)
+    >>> ref = df(x)
+    >>> res.df.shape == (4, 3, 10)
+    True
+    >>> np.allclose(res.df, ref)
+    True
+
+    """
+    xp = array_namespace(x)
+    x = xp.asarray(x)
+    int_dtype = xp.isdtype(x.dtype, 'integral')
+    x0 = xp.asarray(x, dtype=xp.asarray(1.0).dtype) if int_dtype else x
+
+    if x0.ndim < 1:
+        message = "Argument `x` must be at least 1-D."
+        raise ValueError(message)
+
+    m = x0.shape[0]
+    i = xp.arange(m)
+
+    def wrapped(x):
+        p = () if x.ndim == x0.ndim else (x.shape[-1],)  # number of abscissae
+
+        new_shape = (m, m) + x0.shape[1:] + p
+        xph = xp.expand_dims(x0, axis=1)
+        if x.ndim != x0.ndim:
+            xph = xp.expand_dims(xph, axis=-1)
+        xph = xp_copy(xp.broadcast_to(xph, new_shape), xp=xp)
+        xph[i, i] = x
+        return f(xph)
+
+    res = derivative(wrapped, x, tolerances=tolerances,
+                     maxiter=maxiter, order=order, initial_step=initial_step,
+                     step_factor=step_factor, preserve_shape=True,
+                     step_direction=step_direction)
+
+    del res.x  # the user knows `x`, and the way it gets broadcasted is meaningless here
+    return res
+
+
+def hessian(f, x, *, tolerances=None, maxiter=10,
+            order=8, initial_step=0.5, step_factor=2.0):
+    r"""Evaluate the Hessian of a function numerically.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Hessian is desired. The signature must be::
+
+            f(xi: ndarray) -> ndarray
+
+        where each element of ``xi`` is a finite real. If the function to be
+        differentiated accepts additional arguments, wrap it (e.g. using
+        `functools.partial` or ``lambda``) and pass the wrapped callable
+        into `hessian`. `f` must not mutate the array ``xi``. See Notes
+        regarding vectorization and the dimensionality of the input and output.
+    x : float array_like
+        Points at which to evaluate the Hessian. Must have at least one dimension.
+        See Notes regarding the dimensionality and vectorization.
+    tolerances : dictionary of floats, optional
+        Absolute and relative tolerances. Valid keys of the dictionary are:
+
+        - ``atol`` - absolute tolerance on the derivative
+        - ``rtol`` - relative tolerance on the derivative
+
+        Iteration will stop when ``res.error < atol + rtol * abs(res.df)``. The default
+        `atol` is the smallest normal number of the appropriate dtype, and
+        the default `rtol` is the square root of the precision of the
+        appropriate dtype.
+    order : int, default: 8
+        The (positive integer) order of the finite difference formula to be
+        used. Odd integers will be rounded up to the next even integer.
+    initial_step : float, default: 0.5
+        The (absolute) initial step size for the finite difference derivative
+        approximation.
+    step_factor : float, default: 2.0
+        The factor by which the step size is *reduced* in each iteration; i.e.
+        the step size in iteration 1 is ``initial_step/step_factor``. If
+        ``step_factor < 1``, subsequent steps will be greater than the initial
+        step; this may be useful if steps smaller than some threshold are
+        undesirable (e.g. due to subtractive cancellation error).
+    maxiter : int, default: 10
+        The maximum number of iterations of the algorithm to perform. See
+        Notes.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.
+
+        success : bool array
+            ``True`` where the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : The error estimate increased, so iteration was terminated.
+            - ``-2`` : The maximum number of iterations was reached.
+            - ``-3`` : A non-finite value was encountered.
+
+        ddf : float array
+            The Hessian of `f` at `x`, if the algorithm terminated
+            successfully.
+        error : float array
+            An estimate of the error: the magnitude of the difference between
+            the current estimate of the Hessian and the estimate in the
+            previous iteration.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+        Each element of an attribute is associated with the corresponding
+        element of `ddf`. For instance, element ``[i, j]`` of `nfev` is the
+        number of points at which `f` was evaluated for the sake of
+        computing element ``[i, j]`` of `ddf`.
+
+    See Also
+    --------
+    derivative, jacobian
+
+    Notes
+    -----
+    Suppose we wish to evaluate the Hessian of a function
+    :math:`f: \mathbf{R}^m \rightarrow \mathbf{R}`, and we assign to variable
+    ``m`` the positive integer value of :math:`m`. If we wish to evaluate
+    the Hessian at a single point, then:
+
+    - argument `x` must be an array of shape ``(m,)``
+    - argument `f` must be vectorized to accept an array of shape
+      ``(m, ...)``. The first axis represents the :math:`m` inputs of
+      :math:`f`; the remaining axes indicated by ellipses are for evaluating
+      the function at several abscissae in a single call.
+    - argument `f` must return an array of shape ``(...)``.
+    - attribute ``dff`` of the result object will be an array of shape ``(m, m)``,
+      the Hessian.
+
+    This function is also vectorized in the sense that the Hessian can be
+    evaluated at ``k`` points in a single call. In this case, `x` would be an
+    array of shape ``(m, k)``, `f` would accept an array of shape
+    ``(m, ...)`` and return an array of shape ``(...)``, and the ``ddf``
+    attribute of the result would have shape ``(m, m, k)``. Note that the
+    axis associated with the ``k`` points is included within the axes
+    denoted by ``(...)``.
+
+    Currently, `hessian` is implemented by nesting calls to `jacobian`.
+    All options passed to `hessian` are used for both the inner and outer
+    calls with one exception: the `rtol` used in the inner `jacobian` call
+    is tightened by a factor of 100 with the expectation that the inner
+    error can be ignored. A consequence is that `rtol` should not be set
+    less than 100 times the precision of the dtype of `x`; a warning is
+    emitted otherwise.
+
+    References
+    ----------
+    .. [1] Hessian matrix, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Hessian_matrix
+
+    Examples
+    --------
+    The Rosenbrock function maps from :math:`\mathbf{R}^m \rightarrow \mathbf{R}`;
+    the SciPy implementation `scipy.optimize.rosen` is vectorized to accept an
+    array of shape ``(m, ...)`` and return an array of shape ``...``. Suppose we
+    wish to evaluate the Hessian at ``[0.5, 0.5, 0.5]``.
+
+    >>> import numpy as np
+    >>> from scipy.differentiate import hessian
+    >>> from scipy.optimize import rosen, rosen_hess
+    >>> m = 3
+    >>> x = np.full(m, 0.5)
+    >>> res = hessian(rosen, x)
+    >>> ref = rosen_hess(x)  # reference value of the Hessian
+    >>> np.allclose(res.ddf, ref)
+    True
+
+    `hessian` is vectorized to evaluate the Hessian at multiple points
+    in a single call.
+
+    >>> rng = np.random.default_rng(4589245925010)
+    >>> x = rng.random((m, 10))
+    >>> res = hessian(rosen, x)
+    >>> ref = [rosen_hess(xi) for xi in x.T]
+    >>> ref = np.moveaxis(ref, 0, -1)
+    >>> np.allclose(res.ddf, ref)
+    True
+
+    """
+    # todo:
+    # - add ability to vectorize over additional parameters (*args?)
+    # - error estimate stack with inner jacobian (or use legit 2D stencil)
+
+    kwargs = dict(maxiter=maxiter, order=order, initial_step=initial_step,
+                  step_factor=step_factor)
+    tolerances = {} if tolerances is None else tolerances
+    atol = tolerances.get('atol', None)
+    rtol = tolerances.get('rtol', None)
+
+    xp = array_namespace(x)
+    x = xp.asarray(x)
+    dtype = x.dtype if not xp.isdtype(x.dtype, 'integral') else xp.asarray(1.).dtype
+    finfo = xp.finfo(dtype)
+    rtol = finfo.eps**0.5 if rtol is None else rtol  # keep same as `derivative`
+
+    # tighten the inner tolerance to make the inner error negligible
+    rtol_min = finfo.eps * 100
+    message = (f"The specified `{rtol=}`, but error estimates are likely to be "
+               f"unreliable when `rtol < {rtol_min}`.")
+    if 0 < rtol < rtol_min:  # rtol <= 0 is an error
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+        rtol = rtol_min
+
+    def df(x):
+        tolerances = dict(rtol=rtol/100, atol=atol)
+        temp = jacobian(f, x, tolerances=tolerances, **kwargs)
+        nfev.append(temp.nfev if len(nfev) == 0 else temp.nfev.sum(axis=-1))
+        return temp.df
+
+    nfev = []  # track inner function evaluations
+    res = jacobian(df, x, tolerances=tolerances, **kwargs)  # jacobian of jacobian
+
+    nfev = xp.cumulative_sum(xp.stack(nfev), axis=0)
+    res_nit = xp.astype(res.nit[xp.newaxis, ...], xp.int64)  # appease torch
+    res.nfev = xp_take_along_axis(nfev, res_nit, axis=0)[0]
+    res.ddf = res.df
+    del res.df  # this is renamed to ddf
+    del res.nit  # this is only the outer-jacobian nit
+
+    return res
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/test_differentiate.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/test_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..64bc8193cc237465e9427300bedfac8712963e4c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/differentiate/tests/test_differentiate.py
@@ -0,0 +1,695 @@
+import math
+import pytest
+
+import numpy as np
+
+from scipy.conftest import array_api_compatible
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal, xp_assert_less
+from scipy._lib._array_api import is_numpy, is_torch, array_namespace
+
+from scipy import stats, optimize, special
+from scipy.differentiate import derivative, jacobian, hessian
+from scipy.differentiate._differentiate import _EERRORINCREASE
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+
+array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.'
+jax_skip_reason = 'JAX arrays do not support item assignment.'
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+class TestDerivative:
+
+    def f(self, x):
+        return special.ndtr(x)
+
+    @pytest.mark.parametrize('x', [0.6, np.linspace(-0.05, 1.05, 10)])
+    def test_basic(self, x, xp):
+        # Invert distribution CDF and compare against distribution `ppf`
+        default_dtype = xp.asarray(1.).dtype
+        res = derivative(self.f, xp.asarray(x, dtype=default_dtype))
+        ref = xp.asarray(stats.norm().pdf(x), dtype=default_dtype)
+        xp_assert_close(res.df, ref)
+        # This would be nice, but doesn't always work out. `error` is an
+        # estimate, not a bound.
+        if not is_torch(xp):
+            xp_assert_less(xp.abs(res.df - ref), res.error)
+
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.parametrize('case', stats._distr_params.distcont)
+    def test_accuracy(self, case):
+        distname, params = case
+        dist = getattr(stats, distname)(*params)
+        x = dist.median() + 0.1
+        res = derivative(dist.cdf, x)
+        ref = dist.pdf(x)
+        xp_assert_close(res.df, ref, atol=1e-10)
+
+    @pytest.mark.parametrize('order', [1, 6])
+    @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+    def test_vectorization(self, order, shape, xp):
+        # Test for correct functionality, output shapes, and dtypes for various
+        # input shapes.
+        x = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6
+        n = np.size(x)
+        state = {}
+
+        @np.vectorize
+        def _derivative_single(x):
+            return derivative(self.f, x, order=order)
+
+        def f(x, *args, **kwargs):
+            state['nit'] += 1
+            state['feval'] += 1 if (x.size == n or x.ndim <=1) else x.shape[-1]
+            return self.f(x, *args, **kwargs)
+
+        state['nit'] = -1
+        state['feval'] = 0
+
+        res = derivative(f, xp.asarray(x, dtype=xp.float64), order=order)
+        refs = _derivative_single(x).ravel()
+
+        ref_x = [ref.x for ref in refs]
+        xp_assert_close(xp.reshape(res.x, (-1,)), xp.asarray(ref_x))
+
+        ref_df = [ref.df for ref in refs]
+        xp_assert_close(xp.reshape(res.df, (-1,)), xp.asarray(ref_df))
+
+        ref_error = [ref.error for ref in refs]
+        xp_assert_close(xp.reshape(res.error, (-1,)), xp.asarray(ref_error),
+                        atol=1e-12)
+
+        ref_success = [bool(ref.success) for ref in refs]
+        xp_assert_equal(xp.reshape(res.success, (-1,)), xp.asarray(ref_success))
+
+        ref_flag = [np.int32(ref.status) for ref in refs]
+        xp_assert_equal(xp.reshape(res.status, (-1,)), xp.asarray(ref_flag))
+
+        ref_nfev = [np.int32(ref.nfev) for ref in refs]
+        xp_assert_equal(xp.reshape(res.nfev, (-1,)), xp.asarray(ref_nfev))
+        if is_numpy(xp):  # can't expect other backends to be exactly the same
+            assert xp.max(res.nfev) == state['feval']
+
+        ref_nit = [np.int32(ref.nit) for ref in refs]
+        xp_assert_equal(xp.reshape(res.nit, (-1,)), xp.asarray(ref_nit))
+        if is_numpy(xp):  # can't expect other backends to be exactly the same
+            assert xp.max(res.nit) == state['nit']
+
+    def test_flags(self, xp):
+        # Test cases that should produce different status flags; show that all
+        # can be produced simultaneously.
+        rng = np.random.default_rng(5651219684984213)
+        def f(xs, js):
+            f.nit += 1
+            funcs = [lambda x: x - 2.5,  # converges
+                     lambda x: xp.exp(x)*rng.random(),  # error increases
+                     lambda x: xp.exp(x),  # reaches maxiter due to order=2
+                     lambda x: xp.full_like(x, xp.nan)]  # stops due to NaN
+            res = [funcs[int(j)](x) for x, j in zip(xs, xp.reshape(js, (-1,)))]
+            return xp.stack(res)
+        f.nit = 0
+
+        args = (xp.arange(4, dtype=xp.int64),)
+        res = derivative(f, xp.ones(4, dtype=xp.float64),
+                         tolerances=dict(rtol=1e-14),
+                         order=2, args=args)
+
+        ref_flags = xp.asarray([eim._ECONVERGED,
+                                _EERRORINCREASE,
+                                eim._ECONVERR,
+                                eim._EVALUEERR], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_flags_preserve_shape(self, xp):
+        # Same test as above but using `preserve_shape` option to simplify.
+        rng = np.random.default_rng(5651219684984213)
+        def f(x):
+            out = [x - 2.5,  # converges
+                   xp.exp(x)*rng.random(),  # error increases
+                   xp.exp(x),  # reaches maxiter due to order=2
+                   xp.full_like(x, xp.nan)]  # stops due to NaN
+            return xp.stack(out)
+
+        res = derivative(f, xp.asarray(1, dtype=xp.float64),
+                         tolerances=dict(rtol=1e-14),
+                         order=2, preserve_shape=True)
+
+        ref_flags = xp.asarray([eim._ECONVERGED,
+                                _EERRORINCREASE,
+                                eim._ECONVERR,
+                                eim._EVALUEERR], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_preserve_shape(self, xp):
+        # Test `preserve_shape` option
+        def f(x):
+            out = [x, xp.sin(3*x), x+xp.sin(10*x), xp.sin(20*x)*(x-1)**2]
+            return xp.stack(out)
+
+        x = xp.asarray(0.)
+        ref = xp.asarray([xp.asarray(1), 3*xp.cos(3*x), 1+10*xp.cos(10*x),
+                          20*xp.cos(20*x)*(x-1)**2 + 2*xp.sin(20*x)*(x-1)])
+        res = derivative(f, x, preserve_shape=True)
+        xp_assert_close(res.df, ref)
+
+    def test_convergence(self, xp):
+        # Test that the convergence tolerances behave as expected
+        x = xp.asarray(1., dtype=xp.float64)
+        f = special.ndtr
+        ref = float(stats.norm.pdf(1.))
+        tolerances0 = dict(atol=0, rtol=0)
+
+        tolerances = tolerances0.copy()
+        tolerances['atol'] = 1e-3
+        res1 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res1.df - ref) < 1e-3
+        tolerances['atol'] = 1e-6
+        res2 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res2.df - ref) < 1e-6
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        tolerances = tolerances0.copy()
+        tolerances['rtol'] = 1e-3
+        res1 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res1.df - ref) < 1e-3 * ref
+        tolerances['rtol'] = 1e-6
+        res2 = derivative(f, x, tolerances=tolerances, order=4)
+        assert abs(res2.df - ref) < 1e-6 * ref
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+    def test_step_parameters(self, xp):
+        # Test that step factors have the expected effect on accuracy
+        x = xp.asarray(1., dtype=xp.float64)
+        f = special.ndtr
+        ref = float(stats.norm.pdf(1.))
+
+        res1 = derivative(f, x, initial_step=0.5, maxiter=1)
+        res2 = derivative(f, x, initial_step=0.05, maxiter=1)
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        res1 = derivative(f, x, step_factor=2, maxiter=1)
+        res2 = derivative(f, x, step_factor=20, maxiter=1)
+        assert abs(res2.df - ref) < abs(res1.df - ref)
+
+        # `step_factor` can be less than 1: `initial_step` is the minimum step
+        kwargs = dict(order=4, maxiter=1, step_direction=0)
+        res = derivative(f, x, initial_step=0.5, step_factor=0.5, **kwargs)
+        ref = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+        # This is a similar test for one-sided difference
+        kwargs = dict(order=2, maxiter=1, step_direction=1)
+        res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+        kwargs['step_direction'] = -1
+        res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+        ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+        xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+    def test_step_direction(self, xp):
+        # test that `step_direction` works as expected
+        def f(x):
+            y = xp.exp(x)
+            y[(x < 0) + (x > 2)] = xp.nan
+            return y
+
+        x = xp.linspace(0, 2, 10)
+        step_direction = xp.zeros_like(x)
+        step_direction[x < 0.6], step_direction[x > 1.4] = 1, -1
+        res = derivative(f, x, step_direction=step_direction)
+        xp_assert_close(res.df, xp.exp(x))
+        assert xp.all(res.success)
+
+    def test_vectorized_step_direction_args(self, xp):
+        # test that `step_direction` and `args` are vectorized properly
+        def f(x, p):
+            return x ** p
+
+        def df(x, p):
+            return p * x ** (p - 1)
+
+        x = xp.reshape(xp.asarray([1, 2, 3, 4]), (-1, 1, 1))
+        hdir = xp.reshape(xp.asarray([-1, 0, 1]), (1, -1, 1))
+        p = xp.reshape(xp.asarray([2, 3]), (1, 1, -1))
+        res = derivative(f, x, step_direction=hdir, args=(p,))
+        ref = xp.broadcast_to(df(x, p), res.df.shape)
+        ref = xp.asarray(ref, dtype=xp.asarray(1.).dtype)
+        xp_assert_close(res.df, ref)
+
+    def test_initial_step(self, xp):
+        # Test that `initial_step` works as expected and is vectorized
+        def f(x):
+            return xp.exp(x)
+
+        x = xp.asarray(0., dtype=xp.float64)
+        step_direction = xp.asarray([-1, 0, 1])
+        h0 = xp.reshape(xp.logspace(-3, 0, 10), (-1, 1))
+        res = derivative(f, x, initial_step=h0, order=2, maxiter=1,
+                         step_direction=step_direction)
+        err = xp.abs(res.df - f(x))
+
+        # error should be smaller for smaller step sizes
+        assert xp.all(err[:-1, ...] < err[1:, ...])
+
+        # results of vectorized call should match results with
+        # initial_step taken one at a time
+        for i in range(h0.shape[0]):
+            ref = derivative(f, x, initial_step=h0[i, 0], order=2, maxiter=1,
+                             step_direction=step_direction)
+            xp_assert_close(res.df[i, :], ref.df, rtol=1e-14)
+
+    def test_maxiter_callback(self, xp):
+        # Test behavior of `maxiter` parameter and `callback` interface
+        x = xp.asarray(0.612814, dtype=xp.float64)
+        maxiter = 3
+
+        def f(x):
+            res = special.ndtr(x)
+            return res
+
+        default_order = 8
+        res = derivative(f, x, maxiter=maxiter, tolerances=dict(rtol=1e-15))
+        assert not xp.any(res.success)
+        assert xp.all(res.nfev == default_order + 1 + (maxiter - 1)*2)
+        assert xp.all(res.nit == maxiter)
+
+        def callback(res):
+            callback.iter += 1
+            callback.res = res
+            assert hasattr(res, 'x')
+            assert float(res.df) not in callback.dfs
+            callback.dfs.add(float(res.df))
+            assert res.status == eim._EINPROGRESS
+            if callback.iter == maxiter:
+                raise StopIteration
+        callback.iter = -1  # callback called once before first iteration
+        callback.res = None
+        callback.dfs = set()
+
+        res2 = derivative(f, x, callback=callback, tolerances=dict(rtol=1e-15))
+        # terminating with callback is identical to terminating due to maxiter
+        # (except for `status`)
+        for key in res.keys():
+            if key == 'status':
+                assert res[key] == eim._ECONVERR
+                assert res2[key] == eim._ECALLBACK
+            else:
+                assert res2[key] == callback.res[key] == res[key]
+
+    @pytest.mark.parametrize("hdir", (-1, 0, 1))
+    @pytest.mark.parametrize("x", (0.65, [0.65, 0.7]))
+    @pytest.mark.parametrize("dtype", ('float16', 'float32', 'float64'))
+    def test_dtype(self, hdir, x, dtype, xp):
+        if dtype == 'float16' and not is_numpy(xp):
+            pytest.skip('float16 not tested for alternative backends')
+
+        # Test that dtypes are preserved
+        dtype = getattr(xp, dtype)
+        x = xp.asarray(x, dtype=dtype)
+
+        def f(x):
+            assert x.dtype == dtype
+            return xp.exp(x)
+
+        def callback(res):
+            assert res.x.dtype == dtype
+            assert res.df.dtype == dtype
+            assert res.error.dtype == dtype
+
+        res = derivative(f, x, order=4, step_direction=hdir, callback=callback)
+        assert res.x.dtype == dtype
+        assert res.df.dtype == dtype
+        assert res.error.dtype == dtype
+        eps = xp.finfo(dtype).eps
+        # not sure why torch is less accurate here; might be worth investigating
+        rtol = eps**0.5 * 50 if is_torch(xp) else eps**0.5
+        xp_assert_close(res.df, xp.exp(res.x), rtol=rtol)
+
+    def test_input_validation(self, xp):
+        # Test input validation for appropriate error messages
+        one = xp.asarray(1)
+
+        message = '`f` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            derivative(None, one)
+
+        message = 'Abscissae and function output must be real numbers.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, xp.asarray(-4+1j))
+
+        message = "When `preserve_shape=False`, the shape of the array..."
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: [1, 2, 3], xp.asarray([-2, -3]))
+
+        message = 'Tolerances and step parameters must be non-negative...'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, tolerances=dict(atol=-1))
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, tolerances=dict(rtol='ekki'))
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, step_factor=object())
+
+        message = '`maxiter` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, maxiter=1.5)
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, maxiter=0)
+
+        message = '`order` must be a positive integer'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, order=1.5)
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, order=0)
+
+        message = '`preserve_shape` must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, preserve_shape='herring')
+
+        message = '`callback` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            derivative(lambda x: x, one, callback='shrubbery')
+
+    def test_special_cases(self, xp):
+        # Test edge cases and other special cases
+
+        # Test that integers are not passed to `f`
+        # (otherwise this would overflow)
+        def f(x):
+            xp_test = array_namespace(x)  # needs `isdtype`
+            assert xp_test.isdtype(x.dtype, 'real floating')
+            return x ** 99 - 1
+
+        if not is_torch(xp):  # torch defaults to float32
+            res = derivative(f, xp.asarray(7), tolerances=dict(rtol=1e-10))
+            assert res.success
+            xp_assert_close(res.df, xp.asarray(99*7.**98))
+
+        # Test invalid step size and direction
+        res = derivative(xp.exp, xp.asarray(1), step_direction=xp.nan)
+        xp_assert_equal(res.df, xp.asarray(xp.nan))
+        xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+        res = derivative(xp.exp, xp.asarray(1), initial_step=0)
+        xp_assert_equal(res.df, xp.asarray(xp.nan))
+        xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+        # Test that if success is achieved in the correct number
+        # of iterations if function is a polynomial. Ideally, all polynomials
+        # of order 0-2 would get exact result with 0 refinement iterations,
+        # all polynomials of order 3-4 would be differentiated exactly after
+        # 1 iteration, etc. However, it seems that `derivative` needs an
+        # extra iteration to detect convergence based on the error estimate.
+
+        for n in range(6):
+            x = xp.asarray(1.5, dtype=xp.float64)
+            def f(x):
+                return 2*x**n
+
+            ref = 2*n*x**(n-1)
+
+            res = derivative(f, x, maxiter=1, order=max(1, n))
+            xp_assert_close(res.df, ref, rtol=1e-15)
+            xp_assert_equal(res.error, xp.asarray(xp.nan, dtype=xp.float64))
+
+            res = derivative(f, x, order=max(1, n))
+            assert res.success
+            assert res.nit == 2
+            xp_assert_close(res.df, ref, rtol=1e-15)
+
+        # Test scalar `args` (not in tuple)
+        def f(x, c):
+            return c*x - 1
+
+        res = derivative(f, xp.asarray(2), args=xp.asarray(3))
+        xp_assert_close(res.df, xp.asarray(3.))
+
+    # no need to run a test on multiple backends if it's xfailed
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.xfail
+    @pytest.mark.parametrize("case", (  # function, evaluation point
+        (lambda x: (x - 1) ** 3, 1),
+        (lambda x: np.where(x > 1, (x - 1) ** 5, (x - 1) ** 3), 1)
+    ))
+    def test_saddle_gh18811(self, case):
+        # With default settings, `derivative` will not always converge when
+        # the true derivative is exactly zero. This tests that specifying a
+        # (tight) `atol` alleviates the problem. See discussion in gh-18811.
+        atol = 1e-16
+        res = derivative(*case, step_direction=[-1, 0, 1], atol=atol)
+        assert np.all(res.success)
+        xp_assert_close(res.df, 0, atol=atol)
+
+
+class JacobianHessianTest:
+    def test_iv(self, xp):
+        jh_func = self.jh_func.__func__
+
+        # Test input validation
+        message = "Argument `x` must be at least 1-D."
+        with pytest.raises(ValueError, match=message):
+            jh_func(xp.sin, 1, tolerances=dict(atol=-1))
+
+        # Confirm that other parameters are being passed to `derivative`,
+        # which raises an appropriate error message.
+        x = xp.ones(3)
+        func = optimize.rosen
+        message = 'Tolerances and step parameters must be non-negative scalars.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, tolerances=dict(atol=-1))
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, tolerances=dict(rtol=-1))
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, step_factor=-1)
+
+        message = '`order` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, order=-1)
+
+        message = '`maxiter` must be a positive integer.'
+        with pytest.raises(ValueError, match=message):
+            jh_func(func, x, maxiter=-1)
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+class TestJacobian(JacobianHessianTest):
+    jh_func = jacobian
+
+    # Example functions and Jacobians from Wikipedia:
+    # https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant#Examples
+
+    def f1(z, xp):
+        x, y = z
+        return xp.stack([x ** 2 * y, 5 * x + xp.sin(y)])
+
+    def df1(z):
+        x, y = z
+        return [[2 * x * y, x ** 2], [np.full_like(x, 5), np.cos(y)]]
+
+    f1.mn = 2, 2  # type: ignore[attr-defined]
+    f1.ref = df1  # type: ignore[attr-defined]
+
+    def f2(z, xp):
+        r, phi = z
+        return xp.stack([r * xp.cos(phi), r * xp.sin(phi)])
+
+    def df2(z):
+        r, phi = z
+        return [[np.cos(phi), -r * np.sin(phi)],
+                [np.sin(phi), r * np.cos(phi)]]
+
+    f2.mn = 2, 2  # type: ignore[attr-defined]
+    f2.ref = df2  # type: ignore[attr-defined]
+
+    def f3(z, xp):
+        r, phi, th = z
+        return xp.stack([r * xp.sin(phi) * xp.cos(th), r * xp.sin(phi) * xp.sin(th),
+                         r * xp.cos(phi)])
+
+    def df3(z):
+        r, phi, th = z
+        return [[np.sin(phi) * np.cos(th), r * np.cos(phi) * np.cos(th),
+                 -r * np.sin(phi) * np.sin(th)],
+                [np.sin(phi) * np.sin(th), r * np.cos(phi) * np.sin(th),
+                 r * np.sin(phi) * np.cos(th)],
+                [np.cos(phi), -r * np.sin(phi), np.zeros_like(r)]]
+
+    f3.mn = 3, 3  # type: ignore[attr-defined]
+    f3.ref = df3  # type: ignore[attr-defined]
+
+    def f4(x, xp):
+        x1, x2, x3 = x
+        return xp.stack([x1, 5 * x3, 4 * x2 ** 2 - 2 * x3, x3 * xp.sin(x1)])
+
+    def df4(x):
+        x1, x2, x3 = x
+        one = np.ones_like(x1)
+        return [[one, 0 * one, 0 * one],
+                [0 * one, 0 * one, 5 * one],
+                [0 * one, 8 * x2, -2 * one],
+                [x3 * np.cos(x1), 0 * one, np.sin(x1)]]
+
+    f4.mn = 3, 4  # type: ignore[attr-defined]
+    f4.ref = df4  # type: ignore[attr-defined]
+
+    def f5(x, xp):
+        x1, x2, x3 = x
+        return xp.stack([5 * x2, 4 * x1 ** 2 - 2 * xp.sin(x2 * x3), x2 * x3])
+
+    def df5(x):
+        x1, x2, x3 = x
+        one = np.ones_like(x1)
+        return [[0 * one, 5 * one, 0 * one],
+                [8 * x1, -2 * x3 * np.cos(x2 * x3), -2 * x2 * np.cos(x2 * x3)],
+                [0 * one, x3, x2]]
+
+    f5.mn = 3, 3  # type: ignore[attr-defined]
+    f5.ref = df5  # type: ignore[attr-defined]
+
+    def rosen(x, _): return optimize.rosen(x)
+    rosen.mn = 5, 1  # type: ignore[attr-defined]
+    rosen.ref = optimize.rosen_der  # type: ignore[attr-defined]
+
+    @pytest.mark.parametrize('dtype', ('float32', 'float64'))
+    @pytest.mark.parametrize('size', [(), (6,), (2, 3)])
+    @pytest.mark.parametrize('func', [f1, f2, f3, f4, f5, rosen])
+    def test_examples(self, dtype, size, func, xp):
+        atol = 1e-10 if dtype == 'float64' else 1.99e-3
+        dtype = getattr(xp, dtype)
+        rng = np.random.default_rng(458912319542)
+        m, n = func.mn
+        x = rng.random(size=(m,) + size)
+        res = jacobian(lambda x: func(x , xp), xp.asarray(x, dtype=dtype))
+        # convert list of arrays to single array before converting to xp array
+        ref = xp.asarray(np.asarray(func.ref(x)), dtype=dtype)
+        xp_assert_close(res.df, ref, atol=atol)
+
+    def test_attrs(self, xp):
+        # Test attributes of result object
+        z = xp.asarray([0.5, 0.25])
+
+        # case in which some elements of the Jacobian are harder
+        # to calculate than others
+        def df1(z):
+            x, y = z
+            return xp.stack([xp.cos(0.5*x) * xp.cos(y), xp.sin(2*x) * y**2])
+
+        def df1_0xy(x, y):
+            return xp.cos(0.5*x) * xp.cos(y)
+
+        def df1_1xy(x, y):
+            return xp.sin(2*x) * y**2
+
+        res = jacobian(df1, z, initial_step=10)
+        if is_numpy(xp):
+            assert len(np.unique(res.nit)) == 4
+            assert len(np.unique(res.nfev)) == 4
+
+        res00 = jacobian(lambda x: df1_0xy(x, z[1]), z[0:1], initial_step=10)
+        res01 = jacobian(lambda y: df1_0xy(z[0], y), z[1:2], initial_step=10)
+        res10 = jacobian(lambda x: df1_1xy(x, z[1]), z[0:1], initial_step=10)
+        res11 = jacobian(lambda y: df1_1xy(z[0], y), z[1:2], initial_step=10)
+        ref = optimize.OptimizeResult()
+        for attr in ['success', 'status', 'df', 'nit', 'nfev']:
+            ref_attr = xp.asarray([[getattr(res00, attr), getattr(res01, attr)],
+                                   [getattr(res10, attr), getattr(res11, attr)]])
+            ref[attr] = xp.squeeze(ref_attr)
+            rtol = 1.5e-5 if res[attr].dtype == xp.float32 else 1.5e-14
+            xp_assert_close(res[attr], ref[attr], rtol=rtol)
+
+    def test_step_direction_size(self, xp):
+        # Check that `step_direction` and `initial_step` can be used to ensure that
+        # the usable domain of a function is respected.
+        rng = np.random.default_rng(23892589425245)
+        b = rng.random(3)
+        eps = 1e-7  # torch needs wiggle room?
+
+        def f(x):
+            x[0, x[0] < b[0]] = xp.nan
+            x[0, x[0] > b[0] + 0.25] = xp.nan
+            x[1, x[1] > b[1]] = xp.nan
+            x[1, x[1] < b[1] - 0.1-eps] = xp.nan
+            return TestJacobian.f5(x, xp)
+
+        dir = [1, -1, 0]
+        h0 = [0.25, 0.1, 0.5]
+        atol = {'atol': 1e-8}
+        res = jacobian(f, xp.asarray(b, dtype=xp.float64), initial_step=h0,
+                       step_direction=dir, tolerances=atol)
+        ref = xp.asarray(TestJacobian.df5(b), dtype=xp.float64)
+        xp_assert_close(res.df, ref, atol=1e-8)
+        assert xp.all(xp.isfinite(ref))
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+class TestHessian(JacobianHessianTest):
+    jh_func = hessian
+
+    @pytest.mark.parametrize('shape', [(), (4,), (2, 4)])
+    def test_example(self, shape, xp):
+        rng = np.random.default_rng(458912319542)
+        m = 3
+        x = xp.asarray(rng.random((m,) + shape), dtype=xp.float64)
+        res = hessian(optimize.rosen, x)
+        if shape:
+            x = xp.reshape(x, (m, -1))
+            ref = xp.stack([optimize.rosen_hess(xi) for xi in x.T])
+            ref = xp.moveaxis(ref, 0, -1)
+            ref = xp.reshape(ref, (m, m,) + shape)
+        else:
+            ref = optimize.rosen_hess(x)
+        xp_assert_close(res.ddf, ref, atol=1e-8)
+
+        # # Removed symmetry enforcement; consider adding back in as a feature
+        # # check symmetry
+        # for key in ['ddf', 'error', 'nfev', 'success', 'status']:
+        #     assert_equal(res[key], np.swapaxes(res[key], 0, 1))
+
+    def test_float32(self, xp):
+        rng = np.random.default_rng(458912319542)
+        x = xp.asarray(rng.random(3), dtype=xp.float32)
+        res = hessian(optimize.rosen, x)
+        ref = optimize.rosen_hess(x)
+        mask = (ref != 0)
+        xp_assert_close(res.ddf[mask], ref[mask])
+        atol = 1e-2 * xp.abs(xp.min(ref[mask]))
+        xp_assert_close(res.ddf[~mask], ref[~mask], atol=atol)
+
+    def test_nfev(self, xp):
+        z = xp.asarray([0.5, 0.25])
+        xp_test = array_namespace(z)
+
+        def f1(z):
+            x, y = xp_test.broadcast_arrays(*z)
+            f1.nfev = f1.nfev + (math.prod(x.shape[2:]) if x.ndim > 2 else 1)
+            return xp.sin(x) * y ** 3
+        f1.nfev = 0
+
+
+        res = hessian(f1, z, initial_step=10)
+        f1.nfev = 0
+        res00 = hessian(lambda x: f1([x[0], z[1]]), z[0:1], initial_step=10)
+        assert res.nfev[0, 0] == f1.nfev == res00.nfev[0, 0]
+
+        f1.nfev = 0
+        res11 = hessian(lambda y: f1([z[0], y[0]]), z[1:2], initial_step=10)
+        assert res.nfev[1, 1] == f1.nfev == res11.nfev[0, 0]
+
+        # Removed symmetry enforcement; consider adding back in as a feature
+        # assert_equal(res.nfev, res.nfev.T)  # check symmetry
+        # assert np.unique(res.nfev).size == 3
+
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason='Python list input uses NumPy backend')
+    def test_small_rtol_warning(self, xp):
+        message = 'The specified `rtol=1e-15`, but...'
+        with pytest.warns(RuntimeWarning, match=message):
+            hessian(xp.sin, [1.], tolerances=dict(rtol=1e-15))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c545a00b9fd63427088ac873fa3fa65678b77f71
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__init__.py
@@ -0,0 +1,114 @@
+"""
+==============================================
+Discrete Fourier transforms (:mod:`scipy.fft`)
+==============================================
+
+.. currentmodule:: scipy.fft
+
+Fast Fourier Transforms (FFTs)
+==============================
+
+.. autosummary::
+   :toctree: generated/
+
+   fft - Fast (discrete) Fourier Transform (FFT)
+   ifft - Inverse FFT
+   fft2 - 2-D FFT
+   ifft2 - 2-D inverse FFT
+   fftn - N-D FFT
+   ifftn - N-D inverse FFT
+   rfft - FFT of strictly real-valued sequence
+   irfft - Inverse of rfft
+   rfft2 - 2-D FFT of real sequence
+   irfft2 - Inverse of rfft2
+   rfftn - N-D FFT of real sequence
+   irfftn - Inverse of rfftn
+   hfft - FFT of a Hermitian sequence (real spectrum)
+   ihfft - Inverse of hfft
+   hfft2 - 2-D FFT of a Hermitian sequence
+   ihfft2 - Inverse of hfft2
+   hfftn - N-D FFT of a Hermitian sequence
+   ihfftn - Inverse of hfftn
+
+Discrete Sin and Cosine Transforms (DST and DCT)
+================================================
+
+.. autosummary::
+   :toctree: generated/
+
+   dct - Discrete cosine transform
+   idct - Inverse discrete cosine transform
+   dctn - N-D Discrete cosine transform
+   idctn - N-D Inverse discrete cosine transform
+   dst - Discrete sine transform
+   idst - Inverse discrete sine transform
+   dstn - N-D Discrete sine transform
+   idstn - N-D Inverse discrete sine transform
+
+Fast Hankel Transforms
+======================
+
+.. autosummary::
+   :toctree: generated/
+
+   fht - Fast Hankel transform
+   ifht - Inverse of fht
+
+Helper functions
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   fftshift - Shift the zero-frequency component to the center of the spectrum
+   ifftshift - The inverse of `fftshift`
+   fftfreq - Return the Discrete Fourier Transform sample frequencies
+   rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
+   fhtoffset - Compute an optimal offset for the Fast Hankel Transform
+   next_fast_len - Find the optimal length to zero-pad an FFT for speed
+   prev_fast_len - Find the maximum slice length that results in a fast FFT
+   set_workers - Context manager to set default number of workers
+   get_workers - Get the current default number of workers
+
+Backend control
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   set_backend - Context manager to set the backend within a fixed scope
+   skip_backend - Context manager to skip a backend within a fixed scope
+   set_global_backend - Sets the global fft backend
+   register_backend - Register a backend for permanent use
+
+"""
+
+from ._basic import (
+    fft, ifft, fft2, ifft2, fftn, ifftn,
+    rfft, irfft, rfft2, irfft2, rfftn, irfftn,
+    hfft, ihfft, hfft2, ihfft2, hfftn, ihfftn)
+from ._realtransforms import dct, idct, dst, idst, dctn, idctn, dstn, idstn
+from ._fftlog import fht, ifht, fhtoffset
+from ._helper import (
+    next_fast_len, prev_fast_len, fftfreq,
+    rfftfreq, fftshift, ifftshift)
+from ._backend import (set_backend, skip_backend, set_global_backend,
+                       register_backend)
+from ._pocketfft.helper import set_workers, get_workers
+
+__all__ = [
+    'fft', 'ifft', 'fft2', 'ifft2', 'fftn', 'ifftn',
+    'rfft', 'irfft', 'rfft2', 'irfft2', 'rfftn', 'irfftn',
+    'hfft', 'ihfft', 'hfft2', 'ihfft2', 'hfftn', 'ihfftn',
+    'fftfreq', 'rfftfreq', 'fftshift', 'ifftshift',
+    'next_fast_len', 'prev_fast_len',
+    'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn',
+    'fht', 'ifht',
+    'fhtoffset',
+    'set_backend', 'skip_backend', 'set_global_backend', 'register_backend',
+    'get_workers', 'set_workers']
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ac7cb4ad89c1ff05f142867fbc883fb94de44eb
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ae920236c6a7448dd854c669c43233b9aaa0000
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7ea6035304a91e7cca4531e8daf19487c020d1a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d5d46c505eaddf0a6f7df7d211e3e1edbdb18e6a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6231ec84ad4991037b43c7ed4172be19e59b0e9
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0438e2b56b7ad1c14517e4c0e4caa16b2ca1e13
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56a7e5f6ddb39125bcd77ef1b924263331855123
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fce333f26ce7f930533c432061feb7922826e8e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b133b07404f4376fd5f22485228e3091f3a711c2
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_backend.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1e5cfcad5c4cbc43276e151d2da33039368630d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_backend.py
@@ -0,0 +1,196 @@
+import scipy._lib.uarray as ua
+from . import _basic_backend
+from . import _realtransforms_backend
+from . import _fftlog_backend
+
+
+class _ScipyBackend:
+    """The default backend for fft calculations
+
+    Notes
+    -----
+    We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray``
+    treats the domain as a hierarchy. This means the user can install a single
+    backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well.
+    """
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+
+        fn = getattr(_basic_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_realtransforms_backend, method.__name__, None)
+        if fn is None:
+            fn = getattr(_fftlog_backend, method.__name__, None)
+        if fn is None:
+            return NotImplemented
+        return fn(*args, **kwargs)
+
+
+_named_backends = {
+    'scipy': _ScipyBackend,
+}
+
+
+def _backend_from_arg(backend):
+    """Maps strings to known backends and validates the backend"""
+
+    if isinstance(backend, str):
+        try:
+            backend = _named_backends[backend]
+        except KeyError as e:
+            raise ValueError(f'Unknown backend {backend}') from e
+
+    if backend.__ua_domain__ != 'numpy.scipy.fft':
+        raise ValueError('Backend does not implement "numpy.scipy.fft"')
+
+    return backend
+
+
+def set_global_backend(backend, coerce=False, only=False, try_last=False):
+    """Sets the global fft backend
+
+    This utility method replaces the default backend for permanent use. It
+    will be tried in the list of backends automatically, unless the
+    ``only`` flag is set on a backend. This will be the first tried
+    backend outside the :obj:`set_backend` context manager.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    coerce : bool
+        Whether to coerce input types when trying this backend.
+    only : bool
+        If ``True``, no more backends will be tried if this fails.
+        Implied by ``coerce=True``.
+    try_last : bool
+        If ``True``, the global backend is tried after registered backends.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Notes
+    -----
+    This will overwrite the previously set global backend, which, by default, is
+    the SciPy implementation.
+
+    Examples
+    --------
+    We can set the global fft backend:
+
+    >>> from scipy.fft import fft, set_global_backend
+    >>> set_global_backend("scipy")  # Sets global backend (default is "scipy").
+    >>> fft([1])  # Calls the global backend
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last)
+
+
+def register_backend(backend):
+    """
+    Register a backend for permanent use.
+
+    Registered backends have the lowest priority and will be tried after the
+    global backend.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    Raises
+    ------
+    ValueError: If the backend does not implement ``numpy.scipy.fft``.
+
+    Examples
+    --------
+    We can register a new fft backend:
+
+    >>> from scipy.fft import fft, register_backend, set_global_backend
+    >>> class NoopBackend:  # Define an invalid Backend
+    ...     __ua_domain__ = "numpy.scipy.fft"
+    ...     def __ua_function__(self, func, args, kwargs):
+    ...          return NotImplemented
+    >>> set_global_backend(NoopBackend())  # Set the invalid backend as global
+    >>> register_backend("scipy")  # Register a new backend
+    # The registered backend is called because
+    # the global backend returns `NotImplemented`
+    >>> fft([1])
+    array([1.+0.j])
+    >>> set_global_backend("scipy")  # Restore global backend to default
+
+    """
+    backend = _backend_from_arg(backend)
+    ua.register_backend(backend)
+
+
+def set_backend(backend, coerce=False, only=False):
+    """Context manager to set the backend within a fixed scope.
+
+    Upon entering the ``with`` statement, the given backend will be added to
+    the list of available backends with the highest priority. Upon exit, the
+    backend is reset to the state before entering the scope.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to use.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+    coerce : bool, optional
+        Whether to allow expensive conversions for the ``x`` parameter. e.g.,
+        copying a NumPy array to the GPU for a CuPy backend. Implies ``only``.
+    only : bool, optional
+        If only is ``True`` and this backend returns ``NotImplemented``, then a
+        BackendNotImplemented error will be raised immediately. Ignoring any
+        lower priority backends.
+
+    Examples
+    --------
+    >>> import scipy.fft as fft
+    >>> with fft.set_backend('scipy', only=True):
+    ...     fft.fft([1])  # Always calls the scipy implementation
+    array([1.+0.j])
+    """
+    backend = _backend_from_arg(backend)
+    return ua.set_backend(backend, coerce=coerce, only=only)
+
+
+def skip_backend(backend):
+    """Context manager to skip a backend within a fixed scope.
+
+    Within the context of a ``with`` statement, the given backend will not be
+    called. This covers backends registered both locally and globally. Upon
+    exit, the backend will again be considered.
+
+    Parameters
+    ----------
+    backend : {object, 'scipy'}
+        The backend to skip.
+        Can either be a ``str`` containing the name of a known backend
+        {'scipy'} or an object that implements the uarray protocol.
+
+    Examples
+    --------
+    >>> import scipy.fft as fft
+    >>> fft.fft([1])  # Calls default SciPy backend
+    array([1.+0.j])
+    >>> with fft.skip_backend('scipy'):  # We explicitly skip the SciPy backend
+    ...     fft.fft([1])                 # leaving no implementation available
+    Traceback (most recent call last):
+        ...
+    BackendNotImplementedError: No selected backends had an implementation ...
+    """
+    backend = _backend_from_arg(backend)
+    return ua.skip_backend(backend)
+
+
+set_global_backend('scipy', try_last=True)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3fc021c9ef9b7c2a40bf7b5138158df8e276ae6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_basic.py
@@ -0,0 +1,1630 @@
+from scipy._lib.uarray import generate_multimethod, Dispatchable
+import numpy as np
+
+
+def _x_replacer(args, kwargs, dispatchables):
+    """
+    uarray argument replacer to replace the transform input array (``x``)
+    """
+    if len(args) > 0:
+        return (dispatchables[0],) + args[1:], kwargs
+    kw = kwargs.copy()
+    kw['x'] = dispatchables[0]
+    return args, kw
+
+
+def _dispatch(func):
+    """
+    Function annotation that creates a uarray multimethod from the function
+    """
+    return generate_multimethod(func, _x_replacer, domain="numpy.scipy.fft")
+
+
+@_dispatch
+def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+        plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) with the efficient Fast Fourier Transform (FFT)
+    algorithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode. Default is "backward", meaning no normalization on
+        the forward transforms and scaling by ``1/n`` on the `ifft`.
+        "forward" instead applies the ``1/n`` factor on the forward transform.
+        For ``norm="ortho"``, both directions are scaled by ``1/sqrt(n)``.
+
+        .. versionadded:: 1.6.0
+           ``norm={"forward", "backward"}`` options were added
+
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See the notes below for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``. See below for more
+        details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        if `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    ifft : The inverse of `fft`.
+    fft2 : The 2-D FFT.
+    fftn : The N-D FFT.
+    rfftn : The N-D FFT of real input.
+    fftfreq : Frequency bins for given FFT parameters.
+    next_fast_len : Size to pad input to for most efficient transforms
+
+    Notes
+    -----
+    FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform
+    (DFT) can be calculated efficiently, by using symmetries in the calculated
+    terms. The symmetry is highest when `n` is a power of 2, and the transform
+    is therefore most efficient for these sizes. For poorly factorizable sizes,
+    `scipy.fft` uses Bluestein's algorithm [2]_ and so is never worse than
+    O(`n` log `n`). Further performance improvements may be seen by zero-padding
+    the input using `next_fast_len`.
+
+    If ``x`` is a 1d array, then the `fft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(-2j * np.pi * k * np.arange(n)/n))
+
+    The frequency term ``f=k/n`` is found at ``y[k]``. At ``y[n/2]`` we reach
+    the Nyquist frequency and wrap around to the negative-frequency terms. So,
+    for an 8-point transform, the frequencies of the result are
+    [0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the
+    zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3],
+    use `fftshift`.
+
+    Transforms can be done in single, double, or extended precision (long
+    double) floating point. Half precision inputs will be converted to single
+    precision and non-floating-point inputs will be converted to double
+    precision.
+
+    If the data type of ``x`` is real, a "real FFT" algorithm is automatically
+    used, which roughly halves the computation time. To increase efficiency
+    a little further, use `rfft`, which does the same calculation, but only
+    outputs half of the symmetrical spectrum. If the data are both real and
+    symmetrical, the `dct` can again double the efficiency, by generating
+    half of the spectrum from half of the signal.
+
+    When ``overwrite_x=True`` is specified, the memory referenced by ``x`` may
+    be used by the implementation in any way. This may include reusing the
+    memory for the result, but this is in no way guaranteed. You should not
+    rely on the contents of ``x`` after the transform as this may change in
+    future without warning.
+
+    The ``workers`` argument specifies the maximum number of parallel jobs to
+    split the FFT computation into. This will execute independent 1-D
+    FFTs within ``x``. So, ``x`` must be at least 2-D and the
+    non-transformed axes must be large enough to split into chunks. If ``x`` is
+    too small, fewer jobs may be used than requested.
+
+    References
+    ----------
+    .. [1] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
+           machine calculation of complex Fourier series," *Math. Comput.*
+           19: 297-301.
+    .. [2] Bluestein, L., 1970, "A linear filtering approach to the
+           computation of discrete Fourier transform". *IEEE Transactions on
+           Audio and Electroacoustics.* 18 (4): 451-455.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
+    array([-2.33486982e-16+1.14423775e-17j,  8.00000000e+00-1.25557246e-15j,
+            2.33486982e-16+2.33486982e-16j,  0.00000000e+00+1.22464680e-16j,
+           -1.14423775e-17+2.33486982e-16j,  0.00000000e+00+5.20784380e-16j,
+            1.14423775e-17+1.14423775e-17j,  0.00000000e+00+1.22464680e-16j])
+
+    In this example, real input has an FFT which is Hermitian, i.e., symmetric
+    in the real part and anti-symmetric in the imaginary part:
+
+    >>> from scipy.fft import fft, fftfreq, fftshift
+    >>> import matplotlib.pyplot as plt
+    >>> t = np.arange(256)
+    >>> sp = fftshift(fft(np.sin(t)))
+    >>> freq = fftshift(fftfreq(t.shape[-1]))
+    >>> plt.plot(freq, sp.real, freq, sp.imag)
+    [,
+     ]
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier transform computed by `fft`.  In other words,
+    ``ifft(fft(x)) == x`` to within numerical accuracy.
+
+    The input should be ordered in the same way as is returned by `fft`,
+    i.e.,
+
+    * ``x[0]`` should contain the zero frequency term,
+    * ``x[1:n//2]`` should contain the positive-frequency terms,
+    * ``x[n//2 + 1:]`` should contain the negative-frequency terms, in
+      increasing order starting from the most negative frequency.
+
+    For an even number of input points, ``x[n//2]`` represents the sum of
+    the values at the positive and negative Nyquist frequencies, as the two
+    are aliased together. See `fft` for details.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    n : int, optional
+        Length of the transformed axis of the output.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+        See notes about padding issues.
+    axis : int, optional
+        Axis over which to compute the inverse DFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+
+    Raises
+    ------
+    IndexError
+        If `axes` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    fft : The 1-D (forward) FFT, of which `ifft` is the inverse.
+    ifft2 : The 2-D inverse FFT.
+    ifftn : The N-D inverse FFT.
+
+    Notes
+    -----
+    If the input parameter `n` is larger than the size of the input, the input
+    is padded by appending zeros at the end. Even though this is the common
+    approach, it might lead to surprising results. If a different padding is
+    desired, it must be performed before calling `ifft`.
+
+    If ``x`` is a 1-D array, then the `ifft` is equivalent to ::
+
+        y[k] = np.sum(x * np.exp(2j * np.pi * k * np.arange(n)/n)) / len(x)
+
+    As with `fft`, `ifft` has support for all floating point types and is
+    optimized for real input.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> scipy.fft.ifft([0, 4, 0, 0])
+    array([ 1.+0.j,  0.+1.j, -1.+0.j,  0.-1.j]) # may vary
+
+    Create and plot a band-limited signal with random phases:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> t = np.arange(400)
+    >>> n = np.zeros((400,), dtype=complex)
+    >>> n[40:60] = np.exp(1j*rng.uniform(0, 2*np.pi, (20,)))
+    >>> s = scipy.fft.ifft(n)
+    >>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
+    [, ]
+    >>> plt.legend(('real', 'imaginary'))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 1-D discrete Fourier Transform for real input.
+
+    This function computes the 1-D *n*-point discrete Fourier
+    Transform (DFT) of a real-valued array by means of an efficient algorithm
+    called the Fast Fourier Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array
+    n : int, optional
+        Number of points along transformation axis in the input to use.
+        If `n` is smaller than the length of the input, the input is cropped.
+        If it is larger, the input is padded with zeros. If `n` is not given,
+        the length of the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last axis is
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        If `n` is even, the length of the transformed axis is ``(n/2)+1``.
+        If `n` is odd, the length is ``(n+1)/2``.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    irfft : The inverse of `rfft`.
+    fft : The 1-D FFT of general (complex) input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+    rfftn : The N-D FFT of real input.
+
+    Notes
+    -----
+    When the DFT is computed for purely real input, the output is
+    Hermitian-symmetric, i.e., the negative frequency terms are just the complex
+    conjugates of the corresponding positive-frequency terms, and the
+    negative-frequency terms are therefore redundant. This function does not
+    compute the negative frequency terms, and the length of the transformed
+    axis of the output is therefore ``n//2 + 1``.
+
+    When ``X = rfft(x)`` and fs is the sampling frequency, ``X[0]`` contains
+    the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
+
+    If `n` is even, ``A[-1]`` contains the term representing both positive
+    and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
+    real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
+    the largest positive frequency (fs/2*(n-1)/n), and is complex in the
+    general case.
+
+    If the input `a` contains an imaginary part, it is silently discarded.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.fft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j,  0.+1.j]) # may vary
+    >>> scipy.fft.rfft([0, 1, 0, 0])
+    array([ 1.+0.j,  0.-1.j, -1.+0.j]) # may vary
+
+    Notice how the final element of the `fft` output is the complex conjugate
+    of the second element, for real input. For `rfft`, this symmetry is
+    exploited to compute only the non-negative frequency terms.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Computes the inverse of `rfft`.
+
+    This function computes the inverse of the 1-D *n*-point
+    discrete Fourier Transform of real input computed by `rfft`.
+    In other words, ``irfft(rfft(x), len(x)) == x`` to within numerical
+    accuracy. (See Notes below for why ``len(a)`` is necessary here.)
+
+    The input is expected to be in the form returned by `rfft`, i.e., the
+    real zero-frequency term followed by the complex positive frequency terms
+    in order of increasing frequency. Since the discrete Fourier Transform of
+    real input is Hermitian-symmetric, the negative frequency terms are taken
+    to be the complex conjugates of the corresponding positive frequency terms.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output.
+        For `n` output points, ``n//2+1`` input points are necessary. If the
+        input is longer than this, it is cropped. If it is shorter than this,
+        it is padded with zeros. If `n` is not given, it is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along the axis
+        specified by `axis`.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*(m-1)`` where ``m`` is the length of the transformed axis of the
+        input. To get an odd number of output points, `n` must be specified.
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `x`.
+
+    See Also
+    --------
+    rfft : The 1-D FFT of real input, of which `irfft` is inverse.
+    fft : The 1-D FFT.
+    irfft2 : The inverse of the 2-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    Returns the real valued `n`-point inverse discrete Fourier transform
+    of `x`, where `x` contains the non-negative frequency terms of a
+    Hermitian-symmetric sequence. `n` is the length of the result, not the
+    input.
+
+    If you specify an `n` such that `a` must be zero-padded or truncated, the
+    extra/removed values will be added/removed at high frequencies. One can
+    thus resample a series to `m` points via Fourier interpolation by:
+    ``a_resamp = irfft(rfft(a), m)``.
+
+    The default value of `n` assumes an even output length. By the Hermitian
+    symmetry, the last imaginary component must be 0 and so is ignored. To
+    avoid losing information, the correct length of the real input *must* be
+    given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> scipy.fft.ifft([1, -1j, -1, 1j])
+    array([0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]) # may vary
+    >>> scipy.fft.irfft([1, -1j, -1])
+    array([0.,  1.,  0.,  0.])
+
+    Notice how the last term in the input to the ordinary `ifft` is the
+    complex conjugate of the second term, and the output has zero imaginary
+    part everywhere. When calling `irfft`, the negative frequencies are not
+    specified, and the output array is purely real.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
+    spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    n : int, optional
+        Length of the transformed axis of the output. For `n` output
+        points, ``n//2 + 1`` input points are necessary. If the input is
+        longer than this, it is cropped. If it is shorter than this, it is
+        padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``,
+        where ``m`` is the length of the input along the axis specified by
+        `axis`.
+    axis : int, optional
+        Axis over which to compute the FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is `n`, or, if `n` is not given,
+        ``2*m - 2``, where ``m`` is the length of the transformed axis of
+        the input. To get an odd number of output points, `n` must be
+        specified, for instance, as ``2*m - 1`` in the typical case,
+
+    Raises
+    ------
+    IndexError
+        If `axis` is larger than the last axis of `a`.
+
+    See Also
+    --------
+    rfft : Compute the 1-D FFT for real input.
+    ihfft : The inverse of `hfft`.
+    hfftn : Compute the N-D FFT of a Hermitian signal.
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd.
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import fft, hfft
+    >>> import numpy as np
+    >>> a = 2 * np.pi * np.arange(10) / 10
+    >>> signal = np.cos(a) + 3j * np.sin(3 * a)
+    >>> fft(signal).round(10)
+    array([ -0.+0.j,   5.+0.j,  -0.+0.j,  15.-0.j,   0.+0.j,   0.+0.j,
+            -0.+0.j, -15.-0.j,   0.+0.j,   5.+0.j])
+    >>> hfft(signal[:6]).round(10) # Input first half of signal
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    >>> hfft(signal, 10)  # Input entire signal and truncate
+    array([  0.,   5.,   0.,  15.,  -0.,   0.,   0., -15.,  -0.,   5.])
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the inverse FFT of a signal that has Hermitian symmetry.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    n : int, optional
+        Length of the inverse FFT, the number of points along
+        transformation axis in the input to use.  If `n` is smaller than
+        the length of the input, the input is cropped. If it is larger,
+        the input is padded with zeros. If `n` is not given, the length of
+        the input along the axis specified by `axis` is used.
+    axis : int, optional
+        Axis over which to compute the inverse FFT. If not given, the last
+        axis is used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axis
+        indicated by `axis`, or the last one if `axis` is not specified.
+        The length of the transformed axis is ``n//2 + 1``.
+
+    See Also
+    --------
+    hfft, irfft
+
+    Notes
+    -----
+    `hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
+    opposite case: here, the signal has Hermitian symmetry in the time
+    domain and is real in the frequency domain. So, here, it's `hfft`, for
+    which you must supply the length of the result if it is to be odd:
+    * even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
+    * odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
+
+    Examples
+    --------
+    >>> from scipy.fft import ifft, ihfft
+    >>> import numpy as np
+    >>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
+    >>> ifft(spectrum)
+    array([1.+0.j,  2.+0.j,  3.+0.j,  4.+0.j,  3.+0.j,  2.+0.j]) # may vary
+    >>> ihfft(spectrum)
+    array([ 1.-0.j,  2.-0.j,  3.-0.j,  4.-0.j]) # may vary
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the N-D discrete Fourier Transform.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D array by means of the Fast Fourier
+    Transform (FFT).
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifftn : The inverse of `fftn`, the inverse N-D FFT.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfftn : The N-D FFT of real input.
+    fft2 : The 2-D FFT.
+    fftshift : Shifts zero-frequency terms to centre of array.
+
+    Notes
+    -----
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of all axes, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:3, :3, :3][0]
+    >>> scipy.fft.fftn(x, axes=(1, 2))
+    array([[[ 0.+0.j,   0.+0.j,   0.+0.j], # may vary
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[ 9.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]],
+           [[18.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j],
+            [ 0.+0.j,   0.+0.j,   0.+0.j]]])
+    >>> scipy.fft.fftn(x, (2, 2), axes=(0, 1))
+    array([[[ 2.+0.j,  2.+0.j,  2.+0.j], # may vary
+            [ 0.+0.j,  0.+0.j,  0.+0.j]],
+           [[-2.+0.j, -2.+0.j, -2.+0.j],
+            [ 0.+0.j,  0.+0.j,  0.+0.j]]])
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
+    ...                      2 * np.pi * np.arange(200) / 34)
+    >>> S = np.sin(X) + np.cos(Y) + rng.uniform(0, 1, X.shape)
+    >>> FS = scipy.fft.fftn(S)
+    >>> plt.imshow(np.log(np.abs(scipy.fft.fftshift(FS))**2))
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ifftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform over any number of axes in an M-D array by
+    means of the Fast Fourier Transform (FFT).  In other words,
+    ``ifftn(fftn(x)) == x`` to within numerical accuracy.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fftn`, i.e., it should have the term for zero frequency
+    in all axes in the low-order corner, the positive frequency terms in the
+    first half of all axes, the term for the Nyquist frequency in the middle
+    of all axes and the negative frequency terms in the second half of all
+    axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``ifft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used. See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the IFFT.  If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fftn : The forward N-D FFT, of which `ifftn` is the inverse.
+    ifft : The 1-D inverse FFT.
+    ifft2 : The 2-D inverse FFT.
+    ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
+        of array.
+
+    Notes
+    -----
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifftn` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.eye(4)
+    >>> scipy.fft.ifftn(scipy.fft.fftn(x, axes=(0,)), axes=(1,))
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j]])
+
+
+    Create and plot an image with band-limited frequency content:
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> n = np.zeros((200,200), dtype=complex)
+    >>> n[60:80, 20:40] = np.exp(1j*rng.uniform(0, 2*np.pi, (20, 20)))
+    >>> im = scipy.fft.ifftn(n).real
+    >>> plt.imshow(im)
+    
+    >>> plt.show()
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    """
+    Compute the 2-D discrete Fourier Transform
+
+    This function computes the N-D discrete Fourier Transform
+    over any axes in an M-D array by means of the
+    Fast Fourier Transform (FFT). By default, the transform is computed over
+    the last two axes of the input array, i.e., a 2-dimensional FFT.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        This corresponds to ``n`` for ``fft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two axes are
+        used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ifft2 : The inverse 2-D FFT.
+    fft : The 1-D FFT.
+    fftn : The N-D FFT.
+    fftshift : Shifts zero-frequency terms to the center of the array.
+        For 2-D input, swaps first and third quadrants, and second
+        and fourth quadrants.
+
+    Notes
+    -----
+    `fft2` is just `fftn` with a different default for `axes`.
+
+    The output, analogously to `fft`, contains the term for zero frequency in
+    the low-order corner of the transformed axes, the positive frequency terms
+    in the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    the axes, in order of decreasingly negative frequency.
+
+    See `fftn` for details and a plotting example, and `fft` for
+    definitions and conventions used.
+
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.mgrid[:5, :5][0]
+    >>> scipy.fft.fft2(x)
+    array([[ 50.  +0.j        ,   0.  +0.j        ,   0.  +0.j        , # may vary
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5+17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 +4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5 -4.0614962j ,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ],
+           [-12.5-17.20477401j,   0.  +0.j        ,   0.  +0.j        ,
+              0.  +0.j        ,   0.  +0.j        ]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D inverse discrete Fourier Transform.
+
+    This function computes the inverse of the 2-D discrete Fourier
+    Transform over any number of axes in an M-D array by means of
+    the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x``
+    to within numerical accuracy. By default, the inverse transform is
+    computed over the last two axes of the input array.
+
+    The input, analogously to `ifft`, should be ordered in the same way as is
+    returned by `fft2`, i.e., it should have the term for zero frequency
+    in the low-order corner of the two axes, the positive frequency terms in
+    the first half of these axes, the term for the Nyquist frequency in the
+    middle of the axes and the negative frequency terms in the second half of
+    both axes, in order of decreasingly negative frequency.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, can be complex.
+    s : sequence of ints, optional
+        Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
+        ``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
+        Along each axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.  See notes for issue on `ifft` zero padding.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last two
+        axes are used.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or the last two axes if `axes` is not given.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length, or `axes` not given and
+        ``len(s) != 2``.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    fft2 : The forward 2-D FFT, of which `ifft2` is the inverse.
+    ifftn : The inverse of the N-D FFT.
+    fft : The 1-D FFT.
+    ifft : The 1-D inverse FFT.
+
+    Notes
+    -----
+    `ifft2` is just `ifftn` with a different default for `axes`.
+
+    See `ifftn` for details and a plotting example, and `fft` for
+    definition and conventions used.
+
+    Zero-padding, analogously with `ifft`, is performed by appending zeros to
+    the input along the specified dimension. Although this is the common
+    approach, it might lead to surprising results. If another form of zero
+    padding is desired, it must be performed before `ifft2` is called.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = 4 * np.eye(4)
+    >>> scipy.fft.ifft2(x)
+    array([[1.+0.j,  0.+0.j,  0.+0.j,  0.+0.j], # may vary
+           [0.+0.j,  0.+0.j,  0.+0.j,  1.+0.j],
+           [0.+0.j,  0.+0.j,  1.+0.j,  0.+0.j],
+           [0.+0.j,  1.+0.j,  0.+0.j,  0.+0.j]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D discrete Fourier Transform for real input.
+
+    This function computes the N-D discrete Fourier Transform over
+    any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining
+    transforms are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
+        for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    irfftn : The inverse of `rfftn`, i.e., the inverse of the N-D FFT
+         of real input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : The 1-D FFT of real input.
+    fftn : The N-D FFT.
+    rfft2 : The 2-D FFT of real input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `rfft`, then the transform over the remaining axes is
+    performed as by `fftn`. The order of the output is as for `rfft` for the
+    final transformation axis, and as for `fftn` for the remaining
+    transformation axes.
+
+    See `fft` for details, definitions and conventions used.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.rfftn(x)
+    array([[[8.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    >>> scipy.fft.rfftn(x, axes=(2, 0))
+    array([[[4.+0.j,  0.+0.j], # may vary
+            [4.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a real array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape of the FFT.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the real 2-D FFT.
+
+    See Also
+    --------
+    irfft2 : The inverse of the 2-D FFT of real input.
+    rfft : The 1-D FFT of real input.
+    rfftn : Compute the N-D discrete Fourier Transform for real
+            input.
+
+    Notes
+    -----
+    This is really just `rfftn` with different default behavior.
+    For more details see `rfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfftn`
+
+    This function computes the inverse of the N-D discrete
+    Fourier Transform for real input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In
+    other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical
+    accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
+    and for the same reason.)
+
+    The input should be ordered in the same way as is returned by `rfftn`,
+    i.e., as for `irfft` for the final transformation axis, and as for `ifftn`
+    along all the other axes.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)``, where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given. In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the
+        length of the final transformed axis of the input. To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    rfftn : The forward N-D FFT of real input,
+            of which `ifftn` is the inverse.
+    fft : The 1-D FFT, with definitions and conventions used.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfft2 : The inverse of the 2-D FFT of real input.
+
+    Notes
+    -----
+    See `fft` for definitions and conventions used.
+
+    See `rfft` for definitions and conventions used for real input.
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.zeros((3, 2, 2))
+    >>> x[0, 0, 0] = 3 * 2 * 2
+    >>> scipy.fft.irfftn(x)
+    array([[[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]],
+           [[1.,  1.],
+            [1.,  1.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Computes the inverse of `rfft2`
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real output to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    rfft2 : The 2-D FFT of real input.
+    irfft : The inverse of the 1-D FFT of real input.
+    irfftn : The inverse of the N-D FFT of real input.
+
+    Notes
+    -----
+    This is really `irfftn` with different defaults.
+    For more details see `irfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def hfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the N-D FFT of Hermitian symmetric complex input, i.e., a
+    signal with a real spectrum.
+
+    This function computes the N-D discrete Fourier Transform for a
+    Hermitian symmetric complex input over any number of axes in an
+    M-D array by means of the Fast Fourier Transform (FFT). In other
+    words, ``ihfftn(hfftn(x, s)) == x`` to within numerical accuracy. (``s``
+    here is ``x.shape`` with ``s[-1] = x.shape[-1] * 2 - 1``, this is necessary
+    for the same reason ``x.shape`` would be necessary for `irfft`.)
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    s : sequence of ints, optional
+        Shape (length of each transformed axis) of the output
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
+        number of input points used along this axis, except for the last axis,
+        where ``s[-1]//2+1`` points of the input are used.
+        Along any axis, if the shape indicated by `s` is smaller than that of
+        the input, the input is cropped. If it is larger, the input is padded
+        with zeros. If `s` is not given, the shape of the input along the axes
+        specified by axes is used. Except for the last axis which is taken to be
+        ``2*(m-1)`` where ``m`` is the length of the input along that axis.
+    axes : sequence of ints, optional
+        Axes over which to compute the inverse FFT. If not given, the last
+        `len(s)` axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` or `x`,
+        as explained in the parameters section above.
+        The length of each transformed axis is as given by the corresponding
+        element of `s`, or the length of the input in every axis except for the
+        last one if `s` is not given.  In the final transformed axis the length
+        of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
+        length of the final transformed axis of the input.  To get an odd
+        number of output points in the final axis, `s` must be specified.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    ihfftn : The inverse N-D FFT with real spectrum. Inverse of `hfftn`.
+    fft : The 1-D FFT, with definitions and conventions used.
+    rfft : Forward FFT of real input.
+
+    Notes
+    -----
+    For a 1-D signal ``x`` to have a real spectrum, it must satisfy
+    the Hermitian property::
+
+        x[i] == np.conj(x[-i]) for all i
+
+    This generalizes into higher dimensions by reflecting over each axis in
+    turn::
+
+        x[i, j, k, ...] == np.conj(x[-i, -j, -k, ...]) for all i, j, k, ...
+
+    This should not be confused with a Hermitian matrix, for which the
+    transpose is its own conjugate::
+
+        x[i, j] == np.conj(x[j, i]) for all i, j
+
+
+    The default value of `s` assumes an even output length in the final
+    transformation axis. When performing the final complex to real
+    transformation, the Hermitian symmetry requires that the last imaginary
+    component along that axis must be 0 and so it is ignored. To avoid losing
+    information, the correct length of the real input *must* be given.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((3, 2, 2))
+    >>> scipy.fft.hfftn(x)
+    array([[[12.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]],
+           [[ 0.,  0.],
+            [ 0.,  0.]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def hfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+          plan=None):
+    """
+    Compute the 2-D FFT of a Hermitian complex array.
+
+    Parameters
+    ----------
+    x : array
+        Input array, taken to be Hermitian complex.
+    s : sequence of ints, optional
+        Shape of the real output.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See `fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The real result of the 2-D Hermitian complex real FFT.
+
+    See Also
+    --------
+    hfftn : Compute the N-D discrete Fourier Transform for Hermitian
+            complex input.
+
+    Notes
+    -----
+    This is really just `hfftn` with different default behavior.
+    For more details see `hfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ihfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the N-D inverse discrete Fourier Transform for a real
+    spectrum.
+
+    This function computes the N-D inverse discrete Fourier Transform
+    over any number of axes in an M-D real array by means of the Fast
+    Fourier Transform (FFT). By default, all axes are transformed, with the
+    real transform performed over the last axis, while the remaining transforms
+    are complex.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array, taken to be real.
+    s : sequence of ints, optional
+        Shape (length along each transformed axis) to use from the input.
+        (``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
+        Along any axis, if the given shape is smaller than that of the input,
+        the input is cropped. If it is larger, the input is padded with zeros.
+        if `s` is not given, the shape of the input along the axes specified
+        by `axes` is used.
+    axes : sequence of ints, optional
+        Axes over which to compute the FFT. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : complex ndarray
+        The truncated or zero-padded input, transformed along the axes
+        indicated by `axes`, or by a combination of `s` and `x`,
+        as explained in the parameters section above.
+        The length of the last axis transformed will be ``s[-1]//2+1``,
+        while the remaining transformed axes will have lengths according to
+        `s`, or unchanged from the input.
+
+    Raises
+    ------
+    ValueError
+        If `s` and `axes` have different length.
+    IndexError
+        If an element of `axes` is larger than the number of axes of `x`.
+
+    See Also
+    --------
+    hfftn : The forward N-D FFT of Hermitian input.
+    hfft : The 1-D FFT of Hermitian input.
+    fft : The 1-D FFT, with definitions and conventions used.
+    fftn : The N-D FFT.
+    hfft2 : The 2-D FFT of Hermitian input.
+
+    Notes
+    -----
+    The transform for real input is performed over the last transformation
+    axis, as by `ihfft`, then the transform over the remaining axes is
+    performed as by `ifftn`. The order of the output is the positive part of
+    the Hermitian output signal, in the same format as `rfft`.
+
+    Examples
+    --------
+    >>> import scipy.fft
+    >>> import numpy as np
+    >>> x = np.ones((2, 2, 2))
+    >>> scipy.fft.ihfftn(x)
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [0.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+    >>> scipy.fft.ihfftn(x, axes=(2, 0))
+    array([[[1.+0.j,  0.+0.j], # may vary
+            [1.+0.j,  0.+0.j]],
+           [[0.+0.j,  0.+0.j],
+            [0.+0.j,  0.+0.j]]])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def ihfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
+           plan=None):
+    """
+    Compute the 2-D inverse FFT of a real spectrum.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array
+    s : sequence of ints, optional
+        Shape of the real input to the inverse FFT.
+    axes : sequence of ints, optional
+        The axes over which to compute the inverse fft.
+        Default is the last two axes.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see `fft`). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+        See :func:`fft` for more details.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    plan : object, optional
+        This argument is reserved for passing in a precomputed plan provided
+        by downstream FFT vendors. It is currently not used in SciPy.
+
+        .. versionadded:: 1.5.0
+
+    Returns
+    -------
+    out : ndarray
+        The result of the inverse real 2-D FFT.
+
+    See Also
+    --------
+    ihfftn : Compute the inverse of the N-D FFT of Hermitian input.
+
+    Notes
+    -----
+    This is really `ihfftn` with different defaults.
+    For more details see `ihfftn`.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..775b26a8bf5922f7fa3634ad6c8c708a96820931
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py
@@ -0,0 +1,197 @@
+from scipy._lib._array_api import (
+    array_namespace, is_numpy, xp_unsupported_param_msg, is_complex, xp_float_to_complex
+)
+from . import _pocketfft
+import numpy as np
+
+
+def _validate_fft_args(workers, plan, norm):
+    if workers is not None:
+        raise ValueError(xp_unsupported_param_msg("workers"))
+    if plan is not None:
+        raise ValueError(xp_unsupported_param_msg("plan"))
+    if norm is None:
+        norm = 'backward'
+    return norm
+
+
+# these functions expect complex input in the fft standard extension
+complex_funcs = {'fft', 'ifft', 'fftn', 'ifftn', 'hfft', 'irfft', 'irfftn'}
+
+# pocketfft is used whenever SCIPY_ARRAY_API is not set,
+# or x is a NumPy array or array-like.
+# When SCIPY_ARRAY_API is set, we try to use xp.fft for CuPy arrays,
+# PyTorch arrays and other array API standard supporting objects.
+# If xp.fft does not exist, we attempt to convert to np and back to use pocketfft.
+
+def _execute_1D(func_str, pocketfft_func, x, n, axis, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return pocketfft_func(x, n=n, axis=axis, norm=norm,
+                              overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+    norm = _validate_fft_args(workers, plan, norm)
+    if hasattr(xp, 'fft'):
+        xp_func = getattr(xp.fft, func_str)
+        if func_str in complex_funcs:
+            try:
+                res = xp_func(x, n=n, axis=axis, norm=norm)
+            except: # backends may require complex input  # noqa: E722
+                x = xp_float_to_complex(x, xp)
+                res = xp_func(x, n=n, axis=axis, norm=norm)
+            return res
+        return xp_func(x, n=n, axis=axis, norm=norm)
+
+    x = np.asarray(x)
+    y = pocketfft_func(x, n=n, axis=axis, norm=norm)
+    return xp.asarray(y)
+
+
+def _execute_nD(func_str, pocketfft_func, x, s, axes, norm, overwrite_x, workers, plan):
+    xp = array_namespace(x)
+    
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return pocketfft_func(x, s=s, axes=axes, norm=norm,
+                              overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+    norm = _validate_fft_args(workers, plan, norm)
+    if hasattr(xp, 'fft'):
+        xp_func = getattr(xp.fft, func_str)
+        if func_str in complex_funcs:
+            try:
+                res = xp_func(x, s=s, axes=axes, norm=norm)
+            except: # backends may require complex input  # noqa: E722
+                x = xp_float_to_complex(x, xp)
+                res = xp_func(x, s=s, axes=axes, norm=norm)
+            return res
+        return xp_func(x, s=s, axes=axes, norm=norm)
+
+    x = np.asarray(x)
+    y = pocketfft_func(x, s=s, axes=axes, norm=norm)
+    return xp.asarray(y)
+
+
+def fft(x, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('fft', _pocketfft.fft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
+         plan=None):
+    return _execute_1D('ifft', _pocketfft.ifft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def rfft(x, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('rfft', _pocketfft.rfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def irfft(x, n=None, axis=-1, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('irfft', _pocketfft.irfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def hfft(x, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('hfft', _pocketfft.hfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def ihfft(x, n=None, axis=-1, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_1D('ihfft', _pocketfft.ihfft, x, n=n, axis=axis, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def fftn(x, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('fftn', _pocketfft.fftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+
+def ifftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('ifftn', _pocketfft.ifftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def fft2(x, s=None, axes=(-2, -1), norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return fftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def ifft2(x, s=None, axes=(-2, -1), norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return ifftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def rfftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('rfftn', _pocketfft.rfftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def rfft2(x, s=None, axes=(-2, -1), norm=None,
+         overwrite_x=False, workers=None, *, plan=None):
+    return rfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def irfftn(x, s=None, axes=None, norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return _execute_nD('irfftn', _pocketfft.irfftn, x, s=s, axes=axes, norm=norm,
+                       overwrite_x=overwrite_x, workers=workers, plan=plan)
+
+
+def irfft2(x, s=None, axes=(-2, -1), norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return irfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def _swap_direction(norm):
+    if norm in (None, 'backward'):
+        norm = 'forward'
+    elif norm == 'forward':
+        norm = 'backward'
+    elif norm != 'ortho':
+        raise ValueError(f'Invalid norm value {norm}; should be "backward", '
+                         '"ortho", or "forward".')
+    return norm
+
+
+def hfftn(x, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    xp = array_namespace(x)
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return _pocketfft.hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+    if is_complex(x, xp):
+        x = xp.conj(x)
+    return irfftn(x, s, axes, _swap_direction(norm),
+                  overwrite_x, workers, plan=plan)
+
+
+def hfft2(x, s=None, axes=(-2, -1), norm=None,
+          overwrite_x=False, workers=None, *, plan=None):
+    return hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+
+
+def ihfftn(x, s=None, axes=None, norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    xp = array_namespace(x)
+    if is_numpy(xp):
+        x = np.asarray(x)
+        return _pocketfft.ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
+    return xp.conj(rfftn(x, s, axes, _swap_direction(norm),
+                         overwrite_x, workers, plan=plan))
+
+def ihfft2(x, s=None, axes=(-2, -1), norm=None,
+           overwrite_x=False, workers=None, *, plan=None):
+    return ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9647c5d6ceddc73b97d95f562662ada02c1ae74
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py
@@ -0,0 +1,22 @@
+import numpy as np
+
+class NumPyBackend:
+    """Backend that uses numpy.fft"""
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+        kwargs.pop("overwrite_x", None)
+
+        fn = getattr(np.fft, method.__name__, None)
+        return (NotImplemented if fn is None
+                else fn(*args, **kwargs))
+
+
+class EchoBackend:
+    """Backend that just prints the __ua_function__ arguments"""
+    __ua_domain__ = "numpy.scipy.fft"
+
+    @staticmethod
+    def __ua_function__(method, args, kwargs):
+        print(method, args, kwargs, sep='\n')
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..61bbe802bbb4a40df8ca3b653c693105b29c6578
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py
@@ -0,0 +1,223 @@
+"""Fast Hankel transforms using the FFTLog algorithm.
+
+The implementation closely follows the Fortran code of Hamilton (2000).
+
+added: 14/11/2020 Nicolas Tessore 
+"""
+
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+from ._fftlog_backend import fhtoffset
+import numpy as np
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+
+@_dispatch
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    r'''Compute the fast Hankel transform.
+
+    Computes the discrete Hankel transform of a logarithmically spaced periodic
+    sequence using the FFTLog algorithm [1]_, [2]_.
+
+    Parameters
+    ----------
+    a : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    A : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    ifht : The inverse of `fht`.
+    fhtoffset : Return an optimal offset for `fht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a(r) \, J_\mu(kr) \, k \, dr \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative.  Note that the
+    numerical Hankel transform uses an integrand of :math:`k \, dr`, while the
+    mathematical Hankel transform is commonly defined using :math:`r \, dr`.
+
+    The input array `a` is a periodic sequence of length :math:`n`, uniformly
+    logarithmically spaced with spacing `dln`,
+
+    .. math::
+
+        a_j = a(r_j) \;, \quad
+        r_j = r_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`r_c`.  Note that the central index
+    :math:`j_c = (n-1)/2` is half-integral if :math:`n` is even, so that
+    :math:`r_c` falls between two input elements.  Similarly, the output
+    array `A` is a periodic sequence of length :math:`n`, also uniformly
+    logarithmically spaced with spacing `dln`
+
+    .. math::
+
+       A_j = A(k_j) \;, \quad
+       k_j = k_c \exp[(j-j_c) \, \mathtt{dln}]
+
+    centred about the point :math:`k_c`.
+
+    The centre points :math:`r_c` and :math:`k_c` of the periodic intervals may
+    be chosen arbitrarily, but it would be usual to choose the product
+    :math:`k_c r_c = k_j r_{n-1-j} = k_{n-1-j} r_j` to be unity.  This can be
+    changed using the `offset` parameter, which controls the logarithmic offset
+    :math:`\log(k_c) = \mathtt{offset} - \log(r_c)` of the output array.
+    Choosing an optimal value for `offset` may reduce ringing of the discrete
+    Hankel transform.
+
+    If the `bias` parameter is nonzero, this function computes a discrete
+    version of the biased Hankel transform
+
+    .. math::
+
+        A(k) = \int_{0}^{\infty} \! a_q(r) \, (kr)^q \, J_\mu(kr) \, k \, dr
+
+    where :math:`q` is the value of `bias`, and a power law bias
+    :math:`a_q(r) = a(r) \, (kr)^{-q}` is applied to the input sequence.
+    Biasing the transform can help approximate the continuous transform of
+    :math:`a(r)` if there is a value :math:`q` such that :math:`a_q(r)` is
+    close to a periodic sequence, in which case the resulting :math:`A(k)` will
+    be close to the continuous transform.
+
+    References
+    ----------
+    .. [1] Talman J. D., 1978, J. Comp. Phys., 29, 35
+    .. [2] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    Examples
+    --------
+
+    This example is the adapted version of ``fftlogtest.f`` which is provided
+    in [2]_. It evaluates the integral
+
+    .. math::
+
+        \int^\infty_0 r^{\mu+1} \exp(-r^2/2) J_\mu(kr) k dr
+        = k^{\mu+1} \exp(-k^2/2) .
+
+    >>> import numpy as np
+    >>> from scipy import fft
+    >>> import matplotlib.pyplot as plt
+
+    Parameters for the transform.
+
+    >>> mu = 0.0                     # Order mu of Bessel function
+    >>> r = np.logspace(-7, 1, 128)  # Input evaluation points
+    >>> dln = np.log(r[1]/r[0])      # Step size
+    >>> offset = fft.fhtoffset(dln, initial=-6*np.log(10), mu=mu)
+    >>> k = np.exp(offset)/r[::-1]   # Output evaluation points
+
+    Define the analytical function.
+
+    >>> def f(x, mu):
+    ...     """Analytical function: x^(mu+1) exp(-x^2/2)."""
+    ...     return x**(mu + 1)*np.exp(-x**2/2)
+
+    Evaluate the function at ``r`` and compute the corresponding values at
+    ``k`` using FFTLog.
+
+    >>> a_r = f(r, mu)
+    >>> fht = fft.fht(a_r, dln, mu=mu, offset=offset)
+
+    For this example we can actually compute the analytical response (which in
+    this case is the same as the input function) for comparison and compute the
+    relative error.
+
+    >>> a_k = f(k, mu)
+    >>> rel_err = abs((fht-a_k)/a_k)
+
+    Plot the result.
+
+    >>> figargs = {'sharex': True, 'sharey': True, 'constrained_layout': True}
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), **figargs)
+    >>> ax1.set_title(r'$r^{\mu+1}\ \exp(-r^2/2)$')
+    >>> ax1.loglog(r, a_r, 'k', lw=2)
+    >>> ax1.set_xlabel('r')
+    >>> ax2.set_title(r'$k^{\mu+1} \exp(-k^2/2)$')
+    >>> ax2.loglog(k, a_k, 'k', lw=2, label='Analytical')
+    >>> ax2.loglog(k, fht, 'C3--', lw=2, label='FFTLog')
+    >>> ax2.set_xlabel('k')
+    >>> ax2.legend(loc=3, framealpha=1)
+    >>> ax2.set_ylim([1e-10, 1e1])
+    >>> ax2b = ax2.twinx()
+    >>> ax2b.loglog(k, rel_err, 'C0', label='Rel. Error (-)')
+    >>> ax2b.set_ylabel('Rel. Error (-)', color='C0')
+    >>> ax2b.tick_params(axis='y', labelcolor='C0')
+    >>> ax2b.legend(loc=4, framealpha=1)
+    >>> ax2b.set_ylim([1e-9, 1e-3])
+    >>> plt.show()
+
+    '''
+    return (Dispatchable(a, np.ndarray),)
+
+
+@_dispatch
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    r"""Compute the inverse fast Hankel transform.
+
+    Computes the discrete inverse Hankel transform of a logarithmically spaced
+    periodic sequence. This is the inverse operation to `fht`.
+
+    Parameters
+    ----------
+    A : array_like (..., n)
+        Real periodic input array, uniformly logarithmically spaced.  For
+        multidimensional input, the transform is performed over the last axis.
+    dln : float
+        Uniform logarithmic spacing of the input array.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    offset : float, optional
+        Offset of the uniform logarithmic spacing of the output array.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    a : array_like (..., n)
+        The transformed output array, which is real, periodic, uniformly
+        logarithmically spaced, and of the same shape as the input array.
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+    fhtoffset : Return an optimal offset for `ifht`.
+
+    Notes
+    -----
+    This function computes a discrete version of the Hankel transform
+
+    .. math::
+
+        a(r) = \int_{0}^{\infty} \! A(k) \, J_\mu(kr) \, r \, dk \;,
+
+    where :math:`J_\mu` is the Bessel function of order :math:`\mu`.  The index
+    :math:`\mu` may be any real number, positive or negative. Note that the
+    numerical inverse Hankel transform uses an integrand of :math:`r \, dk`, while the
+    mathematical inverse Hankel transform is commonly defined using :math:`k \, dk`.
+
+    See `fht` for further details.
+    """
+    return (Dispatchable(A, np.ndarray),)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b38733aaa349c301ba7d5b83691c55204dc8991
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py
@@ -0,0 +1,200 @@
+import numpy as np
+from warnings import warn
+from ._basic import rfft, irfft
+from ..special import loggamma, poch
+
+from scipy._lib._array_api import array_namespace
+
+__all__ = ['fht', 'ifht', 'fhtoffset']
+
+# constants
+LN_2 = np.log(2)
+
+
+def fht(a, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(a)
+    a = xp.asarray(a)
+
+    # size of transform
+    n = a.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # a_q(r) = a(r) (r/r_c)^{-q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        a = a * xp.exp(-bias*(j - j_c)*dln)
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias))
+
+    # transform
+    A = _fhtq(a, u, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # A(k) = A_q(k) (k/k_c)^{-q} (k_c r_c)^{-q}
+        A *= xp.exp(-bias*((j - j_c)*dln + offset))
+
+    return A
+
+
+def ifht(A, dln, mu, offset=0.0, bias=0.0):
+    xp = array_namespace(A)
+    A = xp.asarray(A)
+
+    # size of transform
+    n = A.shape[-1]
+
+    # bias input array
+    if bias != 0:
+        # A_q(k) = A(k) (k/k_c)^{q} (k_c r_c)^{q}
+        j_c = (n-1)/2
+        j = xp.arange(n, dtype=xp.float64)
+        A = A * xp.exp(bias*((j - j_c)*dln + offset))
+
+    # compute FHT coefficients
+    u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias, inverse=True))
+
+    # transform
+    a = _fhtq(A, u, inverse=True, xp=xp)
+
+    # bias output array
+    if bias != 0:
+        # a(r) = a_q(r) (r/r_c)^{q}
+        a /= xp.exp(-bias*(j - j_c)*dln)
+
+    return a
+
+
+def fhtcoeff(n, dln, mu, offset=0.0, bias=0.0, inverse=False):
+    """Compute the coefficient array for a fast Hankel transform."""
+    lnkr, q = offset, bias
+
+    # Hankel transform coefficients
+    # u_m = (kr)^{-i 2m pi/(n dlnr)} U_mu(q + i 2m pi/(n dlnr))
+    # with U_mu(x) = 2^x Gamma((mu+1+x)/2)/Gamma((mu+1-x)/2)
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.linspace(0, np.pi*(n//2)/(n*dln), n//2+1)
+    u = np.empty(n//2+1, dtype=complex)
+    v = np.empty(n//2+1, dtype=complex)
+    u.imag[:] = y
+    u.real[:] = xm
+    loggamma(u, out=v)
+    u.real[:] = xp
+    loggamma(u, out=u)
+    y *= 2*(LN_2 - lnkr)
+    u.real -= v.real
+    u.real += LN_2*q
+    u.imag += v.imag
+    u.imag += y
+    np.exp(u, out=u)
+
+    # fix last coefficient to be real
+    if n % 2 == 0:
+        u.imag[-1] = 0
+
+    # deal with special cases
+    if not np.isfinite(u[0]):
+        # write u_0 = 2^q Gamma(xp)/Gamma(xm) = 2^q poch(xm, xp-xm)
+        # poch() handles special cases for negative integers correctly
+        u[0] = 2**q * poch(xm, xp-xm)
+        # the coefficient may be inf or 0, meaning the transform or the
+        # inverse transform, respectively, is singular
+
+    # check for singular transform or singular inverse transform
+    if np.isinf(u[0]) and not inverse:
+        warn('singular transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) transform anyway
+        u = np.copy(u)
+        u[0] = 0
+    elif u[0] == 0 and inverse:
+        warn('singular inverse transform; consider changing the bias', stacklevel=3)
+        # fix coefficient to obtain (potentially correct) inverse anyway
+        u = np.copy(u)
+        u[0] = np.inf
+
+    return u
+
+
+def fhtoffset(dln, mu, initial=0.0, bias=0.0):
+    """Return optimal offset for a fast Hankel transform.
+
+    Returns an offset close to `initial` that fulfils the low-ringing
+    condition of [1]_ for the fast Hankel transform `fht` with logarithmic
+    spacing `dln`, order `mu` and bias `bias`.
+
+    Parameters
+    ----------
+    dln : float
+        Uniform logarithmic spacing of the transform.
+    mu : float
+        Order of the Hankel transform, any positive or negative real number.
+    initial : float, optional
+        Initial value for the offset. Returns the closest value that fulfils
+        the low-ringing condition.
+    bias : float, optional
+        Exponent of power law bias, any positive or negative real number.
+
+    Returns
+    -------
+    offset : float
+        Optimal offset of the uniform logarithmic spacing of the transform that
+        fulfils a low-ringing condition.
+
+    Examples
+    --------
+    >>> from scipy.fft import fhtoffset
+    >>> dln = 0.1
+    >>> mu = 2.0
+    >>> initial = 0.5
+    >>> bias = 0.0
+    >>> offset = fhtoffset(dln, mu, initial, bias)
+    >>> offset
+    0.5454581477676637
+
+    See Also
+    --------
+    fht : Definition of the fast Hankel transform.
+
+    References
+    ----------
+    .. [1] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
+
+    """
+
+    lnkr, q = initial, bias
+
+    xp = (mu+1+q)/2
+    xm = (mu+1-q)/2
+    y = np.pi/(2*dln)
+    zp = loggamma(xp + 1j*y)
+    zm = loggamma(xm + 1j*y)
+    arg = (LN_2 - lnkr)/dln + (zp.imag + zm.imag)/np.pi
+    return lnkr + (arg - np.round(arg))*dln
+
+
+def _fhtq(a, u, inverse=False, *, xp=None):
+    """Compute the biased fast Hankel transform.
+
+    This is the basic FFTLog routine.
+    """
+    if xp is None:
+        xp = np
+
+    # size of transform
+    n = a.shape[-1]
+
+    # biased fast Hankel transform via real FFT
+    A = rfft(a, axis=-1)
+    if not inverse:
+        # forward transform
+        A *= u
+    else:
+        # backward transform
+        A /= xp.conj(u)
+    A = irfft(A, n, axis=-1)
+    A = xp.flip(A, axis=-1)
+
+    return A
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_helper.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..76e08c4f61c854f9bfb9407a1951f2cf5a2af123
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_helper.py
@@ -0,0 +1,379 @@
+from functools import update_wrapper, lru_cache
+import inspect
+
+from ._pocketfft import helper as _helper
+
+import numpy as np
+from scipy._lib._array_api import array_namespace
+
+
+def next_fast_len(target, real=False):
+    """Find the next fast size of input data to ``fft``, for zero-padding, etc.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    >= ``target`` with only prime factors < `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Length to start searching from. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The smallest fast length greater than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 11.4 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> min_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(min_len)
+    >>> b = fft.fft(a)
+
+    Zero-padding to the next regular length reduces computation time to
+    1.6 ms, a speedup of 7.3 times:
+
+    >>> fft.next_fast_len(min_len, real=True)
+    93312
+    >>> b = fft.fft(a, 93312)
+
+    Rounding up to the next power of 2 is not optimal, taking 3.0 ms to
+    compute; 1.9 times longer than the size given by ``next_fast_len``:
+
+    >>> b = fft.fft(a, 131072)
+
+    """
+    pass
+
+
+# Directly wrap the c-function good_size but take the docstring etc., from the
+# next_fast_len function above
+_sig = inspect.signature(next_fast_len)
+next_fast_len = update_wrapper(lru_cache(_helper.good_size), next_fast_len)
+next_fast_len.__wrapped__ = _helper.good_size
+next_fast_len.__signature__ = _sig
+
+
+def prev_fast_len(target, real=False):
+    """Find the previous fast size of input data to ``fft``.
+    Useful for discarding a minimal number of samples before FFT.
+
+    SciPy's FFT algorithms gain their speed by a recursive divide and conquer
+    strategy. This relies on efficient functions for small prime factors of the
+    input length. Thus, the transforms are fastest when using composites of the
+    prime factors handled by the fft implementation. If there are efficient
+    functions for all radices <= `n`, then the result will be a number `x`
+    <= ``target`` with only prime factors <= `n`. (Also known as `n`-smooth
+    numbers)
+
+    Parameters
+    ----------
+    target : int
+        Maximum length to search until. Must be a positive integer.
+    real : bool, optional
+        True if the FFT involves real input or output (e.g., `rfft` or `hfft`
+        but not `fft`). Defaults to False.
+
+    Returns
+    -------
+    out : int
+        The largest fast length less than or equal to ``target``.
+
+    Notes
+    -----
+    The result of this function may change in future as performance
+    considerations change, for example, if new prime factors are added.
+
+    Calling `fft` or `ifft` with real input data performs an ``'R2C'``
+    transform internally.
+
+    In the current implementation, prev_fast_len assumes radices of
+    2,3,5,7,11 for complex FFT and 2,3,5 for real FFT.
+
+    Examples
+    --------
+    On a particular machine, an FFT of prime length takes 16.2 ms:
+
+    >>> from scipy import fft
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> max_len = 93059  # prime length is worst case for speed
+    >>> a = rng.standard_normal(max_len)
+    >>> b = fft.fft(a)
+
+    Performing FFT on the maximum fast length less than max_len
+    reduces the computation time to 1.5 ms, a speedup of 10.5 times:
+
+    >>> fft.prev_fast_len(max_len, real=True)
+    92160
+    >>> c = fft.fft(a[:92160]) # discard last 899 samples
+
+    """
+    pass
+
+
+# Directly wrap the c-function prev_good_size but take the docstring etc.,
+# from the prev_fast_len function above
+_sig_prev_fast_len = inspect.signature(prev_fast_len)
+prev_fast_len = update_wrapper(lru_cache()(_helper.prev_good_size), prev_fast_len)
+prev_fast_len.__wrapped__ = _helper.prev_good_size
+prev_fast_len.__signature__ = _sig_prev_fast_len
+
+
+def _init_nd_shape_and_axes(x, shape, axes):
+    """Handle shape and axes arguments for N-D transforms.
+
+    Returns the shape and axes in a standard form, taking into account negative
+    values and checking for various potential errors.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    shape : int or array_like of ints or None
+        The shape of the result. If both `shape` and `axes` (see below) are
+        None, `shape` is ``x.shape``; if `shape` is None but `axes` is
+        not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
+        If `shape` is -1, the size of the corresponding dimension of `x` is
+        used.
+    axes : int or array_like of ints or None
+        Axes along which the calculation is computed.
+        The default is over all axes.
+        Negative indices are automatically converted to their positive
+        counterparts.
+
+    Returns
+    -------
+    shape : tuple
+        The shape of the result as a tuple of integers.
+    axes : list
+        Axes along which the calculation is computed, as a list of integers.
+
+    """
+    x = np.asarray(x)
+    return _helper._init_nd_shape_and_axes(x, shape, axes)
+
+
+def fftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies.
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,   n/2-1,     -n/2, ..., -1] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n)   if n is odd
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.fftfreq` implements the device parameter.
+     
+    Returns
+    -------
+    f : ndarray
+        Array of length `n` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
+    >>> fourier = scipy.fft.fft(signal)
+    >>> n = signal.size
+    >>> timestep = 0.1
+    >>> freq = scipy.fft.fftfreq(n, d=timestep)
+    >>> freq
+    array([ 0.  ,  1.25,  2.5 , ..., -3.75, -2.5 , -1.25])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.fftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.fftfreq(n, d=d)
+
+
+def rfftfreq(n, d=1.0, *, xp=None, device=None):
+    """Return the Discrete Fourier Transform sample frequencies
+    (for usage with rfft, irfft).
+
+    The returned float array `f` contains the frequency bin centers in cycles
+    per unit of the sample spacing (with zero at the start).  For instance, if
+    the sample spacing is in seconds, then the frequency unit is cycles/second.
+
+    Given a window length `n` and a sample spacing `d`::
+
+      f = [0, 1, ...,     n/2-1,     n/2] / (d*n)   if n is even
+      f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n)   if n is odd
+
+    Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
+    the Nyquist frequency component is considered to be positive.
+
+    Parameters
+    ----------
+    n : int
+        Window length.
+    d : scalar, optional
+        Sample spacing (inverse of the sampling rate). Defaults to 1.
+    xp : array_namespace, optional
+        The namespace for the return array. Default is None, where NumPy is used.
+    device : device, optional
+        The device for the return array.
+        Only valid when `xp.fft.rfftfreq` implements the device parameter.
+
+    Returns
+    -------
+    f : ndarray
+        Array of length ``n//2 + 1`` containing the sample frequencies.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.fft
+    >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
+    >>> fourier = scipy.fft.rfft(signal)
+    >>> n = signal.size
+    >>> sample_rate = 100
+    >>> freq = scipy.fft.fftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20., ..., -30., -20., -10.])
+    >>> freq = scipy.fft.rfftfreq(n, d=1./sample_rate)
+    >>> freq
+    array([  0.,  10.,  20.,  30.,  40.,  50.])
+
+    """
+    xp = np if xp is None else xp
+    # numpy does not yet support the `device` keyword
+    # `xp.__name__ != 'numpy'` should be removed when numpy is compatible
+    if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
+        return xp.fft.rfftfreq(n, d=d, device=device)
+    if device is not None:
+        raise ValueError('device parameter is not supported for input array type')
+    return np.fft.rfftfreq(n, d=d)
+
+
+def fftshift(x, axes=None):
+    """Shift the zero-frequency component to the center of the spectrum.
+
+    This function swaps half-spaces for all axes listed (defaults to all).
+    Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to shift.  Default is None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    ifftshift : The inverse of `fftshift`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(10, 0.1)
+    >>> freqs
+    array([ 0.,  1.,  2., ..., -3., -2., -1.])
+    >>> np.fft.fftshift(freqs)
+    array([-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
+
+    Shift the zero-frequency component only along the second axis:
+
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.fftshift(freqs, axes=(1,))
+    array([[ 2.,  0.,  1.],
+           [-4.,  3.,  4.],
+           [-1., -3., -2.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.fftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.fftshift(x, axes=axes)
+    return xp.asarray(y)
+
+
+def ifftshift(x, axes=None):
+    """The inverse of `fftshift`. Although identical for even-length `x`, the
+    functions differ by one sample for odd-length `x`.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axes : int or shape tuple, optional
+        Axes over which to calculate.  Defaults to None, which shifts all axes.
+
+    Returns
+    -------
+    y : ndarray
+        The shifted array.
+
+    See Also
+    --------
+    fftshift : Shift zero-frequency component to the center of the spectrum.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
+    >>> freqs
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+    >>> np.fft.ifftshift(np.fft.fftshift(freqs))
+    array([[ 0.,  1.,  2.],
+           [ 3.,  4., -4.],
+           [-3., -2., -1.]])
+
+    """
+    xp = array_namespace(x)
+    if hasattr(xp, 'fft'):
+        return xp.fft.ifftshift(x, axes=axes)
+    x = np.asarray(x)
+    y = np.fft.ifftshift(x, axes=axes)
+    return xp.asarray(y)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..1b5163d8435976c24988afbd39ded304947178cb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md
@@ -0,0 +1,25 @@
+Copyright (C) 2010-2019 Max-Planck-Society
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this
+  list of conditions and the following disclaimer in the documentation and/or
+  other materials provided with the distribution.
+* Neither the name of the copyright holder nor the names of its contributors may
+  be used to endorse or promote products derived from this software without
+  specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0671484c9a0780df353b9b783813b6fa7492d38d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py
@@ -0,0 +1,9 @@
+""" FFT backend using pypocketfft """
+
+from .basic import *
+from .realtransforms import *
+from .helper import *
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a493cfdd03598f9521c6edaf1ed7cc628b56d30
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb44150a66b6398f46bfea83cdea47e7d671978e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d6f96c2a7140baf2fd46db7bc7cbb0b1ca3a575
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52642b596edca35b9dc995c5ad7a2090338c1433
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd2d0d33958021c431171b72f72c37363ac98e03
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py
@@ -0,0 +1,251 @@
+"""
+Discrete Fourier Transforms - basic.py
+"""
+import numpy as np
+import functools
+from . import pypocketfft as pfft
+from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
+                     _fix_shape, _fix_shape_1d, _normalization,
+                     _workers)
+
+def c2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
+        workers=None, *, plan=None):
+    """ Return discrete Fourier transform of real or complex sequence. """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    if n is not None:
+        tmp, copied = _fix_shape_1d(tmp, n, axis)
+        overwrite_x = overwrite_x or copied
+    elif tmp.shape[axis] < 1:
+        message = f"invalid number of data points ({tmp.shape[axis]}) specified"
+        raise ValueError(message)
+
+    out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
+
+    return pfft.c2c(tmp, (axis,), forward, norm, out, workers)
+
+
+fft = functools.partial(c2c, True)
+fft.__name__ = 'fft'
+ifft = functools.partial(c2c, False)
+ifft.__name__ = 'ifft'
+
+
+def r2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
+        workers=None, *, plan=None):
+    """
+    Discrete Fourier transform of a real sequence.
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    if not np.isrealobj(tmp):
+        raise TypeError("x must be a real sequence")
+
+    if n is not None:
+        tmp, _ = _fix_shape_1d(tmp, n, axis)
+    elif tmp.shape[axis] < 1:
+        raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
+
+    # Note: overwrite_x is not utilised
+    return pfft.r2c(tmp, (axis,), forward, norm, None, workers)
+
+
+rfft = functools.partial(r2c, True)
+rfft.__name__ = 'rfft'
+ihfft = functools.partial(r2c, False)
+ihfft.__name__ = 'ihfft'
+
+
+def c2r(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
+        workers=None, *, plan=None):
+    """
+    Return inverse discrete Fourier transform of real sequence x.
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    # TODO: Optimize for hermitian and real?
+    if np.isrealobj(tmp):
+        tmp = tmp + 0.j
+
+    # Last axis utilizes hermitian symmetry
+    if n is None:
+        n = (tmp.shape[axis] - 1) * 2
+        if n < 1:
+            raise ValueError(f"Invalid number of data points ({n}) specified")
+    else:
+        tmp, _ = _fix_shape_1d(tmp, (n//2) + 1, axis)
+
+    # Note: overwrite_x is not utilized
+    return pfft.c2r(tmp, (axis,), n, forward, norm, None, workers)
+
+
+hfft = functools.partial(c2r, True)
+hfft.__name__ = 'hfft'
+irfft = functools.partial(c2r, False)
+irfft.__name__ = 'irfft'
+
+
+def hfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
+          *, plan=None):
+    """
+    2-D discrete Fourier transform of a Hermitian sequence
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    return hfftn(x, s, axes, norm, overwrite_x, workers)
+
+
+def ihfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
+           *, plan=None):
+    """
+    2-D discrete inverse Fourier transform of a Hermitian sequence
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    return ihfftn(x, s, axes, norm, overwrite_x, workers)
+
+
+def c2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, plan=None):
+    """
+    Return multidimensional discrete Fourier transform.
+    """
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+
+    shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+    workers = _workers(workers)
+
+    if len(axes) == 0:
+        return x
+
+    tmp, copied = _fix_shape(tmp, shape, axes)
+    overwrite_x = overwrite_x or copied
+
+    norm = _normalization(norm, forward)
+    out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
+
+    return pfft.c2c(tmp, axes, forward, norm, out, workers)
+
+
+fftn = functools.partial(c2cn, True)
+fftn.__name__ = 'fftn'
+ifftn = functools.partial(c2cn, False)
+ifftn.__name__ = 'ifftn'
+
+def r2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, plan=None):
+    """Return multidimensional discrete Fourier transform of real input"""
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+
+    if not np.isrealobj(tmp):
+        raise TypeError("x must be a real sequence")
+
+    shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+    tmp, _ = _fix_shape(tmp, shape, axes)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    if len(axes) == 0:
+        raise ValueError("at least 1 axis must be transformed")
+
+    # Note: overwrite_x is not utilized
+    return pfft.r2c(tmp, axes, forward, norm, None, workers)
+
+
+rfftn = functools.partial(r2cn, True)
+rfftn.__name__ = 'rfftn'
+ihfftn = functools.partial(r2cn, False)
+ihfftn.__name__ = 'ihfftn'
+
+
+def c2rn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, plan=None):
+    """Multidimensional inverse discrete fourier transform with real output"""
+    if plan is not None:
+        raise NotImplementedError('Passing a precomputed plan is not yet '
+                                  'supported by scipy.fft functions')
+    tmp = _asfarray(x)
+
+    # TODO: Optimize for hermitian and real?
+    if np.isrealobj(tmp):
+        tmp = tmp + 0.j
+
+    noshape = s is None
+    shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+
+    if len(axes) == 0:
+        raise ValueError("at least 1 axis must be transformed")
+
+    shape = list(shape)
+    if noshape:
+        shape[-1] = (x.shape[axes[-1]] - 1) * 2
+
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    # Last axis utilizes hermitian symmetry
+    lastsize = shape[-1]
+    shape[-1] = (shape[-1] // 2) + 1
+
+    tmp, _ = tuple(_fix_shape(tmp, shape, axes))
+
+    # Note: overwrite_x is not utilized
+    return pfft.c2r(tmp, axes, lastsize, forward, norm, None, workers)
+
+
+hfftn = functools.partial(c2rn, True)
+hfftn.__name__ = 'hfftn'
+irfftn = functools.partial(c2rn, False)
+irfftn.__name__ = 'irfftn'
+
+
+def r2r_fftpack(forward, x, n=None, axis=-1, norm=None, overwrite_x=False):
+    """FFT of a real sequence, returning fftpack half complex format"""
+    tmp = _asfarray(x)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+    norm = _normalization(norm, forward)
+    workers = _workers(None)
+
+    if tmp.dtype.kind == 'c':
+        raise TypeError('x must be a real sequence')
+
+    if n is not None:
+        tmp, copied = _fix_shape_1d(tmp, n, axis)
+        overwrite_x = overwrite_x or copied
+    elif tmp.shape[axis] < 1:
+        raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
+
+    out = (tmp if overwrite_x else None)
+
+    return pfft.r2r_fftpack(tmp, (axis,), forward, forward, norm, out, workers)
+
+
+rfft_fftpack = functools.partial(r2r_fftpack, True)
+rfft_fftpack.__name__ = 'rfft_fftpack'
+irfft_fftpack = functools.partial(r2r_fftpack, False)
+irfft_fftpack.__name__ = 'irfft_fftpack'
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab2fbc553ccc46a4b337060a62702ec28cb8b254
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py
@@ -0,0 +1,221 @@
+from numbers import Number
+import operator
+import os
+import threading
+import contextlib
+
+import numpy as np
+
+from scipy._lib._util import copy_if_needed
+
+# good_size is exposed (and used) from this import
+from .pypocketfft import good_size, prev_good_size
+
+
+__all__ = ['good_size', 'prev_good_size', 'set_workers', 'get_workers']
+
+_config = threading.local()
+_cpu_count = os.cpu_count()
+
+
+def _iterable_of_int(x, name=None):
+    """Convert ``x`` to an iterable sequence of int
+
+    Parameters
+    ----------
+    x : value, or sequence of values, convertible to int
+    name : str, optional
+        Name of the argument being converted, only used in the error message
+
+    Returns
+    -------
+    y : ``List[int]``
+    """
+    if isinstance(x, Number):
+        x = (x,)
+
+    try:
+        x = [operator.index(a) for a in x]
+    except TypeError as e:
+        name = name or "value"
+        raise ValueError(f"{name} must be a scalar or iterable of integers") from e
+
+    return x
+
+
+def _init_nd_shape_and_axes(x, shape, axes):
+    """Handles shape and axes arguments for nd transforms"""
+    noshape = shape is None
+    noaxes = axes is None
+
+    if not noaxes:
+        axes = _iterable_of_int(axes, 'axes')
+        axes = [a + x.ndim if a < 0 else a for a in axes]
+
+        if any(a >= x.ndim or a < 0 for a in axes):
+            raise ValueError("axes exceeds dimensionality of input")
+        if len(set(axes)) != len(axes):
+            raise ValueError("all axes must be unique")
+
+    if not noshape:
+        shape = _iterable_of_int(shape, 'shape')
+
+        if axes and len(axes) != len(shape):
+            raise ValueError("when given, axes and shape arguments"
+                             " have to be of the same length")
+        if noaxes:
+            if len(shape) > x.ndim:
+                raise ValueError("shape requires more axes than are present")
+            axes = range(x.ndim - len(shape), x.ndim)
+
+        shape = [x.shape[a] if s == -1 else s for s, a in zip(shape, axes)]
+    elif noaxes:
+        shape = list(x.shape)
+        axes = range(x.ndim)
+    else:
+        shape = [x.shape[a] for a in axes]
+
+    if any(s < 1 for s in shape):
+        raise ValueError(
+            f"invalid number of data points ({shape}) specified")
+
+    return tuple(shape), list(axes)
+
+
+def _asfarray(x):
+    """
+    Convert to array with floating or complex dtype.
+
+    float16 values are also promoted to float32.
+    """
+    if not hasattr(x, "dtype"):
+        x = np.asarray(x)
+
+    if x.dtype == np.float16:
+        return np.asarray(x, np.float32)
+    elif x.dtype.kind not in 'fc':
+        return np.asarray(x, np.float64)
+
+    # Require native byte order
+    dtype = x.dtype.newbyteorder('=')
+    # Always align input
+    copy = True if not x.flags['ALIGNED'] else copy_if_needed
+    return np.array(x, dtype=dtype, copy=copy)
+
+def _datacopied(arr, original):
+    """
+    Strict check for `arr` not sharing any data with `original`,
+    under the assumption that arr = asarray(original)
+    """
+    if arr is original:
+        return False
+    if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
+        return False
+    return arr.base is None
+
+
+def _fix_shape(x, shape, axes):
+    """Internal auxiliary function for _raw_fft, _raw_fftnd."""
+    must_copy = False
+
+    # Build an nd slice with the dimensions to be read from x
+    index = [slice(None)]*x.ndim
+    for n, ax in zip(shape, axes):
+        if x.shape[ax] >= n:
+            index[ax] = slice(0, n)
+        else:
+            index[ax] = slice(0, x.shape[ax])
+            must_copy = True
+
+    index = tuple(index)
+
+    if not must_copy:
+        return x[index], False
+
+    s = list(x.shape)
+    for n, axis in zip(shape, axes):
+        s[axis] = n
+
+    z = np.zeros(s, x.dtype)
+    z[index] = x[index]
+    return z, True
+
+
+def _fix_shape_1d(x, n, axis):
+    if n < 1:
+        raise ValueError(
+            f"invalid number of data points ({n}) specified")
+
+    return _fix_shape(x, (n,), (axis,))
+
+
+_NORM_MAP = {None: 0, 'backward': 0, 'ortho': 1, 'forward': 2}
+
+
+def _normalization(norm, forward):
+    """Returns the pypocketfft normalization mode from the norm argument"""
+    try:
+        inorm = _NORM_MAP[norm]
+        return inorm if forward else (2 - inorm)
+    except KeyError:
+        raise ValueError(
+            f'Invalid norm value {norm!r}, should '
+            'be "backward", "ortho" or "forward"') from None
+
+
+def _workers(workers):
+    if workers is None:
+        return getattr(_config, 'default_workers', 1)
+
+    if workers < 0:
+        if workers >= -_cpu_count:
+            workers += 1 + _cpu_count
+        else:
+            raise ValueError(f"workers value out of range; got {workers}, must not be"
+                             f" less than {-_cpu_count}")
+    elif workers == 0:
+        raise ValueError("workers must not be zero")
+
+    return workers
+
+
+@contextlib.contextmanager
+def set_workers(workers):
+    """Context manager for the default number of workers used in `scipy.fft`
+
+    Parameters
+    ----------
+    workers : int
+        The default number of workers to use
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import fft, signal
+    >>> rng = np.random.default_rng()
+    >>> x = rng.standard_normal((128, 64))
+    >>> with fft.set_workers(4):
+    ...     y = signal.fftconvolve(x, x)
+
+    """
+    old_workers = get_workers()
+    _config.default_workers = _workers(operator.index(workers))
+    try:
+        yield
+    finally:
+        _config.default_workers = old_workers
+
+
+def get_workers():
+    """Returns the default number of workers within the current context
+
+    Examples
+    --------
+    >>> from scipy import fft
+    >>> fft.get_workers()
+    1
+    >>> with fft.set_workers(4):
+    ...     fft.get_workers()
+    4
+    """
+    return getattr(_config, 'default_workers', 1)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a0c616742305444d51258e650344c060129dfab
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py
@@ -0,0 +1,109 @@
+import numpy as np
+from . import pypocketfft as pfft
+from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
+                     _fix_shape, _fix_shape_1d, _normalization, _workers)
+import functools
+
+
+def _r2r(forward, transform, x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    """Forward or backward 1-D DCT/DST
+
+    Parameters
+    ----------
+    forward : bool
+        Transform direction (determines type and normalisation)
+    transform : {pypocketfft.dct, pypocketfft.dst}
+        The transform to perform
+    """
+    tmp = _asfarray(x)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+
+    if not forward:
+        if type == 2:
+            type = 3
+        elif type == 3:
+            type = 2
+
+    if n is not None:
+        tmp, copied = _fix_shape_1d(tmp, n, axis)
+        overwrite_x = overwrite_x or copied
+    elif tmp.shape[axis] < 1:
+        raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
+
+    out = (tmp if overwrite_x else None)
+
+    # For complex input, transform real and imaginary components separably
+    if np.iscomplexobj(x):
+        out = np.empty_like(tmp) if out is None else out
+        transform(tmp.real, type, (axis,), norm, out.real, workers)
+        transform(tmp.imag, type, (axis,), norm, out.imag, workers)
+        return out
+
+    return transform(tmp, type, (axis,), norm, out, workers, orthogonalize)
+
+
+dct = functools.partial(_r2r, True, pfft.dct)
+dct.__name__ = 'dct'
+idct = functools.partial(_r2r, False, pfft.dct)
+idct.__name__ = 'idct'
+
+dst = functools.partial(_r2r, True, pfft.dst)
+dst.__name__ = 'dst'
+idst = functools.partial(_r2r, False, pfft.dst)
+idst.__name__ = 'idst'
+
+
+def _r2rn(forward, transform, x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, orthogonalize=None):
+    """Forward or backward nd DCT/DST
+
+    Parameters
+    ----------
+    forward : bool
+        Transform direction (determines type and normalisation)
+    transform : {pypocketfft.dct, pypocketfft.dst}
+        The transform to perform
+    """
+    tmp = _asfarray(x)
+
+    shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+    overwrite_x = overwrite_x or _datacopied(tmp, x)
+
+    if len(axes) == 0:
+        return x
+
+    tmp, copied = _fix_shape(tmp, shape, axes)
+    overwrite_x = overwrite_x or copied
+
+    if not forward:
+        if type == 2:
+            type = 3
+        elif type == 3:
+            type = 2
+
+    norm = _normalization(norm, forward)
+    workers = _workers(workers)
+    out = (tmp if overwrite_x else None)
+
+    # For complex input, transform real and imaginary components separably
+    if np.iscomplexobj(x):
+        out = np.empty_like(tmp) if out is None else out
+        transform(tmp.real, type, axes, norm, out.real, workers)
+        transform(tmp.imag, type, axes, norm, out.imag, workers)
+        return out
+
+    return transform(tmp, type, axes, norm, out, workers, orthogonalize)
+
+
+dctn = functools.partial(_r2rn, True, pfft.dct)
+dctn.__name__ = 'dctn'
+idctn = functools.partial(_r2rn, False, pfft.dct)
+idctn.__name__ = 'idctn'
+
+dstn = functools.partial(_r2rn, True, pfft.dst)
+dstn.__name__ = 'dstn'
+idstn = functools.partial(_r2rn, False, pfft.dst)
+idstn.__name__ = 'idstn'
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..feffc37944c24f81bba3352329cbf75743e4e280
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py
@@ -0,0 +1,1013 @@
+# Created by Pearu Peterson, September 2002
+
+from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
+                           assert_array_almost_equal_nulp, assert_array_less,
+                           assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+from scipy.fft._pocketfft import (ifft, fft, fftn, ifftn,
+                                  rfft, irfft, rfftn, irfftn,
+                                  hfft, ihfft, hfftn, ihfftn)
+
+from numpy import (arange, array, asarray, zeros, dot, exp, pi,
+                   swapaxes, cdouble)
+import numpy as np
+import numpy.fft
+from numpy.random import rand
+
+# "large" composite numbers supported by FFT._PYPOCKETFFT
+LARGE_COMPOSITE_SIZES = [
+    2**13,
+    2**5 * 3**5,
+    2**3 * 3**3 * 5**2,
+]
+SMALL_COMPOSITE_SIZES = [
+    2,
+    2*3*5,
+    2*2*3*3,
+]
+# prime
+LARGE_PRIME_SIZES = [
+    2011
+]
+SMALL_PRIME_SIZES = [
+    29
+]
+
+
+def _assert_close_in_norm(x, y, rtol, size, rdt):
+    # helper function for testing
+    err_msg = f"size: {size}  rdt: {rdt}"
+    assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
+
+
+def random(size):
+    return rand(*size)
+
+def swap_byteorder(arr):
+    """Returns the same array with swapped byteorder"""
+    dtype = arr.dtype.newbyteorder('S')
+    return arr.astype(dtype)
+
+def direct_dft(x):
+    x = asarray(x)
+    n = len(x)
+    y = zeros(n, dtype=cdouble)
+    w = -arange(n)*(2j*pi/n)
+    for i in range(n):
+        y[i] = dot(exp(i*w), x)
+    return y
+
+
+def direct_idft(x):
+    x = asarray(x)
+    n = len(x)
+    y = zeros(n, dtype=cdouble)
+    w = arange(n)*(2j*pi/n)
+    for i in range(n):
+        y[i] = dot(exp(i*w), x)/n
+    return y
+
+
+def direct_dftn(x):
+    x = asarray(x)
+    for axis in range(x.ndim):
+        x = fft(x, axis=axis)
+    return x
+
+
+def direct_idftn(x):
+    x = asarray(x)
+    for axis in range(x.ndim):
+        x = ifft(x, axis=axis)
+    return x
+
+
+def direct_rdft(x):
+    x = asarray(x)
+    n = len(x)
+    w = -arange(n)*(2j*pi/n)
+    y = zeros(n//2+1, dtype=cdouble)
+    for i in range(n//2+1):
+        y[i] = dot(exp(i*w), x)
+    return y
+
+
+def direct_irdft(x, n):
+    x = asarray(x)
+    x1 = zeros(n, dtype=cdouble)
+    for i in range(n//2+1):
+        x1[i] = x[i]
+        if i > 0 and 2*i < n:
+            x1[n-i] = np.conj(x[i])
+    return direct_idft(x1).real
+
+
+def direct_rdftn(x):
+    return fftn(rfft(x), axes=range(x.ndim - 1))
+
+
+class _TestFFTBase:
+    def setup_method(self):
+        self.cdt = None
+        self.rdt = None
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
+        y = fft(x)
+        assert_equal(y.dtype, self.cdt)
+        y1 = direct_dft(x)
+        assert_array_almost_equal(y,y1)
+        x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
+        assert_array_almost_equal(fft(x),direct_dft(x))
+
+    def test_n_argument_real(self):
+        x1 = np.array([1,2,3,4], dtype=self.rdt)
+        x2 = np.array([1,2,3,4], dtype=self.rdt)
+        y = fft([x1,x2],n=4)
+        assert_equal(y.dtype, self.cdt)
+        assert_equal(y.shape,(2,4))
+        assert_array_almost_equal(y[0],direct_dft(x1))
+        assert_array_almost_equal(y[1],direct_dft(x2))
+
+    def _test_n_argument_complex(self):
+        x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
+        x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
+        y = fft([x1,x2],n=4)
+        assert_equal(y.dtype, self.cdt)
+        assert_equal(y.shape,(2,4))
+        assert_array_almost_equal(y[0],direct_dft(x1))
+        assert_array_almost_equal(y[1],direct_dft(x2))
+
+    def test_djbfft(self):
+        for i in range(2,14):
+            n = 2**i
+            x = np.arange(n)
+            y = fft(x.astype(complex))
+            y2 = numpy.fft.fft(x)
+            assert_array_almost_equal(y,y2)
+            y = fft(x)
+            assert_array_almost_equal(y,y2)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, fft, [])
+        assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
+
+
+class TestLongDoubleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.clongdouble
+        self.rdt = np.longdouble
+
+
+class TestDoubleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.cdouble
+        self.rdt = np.float64
+
+
+class TestSingleFFT(_TestFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+
+class TestFloat16FFT:
+
+    def test_1_argument_real(self):
+        x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+        y = fft(x1, n=4)
+        assert_equal(y.dtype, np.complex64)
+        assert_equal(y.shape, (4, ))
+        assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
+
+    def test_n_argument_real(self):
+        x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+        x2 = np.array([1, 2, 3, 4], dtype=np.float16)
+        y = fft([x1, x2], n=4)
+        assert_equal(y.dtype, np.complex64)
+        assert_equal(y.shape, (2, 4))
+        assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
+        assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
+
+
+class _TestIFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
+        y = ifft(x)
+        y1 = direct_idft(x)
+        assert_equal(y.dtype, self.cdt)
+        assert_array_almost_equal(y,y1)
+
+        x = np.array([1,2,3,4+0j,5], self.cdt)
+        assert_array_almost_equal(ifft(x),direct_idft(x))
+
+    def test_definition_real(self):
+        x = np.array([1,2,3,4,1,2,3,4], self.rdt)
+        y = ifft(x)
+        assert_equal(y.dtype, self.cdt)
+        y1 = direct_idft(x)
+        assert_array_almost_equal(y,y1)
+
+        x = np.array([1,2,3,4,5], dtype=self.rdt)
+        assert_equal(y.dtype, self.cdt)
+        assert_array_almost_equal(ifft(x),direct_idft(x))
+
+    def test_djbfft(self):
+        for i in range(2,14):
+            n = 2**i
+            x = np.arange(n)
+            y = ifft(x.astype(self.cdt))
+            y2 = numpy.fft.ifft(x.astype(self.cdt))
+            assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
+            y = ifft(x)
+            assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
+
+    def test_random_complex(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.cdt)
+            x = random([size]).astype(self.cdt) + 1j*x
+            y1 = ifft(fft(x))
+            y2 = fft(ifft(x))
+            assert_equal(y1.dtype, self.cdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x)
+            assert_array_almost_equal(y2, x)
+
+    def test_random_real(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.rdt)
+            y1 = ifft(fft(x))
+            y2 = fft(ifft(x))
+            assert_equal(y1.dtype, self.cdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x)
+            assert_array_almost_equal(y2, x)
+
+    def test_size_accuracy(self):
+        # Sanity check for the accuracy for prime and non-prime sized inputs
+        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+            np.random.seed(1234)
+            x = np.random.rand(size).astype(self.rdt)
+            y = ifft(fft(x))
+            _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+            y = fft(ifft(x))
+            _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+
+            x = (x + 1j*np.random.rand(size)).astype(self.cdt)
+            y = ifft(fft(x))
+            _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+            y = fft(ifft(x))
+            _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, ifft, [])
+        assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
+
+
+@pytest.mark.skipif(np.longdouble is np.float64,
+                    reason="Long double is aliased to double")
+class TestLongDoubleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.clongdouble
+        self.rdt = np.longdouble
+        self.rtol = 1e-10
+        self.atol = 1e-10
+
+
+class TestDoubleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+        self.rtol = 1e-10
+        self.atol = 1e-10
+
+
+class TestSingleIFFT(_TestIFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+        self.rtol = 1e-5
+        self.atol = 1e-4
+
+
+class _TestRFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
+            x = np.array(t, dtype=self.rdt)
+            y = rfft(x)
+            y1 = direct_rdft(x)
+            assert_array_almost_equal(y,y1)
+            assert_equal(y.dtype, self.cdt)
+
+    def test_djbfft(self):
+        for i in range(2,14):
+            n = 2**i
+            x = np.arange(n)
+            y1 = np.fft.rfft(x)
+            y = rfft(x)
+            assert_array_almost_equal(y,y1)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, rfft, [])
+        assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
+
+    def test_complex_input(self):
+        x = np.zeros(10, dtype=self.cdt)
+        with assert_raises(TypeError, match="x must be a real sequence"):
+            rfft(x)
+
+    # See gh-5790
+    class MockSeries:
+        def __init__(self, data):
+            self.data = np.asarray(data)
+
+        def __getattr__(self, item):
+            try:
+                return getattr(self.data, item)
+            except AttributeError as e:
+                raise AttributeError("'MockSeries' object "
+                                      f"has no attribute '{item}'") from e
+
+    def test_non_ndarray_with_dtype(self):
+        x = np.array([1., 2., 3., 4., 5.])
+        xs = _TestRFFTBase.MockSeries(x)
+
+        expected = [1, 2, 3, 4, 5]
+        rfft(xs)
+
+        # Data should not have been overwritten
+        assert_equal(x, expected)
+        assert_equal(xs.data, expected)
+
+@pytest.mark.skipif(np.longdouble is np.float64,
+                    reason="Long double is aliased to double")
+class TestRFFTLongDouble(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.clongdouble
+        self.rdt = np.longdouble
+
+
+class TestRFFTDouble(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+
+
+class TestRFFTSingle(_TestRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+
+
+class _TestIRFFTBase:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x1 = [1,2+3j,4+1j,1+2j,3+4j]
+        x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
+        x1 = x1_1[:5]
+        x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
+        x2 = x2_1[:5]
+
+        def _test(x, xr):
+            y = irfft(np.array(x, dtype=self.cdt), n=len(xr))
+            y1 = direct_irdft(x, len(xr))
+            assert_equal(y.dtype, self.rdt)
+            assert_array_almost_equal(y,y1, decimal=self.ndec)
+            assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
+
+        _test(x1, x1_1)
+        _test(x2, x2_1)
+
+    def test_djbfft(self):
+        for i in range(2,14):
+            n = 2**i
+            x = np.arange(-1, n, 2) + 1j * np.arange(0, n+1, 2)
+            x[0] = 0
+            if n % 2 == 0:
+                x[-1] = np.real(x[-1])
+            y1 = np.fft.irfft(x)
+            y = irfft(x)
+            assert_array_almost_equal(y,y1)
+
+    def test_random_real(self):
+        for size in [1,51,111,100,200,64,128,256,1024]:
+            x = random([size]).astype(self.rdt)
+            y1 = irfft(rfft(x), n=size)
+            y2 = rfft(irfft(x, n=(size*2-1)))
+            assert_equal(y1.dtype, self.rdt)
+            assert_equal(y2.dtype, self.cdt)
+            assert_array_almost_equal(y1, x, decimal=self.ndec,
+                                       err_msg="size=%d" % size)
+            assert_array_almost_equal(y2, x, decimal=self.ndec,
+                                       err_msg="size=%d" % size)
+
+    def test_size_accuracy(self):
+        # Sanity check for the accuracy for prime and non-prime sized inputs
+        if self.rdt == np.float32:
+            rtol = 1e-5
+        elif self.rdt == np.float64:
+            rtol = 1e-10
+
+        for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+            np.random.seed(1234)
+            x = np.random.rand(size).astype(self.rdt)
+            y = irfft(rfft(x), len(x))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+            y = rfft(irfft(x, 2 * len(x) - 1))
+            _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+    def test_invalid_sizes(self):
+        assert_raises(ValueError, irfft, [])
+        assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
+
+
+# self.ndec is bogus; we should have a assert_array_approx_equal for number of
+# significant digits
+
+@pytest.mark.skipif(np.longdouble is np.float64,
+                    reason="Long double is aliased to double")
+class TestIRFFTLongDouble(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+        self.ndec = 14
+
+
+class TestIRFFTDouble(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex128
+        self.rdt = np.float64
+        self.ndec = 14
+
+
+class TestIRFFTSingle(_TestIRFFTBase):
+    def setup_method(self):
+        self.cdt = np.complex64
+        self.rdt = np.float32
+        self.ndec = 5
+
+
+class TestFftnSingle:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(np.array(x, np.float32))
+        assert_(y.dtype == np.complex64,
+                msg="double precision output with single precision")
+
+        y_r = np.array(fftn(x), np.complex64)
+        assert_array_almost_equal_nulp(y, y_r)
+
+    @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+    def test_size_accuracy_small(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, size)) + 1j * rng.random((size, size))
+        y1 = fftn(x.real.astype(np.float32))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2000)
+
+    @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+    def test_size_accuracy_large(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, 3)) + 1j * rng.random((size, 3))
+        y1 = fftn(x.real.astype(np.float32))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2000)
+
+    def test_definition_float16(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(np.array(x, np.float16))
+        assert_equal(y.dtype, np.complex64)
+        y_r = np.array(fftn(x), np.complex64)
+        assert_array_almost_equal_nulp(y, y_r)
+
+    @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+    def test_float16_input_small(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, size)) + 1j*rng.random((size, size))
+        y1 = fftn(x.real.astype(np.float16))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 5e5)
+
+    @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+    def test_float16_input_large(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random((size, 3)) + 1j*rng.random((size, 3))
+        y1 = fftn(x.real.astype(np.float16))
+        y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+        assert_equal(y1.dtype, np.complex64)
+        assert_array_almost_equal_nulp(y1, y2, 2e6)
+
+
+class TestFftn:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_definition(self):
+        x = [[1, 2, 3],
+             [4, 5, 6],
+             [7, 8, 9]]
+        y = fftn(x)
+        assert_array_almost_equal(y, direct_dftn(x))
+
+        x = random((20, 26))
+        assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+        x = random((5, 4, 3, 20))
+        assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+    def test_axes_argument(self):
+        # plane == ji_plane, x== kji_space
+        plane1 = [[1, 2, 3],
+                  [4, 5, 6],
+                  [7, 8, 9]]
+        plane2 = [[10, 11, 12],
+                  [13, 14, 15],
+                  [16, 17, 18]]
+        plane3 = [[19, 20, 21],
+                  [22, 23, 24],
+                  [25, 26, 27]]
+        ki_plane1 = [[1, 2, 3],
+                     [10, 11, 12],
+                     [19, 20, 21]]
+        ki_plane2 = [[4, 5, 6],
+                     [13, 14, 15],
+                     [22, 23, 24]]
+        ki_plane3 = [[7, 8, 9],
+                     [16, 17, 18],
+                     [25, 26, 27]]
+        jk_plane1 = [[1, 10, 19],
+                     [4, 13, 22],
+                     [7, 16, 25]]
+        jk_plane2 = [[2, 11, 20],
+                     [5, 14, 23],
+                     [8, 17, 26]]
+        jk_plane3 = [[3, 12, 21],
+                     [6, 15, 24],
+                     [9, 18, 27]]
+        kj_plane1 = [[1, 4, 7],
+                     [10, 13, 16], [19, 22, 25]]
+        kj_plane2 = [[2, 5, 8],
+                     [11, 14, 17], [20, 23, 26]]
+        kj_plane3 = [[3, 6, 9],
+                     [12, 15, 18], [21, 24, 27]]
+        ij_plane1 = [[1, 4, 7],
+                     [2, 5, 8],
+                     [3, 6, 9]]
+        ij_plane2 = [[10, 13, 16],
+                     [11, 14, 17],
+                     [12, 15, 18]]
+        ij_plane3 = [[19, 22, 25],
+                     [20, 23, 26],
+                     [21, 24, 27]]
+        ik_plane1 = [[1, 10, 19],
+                     [2, 11, 20],
+                     [3, 12, 21]]
+        ik_plane2 = [[4, 13, 22],
+                     [5, 14, 23],
+                     [6, 15, 24]]
+        ik_plane3 = [[7, 16, 25],
+                     [8, 17, 26],
+                     [9, 18, 27]]
+        ijk_space = [jk_plane1, jk_plane2, jk_plane3]
+        ikj_space = [kj_plane1, kj_plane2, kj_plane3]
+        jik_space = [ik_plane1, ik_plane2, ik_plane3]
+        jki_space = [ki_plane1, ki_plane2, ki_plane3]
+        kij_space = [ij_plane1, ij_plane2, ij_plane3]
+        x = array([plane1, plane2, plane3])
+
+        assert_array_almost_equal(fftn(x),
+                                  fftn(x, axes=(-3, -2, -1)))  # kji_space
+        assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
+        assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
+        y = fftn(x, axes=(2, 1, 0))  # ijk_space
+        assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
+        y = fftn(x, axes=(2, 0, 1))  # ikj_space
+        assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
+                                  fftn(ikj_space))
+        y = fftn(x, axes=(1, 2, 0))  # jik_space
+        assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
+                                  fftn(jik_space))
+        y = fftn(x, axes=(1, 0, 2))  # jki_space
+        assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
+        y = fftn(x, axes=(0, 2, 1))  # kij_space
+        assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
+
+        y = fftn(x, axes=(-2, -1))  # ji_plane
+        assert_array_almost_equal(fftn(plane1), y[0])
+        assert_array_almost_equal(fftn(plane2), y[1])
+        assert_array_almost_equal(fftn(plane3), y[2])
+
+        y = fftn(x, axes=(1, 2))  # ji_plane
+        assert_array_almost_equal(fftn(plane1), y[0])
+        assert_array_almost_equal(fftn(plane2), y[1])
+        assert_array_almost_equal(fftn(plane3), y[2])
+
+        y = fftn(x, axes=(-3, -2))  # kj_plane
+        assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
+        assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
+        assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
+
+        y = fftn(x, axes=(-3, -1))  # ki_plane
+        assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
+        assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
+        assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
+
+        y = fftn(x, axes=(-1, -2))  # ij_plane
+        assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
+        assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
+        assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
+
+        y = fftn(x, axes=(-1, -3))  # ik_plane
+        assert_array_almost_equal(fftn(ik_plane1),
+                                  swapaxes(y[:, 0, :], -1, -2))
+        assert_array_almost_equal(fftn(ik_plane2),
+                                  swapaxes(y[:, 1, :], -1, -2))
+        assert_array_almost_equal(fftn(ik_plane3),
+                                  swapaxes(y[:, 2, :], -1, -2))
+
+        y = fftn(x, axes=(-2, -3))  # jk_plane
+        assert_array_almost_equal(fftn(jk_plane1),
+                                  swapaxes(y[:, :, 0], -1, -2))
+        assert_array_almost_equal(fftn(jk_plane2),
+                                  swapaxes(y[:, :, 1], -1, -2))
+        assert_array_almost_equal(fftn(jk_plane3),
+                                  swapaxes(y[:, :, 2], -1, -2))
+
+        y = fftn(x, axes=(-1,))  # i_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
+        y = fftn(x, axes=(-2,))  # j_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
+        y = fftn(x, axes=(0,))  # k_line
+        for i in range(3):
+            for j in range(3):
+                assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
+
+        y = fftn(x, axes=())  # point
+        assert_array_almost_equal(y, x)
+
+    def test_shape_argument(self):
+        small_x = [[1, 2, 3],
+                   [4, 5, 6]]
+        large_x1 = [[1, 2, 3, 0],
+                    [4, 5, 6, 0],
+                    [0, 0, 0, 0],
+                    [0, 0, 0, 0]]
+
+        y = fftn(small_x, s=(4, 4))
+        assert_array_almost_equal(y, fftn(large_x1))
+
+        y = fftn(small_x, s=(3, 4))
+        assert_array_almost_equal(y, fftn(large_x1[:-1]))
+
+    def test_shape_axes_argument(self):
+        small_x = [[1, 2, 3],
+                   [4, 5, 6],
+                   [7, 8, 9]]
+        large_x1 = array([[1, 2, 3, 0],
+                          [4, 5, 6, 0],
+                          [7, 8, 9, 0],
+                          [0, 0, 0, 0]])
+        y = fftn(small_x, s=(4, 4), axes=(-2, -1))
+        assert_array_almost_equal(y, fftn(large_x1))
+        y = fftn(small_x, s=(4, 4), axes=(-1, -2))
+
+        assert_array_almost_equal(y, swapaxes(
+            fftn(swapaxes(large_x1, -1, -2)), -1, -2))
+
+    def test_shape_axes_argument2(self):
+        # Change shape of the last axis
+        x = numpy.random.random((10, 5, 3, 7))
+        y = fftn(x, axes=(-1,), s=(8,))
+        assert_array_almost_equal(y, fft(x, axis=-1, n=8))
+
+        # Change shape of an arbitrary axis which is not the last one
+        x = numpy.random.random((10, 5, 3, 7))
+        y = fftn(x, axes=(-2,), s=(8,))
+        assert_array_almost_equal(y, fft(x, axis=-2, n=8))
+
+        # Change shape of axes: cf #244, where shape and axes were mixed up
+        x = numpy.random.random((4, 4, 2))
+        y = fftn(x, axes=(-3, -2), s=(8, 8))
+        assert_array_almost_equal(y,
+                                  numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
+
+    def test_shape_argument_more(self):
+        x = zeros((4, 4, 2))
+        with assert_raises(ValueError,
+                           match="shape requires more axes than are present"):
+            fftn(x, s=(8, 8, 2, 1))
+
+    def test_invalid_sizes(self):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            fftn([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            fftn([[1, 1], [2, 2]], (4, -3))
+
+    def test_no_axes(self):
+        x = numpy.random.random((2,2,2))
+        assert_allclose(fftn(x, axes=[]), x, atol=1e-7)
+
+    def test_regression_244(self):
+        """FFT returns wrong result with axes parameter."""
+        # fftn (and hence fft2) used to break when both axes and shape were used
+        x = numpy.ones((4, 4, 2))
+        y = fftn(x, s=(8, 8), axes=(-3, -2))
+        y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
+        assert_allclose(y, y_r)
+
+
+class TestIfftn:
+    dtype = None
+    cdtype = None
+
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.parametrize('dtype,cdtype,maxnlp',
+                             [(np.float64, np.complex128, 2000),
+                              (np.float32, np.complex64, 3500)])
+    def test_definition(self, dtype, cdtype, maxnlp):
+        rng = np.random.default_rng(1234)
+        x = np.array([[1, 2, 3],
+                      [4, 5, 6],
+                      [7, 8, 9]], dtype=dtype)
+        y = ifftn(x)
+        assert_equal(y.dtype, cdtype)
+        assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
+
+        x = rng.random((20, 26))
+        assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+        x = rng.random((5, 4, 3, 20))
+        assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+    @pytest.mark.parametrize('maxnlp', [2000, 3500])
+    @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
+    def test_random_complex(self, maxnlp, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random([size, size]) + 1j * rng.random([size, size])
+        assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
+        assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
+
+    def test_invalid_sizes(self):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            ifftn([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            ifftn([[1, 1], [2, 2]], (4, -3))
+
+    def test_no_axes(self):
+        x = numpy.random.random((2,2,2))
+        assert_allclose(ifftn(x, axes=[]), x, atol=1e-7)
+
+class TestRfftn:
+    dtype = None
+    cdtype = None
+
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.parametrize('dtype,cdtype,maxnlp',
+                             [(np.float64, np.complex128, 2000),
+                              (np.float32, np.complex64, 3500)])
+    def test_definition(self, dtype, cdtype, maxnlp):
+        rng = np.random.default_rng(1234)
+        x = np.array([[1, 2, 3],
+                      [4, 5, 6],
+                      [7, 8, 9]], dtype=dtype)
+        y = rfftn(x)
+        assert_equal(y.dtype, cdtype)
+        assert_array_almost_equal_nulp(y, direct_rdftn(x), maxnlp)
+
+        x = rng.random((20, 26))
+        assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
+
+        x = rng.random((5, 4, 3, 20))
+        assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
+
+    @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
+    def test_random(self, size):
+        rng = np.random.default_rng(1234)
+        x = rng.random([size, size])
+        assert_allclose(irfftn(rfftn(x), x.shape), x, atol=1e-10)
+
+    @pytest.mark.parametrize('func', [rfftn, irfftn])
+    def test_invalid_sizes(self, func):
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[1, 0\]\) specified"):
+            func([[]])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[4, -3\]\) specified"):
+            func([[1, 1], [2, 2]], (4, -3))
+
+    @pytest.mark.parametrize('func', [rfftn, irfftn])
+    def test_no_axes(self, func):
+        with assert_raises(ValueError,
+                           match="at least 1 axis must be transformed"):
+            func([], axes=[])
+
+    def test_complex_input(self):
+        with assert_raises(TypeError, match="x must be a real sequence"):
+            rfftn(np.zeros(10, dtype=np.complex64))
+
+
+class FakeArray:
+    def __init__(self, data):
+        self._data = data
+        self.__array_interface__ = data.__array_interface__
+
+
+class FakeArray2:
+    def __init__(self, data):
+        self._data = data
+
+    def __array__(self, dtype=None, copy=None):
+        return self._data
+
+# TODO: Is this test actually valuable? The behavior it's testing shouldn't be
+# relied upon by users except for overwrite_x = False
+class TestOverwrite:
+    """Check input overwrite behavior of the FFT functions."""
+
+    real_dtypes = [np.float32, np.float64, np.longdouble]
+    dtypes = real_dtypes + [np.complex64, np.complex128, np.clongdouble]
+    fftsizes = [8, 16, 32]
+
+    def _check(self, x, routine, fftsize, axis, overwrite_x, should_overwrite):
+        x2 = x.copy()
+        for fake in [lambda x: x, FakeArray, FakeArray2]:
+            routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
+
+            sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
+                   f"axis={axis!r}, overwrite_x={overwrite_x!r})")
+            if not should_overwrite:
+                assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+    def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
+                  fftsize, overwrite_x):
+        np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+        else:
+            data = np.random.randn(*shape)
+        data = data.astype(dtype)
+
+        should_overwrite = (overwrite_x
+                            and dtype in overwritable_dtypes
+                            and fftsize <= shape[axis])
+        self._check(data, routine, fftsize, axis,
+                    overwrite_x=overwrite_x,
+                    should_overwrite=should_overwrite)
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    @pytest.mark.parametrize('fftsize', fftsizes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), -1),
+                                            ((16, 2), 0),
+                                            ((2, 16), 1)])
+    def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
+        overwritable = (np.clongdouble, np.complex128, np.complex64)
+        self._check_1d(fft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+        self._check_1d(ifft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+
+    @pytest.mark.parametrize('dtype', real_dtypes)
+    @pytest.mark.parametrize('fftsize', fftsizes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), -1),
+                                            ((16, 2), 0),
+                                            ((2, 16), 1)])
+    def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
+        overwritable = self.real_dtypes
+        self._check_1d(irfft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+        self._check_1d(rfft, dtype, shape, axes, overwritable,
+                       fftsize, overwrite_x)
+
+    def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
+                      overwrite_x):
+        np.random.seed(1234)
+        if np.issubdtype(dtype, np.complexfloating):
+            data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+        else:
+            data = np.random.randn(*shape)
+        data = data.astype(dtype)
+
+        def fftshape_iter(shp):
+            if len(shp) <= 0:
+                yield ()
+            else:
+                for j in (shp[0]//2, shp[0], shp[0]*2):
+                    for rest in fftshape_iter(shp[1:]):
+                        yield (j,) + rest
+
+        def part_shape(shape, axes):
+            if axes is None:
+                return shape
+            else:
+                return tuple(np.take(shape, axes))
+
+        def should_overwrite(data, shape, axes):
+            s = part_shape(data.shape, axes)
+            return (overwrite_x and
+                    np.prod(shape) <= np.prod(s)
+                    and dtype in overwritable_dtypes)
+
+        for fftshape in fftshape_iter(part_shape(shape, axes)):
+            self._check(data, routine, fftshape, axes,
+                        overwrite_x=overwrite_x,
+                        should_overwrite=should_overwrite(data, fftshape, axes))
+            if data.ndim > 1:
+                # check fortran order
+                self._check(data.T, routine, fftshape, axes,
+                            overwrite_x=overwrite_x,
+                            should_overwrite=should_overwrite(
+                                data.T, fftshape, axes))
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    @pytest.mark.parametrize('overwrite_x', [True, False])
+    @pytest.mark.parametrize('shape,axes', [((16,), None),
+                                            ((16,), (0,)),
+                                            ((16, 2), (0,)),
+                                            ((2, 16), (1,)),
+                                            ((8, 16), None),
+                                            ((8, 16), (0, 1)),
+                                            ((8, 16, 2), (0, 1)),
+                                            ((8, 16, 2), (1, 2)),
+                                            ((8, 16, 2), (0,)),
+                                            ((8, 16, 2), (1,)),
+                                            ((8, 16, 2), (2,)),
+                                            ((8, 16, 2), None),
+                                            ((8, 16, 2), (0, 1, 2))])
+    def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
+        overwritable = (np.clongdouble, np.complex128, np.complex64)
+        self._check_nd_one(fftn, dtype, shape, axes, overwritable,
+                           overwrite_x)
+        self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
+                           overwrite_x)
+
+
+@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
+                                 rfft, irfft, rfftn, irfftn])
+def test_invalid_norm(func):
+    x = np.arange(10, dtype=float)
+    with assert_raises(ValueError,
+                       match='Invalid norm value \'o\', should be'
+                             ' "backward", "ortho" or "forward"'):
+        func(x, norm='o')
+
+
+@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
+                                   irfft, irfftn, hfft, hfftn])
+def test_swapped_byte_order_complex(func):
+    rng = np.random.RandomState(1234)
+    x = rng.rand(10) + 1j * rng.rand(10)
+    assert_allclose(func(swap_byteorder(x)), func(x))
+
+
+@pytest.mark.parametrize('func', [ihfft, ihfftn, rfft, rfftn])
+def test_swapped_byte_order_real(func):
+    rng = np.random.RandomState(1234)
+    x = rng.rand(10)
+    assert_allclose(func(swap_byteorder(x)), func(x))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..38b3f0a7367a9e97a97133f62ddb5dfb223581ed
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py
@@ -0,0 +1,505 @@
+from os.path import join, dirname
+from collections.abc import Callable
+from threading import Lock
+
+import numpy as np
+from numpy.testing import (
+    assert_array_almost_equal, assert_equal, assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.fft._pocketfft.realtransforms import (
+    dct, idct, dst, idst, dctn, idctn, dstn, idstn)
+
+fftpack_test_dir = join(dirname(__file__), '..', '..', '..', 'fftpack', 'tests')
+
+MDATA_COUNT = 8
+FFTWDATA_COUNT = 14
+
+def is_longdouble_binary_compatible():
+    try:
+        one = np.frombuffer(
+            b'\x00\x00\x00\x00\x00\x00\x00\x80\xff\x3f\x00\x00\x00\x00\x00\x00',
+            dtype=' decimal
+dec_map: DecMapType = {
+    # DCT
+    (dct, np.float64, 1): 13,
+    (dct, np.float32, 1): 6,
+
+    (dct, np.float64, 2): 14,
+    (dct, np.float32, 2): 5,
+
+    (dct, np.float64, 3): 14,
+    (dct, np.float32, 3): 5,
+
+    (dct, np.float64, 4): 13,
+    (dct, np.float32, 4): 6,
+
+    # IDCT
+    (idct, np.float64, 1): 14,
+    (idct, np.float32, 1): 6,
+
+    (idct, np.float64, 2): 14,
+    (idct, np.float32, 2): 5,
+
+    (idct, np.float64, 3): 14,
+    (idct, np.float32, 3): 5,
+
+    (idct, np.float64, 4): 14,
+    (idct, np.float32, 4): 6,
+
+    # DST
+    (dst, np.float64, 1): 13,
+    (dst, np.float32, 1): 6,
+
+    (dst, np.float64, 2): 14,
+    (dst, np.float32, 2): 6,
+
+    (dst, np.float64, 3): 14,
+    (dst, np.float32, 3): 7,
+
+    (dst, np.float64, 4): 13,
+    (dst, np.float32, 4): 5,
+
+    # IDST
+    (idst, np.float64, 1): 14,
+    (idst, np.float32, 1): 6,
+
+    (idst, np.float64, 2): 14,
+    (idst, np.float32, 2): 6,
+
+    (idst, np.float64, 3): 14,
+    (idst, np.float32, 3): 6,
+
+    (idst, np.float64, 4): 14,
+    (idst, np.float32, 4): 6,
+}
+
+for k,v in dec_map.copy().items():
+    if k[1] == np.float64:
+        dec_map[(k[0], np.longdouble, k[2])] = v
+    elif k[1] == np.float32:
+        dec_map[(k[0], int, k[2])] = v
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+class TestDCT:
+    def test_definition(self, rdt, type, fftwdata_size,
+                        reference_data, ref_lock):
+        with ref_lock:
+            x, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
+        y = dct(x, type=type)
+        assert_equal(y.dtype, dt)
+        dec = dec_map[(dct, rdt, type)]
+        assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
+
+    @pytest.mark.parametrize('size', [7, 8, 9, 16, 32, 64])
+    def test_axis(self, rdt, type, size):
+        nt = 2
+        dec = dec_map[(dct, rdt, type)]
+        x = np.random.randn(nt, size)
+        y = dct(x, type=type)
+        for j in range(nt):
+            assert_array_almost_equal(y[j], dct(x[j], type=type),
+                                      decimal=dec)
+
+        x = x.T
+        y = dct(x, axis=0, type=type)
+        for j in range(nt):
+            assert_array_almost_equal(y[:,j], dct(x[:,j], type=type),
+                                      decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct1_definition_ortho(rdt, mdata_x):
+    # Test orthornomal mode.
+    dec = dec_map[(dct, rdt, 1)]
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dct(x, norm='ortho', type=1)
+    y2 = naive_dct1(x, norm='ortho')
+    assert_equal(y.dtype, dt)
+    assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct2_definition_matlab(mdata_xy, rdt):
+    # Test correspondence with matlab (orthornomal mode).
+    dt = np.result_type(np.float32, rdt)
+    x = np.array(mdata_xy[0], dtype=dt)
+
+    yr = mdata_xy[1]
+    y = dct(x, norm="ortho", type=2)
+    dec = dec_map[(dct, rdt, 2)]
+    assert_equal(y.dtype, dt)
+    assert_array_almost_equal(y, yr, decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct3_definition_ortho(mdata_x, rdt):
+    # Test orthornomal mode.
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dct(x, norm='ortho', type=2)
+    xi = dct(y, norm="ortho", type=3)
+    dec = dec_map[(dct, rdt, 3)]
+    assert_equal(xi.dtype, dt)
+    assert_array_almost_equal(xi, x, decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct4_definition_ortho(mdata_x, rdt):
+    # Test orthornomal mode.
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dct(x, norm='ortho', type=4)
+    y2 = naive_dct4(x, norm='ortho')
+    dec = dec_map[(dct, rdt, 4)]
+    assert_equal(y.dtype, dt)
+    assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+def test_idct_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
+    with ref_lock:
+        xr, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
+    x = idct(yr, type=type)
+    dec = dec_map[(idct, rdt, type)]
+    assert_equal(x.dtype, dt)
+    assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+def test_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
+    with ref_lock:
+        xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
+    y = dst(xr, type=type)
+    dec = dec_map[(dst, rdt, type)]
+    assert_equal(y.dtype, dt)
+    assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dst1_definition_ortho(rdt, mdata_x):
+    # Test orthornomal mode.
+    dec = dec_map[(dst, rdt, 1)]
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dst(x, norm='ortho', type=1)
+    y2 = naive_dst1(x, norm='ortho')
+    assert_equal(y.dtype, dt)
+    assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dst4_definition_ortho(rdt, mdata_x):
+    # Test orthornomal mode.
+    dec = dec_map[(dst, rdt, 4)]
+    x = np.array(mdata_x, dtype=rdt)
+    dt = np.result_type(np.float32, rdt)
+    y = dst(x, norm='ortho', type=4)
+    y2 = naive_dst4(x, norm='ortho')
+    assert_equal(y.dtype, dt)
+    assert_array_almost_equal(y, y2, decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+def test_idst_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
+    with ref_lock:
+        xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
+    x = idst(yr, type=type)
+    dec = dec_map[(idst, rdt, type)]
+    assert_equal(x.dtype, dt)
+    assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
+
+
+@pytest.mark.parametrize('routine', [dct, dst, idct, idst])
+@pytest.mark.parametrize('dtype', [np.float32, np.float64, np.longdouble])
+@pytest.mark.parametrize('shape, axis', [
+    ((16,), -1), ((16, 2), 0), ((2, 16), 1)
+])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+@pytest.mark.parametrize('overwrite_x', [True, False])
+@pytest.mark.parametrize('norm', [None, 'ortho'])
+def test_overwrite(routine, dtype, shape, axis, type, norm, overwrite_x):
+    # Check input overwrite behavior
+    np.random.seed(1234)
+    if np.issubdtype(dtype, np.complexfloating):
+        x = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+    else:
+        x = np.random.randn(*shape)
+    x = x.astype(dtype)
+    x2 = x.copy()
+    routine(x2, type, None, axis, norm, overwrite_x=overwrite_x)
+
+    sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {None!r}, axis={axis!r}, "
+           f"overwrite_x={overwrite_x!r})")
+    if not overwrite_x:
+        assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+
+class Test_DCTN_IDCTN:
+    dec = 14
+    dct_type = [1, 2, 3, 4]
+    norms = [None, 'backward', 'ortho', 'forward']
+    rstate = np.random.RandomState(1234)
+    shape = (32, 16)
+    data = rstate.randn(*shape)
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    @pytest.mark.parametrize('axes', [None,
+                                      1, (1,), [1],
+                                      0, (0,), [0],
+                                      (0, 1), [0, 1],
+                                      (-2, -1), [-2, -1]])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', ['ortho'])
+    def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
+        tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
+        tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
+        assert_array_almost_equal(self.data, tmp, decimal=12)
+
+    @pytest.mark.parametrize('funcn,func', [(dctn, dct), (dstn, dst)])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', norms)
+    def test_dctn_vs_2d_reference(self, funcn, func, dct_type, norm):
+        y1 = funcn(self.data, type=dct_type, axes=None, norm=norm)
+        y2 = ref_2d(func, self.data, type=dct_type, norm=norm)
+        assert_array_almost_equal(y1, y2, decimal=11)
+
+    @pytest.mark.parametrize('funcn,func', [(idctn, idct), (idstn, idst)])
+    @pytest.mark.parametrize('dct_type', dct_type)
+    @pytest.mark.parametrize('norm', norms)
+    def test_idctn_vs_2d_reference(self, funcn, func, dct_type, norm):
+        fdata = dctn(self.data, type=dct_type, norm=norm)
+        y1 = funcn(fdata, type=dct_type, norm=norm)
+        y2 = ref_2d(func, fdata, type=dct_type, norm=norm)
+        assert_array_almost_equal(y1, y2, decimal=11)
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    def test_axes_and_shape(self, fforward, finverse):
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, s=self.data.shape[0], axes=(0, 1))
+
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            fforward(self.data, s=self.data.shape, axes=0)
+
+    @pytest.mark.parametrize('fforward', [dctn, dstn])
+    def test_shape(self, fforward):
+        tmp = fforward(self.data, s=(128, 128), axes=None)
+        assert_equal(tmp.shape, (128, 128))
+
+    @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+                                                   (dstn, idstn)])
+    @pytest.mark.parametrize('axes', [1, (1,), [1],
+                                      0, (0,), [0]])
+    def test_shape_is_none_with_axes(self, fforward, finverse, axes):
+        tmp = fforward(self.data, s=None, axes=axes, norm='ortho')
+        tmp = finverse(tmp, s=None, axes=axes, norm='ortho')
+        assert_array_almost_equal(self.data, tmp, decimal=self.dec)
+
+
+@pytest.mark.parametrize('func', [dct, dctn, idct, idctn,
+                                  dst, dstn, idst, idstn])
+def test_swapped_byte_order(func):
+    rng = np.random.RandomState(1234)
+    x = rng.rand(10)
+    swapped_dt = x.dtype.newbyteorder('S')
+    assert_allclose(func(x.astype(swapped_dt)), func(x))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c7a3d683dd78d3227a7de88f5c47569d2f4e17f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py
@@ -0,0 +1,693 @@
+from ._basic import _dispatch
+from scipy._lib.uarray import Dispatchable
+import numpy as np
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+@_dispatch
+def dctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, *, orthogonalize=None):
+    """
+    Return multidimensional Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result. If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the DCT is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idctn : Inverse multidimensional DCT
+
+    Notes
+    -----
+    For full details of the DCT types and normalization modes, as well as
+    references, see `dct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+          workers=None, orthogonalize=None):
+    """
+    Return multidimensional Inverse Discrete Cosine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are
+        None, `s` is ``x.shape``; if `s` is None but `axes` is
+        not None, then `s` is ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the IDCT is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dctn : multidimensional DCT
+
+    Notes
+    -----
+    For full details of the IDCT types and normalization modes, as well as
+    references, see `idct`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dctn, idctn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idctn(dctn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    Return multidimensional Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `shape` is -1, the size of the corresponding dimension
+        of `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the DST is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idstn : Inverse multidimensional DST
+
+    Notes
+    -----
+    For full details of the DST types and normalization modes, as well as
+    references, see `dst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
+          workers=None, orthogonalize=None):
+    """
+    Return multidimensional Inverse Discrete Sine Transform along the specified axes.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    s : int or array_like of ints or None, optional
+        The shape of the result.  If both `s` and `axes` (see below) are None,
+        `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
+        ``numpy.take(x.shape, axes, axis=0)``.
+        If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
+        If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
+        ``s[i]``.
+        If any element of `s` is -1, the size of the corresponding dimension of
+        `x` is used.
+    axes : int or array_like of ints or None, optional
+        Axes over which the IDST is computed. If not given, the last ``len(s)``
+        axes are used, or all axes if `s` is also not specified.
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dstn : multidimensional DST
+
+    Notes
+    -----
+    For full details of the IDST types and normalization modes, as well as
+    references, see `idst`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.fft import dstn, idstn
+    >>> rng = np.random.default_rng()
+    >>> y = rng.standard_normal((16, 16))
+    >>> np.allclose(y, idstn(dstn(y)))
+    True
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
+        orthogonalize=None):
+    r"""Return the Discrete Cosine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    y : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    idct : Inverse DCT
+
+    Notes
+    -----
+    For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
+    MATLAB ``dct(x)``.
+
+    .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the direct Fourier transform. To recover
+                 it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 1, 2 and 3 means the transform definition is
+    modified to give orthogonality of the DCT matrix (see below).
+
+    For ``norm="backward"``, there is no scaling on `dct` and the `idct` is
+    scaled by ``1/N`` where ``N`` is the "logical" size of the DCT. For
+    ``norm="forward"`` the ``1/N`` normalization is applied to the forward
+    `dct` instead and the `idct` is unnormalized.
+
+    There are, theoretically, 8 types of the DCT, only the first 4 types are
+    implemented in SciPy.'The' DCT generally refers to DCT type 2, and 'the'
+    Inverse DCT generally refers to DCT type 3.
+
+    **Type I**
+
+    There are several definitions of the DCT-I; we use the following
+    (for ``norm="backward"``)
+
+    .. math::
+
+       y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
+       \frac{\pi k n}{N-1} \right)
+
+    If ``orthogonalize=True``, ``x[0]`` and ``x[N-1]`` are multiplied by a
+    scaling factor of :math:`\sqrt{2}`, and ``y[0]`` and ``y[N-1]`` are divided
+    by :math:`\sqrt{2}`. When combined with ``norm="ortho"``, this makes the
+    corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    .. note::
+       The DCT-I is only supported for input size > 1.
+
+    **Type II**
+
+    There are several definitions of the DCT-II; we use the following
+    (for ``norm="backward"``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
+
+    If ``orthogonalize=True``, ``y[0]`` is divided by :math:`\sqrt{2}` which,
+    when combined with ``norm="ortho"``, makes the corresponding matrix of
+    coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions, we use the following (for
+    ``norm="backward"``)
+
+    .. math::
+
+       y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
+
+    If ``orthogonalize=True``, ``x[0]`` terms are multiplied by
+    :math:`\sqrt{2}` which, when combined with ``norm="ortho"``, makes the
+    corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
+    to a factor `2N`. The orthonormalized DCT-III is exactly the inverse of
+    the orthonormalized DCT-II.
+
+    **Type IV**
+
+    There are several definitions of the DCT-IV; we use the following
+    (for ``norm="backward"``)
+
+    .. math::
+
+       y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
+
+    ``orthogonalize`` has no effect here, as the DCT-IV matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    References
+    ----------
+    .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
+           Makhoul, `IEEE Transactions on acoustics, speech and signal
+           processing` vol. 28(1), pp. 27-34,
+           :doi:`10.1109/TASSP.1980.1163351` (1980).
+    .. [2] Wikipedia, "Discrete cosine transform",
+           https://en.wikipedia.org/wiki/Discrete_cosine_transform
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the FFT (though faster) for real,
+    even-symmetrical inputs. The output is also real and even-symmetrical.
+    Half of the FFT input is used to generate half of the FFT output:
+
+    >>> from scipy.fft import fft, dct
+    >>> import numpy as np
+    >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
+    array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])
+    >>> dct(np.array([4., 3., 5., 10.]), 1)
+    array([ 30.,  -8.,   6.,  -2.])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DCT (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform.  If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idct is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDCT variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    idct : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dct : Forward DCT
+
+    Notes
+    -----
+    For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
+    MATLAB ``idct(x)``.
+
+    .. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the inverse direct Fourier transform. To
+                 recover it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 1, 2 and 3 means the transform definition is
+    modified to give orthogonality of the IDCT matrix (see `dct` for the full
+    definitions).
+
+    'The' IDCT is the IDCT-II, which is the same as the normalized DCT-III.
+
+    The IDCT is equivalent to a normal DCT except for the normalization and
+    type. DCT type 1 and 4 are their own inverse and DCTs 2 and 3 are each
+    other's inverses.
+
+    Examples
+    --------
+    The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
+    inputs. The output is also real and even-symmetrical. Half of the IFFT
+    input is used to generate half of the IFFT output:
+
+    >>> from scipy.fft import ifft, idct
+    >>> import numpy as np
+    >>> ifft(np.array([ 30.,  -8.,   6.,  -2.,   6.,  -8.])).real
+    array([  4.,   3.,   5.,  10.,   5.,   3.])
+    >>> idct(np.array([ 30.,  -8.,   6.,  -2.]), 1)
+    array([  4.,   3.,   5.,  10.])
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
+        orthogonalize=None):
+    r"""
+    Return the Discrete Sine Transform of arbitrary type sequence x.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform. If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the dst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized DST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    dst : ndarray of reals
+        The transformed input array.
+
+    See Also
+    --------
+    idst : Inverse DST
+
+    Notes
+    -----
+    .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the direct Fourier transform. To recover
+                 it you must specify ``orthogonalize=False``.
+
+    For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 2 and 3 means the transform definition is
+    modified to give orthogonality of the DST matrix (see below).
+
+    For ``norm="backward"``, there is no scaling on the `dst` and the `idst` is
+    scaled by ``1/N`` where ``N`` is the "logical" size of the DST.
+
+    There are, theoretically, 8 types of the DST for different combinations of
+    even/odd boundary conditions and boundary off sets [1]_, only the first
+    4 types are implemented in SciPy.
+
+    **Type I**
+
+    There are several definitions of the DST-I; we use the following for
+    ``norm="backward"``. DST-I assumes the input is odd around :math:`n=-1` and
+    :math:`n=N`.
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
+
+    Note that the DST-I is only supported for input size > 1.
+    The (unnormalized) DST-I is its own inverse, up to a factor :math:`2(N+1)`.
+    The orthonormalized DST-I is exactly its own inverse.
+
+    ``orthogonalize`` has no effect here, as the DST-I matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    **Type II**
+
+    There are several definitions of the DST-II; we use the following for
+    ``norm="backward"``. DST-II assumes the input is odd around :math:`n=-1/2` and
+    :math:`n=N-1/2`; the output is odd around :math:`k=-1` and even around :math:`k=N-1`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
+
+    If ``orthogonalize=True``, ``y[-1]`` is divided :math:`\sqrt{2}` which, when
+    combined with ``norm="ortho"``, makes the corresponding matrix of
+    coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    **Type III**
+
+    There are several definitions of the DST-III, we use the following (for
+    ``norm="backward"``). DST-III assumes the input is odd around :math:`n=-1` and
+    even around :math:`n=N-1`
+
+    .. math::
+
+        y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
+        \frac{\pi(2k+1)(n+1)}{2N}\right)
+
+    If ``orthogonalize=True``, ``x[-1]`` is multiplied by :math:`\sqrt{2}`
+    which, when combined with ``norm="ortho"``, makes the corresponding matrix
+    of coefficients orthonormal (``O @ O.T = np.eye(N)``).
+
+    The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
+    to a factor :math:`2N`. The orthonormalized DST-III is exactly the inverse of the
+    orthonormalized DST-II.
+
+    **Type IV**
+
+    There are several definitions of the DST-IV, we use the following (for
+    ``norm="backward"``). DST-IV assumes the input is odd around :math:`n=-0.5` and
+    even around :math:`n=N-0.5`
+
+    .. math::
+
+        y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
+
+    ``orthogonalize`` has no effect here, as the DST-IV matrix is already
+    orthogonal up to a scale factor of ``2N``.
+
+    The (unnormalized) DST-IV is its own inverse, up to a factor :math:`2N`. The
+    orthonormalized DST-IV is exactly its own inverse.
+
+    References
+    ----------
+    .. [1] Wikipedia, "Discrete sine transform",
+           https://en.wikipedia.org/wiki/Discrete_sine_transform
+
+    """
+    return (Dispatchable(x, np.ndarray),)
+
+
+@_dispatch
+def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
+         workers=None, orthogonalize=None):
+    """
+    Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    type : {1, 2, 3, 4}, optional
+        Type of the DST (see Notes). Default type is 2.
+    n : int, optional
+        Length of the transform. If ``n < x.shape[axis]``, `x` is
+        truncated.  If ``n > x.shape[axis]``, `x` is zero-padded. The
+        default results in ``n = x.shape[axis]``.
+    axis : int, optional
+        Axis along which the idst is computed; the default is over the
+        last axis (i.e., ``axis=-1``).
+    norm : {"backward", "ortho", "forward"}, optional
+        Normalization mode (see Notes). Default is "backward".
+    overwrite_x : bool, optional
+        If True, the contents of `x` can be destroyed; the default is False.
+    workers : int, optional
+        Maximum number of workers to use for parallel computation. If negative,
+        the value wraps around from ``os.cpu_count()``.
+        See :func:`~scipy.fft.fft` for more details.
+    orthogonalize : bool, optional
+        Whether to use the orthogonalized IDST variant (see Notes).
+        Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    idst : ndarray of real
+        The transformed input array.
+
+    See Also
+    --------
+    dst : Forward DST
+
+    Notes
+    -----
+    .. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
+                 correspondence with the inverse direct Fourier transform.
+
+    For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
+    overall factor in both directions. By default, the transform is also
+    orthogonalized which for types 2 and 3 means the transform definition is
+    modified to give orthogonality of the DST matrix (see `dst` for the full
+    definitions).
+
+    'The' IDST is the IDST-II, which is the same as the normalized DST-III.
+
+    The IDST is equivalent to a normal DST except for the normalization and
+    type. DST type 1 and 4 are their own inverse and DSTs 2 and 3 are each
+    other's inverses.
+
+    """
+    return (Dispatchable(x, np.ndarray),)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..2042453733bec54860974cc1e20ba908e8c9b94d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py
@@ -0,0 +1,63 @@
+from scipy._lib._array_api import array_namespace
+import numpy as np
+from . import _pocketfft
+
+__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
+
+
+def _execute(pocketfft_func, x, type, s, axes, norm, 
+             overwrite_x, workers, orthogonalize):
+    xp = array_namespace(x)
+    x = np.asarray(x)
+    y = pocketfft_func(x, type, s, axes, norm,
+                       overwrite_x=overwrite_x, workers=workers,
+                       orthogonalize=orthogonalize)
+    return xp.asarray(y)
+
+
+def dctn(x, type=2, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_pocketfft.dctn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idctn(x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_pocketfft.idctn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dstn(x, type=2, s=None, axes=None, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.dstn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idstn(x, type=2, s=None, axes=None, norm=None,
+          overwrite_x=False, workers=None, *, orthogonalize=None):
+    return _execute(_pocketfft.idstn, x, type, s, axes, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dct(x, type=2, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.dct, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idct(x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.idct, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def dst(x, type=2, n=None, axis=-1, norm=None,
+        overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.dst, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
+
+
+def idst(x, type=2, n=None, axis=-1, norm=None,
+         overwrite_x=False, workers=None, orthogonalize=None):
+    return _execute(_pocketfft.idst, x, type, n, axis, norm, 
+                    overwrite_x, workers, orthogonalize)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..48a7d2b3b50501b84f7c18e366ad2e66782b4ab6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py
@@ -0,0 +1,96 @@
+import numpy as np
+import scipy.fft
+import threading
+
+class _MockFunction:
+    def __init__(self, return_value = None):
+        self.number_calls = threading.local()
+        self.return_value = return_value
+        self.last_args = threading.local()
+
+    def __call__(self, *args, **kwargs):
+        if not hasattr(self.number_calls, 'c'):
+            self.number_calls.c = 0
+
+        self.number_calls.c += 1
+        self.last_args.l = (args, kwargs)
+        return self.return_value
+
+
+fft = _MockFunction(np.random.random(10))
+fft2 = _MockFunction(np.random.random(10))
+fftn = _MockFunction(np.random.random(10))
+
+ifft = _MockFunction(np.random.random(10))
+ifft2 = _MockFunction(np.random.random(10))
+ifftn = _MockFunction(np.random.random(10))
+
+rfft = _MockFunction(np.random.random(10))
+rfft2 = _MockFunction(np.random.random(10))
+rfftn = _MockFunction(np.random.random(10))
+
+irfft = _MockFunction(np.random.random(10))
+irfft2 = _MockFunction(np.random.random(10))
+irfftn = _MockFunction(np.random.random(10))
+
+hfft = _MockFunction(np.random.random(10))
+hfft2 = _MockFunction(np.random.random(10))
+hfftn = _MockFunction(np.random.random(10))
+
+ihfft = _MockFunction(np.random.random(10))
+ihfft2 = _MockFunction(np.random.random(10))
+ihfftn = _MockFunction(np.random.random(10))
+
+dct = _MockFunction(np.random.random(10))
+idct = _MockFunction(np.random.random(10))
+dctn = _MockFunction(np.random.random(10))
+idctn = _MockFunction(np.random.random(10))
+
+dst = _MockFunction(np.random.random(10))
+idst = _MockFunction(np.random.random(10))
+dstn = _MockFunction(np.random.random(10))
+idstn = _MockFunction(np.random.random(10))
+
+fht = _MockFunction(np.random.random(10))
+ifht = _MockFunction(np.random.random(10))
+
+
+__ua_domain__ = "numpy.scipy.fft"
+
+
+_implements = {
+    scipy.fft.fft: fft,
+    scipy.fft.fft2: fft2,
+    scipy.fft.fftn: fftn,
+    scipy.fft.ifft: ifft,
+    scipy.fft.ifft2: ifft2,
+    scipy.fft.ifftn: ifftn,
+    scipy.fft.rfft: rfft,
+    scipy.fft.rfft2: rfft2,
+    scipy.fft.rfftn: rfftn,
+    scipy.fft.irfft: irfft,
+    scipy.fft.irfft2: irfft2,
+    scipy.fft.irfftn: irfftn,
+    scipy.fft.hfft: hfft,
+    scipy.fft.hfft2: hfft2,
+    scipy.fft.hfftn: hfftn,
+    scipy.fft.ihfft: ihfft,
+    scipy.fft.ihfft2: ihfft2,
+    scipy.fft.ihfftn: ihfftn,
+    scipy.fft.dct: dct,
+    scipy.fft.idct: idct,
+    scipy.fft.dctn: dctn,
+    scipy.fft.idctn: idctn,
+    scipy.fft.dst: dst,
+    scipy.fft.idst: idst,
+    scipy.fft.dstn: dstn,
+    scipy.fft.idstn: idstn,
+    scipy.fft.fht: fht,
+    scipy.fft.ifht: ifht
+}
+
+
+def __ua_function__(method, args, kwargs):
+    fn = _implements.get(method)
+    return (fn(*args, **kwargs) if fn is not None
+            else NotImplemented)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..933e9c0302d46faf33b3dc015d58996e3e46c058
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_backend.py
@@ -0,0 +1,98 @@
+from functools import partial
+
+import numpy as np
+import scipy.fft
+from scipy.fft import _fftlog, _pocketfft, set_backend
+from scipy.fft.tests import mock_backend
+
+from numpy.testing import assert_allclose, assert_equal
+import pytest
+
+fnames = ('fft', 'fft2', 'fftn',
+          'ifft', 'ifft2', 'ifftn',
+          'rfft', 'rfft2', 'rfftn',
+          'irfft', 'irfft2', 'irfftn',
+          'dct', 'idct', 'dctn', 'idctn',
+          'dst', 'idst', 'dstn', 'idstn',
+          'fht', 'ifht')
+
+np_funcs = (np.fft.fft, np.fft.fft2, np.fft.fftn,
+            np.fft.ifft, np.fft.ifft2, np.fft.ifftn,
+            np.fft.rfft, np.fft.rfft2, np.fft.rfftn,
+            np.fft.irfft, np.fft.irfft2, np.fft.irfftn,
+            np.fft.hfft, _pocketfft.hfft2, _pocketfft.hfftn,  # np has no hfftn
+            np.fft.ihfft, _pocketfft.ihfft2, _pocketfft.ihfftn,
+            _pocketfft.dct, _pocketfft.idct, _pocketfft.dctn, _pocketfft.idctn,
+            _pocketfft.dst, _pocketfft.idst, _pocketfft.dstn, _pocketfft.idstn,
+            # must provide required kwargs for fht, ifht
+            partial(_fftlog.fht, dln=2, mu=0.5),
+            partial(_fftlog.ifht, dln=2, mu=0.5))
+
+funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn,
+         scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn,
+         scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn,
+         scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn,
+         scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn,
+         scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn,
+         scipy.fft.dct, scipy.fft.idct, scipy.fft.dctn, scipy.fft.idctn,
+         scipy.fft.dst, scipy.fft.idst, scipy.fft.dstn, scipy.fft.idstn,
+         # must provide required kwargs for fht, ifht
+         partial(scipy.fft.fht, dln=2, mu=0.5),
+         partial(scipy.fft.ifht, dln=2, mu=0.5))
+
+mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn,
+         mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn,
+         mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn,
+         mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn,
+         mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn,
+         mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn,
+         mock_backend.dct, mock_backend.idct,
+         mock_backend.dctn, mock_backend.idctn,
+         mock_backend.dst, mock_backend.idst,
+         mock_backend.dstn, mock_backend.idstn,
+         mock_backend.fht, mock_backend.ifht)
+
+
+@pytest.mark.parametrize("func, np_func, mock", zip(funcs, np_funcs, mocks))
+def test_backend_call(func, np_func, mock):
+    x = np.arange(20).reshape((10,2))
+    answer = np_func(x.astype(np.float64))
+    assert_allclose(func(x), answer, atol=1e-10)
+
+    with set_backend(mock_backend, only=True):
+        mock.number_calls.c = 0
+        y = func(x)
+        assert_equal(y, mock.return_value)
+        assert_equal(mock.number_calls.c, 1)
+
+    assert_allclose(func(x), answer, atol=1e-10)
+
+
+plan_funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn,
+              scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn,
+              scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn,
+              scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn,
+              scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn,
+              scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn)
+
+plan_mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn,
+              mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn,
+              mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn,
+              mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn,
+              mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn,
+              mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn)
+
+
+@pytest.mark.parametrize("func, mock", zip(plan_funcs, plan_mocks))
+def test_backend_plan(func, mock):
+    x = np.arange(20).reshape((10, 2))
+
+    with pytest.raises(NotImplementedError, match='precomputed plan'):
+        func(x, plan='foo')
+
+    with set_backend(mock_backend, only=True):
+        mock.number_calls.c = 0
+        y = func(x, plan='foo')
+        assert_equal(y, mock.return_value)
+        assert_equal(mock.number_calls.c, 1)
+        assert_equal(mock.last_args.l[1]['plan'], 'foo')
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ed32d54c8936b8b36ff52ef7b639d05338a783c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_basic.py
@@ -0,0 +1,502 @@
+import queue
+import threading
+import multiprocessing
+import numpy as np
+import pytest
+from numpy.random import random
+from numpy.testing import assert_array_almost_equal, assert_allclose
+from pytest import raises as assert_raises
+import scipy.fft as fft
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import (
+    array_namespace, xp_size, xp_assert_close, xp_assert_equal
+)
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+# Expected input dtypes. Note that `scipy.fft` is more flexible for numpy,
+# but for C2C transforms like `fft.fft`, the array API standard only mandates
+# that complex dtypes should work, float32/float64 aren't guaranteed to.
+def get_expected_input_dtype(func, xp):
+    if func in [fft.fft, fft.fftn, fft.fft2,
+                fft.ifft, fft.ifftn, fft.ifft2,
+                fft.hfft, fft.hfftn, fft.hfft2,
+                fft.irfft, fft.irfftn, fft.irfft2]:
+        dtype = xp.complex128
+    elif func in [fft.rfft, fft.rfftn, fft.rfft2,
+                  fft.ihfft, fft.ihfftn, fft.ihfft2]:
+        dtype = xp.float64
+    else:
+        raise ValueError(f'Unknown FFT function: {func}')
+
+    return dtype
+
+
+def fft1(x):
+    L = len(x)
+    phase = -2j*np.pi*(np.arange(L)/float(L))
+    phase = np.arange(L).reshape(-1, 1) * phase
+    return np.sum(x*np.exp(phase), axis=1)
+
+class TestFFT:
+
+    def test_identity(self, xp):
+        maxlen = 512
+        x = xp.asarray(random(maxlen) + 1j*random(maxlen))
+        xr = xp.asarray(random(maxlen))
+        # Check some powers of 2 and some primes
+        for i in [1, 2, 16, 128, 512, 53, 149, 281, 397]:
+            xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i])
+            xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i])
+
+    @skip_xp_backends(np_only=True, reason='significant overhead for some backends')
+    def test_identity_extensive(self, xp):
+        maxlen = 512
+        x = xp.asarray(random(maxlen) + 1j*random(maxlen))
+        xr = xp.asarray(random(maxlen))
+        for i in range(1, maxlen):
+            xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i])
+            xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i])
+
+    def test_fft(self, xp):
+        x = random(30) + 1j*random(30)
+        expect = xp.asarray(fft1(x))
+        x = xp.asarray(x)
+        xp_assert_close(fft.fft(x), expect)
+        xp_assert_close(fft.fft(x, norm="backward"), expect)
+        xp_assert_close(fft.fft(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)),)
+        xp_assert_close(fft.fft(x, norm="forward"), expect / 30)
+
+    @skip_xp_backends(np_only=True, reason='some backends allow `n=0`')
+    def test_fft_n(self, xp):
+        x = xp.asarray([1, 2, 3], dtype=xp.complex128)
+        assert_raises(ValueError, fft.fft, x, 0)
+
+    def test_ifft(self, xp):
+        x = xp.asarray(random(30) + 1j*random(30))
+        xp_assert_close(fft.ifft(fft.fft(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.ifft(fft.fft(x, norm=norm), norm=norm), x)
+
+    def test_fft2(self, xp):
+        x = xp.asarray(random((30, 20)) + 1j*random((30, 20)))
+        expect = fft.fft(fft.fft(x, axis=1), axis=0)
+        xp_assert_close(fft.fft2(x), expect)
+        xp_assert_close(fft.fft2(x, norm="backward"), expect)
+        xp_assert_close(fft.fft2(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
+        xp_assert_close(fft.fft2(x, norm="forward"), expect / (30 * 20))
+
+    def test_ifft2(self, xp):
+        x = xp.asarray(random((30, 20)) + 1j*random((30, 20)))
+        expect = fft.ifft(fft.ifft(x, axis=1), axis=0)
+        xp_assert_close(fft.ifft2(x), expect)
+        xp_assert_close(fft.ifft2(x, norm="backward"), expect)
+        xp_assert_close(fft.ifft2(x, norm="ortho"),
+                        expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
+        xp_assert_close(fft.ifft2(x, norm="forward"), expect * (30 * 20))
+
+    def test_fftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10)))
+        expect = fft.fft(fft.fft(fft.fft(x, axis=2), axis=1), axis=0)
+        xp_assert_close(fft.fftn(x), expect)
+        xp_assert_close(fft.fftn(x, norm="backward"), expect)
+        xp_assert_close(fft.fftn(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)))
+        xp_assert_close(fft.fftn(x, norm="forward"), expect / (30 * 20 * 10))
+
+    def test_ifftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10)))
+        expect = fft.ifft(fft.ifft(fft.ifft(x, axis=2), axis=1), axis=0)
+        xp_assert_close(fft.ifftn(x), expect, rtol=1e-7)
+        xp_assert_close(fft.ifftn(x, norm="backward"), expect, rtol=1e-7)
+        xp_assert_close(
+            fft.ifftn(x, norm="ortho"),
+            fft.ifftn(x) * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))
+        )
+        xp_assert_close(fft.ifftn(x, norm="forward"),
+                        expect * (30 * 20 * 10),
+                        rtol=1e-7)
+
+    def test_rfft(self, xp):
+        x = xp.asarray(random(29), dtype=xp.float64)
+        for n in [xp_size(x), 2*xp_size(x)]:
+            for norm in [None, "backward", "ortho", "forward"]:
+                xp_assert_close(fft.rfft(x, n=n, norm=norm),
+                                fft.fft(xp.asarray(x, dtype=xp.complex128),
+                                        n=n, norm=norm)[:(n//2 + 1)])
+            xp_assert_close(
+                fft.rfft(x, n=n, norm="ortho"),
+                fft.rfft(x, n=n) / xp.sqrt(xp.asarray(n, dtype=xp.float64))
+            )
+
+    def test_irfft(self, xp):
+        x = xp.asarray(random(30))
+        xp_assert_close(fft.irfft(fft.rfft(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.irfft(fft.rfft(x, norm=norm), norm=norm), x)
+
+    def test_rfft2(self, xp):
+        x = xp.asarray(random((30, 20)), dtype=xp.float64)
+        expect = fft.fft2(xp.asarray(x, dtype=xp.complex128))[:, :11]
+        xp_assert_close(fft.rfft2(x), expect)
+        xp_assert_close(fft.rfft2(x, norm="backward"), expect)
+        xp_assert_close(fft.rfft2(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
+        xp_assert_close(fft.rfft2(x, norm="forward"), expect / (30 * 20))
+
+    def test_irfft2(self, xp):
+        x = xp.asarray(random((30, 20)))
+        xp_assert_close(fft.irfft2(fft.rfft2(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.irfft2(fft.rfft2(x, norm=norm), norm=norm), x)
+
+    def test_rfftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)), dtype=xp.float64)
+        expect = fft.fftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6]
+        xp_assert_close(fft.rfftn(x), expect)
+        xp_assert_close(fft.rfftn(x, norm="backward"), expect)
+        xp_assert_close(fft.rfftn(x, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)))
+        xp_assert_close(fft.rfftn(x, norm="forward"), expect / (30 * 20 * 10))
+
+    def test_irfftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)))
+        xp_assert_close(fft.irfftn(fft.rfftn(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.irfftn(fft.rfftn(x, norm=norm), norm=norm), x)
+
+    def test_hfft(self, xp):
+        x = random(14) + 1j*random(14)
+        x_herm = np.concatenate((random(1), x, random(1)))
+        x = np.concatenate((x_herm, x[::-1].conj()))
+        x = xp.asarray(x)
+        x_herm = xp.asarray(x_herm)
+        expect = xp.real(fft.fft(x))
+        xp_assert_close(fft.hfft(x_herm), expect)
+        xp_assert_close(fft.hfft(x_herm, norm="backward"), expect)
+        xp_assert_close(fft.hfft(x_herm, norm="ortho"),
+                        expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)))
+        xp_assert_close(fft.hfft(x_herm, norm="forward"), expect / 30)
+
+    def test_ihfft(self, xp):
+        x = random(14) + 1j*random(14)
+        x_herm = np.concatenate((random(1), x, random(1)))
+        x = np.concatenate((x_herm, x[::-1].conj()))
+        x = xp.asarray(x)
+        x_herm = xp.asarray(x_herm)
+        xp_assert_close(fft.ihfft(fft.hfft(x_herm)), x_herm)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.ihfft(fft.hfft(x_herm, norm=norm), norm=norm), x_herm)
+
+    def test_hfft2(self, xp):
+        x = xp.asarray(random((30, 20)))
+        xp_assert_close(fft.hfft2(fft.ihfft2(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.hfft2(fft.ihfft2(x, norm=norm), norm=norm), x)
+
+    def test_ihfft2(self, xp):
+        x = xp.asarray(random((30, 20)), dtype=xp.float64)
+        expect = fft.ifft2(xp.asarray(x, dtype=xp.complex128))[:, :11]
+        xp_assert_close(fft.ihfft2(x), expect)
+        xp_assert_close(fft.ihfft2(x, norm="backward"), expect)
+        xp_assert_close(
+            fft.ihfft2(x, norm="ortho"),
+            expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))
+        )
+        xp_assert_close(fft.ihfft2(x, norm="forward"), expect * (30 * 20))
+
+    def test_hfftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)))
+        xp_assert_close(fft.hfftn(fft.ihfftn(x)), x)
+        for norm in ["backward", "ortho", "forward"]:
+            xp_assert_close(fft.hfftn(fft.ihfftn(x, norm=norm), norm=norm), x)
+
+    def test_ihfftn(self, xp):
+        x = xp.asarray(random((30, 20, 10)), dtype=xp.float64)
+        expect = fft.ifftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6]
+        xp_assert_close(expect, fft.ihfftn(x))
+        xp_assert_close(expect, fft.ihfftn(x, norm="backward"))
+        xp_assert_close(
+            fft.ihfftn(x, norm="ortho"),
+            expect * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))
+        )
+        xp_assert_close(fft.ihfftn(x, norm="forward"), expect * (30 * 20 * 10))
+
+    def _check_axes(self, op, xp):
+        dtype = get_expected_input_dtype(op, xp)
+        x = xp.asarray(random((30, 20, 10)), dtype=dtype)
+        axes = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
+        xp_test = array_namespace(x)
+        for a in axes:
+            op_tr = op(xp_test.permute_dims(x, axes=a))
+            tr_op = xp_test.permute_dims(op(x, axes=a), axes=a)
+            xp_assert_close(op_tr, tr_op)
+
+    @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn, fft.rfftn, fft.irfftn])
+    def test_axes_standard(self, op, xp):
+        self._check_axes(op, xp)
+
+    @pytest.mark.parametrize("op", [fft.hfftn, fft.ihfftn])
+    def test_axes_non_standard(self, op, xp):
+        self._check_axes(op, xp)
+
+    @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn,
+                                    fft.rfftn, fft.irfftn])
+    def test_axes_subset_with_shape_standard(self, op, xp):
+        dtype = get_expected_input_dtype(op, xp)
+        x = xp.asarray(random((16, 8, 4)), dtype=dtype)
+        axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)]
+        xp_test = array_namespace(x)
+        for a in axes:
+            # different shape on the first two axes
+            shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax]
+                           for ax in range(x.ndim)])
+            # transform only the first two axes
+            op_tr = op(xp_test.permute_dims(x, axes=a),
+                       s=shape[:2], axes=(0, 1))
+            tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]),
+                                         axes=a)
+            xp_assert_close(op_tr, tr_op)
+
+    @pytest.mark.parametrize("op", [fft.fft2, fft.ifft2,
+                                    fft.rfft2, fft.irfft2,
+                                    fft.hfft2, fft.ihfft2,
+                                    fft.hfftn, fft.ihfftn])
+    def test_axes_subset_with_shape_non_standard(self, op, xp):
+        dtype = get_expected_input_dtype(op, xp)
+        x = xp.asarray(random((16, 8, 4)), dtype=dtype)
+        axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)]
+        xp_test = array_namespace(x)
+        for a in axes:
+            # different shape on the first two axes
+            shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax]
+                           for ax in range(x.ndim)])
+            # transform only the first two axes
+            op_tr = op(xp_test.permute_dims(x, axes=a), s=shape[:2], axes=(0, 1))
+            tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]), axes=a)
+            xp_assert_close(op_tr, tr_op)
+
+    def test_all_1d_norm_preserving(self, xp):
+        # verify that round-trip transforms are norm-preserving
+        x = xp.asarray(random(30), dtype=xp.float64)
+        xp_test = array_namespace(x)
+        x_norm = xp_test.linalg.vector_norm(x)
+        n = xp_size(x) * 2
+        func_pairs = [(fft.rfft, fft.irfft),
+                      # hfft: order so the first function takes x.size samples
+                      #       (necessary for comparison to x_norm above)
+                      (fft.ihfft, fft.hfft),
+                      # functions that expect complex dtypes at the end
+                      (fft.fft, fft.ifft),
+                      ]
+        for forw, back in func_pairs:
+            if forw == fft.fft:
+                x = xp.asarray(x, dtype=xp.complex128)
+                x_norm = xp_test.linalg.vector_norm(x)
+            for n in [xp_size(x), 2*xp_size(x)]:
+                for norm in ['backward', 'ortho', 'forward']:
+                    tmp = forw(x, n=n, norm=norm)
+                    tmp = back(tmp, n=n, norm=norm)
+                    xp_assert_close(xp_test.linalg.vector_norm(tmp), x_norm)
+
+    @skip_xp_backends(np_only=True)
+    @pytest.mark.parametrize("dtype", [np.float16, np.longdouble])
+    def test_dtypes_nonstandard(self, dtype):
+        x = random(30).astype(dtype)
+        out_dtypes = {np.float16: np.complex64, np.longdouble: np.clongdouble}
+        x_complex = x.astype(out_dtypes[dtype])
+
+        res_fft = fft.ifft(fft.fft(x))
+        res_rfft = fft.irfft(fft.rfft(x))
+        res_hfft = fft.hfft(fft.ihfft(x), x.shape[0])
+        # Check both numerical results and exact dtype matches
+        assert_array_almost_equal(res_fft, x_complex)
+        assert_array_almost_equal(res_rfft, x)
+        assert_array_almost_equal(res_hfft, x)
+        assert res_fft.dtype == x_complex.dtype
+        assert res_rfft.dtype == np.result_type(np.float32, x.dtype)
+        assert res_hfft.dtype == np.result_type(np.float32, x.dtype)
+
+    @pytest.mark.parametrize("dtype", ["float32", "float64"])
+    def test_dtypes_real(self, dtype, xp):
+        x = xp.asarray(random(30), dtype=getattr(xp, dtype))
+
+        res_rfft = fft.irfft(fft.rfft(x))
+        res_hfft = fft.hfft(fft.ihfft(x), x.shape[0])
+        # Check both numerical results and exact dtype matches
+        xp_assert_close(res_rfft, x)
+        xp_assert_close(res_hfft, x)
+
+    @pytest.mark.parametrize("dtype", ["complex64", "complex128"])
+    def test_dtypes_complex(self, dtype, xp):
+        rng = np.random.default_rng(1234)
+        x = xp.asarray(rng.random(30), dtype=getattr(xp, dtype))
+
+        res_fft = fft.ifft(fft.fft(x))
+        # Check both numerical results and exact dtype matches
+        xp_assert_close(res_fft, x)
+
+    @skip_xp_backends(np_only=True,
+                      reason='array-likes only supported for NumPy backend')
+    @pytest.mark.parametrize("op", [fft.fft, fft.ifft,
+                                    fft.fft2, fft.ifft2,
+                                    fft.fftn, fft.ifftn,
+                                    fft.rfft, fft.irfft,
+                                    fft.rfft2, fft.irfft2,
+                                    fft.rfftn, fft.irfftn,
+                                    fft.hfft, fft.ihfft,
+                                    fft.hfft2, fft.ihfft2,
+                                    fft.hfftn, fft.ihfftn,])
+    def test_array_like(self, xp, op):
+        x = [[[1.0, 1.0], [1.0, 1.0]],
+             [[1.0, 1.0], [1.0, 1.0]],
+             [[1.0, 1.0], [1.0, 1.0]]]
+        xp_assert_close(op(x), op(xp.asarray(x)))
+
+
+@skip_xp_backends(np_only=True)
+@pytest.mark.parametrize(
+        "dtype",
+        [np.float32, np.float64, np.longdouble,
+         np.complex64, np.complex128, np.clongdouble])
+@pytest.mark.parametrize("order", ["F", 'non-contiguous'])
+@pytest.mark.parametrize(
+        "fft",
+        [fft.fft, fft.fft2, fft.fftn,
+         fft.ifft, fft.ifft2, fft.ifftn])
+def test_fft_with_order(dtype, order, fft):
+    # Check that FFT/IFFT produces identical results for C, Fortran and
+    # non contiguous arrays
+    rng = np.random.RandomState(42)
+    X = rng.rand(8, 7, 13).astype(dtype, copy=False)
+    if order == 'F':
+        Y = np.asfortranarray(X)
+    else:
+        # Make a non contiguous array
+        Y = X[::-1]
+        X = np.ascontiguousarray(X[::-1])
+
+    if fft.__name__.endswith('fft'):
+        for axis in range(3):
+            X_res = fft(X, axis=axis)
+            Y_res = fft(Y, axis=axis)
+            assert_array_almost_equal(X_res, Y_res)
+    elif fft.__name__.endswith(('fft2', 'fftn')):
+        axes = [(0, 1), (1, 2), (0, 2)]
+        if fft.__name__.endswith('fftn'):
+            axes.extend([(0,), (1,), (2,), None])
+        for ax in axes:
+            X_res = fft(X, axes=ax)
+            Y_res = fft(Y, axes=ax)
+            assert_array_almost_equal(X_res, Y_res)
+    else:
+        raise ValueError
+
+
+@skip_xp_backends(cpu_only=True)
+class TestFFTThreadSafe:
+    threads = 16
+    input_shape = (800, 200)
+
+    def _test_mtsame(self, func, *args, xp=None):
+        def worker(args, q):
+            q.put(func(*args))
+
+        q = queue.Queue()
+        expected = func(*args)
+
+        # Spin off a bunch of threads to call the same function simultaneously
+        t = [threading.Thread(target=worker, args=(args, q))
+             for i in range(self.threads)]
+        [x.start() for x in t]
+
+        [x.join() for x in t]
+
+        # Make sure all threads returned the correct value
+        for i in range(self.threads):
+            xp_assert_equal(
+                q.get(timeout=5), expected,
+                err_msg='Function returned wrong value in multithreaded context'
+            )
+
+    def test_fft(self, xp):
+        a = xp.ones(self.input_shape, dtype=xp.complex128)
+        self._test_mtsame(fft.fft, a, xp=xp)
+
+    def test_ifft(self, xp):
+        a = xp.full(self.input_shape, 1+0j)
+        self._test_mtsame(fft.ifft, a, xp=xp)
+
+    def test_rfft(self, xp):
+        a = xp.ones(self.input_shape)
+        self._test_mtsame(fft.rfft, a, xp=xp)
+
+    def test_irfft(self, xp):
+        a = xp.full(self.input_shape, 1+0j)
+        self._test_mtsame(fft.irfft, a, xp=xp)
+
+    def test_hfft(self, xp):
+        a = xp.ones(self.input_shape, dtype=xp.complex64)
+        self._test_mtsame(fft.hfft, a, xp=xp)
+
+    def test_ihfft(self, xp):
+        a = xp.ones(self.input_shape)
+        self._test_mtsame(fft.ihfft, a, xp=xp)
+
+
+@skip_xp_backends(np_only=True)
+@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft])
+def test_multiprocess(func):
+    # Test that fft still works after fork (gh-10422)
+
+    with multiprocessing.Pool(2) as p:
+        res = p.map(func, [np.ones(100) for _ in range(4)])
+
+    expect = func(np.ones(100))
+    for x in res:
+        assert_allclose(x, expect)
+
+
+class TestIRFFTN:
+
+    def test_not_last_axis_success(self, xp):
+        ar, ai = np.random.random((2, 16, 8, 32))
+        a = ar + 1j*ai
+        a = xp.asarray(a)
+
+        axes = (-2,)
+
+        # Should not raise error
+        fft.irfftn(a, axes=axes)
+
+
+@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft,
+                                  fft.fftn, fft.ifftn,
+                                  fft.rfftn, fft.irfftn, fft.hfft, fft.ihfft])
+def test_non_standard_params(func, xp):
+    if func in [fft.rfft, fft.rfftn, fft.ihfft]:
+        dtype = xp.float64
+    else:
+        dtype = xp.complex128
+
+    if xp.__name__ != 'numpy':
+        x = xp.asarray([1, 2, 3], dtype=dtype)
+        # func(x) should not raise an exception
+        func(x)
+        assert_raises(ValueError, func, x, workers=2)
+        # `plan` param is not tested since SciPy does not use it currently
+        # but should be tested if it comes into use
+
+
+@pytest.mark.parametrize("dtype", ['float32', 'float64'])
+@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.irfft,
+                                  fft.fftn, fft.ifftn,
+                                  fft.irfftn, fft.hfft,])
+def test_real_input(func, dtype, xp):
+    x = xp.asarray([1, 2, 3], dtype=getattr(xp, dtype))
+    # func(x) should not raise an exception
+    func(x)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..3480e165180baf3866ca7c99a313996a2dbbca49
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_fftlog.py
@@ -0,0 +1,206 @@
+import warnings
+import math
+
+import numpy as np
+import pytest
+
+from scipy.fft._fftlog import fht, ifht, fhtoffset
+from scipy.special import poch
+
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import xp_assert_close, xp_assert_less, array_namespace
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+def test_fht_agrees_with_fftlog(xp):
+    # check that fht numerically agrees with the output from Fortran FFTLog,
+    # the results were generated with the provided `fftlogtest` program,
+    # after fixing how the k array is generated (divide range by n-1, not n)
+
+    # test function, analytical Hankel transform is of the same form
+    def f(r, mu):
+        return r**(mu+1)*np.exp(-r**2/2)
+
+    r = np.logspace(-4, 4, 16)
+
+    dln = np.log(r[1]/r[0])
+    mu = 0.3
+    offset = 0.0
+    bias = 0.0
+
+    a = xp.asarray(f(r, mu))
+
+    # test 1: compute as given
+    ours = fht(a, dln, mu, offset=offset, bias=bias)
+    theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,
+              -0.1949518286432330E-02, +0.3789220182554077E-02,
+              +0.5093959119952945E-03, +0.2785387803618774E-01,
+              +0.9944952700848897E-01, +0.4599202164586588E+00,
+              +0.3157462160881342E+00, -0.8201236844404755E-03,
+              -0.7834031308271878E-03, +0.3931444945110708E-03,
+              -0.2697710625194777E-03, +0.3568398050238820E-03,
+              -0.5554454827797206E-03, +0.8286331026468585E-03]
+    theirs = xp.asarray(theirs, dtype=xp.float64)
+    xp_assert_close(ours, theirs)
+
+    # test 2: change to optimal offset
+    offset = fhtoffset(dln, mu, bias=bias)
+    ours = fht(a, dln, mu, offset=offset, bias=bias)
+    theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05,
+              +0.3150140927838524E-03, +0.9149121960963704E-03,
+              +0.5808089753959363E-02, +0.2548065256377240E-01,
+              +0.1339477692089897E+00, +0.4821530509479356E+00,
+              +0.2659899781579785E+00, -0.1116475278448113E-01,
+              +0.1791441617592385E-02, -0.4181810476548056E-03,
+              +0.1314963536765343E-03, -0.5422057743066297E-04,
+              +0.3208681804170443E-04, -0.2696849476008234E-04]
+    theirs = xp.asarray(theirs, dtype=xp.float64)
+    xp_assert_close(ours, theirs)
+
+    # test 3: positive bias
+    bias = 0.8
+    offset = fhtoffset(dln, mu, bias=bias)
+    ours = fht(a, dln, mu, offset=offset, bias=bias)
+    theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00,
+              +0.1065374386206564E+00, -0.5121739602708132E-01,
+              +0.2636649319269470E-01, +0.1697209218849693E-01,
+              +0.1250215614723183E+00, +0.4739583261486729E+00,
+              +0.2841149874912028E+00, -0.8312764741645729E-02,
+              +0.1024233505508988E-02, -0.1644902767389120E-03,
+              +0.3305775476926270E-04, -0.7786993194882709E-05,
+              +0.1962258449520547E-05, -0.8977895734909250E-06]
+    theirs = xp.asarray(theirs, dtype=xp.float64)
+    xp_assert_close(ours, theirs)
+
+    # test 4: negative bias
+    bias = -0.8
+    offset = fhtoffset(dln, mu, bias=bias)
+    ours = fht(a, dln, mu, offset=offset, bias=bias)
+    theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04,
+              +0.2123969254700955E-03, +0.1009558244834628E-02,
+              +0.5131386375222176E-02, +0.2461678673516286E-01,
+              +0.1235812845384476E+00, +0.4719570096404403E+00,
+              +0.2893487490631317E+00, -0.1686570611318716E-01,
+              +0.2231398155172505E-01, -0.1480742256379873E-01,
+              +0.1692387813500801E+00, +0.3097490354365797E+00,
+              +2.7593607182401860E+00, 10.5251075070045800E+00]
+    theirs = xp.asarray(theirs, dtype=xp.float64)
+    xp_assert_close(ours, theirs)
+
+
+@pytest.mark.parametrize('optimal', [True, False])
+@pytest.mark.parametrize('offset', [0.0, 1.0, -1.0])
+@pytest.mark.parametrize('bias', [0, 0.1, -0.1])
+@pytest.mark.parametrize('n', [64, 63])
+def test_fht_identity(n, bias, offset, optimal, xp):
+    rng = np.random.RandomState(3491349965)
+
+    a = xp.asarray(rng.standard_normal(n))
+    dln = rng.uniform(-1, 1)
+    mu = rng.uniform(-2, 2)
+
+    if optimal:
+        offset = fhtoffset(dln, mu, initial=offset, bias=bias)
+
+    A = fht(a, dln, mu, offset=offset, bias=bias)
+    a_ = ifht(A, dln, mu, offset=offset, bias=bias)
+
+    xp_assert_close(a_, a, rtol=1.5e-7)
+
+
+
+
+@pytest.mark.thread_unsafe
+def test_fht_special_cases(xp):
+    rng = np.random.RandomState(3491349965)
+
+    a = xp.asarray(rng.standard_normal(64))
+    dln = rng.uniform(-1, 1)
+
+    # let x = (mu+1+q)/2, y = (mu+1-q)/2, M = {0, -1, -2, ...}
+
+    # case 1: x in M, y in M => well-defined transform
+    mu, bias = -4.0, 1.0
+    with warnings.catch_warnings(record=True) as record:
+        fht(a, dln, mu, bias=bias)
+        assert not record, 'fht warned about a well-defined transform'
+
+    # case 2: x not in M, y in M => well-defined transform
+    mu, bias = -2.5, 0.5
+    with warnings.catch_warnings(record=True) as record:
+        fht(a, dln, mu, bias=bias)
+        assert not record, 'fht warned about a well-defined transform'
+
+    # with fht_lock:
+    # case 3: x in M, y not in M => singular transform
+    mu, bias = -3.5, 0.5
+    with pytest.warns(Warning) as record:
+        fht(a, dln, mu, bias=bias)
+        assert record, 'fht did not warn about a singular transform'
+
+    # with fht_lock:
+    # case 4: x not in M, y in M => singular inverse transform
+    mu, bias = -2.5, 0.5
+    with pytest.warns(Warning) as record:
+        ifht(a, dln, mu, bias=bias)
+        assert record, 'ifht did not warn about a singular transform'
+
+
+@pytest.mark.parametrize('n', [64, 63])
+def test_fht_exact(n, xp):
+    rng = np.random.RandomState(3491349965)
+
+    # for a(r) a power law r^\gamma, the fast Hankel transform produces the
+    # exact continuous Hankel transform if biased with q = \gamma
+
+    mu = rng.uniform(0, 3)
+
+    # convergence of HT: -1-mu < gamma < 1/2
+    gamma = rng.uniform(-1-mu, 1/2)
+
+    r = np.logspace(-2, 2, n)
+    a = xp.asarray(r**gamma)
+
+    dln = np.log(r[1]/r[0])
+
+    offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)
+
+    A = fht(a, dln, mu, offset=offset, bias=gamma)
+
+    k = np.exp(offset)/r[::-1]
+
+    # analytical result
+    At = xp.asarray((2/k)**gamma * poch((mu+1-gamma)/2, gamma))
+
+    xp_assert_close(A, At)
+
+@skip_xp_backends(np_only=True,
+                  reason='array-likes only supported for NumPy backend')
+@pytest.mark.parametrize("op", [fht, ifht])
+def test_array_like(xp, op):
+    x = [[[1.0, 1.0], [1.0, 1.0]],
+         [[1.0, 1.0], [1.0, 1.0]],
+         [[1.0, 1.0], [1.0, 1.0]]]
+    xp_assert_close(op(x, 1.0, 2.0), op(xp.asarray(x), 1.0, 2.0))
+
+@pytest.mark.parametrize('n', [128, 129])
+def test_gh_21661(xp, n):
+    one = xp.asarray(1.0)
+    xp_test = array_namespace(one)
+    mu = 0.0
+    r = np.logspace(-7, 1, n)
+    dln = math.log(r[1] / r[0])
+    offset = fhtoffset(dln, initial=-6 * np.log(10), mu=mu)
+    r = xp.asarray(r, dtype=one.dtype)
+    k = math.exp(offset) / xp_test.flip(r, axis=-1)
+
+    def f(x, mu):
+        return x**(mu + 1)*xp.exp(-x**2/2)
+
+    a_r = f(r, mu)
+    fht_val = fht(a_r, dln, mu=mu, offset=offset)
+    a_k = f(k, mu)
+    rel_err = xp.max(xp.abs((fht_val - a_k) / a_k))
+    xp_assert_less(rel_err, xp.asarray(7.28e+16)[()])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..4333886555ffbbb0831f830456a3290f32e317fa
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_helper.py
@@ -0,0 +1,574 @@
+"""Includes test functions for fftpack.helper module
+
+Copied from fftpack.helper by Pearu Peterson, October 2005
+Modified for Array API, 2023
+
+"""
+from scipy.fft._helper import next_fast_len, prev_fast_len, _init_nd_shape_and_axes
+from numpy.testing import assert_equal
+from pytest import raises as assert_raises
+import pytest
+import numpy as np
+import sys
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import (
+    xp_assert_close, get_xp_devices, xp_device, array_namespace
+)
+from scipy import fft
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+_5_smooth_numbers = [
+    2, 3, 4, 5, 6, 8, 9, 10,
+    2 * 3 * 5,
+    2**3 * 3**5,
+    2**3 * 3**3 * 5**2,
+]
+
+def test_next_fast_len():
+    for n in _5_smooth_numbers:
+        assert_equal(next_fast_len(n), n)
+
+
+def _assert_n_smooth(x, n):
+    x_orig = x
+    if n < 2:
+        assert False
+
+    while True:
+        q, r = divmod(x, 2)
+        if r != 0:
+            break
+        x = q
+
+    for d in range(3, n+1, 2):
+        while True:
+            q, r = divmod(x, d)
+            if r != 0:
+                break
+            x = q
+
+    assert x == 1, \
+           f'x={x_orig} is not {n}-smooth, remainder={x}'
+
+
+@skip_xp_backends(np_only=True)
+class TestNextFastLen:
+
+    def test_next_fast_len(self):
+        np.random.seed(1234)
+
+        def nums():
+            yield from range(1, 1000)
+            yield 2**5 * 3**5 * 4**5 + 1
+
+        for n in nums():
+            m = next_fast_len(n)
+            _assert_n_smooth(m, 11)
+            assert m == next_fast_len(n, False)
+
+            m = next_fast_len(n, True)
+            _assert_n_smooth(m, 5)
+
+    def test_np_integers(self):
+        ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, np.uint64]
+        for ityp in ITYPES:
+            x = ityp(12345)
+            testN = next_fast_len(x)
+            assert_equal(testN, next_fast_len(int(x)))
+
+    def testnext_fast_len_small(self):
+        hams = {
+            1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 8, 8: 8, 14: 15, 15: 15,
+            16: 16, 17: 18, 1021: 1024, 1536: 1536, 51200000: 51200000
+        }
+        for x, y in hams.items():
+            assert_equal(next_fast_len(x, True), y)
+
+    @pytest.mark.xfail(sys.maxsize < 2**32,
+                       reason="Hamming Numbers too large for 32-bit",
+                       raises=ValueError, strict=True)
+    def testnext_fast_len_big(self):
+        hams = {
+            510183360: 510183360, 510183360 + 1: 512000000,
+            511000000: 512000000,
+            854296875: 854296875, 854296875 + 1: 859963392,
+            196608000000: 196608000000, 196608000000 + 1: 196830000000,
+            8789062500000: 8789062500000, 8789062500000 + 1: 8796093022208,
+            206391214080000: 206391214080000,
+            206391214080000 + 1: 206624260800000,
+            470184984576000: 470184984576000,
+            470184984576000 + 1: 470715894135000,
+            7222041363087360: 7222041363087360,
+            7222041363087360 + 1: 7230196133913600,
+            # power of 5    5**23
+            11920928955078125: 11920928955078125,
+            11920928955078125 - 1: 11920928955078125,
+            # power of 3    3**34
+            16677181699666569: 16677181699666569,
+            16677181699666569 - 1: 16677181699666569,
+            # power of 2   2**54
+            18014398509481984: 18014398509481984,
+            18014398509481984 - 1: 18014398509481984,
+            # above this, int(ceil(n)) == int(ceil(n+1))
+            19200000000000000: 19200000000000000,
+            19200000000000000 + 1: 19221679687500000,
+            288230376151711744: 288230376151711744,
+            288230376151711744 + 1: 288325195312500000,
+            288325195312500000 - 1: 288325195312500000,
+            288325195312500000: 288325195312500000,
+            288325195312500000 + 1: 288555831593533440,
+        }
+        for x, y in hams.items():
+            assert_equal(next_fast_len(x, True), y)
+
+    def test_keyword_args(self):
+        assert next_fast_len(11, real=True) == 12
+        assert next_fast_len(target=7, real=False) == 7
+
+@skip_xp_backends(np_only=True)
+class TestPrevFastLen:
+
+    def test_prev_fast_len(self):
+        np.random.seed(1234)
+
+        def nums():
+            yield from range(1, 1000)
+            yield 2**5 * 3**5 * 4**5 + 1
+
+        for n in nums():
+            m = prev_fast_len(n)
+            _assert_n_smooth(m, 11)
+            assert m == prev_fast_len(n, False)
+
+            m = prev_fast_len(n, True)
+            _assert_n_smooth(m, 5)
+
+    def test_np_integers(self):
+        ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, 
+                    np.uint64]
+        for ityp in ITYPES:
+            x = ityp(12345)
+            testN = prev_fast_len(x)
+            assert_equal(testN, prev_fast_len(int(x)))
+
+            testN = prev_fast_len(x, real=True)
+            assert_equal(testN, prev_fast_len(int(x), real=True))
+
+    def testprev_fast_len_small(self):
+        hams = {
+            1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 8, 14: 12, 15: 15,
+            16: 16, 17: 16, 1021: 1000, 1536: 1536, 51200000: 51200000
+        }
+        for x, y in hams.items():
+            assert_equal(prev_fast_len(x, True), y)
+
+        hams = {
+            1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10,
+            11: 11, 12: 12, 13: 12, 14: 14, 15: 15, 16: 16, 17: 16, 18: 18,
+            19: 18, 20: 20, 21: 21, 22: 22, 120: 120, 121: 121, 122: 121,
+            1021: 1008, 1536: 1536, 51200000: 51200000
+        }
+        for x, y in hams.items():
+            assert_equal(prev_fast_len(x, False), y)
+
+    @pytest.mark.xfail(sys.maxsize < 2**32,
+                       reason="Hamming Numbers too large for 32-bit",
+                       raises=ValueError, strict=True)
+    def testprev_fast_len_big(self):
+        hams = {
+            # 2**6 * 3**13 * 5**1
+            510183360: 510183360,
+            510183360 + 1: 510183360,
+            510183360 - 1: 509607936,  # 2**21 * 3**5
+            # 2**6 * 5**6 * 7**1 * 73**1
+            511000000: 510183360,
+            511000000 + 1: 510183360,
+            511000000 - 1: 510183360,  # 2**6 * 3**13 * 5**1
+            # 3**7 * 5**8
+            854296875: 854296875,
+            854296875 + 1: 854296875,
+            854296875 - 1: 850305600,  # 2**6 * 3**12 * 5**2
+            # 2**22 * 3**1 * 5**6
+            196608000000: 196608000000,
+            196608000000 + 1: 196608000000,
+            196608000000 - 1: 195910410240,  # 2**13 * 3**14 * 5**1
+            # 2**5 * 3**2 * 5**15
+            8789062500000: 8789062500000,
+            8789062500000 + 1: 8789062500000,
+            8789062500000 - 1: 8748000000000,  # 2**11 * 3**7 * 5**9
+            # 2**24 * 3**9 * 5**4
+            206391214080000: 206391214080000,
+            206391214080000 + 1: 206391214080000,
+            206391214080000 - 1: 206158430208000,  # 2**39 * 3**1 * 5**3
+            # 2**18 * 3**15 * 5**3
+            470184984576000: 470184984576000,
+            470184984576000 + 1: 470184984576000,
+            470184984576000 - 1: 469654673817600,  # 2**33 * 3**7 **5**2
+            # 2**25 * 3**16 * 5**1
+            7222041363087360: 7222041363087360,
+            7222041363087360 + 1: 7222041363087360,
+            7222041363087360 - 1: 7213895789838336,  # 2**40 * 3**8
+            # power of 5    5**23
+            11920928955078125: 11920928955078125,
+            11920928955078125 + 1: 11920928955078125,
+            11920928955078125 - 1: 11901557422080000,  # 2**14 * 3**19 * 5**4
+            # power of 3    3**34
+            16677181699666569: 16677181699666569,
+            16677181699666569 + 1: 16677181699666569,
+            16677181699666569 - 1: 16607531250000000,  # 2**7 * 3**12 * 5**12
+            # power of 2   2**54
+            18014398509481984: 18014398509481984,
+            18014398509481984 + 1: 18014398509481984,
+            18014398509481984 - 1: 18000000000000000,  # 2**16 * 3**2 * 5**15
+            # 2**20 * 3**1 * 5**14
+            19200000000000000: 19200000000000000,
+            19200000000000000 + 1: 19200000000000000,
+            19200000000000000 - 1: 19131876000000000,  # 2**11 * 3**14 * 5**9
+            # 2**58
+            288230376151711744: 288230376151711744,
+            288230376151711744 + 1: 288230376151711744,
+            288230376151711744 - 1: 288000000000000000,  # 2**20 * 3**2 * 5**15
+            # 2**5 * 3**10 * 5**16
+            288325195312500000: 288325195312500000,
+            288325195312500000 + 1: 288325195312500000,
+            288325195312500000 - 1: 288230376151711744,  # 2**58
+        }
+        for x, y in hams.items():
+            assert_equal(prev_fast_len(x, True), y)
+
+    def test_keyword_args(self):
+        assert prev_fast_len(11, real=True) == 10
+        assert prev_fast_len(target=7, real=False) == 7
+
+
+@skip_xp_backends(cpu_only=True)
+class Test_init_nd_shape_and_axes:
+
+    def test_py_0d_defaults(self, xp):
+        x = xp.asarray(4)
+        shape = None
+        axes = None
+
+        shape_expected = ()
+        axes_expected = []
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_0d_defaults(self, xp):
+        x = xp.asarray(7.)
+        shape = None
+        axes = None
+
+        shape_expected = ()
+        axes_expected = []
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_py_1d_defaults(self, xp):
+        x = xp.asarray([1, 2, 3])
+        shape = None
+        axes = None
+
+        shape_expected = (3,)
+        axes_expected = [0]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_1d_defaults(self, xp):
+        x = xp.arange(0, 1, .1)
+        shape = None
+        axes = None
+
+        shape_expected = (10,)
+        axes_expected = [0]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_py_2d_defaults(self, xp):
+        x = xp.asarray([[1, 2, 3, 4],
+                        [5, 6, 7, 8]])
+        shape = None
+        axes = None
+
+        shape_expected = (2, 4)
+        axes_expected = [0, 1]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_2d_defaults(self, xp):
+        x = xp.arange(0, 1, .1)
+        x = xp.reshape(x, (5, 2))
+        shape = None
+        axes = None
+
+        shape_expected = (5, 2)
+        axes_expected = [0, 1]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_5d_defaults(self, xp):
+        x = xp.zeros([6, 2, 5, 3, 4])
+        shape = None
+        axes = None
+
+        shape_expected = (6, 2, 5, 3, 4)
+        axes_expected = [0, 1, 2, 3, 4]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_5d_set_shape(self, xp):
+        x = xp.zeros([6, 2, 5, 3, 4])
+        shape = [10, -1, -1, 1, 4]
+        axes = None
+
+        shape_expected = (10, 2, 5, 1, 4)
+        axes_expected = [0, 1, 2, 3, 4]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_5d_set_axes(self, xp):
+        x = xp.zeros([6, 2, 5, 3, 4])
+        shape = None
+        axes = [4, 1, 2]
+
+        shape_expected = (4, 2, 5)
+        axes_expected = [4, 1, 2]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_xp_5d_set_shape_axes(self, xp):
+        x = xp.zeros([6, 2, 5, 3, 4])
+        shape = [10, -1, 2]
+        axes = [1, 0, 3]
+
+        shape_expected = (10, 6, 2)
+        axes_expected = [1, 0, 3]
+
+        shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+        assert shape_res == shape_expected
+        assert axes_res == axes_expected
+
+    def test_shape_axes_subset(self, xp):
+        x = xp.zeros((2, 3, 4, 5))
+        shape, axes = _init_nd_shape_and_axes(x, shape=(5, 5, 5), axes=None)
+
+        assert shape == (5, 5, 5)
+        assert axes == [1, 2, 3]
+
+    def test_errors(self, xp):
+        x = xp.zeros(1)
+        with assert_raises(ValueError, match="axes must be a scalar or "
+                           "iterable of integers"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[[1, 2], [3, 4]])
+
+        with assert_raises(ValueError, match="axes must be a scalar or "
+                           "iterable of integers"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[1., 2., 3., 4.])
+
+        with assert_raises(ValueError,
+                           match="axes exceeds dimensionality of input"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[1])
+
+        with assert_raises(ValueError,
+                           match="axes exceeds dimensionality of input"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[-2])
+
+        with assert_raises(ValueError,
+                           match="all axes must be unique"):
+            _init_nd_shape_and_axes(x, shape=None, axes=[0, 0])
+
+        with assert_raises(ValueError, match="shape must be a scalar or "
+                           "iterable of integers"):
+            _init_nd_shape_and_axes(x, shape=[[1, 2], [3, 4]], axes=None)
+
+        with assert_raises(ValueError, match="shape must be a scalar or "
+                           "iterable of integers"):
+            _init_nd_shape_and_axes(x, shape=[1., 2., 3., 4.], axes=None)
+
+        with assert_raises(ValueError,
+                           match="when given, axes and shape arguments"
+                           " have to be of the same length"):
+            _init_nd_shape_and_axes(xp.zeros([1, 1, 1, 1]),
+                                    shape=[1, 2, 3], axes=[1])
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[0\]\) specified"):
+            _init_nd_shape_and_axes(x, shape=[0], axes=None)
+
+        with assert_raises(ValueError,
+                           match="invalid number of data points"
+                           r" \(\[-2\]\) specified"):
+            _init_nd_shape_and_axes(x, shape=-2, axes=None)
+
+
+class TestFFTShift:
+
+    def test_definition(self, xp):
+        x = xp.asarray([0., 1, 2, 3, 4, -4, -3, -2, -1])
+        y = xp.asarray([-4., -3, -2, -1, 0, 1, 2, 3, 4])
+        xp_assert_close(fft.fftshift(x), y)
+        xp_assert_close(fft.ifftshift(y), x)
+        x = xp.asarray([0., 1, 2, 3, 4, -5, -4, -3, -2, -1])
+        y = xp.asarray([-5., -4, -3, -2, -1, 0, 1, 2, 3, 4])
+        xp_assert_close(fft.fftshift(x), y)
+        xp_assert_close(fft.ifftshift(y), x)
+
+    def test_inverse(self, xp):
+        for n in [1, 4, 9, 100, 211]:
+            x = xp.asarray(np.random.random((n,)))
+            xp_assert_close(fft.ifftshift(fft.fftshift(x)), x)
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8393')
+    def test_axes_keyword(self, xp):
+        freqs = xp.asarray([[0., 1, 2], [3, 4, -4], [-3, -2, -1]])
+        shifted = xp.asarray([[-1., -3, -2], [2, 0, 1], [-4, 3, 4]])
+        xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shifted)
+        xp_assert_close(fft.fftshift(freqs, axes=0), fft.fftshift(freqs, axes=(0,)))
+        xp_assert_close(fft.ifftshift(shifted, axes=(0, 1)), freqs)
+        xp_assert_close(fft.ifftshift(shifted, axes=0),
+                        fft.ifftshift(shifted, axes=(0,)))
+        xp_assert_close(fft.fftshift(freqs), shifted)
+        xp_assert_close(fft.ifftshift(shifted), freqs)
+    
+    @skip_xp_backends('cupy', reason='cupy/cupy#8393')
+    def test_uneven_dims(self, xp):
+        """ Test 2D input, which has uneven dimension sizes """
+        freqs = xp.asarray([
+            [0, 1],
+            [2, 3],
+            [4, 5]
+        ], dtype=xp.float64)
+
+        # shift in dimension 0
+        shift_dim0 = xp.asarray([
+            [4, 5],
+            [0, 1],
+            [2, 3]
+        ], dtype=xp.float64)
+        xp_assert_close(fft.fftshift(freqs, axes=0), shift_dim0)
+        xp_assert_close(fft.ifftshift(shift_dim0, axes=0), freqs)
+        xp_assert_close(fft.fftshift(freqs, axes=(0,)), shift_dim0)
+        xp_assert_close(fft.ifftshift(shift_dim0, axes=[0]), freqs)
+
+        # shift in dimension 1
+        shift_dim1 = xp.asarray([
+            [1, 0],
+            [3, 2],
+            [5, 4]
+        ], dtype=xp.float64)
+        xp_assert_close(fft.fftshift(freqs, axes=1), shift_dim1)
+        xp_assert_close(fft.ifftshift(shift_dim1, axes=1), freqs)
+
+        # shift in both dimensions
+        shift_dim_both = xp.asarray([
+            [5, 4],
+            [1, 0],
+            [3, 2]
+        ], dtype=xp.float64)
+        xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shift_dim_both)
+        xp_assert_close(fft.ifftshift(shift_dim_both, axes=(0, 1)), freqs)
+        xp_assert_close(fft.fftshift(freqs, axes=[0, 1]), shift_dim_both)
+        xp_assert_close(fft.ifftshift(shift_dim_both, axes=[0, 1]), freqs)
+
+        # axes=None (default) shift in all dimensions
+        xp_assert_close(fft.fftshift(freqs, axes=None), shift_dim_both)
+        xp_assert_close(fft.ifftshift(shift_dim_both, axes=None), freqs)
+        xp_assert_close(fft.fftshift(freqs), shift_dim_both)
+        xp_assert_close(fft.ifftshift(shift_dim_both), freqs)
+
+
+@skip_xp_backends("cupy",
+                  reason="CuPy has not implemented the `device` param")
+@skip_xp_backends("jax.numpy",
+                  reason="JAX has not implemented the `device` param")
+class TestFFTFreq:
+
+    def test_definition(self, xp):
+        x = xp.asarray([0, 1, 2, 3, 4, -4, -3, -2, -1], dtype=xp.float64)
+        x2 = xp.asarray([0, 1, 2, 3, 4, -5, -4, -3, -2, -1], dtype=xp.float64)
+
+        # default dtype varies across backends
+
+        y = 9 * fft.fftfreq(9, xp=xp)
+        xp_assert_close(y, x, check_dtype=False, check_namespace=True)
+
+        y = 9 * xp.pi * fft.fftfreq(9, xp.pi, xp=xp)
+        xp_assert_close(y, x, check_dtype=False)
+
+        y = 10 * fft.fftfreq(10, xp=xp)
+        xp_assert_close(y, x2, check_dtype=False)
+
+        y = 10 * xp.pi * fft.fftfreq(10, xp.pi, xp=xp)
+        xp_assert_close(y, x2, check_dtype=False)
+
+    def test_device(self, xp):
+        xp_test = array_namespace(xp.empty(0))
+        devices = get_xp_devices(xp)
+        for d in devices:
+            y = fft.fftfreq(9, xp=xp, device=d)
+            x = xp_test.empty(0, device=d)
+            assert xp_device(y) == xp_device(x)
+
+
+@skip_xp_backends("cupy",
+                  reason="CuPy has not implemented the `device` param")
+@skip_xp_backends("jax.numpy",
+                  reason="JAX has not implemented the `device` param")
+class TestRFFTFreq:
+
+    def test_definition(self, xp):
+        x = xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64)
+        x2 = xp.asarray([0, 1, 2, 3, 4, 5], dtype=xp.float64)
+
+        # default dtype varies across backends
+        
+        y = 9 * fft.rfftfreq(9, xp=xp)
+        xp_assert_close(y, x, check_dtype=False, check_namespace=True)
+
+        y = 9 * xp.pi * fft.rfftfreq(9, xp.pi, xp=xp)
+        xp_assert_close(y, x, check_dtype=False)
+
+        y = 10 * fft.rfftfreq(10, xp=xp)
+        xp_assert_close(y, x2, check_dtype=False)
+
+        y = 10 * xp.pi * fft.rfftfreq(10, xp.pi, xp=xp)
+        xp_assert_close(y, x2, check_dtype=False)
+
+    def test_device(self, xp):
+        xp_test = array_namespace(xp.empty(0))
+        devices = get_xp_devices(xp)
+        for d in devices:
+            y = fft.rfftfreq(9, xp=xp, device=d)
+            x = xp_test.empty(0, device=d)
+            assert xp_device(y) == xp_device(x)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a6b71b830211f8bcbe56e97ff71098be75021c8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_multithreading.py
@@ -0,0 +1,84 @@
+from scipy import fft
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose
+import multiprocessing
+import os
+
+
+@pytest.fixture(scope='module')
+def x():
+    return np.random.randn(512, 128)  # Must be large enough to qualify for mt
+
+
+@pytest.mark.parametrize("func", [
+    fft.fft, fft.ifft, fft.fft2, fft.ifft2, fft.fftn, fft.ifftn,
+    fft.rfft, fft.irfft, fft.rfft2, fft.irfft2, fft.rfftn, fft.irfftn,
+    fft.hfft, fft.ihfft, fft.hfft2, fft.ihfft2, fft.hfftn, fft.ihfftn,
+    fft.dct, fft.idct, fft.dctn, fft.idctn,
+    fft.dst, fft.idst, fft.dstn, fft.idstn,
+])
+@pytest.mark.parametrize("workers", [2, -1])
+def test_threaded_same(x, func, workers):
+    expected = func(x, workers=1)
+    actual = func(x, workers=workers)
+    assert_allclose(actual, expected)
+
+
+def _mt_fft(x):
+    return fft.fft(x, workers=2)
+
+
+@pytest.mark.slow
+def test_mixed_threads_processes(x):
+    # Test that the fft threadpool is safe to use before & after fork
+
+    expect = fft.fft(x, workers=2)
+
+    with multiprocessing.Pool(2) as p:
+        res = p.map(_mt_fft, [x for _ in range(4)])
+
+    for r in res:
+        assert_allclose(r, expect)
+
+    fft.fft(x, workers=2)
+
+
+def test_invalid_workers(x):
+    cpus = os.cpu_count()
+
+    fft.ifft([1], workers=-cpus)
+
+    with pytest.raises(ValueError, match='workers must not be zero'):
+        fft.fft(x, workers=0)
+
+    with pytest.raises(ValueError, match='workers value out of range'):
+        fft.ifft(x, workers=-cpus-1)
+
+
+def test_set_get_workers():
+    cpus = os.cpu_count()
+    assert fft.get_workers() == 1
+    with fft.set_workers(4):
+        assert fft.get_workers() == 4
+
+        with fft.set_workers(-1):
+            assert fft.get_workers() == cpus
+
+        assert fft.get_workers() == 4
+
+    assert fft.get_workers() == 1
+
+    with fft.set_workers(-cpus):
+        assert fft.get_workers() == 1
+
+
+def test_set_workers_invalid():
+
+    with pytest.raises(ValueError, match='workers must not be zero'):
+        with fft.set_workers(0):
+            pass
+
+    with pytest.raises(ValueError, match='workers value out of range'):
+        with fft.set_workers(-os.cpu_count()-1):
+            pass
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..890dc79640aff571262f5a12f721f62f5c907069
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/fft/tests/test_real_transforms.py
@@ -0,0 +1,249 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_equal
+import pytest
+import math
+
+from scipy.fft import dct, idct, dctn, idctn, dst, idst, dstn, idstn
+import scipy.fft as fft
+from scipy import fftpack
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import xp_copy, xp_assert_close
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+SQRT_2 = math.sqrt(2)
+
+# scipy.fft wraps the fftpack versions but with normalized inverse transforms.
+# So, the forward transforms and definitions are already thoroughly tested in
+# fftpack/test_real_transforms.py
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("n", [2, 3, 4, 5, 10, 16])
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("orthogonalize", [False, True])
+def test_identity_1d(forward, backward, type, n, axis, norm, orthogonalize, xp):
+    # Test the identity f^-1(f(x)) == x
+    x = xp.asarray(np.random.rand(n, n))
+
+    y = forward(x, type, axis=axis, norm=norm, orthogonalize=orthogonalize)
+    z = backward(y, type, axis=axis, norm=norm, orthogonalize=orthogonalize)
+    xp_assert_close(z, x)
+
+    pad = [(0, 0)] * 2
+    pad[axis] = (0, 4)
+
+    y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge'))
+    z2 = backward(y2, type, n, axis, norm, orthogonalize=orthogonalize)
+    xp_assert_close(z2, x)
+
+
+@skip_xp_backends(np_only=True,
+                  reason='`overwrite_x` only supported for NumPy backend.')
+@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64,
+                                   np.complex64, np.complex128])
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("overwrite_x", [True, False])
+def test_identity_1d_overwrite(forward, backward, type, dtype, axis, norm,
+                               overwrite_x):
+    # Test the identity f^-1(f(x)) == x
+    x = np.random.rand(7, 8).astype(dtype)
+    x_orig = x.copy()
+
+    y = forward(x, type, axis=axis, norm=norm, overwrite_x=overwrite_x)
+    y_orig = y.copy()
+    z = backward(y, type, axis=axis, norm=norm, overwrite_x=overwrite_x)
+    if not overwrite_x:
+        assert_allclose(z, x, rtol=1e-6, atol=1e-6)
+        assert_array_equal(x, x_orig)
+        assert_array_equal(y, y_orig)
+    else:
+        assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("shape, axes",
+                         [
+                             ((4, 4), 0),
+                             ((4, 4), 1),
+                             ((4, 4), None),
+                             ((4, 4), (0, 1)),
+                             ((10, 12), None),
+                             ((10, 12), (0, 1)),
+                             ((4, 5, 6), None),
+                             ((4, 5, 6), 1),
+                             ((4, 5, 6), (0, 2)),
+                         ])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("orthogonalize", [False, True])
+def test_identity_nd(forward, backward, type, shape, axes, norm,
+                     orthogonalize, xp):
+    # Test the identity f^-1(f(x)) == x
+
+    x = xp.asarray(np.random.random(shape))
+
+    if axes is not None:
+        shape = np.take(shape, axes)
+
+    y = forward(x, type, axes=axes, norm=norm, orthogonalize=orthogonalize)
+    z = backward(y, type, axes=axes, norm=norm, orthogonalize=orthogonalize)
+    xp_assert_close(z, x)
+
+    if axes is None:
+        pad = [(0, 4)] * x.ndim
+    elif isinstance(axes, int):
+        pad = [(0, 0)] * x.ndim
+        pad[axes] = (0, 4)
+    else:
+        pad = [(0, 0)] * x.ndim
+
+        for a in axes:
+            pad[a] = (0, 4)
+
+    # TODO write an array-agnostic pad
+    y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge'))
+    z2 = backward(y2, type, shape, axes, norm, orthogonalize=orthogonalize)
+    xp_assert_close(z2, x)
+
+
+@skip_xp_backends(np_only=True,
+                  reason='`overwrite_x` only supported for NumPy backend.')
+@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("shape, axes",
+                         [
+                             ((4, 5), 0),
+                             ((4, 5), 1),
+                             ((4, 5), None),
+                         ])
+@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64,
+                                   np.complex64, np.complex128])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("overwrite_x", [False, True])
+def test_identity_nd_overwrite(forward, backward, type, shape, axes, dtype,
+                               norm, overwrite_x):
+    # Test the identity f^-1(f(x)) == x
+
+    x = np.random.random(shape).astype(dtype)
+    x_orig = x.copy()
+
+    if axes is not None:
+        shape = np.take(shape, axes)
+
+    y = forward(x, type, axes=axes, norm=norm)
+    y_orig = y.copy()
+    z = backward(y, type, axes=axes, norm=norm)
+    if overwrite_x:
+        assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6)
+    else:
+        assert_allclose(z, x, rtol=1e-6, atol=1e-6)
+        assert_array_equal(x, x_orig)
+        assert_array_equal(y, y_orig)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("func", ['dct', 'dst', 'dctn', 'dstn'])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+def test_fftpack_equivalience(func, type, norm, xp):
+    x = np.random.rand(8, 16)
+    fftpack_res = xp.asarray(getattr(fftpack, func)(x, type, norm=norm))
+    x = xp.asarray(x)
+    fft_res = getattr(fft, func)(x, type, norm=norm)
+
+    xp_assert_close(fft_res, fftpack_res)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("func", [dct, dst, dctn, dstn])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+def test_orthogonalize_default(func, type, xp):
+    # Test orthogonalize is the default when norm="ortho", but not otherwise
+    x = xp.asarray(np.random.rand(100))
+
+    for norm, ortho in [
+            ("forward", False),
+            ("backward", False),
+            ("ortho", True),
+    ]:
+        a = func(x, type=type, norm=norm, orthogonalize=ortho)
+        b = func(x, type=type, norm=norm)
+        xp_assert_close(a, b)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func, type", [
+    (dct, 4), (dst, 1), (dst, 4)])
+def test_orthogonalize_noop(func, type, norm, xp):
+    # Transforms where orthogonalize is a no-op
+    x = xp.asarray(np.random.rand(100))
+    y1 = func(x, type=type, norm=norm, orthogonalize=True)
+    y2 = func(x, type=type, norm=norm, orthogonalize=False)
+    xp_assert_close(y1, y2)
+
+
+@skip_xp_backends('jax.numpy',
+                  reason='jax arrays do not support item assignment',
+                  cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+def test_orthogonalize_dct1(norm, xp):
+    x = xp.asarray(np.random.rand(100))
+
+    x2 = xp_copy(x, xp=xp)
+    x2[0] *= SQRT_2
+    x2[-1] *= SQRT_2
+
+    y1 = dct(x, type=1, norm=norm, orthogonalize=True)
+    y2 = dct(x2, type=1, norm=norm, orthogonalize=False)
+
+    y2[0] /= SQRT_2
+    y2[-1] /= SQRT_2
+    xp_assert_close(y1, y2)
+
+
+@skip_xp_backends('jax.numpy',
+                  reason='jax arrays do not support item assignment',
+                  cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func", [dct, dst])
+def test_orthogonalize_dcst2(func, norm, xp):
+    x = xp.asarray(np.random.rand(100))
+    y1 = func(x, type=2, norm=norm, orthogonalize=True)
+    y2 = func(x, type=2, norm=norm, orthogonalize=False)
+
+    y2[0 if func == dct else -1] /= SQRT_2
+    xp_assert_close(y1, y2)
+
+
+@skip_xp_backends('jax.numpy',
+                  reason='jax arrays do not support item assignment',
+                  cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func", [dct, dst])
+def test_orthogonalize_dcst3(func, norm, xp):
+    x = xp.asarray(np.random.rand(100))
+    x2 = xp_copy(x, xp=xp)
+    x2[0 if func == dct else -1] *= SQRT_2
+
+    y1 = func(x, type=3, norm=norm, orthogonalize=True)
+    y2 = func(x2, type=3, norm=norm, orthogonalize=False)
+    xp_assert_close(y1, y2)
+
+@skip_xp_backends(np_only=True,
+                  reason='array-likes only supported for NumPy backend')
+@pytest.mark.parametrize("func", [dct, idct, dctn, idctn, dst, idst, dstn, idstn])
+def test_array_like(xp, func):
+    x = [[[1.0, 1.0], [1.0, 1.0]],
+         [[1.0, 1.0], [1.0, 1.0]],
+         [[1.0, 1.0], [1.0, 1.0]]]
+    xp_assert_close(func(x), func(xp.asarray(x)))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1533b5c60b695fce0abf08e2163dfba3bdd4fb17
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__init__.py
@@ -0,0 +1,122 @@
+"""
+=============================================
+Integration and ODEs (:mod:`scipy.integrate`)
+=============================================
+
+.. currentmodule:: scipy.integrate
+
+Integrating functions, given function object
+============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   quad          -- General purpose integration
+   quad_vec      -- General purpose integration of vector-valued functions
+   cubature      -- General purpose multi-dimensional integration of array-valued functions
+   dblquad       -- General purpose double integration
+   tplquad       -- General purpose triple integration
+   nquad         -- General purpose N-D integration
+   tanhsinh      -- General purpose elementwise integration
+   fixed_quad    -- Integrate func(x) using Gaussian quadrature of order n
+   newton_cotes  -- Weights and error coefficient for Newton-Cotes integration
+   lebedev_rule
+   qmc_quad      -- N-D integration using Quasi-Monte Carlo quadrature
+   IntegrationWarning -- Warning on issues during integration
+
+
+Integrating functions, given fixed samples
+==========================================
+
+.. autosummary::
+   :toctree: generated/
+
+   trapezoid            -- Use trapezoidal rule to compute integral.
+   cumulative_trapezoid -- Use trapezoidal rule to cumulatively compute integral.
+   simpson              -- Use Simpson's rule to compute integral from samples.
+   cumulative_simpson   -- Use Simpson's rule to cumulatively compute integral from samples.
+   romb                 -- Use Romberg Integration to compute integral from
+                        -- (2**k + 1) evenly-spaced samples.
+
+.. seealso::
+
+   :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
+   quadrature roots and weights for other weighting factors and regions.
+
+Summation
+=========
+
+.. autosummary::
+   :toctree: generated/
+
+   nsum
+
+Solving initial value problems for ODE systems
+==============================================
+
+The solvers are implemented as individual classes, which can be used directly
+(low-level usage) or through a convenience function.
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_ivp     -- Convenient function for ODE integration.
+   RK23          -- Explicit Runge-Kutta solver of order 3(2).
+   RK45          -- Explicit Runge-Kutta solver of order 5(4).
+   DOP853        -- Explicit Runge-Kutta solver of order 8.
+   Radau         -- Implicit Runge-Kutta solver of order 5.
+   BDF           -- Implicit multi-step variable order (1 to 5) solver.
+   LSODA         -- LSODA solver from ODEPACK Fortran package.
+   OdeSolver     -- Base class for ODE solvers.
+   DenseOutput   -- Local interpolant for computing a dense output.
+   OdeSolution   -- Class which represents a continuous ODE solution.
+
+
+Old API
+-------
+
+These are the routines developed earlier for SciPy. They wrap older solvers
+implemented in Fortran (mostly ODEPACK). While the interface to them is not
+particularly convenient and certain features are missing compared to the new
+API, the solvers themselves are of good quality and work fast as compiled
+Fortran code. In some cases, it might be worth using this old API.
+
+.. autosummary::
+   :toctree: generated/
+
+   odeint        -- General integration of ordinary differential equations.
+   ode           -- Integrate ODE using VODE and ZVODE routines.
+   complex_ode   -- Convert a complex-valued ODE to real-valued and integrate.
+   ODEintWarning -- Warning raised during the execution of `odeint`.
+
+
+Solving boundary value problems for ODE systems
+===============================================
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_bvp     -- Solve a boundary value problem for a system of ODEs.
+"""  # noqa: E501
+
+
+from ._quadrature import *
+from ._odepack_py import *
+from ._quadpack_py import *
+from ._ode import *
+from ._bvp import solve_bvp
+from ._ivp import (solve_ivp, OdeSolution, DenseOutput,
+                   OdeSolver, RK23, RK45, DOP853, Radau, BDF, LSODA)
+from ._quad_vec import quad_vec
+from ._tanhsinh import nsum, tanhsinh
+from ._cubature import cubature
+from ._lebedev import lebedev_rule
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import dop, lsoda, vode, odepack, quadpack
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46dbb9d89cc69f5e7a841d09e6d185e0f2bc30fe
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..108f3b34507159955e8d70009ad7110b67e3173a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_cubature.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_cubature.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f79332c101e7aa511abca1aef28e0618c1ff5bc5
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_cubature.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fa38163055a7c2358868d6ce9666d56251d592f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..415fd34c85c7b76171f600c79b51e1b1a8d9b105
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_odepack_py.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..820e48080f3476690df7215b8e1231b65371e077
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quad_vec.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73fb7c3e6638bc7b361f679ae44ce7fa36f31d27
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadpack_py.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de5671e50241d5871e06959905e8b0bd7678ed37
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e80f4d8eab92f95c79e6872f83a6a7baa6b5d988
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/_tanhsinh.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec6703d9b9937e20036b7c68ecbbb5a2e566bf52
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e25e967ac354b60be237743880ae1236fd4fea2
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/odepack.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/odepack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2176795f1820828dc6d2d6fdcf951f2ea2f1dcf4
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/odepack.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..730b3c12d4048f47a9cc81e951c2234f183e2278
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb350f571abbd8ce7b696eb755d929f75385ceea
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_bvp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_bvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..74406c89a689edc3de21fcb7274c90d41b8d2dcc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_bvp.py
@@ -0,0 +1,1154 @@
+"""Boundary value problem solver."""
+from warnings import warn
+
+import numpy as np
+from numpy.linalg import pinv
+
+from scipy.sparse import coo_matrix, csc_matrix
+from scipy.sparse.linalg import splu
+from scipy.optimize import OptimizeResult
+
+
+EPS = np.finfo(float).eps
+
+
+def estimate_fun_jac(fun, x, y, p, f0=None):
+    """Estimate derivatives of an ODE system rhs with forward differences.
+
+    Returns
+    -------
+    df_dy : ndarray, shape (n, n, m)
+        Derivatives with respect to y. An element (i, j, q) corresponds to
+        d f_i(x_q, y_q) / d (y_q)_j.
+    df_dp : ndarray with shape (n, k, m) or None
+        Derivatives with respect to p. An element (i, j, q) corresponds to
+        d f_i(x_q, y_q, p) / d p_j. If `p` is empty, None is returned.
+    """
+    n, m = y.shape
+    if f0 is None:
+        f0 = fun(x, y, p)
+
+    dtype = y.dtype
+
+    df_dy = np.empty((n, n, m), dtype=dtype)
+    h = EPS**0.5 * (1 + np.abs(y))
+    for i in range(n):
+        y_new = y.copy()
+        y_new[i] += h[i]
+        hi = y_new[i] - y[i]
+        f_new = fun(x, y_new, p)
+        df_dy[:, i, :] = (f_new - f0) / hi
+
+    k = p.shape[0]
+    if k == 0:
+        df_dp = None
+    else:
+        df_dp = np.empty((n, k, m), dtype=dtype)
+        h = EPS**0.5 * (1 + np.abs(p))
+        for i in range(k):
+            p_new = p.copy()
+            p_new[i] += h[i]
+            hi = p_new[i] - p[i]
+            f_new = fun(x, y, p_new)
+            df_dp[:, i, :] = (f_new - f0) / hi
+
+    return df_dy, df_dp
+
+
+def estimate_bc_jac(bc, ya, yb, p, bc0=None):
+    """Estimate derivatives of boundary conditions with forward differences.
+
+    Returns
+    -------
+    dbc_dya : ndarray, shape (n + k, n)
+        Derivatives with respect to ya. An element (i, j) corresponds to
+        d bc_i / d ya_j.
+    dbc_dyb : ndarray, shape (n + k, n)
+        Derivatives with respect to yb. An element (i, j) corresponds to
+        d bc_i / d ya_j.
+    dbc_dp : ndarray with shape (n + k, k) or None
+        Derivatives with respect to p. An element (i, j) corresponds to
+        d bc_i / d p_j. If `p` is empty, None is returned.
+    """
+    n = ya.shape[0]
+    k = p.shape[0]
+
+    if bc0 is None:
+        bc0 = bc(ya, yb, p)
+
+    dtype = ya.dtype
+
+    dbc_dya = np.empty((n, n + k), dtype=dtype)
+    h = EPS**0.5 * (1 + np.abs(ya))
+    for i in range(n):
+        ya_new = ya.copy()
+        ya_new[i] += h[i]
+        hi = ya_new[i] - ya[i]
+        bc_new = bc(ya_new, yb, p)
+        dbc_dya[i] = (bc_new - bc0) / hi
+    dbc_dya = dbc_dya.T
+
+    h = EPS**0.5 * (1 + np.abs(yb))
+    dbc_dyb = np.empty((n, n + k), dtype=dtype)
+    for i in range(n):
+        yb_new = yb.copy()
+        yb_new[i] += h[i]
+        hi = yb_new[i] - yb[i]
+        bc_new = bc(ya, yb_new, p)
+        dbc_dyb[i] = (bc_new - bc0) / hi
+    dbc_dyb = dbc_dyb.T
+
+    if k == 0:
+        dbc_dp = None
+    else:
+        h = EPS**0.5 * (1 + np.abs(p))
+        dbc_dp = np.empty((k, n + k), dtype=dtype)
+        for i in range(k):
+            p_new = p.copy()
+            p_new[i] += h[i]
+            hi = p_new[i] - p[i]
+            bc_new = bc(ya, yb, p_new)
+            dbc_dp[i] = (bc_new - bc0) / hi
+        dbc_dp = dbc_dp.T
+
+    return dbc_dya, dbc_dyb, dbc_dp
+
+
+def compute_jac_indices(n, m, k):
+    """Compute indices for the collocation system Jacobian construction.
+
+    See `construct_global_jac` for the explanation.
+    """
+    i_col = np.repeat(np.arange((m - 1) * n), n)
+    j_col = (np.tile(np.arange(n), n * (m - 1)) +
+             np.repeat(np.arange(m - 1) * n, n**2))
+
+    i_bc = np.repeat(np.arange((m - 1) * n, m * n + k), n)
+    j_bc = np.tile(np.arange(n), n + k)
+
+    i_p_col = np.repeat(np.arange((m - 1) * n), k)
+    j_p_col = np.tile(np.arange(m * n, m * n + k), (m - 1) * n)
+
+    i_p_bc = np.repeat(np.arange((m - 1) * n, m * n + k), k)
+    j_p_bc = np.tile(np.arange(m * n, m * n + k), n + k)
+
+    i = np.hstack((i_col, i_col, i_bc, i_bc, i_p_col, i_p_bc))
+    j = np.hstack((j_col, j_col + n,
+                   j_bc, j_bc + (m - 1) * n,
+                   j_p_col, j_p_bc))
+
+    return i, j
+
+
+def stacked_matmul(a, b):
+    """Stacked matrix multiply: out[i,:,:] = np.dot(a[i,:,:], b[i,:,:]).
+
+    Empirical optimization. Use outer Python loop and BLAS for large
+    matrices, otherwise use a single einsum call.
+    """
+    if a.shape[1] > 50:
+        out = np.empty((a.shape[0], a.shape[1], b.shape[2]))
+        for i in range(a.shape[0]):
+            out[i] = np.dot(a[i], b[i])
+        return out
+    else:
+        return np.einsum('...ij,...jk->...ik', a, b)
+
+
+def construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, df_dp,
+                         df_dp_middle, dbc_dya, dbc_dyb, dbc_dp):
+    """Construct the Jacobian of the collocation system.
+
+    There are n * m + k functions: m - 1 collocations residuals, each
+    containing n components, followed by n + k boundary condition residuals.
+
+    There are n * m + k variables: m vectors of y, each containing n
+    components, followed by k values of vector p.
+
+    For example, let m = 4, n = 2 and k = 1, then the Jacobian will have
+    the following sparsity structure:
+
+        1 1 2 2 0 0 0 0  5
+        1 1 2 2 0 0 0 0  5
+        0 0 1 1 2 2 0 0  5
+        0 0 1 1 2 2 0 0  5
+        0 0 0 0 1 1 2 2  5
+        0 0 0 0 1 1 2 2  5
+
+        3 3 0 0 0 0 4 4  6
+        3 3 0 0 0 0 4 4  6
+        3 3 0 0 0 0 4 4  6
+
+    Zeros denote identically zero values, other values denote different kinds
+    of blocks in the matrix (see below). The blank row indicates the separation
+    of collocation residuals from boundary conditions. And the blank column
+    indicates the separation of y values from p values.
+
+    Refer to [1]_  (p. 306) for the formula of n x n blocks for derivatives
+    of collocation residuals with respect to y.
+
+    Parameters
+    ----------
+    n : int
+        Number of equations in the ODE system.
+    m : int
+        Number of nodes in the mesh.
+    k : int
+        Number of the unknown parameters.
+    i_jac, j_jac : ndarray
+        Row and column indices returned by `compute_jac_indices`. They
+        represent different blocks in the Jacobian matrix in the following
+        order (see the scheme above):
+
+            * 1: m - 1 diagonal n x n blocks for the collocation residuals.
+            * 2: m - 1 off-diagonal n x n blocks for the collocation residuals.
+            * 3 : (n + k) x n block for the dependency of the boundary
+              conditions on ya.
+            * 4: (n + k) x n block for the dependency of the boundary
+              conditions on yb.
+            * 5: (m - 1) * n x k block for the dependency of the collocation
+              residuals on p.
+            * 6: (n + k) x k block for the dependency of the boundary
+              conditions on p.
+
+    df_dy : ndarray, shape (n, n, m)
+        Jacobian of f with respect to y computed at the mesh nodes.
+    df_dy_middle : ndarray, shape (n, n, m - 1)
+        Jacobian of f with respect to y computed at the middle between the
+        mesh nodes.
+    df_dp : ndarray with shape (n, k, m) or None
+        Jacobian of f with respect to p computed at the mesh nodes.
+    df_dp_middle : ndarray with shape (n, k, m - 1) or None
+        Jacobian of f with respect to p computed at the middle between the
+        mesh nodes.
+    dbc_dya, dbc_dyb : ndarray, shape (n, n)
+        Jacobian of bc with respect to ya and yb.
+    dbc_dp : ndarray with shape (n, k) or None
+        Jacobian of bc with respect to p.
+
+    Returns
+    -------
+    J : csc_matrix, shape (n * m + k, n * m + k)
+        Jacobian of the collocation system in a sparse form.
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+       Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+       Number 3, pp. 299-316, 2001.
+    """
+    df_dy = np.transpose(df_dy, (2, 0, 1))
+    df_dy_middle = np.transpose(df_dy_middle, (2, 0, 1))
+
+    h = h[:, np.newaxis, np.newaxis]
+
+    dtype = df_dy.dtype
+
+    # Computing diagonal n x n blocks.
+    dPhi_dy_0 = np.empty((m - 1, n, n), dtype=dtype)
+    dPhi_dy_0[:] = -np.identity(n)
+    dPhi_dy_0 -= h / 6 * (df_dy[:-1] + 2 * df_dy_middle)
+    T = stacked_matmul(df_dy_middle, df_dy[:-1])
+    dPhi_dy_0 -= h**2 / 12 * T
+
+    # Computing off-diagonal n x n blocks.
+    dPhi_dy_1 = np.empty((m - 1, n, n), dtype=dtype)
+    dPhi_dy_1[:] = np.identity(n)
+    dPhi_dy_1 -= h / 6 * (df_dy[1:] + 2 * df_dy_middle)
+    T = stacked_matmul(df_dy_middle, df_dy[1:])
+    dPhi_dy_1 += h**2 / 12 * T
+
+    values = np.hstack((dPhi_dy_0.ravel(), dPhi_dy_1.ravel(), dbc_dya.ravel(),
+                        dbc_dyb.ravel()))
+
+    if k > 0:
+        df_dp = np.transpose(df_dp, (2, 0, 1))
+        df_dp_middle = np.transpose(df_dp_middle, (2, 0, 1))
+        T = stacked_matmul(df_dy_middle, df_dp[:-1] - df_dp[1:])
+        df_dp_middle += 0.125 * h * T
+        dPhi_dp = -h/6 * (df_dp[:-1] + df_dp[1:] + 4 * df_dp_middle)
+        values = np.hstack((values, dPhi_dp.ravel(), dbc_dp.ravel()))
+
+    J = coo_matrix((values, (i_jac, j_jac)))
+    return csc_matrix(J)
+
+
+def collocation_fun(fun, y, p, x, h):
+    """Evaluate collocation residuals.
+
+    This function lies in the core of the method. The solution is sought
+    as a cubic C1 continuous spline with derivatives matching the ODE rhs
+    at given nodes `x`. Collocation conditions are formed from the equality
+    of the spline derivatives and rhs of the ODE system in the middle points
+    between nodes.
+
+    Such method is classified to Lobbato IIIA family in ODE literature.
+    Refer to [1]_ for the formula and some discussion.
+
+    Returns
+    -------
+    col_res : ndarray, shape (n, m - 1)
+        Collocation residuals at the middle points of the mesh intervals.
+    y_middle : ndarray, shape (n, m - 1)
+        Values of the cubic spline evaluated at the middle points of the mesh
+        intervals.
+    f : ndarray, shape (n, m)
+        RHS of the ODE system evaluated at the mesh nodes.
+    f_middle : ndarray, shape (n, m - 1)
+        RHS of the ODE system evaluated at the middle points of the mesh
+        intervals (and using `y_middle`).
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+           Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+           Number 3, pp. 299-316, 2001.
+    """
+    f = fun(x, y, p)
+    y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) -
+                0.125 * h * (f[:, 1:] - f[:, :-1]))
+    f_middle = fun(x[:-1] + 0.5 * h, y_middle, p)
+    col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] +
+                                              4 * f_middle)
+
+    return col_res, y_middle, f, f_middle
+
+
+def prepare_sys(n, m, k, fun, bc, fun_jac, bc_jac, x, h):
+    """Create the function and the Jacobian for the collocation system."""
+    x_middle = x[:-1] + 0.5 * h
+    i_jac, j_jac = compute_jac_indices(n, m, k)
+
+    def col_fun(y, p):
+        return collocation_fun(fun, y, p, x, h)
+
+    def sys_jac(y, p, y_middle, f, f_middle, bc0):
+        if fun_jac is None:
+            df_dy, df_dp = estimate_fun_jac(fun, x, y, p, f)
+            df_dy_middle, df_dp_middle = estimate_fun_jac(
+                fun, x_middle, y_middle, p, f_middle)
+        else:
+            df_dy, df_dp = fun_jac(x, y, p)
+            df_dy_middle, df_dp_middle = fun_jac(x_middle, y_middle, p)
+
+        if bc_jac is None:
+            dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc, y[:, 0], y[:, -1],
+                                                       p, bc0)
+        else:
+            dbc_dya, dbc_dyb, dbc_dp = bc_jac(y[:, 0], y[:, -1], p)
+
+        return construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy,
+                                    df_dy_middle, df_dp, df_dp_middle, dbc_dya,
+                                    dbc_dyb, dbc_dp)
+
+    return col_fun, sys_jac
+
+
+def solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol):
+    """Solve the nonlinear collocation system by a Newton method.
+
+    This is a simple Newton method with a backtracking line search. As
+    advised in [1]_, an affine-invariant criterion function F = ||J^-1 r||^2
+    is used, where J is the Jacobian matrix at the current iteration and r is
+    the vector or collocation residuals (values of the system lhs).
+
+    The method alters between full Newton iterations and the fixed-Jacobian
+    iterations based
+
+    There are other tricks proposed in [1]_, but they are not used as they
+    don't seem to improve anything significantly, and even break the
+    convergence on some test problems I tried.
+
+    All important parameters of the algorithm are defined inside the function.
+
+    Parameters
+    ----------
+    n : int
+        Number of equations in the ODE system.
+    m : int
+        Number of nodes in the mesh.
+    h : ndarray, shape (m-1,)
+        Mesh intervals.
+    col_fun : callable
+        Function computing collocation residuals.
+    bc : callable
+        Function computing boundary condition residuals.
+    jac : callable
+        Function computing the Jacobian of the whole system (including
+        collocation and boundary condition residuals). It is supposed to
+        return csc_matrix.
+    y : ndarray, shape (n, m)
+        Initial guess for the function values at the mesh nodes.
+    p : ndarray, shape (k,)
+        Initial guess for the unknown parameters.
+    B : ndarray with shape (n, n) or None
+        Matrix to force the S y(a) = 0 condition for a problems with the
+        singular term. If None, the singular term is assumed to be absent.
+    bvp_tol : float
+        Tolerance to which we want to solve a BVP.
+    bc_tol : float
+        Tolerance to which we want to satisfy the boundary conditions.
+
+    Returns
+    -------
+    y : ndarray, shape (n, m)
+        Final iterate for the function values at the mesh nodes.
+    p : ndarray, shape (k,)
+        Final iterate for the unknown parameters.
+    singular : bool
+        True, if the LU decomposition failed because Jacobian turned out
+        to be singular.
+
+    References
+    ----------
+    .. [1]  U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
+       Boundary Value Problems for Ordinary Differential Equations"
+    """
+    # We know that the solution residuals at the middle points of the mesh
+    # are connected with collocation residuals  r_middle = 1.5 * col_res / h.
+    # As our BVP solver tries to decrease relative residuals below a certain
+    # tolerance, it seems reasonable to terminated Newton iterations by
+    # comparison of r_middle / (1 + np.abs(f_middle)) with a certain threshold,
+    # which we choose to be 1.5 orders lower than the BVP tolerance. We rewrite
+    # the condition as col_res < tol_r * (1 + np.abs(f_middle)), then tol_r
+    # should be computed as follows:
+    tol_r = 2/3 * h * 5e-2 * bvp_tol
+
+    # Maximum allowed number of Jacobian evaluation and factorization, in
+    # other words, the maximum number of full Newton iterations. A small value
+    # is recommended in the literature.
+    max_njev = 4
+
+    # Maximum number of iterations, considering that some of them can be
+    # performed with the fixed Jacobian. In theory, such iterations are cheap,
+    # but it's not that simple in Python.
+    max_iter = 8
+
+    # Minimum relative improvement of the criterion function to accept the
+    # step (Armijo constant).
+    sigma = 0.2
+
+    # Step size decrease factor for backtracking.
+    tau = 0.5
+
+    # Maximum number of backtracking steps, the minimum step is then
+    # tau ** n_trial.
+    n_trial = 4
+
+    col_res, y_middle, f, f_middle = col_fun(y, p)
+    bc_res = bc(y[:, 0], y[:, -1], p)
+    res = np.hstack((col_res.ravel(order='F'), bc_res))
+
+    njev = 0
+    singular = False
+    recompute_jac = True
+    for iteration in range(max_iter):
+        if recompute_jac:
+            J = jac(y, p, y_middle, f, f_middle, bc_res)
+            njev += 1
+            try:
+                LU = splu(J)
+            except RuntimeError:
+                singular = True
+                break
+
+            step = LU.solve(res)
+            cost = np.dot(step, step)
+
+        y_step = step[:m * n].reshape((n, m), order='F')
+        p_step = step[m * n:]
+
+        alpha = 1
+        for trial in range(n_trial + 1):
+            y_new = y - alpha * y_step
+            if B is not None:
+                y_new[:, 0] = np.dot(B, y_new[:, 0])
+            p_new = p - alpha * p_step
+
+            col_res, y_middle, f, f_middle = col_fun(y_new, p_new)
+            bc_res = bc(y_new[:, 0], y_new[:, -1], p_new)
+            res = np.hstack((col_res.ravel(order='F'), bc_res))
+
+            step_new = LU.solve(res)
+            cost_new = np.dot(step_new, step_new)
+            if cost_new < (1 - 2 * alpha * sigma) * cost:
+                break
+
+            if trial < n_trial:
+                alpha *= tau
+
+        y = y_new
+        p = p_new
+
+        if njev == max_njev:
+            break
+
+        if (np.all(np.abs(col_res) < tol_r * (1 + np.abs(f_middle))) and
+                np.all(np.abs(bc_res) < bc_tol)):
+            break
+
+        # If the full step was taken, then we are going to continue with
+        # the same Jacobian. This is the approach of BVP_SOLVER.
+        if alpha == 1:
+            step = step_new
+            cost = cost_new
+            recompute_jac = False
+        else:
+            recompute_jac = True
+
+    return y, p, singular
+
+
+def print_iteration_header():
+    print(f"{'Iteration':^15}{'Max residual':^15}{'Max BC residual':^15}"
+          f"{'Total nodes':^15}{'Nodes added':^15}")
+
+
+def print_iteration_progress(iteration, residual, bc_residual, total_nodes,
+                             nodes_added):
+    print(f"{iteration:^15}{residual:^15.2e}{bc_residual:^15.2e}"
+          f"{total_nodes:^15}{nodes_added:^15}")
+
+
+class BVPResult(OptimizeResult):
+    pass
+
+
+TERMINATION_MESSAGES = {
+    0: "The algorithm converged to the desired accuracy.",
+    1: "The maximum number of mesh nodes is exceeded.",
+    2: "A singular Jacobian encountered when solving the collocation system.",
+    3: "The solver was unable to satisfy boundary conditions tolerance on iteration 10."
+}
+
+
+def estimate_rms_residuals(fun, sol, x, h, p, r_middle, f_middle):
+    """Estimate rms values of collocation residuals using Lobatto quadrature.
+
+    The residuals are defined as the difference between the derivatives of
+    our solution and rhs of the ODE system. We use relative residuals, i.e.,
+    normalized by 1 + np.abs(f). RMS values are computed as sqrt from the
+    normalized integrals of the squared relative residuals over each interval.
+    Integrals are estimated using 5-point Lobatto quadrature [1]_, we use the
+    fact that residuals at the mesh nodes are identically zero.
+
+    In [2] they don't normalize integrals by interval lengths, which gives
+    a higher rate of convergence of the residuals by the factor of h**0.5.
+    I chose to do such normalization for an ease of interpretation of return
+    values as RMS estimates.
+
+    Returns
+    -------
+    rms_res : ndarray, shape (m - 1,)
+        Estimated rms values of the relative residuals over each interval.
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/LobattoQuadrature.html
+    .. [2] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+       Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+       Number 3, pp. 299-316, 2001.
+    """
+    x_middle = x[:-1] + 0.5 * h
+    s = 0.5 * h * (3/7)**0.5
+    x1 = x_middle + s
+    x2 = x_middle - s
+    y1 = sol(x1)
+    y2 = sol(x2)
+    y1_prime = sol(x1, 1)
+    y2_prime = sol(x2, 1)
+    f1 = fun(x1, y1, p)
+    f2 = fun(x2, y2, p)
+    r1 = y1_prime - f1
+    r2 = y2_prime - f2
+
+    r_middle /= 1 + np.abs(f_middle)
+    r1 /= 1 + np.abs(f1)
+    r2 /= 1 + np.abs(f2)
+
+    r1 = np.sum(np.real(r1 * np.conj(r1)), axis=0)
+    r2 = np.sum(np.real(r2 * np.conj(r2)), axis=0)
+    r_middle = np.sum(np.real(r_middle * np.conj(r_middle)), axis=0)
+
+    return (0.5 * (32 / 45 * r_middle + 49 / 90 * (r1 + r2))) ** 0.5
+
+
+def create_spline(y, yp, x, h):
+    """Create a cubic spline given values and derivatives.
+
+    Formulas for the coefficients are taken from interpolate.CubicSpline.
+
+    Returns
+    -------
+    sol : PPoly
+        Constructed spline as a PPoly instance.
+    """
+    from scipy.interpolate import PPoly
+
+    n, m = y.shape
+    c = np.empty((4, n, m - 1), dtype=y.dtype)
+    slope = (y[:, 1:] - y[:, :-1]) / h
+    t = (yp[:, :-1] + yp[:, 1:] - 2 * slope) / h
+    c[0] = t / h
+    c[1] = (slope - yp[:, :-1]) / h - t
+    c[2] = yp[:, :-1]
+    c[3] = y[:, :-1]
+    c = np.moveaxis(c, 1, 0)
+
+    return PPoly(c, x, extrapolate=True, axis=1)
+
+
+def modify_mesh(x, insert_1, insert_2):
+    """Insert nodes into a mesh.
+
+    Nodes removal logic is not established, its impact on the solver is
+    presumably negligible. So, only insertion is done in this function.
+
+    Parameters
+    ----------
+    x : ndarray, shape (m,)
+        Mesh nodes.
+    insert_1 : ndarray
+        Intervals to each insert 1 new node in the middle.
+    insert_2 : ndarray
+        Intervals to each insert 2 new nodes, such that divide an interval
+        into 3 equal parts.
+
+    Returns
+    -------
+    x_new : ndarray
+        New mesh nodes.
+
+    Notes
+    -----
+    `insert_1` and `insert_2` should not have common values.
+    """
+    # Because np.insert implementation apparently varies with a version of
+    # NumPy, we use a simple and reliable approach with sorting.
+    return np.sort(np.hstack((
+        x,
+        0.5 * (x[insert_1] + x[insert_1 + 1]),
+        (2 * x[insert_2] + x[insert_2 + 1]) / 3,
+        (x[insert_2] + 2 * x[insert_2 + 1]) / 3
+    )))
+
+
+def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype):
+    """Wrap functions for unified usage in the solver."""
+    if fun_jac is None:
+        fun_jac_wrapped = None
+
+    if bc_jac is None:
+        bc_jac_wrapped = None
+
+    if k == 0:
+        def fun_p(x, y, _):
+            return np.asarray(fun(x, y), dtype)
+
+        def bc_wrapped(ya, yb, _):
+            return np.asarray(bc(ya, yb), dtype)
+
+        if fun_jac is not None:
+            def fun_jac_p(x, y, _):
+                return np.asarray(fun_jac(x, y), dtype), None
+
+        if bc_jac is not None:
+            def bc_jac_wrapped(ya, yb, _):
+                dbc_dya, dbc_dyb = bc_jac(ya, yb)
+                return (np.asarray(dbc_dya, dtype),
+                        np.asarray(dbc_dyb, dtype), None)
+    else:
+        def fun_p(x, y, p):
+            return np.asarray(fun(x, y, p), dtype)
+
+        def bc_wrapped(x, y, p):
+            return np.asarray(bc(x, y, p), dtype)
+
+        if fun_jac is not None:
+            def fun_jac_p(x, y, p):
+                df_dy, df_dp = fun_jac(x, y, p)
+                return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype)
+
+        if bc_jac is not None:
+            def bc_jac_wrapped(ya, yb, p):
+                dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p)
+                return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype),
+                        np.asarray(dbc_dp, dtype))
+
+    if S is None:
+        fun_wrapped = fun_p
+    else:
+        def fun_wrapped(x, y, p):
+            f = fun_p(x, y, p)
+            if x[0] == a:
+                f[:, 0] = np.dot(D, f[:, 0])
+                f[:, 1:] += np.dot(S, y[:, 1:]) / (x[1:] - a)
+            else:
+                f += np.dot(S, y) / (x - a)
+            return f
+
+    if fun_jac is not None:
+        if S is None:
+            fun_jac_wrapped = fun_jac_p
+        else:
+            Sr = S[:, :, np.newaxis]
+
+            def fun_jac_wrapped(x, y, p):
+                df_dy, df_dp = fun_jac_p(x, y, p)
+                if x[0] == a:
+                    df_dy[:, :, 0] = np.dot(D, df_dy[:, :, 0])
+                    df_dy[:, :, 1:] += Sr / (x[1:] - a)
+                else:
+                    df_dy += Sr / (x - a)
+
+                return df_dy, df_dp
+
+    return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped
+
+
+def solve_bvp(fun, bc, x, y, p=None, S=None, fun_jac=None, bc_jac=None,
+              tol=1e-3, max_nodes=1000, verbose=0, bc_tol=None):
+    """Solve a boundary value problem for a system of ODEs.
+
+    This function numerically solves a first order system of ODEs subject to
+    two-point boundary conditions::
+
+        dy / dx = f(x, y, p) + S * y / (x - a), a <= x <= b
+        bc(y(a), y(b), p) = 0
+
+    Here x is a 1-D independent variable, y(x) is an n-D
+    vector-valued function and p is a k-D vector of unknown
+    parameters which is to be found along with y(x). For the problem to be
+    determined, there must be n + k boundary conditions, i.e., bc must be an
+    (n + k)-D function.
+
+    The last singular term on the right-hand side of the system is optional.
+    It is defined by an n-by-n matrix S, such that the solution must satisfy
+    S y(a) = 0. This condition will be forced during iterations, so it must not
+    contradict boundary conditions. See [2]_ for the explanation how this term
+    is handled when solving BVPs numerically.
+
+    Problems in a complex domain can be solved as well. In this case, y and p
+    are considered to be complex, and f and bc are assumed to be complex-valued
+    functions, but x stays real. Note that f and bc must be complex
+    differentiable (satisfy Cauchy-Riemann equations [4]_), otherwise you
+    should rewrite your problem for real and imaginary parts separately. To
+    solve a problem in a complex domain, pass an initial guess for y with a
+    complex data type (see below).
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system. The calling signature is ``fun(x, y)``,
+        or ``fun(x, y, p)`` if parameters are present. All arguments are
+        ndarray: ``x`` with shape (m,), ``y`` with shape (n, m), meaning that
+        ``y[:, i]`` corresponds to ``x[i]``, and ``p`` with shape (k,). The
+        return value must be an array with shape (n, m) and with the same
+        layout as ``y``.
+    bc : callable
+        Function evaluating residuals of the boundary conditions. The calling
+        signature is ``bc(ya, yb)``, or ``bc(ya, yb, p)`` if parameters are
+        present. All arguments are ndarray: ``ya`` and ``yb`` with shape (n,),
+        and ``p`` with shape (k,). The return value must be an array with
+        shape (n + k,).
+    x : array_like, shape (m,)
+        Initial mesh. Must be a strictly increasing sequence of real numbers
+        with ``x[0]=a`` and ``x[-1]=b``.
+    y : array_like, shape (n, m)
+        Initial guess for the function values at the mesh nodes, ith column
+        corresponds to ``x[i]``. For problems in a complex domain pass `y`
+        with a complex data type (even if the initial guess is purely real).
+    p : array_like with shape (k,) or None, optional
+        Initial guess for the unknown parameters. If None (default), it is
+        assumed that the problem doesn't depend on any parameters.
+    S : array_like with shape (n, n) or None
+        Matrix defining the singular term. If None (default), the problem is
+        solved without the singular term.
+    fun_jac : callable or None, optional
+        Function computing derivatives of f with respect to y and p. The
+        calling signature is ``fun_jac(x, y)``, or ``fun_jac(x, y, p)`` if
+        parameters are present. The return must contain 1 or 2 elements in the
+        following order:
+
+            * df_dy : array_like with shape (n, n, m), where an element
+              (i, j, q) equals to d f_i(x_q, y_q, p) / d (y_q)_j.
+            * df_dp : array_like with shape (n, k, m), where an element
+              (i, j, q) equals to d f_i(x_q, y_q, p) / d p_j.
+
+        Here q numbers nodes at which x and y are defined, whereas i and j
+        number vector components. If the problem is solved without unknown
+        parameters, df_dp should not be returned.
+
+        If `fun_jac` is None (default), the derivatives will be estimated
+        by the forward finite differences.
+    bc_jac : callable or None, optional
+        Function computing derivatives of bc with respect to ya, yb, and p.
+        The calling signature is ``bc_jac(ya, yb)``, or ``bc_jac(ya, yb, p)``
+        if parameters are present. The return must contain 2 or 3 elements in
+        the following order:
+
+            * dbc_dya : array_like with shape (n, n), where an element (i, j)
+              equals to d bc_i(ya, yb, p) / d ya_j.
+            * dbc_dyb : array_like with shape (n, n), where an element (i, j)
+              equals to d bc_i(ya, yb, p) / d yb_j.
+            * dbc_dp : array_like with shape (n, k), where an element (i, j)
+              equals to d bc_i(ya, yb, p) / d p_j.
+
+        If the problem is solved without unknown parameters, dbc_dp should not
+        be returned.
+
+        If `bc_jac` is None (default), the derivatives will be estimated by
+        the forward finite differences.
+    tol : float, optional
+        Desired tolerance of the solution. If we define ``r = y' - f(x, y)``,
+        where y is the found solution, then the solver tries to achieve on each
+        mesh interval ``norm(r / (1 + abs(f)) < tol``, where ``norm`` is
+        estimated in a root mean squared sense (using a numerical quadrature
+        formula). Default is 1e-3.
+    max_nodes : int, optional
+        Maximum allowed number of the mesh nodes. If exceeded, the algorithm
+        terminates. Default is 1000.
+    verbose : {0, 1, 2}, optional
+        Level of algorithm's verbosity:
+
+            * 0 (default) : work silently.
+            * 1 : display a termination report.
+            * 2 : display progress during iterations.
+    bc_tol : float, optional
+        Desired absolute tolerance for the boundary condition residuals: `bc`
+        value should satisfy ``abs(bc) < bc_tol`` component-wise.
+        Equals to `tol` by default. Up to 10 iterations are allowed to achieve this
+        tolerance.
+
+    Returns
+    -------
+    Bunch object with the following fields defined:
+    sol : PPoly
+        Found solution for y as `scipy.interpolate.PPoly` instance, a C1
+        continuous cubic spline.
+    p : ndarray or None, shape (k,)
+        Found parameters. None, if the parameters were not present in the
+        problem.
+    x : ndarray, shape (m,)
+        Nodes of the final mesh.
+    y : ndarray, shape (n, m)
+        Solution values at the mesh nodes.
+    yp : ndarray, shape (n, m)
+        Solution derivatives at the mesh nodes.
+    rms_residuals : ndarray, shape (m - 1,)
+        RMS values of the relative residuals over each mesh interval (see the
+        description of `tol` parameter).
+    niter : int
+        Number of completed iterations.
+    status : int
+        Reason for algorithm termination:
+
+            * 0: The algorithm converged to the desired accuracy.
+            * 1: The maximum number of mesh nodes is exceeded.
+            * 2: A singular Jacobian encountered when solving the collocation
+              system.
+
+    message : string
+        Verbal description of the termination reason.
+    success : bool
+        True if the algorithm converged to the desired accuracy (``status=0``).
+
+    Notes
+    -----
+    This function implements a 4th order collocation algorithm with the
+    control of residuals similar to [1]_. A collocation system is solved
+    by a damped Newton method with an affine-invariant criterion function as
+    described in [3]_.
+
+    Note that in [1]_  integral residuals are defined without normalization
+    by interval lengths. So, their definition is different by a multiplier of
+    h**0.5 (h is an interval length) from the definition used here.
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
+           Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
+           Number 3, pp. 299-316, 2001.
+    .. [2] L.F. Shampine, P. H. Muir and H. Xu, "A User-Friendly Fortran BVP
+           Solver".
+    .. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
+           Boundary Value Problems for Ordinary Differential Equations".
+    .. [4] `Cauchy-Riemann equations
+            `_ on
+            Wikipedia.
+
+    Examples
+    --------
+    In the first example, we solve Bratu's problem::
+
+        y'' + k * exp(y) = 0
+        y(0) = y(1) = 0
+
+    for k = 1.
+
+    We rewrite the equation as a first-order system and implement its
+    right-hand side evaluation::
+
+        y1' = y2
+        y2' = -exp(y1)
+
+    >>> import numpy as np
+    >>> def fun(x, y):
+    ...     return np.vstack((y[1], -np.exp(y[0])))
+
+    Implement evaluation of the boundary condition residuals:
+
+    >>> def bc(ya, yb):
+    ...     return np.array([ya[0], yb[0]])
+
+    Define the initial mesh with 5 nodes:
+
+    >>> x = np.linspace(0, 1, 5)
+
+    This problem is known to have two solutions. To obtain both of them, we
+    use two different initial guesses for y. We denote them by subscripts
+    a and b.
+
+    >>> y_a = np.zeros((2, x.size))
+    >>> y_b = np.zeros((2, x.size))
+    >>> y_b[0] = 3
+
+    Now we are ready to run the solver.
+
+    >>> from scipy.integrate import solve_bvp
+    >>> res_a = solve_bvp(fun, bc, x, y_a)
+    >>> res_b = solve_bvp(fun, bc, x, y_b)
+
+    Let's plot the two found solutions. We take an advantage of having the
+    solution in a spline form to produce a smooth plot.
+
+    >>> x_plot = np.linspace(0, 1, 100)
+    >>> y_plot_a = res_a.sol(x_plot)[0]
+    >>> y_plot_b = res_b.sol(x_plot)[0]
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(x_plot, y_plot_a, label='y_a')
+    >>> plt.plot(x_plot, y_plot_b, label='y_b')
+    >>> plt.legend()
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("y")
+    >>> plt.show()
+
+    We see that the two solutions have similar shape, but differ in scale
+    significantly.
+
+    In the second example, we solve a simple Sturm-Liouville problem::
+
+        y'' + k**2 * y = 0
+        y(0) = y(1) = 0
+
+    It is known that a non-trivial solution y = A * sin(k * x) is possible for
+    k = pi * n, where n is an integer. To establish the normalization constant
+    A = 1 we add a boundary condition::
+
+        y'(0) = k
+
+    Again, we rewrite our equation as a first-order system and implement its
+    right-hand side evaluation::
+
+        y1' = y2
+        y2' = -k**2 * y1
+
+    >>> def fun(x, y, p):
+    ...     k = p[0]
+    ...     return np.vstack((y[1], -k**2 * y[0]))
+
+    Note that parameters p are passed as a vector (with one element in our
+    case).
+
+    Implement the boundary conditions:
+
+    >>> def bc(ya, yb, p):
+    ...     k = p[0]
+    ...     return np.array([ya[0], yb[0], ya[1] - k])
+
+    Set up the initial mesh and guess for y. We aim to find the solution for
+    k = 2 * pi, to achieve that we set values of y to approximately follow
+    sin(2 * pi * x):
+
+    >>> x = np.linspace(0, 1, 5)
+    >>> y = np.zeros((2, x.size))
+    >>> y[0, 1] = 1
+    >>> y[0, 3] = -1
+
+    Run the solver with 6 as an initial guess for k.
+
+    >>> sol = solve_bvp(fun, bc, x, y, p=[6])
+
+    We see that the found k is approximately correct:
+
+    >>> sol.p[0]
+    6.28329460046
+
+    And, finally, plot the solution to see the anticipated sinusoid:
+
+    >>> x_plot = np.linspace(0, 1, 100)
+    >>> y_plot = sol.sol(x_plot)[0]
+    >>> plt.plot(x_plot, y_plot)
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("y")
+    >>> plt.show()
+    """
+    x = np.asarray(x, dtype=float)
+    if x.ndim != 1:
+        raise ValueError("`x` must be 1 dimensional.")
+    h = np.diff(x)
+    if np.any(h <= 0):
+        raise ValueError("`x` must be strictly increasing.")
+    a = x[0]
+
+    y = np.asarray(y)
+    if np.issubdtype(y.dtype, np.complexfloating):
+        dtype = complex
+    else:
+        dtype = float
+    y = y.astype(dtype, copy=False)
+
+    if y.ndim != 2:
+        raise ValueError("`y` must be 2 dimensional.")
+    if y.shape[1] != x.shape[0]:
+        raise ValueError(f"`y` is expected to have {x.shape[0]} columns, but actually "
+                         f"has {y.shape[1]}.")
+
+    if p is None:
+        p = np.array([])
+    else:
+        p = np.asarray(p, dtype=dtype)
+    if p.ndim != 1:
+        raise ValueError("`p` must be 1 dimensional.")
+
+    if tol < 100 * EPS:
+        warn(f"`tol` is too low, setting to {100 * EPS:.2e}", stacklevel=2)
+        tol = 100 * EPS
+
+    if verbose not in [0, 1, 2]:
+        raise ValueError("`verbose` must be in [0, 1, 2].")
+
+    n = y.shape[0]
+    k = p.shape[0]
+
+    if S is not None:
+        S = np.asarray(S, dtype=dtype)
+        if S.shape != (n, n):
+            raise ValueError(f"`S` is expected to have shape {(n, n)}, "
+                             f"but actually has {S.shape}")
+
+        # Compute I - S^+ S to impose necessary boundary conditions.
+        B = np.identity(n) - np.dot(pinv(S), S)
+
+        y[:, 0] = np.dot(B, y[:, 0])
+
+        # Compute (I - S)^+ to correct derivatives at x=a.
+        D = pinv(np.identity(n) - S)
+    else:
+        B = None
+        D = None
+
+    if bc_tol is None:
+        bc_tol = tol
+
+    # Maximum number of iterations
+    max_iteration = 10
+
+    fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions(
+        fun, bc, fun_jac, bc_jac, k, a, S, D, dtype)
+
+    f = fun_wrapped(x, y, p)
+    if f.shape != y.shape:
+        raise ValueError(f"`fun` return is expected to have shape {y.shape}, "
+                         f"but actually has {f.shape}.")
+
+    bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
+    if bc_res.shape != (n + k,):
+        raise ValueError(f"`bc` return is expected to have shape {(n + k,)}, "
+                         f"but actually has {bc_res.shape}.")
+
+    status = 0
+    iteration = 0
+    if verbose == 2:
+        print_iteration_header()
+
+    while True:
+        m = x.shape[0]
+
+        col_fun, jac_sys = prepare_sys(n, m, k, fun_wrapped, bc_wrapped,
+                                       fun_jac_wrapped, bc_jac_wrapped, x, h)
+        y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys,
+                                      y, p, B, tol, bc_tol)
+        iteration += 1
+
+        col_res, y_middle, f, f_middle = collocation_fun(fun_wrapped, y,
+                                                         p, x, h)
+        bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
+        max_bc_res = np.max(abs(bc_res))
+
+        # This relation is not trivial, but can be verified.
+        r_middle = 1.5 * col_res / h
+        sol = create_spline(y, f, x, h)
+        rms_res = estimate_rms_residuals(fun_wrapped, sol, x, h, p,
+                                         r_middle, f_middle)
+        max_rms_res = np.max(rms_res)
+
+        if singular:
+            status = 2
+            break
+
+        insert_1, = np.nonzero((rms_res > tol) & (rms_res < 100 * tol))
+        insert_2, = np.nonzero(rms_res >= 100 * tol)
+        nodes_added = insert_1.shape[0] + 2 * insert_2.shape[0]
+
+        if m + nodes_added > max_nodes:
+            status = 1
+            if verbose == 2:
+                nodes_added = f"({nodes_added})"
+                print_iteration_progress(iteration, max_rms_res, max_bc_res,
+                                         m, nodes_added)
+            break
+
+        if verbose == 2:
+            print_iteration_progress(iteration, max_rms_res, max_bc_res, m,
+                                     nodes_added)
+
+        if nodes_added > 0:
+            x = modify_mesh(x, insert_1, insert_2)
+            h = np.diff(x)
+            y = sol(x)
+        elif max_bc_res <= bc_tol:
+            status = 0
+            break
+        elif iteration >= max_iteration:
+            status = 3
+            break
+
+    if verbose > 0:
+        if status == 0:
+            print(f"Solved in {iteration} iterations, number of nodes {x.shape[0]}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 1:
+            print(f"Number of nodes is exceeded after iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 2:
+            print("Singular Jacobian encountered when solving the collocation "
+                  f"system on iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+        elif status == 3:
+            print("The solver was unable to satisfy boundary conditions "
+                  f"tolerance on iteration {iteration}. \n"
+                  f"Maximum relative residual: {max_rms_res:.2e} \n"
+                  f"Maximum boundary residual: {max_bc_res:.2e}")
+
+    if p.size == 0:
+        p = None
+
+    return BVPResult(sol=sol, p=p, x=x, y=y, yp=f, rms_residuals=rms_res,
+                     niter=iteration, status=status,
+                     message=TERMINATION_MESSAGES[status], success=status == 0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_cubature.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_cubature.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e6d8911d13eeaa2420ef65a12e9b4ba34400ca0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_cubature.py
@@ -0,0 +1,728 @@
+import math
+import heapq
+import itertools
+
+from dataclasses import dataclass, field
+from types import ModuleType
+from typing import Any, TypeAlias
+
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_copy,
+    xp_broadcast_promote
+)
+from scipy._lib._util import MapWrapper
+
+from scipy.integrate._rules import (
+    ProductNestedFixed,
+    GaussKronrodQuadrature,
+    GenzMalikCubature,
+)
+from scipy.integrate._rules._base import _split_subregion
+
+__all__ = ['cubature']
+
+Array: TypeAlias = Any  # To be changed to an array-api-typing Protocol later
+
+
+@dataclass
+class CubatureRegion:
+    estimate: Array
+    error: Array
+    a: Array
+    b: Array
+    _xp: ModuleType = field(repr=False)
+
+    def __lt__(self, other):
+        # Consider regions with higher error estimates as being "less than" regions with
+        # lower order estimates, so that regions with high error estimates are placed at
+        # the top of the heap.
+
+        this_err = self._xp.max(self._xp.abs(self.error))
+        other_err = self._xp.max(self._xp.abs(other.error))
+
+        return this_err > other_err
+
+
+@dataclass
+class CubatureResult:
+    estimate: Array
+    error: Array
+    status: str
+    regions: list[CubatureRegion]
+    subdivisions: int
+    atol: float
+    rtol: float
+
+
+def cubature(f, a, b, *, rule="gk21", rtol=1e-8, atol=0, max_subdivisions=10000,
+             args=(), workers=1, points=None):
+    r"""
+    Adaptive cubature of multidimensional array-valued function.
+
+    Given an arbitrary integration rule, this function returns an estimate of the
+    integral to the requested tolerance over the region defined by the arrays `a` and
+    `b` specifying the corners of a hypercube.
+
+    Convergence is not guaranteed for all integrals.
+
+    Parameters
+    ----------
+    f : callable
+        Function to integrate. `f` must have the signature::
+
+            f(x : ndarray, *args) -> ndarray
+
+        `f` should accept arrays ``x`` of shape::
+
+            (npoints, ndim)
+
+        and output arrays of shape::
+
+            (npoints, output_dim_1, ..., output_dim_n)
+
+        In this case, `cubature` will return arrays of shape::
+
+            (output_dim_1, ..., output_dim_n)
+    a, b : array_like
+        Lower and upper limits of integration as 1D arrays specifying the left and right
+        endpoints of the intervals being integrated over. Limits can be infinite.
+    rule : str, optional
+        Rule used to estimate the integral. If passing a string, the options are
+        "gauss-kronrod" (21 node), or "genz-malik" (degree 7). If a rule like
+        "gauss-kronrod" is specified for an ``n``-dim integrand, the corresponding
+        Cartesian product rule is used. "gk21", "gk15" are also supported for
+        compatibility with `quad_vec`. See Notes.
+    rtol, atol : float, optional
+        Relative and absolute tolerances. Iterations are performed until the error is
+        estimated to be less than ``atol + rtol * abs(est)``. Here `rtol` controls
+        relative accuracy (number of correct digits), while `atol` controls absolute
+        accuracy (number of correct decimal places). To achieve the desired `rtol`, set
+        `atol` to be smaller than the smallest value that can be expected from
+        ``rtol * abs(y)`` so that `rtol` dominates the allowable error. If `atol` is
+        larger than ``rtol * abs(y)`` the number of correct digits is not guaranteed.
+        Conversely, to achieve the desired `atol`, set `rtol` such that
+        ``rtol * abs(y)`` is always smaller than `atol`. Default values are 1e-8 for
+        `rtol` and 0 for `atol`.
+    max_subdivisions : int, optional
+        Upper bound on the number of subdivisions to perform. Default is 10,000.
+    args : tuple, optional
+        Additional positional args passed to `f`, if any.
+    workers : int or map-like callable, optional
+        If `workers` is an integer, part of the computation is done in parallel
+        subdivided to this many tasks (using :class:`python:multiprocessing.pool.Pool`).
+        Supply `-1` to use all cores available to the Process. Alternatively, supply a
+        map-like callable, such as :meth:`python:multiprocessing.pool.Pool.map` for
+        evaluating the population in parallel. This evaluation is carried out as
+        ``workers(func, iterable)``.
+    points : list of array_like, optional
+        List of points to avoid evaluating `f` at, under the condition that the rule
+        being used does not evaluate `f` on the boundary of a region (which is the
+        case for all Genz-Malik and Gauss-Kronrod rules). This can be useful if `f` has
+        a singularity at the specified point. This should be a list of array-likes where
+        each element has length ``ndim``. Default is empty. See Examples.
+
+    Returns
+    -------
+    res : object
+        Object containing the results of the estimation. It has the following
+        attributes:
+
+        estimate : ndarray
+            Estimate of the value of the integral over the overall region specified.
+        error : ndarray
+            Estimate of the error of the approximation over the overall region
+            specified.
+        status : str
+            Whether the estimation was successful. Can be either: "converged",
+            "not_converged".
+        subdivisions : int
+            Number of subdivisions performed.
+        atol, rtol : float
+            Requested tolerances for the approximation.
+        regions: list of object
+            List of objects containing the estimates of the integral over smaller
+            regions of the domain.
+
+        Each object in ``regions`` has the following attributes:
+
+        a, b : ndarray
+            Points describing the corners of the region. If the original integral
+            contained infinite limits or was over a region described by `region`,
+            then `a` and `b` are in the transformed coordinates.
+        estimate : ndarray
+            Estimate of the value of the integral over this region.
+        error : ndarray
+            Estimate of the error of the approximation over this region.
+
+    Notes
+    -----
+    The algorithm uses a similar algorithm to `quad_vec`, which itself is based on the
+    implementation of QUADPACK's DQAG* algorithms, implementing global error control and
+    adaptive subdivision.
+
+    The source of the nodes and weights used for Gauss-Kronrod quadrature can be found
+    in [1]_, and the algorithm for calculating the nodes and weights in Genz-Malik
+    cubature can be found in [2]_.
+
+    The rules currently supported via the `rule` argument are:
+
+    - ``"gauss-kronrod"``, 21-node Gauss-Kronrod
+    - ``"genz-malik"``, n-node Genz-Malik
+
+    If using Gauss-Kronrod for an ``n``-dim integrand where ``n > 2``, then the
+    corresponding Cartesian product rule will be found by taking the Cartesian product
+    of the nodes in the 1D case. This means that the number of nodes scales
+    exponentially as ``21^n`` in the Gauss-Kronrod case, which may be problematic in a
+    moderate number of dimensions.
+
+    Genz-Malik is typically less accurate than Gauss-Kronrod but has much fewer nodes,
+    so in this situation using "genz-malik" might be preferable.
+
+    Infinite limits are handled with an appropriate variable transformation. Assuming
+    ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
+
+    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
+
+    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
+    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    References
+    ----------
+    .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
+        Integration, files: dqk21.f, dqk15.f (1983).
+
+    .. [2] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
+        numerical integration over an N-dimensional rectangular region, Journal of
+        Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
+        ISSN 0377-0427
+        :doi:`10.1016/0771-050X(80)90039-X`
+
+    Examples
+    --------
+    **1D integral with vector output**:
+
+    .. math::
+
+        \int^1_0 \mathbf f(x) \text dx
+
+    Where ``f(x) = x^n`` and ``n = np.arange(10)`` is a vector. Since no rule is
+    specified, the default "gk21" is used, which corresponds to Gauss-Kronrod
+    integration with 21 nodes.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> def f(x, n):
+    ...    # Make sure x and n are broadcastable
+    ...    return x[:, np.newaxis]**n[np.newaxis, :]
+    >>> res = cubature(
+    ...     f,
+    ...     a=[0],
+    ...     b=[1],
+    ...     args=(np.arange(10),),
+    ... )
+    >>> res.estimate
+     array([1.        , 0.5       , 0.33333333, 0.25      , 0.2       ,
+            0.16666667, 0.14285714, 0.125     , 0.11111111, 0.1       ])
+
+    **7D integral with arbitrary-shaped array output**::
+
+        f(x) = cos(2*pi*r + alphas @ x)
+
+    for some ``r`` and ``alphas``, and the integral is performed over the unit
+    hybercube, :math:`[0, 1]^7`. Since the integral is in a moderate number of
+    dimensions, "genz-malik" is used rather than the default "gauss-kronrod" to
+    avoid constructing a product rule with :math:`21^7 \approx 2 \times 10^9` nodes.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> def f(x, r, alphas):
+    ...     # f(x) = cos(2*pi*r + alphas @ x)
+    ...     # Need to allow r and alphas to be arbitrary shape
+    ...     npoints, ndim = x.shape[0], x.shape[-1]
+    ...     alphas = alphas[np.newaxis, ...]
+    ...     x = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
+    ...     return np.cos(2*np.pi*r + np.sum(alphas * x, axis=-1))
+    >>> rng = np.random.default_rng()
+    >>> r, alphas = rng.random((2, 3)), rng.random((2, 3, 7))
+    >>> res = cubature(
+    ...     f=f,
+    ...     a=np.array([0, 0, 0, 0, 0, 0, 0]),
+    ...     b=np.array([1, 1, 1, 1, 1, 1, 1]),
+    ...     rtol=1e-5,
+    ...     rule="genz-malik",
+    ...     args=(r, alphas),
+    ... )
+    >>> res.estimate
+     array([[-0.79812452,  0.35246913, -0.52273628],
+            [ 0.88392779,  0.59139899,  0.41895111]])
+
+    **Parallel computation with** `workers`:
+
+    >>> from concurrent.futures import ThreadPoolExecutor
+    >>> with ThreadPoolExecutor() as executor:
+    ...     res = cubature(
+    ...         f=f,
+    ...         a=np.array([0, 0, 0, 0, 0, 0, 0]),
+    ...         b=np.array([1, 1, 1, 1, 1, 1, 1]),
+    ...         rtol=1e-5,
+    ...         rule="genz-malik",
+    ...         args=(r, alphas),
+    ...         workers=executor.map,
+    ...      )
+    >>> res.estimate
+     array([[-0.79812452,  0.35246913, -0.52273628],
+            [ 0.88392779,  0.59139899,  0.41895111]])
+
+    **2D integral with infinite limits**:
+
+    .. math::
+
+        \int^{ \infty }_{ -\infty }
+        \int^{ \infty }_{ -\infty }
+            e^{-x^2-y^2}
+        \text dy
+        \text dx
+
+    >>> def gaussian(x):
+    ...     return np.exp(-np.sum(x**2, axis=-1))
+    >>> res = cubature(gaussian, [-np.inf, -np.inf], [np.inf, np.inf])
+    >>> res.estimate
+     3.1415926
+
+    **1D integral with singularities avoided using** `points`:
+
+    .. math::
+
+        \int^{ 1 }_{ -1 }
+          \frac{\sin(x)}{x}
+        \text dx
+
+    It is necessary to use the `points` parameter to avoid evaluating `f` at the origin.
+
+    >>> def sinc(x):
+    ...     return np.sin(x)/x
+    >>> res = cubature(sinc, [-1], [1], points=[[0]])
+    >>> res.estimate
+     1.8921661
+    """
+
+    # It is also possible to use a custom rule, but this is not yet part of the public
+    # API. An example of this can be found in the class scipy.integrate._rules.Rule.
+
+    xp = array_namespace(a, b)
+    max_subdivisions = float("inf") if max_subdivisions is None else max_subdivisions
+    points = [] if points is None else points
+
+    # Convert a and b to arrays and convert each point in points to an array, promoting
+    # each to a common floating dtype.
+    a, b, *points = xp_broadcast_promote(a, b, *points, force_floating=True)
+    result_dtype = a.dtype
+
+    if xp_size(a) == 0 or xp_size(b) == 0:
+        raise ValueError("`a` and `b` must be nonempty")
+
+    if a.ndim != 1 or b.ndim != 1:
+        raise ValueError("`a` and `b` must be 1D arrays")
+
+    # If the rule is a string, convert to a corresponding product rule
+    if isinstance(rule, str):
+        ndim = xp_size(a)
+
+        if rule == "genz-malik":
+            rule = GenzMalikCubature(ndim, xp=xp)
+        else:
+            quadratues = {
+                "gauss-kronrod": GaussKronrodQuadrature(21, xp=xp),
+
+                # Also allow names quad_vec uses:
+                "gk21": GaussKronrodQuadrature(21, xp=xp),
+                "gk15": GaussKronrodQuadrature(15, xp=xp),
+            }
+
+            base_rule = quadratues.get(rule)
+
+            if base_rule is None:
+                raise ValueError(f"unknown rule {rule}")
+
+            rule = ProductNestedFixed([base_rule] * ndim)
+
+    # If any of limits are the wrong way around (a > b), flip them and keep track of
+    # the sign.
+    sign = (-1) ** xp.sum(xp.astype(a > b, xp.int8), dtype=result_dtype)
+
+    a_flipped = xp.min(xp.stack([a, b]), axis=0)
+    b_flipped = xp.max(xp.stack([a, b]), axis=0)
+
+    a, b = a_flipped, b_flipped
+
+    # If any of the limits are infinite, apply a transformation
+    if xp.any(xp.isinf(a)) or xp.any(xp.isinf(b)):
+        f = _InfiniteLimitsTransform(f, a, b, xp=xp)
+        a, b = f.transformed_limits
+
+        # Map points from the original coordinates to the new transformed coordinates.
+        #
+        # `points` is a list of arrays of shape (ndim,), but transformations are applied
+        # to arrays of shape (npoints, ndim).
+        #
+        # It is not possible to combine all the points into one array and then apply
+        # f.inv to all of them at once since `points` needs to remain iterable.
+        # Instead, each point is reshaped to an array of shape (1, ndim), `f.inv` is
+        # applied, and then each is reshaped back to (ndim,).
+        points = [xp.reshape(point, (1, -1)) for point in points]
+        points = [f.inv(point) for point in points]
+        points = [xp.reshape(point, (-1,)) for point in points]
+
+        # Include any problematic points introduced by the transformation
+        points.extend(f.points)
+
+    # If any problematic points are specified, divide the initial region so that these
+    # points lie on the edge of a subregion.
+    #
+    # This means ``f`` won't be evaluated there if the rule being used has no evaluation
+    # points on the boundary.
+    if len(points) == 0:
+        initial_regions = [(a, b)]
+    else:
+        initial_regions = _split_region_at_points(a, b, points, xp)
+
+    regions = []
+    est = 0.0
+    err = 0.0
+
+    for a_k, b_k in initial_regions:
+        est_k = rule.estimate(f, a_k, b_k, args)
+        err_k = rule.estimate_error(f, a_k, b_k, args)
+        regions.append(CubatureRegion(est_k, err_k, a_k, b_k, xp))
+
+        est += est_k
+        err += err_k
+
+    subdivisions = 0
+    success = True
+
+    with MapWrapper(workers) as mapwrapper:
+        while xp.any(err > atol + rtol * xp.abs(est)):
+            # region_k is the region with highest estimated error
+            region_k = heapq.heappop(regions)
+
+            est_k = region_k.estimate
+            err_k = region_k.error
+
+            a_k, b_k = region_k.a, region_k.b
+
+            # Subtract the estimate of the integral and its error over this region from
+            # the current global estimates, since these will be refined in the loop over
+            # all subregions.
+            est -= est_k
+            err -= err_k
+
+            # Find all 2^ndim subregions formed by splitting region_k along each axis,
+            # e.g. for 1D integrals this splits an estimate over an interval into an
+            # estimate over two subintervals, for 3D integrals this splits an estimate
+            # over a cube into 8 subcubes.
+            #
+            # For each of the new subregions, calculate an estimate for the integral and
+            # the error there, and push these regions onto the heap for potential
+            # further subdividing.
+
+            executor_args = zip(
+                itertools.repeat(f),
+                itertools.repeat(rule),
+                itertools.repeat(args),
+                _split_subregion(a_k, b_k, xp),
+            )
+
+            for subdivision_result in mapwrapper(_process_subregion, executor_args):
+                a_k_sub, b_k_sub, est_sub, err_sub = subdivision_result
+
+                est += est_sub
+                err += err_sub
+
+                new_region = CubatureRegion(est_sub, err_sub, a_k_sub, b_k_sub, xp)
+
+                heapq.heappush(regions, new_region)
+
+            subdivisions += 1
+
+            if subdivisions >= max_subdivisions:
+                success = False
+                break
+
+        status = "converged" if success else "not_converged"
+
+        # Apply sign change to handle any limits which were initially flipped.
+        est = sign * est
+
+        return CubatureResult(
+            estimate=est,
+            error=err,
+            status=status,
+            subdivisions=subdivisions,
+            regions=regions,
+            atol=atol,
+            rtol=rtol,
+        )
+
+
+def _process_subregion(data):
+    f, rule, args, coord = data
+    a_k_sub, b_k_sub = coord
+
+    est_sub = rule.estimate(f, a_k_sub, b_k_sub, args)
+    err_sub = rule.estimate_error(f, a_k_sub, b_k_sub, args)
+
+    return a_k_sub, b_k_sub, est_sub, err_sub
+
+
+def _is_strictly_in_region(a, b, point, xp):
+    if xp.all(point == a) or xp.all(point == b):
+        return False
+
+    return xp.all(a <= point) and xp.all(point <= b)
+
+
+def _split_region_at_points(a, b, points, xp):
+    """
+    Given the integration limits `a` and `b` describing a rectangular region and a list
+    of `points`, find the list of ``[(a_1, b_1), ..., (a_l, b_l)]`` which breaks up the
+    initial region into smaller subregion such that no `points` lie strictly inside
+    any of the subregions.
+    """
+
+    regions = [(a, b)]
+
+    for point in points:
+        if xp.any(xp.isinf(point)):
+            # If a point is specified at infinity, ignore.
+            #
+            # This case occurs when points are given by the user to avoid, but after
+            # applying a transformation, they are removed.
+            continue
+
+        new_subregions = []
+
+        for a_k, b_k in regions:
+            if _is_strictly_in_region(a_k, b_k, point, xp):
+                subregions = _split_subregion(a_k, b_k, xp, point)
+
+                for left, right in subregions:
+                    # Skip any zero-width regions.
+                    if xp.any(left == right):
+                        continue
+                    else:
+                        new_subregions.append((left, right))
+
+                new_subregions.extend(subregions)
+
+            else:
+                new_subregions.append((a_k, b_k))
+
+        regions = new_subregions
+
+    return regions
+
+
+class _VariableTransform:
+    """
+    A transformation that can be applied to an integral.
+    """
+
+    @property
+    def transformed_limits(self):
+        """
+        New limits of integration after applying the transformation.
+        """
+
+        raise NotImplementedError
+
+    @property
+    def points(self):
+        """
+        Any problematic points introduced by the transformation.
+
+        These should be specified as points where ``_VariableTransform(f)(self, point)``
+        would be problematic.
+
+        For example, if the transformation ``x = 1/((1-t)(1+t))`` is applied to a
+        univariate integral, then points should return ``[ [1], [-1] ]``.
+        """
+
+        return []
+
+    def inv(self, x):
+        """
+        Map points ``x`` to ``t`` such that if ``f`` is the original function and ``g``
+        is the function after the transformation is applied, then::
+
+            f(x) = g(self.inv(x))
+        """
+
+        raise NotImplementedError
+
+    def __call__(self, t, *args, **kwargs):
+        """
+        Apply the transformation to ``f`` and multiply by the Jacobian determinant.
+        This should be the new integrand after the transformation has been applied so
+        that the following is satisfied::
+
+            f_transformed = _VariableTransform(f)
+
+            cubature(f, a, b) == cubature(
+                f_transformed,
+                *f_transformed.transformed_limits(a, b),
+            )
+        """
+
+        raise NotImplementedError
+
+
+class _InfiniteLimitsTransform(_VariableTransform):
+    r"""
+    Transformation for handling infinite limits.
+
+    Assuming ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
+
+    If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
+
+    If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
+    will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+
+    If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
+    variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
+    :math:`t \in (0, 1)`.
+    """
+
+    def __init__(self, f, a, b, xp):
+        self._xp = xp
+
+        self._f = f
+        self._orig_a = a
+        self._orig_b = b
+
+        # (-oo, oo) will be mapped to (-1, 1).
+        self._double_inf_pos = (a == -math.inf) & (b == math.inf)
+
+        # (start, oo) will be mapped to (0, 1).
+        start_inf_mask = (a != -math.inf) & (b == math.inf)
+
+        # (-oo, end) will be mapped to (0, 1).
+        inf_end_mask = (a == -math.inf) & (b != math.inf)
+
+        # This is handled by making the transformation t = -x and reducing it to
+        # the other semi-infinite case.
+        self._semi_inf_pos = start_inf_mask | inf_end_mask
+
+        # Since we flip the limits, we don't need to separately multiply the
+        # integrand by -1.
+        self._orig_a[inf_end_mask] = -b[inf_end_mask]
+        self._orig_b[inf_end_mask] = -a[inf_end_mask]
+
+        self._num_inf = self._xp.sum(
+            self._xp.astype(self._double_inf_pos | self._semi_inf_pos, self._xp.int64),
+        ).__int__()
+
+    @property
+    def transformed_limits(self):
+        a = xp_copy(self._orig_a)
+        b = xp_copy(self._orig_b)
+
+        a[self._double_inf_pos] = -1
+        b[self._double_inf_pos] = 1
+
+        a[self._semi_inf_pos] = 0
+        b[self._semi_inf_pos] = 1
+
+        return a, b
+
+    @property
+    def points(self):
+        # If there are infinite limits, then the origin becomes a problematic point
+        # due to a division by zero there.
+
+        # If the function using this class only wraps f when a and b contain infinite
+        # limits, this condition will always be met (as is the case with cubature).
+        #
+        # If a and b do not contain infinite limits but f is still wrapped with this
+        # class, then without this condition the initial region of integration will
+        # be split around the origin unnecessarily.
+        if self._num_inf != 0:
+            return [self._xp.zeros(self._orig_a.shape)]
+        else:
+            return []
+
+    def inv(self, x):
+        t = xp_copy(x)
+        npoints = x.shape[0]
+
+        double_inf_mask = self._xp.tile(
+            self._double_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        semi_inf_mask = self._xp.tile(
+            self._semi_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        # If any components of x are 0, then this component will be mapped to infinity
+        # under the transformation used for doubly-infinite limits.
+        #
+        # Handle the zero values and non-zero values separately to avoid division by
+        # zero.
+        zero_mask = x[double_inf_mask] == 0
+        non_zero_mask = double_inf_mask & ~zero_mask
+        t[zero_mask] = math.inf
+        t[non_zero_mask] = 1/(x[non_zero_mask] + self._xp.sign(x[non_zero_mask]))
+
+        start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
+        t[semi_inf_mask] = 1/(x[semi_inf_mask] - start + 1)
+
+        return t
+
+    def __call__(self, t, *args, **kwargs):
+        x = xp_copy(t)
+        npoints = t.shape[0]
+
+        double_inf_mask = self._xp.tile(
+            self._double_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        semi_inf_mask = self._xp.tile(
+            self._semi_inf_pos[self._xp.newaxis, :],
+            (npoints, 1),
+        )
+
+        # For (-oo, oo) -> (-1, 1), use the transformation x = (1-|t|)/t.
+        x[double_inf_mask] = (
+            (1 - self._xp.abs(t[double_inf_mask])) / t[double_inf_mask]
+        )
+
+        start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
+
+        # For (start, oo) -> (0, 1), use the transformation x = start + (1-t)/t.
+        x[semi_inf_mask] = start + (1 - t[semi_inf_mask]) / t[semi_inf_mask]
+
+        jacobian_det = 1/self._xp.prod(
+            self._xp.reshape(
+                t[semi_inf_mask | double_inf_mask]**2,
+                (-1, self._num_inf),
+            ),
+            axis=-1,
+        )
+
+        f_x = self._f(x, *args, **kwargs)
+        jacobian_det = self._xp.reshape(jacobian_det, (-1, *([1]*(len(f_x.shape) - 1))))
+
+        return f_x * jacobian_det
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3c8aaa36588651ae5e48b58fbb1d443bc71fc77
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py
@@ -0,0 +1,8 @@
+"""Suite of ODE solvers implemented in Python."""
+from .ivp import solve_ivp
+from .rk import RK23, RK45, DOP853
+from .radau import Radau
+from .bdf import BDF
+from .lsoda import LSODA
+from .common import OdeSolution
+from .base import DenseOutput, OdeSolver
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85eb4a4b532ec4defefce8adb3173aef00d4030e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..560400c47b8045ffb7aa135aef65ce2fe59e3b5c
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71094111d8be6547366ff430dea6b2d1aa668c65
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e98957f4989e7068fc712c355351eabd40bb0bd
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8af73c39a64e8b8945ecb38e6314c23d879f5f0d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c867b6f0d3877d3e4d92747e8e8400a8ff7a2c9
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c682c76948583bef23c3d7391a682112bc6570cd
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..abd3eb4a47c118fe3a063cabc35f8af76552db0f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c117934a7b7bada976d0e8fa689da9650072b7fa
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..46db9a69dfb3e7aee5c150ac6795234cd455dfe5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py
@@ -0,0 +1,290 @@
+import numpy as np
+
+
+def check_arguments(fun, y0, support_complex):
+    """Helper function for checking arguments common to all solvers."""
+    y0 = np.asarray(y0)
+    if np.issubdtype(y0.dtype, np.complexfloating):
+        if not support_complex:
+            raise ValueError("`y0` is complex, but the chosen solver does "
+                             "not support integration in a complex domain.")
+        dtype = complex
+    else:
+        dtype = float
+    y0 = y0.astype(dtype, copy=False)
+
+    if y0.ndim != 1:
+        raise ValueError("`y0` must be 1-dimensional.")
+
+    if not np.isfinite(y0).all():
+        raise ValueError("All components of the initial state `y0` must be finite.")
+
+    def fun_wrapped(t, y):
+        return np.asarray(fun(t, y), dtype=dtype)
+
+    return fun_wrapped, y0
+
+
+class OdeSolver:
+    """Base class for ODE solvers.
+
+    In order to implement a new solver you need to follow the guidelines:
+
+        1. A constructor must accept parameters presented in the base class
+           (listed below) along with any other parameters specific to a solver.
+        2. A constructor must accept arbitrary extraneous arguments
+           ``**extraneous``, but warn that these arguments are irrelevant
+           using `common.warn_extraneous` function. Do not pass these
+           arguments to the base class.
+        3. A solver must implement a private method `_step_impl(self)` which
+           propagates a solver one step further. It must return tuple
+           ``(success, message)``, where ``success`` is a boolean indicating
+           whether a step was successful, and ``message`` is a string
+           containing description of a failure if a step failed or None
+           otherwise.
+        4. A solver must implement a private method `_dense_output_impl(self)`,
+           which returns a `DenseOutput` object covering the last successful
+           step.
+        5. A solver must have attributes listed below in Attributes section.
+           Note that ``t_old`` and ``step_size`` are updated automatically.
+        6. Use `fun(self, t, y)` method for the system rhs evaluation, this
+           way the number of function evaluations (`nfev`) will be tracked
+           automatically.
+        7. For convenience, a base class provides `fun_single(self, t, y)` and
+           `fun_vectorized(self, t, y)` for evaluating the rhs in
+           non-vectorized and vectorized fashions respectively (regardless of
+           how `fun` from the constructor is implemented). These calls don't
+           increment `nfev`.
+        8. If a solver uses a Jacobian matrix and LU decompositions, it should
+           track the number of Jacobian evaluations (`njev`) and the number of
+           LU decompositions (`nlu`).
+        9. By convention, the function evaluations used to compute a finite
+           difference approximation of the Jacobian should not be counted in
+           `nfev`, thus use `fun_single(self, t, y)` or
+           `fun_vectorized(self, t, y)` when computing a finite difference
+           approximation of the Jacobian.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time --- the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    vectorized : bool
+        Whether `fun` can be called in a vectorized fashion. Default is False.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by methods 'Radau' and 'BDF', but
+        will result in slower execution for other methods. It can also
+        result in slower overall execution for 'Radau' and 'BDF' in some
+        circumstances (e.g. small ``len(y0)``).
+    support_complex : bool, optional
+        Whether integration in a complex domain should be supported.
+        Generally determined by a derived solver class capabilities.
+        Default is False.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number of the system's rhs evaluations.
+    njev : int
+        Number of the Jacobian evaluations.
+    nlu : int
+        Number of LU decompositions.
+    """
+    TOO_SMALL_STEP = "Required step size is less than spacing between numbers."
+
+    def __init__(self, fun, t0, y0, t_bound, vectorized,
+                 support_complex=False):
+        self.t_old = None
+        self.t = t0
+        self._fun, self.y = check_arguments(fun, y0, support_complex)
+        self.t_bound = t_bound
+        self.vectorized = vectorized
+
+        if vectorized:
+            def fun_single(t, y):
+                return self._fun(t, y[:, None]).ravel()
+            fun_vectorized = self._fun
+        else:
+            fun_single = self._fun
+
+            def fun_vectorized(t, y):
+                f = np.empty_like(y)
+                for i, yi in enumerate(y.T):
+                    f[:, i] = self._fun(t, yi)
+                return f
+
+        def fun(t, y):
+            self.nfev += 1
+            return self.fun_single(t, y)
+
+        self.fun = fun
+        self.fun_single = fun_single
+        self.fun_vectorized = fun_vectorized
+
+        self.direction = np.sign(t_bound - t0) if t_bound != t0 else 1
+        self.n = self.y.size
+        self.status = 'running'
+
+        self.nfev = 0
+        self.njev = 0
+        self.nlu = 0
+
+    @property
+    def step_size(self):
+        if self.t_old is None:
+            return None
+        else:
+            return np.abs(self.t - self.t_old)
+
+    def step(self):
+        """Perform one integration step.
+
+        Returns
+        -------
+        message : string or None
+            Report from the solver. Typically a reason for a failure if
+            `self.status` is 'failed' after the step was taken or None
+            otherwise.
+        """
+        if self.status != 'running':
+            raise RuntimeError("Attempt to step on a failed or finished "
+                               "solver.")
+
+        if self.n == 0 or self.t == self.t_bound:
+            # Handle corner cases of empty solver or no integration.
+            self.t_old = self.t
+            self.t = self.t_bound
+            message = None
+            self.status = 'finished'
+        else:
+            t = self.t
+            success, message = self._step_impl()
+
+            if not success:
+                self.status = 'failed'
+            else:
+                self.t_old = t
+                if self.direction * (self.t - self.t_bound) >= 0:
+                    self.status = 'finished'
+
+        return message
+
+    def dense_output(self):
+        """Compute a local interpolant over the last successful step.
+
+        Returns
+        -------
+        sol : `DenseOutput`
+            Local interpolant over the last successful step.
+        """
+        if self.t_old is None:
+            raise RuntimeError("Dense output is available after a successful "
+                               "step was made.")
+
+        if self.n == 0 or self.t == self.t_old:
+            # Handle corner cases of empty solver and no integration.
+            return ConstantDenseOutput(self.t_old, self.t, self.y)
+        else:
+            return self._dense_output_impl()
+
+    def _step_impl(self):
+        raise NotImplementedError
+
+    def _dense_output_impl(self):
+        raise NotImplementedError
+
+
+class DenseOutput:
+    """Base class for local interpolant over step made by an ODE solver.
+
+    It interpolates between `t_min` and `t_max` (see Attributes below).
+    Evaluation outside this interval is not forbidden, but the accuracy is not
+    guaranteed.
+
+    Attributes
+    ----------
+    t_min, t_max : float
+        Time range of the interpolation.
+    """
+    def __init__(self, t_old, t):
+        self.t_old = t_old
+        self.t = t
+        self.t_min = min(t, t_old)
+        self.t_max = max(t, t_old)
+
+    def __call__(self, t):
+        """Evaluate the interpolant.
+
+        Parameters
+        ----------
+        t : float or array_like with shape (n_points,)
+            Points to evaluate the solution at.
+
+        Returns
+        -------
+        y : ndarray, shape (n,) or (n, n_points)
+            Computed values. Shape depends on whether `t` was a scalar or a
+            1-D array.
+        """
+        t = np.asarray(t)
+        if t.ndim > 1:
+            raise ValueError("`t` must be a float or a 1-D array.")
+        return self._call_impl(t)
+
+    def _call_impl(self, t):
+        raise NotImplementedError
+
+
+class ConstantDenseOutput(DenseOutput):
+    """Constant value interpolator.
+
+    This class used for degenerate integration cases: equal integration limits
+    or a system with 0 equations.
+    """
+    def __init__(self, t_old, t, value):
+        super().__init__(t_old, t)
+        self.value = value
+
+    def _call_impl(self, t):
+        if t.ndim == 0:
+            return self.value
+        else:
+            ret = np.empty((self.value.shape[0], t.shape[0]))
+            ret[:] = self.value[:, None]
+            return ret
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..33b47a642b976e623edc9047f6465e328095dcd2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py
@@ -0,0 +1,478 @@
+import numpy as np
+from scipy.linalg import lu_factor, lu_solve
+from scipy.sparse import issparse, csc_matrix, eye
+from scipy.sparse.linalg import splu
+from scipy.optimize._numdiff import group_columns
+from .common import (validate_max_step, validate_tol, select_initial_step,
+                     norm, EPS, num_jac, validate_first_step,
+                     warn_extraneous)
+from .base import OdeSolver, DenseOutput
+
+
+MAX_ORDER = 5
+NEWTON_MAXITER = 4
+MIN_FACTOR = 0.2
+MAX_FACTOR = 10
+
+
+def compute_R(order, factor):
+    """Compute the matrix for changing the differences array."""
+    I = np.arange(1, order + 1)[:, None]
+    J = np.arange(1, order + 1)
+    M = np.zeros((order + 1, order + 1))
+    M[1:, 1:] = (I - 1 - factor * J) / I
+    M[0] = 1
+    return np.cumprod(M, axis=0)
+
+
+def change_D(D, order, factor):
+    """Change differences array in-place when step size is changed."""
+    R = compute_R(order, factor)
+    U = compute_R(order, 1)
+    RU = R.dot(U)
+    D[:order + 1] = np.dot(RU.T, D[:order + 1])
+
+
+def solve_bdf_system(fun, t_new, y_predict, c, psi, LU, solve_lu, scale, tol):
+    """Solve the algebraic system resulting from BDF method."""
+    d = 0
+    y = y_predict.copy()
+    dy_norm_old = None
+    converged = False
+    for k in range(NEWTON_MAXITER):
+        f = fun(t_new, y)
+        if not np.all(np.isfinite(f)):
+            break
+
+        dy = solve_lu(LU, c * f - psi - d)
+        dy_norm = norm(dy / scale)
+
+        if dy_norm_old is None:
+            rate = None
+        else:
+            rate = dy_norm / dy_norm_old
+
+        if (rate is not None and (rate >= 1 or
+                rate ** (NEWTON_MAXITER - k) / (1 - rate) * dy_norm > tol)):
+            break
+
+        y += dy
+        d += dy
+
+        if (dy_norm == 0 or
+                rate is not None and rate / (1 - rate) * dy_norm < tol):
+            converged = True
+            break
+
+        dy_norm_old = dy_norm
+
+    return converged, k + 1, y, d
+
+
+class BDF(OdeSolver):
+    """Implicit method based on backward-differentiation formulas.
+
+    This is a variable order method with the order varying automatically from
+    1 to 5. The general framework of the BDF algorithm is described in [1]_.
+    This class implements a quasi-constant step size as explained in [2]_.
+    The error estimation strategy for the constant-step BDF is derived in [3]_.
+    An accuracy enhancement using modified formulas (NDF) [2]_ is also implemented.
+
+    Can be applied in the complex domain.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    jac : {None, array_like, sparse_matrix, callable}, optional
+        Jacobian matrix of the right-hand side of the system with respect to y,
+        required by this method. The Jacobian matrix has shape (n, n) and its
+        element (i, j) is equal to ``d f_i / d y_j``.
+        There are three ways to define the Jacobian:
+
+            * If array_like or sparse_matrix, the Jacobian is assumed to
+              be constant.
+            * If callable, the Jacobian is assumed to depend on both
+              t and y; it will be called as ``jac(t, y)`` as necessary.
+              For the 'Radau' and 'BDF' methods, the return value might be a
+              sparse matrix.
+            * If None (default), the Jacobian will be approximated by
+              finite differences.
+
+        It is generally recommended to provide the Jacobian rather than
+        relying on a finite-difference approximation.
+    jac_sparsity : {None, array_like, sparse matrix}, optional
+        Defines a sparsity structure of the Jacobian matrix for a
+        finite-difference approximation. Its shape must be (n, n). This argument
+        is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
+        elements in *each* row, providing the sparsity structure will greatly
+        speed up the computations [4]_. A zero entry means that a corresponding
+        element in the Jacobian is always zero. If None (default), the Jacobian
+        is assumed to be dense.
+    vectorized : bool, optional
+        Whether `fun` can be called in a vectorized fashion. Default is False.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by this method, but may result in slower
+        execution overall in some circumstances (e.g. small ``len(y0)``).
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number of evaluations of the right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+    nlu : int
+        Number of LU decompositions.
+
+    References
+    ----------
+    .. [1] G. D. Byrne, A. C. Hindmarsh, "A Polyalgorithm for the Numerical
+           Solution of Ordinary Differential Equations", ACM Transactions on
+           Mathematical Software, Vol. 1, No. 1, pp. 71-96, March 1975.
+    .. [2] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
+           COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
+    .. [3] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations I:
+           Nonstiff Problems", Sec. III.2.
+    .. [4] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+           sparse Jacobian matrices", Journal of the Institute of Mathematics
+           and its Applications, 13, pp. 117-120, 1974.
+    """
+    def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+                 rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
+                 vectorized=False, first_step=None, **extraneous):
+        warn_extraneous(extraneous)
+        super().__init__(fun, t0, y0, t_bound, vectorized,
+                         support_complex=True)
+        self.max_step = validate_max_step(max_step)
+        self.rtol, self.atol = validate_tol(rtol, atol, self.n)
+        f = self.fun(self.t, self.y)
+        if first_step is None:
+            self.h_abs = select_initial_step(self.fun, self.t, self.y, 
+                                             t_bound, max_step, f,
+                                             self.direction, 1,
+                                             self.rtol, self.atol)
+        else:
+            self.h_abs = validate_first_step(first_step, t0, t_bound)
+        self.h_abs_old = None
+        self.error_norm_old = None
+
+        self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
+
+        self.jac_factor = None
+        self.jac, self.J = self._validate_jac(jac, jac_sparsity)
+        if issparse(self.J):
+            def lu(A):
+                self.nlu += 1
+                return splu(A)
+
+            def solve_lu(LU, b):
+                return LU.solve(b)
+
+            I = eye(self.n, format='csc', dtype=self.y.dtype)
+        else:
+            def lu(A):
+                self.nlu += 1
+                return lu_factor(A, overwrite_a=True)
+
+            def solve_lu(LU, b):
+                return lu_solve(LU, b, overwrite_b=True)
+
+            I = np.identity(self.n, dtype=self.y.dtype)
+
+        self.lu = lu
+        self.solve_lu = solve_lu
+        self.I = I
+
+        kappa = np.array([0, -0.1850, -1/9, -0.0823, -0.0415, 0])
+        self.gamma = np.hstack((0, np.cumsum(1 / np.arange(1, MAX_ORDER + 1))))
+        self.alpha = (1 - kappa) * self.gamma
+        self.error_const = kappa * self.gamma + 1 / np.arange(1, MAX_ORDER + 2)
+
+        D = np.empty((MAX_ORDER + 3, self.n), dtype=self.y.dtype)
+        D[0] = self.y
+        D[1] = f * self.h_abs * self.direction
+        self.D = D
+
+        self.order = 1
+        self.n_equal_steps = 0
+        self.LU = None
+
+    def _validate_jac(self, jac, sparsity):
+        t0 = self.t
+        y0 = self.y
+
+        if jac is None:
+            if sparsity is not None:
+                if issparse(sparsity):
+                    sparsity = csc_matrix(sparsity)
+                groups = group_columns(sparsity)
+                sparsity = (sparsity, groups)
+
+            def jac_wrapped(t, y):
+                self.njev += 1
+                f = self.fun_single(t, y)
+                J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
+                                             self.atol, self.jac_factor,
+                                             sparsity)
+                return J
+            J = jac_wrapped(t0, y0)
+        elif callable(jac):
+            J = jac(t0, y0)
+            self.njev += 1
+            if issparse(J):
+                J = csc_matrix(J, dtype=y0.dtype)
+
+                def jac_wrapped(t, y):
+                    self.njev += 1
+                    return csc_matrix(jac(t, y), dtype=y0.dtype)
+            else:
+                J = np.asarray(J, dtype=y0.dtype)
+
+                def jac_wrapped(t, y):
+                    self.njev += 1
+                    return np.asarray(jac(t, y), dtype=y0.dtype)
+
+            if J.shape != (self.n, self.n):
+                raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+                                 f" but actually has {J.shape}.")
+        else:
+            if issparse(jac):
+                J = csc_matrix(jac, dtype=y0.dtype)
+            else:
+                J = np.asarray(jac, dtype=y0.dtype)
+
+            if J.shape != (self.n, self.n):
+                raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+                                 f" but actually has {J.shape}.")
+            jac_wrapped = None
+
+        return jac_wrapped, J
+
+    def _step_impl(self):
+        t = self.t
+        D = self.D
+
+        max_step = self.max_step
+        min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
+        if self.h_abs > max_step:
+            h_abs = max_step
+            change_D(D, self.order, max_step / self.h_abs)
+            self.n_equal_steps = 0
+        elif self.h_abs < min_step:
+            h_abs = min_step
+            change_D(D, self.order, min_step / self.h_abs)
+            self.n_equal_steps = 0
+        else:
+            h_abs = self.h_abs
+
+        atol = self.atol
+        rtol = self.rtol
+        order = self.order
+
+        alpha = self.alpha
+        gamma = self.gamma
+        error_const = self.error_const
+
+        J = self.J
+        LU = self.LU
+        current_jac = self.jac is None
+
+        step_accepted = False
+        while not step_accepted:
+            if h_abs < min_step:
+                return False, self.TOO_SMALL_STEP
+
+            h = h_abs * self.direction
+            t_new = t + h
+
+            if self.direction * (t_new - self.t_bound) > 0:
+                t_new = self.t_bound
+                change_D(D, order, np.abs(t_new - t) / h_abs)
+                self.n_equal_steps = 0
+                LU = None
+
+            h = t_new - t
+            h_abs = np.abs(h)
+
+            y_predict = np.sum(D[:order + 1], axis=0)
+
+            scale = atol + rtol * np.abs(y_predict)
+            psi = np.dot(D[1: order + 1].T, gamma[1: order + 1]) / alpha[order]
+
+            converged = False
+            c = h / alpha[order]
+            while not converged:
+                if LU is None:
+                    LU = self.lu(self.I - c * J)
+
+                converged, n_iter, y_new, d = solve_bdf_system(
+                    self.fun, t_new, y_predict, c, psi, LU, self.solve_lu,
+                    scale, self.newton_tol)
+
+                if not converged:
+                    if current_jac:
+                        break
+                    J = self.jac(t_new, y_predict)
+                    LU = None
+                    current_jac = True
+
+            if not converged:
+                factor = 0.5
+                h_abs *= factor
+                change_D(D, order, factor)
+                self.n_equal_steps = 0
+                LU = None
+                continue
+
+            safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
+                                                       + n_iter)
+
+            scale = atol + rtol * np.abs(y_new)
+            error = error_const[order] * d
+            error_norm = norm(error / scale)
+
+            if error_norm > 1:
+                factor = max(MIN_FACTOR,
+                             safety * error_norm ** (-1 / (order + 1)))
+                h_abs *= factor
+                change_D(D, order, factor)
+                self.n_equal_steps = 0
+                # As we didn't have problems with convergence, we don't
+                # reset LU here.
+            else:
+                step_accepted = True
+
+        self.n_equal_steps += 1
+
+        self.t = t_new
+        self.y = y_new
+
+        self.h_abs = h_abs
+        self.J = J
+        self.LU = LU
+
+        # Update differences. The principal relation here is
+        # D^{j + 1} y_n = D^{j} y_n - D^{j} y_{n - 1}. Keep in mind that D
+        # contained difference for previous interpolating polynomial and
+        # d = D^{k + 1} y_n. Thus this elegant code follows.
+        D[order + 2] = d - D[order + 1]
+        D[order + 1] = d
+        for i in reversed(range(order + 1)):
+            D[i] += D[i + 1]
+
+        if self.n_equal_steps < order + 1:
+            return True, None
+
+        if order > 1:
+            error_m = error_const[order - 1] * D[order]
+            error_m_norm = norm(error_m / scale)
+        else:
+            error_m_norm = np.inf
+
+        if order < MAX_ORDER:
+            error_p = error_const[order + 1] * D[order + 2]
+            error_p_norm = norm(error_p / scale)
+        else:
+            error_p_norm = np.inf
+
+        error_norms = np.array([error_m_norm, error_norm, error_p_norm])
+        with np.errstate(divide='ignore'):
+            factors = error_norms ** (-1 / np.arange(order, order + 3))
+
+        delta_order = np.argmax(factors) - 1
+        order += delta_order
+        self.order = order
+
+        factor = min(MAX_FACTOR, safety * np.max(factors))
+        self.h_abs *= factor
+        change_D(D, order, factor)
+        self.n_equal_steps = 0
+        self.LU = None
+
+        return True, None
+
+    def _dense_output_impl(self):
+        return BdfDenseOutput(self.t_old, self.t, self.h_abs * self.direction,
+                              self.order, self.D[:self.order + 1].copy())
+
+
+class BdfDenseOutput(DenseOutput):
+    def __init__(self, t_old, t, h, order, D):
+        super().__init__(t_old, t)
+        self.order = order
+        self.t_shift = self.t - h * np.arange(self.order)
+        self.denom = h * (1 + np.arange(self.order))
+        self.D = D
+
+    def _call_impl(self, t):
+        if t.ndim == 0:
+            x = (t - self.t_shift) / self.denom
+            p = np.cumprod(x)
+        else:
+            x = (t - self.t_shift[:, None]) / self.denom[:, None]
+            p = np.cumprod(x, axis=0)
+
+        y = np.dot(self.D[1:].T, p)
+        if y.ndim == 1:
+            y += self.D[0]
+        else:
+            y += self.D[0, :, None]
+
+        return y
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c820ad97f5a26955e20f98d80b71168dac54b0a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py
@@ -0,0 +1,451 @@
+from itertools import groupby
+from warnings import warn
+import numpy as np
+from scipy.sparse import find, coo_matrix
+
+
+EPS = np.finfo(float).eps
+
+
+def validate_first_step(first_step, t0, t_bound):
+    """Assert that first_step is valid and return it."""
+    if first_step <= 0:
+        raise ValueError("`first_step` must be positive.")
+    if first_step > np.abs(t_bound - t0):
+        raise ValueError("`first_step` exceeds bounds.")
+    return first_step
+
+
+def validate_max_step(max_step):
+    """Assert that max_Step is valid and return it."""
+    if max_step <= 0:
+        raise ValueError("`max_step` must be positive.")
+    return max_step
+
+
+def warn_extraneous(extraneous):
+    """Display a warning for extraneous keyword arguments.
+
+    The initializer of each solver class is expected to collect keyword
+    arguments that it doesn't understand and warn about them. This function
+    prints a warning for each key in the supplied dictionary.
+
+    Parameters
+    ----------
+    extraneous : dict
+        Extraneous keyword arguments
+    """
+    if extraneous:
+        warn("The following arguments have no effect for a chosen solver: "
+             f"{', '.join(f'`{x}`' for x in extraneous)}.",
+             stacklevel=3)
+
+
+def validate_tol(rtol, atol, n):
+    """Validate tolerance values."""
+
+    if np.any(rtol < 100 * EPS):
+        warn("At least one element of `rtol` is too small. "
+             f"Setting `rtol = np.maximum(rtol, {100 * EPS})`.",
+             stacklevel=3)
+        rtol = np.maximum(rtol, 100 * EPS)
+
+    atol = np.asarray(atol)
+    if atol.ndim > 0 and atol.shape != (n,):
+        raise ValueError("`atol` has wrong shape.")
+
+    if np.any(atol < 0):
+        raise ValueError("`atol` must be positive.")
+
+    return rtol, atol
+
+
+def norm(x):
+    """Compute RMS norm."""
+    return np.linalg.norm(x) / x.size ** 0.5
+
+
+def select_initial_step(fun, t0, y0, t_bound,
+                        max_step, f0, direction, order, rtol, atol):
+    """Empirically select a good initial step.
+
+    The algorithm is described in [1]_.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system.
+    t0 : float
+        Initial value of the independent variable.
+    y0 : ndarray, shape (n,)
+        Initial value of the dependent variable.
+    t_bound : float
+        End-point of integration interval; used to ensure that t0+step<=tbound
+        and that fun is only evaluated in the interval [t0,tbound]
+    max_step : float
+        Maximum allowable step size.
+    f0 : ndarray, shape (n,)
+        Initial value of the derivative, i.e., ``fun(t0, y0)``.
+    direction : float
+        Integration direction.
+    order : float
+        Error estimator order. It means that the error controlled by the
+        algorithm is proportional to ``step_size ** (order + 1)`.
+    rtol : float
+        Desired relative tolerance.
+    atol : float
+        Desired absolute tolerance.
+
+    Returns
+    -------
+    h_abs : float
+        Absolute value of the suggested initial step.
+
+    References
+    ----------
+    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+           Equations I: Nonstiff Problems", Sec. II.4.
+    """
+    if y0.size == 0:
+        return np.inf
+
+    interval_length = abs(t_bound - t0)
+    if interval_length == 0.0:
+        return 0.0
+
+    scale = atol + np.abs(y0) * rtol
+    d0 = norm(y0 / scale)
+    d1 = norm(f0 / scale)
+    if d0 < 1e-5 or d1 < 1e-5:
+        h0 = 1e-6
+    else:
+        h0 = 0.01 * d0 / d1
+    # Check t0+h0*direction doesn't take us beyond t_bound
+    h0 = min(h0, interval_length)
+    y1 = y0 + h0 * direction * f0
+    f1 = fun(t0 + h0 * direction, y1)
+    d2 = norm((f1 - f0) / scale) / h0
+
+    if d1 <= 1e-15 and d2 <= 1e-15:
+        h1 = max(1e-6, h0 * 1e-3)
+    else:
+        h1 = (0.01 / max(d1, d2)) ** (1 / (order + 1))
+
+    return min(100 * h0, h1, interval_length, max_step)
+
+
+class OdeSolution:
+    """Continuous ODE solution.
+
+    It is organized as a collection of `DenseOutput` objects which represent
+    local interpolants. It provides an algorithm to select a right interpolant
+    for each given point.
+
+    The interpolants cover the range between `t_min` and `t_max` (see
+    Attributes below). Evaluation outside this interval is not forbidden, but
+    the accuracy is not guaranteed.
+
+    When evaluating at a breakpoint (one of the values in `ts`) a segment with
+    the lower index is selected.
+
+    Parameters
+    ----------
+    ts : array_like, shape (n_segments + 1,)
+        Time instants between which local interpolants are defined. Must
+        be strictly increasing or decreasing (zero segment with two points is
+        also allowed).
+    interpolants : list of DenseOutput with n_segments elements
+        Local interpolants. An i-th interpolant is assumed to be defined
+        between ``ts[i]`` and ``ts[i + 1]``.
+    alt_segment : boolean
+        Requests the alternative interpolant segment selection scheme. At each
+        solver integration point, two interpolant segments are available. The
+        default (False) and alternative (True) behaviours select the segment
+        for which the requested time corresponded to ``t`` and ``t_old``,
+        respectively. This functionality is only relevant for testing the
+        interpolants' accuracy: different integrators use different
+        construction strategies.
+
+    Attributes
+    ----------
+    t_min, t_max : float
+        Time range of the interpolation.
+    """
+    def __init__(self, ts, interpolants, alt_segment=False):
+        ts = np.asarray(ts)
+        d = np.diff(ts)
+        # The first case covers integration on zero segment.
+        if not ((ts.size == 2 and ts[0] == ts[-1])
+                or np.all(d > 0) or np.all(d < 0)):
+            raise ValueError("`ts` must be strictly increasing or decreasing.")
+
+        self.n_segments = len(interpolants)
+        if ts.shape != (self.n_segments + 1,):
+            raise ValueError("Numbers of time stamps and interpolants "
+                             "don't match.")
+
+        self.ts = ts
+        self.interpolants = interpolants
+        if ts[-1] >= ts[0]:
+            self.t_min = ts[0]
+            self.t_max = ts[-1]
+            self.ascending = True
+            self.side = "right" if alt_segment else "left"
+            self.ts_sorted = ts
+        else:
+            self.t_min = ts[-1]
+            self.t_max = ts[0]
+            self.ascending = False
+            self.side = "left" if alt_segment else "right"
+            self.ts_sorted = ts[::-1]
+
+    def _call_single(self, t):
+        # Here we preserve a certain symmetry that when t is in self.ts,
+        # if alt_segment=False, then we prioritize a segment with a lower
+        # index.
+        ind = np.searchsorted(self.ts_sorted, t, side=self.side)
+
+        segment = min(max(ind - 1, 0), self.n_segments - 1)
+        if not self.ascending:
+            segment = self.n_segments - 1 - segment
+
+        return self.interpolants[segment](t)
+
+    def __call__(self, t):
+        """Evaluate the solution.
+
+        Parameters
+        ----------
+        t : float or array_like with shape (n_points,)
+            Points to evaluate at.
+
+        Returns
+        -------
+        y : ndarray, shape (n_states,) or (n_states, n_points)
+            Computed values. Shape depends on whether `t` is a scalar or a
+            1-D array.
+        """
+        t = np.asarray(t)
+
+        if t.ndim == 0:
+            return self._call_single(t)
+
+        order = np.argsort(t)
+        reverse = np.empty_like(order)
+        reverse[order] = np.arange(order.shape[0])
+        t_sorted = t[order]
+
+        # See comment in self._call_single.
+        segments = np.searchsorted(self.ts_sorted, t_sorted, side=self.side)
+        segments -= 1
+        segments[segments < 0] = 0
+        segments[segments > self.n_segments - 1] = self.n_segments - 1
+        if not self.ascending:
+            segments = self.n_segments - 1 - segments
+
+        ys = []
+        group_start = 0
+        for segment, group in groupby(segments):
+            group_end = group_start + len(list(group))
+            y = self.interpolants[segment](t_sorted[group_start:group_end])
+            ys.append(y)
+            group_start = group_end
+
+        ys = np.hstack(ys)
+        ys = ys[:, reverse]
+
+        return ys
+
+
+NUM_JAC_DIFF_REJECT = EPS ** 0.875
+NUM_JAC_DIFF_SMALL = EPS ** 0.75
+NUM_JAC_DIFF_BIG = EPS ** 0.25
+NUM_JAC_MIN_FACTOR = 1e3 * EPS
+NUM_JAC_FACTOR_INCREASE = 10
+NUM_JAC_FACTOR_DECREASE = 0.1
+
+
+def num_jac(fun, t, y, f, threshold, factor, sparsity=None):
+    """Finite differences Jacobian approximation tailored for ODE solvers.
+
+    This function computes finite difference approximation to the Jacobian
+    matrix of `fun` with respect to `y` using forward differences.
+    The Jacobian matrix has shape (n, n) and its element (i, j) is equal to
+    ``d f_i / d y_j``.
+
+    A special feature of this function is the ability to correct the step
+    size from iteration to iteration. The main idea is to keep the finite
+    difference significantly separated from its round-off error which
+    approximately equals ``EPS * np.abs(f)``. It reduces a possibility of a
+    huge error and assures that the estimated derivative are reasonably close
+    to the true values (i.e., the finite difference approximation is at least
+    qualitatively reflects the structure of the true Jacobian).
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system implemented in a vectorized fashion.
+    t : float
+        Current time.
+    y : ndarray, shape (n,)
+        Current state.
+    f : ndarray, shape (n,)
+        Value of the right hand side at (t, y).
+    threshold : float
+        Threshold for `y` value used for computing the step size as
+        ``factor * np.maximum(np.abs(y), threshold)``. Typically, the value of
+        absolute tolerance (atol) for a solver should be passed as `threshold`.
+    factor : ndarray with shape (n,) or None
+        Factor to use for computing the step size. Pass None for the very
+        evaluation, then use the value returned from this function.
+    sparsity : tuple (structure, groups) or None
+        Sparsity structure of the Jacobian, `structure` must be csc_matrix.
+
+    Returns
+    -------
+    J : ndarray or csc_matrix, shape (n, n)
+        Jacobian matrix.
+    factor : ndarray, shape (n,)
+        Suggested `factor` for the next evaluation.
+    """
+    y = np.asarray(y)
+    n = y.shape[0]
+    if n == 0:
+        return np.empty((0, 0)), factor
+
+    if factor is None:
+        factor = np.full(n, EPS ** 0.5)
+    else:
+        factor = factor.copy()
+
+    # Direct the step as ODE dictates, hoping that such a step won't lead to
+    # a problematic region. For complex ODEs it makes sense to use the real
+    # part of f as we use steps along real axis.
+    f_sign = 2 * (np.real(f) >= 0).astype(float) - 1
+    y_scale = f_sign * np.maximum(threshold, np.abs(y))
+    h = (y + factor * y_scale) - y
+
+    # Make sure that the step is not 0 to start with. Not likely it will be
+    # executed often.
+    for i in np.nonzero(h == 0)[0]:
+        while h[i] == 0:
+            factor[i] *= 10
+            h[i] = (y[i] + factor[i] * y_scale[i]) - y[i]
+
+    if sparsity is None:
+        return _dense_num_jac(fun, t, y, f, h, factor, y_scale)
+    else:
+        structure, groups = sparsity
+        return _sparse_num_jac(fun, t, y, f, h, factor, y_scale,
+                               structure, groups)
+
+
+def _dense_num_jac(fun, t, y, f, h, factor, y_scale):
+    n = y.shape[0]
+    h_vecs = np.diag(h)
+    f_new = fun(t, y[:, None] + h_vecs)
+    diff = f_new - f[:, None]
+    max_ind = np.argmax(np.abs(diff), axis=0)
+    r = np.arange(n)
+    max_diff = np.abs(diff[max_ind, r])
+    scale = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
+
+    diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
+    if np.any(diff_too_small):
+        ind, = np.nonzero(diff_too_small)
+        new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
+        h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
+        h_vecs[ind, ind] = h_new
+        f_new = fun(t, y[:, None] + h_vecs[:, ind])
+        diff_new = f_new - f[:, None]
+        max_ind = np.argmax(np.abs(diff_new), axis=0)
+        r = np.arange(ind.shape[0])
+        max_diff_new = np.abs(diff_new[max_ind, r])
+        scale_new = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
+
+        update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
+        if np.any(update):
+            update, = np.nonzero(update)
+            update_ind = ind[update]
+            factor[update_ind] = new_factor[update]
+            h[update_ind] = h_new[update]
+            diff[:, update_ind] = diff_new[:, update]
+            scale[update_ind] = scale_new[update]
+            max_diff[update_ind] = max_diff_new[update]
+
+    diff /= h
+
+    factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
+    factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
+    factor = np.maximum(factor, NUM_JAC_MIN_FACTOR)
+
+    return diff, factor
+
+
+def _sparse_num_jac(fun, t, y, f, h, factor, y_scale, structure, groups):
+    n = y.shape[0]
+    n_groups = np.max(groups) + 1
+    h_vecs = np.empty((n_groups, n))
+    for group in range(n_groups):
+        e = np.equal(group, groups)
+        h_vecs[group] = h * e
+    h_vecs = h_vecs.T
+
+    f_new = fun(t, y[:, None] + h_vecs)
+    df = f_new - f[:, None]
+
+    i, j, _ = find(structure)
+    diff = coo_matrix((df[i, groups[j]], (i, j)), shape=(n, n)).tocsc()
+    max_ind = np.array(abs(diff).argmax(axis=0)).ravel()
+    r = np.arange(n)
+    max_diff = np.asarray(np.abs(diff[max_ind, r])).ravel()
+    scale = np.maximum(np.abs(f[max_ind]),
+                       np.abs(f_new[max_ind, groups[r]]))
+
+    diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
+    if np.any(diff_too_small):
+        ind, = np.nonzero(diff_too_small)
+        new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
+        h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
+        h_new_all = np.zeros(n)
+        h_new_all[ind] = h_new
+
+        groups_unique = np.unique(groups[ind])
+        groups_map = np.empty(n_groups, dtype=int)
+        h_vecs = np.empty((groups_unique.shape[0], n))
+        for k, group in enumerate(groups_unique):
+            e = np.equal(group, groups)
+            h_vecs[k] = h_new_all * e
+            groups_map[group] = k
+        h_vecs = h_vecs.T
+
+        f_new = fun(t, y[:, None] + h_vecs)
+        df = f_new - f[:, None]
+        i, j, _ = find(structure[:, ind])
+        diff_new = coo_matrix((df[i, groups_map[groups[ind[j]]]],
+                               (i, j)), shape=(n, ind.shape[0])).tocsc()
+
+        max_ind_new = np.array(abs(diff_new).argmax(axis=0)).ravel()
+        r = np.arange(ind.shape[0])
+        max_diff_new = np.asarray(np.abs(diff_new[max_ind_new, r])).ravel()
+        scale_new = np.maximum(
+            np.abs(f[max_ind_new]),
+            np.abs(f_new[max_ind_new, groups_map[groups[ind]]]))
+
+        update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
+        if np.any(update):
+            update, = np.nonzero(update)
+            update_ind = ind[update]
+            factor[update_ind] = new_factor[update]
+            h[update_ind] = h_new[update]
+            diff[:, update_ind] = diff_new[:, update]
+            scale[update_ind] = scale_new[update]
+            max_diff[update_ind] = max_diff_new[update]
+
+    diff.data /= np.repeat(h, np.diff(diff.indptr))
+
+    factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
+    factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
+    factor = np.maximum(factor, NUM_JAC_MIN_FACTOR)
+
+    return diff, factor
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py
new file mode 100644
index 0000000000000000000000000000000000000000..f39f2f3650d321e2c475d4e220f9769139118a5e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py
@@ -0,0 +1,193 @@
+import numpy as np
+
+N_STAGES = 12
+N_STAGES_EXTENDED = 16
+INTERPOLATOR_POWER = 7
+
+C = np.array([0.0,
+              0.526001519587677318785587544488e-01,
+              0.789002279381515978178381316732e-01,
+              0.118350341907227396726757197510,
+              0.281649658092772603273242802490,
+              0.333333333333333333333333333333,
+              0.25,
+              0.307692307692307692307692307692,
+              0.651282051282051282051282051282,
+              0.6,
+              0.857142857142857142857142857142,
+              1.0,
+              1.0,
+              0.1,
+              0.2,
+              0.777777777777777777777777777778])
+
+A = np.zeros((N_STAGES_EXTENDED, N_STAGES_EXTENDED))
+A[1, 0] = 5.26001519587677318785587544488e-2
+
+A[2, 0] = 1.97250569845378994544595329183e-2
+A[2, 1] = 5.91751709536136983633785987549e-2
+
+A[3, 0] = 2.95875854768068491816892993775e-2
+A[3, 2] = 8.87627564304205475450678981324e-2
+
+A[4, 0] = 2.41365134159266685502369798665e-1
+A[4, 2] = -8.84549479328286085344864962717e-1
+A[4, 3] = 9.24834003261792003115737966543e-1
+
+A[5, 0] = 3.7037037037037037037037037037e-2
+A[5, 3] = 1.70828608729473871279604482173e-1
+A[5, 4] = 1.25467687566822425016691814123e-1
+
+A[6, 0] = 3.7109375e-2
+A[6, 3] = 1.70252211019544039314978060272e-1
+A[6, 4] = 6.02165389804559606850219397283e-2
+A[6, 5] = -1.7578125e-2
+
+A[7, 0] = 3.70920001185047927108779319836e-2
+A[7, 3] = 1.70383925712239993810214054705e-1
+A[7, 4] = 1.07262030446373284651809199168e-1
+A[7, 5] = -1.53194377486244017527936158236e-2
+A[7, 6] = 8.27378916381402288758473766002e-3
+
+A[8, 0] = 6.24110958716075717114429577812e-1
+A[8, 3] = -3.36089262944694129406857109825
+A[8, 4] = -8.68219346841726006818189891453e-1
+A[8, 5] = 2.75920996994467083049415600797e1
+A[8, 6] = 2.01540675504778934086186788979e1
+A[8, 7] = -4.34898841810699588477366255144e1
+
+A[9, 0] = 4.77662536438264365890433908527e-1
+A[9, 3] = -2.48811461997166764192642586468
+A[9, 4] = -5.90290826836842996371446475743e-1
+A[9, 5] = 2.12300514481811942347288949897e1
+A[9, 6] = 1.52792336328824235832596922938e1
+A[9, 7] = -3.32882109689848629194453265587e1
+A[9, 8] = -2.03312017085086261358222928593e-2
+
+A[10, 0] = -9.3714243008598732571704021658e-1
+A[10, 3] = 5.18637242884406370830023853209
+A[10, 4] = 1.09143734899672957818500254654
+A[10, 5] = -8.14978701074692612513997267357
+A[10, 6] = -1.85200656599969598641566180701e1
+A[10, 7] = 2.27394870993505042818970056734e1
+A[10, 8] = 2.49360555267965238987089396762
+A[10, 9] = -3.0467644718982195003823669022
+
+A[11, 0] = 2.27331014751653820792359768449
+A[11, 3] = -1.05344954667372501984066689879e1
+A[11, 4] = -2.00087205822486249909675718444
+A[11, 5] = -1.79589318631187989172765950534e1
+A[11, 6] = 2.79488845294199600508499808837e1
+A[11, 7] = -2.85899827713502369474065508674
+A[11, 8] = -8.87285693353062954433549289258
+A[11, 9] = 1.23605671757943030647266201528e1
+A[11, 10] = 6.43392746015763530355970484046e-1
+
+A[12, 0] = 5.42937341165687622380535766363e-2
+A[12, 5] = 4.45031289275240888144113950566
+A[12, 6] = 1.89151789931450038304281599044
+A[12, 7] = -5.8012039600105847814672114227
+A[12, 8] = 3.1116436695781989440891606237e-1
+A[12, 9] = -1.52160949662516078556178806805e-1
+A[12, 10] = 2.01365400804030348374776537501e-1
+A[12, 11] = 4.47106157277725905176885569043e-2
+
+A[13, 0] = 5.61675022830479523392909219681e-2
+A[13, 6] = 2.53500210216624811088794765333e-1
+A[13, 7] = -2.46239037470802489917441475441e-1
+A[13, 8] = -1.24191423263816360469010140626e-1
+A[13, 9] = 1.5329179827876569731206322685e-1
+A[13, 10] = 8.20105229563468988491666602057e-3
+A[13, 11] = 7.56789766054569976138603589584e-3
+A[13, 12] = -8.298e-3
+
+A[14, 0] = 3.18346481635021405060768473261e-2
+A[14, 5] = 2.83009096723667755288322961402e-2
+A[14, 6] = 5.35419883074385676223797384372e-2
+A[14, 7] = -5.49237485713909884646569340306e-2
+A[14, 10] = -1.08347328697249322858509316994e-4
+A[14, 11] = 3.82571090835658412954920192323e-4
+A[14, 12] = -3.40465008687404560802977114492e-4
+A[14, 13] = 1.41312443674632500278074618366e-1
+
+A[15, 0] = -4.28896301583791923408573538692e-1
+A[15, 5] = -4.69762141536116384314449447206
+A[15, 6] = 7.68342119606259904184240953878
+A[15, 7] = 4.06898981839711007970213554331
+A[15, 8] = 3.56727187455281109270669543021e-1
+A[15, 12] = -1.39902416515901462129418009734e-3
+A[15, 13] = 2.9475147891527723389556272149
+A[15, 14] = -9.15095847217987001081870187138
+
+
+B = A[N_STAGES, :N_STAGES]
+
+E3 = np.zeros(N_STAGES + 1)
+E3[:-1] = B.copy()
+E3[0] -= 0.244094488188976377952755905512
+E3[8] -= 0.733846688281611857341361741547
+E3[11] -= 0.220588235294117647058823529412e-1
+
+E5 = np.zeros(N_STAGES + 1)
+E5[0] = 0.1312004499419488073250102996e-1
+E5[5] = -0.1225156446376204440720569753e+1
+E5[6] = -0.4957589496572501915214079952
+E5[7] = 0.1664377182454986536961530415e+1
+E5[8] = -0.3503288487499736816886487290
+E5[9] = 0.3341791187130174790297318841
+E5[10] = 0.8192320648511571246570742613e-1
+E5[11] = -0.2235530786388629525884427845e-1
+
+# First 3 coefficients are computed separately.
+D = np.zeros((INTERPOLATOR_POWER - 3, N_STAGES_EXTENDED))
+D[0, 0] = -0.84289382761090128651353491142e+1
+D[0, 5] = 0.56671495351937776962531783590
+D[0, 6] = -0.30689499459498916912797304727e+1
+D[0, 7] = 0.23846676565120698287728149680e+1
+D[0, 8] = 0.21170345824450282767155149946e+1
+D[0, 9] = -0.87139158377797299206789907490
+D[0, 10] = 0.22404374302607882758541771650e+1
+D[0, 11] = 0.63157877876946881815570249290
+D[0, 12] = -0.88990336451333310820698117400e-1
+D[0, 13] = 0.18148505520854727256656404962e+2
+D[0, 14] = -0.91946323924783554000451984436e+1
+D[0, 15] = -0.44360363875948939664310572000e+1
+
+D[1, 0] = 0.10427508642579134603413151009e+2
+D[1, 5] = 0.24228349177525818288430175319e+3
+D[1, 6] = 0.16520045171727028198505394887e+3
+D[1, 7] = -0.37454675472269020279518312152e+3
+D[1, 8] = -0.22113666853125306036270938578e+2
+D[1, 9] = 0.77334326684722638389603898808e+1
+D[1, 10] = -0.30674084731089398182061213626e+2
+D[1, 11] = -0.93321305264302278729567221706e+1
+D[1, 12] = 0.15697238121770843886131091075e+2
+D[1, 13] = -0.31139403219565177677282850411e+2
+D[1, 14] = -0.93529243588444783865713862664e+1
+D[1, 15] = 0.35816841486394083752465898540e+2
+
+D[2, 0] = 0.19985053242002433820987653617e+2
+D[2, 5] = -0.38703730874935176555105901742e+3
+D[2, 6] = -0.18917813819516756882830838328e+3
+D[2, 7] = 0.52780815920542364900561016686e+3
+D[2, 8] = -0.11573902539959630126141871134e+2
+D[2, 9] = 0.68812326946963000169666922661e+1
+D[2, 10] = -0.10006050966910838403183860980e+1
+D[2, 11] = 0.77771377980534432092869265740
+D[2, 12] = -0.27782057523535084065932004339e+1
+D[2, 13] = -0.60196695231264120758267380846e+2
+D[2, 14] = 0.84320405506677161018159903784e+2
+D[2, 15] = 0.11992291136182789328035130030e+2
+
+D[3, 0] = -0.25693933462703749003312586129e+2
+D[3, 5] = -0.15418974869023643374053993627e+3
+D[3, 6] = -0.23152937917604549567536039109e+3
+D[3, 7] = 0.35763911791061412378285349910e+3
+D[3, 8] = 0.93405324183624310003907691704e+2
+D[3, 9] = -0.37458323136451633156875139351e+2
+D[3, 10] = 0.10409964950896230045147246184e+3
+D[3, 11] = 0.29840293426660503123344363579e+2
+D[3, 12] = -0.43533456590011143754432175058e+2
+D[3, 13] = 0.96324553959188282948394950600e+2
+D[3, 14] = -0.39177261675615439165231486172e+2
+D[3, 15] = -0.14972683625798562581422125276e+3
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py
new file mode 100644
index 0000000000000000000000000000000000000000..8186982e4fddbd8c1058b59c745ca66ab3a9c224
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py
@@ -0,0 +1,755 @@
+import inspect
+import numpy as np
+from .bdf import BDF
+from .radau import Radau
+from .rk import RK23, RK45, DOP853
+from .lsoda import LSODA
+from scipy.optimize import OptimizeResult
+from .common import EPS, OdeSolution
+from .base import OdeSolver
+
+
+METHODS = {'RK23': RK23,
+           'RK45': RK45,
+           'DOP853': DOP853,
+           'Radau': Radau,
+           'BDF': BDF,
+           'LSODA': LSODA}
+
+
+MESSAGES = {0: "The solver successfully reached the end of the integration interval.",
+            1: "A termination event occurred."}
+
+
+class OdeResult(OptimizeResult):
+    pass
+
+
+def prepare_events(events):
+    """Standardize event functions and extract attributes."""
+    if callable(events):
+        events = (events,)
+
+    max_events = np.empty(len(events))
+    direction = np.empty(len(events))
+    for i, event in enumerate(events):
+        terminal = getattr(event, 'terminal', None)
+        direction[i] = getattr(event, 'direction', 0)
+
+        message = ('The `terminal` attribute of each event '
+                   'must be a boolean or positive integer.')
+        if terminal is None or terminal == 0:
+            max_events[i] = np.inf
+        elif int(terminal) == terminal and terminal > 0:
+            max_events[i] = terminal
+        else:
+            raise ValueError(message)
+
+    return events, max_events, direction
+
+
+def solve_event_equation(event, sol, t_old, t):
+    """Solve an equation corresponding to an ODE event.
+
+    The equation is ``event(t, y(t)) = 0``, here ``y(t)`` is known from an
+    ODE solver using some sort of interpolation. It is solved by
+    `scipy.optimize.brentq` with xtol=atol=4*EPS.
+
+    Parameters
+    ----------
+    event : callable
+        Function ``event(t, y)``.
+    sol : callable
+        Function ``sol(t)`` which evaluates an ODE solution between `t_old`
+        and  `t`.
+    t_old, t : float
+        Previous and new values of time. They will be used as a bracketing
+        interval.
+
+    Returns
+    -------
+    root : float
+        Found solution.
+    """
+    from scipy.optimize import brentq
+    return brentq(lambda t: event(t, sol(t)), t_old, t,
+                  xtol=4 * EPS, rtol=4 * EPS)
+
+
+def handle_events(sol, events, active_events, event_count, max_events,
+                  t_old, t):
+    """Helper function to handle events.
+
+    Parameters
+    ----------
+    sol : DenseOutput
+        Function ``sol(t)`` which evaluates an ODE solution between `t_old`
+        and  `t`.
+    events : list of callables, length n_events
+        Event functions with signatures ``event(t, y)``.
+    active_events : ndarray
+        Indices of events which occurred.
+    event_count : ndarray
+        Current number of occurrences for each event.
+    max_events : ndarray, shape (n_events,)
+        Number of occurrences allowed for each event before integration
+        termination is issued.
+    t_old, t : float
+        Previous and new values of time.
+
+    Returns
+    -------
+    root_indices : ndarray
+        Indices of events which take zero between `t_old` and `t` and before
+        a possible termination.
+    roots : ndarray
+        Values of t at which events occurred.
+    terminate : bool
+        Whether a terminal event occurred.
+    """
+    roots = [solve_event_equation(events[event_index], sol, t_old, t)
+             for event_index in active_events]
+
+    roots = np.asarray(roots)
+
+    if np.any(event_count[active_events] >= max_events[active_events]):
+        if t > t_old:
+            order = np.argsort(roots)
+        else:
+            order = np.argsort(-roots)
+        active_events = active_events[order]
+        roots = roots[order]
+        t = np.nonzero(event_count[active_events]
+                       >= max_events[active_events])[0][0]
+        active_events = active_events[:t + 1]
+        roots = roots[:t + 1]
+        terminate = True
+    else:
+        terminate = False
+
+    return active_events, roots, terminate
+
+
+def find_active_events(g, g_new, direction):
+    """Find which event occurred during an integration step.
+
+    Parameters
+    ----------
+    g, g_new : array_like, shape (n_events,)
+        Values of event functions at a current and next points.
+    direction : ndarray, shape (n_events,)
+        Event "direction" according to the definition in `solve_ivp`.
+
+    Returns
+    -------
+    active_events : ndarray
+        Indices of events which occurred during the step.
+    """
+    g, g_new = np.asarray(g), np.asarray(g_new)
+    up = (g <= 0) & (g_new >= 0)
+    down = (g >= 0) & (g_new <= 0)
+    either = up | down
+    mask = (up & (direction > 0) |
+            down & (direction < 0) |
+            either & (direction == 0))
+
+    return np.nonzero(mask)[0]
+
+
+def solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False,
+              events=None, vectorized=False, args=None, **options):
+    """Solve an initial value problem for a system of ODEs.
+
+    This function numerically integrates a system of ordinary differential
+    equations given an initial value::
+
+        dy / dt = f(t, y)
+        y(t0) = y0
+
+    Here t is a 1-D independent variable (time), y(t) is an
+    N-D vector-valued function (state), and an N-D
+    vector-valued function f(t, y) determines the differential equations.
+    The goal is to find y(t) approximately satisfying the differential
+    equations, given an initial value y(t0)=y0.
+
+    Some of the solvers support integration in the complex domain, but note
+    that for stiff ODE solvers, the right-hand side must be
+    complex-differentiable (satisfy Cauchy-Riemann equations [11]_).
+    To solve a problem in the complex domain, pass y0 with a complex data type.
+    Another option always available is to rewrite your problem for real and
+    imaginary parts separately.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. Additional
+        arguments need to be passed if ``args`` is used (see documentation of
+        ``args`` argument). ``fun`` must return an array of the same shape as
+        ``y``. See `vectorized` for more information.
+    t_span : 2-member sequence
+        Interval of integration (t0, tf). The solver starts with t=t0 and
+        integrates until it reaches t=tf. Both t0 and tf must be floats
+        or values interpretable by the float conversion function.
+    y0 : array_like, shape (n,)
+        Initial state. For problems in the complex domain, pass `y0` with a
+        complex data type (even if the initial value is purely real).
+    method : string or `OdeSolver`, optional
+        Integration method to use:
+
+            * 'RK45' (default): Explicit Runge-Kutta method of order 5(4) [1]_.
+              The error is controlled assuming accuracy of the fourth-order
+              method, but steps are taken using the fifth-order accurate
+              formula (local extrapolation is done). A quartic interpolation
+              polynomial is used for the dense output [2]_. Can be applied in
+              the complex domain.
+            * 'RK23': Explicit Runge-Kutta method of order 3(2) [3]_. The error
+              is controlled assuming accuracy of the second-order method, but
+              steps are taken using the third-order accurate formula (local
+              extrapolation is done). A cubic Hermite polynomial is used for the
+              dense output. Can be applied in the complex domain.
+            * 'DOP853': Explicit Runge-Kutta method of order 8 [13]_.
+              Python implementation of the "DOP853" algorithm originally
+              written in Fortran [14]_. A 7-th order interpolation polynomial
+              accurate to 7-th order is used for the dense output.
+              Can be applied in the complex domain.
+            * 'Radau': Implicit Runge-Kutta method of the Radau IIA family of
+              order 5 [4]_. The error is controlled with a third-order accurate
+              embedded formula. A cubic polynomial which satisfies the
+              collocation conditions is used for the dense output.
+            * 'BDF': Implicit multi-step variable-order (1 to 5) method based
+              on a backward differentiation formula for the derivative
+              approximation [5]_. The implementation follows the one described
+              in [6]_. A quasi-constant step scheme is used and accuracy is
+              enhanced using the NDF modification. Can be applied in the
+              complex domain.
+            * 'LSODA': Adams/BDF method with automatic stiffness detection and
+              switching [7]_, [8]_. This is a wrapper of the Fortran solver
+              from ODEPACK.
+
+        Explicit Runge-Kutta methods ('RK23', 'RK45', 'DOP853') should be used
+        for non-stiff problems and implicit methods ('Radau', 'BDF') for
+        stiff problems [9]_. Among Runge-Kutta methods, 'DOP853' is recommended
+        for solving with high precision (low values of `rtol` and `atol`).
+
+        If not sure, first try to run 'RK45'. If it makes unusually many
+        iterations, diverges, or fails, your problem is likely to be stiff and
+        you should use 'Radau' or 'BDF'. 'LSODA' can also be a good universal
+        choice, but it might be somewhat less convenient to work with as it
+        wraps old Fortran code.
+
+        You can also pass an arbitrary class derived from `OdeSolver` which
+        implements the solver.
+    t_eval : array_like or None, optional
+        Times at which to store the computed solution, must be sorted and lie
+        within `t_span`. If None (default), use points selected by the solver.
+    dense_output : bool, optional
+        Whether to compute a continuous solution. Default is False.
+    events : callable, or list of callables, optional
+        Events to track. If None (default), no events will be tracked.
+        Each event occurs at the zeros of a continuous function of time and
+        state. Each function must have the signature ``event(t, y)`` where
+        additional argument have to be passed if ``args`` is used (see
+        documentation of ``args`` argument). Each function must return a
+        float. The solver will find an accurate value of `t` at which
+        ``event(t, y(t)) = 0`` using a root-finding algorithm. By default,
+        all zeros will be found. The solver looks for a sign change over
+        each step, so if multiple zero crossings occur within one step,
+        events may be missed. Additionally each `event` function might
+        have the following attributes:
+
+            terminal: bool or int, optional
+                When boolean, whether to terminate integration if this event occurs.
+                When integral, termination occurs after the specified the number of
+                occurrences of this event.
+                Implicitly False if not assigned.
+            direction: float, optional
+                Direction of a zero crossing. If `direction` is positive,
+                `event` will only trigger when going from negative to positive,
+                and vice versa if `direction` is negative. If 0, then either
+                direction will trigger event. Implicitly 0 if not assigned.
+
+        You can assign attributes like ``event.terminal = True`` to any
+        function in Python.
+    vectorized : bool, optional
+        Whether `fun` can be called in a vectorized fashion. Default is False.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by methods 'Radau' and 'BDF', but
+        will result in slower execution for other methods and for 'Radau' and
+        'BDF' in some circumstances (e.g. small ``len(y0)``).
+    args : tuple, optional
+        Additional arguments to pass to the user-defined functions.  If given,
+        the additional arguments are passed to all user-defined functions.
+        So if, for example, `fun` has the signature ``fun(t, y, a, b, c)``,
+        then `jac` (if given) and any event functions must have the same
+        signature, and `args` must be a tuple of length 3.
+    **options
+        Options passed to a chosen solver. All options available for already
+        implemented solvers are listed below.
+    first_step : float or None, optional
+        Initial step size. Default is `None` which means that the algorithm
+        should choose.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float or array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    jac : array_like, sparse_matrix, callable or None, optional
+        Jacobian matrix of the right-hand side of the system with respect
+        to y, required by the 'Radau', 'BDF' and 'LSODA' method. The
+        Jacobian matrix has shape (n, n) and its element (i, j) is equal to
+        ``d f_i / d y_j``.  There are three ways to define the Jacobian:
+
+            * If array_like or sparse_matrix, the Jacobian is assumed to
+              be constant. Not supported by 'LSODA'.
+            * If callable, the Jacobian is assumed to depend on both
+              t and y; it will be called as ``jac(t, y)``, as necessary.
+              Additional arguments have to be passed if ``args`` is
+              used (see documentation of ``args`` argument).
+              For 'Radau' and 'BDF' methods, the return value might be a
+              sparse matrix.
+            * If None (default), the Jacobian will be approximated by
+              finite differences.
+
+        It is generally recommended to provide the Jacobian rather than
+        relying on a finite-difference approximation.
+    jac_sparsity : array_like, sparse matrix or None, optional
+        Defines a sparsity structure of the Jacobian matrix for a finite-
+        difference approximation. Its shape must be (n, n). This argument
+        is ignored if `jac` is not `None`. If the Jacobian has only few
+        non-zero elements in *each* row, providing the sparsity structure
+        will greatly speed up the computations [10]_. A zero entry means that
+        a corresponding element in the Jacobian is always zero. If None
+        (default), the Jacobian is assumed to be dense.
+        Not supported by 'LSODA', see `lband` and `uband` instead.
+    lband, uband : int or None, optional
+        Parameters defining the bandwidth of the Jacobian for the 'LSODA'
+        method, i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``.
+        Default is None. Setting these requires your jac routine to return the
+        Jacobian in the packed format: the returned array must have ``n``
+        columns and ``uband + lband + 1`` rows in which Jacobian diagonals are
+        written. Specifically ``jac_packed[uband + i - j , j] = jac[i, j]``.
+        The same format is used in `scipy.linalg.solve_banded` (check for an
+        illustration).  These parameters can be also used with ``jac=None`` to
+        reduce the number of Jacobian elements estimated by finite differences.
+    min_step : float, optional
+        The minimum allowed step size for 'LSODA' method.
+        By default `min_step` is zero.
+
+    Returns
+    -------
+    Bunch object with the following fields defined:
+    t : ndarray, shape (n_points,)
+        Time points.
+    y : ndarray, shape (n, n_points)
+        Values of the solution at `t`.
+    sol : `OdeSolution` or None
+        Found solution as `OdeSolution` instance; None if `dense_output` was
+        set to False.
+    t_events : list of ndarray or None
+        Contains for each event type a list of arrays at which an event of
+        that type event was detected. None if `events` was None.
+    y_events : list of ndarray or None
+        For each value of `t_events`, the corresponding value of the solution.
+        None if `events` was None.
+    nfev : int
+        Number of evaluations of the right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+    nlu : int
+        Number of LU decompositions.
+    status : int
+        Reason for algorithm termination:
+
+            * -1: Integration step failed.
+            *  0: The solver successfully reached the end of `tspan`.
+            *  1: A termination event occurred.
+
+    message : string
+        Human-readable description of the termination reason.
+    success : bool
+        True if the solver reached the interval end or a termination event
+        occurred (``status >= 0``).
+
+    References
+    ----------
+    .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
+           formulae", Journal of Computational and Applied Mathematics, Vol. 6,
+           No. 1, pp. 19-26, 1980.
+    .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
+           of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
+    .. [3] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
+           Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
+    .. [4] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
+           Stiff and Differential-Algebraic Problems", Sec. IV.8.
+    .. [5] `Backward Differentiation Formula
+            `_
+            on Wikipedia.
+    .. [6] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
+           COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
+    .. [7] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
+           Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
+           pp. 55-64, 1983.
+    .. [8] L. Petzold, "Automatic selection of methods for solving stiff and
+           nonstiff systems of ordinary differential equations", SIAM Journal
+           on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
+           1983.
+    .. [9] `Stiff equation `_ on
+           Wikipedia.
+    .. [10] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+            sparse Jacobian matrices", Journal of the Institute of Mathematics
+            and its Applications, 13, pp. 117-120, 1974.
+    .. [11] `Cauchy-Riemann equations
+             `_ on
+             Wikipedia.
+    .. [12] `Lotka-Volterra equations
+            `_
+            on Wikipedia.
+    .. [13] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+            Equations I: Nonstiff Problems", Sec. II.
+    .. [14] `Page with original Fortran code of DOP853
+            `_.
+
+    Examples
+    --------
+    Basic exponential decay showing automatically chosen time points.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import solve_ivp
+    >>> def exponential_decay(t, y): return -0.5 * y
+    >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8])
+    >>> print(sol.t)
+    [ 0.          0.11487653  1.26364188  3.06061781  4.81611105  6.57445806
+      8.33328988 10.        ]
+    >>> print(sol.y)
+    [[2.         1.88836035 1.06327177 0.43319312 0.18017253 0.07483045
+      0.03107158 0.01350781]
+     [4.         3.7767207  2.12654355 0.86638624 0.36034507 0.14966091
+      0.06214316 0.02701561]
+     [8.         7.5534414  4.25308709 1.73277247 0.72069014 0.29932181
+      0.12428631 0.05403123]]
+
+    Specifying points where the solution is desired.
+
+    >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8],
+    ...                 t_eval=[0, 1, 2, 4, 10])
+    >>> print(sol.t)
+    [ 0  1  2  4 10]
+    >>> print(sol.y)
+    [[2.         1.21305369 0.73534021 0.27066736 0.01350938]
+     [4.         2.42610739 1.47068043 0.54133472 0.02701876]
+     [8.         4.85221478 2.94136085 1.08266944 0.05403753]]
+
+    Cannon fired upward with terminal event upon impact. The ``terminal`` and
+    ``direction`` fields of an event are applied by monkey patching a function.
+    Here ``y[0]`` is position and ``y[1]`` is velocity. The projectile starts
+    at position 0 with velocity +10. Note that the integration never reaches
+    t=100 because the event is terminal.
+
+    >>> def upward_cannon(t, y): return [y[1], -0.5]
+    >>> def hit_ground(t, y): return y[0]
+    >>> hit_ground.terminal = True
+    >>> hit_ground.direction = -1
+    >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], events=hit_ground)
+    >>> print(sol.t_events)
+    [array([40.])]
+    >>> print(sol.t)
+    [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
+     1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
+
+    Use `dense_output` and `events` to find position, which is 100, at the apex
+    of the cannonball's trajectory. Apex is not defined as terminal, so both
+    apex and hit_ground are found. There is no information at t=20, so the sol
+    attribute is used to evaluate the solution. The sol attribute is returned
+    by setting ``dense_output=True``. Alternatively, the `y_events` attribute
+    can be used to access the solution at the time of the event.
+
+    >>> def apex(t, y): return y[1]
+    >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10],
+    ...                 events=(hit_ground, apex), dense_output=True)
+    >>> print(sol.t_events)
+    [array([40.]), array([20.])]
+    >>> print(sol.t)
+    [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
+     1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
+    >>> print(sol.sol(sol.t_events[1][0]))
+    [100.   0.]
+    >>> print(sol.y_events)
+    [array([[-5.68434189e-14, -1.00000000e+01]]),
+     array([[1.00000000e+02, 1.77635684e-15]])]
+
+    As an example of a system with additional parameters, we'll implement
+    the Lotka-Volterra equations [12]_.
+
+    >>> def lotkavolterra(t, z, a, b, c, d):
+    ...     x, y = z
+    ...     return [a*x - b*x*y, -c*y + d*x*y]
+    ...
+
+    We pass in the parameter values a=1.5, b=1, c=3 and d=1 with the `args`
+    argument.
+
+    >>> sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1),
+    ...                 dense_output=True)
+
+    Compute a dense solution and plot it.
+
+    >>> t = np.linspace(0, 15, 300)
+    >>> z = sol.sol(t)
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(t, z.T)
+    >>> plt.xlabel('t')
+    >>> plt.legend(['x', 'y'], shadow=True)
+    >>> plt.title('Lotka-Volterra System')
+    >>> plt.show()
+
+    A couple examples of using solve_ivp to solve the differential
+    equation ``y' = Ay`` with complex matrix ``A``.
+
+    >>> A = np.array([[-0.25 + 0.14j, 0, 0.33 + 0.44j],
+    ...               [0.25 + 0.58j, -0.2 + 0.14j, 0],
+    ...               [0, 0.2 + 0.4j, -0.1 + 0.97j]])
+
+    Solving an IVP with ``A`` from above and ``y`` as 3x1 vector:
+
+    >>> def deriv_vec(t, y):
+    ...     return A @ y
+    >>> result = solve_ivp(deriv_vec, [0, 25],
+    ...                    np.array([10 + 0j, 20 + 0j, 30 + 0j]),
+    ...                    t_eval=np.linspace(0, 25, 101))
+    >>> print(result.y[:, 0])
+    [10.+0.j 20.+0.j 30.+0.j]
+    >>> print(result.y[:, -1])
+    [18.46291039+45.25653651j 10.01569306+36.23293216j
+     -4.98662741+80.07360388j]
+
+    Solving an IVP with ``A`` from above with ``y`` as 3x3 matrix :
+
+    >>> def deriv_mat(t, y):
+    ...     return (A @ y.reshape(3, 3)).flatten()
+    >>> y0 = np.array([[2 + 0j, 3 + 0j, 4 + 0j],
+    ...                [5 + 0j, 6 + 0j, 7 + 0j],
+    ...                [9 + 0j, 34 + 0j, 78 + 0j]])
+
+    >>> result = solve_ivp(deriv_mat, [0, 25], y0.flatten(),
+    ...                    t_eval=np.linspace(0, 25, 101))
+    >>> print(result.y[:, 0].reshape(3, 3))
+    [[ 2.+0.j  3.+0.j  4.+0.j]
+     [ 5.+0.j  6.+0.j  7.+0.j]
+     [ 9.+0.j 34.+0.j 78.+0.j]]
+    >>> print(result.y[:, -1].reshape(3, 3))
+    [[  5.67451179 +12.07938445j  17.2888073  +31.03278837j
+        37.83405768 +63.25138759j]
+     [  3.39949503 +11.82123994j  21.32530996 +44.88668871j
+        53.17531184+103.80400411j]
+     [ -2.26105874 +22.19277664j -15.1255713  +70.19616341j
+       -38.34616845+153.29039931j]]
+
+
+    """
+    if method not in METHODS and not (
+            inspect.isclass(method) and issubclass(method, OdeSolver)):
+        raise ValueError(f"`method` must be one of {METHODS} or OdeSolver class.")
+
+    t0, tf = map(float, t_span)
+
+    if args is not None:
+        # Wrap the user's fun (and jac, if given) in lambdas to hide the
+        # additional parameters.  Pass in the original fun as a keyword
+        # argument to keep it in the scope of the lambda.
+        try:
+            _ = [*(args)]
+        except TypeError as exp:
+            suggestion_tuple = (
+                "Supplied 'args' cannot be unpacked. Please supply `args`"
+                f" as a tuple (e.g. `args=({args},)`)"
+            )
+            raise TypeError(suggestion_tuple) from exp
+
+        def fun(t, x, fun=fun):
+            return fun(t, x, *args)
+        jac = options.get('jac')
+        if callable(jac):
+            options['jac'] = lambda t, x: jac(t, x, *args)
+
+    if t_eval is not None:
+        t_eval = np.asarray(t_eval)
+        if t_eval.ndim != 1:
+            raise ValueError("`t_eval` must be 1-dimensional.")
+
+        if np.any(t_eval < min(t0, tf)) or np.any(t_eval > max(t0, tf)):
+            raise ValueError("Values in `t_eval` are not within `t_span`.")
+
+        d = np.diff(t_eval)
+        if tf > t0 and np.any(d <= 0) or tf < t0 and np.any(d >= 0):
+            raise ValueError("Values in `t_eval` are not properly sorted.")
+
+        if tf > t0:
+            t_eval_i = 0
+        else:
+            # Make order of t_eval decreasing to use np.searchsorted.
+            t_eval = t_eval[::-1]
+            # This will be an upper bound for slices.
+            t_eval_i = t_eval.shape[0]
+
+    if method in METHODS:
+        method = METHODS[method]
+
+    solver = method(fun, t0, y0, tf, vectorized=vectorized, **options)
+
+    if t_eval is None:
+        ts = [t0]
+        ys = [y0]
+    elif t_eval is not None and dense_output:
+        ts = []
+        ti = [t0]
+        ys = []
+    else:
+        ts = []
+        ys = []
+
+    interpolants = []
+
+    if events is not None:
+        events, max_events, event_dir = prepare_events(events)
+        event_count = np.zeros(len(events))
+        if args is not None:
+            # Wrap user functions in lambdas to hide the additional parameters.
+            # The original event function is passed as a keyword argument to the
+            # lambda to keep the original function in scope (i.e., avoid the
+            # late binding closure "gotcha").
+            events = [lambda t, x, event=event: event(t, x, *args)
+                      for event in events]
+        g = [event(t0, y0) for event in events]
+        t_events = [[] for _ in range(len(events))]
+        y_events = [[] for _ in range(len(events))]
+    else:
+        t_events = None
+        y_events = None
+
+    status = None
+    while status is None:
+        message = solver.step()
+
+        if solver.status == 'finished':
+            status = 0
+        elif solver.status == 'failed':
+            status = -1
+            break
+
+        t_old = solver.t_old
+        t = solver.t
+        y = solver.y
+
+        if dense_output:
+            sol = solver.dense_output()
+            interpolants.append(sol)
+        else:
+            sol = None
+
+        if events is not None:
+            g_new = [event(t, y) for event in events]
+            active_events = find_active_events(g, g_new, event_dir)
+            if active_events.size > 0:
+                if sol is None:
+                    sol = solver.dense_output()
+
+                event_count[active_events] += 1
+                root_indices, roots, terminate = handle_events(
+                    sol, events, active_events, event_count, max_events,
+                    t_old, t)
+
+                for e, te in zip(root_indices, roots):
+                    t_events[e].append(te)
+                    y_events[e].append(sol(te))
+
+                if terminate:
+                    status = 1
+                    t = roots[-1]
+                    y = sol(t)
+
+            g = g_new
+
+        if t_eval is None:
+            donot_append = (len(ts) > 1 and
+                            ts[-1] == t and
+                            dense_output)
+            if not donot_append:
+                ts.append(t)
+                ys.append(y)
+            else:
+                if len(interpolants) > 0:
+                    interpolants.pop()
+        else:
+            # The value in t_eval equal to t will be included.
+            if solver.direction > 0:
+                t_eval_i_new = np.searchsorted(t_eval, t, side='right')
+                t_eval_step = t_eval[t_eval_i:t_eval_i_new]
+            else:
+                t_eval_i_new = np.searchsorted(t_eval, t, side='left')
+                # It has to be done with two slice operations, because
+                # you can't slice to 0th element inclusive using backward
+                # slicing.
+                t_eval_step = t_eval[t_eval_i_new:t_eval_i][::-1]
+
+            if t_eval_step.size > 0:
+                if sol is None:
+                    sol = solver.dense_output()
+                ts.append(t_eval_step)
+                ys.append(sol(t_eval_step))
+                t_eval_i = t_eval_i_new
+
+        if t_eval is not None and dense_output:
+            ti.append(t)
+
+    message = MESSAGES.get(status, message)
+
+    if t_events is not None:
+        t_events = [np.asarray(te) for te in t_events]
+        y_events = [np.asarray(ye) for ye in y_events]
+
+    if t_eval is None:
+        ts = np.array(ts)
+        ys = np.vstack(ys).T
+    elif ts:
+        ts = np.hstack(ts)
+        ys = np.hstack(ys)
+
+    if dense_output:
+        if t_eval is None:
+            sol = OdeSolution(
+                ts, interpolants, alt_segment=True if method in [BDF, LSODA] else False
+            )
+        else:
+            sol = OdeSolution(
+                ti, interpolants, alt_segment=True if method in [BDF, LSODA] else False
+            )
+    else:
+        sol = None
+
+    return OdeResult(t=ts, y=ys, sol=sol, t_events=t_events, y_events=y_events,
+                     nfev=solver.nfev, njev=solver.njev, nlu=solver.nlu,
+                     status=status, message=message, success=status >= 0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a5a7c530c04eddc9beff44e2d4f6df439d5ef01
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py
@@ -0,0 +1,224 @@
+import numpy as np
+from scipy.integrate import ode
+from .common import validate_tol, validate_first_step, warn_extraneous
+from .base import OdeSolver, DenseOutput
+
+
+class LSODA(OdeSolver):
+    """Adams/BDF method with automatic stiffness detection and switching.
+
+    This is a wrapper to the Fortran solver from ODEPACK [1]_. It switches
+    automatically between the nonstiff Adams method and the stiff BDF method.
+    The method was originally detailed in [2]_.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    min_step : float, optional
+        Minimum allowed step size. Default is 0.0, i.e., the step size is not
+        bounded and determined solely by the solver.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    jac : None or callable, optional
+        Jacobian matrix of the right-hand side of the system with respect to
+        ``y``. The Jacobian matrix has shape (n, n) and its element (i, j) is
+        equal to ``d f_i / d y_j``. The function will be called as
+        ``jac(t, y)``. If None (default), the Jacobian will be
+        approximated by finite differences. It is generally recommended to
+        provide the Jacobian rather than relying on a finite-difference
+        approximation.
+    lband, uband : int or None
+        Parameters defining the bandwidth of the Jacobian,
+        i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. Setting
+        these requires your jac routine to return the Jacobian in the packed format:
+        the returned array must have ``n`` columns and ``uband + lband + 1``
+        rows in which Jacobian diagonals are written. Specifically
+        ``jac_packed[uband + i - j , j] = jac[i, j]``. The same format is used
+        in `scipy.linalg.solve_banded` (check for an illustration).
+        These parameters can be also used with ``jac=None`` to reduce the
+        number of Jacobian elements estimated by finite differences.
+    vectorized : bool, optional
+        Whether `fun` may be called in a vectorized fashion. False (default)
+        is recommended for this solver.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by methods 'Radau' and 'BDF', but
+        will result in slower execution for this solver.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    nfev : int
+        Number of evaluations of the right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+
+    References
+    ----------
+    .. [1] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
+           Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
+           pp. 55-64, 1983.
+    .. [2] L. Petzold, "Automatic selection of methods for solving stiff and
+           nonstiff systems of ordinary differential equations", SIAM Journal
+           on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
+           1983.
+    """
+    def __init__(self, fun, t0, y0, t_bound, first_step=None, min_step=0.0,
+                 max_step=np.inf, rtol=1e-3, atol=1e-6, jac=None, lband=None,
+                 uband=None, vectorized=False, **extraneous):
+        warn_extraneous(extraneous)
+        super().__init__(fun, t0, y0, t_bound, vectorized)
+
+        if first_step is None:
+            first_step = 0  # LSODA value for automatic selection.
+        else:
+            first_step = validate_first_step(first_step, t0, t_bound)
+
+        first_step *= self.direction
+
+        if max_step == np.inf:
+            max_step = 0  # LSODA value for infinity.
+        elif max_step <= 0:
+            raise ValueError("`max_step` must be positive.")
+
+        if min_step < 0:
+            raise ValueError("`min_step` must be nonnegative.")
+
+        rtol, atol = validate_tol(rtol, atol, self.n)
+
+        solver = ode(self.fun, jac)
+        solver.set_integrator('lsoda', rtol=rtol, atol=atol, max_step=max_step,
+                              min_step=min_step, first_step=first_step,
+                              lband=lband, uband=uband)
+        solver.set_initial_value(y0, t0)
+
+        # Inject t_bound into rwork array as needed for itask=5.
+        solver._integrator.rwork[0] = self.t_bound
+        solver._integrator.call_args[4] = solver._integrator.rwork
+
+        self._lsoda_solver = solver
+
+    def _step_impl(self):
+        solver = self._lsoda_solver
+        integrator = solver._integrator
+
+        # From lsoda.step and lsoda.integrate itask=5 means take a single
+        # step and do not go past t_bound.
+        itask = integrator.call_args[2]
+        integrator.call_args[2] = 5
+        solver._y, solver.t = integrator.run(
+            solver.f, solver.jac or (lambda: None), solver._y, solver.t,
+            self.t_bound, solver.f_params, solver.jac_params)
+        integrator.call_args[2] = itask
+
+        if solver.successful():
+            self.t = solver.t
+            self.y = solver._y
+            # From LSODA Fortran source njev is equal to nlu.
+            self.njev = integrator.iwork[12]
+            self.nlu = integrator.iwork[12]
+            return True, None
+        else:
+            return False, 'Unexpected istate in LSODA.'
+
+    def _dense_output_impl(self):
+        iwork = self._lsoda_solver._integrator.iwork
+        rwork = self._lsoda_solver._integrator.rwork
+
+        # We want to produce the Nordsieck history array, yh, up to the order
+        # used in the last successful iteration. The step size is unimportant
+        # because it will be scaled out in LsodaDenseOutput. Some additional
+        # work may be required because ODEPACK's LSODA implementation produces
+        # the Nordsieck history in the state needed for the next iteration.
+
+        # iwork[13] contains order from last successful iteration, while
+        # iwork[14] contains order to be attempted next.
+        order = iwork[13]
+
+        # rwork[11] contains the step size to be attempted next, while
+        # rwork[10] contains step size from last successful iteration.
+        h = rwork[11]
+
+        # rwork[20:20 + (iwork[14] + 1) * self.n] contains entries of the
+        # Nordsieck array in state needed for next iteration. We want
+        # the entries up to order for the last successful step so use the 
+        # following.
+        yh = np.reshape(rwork[20:20 + (order + 1) * self.n],
+                        (self.n, order + 1), order='F').copy()
+        if iwork[14] < order:
+            # If the order is set to decrease then the final column of yh
+            # has not been updated within ODEPACK's LSODA
+            # implementation because this column will not be used in the
+            # next iteration. We must rescale this column to make the
+            # associated step size consistent with the other columns.
+            yh[:, -1] *= (h / rwork[10]) ** order
+
+        return LsodaDenseOutput(self.t_old, self.t, h, order, yh)
+
+
+class LsodaDenseOutput(DenseOutput):
+    def __init__(self, t_old, t, h, order, yh):
+        super().__init__(t_old, t)
+        self.h = h
+        self.yh = yh
+        self.p = np.arange(order + 1)
+
+    def _call_impl(self, t):
+        if t.ndim == 0:
+            x = ((t - self.t) / self.h) ** self.p
+        else:
+            x = ((t - self.t) / self.h) ** self.p[:, None]
+
+        return np.dot(self.yh, x)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d572b48de51ebc7e8f8fd278ce1000bdef581b5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py
@@ -0,0 +1,572 @@
+import numpy as np
+from scipy.linalg import lu_factor, lu_solve
+from scipy.sparse import csc_matrix, issparse, eye
+from scipy.sparse.linalg import splu
+from scipy.optimize._numdiff import group_columns
+from .common import (validate_max_step, validate_tol, select_initial_step,
+                     norm, num_jac, EPS, warn_extraneous,
+                     validate_first_step)
+from .base import OdeSolver, DenseOutput
+
+S6 = 6 ** 0.5
+
+# Butcher tableau. A is not used directly, see below.
+C = np.array([(4 - S6) / 10, (4 + S6) / 10, 1])
+E = np.array([-13 - 7 * S6, -13 + 7 * S6, -1]) / 3
+
+# Eigendecomposition of A is done: A = T L T**-1. There is 1 real eigenvalue
+# and a complex conjugate pair. They are written below.
+MU_REAL = 3 + 3 ** (2 / 3) - 3 ** (1 / 3)
+MU_COMPLEX = (3 + 0.5 * (3 ** (1 / 3) - 3 ** (2 / 3))
+              - 0.5j * (3 ** (5 / 6) + 3 ** (7 / 6)))
+
+# These are transformation matrices.
+T = np.array([
+    [0.09443876248897524, -0.14125529502095421, 0.03002919410514742],
+    [0.25021312296533332, 0.20412935229379994, -0.38294211275726192],
+    [1, 1, 0]])
+TI = np.array([
+    [4.17871859155190428, 0.32768282076106237, 0.52337644549944951],
+    [-4.17871859155190428, -0.32768282076106237, 0.47662355450055044],
+    [0.50287263494578682, -2.57192694985560522, 0.59603920482822492]])
+# These linear combinations are used in the algorithm.
+TI_REAL = TI[0]
+TI_COMPLEX = TI[1] + 1j * TI[2]
+
+# Interpolator coefficients.
+P = np.array([
+    [13/3 + 7*S6/3, -23/3 - 22*S6/3, 10/3 + 5 * S6],
+    [13/3 - 7*S6/3, -23/3 + 22*S6/3, 10/3 - 5 * S6],
+    [1/3, -8/3, 10/3]])
+
+
+NEWTON_MAXITER = 6  # Maximum number of Newton iterations.
+MIN_FACTOR = 0.2  # Minimum allowed decrease in a step size.
+MAX_FACTOR = 10  # Maximum allowed increase in a step size.
+
+
+def solve_collocation_system(fun, t, y, h, Z0, scale, tol,
+                             LU_real, LU_complex, solve_lu):
+    """Solve the collocation system.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system.
+    t : float
+        Current time.
+    y : ndarray, shape (n,)
+        Current state.
+    h : float
+        Step to try.
+    Z0 : ndarray, shape (3, n)
+        Initial guess for the solution. It determines new values of `y` at
+        ``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants.
+    scale : ndarray, shape (n)
+        Problem tolerance scale, i.e. ``rtol * abs(y) + atol``.
+    tol : float
+        Tolerance to which solve the system. This value is compared with
+        the normalized by `scale` error.
+    LU_real, LU_complex
+        LU decompositions of the system Jacobians.
+    solve_lu : callable
+        Callable which solves a linear system given a LU decomposition. The
+        signature is ``solve_lu(LU, b)``.
+
+    Returns
+    -------
+    converged : bool
+        Whether iterations converged.
+    n_iter : int
+        Number of completed iterations.
+    Z : ndarray, shape (3, n)
+        Found solution.
+    rate : float
+        The rate of convergence.
+    """
+    n = y.shape[0]
+    M_real = MU_REAL / h
+    M_complex = MU_COMPLEX / h
+
+    W = TI.dot(Z0)
+    Z = Z0
+
+    F = np.empty((3, n))
+    ch = h * C
+
+    dW_norm_old = None
+    dW = np.empty_like(W)
+    converged = False
+    rate = None
+    for k in range(NEWTON_MAXITER):
+        for i in range(3):
+            F[i] = fun(t + ch[i], y + Z[i])
+
+        if not np.all(np.isfinite(F)):
+            break
+
+        f_real = F.T.dot(TI_REAL) - M_real * W[0]
+        f_complex = F.T.dot(TI_COMPLEX) - M_complex * (W[1] + 1j * W[2])
+
+        dW_real = solve_lu(LU_real, f_real)
+        dW_complex = solve_lu(LU_complex, f_complex)
+
+        dW[0] = dW_real
+        dW[1] = dW_complex.real
+        dW[2] = dW_complex.imag
+
+        dW_norm = norm(dW / scale)
+        if dW_norm_old is not None:
+            rate = dW_norm / dW_norm_old
+
+        if (rate is not None and (rate >= 1 or
+                rate ** (NEWTON_MAXITER - k) / (1 - rate) * dW_norm > tol)):
+            break
+
+        W += dW
+        Z = T.dot(W)
+
+        if (dW_norm == 0 or
+                rate is not None and rate / (1 - rate) * dW_norm < tol):
+            converged = True
+            break
+
+        dW_norm_old = dW_norm
+
+    return converged, k + 1, Z, rate
+
+
+def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old):
+    """Predict by which factor to increase/decrease the step size.
+
+    The algorithm is described in [1]_.
+
+    Parameters
+    ----------
+    h_abs, h_abs_old : float
+        Current and previous values of the step size, `h_abs_old` can be None
+        (see Notes).
+    error_norm, error_norm_old : float
+        Current and previous values of the error norm, `error_norm_old` can
+        be None (see Notes).
+
+    Returns
+    -------
+    factor : float
+        Predicted factor.
+
+    Notes
+    -----
+    If `h_abs_old` and `error_norm_old` are both not None then a two-step
+    algorithm is used, otherwise a one-step algorithm is used.
+
+    References
+    ----------
+    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+           Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8.
+    """
+    if error_norm_old is None or h_abs_old is None or error_norm == 0:
+        multiplier = 1
+    else:
+        multiplier = h_abs / h_abs_old * (error_norm_old / error_norm) ** 0.25
+
+    with np.errstate(divide='ignore'):
+        factor = min(1, multiplier) * error_norm ** -0.25
+
+    return factor
+
+
+class Radau(OdeSolver):
+    """Implicit Runge-Kutta method of Radau IIA family of order 5.
+
+    The implementation follows [1]_. The error is controlled with a
+    third-order accurate embedded formula. A cubic polynomial which satisfies
+    the collocation conditions is used for the dense output.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. HHere `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    jac : {None, array_like, sparse_matrix, callable}, optional
+        Jacobian matrix of the right-hand side of the system with respect to
+        y, required by this method. The Jacobian matrix has shape (n, n) and
+        its element (i, j) is equal to ``d f_i / d y_j``.
+        There are three ways to define the Jacobian:
+
+            * If array_like or sparse_matrix, the Jacobian is assumed to
+              be constant.
+            * If callable, the Jacobian is assumed to depend on both
+              t and y; it will be called as ``jac(t, y)`` as necessary.
+              For the 'Radau' and 'BDF' methods, the return value might be a
+              sparse matrix.
+            * If None (default), the Jacobian will be approximated by
+              finite differences.
+
+        It is generally recommended to provide the Jacobian rather than
+        relying on a finite-difference approximation.
+    jac_sparsity : {None, array_like, sparse matrix}, optional
+        Defines a sparsity structure of the Jacobian matrix for a
+        finite-difference approximation. Its shape must be (n, n). This argument
+        is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
+        elements in *each* row, providing the sparsity structure will greatly
+        speed up the computations [2]_. A zero entry means that a corresponding
+        element in the Jacobian is always zero. If None (default), the Jacobian
+        is assumed to be dense.
+    vectorized : bool, optional
+        Whether `fun` can be called in a vectorized fashion. Default is False.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by this method, but may result in slower
+        execution overall in some circumstances (e.g. small ``len(y0)``).
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number of evaluations of the right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+    nlu : int
+        Number of LU decompositions.
+
+    References
+    ----------
+    .. [1] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
+           Stiff and Differential-Algebraic Problems", Sec. IV.8.
+    .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+           sparse Jacobian matrices", Journal of the Institute of Mathematics
+           and its Applications, 13, pp. 117-120, 1974.
+    """
+    def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+                 rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
+                 vectorized=False, first_step=None, **extraneous):
+        warn_extraneous(extraneous)
+        super().__init__(fun, t0, y0, t_bound, vectorized)
+        self.y_old = None
+        self.max_step = validate_max_step(max_step)
+        self.rtol, self.atol = validate_tol(rtol, atol, self.n)
+        self.f = self.fun(self.t, self.y)
+        # Select initial step assuming the same order which is used to control
+        # the error.
+        if first_step is None:
+            self.h_abs = select_initial_step(
+                self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
+                3, self.rtol, self.atol)
+        else:
+            self.h_abs = validate_first_step(first_step, t0, t_bound)
+        self.h_abs_old = None
+        self.error_norm_old = None
+
+        self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
+        self.sol = None
+
+        self.jac_factor = None
+        self.jac, self.J = self._validate_jac(jac, jac_sparsity)
+        if issparse(self.J):
+            def lu(A):
+                self.nlu += 1
+                return splu(A)
+
+            def solve_lu(LU, b):
+                return LU.solve(b)
+
+            I = eye(self.n, format='csc')
+        else:
+            def lu(A):
+                self.nlu += 1
+                return lu_factor(A, overwrite_a=True)
+
+            def solve_lu(LU, b):
+                return lu_solve(LU, b, overwrite_b=True)
+
+            I = np.identity(self.n)
+
+        self.lu = lu
+        self.solve_lu = solve_lu
+        self.I = I
+
+        self.current_jac = True
+        self.LU_real = None
+        self.LU_complex = None
+        self.Z = None
+
+    def _validate_jac(self, jac, sparsity):
+        t0 = self.t
+        y0 = self.y
+
+        if jac is None:
+            if sparsity is not None:
+                if issparse(sparsity):
+                    sparsity = csc_matrix(sparsity)
+                groups = group_columns(sparsity)
+                sparsity = (sparsity, groups)
+
+            def jac_wrapped(t, y, f):
+                self.njev += 1
+                J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
+                                             self.atol, self.jac_factor,
+                                             sparsity)
+                return J
+            J = jac_wrapped(t0, y0, self.f)
+        elif callable(jac):
+            J = jac(t0, y0)
+            self.njev = 1
+            if issparse(J):
+                J = csc_matrix(J)
+
+                def jac_wrapped(t, y, _=None):
+                    self.njev += 1
+                    return csc_matrix(jac(t, y), dtype=float)
+
+            else:
+                J = np.asarray(J, dtype=float)
+
+                def jac_wrapped(t, y, _=None):
+                    self.njev += 1
+                    return np.asarray(jac(t, y), dtype=float)
+
+            if J.shape != (self.n, self.n):
+                raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+                                 f" but actually has {J.shape}.")
+        else:
+            if issparse(jac):
+                J = csc_matrix(jac)
+            else:
+                J = np.asarray(jac, dtype=float)
+
+            if J.shape != (self.n, self.n):
+                raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+                                 f" but actually has {J.shape}.")
+            jac_wrapped = None
+
+        return jac_wrapped, J
+
+    def _step_impl(self):
+        t = self.t
+        y = self.y
+        f = self.f
+
+        max_step = self.max_step
+        atol = self.atol
+        rtol = self.rtol
+
+        min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
+        if self.h_abs > max_step:
+            h_abs = max_step
+            h_abs_old = None
+            error_norm_old = None
+        elif self.h_abs < min_step:
+            h_abs = min_step
+            h_abs_old = None
+            error_norm_old = None
+        else:
+            h_abs = self.h_abs
+            h_abs_old = self.h_abs_old
+            error_norm_old = self.error_norm_old
+
+        J = self.J
+        LU_real = self.LU_real
+        LU_complex = self.LU_complex
+
+        current_jac = self.current_jac
+        jac = self.jac
+
+        rejected = False
+        step_accepted = False
+        message = None
+        while not step_accepted:
+            if h_abs < min_step:
+                return False, self.TOO_SMALL_STEP
+
+            h = h_abs * self.direction
+            t_new = t + h
+
+            if self.direction * (t_new - self.t_bound) > 0:
+                t_new = self.t_bound
+
+            h = t_new - t
+            h_abs = np.abs(h)
+
+            if self.sol is None:
+                Z0 = np.zeros((3, y.shape[0]))
+            else:
+                Z0 = self.sol(t + h * C).T - y
+
+            scale = atol + np.abs(y) * rtol
+
+            converged = False
+            while not converged:
+                if LU_real is None or LU_complex is None:
+                    LU_real = self.lu(MU_REAL / h * self.I - J)
+                    LU_complex = self.lu(MU_COMPLEX / h * self.I - J)
+
+                converged, n_iter, Z, rate = solve_collocation_system(
+                    self.fun, t, y, h, Z0, scale, self.newton_tol,
+                    LU_real, LU_complex, self.solve_lu)
+
+                if not converged:
+                    if current_jac:
+                        break
+
+                    J = self.jac(t, y, f)
+                    current_jac = True
+                    LU_real = None
+                    LU_complex = None
+
+            if not converged:
+                h_abs *= 0.5
+                LU_real = None
+                LU_complex = None
+                continue
+
+            y_new = y + Z[-1]
+            ZE = Z.T.dot(E) / h
+            error = self.solve_lu(LU_real, f + ZE)
+            scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
+            error_norm = norm(error / scale)
+            safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
+                                                       + n_iter)
+
+            if rejected and error_norm > 1:
+                error = self.solve_lu(LU_real, self.fun(t, y + error) + ZE)
+                error_norm = norm(error / scale)
+
+            if error_norm > 1:
+                factor = predict_factor(h_abs, h_abs_old,
+                                        error_norm, error_norm_old)
+                h_abs *= max(MIN_FACTOR, safety * factor)
+
+                LU_real = None
+                LU_complex = None
+                rejected = True
+            else:
+                step_accepted = True
+
+        recompute_jac = jac is not None and n_iter > 2 and rate > 1e-3
+
+        factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old)
+        factor = min(MAX_FACTOR, safety * factor)
+
+        if not recompute_jac and factor < 1.2:
+            factor = 1
+        else:
+            LU_real = None
+            LU_complex = None
+
+        f_new = self.fun(t_new, y_new)
+        if recompute_jac:
+            J = jac(t_new, y_new, f_new)
+            current_jac = True
+        elif jac is not None:
+            current_jac = False
+
+        self.h_abs_old = self.h_abs
+        self.error_norm_old = error_norm
+
+        self.h_abs = h_abs * factor
+
+        self.y_old = y
+
+        self.t = t_new
+        self.y = y_new
+        self.f = f_new
+
+        self.Z = Z
+
+        self.LU_real = LU_real
+        self.LU_complex = LU_complex
+        self.current_jac = current_jac
+        self.J = J
+
+        self.t_old = t
+        self.sol = self._compute_dense_output()
+
+        return step_accepted, message
+
+    def _compute_dense_output(self):
+        Q = np.dot(self.Z.T, P)
+        return RadauDenseOutput(self.t_old, self.t, self.y_old, Q)
+
+    def _dense_output_impl(self):
+        return self.sol
+
+
+class RadauDenseOutput(DenseOutput):
+    def __init__(self, t_old, t, y_old, Q):
+        super().__init__(t_old, t)
+        self.h = t - t_old
+        self.Q = Q
+        self.order = Q.shape[1] - 1
+        self.y_old = y_old
+
+    def _call_impl(self, t):
+        x = (t - self.t_old) / self.h
+        if t.ndim == 0:
+            p = np.tile(x, self.order + 1)
+            p = np.cumprod(p)
+        else:
+            p = np.tile(x, (self.order + 1, 1))
+            p = np.cumprod(p, axis=0)
+        # Here we don't multiply by h, not a mistake.
+        y = np.dot(self.Q, p)
+        if y.ndim == 2:
+            y += self.y_old[:, None]
+        else:
+            y += self.y_old
+
+        return y
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py
new file mode 100644
index 0000000000000000000000000000000000000000..62a5347ffe91afc754e9b818d0b34c010d0c4d12
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py
@@ -0,0 +1,601 @@
+import numpy as np
+from .base import OdeSolver, DenseOutput
+from .common import (validate_max_step, validate_tol, select_initial_step,
+                     norm, warn_extraneous, validate_first_step)
+from . import dop853_coefficients
+
+# Multiply steps computed from asymptotic behaviour of errors by this.
+SAFETY = 0.9
+
+MIN_FACTOR = 0.2  # Minimum allowed decrease in a step size.
+MAX_FACTOR = 10  # Maximum allowed increase in a step size.
+
+
+def rk_step(fun, t, y, f, h, A, B, C, K):
+    """Perform a single Runge-Kutta step.
+
+    This function computes a prediction of an explicit Runge-Kutta method and
+    also estimates the error of a less accurate method.
+
+    Notation for Butcher tableau is as in [1]_.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system.
+    t : float
+        Current time.
+    y : ndarray, shape (n,)
+        Current state.
+    f : ndarray, shape (n,)
+        Current value of the derivative, i.e., ``fun(x, y)``.
+    h : float
+        Step to use.
+    A : ndarray, shape (n_stages, n_stages)
+        Coefficients for combining previous RK stages to compute the next
+        stage. For explicit methods the coefficients at and above the main
+        diagonal are zeros.
+    B : ndarray, shape (n_stages,)
+        Coefficients for combining RK stages for computing the final
+        prediction.
+    C : ndarray, shape (n_stages,)
+        Coefficients for incrementing time for consecutive RK stages.
+        The value for the first stage is always zero.
+    K : ndarray, shape (n_stages + 1, n)
+        Storage array for putting RK stages here. Stages are stored in rows.
+        The last row is a linear combination of the previous rows with
+        coefficients
+
+    Returns
+    -------
+    y_new : ndarray, shape (n,)
+        Solution at t + h computed with a higher accuracy.
+    f_new : ndarray, shape (n,)
+        Derivative ``fun(t + h, y_new)``.
+
+    References
+    ----------
+    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+           Equations I: Nonstiff Problems", Sec. II.4.
+    """
+    K[0] = f
+    for s, (a, c) in enumerate(zip(A[1:], C[1:]), start=1):
+        dy = np.dot(K[:s].T, a[:s]) * h
+        K[s] = fun(t + c * h, y + dy)
+
+    y_new = y + h * np.dot(K[:-1].T, B)
+    f_new = fun(t + h, y_new)
+
+    K[-1] = f_new
+
+    return y_new, f_new
+
+
+class RungeKutta(OdeSolver):
+    """Base class for explicit Runge-Kutta methods."""
+    C: np.ndarray = NotImplemented
+    A: np.ndarray = NotImplemented
+    B: np.ndarray = NotImplemented
+    E: np.ndarray = NotImplemented
+    P: np.ndarray = NotImplemented
+    order: int = NotImplemented
+    error_estimator_order: int = NotImplemented
+    n_stages: int = NotImplemented
+
+    def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+                 rtol=1e-3, atol=1e-6, vectorized=False,
+                 first_step=None, **extraneous):
+        warn_extraneous(extraneous)
+        super().__init__(fun, t0, y0, t_bound, vectorized,
+                         support_complex=True)
+        self.y_old = None
+        self.max_step = validate_max_step(max_step)
+        self.rtol, self.atol = validate_tol(rtol, atol, self.n)
+        self.f = self.fun(self.t, self.y)
+        if first_step is None:
+            self.h_abs = select_initial_step(
+                self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
+                self.error_estimator_order, self.rtol, self.atol)
+        else:
+            self.h_abs = validate_first_step(first_step, t0, t_bound)
+        self.K = np.empty((self.n_stages + 1, self.n), dtype=self.y.dtype)
+        self.error_exponent = -1 / (self.error_estimator_order + 1)
+        self.h_previous = None
+
+    def _estimate_error(self, K, h):
+        return np.dot(K.T, self.E) * h
+
+    def _estimate_error_norm(self, K, h, scale):
+        return norm(self._estimate_error(K, h) / scale)
+
+    def _step_impl(self):
+        t = self.t
+        y = self.y
+
+        max_step = self.max_step
+        rtol = self.rtol
+        atol = self.atol
+
+        min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
+
+        if self.h_abs > max_step:
+            h_abs = max_step
+        elif self.h_abs < min_step:
+            h_abs = min_step
+        else:
+            h_abs = self.h_abs
+
+        step_accepted = False
+        step_rejected = False
+
+        while not step_accepted:
+            if h_abs < min_step:
+                return False, self.TOO_SMALL_STEP
+
+            h = h_abs * self.direction
+            t_new = t + h
+
+            if self.direction * (t_new - self.t_bound) > 0:
+                t_new = self.t_bound
+
+            h = t_new - t
+            h_abs = np.abs(h)
+
+            y_new, f_new = rk_step(self.fun, t, y, self.f, h, self.A,
+                                   self.B, self.C, self.K)
+            scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
+            error_norm = self._estimate_error_norm(self.K, h, scale)
+
+            if error_norm < 1:
+                if error_norm == 0:
+                    factor = MAX_FACTOR
+                else:
+                    factor = min(MAX_FACTOR,
+                                 SAFETY * error_norm ** self.error_exponent)
+
+                if step_rejected:
+                    factor = min(1, factor)
+
+                h_abs *= factor
+
+                step_accepted = True
+            else:
+                h_abs *= max(MIN_FACTOR,
+                             SAFETY * error_norm ** self.error_exponent)
+                step_rejected = True
+
+        self.h_previous = h
+        self.y_old = y
+
+        self.t = t_new
+        self.y = y_new
+
+        self.h_abs = h_abs
+        self.f = f_new
+
+        return True, None
+
+    def _dense_output_impl(self):
+        Q = self.K.T.dot(self.P)
+        return RkDenseOutput(self.t_old, self.t, self.y_old, Q)
+
+
+class RK23(RungeKutta):
+    """Explicit Runge-Kutta method of order 3(2).
+
+    This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled
+    assuming accuracy of the second-order method, but steps are taken using the
+    third-order accurate formula (local extrapolation is done). A cubic Hermite
+    polynomial is used for the dense output.
+
+    Can be applied in the complex domain.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system: the time derivative of the state ``y``
+        at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+        scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+        return an array of the same shape as ``y``. See `vectorized` for more
+        information.
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    vectorized : bool, optional
+        Whether `fun` may be called in a vectorized fashion. False (default)
+        is recommended for this solver.
+
+        If ``vectorized`` is False, `fun` will always be called with ``y`` of
+        shape ``(n,)``, where ``n = len(y0)``.
+
+        If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+        ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+        such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+        the returned array is the time derivative of the state corresponding
+        with a column of ``y``).
+
+        Setting ``vectorized=True`` allows for faster finite difference
+        approximation of the Jacobian by methods 'Radau' and 'BDF', but
+        will result in slower execution for this solver.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number evaluations of the system's right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+        Is always 0 for this solver as it does not use the Jacobian.
+    nlu : int
+        Number of LU decompositions. Is always 0 for this solver.
+
+    References
+    ----------
+    .. [1] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
+           Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
+    """
+    order = 3
+    error_estimator_order = 2
+    n_stages = 3
+    C = np.array([0, 1/2, 3/4])
+    A = np.array([
+        [0, 0, 0],
+        [1/2, 0, 0],
+        [0, 3/4, 0]
+    ])
+    B = np.array([2/9, 1/3, 4/9])
+    E = np.array([5/72, -1/12, -1/9, 1/8])
+    P = np.array([[1, -4 / 3, 5 / 9],
+                  [0, 1, -2/3],
+                  [0, 4/3, -8/9],
+                  [0, -1, 1]])
+
+
+class RK45(RungeKutta):
+    """Explicit Runge-Kutta method of order 5(4).
+
+    This uses the Dormand-Prince pair of formulas [1]_. The error is controlled
+    assuming accuracy of the fourth-order method accuracy, but steps are taken
+    using the fifth-order accurate formula (local extrapolation is done).
+    A quartic interpolation polynomial is used for the dense output [2]_.
+
+    Can be applied in the complex domain.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system. The calling signature is ``fun(t, y)``.
+        Here ``t`` is a scalar, and there are two options for the ndarray ``y``:
+        It can either have shape (n,); then ``fun`` must return array_like with
+        shape (n,). Alternatively it can have shape (n, k); then ``fun``
+        must return an array_like with shape (n, k), i.e., each column
+        corresponds to a single column in ``y``. The choice between the two
+        options is determined by `vectorized` argument (see below).
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e., the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    vectorized : bool, optional
+        Whether `fun` is implemented in a vectorized fashion. Default is False.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number evaluations of the system's right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian.
+        Is always 0 for this solver as it does not use the Jacobian.
+    nlu : int
+        Number of LU decompositions. Is always 0 for this solver.
+
+    References
+    ----------
+    .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
+           formulae", Journal of Computational and Applied Mathematics, Vol. 6,
+           No. 1, pp. 19-26, 1980.
+    .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
+           of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
+    """
+    order = 5
+    error_estimator_order = 4
+    n_stages = 6
+    C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1])
+    A = np.array([
+        [0, 0, 0, 0, 0],
+        [1/5, 0, 0, 0, 0],
+        [3/40, 9/40, 0, 0, 0],
+        [44/45, -56/15, 32/9, 0, 0],
+        [19372/6561, -25360/2187, 64448/6561, -212/729, 0],
+        [9017/3168, -355/33, 46732/5247, 49/176, -5103/18656]
+    ])
+    B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84])
+    E = np.array([-71/57600, 0, 71/16695, -71/1920, 17253/339200, -22/525,
+                  1/40])
+    # Corresponds to the optimum value of c_6 from [2]_.
+    P = np.array([
+        [1, -8048581381/2820520608, 8663915743/2820520608,
+         -12715105075/11282082432],
+        [0, 0, 0, 0],
+        [0, 131558114200/32700410799, -68118460800/10900136933,
+         87487479700/32700410799],
+        [0, -1754552775/470086768, 14199869525/1410260304,
+         -10690763975/1880347072],
+        [0, 127303824393/49829197408, -318862633887/49829197408,
+         701980252875 / 199316789632],
+        [0, -282668133/205662961, 2019193451/616988883, -1453857185/822651844],
+        [0, 40617522/29380423, -110615467/29380423, 69997945/29380423]])
+
+
+class DOP853(RungeKutta):
+    """Explicit Runge-Kutta method of order 8.
+
+    This is a Python implementation of "DOP853" algorithm originally written
+    in Fortran [1]_, [2]_. Note that this is not a literal translation, but
+    the algorithmic core and coefficients are the same.
+
+    Can be applied in the complex domain.
+
+    Parameters
+    ----------
+    fun : callable
+        Right-hand side of the system. The calling signature is ``fun(t, y)``.
+        Here, ``t`` is a scalar, and there are two options for the ndarray ``y``:
+        It can either have shape (n,); then ``fun`` must return array_like with
+        shape (n,). Alternatively it can have shape (n, k); then ``fun``
+        must return an array_like with shape (n, k), i.e. each column
+        corresponds to a single column in ``y``. The choice between the two
+        options is determined by `vectorized` argument (see below).
+    t0 : float
+        Initial time.
+    y0 : array_like, shape (n,)
+        Initial state.
+    t_bound : float
+        Boundary time - the integration won't continue beyond it. It also
+        determines the direction of the integration.
+    first_step : float or None, optional
+        Initial step size. Default is ``None`` which means that the algorithm
+        should choose.
+    max_step : float, optional
+        Maximum allowed step size. Default is np.inf, i.e. the step size is not
+        bounded and determined solely by the solver.
+    rtol, atol : float and array_like, optional
+        Relative and absolute tolerances. The solver keeps the local error
+        estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+        relative accuracy (number of correct digits), while `atol` controls
+        absolute accuracy (number of correct decimal places). To achieve the
+        desired `rtol`, set `atol` to be smaller than the smallest value that
+        can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+        allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+        number of correct digits is not guaranteed. Conversely, to achieve the
+        desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+        than `atol`. If components of y have different scales, it might be
+        beneficial to set different `atol` values for different components by
+        passing array_like with shape (n,) for `atol`. Default values are
+        1e-3 for `rtol` and 1e-6 for `atol`.
+    vectorized : bool, optional
+        Whether `fun` is implemented in a vectorized fashion. Default is False.
+
+    Attributes
+    ----------
+    n : int
+        Number of equations.
+    status : string
+        Current status of the solver: 'running', 'finished' or 'failed'.
+    t_bound : float
+        Boundary time.
+    direction : float
+        Integration direction: +1 or -1.
+    t : float
+        Current time.
+    y : ndarray
+        Current state.
+    t_old : float
+        Previous time. None if no steps were made yet.
+    step_size : float
+        Size of the last successful step. None if no steps were made yet.
+    nfev : int
+        Number evaluations of the system's right-hand side.
+    njev : int
+        Number of evaluations of the Jacobian. Is always 0 for this solver
+        as it does not use the Jacobian.
+    nlu : int
+        Number of LU decompositions. Is always 0 for this solver.
+
+    References
+    ----------
+    .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+           Equations I: Nonstiff Problems", Sec. II.
+    .. [2] `Page with original Fortran code of DOP853
+            `_.
+    """
+    n_stages = dop853_coefficients.N_STAGES
+    order = 8
+    error_estimator_order = 7
+    A = dop853_coefficients.A[:n_stages, :n_stages]
+    B = dop853_coefficients.B
+    C = dop853_coefficients.C[:n_stages]
+    E3 = dop853_coefficients.E3
+    E5 = dop853_coefficients.E5
+    D = dop853_coefficients.D
+
+    A_EXTRA = dop853_coefficients.A[n_stages + 1:]
+    C_EXTRA = dop853_coefficients.C[n_stages + 1:]
+
+    def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+                 rtol=1e-3, atol=1e-6, vectorized=False,
+                 first_step=None, **extraneous):
+        super().__init__(fun, t0, y0, t_bound, max_step, rtol, atol,
+                         vectorized, first_step, **extraneous)
+        self.K_extended = np.empty((dop853_coefficients.N_STAGES_EXTENDED,
+                                    self.n), dtype=self.y.dtype)
+        self.K = self.K_extended[:self.n_stages + 1]
+
+    def _estimate_error(self, K, h):  # Left for testing purposes.
+        err5 = np.dot(K.T, self.E5)
+        err3 = np.dot(K.T, self.E3)
+        denom = np.hypot(np.abs(err5), 0.1 * np.abs(err3))
+        correction_factor = np.ones_like(err5)
+        mask = denom > 0
+        correction_factor[mask] = np.abs(err5[mask]) / denom[mask]
+        return h * err5 * correction_factor
+
+    def _estimate_error_norm(self, K, h, scale):
+        err5 = np.dot(K.T, self.E5) / scale
+        err3 = np.dot(K.T, self.E3) / scale
+        err5_norm_2 = np.linalg.norm(err5)**2
+        err3_norm_2 = np.linalg.norm(err3)**2
+        if err5_norm_2 == 0 and err3_norm_2 == 0:
+            return 0.0
+        denom = err5_norm_2 + 0.01 * err3_norm_2
+        return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale))
+
+    def _dense_output_impl(self):
+        K = self.K_extended
+        h = self.h_previous
+        for s, (a, c) in enumerate(zip(self.A_EXTRA, self.C_EXTRA),
+                                   start=self.n_stages + 1):
+            dy = np.dot(K[:s].T, a[:s]) * h
+            K[s] = self.fun(self.t_old + c * h, self.y_old + dy)
+
+        F = np.empty((dop853_coefficients.INTERPOLATOR_POWER, self.n),
+                     dtype=self.y_old.dtype)
+
+        f_old = K[0]
+        delta_y = self.y - self.y_old
+
+        F[0] = delta_y
+        F[1] = h * f_old - delta_y
+        F[2] = 2 * delta_y - h * (self.f + f_old)
+        F[3:] = h * np.dot(self.D, K)
+
+        return Dop853DenseOutput(self.t_old, self.t, self.y_old, F)
+
+
+class RkDenseOutput(DenseOutput):
+    def __init__(self, t_old, t, y_old, Q):
+        super().__init__(t_old, t)
+        self.h = t - t_old
+        self.Q = Q
+        self.order = Q.shape[1] - 1
+        self.y_old = y_old
+
+    def _call_impl(self, t):
+        x = (t - self.t_old) / self.h
+        if t.ndim == 0:
+            p = np.tile(x, self.order + 1)
+            p = np.cumprod(p)
+        else:
+            p = np.tile(x, (self.order + 1, 1))
+            p = np.cumprod(p, axis=0)
+        y = self.h * np.dot(self.Q, p)
+        if y.ndim == 2:
+            y += self.y_old[:, None]
+        else:
+            y += self.y_old
+
+        return y
+
+
+class Dop853DenseOutput(DenseOutput):
+    def __init__(self, t_old, t, y_old, F):
+        super().__init__(t_old, t)
+        self.h = t - t_old
+        self.F = F
+        self.y_old = y_old
+
+    def _call_impl(self, t):
+        x = (t - self.t_old) / self.h
+
+        if t.ndim == 0:
+            y = np.zeros_like(self.y_old)
+        else:
+            x = x[:, None]
+            y = np.zeros((len(x), len(self.y_old)), dtype=self.y_old.dtype)
+
+        for i, f in enumerate(reversed(self.F)):
+            y += f
+            if i % 2 == 0:
+                y *= x
+            else:
+                y *= 1 - x
+        y += self.y_old
+
+        return y.T
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd318b9a165051293ac13b9b0e63be2df322963b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
@@ -0,0 +1,1287 @@
+from itertools import product
+from numpy.testing import (assert_, assert_allclose, assert_array_less,
+                           assert_equal, assert_no_warnings, suppress_warnings)
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from scipy.optimize._numdiff import group_columns
+from scipy.integrate import solve_ivp, RK23, RK45, DOP853, Radau, BDF, LSODA
+from scipy.integrate import OdeSolution
+from scipy.integrate._ivp.common import num_jac, select_initial_step
+from scipy.integrate._ivp.base import ConstantDenseOutput
+from scipy.sparse import coo_matrix, csc_matrix
+
+
+def fun_zero(t, y):
+    return np.zeros_like(y)
+
+
+def fun_linear(t, y):
+    return np.array([-y[0] - 5 * y[1], y[0] + y[1]])
+
+
+def jac_linear():
+    return np.array([[-1, -5], [1, 1]])
+
+
+def sol_linear(t):
+    return np.vstack((-5 * np.sin(2 * t),
+                      2 * np.cos(2 * t) + np.sin(2 * t)))
+
+
+def fun_rational(t, y):
+    return np.array([y[1] / t,
+                     y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))])
+
+
+def fun_rational_vectorized(t, y):
+    return np.vstack((y[1] / t,
+                      y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))))
+
+
+def jac_rational(t, y):
+    return np.array([
+        [0, 1 / t],
+        [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
+         (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
+    ])
+
+
+def jac_rational_sparse(t, y):
+    return csc_matrix([
+        [0, 1 / t],
+        [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
+         (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
+    ])
+
+
+def sol_rational(t):
+    return np.asarray((t / (t + 10), 10 * t / (t + 10) ** 2))
+
+
+def fun_medazko(t, y):
+    n = y.shape[0] // 2
+    k = 100
+    c = 4
+
+    phi = 2 if t <= 5 else 0
+    y = np.hstack((phi, 0, y, y[-2]))
+
+    d = 1 / n
+    j = np.arange(n) + 1
+    alpha = 2 * (j * d - 1) ** 3 / c ** 2
+    beta = (j * d - 1) ** 4 / c ** 2
+
+    j_2_p1 = 2 * j + 2
+    j_2_m3 = 2 * j - 2
+    j_2_m1 = 2 * j
+    j_2 = 2 * j + 1
+
+    f = np.empty(2 * n)
+    f[::2] = (alpha * (y[j_2_p1] - y[j_2_m3]) / (2 * d) +
+              beta * (y[j_2_m3] - 2 * y[j_2_m1] + y[j_2_p1]) / d ** 2 -
+              k * y[j_2_m1] * y[j_2])
+    f[1::2] = -k * y[j_2] * y[j_2_m1]
+
+    return f
+
+
+def medazko_sparsity(n):
+    cols = []
+    rows = []
+
+    i = np.arange(n) * 2
+
+    cols.append(i[1:])
+    rows.append(i[1:] - 2)
+
+    cols.append(i)
+    rows.append(i)
+
+    cols.append(i)
+    rows.append(i + 1)
+
+    cols.append(i[:-1])
+    rows.append(i[:-1] + 2)
+
+    i = np.arange(n) * 2 + 1
+
+    cols.append(i)
+    rows.append(i)
+
+    cols.append(i)
+    rows.append(i - 1)
+
+    cols = np.hstack(cols)
+    rows = np.hstack(rows)
+
+    return coo_matrix((np.ones_like(cols), (cols, rows)))
+
+
+def fun_complex(t, y):
+    return -y
+
+
+def jac_complex(t, y):
+    return -np.eye(y.shape[0])
+
+
+def jac_complex_sparse(t, y):
+    return csc_matrix(jac_complex(t, y))
+
+
+def sol_complex(t):
+    y = (0.5 + 1j) * np.exp(-t)
+    return y.reshape((1, -1))
+
+
+def fun_event_dense_output_LSODA(t, y):
+    return y * (t - 2)
+
+
+def jac_event_dense_output_LSODA(t, y):
+    return t - 2
+
+
+def sol_event_dense_output_LSODA(t):
+    return np.exp(t ** 2 / 2 - 2 * t + np.log(0.05) - 6)
+
+
+def compute_error(y, y_true, rtol, atol):
+    e = (y - y_true) / (atol + rtol * np.abs(y_true))
+    return np.linalg.norm(e, axis=0) / np.sqrt(e.shape[0])
+
+def test_duplicate_timestamps():
+    def upward_cannon(t, y):
+        return [y[1], -9.80665]
+
+    def hit_ground(t, y):
+        return y[0]
+
+    hit_ground.terminal = True
+    hit_ground.direction = -1
+
+    sol = solve_ivp(upward_cannon, [0, np.inf], [0, 0.01],
+                    max_step=0.05 * 0.001 / 9.80665,
+                    events=hit_ground, dense_output=True)
+    assert_allclose(sol.sol(0.01), np.asarray([-0.00039033, -0.08806632]),
+                    rtol=1e-5, atol=1e-8)
+    assert_allclose(sol.t_events, np.asarray([[0.00203943]]), rtol=1e-5, atol=1e-8)
+    assert_allclose(sol.y_events, [np.asarray([[ 0.0, -0.01 ]])], atol=1e-9)
+    assert sol.success
+    assert_equal(sol.status, 1)
+
+@pytest.mark.thread_unsafe
+def test_integration():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+
+    for vectorized, method, t_span, jac in product(
+            [False, True],
+            ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'],
+            [[5, 9], [5, 1]],
+            [None, jac_rational, jac_rational_sparse]):
+
+        if vectorized:
+            fun = fun_rational_vectorized
+        else:
+            fun = fun_rational
+
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       "The following arguments have no effect for a chosen "
+                       "solver: `jac`")
+            res = solve_ivp(fun, t_span, y0, rtol=rtol,
+                            atol=atol, method=method, dense_output=True,
+                            jac=jac, vectorized=vectorized)
+        assert_equal(res.t[0], t_span[0])
+        assert_(res.t_events is None)
+        assert_(res.y_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        if method == 'DOP853':
+            # DOP853 spends more functions evaluation because it doesn't
+            # have enough time to develop big enough step size.
+            assert_(res.nfev < 50)
+        else:
+            assert_(res.nfev < 40)
+
+        if method in ['RK23', 'RK45', 'DOP853', 'LSODA']:
+            assert_equal(res.njev, 0)
+            assert_equal(res.nlu, 0)
+        else:
+            assert_(0 < res.njev < 3)
+            assert_(0 < res.nlu < 10)
+
+        y_true = sol_rational(res.t)
+        e = compute_error(res.y, y_true, rtol, atol)
+        assert_(np.all(e < 5))
+
+        tc = np.linspace(*t_span)
+        yc_true = sol_rational(tc)
+        yc = res.sol(tc)
+
+        e = compute_error(yc, yc_true, rtol, atol)
+        assert_(np.all(e < 5))
+
+        tc = (t_span[0] + t_span[-1]) / 2
+        yc_true = sol_rational(tc)
+        yc = res.sol(tc)
+
+        e = compute_error(yc, yc_true, rtol, atol)
+        assert_(np.all(e < 5))
+
+        assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+
+@pytest.mark.thread_unsafe
+def test_integration_complex():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [0.5 + 1j]
+    t_span = [0, 1]
+    tc = np.linspace(t_span[0], t_span[1])
+    for method, jac in product(['RK23', 'RK45', 'DOP853', 'BDF'],
+                               [None, jac_complex, jac_complex_sparse]):
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       "The following arguments have no effect for a chosen "
+                       "solver: `jac`")
+            res = solve_ivp(fun_complex, t_span, y0, method=method,
+                            dense_output=True, rtol=rtol, atol=atol, jac=jac)
+
+        assert_equal(res.t[0], t_span[0])
+        assert_(res.t_events is None)
+        assert_(res.y_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        if method == 'DOP853':
+            assert res.nfev < 35
+        else:
+            assert res.nfev < 25
+
+        if method == 'BDF':
+            assert_equal(res.njev, 1)
+            assert res.nlu < 6
+        else:
+            assert res.njev == 0
+            assert res.nlu == 0
+
+        y_true = sol_complex(res.t)
+        e = compute_error(res.y, y_true, rtol, atol)
+        assert np.all(e < 5)
+
+        yc_true = sol_complex(tc)
+        yc = res.sol(tc)
+        e = compute_error(yc, yc_true, rtol, atol)
+
+        assert np.all(e < 5)
+
+
+@pytest.mark.fail_slow(5)
+def test_integration_sparse_difference():
+    n = 200
+    t_span = [0, 20]
+    y0 = np.zeros(2 * n)
+    y0[1::2] = 1
+    sparsity = medazko_sparsity(n)
+
+    for method in ['BDF', 'Radau']:
+        res = solve_ivp(fun_medazko, t_span, y0, method=method,
+                        jac_sparsity=sparsity)
+
+        assert_equal(res.t[0], t_span[0])
+        assert_(res.t_events is None)
+        assert_(res.y_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        assert_allclose(res.y[78, -1], 0.233994e-3, rtol=1e-2)
+        assert_allclose(res.y[79, -1], 0, atol=1e-3)
+        assert_allclose(res.y[148, -1], 0.359561e-3, rtol=1e-2)
+        assert_allclose(res.y[149, -1], 0, atol=1e-3)
+        assert_allclose(res.y[198, -1], 0.117374129e-3, rtol=1e-2)
+        assert_allclose(res.y[199, -1], 0.6190807e-5, atol=1e-3)
+        assert_allclose(res.y[238, -1], 0, atol=1e-3)
+        assert_allclose(res.y[239, -1], 0.9999997, rtol=1e-2)
+
+
+def test_integration_const_jac():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [0, 2]
+    t_span = [0, 2]
+    J = jac_linear()
+    J_sparse = csc_matrix(J)
+
+    for method, jac in product(['Radau', 'BDF'], [J, J_sparse]):
+        res = solve_ivp(fun_linear, t_span, y0, rtol=rtol, atol=atol,
+                        method=method, dense_output=True, jac=jac)
+        assert_equal(res.t[0], t_span[0])
+        assert_(res.t_events is None)
+        assert_(res.y_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        assert_(res.nfev < 100)
+        assert_equal(res.njev, 0)
+        assert_(0 < res.nlu < 15)
+
+        y_true = sol_linear(res.t)
+        e = compute_error(res.y, y_true, rtol, atol)
+        assert_(np.all(e < 10))
+
+        tc = np.linspace(*t_span)
+        yc_true = sol_linear(tc)
+        yc = res.sol(tc)
+
+        e = compute_error(yc, yc_true, rtol, atol)
+        assert_(np.all(e < 15))
+
+        assert_allclose(res.sol(res.t), res.y, rtol=1e-14, atol=1e-14)
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize('method', ['Radau', 'BDF', 'LSODA'])
+def test_integration_stiff(method, num_parallel_threads):
+    rtol = 1e-6
+    atol = 1e-6
+    y0 = [1e4, 0, 0]
+    tspan = [0, 1e8]
+
+    if method == 'LSODA' and num_parallel_threads > 1:
+        pytest.skip(reason='LSODA does not allow for concurrent calls')
+
+    def fun_robertson(t, state):
+        x, y, z = state
+        return [
+            -0.04 * x + 1e4 * y * z,
+            0.04 * x - 1e4 * y * z - 3e7 * y * y,
+            3e7 * y * y,
+        ]
+
+    res = solve_ivp(fun_robertson, tspan, y0, rtol=rtol,
+                    atol=atol, method=method)
+
+    # If the stiff mode is not activated correctly, these numbers will be much bigger
+    assert res.nfev < 5000
+    assert res.njev < 200
+
+
+def test_events(num_parallel_threads):
+    def event_rational_1(t, y):
+        return y[0] - y[1] ** 0.7
+
+    def event_rational_2(t, y):
+        return y[1] ** 0.6 - y[0]
+
+    def event_rational_3(t, y):
+        return t - 7.4
+
+    event_rational_3.terminal = True
+
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        if method == 'LSODA' and num_parallel_threads > 1:
+            continue
+
+        res = solve_ivp(fun_rational, [5, 8], [1/3, 2/9], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 1)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+        event_rational_1.direction = 1
+        event_rational_2.direction = 1
+        res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 0)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (0,))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+
+        event_rational_1.direction = -1
+        event_rational_2.direction = -1
+        res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 0)
+        assert_equal(res.t_events[1].size, 1)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+        assert_equal(res.y_events[0].shape, (0,))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+        event_rational_1.direction = 0
+        event_rational_2.direction = 0
+
+        res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+                        events=(event_rational_1, event_rational_2,
+                                event_rational_3), dense_output=True)
+        assert_equal(res.status, 1)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 0)
+        assert_equal(res.t_events[2].size, 1)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+        assert_(7.3 < res.t_events[2][0] < 7.5)
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (0,))
+        assert_equal(res.y_events[2].shape, (1, 2))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+        assert np.isclose(
+            event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
+
+        res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+                        events=event_rational_1, dense_output=True)
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+
+        # Also test that termination by event doesn't break interpolants.
+        tc = np.linspace(res.t[0], res.t[-1])
+        yc_true = sol_rational(tc)
+        yc = res.sol(tc)
+        e = compute_error(yc, yc_true, 1e-3, 1e-6)
+        assert_(np.all(e < 5))
+
+        # Test that the y_event matches solution
+        assert np.allclose(sol_rational(res.t_events[0][0]), res.y_events[0][0],
+                           rtol=1e-3, atol=1e-6)
+
+    # Test in backward direction.
+    event_rational_1.direction = 0
+    event_rational_2.direction = 0
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        if method == 'LSODA' and num_parallel_threads > 1:
+            continue
+
+        res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 1)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+        event_rational_1.direction = -1
+        event_rational_2.direction = -1
+        res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 1)
+        assert_equal(res.t_events[1].size, 0)
+        assert_(5.3 < res.t_events[0][0] < 5.7)
+
+        assert_equal(res.y_events[0].shape, (1, 2))
+        assert_equal(res.y_events[1].shape, (0,))
+        assert np.isclose(
+            event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+
+        event_rational_1.direction = 1
+        event_rational_2.direction = 1
+        res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+                        events=(event_rational_1, event_rational_2))
+        assert_equal(res.status, 0)
+        assert_equal(res.t_events[0].size, 0)
+        assert_equal(res.t_events[1].size, 1)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+
+        assert_equal(res.y_events[0].shape, (0,))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+        event_rational_1.direction = 0
+        event_rational_2.direction = 0
+
+        res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+                        events=(event_rational_1, event_rational_2,
+                                event_rational_3), dense_output=True)
+        assert_equal(res.status, 1)
+        assert_equal(res.t_events[0].size, 0)
+        assert_equal(res.t_events[1].size, 1)
+        assert_equal(res.t_events[2].size, 1)
+        assert_(7.3 < res.t_events[1][0] < 7.7)
+        assert_(7.3 < res.t_events[2][0] < 7.5)
+
+        assert_equal(res.y_events[0].shape, (0,))
+        assert_equal(res.y_events[1].shape, (1, 2))
+        assert_equal(res.y_events[2].shape, (1, 2))
+        assert np.isclose(
+            event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+        assert np.isclose(
+            event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
+
+        # Also test that termination by event doesn't break interpolants.
+        tc = np.linspace(res.t[-1], res.t[0])
+        yc_true = sol_rational(tc)
+        yc = res.sol(tc)
+        e = compute_error(yc, yc_true, 1e-3, 1e-6)
+        assert_(np.all(e < 5))
+
+        assert np.allclose(sol_rational(res.t_events[1][0]), res.y_events[1][0],
+                           rtol=1e-3, atol=1e-6)
+        assert np.allclose(sol_rational(res.t_events[2][0]), res.y_events[2][0],
+                           rtol=1e-3, atol=1e-6)
+
+
+def _get_harmonic_oscillator():
+    def f(t, y):
+        return [y[1], -y[0]]
+
+    def event(t, y):
+        return y[0]
+
+    return f, event
+
+
+@pytest.mark.parametrize('n_events', [3, 4])
+def test_event_terminal_integer(n_events):
+    f, event = _get_harmonic_oscillator()
+    event.terminal = n_events
+    res = solve_ivp(f, (0, 100), [1, 0], events=event)
+    assert len(res.t_events[0]) == n_events
+    assert len(res.y_events[0]) == n_events
+    assert_allclose(res.y_events[0][:, 0], 0, atol=1e-14)
+
+
+def test_event_terminal_iv():
+    f, event = _get_harmonic_oscillator()
+    args = (f, (0, 100), [1, 0])
+
+    event.terminal = None
+    res = solve_ivp(*args, events=event)
+    event.terminal = 0
+    ref = solve_ivp(*args, events=event)
+    assert_allclose(res.t_events, ref.t_events)
+
+    message = "The `terminal` attribute..."
+    event.terminal = -1
+    with pytest.raises(ValueError, match=message):
+        solve_ivp(*args, events=event)
+    event.terminal = 3.5
+    with pytest.raises(ValueError, match=message):
+        solve_ivp(*args, events=event)
+
+
+def test_max_step(num_parallel_threads):
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+        if method is LSODA and num_parallel_threads > 1:
+            continue
+        for t_span in ([5, 9], [5, 1]):
+            res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
+                            max_step=0.5, atol=atol, method=method,
+                            dense_output=True)
+            assert_equal(res.t[0], t_span[0])
+            assert_equal(res.t[-1], t_span[-1])
+            assert_(np.all(np.abs(np.diff(res.t)) <= 0.5 + 1e-15))
+            assert_(res.t_events is None)
+            assert_(res.success)
+            assert_equal(res.status, 0)
+
+            y_true = sol_rational(res.t)
+            e = compute_error(res.y, y_true, rtol, atol)
+            assert_(np.all(e < 5))
+
+            tc = np.linspace(*t_span)
+            yc_true = sol_rational(tc)
+            yc = res.sol(tc)
+
+            e = compute_error(yc, yc_true, rtol, atol)
+            assert_(np.all(e < 5))
+
+            assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+            assert_raises(ValueError, method, fun_rational, t_span[0], y0,
+                          t_span[1], max_step=-1)
+
+            if method is not LSODA:
+                solver = method(fun_rational, t_span[0], y0, t_span[1],
+                                rtol=rtol, atol=atol, max_step=1e-20)
+                message = solver.step()
+                message = solver.step()  # First step succeeds but second step fails.
+                assert_equal(solver.status, 'failed')
+                assert_("step size is less" in message)
+                assert_raises(RuntimeError, solver.step)
+
+
+def test_first_step(num_parallel_threads):
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    first_step = 0.1
+    for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+        if method is LSODA and num_parallel_threads > 1:
+            continue
+        for t_span in ([5, 9], [5, 1]):
+            res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
+                            max_step=0.5, atol=atol, method=method,
+                            dense_output=True, first_step=first_step)
+
+            assert_equal(res.t[0], t_span[0])
+            assert_equal(res.t[-1], t_span[-1])
+            assert_allclose(first_step, np.abs(res.t[1] - 5))
+            assert_(res.t_events is None)
+            assert_(res.success)
+            assert_equal(res.status, 0)
+
+            y_true = sol_rational(res.t)
+            e = compute_error(res.y, y_true, rtol, atol)
+            assert_(np.all(e < 5))
+
+            tc = np.linspace(*t_span)
+            yc_true = sol_rational(tc)
+            yc = res.sol(tc)
+
+            e = compute_error(yc, yc_true, rtol, atol)
+            assert_(np.all(e < 5))
+
+            assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+            assert_raises(ValueError, method, fun_rational, t_span[0], y0,
+                          t_span[1], first_step=-1)
+            assert_raises(ValueError, method, fun_rational, t_span[0], y0,
+                          t_span[1], first_step=5)
+
+
+def test_t_eval():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    for t_span in ([5, 9], [5, 1]):
+        t_eval = np.linspace(t_span[0], t_span[1], 10)
+        res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+                        t_eval=t_eval)
+        assert_equal(res.t, t_eval)
+        assert_(res.t_events is None)
+        assert_(res.success)
+        assert_equal(res.status, 0)
+
+        y_true = sol_rational(res.t)
+        e = compute_error(res.y, y_true, rtol, atol)
+        assert_(np.all(e < 5))
+
+    t_eval = [5, 5.01, 7, 8, 8.01, 9]
+    res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    y_true = sol_rational(res.t)
+    e = compute_error(res.y, y_true, rtol, atol)
+    assert_(np.all(e < 5))
+
+    t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1]
+    res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    t_eval = [5.01, 7, 8, 8.01]
+    res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    y_true = sol_rational(res.t)
+    e = compute_error(res.y, y_true, rtol, atol)
+    assert_(np.all(e < 5))
+
+    t_eval = [4.99, 3, 1.5, 1.1, 1.01]
+    res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    t_eval = [4, 6]
+    assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0,
+                  rtol=rtol, atol=atol, t_eval=t_eval)
+
+
+def test_t_eval_dense_output():
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    t_span = [5, 9]
+    t_eval = np.linspace(t_span[0], t_span[1], 10)
+    res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+                    t_eval=t_eval)
+    res_d = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+                      t_eval=t_eval, dense_output=True)
+    assert_equal(res.t, t_eval)
+    assert_(res.t_events is None)
+    assert_(res.success)
+    assert_equal(res.status, 0)
+
+    assert_equal(res.t, res_d.t)
+    assert_equal(res.y, res_d.y)
+    assert_(res_d.t_events is None)
+    assert_(res_d.success)
+    assert_equal(res_d.status, 0)
+
+    # if t and y are equal only test values for one case
+    y_true = sol_rational(res.t)
+    e = compute_error(res.y, y_true, rtol, atol)
+    assert_(np.all(e < 5))
+
+
+@pytest.mark.thread_unsafe
+def test_t_eval_early_event():
+    def early_event(t, y):
+        return t - 7
+
+    early_event.terminal = True
+
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [1/3, 2/9]
+    t_span = [5, 9]
+    t_eval = np.linspace(7.5, 9, 16)
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       "The following arguments have no effect for a chosen "
+                       "solver: `jac`")
+            res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+                            method=method, t_eval=t_eval, events=early_event,
+                            jac=jac_rational)
+        assert res.success
+        assert res.message == 'A termination event occurred.'
+        assert res.status == 1
+        assert not res.t and not res.y
+        assert len(res.t_events) == 1
+        assert res.t_events[0].size == 1
+        assert res.t_events[0][0] == 7
+
+
+def test_event_dense_output_LSODA(num_parallel_threads):
+    if num_parallel_threads > 1:
+        pytest.skip('LSODA does not allow for concurrent execution')
+
+    def event_lsoda(t, y):
+        return y[0] - 2.02e-5
+
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = [0.05]
+    t_span = [-2, 2]
+    first_step = 1e-3
+    res = solve_ivp(
+        fun_event_dense_output_LSODA,
+        t_span,
+        y0,
+        method="LSODA",
+        dense_output=True,
+        events=event_lsoda,
+        first_step=first_step,
+        max_step=1,
+        rtol=rtol,
+        atol=atol,
+        jac=jac_event_dense_output_LSODA,
+    )
+
+    assert_equal(res.t[0], t_span[0])
+    assert_equal(res.t[-1], t_span[-1])
+    assert_allclose(first_step, np.abs(res.t[1] - t_span[0]))
+    assert res.success
+    assert_equal(res.status, 0)
+
+    y_true = sol_event_dense_output_LSODA(res.t)
+    e = compute_error(res.y, y_true, rtol, atol)
+    assert_array_less(e, 5)
+
+    tc = np.linspace(*t_span)
+    yc_true = sol_event_dense_output_LSODA(tc)
+    yc = res.sol(tc)
+    e = compute_error(yc, yc_true, rtol, atol)
+    assert_array_less(e, 5)
+
+    assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+
+def test_no_integration():
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        sol = solve_ivp(lambda t, y: -y, [4, 4], [2, 3],
+                        method=method, dense_output=True)
+        assert_equal(sol.sol(4), [2, 3])
+        assert_equal(sol.sol([4, 5, 6]), [[2, 2, 2], [3, 3, 3]])
+
+
+def test_no_integration_class():
+    for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+        solver = method(lambda t, y: -y, 0.0, [10.0, 0.0], 0.0)
+        solver.step()
+        assert_equal(solver.status, 'finished')
+        sol = solver.dense_output()
+        assert_equal(sol(0.0), [10.0, 0.0])
+        assert_equal(sol([0, 1, 2]), [[10, 10, 10], [0, 0, 0]])
+
+        solver = method(lambda t, y: -y, 0.0, [], np.inf)
+        solver.step()
+        assert_equal(solver.status, 'finished')
+        sol = solver.dense_output()
+        assert_equal(sol(100.0), [])
+        assert_equal(sol([0, 1, 2]), np.empty((0, 3)))
+
+
+def test_empty():
+    def fun(t, y):
+        return np.zeros((0,))
+
+    y0 = np.zeros((0,))
+
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0,
+                                 method=method, dense_output=True)
+        assert_equal(sol.sol(10), np.zeros((0,)))
+        assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
+
+    for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+        sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0,
+                                 method=method, dense_output=True)
+        assert_equal(sol.sol(10), np.zeros((0,)))
+        assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
+
+
+def test_ConstantDenseOutput():
+    sol = ConstantDenseOutput(0, 1, np.array([1, 2]))
+    assert_allclose(sol(1.5), [1, 2])
+    assert_allclose(sol([1, 1.5, 2]), [[1, 1, 1], [2, 2, 2]])
+
+    sol = ConstantDenseOutput(0, 1, np.array([]))
+    assert_allclose(sol(1.5), np.empty(0))
+    assert_allclose(sol([1, 1.5, 2]), np.empty((0, 3)))
+
+
+def test_classes():
+    y0 = [1 / 3, 2 / 9]
+    for cls in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+        solver = cls(fun_rational, 5, y0, np.inf)
+        assert_equal(solver.n, 2)
+        assert_equal(solver.status, 'running')
+        assert_equal(solver.t_bound, np.inf)
+        assert_equal(solver.direction, 1)
+        assert_equal(solver.t, 5)
+        assert_equal(solver.y, y0)
+        assert_(solver.step_size is None)
+        if cls is not LSODA:
+            assert_(solver.nfev > 0)
+            assert_(solver.njev >= 0)
+            assert_equal(solver.nlu, 0)
+        else:
+            assert_equal(solver.nfev, 0)
+            assert_equal(solver.njev, 0)
+            assert_equal(solver.nlu, 0)
+
+        assert_raises(RuntimeError, solver.dense_output)
+
+        message = solver.step()
+        assert_equal(solver.status, 'running')
+        assert_equal(message, None)
+        assert_equal(solver.n, 2)
+        assert_equal(solver.t_bound, np.inf)
+        assert_equal(solver.direction, 1)
+        assert_(solver.t > 5)
+        assert_(not np.all(np.equal(solver.y, y0)))
+        assert_(solver.step_size > 0)
+        assert_(solver.nfev > 0)
+        assert_(solver.njev >= 0)
+        assert_(solver.nlu >= 0)
+        sol = solver.dense_output()
+        assert_allclose(sol(5), y0, rtol=1e-15, atol=0)
+
+
+def test_OdeSolution():
+    ts = np.array([0, 2, 5], dtype=float)
+    s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
+    s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
+
+    sol = OdeSolution(ts, [s1, s2])
+
+    assert_equal(sol(-1), [-1])
+    assert_equal(sol(1), [-1])
+    assert_equal(sol(2), [-1])
+    assert_equal(sol(3), [1])
+    assert_equal(sol(5), [1])
+    assert_equal(sol(6), [1])
+
+    assert_equal(sol([0, 6, -2, 1.5, 4.5, 2.5, 5, 5.5, 2]),
+                 np.array([[-1, 1, -1, -1, 1, 1, 1, 1, -1]]))
+
+    ts = np.array([10, 4, -3])
+    s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
+    s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
+
+    sol = OdeSolution(ts, [s1, s2])
+    assert_equal(sol(11), [-1])
+    assert_equal(sol(10), [-1])
+    assert_equal(sol(5), [-1])
+    assert_equal(sol(4), [-1])
+    assert_equal(sol(0), [1])
+    assert_equal(sol(-3), [1])
+    assert_equal(sol(-4), [1])
+
+    assert_equal(sol([12, -5, 10, -3, 6, 1, 4]),
+                 np.array([[-1, 1, -1, 1, -1, 1, -1]]))
+
+    ts = np.array([1, 1])
+    s = ConstantDenseOutput(1, 1, np.array([10]))
+    sol = OdeSolution(ts, [s])
+    assert_equal(sol(0), [10])
+    assert_equal(sol(1), [10])
+    assert_equal(sol(2), [10])
+
+    assert_equal(sol([2, 1, 0]), np.array([[10, 10, 10]]))
+
+
+def test_num_jac():
+    def fun(t, y):
+        return np.vstack([
+            -0.04 * y[0] + 1e4 * y[1] * y[2],
+            0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] ** 2,
+            3e7 * y[1] ** 2
+        ])
+
+    def jac(t, y):
+        return np.array([
+            [-0.04, 1e4 * y[2], 1e4 * y[1]],
+            [0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]],
+            [0, 6e7 * y[1], 0]
+        ])
+
+    t = 1
+    y = np.array([1, 0, 0])
+    J_true = jac(t, y)
+    threshold = 1e-5
+    f = fun(t, y).ravel()
+
+    J_num, factor = num_jac(fun, t, y, f, threshold, None)
+    assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
+
+    J_num, factor = num_jac(fun, t, y, f, threshold, factor)
+    assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
+
+
+def test_num_jac_sparse():
+    def fun(t, y):
+        e = y[1:]**3 - y[:-1]**2
+        z = np.zeros(y.shape[1])
+        return np.vstack((z, 3 * e)) + np.vstack((2 * e, z))
+
+    def structure(n):
+        A = np.zeros((n, n), dtype=int)
+        A[0, 0] = 1
+        A[0, 1] = 1
+        for i in range(1, n - 1):
+            A[i, i - 1: i + 2] = 1
+        A[-1, -1] = 1
+        A[-1, -2] = 1
+
+        return A
+
+    np.random.seed(0)
+    n = 20
+    y = np.random.randn(n)
+    A = structure(n)
+    groups = group_columns(A)
+
+    f = fun(0, y[:, None]).ravel()
+
+    # Compare dense and sparse results, assuming that dense implementation
+    # is correct (as it is straightforward).
+    J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, None,
+                                          sparsity=(A, groups))
+    J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, None)
+    assert_allclose(J_num_dense, J_num_sparse.toarray(),
+                    rtol=1e-12, atol=1e-14)
+    assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
+
+    # Take small factors to trigger their recomputing inside.
+    factor = np.random.uniform(0, 1e-12, size=n)
+    J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, factor,
+                                          sparsity=(A, groups))
+    J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, factor)
+
+    assert_allclose(J_num_dense, J_num_sparse.toarray(),
+                    rtol=1e-12, atol=1e-14)
+    assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
+
+
+def test_args():
+
+    # sys3 is actually two decoupled systems. (x, y) form a
+    # linear oscillator, while z is a nonlinear first order
+    # system with equilibria at z=0 and z=1. If k > 0, z=1
+    # is stable and z=0 is unstable.
+
+    def sys3(t, w, omega, k, zfinal):
+        x, y, z = w
+        return [-omega*y, omega*x, k*z*(1 - z)]
+
+    def sys3_jac(t, w, omega, k, zfinal):
+        x, y, z = w
+        J = np.array([[0, -omega, 0],
+                      [omega, 0, 0],
+                      [0, 0, k*(1 - 2*z)]])
+        return J
+
+    def sys3_x0decreasing(t, w, omega, k, zfinal):
+        x, y, z = w
+        return x
+
+    def sys3_y0increasing(t, w, omega, k, zfinal):
+        x, y, z = w
+        return y
+
+    def sys3_zfinal(t, w, omega, k, zfinal):
+        x, y, z = w
+        return z - zfinal
+
+    # Set the event flags for the event functions.
+    sys3_x0decreasing.direction = -1
+    sys3_y0increasing.direction = 1
+    sys3_zfinal.terminal = True
+
+    omega = 2
+    k = 4
+
+    tfinal = 5
+    zfinal = 0.99
+    # Find z0 such that when z(0) = z0, z(tfinal) = zfinal.
+    # The condition z(tfinal) = zfinal is the terminal event.
+    z0 = np.exp(-k*tfinal)/((1 - zfinal)/zfinal + np.exp(-k*tfinal))
+
+    w0 = [0, -1, z0]
+
+    # Provide the jac argument and use the Radau method to ensure that the use
+    # of the Jacobian function is exercised.
+    # If event handling is working, the solution will stop at tfinal, not tend.
+    tend = 2*tfinal
+    sol = solve_ivp(sys3, [0, tend], w0,
+                    events=[sys3_x0decreasing, sys3_y0increasing, sys3_zfinal],
+                    dense_output=True, args=(omega, k, zfinal),
+                    method='Radau', jac=sys3_jac,
+                    rtol=1e-10, atol=1e-13)
+
+    # Check that we got the expected events at the expected times.
+    x0events_t = sol.t_events[0]
+    y0events_t = sol.t_events[1]
+    zfinalevents_t = sol.t_events[2]
+    assert_allclose(x0events_t, [0.5*np.pi, 1.5*np.pi])
+    assert_allclose(y0events_t, [0.25*np.pi, 1.25*np.pi])
+    assert_allclose(zfinalevents_t, [tfinal])
+
+    # Check that the solution agrees with the known exact solution.
+    t = np.linspace(0, zfinalevents_t[0], 250)
+    w = sol.sol(t)
+    assert_allclose(w[0], np.sin(omega*t), rtol=1e-9, atol=1e-12)
+    assert_allclose(w[1], -np.cos(omega*t), rtol=1e-9, atol=1e-12)
+    assert_allclose(w[2], 1/(((1 - z0)/z0)*np.exp(-k*t) + 1),
+                    rtol=1e-9, atol=1e-12)
+
+    # Check that the state variables have the expected values at the events.
+    x0events = sol.sol(x0events_t)
+    y0events = sol.sol(y0events_t)
+    zfinalevents = sol.sol(zfinalevents_t)
+    assert_allclose(x0events[0], np.zeros_like(x0events[0]), atol=5e-14)
+    assert_allclose(x0events[1], np.ones_like(x0events[1]))
+    assert_allclose(y0events[0], np.ones_like(y0events[0]))
+    assert_allclose(y0events[1], np.zeros_like(y0events[1]), atol=5e-14)
+    assert_allclose(zfinalevents[2], [zfinal])
+
+
+@pytest.mark.thread_unsafe
+def test_array_rtol():
+    # solve_ivp had a bug with array_like `rtol`; see gh-15482
+    # check that it's fixed
+    def f(t, y):
+        return y[0], y[1]
+
+    # no warning (or error) when `rtol` is array_like
+    sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-1])
+    err1 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
+
+    # warning when an element of `rtol` is too small
+    with pytest.warns(UserWarning, match="At least one element..."):
+        sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-16])
+        err2 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
+
+    # tighter rtol improves the error
+    assert err2 < err1
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'])
+def test_integration_zero_rhs(method, num_parallel_threads):
+    if method == 'LSODA' and num_parallel_threads > 1:
+        pytest.skip(reason='LSODA does not allow for concurrent execution')
+
+    result = solve_ivp(fun_zero, [0, 10], np.ones(3), method=method)
+    assert_(result.success)
+    assert_equal(result.status, 0)
+    assert_allclose(result.y, 1.0, rtol=1e-15)
+
+
+def test_args_single_value():
+    def fun_with_arg(t, y, a):
+        return a*y
+
+    message = "Supplied 'args' cannot be unpacked."
+    with pytest.raises(TypeError, match=message):
+        solve_ivp(fun_with_arg, (0, 0.1), [1], args=-1)
+
+    sol = solve_ivp(fun_with_arg, (0, 0.1), [1], args=(-1,))
+    assert_allclose(sol.y[0, -1], np.exp(-0.1))
+
+
+@pytest.mark.parametrize("f0_fill", [np.nan, np.inf])
+def test_initial_state_finiteness(f0_fill):
+    # regression test for gh-17846
+    msg = "All components of the initial state `y0` must be finite."
+    with pytest.raises(ValueError, match=msg):
+        solve_ivp(fun_zero, [0, 10], np.full(3, f0_fill))
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_zero_interval(method):
+    # Case where upper and lower limits of integration are the same
+    # Result of integration should match initial state.
+    # f[y(t)] = 2y(t)
+    def f(t, y):
+        return 2 * y
+    res = solve_ivp(f, (0.0, 0.0), np.array([1.0]), method=method)
+    assert res.success
+    assert_allclose(res.y[0, -1], 1.0)
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_tbound_respected_small_interval(method):
+    """Regression test for gh-17341"""
+    SMALL = 1e-4
+
+    # f[y(t)] = 2y(t) on t in [0,SMALL]
+    #           undefined otherwise
+    def f(t, y):
+        if t > SMALL:
+            raise ValueError("Function was evaluated outside interval")
+        return 2 * y
+    res = solve_ivp(f, (0.0, SMALL), np.array([1]), method=method)
+    assert res.success
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_tbound_respected_larger_interval(method):
+    """Regression test for gh-8848"""
+    def V(r):
+        return -11/r + 10 * r / (0.05 + r**2)
+
+    def func(t, p):
+        if t < -17 or t > 2:
+            raise ValueError("Function was evaluated outside interval")
+        P = p[0]
+        Q = p[1]
+        r = np.exp(t)
+        dPdr = r * Q
+        dQdr = -2.0 * r * ((-0.2 - V(r)) * P + 1 / r * Q)
+        return np.array([dPdr, dQdr])
+
+    result = solve_ivp(func,
+                       (-17, 2),
+                       y0=np.array([1, -11]),
+                       max_step=0.03,
+                       vectorized=False,
+                       t_eval=None,
+                       atol=1e-8,
+                       rtol=1e-5)
+    assert result.success
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_tbound_respected_oscillator(method):
+    "Regression test for gh-9198"
+    def reactions_func(t, y):
+        if (t > 205):
+            raise ValueError("Called outside interval")
+        yprime = np.array([1.73307544e-02,
+                           6.49376470e-06,
+                           0.00000000e+00,
+                           0.00000000e+00])
+        return yprime
+
+    def run_sim2(t_end, n_timepoints=10, shortest_delay_line=10000000):
+        init_state = np.array([134.08298555, 138.82348612, 100., 0.])
+        t0 = 100.0
+        t1 = 200.0
+        return solve_ivp(reactions_func,
+                         (t0, t1),
+                         init_state.copy(),
+                         dense_output=True,
+                         max_step=t1 - t0)
+    result = run_sim2(1000, 100, 100)
+    assert result.success
+
+
+def test_inital_maxstep():
+    """Verify that select_inital_step respects max_step"""
+    rtol = 1e-3
+    atol = 1e-6
+    y0 = np.array([1/3, 2/9])
+    for (t0, t_bound) in ((5, 9), (5, 1)):
+        for method_order in [RK23.error_estimator_order,
+                            RK45.error_estimator_order,
+                            DOP853.error_estimator_order,
+                            3, #RADAU
+                            1 #BDF
+                            ]:
+            step_no_max = select_initial_step(fun_rational, t0, y0, t_bound,
+                                            np.inf,
+                                            fun_rational(t0,y0),
+                                            np.sign(t_bound - t0),
+                                            method_order,
+                                            rtol, atol)
+            max_step = step_no_max/2
+            step_with_max = select_initial_step(fun_rational, t0, y0, t_bound,
+                                            max_step,
+                                            fun_rational(t0, y0),
+                                            np.sign(t_bound - t0),
+                                            method_order,
+                                            rtol, atol)
+            assert_equal(max_step, step_with_max)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py
new file mode 100644
index 0000000000000000000000000000000000000000..33cb27d0323d037c0937ab94b4de8f63b46be3d7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py
@@ -0,0 +1,37 @@
+import pytest
+from numpy.testing import assert_allclose, assert_
+import numpy as np
+from scipy.integrate import RK23, RK45, DOP853
+from scipy.integrate._ivp import dop853_coefficients
+
+
+@pytest.mark.parametrize("solver", [RK23, RK45, DOP853])
+def test_coefficient_properties(solver):
+    assert_allclose(np.sum(solver.B), 1, rtol=1e-15)
+    assert_allclose(np.sum(solver.A, axis=1), solver.C, rtol=1e-14)
+
+
+def test_coefficient_properties_dop853():
+    assert_allclose(np.sum(dop853_coefficients.B), 1, rtol=1e-15)
+    assert_allclose(np.sum(dop853_coefficients.A, axis=1),
+                    dop853_coefficients.C,
+                    rtol=1e-14)
+
+
+@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
+def test_error_estimation(solver_class):
+    step = 0.2
+    solver = solver_class(lambda t, y: y, 0, [1], 1, first_step=step)
+    solver.step()
+    error_estimate = solver._estimate_error(solver.K, step)
+    error = solver.y - np.exp([step])
+    assert_(np.abs(error) < np.abs(error_estimate))
+
+
+@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
+def test_error_estimation_complex(solver_class):
+    h = 0.2
+    solver = solver_class(lambda t, y: 1j * y, 0, [1j], 1, first_step=h)
+    solver.step()
+    err_norm = solver._estimate_error_norm(solver.K, h, scale=[1])
+    assert np.isrealobj(err_norm)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_lebedev.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_lebedev.py
new file mode 100644
index 0000000000000000000000000000000000000000..da200972f9d475162f84294ed335149dc86fe94b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_lebedev.py
@@ -0,0 +1,5450 @@
+# getLebedevSphere
+# Copyright (c) 2010, Robert Parrish
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+#     * Redistributions of source code must retain the above copyright
+#       notice, this list of conditions and the following disclaimer.
+#     * Redistributions in binary form must reproduce the above copyright
+#       notice, this list of conditions and the following disclaimer in
+#       the documentation and/or other materials provided with the distribution
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+#
+# Brainlessly translated to Python
+
+import numpy as np
+from numpy import pi, zeros, sqrt
+
+
+__all__ = ['lebedev_rule']
+
+
+def get_lebedev_sphere(degree):
+    # getLebedevSphere
+    # @author Rob Parrish, The Sherrill Group, CCMST Georgia Tech
+    # @email robparrish@gmail.com
+    # @date 03/24/2010
+    #
+    # @description - function to compute normalized points and weights
+    # for Lebedev quadratures on the surface of the unit sphere at double precision.
+    # **********Relative error is generally expected to be ~2.0E-14 [1]********
+    # Lebedev quadratures are superbly accurate and efficient quadrature rules for
+    # approximating integrals of the form $v = \iint_{4\pi}  f(\Omega) \ \ud
+    # \Omega$, where $\Omega is the solid angle on the surface of the unit
+    # sphere. Lebedev quadratures integrate all spherical harmonics up to $l =
+    # order$, where $degree \approx order(order+1)/3$. These grids may be easily
+    # combined with radial quadratures to provide robust cubature formulae. For
+    # example, see 'A. Becke, 1988c, J. Chem. Phys., 88(4), pp. 2547' (The first
+    # paper on tractable molecular Density Functional Theory methods, of which
+    # Lebedev grids and numerical cubature are an intrinsic part).
+    #
+    # @param degree - positive integer specifying number of points in the
+    # requested quadrature. Allowed values are (degree -> order):
+    # degree: { 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302,
+    #   350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074,
+    #   3470, 3890, 4334, 4802, 5294, 5810 }
+    # order: {3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,35,41,47,53,59,65,71,77,
+    #   83,89,95,101,107,113,119,125,131}
+    #
+    #
+    # @return leb_tmp - struct containing fields:
+    #   x - x values of quadrature, constrained to unit sphere
+    #   y - y values of quadrature, constrained to unit sphere
+    #   z - z values of quadrature, constrained to unit sphere
+    #   w - quadrature weights, normalized to $4\pi$.
+    #
+    # @example: $\int_S x^2+y^2-z^2 \ud \Omega = 4.188790204786399$
+    #   f = @(x,y,z) x.^2+y.^2-z.^2
+    #   leb = getLebedevSphere(590)
+    #   v = f(leb.x,leb.y,leb.z)
+    #   int = sum(v.*leb.w)
+    #
+    # @citation - Translated from a Fortran code kindly provided by Christoph van
+    # Wuellen (Ruhr-Universitaet, Bochum, Germany), which in turn came from the
+    # original C routines coded by Dmitri Laikov (Moscow State University,
+    # Moscow, Russia). The MATLAB implementation of this code is designed for
+    # benchmarking of new DFT integration techniques to be implemented in the
+    # open source Psi4 ab initio quantum chemistry program.
+    #
+    # As per Professor Wuellen's request, any papers published using this code
+    # or its derivatives are requested to include the following citation:
+    #
+    # [1] V.I. Lebedev, and D.N. Laikov
+    #    "A quadrature formula for the sphere of the 131st
+    #     algebraic order of accuracy"
+    #    Doklady Mathematics, Vol. 59, No. 3, 1999, pp. 477-481.
+
+    class Leb:
+        x, y, z, w = None, None, None, None
+
+    leb_tmp = Leb()
+
+    leb_tmp.x = zeros(degree)
+    leb_tmp.y = zeros(degree)
+    leb_tmp.z = zeros(degree)
+    leb_tmp.w = zeros(degree)
+
+    start = 0
+    a = 0.0
+    b = 0.0
+
+    match degree:
+
+        case 6:
+
+            v = 0.1666666666666667E+0
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+
+        case 14:
+
+            v = 0.6666666666666667E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7500000000000000E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+
+        case 26:
+
+            v = 0.4761904761904762E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3809523809523810E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.3214285714285714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+
+        case 38:
+
+            v = 0.9523809523809524E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3214285714285714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4597008433809831E+0
+            v = 0.2857142857142857E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 50:
+
+            v = 0.1269841269841270E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2257495590828924E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2109375000000000E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3015113445777636E+0
+            v = 0.2017333553791887E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+
+        case 74:
+
+            v = 0.5130671797338464E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1660406956574204E-1
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = -0.2958603896103896E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4803844614152614E+0
+            v = 0.2657620708215946E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3207726489807764E+0
+            v = 0.1652217099371571E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 86:
+
+            v = 0.1154401154401154E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1194390908585628E-1
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3696028464541502E+0
+            v = 0.1111055571060340E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6943540066026664E+0
+            v = 0.1187650129453714E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3742430390903412E+0
+            v = 0.1181230374690448E-1
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 110:
+
+            v = 0.3828270494937162E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.9793737512487512E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1851156353447362E+0
+            v = 0.8211737283191111E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6904210483822922E+0
+            v = 0.9942814891178103E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3956894730559419E+0
+            v = 0.9595471336070963E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4783690288121502E+0
+            v = 0.9694996361663028E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+
+        case 146:
+
+            v = 0.5996313688621381E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7372999718620756E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.7210515360144488E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6764410400114264E+0
+            v = 0.7116355493117555E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4174961227965453E+0
+            v = 0.6753829486314477E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1574676672039082E+0
+            v = 0.7574394159054034E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1403553811713183E+0
+            b = 0.4493328323269557E+0
+            v = 0.6991087353303262E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 170:
+
+            v = 0.5544842902037365E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.6071332770670752E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.6383674773515093E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2551252621114134E+0
+            v = 0.5183387587747790E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6743601460362766E+0
+            v = 0.6317929009813725E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4318910696719410E+0
+            v = 0.6201670006589077E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2613931360335988E+0
+            v = 0.5477143385137348E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4990453161796037E+0
+            b = 0.1446630744325115E+0
+            v = 0.5968383987681156E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 194:
+
+            v = 0.1782340447244611E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.5716905949977102E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.5573383178848738E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6712973442695226E+0
+            v = 0.5608704082587997E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2892465627575439E+0
+            v = 0.5158237711805383E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4446933178717437E+0
+            v = 0.5518771467273614E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1299335447650067E+0
+            v = 0.4106777028169394E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3457702197611283E+0
+            v = 0.5051846064614808E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1590417105383530E+0
+            b = 0.8360360154824589E+0
+            v = 0.5530248916233094E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 230:
+
+            v = -0.5522639919727325E-1
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4450274607445226E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4492044687397611E+0
+            v = 0.4496841067921404E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2520419490210201E+0
+            v = 0.5049153450478750E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6981906658447242E+0
+            v = 0.3976408018051883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6587405243460960E+0
+            v = 0.4401400650381014E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4038544050097660E-1
+            v = 0.1724544350544401E-1
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5823842309715585E+0
+            v = 0.4231083095357343E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3545877390518688E+0
+            v = 0.5198069864064399E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2272181808998187E+0
+            b = 0.4864661535886647E+0
+            v = 0.4695720972568883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 266:
+
+            v = -0.1313769127326952E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = -0.2522728704859336E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.4186853881700583E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7039373391585475E+0
+            v = 0.5315167977810885E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1012526248572414E+0
+            v = 0.4047142377086219E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4647448726420539E+0
+            v = 0.4112482394406990E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3277420654971629E+0
+            v = 0.3595584899758782E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6620338663699974E+0
+            v = 0.4256131351428158E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8506508083520399E+0
+            v = 0.4229582700647240E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3233484542692899E+0
+            b = 0.1153112011009701E+0
+            v = 0.4080914225780505E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2314790158712601E+0
+            b = 0.5244939240922365E+0
+            v = 0.4071467593830964E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 302:
+
+            v = 0.8545911725128148E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3599119285025571E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3515640345570105E+0
+            v = 0.3449788424305883E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6566329410219612E+0
+            v = 0.3604822601419882E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4729054132581005E+0
+            v = 0.3576729661743367E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9618308522614784E-1
+            v = 0.2352101413689164E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2219645236294178E+0
+            v = 0.3108953122413675E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7011766416089545E+0
+            v = 0.3650045807677255E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2644152887060663E+0
+            v = 0.2982344963171804E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5718955891878961E+0
+            v = 0.3600820932216460E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2510034751770465E+0
+            b = 0.8000727494073952E+0
+            v = 0.3571540554273387E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1233548532583327E+0
+            b = 0.4127724083168531E+0
+            v = 0.3392312205006170E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 350:
+
+            v = 0.3006796749453936E-2
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3050627745650771E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7068965463912316E+0
+            v = 0.1621104600288991E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4794682625712025E+0
+            v = 0.3005701484901752E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1927533154878019E+0
+            v = 0.2990992529653774E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6930357961327123E+0
+            v = 0.2982170644107595E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3608302115520091E+0
+            v = 0.2721564237310992E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6498486161496169E+0
+            v = 0.3033513795811141E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1932945013230339E+0
+            v = 0.3007949555218533E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3800494919899303E+0
+            v = 0.2881964603055307E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2899558825499574E+0
+            b = 0.7934537856582316E+0
+            v = 0.2958357626535696E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9684121455103957E-1
+            b = 0.8280801506686862E+0
+            v = 0.3036020026407088E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1833434647041659E+0
+            b = 0.9074658265305127E+0
+            v = 0.2832187403926303E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 434:
+
+            v = 0.5265897968224436E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2548219972002607E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2512317418927307E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.6909346307509111E+0
+            v = 0.2530403801186355E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1774836054609158E+0
+            v = 0.2014279020918528E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4914342637784746E+0
+            v = 0.2501725168402936E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6456664707424256E+0
+            v = 0.2513267174597564E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2861289010307638E+0
+            v = 0.2302694782227416E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7568084367178018E-1
+            v = 0.1462495621594614E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3927259763368002E+0
+            v = 0.2445373437312980E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8818132877794288E+0
+            v = 0.2417442375638981E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9776428111182649E+0
+            v = 0.1910951282179532E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2054823696403044E+0
+            b = 0.8689460322872412E+0
+            v = 0.2416930044324775E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5905157048925271E+0
+            b = 0.7999278543857286E+0
+            v = 0.2512236854563495E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5550152361076807E+0
+            b = 0.7717462626915901E+0
+            v = 0.2496644054553086E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9371809858553722E+0
+            b = 0.3344363145343455E+0
+            v = 0.2236607760437849E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 590:
+
+            v = 0.3095121295306187E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1852379698597489E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.7040954938227469E+0
+            v = 0.1871790639277744E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6807744066455243E+0
+            v = 0.1858812585438317E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6372546939258752E+0
+            v = 0.1852028828296213E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5044419707800358E+0
+            v = 0.1846715956151242E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4215761784010967E+0
+            v = 0.1818471778162769E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3317920736472123E+0
+            v = 0.1749564657281154E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2384736701421887E+0
+            v = 0.1617210647254411E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1459036449157763E+0
+            v = 0.1384737234851692E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6095034115507196E-1
+            v = 0.9764331165051050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6116843442009876E+0
+            v = 0.1857161196774078E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3964755348199858E+0
+            v = 0.1705153996395864E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1724782009907724E+0
+            v = 0.1300321685886048E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5610263808622060E+0
+            b = 0.3518280927733519E+0
+            v = 0.1842866472905286E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4742392842551980E+0
+            b = 0.2634716655937950E+0
+            v = 0.1802658934377451E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5984126497885380E+0
+            b = 0.1816640840360209E+0
+            v = 0.1849830560443660E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3791035407695563E+0
+            b = 0.1720795225656878E+0
+            v = 0.1713904507106709E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2778673190586244E+0
+            b = 0.8213021581932511E-1
+            v = 0.1555213603396808E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5033564271075117E+0
+            b = 0.8999205842074875E-1
+            v = 0.1802239128008525E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 770:
+
+            v = 0.2192942088181184E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1436433617319080E-2
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.1421940344335877E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.5087204410502360E-1
+            v = 0.6798123511050502E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1228198790178831E+0
+            v = 0.9913184235294912E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2026890814408786E+0
+            v = 0.1180207833238949E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2847745156464294E+0
+            v = 0.1296599602080921E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3656719078978026E+0
+            v = 0.1365871427428316E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4428264886713469E+0
+            v = 0.1402988604775325E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5140619627249735E+0
+            v = 0.1418645563595609E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6306401219166803E+0
+            v = 0.1421376741851662E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6716883332022612E+0
+            v = 0.1423996475490962E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6979792685336881E+0
+            v = 0.1431554042178567E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1446865674195309E+0
+            v = 0.9254401499865368E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3390263475411216E+0
+            v = 0.1250239995053509E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5335804651263506E+0
+            v = 0.1394365843329230E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6944024393349413E-1
+            b = 0.2355187894242326E+0
+            v = 0.1127089094671749E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2269004109529460E+0
+            b = 0.4102182474045730E+0
+            v = 0.1345753760910670E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8025574607775339E-1
+            b = 0.6214302417481605E+0
+            v = 0.1424957283316783E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1467999527896572E+0
+            b = 0.3245284345717394E+0
+            v = 0.1261523341237750E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1571507769824727E+0
+            b = 0.5224482189696630E+0
+            v = 0.1392547106052696E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2365702993157246E+0
+            b = 0.6017546634089558E+0
+            v = 0.1418761677877656E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7714815866765732E-1
+            b = 0.4346575516141163E+0
+            v = 0.1338366684479554E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3062936666210730E+0
+            b = 0.4908826589037616E+0
+            v = 0.1393700862676131E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3822477379524787E+0
+            b = 0.5648768149099500E+0
+            v = 0.1415914757466932E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 974:
+
+            v = 0.1438294190527431E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1125772288287004E-2
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.4292963545341347E-1
+            v = 0.4948029341949241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1051426854086404E+0
+            v = 0.7357990109125470E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1750024867623087E+0
+            v = 0.8889132771304384E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2477653379650257E+0
+            v = 0.9888347838921435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3206567123955957E+0
+            v = 0.1053299681709471E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3916520749849983E+0
+            v = 0.1092778807014578E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4590825874187624E+0
+            v = 0.1114389394063227E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5214563888415861E+0
+            v = 0.1123724788051555E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6253170244654199E+0
+            v = 0.1125239325243814E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6637926744523170E+0
+            v = 0.1126153271815905E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6910410398498301E+0
+            v = 0.1130286931123841E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7052907007457760E+0
+            v = 0.1134986534363955E-2
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1236686762657990E+0
+            v = 0.6823367927109931E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2940777114468387E+0
+            v = 0.9454158160447096E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4697753849207649E+0
+            v = 0.1074429975385679E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6334563241139567E+0
+            v = 0.1129300086569132E-2
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5974048614181342E-1
+            b = 0.2029128752777523E+0
+            v = 0.8436884500901954E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1375760408473636E+0
+            b = 0.4602621942484054E+0
+            v = 0.1075255720448885E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3391016526336286E+0
+            b = 0.5030673999662036E+0
+            v = 0.1108577236864462E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1271675191439820E+0
+            b = 0.2817606422442134E+0
+            v = 0.9566475323783357E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2693120740413512E+0
+            b = 0.4331561291720157E+0
+            v = 0.1080663250717391E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1419786452601918E+0
+            b = 0.6256167358580814E+0
+            v = 0.1126797131196295E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6709284600738255E-1
+            b = 0.3798395216859157E+0
+            v = 0.1022568715358061E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7057738183256172E-1
+            b = 0.5517505421423520E+0
+            v = 0.1108960267713108E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2783888477882155E+0
+            b = 0.6029619156159187E+0
+            v = 0.1122790653435766E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1979578938917407E+0
+            b = 0.3589606329589096E+0
+            v = 0.1032401847117460E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2087307061103274E+0
+            b = 0.5348666438135476E+0
+            v = 0.1107249382283854E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4055122137872836E+0
+            b = 0.5674997546074373E+0
+            v = 0.1121780048519972E-2
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1202:
+
+            v = 0.1105189233267572E-3
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.9205232738090741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.9133159786443561E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3712636449657089E-1
+            v = 0.3690421898017899E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9140060412262223E-1
+            v = 0.5603990928680660E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1531077852469906E+0
+            v = 0.6865297629282609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2180928891660612E+0
+            v = 0.7720338551145630E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2839874532200175E+0
+            v = 0.8301545958894795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3491177600963764E+0
+            v = 0.8686692550179628E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4121431461444309E+0
+            v = 0.8927076285846890E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4718993627149127E+0
+            v = 0.9060820238568219E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5273145452842337E+0
+            v = 0.9119777254940867E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6209475332444019E+0
+            v = 0.9128720138604181E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6569722711857291E+0
+            v = 0.9130714935691735E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6841788309070143E+0
+            v = 0.9152873784554116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012604330123631E+0
+            v = 0.9187436274321654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1072382215478166E+0
+            v = 0.5176977312965694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2582068959496968E+0
+            v = 0.7331143682101417E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4172752955306717E+0
+            v = 0.8463232836379928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5700366911792503E+0
+            v = 0.9031122694253992E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9827986018263947E+0
+            b = 0.1771774022615325E+0
+            v = 0.6485778453163257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9624249230326228E+0
+            b = 0.2475716463426288E+0
+            v = 0.7435030910982369E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9402007994128811E+0
+            b = 0.3354616289066489E+0
+            v = 0.7998527891839054E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9320822040143202E+0
+            b = 0.3173615246611977E+0
+            v = 0.8101731497468018E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9043674199393299E+0
+            b = 0.4090268427085357E+0
+            v = 0.8483389574594331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8912407560074747E+0
+            b = 0.3854291150669224E+0
+            v = 0.8556299257311812E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8676435628462708E+0
+            b = 0.4932221184851285E+0
+            v = 0.8803208679738260E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8581979986041619E+0
+            b = 0.4785320675922435E+0
+            v = 0.8811048182425720E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8396753624049856E+0
+            b = 0.4507422593157064E+0
+            v = 0.8850282341265444E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8165288564022188E+0
+            b = 0.5632123020762100E+0
+            v = 0.9021342299040653E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8015469370783529E+0
+            b = 0.5434303569693900E+0
+            v = 0.9010091677105086E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7773563069070351E+0
+            b = 0.5123518486419871E+0
+            v = 0.9022692938426915E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7661621213900394E+0
+            b = 0.6394279634749102E+0
+            v = 0.9158016174693465E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7553584143533510E+0
+            b = 0.6269805509024392E+0
+            v = 0.9131578003189435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7344305757559503E+0
+            b = 0.6031161693096310E+0
+            v = 0.9107813579482705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.7043837184021765E+0
+            b = 0.5693702498468441E+0
+            v = 0.9105760258970126E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1454:
+
+            v = 0.7777160743261247E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.7557646413004701E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.3229290663413854E-1
+            v = 0.2841633806090617E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8036733271462222E-1
+            v = 0.4374419127053555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1354289960531653E+0
+            v = 0.5417174740872172E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1938963861114426E+0
+            v = 0.6148000891358593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2537343715011275E+0
+            v = 0.6664394485800705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3135251434752570E+0
+            v = 0.7025039356923220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3721558339375338E+0
+            v = 0.7268511789249627E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4286809575195696E+0
+            v = 0.7422637534208629E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4822510128282994E+0
+            v = 0.7509545035841214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5320679333566263E+0
+            v = 0.7548535057718401E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6172998195394274E+0
+            v = 0.7554088969774001E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6510679849127481E+0
+            v = 0.7553147174442808E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6777315251687360E+0
+            v = 0.7564767653292297E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6963109410648741E+0
+            v = 0.7587991808518730E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7058935009831749E+0
+            v = 0.7608261832033027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9955546194091857E+0
+            v = 0.4021680447874916E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9734115901794209E+0
+            v = 0.5804871793945964E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9275693732388626E+0
+            v = 0.6792151955945159E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8568022422795103E+0
+            v = 0.7336741211286294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7623495553719372E+0
+            v = 0.7581866300989608E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5707522908892223E+0
+            b = 0.4387028039889501E+0
+            v = 0.7538257859800743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5196463388403083E+0
+            b = 0.3858908414762617E+0
+            v = 0.7483517247053123E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4646337531215351E+0
+            b = 0.3301937372343854E+0
+            v = 0.7371763661112059E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4063901697557691E+0
+            b = 0.2725423573563777E+0
+            v = 0.7183448895756934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3456329466643087E+0
+            b = 0.2139510237495250E+0
+            v = 0.6895815529822191E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2831395121050332E+0
+            b = 0.1555922309786647E+0
+            v = 0.6480105801792886E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2197682022925330E+0
+            b = 0.9892878979686097E-1
+            v = 0.5897558896594636E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1564696098650355E+0
+            b = 0.4598642910675510E-1
+            v = 0.5095708849247346E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6027356673721295E+0
+            b = 0.3376625140173426E+0
+            v = 0.7536906428909755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5496032320255096E+0
+            b = 0.2822301309727988E+0
+            v = 0.7472505965575118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4921707755234567E+0
+            b = 0.2248632342592540E+0
+            v = 0.7343017132279698E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4309422998598483E+0
+            b = 0.1666224723456479E+0
+            v = 0.7130871582177445E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3664108182313672E+0
+            b = 0.1086964901822169E+0
+            v = 0.6817022032112776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2990189057758436E+0
+            b = 0.5251989784120085E-1
+            v = 0.6380941145604121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6268724013144998E+0
+            b = 0.2297523657550023E+0
+            v = 0.7550381377920310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5707324144834607E+0
+            b = 0.1723080607093800E+0
+            v = 0.7478646640144802E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5096360901960365E+0
+            b = 0.1140238465390513E+0
+            v = 0.7335918720601220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4438729938312456E+0
+            b = 0.5611522095882537E-1
+            v = 0.7110120527658118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6419978471082389E+0
+            b = 0.1164174423140873E+0
+            v = 0.7571363978689501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5817218061802611E+0
+            b = 0.5797589531445219E-1
+            v = 0.7489908329079234E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 1730:
+
+            v = 0.6309049437420976E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.6398287705571748E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.6357185073530720E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2860923126194662E-1
+            v = 0.2221207162188168E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7142556767711522E-1
+            v = 0.3475784022286848E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1209199540995559E+0
+            v = 0.4350742443589804E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1738673106594379E+0
+            v = 0.4978569136522127E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2284645438467734E+0
+            v = 0.5435036221998053E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2834807671701512E+0
+            v = 0.5765913388219542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3379680145467339E+0
+            v = 0.6001200359226003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3911355454819537E+0
+            v = 0.6162178172717512E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4422860353001403E+0
+            v = 0.6265218152438485E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4907781568726057E+0
+            v = 0.6323987160974212E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5360006153211468E+0
+            v = 0.6350767851540569E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6142105973596603E+0
+            v = 0.6354362775297107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6459300387977504E+0
+            v = 0.6352302462706235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718056125089225E+0
+            v = 0.6358117881417972E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6910888533186254E+0
+            v = 0.6373101590310117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7030467416823252E+0
+            v = 0.6390428961368665E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8354951166354646E-1
+            v = 0.3186913449946576E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2050143009099486E+0
+            v = 0.4678028558591711E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3370208290706637E+0
+            v = 0.5538829697598626E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4689051484233963E+0
+            v = 0.6044475907190476E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5939400424557334E+0
+            v = 0.6313575103509012E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1394983311832261E+0
+            b = 0.4097581162050343E-1
+            v = 0.4078626431855630E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1967999180485014E+0
+            b = 0.8851987391293348E-1
+            v = 0.4759933057812725E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2546183732548967E+0
+            b = 0.1397680182969819E+0
+            v = 0.5268151186413440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3121281074713875E+0
+            b = 0.1929452542226526E+0
+            v = 0.5643048560507316E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3685981078502492E+0
+            b = 0.2467898337061562E+0
+            v = 0.5914501076613073E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4233760321547856E+0
+            b = 0.3003104124785409E+0
+            v = 0.6104561257874195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4758671236059246E+0
+            b = 0.3526684328175033E+0
+            v = 0.6230252860707806E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5255178579796463E+0
+            b = 0.4031134861145713E+0
+            v = 0.6305618761760796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5718025633734589E+0
+            b = 0.4509426448342351E+0
+            v = 0.6343092767597889E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2686927772723415E+0
+            b = 0.4711322502423248E-1
+            v = 0.5176268945737826E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3306006819904809E+0
+            b = 0.9784487303942695E-1
+            v = 0.5564840313313692E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3904906850594983E+0
+            b = 0.1505395810025273E+0
+            v = 0.5856426671038980E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4479957951904390E+0
+            b = 0.2039728156296050E+0
+            v = 0.6066386925777091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5027076848919780E+0
+            b = 0.2571529941121107E+0
+            v = 0.6208824962234458E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5542087392260217E+0
+            b = 0.3092191375815670E+0
+            v = 0.6296314297822907E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6020850887375187E+0
+            b = 0.3593807506130276E+0
+            v = 0.6340423756791859E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4019851409179594E+0
+            b = 0.5063389934378671E-1
+            v = 0.5829627677107342E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4635614567449800E+0
+            b = 0.1032422269160612E+0
+            v = 0.6048693376081110E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5215860931591575E+0
+            b = 0.1566322094006254E+0
+            v = 0.6202362317732461E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5758202499099271E+0
+            b = 0.2098082827491099E+0
+            v = 0.6299005328403779E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6259893683876795E+0
+            b = 0.2618824114553391E+0
+            v = 0.6347722390609353E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5313795124811891E+0
+            b = 0.5263245019338556E-1
+            v = 0.6203778981238834E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5893317955931995E+0
+            b = 0.1061059730982005E+0
+            v = 0.6308414671239979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6426246321215801E+0
+            b = 0.1594171564034221E+0
+            v = 0.6362706466959498E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6511904367376113E+0
+            b = 0.5354789536565540E-1
+            v = 0.6375414170333233E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2030:
+
+            v = 0.4656031899197431E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.5421549195295507E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2540835336814348E-1
+            v = 0.1778522133346553E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6399322800504915E-1
+            v = 0.2811325405682796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1088269469804125E+0
+            v = 0.3548896312631459E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1570670798818287E+0
+            v = 0.4090310897173364E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2071163932282514E+0
+            v = 0.4493286134169965E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2578914044450844E+0
+            v = 0.4793728447962723E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3085687558169623E+0
+            v = 0.5015415319164265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3584719706267024E+0
+            v = 0.5175127372677937E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4070135594428709E+0
+            v = 0.5285522262081019E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4536618626222638E+0
+            v = 0.5356832703713962E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4979195686463577E+0
+            v = 0.5397914736175170E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5393075111126999E+0
+            v = 0.5416899441599930E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6115617676843916E+0
+            v = 0.5419308476889938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6414308435160159E+0
+            v = 0.5416936902030596E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6664099412721607E+0
+            v = 0.5419544338703164E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6859161771214913E+0
+            v = 0.5428983656630975E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6993625593503890E+0
+            v = 0.5442286500098193E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7062393387719380E+0
+            v = 0.5452250345057301E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7479028168349763E-1
+            v = 0.2568002497728530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1848951153969366E+0
+            v = 0.3827211700292145E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3059529066581305E+0
+            v = 0.4579491561917824E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4285556101021362E+0
+            v = 0.5042003969083574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5468758653496526E+0
+            v = 0.5312708889976025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6565821978343439E+0
+            v = 0.5438401790747117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1253901572367117E+0
+            b = 0.3681917226439641E-1
+            v = 0.3316041873197344E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1775721510383941E+0
+            b = 0.7982487607213301E-1
+            v = 0.3899113567153771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2305693358216114E+0
+            b = 0.1264640966592335E+0
+            v = 0.4343343327201309E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2836502845992063E+0
+            b = 0.1751585683418957E+0
+            v = 0.4679415262318919E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3361794746232590E+0
+            b = 0.2247995907632670E+0
+            v = 0.4930847981631031E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3875979172264824E+0
+            b = 0.2745299257422246E+0
+            v = 0.5115031867540091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4374019316999074E+0
+            b = 0.3236373482441118E+0
+            v = 0.5245217148457367E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4851275843340022E+0
+            b = 0.3714967859436741E+0
+            v = 0.5332041499895321E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5303391803806868E+0
+            b = 0.4175353646321745E+0
+            v = 0.5384583126021542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726197380596287E+0
+            b = 0.4612084406355461E+0
+            v = 0.5411067210798852E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2431520732564863E+0
+            b = 0.4258040133043952E-1
+            v = 0.4259797391468714E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3002096800895869E+0
+            b = 0.8869424306722721E-1
+            v = 0.4604931368460021E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3558554457457432E+0
+            b = 0.1368811706510655E+0
+            v = 0.4871814878255202E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4097782537048887E+0
+            b = 0.1860739985015033E+0
+            v = 0.5072242910074885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4616337666067458E+0
+            b = 0.2354235077395853E+0
+            v = 0.5217069845235350E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5110707008417874E+0
+            b = 0.2842074921347011E+0
+            v = 0.5315785966280310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5577415286163795E+0
+            b = 0.3317784414984102E+0
+            v = 0.5376833708758905E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6013060431366950E+0
+            b = 0.3775299002040700E+0
+            v = 0.5408032092069521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3661596767261781E+0
+            b = 0.4599367887164592E-1
+            v = 0.4842744917904866E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4237633153506581E+0
+            b = 0.9404893773654421E-1
+            v = 0.5048926076188130E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4786328454658452E+0
+            b = 0.1431377109091971E+0
+            v = 0.5202607980478373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5305702076789774E+0
+            b = 0.1924186388843570E+0
+            v = 0.5309932388325743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5793436224231788E+0
+            b = 0.2411590944775190E+0
+            v = 0.5377419770895208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6247069017094747E+0
+            b = 0.2886871491583605E+0
+            v = 0.5411696331677717E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4874315552535204E+0
+            b = 0.4804978774953206E-1
+            v = 0.5197996293282420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5427337322059053E+0
+            b = 0.9716857199366665E-1
+            v = 0.5311120836622945E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5943493747246700E+0
+            b = 0.1465205839795055E+0
+            v = 0.5384309319956951E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6421314033564943E+0
+            b = 0.1953579449803574E+0
+            v = 0.5421859504051886E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6020628374713980E+0
+            b = 0.4916375015738108E-1
+            v = 0.5390948355046314E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6529222529856881E+0
+            b = 0.9861621540127005E-1
+            v = 0.5433312705027845E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2354:
+
+            v = 0.3922616270665292E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4703831750854424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.4678202801282136E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2290024646530589E-1
+            v = 0.1437832228979900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5779086652271284E-1
+            v = 0.2303572493577644E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9863103576375984E-1
+            v = 0.2933110752447454E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1428155792982185E+0
+            v = 0.3402905998359838E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1888978116601463E+0
+            v = 0.3759138466870372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2359091682970210E+0
+            v = 0.4030638447899798E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2831228833706171E+0
+            v = 0.4236591432242211E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3299495857966693E+0
+            v = 0.4390522656946746E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3758840802660796E+0
+            v = 0.4502523466626247E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4204751831009480E+0
+            v = 0.4580577727783541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4633068518751051E+0
+            v = 0.4631391616615899E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5039849474507313E+0
+            v = 0.4660928953698676E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5421265793440747E+0
+            v = 0.4674751807936953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6092660230557310E+0
+            v = 0.4676414903932920E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6374654204984869E+0
+            v = 0.4674086492347870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6615136472609892E+0
+            v = 0.4674928539483207E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6809487285958127E+0
+            v = 0.4680748979686447E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6952980021665196E+0
+            v = 0.4690449806389040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7041245497695400E+0
+            v = 0.4699877075860818E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6744033088306065E-1
+            v = 0.2099942281069176E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1678684485334166E+0
+            v = 0.3172269150712804E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2793559049539613E+0
+            v = 0.3832051358546523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3935264218057639E+0
+            v = 0.4252193818146985E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5052629268232558E+0
+            v = 0.4513807963755000E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6107905315437531E+0
+            v = 0.4657797469114178E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1135081039843524E+0
+            b = 0.3331954884662588E-1
+            v = 0.2733362800522836E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1612866626099378E+0
+            b = 0.7247167465436538E-1
+            v = 0.3235485368463559E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2100786550168205E+0
+            b = 0.1151539110849745E+0
+            v = 0.3624908726013453E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2592282009459942E+0
+            b = 0.1599491097143677E+0
+            v = 0.3925540070712828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3081740561320203E+0
+            b = 0.2058699956028027E+0
+            v = 0.4156129781116235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3564289781578164E+0
+            b = 0.2521624953502911E+0
+            v = 0.4330644984623263E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4035587288240703E+0
+            b = 0.2982090785797674E+0
+            v = 0.4459677725921312E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4491671196373903E+0
+            b = 0.3434762087235733E+0
+            v = 0.4551593004456795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4928854782917489E+0
+            b = 0.3874831357203437E+0
+            v = 0.4613341462749918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5343646791958988E+0
+            b = 0.4297814821746926E+0
+            v = 0.4651019618269806E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5732683216530990E+0
+            b = 0.4699402260943537E+0
+            v = 0.4670249536100625E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2214131583218986E+0
+            b = 0.3873602040643895E-1
+            v = 0.3549555576441708E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2741796504750071E+0
+            b = 0.8089496256902013E-1
+            v = 0.3856108245249010E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3259797439149485E+0
+            b = 0.1251732177620872E+0
+            v = 0.4098622845756882E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3765441148826891E+0
+            b = 0.1706260286403185E+0
+            v = 0.4286328604268950E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4255773574530558E+0
+            b = 0.2165115147300408E+0
+            v = 0.4427802198993945E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4727795117058430E+0
+            b = 0.2622089812225259E+0
+            v = 0.4530473511488561E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5178546895819012E+0
+            b = 0.3071721431296201E+0
+            v = 0.4600805475703138E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5605141192097460E+0
+            b = 0.3508998998801138E+0
+            v = 0.4644599059958017E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6004763319352512E+0
+            b = 0.3929160876166931E+0
+            v = 0.4667274455712508E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3352842634946949E+0
+            b = 0.4202563457288019E-1
+            v = 0.4069360518020356E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3891971629814670E+0
+            b = 0.8614309758870850E-1
+            v = 0.4260442819919195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4409875565542281E+0
+            b = 0.1314500879380001E+0
+            v = 0.4408678508029063E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4904893058592484E+0
+            b = 0.1772189657383859E+0
+            v = 0.4518748115548597E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5375056138769549E+0
+            b = 0.2228277110050294E+0
+            v = 0.4595564875375116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5818255708669969E+0
+            b = 0.2677179935014386E+0
+            v = 0.4643988774315846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6232334858144959E+0
+            b = 0.3113675035544165E+0
+            v = 0.4668827491646946E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4489485354492058E+0
+            b = 0.4409162378368174E-1
+            v = 0.4400541823741973E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5015136875933150E+0
+            b = 0.8939009917748489E-1
+            v = 0.4514512890193797E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5511300550512623E+0
+            b = 0.1351806029383365E+0
+            v = 0.4596198627347549E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5976720409858000E+0
+            b = 0.1808370355053196E+0
+            v = 0.4648659016801781E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6409956378989354E+0
+            b = 0.2257852192301602E+0
+            v = 0.4675502017157673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5581222330827514E+0
+            b = 0.4532173421637160E-1
+            v = 0.4598494476455523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6074705984161695E+0
+            b = 0.9117488031840314E-1
+            v = 0.4654916955152048E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6532272537379033E+0
+            b = 0.1369294213140155E+0
+            v = 0.4684709779505137E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6594761494500487E+0
+            b = 0.4589901487275583E-1
+            v = 0.4691445539106986E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 2702:
+
+            v = 0.2998675149888161E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.4077860529495355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2065562538818703E-1
+            v = 0.1185349192520667E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5250918173022379E-1
+            v = 0.1913408643425751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8993480082038376E-1
+            v = 0.2452886577209897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1306023924436019E+0
+            v = 0.2862408183288702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1732060388531418E+0
+            v = 0.3178032258257357E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2168727084820249E+0
+            v = 0.3422945667633690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2609528309173586E+0
+            v = 0.3612790520235922E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3049252927938952E+0
+            v = 0.3758638229818521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3483484138084404E+0
+            v = 0.3868711798859953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3908321549106406E+0
+            v = 0.3949429933189938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4320210071894814E+0
+            v = 0.4006068107541156E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4715824795890053E+0
+            v = 0.4043192149672723E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5091984794078453E+0
+            v = 0.4064947495808078E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5445580145650803E+0
+            v = 0.4075245619813152E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6072575796841768E+0
+            v = 0.4076423540893566E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6339484505755803E+0
+            v = 0.4074280862251555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6570718257486958E+0
+            v = 0.4074163756012244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6762557330090709E+0
+            v = 0.4077647795071246E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911161696923790E+0
+            v = 0.4084517552782530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012841911659961E+0
+            v = 0.4092468459224052E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7064559272410020E+0
+            v = 0.4097872687240906E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6123554989894765E-1
+            v = 0.1738986811745028E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1533070348312393E+0
+            v = 0.2659616045280191E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2563902605244206E+0
+            v = 0.3240596008171533E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3629346991663361E+0
+            v = 0.3621195964432943E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4683949968987538E+0
+            v = 0.3868838330760539E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5694479240657952E+0
+            v = 0.4018911532693111E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6634465430993955E+0
+            v = 0.4089929432983252E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1033958573552305E+0
+            b = 0.3034544009063584E-1
+            v = 0.2279907527706409E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1473521412414395E+0
+            b = 0.6618803044247135E-1
+            v = 0.2715205490578897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1924552158705967E+0
+            b = 0.1054431128987715E+0
+            v = 0.3057917896703976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2381094362890328E+0
+            b = 0.1468263551238858E+0
+            v = 0.3326913052452555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838121707936760E+0
+            b = 0.1894486108187886E+0
+            v = 0.3537334711890037E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3291323133373415E+0
+            b = 0.2326374238761579E+0
+            v = 0.3700567500783129E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3736896978741460E+0
+            b = 0.2758485808485768E+0
+            v = 0.3825245372589122E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4171406040760013E+0
+            b = 0.3186179331996921E+0
+            v = 0.3918125171518296E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4591677985256915E+0
+            b = 0.3605329796303794E+0
+            v = 0.3984720419937579E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4994733831718418E+0
+            b = 0.4012147253586509E+0
+            v = 0.4029746003338211E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5377731830445096E+0
+            b = 0.4403050025570692E+0
+            v = 0.4057428632156627E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5737917830001331E+0
+            b = 0.4774565904277483E+0
+            v = 0.4071719274114857E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2027323586271389E+0
+            b = 0.3544122504976147E-1
+            v = 0.2990236950664119E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2516942375187273E+0
+            b = 0.7418304388646328E-1
+            v = 0.3262951734212878E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3000227995257181E+0
+            b = 0.1150502745727186E+0
+            v = 0.3482634608242413E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3474806691046342E+0
+            b = 0.1571963371209364E+0
+            v = 0.3656596681700892E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3938103180359209E+0
+            b = 0.1999631877247100E+0
+            v = 0.3791740467794218E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4387519590455703E+0
+            b = 0.2428073457846535E+0
+            v = 0.3894034450156905E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4820503960077787E+0
+            b = 0.2852575132906155E+0
+            v = 0.3968600245508371E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5234573778475101E+0
+            b = 0.3268884208674639E+0
+            v = 0.4019931351420050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5627318647235282E+0
+            b = 0.3673033321675939E+0
+            v = 0.4052108801278599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5996390607156954E+0
+            b = 0.4061211551830290E+0
+            v = 0.4068978613940934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3084780753791947E+0
+            b = 0.3860125523100059E-1
+            v = 0.3454275351319704E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3589988275920223E+0
+            b = 0.7928938987104867E-1
+            v = 0.3629963537007920E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4078628415881973E+0
+            b = 0.1212614643030087E+0
+            v = 0.3770187233889873E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4549287258889735E+0
+            b = 0.1638770827382693E+0
+            v = 0.3878608613694378E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5000278512957279E+0
+            b = 0.2065965798260176E+0
+            v = 0.3959065270221274E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5429785044928199E+0
+            b = 0.2489436378852235E+0
+            v = 0.4015286975463570E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5835939850491711E+0
+            b = 0.2904811368946891E+0
+            v = 0.4050866785614717E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6216870353444856E+0
+            b = 0.3307941957666609E+0
+            v = 0.4069320185051913E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4151104662709091E+0
+            b = 0.4064829146052554E-1
+            v = 0.3760120964062763E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4649804275009218E+0
+            b = 0.8258424547294755E-1
+            v = 0.3870969564418064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5124695757009662E+0
+            b = 0.1251841962027289E+0
+            v = 0.3955287790534055E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5574711100606224E+0
+            b = 0.1679107505976331E+0
+            v = 0.4015361911302668E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5998597333287227E+0
+            b = 0.2102805057358715E+0
+            v = 0.4053836986719548E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6395007148516600E+0
+            b = 0.2518418087774107E+0
+            v = 0.4073578673299117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5188456224746252E+0
+            b = 0.4194321676077518E-1
+            v = 0.3954628379231406E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5664190707942778E+0
+            b = 0.8457661551921499E-1
+            v = 0.4017645508847530E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6110464353283153E+0
+            b = 0.1273652932519396E+0
+            v = 0.4059030348651293E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6526430302051563E+0
+            b = 0.1698173239076354E+0
+            v = 0.4080565809484880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6167551880377548E+0
+            b = 0.4266398851548864E-1
+            v = 0.4063018753664651E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6607195418355383E+0
+            b = 0.8551925814238349E-1
+            v = 0.4087191292799671E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3074:
+
+            v = 0.2599095953754734E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3603134089687541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.3586067974412447E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1886108518723392E-1
+            v = 0.9831528474385880E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4800217244625303E-1
+            v = 0.1605023107954450E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8244922058397242E-1
+            v = 0.2072200131464099E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1200408362484023E+0
+            v = 0.2431297618814187E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1595773530809965E+0
+            v = 0.2711819064496707E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2002635973434064E+0
+            v = 0.2932762038321116E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2415127590139982E+0
+            v = 0.3107032514197368E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2828584158458477E+0
+            v = 0.3243808058921213E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3239091015338138E+0
+            v = 0.3349899091374030E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3643225097962194E+0
+            v = 0.3430580688505218E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4037897083691802E+0
+            v = 0.3490124109290343E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4420247515194127E+0
+            v = 0.3532148948561955E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4787572538464938E+0
+            v = 0.3559862669062833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5137265251275234E+0
+            v = 0.3576224317551411E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5466764056654611E+0
+            v = 0.3584050533086076E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6054859420813535E+0
+            v = 0.3584903581373224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6308106701764562E+0
+            v = 0.3582991879040586E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6530369230179584E+0
+            v = 0.3582371187963125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718609524611158E+0
+            v = 0.3584353631122350E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6869676499894013E+0
+            v = 0.3589120166517785E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6980467077240748E+0
+            v = 0.3595445704531601E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7048241721250522E+0
+            v = 0.3600943557111074E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5591105222058232E-1
+            v = 0.1456447096742039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1407384078513916E+0
+            v = 0.2252370188283782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2364035438976309E+0
+            v = 0.2766135443474897E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3360602737818170E+0
+            v = 0.3110729491500851E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4356292630054665E+0
+            v = 0.3342506712303391E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5321569415256174E+0
+            v = 0.3491981834026860E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6232956305040554E+0
+            v = 0.3576003604348932E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9469870086838469E-1
+            b = 0.2778748387309470E-1
+            v = 0.1921921305788564E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1353170300568141E+0
+            b = 0.6076569878628364E-1
+            v = 0.2301458216495632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1771679481726077E+0
+            b = 0.9703072762711040E-1
+            v = 0.2604248549522893E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2197066664231751E+0
+            b = 0.1354112458524762E+0
+            v = 0.2845275425870697E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2624783557374927E+0
+            b = 0.1750996479744100E+0
+            v = 0.3036870897974840E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3050969521214442E+0
+            b = 0.2154896907449802E+0
+            v = 0.3188414832298066E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3472252637196021E+0
+            b = 0.2560954625740152E+0
+            v = 0.3307046414722089E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3885610219026360E+0
+            b = 0.2965070050624096E+0
+            v = 0.3398330969031360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4288273776062765E+0
+            b = 0.3363641488734497E+0
+            v = 0.3466757899705373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4677662471302948E+0
+            b = 0.3753400029836788E+0
+            v = 0.3516095923230054E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5051333589553359E+0
+            b = 0.4131297522144286E+0
+            v = 0.3549645184048486E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5406942145810492E+0
+            b = 0.4494423776081795E+0
+            v = 0.3570415969441392E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5742204122576457E+0
+            b = 0.4839938958841502E+0
+            v = 0.3581251798496118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1865407027225188E+0
+            b = 0.3259144851070796E-1
+            v = 0.2543491329913348E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2321186453689432E+0
+            b = 0.6835679505297343E-1
+            v = 0.2786711051330776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2773159142523882E+0
+            b = 0.1062284864451989E+0
+            v = 0.2985552361083679E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3219200192237254E+0
+            b = 0.1454404409323047E+0
+            v = 0.3145867929154039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3657032593944029E+0
+            b = 0.1854018282582510E+0
+            v = 0.3273290662067609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4084376778363622E+0
+            b = 0.2256297412014750E+0
+            v = 0.3372705511943501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4499004945751427E+0
+            b = 0.2657104425000896E+0
+            v = 0.3448274437851510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4898758141326335E+0
+            b = 0.3052755487631557E+0
+            v = 0.3503592783048583E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5281547442266309E+0
+            b = 0.3439863920645423E+0
+            v = 0.3541854792663162E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5645346989813992E+0
+            b = 0.3815229456121914E+0
+            v = 0.3565995517909428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5988181252159848E+0
+            b = 0.4175752420966734E+0
+            v = 0.3578802078302898E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2850425424471603E+0
+            b = 0.3562149509862536E-1
+            v = 0.2958644592860982E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3324619433027876E+0
+            b = 0.7330318886871096E-1
+            v = 0.3119548129116835E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3785848333076282E+0
+            b = 0.1123226296008472E+0
+            v = 0.3250745225005984E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4232891028562115E+0
+            b = 0.1521084193337708E+0
+            v = 0.3355153415935208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4664287050829722E+0
+            b = 0.1921844459223610E+0
+            v = 0.3435847568549328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5078458493735726E+0
+            b = 0.2321360989678303E+0
+            v = 0.3495786831622488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5473779816204180E+0
+            b = 0.2715886486360520E+0
+            v = 0.3537767805534621E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5848617133811376E+0
+            b = 0.3101924707571355E+0
+            v = 0.3564459815421428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6201348281584888E+0
+            b = 0.3476121052890973E+0
+            v = 0.3578464061225468E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3852191185387871E+0
+            b = 0.3763224880035108E-1
+            v = 0.3239748762836212E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4325025061073423E+0
+            b = 0.7659581935637135E-1
+            v = 0.3345491784174287E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4778486229734490E+0
+            b = 0.1163381306083900E+0
+            v = 0.3429126177301782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5211663693009000E+0
+            b = 0.1563890598752899E+0
+            v = 0.3492420343097421E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5623469504853703E+0
+            b = 0.1963320810149200E+0
+            v = 0.3537399050235257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6012718188659246E+0
+            b = 0.2357847407258738E+0
+            v = 0.3566209152659172E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6378179206390117E+0
+            b = 0.2743846121244060E+0
+            v = 0.3581084321919782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4836936460214534E+0
+            b = 0.3895902610739024E-1
+            v = 0.3426522117591512E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5293792562683797E+0
+            b = 0.7871246819312640E-1
+            v = 0.3491848770121379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726281253100033E+0
+            b = 0.1187963808202981E+0
+            v = 0.3539318235231476E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6133658776169068E+0
+            b = 0.1587914708061787E+0
+            v = 0.3570231438458694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6515085491865307E+0
+            b = 0.1983058575227646E+0
+            v = 0.3586207335051714E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5778692716064976E+0
+            b = 0.3977209689791542E-1
+            v = 0.3541196205164025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6207904288086192E+0
+            b = 0.7990157592981152E-1
+            v = 0.3574296911573953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6608688171046802E+0
+            b = 0.1199671308754309E+0
+            v = 0.3591993279818963E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6656263089489130E+0
+            b = 0.4015955957805969E-1
+            v = 0.3595855034661997E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3470:
+
+            v = 0.2040382730826330E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.3178149703889544E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1721420832906233E-1
+            v = 0.8288115128076110E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4408875374981770E-1
+            v = 0.1360883192522954E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7594680813878681E-1
+            v = 0.1766854454542662E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1108335359204799E+0
+            v = 0.2083153161230153E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1476517054388567E+0
+            v = 0.2333279544657158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1856731870860615E+0
+            v = 0.2532809539930247E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2243634099428821E+0
+            v = 0.2692472184211158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2633006881662727E+0
+            v = 0.2819949946811885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3021340904916283E+0
+            v = 0.2920953593973030E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3405594048030089E+0
+            v = 0.2999889782948352E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3783044434007372E+0
+            v = 0.3060292120496902E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4151194767407910E+0
+            v = 0.3105109167522192E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4507705766443257E+0
+            v = 0.3136902387550312E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4850346056573187E+0
+            v = 0.3157984652454632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5176950817792470E+0
+            v = 0.3170516518425422E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5485384240820989E+0
+            v = 0.3176568425633755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6039117238943308E+0
+            v = 0.3177198411207062E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6279956655573113E+0
+            v = 0.3175519492394733E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6493636169568952E+0
+            v = 0.3174654952634756E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6677644117704504E+0
+            v = 0.3175676415467654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6829368572115624E+0
+            v = 0.3178923417835410E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6946195818184121E+0
+            v = 0.3183788287531909E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7025711542057026E+0
+            v = 0.3188755151918807E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7066004767140119E+0
+            v = 0.3191916889313849E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5132537689946062E-1
+            v = 0.1231779611744508E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1297994661331225E+0
+            v = 0.1924661373839880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2188852049401307E+0
+            v = 0.2380881867403424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3123174824903457E+0
+            v = 0.2693100663037885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4064037620738195E+0
+            v = 0.2908673382834366E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4984958396944782E+0
+            v = 0.3053914619381535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5864975046021365E+0
+            v = 0.3143916684147777E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6686711634580175E+0
+            v = 0.3187042244055363E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8715738780835950E-1
+            b = 0.2557175233367578E-1
+            v = 0.1635219535869790E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1248383123134007E+0
+            b = 0.5604823383376681E-1
+            v = 0.1968109917696070E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1638062693383378E+0
+            b = 0.8968568601900765E-1
+            v = 0.2236754342249974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2035586203373176E+0
+            b = 0.1254086651976279E+0
+            v = 0.2453186687017181E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2436798975293774E+0
+            b = 0.1624780150162012E+0
+            v = 0.2627551791580541E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838207507773806E+0
+            b = 0.2003422342683208E+0
+            v = 0.2767654860152220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3236787502217692E+0
+            b = 0.2385628026255263E+0
+            v = 0.2879467027765895E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3629849554840691E+0
+            b = 0.2767731148783578E+0
+            v = 0.2967639918918702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4014948081992087E+0
+            b = 0.3146542308245309E+0
+            v = 0.3035900684660351E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4389818379260225E+0
+            b = 0.3519196415895088E+0
+            v = 0.3087338237298308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4752331143674377E+0
+            b = 0.3883050984023654E+0
+            v = 0.3124608838860167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5100457318374018E+0
+            b = 0.4235613423908649E+0
+            v = 0.3150084294226743E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5432238388954868E+0
+            b = 0.4574484717196220E+0
+            v = 0.3165958398598402E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5745758685072442E+0
+            b = 0.4897311639255524E+0
+            v = 0.3174320440957372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1723981437592809E+0
+            b = 0.3010630597881105E-1
+            v = 0.2182188909812599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2149553257844597E+0
+            b = 0.6326031554204694E-1
+            v = 0.2399727933921445E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2573256081247422E+0
+            b = 0.9848566980258631E-1
+            v = 0.2579796133514652E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2993163751238106E+0
+            b = 0.1350835952384266E+0
+            v = 0.2727114052623535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3407238005148000E+0
+            b = 0.1725184055442181E+0
+            v = 0.2846327656281355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3813454978483264E+0
+            b = 0.2103559279730725E+0
+            v = 0.2941491102051334E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4209848104423343E+0
+            b = 0.2482278774554860E+0
+            v = 0.3016049492136107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4594519699996300E+0
+            b = 0.2858099509982883E+0
+            v = 0.3072949726175648E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4965640166185930E+0
+            b = 0.3228075659915428E+0
+            v = 0.3114768142886460E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5321441655571562E+0
+            b = 0.3589459907204151E+0
+            v = 0.3143823673666223E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5660208438582166E+0
+            b = 0.3939630088864310E+0
+            v = 0.3162269764661535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5980264315964364E+0
+            b = 0.4276029922949089E+0
+            v = 0.3172164663759821E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2644215852350733E+0
+            b = 0.3300939429072552E-1
+            v = 0.2554575398967435E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3090113743443063E+0
+            b = 0.6803887650078501E-1
+            v = 0.2701704069135677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3525871079197808E+0
+            b = 0.1044326136206709E+0
+            v = 0.2823693413468940E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3950418005354029E+0
+            b = 0.1416751597517679E+0
+            v = 0.2922898463214289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4362475663430163E+0
+            b = 0.1793408610504821E+0
+            v = 0.3001829062162428E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4760661812145854E+0
+            b = 0.2170630750175722E+0
+            v = 0.3062890864542953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5143551042512103E+0
+            b = 0.2545145157815807E+0
+            v = 0.3108328279264746E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5509709026935597E+0
+            b = 0.2913940101706601E+0
+            v = 0.3140243146201245E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5857711030329428E+0
+            b = 0.3274169910910705E+0
+            v = 0.3160638030977130E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6186149917404392E+0
+            b = 0.3623081329317265E+0
+            v = 0.3171462882206275E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3586894569557064E+0
+            b = 0.3497354386450040E-1
+            v = 0.2812388416031796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4035266610019441E+0
+            b = 0.7129736739757095E-1
+            v = 0.2912137500288045E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4467775312332510E+0
+            b = 0.1084758620193165E+0
+            v = 0.2993241256502206E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4883638346608543E+0
+            b = 0.1460915689241772E+0
+            v = 0.3057101738983822E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5281908348434601E+0
+            b = 0.1837790832369980E+0
+            v = 0.3105319326251432E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5661542687149311E+0
+            b = 0.2212075390874021E+0
+            v = 0.3139565514428167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6021450102031452E+0
+            b = 0.2580682841160985E+0
+            v = 0.3161543006806366E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6360520783610050E+0
+            b = 0.2940656362094121E+0
+            v = 0.3172985960613294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4521611065087196E+0
+            b = 0.3631055365867002E-1
+            v = 0.2989400336901431E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4959365651560963E+0
+            b = 0.7348318468484350E-1
+            v = 0.3054555883947677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5376815804038283E+0
+            b = 0.1111087643812648E+0
+            v = 0.3104764960807702E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5773314480243768E+0
+            b = 0.1488226085145408E+0
+            v = 0.3141015825977616E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6148113245575056E+0
+            b = 0.1862892274135151E+0
+            v = 0.3164520621159896E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6500407462842380E+0
+            b = 0.2231909701714456E+0
+            v = 0.3176652305912204E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5425151448707213E+0
+            b = 0.3718201306118944E-1
+            v = 0.3105097161023939E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5841860556907931E+0
+            b = 0.7483616335067346E-1
+            v = 0.3143014117890550E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6234632186851500E+0
+            b = 0.1125990834266120E+0
+            v = 0.3168172866287200E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6602934551848843E+0
+            b = 0.1501303813157619E+0
+            v = 0.3181401865570968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6278573968375105E+0
+            b = 0.3767559930245720E-1
+            v = 0.3170663659156037E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6665611711264577E+0
+            b = 0.7548443301360158E-1
+            v = 0.3185447944625510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 3890:
+
+            v = 0.1807395252196920E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2848008782238827E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2836065837530581E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1587876419858352E-1
+            v = 0.7013149266673816E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4069193593751206E-1
+            v = 0.1162798021956766E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7025888115257997E-1
+            v = 0.1518728583972105E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1027495450028704E+0
+            v = 0.1798796108216934E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1371457730893426E+0
+            v = 0.2022593385972785E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1727758532671953E+0
+            v = 0.2203093105575464E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2091492038929037E+0
+            v = 0.2349294234299855E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2458813281751915E+0
+            v = 0.2467682058747003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2826545859450066E+0
+            v = 0.2563092683572224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3191957291799622E+0
+            v = 0.2639253896763318E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3552621469299578E+0
+            v = 0.2699137479265108E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3906329503406230E+0
+            v = 0.2745196420166739E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4251028614093031E+0
+            v = 0.2779529197397593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4584777520111870E+0
+            v = 0.2803996086684265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4905711358710193E+0
+            v = 0.2820302356715842E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5212011669847385E+0
+            v = 0.2830056747491068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5501878488737995E+0
+            v = 0.2834808950776839E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6025037877479342E+0
+            v = 0.2835282339078929E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6254572689549016E+0
+            v = 0.2833819267065800E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6460107179528248E+0
+            v = 0.2832858336906784E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6639541138154251E+0
+            v = 0.2833268235451244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6790688515667495E+0
+            v = 0.2835432677029253E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911338580371512E+0
+            v = 0.2839091722743049E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6999385956126490E+0
+            v = 0.2843308178875841E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7053037748656896E+0
+            v = 0.2846703550533846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4732224387180115E-1
+            v = 0.1051193406971900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1202100529326803E+0
+            v = 0.1657871838796974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2034304820664855E+0
+            v = 0.2064648113714232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2912285643573002E+0
+            v = 0.2347942745819741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3802361792726768E+0
+            v = 0.2547775326597726E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4680598511056146E+0
+            v = 0.2686876684847025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5528151052155599E+0
+            v = 0.2778665755515867E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6329386307803041E+0
+            v = 0.2830996616782929E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.8056516651369069E-1
+            b = 0.2363454684003124E-1
+            v = 0.1403063340168372E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1156476077139389E+0
+            b = 0.5191291632545936E-1
+            v = 0.1696504125939477E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1520473382760421E+0
+            b = 0.8322715736994519E-1
+            v = 0.1935787242745390E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1892986699745931E+0
+            b = 0.1165855667993712E+0
+            v = 0.2130614510521968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2270194446777792E+0
+            b = 0.1513077167409504E+0
+            v = 0.2289381265931048E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2648908185093273E+0
+            b = 0.1868882025807859E+0
+            v = 0.2418630292816186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3026389259574136E+0
+            b = 0.2229277629776224E+0
+            v = 0.2523400495631193E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3400220296151384E+0
+            b = 0.2590951840746235E+0
+            v = 0.2607623973449605E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3768217953335510E+0
+            b = 0.2951047291750847E+0
+            v = 0.2674441032689209E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4128372900921884E+0
+            b = 0.3307019714169930E+0
+            v = 0.2726432360343356E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4478807131815630E+0
+            b = 0.3656544101087634E+0
+            v = 0.2765787685924545E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4817742034089257E+0
+            b = 0.3997448951939695E+0
+            v = 0.2794428690642224E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5143472814653344E+0
+            b = 0.4327667110812024E+0
+            v = 0.2814099002062895E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5454346213905650E+0
+            b = 0.4645196123532293E+0
+            v = 0.2826429531578994E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5748739313170252E+0
+            b = 0.4948063555703345E+0
+            v = 0.2832983542550884E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1599598738286342E+0
+            b = 0.2792357590048985E-1
+            v = 0.1886695565284976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1998097412500951E+0
+            b = 0.5877141038139065E-1
+            v = 0.2081867882748234E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2396228952566202E+0
+            b = 0.9164573914691377E-1
+            v = 0.2245148680600796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2792228341097746E+0
+            b = 0.1259049641962687E+0
+            v = 0.2380370491511872E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3184251107546741E+0
+            b = 0.1610594823400863E+0
+            v = 0.2491398041852455E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3570481164426244E+0
+            b = 0.1967151653460898E+0
+            v = 0.2581632405881230E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3949164710492144E+0
+            b = 0.2325404606175168E+0
+            v = 0.2653965506227417E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318617293970503E+0
+            b = 0.2682461141151439E+0
+            v = 0.2710857216747087E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4677221009931678E+0
+            b = 0.3035720116011973E+0
+            v = 0.2754434093903659E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5023417939270955E+0
+            b = 0.3382781859197439E+0
+            v = 0.2786579932519380E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5355701836636128E+0
+            b = 0.3721383065625942E+0
+            v = 0.2809011080679474E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5672608451328771E+0
+            b = 0.4049346360466055E+0
+            v = 0.2823336184560987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5972704202540162E+0
+            b = 0.4364538098633802E+0
+            v = 0.2831101175806309E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2461687022333596E+0
+            b = 0.3070423166833368E-1
+            v = 0.2221679970354546E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2881774566286831E+0
+            b = 0.6338034669281885E-1
+            v = 0.2356185734270703E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3293963604116978E+0
+            b = 0.9742862487067941E-1
+            v = 0.2469228344805590E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3697303822241377E+0
+            b = 0.1323799532282290E+0
+            v = 0.2562726348642046E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4090663023135127E+0
+            b = 0.1678497018129336E+0
+            v = 0.2638756726753028E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4472819355411712E+0
+            b = 0.2035095105326114E+0
+            v = 0.2699311157390862E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4842513377231437E+0
+            b = 0.2390692566672091E+0
+            v = 0.2746233268403837E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5198477629962928E+0
+            b = 0.2742649818076149E+0
+            v = 0.2781225674454771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5539453011883145E+0
+            b = 0.3088503806580094E+0
+            v = 0.2805881254045684E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5864196762401251E+0
+            b = 0.3425904245906614E+0
+            v = 0.2821719877004913E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6171484466668390E+0
+            b = 0.3752562294789468E+0
+            v = 0.2830222502333124E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3350337830565727E+0
+            b = 0.3261589934634747E-1
+            v = 0.2457995956744870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3775773224758284E+0
+            b = 0.6658438928081572E-1
+            v = 0.2551474407503706E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4188155229848973E+0
+            b = 0.1014565797157954E+0
+            v = 0.2629065335195311E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4586805892009344E+0
+            b = 0.1368573320843822E+0
+            v = 0.2691900449925075E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4970895714224235E+0
+            b = 0.1724614851951608E+0
+            v = 0.2741275485754276E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5339505133960747E+0
+            b = 0.2079779381416412E+0
+            v = 0.2778530970122595E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5691665792531440E+0
+            b = 0.2431385788322288E+0
+            v = 0.2805010567646741E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6026387682680377E+0
+            b = 0.2776901883049853E+0
+            v = 0.2822055834031040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6342676150163307E+0
+            b = 0.3113881356386632E+0
+            v = 0.2831016901243473E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4237951119537067E+0
+            b = 0.3394877848664351E-1
+            v = 0.2624474901131803E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4656918683234929E+0
+            b = 0.6880219556291447E-1
+            v = 0.2688034163039377E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5058857069185980E+0
+            b = 0.1041946859721635E+0
+            v = 0.2738932751287636E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5443204666713996E+0
+            b = 0.1398039738736393E+0
+            v = 0.2777944791242523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5809298813759742E+0
+            b = 0.1753373381196155E+0
+            v = 0.2806011661660987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6156416039447128E+0
+            b = 0.2105215793514010E+0
+            v = 0.2824181456597460E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6483801351066604E+0
+            b = 0.2450953312157051E+0
+            v = 0.2833585216577828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5103616577251688E+0
+            b = 0.3485560643800719E-1
+            v = 0.2738165236962878E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5506738792580681E+0
+            b = 0.7026308631512033E-1
+            v = 0.2778365208203180E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5889573040995292E+0
+            b = 0.1059035061296403E+0
+            v = 0.2807852940418966E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6251641589516930E+0
+            b = 0.1414823925236026E+0
+            v = 0.2827245949674705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6592414921570178E+0
+            b = 0.1767207908214530E+0
+            v = 0.2837342344829828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5930314017533384E+0
+            b = 0.3542189339561672E-1
+            v = 0.2809233907610981E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6309812253390175E+0
+            b = 0.7109574040369549E-1
+            v = 0.2829930809742694E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6666296011353230E+0
+            b = 0.1067259792282730E+0
+            v = 0.2841097874111479E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6703715271049922E+0
+            b = 0.3569455268820809E-1
+            v = 0.2843455206008783E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 4334:
+
+            v = 0.1449063022537883E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2546377329828424E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1462896151831013E-1
+            v = 0.6018432961087496E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3769840812493139E-1
+            v = 0.1002286583263673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6524701904096891E-1
+            v = 0.1315222931028093E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9560543416134648E-1
+            v = 0.1564213746876724E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1278335898929198E+0
+            v = 0.1765118841507736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1613096104466031E+0
+            v = 0.1928737099311080E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1955806225745371E+0
+            v = 0.2062658534263270E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2302935218498028E+0
+            v = 0.2172395445953787E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2651584344113027E+0
+            v = 0.2262076188876047E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2999276825183209E+0
+            v = 0.2334885699462397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3343828669718798E+0
+            v = 0.2393355273179203E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3683265013750518E+0
+            v = 0.2439559200468863E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4015763206518108E+0
+            v = 0.2475251866060002E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4339612026399770E+0
+            v = 0.2501965558158773E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4653180651114582E+0
+            v = 0.2521081407925925E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4954893331080803E+0
+            v = 0.2533881002388081E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5243207068924930E+0
+            v = 0.2541582900848261E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5516590479041704E+0
+            v = 0.2545365737525860E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6012371927804176E+0
+            v = 0.2545726993066799E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6231574466449819E+0
+            v = 0.2544456197465555E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6429416514181271E+0
+            v = 0.2543481596881064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6604124272943595E+0
+            v = 0.2543506451429194E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6753851470408250E+0
+            v = 0.2544905675493763E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6876717970626160E+0
+            v = 0.2547611407344429E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6970895061319234E+0
+            v = 0.2551060375448869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7034746912553310E+0
+            v = 0.2554291933816039E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7067017217542295E+0
+            v = 0.2556255710686343E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4382223501131123E-1
+            v = 0.9041339695118195E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1117474077400006E+0
+            v = 0.1438426330079022E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1897153252911440E+0
+            v = 0.1802523089820518E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2724023009910331E+0
+            v = 0.2060052290565496E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3567163308709902E+0
+            v = 0.2245002248967466E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4404784483028087E+0
+            v = 0.2377059847731150E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5219833154161411E+0
+            v = 0.2468118955882525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5998179868977553E+0
+            v = 0.2525410872966528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6727803154548222E+0
+            v = 0.2553101409933397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7476563943166086E-1
+            b = 0.2193168509461185E-1
+            v = 0.1212879733668632E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1075341482001416E+0
+            b = 0.4826419281533887E-1
+            v = 0.1472872881270931E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1416344885203259E+0
+            b = 0.7751191883575742E-1
+            v = 0.1686846601010828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1766325315388586E+0
+            b = 0.1087558139247680E+0
+            v = 0.1862698414660208E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2121744174481514E+0
+            b = 0.1413661374253096E+0
+            v = 0.2007430956991861E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2479669443408145E+0
+            b = 0.1748768214258880E+0
+            v = 0.2126568125394796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2837600452294113E+0
+            b = 0.2089216406612073E+0
+            v = 0.2224394603372113E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3193344933193984E+0
+            b = 0.2431987685545972E+0
+            v = 0.2304264522673135E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3544935442438745E+0
+            b = 0.2774497054377770E+0
+            v = 0.2368854288424087E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3890571932288154E+0
+            b = 0.3114460356156915E+0
+            v = 0.2420352089461772E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4228581214259090E+0
+            b = 0.3449806851913012E+0
+            v = 0.2460597113081295E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4557387211304052E+0
+            b = 0.3778618641248256E+0
+            v = 0.2491181912257687E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4875487950541643E+0
+            b = 0.4099086391698978E+0
+            v = 0.2513528194205857E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5181436529962997E+0
+            b = 0.4409474925853973E+0
+            v = 0.2528943096693220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5473824095600661E+0
+            b = 0.4708094517711291E+0
+            v = 0.2538660368488136E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5751263398976174E+0
+            b = 0.4993275140354637E+0
+            v = 0.2543868648299022E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1489515746840028E+0
+            b = 0.2599381993267017E-1
+            v = 0.1642595537825183E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1863656444351767E+0
+            b = 0.5479286532462190E-1
+            v = 0.1818246659849308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2238602880356348E+0
+            b = 0.8556763251425254E-1
+            v = 0.1966565649492420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2612723375728160E+0
+            b = 0.1177257802267011E+0
+            v = 0.2090677905657991E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2984332990206190E+0
+            b = 0.1508168456192700E+0
+            v = 0.2193820409510504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3351786584663333E+0
+            b = 0.1844801892177727E+0
+            v = 0.2278870827661928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3713505522209120E+0
+            b = 0.2184145236087598E+0
+            v = 0.2348283192282090E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4067981098954663E+0
+            b = 0.2523590641486229E+0
+            v = 0.2404139755581477E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4413769993687534E+0
+            b = 0.2860812976901373E+0
+            v = 0.2448227407760734E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4749487182516394E+0
+            b = 0.3193686757808996E+0
+            v = 0.2482110455592573E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5073798105075426E+0
+            b = 0.3520226949547602E+0
+            v = 0.2507192397774103E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5385410448878654E+0
+            b = 0.3838544395667890E+0
+            v = 0.2524765968534880E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5683065353670530E+0
+            b = 0.4146810037640963E+0
+            v = 0.2536052388539425E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5965527620663510E+0
+            b = 0.4443224094681121E+0
+            v = 0.2542230588033068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2299227700856157E+0
+            b = 0.2865757664057584E-1
+            v = 0.1944817013047896E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2695752998553267E+0
+            b = 0.5923421684485993E-1
+            v = 0.2067862362746635E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3086178716611389E+0
+            b = 0.9117817776057715E-1
+            v = 0.2172440734649114E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3469649871659077E+0
+            b = 0.1240593814082605E+0
+            v = 0.2260125991723423E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3845153566319655E+0
+            b = 0.1575272058259175E+0
+            v = 0.2332655008689523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4211600033403215E+0
+            b = 0.1912845163525413E+0
+            v = 0.2391699681532458E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4567867834329882E+0
+            b = 0.2250710177858171E+0
+            v = 0.2438801528273928E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4912829319232061E+0
+            b = 0.2586521303440910E+0
+            v = 0.2475370504260665E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5245364793303812E+0
+            b = 0.2918112242865407E+0
+            v = 0.2502707235640574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5564369788915756E+0
+            b = 0.3243439239067890E+0
+            v = 0.2522031701054241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5868757697775287E+0
+            b = 0.3560536787835351E+0
+            v = 0.2534511269978784E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6157458853519617E+0
+            b = 0.3867480821242581E+0
+            v = 0.2541284914955151E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3138461110672113E+0
+            b = 0.3051374637507278E-1
+            v = 0.2161509250688394E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3542495872050569E+0
+            b = 0.6237111233730755E-1
+            v = 0.2248778513437852E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3935751553120181E+0
+            b = 0.9516223952401907E-1
+            v = 0.2322388803404617E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4317634668111147E+0
+            b = 0.1285467341508517E+0
+            v = 0.2383265471001355E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4687413842250821E+0
+            b = 0.1622318931656033E+0
+            v = 0.2432476675019525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5044274237060283E+0
+            b = 0.1959581153836453E+0
+            v = 0.2471122223750674E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5387354077925727E+0
+            b = 0.2294888081183837E+0
+            v = 0.2500291752486870E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5715768898356105E+0
+            b = 0.2626031152713945E+0
+            v = 0.2521055942764682E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6028627200136111E+0
+            b = 0.2950904075286713E+0
+            v = 0.2534472785575503E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6325039812653463E+0
+            b = 0.3267458451113286E+0
+            v = 0.2541599713080121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3981986708423407E+0
+            b = 0.3183291458749821E-1
+            v = 0.2317380975862936E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4382791182133300E+0
+            b = 0.6459548193880908E-1
+            v = 0.2378550733719775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4769233057218166E+0
+            b = 0.9795757037087952E-1
+            v = 0.2428884456739118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5140823911194238E+0
+            b = 0.1316307235126655E+0
+            v = 0.2469002655757292E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5496977833862983E+0
+            b = 0.1653556486358704E+0
+            v = 0.2499657574265851E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5837047306512727E+0
+            b = 0.1988931724126510E+0
+            v = 0.2521676168486082E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6160349566926879E+0
+            b = 0.2320174581438950E+0
+            v = 0.2535935662645334E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6466185353209440E+0
+            b = 0.2645106562168662E+0
+            v = 0.2543356743363214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4810835158795404E+0
+            b = 0.3275917807743992E-1
+            v = 0.2427353285201535E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5199925041324341E+0
+            b = 0.6612546183967181E-1
+            v = 0.2468258039744386E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5571717692207494E+0
+            b = 0.9981498331474143E-1
+            v = 0.2500060956440310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5925789250836378E+0
+            b = 0.1335687001410374E+0
+            v = 0.2523238365420979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6261658523859670E+0
+            b = 0.1671444402896463E+0
+            v = 0.2538399260252846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6578811126669331E+0
+            b = 0.2003106382156076E+0
+            v = 0.2546255927268069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5609624612998100E+0
+            b = 0.3337500940231335E-1
+            v = 0.2500583360048449E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5979959659984670E+0
+            b = 0.6708750335901803E-1
+            v = 0.2524777638260203E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6330523711054002E+0
+            b = 0.1008792126424850E+0
+            v = 0.2540951193860656E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6660960998103972E+0
+            b = 0.1345050343171794E+0
+            v = 0.2549524085027472E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6365384364585819E+0
+            b = 0.3372799460737052E-1
+            v = 0.2542569507009158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6710994302899275E+0
+            b = 0.6755249309678028E-1
+            v = 0.2552114127580376E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 4802:
+
+            v = 0.9687521879420705E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2307897895367918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.2297310852498558E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2335728608887064E-1
+            v = 0.7386265944001919E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4352987836550653E-1
+            v = 0.8257977698542210E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6439200521088801E-1
+            v = 0.9706044762057630E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.9003943631993181E-1
+            v = 0.1302393847117003E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1196706615548473E+0
+            v = 0.1541957004600968E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1511715412838134E+0
+            v = 0.1704459770092199E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1835982828503801E+0
+            v = 0.1827374890942906E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2165081259155405E+0
+            v = 0.1926360817436107E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2496208720417563E+0
+            v = 0.2008010239494833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2827200673567900E+0
+            v = 0.2075635983209175E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3156190823994346E+0
+            v = 0.2131306638690909E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3481476793749115E+0
+            v = 0.2176562329937335E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3801466086947226E+0
+            v = 0.2212682262991018E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4114652119634011E+0
+            v = 0.2240799515668565E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4419598786519751E+0
+            v = 0.2261959816187525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4714925949329543E+0
+            v = 0.2277156368808855E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4999293972879466E+0
+            v = 0.2287351772128336E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5271387221431248E+0
+            v = 0.2293490814084085E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5529896780837761E+0
+            v = 0.2296505312376273E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6000856099481712E+0
+            v = 0.2296793832318756E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6210562192785175E+0
+            v = 0.2295785443842974E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6401165879934240E+0
+            v = 0.2295017931529102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6571144029244334E+0
+            v = 0.2295059638184868E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6718910821718863E+0
+            v = 0.2296232343237362E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6842845591099010E+0
+            v = 0.2298530178740771E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6941353476269816E+0
+            v = 0.2301579790280501E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7012965242212991E+0
+            v = 0.2304690404996513E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7056471428242644E+0
+            v = 0.2307027995907102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4595557643585895E-1
+            v = 0.9312274696671092E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1049316742435023E+0
+            v = 0.1199919385876926E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1773548879549274E+0
+            v = 0.1598039138877690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2559071411236127E+0
+            v = 0.1822253763574900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3358156837985898E+0
+            v = 0.1988579593655040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4155835743763893E+0
+            v = 0.2112620102533307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4937894296167472E+0
+            v = 0.2201594887699007E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5691569694793316E+0
+            v = 0.2261622590895036E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6405840854894251E+0
+            v = 0.2296458453435705E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.7345133894143348E-1
+            b = 0.2177844081486067E-1
+            v = 0.1006006990267000E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1009859834044931E+0
+            b = 0.4590362185775188E-1
+            v = 0.1227676689635876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1324289619748758E+0
+            b = 0.7255063095690877E-1
+            v = 0.1467864280270117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1654272109607127E+0
+            b = 0.1017825451960684E+0
+            v = 0.1644178912101232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1990767186776461E+0
+            b = 0.1325652320980364E+0
+            v = 0.1777664890718961E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2330125945523278E+0
+            b = 0.1642765374496765E+0
+            v = 0.1884825664516690E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2670080611108287E+0
+            b = 0.1965360374337889E+0
+            v = 0.1973269246453848E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3008753376294316E+0
+            b = 0.2290726770542238E+0
+            v = 0.2046767775855328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3344475596167860E+0
+            b = 0.2616645495370823E+0
+            v = 0.2107600125918040E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3675709724070786E+0
+            b = 0.2941150728843141E+0
+            v = 0.2157416362266829E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4001000887587812E+0
+            b = 0.3262440400919066E+0
+            v = 0.2197557816920721E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318956350436028E+0
+            b = 0.3578835350611916E+0
+            v = 0.2229192611835437E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4628239056795531E+0
+            b = 0.3888751854043678E+0
+            v = 0.2253385110212775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4927563229773636E+0
+            b = 0.4190678003222840E+0
+            v = 0.2271137107548774E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5215687136707969E+0
+            b = 0.4483151836883852E+0
+            v = 0.2283414092917525E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5491402346984905E+0
+            b = 0.4764740676087880E+0
+            v = 0.2291161673130077E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5753520160126075E+0
+            b = 0.5034021310998277E+0
+            v = 0.2295313908576598E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1388326356417754E+0
+            b = 0.2435436510372806E-1
+            v = 0.1438204721359031E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1743686900537244E+0
+            b = 0.5118897057342652E-1
+            v = 0.1607738025495257E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2099737037950268E+0
+            b = 0.8014695048539634E-1
+            v = 0.1741483853528379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2454492590908548E+0
+            b = 0.1105117874155699E+0
+            v = 0.1851918467519151E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2807219257864278E+0
+            b = 0.1417950531570966E+0
+            v = 0.1944628638070613E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3156842271975842E+0
+            b = 0.1736604945719597E+0
+            v = 0.2022495446275152E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3502090945177752E+0
+            b = 0.2058466324693981E+0
+            v = 0.2087462382438514E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3841684849519686E+0
+            b = 0.2381284261195919E+0
+            v = 0.2141074754818308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4174372367906016E+0
+            b = 0.2703031270422569E+0
+            v = 0.2184640913748162E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4498926465011892E+0
+            b = 0.3021845683091309E+0
+            v = 0.2219309165220329E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4814146229807701E+0
+            b = 0.3335993355165720E+0
+            v = 0.2246123118340624E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5118863625734701E+0
+            b = 0.3643833735518232E+0
+            v = 0.2266062766915125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5411947455119144E+0
+            b = 0.3943789541958179E+0
+            v = 0.2280072952230796E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5692301500357246E+0
+            b = 0.4234320144403542E+0
+            v = 0.2289082025202583E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5958857204139576E+0
+            b = 0.4513897947419260E+0
+            v = 0.2294012695120025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2156270284785766E+0
+            b = 0.2681225755444491E-1
+            v = 0.1722434488736947E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2532385054909710E+0
+            b = 0.5557495747805614E-1
+            v = 0.1830237421455091E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2902564617771537E+0
+            b = 0.8569368062950249E-1
+            v = 0.1923855349997633E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3266979823143256E+0
+            b = 0.1167367450324135E+0
+            v = 0.2004067861936271E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3625039627493614E+0
+            b = 0.1483861994003304E+0
+            v = 0.2071817297354263E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3975838937548699E+0
+            b = 0.1803821503011405E+0
+            v = 0.2128250834102103E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4318396099009774E+0
+            b = 0.2124962965666424E+0
+            v = 0.2174513719440102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4651706555732742E+0
+            b = 0.2445221837805913E+0
+            v = 0.2211661839150214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4974752649620969E+0
+            b = 0.2762701224322987E+0
+            v = 0.2240665257813102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5286517579627517E+0
+            b = 0.3075627775211328E+0
+            v = 0.2262439516632620E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5586001195731895E+0
+            b = 0.3382311089826877E+0
+            v = 0.2277874557231869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5872229902021319E+0
+            b = 0.3681108834741399E+0
+            v = 0.2287854314454994E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6144258616235123E+0
+            b = 0.3970397446872839E+0
+            v = 0.2293268499615575E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2951676508064861E+0
+            b = 0.2867499538750441E-1
+            v = 0.1912628201529828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3335085485472725E+0
+            b = 0.5867879341903510E-1
+            v = 0.1992499672238701E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3709561760636381E+0
+            b = 0.8961099205022284E-1
+            v = 0.2061275533454027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4074722861667498E+0
+            b = 0.1211627927626297E+0
+            v = 0.2119318215968572E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4429923648839117E+0
+            b = 0.1530748903554898E+0
+            v = 0.2167416581882652E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4774428052721736E+0
+            b = 0.1851176436721877E+0
+            v = 0.2206430730516600E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5107446539535904E+0
+            b = 0.2170829107658179E+0
+            v = 0.2237186938699523E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5428151370542935E+0
+            b = 0.2487786689026271E+0
+            v = 0.2260480075032884E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5735699292556964E+0
+            b = 0.2800239952795016E+0
+            v = 0.2277098884558542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6029253794562866E+0
+            b = 0.3106445702878119E+0
+            v = 0.2287845715109671E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6307998987073145E+0
+            b = 0.3404689500841194E+0
+            v = 0.2293547268236294E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3752652273692719E+0
+            b = 0.2997145098184479E-1
+            v = 0.2056073839852528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4135383879344028E+0
+            b = 0.6086725898678011E-1
+            v = 0.2114235865831876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4506113885153907E+0
+            b = 0.9238849548435643E-1
+            v = 0.2163175629770551E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4864401554606072E+0
+            b = 0.1242786603851851E+0
+            v = 0.2203392158111650E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5209708076611709E+0
+            b = 0.1563086731483386E+0
+            v = 0.2235473176847839E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5541422135830122E+0
+            b = 0.1882696509388506E+0
+            v = 0.2260024141501235E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5858880915113817E+0
+            b = 0.2199672979126059E+0
+            v = 0.2277675929329182E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6161399390603444E+0
+            b = 0.2512165482924867E+0
+            v = 0.2289102112284834E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6448296482255090E+0
+            b = 0.2818368701871888E+0
+            v = 0.2295027954625118E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4544796274917948E+0
+            b = 0.3088970405060312E-1
+            v = 0.2161281589879992E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4919389072146628E+0
+            b = 0.6240947677636835E-1
+            v = 0.2201980477395102E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5279313026985183E+0
+            b = 0.9430706144280313E-1
+            v = 0.2234952066593166E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5624169925571135E+0
+            b = 0.1263547818770374E+0
+            v = 0.2260540098520838E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5953484627093287E+0
+            b = 0.1583430788822594E+0
+            v = 0.2279157981899988E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6266730715339185E+0
+            b = 0.1900748462555988E+0
+            v = 0.2291296918565571E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6563363204278871E+0
+            b = 0.2213599519592567E+0
+            v = 0.2297533752536649E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5314574716585696E+0
+            b = 0.3152508811515374E-1
+            v = 0.2234927356465995E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5674614932298185E+0
+            b = 0.6343865291465561E-1
+            v = 0.2261288012985219E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6017706004970264E+0
+            b = 0.9551503504223951E-1
+            v = 0.2280818160923688E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6343471270264178E+0
+            b = 0.1275440099801196E+0
+            v = 0.2293773295180159E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6651494599127802E+0
+            b = 0.1593252037671960E+0
+            v = 0.2300528767338634E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6050184986005704E+0
+            b = 0.3192538338496105E-1
+            v = 0.2281893855065666E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6390163550880400E+0
+            b = 0.6402824353962306E-1
+            v = 0.2295720444840727E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6711199107088448E+0
+            b = 0.9609805077002909E-1
+            v = 0.2303227649026753E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6741354429572275E+0
+            b = 0.3211853196273233E-1
+            v = 0.2304831913227114E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 5294:
+
+            v = 0.9080510764308163E-4
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.2084824361987793E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.2303261686261450E-1
+            v = 0.5011105657239616E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3757208620162394E-1
+            v = 0.5942520409683854E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5821912033821852E-1
+            v = 0.9564394826109721E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.8403127529194872E-1
+            v = 0.1185530657126338E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1122927798060578E+0
+            v = 0.1364510114230331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1420125319192987E+0
+            v = 0.1505828825605415E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1726396437341978E+0
+            v = 0.1619298749867023E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2038170058115696E+0
+            v = 0.1712450504267789E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2352849892876508E+0
+            v = 0.1789891098164999E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2668363354312461E+0
+            v = 0.1854474955629795E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2982941279900452E+0
+            v = 0.1908148636673661E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3295002922087076E+0
+            v = 0.1952377405281833E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3603094918363593E+0
+            v = 0.1988349254282232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3905857895173920E+0
+            v = 0.2017079807160050E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4202005758160837E+0
+            v = 0.2039473082709094E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4490310061597227E+0
+            v = 0.2056360279288953E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4769586160311491E+0
+            v = 0.2068525823066865E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5038679887049750E+0
+            v = 0.2076724877534488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5296454286519961E+0
+            v = 0.2081694278237885E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5541776207164850E+0
+            v = 0.2084157631219326E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5990467321921213E+0
+            v = 0.2084381531128593E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6191467096294587E+0
+            v = 0.2083476277129307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6375251212901849E+0
+            v = 0.2082686194459732E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6540514381131168E+0
+            v = 0.2082475686112415E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6685899064391510E+0
+            v = 0.2083139860289915E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6810013009681648E+0
+            v = 0.2084745561831237E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6911469578730340E+0
+            v = 0.2087091313375890E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6988956915141736E+0
+            v = 0.2089718413297697E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7041335794868720E+0
+            v = 0.2092003303479793E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7067754398018567E+0
+            v = 0.2093336148263241E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3840368707853623E-1
+            v = 0.7591708117365267E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9835485954117399E-1
+            v = 0.1083383968169186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1665774947612998E+0
+            v = 0.1403019395292510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2405702335362910E+0
+            v = 0.1615970179286436E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3165270770189046E+0
+            v = 0.1771144187504911E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3927386145645443E+0
+            v = 0.1887760022988168E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4678825918374656E+0
+            v = 0.1973474670768214E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5408022024266935E+0
+            v = 0.2033787661234659E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6104967445752438E+0
+            v = 0.2072343626517331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6760910702685738E+0
+            v = 0.2091177834226918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6655644120217392E-1
+            b = 0.1936508874588424E-1
+            v = 0.9316684484675566E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.9446246161270182E-1
+            b = 0.4252442002115869E-1
+            v = 0.1116193688682976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1242651925452509E+0
+            b = 0.6806529315354374E-1
+            v = 0.1298623551559414E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1553438064846751E+0
+            b = 0.9560957491205369E-1
+            v = 0.1450236832456426E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1871137110542670E+0
+            b = 0.1245931657452888E+0
+            v = 0.1572719958149914E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2192612628836257E+0
+            b = 0.1545385828778978E+0
+            v = 0.1673234785867195E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2515682807206955E+0
+            b = 0.1851004249723368E+0
+            v = 0.1756860118725188E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2838535866287290E+0
+            b = 0.2160182608272384E+0
+            v = 0.1826776290439367E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3159578817528521E+0
+            b = 0.2470799012277111E+0
+            v = 0.1885116347992865E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3477370882791392E+0
+            b = 0.2781014208986402E+0
+            v = 0.1933457860170574E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3790576960890540E+0
+            b = 0.3089172523515731E+0
+            v = 0.1973060671902064E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4097938317810200E+0
+            b = 0.3393750055472244E+0
+            v = 0.2004987099616311E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4398256572859637E+0
+            b = 0.3693322470987730E+0
+            v = 0.2030170909281499E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4690384114718480E+0
+            b = 0.3986541005609877E+0
+            v = 0.2049461460119080E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4973216048301053E+0
+            b = 0.4272112491408562E+0
+            v = 0.2063653565200186E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5245681526132446E+0
+            b = 0.4548781735309936E+0
+            v = 0.2073507927381027E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5506733911803888E+0
+            b = 0.4815315355023251E+0
+            v = 0.2079764593256122E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5755339829522475E+0
+            b = 0.5070486445801855E+0
+            v = 0.2083150534968778E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1305472386056362E+0
+            b = 0.2284970375722366E-1
+            v = 0.1262715121590664E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1637327908216477E+0
+            b = 0.4812254338288384E-1
+            v = 0.1414386128545972E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1972734634149637E+0
+            b = 0.7531734457511935E-1
+            v = 0.1538740401313898E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2308694653110130E+0
+            b = 0.1039043639882017E+0
+            v = 0.1642434942331432E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2643899218338160E+0
+            b = 0.1334526587117626E+0
+            v = 0.1729790609237496E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2977171599622171E+0
+            b = 0.1636414868936382E+0
+            v = 0.1803505190260828E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3307293903032310E+0
+            b = 0.1942195406166568E+0
+            v = 0.1865475350079657E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3633069198219073E+0
+            b = 0.2249752879943753E+0
+            v = 0.1917182669679069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3953346955922727E+0
+            b = 0.2557218821820032E+0
+            v = 0.1959851709034382E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4267018394184914E+0
+            b = 0.2862897925213193E+0
+            v = 0.1994529548117882E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4573009622571704E+0
+            b = 0.3165224536636518E+0
+            v = 0.2022138911146548E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4870279559856109E+0
+            b = 0.3462730221636496E+0
+            v = 0.2043518024208592E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5157819581450322E+0
+            b = 0.3754016870282835E+0
+            v = 0.2059450313018110E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5434651666465393E+0
+            b = 0.4037733784993613E+0
+            v = 0.2070685715318472E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5699823887764627E+0
+            b = 0.4312557784139123E+0
+            v = 0.2077955310694373E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5952403350947741E+0
+            b = 0.4577175367122110E+0
+            v = 0.2081980387824712E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2025152599210369E+0
+            b = 0.2520253617719557E-1
+            v = 0.1521318610377956E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2381066653274425E+0
+            b = 0.5223254506119000E-1
+            v = 0.1622772720185755E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2732823383651612E+0
+            b = 0.8060669688588620E-1
+            v = 0.1710498139420709E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3080137692611118E+0
+            b = 0.1099335754081255E+0
+            v = 0.1785911149448736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3422405614587601E+0
+            b = 0.1399120955959857E+0
+            v = 0.1850125313687736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3758808773890420E+0
+            b = 0.1702977801651705E+0
+            v = 0.1904229703933298E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4088458383438932E+0
+            b = 0.2008799256601680E+0
+            v = 0.1949259956121987E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4410450550841152E+0
+            b = 0.2314703052180836E+0
+            v = 0.1986161545363960E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4723879420561312E+0
+            b = 0.2618972111375892E+0
+            v = 0.2015790585641370E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5027843561874343E+0
+            b = 0.2920013195600270E+0
+            v = 0.2038934198707418E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5321453674452458E+0
+            b = 0.3216322555190551E+0
+            v = 0.2056334060538251E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5603839113834030E+0
+            b = 0.3506456615934198E+0
+            v = 0.2068705959462289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5874150706875146E+0
+            b = 0.3789007181306267E+0
+            v = 0.2076753906106002E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6131559381660038E+0
+            b = 0.4062580170572782E+0
+            v = 0.2081179391734803E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2778497016394506E+0
+            b = 0.2696271276876226E-1
+            v = 0.1700345216228943E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3143733562261912E+0
+            b = 0.5523469316960465E-1
+            v = 0.1774906779990410E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3501485810261827E+0
+            b = 0.8445193201626464E-1
+            v = 0.1839659377002642E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3851430322303653E+0
+            b = 0.1143263119336083E+0
+            v = 0.1894987462975169E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4193013979470415E+0
+            b = 0.1446177898344475E+0
+            v = 0.1941548809452595E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4525585960458567E+0
+            b = 0.1751165438438091E+0
+            v = 0.1980078427252384E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4848447779622947E+0
+            b = 0.2056338306745660E+0
+            v = 0.2011296284744488E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5160871208276894E+0
+            b = 0.2359965487229226E+0
+            v = 0.2035888456966776E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5462112185696926E+0
+            b = 0.2660430223139146E+0
+            v = 0.2054516325352142E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5751425068101757E+0
+            b = 0.2956193664498032E+0
+            v = 0.2067831033092635E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6028073872853596E+0
+            b = 0.3245763905312779E+0
+            v = 0.2076485320284876E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6291338275278409E+0
+            b = 0.3527670026206972E+0
+            v = 0.2081141439525255E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3541797528439391E+0
+            b = 0.2823853479435550E-1
+            v = 0.1834383015469222E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3908234972074657E+0
+            b = 0.5741296374713106E-1
+            v = 0.1889540591777677E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4264408450107590E+0
+            b = 0.8724646633650199E-1
+            v = 0.1936677023597375E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4609949666553286E+0
+            b = 0.1175034422915616E+0
+            v = 0.1976176495066504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4944389496536006E+0
+            b = 0.1479755652628428E+0
+            v = 0.2008536004560983E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5267194884346086E+0
+            b = 0.1784740659484352E+0
+            v = 0.2034280351712291E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5577787810220990E+0
+            b = 0.2088245700431244E+0
+            v = 0.2053944466027758E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5875563763536670E+0
+            b = 0.2388628136570763E+0
+            v = 0.2068077642882360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6159910016391269E+0
+            b = 0.2684308928769185E+0
+            v = 0.2077250949661599E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6430219602956268E+0
+            b = 0.2973740761960252E+0
+            v = 0.2082062440705320E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4300647036213646E+0
+            b = 0.2916399920493977E-1
+            v = 0.1934374486546626E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4661486308935531E+0
+            b = 0.5898803024755659E-1
+            v = 0.1974107010484300E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5009658555287261E+0
+            b = 0.8924162698525409E-1
+            v = 0.2007129290388658E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5344824270447704E+0
+            b = 0.1197185199637321E+0
+            v = 0.2033736947471293E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5666575997416371E+0
+            b = 0.1502300756161382E+0
+            v = 0.2054287125902493E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5974457471404752E+0
+            b = 0.1806004191913564E+0
+            v = 0.2069184936818894E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6267984444116886E+0
+            b = 0.2106621764786252E+0
+            v = 0.2078883689808782E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6546664713575417E+0
+            b = 0.2402526932671914E+0
+            v = 0.2083886366116359E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5042711004437253E+0
+            b = 0.2982529203607657E-1
+            v = 0.2006593275470817E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5392127456774380E+0
+            b = 0.6008728062339922E-1
+            v = 0.2033728426135397E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5726819437668618E+0
+            b = 0.9058227674571398E-1
+            v = 0.2055008781377608E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6046469254207278E+0
+            b = 0.1211219235803400E+0
+            v = 0.2070651783518502E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6350716157434952E+0
+            b = 0.1515286404791580E+0
+            v = 0.2080953335094320E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6639177679185454E+0
+            b = 0.1816314681255552E+0
+            v = 0.2086284998988521E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5757276040972253E+0
+            b = 0.3026991752575440E-1
+            v = 0.2055549387644668E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6090265823139755E+0
+            b = 0.6078402297870770E-1
+            v = 0.2071871850267654E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6406735344387661E+0
+            b = 0.9135459984176636E-1
+            v = 0.2082856600431965E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6706397927793709E+0
+            b = 0.1218024155966590E+0
+            v = 0.2088705858819358E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6435019674426665E+0
+            b = 0.3052608357660639E-1
+            v = 0.2083995867536322E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6747218676375681E+0
+            b = 0.6112185773983089E-1
+            v = 0.2090509712889637E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case 5810:
+
+            v = 0.9735347946175486E-5
+            leb_tmp, start = get_lebedev_recurrence_points(1, start, a, b, v, leb_tmp)
+            v = 0.1907581241803167E-3
+            leb_tmp, start = get_lebedev_recurrence_points(2, start, a, b, v, leb_tmp)
+            v = 0.1901059546737578E-3
+            leb_tmp, start = get_lebedev_recurrence_points(3, start, a, b, v, leb_tmp)
+            a = 0.1182361662400277E-1
+            v = 0.3926424538919212E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3062145009138958E-1
+            v = 0.6667905467294382E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5329794036834243E-1
+            v = 0.8868891315019135E-4
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7848165532862220E-1
+            v = 0.1066306000958872E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1054038157636201E+0
+            v = 0.1214506743336128E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1335577797766211E+0
+            v = 0.1338054681640871E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1625769955502252E+0
+            v = 0.1441677023628504E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.1921787193412792E+0
+            v = 0.1528880200826557E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2221340534690548E+0
+            v = 0.1602330623773609E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2522504912791132E+0
+            v = 0.1664102653445244E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.2823610860679697E+0
+            v = 0.1715845854011323E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3123173966267560E+0
+            v = 0.1758901000133069E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3419847036953789E+0
+            v = 0.1794382485256736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3712386456999758E+0
+            v = 0.1823238106757407E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3999627649876828E+0
+            v = 0.1846293252959976E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4280466458648093E+0
+            v = 0.1864284079323098E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4553844360185711E+0
+            v = 0.1877882694626914E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.4818736094437834E+0
+            v = 0.1887716321852025E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5074138709260629E+0
+            v = 0.1894381638175673E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5319061304570707E+0
+            v = 0.1898454899533629E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5552514978677286E+0
+            v = 0.1900497929577815E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.5981009025246183E+0
+            v = 0.1900671501924092E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6173990192228116E+0
+            v = 0.1899837555533510E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6351365239411131E+0
+            v = 0.1899014113156229E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6512010228227200E+0
+            v = 0.1898581257705106E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6654758363948120E+0
+            v = 0.1898804756095753E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6778410414853370E+0
+            v = 0.1899793610426402E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6881760887484110E+0
+            v = 0.1901464554844117E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.6963645267094598E+0
+            v = 0.1903533246259542E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7023010617153579E+0
+            v = 0.1905556158463228E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.7059004636628753E+0
+            v = 0.1907037155663528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(4, start, a, b, v, leb_tmp)
+            a = 0.3552470312472575E-1
+            v = 0.5992997844249967E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.9151176620841283E-1
+            v = 0.9749059382456978E-4
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.1566197930068980E+0
+            v = 0.1241680804599158E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2265467599271907E+0
+            v = 0.1437626154299360E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.2988242318581361E+0
+            v = 0.1584200054793902E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.3717482419703886E+0
+            v = 0.1694436550982744E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.4440094491758889E+0
+            v = 0.1776617014018108E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5145337096756642E+0
+            v = 0.1836132434440077E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.5824053672860230E+0
+            v = 0.1876494727075983E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6468283961043370E+0
+            v = 0.1899906535336482E-3
+            leb_tmp, start = get_lebedev_recurrence_points(5, start, a, b, v, leb_tmp)
+            a = 0.6095964259104373E-1
+            b = 0.1787828275342931E-1
+            v = 0.8143252820767350E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.8811962270959388E-1
+            b = 0.3953888740792096E-1
+            v = 0.9998859890887728E-4
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1165936722428831E+0
+            b = 0.6378121797722990E-1
+            v = 0.1156199403068359E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1460232857031785E+0
+            b = 0.8985890813745037E-1
+            v = 0.1287632092635513E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1761197110181755E+0
+            b = 0.1172606510576162E+0
+            v = 0.1398378643365139E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2066471190463718E+0
+            b = 0.1456102876970995E+0
+            v = 0.1491876468417391E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2374076026328152E+0
+            b = 0.1746153823011775E+0
+            v = 0.1570855679175456E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2682305474337051E+0
+            b = 0.2040383070295584E+0
+            v = 0.1637483948103775E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2989653312142369E+0
+            b = 0.2336788634003698E+0
+            v = 0.1693500566632843E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3294762752772209E+0
+            b = 0.2633632752654219E+0
+            v = 0.1740322769393633E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3596390887276086E+0
+            b = 0.2929369098051601E+0
+            v = 0.1779126637278296E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3893383046398812E+0
+            b = 0.3222592785275512E+0
+            v = 0.1810908108835412E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4184653789358347E+0
+            b = 0.3512004791195743E+0
+            v = 0.1836529132600190E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4469172319076166E+0
+            b = 0.3796385677684537E+0
+            v = 0.1856752841777379E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4745950813276976E+0
+            b = 0.4074575378263879E+0
+            v = 0.1872270566606832E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5014034601410262E+0
+            b = 0.4345456906027828E+0
+            v = 0.1883722645591307E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5272493404551239E+0
+            b = 0.4607942515205134E+0
+            v = 0.1891714324525297E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5520413051846366E+0
+            b = 0.4860961284181720E+0
+            v = 0.1896827480450146E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5756887237503077E+0
+            b = 0.5103447395342790E+0
+            v = 0.1899628417059528E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1225039430588352E+0
+            b = 0.2136455922655793E-1
+            v = 0.1123301829001669E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1539113217321372E+0
+            b = 0.4520926166137188E-1
+            v = 0.1253698826711277E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1856213098637712E+0
+            b = 0.7086468177864818E-1
+            v = 0.1366266117678531E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2174998728035131E+0
+            b = 0.9785239488772918E-1
+            v = 0.1462736856106918E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2494128336938330E+0
+            b = 0.1258106396267210E+0
+            v = 0.1545076466685412E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2812321562143480E+0
+            b = 0.1544529125047001E+0
+            v = 0.1615096280814007E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3128372276456111E+0
+            b = 0.1835433512202753E+0
+            v = 0.1674366639741759E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3441145160177973E+0
+            b = 0.2128813258619585E+0
+            v = 0.1724225002437900E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3749567714853510E+0
+            b = 0.2422913734880829E+0
+            v = 0.1765810822987288E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4052621732015610E+0
+            b = 0.2716163748391453E+0
+            v = 0.1800104126010751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4349335453522385E+0
+            b = 0.3007127671240280E+0
+            v = 0.1827960437331284E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4638776641524965E+0
+            b = 0.3294470677216479E+0
+            v = 0.1850140300716308E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4920046410462687E+0
+            b = 0.3576932543699155E+0
+            v = 0.1867333507394938E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5192273554861704E+0
+            b = 0.3853307059757764E+0
+            v = 0.1880178688638289E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5454609081136522E+0
+            b = 0.4122425044452694E+0
+            v = 0.1889278925654758E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5706220661424140E+0
+            b = 0.4383139587781027E+0
+            v = 0.1895213832507346E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5946286755181518E+0
+            b = 0.4634312536300553E+0
+            v = 0.1898548277397420E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.1905370790924295E+0
+            b = 0.2371311537781979E-1
+            v = 0.1349105935937341E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2242518717748009E+0
+            b = 0.4917878059254806E-1
+            v = 0.1444060068369326E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2577190808025936E+0
+            b = 0.7595498960495142E-1
+            v = 0.1526797390930008E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2908724534927187E+0
+            b = 0.1036991083191100E+0
+            v = 0.1598208771406474E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3236354020056219E+0
+            b = 0.1321348584450234E+0
+            v = 0.1659354368615331E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3559267359304543E+0
+            b = 0.1610316571314789E+0
+            v = 0.1711279910946440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3876637123676956E+0
+            b = 0.1901912080395707E+0
+            v = 0.1754952725601440E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4187636705218842E+0
+            b = 0.2194384950137950E+0
+            v = 0.1791247850802529E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4491449019883107E+0
+            b = 0.2486155334763858E+0
+            v = 0.1820954300877716E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4787270932425445E+0
+            b = 0.2775768931812335E+0
+            v = 0.1844788524548449E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5074315153055574E+0
+            b = 0.3061863786591120E+0
+            v = 0.1863409481706220E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5351810507738336E+0
+            b = 0.3343144718152556E+0
+            v = 0.1877433008795068E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5619001025975381E+0
+            b = 0.3618362729028427E+0
+            v = 0.1887444543705232E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5875144035268046E+0
+            b = 0.3886297583620408E+0
+            v = 0.1894009829375006E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6119507308734495E+0
+            b = 0.4145742277792031E+0
+            v = 0.1897683345035198E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2619733870119463E+0
+            b = 0.2540047186389353E-1
+            v = 0.1517327037467653E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.2968149743237949E+0
+            b = 0.5208107018543989E-1
+            v = 0.1587740557483543E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3310451504860488E+0
+            b = 0.7971828470885599E-1
+            v = 0.1649093382274097E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3646215567376676E+0
+            b = 0.1080465999177927E+0
+            v = 0.1701915216193265E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3974916785279360E+0
+            b = 0.1368413849366629E+0
+            v = 0.1746847753144065E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4295967403772029E+0
+            b = 0.1659073184763559E+0
+            v = 0.1784555512007570E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4608742854473447E+0
+            b = 0.1950703730454614E+0
+            v = 0.1815687562112174E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4912598858949903E+0
+            b = 0.2241721144376724E+0
+            v = 0.1840864370663302E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5206882758945558E+0
+            b = 0.2530655255406489E+0
+            v = 0.1860676785390006E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5490940914019819E+0
+            b = 0.2816118409731066E+0
+            v = 0.1875690583743703E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5764123302025542E+0
+            b = 0.3096780504593238E+0
+            v = 0.1886453236347225E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6025786004213506E+0
+            b = 0.3371348366394987E+0
+            v = 0.1893501123329645E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6275291964794956E+0
+            b = 0.3638547827694396E+0
+            v = 0.1897366184519868E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3348189479861771E+0
+            b = 0.2664841935537443E-1
+            v = 0.1643908815152736E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.3699515545855295E+0
+            b = 0.5424000066843495E-1
+            v = 0.1696300350907768E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4042003071474669E+0
+            b = 0.8251992715430854E-1
+            v = 0.1741553103844483E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4375320100182624E+0
+            b = 0.1112695182483710E+0
+            v = 0.1780015282386092E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4699054490335947E+0
+            b = 0.1402964116467816E+0
+            v = 0.1812116787077125E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5012739879431952E+0
+            b = 0.1694275117584291E+0
+            v = 0.1838323158085421E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5315874883754966E+0
+            b = 0.1985038235312689E+0
+            v = 0.1859113119837737E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5607937109622117E+0
+            b = 0.2273765660020893E+0
+            v = 0.1874969220221698E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5888393223495521E+0
+            b = 0.2559041492849764E+0
+            v = 0.1886375612681076E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6156705979160163E+0
+            b = 0.2839497251976899E+0
+            v = 0.1893819575809276E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6412338809078123E+0
+            b = 0.3113791060500690E+0
+            v = 0.1897794748256767E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4076051259257167E+0
+            b = 0.2757792290858463E-1
+            v = 0.1738963926584846E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4423788125791520E+0
+            b = 0.5584136834984293E-1
+            v = 0.1777442359873466E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4760480917328258E+0
+            b = 0.8457772087727143E-1
+            v = 0.1810010815068719E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5085838725946297E+0
+            b = 0.1135975846359248E+0
+            v = 0.1836920318248129E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5399513637391218E+0
+            b = 0.1427286904765053E+0
+            v = 0.1858489473214328E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5701118433636380E+0
+            b = 0.1718112740057635E+0
+            v = 0.1875079342496592E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5990240530606021E+0
+            b = 0.2006944855985351E+0
+            v = 0.1887080239102310E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6266452685139695E+0
+            b = 0.2292335090598907E+0
+            v = 0.1894905752176822E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6529320971415942E+0
+            b = 0.2572871512353714E+0
+            v = 0.1898991061200695E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.4791583834610126E+0
+            b = 0.2826094197735932E-1
+            v = 0.1809065016458791E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5130373952796940E+0
+            b = 0.5699871359683649E-1
+            v = 0.1836297121596799E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5456252429628476E+0
+            b = 0.8602712528554394E-1
+            v = 0.1858426916241869E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5768956329682385E+0
+            b = 0.1151748137221281E+0
+            v = 0.1875654101134641E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6068186944699046E+0
+            b = 0.1442811654136362E+0
+            v = 0.1888240751833503E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6353622248024907E+0
+            b = 0.1731930321657680E+0
+            v = 0.1896497383866979E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6624927035731797E+0
+            b = 0.2017619958756061E+0
+            v = 0.1900775530219121E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5484933508028488E+0
+            b = 0.2874219755907391E-1
+            v = 0.1858525041478814E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.5810207682142106E+0
+            b = 0.5778312123713695E-1
+            v = 0.1876248690077947E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6120955197181352E+0
+            b = 0.8695262371439526E-1
+            v = 0.1889404439064607E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6416944284294319E+0
+            b = 0.1160893767057166E+0
+            v = 0.1898168539265290E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6697926391731260E+0
+            b = 0.1450378826743251E+0
+            v = 0.1902779940661772E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6147594390585488E+0
+            b = 0.2904957622341456E-1
+            v = 0.1890125641731815E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6455390026356783E+0
+            b = 0.5823809152617197E-1
+            v = 0.1899434637795751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6747258588365477E+0
+            b = 0.8740384899884715E-1
+            v = 0.1904520856831751E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+            a = 0.6772135750395347E+0
+            b = 0.2919946135808105E-1
+            v = 0.1905534498734563E-3
+            leb_tmp, start = get_lebedev_recurrence_points(6, start, a, b, v, leb_tmp)
+
+        case _:
+            raise Exception('Angular grid unrecognized, choices are 6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350, 434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810')  # noqa: E501
+
+    leb_tmp.n = degree
+    return leb_tmp
+
+
+def get_lebedev_recurrence_points(type_, start, a, b, v, leb):
+    c = 0.0
+
+    match type_:
+
+        case 1:
+            a = 1.0
+
+            leb.x[start] = a
+            leb.y[start] = 0.0
+            leb.z[start] = 0.0
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = 0.0
+            leb.z[start + 1] = 0.0
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = 0.0
+            leb.y[start + 2] = a
+            leb.z[start + 2] = 0.0
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = 0.0
+            leb.y[start + 3] = -a
+            leb.z[start + 3] = 0.0
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = 0.0
+            leb.y[start + 4] = 0.0
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = 0.0
+            leb.y[start + 5] = 0.0
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+            start = start + 6
+
+        case 2:
+            a = sqrt(0.5)
+            leb.x[start] = 0.0
+            leb.y[start] = a
+            leb.z[start] = a
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = 0.0
+            leb.y[start + 1] = -a
+            leb.z[start + 1] = a
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = 0.0
+            leb.y[start + 2] = a
+            leb.z[start + 2] = -a
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = 0.0
+            leb.y[start + 3] = -a
+            leb.z[start + 3] = -a
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = a
+            leb.y[start + 4] = 0.0
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = 0.0
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = 0.0
+            leb.z[start + 6] = a
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = 0.0
+            leb.z[start + 7] = -a
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = a
+            leb.y[start + 8] = a
+            leb.z[start + 8] = 0.0
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -a
+            leb.y[start + 9] = a
+            leb.z[start + 9] = 0.0
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = -a
+            leb.z[start + 10] = 0.0
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = -a
+            leb.z[start + 11] = 0.0
+            leb.w[start + 11] = 4.0 * pi * v
+            start = start + 12
+
+        case 3:
+            a = sqrt(1.0 / 3.0)
+            leb.x[start] = a
+            leb.y[start] = a
+            leb.z[start] = a
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = a
+            leb.z[start + 1] = a
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -a
+            leb.z[start + 2] = a
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = a
+            leb.z[start + 3] = -a
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -a
+            leb.z[start + 4] = a
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = -a
+            leb.z[start + 5] = -a
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = a
+            leb.z[start + 6] = -a
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = -a
+            leb.w[start + 7] = 4.0 * pi * v
+            start = start + 8
+
+        case 4:
+            # /* In this case A is inputed */
+            b = sqrt(1.0 - 2.0 * a * a)
+            leb.x[start] = a
+            leb.y[start] = a
+            leb.z[start] = b
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = a
+            leb.z[start + 1] = b
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -a
+            leb.z[start + 2] = b
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = a
+            leb.z[start + 3] = -b
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -a
+            leb.z[start + 4] = b
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = -a
+            leb.y[start + 5] = a
+            leb.z[start + 5] = -b
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = a
+            leb.y[start + 6] = -a
+            leb.z[start + 6] = -b
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = -b
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = -a
+            leb.y[start + 8] = b
+            leb.z[start + 8] = a
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = a
+            leb.y[start + 9] = -b
+            leb.z[start + 9] = a
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = b
+            leb.z[start + 10] = -a
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = -b
+            leb.z[start + 11] = a
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = -a
+            leb.y[start + 12] = b
+            leb.z[start + 12] = -a
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = a
+            leb.y[start + 13] = -b
+            leb.z[start + 13] = -a
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = -a
+            leb.y[start + 14] = -b
+            leb.z[start + 14] = -a
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = a
+            leb.y[start + 15] = b
+            leb.z[start + 15] = a
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = b
+            leb.y[start + 16] = a
+            leb.z[start + 16] = a
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = -b
+            leb.y[start + 17] = a
+            leb.z[start + 17] = a
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = b
+            leb.y[start + 18] = -a
+            leb.z[start + 18] = a
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = b
+            leb.y[start + 19] = a
+            leb.z[start + 19] = -a
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = -b
+            leb.y[start + 20] = -a
+            leb.z[start + 20] = a
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = -b
+            leb.y[start + 21] = a
+            leb.z[start + 21] = -a
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = b
+            leb.y[start + 22] = -a
+            leb.z[start + 22] = -a
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = -b
+            leb.y[start + 23] = -a
+            leb.z[start + 23] = -a
+            leb.w[start + 23] = 4.0 * pi * v
+            start = start + 24
+
+        case 5:
+            # /* A is inputed in this case as well*/
+            b = sqrt(1 - a * a)
+            leb.x[start] = a
+            leb.y[start] = b
+            leb.z[start] = 0.0
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = b
+            leb.z[start + 1] = 0.0
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -b
+            leb.z[start + 2] = 0.0
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = -a
+            leb.y[start + 3] = -b
+            leb.z[start + 3] = 0.0
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = b
+            leb.y[start + 4] = a
+            leb.z[start + 4] = 0.0
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = -b
+            leb.y[start + 5] = a
+            leb.z[start + 5] = 0.0
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = b
+            leb.y[start + 6] = -a
+            leb.z[start + 6] = 0.0
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -b
+            leb.y[start + 7] = -a
+            leb.z[start + 7] = 0.0
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = a
+            leb.y[start + 8] = 0.0
+            leb.z[start + 8] = b
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -a
+            leb.y[start + 9] = 0.0
+            leb.z[start + 9] = b
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = a
+            leb.y[start + 10] = 0.0
+            leb.z[start + 10] = -b
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = -a
+            leb.y[start + 11] = 0.0
+            leb.z[start + 11] = -b
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = b
+            leb.y[start + 12] = 0.0
+            leb.z[start + 12] = a
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = -b
+            leb.y[start + 13] = 0.0
+            leb.z[start + 13] = a
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = b
+            leb.y[start + 14] = 0.0
+            leb.z[start + 14] = -a
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = -b
+            leb.y[start + 15] = 0.0
+            leb.z[start + 15] = -a
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = 0.0
+            leb.y[start + 16] = a
+            leb.z[start + 16] = b
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = 0.0
+            leb.y[start + 17] = -a
+            leb.z[start + 17] = b
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = 0.0
+            leb.y[start + 18] = a
+            leb.z[start + 18] = -b
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = 0.0
+            leb.y[start + 19] = -a
+            leb.z[start + 19] = -b
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = 0.0
+            leb.y[start + 20] = b
+            leb.z[start + 20] = a
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = 0.0
+            leb.y[start + 21] = -b
+            leb.z[start + 21] = a
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = 0.0
+            leb.y[start + 22] = b
+            leb.z[start + 22] = -a
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = 0.0
+            leb.y[start + 23] = -b
+            leb.z[start + 23] = -a
+            leb.w[start + 23] = 4.0 * pi * v
+            start = start + 24
+
+        case 6:
+            # /* both A and B are inputed in this case */
+            c = sqrt(1.0 - a * a - b * b)
+            leb.x[start] = a
+            leb.y[start] = b
+            leb.z[start] = c
+            leb.w[start] = 4.0 * pi * v
+
+            leb.x[start + 1] = -a
+            leb.y[start + 1] = b
+            leb.z[start + 1] = c
+            leb.w[start + 1] = 4.0 * pi * v
+
+            leb.x[start + 2] = a
+            leb.y[start + 2] = -b
+            leb.z[start + 2] = c
+            leb.w[start + 2] = 4.0 * pi * v
+
+            leb.x[start + 3] = a
+            leb.y[start + 3] = b
+            leb.z[start + 3] = -c
+            leb.w[start + 3] = 4.0 * pi * v
+
+            leb.x[start + 4] = -a
+            leb.y[start + 4] = -b
+            leb.z[start + 4] = c
+            leb.w[start + 4] = 4.0 * pi * v
+
+            leb.x[start + 5] = a
+            leb.y[start + 5] = -b
+            leb.z[start + 5] = -c
+            leb.w[start + 5] = 4.0 * pi * v
+
+            leb.x[start + 6] = -a
+            leb.y[start + 6] = b
+            leb.z[start + 6] = -c
+            leb.w[start + 6] = 4.0 * pi * v
+
+            leb.x[start + 7] = -a
+            leb.y[start + 7] = -b
+            leb.z[start + 7] = -c
+            leb.w[start + 7] = 4.0 * pi * v
+
+            leb.x[start + 8] = b
+            leb.y[start + 8] = a
+            leb.z[start + 8] = c
+            leb.w[start + 8] = 4.0 * pi * v
+
+            leb.x[start + 9] = -b
+            leb.y[start + 9] = a
+            leb.z[start + 9] = c
+            leb.w[start + 9] = 4.0 * pi * v
+
+            leb.x[start + 10] = b
+            leb.y[start + 10] = -a
+            leb.z[start + 10] = c
+            leb.w[start + 10] = 4.0 * pi * v
+
+            leb.x[start + 11] = b
+            leb.y[start + 11] = a
+            leb.z[start + 11] = -c
+            leb.w[start + 11] = 4.0 * pi * v
+
+            leb.x[start + 12] = -b
+            leb.y[start + 12] = -a
+            leb.z[start + 12] = c
+            leb.w[start + 12] = 4.0 * pi * v
+
+            leb.x[start + 13] = b
+            leb.y[start + 13] = -a
+            leb.z[start + 13] = -c
+            leb.w[start + 13] = 4.0 * pi * v
+
+            leb.x[start + 14] = -b
+            leb.y[start + 14] = a
+            leb.z[start + 14] = -c
+            leb.w[start + 14] = 4.0 * pi * v
+
+            leb.x[start + 15] = -b
+            leb.y[start + 15] = -a
+            leb.z[start + 15] = -c
+            leb.w[start + 15] = 4.0 * pi * v
+
+            leb.x[start + 16] = c
+            leb.y[start + 16] = a
+            leb.z[start + 16] = b
+            leb.w[start + 16] = 4.0 * pi * v
+
+            leb.x[start + 17] = -c
+            leb.y[start + 17] = a
+            leb.z[start + 17] = b
+            leb.w[start + 17] = 4.0 * pi * v
+
+            leb.x[start + 18] = c
+            leb.y[start + 18] = -a
+            leb.z[start + 18] = b
+            leb.w[start + 18] = 4.0 * pi * v
+
+            leb.x[start + 19] = c
+            leb.y[start + 19] = a
+            leb.z[start + 19] = -b
+            leb.w[start + 19] = 4.0 * pi * v
+
+            leb.x[start + 20] = -c
+            leb.y[start + 20] = -a
+            leb.z[start + 20] = b
+            leb.w[start + 20] = 4.0 * pi * v
+
+            leb.x[start + 21] = c
+            leb.y[start + 21] = -a
+            leb.z[start + 21] = -b
+            leb.w[start + 21] = 4.0 * pi * v
+
+            leb.x[start + 22] = -c
+            leb.y[start + 22] = a
+            leb.z[start + 22] = -b
+            leb.w[start + 22] = 4.0 * pi * v
+
+            leb.x[start + 23] = -c
+            leb.y[start + 23] = -a
+            leb.z[start + 23] = -b
+            leb.w[start + 23] = 4.0 * pi * v
+
+            leb.x[start + 24] = c
+            leb.y[start + 24] = b
+            leb.z[start + 24] = a
+            leb.w[start + 24] = 4.0 * pi * v
+
+            leb.x[start + 25] = -c
+            leb.y[start + 25] = b
+            leb.z[start + 25] = a
+            leb.w[start + 25] = 4.0 * pi * v
+
+            leb.x[start + 26] = c
+            leb.y[start + 26] = -b
+            leb.z[start + 26] = a
+            leb.w[start + 26] = 4.0 * pi * v
+
+            leb.x[start + 27] = c
+            leb.y[start + 27] = b
+            leb.z[start + 27] = -a
+            leb.w[start + 27] = 4.0 * pi * v
+
+            leb.x[start + 28] = -c
+            leb.y[start + 28] = -b
+            leb.z[start + 28] = a
+            leb.w[start + 28] = 4.0 * pi * v
+
+            leb.x[start + 29] = c
+            leb.y[start + 29] = -b
+            leb.z[start + 29] = -a
+            leb.w[start + 29] = 4.0 * pi * v
+
+            leb.x[start + 30] = -c
+            leb.y[start + 30] = b
+            leb.z[start + 30] = -a
+            leb.w[start + 30] = 4.0 * pi * v
+
+            leb.x[start + 31] = -c
+            leb.y[start + 31] = -b
+            leb.z[start + 31] = -a
+            leb.w[start + 31] = 4.0 * pi * v
+
+            leb.x[start + 32] = a
+            leb.y[start + 32] = c
+            leb.z[start + 32] = b
+            leb.w[start + 32] = 4.0 * pi * v
+
+            leb.x[start + 33] = -a
+            leb.y[start + 33] = c
+            leb.z[start + 33] = b
+            leb.w[start + 33] = 4.0 * pi * v
+
+            leb.x[start + 34] = a
+            leb.y[start + 34] = -c
+            leb.z[start + 34] = b
+            leb.w[start + 34] = 4.0 * pi * v
+
+            leb.x[start + 35] = a
+            leb.y[start + 35] = c
+            leb.z[start + 35] = -b
+            leb.w[start + 35] = 4.0 * pi * v
+
+            leb.x[start + 36] = -a
+            leb.y[start + 36] = -c
+            leb.z[start + 36] = b
+            leb.w[start + 36] = 4.0 * pi * v
+
+            leb.x[start + 37] = a
+            leb.y[start + 37] = -c
+            leb.z[start + 37] = -b
+            leb.w[start + 37] = 4.0 * pi * v
+
+            leb.x[start + 38] = -a
+            leb.y[start + 38] = c
+            leb.z[start + 38] = -b
+            leb.w[start + 38] = 4.0 * pi * v
+
+            leb.x[start + 39] = -a
+            leb.y[start + 39] = -c
+            leb.z[start + 39] = -b
+            leb.w[start + 39] = 4.0 * pi * v
+
+            leb.x[start + 40] = b
+            leb.y[start + 40] = c
+            leb.z[start + 40] = a
+            leb.w[start + 40] = 4.0 * pi * v
+
+            leb.x[start + 41] = -b
+            leb.y[start + 41] = c
+            leb.z[start + 41] = a
+            leb.w[start + 41] = 4.0 * pi * v
+
+            leb.x[start + 42] = b
+            leb.y[start + 42] = -c
+            leb.z[start + 42] = a
+            leb.w[start + 42] = 4.0 * pi * v
+
+            leb.x[start + 43] = b
+            leb.y[start + 43] = c
+            leb.z[start + 43] = -a
+            leb.w[start + 43] = 4.0 * pi * v
+
+            leb.x[start + 44] = -b
+            leb.y[start + 44] = -c
+            leb.z[start + 44] = a
+            leb.w[start + 44] = 4.0 * pi * v
+
+            leb.x[start + 45] = b
+            leb.y[start + 45] = -c
+            leb.z[start + 45] = -a
+            leb.w[start + 45] = 4.0 * pi * v
+
+            leb.x[start + 46] = -b
+            leb.y[start + 46] = c
+            leb.z[start + 46] = -a
+            leb.w[start + 46] = 4.0 * pi * v
+
+            leb.x[start + 47] = -b
+            leb.y[start + 47] = -c
+            leb.z[start + 47] = -a
+            leb.w[start + 47] = 4.0 * pi * v
+            start = start + 48
+
+        case _:
+            raise Exception('Bad grid order')
+
+    return leb, start
+
+
+def lebedev_rule(n):
+    r"""Lebedev quadrature.
+
+    Compute the sample points and weights for Lebedev quadrature [1]_
+    for integration of a function over the surface of a unit sphere.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order. See Notes for supported values.
+
+    Returns
+    -------
+    x : ndarray of shape ``(3, m)``
+        Sample points on the unit sphere in Cartesian coordinates.
+        ``m`` is the "degree" corresponding with the specified order; see Notes.
+    w : ndarray of shape ``(m,)``
+        Weights
+
+    Notes
+    -----
+    Implemented by translating the Matlab code of [2]_ to Python.
+
+    The available orders (argument `n`) are::
+
+        3, 5, 7, 9, 11, 13, 15, 17,
+        19, 21, 23, 25, 27, 29, 31, 35,
+        41, 47, 53, 59, 65, 71, 77, 83,
+        89, 95, 101, 107, 113, 119, 125, 131
+
+    The corresponding degrees ``m`` are::
+
+        6, 14, 26, 38, 50, 74, 86, 110,
+        146, 170, 194, 230, 266, 302, 350, 434,
+        590, 770, 974, 1202, 1454, 1730, 2030, 2354,
+        2702, 3074, 3470, 3890, 4334, 4802, 5294, 5810
+
+    References
+    ----------
+    .. [1] V.I. Lebedev, and D.N. Laikov. "A quadrature formula for the sphere of
+           the 131st algebraic order of accuracy". Doklady Mathematics, Vol. 59,
+           No. 3, 1999, pp. 477-481.
+    .. [2] R. Parrish. ``getLebedevSphere``. Matlab Central File Exchange.
+           https://www.mathworks.com/matlabcentral/fileexchange/27097-getlebedevsphere.
+    .. [3] Bellet, Jean-Baptiste, Matthieu Brachet, and Jean-Pierre Croisille.
+           "Quadrature and symmetry on the Cubed Sphere." Journal of Computational and
+           Applied Mathematics 409 (2022): 114142. :doi:`10.1016/j.cam.2022.114142`.
+
+    Examples
+    --------
+    An example given in [3]_ is integration of :math:`f(x, y, z) = \exp(x)` over a
+    sphere of radius :math:`1`; the reference there is ``14.7680137457653``.
+    Show the convergence to the expected result as the order increases:
+
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> from scipy.integrate import lebedev_rule
+    >>>
+    >>> def f(x):
+    ...     return np.exp(x[0])
+    >>>
+    >>> res = []
+    >>> orders = np.arange(3, 20, 2)
+    >>> for n in orders:
+    ...     x, w = lebedev_rule(n)
+    ...     res.append(w @ f(x))
+    >>>
+    >>> ref = np.full_like(res, 14.7680137457653)
+    >>> err = abs(res - ref)/abs(ref)
+    >>> plt.semilogy(orders, err)
+    >>> plt.xlabel('order $n$')
+    >>> plt.ylabel('relative error')
+    >>> plt.title(r'Convergence for $f(x, y, z) = \exp(x)$')
+    >>> plt.show()
+
+    """
+    degree = [6, 14, 26, 38, 50, 74, 86, 110, 146, 170, 194, 230, 266, 302, 350,
+              434, 590, 770, 974, 1202, 1454, 1730, 2030, 2354, 2702, 3074, 3470,
+              3890, 4334, 4802, 5294, 5810]
+    order = [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 35, 41, 47,
+             53, 59, 65, 71, 77, 83, 89, 95, 101, 107, 113, 119, 125, 131]
+    order_degree_map = dict(zip(order, degree))
+
+    if n not in order_degree_map:
+        message = f"Order {n=} not available. Available orders are {order}."
+        raise NotImplementedError(message)
+
+    degree = order_degree_map[n]
+    res = get_lebedev_sphere(degree)
+    x = np.stack((res.x, res.y, res.z))
+    w = res.w
+
+    return x, w
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ode.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ode.py
new file mode 100644
index 0000000000000000000000000000000000000000..72d9da2495da768753f45796e8df1996cd70d382
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_ode.py
@@ -0,0 +1,1388 @@
+# Authors: Pearu Peterson, Pauli Virtanen, John Travers
+"""
+First-order ODE integrators.
+
+User-friendly interface to various numerical integrators for solving a
+system of first order ODEs with prescribed initial conditions::
+
+    d y(t)[i]
+    ---------  = f(t,y(t))[i],
+       d t
+
+    y(t=0)[i] = y0[i],
+
+where::
+
+    i = 0, ..., len(y0) - 1
+
+class ode
+---------
+
+A generic interface class to numeric integrators. It has the following
+methods::
+
+    integrator = ode(f, jac=None)
+    integrator = integrator.set_integrator(name, **params)
+    integrator = integrator.set_initial_value(y0, t0=0.0)
+    integrator = integrator.set_f_params(*args)
+    integrator = integrator.set_jac_params(*args)
+    y1 = integrator.integrate(t1, step=False, relax=False)
+    flag = integrator.successful()
+
+class complex_ode
+-----------------
+
+This class has the same generic interface as ode, except it can handle complex
+f, y and Jacobians by transparently translating them into the equivalent
+real-valued system. It supports the real-valued solvers (i.e., not zvode) and is
+an alternative to ode with the zvode solver, sometimes performing better.
+"""
+# XXX: Integrators must have:
+# ===========================
+# cvode - C version of vode and vodpk with many improvements.
+#   Get it from http://www.netlib.org/ode/cvode.tar.gz.
+#   To wrap cvode to Python, one must write the extension module by
+#   hand. Its interface is too much 'advanced C' that using f2py
+#   would be too complicated (or impossible).
+#
+# How to define a new integrator:
+# ===============================
+#
+# class myodeint(IntegratorBase):
+#
+#     runner =  or None
+#
+#     def __init__(self,...):                           # required
+#         
+#
+#     def reset(self,n,has_jac):                        # optional
+#         # n - the size of the problem (number of equations)
+#         # has_jac - whether user has supplied its own routine for Jacobian
+#         
+#
+#     def run(self,f,jac,y0,t0,t1,f_params,jac_params): # required
+#         # this method is called to integrate from t=t0 to t=t1
+#         # with initial condition y0. f and jac are user-supplied functions
+#         # that define the problem. f_params,jac_params are additional
+#         # arguments
+#         # to these functions.
+#         
+#         if :
+#             self.success = 0
+#         return t1,y1
+#
+#     # In addition, one can define step() and run_relax() methods (they
+#     # take the same arguments as run()) if the integrator can support
+#     # these features (see IntegratorBase doc strings).
+#
+# if myodeint.runner:
+#     IntegratorBase.integrator_classes.append(myodeint)
+
+__all__ = ['ode', 'complex_ode']
+
+import re
+import threading
+import warnings
+
+from numpy import asarray, array, zeros, isscalar, real, imag, vstack
+
+from . import _vode
+from . import _dop
+from . import _lsoda
+
+
+_dop_int_dtype = _dop.types.intvar.dtype
+_vode_int_dtype = _vode.types.intvar.dtype
+_lsoda_int_dtype = _lsoda.types.intvar.dtype
+
+
+# lsoda, vode and zvode are not thread-safe. VODE_LOCK protects both vode and
+# zvode; they share the `def run` implementation
+LSODA_LOCK = threading.Lock()
+VODE_LOCK = threading.Lock()
+
+
+# ------------------------------------------------------------------------------
+# User interface
+# ------------------------------------------------------------------------------
+
+
+class ode:
+    """
+    A generic interface class to numeric integrators.
+
+    Solve an equation system :math:`y'(t) = f(t,y)` with (optional) ``jac = df/dy``.
+
+    *Note*: The first two arguments of ``f(t, y, ...)`` are in the
+    opposite order of the arguments in the system definition function used
+    by `scipy.integrate.odeint`.
+
+    Parameters
+    ----------
+    f : callable ``f(t, y, *f_args)``
+        Right-hand side of the differential equation. t is a scalar,
+        ``y.shape == (n,)``.
+        ``f_args`` is set by calling ``set_f_params(*args)``.
+        `f` should return a scalar, array or list (not a tuple).
+    jac : callable ``jac(t, y, *jac_args)``, optional
+        Jacobian of the right-hand side, ``jac[i,j] = d f[i] / d y[j]``.
+        ``jac_args`` is set by calling ``set_jac_params(*args)``.
+
+    Attributes
+    ----------
+    t : float
+        Current time.
+    y : ndarray
+        Current variable values.
+
+    See also
+    --------
+    odeint : an integrator with a simpler interface based on lsoda from ODEPACK
+    quad : for finding the area under a curve
+
+    Notes
+    -----
+    Available integrators are listed below. They can be selected using
+    the `set_integrator` method.
+
+    "vode"
+
+        Real-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        implicit Adams method (for non-stiff problems) and a method based on
+        backward differentiation formulas (BDF) (for stiff problems).
+
+        Source: http://www.netlib.org/ode/vode.f
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "vode" integrator at the same time.
+
+        This integrator accepts the following parameters in `set_integrator`
+        method of the `ode` class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - lband : None or int
+        - uband : None or int
+          Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
+          Setting these requires your jac routine to return the jacobian
+          in packed format, jac_packed[i-j+uband, j] = jac[i,j]. The
+          dimension of the matrix must be (lband+uband+1, len(y)).
+        - method: 'adams' or 'bdf'
+          Which solver to use, Adams (non-stiff) or BDF (stiff)
+        - with_jacobian : bool
+          This option is only considered when the user has not supplied a
+          Jacobian function and has not indicated (by setting either band)
+          that the Jacobian is banded. In this case, `with_jacobian` specifies
+          whether the iteration method of the ODE solver's correction step is
+          chord iteration with an internally generated full Jacobian or
+          functional iteration with no Jacobian.
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - min_step : float
+        - max_step : float
+          Limits for the step sizes used by the integrator.
+        - order : int
+          Maximum order used by the integrator,
+          order <= 12 for Adams, <= 5 for BDF.
+
+    "zvode"
+
+        Complex-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        implicit Adams method (for non-stiff problems) and a method based on
+        backward differentiation formulas (BDF) (for stiff problems).
+
+        Source: http://www.netlib.org/ode/zvode.f
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "zvode" integrator at the same time.
+
+        This integrator accepts the same parameters in `set_integrator`
+        as the "vode" solver.
+
+        .. note::
+
+            When using ZVODE for a stiff system, it should only be used for
+            the case in which the function f is analytic, that is, when each f(i)
+            is an analytic function of each y(j). Analyticity means that the
+            partial derivative df(i)/dy(j) is a unique complex number, and this
+            fact is critical in the way ZVODE solves the dense or banded linear
+            systems that arise in the stiff case. For a complex stiff ODE system
+            in which f is not analytic, ZVODE is likely to have convergence
+            failures, and for this problem one should instead use DVODE on the
+            equivalent real system (in the real and imaginary parts of y).
+
+    "lsoda"
+
+        Real-valued Variable-coefficient Ordinary Differential Equation
+        solver, with fixed-leading-coefficient implementation. It provides
+        automatic method switching between implicit Adams method (for non-stiff
+        problems) and a method based on backward differentiation formulas (BDF)
+        (for stiff problems).
+
+        Source: http://www.netlib.org/odepack
+
+        .. warning::
+
+           This integrator is not re-entrant. You cannot have two `ode`
+           instances using the "lsoda" integrator at the same time.
+
+        This integrator accepts the following parameters in `set_integrator`
+        method of the `ode` class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - lband : None or int
+        - uband : None or int
+          Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
+          Setting these requires your jac routine to return the jacobian
+          in packed format, jac_packed[i-j+uband, j] = jac[i,j].
+        - with_jacobian : bool
+          *Not used.*
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - min_step : float
+        - max_step : float
+          Limits for the step sizes used by the integrator.
+        - max_order_ns : int
+          Maximum order used in the nonstiff case (default 12).
+        - max_order_s : int
+          Maximum order used in the stiff case (default 5).
+        - max_hnil : int
+          Maximum number of messages reporting too small step size (t + h = t)
+          (default 0)
+        - ixpr : int
+          Whether to generate extra printing at method switches (default False).
+
+    "dopri5"
+
+        This is an explicit runge-kutta method of order (4)5 due to Dormand &
+        Prince (with stepsize control and dense output).
+
+        Authors:
+
+            E. Hairer and G. Wanner
+            Universite de Geneve, Dept. de Mathematiques
+            CH-1211 Geneve 24, Switzerland
+            e-mail:  ernst.hairer@math.unige.ch, gerhard.wanner@math.unige.ch
+
+        This code is described in [HNW93]_.
+
+        This integrator accepts the following parameters in set_integrator()
+        method of the ode class:
+
+        - atol : float or sequence
+          absolute tolerance for solution
+        - rtol : float or sequence
+          relative tolerance for solution
+        - nsteps : int
+          Maximum number of (internally defined) steps allowed during one
+          call to the solver.
+        - first_step : float
+        - max_step : float
+        - safety : float
+          Safety factor on new step selection (default 0.9)
+        - ifactor : float
+        - dfactor : float
+          Maximum factor to increase/decrease step size by in one step
+        - beta : float
+          Beta parameter for stabilised step size control.
+        - verbosity : int
+          Switch for printing messages (< 0 for no messages).
+
+    "dop853"
+
+        This is an explicit runge-kutta method of order 8(5,3) due to Dormand
+        & Prince (with stepsize control and dense output).
+
+        Options and references the same as "dopri5".
+
+    Examples
+    --------
+
+    A problem to integrate and the corresponding jacobian:
+
+    >>> from scipy.integrate import ode
+    >>>
+    >>> y0, t0 = [1.0j, 2.0], 0
+    >>>
+    >>> def f(t, y, arg1):
+    ...     return [1j*arg1*y[0] + y[1], -arg1*y[1]**2]
+    >>> def jac(t, y, arg1):
+    ...     return [[1j*arg1, 1], [0, -arg1*2*y[1]]]
+
+    The integration:
+
+    >>> r = ode(f, jac).set_integrator('zvode', method='bdf')
+    >>> r.set_initial_value(y0, t0).set_f_params(2.0).set_jac_params(2.0)
+    >>> t1 = 10
+    >>> dt = 1
+    >>> while r.successful() and r.t < t1:
+    ...     print(r.t+dt, r.integrate(r.t+dt))
+    1 [-0.71038232+0.23749653j  0.40000271+0.j        ]
+    2.0 [0.19098503-0.52359246j 0.22222356+0.j        ]
+    3.0 [0.47153208+0.52701229j 0.15384681+0.j        ]
+    4.0 [-0.61905937+0.30726255j  0.11764744+0.j        ]
+    5.0 [0.02340997-0.61418799j 0.09523835+0.j        ]
+    6.0 [0.58643071+0.339819j 0.08000018+0.j      ]
+    7.0 [-0.52070105+0.44525141j  0.06896565+0.j        ]
+    8.0 [-0.15986733-0.61234476j  0.06060616+0.j        ]
+    9.0 [0.64850462+0.15048982j 0.05405414+0.j        ]
+    10.0 [-0.38404699+0.56382299j  0.04878055+0.j        ]
+
+    References
+    ----------
+    .. [HNW93] E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary
+        Differential Equations i. Nonstiff Problems. 2nd edition.
+        Springer Series in Computational Mathematics,
+        Springer-Verlag (1993)
+
+    """
+
+    def __init__(self, f, jac=None):
+        self.stiff = 0
+        self.f = f
+        self.jac = jac
+        self.f_params = ()
+        self.jac_params = ()
+        self._y = []
+
+    @property
+    def y(self):
+        return self._y
+
+    def set_initial_value(self, y, t=0.0):
+        """Set initial conditions y(t) = y."""
+        if isscalar(y):
+            y = [y]
+        n_prev = len(self._y)
+        if not n_prev:
+            self.set_integrator('')  # find first available integrator
+        self._y = asarray(y, self._integrator.scalar)
+        self.t = t
+        self._integrator.reset(len(self._y), self.jac is not None)
+        return self
+
+    def set_integrator(self, name, **integrator_params):
+        """
+        Set integrator by name.
+
+        Parameters
+        ----------
+        name : str
+            Name of the integrator.
+        **integrator_params
+            Additional parameters for the integrator.
+        """
+        integrator = find_integrator(name)
+        if integrator is None:
+            # FIXME: this really should be raise an exception. Will that break
+            # any code?
+            message = f'No integrator name match with {name!r} or is not available.'
+            warnings.warn(message, stacklevel=2)
+        else:
+            self._integrator = integrator(**integrator_params)
+            if not len(self._y):
+                self.t = 0.0
+                self._y = array([0.0], self._integrator.scalar)
+            self._integrator.reset(len(self._y), self.jac is not None)
+        return self
+
+    def integrate(self, t, step=False, relax=False):
+        """Find y=y(t), set y as an initial condition, and return y.
+
+        Parameters
+        ----------
+        t : float
+            The endpoint of the integration step.
+        step : bool
+            If True, and if the integrator supports the step method,
+            then perform a single integration step and return.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+        relax : bool
+            If True and if the integrator supports the run_relax method,
+            then integrate until t_1 >= t and return. ``relax`` is not
+            referenced if ``step=True``.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+
+        Returns
+        -------
+        y : float
+            The integrated value at t
+        """
+        if step and self._integrator.supports_step:
+            mth = self._integrator.step
+        elif relax and self._integrator.supports_run_relax:
+            mth = self._integrator.run_relax
+        else:
+            mth = self._integrator.run
+
+        try:
+            self._y, self.t = mth(self.f, self.jac or (lambda: None),
+                                  self._y, self.t, t,
+                                  self.f_params, self.jac_params)
+        except SystemError as e:
+            # f2py issue with tuple returns, see ticket 1187.
+            raise ValueError(
+                'Function to integrate must not return a tuple.'
+            ) from e
+
+        return self._y
+
+    def successful(self):
+        """Check if integration was successful."""
+        try:
+            self._integrator
+        except AttributeError:
+            self.set_integrator('')
+        return self._integrator.success == 1
+
+    def get_return_code(self):
+        """Extracts the return code for the integration to enable better control
+        if the integration fails.
+
+        In general, a return code > 0 implies success, while a return code < 0
+        implies failure.
+
+        Notes
+        -----
+        This section describes possible return codes and their meaning, for available
+        integrators that can be selected by `set_integrator` method.
+
+        "vode"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call. (Perhaps wrong MF.)
+        -2           Excess accuracy requested. (Tolerances too small.)
+        -3           Illegal input detected. (See printed message.)
+        -4           Repeated error test failures. (Check all input.)
+        -5           Repeated convergence failures. (Perhaps bad Jacobian
+                     supplied or wrong choice of MF or tolerances.)
+        -6           Error weight became zero during problem. (Solution
+                     component i vanished, and ATOL or ATOL(i) = 0.)
+        ===========  =======
+
+        "zvode"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call. (Perhaps wrong MF.)
+        -2           Excess accuracy requested. (Tolerances too small.)
+        -3           Illegal input detected. (See printed message.)
+        -4           Repeated error test failures. (Check all input.)
+        -5           Repeated convergence failures. (Perhaps bad Jacobian
+                     supplied or wrong choice of MF or tolerances.)
+        -6           Error weight became zero during problem. (Solution
+                     component i vanished, and ATOL or ATOL(i) = 0.)
+        ===========  =======
+
+        "dopri5"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        1            Integration successful.
+        2            Integration successful (interrupted by solout).
+        -1           Input is not consistent.
+        -2           Larger nsteps is needed.
+        -3           Step size becomes too small.
+        -4           Problem is probably stiff (interrupted).
+        ===========  =======
+
+        "dop853"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        1            Integration successful.
+        2            Integration successful (interrupted by solout).
+        -1           Input is not consistent.
+        -2           Larger nsteps is needed.
+        -3           Step size becomes too small.
+        -4           Problem is probably stiff (interrupted).
+        ===========  =======
+
+        "lsoda"
+
+        ===========  =======
+        Return Code  Message
+        ===========  =======
+        2            Integration successful.
+        -1           Excess work done on this call (perhaps wrong Dfun type).
+        -2           Excess accuracy requested (tolerances too small).
+        -3           Illegal input detected (internal error).
+        -4           Repeated error test failures (internal error).
+        -5           Repeated convergence failures (perhaps bad Jacobian or tolerances).
+        -6           Error weight became zero during problem.
+        -7           Internal workspace insufficient to finish (internal error).
+        ===========  =======
+        """
+        try:
+            self._integrator
+        except AttributeError:
+            self.set_integrator('')
+        return self._integrator.istate
+
+    def set_f_params(self, *args):
+        """Set extra parameters for user-supplied function f."""
+        self.f_params = args
+        return self
+
+    def set_jac_params(self, *args):
+        """Set extra parameters for user-supplied function jac."""
+        self.jac_params = args
+        return self
+
+    def set_solout(self, solout):
+        """
+        Set callable to be called at every successful integration step.
+
+        Parameters
+        ----------
+        solout : callable
+            ``solout(t, y)`` is called at each internal integrator step,
+            t is a scalar providing the current independent position
+            y is the current solution ``y.shape == (n,)``
+            solout should return -1 to stop integration
+            otherwise it should return None or 0
+
+        """
+        if self._integrator.supports_solout:
+            self._integrator.set_solout(solout)
+            if self._y is not None:
+                self._integrator.reset(len(self._y), self.jac is not None)
+        else:
+            raise ValueError("selected integrator does not support solout,"
+                             " choose another one")
+
+
+def _transform_banded_jac(bjac):
+    """
+    Convert a real matrix of the form (for example)
+
+        [0 0 A B]        [0 0 0 B]
+        [0 0 C D]        [0 0 A D]
+        [E F G H]   to   [0 F C H]
+        [I J K L]        [E J G L]
+                         [I 0 K 0]
+
+    That is, every other column is shifted up one.
+    """
+    # Shift every other column.
+    newjac = zeros((bjac.shape[0] + 1, bjac.shape[1]))
+    newjac[1:, ::2] = bjac[:, ::2]
+    newjac[:-1, 1::2] = bjac[:, 1::2]
+    return newjac
+
+
+class complex_ode(ode):
+    """
+    A wrapper of ode for complex systems.
+
+    This functions similarly as `ode`, but re-maps a complex-valued
+    equation system to a real-valued one before using the integrators.
+
+    Parameters
+    ----------
+    f : callable ``f(t, y, *f_args)``
+        Rhs of the equation. t is a scalar, ``y.shape == (n,)``.
+        ``f_args`` is set by calling ``set_f_params(*args)``.
+    jac : callable ``jac(t, y, *jac_args)``
+        Jacobian of the rhs, ``jac[i,j] = d f[i] / d y[j]``.
+        ``jac_args`` is set by calling ``set_f_params(*args)``.
+
+    Attributes
+    ----------
+    t : float
+        Current time.
+    y : ndarray
+        Current variable values.
+
+    Examples
+    --------
+    For usage examples, see `ode`.
+
+    """
+
+    def __init__(self, f, jac=None):
+        self.cf = f
+        self.cjac = jac
+        if jac is None:
+            ode.__init__(self, self._wrap, None)
+        else:
+            ode.__init__(self, self._wrap, self._wrap_jac)
+
+    def _wrap(self, t, y, *f_args):
+        f = self.cf(*((t, y[::2] + 1j * y[1::2]) + f_args))
+        # self.tmp is a real-valued array containing the interleaved
+        # real and imaginary parts of f.
+        self.tmp[::2] = real(f)
+        self.tmp[1::2] = imag(f)
+        return self.tmp
+
+    def _wrap_jac(self, t, y, *jac_args):
+        # jac is the complex Jacobian computed by the user-defined function.
+        jac = self.cjac(*((t, y[::2] + 1j * y[1::2]) + jac_args))
+
+        # jac_tmp is the real version of the complex Jacobian.  Each complex
+        # entry in jac, say 2+3j, becomes a 2x2 block of the form
+        #     [2 -3]
+        #     [3  2]
+        jac_tmp = zeros((2 * jac.shape[0], 2 * jac.shape[1]))
+        jac_tmp[1::2, 1::2] = jac_tmp[::2, ::2] = real(jac)
+        jac_tmp[1::2, ::2] = imag(jac)
+        jac_tmp[::2, 1::2] = -jac_tmp[1::2, ::2]
+
+        ml = getattr(self._integrator, 'ml', None)
+        mu = getattr(self._integrator, 'mu', None)
+        if ml is not None or mu is not None:
+            # Jacobian is banded.  The user's Jacobian function has computed
+            # the complex Jacobian in packed format.  The corresponding
+            # real-valued version has every other column shifted up.
+            jac_tmp = _transform_banded_jac(jac_tmp)
+
+        return jac_tmp
+
+    @property
+    def y(self):
+        return self._y[::2] + 1j * self._y[1::2]
+
+    def set_integrator(self, name, **integrator_params):
+        """
+        Set integrator by name.
+
+        Parameters
+        ----------
+        name : str
+            Name of the integrator
+        **integrator_params
+            Additional parameters for the integrator.
+        """
+        if name == 'zvode':
+            raise ValueError("zvode must be used with ode, not complex_ode")
+
+        lband = integrator_params.get('lband')
+        uband = integrator_params.get('uband')
+        if lband is not None or uband is not None:
+            # The Jacobian is banded.  Override the user-supplied bandwidths
+            # (which are for the complex Jacobian) with the bandwidths of
+            # the corresponding real-valued Jacobian wrapper of the complex
+            # Jacobian.
+            integrator_params['lband'] = 2 * (lband or 0) + 1
+            integrator_params['uband'] = 2 * (uband or 0) + 1
+
+        return ode.set_integrator(self, name, **integrator_params)
+
+    def set_initial_value(self, y, t=0.0):
+        """Set initial conditions y(t) = y."""
+        y = asarray(y)
+        self.tmp = zeros(y.size * 2, 'float')
+        self.tmp[::2] = real(y)
+        self.tmp[1::2] = imag(y)
+        return ode.set_initial_value(self, self.tmp, t)
+
+    def integrate(self, t, step=False, relax=False):
+        """Find y=y(t), set y as an initial condition, and return y.
+
+        Parameters
+        ----------
+        t : float
+            The endpoint of the integration step.
+        step : bool
+            If True, and if the integrator supports the step method,
+            then perform a single integration step and return.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+        relax : bool
+            If True and if the integrator supports the run_relax method,
+            then integrate until t_1 >= t and return. ``relax`` is not
+            referenced if ``step=True``.
+            This parameter is provided in order to expose internals of
+            the implementation, and should not be changed from its default
+            value in most cases.
+
+        Returns
+        -------
+        y : float
+            The integrated value at t
+        """
+        y = ode.integrate(self, t, step, relax)
+        return y[::2] + 1j * y[1::2]
+
+    def set_solout(self, solout):
+        """
+        Set callable to be called at every successful integration step.
+
+        Parameters
+        ----------
+        solout : callable
+            ``solout(t, y)`` is called at each internal integrator step,
+            t is a scalar providing the current independent position
+            y is the current solution ``y.shape == (n,)``
+            solout should return -1 to stop integration
+            otherwise it should return None or 0
+
+        """
+        if self._integrator.supports_solout:
+            self._integrator.set_solout(solout, complex=True)
+        else:
+            raise TypeError("selected integrator does not support solouta, "
+                            "choose another one")
+
+
+# ------------------------------------------------------------------------------
+# ODE integrators
+# ------------------------------------------------------------------------------
+
+def find_integrator(name):
+    for cl in IntegratorBase.integrator_classes:
+        if re.match(name, cl.__name__, re.I):
+            return cl
+    return None
+
+
+class IntegratorConcurrencyError(RuntimeError):
+    """
+    Failure due to concurrent usage of an integrator that can be used
+    only for a single problem at a time.
+
+    """
+
+    def __init__(self, name):
+        msg = (f"Integrator `{name}` can be used to solve only a single problem "
+                "at a time. If you want to integrate multiple problems, "
+                "consider using a different integrator (see `ode.set_integrator`)")
+        RuntimeError.__init__(self, msg)
+
+
+class IntegratorBase:
+    runner = None  # runner is None => integrator is not available
+    success = None  # success==1 if integrator was called successfully
+    istate = None  # istate > 0 means success, istate < 0 means failure
+    supports_run_relax = None
+    supports_step = None
+    supports_solout = False
+    integrator_classes = []
+    scalar = float
+
+    def acquire_new_handle(self):
+        # Some of the integrators have internal state (ancient
+        # Fortran...), and so only one instance can use them at a time.
+        # We keep track of this, and fail when concurrent usage is tried.
+        self.__class__.active_global_handle += 1
+        self.handle = self.__class__.active_global_handle
+
+    def check_handle(self):
+        if self.handle is not self.__class__.active_global_handle:
+            raise IntegratorConcurrencyError(self.__class__.__name__)
+
+    def reset(self, n, has_jac):
+        """Prepare integrator for call: allocate memory, set flags, etc.
+        n - number of equations.
+        has_jac - if user has supplied function for evaluating Jacobian.
+        """
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Integrate from t=t0 to t=t1 using y0 as an initial condition.
+        Return 2-tuple (y1,t1) where y1 is the result and t=t1
+        defines the stoppage coordinate of the result.
+        """
+        raise NotImplementedError('all integrators must define '
+                                  'run(f, jac, t0, t1, y0, f_params, jac_params)')
+
+    def step(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Make one integration step and return (y1,t1)."""
+        raise NotImplementedError(f'{self.__class__.__name__} '
+                                  'does not support step() method')
+
+    def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params):
+        """Integrate from t=t0 to t>=t1 and return (y1,t)."""
+        raise NotImplementedError(f'{self.__class__.__name__} '
+                                  'does not support run_relax() method')
+
+    # XXX: __str__ method for getting visual state of the integrator
+
+
+def _vode_banded_jac_wrapper(jacfunc, ml, jac_params):
+    """
+    Wrap a banded Jacobian function with a function that pads
+    the Jacobian with `ml` rows of zeros.
+    """
+
+    def jac_wrapper(t, y):
+        jac = asarray(jacfunc(t, y, *jac_params))
+        padded_jac = vstack((jac, zeros((ml, jac.shape[1]))))
+        return padded_jac
+
+    return jac_wrapper
+
+
+class vode(IntegratorBase):
+    runner = getattr(_vode, 'dvode', None)
+
+    messages = {-1: 'Excess work done on this call. (Perhaps wrong MF.)',
+                -2: 'Excess accuracy requested. (Tolerances too small.)',
+                -3: 'Illegal input detected. (See printed message.)',
+                -4: 'Repeated error test failures. (Check all input.)',
+                -5: 'Repeated convergence failures. (Perhaps bad'
+                    ' Jacobian supplied or wrong choice of MF or tolerances.)',
+                -6: 'Error weight became zero during problem. (Solution'
+                    ' component i vanished, and ATOL or ATOL(i) = 0.)'
+                }
+    supports_run_relax = 1
+    supports_step = 1
+    active_global_handle = 0
+
+    def __init__(self,
+                 method='adams',
+                 with_jacobian=False,
+                 rtol=1e-6, atol=1e-12,
+                 lband=None, uband=None,
+                 order=12,
+                 nsteps=500,
+                 max_step=0.0,  # corresponds to infinite
+                 min_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 ):
+
+        if re.match(method, r'adams', re.I):
+            self.meth = 1
+        elif re.match(method, r'bdf', re.I):
+            self.meth = 2
+        else:
+            raise ValueError(f'Unknown integration method {method}')
+        self.with_jacobian = with_jacobian
+        self.rtol = rtol
+        self.atol = atol
+        self.mu = uband
+        self.ml = lband
+
+        self.order = order
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.min_step = min_step
+        self.first_step = first_step
+        self.success = 1
+
+        self.initialized = False
+
+    def _determine_mf_and_set_bands(self, has_jac):
+        """
+        Determine the `MF` parameter (Method Flag) for the Fortran subroutine `dvode`.
+
+        In the Fortran code, the legal values of `MF` are:
+            10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25,
+            -11, -12, -14, -15, -21, -22, -24, -25
+        but this Python wrapper does not use negative values.
+
+        Returns
+
+            mf  = 10*self.meth + miter
+
+        self.meth is the linear multistep method:
+            self.meth == 1:  method="adams"
+            self.meth == 2:  method="bdf"
+
+        miter is the correction iteration method:
+            miter == 0:  Functional iteration; no Jacobian involved.
+            miter == 1:  Chord iteration with user-supplied full Jacobian.
+            miter == 2:  Chord iteration with internally computed full Jacobian.
+            miter == 3:  Chord iteration with internally computed diagonal Jacobian.
+            miter == 4:  Chord iteration with user-supplied banded Jacobian.
+            miter == 5:  Chord iteration with internally computed banded Jacobian.
+
+        Side effects: If either self.mu or self.ml is not None and the other is None,
+        then the one that is None is set to 0.
+        """
+
+        jac_is_banded = self.mu is not None or self.ml is not None
+        if jac_is_banded:
+            if self.mu is None:
+                self.mu = 0
+            if self.ml is None:
+                self.ml = 0
+
+        # has_jac is True if the user provided a Jacobian function.
+        if has_jac:
+            if jac_is_banded:
+                miter = 4
+            else:
+                miter = 1
+        else:
+            if jac_is_banded:
+                if self.ml == self.mu == 0:
+                    miter = 3  # Chord iteration with internal diagonal Jacobian.
+                else:
+                    miter = 5  # Chord iteration with internal banded Jacobian.
+            else:
+                # self.with_jacobian is set by the user in
+                # the call to ode.set_integrator.
+                if self.with_jacobian:
+                    miter = 2  # Chord iteration with internal full Jacobian.
+                else:
+                    miter = 0  # Functional iteration; no Jacobian involved.
+
+        mf = 10 * self.meth + miter
+        return mf
+
+    def reset(self, n, has_jac):
+        mf = self._determine_mf_and_set_bands(has_jac)
+
+        if mf == 10:
+            lrw = 20 + 16 * n
+        elif mf in [11, 12]:
+            lrw = 22 + 16 * n + 2 * n * n
+        elif mf == 13:
+            lrw = 22 + 17 * n
+        elif mf in [14, 15]:
+            lrw = 22 + 18 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf == 20:
+            lrw = 20 + 9 * n
+        elif mf in [21, 22]:
+            lrw = 22 + 9 * n + 2 * n * n
+        elif mf == 23:
+            lrw = 22 + 10 * n
+        elif mf in [24, 25]:
+            lrw = 22 + 11 * n + (3 * self.ml + 2 * self.mu) * n
+        else:
+            raise ValueError(f'Unexpected mf={mf}')
+
+        if mf % 10 in [0, 3]:
+            liw = 30
+        else:
+            liw = 30 + n
+
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+
+        iwork = zeros((liw,), _vode_int_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.order
+        iwork[5] = self.nsteps
+        iwork[6] = 2  # mxhnil
+        self.iwork = iwork
+
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.rwork, self.iwork, mf]
+        self.success = 1
+        self.initialized = False
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        if self.initialized:
+            self.check_handle()
+        else:
+            self.initialized = True
+            self.acquire_new_handle()
+
+        if self.ml is not None and self.ml > 0:
+            # Banded Jacobian. Wrap the user-provided function with one
+            # that pads the Jacobian array with the extra `self.ml` rows
+            # required by the f2py-generated wrapper.
+            jac = _vode_banded_jac_wrapper(jac, self.ml, jac_params)
+
+        args = ((f, jac, y0, t0, t1) + tuple(self.call_args) +
+                (f_params, jac_params))
+
+        with VODE_LOCK:
+            y1, t, istate = self.runner(*args)
+
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        else:
+            self.call_args[3] = 2  # upgrade istate from 1 to 2
+            self.istate = 2
+        return y1, t
+
+    def step(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 2
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+    def run_relax(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 3
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+
+if vode.runner is not None:
+    IntegratorBase.integrator_classes.append(vode)
+
+
+class zvode(vode):
+    runner = getattr(_vode, 'zvode', None)
+
+    supports_run_relax = 1
+    supports_step = 1
+    scalar = complex
+    active_global_handle = 0
+
+    def reset(self, n, has_jac):
+        mf = self._determine_mf_and_set_bands(has_jac)
+
+        if mf in (10,):
+            lzw = 15 * n
+        elif mf in (11, 12):
+            lzw = 15 * n + 2 * n ** 2
+        elif mf in (-11, -12):
+            lzw = 15 * n + n ** 2
+        elif mf in (13,):
+            lzw = 16 * n
+        elif mf in (14, 15):
+            lzw = 17 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf in (-14, -15):
+            lzw = 16 * n + (2 * self.ml + self.mu) * n
+        elif mf in (20,):
+            lzw = 8 * n
+        elif mf in (21, 22):
+            lzw = 8 * n + 2 * n ** 2
+        elif mf in (-21, -22):
+            lzw = 8 * n + n ** 2
+        elif mf in (23,):
+            lzw = 9 * n
+        elif mf in (24, 25):
+            lzw = 10 * n + (3 * self.ml + 2 * self.mu) * n
+        elif mf in (-24, -25):
+            lzw = 9 * n + (2 * self.ml + self.mu) * n
+
+        lrw = 20 + n
+
+        if mf % 10 in (0, 3):
+            liw = 30
+        else:
+            liw = 30 + n
+
+        zwork = zeros((lzw,), complex)
+        self.zwork = zwork
+
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+
+        iwork = zeros((liw,), _vode_int_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.order
+        iwork[5] = self.nsteps
+        iwork[6] = 2  # mxhnil
+        self.iwork = iwork
+
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.zwork, self.rwork, self.iwork, mf]
+        self.success = 1
+        self.initialized = False
+
+
+if zvode.runner is not None:
+    IntegratorBase.integrator_classes.append(zvode)
+
+
+class dopri5(IntegratorBase):
+    runner = getattr(_dop, 'dopri5', None)
+    name = 'dopri5'
+    supports_solout = True
+
+    messages = {1: 'computation successful',
+                2: 'computation successful (interrupted by solout)',
+                -1: 'input is not consistent',
+                -2: 'larger nsteps is needed',
+                -3: 'step size becomes too small',
+                -4: 'problem is probably stiff (interrupted)',
+                }
+
+    def __init__(self,
+                 rtol=1e-6, atol=1e-12,
+                 nsteps=500,
+                 max_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 safety=0.9,
+                 ifactor=10.0,
+                 dfactor=0.2,
+                 beta=0.0,
+                 method=None,
+                 verbosity=-1,  # no messages if negative
+                 ):
+        self.rtol = rtol
+        self.atol = atol
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.first_step = first_step
+        self.safety = safety
+        self.ifactor = ifactor
+        self.dfactor = dfactor
+        self.beta = beta
+        self.verbosity = verbosity
+        self.success = 1
+        self.set_solout(None)
+
+    def set_solout(self, solout, complex=False):
+        self.solout = solout
+        self.solout_cmplx = complex
+        if solout is None:
+            self.iout = 0
+        else:
+            self.iout = 1
+
+    def reset(self, n, has_jac):
+        work = zeros((8 * n + 21,), float)
+        work[1] = self.safety
+        work[2] = self.dfactor
+        work[3] = self.ifactor
+        work[4] = self.beta
+        work[5] = self.max_step
+        work[6] = self.first_step
+        self.work = work
+        iwork = zeros((21,), _dop_int_dtype)
+        iwork[0] = self.nsteps
+        iwork[2] = self.verbosity
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork]
+        self.success = 1
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        x, y, iwork, istate = self.runner(*((f, t0, y0, t1) +
+                                          tuple(self.call_args) + (f_params,)))
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        return y, x
+
+    def _solout(self, nr, xold, x, y, nd, icomp, con):
+        if self.solout is not None:
+            if self.solout_cmplx:
+                y = y[::2] + 1j * y[1::2]
+            return self.solout(x, y)
+        else:
+            return 1
+
+
+if dopri5.runner is not None:
+    IntegratorBase.integrator_classes.append(dopri5)
+
+
+class dop853(dopri5):
+    runner = getattr(_dop, 'dop853', None)
+    name = 'dop853'
+
+    def __init__(self,
+                 rtol=1e-6, atol=1e-12,
+                 nsteps=500,
+                 max_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 safety=0.9,
+                 ifactor=6.0,
+                 dfactor=0.3,
+                 beta=0.0,
+                 method=None,
+                 verbosity=-1,  # no messages if negative
+                 ):
+        super().__init__(rtol, atol, nsteps, max_step, first_step, safety,
+                         ifactor, dfactor, beta, method, verbosity)
+
+    def reset(self, n, has_jac):
+        work = zeros((11 * n + 21,), float)
+        work[1] = self.safety
+        work[2] = self.dfactor
+        work[3] = self.ifactor
+        work[4] = self.beta
+        work[5] = self.max_step
+        work[6] = self.first_step
+        self.work = work
+        iwork = zeros((21,), _dop_int_dtype)
+        iwork[0] = self.nsteps
+        iwork[2] = self.verbosity
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, self._solout,
+                          self.iout, self.work, self.iwork]
+        self.success = 1
+
+
+if dop853.runner is not None:
+    IntegratorBase.integrator_classes.append(dop853)
+
+
+class lsoda(IntegratorBase):
+    runner = getattr(_lsoda, 'lsoda', None)
+    active_global_handle = 0
+
+    messages = {
+        2: "Integration successful.",
+        -1: "Excess work done on this call (perhaps wrong Dfun type).",
+        -2: "Excess accuracy requested (tolerances too small).",
+        -3: "Illegal input detected (internal error).",
+        -4: "Repeated error test failures (internal error).",
+        -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
+        -6: "Error weight became zero during problem.",
+        -7: "Internal workspace insufficient to finish (internal error)."
+    }
+
+    def __init__(self,
+                 with_jacobian=False,
+                 rtol=1e-6, atol=1e-12,
+                 lband=None, uband=None,
+                 nsteps=500,
+                 max_step=0.0,  # corresponds to infinite
+                 min_step=0.0,
+                 first_step=0.0,  # determined by solver
+                 ixpr=0,
+                 max_hnil=0,
+                 max_order_ns=12,
+                 max_order_s=5,
+                 method=None
+                 ):
+
+        self.with_jacobian = with_jacobian
+        self.rtol = rtol
+        self.atol = atol
+        self.mu = uband
+        self.ml = lband
+
+        self.max_order_ns = max_order_ns
+        self.max_order_s = max_order_s
+        self.nsteps = nsteps
+        self.max_step = max_step
+        self.min_step = min_step
+        self.first_step = first_step
+        self.ixpr = ixpr
+        self.max_hnil = max_hnil
+        self.success = 1
+
+        self.initialized = False
+
+    def reset(self, n, has_jac):
+        # Calculate parameters for Fortran subroutine dvode.
+        if has_jac:
+            if self.mu is None and self.ml is None:
+                jt = 1
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 4
+        else:
+            if self.mu is None and self.ml is None:
+                jt = 2
+            else:
+                if self.mu is None:
+                    self.mu = 0
+                if self.ml is None:
+                    self.ml = 0
+                jt = 5
+        lrn = 20 + (self.max_order_ns + 4) * n
+        if jt in [1, 2]:
+            lrs = 22 + (self.max_order_s + 4) * n + n * n
+        elif jt in [4, 5]:
+            lrs = 22 + (self.max_order_s + 5 + 2 * self.ml + self.mu) * n
+        else:
+            raise ValueError(f'Unexpected jt={jt}')
+        lrw = max(lrn, lrs)
+        liw = 20 + n
+        rwork = zeros((lrw,), float)
+        rwork[4] = self.first_step
+        rwork[5] = self.max_step
+        rwork[6] = self.min_step
+        self.rwork = rwork
+        iwork = zeros((liw,), _lsoda_int_dtype)
+        if self.ml is not None:
+            iwork[0] = self.ml
+        if self.mu is not None:
+            iwork[1] = self.mu
+        iwork[4] = self.ixpr
+        iwork[5] = self.nsteps
+        iwork[6] = self.max_hnil
+        iwork[7] = self.max_order_ns
+        iwork[8] = self.max_order_s
+        self.iwork = iwork
+        self.call_args = [self.rtol, self.atol, 1, 1,
+                          self.rwork, self.iwork, jt]
+        self.success = 1
+        self.initialized = False
+
+    def run(self, f, jac, y0, t0, t1, f_params, jac_params):
+        if self.initialized:
+            self.check_handle()
+        else:
+            self.initialized = True
+            self.acquire_new_handle()
+        args = [f, y0, t0, t1] + self.call_args[:-1] + \
+               [jac, self.call_args[-1], f_params, 0, jac_params]
+
+        with LSODA_LOCK:
+            y1, t, istate = self.runner(*args)
+
+        self.istate = istate
+        if istate < 0:
+            unexpected_istate_msg = f'Unexpected istate={istate:d}'
+            warnings.warn(f'{self.__class__.__name__:s}: '
+                          f'{self.messages.get(istate, unexpected_istate_msg):s}',
+                          stacklevel=2)
+            self.success = 0
+        else:
+            self.call_args[3] = 2  # upgrade istate from 1 to 2
+            self.istate = 2
+        return y1, t
+
+    def step(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 2
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+    def run_relax(self, *args):
+        itask = self.call_args[2]
+        self.call_args[2] = 3
+        r = self.run(*args)
+        self.call_args[2] = itask
+        return r
+
+
+if lsoda.runner:
+    IntegratorBase.integrator_classes.append(lsoda)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..75dfe925b312ae609d19ccbec27927c6c945176f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py
@@ -0,0 +1,273 @@
+# Author: Travis Oliphant
+
+__all__ = ['odeint', 'ODEintWarning']
+
+import numpy as np
+from . import _odepack
+from copy import copy
+import warnings
+
+from threading import Lock
+
+
+ODE_LOCK = Lock()
+
+
+class ODEintWarning(Warning):
+    """Warning raised during the execution of `odeint`."""
+    pass
+
+
+_msgs = {2: "Integration successful.",
+         1: "Nothing was done; the integration time was 0.",
+         -1: "Excess work done on this call (perhaps wrong Dfun type).",
+         -2: "Excess accuracy requested (tolerances too small).",
+         -3: "Illegal input detected (internal error).",
+         -4: "Repeated error test failures (internal error).",
+         -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
+         -6: "Error weight became zero during problem.",
+         -7: "Internal workspace insufficient to finish (internal error).",
+         -8: "Run terminated (internal error)."
+         }
+
+
+def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,
+           ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0,
+           hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12,
+           mxords=5, printmessg=0, tfirst=False):
+    """
+    Integrate a system of ordinary differential equations.
+
+    .. note:: For new code, use `scipy.integrate.solve_ivp` to solve a
+              differential equation.
+
+    Solve a system of ordinary differential equations using lsoda from the
+    FORTRAN library odepack.
+
+    Solves the initial value problem for stiff or non-stiff systems
+    of first order ode-s::
+
+        dy/dt = func(y, t, ...)  [or func(t, y, ...)]
+
+    where y can be a vector.
+
+    .. note:: By default, the required order of the first two arguments of
+              `func` are in the opposite order of the arguments in the system
+              definition function used by the `scipy.integrate.ode` class and
+              the function `scipy.integrate.solve_ivp`. To use a function with
+              the signature ``func(t, y, ...)``, the argument `tfirst` must be
+              set to ``True``.
+
+    Parameters
+    ----------
+    func : callable(y, t, ...) or callable(t, y, ...)
+        Computes the derivative of y at t.
+        If the signature is ``callable(t, y, ...)``, then the argument
+        `tfirst` must be set ``True``.
+        `func` must not modify the data in `y`, as it is a
+        view of the data used internally by the ODE solver.
+    y0 : array
+        Initial condition on y (can be a vector).
+    t : array
+        A sequence of time points for which to solve for y. The initial
+        value point should be the first element of this sequence.
+        This sequence must be monotonically increasing or monotonically
+        decreasing; repeated values are allowed.
+    args : tuple, optional
+        Extra arguments to pass to function.
+    Dfun : callable(y, t, ...) or callable(t, y, ...)
+        Gradient (Jacobian) of `func`.
+        If the signature is ``callable(t, y, ...)``, then the argument
+        `tfirst` must be set ``True``.
+        `Dfun` must not modify the data in `y`, as it is a
+        view of the data used internally by the ODE solver.
+    col_deriv : bool, optional
+        True if `Dfun` defines derivatives down columns (faster),
+        otherwise `Dfun` should define derivatives across rows.
+    full_output : bool, optional
+        True if to return a dictionary of optional outputs as the second output
+    printmessg : bool, optional
+        Whether to print the convergence message
+    tfirst : bool, optional
+        If True, the first two arguments of `func` (and `Dfun`, if given)
+        must ``t, y`` instead of the default ``y, t``.
+
+        .. versionadded:: 1.1.0
+
+    Returns
+    -------
+    y : array, shape (len(t), len(y0))
+        Array containing the value of y for each desired time in t,
+        with the initial value `y0` in the first row.
+    infodict : dict, only returned if full_output == True
+        Dictionary containing additional output information
+
+        =======  ============================================================
+        key      meaning
+        =======  ============================================================
+        'hu'     vector of step sizes successfully used for each time step
+        'tcur'   vector with the value of t reached for each time step
+                 (will always be at least as large as the input times)
+        'tolsf'  vector of tolerance scale factors, greater than 1.0,
+                 computed when a request for too much accuracy was detected
+        'tsw'    value of t at the time of the last method switch
+                 (given for each time step)
+        'nst'    cumulative number of time steps
+        'nfe'    cumulative number of function evaluations for each time step
+        'nje'    cumulative number of jacobian evaluations for each time step
+        'nqu'    a vector of method orders for each successful step
+        'imxer'  index of the component of largest magnitude in the
+                 weighted local error vector (e / ewt) on an error return, -1
+                 otherwise
+        'lenrw'  the length of the double work array required
+        'leniw'  the length of integer work array required
+        'mused'  a vector of method indicators for each successful time step:
+                 1: adams (nonstiff), 2: bdf (stiff)
+        =======  ============================================================
+
+    Other Parameters
+    ----------------
+    ml, mu : int, optional
+        If either of these are not None or non-negative, then the
+        Jacobian is assumed to be banded. These give the number of
+        lower and upper non-zero diagonals in this banded matrix.
+        For the banded case, `Dfun` should return a matrix whose
+        rows contain the non-zero bands (starting with the lowest diagonal).
+        Thus, the return matrix `jac` from `Dfun` should have shape
+        ``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
+        The data in `jac` must be stored such that ``jac[i - j + mu, j]``
+        holds the derivative of the ``i``\\ th equation with respect to the
+        ``j``\\ th state variable.  If `col_deriv` is True, the transpose of
+        this `jac` must be returned.
+    rtol, atol : float, optional
+        The input parameters `rtol` and `atol` determine the error
+        control performed by the solver.  The solver will control the
+        vector, e, of estimated local errors in y, according to an
+        inequality of the form ``max-norm of (e / ewt) <= 1``,
+        where ewt is a vector of positive error weights computed as
+        ``ewt = rtol * abs(y) + atol``.
+        rtol and atol can be either vectors the same length as y or scalars.
+        Defaults to 1.49012e-8.
+    tcrit : ndarray, optional
+        Vector of critical points (e.g., singularities) where integration
+        care should be taken.
+    h0 : float, (0: solver-determined), optional
+        The step size to be attempted on the first step.
+    hmax : float, (0: solver-determined), optional
+        The maximum absolute step size allowed.
+    hmin : float, (0: solver-determined), optional
+        The minimum absolute step size allowed.
+    ixpr : bool, optional
+        Whether to generate extra printing at method switches.
+    mxstep : int, (0: solver-determined), optional
+        Maximum number of (internally defined) steps allowed for each
+        integration point in t.
+    mxhnil : int, (0: solver-determined), optional
+        Maximum number of messages printed.
+    mxordn : int, (0: solver-determined), optional
+        Maximum order to be allowed for the non-stiff (Adams) method.
+    mxords : int, (0: solver-determined), optional
+        Maximum order to be allowed for the stiff (BDF) method.
+
+    See Also
+    --------
+    solve_ivp : solve an initial value problem for a system of ODEs
+    ode : a more object-oriented integrator based on VODE
+    quad : for finding the area under a curve
+
+    Examples
+    --------
+    The second order differential equation for the angle `theta` of a
+    pendulum acted on by gravity with friction can be written::
+
+        theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
+
+    where `b` and `c` are positive constants, and a prime (') denotes a
+    derivative. To solve this equation with `odeint`, we must first convert
+    it to a system of first order equations. By defining the angular
+    velocity ``omega(t) = theta'(t)``, we obtain the system::
+
+        theta'(t) = omega(t)
+        omega'(t) = -b*omega(t) - c*sin(theta(t))
+
+    Let `y` be the vector [`theta`, `omega`]. We implement this system
+    in Python as:
+
+    >>> import numpy as np
+    >>> def pend(y, t, b, c):
+    ...     theta, omega = y
+    ...     dydt = [omega, -b*omega - c*np.sin(theta)]
+    ...     return dydt
+    ...
+
+    We assume the constants are `b` = 0.25 and `c` = 5.0:
+
+    >>> b = 0.25
+    >>> c = 5.0
+
+    For initial conditions, we assume the pendulum is nearly vertical
+    with `theta(0)` = `pi` - 0.1, and is initially at rest, so
+    `omega(0)` = 0.  Then the vector of initial conditions is
+
+    >>> y0 = [np.pi - 0.1, 0.0]
+
+    We will generate a solution at 101 evenly spaced samples in the interval
+    0 <= `t` <= 10.  So our array of times is:
+
+    >>> t = np.linspace(0, 10, 101)
+
+    Call `odeint` to generate the solution. To pass the parameters
+    `b` and `c` to `pend`, we give them to `odeint` using the `args`
+    argument.
+
+    >>> from scipy.integrate import odeint
+    >>> sol = odeint(pend, y0, t, args=(b, c))
+
+    The solution is an array with shape (101, 2). The first column
+    is `theta(t)`, and the second is `omega(t)`. The following code
+    plots both components.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
+    >>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
+    >>> plt.legend(loc='best')
+    >>> plt.xlabel('t')
+    >>> plt.grid()
+    >>> plt.show()
+    """
+
+    if ml is None:
+        ml = -1  # changed to zero inside function call
+    if mu is None:
+        mu = -1  # changed to zero inside function call
+
+    dt = np.diff(t)
+    if not ((dt >= 0).all() or (dt <= 0).all()):
+        raise ValueError("The values in t must be monotonically increasing "
+                         "or monotonically decreasing; repeated values are "
+                         "allowed.")
+
+    t = copy(t)
+    y0 = copy(y0)
+
+    with ODE_LOCK:
+        output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
+                                full_output, rtol, atol, tcrit, h0, hmax, hmin,
+                                ixpr, mxstep, mxhnil, mxordn, mxords,
+                                int(bool(tfirst)))
+    if output[-1] < 0:
+        warning_msg = (f"{_msgs[output[-1]]} Run with full_output = 1 to "
+                       f"get quantitative information.")
+        warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
+    elif printmessg:
+        warning_msg = _msgs[output[-1]]
+        warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
+
+    if full_output:
+        output[1]['message'] = _msgs[output[-1]]
+
+    output = output[:-1]
+    if len(output) == 1:
+        return output[0]
+    else:
+        return output
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..758bac5138777dbe152c2b455b5160196d2282ca
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py
@@ -0,0 +1,682 @@
+import sys
+import copy
+import heapq
+import collections
+import functools
+import warnings
+
+import numpy as np
+
+from scipy._lib._util import MapWrapper, _FunctionWrapper
+
+
+class LRUDict(collections.OrderedDict):
+    def __init__(self, max_size):
+        self.__max_size = max_size
+
+    def __setitem__(self, key, value):
+        existing_key = (key in self)
+        super().__setitem__(key, value)
+        if existing_key:
+            self.move_to_end(key)
+        elif len(self) > self.__max_size:
+            self.popitem(last=False)
+
+    def update(self, other):
+        # Not needed below
+        raise NotImplementedError()
+
+
+class SemiInfiniteFunc:
+    """
+    Argument transform from (start, +-oo) to (0, 1)
+    """
+    def __init__(self, func, start, infty):
+        self._func = func
+        self._start = start
+        self._sgn = -1 if infty < 0 else 1
+
+        # Overflow threshold for the 1/t**2 factor
+        self._tmin = sys.float_info.min**0.5
+
+    def get_t(self, x):
+        z = self._sgn * (x - self._start) + 1
+        if z == 0:
+            # Can happen only if point not in range
+            return np.inf
+        return 1 / z
+
+    def __call__(self, t):
+        if t < self._tmin:
+            return 0.0
+        else:
+            x = self._start + self._sgn * (1 - t) / t
+            f = self._func(x)
+            return self._sgn * (f / t) / t
+
+
+class DoubleInfiniteFunc:
+    """
+    Argument transform from (-oo, oo) to (-1, 1)
+    """
+    def __init__(self, func):
+        self._func = func
+
+        # Overflow threshold for the 1/t**2 factor
+        self._tmin = sys.float_info.min**0.5
+
+    def get_t(self, x):
+        s = -1 if x < 0 else 1
+        return s / (abs(x) + 1)
+
+    def __call__(self, t):
+        if abs(t) < self._tmin:
+            return 0.0
+        else:
+            x = (1 - abs(t)) / t
+            f = self._func(x)
+            return (f / t) / t
+
+
+def _max_norm(x):
+    return np.amax(abs(x))
+
+
+def _get_sizeof(obj):
+    try:
+        return sys.getsizeof(obj)
+    except TypeError:
+        # occurs on pypy
+        if hasattr(obj, '__sizeof__'):
+            return int(obj.__sizeof__())
+        return 64
+
+
+class _Bunch:
+    def __init__(self, **kwargs):
+        self.__keys = kwargs.keys()
+        self.__dict__.update(**kwargs)
+
+    def __repr__(self):
+        key_value_pairs = ', '.join(
+            f'{k}={repr(self.__dict__[k])}' for k in self.__keys
+        )
+        return f"_Bunch({key_value_pairs})"
+
+
+def quad_vec(f, a, b, epsabs=1e-200, epsrel=1e-8, norm='2', cache_size=100e6,
+             limit=10000, workers=1, points=None, quadrature=None, full_output=False,
+             *, args=()):
+    r"""Adaptive integration of a vector-valued function.
+
+    Parameters
+    ----------
+    f : callable
+        Vector-valued function f(x) to integrate.
+    a : float
+        Initial point.
+    b : float
+        Final point.
+    epsabs : float, optional
+        Absolute tolerance.
+    epsrel : float, optional
+        Relative tolerance.
+    norm : {'max', '2'}, optional
+        Vector norm to use for error estimation.
+    cache_size : int, optional
+        Number of bytes to use for memoization.
+    limit : float or int, optional
+        An upper bound on the number of subintervals used in the adaptive
+        algorithm.
+    workers : int or map-like callable, optional
+        If `workers` is an integer, part of the computation is done in
+        parallel subdivided to this many tasks (using
+        :class:`python:multiprocessing.pool.Pool`).
+        Supply `-1` to use all cores available to the Process.
+        Alternatively, supply a map-like callable, such as
+        :meth:`python:multiprocessing.pool.Pool.map` for evaluating the
+        population in parallel.
+        This evaluation is carried out as ``workers(func, iterable)``.
+    points : list, optional
+        List of additional breakpoints.
+    quadrature : {'gk21', 'gk15', 'trapezoid'}, optional
+        Quadrature rule to use on subintervals.
+        Options: 'gk21' (Gauss-Kronrod 21-point rule),
+        'gk15' (Gauss-Kronrod 15-point rule),
+        'trapezoid' (composite trapezoid rule).
+        Default: 'gk21' for finite intervals and 'gk15' for (semi-)infinite
+    full_output : bool, optional
+        Return an additional ``info`` dictionary.
+    args : tuple, optional
+        Extra arguments to pass to function, if any.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    res : {float, array-like}
+        Estimate for the result
+    err : float
+        Error estimate for the result in the given norm
+    info : dict
+        Returned only when ``full_output=True``.
+        Info dictionary. Is an object with the attributes:
+
+            success : bool
+                Whether integration reached target precision.
+            status : int
+                Indicator for convergence, success (0),
+                failure (1), and failure due to rounding error (2).
+            neval : int
+                Number of function evaluations.
+            intervals : ndarray, shape (num_intervals, 2)
+                Start and end points of subdivision intervals.
+            integrals : ndarray, shape (num_intervals, ...)
+                Integral for each interval.
+                Note that at most ``cache_size`` values are recorded,
+                and the array may contains *nan* for missing items.
+            errors : ndarray, shape (num_intervals,)
+                Estimated integration error for each interval.
+
+    Notes
+    -----
+    The algorithm mainly follows the implementation of QUADPACK's
+    DQAG* algorithms, implementing global error control and adaptive
+    subdivision.
+
+    The algorithm here has some differences to the QUADPACK approach:
+
+    Instead of subdividing one interval at a time, the algorithm
+    subdivides N intervals with largest errors at once. This enables
+    (partial) parallelization of the integration.
+
+    The logic of subdividing "next largest" intervals first is then
+    not implemented, and we rely on the above extension to avoid
+    concentrating on "small" intervals only.
+
+    The Wynn epsilon table extrapolation is not used (QUADPACK uses it
+    for infinite intervals). This is because the algorithm here is
+    supposed to work on vector-valued functions, in an user-specified
+    norm, and the extension of the epsilon algorithm to this case does
+    not appear to be widely agreed. For max-norm, using elementwise
+    Wynn epsilon could be possible, but we do not do this here with
+    the hope that the epsilon extrapolation is mainly useful in
+    special cases.
+
+    References
+    ----------
+    [1] R. Piessens, E. de Doncker, QUADPACK (1983).
+
+    Examples
+    --------
+    We can compute integrations of a vector-valued function:
+
+    >>> from scipy.integrate import quad_vec
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> alpha = np.linspace(0.0, 2.0, num=30)
+    >>> f = lambda x: x**alpha
+    >>> x0, x1 = 0, 2
+    >>> y, err = quad_vec(f, x0, x1)
+    >>> plt.plot(alpha, y)
+    >>> plt.xlabel(r"$\alpha$")
+    >>> plt.ylabel(r"$\int_{0}^{2} x^\alpha dx$")
+    >>> plt.show()
+
+    When using the argument `workers`, one should ensure
+    that the main module is import-safe, for instance
+    by rewriting the example above as:
+
+    .. code-block:: python
+
+        from scipy.integrate import quad_vec
+        import numpy as np
+        import matplotlib.pyplot as plt
+
+        alpha = np.linspace(0.0, 2.0, num=30)
+        x0, x1 = 0, 2
+        def f(x):
+            return x**alpha
+
+        if __name__ == "__main__":
+            y, err = quad_vec(f, x0, x1, workers=2)
+    """
+    a = float(a)
+    b = float(b)
+
+    if args:
+        if not isinstance(args, tuple):
+            args = (args,)
+
+        # create a wrapped function to allow the use of map and Pool.map
+        f = _FunctionWrapper(f, args)
+
+    # Use simple transformations to deal with integrals over infinite
+    # intervals.
+    kwargs = dict(epsabs=epsabs,
+                  epsrel=epsrel,
+                  norm=norm,
+                  cache_size=cache_size,
+                  limit=limit,
+                  workers=workers,
+                  points=points,
+                  quadrature='gk15' if quadrature is None else quadrature,
+                  full_output=full_output)
+    if np.isfinite(a) and np.isinf(b):
+        f2 = SemiInfiniteFunc(f, start=a, infty=b)
+        if points is not None:
+            kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
+        return quad_vec(f2, 0, 1, **kwargs)
+    elif np.isfinite(b) and np.isinf(a):
+        f2 = SemiInfiniteFunc(f, start=b, infty=a)
+        if points is not None:
+            kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
+        res = quad_vec(f2, 0, 1, **kwargs)
+        return (-res[0],) + res[1:]
+    elif np.isinf(a) and np.isinf(b):
+        sgn = -1 if b < a else 1
+
+        # NB. explicitly split integral at t=0, which separates
+        # the positive and negative sides
+        f2 = DoubleInfiniteFunc(f)
+        if points is not None:
+            kwargs['points'] = (0,) + tuple(f2.get_t(xp) for xp in points)
+        else:
+            kwargs['points'] = (0,)
+
+        if a != b:
+            res = quad_vec(f2, -1, 1, **kwargs)
+        else:
+            res = quad_vec(f2, 1, 1, **kwargs)
+
+        return (res[0]*sgn,) + res[1:]
+    elif not (np.isfinite(a) and np.isfinite(b)):
+        raise ValueError(f"invalid integration bounds a={a}, b={b}")
+
+    norm_funcs = {
+        None: _max_norm,
+        'max': _max_norm,
+        '2': np.linalg.norm
+    }
+    if callable(norm):
+        norm_func = norm
+    else:
+        norm_func = norm_funcs[norm]
+
+    parallel_count = 128
+    min_intervals = 2
+
+    try:
+        _quadrature = {None: _quadrature_gk21,
+                       'gk21': _quadrature_gk21,
+                       'gk15': _quadrature_gk15,
+                       'trapz': _quadrature_trapezoid,  # alias for backcompat
+                       'trapezoid': _quadrature_trapezoid}[quadrature]
+    except KeyError as e:
+        raise ValueError(f"unknown quadrature {quadrature!r}") from e
+
+    if quadrature == "trapz":
+        msg = ("`quadrature='trapz'` is deprecated in favour of "
+               "`quadrature='trapezoid' and will raise an error from SciPy 1.16.0 "
+               "onwards.")
+        warnings.warn(msg, DeprecationWarning, stacklevel=2)
+
+    # Initial interval set
+    if points is None:
+        initial_intervals = [(a, b)]
+    else:
+        prev = a
+        initial_intervals = []
+        for p in sorted(points):
+            p = float(p)
+            if not (a < p < b) or p == prev:
+                continue
+            initial_intervals.append((prev, p))
+            prev = p
+        initial_intervals.append((prev, b))
+
+    global_integral = None
+    global_error = None
+    rounding_error = None
+    interval_cache = None
+    intervals = []
+    neval = 0
+
+    for x1, x2 in initial_intervals:
+        ig, err, rnd = _quadrature(x1, x2, f, norm_func)
+        neval += _quadrature.num_eval
+
+        if global_integral is None:
+            if isinstance(ig, (float, complex)):
+                # Specialize for scalars
+                if norm_func in (_max_norm, np.linalg.norm):
+                    norm_func = abs
+
+            global_integral = ig
+            global_error = float(err)
+            rounding_error = float(rnd)
+
+            cache_count = cache_size // _get_sizeof(ig)
+            interval_cache = LRUDict(cache_count)
+        else:
+            global_integral += ig
+            global_error += err
+            rounding_error += rnd
+
+        interval_cache[(x1, x2)] = copy.copy(ig)
+        intervals.append((-err, x1, x2))
+
+    heapq.heapify(intervals)
+
+    CONVERGED = 0
+    NOT_CONVERGED = 1
+    ROUNDING_ERROR = 2
+    NOT_A_NUMBER = 3
+
+    status_msg = {
+        CONVERGED: "Target precision reached.",
+        NOT_CONVERGED: "Target precision not reached.",
+        ROUNDING_ERROR: "Target precision could not be reached due to rounding error.",
+        NOT_A_NUMBER: "Non-finite values encountered."
+    }
+
+    # Process intervals
+    with MapWrapper(workers) as mapwrapper:
+        ier = NOT_CONVERGED
+
+        while intervals and len(intervals) < limit:
+            # Select intervals with largest errors for subdivision
+            tol = max(epsabs, epsrel*norm_func(global_integral))
+
+            to_process = []
+            err_sum = 0
+
+            for j in range(parallel_count):
+                if not intervals:
+                    break
+
+                if j > 0 and err_sum > global_error - tol/8:
+                    # avoid unnecessary parallel splitting
+                    break
+
+                interval = heapq.heappop(intervals)
+
+                neg_old_err, a, b = interval
+                old_int = interval_cache.pop((a, b), None)
+                to_process.append(
+                    ((-neg_old_err, a, b, old_int), f, norm_func, _quadrature)
+                )
+                err_sum += -neg_old_err
+
+            # Subdivide intervals
+            for parts in mapwrapper(_subdivide_interval, to_process):
+                dint, derr, dround_err, subint, dneval = parts
+                neval += dneval
+                global_integral += dint
+                global_error += derr
+                rounding_error += dround_err
+                for x in subint:
+                    x1, x2, ig, err = x
+                    interval_cache[(x1, x2)] = ig
+                    heapq.heappush(intervals, (-err, x1, x2))
+
+            # Termination check
+            if len(intervals) >= min_intervals:
+                tol = max(epsabs, epsrel*norm_func(global_integral))
+                if global_error < tol/8:
+                    ier = CONVERGED
+                    break
+                if global_error < rounding_error:
+                    ier = ROUNDING_ERROR
+                    break
+
+            if not (np.isfinite(global_error) and np.isfinite(rounding_error)):
+                ier = NOT_A_NUMBER
+                break
+
+    res = global_integral
+    err = global_error + rounding_error
+
+    if full_output:
+        res_arr = np.asarray(res)
+        dummy = np.full(res_arr.shape, np.nan, dtype=res_arr.dtype)
+        integrals = np.array([interval_cache.get((z[1], z[2]), dummy)
+                                      for z in intervals], dtype=res_arr.dtype)
+        errors = np.array([-z[0] for z in intervals])
+        intervals = np.array([[z[1], z[2]] for z in intervals])
+
+        info = _Bunch(neval=neval,
+                      success=(ier == CONVERGED),
+                      status=ier,
+                      message=status_msg[ier],
+                      intervals=intervals,
+                      integrals=integrals,
+                      errors=errors)
+        return (res, err, info)
+    else:
+        return (res, err)
+
+
+def _subdivide_interval(args):
+    interval, f, norm_func, _quadrature = args
+    old_err, a, b, old_int = interval
+
+    c = 0.5 * (a + b)
+
+    # Left-hand side
+    if getattr(_quadrature, 'cache_size', 0) > 0:
+        f = functools.lru_cache(_quadrature.cache_size)(f)
+
+    s1, err1, round1 = _quadrature(a, c, f, norm_func)
+    dneval = _quadrature.num_eval
+    s2, err2, round2 = _quadrature(c, b, f, norm_func)
+    dneval += _quadrature.num_eval
+    if old_int is None:
+        old_int, _, _ = _quadrature(a, b, f, norm_func)
+        dneval += _quadrature.num_eval
+
+    if getattr(_quadrature, 'cache_size', 0) > 0:
+        dneval = f.cache_info().misses
+
+    dint = s1 + s2 - old_int
+    derr = err1 + err2 - old_err
+    dround_err = round1 + round2
+
+    subintervals = ((a, c, s1, err1), (c, b, s2, err2))
+    return dint, derr, dround_err, subintervals, dneval
+
+
+def _quadrature_trapezoid(x1, x2, f, norm_func):
+    """
+    Composite trapezoid quadrature
+    """
+    x3 = 0.5*(x1 + x2)
+    f1 = f(x1)
+    f2 = f(x2)
+    f3 = f(x3)
+
+    s2 = 0.25 * (x2 - x1) * (f1 + 2*f3 + f2)
+
+    round_err = 0.25 * abs(x2 - x1) * (float(norm_func(f1))
+                                       + 2*float(norm_func(f3))
+                                       + float(norm_func(f2))) * 2e-16
+
+    s1 = 0.5 * (x2 - x1) * (f1 + f2)
+    err = 1/3 * float(norm_func(s1 - s2))
+    return s2, err, round_err
+
+
+_quadrature_trapezoid.cache_size = 3 * 3
+_quadrature_trapezoid.num_eval = 3
+
+
+def _quadrature_gk(a, b, f, norm_func, x, w, v):
+    """
+    Generic Gauss-Kronrod quadrature
+    """
+
+    fv = [0.0]*len(x)
+
+    c = 0.5 * (a + b)
+    h = 0.5 * (b - a)
+
+    # Gauss-Kronrod
+    s_k = 0.0
+    s_k_abs = 0.0
+    for i in range(len(x)):
+        ff = f(c + h*x[i])
+        fv[i] = ff
+
+        vv = v[i]
+
+        # \int f(x)
+        s_k += vv * ff
+        # \int |f(x)|
+        s_k_abs += vv * abs(ff)
+
+    # Gauss
+    s_g = 0.0
+    for i in range(len(w)):
+        s_g += w[i] * fv[2*i + 1]
+
+    # Quadrature of abs-deviation from average
+    s_k_dabs = 0.0
+    y0 = s_k / 2.0
+    for i in range(len(x)):
+        # \int |f(x) - y0|
+        s_k_dabs += v[i] * abs(fv[i] - y0)
+
+    # Use similar error estimation as quadpack
+    err = float(norm_func((s_k - s_g) * h))
+    dabs = float(norm_func(s_k_dabs * h))
+    if dabs != 0 and err != 0:
+        err = dabs * min(1.0, (200 * err / dabs)**1.5)
+
+    eps = sys.float_info.epsilon
+    round_err = float(norm_func(50 * eps * h * s_k_abs))
+
+    if round_err > sys.float_info.min:
+        err = max(err, round_err)
+
+    return h * s_k, err, round_err
+
+
+def _quadrature_gk21(a, b, f, norm_func):
+    """
+    Gauss-Kronrod 21 quadrature with error estimate
+    """
+    # Gauss-Kronrod points
+    x = (0.995657163025808080735527280689003,
+         0.973906528517171720077964012084452,
+         0.930157491355708226001207180059508,
+         0.865063366688984510732096688423493,
+         0.780817726586416897063717578345042,
+         0.679409568299024406234327365114874,
+         0.562757134668604683339000099272694,
+         0.433395394129247190799265943165784,
+         0.294392862701460198131126603103866,
+         0.148874338981631210884826001129720,
+         0,
+         -0.148874338981631210884826001129720,
+         -0.294392862701460198131126603103866,
+         -0.433395394129247190799265943165784,
+         -0.562757134668604683339000099272694,
+         -0.679409568299024406234327365114874,
+         -0.780817726586416897063717578345042,
+         -0.865063366688984510732096688423493,
+         -0.930157491355708226001207180059508,
+         -0.973906528517171720077964012084452,
+         -0.995657163025808080735527280689003)
+
+    # 10-point weights
+    w = (0.066671344308688137593568809893332,
+         0.149451349150580593145776339657697,
+         0.219086362515982043995534934228163,
+         0.269266719309996355091226921569469,
+         0.295524224714752870173892994651338,
+         0.295524224714752870173892994651338,
+         0.269266719309996355091226921569469,
+         0.219086362515982043995534934228163,
+         0.149451349150580593145776339657697,
+         0.066671344308688137593568809893332)
+
+    # 21-point weights
+    v = (0.011694638867371874278064396062192,
+         0.032558162307964727478818972459390,
+         0.054755896574351996031381300244580,
+         0.075039674810919952767043140916190,
+         0.093125454583697605535065465083366,
+         0.109387158802297641899210590325805,
+         0.123491976262065851077958109831074,
+         0.134709217311473325928054001771707,
+         0.142775938577060080797094273138717,
+         0.147739104901338491374841515972068,
+         0.149445554002916905664936468389821,
+         0.147739104901338491374841515972068,
+         0.142775938577060080797094273138717,
+         0.134709217311473325928054001771707,
+         0.123491976262065851077958109831074,
+         0.109387158802297641899210590325805,
+         0.093125454583697605535065465083366,
+         0.075039674810919952767043140916190,
+         0.054755896574351996031381300244580,
+         0.032558162307964727478818972459390,
+         0.011694638867371874278064396062192)
+
+    return _quadrature_gk(a, b, f, norm_func, x, w, v)
+
+
+_quadrature_gk21.num_eval = 21
+
+
+def _quadrature_gk15(a, b, f, norm_func):
+    """
+    Gauss-Kronrod 15 quadrature with error estimate
+    """
+    # Gauss-Kronrod points
+    x = (0.991455371120812639206854697526329,
+         0.949107912342758524526189684047851,
+         0.864864423359769072789712788640926,
+         0.741531185599394439863864773280788,
+         0.586087235467691130294144838258730,
+         0.405845151377397166906606412076961,
+         0.207784955007898467600689403773245,
+         0.000000000000000000000000000000000,
+         -0.207784955007898467600689403773245,
+         -0.405845151377397166906606412076961,
+         -0.586087235467691130294144838258730,
+         -0.741531185599394439863864773280788,
+         -0.864864423359769072789712788640926,
+         -0.949107912342758524526189684047851,
+         -0.991455371120812639206854697526329)
+
+    # 7-point weights
+    w = (0.129484966168869693270611432679082,
+         0.279705391489276667901467771423780,
+         0.381830050505118944950369775488975,
+         0.417959183673469387755102040816327,
+         0.381830050505118944950369775488975,
+         0.279705391489276667901467771423780,
+         0.129484966168869693270611432679082)
+
+    # 15-point weights
+    v = (0.022935322010529224963732008058970,
+         0.063092092629978553290700663189204,
+         0.104790010322250183839876322541518,
+         0.140653259715525918745189590510238,
+         0.169004726639267902826583426598550,
+         0.190350578064785409913256402421014,
+         0.204432940075298892414161999234649,
+         0.209482141084727828012999174891714,
+         0.204432940075298892414161999234649,
+         0.190350578064785409913256402421014,
+         0.169004726639267902826583426598550,
+         0.140653259715525918745189590510238,
+         0.104790010322250183839876322541518,
+         0.063092092629978553290700663189204,
+         0.022935322010529224963732008058970)
+
+    return _quadrature_gk(a, b, f, norm_func, x, w, v)
+
+
+_quadrature_gk15.num_eval = 15
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d273f6d2c9943f4a35f9b0c761a944b7be84cfe
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py
@@ -0,0 +1,1279 @@
+# Author: Travis Oliphant 2001
+# Author: Nathan Woods 2013 (nquad &c)
+import sys
+import warnings
+from functools import partial
+
+from . import _quadpack
+import numpy as np
+
+__all__ = ["quad", "dblquad", "tplquad", "nquad", "IntegrationWarning"]
+
+
+class IntegrationWarning(UserWarning):
+    """
+    Warning on issues during integration.
+    """
+    pass
+
+
+def quad(func, a, b, args=(), full_output=0, epsabs=1.49e-8, epsrel=1.49e-8,
+         limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50,
+         limlst=50, complex_func=False):
+    """
+    Compute a definite integral.
+
+    Integrate func from `a` to `b` (possibly infinite interval) using a
+    technique from the Fortran library QUADPACK.
+
+    Parameters
+    ----------
+    func : {function, scipy.LowLevelCallable}
+        A Python function or method to integrate. If `func` takes many
+        arguments, it is integrated along the axis corresponding to the
+        first argument.
+
+        If the user desires improved integration performance, then `f` may
+        be a `scipy.LowLevelCallable` with one of the signatures::
+
+            double func(double x)
+            double func(double x, void *user_data)
+            double func(int n, double *xx)
+            double func(int n, double *xx, void *user_data)
+
+        The ``user_data`` is the data contained in the `scipy.LowLevelCallable`.
+        In the call forms with ``xx``,  ``n`` is the length of the ``xx``
+        array which contains ``xx[0] == x`` and the rest of the items are
+        numbers contained in the ``args`` argument of quad.
+
+        In addition, certain ctypes call signatures are supported for
+        backward compatibility, but those should not be used in new code.
+    a : float
+        Lower limit of integration (use -numpy.inf for -infinity).
+    b : float
+        Upper limit of integration (use numpy.inf for +infinity).
+    args : tuple, optional
+        Extra arguments to pass to `func`.
+    full_output : int, optional
+        Non-zero to return a dictionary of integration information.
+        If non-zero, warning messages are also suppressed and the
+        message is appended to the output tuple.
+    complex_func : bool, optional
+        Indicate if the function's (`func`) return type is real
+        (``complex_func=False``: default) or complex (``complex_func=True``).
+        In both cases, the function's argument is real.
+        If full_output is also non-zero, the `infodict`, `message`, and
+        `explain` for the real and complex components are returned in
+        a dictionary with keys "real output" and "imag output".
+
+    Returns
+    -------
+    y : float
+        The integral of func from `a` to `b`.
+    abserr : float
+        An estimate of the absolute error in the result.
+    infodict : dict
+        A dictionary containing additional information.
+    message
+        A convergence message.
+    explain
+        Appended only with 'cos' or 'sin' weighting and infinite
+        integration limits, it contains an explanation of the codes in
+        infodict['ierlst']
+
+    Other Parameters
+    ----------------
+    epsabs : float or int, optional
+        Absolute error tolerance. Default is 1.49e-8. `quad` tries to obtain
+        an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``
+        where ``i`` = integral of `func` from `a` to `b`, and ``result`` is the
+        numerical approximation. See `epsrel` below.
+    epsrel : float or int, optional
+        Relative error tolerance. Default is 1.49e-8.
+        If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29
+        and ``50 * (machine epsilon)``. See `epsabs` above.
+    limit : float or int, optional
+        An upper bound on the number of subintervals used in the adaptive
+        algorithm.
+    points : (sequence of floats,ints), optional
+        A sequence of break points in the bounded integration interval
+        where local difficulties of the integrand may occur (e.g.,
+        singularities, discontinuities). The sequence does not have
+        to be sorted. Note that this option cannot be used in conjunction
+        with ``weight``.
+    weight : float or int, optional
+        String indicating weighting function. Full explanation for this
+        and the remaining arguments can be found below.
+    wvar : optional
+        Variables for use with weighting functions.
+    wopts : optional
+        Optional input for reusing Chebyshev moments.
+    maxp1 : float or int, optional
+        An upper bound on the number of Chebyshev moments.
+    limlst : int, optional
+        Upper bound on the number of cycles (>=3) for use with a sinusoidal
+        weighting and an infinite end-point.
+
+    See Also
+    --------
+    dblquad : double integral
+    tplquad : triple integral
+    nquad : n-dimensional integrals (uses `quad` recursively)
+    fixed_quad : fixed-order Gaussian quadrature
+    simpson : integrator for sampled data
+    romb : integrator for sampled data
+    scipy.special : for coefficients and roots of orthogonal polynomials
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Extra information for quad() inputs and outputs**
+
+    If full_output is non-zero, then the third output argument
+    (infodict) is a dictionary with entries as tabulated below. For
+    infinite limits, the range is transformed to (0,1) and the
+    optional outputs are given with respect to this transformed range.
+    Let M be the input argument limit and let K be infodict['last'].
+    The entries are:
+
+    'neval'
+        The number of function evaluations.
+    'last'
+        The number, K, of subintervals produced in the subdivision process.
+    'alist'
+        A rank-1 array of length M, the first K elements of which are the
+        left end points of the subintervals in the partition of the
+        integration range.
+    'blist'
+        A rank-1 array of length M, the first K elements of which are the
+        right end points of the subintervals.
+    'rlist'
+        A rank-1 array of length M, the first K elements of which are the
+        integral approximations on the subintervals.
+    'elist'
+        A rank-1 array of length M, the first K elements of which are the
+        moduli of the absolute error estimates on the subintervals.
+    'iord'
+        A rank-1 integer array of length M, the first L elements of
+        which are pointers to the error estimates over the subintervals
+        with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
+        sequence ``infodict['iord']`` and let E be the sequence
+        ``infodict['elist']``.  Then ``E[I[1]], ..., E[I[L]]`` forms a
+        decreasing sequence.
+
+    If the input argument points is provided (i.e., it is not None),
+    the following additional outputs are placed in the output
+    dictionary. Assume the points sequence is of length P.
+
+    'pts'
+        A rank-1 array of length P+2 containing the integration limits
+        and the break points of the intervals in ascending order.
+        This is an array giving the subintervals over which integration
+        will occur.
+    'level'
+        A rank-1 integer array of length M (=limit), containing the
+        subdivision levels of the subintervals, i.e., if (aa,bb) is a
+        subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
+        are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
+        if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
+    'ndin'
+        A rank-1 integer array of length P+2. After the first integration
+        over the intervals (pts[1], pts[2]), the error estimates over some
+        of the intervals may have been increased artificially in order to
+        put their subdivision forward. This array has ones in slots
+        corresponding to the subintervals for which this happens.
+
+    **Weighting the integrand**
+
+    The input variables, *weight* and *wvar*, are used to weight the
+    integrand by a select list of functions. Different integration
+    methods are used to compute the integral with these weighting
+    functions, and these do not support specifying break points. The
+    possible values of weight and the corresponding weighting functions are.
+
+    ==========  ===================================   =====================
+    ``weight``  Weight function used                  ``wvar``
+    ==========  ===================================   =====================
+    'cos'       cos(w*x)                              wvar = w
+    'sin'       sin(w*x)                              wvar = w
+    'alg'       g(x) = ((x-a)**alpha)*((b-x)**beta)   wvar = (alpha, beta)
+    'alg-loga'  g(x)*log(x-a)                         wvar = (alpha, beta)
+    'alg-logb'  g(x)*log(b-x)                         wvar = (alpha, beta)
+    'alg-log'   g(x)*log(x-a)*log(b-x)                wvar = (alpha, beta)
+    'cauchy'    1/(x-c)                               wvar = c
+    ==========  ===================================   =====================
+
+    wvar holds the parameter w, (alpha, beta), or c depending on the weight
+    selected. In these expressions, a and b are the integration limits.
+
+    For the 'cos' and 'sin' weighting, additional inputs and outputs are
+    available.
+
+    For finite integration limits, the integration is performed using a
+    Clenshaw-Curtis method which uses Chebyshev moments. For repeated
+    calculations, these moments are saved in the output dictionary:
+
+    'momcom'
+        The maximum level of Chebyshev moments that have been computed,
+        i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
+        computed for intervals of length ``|b-a| * 2**(-l)``,
+        ``l=0,1,...,M_c``.
+    'nnlog'
+        A rank-1 integer array of length M(=limit), containing the
+        subdivision levels of the subintervals, i.e., an element of this
+        array is equal to l if the corresponding subinterval is
+        ``|b-a|* 2**(-l)``.
+    'chebmo'
+        A rank-2 array of shape (25, maxp1) containing the computed
+        Chebyshev moments. These can be passed on to an integration
+        over the same interval by passing this array as the second
+        element of the sequence wopts and passing infodict['momcom'] as
+        the first element.
+
+    If one of the integration limits is infinite, then a Fourier integral is
+    computed (assuming w neq 0). If full_output is 1 and a numerical error
+    is encountered, besides the error message attached to the output tuple,
+    a dictionary is also appended to the output tuple which translates the
+    error codes in the array ``info['ierlst']`` to English messages. The
+    output information dictionary contains the following entries instead of
+    'last', 'alist', 'blist', 'rlist', and 'elist':
+
+    'lst'
+        The number of subintervals needed for the integration (call it ``K_f``).
+    'rslst'
+        A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
+        contain the integral contribution over the interval
+        ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
+        and ``k=1,2,...,K_f``.
+    'erlst'
+        A rank-1 array of length ``M_f`` containing the error estimate
+        corresponding to the interval in the same position in
+        ``infodict['rslist']``.
+    'ierlst'
+        A rank-1 integer array of length ``M_f`` containing an error flag
+        corresponding to the interval in the same position in
+        ``infodict['rslist']``.  See the explanation dictionary (last entry
+        in the output tuple) for the meaning of the codes.
+
+
+    **Details of QUADPACK level routines**
+
+    `quad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. The routine called depends on
+    `weight`, `points` and the integration limits `a` and `b`.
+
+    ================  ==============  ==========  =====================
+    QUADPACK routine  `weight`        `points`    infinite bounds
+    ================  ==============  ==========  =====================
+    qagse             None            No          No
+    qagie             None            No          Yes
+    qagpe             None            Yes         No
+    qawoe             'sin', 'cos'    No          No
+    qawfe             'sin', 'cos'    No          either `a` or `b`
+    qawse             'alg*'          No          No
+    qawce             'cauchy'        No          No
+    ================  ==============  ==========  =====================
+
+    The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+    qagpe
+        serves the same purposes as QAGS, but also allows the
+        user to provide explicit information about the location
+        and type of trouble-spots i.e. the abscissae of internal
+        singularities, discontinuities and other difficulties of
+        the integrand function.
+    qawoe
+        is an integrator for the evaluation of
+        :math:`\\int^b_a \\cos(\\omega x)f(x)dx` or
+        :math:`\\int^b_a \\sin(\\omega x)f(x)dx`
+        over a finite interval [a,b], where :math:`\\omega` and :math:`f`
+        are specified by the user. The rule evaluation component is based
+        on the modified Clenshaw-Curtis technique
+
+        An adaptive subdivision scheme is used in connection
+        with an extrapolation procedure, which is a modification
+        of that in ``QAGS`` and allows the algorithm to deal with
+        singularities in :math:`f(x)`.
+    qawfe
+        calculates the Fourier transform
+        :math:`\\int^\\infty_a \\cos(\\omega x)f(x)dx` or
+        :math:`\\int^\\infty_a \\sin(\\omega x)f(x)dx`
+        for user-provided :math:`\\omega` and :math:`f`. The procedure of
+        ``QAWO`` is applied on successive finite intervals, and convergence
+        acceleration by means of the :math:`\\varepsilon`-algorithm is applied
+        to the series of integral approximations.
+    qawse
+        approximate :math:`\\int^b_a w(x)f(x)dx`, with :math:`a < b` where
+        :math:`w(x) = (x-a)^{\\alpha}(b-x)^{\\beta}v(x)` with
+        :math:`\\alpha,\\beta > -1`, where :math:`v(x)` may be one of the
+        following functions: :math:`1`, :math:`\\log(x-a)`, :math:`\\log(b-x)`,
+        :math:`\\log(x-a)\\log(b-x)`.
+
+        The user specifies :math:`\\alpha`, :math:`\\beta` and the type of the
+        function :math:`v`. A globally adaptive subdivision strategy is
+        applied, with modified Clenshaw-Curtis integration on those
+        subintervals which contain `a` or `b`.
+    qawce
+        compute :math:`\\int^b_a f(x) / (x-c)dx` where the integral must be
+        interpreted as a Cauchy principal value integral, for user specified
+        :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
+        Clenshaw-Curtis integration is used on those intervals containing the
+        point :math:`x = c`.
+
+    **Integration of Complex Function of a Real Variable**
+
+    A complex valued function, :math:`f`, of a real variable can be written as
+    :math:`f = g + ih`.  Similarly, the integral of :math:`f` can be
+    written as
+
+    .. math::
+        \\int_a^b f(x) dx = \\int_a^b g(x) dx + i\\int_a^b h(x) dx
+
+    assuming that the integrals of :math:`g` and :math:`h` exist
+    over the interval :math:`[a,b]` [2]_. Therefore, ``quad`` integrates
+    complex-valued functions by integrating the real and imaginary components
+    separately.
+
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    .. [2] McCullough, Thomas; Phillips, Keith (1973).
+           Foundations of Analysis in the Complex Plane.
+           Holt Rinehart Winston.
+           ISBN 0-03-086370-8
+
+    Examples
+    --------
+    Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result
+
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x2 = lambda x: x**2
+    >>> integrate.quad(x2, 0, 4)
+    (21.333333333333332, 2.3684757858670003e-13)
+    >>> print(4**3 / 3.)  # analytical result
+    21.3333333333
+
+    Calculate :math:`\\int^\\infty_0 e^{-x} dx`
+
+    >>> invexp = lambda x: np.exp(-x)
+    >>> integrate.quad(invexp, 0, np.inf)
+    (1.0, 5.842605999138044e-11)
+
+    Calculate :math:`\\int^1_0 a x \\,dx` for :math:`a = 1, 3`
+
+    >>> f = lambda x, a: a*x
+    >>> y, err = integrate.quad(f, 0, 1, args=(1,))
+    >>> y
+    0.5
+    >>> y, err = integrate.quad(f, 0, 1, args=(3,))
+    >>> y
+    1.5
+
+    Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding
+    y parameter as 1::
+
+        testlib.c =>
+            double func(int n, double args[n]){
+                return args[0]*args[0] + args[1]*args[1];}
+        compile to library testlib.*
+
+    ::
+
+       from scipy import integrate
+       import ctypes
+       lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
+       lib.func.restype = ctypes.c_double
+       lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
+       integrate.quad(lib.func,0,1,(1))
+       #(1.3333333333333333, 1.4802973661668752e-14)
+       print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
+       # 1.3333333333333333
+
+    Be aware that pulse shapes and other sharp features as compared to the
+    size of the integration interval may not be integrated correctly using
+    this method. A simplified example of this limitation is integrating a
+    y-axis reflected step function with many zero values within the integrals
+    bounds.
+
+    >>> y = lambda x: 1 if x<=0 else 0
+    >>> integrate.quad(y, -1, 1)
+    (1.0, 1.1102230246251565e-14)
+    >>> integrate.quad(y, -1, 100)
+    (1.0000000002199108, 1.0189464580163188e-08)
+    >>> integrate.quad(y, -1, 10000)
+    (0.0, 0.0)
+
+    """
+    if not isinstance(args, tuple):
+        args = (args,)
+
+    # check the limits of integration: \int_a^b, expect a < b
+    flip, a, b = b < a, min(a, b), max(a, b)
+
+    if complex_func:
+        def imfunc(x, *args):
+            return func(x, *args).imag
+
+        def refunc(x, *args):
+            return func(x, *args).real
+
+        re_retval = quad(refunc, a, b, args, full_output, epsabs,
+                         epsrel, limit, points, weight, wvar, wopts,
+                         maxp1, limlst, complex_func=False)
+        im_retval = quad(imfunc, a, b, args, full_output, epsabs,
+                         epsrel, limit, points, weight, wvar, wopts,
+                         maxp1, limlst, complex_func=False)
+        integral = re_retval[0] + 1j*im_retval[0]
+        error_estimate = re_retval[1] + 1j*im_retval[1]
+        retval = integral, error_estimate
+        if full_output:
+            msgexp = {}
+            msgexp["real"] = re_retval[2:]
+            msgexp["imag"] = im_retval[2:]
+            retval = retval + (msgexp,)
+
+        return retval
+
+    if weight is None:
+        retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
+                       points)
+    else:
+        if points is not None:
+            msg = ("Break points cannot be specified when using weighted integrand.\n"
+                   "Continuing, ignoring specified points.")
+            warnings.warn(msg, IntegrationWarning, stacklevel=2)
+        retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
+                              limlst, limit, maxp1, weight, wvar, wopts)
+
+    if flip:
+        retval = (-retval[0],) + retval[1:]
+
+    ier = retval[-1]
+    if ier == 0:
+        return retval[:-1]
+
+    msgs = {80: "A Python error occurred possibly while calling the function.",
+             1: f"The maximum number of subdivisions ({limit}) has been achieved.\n  "
+                f"If increasing the limit yields no improvement it is advised to "
+                f"analyze \n  the integrand in order to determine the difficulties.  "
+                f"If the position of a \n  local difficulty can be determined "
+                f"(singularity, discontinuity) one will \n  probably gain from "
+                f"splitting up the interval and calling the integrator \n  on the "
+                f"subranges.  Perhaps a special-purpose integrator should be used.",
+             2: "The occurrence of roundoff error is detected, which prevents \n  "
+                "the requested tolerance from being achieved.  "
+                "The error may be \n  underestimated.",
+             3: "Extremely bad integrand behavior occurs at some points of the\n  "
+                "integration interval.",
+             4: "The algorithm does not converge.  Roundoff error is detected\n  "
+                "in the extrapolation table.  It is assumed that the requested "
+                "tolerance\n  cannot be achieved, and that the returned result "
+                "(if full_output = 1) is \n  the best which can be obtained.",
+             5: "The integral is probably divergent, or slowly convergent.",
+             6: "The input is invalid.",
+             7: "Abnormal termination of the routine.  The estimates for result\n  "
+                "and error are less reliable.  It is assumed that the requested "
+                "accuracy\n  has not been achieved.",
+            'unknown': "Unknown error."}
+
+    if weight in ['cos','sin'] and (b == np.inf or a == -np.inf):
+        msgs[1] = (
+            "The maximum number of cycles allowed has been achieved., e.e.\n  of "
+            "subintervals (a+(k-1)c, a+kc) where c = (2*int(abs(omega)+1))\n  "
+            "*pi/abs(omega), for k = 1, 2, ..., lst.  "
+            "One can allow more cycles by increasing the value of limlst.  "
+            "Look at info['ierlst'] with full_output=1."
+        )
+        msgs[4] = (
+            "The extrapolation table constructed for convergence acceleration\n  of "
+            "the series formed by the integral contributions over the cycles, \n  does "
+            "not converge to within the requested accuracy.  "
+            "Look at \n  info['ierlst'] with full_output=1."
+        )
+        msgs[7] = (
+            "Bad integrand behavior occurs within one or more of the cycles.\n  "
+            "Location and type of the difficulty involved can be determined from \n  "
+            "the vector info['ierlist'] obtained with full_output=1."
+        )
+        explain = {1: "The maximum number of subdivisions (= limit) has been \n  "
+                      "achieved on this cycle.",
+                   2: "The occurrence of roundoff error is detected and prevents\n  "
+                      "the tolerance imposed on this cycle from being achieved.",
+                   3: "Extremely bad integrand behavior occurs at some points of\n  "
+                      "this cycle.",
+                   4: "The integral over this cycle does not converge (to within the "
+                      "required accuracy) due to roundoff in the extrapolation "
+                      "procedure invoked on this cycle.  It is assumed that the result "
+                      "on this interval is the best which can be obtained.",
+                   5: "The integral over this cycle is probably divergent or "
+                      "slowly convergent."}
+
+    try:
+        msg = msgs[ier]
+    except KeyError:
+        msg = msgs['unknown']
+
+    if ier in [1,2,3,4,5,7]:
+        if full_output:
+            if weight in ['cos', 'sin'] and (b == np.inf or a == -np.inf):
+                return retval[:-1] + (msg, explain)
+            else:
+                return retval[:-1] + (msg,)
+        else:
+            warnings.warn(msg, IntegrationWarning, stacklevel=2)
+            return retval[:-1]
+
+    elif ier == 6:  # Forensic decision tree when QUADPACK throws ier=6
+        if epsabs <= 0:  # Small error tolerance - applies to all methods
+            if epsrel < max(50 * sys.float_info.epsilon, 5e-29):
+                msg = ("If 'epsabs'<=0, 'epsrel' must be greater than both"
+                       " 5e-29 and 50*(machine epsilon).")
+            elif weight in ['sin', 'cos'] and (abs(a) + abs(b) == np.inf):
+                msg = ("Sine or cosine weighted integrals with infinite domain"
+                       " must have 'epsabs'>0.")
+
+        elif weight is None:
+            if points is None:  # QAGSE/QAGIE
+                msg = ("Invalid 'limit' argument. There must be"
+                       " at least one subinterval")
+            else:  # QAGPE
+                if not (min(a, b) <= min(points) <= max(points) <= max(a, b)):
+                    msg = ("All break points in 'points' must lie within the"
+                           " integration limits.")
+                elif len(points) >= limit:
+                    msg = (f"Number of break points ({len(points):d}) "
+                           f"must be less than subinterval limit ({limit:d})")
+
+        else:
+            if maxp1 < 1:
+                msg = "Chebyshev moment limit maxp1 must be >=1."
+
+            elif weight in ('cos', 'sin') and abs(a+b) == np.inf:  # QAWFE
+                msg = "Cycle limit limlst must be >=3."
+
+            elif weight.startswith('alg'):  # QAWSE
+                if min(wvar) < -1:
+                    msg = "wvar parameters (alpha, beta) must both be >= -1."
+                if b < a:
+                    msg = "Integration limits a, b must satistfy a>> import numpy as np
+    >>> from scipy import integrate
+    >>> f = lambda y, x: x*y**2
+    >>> integrate.dblquad(f, 0, 2, 0, 1)
+        (0.6666666666666667, 7.401486830834377e-15)
+
+    Calculate :math:`\\int^{x=\\pi/4}_{x=0} \\int^{y=\\cos(x)}_{y=\\sin(x)} 1
+    \\,dy \\,dx`.
+
+    >>> f = lambda y, x: 1
+    >>> integrate.dblquad(f, 0, np.pi/4, np.sin, np.cos)
+        (0.41421356237309503, 1.1083280054755938e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=2-x}_{y=x} a x y \\,dy \\,dx`
+    for :math:`a=1, 3`.
+
+    >>> f = lambda y, x, a: a*x*y
+    >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(1,))
+        (0.33333333333333337, 5.551115123125783e-15)
+    >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(3,))
+        (0.9999999999999999, 1.6653345369377348e-14)
+
+    Compute the two-dimensional Gaussian Integral, which is the integral of the
+    Gaussian function :math:`f(x,y) = e^{-(x^{2} + y^{2})}`, over
+    :math:`(-\\infty,+\\infty)`. That is, compute the integral
+    :math:`\\iint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2})} \\,dy\\,dx`.
+
+    >>> f = lambda x, y: np.exp(-(x ** 2 + y ** 2))
+    >>> integrate.dblquad(f, -np.inf, np.inf, -np.inf, np.inf)
+        (3.141592653589777, 2.5173086737433208e-08)
+
+    """
+
+    def temp_ranges(*args):
+        return [gfun(args[0]) if callable(gfun) else gfun,
+                hfun(args[0]) if callable(hfun) else hfun]
+
+    return nquad(func, [temp_ranges, [a, b]], args=args,
+            opts={"epsabs": epsabs, "epsrel": epsrel})
+
+
+def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=1.49e-8,
+            epsrel=1.49e-8):
+    """
+    Compute a triple (definite) integral.
+
+    Return the triple integral of ``func(z, y, x)`` from ``x = a..b``,
+    ``y = gfun(x)..hfun(x)``, and ``z = qfun(x,y)..rfun(x,y)``.
+
+    Parameters
+    ----------
+    func : function
+        A Python function or method of at least three variables in the
+        order (z, y, x).
+    a, b : float
+        The limits of integration in x: `a` < `b`
+    gfun : function or float
+        The lower boundary curve in y which is a function taking a single
+        floating point argument (x) and returning a floating point result
+        or a float indicating a constant boundary curve.
+    hfun : function or float
+        The upper boundary curve in y (same requirements as `gfun`).
+    qfun : function or float
+        The lower boundary surface in z.  It must be a function that takes
+        two floats in the order (x, y) and returns a float or a float
+        indicating a constant boundary surface.
+    rfun : function or float
+        The upper boundary surface in z. (Same requirements as `qfun`.)
+    args : tuple, optional
+        Extra arguments to pass to `func`.
+    epsabs : float, optional
+        Absolute tolerance passed directly to the innermost 1-D quadrature
+        integration. Default is 1.49e-8.
+    epsrel : float, optional
+        Relative tolerance of the innermost 1-D integrals. Default is 1.49e-8.
+
+    Returns
+    -------
+    y : float
+        The resultant integral.
+    abserr : float
+        An estimate of the error.
+
+    See Also
+    --------
+    quad : Adaptive quadrature using QUADPACK
+    fixed_quad : Fixed-order Gaussian quadrature
+    dblquad : Double integrals
+    nquad : N-dimensional integrals
+    romb : Integrators for sampled data
+    simpson : Integrators for sampled data
+    scipy.special : For coefficients and roots of orthogonal polynomials
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Details of QUADPACK level routines**
+
+    `quad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. For each level of integration, ``qagse``
+    is used for finite limits or ``qagie`` is used, if either limit (or both!)
+    are infinite. The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    Examples
+    --------
+    Compute the triple integral of ``x * y * z``, over ``x`` ranging
+    from 1 to 2, ``y`` ranging from 2 to 3, ``z`` ranging from 0 to 1.
+    That is, :math:`\\int^{x=2}_{x=1} \\int^{y=3}_{y=2} \\int^{z=1}_{z=0} x y z
+    \\,dz \\,dy \\,dx`.
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> f = lambda z, y, x: x*y*z
+    >>> integrate.tplquad(f, 1, 2, 2, 3, 0, 1)
+    (1.8749999999999998, 3.3246447942574074e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1-2x}_{y=0}
+    \\int^{z=1-x-2y}_{z=0} x y z \\,dz \\,dy \\,dx`.
+    Note: `qfun`/`rfun` takes arguments in the order (x, y), even though ``f``
+    takes arguments in the order (z, y, x).
+
+    >>> f = lambda z, y, x: x*y*z
+    >>> integrate.tplquad(f, 0, 1, 0, lambda x: 1-2*x, 0, lambda x, y: 1-x-2*y)
+    (0.05416666666666668, 2.1774196738157757e-14)
+
+    Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1}_{y=0} \\int^{z=1}_{z=0}
+    a x y z \\,dz \\,dy \\,dx` for :math:`a=1, 3`.
+
+    >>> f = lambda z, y, x, a: a*x*y*z
+    >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(1,))
+        (0.125, 5.527033708952211e-15)
+    >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(3,))
+        (0.375, 1.6581101126856635e-14)
+
+    Compute the three-dimensional Gaussian Integral, which is the integral of
+    the Gaussian function :math:`f(x,y,z) = e^{-(x^{2} + y^{2} + z^{2})}`, over
+    :math:`(-\\infty,+\\infty)`. That is, compute the integral
+    :math:`\\iiint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2} + z^{2})} \\,dz
+    \\,dy\\,dx`.
+
+    >>> f = lambda x, y, z: np.exp(-(x ** 2 + y ** 2 + z ** 2))
+    >>> integrate.tplquad(f, -np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf)
+        (5.568327996830833, 4.4619078828029765e-08)
+
+    """
+    # f(z, y, x)
+    # qfun/rfun(x, y)
+    # gfun/hfun(x)
+    # nquad will hand (y, x, t0, ...) to ranges0
+    # nquad will hand (x, t0, ...) to ranges1
+    # Only qfun / rfun is different API...
+
+    def ranges0(*args):
+        return [qfun(args[1], args[0]) if callable(qfun) else qfun,
+                rfun(args[1], args[0]) if callable(rfun) else rfun]
+
+    def ranges1(*args):
+        return [gfun(args[0]) if callable(gfun) else gfun,
+                hfun(args[0]) if callable(hfun) else hfun]
+
+    ranges = [ranges0, ranges1, [a, b]]
+    return nquad(func, ranges, args=args,
+            opts={"epsabs": epsabs, "epsrel": epsrel})
+
+
+def nquad(func, ranges, args=None, opts=None, full_output=False):
+    r"""
+    Integration over multiple variables.
+
+    Wraps `quad` to enable integration over multiple variables.
+    Various options allow improved integration of discontinuous functions, as
+    well as the use of weighted integration, and generally finer control of the
+    integration process.
+
+    Parameters
+    ----------
+    func : {callable, scipy.LowLevelCallable}
+        The function to be integrated. Has arguments of ``x0, ... xn``,
+        ``t0, ... tm``, where integration is carried out over ``x0, ... xn``,
+        which must be floats.  Where ``t0, ... tm`` are extra arguments
+        passed in args.
+        Function signature should be ``func(x0, x1, ..., xn, t0, t1, ..., tm)``.
+        Integration is carried out in order.  That is, integration over ``x0``
+        is the innermost integral, and ``xn`` is the outermost.
+
+        If the user desires improved integration performance, then `f` may
+        be a `scipy.LowLevelCallable` with one of the signatures::
+
+            double func(int n, double *xx)
+            double func(int n, double *xx, void *user_data)
+
+        where ``n`` is the number of variables and args.  The ``xx`` array
+        contains the coordinates and extra arguments. ``user_data`` is the data
+        contained in the `scipy.LowLevelCallable`.
+    ranges : iterable object
+        Each element of ranges may be either a sequence  of 2 numbers, or else
+        a callable that returns such a sequence. ``ranges[0]`` corresponds to
+        integration over x0, and so on. If an element of ranges is a callable,
+        then it will be called with all of the integration arguments available,
+        as well as any parametric arguments. e.g., if
+        ``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as
+        either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``.
+    args : iterable object, optional
+        Additional arguments ``t0, ... tn``, required by ``func``, ``ranges``,
+        and ``opts``.
+    opts : iterable object or dict, optional
+        Options to be passed to `quad`. May be empty, a dict, or
+        a sequence of dicts or functions that return a dict. If empty, the
+        default options from scipy.integrate.quad are used. If a dict, the same
+        options are used for all levels of integraion. If a sequence, then each
+        element of the sequence corresponds to a particular integration. e.g.,
+        ``opts[0]`` corresponds to integration over ``x0``, and so on. If a
+        callable, the signature must be the same as for ``ranges``. The
+        available options together with their default values are:
+
+          - epsabs = 1.49e-08
+          - epsrel = 1.49e-08
+          - limit  = 50
+          - points = None
+          - weight = None
+          - wvar   = None
+          - wopts  = None
+
+        For more information on these options, see `quad`.
+
+    full_output : bool, optional
+        Partial implementation of ``full_output`` from scipy.integrate.quad.
+        The number of integrand function evaluations ``neval`` can be obtained
+        by setting ``full_output=True`` when calling nquad.
+
+    Returns
+    -------
+    result : float
+        The result of the integration.
+    abserr : float
+        The maximum of the estimates of the absolute error in the various
+        integration results.
+    out_dict : dict, optional
+        A dict containing additional information on the integration.
+
+    See Also
+    --------
+    quad : 1-D numerical integration
+    dblquad, tplquad : double and triple integrals
+    fixed_quad : fixed-order Gaussian quadrature
+
+    Notes
+    -----
+    For valid results, the integral must converge; behavior for divergent
+    integrals is not guaranteed.
+
+    **Details of QUADPACK level routines**
+
+    `nquad` calls routines from the FORTRAN library QUADPACK. This section
+    provides details on the conditions for each routine to be called and a
+    short description of each routine. The routine called depends on
+    `weight`, `points` and the integration limits `a` and `b`.
+
+    ================  ==============  ==========  =====================
+    QUADPACK routine  `weight`        `points`    infinite bounds
+    ================  ==============  ==========  =====================
+    qagse             None            No          No
+    qagie             None            No          Yes
+    qagpe             None            Yes         No
+    qawoe             'sin', 'cos'    No          No
+    qawfe             'sin', 'cos'    No          either `a` or `b`
+    qawse             'alg*'          No          No
+    qawce             'cauchy'        No          No
+    ================  ==============  ==========  =====================
+
+    The following provides a short description from [1]_ for each
+    routine.
+
+    qagse
+        is an integrator based on globally adaptive interval
+        subdivision in connection with extrapolation, which will
+        eliminate the effects of integrand singularities of
+        several types.
+    qagie
+        handles integration over infinite intervals. The infinite range is
+        mapped onto a finite interval and subsequently the same strategy as
+        in ``QAGS`` is applied.
+    qagpe
+        serves the same purposes as QAGS, but also allows the
+        user to provide explicit information about the location
+        and type of trouble-spots i.e. the abscissae of internal
+        singularities, discontinuities and other difficulties of
+        the integrand function.
+    qawoe
+        is an integrator for the evaluation of
+        :math:`\int^b_a \cos(\omega x)f(x)dx` or
+        :math:`\int^b_a \sin(\omega x)f(x)dx`
+        over a finite interval [a,b], where :math:`\omega` and :math:`f`
+        are specified by the user. The rule evaluation component is based
+        on the modified Clenshaw-Curtis technique
+
+        An adaptive subdivision scheme is used in connection
+        with an extrapolation procedure, which is a modification
+        of that in ``QAGS`` and allows the algorithm to deal with
+        singularities in :math:`f(x)`.
+    qawfe
+        calculates the Fourier transform
+        :math:`\int^\infty_a \cos(\omega x)f(x)dx` or
+        :math:`\int^\infty_a \sin(\omega x)f(x)dx`
+        for user-provided :math:`\omega` and :math:`f`. The procedure of
+        ``QAWO`` is applied on successive finite intervals, and convergence
+        acceleration by means of the :math:`\varepsilon`-algorithm is applied
+        to the series of integral approximations.
+    qawse
+        approximate :math:`\int^b_a w(x)f(x)dx`, with :math:`a < b` where
+        :math:`w(x) = (x-a)^{\alpha}(b-x)^{\beta}v(x)` with
+        :math:`\alpha,\beta > -1`, where :math:`v(x)` may be one of the
+        following functions: :math:`1`, :math:`\log(x-a)`, :math:`\log(b-x)`,
+        :math:`\log(x-a)\log(b-x)`.
+
+        The user specifies :math:`\alpha`, :math:`\beta` and the type of the
+        function :math:`v`. A globally adaptive subdivision strategy is
+        applied, with modified Clenshaw-Curtis integration on those
+        subintervals which contain `a` or `b`.
+    qawce
+        compute :math:`\int^b_a f(x) / (x-c)dx` where the integral must be
+        interpreted as a Cauchy principal value integral, for user specified
+        :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
+        Clenshaw-Curtis integration is used on those intervals containing the
+        point :math:`x = c`.
+
+    References
+    ----------
+
+    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
+           Überhuber, Christoph W.; Kahaner, David (1983).
+           QUADPACK: A subroutine package for automatic integration.
+           Springer-Verlag.
+           ISBN 978-3-540-12553-2.
+
+    Examples
+    --------
+    Calculate
+
+    .. math::
+
+        \int^{1}_{-0.15} \int^{0.8}_{0.13} \int^{1}_{-1} \int^{1}_{0}
+        f(x_0, x_1, x_2, x_3) \,dx_0 \,dx_1 \,dx_2 \,dx_3 ,
+
+    where
+
+    .. math::
+
+        f(x_0, x_1, x_2, x_3) = \begin{cases}
+          x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+1 & (x_0-0.2 x_3-0.5-0.25 x_1 > 0) \\
+          x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+0 & (x_0-0.2 x_3-0.5-0.25 x_1 \leq 0)
+        \end{cases} .
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + (
+    ...                                 1 if (x0-.2*x3-.5-.25*x1>0) else 0)
+    >>> def opts0(*args, **kwargs):
+    ...     return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]}
+    >>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]],
+    ...                 opts=[opts0,{},{},{}], full_output=True)
+    (1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962})
+
+    Calculate
+
+    .. math::
+
+        \int^{t_0+t_1+1}_{t_0+t_1-1}
+        \int^{x_2+t_0^2 t_1^3+1}_{x_2+t_0^2 t_1^3-1}
+        \int^{t_0 x_1+t_1 x_2+1}_{t_0 x_1+t_1 x_2-1}
+        f(x_0,x_1, x_2,t_0,t_1)
+        \,dx_0 \,dx_1 \,dx_2,
+
+    where
+
+    .. math::
+
+        f(x_0, x_1, x_2, t_0, t_1) = \begin{cases}
+          x_0 x_2^2 + \sin{x_1}+2 & (x_0+t_1 x_1-t_0 > 0) \\
+          x_0 x_2^2 +\sin{x_1}+1 & (x_0+t_1 x_1-t_0 \leq 0)
+        \end{cases}
+
+    and :math:`(t_0, t_1) = (0, 1)` .
+
+    >>> def func2(x0, x1, x2, t0, t1):
+    ...     return x0*x2**2 + np.sin(x1) + 1 + (1 if x0+t1*x1-t0>0 else 0)
+    >>> def lim0(x1, x2, t0, t1):
+    ...     return [t0*x1 + t1*x2 - 1, t0*x1 + t1*x2 + 1]
+    >>> def lim1(x2, t0, t1):
+    ...     return [x2 + t0**2*t1**3 - 1, x2 + t0**2*t1**3 + 1]
+    >>> def lim2(t0, t1):
+    ...     return [t0 + t1 - 1, t0 + t1 + 1]
+    >>> def opts0(x1, x2, t0, t1):
+    ...     return {'points' : [t0 - t1*x1]}
+    >>> def opts1(x2, t0, t1):
+    ...     return {}
+    >>> def opts2(t0, t1):
+    ...     return {}
+    >>> integrate.nquad(func2, [lim0, lim1, lim2], args=(0,1),
+    ...                 opts=[opts0, opts1, opts2])
+    (36.099919226771625, 1.8546948553373528e-07)
+
+    """
+    depth = len(ranges)
+    ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges]
+    if args is None:
+        args = ()
+    if opts is None:
+        opts = [dict([])] * depth
+
+    if isinstance(opts, dict):
+        opts = [_OptFunc(opts)] * depth
+    else:
+        opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts]
+    return _NQuad(func, ranges, opts, full_output).integrate(*args)
+
+
+class _RangeFunc:
+    def __init__(self, range_):
+        self.range_ = range_
+
+    def __call__(self, *args):
+        """Return stored value.
+
+        *args needed because range_ can be float or func, and is called with
+        variable number of parameters.
+        """
+        return self.range_
+
+
+class _OptFunc:
+    def __init__(self, opt):
+        self.opt = opt
+
+    def __call__(self, *args):
+        """Return stored dict."""
+        return self.opt
+
+
+class _NQuad:
+    def __init__(self, func, ranges, opts, full_output):
+        self.abserr = 0
+        self.func = func
+        self.ranges = ranges
+        self.opts = opts
+        self.maxdepth = len(ranges)
+        self.full_output = full_output
+        if self.full_output:
+            self.out_dict = {'neval': 0}
+
+    def integrate(self, *args, **kwargs):
+        depth = kwargs.pop('depth', 0)
+        if kwargs:
+            raise ValueError('unexpected kwargs')
+
+        # Get the integration range and options for this depth.
+        ind = -(depth + 1)
+        fn_range = self.ranges[ind]
+        low, high = fn_range(*args)
+        fn_opt = self.opts[ind]
+        opt = dict(fn_opt(*args))
+
+        if 'points' in opt:
+            opt['points'] = [x for x in opt['points'] if low <= x <= high]
+        if depth + 1 == self.maxdepth:
+            f = self.func
+        else:
+            f = partial(self.integrate, depth=depth+1)
+        quad_r = quad(f, low, high, args=args, full_output=self.full_output,
+                      **opt)
+        value = quad_r[0]
+        abserr = quad_r[1]
+        if self.full_output:
+            infodict = quad_r[2]
+            # The 'neval' parameter in full_output returns the total
+            # number of times the integrand function was evaluated.
+            # Therefore, only the innermost integration loop counts.
+            if depth + 1 == self.maxdepth:
+                self.out_dict['neval'] += infodict['neval']
+        self.abserr = max(self.abserr, abserr)
+        if depth > 0:
+            return value
+        else:
+            # Final result of N-D integration with error
+            if self.full_output:
+                return value, self.abserr, self.out_dict
+            else:
+                return value, self.abserr
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_quadrature.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_quadrature.py
new file mode 100644
index 0000000000000000000000000000000000000000..44cf10b32335014cd7cb26459c8dc89ac8f851ff
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_quadrature.py
@@ -0,0 +1,1336 @@
+import numpy as np
+import numpy.typing as npt
+import math
+import warnings
+from collections import namedtuple
+from collections.abc import Callable
+
+from scipy.special import roots_legendre
+from scipy.special import gammaln, logsumexp
+from scipy._lib._util import _rng_spawn
+from scipy._lib._array_api import _asarray, array_namespace, xp_broadcast_promote
+
+
+__all__ = ['fixed_quad', 'romb',
+           'trapezoid', 'simpson',
+           'cumulative_trapezoid', 'newton_cotes',
+           'qmc_quad', 'cumulative_simpson']
+
+
+def trapezoid(y, x=None, dx=1.0, axis=-1):
+    r"""
+    Integrate along the given axis using the composite trapezoidal rule.
+
+    If `x` is provided, the integration happens in sequence along its
+    elements - they are not sorted.
+
+    Integrate `y` (`x`) along each 1d slice on the given axis, compute
+    :math:`\int y(x) dx`.
+    When `x` is specified, this integrates along the parametric curve,
+    computing :math:`\int_t y(t) dt =
+    \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
+
+    Parameters
+    ----------
+    y : array_like
+        Input array to integrate.
+    x : array_like, optional
+        The sample points corresponding to the `y` values. If `x` is None,
+        the sample points are assumed to be evenly spaced `dx` apart. The
+        default is None.
+    dx : scalar, optional
+        The spacing between sample points when `x` is None. The default is 1.
+    axis : int, optional
+        The axis along which to integrate. The default is the last axis.
+
+    Returns
+    -------
+    trapezoid : float or ndarray
+        Definite integral of `y` = n-dimensional array as approximated along
+        a single axis by the trapezoidal rule. If `y` is a 1-dimensional array,
+        then the result is a float. If `n` is greater than 1, then the result
+        is an `n`-1 dimensional array.
+
+    See Also
+    --------
+    cumulative_trapezoid, simpson, romb
+
+    Notes
+    -----
+    Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
+    will be taken from `y` array, by default x-axis distances between
+    points will be 1.0, alternatively they can be provided with `x` array
+    or with `dx` scalar.  Return value will be equal to combined area under
+    the red lines.
+
+    References
+    ----------
+    .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
+
+    .. [2] Illustration image:
+           https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
+
+    Examples
+    --------
+    Use the trapezoidal rule on evenly spaced points:
+
+    >>> import numpy as np
+    >>> from scipy import integrate
+    >>> integrate.trapezoid([1, 2, 3])
+    4.0
+
+    The spacing between sample points can be selected by either the
+    ``x`` or ``dx`` arguments:
+
+    >>> integrate.trapezoid([1, 2, 3], x=[4, 6, 8])
+    8.0
+    >>> integrate.trapezoid([1, 2, 3], dx=2)
+    8.0
+
+    Using a decreasing ``x`` corresponds to integrating in reverse:
+
+    >>> integrate.trapezoid([1, 2, 3], x=[8, 6, 4])
+    -8.0
+
+    More generally ``x`` is used to integrate along a parametric curve. We can
+    estimate the integral :math:`\int_0^1 x^2 = 1/3` using:
+
+    >>> x = np.linspace(0, 1, num=50)
+    >>> y = x**2
+    >>> integrate.trapezoid(y, x)
+    0.33340274885464394
+
+    Or estimate the area of a circle, noting we repeat the sample which closes
+    the curve:
+
+    >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
+    >>> integrate.trapezoid(np.cos(theta), x=np.sin(theta))
+    3.141571941375841
+
+    ``trapezoid`` can be applied along a specified axis to do multiple
+    computations in one call:
+
+    >>> a = np.arange(6).reshape(2, 3)
+    >>> a
+    array([[0, 1, 2],
+           [3, 4, 5]])
+    >>> integrate.trapezoid(a, axis=0)
+    array([1.5, 2.5, 3.5])
+    >>> integrate.trapezoid(a, axis=1)
+    array([2.,  8.])
+    """
+    xp = array_namespace(y)
+    y = _asarray(y, xp=xp, subok=True)
+    # Cannot just use the broadcasted arrays that are returned
+    # because trapezoid does not follow normal broadcasting rules
+    # cf. https://github.com/scipy/scipy/pull/21524#issuecomment-2354105942
+    result_dtype = xp_broadcast_promote(y, force_floating=True, xp=xp)[0].dtype
+    nd = y.ndim
+    slice1 = [slice(None)]*nd
+    slice2 = [slice(None)]*nd
+    slice1[axis] = slice(1, None)
+    slice2[axis] = slice(None, -1)
+    if x is None:
+        d = dx
+    else:
+        x = _asarray(x, xp=xp, subok=True)
+        if x.ndim == 1:
+            d = x[1:] - x[:-1]
+            # make d broadcastable to y
+            slice3 = [None] * nd
+            slice3[axis] = slice(None)
+            d = d[tuple(slice3)]
+        else:
+            # if x is n-D it should be broadcastable to y
+            x = xp.broadcast_to(x, y.shape)
+            d = x[tuple(slice1)] - x[tuple(slice2)]
+    try:
+        ret = xp.sum(
+            d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
+            axis=axis, dtype=result_dtype
+        )
+    except ValueError:
+        # Operations didn't work, cast to ndarray
+        d = xp.asarray(d)
+        y = xp.asarray(y)
+        ret = xp.sum(
+            d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
+            axis=axis, dtype=result_dtype
+        )
+    return ret
+
+
+def _cached_roots_legendre(n):
+    """
+    Cache roots_legendre results to speed up calls of the fixed_quad
+    function.
+    """
+    if n in _cached_roots_legendre.cache:
+        return _cached_roots_legendre.cache[n]
+
+    _cached_roots_legendre.cache[n] = roots_legendre(n)
+    return _cached_roots_legendre.cache[n]
+
+
+_cached_roots_legendre.cache = dict()
+
+
+def fixed_quad(func, a, b, args=(), n=5):
+    """
+    Compute a definite integral using fixed-order Gaussian quadrature.
+
+    Integrate `func` from `a` to `b` using Gaussian quadrature of
+    order `n`.
+
+    Parameters
+    ----------
+    func : callable
+        A Python function or method to integrate (must accept vector inputs).
+        If integrating a vector-valued function, the returned array must have
+        shape ``(..., len(x))``.
+    a : float
+        Lower limit of integration.
+    b : float
+        Upper limit of integration.
+    args : tuple, optional
+        Extra arguments to pass to function, if any.
+    n : int, optional
+        Order of quadrature integration. Default is 5.
+
+    Returns
+    -------
+    val : float
+        Gaussian quadrature approximation to the integral
+    none : None
+        Statically returned value of None
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+    simpson : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> f = lambda x: x**8
+    >>> integrate.fixed_quad(f, 0.0, 1.0, n=4)
+    (0.1110884353741496, None)
+    >>> integrate.fixed_quad(f, 0.0, 1.0, n=5)
+    (0.11111111111111102, None)
+    >>> print(1/9.0)  # analytical result
+    0.1111111111111111
+
+    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=4)
+    (0.9999999771971152, None)
+    >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=5)
+    (1.000000000039565, None)
+    >>> np.sin(np.pi/2)-np.sin(0)  # analytical result
+    1.0
+
+    """
+    x, w = _cached_roots_legendre(n)
+    x = np.real(x)
+    if np.isinf(a) or np.isinf(b):
+        raise ValueError("Gaussian quadrature is only available for "
+                         "finite limits.")
+    y = (b-a)*(x+1)/2.0 + a
+    return (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1), None
+
+
+def tupleset(t, i, value):
+    l = list(t)
+    l[i] = value
+    return tuple(l)
+
+
+def cumulative_trapezoid(y, x=None, dx=1.0, axis=-1, initial=None):
+    """
+    Cumulatively integrate y(x) using the composite trapezoidal rule.
+
+    Parameters
+    ----------
+    y : array_like
+        Values to integrate.
+    x : array_like, optional
+        The coordinate to integrate along. If None (default), use spacing `dx`
+        between consecutive elements in `y`.
+    dx : float, optional
+        Spacing between elements of `y`. Only used if `x` is None.
+    axis : int, optional
+        Specifies the axis to cumulate. Default is -1 (last axis).
+    initial : scalar, optional
+        If given, insert this value at the beginning of the returned result.
+        0 or None are the only values accepted. Default is None, which means
+        `res` has one element less than `y` along the axis of integration.
+
+    Returns
+    -------
+    res : ndarray
+        The result of cumulative integration of `y` along `axis`.
+        If `initial` is None, the shape is such that the axis of integration
+        has one less value than `y`. If `initial` is given, the shape is equal
+        to that of `y`.
+
+    See Also
+    --------
+    numpy.cumsum, numpy.cumprod
+    cumulative_simpson : cumulative integration using Simpson's 1/3 rule
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-2, 2, num=20)
+    >>> y = x
+    >>> y_int = integrate.cumulative_trapezoid(y, x, initial=0)
+    >>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-')
+    >>> plt.show()
+
+    """
+    y = np.asarray(y)
+    if y.shape[axis] == 0:
+        raise ValueError("At least one point is required along `axis`.")
+    if x is None:
+        d = dx
+    else:
+        x = np.asarray(x)
+        if x.ndim == 1:
+            d = np.diff(x)
+            # reshape to correct shape
+            shape = [1] * y.ndim
+            shape[axis] = -1
+            d = d.reshape(shape)
+        elif len(x.shape) != len(y.shape):
+            raise ValueError("If given, shape of x must be 1-D or the "
+                             "same as y.")
+        else:
+            d = np.diff(x, axis=axis)
+
+        if d.shape[axis] != y.shape[axis] - 1:
+            raise ValueError("If given, length of x along axis must be the "
+                             "same as y.")
+
+    nd = len(y.shape)
+    slice1 = tupleset((slice(None),)*nd, axis, slice(1, None))
+    slice2 = tupleset((slice(None),)*nd, axis, slice(None, -1))
+    res = np.cumsum(d * (y[slice1] + y[slice2]) / 2.0, axis=axis)
+
+    if initial is not None:
+        if initial != 0:
+            raise ValueError("`initial` must be `None` or `0`.")
+        if not np.isscalar(initial):
+            raise ValueError("`initial` parameter should be a scalar.")
+
+        shape = list(res.shape)
+        shape[axis] = 1
+        res = np.concatenate([np.full(shape, initial, dtype=res.dtype), res],
+                             axis=axis)
+
+    return res
+
+
+def _basic_simpson(y, start, stop, x, dx, axis):
+    nd = len(y.shape)
+    if start is None:
+        start = 0
+    step = 2
+    slice_all = (slice(None),)*nd
+    slice0 = tupleset(slice_all, axis, slice(start, stop, step))
+    slice1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
+    slice2 = tupleset(slice_all, axis, slice(start+2, stop+2, step))
+
+    if x is None:  # Even-spaced Simpson's rule.
+        result = np.sum(y[slice0] + 4.0*y[slice1] + y[slice2], axis=axis)
+        result *= dx / 3.0
+    else:
+        # Account for possibly different spacings.
+        #    Simpson's rule changes a bit.
+        h = np.diff(x, axis=axis)
+        sl0 = tupleset(slice_all, axis, slice(start, stop, step))
+        sl1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
+        h0 = h[sl0].astype(float, copy=False)
+        h1 = h[sl1].astype(float, copy=False)
+        hsum = h0 + h1
+        hprod = h0 * h1
+        h0divh1 = np.true_divide(h0, h1, out=np.zeros_like(h0), where=h1 != 0)
+        tmp = hsum/6.0 * (y[slice0] *
+                          (2.0 - np.true_divide(1.0, h0divh1,
+                                                out=np.zeros_like(h0divh1),
+                                                where=h0divh1 != 0)) +
+                          y[slice1] * (hsum *
+                                       np.true_divide(hsum, hprod,
+                                                      out=np.zeros_like(hsum),
+                                                      where=hprod != 0)) +
+                          y[slice2] * (2.0 - h0divh1))
+        result = np.sum(tmp, axis=axis)
+    return result
+
+
+def simpson(y, x=None, *, dx=1.0, axis=-1):
+    """
+    Integrate y(x) using samples along the given axis and the composite
+    Simpson's rule. If x is None, spacing of dx is assumed.
+
+    Parameters
+    ----------
+    y : array_like
+        Array to be integrated.
+    x : array_like, optional
+        If given, the points at which `y` is sampled.
+    dx : float, optional
+        Spacing of integration points along axis of `x`. Only used when
+        `x` is None. Default is 1.
+    axis : int, optional
+        Axis along which to integrate. Default is the last axis.
+
+    Returns
+    -------
+    float
+        The estimated integral computed with the composite Simpson's rule.
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    romb : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+    cumulative_simpson : cumulative integration using Simpson's 1/3 rule
+
+    Notes
+    -----
+    For an odd number of samples that are equally spaced the result is
+    exact if the function is a polynomial of order 3 or less. If
+    the samples are not equally spaced, then the result is exact only
+    if the function is a polynomial of order 2 or less.
+
+    References
+    ----------
+    .. [1] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
+           MS Excel and Irregularly-spaced Data. Journal of Mathematical
+           Sciences and Mathematics Education. 12 (2): 1-9
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x = np.arange(0, 10)
+    >>> y = np.arange(0, 10)
+
+    >>> integrate.simpson(y, x=x)
+    40.5
+
+    >>> y = np.power(x, 3)
+    >>> integrate.simpson(y, x=x)
+    1640.5
+    >>> integrate.quad(lambda x: x**3, 0, 9)[0]
+    1640.25
+
+    """
+    y = np.asarray(y)
+    nd = len(y.shape)
+    N = y.shape[axis]
+    last_dx = dx
+    returnshape = 0
+    if x is not None:
+        x = np.asarray(x)
+        if len(x.shape) == 1:
+            shapex = [1] * nd
+            shapex[axis] = x.shape[0]
+            saveshape = x.shape
+            returnshape = 1
+            x = x.reshape(tuple(shapex))
+        elif len(x.shape) != len(y.shape):
+            raise ValueError("If given, shape of x must be 1-D or the "
+                             "same as y.")
+        if x.shape[axis] != N:
+            raise ValueError("If given, length of x along axis must be the "
+                             "same as y.")
+
+    if N % 2 == 0:
+        val = 0.0
+        result = 0.0
+        slice_all = (slice(None),) * nd
+
+        if N == 2:
+            # need at least 3 points in integration axis to form parabolic
+            # segment. If there are two points then any of 'avg', 'first',
+            # 'last' should give the same result.
+            slice1 = tupleset(slice_all, axis, -1)
+            slice2 = tupleset(slice_all, axis, -2)
+            if x is not None:
+                last_dx = x[slice1] - x[slice2]
+            val += 0.5 * last_dx * (y[slice1] + y[slice2])
+        else:
+            # use Simpson's rule on first intervals
+            result = _basic_simpson(y, 0, N-3, x, dx, axis)
+
+            slice1 = tupleset(slice_all, axis, -1)
+            slice2 = tupleset(slice_all, axis, -2)
+            slice3 = tupleset(slice_all, axis, -3)
+
+            h = np.asarray([dx, dx], dtype=np.float64)
+            if x is not None:
+                # grab the last two spacings from the appropriate axis
+                hm2 = tupleset(slice_all, axis, slice(-2, -1, 1))
+                hm1 = tupleset(slice_all, axis, slice(-1, None, 1))
+
+                diffs = np.float64(np.diff(x, axis=axis))
+                h = [np.squeeze(diffs[hm2], axis=axis),
+                     np.squeeze(diffs[hm1], axis=axis)]
+
+            # This is the correction for the last interval according to
+            # Cartwright.
+            # However, I used the equations given at
+            # https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule_for_irregularly_spaced_data
+            # A footnote on Wikipedia says:
+            # Cartwright 2017, Equation 8. The equation in Cartwright is
+            # calculating the first interval whereas the equations in the
+            # Wikipedia article are adjusting for the last integral. If the
+            # proper algebraic substitutions are made, the equation results in
+            # the values shown.
+            num = 2 * h[1] ** 2 + 3 * h[0] * h[1]
+            den = 6 * (h[1] + h[0])
+            alpha = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            num = h[1] ** 2 + 3.0 * h[0] * h[1]
+            den = 6 * h[0]
+            beta = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            num = 1 * h[1] ** 3
+            den = 6 * h[0] * (h[0] + h[1])
+            eta = np.true_divide(
+                num,
+                den,
+                out=np.zeros_like(den),
+                where=den != 0
+            )
+
+            result += alpha*y[slice1] + beta*y[slice2] - eta*y[slice3]
+
+        result += val
+    else:
+        result = _basic_simpson(y, 0, N-2, x, dx, axis)
+    if returnshape:
+        x = x.reshape(saveshape)
+    return result
+
+
+def _cumulatively_sum_simpson_integrals(
+    y: np.ndarray, 
+    dx: np.ndarray, 
+    integration_func: Callable[[np.ndarray, np.ndarray], np.ndarray],
+) -> np.ndarray:
+    """Calculate cumulative sum of Simpson integrals.
+    Takes as input the integration function to be used. 
+    The integration_func is assumed to return the cumulative sum using
+    composite Simpson's rule. Assumes the axis of summation is -1.
+    """
+    sub_integrals_h1 = integration_func(y, dx)
+    sub_integrals_h2 = integration_func(y[..., ::-1], dx[..., ::-1])[..., ::-1]
+    
+    shape = list(sub_integrals_h1.shape)
+    shape[-1] += 1
+    sub_integrals = np.empty(shape)
+    sub_integrals[..., :-1:2] = sub_integrals_h1[..., ::2]
+    sub_integrals[..., 1::2] = sub_integrals_h2[..., ::2]
+    # Integral over last subinterval can only be calculated from 
+    # formula for h2
+    sub_integrals[..., -1] = sub_integrals_h2[..., -1]
+    res = np.cumsum(sub_integrals, axis=-1)
+    return res
+
+
+def _cumulative_simpson_equal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
+    """Calculate the Simpson integrals for all h1 intervals assuming equal interval
+    widths. The function can also be used to calculate the integral for all
+    h2 intervals by reversing the inputs, `y` and `dx`.
+    """
+    d = dx[..., :-1]
+    f1 = y[..., :-2]
+    f2 = y[..., 1:-1]
+    f3 = y[..., 2:]
+
+    # Calculate integral over the subintervals (eqn (10) of Reference [2])
+    return d / 3 * (5 * f1 / 4 + 2 * f2 - f3 / 4)
+
+
+def _cumulative_simpson_unequal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
+    """Calculate the Simpson integrals for all h1 intervals assuming unequal interval
+    widths. The function can also be used to calculate the integral for all
+    h2 intervals by reversing the inputs, `y` and `dx`.
+    """
+    x21 = dx[..., :-1]
+    x32 = dx[..., 1:]
+    f1 = y[..., :-2]
+    f2 = y[..., 1:-1]
+    f3 = y[..., 2:]
+
+    x31 = x21 + x32
+    x21_x31 = x21/x31
+    x21_x32 = x21/x32
+    x21x21_x31x32 = x21_x31 * x21_x32
+
+    # Calculate integral over the subintervals (eqn (8) of Reference [2])
+    coeff1 = 3 - x21_x31
+    coeff2 = 3 + x21x21_x31x32 + x21_x31
+    coeff3 = -x21x21_x31x32
+
+    return x21/6 * (coeff1*f1 + coeff2*f2 + coeff3*f3)
+
+
+def _ensure_float_array(arr: npt.ArrayLike) -> np.ndarray:
+    arr = np.asarray(arr)
+    if np.issubdtype(arr.dtype, np.integer):
+        arr = arr.astype(float, copy=False)
+    return arr
+
+
+def cumulative_simpson(y, *, x=None, dx=1.0, axis=-1, initial=None):
+    r"""
+    Cumulatively integrate y(x) using the composite Simpson's 1/3 rule.
+    The integral of the samples at every point is calculated by assuming a 
+    quadratic relationship between each point and the two adjacent points.
+
+    Parameters
+    ----------
+    y : array_like
+        Values to integrate. Requires at least one point along `axis`. If two or fewer
+        points are provided along `axis`, Simpson's integration is not possible and the
+        result is calculated with `cumulative_trapezoid`.
+    x : array_like, optional
+        The coordinate to integrate along. Must have the same shape as `y` or
+        must be 1D with the same length as `y` along `axis`. `x` must also be
+        strictly increasing along `axis`.
+        If `x` is None (default), integration is performed using spacing `dx`
+        between consecutive elements in `y`.
+    dx : scalar or array_like, optional
+        Spacing between elements of `y`. Only used if `x` is None. Can either 
+        be a float, or an array with the same shape as `y`, but of length one along
+        `axis`. Default is 1.0.
+    axis : int, optional
+        Specifies the axis to integrate along. Default is -1 (last axis).
+    initial : scalar or array_like, optional
+        If given, insert this value at the beginning of the returned result,
+        and add it to the rest of the result. Default is None, which means no
+        value at ``x[0]`` is returned and `res` has one element less than `y`
+        along the axis of integration. Can either be a float, or an array with
+        the same shape as `y`, but of length one along `axis`.
+
+    Returns
+    -------
+    res : ndarray
+        The result of cumulative integration of `y` along `axis`.
+        If `initial` is None, the shape is such that the axis of integration
+        has one less value than `y`. If `initial` is given, the shape is equal
+        to that of `y`.
+
+    See Also
+    --------
+    numpy.cumsum
+    cumulative_trapezoid : cumulative integration using the composite 
+        trapezoidal rule
+    simpson : integrator for sampled data using the Composite Simpson's Rule
+
+    Notes
+    -----
+
+    .. versionadded:: 1.12.0
+
+    The composite Simpson's 1/3 method can be used to approximate the definite 
+    integral of a sampled input function :math:`y(x)` [1]_. The method assumes 
+    a quadratic relationship over the interval containing any three consecutive
+    sampled points.
+
+    Consider three consecutive points: 
+    :math:`(x_1, y_1), (x_2, y_2), (x_3, y_3)`.
+
+    Assuming a quadratic relationship over the three points, the integral over
+    the subinterval between :math:`x_1` and :math:`x_2` is given by formula
+    (8) of [2]_:
+    
+    .. math::
+        \int_{x_1}^{x_2} y(x) dx\ &= \frac{x_2-x_1}{6}\left[\
+        \left\{3-\frac{x_2-x_1}{x_3-x_1}\right\} y_1 + \
+        \left\{3 + \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} + \
+        \frac{x_2-x_1}{x_3-x_1}\right\} y_2\\
+        - \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} y_3\right]
+
+    The integral between :math:`x_2` and :math:`x_3` is given by swapping
+    appearances of :math:`x_1` and :math:`x_3`. The integral is estimated
+    separately for each subinterval and then cumulatively summed to obtain
+    the final result.
+    
+    For samples that are equally spaced, the result is exact if the function
+    is a polynomial of order three or less [1]_ and the number of subintervals
+    is even. Otherwise, the integral is exact for polynomials of order two or
+    less. 
+
+    References
+    ----------
+    .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Simpson's_rule
+    .. [2] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
+            MS Excel and Irregularly-spaced Data. Journal of Mathematical
+            Sciences and Mathematics Education. 12 (2): 1-9
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-2, 2, num=20)
+    >>> y = x**2
+    >>> y_int = integrate.cumulative_simpson(y, x=x, initial=0)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y_int, 'ro', x, x**3/3 - (x[0])**3/3, 'b-')
+    >>> ax.grid()
+    >>> plt.show()
+
+    The output of `cumulative_simpson` is similar to that of iteratively
+    calling `simpson` with successively higher upper limits of integration, but
+    not identical.
+
+    >>> def cumulative_simpson_reference(y, x):
+    ...     return np.asarray([integrate.simpson(y[:i], x=x[:i])
+    ...                        for i in range(2, len(y) + 1)])
+    >>>
+    >>> rng = np.random.default_rng(354673834679465)
+    >>> x, y = rng.random(size=(2, 10))
+    >>> x.sort()
+    >>>
+    >>> res = integrate.cumulative_simpson(y, x=x)
+    >>> ref = cumulative_simpson_reference(y, x)
+    >>> equal = np.abs(res - ref) < 1e-15
+    >>> equal  # not equal when `simpson` has even number of subintervals
+    array([False,  True, False,  True, False,  True, False,  True,  True])
+
+    This is expected: because `cumulative_simpson` has access to more
+    information than `simpson`, it can typically produce more accurate
+    estimates of the underlying integral over subintervals.
+
+    """
+    y = _ensure_float_array(y)
+
+    # validate `axis` and standardize to work along the last axis
+    original_y = y
+    original_shape = y.shape
+    try:
+        y = np.swapaxes(y, axis, -1)
+    except IndexError as e:
+        message = f"`axis={axis}` is not valid for `y` with `y.ndim={y.ndim}`."
+        raise ValueError(message) from e
+    if y.shape[-1] < 3:
+        res = cumulative_trapezoid(original_y, x, dx=dx, axis=axis, initial=None)
+        res = np.swapaxes(res, axis, -1)
+
+    elif x is not None:
+        x = _ensure_float_array(x)
+        message = ("If given, shape of `x` must be the same as `y` or 1-D with "
+                   "the same length as `y` along `axis`.")
+        if not (x.shape == original_shape
+                or (x.ndim == 1 and len(x) == original_shape[axis])):
+            raise ValueError(message)
+
+        x = np.broadcast_to(x, y.shape) if x.ndim == 1 else np.swapaxes(x, axis, -1)
+        dx = np.diff(x, axis=-1)
+        if np.any(dx <= 0):
+            raise ValueError("Input x must be strictly increasing.")
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_unequal_intervals
+        )
+
+    else:
+        dx = _ensure_float_array(dx)
+        final_dx_shape = tupleset(original_shape, axis, original_shape[axis] - 1)
+        alt_input_dx_shape = tupleset(original_shape, axis, 1)
+        message = ("If provided, `dx` must either be a scalar or have the same "
+                   "shape as `y` but with only 1 point along `axis`.")
+        if not (dx.ndim == 0 or dx.shape == alt_input_dx_shape):
+            raise ValueError(message)
+        dx = np.broadcast_to(dx, final_dx_shape)
+        dx = np.swapaxes(dx, axis, -1)
+        res = _cumulatively_sum_simpson_integrals(
+            y, dx, _cumulative_simpson_equal_intervals
+        )
+
+    if initial is not None:
+        initial = _ensure_float_array(initial)
+        alt_initial_input_shape = tupleset(original_shape, axis, 1)
+        message = ("If provided, `initial` must either be a scalar or have the "
+                   "same shape as `y` but with only 1 point along `axis`.")
+        if not (initial.ndim == 0 or initial.shape == alt_initial_input_shape):
+            raise ValueError(message)
+        initial = np.broadcast_to(initial, alt_initial_input_shape)
+        initial = np.swapaxes(initial, axis, -1)
+
+        res += initial
+        res = np.concatenate((initial, res), axis=-1)
+
+    res = np.swapaxes(res, -1, axis)
+    return res
+
+
+def romb(y, dx=1.0, axis=-1, show=False):
+    """
+    Romberg integration using samples of a function.
+
+    Parameters
+    ----------
+    y : array_like
+        A vector of ``2**k + 1`` equally-spaced samples of a function.
+    dx : float, optional
+        The sample spacing. Default is 1.
+    axis : int, optional
+        The axis along which to integrate. Default is -1 (last axis).
+    show : bool, optional
+        When `y` is a single 1-D array, then if this argument is True
+        print the table showing Richardson extrapolation from the
+        samples. Default is False.
+
+    Returns
+    -------
+    romb : ndarray
+        The integrated result for `axis`.
+
+    See Also
+    --------
+    quad : adaptive quadrature using QUADPACK
+    fixed_quad : fixed-order Gaussian quadrature
+    dblquad : double integrals
+    tplquad : triple integrals
+    simpson : integrators for sampled data
+    cumulative_trapezoid : cumulative integration for sampled data
+
+    Examples
+    --------
+    >>> from scipy import integrate
+    >>> import numpy as np
+    >>> x = np.arange(10, 14.25, 0.25)
+    >>> y = np.arange(3, 12)
+
+    >>> integrate.romb(y)
+    56.0
+
+    >>> y = np.sin(np.power(x, 2.5))
+    >>> integrate.romb(y)
+    -0.742561336672229
+
+    >>> integrate.romb(y, show=True)
+    Richardson Extrapolation Table for Romberg Integration
+    ======================================================
+    -0.81576
+     4.63862  6.45674
+    -1.10581 -3.02062 -3.65245
+    -2.57379 -3.06311 -3.06595 -3.05664
+    -1.34093 -0.92997 -0.78776 -0.75160 -0.74256
+    ======================================================
+    -0.742561336672229  # may vary
+
+    """
+    y = np.asarray(y)
+    nd = len(y.shape)
+    Nsamps = y.shape[axis]
+    Ninterv = Nsamps-1
+    n = 1
+    k = 0
+    while n < Ninterv:
+        n <<= 1
+        k += 1
+    if n != Ninterv:
+        raise ValueError("Number of samples must be one plus a "
+                         "non-negative power of 2.")
+
+    R = {}
+    slice_all = (slice(None),) * nd
+    slice0 = tupleset(slice_all, axis, 0)
+    slicem1 = tupleset(slice_all, axis, -1)
+    h = Ninterv * np.asarray(dx, dtype=float)
+    R[(0, 0)] = (y[slice0] + y[slicem1])/2.0*h
+    slice_R = slice_all
+    start = stop = step = Ninterv
+    for i in range(1, k+1):
+        start >>= 1
+        slice_R = tupleset(slice_R, axis, slice(start, stop, step))
+        step >>= 1
+        R[(i, 0)] = 0.5*(R[(i-1, 0)] + h*y[slice_R].sum(axis=axis))
+        for j in range(1, i+1):
+            prev = R[(i, j-1)]
+            R[(i, j)] = prev + (prev-R[(i-1, j-1)]) / ((1 << (2*j))-1)
+        h /= 2.0
+
+    if show:
+        if not np.isscalar(R[(0, 0)]):
+            print("*** Printing table only supported for integrals" +
+                  " of a single data set.")
+        else:
+            try:
+                precis = show[0]
+            except (TypeError, IndexError):
+                precis = 5
+            try:
+                width = show[1]
+            except (TypeError, IndexError):
+                width = 8
+            formstr = "%%%d.%df" % (width, precis)
+
+            title = "Richardson Extrapolation Table for Romberg Integration"
+            print(title, "=" * len(title), sep="\n", end="\n")
+            for i in range(k+1):
+                for j in range(i+1):
+                    print(formstr % R[(i, j)], end=" ")
+                print()
+            print("=" * len(title))
+
+    return R[(k, k)]
+
+
+# Coefficients for Newton-Cotes quadrature
+#
+# These are the points being used
+#  to construct the local interpolating polynomial
+#  a are the weights for Newton-Cotes integration
+#  B is the error coefficient.
+#  error in these coefficients grows as N gets larger.
+#  or as samples are closer and closer together
+
+# You can use maxima to find these rational coefficients
+#  for equally spaced data using the commands
+#  a(i,N) := (integrate(product(r-j,j,0,i-1) * product(r-j,j,i+1,N),r,0,N)
+#             / ((N-i)! * i!) * (-1)^(N-i));
+#  Be(N) := N^(N+2)/(N+2)! * (N/(N+3) - sum((i/N)^(N+2)*a(i,N),i,0,N));
+#  Bo(N) := N^(N+1)/(N+1)! * (N/(N+2) - sum((i/N)^(N+1)*a(i,N),i,0,N));
+#  B(N) := (if (mod(N,2)=0) then Be(N) else Bo(N));
+#
+# pre-computed for equally-spaced weights
+#
+# num_a, den_a, int_a, num_B, den_B = _builtincoeffs[N]
+#
+#  a = num_a*array(int_a)/den_a
+#  B = num_B*1.0 / den_B
+#
+#  integrate(f(x),x,x_0,x_N) = dx*sum(a*f(x_i)) + B*(dx)^(2k+3) f^(2k+2)(x*)
+#    where k = N // 2
+#
+_builtincoeffs = {
+    1: (1,2,[1,1],-1,12),
+    2: (1,3,[1,4,1],-1,90),
+    3: (3,8,[1,3,3,1],-3,80),
+    4: (2,45,[7,32,12,32,7],-8,945),
+    5: (5,288,[19,75,50,50,75,19],-275,12096),
+    6: (1,140,[41,216,27,272,27,216,41],-9,1400),
+    7: (7,17280,[751,3577,1323,2989,2989,1323,3577,751],-8183,518400),
+    8: (4,14175,[989,5888,-928,10496,-4540,10496,-928,5888,989],
+        -2368,467775),
+    9: (9,89600,[2857,15741,1080,19344,5778,5778,19344,1080,
+                 15741,2857], -4671, 394240),
+    10: (5,299376,[16067,106300,-48525,272400,-260550,427368,
+                   -260550,272400,-48525,106300,16067],
+         -673175, 163459296),
+    11: (11,87091200,[2171465,13486539,-3237113, 25226685,-9595542,
+                      15493566,15493566,-9595542,25226685,-3237113,
+                      13486539,2171465], -2224234463, 237758976000),
+    12: (1, 5255250, [1364651,9903168,-7587864,35725120,-51491295,
+                      87516288,-87797136,87516288,-51491295,35725120,
+                      -7587864,9903168,1364651], -3012, 875875),
+    13: (13, 402361344000,[8181904909, 56280729661, -31268252574,
+                           156074417954,-151659573325,206683437987,
+                           -43111992612,-43111992612,206683437987,
+                           -151659573325,156074417954,-31268252574,
+                           56280729661,8181904909], -2639651053,
+         344881152000),
+    14: (7, 2501928000, [90241897,710986864,-770720657,3501442784,
+                         -6625093363,12630121616,-16802270373,19534438464,
+                         -16802270373,12630121616,-6625093363,3501442784,
+                         -770720657,710986864,90241897], -3740727473,
+         1275983280000)
+    }
+
+
+def newton_cotes(rn, equal=0):
+    r"""
+    Return weights and error coefficient for Newton-Cotes integration.
+
+    Suppose we have (N+1) samples of f at the positions
+    x_0, x_1, ..., x_N. Then an N-point Newton-Cotes formula for the
+    integral between x_0 and x_N is:
+
+    :math:`\int_{x_0}^{x_N} f(x)dx = \Delta x \sum_{i=0}^{N} a_i f(x_i)
+    + B_N (\Delta x)^{N+2} f^{N+1} (\xi)`
+
+    where :math:`\xi \in [x_0,x_N]`
+    and :math:`\Delta x = \frac{x_N-x_0}{N}` is the average samples spacing.
+
+    If the samples are equally-spaced and N is even, then the error
+    term is :math:`B_N (\Delta x)^{N+3} f^{N+2}(\xi)`.
+
+    Parameters
+    ----------
+    rn : int
+        The integer order for equally-spaced data or the relative positions of
+        the samples with the first sample at 0 and the last at N, where N+1 is
+        the length of `rn`. N is the order of the Newton-Cotes integration.
+    equal : int, optional
+        Set to 1 to enforce equally spaced data.
+
+    Returns
+    -------
+    an : ndarray
+        1-D array of weights to apply to the function at the provided sample
+        positions.
+    B : float
+        Error coefficient.
+
+    Notes
+    -----
+    Normally, the Newton-Cotes rules are used on smaller integration
+    regions and a composite rule is used to return the total integral.
+
+    Examples
+    --------
+    Compute the integral of sin(x) in [0, :math:`\pi`]:
+
+    >>> from scipy.integrate import newton_cotes
+    >>> import numpy as np
+    >>> def f(x):
+    ...     return np.sin(x)
+    >>> a = 0
+    >>> b = np.pi
+    >>> exact = 2
+    >>> for N in [2, 4, 6, 8, 10]:
+    ...     x = np.linspace(a, b, N + 1)
+    ...     an, B = newton_cotes(N, 1)
+    ...     dx = (b - a) / N
+    ...     quad = dx * np.sum(an * f(x))
+    ...     error = abs(quad - exact)
+    ...     print('{:2d}  {:10.9f}  {:.5e}'.format(N, quad, error))
+    ...
+     2   2.094395102   9.43951e-02
+     4   1.998570732   1.42927e-03
+     6   2.000017814   1.78136e-05
+     8   1.999999835   1.64725e-07
+    10   2.000000001   1.14677e-09
+
+    """
+    try:
+        N = len(rn)-1
+        if equal:
+            rn = np.arange(N+1)
+        elif np.all(np.diff(rn) == 1):
+            equal = 1
+    except Exception:
+        N = rn
+        rn = np.arange(N+1)
+        equal = 1
+
+    if equal and N in _builtincoeffs:
+        na, da, vi, nb, db = _builtincoeffs[N]
+        an = na * np.array(vi, dtype=float) / da
+        return an, float(nb)/db
+
+    if (rn[0] != 0) or (rn[-1] != N):
+        raise ValueError("The sample positions must start at 0"
+                         " and end at N")
+    yi = rn / float(N)
+    ti = 2 * yi - 1
+    nvec = np.arange(N+1)
+    C = ti ** nvec[:, np.newaxis]
+    Cinv = np.linalg.inv(C)
+    # improve precision of result
+    for i in range(2):
+        Cinv = 2*Cinv - Cinv.dot(C).dot(Cinv)
+    vec = 2.0 / (nvec[::2]+1)
+    ai = Cinv[:, ::2].dot(vec) * (N / 2.)
+
+    if (N % 2 == 0) and equal:
+        BN = N/(N+3.)
+        power = N+2
+    else:
+        BN = N/(N+2.)
+        power = N+1
+
+    BN = BN - np.dot(yi**power, ai)
+    p1 = power+1
+    fac = power*math.log(N) - gammaln(p1)
+    fac = math.exp(fac)
+    return ai, BN*fac
+
+
+def _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log):
+
+    # lazy import to avoid issues with partially-initialized submodule
+    if not hasattr(qmc_quad, 'qmc'):
+        from scipy import stats
+        qmc_quad.stats = stats
+    else:
+        stats = qmc_quad.stats
+
+    if not callable(func):
+        message = "`func` must be callable."
+        raise TypeError(message)
+
+    # a, b will be modified, so copy. Oh well if it's copied twice.
+    a = np.atleast_1d(a).copy()
+    b = np.atleast_1d(b).copy()
+    a, b = np.broadcast_arrays(a, b)
+    dim = a.shape[0]
+
+    try:
+        func((a + b) / 2)
+    except Exception as e:
+        message = ("`func` must evaluate the integrand at points within "
+                   "the integration range; e.g. `func( (a + b) / 2)` "
+                   "must return the integrand at the centroid of the "
+                   "integration volume.")
+        raise ValueError(message) from e
+
+    try:
+        func(np.array([a, b]).T)
+        vfunc = func
+    except Exception as e:
+        message = ("Exception encountered when attempting vectorized call to "
+                   f"`func`: {e}. For better performance, `func` should "
+                   "accept two-dimensional array `x` with shape `(len(a), "
+                   "n_points)` and return an array of the integrand value at "
+                   "each of the `n_points.")
+        warnings.warn(message, stacklevel=3)
+
+        def vfunc(x):
+            return np.apply_along_axis(func, axis=-1, arr=x)
+
+    n_points_int = np.int64(n_points)
+    if n_points != n_points_int:
+        message = "`n_points` must be an integer."
+        raise TypeError(message)
+
+    n_estimates_int = np.int64(n_estimates)
+    if n_estimates != n_estimates_int:
+        message = "`n_estimates` must be an integer."
+        raise TypeError(message)
+
+    if qrng is None:
+        qrng = stats.qmc.Halton(dim)
+    elif not isinstance(qrng, stats.qmc.QMCEngine):
+        message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine."
+        raise TypeError(message)
+
+    if qrng.d != a.shape[0]:
+        message = ("`qrng` must be initialized with dimensionality equal to "
+                   "the number of variables in `a`, i.e., "
+                   "`qrng.random().shape[-1]` must equal `a.shape[0]`.")
+        raise ValueError(message)
+
+    rng_seed = getattr(qrng, 'rng_seed', None)
+    rng = stats._qmc.check_random_state(rng_seed)
+
+    if log not in {True, False}:
+        message = "`log` must be boolean (`True` or `False`)."
+        raise TypeError(message)
+
+    return (vfunc, a, b, n_points_int, n_estimates_int, qrng, rng, log, stats)
+
+
+QMCQuadResult = namedtuple('QMCQuadResult', ['integral', 'standard_error'])
+
+
+def qmc_quad(func, a, b, *, n_estimates=8, n_points=1024, qrng=None,
+             log=False):
+    """
+    Compute an integral in N-dimensions using Quasi-Monte Carlo quadrature.
+
+    Parameters
+    ----------
+    func : callable
+        The integrand. Must accept a single argument ``x``, an array which
+        specifies the point(s) at which to evaluate the scalar-valued
+        integrand, and return the value(s) of the integrand.
+        For efficiency, the function should be vectorized to accept an array of
+        shape ``(d, n_points)``, where ``d`` is the number of variables (i.e.
+        the dimensionality of the function domain) and `n_points` is the number
+        of quadrature points, and return an array of shape ``(n_points,)``,
+        the integrand at each quadrature point.
+    a, b : array-like
+        One-dimensional arrays specifying the lower and upper integration
+        limits, respectively, of each of the ``d`` variables.
+    n_estimates, n_points : int, optional
+        `n_estimates` (default: 8) statistically independent QMC samples, each
+        of `n_points` (default: 1024) points, will be generated by `qrng`.
+        The total number of points at which the integrand `func` will be
+        evaluated is ``n_points * n_estimates``. See Notes for details.
+    qrng : `~scipy.stats.qmc.QMCEngine`, optional
+        An instance of the QMCEngine from which to sample QMC points.
+        The QMCEngine must be initialized to a number of dimensions ``d``
+        corresponding with the number of variables ``x1, ..., xd`` passed to
+        `func`.
+        The provided QMCEngine is used to produce the first integral estimate.
+        If `n_estimates` is greater than one, additional QMCEngines are
+        spawned from the first (with scrambling enabled, if it is an option.)
+        If a QMCEngine is not provided, the default `scipy.stats.qmc.Halton`
+        will be initialized with the number of dimensions determine from
+        the length of `a`.
+    log : boolean, default: False
+        When set to True, `func` returns the log of the integrand, and
+        the result object contains the log of the integral.
+
+    Returns
+    -------
+    result : object
+        A result object with attributes:
+
+        integral : float
+            The estimate of the integral.
+        standard_error :
+            The error estimate. See Notes for interpretation.
+
+    Notes
+    -----
+    Values of the integrand at each of the `n_points` points of a QMC sample
+    are used to produce an estimate of the integral. This estimate is drawn
+    from a population of possible estimates of the integral, the value of
+    which we obtain depends on the particular points at which the integral
+    was evaluated. We perform this process `n_estimates` times, each time
+    evaluating the integrand at different scrambled QMC points, effectively
+    drawing i.i.d. random samples from the population of integral estimates.
+    The sample mean :math:`m` of these integral estimates is an
+    unbiased estimator of the true value of the integral, and the standard
+    error of the mean :math:`s` of these estimates may be used to generate
+    confidence intervals using the t distribution with ``n_estimates - 1``
+    degrees of freedom. Perhaps counter-intuitively, increasing `n_points`
+    while keeping the total number of function evaluation points
+    ``n_points * n_estimates`` fixed tends to reduce the actual error, whereas
+    increasing `n_estimates` tends to decrease the error estimate.
+
+    Examples
+    --------
+    QMC quadrature is particularly useful for computing integrals in higher
+    dimensions. An example integrand is the probability density function
+    of a multivariate normal distribution.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> dim = 8
+    >>> mean = np.zeros(dim)
+    >>> cov = np.eye(dim)
+    >>> def func(x):
+    ...     # `multivariate_normal` expects the _last_ axis to correspond with
+    ...     # the dimensionality of the space, so `x` must be transposed
+    ...     return stats.multivariate_normal.pdf(x.T, mean, cov)
+
+    To compute the integral over the unit hypercube:
+
+    >>> from scipy.integrate import qmc_quad
+    >>> a = np.zeros(dim)
+    >>> b = np.ones(dim)
+    >>> rng = np.random.default_rng()
+    >>> qrng = stats.qmc.Halton(d=dim, seed=rng)
+    >>> n_estimates = 8
+    >>> res = qmc_quad(func, a, b, n_estimates=n_estimates, qrng=qrng)
+    >>> res.integral, res.standard_error
+    (0.00018429555666024108, 1.0389431116001344e-07)
+
+    A two-sided, 99% confidence interval for the integral may be estimated
+    as:
+
+    >>> t = stats.t(df=n_estimates-1, loc=res.integral,
+    ...             scale=res.standard_error)
+    >>> t.interval(0.99)
+    (0.0001839319802536469, 0.00018465913306683527)
+
+    Indeed, the value reported by `scipy.stats.multivariate_normal` is
+    within this range.
+
+    >>> stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a)
+    0.00018430867675187443
+
+    """
+    args = _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log)
+    func, a, b, n_points, n_estimates, qrng, rng, log, stats = args
+
+    def sum_product(integrands, dA, log=False):
+        if log:
+            return logsumexp(integrands) + np.log(dA)
+        else:
+            return np.sum(integrands * dA)
+
+    def mean(estimates, log=False):
+        if log:
+            return logsumexp(estimates) - np.log(n_estimates)
+        else:
+            return np.mean(estimates)
+
+    def std(estimates, m=None, ddof=0, log=False):
+        m = m or mean(estimates, log)
+        if log:
+            estimates, m = np.broadcast_arrays(estimates, m)
+            temp = np.vstack((estimates, m + np.pi * 1j))
+            diff = logsumexp(temp, axis=0)
+            return np.real(0.5 * (logsumexp(2 * diff)
+                                  - np.log(n_estimates - ddof)))
+        else:
+            return np.std(estimates, ddof=ddof)
+
+    def sem(estimates, m=None, s=None, log=False):
+        m = m or mean(estimates, log)
+        s = s or std(estimates, m, ddof=1, log=log)
+        if log:
+            return s - 0.5*np.log(n_estimates)
+        else:
+            return s / np.sqrt(n_estimates)
+
+    # The sign of the integral depends on the order of the limits. Fix this by
+    # ensuring that lower bounds are indeed lower and setting sign of resulting
+    # integral manually
+    if np.any(a == b):
+        message = ("A lower limit was equal to an upper limit, so the value "
+                   "of the integral is zero by definition.")
+        warnings.warn(message, stacklevel=2)
+        return QMCQuadResult(-np.inf if log else 0, 0)
+
+    i_swap = b < a
+    sign = (-1)**(i_swap.sum(axis=-1))  # odd # of swaps -> negative
+    a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
+
+    A = np.prod(b - a)
+    dA = A / n_points
+
+    estimates = np.zeros(n_estimates)
+    rngs = _rng_spawn(qrng.rng, n_estimates)
+    for i in range(n_estimates):
+        # Generate integral estimate
+        sample = qrng.random(n_points)
+        # The rationale for transposing is that this allows users to easily
+        # unpack `x` into separate variables, if desired. This is consistent
+        # with the `xx` array passed into the `scipy.integrate.nquad` `func`.
+        x = stats.qmc.scale(sample, a, b).T  # (n_dim, n_points)
+        integrands = func(x)
+        estimates[i] = sum_product(integrands, dA, log)
+
+        # Get a new, independently-scrambled QRNG for next time
+        qrng = type(qrng)(seed=rngs[i], **qrng._init_quad)
+
+    integral = mean(estimates, log)
+    standard_error = sem(estimates, m=integral, log=log)
+    integral = integral + np.pi*1j if (log and sign < 0) else integral*sign
+    return QMCQuadResult(integral, standard_error)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c91aa324478d49a8723f05618801f9b256d07af
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__init__.py
@@ -0,0 +1,12 @@
+"""Numerical cubature algorithms"""
+
+from ._base import (
+    Rule, FixedRule,
+    NestedFixedRule,
+    ProductNestedFixed,
+)
+from ._genz_malik import GenzMalikCubature
+from ._gauss_kronrod import GaussKronrodQuadrature
+from ._gauss_legendre import GaussLegendreQuadrature
+
+__all__ = [s for s in dir() if not s.startswith('_')]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b01e2df76d204ad27d7bf98bfa694672db2e788
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d56af26dca3ce776ca28feb447aefba734e3eeb
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7294f3c0fe8064cd799362de031a762e87b3c9bf
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f1657475bce1f43cc507646d68f1ae785210bc8
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c528a2e08cdc876fa8d9dd260ef96d982cc5bea
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_base.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a3ae5f506505c9c03b2ac8be33d301d60074681
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_base.py
@@ -0,0 +1,518 @@
+from scipy._lib._array_api import array_namespace, xp_size
+
+from functools import cached_property
+
+
+class Rule:
+    """
+    Base class for numerical integration algorithms (cubatures).
+
+    Finds an estimate for the integral of ``f`` over the region described by two arrays
+    ``a`` and ``b`` via `estimate`, and find an estimate for the error of this
+    approximation via `estimate_error`.
+
+    If a subclass does not implement its own `estimate_error`, then it will use a
+    default error estimate based on the difference between the estimate over the whole
+    region and the sum of estimates over that region divided into ``2^ndim`` subregions.
+
+    See Also
+    --------
+    FixedRule
+
+    Examples
+    --------
+    In the following, a custom rule is created which uses 3D Genz-Malik cubature for
+    the estimate of the integral, and the difference between this estimate and a less
+    accurate estimate using 5-node Gauss-Legendre quadrature as an estimate for the
+    error.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import (
+    ...     Rule, ProductNestedFixed, GenzMalikCubature, GaussLegendreQuadrature
+    ... )
+    >>> def f(x, r, alphas):
+    ...     # f(x) = cos(2*pi*r + alpha @ x)
+    ...     # Need to allow r and alphas to be arbitrary shape
+    ...     npoints, ndim = x.shape[0], x.shape[-1]
+    ...     alphas_reshaped = alphas[np.newaxis, :]
+    ...     x_reshaped = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
+    ...     return np.cos(2*np.pi*r + np.sum(alphas_reshaped * x_reshaped, axis=-1))
+    >>> genz = GenzMalikCubature(ndim=3)
+    >>> gauss = GaussKronrodQuadrature(npoints=21)
+    >>> # Gauss-Kronrod is 1D, so we find the 3D product rule:
+    >>> gauss_3d = ProductNestedFixed([gauss, gauss, gauss])
+    >>> class CustomRule(Rule):
+    ...     def estimate(self, f, a, b, args=()):
+    ...         return genz.estimate(f, a, b, args)
+    ...     def estimate_error(self, f, a, b, args=()):
+    ...         return np.abs(
+    ...             genz.estimate(f, a, b, args)
+    ...             - gauss_3d.estimate(f, a, b, args)
+    ...         )
+    >>> rng = np.random.default_rng()
+    >>> res = cubature(
+    ...     f=f,
+    ...     a=np.array([0, 0, 0]),
+    ...     b=np.array([1, 1, 1]),
+    ...     rule=CustomRule(),
+    ...     args=(rng.random((2,)), rng.random((3, 2, 3)))
+    ... )
+    >>> res.estimate
+     array([[-0.95179502,  0.12444608],
+            [-0.96247411,  0.60866385],
+            [-0.97360014,  0.25515587]])
+    """
+
+    def estimate(self, f, a, b, args=()):
+        r"""
+        Calculate estimate of integral of `f` in rectangular region described by
+        corners `a` and ``b``.
+
+        Parameters
+        ----------
+        f : callable
+            Function to integrate. `f` must have the signature::
+                f(x : ndarray, \*args) -> ndarray
+
+            `f` should accept arrays ``x`` of shape::
+                (npoints, ndim)
+
+            and output arrays of shape::
+                (npoints, output_dim_1, ..., output_dim_n)
+
+            In this case, `estimate` will return arrays of shape::
+                (output_dim_1, ..., output_dim_n)
+        a, b : ndarray
+            Lower and upper limits of integration as rank-1 arrays specifying the left
+            and right endpoints of the intervals being integrated over. Infinite limits
+            are currently not supported.
+        args : tuple, optional
+            Additional positional args passed to ``f``, if any.
+
+        Returns
+        -------
+        est : ndarray
+            Result of estimation. If `f` returns arrays of shape ``(npoints,
+            output_dim_1, ..., output_dim_n)``, then `est` will be of shape
+            ``(output_dim_1, ..., output_dim_n)``.
+        """
+        raise NotImplementedError
+
+    def estimate_error(self, f, a, b, args=()):
+        r"""
+        Estimate the error of the approximation for the integral of `f` in rectangular
+        region described by corners `a` and `b`.
+
+        If a subclass does not override this method, then a default error estimator is
+        used. This estimates the error as ``|est - refined_est|`` where ``est`` is
+        ``estimate(f, a, b)`` and ``refined_est`` is the sum of
+        ``estimate(f, a_k, b_k)`` where ``a_k, b_k`` are the coordinates of each
+        subregion of the region described by ``a`` and ``b``. In the 1D case, this
+        is equivalent to comparing the integral over an entire interval ``[a, b]`` to
+        the sum of the integrals over the left and right subintervals, ``[a, (a+b)/2]``
+        and ``[(a+b)/2, b]``.
+
+        Parameters
+        ----------
+        f : callable
+            Function to estimate error for. `f` must have the signature::
+                f(x : ndarray, \*args) -> ndarray
+
+            `f` should accept arrays `x` of shape::
+                (npoints, ndim)
+
+            and output arrays of shape::
+                (npoints, output_dim_1, ..., output_dim_n)
+
+            In this case, `estimate` will return arrays of shape::
+                (output_dim_1, ..., output_dim_n)
+        a, b : ndarray
+            Lower and upper limits of integration as rank-1 arrays specifying the left
+            and right endpoints of the intervals being integrated over. Infinite limits
+            are currently not supported.
+        args : tuple, optional
+            Additional positional args passed to `f`, if any.
+
+        Returns
+        -------
+        err_est : ndarray
+            Result of error estimation. If `f` returns arrays of shape
+            ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
+            of shape ``(output_dim_1, ..., output_dim_n)``.
+        """
+
+        est = self.estimate(f, a, b, args)
+        refined_est = 0
+
+        for a_k, b_k in _split_subregion(a, b):
+            refined_est += self.estimate(f, a_k, b_k, args)
+
+        return self.xp.abs(est - refined_est)
+
+
+class FixedRule(Rule):
+    """
+    A rule implemented as the weighted sum of function evaluations at fixed nodes.
+
+    Attributes
+    ----------
+    nodes_and_weights : (ndarray, ndarray)
+        A tuple ``(nodes, weights)`` of nodes at which to evaluate ``f`` and the
+        corresponding weights. ``nodes`` should be of shape ``(num_nodes,)`` for 1D
+        cubature rules (quadratures) and more generally for N-D cubature rules, it
+        should be of shape ``(num_nodes, ndim)``. ``weights`` should be of shape
+        ``(num_nodes,)``. The nodes and weights should be for integrals over
+        :math:`[-1, 1]^n`.
+
+    See Also
+    --------
+    GaussLegendreQuadrature, GaussKronrodQuadrature, GenzMalikCubature
+
+    Examples
+    --------
+
+    Implementing Simpson's 1/3 rule:
+
+    >>> import numpy as np
+    >>> from scipy.integrate._rules import FixedRule
+    >>> class SimpsonsQuad(FixedRule):
+    ...     @property
+    ...     def nodes_and_weights(self):
+    ...         nodes = np.array([-1, 0, 1])
+    ...         weights = np.array([1/3, 4/3, 1/3])
+    ...         return (nodes, weights)
+    >>> rule = SimpsonsQuad()
+    >>> rule.estimate(
+    ...     f=lambda x: x**2,
+    ...     a=np.array([0]),
+    ...     b=np.array([1]),
+    ... )
+     [0.3333333]
+    """
+
+    def __init__(self):
+        self.xp = None
+
+    @property
+    def nodes_and_weights(self):
+        raise NotImplementedError
+
+    def estimate(self, f, a, b, args=()):
+        r"""
+        Calculate estimate of integral of `f` in rectangular region described by
+        corners `a` and `b` as ``sum(weights * f(nodes))``.
+
+        Nodes and weights will automatically be adjusted from calculating integrals over
+        :math:`[-1, 1]^n` to :math:`[a, b]^n`.
+
+        Parameters
+        ----------
+        f : callable
+            Function to integrate. `f` must have the signature::
+                f(x : ndarray, \*args) -> ndarray
+
+            `f` should accept arrays `x` of shape::
+                (npoints, ndim)
+
+            and output arrays of shape::
+                (npoints, output_dim_1, ..., output_dim_n)
+
+            In this case, `estimate` will return arrays of shape::
+                (output_dim_1, ..., output_dim_n)
+        a, b : ndarray
+            Lower and upper limits of integration as rank-1 arrays specifying the left
+            and right endpoints of the intervals being integrated over. Infinite limits
+            are currently not supported.
+        args : tuple, optional
+            Additional positional args passed to `f`, if any.
+
+        Returns
+        -------
+        est : ndarray
+            Result of estimation. If `f` returns arrays of shape ``(npoints,
+            output_dim_1, ..., output_dim_n)``, then `est` will be of shape
+            ``(output_dim_1, ..., output_dim_n)``.
+        """
+        nodes, weights = self.nodes_and_weights
+
+        if self.xp is None:
+            self.xp = array_namespace(nodes)
+
+        return _apply_fixed_rule(f, a, b, nodes, weights, args, self.xp)
+
+
+class NestedFixedRule(FixedRule):
+    r"""
+    A cubature rule with error estimate given by the difference between two underlying
+    fixed rules.
+
+    If constructed as ``NestedFixedRule(higher, lower)``, this will use::
+
+        estimate(f, a, b) := higher.estimate(f, a, b)
+        estimate_error(f, a, b) := \|higher.estimate(f, a, b) - lower.estimate(f, a, b)|
+
+    (where the absolute value is taken elementwise).
+
+    Attributes
+    ----------
+    higher : Rule
+        Higher accuracy rule.
+
+    lower : Rule
+        Lower accuracy rule.
+
+    See Also
+    --------
+    GaussKronrodQuadrature
+
+    Examples
+    --------
+
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import (
+    ...     GaussLegendreQuadrature, NestedFixedRule, ProductNestedFixed
+    ... )
+    >>> higher = GaussLegendreQuadrature(10)
+    >>> lower = GaussLegendreQuadrature(5)
+    >>> rule = NestedFixedRule(
+    ...     higher,
+    ...     lower
+    ... )
+    >>> rule_2d = ProductNestedFixed([rule, rule])
+    """
+
+    def __init__(self, higher, lower):
+        self.higher = higher
+        self.lower = lower
+        self.xp = None
+
+    @property
+    def nodes_and_weights(self):
+        if self.higher is not None:
+            return self.higher.nodes_and_weights
+        else:
+            raise NotImplementedError
+
+    @property
+    def lower_nodes_and_weights(self):
+        if self.lower is not None:
+            return self.lower.nodes_and_weights
+        else:
+            raise NotImplementedError
+
+    def estimate_error(self, f, a, b, args=()):
+        r"""
+        Estimate the error of the approximation for the integral of `f` in rectangular
+        region described by corners `a` and `b`.
+
+        Parameters
+        ----------
+        f : callable
+            Function to estimate error for. `f` must have the signature::
+                f(x : ndarray, \*args) -> ndarray
+
+            `f` should accept arrays `x` of shape::
+                (npoints, ndim)
+
+            and output arrays of shape::
+                (npoints, output_dim_1, ..., output_dim_n)
+
+            In this case, `estimate` will return arrays of shape::
+                (output_dim_1, ..., output_dim_n)
+        a, b : ndarray
+            Lower and upper limits of integration as rank-1 arrays specifying the left
+            and right endpoints of the intervals being integrated over. Infinite limits
+            are currently not supported.
+        args : tuple, optional
+            Additional positional args passed to `f`, if any.
+
+        Returns
+        -------
+        err_est : ndarray
+            Result of error estimation. If `f` returns arrays of shape
+            ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
+            of shape ``(output_dim_1, ..., output_dim_n)``.
+        """
+
+        nodes, weights = self.nodes_and_weights
+        lower_nodes, lower_weights = self.lower_nodes_and_weights
+
+        if self.xp is None:
+            self.xp = array_namespace(nodes)
+
+        error_nodes = self.xp.concat([nodes, lower_nodes], axis=0)
+        error_weights = self.xp.concat([weights, -lower_weights], axis=0)
+
+        return self.xp.abs(
+            _apply_fixed_rule(f, a, b, error_nodes, error_weights, args, self.xp)
+        )
+
+
+class ProductNestedFixed(NestedFixedRule):
+    """
+    Find the n-dimensional cubature rule constructed from the Cartesian product of 1-D
+    `NestedFixedRule` quadrature rules.
+
+    Given a list of N 1-dimensional quadrature rules which support error estimation
+    using NestedFixedRule, this will find the N-dimensional cubature rule obtained by
+    taking the Cartesian product of their nodes, and estimating the error by taking the
+    difference with a lower-accuracy N-dimensional cubature rule obtained using the
+    ``.lower_nodes_and_weights`` rule in each of the base 1-dimensional rules.
+
+    Parameters
+    ----------
+    base_rules : list of NestedFixedRule
+        List of base 1-dimensional `NestedFixedRule` quadrature rules.
+
+    Attributes
+    ----------
+    base_rules : list of NestedFixedRule
+        List of base 1-dimensional `NestedFixedRule` qudarature rules.
+
+    Examples
+    --------
+
+    Evaluate a 2D integral by taking the product of two 1D rules:
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import (
+    ...  ProductNestedFixed, GaussKronrodQuadrature
+    ... )
+    >>> def f(x):
+    ...     # f(x) = cos(x_1) + cos(x_2)
+    ...     return np.sum(np.cos(x), axis=-1)
+    >>> rule = ProductNestedFixed(
+    ...     [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)]
+    ... ) # Use 15-point Gauss-Kronrod, which implements NestedFixedRule
+    >>> a, b = np.array([0, 0]), np.array([1, 1])
+    >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829
+     np.float64(1.682941969615793)
+    >>> rule.estimate_error(f, a, b)
+     np.float64(2.220446049250313e-16)
+    """
+
+    def __init__(self, base_rules):
+        for rule in base_rules:
+            if not isinstance(rule, NestedFixedRule):
+                raise ValueError("base rules for product need to be instance of"
+                                 "NestedFixedRule")
+
+        self.base_rules = base_rules
+        self.xp = None
+
+    @cached_property
+    def nodes_and_weights(self):
+        nodes = _cartesian_product(
+            [rule.nodes_and_weights[0] for rule in self.base_rules]
+        )
+
+        if self.xp is None:
+            self.xp = array_namespace(nodes)
+
+        weights = self.xp.prod(
+            _cartesian_product(
+                [rule.nodes_and_weights[1] for rule in self.base_rules]
+            ),
+            axis=-1,
+        )
+
+        return nodes, weights
+
+    @cached_property
+    def lower_nodes_and_weights(self):
+        nodes = _cartesian_product(
+            [cubature.lower_nodes_and_weights[0] for cubature in self.base_rules]
+        )
+
+        if self.xp is None:
+            self.xp = array_namespace(nodes)
+
+        weights = self.xp.prod(
+            _cartesian_product(
+                [cubature.lower_nodes_and_weights[1] for cubature in self.base_rules]
+            ),
+            axis=-1,
+        )
+
+        return nodes, weights
+
+
+def _cartesian_product(arrays):
+    xp = array_namespace(*arrays)
+
+    arrays_ix = xp.meshgrid(*arrays, indexing='ij')
+    result = xp.reshape(xp.stack(arrays_ix, axis=-1), (-1, len(arrays)))
+
+    return result
+
+
+def _split_subregion(a, b, xp, split_at=None):
+    """
+    Given the coordinates of a region like a=[0, 0] and b=[1, 1], yield the coordinates
+    of all subregions, which in this case would be::
+
+        ([0, 0], [1/2, 1/2]),
+        ([0, 1/2], [1/2, 1]),
+        ([1/2, 0], [1, 1/2]),
+        ([1/2, 1/2], [1, 1])
+    """
+    xp = array_namespace(a, b)
+
+    if split_at is None:
+        split_at = (a + b) / 2
+
+    left = [xp.asarray([a[i], split_at[i]]) for i in range(a.shape[0])]
+    right = [xp.asarray([split_at[i], b[i]]) for i in range(b.shape[0])]
+
+    a_sub = _cartesian_product(left)
+    b_sub = _cartesian_product(right)
+
+    for i in range(a_sub.shape[0]):
+        yield a_sub[i, ...], b_sub[i, ...]
+
+
+def _apply_fixed_rule(f, a, b, orig_nodes, orig_weights, args, xp):
+    # Downcast nodes and weights to common dtype of a and b
+    result_dtype = a.dtype
+    orig_nodes = xp.astype(orig_nodes, result_dtype)
+    orig_weights = xp.astype(orig_weights, result_dtype)
+
+    # Ensure orig_nodes are at least 2D, since 1D cubature methods can return arrays of
+    # shape (npoints,) rather than (npoints, 1)
+    if orig_nodes.ndim == 1:
+        orig_nodes = orig_nodes[:, None]
+
+    rule_ndim = orig_nodes.shape[-1]
+
+    a_ndim = xp_size(a)
+    b_ndim = xp_size(b)
+
+    if rule_ndim != a_ndim or rule_ndim != b_ndim:
+        raise ValueError(f"rule and function are of incompatible dimension, nodes have"
+                         f"ndim {rule_ndim}, while limit of integration has ndim"
+                         f"a_ndim={a_ndim}, b_ndim={b_ndim}")
+
+    lengths = b - a
+
+    # The underlying rule is for the hypercube [-1, 1]^n.
+    #
+    # To handle arbitrary regions of integration, it's necessary to apply a linear
+    # change of coordinates to map each interval [a[i], b[i]] to [-1, 1].
+    nodes = (orig_nodes + 1) * (lengths * 0.5) + a
+
+    # Also need to multiply the weights by a scale factor equal to the determinant
+    # of the Jacobian for this coordinate change.
+    weight_scale_factor = xp.prod(lengths, dtype=result_dtype) / 2**rule_ndim
+    weights = orig_weights * weight_scale_factor
+
+    f_nodes = f(nodes, *args)
+    weights_reshaped = xp.reshape(weights, (-1, *([1] * (f_nodes.ndim - 1))))
+
+    # f(nodes) will have shape (num_nodes, output_dim_1, ..., output_dim_n)
+    # Summing along the first axis means estimate will shape (output_dim_1, ...,
+    # output_dim_n)
+    est = xp.sum(weights_reshaped * f_nodes, axis=0, dtype=result_dtype)
+
+    return est
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_kronrod.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_kronrod.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2a3518c55cf49cd14c777d243ea7e93a489f86c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_kronrod.py
@@ -0,0 +1,202 @@
+from scipy._lib._array_api import np_compat, array_namespace
+
+from functools import cached_property
+
+from ._base import NestedFixedRule
+from ._gauss_legendre import GaussLegendreQuadrature
+
+
+class GaussKronrodQuadrature(NestedFixedRule):
+    """
+    Gauss-Kronrod quadrature.
+
+    Gauss-Kronrod rules consist of two quadrature rules, one higher-order and one
+    lower-order. The higher-order rule is used as the estimate of the integral and the
+    difference between them is used as an estimate for the error.
+
+    Gauss-Kronrod is a 1D rule. To use it for multidimensional integrals, it will be
+    necessary to use ProductNestedFixed and multiple Gauss-Kronrod rules. See Examples.
+
+    For n-node Gauss-Kronrod, the lower-order rule has ``n//2`` nodes, which are the
+    ordinary Gauss-Legendre nodes with corresponding weights. The higher-order rule has
+    ``n`` nodes, ``n//2`` of which are the same as the lower-order rule and the
+    remaining nodes are the Kronrod extension of those nodes.
+
+    Parameters
+    ----------
+    npoints : int
+        Number of nodes for the higher-order rule.
+
+    xp : array_namespace, optional
+        The namespace for the node and weight arrays. Default is None, where NumPy is
+        used.
+
+    Attributes
+    ----------
+    lower : Rule
+        Lower-order rule.
+
+    References
+    ----------
+    .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
+        Integration, files: dqk21.f, dqk15.f (1983).
+
+    Examples
+    --------
+    Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the
+    estimates will also be arrays, despite the fact that this is a 1D problem.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import GaussKronrodQuadrature
+    >>> def f(x):
+    ...     return np.cos(x)
+    >>> rule = GaussKronrodQuadrature(21) # Use 21-point GaussKronrod
+    >>> a, b = np.array([0]), np.array([1])
+    >>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147
+     array([0.84147098])
+    >>> rule.estimate_error(f, a, b)
+     array([1.11022302e-16])
+
+    Evaluate a 2D integral. Note that in this example ``f`` returns a float, so the
+    estimates will also be floats.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import (
+    ...     ProductNestedFixed, GaussKronrodQuadrature
+    ... )
+    >>> def f(x):
+    ...     # f(x) = cos(x_1) + cos(x_2)
+    ...     return np.sum(np.cos(x), axis=-1)
+    >>> rule = ProductNestedFixed(
+    ...     [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)]
+    ... ) # Use 15-point Gauss-Kronrod
+    >>> a, b = np.array([0, 0]), np.array([1, 1])
+    >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829
+     np.float64(1.682941969615793)
+    >>> rule.estimate_error(f, a, b)
+     np.float64(2.220446049250313e-16)
+    """
+
+    def __init__(self, npoints, xp=None):
+        # TODO: nodes and weights are currently hard-coded for values 15 and 21, but in
+        # the future it would be best to compute the Kronrod extension of the lower rule
+        if npoints != 15 and npoints != 21:
+            raise NotImplementedError("Gauss-Kronrod quadrature is currently only"
+                                      "supported for 15 or 21 nodes")
+
+        self.npoints = npoints
+
+        if xp is None:
+            xp = np_compat
+
+        self.xp = array_namespace(xp.empty(0))
+
+        self.gauss = GaussLegendreQuadrature(npoints//2, xp=self.xp)
+
+    @cached_property
+    def nodes_and_weights(self):
+        # These values are from QUADPACK's `dqk21.f` and `dqk15.f` (1983).
+        if self.npoints == 21:
+            nodes = self.xp.asarray(
+                [
+                    0.995657163025808080735527280689003,
+                    0.973906528517171720077964012084452,
+                    0.930157491355708226001207180059508,
+                    0.865063366688984510732096688423493,
+                    0.780817726586416897063717578345042,
+                    0.679409568299024406234327365114874,
+                    0.562757134668604683339000099272694,
+                    0.433395394129247190799265943165784,
+                    0.294392862701460198131126603103866,
+                    0.148874338981631210884826001129720,
+                    0,
+                    -0.148874338981631210884826001129720,
+                    -0.294392862701460198131126603103866,
+                    -0.433395394129247190799265943165784,
+                    -0.562757134668604683339000099272694,
+                    -0.679409568299024406234327365114874,
+                    -0.780817726586416897063717578345042,
+                    -0.865063366688984510732096688423493,
+                    -0.930157491355708226001207180059508,
+                    -0.973906528517171720077964012084452,
+                    -0.995657163025808080735527280689003,
+                ],
+                dtype=self.xp.float64,
+            )
+
+            weights = self.xp.asarray(
+                [
+                    0.011694638867371874278064396062192,
+                    0.032558162307964727478818972459390,
+                    0.054755896574351996031381300244580,
+                    0.075039674810919952767043140916190,
+                    0.093125454583697605535065465083366,
+                    0.109387158802297641899210590325805,
+                    0.123491976262065851077958109831074,
+                    0.134709217311473325928054001771707,
+                    0.142775938577060080797094273138717,
+                    0.147739104901338491374841515972068,
+                    0.149445554002916905664936468389821,
+                    0.147739104901338491374841515972068,
+                    0.142775938577060080797094273138717,
+                    0.134709217311473325928054001771707,
+                    0.123491976262065851077958109831074,
+                    0.109387158802297641899210590325805,
+                    0.093125454583697605535065465083366,
+                    0.075039674810919952767043140916190,
+                    0.054755896574351996031381300244580,
+                    0.032558162307964727478818972459390,
+                    0.011694638867371874278064396062192,
+                ],
+                dtype=self.xp.float64,
+            )
+        elif self.npoints == 15:
+            nodes = self.xp.asarray(
+                [
+                    0.991455371120812639206854697526329,
+                    0.949107912342758524526189684047851,
+                    0.864864423359769072789712788640926,
+                    0.741531185599394439863864773280788,
+                    0.586087235467691130294144838258730,
+                    0.405845151377397166906606412076961,
+                    0.207784955007898467600689403773245,
+                    0.000000000000000000000000000000000,
+                    -0.207784955007898467600689403773245,
+                    -0.405845151377397166906606412076961,
+                    -0.586087235467691130294144838258730,
+                    -0.741531185599394439863864773280788,
+                    -0.864864423359769072789712788640926,
+                    -0.949107912342758524526189684047851,
+                    -0.991455371120812639206854697526329,
+                ],
+                dtype=self.xp.float64,
+            )
+
+            weights = self.xp.asarray(
+                [
+                    0.022935322010529224963732008058970,
+                    0.063092092629978553290700663189204,
+                    0.104790010322250183839876322541518,
+                    0.140653259715525918745189590510238,
+                    0.169004726639267902826583426598550,
+                    0.190350578064785409913256402421014,
+                    0.204432940075298892414161999234649,
+                    0.209482141084727828012999174891714,
+                    0.204432940075298892414161999234649,
+                    0.190350578064785409913256402421014,
+                    0.169004726639267902826583426598550,
+                    0.140653259715525918745189590510238,
+                    0.104790010322250183839876322541518,
+                    0.063092092629978553290700663189204,
+                    0.022935322010529224963732008058970,
+                ],
+                dtype=self.xp.float64,
+            )
+
+        return nodes, weights
+
+    @property
+    def lower_nodes_and_weights(self):
+        return self.gauss.nodes_and_weights
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_legendre.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_legendre.py
new file mode 100644
index 0000000000000000000000000000000000000000..1163aec5370fb93951402ab99ee2ae4b79158d52
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_legendre.py
@@ -0,0 +1,62 @@
+from scipy._lib._array_api import array_namespace, np_compat
+
+from functools import cached_property
+
+from scipy.special import roots_legendre
+
+from ._base import FixedRule
+
+
+class GaussLegendreQuadrature(FixedRule):
+    """
+    Gauss-Legendre quadrature.
+
+    Parameters
+    ----------
+    npoints : int
+        Number of nodes for the higher-order rule.
+
+    xp : array_namespace, optional
+        The namespace for the node and weight arrays. Default is None, where NumPy is
+        used.
+
+    Examples
+    --------
+    Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the
+    estimates will also be arrays.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import GaussLegendreQuadrature
+    >>> def f(x):
+    ...     return np.cos(x)
+    >>> rule = GaussLegendreQuadrature(21) # Use 21-point GaussLegendre
+    >>> a, b = np.array([0]), np.array([1])
+    >>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147
+     array([0.84147098])
+    >>> rule.estimate_error(f, a, b)
+     array([1.11022302e-16])
+    """
+
+    def __init__(self, npoints, xp=None):
+        if npoints < 2:
+            raise ValueError(
+                "At least 2 nodes required for Gauss-Legendre cubature"
+            )
+
+        self.npoints = npoints
+
+        if xp is None:
+            xp = np_compat
+
+        self.xp = array_namespace(xp.empty(0))
+
+    @cached_property
+    def nodes_and_weights(self):
+        # TODO: current converting to/from numpy
+        nodes, weights = roots_legendre(self.npoints)
+
+        return (
+            self.xp.asarray(nodes, dtype=self.xp.float64),
+            self.xp.asarray(weights, dtype=self.xp.float64)
+        )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_genz_malik.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_genz_malik.py
new file mode 100644
index 0000000000000000000000000000000000000000..4873805e3364b10a3366de47c15fe3c4b306e5d6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_rules/_genz_malik.py
@@ -0,0 +1,210 @@
+import math
+import itertools
+
+from functools import cached_property
+
+from scipy._lib._array_api import array_namespace, np_compat
+
+from scipy.integrate._rules import NestedFixedRule
+
+
+class GenzMalikCubature(NestedFixedRule):
+    """
+    Genz-Malik cubature.
+
+    Genz-Malik is only defined for integrals of dimension >= 2.
+
+    Parameters
+    ----------
+    ndim : int
+        The spatial dimension of the integrand.
+
+    xp : array_namespace, optional
+        The namespace for the node and weight arrays. Default is None, where NumPy is
+        used.
+
+    Attributes
+    ----------
+    higher : Cubature
+        Higher-order rule.
+
+    lower : Cubature
+        Lower-order rule.
+
+    References
+    ----------
+    .. [1] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
+        numerical integration over an N-dimensional rectangular region, Journal of
+        Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
+        ISSN 0377-0427, https://doi.org/10.1016/0771-050X(80)90039-X.
+
+    Examples
+    --------
+    Evaluate a 3D integral:
+
+    >>> import numpy as np
+    >>> from scipy.integrate import cubature
+    >>> from scipy.integrate._rules import GenzMalikCubature
+    >>> def f(x):
+    ...     # f(x) = cos(x_1) + cos(x_2) + cos(x_3)
+    ...     return np.sum(np.cos(x), axis=-1)
+    >>> rule = GenzMalikCubature(3) # Use 3D Genz-Malik
+    >>> a, b = np.array([0, 0, 0]), np.array([1, 1, 1])
+    >>> rule.estimate(f, a, b) # True value 3*sin(1), approximately 2.5244
+     np.float64(2.5244129547230862)
+    >>> rule.estimate_error(f, a, b)
+     np.float64(1.378269656626685e-06)
+    """
+
+    def __init__(self, ndim, degree=7, lower_degree=5, xp=None):
+        if ndim < 2:
+            raise ValueError("Genz-Malik cubature is only defined for ndim >= 2")
+
+        if degree != 7 or lower_degree != 5:
+            raise NotImplementedError("Genz-Malik cubature is currently only supported"
+                                      "for degree=7, lower_degree=5")
+
+        self.ndim = ndim
+        self.degree = degree
+        self.lower_degree = lower_degree
+
+        if xp is None:
+            xp = np_compat
+
+        self.xp = array_namespace(xp.empty(0))
+
+    @cached_property
+    def nodes_and_weights(self):
+        # TODO: Currently only support for degree 7 Genz-Malik cubature, should aim to
+        # support arbitrary degree
+        l_2 = math.sqrt(9/70)
+        l_3 = math.sqrt(9/10)
+        l_4 = math.sqrt(9/10)
+        l_5 = math.sqrt(9/19)
+
+        its = itertools.chain(
+            [(0,) * self.ndim],
+            _distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
+            _distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
+            _distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
+            itertools.product((l_5, -l_5), repeat=self.ndim),
+        )
+
+        nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim) + 2**self.ndim
+
+        nodes = self.xp.asarray(
+            list(zip(*its)),
+            dtype=self.xp.float64,
+        )
+
+        nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
+
+        # It's convenient to generate the nodes as a sequence of evaluation points
+        # as an array of shape (npoints, ndim), but nodes needs to have shape
+        # (ndim, npoints)
+        nodes = nodes.T
+
+        w_1 = (
+            (2**self.ndim) * (12824 - 9120*self.ndim + (400 * self.ndim**2)) / 19683
+        )
+        w_2 = (2**self.ndim) * 980/6561
+        w_3 = (2**self.ndim) * (1820 - 400 * self.ndim) / 19683
+        w_4 = (2**self.ndim) * (200 / 19683)
+        w_5 = 6859 / 19683
+
+        weights = self.xp.concat([
+            self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
+            self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
+            self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
+            self.xp.asarray(
+                [w_4] * (2 * (self.ndim - 1) * self.ndim),
+                dtype=self.xp.float64,
+            ),
+            self.xp.asarray([w_5] * (2**self.ndim), dtype=self.xp.float64),
+        ])
+
+        return nodes, weights
+
+    @cached_property
+    def lower_nodes_and_weights(self):
+        # TODO: Currently only support for the degree 5 lower rule, in the future it
+        # would be worth supporting arbitrary degree
+
+        # Nodes are almost the same as the full rule, but there are no nodes
+        # corresponding to l_5.
+        l_2 = math.sqrt(9/70)
+        l_3 = math.sqrt(9/10)
+        l_4 = math.sqrt(9/10)
+
+        its = itertools.chain(
+            [(0,) * self.ndim],
+            _distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
+            _distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
+            _distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
+            _distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
+        )
+
+        nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim)
+
+        nodes = self.xp.asarray(list(zip(*its)), dtype=self.xp.float64)
+        nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
+        nodes = nodes.T
+
+        # Weights are different from those in the full rule.
+        w_1 = (2**self.ndim) * (729 - 950*self.ndim + 50*self.ndim**2) / 729
+        w_2 = (2**self.ndim) * (245 / 486)
+        w_3 = (2**self.ndim) * (265 - 100*self.ndim) / 1458
+        w_4 = (2**self.ndim) * (25 / 729)
+
+        weights = self.xp.concat([
+            self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
+            self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
+            self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
+            self.xp.asarray(
+                [w_4] * (2 * (self.ndim - 1) * self.ndim),
+                dtype=self.xp.float64,
+            ),
+        ])
+
+        return nodes, weights
+
+
+def _distinct_permutations(iterable):
+    """
+    Find the number of distinct permutations of elements of `iterable`.
+    """
+
+    # Algorithm: https://w.wiki/Qai
+
+    items = sorted(iterable)
+    size = len(items)
+
+    while True:
+        # Yield the permutation we have
+        yield tuple(items)
+
+        # Find the largest index i such that A[i] < A[i + 1]
+        for i in range(size - 2, -1, -1):
+            if items[i] < items[i + 1]:
+                break
+
+        #  If no such index exists, this permutation is the last one
+        else:
+            return
+
+        # Find the largest index j greater than j such that A[i] < A[j]
+        for j in range(size - 1, i, -1):
+            if items[i] < items[j]:
+                break
+
+        # Swap the value of A[i] with that of A[j], then reverse the
+        # sequence from A[i + 1] to form the new permutation
+        items[i], items[j] = items[j], items[i]
+        items[i+1:] = items[:i-size:-1]  # A[i + 1:][::-1]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py
new file mode 100644
index 0000000000000000000000000000000000000000..de1d844f88f999d96d4616d8060b0b47de1d8dbe
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py
@@ -0,0 +1,1384 @@
+# mypy: disable-error-code="attr-defined"
+import math
+import numpy as np
+from scipy import special
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import (array_namespace, xp_copy, xp_ravel,
+                                   xp_real, xp_take_along_axis)
+
+
+__all__ = ['nsum']
+
+
+# todo:
+#  figure out warning situation
+#  address https://github.com/scipy/scipy/pull/18650#discussion_r1233032521
+#  without `minweight`, we are also suppressing infinities within the interval.
+#    Is that OK? If so, we can probably get rid of `status=3`.
+#  Add heuristic to stop when improvement is too slow / antithrashing
+#  support singularities? interval subdivision? this feature will be added
+#    eventually, but do we adjust the interface now?
+#  When doing log-integration, should the tolerances control the error of the
+#    log-integral or the error of the integral?  The trouble is that `log`
+#    inherently looses some precision so it may not be possible to refine
+#    the integral further. Example: 7th moment of stats.f(15, 20)
+#  respect function evaluation limit?
+#  make public?
+
+
+def tanhsinh(f, a, b, *, args=(), log=False, maxlevel=None, minlevel=2,
+             atol=None, rtol=None, preserve_shape=False, callback=None):
+    """Evaluate a convergent integral numerically using tanh-sinh quadrature.
+
+    In practice, tanh-sinh quadrature achieves quadratic convergence for
+    many integrands: the number of accurate *digits* scales roughly linearly
+    with the number of function evaluations [1]_.
+
+    Either or both of the limits of integration may be infinite, and
+    singularities at the endpoints are acceptable. Divergent integrals and
+    integrands with non-finite derivatives or singularities within an interval
+    are out of scope, but the latter may be evaluated be calling `tanhsinh` on
+    each sub-interval separately.
+
+    Parameters
+    ----------
+    f : callable
+        The function to be integrated. The signature must be::
+
+            f(xi: ndarray, *argsi) -> ndarray
+
+        where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable
+        with ``xi``. `f` must be an elementwise function: see documentation of parameter
+        `preserve_shape` for details. It must not mutate the array ``xi`` or the arrays
+        in ``argsi``.
+        If ``f`` returns a value with complex dtype when evaluated at
+        either endpoint, subsequent arguments ``x`` will have complex dtype
+        (but zero imaginary part).
+    a, b : float array_like
+        Real lower and upper limits of integration. Must be broadcastable with one
+        another and with arrays in `args`. Elements may be infinite.
+    args : tuple of array_like, optional
+        Additional positional array arguments to be passed to `f`. Arrays
+        must be broadcastable with one another and the arrays of `a` and `b`.
+        If the callable for which the root is desired requires arguments that are
+        not broadcastable with `x`, wrap that callable with `f` such that `f`
+        accepts only `x` and broadcastable ``*args``.
+    log : bool, default: False
+        Setting to True indicates that `f` returns the log of the integrand
+        and that `atol` and `rtol` are expressed as the logs of the absolute
+        and relative errors. In this case, the result object will contain the
+        log of the integral and error. This is useful for integrands for which
+        numerical underflow or overflow would lead to inaccuracies.
+        When ``log=True``, the integrand (the exponential of `f`) must be real,
+        but it may be negative, in which case the log of the integrand is a
+        complex number with an imaginary part that is an odd multiple of π.
+    maxlevel : int, default: 10
+        The maximum refinement level of the algorithm.
+
+        At the zeroth level, `f` is called once, performing 16 function
+        evaluations. At each subsequent level, `f` is called once more,
+        approximately doubling the number of function evaluations that have
+        been performed. Accordingly, for many integrands, each successive level
+        will double the number of accurate digits in the result (up to the
+        limits of floating point precision).
+
+        The algorithm will terminate after completing level `maxlevel` or after
+        another termination condition is satisfied, whichever comes first.
+    minlevel : int, default: 2
+        The level at which to begin iteration (default: 2). This does not
+        change the total number of function evaluations or the abscissae at
+        which the function is evaluated; it changes only the *number of times*
+        `f` is called. If ``minlevel=k``, then the integrand is evaluated at
+        all abscissae from levels ``0`` through ``k`` in a single call.
+        Note that if `minlevel` exceeds `maxlevel`, the provided `minlevel` is
+        ignored, and `minlevel` is set equal to `maxlevel`.
+    atol, rtol : float, optional
+        Absolute termination tolerance (default: 0) and relative termination
+        tolerance (default: ``eps**0.75``, where ``eps`` is the precision of
+        the result dtype), respectively.  Iteration will stop when
+        ``res.error < atol`` or  ``res.error < res.integral * rtol``. The error
+        estimate is as described in [1]_ Section 5 but with a lower bound of
+        ``eps * res.integral``. While not theoretically rigorous or
+        conservative, it is said to work well in practice. Must be non-negative
+        and finite if `log` is False, and must be expressed as the log of a
+        non-negative and finite number if `log` is True.
+    preserve_shape : bool, default: False
+        In the following, "arguments of `f`" refers to the array ``xi`` and
+        any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
+        of `a`, `b`, and all elements of `args` (which is conceptually
+        distinct from ``xi` and ``argsi`` passed into `f`).
+
+        - When ``preserve_shape=False`` (default), `f` must accept arguments
+          of *any* broadcastable shapes.
+
+        - When ``preserve_shape=True``, `f` must accept arguments of shape
+          ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
+          abscissae at which the function is being evaluated.
+
+        In either case, for each scalar element ``xi[j]`` within ``xi``, the array
+        returned by `f` must include the scalar ``f(xi[j])`` at the same index.
+        Consequently, the shape of the output is always the shape of the input
+        ``xi``.
+
+        See Examples.
+
+    callback : callable, optional
+        An optional user-supplied function to be called before the first
+        iteration and after each iteration.
+        Called as ``callback(res)``, where ``res`` is a ``_RichResult``
+        similar to that returned by `_differentiate` (but containing the
+        current iterate's values of all variables). If `callback` raises a
+        ``StopIteration``, the algorithm will terminate immediately and
+        `tanhsinh` will return a result object. `callback` must not mutate
+        `res` or its attributes.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. (The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.)
+
+        success : bool array
+            ``True`` when the algorithm terminated successfully (status ``0``).
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            ``0`` : The algorithm converged to the specified tolerances.
+            ``-1`` : (unused)
+            ``-2`` : The maximum number of iterations was reached.
+            ``-3`` : A non-finite value was encountered.
+            ``-4`` : Iteration was terminated by `callback`.
+            ``1`` : The algorithm is proceeding normally (in `callback` only).
+
+        integral : float array
+            An estimate of the integral.
+        error : float array
+            An estimate of the error. Only available if level two or higher
+            has been completed; otherwise NaN.
+        maxlevel : int array
+            The maximum refinement level used.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+    See Also
+    --------
+    quad
+
+    Notes
+    -----
+    Implements the algorithm as described in [1]_ with minor adaptations for
+    finite-precision arithmetic, including some described by [2]_ and [3]_. The
+    tanh-sinh scheme was originally introduced in [4]_.
+
+    Due to floating-point error in the abscissae, the function may be evaluated
+    at the endpoints of the interval during iterations, but the values returned by
+    the function at the endpoints will be ignored.
+
+    References
+    ----------
+    .. [1] Bailey, David H., Karthik Jeyabalan, and Xiaoye S. Li. "A comparison of
+           three high-precision quadrature schemes." Experimental Mathematics 14.3
+           (2005): 317-329.
+    .. [2] Vanherck, Joren, Bart Sorée, and Wim Magnus. "Tanh-sinh quadrature for
+           single and multiple integration using floating-point arithmetic."
+           arXiv preprint arXiv:2007.15057 (2020).
+    .. [3] van Engelen, Robert A.  "Improving the Double Exponential Quadrature
+           Tanh-Sinh, Sinh-Sinh and Exp-Sinh Formulas."
+           https://www.genivia.com/files/qthsh.pdf
+    .. [4] Takahasi, Hidetosi, and Masatake Mori. "Double exponential formulas for
+           numerical integration." Publications of the Research Institute for
+           Mathematical Sciences 9.3 (1974): 721-741.
+
+    Examples
+    --------
+    Evaluate the Gaussian integral:
+
+    >>> import numpy as np
+    >>> from scipy.integrate import tanhsinh
+    >>> def f(x):
+    ...     return np.exp(-x**2)
+    >>> res = tanhsinh(f, -np.inf, np.inf)
+    >>> res.integral  # true value is np.sqrt(np.pi), 1.7724538509055159
+    1.7724538509055159
+    >>> res.error  # actual error is 0
+    4.0007963937534104e-16
+
+    The value of the Gaussian function (bell curve) is nearly zero for
+    arguments sufficiently far from zero, so the value of the integral
+    over a finite interval is nearly the same.
+
+    >>> tanhsinh(f, -20, 20).integral
+    1.772453850905518
+
+    However, with unfavorable integration limits, the integration scheme
+    may not be able to find the important region.
+
+    >>> tanhsinh(f, -np.inf, 1000).integral
+    4.500490856616431
+
+    In such cases, or when there are singularities within the interval,
+    break the integral into parts with endpoints at the important points.
+
+    >>> tanhsinh(f, -np.inf, 0).integral + tanhsinh(f, 0, 1000).integral
+    1.772453850905404
+
+    For integration involving very large or very small magnitudes, use
+    log-integration. (For illustrative purposes, the following example shows a
+    case in which both regular and log-integration work, but for more extreme
+    limits of integration, log-integration would avoid the underflow
+    experienced when evaluating the integral normally.)
+
+    >>> res = tanhsinh(f, 20, 30, rtol=1e-10)
+    >>> res.integral, res.error
+    (4.7819613911309014e-176, 4.670364401645202e-187)
+    >>> def log_f(x):
+    ...     return -x**2
+    >>> res = tanhsinh(log_f, 20, 30, log=True, rtol=np.log(1e-10))
+    >>> np.exp(res.integral), np.exp(res.error)
+    (4.7819613911306924e-176, 4.670364401645093e-187)
+
+    The limits of integration and elements of `args` may be broadcastable
+    arrays, and integration is performed elementwise.
+
+    >>> from scipy import stats
+    >>> dist = stats.gausshyper(13.8, 3.12, 2.51, 5.18)
+    >>> a, b = dist.support()
+    >>> x = np.linspace(a, b, 100)
+    >>> res = tanhsinh(dist.pdf, a, x)
+    >>> ref = dist.cdf(x)
+    >>> np.allclose(res.integral, ref)
+    True
+
+    By default, `preserve_shape` is False, and therefore the callable
+    `f` may be called with arrays of any broadcastable shapes.
+    For example:
+
+    >>> shapes = []
+    >>> def f(x, c):
+    ...    shape = np.broadcast_shapes(x.shape, c.shape)
+    ...    shapes.append(shape)
+    ...    return np.sin(c*x)
+    >>>
+    >>> c = [1, 10, 30, 100]
+    >>> res = tanhsinh(f, 0, 1, args=(c,), minlevel=1)
+    >>> shapes
+    [(4,), (4, 34), (4, 32), (3, 64), (2, 128), (1, 256)]
+
+    To understand where these shapes are coming from - and to better
+    understand how `tanhsinh` computes accurate results - note that
+    higher values of ``c`` correspond with higher frequency sinusoids.
+    The higher frequency sinusoids make the integrand more complicated,
+    so more function evaluations are required to achieve the target
+    accuracy:
+
+    >>> res.nfev
+    array([ 67, 131, 259, 515], dtype=int32)
+
+    The initial ``shape``, ``(4,)``, corresponds with evaluating the
+    integrand at a single abscissa and all four frequencies; this is used
+    for input validation and to determine the size and dtype of the arrays
+    that store results. The next shape corresponds with evaluating the
+    integrand at an initial grid of abscissae and all four frequencies.
+    Successive calls to the function double the total number of abscissae at
+    which the function has been evaluated. However, in later function
+    evaluations, the integrand is evaluated at fewer frequencies because
+    the corresponding integral has already converged to the required
+    tolerance. This saves function evaluations to improve performance, but
+    it requires the function to accept arguments of any shape.
+
+    "Vector-valued" integrands, such as those written for use with
+    `scipy.integrate.quad_vec`, are unlikely to satisfy this requirement.
+    For example, consider
+
+    >>> def f(x):
+    ...    return [x, np.sin(10*x), np.cos(30*x), x*np.sin(100*x)**2]
+
+    This integrand is not compatible with `tanhsinh` as written; for instance,
+    the shape of the output will not be the same as the shape of ``x``. Such a
+    function *could* be converted to a compatible form with the introduction of
+    additional parameters, but this would be inconvenient. In such cases,
+    a simpler solution would be to use `preserve_shape`.
+
+    >>> shapes = []
+    >>> def f(x):
+    ...     shapes.append(x.shape)
+    ...     x0, x1, x2, x3 = x
+    ...     return [x0, np.sin(10*x1), np.cos(30*x2), x3*np.sin(100*x3)]
+    >>>
+    >>> a = np.zeros(4)
+    >>> res = tanhsinh(f, a, 1, preserve_shape=True)
+    >>> shapes
+    [(4,), (4, 66), (4, 64), (4, 128), (4, 256)]
+
+    Here, the broadcasted shape of `a` and `b` is ``(4,)``. With
+    ``preserve_shape=True``, the function may be called with argument
+    ``x`` of shape ``(4,)`` or ``(4, n)``, and this is what we observe.
+
+    """
+    maxfun = None  # unused right now
+    (f, a, b, log, maxfun, maxlevel, minlevel,
+     atol, rtol, args, preserve_shape, callback, xp) = _tanhsinh_iv(
+        f, a, b, log, maxfun, maxlevel, minlevel, atol,
+        rtol, args, preserve_shape, callback)
+
+    # Initialization
+    # `eim._initialize` does several important jobs, including
+    # ensuring that limits, each of the `args`, and the output of `f`
+    # broadcast correctly and are of consistent types. To save a function
+    # evaluation, I pass the midpoint of the integration interval. This comes
+    # at a cost of some gymnastics to ensure that the midpoint has the right
+    # shape and dtype. Did you know that 0d and >0d arrays follow different
+    # type promotion rules?
+    with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
+        c = xp.reshape((xp_ravel(a) + xp_ravel(b))/2, a.shape)
+        inf_a, inf_b = xp.isinf(a), xp.isinf(b)
+        c[inf_a] = b[inf_a] - 1.  # takes care of infinite a
+        c[inf_b] = a[inf_b] + 1.  # takes care of infinite b
+        c[inf_a & inf_b] = 0.  # takes care of infinite a and b
+        temp = eim._initialize(f, (c,), args, complex_ok=True,
+                               preserve_shape=preserve_shape, xp=xp)
+    f, xs, fs, args, shape, dtype, xp = temp
+    a = xp_ravel(xp.astype(xp.broadcast_to(a, shape), dtype))
+    b = xp_ravel(xp.astype(xp.broadcast_to(b, shape), dtype))
+
+    # Transform improper integrals
+    a, b, a0, negative, abinf, ainf, binf = _transform_integrals(a, b, xp)
+
+    # Define variables we'll need
+    nit, nfev = 0, 1  # one function evaluation performed above
+    zero = -xp.inf if log else 0
+    pi = xp.asarray(xp.pi, dtype=dtype)[()]
+    maxiter = maxlevel - minlevel + 1
+    eps = xp.finfo(dtype).eps
+    if rtol is None:
+        rtol = 0.75*math.log(eps) if log else eps**0.75
+
+    Sn = xp_ravel(xp.full(shape, zero, dtype=dtype))  # latest integral estimate
+    Sn[xp.isnan(a) | xp.isnan(b) | xp.isnan(fs[0])] = xp.nan
+    Sk = xp.reshape(xp.empty_like(Sn), (-1, 1))[:, 0:0]  # all integral estimates
+    aerr = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))  # absolute error
+    status = xp_ravel(xp.full(shape, eim._EINPROGRESS, dtype=xp.int32))
+    h0 = _get_base_step(dtype, xp)
+    h0 = xp_real(h0) # base step
+
+    # For term `d4` of error estimate ([1] Section 5), we need to keep the
+    # most extreme abscissae and corresponding `fj`s, `wj`s in Euler-Maclaurin
+    # sum. Here, we initialize these variables.
+    xr0 = xp_ravel(xp.full(shape, -xp.inf, dtype=dtype))
+    fr0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
+    wr0 = xp_ravel(xp.zeros(shape, dtype=dtype))
+    xl0 = xp_ravel(xp.full(shape, xp.inf, dtype=dtype))
+    fl0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
+    wl0 = xp_ravel(xp.zeros(shape, dtype=dtype))
+    d4 = xp_ravel(xp.zeros(shape, dtype=dtype))
+
+    work = _RichResult(
+        Sn=Sn, Sk=Sk, aerr=aerr, h=h0, log=log, dtype=dtype, pi=pi, eps=eps,
+        a=xp.reshape(a, (-1, 1)), b=xp.reshape(b, (-1, 1)),  # integration limits
+        n=minlevel, nit=nit, nfev=nfev, status=status,  # iter/eval counts
+        xr0=xr0, fr0=fr0, wr0=wr0, xl0=xl0, fl0=fl0, wl0=wl0, d4=d4,  # err est
+        ainf=ainf, binf=binf, abinf=abinf, a0=xp.reshape(a0, (-1, 1)),  # transforms
+        # Store the xjc/wj pair cache in an object so they can't get compressed
+        # Using RichResult to allow dot notation, but a dictionary would suffice
+        pair_cache=_RichResult(xjc=None, wj=None, indices=[0], h0=None))  # pair cache
+
+    # Constant scalars don't need to be put in `work` unless they need to be
+    # passed outside `tanhsinh`. Examples: atol, rtol, h0, minlevel.
+
+    # Correspondence between terms in the `work` object and the result
+    res_work_pairs = [('status', 'status'), ('integral', 'Sn'),
+                      ('error', 'aerr'), ('nit', 'nit'), ('nfev', 'nfev')]
+
+    def pre_func_eval(work):
+        # Determine abscissae at which to evaluate `f`
+        work.h = h0 / 2**work.n
+        xjc, wj = _get_pairs(work.n, h0, dtype=work.dtype,
+                             inclusive=(work.n == minlevel), xp=xp, work=work)
+        work.xj, work.wj = _transform_to_limits(xjc, wj, work.a, work.b, xp)
+
+        # Perform abscissae substitutions for infinite limits of integration
+        xj = xp_copy(work.xj)
+        # use xp_real here to avoid cupy/cupy#8434
+        xj[work.abinf] = xj[work.abinf] / (1 - xp_real(xj[work.abinf])**2)
+        xj[work.binf] = 1/xj[work.binf] - 1 + work.a0[work.binf]
+        xj[work.ainf] *= -1
+        return xj
+
+    def post_func_eval(x, fj, work):
+        # Weight integrand as required by substitutions for infinite limits
+        if work.log:
+            fj[work.abinf] += (xp.log(1 + work.xj[work.abinf]**2)
+                               - 2*xp.log(1 - work.xj[work.abinf]**2))
+            fj[work.binf] -= 2 * xp.log(work.xj[work.binf])
+        else:
+            fj[work.abinf] *= ((1 + work.xj[work.abinf]**2) /
+                               (1 - work.xj[work.abinf]**2)**2)
+            fj[work.binf] *= work.xj[work.binf]**-2.
+
+        # Estimate integral with Euler-Maclaurin Sum
+        fjwj, Sn = _euler_maclaurin_sum(fj, work, xp)
+        if work.Sk.shape[-1]:
+            Snm1 = work.Sk[:, -1]
+            Sn = (special.logsumexp(xp.stack([Snm1 - math.log(2), Sn]), axis=0) if log
+                  else Snm1 / 2 + Sn)
+
+        work.fjwj = fjwj
+        work.Sn = Sn
+
+    def check_termination(work):
+        """Terminate due to convergence or encountering non-finite values"""
+        stop = xp.zeros(work.Sn.shape, dtype=bool)
+
+        # Terminate before first iteration if integration limits are equal
+        if work.nit == 0:
+            i = xp_ravel(work.a == work.b)  # ravel singleton dimension
+            zero = xp.asarray(-xp.inf if log else 0.)
+            zero = xp.full(work.Sn.shape, zero, dtype=Sn.dtype)
+            zero[xp.isnan(Sn)] = xp.nan
+            work.Sn[i] = zero[i]
+            work.aerr[i] = zero[i]
+            work.status[i] = eim._ECONVERGED
+            stop[i] = True
+        else:
+            # Terminate if convergence criterion is met
+            rerr, aerr = _estimate_error(work, xp)
+            i = (rerr < rtol) | (aerr < atol)
+            work.aerr =  xp.reshape(xp.astype(aerr, work.dtype), work.Sn.shape)
+            work.status[i] = eim._ECONVERGED
+            stop[i] = True
+
+        # Terminate if integral estimate becomes invalid
+        if log:
+            Sn_real = xp_real(work.Sn)
+            Sn_pos_inf = xp.isinf(Sn_real) & (Sn_real > 0)
+            i = (Sn_pos_inf | xp.isnan(work.Sn)) & ~stop
+        else:
+            i = ~xp.isfinite(work.Sn) & ~stop
+        work.status[i] = eim._EVALUEERR
+        stop[i] = True
+
+        return stop
+
+    def post_termination_check(work):
+        work.n += 1
+        work.Sk = xp.concat((work.Sk, work.Sn[:, xp.newaxis]), axis=-1)
+        return
+
+    def customize_result(res, shape):
+        # If the integration limits were such that b < a, we reversed them
+        # to perform the calculation, and the final result needs to be negated.
+        if log and xp.any(negative):
+            dtype = res['integral'].dtype
+            pi = xp.asarray(xp.pi, dtype=dtype)[()]
+            j = xp.asarray(1j, dtype=xp.complex64)[()]  # minimum complex type
+            res['integral'] = res['integral'] + negative*pi*j
+        else:
+            res['integral'][negative] *= -1
+
+        # For this algorithm, it seems more appropriate to report the maximum
+        # level rather than the number of iterations in which it was performed.
+        res['maxlevel'] = minlevel + res['nit'] - 1
+        res['maxlevel'][res['nit'] == 0] = -1
+        del res['nit']
+        return shape
+
+    # Suppress all warnings initially, since there are many places in the code
+    # for which this is expected behavior.
+    with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
+        res = eim._loop(work, callback, shape, maxiter, f, args, dtype, pre_func_eval,
+                        post_func_eval, check_termination, post_termination_check,
+                        customize_result, res_work_pairs, xp, preserve_shape)
+    return res
+
+
+def _get_base_step(dtype, xp):
+    # Compute the base step length for the provided dtype. Theoretically, the
+    # Euler-Maclaurin sum is infinite, but it gets cut off when either the
+    # weights underflow or the abscissae cannot be distinguished from the
+    # limits of integration. The latter happens to occur first for float32 and
+    # float64, and it occurs when `xjc` (the abscissa complement)
+    # in `_compute_pair` underflows. We can solve for the argument `tmax` at
+    # which it will underflow using [2] Eq. 13.
+    fmin = 4*xp.finfo(dtype).smallest_normal  # stay a little away from the limit
+    tmax = math.asinh(math.log(2/fmin - 1) / xp.pi)
+
+    # Based on this, we can choose a base step size `h` for level 0.
+    # The number of function evaluations will be `2 + m*2^(k+1)`, where `k` is
+    # the level and `m` is an integer we get to choose. I choose
+    # m = _N_BASE_STEPS = `8` somewhat arbitrarily, but a rationale is that a
+    # power of 2 makes floating point arithmetic more predictable. It also
+    # results in a base step size close to `1`, which is what [1] uses (and I
+    # used here until I found [2] and these ideas settled).
+    h0 = tmax / _N_BASE_STEPS
+    return xp.asarray(h0, dtype=dtype)[()]
+
+
+_N_BASE_STEPS = 8
+
+
+def _compute_pair(k, h0, xp):
+    # Compute the abscissa-weight pairs for each level k. See [1] page 9.
+
+    # For now, we compute and store in 64-bit precision. If higher-precision
+    # data types become better supported, it would be good to compute these
+    # using the highest precision available. Or, once there is an Array API-
+    # compatible arbitrary precision array, we can compute at the required
+    # precision.
+
+    # "....each level k of abscissa-weight pairs uses h = 2 **-k"
+    # We adapt to floating point arithmetic using ideas of [2].
+    h = h0 / 2**k
+    max = _N_BASE_STEPS * 2**k
+
+    # For iterations after the first, "....the integrand function needs to be
+    # evaluated only at the odd-indexed abscissas at each level."
+    j = xp.arange(max+1) if k == 0 else xp.arange(1, max+1, 2)
+    jh = j * h
+
+    # "In this case... the weights wj = u1/cosh(u2)^2, where..."
+    pi_2 = xp.pi / 2
+    u1 = pi_2*xp.cosh(jh)
+    u2 = pi_2*xp.sinh(jh)
+    # Denominators get big here. Overflow then underflow doesn't need warning.
+    # with np.errstate(under='ignore', over='ignore'):
+    wj = u1 / xp.cosh(u2)**2
+    # "We actually store 1-xj = 1/(...)."
+    xjc = 1 / (xp.exp(u2) * xp.cosh(u2))  # complement of xj = xp.tanh(u2)
+
+    # When level k == 0, the zeroth xj corresponds with xj = 0. To simplify
+    # code, the function will be evaluated there twice; each gets half weight.
+    wj[0] = wj[0] / 2 if k == 0 else wj[0]
+
+    return xjc, wj  # store at full precision
+
+
+def _pair_cache(k, h0, xp, work):
+    # Cache the abscissa-weight pairs up to a specified level.
+    # Abscissae and weights of consecutive levels are concatenated.
+    # `index` records the indices that correspond with each level:
+    # `xjc[index[k]:index[k+1]` extracts the level `k` abscissae.
+    if not isinstance(h0, type(work.pair_cache.h0)) or h0 != work.pair_cache.h0:
+        work.pair_cache.xjc = xp.empty(0)
+        work.pair_cache.wj = xp.empty(0)
+        work.pair_cache.indices = [0]
+
+    xjcs = [work.pair_cache.xjc]
+    wjs = [work.pair_cache.wj]
+
+    for i in range(len(work.pair_cache.indices)-1, k + 1):
+        xjc, wj = _compute_pair(i, h0, xp)
+        xjcs.append(xjc)
+        wjs.append(wj)
+        work.pair_cache.indices.append(work.pair_cache.indices[-1] + xjc.shape[0])
+
+    work.pair_cache.xjc = xp.concat(xjcs)
+    work.pair_cache.wj = xp.concat(wjs)
+    work.pair_cache.h0 = h0
+
+
+def _get_pairs(k, h0, inclusive, dtype, xp, work):
+    # Retrieve the specified abscissa-weight pairs from the cache
+    # If `inclusive`, return all up to and including the specified level
+    if (len(work.pair_cache.indices) <= k+2
+        or not isinstance (h0, type(work.pair_cache.h0))
+        or h0 != work.pair_cache.h0):
+            _pair_cache(k, h0, xp, work)
+
+    xjc = work.pair_cache.xjc
+    wj = work.pair_cache.wj
+    indices = work.pair_cache.indices
+
+    start = 0 if inclusive else indices[k]
+    end = indices[k+1]
+
+    return xp.astype(xjc[start:end], dtype), xp.astype(wj[start:end], dtype)
+
+
+def _transform_to_limits(xjc, wj, a, b, xp):
+    # Transform integral according to user-specified limits. This is just
+    # math that follows from the fact that the standard limits are (-1, 1).
+    # Note: If we had stored xj instead of xjc, we would have
+    # xj = alpha * xj + beta, where beta = (a + b)/2
+    alpha = (b - a) / 2
+    xj = xp.concat((-alpha * xjc + b, alpha * xjc + a), axis=-1)
+    wj = wj*alpha  # arguments get broadcasted, so we can't use *=
+    wj = xp.concat((wj, wj), axis=-1)
+
+    # Points at the boundaries can be generated due to finite precision
+    # arithmetic, but these function values aren't supposed to be included in
+    # the Euler-Maclaurin sum. Ideally we wouldn't evaluate the function at
+    # these points; however, we can't easily filter out points since this
+    # function is vectorized. Instead, zero the weights.
+    # Note: values may have complex dtype, but have zero imaginary part
+    xj_real, a_real, b_real = xp_real(xj), xp_real(a), xp_real(b)
+    invalid = (xj_real <= a_real) | (xj_real >= b_real)
+    wj[invalid] = 0
+    return xj, wj
+
+
+def _euler_maclaurin_sum(fj, work, xp):
+    # Perform the Euler-Maclaurin Sum, [1] Section 4
+
+    # The error estimate needs to know the magnitude of the last term
+    # omitted from the Euler-Maclaurin sum. This is a bit involved because
+    # it may have been computed at a previous level. I sure hope it's worth
+    # all the trouble.
+    xr0, fr0, wr0 = work.xr0, work.fr0, work.wr0
+    xl0, fl0, wl0 = work.xl0, work.fl0, work.wl0
+
+    # It is much more convenient to work with the transposes of our work
+    # variables here.
+    xj, fj, wj = work.xj.T, fj.T, work.wj.T
+    n_x, n_active = xj.shape  # number of abscissae, number of active elements
+
+    # We'll work with the left and right sides separately
+    xr, xl = xp_copy(xp.reshape(xj, (2, n_x // 2, n_active)))  # this gets modified
+    fr, fl = xp.reshape(fj, (2, n_x // 2, n_active))
+    wr, wl = xp.reshape(wj, (2, n_x // 2, n_active))
+
+    invalid_r = ~xp.isfinite(fr) | (wr == 0)
+    invalid_l = ~xp.isfinite(fl) | (wl == 0)
+
+    # integer index of the maximum abscissa at this level
+    xr[invalid_r] = -xp.inf
+    ir = xp.argmax(xp_real(xr), axis=0, keepdims=True)
+    # abscissa, function value, and weight at this index
+    ### Not Array API Compatible... yet ###
+    xr_max = xp_take_along_axis(xr, ir, axis=0)[0]
+    fr_max = xp_take_along_axis(fr, ir, axis=0)[0]
+    wr_max = xp_take_along_axis(wr, ir, axis=0)[0]
+    # boolean indices at which maximum abscissa at this level exceeds
+    # the incumbent maximum abscissa (from all previous levels)
+    # note: abscissa may have complex dtype, but will have zero imaginary part
+    j = xp_real(xr_max) > xp_real(xr0)
+    # Update record of the incumbent abscissa, function value, and weight
+    xr0[j] = xr_max[j]
+    fr0[j] = fr_max[j]
+    wr0[j] = wr_max[j]
+
+    # integer index of the minimum abscissa at this level
+    xl[invalid_l] = xp.inf
+    il = xp.argmin(xp_real(xl), axis=0, keepdims=True)
+    # abscissa, function value, and weight at this index
+    xl_min = xp_take_along_axis(xl, il, axis=0)[0]
+    fl_min = xp_take_along_axis(fl, il, axis=0)[0]
+    wl_min = xp_take_along_axis(wl, il, axis=0)[0]
+    # boolean indices at which minimum abscissa at this level is less than
+    # the incumbent minimum abscissa (from all previous levels)
+    # note: abscissa may have complex dtype, but will have zero imaginary part
+    j = xp_real(xl_min) < xp_real(xl0)
+    # Update record of the incumbent abscissa, function value, and weight
+    xl0[j] = xl_min[j]
+    fl0[j] = fl_min[j]
+    wl0[j] = wl_min[j]
+    fj = fj.T
+
+    # Compute the error estimate `d4` - the magnitude of the leftmost or
+    # rightmost term, whichever is greater.
+    flwl0 = fl0 + xp.log(wl0) if work.log else fl0 * wl0  # leftmost term
+    frwr0 = fr0 + xp.log(wr0) if work.log else fr0 * wr0  # rightmost term
+    magnitude = xp_real if work.log else xp.abs
+    work.d4 = xp.maximum(magnitude(flwl0), magnitude(frwr0))
+
+    # There are two approaches to dealing with function values that are
+    # numerically infinite due to approaching a singularity - zero them, or
+    # replace them with the function value at the nearest non-infinite point.
+    # [3] pg. 22 suggests the latter, so let's do that given that we have the
+    # information.
+    fr0b = xp.broadcast_to(fr0[xp.newaxis, :], fr.shape)
+    fl0b = xp.broadcast_to(fl0[xp.newaxis, :], fl.shape)
+    fr[invalid_r] = fr0b[invalid_r]
+    fl[invalid_l] = fl0b[invalid_l]
+
+    # When wj is zero, log emits a warning
+    # with np.errstate(divide='ignore'):
+    fjwj = fj + xp.log(work.wj) if work.log else fj * work.wj
+
+    # update integral estimate
+    Sn = (special.logsumexp(fjwj + xp.log(work.h), axis=-1) if work.log
+          else xp.sum(fjwj, axis=-1) * work.h)
+
+    work.xr0, work.fr0, work.wr0 = xr0, fr0, wr0
+    work.xl0, work.fl0, work.wl0 = xl0, fl0, wl0
+
+    return fjwj, Sn
+
+
+def _estimate_error(work, xp):
+    # Estimate the error according to [1] Section 5
+
+    if work.n == 0 or work.nit == 0:
+        # The paper says to use "one" as the error before it can be calculated.
+        # NaN seems to be more appropriate.
+        nan = xp.full_like(work.Sn, xp.nan)
+        return nan, nan
+
+    indices = work.pair_cache.indices
+
+    n_active = work.Sn.shape[0]  # number of active elements
+    axis_kwargs = dict(axis=-1, keepdims=True)
+
+    # With a jump start (starting at level higher than 0), we haven't
+    # explicitly calculated the integral estimate at lower levels. But we have
+    # all the function value-weight products, so we can compute the
+    # lower-level estimates.
+    if work.Sk.shape[-1] == 0:
+        h = 2 * work.h  # step size at this level
+        n_x = indices[work.n]  # number of abscissa up to this level
+        # The right and left fjwj terms from all levels are concatenated along
+        # the last axis. Get out only the terms up to this level.
+        fjwj_rl = xp.reshape(work.fjwj, (n_active, 2, -1))
+        fjwj = xp.reshape(fjwj_rl[:, :, :n_x], (n_active, 2*n_x))
+        # Compute the Euler-Maclaurin sum at this level
+        Snm1 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
+                else xp.sum(fjwj, **axis_kwargs) * h)
+        work.Sk = xp.concat((Snm1, work.Sk), axis=-1)
+
+    if work.n == 1:
+        nan = xp.full_like(work.Sn, xp.nan)
+        return nan, nan
+
+    # The paper says not to calculate the error for n<=2, but it's not clear
+    # about whether it starts at level 0 or level 1. We start at level 0, so
+    # why not compute the error beginning in level 2?
+    if work.Sk.shape[-1] < 2:
+        h = 4 * work.h  # step size at this level
+        n_x = indices[work.n-1]  # number of abscissa up to this level
+        # The right and left fjwj terms from all levels are concatenated along
+        # the last axis. Get out only the terms up to this level.
+        fjwj_rl = xp.reshape(work.fjwj, (work.Sn.shape[0], 2, -1))
+        fjwj = xp.reshape(fjwj_rl[..., :n_x], (n_active, 2*n_x))
+        # Compute the Euler-Maclaurin sum at this level
+        Snm2 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
+                else xp.sum(fjwj, **axis_kwargs) * h)
+        work.Sk = xp.concat((Snm2, work.Sk), axis=-1)
+
+    Snm2 = work.Sk[..., -2]
+    Snm1 = work.Sk[..., -1]
+
+    e1 = xp.asarray(work.eps)[()]
+
+    if work.log:
+        log_e1 = xp.log(e1)
+        # Currently, only real integrals are supported in log-scale. All
+        # complex values have imaginary part in increments of pi*j, which just
+        # carries sign information of the original integral, so use of
+        # `xp.real` here is equivalent to absolute value in real scale.
+        d1 = xp_real(special.logsumexp(xp.stack([work.Sn, Snm1 + work.pi*1j]), axis=0))
+        d2 = xp_real(special.logsumexp(xp.stack([work.Sn, Snm2 + work.pi*1j]), axis=0))
+        d3 = log_e1 + xp.max(xp_real(work.fjwj), axis=-1)
+        d4 = work.d4
+        d5 = log_e1 + xp.real(work.Sn)
+        temp = xp.where(d1 > -xp.inf, d1 ** 2 / d2, -xp.inf)
+        ds = xp.stack([temp, 2 * d1, d3, d4, d5])
+        aerr = xp.max(ds, axis=0)
+        rerr = aerr - xp.real(work.Sn)
+    else:
+        # Note: explicit computation of log10 of each of these is unnecessary.
+        d1 = xp.abs(work.Sn - Snm1)
+        d2 = xp.abs(work.Sn - Snm2)
+        d3 = e1 * xp.max(xp.abs(work.fjwj), axis=-1)
+        d4 = work.d4
+        d5 = e1 * xp.abs(work.Sn)
+        temp = xp.where(d1 > 0, d1**(xp.log(d1)/xp.log(d2)), 0)
+        ds = xp.stack([temp, d1**2, d3, d4, d5])
+        aerr = xp.max(ds, axis=0)
+        rerr = aerr/xp.abs(work.Sn)
+
+    return rerr, aerr
+
+
+def _transform_integrals(a, b, xp):
+    # Transform integrals to a form with finite a <= b
+    # For b == a (even infinite), we ensure that the limits remain equal
+    # For b < a, we reverse the limits and will multiply the final result by -1
+    # For infinite limit on the right, we use the substitution x = 1/t - 1 + a
+    # For infinite limit on the left, we substitute x = -x and treat as above
+    # For infinite limits, we substitute x = t / (1-t**2)
+    ab_same = (a == b)
+    a[ab_same], b[ab_same] = 1, 1
+
+    # `a, b` may have complex dtype but have zero imaginary part
+    negative = xp_real(b) < xp_real(a)
+    a[negative], b[negative] = b[negative], a[negative]
+
+    abinf = xp.isinf(a) & xp.isinf(b)
+    a[abinf], b[abinf] = -1, 1
+
+    ainf = xp.isinf(a)
+    a[ainf], b[ainf] = -b[ainf], -a[ainf]
+
+    binf = xp.isinf(b)
+    a0 = xp_copy(a)
+    a[binf], b[binf] = 0, 1
+
+    return a, b, a0, negative, abinf, ainf, binf
+
+
+def _tanhsinh_iv(f, a, b, log, maxfun, maxlevel, minlevel,
+                 atol, rtol, args, preserve_shape, callback):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a` and `b` must be real numbers.'
+    a, b = xp.asarray(a), xp.asarray(b)
+    a, b = xp.broadcast_arrays(a, b)
+    if (xp.isdtype(a.dtype, 'complex floating')
+            or xp.isdtype(b.dtype, 'complex floating')):
+        raise ValueError(message)
+
+    message = '`log` must be True or False.'
+    if log not in {True, False}:
+        raise ValueError(message)
+    log = bool(log)
+
+    if atol is None:
+        atol = -xp.inf if log else 0
+
+    rtol_temp = rtol if rtol is not None else 0.
+
+    # using NumPy for convenience here; these are just floats, not arrays
+    params = np.asarray([atol, rtol_temp, 0.])
+    message = "`atol` and `rtol` must be real numbers."
+    if not np.issubdtype(params.dtype, np.floating):
+        raise ValueError(message)
+
+    if log:
+        message = '`atol` and `rtol` may not be positive infinity.'
+        if np.any(np.isposinf(params)):
+            raise ValueError(message)
+    else:
+        message = '`atol` and `rtol` must be non-negative and finite.'
+        if np.any(params < 0) or np.any(np.isinf(params)):
+            raise ValueError(message)
+    atol = params[0]
+    rtol = rtol if rtol is None else params[1]
+
+    BIGINT = float(2**62)
+    if maxfun is None and maxlevel is None:
+        maxlevel = 10
+
+    maxfun = BIGINT if maxfun is None else maxfun
+    maxlevel = BIGINT if maxlevel is None else maxlevel
+
+    message = '`maxfun`, `maxlevel`, and `minlevel` must be integers.'
+    params = np.asarray([maxfun, maxlevel, minlevel])
+    if not (np.issubdtype(params.dtype, np.number)
+            and np.all(np.isreal(params))
+            and np.all(params.astype(np.int64) == params)):
+        raise ValueError(message)
+    message = '`maxfun`, `maxlevel`, and `minlevel` must be non-negative.'
+    if np.any(params < 0):
+        raise ValueError(message)
+    maxfun, maxlevel, minlevel = params.astype(np.int64)
+    minlevel = min(minlevel, maxlevel)
+
+    if not np.iterable(args):
+        args = (args,)
+    args = (xp.asarray(arg) for arg in args)
+
+    message = '`preserve_shape` must be True or False.'
+    if preserve_shape not in {True, False}:
+        raise ValueError(message)
+
+    if callback is not None and not callable(callback):
+        raise ValueError('`callback` must be callable.')
+
+    return (f, a, b, log, maxfun, maxlevel, minlevel,
+            atol, rtol, args, preserve_shape, callback, xp)
+
+
+def _nsum_iv(f, a, b, step, args, log, maxterms, tolerances):
+    # Input validation and standardization
+
+    xp = array_namespace(a, b)
+
+    message = '`f` must be callable.'
+    if not callable(f):
+        raise ValueError(message)
+
+    message = 'All elements of `a`, `b`, and `step` must be real numbers.'
+    a, b, step = xp.broadcast_arrays(xp.asarray(a), xp.asarray(b), xp.asarray(step))
+    dtype = xp.result_type(a.dtype, b.dtype, step.dtype)
+    if not xp.isdtype(dtype, 'numeric') or xp.isdtype(dtype, 'complex floating'):
+        raise ValueError(message)
+
+    valid_b = b >= a  # NaNs will be False
+    valid_step = xp.isfinite(step) & (step > 0)
+    valid_abstep = valid_b & valid_step
+
+    message = '`log` must be True or False.'
+    if log not in {True, False}:
+        raise ValueError(message)
+
+    tolerances = {} if tolerances is None else tolerances
+
+    atol = tolerances.get('atol', None)
+    if atol is None:
+        atol = -xp.inf if log else 0
+
+    rtol = tolerances.get('rtol', None)
+    rtol_temp = rtol if rtol is not None else 0.
+
+    # using NumPy for convenience here; these are just floats, not arrays
+    params = np.asarray([atol, rtol_temp, 0.])
+    message = "`atol` and `rtol` must be real numbers."
+    if not np.issubdtype(params.dtype, np.floating):
+        raise ValueError(message)
+
+    if log:
+        message = '`atol`, `rtol` may not be positive infinity or NaN.'
+        if np.any(np.isposinf(params) | np.isnan(params)):
+            raise ValueError(message)
+    else:
+        message = '`atol`, and `rtol` must be non-negative and finite.'
+        if np.any((params < 0) | (~np.isfinite(params))):
+            raise ValueError(message)
+    atol = params[0]
+    rtol = rtol if rtol is None else params[1]
+
+    maxterms_int = int(maxterms)
+    if maxterms_int != maxterms or maxterms < 0:
+        message = "`maxterms` must be a non-negative integer."
+        raise ValueError(message)
+
+    if not np.iterable(args):
+        args = (args,)
+
+    return f, a, b, step, valid_abstep, args, log, maxterms_int, atol, rtol, xp
+
+
+def nsum(f, a, b, *, step=1, args=(), log=False, maxterms=int(2**20), tolerances=None):
+    r"""Evaluate a convergent finite or infinite series.
+
+    For finite `a` and `b`, this evaluates::
+
+        f(a + np.arange(n)*step).sum()
+
+    where ``n = int((b - a) / step) + 1``, where `f` is smooth, positive, and
+    unimodal. The number of terms in the sum may be very large or infinite,
+    in which case a partial sum is evaluated directly and the remainder is
+    approximated using integration.
+
+    Parameters
+    ----------
+    f : callable
+        The function that evaluates terms to be summed. The signature must be::
+
+            f(x: ndarray, *args) -> ndarray
+
+        where each element of ``x`` is a finite real and ``args`` is a tuple,
+        which may contain an arbitrary number of arrays that are broadcastable
+        with ``x``.
+
+        `f` must be an elementwise function: each element ``f(x)[i]``
+        must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
+        array ``x`` or the arrays in ``args``, and it must return NaN where
+        the argument is NaN.
+
+        `f` must represent a smooth, positive, unimodal function of `x` defined at
+        *all reals* between `a` and `b`.
+    a, b : float array_like
+        Real lower and upper limits of summed terms. Must be broadcastable.
+        Each element of `a` must be less than the corresponding element in `b`.
+    step : float array_like
+        Finite, positive, real step between summed terms. Must be broadcastable
+        with `a` and `b`. Note that the number of terms included in the sum will
+        be ``floor((b - a) / step)`` + 1; adjust `b` accordingly to ensure
+        that ``f(b)`` is included if intended.
+    args : tuple of array_like, optional
+        Additional positional arguments to be passed to `f`. Must be arrays
+        broadcastable with `a`, `b`, and `step`. If the callable to be summed
+        requires arguments that are not broadcastable with `a`, `b`, and `step`,
+        wrap that callable with `f` such that `f` accepts only `x` and
+        broadcastable ``*args``. See Examples.
+    log : bool, default: False
+        Setting to True indicates that `f` returns the log of the terms
+        and that `atol` and `rtol` are expressed as the logs of the absolute
+        and relative errors. In this case, the result object will contain the
+        log of the sum and error. This is useful for summands for which
+        numerical underflow or overflow would lead to inaccuracies.
+    maxterms : int, default: 2**20
+        The maximum number of terms to evaluate for direct summation.
+        Additional function evaluations may be performed for input
+        validation and integral evaluation.
+    atol, rtol : float, optional
+        Absolute termination tolerance (default: 0) and relative termination
+        tolerance (default: ``eps**0.5``, where ``eps`` is the precision of
+        the result dtype), respectively. Must be non-negative
+        and finite if `log` is False, and must be expressed as the log of a
+        non-negative and finite number if `log` is True.
+
+    Returns
+    -------
+    res : _RichResult
+        An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+        following attributes. (The descriptions are written as though the values will
+        be scalars; however, if `f` returns an array, the outputs will be
+        arrays of the same shape.)
+
+        success : bool
+            ``True`` when the algorithm terminated successfully (status ``0``);
+            ``False`` otherwise.
+        status : int array
+            An integer representing the exit status of the algorithm.
+
+            - ``0`` : The algorithm converged to the specified tolerances.
+            - ``-1`` : Element(s) of `a`, `b`, or `step` are invalid
+            - ``-2`` : Numerical integration reached its iteration limit;
+              the sum may be divergent.
+            - ``-3`` : A non-finite value was encountered.
+            - ``-4`` : The magnitude of the last term of the partial sum exceeds
+              the tolerances, so the error estimate exceeds the tolerances.
+              Consider increasing `maxterms` or loosening `tolerances`.
+              Alternatively, the callable may not be unimodal, or the limits of
+              summation may be too far from the function maximum. Consider
+              increasing `maxterms` or breaking the sum into pieces.
+
+        sum : float array
+            An estimate of the sum.
+        error : float array
+            An estimate of the absolute error, assuming all terms are non-negative,
+            the function is computed exactly, and direct summation is accurate to
+            the precision of the result dtype.
+        nfev : int array
+            The number of points at which `f` was evaluated.
+
+    See Also
+    --------
+    mpmath.nsum
+
+    Notes
+    -----
+    The method implemented for infinite summation is related to the integral
+    test for convergence of an infinite series: assuming `step` size 1 for
+    simplicity of exposition, the sum of a monotone decreasing function is bounded by
+
+    .. math::
+
+        \int_u^\infty f(x) dx \leq \sum_{k=u}^\infty f(k) \leq \int_u^\infty f(x) dx + f(u)
+
+    Let :math:`a` represent  `a`, :math:`n` represent `maxterms`, :math:`\epsilon_a`
+    represent `atol`, and :math:`\epsilon_r` represent `rtol`.
+    The implementation first evaluates the integral :math:`S_l=\int_a^\infty f(x) dx`
+    as a lower bound of the infinite sum. Then, it seeks a value :math:`c > a` such
+    that :math:`f(c) < \epsilon_a + S_l \epsilon_r`, if it exists; otherwise,
+    let :math:`c = a + n`. Then the infinite sum is approximated as
+
+    .. math::
+
+        \sum_{k=a}^{c-1} f(k) + \int_c^\infty f(x) dx + f(c)/2
+
+    and the reported error is :math:`f(c)/2` plus the error estimate of
+    numerical integration. Note that the integral approximations may require
+    evaluation of the function at points besides those that appear in the sum,
+    so `f` must be a continuous and monotonically decreasing function defined
+    for all reals within the integration interval. However, due to the nature
+    of the integral approximation, the shape of the function between points
+    that appear in the sum has little effect. If there is not a natural
+    extension of the function to all reals, consider using linear interpolation,
+    which is easy to evaluate and preserves monotonicity.
+
+    The approach described above is generalized for non-unit
+    `step` and finite `b` that is too large for direct evaluation of the sum,
+    i.e. ``b - a + 1 > maxterms``. It is further generalized to unimodal
+    functions by directly summing terms surrounding the maximum.
+    This strategy may fail:
+
+    - If the left limit is finite and the maximum is far from it.
+    - If the right limit is finite and the maximum is far from it.
+    - If both limits are finite and the maximum is far from the origin.
+
+    In these cases, accuracy may be poor, and `nsum` may return status code ``4``.
+
+    Although the callable `f` must be non-negative and unimodal,
+    `nsum` can be used to evaluate more general forms of series. For instance, to
+    evaluate an alternating series, pass a callable that returns the difference
+    between pairs of adjacent terms, and adjust `step` accordingly. See Examples.
+
+    References
+    ----------
+    .. [1] Wikipedia. "Integral test for convergence."
+           https://en.wikipedia.org/wiki/Integral_test_for_convergence
+
+    Examples
+    --------
+    Compute the infinite sum of the reciprocals of squared integers.
+
+    >>> import numpy as np
+    >>> from scipy.integrate import nsum
+    >>> res = nsum(lambda k: 1/k**2, 1, np.inf)
+    >>> ref = np.pi**2/6  # true value
+    >>> res.error  # estimated error
+    np.float64(7.448762306416137e-09)
+    >>> (res.sum - ref)/ref  # true error
+    np.float64(-1.839871898894426e-13)
+    >>> res.nfev  # number of points at which callable was evaluated
+    np.int32(8561)
+
+    Compute the infinite sums of the reciprocals of integers raised to powers ``p``,
+    where ``p`` is an array.
+
+    >>> from scipy import special
+    >>> p = np.arange(3, 10)
+    >>> res = nsum(lambda k, p: 1/k**p, 1, np.inf, maxterms=1e3, args=(p,))
+    >>> ref = special.zeta(p, 1)
+    >>> np.allclose(res.sum, ref)
+    True
+
+    Evaluate the alternating harmonic series.
+
+    >>> res = nsum(lambda x: 1/x - 1/(x+1), 1, np.inf, step=2)
+    >>> res.sum, res.sum - np.log(2)  # result, difference vs analytical sum
+    (np.float64(0.6931471805598691), np.float64(-7.616129948928574e-14))
+
+    """ # noqa: E501
+    # Potential future work:
+    # - improve error estimate of `_direct` sum
+    # - add other methods for convergence acceleration (Richardson, epsilon)
+    # - support negative monotone increasing functions?
+    # - b < a / negative step?
+    # - complex-valued function?
+    # - check for violations of monotonicity?
+
+    # Function-specific input validation / standardization
+    tmp = _nsum_iv(f, a, b, step, args, log, maxterms, tolerances)
+    f, a, b, step, valid_abstep, args, log, maxterms, atol, rtol, xp = tmp
+
+    # Additional elementwise algorithm input validation / standardization
+    tmp = eim._initialize(f, (a,), args, complex_ok=False, xp=xp)
+    f, xs, fs, args, shape, dtype, xp = tmp
+
+    # Finish preparing `a`, `b`, and `step` arrays
+    a = xs[0]
+    b = xp.astype(xp_ravel(xp.broadcast_to(b, shape)), dtype)
+    step = xp.astype(xp_ravel(xp.broadcast_to(step, shape)), dtype)
+    valid_abstep = xp_ravel(xp.broadcast_to(valid_abstep, shape))
+    nterms = xp.floor((b - a) / step)
+    finite_terms = xp.isfinite(nterms)
+    b[finite_terms] = a[finite_terms] + nterms[finite_terms]*step[finite_terms]
+
+    # Define constants
+    eps = xp.finfo(dtype).eps
+    zero = xp.asarray(-xp.inf if log else 0, dtype=dtype)[()]
+    if rtol is None:
+        rtol = 0.5*math.log(eps) if log else eps**0.5
+    constants = (dtype, log, eps, zero, rtol, atol, maxterms)
+
+    # Prepare result arrays
+    S = xp.empty_like(a)
+    E = xp.empty_like(a)
+    status = xp.zeros(len(a), dtype=xp.int32)
+    nfev = xp.ones(len(a), dtype=xp.int32)  # one function evaluation above
+
+    # Branch for direct sum evaluation / integral approximation / invalid input
+    i0 = ~valid_abstep                     # invalid
+    i1 = (nterms + 1 <= maxterms) & ~i0    # direct sum evaluation
+    i2 = xp.isfinite(a) & ~i1 & ~i0        # infinite sum to the right
+    i3 = xp.isfinite(b) & ~i2 & ~i1 & ~i0  # infinite sum to the left
+    i4 = ~i3 & ~i2 & ~i1 & ~i0             # infinite sum on both sides
+
+    if xp.any(i0):
+        S[i0], E[i0] = xp.nan, xp.nan
+        status[i0] = -1
+
+    if xp.any(i1):
+        args_direct = [arg[i1] for arg in args]
+        tmp = _direct(f, a[i1], b[i1], step[i1], args_direct, constants, xp)
+        S[i1], E[i1] = tmp[:-1]
+        nfev[i1] += tmp[-1]
+        status[i1] = -3 * xp.asarray(~xp.isfinite(S[i1]), dtype=xp.int32)
+
+    if xp.any(i2):
+        args_indirect = [arg[i2] for arg in args]
+        tmp = _integral_bound(f, a[i2], b[i2], step[i2],
+                              args_indirect, constants, xp)
+        S[i2], E[i2], status[i2] = tmp[:-1]
+        nfev[i2] += tmp[-1]
+
+    if xp.any(i3):
+        args_indirect = [arg[i3] for arg in args]
+        def _f(x, *args): return f(-x, *args)
+        tmp = _integral_bound(_f, -b[i3], -a[i3], step[i3],
+                              args_indirect, constants, xp)
+        S[i3], E[i3], status[i3] = tmp[:-1]
+        nfev[i3] += tmp[-1]
+
+    if xp.any(i4):
+        args_indirect = [arg[i4] for arg in args]
+
+        # There are two obvious high-level strategies:
+        # - Do two separate half-infinite sums (e.g. from -inf to 0 and 1 to inf)
+        # - Make a callable that returns f(x) + f(-x) and do a single half-infinite sum
+        # I thought the latter would have about half the overhead, so I went that way.
+        # Then there are two ways of ensuring that f(0) doesn't get counted twice.
+        # - Evaluate the sum from 1 to inf and add f(0)
+        # - Evaluate the sum from 0 to inf and subtract f(0)
+        # - Evaluate the sum from 0 to inf, but apply a weight of 0.5 when `x = 0`
+        # The last option has more overhead, but is simpler to implement correctly
+        # (especially getting the status message right)
+        if log:
+            def _f(x, *args):
+                log_factor = xp.where(x==0, math.log(0.5), 0)
+                out = xp.stack([f(x, *args), f(-x, *args)], axis=0)
+                return special.logsumexp(out, axis=0) + log_factor
+
+        else:
+            def _f(x, *args):
+                factor = xp.where(x==0, 0.5, 1)
+                return (f(x, *args) + f(-x, *args)) * factor
+
+        zero = xp.zeros_like(a[i4])
+        tmp = _integral_bound(_f, zero, b[i4], step[i4], args_indirect, constants, xp)
+        S[i4], E[i4], status[i4] = tmp[:-1]
+        nfev[i4] += 2*tmp[-1]
+
+    # Return results
+    S, E = S.reshape(shape)[()], E.reshape(shape)[()]
+    status, nfev = status.reshape(shape)[()], nfev.reshape(shape)[()]
+    return _RichResult(sum=S, error=E, status=status, success=status == 0,
+                       nfev=nfev)
+
+
+def _direct(f, a, b, step, args, constants, xp, inclusive=True):
+    # Directly evaluate the sum.
+
+    # When used in the context of distributions, `args` would contain the
+    # distribution parameters. We have broadcasted for simplicity, but we could
+    # reduce function evaluations when distribution parameters are the same but
+    # sum limits differ. Roughly:
+    # - compute the function at all points between min(a) and max(b),
+    # - compute the cumulative sum,
+    # - take the difference between elements of the cumulative sum
+    #   corresponding with b and a.
+    # This is left to future enhancement
+
+    dtype, log, eps, zero, _, _, _ = constants
+
+    # To allow computation in a single vectorized call, find the maximum number
+    # of points (over all slices) at which the function needs to be evaluated.
+    # Note: if `inclusive` is `True`, then we want `1` more term in the sum.
+    # I didn't think it was great style to use `True` as `1` in Python, so I
+    # explicitly converted it to an `int` before using it.
+    inclusive_adjustment = int(inclusive)
+    steps = xp.round((b - a) / step) + inclusive_adjustment
+    # Equivalently, steps = xp.round((b - a) / step) + inclusive
+    max_steps = int(xp.max(steps))
+
+    # In each slice, the function will be evaluated at the same number of points,
+    # but excessive points (those beyond the right sum limit `b`) are replaced
+    # with NaN to (potentially) reduce the time of these unnecessary calculations.
+    # Use a new last axis for these calculations for consistency with other
+    # elementwise algorithms.
+    a2, b2, step2 = a[:, xp.newaxis], b[:, xp.newaxis], step[:, xp.newaxis]
+    args2 = [arg[:, xp.newaxis] for arg in args]
+    ks = a2 + xp.arange(max_steps, dtype=dtype) * step2
+    i_nan = ks >= (b2 + inclusive_adjustment*step2/2)
+    ks[i_nan] = xp.nan
+    fs = f(ks, *args2)
+
+    # The function evaluated at NaN is NaN, and NaNs are zeroed in the sum.
+    # In some cases it may be faster to loop over slices than to vectorize
+    # like this. This is an optimization that can be added later.
+    fs[i_nan] = zero
+    nfev = max_steps - i_nan.sum(axis=-1)
+    S = special.logsumexp(fs, axis=-1) if log else xp.sum(fs, axis=-1)
+    # Rough, non-conservative error estimate. See gh-19667 for improvement ideas.
+    E = xp_real(S) + math.log(eps) if log else eps * abs(S)
+    return S, E, nfev
+
+
+def _integral_bound(f, a, b, step, args, constants, xp):
+    # Estimate the sum with integral approximation
+    dtype, log, _, _, rtol, atol, maxterms = constants
+    log2 = xp.asarray(math.log(2), dtype=dtype)
+
+    # Get a lower bound on the sum and compute effective absolute tolerance
+    lb = tanhsinh(f, a, b, args=args, atol=atol, rtol=rtol, log=log)
+    tol = xp.broadcast_to(xp.asarray(atol), lb.integral.shape)
+    if log:
+        tol = special.logsumexp(xp.stack((tol, rtol + lb.integral)), axis=0)
+    else:
+        tol = tol + rtol*lb.integral
+    i_skip = lb.status < 0  # avoid unnecessary f_evals if integral is divergent
+    tol[i_skip] = xp.nan
+    status = lb.status
+
+    # As in `_direct`, we'll need a temporary new axis for points
+    # at which to evaluate the function. Append axis at the end for
+    # consistency with other elementwise algorithms.
+    a2 = a[..., xp.newaxis]
+    step2 = step[..., xp.newaxis]
+    args2 = [arg[..., xp.newaxis] for arg in args]
+
+    # Find the location of a term that is less than the tolerance (if possible)
+    log2maxterms = math.floor(math.log2(maxterms)) if maxterms else 0
+    n_steps = xp.concat((2**xp.arange(0, log2maxterms), xp.asarray([maxterms])))
+    n_steps = xp.astype(n_steps, dtype)
+    nfev = len(n_steps) * 2
+    ks = a2 + n_steps * step2
+    fks = f(ks, *args2)
+    fksp1 = f(ks + step2, *args2)  # check that the function is decreasing
+    fk_insufficient = (fks > tol[:, xp.newaxis]) | (fksp1 > fks)
+    n_fk_insufficient = xp.sum(fk_insufficient, axis=-1)
+    nt = xp.minimum(n_fk_insufficient, xp.asarray(n_steps.shape[-1]-1))
+    n_steps = n_steps[nt]
+
+    # If `maxterms` is insufficient (i.e. either the magnitude of the last term of the
+    # partial sum exceeds the tolerance or the function is not decreasing), finish the
+    # calculation, but report nonzero status. (Improvement: separate the status codes
+    # for these two cases.)
+    i_fk_insufficient = (n_fk_insufficient == nfev//2)
+
+    # Directly evaluate the sum up to this term
+    k = a + n_steps * step
+    left, left_error, left_nfev = _direct(f, a, k, step, args,
+                                          constants, xp, inclusive=False)
+    left_is_pos_inf = xp.isinf(left) & (left > 0)
+    i_skip |= left_is_pos_inf  # if sum is infinite, no sense in continuing
+    status[left_is_pos_inf] = -3
+    k[i_skip] = xp.nan
+
+    # Use integration to estimate the remaining sum
+    # Possible optimization for future work: if there were no terms less than
+    # the tolerance, there is no need to compute the integral to better accuracy.
+    # Something like:
+    # atol = xp.maximum(atol, xp.minimum(fk/2 - fb/2))
+    # rtol = xp.maximum(rtol, xp.minimum((fk/2 - fb/2)/left))
+    # where `fk`/`fb` are currently calculated below.
+    right = tanhsinh(f, k, b, args=args, atol=atol, rtol=rtol, log=log)
+
+    # Calculate the full estimate and error from the pieces
+    fk = fks[xp.arange(len(fks)), nt]
+
+    # fb = f(b, *args), but some functions return NaN at infinity.
+    # instead of 0 like they must (for the sum to be convergent).
+    fb = xp.full_like(fk, -xp.inf) if log else xp.zeros_like(fk)
+    i = xp.isfinite(b)
+    if xp.any(i):  # better not call `f` with empty arrays
+        fb[i] = f(b[i], *[arg[i] for arg in args])
+    nfev = nfev + xp.asarray(i, dtype=left_nfev.dtype)
+
+    if log:
+        log_step = xp.log(step)
+        S_terms = (left, right.integral - log_step, fk - log2, fb - log2)
+        S = special.logsumexp(xp.stack(S_terms), axis=0)
+        E_terms = (left_error, right.error - log_step, fk-log2, fb-log2+xp.pi*1j)
+        E = xp_real(special.logsumexp(xp.stack(E_terms), axis=0))
+    else:
+        S = left + right.integral/step + fk/2 + fb/2
+        E = left_error + right.error/step + fk/2 - fb/2
+    status[~i_skip] = right.status[~i_skip]
+
+    status[(status == 0) & i_fk_insufficient] = -4
+    return S, E, status, left_nfev + right.nfev + nfev + lb.nfev
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..fbe799fa8bfe4c5f1b2d2ed5edc07fe91db628ef
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/dop.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/dop.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf67a9a35b7d2959c2617aadc5638b577a45b9b5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/dop.py
@@ -0,0 +1,15 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="dop",
+                                   private_modules=["_dop"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/lsoda.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/lsoda.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bc1f1da3c4f0aefad9da73b6405b957ce9335b4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/lsoda.py
@@ -0,0 +1,15 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ['lsoda']  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="lsoda",
+                                   private_modules=["_lsoda"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/odepack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/odepack.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bb4c1a8c9be375df855abe6e1b30ca9711f2607
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/odepack.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.integrate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ['odeint', 'ODEintWarning']  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="odepack",
+                                   private_modules=["_odepack_py"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/quadpack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/quadpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..144584988095c8855da8c34253c045f1a3940572
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/quadpack.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.integrate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    "quad",
+    "dblquad",
+    "tplquad",
+    "nquad",
+    "IntegrationWarning",
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="quadpack",
+                                   private_modules=["_quadpack_py"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test__quad_vec.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test__quad_vec.py
new file mode 100644
index 0000000000000000000000000000000000000000..851d28f5671c3eb5821a7379547c1ba66a7e1340
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test__quad_vec.py
@@ -0,0 +1,217 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.integrate import quad_vec
+
+from multiprocessing.dummy import Pool
+
+
+quadrature_params = pytest.mark.parametrize(
+    'quadrature', [None, "gk15", "gk21", "trapezoid"])
+
+
+@quadrature_params
+def test_quad_vec_simple(quadrature):
+    n = np.arange(10)
+    def f(x):
+        return x ** n
+    for epsabs in [0.1, 1e-3, 1e-6]:
+        if quadrature == 'trapezoid' and epsabs < 1e-4:
+            # slow: skip
+            continue
+
+        kwargs = dict(epsabs=epsabs, quadrature=quadrature)
+
+        exact = 2**(n+1)/(n + 1)
+
+        res, err = quad_vec(f, 0, 2, norm='max', **kwargs)
+        assert_allclose(res, exact, rtol=0, atol=epsabs)
+
+        res, err = quad_vec(f, 0, 2, norm='2', **kwargs)
+        assert np.linalg.norm(res - exact) < epsabs
+
+        res, err = quad_vec(f, 0, 2, norm='max', points=(0.5, 1.0), **kwargs)
+        assert_allclose(res, exact, rtol=0, atol=epsabs)
+
+        res, err, *rest = quad_vec(f, 0, 2, norm='max',
+                                   epsrel=1e-8,
+                                   full_output=True,
+                                   limit=10000,
+                                   **kwargs)
+        assert_allclose(res, exact, rtol=0, atol=epsabs)
+
+
+@quadrature_params
+def test_quad_vec_simple_inf(quadrature):
+    def f(x):
+        return 1 / (1 + np.float64(x) ** 2)
+
+    for epsabs in [0.1, 1e-3, 1e-6]:
+        if quadrature == 'trapezoid' and epsabs < 1e-4:
+            # slow: skip
+            continue
+
+        kwargs = dict(norm='max', epsabs=epsabs, quadrature=quadrature)
+
+        res, err = quad_vec(f, 0, np.inf, **kwargs)
+        assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err))
+
+        res, err = quad_vec(f, 0, -np.inf, **kwargs)
+        assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err))
+
+        res, err = quad_vec(f, -np.inf, 0, **kwargs)
+        assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err))
+
+        res, err = quad_vec(f, np.inf, 0, **kwargs)
+        assert_allclose(res, -np.pi/2, rtol=0, atol=max(epsabs, err))
+
+        res, err = quad_vec(f, -np.inf, np.inf, **kwargs)
+        assert_allclose(res, np.pi, rtol=0, atol=max(epsabs, err))
+
+        res, err = quad_vec(f, np.inf, -np.inf, **kwargs)
+        assert_allclose(res, -np.pi, rtol=0, atol=max(epsabs, err))
+
+        res, err = quad_vec(f, np.inf, np.inf, **kwargs)
+        assert_allclose(res, 0, rtol=0, atol=max(epsabs, err))
+
+        res, err = quad_vec(f, -np.inf, -np.inf, **kwargs)
+        assert_allclose(res, 0, rtol=0, atol=max(epsabs, err))
+
+        res, err = quad_vec(f, 0, np.inf, points=(1.0, 2.0), **kwargs)
+        assert_allclose(res, np.pi/2, rtol=0, atol=max(epsabs, err))
+
+    def f(x):
+        return np.sin(x + 2) / (1 + x ** 2)
+    exact = np.pi / np.e * np.sin(2)
+    epsabs = 1e-5
+
+    res, err, info = quad_vec(f, -np.inf, np.inf, limit=1000, norm='max', epsabs=epsabs,
+                              quadrature=quadrature, full_output=True)
+    assert info.status == 1
+    assert_allclose(res, exact, rtol=0, atol=max(epsabs, 1.5 * err))
+
+
+def test_quad_vec_args():
+    def f(x, a):
+        return x * (x + a) * np.arange(3)
+    a = 2
+    exact = np.array([0, 4/3, 8/3])
+
+    res, err = quad_vec(f, 0, 1, args=(a,))
+    assert_allclose(res, exact, rtol=0, atol=1e-4)
+
+
+def _lorenzian(x):
+    return 1 / (1 + x**2)
+
+
+@pytest.mark.fail_slow(10)
+def test_quad_vec_pool():
+    f = _lorenzian
+    res, err = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4, workers=4)
+    assert_allclose(res, np.pi, rtol=0, atol=1e-4)
+
+    with Pool(10) as pool:
+        def f(x):
+            return 1 / (1 + x ** 2)
+        res, _ = quad_vec(f, -np.inf, np.inf, norm='max', epsabs=1e-4, workers=pool.map)
+        assert_allclose(res, np.pi, rtol=0, atol=1e-4)
+
+
+def _func_with_args(x, a):
+    return x * (x + a) * np.arange(3)
+
+
+@pytest.mark.fail_slow(10)
+@pytest.mark.parametrize('extra_args', [2, (2,)])
+@pytest.mark.parametrize('workers', [1, 10])
+def test_quad_vec_pool_args(extra_args, workers):
+    f = _func_with_args
+    exact = np.array([0, 4/3, 8/3])
+
+    res, err = quad_vec(f, 0, 1, args=extra_args, workers=workers)
+    assert_allclose(res, exact, rtol=0, atol=1e-4)
+
+    with Pool(workers) as pool:
+        res, err = quad_vec(f, 0, 1, args=extra_args, workers=pool.map)
+        assert_allclose(res, exact, rtol=0, atol=1e-4)
+
+
+@quadrature_params
+def test_num_eval(quadrature):
+    def f(x):
+        count[0] += 1
+        return x**5
+
+    count = [0]
+    res = quad_vec(f, 0, 1, norm='max', full_output=True, quadrature=quadrature)
+    assert res[2].neval == count[0]
+
+
+def test_info():
+    def f(x):
+        return np.ones((3, 2, 1))
+
+    res, err, info = quad_vec(f, 0, 1, norm='max', full_output=True)
+
+    assert info.success is True
+    assert info.status == 0
+    assert info.message == 'Target precision reached.'
+    assert info.neval > 0
+    assert info.intervals.shape[1] == 2
+    assert info.integrals.shape == (info.intervals.shape[0], 3, 2, 1)
+    assert info.errors.shape == (info.intervals.shape[0],)
+
+
+def test_nan_inf():
+    def f_nan(x):
+        return np.nan
+
+    def f_inf(x):
+        return np.inf if x < 0.1 else 1/x
+
+    res, err, info = quad_vec(f_nan, 0, 1, full_output=True)
+    assert info.status == 3
+
+    res, err, info = quad_vec(f_inf, 0, 1, full_output=True)
+    assert info.status == 3
+
+
+@pytest.mark.parametrize('a,b', [(0, 1), (0, np.inf), (np.inf, 0),
+                                 (-np.inf, np.inf), (np.inf, -np.inf)])
+def test_points(a, b):
+    # Check that initial interval splitting is done according to
+    # `points`, by checking that consecutive sets of 15 point (for
+    # gk15) function evaluations lie between `points`
+
+    points = (0, 0.25, 0.5, 0.75, 1.0)
+    points += tuple(-x for x in points)
+
+    quadrature_points = 15
+    interval_sets = []
+    count = 0
+
+    def f(x):
+        nonlocal count
+
+        if count % quadrature_points == 0:
+            interval_sets.append(set())
+
+        count += 1
+        interval_sets[-1].add(float(x))
+        return 0.0
+
+    quad_vec(f, a, b, points=points, quadrature='gk15', limit=0)
+
+    # Check that all point sets lie in a single `points` interval
+    for p in interval_sets:
+        j = np.searchsorted(sorted(points), tuple(p))
+        assert np.all(j == j[0])
+
+
+@pytest.mark.thread_unsafe
+def test_trapz_deprecation():
+    with pytest.deprecated_call(match="`quadrature='trapz'`"):
+        quad_vec(lambda x: x, 0, 1, quadrature="trapz")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..358c5e3d1fcfe7ccd7e3691bd9af2f47656f4e2b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_banded_ode_solvers.py
@@ -0,0 +1,220 @@
+import itertools
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+from scipy.integrate import ode
+
+
+def _band_count(a):
+    """Returns ml and mu, the lower and upper band sizes of a."""
+    nrows, ncols = a.shape
+    ml = 0
+    for k in range(-nrows+1, 0):
+        if np.diag(a, k).any():
+            ml = -k
+            break
+    mu = 0
+    for k in range(nrows-1, 0, -1):
+        if np.diag(a, k).any():
+            mu = k
+            break
+    return ml, mu
+
+
+def _linear_func(t, y, a):
+    """Linear system dy/dt = a * y"""
+    return a.dot(y)
+
+
+def _linear_jac(t, y, a):
+    """Jacobian of a * y is a."""
+    return a
+
+
+def _linear_banded_jac(t, y, a):
+    """Banded Jacobian."""
+    ml, mu = _band_count(a)
+    bjac = [np.r_[[0] * k, np.diag(a, k)] for k in range(mu, 0, -1)]
+    bjac.append(np.diag(a))
+    for k in range(-1, -ml-1, -1):
+        bjac.append(np.r_[np.diag(a, k), [0] * (-k)])
+    return bjac
+
+
+def _solve_linear_sys(a, y0, tend=1, dt=0.1,
+                      solver=None, method='bdf', use_jac=True,
+                      with_jacobian=False, banded=False):
+    """Use scipy.integrate.ode to solve a linear system of ODEs.
+
+    a : square ndarray
+        Matrix of the linear system to be solved.
+    y0 : ndarray
+        Initial condition
+    tend : float
+        Stop time.
+    dt : float
+        Step size of the output.
+    solver : str
+        If not None, this must be "vode", "lsoda" or "zvode".
+    method : str
+        Either "bdf" or "adams".
+    use_jac : bool
+        Determines if the jacobian function is passed to ode().
+    with_jacobian : bool
+        Passed to ode.set_integrator().
+    banded : bool
+        Determines whether a banded or full jacobian is used.
+        If `banded` is True, `lband` and `uband` are determined by the
+        values in `a`.
+    """
+    if banded:
+        lband, uband = _band_count(a)
+    else:
+        lband = None
+        uband = None
+
+    if use_jac:
+        if banded:
+            r = ode(_linear_func, _linear_banded_jac)
+        else:
+            r = ode(_linear_func, _linear_jac)
+    else:
+        r = ode(_linear_func)
+
+    if solver is None:
+        if np.iscomplexobj(a):
+            solver = "zvode"
+        else:
+            solver = "vode"
+
+    r.set_integrator(solver,
+                     with_jacobian=with_jacobian,
+                     method=method,
+                     lband=lband, uband=uband,
+                     rtol=1e-9, atol=1e-10,
+                     )
+    t0 = 0
+    r.set_initial_value(y0, t0)
+    r.set_f_params(a)
+    r.set_jac_params(a)
+
+    t = [t0]
+    y = [y0]
+    while r.successful() and r.t < tend:
+        r.integrate(r.t + dt)
+        t.append(r.t)
+        y.append(r.y)
+
+    t = np.array(t)
+    y = np.array(y)
+    return t, y
+
+
+def _analytical_solution(a, y0, t):
+    """
+    Analytical solution to the linear differential equations dy/dt = a*y.
+
+    The solution is only valid if `a` is diagonalizable.
+
+    Returns a 2-D array with shape (len(t), len(y0)).
+    """
+    lam, v = np.linalg.eig(a)
+    c = np.linalg.solve(v, y0)
+    e = c * np.exp(lam * t.reshape(-1, 1))
+    sol = e.dot(v.T)
+    return sol
+
+
+@pytest.mark.thread_unsafe
+def test_banded_ode_solvers():
+    # Test the "lsoda", "vode" and "zvode" solvers of the `ode` class
+    # with a system that has a banded Jacobian matrix.
+
+    t_exact = np.linspace(0, 1.0, 5)
+
+    # --- Real arrays for testing the "lsoda" and "vode" solvers ---
+
+    # lband = 2, uband = 1:
+    a_real = np.array([[-0.6, 0.1, 0.0, 0.0, 0.0],
+                       [0.2, -0.5, 0.9, 0.0, 0.0],
+                       [0.1, 0.1, -0.4, 0.1, 0.0],
+                       [0.0, 0.3, -0.1, -0.9, -0.3],
+                       [0.0, 0.0, 0.1, 0.1, -0.7]])
+
+    # lband = 0, uband = 1:
+    a_real_upper = np.triu(a_real)
+
+    # lband = 2, uband = 0:
+    a_real_lower = np.tril(a_real)
+
+    # lband = 0, uband = 0:
+    a_real_diag = np.triu(a_real_lower)
+
+    real_matrices = [a_real, a_real_upper, a_real_lower, a_real_diag]
+    real_solutions = []
+
+    for a in real_matrices:
+        y0 = np.arange(1, a.shape[0] + 1)
+        y_exact = _analytical_solution(a, y0, t_exact)
+        real_solutions.append((y0, t_exact, y_exact))
+
+    def check_real(idx, solver, meth, use_jac, with_jac, banded):
+        a = real_matrices[idx]
+        y0, t_exact, y_exact = real_solutions[idx]
+        t, y = _solve_linear_sys(a, y0,
+                                 tend=t_exact[-1],
+                                 dt=t_exact[1] - t_exact[0],
+                                 solver=solver,
+                                 method=meth,
+                                 use_jac=use_jac,
+                                 with_jacobian=with_jac,
+                                 banded=banded)
+        assert_allclose(t, t_exact)
+        assert_allclose(y, y_exact)
+
+    for idx in range(len(real_matrices)):
+        p = [['vode', 'lsoda'],  # solver
+             ['bdf', 'adams'],   # method
+             [False, True],      # use_jac
+             [False, True],      # with_jacobian
+             [False, True]]      # banded
+        for solver, meth, use_jac, with_jac, banded in itertools.product(*p):
+            check_real(idx, solver, meth, use_jac, with_jac, banded)
+
+    # --- Complex arrays for testing the "zvode" solver ---
+
+    # complex, lband = 2, uband = 1:
+    a_complex = a_real - 0.5j * a_real
+
+    # complex, lband = 0, uband = 0:
+    a_complex_diag = np.diag(np.diag(a_complex))
+
+    complex_matrices = [a_complex, a_complex_diag]
+    complex_solutions = []
+
+    for a in complex_matrices:
+        y0 = np.arange(1, a.shape[0] + 1) + 1j
+        y_exact = _analytical_solution(a, y0, t_exact)
+        complex_solutions.append((y0, t_exact, y_exact))
+
+    def check_complex(idx, solver, meth, use_jac, with_jac, banded):
+        a = complex_matrices[idx]
+        y0, t_exact, y_exact = complex_solutions[idx]
+        t, y = _solve_linear_sys(a, y0,
+                                 tend=t_exact[-1],
+                                 dt=t_exact[1] - t_exact[0],
+                                 solver=solver,
+                                 method=meth,
+                                 use_jac=use_jac,
+                                 with_jacobian=with_jac,
+                                 banded=banded)
+        assert_allclose(t, t_exact)
+        assert_allclose(y, y_exact)
+
+    for idx in range(len(complex_matrices)):
+        p = [['bdf', 'adams'],   # method
+             [False, True],      # use_jac
+             [False, True],      # with_jacobian
+             [False, True]]      # banded
+        for meth, use_jac, with_jac, banded in itertools.product(*p):
+            check_complex(idx, "zvode", meth, use_jac, with_jac, banded)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ef9eb6ff0502e1113d6bea7ad1e0088633d3151
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py
@@ -0,0 +1,714 @@
+import sys
+
+try:
+    from StringIO import StringIO
+except ImportError:
+    from io import StringIO
+
+import numpy as np
+from numpy.testing import (assert_, assert_array_equal, assert_allclose,
+                           assert_equal)
+from pytest import raises as assert_raises
+
+from scipy.sparse import coo_matrix
+from scipy.special import erf
+from scipy.integrate._bvp import (modify_mesh, estimate_fun_jac,
+                                  estimate_bc_jac, compute_jac_indices,
+                                  construct_global_jac, solve_bvp)
+
+import pytest
+
+
+def exp_fun(x, y):
+    return np.vstack((y[1], y[0]))
+
+
+def exp_fun_jac(x, y):
+    df_dy = np.empty((2, 2, x.shape[0]))
+    df_dy[0, 0] = 0
+    df_dy[0, 1] = 1
+    df_dy[1, 0] = 1
+    df_dy[1, 1] = 0
+    return df_dy
+
+
+def exp_bc(ya, yb):
+    return np.hstack((ya[0] - 1, yb[0]))
+
+
+def exp_bc_complex(ya, yb):
+    return np.hstack((ya[0] - 1 - 1j, yb[0]))
+
+
+def exp_bc_jac(ya, yb):
+    dbc_dya = np.array([
+        [1, 0],
+        [0, 0]
+    ])
+    dbc_dyb = np.array([
+        [0, 0],
+        [1, 0]
+    ])
+    return dbc_dya, dbc_dyb
+
+
+def exp_sol(x):
+    return (np.exp(-x) - np.exp(x - 2)) / (1 - np.exp(-2))
+
+
+def sl_fun(x, y, p):
+    return np.vstack((y[1], -p[0]**2 * y[0]))
+
+
+def sl_fun_jac(x, y, p):
+    n, m = y.shape
+    df_dy = np.empty((n, 2, m))
+    df_dy[0, 0] = 0
+    df_dy[0, 1] = 1
+    df_dy[1, 0] = -p[0]**2
+    df_dy[1, 1] = 0
+
+    df_dp = np.empty((n, 1, m))
+    df_dp[0, 0] = 0
+    df_dp[1, 0] = -2 * p[0] * y[0]
+
+    return df_dy, df_dp
+
+
+def sl_bc(ya, yb, p):
+    return np.hstack((ya[0], yb[0], ya[1] - p[0]))
+
+
+def sl_bc_jac(ya, yb, p):
+    dbc_dya = np.zeros((3, 2))
+    dbc_dya[0, 0] = 1
+    dbc_dya[2, 1] = 1
+
+    dbc_dyb = np.zeros((3, 2))
+    dbc_dyb[1, 0] = 1
+
+    dbc_dp = np.zeros((3, 1))
+    dbc_dp[2, 0] = -1
+
+    return dbc_dya, dbc_dyb, dbc_dp
+
+
+def sl_sol(x, p):
+    return np.sin(p[0] * x)
+
+
+def emden_fun(x, y):
+    return np.vstack((y[1], -y[0]**5))
+
+
+def emden_fun_jac(x, y):
+    df_dy = np.empty((2, 2, x.shape[0]))
+    df_dy[0, 0] = 0
+    df_dy[0, 1] = 1
+    df_dy[1, 0] = -5 * y[0]**4
+    df_dy[1, 1] = 0
+    return df_dy
+
+
+def emden_bc(ya, yb):
+    return np.array([ya[1], yb[0] - (3/4)**0.5])
+
+
+def emden_bc_jac(ya, yb):
+    dbc_dya = np.array([
+        [0, 1],
+        [0, 0]
+    ])
+    dbc_dyb = np.array([
+        [0, 0],
+        [1, 0]
+    ])
+    return dbc_dya, dbc_dyb
+
+
+def emden_sol(x):
+    return (1 + x**2/3)**-0.5
+
+
+def undefined_fun(x, y):
+    return np.zeros_like(y)
+
+
+def undefined_bc(ya, yb):
+    return np.array([ya[0], yb[0] - 1])
+
+
+def big_fun(x, y):
+    f = np.zeros_like(y)
+    f[::2] = y[1::2]
+    return f
+
+
+def big_bc(ya, yb):
+    return np.hstack((ya[::2], yb[::2] - 1))
+
+
+def big_sol(x, n):
+    y = np.ones((2 * n, x.size))
+    y[::2] = x
+    return x
+
+
+def big_fun_with_parameters(x, y, p):
+    """ Big version of sl_fun, with two parameters.
+
+    The two differential equations represented by sl_fun are broadcast to the
+    number of rows of y, rotating between the parameters p[0] and p[1].
+    Here are the differential equations:
+
+        dy[0]/dt = y[1]
+        dy[1]/dt = -p[0]**2 * y[0]
+        dy[2]/dt = y[3]
+        dy[3]/dt = -p[1]**2 * y[2]
+        dy[4]/dt = y[5]
+        dy[5]/dt = -p[0]**2 * y[4]
+        dy[6]/dt = y[7]
+        dy[7]/dt = -p[1]**2 * y[6]
+        .
+        .
+        .
+
+    """
+    f = np.zeros_like(y)
+    f[::2] = y[1::2]
+    f[1::4] = -p[0]**2 * y[::4]
+    f[3::4] = -p[1]**2 * y[2::4]
+    return f
+
+
+def big_fun_with_parameters_jac(x, y, p):
+    # big version of sl_fun_jac, with two parameters
+    n, m = y.shape
+    df_dy = np.zeros((n, n, m))
+    df_dy[range(0, n, 2), range(1, n, 2)] = 1
+    df_dy[range(1, n, 4), range(0, n, 4)] = -p[0]**2
+    df_dy[range(3, n, 4), range(2, n, 4)] = -p[1]**2
+
+    df_dp = np.zeros((n, 2, m))
+    df_dp[range(1, n, 4), 0] = -2 * p[0] * y[range(0, n, 4)]
+    df_dp[range(3, n, 4), 1] = -2 * p[1] * y[range(2, n, 4)]
+
+    return df_dy, df_dp
+
+
+def big_bc_with_parameters(ya, yb, p):
+    # big version of sl_bc, with two parameters
+    return np.hstack((ya[::2], yb[::2], ya[1] - p[0], ya[3] - p[1]))
+
+
+def big_bc_with_parameters_jac(ya, yb, p):
+    # big version of sl_bc_jac, with two parameters
+    n = ya.shape[0]
+    dbc_dya = np.zeros((n + 2, n))
+    dbc_dyb = np.zeros((n + 2, n))
+
+    dbc_dya[range(n // 2), range(0, n, 2)] = 1
+    dbc_dyb[range(n // 2, n), range(0, n, 2)] = 1
+
+    dbc_dp = np.zeros((n + 2, 2))
+    dbc_dp[n, 0] = -1
+    dbc_dya[n, 1] = 1
+    dbc_dp[n + 1, 1] = -1
+    dbc_dya[n + 1, 3] = 1
+
+    return dbc_dya, dbc_dyb, dbc_dp
+
+
+def big_sol_with_parameters(x, p):
+    # big version of sl_sol, with two parameters
+    return np.vstack((np.sin(p[0] * x), np.sin(p[1] * x)))
+
+
+def shock_fun(x, y):
+    eps = 1e-3
+    return np.vstack((
+        y[1],
+        -(x * y[1] + eps * np.pi**2 * np.cos(np.pi * x) +
+          np.pi * x * np.sin(np.pi * x)) / eps
+    ))
+
+
+def shock_bc(ya, yb):
+    return np.array([ya[0] + 2, yb[0]])
+
+
+def shock_sol(x):
+    eps = 1e-3
+    k = np.sqrt(2 * eps)
+    return np.cos(np.pi * x) + erf(x / k) / erf(1 / k)
+
+
+def nonlin_bc_fun(x, y):
+    # laplace eq.
+    return np.stack([y[1], np.zeros_like(x)])
+
+
+def nonlin_bc_bc(ya, yb):
+    phiA, phipA = ya
+    phiC, phipC = yb
+
+    kappa, ioA, ioC, V, f = 1.64, 0.01, 1.0e-4, 0.5, 38.9
+
+    # Butler-Volmer Kinetics at Anode
+    hA = 0.0-phiA-0.0
+    iA = ioA * (np.exp(f*hA) - np.exp(-f*hA))
+    res0 = iA + kappa * phipA
+
+    # Butler-Volmer Kinetics at Cathode
+    hC = V - phiC - 1.0
+    iC = ioC * (np.exp(f*hC) - np.exp(-f*hC))
+    res1 = iC - kappa*phipC
+
+    return np.array([res0, res1])
+
+
+def nonlin_bc_sol(x):
+    return -0.13426436116763119 - 1.1308709 * x
+
+
+def test_modify_mesh():
+    x = np.array([0, 1, 3, 9], dtype=float)
+    x_new = modify_mesh(x, np.array([0]), np.array([2]))
+    assert_array_equal(x_new, np.array([0, 0.5, 1, 3, 5, 7, 9]))
+
+    x = np.array([-6, -3, 0, 3, 6], dtype=float)
+    x_new = modify_mesh(x, np.array([1], dtype=int), np.array([0, 2, 3]))
+    assert_array_equal(x_new, [-6, -5, -4, -3, -1.5, 0, 1, 2, 3, 4, 5, 6])
+
+
+def test_compute_fun_jac():
+    x = np.linspace(0, 1, 5)
+    y = np.empty((2, x.shape[0]))
+    y[0] = 0.01
+    y[1] = 0.02
+    p = np.array([])
+    df_dy, df_dp = estimate_fun_jac(lambda x, y, p: exp_fun(x, y), x, y, p)
+    df_dy_an = exp_fun_jac(x, y)
+    assert_allclose(df_dy, df_dy_an)
+    assert_(df_dp is None)
+
+    x = np.linspace(0, np.pi, 5)
+    y = np.empty((2, x.shape[0]))
+    y[0] = np.sin(x)
+    y[1] = np.cos(x)
+    p = np.array([1.0])
+    df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p)
+    df_dy_an, df_dp_an = sl_fun_jac(x, y, p)
+    assert_allclose(df_dy, df_dy_an)
+    assert_allclose(df_dp, df_dp_an)
+
+    x = np.linspace(0, 1, 10)
+    y = np.empty((2, x.shape[0]))
+    y[0] = (3/4)**0.5
+    y[1] = 1e-4
+    p = np.array([])
+    df_dy, df_dp = estimate_fun_jac(lambda x, y, p: emden_fun(x, y), x, y, p)
+    df_dy_an = emden_fun_jac(x, y)
+    assert_allclose(df_dy, df_dy_an)
+    assert_(df_dp is None)
+
+
+def test_compute_bc_jac():
+    ya = np.array([-1.0, 2])
+    yb = np.array([0.5, 3])
+    p = np.array([])
+    dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(
+        lambda ya, yb, p: exp_bc(ya, yb), ya, yb, p)
+    dbc_dya_an, dbc_dyb_an = exp_bc_jac(ya, yb)
+    assert_allclose(dbc_dya, dbc_dya_an)
+    assert_allclose(dbc_dyb, dbc_dyb_an)
+    assert_(dbc_dp is None)
+
+    ya = np.array([0.0, 1])
+    yb = np.array([0.0, -1])
+    p = np.array([0.5])
+    dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, ya, yb, p)
+    dbc_dya_an, dbc_dyb_an, dbc_dp_an = sl_bc_jac(ya, yb, p)
+    assert_allclose(dbc_dya, dbc_dya_an)
+    assert_allclose(dbc_dyb, dbc_dyb_an)
+    assert_allclose(dbc_dp, dbc_dp_an)
+
+    ya = np.array([0.5, 100])
+    yb = np.array([-1000, 10.5])
+    p = np.array([])
+    dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(
+        lambda ya, yb, p: emden_bc(ya, yb), ya, yb, p)
+    dbc_dya_an, dbc_dyb_an = emden_bc_jac(ya, yb)
+    assert_allclose(dbc_dya, dbc_dya_an)
+    assert_allclose(dbc_dyb, dbc_dyb_an)
+    assert_(dbc_dp is None)
+
+
+def test_compute_jac_indices():
+    n = 2
+    m = 4
+    k = 2
+    i, j = compute_jac_indices(n, m, k)
+    s = coo_matrix((np.ones_like(i), (i, j))).toarray()
+    s_true = np.array([
+        [1, 1, 1, 1, 0, 0, 0, 0, 1, 1],
+        [1, 1, 1, 1, 0, 0, 0, 0, 1, 1],
+        [0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
+        [0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
+        [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
+        [0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
+        [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
+        [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
+        [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
+        [1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
+    ])
+    assert_array_equal(s, s_true)
+
+
+def test_compute_global_jac():
+    n = 2
+    m = 5
+    k = 1
+    i_jac, j_jac = compute_jac_indices(2, 5, 1)
+    x = np.linspace(0, 1, 5)
+    h = np.diff(x)
+    y = np.vstack((np.sin(np.pi * x), np.pi * np.cos(np.pi * x)))
+    p = np.array([3.0])
+
+    f = sl_fun(x, y, p)
+
+    x_middle = x[:-1] + 0.5 * h
+    y_middle = 0.5 * (y[:, :-1] + y[:, 1:]) - h/8 * (f[:, 1:] - f[:, :-1])
+
+    df_dy, df_dp = sl_fun_jac(x, y, p)
+    df_dy_middle, df_dp_middle = sl_fun_jac(x_middle, y_middle, p)
+    dbc_dya, dbc_dyb, dbc_dp = sl_bc_jac(y[:, 0], y[:, -1], p)
+
+    J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle,
+                             df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp)
+    J = J.toarray()
+
+    def J_block(h, p):
+        return np.array([
+            [h**2*p**2/12 - 1, -0.5*h, -h**2*p**2/12 + 1, -0.5*h],
+            [0.5*h*p**2, h**2*p**2/12 - 1, 0.5*h*p**2, 1 - h**2*p**2/12]
+        ])
+
+    J_true = np.zeros((m * n + k, m * n + k))
+    for i in range(m - 1):
+        J_true[i * n: (i + 1) * n, i * n: (i + 2) * n] = J_block(h[i], p[0])
+
+    J_true[:(m - 1) * n:2, -1] = p * h**2/6 * (y[0, :-1] - y[0, 1:])
+    J_true[1:(m - 1) * n:2, -1] = p * (h * (y[0, :-1] + y[0, 1:]) +
+                                       h**2/6 * (y[1, :-1] - y[1, 1:]))
+
+    J_true[8, 0] = 1
+    J_true[9, 8] = 1
+    J_true[10, 1] = 1
+    J_true[10, 10] = -1
+
+    assert_allclose(J, J_true, rtol=1e-10)
+
+    df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p)
+    df_dy_middle, df_dp_middle = estimate_fun_jac(sl_fun, x_middle, y_middle, p)
+    dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, y[:, 0], y[:, -1], p)
+    J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle,
+                             df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp)
+    J = J.toarray()
+    assert_allclose(J, J_true, rtol=2e-8, atol=2e-8)
+
+
+def test_parameter_validation():
+    x = [0, 1, 0.5]
+    y = np.zeros((2, 3))
+    assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y)
+
+    x = np.linspace(0, 1, 5)
+    y = np.zeros((2, 4))
+    assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y)
+
+    def fun(x, y, p):
+        return exp_fun(x, y)
+    def bc(ya, yb, p):
+        return exp_bc(ya, yb)
+
+    y = np.zeros((2, x.shape[0]))
+    assert_raises(ValueError, solve_bvp, fun, bc, x, y, p=[1])
+
+    def wrong_shape_fun(x, y):
+        return np.zeros(3)
+
+    assert_raises(ValueError, solve_bvp, wrong_shape_fun, bc, x, y)
+
+    S = np.array([[0, 0]])
+    assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y, S=S)
+
+
+def test_no_params():
+    x = np.linspace(0, 1, 5)
+    x_test = np.linspace(0, 1, 100)
+    y = np.zeros((2, x.shape[0]))
+    for fun_jac in [None, exp_fun_jac]:
+        for bc_jac in [None, exp_bc_jac]:
+            sol = solve_bvp(exp_fun, exp_bc, x, y, fun_jac=fun_jac,
+                            bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            assert_equal(sol.x.size, 5)
+
+            sol_test = sol.sol(x_test)
+
+            assert_allclose(sol_test[0], exp_sol(x_test), atol=1e-5)
+
+            f_test = exp_fun(x_test, sol_test)
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(rel_res**2, axis=0)**0.5
+            assert_(np.all(norm_res < 1e-3))
+
+            assert_(np.all(sol.rms_residuals < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_with_params():
+    x = np.linspace(0, np.pi, 5)
+    x_test = np.linspace(0, np.pi, 100)
+    y = np.ones((2, x.shape[0]))
+
+    for fun_jac in [None, sl_fun_jac]:
+        for bc_jac in [None, sl_bc_jac]:
+            sol = solve_bvp(sl_fun, sl_bc, x, y, p=[0.5], fun_jac=fun_jac,
+                            bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            assert_(sol.x.size < 10)
+
+            assert_allclose(sol.p, [1], rtol=1e-4)
+
+            sol_test = sol.sol(x_test)
+
+            assert_allclose(sol_test[0], sl_sol(x_test, [1]),
+                            rtol=1e-4, atol=1e-4)
+
+            f_test = sl_fun(x_test, sol_test, [1])
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+            assert_(np.all(norm_res < 1e-3))
+
+            assert_(np.all(sol.rms_residuals < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_singular_term():
+    x = np.linspace(0, 1, 10)
+    x_test = np.linspace(0.05, 1, 100)
+    y = np.empty((2, 10))
+    y[0] = (3/4)**0.5
+    y[1] = 1e-4
+    S = np.array([[0, 0], [0, -2]])
+
+    for fun_jac in [None, emden_fun_jac]:
+        for bc_jac in [None, emden_bc_jac]:
+            sol = solve_bvp(emden_fun, emden_bc, x, y, S=S, fun_jac=fun_jac,
+                            bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            assert_equal(sol.x.size, 10)
+
+            sol_test = sol.sol(x_test)
+            assert_allclose(sol_test[0], emden_sol(x_test), atol=1e-5)
+
+            f_test = emden_fun(x_test, sol_test) + S.dot(sol_test) / x_test
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+
+            assert_(np.all(norm_res < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_complex():
+    # The test is essentially the same as test_no_params, but boundary
+    # conditions are turned into complex.
+    x = np.linspace(0, 1, 5)
+    x_test = np.linspace(0, 1, 100)
+    y = np.zeros((2, x.shape[0]), dtype=complex)
+    for fun_jac in [None, exp_fun_jac]:
+        for bc_jac in [None, exp_bc_jac]:
+            sol = solve_bvp(exp_fun, exp_bc_complex, x, y, fun_jac=fun_jac,
+                            bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            sol_test = sol.sol(x_test)
+
+            assert_allclose(sol_test[0].real, exp_sol(x_test), atol=1e-5)
+            assert_allclose(sol_test[0].imag, exp_sol(x_test), atol=1e-5)
+
+            f_test = exp_fun(x_test, sol_test)
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(np.real(rel_res * np.conj(rel_res)),
+                              axis=0) ** 0.5
+            assert_(np.all(norm_res < 1e-3))
+
+            assert_(np.all(sol.rms_residuals < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_failures():
+    x = np.linspace(0, 1, 2)
+    y = np.zeros((2, x.size))
+    res = solve_bvp(exp_fun, exp_bc, x, y, tol=1e-5, max_nodes=5)
+    assert_equal(res.status, 1)
+    assert_(not res.success)
+
+    x = np.linspace(0, 1, 5)
+    y = np.zeros((2, x.size))
+    res = solve_bvp(undefined_fun, undefined_bc, x, y)
+    assert_equal(res.status, 2)
+    assert_(not res.success)
+
+
+def test_big_problem():
+    n = 30
+    x = np.linspace(0, 1, 5)
+    y = np.zeros((2 * n, x.size))
+    sol = solve_bvp(big_fun, big_bc, x, y)
+
+    assert_equal(sol.status, 0)
+    assert_(sol.success)
+
+    sol_test = sol.sol(x)
+
+    assert_allclose(sol_test[0], big_sol(x, n))
+
+    f_test = big_fun(x, sol_test)
+    r = sol.sol(x, 1) - f_test
+    rel_res = r / (1 + np.abs(f_test))
+    norm_res = np.sum(np.real(rel_res * np.conj(rel_res)), axis=0) ** 0.5
+    assert_(np.all(norm_res < 1e-3))
+
+    assert_(np.all(sol.rms_residuals < 1e-3))
+    assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+    assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_big_problem_with_parameters():
+    n = 30
+    x = np.linspace(0, np.pi, 5)
+    x_test = np.linspace(0, np.pi, 100)
+    y = np.ones((2 * n, x.size))
+
+    for fun_jac in [None, big_fun_with_parameters_jac]:
+        for bc_jac in [None, big_bc_with_parameters_jac]:
+            sol = solve_bvp(big_fun_with_parameters, big_bc_with_parameters, x,
+                            y, p=[0.5, 0.5], fun_jac=fun_jac, bc_jac=bc_jac)
+
+            assert_equal(sol.status, 0)
+            assert_(sol.success)
+
+            assert_allclose(sol.p, [1, 1], rtol=1e-4)
+
+            sol_test = sol.sol(x_test)
+
+            for isol in range(0, n, 4):
+                assert_allclose(sol_test[isol],
+                                big_sol_with_parameters(x_test, [1, 1])[0],
+                                rtol=1e-4, atol=1e-4)
+                assert_allclose(sol_test[isol + 2],
+                                big_sol_with_parameters(x_test, [1, 1])[1],
+                                rtol=1e-4, atol=1e-4)
+
+            f_test = big_fun_with_parameters(x_test, sol_test, [1, 1])
+            r = sol.sol(x_test, 1) - f_test
+            rel_res = r / (1 + np.abs(f_test))
+            norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+            assert_(np.all(norm_res < 1e-3))
+
+            assert_(np.all(sol.rms_residuals < 1e-3))
+            assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+            assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_shock_layer():
+    x = np.linspace(-1, 1, 5)
+    x_test = np.linspace(-1, 1, 100)
+    y = np.zeros((2, x.size))
+    sol = solve_bvp(shock_fun, shock_bc, x, y)
+
+    assert_equal(sol.status, 0)
+    assert_(sol.success)
+
+    assert_(sol.x.size < 110)
+
+    sol_test = sol.sol(x_test)
+    assert_allclose(sol_test[0], shock_sol(x_test), rtol=1e-5, atol=1e-5)
+
+    f_test = shock_fun(x_test, sol_test)
+    r = sol.sol(x_test, 1) - f_test
+    rel_res = r / (1 + np.abs(f_test))
+    norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+
+    assert_(np.all(norm_res < 1e-3))
+    assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+    assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+def test_nonlin_bc():
+    x = np.linspace(0, 0.1, 5)
+    x_test = x
+    y = np.zeros([2, x.size])
+    sol = solve_bvp(nonlin_bc_fun, nonlin_bc_bc, x, y)
+
+    assert_equal(sol.status, 0)
+    assert_(sol.success)
+
+    assert_(sol.x.size < 8)
+
+    sol_test = sol.sol(x_test)
+    assert_allclose(sol_test[0], nonlin_bc_sol(x_test), rtol=1e-5, atol=1e-5)
+
+    f_test = nonlin_bc_fun(x_test, sol_test)
+    r = sol.sol(x_test, 1) - f_test
+    rel_res = r / (1 + np.abs(f_test))
+    norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
+
+    assert_(np.all(norm_res < 1e-3))
+    assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
+    assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
+
+
+@pytest.mark.thread_unsafe
+def test_verbose():
+    # Smoke test that checks the printing does something and does not crash
+    x = np.linspace(0, 1, 5)
+    y = np.zeros((2, x.shape[0]))
+    for verbose in [0, 1, 2]:
+        old_stdout = sys.stdout
+        sys.stdout = StringIO()
+        try:
+            sol = solve_bvp(exp_fun, exp_bc, x, y, verbose=verbose)
+            text = sys.stdout.getvalue()
+        finally:
+            sys.stdout = old_stdout
+
+        assert_(sol.success)
+        if verbose == 0:
+            assert_(not text, text)
+        if verbose >= 1:
+            assert_("Solved in" in text, text)
+        if verbose >= 2:
+            assert_("Max residual" in text, text)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_cubature.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_cubature.py
new file mode 100644
index 0000000000000000000000000000000000000000..899655c7631fbc86d06eb97c514761d4c882a632
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_cubature.py
@@ -0,0 +1,1389 @@
+import math
+import scipy
+import itertools
+
+import pytest
+
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_assert_close,
+    xp_size,
+    np_compat,
+    is_array_api_strict,
+)
+from scipy.conftest import array_api_compatible
+
+from scipy.integrate import cubature
+
+from scipy.integrate._rules import (
+    Rule, FixedRule,
+    NestedFixedRule,
+    GaussLegendreQuadrature, GaussKronrodQuadrature,
+    GenzMalikCubature,
+)
+
+from scipy.integrate._cubature import _InfiniteLimitsTransform
+
+pytestmark = [pytest.mark.usefixtures("skip_xp_backends"),]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+# The integrands ``genz_malik_1980_*`` come from the paper:
+#   A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
+#   numerical integration over an N-dimensional rectangular region, Journal of
+#   Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
+#   ISSN 0377-0427, https://doi.org/10.1016/0771-050X(80)90039-X.
+
+
+def basic_1d_integrand(x, n, xp):
+    x_reshaped = xp.reshape(x, (-1, 1, 1))
+    n_reshaped = xp.reshape(n, (1, -1, 1))
+
+    return x_reshaped**n_reshaped
+
+
+def basic_1d_integrand_exact(n, xp):
+    # Exact only for integration over interval [0, 2].
+    return xp.reshape(2**(n+1)/(n+1), (-1, 1))
+
+
+def basic_nd_integrand(x, n, xp):
+    return xp.reshape(xp.sum(x, axis=-1), (-1, 1))**xp.reshape(n, (1, -1))
+
+
+def basic_nd_integrand_exact(n, xp):
+    # Exact only for integration over interval [0, 2].
+    return (-2**(3+n) + 4**(2+n))/((1+n)*(2+n))
+
+
+def genz_malik_1980_f_1(x, r, alphas, xp):
+    r"""
+    .. math:: f_1(\mathbf x) = \cos\left(2\pi r + \sum^n_{i = 1}\alpha_i x_i\right)
+
+    .. code-block:: mathematica
+
+        genzMalik1980f1[x_List, r_, alphas_List] := Cos[2*Pi*r + Total[x*alphas]]
+    """
+
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return xp.cos(2*math.pi*r + xp.sum(alphas_reshaped * x_reshaped, axis=-1))
+
+
+def genz_malik_1980_f_1_exact(a, b, r, alphas, xp):
+    ndim = xp_size(a)
+    a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
+    b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+    return (
+        (-2)**ndim
+        * 1/xp.prod(alphas, axis=-1)
+        * xp.cos(2*math.pi*r + xp.sum(alphas * (a+b) * 0.5, axis=-1))
+        * xp.prod(xp.sin(alphas * (a-b)/2), axis=-1)
+    )
+
+
+def genz_malik_1980_f_1_random_args(rng, shape, xp):
+    r = xp.asarray(rng.random(shape[:-1]))
+    alphas = xp.asarray(rng.random(shape))
+
+    difficulty = 9
+    normalisation_factors = xp.sum(alphas, axis=-1)[..., None]
+    alphas = difficulty * alphas / normalisation_factors
+
+    return (r, alphas)
+
+
+def genz_malik_1980_f_2(x, alphas, betas, xp):
+    r"""
+    .. math:: f_2(\mathbf x) = \prod^n_{i = 1} (\alpha_i^2 + (x_i - \beta_i)^2)^{-1}
+
+    .. code-block:: mathematica
+
+        genzMalik1980f2[x_List, alphas_List, betas_List] :=
+            1/Times @@ ((alphas^2 + (x - betas)^2))
+    """
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    betas_reshaped = betas[None, ...]
+
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return 1/xp.prod(alphas_reshaped**2 + (x_reshaped-betas_reshaped)**2, axis=-1)
+
+
+def genz_malik_1980_f_2_exact(a, b, alphas, betas, xp):
+    ndim = xp_size(a)
+    a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
+    b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+    # `xp` is the unwrapped namespace, so `.atan` won't work for `xp = np` and np<2.
+    xp_test = array_namespace(a)
+
+    return (
+        (-1)**ndim * 1/xp.prod(alphas, axis=-1)
+        * xp.prod(
+            xp_test.atan((a - betas)/alphas) - xp_test.atan((b - betas)/alphas),
+            axis=-1,
+        )
+    )
+
+
+def genz_malik_1980_f_2_random_args(rng, shape, xp):
+    ndim = shape[-1]
+    alphas = xp.asarray(rng.random(shape))
+    betas = xp.asarray(rng.random(shape))
+
+    difficulty = 25.0
+    products = xp.prod(alphas**xp.asarray(-2.0), axis=-1)
+    normalisation_factors = (products**xp.asarray(1 / (2*ndim)))[..., None]
+    alphas = alphas * normalisation_factors * math.pow(difficulty, 1 / (2*ndim))
+
+    # Adjust alphas from distribution used in Genz and Malik 1980 since denominator
+    # is very small for high dimensions.
+    alphas *= 10
+
+    return alphas, betas
+
+
+def genz_malik_1980_f_3(x, alphas, xp):
+    r"""
+    .. math:: f_3(\mathbf x) = \exp\left(\sum^n_{i = 1} \alpha_i x_i\right)
+
+    .. code-block:: mathematica
+
+        genzMalik1980f3[x_List, alphas_List] := Exp[Dot[x, alphas]]
+    """
+
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return xp.exp(xp.sum(alphas_reshaped * x_reshaped, axis=-1))
+
+
+def genz_malik_1980_f_3_exact(a, b, alphas, xp):
+    ndim = xp_size(a)
+    a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
+    b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+    return (
+        (-1)**ndim * 1/xp.prod(alphas, axis=-1)
+        * xp.prod(xp.exp(alphas * a) - xp.exp(alphas * b), axis=-1)
+    )
+
+
+def genz_malik_1980_f_3_random_args(rng, shape, xp):
+    alphas = xp.asarray(rng.random(shape))
+    normalisation_factors = xp.sum(alphas, axis=-1)[..., None]
+    difficulty = 12.0
+    alphas = difficulty * alphas / normalisation_factors
+
+    return (alphas,)
+
+
+def genz_malik_1980_f_4(x, alphas, xp):
+    r"""
+    .. math:: f_4(\mathbf x) = \left(1 + \sum^n_{i = 1} \alpha_i x_i\right)^{-n-1}
+
+    .. code-block:: mathematica
+        genzMalik1980f4[x_List, alphas_List] :=
+            (1 + Dot[x, alphas])^(-Length[alphas] - 1)
+    """
+
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return (1 + xp.sum(alphas_reshaped * x_reshaped, axis=-1))**(-ndim-1)
+
+
+def genz_malik_1980_f_4_exact(a, b, alphas, xp):
+    ndim = xp_size(a)
+
+    def F(x):
+        x_reshaped = xp.reshape(x, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+        return (
+            (-1)**ndim/xp.prod(alphas, axis=-1)
+            / math.factorial(ndim)
+            / (1 + xp.sum(alphas * x_reshaped, axis=-1))
+        )
+
+    return _eval_indefinite_integral(F, a, b, xp)
+
+
+def _eval_indefinite_integral(F, a, b, xp):
+    """
+    Calculates a definite integral from points `a` to `b` by summing up over the corners
+    of the corresponding hyperrectangle.
+    """
+
+    ndim = xp_size(a)
+    points = xp.stack([a, b], axis=0)
+
+    out = 0
+    for ind in itertools.product(range(2), repeat=ndim):
+        selected_points = xp.asarray([points[i, j] for i, j in zip(ind, range(ndim))])
+        out += pow(-1, sum(ind) + ndim) * F(selected_points)
+
+    return out
+
+
+def genz_malik_1980_f_4_random_args(rng, shape, xp):
+    ndim = shape[-1]
+
+    alphas = xp.asarray(rng.random(shape))
+    normalisation_factors = xp.sum(alphas, axis=-1)[..., None]
+    difficulty = 14.0
+    alphas = (difficulty / ndim) * alphas / normalisation_factors
+
+    return (alphas,)
+
+
+def genz_malik_1980_f_5(x, alphas, betas, xp):
+    r"""
+    .. math::
+
+        f_5(\mathbf x) = \exp\left(-\sum^n_{i = 1} \alpha^2_i (x_i - \beta_i)^2\right)
+
+    .. code-block:: mathematica
+
+        genzMalik1980f5[x_List, alphas_List, betas_List] :=
+            Exp[-Total[alphas^2 * (x - betas)^2]]
+    """
+
+    npoints, ndim = x.shape[0], x.shape[-1]
+
+    alphas_reshaped = alphas[None, ...]
+    betas_reshaped = betas[None, ...]
+
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return xp.exp(
+        -xp.sum(alphas_reshaped**2 * (x_reshaped - betas_reshaped)**2, axis=-1)
+    )
+
+
+def genz_malik_1980_f_5_exact(a, b, alphas, betas, xp):
+    ndim = xp_size(a)
+    a = xp.reshape(a, (*([1]*(len(alphas.shape) - 1)), ndim))
+    b = xp.reshape(b, (*([1]*(len(alphas.shape) - 1)), ndim))
+
+    return (
+        (1/2)**ndim
+        * 1/xp.prod(alphas, axis=-1)
+        * (math.pi**(ndim/2))
+        * xp.prod(
+            scipy.special.erf(alphas * (betas - a))
+            + scipy.special.erf(alphas * (b - betas)),
+            axis=-1,
+        )
+    )
+
+
+def genz_malik_1980_f_5_random_args(rng, shape, xp):
+    alphas = xp.asarray(rng.random(shape))
+    betas = xp.asarray(rng.random(shape))
+
+    difficulty = 21.0
+    normalisation_factors = xp.sqrt(xp.sum(alphas**xp.asarray(2.0), axis=-1))[..., None]
+    alphas = alphas / normalisation_factors * math.sqrt(difficulty)
+
+    return alphas, betas
+
+
+def f_gaussian(x, alphas, xp):
+    r"""
+    .. math::
+
+        f(\mathbf x) = \exp\left(-\sum^n_{i = 1} (\alpha_i x_i)^2 \right)
+    """
+    npoints, ndim = x.shape[0], x.shape[-1]
+    alphas_reshaped = alphas[None, ...]
+    x_reshaped = xp.reshape(x, (npoints, *([1]*(len(alphas.shape) - 1)), ndim))
+
+    return xp.exp(-xp.sum((alphas_reshaped * x_reshaped)**2, axis=-1))
+
+
+def f_gaussian_exact(a, b, alphas, xp):
+    # Exact only when `a` and `b` are one of:
+    #   (-oo, oo), or
+    #   (0, oo), or
+    #   (-oo, 0)
+    # `alphas` can be arbitrary.
+
+    ndim = xp_size(a)
+    double_infinite_count = 0
+    semi_infinite_count = 0
+
+    for i in range(ndim):
+        if xp.isinf(a[i]) and xp.isinf(b[i]):   # doubly-infinite
+            double_infinite_count += 1
+        elif xp.isinf(a[i]) != xp.isinf(b[i]):  # exclusive or, so semi-infinite
+            semi_infinite_count += 1
+
+    return (math.sqrt(math.pi) ** ndim) / (
+        2**semi_infinite_count * xp.prod(alphas, axis=-1)
+    )
+
+
+def f_gaussian_random_args(rng, shape, xp):
+    alphas = xp.asarray(rng.random(shape))
+
+    # If alphas are very close to 0 this makes the problem very difficult due to large
+    # values of ``f``.
+    alphas *= 100
+
+    return (alphas,)
+
+
+def f_modified_gaussian(x_arr, n, xp):
+    r"""
+    .. math::
+
+        f(x, y, z, w) = x^n \sqrt{y} \exp(-y-z^2-w^2)
+    """
+    x, y, z, w = x_arr[:, 0], x_arr[:, 1], x_arr[:, 2], x_arr[:, 3]
+    res = (x ** n[:, None]) * xp.sqrt(y) * xp.exp(-y-z**2-w**2)
+
+    return res.T
+
+
+def f_modified_gaussian_exact(a, b, n, xp):
+    # Exact only for the limits
+    #   a = (0, 0, -oo, -oo)
+    #   b = (1, oo, oo, oo)
+    # but defined here as a function to match the format of the other integrands.
+    return 1/(2 + 2*n) * math.pi ** (3/2)
+
+
+def f_with_problematic_points(x_arr, points, xp):
+    """
+    This emulates a function with a list of singularities given by `points`.
+
+    If no `x_arr` are one of the `points`, then this function returns 1.
+    """
+
+    for point in points:
+        if xp.any(x_arr == point):
+            raise ValueError("called with a problematic point")
+
+    return xp.ones(x_arr.shape[0])
+
+
+@array_api_compatible
+class TestCubature:
+    """
+    Tests related to the interface of `cubature`.
+    """
+
+    @pytest.mark.parametrize("rule_str", [
+        "gauss-kronrod",
+        "genz-malik",
+        "gk21",
+        "gk15",
+    ])
+    def test_pass_str(self, rule_str, xp):
+        n = xp.arange(5, dtype=xp.float64)
+        a = xp.asarray([0, 0], dtype=xp.float64)
+        b = xp.asarray([2, 2], dtype=xp.float64)
+
+        res = cubature(basic_nd_integrand, a, b, rule=rule_str, args=(n, xp))
+
+        xp_assert_close(
+            res.estimate,
+            basic_nd_integrand_exact(n, xp),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    @skip_xp_backends(np_only=True,
+                      reason='array-likes only supported for NumPy backend')
+    def test_pass_array_like_not_array(self, xp):
+        n = np_compat.arange(5, dtype=np_compat.float64)
+        a = [0]
+        b = [2]
+
+        res = cubature(
+            basic_1d_integrand,
+            a,
+            b,
+            args=(n, xp)
+        )
+
+        xp_assert_close(
+            res.estimate,
+            basic_1d_integrand_exact(n, xp),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    def test_stops_after_max_subdivisions(self, xp):
+        a = xp.asarray([0])
+        b = xp.asarray([1])
+        rule = BadErrorRule()
+
+        res = cubature(
+            basic_1d_integrand,  # Any function would suffice
+            a,
+            b,
+            rule=rule,
+            max_subdivisions=10,
+            args=(xp.arange(5, dtype=xp.float64), xp),
+        )
+
+        assert res.subdivisions == 10
+        assert res.status == "not_converged"
+
+    def test_a_and_b_must_be_1d(self, xp):
+        a = xp.asarray([[0]], dtype=xp.float64)
+        b = xp.asarray([[1]], dtype=xp.float64)
+
+        with pytest.raises(Exception, match="`a` and `b` must be 1D arrays"):
+            cubature(basic_1d_integrand, a, b, args=(xp,))
+
+    def test_a_and_b_must_be_nonempty(self, xp):
+        a = xp.asarray([])
+        b = xp.asarray([])
+
+        with pytest.raises(Exception, match="`a` and `b` must be nonempty"):
+            cubature(basic_1d_integrand, a, b, args=(xp,))
+
+    def test_zero_width_limits(self, xp):
+        n = xp.arange(5, dtype=xp.float64)
+
+        a = xp.asarray([0], dtype=xp.float64)
+        b = xp.asarray([0], dtype=xp.float64)
+
+        res = cubature(
+            basic_1d_integrand,
+            a,
+            b,
+            args=(n, xp),
+        )
+
+        xp_assert_close(
+            res.estimate,
+            xp.asarray([[0], [0], [0], [0], [0]], dtype=xp.float64),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    def test_limits_other_way_around(self, xp):
+        n = xp.arange(5, dtype=xp.float64)
+
+        a = xp.asarray([2], dtype=xp.float64)
+        b = xp.asarray([0], dtype=xp.float64)
+
+        res = cubature(
+            basic_1d_integrand,
+            a,
+            b,
+            args=(n, xp),
+        )
+
+        xp_assert_close(
+            res.estimate,
+            -basic_1d_integrand_exact(n, xp),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    def test_result_dtype_promoted_correctly(self, xp):
+        result_dtype = cubature(
+            basic_1d_integrand,
+            xp.asarray([0], dtype=xp.float64),
+            xp.asarray([1], dtype=xp.float64),
+            points=[],
+            args=(xp.asarray([1], dtype=xp.float64), xp),
+        ).estimate.dtype
+
+        assert result_dtype == xp.float64
+
+        result_dtype = cubature(
+            basic_1d_integrand,
+            xp.asarray([0], dtype=xp.float32),
+            xp.asarray([1], dtype=xp.float32),
+            points=[],
+            args=(xp.asarray([1], dtype=xp.float32), xp),
+        ).estimate.dtype
+
+        assert result_dtype == xp.float32
+
+        result_dtype = cubature(
+            basic_1d_integrand,
+            xp.asarray([0], dtype=xp.float32),
+            xp.asarray([1], dtype=xp.float64),
+            points=[],
+            args=(xp.asarray([1], dtype=xp.float32), xp),
+        ).estimate.dtype
+
+        assert result_dtype == xp.float64
+
+
+@pytest.mark.parametrize("rtol", [1e-4])
+@pytest.mark.parametrize("atol", [1e-5])
+@pytest.mark.parametrize("rule", [
+    "gk15",
+    "gk21",
+    "genz-malik",
+])
+@array_api_compatible
+class TestCubatureProblems:
+    """
+    Tests that `cubature` gives the correct answer.
+    """
+
+    @pytest.mark.parametrize("problem", [
+        # -- f1 --
+        (
+            # Function to integrate, like `f(x, *args)`
+            genz_malik_1980_f_1,
+
+            # Exact solution, like `exact(a, b, *args)`
+            genz_malik_1980_f_1_exact,
+
+            # Coordinates of `a`
+            [0],
+
+            # Coordinates of `b`
+            [10],
+
+            # Arguments to pass to `f` and `exact`
+            (
+                1/4,
+                [5],
+            )
+        ),
+        (
+            genz_malik_1980_f_1,
+            genz_malik_1980_f_1_exact,
+            [0, 0],
+            [1, 1],
+            (
+                1/4,
+                [2, 4],
+            ),
+        ),
+        (
+            genz_malik_1980_f_1,
+            genz_malik_1980_f_1_exact,
+            [0, 0],
+            [5, 5],
+            (
+                1/2,
+                [2, 4],
+            )
+        ),
+        (
+            genz_malik_1980_f_1,
+            genz_malik_1980_f_1_exact,
+            [0, 0, 0],
+            [5, 5, 5],
+            (
+                1/2,
+                [1, 1, 1],
+            )
+        ),
+
+        # -- f2 --
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [-1],
+            [1],
+            (
+                [5],
+                [4],
+            )
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+
+            [0, 0],
+            [10, 50],
+            (
+                [-3, 3],
+                [-2, 2],
+            ),
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [0, 0, 0],
+            [1, 1, 1],
+            (
+                [1, 1, 1],
+                [1, 1, 1],
+            )
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [0, 0, 0],
+            [1, 1, 1],
+            (
+                [2, 3, 4],
+                [2, 3, 4],
+            )
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [-1, -1, -1],
+            [1, 1, 1],
+            (
+                [1, 1, 1],
+                [2, 2, 2],
+            )
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            [-1, -1, -1, -1],
+            [1, 1, 1, 1],
+            (
+                [1, 1, 1, 1],
+                [1, 1, 1, 1],
+            )
+        ),
+
+        # -- f3 --
+        (
+            genz_malik_1980_f_3,
+            genz_malik_1980_f_3_exact,
+            [-1],
+            [1],
+            (
+                [1/2],
+            ),
+        ),
+        (
+            genz_malik_1980_f_3,
+            genz_malik_1980_f_3_exact,
+            [0, -1],
+            [1, 1],
+            (
+                [5, 5],
+            ),
+        ),
+        (
+            genz_malik_1980_f_3,
+            genz_malik_1980_f_3_exact,
+            [-1, -1, -1],
+            [1, 1, 1],
+            (
+                [1, 1, 1],
+            ),
+        ),
+
+        # -- f4 --
+        (
+            genz_malik_1980_f_4,
+            genz_malik_1980_f_4_exact,
+            [0],
+            [2],
+            (
+                [1],
+            ),
+        ),
+        (
+            genz_malik_1980_f_4,
+            genz_malik_1980_f_4_exact,
+            [0, 0],
+            [2, 1],
+            ([1, 1],),
+        ),
+        (
+            genz_malik_1980_f_4,
+            genz_malik_1980_f_4_exact,
+            [0, 0, 0],
+            [1, 1, 1],
+            ([1, 1, 1],),
+        ),
+
+        # -- f5 --
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            [-1],
+            [1],
+            (
+                [-2],
+                [2],
+            ),
+        ),
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            [-1, -1],
+            [1, 1],
+            (
+                [2, 3],
+                [4, 5],
+            ),
+        ),
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            [-1, -1],
+            [1, 1],
+            (
+                [-1, 1],
+                [0, 0],
+            ),
+        ),
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            [-1, -1, -1],
+            [1, 1, 1],
+            (
+                [1, 1, 1],
+                [1, 1, 1],
+            ),
+        ),
+    ])
+    def test_scalar_output(self, problem, rule, rtol, atol, xp):
+        f, exact, a, b, args = problem
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+        args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args)
+
+        ndim = xp_size(a)
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            args=(*args, xp),
+        )
+
+        assert res.status == "converged"
+
+        est = res.estimate
+        exact_sol = exact(a, b, *args, xp)
+
+        xp_assert_close(
+            est,
+            exact_sol,
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}",
+        )
+
+    @pytest.mark.parametrize("problem", [
+        (
+            # Function to integrate, like `f(x, *args)`
+            genz_malik_1980_f_1,
+
+            # Exact solution, like `exact(a, b, *args)`
+            genz_malik_1980_f_1_exact,
+
+            # Function that generates random args of a certain shape.
+            genz_malik_1980_f_1_random_args,
+        ),
+        (
+            genz_malik_1980_f_2,
+            genz_malik_1980_f_2_exact,
+            genz_malik_1980_f_2_random_args,
+        ),
+        (
+            genz_malik_1980_f_3,
+            genz_malik_1980_f_3_exact,
+            genz_malik_1980_f_3_random_args
+        ),
+        (
+            genz_malik_1980_f_4,
+            genz_malik_1980_f_4_exact,
+            genz_malik_1980_f_4_random_args
+        ),
+        (
+            genz_malik_1980_f_5,
+            genz_malik_1980_f_5_exact,
+            genz_malik_1980_f_5_random_args,
+        ),
+    ])
+    @pytest.mark.parametrize("shape", [
+        (2,),
+        (3,),
+        (4,),
+        (1, 2),
+        (1, 3),
+        (1, 4),
+        (3, 2),
+        (3, 4, 2),
+        (2, 1, 3),
+    ])
+    def test_array_output(self, problem, rule, shape, rtol, atol, xp):
+        rng = np_compat.random.default_rng(1)
+        ndim = shape[-1]
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        if rule == "genz-malik" and ndim >= 5:
+            pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim")
+
+        f, exact, random_args = problem
+        args = random_args(rng, shape, xp)
+
+        a = xp.asarray([0] * ndim, dtype=xp.float64)
+        b = xp.asarray([1] * ndim, dtype=xp.float64)
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            args=(*args, xp),
+        )
+
+        est = res.estimate
+        exact_sol = exact(a, b, *args, xp)
+
+        xp_assert_close(
+            est,
+            exact_sol,
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}",
+        )
+
+        err_msg = (f"estimate_error={res.error}, "
+                   f"subdivisions= {res.subdivisions}, "
+                   f"true_error={xp.abs(res.estimate - exact_sol)}")
+        assert res.status == "converged", err_msg
+
+        assert res.estimate.shape == shape[:-1]
+
+    @pytest.mark.parametrize("problem", [
+        (
+            # Function to integrate
+            lambda x, xp: x,
+
+            # Exact value
+            [50.0],
+
+            # Coordinates of `a`
+            [0],
+
+            # Coordinates of `b`
+            [10],
+
+            # Points by which to split up the initial region
+            None,
+        ),
+        (
+            lambda x, xp: xp.sin(x)/x,
+            [2.551496047169878],  # si(1) + si(2),
+            [-1],
+            [2],
+            [
+                [0.0],
+            ],
+        ),
+        (
+            lambda x, xp: xp.ones((x.shape[0], 1)),
+            [1.0],
+            [0, 0, 0],
+            [1, 1, 1],
+            [
+                [0.5, 0.5, 0.5],
+            ],
+        ),
+        (
+            lambda x, xp: xp.ones((x.shape[0], 1)),
+            [1.0],
+            [0, 0, 0],
+            [1, 1, 1],
+            [
+                [0.25, 0.25, 0.25],
+                [0.5, 0.5, 0.5],
+            ],
+        ),
+        (
+            lambda x, xp: xp.ones((x.shape[0], 1)),
+            [1.0],
+            [0, 0, 0],
+            [1, 1, 1],
+            [
+                [0.1, 0.25, 0.5],
+                [0.25, 0.25, 0.25],
+                [0.5, 0.5, 0.5],
+            ],
+        )
+    ])
+    def test_break_points(self, problem, rule, rtol, atol, xp):
+        f, exact, a, b, points = problem
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+        exact = xp.asarray(exact, dtype=xp.float64)
+
+        if points is not None:
+            points = [xp.asarray(point, dtype=xp.float64) for point in points]
+
+        ndim = xp_size(a)
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        if rule == "genz-malik" and ndim >= 5:
+            pytest.mark.slow("Gauss-Kronrod is slow in >= 5 dim")
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            points=points,
+            args=(xp,),
+        )
+
+        xp_assert_close(
+            res.estimate,
+            exact,
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"estimate_error={res.error}, subdivisions={res.subdivisions}",
+            check_dtype=False,
+        )
+
+        err_msg = (f"estimate_error={res.error}, "
+                   f"subdivisions= {res.subdivisions}, "
+                   f"true_error={xp.abs(res.estimate - exact)}")
+        assert res.status == "converged", err_msg
+
+    @skip_xp_backends(
+        "jax.numpy",
+        reasons=["transforms make use of indexing assignment"],
+    )
+    @pytest.mark.parametrize("problem", [
+        (
+            # Function to integrate
+            f_gaussian,
+
+            # Exact solution
+            f_gaussian_exact,
+
+            # Arguments passed to f
+            f_gaussian_random_args,
+            (1, 1),
+
+            # Limits, have to match the shape of the arguments
+            [-math.inf],  # a
+            [math.inf],   # b
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (2, 2),
+            [-math.inf, -math.inf],
+            [math.inf, math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (1, 1),
+            [0],
+            [math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (1, 1),
+            [-math.inf],
+            [0],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (2, 2),
+            [0, 0],
+            [math.inf, math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (2, 2),
+            [0, -math.inf],
+            [math.inf, math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (1, 4),
+            [0, 0, -math.inf, -math.inf],
+            [math.inf, math.inf, math.inf, math.inf],
+        ),
+        (
+            f_gaussian,
+            f_gaussian_exact,
+            f_gaussian_random_args,
+            (1, 4),
+            [-math.inf, -math.inf, -math.inf, -math.inf],
+            [0, 0, math.inf, math.inf],
+        ),
+        (
+            lambda x, xp: 1/xp.prod(x, axis=-1)**2,
+
+            # Exact only for the below limits, not for general `a` and `b`.
+            lambda a, b, xp: xp.asarray(1/6, dtype=xp.float64),
+
+            # Arguments
+            lambda rng, shape, xp: tuple(),
+            tuple(),
+
+            [1, -math.inf, 3],
+            [math.inf, -2, math.inf],
+        ),
+
+        # This particular problem can be slow
+        pytest.param(
+            (
+                # f(x, y, z, w) = x^n * sqrt(y) * exp(-y-z**2-w**2) for n in [0,1,2,3]
+                f_modified_gaussian,
+
+                # This exact solution is for the below limits, not in general
+                f_modified_gaussian_exact,
+
+                # Constant arguments
+                lambda rng, shape, xp: (xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64),),
+                tuple(),
+
+                [0, 0, -math.inf, -math.inf],
+                [1, math.inf, math.inf, math.inf]
+            ),
+
+            marks=pytest.mark.xslow,
+        ),
+    ])
+    def test_infinite_limits(self, problem, rule, rtol, atol, xp):
+        rng = np_compat.random.default_rng(1)
+        f, exact, random_args_func, random_args_shape, a, b = problem
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+        args = random_args_func(rng, random_args_shape, xp)
+
+        ndim = xp_size(a)
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        if rule == "genz-malik" and ndim >= 4:
+            pytest.mark.slow("Genz-Malik is slow in >= 5 dim")
+
+        if rule == "genz-malik" and ndim >= 4 and is_array_api_strict(xp):
+            pytest.mark.xslow("Genz-Malik very slow for array_api_strict in >= 4 dim")
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            args=(*args, xp),
+        )
+
+        assert res.status == "converged"
+
+        xp_assert_close(
+            res.estimate,
+            exact(a, b, *args, xp),
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}",
+            check_0d=False,
+        )
+
+    @skip_xp_backends(
+        "jax.numpy",
+        reasons=["transforms make use of indexing assignment"],
+    )
+    @pytest.mark.parametrize("problem", [
+        (
+            # Function to integrate
+            lambda x, xp: (xp.sin(x) / x)**8,
+
+            # Exact value
+            [151/315 * math.pi],
+
+            # Limits
+            [-math.inf],
+            [math.inf],
+
+            # Breakpoints
+            [[0]],
+
+        ),
+        (
+            # Function to integrate
+            lambda x, xp: (xp.sin(x[:, 0]) / x[:, 0])**8,
+
+            # Exact value
+            151/315 * math.pi,
+
+            # Limits
+            [-math.inf, 0],
+            [math.inf, 1],
+
+            # Breakpoints
+            [[0, 0.5]],
+
+        )
+    ])
+    def test_infinite_limits_and_break_points(self, problem, rule, rtol, atol, xp):
+        f, exact, a, b, points = problem
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+        exact = xp.asarray(exact, dtype=xp.float64)
+
+        ndim = xp_size(a)
+
+        if rule == "genz-malik" and ndim < 2:
+            pytest.skip("Genz-Malik cubature does not support 1D integrals")
+
+        if points is not None:
+            points = [xp.asarray(point, dtype=xp.float64) for point in points]
+
+        res = cubature(
+            f,
+            a,
+            b,
+            rule=rule,
+            rtol=rtol,
+            atol=atol,
+            points=points,
+            args=(xp,),
+        )
+
+        assert res.status == "converged"
+
+        xp_assert_close(
+            res.estimate,
+            exact,
+            rtol=rtol,
+            atol=atol,
+            err_msg=f"error_estimate={res.error}, subdivisions={res.subdivisions}",
+            check_0d=False,
+        )
+
+
+@array_api_compatible
+class TestRules:
+    """
+    Tests related to the general Rule interface (currently private).
+    """
+
+    @pytest.mark.parametrize("problem", [
+        (
+            # 2D problem, 1D rule
+            [0, 0],
+            [1, 1],
+            GaussKronrodQuadrature,
+            (21,),
+        ),
+        (
+            # 1D problem, 2D rule
+            [0],
+            [1],
+            GenzMalikCubature,
+            (2,),
+        )
+    ])
+    def test_incompatible_dimension_raises_error(self, problem, xp):
+        a, b, quadrature, quadrature_args = problem
+        rule = quadrature(*quadrature_args, xp=xp)
+
+        a = xp.asarray(a, dtype=xp.float64)
+        b = xp.asarray(b, dtype=xp.float64)
+
+        with pytest.raises(Exception, match="incompatible dimension"):
+            rule.estimate(basic_1d_integrand, a, b, args=(xp,))
+
+    def test_estimate_with_base_classes_raise_error(self, xp):
+        a = xp.asarray([0])
+        b = xp.asarray([1])
+
+        for base_class in [Rule(), FixedRule()]:
+            with pytest.raises(Exception):
+                base_class.estimate(basic_1d_integrand, a, b, args=(xp,))
+
+
+@array_api_compatible
+class TestRulesQuadrature:
+    """
+    Tests underlying quadrature rules (ndim == 1).
+    """
+
+    @pytest.mark.parametrize(("rule", "rule_args"), [
+        (GaussLegendreQuadrature, (3,)),
+        (GaussLegendreQuadrature, (5,)),
+        (GaussLegendreQuadrature, (10,)),
+        (GaussKronrodQuadrature, (15,)),
+        (GaussKronrodQuadrature, (21,)),
+    ])
+    def test_base_1d_quadratures_simple(self, rule, rule_args, xp):
+        quadrature = rule(*rule_args, xp=xp)
+
+        n = xp.arange(5, dtype=xp.float64)
+
+        def f(x):
+            x_reshaped = xp.reshape(x, (-1, 1, 1))
+            n_reshaped = xp.reshape(n, (1, -1, 1))
+
+            return x_reshaped**n_reshaped
+
+        a = xp.asarray([0], dtype=xp.float64)
+        b = xp.asarray([2], dtype=xp.float64)
+
+        exact = xp.reshape(2**(n+1)/(n+1), (-1, 1))
+        estimate = quadrature.estimate(f, a, b)
+
+        xp_assert_close(
+            estimate,
+            exact,
+            rtol=1e-8,
+            atol=0,
+        )
+
+    @pytest.mark.parametrize(("rule_pair", "rule_pair_args"), [
+        ((GaussLegendreQuadrature, GaussLegendreQuadrature), (10, 5)),
+    ])
+    def test_base_1d_quadratures_error_from_difference(self, rule_pair, rule_pair_args,
+                                                       xp):
+        n = xp.arange(5, dtype=xp.float64)
+        a = xp.asarray([0], dtype=xp.float64)
+        b = xp.asarray([2], dtype=xp.float64)
+
+        higher = rule_pair[0](rule_pair_args[0], xp=xp)
+        lower = rule_pair[1](rule_pair_args[1], xp=xp)
+
+        rule = NestedFixedRule(higher, lower)
+        res = cubature(
+            basic_1d_integrand,
+            a, b,
+            rule=rule,
+            rtol=1e-8,
+            args=(n, xp),
+        )
+
+        xp_assert_close(
+            res.estimate,
+            basic_1d_integrand_exact(n, xp),
+            rtol=1e-8,
+            atol=0,
+        )
+
+    @pytest.mark.parametrize("quadrature", [
+        GaussLegendreQuadrature
+    ])
+    def test_one_point_fixed_quad_impossible(self, quadrature, xp):
+        with pytest.raises(Exception):
+            quadrature(1, xp=xp)
+
+
+@array_api_compatible
+class TestRulesCubature:
+    """
+    Tests underlying cubature rules (ndim >= 2).
+    """
+
+    @pytest.mark.parametrize("ndim", range(2, 11))
+    def test_genz_malik_func_evaluations(self, ndim, xp):
+        """
+        Tests that the number of function evaluations required for Genz-Malik cubature
+        matches the number in Genz and Malik 1980.
+        """
+
+        nodes, _ = GenzMalikCubature(ndim, xp=xp).nodes_and_weights
+
+        assert nodes.shape[0] == (2**ndim) + 2*ndim**2 + 2*ndim + 1
+
+    def test_genz_malik_1d_raises_error(self, xp):
+        with pytest.raises(Exception, match="only defined for ndim >= 2"):
+            GenzMalikCubature(1, xp=xp)
+
+
+@array_api_compatible
+@skip_xp_backends(
+    "jax.numpy",
+    reasons=["transforms make use of indexing assignment"],
+)
+class TestTransformations:
+    @pytest.mark.parametrize(("a", "b", "points"), [
+        (
+            [0, 1, -math.inf],
+            [1, math.inf, math.inf],
+            [
+                [1, 1, 1],
+                [0.5, 10, 10],
+            ]
+        )
+    ])
+    def test_infinite_limits_maintains_points(self, a, b, points, xp):
+        """
+        Test that break points are correctly mapped under the _InfiniteLimitsTransform
+        transformation.
+        """
+
+        xp_compat = array_namespace(xp.empty(0))
+        points = [xp.asarray(p, dtype=xp.float64) for p in points]
+
+        f_transformed = _InfiniteLimitsTransform(
+            # Bind `points` and `xp` argument in f
+            lambda x: f_with_problematic_points(x, points, xp_compat),
+            xp.asarray(a, dtype=xp_compat.float64),
+            xp.asarray(b, dtype=xp_compat.float64),
+            xp=xp_compat,
+        )
+
+        for point in points:
+            transformed_point = f_transformed.inv(xp_compat.reshape(point, (1, -1)))
+
+            with pytest.raises(Exception, match="called with a problematic point"):
+                f_transformed(transformed_point)
+
+
+class BadErrorRule(Rule):
+    """
+    A rule with fake high error so that cubature will keep on subdividing.
+    """
+
+    def estimate(self, f, a, b, args=()):
+        xp = array_namespace(a, b)
+        underlying = GaussLegendreQuadrature(10, xp=xp)
+
+        return underlying.estimate(f, a, b, args)
+
+    def estimate_error(self, f, a, b, args=()):
+        xp = array_namespace(a, b)
+        return xp.asarray(1e6, dtype=xp.float64)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_integrate.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_integrate.py
new file mode 100644
index 0000000000000000000000000000000000000000..44bfecdaac0f00b413538510c61dd1317a076261
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_integrate.py
@@ -0,0 +1,840 @@
+# Authors: Nils Wagner, Ed Schofield, Pauli Virtanen, John Travers
+"""
+Tests for numerical integration.
+"""
+import numpy as np
+from numpy import (arange, zeros, array, dot, sqrt, cos, sin, eye, pi, exp,
+                   allclose)
+
+from numpy.testing import (
+    assert_, assert_array_almost_equal,
+    assert_allclose, assert_array_equal, assert_equal, assert_warns)
+import pytest
+from pytest import raises as assert_raises
+from scipy.integrate import odeint, ode, complex_ode
+
+#------------------------------------------------------------------------------
+# Test ODE integrators
+#------------------------------------------------------------------------------
+
+
+class TestOdeint:
+    # Check integrate.odeint
+
+    def _do_problem(self, problem):
+        t = arange(0.0, problem.stop_t, 0.05)
+
+        # Basic case
+        z, infodict = odeint(problem.f, problem.z0, t, full_output=True)
+        assert_(problem.verify(z, t))
+
+        # Use tfirst=True
+        z, infodict = odeint(lambda t, y: problem.f(y, t), problem.z0, t,
+                             full_output=True, tfirst=True)
+        assert_(problem.verify(z, t))
+
+        if hasattr(problem, 'jac'):
+            # Use Dfun
+            z, infodict = odeint(problem.f, problem.z0, t, Dfun=problem.jac,
+                                 full_output=True)
+            assert_(problem.verify(z, t))
+
+            # Use Dfun and tfirst=True
+            z, infodict = odeint(lambda t, y: problem.f(y, t), problem.z0, t,
+                                 Dfun=lambda t, y: problem.jac(y, t),
+                                 full_output=True, tfirst=True)
+            assert_(problem.verify(z, t))
+
+    def test_odeint(self):
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            self._do_problem(problem)
+
+
+class TestODEClass:
+
+    ode_class = None   # Set in subclass.
+
+    def _do_problem(self, problem, integrator, method='adams'):
+
+        # ode has callback arguments in different order than odeint
+        def f(t, z):
+            return problem.f(z, t)
+        jac = None
+        if hasattr(problem, 'jac'):
+            def jac(t, z):
+                return problem.jac(z, t)
+
+        integrator_params = {}
+        if problem.lband is not None or problem.uband is not None:
+            integrator_params['uband'] = problem.uband
+            integrator_params['lband'] = problem.lband
+
+        ig = self.ode_class(f, jac)
+        ig.set_integrator(integrator,
+                          atol=problem.atol/10,
+                          rtol=problem.rtol/10,
+                          method=method,
+                          **integrator_params)
+
+        ig.set_initial_value(problem.z0, t=0.0)
+        z = ig.integrate(problem.stop_t)
+
+        assert_array_equal(z, ig.y)
+        assert_(ig.successful(), (problem, method))
+        assert_(ig.get_return_code() > 0, (problem, method))
+        assert_(problem.verify(array([z]), problem.stop_t), (problem, method))
+
+
+class TestOde(TestODEClass):
+
+    ode_class = ode
+
+    def test_vode(self):
+        # Check the vode solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            if not problem.stiff:
+                self._do_problem(problem, 'vode', 'adams')
+            self._do_problem(problem, 'vode', 'bdf')
+
+    def test_zvode(self):
+        # Check the zvode solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if not problem.stiff:
+                self._do_problem(problem, 'zvode', 'adams')
+            self._do_problem(problem, 'zvode', 'bdf')
+
+    def test_lsoda(self):
+        # Check the lsoda solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            self._do_problem(problem, 'lsoda')
+
+    def test_dopri5(self):
+        # Check the dopri5 solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            if problem.stiff:
+                continue
+            if hasattr(problem, 'jac'):
+                continue
+            self._do_problem(problem, 'dopri5')
+
+    def test_dop853(self):
+        # Check the dop853 solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.cmplx:
+                continue
+            if problem.stiff:
+                continue
+            if hasattr(problem, 'jac'):
+                continue
+            self._do_problem(problem, 'dop853')
+
+    @pytest.mark.thread_unsafe
+    def test_concurrent_fail(self):
+        for sol in ('vode', 'zvode', 'lsoda'):
+            def f(t, y):
+                return 1.0
+
+            r = ode(f).set_integrator(sol)
+            r.set_initial_value(0, 0)
+
+            r2 = ode(f).set_integrator(sol)
+            r2.set_initial_value(0, 0)
+
+            r.integrate(r.t + 0.1)
+            r2.integrate(r2.t + 0.1)
+
+            assert_raises(RuntimeError, r.integrate, r.t + 0.1)
+
+    def test_concurrent_ok(self, num_parallel_threads):
+        def f(t, y):
+            return 1.0
+
+        for k in range(3):
+            for sol in ('vode', 'zvode', 'lsoda', 'dopri5', 'dop853'):
+                if sol in {'vode', 'zvode', 'lsoda'} and num_parallel_threads > 1:
+                    continue
+                r = ode(f).set_integrator(sol)
+                r.set_initial_value(0, 0)
+
+                r2 = ode(f).set_integrator(sol)
+                r2.set_initial_value(0, 0)
+
+                r.integrate(r.t + 0.1)
+                r2.integrate(r2.t + 0.1)
+                r2.integrate(r2.t + 0.1)
+
+                assert_allclose(r.y, 0.1)
+                assert_allclose(r2.y, 0.2)
+
+            for sol in ('dopri5', 'dop853'):
+                r = ode(f).set_integrator(sol)
+                r.set_initial_value(0, 0)
+
+                r2 = ode(f).set_integrator(sol)
+                r2.set_initial_value(0, 0)
+
+                r.integrate(r.t + 0.1)
+                r.integrate(r.t + 0.1)
+                r2.integrate(r2.t + 0.1)
+                r.integrate(r.t + 0.1)
+                r2.integrate(r2.t + 0.1)
+
+                assert_allclose(r.y, 0.3)
+                assert_allclose(r2.y, 0.2)
+
+
+class TestComplexOde(TestODEClass):
+
+    ode_class = complex_ode
+
+    def test_vode(self):
+        # Check the vode solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if not problem.stiff:
+                self._do_problem(problem, 'vode', 'adams')
+            else:
+                self._do_problem(problem, 'vode', 'bdf')
+
+    def test_lsoda(self):
+
+        # Check the lsoda solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            self._do_problem(problem, 'lsoda')
+
+    def test_dopri5(self):
+        # Check the dopri5 solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.stiff:
+                continue
+            if hasattr(problem, 'jac'):
+                continue
+            self._do_problem(problem, 'dopri5')
+
+    def test_dop853(self):
+        # Check the dop853 solver
+        for problem_cls in PROBLEMS:
+            problem = problem_cls()
+            if problem.stiff:
+                continue
+            if hasattr(problem, 'jac'):
+                continue
+            self._do_problem(problem, 'dop853')
+
+
+class TestSolout:
+    # Check integrate.ode correctly handles solout for dopri5 and dop853
+    def _run_solout_test(self, integrator):
+        # Check correct usage of solout
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 10.0
+        y0 = [1.0, 2.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+
+        def rhs(t, y):
+            return [y[0] + y[1], -y[1]**2]
+
+        ig = ode(rhs).set_integrator(integrator)
+        ig.set_solout(solout)
+        ig.set_initial_value(y0, t0)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_equal(ts[-1], tend)
+
+    def test_solout(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_test(integrator)
+
+    def _run_solout_after_initial_test(self, integrator):
+        # Check if solout works even if it is set after the initial value.
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 10.0
+        y0 = [1.0, 2.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+
+        def rhs(t, y):
+            return [y[0] + y[1], -y[1]**2]
+
+        ig = ode(rhs).set_integrator(integrator)
+        ig.set_initial_value(y0, t0)
+        ig.set_solout(solout)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_equal(ts[-1], tend)
+
+    def test_solout_after_initial(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_after_initial_test(integrator)
+
+    def _run_solout_break_test(self, integrator):
+        # Check correct usage of stopping via solout
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 10.0
+        y0 = [1.0, 2.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+            if t > tend/2.0:
+                return -1
+
+        def rhs(t, y):
+            return [y[0] + y[1], -y[1]**2]
+
+        ig = ode(rhs).set_integrator(integrator)
+        ig.set_solout(solout)
+        ig.set_initial_value(y0, t0)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_(ts[-1] > tend/2.0)
+        assert_(ts[-1] < tend)
+
+    def test_solout_break(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_break_test(integrator)
+
+
+class TestComplexSolout:
+    # Check integrate.ode correctly handles solout for dopri5 and dop853
+    def _run_solout_test(self, integrator):
+        # Check correct usage of solout
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 20.0
+        y0 = [0.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+
+        def rhs(t, y):
+            return [1.0/(t - 10.0 - 1j)]
+
+        ig = complex_ode(rhs).set_integrator(integrator)
+        ig.set_solout(solout)
+        ig.set_initial_value(y0, t0)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_equal(ts[-1], tend)
+
+    def test_solout(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_test(integrator)
+
+    def _run_solout_break_test(self, integrator):
+        # Check correct usage of stopping via solout
+        ts = []
+        ys = []
+        t0 = 0.0
+        tend = 20.0
+        y0 = [0.0]
+
+        def solout(t, y):
+            ts.append(t)
+            ys.append(y.copy())
+            if t > tend/2.0:
+                return -1
+
+        def rhs(t, y):
+            return [1.0/(t - 10.0 - 1j)]
+
+        ig = complex_ode(rhs).set_integrator(integrator)
+        ig.set_solout(solout)
+        ig.set_initial_value(y0, t0)
+        ret = ig.integrate(tend)
+        assert_array_equal(ys[0], y0)
+        assert_array_equal(ys[-1], ret)
+        assert_equal(ts[0], t0)
+        assert_(ts[-1] > tend/2.0)
+        assert_(ts[-1] < tend)
+
+    def test_solout_break(self):
+        for integrator in ('dopri5', 'dop853'):
+            self._run_solout_break_test(integrator)
+
+
+#------------------------------------------------------------------------------
+# Test problems
+#------------------------------------------------------------------------------
+
+
+class ODE:
+    """
+    ODE problem
+    """
+    stiff = False
+    cmplx = False
+    stop_t = 1
+    z0 = []
+
+    lband = None
+    uband = None
+
+    atol = 1e-6
+    rtol = 1e-5
+
+
+class SimpleOscillator(ODE):
+    r"""
+    Free vibration of a simple oscillator::
+        m \ddot{u} + k u = 0, u(0) = u_0 \dot{u}(0) \dot{u}_0
+    Solution::
+        u(t) = u_0*cos(sqrt(k/m)*t)+\dot{u}_0*sin(sqrt(k/m)*t)/sqrt(k/m)
+    """
+    stop_t = 1 + 0.09
+    z0 = array([1.0, 0.1], float)
+
+    k = 4.0
+    m = 1.0
+
+    def f(self, z, t):
+        tmp = zeros((2, 2), float)
+        tmp[0, 1] = 1.0
+        tmp[1, 0] = -self.k / self.m
+        return dot(tmp, z)
+
+    def verify(self, zs, t):
+        omega = sqrt(self.k / self.m)
+        u = self.z0[0]*cos(omega*t) + self.z0[1]*sin(omega*t)/omega
+        return allclose(u, zs[:, 0], atol=self.atol, rtol=self.rtol)
+
+
+class ComplexExp(ODE):
+    r"""The equation :lm:`\dot u = i u`"""
+    stop_t = 1.23*pi
+    z0 = exp([1j, 2j, 3j, 4j, 5j])
+    cmplx = True
+
+    def f(self, z, t):
+        return 1j*z
+
+    def jac(self, z, t):
+        return 1j*eye(5)
+
+    def verify(self, zs, t):
+        u = self.z0 * exp(1j*t)
+        return allclose(u, zs, atol=self.atol, rtol=self.rtol)
+
+
+class Pi(ODE):
+    r"""Integrate 1/(t + 1j) from t=-10 to t=10"""
+    stop_t = 20
+    z0 = [0]
+    cmplx = True
+
+    def f(self, z, t):
+        return array([1./(t - 10 + 1j)])
+
+    def verify(self, zs, t):
+        u = -2j * np.arctan(10)
+        return allclose(u, zs[-1, :], atol=self.atol, rtol=self.rtol)
+
+
+class CoupledDecay(ODE):
+    r"""
+    3 coupled decays suited for banded treatment
+    (banded mode makes it necessary when N>>3)
+    """
+
+    stiff = True
+    stop_t = 0.5
+    z0 = [5.0, 7.0, 13.0]
+    lband = 1
+    uband = 0
+
+    lmbd = [0.17, 0.23, 0.29]  # fictitious decay constants
+
+    def f(self, z, t):
+        lmbd = self.lmbd
+        return np.array([-lmbd[0]*z[0],
+                         -lmbd[1]*z[1] + lmbd[0]*z[0],
+                         -lmbd[2]*z[2] + lmbd[1]*z[1]])
+
+    def jac(self, z, t):
+        # The full Jacobian is
+        #
+        #    [-lmbd[0]      0         0   ]
+        #    [ lmbd[0]  -lmbd[1]      0   ]
+        #    [    0      lmbd[1]  -lmbd[2]]
+        #
+        # The lower and upper bandwidths are lband=1 and uband=0, resp.
+        # The representation of this array in packed format is
+        #
+        #    [-lmbd[0]  -lmbd[1]  -lmbd[2]]
+        #    [ lmbd[0]   lmbd[1]      0   ]
+
+        lmbd = self.lmbd
+        j = np.zeros((self.lband + self.uband + 1, 3), order='F')
+
+        def set_j(ri, ci, val):
+            j[self.uband + ri - ci, ci] = val
+        set_j(0, 0, -lmbd[0])
+        set_j(1, 0, lmbd[0])
+        set_j(1, 1, -lmbd[1])
+        set_j(2, 1, lmbd[1])
+        set_j(2, 2, -lmbd[2])
+        return j
+
+    def verify(self, zs, t):
+        # Formulae derived by hand
+        lmbd = np.array(self.lmbd)
+        d10 = lmbd[1] - lmbd[0]
+        d21 = lmbd[2] - lmbd[1]
+        d20 = lmbd[2] - lmbd[0]
+        e0 = np.exp(-lmbd[0] * t)
+        e1 = np.exp(-lmbd[1] * t)
+        e2 = np.exp(-lmbd[2] * t)
+        u = np.vstack((
+            self.z0[0] * e0,
+            self.z0[1] * e1 + self.z0[0] * lmbd[0] / d10 * (e0 - e1),
+            self.z0[2] * e2 + self.z0[1] * lmbd[1] / d21 * (e1 - e2) +
+            lmbd[1] * lmbd[0] * self.z0[0] / d10 *
+            (1 / d20 * (e0 - e2) - 1 / d21 * (e1 - e2)))).transpose()
+        return allclose(u, zs, atol=self.atol, rtol=self.rtol)
+
+
+PROBLEMS = [SimpleOscillator, ComplexExp, Pi, CoupledDecay]
+
+#------------------------------------------------------------------------------
+
+
+def f(t, x):
+    dxdt = [x[1], -x[0]]
+    return dxdt
+
+
+def jac(t, x):
+    j = array([[0.0, 1.0],
+               [-1.0, 0.0]])
+    return j
+
+
+def f1(t, x, omega):
+    dxdt = [omega*x[1], -omega*x[0]]
+    return dxdt
+
+
+def jac1(t, x, omega):
+    j = array([[0.0, omega],
+               [-omega, 0.0]])
+    return j
+
+
+def f2(t, x, omega1, omega2):
+    dxdt = [omega1*x[1], -omega2*x[0]]
+    return dxdt
+
+
+def jac2(t, x, omega1, omega2):
+    j = array([[0.0, omega1],
+               [-omega2, 0.0]])
+    return j
+
+
+def fv(t, x, omega):
+    dxdt = [omega[0]*x[1], -omega[1]*x[0]]
+    return dxdt
+
+
+def jacv(t, x, omega):
+    j = array([[0.0, omega[0]],
+               [-omega[1], 0.0]])
+    return j
+
+
+class ODECheckParameterUse:
+    """Call an ode-class solver with several cases of parameter use."""
+
+    # solver_name must be set before tests can be run with this class.
+
+    # Set these in subclasses.
+    solver_name = ''
+    solver_uses_jac = False
+
+    def _get_solver(self, f, jac):
+        solver = ode(f, jac)
+        if self.solver_uses_jac:
+            solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7,
+                                  with_jacobian=self.solver_uses_jac)
+        else:
+            # XXX Shouldn't set_integrator *always* accept the keyword arg
+            # 'with_jacobian', and perhaps raise an exception if it is set
+            # to True if the solver can't actually use it?
+            solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7)
+        return solver
+
+    def _check_solver(self, solver):
+        ic = [1.0, 0.0]
+        solver.set_initial_value(ic, 0.0)
+        solver.integrate(pi)
+        assert_array_almost_equal(solver.y, [-1.0, 0.0])
+
+    def test_no_params(self):
+        solver = self._get_solver(f, jac)
+        self._check_solver(solver)
+
+    def test_one_scalar_param(self):
+        solver = self._get_solver(f1, jac1)
+        omega = 1.0
+        solver.set_f_params(omega)
+        if self.solver_uses_jac:
+            solver.set_jac_params(omega)
+        self._check_solver(solver)
+
+    def test_two_scalar_params(self):
+        solver = self._get_solver(f2, jac2)
+        omega1 = 1.0
+        omega2 = 1.0
+        solver.set_f_params(omega1, omega2)
+        if self.solver_uses_jac:
+            solver.set_jac_params(omega1, omega2)
+        self._check_solver(solver)
+
+    def test_vector_param(self):
+        solver = self._get_solver(fv, jacv)
+        omega = [1.0, 1.0]
+        solver.set_f_params(omega)
+        if self.solver_uses_jac:
+            solver.set_jac_params(omega)
+        self._check_solver(solver)
+
+    @pytest.mark.thread_unsafe
+    def test_warns_on_failure(self):
+        # Set nsteps small to ensure failure
+        solver = self._get_solver(f, jac)
+        solver.set_integrator(self.solver_name, nsteps=1)
+        ic = [1.0, 0.0]
+        solver.set_initial_value(ic, 0.0)
+        assert_warns(UserWarning, solver.integrate, pi)
+
+
+class TestDOPRI5CheckParameterUse(ODECheckParameterUse):
+    solver_name = 'dopri5'
+    solver_uses_jac = False
+
+
+class TestDOP853CheckParameterUse(ODECheckParameterUse):
+    solver_name = 'dop853'
+    solver_uses_jac = False
+
+
+class TestVODECheckParameterUse(ODECheckParameterUse):
+    solver_name = 'vode'
+    solver_uses_jac = True
+
+
+class TestZVODECheckParameterUse(ODECheckParameterUse):
+    solver_name = 'zvode'
+    solver_uses_jac = True
+
+
+class TestLSODACheckParameterUse(ODECheckParameterUse):
+    solver_name = 'lsoda'
+    solver_uses_jac = True
+
+
+def test_odeint_trivial_time():
+    # Test that odeint succeeds when given a single time point
+    # and full_output=True.  This is a regression test for gh-4282.
+    y0 = 1
+    t = [0]
+    y, info = odeint(lambda y, t: -y, y0, t, full_output=True)
+    assert_array_equal(y, np.array([[y0]]))
+
+
+def test_odeint_banded_jacobian():
+    # Test the use of the `Dfun`, `ml` and `mu` options of odeint.
+
+    def func(y, t, c):
+        return c.dot(y)
+
+    def jac(y, t, c):
+        return c
+
+    def jac_transpose(y, t, c):
+        return c.T.copy(order='C')
+
+    def bjac_rows(y, t, c):
+        jac = np.vstack((np.r_[0, np.diag(c, 1)],
+                            np.diag(c),
+                            np.r_[np.diag(c, -1), 0],
+                            np.r_[np.diag(c, -2), 0, 0]))
+        return jac
+
+    def bjac_cols(y, t, c):
+        return bjac_rows(y, t, c).T.copy(order='C')
+
+    c = array([[-205, 0.01, 0.00, 0.0],
+               [0.1, -2.50, 0.02, 0.0],
+               [1e-3, 0.01, -2.0, 0.01],
+               [0.00, 0.00, 0.1, -1.0]])
+
+    y0 = np.ones(4)
+    t = np.array([0, 5, 10, 100])
+
+    # Use the full Jacobian.
+    sol1, info1 = odeint(func, y0, t, args=(c,), full_output=True,
+                         atol=1e-13, rtol=1e-11, mxstep=10000,
+                         Dfun=jac)
+
+    # Use the transposed full Jacobian, with col_deriv=True.
+    sol2, info2 = odeint(func, y0, t, args=(c,), full_output=True,
+                         atol=1e-13, rtol=1e-11, mxstep=10000,
+                         Dfun=jac_transpose, col_deriv=True)
+
+    # Use the banded Jacobian.
+    sol3, info3 = odeint(func, y0, t, args=(c,), full_output=True,
+                         atol=1e-13, rtol=1e-11, mxstep=10000,
+                         Dfun=bjac_rows, ml=2, mu=1)
+
+    # Use the transposed banded Jacobian, with col_deriv=True.
+    sol4, info4 = odeint(func, y0, t, args=(c,), full_output=True,
+                         atol=1e-13, rtol=1e-11, mxstep=10000,
+                         Dfun=bjac_cols, ml=2, mu=1, col_deriv=True)
+
+    assert_allclose(sol1, sol2, err_msg="sol1 != sol2")
+    assert_allclose(sol1, sol3, atol=1e-12, err_msg="sol1 != sol3")
+    assert_allclose(sol3, sol4, err_msg="sol3 != sol4")
+
+    # Verify that the number of jacobian evaluations was the same for the
+    # calls of odeint with a full jacobian and with a banded jacobian. This is
+    # a regression test--there was a bug in the handling of banded jacobians
+    # that resulted in an incorrect jacobian matrix being passed to the LSODA
+    # code.  That would cause errors or excessive jacobian evaluations.
+    assert_array_equal(info1['nje'], info2['nje'])
+    assert_array_equal(info3['nje'], info4['nje'])
+
+    # Test the use of tfirst
+    sol1ty, info1ty = odeint(lambda t, y, c: func(y, t, c), y0, t, args=(c,),
+                             full_output=True, atol=1e-13, rtol=1e-11,
+                             mxstep=10000,
+                             Dfun=lambda t, y, c: jac(y, t, c), tfirst=True)
+    # The code should execute the exact same sequence of floating point
+    # calculations, so these should be exactly equal. We'll be safe and use
+    # a small tolerance.
+    assert_allclose(sol1, sol1ty, rtol=1e-12, err_msg="sol1 != sol1ty")
+
+
+def test_odeint_errors():
+    def sys1d(x, t):
+        return -100*x
+
+    def bad1(x, t):
+        return 1.0/0
+
+    def bad2(x, t):
+        return "foo"
+
+    def bad_jac1(x, t):
+        return 1.0/0
+
+    def bad_jac2(x, t):
+        return [["foo"]]
+
+    def sys2d(x, t):
+        return [-100*x[0], -0.1*x[1]]
+
+    def sys2d_bad_jac(x, t):
+        return [[1.0/0, 0], [0, -0.1]]
+
+    assert_raises(ZeroDivisionError, odeint, bad1, 1.0, [0, 1])
+    assert_raises(ValueError, odeint, bad2, 1.0, [0, 1])
+
+    assert_raises(ZeroDivisionError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac1)
+    assert_raises(ValueError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac2)
+
+    assert_raises(ZeroDivisionError, odeint, sys2d, [1.0, 1.0], [0, 1],
+                  Dfun=sys2d_bad_jac)
+
+
+def test_odeint_bad_shapes():
+    # Tests of some errors that can occur with odeint.
+
+    def badrhs(x, t):
+        return [1, -1]
+
+    def sys1(x, t):
+        return -100*x
+
+    def badjac(x, t):
+        return [[0, 0, 0]]
+
+    # y0 must be at most 1-d.
+    bad_y0 = [[0, 0], [0, 0]]
+    assert_raises(ValueError, odeint, sys1, bad_y0, [0, 1])
+
+    # t must be at most 1-d.
+    bad_t = [[0, 1], [2, 3]]
+    assert_raises(ValueError, odeint, sys1, [10.0], bad_t)
+
+    # y0 is 10, but badrhs(x, t) returns [1, -1].
+    assert_raises(RuntimeError, odeint, badrhs, 10, [0, 1])
+
+    # shape of array returned by badjac(x, t) is not correct.
+    assert_raises(RuntimeError, odeint, sys1, [10, 10], [0, 1], Dfun=badjac)
+
+
+def test_repeated_t_values():
+    """Regression test for gh-8217."""
+
+    def func(x, t):
+        return -0.25*x
+
+    t = np.zeros(10)
+    sol = odeint(func, [1.], t)
+    assert_array_equal(sol, np.ones((len(t), 1)))
+
+    tau = 4*np.log(2)
+    t = [0]*9 + [tau, 2*tau, 2*tau, 3*tau]
+    sol = odeint(func, [1, 2], t, rtol=1e-12, atol=1e-12)
+    expected_sol = np.array([[1.0, 2.0]]*9 +
+                            [[0.5, 1.0],
+                             [0.25, 0.5],
+                             [0.25, 0.5],
+                             [0.125, 0.25]])
+    assert_allclose(sol, expected_sol)
+
+    # Edge case: empty t sequence.
+    sol = odeint(func, [1.], [])
+    assert_array_equal(sol, np.array([], dtype=np.float64).reshape((0, 1)))
+
+    # t values are not monotonic.
+    assert_raises(ValueError, odeint, func, [1.], [0, 1, 0.5, 0])
+    assert_raises(ValueError, odeint, func, [1, 2, 3], [0, -1, -2, 3])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_odeint_jac.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_odeint_jac.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d28ccc93f4444f3f2e0b71da01c573d4f903dbc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_odeint_jac.py
@@ -0,0 +1,74 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+from scipy.integrate import odeint
+import scipy.integrate._test_odeint_banded as banded5x5
+
+
+def rhs(y, t):
+    dydt = np.zeros_like(y)
+    banded5x5.banded5x5(t, y, dydt)
+    return dydt
+
+
+def jac(y, t):
+    n = len(y)
+    jac = np.zeros((n, n), order='F')
+    banded5x5.banded5x5_jac(t, y, 1, 1, jac)
+    return jac
+
+
+def bjac(y, t):
+    n = len(y)
+    bjac = np.zeros((4, n), order='F')
+    banded5x5.banded5x5_bjac(t, y, 1, 1, bjac)
+    return bjac
+
+
+JACTYPE_FULL = 1
+JACTYPE_BANDED = 4
+
+
+def check_odeint(jactype):
+    if jactype == JACTYPE_FULL:
+        ml = None
+        mu = None
+        jacobian = jac
+    elif jactype == JACTYPE_BANDED:
+        ml = 2
+        mu = 1
+        jacobian = bjac
+    else:
+        raise ValueError(f"invalid jactype: {jactype!r}")
+
+    y0 = np.arange(1.0, 6.0)
+    # These tolerances must match the tolerances used in banded5x5.f.
+    rtol = 1e-11
+    atol = 1e-13
+    dt = 0.125
+    nsteps = 64
+    t = dt * np.arange(nsteps+1)
+
+    sol, info = odeint(rhs, y0, t,
+                       Dfun=jacobian, ml=ml, mu=mu,
+                       atol=atol, rtol=rtol, full_output=True)
+    yfinal = sol[-1]
+    odeint_nst = info['nst'][-1]
+    odeint_nfe = info['nfe'][-1]
+    odeint_nje = info['nje'][-1]
+
+    y1 = y0.copy()
+    # Pure Fortran solution. y1 is modified in-place.
+    nst, nfe, nje = banded5x5.banded5x5_solve(y1, nsteps, dt, jactype)
+
+    # It is likely that yfinal and y1 are *exactly* the same, but
+    # we'll be cautious and use assert_allclose.
+    assert_allclose(yfinal, y1, rtol=1e-12)
+    assert_equal((odeint_nst, odeint_nfe, odeint_nje), (nst, nfe, nje))
+
+
+def test_odeint_full_jac():
+    check_odeint(JACTYPE_FULL)
+
+
+def test_odeint_banded_jac():
+    check_odeint(JACTYPE_BANDED)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..e61a69df40f9b5975a6f02f40e6f72e34dbbf297
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py
@@ -0,0 +1,680 @@
+import sys
+import math
+import numpy as np
+from numpy import sqrt, cos, sin, arctan, exp, log, pi
+from numpy.testing import (assert_,
+        assert_allclose, assert_array_less, assert_almost_equal)
+import pytest
+
+from scipy.integrate import quad, dblquad, tplquad, nquad
+from scipy.special import erf, erfc
+from scipy._lib._ccallback import LowLevelCallable
+
+import ctypes
+import ctypes.util
+from scipy._lib._ccallback_c import sine_ctypes
+
+import scipy.integrate._test_multivariate as clib_test
+
+
+def assert_quad(value_and_err, tabled_value, error_tolerance=1.5e-8):
+    value, err = value_and_err
+    assert_allclose(value, tabled_value, atol=err, rtol=0)
+    if error_tolerance is not None:
+        assert_array_less(err, error_tolerance)
+
+
+def get_clib_test_routine(name, restype, *argtypes):
+    ptr = getattr(clib_test, name)
+    return ctypes.cast(ptr, ctypes.CFUNCTYPE(restype, *argtypes))
+
+
+class TestCtypesQuad:
+    def setup_method(self):
+        if sys.platform == 'win32':
+            files = ['api-ms-win-crt-math-l1-1-0.dll']
+        elif sys.platform == 'darwin':
+            files = ['libm.dylib']
+        else:
+            files = ['libm.so', 'libm.so.6']
+
+        for file in files:
+            try:
+                self.lib = ctypes.CDLL(file)
+                break
+            except OSError:
+                pass
+        else:
+            # This test doesn't work on some Linux platforms (Fedora for
+            # example) that put an ld script in libm.so - see gh-5370
+            pytest.skip("Ctypes can't import libm.so")
+
+        restype = ctypes.c_double
+        argtypes = (ctypes.c_double,)
+        for name in ['sin', 'cos', 'tan']:
+            func = getattr(self.lib, name)
+            func.restype = restype
+            func.argtypes = argtypes
+
+    def test_typical(self):
+        assert_quad(quad(self.lib.sin, 0, 5), quad(math.sin, 0, 5)[0])
+        assert_quad(quad(self.lib.cos, 0, 5), quad(math.cos, 0, 5)[0])
+        assert_quad(quad(self.lib.tan, 0, 1), quad(math.tan, 0, 1)[0])
+
+    def test_ctypes_sine(self):
+        quad(LowLevelCallable(sine_ctypes), 0, 1)
+
+    def test_ctypes_variants(self):
+        sin_0 = get_clib_test_routine('_sin_0', ctypes.c_double,
+                                      ctypes.c_double, ctypes.c_void_p)
+
+        sin_1 = get_clib_test_routine('_sin_1', ctypes.c_double,
+                                      ctypes.c_int, ctypes.POINTER(ctypes.c_double),
+                                      ctypes.c_void_p)
+
+        sin_2 = get_clib_test_routine('_sin_2', ctypes.c_double,
+                                      ctypes.c_double)
+
+        sin_3 = get_clib_test_routine('_sin_3', ctypes.c_double,
+                                      ctypes.c_int, ctypes.POINTER(ctypes.c_double))
+
+        sin_4 = get_clib_test_routine('_sin_3', ctypes.c_double,
+                                      ctypes.c_int, ctypes.c_double)
+
+        all_sigs = [sin_0, sin_1, sin_2, sin_3, sin_4]
+        legacy_sigs = [sin_2, sin_4]
+        legacy_only_sigs = [sin_4]
+
+        # LowLevelCallables work for new signatures
+        for j, func in enumerate(all_sigs):
+            callback = LowLevelCallable(func)
+            if func in legacy_only_sigs:
+                pytest.raises(ValueError, quad, callback, 0, pi)
+            else:
+                assert_allclose(quad(callback, 0, pi)[0], 2.0)
+
+        # Plain ctypes items work only for legacy signatures
+        for j, func in enumerate(legacy_sigs):
+            if func in legacy_sigs:
+                assert_allclose(quad(func, 0, pi)[0], 2.0)
+            else:
+                pytest.raises(ValueError, quad, func, 0, pi)
+
+
+class TestMultivariateCtypesQuad:
+    def setup_method(self):
+        restype = ctypes.c_double
+        argtypes = (ctypes.c_int, ctypes.c_double)
+        for name in ['_multivariate_typical', '_multivariate_indefinite',
+                     '_multivariate_sin']:
+            func = get_clib_test_routine(name, restype, *argtypes)
+            setattr(self, name, func)
+
+    def test_typical(self):
+        # 1) Typical function with two extra arguments:
+        assert_quad(quad(self._multivariate_typical, 0, pi, (2, 1.8)),
+                    0.30614353532540296487)
+
+    def test_indefinite(self):
+        # 2) Infinite integration limits --- Euler's constant
+        assert_quad(quad(self._multivariate_indefinite, 0, np.inf),
+                    0.577215664901532860606512)
+
+    def test_threadsafety(self):
+        # Ensure multivariate ctypes are threadsafe
+        def threadsafety(y):
+            return y + quad(self._multivariate_sin, 0, 1)[0]
+        assert_quad(quad(threadsafety, 0, 1), 0.9596976941318602)
+
+
+class TestQuad:
+    def test_typical(self):
+        # 1) Typical function with two extra arguments:
+        def myfunc(x, n, z):       # Bessel function integrand
+            return cos(n*x-z*sin(x))/pi
+        assert_quad(quad(myfunc, 0, pi, (2, 1.8)), 0.30614353532540296487)
+
+    def test_indefinite(self):
+        # 2) Infinite integration limits --- Euler's constant
+        def myfunc(x):           # Euler's constant integrand
+            return -exp(-x)*log(x)
+        assert_quad(quad(myfunc, 0, np.inf), 0.577215664901532860606512)
+
+    def test_singular(self):
+        # 3) Singular points in region of integration.
+        def myfunc(x):
+            if 0 < x < 2.5:
+                return sin(x)
+            elif 2.5 <= x <= 5.0:
+                return exp(-x)
+            else:
+                return 0.0
+
+        assert_quad(quad(myfunc, 0, 10, points=[2.5, 5.0]),
+                    1 - cos(2.5) + exp(-2.5) - exp(-5.0))
+
+    def test_sine_weighted_finite(self):
+        # 4) Sine weighted integral (finite limits)
+        def myfunc(x, a):
+            return exp(a*(x-1))
+
+        ome = 2.0**3.4
+        assert_quad(quad(myfunc, 0, 1, args=20, weight='sin', wvar=ome),
+                    (20*sin(ome)-ome*cos(ome)+ome*exp(-20))/(20**2 + ome**2))
+
+    def test_sine_weighted_infinite(self):
+        # 5) Sine weighted integral (infinite limits)
+        def myfunc(x, a):
+            return exp(-x*a)
+
+        a = 4.0
+        ome = 3.0
+        assert_quad(quad(myfunc, 0, np.inf, args=a, weight='sin', wvar=ome),
+                    ome/(a**2 + ome**2))
+
+    def test_cosine_weighted_infinite(self):
+        # 6) Cosine weighted integral (negative infinite limits)
+        def myfunc(x, a):
+            return exp(x*a)
+
+        a = 2.5
+        ome = 2.3
+        assert_quad(quad(myfunc, -np.inf, 0, args=a, weight='cos', wvar=ome),
+                    a/(a**2 + ome**2))
+
+    def test_algebraic_log_weight(self):
+        # 6) Algebraic-logarithmic weight.
+        def myfunc(x, a):
+            return 1/(1+x+2**(-a))
+
+        a = 1.5
+        assert_quad(quad(myfunc, -1, 1, args=a, weight='alg',
+                         wvar=(-0.5, -0.5)),
+                    pi/sqrt((1+2**(-a))**2 - 1))
+
+    def test_cauchypv_weight(self):
+        # 7) Cauchy prinicpal value weighting w(x) = 1/(x-c)
+        def myfunc(x, a):
+            return 2.0**(-a)/((x-1)**2+4.0**(-a))
+
+        a = 0.4
+        tabledValue = ((2.0**(-0.4)*log(1.5) -
+                        2.0**(-1.4)*log((4.0**(-a)+16) / (4.0**(-a)+1)) -
+                        arctan(2.0**(a+2)) -
+                        arctan(2.0**a)) /
+                       (4.0**(-a) + 1))
+        assert_quad(quad(myfunc, 0, 5, args=0.4, weight='cauchy', wvar=2.0),
+                    tabledValue, error_tolerance=1.9e-8)
+
+    def test_b_less_than_a(self):
+        def f(x, p, q):
+            return p * np.exp(-q*x)
+
+        val_1, err_1 = quad(f, 0, np.inf, args=(2, 3))
+        val_2, err_2 = quad(f, np.inf, 0, args=(2, 3))
+        assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
+
+    def test_b_less_than_a_2(self):
+        def f(x, s):
+            return np.exp(-x**2 / 2 / s) / np.sqrt(2.*s)
+
+        val_1, err_1 = quad(f, -np.inf, np.inf, args=(2,))
+        val_2, err_2 = quad(f, np.inf, -np.inf, args=(2,))
+        assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
+
+    def test_b_less_than_a_3(self):
+        def f(x):
+            return 1.0
+
+        val_1, err_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0))
+        val_2, err_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0))
+        assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
+
+    def test_b_less_than_a_full_output(self):
+        def f(x):
+            return 1.0
+
+        res_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0), full_output=True)
+        res_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0), full_output=True)
+        err = max(res_1[1], res_2[1])
+        assert_allclose(res_1[0], -res_2[0], atol=err)
+
+    def test_double_integral(self):
+        # 8) Double Integral test
+        def simpfunc(y, x):       # Note order of arguments.
+            return x+y
+
+        a, b = 1.0, 2.0
+        assert_quad(dblquad(simpfunc, a, b, lambda x: x, lambda x: 2*x),
+                    5/6.0 * (b**3.0-a**3.0))
+
+    def test_double_integral2(self):
+        def func(x0, x1, t0, t1):
+            return x0 + x1 + t0 + t1
+        def g(x):
+            return x
+        def h(x):
+            return 2 * x
+        args = 1, 2
+        assert_quad(dblquad(func, 1, 2, g, h, args=args),35./6 + 9*.5)
+
+    def test_double_integral3(self):
+        def func(x0, x1):
+            return x0 + x1 + 1 + 2
+        assert_quad(dblquad(func, 1, 2, 1, 2),6.)
+
+    @pytest.mark.parametrize(
+        "x_lower, x_upper, y_lower, y_upper, expected",
+        [
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, 0] for all n.
+            (-np.inf, 0, -np.inf, 0, np.pi / 4),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for each n (one at a time).
+            (-np.inf, -1, -np.inf, 0, np.pi / 4 * erfc(1)),
+            (-np.inf, 0, -np.inf, -1, np.pi / 4 * erfc(1)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for all n.
+            (-np.inf, -1, -np.inf, -1, np.pi / 4 * (erfc(1) ** 2)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for each n (one at a time).
+            (-np.inf, 1, -np.inf, 0, np.pi / 4 * (erf(1) + 1)),
+            (-np.inf, 0, -np.inf, 1, np.pi / 4 * (erf(1) + 1)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for all n.
+            (-np.inf, 1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) ** 2)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain Dx = [-inf, -1] and Dy = [-inf, 1].
+            (-np.inf, -1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain Dx = [-inf, 1] and Dy = [-inf, -1].
+            (-np.inf, 1, -np.inf, -1, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [0, inf] for all n.
+            (0, np.inf, 0, np.inf, np.pi / 4),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [1, inf] for each n (one at a time).
+            (1, np.inf, 0, np.inf, np.pi / 4 * erfc(1)),
+            (0, np.inf, 1, np.inf, np.pi / 4 * erfc(1)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [1, inf] for all n.
+            (1, np.inf, 1, np.inf, np.pi / 4 * (erfc(1) ** 2)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-1, inf] for each n (one at a time).
+            (-1, np.inf, 0, np.inf, np.pi / 4 * (erf(1) + 1)),
+            (0, np.inf, -1, np.inf, np.pi / 4 * (erf(1) + 1)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-1, inf] for all n.
+            (-1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) ** 2)),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain Dx = [-1, inf] and Dy = [1, inf].
+            (-1, np.inf, 1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain Dx = [1, inf] and Dy = [-1, inf].
+            (1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
+            # Multiple integration of a function in n = 2 variables: f(x, y, z)
+            # over domain D = [-inf, inf] for all n.
+            (-np.inf, np.inf, -np.inf, np.inf, np.pi)
+        ]
+    )
+    def test_double_integral_improper(
+            self, x_lower, x_upper, y_lower, y_upper, expected
+    ):
+        # The Gaussian Integral.
+        def f(x, y):
+            return np.exp(-x ** 2 - y ** 2)
+
+        assert_quad(
+            dblquad(f, x_lower, x_upper, y_lower, y_upper),
+            expected,
+            error_tolerance=3e-8
+        )
+
+    def test_triple_integral(self):
+        # 9) Triple Integral test
+        def simpfunc(z, y, x, t):      # Note order of arguments.
+            return (x+y+z)*t
+
+        a, b = 1.0, 2.0
+        assert_quad(tplquad(simpfunc, a, b,
+                            lambda x: x, lambda x: 2*x,
+                            lambda x, y: x - y, lambda x, y: x + y,
+                            (2.,)),
+                     2*8/3.0 * (b**4.0 - a**4.0))
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize(
+        "x_lower, x_upper, y_lower, y_upper, z_lower, z_upper, expected",
+        [
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, 0] for all n.
+            (-np.inf, 0, -np.inf, 0, -np.inf, 0, (np.pi ** (3 / 2)) / 8),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for each n (one at a time).
+            (-np.inf, -1, -np.inf, 0, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            (-np.inf, 0, -np.inf, -1, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            (-np.inf, 0, -np.inf, 0, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for each n (two at a time).
+            (-np.inf, -1, -np.inf, -1, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            (-np.inf, -1, -np.inf, 0, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            (-np.inf, 0, -np.inf, -1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, -1] for all n.
+            (-np.inf, -1, -np.inf, -1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = [-inf, -1] and Dy = Dz = [-inf, 1].
+            (-np.inf, -1, -np.inf, 1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dy = [-inf, -1] and Dz = [-inf, 1].
+            (-np.inf, -1, -np.inf, -1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dz = [-inf, -1] and Dy = [-inf, 1].
+            (-np.inf, -1, -np.inf, 1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = [-inf, 1] and Dy = Dz = [-inf, -1].
+            (-np.inf, 1, -np.inf, -1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dy = [-inf, 1] and Dz = [-inf, -1].
+            (-np.inf, 1, -np.inf, 1, -np.inf, -1,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dz = [-inf, 1] and Dy = [-inf, -1].
+            (-np.inf, 1, -np.inf, -1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for each n (one at a time).
+            (-np.inf, 1, -np.inf, 0, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            (-np.inf, 0, -np.inf, 1, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            (-np.inf, 0, -np.inf, 0, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for each n (two at a time).
+            (-np.inf, 1, -np.inf, 1, -np.inf, 0,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            (-np.inf, 1, -np.inf, 0, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            (-np.inf, 0, -np.inf, 1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, 1] for all n.
+            (-np.inf, 1, -np.inf, 1, -np.inf, 1,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [0, inf] for all n.
+            (0, np.inf, 0, np.inf, 0, np.inf, (np.pi ** (3 / 2)) / 8),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [1, inf] for each n (one at a time).
+            (1, np.inf, 0, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            (0, np.inf, 1, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            (0, np.inf, 0, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * erfc(1)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [1, inf] for each n (two at a time).
+            (1, np.inf, 1, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            (1, np.inf, 0, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            (0, np.inf, 1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [1, inf] for all n.
+            (1, np.inf, 1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-1, inf] for each n (one at a time).
+            (-1, np.inf, 0, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            (0, np.inf, -1, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            (0, np.inf, 0, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-1, inf] for each n (two at a time).
+            (-1, np.inf, -1, np.inf, 0, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            (-1, np.inf, 0, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            (0, np.inf, -1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-1, inf] for all n.
+            (-1, np.inf, -1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = [1, inf] and Dy = Dz = [-1, inf].
+            (1, np.inf, -1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dy = [1, inf] and Dz = [-1, inf].
+            (1, np.inf, 1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dz = [1, inf] and Dy = [-1, inf].
+            (1, np.inf, -1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = [-1, inf] and Dy = Dz = [1, inf].
+            (-1, np.inf, 1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dy = [-1, inf] and Dz = [1, inf].
+            (-1, np.inf, -1, np.inf, 1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain Dx = Dz = [-1, inf] and Dy = [1, inf].
+            (-1, np.inf, 1, np.inf, -1, np.inf,
+             (np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
+            # Multiple integration of a function in n = 3 variables: f(x, y, z)
+            # over domain D = [-inf, inf] for all n.
+            (-np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf,
+             np.pi ** (3 / 2)),
+        ],
+    )
+    def test_triple_integral_improper(
+            self,
+            x_lower,
+            x_upper,
+            y_lower,
+            y_upper,
+            z_lower,
+            z_upper,
+            expected
+    ):
+        # The Gaussian Integral.
+        def f(x, y, z):
+            return np.exp(-x ** 2 - y ** 2 - z ** 2)
+
+        assert_quad(
+            tplquad(f, x_lower, x_upper, y_lower, y_upper, z_lower, z_upper),
+            expected,
+            error_tolerance=6e-8
+        )
+
+    def test_complex(self):
+        def tfunc(x):
+            return np.exp(1j*x)
+
+        assert np.allclose(
+                    quad(tfunc, 0, np.pi/2, complex_func=True)[0],
+                    1+1j)
+
+        # We consider a divergent case in order to force quadpack
+        # to return an error message.  The output is compared
+        # against what is returned by explicit integration
+        # of the parts.
+        kwargs = {'a': 0, 'b': np.inf, 'full_output': True,
+                  'weight': 'cos', 'wvar': 1}
+        res_c = quad(tfunc, complex_func=True, **kwargs)
+        res_r = quad(lambda x: np.real(np.exp(1j*x)),
+                     complex_func=False,
+                     **kwargs)
+        res_i = quad(lambda x: np.imag(np.exp(1j*x)),
+                     complex_func=False,
+                     **kwargs)
+
+        np.testing.assert_equal(res_c[0], res_r[0] + 1j*res_i[0])
+        np.testing.assert_equal(res_c[1], res_r[1] + 1j*res_i[1])
+
+        assert len(res_c[2]['real']) == len(res_r[2:]) == 3
+        assert res_c[2]['real'][2] == res_r[4]
+        assert res_c[2]['real'][1] == res_r[3]
+        assert res_c[2]['real'][0]['lst'] == res_r[2]['lst']
+
+        assert len(res_c[2]['imag']) == len(res_i[2:]) == 1
+        assert res_c[2]['imag'][0]['lst'] == res_i[2]['lst']
+
+
+class TestNQuad:
+    @pytest.mark.fail_slow(5)
+    def test_fixed_limits(self):
+        def func1(x0, x1, x2, x3):
+            val = (x0**2 + x1*x2 - x3**3 + np.sin(x0) +
+                   (1 if (x0 - 0.2*x3 - 0.5 - 0.25*x1 > 0) else 0))
+            return val
+
+        def opts_basic(*args):
+            return {'points': [0.2*args[2] + 0.5 + 0.25*args[0]]}
+
+        res = nquad(func1, [[0, 1], [-1, 1], [.13, .8], [-.15, 1]],
+                    opts=[opts_basic, {}, {}, {}], full_output=True)
+        assert_quad(res[:-1], 1.5267454070738635)
+        assert_(res[-1]['neval'] > 0 and res[-1]['neval'] < 4e5)
+
+    @pytest.mark.fail_slow(5)
+    def test_variable_limits(self):
+        scale = .1
+
+        def func2(x0, x1, x2, x3, t0, t1):
+            val = (x0*x1*x3**2 + np.sin(x2) + 1 +
+                   (1 if x0 + t1*x1 - t0 > 0 else 0))
+            return val
+
+        def lim0(x1, x2, x3, t0, t1):
+            return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1,
+                    scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1]
+
+        def lim1(x2, x3, t0, t1):
+            return [scale * (t0*x2 + t1*x3) - 1,
+                    scale * (t0*x2 + t1*x3) + 1]
+
+        def lim2(x3, t0, t1):
+            return [scale * (x3 + t0**2*t1**3) - 1,
+                    scale * (x3 + t0**2*t1**3) + 1]
+
+        def lim3(t0, t1):
+            return [scale * (t0 + t1) - 1, scale * (t0 + t1) + 1]
+
+        def opts0(x1, x2, x3, t0, t1):
+            return {'points': [t0 - t1*x1]}
+
+        def opts1(x2, x3, t0, t1):
+            return {}
+
+        def opts2(x3, t0, t1):
+            return {}
+
+        def opts3(t0, t1):
+            return {}
+
+        res = nquad(func2, [lim0, lim1, lim2, lim3], args=(0, 0),
+                    opts=[opts0, opts1, opts2, opts3])
+        assert_quad(res, 25.066666666666663)
+
+    def test_square_separate_ranges_and_opts(self):
+        def f(y, x):
+            return 1.0
+
+        assert_quad(nquad(f, [[-1, 1], [-1, 1]], opts=[{}, {}]), 4.0)
+
+    def test_square_aliased_ranges_and_opts(self):
+        def f(y, x):
+            return 1.0
+
+        r = [-1, 1]
+        opt = {}
+        assert_quad(nquad(f, [r, r], opts=[opt, opt]), 4.0)
+
+    def test_square_separate_fn_ranges_and_opts(self):
+        def f(y, x):
+            return 1.0
+
+        def fn_range0(*args):
+            return (-1, 1)
+
+        def fn_range1(*args):
+            return (-1, 1)
+
+        def fn_opt0(*args):
+            return {}
+
+        def fn_opt1(*args):
+            return {}
+
+        ranges = [fn_range0, fn_range1]
+        opts = [fn_opt0, fn_opt1]
+        assert_quad(nquad(f, ranges, opts=opts), 4.0)
+
+    def test_square_aliased_fn_ranges_and_opts(self):
+        def f(y, x):
+            return 1.0
+
+        def fn_range(*args):
+            return (-1, 1)
+
+        def fn_opt(*args):
+            return {}
+
+        ranges = [fn_range, fn_range]
+        opts = [fn_opt, fn_opt]
+        assert_quad(nquad(f, ranges, opts=opts), 4.0)
+
+    def test_matching_quad(self):
+        def func(x):
+            return x**2 + 1
+
+        res, reserr = quad(func, 0, 4)
+        res2, reserr2 = nquad(func, ranges=[[0, 4]])
+        assert_almost_equal(res, res2)
+        assert_almost_equal(reserr, reserr2)
+
+    def test_matching_dblquad(self):
+        def func2d(x0, x1):
+            return x0**2 + x1**3 - x0 * x1 + 1
+
+        res, reserr = dblquad(func2d, -2, 2, lambda x: -3, lambda x: 3)
+        res2, reserr2 = nquad(func2d, [[-3, 3], (-2, 2)])
+        assert_almost_equal(res, res2)
+        assert_almost_equal(reserr, reserr2)
+
+    def test_matching_tplquad(self):
+        def func3d(x0, x1, x2, c0, c1):
+            return x0**2 + c0 * x1**3 - x0 * x1 + 1 + c1 * np.sin(x2)
+
+        res = tplquad(func3d, -1, 2, lambda x: -2, lambda x: 2,
+                      lambda x, y: -np.pi, lambda x, y: np.pi,
+                      args=(2, 3))
+        res2 = nquad(func3d, [[-np.pi, np.pi], [-2, 2], (-1, 2)], args=(2, 3))
+        assert_almost_equal(res, res2)
+
+    def test_dict_as_opts(self):
+        try:
+            nquad(lambda x, y: x * y, [[0, 1], [0, 1]], opts={'epsrel': 0.0001})
+        except TypeError:
+            assert False
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadrature.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadrature.py
new file mode 100644
index 0000000000000000000000000000000000000000..0198b53093a79c15d2fd644956cb0d2862ca92a2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_quadrature.py
@@ -0,0 +1,732 @@
+# mypy: disable-error-code="attr-defined"
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_almost_equal, assert_allclose
+from hypothesis import given
+import hypothesis.strategies as st
+import hypothesis.extra.numpy as hyp_num
+
+from scipy.integrate import (romb, newton_cotes,
+                             cumulative_trapezoid, trapezoid,
+                             quad, simpson, fixed_quad,
+                             qmc_quad, cumulative_simpson)
+from scipy.integrate._quadrature import _cumulative_simpson_unequal_intervals
+
+from scipy import stats, special, integrate
+from scipy.conftest import array_api_compatible, skip_xp_invalid_arg
+from scipy._lib._array_api_no_0d import xp_assert_close
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+class TestFixedQuad:
+    def test_scalar(self):
+        n = 4
+        expected = 1/(2*n)
+        got, _ = fixed_quad(lambda x: x**(2*n - 1), 0, 1, n=n)
+        # quadrature exact for this input
+        assert_allclose(got, expected, rtol=1e-12)
+
+    def test_vector(self):
+        n = 4
+        p = np.arange(1, 2*n)
+        expected = 1/(p + 1)
+        got, _ = fixed_quad(lambda x: x**p[:, None], 0, 1, n=n)
+        assert_allclose(got, expected, rtol=1e-12)
+
+
+class TestQuadrature:
+    def quad(self, x, a, b, args):
+        raise NotImplementedError
+
+    def test_romb(self):
+        assert_equal(romb(np.arange(17)), 128)
+
+    def test_romb_gh_3731(self):
+        # Check that romb makes maximal use of data points
+        x = np.arange(2**4+1)
+        y = np.cos(0.2*x)
+        val = romb(y)
+        val2, err = quad(lambda x: np.cos(0.2*x), x.min(), x.max())
+        assert_allclose(val, val2, rtol=1e-8, atol=0)
+
+    def test_newton_cotes(self):
+        """Test the first few degrees, for evenly spaced points."""
+        n = 1
+        wts, errcoff = newton_cotes(n, 1)
+        assert_equal(wts, n*np.array([0.5, 0.5]))
+        assert_almost_equal(errcoff, -n**3/12.0)
+
+        n = 2
+        wts, errcoff = newton_cotes(n, 1)
+        assert_almost_equal(wts, n*np.array([1.0, 4.0, 1.0])/6.0)
+        assert_almost_equal(errcoff, -n**5/2880.0)
+
+        n = 3
+        wts, errcoff = newton_cotes(n, 1)
+        assert_almost_equal(wts, n*np.array([1.0, 3.0, 3.0, 1.0])/8.0)
+        assert_almost_equal(errcoff, -n**5/6480.0)
+
+        n = 4
+        wts, errcoff = newton_cotes(n, 1)
+        assert_almost_equal(wts, n*np.array([7.0, 32.0, 12.0, 32.0, 7.0])/90.0)
+        assert_almost_equal(errcoff, -n**7/1935360.0)
+
+    def test_newton_cotes2(self):
+        """Test newton_cotes with points that are not evenly spaced."""
+
+        x = np.array([0.0, 1.5, 2.0])
+        y = x**2
+        wts, errcoff = newton_cotes(x)
+        exact_integral = 8.0/3
+        numeric_integral = np.dot(wts, y)
+        assert_almost_equal(numeric_integral, exact_integral)
+
+        x = np.array([0.0, 1.4, 2.1, 3.0])
+        y = x**2
+        wts, errcoff = newton_cotes(x)
+        exact_integral = 9.0
+        numeric_integral = np.dot(wts, y)
+        assert_almost_equal(numeric_integral, exact_integral)
+
+    def test_simpson(self):
+        y = np.arange(17)
+        assert_equal(simpson(y), 128)
+        assert_equal(simpson(y, dx=0.5), 64)
+        assert_equal(simpson(y, x=np.linspace(0, 4, 17)), 32)
+
+        # integral should be exactly 21
+        x = np.linspace(1, 4, 4)
+        def f(x):
+            return x**2
+
+        assert_allclose(simpson(f(x), x=x), 21.0)
+
+        # integral should be exactly 114
+        x = np.linspace(1, 7, 4)
+        assert_allclose(simpson(f(x), dx=2.0), 114)
+
+        # test multi-axis behaviour
+        a = np.arange(16).reshape(4, 4)
+        x = np.arange(64.).reshape(4, 4, 4)
+        y = f(x)
+        for i in range(3):
+            r = simpson(y, x=x, axis=i)
+            it = np.nditer(a, flags=['multi_index'])
+            for _ in it:
+                idx = list(it.multi_index)
+                idx.insert(i, slice(None))
+                integral = x[tuple(idx)][-1]**3 / 3 - x[tuple(idx)][0]**3 / 3
+                assert_allclose(r[it.multi_index], integral)
+
+        # test when integration axis only has two points
+        x = np.arange(16).reshape(8, 2)
+        y = f(x)
+        r = simpson(y, x=x, axis=-1)
+
+        integral = 0.5 * (y[:, 1] + y[:, 0]) * (x[:, 1] - x[:, 0])
+        assert_allclose(r, integral)
+
+        # odd points, test multi-axis behaviour
+        a = np.arange(25).reshape(5, 5)
+        x = np.arange(125).reshape(5, 5, 5)
+        y = f(x)
+        for i in range(3):
+            r = simpson(y, x=x, axis=i)
+            it = np.nditer(a, flags=['multi_index'])
+            for _ in it:
+                idx = list(it.multi_index)
+                idx.insert(i, slice(None))
+                integral = x[tuple(idx)][-1]**3 / 3 - x[tuple(idx)][0]**3 / 3
+                assert_allclose(r[it.multi_index], integral)
+
+        # Tests for checking base case
+        x = np.array([3])
+        y = np.power(x, 2)
+        assert_allclose(simpson(y, x=x, axis=0), 0.0)
+        assert_allclose(simpson(y, x=x, axis=-1), 0.0)
+
+        x = np.array([3, 3, 3, 3])
+        y = np.power(x, 2)
+        assert_allclose(simpson(y, x=x, axis=0), 0.0)
+        assert_allclose(simpson(y, x=x, axis=-1), 0.0)
+
+        x = np.array([[1, 2, 4, 8], [1, 2, 4, 8], [1, 2, 4, 8]])
+        y = np.power(x, 2)
+        zero_axis = [0.0, 0.0, 0.0, 0.0]
+        default_axis = [170 + 1/3] * 3   # 8**3 / 3 - 1/3
+        assert_allclose(simpson(y, x=x, axis=0), zero_axis)
+        # the following should be exact
+        assert_allclose(simpson(y, x=x, axis=-1), default_axis)
+
+        x = np.array([[1, 2, 4, 8], [1, 2, 4, 8], [1, 8, 16, 32]])
+        y = np.power(x, 2)
+        zero_axis = [0.0, 136.0, 1088.0, 8704.0]
+        default_axis = [170 + 1/3, 170 + 1/3, 32**3 / 3 - 1/3]
+        assert_allclose(simpson(y, x=x, axis=0), zero_axis)
+        assert_allclose(simpson(y, x=x, axis=-1), default_axis)
+
+
+    @pytest.mark.parametrize('droplast', [False, True])
+    def test_simpson_2d_integer_no_x(self, droplast):
+        # The inputs are 2d integer arrays.  The results should be
+        # identical to the results when the inputs are floating point.
+        y = np.array([[2, 2, 4, 4, 8, 8, -4, 5],
+                      [4, 4, 2, -4, 10, 22, -2, 10]])
+        if droplast:
+            y = y[:, :-1]
+        result = simpson(y, axis=-1)
+        expected = simpson(np.array(y, dtype=np.float64), axis=-1)
+        assert_equal(result, expected)
+
+
+class TestCumulative_trapezoid:
+    def test_1d(self):
+        x = np.linspace(-2, 2, num=5)
+        y = x
+        y_int = cumulative_trapezoid(y, x, initial=0)
+        y_expected = [0., -1.5, -2., -1.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, x, initial=None)
+        assert_allclose(y_int, y_expected[1:])
+
+    def test_y_nd_x_nd(self):
+        x = np.arange(3 * 2 * 4).reshape(3, 2, 4)
+        y = x
+        y_int = cumulative_trapezoid(y, x, initial=0)
+        y_expected = np.array([[[0., 0.5, 2., 4.5],
+                                [0., 4.5, 10., 16.5]],
+                               [[0., 8.5, 18., 28.5],
+                                [0., 12.5, 26., 40.5]],
+                               [[0., 16.5, 34., 52.5],
+                                [0., 20.5, 42., 64.5]]])
+
+        assert_allclose(y_int, y_expected)
+
+        # Try with all axes
+        shapes = [(2, 2, 4), (3, 1, 4), (3, 2, 3)]
+        for axis, shape in zip([0, 1, 2], shapes):
+            y_int = cumulative_trapezoid(y, x, initial=0, axis=axis)
+            assert_equal(y_int.shape, (3, 2, 4))
+            y_int = cumulative_trapezoid(y, x, initial=None, axis=axis)
+            assert_equal(y_int.shape, shape)
+
+    def test_y_nd_x_1d(self):
+        y = np.arange(3 * 2 * 4).reshape(3, 2, 4)
+        x = np.arange(4)**2
+        # Try with all axes
+        ys_expected = (
+            np.array([[[4., 5., 6., 7.],
+                       [8., 9., 10., 11.]],
+                      [[40., 44., 48., 52.],
+                       [56., 60., 64., 68.]]]),
+            np.array([[[2., 3., 4., 5.]],
+                      [[10., 11., 12., 13.]],
+                      [[18., 19., 20., 21.]]]),
+            np.array([[[0.5, 5., 17.5],
+                       [4.5, 21., 53.5]],
+                      [[8.5, 37., 89.5],
+                       [12.5, 53., 125.5]],
+                      [[16.5, 69., 161.5],
+                       [20.5, 85., 197.5]]]))
+
+        for axis, y_expected in zip([0, 1, 2], ys_expected):
+            y_int = cumulative_trapezoid(y, x=x[:y.shape[axis]], axis=axis,
+                                         initial=None)
+            assert_allclose(y_int, y_expected)
+
+    def test_x_none(self):
+        y = np.linspace(-2, 2, num=5)
+
+        y_int = cumulative_trapezoid(y)
+        y_expected = [-1.5, -2., -1.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, initial=0)
+        y_expected = [0, -1.5, -2., -1.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, dx=3)
+        y_expected = [-4.5, -6., -4.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+        y_int = cumulative_trapezoid(y, dx=3, initial=0)
+        y_expected = [0, -4.5, -6., -4.5, 0.]
+        assert_allclose(y_int, y_expected)
+
+    @pytest.mark.parametrize(
+        "initial", [1, 0.5]
+    )
+    def test_initial_error(self, initial):
+        """If initial is not None or 0, a ValueError is raised."""
+        y = np.linspace(0, 10, num=10)
+        with pytest.raises(ValueError, match="`initial`"):
+            cumulative_trapezoid(y, initial=initial)
+
+    def test_zero_len_y(self):
+        with pytest.raises(ValueError, match="At least one point is required"):
+            cumulative_trapezoid(y=[])
+
+
+@array_api_compatible
+class TestTrapezoid:
+    def test_simple(self, xp):
+        x = xp.arange(-10, 10, .1)
+        r = trapezoid(xp.exp(-.5 * x ** 2) / xp.sqrt(2 * xp.asarray(xp.pi)), dx=0.1)
+        # check integral of normal equals 1
+        xp_assert_close(r, xp.asarray(1.0))
+
+    @skip_xp_backends('jax.numpy',
+                      reasons=["JAX arrays do not support item assignment"])
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_ndim(self, xp):
+        x = xp.linspace(0, 1, 3)
+        y = xp.linspace(0, 2, 8)
+        z = xp.linspace(0, 3, 13)
+
+        wx = xp.ones_like(x) * (x[1] - x[0])
+        wx[0] /= 2
+        wx[-1] /= 2
+        wy = xp.ones_like(y) * (y[1] - y[0])
+        wy[0] /= 2
+        wy[-1] /= 2
+        wz = xp.ones_like(z) * (z[1] - z[0])
+        wz[0] /= 2
+        wz[-1] /= 2
+
+        q = x[:, None, None] + y[None,:, None] + z[None, None,:]
+
+        qx = xp.sum(q * wx[:, None, None], axis=0)
+        qy = xp.sum(q * wy[None, :, None], axis=1)
+        qz = xp.sum(q * wz[None, None, :], axis=2)
+
+        # n-d `x`
+        r = trapezoid(q, x=x[:, None, None], axis=0)
+        xp_assert_close(r, qx)
+        r = trapezoid(q, x=y[None,:, None], axis=1)
+        xp_assert_close(r, qy)
+        r = trapezoid(q, x=z[None, None,:], axis=2)
+        xp_assert_close(r, qz)
+
+        # 1-d `x`
+        r = trapezoid(q, x=x, axis=0)
+        xp_assert_close(r, qx)
+        r = trapezoid(q, x=y, axis=1)
+        xp_assert_close(r, qy)
+        r = trapezoid(q, x=z, axis=2)
+        xp_assert_close(r, qz)
+
+    @skip_xp_backends('jax.numpy',
+                      reasons=["JAX arrays do not support item assignment"])
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_gh21908(self, xp):
+        # extended testing for n-dim arrays
+        x = xp.reshape(xp.linspace(0, 29, 30), (3, 10))
+        y = xp.reshape(xp.linspace(0, 29, 30), (3, 10))
+
+        out0 = xp.linspace(200, 380, 10)
+        xp_assert_close(trapezoid(y, x=x, axis=0), out0)
+        xp_assert_close(trapezoid(y, x=xp.asarray([0, 10., 20.]), axis=0), out0)
+        # x needs to be broadcastable against y
+        xp_assert_close(
+            trapezoid(y, x=xp.asarray([0, 10., 20.])[:, None], axis=0),
+            out0
+        )
+        with pytest.raises(Exception):
+            # x is not broadcastable against y
+            trapezoid(y, x=xp.asarray([0, 10., 20.])[None, :], axis=0)
+
+        out1 = xp.asarray([ 40.5, 130.5, 220.5])
+        xp_assert_close(trapezoid(y, x=x, axis=1), out1)
+        xp_assert_close(
+            trapezoid(y, x=xp.linspace(0, 9, 10), axis=1),
+            out1
+        )
+
+    @skip_xp_invalid_arg
+    def test_masked(self, xp):
+        # Testing that masked arrays behave as if the function is 0 where
+        # masked
+        x = np.arange(5)
+        y = x * x
+        mask = x == 2
+        ym = np.ma.array(y, mask=mask)
+        r = 13.0  # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16))
+        assert_allclose(trapezoid(ym, x), r)
+
+        xm = np.ma.array(x, mask=mask)
+        assert_allclose(trapezoid(ym, xm), r)
+
+        xm = np.ma.array(x, mask=mask)
+        assert_allclose(trapezoid(y, xm), r)
+
+    @skip_xp_backends(np_only=True,
+                      reasons=['array-likes only supported for NumPy backend'])
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_array_like(self, xp):
+        x = list(range(5))
+        y = [t * t for t in x]
+        xarr = xp.asarray(x, dtype=xp.float64)
+        yarr = xp.asarray(y, dtype=xp.float64)
+        res = trapezoid(y, x)
+        resarr = trapezoid(yarr, xarr)
+        xp_assert_close(res, resarr)
+
+
+class TestQMCQuad:
+    @pytest.mark.thread_unsafe
+    def test_input_validation(self):
+        message = "`func` must be callable."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad("a duck", [0, 0], [1, 1])
+
+        message = "`func` must evaluate the integrand at points..."
+        with pytest.raises(ValueError, match=message):
+            qmc_quad(lambda: 1, [0, 0], [1, 1])
+
+        def func(x):
+            assert x.ndim == 1
+            return np.sum(x)
+        message = "Exception encountered when attempting vectorized call..."
+        with pytest.warns(UserWarning, match=message):
+            qmc_quad(func, [0, 0], [1, 1])
+
+        message = "`n_points` must be an integer."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, [0, 0], [1, 1], n_points=1024.5)
+
+        message = "`n_estimates` must be an integer."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, [0, 0], [1, 1], n_estimates=8.5)
+
+        message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, [0, 0], [1, 1], qrng="a duck")
+
+        message = "`qrng` must be initialized with dimensionality equal to "
+        with pytest.raises(ValueError, match=message):
+            qmc_quad(lambda x: 1, [0, 0], [1, 1], qrng=stats.qmc.Sobol(1))
+
+        message = r"`log` must be boolean \(`True` or `False`\)."
+        with pytest.raises(TypeError, match=message):
+            qmc_quad(lambda x: 1, [0, 0], [1, 1], log=10)
+
+    def basic_test(self, n_points=2**8, n_estimates=8, signs=None):
+        if signs is None:
+            signs = np.ones(2)
+        ndim = 2
+        mean = np.zeros(ndim)
+        cov = np.eye(ndim)
+
+        def func(x):
+            return stats.multivariate_normal.pdf(x.T, mean, cov)
+
+        rng = np.random.default_rng(2879434385674690281)
+        qrng = stats.qmc.Sobol(ndim, seed=rng)
+        a = np.zeros(ndim)
+        b = np.ones(ndim) * signs
+        res = qmc_quad(func, a, b, n_points=n_points,
+                       n_estimates=n_estimates, qrng=qrng)
+        ref = stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a)
+        atol = special.stdtrit(n_estimates-1, 0.995) * res.standard_error  # 99% CI
+        assert_allclose(res.integral, ref, atol=atol)
+        assert np.prod(signs)*res.integral > 0
+
+        rng = np.random.default_rng(2879434385674690281)
+        qrng = stats.qmc.Sobol(ndim, seed=rng)
+        logres = qmc_quad(lambda *args: np.log(func(*args)), a, b,
+                          n_points=n_points, n_estimates=n_estimates,
+                          log=True, qrng=qrng)
+        assert_allclose(np.exp(logres.integral), res.integral, rtol=1e-14)
+        assert np.imag(logres.integral) == (np.pi if np.prod(signs) < 0 else 0)
+        assert_allclose(np.exp(logres.standard_error),
+                        res.standard_error, rtol=1e-14, atol=1e-16)
+
+    @pytest.mark.parametrize("n_points", [2**8, 2**12])
+    @pytest.mark.parametrize("n_estimates", [8, 16])
+    def test_basic(self, n_points, n_estimates):
+        self.basic_test(n_points, n_estimates)
+
+    @pytest.mark.parametrize("signs", [[1, 1], [-1, -1], [-1, 1], [1, -1]])
+    def test_sign(self, signs):
+        self.basic_test(signs=signs)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize("log", [False, True])
+    def test_zero(self, log):
+        message = "A lower limit was equal to an upper limit, so"
+        with pytest.warns(UserWarning, match=message):
+            res = qmc_quad(lambda x: 1, [0, 0], [0, 1], log=log)
+        assert res.integral == (-np.inf if log else 0)
+        assert res.standard_error == 0
+
+    def test_flexible_input(self):
+        # check that qrng is not required
+        # also checks that for 1d problems, a and b can be scalars
+        def func(x):
+            return stats.norm.pdf(x, scale=2)
+
+        res = qmc_quad(func, 0, 1)
+        ref = stats.norm.cdf(1, scale=2) - stats.norm.cdf(0, scale=2)
+        assert_allclose(res.integral, ref, 1e-2)
+
+
+def cumulative_simpson_nd_reference(y, *, x=None, dx=None, initial=None, axis=-1):
+    # Use cumulative_trapezoid if length of y < 3
+    if y.shape[axis] < 3:
+        if initial is None:
+            return cumulative_trapezoid(y, x=x, dx=dx, axis=axis, initial=None)
+        else:
+            return initial + cumulative_trapezoid(y, x=x, dx=dx, axis=axis, initial=0)
+
+    # Ensure that working axis is last axis
+    y = np.moveaxis(y, axis, -1)
+    x = np.moveaxis(x, axis, -1) if np.ndim(x) > 1 else x
+    dx = np.moveaxis(dx, axis, -1) if np.ndim(dx) > 1 else dx
+    initial = np.moveaxis(initial, axis, -1) if np.ndim(initial) > 1 else initial
+
+    # If `x` is not present, create it from `dx`
+    n = y.shape[-1]
+    x = dx * np.arange(n) if dx is not None else x
+    # Similarly, if `initial` is not present, set it to 0
+    initial_was_none = initial is None
+    initial = 0 if initial_was_none else initial
+
+    # `np.apply_along_axis` accepts only one array, so concatenate arguments
+    x = np.broadcast_to(x, y.shape)
+    initial = np.broadcast_to(initial, y.shape[:-1] + (1,))
+    z = np.concatenate((y, x, initial), axis=-1)
+
+    # Use `np.apply_along_axis` to compute result
+    def f(z):
+        return cumulative_simpson(z[:n], x=z[n:2*n], initial=z[2*n:])
+    res = np.apply_along_axis(f, -1, z)
+
+    # Remove `initial` and undo axis move as needed
+    res = res[..., 1:] if initial_was_none else res
+    res = np.moveaxis(res, -1, axis)
+    return res
+
+
+class TestCumulativeSimpson:
+    x0 = np.arange(4)
+    y0 = x0**2
+
+    @pytest.mark.parametrize('use_dx', (False, True))
+    @pytest.mark.parametrize('use_initial', (False, True))
+    def test_1d(self, use_dx, use_initial):
+        # Test for exact agreement with polynomial of highest
+        # possible order (3 if `dx` is constant, 2 otherwise).
+        rng = np.random.default_rng(82456839535679456794)
+        n = 10
+
+        # Generate random polynomials and ground truth
+        # integral of appropriate order
+        order = 3 if use_dx else 2
+        dx = rng.random()
+        x = (np.sort(rng.random(n)) if order == 2
+             else np.arange(n)*dx + rng.random())
+        i = np.arange(order + 1)[:, np.newaxis]
+        c = rng.random(order + 1)[:, np.newaxis]
+        y = np.sum(c*x**i, axis=0)
+        Y = np.sum(c*x**(i + 1)/(i + 1), axis=0)
+        ref = Y if use_initial else (Y-Y[0])[1:]
+
+        # Integrate with `cumulative_simpson`
+        initial = Y[0] if use_initial else None
+        kwarg = {'dx': dx} if use_dx else {'x': x}
+        res = cumulative_simpson(y, **kwarg, initial=initial)
+
+        # Compare result against reference
+        if not use_dx:
+            assert_allclose(res, ref, rtol=2e-15)
+        else:
+            i0 = 0 if use_initial else 1
+            # all terms are "close"
+            assert_allclose(res, ref, rtol=0.0025)
+            # only even-interval terms are "exact"
+            assert_allclose(res[i0::2], ref[i0::2], rtol=2e-15)
+
+    @pytest.mark.parametrize('axis', np.arange(-3, 3))
+    @pytest.mark.parametrize('x_ndim', (1, 3))
+    @pytest.mark.parametrize('x_len', (1, 2, 7))
+    @pytest.mark.parametrize('i_ndim', (None, 0, 3,))
+    @pytest.mark.parametrize('dx', (None, True))
+    def test_nd(self, axis, x_ndim, x_len, i_ndim, dx):
+        # Test behavior of `cumulative_simpson` with N-D `y`
+        rng = np.random.default_rng(82456839535679456794)
+
+        # determine shapes
+        shape = [5, 6, x_len]
+        shape[axis], shape[-1] = shape[-1], shape[axis]
+        shape_len_1 = shape.copy()
+        shape_len_1[axis] = 1
+        i_shape = shape_len_1 if i_ndim == 3 else ()
+
+        # initialize arguments
+        y = rng.random(size=shape)
+        x, dx = None, None
+        if dx:
+            dx = rng.random(size=shape_len_1) if x_ndim > 1 else rng.random()
+        else:
+            x = (np.sort(rng.random(size=shape), axis=axis) if x_ndim > 1
+                 else np.sort(rng.random(size=shape[axis])))
+        initial = None if i_ndim is None else rng.random(size=i_shape)
+
+        # compare results
+        res = cumulative_simpson(y, x=x, dx=dx, initial=initial, axis=axis)
+        ref = cumulative_simpson_nd_reference(y, x=x, dx=dx, initial=initial, axis=axis)
+        np.testing.assert_allclose(res, ref, rtol=1e-15)
+
+    @pytest.mark.parametrize(('message', 'kwarg_update'), [
+        ("x must be strictly increasing", dict(x=[2, 2, 3, 4])),
+        ("x must be strictly increasing", dict(x=[x0, [2, 2, 4, 8]], y=[y0, y0])),
+        ("x must be strictly increasing", dict(x=[x0, x0, x0], y=[y0, y0, y0], axis=0)),
+        ("At least one point is required", dict(x=[], y=[])),
+        ("`axis=4` is not valid for `y` with `y.ndim=1`", dict(axis=4)),
+        ("shape of `x` must be the same as `y` or 1-D", dict(x=np.arange(5))),
+        ("`initial` must either be a scalar or...", dict(initial=np.arange(5))),
+        ("`dx` must either be a scalar or...", dict(x=None, dx=np.arange(5))),
+    ])
+    def test_simpson_exceptions(self, message, kwarg_update):
+        kwargs0 = dict(y=self.y0, x=self.x0, dx=None, initial=None, axis=-1)
+        with pytest.raises(ValueError, match=message):
+            cumulative_simpson(**dict(kwargs0, **kwarg_update))
+
+    def test_special_cases(self):
+        # Test special cases not checked elsewhere
+        rng = np.random.default_rng(82456839535679456794)
+        y = rng.random(size=10)
+        res = cumulative_simpson(y, dx=0)
+        assert_equal(res, 0)
+
+        # Should add tests of:
+        # - all elements of `x` identical
+        # These should work as they do for `simpson`
+
+    def _get_theoretical_diff_between_simps_and_cum_simps(self, y, x):
+        """`cumulative_simpson` and `simpson` can be tested against other to verify
+        they give consistent results. `simpson` will iteratively be called with
+        successively higher upper limits of integration. This function calculates
+        the theoretical correction required to `simpson` at even intervals to match
+        with `cumulative_simpson`.
+        """
+        d = np.diff(x, axis=-1)
+        sub_integrals_h1 = _cumulative_simpson_unequal_intervals(y, d)
+        sub_integrals_h2 = _cumulative_simpson_unequal_intervals(
+            y[..., ::-1], d[..., ::-1]
+        )[..., ::-1]
+
+        # Concatenate to build difference array
+        zeros_shape = (*y.shape[:-1], 1)
+        theoretical_difference = np.concatenate(
+            [
+                np.zeros(zeros_shape),
+                (sub_integrals_h1[..., 1:] - sub_integrals_h2[..., :-1]),
+                np.zeros(zeros_shape),
+            ],
+            axis=-1,
+        )
+        # Differences only expected at even intervals. Odd intervals will
+        # match exactly so there is no correction
+        theoretical_difference[..., 1::2] = 0.0
+        # Note: the first interval will not match from this correction as
+        # `simpson` uses the trapezoidal rule
+        return theoretical_difference
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.slow
+    @given(
+        y=hyp_num.arrays(
+            np.float64,
+            hyp_num.array_shapes(max_dims=4, min_side=3, max_side=10),
+            elements=st.floats(-10, 10, allow_nan=False).filter(lambda x: abs(x) > 1e-7)
+        )
+    )
+    def test_cumulative_simpson_against_simpson_with_default_dx(
+        self, y
+    ):
+        """Theoretically, the output of `cumulative_simpson` will be identical
+        to `simpson` at all even indices and in the last index. The first index
+        will not match as `simpson` uses the trapezoidal rule when there are only two
+        data points. Odd indices after the first index are shown to match with
+        a mathematically-derived correction."""
+        def simpson_reference(y):
+            return np.stack(
+                [simpson(y[..., :i], dx=1.0) for i in range(2, y.shape[-1]+1)], axis=-1,
+            )
+
+        res = cumulative_simpson(y, dx=1.0)
+        ref = simpson_reference(y)
+        theoretical_difference = self._get_theoretical_diff_between_simps_and_cum_simps(
+            y, x=np.arange(y.shape[-1])
+        )
+        np.testing.assert_allclose(
+            res[..., 1:], ref[..., 1:] + theoretical_difference[..., 1:], atol=1e-16
+        )
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.slow
+    @given(
+        y=hyp_num.arrays(
+            np.float64,
+            hyp_num.array_shapes(max_dims=4, min_side=3, max_side=10),
+            elements=st.floats(-10, 10, allow_nan=False).filter(lambda x: abs(x) > 1e-7)
+        )
+    )
+    def test_cumulative_simpson_against_simpson(
+        self, y
+    ):
+        """Theoretically, the output of `cumulative_simpson` will be identical
+        to `simpson` at all even indices and in the last index. The first index
+        will not match as `simpson` uses the trapezoidal rule when there are only two
+        data points. Odd indices after the first index are shown to match with
+        a mathematically-derived correction."""
+        interval = 10/(y.shape[-1] - 1)
+        x = np.linspace(0, 10, num=y.shape[-1])
+        x[1:] = x[1:] + 0.2*interval*np.random.uniform(-1, 1, len(x) - 1)
+
+        def simpson_reference(y, x):
+            return np.stack(
+                [simpson(y[..., :i], x=x[..., :i]) for i in range(2, y.shape[-1]+1)],
+                axis=-1,
+            )
+
+        res = cumulative_simpson(y, x=x)
+        ref = simpson_reference(y, x)
+        theoretical_difference = self._get_theoretical_diff_between_simps_and_cum_simps(
+            y, x
+        )
+        np.testing.assert_allclose(
+            res[..., 1:], ref[..., 1:] + theoretical_difference[..., 1:]
+        )
+
+class TestLebedev:
+    def test_input_validation(self):
+        # only certain rules are available
+        message = "Order n=-1 not available..."
+        with pytest.raises(NotImplementedError, match=message):
+            integrate.lebedev_rule(-1)
+
+    def test_quadrature(self):
+        # Test points/weights to integrate an example function
+
+        def f(x):
+            return np.exp(x[0])
+
+        x, w = integrate.lebedev_rule(15)
+        res = w @ f(x)
+        ref = 14.7680137457653  # lebedev_rule reference [3]
+        assert_allclose(res, ref, rtol=1e-14)
+        assert_allclose(np.sum(w), 4 * np.pi)
+
+    @pytest.mark.parametrize('order', list(range(3, 32, 2)) + list(range(35, 132, 6)))
+    def test_properties(self, order):
+        x, w = integrate.lebedev_rule(order)
+        # dispersion should be maximal; no clear spherical mean
+        with np.errstate(divide='ignore', invalid='ignore'):
+            res = stats.directional_stats(x.T, axis=0)
+            assert_allclose(res.mean_resultant_length, 0, atol=1e-15)
+        # weights should sum to 4*pi (surface area of unit sphere)
+        assert_allclose(np.sum(w), 4*np.pi)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_tanhsinh.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_tanhsinh.py
new file mode 100644
index 0000000000000000000000000000000000000000..15782ba13efcb16cf8982adf94b8b2f74be63a18
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/tests/test_tanhsinh.py
@@ -0,0 +1,1163 @@
+# mypy: disable-error-code="attr-defined"
+import os
+import pytest
+import math
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.conftest import array_api_compatible
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal
+from scipy._lib._array_api import array_namespace, xp_size, xp_ravel, xp_copy, is_numpy
+from scipy import special, stats
+from scipy.integrate import quad_vec, nsum, tanhsinh as _tanhsinh
+from scipy.integrate._tanhsinh import _pair_cache
+from scipy.stats._discrete_distns import _gen_harmonic_gt1
+
+
+def norm_pdf(x, xp=None):
+    xp = array_namespace(x) if xp is None else xp
+    return 1/(2*xp.pi)**0.5 * xp.exp(-x**2/2)
+
+def norm_logpdf(x, xp=None):
+    xp = array_namespace(x) if xp is None else xp
+    return -0.5*math.log(2*xp.pi) - x**2/2
+
+
+def _vectorize(xp):
+    # xp-compatible version of np.vectorize
+    # assumes arguments are all arrays of the same shape
+    def decorator(f):
+        def wrapped(*arg_arrays):
+            shape = arg_arrays[0].shape
+            arg_arrays = [xp_ravel(arg_array) for arg_array in arg_arrays]
+            res = []
+            for i in range(math.prod(shape)):
+                arg_scalars = [arg_array[i] for arg_array in arg_arrays]
+                res.append(f(*arg_scalars))
+            return res
+
+        return wrapped
+
+    return decorator
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends(
+    'array_api_strict', reason='Currently uses fancy indexing assignment.'
+)
+@pytest.mark.skip_xp_backends(
+    'jax.numpy', reason='JAX arrays do not support item assignment.'
+)
+class TestTanhSinh:
+
+    # Test problems from [1] Section 6
+    def f1(self, t):
+        return t * np.log(1 + t)
+
+    f1.ref = 0.25
+    f1.b = 1
+
+    def f2(self, t):
+        return t ** 2 * np.arctan(t)
+
+    f2.ref = (np.pi - 2 + 2 * np.log(2)) / 12
+    f2.b = 1
+
+    def f3(self, t):
+        return np.exp(t) * np.cos(t)
+
+    f3.ref = (np.exp(np.pi / 2) - 1) / 2
+    f3.b = np.pi / 2
+
+    def f4(self, t):
+        a = np.sqrt(2 + t ** 2)
+        return np.arctan(a) / ((1 + t ** 2) * a)
+
+    f4.ref = 5 * np.pi ** 2 / 96
+    f4.b = 1
+
+    def f5(self, t):
+        return np.sqrt(t) * np.log(t)
+
+    f5.ref = -4 / 9
+    f5.b = 1
+
+    def f6(self, t):
+        return np.sqrt(1 - t ** 2)
+
+    f6.ref = np.pi / 4
+    f6.b = 1
+
+    def f7(self, t):
+        return np.sqrt(t) / np.sqrt(1 - t ** 2)
+
+    f7.ref = 2 * np.sqrt(np.pi) * special.gamma(3 / 4) / special.gamma(1 / 4)
+    f7.b = 1
+
+    def f8(self, t):
+        return np.log(t) ** 2
+
+    f8.ref = 2
+    f8.b = 1
+
+    def f9(self, t):
+        return np.log(np.cos(t))
+
+    f9.ref = -np.pi * np.log(2) / 2
+    f9.b = np.pi / 2
+
+    def f10(self, t):
+        return np.sqrt(np.tan(t))
+
+    f10.ref = np.pi * np.sqrt(2) / 2
+    f10.b = np.pi / 2
+
+    def f11(self, t):
+        return 1 / (1 + t ** 2)
+
+    f11.ref = np.pi / 2
+    f11.b = np.inf
+
+    def f12(self, t):
+        return np.exp(-t) / np.sqrt(t)
+
+    f12.ref = np.sqrt(np.pi)
+    f12.b = np.inf
+
+    def f13(self, t):
+        return np.exp(-t ** 2 / 2)
+
+    f13.ref = np.sqrt(np.pi / 2)
+    f13.b = np.inf
+
+    def f14(self, t):
+        return np.exp(-t) * np.cos(t)
+
+    f14.ref = 0.5
+    f14.b = np.inf
+
+    def f15(self, t):
+        return np.sin(t) / t
+
+    f15.ref = np.pi / 2
+    f15.b = np.inf
+
+    def error(self, res, ref, log=False, xp=None):
+        xp = array_namespace(res, ref) if xp is None else xp
+        err = abs(res - ref)
+
+        if not log:
+            return err
+
+        with np.errstate(divide='ignore'):
+            return xp.log10(err)
+
+    def test_input_validation(self, xp):
+        f = self.f1
+
+        zero = xp.asarray(0)
+        f_b = xp.asarray(f.b)
+
+        message = '`f` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(42, zero, f_b)
+
+        message = '...must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, log=2)
+
+        message = '...must be real numbers.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, xp.asarray(1+1j), f_b)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, atol='ekki')
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, rtol=pytest)
+
+        message = '...must be non-negative and finite.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, rtol=-1)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, atol=xp.inf)
+
+        message = '...may not be positive infinity.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, rtol=xp.inf, log=True)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, atol=xp.inf, log=True)
+
+        message = '...must be integers.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, maxlevel=object())
+        # with pytest.raises(ValueError, match=message):  # unused for now
+        #     _tanhsinh(f, zero, f_b, maxfun=1+1j)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, minlevel="migratory coconut")
+
+        message = '...must be non-negative.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, maxlevel=-1)
+        # with pytest.raises(ValueError, match=message):  # unused for now
+        #     _tanhsinh(f, zero, f_b, maxfun=-1)
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, minlevel=-1)
+
+        message = '...must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, preserve_shape=2)
+
+        message = '...must be callable.'
+        with pytest.raises(ValueError, match=message):
+            _tanhsinh(f, zero, f_b, callback='elderberry')
+
+    @pytest.mark.parametrize("limits, ref", [
+        [(0, math.inf), 0.5],  # b infinite
+        [(-math.inf, 0), 0.5],  # a infinite
+        [(-math.inf, math.inf), 1.],  # a and b infinite
+        [(math.inf, -math.inf), -1.],  # flipped limits
+        [(1, -1), stats.norm.cdf(-1.) -  stats.norm.cdf(1.)],  # flipped limits
+    ])
+    def test_integral_transforms(self, limits, ref, xp):
+        # Check that the integral transforms are behaving for both normal and
+        # log integration
+        limits = [xp.asarray(limit) for limit in limits]
+        dtype = xp.asarray(float(limits[0])).dtype
+        ref = xp.asarray(ref, dtype=dtype)
+
+        res = _tanhsinh(norm_pdf, *limits)
+        xp_assert_close(res.integral, ref)
+
+        logres = _tanhsinh(norm_logpdf, *limits, log=True)
+        xp_assert_close(xp.exp(logres.integral), ref, check_dtype=False)
+        # Transformation should not make the result complex unnecessarily
+        xp_test = array_namespace(*limits)  # we need xp.isdtype
+        assert (xp_test.isdtype(logres.integral.dtype, "real floating") if ref > 0
+                else xp_test.isdtype(logres.integral.dtype, "complex floating"))
+
+        xp_assert_close(xp.exp(logres.error), res.error, atol=1e-16, check_dtype=False)
+
+    # 15 skipped intentionally; it's very difficult numerically
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason='Cumbersome to convert everything.')
+    @pytest.mark.parametrize('f_number', range(1, 15))
+    def test_basic(self, f_number, xp):
+        f = getattr(self, f"f{f_number}")
+        rtol = 2e-8
+        res = _tanhsinh(f, 0, f.b, rtol=rtol)
+        assert_allclose(res.integral, f.ref, rtol=rtol)
+        if f_number not in {14}:  # mildly underestimates error here
+            true_error = abs(self.error(res.integral, f.ref)/res.integral)
+            assert true_error < res.error
+
+        if f_number in {7, 10, 12}:  # succeeds, but doesn't know it
+            return
+
+        assert res.success
+        assert res.status == 0
+
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason="Distributions aren't xp-compatible.")
+    @pytest.mark.parametrize('ref', (0.5, [0.4, 0.6]))
+    @pytest.mark.parametrize('case', stats._distr_params.distcont)
+    def test_accuracy(self, ref, case, xp):
+        distname, params = case
+        if distname in {'dgamma', 'dweibull', 'laplace', 'kstwo'}:
+            # should split up interval at first-derivative discontinuity
+            pytest.skip('tanh-sinh is not great for non-smooth integrands')
+        if (distname in {'studentized_range', 'levy_stable'}
+                and not int(os.getenv('SCIPY_XSLOW', 0))):
+            pytest.skip('This case passes, but it is too slow.')
+        dist = getattr(stats, distname)(*params)
+        x = dist.interval(ref)
+        res = _tanhsinh(dist.pdf, *x)
+        assert_allclose(res.integral, ref)
+
+    @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+    def test_vectorization(self, shape, xp):
+        # Test for correct functionality, output shapes, and dtypes for various
+        # input shapes.
+        rng = np.random.default_rng(82456839535679456794)
+        a = xp.asarray(rng.random(shape))
+        b = xp.asarray(rng.random(shape))
+        p = xp.asarray(rng.random(shape))
+        n = math.prod(shape)
+
+        def f(x, p):
+            f.ncall += 1
+            f.feval += 1 if (xp_size(x) == n or x.ndim <= 1) else x.shape[-1]
+            return x**p
+        f.ncall = 0
+        f.feval = 0
+
+        @_vectorize(xp)
+        def _tanhsinh_single(a, b, p):
+            return _tanhsinh(lambda x: x**p, a, b)
+
+        res = _tanhsinh(f, a, b, args=(p,))
+        refs = _tanhsinh_single(a, b, p)
+
+        xp_test = array_namespace(a)  # need xp.stack, isdtype
+        attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel']
+        for attr in attrs:
+            ref_attr = xp_test.stack([getattr(ref, attr) for ref in refs])
+            res_attr = xp_ravel(getattr(res, attr))
+            xp_assert_close(res_attr, ref_attr, rtol=1e-15)
+            assert getattr(res, attr).shape == shape
+
+        assert xp_test.isdtype(res.success.dtype, 'bool')
+        assert xp_test.isdtype(res.status.dtype, 'integral')
+        assert xp_test.isdtype(res.nfev.dtype, 'integral')
+        assert xp_test.isdtype(res.maxlevel.dtype, 'integral')
+        assert xp.max(res.nfev) == f.feval
+        # maxlevel = 2 -> 3 function calls (2 initialization, 1 work)
+        assert xp.max(res.maxlevel) >= 2
+        assert xp.max(res.maxlevel) == f.ncall
+
+    def test_flags(self, xp):
+        # Test cases that should produce different status flags; show that all
+        # can be produced simultaneously.
+        def f(xs, js):
+            f.nit += 1
+            funcs = [lambda x: xp.exp(-x**2),  # converges
+                     lambda x: xp.exp(x),  # reaches maxiter due to order=2
+                     lambda x: xp.full_like(x, xp.nan)]  # stops due to NaN
+            res = []
+            for i in range(xp_size(js)):
+                x = xs[i, ...]
+                j = int(xp_ravel(js)[i])
+                res.append(funcs[j](x))
+            return xp.stack(res)
+        f.nit = 0
+
+        args = (xp.arange(3, dtype=xp.int64),)
+        a = xp.asarray([xp.inf]*3)
+        b = xp.asarray([-xp.inf] * 3)
+        res = _tanhsinh(f, a, b, maxlevel=5, args=args)
+        ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_flags_preserve_shape(self, xp):
+        # Same test as above but using `preserve_shape` option to simplify.
+        def f(x):
+            res = [xp.exp(-x[0]**2),  # converges
+                   xp.exp(x[1]),  # reaches maxiter due to order=2
+                   xp.full_like(x[2], xp.nan)]  # stops due to NaN
+            return xp.stack(res)
+
+        a = xp.asarray([xp.inf] * 3)
+        b = xp.asarray([-xp.inf] * 3)
+        res = _tanhsinh(f, a, b, maxlevel=5, preserve_shape=True)
+        ref_flags = xp.asarray([0, -2, -3], dtype=xp.int32)
+        xp_assert_equal(res.status, ref_flags)
+
+    def test_preserve_shape(self, xp):
+        # Test `preserve_shape` option
+        def f(x, xp):
+            return xp.stack([xp.stack([x, xp.sin(10 * x)]),
+                             xp.stack([xp.cos(30 * x), x * xp.sin(100 * x)])])
+
+        ref = quad_vec(lambda x: f(x, np), 0, 1)
+        res = _tanhsinh(lambda x: f(x, xp), xp.asarray(0), xp.asarray(1),
+                        preserve_shape=True)
+        dtype = xp.asarray(0.).dtype
+        xp_assert_close(res.integral, xp.asarray(ref[0], dtype=dtype))
+
+    def test_convergence(self, xp):
+        # demonstrate that number of accurate digits doubles each iteration
+        dtype = xp.float64  # this only works with good precision
+        def f(t):
+            return t * xp.log(1 + t)
+        ref = xp.asarray(0.25, dtype=dtype)
+        a, b = xp.asarray(0., dtype=dtype), xp.asarray(1., dtype=dtype)
+
+        last_logerr = 0
+        for i in range(4):
+            res = _tanhsinh(f, a, b, minlevel=0, maxlevel=i)
+            logerr = self.error(res.integral, ref, log=True, xp=xp)
+            assert (logerr < last_logerr * 2 or logerr < -15.5)
+            last_logerr = logerr
+
+    def test_options_and_result_attributes(self, xp):
+        # demonstrate that options are behaving as advertised and status
+        # messages are as intended
+        xp_test = array_namespace(xp.asarray(1.))  # need xp.atan
+
+        def f(x):
+            f.calls += 1
+            f.feval += xp_size(xp.asarray(x))
+            return x**2 * xp_test.atan(x)
+
+        f.ref = xp.asarray((math.pi - 2 + 2 * math.log(2)) / 12, dtype=xp.float64)
+
+        default_rtol = 1e-12
+        default_atol = f.ref * default_rtol  # effective default absolute tol
+
+        # Keep things simpler by leaving tolerances fixed rather than
+        # having to make them dtype-dependent
+        a = xp.asarray(0., dtype=xp.float64)
+        b = xp.asarray(1., dtype=xp.float64)
+
+        # Test default options
+        f.feval, f.calls = 0, 0
+        ref = _tanhsinh(f, a, b)
+        assert self.error(ref.integral, f.ref) < ref.error < default_atol
+        assert ref.nfev == f.feval
+        ref.calls = f.calls  # reference number of function calls
+        assert ref.success
+        assert ref.status == 0
+
+        # Test `maxlevel` equal to required max level
+        # We should get all the same results
+        f.feval, f.calls = 0, 0
+        maxlevel = int(ref.maxlevel)
+        res = _tanhsinh(f, a, b, maxlevel=maxlevel)
+        res.calls = f.calls
+        assert res == ref
+
+        # Now reduce the maximum level. We won't meet tolerances.
+        f.feval, f.calls = 0, 0
+        maxlevel -= 1
+        assert maxlevel >= 2  # can't compare errors otherwise
+        res = _tanhsinh(f, a, b, maxlevel=maxlevel)
+        assert self.error(res.integral, f.ref) < res.error > default_atol
+        assert res.nfev == f.feval < ref.nfev
+        assert f.calls == ref.calls - 1
+        assert not res.success
+        assert res.status == eim._ECONVERR
+
+        # `maxfun` is currently not enforced
+
+        # # Test `maxfun` equal to required number of function evaluations
+        # # We should get all the same results
+        # f.feval, f.calls = 0, 0
+        # maxfun = ref.nfev
+        # res = _tanhsinh(f, 0, f.b, maxfun = maxfun)
+        # assert res == ref
+        #
+        # # Now reduce `maxfun`. We won't meet tolerances.
+        # f.feval, f.calls = 0, 0
+        # maxfun -= 1
+        # res = _tanhsinh(f, 0, f.b, maxfun=maxfun)
+        # assert self.error(res.integral, f.ref) < res.error > default_atol
+        # assert res.nfev == f.feval < ref.nfev
+        # assert f.calls == ref.calls - 1
+        # assert not res.success
+        # assert res.status == 2
+
+        # Take this result to be the new reference
+        ref = res
+        ref.calls = f.calls
+
+        # Test `atol`
+        f.feval, f.calls = 0, 0
+        # With this tolerance, we should get the exact same result as ref
+        atol = np.nextafter(float(ref.error), np.inf)
+        res = _tanhsinh(f, a, b, rtol=0, atol=atol)
+        assert res.integral == ref.integral
+        assert res.error == ref.error
+        assert res.nfev == f.feval == ref.nfev
+        assert f.calls == ref.calls
+        # Except the result is considered to be successful
+        assert res.success
+        assert res.status == 0
+
+        f.feval, f.calls = 0, 0
+        # With a tighter tolerance, we should get a more accurate result
+        atol = np.nextafter(float(ref.error), -np.inf)
+        res = _tanhsinh(f, a, b, rtol=0, atol=atol)
+        assert self.error(res.integral, f.ref) < res.error < atol
+        assert res.nfev == f.feval > ref.nfev
+        assert f.calls > ref.calls
+        assert res.success
+        assert res.status == 0
+
+        # Test `rtol`
+        f.feval, f.calls = 0, 0
+        # With this tolerance, we should get the exact same result as ref
+        rtol = np.nextafter(float(ref.error/ref.integral), np.inf)
+        res = _tanhsinh(f, a, b, rtol=rtol)
+        assert res.integral == ref.integral
+        assert res.error == ref.error
+        assert res.nfev == f.feval == ref.nfev
+        assert f.calls == ref.calls
+        # Except the result is considered to be successful
+        assert res.success
+        assert res.status == 0
+
+        f.feval, f.calls = 0, 0
+        # With a tighter tolerance, we should get a more accurate result
+        rtol = np.nextafter(float(ref.error/ref.integral), -np.inf)
+        res = _tanhsinh(f, a, b, rtol=rtol)
+        assert self.error(res.integral, f.ref)/f.ref < res.error/res.integral < rtol
+        assert res.nfev == f.feval > ref.nfev
+        assert f.calls > ref.calls
+        assert res.success
+        assert res.status == 0
+
+    @pytest.mark.skip_xp_backends('torch', reason=
+            'https://github.com/scipy/scipy/pull/21149#issuecomment-2330477359',
+    )
+    @pytest.mark.parametrize('rtol', [1e-4, 1e-14])
+    def test_log(self, rtol, xp):
+        # Test equivalence of log-integration and regular integration
+        test_tols = dict(atol=1e-18, rtol=1e-15)
+
+        # Positive integrand (real log-integrand)
+        a = xp.asarray(-1., dtype=xp.float64)
+        b = xp.asarray(2., dtype=xp.float64)
+        res = _tanhsinh(norm_logpdf, a, b, log=True, rtol=math.log(rtol))
+        ref = _tanhsinh(norm_pdf, a, b, rtol=rtol)
+        xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols)
+        xp_assert_close(xp.exp(res.error), ref.error, **test_tols)
+        assert res.nfev == ref.nfev
+
+        # Real integrand (complex log-integrand)
+        def f(x):
+            return -norm_logpdf(x)*norm_pdf(x)
+
+        def logf(x):
+            return xp.log(norm_logpdf(x) + 0j) + norm_logpdf(x) + xp.pi * 1j
+
+        a = xp.asarray(-xp.inf, dtype=xp.float64)
+        b = xp.asarray(xp.inf, dtype=xp.float64)
+        res = _tanhsinh(logf, a, b, log=True)
+        ref = _tanhsinh(f, a, b)
+        # In gh-19173, we saw `invalid` warnings on one CI platform.
+        # Silencing `all` because I can't reproduce locally and don't want
+        # to risk the need to run CI again.
+        with np.errstate(all='ignore'):
+            xp_assert_close(xp.exp(res.integral), ref.integral, **test_tols,
+                            check_dtype=False)
+            xp_assert_close(xp.exp(res.error), ref.error, **test_tols,
+                            check_dtype=False)
+        assert res.nfev == ref.nfev
+
+    def test_complex(self, xp):
+        # Test integration of complex integrand
+        # Finite limits
+        def f(x):
+            return xp.exp(1j * x)
+
+        a, b = xp.asarray(0.), xp.asarray(xp.pi/4)
+        res = _tanhsinh(f, a, b)
+        ref = math.sqrt(2)/2 + (1-math.sqrt(2)/2)*1j
+        xp_assert_close(res.integral, xp.asarray(ref))
+
+        # Infinite limits
+        def f(x):
+            return norm_pdf(x) + 1j/2*norm_pdf(x/2)
+
+        a, b = xp.asarray(xp.inf), xp.asarray(-xp.inf)
+        res = _tanhsinh(f, a, b)
+        xp_assert_close(res.integral, xp.asarray(-(1+1j)))
+
+    @pytest.mark.parametrize("maxlevel", range(4))
+    def test_minlevel(self, maxlevel, xp):
+        # Verify that minlevel does not change the values at which the
+        # integrand is evaluated or the integral/error estimates, only the
+        # number of function calls
+
+        # need `xp.concat`, `xp.atan`, and `xp.sort`
+        xp_test = array_namespace(xp.asarray(1.))
+
+        def f(x):
+            f.calls += 1
+            f.feval += xp_size(xp.asarray(x))
+            f.x = xp_test.concat((f.x, xp_ravel(x)))
+            return x**2 * xp_test.atan(x)
+
+        f.feval, f.calls, f.x = 0, 0, xp.asarray([])
+
+        a = xp.asarray(0, dtype=xp.float64)
+        b = xp.asarray(1, dtype=xp.float64)
+        ref = _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel)
+        ref_x = xp_test.sort(f.x)
+
+        for minlevel in range(0, maxlevel + 1):
+            f.feval, f.calls, f.x = 0, 0, xp.asarray([])
+            options = dict(minlevel=minlevel, maxlevel=maxlevel)
+            res = _tanhsinh(f, a, b, **options)
+            # Should be very close; all that has changed is the order of values
+            xp_assert_close(res.integral, ref.integral, rtol=4e-16)
+            # Difference in absolute errors << magnitude of integral
+            xp_assert_close(res.error, ref.error, atol=4e-16 * ref.integral)
+            assert res.nfev == f.feval == f.x.shape[0]
+            assert f.calls == maxlevel - minlevel + 1 + 1  # 1 validation call
+            assert res.status == ref.status
+            xp_assert_equal(ref_x, xp_test.sort(f.x))
+
+    def test_improper_integrals(self, xp):
+        # Test handling of infinite limits of integration (mixed with finite limits)
+        def f(x):
+            x[xp.isinf(x)] = xp.nan
+            return xp.exp(-x**2)
+        a = xp.asarray([-xp.inf, 0, -xp.inf, xp.inf, -20, -xp.inf, -20])
+        b = xp.asarray([xp.inf, xp.inf, 0, -xp.inf, 20, 20, xp.inf])
+        ref = math.sqrt(math.pi)
+        ref = xp.asarray([ref, ref/2, ref/2, -ref, ref, ref, ref])
+        res = _tanhsinh(f, a, b)
+        xp_assert_close(res.integral, ref)
+
+    @pytest.mark.parametrize("limits", ((0, 3), ([-math.inf, 0], [3, 3])))
+    @pytest.mark.parametrize("dtype", ('float32', 'float64'))
+    def test_dtype(self, limits, dtype, xp):
+        # Test that dtypes are preserved
+        dtype = getattr(xp, dtype)
+        a, b = xp.asarray(limits, dtype=dtype)
+
+        def f(x):
+            assert x.dtype == dtype
+            return xp.exp(x)
+
+        rtol = 1e-12 if dtype == xp.float64 else 1e-5
+        res = _tanhsinh(f, a, b, rtol=rtol)
+        assert res.integral.dtype == dtype
+        assert res.error.dtype == dtype
+        assert xp.all(res.success)
+        xp_assert_close(res.integral, xp.exp(b)-xp.exp(a))
+
+    def test_maxiter_callback(self, xp):
+        # Test behavior of `maxiter` parameter and `callback` interface
+        a, b = xp.asarray(-xp.inf), xp.asarray(xp.inf)
+        def f(x):
+            return xp.exp(-x*x)
+
+        minlevel, maxlevel = 0, 2
+        maxiter = maxlevel - minlevel + 1
+        kwargs = dict(minlevel=minlevel, maxlevel=maxlevel, rtol=1e-15)
+        res = _tanhsinh(f, a, b, **kwargs)
+        assert not res.success
+        assert res.maxlevel == maxlevel
+
+        def callback(res):
+            callback.iter += 1
+            callback.res = res
+            assert hasattr(res, 'integral')
+            assert res.status == 1
+            if callback.iter == maxiter:
+                raise StopIteration
+        callback.iter = -1  # callback called once before first iteration
+        callback.res = None
+
+        del kwargs['maxlevel']
+        res2 = _tanhsinh(f, a, b, **kwargs, callback=callback)
+        # terminating with callback is identical to terminating due to maxiter
+        # (except for `status`)
+        for key in res.keys():
+            if key == 'status':
+                assert res[key] == -2
+                assert res2[key] == -4
+            else:
+                assert res2[key] == callback.res[key] == res[key]
+
+    def test_jumpstart(self, xp):
+        # The intermediate results at each level i should be the same as the
+        # final results when jumpstarting at level i; i.e. minlevel=maxlevel=i
+        a = xp.asarray(-xp.inf, dtype=xp.float64)
+        b = xp.asarray(xp.inf, dtype=xp.float64)
+
+        def f(x):
+            return xp.exp(-x*x)
+
+        def callback(res):
+            callback.integrals.append(xp_copy(res.integral)[()])
+            callback.errors.append(xp_copy(res.error)[()])
+        callback.integrals = []
+        callback.errors = []
+
+        maxlevel = 4
+        _tanhsinh(f, a, b, minlevel=0, maxlevel=maxlevel, callback=callback)
+
+        for i in range(maxlevel + 1):
+            res = _tanhsinh(f, a, b, minlevel=i, maxlevel=i)
+            xp_assert_close(callback.integrals[1+i], res.integral, rtol=1e-15)
+            xp_assert_close(callback.errors[1+i], res.error, rtol=1e-15, atol=1e-16)
+
+    def test_special_cases(self, xp):
+        # Test edge cases and other special cases
+        a, b = xp.asarray(0), xp.asarray(1)
+        xp_test = array_namespace(a, b)  # need `xp.isdtype`
+
+        def f(x):
+            assert xp_test.isdtype(x.dtype, "real floating")
+            return x
+
+        res = _tanhsinh(f, a, b)
+        assert res.success
+        xp_assert_close(res.integral, xp.asarray(0.5))
+
+        # Test levels 0 and 1; error is NaN
+        res = _tanhsinh(f, a, b, maxlevel=0)
+        assert res.integral > 0
+        xp_assert_equal(res.error, xp.asarray(xp.nan))
+        res = _tanhsinh(f, a, b, maxlevel=1)
+        assert res.integral > 0
+        xp_assert_equal(res.error, xp.asarray(xp.nan))
+
+        # Test equal left and right integration limits
+        res = _tanhsinh(f, b, b)
+        assert res.success
+        assert res.maxlevel == -1
+        xp_assert_close(res.integral, xp.asarray(0.))
+
+        # Test scalar `args` (not in tuple)
+        def f(x, c):
+            return x**c
+
+        res = _tanhsinh(f, a, b, args=29)
+        xp_assert_close(res.integral, xp.asarray(1/30))
+
+        # Test NaNs
+        a = xp.asarray([xp.nan, 0, 0, 0])
+        b = xp.asarray([1, xp.nan, 1, 1])
+        c = xp.asarray([1, 1, xp.nan, 1])
+        res = _tanhsinh(f, a, b, args=(c,))
+        xp_assert_close(res.integral, xp.asarray([xp.nan, xp.nan, xp.nan, 0.5]))
+        xp_assert_equal(res.error[:3], xp.full((3,), xp.nan))
+        xp_assert_equal(res.status, xp.asarray([-3, -3, -3, 0], dtype=xp.int32))
+        xp_assert_equal(res.success, xp.asarray([False, False, False, True]))
+        xp_assert_equal(res.nfev[:3], xp.full((3,), 1, dtype=xp.int32))
+
+        # Test complex integral followed by real integral
+        # Previously, h0 was of the result dtype. If the `dtype` were complex,
+        # this could lead to complex cached abscissae/weights. If these get
+        # cast to real dtype for a subsequent real integral, we would get a
+        # ComplexWarning. Check that this is avoided.
+        _pair_cache.xjc = xp.empty(0)
+        _pair_cache.wj = xp.empty(0)
+        _pair_cache.indices = [0]
+        _pair_cache.h0 = None
+        a, b = xp.asarray(0), xp.asarray(1)
+        res = _tanhsinh(lambda x: xp.asarray(x*1j), a, b)
+        xp_assert_close(res.integral, xp.asarray(0.5*1j))
+        res = _tanhsinh(lambda x: x, a, b)
+        xp_assert_close(res.integral, xp.asarray(0.5))
+
+        # Test zero-size
+        shape = (0, 3)
+        res = _tanhsinh(lambda x: x, xp.asarray(0), xp.zeros(shape))
+        attrs = ['integral', 'error', 'success', 'status', 'nfev', 'maxlevel']
+        for attr in attrs:
+            assert res[attr].shape == shape
+
+    @pytest.mark.skip_xp_backends(np_only=True)
+    def test_compress_nodes_weights_gh21496(self, xp):
+        # See discussion in:
+        # https://github.com/scipy/scipy/pull/21496#discussion_r1878681049
+        # This would cause "ValueError: attempt to get argmax of an empty sequence"
+        # Check that this has been resolved.
+        x = np.full(65, 3)
+        x[-1] = 1000
+        _tanhsinh(np.sin, 1, x)
+
+    def test_gh_22681_finite_error(self, xp):
+        # gh-22681 noted a case in which the error was NaN on some platforms;
+        # check that this does in fact fail in CI.
+        a = complex(12, -10)
+        b = complex(12, 39)
+        def f(t):
+            return xp.sin(a * (1 - t) + b * t)
+        res = _tanhsinh(f, xp.asarray(0.), xp.asarray(1.), atol=0, rtol=0, maxlevel=10)
+        assert xp.isfinite(res.error)
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends('array_api_strict', reason='No fancy indexing.')
+@pytest.mark.skip_xp_backends('jax.numpy', reason='No mutation.')
+class TestNSum:
+    rng = np.random.default_rng(5895448232066142650)
+    p = rng.uniform(1, 10, size=10).tolist()
+
+    def f1(self, k):
+        # Integers are never passed to `f1`; if they were, we'd get
+        # integer to negative integer power error
+        return k**(-2)
+
+    f1.ref = np.pi**2/6
+    f1.a = 1
+    f1.b = np.inf
+    f1.args = tuple()
+
+    def f2(self, k, p):
+        return 1 / k**p
+
+    f2.ref = special.zeta(p, 1)
+    f2.a = 1.
+    f2.b = np.inf
+    f2.args = (p,)
+
+    def f3(self, k, p):
+        return 1 / k**p
+
+    f3.a = 1
+    f3.b = rng.integers(5, 15, size=(3, 1))
+    f3.ref = _gen_harmonic_gt1(f3.b, p)
+    f3.args = (p,)
+
+    def test_input_validation(self, xp):
+        f = self.f1
+        a, b = xp.asarray(f.a), xp.asarray(f.b)
+
+        message = '`f` must be callable.'
+        with pytest.raises(ValueError, match=message):
+            nsum(42, a, b)
+
+        message = '...must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, log=2)
+
+        message = '...must be real numbers.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, xp.asarray(1+1j), b)
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, xp.asarray(1+1j))
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, step=xp.asarray(1+1j))
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(atol='ekki'))
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(rtol=pytest))
+
+        with np.errstate(all='ignore'):
+            res = nsum(f, xp.asarray([np.nan, np.inf]), xp.asarray(1.))
+            assert xp.all((res.status == -1) & xp.isnan(res.sum)
+                          & xp.isnan(res.error) & ~res.success & res.nfev == 1)
+            res = nsum(f, xp.asarray(10.), xp.asarray([np.nan, 1]))
+            assert xp.all((res.status == -1) & xp.isnan(res.sum)
+                          & xp.isnan(res.error) & ~res.success & res.nfev == 1)
+            res = nsum(f, xp.asarray(1.), xp.asarray(10.),
+                       step=xp.asarray([xp.nan, -xp.inf, xp.inf, -1, 0]))
+            assert xp.all((res.status == -1) & xp.isnan(res.sum)
+                          & xp.isnan(res.error) & ~res.success & res.nfev == 1)
+
+        message = '...must be non-negative and finite.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(rtol=-1))
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(atol=np.inf))
+
+        message = '...may not be positive infinity.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(rtol=np.inf), log=True)
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, tolerances=dict(atol=np.inf), log=True)
+
+        message = '...must be a non-negative integer.'
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, maxterms=3.5)
+        with pytest.raises(ValueError, match=message):
+            nsum(f, a, b, maxterms=-2)
+
+    @pytest.mark.parametrize('f_number', range(1, 4))
+    def test_basic(self, f_number, xp):
+        dtype = xp.asarray(1.).dtype
+        f = getattr(self, f"f{f_number}")
+        a, b = xp.asarray(f.a), xp.asarray(f.b),
+        args = tuple(xp.asarray(arg) for arg in f.args)
+        ref = xp.asarray(f.ref, dtype=dtype)
+        res = nsum(f, a, b, args=args)
+        xp_assert_close(res.sum, ref)
+        xp_assert_equal(res.status, xp.zeros(ref.shape, dtype=xp.int32))
+        xp_test = array_namespace(a)  # CuPy doesn't have `bool`
+        xp_assert_equal(res.success, xp.ones(ref.shape, dtype=xp_test.bool))
+
+        with np.errstate(divide='ignore'):
+            logres = nsum(lambda *args: xp.log(f(*args)),
+                           a, b, log=True, args=args)
+        xp_assert_close(xp.exp(logres.sum), res.sum)
+        xp_assert_close(xp.exp(logres.error), res.error, atol=1e-15)
+        xp_assert_equal(logres.status, res.status)
+        xp_assert_equal(logres.success, res.success)
+
+    @pytest.mark.parametrize('maxterms', [0, 1, 10, 20, 100])
+    def test_integral(self, maxterms, xp):
+        # test precise behavior of integral approximation
+        f = self.f1
+
+        def logf(x):
+            return -2*xp.log(x)
+
+        def F(x):
+            return -1 / x
+
+        a = xp.asarray([1, 5], dtype=xp.float64)[:, xp.newaxis]
+        b = xp.asarray([20, 100, xp.inf], dtype=xp.float64)[:, xp.newaxis, xp.newaxis]
+        step = xp.asarray([0.5, 1, 2], dtype=xp.float64).reshape((-1, 1, 1, 1))
+        nsteps = xp.floor((b - a)/step)
+        b_original = b
+        b = a + nsteps*step
+
+        k = a + maxterms*step
+        # partial sum
+        direct = xp.sum(f(a + xp.arange(maxterms)*step), axis=-1, keepdims=True)
+        integral = (F(b) - F(k))/step  # integral approximation of remainder
+        low = direct + integral + f(b)  # theoretical lower bound
+        high = direct + integral + f(k)  # theoretical upper bound
+        ref_sum = (low + high)/2  # nsum uses average of the two
+        ref_err = (high - low)/2  # error (assuming perfect quadrature)
+
+        # correct reference values where number of terms < maxterms
+        xp_test = array_namespace(a)  # torch needs broadcast_arrays
+        a, b, step = xp_test.broadcast_arrays(a, b, step)
+        for i in np.ndindex(a.shape):
+            ai, bi, stepi = float(a[i]), float(b[i]), float(step[i])
+            if (bi - ai)/stepi + 1 <= maxterms:
+                direct = xp.sum(f(xp.arange(ai, bi+stepi, stepi, dtype=xp.float64)))
+                ref_sum[i] = direct
+                ref_err[i] = direct * xp.finfo(direct.dtype).eps
+
+        rtol = 1e-12
+        res = nsum(f, a, b_original, step=step, maxterms=maxterms,
+                   tolerances=dict(rtol=rtol))
+        xp_assert_close(res.sum, ref_sum, rtol=10*rtol)
+        xp_assert_close(res.error, ref_err, rtol=100*rtol)
+
+        i = ((b_original - a)/step + 1 <= maxterms)
+        xp_assert_close(res.sum[i], ref_sum[i], rtol=1e-15)
+        xp_assert_close(res.error[i], ref_err[i], rtol=1e-15)
+
+        logres = nsum(logf, a, b_original, step=step, log=True,
+                      tolerances=dict(rtol=math.log(rtol)), maxterms=maxterms)
+        xp_assert_close(xp.exp(logres.sum), res.sum)
+        xp_assert_close(xp.exp(logres.error), res.error)
+
+    @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+    def test_vectorization(self, shape, xp):
+        # Test for correct functionality, output shapes, and dtypes for various
+        # input shapes.
+        rng = np.random.default_rng(82456839535679456794)
+        a = rng.integers(1, 10, size=shape)
+        # when the sum can be computed directly or `maxterms` is large enough
+        # to meet `atol`, there are slight differences (for good reason)
+        # between vectorized call and looping.
+        b = np.inf
+        p = rng.random(shape) + 1
+        n = math.prod(shape)
+
+        def f(x, p):
+            f.feval += 1 if (x.size == n or x.ndim <= 1) else x.shape[-1]
+            return 1 / x ** p
+
+        f.feval = 0
+
+        @np.vectorize
+        def nsum_single(a, b, p, maxterms):
+            return nsum(lambda x: 1 / x**p, a, b, maxterms=maxterms)
+
+        res = nsum(f, xp.asarray(a), xp.asarray(b), maxterms=1000,
+                   args=(xp.asarray(p),))
+        refs = nsum_single(a, b, p, maxterms=1000).ravel()
+
+        attrs = ['sum', 'error', 'success', 'status', 'nfev']
+        for attr in attrs:
+            ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs]
+            res_attr = getattr(res, attr)
+            xp_assert_close(xp_ravel(res_attr), xp.asarray(ref_attr), rtol=1e-15)
+            assert res_attr.shape == shape
+
+        xp_test = array_namespace(xp.asarray(1.))
+        assert xp_test.isdtype(res.success.dtype, 'bool')
+        assert xp_test.isdtype(res.status.dtype, 'integral')
+        assert xp_test.isdtype(res.nfev.dtype, 'integral')
+        if is_numpy(xp):  # other libraries might have different number
+            assert int(xp.max(res.nfev)) == f.feval
+
+    def test_status(self, xp):
+        f = self.f2
+
+        p = [2, 2, 0.9, 1.1, 2, 2]
+        a = xp.asarray([0, 0, 1, 1, 1, np.nan], dtype=xp.float64)
+        b = xp.asarray([10, np.inf, np.inf, np.inf, np.inf, np.inf], dtype=xp.float64)
+        ref = special.zeta(p, 1)
+        p = xp.asarray(p, dtype=xp.float64)
+
+        with np.errstate(divide='ignore'):  # intentionally dividing by zero
+            res = nsum(f, a, b, args=(p,))
+
+        ref_success = xp.asarray([False, False, False, False, True, False])
+        ref_status = xp.asarray([-3, -3, -2, -4, 0, -1], dtype=xp.int32)
+        xp_assert_equal(res.success, ref_success)
+        xp_assert_equal(res.status, ref_status)
+        xp_assert_close(res.sum[res.success], xp.asarray(ref)[res.success])
+
+    def test_nfev(self, xp):
+        def f(x):
+            f.nfev += xp_size(x)
+            return 1 / x**2
+
+        f.nfev = 0
+        res = nsum(f, xp.asarray(1), xp.asarray(10))
+        assert res.nfev == f.nfev
+
+        f.nfev = 0
+        res = nsum(f, xp.asarray(1), xp.asarray(xp.inf), tolerances=dict(atol=1e-6))
+        assert res.nfev == f.nfev
+
+    def test_inclusive(self, xp):
+        # There was an edge case off-by one bug when `_direct` was called with
+        # `inclusive=True`. Check that this is resolved.
+        a = xp.asarray([1, 4])
+        b = xp.asarray(xp.inf)
+        res = nsum(lambda k: 1 / k ** 2, a, b,
+                   maxterms=500, tolerances=dict(atol=0.1))
+        ref = nsum(lambda k: 1 / k ** 2, a, b)
+        assert xp.all(res.sum > (ref.sum - res.error))
+        assert xp.all(res.sum < (ref.sum + res.error))
+
+    @pytest.mark.parametrize('log', [True, False])
+    def test_infinite_bounds(self, log, xp):
+        a = xp.asarray([1, -np.inf, -np.inf])
+        b = xp.asarray([np.inf, -1, np.inf])
+        c = xp.asarray([1, 2, 3])
+
+        def f(x, a):
+            return (xp.log(xp.tanh(a / 2)) - a*xp.abs(x) if log
+                    else xp.tanh(a/2) * xp.exp(-a*xp.abs(x)))
+
+        res = nsum(f, a, b, args=(c,), log=log)
+        ref = xp.asarray([stats.dlaplace.sf(0, 1), stats.dlaplace.sf(0, 2), 1])
+        ref = xp.log(ref) if log else ref
+        atol = (1e-10 if a.dtype==xp.float64 else 1e-5) if log else 0
+        xp_assert_close(res.sum, xp.asarray(ref, dtype=a.dtype), atol=atol)
+
+        # # Make sure the sign of `x` passed into `f` is correct.
+        def f(x, c):
+            return -3*xp.log(c*x) if log else 1 / (c*x)**3
+
+        a = xp.asarray([1, -np.inf])
+        b = xp.asarray([np.inf, -1])
+        arg = xp.asarray([1, -1])
+        res = nsum(f, a, b, args=(arg,), log=log)
+        ref = np.log(special.zeta(3)) if log else special.zeta(3)
+        xp_assert_close(res.sum, xp.full(a.shape, ref, dtype=a.dtype))
+
+    def test_decreasing_check(self, xp):
+        # Test accuracy when we start sum on an uphill slope.
+        # Without the decreasing check, the terms would look small enough to
+        # use the integral approximation. Because the function is not decreasing,
+        # the error is not bounded by the magnitude of the last term of the
+        # partial sum. In this case, the error would be  ~1e-4, causing the test
+        # to fail.
+        def f(x):
+            return xp.exp(-x ** 2)
+
+        a, b = xp.asarray(-25, dtype=xp.float64), xp.asarray(np.inf, dtype=xp.float64)
+        res = nsum(f, a, b)
+
+        # Reference computed with mpmath:
+        # from mpmath import mp
+        # mp.dps = 50
+        # def fmp(x): return mp.exp(-x**2)
+        # ref = mp.nsum(fmp, (-25, 0)) + mp.nsum(fmp, (1, mp.inf))
+        ref = xp.asarray(1.772637204826652, dtype=xp.float64)
+
+        xp_assert_close(res.sum, ref, rtol=1e-15)
+
+    def test_special_case(self, xp):
+        # test equal lower/upper limit
+        f = self.f1
+        a = b = xp.asarray(2)
+        res = nsum(f, a, b)
+        xp_assert_equal(res.sum, xp.asarray(f(2)))
+
+        # Test scalar `args` (not in tuple)
+        res = nsum(self.f2, xp.asarray(1), xp.asarray(np.inf), args=xp.asarray(2))
+        xp_assert_close(res.sum, xp.asarray(self.f1.ref))  # f1.ref is correct w/ args=2
+
+        # Test 0 size input
+        a = xp.empty((3, 1, 1))  # arbitrary broadcastable shapes
+        b = xp.empty((0, 1))  # could use Hypothesis
+        p = xp.empty(4)  # but it's overkill
+        shape = np.broadcast_shapes(a.shape, b.shape, p.shape)
+        res = nsum(self.f2, a, b, args=(p,))
+        assert res.sum.shape == shape
+        assert res.status.shape == shape
+        assert res.nfev.shape == shape
+
+        # Test maxterms=0
+        def f(x):
+            with np.errstate(divide='ignore'):
+                return 1 / x
+
+        res = nsum(f, xp.asarray(0), xp.asarray(10), maxterms=0)
+        assert xp.isnan(res.sum)
+        assert xp.isnan(res.error)
+        assert res.status == -2
+
+        res = nsum(f, xp.asarray(0), xp.asarray(10), maxterms=1)
+        assert xp.isnan(res.sum)
+        assert xp.isnan(res.error)
+        assert res.status == -3
+
+        # Test NaNs
+        # should skip both direct and integral methods if there are NaNs
+        a = xp.asarray([xp.nan, 1, 1, 1])
+        b = xp.asarray([xp.inf, xp.nan, xp.inf, xp.inf])
+        p = xp.asarray([2, 2, xp.nan, 2])
+        res = nsum(self.f2, a, b, args=(p,))
+        xp_assert_close(res.sum, xp.asarray([xp.nan, xp.nan, xp.nan, self.f1.ref]))
+        xp_assert_close(res.error[:3], xp.full((3,), xp.nan))
+        xp_assert_equal(res.status, xp.asarray([-1, -1, -3, 0], dtype=xp.int32))
+        xp_assert_equal(res.success, xp.asarray([False, False, False, True]))
+        # Ideally res.nfev[2] would be 1, but `tanhsinh` has some function evals
+        xp_assert_equal(res.nfev[:2], xp.full((2,), 1, dtype=xp.int32))
+
+    @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+    def test_dtype(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        def f(k):
+            assert k.dtype == dtype
+            return 1 / k ** xp.asarray(2, dtype=dtype)
+
+        a = xp.asarray(1, dtype=dtype)
+        b = xp.asarray([10, xp.inf], dtype=dtype)
+        res = nsum(f, a, b)
+        assert res.sum.dtype == dtype
+        assert res.error.dtype == dtype
+
+        rtol = 1e-12 if dtype == xp.float64 else 1e-6
+        ref = _gen_harmonic_gt1(np.asarray([10, xp.inf]), 2)
+        xp_assert_close(res.sum, xp.asarray(ref, dtype=dtype), rtol=rtol)
+
+    @pytest.mark.parametrize('case', [(10, 100), (100, 10)])
+    def test_nondivisible_interval(self, case, xp):
+        # When the limits of the sum are such that (b - a)/step
+        # is not exactly integral, check that only floor((b - a)/step)
+        # terms are included.
+        n, maxterms = case
+
+        def f(k):
+            return 1 / k ** 2
+
+        a = np.e
+        step = 1 / 3
+        b0 = a + n * step
+        i = np.arange(-2, 3)
+        b = b0 + i * np.spacing(b0)
+        ns = np.floor((b - a) / step)
+        assert len(set(ns)) == 2
+
+        a, b = xp.asarray(a, dtype=xp.float64), xp.asarray(b, dtype=xp.float64)
+        step, ns = xp.asarray(step, dtype=xp.float64), xp.asarray(ns, dtype=xp.float64)
+        res = nsum(f, a, b, step=step, maxterms=maxterms)
+        xp_assert_equal(xp.diff(ns) > 0, xp.diff(res.sum) > 0)
+        xp_assert_close(res.sum[-1], res.sum[0] + f(b0))
+
+    @pytest.mark.skip_xp_backends(np_only=True, reason='Needs beta function.')
+    def test_logser_kurtosis_gh20648(self, xp):
+        # Some functions return NaN at infinity rather than 0 like they should.
+        # Check that this is accounted for.
+        ref = stats.yulesimon.moment(4, 5)
+        def f(x):
+            return stats.yulesimon._pmf(x, 5) * x**4
+
+        with np.errstate(invalid='ignore'):
+            assert np.isnan(f(np.inf))
+
+        res = nsum(f, 1, np.inf)
+        assert_allclose(res.sum, ref)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/vode.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/vode.py
new file mode 100644
index 0000000000000000000000000000000000000000..f92927901084ce33cdeb006057d85dd501b13aae
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/integrate/vode.py
@@ -0,0 +1,15 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="integrate", module="vode",
+                                   private_modules=["_vode"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c4f97134d20b8d3acb1bea54c8384c510314aaa
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/__init__.py
@@ -0,0 +1,216 @@
+"""
+========================================
+Interpolation (:mod:`scipy.interpolate`)
+========================================
+
+.. currentmodule:: scipy.interpolate
+
+Sub-package for objects used in interpolation.
+
+As listed below, this sub-package contains spline functions and classes,
+1-D and multidimensional (univariate and multivariate)
+interpolation classes, Lagrange and Taylor polynomial interpolators, and
+wrappers for `FITPACK `__
+and DFITPACK functions.
+
+Univariate interpolation
+========================
+
+.. autosummary::
+   :toctree: generated/
+
+   interp1d
+   BarycentricInterpolator
+   KroghInterpolator
+   barycentric_interpolate
+   krogh_interpolate
+   pchip_interpolate
+   CubicHermiteSpline
+   PchipInterpolator
+   Akima1DInterpolator
+   CubicSpline
+   PPoly
+   BPoly
+   FloaterHormannInterpolator
+
+
+Multivariate interpolation
+==========================
+
+Unstructured data:
+
+.. autosummary::
+   :toctree: generated/
+
+   griddata
+   LinearNDInterpolator
+   NearestNDInterpolator
+   CloughTocher2DInterpolator
+   RBFInterpolator
+   Rbf
+   interp2d
+
+For data on a grid:
+
+.. autosummary::
+   :toctree: generated/
+
+   interpn
+   RegularGridInterpolator
+   RectBivariateSpline
+
+.. seealso::
+
+    `scipy.ndimage.map_coordinates`
+
+Tensor product polynomials:
+
+.. autosummary::
+   :toctree: generated/
+
+   NdPPoly
+   NdBSpline
+
+1-D Splines
+===========
+
+.. autosummary::
+   :toctree: generated/
+
+   BSpline
+   make_interp_spline
+   make_lsq_spline
+   make_smoothing_spline
+   generate_knots
+   make_splrep
+   make_splprep
+
+Functional interface to FITPACK routines:
+
+.. autosummary::
+   :toctree: generated/
+
+   splrep
+   splprep
+   splev
+   splint
+   sproot
+   spalde
+   splder
+   splantider
+   insert
+
+Object-oriented FITPACK interface:
+
+.. autosummary::
+   :toctree: generated/
+
+   UnivariateSpline
+   InterpolatedUnivariateSpline
+   LSQUnivariateSpline
+
+
+
+2-D Splines
+===========
+
+For data on a grid:
+
+.. autosummary::
+   :toctree: generated/
+
+   RectBivariateSpline
+   RectSphereBivariateSpline
+
+For unstructured data:
+
+.. autosummary::
+   :toctree: generated/
+
+   BivariateSpline
+   SmoothBivariateSpline
+   SmoothSphereBivariateSpline
+   LSQBivariateSpline
+   LSQSphereBivariateSpline
+
+Low-level interface to FITPACK functions:
+
+.. autosummary::
+   :toctree: generated/
+
+   bisplrep
+   bisplev
+
+Rational Approximation
+======================
+
+.. autosummary::
+   :toctree: generated/
+
+   pade
+   AAA
+
+Additional tools
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   lagrange
+   approximate_taylor_polynomial
+
+.. seealso::
+
+   `scipy.ndimage.map_coordinates`,
+   `scipy.ndimage.spline_filter`,
+   `scipy.signal.resample`,
+   `scipy.signal.bspline`,
+   `scipy.signal.gauss_spline`,
+   `scipy.signal.qspline1d`,
+   `scipy.signal.cspline1d`,
+   `scipy.signal.qspline1d_eval`,
+   `scipy.signal.cspline1d_eval`,
+   `scipy.signal.qspline2d`,
+   `scipy.signal.cspline2d`.
+
+``pchip`` is an alias of `PchipInterpolator` for backward compatibility
+(should not be used in new code).
+"""
+from ._interpolate import *
+from ._fitpack_py import *
+
+# New interface to fitpack library:
+from ._fitpack2 import *
+
+from ._rbf import Rbf
+
+from ._rbfinterp import *
+
+from ._polyint import *
+
+from ._cubic import *
+
+from ._ndgriddata import *
+
+from ._bsplines import *
+from ._fitpack_repro import generate_knots, make_splrep, make_splprep
+
+from ._pade import *
+
+from ._rgi import *
+
+from ._ndbspline import NdBSpline
+
+from ._bary_rational import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import fitpack, fitpack2, interpolate, ndgriddata, polyint, rbf, interpnd
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
+
+# Backward compatibility
+pchip = PchipInterpolator
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_bary_rational.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_bary_rational.py
new file mode 100644
index 0000000000000000000000000000000000000000..be13c06e27cb8df7ec4c55993dd3937e867429e5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_bary_rational.py
@@ -0,0 +1,715 @@
+# Copyright (c) 2017, The Chancellor, Masters and Scholars of the University
+# of Oxford, and the Chebfun Developers. All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#     * Redistributions of source code must retain the above copyright
+#       notice, this list of conditions and the following disclaimer.
+#     * Redistributions in binary form must reproduce the above copyright
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#     * Neither the name of the University of Oxford nor the names of its
+#       contributors may be used to endorse or promote products derived from
+#       this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import warnings
+import operator
+
+import numpy as np
+import scipy
+
+
+__all__ = ["AAA", "FloaterHormannInterpolator"]
+
+
+class _BarycentricRational:
+    """Base class for Barycentric representation of a rational function."""
+    def __init__(self, x, y, **kwargs):
+        # input validation
+        z = np.asarray(x)
+        f = np.asarray(y)
+
+        self._input_validation(z, f, **kwargs)
+
+        # Remove infinite or NaN function values and repeated entries
+        to_keep = np.logical_and.reduce(
+            ((np.isfinite(f)) & (~np.isnan(f))).reshape(f.shape[0], -1),
+            axis=-1
+        )
+        f = f[to_keep, ...]
+        z = z[to_keep]
+        z, uni = np.unique(z, return_index=True)
+        f = f[uni, ...]
+
+        self._shape = f.shape[1:]
+        self._support_points, self._support_values, self.weights = (
+            self._compute_weights(z, f, **kwargs)
+        )
+
+        # only compute once
+        self._poles = None
+        self._residues = None
+        self._roots = None
+
+    def _input_validation(self, x, y, **kwargs):
+        if x.ndim != 1:
+            raise ValueError("`x` must be 1-D.")
+
+        if not y.ndim >= 1:
+            raise ValueError("`y` must be at least 1-D.")
+
+        if x.size != y.shape[0]:
+            raise ValueError("`x` be the same size as the first dimension of `y`.")
+
+        if not np.all(np.isfinite(x)):
+            raise ValueError("`x` must be finite.")
+
+    def _compute_weights(z, f, **kwargs):
+        raise NotImplementedError
+
+    def __call__(self, z):
+        """Evaluate the rational approximation at given values.
+
+        Parameters
+        ----------
+        z : array_like
+            Input values.
+        """
+        # evaluate rational function in barycentric form.
+        z = np.asarray(z)
+        zv = np.ravel(z)
+
+        support_values = self._support_values.reshape(
+            (self._support_values.shape[0], -1)
+        )
+        weights = self.weights[..., np.newaxis]
+
+        # Cauchy matrix
+        # Ignore errors due to inf/inf at support points, these will be fixed later
+        with np.errstate(invalid="ignore", divide="ignore"):
+            CC = 1 / np.subtract.outer(zv, self._support_points)
+            # Vector of values
+            r = CC @ (weights * support_values) / (CC @ weights)
+
+        # Deal with input inf: `r(inf) = lim r(z) = sum(w*f) / sum(w)`
+        if np.any(np.isinf(zv)):
+            r[np.isinf(zv)] = (np.sum(weights * support_values)
+                               / np.sum(weights))
+
+        # Deal with NaN
+        ii = np.nonzero(np.isnan(r))[0]
+        for jj in ii:
+            if np.isnan(zv[jj]) or not np.any(zv[jj] == self._support_points):
+                # r(NaN) = NaN is fine.
+                # The second case may happen if `r(zv[ii]) = 0/0` at some point.
+                pass
+            else:
+                # Clean up values `NaN = inf/inf` at support points.
+                # Find the corresponding node and set entry to correct value:
+                r[jj] = support_values[zv[jj] == self._support_points].squeeze()
+
+        return np.reshape(r, z.shape + self._shape)
+
+    def poles(self):
+        """Compute the poles of the rational approximation.
+
+        Returns
+        -------
+        poles : array
+            Poles of the AAA approximation, repeated according to their multiplicity
+            but not in any specific order.
+        """
+        if self._poles is None:
+            # Compute poles via generalized eigenvalue problem
+            m = self.weights.size
+            B = np.eye(m + 1, dtype=self.weights.dtype)
+            B[0, 0] = 0
+
+            E = np.zeros_like(B, dtype=np.result_type(self.weights,
+                                                      self._support_points))
+            E[0, 1:] = self.weights
+            E[1:, 0] = 1
+            np.fill_diagonal(E[1:, 1:], self._support_points)
+
+            pol = scipy.linalg.eigvals(E, B)
+            self._poles = pol[np.isfinite(pol)]
+        return self._poles
+
+    def residues(self):
+        """Compute the residues of the poles of the approximation.
+
+        Returns
+        -------
+        residues : array
+            Residues associated with the `poles` of the approximation
+        """
+        if self._residues is None:
+            # Compute residues via formula for res of quotient of analytic functions
+            with np.errstate(divide="ignore", invalid="ignore"):
+                N = (1/(np.subtract.outer(self.poles(), self._support_points))) @ (
+                    self._support_values * self.weights
+                )
+                Ddiff = (
+                    -((1/np.subtract.outer(self.poles(), self._support_points))**2)
+                    @ self.weights
+                )
+                self._residues = N / Ddiff
+        return self._residues
+
+    def roots(self):
+        """Compute the zeros of the rational approximation.
+
+        Returns
+        -------
+        zeros : array
+            Zeros of the AAA approximation, repeated according to their multiplicity
+            but not in any specific order.
+        """
+        if self._roots is None:
+            # Compute zeros via generalized eigenvalue problem
+            m = self.weights.size
+            B = np.eye(m + 1, dtype=self.weights.dtype)
+            B[0, 0] = 0
+            E = np.zeros_like(B, dtype=np.result_type(self.weights,
+                                                      self._support_values,
+                                                      self._support_points))
+            E[0, 1:] = self.weights * self._support_values
+            E[1:, 0] = 1
+            np.fill_diagonal(E[1:, 1:], self._support_points)
+
+            zer = scipy.linalg.eigvals(E, B)
+            self._roots = zer[np.isfinite(zer)]
+        return self._roots
+
+
+class AAA(_BarycentricRational):
+    r"""
+    AAA real or complex rational approximation.
+
+    As described in [1]_, the AAA algorithm is a greedy algorithm for approximation by
+    rational functions on a real or complex set of points. The rational approximation is
+    represented in a barycentric form from which the roots (zeros), poles, and residues
+    can be computed.
+
+    Parameters
+    ----------
+    x : 1D array_like, shape (n,)
+        1-D array containing values of the independent variable. Values may be real or
+        complex but must be finite.
+    y : 1D array_like, shape (n,)
+        Function values ``f(x)``. Infinite and NaN values of `values` and
+        corresponding values of `points` will be discarded.
+    rtol : float, optional
+        Relative tolerance, defaults to ``eps**0.75``. If a small subset of the entries
+        in `values` are much larger than the rest the default tolerance may be too
+        loose. If the tolerance is too tight then the approximation may contain
+        Froissart doublets or the algorithm may fail to converge entirely.
+    max_terms : int, optional
+        Maximum number of terms in the barycentric representation, defaults to ``100``.
+        Must be greater than or equal to one.
+    clean_up : bool, optional
+        Automatic removal of Froissart doublets, defaults to ``True``. See notes for
+        more details.
+    clean_up_tol : float, optional
+        Poles with residues less than this number times the geometric mean
+        of `values` times the minimum distance to `points` are deemed spurious by the
+        cleanup procedure, defaults to 1e-13. See notes for more details.
+
+    Attributes
+    ----------
+    support_points : array
+        Support points of the approximation. These are a subset of the provided `x` at
+        which the approximation strictly interpolates `y`.
+        See notes for more details.
+    support_values : array
+        Value of the approximation at the `support_points`.
+    weights : array
+        Weights of the barycentric approximation.
+    errors : array
+        Error :math:`|f(z) - r(z)|_\infty` over `points` in the successive iterations
+        of AAA.
+
+    Warns
+    -----
+    RuntimeWarning
+        If `rtol` is not achieved in `max_terms` iterations.
+
+    See Also
+    --------
+    FloaterHormannInterpolator : Floater-Hormann barycentric rational interpolation.
+    pade : Padé approximation.
+
+    Notes
+    -----
+    At iteration :math:`m` (at which point there are :math:`m` terms in the both the
+    numerator and denominator of the approximation), the
+    rational approximation in the AAA algorithm takes the barycentric form
+
+    .. math::
+
+        r(z) = n(z)/d(z) =
+        \frac{\sum_{j=1}^m\ w_j f_j / (z - z_j)}{\sum_{j=1}^m w_j / (z - z_j)},
+
+    where :math:`z_1,\dots,z_m` are real or complex support points selected from
+    `x`, :math:`f_1,\dots,f_m` are the corresponding real or complex data values
+    from `y`, and :math:`w_1,\dots,w_m` are real or complex weights.
+
+    Each iteration of the algorithm has two parts: the greedy selection the next support
+    point and the computation of the weights. The first part of each iteration is to
+    select the next support point to be added :math:`z_{m+1}` from the remaining
+    unselected `x`, such that the nonlinear residual
+    :math:`|f(z_{m+1}) - n(z_{m+1})/d(z_{m+1})|` is maximised. The algorithm terminates
+    when this maximum is less than ``rtol * np.linalg.norm(f, ord=np.inf)``. This means
+    the interpolation property is only satisfied up to a tolerance, except at the
+    support points where approximation exactly interpolates the supplied data.
+
+    In the second part of each iteration, the weights :math:`w_j` are selected to solve
+    the least-squares problem
+
+    .. math::
+
+        \text{minimise}_{w_j}|fd - n| \quad \text{subject to} \quad
+        \sum_{j=1}^{m+1} w_j = 1,
+
+    over the unselected elements of `x`.
+
+    One of the challenges with working with rational approximations is the presence of
+    Froissart doublets, which are either poles with vanishingly small residues or
+    pole-zero pairs that are close enough together to nearly cancel, see [2]_. The
+    greedy nature of the AAA algorithm means Froissart doublets are rare. However, if
+    `rtol` is set too tight then the approximation will stagnate and many Froissart
+    doublets will appear. Froissart doublets can usually be removed by removing support
+    points and then resolving the least squares problem. The support point :math:`z_j`,
+    which is the closest support point to the pole :math:`a` with residue
+    :math:`\alpha`, is removed if the following is satisfied
+
+    .. math::
+
+        |\alpha| / |z_j - a| < \verb|clean_up_tol| \cdot \tilde{f},
+
+    where :math:`\tilde{f}` is the geometric mean of `support_values`.
+
+
+    References
+    ----------
+    .. [1] Y. Nakatsukasa, O. Sete, and L. N. Trefethen, "The AAA algorithm for
+            rational approximation", SIAM J. Sci. Comp. 40 (2018), A1494-A1522.
+            :doi:`10.1137/16M1106122`
+    .. [2] J. Gilewicz and M. Pindor, Pade approximants and noise: rational functions,
+           J. Comp. Appl. Math. 105 (1999), pp. 285-297.
+           :doi:`10.1016/S0377-0427(02)00674-X`
+
+    Examples
+    --------
+
+    Here we reproduce a number of the numerical examples from [1]_ as a demonstration
+    of the functionality offered by this method.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import AAA
+    >>> import warnings
+
+    For the first example we approximate the gamma function on ``[-3.5, 4.5]`` by
+    extrapolating from 100 samples in ``[-1.5, 1.5]``.
+
+    >>> from scipy.special import gamma
+    >>> sample_points = np.linspace(-1.5, 1.5, num=100)
+    >>> r = AAA(sample_points, gamma(sample_points))
+    >>> z = np.linspace(-3.5, 4.5, num=1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(z, gamma(z), label="Gamma")
+    >>> ax.plot(sample_points, gamma(sample_points), label="Sample points")
+    >>> ax.plot(z, r(z).real, '--', label="AAA approximation")
+    >>> ax.set(xlabel="z", ylabel="r(z)", ylim=[-8, 8], xlim=[-3.5, 4.5])
+    >>> ax.legend()
+    >>> plt.show()
+
+    We can also view the poles of the rational approximation and their residues:
+
+    >>> order = np.argsort(r.poles())
+    >>> r.poles()[order]
+    array([-3.81591039e+00+0.j        , -3.00269049e+00+0.j        ,
+           -1.99999988e+00+0.j        , -1.00000000e+00+0.j        ,
+            5.85842812e-17+0.j        ,  4.77485458e+00-3.06919376j,
+            4.77485458e+00+3.06919376j,  5.29095868e+00-0.97373072j,
+            5.29095868e+00+0.97373072j])
+    >>> r.residues()[order]
+    array([ 0.03658074 +0.j        , -0.16915426 -0.j        ,
+            0.49999915 +0.j        , -1.         +0.j        ,
+            1.         +0.j        , -0.81132013 -2.30193429j,
+           -0.81132013 +2.30193429j,  0.87326839+10.70148546j,
+            0.87326839-10.70148546j])
+
+    For the second example, we call `AAA` with a spiral of 1000 points that wind 7.5
+    times around the origin in the complex plane.
+
+    >>> z = np.exp(np.linspace(-0.5, 0.5 + 15j*np.pi, 1000))
+    >>> r = AAA(z, np.tan(np.pi*z/2), rtol=1e-13)
+
+    We see that AAA takes 12 steps to converge with the following errors:
+
+    >>> r.errors.size
+    12
+    >>> r.errors
+    array([2.49261500e+01, 4.28045609e+01, 1.71346935e+01, 8.65055336e-02,
+           1.27106444e-02, 9.90889874e-04, 5.86910543e-05, 1.28735561e-06,
+           3.57007424e-08, 6.37007837e-10, 1.67103357e-11, 1.17112299e-13])
+
+    We can also plot the computed poles:
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(z.real, z.imag, '.', markersize=2, label="Sample points")
+    >>> ax.plot(r.poles().real, r.poles().imag, '.', markersize=5,
+    ...         label="Computed poles")
+    >>> ax.set(xlim=[-3.5, 3.5], ylim=[-3.5, 3.5], aspect="equal")
+    >>> ax.legend()
+    >>> plt.show()
+
+    We now demonstrate the removal of Froissart doublets using the `clean_up` method
+    using an example from [1]_. Here we approximate the function
+    :math:`f(z)=\log(2 + z^4)/(1 + 16z^4)` by sampling it at 1000 roots of unity. The
+    algorithm is run with ``rtol=0`` and ``clean_up=False`` to deliberately cause
+    Froissart doublets to appear.
+
+    >>> z = np.exp(1j*2*np.pi*np.linspace(0,1, num=1000))
+    >>> def f(z):
+    ...     return np.log(2 + z**4)/(1 - 16*z**4)
+    >>> with warnings.catch_warnings():  # filter convergence warning due to rtol=0
+    ...     warnings.simplefilter('ignore', RuntimeWarning)
+    ...     r = AAA(z, f(z), rtol=0, max_terms=50, clean_up=False)
+    >>> mask = np.abs(r.residues()) < 1e-13
+    >>> fig, axs = plt.subplots(ncols=2)
+    >>> axs[0].plot(r.poles().real[~mask], r.poles().imag[~mask], '.')
+    >>> axs[0].plot(r.poles().real[mask], r.poles().imag[mask], 'r.')
+
+    Now we call the `clean_up` method to remove Froissart doublets.
+
+    >>> with warnings.catch_warnings():
+    ...     warnings.simplefilter('ignore', RuntimeWarning)
+    ...     r.clean_up()
+    4
+    >>> mask = np.abs(r.residues()) < 1e-13
+    >>> axs[1].plot(r.poles().real[~mask], r.poles().imag[~mask], '.')
+    >>> axs[1].plot(r.poles().real[mask], r.poles().imag[mask], 'r.')
+    >>> plt.show()
+
+    The left image shows the poles prior of the approximation ``clean_up=False`` with
+    poles with residue less than ``10^-13`` in absolute value shown in red. The right
+    image then shows the poles after the `clean_up` method has been called.
+    """
+    def __init__(self, x, y, *, rtol=None, max_terms=100, clean_up=True,
+                 clean_up_tol=1e-13):
+        super().__init__(x, y, rtol=rtol, max_terms=max_terms)
+
+        if clean_up:
+            self.clean_up(clean_up_tol)
+
+    def _input_validation(self, x, y, rtol=None, max_terms=100, clean_up=True,
+                          clean_up_tol=1e-13):
+        max_terms = operator.index(max_terms)
+        if max_terms < 1:
+            raise ValueError("`max_terms` must be an integer value greater than or "
+                             "equal to one.")
+
+        if y.ndim != 1:
+            raise ValueError("`y` must be 1-D.")
+
+        super()._input_validation(x, y)
+
+    @property
+    def support_points(self):
+        return self._support_points
+
+    @property
+    def support_values(self):
+        return self._support_values
+
+    def _compute_weights(self, z, f, rtol, max_terms):
+        # Initialization for AAA iteration
+        M = np.size(z)
+        mask = np.ones(M, dtype=np.bool_)
+        dtype = np.result_type(z, f, 1.0)
+        rtol = np.finfo(dtype).eps**0.75 if rtol is None else rtol
+        atol = rtol * np.linalg.norm(f, ord=np.inf)
+        zj = np.empty(max_terms, dtype=dtype)
+        fj = np.empty(max_terms, dtype=dtype)
+        # Cauchy matrix
+        C = np.empty((M, max_terms), dtype=dtype)
+        # Loewner matrix
+        A = np.empty((M, max_terms), dtype=dtype)
+        errors = np.empty(max_terms, dtype=A.real.dtype)
+        R = np.repeat(np.mean(f), M)
+
+        # AAA iteration
+        for m in range(max_terms):
+            # Introduce next support point
+            # Select next support point
+            jj = np.argmax(np.abs(f[mask] - R[mask]))
+            # Update support points
+            zj[m] = z[mask][jj]
+            # Update data values
+            fj[m] = f[mask][jj]
+            # Next column of Cauchy matrix
+            # Ignore errors as we manually interpolate at support points
+            with np.errstate(divide="ignore", invalid="ignore"):
+                C[:, m] = 1 / (z - z[mask][jj])
+            # Update mask
+            mask[np.nonzero(mask)[0][jj]] = False
+            # Update Loewner matrix
+            # Ignore errors as inf values will be masked out in SVD call
+            with np.errstate(invalid="ignore"):
+                A[:, m] = (f - fj[m]) * C[:, m]
+
+            # Compute weights
+            rows = mask.sum()
+            if rows >= m + 1:
+                # The usual tall-skinny case
+                _, s, V = scipy.linalg.svd(
+                    A[mask, : m + 1], full_matrices=False, check_finite=False,
+                )
+                # Treat case of multiple min singular values
+                mm = s == np.min(s)
+                # Aim for non-sparse weight vector
+                wj = (V.conj()[mm, :].sum(axis=0) / np.sqrt(mm.sum())).astype(dtype)
+            else:
+                # Fewer rows than columns
+                V = scipy.linalg.null_space(A[mask, : m + 1], check_finite=False)
+                nm = V.shape[-1]
+                # Aim for non-sparse wt vector
+                wj = V.sum(axis=-1) / np.sqrt(nm)
+
+            # Compute rational approximant
+            # Omit columns with `wj == 0`
+            i0 = wj != 0
+            # Ignore errors as we manually interpolate at support points
+            with np.errstate(invalid="ignore"):
+                # Numerator
+                N = C[:, : m + 1][:, i0] @ (wj[i0] * fj[: m + 1][i0])
+                # Denominator
+                D = C[:, : m + 1][:, i0] @ wj[i0]
+            # Interpolate at support points with `wj !=0`
+            D_inf = np.isinf(D) | np.isnan(D)
+            D[D_inf] = 1
+            N[D_inf] = f[D_inf]
+            R = N / D
+
+            # Check if converged
+            max_error = np.linalg.norm(f - R, ord=np.inf)
+            errors[m] = max_error
+            if max_error <= atol:
+                break
+
+        if m == max_terms - 1:
+            warnings.warn(f"AAA failed to converge within {max_terms} iterations.",
+                          RuntimeWarning, stacklevel=2)
+
+        # Trim off unused array allocation
+        zj = zj[: m + 1]
+        fj = fj[: m + 1]
+
+        # Remove support points with zero weight
+        i_non_zero = wj != 0
+        self.errors = errors[: m + 1]
+        self._points = z
+        self._values = f
+        return zj[i_non_zero], fj[i_non_zero], wj[i_non_zero]
+
+    def clean_up(self, cleanup_tol=1e-13):
+        """Automatic removal of Froissart doublets.
+
+        Parameters
+        ----------
+        cleanup_tol : float, optional
+            Poles with residues less than this number times the geometric mean
+            of `values` times the minimum distance to `points` are deemed spurious by
+            the cleanup procedure, defaults to 1e-13.
+
+        Returns
+        -------
+        int
+            Number of Froissart doublets detected
+        """
+        # Find negligible residues
+        geom_mean_abs_f = scipy.stats.gmean(np.abs(self._values))
+
+        Z_distances = np.min(
+            np.abs(np.subtract.outer(self.poles(), self._points)), axis=1
+        )
+
+        with np.errstate(divide="ignore", invalid="ignore"):
+            ii = np.nonzero(
+                np.abs(self.residues()) / Z_distances < cleanup_tol * geom_mean_abs_f
+            )
+
+        ni = ii[0].size
+        if ni == 0:
+            return ni
+
+        warnings.warn(f"{ni} Froissart doublets detected.", RuntimeWarning,
+                        stacklevel=2)
+
+        # For each spurious pole find and remove closest support point
+        closest_spt_point = np.argmin(
+            np.abs(np.subtract.outer(self._support_points, self.poles()[ii])), axis=0
+        )
+        self._support_points = np.delete(self._support_points, closest_spt_point)
+        self._support_values = np.delete(self._support_values, closest_spt_point)
+
+        # Remove support points z from sample set
+        mask = np.logical_and.reduce(
+            np.not_equal.outer(self._points, self._support_points), axis=1
+        )
+        f = self._values[mask]
+        z = self._points[mask]
+
+        # recompute weights, we resolve the least squares problem for the remaining
+        # support points
+
+        m = self._support_points.size
+
+        # Cauchy matrix
+        C = 1 / np.subtract.outer(z, self._support_points)
+        # Loewner matrix
+        A = f[:, np.newaxis] * C - C * self._support_values
+
+        # Solve least-squares problem to obtain weights
+        _, _, V = scipy.linalg.svd(A, check_finite=False)
+        self.weights = np.conj(V[m - 1,:])
+
+        # reset roots, poles, residues as cached values will be wrong with new weights
+        self._poles = None
+        self._residues = None
+        self._roots = None
+
+        return ni
+
+
+class FloaterHormannInterpolator(_BarycentricRational):
+    r"""
+    Floater-Hormann barycentric rational interpolation.
+
+    As described in [1]_, the method of Floater and Hormann computes weights for a
+    Barycentric rational interpolant with no poles on the real axis.
+
+    Parameters
+    ----------
+    x : 1D array_like, shape (n,)
+        1-D array containing values of the independent variable. Values may be real or
+        complex but must be finite.
+    y : array_like, shape (n, ...)
+        Array containing values of the dependent variable. Infinite and NaN values
+        of `values` and corresponding values of `x` will be discarded.
+    d : int, optional
+        Blends ``n - d`` degree `d` polynomials together. For ``d = n - 1`` it is
+        equivalent to polynomial interpolation. Must satisfy ``0 <= d < n``,
+        defaults to 3.
+
+    Attributes
+    ----------
+    weights : array
+        Weights of the barycentric approximation.
+
+    See Also
+    --------
+    AAA : Barycentric rational approximation of real and complex functions.
+    pade : Padé approximation.
+
+    Notes
+    -----
+    The Floater-Hormann interpolant is a rational function that interpolates the data
+    with approximation order :math:`O(h^{d+1})`. The rational function blends ``n - d``
+    polynomials of degree `d` together to produce a rational interpolant that contains
+    no poles on the real axis, unlike `AAA`. The interpolant is given
+    by
+
+    .. math::
+
+        r(x) = \frac{\sum_{i=0}^{n-d} \lambda_i(x) p_i(x)}
+        {\sum_{i=0}^{n-d} \lambda_i(x)},
+
+    where :math:`p_i(x)` is an interpolating polynomials of at most degree `d` through
+    the points :math:`(x_i,y_i),\dots,(x_{i+d},y_{i+d}), and :math:`\lambda_i(z)` are
+    blending functions defined by
+
+    .. math::
+
+        \lambda_i(x) = \frac{(-1)^i}{(x - x_i)\cdots(x - x_{i+d})}.
+
+    When ``d = n - 1`` this reduces to polynomial interpolation.
+
+    Due to its stability following barycentric representation of the above equation
+    is used instead for computation
+
+    .. math::
+
+        r(z) = \frac{\sum_{k=1}^m\ w_k f_k / (x - x_k)}{\sum_{k=1}^m w_k / (x - x_k)},
+
+    where the weights :math:`w_j` are computed as
+
+    .. math::
+
+        w_k &= (-1)^{k - d} \sum_{i \in J_k} \prod_{j = i, j \neq k}^{i + d}
+        1/|x_k - x_j|, \\
+        J_k &= \{ i \in I: k - d \leq i \leq k\},\\
+        I &= \{0, 1, \dots, n - d\}.
+
+    References
+    ----------
+    .. [1] M.S. Floater and K. Hormann, "Barycentric rational interpolation with no
+           poles and high rates of approximation", Numer. Math. 107, 315 (2007).
+           :doi:`10.1007/s00211-007-0093-y`
+
+    Examples
+    --------
+
+    Here we compare the method against polynomial interpolation for an example where
+    the polynomial interpolation fails due to Runge's phenomenon.
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import (FloaterHormannInterpolator,
+    ...                                BarycentricInterpolator)
+    >>> def f(z):
+    ...     return 1/(1 + z**2)
+    >>> z = np.linspace(-5, 5, num=15)
+    >>> r = FloaterHormannInterpolator(z, f(z))
+    >>> p = BarycentricInterpolator(z, f(z))
+    >>> zz = np.linspace(-5, 5, num=1000)
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(zz, r(zz), label="Floater=Hormann")
+    >>> ax.plot(zz, p(zz), label="Polynomial")
+    >>> ax.legend()
+    >>> plt.show()
+    """
+    def __init__(self, points, values, *, d=3):
+        super().__init__(points, values, d=d)
+
+    def _input_validation(self, x, y, d):
+        d = operator.index(d)
+        if not (0 <= d < len(x)):
+            raise ValueError("`d` must satisfy 0 <= d < n")
+
+        super()._input_validation(x, y)
+
+    def _compute_weights(self, z, f, d):
+        # Floater and Hormann 2007 Eqn. (18) 3 equations later
+        w = np.zeros_like(z, dtype=np.result_type(z, 1.0))
+        n = w.size
+        for k in range(n):
+            for i in range(max(k-d, 0), min(k+1, n-d)):
+                w[k] += 1/np.prod(np.abs(np.delete(z[k] - z[i : i + d + 1], k - i)))
+        w *= (-1.)**(np.arange(n) - d)
+
+        return z, f, w
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d68e8d532100f4926328d68cb68d1048f4290e8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py
@@ -0,0 +1,2416 @@
+import operator
+from math import prod
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+from scipy.linalg import (get_lapack_funcs, LinAlgError,
+                          cholesky_banded, cho_solve_banded,
+                          solve, solve_banded)
+from scipy.optimize import minimize_scalar
+from . import _dierckx
+from . import _fitpack_impl
+from scipy.sparse import csr_array
+from scipy.special import poch
+from itertools import combinations
+
+
+__all__ = ["BSpline", "make_interp_spline", "make_lsq_spline",
+           "make_smoothing_spline"]
+
+
+def _get_dtype(dtype):
+    """Return np.complex128 for complex dtypes, np.float64 otherwise."""
+    if np.issubdtype(dtype, np.complexfloating):
+        return np.complex128
+    else:
+        return np.float64
+
+
+def _as_float_array(x, check_finite=False):
+    """Convert the input into a C contiguous float array.
+
+    NB: Upcasts half- and single-precision floats to double precision.
+    """
+    x = np.ascontiguousarray(x)
+    dtyp = _get_dtype(x.dtype)
+    x = x.astype(dtyp, copy=False)
+    if check_finite and not np.isfinite(x).all():
+        raise ValueError("Array must not contain infs or nans.")
+    return x
+
+
+def _dual_poly(j, k, t, y):
+    """
+    Dual polynomial of the B-spline B_{j,k,t} -
+    polynomial which is associated with B_{j,k,t}:
+    $p_{j,k}(y) = (y - t_{j+1})(y - t_{j+2})...(y - t_{j+k})$
+    """
+    if k == 0:
+        return 1
+    return np.prod([(y - t[j + i]) for i in range(1, k + 1)])
+
+
+def _diff_dual_poly(j, k, y, d, t):
+    """
+    d-th derivative of the dual polynomial $p_{j,k}(y)$
+    """
+    if d == 0:
+        return _dual_poly(j, k, t, y)
+    if d == k:
+        return poch(1, k)
+    comb = list(combinations(range(j + 1, j + k + 1), d))
+    res = 0
+    for i in range(len(comb) * len(comb[0])):
+        res += np.prod([(y - t[j + p]) for p in range(1, k + 1)
+                        if (j + p) not in comb[i//d]])
+    return res
+
+
+class BSpline:
+    r"""Univariate spline in the B-spline basis.
+
+    .. math::
+
+        S(x) = \sum_{j=0}^{n-1} c_j  B_{j, k; t}(x)
+
+    where :math:`B_{j, k; t}` are B-spline basis functions of degree `k`
+    and knots `t`.
+
+    Parameters
+    ----------
+    t : ndarray, shape (n+k+1,)
+        knots
+    c : ndarray, shape (>=n, ...)
+        spline coefficients
+    k : int
+        B-spline degree
+    extrapolate : bool or 'periodic', optional
+        whether to extrapolate beyond the base interval, ``t[k] .. t[n]``,
+        or to return nans.
+        If True, extrapolates the first and last polynomial pieces of b-spline
+        functions active on the base interval.
+        If 'periodic', periodic extrapolation is used.
+        Default is True.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+
+    Attributes
+    ----------
+    t : ndarray
+        knot vector
+    c : ndarray
+        spline coefficients
+    k : int
+        spline degree
+    extrapolate : bool
+        If True, extrapolates the first and last polynomial pieces of b-spline
+        functions active on the base interval.
+    axis : int
+        Interpolation axis.
+    tck : tuple
+        A read-only equivalent of ``(self.t, self.c, self.k)``
+
+    Methods
+    -------
+    __call__
+    basis_element
+    derivative
+    antiderivative
+    integrate
+    insert_knot
+    construct_fast
+    design_matrix
+    from_power_basis
+
+    Notes
+    -----
+    B-spline basis elements are defined via
+
+    .. math::
+
+        B_{i, 0}(x) = 1, \textrm{if $t_i \le x < t_{i+1}$, otherwise $0$,}
+
+        B_{i, k}(x) = \frac{x - t_i}{t_{i+k} - t_i} B_{i, k-1}(x)
+                 + \frac{t_{i+k+1} - x}{t_{i+k+1} - t_{i+1}} B_{i+1, k-1}(x)
+
+    **Implementation details**
+
+    - At least ``k+1`` coefficients are required for a spline of degree `k`,
+      so that ``n >= k+1``. Additional coefficients, ``c[j]`` with
+      ``j > n``, are ignored.
+
+    - B-spline basis elements of degree `k` form a partition of unity on the
+      *base interval*, ``t[k] <= x <= t[n]``.
+
+
+    Examples
+    --------
+
+    Translating the recursive definition of B-splines into Python code, we have:
+
+    >>> def B(x, k, i, t):
+    ...    if k == 0:
+    ...       return 1.0 if t[i] <= x < t[i+1] else 0.0
+    ...    if t[i+k] == t[i]:
+    ...       c1 = 0.0
+    ...    else:
+    ...       c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t)
+    ...    if t[i+k+1] == t[i+1]:
+    ...       c2 = 0.0
+    ...    else:
+    ...       c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t)
+    ...    return c1 + c2
+
+    >>> def bspline(x, t, c, k):
+    ...    n = len(t) - k - 1
+    ...    assert (n >= k+1) and (len(c) >= n)
+    ...    return sum(c[i] * B(x, k, i, t) for i in range(n))
+
+    Note that this is an inefficient (if straightforward) way to
+    evaluate B-splines --- this spline class does it in an equivalent,
+    but much more efficient way.
+
+    Here we construct a quadratic spline function on the base interval
+    ``2 <= x <= 4`` and compare with the naive way of evaluating the spline:
+
+    >>> from scipy.interpolate import BSpline
+    >>> k = 2
+    >>> t = [0, 1, 2, 3, 4, 5, 6]
+    >>> c = [-1, 2, 0, -1]
+    >>> spl = BSpline(t, c, k)
+    >>> spl(2.5)
+    array(1.375)
+    >>> bspline(2.5, t, c, k)
+    1.375
+
+    Note that outside of the base interval results differ. This is because
+    `BSpline` extrapolates the first and last polynomial pieces of B-spline
+    functions active on the base interval.
+
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> fig, ax = plt.subplots()
+    >>> xx = np.linspace(1.5, 4.5, 50)
+    >>> ax.plot(xx, [bspline(x, t, c ,k) for x in xx], 'r-', lw=3, label='naive')
+    >>> ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline')
+    >>> ax.grid(True)
+    >>> ax.legend(loc='best')
+    >>> plt.show()
+
+
+    References
+    ----------
+    .. [1] Tom Lyche and Knut Morken, Spline methods,
+        http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/
+    .. [2] Carl de Boor, A practical guide to splines, Springer, 2001.
+
+    """
+
+    def __init__(self, t, c, k, extrapolate=True, axis=0):
+        super().__init__()
+
+        self.k = operator.index(k)
+        self.c = np.asarray(c)
+        self.t = np.ascontiguousarray(t, dtype=np.float64)
+
+        if extrapolate == 'periodic':
+            self.extrapolate = extrapolate
+        else:
+            self.extrapolate = bool(extrapolate)
+
+        n = self.t.shape[0] - self.k - 1
+
+        axis = normalize_axis_index(axis, self.c.ndim)
+
+        # Note that the normalized axis is stored in the object.
+        self.axis = axis
+        if axis != 0:
+            # roll the interpolation axis to be the first one in self.c
+            # More specifically, the target shape for self.c is (n, ...),
+            # and axis !=0 means that we have c.shape (..., n, ...)
+            #                                               ^
+            #                                              axis
+            self.c = np.moveaxis(self.c, axis, 0)
+
+        if k < 0:
+            raise ValueError("Spline order cannot be negative.")
+        if self.t.ndim != 1:
+            raise ValueError("Knot vector must be one-dimensional.")
+        if n < self.k + 1:
+            raise ValueError("Need at least %d knots for degree %d" %
+                             (2*k + 2, k))
+        if (np.diff(self.t) < 0).any():
+            raise ValueError("Knots must be in a non-decreasing order.")
+        if len(np.unique(self.t[k:n+1])) < 2:
+            raise ValueError("Need at least two internal knots.")
+        if not np.isfinite(self.t).all():
+            raise ValueError("Knots should not have nans or infs.")
+        if self.c.ndim < 1:
+            raise ValueError("Coefficients must be at least 1-dimensional.")
+        if self.c.shape[0] < n:
+            raise ValueError("Knots, coefficients and degree are inconsistent.")
+
+        dt = _get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dt)
+
+    @classmethod
+    def construct_fast(cls, t, c, k, extrapolate=True, axis=0):
+        """Construct a spline without making checks.
+
+        Accepts same parameters as the regular constructor. Input arrays
+        `t` and `c` must of correct shape and dtype.
+        """
+        self = object.__new__(cls)
+        self.t, self.c, self.k = t, c, k
+        self.extrapolate = extrapolate
+        self.axis = axis
+        return self
+
+    @property
+    def tck(self):
+        """Equivalent to ``(self.t, self.c, self.k)`` (read-only).
+        """
+        return self.t, self.c, self.k
+
+    @classmethod
+    def basis_element(cls, t, extrapolate=True):
+        """Return a B-spline basis element ``B(x | t[0], ..., t[k+1])``.
+
+        Parameters
+        ----------
+        t : ndarray, shape (k+2,)
+            internal knots
+        extrapolate : bool or 'periodic', optional
+            whether to extrapolate beyond the base interval, ``t[0] .. t[k+1]``,
+            or to return nans.
+            If 'periodic', periodic extrapolation is used.
+            Default is True.
+
+        Returns
+        -------
+        basis_element : callable
+            A callable representing a B-spline basis element for the knot
+            vector `t`.
+
+        Notes
+        -----
+        The degree of the B-spline, `k`, is inferred from the length of `t` as
+        ``len(t)-2``. The knot vector is constructed by appending and prepending
+        ``k+1`` elements to internal knots `t`.
+
+        Examples
+        --------
+
+        Construct a cubic B-spline:
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import BSpline
+        >>> b = BSpline.basis_element([0, 1, 2, 3, 4])
+        >>> k = b.k
+        >>> b.t[k:-k]
+        array([ 0.,  1.,  2.,  3.,  4.])
+        >>> k
+        3
+
+        Construct a quadratic B-spline on ``[0, 1, 1, 2]``, and compare
+        to its explicit form:
+
+        >>> t = [0, 1, 1, 2]
+        >>> b = BSpline.basis_element(t)
+        >>> def f(x):
+        ...     return np.where(x < 1, x*x, (2. - x)**2)
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig, ax = plt.subplots()
+        >>> x = np.linspace(0, 2, 51)
+        >>> ax.plot(x, b(x), 'g', lw=3)
+        >>> ax.plot(x, f(x), 'r', lw=8, alpha=0.4)
+        >>> ax.grid(True)
+        >>> plt.show()
+
+        """
+        k = len(t) - 2
+        t = _as_float_array(t)
+        t = np.r_[(t[0]-1,) * k, t, (t[-1]+1,) * k]
+        c = np.zeros_like(t)
+        c[k] = 1.
+        return cls.construct_fast(t, c, k, extrapolate)
+
+    @classmethod
+    def design_matrix(cls, x, t, k, extrapolate=False):
+        """
+        Returns a design matrix as a CSR format sparse array.
+
+        Parameters
+        ----------
+        x : array_like, shape (n,)
+            Points to evaluate the spline at.
+        t : array_like, shape (nt,)
+            Sorted 1D array of knots.
+        k : int
+            B-spline degree.
+        extrapolate : bool or 'periodic', optional
+            Whether to extrapolate based on the first and last intervals
+            or raise an error. If 'periodic', periodic extrapolation is used.
+            Default is False.
+
+            .. versionadded:: 1.10.0
+
+        Returns
+        -------
+        design_matrix : `csr_array` object
+            Sparse matrix in CSR format where each row contains all the basis
+            elements of the input row (first row = basis elements of x[0],
+            ..., last row = basis elements x[-1]).
+
+        Examples
+        --------
+        Construct a design matrix for a B-spline
+
+        >>> from scipy.interpolate import make_interp_spline, BSpline
+        >>> import numpy as np
+        >>> x = np.linspace(0, np.pi * 2, 4)
+        >>> y = np.sin(x)
+        >>> k = 3
+        >>> bspl = make_interp_spline(x, y, k=k)
+        >>> design_matrix = bspl.design_matrix(x, bspl.t, k)
+        >>> design_matrix.toarray()
+        [[1.        , 0.        , 0.        , 0.        ],
+        [0.2962963 , 0.44444444, 0.22222222, 0.03703704],
+        [0.03703704, 0.22222222, 0.44444444, 0.2962963 ],
+        [0.        , 0.        , 0.        , 1.        ]]
+
+        Construct a design matrix for some vector of knots
+
+        >>> k = 2
+        >>> t = [-1, 0, 1, 2, 3, 4, 5, 6]
+        >>> x = [1, 2, 3, 4]
+        >>> design_matrix = BSpline.design_matrix(x, t, k).toarray()
+        >>> design_matrix
+        [[0.5, 0.5, 0. , 0. , 0. ],
+        [0. , 0.5, 0.5, 0. , 0. ],
+        [0. , 0. , 0.5, 0.5, 0. ],
+        [0. , 0. , 0. , 0.5, 0.5]]
+
+        This result is equivalent to the one created in the sparse format
+
+        >>> c = np.eye(len(t) - k - 1)
+        >>> design_matrix_gh = BSpline(t, c, k)(x)
+        >>> np.allclose(design_matrix, design_matrix_gh, atol=1e-14)
+        True
+
+        Notes
+        -----
+        .. versionadded:: 1.8.0
+
+        In each row of the design matrix all the basis elements are evaluated
+        at the certain point (first row - x[0], ..., last row - x[-1]).
+
+        `nt` is a length of the vector of knots: as far as there are
+        `nt - k - 1` basis elements, `nt` should be not less than `2 * k + 2`
+        to have at least `k + 1` basis element.
+
+        Out of bounds `x` raises a ValueError.
+        """
+        x = _as_float_array(x, True)
+        t = _as_float_array(t, True)
+
+        if extrapolate != 'periodic':
+            extrapolate = bool(extrapolate)
+
+        if k < 0:
+            raise ValueError("Spline order cannot be negative.")
+        if t.ndim != 1 or np.any(t[1:] < t[:-1]):
+            raise ValueError(f"Expect t to be a 1-D sorted array_like, but "
+                             f"got t={t}.")
+        # There are `nt - k - 1` basis elements in a BSpline built on the
+        # vector of knots with length `nt`, so to have at least `k + 1` basis
+        # elements we need to have at least `2 * k + 2` elements in the vector
+        # of knots.
+        if len(t) < 2 * k + 2:
+            raise ValueError(f"Length t is not enough for k={k}.")
+
+        if extrapolate == 'periodic':
+            # With periodic extrapolation we map x to the segment
+            # [t[k], t[n]].
+            n = t.size - k - 1
+            x = t[k] + (x - t[k]) % (t[n] - t[k])
+            extrapolate = False
+        elif not extrapolate and (
+            (min(x) < t[k]) or (max(x) > t[t.shape[0] - k - 1])
+        ):
+            # Checks from `find_interval` function
+            raise ValueError(f'Out of bounds w/ x = {x}.')
+
+        # Compute number of non-zeros of final CSR array in order to determine
+        # the dtype of indices and indptr of the CSR array.
+        n = x.shape[0]
+        nnz = n * (k + 1)
+        if nnz < np.iinfo(np.int32).max:
+            int_dtype = np.int32
+        else:
+            int_dtype = np.int64
+
+        # Get the non-zero elements of the design matrix and per-row `offsets`:
+        # In row `i`, k+1 nonzero elements are consecutive, and start from `offset[i]`
+        data, offsets, _ = _dierckx.data_matrix(x, t, k, np.ones_like(x), extrapolate)
+        data = data.ravel()
+
+        if offsets.dtype != int_dtype:
+            offsets = offsets.astype(int_dtype)
+
+        # Convert from per-row offsets to the CSR indices/indptr format
+        indices = np.repeat(offsets, k+1).reshape(-1, k+1)
+        indices = indices + np.arange(k+1, dtype=int_dtype)
+        indices = indices.ravel()
+
+        indptr = np.arange(0, (n + 1) * (k + 1), k + 1, dtype=int_dtype)
+
+        return csr_array(
+            (data, indices, indptr),
+            shape=(x.shape[0], t.shape[0] - k - 1)
+        )
+
+    def __call__(self, x, nu=0, extrapolate=None):
+        """
+        Evaluate a spline function.
+
+        Parameters
+        ----------
+        x : array_like
+            points to evaluate the spline at.
+        nu : int, optional
+            derivative to evaluate (default is 0).
+        extrapolate : bool or 'periodic', optional
+            whether to extrapolate based on the first and last intervals
+            or return nans. If 'periodic', periodic extrapolation is used.
+            Default is `self.extrapolate`.
+
+        Returns
+        -------
+        y : array_like
+            Shape is determined by replacing the interpolation axis
+            in the coefficient array with the shape of `x`.
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        x = np.asarray(x)
+        x_shape, x_ndim = x.shape, x.ndim
+        x = np.ascontiguousarray(x.ravel(), dtype=np.float64)
+
+        # With periodic extrapolation we map x to the segment
+        # [self.t[k], self.t[n]].
+        if extrapolate == 'periodic':
+            n = self.t.size - self.k - 1
+            x = self.t[self.k] + (x - self.t[self.k]) % (self.t[n] -
+                                                         self.t[self.k])
+            extrapolate = False
+
+        out = np.empty((len(x), prod(self.c.shape[1:])), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+
+        # if self.c is complex, so is `out`; cython code in _bspl.pyx expectes
+        # floats though, so make a view---this expands the last axis, and
+        # the view is C contiguous if the original is.
+        # if c.dtype is complex of shape (n,), c.view(float).shape == (2*n,)
+        # if c.dtype is complex of shape (n, m), c.view(float).shape == (n, 2*m)
+
+        cc = self.c.view(float)
+        if self.c.ndim == 1 and self.c.dtype.kind == 'c':
+            cc = cc.reshape(self.c.shape[0], 2)
+
+        _dierckx.evaluate_spline(self.t, cc.reshape(cc.shape[0], -1),
+                              self.k, x, nu, extrapolate, out.view(float))
+
+        out = out.reshape(x_shape + self.c.shape[1:])
+        if self.axis != 0:
+            # transpose to move the calculated values to the interpolation axis
+            l = list(range(out.ndim))
+            l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:]
+            out = out.transpose(l)
+        return out
+
+    def _ensure_c_contiguous(self):
+        """
+        c and t may be modified by the user. The Cython code expects
+        that they are C contiguous.
+
+        """
+        if not self.t.flags.c_contiguous:
+            self.t = self.t.copy()
+        if not self.c.flags.c_contiguous:
+            self.c = self.c.copy()
+
+    def derivative(self, nu=1):
+        """Return a B-spline representing the derivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Derivative order.
+            Default is 1.
+
+        Returns
+        -------
+        b : BSpline object
+            A new instance representing the derivative.
+
+        See Also
+        --------
+        splder, splantider
+
+        """
+        c = self.c.copy()
+        # pad the c array if needed
+        ct = len(self.t) - len(c)
+        if ct > 0:
+            c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
+        tck = _fitpack_impl.splder((self.t, c, self.k), nu)
+        return self.construct_fast(*tck, extrapolate=self.extrapolate,
+                                   axis=self.axis)
+
+    def antiderivative(self, nu=1):
+        """Return a B-spline representing the antiderivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Antiderivative order. Default is 1.
+
+        Returns
+        -------
+        b : BSpline object
+            A new instance representing the antiderivative.
+
+        Notes
+        -----
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+
+        See Also
+        --------
+        splder, splantider
+
+        """
+        c = self.c.copy()
+        # pad the c array if needed
+        ct = len(self.t) - len(c)
+        if ct > 0:
+            c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
+        tck = _fitpack_impl.splantider((self.t, c, self.k), nu)
+
+        if self.extrapolate == 'periodic':
+            extrapolate = False
+        else:
+            extrapolate = self.extrapolate
+
+        return self.construct_fast(*tck, extrapolate=extrapolate,
+                                   axis=self.axis)
+
+    def integrate(self, a, b, extrapolate=None):
+        """Compute a definite integral of the spline.
+
+        Parameters
+        ----------
+        a : float
+            Lower limit of integration.
+        b : float
+            Upper limit of integration.
+        extrapolate : bool or 'periodic', optional
+            whether to extrapolate beyond the base interval,
+            ``t[k] .. t[-k-1]``, or take the spline to be zero outside of the
+            base interval. If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        I : array_like
+            Definite integral of the spline over the interval ``[a, b]``.
+
+        Examples
+        --------
+        Construct the linear spline ``x if x < 1 else 2 - x`` on the base
+        interval :math:`[0, 2]`, and integrate it
+
+        >>> from scipy.interpolate import BSpline
+        >>> b = BSpline.basis_element([0, 1, 2])
+        >>> b.integrate(0, 1)
+        array(0.5)
+
+        If the integration limits are outside of the base interval, the result
+        is controlled by the `extrapolate` parameter
+
+        >>> b.integrate(-1, 1)
+        array(0.0)
+        >>> b.integrate(-1, 1, extrapolate=False)
+        array(0.5)
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig, ax = plt.subplots()
+        >>> ax.grid(True)
+        >>> ax.axvline(0, c='r', lw=5, alpha=0.5)  # base interval
+        >>> ax.axvline(2, c='r', lw=5, alpha=0.5)
+        >>> xx = [-1, 1, 2]
+        >>> ax.plot(xx, b(xx))
+        >>> plt.show()
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        # Prepare self.t and self.c.
+        self._ensure_c_contiguous()
+
+        # Swap integration bounds if needed.
+        sign = 1
+        if b < a:
+            a, b = b, a
+            sign = -1
+        n = self.t.size - self.k - 1
+
+        if extrapolate != "periodic" and not extrapolate:
+            # Shrink the integration interval, if needed.
+            a = max(a, self.t[self.k])
+            b = min(b, self.t[n])
+
+            if self.c.ndim == 1:
+                # Fast path: use FITPACK's routine
+                # (cf _fitpack_impl.splint).
+                integral = _fitpack_impl.splint(a, b, self.tck)
+                return np.asarray(integral * sign)
+
+        out = np.empty((2, prod(self.c.shape[1:])), dtype=self.c.dtype)
+
+        # Compute the antiderivative.
+        c = self.c
+        ct = len(self.t) - len(c)
+        if ct > 0:
+            c = np.r_[c, np.zeros((ct,) + c.shape[1:])]
+        ta, ca, ka = _fitpack_impl.splantider((self.t, c, self.k), 1)
+
+        if extrapolate == 'periodic':
+            # Split the integral into the part over period (can be several
+            # of them) and the remaining part.
+
+            ts, te = self.t[self.k], self.t[n]
+            period = te - ts
+            interval = b - a
+            n_periods, left = divmod(interval, period)
+
+            if n_periods > 0:
+                # Evaluate the difference of antiderivatives.
+                x = np.asarray([ts, te], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral = out[1] - out[0]
+                integral *= n_periods
+            else:
+                integral = np.zeros((1, prod(self.c.shape[1:])),
+                                    dtype=self.c.dtype)
+
+            # Map a to [ts, te], b is always a + left.
+            a = ts + (a - ts) % period
+            b = a + left
+
+            # If b <= te then we need to integrate over [a, b], otherwise
+            # over [a, te] and from xs to what is remained.
+            if b <= te:
+                x = np.asarray([a, b], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral += out[1] - out[0]
+            else:
+                x = np.asarray([a, te], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral += out[1] - out[0]
+
+                x = np.asarray([ts, ts + b - te], dtype=np.float64)
+                _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                      ka, x, 0, False, out)
+                integral += out[1] - out[0]
+        else:
+            # Evaluate the difference of antiderivatives.
+            x = np.asarray([a, b], dtype=np.float64)
+            _dierckx.evaluate_spline(ta, ca.reshape(ca.shape[0], -1),
+                                  ka, x, 0, extrapolate, out)
+            integral = out[1] - out[0]
+
+        integral *= sign
+        return integral.reshape(ca.shape[1:])
+
+    @classmethod
+    def from_power_basis(cls, pp, bc_type='not-a-knot'):
+        r"""
+        Construct a polynomial in the B-spline basis
+        from a piecewise polynomial in the power basis.
+
+        For now, accepts ``CubicSpline`` instances only.
+
+        Parameters
+        ----------
+        pp : CubicSpline
+            A piecewise polynomial in the power basis, as created
+            by ``CubicSpline``
+        bc_type : string, optional
+            Boundary condition type as in ``CubicSpline``: one of the
+            ``not-a-knot``, ``natural``, ``clamped``, or ``periodic``.
+            Necessary for construction an instance of ``BSpline`` class.
+            Default is ``not-a-knot``.
+
+        Returns
+        -------
+        b : BSpline object
+            A new instance representing the initial polynomial
+            in the B-spline basis.
+
+        Notes
+        -----
+        .. versionadded:: 1.8.0
+
+        Accepts only ``CubicSpline`` instances for now.
+
+        The algorithm follows from differentiation
+        the Marsden's identity [1]: each of coefficients of spline
+        interpolation function in the B-spline basis is computed as follows:
+
+        .. math::
+
+            c_j = \sum_{m=0}^{k} \frac{(k-m)!}{k!}
+                       c_{m,i} (-1)^{k-m} D^m p_{j,k}(x_i)
+
+        :math:`c_{m, i}` - a coefficient of CubicSpline,
+        :math:`D^m p_{j, k}(x_i)` - an m-th defivative of a dual polynomial
+        in :math:`x_i`.
+
+        ``k`` always equals 3 for now.
+
+        First ``n - 2`` coefficients are computed in :math:`x_i = x_j`, e.g.
+
+        .. math::
+
+            c_1 = \sum_{m=0}^{k} \frac{(k-1)!}{k!} c_{m,1} D^m p_{j,3}(x_1)
+
+        Last ``nod + 2`` coefficients are computed in ``x[-2]``,
+        ``nod`` - number of derivatives at the ends.
+
+        For example, consider :math:`x = [0, 1, 2, 3, 4]`,
+        :math:`y = [1, 1, 1, 1, 1]` and bc_type = ``natural``
+
+        The coefficients of CubicSpline in the power basis:
+
+        :math:`[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 0], [1, 1, 1, 1, 1]]`
+
+        The knot vector: :math:`t = [0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4]`
+
+        In this case
+
+        .. math::
+
+            c_j = \frac{0!}{k!} c_{3, i} k! = c_{3, i} = 1,~j = 0, ..., 6
+
+        References
+        ----------
+        .. [1] Tom Lyche and Knut Morken, Spline Methods, 2005, Section 3.1.2
+
+        """
+        from ._cubic import CubicSpline
+        if not isinstance(pp, CubicSpline):
+            raise NotImplementedError(f"Only CubicSpline objects are accepted "
+                                      f"for now. Got {type(pp)} instead.")
+        x = pp.x
+        coef = pp.c
+        k = pp.c.shape[0] - 1
+        n = x.shape[0]
+
+        if bc_type == 'not-a-knot':
+            t = _not_a_knot(x, k)
+        elif bc_type == 'natural' or bc_type == 'clamped':
+            t = _augknt(x, k)
+        elif bc_type == 'periodic':
+            t = _periodic_knots(x, k)
+        else:
+            raise TypeError(f'Unknown boundary condition: {bc_type}')
+
+        nod = t.shape[0] - (n + k + 1)  # number of derivatives at the ends
+        c = np.zeros(n + nod, dtype=pp.c.dtype)
+        for m in range(k + 1):
+            for i in range(n - 2):
+                c[i] += poch(k + 1, -m) * coef[m, i]\
+                        * np.power(-1, k - m)\
+                        * _diff_dual_poly(i, k, x[i], m, t)
+            for j in range(n - 2, n + nod):
+                c[j] += poch(k + 1, -m) * coef[m, n - 2]\
+                        * np.power(-1, k - m)\
+                        * _diff_dual_poly(j, k, x[n - 2], m, t)
+        return cls.construct_fast(t, c, k, pp.extrapolate, pp.axis)
+
+    def insert_knot(self, x, m=1):
+        """Insert a new knot at `x` of multiplicity `m`.
+
+        Given the knots and coefficients of a B-spline representation, create a
+        new B-spline with a knot inserted `m` times at point `x`.
+
+        Parameters
+        ----------
+        x : float
+            The position of the new knot
+        m : int, optional
+            The number of times to insert the given knot (its multiplicity).
+            Default is 1.
+
+        Returns
+        -------
+        spl : BSpline object
+            A new BSpline object with the new knot inserted.
+
+        Notes
+        -----
+        Based on algorithms from [1]_ and [2]_.
+
+        In case of a periodic spline (``self.extrapolate == "periodic"``)
+        there must be either at least k interior knots t(j) satisfying
+        ``t(k+1)>> import numpy as np
+        >>> from scipy.interpolate import BSpline, make_interp_spline
+        >>> x = np.linspace(0, 10, 5)
+        >>> y = np.sin(x)
+        >>> spl = make_interp_spline(x, y, k=3)
+        >>> spl.t
+        array([ 0.,  0.,  0.,  0.,  5., 10., 10., 10., 10.])
+
+        Insert a single knot
+
+        >>> spl_1 = spl.insert_knot(3)
+        >>> spl_1.t
+        array([ 0.,  0.,  0.,  0.,  3.,  5., 10., 10., 10., 10.])
+
+        Insert a multiple knot
+
+        >>> spl_2 = spl.insert_knot(8, m=3)
+        >>> spl_2.t
+        array([ 0.,  0.,  0.,  0.,  5.,  8.,  8.,  8., 10., 10., 10., 10.])
+
+        """
+        if x < self.t[self.k] or x > self.t[-self.k-1]:
+            raise ValueError(f"Cannot insert a knot at {x}.")
+        if m <= 0:
+            raise ValueError(f"`m` must be positive, got {m = }.")
+
+        tt = self.t.copy()
+        cc = self.c.copy()
+
+        for _ in range(m):
+            tt, cc = _insert(x, tt, cc, self.k, self.extrapolate == "periodic")
+        return self.construct_fast(tt, cc, self.k, self.extrapolate, self.axis)
+
+
+def _insert(xval, t, c, k, periodic=False):
+    """Insert a single knot at `xval`."""
+    #
+    # This is a port of the FORTRAN `insert` routine by P. Dierckx,
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/insert.f
+    # which carries the following comment:
+    #
+    # subroutine insert inserts a new knot x into a spline function s(x)
+    # of degree k and calculates the b-spline representation of s(x) with
+    # respect to the new set of knots. in addition, if iopt.ne.0, s(x)
+    # will be considered as a periodic spline with period per=t(n-k)-t(k+1)
+    # satisfying the boundary constraints
+    #      t(i+n-2*k-1) = t(i)+per  ,i=1,2,...,2*k+1
+    #      c(i+n-2*k-1) = c(i)      ,i=1,2,...,k
+    # in that case, the knots and b-spline coefficients returned will also
+    # satisfy these boundary constraints, i.e.
+    #      tt(i+nn-2*k-1) = tt(i)+per  ,i=1,2,...,2*k+1
+    #      cc(i+nn-2*k-1) = cc(i)      ,i=1,2,...,k
+    interval = _dierckx.find_interval(t, k, float(xval), k, False)
+    if interval < 0:
+        # extrapolated values are guarded for in BSpline.insert_knot
+        raise ValueError(f"Cannot insert the knot at {xval}.")
+
+    # super edge case: a knot with multiplicity > k+1
+    # see https://github.com/scipy/scipy/commit/037204c3e91
+    if t[interval] == t[interval + k + 1]:
+        interval -= 1
+
+    if periodic:
+        if (interval + 1 <= 2*k) and (interval + 1 >= t.shape[0] - 2*k):
+            # in case of a periodic spline (iopt.ne.0) there must be
+            # either at least k interior knots t(j) satisfying t(k+1)= nk - k:
+            # adjust the left-hand boundary knots & coefs
+            tt[:k] = tt[nk - k:nk] - T
+            cc[:k, ...] = cc[n2k:n2k + k, ...]
+
+        if interval <= 2*k-1:
+            # adjust the right-hand boundary knots & coefs
+            tt[n-k:] = tt[k+1:k+1+k] + T
+            cc[n2k:n2k + k, ...] = cc[:k, ...]
+
+    return tt, cc
+
+
+#################################
+#  Interpolating spline helpers #
+#################################
+
+def _not_a_knot(x, k):
+    """Given data x, construct the knot vector w/ not-a-knot BC.
+    cf de Boor, XIII(12).
+
+    For even k, it's a bit ad hoc: Greville sites + omit 2nd and 2nd-to-last
+    data points, a la not-a-knot.
+    This seems to match what Dierckx does, too:
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L63-L80
+    """
+    x = np.asarray(x)
+    if k % 2 == 1:
+        k2 = (k + 1) // 2
+        t = x.copy()
+    else:
+        k2 = k // 2
+        t = (x[1:] + x[:-1]) / 2
+
+    t = t[k2:-k2]
+    t = np.r_[(x[0],)*(k+1), t, (x[-1],)*(k+1)]
+    return t
+
+
+def _augknt(x, k):
+    """Construct a knot vector appropriate for the order-k interpolation."""
+    return np.r_[(x[0],)*k, x, (x[-1],)*k]
+
+
+def _convert_string_aliases(deriv, target_shape):
+    if isinstance(deriv, str):
+        if deriv == "clamped":
+            deriv = [(1, np.zeros(target_shape))]
+        elif deriv == "natural":
+            deriv = [(2, np.zeros(target_shape))]
+        else:
+            raise ValueError(f"Unknown boundary condition : {deriv}")
+    return deriv
+
+
+def _process_deriv_spec(deriv):
+    if deriv is not None:
+        try:
+            ords, vals = zip(*deriv)
+        except TypeError as e:
+            msg = ("Derivatives, `bc_type`, should be specified as a pair of "
+                   "iterables of pairs of (order, value).")
+            raise ValueError(msg) from e
+    else:
+        ords, vals = [], []
+    return np.atleast_1d(ords, vals)
+
+
+def _woodbury_algorithm(A, ur, ll, b, k):
+    '''
+    Solve a cyclic banded linear system with upper right
+    and lower blocks of size ``(k-1) / 2`` using
+    the Woodbury formula
+
+    Parameters
+    ----------
+    A : 2-D array, shape(k, n)
+        Matrix of diagonals of original matrix (see
+        ``solve_banded`` documentation).
+    ur : 2-D array, shape(bs, bs)
+        Upper right block matrix.
+    ll : 2-D array, shape(bs, bs)
+        Lower left block matrix.
+    b : 1-D array, shape(n,)
+        Vector of constant terms of the system of linear equations.
+    k : int
+        B-spline degree.
+
+    Returns
+    -------
+    c : 1-D array, shape(n,)
+        Solution of the original system of linear equations.
+
+    Notes
+    -----
+    This algorithm works only for systems with banded matrix A plus
+    a correction term U @ V.T, where the matrix U @ V.T gives upper right
+    and lower left block of A
+    The system is solved with the following steps:
+        1.  New systems of linear equations are constructed:
+            A @ z_i = u_i,
+            u_i - column vector of U,
+            i = 1, ..., k - 1
+        2.  Matrix Z is formed from vectors z_i:
+            Z = [ z_1 | z_2 | ... | z_{k - 1} ]
+        3.  Matrix H = (1 + V.T @ Z)^{-1}
+        4.  The system A' @ y = b is solved
+        5.  x = y - Z @ (H @ V.T @ y)
+    Also, ``n`` should be greater than ``k``, otherwise corner block
+    elements will intersect with diagonals.
+
+    Examples
+    --------
+    Consider the case of n = 8, k = 5 (size of blocks - 2 x 2).
+    The matrix of a system:       U:          V:
+      x  x  x  *  *  a  b         a b 0 0     0 0 1 0
+      x  x  x  x  *  *  c         0 c 0 0     0 0 0 1
+      x  x  x  x  x  *  *         0 0 0 0     0 0 0 0
+      *  x  x  x  x  x  *         0 0 0 0     0 0 0 0
+      *  *  x  x  x  x  x         0 0 0 0     0 0 0 0
+      d  *  *  x  x  x  x         0 0 d 0     1 0 0 0
+      e  f  *  *  x  x  x         0 0 e f     0 1 0 0
+
+    References
+    ----------
+    .. [1] William H. Press, Saul A. Teukolsky, William T. Vetterling
+           and Brian P. Flannery, Numerical Recipes, 2007, Section 2.7.3
+
+    '''
+    k_mod = k - k % 2
+    bs = int((k - 1) / 2) + (k + 1) % 2
+
+    n = A.shape[1] + 1
+    U = np.zeros((n - 1, k_mod))
+    VT = np.zeros((k_mod, n - 1))  # V transpose
+
+    # upper right block
+    U[:bs, :bs] = ur
+    VT[np.arange(bs), np.arange(bs) - bs] = 1
+
+    # lower left block
+    U[-bs:, -bs:] = ll
+    VT[np.arange(bs) - bs, np.arange(bs)] = 1
+
+    Z = solve_banded((bs, bs), A, U)
+
+    H = solve(np.identity(k_mod) + VT @ Z, np.identity(k_mod))
+
+    y = solve_banded((bs, bs), A, b)
+    c = y - Z @ (H @ (VT @ y))
+
+    return c
+
+
+def _periodic_knots(x, k):
+    '''
+    returns vector of nodes on circle
+    '''
+    xc = np.copy(x)
+    n = len(xc)
+    if k % 2 == 0:
+        dx = np.diff(xc)
+        xc[1: -1] -= dx[:-1] / 2
+    dx = np.diff(xc)
+    t = np.zeros(n + 2 * k)
+    t[k: -k] = xc
+    for i in range(0, k):
+        # filling first `k` elements in descending order
+        t[k - i - 1] = t[k - i] - dx[-(i % (n - 1)) - 1]
+        # filling last `k` elements in ascending order
+        t[-k + i] = t[-k + i - 1] + dx[i % (n - 1)]
+    return t
+
+
+def _make_interp_per_full_matr(x, y, t, k):
+    '''
+    Returns a solution of a system for B-spline interpolation with periodic
+    boundary conditions. First ``k - 1`` rows of matrix are conditions of
+    periodicity (continuity of ``k - 1`` derivatives at the boundary points).
+    Last ``n`` rows are interpolation conditions.
+    RHS is ``k - 1`` zeros and ``n`` ordinates in this case.
+
+    Parameters
+    ----------
+    x : 1-D array, shape (n,)
+        Values of x - coordinate of a given set of points.
+    y : 1-D array, shape (n,)
+        Values of y - coordinate of a given set of points.
+    t : 1-D array, shape(n+2*k,)
+        Vector of knots.
+    k : int
+        The maximum degree of spline
+
+    Returns
+    -------
+    c : 1-D array, shape (n+k-1,)
+        B-spline coefficients
+
+    Notes
+    -----
+    ``t`` is supposed to be taken on circle.
+
+    '''
+
+    x, y, t = map(np.asarray, (x, y, t))
+
+    n = x.size
+    # LHS: the colocation matrix + derivatives at edges
+    matr = np.zeros((n + k - 1, n + k - 1))
+
+    # derivatives at x[0] and x[-1]:
+    for i in range(k - 1):
+        bb = _dierckx.evaluate_all_bspl(t, k, x[0], k, i + 1)
+        matr[i, : k + 1] += bb
+        bb = _dierckx.evaluate_all_bspl(t, k, x[-1], n + k - 1, i + 1)[:-1]
+        matr[i, -k:] -= bb
+
+    # colocation matrix
+    for i in range(n):
+        xval = x[i]
+        # find interval
+        if xval == t[k]:
+            left = k
+        else:
+            left = np.searchsorted(t, xval) - 1
+
+        # fill a row
+        bb = _dierckx.evaluate_all_bspl(t, k, xval, left)
+        matr[i + k - 1, left-k:left+1] = bb
+
+    # RHS
+    b = np.r_[[0] * (k - 1), y]
+
+    c = solve(matr, b)
+    return c
+
+
+def _handle_lhs_derivatives(t, k, xval, ab, kl, ku, deriv_ords, offset=0):
+    """ Fill in the entries of the colocation matrix corresponding to known
+    derivatives at `xval`.
+
+    The colocation matrix is in the banded storage, as prepared by _coloc.
+    No error checking.
+
+    Parameters
+    ----------
+    t : ndarray, shape (nt + k + 1,)
+        knots
+    k : integer
+        B-spline order
+    xval : float
+        The value at which to evaluate the derivatives at.
+    ab : ndarray, shape(2*kl + ku + 1, nt), Fortran order
+        B-spline colocation matrix.
+        This argument is modified *in-place*.
+    kl : integer
+        Number of lower diagonals of ab.
+    ku : integer
+        Number of upper diagonals of ab.
+    deriv_ords : 1D ndarray
+        Orders of derivatives known at xval
+    offset : integer, optional
+        Skip this many rows of the matrix ab.
+
+    """
+    # find where `xval` is in the knot vector, `t`
+    left = _dierckx.find_interval(t, k, float(xval), k, False)
+
+    # compute and fill in the derivatives @ xval
+    for row in range(deriv_ords.shape[0]):
+        nu = deriv_ords[row]
+        wrk = _dierckx.evaluate_all_bspl(t, k, xval, left, nu)
+
+        # if A were a full matrix, it would be just
+        # ``A[row + offset, left-k:left+1] = bb``.
+        for a in range(k+1):
+            clmn = left - k + a
+            ab[kl + ku + offset + row - clmn, clmn] = wrk[a]
+
+
+def _make_periodic_spline(x, y, t, k, axis):
+    '''
+    Compute the (coefficients of) interpolating B-spline with periodic
+    boundary conditions.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        Abscissas.
+    y : array_like, shape (n,)
+        Ordinates.
+    k : int
+        B-spline degree.
+    t : array_like, shape (n + 2 * k,).
+        Knots taken on a circle, ``k`` on the left and ``k`` on the right
+        of the vector ``x``.
+
+    Returns
+    -------
+    b : a BSpline object of the degree ``k`` and with knots ``t``.
+
+    Notes
+    -----
+    The original system is formed by ``n + k - 1`` equations where the first
+    ``k - 1`` of them stand for the ``k - 1`` derivatives continuity on the
+    edges while the other equations correspond to an interpolating case
+    (matching all the input points). Due to a special form of knot vector, it
+    can be proved that in the original system the first and last ``k``
+    coefficients of a spline function are the same, respectively. It follows
+    from the fact that all ``k - 1`` derivatives are equal term by term at ends
+    and that the matrix of the original system of linear equations is
+    non-degenerate. So, we can reduce the number of equations to ``n - 1``
+    (first ``k - 1`` equations could be reduced). Another trick of this
+    implementation is cyclic shift of values of B-splines due to equality of
+    ``k`` unknown coefficients. With this we can receive matrix of the system
+    with upper right and lower left blocks, and ``k`` diagonals.  It allows
+    to use Woodbury formula to optimize the computations.
+
+    '''
+    n = y.shape[0]
+
+    extradim = prod(y.shape[1:])
+    y_new = y.reshape(n, extradim)
+    c = np.zeros((n + k - 1, extradim))
+
+    # n <= k case is solved with full matrix
+    if n <= k:
+        for i in range(extradim):
+            c[:, i] = _make_interp_per_full_matr(x, y_new[:, i], t, k)
+        c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:]))
+        return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis)
+
+    nt = len(t) - k - 1
+
+    # size of block elements
+    kul = int(k / 2)
+
+    # kl = ku = k
+    ab = np.zeros((3 * k + 1, nt), dtype=np.float64, order='F')
+
+    # upper right and lower left blocks
+    ur = np.zeros((kul, kul))
+    ll = np.zeros_like(ur)
+
+    # `offset` is made to shift all the non-zero elements to the end of the
+    # matrix
+    # NB: 1. drop the last element of `x` because `x[0] = x[-1] + T` & `y[0] == y[-1]`
+    #     2. pass ab.T to _coloc to make it C-ordered; below it'll be fed to banded
+    #        LAPACK, which needs F-ordered arrays
+    _dierckx._coloc(x[:-1], t, k, ab.T, k)
+
+    # remove zeros before the matrix
+    ab = ab[-k - (k + 1) % 2:, :]
+
+    # The least elements in rows (except repetitions) are diagonals
+    # of block matrices. Upper right matrix is an upper triangular
+    # matrix while lower left is a lower triangular one.
+    for i in range(kul):
+        ur += np.diag(ab[-i - 1, i: kul], k=i)
+        ll += np.diag(ab[i, -kul - (k % 2): n - 1 + 2 * kul - i], k=-i)
+
+    # remove elements that occur in the last point
+    # (first and last points are equivalent)
+    A = ab[:, kul: -k + kul]
+
+    for i in range(extradim):
+        cc = _woodbury_algorithm(A, ur, ll, y_new[:, i][:-1], k)
+        c[:, i] = np.concatenate((cc[-kul:], cc, cc[:kul + k % 2]))
+    c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:]))
+    return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis)
+
+
+def make_interp_spline(x, y, k=3, t=None, bc_type=None, axis=0,
+                       check_finite=True):
+    """Compute the (coefficients of) interpolating B-spline.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        Abscissas.
+    y : array_like, shape (n, ...)
+        Ordinates.
+    k : int, optional
+        B-spline degree. Default is cubic, ``k = 3``.
+    t : array_like, shape (nt + k + 1,), optional.
+        Knots.
+        The number of knots needs to agree with the number of data points and
+        the number of derivatives at the edges. Specifically, ``nt - n`` must
+        equal ``len(deriv_l) + len(deriv_r)``.
+    bc_type : 2-tuple or None
+        Boundary conditions.
+        Default is None, which means choosing the boundary conditions
+        automatically. Otherwise, it must be a length-two tuple where the first
+        element (``deriv_l``) sets the boundary conditions at ``x[0]`` and
+        the second element (``deriv_r``) sets the boundary conditions at
+        ``x[-1]``. Each of these must be an iterable of pairs
+        ``(order, value)`` which gives the values of derivatives of specified
+        orders at the given edge of the interpolation interval.
+        Alternatively, the following string aliases are recognized:
+
+        * ``"clamped"``: The first derivatives at the ends are zero. This is
+           equivalent to ``bc_type=([(1, 0.0)], [(1, 0.0)])``.
+        * ``"natural"``: The second derivatives at ends are zero. This is
+          equivalent to ``bc_type=([(2, 0.0)], [(2, 0.0)])``.
+        * ``"not-a-knot"`` (default): The first and second segments are the
+          same polynomial. This is equivalent to having ``bc_type=None``.
+        * ``"periodic"``: The values and the first ``k-1`` derivatives at the
+          ends are equivalent.
+
+    axis : int, optional
+        Interpolation axis. Default is 0.
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default is True.
+
+    Returns
+    -------
+    b : a BSpline object of the degree ``k`` and with knots ``t``.
+
+    See Also
+    --------
+    BSpline : base class representing the B-spline objects
+    CubicSpline : a cubic spline in the polynomial basis
+    make_lsq_spline : a similar factory function for spline fitting
+    UnivariateSpline : a wrapper over FITPACK spline fitting routines
+    splrep : a wrapper over FITPACK spline fitting routines
+
+    Examples
+    --------
+
+    Use cubic interpolation on Chebyshev nodes:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> def cheb_nodes(N):
+    ...     jj = 2.*np.arange(N) + 1
+    ...     x = np.cos(np.pi * jj / 2 / N)[::-1]
+    ...     return x
+
+    >>> x = cheb_nodes(20)
+    >>> y = np.sqrt(1 - x**2)
+
+    >>> from scipy.interpolate import BSpline, make_interp_spline
+    >>> b = make_interp_spline(x, y)
+    >>> np.allclose(b(x), y)
+    True
+
+    Note that the default is a cubic spline with a not-a-knot boundary condition
+
+    >>> b.k
+    3
+
+    Here we use a 'natural' spline, with zero 2nd derivatives at edges:
+
+    >>> l, r = [(2, 0.0)], [(2, 0.0)]
+    >>> b_n = make_interp_spline(x, y, bc_type=(l, r))  # or, bc_type="natural"
+    >>> np.allclose(b_n(x), y)
+    True
+    >>> x0, x1 = x[0], x[-1]
+    >>> np.allclose([b_n(x0, 2), b_n(x1, 2)], [0, 0])
+    True
+
+    Interpolation of parametric curves is also supported. As an example, we
+    compute a discretization of a snail curve in polar coordinates
+
+    >>> phi = np.linspace(0, 2.*np.pi, 40)
+    >>> r = 0.3 + np.cos(phi)
+    >>> x, y = r*np.cos(phi), r*np.sin(phi)  # convert to Cartesian coordinates
+
+    Build an interpolating curve, parameterizing it by the angle
+
+    >>> spl = make_interp_spline(phi, np.c_[x, y])
+
+    Evaluate the interpolant on a finer grid (note that we transpose the result
+    to unpack it into a pair of x- and y-arrays)
+
+    >>> phi_new = np.linspace(0, 2.*np.pi, 100)
+    >>> x_new, y_new = spl(phi_new).T
+
+    Plot the result
+
+    >>> plt.plot(x, y, 'o')
+    >>> plt.plot(x_new, y_new, '-')
+    >>> plt.show()
+
+    Build a B-spline curve with 2 dimensional y
+
+    >>> x = np.linspace(0, 2*np.pi, 10)
+    >>> y = np.array([np.sin(x), np.cos(x)])
+
+    Periodic condition is satisfied because y coordinates of points on the ends
+    are equivalent
+
+    >>> ax = plt.axes(projection='3d')
+    >>> xx = np.linspace(0, 2*np.pi, 100)
+    >>> bspl = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1)
+    >>> ax.plot3D(xx, *bspl(xx))
+    >>> ax.scatter3D(x, *y, color='red')
+    >>> plt.show()
+
+    """
+    # convert string aliases for the boundary conditions
+    if bc_type is None or bc_type == 'not-a-knot' or bc_type == 'periodic':
+        deriv_l, deriv_r = None, None
+    elif isinstance(bc_type, str):
+        deriv_l, deriv_r = bc_type, bc_type
+    else:
+        try:
+            deriv_l, deriv_r = bc_type
+        except TypeError as e:
+            raise ValueError(f"Unknown boundary condition: {bc_type}") from e
+
+    y = np.asarray(y)
+
+    axis = normalize_axis_index(axis, y.ndim)
+
+    x = _as_float_array(x, check_finite)
+    y = _as_float_array(y, check_finite)
+
+    y = np.moveaxis(y, axis, 0)    # now internally interp axis is zero
+
+    # sanity check the input
+    if bc_type == 'periodic' and not np.allclose(y[0], y[-1], atol=1e-15):
+        raise ValueError("First and last points does not match while "
+                         "periodic case expected")
+    if x.size != y.shape[0]:
+        raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible')
+    if np.any(x[1:] == x[:-1]):
+        raise ValueError("Expect x to not have duplicates")
+    if x.ndim != 1 or np.any(x[1:] < x[:-1]):
+        raise ValueError("Expect x to be a 1D strictly increasing sequence.")
+
+    # special-case k=0 right away
+    if k == 0:
+        if any(_ is not None for _ in (t, deriv_l, deriv_r)):
+            raise ValueError("Too much info for k=0: t and bc_type can only "
+                             "be None.")
+        t = np.r_[x, x[-1]]
+        c = np.asarray(y)
+        c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype))
+        return BSpline.construct_fast(t, c, k, axis=axis)
+
+    # special-case k=1 (e.g., Lyche and Morken, Eq.(2.16))
+    if k == 1 and t is None:
+        if not (deriv_l is None and deriv_r is None):
+            raise ValueError("Too much info for k=1: bc_type can only be None.")
+        t = np.r_[x[0], x, x[-1]]
+        c = np.asarray(y)
+        c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype))
+        return BSpline.construct_fast(t, c, k, axis=axis)
+
+    k = operator.index(k)
+
+    if bc_type == 'periodic' and t is not None:
+        raise NotImplementedError("For periodic case t is constructed "
+                                  "automatically and can not be passed "
+                                  "manually")
+
+    # come up with a sensible knot vector, if needed
+    if t is None:
+        if deriv_l is None and deriv_r is None:
+            if bc_type == 'periodic':
+                t = _periodic_knots(x, k)
+            else:
+                t = _not_a_knot(x, k)
+        else:
+            t = _augknt(x, k)
+
+    t = _as_float_array(t, check_finite)
+
+    if k < 0:
+        raise ValueError("Expect non-negative k.")
+    if t.ndim != 1 or np.any(t[1:] < t[:-1]):
+        raise ValueError("Expect t to be a 1-D sorted array_like.")
+    if t.size < x.size + k + 1:
+        raise ValueError('Got %d knots, need at least %d.' %
+                         (t.size, x.size + k + 1))
+    if (x[0] < t[k]) or (x[-1] > t[-k]):
+        raise ValueError(f'Out of bounds w/ x = {x}.')
+
+    if bc_type == 'periodic':
+        return _make_periodic_spline(x, y, t, k, axis)
+
+    # Here : deriv_l, r = [(nu, value), ...]
+    deriv_l = _convert_string_aliases(deriv_l, y.shape[1:])
+    deriv_l_ords, deriv_l_vals = _process_deriv_spec(deriv_l)
+    nleft = deriv_l_ords.shape[0]
+
+    deriv_r = _convert_string_aliases(deriv_r, y.shape[1:])
+    deriv_r_ords, deriv_r_vals = _process_deriv_spec(deriv_r)
+    nright = deriv_r_ords.shape[0]
+
+    if not all(0 <= i <= k for i in deriv_l_ords):
+        raise ValueError(f"Bad boundary conditions at {x[0]}.")
+
+    if not all(0 <= i <= k for i in deriv_r_ords):
+        raise ValueError(f"Bad boundary conditions at {x[-1]}.")
+
+    # have `n` conditions for `nt` coefficients; need nt-n derivatives
+    n = x.size
+    nt = t.size - k - 1
+
+    if nt - n != nleft + nright:
+        raise ValueError("The number of derivatives at boundaries does not "
+                         f"match: expected {nt-n}, got {nleft}+{nright}")
+
+    # bail out if the `y` array is zero-sized
+    if y.size == 0:
+        c = np.zeros((nt,) + y.shape[1:], dtype=float)
+        return BSpline.construct_fast(t, c, k, axis=axis)
+
+    # set up the LHS: the colocation matrix + derivatives at boundaries
+    # NB: ab is in F order for banded LAPACK; _coloc needs C-ordered arrays,
+    #     this pass ab.T into _coloc
+    kl = ku = k
+    ab = np.zeros((2*kl + ku + 1, nt), dtype=np.float64, order='F')
+    _dierckx._coloc(x, t, k, ab.T, nleft)
+    if nleft > 0:
+        _handle_lhs_derivatives(t, k, x[0], ab, kl, ku, deriv_l_ords)
+    if nright > 0:
+        _handle_lhs_derivatives(t, k, x[-1], ab, kl, ku, deriv_r_ords,
+                                offset=nt-nright)
+
+    # set up the RHS: values to interpolate (+ derivative values, if any)
+    extradim = prod(y.shape[1:])
+    rhs = np.empty((nt, extradim), dtype=y.dtype)
+    if nleft > 0:
+        rhs[:nleft] = deriv_l_vals.reshape(-1, extradim)
+    rhs[nleft:nt - nright] = y.reshape(-1, extradim)
+    if nright > 0:
+        rhs[nt - nright:] = deriv_r_vals.reshape(-1, extradim)
+
+    # solve Ab @ x = rhs; this is the relevant part of linalg.solve_banded
+    if check_finite:
+        ab, rhs = map(np.asarray_chkfinite, (ab, rhs))
+    gbsv, = get_lapack_funcs(('gbsv',), (ab, rhs))
+    lu, piv, c, info = gbsv(kl, ku, ab, rhs,
+                            overwrite_ab=True, overwrite_b=True)
+
+    if info > 0:
+        raise LinAlgError("Colocation matrix is singular.")
+    elif info < 0:
+        raise ValueError('illegal value in %d-th argument of internal gbsv' % -info)
+
+    c = np.ascontiguousarray(c.reshape((nt,) + y.shape[1:]))
+    return BSpline.construct_fast(t, c, k, axis=axis)
+
+
+def make_lsq_spline(x, y, t, k=3, w=None, axis=0, check_finite=True, *, method="qr"):
+    r"""Compute the (coefficients of) an LSQ (Least SQuared) based
+    fitting B-spline.
+
+    The result is a linear combination
+
+    .. math::
+
+            S(x) = \sum_j c_j B_j(x; t)
+
+    of the B-spline basis elements, :math:`B_j(x; t)`, which minimizes
+
+    .. math::
+
+        \sum_{j} \left( w_j \times (S(x_j) - y_j) \right)^2
+
+    Parameters
+    ----------
+    x : array_like, shape (m,)
+        Abscissas.
+    y : array_like, shape (m, ...)
+        Ordinates.
+    t : array_like, shape (n + k + 1,).
+        Knots.
+        Knots and data points must satisfy Schoenberg-Whitney conditions.
+    k : int, optional
+        B-spline degree. Default is cubic, ``k = 3``.
+    w : array_like, shape (m,), optional
+        Weights for spline fitting. Must be positive. If ``None``,
+        then weights are all equal.
+        Default is ``None``.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+        Default is True.
+    method : str, optional
+        Method for solving the linear LSQ problem. Allowed values are "norm-eq"
+        (Explicitly construct and solve the normal system of equations), and
+        "qr" (Use the QR factorization of the design matrix).
+        Default is "qr".
+
+    Returns
+    -------
+    b : a BSpline object of the degree ``k`` with knots ``t``.
+
+    See Also
+    --------
+    BSpline : base class representing the B-spline objects
+    make_interp_spline : a similar factory function for interpolating splines
+    LSQUnivariateSpline : a FITPACK-based spline fitting routine
+    splrep : a FITPACK-based fitting routine
+
+    Notes
+    -----
+    The number of data points must be larger than the spline degree ``k``.
+
+    Knots ``t`` must satisfy the Schoenberg-Whitney conditions,
+    i.e., there must be a subset of data points ``x[j]`` such that
+    ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
+
+    Examples
+    --------
+    Generate some noisy data:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+
+    Now fit a smoothing cubic spline with a pre-defined internal knots.
+    Here we make the knot vector (k+1)-regular by adding boundary knots:
+
+    >>> from scipy.interpolate import make_lsq_spline, BSpline
+    >>> t = [-1, 0, 1]
+    >>> k = 3
+    >>> t = np.r_[(x[0],)*(k+1),
+    ...           t,
+    ...           (x[-1],)*(k+1)]
+    >>> spl = make_lsq_spline(x, y, t, k)
+
+    For comparison, we also construct an interpolating spline for the same
+    set of data:
+
+    >>> from scipy.interpolate import make_interp_spline
+    >>> spl_i = make_interp_spline(x, y)
+
+    Plot both:
+
+    >>> xs = np.linspace(-3, 3, 100)
+    >>> plt.plot(x, y, 'ro', ms=5)
+    >>> plt.plot(xs, spl(xs), 'g-', lw=3, label='LSQ spline')
+    >>> plt.plot(xs, spl_i(xs), 'b-', lw=3, alpha=0.7, label='interp spline')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    **NaN handling**: If the input arrays contain ``nan`` values, the result is
+    not useful since the underlying spline fitting routines cannot deal with
+    ``nan``. A workaround is to use zero weights for not-a-number data points:
+
+    >>> y[8] = np.nan
+    >>> w = np.isnan(y)
+    >>> y[w] = 0.
+    >>> tck = make_lsq_spline(x, y, t, w=~w)
+
+    Notice the need to replace a ``nan`` by a numerical value (precise value
+    does not matter as long as the corresponding weight is zero.)
+
+    """
+    x = _as_float_array(x, check_finite)
+    y = _as_float_array(y, check_finite)
+    t = _as_float_array(t, check_finite)
+    if w is not None:
+        w = _as_float_array(w, check_finite)
+    else:
+        w = np.ones_like(x)
+    k = operator.index(k)
+
+    axis = normalize_axis_index(axis, y.ndim)
+
+    y = np.moveaxis(y, axis, 0)    # now internally interp axis is zero
+
+    if x.ndim != 1:
+        raise ValueError("Expect x to be a 1-D sequence.")
+    if x.shape[0] < k+1:
+        raise ValueError("Need more x points.")
+    if k < 0:
+        raise ValueError("Expect non-negative k.")
+    if t.ndim != 1 or np.any(t[1:] - t[:-1] < 0):
+        raise ValueError("Expect t to be a 1D strictly increasing sequence.")
+    if x.size != y.shape[0]:
+        raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible')
+    if k > 0 and np.any((x < t[k]) | (x > t[-k])):
+        raise ValueError(f'Out of bounds w/ x = {x}.')
+    if x.size != w.size:
+        raise ValueError(f'Shapes of x {x.shape} and w {w.shape} are incompatible')
+    if method == "norm-eq" and np.any(x[1:] - x[:-1] <= 0):
+        raise ValueError("Expect x to be a 1D strictly increasing sequence.")
+    if method == "qr" and any(x[1:] - x[:-1] < 0):
+        raise ValueError("Expect x to be a 1D non-decreasing sequence.")
+
+    # number of coefficients
+    n = t.size - k - 1
+
+    # complex y: view as float, preserve the length
+    was_complex =  y.dtype.kind == 'c'
+    yy = y.view(float)
+    if was_complex and y.ndim == 1:
+        yy = yy.reshape(y.shape[0], 2)
+
+    # multiple r.h.s
+    extradim = prod(yy.shape[1:])
+    yy = yy.reshape(-1, extradim)
+
+    # complex y: view as float, preserve the length
+    was_complex =  y.dtype.kind == 'c'
+    yy = y.view(float)
+    if was_complex and y.ndim == 1:
+        yy = yy.reshape(y.shape[0], 2)
+
+    # multiple r.h.s
+    extradim = prod(yy.shape[1:])
+    yy = yy.reshape(-1, extradim)
+
+    if method == "norm-eq":
+        # construct A.T @ A and rhs with A the colocation matrix, and
+        # rhs = A.T @ y for solving the LSQ problem  ``A.T @ A @ c = A.T @ y``
+        lower = True
+        ab = np.zeros((k+1, n), dtype=np.float64, order='F')
+        rhs = np.zeros((n, extradim), dtype=np.float64)
+        _dierckx._norm_eq_lsq(x, t, k,
+                              yy,
+                              w,
+                              ab.T, rhs)
+
+        # undo complex -> float and flattening the trailing dims
+        if was_complex:
+            rhs = rhs.view(complex)
+
+        rhs = rhs.reshape((n,) + y.shape[1:])
+
+        # have observation matrix & rhs, can solve the LSQ problem
+        cho_decomp = cholesky_banded(ab, overwrite_ab=True, lower=lower,
+                                     check_finite=check_finite)
+        c = cho_solve_banded((cho_decomp, lower), rhs, overwrite_b=True,
+                             check_finite=check_finite)
+    elif method == "qr":
+        _, _, c = _lsq_solve_qr(x, yy, t, k, w)
+
+        if was_complex:
+            c = c.view(complex)
+
+    else:
+        raise ValueError(f"Unknown {method =}.")
+
+
+    # restore the shape of `c` for both single and multiple r.h.s.
+    c = c.reshape((n,) + y.shape[1:])
+    c = np.ascontiguousarray(c)
+    return BSpline.construct_fast(t, c, k, axis=axis)
+
+
+######################
+# LSQ spline helpers #
+######################
+
+def _lsq_solve_qr(x, y, t, k, w):
+    """Solve for the LSQ spline coeffs given x, y and knots.
+
+    `y` is always 2D: for 1D data, the shape is ``(m, 1)``.
+    `w` is always 1D: one weight value per `x` value.
+
+    """
+    assert y.ndim == 2
+
+    y_w = y * w[:, None]
+    A, offset, nc = _dierckx.data_matrix(x, t, k, w)
+    _dierckx.qr_reduce(A, offset, nc, y_w)         # modifies arguments in-place
+    c = _dierckx.fpback(A, nc, y_w)
+
+    return A, y_w, c
+
+
+#############################
+#  Smoothing spline helpers #
+#############################
+
+def _compute_optimal_gcv_parameter(X, wE, y, w):
+    """
+    Returns an optimal regularization parameter from the GCV criteria [1].
+
+    Parameters
+    ----------
+    X : array, shape (5, n)
+        5 bands of the design matrix ``X`` stored in LAPACK banded storage.
+    wE : array, shape (5, n)
+        5 bands of the penalty matrix :math:`W^{-1} E` stored in LAPACK banded
+        storage.
+    y : array, shape (n,)
+        Ordinates.
+    w : array, shape (n,)
+        Vector of weights.
+
+    Returns
+    -------
+    lam : float
+        An optimal from the GCV criteria point of view regularization
+        parameter.
+
+    Notes
+    -----
+    No checks are performed.
+
+    References
+    ----------
+    .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models
+        for observational data, Philadelphia, Pennsylvania: Society for
+        Industrial and Applied Mathematics, 1990, pp. 45-65.
+        :doi:`10.1137/1.9781611970128`
+
+    """
+
+    def compute_banded_symmetric_XT_W_Y(X, w, Y):
+        """
+        Assuming that the product :math:`X^T W Y` is symmetric and both ``X``
+        and ``Y`` are 5-banded, compute the unique bands of the product.
+
+        Parameters
+        ----------
+        X : array, shape (5, n)
+            5 bands of the matrix ``X`` stored in LAPACK banded storage.
+        w : array, shape (n,)
+            Array of weights
+        Y : array, shape (5, n)
+            5 bands of the matrix ``Y`` stored in LAPACK banded storage.
+
+        Returns
+        -------
+        res : array, shape (4, n)
+            The result of the product :math:`X^T Y` stored in the banded way.
+
+        Notes
+        -----
+        As far as the matrices ``X`` and ``Y`` are 5-banded, their product
+        :math:`X^T W Y` is 7-banded. It is also symmetric, so we can store only
+        unique diagonals.
+
+        """
+        # compute W Y
+        W_Y = np.copy(Y)
+
+        W_Y[2] *= w
+        for i in range(2):
+            W_Y[i, 2 - i:] *= w[:-2 + i]
+            W_Y[3 + i, :-1 - i] *= w[1 + i:]
+
+        n = X.shape[1]
+        res = np.zeros((4, n))
+        for i in range(n):
+            for j in range(min(n-i, 4)):
+                res[-j-1, i + j] = sum(X[j:, i] * W_Y[:5-j, i + j])
+        return res
+
+    def compute_b_inv(A):
+        """
+        Inverse 3 central bands of matrix :math:`A=U^T D^{-1} U` assuming that
+        ``U`` is a unit upper triangular banded matrix using an algorithm
+        proposed in [1].
+
+        Parameters
+        ----------
+        A : array, shape (4, n)
+            Matrix to inverse, stored in LAPACK banded storage.
+
+        Returns
+        -------
+        B : array, shape (4, n)
+            3 unique bands of the symmetric matrix that is an inverse to ``A``.
+            The first row is filled with zeros.
+
+        Notes
+        -----
+        The algorithm is based on the cholesky decomposition and, therefore,
+        in case matrix ``A`` is close to not positive defined, the function
+        raises LinalgError.
+
+        Both matrices ``A`` and ``B`` are stored in LAPACK banded storage.
+
+        References
+        ----------
+        .. [1] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with
+            spline functions," Numerische Mathematik, vol. 47, no. 1,
+            pp. 99-106, 1985.
+            :doi:`10.1007/BF01389878`
+
+        """
+
+        def find_b_inv_elem(i, j, U, D, B):
+            rng = min(3, n - i - 1)
+            rng_sum = 0.
+            if j == 0:
+                # use 2-nd formula from [1]
+                for k in range(1, rng + 1):
+                    rng_sum -= U[-k - 1, i + k] * B[-k - 1, i + k]
+                rng_sum += D[i]
+                B[-1, i] = rng_sum
+            else:
+                # use 1-st formula from [1]
+                for k in range(1, rng + 1):
+                    diag = abs(k - j)
+                    ind = i + min(k, j)
+                    rng_sum -= U[-k - 1, i + k] * B[-diag - 1, ind + diag]
+                B[-j - 1, i + j] = rng_sum
+
+        U = cholesky_banded(A)
+        for i in range(2, 5):
+            U[-i, i-1:] /= U[-1, :-i+1]
+        D = 1. / (U[-1])**2
+        U[-1] /= U[-1]
+
+        n = U.shape[1]
+
+        B = np.zeros(shape=(4, n))
+        for i in range(n - 1, -1, -1):
+            for j in range(min(3, n - i - 1), -1, -1):
+                find_b_inv_elem(i, j, U, D, B)
+        # the first row contains garbage and should be removed
+        B[0] = [0.] * n
+        return B
+
+    def _gcv(lam, X, XtWX, wE, XtE):
+        r"""
+        Computes the generalized cross-validation criteria [1].
+
+        Parameters
+        ----------
+        lam : float, (:math:`\lambda \geq 0`)
+            Regularization parameter.
+        X : array, shape (5, n)
+            Matrix is stored in LAPACK banded storage.
+        XtWX : array, shape (4, n)
+            Product :math:`X^T W X` stored in LAPACK banded storage.
+        wE : array, shape (5, n)
+            Matrix :math:`W^{-1} E` stored in LAPACK banded storage.
+        XtE : array, shape (4, n)
+            Product :math:`X^T E` stored in LAPACK banded storage.
+
+        Returns
+        -------
+        res : float
+            Value of the GCV criteria with the regularization parameter
+            :math:`\lambda`.
+
+        Notes
+        -----
+        Criteria is computed from the formula (1.3.2) [3]:
+
+        .. math:
+
+        GCV(\lambda) = \dfrac{1}{n} \sum\limits_{k = 1}^{n} \dfrac{ \left(
+        y_k - f_{\lambda}(x_k) \right)^2}{\left( 1 - \Tr{A}/n\right)^2}$.
+        The criteria is discussed in section 1.3 [3].
+
+        The numerator is computed using (2.2.4) [3] and the denominator is
+        computed using an algorithm from [2] (see in the ``compute_b_inv``
+        function).
+
+        References
+        ----------
+        .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models
+            for observational data, Philadelphia, Pennsylvania: Society for
+            Industrial and Applied Mathematics, 1990, pp. 45-65.
+            :doi:`10.1137/1.9781611970128`
+        .. [2] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with
+            spline functions," Numerische Mathematik, vol. 47, no. 1,
+            pp. 99-106, 1985.
+            :doi:`10.1007/BF01389878`
+        .. [3] E. Zemlyanoy, "Generalized cross-validation smoothing splines",
+            BSc thesis, 2022. Might be available (in Russian)
+            `here `_
+
+        """
+        # Compute the numerator from (2.2.4) [3]
+        n = X.shape[1]
+        c = solve_banded((2, 2), X + lam * wE, y)
+        res = np.zeros(n)
+        # compute ``W^{-1} E c`` with respect to banded-storage of ``E``
+        tmp = wE * c
+        for i in range(n):
+            for j in range(max(0, i - n + 3), min(5, i + 3)):
+                res[i] += tmp[j, i + 2 - j]
+        numer = np.linalg.norm(lam * res)**2 / n
+
+        # compute the denominator
+        lhs = XtWX + lam * XtE
+        try:
+            b_banded = compute_b_inv(lhs)
+            # compute the trace of the product b_banded @ XtX
+            tr = b_banded * XtWX
+            tr[:-1] *= 2
+            # find the denominator
+            denom = (1 - sum(sum(tr)) / n)**2
+        except LinAlgError:
+            # cholesky decomposition cannot be performed
+            raise ValueError('Seems like the problem is ill-posed')
+
+        res = numer / denom
+
+        return res
+
+    n = X.shape[1]
+
+    XtWX = compute_banded_symmetric_XT_W_Y(X, w, X)
+    XtE = compute_banded_symmetric_XT_W_Y(X, w, wE)
+
+    def fun(lam):
+        return _gcv(lam, X, XtWX, wE, XtE)
+
+    gcv_est = minimize_scalar(fun, bounds=(0, n), method='Bounded')
+    if gcv_est.success:
+        return gcv_est.x
+    raise ValueError(f"Unable to find minimum of the GCV "
+                     f"function: {gcv_est.message}")
+
+
+def _coeff_of_divided_diff(x):
+    """
+    Returns the coefficients of the divided difference.
+
+    Parameters
+    ----------
+    x : array, shape (n,)
+        Array which is used for the computation of divided difference.
+
+    Returns
+    -------
+    res : array_like, shape (n,)
+        Coefficients of the divided difference.
+
+    Notes
+    -----
+    Vector ``x`` should have unique elements, otherwise an error division by
+    zero might be raised.
+
+    No checks are performed.
+
+    """
+    n = x.shape[0]
+    res = np.zeros(n)
+    for i in range(n):
+        pp = 1.
+        for k in range(n):
+            if k != i:
+                pp *= (x[i] - x[k])
+        res[i] = 1. / pp
+    return res
+
+
+def make_smoothing_spline(x, y, w=None, lam=None):
+    r"""
+    Compute the (coefficients of) smoothing cubic spline function using
+    ``lam`` to control the tradeoff between the amount of smoothness of the
+    curve and its proximity to the data. In case ``lam`` is None, using the
+    GCV criteria [1] to find it.
+
+    A smoothing spline is found as a solution to the regularized weighted
+    linear regression problem:
+
+    .. math::
+
+        \sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2 +
+        \lambda\int\limits_{x_1}^{x_n} (f^{(2)}(u))^2 d u
+
+    where :math:`f` is a spline function, :math:`w` is a vector of weights and
+    :math:`\lambda` is a regularization parameter.
+
+    If ``lam`` is None, we use the GCV criteria to find an optimal
+    regularization parameter, otherwise we solve the regularized weighted
+    linear regression problem with given parameter. The parameter controls
+    the tradeoff in the following way: the larger the parameter becomes, the
+    smoother the function gets.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        Abscissas. `n` must be at least 5.
+    y : array_like, shape (n,)
+        Ordinates. `n` must be at least 5.
+    w : array_like, shape (n,), optional
+        Vector of weights. Default is ``np.ones_like(x)``.
+    lam : float, (:math:`\lambda \geq 0`), optional
+        Regularization parameter. If ``lam`` is None, then it is found from
+        the GCV criteria. Default is None.
+
+    Returns
+    -------
+    func : a BSpline object.
+        A callable representing a spline in the B-spline basis
+        as a solution of the problem of smoothing splines using
+        the GCV criteria [1] in case ``lam`` is None, otherwise using the
+        given parameter ``lam``.
+
+    Notes
+    -----
+    This algorithm is a clean room reimplementation of the algorithm
+    introduced by Woltring in FORTRAN [2]. The original version cannot be used
+    in SciPy source code because of the license issues. The details of the
+    reimplementation are discussed here (available only in Russian) [4].
+
+    If the vector of weights ``w`` is None, we assume that all the points are
+    equal in terms of weights, and vector of weights is vector of ones.
+
+    Note that in weighted residual sum of squares, weights are not squared:
+    :math:`\sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2` while in
+    ``splrep`` the sum is built from the squared weights.
+
+    In cases when the initial problem is ill-posed (for example, the product
+    :math:`X^T W X` where :math:`X` is a design matrix is not a positive
+    defined matrix) a ValueError is raised.
+
+    References
+    ----------
+    .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models for
+        observational data, Philadelphia, Pennsylvania: Society for Industrial
+        and Applied Mathematics, 1990, pp. 45-65.
+        :doi:`10.1137/1.9781611970128`
+    .. [2] H. J. Woltring, A Fortran package for generalized, cross-validatory
+        spline smoothing and differentiation, Advances in Engineering
+        Software, vol. 8, no. 2, pp. 104-113, 1986.
+        :doi:`10.1016/0141-1195(86)90098-7`
+    .. [3] T. Hastie, J. Friedman, and R. Tisbshirani, "Smoothing Splines" in
+        The elements of Statistical Learning: Data Mining, Inference, and
+        prediction, New York: Springer, 2017, pp. 241-249.
+        :doi:`10.1007/978-0-387-84858-7`
+    .. [4] E. Zemlyanoy, "Generalized cross-validation smoothing splines",
+        BSc thesis, 2022.
+        ``_ (in
+        Russian)
+
+    Examples
+    --------
+    Generate some noisy data
+
+    >>> import numpy as np
+    >>> np.random.seed(1234)
+    >>> n = 200
+    >>> def func(x):
+    ...    return x**3 + x**2 * np.sin(4 * x)
+    >>> x = np.sort(np.random.random_sample(n) * 4 - 2)
+    >>> y = func(x) + np.random.normal(scale=1.5, size=n)
+
+    Make a smoothing spline function
+
+    >>> from scipy.interpolate import make_smoothing_spline
+    >>> spl = make_smoothing_spline(x, y)
+
+    Plot both
+
+    >>> import matplotlib.pyplot as plt
+    >>> grid = np.linspace(x[0], x[-1], 400)
+    >>> plt.plot(grid, spl(grid), label='Spline')
+    >>> plt.plot(grid, func(grid), label='Original function')
+    >>> plt.scatter(x, y, marker='.')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+
+    x = np.ascontiguousarray(x, dtype=float)
+    y = np.ascontiguousarray(y, dtype=float)
+
+    if any(x[1:] - x[:-1] <= 0):
+        raise ValueError('``x`` should be an ascending array')
+
+    if x.ndim != 1 or y.ndim != 1 or x.shape[0] != y.shape[0]:
+        raise ValueError('``x`` and ``y`` should be one dimensional and the'
+                         ' same size')
+
+    if w is None:
+        w = np.ones(len(x))
+    else:
+        w = np.ascontiguousarray(w)
+        if any(w <= 0):
+            raise ValueError('Invalid vector of weights')
+
+    t = np.r_[[x[0]] * 3, x, [x[-1]] * 3]
+    n = x.shape[0]
+
+    if n <= 4:
+        raise ValueError('``x`` and ``y`` length must be at least 5')
+
+    # It is known that the solution to the stated minimization problem exists
+    # and is a natural cubic spline with vector of knots equal to the unique
+    # elements of ``x`` [3], so we will solve the problem in the basis of
+    # natural splines.
+
+    # create design matrix in the B-spline basis
+    X_bspl = BSpline.design_matrix(x, t, 3)
+    # move from B-spline basis to the basis of natural splines using equations
+    # (2.1.7) [4]
+    # central elements
+    X = np.zeros((5, n))
+    for i in range(1, 4):
+        X[i, 2: -2] = X_bspl[i: i - 4, 3: -3][np.diag_indices(n - 4)]
+
+    # first elements
+    X[1, 1] = X_bspl[0, 0]
+    X[2, :2] = ((x[2] + x[1] - 2 * x[0]) * X_bspl[0, 0],
+                X_bspl[1, 1] + X_bspl[1, 2])
+    X[3, :2] = ((x[2] - x[0]) * X_bspl[1, 1], X_bspl[2, 2])
+
+    # last elements
+    X[1, -2:] = (X_bspl[-3, -3], (x[-1] - x[-3]) * X_bspl[-2, -2])
+    X[2, -2:] = (X_bspl[-2, -3] + X_bspl[-2, -2],
+                 (2 * x[-1] - x[-2] - x[-3]) * X_bspl[-1, -1])
+    X[3, -2] = X_bspl[-1, -1]
+
+    # create penalty matrix and divide it by vector of weights: W^{-1} E
+    wE = np.zeros((5, n))
+    wE[2:, 0] = _coeff_of_divided_diff(x[:3]) / w[:3]
+    wE[1:, 1] = _coeff_of_divided_diff(x[:4]) / w[:4]
+    for j in range(2, n - 2):
+        wE[:, j] = (x[j+2] - x[j-2]) * _coeff_of_divided_diff(x[j-2:j+3])\
+                   / w[j-2: j+3]
+
+    wE[:-1, -2] = -_coeff_of_divided_diff(x[-4:]) / w[-4:]
+    wE[:-2, -1] = _coeff_of_divided_diff(x[-3:]) / w[-3:]
+    wE *= 6
+
+    if lam is None:
+        lam = _compute_optimal_gcv_parameter(X, wE, y, w)
+    elif lam < 0.:
+        raise ValueError('Regularization parameter should be non-negative')
+
+    # solve the initial problem in the basis of natural splines
+    c = solve_banded((2, 2), X + lam * wE, y)
+    # move back to B-spline basis using equations (2.2.10) [4]
+    c_ = np.r_[c[0] * (t[5] + t[4] - 2 * t[3]) + c[1],
+               c[0] * (t[5] - t[3]) + c[1],
+               c[1: -1],
+               c[-1] * (t[-4] - t[-6]) + c[-2],
+               c[-1] * (2 * t[-4] - t[-5] - t[-6]) + c[-2]]
+
+    return BSpline.construct_fast(t, c_, 3)
+
+
+########################
+#  FITPACK look-alikes #
+########################
+
+def fpcheck(x, t, k):
+    """ Check consistency of the data vector `x` and the knot vector `t`.
+
+    Return None if inputs are consistent, raises a ValueError otherwise.
+    """
+    # This routine is a clone of the `fpchec` Fortran routine,
+    # https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f
+    # which carries the following comment:
+    #
+    # subroutine fpchec verifies the number and the position of the knots
+    #  t(j),j=1,2,...,n of a spline of degree k, in relation to the number
+    #  and the position of the data points x(i),i=1,2,...,m. if all of the
+    #  following conditions are fulfilled, the error parameter ier is set
+    #  to zero. if one of the conditions is violated ier is set to ten.
+    #      1) k+1 <= n-k-1 <= m
+    #      2) t(1) <= t(2) <= ... <= t(k+1)
+    #         t(n-k) <= t(n-k+1) <= ... <= t(n)
+    #      3) t(k+1) < t(k+2) < ... < t(n-k)
+    #      4) t(k+1) <= x(i) <= t(n-k)
+    #      5) the conditions specified by schoenberg and whitney must hold
+    #         for at least one subset of data points, i.e. there must be a
+    #         subset of data points y(j) such that
+    #             t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
+    x = np.asarray(x)
+    t = np.asarray(t)
+
+    if x.ndim != 1 or t.ndim != 1:
+        raise ValueError(f"Expect `x` and `t` be 1D sequences. Got {x = } and {t = }")
+
+    m = x.shape[0]
+    n = t.shape[0]
+    nk1 = n - k - 1
+
+    # check condition no 1
+    # c      1) k+1 <= n-k-1 <= m
+    if not (k + 1 <= nk1 <= m):
+        raise ValueError(f"Need k+1 <= n-k-1 <= m. Got {m = }, {n = } and {k = }.")
+
+    # check condition no 2
+    # c      2) t(1) <= t(2) <= ... <= t(k+1)
+    # c         t(n-k) <= t(n-k+1) <= ... <= t(n)
+    if (t[:k+1] > t[1:k+2]).any():
+        raise ValueError(f"First k knots must be ordered; got {t = }.")
+
+    if (t[nk1:] < t[nk1-1:-1]).any():
+        raise ValueError(f"Last k knots must be ordered; got {t = }.")
+
+    # c  check condition no 3
+    # c      3) t(k+1) < t(k+2) < ... < t(n-k)
+    if (t[k+1:n-k] <= t[k:n-k-1]).any():
+        raise ValueError(f"Internal knots must be distinct. Got {t = }.")
+
+    # c  check condition no 4
+    # c      4) t(k+1) <= x(i) <= t(n-k)
+    # NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow.
+    if (x[0] < t[k]) or (x[-1] > t[n-k-1]):
+        raise ValueError(f"Out of bounds: {x = } and {t = }.")
+
+    # c  check condition no 5
+    # c      5) the conditions specified by schoenberg and whitney must hold
+    # c         for at least one subset of data points, i.e. there must be a
+    # c         subset of data points y(j) such that
+    # c             t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
+    mesg = f"Schoenberg-Whitney condition is violated with {t = } and {x =}."
+
+    if (x[0] >= t[k+1]) or (x[-1] <= t[n-k-2]):
+        raise ValueError(mesg)
+
+    m = x.shape[0]
+    l = k+1
+    nk3 = n - k - 3
+    if nk3 < 2:
+        return
+    for j in range(1, nk3+1):
+        tj = t[j]
+        l += 1
+        tl = t[l]
+        i = np.argmax(x > tj)
+        if i >= m-1:
+            raise ValueError(mesg)
+        if x[i] >= tl:
+            raise ValueError(mesg)
+    return
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_cubic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_cubic.py
new file mode 100644
index 0000000000000000000000000000000000000000..3139e145916fa0637552331974ce531da625836f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_cubic.py
@@ -0,0 +1,958 @@
+"""Interpolation algorithms using piecewise cubic polynomials."""
+
+from typing import Literal
+
+import numpy as np
+
+from scipy.linalg import solve, solve_banded
+
+from . import PPoly
+from ._polyint import _isscalar
+
+__all__ = ["CubicHermiteSpline", "PchipInterpolator", "pchip_interpolate",
+           "Akima1DInterpolator", "CubicSpline"]
+
+
+def prepare_input(x, y, axis, dydx=None):
+    """Prepare input for cubic spline interpolators.
+
+    All data are converted to numpy arrays and checked for correctness.
+    Axes equal to `axis` of arrays `y` and `dydx` are moved to be the 0th
+    axis. The value of `axis` is converted to lie in
+    [0, number of dimensions of `y`).
+    """
+
+    x, y = map(np.asarray, (x, y))
+    if np.issubdtype(x.dtype, np.complexfloating):
+        raise ValueError("`x` must contain real values.")
+    x = x.astype(float)
+
+    if np.issubdtype(y.dtype, np.complexfloating):
+        dtype = complex
+    else:
+        dtype = float
+
+    if dydx is not None:
+        dydx = np.asarray(dydx)
+        if y.shape != dydx.shape:
+            raise ValueError("The shapes of `y` and `dydx` must be identical.")
+        if np.issubdtype(dydx.dtype, np.complexfloating):
+            dtype = complex
+        dydx = dydx.astype(dtype, copy=False)
+
+    y = y.astype(dtype, copy=False)
+    axis = axis % y.ndim
+    if x.ndim != 1:
+        raise ValueError("`x` must be 1-dimensional.")
+    if x.shape[0] < 2:
+        raise ValueError("`x` must contain at least 2 elements.")
+    if x.shape[0] != y.shape[axis]:
+        raise ValueError(f"The length of `y` along `axis`={axis} doesn't "
+                         "match the length of `x`")
+
+    if not np.all(np.isfinite(x)):
+        raise ValueError("`x` must contain only finite values.")
+    if not np.all(np.isfinite(y)):
+        raise ValueError("`y` must contain only finite values.")
+
+    if dydx is not None and not np.all(np.isfinite(dydx)):
+        raise ValueError("`dydx` must contain only finite values.")
+
+    dx = np.diff(x)
+    if np.any(dx <= 0):
+        raise ValueError("`x` must be strictly increasing sequence.")
+
+    y = np.moveaxis(y, axis, 0)
+    if dydx is not None:
+        dydx = np.moveaxis(dydx, axis, 0)
+
+    return x, dx, y, axis, dydx
+
+
+class CubicHermiteSpline(PPoly):
+    """Piecewise-cubic interpolator matching values and first derivatives.
+
+    The result is represented as a `PPoly` instance.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        1-D array containing values of the independent variable.
+        Values must be real, finite and in strictly increasing order.
+    y : array_like
+        Array containing values of the dependent variable. It can have
+        arbitrary number of dimensions, but the length along ``axis``
+        (see below) must match the length of ``x``. Values must be finite.
+    dydx : array_like
+        Array containing derivatives of the dependent variable. It can have
+        arbitrary number of dimensions, but the length along ``axis``
+        (see below) must match the length of ``x``. Values must be finite.
+    axis : int, optional
+        Axis along which `y` is assumed to be varying. Meaning that for
+        ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
+        Default is 0.
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), it is set to True.
+
+    Attributes
+    ----------
+    x : ndarray, shape (n,)
+        Breakpoints. The same ``x`` which was passed to the constructor.
+    c : ndarray, shape (4, n-1, ...)
+        Coefficients of the polynomials on each segment. The trailing
+        dimensions match the dimensions of `y`, excluding ``axis``.
+        For example, if `y` is 1-D, then ``c[k, i]`` is a coefficient for
+        ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
+    axis : int
+        Interpolation axis. The same axis which was passed to the
+        constructor.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    roots
+
+    See Also
+    --------
+    Akima1DInterpolator : Akima 1D interpolator.
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+    CubicSpline : Cubic spline data interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints
+
+    Notes
+    -----
+    If you want to create a higher-order spline matching higher-order
+    derivatives, use `BPoly.from_derivatives`.
+
+    References
+    ----------
+    .. [1] `Cubic Hermite spline
+            `_
+            on Wikipedia.
+    """
+
+    def __init__(self, x, y, dydx, axis=0, extrapolate=None):
+        if extrapolate is None:
+            extrapolate = True
+
+        x, dx, y, axis, dydx = prepare_input(x, y, axis, dydx)
+
+        dxr = dx.reshape([dx.shape[0]] + [1] * (y.ndim - 1))
+        slope = np.diff(y, axis=0) / dxr
+        t = (dydx[:-1] + dydx[1:] - 2 * slope) / dxr
+
+        c = np.empty((4, len(x) - 1) + y.shape[1:], dtype=t.dtype)
+        c[0] = t / dxr
+        c[1] = (slope - dydx[:-1]) / dxr - t
+        c[2] = dydx[:-1]
+        c[3] = y[:-1]
+
+        super().__init__(c, x, extrapolate=extrapolate)
+        self.axis = axis
+
+
+class PchipInterpolator(CubicHermiteSpline):
+    r"""PCHIP 1-D monotonic cubic interpolation.
+
+    ``x`` and ``y`` are arrays of values used to approximate some function f,
+    with ``y = f(x)``. The interpolant uses monotonic cubic splines
+    to find the value of new points. (PCHIP stands for Piecewise Cubic
+    Hermite Interpolating Polynomial).
+
+    Parameters
+    ----------
+    x : ndarray, shape (npoints, )
+        A 1-D array of monotonically increasing real values. ``x`` cannot
+        include duplicate values (otherwise f is overspecified)
+    y : ndarray, shape (..., npoints, ...)
+        A N-D array of real values. ``y``'s length along the interpolation
+        axis must be equal to the length of ``x``. Use the ``axis``
+        parameter to select the interpolation axis.
+    axis : int, optional
+        Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
+        to ``axis=0``.
+    extrapolate : bool, optional
+        Whether to extrapolate to out-of-bounds points based on first
+        and last intervals, or to return NaNs.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    roots
+
+    See Also
+    --------
+    CubicHermiteSpline : Piecewise-cubic interpolator.
+    Akima1DInterpolator : Akima 1D interpolator.
+    CubicSpline : Cubic spline data interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints.
+
+    Notes
+    -----
+    The interpolator preserves monotonicity in the interpolation data and does
+    not overshoot if the data is not smooth.
+
+    The first derivatives are guaranteed to be continuous, but the second
+    derivatives may jump at :math:`x_k`.
+
+    Determines the derivatives at the points :math:`x_k`, :math:`f'_k`,
+    by using PCHIP algorithm [1]_.
+
+    Let :math:`h_k = x_{k+1} - x_k`, and  :math:`d_k = (y_{k+1} - y_k) / h_k`
+    are the slopes at internal points :math:`x_k`.
+    If the signs of :math:`d_k` and :math:`d_{k-1}` are different or either of
+    them equals zero, then :math:`f'_k = 0`. Otherwise, it is given by the
+    weighted harmonic mean
+
+    .. math::
+
+        \frac{w_1 + w_2}{f'_k} = \frac{w_1}{d_{k-1}} + \frac{w_2}{d_k}
+
+    where :math:`w_1 = 2 h_k + h_{k-1}` and :math:`w_2 = h_k + 2 h_{k-1}`.
+
+    The end slopes are set using a one-sided scheme [2]_.
+
+
+    References
+    ----------
+    .. [1] F. N. Fritsch and J. Butland,
+           A method for constructing local
+           monotone piecewise cubic interpolants,
+           SIAM J. Sci. Comput., 5(2), 300-304 (1984).
+           :doi:`10.1137/0905021`.
+    .. [2] see, e.g., C. Moler, Numerical Computing with Matlab, 2004.
+           :doi:`10.1137/1.9780898717952`
+
+    """
+
+    def __init__(self, x, y, axis=0, extrapolate=None):
+        x, _, y, axis, _ = prepare_input(x, y, axis)
+        if np.iscomplexobj(y):
+            msg = ("`PchipInterpolator` only works with real values for `y`. "
+                   "If you are trying to use the real components of the passed array, "
+                   "use `np.real` on the array before passing to `PchipInterpolator`.")
+            raise ValueError(msg)
+        xp = x.reshape((x.shape[0],) + (1,)*(y.ndim-1))
+        dk = self._find_derivatives(xp, y)
+        super().__init__(x, y, dk, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    @staticmethod
+    def _edge_case(h0, h1, m0, m1):
+        # one-sided three-point estimate for the derivative
+        d = ((2*h0 + h1)*m0 - h0*m1) / (h0 + h1)
+
+        # try to preserve shape
+        mask = np.sign(d) != np.sign(m0)
+        mask2 = (np.sign(m0) != np.sign(m1)) & (np.abs(d) > 3.*np.abs(m0))
+        mmm = (~mask) & mask2
+
+        d[mask] = 0.
+        d[mmm] = 3.*m0[mmm]
+
+        return d
+
+    @staticmethod
+    def _find_derivatives(x, y):
+        # Determine the derivatives at the points y_k, d_k, by using
+        #  PCHIP algorithm is:
+        # We choose the derivatives at the point x_k by
+        # Let m_k be the slope of the kth segment (between k and k+1)
+        # If m_k=0 or m_{k-1}=0 or sgn(m_k) != sgn(m_{k-1}) then d_k == 0
+        # else use weighted harmonic mean:
+        #   w_1 = 2h_k + h_{k-1}, w_2 = h_k + 2h_{k-1}
+        #   1/d_k = 1/(w_1 + w_2)*(w_1 / m_k + w_2 / m_{k-1})
+        #   where h_k is the spacing between x_k and x_{k+1}
+        y_shape = y.shape
+        if y.ndim == 1:
+            # So that _edge_case doesn't end up assigning to scalars
+            x = x[:, None]
+            y = y[:, None]
+
+        hk = x[1:] - x[:-1]
+        mk = (y[1:] - y[:-1]) / hk
+
+        if y.shape[0] == 2:
+            # edge case: only have two points, use linear interpolation
+            dk = np.zeros_like(y)
+            dk[0] = mk
+            dk[1] = mk
+            return dk.reshape(y_shape)
+
+        smk = np.sign(mk)
+        condition = (smk[1:] != smk[:-1]) | (mk[1:] == 0) | (mk[:-1] == 0)
+
+        w1 = 2*hk[1:] + hk[:-1]
+        w2 = hk[1:] + 2*hk[:-1]
+
+        # values where division by zero occurs will be excluded
+        # by 'condition' afterwards
+        with np.errstate(divide='ignore', invalid='ignore'):
+            whmean = (w1/mk[:-1] + w2/mk[1:]) / (w1 + w2)
+
+        dk = np.zeros_like(y)
+        dk[1:-1][condition] = 0.0
+        dk[1:-1][~condition] = 1.0 / whmean[~condition]
+
+        # special case endpoints, as suggested in
+        # Cleve Moler, Numerical Computing with MATLAB, Chap 3.6 (pchiptx.m)
+        dk[0] = PchipInterpolator._edge_case(hk[0], hk[1], mk[0], mk[1])
+        dk[-1] = PchipInterpolator._edge_case(hk[-1], hk[-2], mk[-1], mk[-2])
+
+        return dk.reshape(y_shape)
+
+
+def pchip_interpolate(xi, yi, x, der=0, axis=0):
+    """
+    Convenience function for pchip interpolation.
+
+    xi and yi are arrays of values used to approximate some function f,
+    with ``yi = f(xi)``. The interpolant uses monotonic cubic splines
+    to find the value of new points x and the derivatives there.
+
+    See `scipy.interpolate.PchipInterpolator` for details.
+
+    Parameters
+    ----------
+    xi : array_like
+        A sorted list of x-coordinates, of length N.
+    yi : array_like
+        A 1-D array of real values. `yi`'s length along the interpolation
+        axis must be equal to the length of `xi`. If N-D array, use axis
+        parameter to select correct axis.
+
+        .. deprecated:: 1.13.0
+            Complex data is deprecated and will raise an error in
+            SciPy 1.15.0. If you are trying to use the real components of
+            the passed array, use ``np.real`` on `yi`.
+
+    x : scalar or array_like
+        Of length M.
+    der : int or list, optional
+        Derivatives to extract. The 0th derivative can be included to
+        return the function value.
+    axis : int, optional
+        Axis in the yi array corresponding to the x-coordinate values.
+
+    Returns
+    -------
+    y : scalar or array_like
+        The result, of length R or length M or M by R.
+
+    See Also
+    --------
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+
+    Examples
+    --------
+    We can interpolate 2D observed data using pchip interpolation:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import pchip_interpolate
+    >>> x_observed = np.linspace(0.0, 10.0, 11)
+    >>> y_observed = np.sin(x_observed)
+    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
+    >>> y = pchip_interpolate(x_observed, y_observed, x)
+    >>> plt.plot(x_observed, y_observed, "o", label="observation")
+    >>> plt.plot(x, y, label="pchip interpolation")
+    >>> plt.legend()
+    >>> plt.show()
+
+    """
+    P = PchipInterpolator(xi, yi, axis=axis)
+
+    if der == 0:
+        return P(x)
+    elif _isscalar(der):
+        return P.derivative(der)(x)
+    else:
+        return [P.derivative(nu)(x) for nu in der]
+
+
+class Akima1DInterpolator(CubicHermiteSpline):
+    r"""
+    Akima interpolator
+
+    Fit piecewise cubic polynomials, given vectors x and y. The interpolation
+    method by Akima uses a continuously differentiable sub-spline built from
+    piecewise cubic polynomials. The resultant curve passes through the given
+    data points and will appear smooth and natural.
+
+    Parameters
+    ----------
+    x : ndarray, shape (npoints, )
+        1-D array of monotonically increasing real values.
+    y : ndarray, shape (..., npoints, ...)
+        N-D array of real values. The length of ``y`` along the interpolation axis
+        must be equal to the length of ``x``. Use the ``axis`` parameter to
+        select the interpolation axis.
+    axis : int, optional
+        Axis in the ``y`` array corresponding to the x-coordinate values. Defaults
+        to ``axis=0``.
+    method : {'akima', 'makima'}, optional
+        If ``"makima"``, use the modified Akima interpolation [2]_.
+        Defaults to ``"akima"``, use the Akima interpolation [1]_.
+
+        .. versionadded:: 1.13.0
+
+    extrapolate : {bool, None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points 
+        based on first and last intervals, or to return NaNs. If None, 
+        ``extrapolate`` is set to False.
+        
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    roots
+
+    See Also
+    --------
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+    CubicSpline : Cubic spline data interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints
+
+    Notes
+    -----
+    .. versionadded:: 0.14
+
+    Use only for precise data, as the fitted curve passes through the given
+    points exactly. This routine is useful for plotting a pleasingly smooth
+    curve through a few given points for purposes of plotting.
+
+    Let :math:`\delta_i = (y_{i+1} - y_i) / (x_{i+1} - x_i)` be the slopes of
+    the interval :math:`\left[x_i, x_{i+1}\right)`. Akima's derivative at
+    :math:`x_i` is defined as:
+
+    .. math::
+
+        d_i = \frac{w_1}{w_1 + w_2}\delta_{i-1} + \frac{w_2}{w_1 + w_2}\delta_i
+
+    In the Akima interpolation [1]_ (``method="akima"``), the weights are:
+
+    .. math::
+
+        \begin{aligned}
+        w_1 &= |\delta_{i+1} - \delta_i| \\
+        w_2 &= |\delta_{i-1} - \delta_{i-2}|
+        \end{aligned}
+
+    In the modified Akima interpolation [2]_ (``method="makima"``),
+    to eliminate overshoot and avoid edge cases of both numerator and
+    denominator being equal to 0, the weights are modified as follows:
+
+    .. math::
+
+        \begin{align*}
+        w_1 &= |\delta_{i+1} - \delta_i| + |\delta_{i+1} + \delta_i| / 2 \\
+        w_2 &= |\delta_{i-1} - \delta_{i-2}| + |\delta_{i-1} + \delta_{i-2}| / 2
+        \end{align*}
+
+    Examples
+    --------
+    Comparison of ``method="akima"`` and ``method="makima"``:
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import Akima1DInterpolator
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(1, 7, 7)
+    >>> y = np.array([-1, -1, -1, 0, 1, 1, 1])
+    >>> xs = np.linspace(min(x), max(x), num=100)
+    >>> y_akima = Akima1DInterpolator(x, y, method="akima")(xs)
+    >>> y_makima = Akima1DInterpolator(x, y, method="makima")(xs)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y, "o", label="data")
+    >>> ax.plot(xs, y_akima, label="akima")
+    >>> ax.plot(xs, y_makima, label="makima")
+    >>> ax.legend()
+    >>> fig.show()
+
+    The overshoot that occurred in ``"akima"`` has been avoided in ``"makima"``.
+
+    References
+    ----------
+    .. [1] A new method of interpolation and smooth curve fitting based
+           on local procedures. Hiroshi Akima, J. ACM, October 1970, 17(4),
+           589-602. :doi:`10.1145/321607.321609`
+    .. [2] Makima Piecewise Cubic Interpolation. Cleve Moler and Cosmin Ionita, 2019.
+           https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/
+
+    """
+
+    def __init__(self, x, y, axis=0, *, method: Literal["akima", "makima"]="akima", 
+                 extrapolate:bool | None = None):
+        if method not in {"akima", "makima"}:
+            raise NotImplementedError(f"`method`={method} is unsupported.")
+        # Original implementation in MATLAB by N. Shamsundar (BSD licensed), see
+        # https://www.mathworks.com/matlabcentral/fileexchange/1814-akima-interpolation
+        x, dx, y, axis, _ = prepare_input(x, y, axis)
+
+        if np.iscomplexobj(y):
+            msg = ("`Akima1DInterpolator` only works with real values for `y`. "
+                   "If you are trying to use the real components of the passed array, "
+                   "use `np.real` on the array before passing to "
+                   "`Akima1DInterpolator`.")
+            raise ValueError(msg)
+
+        # Akima extrapolation historically False; parent class defaults to True.
+        extrapolate = False if extrapolate is None else extrapolate
+
+        # determine slopes between breakpoints
+        m = np.empty((x.size + 3, ) + y.shape[1:])
+        dx = dx[(slice(None), ) + (None, ) * (y.ndim - 1)]
+        m[2:-2] = np.diff(y, axis=0) / dx
+
+        # add two additional points on the left ...
+        m[1] = 2. * m[2] - m[3]
+        m[0] = 2. * m[1] - m[2]
+        # ... and on the right
+        m[-2] = 2. * m[-3] - m[-4]
+        m[-1] = 2. * m[-2] - m[-3]
+
+        # if m1 == m2 != m3 == m4, the slope at the breakpoint is not
+        # defined. This is the fill value:
+        t = .5 * (m[3:] + m[:-3])
+        # get the denominator of the slope t
+        dm = np.abs(np.diff(m, axis=0))
+        if method == "makima":
+            pm = np.abs(m[1:] + m[:-1])
+            f1 = dm[2:] + 0.5 * pm[2:]
+            f2 = dm[:-2] + 0.5 * pm[:-2]
+        else:
+            f1 = dm[2:]
+            f2 = dm[:-2]
+        f12 = f1 + f2
+        # These are the mask of where the slope at breakpoint is defined:
+        ind = np.nonzero(f12 > 1e-9 * np.max(f12, initial=-np.inf))
+        x_ind, y_ind = ind[0], ind[1:]
+        # Set the slope at breakpoint
+        t[ind] = (f1[ind] * m[(x_ind + 1,) + y_ind] +
+                  f2[ind] * m[(x_ind + 2,) + y_ind]) / f12[ind]
+
+        super().__init__(x, y, t, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    def extend(self, c, x, right=True):
+        raise NotImplementedError("Extending a 1-D Akima interpolator is not "
+                                  "yet implemented")
+
+    # These are inherited from PPoly, but they do not produce an Akima
+    # interpolator. Hence stub them out.
+    @classmethod
+    def from_spline(cls, tck, extrapolate=None):
+        raise NotImplementedError("This method does not make sense for "
+                                  "an Akima interpolator.")
+
+    @classmethod
+    def from_bernstein_basis(cls, bp, extrapolate=None):
+        raise NotImplementedError("This method does not make sense for "
+                                  "an Akima interpolator.")
+
+
+class CubicSpline(CubicHermiteSpline):
+    """Cubic spline data interpolator.
+
+    Interpolate data with a piecewise cubic polynomial which is twice
+    continuously differentiable [1]_. The result is represented as a `PPoly`
+    instance with breakpoints matching the given data.
+
+    Parameters
+    ----------
+    x : array_like, shape (n,)
+        1-D array containing values of the independent variable.
+        Values must be real, finite and in strictly increasing order.
+    y : array_like
+        Array containing values of the dependent variable. It can have
+        arbitrary number of dimensions, but the length along ``axis``
+        (see below) must match the length of ``x``. Values must be finite.
+    axis : int, optional
+        Axis along which `y` is assumed to be varying. Meaning that for
+        ``x[i]`` the corresponding values are ``np.take(y, i, axis=axis)``.
+        Default is 0.
+    bc_type : string or 2-tuple, optional
+        Boundary condition type. Two additional equations, given by the
+        boundary conditions, are required to determine all coefficients of
+        polynomials on each segment [2]_.
+
+        If `bc_type` is a string, then the specified condition will be applied
+        at both ends of a spline. Available conditions are:
+
+        * 'not-a-knot' (default): The first and second segment at a curve end
+          are the same polynomial. It is a good default when there is no
+          information on boundary conditions.
+        * 'periodic': The interpolated functions is assumed to be periodic
+          of period ``x[-1] - x[0]``. The first and last value of `y` must be
+          identical: ``y[0] == y[-1]``. This boundary condition will result in
+          ``y'[0] == y'[-1]`` and ``y''[0] == y''[-1]``.
+        * 'clamped': The first derivative at curves ends are zero. Assuming
+          a 1D `y`, ``bc_type=((1, 0.0), (1, 0.0))`` is the same condition.
+        * 'natural': The second derivative at curve ends are zero. Assuming
+          a 1D `y`, ``bc_type=((2, 0.0), (2, 0.0))`` is the same condition.
+
+        If `bc_type` is a 2-tuple, the first and the second value will be
+        applied at the curve start and end respectively. The tuple values can
+        be one of the previously mentioned strings (except 'periodic') or a
+        tuple ``(order, deriv_values)`` allowing to specify arbitrary
+        derivatives at curve ends:
+
+        * `order`: the derivative order, 1 or 2.
+        * `deriv_value`: array_like containing derivative values, shape must
+          be the same as `y`, excluding ``axis`` dimension. For example, if
+          `y` is 1-D, then `deriv_value` must be a scalar. If `y` is 3-D with
+          the shape (n0, n1, n2) and axis=2, then `deriv_value` must be 2-D
+          and have the shape (n0, n1).
+    extrapolate : {bool, 'periodic', None}, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. If None (default), ``extrapolate`` is
+        set to 'periodic' for ``bc_type='periodic'`` and to True otherwise.
+
+    Attributes
+    ----------
+    x : ndarray, shape (n,)
+        Breakpoints. The same ``x`` which was passed to the constructor.
+    c : ndarray, shape (4, n-1, ...)
+        Coefficients of the polynomials on each segment. The trailing
+        dimensions match the dimensions of `y`, excluding ``axis``.
+        For example, if `y` is 1-d, then ``c[k, i]`` is a coefficient for
+        ``(x-x[i])**(3-k)`` on the segment between ``x[i]`` and ``x[i+1]``.
+    axis : int
+        Interpolation axis. The same axis which was passed to the
+        constructor.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    roots
+
+    See Also
+    --------
+    Akima1DInterpolator : Akima 1D interpolator.
+    PchipInterpolator : PCHIP 1-D monotonic cubic interpolator.
+    PPoly : Piecewise polynomial in terms of coefficients and breakpoints.
+
+    Notes
+    -----
+    Parameters `bc_type` and ``extrapolate`` work independently, i.e. the
+    former controls only construction of a spline, and the latter only
+    evaluation.
+
+    When a boundary condition is 'not-a-knot' and n = 2, it is replaced by
+    a condition that the first derivative is equal to the linear interpolant
+    slope. When both boundary conditions are 'not-a-knot' and n = 3, the
+    solution is sought as a parabola passing through given points.
+
+    When 'not-a-knot' boundary conditions is applied to both ends, the
+    resulting spline will be the same as returned by `splrep` (with ``s=0``)
+    and `InterpolatedUnivariateSpline`, but these two methods use a
+    representation in B-spline basis.
+
+    .. versionadded:: 0.18.0
+
+    Examples
+    --------
+    In this example the cubic spline is used to interpolate a sampled sinusoid.
+    You can see that the spline continuity property holds for the first and
+    second derivatives and violates only for the third derivative.
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import CubicSpline
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(10)
+    >>> y = np.sin(x)
+    >>> cs = CubicSpline(x, y)
+    >>> xs = np.arange(-0.5, 9.6, 0.1)
+    >>> fig, ax = plt.subplots(figsize=(6.5, 4))
+    >>> ax.plot(x, y, 'o', label='data')
+    >>> ax.plot(xs, np.sin(xs), label='true')
+    >>> ax.plot(xs, cs(xs), label="S")
+    >>> ax.plot(xs, cs(xs, 1), label="S'")
+    >>> ax.plot(xs, cs(xs, 2), label="S''")
+    >>> ax.plot(xs, cs(xs, 3), label="S'''")
+    >>> ax.set_xlim(-0.5, 9.5)
+    >>> ax.legend(loc='lower left', ncol=2)
+    >>> plt.show()
+
+    In the second example, the unit circle is interpolated with a spline. A
+    periodic boundary condition is used. You can see that the first derivative
+    values, ds/dx=0, ds/dy=1 at the periodic point (1, 0) are correctly
+    computed. Note that a circle cannot be exactly represented by a cubic
+    spline. To increase precision, more breakpoints would be required.
+
+    >>> theta = 2 * np.pi * np.linspace(0, 1, 5)
+    >>> y = np.c_[np.cos(theta), np.sin(theta)]
+    >>> cs = CubicSpline(theta, y, bc_type='periodic')
+    >>> print("ds/dx={:.1f} ds/dy={:.1f}".format(cs(0, 1)[0], cs(0, 1)[1]))
+    ds/dx=0.0 ds/dy=1.0
+    >>> xs = 2 * np.pi * np.linspace(0, 1, 100)
+    >>> fig, ax = plt.subplots(figsize=(6.5, 4))
+    >>> ax.plot(y[:, 0], y[:, 1], 'o', label='data')
+    >>> ax.plot(np.cos(xs), np.sin(xs), label='true')
+    >>> ax.plot(cs(xs)[:, 0], cs(xs)[:, 1], label='spline')
+    >>> ax.axes.set_aspect('equal')
+    >>> ax.legend(loc='center')
+    >>> plt.show()
+
+    The third example is the interpolation of a polynomial y = x**3 on the
+    interval 0 <= x<= 1. A cubic spline can represent this function exactly.
+    To achieve that we need to specify values and first derivatives at
+    endpoints of the interval. Note that y' = 3 * x**2 and thus y'(0) = 0 and
+    y'(1) = 3.
+
+    >>> cs = CubicSpline([0, 1], [0, 1], bc_type=((1, 0), (1, 3)))
+    >>> x = np.linspace(0, 1)
+    >>> np.allclose(x**3, cs(x))
+    True
+
+    References
+    ----------
+    .. [1] `Cubic Spline Interpolation
+            `_
+            on Wikiversity.
+    .. [2] Carl de Boor, "A Practical Guide to Splines", Springer-Verlag, 1978.
+    """
+
+    def __init__(self, x, y, axis=0, bc_type='not-a-knot', extrapolate=None):
+        x, dx, y, axis, _ = prepare_input(x, y, axis)
+        n = len(x)
+
+        bc, y = self._validate_bc(bc_type, y, y.shape[1:], axis)
+
+        if extrapolate is None:
+            if bc[0] == 'periodic':
+                extrapolate = 'periodic'
+            else:
+                extrapolate = True
+
+        if y.size == 0:
+            # bail out early for zero-sized arrays
+            s = np.zeros_like(y)
+        else:
+            dxr = dx.reshape([dx.shape[0]] + [1] * (y.ndim - 1))
+            slope = np.diff(y, axis=0) / dxr
+
+            # If bc is 'not-a-knot' this change is just a convention.
+            # If bc is 'periodic' then we already checked that y[0] == y[-1],
+            # and the spline is just a constant, we handle this case in the
+            # same way by setting the first derivatives to slope, which is 0.
+            if n == 2:
+                if bc[0] in ['not-a-knot', 'periodic']:
+                    bc[0] = (1, slope[0])
+                if bc[1] in ['not-a-knot', 'periodic']:
+                    bc[1] = (1, slope[0])
+
+            # This is a special case, when both conditions are 'not-a-knot'
+            # and n == 3. In this case 'not-a-knot' can't be handled regularly
+            # as the both conditions are identical. We handle this case by
+            # constructing a parabola passing through given points.
+            if n == 3 and bc[0] == 'not-a-knot' and bc[1] == 'not-a-knot':
+                A = np.zeros((3, 3))  # This is a standard matrix.
+                b = np.empty((3,) + y.shape[1:], dtype=y.dtype)
+
+                A[0, 0] = 1
+                A[0, 1] = 1
+                A[1, 0] = dx[1]
+                A[1, 1] = 2 * (dx[0] + dx[1])
+                A[1, 2] = dx[0]
+                A[2, 1] = 1
+                A[2, 2] = 1
+
+                b[0] = 2 * slope[0]
+                b[1] = 3 * (dxr[0] * slope[1] + dxr[1] * slope[0])
+                b[2] = 2 * slope[1]
+
+                s = solve(A, b, overwrite_a=True, overwrite_b=True,
+                          check_finite=False)
+            elif n == 3 and bc[0] == 'periodic':
+                # In case when number of points is 3 we compute the derivatives
+                # manually
+                t = (slope / dxr).sum(0) / (1. / dxr).sum(0)
+                s = np.broadcast_to(t, (n,) + y.shape[1:])
+            else:
+                # Find derivative values at each x[i] by solving a tridiagonal
+                # system.
+                A = np.zeros((3, n))  # This is a banded matrix representation.
+                b = np.empty((n,) + y.shape[1:], dtype=y.dtype)
+
+                # Filling the system for i=1..n-2
+                #                         (x[i-1] - x[i]) * s[i-1] +\
+                # 2 * ((x[i] - x[i-1]) + (x[i+1] - x[i])) * s[i]   +\
+                #                         (x[i] - x[i-1]) * s[i+1] =\
+                #       3 * ((x[i+1] - x[i])*(y[i] - y[i-1])/(x[i] - x[i-1]) +\
+                #           (x[i] - x[i-1])*(y[i+1] - y[i])/(x[i+1] - x[i]))
+
+                A[1, 1:-1] = 2 * (dx[:-1] + dx[1:])  # The diagonal
+                A[0, 2:] = dx[:-1]                   # The upper diagonal
+                A[-1, :-2] = dx[1:]                  # The lower diagonal
+
+                b[1:-1] = 3 * (dxr[1:] * slope[:-1] + dxr[:-1] * slope[1:])
+
+                bc_start, bc_end = bc
+
+                if bc_start == 'periodic':
+                    # Due to the periodicity, and because y[-1] = y[0], the
+                    # linear system has (n-1) unknowns/equations instead of n:
+                    A = A[:, 0:-1]
+                    A[1, 0] = 2 * (dx[-1] + dx[0])
+                    A[0, 1] = dx[-1]
+
+                    b = b[:-1]
+
+                    # Also, due to the periodicity, the system is not tri-diagonal.
+                    # We need to compute a "condensed" matrix of shape (n-2, n-2).
+                    # See https://web.archive.org/web/20151220180652/http://www.cfm.brown.edu/people/gk/chap6/node14.html
+                    # for more explanations.
+                    # The condensed matrix is obtained by removing the last column
+                    # and last row of the (n-1, n-1) system matrix. The removed
+                    # values are saved in scalar variables with the (n-1, n-1)
+                    # system matrix indices forming their names:
+                    a_m1_0 = dx[-2]  # lower left corner value: A[-1, 0]
+                    a_m1_m2 = dx[-1]
+                    a_m1_m1 = 2 * (dx[-1] + dx[-2])
+                    a_m2_m1 = dx[-3]
+                    a_0_m1 = dx[0]
+
+                    b[0] = 3 * (dxr[0] * slope[-1] + dxr[-1] * slope[0])
+                    b[-1] = 3 * (dxr[-1] * slope[-2] + dxr[-2] * slope[-1])
+
+                    Ac = A[:, :-1]
+                    b1 = b[:-1]
+                    b2 = np.zeros_like(b1)
+                    b2[0] = -a_0_m1
+                    b2[-1] = -a_m2_m1
+
+                    # s1 and s2 are the solutions of (n-2, n-2) system
+                    s1 = solve_banded((1, 1), Ac, b1, overwrite_ab=False,
+                                      overwrite_b=False, check_finite=False)
+
+                    s2 = solve_banded((1, 1), Ac, b2, overwrite_ab=False,
+                                      overwrite_b=False, check_finite=False)
+
+                    # computing the s[n-2] solution:
+                    s_m1 = ((b[-1] - a_m1_0 * s1[0] - a_m1_m2 * s1[-1]) /
+                            (a_m1_m1 + a_m1_0 * s2[0] + a_m1_m2 * s2[-1]))
+
+                    # s is the solution of the (n, n) system:
+                    s = np.empty((n,) + y.shape[1:], dtype=y.dtype)
+                    s[:-2] = s1 + s_m1 * s2
+                    s[-2] = s_m1
+                    s[-1] = s[0]
+                else:
+                    if bc_start == 'not-a-knot':
+                        A[1, 0] = dx[1]
+                        A[0, 1] = x[2] - x[0]
+                        d = x[2] - x[0]
+                        b[0] = ((dxr[0] + 2*d) * dxr[1] * slope[0] +
+                                dxr[0]**2 * slope[1]) / d
+                    elif bc_start[0] == 1:
+                        A[1, 0] = 1
+                        A[0, 1] = 0
+                        b[0] = bc_start[1]
+                    elif bc_start[0] == 2:
+                        A[1, 0] = 2 * dx[0]
+                        A[0, 1] = dx[0]
+                        b[0] = -0.5 * bc_start[1] * dx[0]**2 + 3 * (y[1] - y[0])
+
+                    if bc_end == 'not-a-knot':
+                        A[1, -1] = dx[-2]
+                        A[-1, -2] = x[-1] - x[-3]
+                        d = x[-1] - x[-3]
+                        b[-1] = ((dxr[-1]**2*slope[-2] +
+                                 (2*d + dxr[-1])*dxr[-2]*slope[-1]) / d)
+                    elif bc_end[0] == 1:
+                        A[1, -1] = 1
+                        A[-1, -2] = 0
+                        b[-1] = bc_end[1]
+                    elif bc_end[0] == 2:
+                        A[1, -1] = 2 * dx[-1]
+                        A[-1, -2] = dx[-1]
+                        b[-1] = 0.5 * bc_end[1] * dx[-1]**2 + 3 * (y[-1] - y[-2])
+
+                    s = solve_banded((1, 1), A, b, overwrite_ab=True,
+                                     overwrite_b=True, check_finite=False)
+
+        super().__init__(x, y, s, axis=0, extrapolate=extrapolate)
+        self.axis = axis
+
+    @staticmethod
+    def _validate_bc(bc_type, y, expected_deriv_shape, axis):
+        """Validate and prepare boundary conditions.
+
+        Returns
+        -------
+        validated_bc : 2-tuple
+            Boundary conditions for a curve start and end.
+        y : ndarray
+            y casted to complex dtype if one of the boundary conditions has
+            complex dtype.
+        """
+        if isinstance(bc_type, str):
+            if bc_type == 'periodic':
+                if not np.allclose(y[0], y[-1], rtol=1e-15, atol=1e-15):
+                    raise ValueError(
+                        f"The first and last `y` point along axis {axis} must "
+                        "be identical (within machine precision) when "
+                        "bc_type='periodic'.")
+
+            bc_type = (bc_type, bc_type)
+
+        else:
+            if len(bc_type) != 2:
+                raise ValueError("`bc_type` must contain 2 elements to "
+                                 "specify start and end conditions.")
+
+            if 'periodic' in bc_type:
+                raise ValueError("'periodic' `bc_type` is defined for both "
+                                 "curve ends and cannot be used with other "
+                                 "boundary conditions.")
+
+        validated_bc = []
+        for bc in bc_type:
+            if isinstance(bc, str):
+                if bc == 'clamped':
+                    validated_bc.append((1, np.zeros(expected_deriv_shape)))
+                elif bc == 'natural':
+                    validated_bc.append((2, np.zeros(expected_deriv_shape)))
+                elif bc in ['not-a-knot', 'periodic']:
+                    validated_bc.append(bc)
+                else:
+                    raise ValueError(f"bc_type={bc} is not allowed.")
+            else:
+                try:
+                    deriv_order, deriv_value = bc
+                except Exception as e:
+                    raise ValueError(
+                        "A specified derivative value must be "
+                        "given in the form (order, value)."
+                    ) from e
+
+                if deriv_order not in [1, 2]:
+                    raise ValueError("The specified derivative order must "
+                                     "be 1 or 2.")
+
+                deriv_value = np.asarray(deriv_value)
+                if deriv_value.shape != expected_deriv_shape:
+                    raise ValueError(
+                        f"`deriv_value` shape {deriv_value.shape} is not "
+                        f"the expected one {expected_deriv_shape}."
+                    )
+
+                if np.issubdtype(deriv_value.dtype, np.complexfloating):
+                    y = y.astype(complex, copy=False)
+
+                validated_bc.append((deriv_order, deriv_value))
+
+        return validated_bc, y
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..5f1de8a506d90631543927894cd35196744a879a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..daa7773a0f3be6590ea9c0ab328d610efa745859
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py
@@ -0,0 +1,2394 @@
+"""
+fitpack --- curve and surface fitting with splines
+
+fitpack is based on a collection of Fortran routines DIERCKX
+by P. Dierckx (see http://www.netlib.org/dierckx/) transformed
+to double routines by Pearu Peterson.
+"""
+# Created by Pearu Peterson, June,August 2003
+__all__ = [
+    'UnivariateSpline',
+    'InterpolatedUnivariateSpline',
+    'LSQUnivariateSpline',
+    'BivariateSpline',
+    'LSQBivariateSpline',
+    'SmoothBivariateSpline',
+    'LSQSphereBivariateSpline',
+    'SmoothSphereBivariateSpline',
+    'RectBivariateSpline',
+    'RectSphereBivariateSpline']
+
+
+import warnings
+from threading import Lock
+
+from numpy import zeros, concatenate, ravel, diff, array
+import numpy as np
+
+from . import _fitpack_impl
+from . import _dfitpack as dfitpack
+
+
+dfitpack_int = dfitpack.types.intvar.dtype
+FITPACK_LOCK = Lock()
+
+
+# ############### Univariate spline ####################
+
+_curfit_messages = {1: """
+The required storage space exceeds the available storage space, as
+specified by the parameter nest: nest too small. If nest is already
+large (say nest > m/2), it may also indicate that s is too small.
+The approximation returned is the weighted least-squares spline
+according to the knots t[0],t[1],...,t[n-1]. (n=nest) the parameter fp
+gives the corresponding weighted sum of squared residuals (fp>s).
+""",
+                    2: """
+A theoretically impossible result was found during the iteration
+process for finding a smoothing spline with fp = s: s too small.
+There is an approximation returned but the corresponding weighted sum
+of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""",
+                    3: """
+The maximal number of iterations maxit (set to 20 by the program)
+allowed for finding a smoothing spline with fp=s has been reached: s
+too small.
+There is an approximation returned but the corresponding weighted sum
+of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""",
+                    10: """
+Error on entry, no approximation returned. The following conditions
+must hold:
+xb<=x[0]0, i=0..m-1
+if iopt=-1:
+  xb>> import numpy as np
+    >>> from scipy.interpolate import UnivariateSpline
+    >>> x, y = np.array([1, 2, 3, 4]), np.array([1, np.nan, 3, 4])
+    >>> w = np.isnan(y)
+    >>> y[w] = 0.
+    >>> spl = UnivariateSpline(x, y, w=~w)
+
+    Notice the need to replace a ``nan`` by a numerical value (precise value
+    does not matter as long as the corresponding weight is zero.)
+
+    References
+    ----------
+    Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
+
+    .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
+       integration of experimental data using spline functions",
+       J.Comp.Appl.Maths 1 (1975) 165-184.
+    .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
+       grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
+       1286-1304.
+    .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
+       functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
+    .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import UnivariateSpline
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+    >>> plt.plot(x, y, 'ro', ms=5)
+
+    Use the default value for the smoothing parameter:
+
+    >>> spl = UnivariateSpline(x, y)
+    >>> xs = np.linspace(-3, 3, 1000)
+    >>> plt.plot(xs, spl(xs), 'g', lw=3)
+
+    Manually change the amount of smoothing:
+
+    >>> spl.set_smoothing_factor(0.5)
+    >>> plt.plot(xs, spl(xs), 'b', lw=3)
+    >>> plt.show()
+
+    """
+
+    def __init__(self, x, y, w=None, bbox=[None]*2, k=3, s=None,
+                 ext=0, check_finite=False):
+
+        x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, s, ext,
+                                                      check_finite)
+
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        with FITPACK_LOCK:
+            data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0],
+                                    xe=bbox[1], s=s)
+        if data[-1] == 1:
+            # nest too small, setting to maximum bound
+            data = self._reset_nest(data)
+        self._data = data
+        self._reset_class()
+
+    @staticmethod
+    def validate_input(x, y, w, bbox, k, s, ext, check_finite):
+        x, y, bbox = np.asarray(x), np.asarray(y), np.asarray(bbox)
+        if w is not None:
+            w = np.asarray(w)
+        if check_finite:
+            w_finite = np.isfinite(w).all() if w is not None else True
+            if (not np.isfinite(x).all() or not np.isfinite(y).all() or
+                    not w_finite):
+                raise ValueError("x and y array must not contain "
+                                 "NaNs or infs.")
+        if s is None or s > 0:
+            if not np.all(diff(x) >= 0.0):
+                raise ValueError("x must be increasing if s > 0")
+        else:
+            if not np.all(diff(x) > 0.0):
+                raise ValueError("x must be strictly increasing if s = 0")
+        if x.size != y.size:
+            raise ValueError("x and y should have a same length")
+        elif w is not None and not x.size == y.size == w.size:
+            raise ValueError("x, y, and w should have a same length")
+        elif bbox.shape != (2,):
+            raise ValueError("bbox shape should be (2,)")
+        elif not (1 <= k <= 5):
+            raise ValueError("k should be 1 <= k <= 5")
+        elif s is not None and not s >= 0.0:
+            raise ValueError("s should be s >= 0.0")
+
+        try:
+            ext = _extrap_modes[ext]
+        except KeyError as e:
+            raise ValueError(f"Unknown extrapolation mode {ext}.") from e
+
+        return x, y, w, bbox, ext
+
+    @classmethod
+    def _from_tck(cls, tck, ext=0):
+        """Construct a spline object from given tck"""
+        self = cls.__new__(cls)
+        t, c, k = tck
+        self._eval_args = tck
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        self._data = (None, None, None, None, None, k, None, len(t), t,
+                      c, None, None, None, None)
+        self.ext = ext
+        return self
+
+    def _reset_class(self):
+        data = self._data
+        n, t, c, k, ier = data[7], data[8], data[9], data[5], data[-1]
+        self._eval_args = t[:n], c[:n], k
+        if ier == 0:
+            # the spline returned has a residual sum of squares fp
+            # such that abs(fp-s)/s <= tol with tol a relative
+            # tolerance set to 0.001 by the program
+            pass
+        elif ier == -1:
+            # the spline returned is an interpolating spline
+            self._set_class(InterpolatedUnivariateSpline)
+        elif ier == -2:
+            # the spline returned is the weighted least-squares
+            # polynomial of degree k. In this extreme case fp gives
+            # the upper bound fp0 for the smoothing factor s.
+            self._set_class(LSQUnivariateSpline)
+        else:
+            # error
+            if ier == 1:
+                self._set_class(LSQUnivariateSpline)
+            message = _curfit_messages.get(ier, f'ier={ier}')
+            warnings.warn(message, stacklevel=3)
+
+    def _set_class(self, cls):
+        self._spline_class = cls
+        if self.__class__ in (UnivariateSpline, InterpolatedUnivariateSpline,
+                              LSQUnivariateSpline):
+            self.__class__ = cls
+        else:
+            # It's an unknown subclass -- don't change class. cf. #731
+            pass
+
+    def _reset_nest(self, data, nest=None):
+        n = data[10]
+        if nest is None:
+            k, m = data[5], len(data[0])
+            nest = m+k+1  # this is the maximum bound for nest
+        else:
+            if not n <= nest:
+                raise ValueError("`nest` can only be increased")
+        t, c, fpint, nrdata = (np.resize(data[j], nest) for j in
+                               [8, 9, 11, 12])
+
+        args = data[:8] + (t, c, n, fpint, nrdata, data[13])
+        with FITPACK_LOCK:
+            data = dfitpack.fpcurf1(*args)
+        return data
+
+    def set_smoothing_factor(self, s):
+        """ Continue spline computation with the given smoothing
+        factor s and with the knots found at the last call.
+
+        This routine modifies the spline in place.
+
+        """
+        data = self._data
+        if data[6] == -1:
+            warnings.warn('smoothing factor unchanged for'
+                          'LSQ spline with fixed knots',
+                          stacklevel=2)
+            return
+        args = data[:6] + (s,) + data[7:]
+        with FITPACK_LOCK:
+            data = dfitpack.fpcurf1(*args)
+        if data[-1] == 1:
+            # nest too small, setting to maximum bound
+            data = self._reset_nest(data)
+        self._data = data
+        self._reset_class()
+
+    def __call__(self, x, nu=0, ext=None):
+        """
+        Evaluate spline (or its nu-th derivative) at positions x.
+
+        Parameters
+        ----------
+        x : array_like
+            A 1-D array of points at which to return the value of the smoothed
+            spline or its derivatives. Note: `x` can be unordered but the
+            evaluation is more efficient if `x` is (partially) ordered.
+        nu  : int
+            The order of derivative of the spline to compute.
+        ext : int
+            Controls the value returned for elements of `x` not in the
+            interval defined by the knot sequence.
+
+            * if ext=0 or 'extrapolate', return the extrapolated value.
+            * if ext=1 or 'zeros', return 0
+            * if ext=2 or 'raise', raise a ValueError
+            * if ext=3 or 'const', return the boundary value.
+
+            The default value is 0, passed from the initialization of
+            UnivariateSpline.
+
+        """
+        x = np.asarray(x)
+        # empty input yields empty output
+        if x.size == 0:
+            return array([])
+        if ext is None:
+            ext = self.ext
+        else:
+            try:
+                ext = _extrap_modes[ext]
+            except KeyError as e:
+                raise ValueError(f"Unknown extrapolation mode {ext}.") from e
+        with FITPACK_LOCK:
+            return _fitpack_impl.splev(x, self._eval_args, der=nu, ext=ext)
+
+    def get_knots(self):
+        """ Return positions of interior knots of the spline.
+
+        Internally, the knot vector contains ``2*k`` additional boundary knots.
+        """
+        data = self._data
+        k, n = data[5], data[7]
+        return data[8][k:n-k]
+
+    def get_coeffs(self):
+        """Return spline coefficients."""
+        data = self._data
+        k, n = data[5], data[7]
+        return data[9][:n-k-1]
+
+    def get_residual(self):
+        """Return weighted sum of squared residuals of the spline approximation.
+
+           This is equivalent to::
+
+                sum((w[i] * (y[i]-spl(x[i])))**2, axis=0)
+
+        """
+        return self._data[10]
+
+    def integral(self, a, b):
+        """ Return definite integral of the spline between two given points.
+
+        Parameters
+        ----------
+        a : float
+            Lower limit of integration.
+        b : float
+            Upper limit of integration.
+
+        Returns
+        -------
+        integral : float
+            The value of the definite integral of the spline between limits.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, 3, 11)
+        >>> y = x**2
+        >>> spl = UnivariateSpline(x, y)
+        >>> spl.integral(0, 3)
+        9.0
+
+        which agrees with :math:`\\int x^2 dx = x^3 / 3` between the limits
+        of 0 and 3.
+
+        A caveat is that this routine assumes the spline to be zero outside of
+        the data limits:
+
+        >>> spl.integral(-1, 4)
+        9.0
+        >>> spl.integral(-1, 0)
+        0.0
+
+        """
+        with FITPACK_LOCK:
+            return _fitpack_impl.splint(a, b, self._eval_args)
+
+    def derivatives(self, x):
+        """ Return all derivatives of the spline at the point x.
+
+        Parameters
+        ----------
+        x : float
+            The point to evaluate the derivatives at.
+
+        Returns
+        -------
+        der : ndarray, shape(k+1,)
+            Derivatives of the orders 0 to k.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, 3, 11)
+        >>> y = x**2
+        >>> spl = UnivariateSpline(x, y)
+        >>> spl.derivatives(1.5)
+        array([2.25, 3.0, 2.0, 0])
+
+        """
+        with FITPACK_LOCK:
+            return _fitpack_impl.spalde(x, self._eval_args)
+
+    def roots(self):
+        """ Return the zeros of the spline.
+
+        Notes
+        -----
+        Restriction: only cubic splines are supported by FITPACK. For non-cubic
+        splines, use `PPoly.root` (see below for an example).
+
+        Examples
+        --------
+
+        For some data, this method may miss a root. This happens when one of
+        the spline knots (which FITPACK places automatically) happens to
+        coincide with the true root. A workaround is to convert to `PPoly`,
+        which uses a different root-finding algorithm.
+
+        For example,
+
+        >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05]
+        >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03,
+        ...      4.440892e-16,  1.616930e-03,  3.243000e-03,  4.877670e-03,
+        ...      6.520430e-03,  8.170770e-03]
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> spl = UnivariateSpline(x, y, s=0)
+        >>> spl.roots()
+        array([], dtype=float64)
+
+        Converting to a PPoly object does find the roots at `x=2`:
+
+        >>> from scipy.interpolate import splrep, PPoly
+        >>> tck = splrep(x, y, s=0)
+        >>> ppoly = PPoly.from_spline(tck)
+        >>> ppoly.roots(extrapolate=False)
+        array([2.])
+
+        See Also
+        --------
+        sproot
+        PPoly.roots
+
+        """
+        k = self._data[5]
+        if k == 3:
+            t = self._eval_args[0]
+            mest = 3 * (len(t) - 7)
+            with FITPACK_LOCK:
+                return _fitpack_impl.sproot(self._eval_args, mest=mest)
+        raise NotImplementedError('finding roots unsupported for '
+                                  'non-cubic splines')
+
+    def derivative(self, n=1):
+        """
+        Construct a new spline representing the derivative of this spline.
+
+        Parameters
+        ----------
+        n : int, optional
+            Order of derivative to evaluate. Default: 1
+
+        Returns
+        -------
+        spline : UnivariateSpline
+            Spline of order k2=k-n representing the derivative of this
+            spline.
+
+        See Also
+        --------
+        splder, antiderivative
+
+        Notes
+        -----
+
+        .. versionadded:: 0.13.0
+
+        Examples
+        --------
+        This can be used for finding maxima of a curve:
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, 10, 70)
+        >>> y = np.sin(x)
+        >>> spl = UnivariateSpline(x, y, k=4, s=0)
+
+        Now, differentiate the spline and find the zeros of the
+        derivative. (NB: `sproot` only works for order 3 splines, so we
+        fit an order 4 spline):
+
+        >>> spl.derivative().roots() / np.pi
+        array([ 0.50000001,  1.5       ,  2.49999998])
+
+        This agrees well with roots :math:`\\pi/2 + n\\pi` of
+        :math:`\\cos(x) = \\sin'(x)`.
+
+        """
+        with FITPACK_LOCK:
+            tck = _fitpack_impl.splder(self._eval_args, n)
+        # if self.ext is 'const', derivative.ext will be 'zeros'
+        ext = 1 if self.ext == 3 else self.ext
+        return UnivariateSpline._from_tck(tck, ext=ext)
+
+    def antiderivative(self, n=1):
+        """
+        Construct a new spline representing the antiderivative of this spline.
+
+        Parameters
+        ----------
+        n : int, optional
+            Order of antiderivative to evaluate. Default: 1
+
+        Returns
+        -------
+        spline : UnivariateSpline
+            Spline of order k2=k+n representing the antiderivative of this
+            spline.
+
+        Notes
+        -----
+
+        .. versionadded:: 0.13.0
+
+        See Also
+        --------
+        splantider, derivative
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.interpolate import UnivariateSpline
+        >>> x = np.linspace(0, np.pi/2, 70)
+        >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
+        >>> spl = UnivariateSpline(x, y, s=0)
+
+        The derivative is the inverse operation of the antiderivative,
+        although some floating point error accumulates:
+
+        >>> spl(1.7), spl.antiderivative().derivative()(1.7)
+        (array(2.1565429877197317), array(2.1565429877201865))
+
+        Antiderivative can be used to evaluate definite integrals:
+
+        >>> ispl = spl.antiderivative()
+        >>> ispl(np.pi/2) - ispl(0)
+        2.2572053588768486
+
+        This is indeed an approximation to the complete elliptic integral
+        :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
+
+        >>> from scipy.special import ellipk
+        >>> ellipk(0.8)
+        2.2572053268208538
+
+        """
+        with FITPACK_LOCK:
+            tck = _fitpack_impl.splantider(self._eval_args, n)
+        return UnivariateSpline._from_tck(tck, self.ext)
+
+
+class InterpolatedUnivariateSpline(UnivariateSpline):
+    """
+    1-D interpolating spline for a given set of data points.
+
+    .. legacy:: class
+
+        Specifically, we recommend using `make_interp_spline` instead.
+
+    Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data.
+    Spline function passes through all provided points. Equivalent to
+    `UnivariateSpline` with  `s` = 0.
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        Input dimension of data points -- must be strictly increasing
+    y : (N,) array_like
+        input dimension of data points
+    w : (N,) array_like, optional
+        Weights for spline fitting.  Must be positive.  If None (default),
+        weights are all 1.
+    bbox : (2,) array_like, optional
+        2-sequence specifying the boundary of the approximation interval. If
+        None (default), ``bbox=[x[0], x[-1]]``.
+    k : int, optional
+        Degree of the smoothing spline.  Must be ``1 <= k <= 5``. Default is
+        ``k = 3``, a cubic spline.
+    ext : int or str, optional
+        Controls the extrapolation mode for elements
+        not in the interval defined by the knot sequence.
+
+        * if ext=0 or 'extrapolate', return the extrapolated value.
+        * if ext=1 or 'zeros', return 0
+        * if ext=2 or 'raise', raise a ValueError
+        * if ext=3 of 'const', return the boundary value.
+
+        The default value is 0.
+
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination or non-sensical results) if the inputs
+        do contain infinities or NaNs.
+        Default is False.
+
+    See Also
+    --------
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    LSQUnivariateSpline :
+        a spline for which knots are user-selected
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    splrep :
+        a function to find the B-spline representation of a 1-D curve
+    splev :
+        a function to evaluate a B-spline or its derivatives
+    sproot :
+        a function to find the roots of a cubic B-spline
+    splint :
+        a function to evaluate the definite integral of a B-spline between two
+        given points
+    spalde :
+        a function to evaluate all derivatives of a B-spline
+
+    Notes
+    -----
+    The number of data points must be larger than the spline degree `k`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import InterpolatedUnivariateSpline
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+    >>> spl = InterpolatedUnivariateSpline(x, y)
+    >>> plt.plot(x, y, 'ro', ms=5)
+    >>> xs = np.linspace(-3, 3, 1000)
+    >>> plt.plot(xs, spl(xs), 'g', lw=3, alpha=0.7)
+    >>> plt.show()
+
+    Notice that the ``spl(x)`` interpolates `y`:
+
+    >>> spl.get_residual()
+    0.0
+
+    """
+
+    def __init__(self, x, y, w=None, bbox=[None]*2, k=3,
+                 ext=0, check_finite=False):
+
+        x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None,
+                                            ext, check_finite)
+        if not np.all(diff(x) > 0.0):
+            raise ValueError('x must be strictly increasing')
+
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        with FITPACK_LOCK:
+            self._data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0],
+                                          xe=bbox[1], s=0)
+        self._reset_class()
+
+
+_fpchec_error_string = """The input parameters have been rejected by fpchec. \
+This means that at least one of the following conditions is violated:
+
+1) k+1 <= n-k-1 <= m
+2) t(1) <= t(2) <= ... <= t(k+1)
+   t(n-k) <= t(n-k+1) <= ... <= t(n)
+3) t(k+1) < t(k+2) < ... < t(n-k)
+4) t(k+1) <= x(i) <= t(n-k)
+5) The conditions specified by Schoenberg and Whitney must hold
+   for at least one subset of data points, i.e., there must be a
+   subset of data points y(j) such that
+       t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
+"""
+
+
+class LSQUnivariateSpline(UnivariateSpline):
+    """
+    1-D spline with explicit internal knots.
+
+    .. legacy:: class
+
+        Specifically, we recommend using `make_lsq_spline` instead.
+
+
+    Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data.  `t`
+    specifies the internal knots of the spline
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        Input dimension of data points -- must be increasing
+    y : (N,) array_like
+        Input dimension of data points
+    t : (M,) array_like
+        interior knots of the spline.  Must be in ascending order and::
+
+            bbox[0] < t[0] < ... < t[-1] < bbox[-1]
+
+    w : (N,) array_like, optional
+        weights for spline fitting. Must be positive. If None (default),
+        weights are all 1.
+    bbox : (2,) array_like, optional
+        2-sequence specifying the boundary of the approximation interval. If
+        None (default), ``bbox = [x[0], x[-1]]``.
+    k : int, optional
+        Degree of the smoothing spline.  Must be 1 <= `k` <= 5.
+        Default is `k` = 3, a cubic spline.
+    ext : int or str, optional
+        Controls the extrapolation mode for elements
+        not in the interval defined by the knot sequence.
+
+        * if ext=0 or 'extrapolate', return the extrapolated value.
+        * if ext=1 or 'zeros', return 0
+        * if ext=2 or 'raise', raise a ValueError
+        * if ext=3 of 'const', return the boundary value.
+
+        The default value is 0.
+
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination or non-sensical results) if the inputs
+        do contain infinities or NaNs.
+        Default is False.
+
+    Raises
+    ------
+    ValueError
+        If the interior knots do not satisfy the Schoenberg-Whitney conditions
+
+    See Also
+    --------
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    InterpolatedUnivariateSpline :
+        a interpolating univariate spline for a given set of data points.
+    splrep :
+        a function to find the B-spline representation of a 1-D curve
+    splev :
+        a function to evaluate a B-spline or its derivatives
+    sproot :
+        a function to find the roots of a cubic B-spline
+    splint :
+        a function to evaluate the definite integral of a B-spline between two
+        given points
+    spalde :
+        a function to evaluate all derivatives of a B-spline
+
+    Notes
+    -----
+    The number of data points must be larger than the spline degree `k`.
+
+    Knots `t` must satisfy the Schoenberg-Whitney conditions,
+    i.e., there must be a subset of data points ``x[j]`` such that
+    ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.interpolate import LSQUnivariateSpline, UnivariateSpline
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
+
+    Fit a smoothing spline with a pre-defined internal knots:
+
+    >>> t = [-1, 0, 1]
+    >>> spl = LSQUnivariateSpline(x, y, t)
+
+    >>> xs = np.linspace(-3, 3, 1000)
+    >>> plt.plot(x, y, 'ro', ms=5)
+    >>> plt.plot(xs, spl(xs), 'g-', lw=3)
+    >>> plt.show()
+
+    Check the knot vector:
+
+    >>> spl.get_knots()
+    array([-3., -1., 0., 1., 3.])
+
+    Constructing lsq spline using the knots from another spline:
+
+    >>> x = np.arange(10)
+    >>> s = UnivariateSpline(x, x, s=0)
+    >>> s.get_knots()
+    array([ 0.,  2.,  3.,  4.,  5.,  6.,  7.,  9.])
+    >>> knt = s.get_knots()
+    >>> s1 = LSQUnivariateSpline(x, x, knt[1:-1])    # Chop 1st and last knot
+    >>> s1.get_knots()
+    array([ 0.,  2.,  3.,  4.,  5.,  6.,  7.,  9.])
+
+    """
+
+    def __init__(self, x, y, t, w=None, bbox=[None]*2, k=3,
+                 ext=0, check_finite=False):
+
+        x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None,
+                                                      ext, check_finite)
+        if not np.all(diff(x) >= 0.0):
+            raise ValueError('x must be increasing')
+
+        # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
+        xb = bbox[0]
+        xe = bbox[1]
+        if xb is None:
+            xb = x[0]
+        if xe is None:
+            xe = x[-1]
+        t = concatenate(([xb]*(k+1), t, [xe]*(k+1)))
+        n = len(t)
+        if not np.all(t[k+1:n-k]-t[k:n-k-1] > 0, axis=0):
+            raise ValueError('Interior knots t must satisfy '
+                             'Schoenberg-Whitney conditions')
+        with FITPACK_LOCK:
+            if not dfitpack.fpchec(x, t, k) == 0:
+                raise ValueError(_fpchec_error_string)
+            data = dfitpack.fpcurfm1(x, y, k, t, w=w, xb=xb, xe=xe)
+        self._data = data[:-3] + (None, None, data[-1])
+        self._reset_class()
+
+
+# ############### Bivariate spline ####################
+
+class _BivariateSplineBase:
+    """ Base class for Bivariate spline s(x,y) interpolation on the rectangle
+    [xb,xe] x [yb, ye] calculated from a given set of data points
+    (x,y,z).
+
+    See Also
+    --------
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+    BivariateSpline :
+        a base class for bivariate splines.
+    SphereBivariateSpline :
+        a bivariate spline on a spherical grid
+    """
+
+    @classmethod
+    def _from_tck(cls, tck):
+        """Construct a spline object from given tck and degree"""
+        self = cls.__new__(cls)
+        if len(tck) != 5:
+            raise ValueError("tck should be a 5 element tuple of tx,"
+                             " ty, c, kx, ky")
+        self.tck = tck[:3]
+        self.degrees = tck[3:]
+        return self
+
+    def get_residual(self):
+        """ Return weighted sum of squared residuals of the spline
+        approximation: sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0)
+        """
+        return self.fp
+
+    def get_knots(self):
+        """ Return a tuple (tx,ty) where tx,ty contain knots positions
+        of the spline with respect to x-, y-variable, respectively.
+        The position of interior and additional knots are given as
+        t[k+1:-k-1] and t[:k+1]=b, t[-k-1:]=e, respectively.
+        """
+        return self.tck[:2]
+
+    def get_coeffs(self):
+        """ Return spline coefficients."""
+        return self.tck[2]
+
+    def __call__(self, x, y, dx=0, dy=0, grid=True):
+        """
+        Evaluate the spline or its derivatives at given positions.
+
+        Parameters
+        ----------
+        x, y : array_like
+            Input coordinates.
+
+            If `grid` is False, evaluate the spline at points ``(x[i],
+            y[i]), i=0, ..., len(x)-1``.  Standard Numpy broadcasting
+            is obeyed.
+
+            If `grid` is True: evaluate spline at the grid points
+            defined by the coordinate arrays x, y. The arrays must be
+            sorted to increasing order.
+
+            The ordering of axes is consistent with
+            ``np.meshgrid(..., indexing="ij")`` and inconsistent with the
+            default ordering ``np.meshgrid(..., indexing="xy")``.
+        dx : int
+            Order of x-derivative
+
+            .. versionadded:: 0.14.0
+        dy : int
+            Order of y-derivative
+
+            .. versionadded:: 0.14.0
+        grid : bool
+            Whether to evaluate the results on a grid spanned by the
+            input arrays, or at points specified by the input arrays.
+
+            .. versionadded:: 0.14.0
+
+        Examples
+        --------
+        Suppose that we want to bilinearly interpolate an exponentially decaying
+        function in 2 dimensions.
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import RectBivariateSpline
+
+        We sample the function on a coarse grid. Note that the default indexing="xy"
+        of meshgrid would result in an unexpected (transposed) result after
+        interpolation.
+
+        >>> xarr = np.linspace(-3, 3, 100)
+        >>> yarr = np.linspace(-3, 3, 100)
+        >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij")
+
+        The function to interpolate decays faster along one axis than the other.
+
+        >>> zdata = np.exp(-np.sqrt((xgrid / 2) ** 2 + ygrid**2))
+
+        Next we sample on a finer grid using interpolation (kx=ky=1 for bilinear).
+
+        >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1)
+        >>> xarr_fine = np.linspace(-3, 3, 200)
+        >>> yarr_fine = np.linspace(-3, 3, 200)
+        >>> xgrid_fine, ygrid_fine = np.meshgrid(xarr_fine, yarr_fine, indexing="ij")
+        >>> zdata_interp = rbs(xgrid_fine, ygrid_fine, grid=False)
+
+        And check that the result agrees with the input by plotting both.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 2, 1, aspect="equal")
+        >>> ax2 = fig.add_subplot(1, 2, 2, aspect="equal")
+        >>> ax1.imshow(zdata)
+        >>> ax2.imshow(zdata_interp)
+        >>> plt.show()
+        """
+        x = np.asarray(x)
+        y = np.asarray(y)
+
+        tx, ty, c = self.tck[:3]
+        kx, ky = self.degrees
+        if grid:
+            if x.size == 0 or y.size == 0:
+                return np.zeros((x.size, y.size), dtype=self.tck[2].dtype)
+
+            if (x.size >= 2) and (not np.all(np.diff(x) >= 0.0)):
+                raise ValueError("x must be strictly increasing when `grid` is True")
+            if (y.size >= 2) and (not np.all(np.diff(y) >= 0.0)):
+                raise ValueError("y must be strictly increasing when `grid` is True")
+
+            if dx or dy:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by parder: {ier}")
+            else:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.bispev(tx, ty, c, kx, ky, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by bispev: {ier}")
+        else:
+            # standard Numpy broadcasting
+            if x.shape != y.shape:
+                x, y = np.broadcast_arrays(x, y)
+
+            shape = x.shape
+            x = x.ravel()
+            y = y.ravel()
+
+            if x.size == 0 or y.size == 0:
+                return np.zeros(shape, dtype=self.tck[2].dtype)
+
+            if dx or dy:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.pardeu(tx, ty, c, kx, ky, dx, dy, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by pardeu: {ier}")
+            else:
+                with FITPACK_LOCK:
+                    z, ier = dfitpack.bispeu(tx, ty, c, kx, ky, x, y)
+                if not ier == 0:
+                    raise ValueError(f"Error code returned by bispeu: {ier}")
+
+            z = z.reshape(shape)
+        return z
+
+    def partial_derivative(self, dx, dy):
+        """Construct a new spline representing a partial derivative of this
+        spline.
+
+        Parameters
+        ----------
+        dx, dy : int
+            Orders of the derivative in x and y respectively. They must be
+            non-negative integers and less than the respective degree of the
+            original spline (self) in that direction (``kx``, ``ky``).
+
+        Returns
+        -------
+        spline :
+            A new spline of degrees (``kx - dx``, ``ky - dy``) representing the
+            derivative of this spline.
+
+        Notes
+        -----
+
+        .. versionadded:: 1.9.0
+
+        """
+        if dx == 0 and dy == 0:
+            return self
+        else:
+            kx, ky = self.degrees
+            if not (dx >= 0 and dy >= 0):
+                raise ValueError("order of derivative must be positive or"
+                                 " zero")
+            if not (dx < kx and dy < ky):
+                raise ValueError("order of derivative must be less than"
+                                 " degree of spline")
+            tx, ty, c = self.tck[:3]
+            with FITPACK_LOCK:
+                newc, ier = dfitpack.pardtc(tx, ty, c, kx, ky, dx, dy)
+            if ier != 0:
+                # This should not happen under normal conditions.
+                raise ValueError("Unexpected error code returned by"
+                                 " pardtc: %d" % ier)
+            nx = len(tx)
+            ny = len(ty)
+            newtx = tx[dx:nx - dx]
+            newty = ty[dy:ny - dy]
+            newkx, newky = kx - dx, ky - dy
+            newclen = (nx - dx - kx - 1) * (ny - dy - ky - 1)
+            return _DerivedBivariateSpline._from_tck((newtx, newty,
+                                                      newc[:newclen],
+                                                      newkx, newky))
+
+
+_surfit_messages = {1: """
+The required storage space exceeds the available storage space: nxest
+or nyest too small, or s too small.
+The weighted least-squares spline corresponds to the current set of
+knots.""",
+                    2: """
+A theoretically impossible result was found during the iteration
+process for finding a smoothing spline with fp = s: s too small or
+badly chosen eps.
+Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""",
+                    3: """
+the maximal number of iterations maxit (set to 20 by the program)
+allowed for finding a smoothing spline with fp=s has been reached:
+s too small.
+Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""",
+                    4: """
+No more knots can be added because the number of b-spline coefficients
+(nx-kx-1)*(ny-ky-1) already exceeds the number of data points m:
+either s or m too small.
+The weighted least-squares spline corresponds to the current set of
+knots.""",
+                    5: """
+No more knots can be added because the additional knot would (quasi)
+coincide with an old one: s too small or too large a weight to an
+inaccurate data point.
+The weighted least-squares spline corresponds to the current set of
+knots.""",
+                    10: """
+Error on entry, no approximation returned. The following conditions
+must hold:
+xb<=x[i]<=xe, yb<=y[i]<=ye, w[i]>0, i=0..m-1
+If iopt==-1, then
+  xb>> import numpy as np
+        >>> from scipy.interpolate import RectBivariateSpline
+        >>> def f(x, y):
+        ...     return np.exp(-np.sqrt((x / 2) ** 2 + y**2))
+
+        We sample the function on a coarse grid and set up the interpolator. Note that
+        the default ``indexing="xy"`` of meshgrid would result in an unexpected
+        (transposed) result after interpolation.
+
+        >>> xarr = np.linspace(-3, 3, 21)
+        >>> yarr = np.linspace(-3, 3, 21)
+        >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij")
+        >>> zdata = f(xgrid, ygrid)
+        >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1)
+
+        Next we sample the function along a diagonal slice through the coordinate space
+        on a finer grid using interpolation.
+
+        >>> xinterp = np.linspace(-3, 3, 201)
+        >>> yinterp = np.linspace(3, -3, 201)
+        >>> zinterp = rbs.ev(xinterp, yinterp)
+
+        And check that the interpolation passes through the function evaluations as a
+        function of the distance from the origin along the slice.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 1, 1)
+        >>> ax1.plot(np.sqrt(xarr**2 + yarr**2), np.diag(zdata), "or")
+        >>> ax1.plot(np.sqrt(xinterp**2 + yinterp**2), zinterp, "-b")
+        >>> plt.show()
+        """
+        return self.__call__(xi, yi, dx=dx, dy=dy, grid=False)
+
+    def integral(self, xa, xb, ya, yb):
+        """
+        Evaluate the integral of the spline over area [xa,xb] x [ya,yb].
+
+        Parameters
+        ----------
+        xa, xb : float
+            The end-points of the x integration interval.
+        ya, yb : float
+            The end-points of the y integration interval.
+
+        Returns
+        -------
+        integ : float
+            The value of the resulting integral.
+
+        """
+        tx, ty, c = self.tck[:3]
+        kx, ky = self.degrees
+        with FITPACK_LOCK:
+            return dfitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb)
+
+    @staticmethod
+    def _validate_input(x, y, z, w, kx, ky, eps):
+        x, y, z = np.asarray(x), np.asarray(y), np.asarray(z)
+        if not x.size == y.size == z.size:
+            raise ValueError('x, y, and z should have a same length')
+
+        if w is not None:
+            w = np.asarray(w)
+            if x.size != w.size:
+                raise ValueError('x, y, z, and w should have a same length')
+            elif not np.all(w >= 0.0):
+                raise ValueError('w should be positive')
+        if (eps is not None) and (not 0.0 < eps < 1.0):
+            raise ValueError('eps should be between (0, 1)')
+        if not x.size >= (kx + 1) * (ky + 1):
+            raise ValueError('The length of x, y and z should be at least'
+                             ' (kx+1) * (ky+1)')
+        return x, y, z, w
+
+
+class _DerivedBivariateSpline(_BivariateSplineBase):
+    """Bivariate spline constructed from the coefficients and knots of another
+    spline.
+
+    Notes
+    -----
+    The class is not meant to be instantiated directly from the data to be
+    interpolated or smoothed. As a result, its ``fp`` attribute and
+    ``get_residual`` method are inherited but overridden; ``AttributeError`` is
+    raised when they are accessed.
+
+    The other inherited attributes can be used as usual.
+    """
+    _invalid_why = ("is unavailable, because _DerivedBivariateSpline"
+                    " instance is not constructed from data that are to be"
+                    " interpolated or smoothed, but derived from the"
+                    " underlying knots and coefficients of another spline"
+                    " object")
+
+    @property
+    def fp(self):
+        raise AttributeError(f"attribute \"fp\" {self._invalid_why}")
+
+    def get_residual(self):
+        raise AttributeError(f"method \"get_residual\" {self._invalid_why}")
+
+
+class SmoothBivariateSpline(BivariateSpline):
+    """
+    Smooth bivariate spline approximation.
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        1-D sequences of data points (order is not important).
+    w : array_like, optional
+        Positive 1-D sequence of weights, of same length as `x`, `y` and `z`.
+    bbox : array_like, optional
+        Sequence of length 4 specifying the boundary of the rectangular
+        approximation domain.  By default,
+        ``bbox=[min(x), max(x), min(y), max(y)]``.
+    kx, ky : ints, optional
+        Degrees of the bivariate spline. Default is 3.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition:
+        ``sum((w[i]*(z[i]-s(x[i], y[i])))**2, axis=0) <= s``
+        Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an
+        estimate of the standard deviation of ``z[i]``.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the open
+        interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    This routine constructs spline knot vectors automatically via the FITPACK
+    algorithm. The spline knots may be placed away from the data points. For
+    some data sets, this routine may fail to construct an interpolating spline,
+    even if one is requested via ``s=0`` parameter. In such situations, it is
+    recommended to use `bisplrep` / `bisplev` directly instead of this routine
+    and, if needed, increase the values of ``nxest`` and ``nyest`` parameters
+    of `bisplrep`.
+
+    For linear interpolation, prefer `LinearNDInterpolator`.
+    See ``https://gist.github.com/ev-br/8544371b40f414b7eaf3fe6217209bff``
+    for discussion.
+
+    """
+
+    def __init__(self, x, y, z, w=None, bbox=[None] * 4, kx=3, ky=3, s=None,
+                 eps=1e-16):
+
+        x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps)
+        bbox = ravel(bbox)
+        if not bbox.shape == (4,):
+            raise ValueError('bbox shape should be (4,)')
+        if s is not None and not s >= 0.0:
+            raise ValueError("s should be s >= 0.0")
+
+        xb, xe, yb, ye = bbox
+        with FITPACK_LOCK:
+            nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(
+                x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps, lwrk2=1)
+            if ier > 10:          # lwrk2 was to small, re-run
+                nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(
+                    x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps,
+                    lwrk2=ier)
+        if ier in [0, -1, -2]:  # normal return
+            pass
+        else:
+            message = _surfit_messages.get(ier, f'ier={ier}')
+            warnings.warn(message, stacklevel=2)
+
+        self.fp = fp
+        self.tck = tx[:nx], ty[:ny], c[:(nx-kx-1)*(ny-ky-1)]
+        self.degrees = kx, ky
+
+
+class LSQBivariateSpline(BivariateSpline):
+    """
+    Weighted least-squares bivariate spline approximation.
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        1-D sequences of data points (order is not important).
+    tx, ty : array_like
+        Strictly ordered 1-D sequences of knots coordinates.
+    w : array_like, optional
+        Positive 1-D array of weights, of the same length as `x`, `y` and `z`.
+    bbox : (4,) array_like, optional
+        Sequence of length 4 specifying the boundary of the rectangular
+        approximation domain.  By default,
+        ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``.
+    kx, ky : ints, optional
+        Degrees of the bivariate spline. Default is 3.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the open
+        interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    """
+
+    def __init__(self, x, y, z, tx, ty, w=None, bbox=[None]*4, kx=3, ky=3,
+                 eps=None):
+
+        x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps)
+        bbox = ravel(bbox)
+        if not bbox.shape == (4,):
+            raise ValueError('bbox shape should be (4,)')
+
+        nx = 2*kx+2+len(tx)
+        ny = 2*ky+2+len(ty)
+        # The Fortran subroutine "surfit" (called as dfitpack.surfit_lsq)
+        # requires that the knot arrays passed as input should be "real
+        # array(s) of dimension nmax" where "nmax" refers to the greater of nx
+        # and ny. We pad the tx1/ty1 arrays here so that this is satisfied, and
+        # slice them to the desired sizes upon return.
+        nmax = max(nx, ny)
+        tx1 = zeros((nmax,), float)
+        ty1 = zeros((nmax,), float)
+        tx1[kx+1:nx-kx-1] = tx
+        ty1[ky+1:ny-ky-1] = ty
+
+        xb, xe, yb, ye = bbox
+        with FITPACK_LOCK:
+            tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, nx, tx1, ny, ty1,
+                                                    w, xb, xe, yb, ye,
+                                                    kx, ky, eps, lwrk2=1)
+            if ier > 10:
+                tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z,
+                                                        nx, tx1, ny, ty1, w,
+                                                        xb, xe, yb, ye,
+                                                        kx, ky, eps, lwrk2=ier)
+        if ier in [0, -1, -2]:  # normal return
+            pass
+        else:
+            if ier < -2:
+                deficiency = (nx-kx-1)*(ny-ky-1)+ier
+                message = _surfit_messages.get(-3) % (deficiency)
+            else:
+                message = _surfit_messages.get(ier, f'ier={ier}')
+            warnings.warn(message, stacklevel=2)
+        self.fp = fp
+        self.tck = tx1[:nx], ty1[:ny], c
+        self.degrees = kx, ky
+
+
+class RectBivariateSpline(BivariateSpline):
+    """
+    Bivariate spline approximation over a rectangular mesh.
+
+    Can be used for both smoothing and interpolating data.
+
+    Parameters
+    ----------
+    x,y : array_like
+        1-D arrays of coordinates in strictly ascending order.
+        Evaluated points outside the data range will be extrapolated.
+    z : array_like
+        2-D array of data with shape (x.size,y.size).
+    bbox : array_like, optional
+        Sequence of length 4 specifying the boundary of the rectangular
+        approximation domain, which means the start and end spline knots of
+        each dimension are set by these values. By default,
+        ``bbox=[min(x), max(x), min(y), max(y)]``.
+    kx, ky : ints, optional
+        Degrees of the bivariate spline. Default is 3.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition:
+        ``sum((z[i]-f(x[i], y[i]))**2, axis=0) <= s`` where f is a spline
+        function. Default is ``s=0``, which is for interpolation.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    """
+
+    def __init__(self, x, y, z, bbox=[None] * 4, kx=3, ky=3, s=0):
+        x, y, bbox = ravel(x), ravel(y), ravel(bbox)
+        z = np.asarray(z)
+        if not np.all(diff(x) > 0.0):
+            raise ValueError('x must be strictly increasing')
+        if not np.all(diff(y) > 0.0):
+            raise ValueError('y must be strictly increasing')
+        if not x.size == z.shape[0]:
+            raise ValueError('x dimension of z must have same number of '
+                             'elements as x')
+        if not y.size == z.shape[1]:
+            raise ValueError('y dimension of z must have same number of '
+                             'elements as y')
+        if not bbox.shape == (4,):
+            raise ValueError('bbox shape should be (4,)')
+        if s is not None and not s >= 0.0:
+            raise ValueError("s should be s >= 0.0")
+
+        z = ravel(z)
+        xb, xe, yb, ye = bbox
+        with FITPACK_LOCK:
+            nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth(x, y, z, xb, xe, yb,
+                                                            ye, kx, ky, s)
+
+        if ier not in [0, -1, -2]:
+            msg = _surfit_messages.get(ier, f'ier={ier}')
+            raise ValueError(msg)
+
+        self.fp = fp
+        self.tck = tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)]
+        self.degrees = kx, ky
+
+
+_spherefit_messages = _surfit_messages.copy()
+_spherefit_messages[10] = """
+ERROR. On entry, the input data are controlled on validity. The following
+       restrictions must be satisfied:
+            -1<=iopt<=1,  m>=2, ntest>=8 ,npest >=8, 00, i=1,...,m
+            lwrk1 >= 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m
+            kwrk >= m+(ntest-7)*(npest-7)
+            if iopt=-1: 8<=nt<=ntest , 9<=np<=npest
+                        0=0: s>=0
+            if one of these conditions is found to be violated,control
+            is immediately repassed to the calling program. in that
+            case there is no approximation returned."""
+_spherefit_messages[-3] = """
+WARNING. The coefficients of the spline returned have been computed as the
+         minimal norm least-squares solution of a (numerically) rank
+         deficient system (deficiency=%i, rank=%i). Especially if the rank
+         deficiency, which is computed by 6+(nt-8)*(np-7)+ier, is large,
+         the results may be inaccurate. They could also seriously depend on
+         the value of eps."""
+
+
+class SphereBivariateSpline(_BivariateSplineBase):
+    """
+    Bivariate spline s(x,y) of degrees 3 on a sphere, calculated from a
+    given set of data points (theta,phi,r).
+
+    .. versionadded:: 0.11.0
+
+    See Also
+    --------
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQUnivariateSpline :
+        a univariate spline using weighted least-squares fitting
+    """
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+        """
+        Evaluate the spline or its derivatives at given positions.
+
+        Parameters
+        ----------
+        theta, phi : array_like
+            Input coordinates.
+
+            If `grid` is False, evaluate the spline at points
+            ``(theta[i], phi[i]), i=0, ..., len(x)-1``.  Standard
+            Numpy broadcasting is obeyed.
+
+            If `grid` is True: evaluate spline at the grid points
+            defined by the coordinate arrays theta, phi. The arrays
+            must be sorted to increasing order.
+            The ordering of axes is consistent with
+            ``np.meshgrid(..., indexing="ij")`` and inconsistent with the
+            default ordering ``np.meshgrid(..., indexing="xy")``.
+        dtheta : int, optional
+            Order of theta-derivative
+
+            .. versionadded:: 0.14.0
+        dphi : int
+            Order of phi-derivative
+
+            .. versionadded:: 0.14.0
+        grid : bool
+            Whether to evaluate the results on a grid spanned by the
+            input arrays, or at points specified by the input arrays.
+
+            .. versionadded:: 0.14.0
+
+        Examples
+        --------
+
+        Suppose that we want to use splines to interpolate a bivariate function on a
+        sphere. The value of the function is known on a grid of longitudes and
+        colatitudes.
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import RectSphereBivariateSpline
+        >>> def f(theta, phi):
+        ...     return np.sin(theta) * np.cos(phi)
+
+        We evaluate the function on the grid. Note that the default indexing="xy"
+        of meshgrid would result in an unexpected (transposed) result after
+        interpolation.
+
+        >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1]
+        >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1]
+        >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij")
+        >>> zdata = f(thetagrid, phigrid)
+
+        We next set up the interpolator and use it to evaluate the function
+        on a finer grid.
+
+        >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata)
+        >>> thetaarr_fine = np.linspace(0, np.pi, 200)
+        >>> phiarr_fine = np.linspace(0, 2 * np.pi, 200)
+        >>> zdata_fine = rsbs(thetaarr_fine, phiarr_fine)
+
+        Finally we plot the coarsly-sampled input data alongside the
+        finely-sampled interpolated data to check that they agree.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 2, 1)
+        >>> ax2 = fig.add_subplot(1, 2, 2)
+        >>> ax1.imshow(zdata)
+        >>> ax2.imshow(zdata_fine)
+        >>> plt.show()
+        """
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        if theta.size > 0 and (theta.min() < 0. or theta.max() > np.pi):
+            raise ValueError("requested theta out of bounds.")
+
+        return _BivariateSplineBase.__call__(self, theta, phi,
+                                             dx=dtheta, dy=dphi, grid=grid)
+
+    def ev(self, theta, phi, dtheta=0, dphi=0):
+        """
+        Evaluate the spline at points
+
+        Returns the interpolated value at ``(theta[i], phi[i]),
+        i=0,...,len(theta)-1``.
+
+        Parameters
+        ----------
+        theta, phi : array_like
+            Input coordinates. Standard Numpy broadcasting is obeyed.
+            The ordering of axes is consistent with
+            np.meshgrid(..., indexing="ij") and inconsistent with the
+            default ordering np.meshgrid(..., indexing="xy").
+        dtheta : int, optional
+            Order of theta-derivative
+
+            .. versionadded:: 0.14.0
+        dphi : int, optional
+            Order of phi-derivative
+
+            .. versionadded:: 0.14.0
+
+        Examples
+        --------
+        Suppose that we want to use splines to interpolate a bivariate function on a
+        sphere. The value of the function is known on a grid of longitudes and
+        colatitudes.
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import RectSphereBivariateSpline
+        >>> def f(theta, phi):
+        ...     return np.sin(theta) * np.cos(phi)
+
+        We evaluate the function on the grid. Note that the default indexing="xy"
+        of meshgrid would result in an unexpected (transposed) result after
+        interpolation.
+
+        >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1]
+        >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1]
+        >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij")
+        >>> zdata = f(thetagrid, phigrid)
+
+        We next set up the interpolator and use it to evaluate the function
+        at points not on the original grid.
+
+        >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata)
+        >>> thetainterp = np.linspace(thetaarr[0], thetaarr[-1], 200)
+        >>> phiinterp = np.linspace(phiarr[0], phiarr[-1], 200)
+        >>> zinterp = rsbs.ev(thetainterp, phiinterp)
+
+        Finally we plot the original data for a diagonal slice through the
+        initial grid, and the spline approximation along the same slice.
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig = plt.figure()
+        >>> ax1 = fig.add_subplot(1, 1, 1)
+        >>> ax1.plot(np.sin(thetaarr) * np.sin(phiarr), np.diag(zdata), "or")
+        >>> ax1.plot(np.sin(thetainterp) * np.sin(phiinterp), zinterp, "-b")
+        >>> plt.show()
+        """
+        return self.__call__(theta, phi, dtheta=dtheta, dphi=dphi, grid=False)
+
+
+class SmoothSphereBivariateSpline(SphereBivariateSpline):
+    """
+    Smooth bivariate spline approximation in spherical coordinates.
+
+    .. versionadded:: 0.11.0
+
+    Parameters
+    ----------
+    theta, phi, r : array_like
+        1-D sequences of data points (order is not important). Coordinates
+        must be given in radians. Theta must lie within the interval
+        ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``.
+    w : array_like, optional
+        Positive 1-D sequence of weights.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition:
+        ``sum((w(i)*(r(i) - s(theta(i), phi(i))))**2, axis=0) <= s``
+        Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an
+        estimate of the standard deviation of ``r[i]``.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the open
+        interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    For more information, see the FITPACK_ site about this function.
+
+    .. _FITPACK: http://www.netlib.org/dierckx/sphere.f
+
+    Examples
+    --------
+    Suppose we have global data on a coarse grid (the input data does not
+    have to be on a grid):
+
+    >>> import numpy as np
+    >>> theta = np.linspace(0., np.pi, 7)
+    >>> phi = np.linspace(0., 2*np.pi, 9)
+    >>> data = np.empty((theta.shape[0], phi.shape[0]))
+    >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.
+    >>> data[1:-1,1], data[1:-1,-1] = 1., 1.
+    >>> data[1,1:-1], data[-2,1:-1] = 1., 1.
+    >>> data[2:-2,2], data[2:-2,-2] = 2., 2.
+    >>> data[2,2:-2], data[-3,2:-2] = 2., 2.
+    >>> data[3,3:-2] = 3.
+    >>> data = np.roll(data, 4, 1)
+
+    We need to set up the interpolator object
+
+    >>> lats, lons = np.meshgrid(theta, phi)
+    >>> from scipy.interpolate import SmoothSphereBivariateSpline
+    >>> lut = SmoothSphereBivariateSpline(lats.ravel(), lons.ravel(),
+    ...                                   data.T.ravel(), s=3.5)
+
+    As a first test, we'll see what the algorithm returns when run on the
+    input coordinates
+
+    >>> data_orig = lut(theta, phi)
+
+    Finally we interpolate the data to a finer grid
+
+    >>> fine_lats = np.linspace(0., np.pi, 70)
+    >>> fine_lons = np.linspace(0., 2 * np.pi, 90)
+
+    >>> data_smth = lut(fine_lats, fine_lons)
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(131)
+    >>> ax1.imshow(data, interpolation='nearest')
+    >>> ax2 = fig.add_subplot(132)
+    >>> ax2.imshow(data_orig, interpolation='nearest')
+    >>> ax3 = fig.add_subplot(133)
+    >>> ax3.imshow(data_smth, interpolation='nearest')
+    >>> plt.show()
+
+    """
+
+    def __init__(self, theta, phi, r, w=None, s=0., eps=1E-16):
+
+        theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r)
+
+        # input validation
+        if not ((0.0 <= theta).all() and (theta <= np.pi).all()):
+            raise ValueError('theta should be between [0, pi]')
+        if not ((0.0 <= phi).all() and (phi <= 2.0 * np.pi).all()):
+            raise ValueError('phi should be between [0, 2pi]')
+        if w is not None:
+            w = np.asarray(w)
+            if not (w >= 0.0).all():
+                raise ValueError('w should be positive')
+        if not s >= 0.0:
+            raise ValueError('s should be positive')
+        if not 0.0 < eps < 1.0:
+            raise ValueError('eps should be between (0, 1)')
+
+        with FITPACK_LOCK:
+            nt_, tt_, np_, tp_, c, fp, ier = dfitpack.spherfit_smth(theta, phi,
+                                                                    r, w=w, s=s,
+                                                                    eps=eps)
+        if ier not in [0, -1, -2]:
+            message = _spherefit_messages.get(ier, f'ier={ier}')
+            raise ValueError(message)
+
+        self.fp = fp
+        self.tck = tt_[:nt_], tp_[:np_], c[:(nt_ - 4) * (np_ - 4)]
+        self.degrees = (3, 3)
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi):
+            raise ValueError("requested phi out of bounds.")
+
+        return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
+                                              dphi=dphi, grid=grid)
+
+
+class LSQSphereBivariateSpline(SphereBivariateSpline):
+    """
+    Weighted least-squares bivariate spline approximation in spherical
+    coordinates.
+
+    Determines a smoothing bicubic spline according to a given
+    set of knots in the `theta` and `phi` directions.
+
+    .. versionadded:: 0.11.0
+
+    Parameters
+    ----------
+    theta, phi, r : array_like
+        1-D sequences of data points (order is not important). Coordinates
+        must be given in radians. Theta must lie within the interval
+        ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``.
+    tt, tp : array_like
+        Strictly ordered 1-D sequences of knots coordinates.
+        Coordinates must satisfy ``0 < tt[i] < pi``, ``0 < tp[i] < 2*pi``.
+    w : array_like, optional
+        Positive 1-D sequence of weights, of the same length as `theta`, `phi`
+        and `r`.
+    eps : float, optional
+        A threshold for determining the effective rank of an over-determined
+        linear system of equations. `eps` should have a value within the
+        open interval ``(0, 1)``, the default is 1e-16.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    RectSphereBivariateSpline :
+        a bivariate spline over a rectangular mesh on a sphere
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    For more information, see the FITPACK_ site about this function.
+
+    .. _FITPACK: http://www.netlib.org/dierckx/sphere.f
+
+    Examples
+    --------
+    Suppose we have global data on a coarse grid (the input data does not
+    have to be on a grid):
+
+    >>> from scipy.interpolate import LSQSphereBivariateSpline
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+
+    >>> theta = np.linspace(0, np.pi, num=7)
+    >>> phi = np.linspace(0, 2*np.pi, num=9)
+    >>> data = np.empty((theta.shape[0], phi.shape[0]))
+    >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.
+    >>> data[1:-1,1], data[1:-1,-1] = 1., 1.
+    >>> data[1,1:-1], data[-2,1:-1] = 1., 1.
+    >>> data[2:-2,2], data[2:-2,-2] = 2., 2.
+    >>> data[2,2:-2], data[-3,2:-2] = 2., 2.
+    >>> data[3,3:-2] = 3.
+    >>> data = np.roll(data, 4, 1)
+
+    We need to set up the interpolator object. Here, we must also specify the
+    coordinates of the knots to use.
+
+    >>> lats, lons = np.meshgrid(theta, phi)
+    >>> knotst, knotsp = theta.copy(), phi.copy()
+    >>> knotst[0] += .0001
+    >>> knotst[-1] -= .0001
+    >>> knotsp[0] += .0001
+    >>> knotsp[-1] -= .0001
+    >>> lut = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
+    ...                                data.T.ravel(), knotst, knotsp)
+
+    As a first test, we'll see what the algorithm returns when run on the
+    input coordinates
+
+    >>> data_orig = lut(theta, phi)
+
+    Finally we interpolate the data to a finer grid
+
+    >>> fine_lats = np.linspace(0., np.pi, 70)
+    >>> fine_lons = np.linspace(0., 2*np.pi, 90)
+    >>> data_lsq = lut(fine_lats, fine_lons)
+
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(131)
+    >>> ax1.imshow(data, interpolation='nearest')
+    >>> ax2 = fig.add_subplot(132)
+    >>> ax2.imshow(data_orig, interpolation='nearest')
+    >>> ax3 = fig.add_subplot(133)
+    >>> ax3.imshow(data_lsq, interpolation='nearest')
+    >>> plt.show()
+
+    """
+
+    def __init__(self, theta, phi, r, tt, tp, w=None, eps=1E-16):
+
+        theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r)
+        tt, tp = np.asarray(tt), np.asarray(tp)
+
+        if not ((0.0 <= theta).all() and (theta <= np.pi).all()):
+            raise ValueError('theta should be between [0, pi]')
+        if not ((0.0 <= phi).all() and (phi <= 2*np.pi).all()):
+            raise ValueError('phi should be between [0, 2pi]')
+        if not ((0.0 < tt).all() and (tt < np.pi).all()):
+            raise ValueError('tt should be between (0, pi)')
+        if not ((0.0 < tp).all() and (tp < 2*np.pi).all()):
+            raise ValueError('tp should be between (0, 2pi)')
+        if w is not None:
+            w = np.asarray(w)
+            if not (w >= 0.0).all():
+                raise ValueError('w should be positive')
+        if not 0.0 < eps < 1.0:
+            raise ValueError('eps should be between (0, 1)')
+
+        nt_, np_ = 8 + len(tt), 8 + len(tp)
+        tt_, tp_ = zeros((nt_,), float), zeros((np_,), float)
+        tt_[4:-4], tp_[4:-4] = tt, tp
+        tt_[-4:], tp_[-4:] = np.pi, 2. * np.pi
+        with FITPACK_LOCK:
+            tt_, tp_, c, fp, ier = dfitpack.spherfit_lsq(theta, phi, r, tt_, tp_,
+                                                        w=w, eps=eps)
+        if ier > 0:
+            message = _spherefit_messages.get(ier, f'ier={ier}')
+            raise ValueError(message)
+
+        self.fp = fp
+        self.tck = tt_, tp_, c
+        self.degrees = (3, 3)
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi):
+            raise ValueError("requested phi out of bounds.")
+
+        return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
+                                              dphi=dphi, grid=grid)
+
+
+_spfit_messages = _surfit_messages.copy()
+_spfit_messages[10] = """
+ERROR: on entry, the input data are controlled on validity
+       the following restrictions must be satisfied.
+          -1<=iopt(1)<=1, 0<=iopt(2)<=1, 0<=iopt(3)<=1,
+          -1<=ider(1)<=1, 0<=ider(2)<=1, ider(2)=0 if iopt(2)=0.
+          -1<=ider(3)<=1, 0<=ider(4)<=1, ider(4)=0 if iopt(3)=0.
+          mu >= mumin (see above), mv >= 4, nuest >=8, nvest >= 8,
+          kwrk>=5+mu+mv+nuest+nvest,
+          lwrk >= 12+nuest*(mv+nvest+3)+nvest*24+4*mu+8*mv+max(nuest,mv+nvest)
+          0< u(i-1)=0: s>=0
+          if s=0: nuest>=mu+6+iopt(2)+iopt(3), nvest>=mv+7
+       if one of these conditions is found to be violated,control is
+       immediately repassed to the calling program. in that case there is no
+       approximation returned."""
+
+
+class RectSphereBivariateSpline(SphereBivariateSpline):
+    """
+    Bivariate spline approximation over a rectangular mesh on a sphere.
+
+    Can be used for smoothing data.
+
+    .. versionadded:: 0.11.0
+
+    Parameters
+    ----------
+    u : array_like
+        1-D array of colatitude coordinates in strictly ascending order.
+        Coordinates must be given in radians and lie within the open interval
+        ``(0, pi)``.
+    v : array_like
+        1-D array of longitude coordinates in strictly ascending order.
+        Coordinates must be given in radians. First element (``v[0]``) must lie
+        within the interval ``[-pi, pi)``. Last element (``v[-1]``) must satisfy
+        ``v[-1] <= v[0] + 2*pi``.
+    r : array_like
+        2-D array of data with shape ``(u.size, v.size)``.
+    s : float, optional
+        Positive smoothing factor defined for estimation condition
+        (``s=0`` is for interpolation).
+    pole_continuity : bool or (bool, bool), optional
+        Order of continuity at the poles ``u=0`` (``pole_continuity[0]``) and
+        ``u=pi`` (``pole_continuity[1]``).  The order of continuity at the pole
+        will be 1 or 0 when this is True or False, respectively.
+        Defaults to False.
+    pole_values : float or (float, float), optional
+        Data values at the poles ``u=0`` and ``u=pi``.  Either the whole
+        parameter or each individual element can be None.  Defaults to None.
+    pole_exact : bool or (bool, bool), optional
+        Data value exactness at the poles ``u=0`` and ``u=pi``.  If True, the
+        value is considered to be the right function value, and it will be
+        fitted exactly. If False, the value will be considered to be a data
+        value just like the other data values.  Defaults to False.
+    pole_flat : bool or (bool, bool), optional
+        For the poles at ``u=0`` and ``u=pi``, specify whether or not the
+        approximation has vanishing derivatives.  Defaults to False.
+
+    See Also
+    --------
+    BivariateSpline :
+        a base class for bivariate splines.
+    UnivariateSpline :
+        a smooth univariate spline to fit a given set of data points.
+    SmoothBivariateSpline :
+        a smoothing bivariate spline through the given points
+    LSQBivariateSpline :
+        a bivariate spline using weighted least-squares fitting
+    SmoothSphereBivariateSpline :
+        a smoothing bivariate spline in spherical coordinates
+    LSQSphereBivariateSpline :
+        a bivariate spline in spherical coordinates using weighted
+        least-squares fitting
+    RectBivariateSpline :
+        a bivariate spline over a rectangular mesh.
+    bisplrep :
+        a function to find a bivariate B-spline representation of a surface
+    bisplev :
+        a function to evaluate a bivariate B-spline and its derivatives
+
+    Notes
+    -----
+    Currently, only the smoothing spline approximation (``iopt[0] = 0`` and
+    ``iopt[0] = 1`` in the FITPACK routine) is supported.  The exact
+    least-squares spline approximation is not implemented yet.
+
+    When actually performing the interpolation, the requested `v` values must
+    lie within the same length 2pi interval that the original `v` values were
+    chosen from.
+
+    For more information, see the FITPACK_ site about this function.
+
+    .. _FITPACK: http://www.netlib.org/dierckx/spgrid.f
+
+    Examples
+    --------
+    Suppose we have global data on a coarse grid
+
+    >>> import numpy as np
+    >>> lats = np.linspace(10, 170, 9) * np.pi / 180.
+    >>> lons = np.linspace(0, 350, 18) * np.pi / 180.
+    >>> data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T,
+    ...               np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T
+
+    We want to interpolate it to a global one-degree grid
+
+    >>> new_lats = np.linspace(1, 180, 180) * np.pi / 180
+    >>> new_lons = np.linspace(1, 360, 360) * np.pi / 180
+    >>> new_lats, new_lons = np.meshgrid(new_lats, new_lons)
+
+    We need to set up the interpolator object
+
+    >>> from scipy.interpolate import RectSphereBivariateSpline
+    >>> lut = RectSphereBivariateSpline(lats, lons, data)
+
+    Finally we interpolate the data.  The `RectSphereBivariateSpline` object
+    only takes 1-D arrays as input, therefore we need to do some reshaping.
+
+    >>> data_interp = lut.ev(new_lats.ravel(),
+    ...                      new_lons.ravel()).reshape((360, 180)).T
+
+    Looking at the original and the interpolated data, one can see that the
+    interpolant reproduces the original data very well:
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(211)
+    >>> ax1.imshow(data, interpolation='nearest')
+    >>> ax2 = fig.add_subplot(212)
+    >>> ax2.imshow(data_interp, interpolation='nearest')
+    >>> plt.show()
+
+    Choosing the optimal value of ``s`` can be a delicate task. Recommended
+    values for ``s`` depend on the accuracy of the data values.  If the user
+    has an idea of the statistical errors on the data, she can also find a
+    proper estimate for ``s``. By assuming that, if she specifies the
+    right ``s``, the interpolator will use a spline ``f(u,v)`` which exactly
+    reproduces the function underlying the data, she can evaluate
+    ``sum((r(i,j)-s(u(i),v(j)))**2)`` to find a good estimate for this ``s``.
+    For example, if she knows that the statistical errors on her
+    ``r(i,j)``-values are not greater than 0.1, she may expect that a good
+    ``s`` should have a value not larger than ``u.size * v.size * (0.1)**2``.
+
+    If nothing is known about the statistical error in ``r(i,j)``, ``s`` must
+    be determined by trial and error.  The best is then to start with a very
+    large value of ``s`` (to determine the least-squares polynomial and the
+    corresponding upper bound ``fp0`` for ``s``) and then to progressively
+    decrease the value of ``s`` (say by a factor 10 in the beginning, i.e.
+    ``s = fp0 / 10, fp0 / 100, ...``  and more carefully as the approximation
+    shows more detail) to obtain closer fits.
+
+    The interpolation results for different values of ``s`` give some insight
+    into this process:
+
+    >>> fig2 = plt.figure()
+    >>> s = [3e9, 2e9, 1e9, 1e8]
+    >>> for idx, sval in enumerate(s, 1):
+    ...     lut = RectSphereBivariateSpline(lats, lons, data, s=sval)
+    ...     data_interp = lut.ev(new_lats.ravel(),
+    ...                          new_lons.ravel()).reshape((360, 180)).T
+    ...     ax = fig2.add_subplot(2, 2, idx)
+    ...     ax.imshow(data_interp, interpolation='nearest')
+    ...     ax.set_title(f"s = {sval:g}")
+    >>> plt.show()
+
+    """
+
+    def __init__(self, u, v, r, s=0., pole_continuity=False, pole_values=None,
+                 pole_exact=False, pole_flat=False):
+        iopt = np.array([0, 0, 0], dtype=dfitpack_int)
+        ider = np.array([-1, 0, -1, 0], dtype=dfitpack_int)
+        if pole_values is None:
+            pole_values = (None, None)
+        elif isinstance(pole_values, (float, np.float32, np.float64)):
+            pole_values = (pole_values, pole_values)
+        if isinstance(pole_continuity, bool):
+            pole_continuity = (pole_continuity, pole_continuity)
+        if isinstance(pole_exact, bool):
+            pole_exact = (pole_exact, pole_exact)
+        if isinstance(pole_flat, bool):
+            pole_flat = (pole_flat, pole_flat)
+
+        r0, r1 = pole_values
+        iopt[1:] = pole_continuity
+        if r0 is None:
+            ider[0] = -1
+        else:
+            ider[0] = pole_exact[0]
+
+        if r1 is None:
+            ider[2] = -1
+        else:
+            ider[2] = pole_exact[1]
+
+        ider[1], ider[3] = pole_flat
+
+        u, v = np.ravel(u), np.ravel(v)
+        r = np.asarray(r)
+
+        if not (0.0 < u[0] and u[-1] < np.pi):
+            raise ValueError('u should be between (0, pi)')
+        if not -np.pi <= v[0] < np.pi:
+            raise ValueError('v[0] should be between [-pi, pi)')
+        if not v[-1] <= v[0] + 2*np.pi:
+            raise ValueError('v[-1] should be v[0] + 2pi or less ')
+
+        if not np.all(np.diff(u) > 0.0):
+            raise ValueError('u must be strictly increasing')
+        if not np.all(np.diff(v) > 0.0):
+            raise ValueError('v must be strictly increasing')
+
+        if not u.size == r.shape[0]:
+            raise ValueError('u dimension of r must have same number of '
+                             'elements as u')
+        if not v.size == r.shape[1]:
+            raise ValueError('v dimension of r must have same number of '
+                             'elements as v')
+
+        if pole_continuity[1] is False and pole_flat[1] is True:
+            raise ValueError('if pole_continuity is False, so must be '
+                             'pole_flat')
+        if pole_continuity[0] is False and pole_flat[0] is True:
+            raise ValueError('if pole_continuity is False, so must be '
+                             'pole_flat')
+
+        if not s >= 0.0:
+            raise ValueError('s should be positive')
+
+        r = np.ravel(r)
+        with FITPACK_LOCK:
+            nu, tu, nv, tv, c, fp, ier = dfitpack.regrid_smth_spher(iopt, ider,
+                                                                    u.copy(),
+                                                                    v.copy(),
+                                                                    r.copy(),
+                                                                    r0, r1, s)
+
+        if ier not in [0, -1, -2]:
+            msg = _spfit_messages.get(ier, f'ier={ier}')
+            raise ValueError(msg)
+
+        self.fp = fp
+        self.tck = tu[:nu], tv[:nv], c[:(nu - 4) * (nv-4)]
+        self.degrees = (3, 3)
+        self.v0 = v[0]
+
+    def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
+
+        theta = np.asarray(theta)
+        phi = np.asarray(phi)
+
+        return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
+                                              dphi=dphi, grid=grid)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_impl.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_impl.py
new file mode 100644
index 0000000000000000000000000000000000000000..a00ca101b591dd69b6b590278083f0bdafbd3a01
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_impl.py
@@ -0,0 +1,805 @@
+"""
+fitpack (dierckx in netlib) --- A Python-C wrapper to FITPACK (by P. Dierckx).
+        FITPACK is a collection of FORTRAN programs for curve and surface
+        fitting with splines and tensor product splines.
+
+See
+ https://web.archive.org/web/20010524124604/http://www.cs.kuleuven.ac.be:80/cwis/research/nalag/research/topics/fitpack.html
+or
+ http://www.netlib.org/dierckx/
+
+Copyright 2002 Pearu Peterson all rights reserved,
+Pearu Peterson 
+Permission to use, modify, and distribute this software is given under the
+terms of the SciPy (BSD style) license. See LICENSE.txt that came with
+this distribution for specifics.
+
+NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
+
+TODO: Make interfaces to the following fitpack functions:
+    For univariate splines: cocosp, concon, fourco, insert
+    For bivariate splines: profil, regrid, parsur, surev
+"""
+
+__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde',
+           'bisplrep', 'bisplev', 'insert', 'splder', 'splantider']
+
+import warnings
+import numpy as np
+from . import _fitpack
+from numpy import (atleast_1d, array, ones, zeros, sqrt, ravel, transpose,
+                   empty, iinfo, asarray)
+
+# Try to replace _fitpack interface with
+#  f2py-generated version
+from . import _dfitpack as dfitpack
+
+
+dfitpack_int = dfitpack.types.intvar.dtype
+
+
+def _int_overflow(x, exception, msg=None):
+    """Cast the value to an dfitpack_int and raise an OverflowError if the value
+    cannot fit.
+    """
+    if x > iinfo(dfitpack_int).max:
+        if msg is None:
+            msg = f'{x!r} cannot fit into an {dfitpack_int!r}'
+        raise exception(msg)
+    return dfitpack_int.type(x)
+
+
+_iermess = {
+    0: ["The spline has a residual sum of squares fp such that "
+        "abs(fp-s)/s<=0.001", None],
+    -1: ["The spline is an interpolating spline (fp=0)", None],
+    -2: ["The spline is weighted least-squares polynomial of degree k.\n"
+         "fp gives the upper bound fp0 for the smoothing factor s", None],
+    1: ["The required storage space exceeds the available storage space.\n"
+        "Probable causes: data (x,y) size is too small or smoothing parameter"
+        "\ns is too small (fp>s).", ValueError],
+    2: ["A theoretically impossible result when finding a smoothing spline\n"
+        "with fp = s. Probable cause: s too small. (abs(fp-s)/s>0.001)",
+        ValueError],
+    3: ["The maximal number of iterations (20) allowed for finding smoothing\n"
+        "spline with fp=s has been reached. Probable cause: s too small.\n"
+        "(abs(fp-s)/s>0.001)", ValueError],
+    10: ["Error on input data", ValueError],
+    'unknown': ["An error occurred", TypeError]
+}
+
+_iermess2 = {
+    0: ["The spline has a residual sum of squares fp such that "
+        "abs(fp-s)/s<=0.001", None],
+    -1: ["The spline is an interpolating spline (fp=0)", None],
+    -2: ["The spline is weighted least-squares polynomial of degree kx and ky."
+         "\nfp gives the upper bound fp0 for the smoothing factor s", None],
+    -3: ["Warning. The coefficients of the spline have been computed as the\n"
+         "minimal norm least-squares solution of a rank deficient system.",
+         None],
+    1: ["The required storage space exceeds the available storage space.\n"
+        "Probable causes: nxest or nyest too small or s is too small. (fp>s)",
+        ValueError],
+    2: ["A theoretically impossible result when finding a smoothing spline\n"
+        "with fp = s. Probable causes: s too small or badly chosen eps.\n"
+        "(abs(fp-s)/s>0.001)", ValueError],
+    3: ["The maximal number of iterations (20) allowed for finding smoothing\n"
+        "spline with fp=s has been reached. Probable cause: s too small.\n"
+        "(abs(fp-s)/s>0.001)", ValueError],
+    4: ["No more knots can be added because the number of B-spline\n"
+        "coefficients already exceeds the number of data points m.\n"
+        "Probable causes: either s or m too small. (fp>s)", ValueError],
+    5: ["No more knots can be added because the additional knot would\n"
+        "coincide with an old one. Probable cause: s too small or too large\n"
+        "a weight to an inaccurate data point. (fp>s)", ValueError],
+    10: ["Error on input data", ValueError],
+    11: ["rwrk2 too small, i.e., there is not enough workspace for computing\n"
+         "the minimal least-squares solution of a rank deficient system of\n"
+         "linear equations.", ValueError],
+    'unknown': ["An error occurred", TypeError]
+}
+
+_parcur_cache = {'t': array([], float), 'wrk': array([], float),
+                 'iwrk': array([], dfitpack_int), 'u': array([], float),
+                 'ub': 0, 'ue': 1}
+
+
+def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None,
+            full_output=0, nest=None, per=0, quiet=1):
+    # see the docstring of `_fitpack_py/splprep`
+    if task <= 0:
+        _parcur_cache = {'t': array([], float), 'wrk': array([], float),
+                         'iwrk': array([], dfitpack_int), 'u': array([], float),
+                         'ub': 0, 'ue': 1}
+    x = atleast_1d(x)
+    idim, m = x.shape
+    if per:
+        for i in range(idim):
+            if x[i][0] != x[i][-1]:
+                if not quiet:
+                    warnings.warn(RuntimeWarning('Setting x[%d][%d]=x[%d][0]' %
+                                                 (i, m, i)),
+                                  stacklevel=2)
+                x[i][-1] = x[i][0]
+    if not 0 < idim < 11:
+        raise TypeError('0 < idim < 11 must hold')
+    if w is None:
+        w = ones(m, float)
+    else:
+        w = atleast_1d(w)
+    ipar = (u is not None)
+    if ipar:
+        _parcur_cache['u'] = u
+        if ub is None:
+            _parcur_cache['ub'] = u[0]
+        else:
+            _parcur_cache['ub'] = ub
+        if ue is None:
+            _parcur_cache['ue'] = u[-1]
+        else:
+            _parcur_cache['ue'] = ue
+    else:
+        _parcur_cache['u'] = zeros(m, float)
+    if not (1 <= k <= 5):
+        raise TypeError('1 <= k= %d <=5 must hold' % k)
+    if not (-1 <= task <= 1):
+        raise TypeError('task must be -1, 0 or 1')
+    if (not len(w) == m) or (ipar == 1 and (not len(u) == m)):
+        raise TypeError('Mismatch of input dimensions')
+    if s is None:
+        s = m - sqrt(2*m)
+    if t is None and task == -1:
+        raise TypeError('Knots must be given for task=-1')
+    if t is not None:
+        _parcur_cache['t'] = atleast_1d(t)
+    n = len(_parcur_cache['t'])
+    if task == -1 and n < 2*k + 2:
+        raise TypeError('There must be at least 2*k+2 knots for task=-1')
+    if m <= k:
+        raise TypeError('m > k must hold')
+    if nest is None:
+        nest = m + 2*k
+
+    if (task >= 0 and s == 0) or (nest < 0):
+        if per:
+            nest = m + 2*k
+        else:
+            nest = m + k + 1
+    nest = max(nest, 2*k + 3)
+    u = _parcur_cache['u']
+    ub = _parcur_cache['ub']
+    ue = _parcur_cache['ue']
+    t = _parcur_cache['t']
+    wrk = _parcur_cache['wrk']
+    iwrk = _parcur_cache['iwrk']
+    t, c, o = _fitpack._parcur(ravel(transpose(x)), w, u, ub, ue, k,
+                               task, ipar, s, t, nest, wrk, iwrk, per)
+    _parcur_cache['u'] = o['u']
+    _parcur_cache['ub'] = o['ub']
+    _parcur_cache['ue'] = o['ue']
+    _parcur_cache['t'] = t
+    _parcur_cache['wrk'] = o['wrk']
+    _parcur_cache['iwrk'] = o['iwrk']
+    ier = o['ier']
+    fp = o['fp']
+    n = len(t)
+    u = o['u']
+    c.shape = idim, n - k - 1
+    tcku = [t, list(c), k], u
+    if ier <= 0 and not quiet:
+        warnings.warn(RuntimeWarning(_iermess[ier][0] +
+                                     "\tk=%d n=%d m=%d fp=%f s=%f" %
+                                     (k, len(t), m, fp, s)),
+                      stacklevel=2)
+    if ier > 0 and not full_output:
+        if ier in [1, 2, 3]:
+            warnings.warn(RuntimeWarning(_iermess[ier][0]), stacklevel=2)
+        else:
+            try:
+                raise _iermess[ier][1](_iermess[ier][0])
+            except KeyError as e:
+                raise _iermess['unknown'][1](_iermess['unknown'][0]) from e
+    if full_output:
+        try:
+            return tcku, fp, ier, _iermess[ier][0]
+        except KeyError:
+            return tcku, fp, ier, _iermess['unknown'][0]
+    else:
+        return tcku
+
+
+_curfit_cache = {'t': array([], float), 'wrk': array([], float),
+                 'iwrk': array([], dfitpack_int)}
+
+
+def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None,
+           full_output=0, per=0, quiet=1):
+    # see the docstring of `_fitpack_py/splrep`
+    if task <= 0:
+        _curfit_cache = {}
+    x, y = map(atleast_1d, [x, y])
+    m = len(x)
+    if w is None:
+        w = ones(m, float)
+        if s is None:
+            s = 0.0
+    else:
+        w = atleast_1d(w)
+        if s is None:
+            s = m - sqrt(2*m)
+    if not len(w) == m:
+        raise TypeError('len(w)=%d is not equal to m=%d' % (len(w), m))
+    if (m != len(y)) or (m != len(w)):
+        raise TypeError('Lengths of the first three arguments (x,y,w) must '
+                        'be equal')
+    if not (1 <= k <= 5):
+        raise TypeError('Given degree of the spline (k=%d) is not supported. '
+                        '(1<=k<=5)' % k)
+    if m <= k:
+        raise TypeError('m > k must hold')
+    if xb is None:
+        xb = x[0]
+    if xe is None:
+        xe = x[-1]
+    if not (-1 <= task <= 1):
+        raise TypeError('task must be -1, 0 or 1')
+    if t is not None:
+        task = -1
+    if task == -1:
+        if t is None:
+            raise TypeError('Knots must be given for task=-1')
+        numknots = len(t)
+        _curfit_cache['t'] = empty((numknots + 2*k + 2,), float)
+        _curfit_cache['t'][k+1:-k-1] = t
+        nest = len(_curfit_cache['t'])
+    elif task == 0:
+        if per:
+            nest = max(m + 2*k, 2*k + 3)
+        else:
+            nest = max(m + k + 1, 2*k + 3)
+        t = empty((nest,), float)
+        _curfit_cache['t'] = t
+    if task <= 0:
+        if per:
+            _curfit_cache['wrk'] = empty((m*(k + 1) + nest*(8 + 5*k),), float)
+        else:
+            _curfit_cache['wrk'] = empty((m*(k + 1) + nest*(7 + 3*k),), float)
+        _curfit_cache['iwrk'] = empty((nest,), dfitpack_int)
+    try:
+        t = _curfit_cache['t']
+        wrk = _curfit_cache['wrk']
+        iwrk = _curfit_cache['iwrk']
+    except KeyError as e:
+        raise TypeError("must call with task=1 only after"
+                        " call with task=0,-1") from e
+    if not per:
+        n, c, fp, ier = dfitpack.curfit(task, x, y, w, t, wrk, iwrk,
+                                        xb, xe, k, s)
+    else:
+        n, c, fp, ier = dfitpack.percur(task, x, y, w, t, wrk, iwrk, k, s)
+    tck = (t[:n], c[:n], k)
+    if ier <= 0 and not quiet:
+        _mess = (_iermess[ier][0] + "\tk=%d n=%d m=%d fp=%f s=%f" %
+                 (k, len(t), m, fp, s))
+        warnings.warn(RuntimeWarning(_mess), stacklevel=2)
+    if ier > 0 and not full_output:
+        if ier in [1, 2, 3]:
+            warnings.warn(RuntimeWarning(_iermess[ier][0]), stacklevel=2)
+        else:
+            try:
+                raise _iermess[ier][1](_iermess[ier][0])
+            except KeyError as e:
+                raise _iermess['unknown'][1](_iermess['unknown'][0]) from e
+    if full_output:
+        try:
+            return tck, fp, ier, _iermess[ier][0]
+        except KeyError:
+            return tck, fp, ier, _iermess['unknown'][0]
+    else:
+        return tck
+
+
+def splev(x, tck, der=0, ext=0):
+    # see the docstring of `_fitpack_py/splev`
+    t, c, k = tck
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        return list(map(lambda c, x=x, t=t, k=k, der=der:
+                        splev(x, [t, c, k], der, ext), c))
+    else:
+        if not (0 <= der <= k):
+            raise ValueError("0<=der=%d<=k=%d must hold" % (der, k))
+        if ext not in (0, 1, 2, 3):
+            raise ValueError(f"ext = {ext} not in (0, 1, 2, 3) ")
+
+        x = asarray(x)
+        shape = x.shape
+        x = atleast_1d(x).ravel()
+        if der == 0:
+            y, ier = dfitpack.splev(t, c, k, x, ext)
+        else:
+            y, ier = dfitpack.splder(t, c, k, x, der, ext)
+
+        if ier == 10:
+            raise ValueError("Invalid input data")
+        if ier == 1:
+            raise ValueError("Found x value not in the domain")
+        if ier:
+            raise TypeError("An error occurred")
+
+        return y.reshape(shape)
+
+
+def splint(a, b, tck, full_output=0):
+    # see the docstring of `_fitpack_py/splint`
+    t, c, k = tck
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        return list(map(lambda c, a=a, b=b, t=t, k=k:
+                        splint(a, b, [t, c, k]), c))
+    else:
+        aint, wrk = dfitpack.splint(t, c, k, a, b)
+        if full_output:
+            return aint, wrk
+        else:
+            return aint
+
+
+def sproot(tck, mest=10):
+    # see the docstring of `_fitpack_py/sproot`
+    t, c, k = tck
+    if k != 3:
+        raise ValueError("sproot works only for cubic (k=3) splines")
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        return list(map(lambda c, t=t, k=k, mest=mest:
+                        sproot([t, c, k], mest), c))
+    else:
+        if len(t) < 8:
+            raise TypeError(f"The number of knots {len(t)}>=8")
+        z, m, ier = dfitpack.sproot(t, c, mest)
+        if ier == 10:
+            raise TypeError("Invalid input data. "
+                            "t1<=..<=t4 1:
+            return list(map(lambda x, tck=tck: spalde(x, tck), x))
+        d, ier = dfitpack.spalde(t, c, k+1, x[0])
+        if ier == 0:
+            return d
+        if ier == 10:
+            raise TypeError("Invalid input data. t(k)<=x<=t(n-k+1) must hold.")
+        raise TypeError("Unknown error")
+
+# def _curfit(x,y,w=None,xb=None,xe=None,k=3,task=0,s=None,t=None,
+#           full_output=0,nest=None,per=0,quiet=1):
+
+
+_surfit_cache = {'tx': array([], float), 'ty': array([], float),
+                 'wrk': array([], float), 'iwrk': array([], dfitpack_int)}
+
+
+def bisplrep(x, y, z, w=None, xb=None, xe=None, yb=None, ye=None,
+             kx=3, ky=3, task=0, s=None, eps=1e-16, tx=None, ty=None,
+             full_output=0, nxest=None, nyest=None, quiet=1):
+    """
+    Find a bivariate B-spline representation of a surface.
+
+    Given a set of data points (x[i], y[i], z[i]) representing a surface
+    z=f(x,y), compute a B-spline representation of the surface. Based on
+    the routine SURFIT from FITPACK.
+
+    Parameters
+    ----------
+    x, y, z : ndarray
+        Rank-1 arrays of data points.
+    w : ndarray, optional
+        Rank-1 array of weights. By default ``w=np.ones(len(x))``.
+    xb, xe : float, optional
+        End points of approximation interval in `x`.
+        By default ``xb = x.min(), xe=x.max()``.
+    yb, ye : float, optional
+        End points of approximation interval in `y`.
+        By default ``yb=y.min(), ye = y.max()``.
+    kx, ky : int, optional
+        The degrees of the spline (1 <= kx, ky <= 5).
+        Third order (kx=ky=3) is recommended.
+    task : int, optional
+        If task=0, find knots in x and y and coefficients for a given
+        smoothing factor, s.
+        If task=1, find knots and coefficients for another value of the
+        smoothing factor, s.  bisplrep must have been previously called
+        with task=0 or task=1.
+        If task=-1, find coefficients for a given set of knots tx, ty.
+    s : float, optional
+        A non-negative smoothing factor. If weights correspond
+        to the inverse of the standard-deviation of the errors in z,
+        then a good s-value should be found in the range
+        ``(m-sqrt(2*m),m+sqrt(2*m))`` where m=len(x).
+    eps : float, optional
+        A threshold for determining the effective rank of an
+        over-determined linear system of equations (0 < eps < 1).
+        `eps` is not likely to need changing.
+    tx, ty : ndarray, optional
+        Rank-1 arrays of the knots of the spline for task=-1
+    full_output : int, optional
+        Non-zero to return optional outputs.
+    nxest, nyest : int, optional
+        Over-estimates of the total number of knots. If None then
+        ``nxest = max(kx+sqrt(m/2),2*kx+3)``,
+        ``nyest = max(ky+sqrt(m/2),2*ky+3)``.
+    quiet : int, optional
+        Non-zero to suppress printing of messages.
+
+    Returns
+    -------
+    tck : array_like
+        A list [tx, ty, c, kx, ky] containing the knots (tx, ty) and
+        coefficients (c) of the bivariate B-spline representation of the
+        surface along with the degree of the spline.
+    fp : ndarray
+        The weighted sum of squared residuals of the spline approximation.
+    ier : int
+        An integer flag about splrep success. Success is indicated if
+        ier<=0. If ier in [1,2,3] an error occurred but was not raised.
+        Otherwise an error is raised.
+    msg : str
+        A message corresponding to the integer flag, ier.
+
+    See Also
+    --------
+    splprep, splrep, splint, sproot, splev
+    UnivariateSpline, BivariateSpline
+
+    Notes
+    -----
+    See `bisplev` to evaluate the value of the B-spline given its tck
+    representation.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolation.
+
+    References
+    ----------
+    .. [1] Dierckx P.:An algorithm for surface fitting with spline functions
+       Ima J. Numer. Anal. 1 (1981) 267-283.
+    .. [2] Dierckx P.:An algorithm for surface fitting with spline functions
+       report tw50, Dept. Computer Science,K.U.Leuven, 1980.
+    .. [3] Dierckx P.:Curve and surface fitting with splines, Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    """
+    x, y, z = map(ravel, [x, y, z])  # ensure 1-d arrays.
+    m = len(x)
+    if not (m == len(y) == len(z)):
+        raise TypeError('len(x)==len(y)==len(z) must hold.')
+    if w is None:
+        w = ones(m, float)
+    else:
+        w = atleast_1d(w)
+    if not len(w) == m:
+        raise TypeError('len(w)=%d is not equal to m=%d' % (len(w), m))
+    if xb is None:
+        xb = x.min()
+    if xe is None:
+        xe = x.max()
+    if yb is None:
+        yb = y.min()
+    if ye is None:
+        ye = y.max()
+    if not (-1 <= task <= 1):
+        raise TypeError('task must be -1, 0 or 1')
+    if s is None:
+        s = m - sqrt(2*m)
+    if tx is None and task == -1:
+        raise TypeError('Knots_x must be given for task=-1')
+    if tx is not None:
+        _surfit_cache['tx'] = atleast_1d(tx)
+    nx = len(_surfit_cache['tx'])
+    if ty is None and task == -1:
+        raise TypeError('Knots_y must be given for task=-1')
+    if ty is not None:
+        _surfit_cache['ty'] = atleast_1d(ty)
+    ny = len(_surfit_cache['ty'])
+    if task == -1 and nx < 2*kx+2:
+        raise TypeError('There must be at least 2*kx+2 knots_x for task=-1')
+    if task == -1 and ny < 2*ky+2:
+        raise TypeError('There must be at least 2*ky+2 knots_x for task=-1')
+    if not ((1 <= kx <= 5) and (1 <= ky <= 5)):
+        raise TypeError('Given degree of the spline (kx,ky=%d,%d) is not '
+                        'supported. (1<=k<=5)' % (kx, ky))
+    if m < (kx + 1)*(ky + 1):
+        raise TypeError('m >= (kx+1)(ky+1) must hold')
+    if nxest is None:
+        nxest = int(kx + sqrt(m/2))
+    if nyest is None:
+        nyest = int(ky + sqrt(m/2))
+    nxest, nyest = max(nxest, 2*kx + 3), max(nyest, 2*ky + 3)
+    if task >= 0 and s == 0:
+        nxest = int(kx + sqrt(3*m))
+        nyest = int(ky + sqrt(3*m))
+    if task == -1:
+        _surfit_cache['tx'] = atleast_1d(tx)
+        _surfit_cache['ty'] = atleast_1d(ty)
+    tx, ty = _surfit_cache['tx'], _surfit_cache['ty']
+    wrk = _surfit_cache['wrk']
+    u = nxest - kx - 1
+    v = nyest - ky - 1
+    km = max(kx, ky) + 1
+    ne = max(nxest, nyest)
+    bx, by = kx*v + ky + 1, ky*u + kx + 1
+    b1, b2 = bx, bx + v - ky
+    if bx > by:
+        b1, b2 = by, by + u - kx
+    msg = "Too many data points to interpolate"
+    lwrk1 = _int_overflow(u*v*(2 + b1 + b2) +
+                          2*(u + v + km*(m + ne) + ne - kx - ky) + b2 + 1,
+                          OverflowError,
+                          msg=msg)
+    lwrk2 = _int_overflow(u*v*(b2 + 1) + b2, OverflowError, msg=msg)
+    tx, ty, c, o = _fitpack._surfit(x, y, z, w, xb, xe, yb, ye, kx, ky,
+                                    task, s, eps, tx, ty, nxest, nyest,
+                                    wrk, lwrk1, lwrk2)
+    _curfit_cache['tx'] = tx
+    _curfit_cache['ty'] = ty
+    _curfit_cache['wrk'] = o['wrk']
+    ier, fp = o['ier'], o['fp']
+    tck = [tx, ty, c, kx, ky]
+
+    ierm = min(11, max(-3, ier))
+    if ierm <= 0 and not quiet:
+        _mess = (_iermess2[ierm][0] +
+                 "\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" %
+                 (kx, ky, len(tx), len(ty), m, fp, s))
+        warnings.warn(RuntimeWarning(_mess), stacklevel=2)
+    if ierm > 0 and not full_output:
+        if ier in [1, 2, 3, 4, 5]:
+            _mess = ("\n\tkx,ky=%d,%d nx,ny=%d,%d m=%d fp=%f s=%f" %
+                     (kx, ky, len(tx), len(ty), m, fp, s))
+            warnings.warn(RuntimeWarning(_iermess2[ierm][0] + _mess), stacklevel=2)
+        else:
+            try:
+                raise _iermess2[ierm][1](_iermess2[ierm][0])
+            except KeyError as e:
+                raise _iermess2['unknown'][1](_iermess2['unknown'][0]) from e
+    if full_output:
+        try:
+            return tck, fp, ier, _iermess2[ierm][0]
+        except KeyError:
+            return tck, fp, ier, _iermess2['unknown'][0]
+    else:
+        return tck
+
+
+def bisplev(x, y, tck, dx=0, dy=0):
+    """
+    Evaluate a bivariate B-spline and its derivatives.
+
+    Return a rank-2 array of spline function values (or spline derivative
+    values) at points given by the cross-product of the rank-1 arrays `x` and
+    `y`.  In special cases, return an array or just a float if either `x` or
+    `y` or both are floats.  Based on BISPEV and PARDER from FITPACK.
+
+    Parameters
+    ----------
+    x, y : ndarray
+        Rank-1 arrays specifying the domain over which to evaluate the
+        spline or its derivative.
+    tck : tuple
+        A sequence of length 5 returned by `bisplrep` containing the knot
+        locations, the coefficients, and the degree of the spline:
+        [tx, ty, c, kx, ky].
+    dx, dy : int, optional
+        The orders of the partial derivatives in `x` and `y` respectively.
+
+    Returns
+    -------
+    vals : ndarray
+        The B-spline or its derivative evaluated over the set formed by
+        the cross-product of `x` and `y`.
+
+    See Also
+    --------
+    splprep, splrep, splint, sproot, splev
+    UnivariateSpline, BivariateSpline
+
+    Notes
+    -----
+        See `bisplrep` to generate the `tck` representation.
+
+    References
+    ----------
+    .. [1] Dierckx P. : An algorithm for surface fitting
+       with spline functions
+       Ima J. Numer. Anal. 1 (1981) 267-283.
+    .. [2] Dierckx P. : An algorithm for surface fitting
+       with spline functions
+       report tw50, Dept. Computer Science,K.U.Leuven, 1980.
+    .. [3] Dierckx P. : Curve and surface fitting with splines,
+       Monographs on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    """
+    tx, ty, c, kx, ky = tck
+    if not (0 <= dx < kx):
+        raise ValueError("0 <= dx = %d < kx = %d must hold" % (dx, kx))
+    if not (0 <= dy < ky):
+        raise ValueError("0 <= dy = %d < ky = %d must hold" % (dy, ky))
+    x, y = map(atleast_1d, [x, y])
+    if (len(x.shape) != 1) or (len(y.shape) != 1):
+        raise ValueError("First two entries should be rank-1 arrays.")
+
+    msg = "Too many data points to interpolate."
+
+    _int_overflow(x.size * y.size, MemoryError, msg=msg)
+
+    if dx != 0 or dy != 0:
+        _int_overflow((tx.size - kx - 1)*(ty.size - ky - 1),
+                      MemoryError, msg=msg)
+        z, ier = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y)
+    else:
+        z, ier = dfitpack.bispev(tx, ty, c, kx, ky, x, y)
+
+    if ier == 10:
+        raise ValueError("Invalid input data")
+    if ier:
+        raise TypeError("An error occurred")
+    z.shape = len(x), len(y)
+    if len(z) > 1:
+        return z
+    if len(z[0]) > 1:
+        return z[0]
+    return z[0][0]
+
+
+def dblint(xa, xb, ya, yb, tck):
+    """Evaluate the integral of a spline over area [xa,xb] x [ya,yb].
+
+    Parameters
+    ----------
+    xa, xb : float
+        The end-points of the x integration interval.
+    ya, yb : float
+        The end-points of the y integration interval.
+    tck : list [tx, ty, c, kx, ky]
+        A sequence of length 5 returned by bisplrep containing the knot
+        locations tx, ty, the coefficients c, and the degrees kx, ky
+        of the spline.
+
+    Returns
+    -------
+    integ : float
+        The value of the resulting integral.
+    """
+    tx, ty, c, kx, ky = tck
+    return dfitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb)
+
+
+def insert(x, tck, m=1, per=0):
+    # see the docstring of `_fitpack_py/insert`
+    t, c, k = tck
+    try:
+        c[0][0]
+        parametric = True
+    except Exception:
+        parametric = False
+    if parametric:
+        cc = []
+        for c_vals in c:
+            tt, cc_val, kk = insert(x, [t, c_vals, k], m)
+            cc.append(cc_val)
+        return (tt, cc, kk)
+    else:
+        tt, cc, ier = _fitpack._insert(per, t, c, k, x, m)
+        if ier == 10:
+            raise ValueError("Invalid input data")
+        if ier:
+            raise TypeError("An error occurred")
+        return (tt, cc, k)
+
+
+def splder(tck, n=1):
+    # see the docstring of `_fitpack_py/splder`
+    if n < 0:
+        return splantider(tck, -n)
+
+    t, c, k = tck
+
+    if n > k:
+        raise ValueError(f"Order of derivative (n = {n!r}) must be <= "
+                         f"order of spline (k = {tck[2]!r})")
+
+    # Extra axes for the trailing dims of the `c` array:
+    sh = (slice(None),) + ((None,)*len(c.shape[1:]))
+
+    with np.errstate(invalid='raise', divide='raise'):
+        try:
+            for j in range(n):
+                # See e.g. Schumaker, Spline Functions: Basic Theory, Chapter 5
+
+                # Compute the denominator in the differentiation formula.
+                # (and append trailing dims, if necessary)
+                dt = t[k+1:-1] - t[1:-k-1]
+                dt = dt[sh]
+                # Compute the new coefficients
+                c = (c[1:-1-k] - c[:-2-k]) * k / dt
+                # Pad coefficient array to same size as knots (FITPACK
+                # convention)
+                c = np.r_[c, np.zeros((k,) + c.shape[1:])]
+                # Adjust knots
+                t = t[1:-1]
+                k -= 1
+        except FloatingPointError as e:
+            raise ValueError(("The spline has internal repeated knots "
+                              "and is not differentiable %d times") % n) from e
+
+    return t, c, k
+
+
+def splantider(tck, n=1):
+    # see the docstring of `_fitpack_py/splantider`
+    if n < 0:
+        return splder(tck, -n)
+
+    t, c, k = tck
+
+    # Extra axes for the trailing dims of the `c` array:
+    sh = (slice(None),) + (None,)*len(c.shape[1:])
+
+    for j in range(n):
+        # This is the inverse set of operations to splder.
+
+        # Compute the multiplier in the antiderivative formula.
+        dt = t[k+1:] - t[:-k-1]
+        dt = dt[sh]
+        # Compute the new coefficients
+        c = np.cumsum(c[:-k-1] * dt, axis=0) / (k + 1)
+        c = np.r_[np.zeros((1,) + c.shape[1:]),
+                  c,
+                  [c[-1]] * (k+2)]
+        # New knots
+        t = np.r_[t[0], t, t[-1]]
+        k += 1
+
+    return t, c, k
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_py.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f7a2ded7e46885b4e0e0e4ccdb8065c25742e6a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_py.py
@@ -0,0 +1,898 @@
+__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde',
+           'bisplrep', 'bisplev', 'insert', 'splder', 'splantider']
+
+
+import numpy as np
+
+# These are in the API for fitpack even if not used in fitpack.py itself.
+from ._fitpack_impl import bisplrep, bisplev, dblint  # noqa: F401
+from . import _fitpack_impl as _impl
+from ._bsplines import BSpline
+
+
+def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None,
+            full_output=0, nest=None, per=0, quiet=1):
+    """
+    Find the B-spline representation of an N-D curve.
+
+    .. legacy:: function
+
+        Specifically, we recommend using `make_splprep` in new code.
+
+    Given a list of N rank-1 arrays, `x`, which represent a curve in
+    N-dimensional space parametrized by `u`, find a smooth approximating
+    spline curve g(`u`). Uses the FORTRAN routine parcur from FITPACK.
+
+    Parameters
+    ----------
+    x : array_like
+        A list of sample vector arrays representing the curve.
+    w : array_like, optional
+        Strictly positive rank-1 array of weights the same length as `x[0]`.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the `x` values have standard-deviation given by
+        the vector d, then `w` should be 1/d. Default is ``ones(len(x[0]))``.
+    u : array_like, optional
+        An array of parameter values. If not given, these values are
+        calculated automatically as ``M = len(x[0])``, where
+
+            v[0] = 0
+
+            v[i] = v[i-1] + distance(`x[i]`, `x[i-1]`)
+
+            u[i] = v[i] / v[M-1]
+
+    ub, ue : int, optional
+        The end-points of the parameters interval.  Defaults to
+        u[0] and u[-1].
+    k : int, optional
+        Degree of the spline. Cubic splines are recommended.
+        Even values of `k` should be avoided especially with a small s-value.
+        ``1 <= k <= 5``, default is 3.
+    task : int, optional
+        If task==0 (default), find t and c for a given smoothing factor, s.
+        If task==1, find t and c for another value of the smoothing factor, s.
+        There must have been a previous call with task=0 or task=1
+        for the same set of data.
+        If task=-1 find the weighted least square spline for a given set of
+        knots, t.
+    s : float, optional
+        A smoothing condition.  The amount of smoothness is determined by
+        satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s``,
+        where g(x) is the smoothed interpolation of (x,y).  The user can
+        use `s` to control the trade-off between closeness and smoothness
+        of fit.  Larger `s` means more smoothing while smaller values of `s`
+        indicate less smoothing. Recommended values of `s` depend on the
+        weights, w.  If the weights represent the inverse of the
+        standard-deviation of y, then a good `s` value should be found in
+        the range ``(m-sqrt(2*m),m+sqrt(2*m))``, where m is the number of
+        data points in x, y, and w.
+    t : array, optional
+        The knots needed for ``task=-1``.
+        There must be at least ``2*k+2`` knots.
+    full_output : int, optional
+        If non-zero, then return optional outputs.
+    nest : int, optional
+        An over-estimate of the total number of knots of the spline to
+        help in determining the storage space.  By default nest=m/2.
+        Always large enough is nest=m+k+1.
+    per : int, optional
+       If non-zero, data points are considered periodic with period
+       ``x[m-1] - x[0]`` and a smooth periodic spline approximation is
+       returned.  Values of ``y[m-1]`` and ``w[m-1]`` are not used.
+    quiet : int, optional
+         Non-zero to suppress messages.
+
+    Returns
+    -------
+    tck : tuple
+        A tuple, ``(t,c,k)`` containing the vector of knots, the B-spline
+        coefficients, and the degree of the spline.
+    u : array
+        An array of the values of the parameter.
+    fp : float
+        The weighted sum of squared residuals of the spline approximation.
+    ier : int
+        An integer flag about splrep success.  Success is indicated
+        if ier<=0. If ier in [1,2,3] an error occurred but was not raised.
+        Otherwise an error is raised.
+    msg : str
+        A message corresponding to the integer flag, ier.
+
+    See Also
+    --------
+    splrep, splev, sproot, spalde, splint,
+    bisplrep, bisplev
+    UnivariateSpline, BivariateSpline
+    BSpline
+    make_interp_spline
+
+    Notes
+    -----
+    See `splev` for evaluation of the spline and its derivatives.
+    The number of dimensions N must be smaller than 11.
+
+    The number of coefficients in the `c` array is ``k+1`` less than the number
+    of knots, ``len(t)``. This is in contrast with `splrep`, which zero-pads
+    the array of coefficients to have the same length as the array of knots.
+    These additional coefficients are ignored by evaluation routines, `splev`
+    and `BSpline`.
+
+    References
+    ----------
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+    .. [2] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines", report tw55, Dept. Computer Science,
+        K.U.Leuven, 1981.
+    .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+        Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Generate a discretization of a limacon curve in the polar coordinates:
+
+    >>> import numpy as np
+    >>> phi = np.linspace(0, 2.*np.pi, 40)
+    >>> r = 0.5 + np.cos(phi)         # polar coords
+    >>> x, y = r * np.cos(phi), r * np.sin(phi)    # convert to cartesian
+
+    And interpolate:
+
+    >>> from scipy.interpolate import splprep, splev
+    >>> tck, u = splprep([x, y], s=0)
+    >>> new_points = splev(u, tck)
+
+    Notice that (i) we force interpolation by using ``s=0``,
+    (ii) the parameterization, ``u``, is generated automatically.
+    Now plot the result:
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y, 'ro')
+    >>> ax.plot(new_points[0], new_points[1], 'r-')
+    >>> plt.show()
+
+    """
+
+    res = _impl.splprep(x, w, u, ub, ue, k, task, s, t, full_output, nest, per,
+                        quiet)
+    return res
+
+
+def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None,
+           full_output=0, per=0, quiet=1):
+    """
+    Find the B-spline representation of a 1-D curve.
+
+    .. legacy:: function
+
+        Specifically, we recommend using `make_splrep` in new code.
+
+
+    Given the set of data points ``(x[i], y[i])`` determine a smooth spline
+    approximation of degree k on the interval ``xb <= x <= xe``.
+
+    Parameters
+    ----------
+    x, y : array_like
+        The data points defining a curve ``y = f(x)``.
+    w : array_like, optional
+        Strictly positive rank-1 array of weights the same length as `x` and `y`.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the `y` values have standard-deviation given by the
+        vector ``d``, then `w` should be ``1/d``. Default is ``ones(len(x))``.
+    xb, xe : float, optional
+        The interval to fit.  If None, these default to ``x[0]`` and ``x[-1]``
+        respectively.
+    k : int, optional
+        The degree of the spline fit. It is recommended to use cubic splines.
+        Even values of `k` should be avoided especially with small `s` values.
+        ``1 <= k <= 5``.
+    task : {1, 0, -1}, optional
+        If ``task==0``, find ``t`` and ``c`` for a given smoothing factor, `s`.
+
+        If ``task==1`` find ``t`` and ``c`` for another value of the smoothing factor,
+        `s`. There must have been a previous call with ``task=0`` or ``task=1`` for
+        the same set of data (``t`` will be stored an used internally)
+
+        If ``task=-1`` find the weighted least square spline for a given set of
+        knots, ``t``. These should be interior knots as knots on the ends will be
+        added automatically.
+    s : float, optional
+        A smoothing condition. The amount of smoothness is determined by
+        satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s`` where ``g(x)``
+        is the smoothed interpolation of ``(x,y)``. The user can use `s` to control
+        the tradeoff between closeness and smoothness of fit. Larger `s` means
+        more smoothing while smaller values of `s` indicate less smoothing.
+        Recommended values of `s` depend on the weights, `w`. If the weights
+        represent the inverse of the standard-deviation of `y`, then a good `s`
+        value should be found in the range ``(m-sqrt(2*m),m+sqrt(2*m))`` where ``m`` is
+        the number of datapoints in `x`, `y`, and `w`. default : ``s=m-sqrt(2*m)`` if
+        weights are supplied. ``s = 0.0`` (interpolating) if no weights are
+        supplied.
+    t : array_like, optional
+        The knots needed for ``task=-1``. If given then task is automatically set
+        to ``-1``.
+    full_output : bool, optional
+        If non-zero, then return optional outputs.
+    per : bool, optional
+        If non-zero, data points are considered periodic with period ``x[m-1]`` -
+        ``x[0]`` and a smooth periodic spline approximation is returned. Values of
+        ``y[m-1]`` and ``w[m-1]`` are not used.
+        The default is zero, corresponding to boundary condition 'not-a-knot'.
+    quiet : bool, optional
+        Non-zero to suppress messages.
+
+    Returns
+    -------
+    tck : tuple
+        A tuple ``(t,c,k)`` containing the vector of knots, the B-spline
+        coefficients, and the degree of the spline.
+    fp : array, optional
+        The weighted sum of squared residuals of the spline approximation.
+    ier : int, optional
+        An integer flag about splrep success. Success is indicated if ``ier<=0``.
+        If ``ier in [1,2,3]``, an error occurred but was not raised. Otherwise an
+        error is raised.
+    msg : str, optional
+        A message corresponding to the integer flag, `ier`.
+
+    See Also
+    --------
+    UnivariateSpline, BivariateSpline
+    splprep, splev, sproot, spalde, splint
+    bisplrep, bisplev
+    BSpline
+    make_interp_spline
+
+    Notes
+    -----
+    See `splev` for evaluation of the spline and its derivatives. Uses the
+    FORTRAN routine ``curfit`` from FITPACK.
+
+    The user is responsible for assuring that the values of `x` are unique.
+    Otherwise, `splrep` will not return sensible results.
+
+    If provided, knots `t` must satisfy the Schoenberg-Whitney conditions,
+    i.e., there must be a subset of data points ``x[j]`` such that
+    ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
+
+    This routine zero-pads the coefficients array ``c`` to have the same length
+    as the array of knots ``t`` (the trailing ``k + 1`` coefficients are ignored
+    by the evaluation routines, `splev` and `BSpline`.) This is in contrast with
+    `splprep`, which does not zero-pad the coefficients.
+
+    The default boundary condition is 'not-a-knot', i.e. the first and second
+    segment at a curve end are the same polynomial. More boundary conditions are
+    available in `CubicSpline`.
+
+    References
+    ----------
+    Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
+
+    .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
+       integration of experimental data using spline functions",
+       J.Comp.Appl.Maths 1 (1975) 165-184.
+    .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
+       grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
+       1286-1304.
+    .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
+       functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
+    .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    You can interpolate 1-D points with a B-spline curve.
+    Further examples are given in
+    :ref:`in the tutorial `.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import splev, splrep
+    >>> x = np.linspace(0, 10, 10)
+    >>> y = np.sin(x)
+    >>> spl = splrep(x, y)
+    >>> x2 = np.linspace(0, 10, 200)
+    >>> y2 = splev(x2, spl)
+    >>> plt.plot(x, y, 'o', x2, y2)
+    >>> plt.show()
+
+    """
+    res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet)
+    return res
+
+
+def splev(x, tck, der=0, ext=0):
+    """
+    Evaluate a B-spline or its derivatives.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using
+        its ``__call__`` method.
+
+    Given the knots and coefficients of a B-spline representation, evaluate
+    the value of the smoothing polynomial and its derivatives. This is a
+    wrapper around the FORTRAN routines splev and splder of FITPACK.
+
+    Parameters
+    ----------
+    x : array_like
+        An array of points at which to return the value of the smoothed
+        spline or its derivatives. If `tck` was returned from `splprep`,
+        then the parameter values, u should be given.
+    tck : BSpline instance or tuple
+        If a tuple, then it should be a sequence of length 3 returned by
+        `splrep` or `splprep` containing the knots, coefficients, and degree
+        of the spline. (Also see Notes.)
+    der : int, optional
+        The order of derivative of the spline to compute (must be less than
+        or equal to k, the degree of the spline).
+    ext : int, optional
+        Controls the value returned for elements of ``x`` not in the
+        interval defined by the knot sequence.
+
+        * if ext=0, return the extrapolated value.
+        * if ext=1, return 0
+        * if ext=2, raise a ValueError
+        * if ext=3, return the boundary value.
+
+        The default value is 0.
+
+    Returns
+    -------
+    y : ndarray or list of ndarrays
+        An array of values representing the spline function evaluated at
+        the points in `x`.  If `tck` was returned from `splprep`, then this
+        is a list of arrays representing the curve in an N-D space.
+
+    See Also
+    --------
+    splprep, splrep, sproot, spalde, splint
+    bisplrep, bisplev
+    BSpline
+
+    Notes
+    -----
+    Manipulating the tck-tuples directly is not recommended. In new code,
+    prefer using `BSpline` objects.
+
+    References
+    ----------
+    .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
+        Theory, 6, p.50-62, 1972.
+    .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
+        Applics, 10, p.134-149, 1972.
+    .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
+        on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    A comparison between `splev`, `splder` and `spalde` to compute the derivatives of a 
+    B-spline can be found in the `spalde` examples section.
+
+    """
+    if isinstance(tck, BSpline):
+        if tck.c.ndim > 1:
+            mesg = ("Calling splev() with BSpline objects with c.ndim > 1 is "
+                    "not allowed. Use BSpline.__call__(x) instead.")
+            raise ValueError(mesg)
+
+        # remap the out-of-bounds behavior
+        try:
+            extrapolate = {0: True, }[ext]
+        except KeyError as e:
+            raise ValueError(f"Extrapolation mode {ext} is not supported "
+                             "by BSpline.") from e
+
+        return tck(x, der, extrapolate=extrapolate)
+    else:
+        return _impl.splev(x, tck, der, ext)
+
+
+def splint(a, b, tck, full_output=0):
+    """
+    Evaluate the definite integral of a B-spline between two given points.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using its
+        ``integrate`` method.
+
+    Parameters
+    ----------
+    a, b : float
+        The end-points of the integration interval.
+    tck : tuple or a BSpline instance
+        If a tuple, then it should be a sequence of length 3, containing the
+        vector of knots, the B-spline coefficients, and the degree of the
+        spline (see `splev`).
+    full_output : int, optional
+        Non-zero to return optional output.
+
+    Returns
+    -------
+    integral : float
+        The resulting integral.
+    wrk : ndarray
+        An array containing the integrals of the normalized B-splines
+        defined on the set of knots.
+        (Only returned if `full_output` is non-zero)
+
+    See Also
+    --------
+    splprep, splrep, sproot, spalde, splev
+    bisplrep, bisplev
+    BSpline
+
+    Notes
+    -----
+    `splint` silently assumes that the spline function is zero outside the data
+    interval (`a`, `b`).
+
+    Manipulating the tck-tuples directly is not recommended. In new code,
+    prefer using the `BSpline` objects.
+
+    References
+    ----------
+    .. [1] P.W. Gaffney, The calculation of indefinite integrals of b-splines",
+        J. Inst. Maths Applics, 17, p.37-41, 1976.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs
+        on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    Examples are given :ref:`in the tutorial `.
+
+    """
+    if isinstance(tck, BSpline):
+        if tck.c.ndim > 1:
+            mesg = ("Calling splint() with BSpline objects with c.ndim > 1 is "
+                    "not allowed. Use BSpline.integrate() instead.")
+            raise ValueError(mesg)
+
+        if full_output != 0:
+            mesg = (f"full_output = {full_output} is not supported. Proceeding as if "
+                    "full_output = 0")
+
+        return tck.integrate(a, b, extrapolate=False)
+    else:
+        return _impl.splint(a, b, tck, full_output)
+
+
+def sproot(tck, mest=10):
+    """
+    Find the roots of a cubic B-spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using the
+        following pattern: `PPoly.from_spline(spl).roots()`.
+
+    Given the knots (>=8) and coefficients of a cubic B-spline return the
+    roots of the spline.
+
+    Parameters
+    ----------
+    tck : tuple or a BSpline object
+        If a tuple, then it should be a sequence of length 3, containing the
+        vector of knots, the B-spline coefficients, and the degree of the
+        spline.
+        The number of knots must be >= 8, and the degree must be 3.
+        The knots must be a montonically increasing sequence.
+    mest : int, optional
+        An estimate of the number of zeros (Default is 10).
+
+    Returns
+    -------
+    zeros : ndarray
+        An array giving the roots of the spline.
+
+    See Also
+    --------
+    splprep, splrep, splint, spalde, splev
+    bisplrep, bisplev
+    BSpline
+
+    Notes
+    -----
+    Manipulating the tck-tuples directly is not recommended. In new code,
+    prefer using the `BSpline` objects.
+
+    References
+    ----------
+    .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
+        Theory, 6, p.50-62, 1972.
+    .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
+        Applics, 10, p.134-149, 1972.
+    .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
+        on Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+
+    For some data, this method may miss a root. This happens when one of
+    the spline knots (which FITPACK places automatically) happens to
+    coincide with the true root. A workaround is to convert to `PPoly`,
+    which uses a different root-finding algorithm.
+
+    For example,
+
+    >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05]
+    >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03,
+    ...      4.440892e-16,  1.616930e-03,  3.243000e-03,  4.877670e-03,
+    ...      6.520430e-03,  8.170770e-03]
+    >>> from scipy.interpolate import splrep, sproot, PPoly
+    >>> tck = splrep(x, y, s=0)
+    >>> sproot(tck)
+    array([], dtype=float64)
+
+    Converting to a PPoly object does find the roots at ``x=2``:
+
+    >>> ppoly = PPoly.from_spline(tck)
+    >>> ppoly.roots(extrapolate=False)
+    array([2.])
+
+
+    Further examples are given :ref:`in the tutorial
+    `.
+
+    """
+    if isinstance(tck, BSpline):
+        if tck.c.ndim > 1:
+            mesg = ("Calling sproot() with BSpline objects with c.ndim > 1 is "
+                    "not allowed.")
+            raise ValueError(mesg)
+
+        t, c, k = tck.tck
+
+        # _impl.sproot expects the interpolation axis to be last, so roll it.
+        # NB: This transpose is a no-op if c is 1D.
+        sh = tuple(range(c.ndim))
+        c = c.transpose(sh[1:] + (0,))
+        return _impl.sproot((t, c, k), mest)
+    else:
+        return _impl.sproot(tck, mest)
+
+
+def spalde(x, tck):
+    """
+    Evaluate a B-spline and all its derivatives at one point (or set of points) up
+    to order k (the degree of the spline), being 0 the spline itself.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and evaluate
+        its derivative in a loop or a list comprehension.
+
+    Parameters
+    ----------
+    x : array_like
+        A point or a set of points at which to evaluate the derivatives.
+        Note that ``t(k) <= x <= t(n-k+1)`` must hold for each `x`.
+    tck : tuple
+        A tuple (t,c,k) containing the vector of knots,
+        the B-spline coefficients, and the degree of the spline whose 
+        derivatives to compute.
+
+    Returns
+    -------
+    results : {ndarray, list of ndarrays}
+        An array (or a list of arrays) containing all derivatives
+        up to order k inclusive for each point `x`, being the first element the 
+        spline itself.
+
+    See Also
+    --------
+    splprep, splrep, splint, sproot, splev, bisplrep, bisplev,
+    UnivariateSpline, BivariateSpline
+
+    References
+    ----------
+    .. [1] de Boor C : On calculating with b-splines, J. Approximation Theory
+       6 (1972) 50-62.
+    .. [2] Cox M.G. : The numerical evaluation of b-splines, J. Inst. Maths
+       applics 10 (1972) 134-149.
+    .. [3] Dierckx P. : Curve and surface fitting with splines, Monographs on
+       Numerical Analysis, Oxford University Press, 1993.
+
+    Examples
+    --------
+    To calculate the derivatives of a B-spline there are several aproaches. 
+    In this example, we will demonstrate that `spalde` is equivalent to
+    calling `splev` and `splder`.
+    
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import BSpline, spalde, splder, splev
+    
+    >>> # Store characteristic parameters of a B-spline
+    >>> tck = ((-2, -2, -2, -2, -1, 0, 1, 2, 2, 2, 2),  # knots
+    ...        (0, 0, 0, 6, 0, 0, 0),  # coefficients
+    ...        3)  # degree (cubic)
+    >>> # Instance a B-spline object
+    >>> # `BSpline` objects are preferred, except for spalde()
+    >>> bspl = BSpline(tck[0], tck[1], tck[2])
+    >>> # Generate extra points to get a smooth curve
+    >>> x = np.linspace(min(tck[0]), max(tck[0]), 100)
+    
+    Evaluate the curve and all derivatives
+    
+    >>> # The order of derivative must be less or equal to k, the degree of the spline
+    >>> # Method 1: spalde()
+    >>> f1_y_bsplin = [spalde(i, tck)[0] for i in x ]  # The B-spline itself
+    >>> f1_y_deriv1 = [spalde(i, tck)[1] for i in x ]  # 1st derivative
+    >>> f1_y_deriv2 = [spalde(i, tck)[2] for i in x ]  # 2nd derivative
+    >>> f1_y_deriv3 = [spalde(i, tck)[3] for i in x ]  # 3rd derivative
+    >>> # You can reach the same result by using `splev`and `splder`
+    >>> f2_y_deriv3 = splev(x, bspl, der=3)
+    >>> f3_y_deriv3 = splder(bspl, n=3)(x)
+    
+    >>> # Generate a figure with three axes for graphic comparison
+    >>> fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(16, 5))
+    >>> suptitle = fig.suptitle(f'Evaluate a B-spline and all derivatives')
+    >>> # Plot B-spline and all derivatives using the three methods
+    >>> orders = range(4)
+    >>> linetypes = ['-', '--', '-.', ':']
+    >>> labels = ['B-Spline', '1st deriv.', '2nd deriv.', '3rd deriv.']
+    >>> functions = ['splev()', 'splder()', 'spalde()']
+    >>> for order, linetype, label in zip(orders, linetypes, labels):
+    ...     ax1.plot(x, splev(x, bspl, der=order), linetype, label=label)
+    ...     ax2.plot(x, splder(bspl, n=order)(x), linetype, label=label)
+    ...     ax3.plot(x, [spalde(i, tck)[order] for i in x], linetype, label=label)
+    >>> for ax, function in zip((ax1, ax2, ax3), functions):
+    ...     ax.set_title(function)
+    ...     ax.legend()
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    """
+    if isinstance(tck, BSpline):
+        raise TypeError("spalde does not accept BSpline instances.")
+    else:
+        return _impl.spalde(x, tck)
+
+
+def insert(x, tck, m=1, per=0):
+    """
+    Insert knots into a B-spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using
+        its ``insert_knot`` method.
+
+    Given the knots and coefficients of a B-spline representation, create a
+    new B-spline with a knot inserted `m` times at point `x`.
+    This is a wrapper around the FORTRAN routine insert of FITPACK.
+
+    Parameters
+    ----------
+    x (u) : float
+        A knot value at which to insert a new knot.  If `tck` was returned
+        from ``splprep``, then the parameter values, u should be given.
+    tck : a `BSpline` instance or a tuple
+        If tuple, then it is expected to be a tuple (t,c,k) containing
+        the vector of knots, the B-spline coefficients, and the degree of
+        the spline.
+    m : int, optional
+        The number of times to insert the given knot (its multiplicity).
+        Default is 1.
+    per : int, optional
+        If non-zero, the input spline is considered periodic.
+
+    Returns
+    -------
+    BSpline instance or a tuple
+        A new B-spline with knots t, coefficients c, and degree k.
+        ``t(k+1) <= x <= t(n-k)``, where k is the degree of the spline.
+        In case of a periodic spline (``per != 0``) there must be
+        either at least k interior knots t(j) satisfying ``t(k+1)>> from scipy.interpolate import splrep, insert
+    >>> import numpy as np
+    >>> x = np.linspace(0, 10, 5)
+    >>> y = np.sin(x)
+    >>> tck = splrep(x, y)
+    >>> tck[0]
+    array([ 0.,  0.,  0.,  0.,  5., 10., 10., 10., 10.])
+
+    A knot is inserted:
+
+    >>> tck_inserted = insert(3, tck)
+    >>> tck_inserted[0]
+    array([ 0.,  0.,  0.,  0.,  3.,  5., 10., 10., 10., 10.])
+
+    Some knots are inserted:
+
+    >>> tck_inserted2 = insert(8, tck, m=3)
+    >>> tck_inserted2[0]
+    array([ 0.,  0.,  0.,  0.,  5.,  8.,  8.,  8., 10., 10., 10., 10.])
+
+    """
+    if isinstance(tck, BSpline):
+
+        t, c, k = tck.tck
+
+        # FITPACK expects the interpolation axis to be last, so roll it over
+        # NB: if c array is 1D, transposes are no-ops
+        sh = tuple(range(c.ndim))
+        c = c.transpose(sh[1:] + (0,))
+        t_, c_, k_ = _impl.insert(x, (t, c, k), m, per)
+
+        # and roll the last axis back
+        c_ = np.asarray(c_)
+        c_ = c_.transpose((sh[-1],) + sh[:-1])
+        return BSpline(t_, c_, k_)
+    else:
+        return _impl.insert(x, tck, m, per)
+
+
+def splder(tck, n=1):
+    """
+    Compute the spline representation of the derivative of a given spline
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using its
+        ``derivative`` method.
+
+    Parameters
+    ----------
+    tck : BSpline instance or tuple
+        BSpline instance or a tuple (t,c,k) containing the vector of knots,
+        the B-spline coefficients, and the degree of the spline whose 
+        derivative to compute
+    n : int, optional
+        Order of derivative to evaluate. Default: 1
+
+    Returns
+    -------
+    `BSpline` instance or tuple
+        Spline of order k2=k-n representing the derivative
+        of the input spline.
+        A tuple is returned if the input argument `tck` is a tuple, otherwise
+        a BSpline object is constructed and returned.
+
+    See Also
+    --------
+    splantider, splev, spalde
+    BSpline
+
+    Notes
+    -----
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    This can be used for finding maxima of a curve:
+
+    >>> from scipy.interpolate import splrep, splder, sproot
+    >>> import numpy as np
+    >>> x = np.linspace(0, 10, 70)
+    >>> y = np.sin(x)
+    >>> spl = splrep(x, y, k=4)
+
+    Now, differentiate the spline and find the zeros of the
+    derivative. (NB: `sproot` only works for order 3 splines, so we
+    fit an order 4 spline):
+
+    >>> dspl = splder(spl)
+    >>> sproot(dspl) / np.pi
+    array([ 0.50000001,  1.5       ,  2.49999998])
+
+    This agrees well with roots :math:`\\pi/2 + n\\pi` of
+    :math:`\\cos(x) = \\sin'(x)`.
+
+    A comparison between `splev`, `splder` and `spalde` to compute the derivatives of a 
+    B-spline can be found in the `spalde` examples section.
+
+    """
+    if isinstance(tck, BSpline):
+        return tck.derivative(n)
+    else:
+        return _impl.splder(tck, n)
+
+
+def splantider(tck, n=1):
+    """
+    Compute the spline for the antiderivative (integral) of a given spline.
+
+    .. legacy:: function
+
+        Specifically, we recommend constructing a `BSpline` object and using its
+        ``antiderivative`` method.
+
+    Parameters
+    ----------
+    tck : BSpline instance or a tuple of (t, c, k)
+        Spline whose antiderivative to compute
+    n : int, optional
+        Order of antiderivative to evaluate. Default: 1
+
+    Returns
+    -------
+    BSpline instance or a tuple of (t2, c2, k2)
+        Spline of order k2=k+n representing the antiderivative of the input
+        spline.
+        A tuple is returned iff the input argument `tck` is a tuple, otherwise
+        a BSpline object is constructed and returned.
+
+    See Also
+    --------
+    splder, splev, spalde
+    BSpline
+
+    Notes
+    -----
+    The `splder` function is the inverse operation of this function.
+    Namely, ``splder(splantider(tck))`` is identical to `tck`, modulo
+    rounding error.
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    >>> from scipy.interpolate import splrep, splder, splantider, splev
+    >>> import numpy as np
+    >>> x = np.linspace(0, np.pi/2, 70)
+    >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
+    >>> spl = splrep(x, y)
+
+    The derivative is the inverse operation of the antiderivative,
+    although some floating point error accumulates:
+
+    >>> splev(1.7, spl), splev(1.7, splder(splantider(spl)))
+    (array(2.1565429877197317), array(2.1565429877201865))
+
+    Antiderivative can be used to evaluate definite integrals:
+
+    >>> ispl = splantider(spl)
+    >>> splev(np.pi/2, ispl) - splev(0, ispl)
+    2.2572053588768486
+
+    This is indeed an approximation to the complete elliptic integral
+    :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
+
+    >>> from scipy.special import ellipk
+    >>> ellipk(0.8)
+    2.2572053268208538
+
+    """
+    if isinstance(tck, BSpline):
+        return tck.antiderivative(n)
+    else:
+        return _impl.splantider(tck, n)
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_repro.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_repro.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5697f3ad716500f6557175e88adead6b3b4caac
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_fitpack_repro.py
@@ -0,0 +1,992 @@
+""" Replicate FITPACK's logic for constructing smoothing spline functions and curves.
+
+    Currently provides analogs of splrep and splprep python routines, i.e.
+    curfit.f and parcur.f routines (the drivers are fpcurf.f and fppara.f, respectively)
+
+    The Fortran sources are from
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/
+
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+        :doi:`10.1016/0146-664X(82)90043-0`.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+         Numerical Analysis, Oxford University Press, 1993.
+    .. [3] P. Dierckx, "An algorithm for smoothing, differentiation and integration
+         of experimental data using spline functions",
+         Journal of Computational and Applied Mathematics, vol. I, no 3, p. 165 (1975).
+         https://doi.org/10.1016/0771-050X(75)90034-0
+"""
+import warnings
+import operator
+import numpy as np
+
+from ._bsplines import (
+    _not_a_knot, make_interp_spline, BSpline, fpcheck, _lsq_solve_qr
+)
+from . import _dierckx      # type: ignore[attr-defined]
+
+
+#    cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
+#    c  part 1: determination of the number of knots and their position     c
+#    c  **************************************************************      c
+#
+# https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L31
+
+
+# Hardcoded in curfit.f
+TOL = 0.001
+MAXIT = 20
+
+
+def _get_residuals(x, y, t, k, w):
+    # FITPACK has (w*(spl(x)-y))**2; make_lsq_spline has w*(spl(x)-y)**2
+    w2 = w**2
+
+    # inline the relevant part of
+    # >>> spl = make_lsq_spline(x, y, w=w2, t=t, k=k)
+    # NB:
+    #     1. y is assumed to be 2D here. For 1D case (parametric=False),
+    #        the call must have been preceded by y = y[:, None] (cf _validate_inputs)
+    #     2. We always sum the squares across axis=1:
+    #         * For 1D (parametric=False), the last dimension has size one,
+    #           so the summation is a no-op.
+    #         * For 2D (parametric=True), the summation is actually how the
+    #           'residuals' are defined, see Eq. (42) in Dierckx1982
+    #           (the reference is in the docstring of `class F`) below.
+    _, _, c = _lsq_solve_qr(x, y, t, k, w)
+    c = np.ascontiguousarray(c)
+    spl = BSpline(t, c, k)
+    return _compute_residuals(w2, spl(x), y)
+
+
+def _compute_residuals(w2, splx, y):
+    delta = ((splx - y)**2).sum(axis=1)
+    return w2 * delta
+
+
+def add_knot(x, t, k, residuals):
+    """Add a new knot.
+
+    (Approximately) replicate FITPACK's logic:
+      1. split the `x` array into knot intervals, ``t(j+k) <= x(i) <= t(j+k+1)``
+      2. find the interval with the maximum sum of residuals
+      3. insert a new knot into the middle of that interval.
+
+    NB: a new knot is in fact an `x` value at the middle of the interval.
+    So *the knots are a subset of `x`*.
+
+    This routine is an analog of
+    https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpcurf.f#L190-L215
+    (cf _split function)
+
+    and https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpknot.f
+    """
+    new_knot = _dierckx.fpknot(x, t, k, residuals)
+
+    idx_t = np.searchsorted(t, new_knot)
+    t_new = np.r_[t[:idx_t], new_knot, t[idx_t:]]
+    return t_new
+
+
+def _validate_inputs(x, y, w, k, s, xb, xe, parametric):
+    """Common input validations for generate_knots and make_splrep.
+    """
+    x = np.asarray(x, dtype=float)
+    y = np.asarray(y, dtype=float)
+
+    if w is None:
+        w = np.ones_like(x, dtype=float)
+    else:
+        w = np.asarray(w, dtype=float)
+        if w.ndim != 1:
+            raise ValueError(f"{w.ndim = } not implemented yet.")
+        if (w < 0).any():
+            raise ValueError("Weights must be non-negative")
+
+    if y.ndim == 0 or y.ndim > 2:
+        raise ValueError(f"{y.ndim = } not supported (must be 1 or 2.)")
+
+    parametric = bool(parametric)
+    if parametric:
+        if y.ndim != 2:
+            raise ValueError(f"{y.ndim = } != 2 not supported with {parametric =}.")
+    else:
+        if y.ndim != 1:
+            raise ValueError(f"{y.ndim = } != 1 not supported with {parametric =}.")
+        # all _impl functions expect y.ndim = 2
+        y = y[:, None]
+
+    if w.shape[0] != x.shape[0]:
+        raise ValueError(f"Weights is incompatible: {w.shape =} != {x.shape}.")
+
+    if x.shape[0] != y.shape[0]:
+        raise ValueError(f"Data is incompatible: {x.shape = } and {y.shape = }.")
+    if x.ndim != 1 or (x[1:] < x[:-1]).any():
+        raise ValueError("Expect `x` to be an ordered 1D sequence.")
+
+    k = operator.index(k)
+
+    if s < 0:
+        raise ValueError(f"`s` must be non-negative. Got {s = }")
+
+    if xb is None:
+        xb = min(x)
+    if xe is None:
+        xe = max(x)
+
+    return x, y, w, k, s, xb, xe
+
+
+def generate_knots(x, y, *, w=None, xb=None, xe=None, k=3, s=0, nest=None):
+    """Replicate FITPACK's constructing the knot vector.
+
+    Parameters
+    ----------
+    x, y : array_like
+        The data points defining the curve ``y = f(x)``.
+    w : array_like, optional
+        Weights.
+    xb : float, optional
+        The boundary of the approximation interval. If None (default),
+        is set to ``x[0]``.
+    xe : float, optional
+        The boundary of the approximation interval. If None (default),
+        is set to ``x[-1]``.
+    k : int, optional
+        The spline degree. Default is cubic, ``k = 3``.
+    s : float, optional
+        The smoothing factor. Default is ``s = 0``.
+    nest : int, optional
+        Stop when at least this many knots are placed.
+
+    Yields
+    ------
+    t : ndarray
+        Knot vectors with an increasing number of knots.
+        The generator is finite: it stops when the smoothing critetion is
+        satisfied, or when then number of knots exceeds the maximum value:
+        the user-provided `nest` or `x.size + k + 1` --- which is the knot vector
+        for the interpolating spline.
+
+    Examples
+    --------
+    Generate some noisy data and fit a sequence of LSQ splines:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import make_lsq_spline, generate_knots
+    >>> rng = np.random.default_rng(12345)
+    >>> x = np.linspace(-3, 3, 50)
+    >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(size=50)
+
+    >>> knots = list(generate_knots(x, y, s=1e-10))
+    >>> for t in knots[::3]:
+    ...     spl = make_lsq_spline(x, y, t)
+    ...     xs = xs = np.linspace(-3, 3, 201)
+    ...     plt.plot(xs, spl(xs), '-', label=f'n = {len(t)}', lw=3, alpha=0.7)
+    >>> plt.plot(x, y, 'o', label='data')
+    >>> plt.plot(xs, np.exp(-xs**2), '--')
+    >>> plt.legend()
+
+    Note that increasing the number of knots make the result follow the data
+    more and more closely.
+
+    Also note that a step of the generator may add multiple knots:
+
+    >>> [len(t) for t in knots]
+    [8, 9, 10, 12, 16, 24, 40, 48, 52, 54]
+
+    Notes
+    -----
+    The routine generates successive knots vectors of increasing length, starting
+    from ``2*(k+1)`` to ``len(x) + k + 1``, trying to make knots more dense
+    in the regions where the deviation of the LSQ spline from data is large.
+
+    When the maximum number of knots, ``len(x) + k + 1`` is reached
+    (this happens when ``s`` is small and ``nest`` is large), the generator
+    stops, and the last output is the knots for the interpolation with the
+    not-a-knot boundary condition.
+
+    Knots are located at data sites, unless ``k`` is even and the number of knots
+    is ``len(x) + k + 1``. In that case, the last output of the generator
+    has internal knots at Greville sites, ``(x[1:] + x[:-1]) / 2``.
+
+    .. versionadded:: 1.15.0
+
+    """
+    if s == 0:
+        if nest is not None or w is not None:
+            raise ValueError("s == 0 is interpolation only")
+        t = _not_a_knot(x, k)
+        yield t
+        return
+
+    x, y, w, k, s, xb, xe = _validate_inputs(
+        x, y, w, k, s, xb, xe, parametric=np.ndim(y) == 2
+    )
+
+    yield from _generate_knots_impl(x, y, w=w, xb=xb, xe=xe, k=k, s=s, nest=nest)
+
+
+def _generate_knots_impl(x, y, *, w=None, xb=None, xe=None, k=3, s=0, nest=None):
+
+    acc = s * TOL
+    m = x.size    # the number of data points
+
+    if nest is None:
+        # the max number of knots. This is set in _fitpack_impl.py line 274
+        # and fitpack.pyf line 198
+        nest = max(m + k + 1, 2*k + 3)
+    else:
+        if nest < 2*(k + 1):
+            raise ValueError(f"`nest` too small: {nest = } < 2*(k+1) = {2*(k+1)}.")
+
+    nmin = 2*(k + 1)    # the number of knots for an LSQ polynomial approximation
+    nmax = m + k + 1  # the number of knots for the spline interpolation
+
+    # start from no internal knots
+    t = np.asarray([xb]*(k+1) + [xe]*(k+1), dtype=float)
+    n = t.shape[0]
+    fp = 0.0
+    fpold = 0.0
+
+    # c  main loop for the different sets of knots. m is a safe upper bound
+    # c  for the number of trials.
+    for _ in range(m):
+        yield t
+
+        # construct the LSQ spline with this set of knots
+        fpold = fp
+        residuals = _get_residuals(x, y, t, k, w=w)
+        fp = residuals.sum()
+        fpms = fp - s
+
+        # c  test whether the approximation sinf(x) is an acceptable solution.
+        # c  if f(p=inf) < s accept the choice of knots.
+        if (abs(fpms) < acc) or (fpms < 0):
+            return
+
+        # ### c  increase the number of knots. ###
+
+        # c  determine the number of knots nplus we are going to add.
+        if n == nmin:
+            # the first iteration
+            nplus = 1
+        else:
+            delta = fpold - fp
+            npl1 = int(nplus * fpms / delta) if delta > acc else nplus*2
+            nplus = min(nplus*2, max(npl1, nplus//2, 1))
+
+        # actually add knots
+        for j in range(nplus):
+            t = add_knot(x, t, k, residuals)
+
+            # check if we have enough knots already
+
+            n = t.shape[0]
+            # c  if n = nmax, sinf(x) is an interpolating spline.
+            # c  if n=nmax we locate the knots as for interpolation.
+            if n >= nmax:
+                t = _not_a_knot(x, k)
+                yield t
+                return
+
+            # c  if n=nest we cannot increase the number of knots because of
+            # c  the storage capacity limitation.
+            if n >= nest:
+                yield t
+                return
+
+            # recompute if needed
+            if j < nplus - 1:
+                residuals = _get_residuals(x, y, t, k, w=w)
+
+    # this should never be reached
+    return
+
+
+#   cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
+#   c  part 2: determination of the smoothing spline sp(x).                c
+#   c  ***************************************************                 c
+#   c  we have determined the number of knots and their position.          c
+#   c  we now compute the b-spline coefficients of the smoothing spline    c
+#   c  sp(x). the observation matrix a is extended by the rows of matrix   c
+#   c  b expressing that the kth derivative discontinuities of sp(x) at    c
+#   c  the interior knots t(k+2),...t(n-k-1) must be zero. the corres-     c
+#   c  ponding weights of these additional rows are set to 1/p.            c
+#   c  iteratively we then have to determine the value of p such that      c
+#   c  f(p)=sum((w(i)*(y(i)-sp(x(i))))**2) be = s. we already know that    c
+#   c  the least-squares kth degree polynomial corresponds to p=0, and     c
+#   c  that the least-squares spline corresponds to p=infinity. the        c
+#   c  iteration process which is proposed here, makes use of rational     c
+#   c  interpolation. since f(p) is a convex and strictly decreasing       c
+#   c  function of p, it can be approximated by a rational function        c
+#   c  r(p) = (u*p+v)/(p+w). three values of p(p1,p2,p3) with correspond-  c
+#   c  ing values of f(p) (f1=f(p1)-s,f2=f(p2)-s,f3=f(p3)-s) are used      c
+#   c  to calculate the new value of p such that r(p)=s. convergence is    c
+#   c  guaranteed by taking f1>0 and f3<0.                                 c
+#   cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
+
+
+def prodd(t, i, j, k):
+    res = 1.0
+    for s in range(k+2):
+        if i + s != j:
+            res *= (t[j] - t[i+s])
+    return res
+
+
+def disc(t, k):
+    """Discontinuity matrix: jumps of k-th derivatives of b-splines at internal knots.
+
+    See Eqs. (9)-(10) of Ref. [1], or, equivalently, Eq. (3.43) of Ref. [2].
+
+    This routine assumes internal knots are all simple (have multiplicity =1).
+
+    Parameters
+    ----------
+    t : ndarray, 1D, shape(n,)
+        Knots.
+    k : int
+        The spline degree
+
+    Returns
+    -------
+    disc : ndarray, shape(n-2*k-1, k+2)
+        The jumps of the k-th derivatives of b-splines at internal knots,
+        ``t[k+1], ...., t[n-k-1]``.
+    offset : ndarray, shape(2-2*k-1,)
+        Offsets
+    nc : int
+
+    Notes
+    -----
+
+    The normalization here follows FITPACK:
+    (https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpdisc.f#L36)
+
+    The k-th derivative jumps are multiplied by a factor::
+
+        (delta / nrint)**k / k!
+
+    where ``delta`` is the length of the interval spanned by internal knots, and
+    ``nrint`` is one less the number of internal knots (i.e., the number of
+    subintervals between them).
+
+    References
+    ----------
+    .. [1] Paul Dierckx, Algorithms for smoothing data with periodic and parametric
+           splines, Computer Graphics and Image Processing, vol. 20, p. 171 (1982).
+           :doi:`10.1016/0146-664X(82)90043-0`
+
+    .. [2] Tom Lyche and Knut Morken, Spline methods,
+        http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/
+
+    """
+    n = t.shape[0]
+
+    # the length of the base interval spanned by internal knots & the number
+    # of subintervas between these internal knots
+    delta = t[n - k - 1] - t[k]
+    nrint = n - 2*k - 1
+
+    matr = np.empty((nrint - 1, k + 2), dtype=float)
+    for jj in range(nrint - 1):
+        j = jj + k + 1
+        for ii in range(k + 2):
+            i = jj + ii
+            matr[jj, ii] = (t[i + k + 1] - t[i]) / prodd(t, i, j, k)
+        # NB: equivalent to
+        # row = [(t[i + k + 1] - t[i]) / prodd(t, i, j, k) for i in range(j-k-1, j+1)]
+        # assert (matr[j-k-1, :] == row).all()
+
+    # follow FITPACK
+    matr *= (delta/ nrint)**k
+
+    # make it packed
+    offset = np.array([i for i in range(nrint-1)], dtype=np.int64)
+    nc = n - k - 1
+    return matr, offset, nc
+
+
+class F:
+    """ The r.h.s. of ``f(p) = s``.
+
+    Given scalar `p`, we solve the system of equations in the LSQ sense:
+
+        | A     |  @ | c | = | y |
+        | B / p |    | 0 |   | 0 |
+
+    where `A` is the matrix of b-splines and `b` is the discontinuity matrix
+    (the jumps of the k-th derivatives of b-spline basis elements at knots).
+
+    Since we do that repeatedly while minimizing over `p`, we QR-factorize
+    `A` only once and update the QR factorization only of the `B` rows of the
+    augmented matrix |A, B/p|.
+
+    The system of equations is Eq. (15) Ref. [1]_, the strategy and implementation
+    follows that of FITPACK, see specific links below.
+
+    References
+    ----------
+    [1] P. Dierckx, Algorithms for Smoothing Data with Periodic and Parametric Splines,
+        COMPUTER GRAPHICS AND IMAGE PROCESSING vol. 20, pp 171-184 (1982.)
+        https://doi.org/10.1016/0146-664X(82)90043-0
+
+    """
+    def __init__(self, x, y, t, k, s, w=None, *, R=None, Y=None):
+        self.x = x
+        self.y = y
+        self.t = t
+        self.k = k
+        w = np.ones_like(x, dtype=float) if w is None else w
+        if w.ndim != 1:
+            raise ValueError(f"{w.ndim = } != 1.")
+        self.w = w
+        self.s = s
+
+        if y.ndim != 2:
+            raise ValueError(f"F: expected y.ndim == 2, got {y.ndim = } instead.")
+
+        # ### precompute what we can ###
+
+        # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L250
+        # c  evaluate the discontinuity jump of the kth derivative of the
+        # c  b-splines at the knots t(l),l=k+2,...n-k-1 and store in b.
+        b, b_offset, b_nc = disc(t, k)
+
+        # the QR factorization of the data matrix, if not provided
+        # NB: otherwise, must be consistent with x,y & s, but this is not checked
+        if R is None and Y is None:
+            R, Y, _ = _lsq_solve_qr(x, y, t, k, w)
+
+        # prepare to combine R and the discontinuity matrix (AB); also r.h.s. (YY)
+        # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L269
+        # c  the rows of matrix b with weight 1/p are rotated into the
+        # c  triangularised observation matrix a which is stored in g.
+        nc = t.shape[0] - k - 1
+        nz = k + 1
+        if R.shape[1] != nz:
+            raise ValueError(f"Internal error: {R.shape[1] =} != {k+1 =}.")
+
+        # r.h.s. of the augmented system
+        z = np.zeros((b.shape[0], Y.shape[1]), dtype=float)
+        self.YY = np.r_[Y[:nc], z]
+
+        # l.h.s. of the augmented system
+        AA = np.zeros((nc + b.shape[0], self.k+2), dtype=float)
+        AA[:nc, :nz] = R[:nc, :]
+        # AA[nc:, :] = b.a / p  # done in __call__(self, p)
+        self.AA  = AA
+        self.offset = np.r_[np.arange(nc, dtype=np.int64), b_offset]
+
+        self.nc = nc
+        self.b = b
+
+    def __call__(self, p):
+        # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L279
+        # c  the row of matrix b is rotated into triangle by givens transformation
+
+        # copy the precomputed matrices over for in-place work
+        # R = PackedMatrix(self.AB.a.copy(), self.AB.offset.copy(), nc)
+        AB = self.AA.copy()
+        offset = self.offset.copy()
+        nc = self.nc
+
+        AB[nc:, :] = self.b / p
+        QY = self.YY.copy()
+
+        # heavy lifting happens here, in-place
+        _dierckx.qr_reduce(AB, offset, nc, QY, startrow=nc)
+
+        # solve for the coefficients
+        c = _dierckx.fpback(AB, nc, QY)
+
+        spl = BSpline(self.t, c, self.k)
+        residuals = _compute_residuals(self.w**2, spl(self.x), self.y)
+        fp = residuals.sum()
+
+        self.spl = spl   # store it
+
+        return fp - self.s
+
+
+def fprati(p1, f1, p2, f2, p3, f3):
+    """The root of r(p) = (u*p + v) / (p + w) given three points and values,
+    (p1, f2), (p2, f2) and (p3, f3).
+
+    The FITPACK analog adjusts the bounds, and we do not
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fprati.f
+
+    NB: FITPACK uses p < 0 to encode p=infinity. We just use the infinity itself.
+    Since the bracket is ``p1 <= p2 <= p3``, ``p3`` can be infinite (in fact,
+    this is what the minimizer starts with, ``p3=inf``).
+    """
+    h1 = f1 * (f2 - f3)
+    h2 = f2 * (f3 - f1)
+    h3 = f3 * (f1 - f2)
+    if p3 == np.inf:
+        return -(p2*h1 + p1*h2) / h3
+    return -(p1*p2*h3 + p2*p3*h1 + p1*p3*h2) / (p1*h1 + p2*h2 + p3*h3)
+
+
+class Bunch:
+    def __init__(self, **kwargs):
+        self.__dict__.update(**kwargs)
+
+
+_iermesg = {
+2: """error. a theoretically impossible result was found during
+the iteration process for finding a smoothing spline with
+fp = s. probably causes : s too small.
+there is an approximation returned but the corresponding
+weighted sum of squared residuals does not satisfy the
+condition abs(fp-s)/s < tol.
+""",
+3: """error. the maximal number of iterations maxit (set to 20
+by the program) allowed for finding a smoothing spline
+with fp=s has been reached. probably causes : s too small
+there is an approximation returned but the corresponding
+weighted sum of squared residuals does not satisfy the
+condition abs(fp-s)/s < tol.
+"""
+}
+
+
+def root_rati(f, p0, bracket, acc):
+    """Solve `f(p) = 0` using a rational function approximation.
+
+    In a nutshell, since the function f(p) is known to be monotonically decreasing, we
+       - maintain the bracket (p1, f1), (p2, f2) and (p3, f3)
+       - at each iteration step, approximate f(p) by a rational function
+         r(p) = (u*p + v) / (p + w)
+         and make a step to p_new to the root of f(p): r(p_new) = 0.
+         The coefficients u, v and w are found from the bracket values p1..3 and f1...3
+
+    The algorithm and implementation follows
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L229
+    and
+    https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fppara.f#L290
+
+    Note that the latter is for parametric splines and the former is for 1D spline
+    functions. The minimization is indentical though [modulo a summation over the
+    dimensions in the computation of f(p)], so we reuse the minimizer for both
+    d=1 and d>1.
+    """
+    # Magic values from
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L27
+    con1 = 0.1
+    con9 = 0.9
+    con4 = 0.04
+
+    # bracketing flags (follow FITPACK)
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fppara.f#L365
+    ich1, ich3 = 0, 0
+
+    (p1, f1), (p3, f3)  = bracket
+    p = p0
+
+    for it in range(MAXIT):
+        p2, f2 = p, f(p)
+
+        # c  test whether the approximation sp(x) is an acceptable solution.
+        if abs(f2) < acc:
+            ier, converged = 0, True
+            break
+
+        # c  carry out one more step of the iteration process.
+        if ich3 == 0:
+            if f2 - f3 <= acc:
+                # c  our initial choice of p is too large.
+                p3 = p2
+                f3 = f2
+                p = p*con4
+                if p <= p1:
+                     p = p1*con9 + p2*con1
+                continue
+            else:
+                if f2 < 0:
+                    ich3 = 1
+
+        if ich1 == 0:
+            if f1 - f2 <= acc:
+                # c  our initial choice of p is too small
+                p1 = p2
+                f1 = f2
+                p = p/con4
+                if p3 != np.inf and p <= p3:
+                     p = p2*con1 + p3*con9
+                continue
+            else:
+                if f2 > 0:
+                    ich1 = 1
+
+        # c  test whether the iteration process proceeds as theoretically expected.
+        # [f(p) should be monotonically decreasing]
+        if f1 <= f2 or f2 <= f3:
+            ier, converged = 2, False
+            break
+
+        # actually make the iteration step
+        p = fprati(p1, f1, p2, f2, p3, f3)
+
+        # c  adjust the value of p1,f1,p3 and f3 such that f1 > 0 and f3 < 0.
+        if f2 < 0:
+            p3, f3 = p2, f2
+        else:
+            p1, f1 = p2, f2
+
+    else:
+        # not converged in MAXIT iterations
+        ier, converged = 3, False
+
+    if ier != 0:
+        warnings.warn(RuntimeWarning(_iermesg[ier]), stacklevel=2)
+
+    return Bunch(converged=converged, root=p, iterations=it, ier=ier)
+
+
+def _make_splrep_impl(x, y, *, w=None, xb=None, xe=None, k=3, s=0, t=None, nest=None):
+    """Shared infra for make_splrep and make_splprep.
+    """
+    acc = s * TOL
+    m = x.size    # the number of data points
+
+    if nest is None:
+        # the max number of knots. This is set in _fitpack_impl.py line 274
+        # and fitpack.pyf line 198
+        nest = max(m + k + 1, 2*k + 3)
+    else:
+        if nest < 2*(k + 1):
+            raise ValueError(f"`nest` too small: {nest = } < 2*(k+1) = {2*(k+1)}.")    
+        if t is not None:
+            raise ValueError("Either supply `t` or `nest`.")
+
+    if t is None:
+        gen = _generate_knots_impl(x, y, w=w, k=k, s=s, xb=xb, xe=xe, nest=nest)
+        t = list(gen)[-1]
+    else:
+        fpcheck(x, t, k)
+
+    if t.shape[0] == 2 * (k + 1):
+        # nothing to optimize
+        _, _, c = _lsq_solve_qr(x, y, t, k, w)
+        return BSpline(t, c, k)
+
+    ### solve ###
+
+    # c  initial value for p.
+    # https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L253
+    R, Y, _ = _lsq_solve_qr(x, y, t, k, w)
+    nc = t.shape[0] -k -1
+    p = nc / R[:, 0].sum()
+
+    # ### bespoke solver ####
+    # initial conditions
+    # f(p=inf) : LSQ spline with knots t   (XXX: reuse R, c)
+    residuals = _get_residuals(x, y, t, k, w=w)
+    fp = residuals.sum()
+    fpinf = fp - s
+
+    # f(p=0): LSQ spline without internal knots
+    residuals = _get_residuals(x, y, np.array([xb]*(k+1) + [xe]*(k+1)), k, w)
+    fp0 = residuals.sum()
+    fp0 = fp0 - s
+
+    # solve
+    bracket = (0, fp0), (np.inf, fpinf)
+    f = F(x, y, t, k=k, s=s, w=w, R=R, Y=Y)
+    _ = root_rati(f, p, bracket, acc)
+
+    # solve ALTERNATIVE: is roughly equivalent, gives slightly different results
+    # starting from scratch, that would have probably been tolerable;
+    # backwards compatibility dictates that we replicate the FITPACK minimizer though.
+ #   f = F(x, y, t, k=k, s=s, w=w, R=R, Y=Y)
+ #   from scipy.optimize import root_scalar
+ #   res_ = root_scalar(f, x0=p, rtol=acc)
+ #   assert res_.converged
+
+    # f.spl is the spline corresponding to the found `p` value
+    return f.spl
+
+
+def make_splrep(x, y, *, w=None, xb=None, xe=None, k=3, s=0, t=None, nest=None):
+    r"""Find the B-spline representation of a 1D function.
+
+    Given the set of data points ``(x[i], y[i])``, determine a smooth spline
+    approximation of degree ``k`` on the interval ``xb <= x <= xe``.
+
+    Parameters
+    ----------
+    x, y : array_like, shape (m,)
+        The data points defining a curve ``y = f(x)``.
+    w : array_like, shape (m,), optional
+        Strictly positive 1D array of weights, of the same length as `x` and `y`.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the y values have standard-deviation given by the
+        vector ``d``, then `w` should be ``1/d``.
+        Default is ``np.ones(m)``.
+    xb, xe : float, optional
+        The interval to fit.  If None, these default to ``x[0]`` and ``x[-1]``,
+        respectively.
+    k : int, optional
+        The degree of the spline fit. It is recommended to use cubic splines,
+        ``k=3``, which is the default. Even values of `k` should be avoided,
+        especially with small `s` values.
+    s : float, optional
+        The smoothing condition. The amount of smoothness is determined by
+        satisfying the conditions::
+
+            sum((w * (g(x)  - y))**2 ) <= s
+
+        where ``g(x)`` is the smoothed fit to ``(x, y)``. The user can use `s`
+        to control the tradeoff between closeness to data and smoothness of fit.
+        Larger `s` means more smoothing while smaller values of `s` indicate less
+        smoothing.
+        Recommended values of `s` depend on the weights, `w`. If the weights
+        represent the inverse of the standard deviation of `y`, then a good `s`
+        value should be found in the range ``(m-sqrt(2*m), m+sqrt(2*m))`` where
+        ``m`` is the number of datapoints in `x`, `y`, and `w`.
+        Default is ``s = 0.0``, i.e. interpolation.
+    t : array_like, optional
+        The spline knots. If None (default), the knots will be constructed
+        automatically.
+        There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots.
+    nest : int, optional
+        The target length of the knot vector. Should be between ``2*(k + 1)``
+        (the minimum number of knots for a degree-``k`` spline), and
+        ``m + k + 1`` (the number of knots of the interpolating spline).
+        The actual number of knots returned by this routine may be slightly
+        larger than `nest`.
+        Default is None (no limit, add up to ``m + k + 1`` knots).
+
+    Returns
+    -------
+    spl : a `BSpline` instance
+        For `s=0`,  ``spl(x) == y``.
+        For non-zero values of `s` the `spl` represents the smoothed approximation
+        to `(x, y)`, generally with fewer knots.
+
+    See Also
+    --------
+    generate_knots : is used under the hood for generating the knots
+    make_splprep : the analog of this routine for parametric curves
+    make_interp_spline : construct an interpolating spline (``s = 0``)
+    make_lsq_spline : construct the least-squares spline given the knot vector
+    splrep : a FITPACK analog of this routine
+
+    References
+    ----------
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+        Numerical Analysis, Oxford University Press, 1993.
+
+    Notes
+    -----
+    This routine constructs the smoothing spline function, :math:`g(x)`, to
+    minimize the sum of jumps, :math:`D_j`, of the ``k``-th derivative at the
+    internal knots (:math:`x_b < t_i < x_e`), where
+
+    .. math::
+
+        D_i = g^{(k)}(t_i + 0) - g^{(k)}(t_i - 0)
+
+    Specifically, the routine constructs the spline function :math:`g(x)` which
+    minimizes
+
+    .. math::
+
+            \sum_i | D_i |^2 \to \mathrm{min}
+
+    provided that
+
+    .. math::
+
+           \sum_{j=1}^m (w_j \times (g(x_j) - y_j))^2 \leqslant s ,
+
+    where :math:`s > 0` is the input parameter.
+
+    In other words, we balance maximizing the smoothness (measured as the jumps
+    of the derivative, the first criterion), and the deviation of :math:`g(x_j)`
+    from the data :math:`y_j` (the second criterion).
+
+    Note that the summation in the second criterion is over all data points,
+    and in the first criterion it is over the internal spline knots (i.e.
+    those with ``xb < t[i] < xe``). The spline knots are in general a subset
+    of data, see `generate_knots` for details.
+
+    Also note the difference of this routine to `make_lsq_spline`: the latter
+    routine does not consider smoothness and simply solves a least-squares
+    problem
+
+    .. math::
+
+        \sum w_j \times (g(x_j) - y_j)^2 \to \mathrm{min}
+
+    for a spline function :math:`g(x)` with a _fixed_ knot vector ``t``.
+
+    .. versionadded:: 1.15.0
+    """
+    if s == 0:
+        if t is not None or w is not None or nest is not None:
+            raise ValueError("s==0 is for interpolation only")
+        return make_interp_spline(x, y, k=k)
+
+    x, y, w, k, s, xb, xe = _validate_inputs(x, y, w, k, s, xb, xe, parametric=False)
+
+    spl = _make_splrep_impl(x, y, w=w, xb=xb, xe=xe, k=k, s=s, t=t, nest=nest)
+
+    # postprocess: squeeze out the last dimension: was added to simplify the internals.
+    spl.c = spl.c[:, 0]
+    return spl
+
+
+def make_splprep(x, *, w=None, u=None, ub=None, ue=None, k=3, s=0, t=None, nest=None):
+    r"""
+    Find a smoothed B-spline representation of a parametric N-D curve.
+
+    Given a list of N 1D arrays, `x`, which represent a curve in
+    N-dimensional space parametrized by `u`, find a smooth approximating
+    spline curve ``g(u)``.
+
+    Parameters
+    ----------
+    x : array_like, shape (m, ndim)
+        Sampled data points representing the curve in ``ndim`` dimensions.
+        The typical use is a list of 1D arrays, each of length ``m``.
+    w : array_like, shape(m,), optional
+        Strictly positive 1D array of weights.
+        The weights are used in computing the weighted least-squares spline
+        fit. If the errors in the `x` values have standard deviation given by
+        the vector d, then `w` should be 1/d. Default is ``np.ones(m)``.
+    u : array_like, optional
+        An array of parameter values for the curve in the parametric form.
+        If not given, these values are calculated automatically, according to::
+
+            v[0] = 0
+            v[i] = v[i-1] + distance(x[i], x[i-1])
+            u[i] = v[i] / v[-1]
+
+    ub, ue : float, optional
+        The end-points of the parameters interval. Default to ``u[0]`` and ``u[-1]``.
+    k : int, optional
+        Degree of the spline. Cubic splines, ``k=3``, are recommended.
+        Even values of `k` should be avoided especially with a small ``s`` value.
+        Default is ``k=3``
+    s : float, optional
+        A smoothing condition.  The amount of smoothness is determined by
+        satisfying the conditions::
+
+            sum((w * (g(u) - x))**2) <= s,
+
+        where ``g(u)`` is the smoothed approximation to ``x``.  The user can
+        use `s` to control the trade-off between closeness and smoothness
+        of fit.  Larger ``s`` means more smoothing while smaller values of ``s``
+        indicate less smoothing.
+        Recommended values of ``s`` depend on the weights, ``w``.  If the weights
+        represent the inverse of the standard deviation of ``x``, then a good
+        ``s`` value should be found in the range ``(m - sqrt(2*m), m + sqrt(2*m))``,
+        where ``m`` is the number of data points in ``x`` and ``w``.
+    t : array_like, optional
+        The spline knots. If None (default), the knots will be constructed
+        automatically.
+        There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots.
+    nest : int, optional
+        The target length of the knot vector. Should be between ``2*(k + 1)``
+        (the minimum number of knots for a degree-``k`` spline), and
+        ``m + k + 1`` (the number of knots of the interpolating spline).
+        The actual number of knots returned by this routine may be slightly
+        larger than `nest`.
+        Default is None (no limit, add up to ``m + k + 1`` knots).
+
+    Returns
+    -------
+    spl : a `BSpline` instance
+        For `s=0`,  ``spl(u) == x``.
+        For non-zero values of ``s``, `spl` represents the smoothed approximation
+        to ``x``, generally with fewer knots.
+    u : ndarray
+        The values of the parameters
+
+    See Also
+    --------
+    generate_knots : is used under the hood for generating the knots
+    make_splrep : the analog of this routine 1D functions
+    make_interp_spline : construct an interpolating spline (``s = 0``)
+    make_lsq_spline : construct the least-squares spline given the knot vector
+    splprep : a FITPACK analog of this routine
+
+    Notes
+    -----
+    Given a set of :math:`m` data points in :math:`D` dimensions, :math:`\vec{x}_j`,
+    with :math:`j=1, ..., m` and :math:`\vec{x}_j = (x_{j; 1}, ..., x_{j; D})`,
+    this routine constructs the parametric spline curve :math:`g_a(u)` with
+    :math:`a=1, ..., D`, to minimize the sum of jumps, :math:`D_{i; a}`, of the
+    ``k``-th derivative at the internal knots (:math:`u_b < t_i < u_e`), where
+
+    .. math::
+
+        D_{i; a} = g_a^{(k)}(t_i + 0) - g_a^{(k)}(t_i - 0)
+
+    Specifically, the routine constructs the spline function :math:`g(u)` which
+    minimizes
+
+    .. math::
+
+            \sum_i \sum_{a=1}^D | D_{i; a} |^2 \to \mathrm{min}
+
+    provided that
+
+    .. math::
+
+        \sum_{j=1}^m \sum_{a=1}^D (w_j \times (g_a(u_j) - x_{j; a}))^2 \leqslant s
+
+    where :math:`u_j` is the value of the parameter corresponding to the data point
+    :math:`(x_{j; 1}, ..., x_{j; D})`, and :math:`s > 0` is the input parameter.
+
+    In other words, we balance maximizing the smoothness (measured as the jumps
+    of the derivative, the first criterion), and the deviation of :math:`g(u_j)`
+    from the data :math:`x_j` (the second criterion).
+
+    Note that the summation in the second criterion is over all data points,
+    and in the first criterion it is over the internal spline knots (i.e.
+    those with ``ub < t[i] < ue``). The spline knots are in general a subset
+    of data, see `generate_knots` for details.
+
+    .. versionadded:: 1.15.0
+
+    References
+    ----------
+    .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
+        parametric splines, Computer Graphics and Image Processing",
+        20 (1982) 171-184.
+    .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
+        Numerical Analysis, Oxford University Press, 1993.
+    """
+    x = np.stack(x, axis=1)
+
+    # construct the default parametrization of the curve
+    if u is None:
+        dp = (x[1:, :] - x[:-1, :])**2
+        u = np.sqrt((dp).sum(axis=1)).cumsum()
+        u = np.r_[0, u / u[-1]]
+
+    if s == 0:
+        if t is not None or w is not None or nest is not None:
+            raise ValueError("s==0 is for interpolation only")
+        return make_interp_spline(u, x.T, k=k, axis=1), u
+
+    u, x, w, k, s, ub, ue = _validate_inputs(u, x, w, k, s, ub, ue, parametric=True)
+
+    spl = _make_splrep_impl(u, x, w=w, xb=ub, xe=ue, k=k, s=s, t=t, nest=nest)
+
+    # posprocess: `axis=1` so that spl(u).shape == np.shape(x)
+    # when `x` is a list of 1D arrays (cf original splPrep)
+    cc = spl.c.T
+    spl1 = BSpline(spl.t, cc, spl.k, axis=1)
+
+    return spl1, u
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..7558bd7db25cbd60206f908aabbcb6dc9c567fa4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py
@@ -0,0 +1,2248 @@
+__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly']
+
+from math import prod
+
+import numpy as np
+from numpy import array, asarray, intp, poly1d, searchsorted
+
+import scipy.special as spec
+from scipy._lib._util import copy_if_needed
+from scipy.special import comb
+
+from . import _fitpack_py
+from ._polyint import _Interpolator1D
+from . import _ppoly
+from ._interpnd import _ndim_coords_from_arrays
+from ._bsplines import make_interp_spline, BSpline
+
+
+def lagrange(x, w):
+    r"""
+    Return a Lagrange interpolating polynomial.
+
+    Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating
+    polynomial through the points ``(x, w)``.
+
+    Warning: This implementation is numerically unstable. Do not expect to
+    be able to use more than about 20 points even if they are chosen optimally.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` represents the x-coordinates of a set of datapoints.
+    w : array_like
+        `w` represents the y-coordinates of a set of datapoints, i.e., f(`x`).
+
+    Returns
+    -------
+    lagrange : `numpy.poly1d` instance
+        The Lagrange interpolating polynomial.
+
+    Examples
+    --------
+    Interpolate :math:`f(x) = x^3` by 3 points.
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import lagrange
+    >>> x = np.array([0, 1, 2])
+    >>> y = x**3
+    >>> poly = lagrange(x, y)
+
+    Since there are only 3 points, Lagrange polynomial has degree 2. Explicitly,
+    it is given by
+
+    .. math::
+
+        \begin{aligned}
+            L(x) &= 1\times \frac{x (x - 2)}{-1} + 8\times \frac{x (x-1)}{2} \\
+                 &= x (-2 + 3x)
+        \end{aligned}
+
+    >>> from numpy.polynomial.polynomial import Polynomial
+    >>> Polynomial(poly.coef[::-1]).coef
+    array([ 0., -2.,  3.])
+
+    >>> import matplotlib.pyplot as plt
+    >>> x_new = np.arange(0, 2.1, 0.1)
+    >>> plt.scatter(x, y, label='data')
+    >>> plt.plot(x_new, Polynomial(poly.coef[::-1])(x_new), label='Polynomial')
+    >>> plt.plot(x_new, 3*x_new**2 - 2*x_new + 0*x_new,
+    ...          label=r"$3 x^2 - 2 x$", linestyle='-.')
+    >>> plt.legend()
+    >>> plt.show()
+
+    """
+
+    M = len(x)
+    p = poly1d(0.0)
+    for j in range(M):
+        pt = poly1d(w[j])
+        for k in range(M):
+            if k == j:
+                continue
+            fac = x[j]-x[k]
+            pt *= poly1d([1.0, -x[k]])/fac
+        p += pt
+    return p
+
+
+# !! Need to find argument for keeping initialize. If it isn't
+# !! found, get rid of it!
+
+
+err_mesg = """\
+`interp2d` has been removed in SciPy 1.14.0.
+
+For legacy code, nearly bug-for-bug compatible replacements are
+`RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for
+scattered 2D data.
+
+In new code, for regular grids use `RegularGridInterpolator` instead.
+For scattered data, prefer `LinearNDInterpolator` or
+`CloughTocher2DInterpolator`.
+
+For more details see
+https://scipy.github.io/devdocs/tutorial/interpolate/interp_transition_guide.html
+"""
+
+class interp2d:
+    """
+    interp2d(x, y, z, kind='linear', copy=True, bounds_error=False,
+             fill_value=None)
+
+    .. versionremoved:: 1.14.0
+
+        `interp2d` has been removed in SciPy 1.14.0.
+
+        For legacy code, nearly bug-for-bug compatible replacements are
+        `RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for
+        scattered 2D data.
+
+        In new code, for regular grids use `RegularGridInterpolator` instead.
+        For scattered data, prefer `LinearNDInterpolator` or
+        `CloughTocher2DInterpolator`.
+
+        For more details see :ref:`interp-transition-guide`.
+    """
+    def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False,
+                 fill_value=None):
+        raise NotImplementedError(err_mesg)
+
+
+def _check_broadcast_up_to(arr_from, shape_to, name):
+    """Helper to check that arr_from broadcasts up to shape_to"""
+    shape_from = arr_from.shape
+    if len(shape_to) >= len(shape_from):
+        for t, f in zip(shape_to[::-1], shape_from[::-1]):
+            if f != 1 and f != t:
+                break
+        else:  # all checks pass, do the upcasting that we need later
+            if arr_from.size != 1 and arr_from.shape != shape_to:
+                arr_from = np.ones(shape_to, arr_from.dtype) * arr_from
+            return arr_from.ravel()
+    # at least one check failed
+    raise ValueError(f'{name} argument must be able to broadcast up '
+                     f'to shape {shape_to} but had shape {shape_from}')
+
+
+def _do_extrapolate(fill_value):
+    """Helper to check if fill_value == "extrapolate" without warnings"""
+    return (isinstance(fill_value, str) and
+            fill_value == 'extrapolate')
+
+
+class interp1d(_Interpolator1D):
+    """
+    Interpolate a 1-D function.
+
+    .. legacy:: class
+
+        For a guide to the intended replacements for `interp1d` see
+        :ref:`tutorial-interpolate_1Dsection`.
+
+    `x` and `y` are arrays of values used to approximate some function f:
+    ``y = f(x)``. This class returns a function whose call method uses
+    interpolation to find the value of new points.
+
+    Parameters
+    ----------
+    x : (npoints, ) array_like
+        A 1-D array of real values.
+    y : (..., npoints, ...) array_like
+        A N-D array of real values. The length of `y` along the interpolation
+        axis must be equal to the length of `x`. Use the ``axis`` parameter
+        to select correct axis. Unlike other interpolators, the default
+        interpolation axis is the last axis of `y`.
+    kind : str or int, optional
+        Specifies the kind of interpolation as a string or as an integer
+        specifying the order of the spline interpolator to use.
+        The string has to be one of 'linear', 'nearest', 'nearest-up', 'zero',
+        'slinear', 'quadratic', 'cubic', 'previous', or 'next'. 'zero',
+        'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of
+        zeroth, first, second or third order; 'previous' and 'next' simply
+        return the previous or next value of the point; 'nearest-up' and
+        'nearest' differ when interpolating half-integers (e.g. 0.5, 1.5)
+        in that 'nearest-up' rounds up and 'nearest' rounds down. Default
+        is 'linear'.
+    axis : int, optional
+        Axis in the ``y`` array corresponding to the x-coordinate values. Unlike
+        other interpolators, defaults to ``axis=-1``.
+    copy : bool, optional
+        If ``True``, the class makes internal copies of x and y. If ``False``,
+        references to ``x`` and ``y`` are used if possible. The default is to copy.
+    bounds_error : bool, optional
+        If True, a ValueError is raised any time interpolation is attempted on
+        a value outside of the range of x (where extrapolation is
+        necessary). If False, out of bounds values are assigned `fill_value`.
+        By default, an error is raised unless ``fill_value="extrapolate"``.
+    fill_value : array-like or (array-like, array_like) or "extrapolate", optional
+        - if a ndarray (or float), this value will be used to fill in for
+          requested points outside of the data range. If not provided, then
+          the default is NaN. The array-like must broadcast properly to the
+          dimensions of the non-interpolation axes.
+        - If a two-element tuple, then the first element is used as a
+          fill value for ``x_new < x[0]`` and the second element is used for
+          ``x_new > x[-1]``. Anything that is not a 2-element tuple (e.g.,
+          list or ndarray, regardless of shape) is taken to be a single
+          array-like argument meant to be used for both bounds as
+          ``below, above = fill_value, fill_value``. Using a two-element tuple
+          or ndarray requires ``bounds_error=False``.
+
+          .. versionadded:: 0.17.0
+        - If "extrapolate", then points outside the data range will be
+          extrapolated.
+
+          .. versionadded:: 0.17.0
+    assume_sorted : bool, optional
+        If False, values of `x` can be in any order and they are sorted first.
+        If True, `x` has to be an array of monotonically increasing values.
+
+    Attributes
+    ----------
+    fill_value
+
+    Methods
+    -------
+    __call__
+
+    See Also
+    --------
+    splrep, splev
+        Spline interpolation/smoothing based on FITPACK.
+    UnivariateSpline : An object-oriented wrapper of the FITPACK routines.
+    interp2d : 2-D interpolation
+
+    Notes
+    -----
+    Calling `interp1d` with NaNs present in input values results in
+    undefined behaviour.
+
+    Input values `x` and `y` must be convertible to `float` values like
+    `int` or `float`.
+
+    If the values in `x` are not unique, the resulting behavior is
+    undefined and specific to the choice of `kind`, i.e., changing
+    `kind` will change the behavior for duplicates.
+
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import interpolate
+    >>> x = np.arange(0, 10)
+    >>> y = np.exp(-x/3.0)
+    >>> f = interpolate.interp1d(x, y)
+
+    >>> xnew = np.arange(0, 9, 0.1)
+    >>> ynew = f(xnew)   # use interpolation function returned by `interp1d`
+    >>> plt.plot(x, y, 'o', xnew, ynew, '-')
+    >>> plt.show()
+    """
+
+    def __init__(self, x, y, kind='linear', axis=-1,
+                 copy=True, bounds_error=None, fill_value=np.nan,
+                 assume_sorted=False):
+        """ Initialize a 1-D linear interpolation class."""
+        _Interpolator1D.__init__(self, x, y, axis=axis)
+
+        self.bounds_error = bounds_error  # used by fill_value setter
+
+        # `copy` keyword semantics changed in NumPy 2.0, once that is
+        # the minimum version this can use `copy=None`.
+        self.copy = copy
+        if not copy:
+            self.copy = copy_if_needed
+
+        if kind in ['zero', 'slinear', 'quadratic', 'cubic']:
+            order = {'zero': 0, 'slinear': 1,
+                     'quadratic': 2, 'cubic': 3}[kind]
+            kind = 'spline'
+        elif isinstance(kind, int):
+            order = kind
+            kind = 'spline'
+        elif kind not in ('linear', 'nearest', 'nearest-up', 'previous',
+                          'next'):
+            raise NotImplementedError(f"{kind} is unsupported: Use fitpack "
+                                      "routines for other types.")
+        x = array(x, copy=self.copy)
+        y = array(y, copy=self.copy)
+
+        if not assume_sorted:
+            ind = np.argsort(x, kind="mergesort")
+            x = x[ind]
+            y = np.take(y, ind, axis=axis)
+
+        if x.ndim != 1:
+            raise ValueError("the x array must have exactly one dimension.")
+        if y.ndim == 0:
+            raise ValueError("the y array must have at least one dimension.")
+
+        # Force-cast y to a floating-point type, if it's not yet one
+        if not issubclass(y.dtype.type, np.inexact):
+            y = y.astype(np.float64)
+
+        # Backward compatibility
+        self.axis = axis % y.ndim
+
+        # Interpolation goes internally along the first axis
+        self.y = y
+        self._y = self._reshape_yi(self.y)
+        self.x = x
+        del y, x  # clean up namespace to prevent misuse; use attributes
+        self._kind = kind
+
+        # Adjust to interpolation kind; store reference to *unbound*
+        # interpolation methods, in order to avoid circular references to self
+        # stored in the bound instance methods, and therefore delayed garbage
+        # collection.  See: https://docs.python.org/reference/datamodel.html
+        if kind in ('linear', 'nearest', 'nearest-up', 'previous', 'next'):
+            # Make a "view" of the y array that is rotated to the interpolation
+            # axis.
+            minval = 1
+            if kind == 'nearest':
+                # Do division before addition to prevent possible integer
+                # overflow
+                self._side = 'left'
+                self.x_bds = self.x / 2.0
+                self.x_bds = self.x_bds[1:] + self.x_bds[:-1]
+
+                self._call = self.__class__._call_nearest
+            elif kind == 'nearest-up':
+                # Do division before addition to prevent possible integer
+                # overflow
+                self._side = 'right'
+                self.x_bds = self.x / 2.0
+                self.x_bds = self.x_bds[1:] + self.x_bds[:-1]
+
+                self._call = self.__class__._call_nearest
+            elif kind == 'previous':
+                # Side for np.searchsorted and index for clipping
+                self._side = 'left'
+                self._ind = 0
+                # Move x by one floating point value to the left
+                self._x_shift = np.nextafter(self.x, -np.inf)
+                self._call = self.__class__._call_previousnext
+                if _do_extrapolate(fill_value):
+                    self._check_and_update_bounds_error_for_extrapolation()
+                    # assume y is sorted by x ascending order here.
+                    fill_value = (np.nan, np.take(self.y, -1, axis))
+            elif kind == 'next':
+                self._side = 'right'
+                self._ind = 1
+                # Move x by one floating point value to the right
+                self._x_shift = np.nextafter(self.x, np.inf)
+                self._call = self.__class__._call_previousnext
+                if _do_extrapolate(fill_value):
+                    self._check_and_update_bounds_error_for_extrapolation()
+                    # assume y is sorted by x ascending order here.
+                    fill_value = (np.take(self.y, 0, axis), np.nan)
+            else:
+                # Check if we can delegate to numpy.interp (2x-10x faster).
+                np_dtypes = (np.dtype(np.float64), np.dtype(int))
+                cond = self.x.dtype in np_dtypes and self.y.dtype in np_dtypes
+                cond = cond and self.y.ndim == 1
+                cond = cond and not _do_extrapolate(fill_value)
+
+                if cond:
+                    self._call = self.__class__._call_linear_np
+                else:
+                    self._call = self.__class__._call_linear
+        else:
+            minval = order + 1
+
+            rewrite_nan = False
+            xx, yy = self.x, self._y
+            if order > 1:
+                # Quadratic or cubic spline. If input contains even a single
+                # nan, then the output is all nans. We cannot just feed data
+                # with nans to make_interp_spline because it calls LAPACK.
+                # So, we make up a bogus x and y with no nans and use it
+                # to get the correct shape of the output, which we then fill
+                # with nans.
+                # For slinear or zero order spline, we just pass nans through.
+                mask = np.isnan(self.x)
+                if mask.any():
+                    sx = self.x[~mask]
+                    if sx.size == 0:
+                        raise ValueError("`x` array is all-nan")
+                    xx = np.linspace(np.nanmin(self.x),
+                                     np.nanmax(self.x),
+                                     len(self.x))
+                    rewrite_nan = True
+                if np.isnan(self._y).any():
+                    yy = np.ones_like(self._y)
+                    rewrite_nan = True
+
+            self._spline = make_interp_spline(xx, yy, k=order,
+                                              check_finite=False)
+            if rewrite_nan:
+                self._call = self.__class__._call_nan_spline
+            else:
+                self._call = self.__class__._call_spline
+
+        if len(self.x) < minval:
+            raise ValueError("x and y arrays must have at "
+                             "least %d entries" % minval)
+
+        self.fill_value = fill_value  # calls the setter, can modify bounds_err
+
+    @property
+    def fill_value(self):
+        """The fill value."""
+        # backwards compat: mimic a public attribute
+        return self._fill_value_orig
+
+    @fill_value.setter
+    def fill_value(self, fill_value):
+        # extrapolation only works for nearest neighbor and linear methods
+        if _do_extrapolate(fill_value):
+            self._check_and_update_bounds_error_for_extrapolation()
+            self._extrapolate = True
+        else:
+            broadcast_shape = (self.y.shape[:self.axis] +
+                               self.y.shape[self.axis + 1:])
+            if len(broadcast_shape) == 0:
+                broadcast_shape = (1,)
+            # it's either a pair (_below_range, _above_range) or a single value
+            # for both above and below range
+            if isinstance(fill_value, tuple) and len(fill_value) == 2:
+                below_above = [np.asarray(fill_value[0]),
+                               np.asarray(fill_value[1])]
+                names = ('fill_value (below)', 'fill_value (above)')
+                for ii in range(2):
+                    below_above[ii] = _check_broadcast_up_to(
+                        below_above[ii], broadcast_shape, names[ii])
+            else:
+                fill_value = np.asarray(fill_value)
+                below_above = [_check_broadcast_up_to(
+                    fill_value, broadcast_shape, 'fill_value')] * 2
+            self._fill_value_below, self._fill_value_above = below_above
+            self._extrapolate = False
+            if self.bounds_error is None:
+                self.bounds_error = True
+        # backwards compat: fill_value was a public attr; make it writeable
+        self._fill_value_orig = fill_value
+
+    def _check_and_update_bounds_error_for_extrapolation(self):
+        if self.bounds_error:
+            raise ValueError("Cannot extrapolate and raise "
+                             "at the same time.")
+        self.bounds_error = False
+
+    def _call_linear_np(self, x_new):
+        # Note that out-of-bounds values are taken care of in self._evaluate
+        return np.interp(x_new, self.x, self.y)
+
+    def _call_linear(self, x_new):
+        # 2. Find where in the original data, the values to interpolate
+        #    would be inserted.
+        #    Note: If x_new[n] == x[m], then m is returned by searchsorted.
+        x_new_indices = searchsorted(self.x, x_new)
+
+        # 3. Clip x_new_indices so that they are within the range of
+        #    self.x indices and at least 1. Removes mis-interpolation
+        #    of x_new[n] = x[0]
+        x_new_indices = x_new_indices.clip(1, len(self.x)-1).astype(int)
+
+        # 4. Calculate the slope of regions that each x_new value falls in.
+        lo = x_new_indices - 1
+        hi = x_new_indices
+
+        x_lo = self.x[lo]
+        x_hi = self.x[hi]
+        y_lo = self._y[lo]
+        y_hi = self._y[hi]
+
+        # Note that the following two expressions rely on the specifics of the
+        # broadcasting semantics.
+        slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None]
+
+        # 5. Calculate the actual value for each entry in x_new.
+        y_new = slope*(x_new - x_lo)[:, None] + y_lo
+
+        return y_new
+
+    def _call_nearest(self, x_new):
+        """ Find nearest neighbor interpolated y_new = f(x_new)."""
+
+        # 2. Find where in the averaged data the values to interpolate
+        #    would be inserted.
+        #    Note: use side='left' (right) to searchsorted() to define the
+        #    halfway point to be nearest to the left (right) neighbor
+        x_new_indices = searchsorted(self.x_bds, x_new, side=self._side)
+
+        # 3. Clip x_new_indices so that they are within the range of x indices.
+        x_new_indices = x_new_indices.clip(0, len(self.x)-1).astype(intp)
+
+        # 4. Calculate the actual value for each entry in x_new.
+        y_new = self._y[x_new_indices]
+
+        return y_new
+
+    def _call_previousnext(self, x_new):
+        """Use previous/next neighbor of x_new, y_new = f(x_new)."""
+
+        # 1. Get index of left/right value
+        x_new_indices = searchsorted(self._x_shift, x_new, side=self._side)
+
+        # 2. Clip x_new_indices so that they are within the range of x indices.
+        x_new_indices = x_new_indices.clip(1-self._ind,
+                                           len(self.x)-self._ind).astype(intp)
+
+        # 3. Calculate the actual value for each entry in x_new.
+        y_new = self._y[x_new_indices+self._ind-1]
+
+        return y_new
+
+    def _call_spline(self, x_new):
+        return self._spline(x_new)
+
+    def _call_nan_spline(self, x_new):
+        out = self._spline(x_new)
+        out[...] = np.nan
+        return out
+
+    def _evaluate(self, x_new):
+        # 1. Handle values in x_new that are outside of x. Throw error,
+        #    or return a list of mask array indicating the outofbounds values.
+        #    The behavior is set by the bounds_error variable.
+        x_new = asarray(x_new)
+        y_new = self._call(self, x_new)
+        if not self._extrapolate:
+            below_bounds, above_bounds = self._check_bounds(x_new)
+            if len(y_new) > 0:
+                # Note fill_value must be broadcast up to the proper size
+                # and flattened to work here
+                y_new[below_bounds] = self._fill_value_below
+                y_new[above_bounds] = self._fill_value_above
+        return y_new
+
+    def _check_bounds(self, x_new):
+        """Check the inputs for being in the bounds of the interpolated data.
+
+        Parameters
+        ----------
+        x_new : array
+
+        Returns
+        -------
+        out_of_bounds : bool array
+            The mask on x_new of values that are out of the bounds.
+        """
+
+        # If self.bounds_error is True, we raise an error if any x_new values
+        # fall outside the range of x. Otherwise, we return an array indicating
+        # which values are outside the boundary region.
+        below_bounds = x_new < self.x[0]
+        above_bounds = x_new > self.x[-1]
+
+        if self.bounds_error and below_bounds.any():
+            below_bounds_value = x_new[np.argmax(below_bounds)]
+            raise ValueError(f"A value ({below_bounds_value}) in x_new is below "
+                             f"the interpolation range's minimum value ({self.x[0]}).")
+        if self.bounds_error and above_bounds.any():
+            above_bounds_value = x_new[np.argmax(above_bounds)]
+            raise ValueError(f"A value ({above_bounds_value}) in x_new is above "
+                             f"the interpolation range's maximum value ({self.x[-1]}).")
+
+        # !! Should we emit a warning if some values are out of bounds?
+        # !! matlab does not.
+        return below_bounds, above_bounds
+
+
+class _PPolyBase:
+    """Base class for piecewise polynomials."""
+    __slots__ = ('c', 'x', 'extrapolate', 'axis')
+
+    def __init__(self, c, x, extrapolate=None, axis=0):
+        self.c = np.asarray(c)
+        self.x = np.ascontiguousarray(x, dtype=np.float64)
+
+        if extrapolate is None:
+            extrapolate = True
+        elif extrapolate != 'periodic':
+            extrapolate = bool(extrapolate)
+        self.extrapolate = extrapolate
+
+        if self.c.ndim < 2:
+            raise ValueError("Coefficients array must be at least "
+                             "2-dimensional.")
+
+        if not (0 <= axis < self.c.ndim - 1):
+            raise ValueError(f"axis={axis} must be between 0 and {self.c.ndim-1}")
+
+        self.axis = axis
+        if axis != 0:
+            # move the interpolation axis to be the first one in self.c
+            # More specifically, the target shape for self.c is (k, m, ...),
+            # and axis !=0 means that we have c.shape (..., k, m, ...)
+            #                                               ^
+            #                                              axis
+            # So we roll two of them.
+            self.c = np.moveaxis(self.c, axis+1, 0)
+            self.c = np.moveaxis(self.c, axis+1, 0)
+
+        if self.x.ndim != 1:
+            raise ValueError("x must be 1-dimensional")
+        if self.x.size < 2:
+            raise ValueError("at least 2 breakpoints are needed")
+        if self.c.ndim < 2:
+            raise ValueError("c must have at least 2 dimensions")
+        if self.c.shape[0] == 0:
+            raise ValueError("polynomial must be at least of order 0")
+        if self.c.shape[1] != self.x.size-1:
+            raise ValueError("number of coefficients != len(x)-1")
+        dx = np.diff(self.x)
+        if not (np.all(dx >= 0) or np.all(dx <= 0)):
+            raise ValueError("`x` must be strictly increasing or decreasing.")
+
+        dtype = self._get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dtype)
+
+    def _get_dtype(self, dtype):
+        if np.issubdtype(dtype, np.complexfloating) \
+               or np.issubdtype(self.c.dtype, np.complexfloating):
+            return np.complex128
+        else:
+            return np.float64
+
+    @classmethod
+    def construct_fast(cls, c, x, extrapolate=None, axis=0):
+        """
+        Construct the piecewise polynomial without making checks.
+
+        Takes the same parameters as the constructor. Input arguments
+        ``c`` and ``x`` must be arrays of the correct shape and type. The
+        ``c`` array can only be of dtypes float and complex, and ``x``
+        array must have dtype float.
+        """
+        self = object.__new__(cls)
+        self.c = c
+        self.x = x
+        self.axis = axis
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = extrapolate
+        return self
+
+    def _ensure_c_contiguous(self):
+        """
+        c and x may be modified by the user. The Cython code expects
+        that they are C contiguous.
+        """
+        if not self.x.flags.c_contiguous:
+            self.x = self.x.copy()
+        if not self.c.flags.c_contiguous:
+            self.c = self.c.copy()
+
+    def extend(self, c, x):
+        """
+        Add additional breakpoints and coefficients to the polynomial.
+
+        Parameters
+        ----------
+        c : ndarray, size (k, m, ...)
+            Additional coefficients for polynomials in intervals. Note that
+            the first additional interval will be formed using one of the
+            ``self.x`` end points.
+        x : ndarray, size (m,)
+            Additional breakpoints. Must be sorted in the same order as
+            ``self.x`` and either to the right or to the left of the current
+            breakpoints.
+
+        Notes
+        -----
+        This method is not thread safe and must not be executed concurrently
+        with other methods available in this class. Doing so may cause
+        unexpected errors or numerical output mismatches.
+        """
+
+        c = np.asarray(c)
+        x = np.asarray(x)
+
+        if c.ndim < 2:
+            raise ValueError("invalid dimensions for c")
+        if x.ndim != 1:
+            raise ValueError("invalid dimensions for x")
+        if x.shape[0] != c.shape[1]:
+            raise ValueError(f"Shapes of x {x.shape} and c {c.shape} are incompatible")
+        if c.shape[2:] != self.c.shape[2:] or c.ndim != self.c.ndim:
+            raise ValueError(
+                f"Shapes of c {c.shape} and self.c {self.c.shape} are incompatible"
+            )
+
+        if c.size == 0:
+            return
+
+        dx = np.diff(x)
+        if not (np.all(dx >= 0) or np.all(dx <= 0)):
+            raise ValueError("`x` is not sorted.")
+
+        if self.x[-1] >= self.x[0]:
+            if not x[-1] >= x[0]:
+                raise ValueError("`x` is in the different order "
+                                "than `self.x`.")
+
+            if x[0] >= self.x[-1]:
+                action = 'append'
+            elif x[-1] <= self.x[0]:
+                action = 'prepend'
+            else:
+                raise ValueError("`x` is neither on the left or on the right "
+                                "from `self.x`.")
+        else:
+            if not x[-1] <= x[0]:
+                raise ValueError("`x` is in the different order "
+                                "than `self.x`.")
+
+            if x[0] <= self.x[-1]:
+                action = 'append'
+            elif x[-1] >= self.x[0]:
+                action = 'prepend'
+            else:
+                raise ValueError("`x` is neither on the left or on the right "
+                                "from `self.x`.")
+
+        dtype = self._get_dtype(c.dtype)
+
+        k2 = max(c.shape[0], self.c.shape[0])
+        c2 = np.zeros((k2, self.c.shape[1] + c.shape[1]) + self.c.shape[2:],
+                    dtype=dtype)
+
+        if action == 'append':
+            c2[k2-self.c.shape[0]:, :self.c.shape[1]] = self.c
+            c2[k2-c.shape[0]:, self.c.shape[1]:] = c
+            self.x = np.r_[self.x, x]
+        elif action == 'prepend':
+            c2[k2-self.c.shape[0]:, :c.shape[1]] = c
+            c2[k2-c.shape[0]:, c.shape[1]:] = self.c
+            self.x = np.r_[x, self.x]
+
+        self.c = c2
+
+    def __call__(self, x, nu=0, extrapolate=None):
+        """
+        Evaluate the piecewise polynomial or its derivative.
+
+        Parameters
+        ----------
+        x : array_like
+            Points to evaluate the interpolant at.
+        nu : int, optional
+            Order of derivative to evaluate. Must be non-negative.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of x.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        x = np.asarray(x)
+        x_shape, x_ndim = x.shape, x.ndim
+        x = np.ascontiguousarray(x.ravel(), dtype=np.float64)
+
+        # With periodic extrapolation we map x to the segment
+        # [self.x[0], self.x[-1]].
+        if extrapolate == 'periodic':
+            x = self.x[0] + (x - self.x[0]) % (self.x[-1] - self.x[0])
+            extrapolate = False
+
+        out = np.empty((len(x), prod(self.c.shape[2:])), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+        self._evaluate(x, nu, extrapolate, out)
+        out = out.reshape(x_shape + self.c.shape[2:])
+        if self.axis != 0:
+            # transpose to move the calculated values to the interpolation axis
+            l = list(range(out.ndim))
+            l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:]
+            out = out.transpose(l)
+        return out
+
+
+class PPoly(_PPolyBase):
+    """
+    Piecewise polynomial in terms of coefficients and breakpoints
+
+    The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the
+    local power basis::
+
+        S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1))
+
+    where ``k`` is the degree of the polynomial.
+
+    Parameters
+    ----------
+    c : ndarray, shape (k, m, ...)
+        Polynomial coefficients, order `k` and `m` intervals.
+    x : ndarray, shape (m+1,)
+        Polynomial breakpoints. Must be sorted in either increasing or
+        decreasing order.
+    extrapolate : bool or 'periodic', optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. Default is True.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+
+    Attributes
+    ----------
+    x : ndarray
+        Breakpoints.
+    c : ndarray
+        Coefficients of the polynomials. They are reshaped
+        to a 3-D array with the last dimension representing
+        the trailing dimensions of the original coefficient array.
+    axis : int
+        Interpolation axis.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    solve
+    roots
+    extend
+    from_spline
+    from_bernstein_basis
+    construct_fast
+
+    See also
+    --------
+    BPoly : piecewise polynomials in the Bernstein basis
+
+    Notes
+    -----
+    High-order polynomials in the power basis can be numerically
+    unstable. Precision problems can start to appear for orders
+    larger than 20-30.
+    """
+
+    def _evaluate(self, x, nu, extrapolate, out):
+        _ppoly.evaluate(self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                        self.x, x, nu, bool(extrapolate), out)
+
+    def derivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the derivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of derivative to evaluate. Default is 1, i.e., compute the
+            first derivative. If negative, the antiderivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k - n representing the derivative
+            of this polynomial.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+        """
+        if nu < 0:
+            return self.antiderivative(-nu)
+
+        # reduce order
+        if nu == 0:
+            c2 = self.c.copy()
+        else:
+            c2 = self.c[:-nu, :].copy()
+
+        if c2.shape[0] == 0:
+            # derivative of order 0 is zero
+            c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype)
+
+        # multiply by the correct rising factorials
+        factor = spec.poch(np.arange(c2.shape[0], 0, -1), nu)
+        c2 *= factor[(slice(None),) + (None,)*(c2.ndim-1)]
+
+        # construct a compatible polynomial
+        return self.construct_fast(c2, self.x, self.extrapolate, self.axis)
+
+    def antiderivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Antiderivative is also the indefinite integral of the function,
+        and derivative is its inverse operation.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of antiderivative to evaluate. Default is 1, i.e., compute
+            the first integral. If negative, the derivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k + n representing
+            the antiderivative of this polynomial.
+
+        Notes
+        -----
+        The antiderivative returned by this function is continuous and
+        continuously differentiable to order n-1, up to floating point
+        rounding error.
+
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+        """
+        if nu <= 0:
+            return self.derivative(-nu)
+
+        c = np.zeros((self.c.shape[0] + nu, self.c.shape[1]) + self.c.shape[2:],
+                     dtype=self.c.dtype)
+        c[:-nu] = self.c
+
+        # divide by the correct rising factorials
+        factor = spec.poch(np.arange(self.c.shape[0], 0, -1), nu)
+        c[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)]
+
+        # fix continuity of added degrees of freedom
+        self._ensure_c_contiguous()
+        _ppoly.fix_continuity(c.reshape(c.shape[0], c.shape[1], -1),
+                              self.x, nu - 1)
+
+        if self.extrapolate == 'periodic':
+            extrapolate = False
+        else:
+            extrapolate = self.extrapolate
+
+        # construct a compatible polynomial
+        return self.construct_fast(c, self.x, extrapolate, self.axis)
+
+    def integrate(self, a, b, extrapolate=None):
+        """
+        Compute a definite integral over a piecewise polynomial.
+
+        Parameters
+        ----------
+        a : float
+            Lower integration bound
+        b : float
+            Upper integration bound
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used.
+            If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        ig : array_like
+            Definite integral of the piecewise polynomial over [a, b]
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        # Swap integration bounds if needed
+        sign = 1
+        if b < a:
+            a, b = b, a
+            sign = -1
+
+        range_int = np.empty((prod(self.c.shape[2:]),), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+
+        # Compute the integral.
+        if extrapolate == 'periodic':
+            # Split the integral into the part over period (can be several
+            # of them) and the remaining part.
+
+            xs, xe = self.x[0], self.x[-1]
+            period = xe - xs
+            interval = b - a
+            n_periods, left = divmod(interval, period)
+
+            if n_periods > 0:
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, xs, xe, False, out=range_int)
+                range_int *= n_periods
+            else:
+                range_int.fill(0)
+
+            # Map a to [xs, xe], b is always a + left.
+            a = xs + (a - xs) % period
+            b = a + left
+
+            # If b <= xe then we need to integrate over [a, b], otherwise
+            # over [a, xe] and from xs to what is remained.
+            remainder_int = np.empty_like(range_int)
+            if b <= xe:
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, a, b, False, out=remainder_int)
+                range_int += remainder_int
+            else:
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, a, xe, False, out=remainder_int)
+                range_int += remainder_int
+
+                _ppoly.integrate(
+                    self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                    self.x, xs, xs + left + a - xe, False, out=remainder_int)
+                range_int += remainder_int
+        else:
+            _ppoly.integrate(
+                self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                self.x, a, b, bool(extrapolate), out=range_int)
+
+        # Return
+        range_int *= sign
+        return range_int.reshape(self.c.shape[2:])
+
+    def solve(self, y=0., discontinuity=True, extrapolate=None):
+        """
+        Find real solutions of the equation ``pp(x) == y``.
+
+        Parameters
+        ----------
+        y : float, optional
+            Right-hand side. Default is zero.
+        discontinuity : bool, optional
+            Whether to report sign changes across discontinuities at
+            breakpoints as roots.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to return roots from the polynomial
+            extrapolated based on first and last intervals, 'periodic' works
+            the same as False. If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        roots : ndarray
+            Roots of the polynomial(s).
+
+            If the PPoly object describes multiple polynomials, the
+            return value is an object array whose each element is an
+            ndarray containing the roots.
+
+        Notes
+        -----
+        This routine works only on real-valued polynomials.
+
+        If the piecewise polynomial contains sections that are
+        identically zero, the root list will contain the start point
+        of the corresponding interval, followed by a ``nan`` value.
+
+        If the polynomial is discontinuous across a breakpoint, and
+        there is a sign change across the breakpoint, this is reported
+        if the `discont` parameter is True.
+
+        Examples
+        --------
+
+        Finding roots of ``[x**2 - 1, (x - 1)**2]`` defined on intervals
+        ``[-2, 1], [1, 2]``:
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import PPoly
+        >>> pp = PPoly(np.array([[1, -4, 3], [1, 0, 0]]).T, [-2, 1, 2])
+        >>> pp.solve()
+        array([-1.,  1.])
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        self._ensure_c_contiguous()
+
+        if np.issubdtype(self.c.dtype, np.complexfloating):
+            raise ValueError("Root finding is only for "
+                             "real-valued polynomials")
+
+        y = float(y)
+        r = _ppoly.real_roots(self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+                              self.x, y, bool(discontinuity),
+                              bool(extrapolate))
+        if self.c.ndim == 2:
+            return r[0]
+        else:
+            r2 = np.empty(prod(self.c.shape[2:]), dtype=object)
+            # this for-loop is equivalent to ``r2[...] = r``, but that's broken
+            # in NumPy 1.6.0
+            for ii, root in enumerate(r):
+                r2[ii] = root
+
+            return r2.reshape(self.c.shape[2:])
+
+    def roots(self, discontinuity=True, extrapolate=None):
+        """
+        Find real roots of the piecewise polynomial.
+
+        Parameters
+        ----------
+        discontinuity : bool, optional
+            Whether to report sign changes across discontinuities at
+            breakpoints as roots.
+        extrapolate : {bool, 'periodic', None}, optional
+            If bool, determines whether to return roots from the polynomial
+            extrapolated based on first and last intervals, 'periodic' works
+            the same as False. If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        roots : ndarray
+            Roots of the polynomial(s).
+
+            If the PPoly object describes multiple polynomials, the
+            return value is an object array whose each element is an
+            ndarray containing the roots.
+
+        See Also
+        --------
+        PPoly.solve
+        """
+        return self.solve(0, discontinuity, extrapolate)
+
+    @classmethod
+    def from_spline(cls, tck, extrapolate=None):
+        """
+        Construct a piecewise polynomial from a spline
+
+        Parameters
+        ----------
+        tck
+            A spline, as returned by `splrep` or a BSpline object.
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+
+        Examples
+        --------
+        Construct an interpolating spline and convert it to a `PPoly` instance
+
+        >>> import numpy as np
+        >>> from scipy.interpolate import splrep, PPoly
+        >>> x = np.linspace(0, 1, 11)
+        >>> y = np.sin(2*np.pi*x)
+        >>> tck = splrep(x, y, s=0)
+        >>> p = PPoly.from_spline(tck)
+        >>> isinstance(p, PPoly)
+        True
+
+        Note that this function only supports 1D splines out of the box.
+
+        If the ``tck`` object represents a parametric spline (e.g. constructed
+        by `splprep` or a `BSpline` with ``c.ndim > 1``), you will need to loop
+        over the dimensions manually.
+
+        >>> from scipy.interpolate import splprep, splev
+        >>> t = np.linspace(0, 1, 11)
+        >>> x = np.sin(2*np.pi*t)
+        >>> y = np.cos(2*np.pi*t)
+        >>> (t, c, k), u = splprep([x, y], s=0)
+
+        Note that ``c`` is a list of two arrays of length 11.
+
+        >>> unew = np.arange(0, 1.01, 0.01)
+        >>> out = splev(unew, (t, c, k))
+
+        To convert this spline to the power basis, we convert each
+        component of the list of b-spline coefficients, ``c``, into the
+        corresponding cubic polynomial.
+
+        >>> polys = [PPoly.from_spline((t, cj, k)) for cj in c]
+        >>> polys[0].c.shape
+        (4, 14)
+
+        Note that the coefficients of the polynomials `polys` are in the
+        power basis and their dimensions reflect just that: here 4 is the order
+        (degree+1), and 14 is the number of intervals---which is nothing but
+        the length of the knot array of the original `tck` minus one.
+
+        Optionally, we can stack the components into a single `PPoly` along
+        the third dimension:
+
+        >>> cc = np.dstack([p.c for p in polys])    # has shape = (4, 14, 2)
+        >>> poly = PPoly(cc, polys[0].x)
+        >>> np.allclose(poly(unew).T,     # note the transpose to match `splev`
+        ...             out, atol=1e-15)
+        True
+
+        """
+        if isinstance(tck, BSpline):
+            t, c, k = tck.tck
+            if extrapolate is None:
+                extrapolate = tck.extrapolate
+        else:
+            t, c, k = tck
+
+        cvals = np.empty((k + 1, len(t)-1), dtype=c.dtype)
+        for m in range(k, -1, -1):
+            y = _fitpack_py.splev(t[:-1], tck, der=m)
+            cvals[k - m, :] = y/spec.gamma(m+1)
+
+        return cls.construct_fast(cvals, t, extrapolate)
+
+    @classmethod
+    def from_bernstein_basis(cls, bp, extrapolate=None):
+        """
+        Construct a piecewise polynomial in the power basis
+        from a polynomial in Bernstein basis.
+
+        Parameters
+        ----------
+        bp : BPoly
+            A Bernstein basis polynomial, as created by BPoly
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+        """
+        if not isinstance(bp, BPoly):
+            raise TypeError(f".from_bernstein_basis only accepts BPoly instances. "
+                            f"Got {type(bp)} instead.")
+
+        dx = np.diff(bp.x)
+        k = bp.c.shape[0] - 1  # polynomial order
+
+        rest = (None,)*(bp.c.ndim-2)
+
+        c = np.zeros_like(bp.c)
+        for a in range(k+1):
+            factor = (-1)**a * comb(k, a) * bp.c[a]
+            for s in range(a, k+1):
+                val = comb(k-a, s-a) * (-1)**s
+                c[k-s] += factor * val / dx[(slice(None),)+rest]**s
+
+        if extrapolate is None:
+            extrapolate = bp.extrapolate
+
+        return cls.construct_fast(c, bp.x, extrapolate, bp.axis)
+
+
+class BPoly(_PPolyBase):
+    """Piecewise polynomial in terms of coefficients and breakpoints.
+
+    The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the
+    Bernstein polynomial basis::
+
+        S = sum(c[a, i] * b(a, k; x) for a in range(k+1)),
+
+    where ``k`` is the degree of the polynomial, and::
+
+        b(a, k; x) = binom(k, a) * t**a * (1 - t)**(k - a),
+
+    with ``t = (x - x[i]) / (x[i+1] - x[i])`` and ``binom`` is the binomial
+    coefficient.
+
+    Parameters
+    ----------
+    c : ndarray, shape (k, m, ...)
+        Polynomial coefficients, order `k` and `m` intervals
+    x : ndarray, shape (m+1,)
+        Polynomial breakpoints. Must be sorted in either increasing or
+        decreasing order.
+    extrapolate : bool, optional
+        If bool, determines whether to extrapolate to out-of-bounds points
+        based on first and last intervals, or to return NaNs. If 'periodic',
+        periodic extrapolation is used. Default is True.
+    axis : int, optional
+        Interpolation axis. Default is zero.
+
+    Attributes
+    ----------
+    x : ndarray
+        Breakpoints.
+    c : ndarray
+        Coefficients of the polynomials. They are reshaped
+        to a 3-D array with the last dimension representing
+        the trailing dimensions of the original coefficient array.
+    axis : int
+        Interpolation axis.
+
+    Methods
+    -------
+    __call__
+    extend
+    derivative
+    antiderivative
+    integrate
+    construct_fast
+    from_power_basis
+    from_derivatives
+
+    See also
+    --------
+    PPoly : piecewise polynomials in the power basis
+
+    Notes
+    -----
+    Properties of Bernstein polynomials are well documented in the literature,
+    see for example [1]_ [2]_ [3]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Bernstein_polynomial
+
+    .. [2] Kenneth I. Joy, Bernstein polynomials,
+       http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf
+
+    .. [3] E. H. Doha, A. H. Bhrawy, and M. A. Saker, Boundary Value Problems,
+           vol 2011, article ID 829546, :doi:`10.1155/2011/829543`.
+
+    Examples
+    --------
+    >>> from scipy.interpolate import BPoly
+    >>> x = [0, 1]
+    >>> c = [[1], [2], [3]]
+    >>> bp = BPoly(c, x)
+
+    This creates a 2nd order polynomial
+
+    .. math::
+
+        B(x) = 1 \\times b_{0, 2}(x) + 2 \\times b_{1, 2}(x) + 3
+               \\times b_{2, 2}(x) \\\\
+             = 1 \\times (1-x)^2 + 2 \\times 2 x (1 - x) + 3 \\times x^2
+
+    """  # noqa: E501
+
+    def _evaluate(self, x, nu, extrapolate, out):
+        _ppoly.evaluate_bernstein(
+            self.c.reshape(self.c.shape[0], self.c.shape[1], -1),
+            self.x, x, nu, bool(extrapolate), out)
+
+    def derivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the derivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of derivative to evaluate. Default is 1, i.e., compute the
+            first derivative. If negative, the antiderivative is returned.
+
+        Returns
+        -------
+        bp : BPoly
+            Piecewise polynomial of order k - nu representing the derivative of
+            this polynomial.
+
+        """
+        if nu < 0:
+            return self.antiderivative(-nu)
+
+        if nu > 1:
+            bp = self
+            for k in range(nu):
+                bp = bp.derivative()
+            return bp
+
+        # reduce order
+        if nu == 0:
+            c2 = self.c.copy()
+        else:
+            # For a polynomial
+            #    B(x) = \sum_{a=0}^{k} c_a b_{a, k}(x),
+            # we use the fact that
+            #   b'_{a, k} = k ( b_{a-1, k-1} - b_{a, k-1} ),
+            # which leads to
+            #   B'(x) = \sum_{a=0}^{k-1} (c_{a+1} - c_a) b_{a, k-1}
+            #
+            # finally, for an interval [y, y + dy] with dy != 1,
+            # we need to correct for an extra power of dy
+
+            rest = (None,)*(self.c.ndim-2)
+
+            k = self.c.shape[0] - 1
+            dx = np.diff(self.x)[(None, slice(None))+rest]
+            c2 = k * np.diff(self.c, axis=0) / dx
+
+        if c2.shape[0] == 0:
+            # derivative of order 0 is zero
+            c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype)
+
+        # construct a compatible polynomial
+        return self.construct_fast(c2, self.x, self.extrapolate, self.axis)
+
+    def antiderivative(self, nu=1):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Parameters
+        ----------
+        nu : int, optional
+            Order of antiderivative to evaluate. Default is 1, i.e., compute
+            the first integral. If negative, the derivative is returned.
+
+        Returns
+        -------
+        bp : BPoly
+            Piecewise polynomial of order k + nu representing the
+            antiderivative of this polynomial.
+
+        Notes
+        -----
+        If antiderivative is computed and ``self.extrapolate='periodic'``,
+        it will be set to False for the returned instance. This is done because
+        the antiderivative is no longer periodic and its correct evaluation
+        outside of the initially given x interval is difficult.
+        """
+        if nu <= 0:
+            return self.derivative(-nu)
+
+        if nu > 1:
+            bp = self
+            for k in range(nu):
+                bp = bp.antiderivative()
+            return bp
+
+        # Construct the indefinite integrals on individual intervals
+        c, x = self.c, self.x
+        k = c.shape[0]
+        c2 = np.zeros((k+1,) + c.shape[1:], dtype=c.dtype)
+
+        c2[1:, ...] = np.cumsum(c, axis=0) / k
+        delta = x[1:] - x[:-1]
+        c2 *= delta[(None, slice(None)) + (None,)*(c.ndim-2)]
+
+        # Now fix continuity: on the very first interval, take the integration
+        # constant to be zero; on an interval [x_j, x_{j+1}) with j>0,
+        # the integration constant is then equal to the jump of the `bp` at x_j.
+        # The latter is given by the coefficient of B_{n+1, n+1}
+        # *on the previous interval* (other B. polynomials are zero at the
+        # breakpoint). Finally, use the fact that BPs form a partition of unity.
+        c2[:,1:] += np.cumsum(c2[k, :], axis=0)[:-1]
+
+        if self.extrapolate == 'periodic':
+            extrapolate = False
+        else:
+            extrapolate = self.extrapolate
+
+        return self.construct_fast(c2, x, extrapolate, axis=self.axis)
+
+    def integrate(self, a, b, extrapolate=None):
+        """
+        Compute a definite integral over a piecewise polynomial.
+
+        Parameters
+        ----------
+        a : float
+            Lower integration bound
+        b : float
+            Upper integration bound
+        extrapolate : {bool, 'periodic', None}, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs. If 'periodic', periodic
+            extrapolation is used. If None (default), use `self.extrapolate`.
+
+        Returns
+        -------
+        array_like
+            Definite integral of the piecewise polynomial over [a, b]
+
+        """
+        # XXX: can probably use instead the fact that
+        # \int_0^{1} B_{j, n}(x) \dx = 1/(n+1)
+        ib = self.antiderivative()
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+
+        # ib.extrapolate shouldn't be 'periodic', it is converted to
+        # False for 'periodic. in antiderivative() call.
+        if extrapolate != 'periodic':
+            ib.extrapolate = extrapolate
+
+        if extrapolate == 'periodic':
+            # Split the integral into the part over period (can be several
+            # of them) and the remaining part.
+
+            # For simplicity and clarity convert to a <= b case.
+            if a <= b:
+                sign = 1
+            else:
+                a, b = b, a
+                sign = -1
+
+            xs, xe = self.x[0], self.x[-1]
+            period = xe - xs
+            interval = b - a
+            n_periods, left = divmod(interval, period)
+            res = n_periods * (ib(xe) - ib(xs))
+
+            # Map a and b to [xs, xe].
+            a = xs + (a - xs) % period
+            b = a + left
+
+            # If b <= xe then we need to integrate over [a, b], otherwise
+            # over [a, xe] and from xs to what is remained.
+            if b <= xe:
+                res += ib(b) - ib(a)
+            else:
+                res += ib(xe) - ib(a) + ib(xs + left + a - xe) - ib(xs)
+
+            return sign * res
+        else:
+            return ib(b) - ib(a)
+
+    def extend(self, c, x):
+        k = max(self.c.shape[0], c.shape[0])
+        self.c = self._raise_degree(self.c, k - self.c.shape[0])
+        c = self._raise_degree(c, k - c.shape[0])
+        return _PPolyBase.extend(self, c, x)
+    extend.__doc__ = _PPolyBase.extend.__doc__
+
+    @classmethod
+    def from_power_basis(cls, pp, extrapolate=None):
+        """
+        Construct a piecewise polynomial in Bernstein basis
+        from a power basis polynomial.
+
+        Parameters
+        ----------
+        pp : PPoly
+            A piecewise polynomial in the power basis
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+        """
+        if not isinstance(pp, PPoly):
+            raise TypeError(f".from_power_basis only accepts PPoly instances. "
+                            f"Got {type(pp)} instead.")
+
+        dx = np.diff(pp.x)
+        k = pp.c.shape[0] - 1   # polynomial order
+
+        rest = (None,)*(pp.c.ndim-2)
+
+        c = np.zeros_like(pp.c)
+        for a in range(k+1):
+            factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),)+rest]**(k-a)
+            for j in range(k-a, k+1):
+                c[j] += factor * comb(j, k-a)
+
+        if extrapolate is None:
+            extrapolate = pp.extrapolate
+
+        return cls.construct_fast(c, pp.x, extrapolate, pp.axis)
+
+    @classmethod
+    def from_derivatives(cls, xi, yi, orders=None, extrapolate=None):
+        """Construct a piecewise polynomial in the Bernstein basis,
+        compatible with the specified values and derivatives at breakpoints.
+
+        Parameters
+        ----------
+        xi : array_like
+            sorted 1-D array of x-coordinates
+        yi : array_like or list of array_likes
+            ``yi[i][j]`` is the ``j``\\ th derivative known at ``xi[i]``
+        orders : None or int or array_like of ints. Default: None.
+            Specifies the degree of local polynomials. If not None, some
+            derivatives are ignored.
+        extrapolate : bool or 'periodic', optional
+            If bool, determines whether to extrapolate to out-of-bounds points
+            based on first and last intervals, or to return NaNs.
+            If 'periodic', periodic extrapolation is used. Default is True.
+
+        Notes
+        -----
+        If ``k`` derivatives are specified at a breakpoint ``x``, the
+        constructed polynomial is exactly ``k`` times continuously
+        differentiable at ``x``, unless the ``order`` is provided explicitly.
+        In the latter case, the smoothness of the polynomial at
+        the breakpoint is controlled by the ``order``.
+
+        Deduces the number of derivatives to match at each end
+        from ``order`` and the number of derivatives available. If
+        possible it uses the same number of derivatives from
+        each end; if the number is odd it tries to take the
+        extra one from y2. In any case if not enough derivatives
+        are available at one end or another it draws enough to
+        make up the total from the other end.
+
+        If the order is too high and not enough derivatives are available,
+        an exception is raised.
+
+        Examples
+        --------
+
+        >>> from scipy.interpolate import BPoly
+        >>> BPoly.from_derivatives([0, 1], [[1, 2], [3, 4]])
+
+        Creates a polynomial `f(x)` of degree 3, defined on ``[0, 1]``
+        such that `f(0) = 1, df/dx(0) = 2, f(1) = 3, df/dx(1) = 4`
+
+        >>> BPoly.from_derivatives([0, 1, 2], [[0, 1], [0], [2]])
+
+        Creates a piecewise polynomial `f(x)`, such that
+        `f(0) = f(1) = 0`, `f(2) = 2`, and `df/dx(0) = 1`.
+        Based on the number of derivatives provided, the order of the
+        local polynomials is 2 on ``[0, 1]`` and 1 on ``[1, 2]``.
+        Notice that no restriction is imposed on the derivatives at
+        ``x = 1`` and ``x = 2``.
+
+        Indeed, the explicit form of the polynomial is::
+
+            f(x) = | x * (1 - x),  0 <= x < 1
+                   | 2 * (x - 1),  1 <= x <= 2
+
+        So that f'(1-0) = -1 and f'(1+0) = 2
+
+        """
+        xi = np.asarray(xi)
+        if len(xi) != len(yi):
+            raise ValueError("xi and yi need to have the same length")
+        if np.any(xi[1:] - xi[:1] <= 0):
+            raise ValueError("x coordinates are not in increasing order")
+
+        # number of intervals
+        m = len(xi) - 1
+
+        # global poly order is k-1, local orders are <=k and can vary
+        try:
+            k = max(len(yi[i]) + len(yi[i+1]) for i in range(m))
+        except TypeError as e:
+            raise ValueError(
+                "Using a 1-D array for y? Please .reshape(-1, 1)."
+            ) from e
+
+        if orders is None:
+            orders = [None] * m
+        else:
+            if isinstance(orders, (int, np.integer)):
+                orders = [orders] * m
+            k = max(k, max(orders))
+
+            if any(o <= 0 for o in orders):
+                raise ValueError("Orders must be positive.")
+
+        c = []
+        for i in range(m):
+            y1, y2 = yi[i], yi[i+1]
+            if orders[i] is None:
+                n1, n2 = len(y1), len(y2)
+            else:
+                n = orders[i]+1
+                n1 = min(n//2, len(y1))
+                n2 = min(n - n1, len(y2))
+                n1 = min(n - n2, len(y2))
+                if n1+n2 != n:
+                    mesg = ("Point %g has %d derivatives, point %g"
+                            " has %d derivatives, but order %d requested" % (
+                               xi[i], len(y1), xi[i+1], len(y2), orders[i]))
+                    raise ValueError(mesg)
+
+                if not (n1 <= len(y1) and n2 <= len(y2)):
+                    raise ValueError("`order` input incompatible with"
+                                     " length y1 or y2.")
+
+            b = BPoly._construct_from_derivatives(xi[i], xi[i+1],
+                                                  y1[:n1], y2[:n2])
+            if len(b) < k:
+                b = BPoly._raise_degree(b, k - len(b))
+            c.append(b)
+
+        c = np.asarray(c)
+        return cls(c.swapaxes(0, 1), xi, extrapolate)
+
+    @staticmethod
+    def _construct_from_derivatives(xa, xb, ya, yb):
+        r"""Compute the coefficients of a polynomial in the Bernstein basis
+        given the values and derivatives at the edges.
+
+        Return the coefficients of a polynomial in the Bernstein basis
+        defined on ``[xa, xb]`` and having the values and derivatives at the
+        endpoints `xa` and `xb` as specified by `ya` and `yb`.
+        The polynomial constructed is of the minimal possible degree, i.e.,
+        if the lengths of `ya` and `yb` are `na` and `nb`, the degree
+        of the polynomial is ``na + nb - 1``.
+
+        Parameters
+        ----------
+        xa : float
+            Left-hand end point of the interval
+        xb : float
+            Right-hand end point of the interval
+        ya : array_like
+            Derivatives at `xa`. ``ya[0]`` is the value of the function, and
+            ``ya[i]`` for ``i > 0`` is the value of the ``i``\ th derivative.
+        yb : array_like
+            Derivatives at `xb`.
+
+        Returns
+        -------
+        array
+            coefficient array of a polynomial having specified derivatives
+
+        Notes
+        -----
+        This uses several facts from life of Bernstein basis functions.
+        First of all,
+
+            .. math:: b'_{a, n} = n (b_{a-1, n-1} - b_{a, n-1})
+
+        If B(x) is a linear combination of the form
+
+            .. math:: B(x) = \sum_{a=0}^{n} c_a b_{a, n},
+
+        then :math: B'(x) = n \sum_{a=0}^{n-1} (c_{a+1} - c_{a}) b_{a, n-1}.
+        Iterating the latter one, one finds for the q-th derivative
+
+            .. math:: B^{q}(x) = n!/(n-q)! \sum_{a=0}^{n-q} Q_a b_{a, n-q},
+
+        with
+
+          .. math:: Q_a = \sum_{j=0}^{q} (-)^{j+q} comb(q, j) c_{j+a}
+
+        This way, only `a=0` contributes to :math: `B^{q}(x = xa)`, and
+        `c_q` are found one by one by iterating `q = 0, ..., na`.
+
+        At ``x = xb`` it's the same with ``a = n - q``.
+
+        """
+        ya, yb = np.asarray(ya), np.asarray(yb)
+        if ya.shape[1:] != yb.shape[1:]:
+            raise ValueError(
+                f"Shapes of ya {ya.shape} and yb {yb.shape} are incompatible"
+            )
+
+        dta, dtb = ya.dtype, yb.dtype
+        if (np.issubdtype(dta, np.complexfloating) or
+               np.issubdtype(dtb, np.complexfloating)):
+            dt = np.complex128
+        else:
+            dt = np.float64
+
+        na, nb = len(ya), len(yb)
+        n = na + nb
+
+        c = np.empty((na+nb,) + ya.shape[1:], dtype=dt)
+
+        # compute coefficients of a polynomial degree na+nb-1
+        # walk left-to-right
+        for q in range(0, na):
+            c[q] = ya[q] / spec.poch(n - q, q) * (xb - xa)**q
+            for j in range(0, q):
+                c[q] -= (-1)**(j+q) * comb(q, j) * c[j]
+
+        # now walk right-to-left
+        for q in range(0, nb):
+            c[-q-1] = yb[q] / spec.poch(n - q, q) * (-1)**q * (xb - xa)**q
+            for j in range(0, q):
+                c[-q-1] -= (-1)**(j+1) * comb(q, j+1) * c[-q+j]
+
+        return c
+
+    @staticmethod
+    def _raise_degree(c, d):
+        r"""Raise a degree of a polynomial in the Bernstein basis.
+
+        Given the coefficients of a polynomial degree `k`, return (the
+        coefficients of) the equivalent polynomial of degree `k+d`.
+
+        Parameters
+        ----------
+        c : array_like
+            coefficient array, 1-D
+        d : integer
+
+        Returns
+        -------
+        array
+            coefficient array, 1-D array of length `c.shape[0] + d`
+
+        Notes
+        -----
+        This uses the fact that a Bernstein polynomial `b_{a, k}` can be
+        identically represented as a linear combination of polynomials of
+        a higher degree `k+d`:
+
+            .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \
+                                 comb(d, j) / comb(k+d, a+j)
+
+        """
+        if d == 0:
+            return c
+
+        k = c.shape[0] - 1
+        out = np.zeros((c.shape[0] + d,) + c.shape[1:], dtype=c.dtype)
+
+        for a in range(c.shape[0]):
+            f = c[a] * comb(k, a)
+            for j in range(d+1):
+                out[a+j] += f * comb(d, j) / comb(k+d, a+j)
+        return out
+
+
+class NdPPoly:
+    """
+    Piecewise tensor product polynomial
+
+    The value at point ``xp = (x', y', z', ...)`` is evaluated by first
+    computing the interval indices `i` such that::
+
+        x[0][i[0]] <= x' < x[0][i[0]+1]
+        x[1][i[1]] <= y' < x[1][i[1]+1]
+        ...
+
+    and then computing::
+
+        S = sum(c[k0-m0-1,...,kn-mn-1,i[0],...,i[n]]
+                * (xp[0] - x[0][i[0]])**m0
+                * ...
+                * (xp[n] - x[n][i[n]])**mn
+                for m0 in range(k[0]+1)
+                ...
+                for mn in range(k[n]+1))
+
+    where ``k[j]`` is the degree of the polynomial in dimension j. This
+    representation is the piecewise multivariate power basis.
+
+    Parameters
+    ----------
+    c : ndarray, shape (k0, ..., kn, m0, ..., mn, ...)
+        Polynomial coefficients, with polynomial order `kj` and
+        `mj+1` intervals for each dimension `j`.
+    x : ndim-tuple of ndarrays, shapes (mj+1,)
+        Polynomial breakpoints for each dimension. These must be
+        sorted in increasing order.
+    extrapolate : bool, optional
+        Whether to extrapolate to out-of-bounds points based on first
+        and last intervals, or to return NaNs. Default: True.
+
+    Attributes
+    ----------
+    x : tuple of ndarrays
+        Breakpoints.
+    c : ndarray
+        Coefficients of the polynomials.
+
+    Methods
+    -------
+    __call__
+    derivative
+    antiderivative
+    integrate
+    integrate_1d
+    construct_fast
+
+    See also
+    --------
+    PPoly : piecewise polynomials in 1D
+
+    Notes
+    -----
+    High-order polynomials in the power basis can be numerically
+    unstable.
+
+    """
+
+    def __init__(self, c, x, extrapolate=None):
+        self.x = tuple(np.ascontiguousarray(v, dtype=np.float64) for v in x)
+        self.c = np.asarray(c)
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = bool(extrapolate)
+
+        ndim = len(self.x)
+        if any(v.ndim != 1 for v in self.x):
+            raise ValueError("x arrays must all be 1-dimensional")
+        if any(v.size < 2 for v in self.x):
+            raise ValueError("x arrays must all contain at least 2 points")
+        if c.ndim < 2*ndim:
+            raise ValueError("c must have at least 2*len(x) dimensions")
+        if any(np.any(v[1:] - v[:-1] < 0) for v in self.x):
+            raise ValueError("x-coordinates are not in increasing order")
+        if any(a != b.size - 1 for a, b in zip(c.shape[ndim:2*ndim], self.x)):
+            raise ValueError("x and c do not agree on the number of intervals")
+
+        dtype = self._get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dtype)
+
+    @classmethod
+    def construct_fast(cls, c, x, extrapolate=None):
+        """
+        Construct the piecewise polynomial without making checks.
+
+        Takes the same parameters as the constructor. Input arguments
+        ``c`` and ``x`` must be arrays of the correct shape and type.  The
+        ``c`` array can only be of dtypes float and complex, and ``x``
+        array must have dtype float.
+
+        """
+        self = object.__new__(cls)
+        self.c = c
+        self.x = x
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = extrapolate
+        return self
+
+    def _get_dtype(self, dtype):
+        if np.issubdtype(dtype, np.complexfloating) \
+               or np.issubdtype(self.c.dtype, np.complexfloating):
+            return np.complex128
+        else:
+            return np.float64
+
+    def _ensure_c_contiguous(self):
+        if not self.c.flags.c_contiguous:
+            self.c = self.c.copy()
+        if not isinstance(self.x, tuple):
+            self.x = tuple(self.x)
+
+    def __call__(self, x, nu=None, extrapolate=None):
+        """
+        Evaluate the piecewise polynomial or its derivative
+
+        Parameters
+        ----------
+        x : array-like
+            Points to evaluate the interpolant at.
+        nu : tuple, optional
+            Orders of derivatives to evaluate. Each must be non-negative.
+        extrapolate : bool, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs.
+
+        Returns
+        -------
+        y : array-like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of x.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals are considered half-open,
+        ``[a, b)``, except for the last interval which is closed
+        ``[a, b]``.
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        else:
+            extrapolate = bool(extrapolate)
+
+        ndim = len(self.x)
+
+        x = _ndim_coords_from_arrays(x)
+        x_shape = x.shape
+        x = np.ascontiguousarray(x.reshape(-1, x.shape[-1]), dtype=np.float64)
+
+        if nu is None:
+            nu = np.zeros((ndim,), dtype=np.intc)
+        else:
+            nu = np.asarray(nu, dtype=np.intc)
+            if nu.ndim != 1 or nu.shape[0] != ndim:
+                raise ValueError("invalid number of derivative orders nu")
+
+        dim1 = prod(self.c.shape[:ndim])
+        dim2 = prod(self.c.shape[ndim:2*ndim])
+        dim3 = prod(self.c.shape[2*ndim:])
+        ks = np.array(self.c.shape[:ndim], dtype=np.intc)
+
+        out = np.empty((x.shape[0], dim3), dtype=self.c.dtype)
+        self._ensure_c_contiguous()
+
+        _ppoly.evaluate_nd(self.c.reshape(dim1, dim2, dim3),
+                           self.x,
+                           ks,
+                           x,
+                           nu,
+                           bool(extrapolate),
+                           out)
+
+        return out.reshape(x_shape[:-1] + self.c.shape[2*ndim:])
+
+    def _derivative_inplace(self, nu, axis):
+        """
+        Compute 1-D derivative along a selected dimension in-place
+        May result to non-contiguous c array.
+        """
+        if nu < 0:
+            return self._antiderivative_inplace(-nu, axis)
+
+        ndim = len(self.x)
+        axis = axis % ndim
+
+        # reduce order
+        if nu == 0:
+            # noop
+            return
+        else:
+            sl = [slice(None)]*ndim
+            sl[axis] = slice(None, -nu, None)
+            c2 = self.c[tuple(sl)]
+
+        if c2.shape[axis] == 0:
+            # derivative of order 0 is zero
+            shp = list(c2.shape)
+            shp[axis] = 1
+            c2 = np.zeros(shp, dtype=c2.dtype)
+
+        # multiply by the correct rising factorials
+        factor = spec.poch(np.arange(c2.shape[axis], 0, -1), nu)
+        sl = [None]*c2.ndim
+        sl[axis] = slice(None)
+        c2 *= factor[tuple(sl)]
+
+        self.c = c2
+
+    def _antiderivative_inplace(self, nu, axis):
+        """
+        Compute 1-D antiderivative along a selected dimension
+        May result to non-contiguous c array.
+        """
+        if nu <= 0:
+            return self._derivative_inplace(-nu, axis)
+
+        ndim = len(self.x)
+        axis = axis % ndim
+
+        perm = list(range(ndim))
+        perm[0], perm[axis] = perm[axis], perm[0]
+        perm = perm + list(range(ndim, self.c.ndim))
+
+        c = self.c.transpose(perm)
+
+        c2 = np.zeros((c.shape[0] + nu,) + c.shape[1:],
+                     dtype=c.dtype)
+        c2[:-nu] = c
+
+        # divide by the correct rising factorials
+        factor = spec.poch(np.arange(c.shape[0], 0, -1), nu)
+        c2[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)]
+
+        # fix continuity of added degrees of freedom
+        perm2 = list(range(c2.ndim))
+        perm2[1], perm2[ndim+axis] = perm2[ndim+axis], perm2[1]
+
+        c2 = c2.transpose(perm2)
+        c2 = c2.copy()
+        _ppoly.fix_continuity(c2.reshape(c2.shape[0], c2.shape[1], -1),
+                              self.x[axis], nu-1)
+
+        c2 = c2.transpose(perm2)
+        c2 = c2.transpose(perm)
+
+        # Done
+        self.c = c2
+
+    def derivative(self, nu):
+        """
+        Construct a new piecewise polynomial representing the derivative.
+
+        Parameters
+        ----------
+        nu : ndim-tuple of int
+            Order of derivatives to evaluate for each dimension.
+            If negative, the antiderivative is returned.
+
+        Returns
+        -------
+        pp : NdPPoly
+            Piecewise polynomial of orders (k[0] - nu[0], ..., k[n] - nu[n])
+            representing the derivative of this polynomial.
+
+        Notes
+        -----
+        Derivatives are evaluated piecewise for each polynomial
+        segment, even if the polynomial is not differentiable at the
+        breakpoints. The polynomial intervals in each dimension are
+        considered half-open, ``[a, b)``, except for the last interval
+        which is closed ``[a, b]``.
+
+        """
+        p = self.construct_fast(self.c.copy(), self.x, self.extrapolate)
+
+        for axis, n in enumerate(nu):
+            p._derivative_inplace(n, axis)
+
+        p._ensure_c_contiguous()
+        return p
+
+    def antiderivative(self, nu):
+        """
+        Construct a new piecewise polynomial representing the antiderivative.
+
+        Antiderivative is also the indefinite integral of the function,
+        and derivative is its inverse operation.
+
+        Parameters
+        ----------
+        nu : ndim-tuple of int
+            Order of derivatives to evaluate for each dimension.
+            If negative, the derivative is returned.
+
+        Returns
+        -------
+        pp : PPoly
+            Piecewise polynomial of order k2 = k + n representing
+            the antiderivative of this polynomial.
+
+        Notes
+        -----
+        The antiderivative returned by this function is continuous and
+        continuously differentiable to order n-1, up to floating point
+        rounding error.
+
+        """
+        p = self.construct_fast(self.c.copy(), self.x, self.extrapolate)
+
+        for axis, n in enumerate(nu):
+            p._antiderivative_inplace(n, axis)
+
+        p._ensure_c_contiguous()
+        return p
+
+    def integrate_1d(self, a, b, axis, extrapolate=None):
+        r"""
+        Compute NdPPoly representation for one dimensional definite integral
+
+        The result is a piecewise polynomial representing the integral:
+
+        .. math::
+
+           p(y, z, ...) = \int_a^b dx\, p(x, y, z, ...)
+
+        where the dimension integrated over is specified with the
+        `axis` parameter.
+
+        Parameters
+        ----------
+        a, b : float
+            Lower and upper bound for integration.
+        axis : int
+            Dimension over which to compute the 1-D integrals
+        extrapolate : bool, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs.
+
+        Returns
+        -------
+        ig : NdPPoly or array-like
+            Definite integral of the piecewise polynomial over [a, b].
+            If the polynomial was 1D, an array is returned,
+            otherwise, an NdPPoly object.
+
+        """
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        else:
+            extrapolate = bool(extrapolate)
+
+        ndim = len(self.x)
+        axis = int(axis) % ndim
+
+        # reuse 1-D integration routines
+        c = self.c
+        swap = list(range(c.ndim))
+        swap.insert(0, swap[axis])
+        del swap[axis + 1]
+        swap.insert(1, swap[ndim + axis])
+        del swap[ndim + axis + 1]
+
+        c = c.transpose(swap)
+        p = PPoly.construct_fast(c.reshape(c.shape[0], c.shape[1], -1),
+                                 self.x[axis],
+                                 extrapolate=extrapolate)
+        out = p.integrate(a, b, extrapolate=extrapolate)
+
+        # Construct result
+        if ndim == 1:
+            return out.reshape(c.shape[2:])
+        else:
+            c = out.reshape(c.shape[2:])
+            x = self.x[:axis] + self.x[axis+1:]
+            return self.construct_fast(c, x, extrapolate=extrapolate)
+
+    def integrate(self, ranges, extrapolate=None):
+        """
+        Compute a definite integral over a piecewise polynomial.
+
+        Parameters
+        ----------
+        ranges : ndim-tuple of 2-tuples float
+            Sequence of lower and upper bounds for each dimension,
+            ``[(a[0], b[0]), ..., (a[ndim-1], b[ndim-1])]``
+        extrapolate : bool, optional
+            Whether to extrapolate to out-of-bounds points based on first
+            and last intervals, or to return NaNs.
+
+        Returns
+        -------
+        ig : array_like
+            Definite integral of the piecewise polynomial over
+            [a[0], b[0]] x ... x [a[ndim-1], b[ndim-1]]
+
+        """
+
+        ndim = len(self.x)
+
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        else:
+            extrapolate = bool(extrapolate)
+
+        if not hasattr(ranges, '__len__') or len(ranges) != ndim:
+            raise ValueError("Range not a sequence of correct length")
+
+        self._ensure_c_contiguous()
+
+        # Reuse 1D integration routine
+        c = self.c
+        for n, (a, b) in enumerate(ranges):
+            swap = list(range(c.ndim))
+            swap.insert(1, swap[ndim - n])
+            del swap[ndim - n + 1]
+
+            c = c.transpose(swap)
+
+            p = PPoly.construct_fast(c, self.x[n], extrapolate=extrapolate)
+            out = p.integrate(a, b, extrapolate=extrapolate)
+            c = out.reshape(c.shape[2:])
+
+        return c
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndbspline.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndbspline.py
new file mode 100644
index 0000000000000000000000000000000000000000..51ac566ed5ff1271a46ffafcc04c0e180f2ec3f1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndbspline.py
@@ -0,0 +1,420 @@
+import itertools
+import functools
+import operator
+import numpy as np
+
+from math import prod
+
+from . import _bspl   # type: ignore[attr-defined]
+
+import scipy.sparse.linalg as ssl
+from scipy.sparse import csr_array
+
+from ._bsplines import _not_a_knot
+
+__all__ = ["NdBSpline"]
+
+
+def _get_dtype(dtype):
+    """Return np.complex128 for complex dtypes, np.float64 otherwise."""
+    if np.issubdtype(dtype, np.complexfloating):
+        return np.complex128
+    else:
+        return np.float64
+
+
+class NdBSpline:
+    """Tensor product spline object.
+
+    The value at point ``xp = (x1, x2, ..., xN)`` is evaluated as a linear
+    combination of products of one-dimensional b-splines in each of the ``N``
+    dimensions::
+
+       c[i1, i2, ..., iN] * B(x1; i1, t1) * B(x2; i2, t2) * ... * B(xN; iN, tN)
+
+
+    Here ``B(x; i, t)`` is the ``i``-th b-spline defined by the knot vector
+    ``t`` evaluated at ``x``.
+
+    Parameters
+    ----------
+    t : tuple of 1D ndarrays
+        knot vectors in directions 1, 2, ... N,
+        ``len(t[i]) == n[i] + k + 1``
+    c : ndarray, shape (n1, n2, ..., nN, ...)
+        b-spline coefficients
+    k : int or length-d tuple of integers
+        spline degrees.
+        A single integer is interpreted as having this degree for
+        all dimensions.
+    extrapolate : bool, optional
+        Whether to extrapolate out-of-bounds inputs, or return `nan`.
+        Default is to extrapolate.
+
+    Attributes
+    ----------
+    t : tuple of ndarrays
+        Knots vectors.
+    c : ndarray
+        Coefficients of the tensor-product spline.
+    k : tuple of integers
+        Degrees for each dimension.
+    extrapolate : bool, optional
+        Whether to extrapolate or return nans for out-of-bounds inputs.
+        Defaults to true.
+
+    Methods
+    -------
+    __call__
+    design_matrix
+
+    See Also
+    --------
+    BSpline : a one-dimensional B-spline object
+    NdPPoly : an N-dimensional piecewise tensor product polynomial
+
+    """
+    def __init__(self, t, c, k, *, extrapolate=None):
+        self._k, self._indices_k1d, (self._t, self._len_t) = _preprocess_inputs(k, t)
+
+        if extrapolate is None:
+            extrapolate = True
+        self.extrapolate = bool(extrapolate)
+
+        self.c = np.asarray(c)
+
+        ndim = self._t.shape[0]   # == len(self.t)
+        if self.c.ndim < ndim:
+            raise ValueError(f"Coefficients must be at least {ndim}-dimensional.")
+
+        for d in range(ndim):
+            td = self.t[d]
+            kd = self.k[d]
+            n = td.shape[0] - kd - 1
+
+            if self.c.shape[d] != n:
+                raise ValueError(f"Knots, coefficients and degree in dimension"
+                                 f" {d} are inconsistent:"
+                                 f" got {self.c.shape[d]} coefficients for"
+                                 f" {len(td)} knots, need at least {n} for"
+                                 f" k={k}.")
+
+        dt = _get_dtype(self.c.dtype)
+        self.c = np.ascontiguousarray(self.c, dtype=dt)
+
+    @property
+    def k(self):
+        return tuple(self._k)
+
+    @property
+    def t(self):
+        # repack the knots into a tuple
+        return tuple(self._t[d, :self._len_t[d]] for d in range(self._t.shape[0]))
+
+    def __call__(self, xi, *, nu=None, extrapolate=None):
+        """Evaluate the tensor product b-spline at ``xi``.
+
+        Parameters
+        ----------
+        xi : array_like, shape(..., ndim)
+            The coordinates to evaluate the interpolator at.
+            This can be a list or tuple of ndim-dimensional points
+            or an array with the shape (num_points, ndim).
+        nu : array_like, optional, shape (ndim,)
+            Orders of derivatives to evaluate. Each must be non-negative.
+            Defaults to the zeroth derivivative.
+        extrapolate : bool, optional
+            Whether to exrapolate based on first and last intervals in each
+            dimension, or return `nan`. Default is to ``self.extrapolate``.
+
+        Returns
+        -------
+        values : ndarray, shape ``xi.shape[:-1] + self.c.shape[ndim:]``
+            Interpolated values at ``xi``
+        """
+        ndim = self._t.shape[0]  # == len(self.t)
+
+        if extrapolate is None:
+            extrapolate = self.extrapolate
+        extrapolate = bool(extrapolate)
+
+        if nu is None:
+            nu = np.zeros((ndim,), dtype=np.intc)
+        else:
+            nu = np.asarray(nu, dtype=np.intc)
+            if nu.ndim != 1 or nu.shape[0] != ndim:
+                raise ValueError(
+                    f"invalid number of derivative orders {nu = } for "
+                    f"ndim = {len(self.t)}.")
+            if any(nu < 0):
+                raise ValueError(f"derivatives must be positive, got {nu = }")
+
+        # prepare xi : shape (..., m1, ..., md) -> (1, m1, ..., md)
+        xi = np.asarray(xi, dtype=float)
+        xi_shape = xi.shape
+        xi = xi.reshape(-1, xi_shape[-1])
+        xi = np.ascontiguousarray(xi)
+
+        if xi_shape[-1] != ndim:
+            raise ValueError(f"Shapes: xi.shape={xi_shape} and ndim={ndim}")
+
+        # complex -> double
+        was_complex = self.c.dtype.kind == 'c'
+        cc = self.c
+        if was_complex and self.c.ndim == ndim:
+            # make sure that core dimensions are intact, and complex->float
+            # size doubling only adds a trailing dimension
+            cc = self.c[..., None]
+        cc = cc.view(float)
+
+        # prepare the coefficients: flatten the trailing dimensions
+        c1 = cc.reshape(cc.shape[:ndim] + (-1,))
+        c1r = c1.ravel()
+
+        # replacement for np.ravel_multi_index for indexing of `c1`:
+        _strides_c1 = np.asarray([s // c1.dtype.itemsize
+                                  for s in c1.strides], dtype=np.intp)
+
+        num_c_tr = c1.shape[-1]  # # of trailing coefficients
+        out = np.empty(xi.shape[:-1] + (num_c_tr,), dtype=c1.dtype)
+
+        _bspl.evaluate_ndbspline(xi,
+                                 self._t,
+                                 self._len_t,
+                                 self._k,
+                                 nu,
+                                 extrapolate,
+                                 c1r,
+                                 num_c_tr,
+                                 _strides_c1,
+                                 self._indices_k1d,
+                                 out,)
+        out = out.view(self.c.dtype)
+        return out.reshape(xi_shape[:-1] + self.c.shape[ndim:])
+
+    @classmethod
+    def design_matrix(cls, xvals, t, k, extrapolate=True):
+        """Construct the design matrix as a CSR format sparse array.
+
+        Parameters
+        ----------
+        xvals :  ndarray, shape(npts, ndim)
+            Data points. ``xvals[j, :]`` gives the ``j``-th data point as an
+            ``ndim``-dimensional array.
+        t : tuple of 1D ndarrays, length-ndim
+            Knot vectors in directions 1, 2, ... ndim,
+        k : int
+            B-spline degree.
+        extrapolate : bool, optional
+            Whether to extrapolate out-of-bounds values of raise a `ValueError`
+
+        Returns
+        -------
+        design_matrix : a CSR array
+            Each row of the design matrix corresponds to a value in `xvals` and
+            contains values of b-spline basis elements which are non-zero
+            at this value.
+
+        """
+        xvals = np.asarray(xvals, dtype=float)
+        ndim = xvals.shape[-1]
+        if len(t) != ndim:
+            raise ValueError(
+                f"Data and knots are inconsistent: len(t) = {len(t)} for "
+                f" {ndim = }."
+            )
+
+        # tabulate the flat indices for iterating over the (k+1)**ndim subarray
+        k, _indices_k1d, (_t, len_t) = _preprocess_inputs(k, t)
+
+        # Precompute the shape and strides of the 'coefficients array'.
+        # This would have been the NdBSpline coefficients; in the present context
+        # this is a helper to compute the indices into the colocation matrix.
+        c_shape = tuple(len_t[d] - k[d] - 1 for d in range(ndim))
+
+        # The strides of the coeffs array: the computation is equivalent to
+        # >>> cstrides = [s // 8 for s in np.empty(c_shape).strides]
+        cs = c_shape[1:] + (1,)
+        cstrides = np.cumprod(cs[::-1], dtype=np.intp)[::-1].copy()
+
+        # heavy lifting happens here
+        data, indices, indptr = _bspl._colloc_nd(xvals,
+                                                _t,
+                                                len_t,
+                                                k,
+                                                _indices_k1d,
+                                                cstrides)
+        return csr_array((data, indices, indptr))
+
+
+def _preprocess_inputs(k, t_tpl):
+    """Helpers: validate and preprocess NdBSpline inputs.
+
+       Parameters
+       ----------
+       k : int or tuple
+          Spline orders
+       t_tpl : tuple or array-likes
+          Knots.
+    """
+    # 1. Make sure t_tpl is a tuple
+    if not isinstance(t_tpl, tuple):
+        raise ValueError(f"Expect `t` to be a tuple of array-likes. "
+                         f"Got {t_tpl} instead."
+        )
+
+    # 2. Make ``k`` a tuple of integers
+    ndim = len(t_tpl)
+    try:
+        len(k)
+    except TypeError:
+        # make k a tuple
+        k = (k,)*ndim
+
+    k = np.asarray([operator.index(ki) for ki in k], dtype=np.int32)
+
+    if len(k) != ndim:
+        raise ValueError(f"len(t) = {len(t_tpl)} != {len(k) = }.")
+
+    # 3. Validate inputs
+    ndim = len(t_tpl)
+    for d in range(ndim):
+        td = np.asarray(t_tpl[d])
+        kd = k[d]
+        n = td.shape[0] - kd - 1
+        if kd < 0:
+            raise ValueError(f"Spline degree in dimension {d} cannot be"
+                             f" negative.")
+        if td.ndim != 1:
+            raise ValueError(f"Knot vector in dimension {d} must be"
+                             f" one-dimensional.")
+        if n < kd + 1:
+            raise ValueError(f"Need at least {2*kd + 2} knots for degree"
+                             f" {kd} in dimension {d}.")
+        if (np.diff(td) < 0).any():
+            raise ValueError(f"Knots in dimension {d} must be in a"
+                             f" non-decreasing order.")
+        if len(np.unique(td[kd:n + 1])) < 2:
+            raise ValueError(f"Need at least two internal knots in"
+                             f" dimension {d}.")
+        if not np.isfinite(td).all():
+            raise ValueError(f"Knots in dimension {d} should not have"
+                             f" nans or infs.")
+
+    # 4. tabulate the flat indices for iterating over the (k+1)**ndim subarray
+    # non-zero b-spline elements
+    shape = tuple(kd + 1 for kd in k)
+    indices = np.unravel_index(np.arange(prod(shape)), shape)
+    _indices_k1d = np.asarray(indices, dtype=np.intp).T.copy()
+
+    # 5. pack the knots into a single array:
+    #    ([1, 2, 3, 4], [5, 6], (7, 8, 9)) -->
+    #    array([[1, 2, 3, 4],
+    #           [5, 6, nan, nan],
+    #           [7, 8, 9, nan]])
+    ndim = len(t_tpl)
+    len_t = [len(ti) for ti in t_tpl]
+    _t = np.empty((ndim, max(len_t)), dtype=float)
+    _t.fill(np.nan)
+    for d in range(ndim):
+        _t[d, :len(t_tpl[d])] = t_tpl[d]
+    len_t = np.asarray(len_t, dtype=np.int32)
+
+    return k, _indices_k1d, (_t, len_t)
+
+
+def _iter_solve(a, b, solver=ssl.gcrotmk, **solver_args):
+    # work around iterative solvers not accepting multiple r.h.s.
+
+    # also work around a.dtype == float64 and b.dtype == complex128
+    # cf https://github.com/scipy/scipy/issues/19644
+    if np.issubdtype(b.dtype, np.complexfloating):
+        real = _iter_solve(a, b.real, solver, **solver_args)
+        imag = _iter_solve(a, b.imag, solver, **solver_args)
+        return real + 1j*imag
+
+    if b.ndim == 2 and b.shape[1] !=1:
+        res = np.empty_like(b)
+        for j in range(b.shape[1]):
+            res[:, j], info = solver(a, b[:, j], **solver_args)
+            if info != 0:
+                raise ValueError(f"{solver = } returns {info =} for column {j}.")
+        return res
+    else:
+        res, info = solver(a, b, **solver_args)
+        if info != 0:
+            raise ValueError(f"{solver = } returns {info = }.")
+        return res
+
+
+def make_ndbspl(points, values, k=3, *, solver=ssl.gcrotmk, **solver_args):
+    """Construct an interpolating NdBspline.
+
+    Parameters
+    ----------
+    points : tuple of ndarrays of float, with shapes (m1,), ... (mN,)
+        The points defining the regular grid in N dimensions. The points in
+        each dimension (i.e. every element of the `points` tuple) must be
+        strictly ascending or descending.      
+    values : ndarray of float, shape (m1, ..., mN, ...)
+        The data on the regular grid in n dimensions.
+    k : int, optional
+        The spline degree. Must be odd. Default is cubic, k=3
+    solver : a `scipy.sparse.linalg` solver (iterative or direct), optional.
+        An iterative solver from `scipy.sparse.linalg` or a direct one,
+        `sparse.sparse.linalg.spsolve`.
+        Used to solve the sparse linear system
+        ``design_matrix @ coefficients = rhs`` for the coefficients.
+        Default is `scipy.sparse.linalg.gcrotmk`
+    solver_args : dict, optional
+        Additional arguments for the solver. The call signature is
+        ``solver(csr_array, rhs_vector, **solver_args)``
+
+    Returns
+    -------
+    spl : NdBSpline object
+
+    Notes
+    -----
+    Boundary conditions are not-a-knot in all dimensions.
+    """
+    ndim = len(points)
+    xi_shape = tuple(len(x) for x in points)
+
+    try:
+        len(k)
+    except TypeError:
+        # make k a tuple
+        k = (k,)*ndim
+
+    for d, point in enumerate(points):
+        numpts = len(np.atleast_1d(point))
+        if numpts <= k[d]:
+            raise ValueError(f"There are {numpts} points in dimension {d},"
+                             f" but order {k[d]} requires at least "
+                             f" {k[d]+1} points per dimension.")
+
+    t = tuple(_not_a_knot(np.asarray(points[d], dtype=float), k[d])
+              for d in range(ndim))
+    xvals = np.asarray([xv for xv in itertools.product(*points)], dtype=float)
+
+    # construct the colocation matrix
+    matr = NdBSpline.design_matrix(xvals, t, k)
+
+    # Solve for the coefficients given `values`.
+    # Trailing dimensions: first ndim dimensions are data, the rest are batch
+    # dimensions, so stack `values` into a 2D array for `spsolve` to undestand.
+    v_shape = values.shape
+    vals_shape = (prod(v_shape[:ndim]), prod(v_shape[ndim:]))
+    vals = values.reshape(vals_shape)
+
+    if solver != ssl.spsolve:
+        solver = functools.partial(_iter_solve, solver=solver)
+        if "atol" not in solver_args:
+            # avoid a DeprecationWarning, grumble grumble
+            solver_args["atol"] = 1e-6
+
+    coef = solver(matr, vals, **solver_args)
+    coef = coef.reshape(xi_shape + v_shape[ndim:])
+    return NdBSpline(t, coef, k)
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndgriddata.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..78fe9d6995141ad238002e0b48feb94017dc272a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_ndgriddata.py
@@ -0,0 +1,332 @@
+"""
+Convenience interface to N-D interpolation
+
+.. versionadded:: 0.9
+
+"""
+import numpy as np
+from ._interpnd import (LinearNDInterpolator, NDInterpolatorBase,
+     CloughTocher2DInterpolator, _ndim_coords_from_arrays)
+from scipy.spatial import cKDTree
+
+__all__ = ['griddata', 'NearestNDInterpolator', 'LinearNDInterpolator',
+           'CloughTocher2DInterpolator']
+
+#------------------------------------------------------------------------------
+# Nearest-neighbor interpolation
+#------------------------------------------------------------------------------
+
+
+class NearestNDInterpolator(NDInterpolatorBase):
+    """NearestNDInterpolator(x, y).
+
+    Nearest-neighbor interpolator in N > 1 dimensions.
+
+    .. versionadded:: 0.9
+
+    Methods
+    -------
+    __call__
+
+    Parameters
+    ----------
+    x : (npoints, ndims) 2-D ndarray of floats
+        Data point coordinates.
+    y : (npoints, ) 1-D ndarray of float or complex
+        Data values.
+    rescale : boolean, optional
+        Rescale points to unit cube before performing interpolation.
+        This is useful if some of the input dimensions have
+        incommensurable units and differ by many orders of magnitude.
+
+        .. versionadded:: 0.14.0
+    tree_options : dict, optional
+        Options passed to the underlying ``cKDTree``.
+
+        .. versionadded:: 0.17.0
+
+    See Also
+    --------
+    griddata :
+        Interpolate unstructured D-D data.
+    LinearNDInterpolator :
+        Piecewise linear interpolator in N dimensions.
+    CloughTocher2DInterpolator :
+        Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D.
+    interpn : Interpolation on a regular grid or rectilinear grid.
+    RegularGridInterpolator : Interpolator on a regular or rectilinear grid
+                              in arbitrary dimensions (`interpn` wraps this
+                              class).
+
+    Notes
+    -----
+    Uses ``scipy.spatial.cKDTree``
+
+    .. note:: For data on a regular grid use `interpn` instead.
+
+    Examples
+    --------
+    We can interpolate values on a 2D plane:
+
+    >>> from scipy.interpolate import NearestNDInterpolator
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random(10) - 0.5
+    >>> y = rng.random(10) - 0.5
+    >>> z = np.hypot(x, y)
+    >>> X = np.linspace(min(x), max(x))
+    >>> Y = np.linspace(min(y), max(y))
+    >>> X, Y = np.meshgrid(X, Y)  # 2D grid for interpolation
+    >>> interp = NearestNDInterpolator(list(zip(x, y)), z)
+    >>> Z = interp(X, Y)
+    >>> plt.pcolormesh(X, Y, Z, shading='auto')
+    >>> plt.plot(x, y, "ok", label="input point")
+    >>> plt.legend()
+    >>> plt.colorbar()
+    >>> plt.axis("equal")
+    >>> plt.show()
+
+    """
+
+    def __init__(self, x, y, rescale=False, tree_options=None):
+        NDInterpolatorBase.__init__(self, x, y, rescale=rescale,
+                                    need_contiguous=False,
+                                    need_values=False)
+        if tree_options is None:
+            tree_options = dict()
+        self.tree = cKDTree(self.points, **tree_options)
+        self.values = np.asarray(y)
+
+    def __call__(self, *args, **query_options):
+        """
+        Evaluate interpolator at given points.
+
+        Parameters
+        ----------
+        x1, x2, ... xn : array-like of float
+            Points where to interpolate data at.
+            x1, x2, ... xn can be array-like of float with broadcastable shape.
+            or x1 can be array-like of float with shape ``(..., ndim)``
+        **query_options
+            This allows ``eps``, ``p``, ``distance_upper_bound``, and ``workers``
+            being passed to the cKDTree's query function to be explicitly set.
+            See `scipy.spatial.cKDTree.query` for an overview of the different options.
+
+            .. versionadded:: 1.12.0
+
+        """
+        # For the sake of enabling subclassing, NDInterpolatorBase._set_xi performs
+        # some operations which are not required by NearestNDInterpolator.__call__, 
+        # hence here we operate on xi directly, without calling a parent class function.
+        xi = _ndim_coords_from_arrays(args, ndim=self.points.shape[1])
+        xi = self._check_call_shape(xi)
+        xi = self._scale_x(xi)
+
+        # We need to handle two important cases:
+        # (1) the case where xi has trailing dimensions (..., ndim), and
+        # (2) the case where y has trailing dimensions
+        # We will first flatten xi to deal with case (1),
+        # do the computation in flattened array while retaining y's dimensionality,
+        # and then reshape the interpolated values back to match xi's shape.
+
+        # Flatten xi for the query
+        xi_flat = xi.reshape(-1, xi.shape[-1])
+        original_shape = xi.shape
+        flattened_shape = xi_flat.shape
+
+        # if distance_upper_bound is set to not be infinite,
+        # then we need to consider the case where cKDtree
+        # does not find any points within distance_upper_bound to return.
+        # It marks those points as having infinte distance, which is what will be used
+        # below to mask the array and return only the points that were deemed
+        # to have a close enough neighbor to return something useful.
+        dist, i = self.tree.query(xi_flat, **query_options)
+        valid_mask = np.isfinite(dist)
+
+        # create a holder interp_values array and fill with nans.
+        if self.values.ndim > 1:
+            interp_shape = flattened_shape[:-1] + self.values.shape[1:]
+        else:
+            interp_shape = flattened_shape[:-1]
+
+        if np.issubdtype(self.values.dtype, np.complexfloating):
+            interp_values = np.full(interp_shape, np.nan, dtype=self.values.dtype)
+        else:
+            interp_values = np.full(interp_shape, np.nan)
+
+        interp_values[valid_mask] = self.values[i[valid_mask], ...]
+
+        if self.values.ndim > 1:
+            new_shape = original_shape[:-1] + self.values.shape[1:]
+        else:
+            new_shape = original_shape[:-1]
+        interp_values = interp_values.reshape(new_shape)
+
+        return interp_values
+
+
+#------------------------------------------------------------------------------
+# Convenience interface function
+#------------------------------------------------------------------------------
+
+
+def griddata(points, values, xi, method='linear', fill_value=np.nan,
+             rescale=False):
+    """
+    Interpolate unstructured D-D data.
+
+    Parameters
+    ----------
+    points : 2-D ndarray of floats with shape (n, D), or length D tuple of 1-D ndarrays with shape (n,).
+        Data point coordinates.
+    values : ndarray of float or complex, shape (n,)
+        Data values.
+    xi : 2-D ndarray of floats with shape (m, D), or length D tuple of ndarrays broadcastable to the same shape.
+        Points at which to interpolate data.
+    method : {'linear', 'nearest', 'cubic'}, optional
+        Method of interpolation. One of
+
+        ``nearest``
+          return the value at the data point closest to
+          the point of interpolation. See `NearestNDInterpolator` for
+          more details.
+
+        ``linear``
+          tessellate the input point set to N-D
+          simplices, and interpolate linearly on each simplex. See
+          `LinearNDInterpolator` for more details.
+
+        ``cubic`` (1-D)
+          return the value determined from a cubic
+          spline.
+
+        ``cubic`` (2-D)
+          return the value determined from a
+          piecewise cubic, continuously differentiable (C1), and
+          approximately curvature-minimizing polynomial surface. See
+          `CloughTocher2DInterpolator` for more details.
+    fill_value : float, optional
+        Value used to fill in for requested points outside of the
+        convex hull of the input points. If not provided, then the
+        default is ``nan``. This option has no effect for the
+        'nearest' method.
+    rescale : bool, optional
+        Rescale points to unit cube before performing interpolation.
+        This is useful if some of the input dimensions have
+        incommensurable units and differ by many orders of magnitude.
+
+        .. versionadded:: 0.14.0
+
+    Returns
+    -------
+    ndarray
+        Array of interpolated values.
+
+    See Also
+    --------
+    LinearNDInterpolator :
+        Piecewise linear interpolator in N dimensions.
+    NearestNDInterpolator :
+        Nearest-neighbor interpolator in N dimensions.
+    CloughTocher2DInterpolator :
+        Piecewise cubic, C1 smooth, curvature-minimizing interpolator in 2D.
+    interpn : Interpolation on a regular grid or rectilinear grid.
+    RegularGridInterpolator : Interpolator on a regular or rectilinear grid
+                              in arbitrary dimensions (`interpn` wraps this
+                              class).
+
+    Notes
+    -----
+
+    .. versionadded:: 0.9
+
+    .. note:: For data on a regular grid use `interpn` instead.
+
+    Examples
+    --------
+
+    Suppose we want to interpolate the 2-D function
+
+    >>> import numpy as np
+    >>> def func(x, y):
+    ...     return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2
+
+    on a grid in [0, 1]x[0, 1]
+
+    >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]
+
+    but we only know its values at 1000 data points:
+
+    >>> rng = np.random.default_rng()
+    >>> points = rng.random((1000, 2))
+    >>> values = func(points[:,0], points[:,1])
+
+    This can be done with `griddata` -- below we try out all of the
+    interpolation methods:
+
+    >>> from scipy.interpolate import griddata
+    >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
+    >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')
+    >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic')
+
+    One can see that the exact result is reproduced by all of the
+    methods to some degree, but for this smooth function the piecewise
+    cubic interpolant gives the best results:
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.subplot(221)
+    >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower')
+    >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1)
+    >>> plt.title('Original')
+    >>> plt.subplot(222)
+    >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower')
+    >>> plt.title('Nearest')
+    >>> plt.subplot(223)
+    >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower')
+    >>> plt.title('Linear')
+    >>> plt.subplot(224)
+    >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower')
+    >>> plt.title('Cubic')
+    >>> plt.gcf().set_size_inches(6, 6)
+    >>> plt.show()
+
+    """ # numpy/numpydoc#87  # noqa: E501
+
+    points = _ndim_coords_from_arrays(points)
+
+    if points.ndim < 2:
+        ndim = points.ndim
+    else:
+        ndim = points.shape[-1]
+
+    if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
+        from ._interpolate import interp1d
+        points = points.ravel()
+        if isinstance(xi, tuple):
+            if len(xi) != 1:
+                raise ValueError("invalid number of dimensions in xi")
+            xi, = xi
+        # Sort points/values together, necessary as input for interp1d
+        idx = np.argsort(points)
+        points = points[idx]
+        values = values[idx]
+        if method == 'nearest':
+            fill_value = 'extrapolate'
+        ip = interp1d(points, values, kind=method, axis=0, bounds_error=False,
+                      fill_value=fill_value)
+        return ip(xi)
+    elif method == 'nearest':
+        ip = NearestNDInterpolator(points, values, rescale=rescale)
+        return ip(xi)
+    elif method == 'linear':
+        ip = LinearNDInterpolator(points, values, fill_value=fill_value,
+                                  rescale=rescale)
+        return ip(xi)
+    elif method == 'cubic' and ndim == 2:
+        ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value,
+                                        rescale=rescale)
+        return ip(xi)
+    else:
+        raise ValueError("Unknown interpolation method %r for "
+                         "%d dimensional data" % (method, ndim))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_pade.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_pade.py
new file mode 100644
index 0000000000000000000000000000000000000000..387ef11dde5d3ace8a15324058c10fa31899c92c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_pade.py
@@ -0,0 +1,67 @@
+from numpy import zeros, asarray, eye, poly1d, hstack, r_
+from scipy import linalg
+
+__all__ = ["pade"]
+
+def pade(an, m, n=None):
+    """
+    Return Pade approximation to a polynomial as the ratio of two polynomials.
+
+    Parameters
+    ----------
+    an : (N,) array_like
+        Taylor series coefficients.
+    m : int
+        The order of the returned approximating polynomial `q`.
+    n : int, optional
+        The order of the returned approximating polynomial `p`. By default,
+        the order is ``len(an)-1-m``.
+
+    Returns
+    -------
+    p, q : Polynomial class
+        The Pade approximation of the polynomial defined by `an` is
+        ``p(x)/q(x)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.interpolate import pade
+    >>> e_exp = [1.0, 1.0, 1.0/2.0, 1.0/6.0, 1.0/24.0, 1.0/120.0]
+    >>> p, q = pade(e_exp, 2)
+
+    >>> e_exp.reverse()
+    >>> e_poly = np.poly1d(e_exp)
+
+    Compare ``e_poly(x)`` and the Pade approximation ``p(x)/q(x)``
+
+    >>> e_poly(1)
+    2.7166666666666668
+
+    >>> p(1)/q(1)
+    2.7179487179487181
+
+    """
+    an = asarray(an)
+    if n is None:
+        n = len(an) - 1 - m
+        if n < 0:
+            raise ValueError("Order of q  must be smaller than len(an)-1.")
+    if n < 0:
+        raise ValueError("Order of p  must be greater than 0.")
+    N = m + n
+    if N > len(an)-1:
+        raise ValueError("Order of q+p  must be smaller than len(an).")
+    an = an[:N+1]
+    Akj = eye(N+1, n+1, dtype=an.dtype)
+    Bkj = zeros((N+1, m), dtype=an.dtype)
+    for row in range(1, m+1):
+        Bkj[row,:row] = -(an[:row])[::-1]
+    for row in range(m+1, N+1):
+        Bkj[row,:] = -(an[row-m:row])[::-1]
+    C = hstack((Akj, Bkj))
+    pq = linalg.solve(C, an)
+    p = pq[:n+1]
+    q = r_[1.0, pq[n+1:]]
+    return poly1d(p[::-1]), poly1d(q[::-1])
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_polyint.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cec3eb9939abba36505010334911c167797b750
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_polyint.py
@@ -0,0 +1,961 @@
+import warnings
+
+import numpy as np
+from scipy.special import factorial
+from scipy._lib._util import (_asarray_validated, float_factorial, check_random_state,
+                              _transition_to_rng)
+
+
+__all__ = ["KroghInterpolator", "krogh_interpolate",
+           "BarycentricInterpolator", "barycentric_interpolate",
+           "approximate_taylor_polynomial"]
+
+
+def _isscalar(x):
+    """Check whether x is if a scalar type, or 0-dim"""
+    return np.isscalar(x) or hasattr(x, 'shape') and x.shape == ()
+
+
+class _Interpolator1D:
+    """
+    Common features in univariate interpolation
+
+    Deal with input data type and interpolation axis rolling. The
+    actual interpolator can assume the y-data is of shape (n, r) where
+    `n` is the number of x-points, and `r` the number of variables,
+    and use self.dtype as the y-data type.
+
+    Attributes
+    ----------
+    _y_axis
+        Axis along which the interpolation goes in the original array
+    _y_extra_shape
+        Additional trailing shape of the input arrays, excluding
+        the interpolation axis.
+    dtype
+        Dtype of the y-data arrays. Can be set via _set_dtype, which
+        forces it to be float or complex.
+
+    Methods
+    -------
+    __call__
+    _prepare_x
+    _finish_y
+    _reshape_yi
+    _set_yi
+    _set_dtype
+    _evaluate
+
+    """
+
+    __slots__ = ('_y_axis', '_y_extra_shape', 'dtype')
+
+    def __init__(self, xi=None, yi=None, axis=None):
+        self._y_axis = axis
+        self._y_extra_shape = None
+        self.dtype = None
+        if yi is not None:
+            self._set_yi(yi, xi=xi, axis=axis)
+
+    def __call__(self, x):
+        """
+        Evaluate the interpolant
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the interpolant.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of `x`.
+
+        Notes
+        -----
+        Input values `x` must be convertible to `float` values like `int`
+        or `float`.
+
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate(x)
+        return self._finish_y(y, x_shape)
+
+    def _evaluate(self, x):
+        """
+        Actually evaluate the value of the interpolator.
+        """
+        raise NotImplementedError()
+
+    def _prepare_x(self, x):
+        """Reshape input x array to 1-D"""
+        x = _asarray_validated(x, check_finite=False, as_inexact=True)
+        x_shape = x.shape
+        return x.ravel(), x_shape
+
+    def _finish_y(self, y, x_shape):
+        """Reshape interpolated y back to an N-D array similar to initial y"""
+        y = y.reshape(x_shape + self._y_extra_shape)
+        if self._y_axis != 0 and x_shape != ():
+            nx = len(x_shape)
+            ny = len(self._y_extra_shape)
+            s = (list(range(nx, nx + self._y_axis))
+                 + list(range(nx)) + list(range(nx+self._y_axis, nx+ny)))
+            y = y.transpose(s)
+        return y
+
+    def _reshape_yi(self, yi, check=False):
+        yi = np.moveaxis(np.asarray(yi), self._y_axis, 0)
+        if check and yi.shape[1:] != self._y_extra_shape:
+            ok_shape = (f"{self._y_extra_shape[-self._y_axis:]!r} + (N,) + "
+                        f"{self._y_extra_shape[:-self._y_axis]!r}")
+            raise ValueError(f"Data must be of shape {ok_shape}")
+        return yi.reshape((yi.shape[0], -1))
+
+    def _set_yi(self, yi, xi=None, axis=None):
+        if axis is None:
+            axis = self._y_axis
+        if axis is None:
+            raise ValueError("no interpolation axis specified")
+
+        yi = np.asarray(yi)
+
+        shape = yi.shape
+        if shape == ():
+            shape = (1,)
+        if xi is not None and shape[axis] != len(xi):
+            raise ValueError("x and y arrays must be equal in length along "
+                             "interpolation axis.")
+
+        self._y_axis = (axis % yi.ndim)
+        self._y_extra_shape = yi.shape[:self._y_axis] + yi.shape[self._y_axis+1:]
+        self.dtype = None
+        self._set_dtype(yi.dtype)
+
+    def _set_dtype(self, dtype, union=False):
+        if np.issubdtype(dtype, np.complexfloating) \
+               or np.issubdtype(self.dtype, np.complexfloating):
+            self.dtype = np.complex128
+        else:
+            if not union or self.dtype != np.complex128:
+                self.dtype = np.float64
+
+
+class _Interpolator1DWithDerivatives(_Interpolator1D):
+    def derivatives(self, x, der=None):
+        """
+        Evaluate several derivatives of the polynomial at the point `x`
+
+        Produce an array of derivatives evaluated at the point `x`.
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the derivatives
+        der : int or list or None, optional
+            How many derivatives to evaluate, or None for all potentially
+            nonzero derivatives (that is, a number equal to the number
+            of points), or a list of derivatives to evaluate. This number
+            includes the function value as the '0th' derivative.
+
+        Returns
+        -------
+        d : ndarray
+            Array with derivatives; ``d[j]`` contains the jth derivative.
+            Shape of ``d[j]`` is determined by replacing the interpolation
+            axis in the original array with the shape of `x`.
+
+        Examples
+        --------
+        >>> from scipy.interpolate import KroghInterpolator
+        >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives(0)
+        array([1.0,2.0,3.0])
+        >>> KroghInterpolator([0,0,0],[1,2,3]).derivatives([0,0])
+        array([[1.0,1.0],
+               [2.0,2.0],
+               [3.0,3.0]])
+
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate_derivatives(x, der)
+
+        y = y.reshape((y.shape[0],) + x_shape + self._y_extra_shape)
+        if self._y_axis != 0 and x_shape != ():
+            nx = len(x_shape)
+            ny = len(self._y_extra_shape)
+            s = ([0] + list(range(nx+1, nx + self._y_axis+1))
+                 + list(range(1, nx+1)) +
+                 list(range(nx+1+self._y_axis, nx+ny+1)))
+            y = y.transpose(s)
+        return y
+
+    def derivative(self, x, der=1):
+        """
+        Evaluate a single derivative of the polynomial at the point `x`.
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the derivatives
+
+        der : integer, optional
+            Which derivative to evaluate (default: first derivative).
+            This number includes the function value as 0th derivative.
+
+        Returns
+        -------
+        d : ndarray
+            Derivative interpolated at the x-points. Shape of `d` is
+            determined by replacing the interpolation axis in the
+            original array with the shape of `x`.
+
+        Notes
+        -----
+        This may be computed by evaluating all derivatives up to the desired
+        one (using self.derivatives()) and then discarding the rest.
+
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate_derivatives(x, der+1)
+        return self._finish_y(y[der], x_shape)
+
+    def _evaluate_derivatives(self, x, der=None):
+        """
+        Actually evaluate the derivatives.
+
+        Parameters
+        ----------
+        x : array_like
+            1D array of points at which to evaluate the derivatives
+        der : integer, optional
+            The number of derivatives to evaluate, from 'order 0' (der=1)
+            to order der-1.  If omitted, return all possibly-non-zero
+            derivatives, ie 0 to order n-1.
+
+        Returns
+        -------
+        d : ndarray
+            Array of shape ``(der, x.size, self.yi.shape[1])`` containing
+            the derivatives from 0 to der-1
+        """
+        raise NotImplementedError()
+
+
+class KroghInterpolator(_Interpolator1DWithDerivatives):
+    """
+    Interpolating polynomial for a set of points.
+
+    The polynomial passes through all the pairs ``(xi, yi)``. One may
+    additionally specify a number of derivatives at each point `xi`;
+    this is done by repeating the value `xi` and specifying the
+    derivatives as successive `yi` values.
+
+    Allows evaluation of the polynomial and all its derivatives.
+    For reasons of numerical stability, this function does not compute
+    the coefficients of the polynomial, although they can be obtained
+    by evaluating all the derivatives.
+
+    Parameters
+    ----------
+    xi : array_like, shape (npoints, )
+        Known x-coordinates. Must be sorted in increasing order.
+    yi : array_like, shape (..., npoints, ...)
+        Known y-coordinates. When an xi occurs two or more times in
+        a row, the corresponding yi's represent derivative values. The length of `yi`
+        along the interpolation axis must be equal to the length of `xi`. Use the
+        `axis` parameter to select the correct axis.
+    axis : int, optional
+        Axis in the `yi` array corresponding to the x-coordinate values. Defaults to
+        ``axis=0``.
+
+    Notes
+    -----
+    Be aware that the algorithms implemented here are not necessarily
+    the most numerically stable known. Moreover, even in a world of
+    exact computation, unless the x coordinates are chosen very
+    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
+    polynomial interpolation itself is a very ill-conditioned process
+    due to the Runge phenomenon. In general, even with well-chosen
+    x values, degrees higher than about thirty cause problems with
+    numerical instability in this code.
+
+    Based on [1]_.
+
+    References
+    ----------
+    .. [1] Krogh, "Efficient Algorithms for Polynomial Interpolation
+        and Numerical Differentiation", 1970.
+
+    Examples
+    --------
+    To produce a polynomial that is zero at 0 and 1 and has
+    derivative 2 at 0, call
+
+    >>> from scipy.interpolate import KroghInterpolator
+    >>> KroghInterpolator([0,0,1],[0,2,0])
+
+    This constructs the quadratic :math:`2x^2-2x`. The derivative condition
+    is indicated by the repeated zero in the `xi` array; the corresponding
+    yi values are 0, the function value, and 2, the derivative value.
+
+    For another example, given `xi`, `yi`, and a derivative `ypi` for each
+    point, appropriate arrays can be constructed as:
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> xi = np.linspace(0, 1, 5)
+    >>> yi, ypi = rng.random((2, 5))
+    >>> xi_k, yi_k = np.repeat(xi, 2), np.ravel(np.dstack((yi,ypi)))
+    >>> KroghInterpolator(xi_k, yi_k)
+
+    To produce a vector-valued polynomial, supply a higher-dimensional
+    array for `yi`:
+
+    >>> KroghInterpolator([0,1],[[2,3],[4,5]])
+
+    This constructs a linear polynomial giving (2,3) at 0 and (4,5) at 1.
+
+    """
+
+    def __init__(self, xi, yi, axis=0):
+        super().__init__(xi, yi, axis)
+
+        self.xi = np.asarray(xi)
+        self.yi = self._reshape_yi(yi)
+        self.n, self.r = self.yi.shape
+
+        if (deg := self.xi.size) > 30:
+            warnings.warn(f"{deg} degrees provided, degrees higher than about"
+                          " thirty cause problems with numerical instability "
+                          "with 'KroghInterpolator'", stacklevel=2)
+
+        c = np.zeros((self.n+1, self.r), dtype=self.dtype)
+        c[0] = self.yi[0]
+        Vk = np.zeros((self.n, self.r), dtype=self.dtype)
+        for k in range(1, self.n):
+            s = 0
+            while s <= k and xi[k-s] == xi[k]:
+                s += 1
+            s -= 1
+            Vk[0] = self.yi[k]/float_factorial(s)
+            for i in range(k-s):
+                if xi[i] == xi[k]:
+                    raise ValueError("Elements of `xi` can't be equal.")
+                if s == 0:
+                    Vk[i+1] = (c[i]-Vk[i])/(xi[i]-xi[k])
+                else:
+                    Vk[i+1] = (Vk[i+1]-Vk[i])/(xi[i]-xi[k])
+            c[k] = Vk[k-s]
+        self.c = c
+
+    def _evaluate(self, x):
+        pi = 1
+        p = np.zeros((len(x), self.r), dtype=self.dtype)
+        p += self.c[0,np.newaxis,:]
+        for k in range(1, self.n):
+            w = x - self.xi[k-1]
+            pi = w*pi
+            p += pi[:,np.newaxis] * self.c[k]
+        return p
+
+    def _evaluate_derivatives(self, x, der=None):
+        n = self.n
+        r = self.r
+
+        if der is None:
+            der = self.n
+
+        pi = np.zeros((n, len(x)))
+        w = np.zeros((n, len(x)))
+        pi[0] = 1
+        p = np.zeros((len(x), self.r), dtype=self.dtype)
+        p += self.c[0, np.newaxis, :]
+
+        for k in range(1, n):
+            w[k-1] = x - self.xi[k-1]
+            pi[k] = w[k-1] * pi[k-1]
+            p += pi[k, :, np.newaxis] * self.c[k]
+
+        cn = np.zeros((max(der, n+1), len(x), r), dtype=self.dtype)
+        cn[:n+1, :, :] += self.c[:n+1, np.newaxis, :]
+        cn[0] = p
+        for k in range(1, n):
+            for i in range(1, n-k+1):
+                pi[i] = w[k+i-1]*pi[i-1] + pi[i]
+                cn[k] = cn[k] + pi[i, :, np.newaxis]*cn[k+i]
+            cn[k] *= float_factorial(k)
+
+        cn[n, :, :] = 0
+        return cn[:der]
+
+
+def krogh_interpolate(xi, yi, x, der=0, axis=0):
+    """
+    Convenience function for polynomial interpolation.
+
+    See `KroghInterpolator` for more details.
+
+    Parameters
+    ----------
+    xi : array_like
+        Interpolation points (known x-coordinates).
+    yi : array_like
+        Known y-coordinates, of shape ``(xi.size, R)``. Interpreted as
+        vectors of length R, or scalars if R=1.
+    x : array_like
+        Point or points at which to evaluate the derivatives.
+    der : int or list or None, optional
+        How many derivatives to evaluate, or None for all potentially
+        nonzero derivatives (that is, a number equal to the number
+        of points), or a list of derivatives to evaluate. This number
+        includes the function value as the '0th' derivative.
+    axis : int, optional
+        Axis in the `yi` array corresponding to the x-coordinate values.
+
+    Returns
+    -------
+    d : ndarray
+        If the interpolator's values are R-D then the
+        returned array will be the number of derivatives by N by R.
+        If `x` is a scalar, the middle dimension will be dropped; if
+        the `yi` are scalars then the last dimension will be dropped.
+
+    See Also
+    --------
+    KroghInterpolator : Krogh interpolator
+
+    Notes
+    -----
+    Construction of the interpolating polynomial is a relatively expensive
+    process. If you want to evaluate it repeatedly consider using the class
+    KroghInterpolator (which is what this function uses).
+
+    Examples
+    --------
+    We can interpolate 2D observed data using Krogh interpolation:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import krogh_interpolate
+    >>> x_observed = np.linspace(0.0, 10.0, 11)
+    >>> y_observed = np.sin(x_observed)
+    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
+    >>> y = krogh_interpolate(x_observed, y_observed, x)
+    >>> plt.plot(x_observed, y_observed, "o", label="observation")
+    >>> plt.plot(x, y, label="krogh interpolation")
+    >>> plt.legend()
+    >>> plt.show()
+    """
+
+    P = KroghInterpolator(xi, yi, axis=axis)
+    if der == 0:
+        return P(x)
+    elif _isscalar(der):
+        return P.derivative(x, der=der)
+    else:
+        return P.derivatives(x, der=np.amax(der)+1)[der]
+
+
+def approximate_taylor_polynomial(f,x,degree,scale,order=None):
+    """
+    Estimate the Taylor polynomial of f at x by polynomial fitting.
+
+    Parameters
+    ----------
+    f : callable
+        The function whose Taylor polynomial is sought. Should accept
+        a vector of `x` values.
+    x : scalar
+        The point at which the polynomial is to be evaluated.
+    degree : int
+        The degree of the Taylor polynomial
+    scale : scalar
+        The width of the interval to use to evaluate the Taylor polynomial.
+        Function values spread over a range this wide are used to fit the
+        polynomial. Must be chosen carefully.
+    order : int or None, optional
+        The order of the polynomial to be used in the fitting; `f` will be
+        evaluated ``order+1`` times. If None, use `degree`.
+
+    Returns
+    -------
+    p : poly1d instance
+        The Taylor polynomial (translated to the origin, so that
+        for example p(0)=f(x)).
+
+    Notes
+    -----
+    The appropriate choice of "scale" is a trade-off; too large and the
+    function differs from its Taylor polynomial too much to get a good
+    answer, too small and round-off errors overwhelm the higher-order terms.
+    The algorithm used becomes numerically unstable around order 30 even
+    under ideal circumstances.
+
+    Choosing order somewhat larger than degree may improve the higher-order
+    terms.
+
+    Examples
+    --------
+    We can calculate Taylor approximation polynomials of sin function with
+    various degrees:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import approximate_taylor_polynomial
+    >>> x = np.linspace(-10.0, 10.0, num=100)
+    >>> plt.plot(x, np.sin(x), label="sin curve")
+    >>> for degree in np.arange(1, 15, step=2):
+    ...     sin_taylor = approximate_taylor_polynomial(np.sin, 0, degree, 1,
+    ...                                                order=degree + 2)
+    ...     plt.plot(x, sin_taylor(x), label=f"degree={degree}")
+    >>> plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left',
+    ...            borderaxespad=0.0, shadow=True)
+    >>> plt.tight_layout()
+    >>> plt.axis([-10, 10, -10, 10])
+    >>> plt.show()
+
+    """
+    if order is None:
+        order = degree
+
+    n = order+1
+    # Choose n points that cluster near the endpoints of the interval in
+    # a way that avoids the Runge phenomenon. Ensure, by including the
+    # endpoint or not as appropriate, that one point always falls at x
+    # exactly.
+    xs = scale*np.cos(np.linspace(0,np.pi,n,endpoint=n % 1)) + x
+
+    P = KroghInterpolator(xs, f(xs))
+    d = P.derivatives(x,der=degree+1)
+
+    return np.poly1d((d/factorial(np.arange(degree+1)))[::-1])
+
+
+class BarycentricInterpolator(_Interpolator1DWithDerivatives):
+    r"""Interpolating polynomial for a set of points.
+
+    Constructs a polynomial that passes through a given set of points.
+    Allows evaluation of the polynomial and all its derivatives,
+    efficient changing of the y-values to be interpolated,
+    and updating by adding more x- and y-values.
+
+    For reasons of numerical stability, this function does not compute
+    the coefficients of the polynomial.
+
+    The values `yi` need to be provided before the function is
+    evaluated, but none of the preprocessing depends on them, so rapid
+    updates are possible.
+
+    Parameters
+    ----------
+    xi : array_like, shape (npoints, )
+        1-D array of x coordinates of the points the polynomial
+        should pass through
+    yi : array_like, shape (..., npoints, ...), optional
+        N-D array of y coordinates of the points the polynomial should pass through.
+        If None, the y values will be supplied later via the `set_y` method.
+        The length of `yi` along the interpolation axis must be equal to the length
+        of `xi`. Use the ``axis`` parameter to select correct axis.
+    axis : int, optional
+        Axis in the yi array corresponding to the x-coordinate values. Defaults
+        to ``axis=0``.
+    wi : array_like, optional
+        The barycentric weights for the chosen interpolation points `xi`.
+        If absent or None, the weights will be computed from `xi` (default).
+        This allows for the reuse of the weights `wi` if several interpolants
+        are being calculated using the same nodes `xi`, without re-computation.
+    rng : {None, int, `numpy.random.Generator`}, optional
+        If `rng` is passed by keyword, types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rng` is already a ``Generator`` instance, then the provided instance is
+        used. Specify `rng` for repeatable interpolation.
+
+        If this argument `random_state` is passed by keyword,
+        legacy behavior for the argument `random_state` applies:
+
+        - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
+          singleton is used.
+        - If `random_state` is an int, a new ``RandomState`` instance is used,
+          seeded with `random_state`.
+        - If `random_state` is already a ``Generator`` or ``RandomState`` instance then
+          that instance is used.
+
+        .. versionchanged:: 1.15.0
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator` this keyword was changed from `random_state` to `rng`.
+            For an interim period, both keywords will continue to work (only specify
+            one of them). After the interim period using the `random_state` keyword will emit
+            warnings. The behavior of the `random_state` and `rng` keywords is outlined above.
+
+    Notes
+    -----
+    This class uses a "barycentric interpolation" method that treats
+    the problem as a special case of rational function interpolation.
+    This algorithm is quite stable, numerically, but even in a world of
+    exact computation, unless the x coordinates are chosen very
+    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
+    polynomial interpolation itself is a very ill-conditioned process
+    due to the Runge phenomenon.
+
+    Based on Berrut and Trefethen 2004, "Barycentric Lagrange Interpolation".
+
+    Examples
+    --------
+    To produce a quintic barycentric interpolant approximating the function
+    :math:`\sin x`, and its first four derivatives, using six randomly-spaced
+    nodes in :math:`(0, \frac{\pi}{2})`:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import BarycentricInterpolator
+    >>> rng = np.random.default_rng()
+    >>> xi = rng.random(6) * np.pi/2
+    >>> f, f_d1, f_d2, f_d3, f_d4 = np.sin, np.cos, lambda x: -np.sin(x), lambda x: -np.cos(x), np.sin
+    >>> P = BarycentricInterpolator(xi, f(xi), random_state=rng)
+    >>> fig, axs = plt.subplots(5, 1, sharex=True, layout='constrained', figsize=(7,10))
+    >>> x = np.linspace(0, np.pi, 100)
+    >>> axs[0].plot(x, P(x), 'r:', x, f(x), 'k--', xi, f(xi), 'xk')
+    >>> axs[1].plot(x, P.derivative(x), 'r:', x, f_d1(x), 'k--', xi, f_d1(xi), 'xk')
+    >>> axs[2].plot(x, P.derivative(x, 2), 'r:', x, f_d2(x), 'k--', xi, f_d2(xi), 'xk')
+    >>> axs[3].plot(x, P.derivative(x, 3), 'r:', x, f_d3(x), 'k--', xi, f_d3(xi), 'xk')
+    >>> axs[4].plot(x, P.derivative(x, 4), 'r:', x, f_d4(x), 'k--', xi, f_d4(xi), 'xk')
+    >>> axs[0].set_xlim(0, np.pi)
+    >>> axs[4].set_xlabel(r"$x$")
+    >>> axs[4].set_xticks([i * np.pi / 4 for i in range(5)],
+    ...                   ["0", r"$\frac{\pi}{4}$", r"$\frac{\pi}{2}$", r"$\frac{3\pi}{4}$", r"$\pi$"])
+    >>> axs[0].set_ylabel("$f(x)$")
+    >>> axs[1].set_ylabel("$f'(x)$")
+    >>> axs[2].set_ylabel("$f''(x)$")
+    >>> axs[3].set_ylabel("$f^{(3)}(x)$")
+    >>> axs[4].set_ylabel("$f^{(4)}(x)$")
+    >>> labels = ['Interpolation nodes', 'True function $f$', 'Barycentric interpolation']
+    >>> axs[0].legend(axs[0].get_lines()[::-1], labels, bbox_to_anchor=(0., 1.02, 1., .102),
+    ...               loc='lower left', ncols=3, mode="expand", borderaxespad=0., frameon=False)
+    >>> plt.show()
+    """ # numpy/numpydoc#87  # noqa: E501
+
+    @_transition_to_rng("random_state", replace_doc=False)
+    def __init__(self, xi, yi=None, axis=0, *, wi=None, rng=None):
+        super().__init__(xi, yi, axis)
+
+        rng = check_random_state(rng)
+
+        self.xi = np.asarray(xi, dtype=np.float64)
+        self.set_yi(yi)
+        self.n = len(self.xi)
+
+        # cache derivative object to avoid re-computing the weights with every call.
+        self._diff_cij = None
+
+        if wi is not None:
+            self.wi = wi
+        else:
+            # See page 510 of Berrut and Trefethen 2004 for an explanation of the
+            # capacity scaling and the suggestion of using a random permutation of
+            # the input factors.
+            # At the moment, the permutation is not performed for xi that are
+            # appended later through the add_xi interface. It's not clear to me how
+            # to implement that and it seems that most situations that require
+            # these numerical stability improvements will be able to provide all
+            # the points to the constructor.
+            self._inv_capacity = 4.0 / (np.max(self.xi) - np.min(self.xi))
+            permute = rng.permutation(self.n, )
+            inv_permute = np.zeros(self.n, dtype=np.int32)
+            inv_permute[permute] = np.arange(self.n)
+            self.wi = np.zeros(self.n)
+
+            for i in range(self.n):
+                dist = self._inv_capacity * (self.xi[i] - self.xi[permute])
+                dist[inv_permute[i]] = 1.0
+                prod = np.prod(dist)
+                if prod == 0.0:
+                    raise ValueError("Interpolation points xi must be"
+                                     " distinct.")
+                self.wi[i] = 1.0 / prod
+
+    def set_yi(self, yi, axis=None):
+        """
+        Update the y values to be interpolated
+
+        The barycentric interpolation algorithm requires the calculation
+        of weights, but these depend only on the `xi`. The `yi` can be changed
+        at any time.
+
+        Parameters
+        ----------
+        yi : array_like
+            The y-coordinates of the points the polynomial will pass through.
+            If None, the y values must be supplied later.
+        axis : int, optional
+            Axis in the `yi` array corresponding to the x-coordinate values.
+
+        """
+        if yi is None:
+            self.yi = None
+            return
+        self._set_yi(yi, xi=self.xi, axis=axis)
+        self.yi = self._reshape_yi(yi)
+        self.n, self.r = self.yi.shape
+        self._diff_baryint = None
+
+    def add_xi(self, xi, yi=None):
+        """
+        Add more x values to the set to be interpolated
+
+        The barycentric interpolation algorithm allows easy updating by
+        adding more points for the polynomial to pass through.
+
+        Parameters
+        ----------
+        xi : array_like
+            The x coordinates of the points that the polynomial should pass
+            through.
+        yi : array_like, optional
+            The y coordinates of the points the polynomial should pass through.
+            Should have shape ``(xi.size, R)``; if R > 1 then the polynomial is
+            vector-valued.
+            If `yi` is not given, the y values will be supplied later. `yi`
+            should be given if and only if the interpolator has y values
+            specified.
+
+        Notes
+        -----
+        The new points added by `add_xi` are not randomly permuted
+        so there is potential for numerical instability,
+        especially for a large number of points. If this
+        happens, please reconstruct interpolation from scratch instead.
+        """
+        if yi is not None:
+            if self.yi is None:
+                raise ValueError("No previous yi value to update!")
+            yi = self._reshape_yi(yi, check=True)
+            self.yi = np.vstack((self.yi,yi))
+        else:
+            if self.yi is not None:
+                raise ValueError("No update to yi provided!")
+        old_n = self.n
+        self.xi = np.concatenate((self.xi,xi))
+        self.n = len(self.xi)
+        self.wi **= -1
+        old_wi = self.wi
+        self.wi = np.zeros(self.n)
+        self.wi[:old_n] = old_wi
+        for j in range(old_n, self.n):
+            self.wi[:j] *= self._inv_capacity * (self.xi[j]-self.xi[:j])
+            self.wi[j] = np.multiply.reduce(
+                self._inv_capacity * (self.xi[:j]-self.xi[j])
+            )
+        self.wi **= -1
+        self._diff_cij = None
+        self._diff_baryint = None
+
+    def __call__(self, x):
+        """Evaluate the interpolating polynomial at the points x
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the interpolant.
+
+        Returns
+        -------
+        y : array_like
+            Interpolated values. Shape is determined by replacing
+            the interpolation axis in the original array with the shape of `x`.
+
+        Notes
+        -----
+        Currently the code computes an outer product between `x` and the
+        weights, that is, it constructs an intermediate array of size
+        ``(N, len(x))``, where N is the degree of the polynomial.
+        """
+        return _Interpolator1D.__call__(self, x)
+
+    def _evaluate(self, x):
+        if x.size == 0:
+            p = np.zeros((0, self.r), dtype=self.dtype)
+        else:
+            c = x[..., np.newaxis] - self.xi
+            z = c == 0
+            c[z] = 1
+            c = self.wi / c
+            with np.errstate(divide='ignore'):
+                p = np.dot(c, self.yi) / np.sum(c, axis=-1)[..., np.newaxis]
+            # Now fix where x==some xi
+            r = np.nonzero(z)
+            if len(r) == 1:  # evaluation at a scalar
+                if len(r[0]) > 0:  # equals one of the points
+                    p = self.yi[r[0][0]]
+            else:
+                p[r[:-1]] = self.yi[r[-1]]
+        return p
+
+    def derivative(self, x, der=1):
+        """
+        Evaluate a single derivative of the polynomial at the point x.
+
+        Parameters
+        ----------
+        x : array_like
+            Point or points at which to evaluate the derivatives
+        der : integer, optional
+            Which derivative to evaluate (default: first derivative).
+            This number includes the function value as 0th derivative.
+
+        Returns
+        -------
+        d : ndarray
+            Derivative interpolated at the x-points. Shape of `d` is
+            determined by replacing the interpolation axis in the
+            original array with the shape of `x`.
+        """
+        x, x_shape = self._prepare_x(x)
+        y = self._evaluate_derivatives(x, der+1, all_lower=False)
+        return self._finish_y(y, x_shape)
+
+    def _evaluate_derivatives(self, x, der=None, all_lower=True):
+        # NB: der here is not the order of the highest derivative;
+        # instead, it is the size of the derivatives matrix that
+        # would be returned with all_lower=True, including the
+        # '0th' derivative (the undifferentiated function).
+        # E.g. to evaluate the 5th derivative alone, call
+        # _evaluate_derivatives(x, der=6, all_lower=False).
+
+        if (not all_lower) and (x.size == 0 or self.r == 0):
+            return np.zeros((0, self.r), dtype=self.dtype)
+
+        if (not all_lower) and der == 1:
+            return self._evaluate(x)
+
+        if (not all_lower) and (der > self.n):
+            return np.zeros((len(x), self.r), dtype=self.dtype)
+
+        if der is None:
+            der = self.n
+
+        if all_lower and (x.size == 0 or self.r == 0):
+            return np.zeros((der, len(x), self.r), dtype=self.dtype)
+
+        if self._diff_cij is None:
+            # c[i,j] = xi[i] - xi[j]
+            c = self.xi[:, np.newaxis] - self.xi
+
+            # avoid division by 0 (diagonal entries are so far zero by construction)
+            np.fill_diagonal(c, 1)
+
+            # c[i,j] = (w[j] / w[i]) / (xi[i] - xi[j]) (equation 9.4)
+            c = self.wi/ (c * self.wi[..., np.newaxis])
+
+            # fill in correct diagonal entries: each column sums to 0
+            np.fill_diagonal(c, 0)
+
+            # calculate diagonal
+            # c[j,j] = -sum_{i != j} c[i,j] (equation 9.5)
+            d = -c.sum(axis=1)
+            # c[i,j] = l_j(x_i)
+            np.fill_diagonal(c, d)
+
+            self._diff_cij = c
+
+        if self._diff_baryint is None:
+            # initialise and cache derivative interpolator and cijs;
+            # reuse weights wi (which depend only on interpolation points xi),
+            # to avoid unnecessary re-computation
+            self._diff_baryint = BarycentricInterpolator(xi=self.xi,
+                                                         yi=self._diff_cij @ self.yi,
+                                                         wi=self.wi)
+            self._diff_baryint._diff_cij = self._diff_cij
+
+        if all_lower:
+            # assemble matrix of derivatives from order 0 to order der-1,
+            # in the format required by _Interpolator1DWithDerivatives.
+            cn = np.zeros((der, len(x), self.r), dtype=self.dtype)
+            for d in range(der):
+                cn[d, :, :] = self._evaluate_derivatives(x, d+1, all_lower=False)
+            return cn
+
+        # recursively evaluate only the derivative requested
+        return self._diff_baryint._evaluate_derivatives(x, der-1, all_lower=False)
+
+
+def barycentric_interpolate(xi, yi, x, axis=0, *, der=0, rng=None):
+    """
+    Convenience function for polynomial interpolation.
+
+    Constructs a polynomial that passes through a given set of points,
+    then evaluates the polynomial. For reasons of numerical stability,
+    this function does not compute the coefficients of the polynomial.
+
+    This function uses a "barycentric interpolation" method that treats
+    the problem as a special case of rational function interpolation.
+    This algorithm is quite stable, numerically, but even in a world of
+    exact computation, unless the `x` coordinates are chosen very
+    carefully - Chebyshev zeros (e.g., cos(i*pi/n)) are a good choice -
+    polynomial interpolation itself is a very ill-conditioned process
+    due to the Runge phenomenon.
+
+    Parameters
+    ----------
+    xi : array_like
+        1-D array of x coordinates of the points the polynomial should
+        pass through
+    yi : array_like
+        The y coordinates of the points the polynomial should pass through.
+    x : scalar or array_like
+        Point or points at which to evaluate the interpolant.
+    axis : int, optional
+        Axis in the `yi` array corresponding to the x-coordinate values.
+    der : int or list or None, optional
+        How many derivatives to evaluate, or None for all potentially
+        nonzero derivatives (that is, a number equal to the number
+        of points), or a list of derivatives to evaluate. This number
+        includes the function value as the '0th' derivative.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    y : scalar or array_like
+        Interpolated values. Shape is determined by replacing
+        the interpolation axis in the original array with the shape of `x`.
+
+    See Also
+    --------
+    BarycentricInterpolator : Barycentric interpolator
+
+    Notes
+    -----
+    Construction of the interpolation weights is a relatively slow process.
+    If you want to call this many times with the same xi (but possibly
+    varying yi or x) you should use the class `BarycentricInterpolator`.
+    This is what this function uses internally.
+
+    Examples
+    --------
+    We can interpolate 2D observed data using barycentric interpolation:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import barycentric_interpolate
+    >>> x_observed = np.linspace(0.0, 10.0, 11)
+    >>> y_observed = np.sin(x_observed)
+    >>> x = np.linspace(min(x_observed), max(x_observed), num=100)
+    >>> y = barycentric_interpolate(x_observed, y_observed, x)
+    >>> plt.plot(x_observed, y_observed, "o", label="observation")
+    >>> plt.plot(x, y, label="barycentric interpolation")
+    >>> plt.legend()
+    >>> plt.show()
+
+    """
+    P = BarycentricInterpolator(xi, yi, axis=axis, rng=rng)
+    if der == 0:
+        return P(x)
+    elif _isscalar(der):
+        return P.derivative(x, der=der)
+    else:
+        return P.derivatives(x, der=np.amax(der)+1)[der]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbf.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed52230dd1cce678e56ca4427e10bafd07e501c0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbf.py
@@ -0,0 +1,290 @@
+"""rbf - Radial basis functions for interpolation/smoothing scattered N-D data.
+
+Written by John Travers , February 2007
+Based closely on Matlab code by Alex Chirokov
+Additional, large, improvements by Robert Hetland
+Some additional alterations by Travis Oliphant
+Interpolation with multi-dimensional target domain by Josua Sassen
+
+Permission to use, modify, and distribute this software is given under the
+terms of the SciPy (BSD style) license. See LICENSE.txt that came with
+this distribution for specifics.
+
+NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+Copyright (c) 2006-2007, Robert Hetland 
+Copyright (c) 2007, John Travers 
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+    * Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer.
+
+    * Redistributions in binary form must reproduce the above
+       copyright notice, this list of conditions and the following
+       disclaimer in the documentation and/or other materials provided
+       with the distribution.
+
+    * Neither the name of Robert Hetland nor the names of any
+       contributors may be used to endorse or promote products derived
+       from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+"""
+import numpy as np
+
+from scipy import linalg
+from scipy.special import xlogy
+from scipy.spatial.distance import cdist, pdist, squareform
+
+__all__ = ['Rbf']
+
+
+class Rbf:
+    """
+    Rbf(*args, **kwargs)
+
+    A class for radial basis function interpolation of functions from
+    N-D scattered data to an M-D domain.
+
+    .. legacy:: class
+
+        `Rbf` is legacy code, for new usage please use `RBFInterpolator`
+        instead.
+
+    Parameters
+    ----------
+    *args : arrays
+        x, y, z, ..., d, where x, y, z, ... are the coordinates of the nodes
+        and d is the array of values at the nodes
+    function : str or callable, optional
+        The radial basis function, based on the radius, r, given by the norm
+        (default is Euclidean distance); the default is 'multiquadric'::
+
+            'multiquadric': sqrt((r/self.epsilon)**2 + 1)
+            'inverse': 1.0/sqrt((r/self.epsilon)**2 + 1)
+            'gaussian': exp(-(r/self.epsilon)**2)
+            'linear': r
+            'cubic': r**3
+            'quintic': r**5
+            'thin_plate': r**2 * log(r)
+
+        If callable, then it must take 2 arguments (self, r). The epsilon
+        parameter will be available as self.epsilon. Other keyword
+        arguments passed in will be available as well.
+
+    epsilon : float, optional
+        Adjustable constant for gaussian or multiquadrics functions
+        - defaults to approximate average distance between nodes (which is
+        a good start).
+    smooth : float, optional
+        Values greater than zero increase the smoothness of the
+        approximation. 0 is for interpolation (default), the function will
+        always go through the nodal points in this case.
+    norm : str, callable, optional
+        A function that returns the 'distance' between two points, with
+        inputs as arrays of positions (x, y, z, ...), and an output as an
+        array of distance. E.g., the default: 'euclidean', such that the result
+        is a matrix of the distances from each point in ``x1`` to each point in
+        ``x2``. For more options, see documentation of
+        `scipy.spatial.distances.cdist`.
+    mode : str, optional
+        Mode of the interpolation, can be '1-D' (default) or 'N-D'. When it is
+        '1-D' the data `d` will be considered as 1-D and flattened
+        internally. When it is 'N-D' the data `d` is assumed to be an array of
+        shape (n_samples, m), where m is the dimension of the target domain.
+
+
+    Attributes
+    ----------
+    N : int
+        The number of data points (as determined by the input arrays).
+    di : ndarray
+        The 1-D array of data values at each of the data coordinates `xi`.
+    xi : ndarray
+        The 2-D array of data coordinates.
+    function : str or callable
+        The radial basis function. See description under Parameters.
+    epsilon : float
+        Parameter used by gaussian or multiquadrics functions. See Parameters.
+    smooth : float
+        Smoothing parameter. See description under Parameters.
+    norm : str or callable
+        The distance function. See description under Parameters.
+    mode : str
+        Mode of the interpolation. See description under Parameters.
+    nodes : ndarray
+        A 1-D array of node values for the interpolation.
+    A : internal property, do not use
+
+    See Also
+    --------
+    RBFInterpolator
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.interpolate import Rbf
+    >>> rng = np.random.default_rng()
+    >>> x, y, z, d = rng.random((4, 50))
+    >>> rbfi = Rbf(x, y, z, d)  # radial basis function interpolator instance
+    >>> xi = yi = zi = np.linspace(0, 1, 20)
+    >>> di = rbfi(xi, yi, zi)   # interpolated values
+    >>> di.shape
+    (20,)
+
+    """
+    # Available radial basis functions that can be selected as strings;
+    # they all start with _h_ (self._init_function relies on that)
+    def _h_multiquadric(self, r):
+        return np.sqrt((1.0/self.epsilon*r)**2 + 1)
+
+    def _h_inverse_multiquadric(self, r):
+        return 1.0/np.sqrt((1.0/self.epsilon*r)**2 + 1)
+
+    def _h_gaussian(self, r):
+        return np.exp(-(1.0/self.epsilon*r)**2)
+
+    def _h_linear(self, r):
+        return r
+
+    def _h_cubic(self, r):
+        return r**3
+
+    def _h_quintic(self, r):
+        return r**5
+
+    def _h_thin_plate(self, r):
+        return xlogy(r**2, r)
+
+    # Setup self._function and do smoke test on initial r
+    def _init_function(self, r):
+        if isinstance(self.function, str):
+            self.function = self.function.lower()
+            _mapped = {'inverse': 'inverse_multiquadric',
+                       'inverse multiquadric': 'inverse_multiquadric',
+                       'thin-plate': 'thin_plate'}
+            if self.function in _mapped:
+                self.function = _mapped[self.function]
+
+            func_name = "_h_" + self.function
+            if hasattr(self, func_name):
+                self._function = getattr(self, func_name)
+            else:
+                functionlist = [x[3:] for x in dir(self)
+                                if x.startswith('_h_')]
+                raise ValueError("function must be a callable or one of " +
+                                 ", ".join(functionlist))
+            self._function = getattr(self, "_h_"+self.function)
+        elif callable(self.function):
+            allow_one = False
+            if hasattr(self.function, 'func_code') or \
+               hasattr(self.function, '__code__'):
+                val = self.function
+                allow_one = True
+            elif hasattr(self.function, "__call__"):
+                val = self.function.__call__.__func__
+            else:
+                raise ValueError("Cannot determine number of arguments to "
+                                 "function")
+
+            argcount = val.__code__.co_argcount
+            if allow_one and argcount == 1:
+                self._function = self.function
+            elif argcount == 2:
+                self._function = self.function.__get__(self, Rbf)
+            else:
+                raise ValueError("Function argument must take 1 or 2 "
+                                 "arguments.")
+
+        a0 = self._function(r)
+        if a0.shape != r.shape:
+            raise ValueError("Callable must take array and return array of "
+                             "the same shape")
+        return a0
+
+    def __init__(self, *args, **kwargs):
+        # `args` can be a variable number of arrays; we flatten them and store
+        # them as a single 2-D array `xi` of shape (n_args-1, array_size),
+        # plus a 1-D array `di` for the values.
+        # All arrays must have the same number of elements
+        self.xi = np.asarray([np.asarray(a, dtype=np.float64).flatten()
+                              for a in args[:-1]])
+        self.N = self.xi.shape[-1]
+
+        self.mode = kwargs.pop('mode', '1-D')
+
+        if self.mode == '1-D':
+            self.di = np.asarray(args[-1]).flatten()
+            self._target_dim = 1
+        elif self.mode == 'N-D':
+            self.di = np.asarray(args[-1])
+            self._target_dim = self.di.shape[-1]
+        else:
+            raise ValueError("Mode has to be 1-D or N-D.")
+
+        if not all([x.size == self.di.shape[0] for x in self.xi]):
+            raise ValueError("All arrays must be equal length.")
+
+        self.norm = kwargs.pop('norm', 'euclidean')
+        self.epsilon = kwargs.pop('epsilon', None)
+        if self.epsilon is None:
+            # default epsilon is the "the average distance between nodes" based
+            # on a bounding hypercube
+            ximax = np.amax(self.xi, axis=1)
+            ximin = np.amin(self.xi, axis=1)
+            edges = ximax - ximin
+            edges = edges[np.nonzero(edges)]
+            self.epsilon = np.power(np.prod(edges)/self.N, 1.0/edges.size)
+
+        self.smooth = kwargs.pop('smooth', 0.0)
+        self.function = kwargs.pop('function', 'multiquadric')
+
+        # attach anything left in kwargs to self for use by any user-callable
+        # function or to save on the object returned.
+        for item, value in kwargs.items():
+            setattr(self, item, value)
+
+        # Compute weights
+        if self._target_dim > 1:  # If we have more than one target dimension,
+            # we first factorize the matrix
+            self.nodes = np.zeros((self.N, self._target_dim), dtype=self.di.dtype)
+            lu, piv = linalg.lu_factor(self.A)
+            for i in range(self._target_dim):
+                self.nodes[:, i] = linalg.lu_solve((lu, piv), self.di[:, i])
+        else:
+            self.nodes = linalg.solve(self.A, self.di)
+
+    @property
+    def A(self):
+        # this only exists for backwards compatibility: self.A was available
+        # and, at least technically, public.
+        r = squareform(pdist(self.xi.T, self.norm))  # Pairwise norm
+        return self._init_function(r) - np.eye(self.N)*self.smooth
+
+    def _call_norm(self, x1, x2):
+        return cdist(x1.T, x2.T, self.norm)
+
+    def __call__(self, *args):
+        args = [np.asarray(x) for x in args]
+        if not all([x.shape == y.shape for x in args for y in args]):
+            raise ValueError("Array lengths must be equal")
+        if self._target_dim > 1:
+            shp = args[0].shape + (self._target_dim,)
+        else:
+            shp = args[0].shape
+        xa = np.asarray([a.flatten() for a in args], dtype=np.float64)
+        r = self._call_norm(xa, self.xi)
+        return np.dot(self._function(r), self.nodes).reshape(shp)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp.py
new file mode 100644
index 0000000000000000000000000000000000000000..6690e6ccf7d5499db10efffb0ef1c0139a90d2ba
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp.py
@@ -0,0 +1,550 @@
+"""Module for RBF interpolation."""
+import warnings
+from itertools import combinations_with_replacement
+
+import numpy as np
+from numpy.linalg import LinAlgError
+from scipy.spatial import KDTree
+from scipy.special import comb
+from scipy.linalg.lapack import dgesv  # type: ignore[attr-defined]
+
+from ._rbfinterp_pythran import (_build_system,
+                                 _build_evaluation_coefficients,
+                                 _polynomial_matrix)
+
+
+__all__ = ["RBFInterpolator"]
+
+
+# These RBFs are implemented.
+_AVAILABLE = {
+    "linear",
+    "thin_plate_spline",
+    "cubic",
+    "quintic",
+    "multiquadric",
+    "inverse_multiquadric",
+    "inverse_quadratic",
+    "gaussian"
+    }
+
+
+# The shape parameter does not need to be specified when using these RBFs.
+_SCALE_INVARIANT = {"linear", "thin_plate_spline", "cubic", "quintic"}
+
+
+# For RBFs that are conditionally positive definite of order m, the interpolant
+# should include polynomial terms with degree >= m - 1. Define the minimum
+# degrees here. These values are from Chapter 8 of Fasshauer's "Meshfree
+# Approximation Methods with MATLAB". The RBFs that are not in this dictionary
+# are positive definite and do not need polynomial terms.
+_NAME_TO_MIN_DEGREE = {
+    "multiquadric": 0,
+    "linear": 0,
+    "thin_plate_spline": 1,
+    "cubic": 1,
+    "quintic": 2
+    }
+
+
+def _monomial_powers(ndim, degree):
+    """Return the powers for each monomial in a polynomial.
+
+    Parameters
+    ----------
+    ndim : int
+        Number of variables in the polynomial.
+    degree : int
+        Degree of the polynomial.
+
+    Returns
+    -------
+    (nmonos, ndim) int ndarray
+        Array where each row contains the powers for each variable in a
+        monomial.
+
+    """
+    nmonos = comb(degree + ndim, ndim, exact=True)
+    out = np.zeros((nmonos, ndim), dtype=np.dtype("long"))
+    count = 0
+    for deg in range(degree + 1):
+        for mono in combinations_with_replacement(range(ndim), deg):
+            # `mono` is a tuple of variables in the current monomial with
+            # multiplicity indicating power (e.g., (0, 1, 1) represents x*y**2)
+            for var in mono:
+                out[count, var] += 1
+
+            count += 1
+
+    return out
+
+
+def _build_and_solve_system(y, d, smoothing, kernel, epsilon, powers):
+    """Build and solve the RBF interpolation system of equations.
+
+    Parameters
+    ----------
+    y : (P, N) float ndarray
+        Data point coordinates.
+    d : (P, S) float ndarray
+        Data values at `y`.
+    smoothing : (P,) float ndarray
+        Smoothing parameter for each data point.
+    kernel : str
+        Name of the RBF.
+    epsilon : float
+        Shape parameter.
+    powers : (R, N) int ndarray
+        The exponents for each monomial in the polynomial.
+
+    Returns
+    -------
+    coeffs : (P + R, S) float ndarray
+        Coefficients for each RBF and monomial.
+    shift : (N,) float ndarray
+        Domain shift used to create the polynomial matrix.
+    scale : (N,) float ndarray
+        Domain scaling used to create the polynomial matrix.
+
+    """
+    lhs, rhs, shift, scale = _build_system(
+        y, d, smoothing, kernel, epsilon, powers
+        )
+    _, _, coeffs, info = dgesv(lhs, rhs, overwrite_a=True, overwrite_b=True)
+    if info < 0:
+        raise ValueError(f"The {-info}-th argument had an illegal value.")
+    elif info > 0:
+        msg = "Singular matrix."
+        nmonos = powers.shape[0]
+        if nmonos > 0:
+            pmat = _polynomial_matrix((y - shift)/scale, powers)
+            rank = np.linalg.matrix_rank(pmat)
+            if rank < nmonos:
+                msg = (
+                    "Singular matrix. The matrix of monomials evaluated at "
+                    "the data point coordinates does not have full column "
+                    f"rank ({rank}/{nmonos})."
+                    )
+
+        raise LinAlgError(msg)
+
+    return shift, scale, coeffs
+
+
+class RBFInterpolator:
+    """Radial basis function (RBF) interpolation in N dimensions.
+
+    Parameters
+    ----------
+    y : (npoints, ndims) array_like
+        2-D array of data point coordinates.
+    d : (npoints, ...) array_like
+        N-D array of data values at `y`. The length of `d` along the first
+        axis must be equal to the length of `y`. Unlike some interpolators, the
+        interpolation axis cannot be changed.
+    neighbors : int, optional
+        If specified, the value of the interpolant at each evaluation point
+        will be computed using only this many nearest data points. All the data
+        points are used by default.
+    smoothing : float or (npoints, ) array_like, optional
+        Smoothing parameter. The interpolant perfectly fits the data when this
+        is set to 0. For large values, the interpolant approaches a least
+        squares fit of a polynomial with the specified degree. Default is 0.
+    kernel : str, optional
+        Type of RBF. This should be one of
+
+            - 'linear'               : ``-r``
+            - 'thin_plate_spline'    : ``r**2 * log(r)``
+            - 'cubic'                : ``r**3``
+            - 'quintic'              : ``-r**5``
+            - 'multiquadric'         : ``-sqrt(1 + r**2)``
+            - 'inverse_multiquadric' : ``1/sqrt(1 + r**2)``
+            - 'inverse_quadratic'    : ``1/(1 + r**2)``
+            - 'gaussian'             : ``exp(-r**2)``
+
+        Default is 'thin_plate_spline'.
+    epsilon : float, optional
+        Shape parameter that scales the input to the RBF. If `kernel` is
+        'linear', 'thin_plate_spline', 'cubic', or 'quintic', this defaults to
+        1 and can be ignored because it has the same effect as scaling the
+        smoothing parameter. Otherwise, this must be specified.
+    degree : int, optional
+        Degree of the added polynomial. For some RBFs the interpolant may not
+        be well-posed if the polynomial degree is too small. Those RBFs and
+        their corresponding minimum degrees are
+
+            - 'multiquadric'      : 0
+            - 'linear'            : 0
+            - 'thin_plate_spline' : 1
+            - 'cubic'             : 1
+            - 'quintic'           : 2
+
+        The default value is the minimum degree for `kernel` or 0 if there is
+        no minimum degree. Set this to -1 for no added polynomial.
+
+    Notes
+    -----
+    An RBF is a scalar valued function in N-dimensional space whose value at
+    :math:`x` can be expressed in terms of :math:`r=||x - c||`, where :math:`c`
+    is the center of the RBF.
+
+    An RBF interpolant for the vector of data values :math:`d`, which are from
+    locations :math:`y`, is a linear combination of RBFs centered at :math:`y`
+    plus a polynomial with a specified degree. The RBF interpolant is written
+    as
+
+    .. math::
+        f(x) = K(x, y) a + P(x) b,
+
+    where :math:`K(x, y)` is a matrix of RBFs with centers at :math:`y`
+    evaluated at the points :math:`x`, and :math:`P(x)` is a matrix of
+    monomials, which span polynomials with the specified degree, evaluated at
+    :math:`x`. The coefficients :math:`a` and :math:`b` are the solution to the
+    linear equations
+
+    .. math::
+        (K(y, y) + \\lambda I) a + P(y) b = d
+
+    and
+
+    .. math::
+        P(y)^T a = 0,
+
+    where :math:`\\lambda` is a non-negative smoothing parameter that controls
+    how well we want to fit the data. The data are fit exactly when the
+    smoothing parameter is 0.
+
+    The above system is uniquely solvable if the following requirements are
+    met:
+
+        - :math:`P(y)` must have full column rank. :math:`P(y)` always has full
+          column rank when `degree` is -1 or 0. When `degree` is 1,
+          :math:`P(y)` has full column rank if the data point locations are not
+          all collinear (N=2), coplanar (N=3), etc.
+        - If `kernel` is 'multiquadric', 'linear', 'thin_plate_spline',
+          'cubic', or 'quintic', then `degree` must not be lower than the
+          minimum value listed above.
+        - If `smoothing` is 0, then each data point location must be distinct.
+
+    When using an RBF that is not scale invariant ('multiquadric',
+    'inverse_multiquadric', 'inverse_quadratic', or 'gaussian'), an appropriate
+    shape parameter must be chosen (e.g., through cross validation). Smaller
+    values for the shape parameter correspond to wider RBFs. The problem can
+    become ill-conditioned or singular when the shape parameter is too small.
+
+    The memory required to solve for the RBF interpolation coefficients
+    increases quadratically with the number of data points, which can become
+    impractical when interpolating more than about a thousand data points.
+    To overcome memory limitations for large interpolation problems, the
+    `neighbors` argument can be specified to compute an RBF interpolant for
+    each evaluation point using only the nearest data points.
+
+    .. versionadded:: 1.7.0
+
+    See Also
+    --------
+    NearestNDInterpolator
+    LinearNDInterpolator
+    CloughTocher2DInterpolator
+
+    References
+    ----------
+    .. [1] Fasshauer, G., 2007. Meshfree Approximation Methods with Matlab.
+        World Scientific Publishing Co.
+
+    .. [2] http://amadeus.math.iit.edu/~fass/603_ch3.pdf
+
+    .. [3] Wahba, G., 1990. Spline Models for Observational Data. SIAM.
+
+    .. [4] http://pages.stat.wisc.edu/~wahba/stat860public/lect/lect8/lect8.pdf
+
+    Examples
+    --------
+    Demonstrate interpolating scattered data to a grid in 2-D.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.interpolate import RBFInterpolator
+    >>> from scipy.stats.qmc import Halton
+
+    >>> rng = np.random.default_rng()
+    >>> xobs = 2*Halton(2, seed=rng).random(100) - 1
+    >>> yobs = np.sum(xobs, axis=1)*np.exp(-6*np.sum(xobs**2, axis=1))
+
+    >>> xgrid = np.mgrid[-1:1:50j, -1:1:50j]
+    >>> xflat = xgrid.reshape(2, -1).T
+    >>> yflat = RBFInterpolator(xobs, yobs)(xflat)
+    >>> ygrid = yflat.reshape(50, 50)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.pcolormesh(*xgrid, ygrid, vmin=-0.25, vmax=0.25, shading='gouraud')
+    >>> p = ax.scatter(*xobs.T, c=yobs, s=50, ec='k', vmin=-0.25, vmax=0.25)
+    >>> fig.colorbar(p)
+    >>> plt.show()
+
+    """
+
+    def __init__(self, y, d,
+                 neighbors=None,
+                 smoothing=0.0,
+                 kernel="thin_plate_spline",
+                 epsilon=None,
+                 degree=None):
+        y = np.asarray(y, dtype=float, order="C")
+        if y.ndim != 2:
+            raise ValueError("`y` must be a 2-dimensional array.")
+
+        ny, ndim = y.shape
+
+        d_dtype = complex if np.iscomplexobj(d) else float
+        d = np.asarray(d, dtype=d_dtype, order="C")
+        if d.shape[0] != ny:
+            raise ValueError(
+                f"Expected the first axis of `d` to have length {ny}."
+                )
+
+        d_shape = d.shape[1:]
+        d = d.reshape((ny, -1))
+        # If `d` is complex, convert it to a float array with twice as many
+        # columns. Otherwise, the LHS matrix would need to be converted to
+        # complex and take up 2x more memory than necessary.
+        d = d.view(float)
+
+        if np.isscalar(smoothing):
+            smoothing = np.full(ny, smoothing, dtype=float)
+        else:
+            smoothing = np.asarray(smoothing, dtype=float, order="C")
+            if smoothing.shape != (ny,):
+                raise ValueError(
+                    "Expected `smoothing` to be a scalar or have shape "
+                    f"({ny},)."
+                    )
+
+        kernel = kernel.lower()
+        if kernel not in _AVAILABLE:
+            raise ValueError(f"`kernel` must be one of {_AVAILABLE}.")
+
+        if epsilon is None:
+            if kernel in _SCALE_INVARIANT:
+                epsilon = 1.0
+            else:
+                raise ValueError(
+                    "`epsilon` must be specified if `kernel` is not one of "
+                    f"{_SCALE_INVARIANT}."
+                    )
+        else:
+            epsilon = float(epsilon)
+
+        min_degree = _NAME_TO_MIN_DEGREE.get(kernel, -1)
+        if degree is None:
+            degree = max(min_degree, 0)
+        else:
+            degree = int(degree)
+            if degree < -1:
+                raise ValueError("`degree` must be at least -1.")
+            elif -1 < degree < min_degree:
+                warnings.warn(
+                    f"`degree` should not be below {min_degree} except -1 "
+                    f"when `kernel` is '{kernel}'."
+                    f"The interpolant may not be uniquely "
+                    f"solvable, and the smoothing parameter may have an "
+                    f"unintuitive effect.",
+                    UserWarning, stacklevel=2
+                )
+
+        if neighbors is None:
+            nobs = ny
+        else:
+            # Make sure the number of nearest neighbors used for interpolation
+            # does not exceed the number of observations.
+            neighbors = int(min(neighbors, ny))
+            nobs = neighbors
+
+        powers = _monomial_powers(ndim, degree)
+        # The polynomial matrix must have full column rank in order for the
+        # interpolant to be well-posed, which is not possible if there are
+        # fewer observations than monomials.
+        if powers.shape[0] > nobs:
+            raise ValueError(
+                f"At least {powers.shape[0]} data points are required when "
+                f"`degree` is {degree} and the number of dimensions is {ndim}."
+                )
+
+        if neighbors is None:
+            shift, scale, coeffs = _build_and_solve_system(
+                y, d, smoothing, kernel, epsilon, powers
+                )
+
+            # Make these attributes private since they do not always exist.
+            self._shift = shift
+            self._scale = scale
+            self._coeffs = coeffs
+
+        else:
+            self._tree = KDTree(y)
+
+        self.y = y
+        self.d = d
+        self.d_shape = d_shape
+        self.d_dtype = d_dtype
+        self.neighbors = neighbors
+        self.smoothing = smoothing
+        self.kernel = kernel
+        self.epsilon = epsilon
+        self.powers = powers
+
+    def _chunk_evaluator(
+            self,
+            x,
+            y,
+            shift,
+            scale,
+            coeffs,
+            memory_budget=1000000
+    ):
+        """
+        Evaluate the interpolation while controlling memory consumption.
+        We chunk the input if we need more memory than specified.
+
+        Parameters
+        ----------
+        x : (Q, N) float ndarray
+            array of points on which to evaluate
+        y: (P, N) float ndarray
+            array of points on which we know function values
+        shift: (N, ) ndarray
+            Domain shift used to create the polynomial matrix.
+        scale : (N,) float ndarray
+            Domain scaling used to create the polynomial matrix.
+        coeffs: (P+R, S) float ndarray
+            Coefficients in front of basis functions
+        memory_budget: int
+            Total amount of memory (in units of sizeof(float)) we wish
+            to devote for storing the array of coefficients for
+            interpolated points. If we need more memory than that, we
+            chunk the input.
+
+        Returns
+        -------
+        (Q, S) float ndarray
+        Interpolated array
+        """
+        nx, ndim = x.shape
+        if self.neighbors is None:
+            nnei = len(y)
+        else:
+            nnei = self.neighbors
+        # in each chunk we consume the same space we already occupy
+        chunksize = memory_budget // (self.powers.shape[0] + nnei) + 1
+        if chunksize <= nx:
+            out = np.empty((nx, self.d.shape[1]), dtype=float)
+            for i in range(0, nx, chunksize):
+                vec = _build_evaluation_coefficients(
+                    x[i:i + chunksize, :],
+                    y,
+                    self.kernel,
+                    self.epsilon,
+                    self.powers,
+                    shift,
+                    scale)
+                out[i:i + chunksize, :] = np.dot(vec, coeffs)
+        else:
+            vec = _build_evaluation_coefficients(
+                x,
+                y,
+                self.kernel,
+                self.epsilon,
+                self.powers,
+                shift,
+                scale)
+            out = np.dot(vec, coeffs)
+        return out
+
+    def __call__(self, x):
+        """Evaluate the interpolant at `x`.
+
+        Parameters
+        ----------
+        x : (Q, N) array_like
+            Evaluation point coordinates.
+
+        Returns
+        -------
+        (Q, ...) ndarray
+            Values of the interpolant at `x`.
+
+        """
+        x = np.asarray(x, dtype=float, order="C")
+        if x.ndim != 2:
+            raise ValueError("`x` must be a 2-dimensional array.")
+
+        nx, ndim = x.shape
+        if ndim != self.y.shape[1]:
+            raise ValueError("Expected the second axis of `x` to have length "
+                             f"{self.y.shape[1]}.")
+
+        # Our memory budget for storing RBF coefficients is
+        # based on how many floats in memory we already occupy
+        # If this number is below 1e6 we just use 1e6
+        # This memory budget is used to decide how we chunk
+        # the inputs
+        memory_budget = max(x.size + self.y.size + self.d.size, 1000000)
+
+        if self.neighbors is None:
+            out = self._chunk_evaluator(
+                x,
+                self.y,
+                self._shift,
+                self._scale,
+                self._coeffs,
+                memory_budget=memory_budget)
+        else:
+            # Get the indices of the k nearest observation points to each
+            # evaluation point.
+            _, yindices = self._tree.query(x, self.neighbors)
+            if self.neighbors == 1:
+                # `KDTree` squeezes the output when neighbors=1.
+                yindices = yindices[:, None]
+
+            # Multiple evaluation points may have the same neighborhood of
+            # observation points. Make the neighborhoods unique so that we only
+            # compute the interpolation coefficients once for each
+            # neighborhood.
+            yindices = np.sort(yindices, axis=1)
+            yindices, inv = np.unique(yindices, return_inverse=True, axis=0)
+            inv = np.reshape(inv, (-1,))  # flatten, we need 1-D indices
+            # `inv` tells us which neighborhood will be used by each evaluation
+            # point. Now we find which evaluation points will be using each
+            # neighborhood.
+            xindices = [[] for _ in range(len(yindices))]
+            for i, j in enumerate(inv):
+                xindices[j].append(i)
+
+            out = np.empty((nx, self.d.shape[1]), dtype=float)
+            for xidx, yidx in zip(xindices, yindices):
+                # `yidx` are the indices of the observations in this
+                # neighborhood. `xidx` are the indices of the evaluation points
+                # that are using this neighborhood.
+                xnbr = x[xidx]
+                ynbr = self.y[yidx]
+                dnbr = self.d[yidx]
+                snbr = self.smoothing[yidx]
+                shift, scale, coeffs = _build_and_solve_system(
+                    ynbr,
+                    dnbr,
+                    snbr,
+                    self.kernel,
+                    self.epsilon,
+                    self.powers,
+                )
+                out[xidx] = self._chunk_evaluator(
+                    xnbr,
+                    ynbr,
+                    shift,
+                    scale,
+                    coeffs,
+                    memory_budget=memory_budget)
+
+        out = out.view(self.d_dtype)
+        out = out.reshape((nx, ) + self.d_shape)
+        return out
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_rgi.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_rgi.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e20200568ed961849b5510e8626cdbe6e5b9643
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/_rgi.py
@@ -0,0 +1,759 @@
+__all__ = ['RegularGridInterpolator', 'interpn']
+
+import itertools
+
+import numpy as np
+
+import scipy.sparse.linalg as ssl
+
+from ._interpnd import _ndim_coords_from_arrays
+from ._cubic import PchipInterpolator
+from ._rgi_cython import evaluate_linear_2d, find_indices
+from ._bsplines import make_interp_spline
+from ._fitpack2 import RectBivariateSpline
+from ._ndbspline import make_ndbspl
+
+
+def _check_points(points):
+    descending_dimensions = []
+    grid = []
+    for i, p in enumerate(points):
+        # early make points float
+        # see https://github.com/scipy/scipy/pull/17230
+        p = np.asarray(p, dtype=float)
+        if not np.all(p[1:] > p[:-1]):
+            if np.all(p[1:] < p[:-1]):
+                # input is descending, so make it ascending
+                descending_dimensions.append(i)
+                p = np.flip(p)
+            else:
+                raise ValueError(
+                    "The points in dimension %d must be strictly "
+                    "ascending or descending" % i)
+        # see https://github.com/scipy/scipy/issues/17716
+        p = np.ascontiguousarray(p)
+        grid.append(p)
+    return tuple(grid), tuple(descending_dimensions)
+
+
+def _check_dimensionality(points, values):
+    if len(points) > values.ndim:
+        raise ValueError("There are %d point arrays, but values has %d "
+                         "dimensions" % (len(points), values.ndim))
+    for i, p in enumerate(points):
+        if not np.asarray(p).ndim == 1:
+            raise ValueError("The points in dimension %d must be "
+                             "1-dimensional" % i)
+        if not values.shape[i] == len(p):
+            raise ValueError("There are %d points and %d values in "
+                             "dimension %d" % (len(p), values.shape[i], i))
+
+
+class RegularGridInterpolator:
+    """
+    Interpolator on a regular or rectilinear grid in arbitrary dimensions.
+
+    The data must be defined on a rectilinear grid; that is, a rectangular
+    grid with even or uneven spacing. Linear, nearest-neighbor, spline
+    interpolations are supported. After setting up the interpolator object,
+    the interpolation method may be chosen at each evaluation.
+
+    Parameters
+    ----------
+    points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
+        The points defining the regular grid in n dimensions. The points in
+        each dimension (i.e. every elements of the points tuple) must be
+        strictly ascending or descending.
+
+    values : array_like, shape (m1, ..., mn, ...)
+        The data on the regular grid in n dimensions. Complex data is
+        accepted.
+
+    method : str, optional
+        The method of interpolation to perform. Supported are "linear",
+        "nearest", "slinear", "cubic", "quintic" and "pchip". This
+        parameter will become the default for the object's ``__call__``
+        method. Default is "linear".
+
+    bounds_error : bool, optional
+        If True, when interpolated values are requested outside of the
+        domain of the input data, a ValueError is raised.
+        If False, then `fill_value` is used.
+        Default is True.
+
+    fill_value : float or None, optional
+        The value to use for points outside of the interpolation domain.
+        If None, values outside the domain are extrapolated.
+        Default is ``np.nan``.
+
+    solver : callable, optional
+        Only used for methods "slinear", "cubic" and "quintic".
+        Sparse linear algebra solver for construction of the NdBSpline instance.
+        Default is the iterative solver `scipy.sparse.linalg.gcrotmk`.
+
+        .. versionadded:: 1.13
+
+    solver_args: dict, optional
+        Additional arguments to pass to `solver`, if any.
+
+        .. versionadded:: 1.13
+
+    Methods
+    -------
+    __call__
+
+    Attributes
+    ----------
+    grid : tuple of ndarrays
+        The points defining the regular grid in n dimensions.
+        This tuple defines the full grid via
+        ``np.meshgrid(*grid, indexing='ij')``
+    values : ndarray
+        Data values at the grid.
+    method : str
+        Interpolation method.
+    fill_value : float or ``None``
+        Use this value for out-of-bounds arguments to `__call__`.
+    bounds_error : bool
+        If ``True``, out-of-bounds argument raise a ``ValueError``.
+
+    Notes
+    -----
+    Contrary to `LinearNDInterpolator` and `NearestNDInterpolator`, this class
+    avoids expensive triangulation of the input data by taking advantage of the
+    regular grid structure.
+
+    In other words, this class assumes that the data is defined on a
+    *rectilinear* grid.
+
+    .. versionadded:: 0.14
+
+    The 'slinear'(k=1), 'cubic'(k=3), and 'quintic'(k=5) methods are
+    tensor-product spline interpolators, where `k` is the spline degree,
+    If any dimension has fewer points than `k` + 1, an error will be raised.
+
+    .. versionadded:: 1.9
+
+    If the input data is such that dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolating.
+
+    **Choosing a solver for spline methods**
+
+    Spline methods, "slinear", "cubic" and "quintic" involve solving a
+    large sparse linear system at instantiation time. Depending on data,
+    the default solver may or may not be adequate. When it is not, you may
+    need to experiment with an optional `solver` argument, where you may
+    choose between the direct solver (`scipy.sparse.linalg.spsolve`) or
+    iterative solvers from `scipy.sparse.linalg`. You may need to supply
+    additional parameters via the optional `solver_args` parameter (for instance,
+    you may supply the starting value or target tolerance). See the
+    `scipy.sparse.linalg` documentation for the full list of available options.
+
+    Alternatively, you may instead use the legacy methods, "slinear_legacy",
+    "cubic_legacy" and "quintic_legacy". These methods allow faster construction
+    but evaluations will be much slower.
+
+    Examples
+    --------
+    **Evaluate a function on the points of a 3-D grid**
+
+    As a first example, we evaluate a simple example function on the points of
+    a 3-D grid:
+
+    >>> from scipy.interpolate import RegularGridInterpolator
+    >>> import numpy as np
+    >>> def f(x, y, z):
+    ...     return 2 * x**3 + 3 * y**2 - z
+    >>> x = np.linspace(1, 4, 11)
+    >>> y = np.linspace(4, 7, 22)
+    >>> z = np.linspace(7, 9, 33)
+    >>> xg, yg ,zg = np.meshgrid(x, y, z, indexing='ij', sparse=True)
+    >>> data = f(xg, yg, zg)
+
+    ``data`` is now a 3-D array with ``data[i, j, k] = f(x[i], y[j], z[k])``.
+    Next, define an interpolating function from this data:
+
+    >>> interp = RegularGridInterpolator((x, y, z), data)
+
+    Evaluate the interpolating function at the two points
+    ``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``:
+
+    >>> pts = np.array([[2.1, 6.2, 8.3],
+    ...                 [3.3, 5.2, 7.1]])
+    >>> interp(pts)
+    array([ 125.80469388,  146.30069388])
+
+    which is indeed a close approximation to
+
+    >>> f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1)
+    (125.54200000000002, 145.894)
+
+    **Interpolate and extrapolate a 2D dataset**
+
+    As a second example, we interpolate and extrapolate a 2D data set:
+
+    >>> x, y = np.array([-2, 0, 4]), np.array([-2, 0, 2, 5])
+    >>> def ff(x, y):
+    ...     return x**2 + y**2
+
+    >>> xg, yg = np.meshgrid(x, y, indexing='ij')
+    >>> data = ff(xg, yg)
+    >>> interp = RegularGridInterpolator((x, y), data,
+    ...                                  bounds_error=False, fill_value=None)
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(projection='3d')
+    >>> ax.scatter(xg.ravel(), yg.ravel(), data.ravel(),
+    ...            s=60, c='k', label='data')
+
+    Evaluate and plot the interpolator on a finer grid
+
+    >>> xx = np.linspace(-4, 9, 31)
+    >>> yy = np.linspace(-4, 9, 31)
+    >>> X, Y = np.meshgrid(xx, yy, indexing='ij')
+
+    >>> # interpolator
+    >>> ax.plot_wireframe(X, Y, interp((X, Y)), rstride=3, cstride=3,
+    ...                   alpha=0.4, color='m', label='linear interp')
+
+    >>> # ground truth
+    >>> ax.plot_wireframe(X, Y, ff(X, Y), rstride=3, cstride=3,
+    ...                   alpha=0.4, label='ground truth')
+    >>> plt.legend()
+    >>> plt.show()
+
+    Other examples are given
+    :ref:`in the tutorial `.
+
+    See Also
+    --------
+    NearestNDInterpolator : Nearest neighbor interpolator on *unstructured*
+                            data in N dimensions
+
+    LinearNDInterpolator : Piecewise linear interpolator on *unstructured* data
+                           in N dimensions
+
+    interpn : a convenience function which wraps `RegularGridInterpolator`
+
+    scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
+                                    (suitable for e.g., N-D image resampling)
+
+    References
+    ----------
+    .. [1] Python package *regulargrid* by Johannes Buchner, see
+           https://pypi.python.org/pypi/regulargrid/
+    .. [2] Wikipedia, "Trilinear interpolation",
+           https://en.wikipedia.org/wiki/Trilinear_interpolation
+    .. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear
+           and multilinear table interpolation in many dimensions." MATH.
+           COMPUT. 50.181 (1988): 189-196.
+           https://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf
+           :doi:`10.1090/S0025-5718-1988-0917826-0`
+
+    """
+    # this class is based on code originally programmed by Johannes Buchner,
+    # see https://github.com/JohannesBuchner/regulargrid
+
+    _SPLINE_DEGREE_MAP = {"slinear": 1, "cubic": 3, "quintic": 5, 'pchip': 3,
+                          "slinear_legacy": 1, "cubic_legacy": 3, "quintic_legacy": 5,}
+    _SPLINE_METHODS_recursive = {"slinear_legacy", "cubic_legacy",
+                                "quintic_legacy", "pchip"}
+    _SPLINE_METHODS_ndbspl = {"slinear", "cubic", "quintic"}
+    _SPLINE_METHODS = list(_SPLINE_DEGREE_MAP.keys())
+    _ALL_METHODS = ["linear", "nearest"] + _SPLINE_METHODS
+
+    def __init__(self, points, values, method="linear", bounds_error=True,
+                 fill_value=np.nan, *, solver=None, solver_args=None):
+        if method not in self._ALL_METHODS:
+            raise ValueError(f"Method '{method}' is not defined")
+        elif method in self._SPLINE_METHODS:
+            self._validate_grid_dimensions(points, method)
+        self.method = method
+        self._spline = None
+        self.bounds_error = bounds_error
+        self.grid, self._descending_dimensions = _check_points(points)
+        self.values = self._check_values(values)
+        self._check_dimensionality(self.grid, self.values)
+        self.fill_value = self._check_fill_value(self.values, fill_value)
+        if self._descending_dimensions:
+            self.values = np.flip(values, axis=self._descending_dimensions)
+        if self.method == "pchip" and np.iscomplexobj(self.values):
+            msg = ("`PchipInterpolator` only works with real values. If you are trying "
+                   "to use the real components of the passed array, use `np.real` on "
+                   "the array before passing to `RegularGridInterpolator`.")
+            raise ValueError(msg)
+        if method in self._SPLINE_METHODS_ndbspl:
+            if solver_args is None:
+                solver_args = {}
+            self._spline = self._construct_spline(method, solver, **solver_args)
+        else:
+            if solver is not None or solver_args:
+                raise ValueError(
+                    f"{method =} does not accept the 'solver' argument. Got "
+                    f" {solver = } and with arguments {solver_args}."
+                )
+
+    def _construct_spline(self, method, solver=None, **solver_args):
+        if solver is None:
+            solver = ssl.gcrotmk
+        spl = make_ndbspl(
+                self.grid, self.values, self._SPLINE_DEGREE_MAP[method],
+                solver=solver, **solver_args
+              )
+        return spl
+
+    def _check_dimensionality(self, grid, values):
+        _check_dimensionality(grid, values)
+
+    def _check_points(self, points):
+        return _check_points(points)
+
+    def _check_values(self, values):
+        if not hasattr(values, 'ndim'):
+            # allow reasonable duck-typed values
+            values = np.asarray(values)
+
+        if hasattr(values, 'dtype') and hasattr(values, 'astype'):
+            if not np.issubdtype(values.dtype, np.inexact):
+                values = values.astype(float)
+
+        return values
+
+    def _check_fill_value(self, values, fill_value):
+        if fill_value is not None:
+            fill_value_dtype = np.asarray(fill_value).dtype
+            if (hasattr(values, 'dtype') and not
+                    np.can_cast(fill_value_dtype, values.dtype,
+                                casting='same_kind')):
+                raise ValueError("fill_value must be either 'None' or "
+                                 "of a type compatible with values")
+        return fill_value
+
+    def __call__(self, xi, method=None, *, nu=None):
+        """
+        Interpolation at coordinates.
+
+        Parameters
+        ----------
+        xi : ndarray of shape (..., ndim)
+            The coordinates to evaluate the interpolator at.
+
+        method : str, optional
+            The method of interpolation to perform. Supported are "linear",
+            "nearest", "slinear", "cubic", "quintic" and "pchip". Default is
+            the method chosen when the interpolator was created.
+
+        nu : sequence of ints, length ndim, optional
+            If not None, the orders of the derivatives to evaluate.
+            Each entry must be non-negative.
+            Only allowed for methods "slinear", "cubic" and "quintic".
+
+            .. versionadded:: 1.13
+
+        Returns
+        -------
+        values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
+            Interpolated values at `xi`. See notes for behaviour when
+            ``xi.ndim == 1``.
+
+        Notes
+        -----
+        In the case that ``xi.ndim == 1`` a new axis is inserted into
+        the 0 position of the returned array, values_x, so its shape is
+        instead ``(1,) + values.shape[ndim:]``.
+
+        Examples
+        --------
+        Here we define a nearest-neighbor interpolator of a simple function
+
+        >>> import numpy as np
+        >>> x, y = np.array([0, 1, 2]), np.array([1, 3, 7])
+        >>> def f(x, y):
+        ...     return x**2 + y**2
+        >>> data = f(*np.meshgrid(x, y, indexing='ij', sparse=True))
+        >>> from scipy.interpolate import RegularGridInterpolator
+        >>> interp = RegularGridInterpolator((x, y), data, method='nearest')
+
+        By construction, the interpolator uses the nearest-neighbor
+        interpolation
+
+        >>> interp([[1.5, 1.3], [0.3, 4.5]])
+        array([2., 9.])
+
+        We can however evaluate the linear interpolant by overriding the
+        `method` parameter
+
+        >>> interp([[1.5, 1.3], [0.3, 4.5]], method='linear')
+        array([ 4.7, 24.3])
+        """
+        _spline = self._spline
+        method = self.method if method is None else method
+        is_method_changed = self.method != method
+        if method not in self._ALL_METHODS:
+            raise ValueError(f"Method '{method}' is not defined")
+        if is_method_changed and method in self._SPLINE_METHODS_ndbspl:
+            _spline = self._construct_spline(method)
+
+        if nu is not None and method not in self._SPLINE_METHODS_ndbspl:
+            raise ValueError(
+                f"Can only compute derivatives for methods "
+                f"{self._SPLINE_METHODS_ndbspl}, got {method =}."
+            )
+
+        xi, xi_shape, ndim, nans, out_of_bounds = self._prepare_xi(xi)
+
+        if method == "linear":
+            indices, norm_distances = self._find_indices(xi.T)
+            if (ndim == 2 and hasattr(self.values, 'dtype') and
+                    self.values.ndim == 2 and self.values.flags.writeable and
+                    self.values.dtype in (np.float64, np.complex128) and
+                    self.values.dtype.byteorder == '='):
+                # until cython supports const fused types, the fast path
+                # cannot support non-writeable values
+                # a fast path
+                out = np.empty(indices.shape[1], dtype=self.values.dtype)
+                result = evaluate_linear_2d(self.values,
+                                            indices,
+                                            norm_distances,
+                                            self.grid,
+                                            out)
+            else:
+                result = self._evaluate_linear(indices, norm_distances)
+        elif method == "nearest":
+            indices, norm_distances = self._find_indices(xi.T)
+            result = self._evaluate_nearest(indices, norm_distances)
+        elif method in self._SPLINE_METHODS:
+            if is_method_changed:
+                self._validate_grid_dimensions(self.grid, method)
+            if method in self._SPLINE_METHODS_recursive:
+                result = self._evaluate_spline(xi, method)
+            else:
+                result = _spline(xi, nu=nu)
+
+        if not self.bounds_error and self.fill_value is not None:
+            result[out_of_bounds] = self.fill_value
+
+        # f(nan) = nan, if any
+        if np.any(nans):
+            result[nans] = np.nan
+        return result.reshape(xi_shape[:-1] + self.values.shape[ndim:])
+
+    def _prepare_xi(self, xi):
+        ndim = len(self.grid)
+        xi = _ndim_coords_from_arrays(xi, ndim=ndim)
+        if xi.shape[-1] != len(self.grid):
+            raise ValueError("The requested sample points xi have dimension "
+                             f"{xi.shape[-1]} but this "
+                             f"RegularGridInterpolator has dimension {ndim}")
+
+        xi_shape = xi.shape
+        xi = xi.reshape(-1, xi_shape[-1])
+        xi = np.asarray(xi, dtype=float)
+
+        # find nans in input
+        nans = np.any(np.isnan(xi), axis=-1)
+
+        if self.bounds_error:
+            for i, p in enumerate(xi.T):
+                if not np.logical_and(np.all(self.grid[i][0] <= p),
+                                      np.all(p <= self.grid[i][-1])):
+                    raise ValueError("One of the requested xi is out of bounds "
+                                     "in dimension %d" % i)
+            out_of_bounds = None
+        else:
+            out_of_bounds = self._find_out_of_bounds(xi.T)
+
+        return xi, xi_shape, ndim, nans, out_of_bounds
+
+    def _evaluate_linear(self, indices, norm_distances):
+        # slice for broadcasting over trailing dimensions in self.values
+        vslice = (slice(None),) + (None,)*(self.values.ndim - len(indices))
+
+        # Compute shifting up front before zipping everything together
+        shift_norm_distances = [1 - yi for yi in norm_distances]
+        shift_indices = [i + 1 for i in indices]
+
+        # The formula for linear interpolation in 2d takes the form:
+        # values = self.values[(i0, i1)] * (1 - y0) * (1 - y1) + \
+        #          self.values[(i0, i1 + 1)] * (1 - y0) * y1 + \
+        #          self.values[(i0 + 1, i1)] * y0 * (1 - y1) + \
+        #          self.values[(i0 + 1, i1 + 1)] * y0 * y1
+        # We pair i with 1 - yi (zipped1) and i + 1 with yi (zipped2)
+        zipped1 = zip(indices, shift_norm_distances)
+        zipped2 = zip(shift_indices, norm_distances)
+
+        # Take all products of zipped1 and zipped2 and iterate over them
+        # to get the terms in the above formula. This corresponds to iterating
+        # over the vertices of a hypercube.
+        hypercube = itertools.product(*zip(zipped1, zipped2))
+        value = np.array([0.])
+        for h in hypercube:
+            edge_indices, weights = zip(*h)
+            weight = np.array([1.])
+            for w in weights:
+                weight = weight * w
+            term = np.asarray(self.values[edge_indices]) * weight[vslice]
+            value = value + term   # cannot use += because broadcasting
+        return value
+
+    def _evaluate_nearest(self, indices, norm_distances):
+        idx_res = [np.where(yi <= .5, i, i + 1)
+                   for i, yi in zip(indices, norm_distances)]
+        return self.values[tuple(idx_res)]
+
+    def _validate_grid_dimensions(self, points, method):
+        k = self._SPLINE_DEGREE_MAP[method]
+        for i, point in enumerate(points):
+            ndim = len(np.atleast_1d(point))
+            if ndim <= k:
+                raise ValueError(f"There are {ndim} points in dimension {i},"
+                                 f" but method {method} requires at least "
+                                 f" {k+1} points per dimension.")
+
+    def _evaluate_spline(self, xi, method):
+        # ensure xi is 2D list of points to evaluate (`m` is the number of
+        # points and `n` is the number of interpolation dimensions,
+        # ``n == len(self.grid)``.)
+        if xi.ndim == 1:
+            xi = xi.reshape((1, xi.size))
+        m, n = xi.shape
+
+        # Reorder the axes: n-dimensional process iterates over the
+        # interpolation axes from the last axis downwards: E.g. for a 4D grid
+        # the order of axes is 3, 2, 1, 0. Each 1D interpolation works along
+        # the 0th axis of its argument array (for 1D routine it's its ``y``
+        # array). Thus permute the interpolation axes of `values` *and keep
+        # trailing dimensions trailing*.
+        axes = tuple(range(self.values.ndim))
+        axx = axes[:n][::-1] + axes[n:]
+        values = self.values.transpose(axx)
+
+        if method == 'pchip':
+            _eval_func = self._do_pchip
+        else:
+            _eval_func = self._do_spline_fit
+        k = self._SPLINE_DEGREE_MAP[method]
+
+        # Non-stationary procedure: difficult to vectorize this part entirely
+        # into numpy-level operations. Unfortunately this requires explicit
+        # looping over each point in xi.
+
+        # can at least vectorize the first pass across all points in the
+        # last variable of xi.
+        last_dim = n - 1
+        first_values = _eval_func(self.grid[last_dim],
+                                  values,
+                                  xi[:, last_dim],
+                                  k)
+
+        # the rest of the dimensions have to be on a per point-in-xi basis
+        shape = (m, *self.values.shape[n:])
+        result = np.empty(shape, dtype=self.values.dtype)
+        for j in range(m):
+            # Main process: Apply 1D interpolate in each dimension
+            # sequentially, starting with the last dimension.
+            # These are then "folded" into the next dimension in-place.
+            folded_values = first_values[j, ...]
+            for i in range(last_dim-1, -1, -1):
+                # Interpolate for each 1D from the last dimensions.
+                # This collapses each 1D sequence into a scalar.
+                folded_values = _eval_func(self.grid[i],
+                                           folded_values,
+                                           xi[j, i],
+                                           k)
+            result[j, ...] = folded_values
+
+        return result
+
+    @staticmethod
+    def _do_spline_fit(x, y, pt, k):
+        local_interp = make_interp_spline(x, y, k=k, axis=0)
+        values = local_interp(pt)
+        return values
+
+    @staticmethod
+    def _do_pchip(x, y, pt, k):
+        local_interp = PchipInterpolator(x, y, axis=0)
+        values = local_interp(pt)
+        return values
+
+    def _find_indices(self, xi):
+        return find_indices(self.grid, xi)
+
+    def _find_out_of_bounds(self, xi):
+        # check for out of bounds xi
+        out_of_bounds = np.zeros((xi.shape[1]), dtype=bool)
+        # iterate through dimensions
+        for x, grid in zip(xi, self.grid):
+            out_of_bounds += x < grid[0]
+            out_of_bounds += x > grid[-1]
+        return out_of_bounds
+
+
+def interpn(points, values, xi, method="linear", bounds_error=True,
+            fill_value=np.nan):
+    """
+    Multidimensional interpolation on regular or rectilinear grids.
+
+    Strictly speaking, not all regular grids are supported - this function
+    works on *rectilinear* grids, that is, a rectangular grid with even or
+    uneven spacing.
+
+    Parameters
+    ----------
+    points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
+        The points defining the regular grid in n dimensions. The points in
+        each dimension (i.e. every elements of the points tuple) must be
+        strictly ascending or descending.
+
+    values : array_like, shape (m1, ..., mn, ...)
+        The data on the regular grid in n dimensions. Complex data is
+        accepted.
+
+        .. deprecated:: 1.13.0
+            Complex data is deprecated with ``method="pchip"`` and will raise an
+            error in SciPy 1.15.0. This is because ``PchipInterpolator`` only
+            works with real values. If you are trying to use the real components of
+            the passed array, use ``np.real`` on ``values``.
+
+    xi : ndarray of shape (..., ndim)
+        The coordinates to sample the gridded data at
+
+    method : str, optional
+        The method of interpolation to perform. Supported are "linear",
+        "nearest", "slinear", "cubic", "quintic", "pchip", and "splinef2d".
+        "splinef2d" is only supported for 2-dimensional data.
+
+    bounds_error : bool, optional
+        If True, when interpolated values are requested outside of the
+        domain of the input data, a ValueError is raised.
+        If False, then `fill_value` is used.
+
+    fill_value : number, optional
+        If provided, the value to use for points outside of the
+        interpolation domain. If None, values outside
+        the domain are extrapolated.  Extrapolation is not supported by method
+        "splinef2d".
+
+    Returns
+    -------
+    values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:]
+        Interpolated values at `xi`. See notes for behaviour when
+        ``xi.ndim == 1``.
+
+    See Also
+    --------
+    NearestNDInterpolator : Nearest neighbor interpolation on unstructured
+                            data in N dimensions
+    LinearNDInterpolator : Piecewise linear interpolant on unstructured data
+                           in N dimensions
+    RegularGridInterpolator : interpolation on a regular or rectilinear grid
+                              in arbitrary dimensions (`interpn` wraps this
+                              class).
+    RectBivariateSpline : Bivariate spline approximation over a rectangular mesh
+    scipy.ndimage.map_coordinates : interpolation on grids with equal spacing
+                                    (suitable for e.g., N-D image resampling)
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14
+
+    In the case that ``xi.ndim == 1`` a new axis is inserted into
+    the 0 position of the returned array, values_x, so its shape is
+    instead ``(1,) + values.shape[ndim:]``.
+
+    If the input data is such that input dimensions have incommensurate
+    units and differ by many orders of magnitude, the interpolant may have
+    numerical artifacts. Consider rescaling the data before interpolation.
+
+    Examples
+    --------
+    Evaluate a simple example function on the points of a regular 3-D grid:
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import interpn
+    >>> def value_func_3d(x, y, z):
+    ...     return 2 * x + 3 * y - z
+    >>> x = np.linspace(0, 4, 5)
+    >>> y = np.linspace(0, 5, 6)
+    >>> z = np.linspace(0, 6, 7)
+    >>> points = (x, y, z)
+    >>> values = value_func_3d(*np.meshgrid(*points, indexing='ij'))
+
+    Evaluate the interpolating function at a point
+
+    >>> point = np.array([2.21, 3.12, 1.15])
+    >>> print(interpn(points, values, point))
+    [12.63]
+
+    """
+    # sanity check 'method' kwarg
+    if method not in ["linear", "nearest", "cubic", "quintic", "pchip",
+                      "splinef2d", "slinear",
+                      "slinear_legacy", "cubic_legacy", "quintic_legacy"]:
+        raise ValueError("interpn only understands the methods 'linear', "
+                         "'nearest', 'slinear', 'cubic', 'quintic', 'pchip', "
+                         f"and 'splinef2d'. You provided {method}.")
+
+    if not hasattr(values, 'ndim'):
+        values = np.asarray(values)
+
+    ndim = values.ndim
+    if ndim > 2 and method == "splinef2d":
+        raise ValueError("The method splinef2d can only be used for "
+                         "2-dimensional input data")
+    if not bounds_error and fill_value is None and method == "splinef2d":
+        raise ValueError("The method splinef2d does not support extrapolation.")
+
+    # sanity check consistency of input dimensions
+    if len(points) > ndim:
+        raise ValueError("There are %d point arrays, but values has %d "
+                         "dimensions" % (len(points), ndim))
+    if len(points) != ndim and method == 'splinef2d':
+        raise ValueError("The method splinef2d can only be used for "
+                         "scalar data with one point per coordinate")
+
+    grid, descending_dimensions = _check_points(points)
+    _check_dimensionality(grid, values)
+
+    # sanity check requested xi
+    xi = _ndim_coords_from_arrays(xi, ndim=len(grid))
+    if xi.shape[-1] != len(grid):
+        raise ValueError("The requested sample points xi have dimension "
+                         "%d, but this RegularGridInterpolator has "
+                         "dimension %d" % (xi.shape[-1], len(grid)))
+
+    if bounds_error:
+        for i, p in enumerate(xi.T):
+            if not np.logical_and(np.all(grid[i][0] <= p),
+                                  np.all(p <= grid[i][-1])):
+                raise ValueError("One of the requested xi is out of bounds "
+                                 "in dimension %d" % i)
+
+    # perform interpolation
+    if method in RegularGridInterpolator._ALL_METHODS:
+        interp = RegularGridInterpolator(points, values, method=method,
+                                         bounds_error=bounds_error,
+                                         fill_value=fill_value)
+        return interp(xi)
+    elif method == "splinef2d":
+        xi_shape = xi.shape
+        xi = xi.reshape(-1, xi.shape[-1])
+
+        # RectBivariateSpline doesn't support fill_value; we need to wrap here
+        idx_valid = np.all((grid[0][0] <= xi[:, 0], xi[:, 0] <= grid[0][-1],
+                            grid[1][0] <= xi[:, 1], xi[:, 1] <= grid[1][-1]),
+                           axis=0)
+        result = np.empty_like(xi[:, 0])
+
+        # make a copy of values for RectBivariateSpline
+        interp = RectBivariateSpline(points[0], points[1], values[:])
+        result[idx_valid] = interp.ev(xi[idx_valid, 0], xi[idx_valid, 1])
+        result[np.logical_not(idx_valid)] = fill_value
+
+        return result.reshape(xi_shape[:-1])
+    else:
+        raise ValueError(f"unknown {method = }")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/dfitpack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/dfitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..e10da3b3fd0c69dede4767dc17b62c327818ecce
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/dfitpack.py
@@ -0,0 +1,44 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'bispeu',
+    'bispev',
+    'curfit',
+    'dblint',
+    'fpchec',
+    'fpcurf0',
+    'fpcurf1',
+    'fpcurfm1',
+    'parcur',
+    'parder',
+    'pardeu',
+    'pardtc',
+    'percur',
+    'regrid_smth',
+    'regrid_smth_spher',
+    'spalde',
+    'spherfit_lsq',
+    'spherfit_smth',
+    'splder',
+    'splev',
+    'splint',
+    'sproot',
+    'surfit_lsq',
+    'surfit_smth',
+    'types',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="dfitpack",
+                                   private_modules=["_dfitpack"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..6490c93fe02b4c665b032d09e2ad3c269e1f7970
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack.py
@@ -0,0 +1,31 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BSpline',
+    'bisplev',
+    'bisplrep',
+    'insert',
+    'spalde',
+    'splantider',
+    'splder',
+    'splev',
+    'splint',
+    'splprep',
+    'splrep',
+    'sproot',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="fitpack",
+                                   private_modules=["_fitpack_py"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..f993961f94d913d632aa3d2cc7b1348659a6a613
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py
@@ -0,0 +1,29 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BivariateSpline',
+    'InterpolatedUnivariateSpline',
+    'LSQBivariateSpline',
+    'LSQSphereBivariateSpline',
+    'LSQUnivariateSpline',
+    'RectBivariateSpline',
+    'RectSphereBivariateSpline',
+    'SmoothBivariateSpline',
+    'SmoothSphereBivariateSpline',
+    'UnivariateSpline',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="fitpack2",
+                                   private_modules=["_fitpack2"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/interpnd.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/interpnd.py
new file mode 100644
index 0000000000000000000000000000000000000000..4288ac233fdde98dbb19aed84b916cfd15302f4c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/interpnd.py
@@ -0,0 +1,25 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'CloughTocher2DInterpolator',
+    'GradientEstimationWarning',
+    'LinearNDInterpolator',
+    'NDInterpolatorBase',
+    'estimate_gradients_2d_global',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="interpnd",
+                                   private_modules=["_interpnd"], all=__all__,
+                                   attribute=name)
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/interpolate.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..341d13954c81130cceb8afe070db023a82550e7a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/interpolate.py
@@ -0,0 +1,30 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BPoly',
+    'BSpline',
+    'NdPPoly',
+    'PPoly',
+    'RectBivariateSpline',
+    'RegularGridInterpolator',
+    'interp1d',
+    'interp2d',
+    'interpn',
+    'lagrange',
+    'make_interp_spline',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="interpolate",
+                                   private_modules=["_interpolate", "fitpack2", "_rgi"],
+                                   all=__all__, attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/ndgriddata.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..20373eaaedaa1cdec6c7a4bc12639d9658bfa85b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/ndgriddata.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'CloughTocher2DInterpolator',
+    'LinearNDInterpolator',
+    'NearestNDInterpolator',
+    'griddata',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="ndgriddata",
+                                   private_modules=["_ndgriddata"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/polyint.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..e81306304abffb313ab5abe09116a162642a9d67
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/polyint.py
@@ -0,0 +1,24 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'BarycentricInterpolator',
+    'KroghInterpolator',
+    'approximate_taylor_polynomial',
+    'barycentric_interpolate',
+    'krogh_interpolate',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="polyint",
+                                   private_modules=["_polyint"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/rbf.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/rbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..772752ef536f4a3b47fb6f9b5d250c5d7f198d85
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/rbf.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.interpolate` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["Rbf"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="interpolate", module="rbf",
+                                   private_modules=["_rbf"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..d798f0eda4eb0c099bdf46cb4b3468628013c9d3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_fitpack.py
@@ -0,0 +1,519 @@
+import itertools
+import os
+
+import numpy as np
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal
+)
+from pytest import raises as assert_raises
+import pytest
+from scipy._lib._testutils import check_free_memory
+
+from scipy.interpolate import RectBivariateSpline
+from scipy.interpolate import make_splrep
+
+from scipy.interpolate._fitpack_py import (splrep, splev, bisplrep, bisplev,
+     sproot, splprep, splint, spalde, splder, splantider, insert, dblint)
+from scipy.interpolate._dfitpack import regrid_smth
+from scipy.interpolate._fitpack2 import dfitpack_int
+
+
+def data_file(basename):
+    return os.path.join(os.path.abspath(os.path.dirname(__file__)),
+                        'data', basename)
+
+
+def norm2(x):
+    return np.sqrt(np.dot(x.T, x))
+
+
+def f1(x, d=0):
+    """Derivatives of sin->cos->-sin->-cos."""
+    if d % 4 == 0:
+        return np.sin(x)
+    if d % 4 == 1:
+        return np.cos(x)
+    if d % 4 == 2:
+        return -np.sin(x)
+    if d % 4 == 3:
+        return -np.cos(x)
+
+
+def makepairs(x, y):
+    """Helper function to create an array of pairs of x and y."""
+    xy = np.array(list(itertools.product(np.asarray(x), np.asarray(y))))
+    return xy.T
+
+
+class TestSmokeTests:
+    """
+    Smoke tests (with a few asserts) for fitpack routines -- mostly
+    check that they are runnable
+    """
+    def check_1(self, per=0, s=0, a=0, b=2*np.pi, at_nodes=False,
+                xb=None, xe=None):
+        if xb is None:
+            xb = a
+        if xe is None:
+            xe = b
+
+        N = 20
+        # nodes and middle points of the nodes
+        x = np.linspace(a, b, N + 1)
+        x1 = a + (b - a) * np.arange(1, N, dtype=float) / float(N - 1)
+        v = f1(x)
+
+        def err_est(k, d):
+            # Assume f has all derivatives < 1
+            h = 1.0 / N
+            tol = 5 * h**(.75*(k-d))
+            if s > 0:
+                tol += 1e5*s
+            return tol
+
+        for k in range(1, 6):
+            tck = splrep(x, v, s=s, per=per, k=k, xe=xe)
+            tt = tck[0][k:-k] if at_nodes else x1
+
+            for d in range(k+1):
+                tol = err_est(k, d)
+                err = norm2(f1(tt, d) - splev(tt, tck, d)) / norm2(f1(tt, d))
+                assert err < tol
+
+            # smoke test make_splrep
+            if not per:
+                spl = make_splrep(x, v, k=k, s=s, xb=xb, xe=xe)
+                if len(spl.t) == len(tck[0]):
+                    xp_assert_close(spl.t, tck[0], atol=1e-15)
+                    xp_assert_close(spl.c, tck[1][:spl.c.size], atol=1e-13)
+                else:
+                    assert k == 5   # knot length differ in some k=5 cases
+
+    def check_2(self, per=0, N=20, ia=0, ib=2*np.pi):
+        a, b, dx = 0, 2*np.pi, 0.2*np.pi
+        x = np.linspace(a, b, N+1)    # nodes
+        v = np.sin(x)
+
+        def err_est(k, d):
+            # Assume f has all derivatives < 1
+            h = 1.0 / N
+            tol = 5 * h**(.75*(k-d))
+            return tol
+
+        nk = []
+        for k in range(1, 6):
+            tck = splrep(x, v, s=0, per=per, k=k, xe=b)
+            nk.append([splint(ia, ib, tck), spalde(dx, tck)])
+
+        k = 1
+        for r in nk:
+            d = 0
+            for dr in r[1]:
+                tol = err_est(k, d)
+                xp_assert_close(dr, f1(dx, d), atol=0, rtol=tol)
+                d = d+1
+            k = k+1
+
+    def test_smoke_splrep_splev(self):
+        self.check_1(s=1e-6)
+        self.check_1(b=1.5*np.pi)
+        self.check_1(b=1.5*np.pi, xe=2*np.pi, per=1, s=1e-1)
+
+    @pytest.mark.parametrize('per', [0, 1])
+    @pytest.mark.parametrize('at_nodes', [True, False])
+    def test_smoke_splrep_splev_2(self, per, at_nodes):
+        self.check_1(per=per, at_nodes=at_nodes)
+
+    @pytest.mark.parametrize('N', [20, 50])
+    @pytest.mark.parametrize('per', [0, 1])
+    def test_smoke_splint_spalde(self, N, per):
+        self.check_2(per=per, N=N)
+
+    @pytest.mark.parametrize('N', [20, 50])
+    @pytest.mark.parametrize('per', [0, 1])
+    def test_smoke_splint_spalde_iaib(self, N, per):
+        self.check_2(ia=0.2*np.pi, ib=np.pi, N=N, per=per)
+
+    def test_smoke_sproot(self):
+        # sproot is only implemented for k=3
+        a, b = 0.1, 15
+        x = np.linspace(a, b, 20)
+        v = np.sin(x)
+
+        for k in [1, 2, 4, 5]:
+            tck = splrep(x, v, s=0, per=0, k=k, xe=b)
+            with assert_raises(ValueError):
+                sproot(tck)
+
+        k = 3
+        tck = splrep(x, v, s=0, k=3)
+        roots = sproot(tck)
+        xp_assert_close(splev(roots, tck), np.zeros(len(roots)), atol=1e-10, rtol=1e-10)
+        xp_assert_close(roots, np.pi * np.array([1, 2, 3, 4]), rtol=1e-3)
+
+    @pytest.mark.parametrize('N', [20, 50])
+    @pytest.mark.parametrize('k', [1, 2, 3, 4, 5])
+    def test_smoke_splprep_splrep_splev(self, N, k):
+        a, b, dx = 0, 2.*np.pi, 0.2*np.pi
+        x = np.linspace(a, b, N+1)    # nodes
+        v = np.sin(x)
+
+        tckp, u = splprep([x, v], s=0, per=0, k=k, nest=-1)
+        uv = splev(dx, tckp)
+        err1 = abs(uv[1] - np.sin(uv[0]))
+        assert err1 < 1e-2
+
+        tck = splrep(x, v, s=0, per=0, k=k)
+        err2 = abs(splev(uv[0], tck) - np.sin(uv[0]))
+        assert err2 < 1e-2
+
+        # Derivatives of parametric cubic spline at u (first function)
+        if k == 3:
+            tckp, u = splprep([x, v], s=0, per=0, k=k, nest=-1)
+            for d in range(1, k+1):
+                uv = splev(dx, tckp, d)
+
+    def test_smoke_bisplrep_bisplev(self):
+        xb, xe = 0, 2.*np.pi
+        yb, ye = 0, 2.*np.pi
+        kx, ky = 3, 3
+        Nx, Ny = 20, 20
+
+        def f2(x, y):
+            return np.sin(x+y)
+
+        x = np.linspace(xb, xe, Nx + 1)
+        y = np.linspace(yb, ye, Ny + 1)
+        xy = makepairs(x, y)
+        tck = bisplrep(xy[0], xy[1], f2(xy[0], xy[1]), s=0, kx=kx, ky=ky)
+
+        tt = [tck[0][kx:-kx], tck[1][ky:-ky]]
+        t2 = makepairs(tt[0], tt[1])
+        v1 = bisplev(tt[0], tt[1], tck)
+        v2 = f2(t2[0], t2[1])
+        v2.shape = len(tt[0]), len(tt[1])
+
+        assert norm2(np.ravel(v1 - v2)) < 1e-2
+
+
+class TestSplev:
+    def test_1d_shape(self):
+        x = [1,2,3,4,5]
+        y = [4,5,6,7,8]
+        tck = splrep(x, y)
+        z = splev([1], tck)
+        assert z.shape == (1,)
+        z = splev(1, tck)
+        assert z.shape == ()
+
+    def test_2d_shape(self):
+        x = [1, 2, 3, 4, 5]
+        y = [4, 5, 6, 7, 8]
+        tck = splrep(x, y)
+        t = np.array([[1.0, 1.5, 2.0, 2.5],
+                      [3.0, 3.5, 4.0, 4.5]])
+        z = splev(t, tck)
+        z0 = splev(t[0], tck)
+        z1 = splev(t[1], tck)
+        xp_assert_equal(z, np.vstack((z0, z1)))
+
+    def test_extrapolation_modes(self):
+        # test extrapolation modes
+        #    * if ext=0, return the extrapolated value.
+        #    * if ext=1, return 0
+        #    * if ext=2, raise a ValueError
+        #    * if ext=3, return the boundary value.
+        x = [1,2,3]
+        y = [0,2,4]
+        tck = splrep(x, y, k=1)
+
+        rstl = [[-2, 6], [0, 0], None, [0, 4]]
+        for ext in (0, 1, 3):
+            assert_array_almost_equal(splev([0, 4], tck, ext=ext), rstl[ext])
+
+        assert_raises(ValueError, splev, [0, 4], tck, ext=2)
+
+
+class TestSplder:
+    def setup_method(self):
+        # non-uniform grid, just to make it sure
+        x = np.linspace(0, 1, 100)**3
+        y = np.sin(20 * x)
+        self.spl = splrep(x, y)
+
+        # double check that knots are non-uniform
+        assert np.ptp(np.diff(self.spl[0])) > 0
+
+    def test_inverse(self):
+        # Check that antiderivative + derivative is identity.
+        for n in range(5):
+            spl2 = splantider(self.spl, n)
+            spl3 = splder(spl2, n)
+            xp_assert_close(self.spl[0], spl3[0])
+            xp_assert_close(self.spl[1], spl3[1])
+            assert self.spl[2] == spl3[2]
+
+    def test_splder_vs_splev(self):
+        # Check derivative vs. FITPACK
+
+        for n in range(3+1):
+            # Also extrapolation!
+            xx = np.linspace(-1, 2, 2000)
+            if n == 3:
+                # ... except that FITPACK extrapolates strangely for
+                # order 0, so let's not check that.
+                xx = xx[(xx >= 0) & (xx <= 1)]
+
+            dy = splev(xx, self.spl, n)
+            spl2 = splder(self.spl, n)
+            dy2 = splev(xx, spl2)
+            if n == 1:
+                xp_assert_close(dy, dy2, rtol=2e-6)
+            else:
+                xp_assert_close(dy, dy2)
+
+    def test_splantider_vs_splint(self):
+        # Check antiderivative vs. FITPACK
+        spl2 = splantider(self.spl)
+
+        # no extrapolation, splint assumes function is zero outside
+        # range
+        xx = np.linspace(0, 1, 20)
+
+        for x1 in xx:
+            for x2 in xx:
+                y1 = splint(x1, x2, self.spl)
+                y2 = splev(x2, spl2) - splev(x1, spl2)
+                xp_assert_close(np.asarray(y1), np.asarray(y2))
+
+    def test_order0_diff(self):
+        assert_raises(ValueError, splder, self.spl, 4)
+
+    def test_kink(self):
+        # Should refuse to differentiate splines with kinks
+
+        spl2 = insert(0.5, self.spl, m=2)
+        splder(spl2, 2)  # Should work
+        assert_raises(ValueError, splder, spl2, 3)
+
+        spl2 = insert(0.5, self.spl, m=3)
+        splder(spl2, 1)  # Should work
+        assert_raises(ValueError, splder, spl2, 2)
+
+        spl2 = insert(0.5, self.spl, m=4)
+        assert_raises(ValueError, splder, spl2, 1)
+
+    def test_multidim(self):
+        # c can have trailing dims
+        for n in range(3):
+            t, c, k = self.spl
+            c2 = np.c_[c, c, c]
+            c2 = np.dstack((c2, c2))
+
+            spl2 = splantider((t, c2, k), n)
+            spl3 = splder(spl2, n)
+
+            xp_assert_close(t, spl3[0])
+            xp_assert_close(c2, spl3[1])
+            assert k == spl3[2]
+
+
+class TestSplint:
+    def test_len_c(self):
+        n, k = 7, 3
+        x = np.arange(n)
+        y = x**3
+        t, c, k = splrep(x, y, s=0)
+
+        # note that len(c) == len(t) == 11 (== len(x) + 2*(k-1))
+        assert len(t) == len(c) == n + 2*(k-1)
+
+        # integrate directly: $\int_0^6 x^3 dx = 6^4 / 4$
+        res = splint(0, 6, (t, c, k))
+        expected = 6**4 / 4
+        assert abs(res - expected) < 1e-13
+
+        # check that the coefficients past len(t) - k - 1 are ignored
+        c0 = c.copy()
+        c0[len(t) - k - 1:] = np.nan
+        res0 = splint(0, 6, (t, c0, k))
+        assert abs(res0 - expected) < 1e-13
+
+        # however, all other coefficients *are* used
+        c0[6] = np.nan
+        assert np.isnan(splint(0, 6, (t, c0, k)))
+
+        # check that the coefficient array can have length `len(t) - k - 1`
+        c1 = c[:len(t) - k - 1]
+        res1 = splint(0, 6, (t, c1, k))
+        assert (res1 - expected) < 1e-13
+
+
+        # however shorter c arrays raise. The error from f2py is a
+        # `dftipack.error`, which is an Exception but not ValueError etc.
+        with assert_raises(Exception, match=r">=n-k-1"):
+            splint(0, 1, (np.ones(10), np.ones(5), 3))
+
+
+class TestBisplrep:
+    def test_overflow(self):
+        from numpy.lib.stride_tricks import as_strided
+        if dfitpack_int.itemsize == 8:
+            size = 1500000**2
+        else:
+            size = 400**2
+        # Don't allocate a real array, as it's very big, but rely
+        # on that it's not referenced
+        x = as_strided(np.zeros(()), shape=(size,))
+        assert_raises(OverflowError, bisplrep, x, x, x, w=x,
+                      xb=0, xe=1, yb=0, ye=1, s=0)
+
+    def test_regression_1310(self):
+        # Regression test for gh-1310
+        with np.load(data_file('bug-1310.npz')) as loaded_data:
+            data = loaded_data['data']
+
+        # Shouldn't crash -- the input data triggers work array sizes
+        # that caused previously some data to not be aligned on
+        # sizeof(double) boundaries in memory, which made the Fortran
+        # code to crash when compiled with -O3
+        bisplrep(data[:,0], data[:,1], data[:,2], kx=3, ky=3, s=0,
+                 full_output=True)
+
+    @pytest.mark.skipif(dfitpack_int != np.int64, reason="needs ilp64 fitpack")
+    def test_ilp64_bisplrep(self):
+        check_free_memory(28000)  # VM size, doesn't actually use the pages
+        x = np.linspace(0, 1, 400)
+        y = np.linspace(0, 1, 400)
+        x, y = np.meshgrid(x, y)
+        z = np.zeros_like(x)
+        tck = bisplrep(x, y, z, kx=3, ky=3, s=0)
+        xp_assert_close(bisplev(0.5, 0.5, tck), 0.0)
+
+
+def test_dblint():
+    # Basic test to see it runs and gives the correct result on a trivial
+    # problem. Note that `dblint` is not exposed in the interpolate namespace.
+    x = np.linspace(0, 1)
+    y = np.linspace(0, 1)
+    xx, yy = np.meshgrid(x, y)
+    rect = RectBivariateSpline(x, y, 4 * xx * yy)
+    tck = list(rect.tck)
+    tck.extend(rect.degrees)
+
+    assert abs(dblint(0, 1, 0, 1, tck) - 1) < 1e-10
+    assert abs(dblint(0, 0.5, 0, 1, tck) - 0.25) < 1e-10
+    assert abs(dblint(0.5, 1, 0, 1, tck) - 0.75) < 1e-10
+    assert abs(dblint(-100, 100, -100, 100, tck) - 1) < 1e-10
+
+
+def test_splev_der_k():
+    # regression test for gh-2188: splev(x, tck, der=k) gives garbage or crashes
+    # for x outside of knot range
+
+    # test case from gh-2188
+    tck = (np.array([0., 0., 2.5, 2.5]),
+           np.array([-1.56679978, 2.43995873, 0., 0.]),
+           1)
+    t, c, k = tck
+    x = np.array([-3, 0, 2.5, 3])
+
+    # an explicit form of the linear spline
+    xp_assert_close(splev(x, tck), c[0] + (c[1] - c[0]) * x/t[2])
+    xp_assert_close(splev(x, tck, 1),
+                    np.ones_like(x) * (c[1] - c[0]) / t[2]
+    )
+
+    # now check a random spline vs splder
+    np.random.seed(1234)
+    x = np.sort(np.random.random(30))
+    y = np.random.random(30)
+    t, c, k = splrep(x, y)
+
+    x = [t[0] - 1., t[-1] + 1.]
+    tck2 = splder((t, c, k), k)
+    xp_assert_close(splev(x, (t, c, k), k), splev(x, tck2))
+
+
+def test_splprep_segfault():
+    # regression test for gh-3847: splprep segfaults if knots are specified
+    # for task=-1
+    t = np.arange(0, 1.1, 0.1)
+    x = np.sin(2*np.pi*t)
+    y = np.cos(2*np.pi*t)
+    tck, u = splprep([x, y], s=0)
+    np.arange(0, 1.01, 0.01)
+
+    uknots = tck[0]  # using the knots from the previous fitting
+    tck, u = splprep([x, y], task=-1, t=uknots)  # here is the crash
+
+
+def test_bisplev_integer_overflow():
+    np.random.seed(1)
+
+    x = np.linspace(0, 1, 11)
+    y = x
+    z = np.random.randn(11, 11).ravel()
+    kx = 1
+    ky = 1
+
+    nx, tx, ny, ty, c, fp, ier = regrid_smth(
+        x, y, z, None, None, None, None, kx=kx, ky=ky, s=0.0)
+    tck = (tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)], kx, ky)
+
+    xp = np.zeros([2621440])
+    yp = np.zeros([2621440])
+
+    assert_raises((RuntimeError, MemoryError), bisplev, xp, yp, tck)
+
+
+@pytest.mark.xslow
+def test_gh_1766():
+    # this should fail gracefully instead of segfaulting (int overflow)
+    size = 22
+    kx, ky = 3, 3
+    def f2(x, y):
+        return np.sin(x+y)
+
+    x = np.linspace(0, 10, size)
+    y = np.linspace(50, 700, size)
+    xy = makepairs(x, y)
+    tck = bisplrep(xy[0], xy[1], f2(xy[0], xy[1]), s=0, kx=kx, ky=ky)
+    # the size value here can either segfault
+    # or produce a MemoryError on main
+    tx_ty_size = 500000
+    tck[0] = np.arange(tx_ty_size)
+    tck[1] = np.arange(tx_ty_size) * 4
+    tt_0 = np.arange(50)
+    tt_1 = np.arange(50) * 3
+    with pytest.raises(MemoryError):
+        bisplev(tt_0, tt_1, tck, 1, 1)
+
+
+def test_spalde_scalar_input():
+    # Ticket #629
+    x = np.linspace(0, 10)
+    y = x**3
+    tck = splrep(x, y, k=3, t=[5])
+    res = spalde(np.float64(1), tck)
+    des = np.array([1., 3., 6., 6.])
+    assert_almost_equal(res, des)
+
+
+def test_spalde_nc():
+    # regression test for https://github.com/scipy/scipy/issues/19002
+    # here len(t) = 29 and len(c) = 25 (== len(t) - k - 1) 
+    x = np.asarray([-10., -9., -8., -7., -6., -5., -4., -3., -2.5, -2., -1.5,
+                    -1., -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 4., 5., 6.],
+                    dtype="float")
+    t = [-10.0, -10.0, -10.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0,
+         -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0,
+         5.0, 6.0, 6.0, 6.0, 6.0]
+    c = np.asarray([1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+                    0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
+    k = 3
+
+    res = spalde(x, (t, c, k))
+    res = np.vstack(res)
+    res_splev = np.asarray([splev(x, (t, c, k), nu) for nu in range(4)])
+    xp_assert_close(res, res_splev.T, atol=1e-15)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_gil.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_gil.py
new file mode 100644
index 0000000000000000000000000000000000000000..48197062e0b83a9ef54e45089d9089d49b8ad367
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_gil.py
@@ -0,0 +1,64 @@
+import itertools
+import threading
+import time
+
+import numpy as np
+import pytest
+import scipy.interpolate
+
+
+class TestGIL:
+    """Check if the GIL is properly released by scipy.interpolate functions."""
+
+    def setup_method(self):
+        self.messages = []
+
+    def log(self, message):
+        self.messages.append(message)
+
+    def make_worker_thread(self, target, args):
+        log = self.log
+
+        class WorkerThread(threading.Thread):
+            def run(self):
+                log('interpolation started')
+                target(*args)
+                log('interpolation complete')
+
+        return WorkerThread()
+
+    @pytest.mark.xslow
+    @pytest.mark.xfail(reason='race conditions, may depend on system load')
+    def test_rectbivariatespline(self):
+        def generate_params(n_points):
+            x = y = np.linspace(0, 1000, n_points)
+            x_grid, y_grid = np.meshgrid(x, y)
+            z = x_grid * y_grid
+            return x, y, z
+
+        def calibrate_delay(requested_time):
+            for n_points in itertools.count(5000, 1000):
+                args = generate_params(n_points)
+                time_started = time.time()
+                interpolate(*args)
+                if time.time() - time_started > requested_time:
+                    return args
+
+        def interpolate(x, y, z):
+            scipy.interpolate.RectBivariateSpline(x, y, z)
+
+        args = calibrate_delay(requested_time=3)
+        worker_thread = self.make_worker_thread(interpolate, args)
+        worker_thread.start()
+        for i in range(3):
+            time.sleep(0.5)
+            self.log('working')
+        worker_thread.join()
+        assert self.messages == [
+            'interpolation started',
+            'working',
+            'working',
+            'working',
+            'interpolation complete',
+        ]
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpnd.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpnd.py
new file mode 100644
index 0000000000000000000000000000000000000000..981cd99d9d56e11e8d8ce0635e7b7240c19eef1f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpnd.py
@@ -0,0 +1,440 @@
+import os
+import sys
+
+import numpy as np
+from numpy.testing import suppress_warnings
+from pytest import raises as assert_raises
+import pytest
+from scipy._lib._array_api import xp_assert_close, assert_almost_equal
+
+from scipy._lib._testutils import check_free_memory
+import scipy.interpolate._interpnd as interpnd
+import scipy.spatial._qhull as qhull
+
+import pickle
+import threading
+
+_IS_32BIT = (sys.maxsize < 2**32)
+
+
+def data_file(basename):
+    return os.path.join(os.path.abspath(os.path.dirname(__file__)),
+                        'data', basename)
+
+
+class TestLinearNDInterpolation:
+    def test_smoketest(self):
+        # Test at single points
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+
+        yi = interpnd.LinearNDInterpolator(x, y)(x)
+        assert_almost_equal(y, yi)
+
+    def test_smoketest_alternate(self):
+        # Test at single points, alternate calling convention
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+
+        yi = interpnd.LinearNDInterpolator((x[:,0], x[:,1]), y)(x[:,0], x[:,1])
+        assert_almost_equal(y, yi)
+
+    def test_complex_smoketest(self):
+        # Test at single points
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        yi = interpnd.LinearNDInterpolator(x, y)(x)
+        assert_almost_equal(y, yi)
+
+    def test_tri_input(self):
+        # Test at single points
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        interpolator = interpnd.LinearNDInterpolator(tri, y)
+        yi = interpolator(x)
+        assert_almost_equal(y, yi)
+        assert interpolator.tri is tri
+
+    def test_square(self):
+        # Test barycentric interpolation on a square against a manual
+        # implementation
+
+        points = np.array([(0,0), (0,1), (1,1), (1,0)], dtype=np.float64)
+        values = np.array([1., 2., -3., 5.], dtype=np.float64)
+
+        # NB: assume triangles (0, 1, 3) and (1, 2, 3)
+        #
+        #  1----2
+        #  | \  |
+        #  |  \ |
+        #  0----3
+
+        def ip(x, y):
+            t1 = (x + y <= 1)
+            t2 = ~t1
+
+            x1 = x[t1]
+            y1 = y[t1]
+
+            x2 = x[t2]
+            y2 = y[t2]
+
+            z = 0*x
+
+            z[t1] = (values[0]*(1 - x1 - y1)
+                     + values[1]*y1
+                     + values[3]*x1)
+
+            z[t2] = (values[2]*(x2 + y2 - 1)
+                     + values[1]*(1 - x2)
+                     + values[3]*(1 - y2))
+            return z
+
+        xx, yy = np.broadcast_arrays(np.linspace(0, 1, 14)[:,None],
+                                     np.linspace(0, 1, 14)[None,:])
+        xx = xx.ravel()
+        yy = yy.ravel()
+
+        xi = np.array([xx, yy]).T.copy()
+        zi = interpnd.LinearNDInterpolator(points, values)(xi)
+
+        assert_almost_equal(zi, ip(xx, yy))
+
+    def test_smoketest_rescale(self):
+        # Test at single points
+        x = np.array([(0, 0), (-5, -5), (-5, 5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+
+        yi = interpnd.LinearNDInterpolator(x, y, rescale=True)(x)
+        assert_almost_equal(y, yi)
+
+    def test_square_rescale(self):
+        # Test barycentric interpolation on a rectangle with rescaling
+        # agaings the same implementation without rescaling
+
+        points = np.array([(0,0), (0,100), (10,100), (10,0)], dtype=np.float64)
+        values = np.array([1., 2., -3., 5.], dtype=np.float64)
+
+        xx, yy = np.broadcast_arrays(np.linspace(0, 10, 14)[:,None],
+                                     np.linspace(0, 100, 14)[None,:])
+        xx = xx.ravel()
+        yy = yy.ravel()
+        xi = np.array([xx, yy]).T.copy()
+        zi = interpnd.LinearNDInterpolator(points, values)(xi)
+        zi_rescaled = interpnd.LinearNDInterpolator(points, values,
+                rescale=True)(xi)
+
+        assert_almost_equal(zi, zi_rescaled)
+
+    def test_tripoints_input_rescale(self):
+        # Test at single points
+        x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        yi = interpnd.LinearNDInterpolator(tri.points, y)(x)
+        yi_rescale = interpnd.LinearNDInterpolator(tri.points, y,
+                rescale=True)(x)
+        assert_almost_equal(yi, yi_rescale)
+
+    def test_tri_input_rescale(self):
+        # Test at single points
+        x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        match = ("Rescaling is not supported when passing a "
+                 "Delaunay triangulation as ``points``.")
+        with pytest.raises(ValueError, match=match):
+            interpnd.LinearNDInterpolator(tri, y, rescale=True)(x)
+
+    def test_pickle(self):
+        # Test at single points
+        np.random.seed(1234)
+        x = np.random.rand(30, 2)
+        y = np.random.rand(30) + 1j*np.random.rand(30)
+
+        ip = interpnd.LinearNDInterpolator(x, y)
+        ip2 = pickle.loads(pickle.dumps(ip))
+
+        assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5))
+
+    @pytest.mark.slow
+    @pytest.mark.thread_unsafe
+    @pytest.mark.skipif(_IS_32BIT, reason='it fails on 32-bit')
+    def test_threading(self):
+        # This test was taken from issue 8856
+        # https://github.com/scipy/scipy/issues/8856
+        check_free_memory(10000)
+
+        r_ticks = np.arange(0, 4200, 10)
+        phi_ticks = np.arange(0, 4200, 10)
+        r_grid, phi_grid = np.meshgrid(r_ticks, phi_ticks)
+
+        def do_interp(interpolator, slice_rows, slice_cols):
+            grid_x, grid_y = np.mgrid[slice_rows, slice_cols]
+            res = interpolator((grid_x, grid_y))
+            return res
+
+        points = np.vstack((r_grid.ravel(), phi_grid.ravel())).T
+        values = (r_grid * phi_grid).ravel()
+        interpolator = interpnd.LinearNDInterpolator(points, values)
+
+        worker_thread_1 = threading.Thread(
+            target=do_interp,
+            args=(interpolator, slice(0, 2100), slice(0, 2100)))
+        worker_thread_2 = threading.Thread(
+            target=do_interp,
+            args=(interpolator, slice(2100, 4200), slice(0, 2100)))
+        worker_thread_3 = threading.Thread(
+            target=do_interp,
+            args=(interpolator, slice(0, 2100), slice(2100, 4200)))
+        worker_thread_4 = threading.Thread(
+            target=do_interp,
+            args=(interpolator, slice(2100, 4200), slice(2100, 4200)))
+
+        worker_thread_1.start()
+        worker_thread_2.start()
+        worker_thread_3.start()
+        worker_thread_4.start()
+
+        worker_thread_1.join()
+        worker_thread_2.join()
+        worker_thread_3.join()
+        worker_thread_4.join()
+
+
+class TestEstimateGradients2DGlobal:
+    def test_smoketest(self):
+        x = np.array([(0, 0), (0, 2),
+                      (1, 0), (1, 2), (0.25, 0.75), (0.6, 0.8)], dtype=float)
+        tri = qhull.Delaunay(x)
+
+        # Should be exact for linear functions, independent of triangulation
+
+        funcs = [
+            (lambda x, y: 0*x + 1, (0, 0)),
+            (lambda x, y: 0 + x, (1, 0)),
+            (lambda x, y: -2 + y, (0, 1)),
+            (lambda x, y: 3 + 3*x + 14.15*y, (3, 14.15))
+        ]
+
+        for j, (func, grad) in enumerate(funcs):
+            z = func(x[:,0], x[:,1])
+            dz = interpnd.estimate_gradients_2d_global(tri, z, tol=1e-6)
+
+            assert dz.shape == (6, 2)
+            xp_assert_close(dz, np.array(grad)[None,:] + 0*dz,
+                            rtol=1e-5, atol=1e-5, err_msg="item %d" % j)
+
+    def test_regression_2359(self):
+        # Check regression --- for certain point sets, gradient
+        # estimation could end up in an infinite loop
+        points = np.load(data_file('estimate_gradients_hang.npy'))
+        values = np.random.rand(points.shape[0])
+        tri = qhull.Delaunay(points)
+
+        # This should not hang
+        with suppress_warnings() as sup:
+            sup.filter(interpnd.GradientEstimationWarning,
+                       "Gradient estimation did not converge")
+            interpnd.estimate_gradients_2d_global(tri, values, maxiter=1)
+
+
+class TestCloughTocher2DInterpolator:
+
+    def _check_accuracy(self, func, x=None, tol=1e-6, alternate=False,
+                        rescale=False, **kw):
+        rng = np.random.RandomState(1234)
+        # np.random.seed(1234)
+        if x is None:
+            x = np.array([(0, 0), (0, 1),
+                          (1, 0), (1, 1), (0.25, 0.75), (0.6, 0.8),
+                          (0.5, 0.2)],
+                         dtype=float)
+
+        if not alternate:
+            ip = interpnd.CloughTocher2DInterpolator(x, func(x[:,0], x[:,1]),
+                                                     tol=1e-6, rescale=rescale)
+        else:
+            ip = interpnd.CloughTocher2DInterpolator((x[:,0], x[:,1]),
+                                                     func(x[:,0], x[:,1]),
+                                                     tol=1e-6, rescale=rescale)
+
+        p = rng.rand(50, 2)
+
+        if not alternate:
+            a = ip(p)
+        else:
+            a = ip(p[:,0], p[:,1])
+        b = func(p[:,0], p[:,1])
+
+        try:
+            xp_assert_close(a, b, **kw)
+        except AssertionError:
+            print("_check_accuracy: abs(a-b):", abs(a - b))
+            print("ip.grad:", ip.grad)
+            raise
+
+    def test_linear_smoketest(self):
+        # Should be exact for linear functions, independent of triangulation
+        funcs = [
+            lambda x, y: 0*x + 1,
+            lambda x, y: 0 + x,
+            lambda x, y: -2 + y,
+            lambda x, y: 3 + 3*x + 14.15*y,
+        ]
+
+        for j, func in enumerate(funcs):
+            self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
+                                 err_msg="Function %d" % j)
+            self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
+                                 alternate=True,
+                                 err_msg="Function (alternate) %d" % j)
+            # check rescaling
+            self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
+                                 err_msg="Function (rescaled) %d" % j, rescale=True)
+            self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
+                                 alternate=True, rescale=True,
+                                 err_msg="Function (alternate, rescaled) %d" % j)
+
+    def test_quadratic_smoketest(self):
+        # Should be reasonably accurate for quadratic functions
+        funcs = [
+            lambda x, y: x**2,
+            lambda x, y: y**2,
+            lambda x, y: x**2 - y**2,
+            lambda x, y: x*y,
+        ]
+
+        for j, func in enumerate(funcs):
+            self._check_accuracy(func, tol=1e-9, atol=0.22, rtol=0,
+                                 err_msg="Function %d" % j)
+            self._check_accuracy(func, tol=1e-9, atol=0.22, rtol=0,
+                                 err_msg="Function %d" % j, rescale=True)
+
+    def test_tri_input(self):
+        # Test at single points
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        yi = interpnd.CloughTocher2DInterpolator(tri, y)(x)
+        assert_almost_equal(y, yi)
+
+    def test_tri_input_rescale(self):
+        # Test at single points
+        x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        match = ("Rescaling is not supported when passing a "
+                 "Delaunay triangulation as ``points``.")
+        with pytest.raises(ValueError, match=match):
+            interpnd.CloughTocher2DInterpolator(tri, y, rescale=True)(x)
+
+    def test_tripoints_input_rescale(self):
+        # Test at single points
+        x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 3j*y
+
+        tri = qhull.Delaunay(x)
+        yi = interpnd.CloughTocher2DInterpolator(tri.points, y)(x)
+        yi_rescale = interpnd.CloughTocher2DInterpolator(tri.points, y, rescale=True)(x)
+        assert_almost_equal(yi, yi_rescale)
+
+    @pytest.mark.fail_slow(5)
+    def test_dense(self):
+        # Should be more accurate for dense meshes
+        funcs = [
+            lambda x, y: x**2,
+            lambda x, y: y**2,
+            lambda x, y: x**2 - y**2,
+            lambda x, y: x*y,
+            lambda x, y: np.cos(2*np.pi*x)*np.sin(2*np.pi*y)
+        ]
+
+        rng = np.random.RandomState(4321)  # use a different seed than the check!
+        grid = np.r_[np.array([(0,0), (0,1), (1,0), (1,1)], dtype=float),
+                     rng.rand(30*30, 2)]
+
+        for j, func in enumerate(funcs):
+            self._check_accuracy(func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2,
+                                 err_msg="Function %d" % j)
+            self._check_accuracy(func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2,
+                                 err_msg="Function %d" % j, rescale=True)
+
+    def test_wrong_ndim(self):
+        x = np.random.randn(30, 3)
+        y = np.random.randn(30)
+        assert_raises(ValueError, interpnd.CloughTocher2DInterpolator, x, y)
+
+    def test_pickle(self):
+        # Test at single points
+        rng = np.random.RandomState(1234)
+        x = rng.rand(30, 2)
+        y = rng.rand(30) + 1j*rng.rand(30)
+
+        ip = interpnd.CloughTocher2DInterpolator(x, y)
+        ip2 = pickle.loads(pickle.dumps(ip))
+
+        assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5))
+
+    def test_boundary_tri_symmetry(self):
+        # Interpolation at neighbourless triangles should retain
+        # symmetry with mirroring the triangle.
+
+        # Equilateral triangle
+        points = np.array([(0, 0), (1, 0), (0.5, np.sqrt(3)/2)])
+        values = np.array([1, 0, 0])
+
+        ip = interpnd.CloughTocher2DInterpolator(points, values)
+
+        # Set gradient to zero at vertices
+        ip.grad[...] = 0
+
+        # Interpolation should be symmetric vs. bisector
+        alpha = 0.3
+        p1 = np.array([0.5 * np.cos(alpha), 0.5 * np.sin(alpha)])
+        p2 = np.array([0.5 * np.cos(np.pi/3 - alpha), 0.5 * np.sin(np.pi/3 - alpha)])
+
+        v1 = ip(p1)
+        v2 = ip(p2)
+        xp_assert_close(v1, v2)
+
+        # ... and affine invariant
+        rng = np.random.RandomState(1)
+        A = rng.randn(2, 2)
+        b = rng.randn(2)
+
+        points = A.dot(points.T).T + b[None,:]
+        p1 = A.dot(p1) + b
+        p2 = A.dot(p2) + b
+
+        ip = interpnd.CloughTocher2DInterpolator(points, values)
+        ip.grad[...] = 0
+
+        w1 = ip(p1)
+        w2 = ip(p2)
+        xp_assert_close(w1, v1)
+        xp_assert_close(w2, v2)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpolate.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpolate.py
new file mode 100644
index 0000000000000000000000000000000000000000..24a6907b7b050ddb0686cf8b1761bfd50eaf692a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_interpolate.py
@@ -0,0 +1,2586 @@
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, assert_almost_equal, assert_array_almost_equal
+)
+from pytest import raises as assert_raises
+import pytest
+
+from numpy import mgrid, pi, sin, poly1d
+import numpy as np
+
+from scipy.interpolate import (interp1d, interp2d, lagrange, PPoly, BPoly,
+        splrep, splev, splantider, splint, sproot, Akima1DInterpolator,
+        NdPPoly, BSpline, PchipInterpolator)
+
+from scipy.special import poch, gamma
+
+from scipy.interpolate import _ppoly
+
+from scipy._lib._gcutils import assert_deallocated, IS_PYPY
+from scipy._lib._testutils import _run_concurrent_barrier
+
+from scipy.integrate import nquad
+
+from scipy.special import binom
+
+
+class TestInterp2D:
+    def test_interp2d(self):
+        y, x = mgrid[0:2:20j, 0:pi:21j]
+        z = sin(x+0.5*y)
+        with assert_raises(NotImplementedError):
+            interp2d(x, y, z)
+
+
+class TestInterp1D:
+
+    def setup_method(self):
+        self.x5 = np.arange(5.)
+        self.x10 = np.arange(10.)
+        self.y10 = np.arange(10.)
+        self.x25 = self.x10.reshape((2,5))
+        self.x2 = np.arange(2.)
+        self.y2 = np.arange(2.)
+        self.x1 = np.array([0.])
+        self.y1 = np.array([0.])
+
+        self.y210 = np.arange(20.).reshape((2, 10))
+        self.y102 = np.arange(20.).reshape((10, 2))
+        self.y225 = np.arange(20.).reshape((2, 2, 5))
+        self.y25 = np.arange(10.).reshape((2, 5))
+        self.y235 = np.arange(30.).reshape((2, 3, 5))
+        self.y325 = np.arange(30.).reshape((3, 2, 5))
+
+        # Edge updated test matrix 1
+        # array([[ 30,   1,   2,   3,   4,   5,   6,   7,   8, -30],
+        #        [ 30,  11,  12,  13,  14,  15,  16,  17,  18, -30]])
+        self.y210_edge_updated = np.arange(20.).reshape((2, 10))
+        self.y210_edge_updated[:, 0] = 30
+        self.y210_edge_updated[:, -1] = -30
+
+        # Edge updated test matrix 2
+        # array([[ 30,  30],
+        #       [  2,   3],
+        #       [  4,   5],
+        #       [  6,   7],
+        #       [  8,   9],
+        #       [ 10,  11],
+        #       [ 12,  13],
+        #       [ 14,  15],
+        #       [ 16,  17],
+        #       [-30, -30]])
+        self.y102_edge_updated = np.arange(20.).reshape((10, 2))
+        self.y102_edge_updated[0, :] = 30
+        self.y102_edge_updated[-1, :] = -30
+
+        self.fill_value = -100.0
+
+    def test_validation(self):
+        # Make sure that appropriate exceptions are raised when invalid values
+        # are given to the constructor.
+
+        # These should all work.
+        for kind in ('nearest', 'nearest-up', 'zero', 'linear', 'slinear',
+                     'quadratic', 'cubic', 'previous', 'next'):
+            interp1d(self.x10, self.y10, kind=kind)
+            interp1d(self.x10, self.y10, kind=kind, fill_value="extrapolate")
+        interp1d(self.x10, self.y10, kind='linear', fill_value=(-1, 1))
+        interp1d(self.x10, self.y10, kind='linear',
+                 fill_value=np.array([-1]))
+        interp1d(self.x10, self.y10, kind='linear',
+                 fill_value=(-1,))
+        interp1d(self.x10, self.y10, kind='linear',
+                 fill_value=-1)
+        interp1d(self.x10, self.y10, kind='linear',
+                 fill_value=(-1, -1))
+        interp1d(self.x10, self.y10, kind=0)
+        interp1d(self.x10, self.y10, kind=1)
+        interp1d(self.x10, self.y10, kind=2)
+        interp1d(self.x10, self.y10, kind=3)
+        interp1d(self.x10, self.y210, kind='linear', axis=-1,
+                 fill_value=(-1, -1))
+        interp1d(self.x2, self.y210, kind='linear', axis=0,
+                 fill_value=np.ones(10))
+        interp1d(self.x2, self.y210, kind='linear', axis=0,
+                 fill_value=(np.ones(10), np.ones(10)))
+        interp1d(self.x2, self.y210, kind='linear', axis=0,
+                 fill_value=(np.ones(10), -1))
+
+        # x array must be 1D.
+        assert_raises(ValueError, interp1d, self.x25, self.y10)
+
+        # y array cannot be a scalar.
+        assert_raises(ValueError, interp1d, self.x10, np.array(0))
+
+        # Check for x and y arrays having the same length.
+        assert_raises(ValueError, interp1d, self.x10, self.y2)
+        assert_raises(ValueError, interp1d, self.x2, self.y10)
+        assert_raises(ValueError, interp1d, self.x10, self.y102)
+        interp1d(self.x10, self.y210)
+        interp1d(self.x10, self.y102, axis=0)
+
+        # Check for x and y having at least 1 element.
+        assert_raises(ValueError, interp1d, self.x1, self.y10)
+        assert_raises(ValueError, interp1d, self.x10, self.y1)
+
+        # Bad fill values
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=(-1, -1, -1))  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=[-1, -1, -1])  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=np.array((-1, -1, -1)))  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=[[-1]])  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=[-1, -1])  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=np.array([]))  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x10, self.y10, kind='linear',
+                      fill_value=())  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x2, self.y210, kind='linear',
+                      axis=0, fill_value=[-1, -1])  # doesn't broadcast
+        assert_raises(ValueError, interp1d, self.x2, self.y210, kind='linear',
+                      axis=0, fill_value=(0., [-1, -1]))  # above doesn't bc
+
+    def test_init(self):
+        # Check that the attributes are initialized appropriately by the
+        # constructor.
+        assert interp1d(self.x10, self.y10).copy
+        assert not interp1d(self.x10, self.y10, copy=False).copy
+        assert interp1d(self.x10, self.y10).bounds_error
+        assert not interp1d(self.x10, self.y10, bounds_error=False).bounds_error
+        assert np.isnan(interp1d(self.x10, self.y10).fill_value)
+        assert interp1d(self.x10, self.y10, fill_value=3.0).fill_value == 3.0
+        assert (interp1d(self.x10, self.y10, fill_value=(1.0, 2.0)).fill_value ==
+                (1.0, 2.0)
+        )
+        assert interp1d(self.x10, self.y10).axis == 0
+        assert interp1d(self.x10, self.y210).axis == 1
+        assert interp1d(self.x10, self.y102, axis=0).axis == 0
+        xp_assert_equal(interp1d(self.x10, self.y10).x, self.x10)
+        xp_assert_equal(interp1d(self.x10, self.y10).y, self.y10)
+        xp_assert_equal(interp1d(self.x10, self.y210).y, self.y210)
+
+    def test_assume_sorted(self):
+        # Check for unsorted arrays
+        interp10 = interp1d(self.x10, self.y10)
+        interp10_unsorted = interp1d(self.x10[::-1], self.y10[::-1])
+
+        assert_array_almost_equal(interp10_unsorted(self.x10), self.y10)
+        assert_array_almost_equal(interp10_unsorted(1.2), np.array(1.2))
+        assert_array_almost_equal(interp10_unsorted([2.4, 5.6, 6.0]),
+                                  interp10([2.4, 5.6, 6.0]))
+
+        # Check assume_sorted keyword (defaults to False)
+        interp10_assume_kw = interp1d(self.x10[::-1], self.y10[::-1],
+                                      assume_sorted=False)
+        assert_array_almost_equal(interp10_assume_kw(self.x10), self.y10)
+
+        interp10_assume_kw2 = interp1d(self.x10[::-1], self.y10[::-1],
+                                       assume_sorted=True)
+        # Should raise an error for unsorted input if assume_sorted=True
+        assert_raises(ValueError, interp10_assume_kw2, self.x10)
+
+        # Check that if y is a 2-D array, things are still consistent
+        interp10_y_2d = interp1d(self.x10, self.y210)
+        interp10_y_2d_unsorted = interp1d(self.x10[::-1], self.y210[:, ::-1])
+        assert_array_almost_equal(interp10_y_2d(self.x10),
+                                  interp10_y_2d_unsorted(self.x10))
+
+    def test_linear(self):
+        for kind in ['linear', 'slinear']:
+            self._check_linear(kind)
+
+    def _check_linear(self, kind):
+        # Check the actual implementation of linear interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind=kind)
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.2))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2.4, 5.6, 6.0]))
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind=kind,
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        np.asarray([-1.0, 0, 9, 11]), rtol=1e-14)
+
+        opts = dict(kind=kind,
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+    def test_linear_dtypes(self):
+        # regression test for gh-5898, where 1D linear interpolation has been
+        # delegated to numpy.interp for all float dtypes, and the latter was
+        # not handling e.g. np.float128.
+        for dtyp in [np.float16,
+                     np.float32,
+                     np.float64,
+                     np.longdouble]:
+            x = np.arange(8, dtype=dtyp)
+            y = x
+            yp = interp1d(x, y, kind='linear')(x)
+            assert yp.dtype == dtyp
+            xp_assert_close(yp, y, atol=1e-15)
+
+        # regression test for gh-14531, where 1D linear interpolation has been
+        # has been extended to delegate to numpy.interp for integer dtypes
+        x = [0, 1, 2]
+        y = [np.nan, 0, 1]
+        yp = interp1d(x, y)(x)
+        xp_assert_close(yp, y, atol=1e-15)
+
+    def test_slinear_dtypes(self):
+        # regression test for gh-7273: 1D slinear interpolation fails with
+        # float32 inputs
+        dt_r = [np.float16, np.float32, np.float64]
+        dt_rc = dt_r + [np.complex64, np.complex128]
+        spline_kinds = ['slinear', 'zero', 'quadratic', 'cubic']
+        for dtx in dt_r:
+            x = np.arange(0, 10, dtype=dtx)
+            for dty in dt_rc:
+                y = np.exp(-x/3.0).astype(dty)
+                for dtn in dt_r:
+                    xnew = x.astype(dtn)
+                    for kind in spline_kinds:
+                        f = interp1d(x, y, kind=kind, bounds_error=False)
+                        xp_assert_close(f(xnew), y, atol=1e-7,
+                                        check_dtype=False,
+                                        err_msg=f"{dtx}, {dty} {dtn}")
+
+    def test_cubic(self):
+        # Check the actual implementation of spline interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind='cubic')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.2))
+        assert_array_almost_equal(interp10(1.5), np.array(1.5))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2.4, 5.6, 6.0]),)
+
+    def test_nearest(self):
+        # Check the actual implementation of nearest-neighbour interpolation.
+        # Nearest asserts that half-integer case (1.5) rounds down to 1
+        interp10 = interp1d(self.x10, self.y10, kind='nearest')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.))
+        assert_array_almost_equal(interp10(1.5), np.array(1.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2., 6., 6.]),)
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind='nearest',
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        [0.0, 0, 9, 9], rtol=1e-14)
+
+        opts = dict(kind='nearest',
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+    def test_nearest_up(self):
+        # Check the actual implementation of nearest-neighbour interpolation.
+        # Nearest-up asserts that half-integer case (1.5) rounds up to 2
+        interp10 = interp1d(self.x10, self.y10, kind='nearest-up')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.))
+        assert_array_almost_equal(interp10(1.5), np.array(2.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2., 6., 6.]),)
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind='nearest-up',
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        [0.0, 0, 9, 9], rtol=1e-14)
+
+        opts = dict(kind='nearest-up',
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+    def test_previous(self):
+        # Check the actual implementation of previous interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind='previous')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.))
+        assert_array_almost_equal(interp10(1.5), np.array(1.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2., 5., 6.]),)
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind='previous',
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        [np.nan, 0, 9, 9], rtol=1e-14)
+
+        # Tests for gh-9591
+        interpolator1D = interp1d(self.x10, self.y10, kind="previous",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator1D([-1, -2, 5, 8, 12, 25]),
+                        [np.nan, np.nan, 5, 8, 9, 9])
+
+        interpolator2D = interp1d(self.x10, self.y210, kind="previous",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]),
+                        [[np.nan, np.nan, 5, 8, 9, 9],
+                         [np.nan, np.nan, 15, 18, 19, 19]])
+
+        interpolator2DAxis0 = interp1d(self.x10, self.y102, kind="previous",
+                                       axis=0, fill_value='extrapolate')
+        xp_assert_close(interpolator2DAxis0([-2, 5, 12]),
+                        [[np.nan, np.nan],
+                         [10, 11],
+                         [18, 19]])
+
+        opts = dict(kind='previous',
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+        # Tests for gh-16813
+        interpolator1D = interp1d([0, 1, 2],
+                                  [0, 1, -1], kind="previous",
+                                  fill_value='extrapolate',
+                                  assume_sorted=True)
+        xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]),
+                        [np.nan, np.nan, 0, 1, -1, -1, -1])
+
+        interpolator1D = interp1d([2, 0, 1],  # x is not ascending
+                                  [-1, 0, 1], kind="previous",
+                                  fill_value='extrapolate',
+                                  assume_sorted=False)
+        xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]),
+                        [np.nan, np.nan, 0, 1, -1, -1, -1])
+
+        interpolator2D = interp1d(self.x10, self.y210_edge_updated,
+                                  kind="previous",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]),
+                        [[np.nan, np.nan, 5, 8, -30, -30],
+                         [np.nan, np.nan, 15, 18, -30, -30]])
+
+        interpolator2DAxis0 = interp1d(self.x10, self.y102_edge_updated,
+                                       kind="previous",
+                                       axis=0, fill_value='extrapolate')
+        xp_assert_close(interpolator2DAxis0([-2, 5, 12]),
+                        [[np.nan, np.nan],
+                         [10, 11],
+                         [-30, -30]])
+
+    def test_next(self):
+        # Check the actual implementation of next interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind='next')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(2.))
+        assert_array_almost_equal(interp10(1.5), np.array(2.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([3., 6., 6.]),)
+
+        # test fill_value="extrapolate"
+        extrapolator = interp1d(self.x10, self.y10, kind='next',
+                                fill_value='extrapolate')
+        xp_assert_close(extrapolator([-1., 0, 9, 11]),
+                        [0, 0, 9, np.nan], rtol=1e-14)
+
+        # Tests for gh-9591
+        interpolator1D = interp1d(self.x10, self.y10, kind="next",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator1D([-1, -2, 5, 8, 12, 25]),
+                        [0, 0, 5, 8, np.nan, np.nan])
+
+        interpolator2D = interp1d(self.x10, self.y210, kind="next",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]),
+                        [[0, 0, 5, 8, np.nan, np.nan],
+                         [10, 10, 15, 18, np.nan, np.nan]])
+
+        interpolator2DAxis0 = interp1d(self.x10, self.y102, kind="next",
+                                       axis=0, fill_value='extrapolate')
+        xp_assert_close(interpolator2DAxis0([-2, 5, 12]),
+                        [[0, 1],
+                         [10, 11],
+                         [np.nan, np.nan]])
+
+        opts = dict(kind='next',
+                    fill_value='extrapolate',
+                    bounds_error=True)
+        assert_raises(ValueError, interp1d, self.x10, self.y10, **opts)
+
+        # Tests for gh-16813
+        interpolator1D = interp1d([0, 1, 2],
+                                  [0, 1, -1], kind="next",
+                                  fill_value='extrapolate',
+                                  assume_sorted=True)
+        xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]),
+                        [0, 0, 0, 1, -1, np.nan, np.nan])
+
+        interpolator1D = interp1d([2, 0, 1],  # x is not ascending
+                                  [-1, 0, 1], kind="next",
+                                  fill_value='extrapolate',
+                                  assume_sorted=False)
+        xp_assert_close(interpolator1D([-2, -1, 0, 1, 2, 3, 5]),
+                        [0, 0, 0, 1, -1, np.nan, np.nan])
+
+        interpolator2D = interp1d(self.x10, self.y210_edge_updated,
+                                  kind="next",
+                                  fill_value='extrapolate')
+        xp_assert_close(interpolator2D([-1, -2, 5, 8, 12, 25]),
+                        [[30, 30, 5, 8, np.nan, np.nan],
+                         [30, 30, 15, 18, np.nan, np.nan]])
+
+        interpolator2DAxis0 = interp1d(self.x10, self.y102_edge_updated,
+                                       kind="next",
+                                       axis=0, fill_value='extrapolate')
+        xp_assert_close(interpolator2DAxis0([-2, 5, 12]),
+                        [[30, 30],
+                         [10, 11],
+                         [np.nan, np.nan]])
+
+    def test_zero(self):
+        # Check the actual implementation of zero-order spline interpolation.
+        interp10 = interp1d(self.x10, self.y10, kind='zero')
+        assert_array_almost_equal(interp10(self.x10), self.y10)
+        assert_array_almost_equal(interp10(1.2), np.array(1.))
+        assert_array_almost_equal(interp10(1.5), np.array(1.))
+        assert_array_almost_equal(interp10([2.4, 5.6, 6.0]),
+                                  np.array([2., 5., 6.]))
+
+    def bounds_check_helper(self, interpolant, test_array, fail_value):
+        # Asserts that a ValueError is raised and that the error message
+        # contains the value causing this exception.
+        assert_raises(ValueError, interpolant, test_array)
+        try:
+            interpolant(test_array)
+        except ValueError as err:
+            assert (f"{fail_value}" in str(err))
+
+    def _bounds_check(self, kind='linear'):
+        # Test that our handling of out-of-bounds input is correct.
+        extrap10 = interp1d(self.x10, self.y10, fill_value=self.fill_value,
+                            bounds_error=False, kind=kind)
+
+        xp_assert_equal(extrap10(11.2), np.array(self.fill_value))
+        xp_assert_equal(extrap10(-3.4), np.array(self.fill_value))
+        xp_assert_equal(extrap10([[[11.2], [-3.4], [12.6], [19.3]]]),
+                           np.array(self.fill_value), check_shape=False)
+        xp_assert_equal(extrap10._check_bounds(
+                               np.array([-1.0, 0.0, 5.0, 9.0, 11.0])),
+                           np.array([[True, False, False, False, False],
+                                     [False, False, False, False, True]]))
+
+        raises_bounds_error = interp1d(self.x10, self.y10, bounds_error=True,
+                                       kind=kind)
+
+        self.bounds_check_helper(raises_bounds_error, -1.0, -1.0)
+        self.bounds_check_helper(raises_bounds_error, 11.0, 11.0)
+        self.bounds_check_helper(raises_bounds_error, [0.0, -1.0, 0.0], -1.0)
+        self.bounds_check_helper(raises_bounds_error, [0.0, 1.0, 21.0], 21.0)
+
+        raises_bounds_error([0.0, 5.0, 9.0])
+
+    def _bounds_check_int_nan_fill(self, kind='linear'):
+        x = np.arange(10).astype(int)
+        y = np.arange(10).astype(int)
+        c = interp1d(x, y, kind=kind, fill_value=np.nan, bounds_error=False)
+        yi = c(x - 1)
+        assert np.isnan(yi[0])
+        assert_array_almost_equal(yi, np.r_[np.nan, y[:-1]])
+
+    def test_bounds(self):
+        for kind in ('linear', 'cubic', 'nearest', 'previous', 'next',
+                     'slinear', 'zero', 'quadratic'):
+            self._bounds_check(kind)
+            self._bounds_check_int_nan_fill(kind)
+
+    def _check_fill_value(self, kind):
+        interp = interp1d(self.x10, self.y10, kind=kind,
+                          fill_value=(-100, 100), bounds_error=False)
+        assert_array_almost_equal(interp(10), np.asarray(100.))
+        assert_array_almost_equal(interp(-10), np.asarray(-100.))
+        assert_array_almost_equal(interp([-10, 10]), [-100, 100])
+
+        # Proper broadcasting:
+        #    interp along axis of length 5
+        # other dim=(2, 3), (3, 2), (2, 2), or (2,)
+
+        # one singleton fill_value (works for all)
+        for y in (self.y235, self.y325, self.y225, self.y25):
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=100, bounds_error=False)
+            assert_array_almost_equal(interp(10), np.asarray(100.))
+            assert_array_almost_equal(interp(-10), np.asarray(100.))
+            assert_array_almost_equal(interp([-10, 10]), np.asarray(100.))
+
+            # singleton lower, singleton upper
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=(-100, 100), bounds_error=False)
+            assert_array_almost_equal(interp(10), np.asarray(100.))
+            assert_array_almost_equal(interp(-10), np.asarray(-100.))
+            if y.ndim == 3:
+                result = [[[-100, 100]] * y.shape[1]] * y.shape[0]
+            else:
+                result = [[-100, 100]] * y.shape[0]
+            assert_array_almost_equal(interp([-10, 10]), result)
+
+        # one broadcastable (3,) fill_value
+        fill_value = [100, 200, 300]
+        for y in (self.y325, self.y225):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        interp = interp1d(self.x5, self.y235, kind=kind, axis=-1,
+                          fill_value=fill_value, bounds_error=False)
+        assert_array_almost_equal(interp(10), [[100, 200, 300]] * 2)
+        assert_array_almost_equal(interp(-10), [[100, 200, 300]] * 2)
+        assert_array_almost_equal(interp([-10, 10]), [[[100, 100],
+                                                       [200, 200],
+                                                       [300, 300]]] * 2)
+
+        # one broadcastable (2,) fill_value
+        fill_value = [100, 200]
+        assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind,
+                      axis=-1, fill_value=fill_value, bounds_error=False)
+        for y in (self.y225, self.y325, self.y25):
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            result = [100, 200]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp(10), result)
+            assert_array_almost_equal(interp(-10), result)
+            result = [[100, 100], [200, 200]]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp([-10, 10]), result)
+
+        # broadcastable (3,) lower, singleton upper
+        fill_value = (np.array([-100, -200, -300]), 100)
+        for y in (self.y325, self.y225):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        interp = interp1d(self.x5, self.y235, kind=kind, axis=-1,
+                          fill_value=fill_value, bounds_error=False)
+        assert_array_almost_equal(interp(10), np.asarray(100.))
+        assert_array_almost_equal(interp(-10), [[-100, -200, -300]] * 2)
+        assert_array_almost_equal(interp([-10, 10]), [[[-100, 100],
+                                                       [-200, 100],
+                                                       [-300, 100]]] * 2)
+
+        # broadcastable (2,) lower, singleton upper
+        fill_value = (np.array([-100, -200]), 100)
+        assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind,
+                      axis=-1, fill_value=fill_value, bounds_error=False)
+        for y in (self.y225, self.y325, self.y25):
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            assert_array_almost_equal(interp(10), np.asarray(100))
+            result = [-100, -200]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp(-10), result)
+            result = [[-100, 100], [-200, 100]]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp([-10, 10]), result)
+
+        # broadcastable (3,) lower, broadcastable (3,) upper
+        fill_value = ([-100, -200, -300], [100, 200, 300])
+        for y in (self.y325, self.y225):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        for ii in range(2):  # check ndarray as well as list here
+            if ii == 1:
+                fill_value = tuple(np.array(f) for f in fill_value)
+            interp = interp1d(self.x5, self.y235, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            assert_array_almost_equal(interp(10), [[100, 200, 300]] * 2)
+            assert_array_almost_equal(interp(-10), [[-100, -200, -300]] * 2)
+            assert_array_almost_equal(interp([-10, 10]), [[[-100, 100],
+                                                           [-200, 200],
+                                                           [-300, 300]]] * 2)
+        # broadcastable (2,) lower, broadcastable (2,) upper
+        fill_value = ([-100, -200], [100, 200])
+        assert_raises(ValueError, interp1d, self.x5, self.y235, kind=kind,
+                      axis=-1, fill_value=fill_value, bounds_error=False)
+        for y in (self.y325, self.y225, self.y25):
+            interp = interp1d(self.x5, y, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            result = [100, 200]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp(10), result)
+            result = [-100, -200]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp(-10), result)
+            result = [[-100, 100], [-200, 200]]
+            if y.ndim == 3:
+                result = [result] * y.shape[0]
+            assert_array_almost_equal(interp([-10, 10]), result)
+
+        # one broadcastable (2, 2) array-like
+        fill_value = [[100, 200], [1000, 2000]]
+        for y in (self.y235, self.y325, self.y25):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        for ii in range(2):
+            if ii == 1:
+                fill_value = np.array(fill_value)
+            interp = interp1d(self.x5, self.y225, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            assert_array_almost_equal(interp(10), [[100, 200], [1000, 2000]])
+            assert_array_almost_equal(interp(-10), [[100, 200], [1000, 2000]])
+            assert_array_almost_equal(interp([-10, 10]), [[[100, 100],
+                                                           [200, 200]],
+                                                          [[1000, 1000],
+                                                           [2000, 2000]]])
+
+        # broadcastable (2, 2) lower, broadcastable (2, 2) upper
+        fill_value = ([[-100, -200], [-1000, -2000]],
+                      [[100, 200], [1000, 2000]])
+        for y in (self.y235, self.y325, self.y25):
+            assert_raises(ValueError, interp1d, self.x5, y, kind=kind,
+                          axis=-1, fill_value=fill_value, bounds_error=False)
+        for ii in range(2):
+            if ii == 1:
+                fill_value = (np.array(fill_value[0]), np.array(fill_value[1]))
+            interp = interp1d(self.x5, self.y225, kind=kind, axis=-1,
+                              fill_value=fill_value, bounds_error=False)
+            assert_array_almost_equal(interp(10), [[100, 200], [1000, 2000]])
+            assert_array_almost_equal(interp(-10), [[-100, -200],
+                                                    [-1000, -2000]])
+            assert_array_almost_equal(interp([-10, 10]), [[[-100, 100],
+                                                           [-200, 200]],
+                                                          [[-1000, 1000],
+                                                           [-2000, 2000]]])
+
+    def test_fill_value(self):
+        # test that two-element fill value works
+        for kind in ('linear', 'nearest', 'cubic', 'slinear', 'quadratic',
+                     'zero', 'previous', 'next'):
+            self._check_fill_value(kind)
+
+    def test_fill_value_writeable(self):
+        # backwards compat: fill_value is a public writeable attribute
+        interp = interp1d(self.x10, self.y10, fill_value=123.0)
+        assert interp.fill_value == 123.0
+        interp.fill_value = 321.0
+        assert interp.fill_value == 321.0
+
+    def _nd_check_interp(self, kind='linear'):
+        # Check the behavior when the inputs and outputs are multidimensional.
+
+        # Multidimensional input.
+        interp10 = interp1d(self.x10, self.y10, kind=kind)
+        assert_array_almost_equal(interp10(np.array([[3., 5.], [2., 7.]])),
+                                  np.array([[3., 5.], [2., 7.]]))
+
+        # Scalar input -> 0-dim scalar array output
+        assert isinstance(interp10(1.2), np.ndarray)
+        assert interp10(1.2).shape == ()
+
+        # Multidimensional outputs.
+        interp210 = interp1d(self.x10, self.y210, kind=kind)
+        assert_array_almost_equal(interp210(1.), np.array([1., 11.]))
+        assert_array_almost_equal(interp210(np.array([1., 2.])),
+                                  np.array([[1., 2.], [11., 12.]]))
+
+        interp102 = interp1d(self.x10, self.y102, axis=0, kind=kind)
+        assert_array_almost_equal(interp102(1.), np.array([2.0, 3.0]))
+        assert_array_almost_equal(interp102(np.array([1., 3.])),
+                                  np.array([[2., 3.], [6., 7.]]))
+
+        # Both at the same time!
+        x_new = np.array([[3., 5.], [2., 7.]])
+        assert_array_almost_equal(interp210(x_new),
+                                  np.array([[[3., 5.], [2., 7.]],
+                                            [[13., 15.], [12., 17.]]]))
+        assert_array_almost_equal(interp102(x_new),
+                                  np.array([[[6., 7.], [10., 11.]],
+                                            [[4., 5.], [14., 15.]]]))
+
+    def _nd_check_shape(self, kind='linear'):
+        # Check large N-D output shape
+        a = [4, 5, 6, 7]
+        y = np.arange(np.prod(a)).reshape(*a)
+        for n, s in enumerate(a):
+            x = np.arange(s)
+            z = interp1d(x, y, axis=n, kind=kind)
+            assert_array_almost_equal(z(x), y, err_msg=kind)
+
+            x2 = np.arange(2*3*1).reshape((2,3,1)) / 12.
+            b = list(a)
+            b[n:n+1] = [2, 3, 1]
+            assert z(x2).shape == tuple(b), kind
+
+    def test_nd(self):
+        for kind in ('linear', 'cubic', 'slinear', 'quadratic', 'nearest',
+                     'zero', 'previous', 'next'):
+            self._nd_check_interp(kind)
+            self._nd_check_shape(kind)
+
+    def _check_complex(self, dtype=np.complex128, kind='linear'):
+        x = np.array([1, 2.5, 3, 3.1, 4, 6.4, 7.9, 8.0, 9.5, 10])
+        y = x * x ** (1 + 2j)
+        y = y.astype(dtype)
+
+        # simple test
+        c = interp1d(x, y, kind=kind)
+        assert_array_almost_equal(y[:-1], c(x)[:-1])
+
+        # check against interpolating real+imag separately
+        xi = np.linspace(1, 10, 31)
+        cr = interp1d(x, y.real, kind=kind)
+        ci = interp1d(x, y.imag, kind=kind)
+        assert_array_almost_equal(c(xi).real, cr(xi))
+        assert_array_almost_equal(c(xi).imag, ci(xi))
+
+    def test_complex(self):
+        for kind in ('linear', 'nearest', 'cubic', 'slinear', 'quadratic',
+                     'zero', 'previous', 'next'):
+            self._check_complex(np.complex64, kind)
+            self._check_complex(np.complex128, kind)
+
+    @pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+    def test_circular_refs(self):
+        # Test interp1d can be automatically garbage collected
+        x = np.linspace(0, 1)
+        y = np.linspace(0, 1)
+        # Confirm interp can be released from memory after use
+        with assert_deallocated(interp1d, x, y) as interp:
+            interp([0.1, 0.2])
+            del interp
+
+    def test_overflow_nearest(self):
+        # Test that the x range doesn't overflow when given integers as input
+        for kind in ('nearest', 'previous', 'next'):
+            x = np.array([0, 50, 127], dtype=np.int8)
+            ii = interp1d(x, x, kind=kind)
+            assert_array_almost_equal(ii(x), x)
+
+    def test_local_nans(self):
+        # check that for local interpolation kinds (slinear, zero) a single nan
+        # only affects its local neighborhood
+        x = np.arange(10).astype(float)
+        y = x.copy()
+        y[6] = np.nan
+        for kind in ('zero', 'slinear'):
+            ir = interp1d(x, y, kind=kind)
+            vals = ir([4.9, 7.0])
+            assert np.isfinite(vals).all()
+
+    def test_spline_nans(self):
+        # Backwards compat: a single nan makes the whole spline interpolation
+        # return nans in an array of the correct shape. And it doesn't raise,
+        # just quiet nans because of backcompat.
+        x = np.arange(8).astype(float)
+        y = x.copy()
+        yn = y.copy()
+        yn[3] = np.nan
+
+        for kind in ['quadratic', 'cubic']:
+            ir = interp1d(x, y, kind=kind)
+            irn = interp1d(x, yn, kind=kind)
+            for xnew in (6, [1, 6], [[1, 6], [3, 5]]):
+                xnew = np.asarray(xnew)
+                out, outn = ir(x), irn(x)
+                assert np.isnan(outn).all()
+                assert out.shape == outn.shape
+
+    def test_all_nans(self):
+        # regression test for gh-11637: interp1d core dumps with all-nan `x`
+        x = np.ones(10) * np.nan
+        y = np.arange(10)
+        with assert_raises(ValueError):
+            interp1d(x, y, kind='cubic')
+
+    def test_read_only(self):
+        x = np.arange(0, 10)
+        y = np.exp(-x / 3.0)
+        xnew = np.arange(0, 9, 0.1)
+        # Check both read-only and not read-only:
+        for xnew_writeable in (True, False):
+            xnew.flags.writeable = xnew_writeable
+            x.flags.writeable = False
+            for kind in ('linear', 'nearest', 'zero', 'slinear', 'quadratic',
+                         'cubic'):
+                f = interp1d(x, y, kind=kind)
+                vals = f(xnew)
+                assert np.isfinite(vals).all()
+
+    @pytest.mark.parametrize(
+        "kind", ("linear", "nearest", "nearest-up", "previous", "next")
+    )
+    def test_single_value(self, kind):
+        # https://github.com/scipy/scipy/issues/4043
+        f = interp1d([1.5], [6], kind=kind, bounds_error=False,
+                     fill_value=(2, 10))
+        xp_assert_equal(f([1, 1.5, 2]), np.asarray([2.0, 6, 10]))
+        # check still error if bounds_error=True
+        f = interp1d([1.5], [6], kind=kind, bounds_error=True)
+        with assert_raises(ValueError, match="x_new is above"):
+            f(2.0)
+
+
+class TestLagrange:
+
+    def test_lagrange(self):
+        p = poly1d([5,2,1,4,3])
+        xs = np.arange(len(p.coeffs))
+        ys = p(xs)
+        pl = lagrange(xs,ys)
+        assert_array_almost_equal(p.coeffs,pl.coeffs)
+
+
+class TestAkima1DInterpolator:
+    def test_eval(self):
+        x = np.arange(0., 11.)
+        y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+        ak = Akima1DInterpolator(x, y)
+        xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2,
+            8.6, 9.9, 10.])
+        yi = np.array([0., 1.375, 2., 1.5, 1.953125, 2.484375,
+            4.1363636363636366866103344, 5.9803623910336236590978842,
+            5.5067291516462386624652936, 5.2031367459745245795943447,
+            4.1796554159017080820603951, 3.4110386597938129327189927,
+            3.])
+        xp_assert_close(ak(xi), yi)
+
+    def test_eval_mod(self):
+        # Reference values generated with the following MATLAB code:
+        # format longG
+        # x = 0:10; y = [0. 2. 1. 3. 2. 6. 5.5 5.5 2.7 5.1 3.];
+        # xi = [0. 0.5 1. 1.5 2.5 3.5 4.5 5.1 6.5 7.2 8.6 9.9 10.];
+        # makima(x, y, xi)
+        x = np.arange(0., 11.)
+        y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+        ak = Akima1DInterpolator(x, y, method="makima")
+        xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2,
+                       8.6, 9.9, 10.])
+        yi = np.array([
+            0.0, 1.34471153846154, 2.0, 1.44375, 1.94375, 2.51939102564103,
+            4.10366931918656, 5.98501550899192, 5.51756330960439, 5.1757231914014,
+            4.12326636931311, 3.32931513157895, 3.0])
+        xp_assert_close(ak(xi), yi)
+
+    def test_eval_2d(self):
+        x = np.arange(0., 11.)
+        y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+        y = np.column_stack((y, 2. * y))
+        ak = Akima1DInterpolator(x, y)
+        xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2,
+                       8.6, 9.9, 10.])
+        yi = np.array([0., 1.375, 2., 1.5, 1.953125, 2.484375,
+                       4.1363636363636366866103344,
+                       5.9803623910336236590978842,
+                       5.5067291516462386624652936,
+                       5.2031367459745245795943447,
+                       4.1796554159017080820603951,
+                       3.4110386597938129327189927, 3.])
+        yi = np.column_stack((yi, 2. * yi))
+        xp_assert_close(ak(xi), yi)
+
+    def test_eval_3d(self):
+        x = np.arange(0., 11.)
+        y_ = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+        y = np.empty((11, 2, 2))
+        y[:, 0, 0] = y_
+        y[:, 1, 0] = 2. * y_
+        y[:, 0, 1] = 3. * y_
+        y[:, 1, 1] = 4. * y_
+        ak = Akima1DInterpolator(x, y)
+        xi = np.array([0., 0.5, 1., 1.5, 2.5, 3.5, 4.5, 5.1, 6.5, 7.2,
+                       8.6, 9.9, 10.])
+        yi = np.empty((13, 2, 2))
+        yi_ = np.array([0., 1.375, 2., 1.5, 1.953125, 2.484375,
+                        4.1363636363636366866103344,
+                        5.9803623910336236590978842,
+                        5.5067291516462386624652936,
+                        5.2031367459745245795943447,
+                        4.1796554159017080820603951,
+                        3.4110386597938129327189927, 3.])
+        yi[:, 0, 0] = yi_
+        yi[:, 1, 0] = 2. * yi_
+        yi[:, 0, 1] = 3. * yi_
+        yi[:, 1, 1] = 4. * yi_
+        xp_assert_close(ak(xi), yi)
+
+    def test_degenerate_case_multidimensional(self):
+        # This test is for issue #5683.
+        x = np.array([0, 1, 2])
+        y = np.vstack((x, x**2)).T
+        ak = Akima1DInterpolator(x, y)
+        x_eval = np.array([0.5, 1.5])
+        y_eval = ak(x_eval)
+        xp_assert_close(y_eval, np.vstack((x_eval, x_eval**2)).T)
+
+    def test_extend(self):
+        x = np.arange(0., 11.)
+        y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+        ak = Akima1DInterpolator(x, y)
+        match = "Extending a 1-D Akima interpolator is not yet implemented"
+        with pytest.raises(NotImplementedError, match=match):
+            ak.extend(None, None)
+
+    def test_mod_invalid_method(self):
+        x = np.arange(0., 11.)
+        y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+        match = "`method`=invalid is unsupported."
+        with pytest.raises(NotImplementedError, match=match):
+            Akima1DInterpolator(x, y, method="invalid")  # type: ignore
+
+    def test_extrapolate_attr(self):
+        #
+        x = np.linspace(-5, 5, 11)
+        y = x**2
+        x_ext = np.linspace(-10, 10, 17)
+        y_ext = x_ext**2
+        # Testing all extrapolate cases.
+        ak_true = Akima1DInterpolator(x, y, extrapolate=True)
+        ak_false = Akima1DInterpolator(x, y, extrapolate=False)
+        ak_none = Akima1DInterpolator(x, y, extrapolate=None)
+        # None should default to False; extrapolated points are NaN.
+        xp_assert_close(ak_false(x_ext), ak_none(x_ext), atol=1e-15)
+        xp_assert_equal(ak_false(x_ext)[0:4], np.full(4, np.nan))
+        xp_assert_equal(ak_false(x_ext)[-4:-1], np.full(3, np.nan))
+        # Extrapolation on call and attribute should be equal.
+        xp_assert_close(ak_false(x_ext, extrapolate=True), ak_true(x_ext), atol=1e-15)
+        # Testing extrapoation to actual function.
+        xp_assert_close(y_ext, ak_true(x_ext), atol=1e-15)
+
+
+@pytest.mark.parametrize("method", [Akima1DInterpolator, PchipInterpolator])
+def test_complex(method):
+    # Complex-valued data deprecated
+    x = np.arange(0., 11.)
+    y = np.array([0., 2., 1., 3., 2., 6., 5.5, 5.5, 2.7, 5.1, 3.])
+    y = y - 2j*y
+    msg = "real values"
+    with pytest.raises(ValueError, match=msg):
+        method(x, y)
+
+    def test_concurrency(self):
+        # Check that no segfaults appear with concurrent access to Akima1D
+        x = np.linspace(-5, 5, 11)
+        y = x**2
+        x_ext = np.linspace(-10, 10, 17)
+        ak = Akima1DInterpolator(x, y, extrapolate=True)
+
+        def worker_fn(_, ak, x_ext):
+            ak(x_ext)
+
+        _run_concurrent_barrier(10, worker_fn, ak, x_ext)
+
+
+class TestPPolyCommon:
+    # test basic functionality for PPoly and BPoly
+    def test_sort_check(self):
+        c = np.array([[1, 4], [2, 5], [3, 6]])
+        x = np.array([0, 1, 0.5])
+        assert_raises(ValueError, PPoly, c, x)
+        assert_raises(ValueError, BPoly, c, x)
+
+    def test_ctor_c(self):
+        # wrong shape: `c` must be at least 2D
+        with assert_raises(ValueError):
+            PPoly([1, 2], [0, 1])
+
+    def test_extend(self):
+        # Test adding new points to the piecewise polynomial
+        np.random.seed(1234)
+
+        order = 3
+        x = np.unique(np.r_[0, 10 * np.random.rand(30), 10])
+        c = 2*np.random.rand(order+1, len(x)-1, 2, 3) - 1
+
+        for cls in (PPoly, BPoly):
+            pp = cls(c[:,:9], x[:10])
+            pp.extend(c[:,9:], x[10:])
+
+            pp2 = cls(c[:, 10:], x[10:])
+            pp2.extend(c[:, :10], x[:10])
+
+            pp3 = cls(c, x)
+
+            xp_assert_equal(pp.c, pp3.c)
+            xp_assert_equal(pp.x, pp3.x)
+            xp_assert_equal(pp2.c, pp3.c)
+            xp_assert_equal(pp2.x, pp3.x)
+
+    def test_extend_diff_orders(self):
+        # Test extending polynomial with different order one
+        np.random.seed(1234)
+
+        x = np.linspace(0, 1, 6)
+        c = np.random.rand(2, 5)
+
+        x2 = np.linspace(1, 2, 6)
+        c2 = np.random.rand(4, 5)
+
+        for cls in (PPoly, BPoly):
+            pp1 = cls(c, x)
+            pp2 = cls(c2, x2)
+
+            pp_comb = cls(c, x)
+            pp_comb.extend(c2, x2[1:])
+
+            # NB. doesn't match to pp1 at the endpoint, because pp1 is not
+            #     continuous with pp2 as we took random coefs.
+            xi1 = np.linspace(0, 1, 300, endpoint=False)
+            xi2 = np.linspace(1, 2, 300)
+
+            xp_assert_close(pp1(xi1), pp_comb(xi1))
+            xp_assert_close(pp2(xi2), pp_comb(xi2))
+
+    def test_extend_descending(self):
+        np.random.seed(0)
+
+        order = 3
+        x = np.sort(np.random.uniform(0, 10, 20))
+        c = np.random.rand(order + 1, x.shape[0] - 1, 2, 3)
+
+        for cls in (PPoly, BPoly):
+            p = cls(c, x)
+
+            p1 = cls(c[:, :9], x[:10])
+            p1.extend(c[:, 9:], x[10:])
+
+            p2 = cls(c[:, 10:], x[10:])
+            p2.extend(c[:, :10], x[:10])
+
+            xp_assert_equal(p1.c, p.c)
+            xp_assert_equal(p1.x, p.x)
+            xp_assert_equal(p2.c, p.c)
+            xp_assert_equal(p2.x, p.x)
+
+    def test_shape(self):
+        np.random.seed(1234)
+        c = np.random.rand(8, 12, 5, 6, 7)
+        x = np.sort(np.random.rand(13))
+        xp = np.random.rand(3, 4)
+        for cls in (PPoly, BPoly):
+            p = cls(c, x)
+            assert p(xp).shape == (3, 4, 5, 6, 7)
+
+        # 'scalars'
+        for cls in (PPoly, BPoly):
+            p = cls(c[..., 0, 0, 0], x)
+
+            assert np.shape(p(0.5)) == ()
+            assert np.shape(p(np.array(0.5))) == ()
+
+            assert_raises(ValueError, p, np.array([[0.1, 0.2], [0.4]], dtype=object))
+
+    def test_concurrency(self):
+        # Check that no segfaults appear with concurrent access to BPoly, PPoly
+        c = np.random.rand(8, 12, 5, 6, 7)
+        x = np.sort(np.random.rand(13))
+        xp = np.random.rand(3, 4)
+
+        for cls in (PPoly, BPoly):
+            interp = cls(c, x)
+
+            def worker_fn(_, interp, xp):
+                interp(xp)
+
+            _run_concurrent_barrier(10, worker_fn, interp, xp)
+
+
+    def test_complex_coef(self):
+        np.random.seed(12345)
+        x = np.sort(np.random.random(13))
+        c = np.random.random((8, 12)) * (1. + 0.3j)
+        c_re, c_im = c.real, c.imag
+        xp = np.random.random(5)
+        for cls in (PPoly, BPoly):
+            p, p_re, p_im = cls(c, x), cls(c_re, x), cls(c_im, x)
+            for nu in [0, 1, 2]:
+                xp_assert_close(p(xp, nu).real, p_re(xp, nu))
+                xp_assert_close(p(xp, nu).imag, p_im(xp, nu))
+
+    def test_axis(self):
+        np.random.seed(12345)
+        c = np.random.rand(3, 4, 5, 6, 7, 8)
+        c_s = c.shape
+        xp = np.random.random((1, 2))
+        for axis in (0, 1, 2, 3):
+            m = c.shape[axis+1]
+            x = np.sort(np.random.rand(m+1))
+            for cls in (PPoly, BPoly):
+                p = cls(c, x, axis=axis)
+                assert p.c.shape == c_s[axis:axis+2] + c_s[:axis] + c_s[axis+2:]
+                res = p(xp)
+                targ_shape = c_s[:axis] + xp.shape + c_s[2+axis:]
+                assert res.shape == targ_shape
+
+                # deriv/antideriv does not drop the axis
+                for p1 in [cls(c, x, axis=axis).derivative(),
+                           cls(c, x, axis=axis).derivative(2),
+                           cls(c, x, axis=axis).antiderivative(),
+                           cls(c, x, axis=axis).antiderivative(2)]:
+                    assert p1.axis == p.axis
+
+        # c array needs two axes for the coefficients and intervals, so
+        # 0 <= axis < c.ndim-1; raise otherwise
+        for axis in (-1, 4, 5, 6):
+            for cls in (BPoly, PPoly):
+                assert_raises(ValueError, cls, **dict(c=c, x=x, axis=axis))
+
+
+class TestPolySubclassing:
+    class P(PPoly):
+        pass
+
+    class B(BPoly):
+        pass
+
+    def _make_polynomials(self):
+        np.random.seed(1234)
+        x = np.sort(np.random.random(3))
+        c = np.random.random((4, 2))
+        return self.P(c, x), self.B(c, x)
+
+    def test_derivative(self):
+        pp, bp = self._make_polynomials()
+        for p in (pp, bp):
+            pd = p.derivative()
+            assert p.__class__ == pd.__class__
+
+        ppa = pp.antiderivative()
+        assert pp.__class__ == ppa.__class__
+
+    def test_from_spline(self):
+        np.random.seed(1234)
+        x = np.sort(np.r_[0, np.random.rand(11), 1])
+        y = np.random.rand(len(x))
+
+        spl = splrep(x, y, s=0)
+        pp = self.P.from_spline(spl)
+        assert pp.__class__ == self.P
+
+    def test_conversions(self):
+        pp, bp = self._make_polynomials()
+
+        pp1 = self.P.from_bernstein_basis(bp)
+        assert pp1.__class__ == self.P
+
+        bp1 = self.B.from_power_basis(pp)
+        assert bp1.__class__ == self.B
+
+    def test_from_derivatives(self):
+        x = [0, 1, 2]
+        y = [[1], [2], [3]]
+        bp = self.B.from_derivatives(x, y)
+        assert bp.__class__ == self.B
+
+
+class TestPPoly:
+    def test_simple(self):
+        c = np.array([[1, 4], [2, 5], [3, 6]])
+        x = np.array([0, 0.5, 1])
+        p = PPoly(c, x)
+        xp_assert_close(p(0.3), np.asarray(1*0.3**2 + 2*0.3 + 3))
+        xp_assert_close(p(0.7), np.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6))
+
+    def test_periodic(self):
+        c = np.array([[1, 4], [2, 5], [3, 6]])
+        x = np.array([0, 0.5, 1])
+        p = PPoly(c, x, extrapolate='periodic')
+
+        xp_assert_close(p(1.3),
+                        np.asarray(1 * 0.3 ** 2 + 2 * 0.3 + 3))
+        xp_assert_close(p(-0.3),
+                        np.asarray(4 * (0.7 - 0.5) ** 2 + 5 * (0.7 - 0.5) + 6))
+
+        xp_assert_close(p(1.3, 1), np.asarray(2 * 0.3 + 2))
+        xp_assert_close(p(-0.3, 1), np.asarray(8 * (0.7 - 0.5) + 5))
+
+    def test_read_only(self):
+        c = np.array([[1, 4], [2, 5], [3, 6]])
+        x = np.array([0, 0.5, 1])
+        xnew = np.array([0, 0.1, 0.2])
+        PPoly(c, x, extrapolate='periodic')
+
+        for writeable in (True, False):
+            x.flags.writeable = writeable
+            c.flags.writeable = writeable
+            f = PPoly(c, x)
+            vals = f(xnew)
+            assert np.isfinite(vals).all()
+
+    def test_descending(self):
+        def binom_matrix(power):
+            n = np.arange(power + 1).reshape(-1, 1)
+            k = np.arange(power + 1)
+            B = binom(n, k)
+            return B[::-1, ::-1]
+
+        rng = np.random.RandomState(0)
+
+        power = 3
+        for m in [10, 20, 30]:
+            x = np.sort(rng.uniform(0, 10, m + 1))
+            ca = rng.uniform(-2, 2, size=(power + 1, m))
+
+            h = np.diff(x)
+            h_powers = h[None, :] ** np.arange(power + 1)[::-1, None]
+            B = binom_matrix(power)
+            cap = ca * h_powers
+            cdp = np.dot(B.T, cap)
+            cd = cdp / h_powers
+
+            pa = PPoly(ca, x, extrapolate=True)
+            pd = PPoly(cd[:, ::-1], x[::-1], extrapolate=True)
+
+            x_test = rng.uniform(-10, 20, 100)
+            xp_assert_close(pa(x_test), pd(x_test), rtol=1e-13)
+            xp_assert_close(pa(x_test, 1), pd(x_test, 1), rtol=1e-13)
+
+            pa_d = pa.derivative()
+            pd_d = pd.derivative()
+
+            xp_assert_close(pa_d(x_test), pd_d(x_test), rtol=1e-13)
+
+            # Antiderivatives won't be equal because fixing continuity is
+            # done in the reverse order, but surely the differences should be
+            # equal.
+            pa_i = pa.antiderivative()
+            pd_i = pd.antiderivative()
+            for a, b in rng.uniform(-10, 20, (5, 2)):
+                int_a = pa.integrate(a, b)
+                int_d = pd.integrate(a, b)
+                xp_assert_close(int_a, int_d, rtol=1e-13)
+                xp_assert_close(pa_i(b) - pa_i(a), pd_i(b) - pd_i(a),
+                                rtol=1e-13)
+
+            roots_d = pd.roots()
+            roots_a = pa.roots()
+            xp_assert_close(roots_a, np.sort(roots_d), rtol=1e-12)
+
+    def test_multi_shape(self):
+        c = np.random.rand(6, 2, 1, 2, 3)
+        x = np.array([0, 0.5, 1])
+        p = PPoly(c, x)
+        assert p.x.shape == x.shape
+        assert p.c.shape == c.shape
+        assert p(0.3).shape == c.shape[2:]
+
+        assert p(np.random.rand(5, 6)).shape == (5, 6) + c.shape[2:]
+
+        dp = p.derivative()
+        assert dp.c.shape == (5, 2, 1, 2, 3)
+        ip = p.antiderivative()
+        assert ip.c.shape == (7, 2, 1, 2, 3)
+
+    def test_construct_fast(self):
+        np.random.seed(1234)
+        c = np.array([[1, 4], [2, 5], [3, 6]], dtype=float)
+        x = np.array([0, 0.5, 1])
+        p = PPoly.construct_fast(c, x)
+        xp_assert_close(p(0.3), np.asarray(1*0.3**2 + 2*0.3 + 3))
+        xp_assert_close(p(0.7), np.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6))
+
+    def test_vs_alternative_implementations(self):
+        rng = np.random.RandomState(1234)
+        c = rng.rand(3, 12, 22)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+
+        p = PPoly(c, x)
+
+        xp = np.r_[0.3, 0.5, 0.33, 0.6]
+        expected = _ppoly_eval_1(c, x, xp)
+        xp_assert_close(p(xp), expected)
+
+        expected = _ppoly_eval_2(c[:,:,0], x, xp)
+        xp_assert_close(p(xp)[:, 0], expected)
+
+    def test_from_spline(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0)
+        pp = PPoly.from_spline(spl)
+
+        xi = np.linspace(0, 1, 200)
+        xp_assert_close(pp(xi), splev(xi, spl))
+
+        # make sure .from_spline accepts BSpline objects
+        b = BSpline(*spl)
+        ppp = PPoly.from_spline(b)
+        xp_assert_close(ppp(xi), b(xi))
+
+        # BSpline's extrapolate attribute propagates unless overridden
+        t, c, k = spl
+        for extrap in (None, True, False):
+            b = BSpline(t, c, k, extrapolate=extrap)
+            p = PPoly.from_spline(b)
+            assert p.extrapolate == b.extrapolate
+
+    def test_derivative_simple(self):
+        np.random.seed(1234)
+        c = np.array([[4, 3, 2, 1]]).T
+        dc = np.array([[3*4, 2*3, 2]]).T
+        ddc = np.array([[2*3*4, 1*2*3]]).T
+        x = np.array([0, 1])
+
+        pp = PPoly(c, x)
+        dpp = PPoly(dc, x)
+        ddpp = PPoly(ddc, x)
+
+        xp_assert_close(pp.derivative().c, dpp.c)
+        xp_assert_close(pp.derivative(2).c, ddpp.c)
+
+    def test_derivative_eval(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0)
+        pp = PPoly.from_spline(spl)
+
+        xi = np.linspace(0, 1, 200)
+        for dx in range(0, 3):
+            xp_assert_close(pp(xi, dx), splev(xi, spl, dx))
+
+    def test_derivative(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0, k=5)
+        pp = PPoly.from_spline(spl)
+
+        xi = np.linspace(0, 1, 200)
+        for dx in range(0, 10):
+            xp_assert_close(pp(xi, dx), pp.derivative(dx)(xi),
+                            err_msg="dx=%d" % (dx,))
+
+    def test_antiderivative_of_constant(self):
+        # https://github.com/scipy/scipy/issues/4216
+        p = PPoly([[1.]], [0, 1])
+        xp_assert_equal(p.antiderivative().c, PPoly([[1], [0]], [0, 1]).c)
+        xp_assert_equal(p.antiderivative().x, PPoly([[1], [0]], [0, 1]).x)
+
+    def test_antiderivative_regression_4355(self):
+        # https://github.com/scipy/scipy/issues/4355
+        p = PPoly([[1., 0.5]], [0, 1, 2])
+        q = p.antiderivative()
+        xp_assert_equal(q.c, [[1, 0.5], [0, 1]])
+        xp_assert_equal(q.x, [0.0, 1, 2])
+        xp_assert_close(p.integrate(0, 2), np.asarray(1.5))
+        xp_assert_close(np.asarray(q(2) - q(0)),
+                        np.asarray(1.5))
+
+    def test_antiderivative_simple(self):
+        np.random.seed(1234)
+        # [ p1(x) = 3*x**2 + 2*x + 1,
+        #   p2(x) = 1.6875]
+        c = np.array([[3, 2, 1], [0, 0, 1.6875]]).T
+        # [ pp1(x) = x**3 + x**2 + x,
+        #   pp2(x) = 1.6875*(x - 0.25) + pp1(0.25)]
+        ic = np.array([[1, 1, 1, 0], [0, 0, 1.6875, 0.328125]]).T
+        # [ ppp1(x) = (1/4)*x**4 + (1/3)*x**3 + (1/2)*x**2,
+        #   ppp2(x) = (1.6875/2)*(x - 0.25)**2 + pp1(0.25)*x + ppp1(0.25)]
+        iic = np.array([[1/4, 1/3, 1/2, 0, 0],
+                        [0, 0, 1.6875/2, 0.328125, 0.037434895833333336]]).T
+        x = np.array([0, 0.25, 1])
+
+        pp = PPoly(c, x)
+        ipp = pp.antiderivative()
+        iipp = pp.antiderivative(2)
+        iipp2 = ipp.antiderivative()
+
+        xp_assert_close(ipp.x, x)
+        xp_assert_close(ipp.c.T, ic.T)
+        xp_assert_close(iipp.c.T, iic.T)
+        xp_assert_close(iipp2.c.T, iic.T)
+
+    def test_antiderivative_vs_derivative(self):
+        rng = np.random.RandomState(1234)
+        x = np.linspace(0, 1, 30)**2
+        y = rng.rand(len(x))
+        spl = splrep(x, y, s=0, k=5)
+        pp = PPoly.from_spline(spl)
+
+        for dx in range(0, 10):
+            ipp = pp.antiderivative(dx)
+
+            # check that derivative is inverse op
+            pp2 = ipp.derivative(dx)
+            xp_assert_close(pp.c, pp2.c)
+
+            # check continuity
+            for k in range(dx):
+                pp2 = ipp.derivative(k)
+
+                r = 1e-13
+                endpoint = r*pp2.x[:-1] + (1 - r)*pp2.x[1:]
+
+                xp_assert_close(pp2(pp2.x[1:]), pp2(endpoint),
+                                rtol=1e-7, err_msg="dx=%d k=%d" % (dx, k))
+
+    def test_antiderivative_vs_spline(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0, k=5)
+        pp = PPoly.from_spline(spl)
+
+        for dx in range(0, 10):
+            pp2 = pp.antiderivative(dx)
+            spl2 = splantider(spl, dx)
+
+            xi = np.linspace(0, 1, 200)
+            xp_assert_close(pp2(xi), splev(xi, spl2),
+                            rtol=1e-7)
+
+    def test_antiderivative_continuity(self):
+        c = np.array([[2, 1, 2, 2], [2, 1, 3, 3]]).T
+        x = np.array([0, 0.5, 1])
+
+        p = PPoly(c, x)
+        ip = p.antiderivative()
+
+        # check continuity
+        xp_assert_close(ip(0.5 - 1e-9), ip(0.5 + 1e-9), rtol=1e-8)
+
+        # check that only lowest order coefficients were changed
+        p2 = ip.derivative()
+        xp_assert_close(p2.c, p.c)
+
+    def test_integrate(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(np.r_[0, rng.rand(11), 1])
+        y = rng.rand(len(x))
+
+        spl = splrep(x, y, s=0, k=5)
+        pp = PPoly.from_spline(spl)
+
+        a, b = 0.3, 0.9
+        ig = pp.integrate(a, b)
+
+        ipp = pp.antiderivative()
+        xp_assert_close(ig, ipp(b) - ipp(a), check_0d=False)
+        xp_assert_close(ig, splint(a, b, spl), check_0d=False)
+
+        a, b = -0.3, 0.9
+        ig = pp.integrate(a, b, extrapolate=True)
+        xp_assert_close(ig, ipp(b) - ipp(a), check_0d=False)
+
+        assert np.isnan(pp.integrate(a, b, extrapolate=False)).all()
+
+    def test_integrate_readonly(self):
+        x = np.array([1, 2, 4])
+        c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]])
+
+        for writeable in (True, False):
+            x.flags.writeable = writeable
+
+            P = PPoly(c, x)
+            vals = P.integrate(1, 4)
+
+            assert np.isfinite(vals).all()
+
+    def test_integrate_periodic(self):
+        x = np.array([1, 2, 4])
+        c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]])
+
+        P = PPoly(c, x, extrapolate='periodic')
+        I = P.antiderivative()
+
+        period_int = np.asarray(I(4) - I(1))
+
+        xp_assert_close(P.integrate(1, 4), period_int)
+        xp_assert_close(P.integrate(-10, -7), period_int)
+        xp_assert_close(P.integrate(-10, -4), np.asarray(2 * period_int))
+
+        xp_assert_close(P.integrate(1.5, 2.5),
+                        np.asarray(I(2.5) - I(1.5)))
+        xp_assert_close(P.integrate(3.5, 5),
+                        np.asarray(I(2) - I(1) + I(4) - I(3.5)))
+        xp_assert_close(P.integrate(3.5 + 12, 5 + 12),
+                        np.asarray(I(2) - I(1) + I(4) - I(3.5)))
+        xp_assert_close(P.integrate(3.5, 5 + 12),
+                        np.asarray(I(2) - I(1) + I(4) - I(3.5) + 4 * period_int))
+        xp_assert_close(P.integrate(0, -1),
+                        np.asarray(I(2) - I(3)))
+        xp_assert_close(P.integrate(-9, -10),
+                        np.asarray(I(2) - I(3)))
+        xp_assert_close(P.integrate(0, -10),
+                        np.asarray(I(2) - I(3) - 3 * period_int))
+
+    def test_roots(self):
+        x = np.linspace(0, 1, 31)**2
+        y = np.sin(30*x)
+
+        spl = splrep(x, y, s=0, k=3)
+        pp = PPoly.from_spline(spl)
+
+        r = pp.roots()
+        r = r[(r >= 0 - 1e-15) & (r <= 1 + 1e-15)]
+        xp_assert_close(r, sproot(spl), atol=1e-15)
+
+    def test_roots_idzero(self):
+        # Roots for piecewise polynomials with identically zero
+        # sections.
+        c = np.array([[-1, 0.25], [0, 0], [-1, 0.25]]).T
+        x = np.array([0, 0.4, 0.6, 1.0])
+
+        pp = PPoly(c, x)
+        xp_assert_equal(pp.roots(),
+                        [0.25, 0.4, np.nan, 0.6 + 0.25])
+
+        # ditto for p.solve(const) with sections identically equal const
+        const = 2.
+        c1 = c.copy()
+        c1[1, :] += const
+        pp1 = PPoly(c1, x)
+
+        xp_assert_equal(pp1.solve(const),
+                        [0.25, 0.4, np.nan, 0.6 + 0.25])
+
+    def test_roots_all_zero(self):
+        # test the code path for the polynomial being identically zero everywhere
+        c = [[0], [0]]
+        x = [0, 1]
+        p = PPoly(c, x)
+        xp_assert_equal(p.roots(), [0, np.nan])
+        xp_assert_equal(p.solve(0), [0, np.nan])
+        xp_assert_equal(p.solve(1), [])
+
+        c = [[0, 0], [0, 0]]
+        x = [0, 1, 2]
+        p = PPoly(c, x)
+        xp_assert_equal(p.roots(), [0, np.nan, 1, np.nan])
+        xp_assert_equal(p.solve(0), [0, np.nan, 1, np.nan])
+        xp_assert_equal(p.solve(1), [])
+
+    def test_roots_repeated(self):
+        # Check roots repeated in multiple sections are reported only
+        # once.
+
+        # [(x + 1)**2 - 1, -x**2] ; x == 0 is a repeated root
+        c = np.array([[1, 0, -1], [-1, 0, 0]]).T
+        x = np.array([-1, 0, 1])
+
+        pp = PPoly(c, x)
+        xp_assert_equal(pp.roots(), np.asarray([-2.0, 0.0]))
+        xp_assert_equal(pp.roots(extrapolate=False), np.asarray([0.0]))
+
+    def test_roots_discont(self):
+        # Check that a discontinuity across zero is reported as root
+        c = np.array([[1], [-1]]).T
+        x = np.array([0, 0.5, 1])
+        pp = PPoly(c, x)
+        xp_assert_equal(pp.roots(), np.asarray([0.5]))
+        xp_assert_equal(pp.roots(discontinuity=False), np.asarray([]))
+
+        # ditto for a discontinuity across y:
+        xp_assert_equal(pp.solve(0.5), np.asarray([0.5]))
+        xp_assert_equal(pp.solve(0.5, discontinuity=False), np.asarray([]))
+
+        xp_assert_equal(pp.solve(1.5), np.asarray([]))
+        xp_assert_equal(pp.solve(1.5, discontinuity=False), np.asarray([]))
+
+    def test_roots_random(self):
+        # Check high-order polynomials with random coefficients
+        rng = np.random.RandomState(1234)
+
+        num = 0
+
+        for extrapolate in (True, False):
+            for order in range(0, 20):
+                x = np.unique(np.r_[0, 10 * rng.rand(30), 10])
+                c = 2*rng.rand(order+1, len(x)-1, 2, 3) - 1
+
+                pp = PPoly(c, x)
+                for y in [0, rng.random()]:
+                    r = pp.solve(y, discontinuity=False, extrapolate=extrapolate)
+
+                    for i in range(2):
+                        for j in range(3):
+                            rr = r[i,j]
+                            if rr.size > 0:
+                                # Check that the reported roots indeed are roots
+                                num += rr.size
+                                val = pp(rr, extrapolate=extrapolate)[:,i,j]
+                                cmpval = pp(rr, nu=1,
+                                            extrapolate=extrapolate)[:,i,j]
+                                msg = f"({extrapolate!r}) r = {repr(rr)}"
+                                xp_assert_close((val-y) / cmpval, np.asarray(0.0),
+                                                atol=1e-7,
+                                                err_msg=msg, check_shape=False)
+
+        # Check that we checked a number of roots
+        assert num > 100, repr(num)
+
+    def test_roots_croots(self):
+        # Test the complex root finding algorithm
+        rng = np.random.RandomState(1234)
+
+        for k in range(1, 15):
+            c = rng.rand(k, 1, 130)
+
+            if k == 3:
+                # add a case with zero discriminant
+                c[:,0,0] = 1, 2, 1
+
+            for y in [0, rng.random()]:
+                w = np.empty(c.shape, dtype=complex)
+                _ppoly._croots_poly1(c, w, y)
+
+                if k == 1:
+                    assert np.isnan(w).all()
+                    continue
+
+                res = -y
+                cres = 0
+                for i in range(k):
+                    res += c[i,None] * w**(k-1-i)
+                    cres += abs(c[i,None] * w**(k-1-i))
+                with np.errstate(invalid='ignore'):
+                    res /= cres
+                res = res.ravel()
+                res = res[~np.isnan(res)]
+                xp_assert_close(res, np.zeros_like(res), atol=1e-10)
+
+    def test_extrapolate_attr(self):
+        # [ 1 - x**2 ]
+        c = np.array([[-1, 0, 1]]).T
+        x = np.array([0, 1])
+
+        for extrapolate in [True, False, None]:
+            pp = PPoly(c, x, extrapolate=extrapolate)
+            pp_d = pp.derivative()
+            pp_i = pp.antiderivative()
+
+            if extrapolate is False:
+                assert np.isnan(pp([-0.1, 1.1])).all()
+                assert np.isnan(pp_i([-0.1, 1.1])).all()
+                assert np.isnan(pp_d([-0.1, 1.1])).all()
+                assert pp.roots() == [1]
+            else:
+                xp_assert_close(pp([-0.1, 1.1]), [1-0.1**2, 1-1.1**2])
+                assert not np.isnan(pp_i([-0.1, 1.1])).any()
+                assert not np.isnan(pp_d([-0.1, 1.1])).any()
+                xp_assert_close(pp.roots(), np.asarray([1.0, -1.0]))
+
+
+class TestBPoly:
+    def test_simple(self):
+        x = [0, 1]
+        c = [[3]]
+        bp = BPoly(c, x)
+        xp_assert_close(bp(0.1), np.asarray(3.))
+
+    def test_simple2(self):
+        x = [0, 1]
+        c = [[3], [1]]
+        bp = BPoly(c, x)   # 3*(1-x) + 1*x
+        xp_assert_close(bp(0.1), np.asarray(3*0.9 + 1.*0.1))
+
+    def test_simple3(self):
+        x = [0, 1]
+        c = [[3], [1], [4]]
+        bp = BPoly(c, x)   # 3 * (1-x)**2 + 2 * x (1-x) + 4 * x**2
+        xp_assert_close(bp(0.2),
+                np.asarray(3 * 0.8*0.8 + 1 * 2*0.2*0.8 + 4 * 0.2*0.2))
+
+    def test_simple4(self):
+        x = [0, 1]
+        c = [[1], [1], [1], [2]]
+        bp = BPoly(c, x)
+        xp_assert_close(bp(0.3),
+                        np.asarray(    0.7**3 +
+                                   3 * 0.7**2 * 0.3 +
+                                   3 * 0.7 * 0.3**2 +
+                                   2 * 0.3**3)
+        )
+
+    def test_simple5(self):
+        x = [0, 1]
+        c = [[1], [1], [8], [2], [1]]
+        bp = BPoly(c, x)
+        xp_assert_close(bp(0.3),
+                        np.asarray(  0.7**4 +
+                                 4 * 0.7**3 * 0.3 +
+                             8 * 6 * 0.7**2 * 0.3**2 +
+                             2 * 4 * 0.7 * 0.3**3 +
+                                 0.3**4)
+        )
+
+    def test_periodic(self):
+        x = [0, 1, 3]
+        c = [[3, 0], [0, 0], [0, 2]]
+        # [3*(1-x)**2, 2*((x-1)/2)**2]
+        bp = BPoly(c, x, extrapolate='periodic')
+
+        xp_assert_close(bp(3.4), np.asarray(3 * 0.6**2))
+        xp_assert_close(bp(-1.3), np.asarray(2 * (0.7/2)**2))
+
+        xp_assert_close(bp(3.4, 1), np.asarray(-6 * 0.6))
+        xp_assert_close(bp(-1.3, 1), np.asarray(2 * (0.7/2)))
+
+    def test_descending(self):
+        rng = np.random.RandomState(0)
+
+        power = 3
+        for m in [10, 20, 30]:
+            x = np.sort(rng.uniform(0, 10, m + 1))
+            ca = rng.uniform(-0.1, 0.1, size=(power + 1, m))
+            # We need only to flip coefficients to get it right!
+            cd = ca[::-1].copy()
+
+            pa = BPoly(ca, x, extrapolate=True)
+            pd = BPoly(cd[:, ::-1], x[::-1], extrapolate=True)
+
+            x_test = rng.uniform(-10, 20, 100)
+            xp_assert_close(pa(x_test), pd(x_test), rtol=1e-13)
+            xp_assert_close(pa(x_test, 1), pd(x_test, 1), rtol=1e-13)
+
+            pa_d = pa.derivative()
+            pd_d = pd.derivative()
+
+            xp_assert_close(pa_d(x_test), pd_d(x_test), rtol=1e-13)
+
+            # Antiderivatives won't be equal because fixing continuity is
+            # done in the reverse order, but surely the differences should be
+            # equal.
+            pa_i = pa.antiderivative()
+            pd_i = pd.antiderivative()
+            for a, b in rng.uniform(-10, 20, (5, 2)):
+                int_a = pa.integrate(a, b)
+                int_d = pd.integrate(a, b)
+                xp_assert_close(int_a, int_d, rtol=1e-12)
+                xp_assert_close(pa_i(b) - pa_i(a), pd_i(b) - pd_i(a),
+                                rtol=1e-12)
+
+    def test_multi_shape(self):
+        rng = np.random.RandomState(1234)
+        c = rng.rand(6, 2, 1, 2, 3)
+        x = np.array([0, 0.5, 1])
+        p = BPoly(c, x)
+        assert p.x.shape == x.shape
+        assert p.c.shape == c.shape
+        assert p(0.3).shape == c.shape[2:]
+        assert p(rng.rand(5, 6)).shape == (5, 6) + c.shape[2:]
+
+        dp = p.derivative()
+        assert dp.c.shape == (5, 2, 1, 2, 3)
+
+    def test_interval_length(self):
+        x = [0, 2]
+        c = [[3], [1], [4]]
+        bp = BPoly(c, x)
+        xval = 0.1
+        s = xval / 2  # s = (x - xa) / (xb - xa)
+        xp_assert_close(bp(xval),
+                        np.asarray(3 * (1-s)*(1-s) + 1 * 2*s*(1-s) + 4 * s*s)
+        )
+
+    def test_two_intervals(self):
+        x = [0, 1, 3]
+        c = [[3, 0], [0, 0], [0, 2]]
+        bp = BPoly(c, x)  # [3*(1-x)**2, 2*((x-1)/2)**2]
+
+        xp_assert_close(bp(0.4), np.asarray(3 * 0.6*0.6))
+        xp_assert_close(bp(1.7), np.asarray(2 * (0.7/2)**2))
+
+    def test_extrapolate_attr(self):
+        x = [0, 2]
+        c = [[3], [1], [4]]
+        bp = BPoly(c, x)
+
+        for extrapolate in (True, False, None):
+            bp = BPoly(c, x, extrapolate=extrapolate)
+            bp_d = bp.derivative()
+            if extrapolate is False:
+                assert np.isnan(bp([-0.1, 2.1])).all()
+                assert np.isnan(bp_d([-0.1, 2.1])).all()
+            else:
+                assert not np.isnan(bp([-0.1, 2.1])).any()
+                assert not np.isnan(bp_d([-0.1, 2.1])).any()
+
+
+class TestBPolyCalculus:
+    def test_derivative(self):
+        x = [0, 1, 3]
+        c = [[3, 0], [0, 0], [0, 2]]
+        bp = BPoly(c, x)  # [3*(1-x)**2, 2*((x-1)/2)**2]
+        bp_der = bp.derivative()
+        xp_assert_close(bp_der(0.4), np.asarray(-6*(0.6)))
+        xp_assert_close(bp_der(1.7), np.asarray(0.7))
+
+        # derivatives in-place
+        xp_assert_close(np.asarray([bp(0.4, nu) for nu in [1, 2, 3]]),
+                        np.asarray([-6*(1-0.4), 6., 0.])
+        )
+        xp_assert_close(np.asarray([bp(1.7, nu) for nu in [1, 2, 3]]),
+                        np.asarray([0.7, 1., 0])
+        )
+
+    def test_derivative_ppoly(self):
+        # make sure it's consistent w/ power basis
+        rng = np.random.RandomState(1234)
+        m, k = 5, 8   # number of intervals, order
+        x = np.sort(rng.random(m))
+        c = rng.random((k, m-1))
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+
+        for d in range(k):
+            bp = bp.derivative()
+            pp = pp.derivative()
+            xp = np.linspace(x[0], x[-1], 21)
+            xp_assert_close(bp(xp), pp(xp))
+
+    def test_deriv_inplace(self):
+        rng = np.random.RandomState(1234)
+        m, k = 5, 8   # number of intervals, order
+        x = np.sort(rng.random(m))
+        c = rng.random((k, m-1))
+
+        # test both real and complex coefficients
+        for cc in [c.copy(), c*(1. + 2.j)]:
+            bp = BPoly(cc, x)
+            xp = np.linspace(x[0], x[-1], 21)
+            for i in range(k):
+                xp_assert_close(bp(xp, i), bp.derivative(i)(xp))
+
+    def test_antiderivative_simple(self):
+        # f(x) = x        for x \in [0, 1),
+        #        (x-1)/2  for x \in [1, 3]
+        #
+        # antiderivative is then
+        # F(x) = x**2 / 2            for x \in [0, 1),
+        #        0.5*x*(x/2 - 1) + A  for x \in [1, 3]
+        # where A = 3/4 for continuity at x = 1.
+        x = [0, 1, 3]
+        c = [[0, 0], [1, 1]]
+
+        bp = BPoly(c, x)
+        bi = bp.antiderivative()
+
+        xx = np.linspace(0, 3, 11)
+        xp_assert_close(bi(xx),
+                        np.where(xx < 1, xx**2 / 2.,
+                                         0.5 * xx * (xx/2. - 1) + 3./4),
+                        atol=1e-12, rtol=1e-12)
+
+    def test_der_antider(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(11))
+        c = rng.random((4, 10, 2, 3))
+        bp = BPoly(c, x)
+
+        xx = np.linspace(x[0], x[-1], 100)
+        xp_assert_close(bp.antiderivative().derivative()(xx),
+                        bp(xx), atol=1e-12, rtol=1e-12)
+
+    def test_antider_ppoly(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(11))
+        c = rng.random((4, 10, 2, 3))
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+
+        xx = np.linspace(x[0], x[-1], 10)
+
+        xp_assert_close(bp.antiderivative(2)(xx),
+                        pp.antiderivative(2)(xx), atol=1e-12, rtol=1e-12)
+
+    def test_antider_continuous(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(11))
+        c = rng.random((4, 10))
+        bp = BPoly(c, x).antiderivative()
+
+        xx = bp.x[1:-1]
+        xp_assert_close(bp(xx - 1e-14),
+                        bp(xx + 1e-14), atol=1e-12, rtol=1e-12)
+
+    def test_integrate(self):
+        rng = np.random.RandomState(1234)
+        x = np.sort(rng.random(11))
+        c = rng.random((4, 10))
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+        xp_assert_close(bp.integrate(0, 1),
+                        pp.integrate(0, 1), atol=1e-12, rtol=1e-12, check_0d=False)
+
+    def test_integrate_extrap(self):
+        c = [[1]]
+        x = [0, 1]
+        b = BPoly(c, x)
+
+        # default is extrapolate=True
+        xp_assert_close(b.integrate(0, 2), np.asarray(2.),
+                        atol=1e-14, check_0d=False)
+
+        # .integrate argument overrides self.extrapolate
+        b1 = BPoly(c, x, extrapolate=False)
+        assert np.isnan(b1.integrate(0, 2))
+        xp_assert_close(b1.integrate(0, 2, extrapolate=True),
+                        np.asarray(2.), atol=1e-14, check_0d=False)
+
+    def test_integrate_periodic(self):
+        x = np.array([1, 2, 4])
+        c = np.array([[0., 0.], [-1., -1.], [2., -0.], [1., 2.]])
+
+        P = BPoly.from_power_basis(PPoly(c, x), extrapolate='periodic')
+        I = P.antiderivative()
+
+        period_int = I(4) - I(1)
+
+        xp_assert_close(P.integrate(1, 4), period_int) #, check_0d=False)
+        xp_assert_close(P.integrate(-10, -7), period_int)
+        xp_assert_close(P.integrate(-10, -4), 2 * period_int)
+
+        xp_assert_close(P.integrate(1.5, 2.5), I(2.5) - I(1.5))
+        xp_assert_close(P.integrate(3.5, 5), I(2) - I(1) + I(4) - I(3.5))
+        xp_assert_close(P.integrate(3.5 + 12, 5 + 12),
+                        I(2) - I(1) + I(4) - I(3.5))
+        xp_assert_close(P.integrate(3.5, 5 + 12),
+                        I(2) - I(1) + I(4) - I(3.5) + 4 * period_int)
+
+        xp_assert_close(P.integrate(0, -1), I(2) - I(3))
+        xp_assert_close(P.integrate(-9, -10), I(2) - I(3))
+        xp_assert_close(P.integrate(0, -10), I(2) - I(3) - 3 * period_int)
+
+    def test_antider_neg(self):
+        # .derivative(-nu) ==> .andiderivative(nu) and vice versa
+        c = [[1]]
+        x = [0, 1]
+        b = BPoly(c, x)
+
+        xx = np.linspace(0, 1, 21)
+
+        xp_assert_close(b.derivative(-1)(xx), b.antiderivative()(xx),
+                        atol=1e-12, rtol=1e-12)
+        xp_assert_close(b.derivative(1)(xx), b.antiderivative(-1)(xx),
+                        atol=1e-12, rtol=1e-12)
+
+
+class TestPolyConversions:
+    def test_bp_from_pp(self):
+        x = [0, 1, 3]
+        c = [[3, 2], [1, 8], [4, 3]]
+        pp = PPoly(c, x)
+        bp = BPoly.from_power_basis(pp)
+        pp1 = PPoly.from_bernstein_basis(bp)
+
+        xp = [0.1, 1.4]
+        xp_assert_close(pp(xp), bp(xp))
+        xp_assert_close(pp(xp), pp1(xp))
+
+    def test_bp_from_pp_random(self):
+        rng = np.random.RandomState(1234)
+        m, k = 5, 8   # number of intervals, order
+        x = np.sort(rng.random(m))
+        c = rng.random((k, m-1))
+        pp = PPoly(c, x)
+        bp = BPoly.from_power_basis(pp)
+        pp1 = PPoly.from_bernstein_basis(bp)
+
+        xp = np.linspace(x[0], x[-1], 21)
+        xp_assert_close(pp(xp), bp(xp))
+        xp_assert_close(pp(xp), pp1(xp))
+
+    def test_pp_from_bp(self):
+        x = [0, 1, 3]
+        c = [[3, 3], [1, 1], [4, 2]]
+        bp = BPoly(c, x)
+        pp = PPoly.from_bernstein_basis(bp)
+        bp1 = BPoly.from_power_basis(pp)
+
+        xp = [0.1, 1.4]
+        xp_assert_close(bp(xp), pp(xp))
+        xp_assert_close(bp(xp), bp1(xp))
+
+    def test_broken_conversions(self):
+        # regression test for gh-10597: from_power_basis only accepts PPoly etc.
+        x = [0, 1, 3]
+        c = [[3, 3], [1, 1], [4, 2]]
+        pp = PPoly(c, x)
+        with assert_raises(TypeError):
+            PPoly.from_bernstein_basis(pp)
+
+        bp = BPoly(c, x)
+        with assert_raises(TypeError):
+            BPoly.from_power_basis(bp)
+
+
+class TestBPolyFromDerivatives:
+    def test_make_poly_1(self):
+        c1 = BPoly._construct_from_derivatives(0, 1, [2], [3])
+        xp_assert_close(c1, [2., 3.])
+
+    def test_make_poly_2(self):
+        c1 = BPoly._construct_from_derivatives(0, 1, [1, 0], [1])
+        xp_assert_close(c1, [1., 1., 1.])
+
+        # f'(0) = 3
+        c2 = BPoly._construct_from_derivatives(0, 1, [2, 3], [1])
+        xp_assert_close(c2, [2., 7./2, 1.])
+
+        # f'(1) = 3
+        c3 = BPoly._construct_from_derivatives(0, 1, [2], [1, 3])
+        xp_assert_close(c3, [2., -0.5, 1.])
+
+    def test_make_poly_3(self):
+        # f'(0)=2, f''(0)=3
+        c1 = BPoly._construct_from_derivatives(0, 1, [1, 2, 3], [4])
+        xp_assert_close(c1, [1., 5./3, 17./6, 4.])
+
+        # f'(1)=2, f''(1)=3
+        c2 = BPoly._construct_from_derivatives(0, 1, [1], [4, 2, 3])
+        xp_assert_close(c2, [1., 19./6, 10./3, 4.])
+
+        # f'(0)=2, f'(1)=3
+        c3 = BPoly._construct_from_derivatives(0, 1, [1, 2], [4, 3])
+        xp_assert_close(c3, [1., 5./3, 3., 4.])
+
+    def test_make_poly_12(self):
+        rng = np.random.RandomState(12345)
+        ya = np.r_[0, rng.random(5)]
+        yb = np.r_[0, rng.random(5)]
+
+        c = BPoly._construct_from_derivatives(0, 1, ya, yb)
+        pp = BPoly(c[:, None], [0, 1])
+        for j in range(6):
+            xp_assert_close(pp(0.), ya[j], check_0d=False)
+            xp_assert_close(pp(1.), yb[j], check_0d=False)
+            pp = pp.derivative()
+
+    def test_raise_degree(self):
+        rng = np.random.RandomState(12345)
+        x = [0, 1]
+        k, d = 8, 5
+        c = rng.random((k, 1, 2, 3, 4))
+        bp = BPoly(c, x)
+
+        c1 = BPoly._raise_degree(c, d)
+        bp1 = BPoly(c1, x)
+
+        xp = np.linspace(0, 1, 11)
+        xp_assert_close(bp(xp), bp1(xp))
+
+    def test_xi_yi(self):
+        assert_raises(ValueError, BPoly.from_derivatives, [0, 1], [0])
+
+    def test_coords_order(self):
+        xi = [0, 0, 1]
+        yi = [[0], [0], [0]]
+        assert_raises(ValueError, BPoly.from_derivatives, xi, yi)
+
+    def test_zeros(self):
+        xi = [0, 1, 2, 3]
+        yi = [[0, 0], [0], [0, 0], [0, 0]]  # NB: will have to raise the degree
+        pp = BPoly.from_derivatives(xi, yi)
+        assert pp.c.shape == (4, 3)
+
+        ppd = pp.derivative()
+        for xp in [0., 0.1, 1., 1.1, 1.9, 2., 2.5]:
+            xp_assert_close(pp(xp), np.asarray(0.0))
+            xp_assert_close(ppd(xp), np.asarray(0.0))
+
+
+    def _make_random_mk(self, m, k):
+        # k derivatives at each breakpoint
+        rng = np.random.RandomState(1234)
+        xi = np.asarray([1. * j**2 for j in range(m+1)])
+        yi = [rng.random(k) for j in range(m+1)]
+        return xi, yi
+
+    def test_random_12(self):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k)
+        pp = BPoly.from_derivatives(xi, yi)
+
+        for order in range(k//2):
+            xp_assert_close(pp(xi), [yy[order] for yy in yi])
+            pp = pp.derivative()
+
+    def test_order_zero(self):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k)
+        assert_raises(ValueError, BPoly.from_derivatives,
+                **dict(xi=xi, yi=yi, orders=0))
+
+    def test_orders_too_high(self):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k)
+
+        BPoly.from_derivatives(xi, yi, orders=2*k-1)   # this is still ok
+        assert_raises(ValueError, BPoly.from_derivatives,   # but this is not
+                **dict(xi=xi, yi=yi, orders=2*k))
+
+    def test_orders_global(self):
+        m, k = 5, 12
+        xi, yi = self._make_random_mk(m, k)
+
+        # ok, this is confusing. Local polynomials will be of the order 5
+        # which means that up to the 2nd derivatives will be used at each point
+        order = 5
+        pp = BPoly.from_derivatives(xi, yi, orders=order)
+
+        for j in range(order//2+1):
+            xp_assert_close(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12))
+            pp = pp.derivative()
+        assert not np.allclose(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12))
+
+        # now repeat with `order` being even: on each interval, it uses
+        # order//2 'derivatives' @ the right-hand endpoint and
+        # order//2+1 @ 'derivatives' the left-hand endpoint
+        order = 6
+        pp = BPoly.from_derivatives(xi, yi, orders=order)
+        for j in range(order//2):
+            xp_assert_close(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12))
+            pp = pp.derivative()
+        assert not np.allclose(pp(xi[1:-1] - 1e-12), pp(xi[1:-1] + 1e-12))
+
+    def test_orders_local(self):
+        m, k = 7, 12
+        xi, yi = self._make_random_mk(m, k)
+
+        orders = [o + 1 for o in range(m)]
+        for i, x in enumerate(xi[1:-1]):
+            pp = BPoly.from_derivatives(xi, yi, orders=orders)
+            for j in range(orders[i] // 2 + 1):
+                xp_assert_close(pp(x - 1e-12), pp(x + 1e-12))
+                pp = pp.derivative()
+            assert not np.allclose(pp(x - 1e-12), pp(x + 1e-12))
+
+    def test_yi_trailing_dims(self):
+        rng = np.random.RandomState(1234)
+        m, k = 7, 5
+        xi = np.sort(rng.random(m+1))
+        yi = rng.random((m+1, k, 6, 7, 8))
+        pp = BPoly.from_derivatives(xi, yi)
+        assert pp.c.shape == (2*k, m, 6, 7, 8)
+
+    def test_gh_5430(self):
+        # At least one of these raises an error unless gh-5430 is
+        # fixed. In py2k an int is implemented using a C long, so
+        # which one fails depends on your system. In py3k there is only
+        # one arbitrary precision integer type, so both should fail.
+        orders = np.int32(1)
+        p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders)
+        assert_almost_equal(p(0), np.asarray(0))
+        orders = np.int64(1)
+        p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders)
+        assert_almost_equal(p(0), np.asarray(0))
+        orders = 1
+        # This worked before; make sure it still works
+        p = BPoly.from_derivatives([0, 1], [[0], [0]], orders=orders)
+        assert_almost_equal(p(0), np.asarray(0))
+        orders = 1
+
+
+class TestNdPPoly:
+    def test_simple_1d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5)
+        x = np.linspace(0, 1, 5+1)
+
+        xi = rng.rand(200)
+
+        p = NdPPoly(c, (x,))
+        v1 = p((xi,))
+
+        v2 = _ppoly_eval_1(c[:,:,None], x, xi).ravel()
+        xp_assert_close(v1, v2)
+
+    def test_simple_2d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5, 6, 7)
+        x = np.linspace(0, 1, 6+1)
+        y = np.linspace(0, 1, 7+1)**2
+
+        xi = rng.rand(200)
+        yi = rng.rand(200)
+
+        v1 = np.empty([len(xi), 1], dtype=c.dtype)
+        v1.fill(np.nan)
+        _ppoly.evaluate_nd(c.reshape(4*5, 6*7, 1),
+                           (x, y),
+                           np.array([4, 5], dtype=np.intc),
+                           np.c_[xi, yi],
+                           np.array([0, 0], dtype=np.intc),
+                           1,
+                           v1)
+        v1 = v1.ravel()
+        v2 = _ppoly2d_eval(c, (x, y), xi, yi)
+        xp_assert_close(v1, v2)
+
+        p = NdPPoly(c, (x, y))
+        for nu in (None, (0, 0), (0, 1), (1, 0), (2, 3), (9, 2)):
+            v1 = p(np.c_[xi, yi], nu=nu)
+            v2 = _ppoly2d_eval(c, (x, y), xi, yi, nu=nu)
+            xp_assert_close(v1, v2, err_msg=repr(nu))
+
+    def test_simple_3d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5, 6, 7, 8, 9)
+        x = np.linspace(0, 1, 7+1)
+        y = np.linspace(0, 1, 8+1)**2
+        z = np.linspace(0, 1, 9+1)**3
+
+        xi = rng.rand(40)
+        yi = rng.rand(40)
+        zi = rng.rand(40)
+
+        p = NdPPoly(c, (x, y, z))
+
+        for nu in (None, (0, 0, 0), (0, 1, 0), (1, 0, 0), (2, 3, 0),
+                   (6, 0, 2)):
+            v1 = p((xi, yi, zi), nu=nu)
+            v2 = _ppoly3d_eval(c, (x, y, z), xi, yi, zi, nu=nu)
+            xp_assert_close(v1, v2, err_msg=repr(nu))
+
+    def test_simple_4d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5, 6, 7, 8, 9, 10, 11)
+        x = np.linspace(0, 1, 8+1)
+        y = np.linspace(0, 1, 9+1)**2
+        z = np.linspace(0, 1, 10+1)**3
+        u = np.linspace(0, 1, 11+1)**4
+
+        xi = rng.rand(20)
+        yi = rng.rand(20)
+        zi = rng.rand(20)
+        ui = rng.rand(20)
+
+        p = NdPPoly(c, (x, y, z, u))
+        v1 = p((xi, yi, zi, ui))
+
+        v2 = _ppoly4d_eval(c, (x, y, z, u), xi, yi, zi, ui)
+        xp_assert_close(v1, v2)
+
+    def test_deriv_1d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5)
+        x = np.linspace(0, 1, 5+1)
+
+        p = NdPPoly(c, (x,))
+
+        # derivative
+        dp = p.derivative(nu=[1])
+        p1 = PPoly(c, x)
+        dp1 = p1.derivative()
+        xp_assert_close(dp.c, dp1.c)
+
+        # antiderivative
+        dp = p.antiderivative(nu=[2])
+        p1 = PPoly(c, x)
+        dp1 = p1.antiderivative(2)
+        xp_assert_close(dp.c, dp1.c)
+
+    def test_deriv_3d(self):
+        rng = np.random.RandomState(1234)
+
+        c = rng.rand(4, 5, 6, 7, 8, 9)
+        x = np.linspace(0, 1, 7+1)
+        y = np.linspace(0, 1, 8+1)**2
+        z = np.linspace(0, 1, 9+1)**3
+
+        p = NdPPoly(c, (x, y, z))
+
+        # differentiate vs x
+        p1 = PPoly(c.transpose(0, 3, 1, 2, 4, 5), x)
+        dp = p.derivative(nu=[2])
+        dp1 = p1.derivative(2)
+        xp_assert_close(dp.c,
+                        dp1.c.transpose(0, 2, 3, 1, 4, 5))
+
+        # antidifferentiate vs y
+        p1 = PPoly(c.transpose(1, 4, 0, 2, 3, 5), y)
+        dp = p.antiderivative(nu=[0, 1, 0])
+        dp1 = p1.antiderivative(1)
+        xp_assert_close(dp.c,
+                        dp1.c.transpose(2, 0, 3, 4, 1, 5))
+
+        # differentiate vs z
+        p1 = PPoly(c.transpose(2, 5, 0, 1, 3, 4), z)
+        dp = p.derivative(nu=[0, 0, 3])
+        dp1 = p1.derivative(3)
+        xp_assert_close(dp.c,
+                        dp1.c.transpose(2, 3, 0, 4, 5, 1))
+
+    def test_deriv_3d_simple(self):
+        # Integrate to obtain function x y**2 z**4 / (2! 4!)
+        rng = np.random.RandomState(1234)
+
+        c = np.ones((1, 1, 1, 3, 4, 5))
+        x = np.linspace(0, 1, 3+1)**1
+        y = np.linspace(0, 1, 4+1)**2
+        z = np.linspace(0, 1, 5+1)**3
+
+        p = NdPPoly(c, (x, y, z))
+        ip = p.antiderivative((1, 0, 4))
+        ip = ip.antiderivative((0, 2, 0))
+
+        xi = rng.rand(20)
+        yi = rng.rand(20)
+        zi = rng.rand(20)
+
+        xp_assert_close(ip((xi, yi, zi)),
+                        xi * yi**2 * zi**4 / (gamma(3)*gamma(5)))
+
+    def test_integrate_2d(self):
+        rng = np.random.RandomState(1234)
+        c = rng.rand(4, 5, 16, 17)
+        x = np.linspace(0, 1, 16+1)**1
+        y = np.linspace(0, 1, 17+1)**2
+
+        # make continuously differentiable so that nquad() has an
+        # easier time
+        c = c.transpose(0, 2, 1, 3)
+        cx = c.reshape(c.shape[0], c.shape[1], -1).copy()
+        _ppoly.fix_continuity(cx, x, 2)
+        c = cx.reshape(c.shape)
+        c = c.transpose(0, 2, 1, 3)
+        c = c.transpose(1, 3, 0, 2)
+        cx = c.reshape(c.shape[0], c.shape[1], -1).copy()
+        _ppoly.fix_continuity(cx, y, 2)
+        c = cx.reshape(c.shape)
+        c = c.transpose(2, 0, 3, 1).copy()
+
+        # Check integration
+        p = NdPPoly(c, (x, y))
+
+        for ranges in [[(0, 1), (0, 1)],
+                       [(0, 0.5), (0, 1)],
+                       [(0, 1), (0, 0.5)],
+                       [(0.3, 0.7), (0.6, 0.2)]]:
+
+            ig = p.integrate(ranges)
+            ig2, err2 = nquad(lambda x, y: p((x, y)), ranges,
+                              opts=[dict(epsrel=1e-5, epsabs=1e-5)]*2)
+            xp_assert_close(ig, ig2, rtol=1e-5, atol=1e-5, check_0d=False,
+                            err_msg=repr(ranges))
+
+    def test_integrate_1d(self):
+        rng = np.random.RandomState(1234)
+        c = rng.rand(4, 5, 6, 16, 17, 18)
+        x = np.linspace(0, 1, 16+1)**1
+        y = np.linspace(0, 1, 17+1)**2
+        z = np.linspace(0, 1, 18+1)**3
+
+        # Check 1-D integration
+        p = NdPPoly(c, (x, y, z))
+
+        u = rng.rand(200)
+        v = rng.rand(200)
+        a, b = 0.2, 0.7
+
+        px = p.integrate_1d(a, b, axis=0)
+        pax = p.antiderivative((1, 0, 0))
+        xp_assert_close(px((u, v)), pax((b, u, v)) - pax((a, u, v)))
+
+        py = p.integrate_1d(a, b, axis=1)
+        pay = p.antiderivative((0, 1, 0))
+        xp_assert_close(py((u, v)), pay((u, b, v)) - pay((u, a, v)))
+
+        pz = p.integrate_1d(a, b, axis=2)
+        paz = p.antiderivative((0, 0, 1))
+        xp_assert_close(pz((u, v)), paz((u, v, b)) - paz((u, v, a)))
+
+    @pytest.mark.thread_unsafe
+    def test_concurrency(self):
+        rng = np.random.default_rng(12345)
+
+        c = rng.uniform(size=(4, 5, 6, 7, 8, 9))
+        x = np.linspace(0, 1, 7+1)
+        y = np.linspace(0, 1, 8+1)**2
+        z = np.linspace(0, 1, 9+1)**3
+
+        p = NdPPoly(c, (x, y, z))
+
+        def worker_fn(_, spl):
+            xi = rng.uniform(size=40)
+            yi = rng.uniform(size=40)
+            zi = rng.uniform(size=40)
+            spl((xi, yi, zi))
+
+        _run_concurrent_barrier(10, worker_fn, p)
+
+
+def _ppoly_eval_1(c, x, xps):
+    """Evaluate piecewise polynomial manually"""
+    out = np.zeros((len(xps), c.shape[2]))
+    for i, xp in enumerate(xps):
+        if xp < 0 or xp > 1:
+            out[i,:] = np.nan
+            continue
+        j = np.searchsorted(x, xp) - 1
+        d = xp - x[j]
+        assert x[j] <= xp < x[j+1]
+        r = sum(c[k,j] * d**(c.shape[0]-k-1)
+                for k in range(c.shape[0]))
+        out[i,:] = r
+    return out
+
+
+def _ppoly_eval_2(coeffs, breaks, xnew, fill=np.nan):
+    """Evaluate piecewise polynomial manually (another way)"""
+    a = breaks[0]
+    b = breaks[-1]
+    K = coeffs.shape[0]
+
+    saveshape = np.shape(xnew)
+    xnew = np.ravel(xnew)
+    res = np.empty_like(xnew)
+    mask = (xnew >= a) & (xnew <= b)
+    res[~mask] = fill
+    xx = xnew.compress(mask)
+    indxs = np.searchsorted(breaks, xx)-1
+    indxs = indxs.clip(0, len(breaks))
+    pp = coeffs
+    diff = xx - breaks.take(indxs)
+    V = np.vander(diff, N=K)
+    values = np.array([np.dot(V[k, :], pp[:, indxs[k]]) for k in range(len(xx))])
+    res[mask] = values
+    res.shape = saveshape
+    return res
+
+
+def _dpow(x, y, n):
+    """
+    d^n (x**y) / dx^n
+    """
+    if n < 0:
+        raise ValueError("invalid derivative order")
+    elif n > y:
+        return 0
+    else:
+        return poch(y - n + 1, n) * x**(y - n)
+
+
+def _ppoly2d_eval(c, xs, xnew, ynew, nu=None):
+    """
+    Straightforward evaluation of 2-D piecewise polynomial
+    """
+    if nu is None:
+        nu = (0, 0)
+
+    out = np.empty((len(xnew),), dtype=c.dtype)
+
+    nx, ny = c.shape[:2]
+
+    for jout, (x, y) in enumerate(zip(xnew, ynew)):
+        if not ((xs[0][0] <= x <= xs[0][-1]) and
+                (xs[1][0] <= y <= xs[1][-1])):
+            out[jout] = np.nan
+            continue
+
+        j1 = np.searchsorted(xs[0], x) - 1
+        j2 = np.searchsorted(xs[1], y) - 1
+
+        s1 = x - xs[0][j1]
+        s2 = y - xs[1][j2]
+
+        val = 0
+
+        for k1 in range(c.shape[0]):
+            for k2 in range(c.shape[1]):
+                val += (c[nx-k1-1,ny-k2-1,j1,j2]
+                        * _dpow(s1, k1, nu[0])
+                        * _dpow(s2, k2, nu[1]))
+
+        out[jout] = val
+
+    return out
+
+
+def _ppoly3d_eval(c, xs, xnew, ynew, znew, nu=None):
+    """
+    Straightforward evaluation of 3-D piecewise polynomial
+    """
+    if nu is None:
+        nu = (0, 0, 0)
+
+    out = np.empty((len(xnew),), dtype=c.dtype)
+
+    nx, ny, nz = c.shape[:3]
+
+    for jout, (x, y, z) in enumerate(zip(xnew, ynew, znew)):
+        if not ((xs[0][0] <= x <= xs[0][-1]) and
+                (xs[1][0] <= y <= xs[1][-1]) and
+                (xs[2][0] <= z <= xs[2][-1])):
+            out[jout] = np.nan
+            continue
+
+        j1 = np.searchsorted(xs[0], x) - 1
+        j2 = np.searchsorted(xs[1], y) - 1
+        j3 = np.searchsorted(xs[2], z) - 1
+
+        s1 = x - xs[0][j1]
+        s2 = y - xs[1][j2]
+        s3 = z - xs[2][j3]
+
+        val = 0
+        for k1 in range(c.shape[0]):
+            for k2 in range(c.shape[1]):
+                for k3 in range(c.shape[2]):
+                    val += (c[nx-k1-1,ny-k2-1,nz-k3-1,j1,j2,j3]
+                            * _dpow(s1, k1, nu[0])
+                            * _dpow(s2, k2, nu[1])
+                            * _dpow(s3, k3, nu[2]))
+
+        out[jout] = val
+
+    return out
+
+
+def _ppoly4d_eval(c, xs, xnew, ynew, znew, unew, nu=None):
+    """
+    Straightforward evaluation of 4-D piecewise polynomial
+    """
+    if nu is None:
+        nu = (0, 0, 0, 0)
+
+    out = np.empty((len(xnew),), dtype=c.dtype)
+
+    mx, my, mz, mu = c.shape[:4]
+
+    for jout, (x, y, z, u) in enumerate(zip(xnew, ynew, znew, unew)):
+        if not ((xs[0][0] <= x <= xs[0][-1]) and
+                (xs[1][0] <= y <= xs[1][-1]) and
+                (xs[2][0] <= z <= xs[2][-1]) and
+                (xs[3][0] <= u <= xs[3][-1])):
+            out[jout] = np.nan
+            continue
+
+        j1 = np.searchsorted(xs[0], x) - 1
+        j2 = np.searchsorted(xs[1], y) - 1
+        j3 = np.searchsorted(xs[2], z) - 1
+        j4 = np.searchsorted(xs[3], u) - 1
+
+        s1 = x - xs[0][j1]
+        s2 = y - xs[1][j2]
+        s3 = z - xs[2][j3]
+        s4 = u - xs[3][j4]
+
+        val = 0
+        for k1 in range(c.shape[0]):
+            for k2 in range(c.shape[1]):
+                for k3 in range(c.shape[2]):
+                    for k4 in range(c.shape[3]):
+                        val += (c[mx-k1-1,my-k2-1,mz-k3-1,mu-k4-1,j1,j2,j3,j4]
+                                * _dpow(s1, k1, nu[0])
+                                * _dpow(s2, k2, nu[1])
+                                * _dpow(s3, k3, nu[2])
+                                * _dpow(s4, k4, nu[3]))
+
+        out[jout] = val
+
+    return out
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_ndgriddata.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_ndgriddata.py
new file mode 100644
index 0000000000000000000000000000000000000000..047a940b3efcb24ec85a94a87dd1050baa01f165
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_ndgriddata.py
@@ -0,0 +1,308 @@
+import numpy as np
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close
+)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.interpolate import (griddata, NearestNDInterpolator,
+                               LinearNDInterpolator,
+                               CloughTocher2DInterpolator)
+from scipy._lib._testutils import _run_concurrent_barrier
+
+
+parametrize_interpolators = pytest.mark.parametrize(
+    "interpolator", [NearestNDInterpolator, LinearNDInterpolator,
+                     CloughTocher2DInterpolator]
+)
+parametrize_methods = pytest.mark.parametrize(
+    'method',
+    ('nearest', 'linear', 'cubic'),
+)
+parametrize_rescale = pytest.mark.parametrize(
+    'rescale',
+    (True, False),
+)
+
+
+class TestGriddata:
+    def test_fill_value(self):
+        x = [(0,0), (0,1), (1,0)]
+        y = [1, 2, 3]
+
+        yi = griddata(x, y, [(1,1), (1,2), (0,0)], fill_value=-1)
+        xp_assert_equal(yi, [-1., -1, 1])
+
+        yi = griddata(x, y, [(1,1), (1,2), (0,0)])
+        xp_assert_equal(yi, [np.nan, np.nan, 1])
+
+    @parametrize_methods
+    @parametrize_rescale
+    def test_alternative_call(self, method, rescale):
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = (np.arange(x.shape[0], dtype=np.float64)[:,None]
+             + np.array([0,1])[None,:])
+
+        msg = repr((method, rescale))
+        yi = griddata((x[:,0], x[:,1]), y, (x[:,0], x[:,1]), method=method,
+                      rescale=rescale)
+        xp_assert_close(y, yi, atol=1e-14, err_msg=msg)
+
+    @parametrize_methods
+    @parametrize_rescale
+    def test_multivalue_2d(self, method, rescale):
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = (np.arange(x.shape[0], dtype=np.float64)[:,None]
+             + np.array([0,1])[None,:])
+
+        msg = repr((method, rescale))
+        yi = griddata(x, y, x, method=method, rescale=rescale)
+        xp_assert_close(y, yi, atol=1e-14, err_msg=msg)
+
+    @parametrize_methods
+    @parametrize_rescale
+    def test_multipoint_2d(self, method, rescale):
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+
+        xi = x[:,None,:] + np.array([0,0,0])[None,:,None]
+
+        msg = repr((method, rescale))
+        yi = griddata(x, y, xi, method=method, rescale=rescale)
+
+        assert yi.shape == (5, 3), msg
+        xp_assert_close(yi, np.tile(y[:,None], (1, 3)),
+                        atol=1e-14, err_msg=msg)
+
+    @parametrize_methods
+    @parametrize_rescale
+    def test_complex_2d(self, method, rescale):
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 2j*y[::-1]
+
+        xi = x[:,None,:] + np.array([0,0,0])[None,:,None]
+
+        msg = repr((method, rescale))
+        yi = griddata(x, y, xi, method=method, rescale=rescale)
+
+        assert yi.shape == (5, 3)
+        xp_assert_close(yi, np.tile(y[:,None], (1, 3)),
+                        atol=1e-14, err_msg=msg)
+
+    @parametrize_methods
+    def test_1d(self, method):
+        x = np.array([1, 2.5, 3, 4.5, 5, 6])
+        y = np.array([1, 2, 0, 3.9, 2, 1])
+
+        xp_assert_close(griddata(x, y, x, method=method), y,
+                        err_msg=method, atol=1e-14)
+        xp_assert_close(griddata(x.reshape(6, 1), y, x, method=method), y,
+                        err_msg=method, atol=1e-14)
+        xp_assert_close(griddata((x,), y, (x,), method=method), y,
+                        err_msg=method, atol=1e-14)
+
+    def test_1d_borders(self):
+        # Test for nearest neighbor case with xi outside
+        # the range of the values.
+        x = np.array([1, 2.5, 3, 4.5, 5, 6])
+        y = np.array([1, 2, 0, 3.9, 2, 1])
+        xi = np.array([0.9, 6.5])
+        yi_should = np.array([1.0, 1.0])
+
+        method = 'nearest'
+        xp_assert_close(griddata(x, y, xi,
+                                 method=method), yi_should,
+                        err_msg=method,
+                        atol=1e-14)
+        xp_assert_close(griddata(x.reshape(6, 1), y, xi,
+                                 method=method), yi_should,
+                        err_msg=method,
+                        atol=1e-14)
+        xp_assert_close(griddata((x, ), y, (xi, ),
+                                 method=method), yi_should,
+                        err_msg=method,
+                        atol=1e-14)
+
+    @parametrize_methods
+    def test_1d_unsorted(self, method):
+        x = np.array([2.5, 1, 4.5, 5, 6, 3])
+        y = np.array([1, 2, 0, 3.9, 2, 1])
+
+        xp_assert_close(griddata(x, y, x, method=method), y,
+                        err_msg=method, atol=1e-10)
+        xp_assert_close(griddata(x.reshape(6, 1), y, x, method=method), y,
+                        err_msg=method, atol=1e-10)
+        xp_assert_close(griddata((x,), y, (x,), method=method), y,
+                        err_msg=method, atol=1e-10)
+
+    @parametrize_methods
+    def test_square_rescale_manual(self, method):
+        points = np.array([(0,0), (0,100), (10,100), (10,0), (1, 5)], dtype=np.float64)
+        points_rescaled = np.array([(0,0), (0,1), (1,1), (1,0), (0.1, 0.05)],
+                                   dtype=np.float64)
+        values = np.array([1., 2., -3., 5., 9.], dtype=np.float64)
+
+        xx, yy = np.broadcast_arrays(np.linspace(0, 10, 14)[:,None],
+                                     np.linspace(0, 100, 14)[None,:])
+        xx = xx.ravel()
+        yy = yy.ravel()
+        xi = np.array([xx, yy]).T.copy()
+
+        msg = method
+        zi = griddata(points_rescaled, values, xi/np.array([10, 100.]),
+                      method=method)
+        zi_rescaled = griddata(points, values, xi, method=method,
+                               rescale=True)
+        xp_assert_close(zi, zi_rescaled, err_msg=msg,
+                        atol=1e-12)
+
+    @parametrize_methods
+    def test_xi_1d(self, method):
+        # Check that 1-D xi is interpreted as a coordinate
+        x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
+                     dtype=np.float64)
+        y = np.arange(x.shape[0], dtype=np.float64)
+        y = y - 2j*y[::-1]
+
+        xi = np.array([0.5, 0.5])
+
+        p1 = griddata(x, y, xi, method=method)
+        p2 = griddata(x, y, xi[None,:], method=method)
+        xp_assert_close(p1, p2, err_msg=method)
+
+        xi1 = np.array([0.5])
+        xi3 = np.array([0.5, 0.5, 0.5])
+        assert_raises(ValueError, griddata, x, y, xi1,
+                      method=method)
+        assert_raises(ValueError, griddata, x, y, xi3,
+                      method=method)
+
+
+class TestNearestNDInterpolator:
+    def test_nearest_options(self):
+        # smoke test that NearestNDInterpolator accept cKDTree options
+        npts, nd = 4, 3
+        x = np.arange(npts*nd).reshape((npts, nd))
+        y = np.arange(npts)
+        nndi = NearestNDInterpolator(x, y)
+
+        opts = {'balanced_tree': False, 'compact_nodes': False}
+        nndi_o = NearestNDInterpolator(x, y, tree_options=opts)
+        xp_assert_close(nndi(x), nndi_o(x), atol=1e-14)
+
+    def test_nearest_list_argument(self):
+        nd = np.array([[0, 0, 0, 0, 1, 0, 1],
+                       [0, 0, 0, 0, 0, 1, 1],
+                       [0, 0, 0, 0, 1, 1, 2]])
+        d = nd[:, 3:]
+
+        # z is np.array
+        NI = NearestNDInterpolator((d[0], d[1]), d[2])
+        xp_assert_equal(NI([0.1, 0.9], [0.1, 0.9]), [0.0, 2.0])
+
+        # z is list
+        NI = NearestNDInterpolator((d[0], d[1]), list(d[2]))
+        xp_assert_equal(NI([0.1, 0.9], [0.1, 0.9]), [0.0, 2.0])
+
+    def test_nearest_query_options(self):
+        nd = np.array([[0, 0.5, 0, 1],
+                       [0, 0, 0.5, 1],
+                       [0, 1, 1, 2]])
+        delta = 0.1
+        query_points = [0 + delta, 1 + delta], [0 + delta, 1 + delta]
+
+        # case 1 - query max_dist is smaller than
+        # the query points' nearest distance to nd.
+        NI = NearestNDInterpolator((nd[0], nd[1]), nd[2])
+        distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) - 1e-7
+        xp_assert_equal(NI(query_points, distance_upper_bound=distance_upper_bound),
+                           [np.nan, np.nan])
+
+        # case 2 - query p is inf, will return [0, 2]
+        distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) - 1e-7
+        p = np.inf
+        xp_assert_equal(
+            NI(query_points, distance_upper_bound=distance_upper_bound, p=p),
+            [0.0, 2.0]
+        )
+
+        # case 3 - query max_dist is larger, so should return non np.nan
+        distance_upper_bound = np.sqrt(delta ** 2 + delta ** 2) + 1e-7
+        xp_assert_equal(
+            NI(query_points, distance_upper_bound=distance_upper_bound),
+            [0.0, 2.0]
+        )
+
+    def test_nearest_query_valid_inputs(self):
+        nd = np.array([[0, 1, 0, 1],
+                       [0, 0, 1, 1],
+                       [0, 1, 1, 2]])
+        NI = NearestNDInterpolator((nd[0], nd[1]), nd[2])
+        with assert_raises(TypeError):
+            NI([0.5, 0.5], query_options="not a dictionary")
+
+    @pytest.mark.thread_unsafe
+    def test_concurrency(self):
+        npts, nd = 50, 3
+        x = np.arange(npts * nd).reshape((npts, nd))
+        y = np.arange(npts)
+        nndi = NearestNDInterpolator(x, y)
+
+        def worker_fn(_, spl):
+            spl(x)
+
+        _run_concurrent_barrier(10, worker_fn, nndi)
+
+
+class TestNDInterpolators:
+    @parametrize_interpolators
+    def test_broadcastable_input(self, interpolator):
+        # input data
+        rng = np.random.RandomState(0)
+        x = rng.random(10)
+        y = rng.random(10)
+        z = np.hypot(x, y)
+
+        # x-y grid for interpolation
+        X = np.linspace(min(x), max(x))
+        Y = np.linspace(min(y), max(y))
+        X, Y = np.meshgrid(X, Y)
+        XY = np.vstack((X.ravel(), Y.ravel())).T
+        interp = interpolator(list(zip(x, y)), z)
+        # single array input
+        interp_points0 = interp(XY)
+        # tuple input
+        interp_points1 = interp((X, Y))
+        interp_points2 = interp((X, 0.0))
+        # broadcastable input
+        interp_points3 = interp(X, Y)
+        interp_points4 = interp(X, 0.0)
+
+        assert (interp_points0.size ==
+                interp_points1.size ==
+                interp_points2.size ==
+                interp_points3.size ==
+                interp_points4.size)
+
+    @parametrize_interpolators
+    def test_read_only(self, interpolator):
+        # input data
+        rng = np.random.RandomState(0)
+        xy = rng.random((10, 2))
+        x, y = xy[:, 0], xy[:, 1]
+        z = np.hypot(x, y)
+
+        # interpolation points
+        XY = rng.random((50, 2))
+
+        xy.setflags(write=False)
+        z.setflags(write=False)
+        XY.setflags(write=False)
+
+        interp = interpolator(xy, z)
+        interp(XY)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_pade.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_pade.py
new file mode 100644
index 0000000000000000000000000000000000000000..119b7d1c5667368b284fbf6458174ea14e71957a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_pade.py
@@ -0,0 +1,107 @@
+import numpy as np
+from scipy.interpolate import pade
+from scipy._lib._array_api import (
+    xp_assert_equal, assert_array_almost_equal
+)
+
+def test_pade_trivial():
+    nump, denomp = pade([1.0], 0)
+    xp_assert_equal(nump.c, np.asarray([1.0]))
+    xp_assert_equal(denomp.c, np.asarray([1.0]))
+
+    nump, denomp = pade([1.0], 0, 0)
+    xp_assert_equal(nump.c, np.asarray([1.0]))
+    xp_assert_equal(denomp.c, np.asarray([1.0]))
+
+
+def test_pade_4term_exp():
+    # First four Taylor coefficients of exp(x).
+    # Unlike poly1d, the first array element is the zero-order term.
+    an = [1.0, 1.0, 0.5, 1.0/6]
+
+    nump, denomp = pade(an, 0)
+    assert_array_almost_equal(nump.c, [1.0/6, 0.5, 1.0, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0])
+
+    nump, denomp = pade(an, 1)
+    assert_array_almost_equal(nump.c, [1.0/6, 2.0/3, 1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/3, 1.0])
+
+    nump, denomp = pade(an, 2)
+    assert_array_almost_equal(nump.c, [1.0/3, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0/6, -2.0/3, 1.0])
+
+    nump, denomp = pade(an, 3)
+    assert_array_almost_equal(nump.c, [1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/6, 0.5, -1.0, 1.0])
+
+    # Testing inclusion of optional parameter
+    nump, denomp = pade(an, 0, 3)
+    assert_array_almost_equal(nump.c, [1.0/6, 0.5, 1.0, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0])
+
+    nump, denomp = pade(an, 1, 2)
+    assert_array_almost_equal(nump.c, [1.0/6, 2.0/3, 1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/3, 1.0])
+
+    nump, denomp = pade(an, 2, 1)
+    assert_array_almost_equal(nump.c, [1.0/3, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0/6, -2.0/3, 1.0])
+
+    nump, denomp = pade(an, 3, 0)
+    assert_array_almost_equal(nump.c, [1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/6, 0.5, -1.0, 1.0])
+
+    # Testing reducing array.
+    nump, denomp = pade(an, 0, 2)
+    assert_array_almost_equal(nump.c, [0.5, 1.0, 1.0])
+    assert_array_almost_equal(denomp.c, [1.0])
+
+    nump, denomp = pade(an, 1, 1)
+    assert_array_almost_equal(nump.c, [1.0/2, 1.0])
+    assert_array_almost_equal(denomp.c, [-1.0/2, 1.0])
+
+    nump, denomp = pade(an, 2, 0)
+    assert_array_almost_equal(nump.c, [1.0])
+    assert_array_almost_equal(denomp.c, [1.0/2, -1.0, 1.0])
+
+
+def test_pade_ints():
+    # Simple test sequences (one of ints, one of floats).
+    an_int = [1, 2, 3, 4]
+    an_flt = [1.0, 2.0, 3.0, 4.0]
+
+    # Make sure integer arrays give the same result as float arrays with same values.
+    for i in range(0, len(an_int)):
+        for j in range(0, len(an_int) - i):
+
+            # Create float and int pade approximation for given order.
+            nump_int, denomp_int = pade(an_int, i, j)
+            nump_flt, denomp_flt = pade(an_flt, i, j)
+
+            # Check that they are the same.
+            xp_assert_equal(nump_int.c, nump_flt.c)
+            xp_assert_equal(denomp_int.c, denomp_flt.c)
+
+
+def test_pade_complex():
+    # Test sequence with known solutions - see page 6 of 10.1109/PESGM.2012.6344759.
+    # Variable x is parameter - these tests will work with any complex number.
+    x = 0.2 + 0.6j
+    an = [1.0, x, -x*x.conjugate(), x.conjugate()*(x**2) + x*(x.conjugate()**2),
+          -(x**3)*x.conjugate() - 3*(x*x.conjugate())**2 - x*(x.conjugate()**3)]
+
+    nump, denomp = pade(an, 1, 1)
+    assert_array_almost_equal(nump.c, [x + x.conjugate(), 1.0])
+    assert_array_almost_equal(denomp.c, [x.conjugate(), 1.0])
+
+    nump, denomp = pade(an, 1, 2)
+    assert_array_almost_equal(nump.c, [x**2, 2*x + x.conjugate(), 1.0])
+    assert_array_almost_equal(denomp.c, [x + x.conjugate(), 1.0])
+
+    nump, denomp = pade(an, 2, 2)
+    assert_array_almost_equal(
+        nump.c,
+        [x**2 + x*x.conjugate() + x.conjugate()**2, 2*(x + x.conjugate()), 1.0]
+    )
+    assert_array_almost_equal(denomp.c, [x.conjugate()**2, x + 2*x.conjugate(), 1.0])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_polyint.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_polyint.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3e6cb7894ea344289c12b522b45c5e0f22748e6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_polyint.py
@@ -0,0 +1,972 @@
+import warnings
+import io
+import numpy as np
+
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close, assert_array_almost_equal, assert_almost_equal
+)
+from pytest import raises as assert_raises
+import pytest
+
+from scipy.interpolate import (
+    KroghInterpolator, krogh_interpolate,
+    BarycentricInterpolator, barycentric_interpolate,
+    approximate_taylor_polynomial, CubicHermiteSpline, pchip,
+    PchipInterpolator, pchip_interpolate, Akima1DInterpolator, CubicSpline,
+    make_interp_spline)
+from scipy._lib._testutils import _run_concurrent_barrier
+
+
+def check_shape(interpolator_cls, x_shape, y_shape, deriv_shape=None, axis=0,
+                extra_args=None):
+    if extra_args is None:
+        extra_args = {}
+    rng = np.random.RandomState(1234)
+
+    x = [-1, 0, 1, 2, 3, 4]
+    s = list(range(1, len(y_shape)+1))
+    s.insert(axis % (len(y_shape)+1), 0)
+    y = rng.rand(*((6,) + y_shape)).transpose(s)
+
+    xi = np.zeros(x_shape)
+    if interpolator_cls is CubicHermiteSpline:
+        dydx = rng.rand(*((6,) + y_shape)).transpose(s)
+        yi = interpolator_cls(x, y, dydx, axis=axis, **extra_args)(xi)
+    else:
+        yi = interpolator_cls(x, y, axis=axis, **extra_args)(xi)
+
+    target_shape = ((deriv_shape or ()) + y.shape[:axis]
+                    + x_shape + y.shape[axis:][1:])
+    assert yi.shape == target_shape
+
+    # check it works also with lists
+    if x_shape and y.size > 0:
+        if interpolator_cls is CubicHermiteSpline:
+            interpolator_cls(list(x), list(y), list(dydx), axis=axis,
+                             **extra_args)(list(xi))
+        else:
+            interpolator_cls(list(x), list(y), axis=axis,
+                             **extra_args)(list(xi))
+
+    # check also values
+    if xi.size > 0 and deriv_shape is None:
+        bs_shape = y.shape[:axis] + (1,)*len(x_shape) + y.shape[axis:][1:]
+        yv = y[((slice(None,),)*(axis % y.ndim)) + (1,)]
+        yv = yv.reshape(bs_shape)
+
+        yi, y = np.broadcast_arrays(yi, yv)
+        xp_assert_close(yi, y)
+
+
+SHAPES = [(), (0,), (1,), (6, 2, 5)]
+
+
+def test_shapes():
+
+    def spl_interp(x, y, axis):
+        return make_interp_spline(x, y, axis=axis)
+
+    for ip in [KroghInterpolator, BarycentricInterpolator, CubicHermiteSpline,
+               pchip, Akima1DInterpolator, CubicSpline, spl_interp]:
+        for s1 in SHAPES:
+            for s2 in SHAPES:
+                for axis in range(-len(s2), len(s2)):
+                    if ip != CubicSpline:
+                        check_shape(ip, s1, s2, None, axis)
+                    else:
+                        for bc in ['natural', 'clamped']:
+                            extra = {'bc_type': bc}
+                            check_shape(ip, s1, s2, None, axis, extra)
+
+def test_derivs_shapes():
+    for ip in [KroghInterpolator, BarycentricInterpolator]:
+        def interpolator_derivs(x, y, axis=0):
+            return ip(x, y, axis).derivatives
+
+        for s1 in SHAPES:
+            for s2 in SHAPES:
+                for axis in range(-len(s2), len(s2)):
+                    check_shape(interpolator_derivs, s1, s2, (6,), axis)
+
+
+def test_deriv_shapes():
+    def krogh_deriv(x, y, axis=0):
+        return KroghInterpolator(x, y, axis).derivative
+
+    def bary_deriv(x, y, axis=0):
+        return BarycentricInterpolator(x, y, axis).derivative
+
+    def pchip_deriv(x, y, axis=0):
+        return pchip(x, y, axis).derivative()
+
+    def pchip_deriv2(x, y, axis=0):
+        return pchip(x, y, axis).derivative(2)
+
+    def pchip_antideriv(x, y, axis=0):
+        return pchip(x, y, axis).antiderivative()
+
+    def pchip_antideriv2(x, y, axis=0):
+        return pchip(x, y, axis).antiderivative(2)
+
+    def pchip_deriv_inplace(x, y, axis=0):
+        class P(PchipInterpolator):
+            def __call__(self, x):
+                return PchipInterpolator.__call__(self, x, 1)
+            pass
+        return P(x, y, axis)
+
+    def akima_deriv(x, y, axis=0):
+        return Akima1DInterpolator(x, y, axis).derivative()
+
+    def akima_antideriv(x, y, axis=0):
+        return Akima1DInterpolator(x, y, axis).antiderivative()
+
+    def cspline_deriv(x, y, axis=0):
+        return CubicSpline(x, y, axis).derivative()
+
+    def cspline_antideriv(x, y, axis=0):
+        return CubicSpline(x, y, axis).antiderivative()
+
+    def bspl_deriv(x, y, axis=0):
+        return make_interp_spline(x, y, axis=axis).derivative()
+
+    def bspl_antideriv(x, y, axis=0):
+        return make_interp_spline(x, y, axis=axis).antiderivative()
+
+    for ip in [krogh_deriv, bary_deriv, pchip_deriv, pchip_deriv2, pchip_deriv_inplace,
+               pchip_antideriv, pchip_antideriv2, akima_deriv, akima_antideriv,
+               cspline_deriv, cspline_antideriv, bspl_deriv, bspl_antideriv]:
+        for s1 in SHAPES:
+            for s2 in SHAPES:
+                for axis in range(-len(s2), len(s2)):
+                    check_shape(ip, s1, s2, (), axis)
+
+
+def test_complex():
+    x = [1, 2, 3, 4]
+    y = [1, 2, 1j, 3]
+
+    for ip in [KroghInterpolator, BarycentricInterpolator, CubicSpline]:
+        p = ip(x, y)
+        xp_assert_close(p(x), np.asarray(y))
+
+    dydx = [0, -1j, 2, 3j]
+    p = CubicHermiteSpline(x, y, dydx)
+    xp_assert_close(p(x), np.asarray(y))
+    xp_assert_close(p(x, 1), np.asarray(dydx))
+
+
+class TestKrogh:
+    def setup_method(self):
+        self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2])
+        self.test_xs = np.linspace(-1,1,100)
+        self.xs = np.linspace(-1,1,5)
+        self.ys = self.true_poly(self.xs)
+
+    def test_lagrange(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs))
+
+    def test_scalar(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        assert_almost_equal(self.true_poly(7), P(7), check_0d=False)
+        assert_almost_equal(self.true_poly(np.array(7)), P(np.array(7)), check_0d=False)
+
+    def test_derivatives(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        D = P.derivatives(self.test_xs)
+        for i in range(D.shape[0]):
+            assert_almost_equal(self.true_poly.deriv(i)(self.test_xs),
+                                D[i])
+
+    def test_low_derivatives(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        D = P.derivatives(self.test_xs,len(self.xs)+2)
+        for i in range(D.shape[0]):
+            assert_almost_equal(self.true_poly.deriv(i)(self.test_xs),
+                                D[i])
+
+    def test_derivative(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        m = 10
+        r = P.derivatives(self.test_xs,m)
+        for i in range(m):
+            assert_almost_equal(P.derivative(self.test_xs,i),r[i])
+
+    def test_high_derivative(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        for i in range(len(self.xs), 2*len(self.xs)):
+            assert_almost_equal(P.derivative(self.test_xs,i),
+                                np.zeros(len(self.test_xs)))
+
+    def test_ndim_derivatives(self):
+        poly1 = self.true_poly
+        poly2 = np.polynomial.Polynomial([-2, 5, 3, -1])
+        poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6])
+        ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1)
+
+        P = KroghInterpolator(self.xs, ys, axis=0)
+        D = P.derivatives(self.test_xs)
+        for i in range(D.shape[0]):
+            xp_assert_close(D[i],
+                            np.stack((poly1.deriv(i)(self.test_xs),
+                                      poly2.deriv(i)(self.test_xs),
+                                      poly3.deriv(i)(self.test_xs)),
+                                     axis=-1))
+
+    def test_ndim_derivative(self):
+        poly1 = self.true_poly
+        poly2 = np.polynomial.Polynomial([-2, 5, 3, -1])
+        poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6])
+        ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1)
+
+        P = KroghInterpolator(self.xs, ys, axis=0)
+        for i in range(P.n):
+            xp_assert_close(P.derivative(self.test_xs, i),
+                            np.stack((poly1.deriv(i)(self.test_xs),
+                                      poly2.deriv(i)(self.test_xs),
+                                      poly3.deriv(i)(self.test_xs)),
+                                     axis=-1))
+
+    def test_hermite(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        assert_almost_equal(self.true_poly(self.test_xs),P(self.test_xs))
+
+    def test_vector(self):
+        xs = [0, 1, 2]
+        ys = np.array([[0,1],[1,0],[2,1]])
+        P = KroghInterpolator(xs,ys)
+        Pi = [KroghInterpolator(xs,ys[:,i]) for i in range(ys.shape[1])]
+        test_xs = np.linspace(-1,3,100)
+        assert_almost_equal(P(test_xs),
+                            np.asarray([p(test_xs) for p in Pi]).T)
+        assert_almost_equal(P.derivatives(test_xs),
+                np.transpose(np.asarray([p.derivatives(test_xs) for p in Pi]),
+                    (1,2,0)))
+
+    def test_empty(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        xp_assert_equal(P([]), np.asarray([]))
+
+    def test_shapes_scalarvalue(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        assert np.shape(P(0)) == ()
+        assert np.shape(P(np.array(0))) == ()
+        assert np.shape(P([0])) == (1,)
+        assert np.shape(P([0,1])) == (2,)
+
+    def test_shapes_scalarvalue_derivative(self):
+        P = KroghInterpolator(self.xs,self.ys)
+        n = P.n
+        assert np.shape(P.derivatives(0)) == (n,)
+        assert np.shape(P.derivatives(np.array(0))) == (n,)
+        assert np.shape(P.derivatives([0])) == (n, 1)
+        assert np.shape(P.derivatives([0, 1])) == (n, 2)
+
+    def test_shapes_vectorvalue(self):
+        P = KroghInterpolator(self.xs,np.outer(self.ys,np.arange(3)))
+        assert np.shape(P(0)) == (3,)
+        assert np.shape(P([0])) == (1, 3)
+        assert np.shape(P([0, 1])) == (2, 3)
+
+    def test_shapes_1d_vectorvalue(self):
+        P = KroghInterpolator(self.xs,np.outer(self.ys,[1]))
+        assert np.shape(P(0)) == (1,)
+        assert np.shape(P([0])) == (1, 1)
+        assert np.shape(P([0,1])) == (2, 1)
+
+    def test_shapes_vectorvalue_derivative(self):
+        P = KroghInterpolator(self.xs,np.outer(self.ys,np.arange(3)))
+        n = P.n
+        assert np.shape(P.derivatives(0)) == (n, 3)
+        assert np.shape(P.derivatives([0])) == (n, 1, 3)
+        assert np.shape(P.derivatives([0,1])) == (n, 2, 3)
+
+    def test_wrapper(self):
+        P = KroghInterpolator(self.xs, self.ys)
+        ki = krogh_interpolate
+        assert_almost_equal(P(self.test_xs), ki(self.xs, self.ys, self.test_xs))
+        assert_almost_equal(P.derivative(self.test_xs, 2),
+                            ki(self.xs, self.ys, self.test_xs, der=2))
+        assert_almost_equal(P.derivatives(self.test_xs, 2),
+                            ki(self.xs, self.ys, self.test_xs, der=[0, 1]))
+
+    def test_int_inputs(self):
+        # Check input args are cast correctly to floats, gh-3669
+        x = [0, 234, 468, 702, 936, 1170, 1404, 2340, 3744, 6084, 8424,
+             13104, 60000]
+        offset_cdf = np.array([-0.95, -0.86114777, -0.8147762, -0.64072425,
+                               -0.48002351, -0.34925329, -0.26503107,
+                               -0.13148093, -0.12988833, -0.12979296,
+                               -0.12973574, -0.08582937, 0.05])
+        f = KroghInterpolator(x, offset_cdf)
+
+        xp_assert_close(abs((f(x) - offset_cdf) / f.derivative(x, 1)),
+                        np.zeros_like(offset_cdf), atol=1e-10)
+
+    def test_derivatives_complex(self):
+        # regression test for gh-7381: krogh.derivatives(0) fails complex y
+        x, y = np.array([-1, -1, 0, 1, 1]), np.array([1, 1.0j, 0, -1, 1.0j])
+        func = KroghInterpolator(x, y)
+        cmplx = func.derivatives(0)
+
+        cmplx2 = (KroghInterpolator(x, y.real).derivatives(0) +
+                  1j*KroghInterpolator(x, y.imag).derivatives(0))
+        xp_assert_close(cmplx, cmplx2, atol=1e-15)
+
+    @pytest.mark.thread_unsafe
+    def test_high_degree_warning(self):
+        with pytest.warns(UserWarning, match="40 degrees provided,"):
+            KroghInterpolator(np.arange(40), np.ones(40))
+
+    @pytest.mark.thread_unsafe
+    def test_concurrency(self):
+        P = KroghInterpolator(self.xs, self.ys)
+
+        def worker_fn(_, interp):
+            interp(self.xs)
+
+        _run_concurrent_barrier(10, worker_fn, P)
+
+
+class TestTaylor:
+    def test_exponential(self):
+        degree = 5
+        p = approximate_taylor_polynomial(np.exp, 0, degree, 1, 15)
+        for i in range(degree+1):
+            assert_almost_equal(p(0),1)
+            p = p.deriv()
+        assert_almost_equal(p(0),0)
+
+
+class TestBarycentric:
+    def setup_method(self):
+        self.true_poly = np.polynomial.Polynomial([-4, 5, 1, 3, -2])
+        self.test_xs = np.linspace(-1, 1, 100)
+        self.xs = np.linspace(-1, 1, 5)
+        self.ys = self.true_poly(self.xs)
+
+    def test_lagrange(self):
+        # Ensure backwards compatible post SPEC7
+        P = BarycentricInterpolator(self.xs, self.ys, random_state=1)
+        xp_assert_close(P(self.test_xs), self.true_poly(self.test_xs))
+
+    def test_scalar(self):
+        P = BarycentricInterpolator(self.xs, self.ys, rng=1)
+        xp_assert_close(P(7), self.true_poly(7), check_0d=False)
+        xp_assert_close(P(np.array(7)), self.true_poly(np.array(7)), check_0d=False)
+
+    def test_derivatives(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        D = P.derivatives(self.test_xs)
+        for i in range(D.shape[0]):
+            xp_assert_close(self.true_poly.deriv(i)(self.test_xs), D[i])
+
+    def test_low_derivatives(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        D = P.derivatives(self.test_xs, len(self.xs)+2)
+        for i in range(D.shape[0]):
+            xp_assert_close(self.true_poly.deriv(i)(self.test_xs),
+                            D[i],
+                            atol=1e-12)
+
+    def test_derivative(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        m = 10
+        r = P.derivatives(self.test_xs, m)
+        for i in range(m):
+            xp_assert_close(P.derivative(self.test_xs, i), r[i])
+
+    def test_high_derivative(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        for i in range(len(self.xs), 5*len(self.xs)):
+            xp_assert_close(P.derivative(self.test_xs, i),
+                            np.zeros(len(self.test_xs)))
+
+    def test_ndim_derivatives(self):
+        poly1 = self.true_poly
+        poly2 = np.polynomial.Polynomial([-2, 5, 3, -1])
+        poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6])
+        ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1)
+
+        P = BarycentricInterpolator(self.xs, ys, axis=0)
+        D = P.derivatives(self.test_xs)
+        for i in range(D.shape[0]):
+            xp_assert_close(D[i],
+                            np.stack((poly1.deriv(i)(self.test_xs),
+                                      poly2.deriv(i)(self.test_xs),
+                                      poly3.deriv(i)(self.test_xs)),
+                                     axis=-1),
+                            atol=1e-12)
+
+    def test_ndim_derivative(self):
+        poly1 = self.true_poly
+        poly2 = np.polynomial.Polynomial([-2, 5, 3, -1])
+        poly3 = np.polynomial.Polynomial([12, -3, 4, -5, 6])
+        ys = np.stack((poly1(self.xs), poly2(self.xs), poly3(self.xs)), axis=-1)
+
+        P = BarycentricInterpolator(self.xs, ys, axis=0)
+        for i in range(P.n):
+            xp_assert_close(P.derivative(self.test_xs, i),
+                            np.stack((poly1.deriv(i)(self.test_xs),
+                                      poly2.deriv(i)(self.test_xs),
+                                      poly3.deriv(i)(self.test_xs)),
+                                     axis=-1),
+                            atol=1e-12)
+
+    def test_delayed(self):
+        P = BarycentricInterpolator(self.xs)
+        P.set_yi(self.ys)
+        assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs))
+
+    def test_append(self):
+        P = BarycentricInterpolator(self.xs[:3], self.ys[:3])
+        P.add_xi(self.xs[3:], self.ys[3:])
+        assert_almost_equal(self.true_poly(self.test_xs), P(self.test_xs))
+
+    def test_vector(self):
+        xs = [0, 1, 2]
+        ys = np.array([[0, 1], [1, 0], [2, 1]])
+        BI = BarycentricInterpolator
+        P = BI(xs, ys)
+        Pi = [BI(xs, ys[:, i]) for i in range(ys.shape[1])]
+        test_xs = np.linspace(-1, 3, 100)
+        assert_almost_equal(P(test_xs),
+                            np.asarray([p(test_xs) for p in Pi]).T)
+
+    def test_shapes_scalarvalue(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+        assert np.shape(P(0)) == ()
+        assert np.shape(P(np.array(0))) == ()
+        assert np.shape(P([0])) == (1,)
+        assert np.shape(P([0, 1])) == (2,)
+
+    def test_shapes_scalarvalue_derivative(self):
+        P = BarycentricInterpolator(self.xs,self.ys)
+        n = P.n
+        assert np.shape(P.derivatives(0)) == (n,)
+        assert np.shape(P.derivatives(np.array(0))) == (n,)
+        assert np.shape(P.derivatives([0])) == (n,1)
+        assert np.shape(P.derivatives([0,1])) == (n,2)
+
+    def test_shapes_vectorvalue(self):
+        P = BarycentricInterpolator(self.xs, np.outer(self.ys, np.arange(3)))
+        assert np.shape(P(0)) == (3,)
+        assert np.shape(P([0])) == (1, 3)
+        assert np.shape(P([0, 1])) == (2, 3)
+
+    def test_shapes_1d_vectorvalue(self):
+        P = BarycentricInterpolator(self.xs, np.outer(self.ys, [1]))
+        assert np.shape(P(0)) == (1,)
+        assert np.shape(P([0])) == (1, 1)
+        assert np.shape(P([0, 1])) == (2, 1)
+
+    def test_shapes_vectorvalue_derivative(self):
+        P = BarycentricInterpolator(self.xs,np.outer(self.ys,np.arange(3)))
+        n = P.n
+        assert np.shape(P.derivatives(0)) == (n, 3)
+        assert np.shape(P.derivatives([0])) == (n, 1, 3)
+        assert np.shape(P.derivatives([0, 1])) == (n, 2, 3)
+
+    def test_wrapper(self):
+        P = BarycentricInterpolator(self.xs, self.ys, rng=1)
+        bi = barycentric_interpolate
+        xp_assert_close(P(self.test_xs), bi(self.xs, self.ys, self.test_xs, rng=1))
+        xp_assert_close(P.derivative(self.test_xs, 2),
+                        bi(self.xs, self.ys, self.test_xs, der=2, rng=1))
+        xp_assert_close(P.derivatives(self.test_xs, 2),
+                        bi(self.xs, self.ys, self.test_xs, der=[0, 1], rng=1))
+
+    def test_int_input(self):
+        x = 1000 * np.arange(1, 11)  # np.prod(x[-1] - x[:-1]) overflows
+        y = np.arange(1, 11)
+        value = barycentric_interpolate(x, y, 1000 * 9.5)
+        assert_almost_equal(value, np.asarray(9.5))
+
+    def test_large_chebyshev(self):
+        # The weights for Chebyshev points of the second kind have analytically
+        # solvable weights. Naive calculation of barycentric weights will fail
+        # for large N because of numerical underflow and overflow. We test
+        # correctness for large N against analytical Chebyshev weights.
+
+        # Without capacity scaling or permutation, n=800 fails,
+        # With just capacity scaling, n=1097 fails
+        # With both capacity scaling and random permutation, n=30000 succeeds
+        n = 1100
+        j = np.arange(n + 1).astype(np.float64)
+        x = np.cos(j * np.pi / n)
+
+        # See page 506 of Berrut and Trefethen 2004 for this formula
+        w = (-1) ** j
+        w[0] *= 0.5
+        w[-1] *= 0.5
+
+        P = BarycentricInterpolator(x)
+
+        # It's okay to have a constant scaling factor in the weights because it
+        # cancels out in the evaluation of the polynomial.
+        factor = P.wi[0]
+        assert_almost_equal(P.wi / (2 * factor), w)
+
+    def test_warning(self):
+        # Test if the divide-by-zero warning is properly ignored when computing
+        # interpolated values equals to interpolation points
+        P = BarycentricInterpolator([0, 1], [1, 2])
+        with np.errstate(divide='raise'):
+            yi = P(P.xi)
+
+        # Check if the interpolated values match the input values
+        # at the nodes
+        assert_almost_equal(yi, P.yi.ravel())
+
+    @pytest.mark.thread_unsafe
+    def test_repeated_node(self):
+        # check that a repeated node raises a ValueError
+        # (computing the weights requires division by xi[i] - xi[j])
+        xis = np.array([0.1, 0.5, 0.9, 0.5])
+        ys = np.array([1, 2, 3, 4])
+        with pytest.raises(ValueError,
+                           match="Interpolation points xi must be distinct."):
+            BarycentricInterpolator(xis, ys)
+
+    @pytest.mark.thread_unsafe
+    def test_concurrency(self):
+        P = BarycentricInterpolator(self.xs, self.ys)
+
+        def worker_fn(_, interp):
+            interp(self.xs)
+
+        _run_concurrent_barrier(10, worker_fn, P)
+
+
+class TestPCHIP:
+    def _make_random(self, npts=20):
+        rng = np.random.RandomState(1234)
+        xi = np.sort(rng.random(npts))
+        yi = rng.random(npts)
+        return pchip(xi, yi), xi, yi
+
+    def test_overshoot(self):
+        # PCHIP should not overshoot
+        p, xi, yi = self._make_random()
+        for i in range(len(xi)-1):
+            x1, x2 = xi[i], xi[i+1]
+            y1, y2 = yi[i], yi[i+1]
+            if y1 > y2:
+                y1, y2 = y2, y1
+            xp = np.linspace(x1, x2, 10)
+            yp = p(xp)
+            assert ((y1 <= yp + 1e-15) & (yp <= y2 + 1e-15)).all()
+
+    def test_monotone(self):
+        # PCHIP should preserve monotonicty
+        p, xi, yi = self._make_random()
+        for i in range(len(xi)-1):
+            x1, x2 = xi[i], xi[i+1]
+            y1, y2 = yi[i], yi[i+1]
+            xp = np.linspace(x1, x2, 10)
+            yp = p(xp)
+            assert ((y2-y1) * (yp[1:] - yp[:1]) > 0).all()
+
+    def test_cast(self):
+        # regression test for integer input data, see gh-3453
+        data = np.array([[0, 4, 12, 27, 47, 60, 79, 87, 99, 100],
+                         [-33, -33, -19, -2, 12, 26, 38, 45, 53, 55]])
+        xx = np.arange(100)
+        curve = pchip(data[0], data[1])(xx)
+
+        data1 = data * 1.0
+        curve1 = pchip(data1[0], data1[1])(xx)
+
+        xp_assert_close(curve, curve1, atol=1e-14, rtol=1e-14)
+
+    def test_nag(self):
+        # Example from NAG C implementation,
+        # http://nag.com/numeric/cl/nagdoc_cl25/html/e01/e01bec.html
+        # suggested in gh-5326 as a smoke test for the way the derivatives
+        # are computed (see also gh-3453)
+        dataStr = '''
+          7.99   0.00000E+0
+          8.09   0.27643E-4
+          8.19   0.43750E-1
+          8.70   0.16918E+0
+          9.20   0.46943E+0
+         10.00   0.94374E+0
+         12.00   0.99864E+0
+         15.00   0.99992E+0
+         20.00   0.99999E+0
+        '''
+        data = np.loadtxt(io.StringIO(dataStr))
+        pch = pchip(data[:,0], data[:,1])
+
+        resultStr = '''
+           7.9900       0.0000
+           9.1910       0.4640
+          10.3920       0.9645
+          11.5930       0.9965
+          12.7940       0.9992
+          13.9950       0.9998
+          15.1960       0.9999
+          16.3970       1.0000
+          17.5980       1.0000
+          18.7990       1.0000
+          20.0000       1.0000
+        '''
+        result = np.loadtxt(io.StringIO(resultStr))
+        xp_assert_close(result[:,1], pch(result[:,0]), rtol=0., atol=5e-5)
+
+    def test_endslopes(self):
+        # this is a smoke test for gh-3453: PCHIP interpolator should not
+        # set edge slopes to zero if the data do not suggest zero edge derivatives
+        x = np.array([0.0, 0.1, 0.25, 0.35])
+        y1 = np.array([279.35, 0.5e3, 1.0e3, 2.5e3])
+        y2 = np.array([279.35, 2.5e3, 1.50e3, 1.0e3])
+        for pp in (pchip(x, y1), pchip(x, y2)):
+            for t in (x[0], x[-1]):
+                assert pp(t, 1) != 0
+
+    @pytest.mark.thread_unsafe
+    def test_all_zeros(self):
+        x = np.arange(10)
+        y = np.zeros_like(x)
+
+        # this should work and not generate any warnings
+        with warnings.catch_warnings():
+            warnings.filterwarnings('error')
+            pch = pchip(x, y)
+
+        xx = np.linspace(0, 9, 101)
+        assert all(pch(xx) == 0.)
+
+    def test_two_points(self):
+        # regression test for gh-6222: pchip([0, 1], [0, 1]) fails because
+        # it tries to use a three-point scheme to estimate edge derivatives,
+        # while there are only two points available.
+        # Instead, it should construct a linear interpolator.
+        x = np.linspace(0, 1, 11)
+        p = pchip([0, 1], [0, 2])
+        xp_assert_close(p(x), 2*x, atol=1e-15)
+
+    def test_pchip_interpolate(self):
+        assert_array_almost_equal(
+            pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=1),
+            np.asarray([1.]))
+
+        assert_array_almost_equal(
+            pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=0),
+            np.asarray([3.5]))
+
+        assert_array_almost_equal(
+            np.asarray(pchip_interpolate([1, 2, 3], [4, 5, 6], [0.5], der=[0, 1])),
+            np.asarray([[3.5], [1]]))
+
+    def test_roots(self):
+        # regression test for gh-6357: .roots method should work
+        p = pchip([0, 1], [-1, 1])
+        r = p.roots()
+        xp_assert_close(r, np.asarray([0.5]))
+
+
+class TestCubicSpline:
+    @staticmethod
+    def check_correctness(S, bc_start='not-a-knot', bc_end='not-a-knot',
+                          tol=1e-14):
+        """Check that spline coefficients satisfy the continuity and boundary
+        conditions."""
+        x = S.x
+        c = S.c
+        dx = np.diff(x)
+        dx = dx.reshape([dx.shape[0]] + [1] * (c.ndim - 2))
+        dxi = dx[:-1]
+
+        # Check C2 continuity.
+        xp_assert_close(c[3, 1:], c[0, :-1] * dxi**3 + c[1, :-1] * dxi**2 +
+                        c[2, :-1] * dxi + c[3, :-1], rtol=tol, atol=tol)
+        xp_assert_close(c[2, 1:], 3 * c[0, :-1] * dxi**2 +
+                        2 * c[1, :-1] * dxi + c[2, :-1], rtol=tol, atol=tol)
+        xp_assert_close(c[1, 1:], 3 * c[0, :-1] * dxi + c[1, :-1],
+                        rtol=tol, atol=tol)
+
+        # Check that we found a parabola, the third derivative is 0.
+        if x.size == 3 and bc_start == 'not-a-knot' and bc_end == 'not-a-knot':
+            xp_assert_close(c[0], np.zeros_like(c[0]), rtol=tol, atol=tol)
+            return
+
+        # Check periodic boundary conditions.
+        if bc_start == 'periodic':
+            xp_assert_close(S(x[0], 0), S(x[-1], 0), rtol=tol, atol=tol)
+            xp_assert_close(S(x[0], 1), S(x[-1], 1), rtol=tol, atol=tol)
+            xp_assert_close(S(x[0], 2), S(x[-1], 2), rtol=tol, atol=tol)
+            return
+
+        # Check other boundary conditions.
+        if bc_start == 'not-a-knot':
+            if x.size == 2:
+                slope = (S(x[1]) - S(x[0])) / dx[0]
+                slope = np.asarray(slope)
+                xp_assert_close(S(x[0], 1), slope, rtol=tol, atol=tol)
+            else:
+                xp_assert_close(c[0, 0], c[0, 1], rtol=tol, atol=tol)
+        elif bc_start == 'clamped':
+            xp_assert_close(
+                S(x[0], 1), np.zeros_like(S(x[0], 1)), rtol=tol, atol=tol)
+        elif bc_start == 'natural':
+            xp_assert_close(
+                S(x[0], 2), np.zeros_like(S(x[0], 2)), rtol=tol, atol=tol)
+        else:
+            order, value = bc_start
+            xp_assert_close(S(x[0], order), np.asarray(value), rtol=tol, atol=tol)
+
+        if bc_end == 'not-a-knot':
+            if x.size == 2:
+                slope = (S(x[1]) - S(x[0])) / dx[0]
+                slope = np.asarray(slope)
+                xp_assert_close(S(x[1], 1), slope, rtol=tol, atol=tol)
+            else:
+                xp_assert_close(c[0, -1], c[0, -2], rtol=tol, atol=tol)
+        elif bc_end == 'clamped':
+            xp_assert_close(S(x[-1], 1), np.zeros_like(S(x[-1], 1)),
+                            rtol=tol, atol=tol)
+        elif bc_end == 'natural':
+            xp_assert_close(S(x[-1], 2), np.zeros_like(S(x[-1], 2)),
+                            rtol=2*tol, atol=2*tol)
+        else:
+            order, value = bc_end
+            xp_assert_close(S(x[-1], order), np.asarray(value), rtol=tol, atol=tol)
+
+    def check_all_bc(self, x, y, axis):
+        deriv_shape = list(y.shape)
+        del deriv_shape[axis]
+        first_deriv = np.empty(deriv_shape)
+        first_deriv.fill(2)
+        second_deriv = np.empty(deriv_shape)
+        second_deriv.fill(-1)
+        bc_all = [
+            'not-a-knot',
+            'natural',
+            'clamped',
+            (1, first_deriv),
+            (2, second_deriv)
+        ]
+        for bc in bc_all[:3]:
+            S = CubicSpline(x, y, axis=axis, bc_type=bc)
+            self.check_correctness(S, bc, bc)
+
+        for bc_start in bc_all:
+            for bc_end in bc_all:
+                S = CubicSpline(x, y, axis=axis, bc_type=(bc_start, bc_end))
+                self.check_correctness(S, bc_start, bc_end, tol=2e-14)
+
+    def test_general(self):
+        x = np.array([-1, 0, 0.5, 2, 4, 4.5, 5.5, 9])
+        y = np.array([0, -0.5, 2, 3, 2.5, 1, 1, 0.5])
+        for n in [2, 3, x.size]:
+            self.check_all_bc(x[:n], y[:n], 0)
+
+            Y = np.empty((2, n, 2))
+            Y[0, :, 0] = y[:n]
+            Y[0, :, 1] = y[:n] - 1
+            Y[1, :, 0] = y[:n] + 2
+            Y[1, :, 1] = y[:n] + 3
+            self.check_all_bc(x[:n], Y, 1)
+
+    def test_periodic(self):
+        for n in [2, 3, 5]:
+            x = np.linspace(0, 2 * np.pi, n)
+            y = np.cos(x)
+            S = CubicSpline(x, y, bc_type='periodic')
+            self.check_correctness(S, 'periodic', 'periodic')
+
+            Y = np.empty((2, n, 2))
+            Y[0, :, 0] = y
+            Y[0, :, 1] = y + 2
+            Y[1, :, 0] = y - 1
+            Y[1, :, 1] = y + 5
+            S = CubicSpline(x, Y, axis=1, bc_type='periodic')
+            self.check_correctness(S, 'periodic', 'periodic')
+
+    def test_periodic_eval(self):
+        x = np.linspace(0, 2 * np.pi, 10)
+        y = np.cos(x)
+        S = CubicSpline(x, y, bc_type='periodic')
+        assert_almost_equal(S(1), S(1 + 2 * np.pi), decimal=15)
+
+    def test_second_derivative_continuity_gh_11758(self):
+        # gh-11758: C2 continuity fail
+        x = np.array([0.9, 1.3, 1.9, 2.1, 2.6, 3.0, 3.9, 4.4, 4.7, 5.0, 6.0,
+                      7.0, 8.0, 9.2, 10.5, 11.3, 11.6, 12.0, 12.6, 13.0, 13.3])
+        y = np.array([1.3, 1.5, 1.85, 2.1, 2.6, 2.7, 2.4, 2.15, 2.05, 2.1,
+                      2.25, 2.3, 2.25, 1.95, 1.4, 0.9, 0.7, 0.6, 0.5, 0.4, 1.3])
+        S = CubicSpline(x, y, bc_type='periodic', extrapolate='periodic')
+        self.check_correctness(S, 'periodic', 'periodic')
+
+    def test_three_points(self):
+        # gh-11758: Fails computing a_m2_m1
+        # In this case, s (first derivatives) could be found manually by solving
+        # system of 2 linear equations. Due to solution of this system,
+        # s[i] = (h1m2 + h2m1) / (h1 + h2), where h1 = x[1] - x[0], h2 = x[2] - x[1],
+        # m1 = (y[1] - y[0]) / h1, m2 = (y[2] - y[1]) / h2
+        x = np.array([1.0, 2.75, 3.0])
+        y = np.array([1.0, 15.0, 1.0])
+        S = CubicSpline(x, y, bc_type='periodic')
+        self.check_correctness(S, 'periodic', 'periodic')
+        xp_assert_close(S.derivative(1)(x), np.array([-48.0, -48.0, -48.0]))
+
+    def test_periodic_three_points_multidim(self):
+        # make sure one multidimensional interpolator does the same as multiple
+        # one-dimensional interpolators
+        x = np.array([0.0, 1.0, 3.0])
+        y = np.array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
+        S = CubicSpline(x, y, bc_type="periodic")
+        self.check_correctness(S, 'periodic', 'periodic')
+        S0 = CubicSpline(x, y[:, 0], bc_type="periodic")
+        S1 = CubicSpline(x, y[:, 1], bc_type="periodic")
+        q = np.linspace(0, 2, 5)
+        xp_assert_close(S(q)[:, 0], S0(q))
+        xp_assert_close(S(q)[:, 1], S1(q))
+
+    def test_dtypes(self):
+        x = np.array([0, 1, 2, 3], dtype=int)
+        y = np.array([-5, 2, 3, 1], dtype=int)
+        S = CubicSpline(x, y)
+        self.check_correctness(S)
+
+        y = np.array([-1+1j, 0.0, 1-1j, 0.5-1.5j])
+        S = CubicSpline(x, y)
+        self.check_correctness(S)
+
+        S = CubicSpline(x, x ** 3, bc_type=("natural", (1, 2j)))
+        self.check_correctness(S, "natural", (1, 2j))
+
+        y = np.array([-5, 2, 3, 1])
+        S = CubicSpline(x, y, bc_type=[(1, 2 + 0.5j), (2, 0.5 - 1j)])
+        self.check_correctness(S, (1, 2 + 0.5j), (2, 0.5 - 1j))
+
+    def test_small_dx(self):
+        rng = np.random.RandomState(0)
+        x = np.sort(rng.uniform(size=100))
+        y = 1e4 + rng.uniform(size=100)
+        S = CubicSpline(x, y)
+        self.check_correctness(S, tol=1e-13)
+
+    def test_incorrect_inputs(self):
+        x = np.array([1, 2, 3, 4])
+        y = np.array([1, 2, 3, 4])
+        xc = np.array([1 + 1j, 2, 3, 4])
+        xn = np.array([np.nan, 2, 3, 4])
+        xo = np.array([2, 1, 3, 4])
+        yn = np.array([np.nan, 2, 3, 4])
+        y3 = [1, 2, 3]
+        x1 = [1]
+        y1 = [1]
+
+        assert_raises(ValueError, CubicSpline, xc, y)
+        assert_raises(ValueError, CubicSpline, xn, y)
+        assert_raises(ValueError, CubicSpline, x, yn)
+        assert_raises(ValueError, CubicSpline, xo, y)
+        assert_raises(ValueError, CubicSpline, x, y3)
+        assert_raises(ValueError, CubicSpline, x[:, np.newaxis], y)
+        assert_raises(ValueError, CubicSpline, x1, y1)
+
+        wrong_bc = [('periodic', 'clamped'),
+                    ((2, 0), (3, 10)),
+                    ((1, 0), ),
+                    (0., 0.),
+                    'not-a-typo']
+
+        for bc_type in wrong_bc:
+            assert_raises(ValueError, CubicSpline, x, y, 0, bc_type, True)
+
+        # Shapes mismatch when giving arbitrary derivative values:
+        Y = np.c_[y, y]
+        bc1 = ('clamped', (1, 0))
+        bc2 = ('clamped', (1, [0, 0, 0]))
+        bc3 = ('clamped', (1, [[0, 0]]))
+        assert_raises(ValueError, CubicSpline, x, Y, 0, bc1, True)
+        assert_raises(ValueError, CubicSpline, x, Y, 0, bc2, True)
+        assert_raises(ValueError, CubicSpline, x, Y, 0, bc3, True)
+
+        # periodic condition, y[-1] must be equal to y[0]:
+        assert_raises(ValueError, CubicSpline, x, y, 0, 'periodic', True)
+
+
+def test_CubicHermiteSpline_correctness():
+    x = [0, 2, 7]
+    y = [-1, 2, 3]
+    dydx = [0, 3, 7]
+    s = CubicHermiteSpline(x, y, dydx)
+    xp_assert_close(s(x), y, check_shape=False, check_dtype=False, rtol=1e-15)
+    xp_assert_close(s(x, 1), dydx, check_shape=False, check_dtype=False, rtol=1e-15)
+
+
+def test_CubicHermiteSpline_error_handling():
+    x = [1, 2, 3]
+    y = [0, 3, 5]
+    dydx = [1, -1, 2, 3]
+    assert_raises(ValueError, CubicHermiteSpline, x, y, dydx)
+
+    dydx_with_nan = [1, 0, np.nan]
+    assert_raises(ValueError, CubicHermiteSpline, x, y, dydx_with_nan)
+
+
+def test_roots_extrapolate_gh_11185():
+    x = np.array([0.001, 0.002])
+    y = np.array([1.66066935e-06, 1.10410807e-06])
+    dy = np.array([-1.60061854, -1.600619])
+    p = CubicHermiteSpline(x, y, dy)
+
+    # roots(extrapolate=True) for a polynomial with a single interval
+    # should return all three real roots
+    r = p.roots(extrapolate=True)
+    assert p.c.shape[1] == 1
+    assert r.size == 3
+
+
+class TestZeroSizeArrays:
+    # regression tests for gh-17241 : CubicSpline et al must not segfault
+    # when y.size == 0
+    # The two methods below are _almost_ the same, but not quite:
+    # one is for objects which have the `bc_type` argument (CubicSpline)
+    # and the other one is for those which do not (Pchip, Akima1D)
+
+    @pytest.mark.parametrize('y', [np.zeros((10, 0, 5)),
+                                   np.zeros((10, 5, 0))])
+    @pytest.mark.parametrize('bc_type',
+                             ['not-a-knot', 'periodic', 'natural', 'clamped'])
+    @pytest.mark.parametrize('axis', [0, 1, 2])
+    @pytest.mark.parametrize('cls', [make_interp_spline, CubicSpline])
+    def test_zero_size(self, cls, y, bc_type, axis):
+        x = np.arange(10)
+        xval = np.arange(3)
+
+        obj = cls(x, y, bc_type=bc_type)
+        assert obj(xval).size == 0
+        assert obj(xval).shape == xval.shape + y.shape[1:]
+
+        # Also check with an explicit non-default axis
+        yt = np.moveaxis(y, 0, axis)  # (10, 0, 5) --> (0, 10, 5) if axis=1 etc
+
+        obj = cls(x, yt, bc_type=bc_type, axis=axis)
+        sh = yt.shape[:axis] + (xval.size, ) + yt.shape[axis+1:]
+        assert obj(xval).size == 0
+        assert obj(xval).shape == sh
+
+    @pytest.mark.parametrize('y', [np.zeros((10, 0, 5)),
+                                   np.zeros((10, 5, 0))])
+    @pytest.mark.parametrize('axis', [0, 1, 2])
+    @pytest.mark.parametrize('cls', [PchipInterpolator, Akima1DInterpolator])
+    def test_zero_size_2(self, cls, y, axis):
+        x = np.arange(10)
+        xval = np.arange(3)
+
+        obj = cls(x, y)
+        assert obj(xval).size == 0
+        assert obj(xval).shape == xval.shape + y.shape[1:]
+
+        # Also check with an explicit non-default axis
+        yt = np.moveaxis(y, 0, axis)  # (10, 0, 5) --> (0, 10, 5) if axis=1 etc
+
+        obj = cls(x, yt, axis=axis)
+        sh = yt.shape[:axis] + (xval.size, ) + yt.shape[axis+1:]
+        assert obj(xval).size == 0
+        assert obj(xval).shape == sh
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbfinterp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbfinterp.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d2759fdee41fa64c09bb00979f10b70e49a2855
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/interpolate/tests/test_rbfinterp.py
@@ -0,0 +1,534 @@
+import pickle
+import pytest
+import numpy as np
+from numpy.linalg import LinAlgError
+from scipy._lib._array_api import xp_assert_close
+from scipy.stats.qmc import Halton
+from scipy.spatial import cKDTree  # type: ignore[attr-defined]
+from scipy.interpolate._rbfinterp import (
+    _AVAILABLE, _SCALE_INVARIANT, _NAME_TO_MIN_DEGREE, _monomial_powers,
+    RBFInterpolator
+    )
+from scipy.interpolate import _rbfinterp_pythran
+from scipy._lib._testutils import _run_concurrent_barrier
+
+
+def _vandermonde(x, degree):
+    # Returns a matrix of monomials that span polynomials with the specified
+    # degree evaluated at x.
+    powers = _monomial_powers(x.shape[1], degree)
+    return _rbfinterp_pythran._polynomial_matrix(x, powers)
+
+
+def _1d_test_function(x):
+    # Test function used in Wahba's "Spline Models for Observational Data".
+    # domain ~= (0, 3), range ~= (-1.0, 0.2)
+    x = x[:, 0]
+    y = 4.26*(np.exp(-x) - 4*np.exp(-2*x) + 3*np.exp(-3*x))
+    return y
+
+
+def _2d_test_function(x):
+    # Franke's test function.
+    # domain ~= (0, 1) X (0, 1), range ~= (0.0, 1.2)
+    x1, x2 = x[:, 0], x[:, 1]
+    term1 = 0.75 * np.exp(-(9*x1-2)**2/4 - (9*x2-2)**2/4)
+    term2 = 0.75 * np.exp(-(9*x1+1)**2/49 - (9*x2+1)/10)
+    term3 = 0.5 * np.exp(-(9*x1-7)**2/4 - (9*x2-3)**2/4)
+    term4 = -0.2 * np.exp(-(9*x1-4)**2 - (9*x2-7)**2)
+    y = term1 + term2 + term3 + term4
+    return y
+
+
+def _is_conditionally_positive_definite(kernel, m):
+    # Tests whether the kernel is conditionally positive definite of order m.
+    # See chapter 7 of Fasshauer's "Meshfree Approximation Methods with
+    # MATLAB".
+    nx = 10
+    ntests = 100
+    for ndim in [1, 2, 3, 4, 5]:
+        # Generate sample points with a Halton sequence to avoid samples that
+        # are too close to each other, which can make the matrix singular.
+        seq = Halton(ndim, scramble=False, seed=np.random.RandomState())
+        for _ in range(ntests):
+            x = 2*seq.random(nx) - 1
+            A = _rbfinterp_pythran._kernel_matrix(x, kernel)
+            P = _vandermonde(x, m - 1)
+            Q, R = np.linalg.qr(P, mode='complete')
+            # Q2 forms a basis spanning the space where P.T.dot(x) = 0. Project
+            # A onto this space, and then see if it is positive definite using
+            # the Cholesky decomposition. If not, then the kernel is not c.p.d.
+            # of order m.
+            Q2 = Q[:, P.shape[1]:]
+            B = Q2.T.dot(A).dot(Q2)
+            try:
+                np.linalg.cholesky(B)
+            except np.linalg.LinAlgError:
+                return False
+
+    return True
+
+
+# Sorting the parametrize arguments is necessary to avoid a parallelization
+# issue described here: https://github.com/pytest-dev/pytest-xdist/issues/432.
+@pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+def test_conditionally_positive_definite(kernel):
+    # Test if each kernel in _AVAILABLE is conditionally positive definite of
+    # order m, where m comes from _NAME_TO_MIN_DEGREE. This is a necessary
+    # condition for the smoothed RBF interpolant to be well-posed in general.
+    m = _NAME_TO_MIN_DEGREE.get(kernel, -1) + 1
+    assert _is_conditionally_positive_definite(kernel, m)
+
+
+class _TestRBFInterpolator:
+    @pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT))
+    def test_scale_invariance_1d(self, kernel):
+        # Verify that the functions in _SCALE_INVARIANT are insensitive to the
+        # shape parameter (when smoothing == 0) in 1d.
+        seq = Halton(1, scramble=False, seed=np.random.RandomState())
+        x = 3*seq.random(50)
+        y = _1d_test_function(x)
+        xitp = 3*seq.random(50)
+        yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp)
+        yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp)
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    @pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT))
+    def test_scale_invariance_2d(self, kernel):
+        # Verify that the functions in _SCALE_INVARIANT are insensitive to the
+        # shape parameter (when smoothing == 0) in 2d.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+        x = seq.random(100)
+        y = _2d_test_function(x)
+        xitp = seq.random(100)
+        yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp)
+        yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp)
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_extreme_domains(self, kernel):
+        # Make sure the interpolant remains numerically stable for very
+        # large/small domains.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+        scale = 1e50
+        shift = 1e55
+
+        x = seq.random(100)
+        y = _2d_test_function(x)
+        xitp = seq.random(100)
+
+        if kernel in _SCALE_INVARIANT:
+            yitp1 = self.build(x, y, kernel=kernel)(xitp)
+            yitp2 = self.build(
+                x*scale + shift, y,
+                kernel=kernel
+                )(xitp*scale + shift)
+        else:
+            yitp1 = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
+            yitp2 = self.build(
+                x*scale + shift, y,
+                epsilon=5.0/scale,
+                kernel=kernel
+                )(xitp*scale + shift)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    def test_polynomial_reproduction(self):
+        # If the observed data comes from a polynomial, then the interpolant
+        # should be able to reproduce the polynomial exactly, provided that
+        # `degree` is sufficiently high.
+        rng = np.random.RandomState(0)
+        seq = Halton(2, scramble=False, seed=rng)
+        degree = 3
+
+        x = seq.random(50)
+        xitp = seq.random(50)
+
+        P = _vandermonde(x, degree)
+        Pitp = _vandermonde(xitp, degree)
+
+        poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
+
+        y = P.dot(poly_coeffs)
+        yitp1 = Pitp.dot(poly_coeffs)
+        yitp2 = self.build(x, y, degree=degree)(xitp)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    @pytest.mark.slow
+    def test_chunking(self, monkeypatch):
+        # If the observed data comes from a polynomial, then the interpolant
+        # should be able to reproduce the polynomial exactly, provided that
+        # `degree` is sufficiently high.
+        rng = np.random.RandomState(0)
+        seq = Halton(2, scramble=False, seed=rng)
+        degree = 3
+
+        largeN = 1000 + 33
+        # this is large to check that chunking of the RBFInterpolator is tested
+        x = seq.random(50)
+        xitp = seq.random(largeN)
+
+        P = _vandermonde(x, degree)
+        Pitp = _vandermonde(xitp, degree)
+
+        poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
+
+        y = P.dot(poly_coeffs)
+        yitp1 = Pitp.dot(poly_coeffs)
+        interp = self.build(x, y, degree=degree)
+        ce_real = interp._chunk_evaluator
+
+        def _chunk_evaluator(*args, **kwargs):
+            kwargs.update(memory_budget=100)
+            return ce_real(*args, **kwargs)
+
+        monkeypatch.setattr(interp, '_chunk_evaluator', _chunk_evaluator)
+        yitp2 = interp(xitp)
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    def test_vector_data(self):
+        # Make sure interpolating a vector field is the same as interpolating
+        # each component separately.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = np.array([_2d_test_function(x),
+                      _2d_test_function(x[:, ::-1])]).T
+
+        yitp1 = self.build(x, y)(xitp)
+        yitp2 = self.build(x, y[:, 0])(xitp)
+        yitp3 = self.build(x, y[:, 1])(xitp)
+
+        xp_assert_close(yitp1[:, 0], yitp2)
+        xp_assert_close(yitp1[:, 1], yitp3)
+
+    def test_complex_data(self):
+        # Interpolating complex input should be the same as interpolating the
+        # real and complex components.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = _2d_test_function(x) + 1j*_2d_test_function(x[:, ::-1])
+
+        yitp1 = self.build(x, y)(xitp)
+        yitp2 = self.build(x, y.real)(xitp)
+        yitp3 = self.build(x, y.imag)(xitp)
+
+        xp_assert_close(yitp1.real, yitp2)
+        xp_assert_close(yitp1.imag, yitp3)
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_interpolation_misfit_1d(self, kernel):
+        # Make sure that each kernel, with its default `degree` and an
+        # appropriate `epsilon`, does a good job at interpolation in 1d.
+        seq = Halton(1, scramble=False, seed=np.random.RandomState())
+
+        x = 3*seq.random(50)
+        xitp = 3*seq.random(50)
+
+        y = _1d_test_function(x)
+        ytrue = _1d_test_function(xitp)
+        yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
+
+        mse = np.mean((yitp - ytrue)**2)
+        assert mse < 1.0e-4
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_interpolation_misfit_2d(self, kernel):
+        # Make sure that each kernel, with its default `degree` and an
+        # appropriate `epsilon`, does a good job at interpolation in 2d.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = _2d_test_function(x)
+        ytrue = _2d_test_function(xitp)
+        yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
+
+        mse = np.mean((yitp - ytrue)**2)
+        assert mse < 2.0e-4
+
+    @pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
+    def test_smoothing_misfit(self, kernel):
+        # Make sure we can find a smoothing parameter for each kernel that
+        # removes a sufficient amount of noise.
+        rng = np.random.RandomState(0)
+        seq = Halton(1, scramble=False, seed=rng)
+
+        noise = 0.2
+        rmse_tol = 0.1
+        smoothing_range = 10**np.linspace(-4, 1, 20)
+
+        x = 3*seq.random(100)
+        y = _1d_test_function(x) + rng.normal(0.0, noise, (100,))
+        ytrue = _1d_test_function(x)
+        rmse_within_tol = False
+        for smoothing in smoothing_range:
+            ysmooth = self.build(
+                x, y,
+                epsilon=1.0,
+                smoothing=smoothing,
+                kernel=kernel)(x)
+            rmse = np.sqrt(np.mean((ysmooth - ytrue)**2))
+            if rmse < rmse_tol:
+                rmse_within_tol = True
+                break
+
+        assert rmse_within_tol
+
+    def test_array_smoothing(self):
+        # Test using an array for `smoothing` to give less weight to a known
+        # outlier.
+        rng = np.random.RandomState(0)
+        seq = Halton(1, scramble=False, seed=rng)
+        degree = 2
+
+        x = seq.random(50)
+        P = _vandermonde(x, degree)
+        poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
+        y = P.dot(poly_coeffs)
+        y_with_outlier = np.copy(y)
+        y_with_outlier[10] += 1.0
+        smoothing = np.zeros((50,))
+        smoothing[10] = 1000.0
+        yitp = self.build(x, y_with_outlier, smoothing=smoothing)(x)
+        # Should be able to reproduce the uncorrupted data almost exactly.
+        xp_assert_close(yitp, y, atol=1e-4)
+
+    def test_inconsistent_x_dimensions_error(self):
+        # ValueError should be raised if the observation points and evaluation
+        # points have a different number of dimensions.
+        y = Halton(2, scramble=False, seed=np.random.RandomState()).random(10)
+        d = _2d_test_function(y)
+        x = Halton(1, scramble=False, seed=np.random.RandomState()).random(10)
+        match = 'Expected the second axis of `x`'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d)(x)
+
+    def test_inconsistent_d_length_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(1)
+        match = 'Expected the first axis of `d`'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d)
+
+    def test_y_not_2d_error(self):
+        y = np.linspace(0, 1, 5)
+        d = np.zeros(5)
+        match = '`y` must be a 2-dimensional array.'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d)
+
+    def test_inconsistent_smoothing_length_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        smoothing = np.ones(1)
+        match = 'Expected `smoothing` to be'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d, smoothing=smoothing)
+
+    def test_invalid_kernel_name_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        match = '`kernel` must be one of'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d, kernel='test')
+
+    def test_epsilon_not_specified_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        for kernel in _AVAILABLE:
+            if kernel in _SCALE_INVARIANT:
+                continue
+
+            match = '`epsilon` must be specified'
+            with pytest.raises(ValueError, match=match):
+                self.build(y, d, kernel=kernel)
+
+    def test_x_not_2d_error(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        x = np.linspace(0, 1, 5)
+        d = np.zeros(5)
+        match = '`x` must be a 2-dimensional array.'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d)(x)
+
+    def test_not_enough_observations_error(self):
+        y = np.linspace(0, 1, 1)[:, None]
+        d = np.zeros(1)
+        match = 'At least 2 data points are required'
+        with pytest.raises(ValueError, match=match):
+            self.build(y, d, kernel='thin_plate_spline')
+
+    @pytest.mark.thread_unsafe
+    def test_degree_warning(self):
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        for kernel, deg in _NAME_TO_MIN_DEGREE.items():
+            # Only test for kernels that its minimum degree is not 0.
+            if deg >= 1:
+                match = f'`degree` should not be below {deg}'
+                with pytest.warns(Warning, match=match):
+                    self.build(y, d, epsilon=1.0, kernel=kernel, degree=deg-1)
+
+    def test_minus_one_degree(self):
+        # Make sure a degree of -1 is accepted without any warning.
+        y = np.linspace(0, 1, 5)[:, None]
+        d = np.zeros(5)
+        for kernel, _ in _NAME_TO_MIN_DEGREE.items():
+            self.build(y, d, epsilon=1.0, kernel=kernel, degree=-1)
+
+    def test_rank_error(self):
+        # An error should be raised when `kernel` is "thin_plate_spline" and
+        # observations are 2-D and collinear.
+        y = np.array([[2.0, 0.0], [1.0, 0.0], [0.0, 0.0]])
+        d = np.array([0.0, 0.0, 0.0])
+        match = 'does not have full column rank'
+        with pytest.raises(LinAlgError, match=match):
+            self.build(y, d, kernel='thin_plate_spline')(y)
+
+    def test_single_point(self):
+        # Make sure interpolation still works with only one point (in 1, 2, and
+        # 3 dimensions).
+        for dim in [1, 2, 3]:
+            y = np.zeros((1, dim))
+            d = np.ones((1,))
+            f = self.build(y, d, kernel='linear')(y)
+            xp_assert_close(d, f)
+
+    def test_pickleable(self):
+        # Make sure we can pickle and unpickle the interpolant without any
+        # changes in the behavior.
+        seq = Halton(1, scramble=False, seed=np.random.RandomState(2305982309))
+
+        x = 3*seq.random(50)
+        xitp = 3*seq.random(50)
+
+        y = _1d_test_function(x)
+
+        interp = self.build(x, y)
+
+        yitp1 = interp(xitp)
+        yitp2 = pickle.loads(pickle.dumps(interp))(xitp)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-16)
+
+
+class TestRBFInterpolatorNeighborsNone(_TestRBFInterpolator):
+    def build(self, *args, **kwargs):
+        return RBFInterpolator(*args, **kwargs)
+
+    def test_smoothing_limit_1d(self):
+        # For large smoothing parameters, the interpolant should approach a
+        # least squares fit of a polynomial with the specified degree.
+        seq = Halton(1, scramble=False, seed=np.random.RandomState())
+
+        degree = 3
+        smoothing = 1e8
+
+        x = 3*seq.random(50)
+        xitp = 3*seq.random(50)
+
+        y = _1d_test_function(x)
+
+        yitp1 = self.build(
+            x, y,
+            degree=degree,
+            smoothing=smoothing
+            )(xitp)
+
+        P = _vandermonde(x, degree)
+        Pitp = _vandermonde(xitp, degree)
+        yitp2 = Pitp.dot(np.linalg.lstsq(P, y, rcond=None)[0])
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    def test_smoothing_limit_2d(self):
+        # For large smoothing parameters, the interpolant should approach a
+        # least squares fit of a polynomial with the specified degree.
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        degree = 3
+        smoothing = 1e8
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = _2d_test_function(x)
+
+        yitp1 = self.build(
+            x, y,
+            degree=degree,
+            smoothing=smoothing
+            )(xitp)
+
+        P = _vandermonde(x, degree)
+        Pitp = _vandermonde(xitp, degree)
+        yitp2 = Pitp.dot(np.linalg.lstsq(P, y, rcond=None)[0])
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+
+class TestRBFInterpolatorNeighbors20(_TestRBFInterpolator):
+    # RBFInterpolator using 20 nearest neighbors.
+    def build(self, *args, **kwargs):
+        return RBFInterpolator(*args, **kwargs, neighbors=20)
+
+    def test_equivalent_to_rbf_interpolator(self):
+        seq = Halton(2, scramble=False, seed=np.random.RandomState())
+
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = _2d_test_function(x)
+
+        yitp1 = self.build(x, y)(xitp)
+
+        yitp2 = []
+        tree = cKDTree(x)
+        for xi in xitp:
+            _, nbr = tree.query(xi, 20)
+            yitp2.append(RBFInterpolator(x[nbr], y[nbr])(xi[None])[0])
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
+
+    def test_concurrency(self):
+        # Check that no segfaults appear with concurrent access to
+        # RbfInterpolator
+        seq = Halton(2, scramble=False, seed=np.random.RandomState(0))
+        x = seq.random(100)
+        xitp = seq.random(100)
+
+        y = _2d_test_function(x)
+
+        interp = self.build(x, y)
+
+        def worker_fn(_, interp, xp):
+            interp(xp)
+
+        _run_concurrent_barrier(10, worker_fn, interp, xitp)
+
+
+class TestRBFInterpolatorNeighborsInf(TestRBFInterpolatorNeighborsNone):
+    # RBFInterpolator using neighbors=np.inf. This should give exactly the same
+    # results as neighbors=None, but it will be slower.
+    def build(self, *args, **kwargs):
+        return RBFInterpolator(*args, **kwargs, neighbors=np.inf)
+
+    def test_equivalent_to_rbf_interpolator(self):
+        seq = Halton(1, scramble=False, seed=np.random.RandomState())
+
+        x = 3*seq.random(50)
+        xitp = 3*seq.random(50)
+
+        y = _1d_test_function(x)
+        yitp1 = self.build(x, y)(xitp)
+        yitp2 = RBFInterpolator(x, y)(xitp)
+
+        xp_assert_close(yitp1, yitp2, atol=1e-8)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__init__.pxd b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..c7c49f9ad8f4c90ee93725fdcdbe73c2e7f5aacd
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__init__.pxd
@@ -0,0 +1 @@
+from scipy.linalg cimport cython_blas, cython_lapack
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9381d7a02c15a3234f38ee4bdee5d12d11d4afd1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__init__.py
@@ -0,0 +1,236 @@
+"""
+====================================
+Linear algebra (:mod:`scipy.linalg`)
+====================================
+
+.. currentmodule:: scipy.linalg
+
+.. toctree::
+   :hidden:
+
+   linalg.blas
+   linalg.cython_blas
+   linalg.cython_lapack
+   linalg.interpolative
+   linalg.lapack
+
+Linear algebra functions.
+
+.. eventually, we should replace the numpy.linalg HTML link with just `numpy.linalg`
+
+.. seealso::
+
+   `numpy.linalg `__
+   for more linear algebra functions. Note that
+   although `scipy.linalg` imports most of them, identically named
+   functions from `scipy.linalg` may offer more or slightly differing
+   functionality.
+
+
+Basics
+======
+
+.. autosummary::
+   :toctree: generated/
+
+   inv - Find the inverse of a square matrix
+   solve - Solve a linear system of equations
+   solve_banded - Solve a banded linear system
+   solveh_banded - Solve a Hermitian or symmetric banded system
+   solve_circulant - Solve a circulant system
+   solve_triangular - Solve a triangular matrix
+   solve_toeplitz - Solve a toeplitz matrix
+   matmul_toeplitz - Multiply a Toeplitz matrix with an array.
+   det - Find the determinant of a square matrix
+   norm - Matrix and vector norm
+   lstsq - Solve a linear least-squares problem
+   pinv - Pseudo-inverse (Moore-Penrose) using lstsq
+   pinvh - Pseudo-inverse of hermitian matrix
+   kron - Kronecker product of two arrays
+   khatri_rao - Khatri-Rao product of two arrays
+   orthogonal_procrustes - Solve an orthogonal Procrustes problem
+   matrix_balance - Balance matrix entries with a similarity transformation
+   subspace_angles - Compute the subspace angles between two matrices
+   bandwidth - Return the lower and upper bandwidth of an array
+   issymmetric - Check if a square 2D array is symmetric
+   ishermitian - Check if a square 2D array is Hermitian
+   LinAlgError
+   LinAlgWarning
+
+Eigenvalue Problems
+===================
+
+.. autosummary::
+   :toctree: generated/
+
+   eig - Find the eigenvalues and eigenvectors of a square matrix
+   eigvals - Find just the eigenvalues of a square matrix
+   eigh - Find the e-vals and e-vectors of a Hermitian or symmetric matrix
+   eigvalsh - Find just the eigenvalues of a Hermitian or symmetric matrix
+   eig_banded - Find the eigenvalues and eigenvectors of a banded matrix
+   eigvals_banded - Find just the eigenvalues of a banded matrix
+   eigh_tridiagonal - Find the eigenvalues and eigenvectors of a tridiagonal matrix
+   eigvalsh_tridiagonal - Find just the eigenvalues of a tridiagonal matrix
+
+Decompositions
+==============
+
+.. autosummary::
+   :toctree: generated/
+
+   lu - LU decomposition of a matrix
+   lu_factor - LU decomposition returning unordered matrix and pivots
+   lu_solve - Solve Ax=b using back substitution with output of lu_factor
+   svd - Singular value decomposition of a matrix
+   svdvals - Singular values of a matrix
+   diagsvd - Construct matrix of singular values from output of svd
+   orth - Construct orthonormal basis for the range of A using svd
+   null_space - Construct orthonormal basis for the null space of A using svd
+   ldl - LDL.T decomposition of a Hermitian or a symmetric matrix.
+   cholesky - Cholesky decomposition of a matrix
+   cholesky_banded - Cholesky decomp. of a sym. or Hermitian banded matrix
+   cho_factor - Cholesky decomposition for use in solving a linear system
+   cho_solve - Solve previously factored linear system
+   cho_solve_banded - Solve previously factored banded linear system
+   polar - Compute the polar decomposition.
+   qr - QR decomposition of a matrix
+   qr_multiply - QR decomposition and multiplication by Q
+   qr_update - Rank k QR update
+   qr_delete - QR downdate on row or column deletion
+   qr_insert - QR update on row or column insertion
+   rq - RQ decomposition of a matrix
+   qz - QZ decomposition of a pair of matrices
+   ordqz - QZ decomposition of a pair of matrices with reordering
+   schur - Schur decomposition of a matrix
+   rsf2csf - Real to complex Schur form
+   hessenberg - Hessenberg form of a matrix
+   cdf2rdf - Complex diagonal form to real diagonal block form
+   cossin - Cosine sine decomposition of a unitary or orthogonal matrix
+
+.. seealso::
+
+   `scipy.linalg.interpolative` -- Interpolative matrix decompositions
+
+
+Matrix Functions
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   expm - Matrix exponential
+   logm - Matrix logarithm
+   cosm - Matrix cosine
+   sinm - Matrix sine
+   tanm - Matrix tangent
+   coshm - Matrix hyperbolic cosine
+   sinhm - Matrix hyperbolic sine
+   tanhm - Matrix hyperbolic tangent
+   signm - Matrix sign
+   sqrtm - Matrix square root
+   funm - Evaluating an arbitrary matrix function
+   expm_frechet - Frechet derivative of the matrix exponential
+   expm_cond - Relative condition number of expm in the Frobenius norm
+   fractional_matrix_power - Fractional matrix power
+
+
+Matrix Equation Solvers
+=======================
+
+.. autosummary::
+   :toctree: generated/
+
+   solve_sylvester - Solve the Sylvester matrix equation
+   solve_continuous_are - Solve the continuous-time algebraic Riccati equation
+   solve_discrete_are - Solve the discrete-time algebraic Riccati equation
+   solve_continuous_lyapunov - Solve the continuous-time Lyapunov equation
+   solve_discrete_lyapunov - Solve the discrete-time Lyapunov equation
+
+
+Sketches and Random Projections
+===============================
+
+.. autosummary::
+   :toctree: generated/
+
+   clarkson_woodruff_transform - Applies the Clarkson Woodruff Sketch (a.k.a CountMin Sketch)
+
+Special Matrices
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   block_diag - Construct a block diagonal matrix from submatrices
+   circulant - Circulant matrix
+   companion - Companion matrix
+   convolution_matrix - Convolution matrix
+   dft - Discrete Fourier transform matrix
+   fiedler - Fiedler matrix
+   fiedler_companion - Fiedler companion matrix
+   hadamard - Hadamard matrix of order 2**n
+   hankel - Hankel matrix
+   helmert - Helmert matrix
+   hilbert - Hilbert matrix
+   invhilbert - Inverse Hilbert matrix
+   leslie - Leslie matrix
+   pascal - Pascal matrix
+   invpascal - Inverse Pascal matrix
+   toeplitz - Toeplitz matrix
+
+Low-level routines
+==================
+
+.. autosummary::
+   :toctree: generated/
+
+   get_blas_funcs
+   get_lapack_funcs
+   find_best_blas_type
+
+.. seealso::
+
+   `scipy.linalg.blas` -- Low-level BLAS functions
+
+   `scipy.linalg.lapack` -- Low-level LAPACK functions
+
+   `scipy.linalg.cython_blas` -- Low-level BLAS functions for Cython
+
+   `scipy.linalg.cython_lapack` -- Low-level LAPACK functions for Cython
+
+"""  # noqa: E501
+
+from ._misc import *
+from ._cythonized_array_utils import *
+from ._basic import *
+from ._decomp import *
+from ._decomp_lu import *
+from ._decomp_ldl import *
+from ._decomp_cholesky import *
+from ._decomp_qr import *
+from ._decomp_qz import *
+from ._decomp_svd import *
+from ._decomp_schur import *
+from ._decomp_polar import *
+from ._matfuncs import *
+from .blas import *
+from .lapack import *
+from ._special_matrices import *
+from ._solvers import *
+from ._procrustes import *
+from ._decomp_update import *
+from ._sketches import *
+from ._decomp_cossin import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+    decomp, decomp_cholesky, decomp_lu, decomp_qr, decomp_svd, decomp_schur,
+    basic, misc, special_matrices, matfuncs,
+)
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5841d361aa6f97f21fbf96d7575016952c906839
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8f234ff4486ce7f766f58f37969b121ffc36f5f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_basic.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..755da5617251edd3a2511ee3b3095132ce70717f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f6ff99160e5c1cacec14d3ccd0ba4ccfa612d01d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cholesky.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2e3704a8777d23fb4ad0193840c7ffb67a0bed6
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_cossin.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..792307c3b5fa00b4575f19b52c8d7e475354f782
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_ldl.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5267523c284acd4edf46041bb741c11b5e1e0a01
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b656cb2de963ad12cfe6e322e23366e902307f9
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_polar.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf15b24540a8a46d55b9d2e4d2fbb0242fa9f0c1
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qr.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7904a88810a766c3c9dbba53b7783fe5de49dd12
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_qz.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2aa5041c4367697bc87f493a8f7cfc5c4b6edd1c
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_schur.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a9c574ab60cd992183381e230fb269440c0976d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_decomp_svd.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f271fa7d08194fbcb23e9473b76f9db8febd50e2
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_expm_frechet.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b8ee3667d54dccdfe0342632f8565e9080520649
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..619f0818ea35a6e2254c9bcd2c1a6b7bad0fdd7a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_matfuncs_sqrtm.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5d4e534dcfcc07c2850906dbe111fbe93541535
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_misc.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7717851bd89d510aa511b936c1838142f1241f61
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_procrustes.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d636c20ad89169a8f15a70aca852721b462a14e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_sketches.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9eb7e543c245d3e5c672f67c82c05f1882c8abfc
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_solvers.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94cbb434ef763b4feddec83df0823dab6c585802
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23814c045075a90012abfd5936452652eb98670b
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/basic.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21780e29fa849a1dd41a137d62bdec92b4d77403
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/blas.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..70591b65dcf4a4959583b5ad0375f45fa4a61817
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3953dc4a1621d78b2cd2f0a502e90816a68aa7d5
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_cholesky.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8008a4384ff2cbe59efc5bf5b1ad40d13821f683
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_lu.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..760d6146d3463f966d80ccb43fddcab63e4bbb7f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_qr.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe9397638609da92af247ecfb7745da774c2323d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_schur.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..222ba4f4bbcf65f6882ec82537abd7d981240e96
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/decomp_svd.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6355060f70862d74144e1cd6601c2280deb93c26
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/interpolative.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30716d9274a692469ee53c2c226f083e068942de
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/lapack.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..190e27ecfe43448618a679ec8e516e4d6e1c7922
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/matfuncs.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9793afe16d109b3b0c21515fe176bfc0b25d7c3c
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/misc.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2a813fea29de9fbc2032d53cd814e5326ef9831
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/__pycache__/special_matrices.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..70841fa80976c62ed7d894d824fdfbbcb4673273
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_basic.py
@@ -0,0 +1,2119 @@
+#
+# Author: Pearu Peterson, March 2002
+#
+# w/ additions by Travis Oliphant, March 2002
+#              and Jake Vanderplas, August 2012
+
+import warnings
+from warnings import warn
+from itertools import product
+import numpy as np
+from numpy import atleast_1d, atleast_2d
+from .lapack import get_lapack_funcs, _compute_lwork
+from ._misc import LinAlgError, _datacopied, LinAlgWarning
+from ._decomp import _asarray_validated
+from . import _decomp, _decomp_svd
+from ._solve_toeplitz import levinson
+from ._cythonized_array_utils import (find_det_from_lu, bandwidth, issymmetric,
+                                      ishermitian)
+
+__all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
+           'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
+           'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz']
+
+
+# The numpy facilities for type-casting checks are too slow for small sized
+# arrays and eat away the time budget for the checkups. Here we set a
+# precomputed dict container of the numpy.can_cast() table.
+
+# It can be used to determine quickly what a dtype can be cast to LAPACK
+# compatible types, i.e., 'float32, float64, complex64, complex128'.
+# Then it can be checked via "casting_dict[arr.dtype.char]"
+lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
+                    for x in np.typecodes['All']}
+
+
+# Linear equations
+def _solve_check(n, info, lamch=None, rcond=None):
+    """ Check arguments during the different steps of the solution phase """
+    if info < 0:
+        raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument.')
+    elif 0 < info:
+        raise LinAlgError('Matrix is singular.')
+
+    if lamch is None:
+        return
+    E = lamch('E')
+    if rcond < E:
+        warn(f'Ill-conditioned matrix (rcond={rcond:.6g}): '
+             'result may not be accurate.',
+             LinAlgWarning, stacklevel=3)
+
+
+def _find_matrix_structure(a):
+    n = a.shape[0]
+    n_below, n_above = bandwidth(a)
+
+    if n_below == n_above == 0:
+        kind = 'diagonal'
+    elif n_above == 0:
+        kind = 'lower triangular'
+    elif n_below == 0:
+        kind = 'upper triangular'
+    elif n_above <= 1 and n_below <= 1 and n > 3:
+        kind = 'tridiagonal'
+    elif np.issubdtype(a.dtype, np.complexfloating) and ishermitian(a):
+        kind = 'hermitian'
+    elif issymmetric(a):
+        kind = 'symmetric'
+    else:
+        kind = 'general'
+
+    return kind, n_below, n_above
+
+
+def solve(a, b, lower=False, overwrite_a=False,
+          overwrite_b=False, check_finite=True, assume_a=None,
+          transposed=False):
+    """
+    Solves the linear equation set ``a @ x == b`` for the unknown ``x``
+    for square `a` matrix.
+
+    If the data matrix is known to be a particular type then supplying the
+    corresponding string to ``assume_a`` key chooses the dedicated solver.
+    The available options are
+
+    ===================  ================================
+     diagonal             'diagonal'
+     tridiagonal          'tridiagonal'
+     banded               'banded'
+     upper triangular     'upper triangular'
+     lower triangular     'lower triangular'
+     symmetric            'symmetric' (or 'sym')
+     hermitian            'hermitian' (or 'her')
+     positive definite    'positive definite' (or 'pos')
+     general              'general' (or 'gen')
+    ===================  ================================
+
+    Parameters
+    ----------
+    a : (N, N) array_like
+        Square input data
+    b : (N, NRHS) array_like
+        Input data for the right hand side.
+    lower : bool, default: False
+        Ignored unless ``assume_a`` is one of ``'sym'``, ``'her'``, or ``'pos'``.
+        If True, the calculation uses only the data in the lower triangle of `a`;
+        entries above the diagonal are ignored. If False (default), the
+        calculation uses only the data in the upper triangle of `a`; entries
+        below the diagonal are ignored.
+    overwrite_a : bool, default: False
+        Allow overwriting data in `a` (may enhance performance).
+    overwrite_b : bool, default: False
+        Allow overwriting data in `b` (may enhance performance).
+    check_finite : bool, default: True
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    assume_a : str, optional
+        Valid entries are described above.
+        If omitted or ``None``, checks are performed to identify structure so the
+        appropriate solver can be called.
+    transposed : bool, default: False
+        If True, solve ``a.T @ x == b``. Raises `NotImplementedError`
+        for complex `a`.
+
+    Returns
+    -------
+    x : (N, NRHS) ndarray
+        The solution array.
+
+    Raises
+    ------
+    ValueError
+        If size mismatches detected or input a is not square.
+    LinAlgError
+        If the matrix is singular.
+    LinAlgWarning
+        If an ill-conditioned input a is detected.
+    NotImplementedError
+        If transposed is True and input a is a complex matrix.
+
+    Notes
+    -----
+    If the input b matrix is a 1-D array with N elements, when supplied
+    together with an NxN input a, it is assumed as a valid column vector
+    despite the apparent size mismatch. This is compatible with the
+    numpy.dot() behavior and the returned result is still 1-D array.
+
+    The general, symmetric, Hermitian and positive definite solutions are
+    obtained via calling ?GESV, ?SYSV, ?HESV, and ?POSV routines of
+    LAPACK respectively.
+
+    The datatype of the arrays define which solver is called regardless
+    of the values. In other words, even when the complex array entries have
+    precisely zero imaginary parts, the complex solver will be called based
+    on the data type of the array.
+
+    Examples
+    --------
+    Given `a` and `b`, solve for `x`:
+
+    >>> import numpy as np
+    >>> a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
+    >>> b = np.array([2, 4, -1])
+    >>> from scipy import linalg
+    >>> x = linalg.solve(a, b)
+    >>> x
+    array([ 2., -2.,  9.])
+    >>> np.dot(a, x) == b
+    array([ True,  True,  True], dtype=bool)
+
+    """
+    # Flags for 1-D or N-D right-hand side
+    b_is_1D = False
+
+    # check finite after determining structure
+    a1 = atleast_2d(_asarray_validated(a, check_finite=False))
+    b1 = atleast_1d(_asarray_validated(b, check_finite=False))
+    a1, b1 = _ensure_dtype_cdsz(a1, b1)
+    n = a1.shape[0]
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    if a1.shape[0] != a1.shape[1]:
+        raise ValueError('Input a needs to be a square matrix.')
+
+    if n != b1.shape[0]:
+        # Last chance to catch 1x1 scalar a and 1-D b arrays
+        if not (n == 1 and b1.size != 0):
+            raise ValueError('Input b has to have same number of rows as '
+                             'input a')
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = solve(np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype)).dtype
+        return np.empty_like(b1, dtype=dt)
+
+    # regularize 1-D b arrays to 2D
+    if b1.ndim == 1:
+        if n == 1:
+            b1 = b1[None, :]
+        else:
+            b1 = b1[:, None]
+        b_is_1D = True
+
+    if assume_a not in {None, 'diagonal', 'tridiagonal', 'banded', 'lower triangular',
+                        'upper triangular', 'symmetric', 'hermitian',
+                        'positive definite', 'general', 'sym', 'her', 'pos', 'gen'}:
+        raise ValueError(f'{assume_a} is not a recognized matrix structure')
+
+    # for a real matrix, describe it as "symmetric", not "hermitian"
+    # (lapack doesn't know what to do with real hermitian matrices)
+    if assume_a in {'hermitian', 'her'} and not np.iscomplexobj(a1):
+        assume_a = 'symmetric'
+
+    n_below, n_above = None, None
+    if assume_a is None:
+        assume_a, n_below, n_above = _find_matrix_structure(a1)
+
+    # Get the correct lamch function.
+    # The LAMCH functions only exists for S and D
+    # So for complex values we have to convert to real/double.
+    if a1.dtype.char in 'fF':  # single precision
+        lamch = get_lapack_funcs('lamch', dtype='f')
+    else:
+        lamch = get_lapack_funcs('lamch', dtype='d')
+
+    # Currently we do not have the other forms of the norm calculators
+    #   lansy, lanpo, lanhe.
+    # However, in any case they only reduce computations slightly...
+    if assume_a == 'diagonal':
+        _matrix_norm = _matrix_norm_diagonal
+    elif assume_a == 'tridiagonal':
+        _matrix_norm = _matrix_norm_tridiagonal
+    elif assume_a in {'lower triangular', 'upper triangular'}:
+        _matrix_norm = _matrix_norm_triangular(assume_a)
+    else:
+        _matrix_norm = _matrix_norm_general
+
+    # Since the I-norm and 1-norm are the same for symmetric matrices
+    # we can collect them all in this one call
+    # Note however, that when issuing 'gen' and form!='none', then
+    # the I-norm should be used
+    if transposed:
+        trans = 1
+        norm = 'I'
+        if np.iscomplexobj(a1):
+            raise NotImplementedError('scipy.linalg.solve can currently '
+                                      'not solve a^T x = b or a^H x = b '
+                                      'for complex matrices.')
+    else:
+        trans = 0
+        norm = '1'
+
+    anorm = _matrix_norm(norm, a1, check_finite)
+
+    info, rcond = 0, np.inf
+
+    # Generalized case 'gesv'
+    if assume_a in {'general', 'gen'}:
+        gecon, getrf, getrs = get_lapack_funcs(('gecon', 'getrf', 'getrs'),
+                                               (a1, b1))
+        lu, ipvt, info = getrf(a1, overwrite_a=overwrite_a)
+        _solve_check(n, info)
+        x, info = getrs(lu, ipvt, b1,
+                        trans=trans, overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = gecon(lu, anorm, norm=norm)
+    # Hermitian case 'hesv'
+    elif assume_a in {'hermitian', 'her'}:
+        hecon, hesv, hesv_lw = get_lapack_funcs(('hecon', 'hesv',
+                                                 'hesv_lwork'), (a1, b1))
+        lwork = _compute_lwork(hesv_lw, n, lower)
+        lu, ipvt, x, info = hesv(a1, b1, lwork=lwork,
+                                 lower=lower,
+                                 overwrite_a=overwrite_a,
+                                 overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = hecon(lu, ipvt, anorm)
+    # Symmetric case 'sysv'
+    elif assume_a in {'symmetric', 'sym'}:
+        sycon, sysv, sysv_lw = get_lapack_funcs(('sycon', 'sysv',
+                                                 'sysv_lwork'), (a1, b1))
+        lwork = _compute_lwork(sysv_lw, n, lower)
+        lu, ipvt, x, info = sysv(a1, b1, lwork=lwork,
+                                 lower=lower,
+                                 overwrite_a=overwrite_a,
+                                 overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = sycon(lu, ipvt, anorm)
+    # Diagonal case
+    elif assume_a == 'diagonal':
+        diag_a = np.diag(a1)
+        x = (b1.T / diag_a).T
+        abs_diag_a = np.abs(diag_a)
+        rcond = abs_diag_a.min() / abs_diag_a.max()
+    # Tri-diagonal case
+    elif assume_a == 'tridiagonal':
+        a1 = a1.T if transposed else a1
+        dl, d, du = np.diag(a1, -1), np.diag(a1, 0), np.diag(a1, 1)
+        _gttrf, _gttrs, _gtcon = get_lapack_funcs(('gttrf', 'gttrs', 'gtcon'), (a1, b1))
+        dl, d, du, du2, ipiv, info = _gttrf(dl, d, du)
+        _solve_check(n, info)
+        x, info = _gttrs(dl, d, du, du2, ipiv, b1, overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = _gtcon(dl, d, du, du2, ipiv, anorm)
+    # Banded case
+    elif assume_a == 'banded':
+        a1, n_below, n_above = ((a1.T, n_above, n_below) if transposed
+                                else (a1, n_below, n_above))
+        n_below, n_above = bandwidth(a1) if n_below is None else (n_below, n_above)
+        ab = _to_banded(n_below, n_above, a1)
+        gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))
+        # Next two lines copied from `solve_banded`
+        a2 = np.zeros((2*n_below + n_above + 1, ab.shape[1]), dtype=gbsv.dtype)
+        a2[n_below:, :] = ab
+        _, _, x, info = gbsv(n_below, n_above, a2, b1,
+                             overwrite_ab=True, overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        # TODO: wrap gbcon and use to get rcond
+    # Triangular case
+    elif assume_a in {'lower triangular', 'upper triangular'}:
+        lower = assume_a == 'lower triangular'
+        x, info = _solve_triangular(a1, b1, lower=lower, overwrite_b=overwrite_b,
+                                    trans=transposed)
+        _solve_check(n, info)
+        _trcon = get_lapack_funcs(('trcon'), (a1, b1))
+        rcond, info = _trcon(a1, uplo='L' if lower else 'U')
+    # Positive definite case 'posv'
+    else:
+        pocon, posv = get_lapack_funcs(('pocon', 'posv'),
+                                       (a1, b1))
+        lu, x, info = posv(a1, b1, lower=lower,
+                           overwrite_a=overwrite_a,
+                           overwrite_b=overwrite_b)
+        _solve_check(n, info)
+        rcond, info = pocon(lu, anorm)
+
+    _solve_check(n, info, lamch, rcond)
+
+    if b_is_1D:
+        x = x.ravel()
+
+    return x
+
+
+def _matrix_norm_diagonal(_, a, check_finite):
+    # Equivalent of dlange for diagonal matrix, assuming
+    # norm is either 'I' or '1' (really just not the Frobenius norm)
+    d = np.diag(a)
+    d = np.asarray_chkfinite(d) if check_finite else d
+    return np.abs(d).max()
+
+
+def _matrix_norm_tridiagonal(norm, a, check_finite):
+    # Equivalent of dlange for tridiagonal matrix, assuming
+    # norm is either 'I' or '1'
+    if norm == 'I':
+        a = a.T
+    # Context to avoid warning before error in cases like -inf + inf
+    with np.errstate(invalid='ignore'):
+        d = np.abs(np.diag(a))
+        d[1:] += np.abs(np.diag(a, 1))
+        d[:-1] += np.abs(np.diag(a, -1))
+    d = np.asarray_chkfinite(d) if check_finite else d
+    return d.max()
+
+
+def _matrix_norm_triangular(structure):
+    def fun(norm, a, check_finite):
+        a = np.asarray_chkfinite(a) if check_finite else a
+        lantr = get_lapack_funcs('lantr', (a,))
+        return lantr(norm, a, 'L' if structure == 'lower triangular' else 'U' )
+    return fun
+
+
+def _matrix_norm_general(norm, a, check_finite):
+    a = np.asarray_chkfinite(a) if check_finite else a
+    lange = get_lapack_funcs('lange', (a,))
+    return lange(norm, a)
+
+
+def _to_banded(n_below, n_above, a):
+    n = a.shape[0]
+    rows = n_above + n_below + 1
+    ab = np.zeros((rows, n), dtype=a.dtype)
+    ab[n_above] = np.diag(a)
+    for i in range(1, n_above + 1):
+        ab[n_above - i, i:] = np.diag(a, i)
+    for i in range(1, n_below + 1):
+        ab[n_above + i, :-i] = np.diag(a, -i)
+    return ab
+
+
+def _ensure_dtype_cdsz(*arrays):
+    # Ensure that the dtype of arrays is one of the standard types
+    # compatible with LAPACK functions (single or double precision
+    # real or complex).
+    dtype = np.result_type(*arrays)
+    if not np.issubdtype(dtype, np.inexact):
+        return (array.astype(np.float64) for array in arrays)
+    complex = np.issubdtype(dtype, np.complexfloating)
+    if np.finfo(dtype).bits <= 32:
+        dtype = np.complex64 if complex else np.float32
+    elif np.finfo(dtype).bits >= 64:
+        dtype = np.complex128 if complex else np.float64
+    return (array.astype(dtype, copy=False) for array in arrays)
+
+
+def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False,
+                     overwrite_b=False, check_finite=True):
+    """
+    Solve the equation ``a x = b`` for `x`, assuming a is a triangular matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A triangular matrix
+    b : (M,) or (M, N) array_like
+        Right-hand side matrix in ``a x = b``
+    lower : bool, optional
+        Use only data contained in the lower triangle of `a`.
+        Default is to use upper triangle.
+    trans : {0, 1, 2, 'N', 'T', 'C'}, optional
+        Type of system to solve:
+
+        ========  =========
+        trans     system
+        ========  =========
+        0 or 'N'  a x  = b
+        1 or 'T'  a^T x = b
+        2 or 'C'  a^H x = b
+        ========  =========
+    unit_diagonal : bool, optional
+        If True, diagonal elements of `a` are assumed to be 1 and
+        will not be referenced.
+    overwrite_b : bool, optional
+        Allow overwriting data in `b` (may enhance performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, N) ndarray
+        Solution to the system ``a x = b``.  Shape of return matches `b`.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular
+
+    Notes
+    -----
+    .. versionadded:: 0.9.0
+
+    Examples
+    --------
+    Solve the lower triangular system a x = b, where::
+
+             [3  0  0  0]       [4]
+        a =  [2  1  0  0]   b = [2]
+             [1  0  1  0]       [4]
+             [1  1  1  1]       [2]
+
+    >>> import numpy as np
+    >>> from scipy.linalg import solve_triangular
+    >>> a = np.array([[3, 0, 0, 0], [2, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]])
+    >>> b = np.array([4, 2, 4, 2])
+    >>> x = solve_triangular(a, b, lower=True)
+    >>> x
+    array([ 1.33333333, -0.66666667,  2.66666667, -1.33333333])
+    >>> a.dot(x)  # Check the result
+    array([ 4.,  2.,  4.,  2.])
+
+    """
+
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    b1 = _asarray_validated(b, check_finite=check_finite)
+
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square matrix')
+
+    if a1.shape[0] != b1.shape[0]:
+        raise ValueError(f'shapes of a {a1.shape} and b {b1.shape} are incompatible')
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt_nonempty = solve_triangular(
+            np.eye(2, dtype=a1.dtype), np.ones(2, dtype=b1.dtype)
+        ).dtype
+        return np.empty_like(b1, dtype=dt_nonempty)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    x, _ = _solve_triangular(a1, b1, trans, lower, unit_diagonal, overwrite_b)
+    return x
+
+
+# solve_triangular without the input validation
+def _solve_triangular(a1, b1, trans=0, lower=False, unit_diagonal=False,
+                      overwrite_b=False):
+
+    trans = {'N': 0, 'T': 1, 'C': 2}.get(trans, trans)
+    trtrs, = get_lapack_funcs(('trtrs',), (a1, b1))
+    if a1.flags.f_contiguous or trans == 2:
+        x, info = trtrs(a1, b1, overwrite_b=overwrite_b, lower=lower,
+                        trans=trans, unitdiag=unit_diagonal)
+    else:
+        # transposed system is solved since trtrs expects Fortran ordering
+        x, info = trtrs(a1.T, b1, overwrite_b=overwrite_b, lower=not lower,
+                        trans=not trans, unitdiag=unit_diagonal)
+
+    if info == 0:
+        return x, info
+    if info > 0:
+        raise LinAlgError("singular matrix: resolution failed at diagonal %d" %
+                          (info-1))
+    raise ValueError('illegal value in %dth argument of internal trtrs' %
+                     (-info))
+
+
+def solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False,
+                 check_finite=True):
+    """
+    Solve the equation a x = b for x, assuming a is banded matrix.
+
+    The matrix a is stored in `ab` using the matrix diagonal ordered form::
+
+        ab[u + i - j, j] == a[i,j]
+
+    Example of `ab` (shape of a is (6,6), `u` =1, `l` =2)::
+
+        *    a01  a12  a23  a34  a45
+        a00  a11  a22  a33  a44  a55
+        a10  a21  a32  a43  a54   *
+        a20  a31  a42  a53   *    *
+
+    Parameters
+    ----------
+    (l, u) : (integer, integer)
+        Number of non-zero lower and upper diagonals
+    ab : (`l` + `u` + 1, M) array_like
+        Banded matrix
+    b : (M,) or (M, K) array_like
+        Right-hand side
+    overwrite_ab : bool, optional
+        Discard data in `ab` (may enhance performance)
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, K) ndarray
+        The solution to the system a x = b. Returned shape depends on the
+        shape of `b`.
+
+    Examples
+    --------
+    Solve the banded system a x = b, where::
+
+            [5  2 -1  0  0]       [0]
+            [1  4  2 -1  0]       [1]
+        a = [0  1  3  2 -1]   b = [2]
+            [0  0  1  2  2]       [2]
+            [0  0  0  1  1]       [3]
+
+    There is one nonzero diagonal below the main diagonal (l = 1), and
+    two above (u = 2). The diagonal banded form of the matrix is::
+
+             [*  * -1 -1 -1]
+        ab = [*  2  2  2  2]
+             [5  4  3  2  1]
+             [1  1  1  1  *]
+
+    >>> import numpy as np
+    >>> from scipy.linalg import solve_banded
+    >>> ab = np.array([[0,  0, -1, -1, -1],
+    ...                [0,  2,  2,  2,  2],
+    ...                [5,  4,  3,  2,  1],
+    ...                [1,  1,  1,  1,  0]])
+    >>> b = np.array([0, 1, 2, 2, 3])
+    >>> x = solve_banded((1, 2), ab, b)
+    >>> x
+    array([-2.37288136,  3.93220339, -4.        ,  4.3559322 , -1.3559322 ])
+
+    """
+
+    a1 = _asarray_validated(ab, check_finite=check_finite, as_inexact=True)
+    b1 = _asarray_validated(b, check_finite=check_finite, as_inexact=True)
+
+    # Validate shapes.
+    if a1.shape[-1] != b1.shape[0]:
+        raise ValueError("shapes of ab and b are not compatible.")
+
+    (nlower, nupper) = l_and_u
+    if nlower + nupper + 1 != a1.shape[0]:
+        raise ValueError("invalid values for the number of lower and upper "
+                         "diagonals: l+u+1 (%d) does not equal ab.shape[0] "
+                         "(%d)" % (nlower + nupper + 1, ab.shape[0]))
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype
+        return np.empty_like(b1, dtype=dt)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+    if a1.shape[-1] == 1:
+        b2 = np.array(b1, copy=(not overwrite_b))
+        # a1.shape[-1] == 1 -> original matrix is 1x1. Typically, the user
+        # will pass u = l = 0 and `a1` will be 1x1. However, the rest of the
+        # function works with unnecessary rows in `a1` as long as
+        # `a1[u + i - j, j] == a[i,j]`. In the 1x1 case, we want i = j = 0,
+        # so the diagonal is in row `u` of `a1`. See gh-8906.
+        b2 /= a1[nupper, 0]
+        return b2
+    if nlower == nupper == 1:
+        overwrite_ab = overwrite_ab or _datacopied(a1, ab)
+        gtsv, = get_lapack_funcs(('gtsv',), (a1, b1))
+        du = a1[0, 1:]
+        d = a1[1, :]
+        dl = a1[2, :-1]
+        du2, d, du, x, info = gtsv(dl, d, du, b1, overwrite_ab, overwrite_ab,
+                                   overwrite_ab, overwrite_b)
+    else:
+        gbsv, = get_lapack_funcs(('gbsv',), (a1, b1))
+        a2 = np.zeros((2*nlower + nupper + 1, a1.shape[1]), dtype=gbsv.dtype)
+        a2[nlower:, :] = a1
+        lu, piv, x, info = gbsv(nlower, nupper, a2, b1, overwrite_ab=True,
+                                overwrite_b=overwrite_b)
+    if info == 0:
+        return x
+    if info > 0:
+        raise LinAlgError("singular matrix")
+    raise ValueError('illegal value in %d-th argument of internal '
+                     'gbsv/gtsv' % -info)
+
+
+def solveh_banded(ab, b, overwrite_ab=False, overwrite_b=False, lower=False,
+                  check_finite=True):
+    """
+    Solve equation a x = b. a is Hermitian positive-definite banded matrix.
+
+    Uses Thomas' Algorithm, which is more efficient than standard LU
+    factorization, but should only be used for Hermitian positive-definite
+    matrices.
+
+    The matrix ``a`` is stored in `ab` either in lower diagonal or upper
+    diagonal ordered form:
+
+        ab[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        ab[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    Example of `ab` (shape of ``a`` is (6, 6), number of upper diagonals,
+    ``u`` =2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Cells marked with * are not used.
+
+    Parameters
+    ----------
+    ab : (``u`` + 1, M) array_like
+        Banded matrix
+    b : (M,) or (M, K) array_like
+        Right-hand side
+    overwrite_ab : bool, optional
+        Discard data in `ab` (may enhance performance)
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance)
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, K) ndarray
+        The solution to the system ``a x = b``. Shape of return matches shape
+        of `b`.
+
+    Notes
+    -----
+    In the case of a non-positive definite matrix ``a``, the solver
+    `solve_banded` may be used.
+
+    Examples
+    --------
+    Solve the banded system ``A x = b``, where::
+
+            [ 4  2 -1  0  0  0]       [1]
+            [ 2  5  2 -1  0  0]       [2]
+        A = [-1  2  6  2 -1  0]   b = [2]
+            [ 0 -1  2  7  2 -1]       [3]
+            [ 0  0 -1  2  8  2]       [3]
+            [ 0  0  0 -1  2  9]       [3]
+
+    >>> import numpy as np
+    >>> from scipy.linalg import solveh_banded
+
+    ``ab`` contains the main diagonal and the nonzero diagonals below the
+    main diagonal. That is, we use the lower form:
+
+    >>> ab = np.array([[ 4,  5,  6,  7, 8, 9],
+    ...                [ 2,  2,  2,  2, 2, 0],
+    ...                [-1, -1, -1, -1, 0, 0]])
+    >>> b = np.array([1, 2, 2, 3, 3, 3])
+    >>> x = solveh_banded(ab, b, lower=True)
+    >>> x
+    array([ 0.03431373,  0.45938375,  0.05602241,  0.47759104,  0.17577031,
+            0.34733894])
+
+
+    Solve the Hermitian banded system ``H x = b``, where::
+
+            [ 8   2-1j   0     0  ]        [ 1  ]
+        H = [2+1j  5     1j    0  ]    b = [1+1j]
+            [ 0   -1j    9   -2-1j]        [1-2j]
+            [ 0    0   -2+1j   6  ]        [ 0  ]
+
+    In this example, we put the upper diagonals in the array ``hb``:
+
+    >>> hb = np.array([[0, 2-1j, 1j, -2-1j],
+    ...                [8,  5,    9,   6  ]])
+    >>> b = np.array([1, 1+1j, 1-2j, 0])
+    >>> x = solveh_banded(hb, b)
+    >>> x
+    array([ 0.07318536-0.02939412j,  0.11877624+0.17696461j,
+            0.10077984-0.23035393j, -0.00479904-0.09358128j])
+
+    """
+    a1 = _asarray_validated(ab, check_finite=check_finite)
+    b1 = _asarray_validated(b, check_finite=check_finite)
+
+    # Validate shapes.
+    if a1.shape[-1] != b1.shape[0]:
+        raise ValueError("shapes of ab and b are not compatible.")
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = solve(np.eye(1, dtype=a1.dtype), np.ones(1, dtype=b1.dtype)).dtype
+        return np.empty_like(b1, dtype=dt)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+    overwrite_ab = overwrite_ab or _datacopied(a1, ab)
+
+    if a1.shape[0] == 2:
+        ptsv, = get_lapack_funcs(('ptsv',), (a1, b1))
+        if lower:
+            d = a1[0, :].real
+            e = a1[1, :-1]
+        else:
+            d = a1[1, :].real
+            e = a1[0, 1:].conj()
+        d, du, x, info = ptsv(d, e, b1, overwrite_ab, overwrite_ab,
+                              overwrite_b)
+    else:
+        pbsv, = get_lapack_funcs(('pbsv',), (a1, b1))
+        c, x, info = pbsv(a1, b1, lower=lower, overwrite_ab=overwrite_ab,
+                          overwrite_b=overwrite_b)
+    if info > 0:
+        raise LinAlgError("%dth leading minor not positive definite" % info)
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of internal '
+                         'pbsv' % -info)
+    return x
+
+
+def solve_toeplitz(c_or_cr, b, check_finite=True):
+    r"""Solve a Toeplitz system using Levinson Recursion
+
+    The Toeplitz matrix has constant diagonals, with c as its first column
+    and r as its first row. If r is not given, ``r == conjugate(c)`` is
+    assumed.
+
+    .. warning::
+
+        Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
+        not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
+        before passing them to `solve_toeplitz`.
+
+    Parameters
+    ----------
+    c_or_cr : array_like or tuple of (array_like, array_like)
+        The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
+        supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
+        real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
+        of the Toeplitz matrix is ``[c[0], r[1:]]``.
+    b : (M,) or (M, K) array_like
+        Right-hand side in ``T x = b``.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (result entirely NaNs) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : (M,) or (M, K) ndarray
+        The solution to the system ``T x = b``. Shape of return matches shape
+        of `b`.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+
+    Notes
+    -----
+    The solution is computed using Levinson-Durbin recursion, which is faster
+    than generic least-squares methods, but can be less numerically stable.
+
+    Examples
+    --------
+    Solve the Toeplitz system T x = b, where::
+
+            [ 1 -1 -2 -3]       [1]
+        T = [ 3  1 -1 -2]   b = [2]
+            [ 6  3  1 -1]       [2]
+            [10  6  3  1]       [5]
+
+    To specify the Toeplitz matrix, only the first column and the first
+    row are needed.
+
+    >>> import numpy as np
+    >>> c = np.array([1, 3, 6, 10])    # First column of T
+    >>> r = np.array([1, -1, -2, -3])  # First row of T
+    >>> b = np.array([1, 2, 2, 5])
+
+    >>> from scipy.linalg import solve_toeplitz, toeplitz
+    >>> x = solve_toeplitz((c, r), b)
+    >>> x
+    array([ 1.66666667, -1.        , -2.66666667,  2.33333333])
+
+    Check the result by creating the full Toeplitz matrix and
+    multiplying it by `x`.  We should get `b`.
+
+    >>> T = toeplitz(c, r)
+    >>> T.dot(x)
+    array([ 1.,  2.,  2.,  5.])
+
+    """
+    # If numerical stability of this algorithm is a problem, a future
+    # developer might consider implementing other O(N^2) Toeplitz solvers,
+    # such as GKO (https://www.jstor.org/stable/2153371) or Bareiss.
+
+    r, c, b, dtype, b_shape = _validate_args_for_toeplitz_ops(
+        c_or_cr, b, check_finite, keep_b_shape=True)
+
+    # accommodate empty arrays
+    if b.size == 0:
+        return np.empty_like(b)
+
+    # Form a 1-D array of values to be used in the matrix, containing a
+    # reversed copy of r[1:], followed by c.
+    vals = np.concatenate((r[-1:0:-1], c))
+    if b is None:
+        raise ValueError('illegal value, `b` is a required argument')
+
+    if b.ndim == 1:
+        x, _ = levinson(vals, np.ascontiguousarray(b))
+    else:
+        x = np.column_stack([levinson(vals, np.ascontiguousarray(b[:, i]))[0]
+                             for i in range(b.shape[1])])
+        x = x.reshape(*b_shape)
+
+    return x
+
+
+def _get_axis_len(aname, a, axis):
+    ax = axis
+    if ax < 0:
+        ax += a.ndim
+    if 0 <= ax < a.ndim:
+        return a.shape[ax]
+    raise ValueError(f"'{aname}axis' entry is out of bounds")
+
+
+def solve_circulant(c, b, singular='raise', tol=None,
+                    caxis=-1, baxis=0, outaxis=0):
+    """Solve C x = b for x, where C is a circulant matrix.
+
+    `C` is the circulant matrix associated with the vector `c`.
+
+    The system is solved by doing division in Fourier space. The
+    calculation is::
+
+        x = ifft(fft(b) / fft(c))
+
+    where `fft` and `ifft` are the fast Fourier transform and its inverse,
+    respectively. For a large vector `c`, this is *much* faster than
+    solving the system with the full circulant matrix.
+
+    Parameters
+    ----------
+    c : array_like
+        The coefficients of the circulant matrix.
+    b : array_like
+        Right-hand side matrix in ``a x = b``.
+    singular : str, optional
+        This argument controls how a near singular circulant matrix is
+        handled.  If `singular` is "raise" and the circulant matrix is
+        near singular, a `LinAlgError` is raised. If `singular` is
+        "lstsq", the least squares solution is returned. Default is "raise".
+    tol : float, optional
+        If any eigenvalue of the circulant matrix has an absolute value
+        that is less than or equal to `tol`, the matrix is considered to be
+        near singular. If not given, `tol` is set to::
+
+            tol = abs_eigs.max() * abs_eigs.size * np.finfo(np.float64).eps
+
+        where `abs_eigs` is the array of absolute values of the eigenvalues
+        of the circulant matrix.
+    caxis : int
+        When `c` has dimension greater than 1, it is viewed as a collection
+        of circulant vectors. In this case, `caxis` is the axis of `c` that
+        holds the vectors of circulant coefficients.
+    baxis : int
+        When `b` has dimension greater than 1, it is viewed as a collection
+        of vectors. In this case, `baxis` is the axis of `b` that holds the
+        right-hand side vectors.
+    outaxis : int
+        When `c` or `b` are multidimensional, the value returned by
+        `solve_circulant` is multidimensional. In this case, `outaxis` is
+        the axis of the result that holds the solution vectors.
+
+    Returns
+    -------
+    x : ndarray
+        Solution to the system ``C x = b``.
+
+    Raises
+    ------
+    LinAlgError
+        If the circulant matrix associated with `c` is near singular.
+
+    See Also
+    --------
+    circulant : circulant matrix
+
+    Notes
+    -----
+    For a 1-D vector `c` with length `m`, and an array `b`
+    with shape ``(m, ...)``,
+
+        solve_circulant(c, b)
+
+    returns the same result as
+
+        solve(circulant(c), b)
+
+    where `solve` and `circulant` are from `scipy.linalg`.
+
+    .. versionadded:: 0.16.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import solve_circulant, solve, circulant, lstsq
+
+    >>> c = np.array([2, 2, 4])
+    >>> b = np.array([1, 2, 3])
+    >>> solve_circulant(c, b)
+    array([ 0.75, -0.25,  0.25])
+
+    Compare that result to solving the system with `scipy.linalg.solve`:
+
+    >>> solve(circulant(c), b)
+    array([ 0.75, -0.25,  0.25])
+
+    A singular example:
+
+    >>> c = np.array([1, 1, 0, 0])
+    >>> b = np.array([1, 2, 3, 4])
+
+    Calling ``solve_circulant(c, b)`` will raise a `LinAlgError`.  For the
+    least square solution, use the option ``singular='lstsq'``:
+
+    >>> solve_circulant(c, b, singular='lstsq')
+    array([ 0.25,  1.25,  2.25,  1.25])
+
+    Compare to `scipy.linalg.lstsq`:
+
+    >>> x, resid, rnk, s = lstsq(circulant(c), b)
+    >>> x
+    array([ 0.25,  1.25,  2.25,  1.25])
+
+    A broadcasting example:
+
+    Suppose we have the vectors of two circulant matrices stored in an array
+    with shape (2, 5), and three `b` vectors stored in an array with shape
+    (3, 5).  For example,
+
+    >>> c = np.array([[1.5, 2, 3, 0, 0], [1, 1, 4, 3, 2]])
+    >>> b = np.arange(15).reshape(-1, 5)
+
+    We want to solve all combinations of circulant matrices and `b` vectors,
+    with the result stored in an array with shape (2, 3, 5). When we
+    disregard the axes of `c` and `b` that hold the vectors of coefficients,
+    the shapes of the collections are (2,) and (3,), respectively, which are
+    not compatible for broadcasting. To have a broadcast result with shape
+    (2, 3), we add a trivial dimension to `c`: ``c[:, np.newaxis, :]`` has
+    shape (2, 1, 5). The last dimension holds the coefficients of the
+    circulant matrices, so when we call `solve_circulant`, we can use the
+    default ``caxis=-1``. The coefficients of the `b` vectors are in the last
+    dimension of the array `b`, so we use ``baxis=-1``. If we use the
+    default `outaxis`, the result will have shape (5, 2, 3), so we'll use
+    ``outaxis=-1`` to put the solution vectors in the last dimension.
+
+    >>> x = solve_circulant(c[:, np.newaxis, :], b, baxis=-1, outaxis=-1)
+    >>> x.shape
+    (2, 3, 5)
+    >>> np.set_printoptions(precision=3)  # For compact output of numbers.
+    >>> x
+    array([[[-0.118,  0.22 ,  1.277, -0.142,  0.302],
+            [ 0.651,  0.989,  2.046,  0.627,  1.072],
+            [ 1.42 ,  1.758,  2.816,  1.396,  1.841]],
+           [[ 0.401,  0.304,  0.694, -0.867,  0.377],
+            [ 0.856,  0.758,  1.149, -0.412,  0.831],
+            [ 1.31 ,  1.213,  1.603,  0.042,  1.286]]])
+
+    Check by solving one pair of `c` and `b` vectors (cf. ``x[1, 1, :]``):
+
+    >>> solve_circulant(c[1], b[1, :])
+    array([ 0.856,  0.758,  1.149, -0.412,  0.831])
+
+    """
+    c = np.atleast_1d(c)
+    nc = _get_axis_len("c", c, caxis)
+    b = np.atleast_1d(b)
+    nb = _get_axis_len("b", b, baxis)
+    if nc != nb:
+        raise ValueError(f'Shapes of c {c.shape} and b {b.shape} are incompatible')
+
+    # accommodate empty arrays
+    if b.size == 0:
+        dt = solve_circulant(np.arange(3, dtype=c.dtype),
+                             np.ones(3, dtype=b.dtype)).dtype
+        return np.empty_like(b, dtype=dt)
+
+    fc = np.fft.fft(np.moveaxis(c, caxis, -1), axis=-1)
+    abs_fc = np.abs(fc)
+    if tol is None:
+        # This is the same tolerance as used in np.linalg.matrix_rank.
+        tol = abs_fc.max(axis=-1) * nc * np.finfo(np.float64).eps
+        if tol.shape != ():
+            tol.shape = tol.shape + (1,)
+        else:
+            tol = np.atleast_1d(tol)
+
+    near_zeros = abs_fc <= tol
+    is_near_singular = np.any(near_zeros)
+    if is_near_singular:
+        if singular == 'raise':
+            raise LinAlgError("near singular circulant matrix.")
+        else:
+            # Replace the small values with 1 to avoid errors in the
+            # division fb/fc below.
+            fc[near_zeros] = 1
+
+    fb = np.fft.fft(np.moveaxis(b, baxis, -1), axis=-1)
+
+    q = fb / fc
+
+    if is_near_singular:
+        # `near_zeros` is a boolean array, same shape as `c`, that is
+        # True where `fc` is (near) zero. `q` is the broadcasted result
+        # of fb / fc, so to set the values of `q` to 0 where `fc` is near
+        # zero, we use a mask that is the broadcast result of an array
+        # of True values shaped like `b` with `near_zeros`.
+        mask = np.ones_like(b, dtype=bool) & near_zeros
+        q[mask] = 0
+
+    x = np.fft.ifft(q, axis=-1)
+    if not (np.iscomplexobj(c) or np.iscomplexobj(b)):
+        x = x.real
+    if outaxis != -1:
+        x = np.moveaxis(x, -1, outaxis)
+    return x
+
+
+# matrix inversion
+def inv(a, overwrite_a=False, check_finite=True):
+    """
+    Compute the inverse of a matrix.
+
+    Parameters
+    ----------
+    a : array_like
+        Square matrix to be inverted.
+    overwrite_a : bool, optional
+        Discard data in `a` (may improve performance). Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    ainv : ndarray
+        Inverse of the matrix `a`.
+
+    Raises
+    ------
+    LinAlgError
+        If `a` is singular.
+    ValueError
+        If `a` is not square, or not 2D.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[1., 2.], [3., 4.]])
+    >>> linalg.inv(a)
+    array([[-2. ,  1. ],
+           [ 1.5, -0.5]])
+    >>> np.dot(a, linalg.inv(a))
+    array([[ 1.,  0.],
+           [ 0.,  1.]])
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square matrix')
+
+    # accommodate empty square matrices
+    if a1.size == 0:
+        dt = inv(np.eye(2, dtype=a1.dtype)).dtype
+        return np.empty_like(a1, dtype=dt)
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    getrf, getri, getri_lwork = get_lapack_funcs(('getrf', 'getri',
+                                                  'getri_lwork'),
+                                                 (a1,))
+    lu, piv, info = getrf(a1, overwrite_a=overwrite_a)
+    if info == 0:
+        lwork = _compute_lwork(getri_lwork, a1.shape[0])
+
+        # XXX: the following line fixes curious SEGFAULT when
+        # benchmarking 500x500 matrix inverse. This seems to
+        # be a bug in LAPACK ?getri routine because if lwork is
+        # minimal (when using lwork[0] instead of lwork[1]) then
+        # all tests pass. Further investigation is required if
+        # more such SEGFAULTs occur.
+        lwork = int(1.01 * lwork)
+        inv_a, info = getri(lu, piv, lwork=lwork, overwrite_lu=1)
+    if info > 0:
+        raise LinAlgError("singular matrix")
+    if info < 0:
+        raise ValueError('illegal value in %d-th argument of internal '
+                         'getrf|getri' % -info)
+    return inv_a
+
+
+# Determinant
+
+def det(a, overwrite_a=False, check_finite=True):
+    """
+    Compute the determinant of a matrix
+
+    The determinant is a scalar that is a function of the associated square
+    matrix coefficients. The determinant value is zero for singular matrices.
+
+    Parameters
+    ----------
+    a : (..., M, M) array_like
+        Input array to compute determinants for.
+    overwrite_a : bool, optional
+        Allow overwriting data in a (may enhance performance).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    det : (...) float or complex
+        Determinant of `a`. For stacked arrays, a scalar is returned for each
+        (m, m) slice in the last two dimensions of the input. For example, an
+        input of shape (p, q, m, m) will produce a result of shape (p, q). If
+        all dimensions are 1 a scalar is returned regardless of ndim.
+
+    Notes
+    -----
+    The determinant is computed by performing an LU factorization of the
+    input with LAPACK routine 'getrf', and then calculating the product of
+    diagonal entries of the U factor.
+
+    Even if the input array is single precision (float32 or complex64), the
+    result will be returned in double precision (float64 or complex128) to
+    prevent overflows.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])  # A singular matrix
+    >>> linalg.det(a)
+    0.0
+    >>> b = np.array([[0,2,3], [4,5,6], [7,8,9]])
+    >>> linalg.det(b)
+    3.0
+    >>> # An array with the shape (3, 2, 2, 2)
+    >>> c = np.array([[[[1., 2.], [3., 4.]],
+    ...                [[5., 6.], [7., 8.]]],
+    ...               [[[9., 10.], [11., 12.]],
+    ...                [[13., 14.], [15., 16.]]],
+    ...               [[[17., 18.], [19., 20.]],
+    ...                [[21., 22.], [23., 24.]]]])
+    >>> linalg.det(c)  # The resulting shape is (3, 2)
+    array([[-2., -2.],
+           [-2., -2.],
+           [-2., -2.]])
+    >>> linalg.det(c[0, 0])  # Confirm the (0, 0) slice, [[1, 2], [3, 4]]
+    -2.0
+    """
+    # The goal is to end up with a writable contiguous array to pass to Cython
+
+    # First we check and make arrays.
+    a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
+    if a1.ndim < 2:
+        raise ValueError('The input array must be at least two-dimensional.')
+    if a1.shape[-1] != a1.shape[-2]:
+        raise ValueError('Last 2 dimensions of the array must be square'
+                         f' but received shape {a1.shape}.')
+
+    # Also check if dtype is LAPACK compatible
+    if a1.dtype.char not in 'fdFD':
+        dtype_char = lapack_cast_dict[a1.dtype.char]
+        if not dtype_char:  # No casting possible
+            raise TypeError(f'The dtype "{a1.dtype.name}" cannot be cast '
+                            'to float(32, 64) or complex(64, 128).')
+
+        a1 = a1.astype(dtype_char[0])  # makes a copy, free to scratch
+        overwrite_a = True
+
+    # Empty array has determinant 1 because math.
+    if min(*a1.shape) == 0:
+        dtyp = np.float64 if a1.dtype.char not in 'FD' else np.complex128
+        if a1.ndim == 2:
+            return dtyp(1.0)
+        else:
+            return np.ones(shape=a1.shape[:-2], dtype=dtyp)
+
+    # Scalar case
+    if a1.shape[-2:] == (1, 1):
+        a1 = a1[..., 0, 0]
+        if a1.ndim == 0:
+            a1 = a1[()]
+        # Convert float32 to float64, and complex64 to complex128.
+        if a1.dtype.char in 'dD':
+            return a1
+        return a1.astype('d') if a1.dtype.char == 'f' else a1.astype('D')
+
+    # Then check overwrite permission
+    if not _datacopied(a1, a):  # "a"  still alive through "a1"
+        if not overwrite_a:
+            # Data belongs to "a" so make a copy
+            a1 = a1.copy(order='C')
+        #  else: Do nothing we'll use "a" if possible
+    # else:  a1 has its own data thus free to scratch
+
+    # Then layout checks, might happen that overwrite is allowed but original
+    # array was read-only or non-C-contiguous.
+    if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']):
+        a1 = a1.copy(order='C')
+
+    if a1.ndim == 2:
+        det = find_det_from_lu(a1)
+        # Convert float, complex to NumPy scalars
+        return (np.float64(det) if np.isrealobj(det) else np.complex128(det))
+
+    # loop over the stacked array, and avoid overflows for single precision
+    # Cf. np.linalg.det(np.diag([1e+38, 1e+38]).astype(np.float32))
+    dtype_char = a1.dtype.char
+    if dtype_char in 'fF':
+        dtype_char = 'd' if dtype_char.islower() else 'D'
+
+    det = np.empty(a1.shape[:-2], dtype=dtype_char)
+    for ind in product(*[range(x) for x in a1.shape[:-2]]):
+        det[ind] = find_det_from_lu(a1[ind])
+    return det
+
+
+# Linear Least Squares
+def lstsq(a, b, cond=None, overwrite_a=False, overwrite_b=False,
+          check_finite=True, lapack_driver=None):
+    """
+    Compute least-squares solution to equation Ax = b.
+
+    Compute a vector x such that the 2-norm ``|b - A x|`` is minimized.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Left-hand side array
+    b : (M,) or (M, K) array_like
+        Right hand side array
+    cond : float, optional
+        Cutoff for 'small' singular values; used to determine effective
+        rank of a. Singular values smaller than
+        ``cond * largest_singular_value`` are considered zero.
+    overwrite_a : bool, optional
+        Discard data in `a` (may enhance performance). Default is False.
+    overwrite_b : bool, optional
+        Discard data in `b` (may enhance performance). Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    lapack_driver : str, optional
+        Which LAPACK driver is used to solve the least-squares problem.
+        Options are ``'gelsd'``, ``'gelsy'``, ``'gelss'``. Default
+        (``'gelsd'``) is a good choice.  However, ``'gelsy'`` can be slightly
+        faster on many problems.  ``'gelss'`` was used historically.  It is
+        generally slow but uses less memory.
+
+        .. versionadded:: 0.17.0
+
+    Returns
+    -------
+    x : (N,) or (N, K) ndarray
+        Least-squares solution.
+    residues : (K,) ndarray or float
+        Square of the 2-norm for each column in ``b - a x``, if ``M > N`` and
+        ``rank(A) == n`` (returns a scalar if ``b`` is 1-D). Otherwise a
+        (0,)-shaped array is returned.
+    rank : int
+        Effective rank of `a`.
+    s : (min(M, N),) ndarray or None
+        Singular values of `a`. The condition number of ``a`` is
+        ``s[0] / s[-1]``.
+
+    Raises
+    ------
+    LinAlgError
+        If computation does not converge.
+
+    ValueError
+        When parameters are not compatible.
+
+    See Also
+    --------
+    scipy.optimize.nnls : linear least squares with non-negativity constraint
+
+    Notes
+    -----
+    When ``'gelsy'`` is used as a driver, `residues` is set to a (0,)-shaped
+    array and `s` is always ``None``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import lstsq
+    >>> import matplotlib.pyplot as plt
+
+    Suppose we have the following data:
+
+    >>> x = np.array([1, 2.5, 3.5, 4, 5, 7, 8.5])
+    >>> y = np.array([0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6])
+
+    We want to fit a quadratic polynomial of the form ``y = a + b*x**2``
+    to this data.  We first form the "design matrix" M, with a constant
+    column of 1s and a column containing ``x**2``:
+
+    >>> M = x[:, np.newaxis]**[0, 2]
+    >>> M
+    array([[  1.  ,   1.  ],
+           [  1.  ,   6.25],
+           [  1.  ,  12.25],
+           [  1.  ,  16.  ],
+           [  1.  ,  25.  ],
+           [  1.  ,  49.  ],
+           [  1.  ,  72.25]])
+
+    We want to find the least-squares solution to ``M.dot(p) = y``,
+    where ``p`` is a vector with length 2 that holds the parameters
+    ``a`` and ``b``.
+
+    >>> p, res, rnk, s = lstsq(M, y)
+    >>> p
+    array([ 0.20925829,  0.12013861])
+
+    Plot the data and the fitted curve.
+
+    >>> plt.plot(x, y, 'o', label='data')
+    >>> xx = np.linspace(0, 9, 101)
+    >>> yy = p[0] + p[1]*xx**2
+    >>> plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$')
+    >>> plt.xlabel('x')
+    >>> plt.ylabel('y')
+    >>> plt.legend(framealpha=1, shadow=True)
+    >>> plt.grid(alpha=0.25)
+    >>> plt.show()
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    b1 = _asarray_validated(b, check_finite=check_finite)
+    if len(a1.shape) != 2:
+        raise ValueError('Input array a should be 2D')
+    m, n = a1.shape
+    if len(b1.shape) == 2:
+        nrhs = b1.shape[1]
+    else:
+        nrhs = 1
+    if m != b1.shape[0]:
+        raise ValueError('Shape mismatch: a and b should have the same number'
+                         f' of rows ({m} != {b1.shape[0]}).')
+    if m == 0 or n == 0:  # Zero-sized problem, confuses LAPACK
+        x = np.zeros((n,) + b1.shape[1:], dtype=np.common_type(a1, b1))
+        if n == 0:
+            residues = np.linalg.norm(b1, axis=0)**2
+        else:
+            residues = np.empty((0,))
+        return x, residues, 0, np.empty((0,))
+
+    driver = lapack_driver
+    if driver is None:
+        driver = lstsq.default_lapack_driver
+    if driver not in ('gelsd', 'gelsy', 'gelss'):
+        raise ValueError(f'LAPACK driver "{driver}" is not found')
+
+    lapack_func, lapack_lwork = get_lapack_funcs((driver,
+                                                 f'{driver}_lwork'),
+                                                 (a1, b1))
+    real_data = True if (lapack_func.dtype.kind == 'f') else False
+
+    if m < n:
+        # need to extend b matrix as it will be filled with
+        # a larger solution matrix
+        if len(b1.shape) == 2:
+            b2 = np.zeros((n, nrhs), dtype=lapack_func.dtype)
+            b2[:m, :] = b1
+        else:
+            b2 = np.zeros(n, dtype=lapack_func.dtype)
+            b2[:m] = b1
+        b1 = b2
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    if cond is None:
+        cond = np.finfo(lapack_func.dtype).eps
+
+    if driver in ('gelss', 'gelsd'):
+        if driver == 'gelss':
+            lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
+            v, x, s, rank, work, info = lapack_func(a1, b1, cond, lwork,
+                                                    overwrite_a=overwrite_a,
+                                                    overwrite_b=overwrite_b)
+
+        elif driver == 'gelsd':
+            if real_data:
+                lwork, iwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
+                x, s, rank, info = lapack_func(a1, b1, lwork,
+                                               iwork, cond, False, False)
+            else:  # complex data
+                lwork, rwork, iwork = _compute_lwork(lapack_lwork, m, n,
+                                                     nrhs, cond)
+                x, s, rank, info = lapack_func(a1, b1, lwork, rwork, iwork,
+                                               cond, False, False)
+        if info > 0:
+            raise LinAlgError("SVD did not converge in Linear Least Squares")
+        if info < 0:
+            raise ValueError('illegal value in %d-th argument of internal %s'
+                             % (-info, lapack_driver))
+        resids = np.asarray([], dtype=x.dtype)
+        if m > n:
+            x1 = x[:n]
+            if rank == n:
+                resids = np.sum(np.abs(x[n:])**2, axis=0)
+            x = x1
+        return x, resids, rank, s
+
+    elif driver == 'gelsy':
+        lwork = _compute_lwork(lapack_lwork, m, n, nrhs, cond)
+        jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
+        v, x, j, rank, info = lapack_func(a1, b1, jptv, cond,
+                                          lwork, False, False)
+        if info < 0:
+            raise ValueError("illegal value in %d-th argument of internal "
+                             "gelsy" % -info)
+        if m > n:
+            x1 = x[:n]
+            x = x1
+        return x, np.array([], x.dtype), rank, None
+
+
+lstsq.default_lapack_driver = 'gelsd'
+
+
+def pinv(a, *, atol=None, rtol=None, return_rank=False, check_finite=True):
+    """
+    Compute the (Moore-Penrose) pseudo-inverse of a matrix.
+
+    Calculate a generalized inverse of a matrix using its
+    singular-value decomposition ``U @ S @ V`` in the economy mode and picking
+    up only the columns/rows that are associated with significant singular
+    values.
+
+    If ``s`` is the maximum singular value of ``a``, then the
+    significance cut-off value is determined by ``atol + rtol * s``. Any
+    singular value below this value is assumed insignificant.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to be pseudo-inverted.
+    atol : float, optional
+        Absolute threshold term, default value is 0.
+
+        .. versionadded:: 1.7.0
+
+    rtol : float, optional
+        Relative threshold term, default value is ``max(M, N) * eps`` where
+        ``eps`` is the machine precision value of the datatype of ``a``.
+
+        .. versionadded:: 1.7.0
+
+    return_rank : bool, optional
+        If True, return the effective rank of the matrix.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    B : (N, M) ndarray
+        The pseudo-inverse of matrix `a`.
+    rank : int
+        The effective rank of the matrix. Returned if `return_rank` is True.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    pinvh : Moore-Penrose pseudoinverse of a hermitian matrix.
+
+    Notes
+    -----
+    If ``A`` is invertible then the Moore-Penrose pseudoinverse is exactly
+    the inverse of ``A`` [1]_. If ``A`` is not invertible then the
+    Moore-Penrose pseudoinverse computes the ``x`` solution to ``Ax = b`` such
+    that ``||Ax - b||`` is minimized [1]_.
+
+    References
+    ----------
+    .. [1] Penrose, R. (1956). On best approximate solutions of linear matrix
+           equations. Mathematical Proceedings of the Cambridge Philosophical
+           Society, 52(1), 17-19. doi:10.1017/S0305004100030929
+
+    Examples
+    --------
+
+    Given an ``m x n`` matrix ``A`` and an ``n x m`` matrix ``B`` the four
+    Moore-Penrose conditions are:
+
+    1. ``ABA = A`` (``B`` is a generalized inverse of ``A``),
+    2. ``BAB = B`` (``A`` is a generalized inverse of ``B``),
+    3. ``(AB)* = AB`` (``AB`` is hermitian),
+    4. ``(BA)* = BA`` (``BA`` is hermitian) [1]_.
+
+    Here, ``A*`` denotes the conjugate transpose. The Moore-Penrose
+    pseudoinverse is a unique ``B`` that satisfies all four of these
+    conditions and exists for any ``A``. Note that, unlike the standard
+    matrix inverse, ``A`` does not have to be a square matrix or have
+    linearly independent columns/rows.
+
+    As an example, we can calculate the Moore-Penrose pseudoinverse of a
+    random non-square matrix and verify it satisfies the four conditions.
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> A = rng.standard_normal((9, 6))
+    >>> B = linalg.pinv(A)
+    >>> np.allclose(A @ B @ A, A)  # Condition 1
+    True
+    >>> np.allclose(B @ A @ B, B)  # Condition 2
+    True
+    >>> np.allclose((A @ B).conj().T, A @ B)  # Condition 3
+    True
+    >>> np.allclose((B @ A).conj().T, B @ A)  # Condition 4
+    True
+
+    """
+    a = _asarray_validated(a, check_finite=check_finite)
+    u, s, vh = _decomp_svd.svd(a, full_matrices=False, check_finite=False)
+    t = u.dtype.char.lower()
+    maxS = np.max(s, initial=0.)
+
+    atol = 0. if atol is None else atol
+    rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol
+
+    if (atol < 0.) or (rtol < 0.):
+        raise ValueError("atol and rtol values must be positive.")
+
+    val = atol + maxS * rtol
+    rank = np.sum(s > val)
+
+    u = u[:, :rank]
+    u /= s[:rank]
+    B = (u @ vh[:rank]).conj().T
+
+    if return_rank:
+        return B, rank
+    else:
+        return B
+
+
+def pinvh(a, atol=None, rtol=None, lower=True, return_rank=False,
+          check_finite=True):
+    """
+    Compute the (Moore-Penrose) pseudo-inverse of a Hermitian matrix.
+
+    Calculate a generalized inverse of a complex Hermitian/real symmetric
+    matrix using its eigenvalue decomposition and including all eigenvalues
+    with 'large' absolute value.
+
+    Parameters
+    ----------
+    a : (N, N) array_like
+        Real symmetric or complex hermetian matrix to be pseudo-inverted
+
+    atol : float, optional
+        Absolute threshold term, default value is 0.
+
+        .. versionadded:: 1.7.0
+
+    rtol : float, optional
+        Relative threshold term, default value is ``N * eps`` where
+        ``eps`` is the machine precision value of the datatype of ``a``.
+
+        .. versionadded:: 1.7.0
+
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower or upper
+        triangle of `a`. (Default: lower)
+    return_rank : bool, optional
+        If True, return the effective rank of the matrix.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    B : (N, N) ndarray
+        The pseudo-inverse of matrix `a`.
+    rank : int
+        The effective rank of the matrix.  Returned if `return_rank` is True.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue algorithm does not converge.
+
+    See Also
+    --------
+    pinv : Moore-Penrose pseudoinverse of a matrix.
+
+    Examples
+    --------
+
+    For a more detailed example see `pinv`.
+
+    >>> import numpy as np
+    >>> from scipy.linalg import pinvh
+    >>> rng = np.random.default_rng()
+    >>> a = rng.standard_normal((9, 6))
+    >>> a = np.dot(a, a.T)
+    >>> B = pinvh(a)
+    >>> np.allclose(a, a @ B @ a)
+    True
+    >>> np.allclose(B, B @ a @ B)
+    True
+
+    """
+    a = _asarray_validated(a, check_finite=check_finite)
+    s, u = _decomp.eigh(a, lower=lower, check_finite=False, driver='ev')
+    t = u.dtype.char.lower()
+    maxS = np.max(np.abs(s), initial=0.)
+
+    atol = 0. if atol is None else atol
+    rtol = max(a.shape) * np.finfo(t).eps if (rtol is None) else rtol
+
+    if (atol < 0.) or (rtol < 0.):
+        raise ValueError("atol and rtol values must be positive.")
+
+    val = atol + maxS * rtol
+    above_cutoff = (abs(s) > val)
+
+    psigma_diag = 1.0 / s[above_cutoff]
+    u = u[:, above_cutoff]
+
+    B = (u * psigma_diag) @ u.conj().T
+
+    if return_rank:
+        return B, len(psigma_diag)
+    else:
+        return B
+
+
+def matrix_balance(A, permute=True, scale=True, separate=False,
+                   overwrite_a=False):
+    """
+    Compute a diagonal similarity transformation for row/column balancing.
+
+    The balancing tries to equalize the row and column 1-norms by applying
+    a similarity transformation such that the magnitude variation of the
+    matrix entries is reflected to the scaling matrices.
+
+    Moreover, if enabled, the matrix is first permuted to isolate the upper
+    triangular parts of the matrix and, again if scaling is also enabled,
+    only the remaining subblocks are subjected to scaling.
+
+    The balanced matrix satisfies the following equality
+
+    .. math::
+
+                        B = T^{-1} A T
+
+    The scaling coefficients are approximated to the nearest power of 2
+    to avoid round-off errors.
+
+    Parameters
+    ----------
+    A : (n, n) array_like
+        Square data matrix for the balancing.
+    permute : bool, optional
+        The selector to define whether permutation of A is also performed
+        prior to scaling.
+    scale : bool, optional
+        The selector to turn on and off the scaling. If False, the matrix
+        will not be scaled.
+    separate : bool, optional
+        This switches from returning a full matrix of the transformation
+        to a tuple of two separate 1-D permutation and scaling arrays.
+    overwrite_a : bool, optional
+        This is passed to xGEBAL directly. Essentially, overwrites the result
+        to the data. It might increase the space efficiency. See LAPACK manual
+        for details. This is False by default.
+
+    Returns
+    -------
+    B : (n, n) ndarray
+        Balanced matrix
+    T : (n, n) ndarray
+        A possibly permuted diagonal matrix whose nonzero entries are
+        integer powers of 2 to avoid numerical truncation errors.
+    scale, perm : (n,) ndarray
+        If ``separate`` keyword is set to True then instead of the array
+        ``T`` above, the scaling and the permutation vectors are given
+        separately as a tuple without allocating the full array ``T``.
+
+    Notes
+    -----
+    This algorithm is particularly useful for eigenvalue and matrix
+    decompositions and in many cases it is already called by various
+    LAPACK routines.
+
+    The algorithm is based on the well-known technique of [1]_ and has
+    been modified to account for special cases. See [2]_ for details
+    which have been implemented since LAPACK v3.5.0. Before this version
+    there are corner cases where balancing can actually worsen the
+    conditioning. See [3]_ for such examples.
+
+    The code is a wrapper around LAPACK's xGEBAL routine family for matrix
+    balancing.
+
+    .. versionadded:: 0.19.0
+
+    References
+    ----------
+    .. [1] B.N. Parlett and C. Reinsch, "Balancing a Matrix for
+       Calculation of Eigenvalues and Eigenvectors", Numerische Mathematik,
+       Vol.13(4), 1969, :doi:`10.1007/BF02165404`
+    .. [2] R. James, J. Langou, B.R. Lowery, "On matrix balancing and
+       eigenvector computation", 2014, :arxiv:`1401.5766`
+    .. [3] D.S. Watkins. A case where balancing is harmful.
+       Electron. Trans. Numer. Anal, Vol.23, 2006.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> x = np.array([[1,2,0], [9,1,0.01], [1,2,10*np.pi]])
+
+    >>> y, permscale = linalg.matrix_balance(x)
+    >>> np.abs(x).sum(axis=0) / np.abs(x).sum(axis=1)
+    array([ 3.66666667,  0.4995005 ,  0.91312162])
+
+    >>> np.abs(y).sum(axis=0) / np.abs(y).sum(axis=1)
+    array([ 1.2       ,  1.27041742,  0.92658316])  # may vary
+
+    >>> permscale  # only powers of 2 (0.5 == 2^(-1))
+    array([[  0.5,   0. ,  0. ],  # may vary
+           [  0. ,   1. ,  0. ],
+           [  0. ,   0. ,  1. ]])
+
+    """
+
+    A = np.atleast_2d(_asarray_validated(A, check_finite=True))
+
+    if not np.equal(*A.shape):
+        raise ValueError('The data matrix for balancing should be square.')
+
+    # accommodate empty arrays
+    if A.size == 0:
+        b_n, t_n = matrix_balance(np.eye(2, dtype=A.dtype))
+        B = np.empty_like(A, dtype=b_n.dtype)
+        if separate:
+            scaling = np.ones_like(A, shape=len(A))
+            perm = np.arange(len(A))
+            return B, (scaling, perm)
+        return B, np.empty_like(A, dtype=t_n.dtype)
+
+    gebal = get_lapack_funcs(('gebal'), (A,))
+    B, lo, hi, ps, info = gebal(A, scale=scale, permute=permute,
+                                overwrite_a=overwrite_a)
+
+    if info < 0:
+        raise ValueError('xGEBAL exited with the internal error '
+                         f'"illegal value in argument number {-info}.". See '
+                         'LAPACK documentation for the xGEBAL error codes.')
+
+    # Separate the permutations from the scalings and then convert to int
+    scaling = np.ones_like(ps, dtype=float)
+    scaling[lo:hi+1] = ps[lo:hi+1]
+
+    # gebal uses 1-indexing
+    ps = ps.astype(int, copy=False) - 1
+    n = A.shape[0]
+    perm = np.arange(n)
+
+    # LAPACK permutes with the ordering n --> hi, then 0--> lo
+    if hi < n:
+        for ind, x in enumerate(ps[hi+1:][::-1], 1):
+            if n-ind == x:
+                continue
+            perm[[x, n-ind]] = perm[[n-ind, x]]
+
+    if lo > 0:
+        for ind, x in enumerate(ps[:lo]):
+            if ind == x:
+                continue
+            perm[[x, ind]] = perm[[ind, x]]
+
+    if separate:
+        return B, (scaling, perm)
+
+    # get the inverse permutation
+    iperm = np.empty_like(perm)
+    iperm[perm] = np.arange(n)
+
+    return B, np.diag(scaling)[iperm, :]
+
+
+def _validate_args_for_toeplitz_ops(c_or_cr, b, check_finite, keep_b_shape,
+                                    enforce_square=True):
+    """Validate arguments and format inputs for toeplitz functions
+
+    Parameters
+    ----------
+    c_or_cr : array_like or tuple of (array_like, array_like)
+        The vector ``c``, or a tuple of arrays (``c``, ``r``). Whatever the
+        actual shape of ``c``, it will be converted to a 1-D array. If not
+        supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
+        real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
+        of the Toeplitz matrix is ``[c[0], r[1:]]``. Whatever the actual shape
+        of ``r``, it will be converted to a 1-D array.
+    b : (M,) or (M, K) array_like
+        Right-hand side in ``T x = b``.
+    check_finite : bool
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (result entirely NaNs) if the inputs do contain infinities or NaNs.
+    keep_b_shape : bool
+        Whether to convert a (M,) dimensional b into a (M, 1) dimensional
+        matrix.
+    enforce_square : bool, optional
+        If True (default), this verifies that the Toeplitz matrix is square.
+
+    Returns
+    -------
+    r : array
+        1d array corresponding to the first row of the Toeplitz matrix.
+    c: array
+        1d array corresponding to the first column of the Toeplitz matrix.
+    b: array
+        (M,), (M, 1) or (M, K) dimensional array, post validation,
+        corresponding to ``b``.
+    dtype: numpy datatype
+        ``dtype`` stores the datatype of ``r``, ``c`` and ``b``. If any of
+        ``r``, ``c`` or ``b`` are complex, ``dtype`` is ``np.complex128``,
+        otherwise, it is ``np.float``.
+    b_shape: tuple
+        Shape of ``b`` after passing it through ``_asarray_validated``.
+
+    """
+
+    if isinstance(c_or_cr, tuple):
+        c, r = c_or_cr
+        c = _asarray_validated(c, check_finite=check_finite)
+        r = _asarray_validated(r, check_finite=check_finite)
+    else:
+        c = _asarray_validated(c_or_cr, check_finite=check_finite)
+        r = c.conjugate()
+
+    if c.ndim > 1 or r.ndim > 1:
+        msg = ("Beginning in SciPy 1.17, multidimensional input will be treated as a "
+               "batch, not `ravel`ed. To preserve the existing behavior and silence "
+               "this warning, `ravel` arguments before passing them to "
+               "`toeplitz`, `matmul_toeplitz`, and `solve_toeplitz`.")
+        warnings.warn(msg, FutureWarning, stacklevel=2)
+        c = c.ravel()
+        r = r.ravel()
+
+    if b is None:
+        raise ValueError('`b` must be an array, not None.')
+
+    b = _asarray_validated(b, check_finite=check_finite)
+    b_shape = b.shape
+
+    is_not_square = r.shape[0] != c.shape[0]
+    if (enforce_square and is_not_square) or b.shape[0] != r.shape[0]:
+        raise ValueError('Incompatible dimensions.')
+
+    is_cmplx = np.iscomplexobj(r) or np.iscomplexobj(c) or np.iscomplexobj(b)
+    dtype = np.complex128 if is_cmplx else np.float64
+    r, c, b = (np.asarray(i, dtype=dtype) for i in (r, c, b))
+
+    if b.ndim == 1 and not keep_b_shape:
+        b = b.reshape(-1, 1)
+    elif b.ndim != 1:
+        b = b.reshape(b.shape[0], -1 if b.size > 0 else 0)
+
+    return r, c, b, dtype, b_shape
+
+
+def matmul_toeplitz(c_or_cr, x, check_finite=False, workers=None):
+    r"""Efficient Toeplitz Matrix-Matrix Multiplication using FFT
+
+    This function returns the matrix multiplication between a Toeplitz
+    matrix and a dense matrix.
+
+    The Toeplitz matrix has constant diagonals, with c as its first column
+    and r as its first row. If r is not given, ``r == conjugate(c)`` is
+    assumed.
+
+    .. warning::
+
+        Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
+        not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
+        before passing them to `matmul_toeplitz`.
+
+    Parameters
+    ----------
+    c_or_cr : array_like or tuple of (array_like, array_like)
+        The vector ``c``, or a tuple of arrays (``c``, ``r``). If not
+        supplied, ``r = conjugate(c)`` is assumed; in this case, if c[0] is
+        real, the Toeplitz matrix is Hermitian. r[0] is ignored; the first row
+        of the Toeplitz matrix is ``[c[0], r[1:]]``.
+    x : (M,) or (M, K) array_like
+        Matrix with which to multiply.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (result entirely NaNs) if the inputs do contain infinities or NaNs.
+    workers : int, optional
+        To pass to scipy.fft.fft and ifft. Maximum number of workers to use
+        for parallel computation. If negative, the value wraps around from
+        ``os.cpu_count()``. See scipy.fft.fft for more details.
+
+    Returns
+    -------
+    T @ x : (M,) or (M, K) ndarray
+        The result of the matrix multiplication ``T @ x``. Shape of return
+        matches shape of `x`.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+    solve_toeplitz : Solve a Toeplitz system using Levinson Recursion
+
+    Notes
+    -----
+    The Toeplitz matrix is embedded in a circulant matrix and the FFT is used
+    to efficiently calculate the matrix-matrix product.
+
+    Because the computation is based on the FFT, integer inputs will
+    result in floating point outputs.  This is unlike NumPy's `matmul`,
+    which preserves the data type of the input.
+
+    This is partly based on the implementation that can be found in [1]_,
+    licensed under the MIT license. More information about the method can be
+    found in reference [2]_. References [3]_ and [4]_ have more reference
+    implementations in Python.
+
+    .. versionadded:: 1.6.0
+
+    References
+    ----------
+    .. [1] Jacob R Gardner, Geoff Pleiss, David Bindel, Kilian
+       Q Weinberger, Andrew Gordon Wilson, "GPyTorch: Blackbox Matrix-Matrix
+       Gaussian Process Inference with GPU Acceleration" with contributions
+       from Max Balandat and Ruihan Wu. Available online:
+       https://github.com/cornellius-gp/gpytorch
+
+    .. [2] J. Demmel, P. Koev, and X. Li, "A Brief Survey of Direct Linear
+       Solvers". In Z. Bai, J. Demmel, J. Dongarra, A. Ruhe, and H. van der
+       Vorst, editors. Templates for the Solution of Algebraic Eigenvalue
+       Problems: A Practical Guide. SIAM, Philadelphia, 2000. Available at:
+       http://www.netlib.org/utk/people/JackDongarra/etemplates/node384.html
+
+    .. [3] R. Scheibler, E. Bezzam, I. Dokmanic, Pyroomacoustics: A Python
+       package for audio room simulations and array processing algorithms,
+       Proc. IEEE ICASSP, Calgary, CA, 2018.
+       https://github.com/LCAV/pyroomacoustics/blob/pypi-release/
+       pyroomacoustics/adaptive/util.py
+
+    .. [4] Marano S, Edwards B, Ferrari G and Fah D (2017), "Fitting
+       Earthquake Spectra: Colored Noise and Incomplete Data", Bulletin of
+       the Seismological Society of America., January, 2017. Vol. 107(1),
+       pp. 276-291.
+
+    Examples
+    --------
+    Multiply the Toeplitz matrix T with matrix x::
+
+            [ 1 -1 -2 -3]       [1 10]
+        T = [ 3  1 -1 -2]   x = [2 11]
+            [ 6  3  1 -1]       [2 11]
+            [10  6  3  1]       [5 19]
+
+    To specify the Toeplitz matrix, only the first column and the first
+    row are needed.
+
+    >>> import numpy as np
+    >>> c = np.array([1, 3, 6, 10])    # First column of T
+    >>> r = np.array([1, -1, -2, -3])  # First row of T
+    >>> x = np.array([[1, 10], [2, 11], [2, 11], [5, 19]])
+
+    >>> from scipy.linalg import toeplitz, matmul_toeplitz
+    >>> matmul_toeplitz((c, r), x)
+    array([[-20., -80.],
+           [ -7.,  -8.],
+           [  9.,  85.],
+           [ 33., 218.]])
+
+    Check the result by creating the full Toeplitz matrix and
+    multiplying it by ``x``.
+
+    >>> toeplitz(c, r) @ x
+    array([[-20, -80],
+           [ -7,  -8],
+           [  9,  85],
+           [ 33, 218]])
+
+    The full matrix is never formed explicitly, so this routine
+    is suitable for very large Toeplitz matrices.
+
+    >>> n = 1000000
+    >>> matmul_toeplitz([1] + [0]*(n-1), np.ones(n))
+    array([1., 1., 1., ..., 1., 1., 1.], shape=(1000000,))
+
+    """
+
+    from ..fft import fft, ifft, rfft, irfft
+
+    r, c, x, dtype, x_shape = _validate_args_for_toeplitz_ops(
+        c_or_cr, x, check_finite, keep_b_shape=False, enforce_square=False)
+    n, m = x.shape
+
+    T_nrows = len(c)
+    T_ncols = len(r)
+    p = T_nrows + T_ncols - 1  # equivalent to len(embedded_col)
+    return_shape = (T_nrows,) if len(x_shape) == 1 else (T_nrows, m)
+
+    # accommodate empty arrays
+    if x.size == 0:
+        return np.empty_like(x, shape=return_shape)
+
+    embedded_col = np.concatenate((c, r[-1:0:-1]))
+
+    if np.iscomplexobj(embedded_col) or np.iscomplexobj(x):
+        fft_mat = fft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
+        fft_x = fft(x, n=p, axis=0, workers=workers)
+
+        mat_times_x = ifft(fft_mat*fft_x, axis=0,
+                           workers=workers)[:T_nrows, :]
+    else:
+        # Real inputs; using rfft is faster
+        fft_mat = rfft(embedded_col, axis=0, workers=workers).reshape(-1, 1)
+        fft_x = rfft(x, n=p, axis=0, workers=workers)
+
+        mat_times_x = irfft(fft_mat*fft_x, axis=0,
+                            workers=workers, n=p)[:T_nrows, :]
+
+    return mat_times_x.reshape(*return_shape)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h
new file mode 100644
index 0000000000000000000000000000000000000000..a175ca15f4adbed6d5c576e9e5ee1117abbd31ec
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_blas_subroutines.h
@@ -0,0 +1,164 @@
+/*
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+*/
+
+#include "npy_cblas.h"
+#include "fortran_defs.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void BLAS_FUNC(caxpy)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void BLAS_FUNC(ccopy)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void F_FUNC(cdotcwrp,CDOTCWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void F_FUNC(cdotuwrp,CDOTUWRP)(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void BLAS_FUNC(cgbmv)(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cgemm)(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(cgemv)(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cgerc)(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda);
+void BLAS_FUNC(cgeru)(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda);
+void BLAS_FUNC(chbmv)(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(chemm)(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(chemv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cher)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda);
+void BLAS_FUNC(cher2)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda);
+void BLAS_FUNC(cher2k)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(cherk)(char *uplo, char *trans, int *n, int *k, float *alpha, npy_complex64 *a, int *lda, float *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(chpmv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(chpr)(char *uplo, int *n, float *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap);
+void BLAS_FUNC(chpr2)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap);
+void BLAS_FUNC(crotg)(npy_complex64 *ca, npy_complex64 *cb, float *c, npy_complex64 *s);
+void BLAS_FUNC(cscal)(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx);
+void BLAS_FUNC(csrot)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, float *c, float *s);
+void BLAS_FUNC(csscal)(int *n, float *sa, npy_complex64 *cx, int *incx);
+void BLAS_FUNC(cswap)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy);
+void BLAS_FUNC(csymm)(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(csyr2k)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(csyrk)(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc);
+void BLAS_FUNC(ctbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(ctrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+void BLAS_FUNC(ctrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(ctrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx);
+double BLAS_FUNC(dasum)(int *n, double *dx, int *incx);
+void BLAS_FUNC(daxpy)(int *n, double *da, double *dx, int *incx, double *dy, int *incy);
+double BLAS_FUNC(dcabs1)(npy_complex128 *z);
+void BLAS_FUNC(dcopy)(int *n, double *dx, int *incx, double *dy, int *incy);
+double BLAS_FUNC(ddot)(int *n, double *dx, int *incx, double *dy, int *incy);
+void BLAS_FUNC(dgbmv)(char *trans, int *m, int *n, int *kl, int *ku, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dgemm)(char *transa, char *transb, int *m, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dgemv)(char *trans, int *m, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dger)(int *m, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda);
+double BLAS_FUNC(dnrm2)(int *n, double *x, int *incx);
+void BLAS_FUNC(drot)(int *n, double *dx, int *incx, double *dy, int *incy, double *c, double *s);
+void BLAS_FUNC(drotg)(double *da, double *db, double *c, double *s);
+void BLAS_FUNC(drotm)(int *n, double *dx, int *incx, double *dy, int *incy, double *dparam);
+void BLAS_FUNC(drotmg)(double *dd1, double *dd2, double *dx1, double *dy1, double *dparam);
+void BLAS_FUNC(dsbmv)(char *uplo, int *n, int *k, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dscal)(int *n, double *da, double *dx, int *incx);
+double BLAS_FUNC(dsdot)(int *n, float *sx, int *incx, float *sy, int *incy);
+void BLAS_FUNC(dspmv)(char *uplo, int *n, double *alpha, double *ap, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dspr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *ap);
+void BLAS_FUNC(dspr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *ap);
+void BLAS_FUNC(dswap)(int *n, double *dx, int *incx, double *dy, int *incy);
+void BLAS_FUNC(dsymm)(char *side, char *uplo, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dsymv)(char *uplo, int *n, double *alpha, double *a, int *lda, double *x, int *incx, double *beta, double *y, int *incy);
+void BLAS_FUNC(dsyr)(char *uplo, int *n, double *alpha, double *x, int *incx, double *a, int *lda);
+void BLAS_FUNC(dsyr2)(char *uplo, int *n, double *alpha, double *x, int *incx, double *y, int *incy, double *a, int *lda);
+void BLAS_FUNC(dsyr2k)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *b, int *ldb, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dsyrk)(char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c, int *ldc);
+void BLAS_FUNC(dtbmv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx);
+void BLAS_FUNC(dtbsv)(char *uplo, char *trans, char *diag, int *n, int *k, double *a, int *lda, double *x, int *incx);
+void BLAS_FUNC(dtpmv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx);
+void BLAS_FUNC(dtpsv)(char *uplo, char *trans, char *diag, int *n, double *ap, double *x, int *incx);
+void BLAS_FUNC(dtrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb);
+void BLAS_FUNC(dtrmv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx);
+void BLAS_FUNC(dtrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, double *alpha, double *a, int *lda, double *b, int *ldb);
+void BLAS_FUNC(dtrsv)(char *uplo, char *trans, char *diag, int *n, double *a, int *lda, double *x, int *incx);
+double BLAS_FUNC(dzasum)(int *n, npy_complex128 *zx, int *incx);
+double BLAS_FUNC(dznrm2)(int *n, npy_complex128 *x, int *incx);
+int BLAS_FUNC(icamax)(int *n, npy_complex64 *cx, int *incx);
+int BLAS_FUNC(idamax)(int *n, double *dx, int *incx);
+int BLAS_FUNC(isamax)(int *n, float *sx, int *incx);
+int BLAS_FUNC(izamax)(int *n, npy_complex128 *zx, int *incx);
+int BLAS_FUNC(lsame)(char *ca, char *cb);
+float BLAS_FUNC(sasum)(int *n, float *sx, int *incx);
+void BLAS_FUNC(saxpy)(int *n, float *sa, float *sx, int *incx, float *sy, int *incy);
+float BLAS_FUNC(scasum)(int *n, npy_complex64 *cx, int *incx);
+float BLAS_FUNC(scnrm2)(int *n, npy_complex64 *x, int *incx);
+void BLAS_FUNC(scopy)(int *n, float *sx, int *incx, float *sy, int *incy);
+float BLAS_FUNC(sdot)(int *n, float *sx, int *incx, float *sy, int *incy);
+float BLAS_FUNC(sdsdot)(int *n, float *sb, float *sx, int *incx, float *sy, int *incy);
+void BLAS_FUNC(sgbmv)(char *trans, int *m, int *n, int *kl, int *ku, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sgemm)(char *transa, char *transb, int *m, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
+void BLAS_FUNC(sgemv)(char *trans, int *m, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sger)(int *m, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda);
+float BLAS_FUNC(snrm2)(int *n, float *x, int *incx);
+void BLAS_FUNC(srot)(int *n, float *sx, int *incx, float *sy, int *incy, float *c, float *s);
+void BLAS_FUNC(srotg)(float *sa, float *sb, float *c, float *s);
+void BLAS_FUNC(srotm)(int *n, float *sx, int *incx, float *sy, int *incy, float *sparam);
+void BLAS_FUNC(srotmg)(float *sd1, float *sd2, float *sx1, float *sy1, float *sparam);
+void BLAS_FUNC(ssbmv)(char *uplo, int *n, int *k, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sscal)(int *n, float *sa, float *sx, int *incx);
+void BLAS_FUNC(sspmv)(char *uplo, int *n, float *alpha, float *ap, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(sspr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *ap);
+void BLAS_FUNC(sspr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *ap);
+void BLAS_FUNC(sswap)(int *n, float *sx, int *incx, float *sy, int *incy);
+void BLAS_FUNC(ssymm)(char *side, char *uplo, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
+void BLAS_FUNC(ssymv)(char *uplo, int *n, float *alpha, float *a, int *lda, float *x, int *incx, float *beta, float *y, int *incy);
+void BLAS_FUNC(ssyr)(char *uplo, int *n, float *alpha, float *x, int *incx, float *a, int *lda);
+void BLAS_FUNC(ssyr2)(char *uplo, int *n, float *alpha, float *x, int *incx, float *y, int *incy, float *a, int *lda);
+void BLAS_FUNC(ssyr2k)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *b, int *ldb, float *beta, float *c, int *ldc);
+void BLAS_FUNC(ssyrk)(char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *beta, float *c, int *ldc);
+void BLAS_FUNC(stbmv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(stbsv)(char *uplo, char *trans, char *diag, int *n, int *k, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(stpmv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx);
+void BLAS_FUNC(stpsv)(char *uplo, char *trans, char *diag, int *n, float *ap, float *x, int *incx);
+void BLAS_FUNC(strmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb);
+void BLAS_FUNC(strmv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(strsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, float *alpha, float *a, int *lda, float *b, int *ldb);
+void BLAS_FUNC(strsv)(char *uplo, char *trans, char *diag, int *n, float *a, int *lda, float *x, int *incx);
+void BLAS_FUNC(zaxpy)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void BLAS_FUNC(zcopy)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void F_FUNC(zdotcwrp,ZDOTCWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void F_FUNC(zdotuwrp,ZDOTUWRP)(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void BLAS_FUNC(zdrot)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, double *c, double *s);
+void BLAS_FUNC(zdscal)(int *n, double *da, npy_complex128 *zx, int *incx);
+void BLAS_FUNC(zgbmv)(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zgemm)(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zgemv)(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zgerc)(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zgeru)(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zhbmv)(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zhemm)(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zhemv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zher)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zher2)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zher2k)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zherk)(char *uplo, char *trans, int *n, int *k, double *alpha, npy_complex128 *a, int *lda, double *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zhpmv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zhpr)(char *uplo, int *n, double *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap);
+void BLAS_FUNC(zhpr2)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap);
+void BLAS_FUNC(zrotg)(npy_complex128 *ca, npy_complex128 *cb, double *c, npy_complex128 *s);
+void BLAS_FUNC(zscal)(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx);
+void BLAS_FUNC(zswap)(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy);
+void BLAS_FUNC(zsymm)(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zsyr2k)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(zsyrk)(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc);
+void BLAS_FUNC(ztbmv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztbsv)(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztpmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztpsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztrmm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(ztrmv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+void BLAS_FUNC(ztrsm)(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(ztrsv)(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..ccec61c078e57ba7b6a310ec57189fcf236c972d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pxd
@@ -0,0 +1,40 @@
+cimport numpy as cnp
+
+ctypedef fused lapack_t:
+    float
+    double
+    (float complex)
+    (double complex)
+
+ctypedef fused lapack_cz_t:
+    (float complex)
+    (double complex)
+
+ctypedef fused lapack_sd_t:
+    float
+    double
+
+ctypedef fused np_numeric_t:
+    cnp.int8_t
+    cnp.int16_t
+    cnp.int32_t
+    cnp.int64_t
+    cnp.uint8_t
+    cnp.uint16_t
+    cnp.uint32_t
+    cnp.uint64_t
+    cnp.float32_t
+    cnp.float64_t
+    cnp.longdouble_t
+    cnp.complex64_t
+    cnp.complex128_t
+
+ctypedef fused np_complex_numeric_t:
+    cnp.complex64_t
+    cnp.complex128_t
+
+
+cdef void swap_c_and_f_layout(lapack_t *a, lapack_t *b, int r, int c) noexcept nogil
+cdef (int, int) band_check_internal_c(np_numeric_t[:, ::1]A) noexcept nogil
+cdef bint is_sym_her_real_c_internal(np_numeric_t[:, ::1]A) noexcept nogil
+cdef bint is_sym_her_complex_c_internal(np_complex_numeric_t[:, ::1]A) noexcept nogil
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..5633cb61ecf3a90eba901120f64fa6cc6634fa5a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_cythonized_array_utils.pyi
@@ -0,0 +1,16 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def bandwidth(a: NDArray[Any]) -> tuple[int, int]: ...
+
+def issymmetric(
+    a: NDArray[Any],
+    atol: None | float = ...,
+    rtol: None | float = ...,
+) -> bool: ...
+
+def ishermitian(
+    a: NDArray[Any],
+    atol: None | float = ...,
+    rtol: None | float = ...,
+) -> bool: ...
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..c520d6b04b6bf0a22c4fcad62d98a17faea7c9fd
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp.py
@@ -0,0 +1,1632 @@
+#
+# Author: Pearu Peterson, March 2002
+#
+# additions by Travis Oliphant, March 2002
+# additions by Eric Jones,      June 2002
+# additions by Johannes Loehnert, June 2006
+# additions by Bart Vandereycken, June 2006
+# additions by Andrew D Straw, May 2007
+# additions by Tiziano Zito, November 2008
+#
+# April 2010: Functions for LU, QR, SVD, Schur, and Cholesky decompositions
+# were moved to their own files. Still in this file are functions for
+# eigenstuff and for the Hessenberg form.
+
+__all__ = ['eig', 'eigvals', 'eigh', 'eigvalsh',
+           'eig_banded', 'eigvals_banded',
+           'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf']
+
+import numpy as np
+from numpy import (array, isfinite, inexact, nonzero, iscomplexobj,
+                   flatnonzero, conj, asarray, argsort, empty,
+                   iscomplex, zeros, einsum, eye, inf)
+# Local imports
+from scipy._lib._util import _asarray_validated
+from ._misc import LinAlgError, _datacopied, norm
+from .lapack import get_lapack_funcs, _compute_lwork
+
+
+_I = np.array(1j, dtype='F')
+
+
+def _make_complex_eigvecs(w, vin, dtype):
+    """
+    Produce complex-valued eigenvectors from LAPACK DGGEV real-valued output
+    """
+    # - see LAPACK man page DGGEV at ALPHAI
+    v = np.array(vin, dtype=dtype)
+    m = (w.imag > 0)
+    m[:-1] |= (w.imag[1:] < 0)  # workaround for LAPACK bug, cf. ticket #709
+    for i in flatnonzero(m):
+        v.imag[:, i] = vin[:, i+1]
+        conj(v[:, i], v[:, i+1])
+    return v
+
+
+def _make_eigvals(alpha, beta, homogeneous_eigvals):
+    if homogeneous_eigvals:
+        if beta is None:
+            return np.vstack((alpha, np.ones_like(alpha)))
+        else:
+            return np.vstack((alpha, beta))
+    else:
+        if beta is None:
+            return alpha
+        else:
+            w = np.empty_like(alpha)
+            alpha_zero = (alpha == 0)
+            beta_zero = (beta == 0)
+            beta_nonzero = ~beta_zero
+            w[beta_nonzero] = alpha[beta_nonzero]/beta[beta_nonzero]
+            # Use np.inf for complex values too since
+            # 1/np.inf = 0, i.e., it correctly behaves as projective
+            # infinity.
+            w[~alpha_zero & beta_zero] = np.inf
+            if np.all(alpha.imag == 0):
+                w[alpha_zero & beta_zero] = np.nan
+            else:
+                w[alpha_zero & beta_zero] = complex(np.nan, np.nan)
+            return w
+
+
+def _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
+            homogeneous_eigvals):
+    ggev, = get_lapack_funcs(('ggev',), (a1, b1))
+    cvl, cvr = left, right
+    res = ggev(a1, b1, lwork=-1)
+    lwork = res[-2][0].real.astype(np.int_)
+    if ggev.typecode in 'cz':
+        alpha, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr, lwork,
+                                               overwrite_a, overwrite_b)
+        w = _make_eigvals(alpha, beta, homogeneous_eigvals)
+    else:
+        alphar, alphai, beta, vl, vr, work, info = ggev(a1, b1, cvl, cvr,
+                                                        lwork, overwrite_a,
+                                                        overwrite_b)
+        alpha = alphar + _I * alphai
+        w = _make_eigvals(alpha, beta, homogeneous_eigvals)
+    _check_info(info, 'generalized eig algorithm (ggev)')
+
+    only_real = np.all(w.imag == 0.0)
+    if not (ggev.typecode in 'cz' or only_real):
+        t = w.dtype.char
+        if left:
+            vl = _make_complex_eigvecs(w, vl, t)
+        if right:
+            vr = _make_complex_eigvecs(w, vr, t)
+
+    # the eigenvectors returned by the lapack function are NOT normalized
+    for i in range(vr.shape[0]):
+        if right:
+            vr[:, i] /= norm(vr[:, i])
+        if left:
+            vl[:, i] /= norm(vl[:, i])
+
+    if not (left or right):
+        return w
+    if left:
+        if right:
+            return w, vl, vr
+        return w, vl
+    return w, vr
+
+
+def eig(a, b=None, left=False, right=True, overwrite_a=False,
+        overwrite_b=False, check_finite=True, homogeneous_eigvals=False):
+    """
+    Solve an ordinary or generalized eigenvalue problem of a square matrix.
+
+    Find eigenvalues w and right or left eigenvectors of a general matrix::
+
+        a   vr[:,i] = w[i]        b   vr[:,i]
+        a.H vl[:,i] = w[i].conj() b.H vl[:,i]
+
+    where ``.H`` is the Hermitian conjugation.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex or real matrix whose eigenvalues and eigenvectors
+        will be computed.
+    b : (M, M) array_like, optional
+        Right-hand side matrix in a generalized eigenvalue problem.
+        Default is None, identity matrix is assumed.
+    left : bool, optional
+        Whether to calculate and return left eigenvectors.  Default is False.
+    right : bool, optional
+        Whether to calculate and return right eigenvectors.  Default is True.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.  Default is False.
+    overwrite_b : bool, optional
+        Whether to overwrite `b`; may improve performance.  Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    homogeneous_eigvals : bool, optional
+        If True, return the eigenvalues in homogeneous coordinates.
+        In this case ``w`` is a (2, M) array so that::
+
+            w[1,i] a vr[:,i] = w[0,i] b vr[:,i]
+
+        Default is False.
+
+    Returns
+    -------
+    w : (M,) or (2, M) double or complex ndarray
+        The eigenvalues, each repeated according to its
+        multiplicity. The shape is (M,) unless
+        ``homogeneous_eigvals=True``.
+    vl : (M, M) double or complex ndarray
+        The left eigenvector corresponding to the eigenvalue
+        ``w[i]`` is the column ``vl[:,i]``. Only returned if ``left=True``.
+        The left eigenvector is not normalized.
+    vr : (M, M) double or complex ndarray
+        The normalized right eigenvector corresponding to the eigenvalue
+        ``w[i]`` is the column ``vr[:,i]``.  Only returned if ``right=True``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvals : eigenvalues of general arrays
+    eigh : Eigenvalues and right eigenvectors for symmetric/Hermitian arrays.
+    eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
+        band matrices
+    eigh_tridiagonal : eigenvalues and right eiegenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0., -1.], [1., 0.]])
+    >>> linalg.eigvals(a)
+    array([0.+1.j, 0.-1.j])
+
+    >>> b = np.array([[0., 1.], [1., 1.]])
+    >>> linalg.eigvals(a, b)
+    array([ 1.+0.j, -1.+0.j])
+
+    >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
+    >>> linalg.eigvals(a, homogeneous_eigvals=True)
+    array([[3.+0.j, 8.+0.j, 7.+0.j],
+           [1.+0.j, 1.+0.j, 1.+0.j]])
+
+    >>> a = np.array([[0., -1.], [1., 0.]])
+    >>> linalg.eigvals(a) == linalg.eig(a)[0]
+    array([ True,  True])
+    >>> linalg.eig(a, left=True, right=False)[1] # normalized left eigenvector
+    array([[-0.70710678+0.j        , -0.70710678-0.j        ],
+           [-0.        +0.70710678j, -0.        -0.70710678j]])
+    >>> linalg.eig(a, left=False, right=True)[1] # normalized right eigenvector
+    array([[0.70710678+0.j        , 0.70710678-0.j        ],
+           [0.        -0.70710678j, 0.        +0.70710678j]])
+
+
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square matrix')
+
+    # accommodate square empty matrices
+    if a1.size == 0:
+        w_n, vr_n = eig(np.eye(2, dtype=a1.dtype))
+        w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+        vl = np.empty_like(a1, shape=(0, 0), dtype=vr_n.dtype)
+        vr = np.empty_like(a1, shape=(0, 0), dtype=vr_n.dtype)
+        if not (left or right):
+            return w
+        if left:
+            if right:
+                return w, vl, vr
+            return w, vl
+        return w, vr
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    if b is not None:
+        b1 = _asarray_validated(b, check_finite=check_finite)
+        overwrite_b = overwrite_b or _datacopied(b1, b)
+        if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
+            raise ValueError('expected square matrix')
+        if b1.shape != a1.shape:
+            raise ValueError('a and b must have the same shape')
+        return _geneig(a1, b1, left, right, overwrite_a, overwrite_b,
+                       homogeneous_eigvals)
+
+    geev, geev_lwork = get_lapack_funcs(('geev', 'geev_lwork'), (a1,))
+    compute_vl, compute_vr = left, right
+
+    lwork = _compute_lwork(geev_lwork, a1.shape[0],
+                           compute_vl=compute_vl,
+                           compute_vr=compute_vr)
+
+    if geev.typecode in 'cz':
+        w, vl, vr, info = geev(a1, lwork=lwork,
+                               compute_vl=compute_vl,
+                               compute_vr=compute_vr,
+                               overwrite_a=overwrite_a)
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+    else:
+        wr, wi, vl, vr, info = geev(a1, lwork=lwork,
+                                    compute_vl=compute_vl,
+                                    compute_vr=compute_vr,
+                                    overwrite_a=overwrite_a)
+        w = wr + _I * wi
+        w = _make_eigvals(w, None, homogeneous_eigvals)
+
+    _check_info(info, 'eig algorithm (geev)',
+                positive='did not converge (only eigenvalues '
+                         'with order >= %d have converged)')
+
+    only_real = np.all(w.imag == 0.0)
+    if not (geev.typecode in 'cz' or only_real):
+        t = w.dtype.char
+        if left:
+            vl = _make_complex_eigvecs(w, vl, t)
+        if right:
+            vr = _make_complex_eigvecs(w, vr, t)
+    if not (left or right):
+        return w
+    if left:
+        if right:
+            return w, vl, vr
+        return w, vl
+    return w, vr
+
+
+def eigh(a, b=None, *, lower=True, eigvals_only=False, overwrite_a=False,
+         overwrite_b=False, type=1, check_finite=True, subset_by_index=None,
+         subset_by_value=None, driver=None):
+    """
+    Solve a standard or generalized eigenvalue problem for a complex
+    Hermitian or real symmetric matrix.
+
+    Find eigenvalues array ``w`` and optionally eigenvectors array ``v`` of
+    array ``a``, where ``b`` is positive definite such that for every
+    eigenvalue λ (i-th entry of w) and its eigenvector ``vi`` (i-th column of
+    ``v``) satisfies::
+
+                      a @ vi = λ * b @ vi
+        vi.conj().T @ a @ vi = λ
+        vi.conj().T @ b @ vi = 1
+
+    In the standard problem, ``b`` is assumed to be the identity matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex Hermitian or real symmetric matrix whose eigenvalues and
+        eigenvectors will be computed.
+    b : (M, M) array_like, optional
+        A complex Hermitian or real symmetric definite positive matrix in.
+        If omitted, identity matrix is assumed.
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower or upper
+        triangle of ``a`` and, if applicable, ``b``. (Default: lower)
+    eigvals_only : bool, optional
+        Whether to calculate only eigenvalues and no eigenvectors.
+        (Default: both are calculated)
+    subset_by_index : iterable, optional
+        If provided, this two-element iterable defines the start and the end
+        indices of the desired eigenvalues (ascending order and 0-indexed).
+        To return only the second smallest to fifth smallest eigenvalues,
+        ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
+        available with "evr", "evx", and "gvx" drivers. The entries are
+        directly converted to integers via ``int()``.
+    subset_by_value : iterable, optional
+        If provided, this two-element iterable defines the half-open interval
+        ``(a, b]`` that, if any, only the eigenvalues between these values
+        are returned. Only available with "evr", "evx", and "gvx" drivers. Use
+        ``np.inf`` for the unconstrained ends.
+    driver : str, optional
+        Defines which LAPACK driver should be used. Valid options are "ev",
+        "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
+        generalized (where b is not None) problems. See the Notes section.
+        The default for standard problems is "evr". For generalized problems,
+        "gvd" is used for full set, and "gvx" for subset requested cases.
+    type : int, optional
+        For the generalized problems, this keyword specifies the problem type
+        to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
+        inputs)::
+
+            1 =>     a @ v = w @ b @ v
+            2 => a @ b @ v = w @ v
+            3 => b @ a @ v = w @ v
+
+        This keyword is ignored for standard problems.
+    overwrite_a : bool, optional
+        Whether to overwrite data in ``a`` (may improve performance). Default
+        is False.
+    overwrite_b : bool, optional
+        Whether to overwrite data in ``b`` (may improve performance). Default
+        is False.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    w : (N,) ndarray
+        The N (N<=M) selected eigenvalues, in ascending order, each
+        repeated according to its multiplicity.
+    v : (M, N) ndarray
+        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
+        the column ``v[:,i]``. Only returned if ``eigvals_only=False``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge, an error occurred, or
+        b matrix is not definite positive. Note that if input matrices are
+        not symmetric or Hermitian, no error will be reported but results will
+        be wrong.
+
+    See Also
+    --------
+    eigvalsh : eigenvalues of symmetric or Hermitian arrays
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays
+    eigh_tridiagonal : eigenvalues and right eiegenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Notes
+    -----
+    This function does not check the input array for being Hermitian/symmetric
+    in order to allow for representing arrays with only their upper/lower
+    triangular parts. Also, note that even though not taken into account,
+    finiteness check applies to the whole array and unaffected by "lower"
+    keyword.
+
+    This function uses LAPACK drivers for computations in all possible keyword
+    combinations, prefixed with ``sy`` if arrays are real and ``he`` if
+    complex, e.g., a float array with "evr" driver is solved via
+    "syevr", complex arrays with "gvx" driver problem is solved via "hegvx"
+    etc.
+
+    As a brief summary, the slowest and the most robust driver is the
+    classical ``ev`` which uses symmetric QR. ``evr`` is seen as
+    the optimal choice for the most general cases. However, there are certain
+    occasions that ``evd`` computes faster at the expense of more
+    memory usage. ``evx``, while still being faster than ``ev``,
+    often performs worse than the rest except when very few eigenvalues are
+    requested for large arrays though there is still no performance guarantee.
+
+    Note that the underlying LAPACK algorithms are different depending on whether
+    `eigvals_only` is True or False --- thus the eigenvalues may differ
+    depending on whether eigenvectors are requested or not. The difference is
+    generally of the order of machine epsilon times the largest eigenvalue,
+    so is likely only visible for zero or nearly zero eigenvalues.
+
+    For the generalized problem, normalization with respect to the given
+    type argument::
+
+            type 1 and 3 :      v.conj().T @ a @ v = w
+            type 2       : inv(v).conj().T @ a @ inv(v) = w
+
+            type 1 or 2  :      v.conj().T @ b @ v  = I
+            type 3       : v.conj().T @ inv(b) @ v  = I
+
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigh
+    >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
+    >>> w, v = eigh(A)
+    >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
+    True
+
+    Request only the eigenvalues
+
+    >>> w = eigh(A, eigvals_only=True)
+
+    Request eigenvalues that are less than 10.
+
+    >>> A = np.array([[34, -4, -10, -7, 2],
+    ...               [-4, 7, 2, 12, 0],
+    ...               [-10, 2, 44, 2, -19],
+    ...               [-7, 12, 2, 79, -34],
+    ...               [2, 0, -19, -34, 29]])
+    >>> eigh(A, eigvals_only=True, subset_by_value=[-np.inf, 10])
+    array([6.69199443e-07, 9.11938152e+00])
+
+    Request the second smallest eigenvalue and its eigenvector
+
+    >>> w, v = eigh(A, subset_by_index=[1, 1])
+    >>> w
+    array([9.11938152])
+    >>> v.shape  # only a single column is returned
+    (5, 1)
+
+    """
+    # set lower
+    uplo = 'L' if lower else 'U'
+    # Set job for Fortran routines
+    _job = 'N' if eigvals_only else 'V'
+
+    drv_str = [None, "ev", "evd", "evr", "evx", "gv", "gvd", "gvx"]
+    if driver not in drv_str:
+        raise ValueError('"{}" is unknown. Possible values are "None", "{}".'
+                         ''.format(driver, '", "'.join(drv_str[1:])))
+
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]:
+        raise ValueError('expected square "a" matrix')
+
+    # accommodate square empty matrices
+    if a1.size == 0:
+        w_n, v_n = eigh(np.eye(2, dtype=a1.dtype))
+
+        w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
+        v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype)
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    cplx = True if iscomplexobj(a1) else False
+    n = a1.shape[0]
+    drv_args = {'overwrite_a': overwrite_a}
+
+    if b is not None:
+        b1 = _asarray_validated(b, check_finite=check_finite)
+        overwrite_b = overwrite_b or _datacopied(b1, b)
+        if len(b1.shape) != 2 or b1.shape[0] != b1.shape[1]:
+            raise ValueError('expected square "b" matrix')
+
+        if b1.shape != a1.shape:
+            raise ValueError(f"wrong b dimensions {b1.shape}, should be {a1.shape}")
+
+        if type not in [1, 2, 3]:
+            raise ValueError('"type" keyword only accepts 1, 2, and 3.')
+
+        cplx = True if iscomplexobj(b1) else (cplx or False)
+        drv_args.update({'overwrite_b': overwrite_b, 'itype': type})
+
+    subset = (subset_by_index is not None) or (subset_by_value is not None)
+
+    # Both subsets can't be given
+    if subset_by_index and subset_by_value:
+        raise ValueError('Either index or value subset can be requested.')
+
+    # Check indices if given
+    if subset_by_index:
+        lo, hi = (int(x) for x in subset_by_index)
+        if not (0 <= lo <= hi < n):
+            raise ValueError('Requested eigenvalue indices are not valid. '
+                             f'Valid range is [0, {n-1}] and start <= end, but '
+                             f'start={lo}, end={hi} is given')
+        # fortran is 1-indexed
+        drv_args.update({'range': 'I', 'il': lo + 1, 'iu': hi + 1})
+
+    if subset_by_value:
+        lo, hi = subset_by_value
+        if not (-inf <= lo < hi <= inf):
+            raise ValueError('Requested eigenvalue bounds are not valid. '
+                             'Valid range is (-inf, inf) and low < high, but '
+                             f'low={lo}, high={hi} is given')
+
+        drv_args.update({'range': 'V', 'vl': lo, 'vu': hi})
+
+    # fix prefix for lapack routines
+    pfx = 'he' if cplx else 'sy'
+
+    # decide on the driver if not given
+    # first early exit on incompatible choice
+    if driver:
+        if b is None and (driver in ["gv", "gvd", "gvx"]):
+            raise ValueError(f'{driver} requires input b array to be supplied '
+                             'for generalized eigenvalue problems.')
+        if (b is not None) and (driver in ['ev', 'evd', 'evr', 'evx']):
+            raise ValueError(f'"{driver}" does not accept input b array '
+                             'for standard eigenvalue problems.')
+        if subset and (driver in ["ev", "evd", "gv", "gvd"]):
+            raise ValueError(f'"{driver}" cannot compute subsets of eigenvalues')
+
+    # Default driver is evr and gvd
+    else:
+        driver = "evr" if b is None else ("gvx" if subset else "gvd")
+
+    lwork_spec = {
+                  'syevd': ['lwork', 'liwork'],
+                  'syevr': ['lwork', 'liwork'],
+                  'heevd': ['lwork', 'liwork', 'lrwork'],
+                  'heevr': ['lwork', 'lrwork', 'liwork'],
+                  }
+
+    if b is None:  # Standard problem
+        drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
+                                      [a1])
+        clw_args = {'n': n, 'lower': lower}
+        if driver == 'evd':
+            clw_args.update({'compute_v': 0 if _job == "N" else 1})
+
+        lw = _compute_lwork(drvlw, **clw_args)
+        # Multiple lwork vars
+        if isinstance(lw, tuple):
+            lwork_args = dict(zip(lwork_spec[pfx+driver], lw))
+        else:
+            lwork_args = {'lwork': lw}
+
+        drv_args.update({'lower': lower, 'compute_v': 0 if _job == "N" else 1})
+        w, v, *other_args, info = drv(a=a1, **drv_args, **lwork_args)
+
+    else:  # Generalized problem
+        # 'gvd' doesn't have lwork query
+        if driver == "gvd":
+            drv = get_lapack_funcs(pfx + "gvd", [a1, b1])
+            lwork_args = {}
+        else:
+            drv, drvlw = get_lapack_funcs((pfx + driver, pfx+driver+'_lwork'),
+                                          [a1, b1])
+            # generalized drivers use uplo instead of lower
+            lw = _compute_lwork(drvlw, n, uplo=uplo)
+            lwork_args = {'lwork': lw}
+
+        drv_args.update({'uplo': uplo, 'jobz': _job})
+
+        w, v, *other_args, info = drv(a=a1, b=b1, **drv_args, **lwork_args)
+
+    # m is always the first extra argument
+    w = w[:other_args[0]] if subset else w
+    v = v[:, :other_args[0]] if (subset and not eigvals_only) else v
+
+    # Check if we had a  successful exit
+    if info == 0:
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+    else:
+        if info < -1:
+            raise LinAlgError(f'Illegal value in argument {-info} of internal '
+                              f'{drv.typecode + pfx + driver}')
+        elif info > n:
+            raise LinAlgError(f'The leading minor of order {info-n} of B is not '
+                              'positive definite. The factorization of B '
+                              'could not be completed and no eigenvalues '
+                              'or eigenvectors were computed.')
+        else:
+            drv_err = {'ev': 'The algorithm failed to converge; {} '
+                             'off-diagonal elements of an intermediate '
+                             'tridiagonal form did not converge to zero.',
+                       'evx': '{} eigenvectors failed to converge.',
+                       'evd': 'The algorithm failed to compute an eigenvalue '
+                              'while working on the submatrix lying in rows '
+                              'and columns {0}/{1} through mod({0},{1}).',
+                       'evr': 'Internal Error.'
+                       }
+            if driver in ['ev', 'gv']:
+                msg = drv_err['ev'].format(info)
+            elif driver in ['evx', 'gvx']:
+                msg = drv_err['evx'].format(info)
+            elif driver in ['evd', 'gvd']:
+                if eigvals_only:
+                    msg = drv_err['ev'].format(info)
+                else:
+                    msg = drv_err['evd'].format(info, n+1)
+            else:
+                msg = drv_err['evr']
+
+            raise LinAlgError(msg)
+
+
+_conv_dict = {0: 0, 1: 1, 2: 2,
+              'all': 0, 'value': 1, 'index': 2,
+              'a': 0, 'v': 1, 'i': 2}
+
+
+def _check_select(select, select_range, max_ev, max_len):
+    """Check that select is valid, convert to Fortran style."""
+    if isinstance(select, str):
+        select = select.lower()
+    try:
+        select = _conv_dict[select]
+    except KeyError as e:
+        raise ValueError('invalid argument for select') from e
+    vl, vu = 0., 1.
+    il = iu = 1
+    if select != 0:  # (non-all)
+        sr = asarray(select_range)
+        if sr.ndim != 1 or sr.size != 2 or sr[1] < sr[0]:
+            raise ValueError('select_range must be a 2-element array-like '
+                             'in nondecreasing order')
+        if select == 1:  # (value)
+            vl, vu = sr
+            if max_ev == 0:
+                max_ev = max_len
+        else:  # 2 (index)
+            if sr.dtype.char.lower() not in 'hilqp':
+                raise ValueError(
+                    f'when using select="i", select_range must '
+                    f'contain integers, got dtype {sr.dtype} ({sr.dtype.char})'
+                )
+            # translate Python (0 ... N-1) into Fortran (1 ... N) with + 1
+            il, iu = sr + 1
+            if min(il, iu) < 1 or max(il, iu) > max_len:
+                raise ValueError('select_range out of bounds')
+            max_ev = iu - il + 1
+    return select, vl, vu, il, iu, max_ev
+
+
+def eig_banded(a_band, lower=False, eigvals_only=False, overwrite_a_band=False,
+               select='a', select_range=None, max_ev=0, check_finite=True):
+    """
+    Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
+
+    Find eigenvalues w and optionally right eigenvectors v of a::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    The matrix a is stored in a_band either in lower diagonal or upper
+    diagonal ordered form:
+
+        a_band[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        a_band[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    where u is the number of bands above the diagonal.
+
+    Example of a_band (shape of a is (6,6), u=2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Cells marked with * are not used.
+
+    Parameters
+    ----------
+    a_band : (u+1, M) array_like
+        The bands of the M by M matrix a.
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    eigvals_only : bool, optional
+        Compute only the eigenvalues and no eigenvectors.
+        (Default: calculate also eigenvectors)
+    overwrite_a_band : bool, optional
+        Discard data in a_band (may enhance performance)
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    max_ev : int, optional
+        For select=='v', maximum number of eigenvalues expected.
+        For other values of select, has no meaning.
+
+        In doubt, leave this parameter untouched.
+
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+    v : (M, M) float or complex ndarray
+        The normalized eigenvector corresponding to the eigenvalue w[i] is
+        the column v[:,i]. Only returned if ``eigvals_only=False``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
+    eig : eigenvalues and right eigenvectors of general arrays.
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eigh_tridiagonal : eigenvalues and right eigenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eig_banded
+    >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]])
+    >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]])
+    >>> w, v = eig_banded(Ab, lower=True)
+    >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
+    True
+    >>> w = eig_banded(Ab, lower=True, eigvals_only=True)
+    >>> w
+    array([-4.26200532, -2.22987175,  3.95222349, 12.53965359])
+
+    Request only the eigenvalues between ``[-3, 4]``
+
+    >>> w, v = eig_banded(Ab, lower=True, select='v', select_range=[-3, 4])
+    >>> w
+    array([-2.22987175,  3.95222349])
+
+    """
+    if eigvals_only or overwrite_a_band:
+        a1 = _asarray_validated(a_band, check_finite=check_finite)
+        overwrite_a_band = overwrite_a_band or (_datacopied(a1, a_band))
+    else:
+        a1 = array(a_band)
+        if issubclass(a1.dtype.type, inexact) and not isfinite(a1).all():
+            raise ValueError("array must not contain infs or NaNs")
+        overwrite_a_band = 1
+
+    if len(a1.shape) != 2:
+        raise ValueError('expected a 2-D array')
+
+    # accommodate square empty matrices
+    if a1.size == 0:
+        w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=a1.dtype))
+
+        w = np.empty_like(a1, shape=(0,), dtype=w_n.dtype)
+        v = np.empty_like(a1, shape=(0, 0), dtype=v_n.dtype)
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+
+    select, vl, vu, il, iu, max_ev = _check_select(
+        select, select_range, max_ev, a1.shape[1])
+
+    del select_range
+    if select == 0:
+        if a1.dtype.char in 'GFD':
+            # FIXME: implement this somewhen, for now go with builtin values
+            # FIXME: calc optimal lwork by calling ?hbevd(lwork=-1)
+            #        or by using calc_lwork.f ???
+            # lwork = calc_lwork.hbevd(bevd.typecode, a1.shape[0], lower)
+            internal_name = 'hbevd'
+        else:  # a1.dtype.char in 'fd':
+            # FIXME: implement this somewhen, for now go with builtin values
+            #         see above
+            # lwork = calc_lwork.sbevd(bevd.typecode, a1.shape[0], lower)
+            internal_name = 'sbevd'
+        bevd, = get_lapack_funcs((internal_name,), (a1,))
+        w, v, info = bevd(a1, compute_v=not eigvals_only,
+                          lower=lower, overwrite_ab=overwrite_a_band)
+    else:  # select in [1, 2]
+        if eigvals_only:
+            max_ev = 1
+        # calculate optimal abstol for dsbevx (see manpage)
+        if a1.dtype.char in 'fF':  # single precision
+            lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='f'),))
+        else:
+            lamch, = get_lapack_funcs(('lamch',), (array(0, dtype='d'),))
+        abstol = 2 * lamch('s')
+        if a1.dtype.char in 'GFD':
+            internal_name = 'hbevx'
+        else:  # a1.dtype.char in 'gfd'
+            internal_name = 'sbevx'
+        bevx, = get_lapack_funcs((internal_name,), (a1,))
+        w, v, m, ifail, info = bevx(
+            a1, vl, vu, il, iu, compute_v=not eigvals_only, mmax=max_ev,
+            range=select, lower=lower, overwrite_ab=overwrite_a_band,
+            abstol=abstol)
+        # crop off w and v
+        w = w[:m]
+        if not eigvals_only:
+            v = v[:, :m]
+    _check_info(info, internal_name)
+
+    if eigvals_only:
+        return w
+    return w, v
+
+
+def eigvals(a, b=None, overwrite_a=False, check_finite=True,
+            homogeneous_eigvals=False):
+    """
+    Compute eigenvalues from an ordinary or generalized eigenvalue problem.
+
+    Find eigenvalues of a general matrix::
+
+        a   vr[:,i] = w[i]        b   vr[:,i]
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex or real matrix whose eigenvalues and eigenvectors
+        will be computed.
+    b : (M, M) array_like, optional
+        Right-hand side matrix in a generalized eigenvalue problem.
+        If omitted, identity matrix is assumed.
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities
+        or NaNs.
+    homogeneous_eigvals : bool, optional
+        If True, return the eigenvalues in homogeneous coordinates.
+        In this case ``w`` is a (2, M) array so that::
+
+            w[1,i] a vr[:,i] = w[0,i] b vr[:,i]
+
+        Default is False.
+
+    Returns
+    -------
+    w : (M,) or (2, M) double or complex ndarray
+        The eigenvalues, each repeated according to its multiplicity
+        but not in any specific order. The shape is (M,) unless
+        ``homogeneous_eigvals=True``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge
+
+    See Also
+    --------
+    eig : eigenvalues and right eigenvectors of general arrays.
+    eigvalsh : eigenvalues of symmetric or Hermitian arrays
+    eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0., -1.], [1., 0.]])
+    >>> linalg.eigvals(a)
+    array([0.+1.j, 0.-1.j])
+
+    >>> b = np.array([[0., 1.], [1., 1.]])
+    >>> linalg.eigvals(a, b)
+    array([ 1.+0.j, -1.+0.j])
+
+    >>> a = np.array([[3., 0., 0.], [0., 8., 0.], [0., 0., 7.]])
+    >>> linalg.eigvals(a, homogeneous_eigvals=True)
+    array([[3.+0.j, 8.+0.j, 7.+0.j],
+           [1.+0.j, 1.+0.j, 1.+0.j]])
+
+    """
+    return eig(a, b=b, left=0, right=0, overwrite_a=overwrite_a,
+               check_finite=check_finite,
+               homogeneous_eigvals=homogeneous_eigvals)
+
+
+def eigvalsh(a, b=None, *, lower=True, overwrite_a=False,
+             overwrite_b=False, type=1, check_finite=True, subset_by_index=None,
+             subset_by_value=None, driver=None):
+    """
+    Solves a standard or generalized eigenvalue problem for a complex
+    Hermitian or real symmetric matrix.
+
+    Find eigenvalues array ``w`` of array ``a``, where ``b`` is positive
+    definite such that for every eigenvalue λ (i-th entry of w) and its
+    eigenvector vi (i-th column of v) satisfies::
+
+                      a @ vi = λ * b @ vi
+        vi.conj().T @ a @ vi = λ
+        vi.conj().T @ b @ vi = 1
+
+    In the standard problem, b is assumed to be the identity matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        A complex Hermitian or real symmetric matrix whose eigenvalues will
+        be computed.
+    b : (M, M) array_like, optional
+        A complex Hermitian or real symmetric definite positive matrix in.
+        If omitted, identity matrix is assumed.
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower or upper
+        triangle of ``a`` and, if applicable, ``b``. (Default: lower)
+    overwrite_a : bool, optional
+        Whether to overwrite data in ``a`` (may improve performance). Default
+        is False.
+    overwrite_b : bool, optional
+        Whether to overwrite data in ``b`` (may improve performance). Default
+        is False.
+    type : int, optional
+        For the generalized problems, this keyword specifies the problem type
+        to be solved for ``w`` and ``v`` (only takes 1, 2, 3 as possible
+        inputs)::
+
+            1 =>     a @ v = w @ b @ v
+            2 => a @ b @ v = w @ v
+            3 => b @ a @ v = w @ v
+
+        This keyword is ignored for standard problems.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    subset_by_index : iterable, optional
+        If provided, this two-element iterable defines the start and the end
+        indices of the desired eigenvalues (ascending order and 0-indexed).
+        To return only the second smallest to fifth smallest eigenvalues,
+        ``[1, 4]`` is used. ``[n-3, n-1]`` returns the largest three. Only
+        available with "evr", "evx", and "gvx" drivers. The entries are
+        directly converted to integers via ``int()``.
+    subset_by_value : iterable, optional
+        If provided, this two-element iterable defines the half-open interval
+        ``(a, b]`` that, if any, only the eigenvalues between these values
+        are returned. Only available with "evr", "evx", and "gvx" drivers. Use
+        ``np.inf`` for the unconstrained ends.
+    driver : str, optional
+        Defines which LAPACK driver should be used. Valid options are "ev",
+        "evd", "evr", "evx" for standard problems and "gv", "gvd", "gvx" for
+        generalized (where b is not None) problems. See the Notes section of
+        `scipy.linalg.eigh`.
+
+    Returns
+    -------
+    w : (N,) ndarray
+        The N (N<=M) selected eigenvalues, in ascending order, each
+        repeated according to its multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge, an error occurred, or
+        b matrix is not definite positive. Note that if input matrices are
+        not symmetric or Hermitian, no error will be reported but results will
+        be wrong.
+
+    See Also
+    --------
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eigvals : eigenvalues of general arrays
+    eigvals_banded : eigenvalues for symmetric/Hermitian band matrices
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+
+    Notes
+    -----
+    This function does not check the input array for being Hermitian/symmetric
+    in order to allow for representing arrays with only their upper/lower
+    triangular parts.
+
+    This function serves as a one-liner shorthand for `scipy.linalg.eigh` with
+    the option ``eigvals_only=True`` to get the eigenvalues and not the
+    eigenvectors. Here it is kept as a legacy convenience. It might be
+    beneficial to use the main function to have full control and to be a bit
+    more pythonic.
+
+    Examples
+    --------
+    For more examples see `scipy.linalg.eigh`.
+
+    >>> import numpy as np
+    >>> from scipy.linalg import eigvalsh
+    >>> A = np.array([[6, 3, 1, 5], [3, 0, 5, 1], [1, 5, 6, 2], [5, 1, 2, 2]])
+    >>> w = eigvalsh(A)
+    >>> w
+    array([-3.74637491, -0.76263923,  6.08502336, 12.42399079])
+
+    """
+    return eigh(a, b=b, lower=lower, eigvals_only=True, overwrite_a=overwrite_a,
+                overwrite_b=overwrite_b, type=type, check_finite=check_finite,
+                subset_by_index=subset_by_index, subset_by_value=subset_by_value,
+                driver=driver)
+
+
+def eigvals_banded(a_band, lower=False, overwrite_a_band=False,
+                   select='a', select_range=None, check_finite=True):
+    """
+    Solve real symmetric or complex Hermitian band matrix eigenvalue problem.
+
+    Find eigenvalues w of a::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    The matrix a is stored in a_band either in lower diagonal or upper
+    diagonal ordered form:
+
+        a_band[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        a_band[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    where u is the number of bands above the diagonal.
+
+    Example of a_band (shape of a is (6,6), u=2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Cells marked with * are not used.
+
+    Parameters
+    ----------
+    a_band : (u+1, M) array_like
+        The bands of the M by M matrix a.
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    overwrite_a_band : bool, optional
+        Discard data in a_band (may enhance performance)
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
+        band matrices
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+    eigvals : eigenvalues of general arrays
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigvals_banded
+    >>> A = np.array([[1, 5, 2, 0], [5, 2, 5, 2], [2, 5, 3, 5], [0, 2, 5, 4]])
+    >>> Ab = np.array([[1, 2, 3, 4], [5, 5, 5, 0], [2, 2, 0, 0]])
+    >>> w = eigvals_banded(Ab, lower=True)
+    >>> w
+    array([-4.26200532, -2.22987175,  3.95222349, 12.53965359])
+    """
+    return eig_banded(a_band, lower=lower, eigvals_only=1,
+                      overwrite_a_band=overwrite_a_band, select=select,
+                      select_range=select_range, check_finite=check_finite)
+
+
+def eigvalsh_tridiagonal(d, e, select='a', select_range=None,
+                         check_finite=True, tol=0., lapack_driver='auto'):
+    """
+    Solve eigenvalue problem for a real symmetric tridiagonal matrix.
+
+    Find eigenvalues `w` of ``a``::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    For a real symmetric matrix ``a`` with diagonal elements `d` and
+    off-diagonal elements `e`.
+
+    Parameters
+    ----------
+    d : ndarray, shape (ndim,)
+        The diagonal elements of the array.
+    e : ndarray, shape (ndim-1,)
+        The off-diagonal elements of the array.
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    tol : float
+        The absolute tolerance to which each eigenvalue is required
+        (only used when ``lapack_driver='stebz'``).
+        An eigenvalue (or cluster) is considered to have converged if it
+        lies in an interval of this width. If <= 0. (default),
+        the value ``eps*|a|`` is used where eps is the machine precision,
+        and ``|a|`` is the 1-norm of the matrix ``a``.
+    lapack_driver : str
+        LAPACK function to use, can be 'auto', 'stemr', 'stebz',  'sterf',
+        or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'``
+        and 'stebz' otherwise. 'sterf' and 'stev' can only be used when
+        ``select='a'``.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigh_tridiagonal : eigenvalues and right eiegenvectors for
+        symmetric/Hermitian tridiagonal matrices
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigvalsh_tridiagonal, eigvalsh
+    >>> d = 3*np.ones(4)
+    >>> e = -1*np.ones(3)
+    >>> w = eigvalsh_tridiagonal(d, e)
+    >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
+    >>> w2 = eigvalsh(A)  # Verify with other eigenvalue routines
+    >>> np.allclose(w - w2, np.zeros(4))
+    True
+    """
+    return eigh_tridiagonal(
+        d, e, eigvals_only=True, select=select, select_range=select_range,
+        check_finite=check_finite, tol=tol, lapack_driver=lapack_driver)
+
+
+def eigh_tridiagonal(d, e, eigvals_only=False, select='a', select_range=None,
+                     check_finite=True, tol=0., lapack_driver='auto'):
+    """
+    Solve eigenvalue problem for a real symmetric tridiagonal matrix.
+
+    Find eigenvalues `w` and optionally right eigenvectors `v` of ``a``::
+
+        a v[:,i] = w[i] v[:,i]
+        v.H v    = identity
+
+    For a real symmetric matrix ``a`` with diagonal elements `d` and
+    off-diagonal elements `e`.
+
+    Parameters
+    ----------
+    d : ndarray, shape (ndim,)
+        The diagonal elements of the array.
+    e : ndarray, shape (ndim-1,)
+        The off-diagonal elements of the array.
+    eigvals_only : bool, optional
+        Compute only the eigenvalues and no eigenvectors.
+        (Default: calculate also eigenvectors)
+    select : {'a', 'v', 'i'}, optional
+        Which eigenvalues to calculate
+
+        ======  ========================================
+        select  calculated
+        ======  ========================================
+        'a'     All eigenvalues
+        'v'     Eigenvalues in the interval (min, max]
+        'i'     Eigenvalues with indices min <= i <= max
+        ======  ========================================
+    select_range : (min, max), optional
+        Range of selected eigenvalues
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    tol : float
+        The absolute tolerance to which each eigenvalue is required
+        (only used when 'stebz' is the `lapack_driver`).
+        An eigenvalue (or cluster) is considered to have converged if it
+        lies in an interval of this width. If <= 0. (default),
+        the value ``eps*|a|`` is used where eps is the machine precision,
+        and ``|a|`` is the 1-norm of the matrix ``a``.
+    lapack_driver : str
+        LAPACK function to use, can be 'auto', 'stemr', 'stebz', 'sterf',
+        or 'stev'. When 'auto' (default), it will use 'stemr' if ``select='a'``
+        and 'stebz' otherwise. When 'stebz' is used to find the eigenvalues and
+        ``eigvals_only=False``, then a second LAPACK call (to ``?STEIN``) is
+        used to find the corresponding eigenvectors. 'sterf' can only be
+        used when ``eigvals_only=True`` and ``select='a'``. 'stev' can only
+        be used when ``select='a'``.
+
+    Returns
+    -------
+    w : (M,) ndarray
+        The eigenvalues, in ascending order, each repeated according to its
+        multiplicity.
+    v : (M, M) ndarray
+        The normalized eigenvector corresponding to the eigenvalue ``w[i]`` is
+        the column ``v[:,i]``. Only returned if ``eigvals_only=False``.
+
+    Raises
+    ------
+    LinAlgError
+        If eigenvalue computation does not converge.
+
+    See Also
+    --------
+    eigvalsh_tridiagonal : eigenvalues of symmetric/Hermitian tridiagonal
+        matrices
+    eig : eigenvalues and right eigenvectors for non-symmetric arrays
+    eigh : eigenvalues and right eigenvectors for symmetric/Hermitian arrays
+    eig_banded : eigenvalues and right eigenvectors for symmetric/Hermitian
+        band matrices
+
+    Notes
+    -----
+    This function makes use of LAPACK ``S/DSTEMR`` routines.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import eigh_tridiagonal
+    >>> d = 3*np.ones(4)
+    >>> e = -1*np.ones(3)
+    >>> w, v = eigh_tridiagonal(d, e)
+    >>> A = np.diag(d) + np.diag(e, k=1) + np.diag(e, k=-1)
+    >>> np.allclose(A @ v - v @ np.diag(w), np.zeros((4, 4)))
+    True
+    """
+    d = _asarray_validated(d, check_finite=check_finite)
+    e = _asarray_validated(e, check_finite=check_finite)
+    for check in (d, e):
+        if check.ndim != 1:
+            raise ValueError('expected a 1-D array')
+        if check.dtype.char in 'GFD':  # complex
+            raise TypeError('Only real arrays currently supported')
+    if d.size != e.size + 1:
+        raise ValueError(f'd ({d.size}) must have one more element than e ({e.size})')
+    select, vl, vu, il, iu, _ = _check_select(
+        select, select_range, 0, d.size)
+    if not isinstance(lapack_driver, str):
+        raise TypeError('lapack_driver must be str')
+    drivers = ('auto', 'stemr', 'sterf', 'stebz', 'stev')
+    if lapack_driver not in drivers:
+        raise ValueError(f'lapack_driver must be one of {drivers}, '
+                         f'got {lapack_driver}')
+    if lapack_driver == 'auto':
+        lapack_driver = 'stemr' if select == 0 else 'stebz'
+
+    # Quick exit for 1x1 case
+    if len(d) == 1:
+        if select == 1 and (not (vl < d[0] <= vu)):  # request by value
+            w = array([])
+            v = empty([1, 0], dtype=d.dtype)
+        else:  # all and request by index
+            w = array([d[0]], dtype=d.dtype)
+            v = array([[1.]], dtype=d.dtype)
+
+        if eigvals_only:
+            return w
+        else:
+            return w, v
+
+    func, = get_lapack_funcs((lapack_driver,), (d, e))
+    compute_v = not eigvals_only
+    if lapack_driver == 'sterf':
+        if select != 0:
+            raise ValueError('sterf can only be used when select == "a"')
+        if not eigvals_only:
+            raise ValueError('sterf can only be used when eigvals_only is '
+                             'True')
+        w, info = func(d, e)
+        m = len(w)
+    elif lapack_driver == 'stev':
+        if select != 0:
+            raise ValueError('stev can only be used when select == "a"')
+        w, v, info = func(d, e, compute_v=compute_v)
+        m = len(w)
+    elif lapack_driver == 'stebz':
+        tol = float(tol)
+        internal_name = 'stebz'
+        stebz, = get_lapack_funcs((internal_name,), (d, e))
+        # If getting eigenvectors, needs to be block-ordered (B) instead of
+        # matrix-ordered (E), and we will reorder later
+        order = 'E' if eigvals_only else 'B'
+        m, w, iblock, isplit, info = stebz(d, e, select, vl, vu, il, iu, tol,
+                                           order)
+    else:   # 'stemr'
+        # ?STEMR annoyingly requires size N instead of N-1
+        e_ = empty(e.size+1, e.dtype)
+        e_[:-1] = e
+        stemr_lwork, = get_lapack_funcs(('stemr_lwork',), (d, e))
+        lwork, liwork, info = stemr_lwork(d, e_, select, vl, vu, il, iu,
+                                          compute_v=compute_v)
+        _check_info(info, 'stemr_lwork')
+        m, w, v, info = func(d, e_, select, vl, vu, il, iu,
+                             compute_v=compute_v, lwork=lwork, liwork=liwork)
+    _check_info(info, lapack_driver + ' (eigh_tridiagonal)')
+    w = w[:m]
+    if eigvals_only:
+        return w
+    else:
+        # Do we still need to compute the eigenvalues?
+        if lapack_driver == 'stebz':
+            func, = get_lapack_funcs(('stein',), (d, e))
+            v, info = func(d, e, w, iblock, isplit)
+            _check_info(info, 'stein (eigh_tridiagonal)',
+                        positive='%d eigenvectors failed to converge')
+            # Convert block-order to matrix-order
+            order = argsort(w)
+            w, v = w[order], v[:, order]
+        else:
+            v = v[:, :m]
+        return w, v
+
+
+def _check_info(info, driver, positive='did not converge (LAPACK info=%d)'):
+    """Check info return value."""
+    if info < 0:
+        raise ValueError('illegal value in argument %d of internal %s'
+                         % (-info, driver))
+    if info > 0 and positive:
+        raise LinAlgError(("%s " + positive) % (driver, info,))
+
+
+def hessenberg(a, calc_q=False, overwrite_a=False, check_finite=True):
+    """
+    Compute Hessenberg form of a matrix.
+
+    The Hessenberg decomposition is::
+
+        A = Q H Q^H
+
+    where `Q` is unitary/orthogonal and `H` has only zero elements below
+    the first sub-diagonal.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to bring into Hessenberg form.
+    calc_q : bool, optional
+        Whether to compute the transformation matrix.  Default is False.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.
+        Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    H : (M, M) ndarray
+        Hessenberg form of `a`.
+    Q : (M, M) ndarray
+        Unitary/orthogonal similarity transformation matrix ``A = Q H Q^H``.
+        Only returned if ``calc_q=True``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import hessenberg
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> H, Q = hessenberg(A, calc_q=True)
+    >>> H
+    array([[  2.        , -11.65843866,   1.42005301,   0.25349066],
+           [ -9.94987437,  14.53535354,  -5.31022304,   2.43081618],
+           [  0.        ,  -1.83299243,   0.38969961,  -0.51527034],
+           [  0.        ,   0.        ,  -3.83189513,   1.07494686]])
+    >>> np.allclose(Q @ H @ Q.conj().T - A, np.zeros((4, 4)))
+    True
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
+        raise ValueError('expected square matrix')
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    if a1.size == 0:
+        h3 = hessenberg(np.eye(3, dtype=a1.dtype))
+        h = np.empty(a1.shape, dtype=h3.dtype)
+        if not calc_q:
+            return h
+        else:
+            h3, q3 = hessenberg(np.eye(3, dtype=a1.dtype), calc_q=True)
+            q = np.empty(a1.shape, dtype=q3.dtype)
+            h = np.empty(a1.shape, dtype=h3.dtype)
+            return h, q
+
+    # if 2x2 or smaller: already in Hessenberg
+    if a1.shape[0] <= 2:
+        if calc_q:
+            return a1, eye(a1.shape[0])
+        return a1
+
+    gehrd, gebal, gehrd_lwork = get_lapack_funcs(('gehrd', 'gebal',
+                                                  'gehrd_lwork'), (a1,))
+    ba, lo, hi, pivscale, info = gebal(a1, permute=0, overwrite_a=overwrite_a)
+    _check_info(info, 'gebal (hessenberg)', positive=False)
+    n = len(a1)
+
+    lwork = _compute_lwork(gehrd_lwork, ba.shape[0], lo=lo, hi=hi)
+
+    hq, tau, info = gehrd(ba, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
+    _check_info(info, 'gehrd (hessenberg)', positive=False)
+    h = np.triu(hq, -1)
+    if not calc_q:
+        return h
+
+    # use orghr/unghr to compute q
+    orghr, orghr_lwork = get_lapack_funcs(('orghr', 'orghr_lwork'), (a1,))
+    lwork = _compute_lwork(orghr_lwork, n, lo=lo, hi=hi)
+
+    q, info = orghr(a=hq, tau=tau, lo=lo, hi=hi, lwork=lwork, overwrite_a=1)
+    _check_info(info, 'orghr (hessenberg)', positive=False)
+    return h, q
+
+
+def cdf2rdf(w, v):
+    """
+    Converts complex eigenvalues ``w`` and eigenvectors ``v`` to real
+    eigenvalues in a block diagonal form ``wr`` and the associated real
+    eigenvectors ``vr``, such that::
+
+        vr @ wr = X @ vr
+
+    continues to hold, where ``X`` is the original array for which ``w`` and
+    ``v`` are the eigenvalues and eigenvectors.
+
+    .. versionadded:: 1.1.0
+
+    Parameters
+    ----------
+    w : (..., M) array_like
+        Complex or real eigenvalues, an array or stack of arrays
+
+        Conjugate pairs must not be interleaved, else the wrong result
+        will be produced. So ``[1+1j, 1, 1-1j]`` will give a correct result,
+        but ``[1+1j, 2+1j, 1-1j, 2-1j]`` will not.
+
+    v : (..., M, M) array_like
+        Complex or real eigenvectors, a square array or stack of square arrays.
+
+    Returns
+    -------
+    wr : (..., M, M) ndarray
+        Real diagonal block form of eigenvalues
+    vr : (..., M, M) ndarray
+        Real eigenvectors associated with ``wr``
+
+    See Also
+    --------
+    eig : Eigenvalues and right eigenvectors for non-symmetric arrays
+    rsf2csf : Convert real Schur form to complex Schur form
+
+    Notes
+    -----
+    ``w``, ``v`` must be the eigenstructure for some *real* matrix ``X``.
+    For example, obtained by ``w, v = scipy.linalg.eig(X)`` or
+    ``w, v = numpy.linalg.eig(X)`` in which case ``X`` can also represent
+    stacked arrays.
+
+    .. versionadded:: 1.1.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
+    >>> X
+    array([[ 1,  2,  3],
+           [ 0,  4,  5],
+           [ 0, -5,  4]])
+
+    >>> from scipy import linalg
+    >>> w, v = linalg.eig(X)
+    >>> w
+    array([ 1.+0.j,  4.+5.j,  4.-5.j])
+    >>> v
+    array([[ 1.00000+0.j     , -0.01906-0.40016j, -0.01906+0.40016j],
+           [ 0.00000+0.j     ,  0.00000-0.64788j,  0.00000+0.64788j],
+           [ 0.00000+0.j     ,  0.64788+0.j     ,  0.64788-0.j     ]])
+
+    >>> wr, vr = linalg.cdf2rdf(w, v)
+    >>> wr
+    array([[ 1.,  0.,  0.],
+           [ 0.,  4.,  5.],
+           [ 0., -5.,  4.]])
+    >>> vr
+    array([[ 1.     ,  0.40016, -0.01906],
+           [ 0.     ,  0.64788,  0.     ],
+           [ 0.     ,  0.     ,  0.64788]])
+
+    >>> vr @ wr
+    array([[ 1.     ,  1.69593,  1.9246 ],
+           [ 0.     ,  2.59153,  3.23942],
+           [ 0.     , -3.23942,  2.59153]])
+    >>> X @ vr
+    array([[ 1.     ,  1.69593,  1.9246 ],
+           [ 0.     ,  2.59153,  3.23942],
+           [ 0.     , -3.23942,  2.59153]])
+    """
+    w, v = _asarray_validated(w), _asarray_validated(v)
+
+    # check dimensions
+    if w.ndim < 1:
+        raise ValueError('expected w to be at least 1D')
+    if v.ndim < 2:
+        raise ValueError('expected v to be at least 2D')
+    if v.ndim != w.ndim + 1:
+        raise ValueError('expected eigenvectors array to have exactly one '
+                         'dimension more than eigenvalues array')
+
+    # check shapes
+    n = w.shape[-1]
+    M = w.shape[:-1]
+    if v.shape[-2] != v.shape[-1]:
+        raise ValueError('expected v to be a square matrix or stacked square '
+                         'matrices: v.shape[-2] = v.shape[-1]')
+    if v.shape[-1] != n:
+        raise ValueError('expected the same number of eigenvalues as '
+                         'eigenvectors')
+
+    # get indices for each first pair of complex eigenvalues
+    complex_mask = iscomplex(w)
+    n_complex = complex_mask.sum(axis=-1)
+
+    # check if all complex eigenvalues have conjugate pairs
+    if not (n_complex % 2 == 0).all():
+        raise ValueError('expected complex-conjugate pairs of eigenvalues')
+
+    # find complex indices
+    idx = nonzero(complex_mask)
+    idx_stack = idx[:-1]
+    idx_elem = idx[-1]
+
+    # filter them to conjugate indices, assuming pairs are not interleaved
+    j = idx_elem[0::2]
+    k = idx_elem[1::2]
+    stack_ind = ()
+    for i in idx_stack:
+        # should never happen, assuming nonzero orders by the last axis
+        assert (i[0::2] == i[1::2]).all(), \
+                "Conjugate pair spanned different arrays!"
+        stack_ind += (i[0::2],)
+
+    # all eigenvalues to diagonal form
+    wr = zeros(M + (n, n), dtype=w.real.dtype)
+    di = range(n)
+    wr[..., di, di] = w.real
+
+    # complex eigenvalues to real block diagonal form
+    wr[stack_ind + (j, k)] = w[stack_ind + (j,)].imag
+    wr[stack_ind + (k, j)] = w[stack_ind + (k,)].imag
+
+    # compute real eigenvectors associated with real block diagonal eigenvalues
+    u = zeros(M + (n, n), dtype=np.cdouble)
+    u[..., di, di] = 1.0
+    u[stack_ind + (j, j)] = 0.5j
+    u[stack_ind + (j, k)] = 0.5
+    u[stack_ind + (k, j)] = -0.5j
+    u[stack_ind + (k, k)] = 0.5
+
+    # multiply matrices v and u (equivalent to v @ u)
+    vr = einsum('...ij,...jk->...ik', v, u).real
+
+    return wr, vr
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..c35b6a4920dea6bb638fe54a1fa719ebc74fb773
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cholesky.py
@@ -0,0 +1,398 @@
+"""Cholesky decomposition functions."""
+
+import numpy as np
+from numpy import asarray_chkfinite, asarray, atleast_2d, empty_like
+
+# Local imports
+from ._misc import LinAlgError, _datacopied
+from .lapack import get_lapack_funcs
+
+__all__ = ['cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
+           'cho_solve_banded']
+
+
+def _cholesky(a, lower=False, overwrite_a=False, clean=True,
+              check_finite=True):
+    """Common code for cholesky() and cho_factor()."""
+
+    a1 = asarray_chkfinite(a) if check_finite else asarray(a)
+    a1 = atleast_2d(a1)
+
+    # Dimension check
+    if a1.ndim != 2:
+        raise ValueError(f'Input array needs to be 2D but received a {a1.ndim}d-array.')
+    # Squareness check
+    if a1.shape[0] != a1.shape[1]:
+        raise ValueError('Input array is expected to be square but has '
+                         f'the shape: {a1.shape}.')
+
+    # Quick return for square empty array
+    if a1.size == 0:
+        dt = cholesky(np.eye(1, dtype=a1.dtype)).dtype
+        return empty_like(a1, dtype=dt), lower
+
+    overwrite_a = overwrite_a or _datacopied(a1, a)
+    potrf, = get_lapack_funcs(('potrf',), (a1,))
+    c, info = potrf(a1, lower=lower, overwrite_a=overwrite_a, clean=clean)
+    if info > 0:
+        raise LinAlgError("%d-th leading minor of the array is not positive "
+                          "definite" % info)
+    if info < 0:
+        raise ValueError(f'LAPACK reported an illegal value in {-info}-th argument'
+                         'on entry to "POTRF".')
+    return c, lower
+
+
+def cholesky(a, lower=False, overwrite_a=False, check_finite=True):
+    """
+    Compute the Cholesky decomposition of a matrix.
+
+    Returns the Cholesky decomposition, :math:`A = L L^*` or
+    :math:`A = U^* U` of a Hermitian positive-definite matrix A.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to be decomposed
+    lower : bool, optional
+        Whether to compute the upper- or lower-triangular Cholesky
+        factorization. During decomposition, only the selected half of the
+        matrix is referenced. Default is upper-triangular.
+    overwrite_a : bool, optional
+        Whether to overwrite data in `a` (may improve performance).
+    check_finite : bool, optional
+        Whether to check that the entire input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    c : (M, M) ndarray
+        Upper- or lower-triangular Cholesky factor of `a`.
+
+    Raises
+    ------
+    LinAlgError : if decomposition fails.
+
+    Notes
+    -----
+    During the finiteness check (if selected), the entire matrix `a` is
+    checked. During decomposition, `a` is assumed to be symmetric or Hermitian
+    (as applicable), and only the half selected by option `lower` is referenced.
+    Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still
+    succeed if the symmetric/Hermitian matrix represented by the selected half
+    is positive definite, yet it may fail if an element in the other half is
+    non-finite.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cholesky
+    >>> a = np.array([[1,-2j],[2j,5]])
+    >>> L = cholesky(a, lower=True)
+    >>> L
+    array([[ 1.+0.j,  0.+0.j],
+           [ 0.+2.j,  1.+0.j]])
+    >>> L @ L.T.conj()
+    array([[ 1.+0.j,  0.-2.j],
+           [ 0.+2.j,  5.+0.j]])
+
+    """
+    c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=True,
+                         check_finite=check_finite)
+    return c
+
+
+def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):
+    """
+    Compute the Cholesky decomposition of a matrix, to use in cho_solve
+
+    Returns a matrix containing the Cholesky decomposition,
+    ``A = L L*`` or ``A = U* U`` of a Hermitian positive-definite matrix `a`.
+    The return value can be directly used as the first parameter to cho_solve.
+
+    .. warning::
+        The returned matrix also contains random data in the entries not
+        used by the Cholesky decomposition. If you need to zero these
+        entries, use the function `cholesky` instead.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to be decomposed
+    lower : bool, optional
+        Whether to compute the upper or lower triangular Cholesky factorization.
+        During decomposition, only the selected half of the matrix is referenced.
+        (Default: upper-triangular)
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+    check_finite : bool, optional
+        Whether to check that the entire input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    c : (M, M) ndarray
+        Matrix whose upper or lower triangle contains the Cholesky factor
+        of `a`. Other parts of the matrix contain random data.
+    lower : bool
+        Flag indicating whether the factor is in the lower or upper triangle
+
+    Raises
+    ------
+    LinAlgError
+        Raised if decomposition fails.
+
+    See Also
+    --------
+    cho_solve : Solve a linear set equations using the Cholesky factorization
+                of a matrix.
+
+    Notes
+    -----
+    During the finiteness check (if selected), the entire matrix `a` is
+    checked. During decomposition, `a` is assumed to be symmetric or Hermitian
+    (as applicable), and only the half selected by option `lower` is referenced.
+    Consequently, if `a` is asymmetric/non-Hermitian, `cholesky` may still
+    succeed if the symmetric/Hermitian matrix represented by the selected half
+    is positive definite, yet it may fail if an element in the other half is
+    non-finite.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cho_factor
+    >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]])
+    >>> c, low = cho_factor(A)
+    >>> c
+    array([[3.        , 1.        , 0.33333333, 1.66666667],
+           [3.        , 2.44948974, 1.90515869, -0.27216553],
+           [1.        , 5.        , 2.29330749, 0.8559528 ],
+           [5.        , 1.        , 2.        , 1.55418563]])
+    >>> np.allclose(np.triu(c).T @ np. triu(c) - A, np.zeros((4, 4)))
+    True
+
+    """
+    c, lower = _cholesky(a, lower=lower, overwrite_a=overwrite_a, clean=False,
+                         check_finite=check_finite)
+    return c, lower
+
+
+def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):
+    """Solve the linear equations A x = b, given the Cholesky factorization of A.
+
+    Parameters
+    ----------
+    (c, lower) : tuple, (array, bool)
+        Cholesky factorization of a, as given by cho_factor
+    b : array
+        Right-hand side
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may improve performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : array
+        The solution to the system A x = b
+
+    See Also
+    --------
+    cho_factor : Cholesky factorization of a matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cho_factor, cho_solve
+    >>> A = np.array([[9, 3, 1, 5], [3, 7, 5, 1], [1, 5, 9, 2], [5, 1, 2, 6]])
+    >>> c, low = cho_factor(A)
+    >>> x = cho_solve((c, low), [1, 1, 1, 1])
+    >>> np.allclose(A @ x - [1, 1, 1, 1], np.zeros(4))
+    True
+
+    """
+    (c, lower) = c_and_lower
+    if check_finite:
+        b1 = asarray_chkfinite(b)
+        c = asarray_chkfinite(c)
+    else:
+        b1 = asarray(b)
+        c = asarray(c)
+
+    if c.ndim != 2 or c.shape[0] != c.shape[1]:
+        raise ValueError("The factored matrix c is not square.")
+    if c.shape[1] != b1.shape[0]:
+        raise ValueError(f"incompatible dimensions ({c.shape} and {b1.shape})")
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        dt = cho_solve((np.eye(2, dtype=b1.dtype), True),
+                        np.ones(2, dtype=c.dtype)).dtype
+        return empty_like(b1, dtype=dt)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    potrs, = get_lapack_funcs(('potrs',), (c, b1))
+    x, info = potrs(c, b1, lower=lower, overwrite_b=overwrite_b)
+    if info != 0:
+        raise ValueError('illegal value in %dth argument of internal potrs'
+                         % -info)
+    return x
+
+
+def cholesky_banded(ab, overwrite_ab=False, lower=False, check_finite=True):
+    """
+    Cholesky decompose a banded Hermitian positive-definite matrix
+
+    The matrix a is stored in ab either in lower-diagonal or upper-
+    diagonal ordered form::
+
+        ab[u + i - j, j] == a[i,j]        (if upper form; i <= j)
+        ab[    i - j, j] == a[i,j]        (if lower form; i >= j)
+
+    Example of ab (shape of a is (6,6), u=2)::
+
+        upper form:
+        *   *   a02 a13 a24 a35
+        *   a01 a12 a23 a34 a45
+        a00 a11 a22 a33 a44 a55
+
+        lower form:
+        a00 a11 a22 a33 a44 a55
+        a10 a21 a32 a43 a54 *
+        a20 a31 a42 a53 *   *
+
+    Parameters
+    ----------
+    ab : (u + 1, M) array_like
+        Banded matrix
+    overwrite_ab : bool, optional
+        Discard data in ab (may enhance performance)
+    lower : bool, optional
+        Is the matrix in the lower form. (Default is upper form)
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    c : (u + 1, M) ndarray
+        Cholesky factorization of a, in the same banded format as ab
+
+    See Also
+    --------
+    cho_solve_banded :
+        Solve a linear set equations, given the Cholesky factorization
+        of a banded Hermitian.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cholesky_banded
+    >>> from numpy import allclose, zeros, diag
+    >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
+    >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
+    >>> A = A + A.conj().T + np.diag(Ab[2, :])
+    >>> c = cholesky_banded(Ab)
+    >>> C = np.diag(c[0, 2:], k=2) + np.diag(c[1, 1:], k=1) + np.diag(c[2, :])
+    >>> np.allclose(C.conj().T @ C - A, np.zeros((5, 5)))
+    True
+
+    """
+    if check_finite:
+        ab = asarray_chkfinite(ab)
+    else:
+        ab = asarray(ab)
+
+    # accommodate square empty matrices
+    if ab.size == 0:
+        dt = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=ab.dtype)).dtype
+        return empty_like(ab, dtype=dt)
+
+    pbtrf, = get_lapack_funcs(('pbtrf',), (ab,))
+    c, info = pbtrf(ab, lower=lower, overwrite_ab=overwrite_ab)
+    if info > 0:
+        raise LinAlgError("%d-th leading minor not positive definite" % info)
+    if info < 0:
+        raise ValueError('illegal value in %d-th argument of internal pbtrf'
+                         % -info)
+    return c
+
+
+def cho_solve_banded(cb_and_lower, b, overwrite_b=False, check_finite=True):
+    """
+    Solve the linear equations ``A x = b``, given the Cholesky factorization of
+    the banded Hermitian ``A``.
+
+    Parameters
+    ----------
+    (cb, lower) : tuple, (ndarray, bool)
+        `cb` is the Cholesky factorization of A, as given by cholesky_banded.
+        `lower` must be the same value that was given to cholesky_banded.
+    b : array_like
+        Right-hand side
+    overwrite_b : bool, optional
+        If True, the function will overwrite the values in `b`.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : array
+        The solution to the system A x = b
+
+    See Also
+    --------
+    cholesky_banded : Cholesky factorization of a banded matrix
+
+    Notes
+    -----
+
+    .. versionadded:: 0.8.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cholesky_banded, cho_solve_banded
+    >>> Ab = np.array([[0, 0, 1j, 2, 3j], [0, -1, -2, 3, 4], [9, 8, 7, 6, 9]])
+    >>> A = np.diag(Ab[0,2:], k=2) + np.diag(Ab[1,1:], k=1)
+    >>> A = A + A.conj().T + np.diag(Ab[2, :])
+    >>> c = cholesky_banded(Ab)
+    >>> x = cho_solve_banded((c, False), np.ones(5))
+    >>> np.allclose(A @ x - np.ones(5), np.zeros(5))
+    True
+
+    """
+    (cb, lower) = cb_and_lower
+    if check_finite:
+        cb = asarray_chkfinite(cb)
+        b = asarray_chkfinite(b)
+    else:
+        cb = asarray(cb)
+        b = asarray(b)
+
+    # Validate shapes.
+    if cb.shape[-1] != b.shape[0]:
+        raise ValueError("shapes of cb and b are not compatible.")
+
+    # accommodate empty arrays
+    if b.size == 0:
+        m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=cb.dtype))
+        dt = cho_solve_banded((m, True), np.ones(2, dtype=b.dtype)).dtype
+        return empty_like(b, dtype=dt)
+
+    pbtrs, = get_lapack_funcs(('pbtrs',), (cb, b))
+    x, info = pbtrs(cb, b, lower=lower, overwrite_b=overwrite_b)
+    if info > 0:
+        raise LinAlgError("%dth leading minor not positive definite" % info)
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of internal pbtrs'
+                         % -info)
+    return x
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py
new file mode 100644
index 0000000000000000000000000000000000000000..e10c04fe5ebc196e1b84724b25f0fc20a5e46857
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_cossin.py
@@ -0,0 +1,221 @@
+from collections.abc import Iterable
+import numpy as np
+
+from scipy._lib._util import _asarray_validated
+from scipy.linalg import block_diag, LinAlgError
+from .lapack import _compute_lwork, get_lapack_funcs
+
+__all__ = ['cossin']
+
+
+def cossin(X, p=None, q=None, separate=False,
+           swap_sign=False, compute_u=True, compute_vh=True):
+    """
+    Compute the cosine-sine (CS) decomposition of an orthogonal/unitary matrix.
+
+    X is an ``(m, m)`` orthogonal/unitary matrix, partitioned as the following
+    where upper left block has the shape of ``(p, q)``::
+
+                                   ┌                   ┐
+                                   │ I  0  0 │ 0  0  0 │
+        ┌           ┐   ┌         ┐│ 0  C  0 │ 0 -S  0 │┌         ┐*
+        │ X11 │ X12 │   │ U1 │    ││ 0  0  0 │ 0  0 -I ││ V1 │    │
+        │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│
+        │ X21 │ X22 │   │    │ U2 ││ 0  0  0 │ I  0  0 ││    │ V2 │
+        └           ┘   └         ┘│ 0  S  0 │ 0  C  0 │└         ┘
+                                   │ 0  0  I │ 0  0  0 │
+                                   └                   ┘
+
+    ``U1``, ``U2``, ``V1``, ``V2`` are square orthogonal/unitary matrices of
+    dimensions ``(p,p)``, ``(m-p,m-p)``, ``(q,q)``, and ``(m-q,m-q)``
+    respectively, and ``C`` and ``S`` are ``(r, r)`` nonnegative diagonal
+    matrices satisfying ``C^2 + S^2 = I`` where ``r = min(p, m-p, q, m-q)``.
+
+    Moreover, the rank of the identity matrices are ``min(p, q) - r``,
+    ``min(p, m - q) - r``, ``min(m - p, q) - r``, and ``min(m - p, m - q) - r``
+    respectively.
+
+    X can be supplied either by itself and block specifications p, q or its
+    subblocks in an iterable from which the shapes would be derived. See the
+    examples below.
+
+    Parameters
+    ----------
+    X : array_like, iterable
+        complex unitary or real orthogonal matrix to be decomposed, or iterable
+        of subblocks ``X11``, ``X12``, ``X21``, ``X22``, when ``p``, ``q`` are
+        omitted.
+    p : int, optional
+        Number of rows of the upper left block ``X11``, used only when X is
+        given as an array.
+    q : int, optional
+        Number of columns of the upper left block ``X11``, used only when X is
+        given as an array.
+    separate : bool, optional
+        if ``True``, the low level components are returned instead of the
+        matrix factors, i.e. ``(u1,u2)``, ``theta``, ``(v1h,v2h)`` instead of
+        ``u``, ``cs``, ``vh``.
+    swap_sign : bool, optional
+        if ``True``, the ``-S``, ``-I`` block will be the bottom left,
+        otherwise (by default) they will be in the upper right block.
+    compute_u : bool, optional
+        if ``False``, ``u`` won't be computed and an empty array is returned.
+    compute_vh : bool, optional
+        if ``False``, ``vh`` won't be computed and an empty array is returned.
+
+    Returns
+    -------
+    u : ndarray
+        When ``compute_u=True``, contains the block diagonal orthogonal/unitary
+        matrix consisting of the blocks ``U1`` (``p`` x ``p``) and ``U2``
+        (``m-p`` x ``m-p``) orthogonal/unitary matrices. If ``separate=True``,
+        this contains the tuple of ``(U1, U2)``.
+    cs : ndarray
+        The cosine-sine factor with the structure described above.
+         If ``separate=True``, this contains the ``theta`` array containing the
+         angles in radians.
+    vh : ndarray
+        When ``compute_vh=True`, contains the block diagonal orthogonal/unitary
+        matrix consisting of the blocks ``V1H`` (``q`` x ``q``) and ``V2H``
+        (``m-q`` x ``m-q``) orthogonal/unitary matrices. If ``separate=True``,
+        this contains the tuple of ``(V1H, V2H)``.
+
+    References
+    ----------
+    .. [1] Brian D. Sutton. Computing the complete CS decomposition. Numer.
+           Algorithms, 50(1):33-65, 2009.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import cossin
+    >>> from scipy.stats import unitary_group
+    >>> x = unitary_group.rvs(4)
+    >>> u, cs, vdh = cossin(x, p=2, q=2)
+    >>> np.allclose(x, u @ cs @ vdh)
+    True
+
+    Same can be entered via subblocks without the need of ``p`` and ``q``. Also
+    let's skip the computation of ``u``
+
+    >>> ue, cs, vdh = cossin((x[:2, :2], x[:2, 2:], x[2:, :2], x[2:, 2:]),
+    ...                      compute_u=False)
+    >>> print(ue)
+    []
+    >>> np.allclose(x, u @ cs @ vdh)
+    True
+
+    """
+
+    if p or q:
+        p = 1 if p is None else int(p)
+        q = 1 if q is None else int(q)
+        X = _asarray_validated(X, check_finite=True)
+        if not np.equal(*X.shape):
+            raise ValueError("Cosine Sine decomposition only supports square"
+                             f" matrices, got {X.shape}")
+        m = X.shape[0]
+        if p >= m or p <= 0:
+            raise ValueError(f"invalid p={p}, 0= m or q <= 0:
+            raise ValueError(f"invalid q={q}, 0 0:
+        raise LinAlgError(f"{method_name} did not converge: {info}")
+
+    if separate:
+        return (u1, u2), theta, (v1h, v2h)
+
+    U = block_diag(u1, u2)
+    VDH = block_diag(v1h, v2h)
+
+    # Construct the middle factor CS
+    c = np.diag(np.cos(theta))
+    s = np.diag(np.sin(theta))
+    r = min(p, q, m - p, m - q)
+    n11 = min(p, q) - r
+    n12 = min(p, m - q) - r
+    n21 = min(m - p, q) - r
+    n22 = min(m - p, m - q) - r
+    Id = np.eye(np.max([n11, n12, n21, n22, r]), dtype=theta.dtype)
+    CS = np.zeros((m, m), dtype=theta.dtype)
+
+    CS[:n11, :n11] = Id[:n11, :n11]
+
+    xs = n11 + r
+    xe = n11 + r + n12
+    ys = n11 + n21 + n22 + 2 * r
+    ye = n11 + n21 + n22 + 2 * r + n12
+    CS[xs: xe, ys:ye] = Id[:n12, :n12] if swap_sign else -Id[:n12, :n12]
+
+    xs = p + n22 + r
+    xe = p + n22 + r + + n21
+    ys = n11 + r
+    ye = n11 + r + n21
+    CS[xs:xe, ys:ye] = -Id[:n21, :n21] if swap_sign else Id[:n21, :n21]
+
+    CS[p:p + n22, q:q + n22] = Id[:n22, :n22]
+    CS[n11:n11 + r, n11:n11 + r] = c
+    CS[p + n22:p + n22 + r, n11 + r + n21 + n22:2 * r + n11 + n21 + n22] = c
+
+    xs = n11
+    xe = n11 + r
+    ys = n11 + n21 + n22 + r
+    ye = n11 + n21 + n22 + 2 * r
+    CS[xs:xe, ys:ye] = s if swap_sign else -s
+
+    CS[p + n22:p + n22 + r, n11:n11 + r] = -s if swap_sign else s
+
+    return U, CS, VDH
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py
new file mode 100644
index 0000000000000000000000000000000000000000..336df1d5fb416f635c91afe3cc2cfb3c340239fc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_ldl.py
@@ -0,0 +1,353 @@
+from warnings import warn
+
+import numpy as np
+from numpy import (atleast_2d, arange, zeros_like, imag, diag,
+                   iscomplexobj, tril, triu, argsort, empty_like)
+from scipy._lib._util import ComplexWarning
+from ._decomp import _asarray_validated
+from .lapack import get_lapack_funcs, _compute_lwork
+
+__all__ = ['ldl']
+
+
+def ldl(A, lower=True, hermitian=True, overwrite_a=False, check_finite=True):
+    """ Computes the LDLt or Bunch-Kaufman factorization of a symmetric/
+    hermitian matrix.
+
+    This function returns a block diagonal matrix D consisting blocks of size
+    at most 2x2 and also a possibly permuted unit lower triangular matrix
+    ``L`` such that the factorization ``A = L D L^H`` or ``A = L D L^T``
+    holds. If `lower` is False then (again possibly permuted) upper
+    triangular matrices are returned as outer factors.
+
+    The permutation array can be used to triangularize the outer factors
+    simply by a row shuffle, i.e., ``lu[perm, :]`` is an upper/lower
+    triangular matrix. This is also equivalent to multiplication with a
+    permutation matrix ``P.dot(lu)``, where ``P`` is a column-permuted
+    identity matrix ``I[:, perm]``.
+
+    Depending on the value of the boolean `lower`, only upper or lower
+    triangular part of the input array is referenced. Hence, a triangular
+    matrix on entry would give the same result as if the full matrix is
+    supplied.
+
+    Parameters
+    ----------
+    A : array_like
+        Square input array
+    lower : bool, optional
+        This switches between the lower and upper triangular outer factors of
+        the factorization. Lower triangular (``lower=True``) is the default.
+    hermitian : bool, optional
+        For complex-valued arrays, this defines whether ``A = A.conj().T`` or
+        ``A = A.T`` is assumed. For real-valued arrays, this switch has no
+        effect.
+    overwrite_a : bool, optional
+        Allow overwriting data in `A` (may enhance performance). The default
+        is False.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    lu : ndarray
+        The (possibly) permuted upper/lower triangular outer factor of the
+        factorization.
+    d : ndarray
+        The block diagonal multiplier of the factorization.
+    perm : ndarray
+        The row-permutation index array that brings lu into triangular form.
+
+    Raises
+    ------
+    ValueError
+        If input array is not square.
+    ComplexWarning
+        If a complex-valued array with nonzero imaginary parts on the
+        diagonal is given and hermitian is set to True.
+
+    See Also
+    --------
+    cholesky, lu
+
+    Notes
+    -----
+    This function uses ``?SYTRF`` routines for symmetric matrices and
+    ``?HETRF`` routines for Hermitian matrices from LAPACK. See [1]_ for
+    the algorithm details.
+
+    Depending on the `lower` keyword value, only lower or upper triangular
+    part of the input array is referenced. Moreover, this keyword also defines
+    the structure of the outer factors of the factorization.
+
+    .. versionadded:: 1.1.0
+
+    References
+    ----------
+    .. [1] J.R. Bunch, L. Kaufman, Some stable methods for calculating
+       inertia and solving symmetric linear systems, Math. Comput. Vol.31,
+       1977. :doi:`10.2307/2005787`
+
+    Examples
+    --------
+    Given an upper triangular array ``a`` that represents the full symmetric
+    array with its entries, obtain ``l``, 'd' and the permutation vector `perm`:
+
+    >>> import numpy as np
+    >>> from scipy.linalg import ldl
+    >>> a = np.array([[2, -1, 3], [0, 2, 0], [0, 0, 1]])
+    >>> lu, d, perm = ldl(a, lower=0) # Use the upper part
+    >>> lu
+    array([[ 0. ,  0. ,  1. ],
+           [ 0. ,  1. , -0.5],
+           [ 1. ,  1. ,  1.5]])
+    >>> d
+    array([[-5. ,  0. ,  0. ],
+           [ 0. ,  1.5,  0. ],
+           [ 0. ,  0. ,  2. ]])
+    >>> perm
+    array([2, 1, 0])
+    >>> lu[perm, :]
+    array([[ 1. ,  1. ,  1.5],
+           [ 0. ,  1. , -0.5],
+           [ 0. ,  0. ,  1. ]])
+    >>> lu.dot(d).dot(lu.T)
+    array([[ 2., -1.,  3.],
+           [-1.,  2.,  0.],
+           [ 3.,  0.,  1.]])
+
+    """
+    a = atleast_2d(_asarray_validated(A, check_finite=check_finite))
+    if a.shape[0] != a.shape[1]:
+        raise ValueError('The input array "a" should be square.')
+    # Return empty arrays for empty square input
+    if a.size == 0:
+        return empty_like(a), empty_like(a), np.array([], dtype=int)
+
+    n = a.shape[0]
+    r_or_c = complex if iscomplexobj(a) else float
+
+    # Get the LAPACK routine
+    if r_or_c is complex and hermitian:
+        s, sl = 'hetrf', 'hetrf_lwork'
+        if np.any(imag(diag(a))):
+            warn('scipy.linalg.ldl():\nThe imaginary parts of the diagonal'
+                 'are ignored. Use "hermitian=False" for factorization of'
+                 'complex symmetric arrays.', ComplexWarning, stacklevel=2)
+    else:
+        s, sl = 'sytrf', 'sytrf_lwork'
+
+    solver, solver_lwork = get_lapack_funcs((s, sl), (a,))
+    lwork = _compute_lwork(solver_lwork, n, lower=lower)
+    ldu, piv, info = solver(a, lwork=lwork, lower=lower,
+                            overwrite_a=overwrite_a)
+    if info < 0:
+        raise ValueError(f'{s.upper()} exited with the internal error "illegal value '
+                         f'in argument number {-info}". See LAPACK documentation '
+                         'for the error codes.')
+
+    swap_arr, pivot_arr = _ldl_sanitize_ipiv(piv, lower=lower)
+    d, lu = _ldl_get_d_and_l(ldu, pivot_arr, lower=lower, hermitian=hermitian)
+    lu, perm = _ldl_construct_tri_factor(lu, swap_arr, pivot_arr, lower=lower)
+
+    return lu, d, perm
+
+
+def _ldl_sanitize_ipiv(a, lower=True):
+    """
+    This helper function takes the rather strangely encoded permutation array
+    returned by the LAPACK routines ?(HE/SY)TRF and converts it into
+    regularized permutation and diagonal pivot size format.
+
+    Since FORTRAN uses 1-indexing and LAPACK uses different start points for
+    upper and lower formats there are certain offsets in the indices used
+    below.
+
+    Let's assume a result where the matrix is 6x6 and there are two 2x2
+    and two 1x1 blocks reported by the routine. To ease the coding efforts,
+    we still populate a 6-sized array and fill zeros as the following ::
+
+        pivots = [2, 0, 2, 0, 1, 1]
+
+    This denotes a diagonal matrix of the form ::
+
+        [x x        ]
+        [x x        ]
+        [    x x    ]
+        [    x x    ]
+        [        x  ]
+        [          x]
+
+    In other words, we write 2 when the 2x2 block is first encountered and
+    automatically write 0 to the next entry and skip the next spin of the
+    loop. Thus, a separate counter or array appends to keep track of block
+    sizes are avoided. If needed, zeros can be filtered out later without
+    losing the block structure.
+
+    Parameters
+    ----------
+    a : ndarray
+        The permutation array ipiv returned by LAPACK
+    lower : bool, optional
+        The switch to select whether upper or lower triangle is chosen in
+        the LAPACK call.
+
+    Returns
+    -------
+    swap_ : ndarray
+        The array that defines the row/column swap operations. For example,
+        if row two is swapped with row four, the result is [0, 3, 2, 3].
+    pivots : ndarray
+        The array that defines the block diagonal structure as given above.
+
+    """
+    n = a.size
+    swap_ = arange(n)
+    pivots = zeros_like(swap_, dtype=int)
+    skip_2x2 = False
+
+    # Some upper/lower dependent offset values
+    # range (s)tart, r(e)nd, r(i)ncrement
+    x, y, rs, re, ri = (1, 0, 0, n, 1) if lower else (-1, -1, n-1, -1, -1)
+
+    for ind in range(rs, re, ri):
+        # If previous spin belonged already to a 2x2 block
+        if skip_2x2:
+            skip_2x2 = False
+            continue
+
+        cur_val = a[ind]
+        # do we have a 1x1 block or not?
+        if cur_val > 0:
+            if cur_val != ind+1:
+                # Index value != array value --> permutation required
+                swap_[ind] = swap_[cur_val-1]
+            pivots[ind] = 1
+        # Not.
+        elif cur_val < 0 and cur_val == a[ind+x]:
+            # first neg entry of 2x2 block identifier
+            if -cur_val != ind+2:
+                # Index value != array value --> permutation required
+                swap_[ind+x] = swap_[-cur_val-1]
+            pivots[ind+y] = 2
+            skip_2x2 = True
+        else:  # Doesn't make sense, give up
+            raise ValueError('While parsing the permutation array '
+                             'in "scipy.linalg.ldl", invalid entries '
+                             'found. The array syntax is invalid.')
+    return swap_, pivots
+
+
+def _ldl_get_d_and_l(ldu, pivs, lower=True, hermitian=True):
+    """
+    Helper function to extract the diagonal and triangular matrices for
+    LDL.T factorization.
+
+    Parameters
+    ----------
+    ldu : ndarray
+        The compact output returned by the LAPACK routing
+    pivs : ndarray
+        The sanitized array of {0, 1, 2} denoting the sizes of the pivots. For
+        every 2 there is a succeeding 0.
+    lower : bool, optional
+        If set to False, upper triangular part is considered.
+    hermitian : bool, optional
+        If set to False a symmetric complex array is assumed.
+
+    Returns
+    -------
+    d : ndarray
+        The block diagonal matrix.
+    lu : ndarray
+        The upper/lower triangular matrix
+    """
+    is_c = iscomplexobj(ldu)
+    d = diag(diag(ldu))
+    n = d.shape[0]
+    blk_i = 0  # block index
+
+    # row/column offsets for selecting sub-, super-diagonal
+    x, y = (1, 0) if lower else (0, 1)
+
+    lu = tril(ldu, -1) if lower else triu(ldu, 1)
+    diag_inds = arange(n)
+    lu[diag_inds, diag_inds] = 1
+
+    for blk in pivs[pivs != 0]:
+        # increment the block index and check for 2s
+        # if 2 then copy the off diagonals depending on uplo
+        inc = blk_i + blk
+
+        if blk == 2:
+            d[blk_i+x, blk_i+y] = ldu[blk_i+x, blk_i+y]
+            # If Hermitian matrix is factorized, the cross-offdiagonal element
+            # should be conjugated.
+            if is_c and hermitian:
+                d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y].conj()
+            else:
+                d[blk_i+y, blk_i+x] = ldu[blk_i+x, blk_i+y]
+
+            lu[blk_i+x, blk_i+y] = 0.
+        blk_i = inc
+
+    return d, lu
+
+
+def _ldl_construct_tri_factor(lu, swap_vec, pivs, lower=True):
+    """
+    Helper function to construct explicit outer factors of LDL factorization.
+
+    If lower is True the permuted factors are multiplied as L(1)*L(2)*...*L(k).
+    Otherwise, the permuted factors are multiplied as L(k)*...*L(2)*L(1). See
+    LAPACK documentation for more details.
+
+    Parameters
+    ----------
+    lu : ndarray
+        The triangular array that is extracted from LAPACK routine call with
+        ones on the diagonals.
+    swap_vec : ndarray
+        The array that defines the row swapping indices. If the kth entry is m
+        then rows k,m are swapped. Notice that the mth entry is not necessarily
+        k to avoid undoing the swapping.
+    pivs : ndarray
+        The array that defines the block diagonal structure returned by
+        _ldl_sanitize_ipiv().
+    lower : bool, optional
+        The boolean to switch between lower and upper triangular structure.
+
+    Returns
+    -------
+    lu : ndarray
+        The square outer factor which satisfies the L * D * L.T = A
+    perm : ndarray
+        The permutation vector that brings the lu to the triangular form
+
+    Notes
+    -----
+    Note that the original argument "lu" is overwritten.
+
+    """
+    n = lu.shape[0]
+    perm = arange(n)
+    # Setup the reading order of the permutation matrix for upper/lower
+    rs, re, ri = (n-1, -1, -1) if lower else (0, n, 1)
+
+    for ind in range(rs, re, ri):
+        s_ind = swap_vec[ind]
+        if s_ind != ind:
+            # Column start and end positions
+            col_s = ind if lower else 0
+            col_e = n if lower else ind+1
+
+            # If we stumble upon a 2x2 block include both cols in the perm.
+            if pivs[ind] == (0 if lower else 2):
+                col_s += -1 if lower else 0
+                col_e += 0 if lower else 1
+            lu[[s_ind, ind], col_s:col_e] = lu[[ind, s_ind], col_s:col_e]
+            perm[[s_ind, ind]] = perm[[ind, s_ind]]
+
+    return lu, argsort(perm)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..06562a4a490a4328c08d4de45a5463427e33562b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu.py
@@ -0,0 +1,389 @@
+"""LU decomposition functions."""
+
+from warnings import warn
+
+from numpy import asarray, asarray_chkfinite
+import numpy as np
+from itertools import product
+
+# Local imports
+from ._misc import _datacopied, LinAlgWarning
+from .lapack import get_lapack_funcs
+from ._decomp_lu_cython import lu_dispatcher
+
+lapack_cast_dict = {x: ''.join([y for y in 'fdFD' if np.can_cast(x, y)])
+                    for x in np.typecodes['All']}
+
+__all__ = ['lu', 'lu_solve', 'lu_factor']
+
+
+def lu_factor(a, overwrite_a=False, check_finite=True):
+    """
+    Compute pivoted LU decomposition of a matrix.
+
+    The decomposition is::
+
+        A = P L U
+
+    where P is a permutation matrix, L lower triangular with unit
+    diagonal elements, and U upper triangular.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to decompose
+    overwrite_a : bool, optional
+        Whether to overwrite data in A (may increase performance)
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    lu : (M, N) ndarray
+        Matrix containing U in its upper triangle, and L in its lower triangle.
+        The unit diagonal elements of L are not stored.
+    piv : (K,) ndarray
+        Pivot indices representing the permutation matrix P:
+        row i of matrix was interchanged with row piv[i].
+        Of shape ``(K,)``, with ``K = min(M, N)``.
+
+    See Also
+    --------
+    lu : gives lu factorization in more user-friendly format
+    lu_solve : solve an equation system using the LU factorization of a matrix
+
+    Notes
+    -----
+    This is a wrapper to the ``*GETRF`` routines from LAPACK. Unlike
+    :func:`lu`, it outputs the L and U factors into a single array
+    and returns pivot indices instead of a permutation matrix.
+
+    While the underlying ``*GETRF`` routines return 1-based pivot indices, the
+    ``piv`` array returned by ``lu_factor`` contains 0-based indices.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import lu_factor
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> lu, piv = lu_factor(A)
+    >>> piv
+    array([2, 2, 3, 3], dtype=int32)
+
+    Convert LAPACK's ``piv`` array to NumPy index and test the permutation
+
+    >>> def pivot_to_permutation(piv):
+    ...     perm = np.arange(len(piv))
+    ...     for i in range(len(piv)):
+    ...         perm[i], perm[piv[i]] = perm[piv[i]], perm[i]
+    ...     return perm
+    ...
+    >>> p_inv = pivot_to_permutation(piv)
+    >>> p_inv
+    array([2, 0, 3, 1])
+    >>> L, U = np.tril(lu, k=-1) + np.eye(4), np.triu(lu)
+    >>> np.allclose(A[p_inv] - L @ U, np.zeros((4, 4)))
+    True
+
+    The P matrix in P L U is defined by the inverse permutation and
+    can be recovered using argsort:
+
+    >>> p = np.argsort(p_inv)
+    >>> p
+    array([1, 3, 0, 2])
+    >>> np.allclose(A - L[p] @ U, np.zeros((4, 4)))
+    True
+
+    or alternatively:
+
+    >>> P = np.eye(4)[p]
+    >>> np.allclose(A - P @ L @ U, np.zeros((4, 4)))
+    True
+    """
+    if check_finite:
+        a1 = asarray_chkfinite(a)
+    else:
+        a1 = asarray(a)
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        lu = np.empty_like(a1)
+        piv = np.arange(0, dtype=np.int32)
+        return lu, piv
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    getrf, = get_lapack_funcs(('getrf',), (a1,))
+    lu, piv, info = getrf(a1, overwrite_a=overwrite_a)
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of '
+                         'internal getrf (lu_factor)' % -info)
+    if info > 0:
+        warn("Diagonal number %d is exactly zero. Singular matrix." % info,
+             LinAlgWarning, stacklevel=2)
+    return lu, piv
+
+
+def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):
+    """Solve an equation system, a x = b, given the LU factorization of a
+
+    Parameters
+    ----------
+    (lu, piv)
+        Factorization of the coefficient matrix a, as given by lu_factor.
+        In particular piv are 0-indexed pivot indices.
+    b : array
+        Right-hand side
+    trans : {0, 1, 2}, optional
+        Type of system to solve:
+
+        =====  =========
+        trans  system
+        =====  =========
+        0      a x   = b
+        1      a^T x = b
+        2      a^H x = b
+        =====  =========
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may increase performance)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    x : array
+        Solution to the system
+
+    See Also
+    --------
+    lu_factor : LU factorize a matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import lu_factor, lu_solve
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> b = np.array([1, 1, 1, 1])
+    >>> lu, piv = lu_factor(A)
+    >>> x = lu_solve((lu, piv), b)
+    >>> np.allclose(A @ x - b, np.zeros((4,)))
+    True
+
+    """
+    (lu, piv) = lu_and_piv
+    if check_finite:
+        b1 = asarray_chkfinite(b)
+    else:
+        b1 = asarray(b)
+
+    overwrite_b = overwrite_b or _datacopied(b1, b)
+
+    if lu.shape[0] != b1.shape[0]:
+        raise ValueError(f"Shapes of lu {lu.shape} and b {b1.shape} are incompatible")
+
+    # accommodate empty arrays
+    if b1.size == 0:
+        m = lu_solve((np.eye(2, dtype=lu.dtype), [0, 1]), np.ones(2, dtype=b.dtype))
+        return np.empty_like(b1, dtype=m.dtype)
+
+    getrs, = get_lapack_funcs(('getrs',), (lu, b1))
+    x, info = getrs(lu, piv, b1, trans=trans, overwrite_b=overwrite_b)
+    if info == 0:
+        return x
+    raise ValueError('illegal value in %dth argument of internal gesv|posv'
+                     % -info)
+
+
+def lu(a, permute_l=False, overwrite_a=False, check_finite=True,
+       p_indices=False):
+    """
+    Compute LU decomposition of a matrix with partial pivoting.
+
+    The decomposition satisfies::
+
+        A = P @ L @ U
+
+    where ``P`` is a permutation matrix, ``L`` lower triangular with unit
+    diagonal elements, and ``U`` upper triangular. If `permute_l` is set to
+    ``True`` then ``L`` is returned already permuted and hence satisfying
+    ``A = L @ U``.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Array to decompose
+    permute_l : bool, optional
+        Perform the multiplication P*L (Default: do not permute)
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    p_indices : bool, optional
+        If ``True`` the permutation information is returned as row indices.
+        The default is ``False`` for backwards-compatibility reasons.
+
+    Returns
+    -------
+    **(If `permute_l` is ``False``)**
+
+    p : (..., M, M) ndarray
+        Permutation arrays or vectors depending on `p_indices`
+    l : (..., M, K) ndarray
+        Lower triangular or trapezoidal array with unit diagonal.
+        ``K = min(M, N)``
+    u : (..., K, N) ndarray
+        Upper triangular or trapezoidal array
+
+    **(If `permute_l` is ``True``)**
+
+    pl : (..., M, K) ndarray
+        Permuted L matrix.
+        ``K = min(M, N)``
+    u : (..., K, N) ndarray
+        Upper triangular or trapezoidal array
+
+    Notes
+    -----
+    Permutation matrices are costly since they are nothing but row reorder of
+    ``L`` and hence indices are strongly recommended to be used instead if the
+    permutation is required. The relation in the 2D case then becomes simply
+    ``A = L[P, :] @ U``. In higher dimensions, it is better to use `permute_l`
+    to avoid complicated indexing tricks.
+
+    In 2D case, if one has the indices however, for some reason, the
+    permutation matrix is still needed then it can be constructed by
+    ``np.eye(M)[P, :]``.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.linalg import lu
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> p, l, u = lu(A)
+    >>> np.allclose(A, p @ l @ u)
+    True
+    >>> p  # Permutation matrix
+    array([[0., 1., 0., 0.],  # Row index 1
+           [0., 0., 0., 1.],  # Row index 3
+           [1., 0., 0., 0.],  # Row index 0
+           [0., 0., 1., 0.]]) # Row index 2
+    >>> p, _, _ = lu(A, p_indices=True)
+    >>> p
+    array([1, 3, 0, 2], dtype=int32)  # as given by row indices above
+    >>> np.allclose(A, l[p, :] @ u)
+    True
+
+    We can also use nd-arrays, for example, a demonstration with 4D array:
+
+    >>> rng = np.random.default_rng()
+    >>> A = rng.uniform(low=-4, high=4, size=[3, 2, 4, 8])
+    >>> p, l, u = lu(A)
+    >>> p.shape, l.shape, u.shape
+    ((3, 2, 4, 4), (3, 2, 4, 4), (3, 2, 4, 8))
+    >>> np.allclose(A, p @ l @ u)
+    True
+    >>> PL, U = lu(A, permute_l=True)
+    >>> np.allclose(A, PL @ U)
+    True
+
+    """
+    a1 = np.asarray_chkfinite(a) if check_finite else np.asarray(a)
+    if a1.ndim < 2:
+        raise ValueError('The input array must be at least two-dimensional.')
+
+    # Also check if dtype is LAPACK compatible
+    if a1.dtype.char not in 'fdFD':
+        dtype_char = lapack_cast_dict[a1.dtype.char]
+        if not dtype_char:  # No casting possible
+            raise TypeError(f'The dtype {a1.dtype} cannot be cast '
+                            'to float(32, 64) or complex(64, 128).')
+
+        a1 = a1.astype(dtype_char[0])  # makes a copy, free to scratch
+        overwrite_a = True
+
+    *nd, m, n = a1.shape
+    k = min(m, n)
+    real_dchar = 'f' if a1.dtype.char in 'fF' else 'd'
+
+    # Empty input
+    if min(*a1.shape) == 0:
+        if permute_l:
+            PL = np.empty(shape=[*nd, m, k], dtype=a1.dtype)
+            U = np.empty(shape=[*nd, k, n], dtype=a1.dtype)
+            return PL, U
+        else:
+            P = (np.empty([*nd, 0], dtype=np.int32) if p_indices else
+                 np.empty([*nd, 0, 0], dtype=real_dchar))
+            L = np.empty(shape=[*nd, m, k], dtype=a1.dtype)
+            U = np.empty(shape=[*nd, k, n], dtype=a1.dtype)
+            return P, L, U
+
+    # Scalar case
+    if a1.shape[-2:] == (1, 1):
+        if permute_l:
+            return np.ones_like(a1), (a1 if overwrite_a else a1.copy())
+        else:
+            P = (np.zeros(shape=[*nd, m], dtype=int) if p_indices
+                 else np.ones_like(a1))
+            return P, np.ones_like(a1), (a1 if overwrite_a else a1.copy())
+
+    # Then check overwrite permission
+    if not _datacopied(a1, a):  # "a"  still alive through "a1"
+        if not overwrite_a:
+            # Data belongs to "a" so make a copy
+            a1 = a1.copy(order='C')
+        #  else: Do nothing we'll use "a" if possible
+    # else:  a1 has its own data thus free to scratch
+
+    # Then layout checks, might happen that overwrite is allowed but original
+    # array was read-only or non-contiguous.
+
+    if not (a1.flags['C_CONTIGUOUS'] and a1.flags['WRITEABLE']):
+        a1 = a1.copy(order='C')
+
+    if not nd:  # 2D array
+
+        p = np.empty(m, dtype=np.int32)
+        u = np.zeros([k, k], dtype=a1.dtype)
+        lu_dispatcher(a1, u, p, permute_l)
+        P, L, U = (p, a1, u) if m > n else (p, u, a1)
+
+    else:  # Stacked array
+
+        # Prepare the contiguous data holders
+        P = np.empty([*nd, m], dtype=np.int32)  # perm vecs
+
+        if m > n:  # Tall arrays, U will be created
+            U = np.zeros([*nd, k, k], dtype=a1.dtype)
+            for ind in product(*[range(x) for x in a1.shape[:-2]]):
+                lu_dispatcher(a1[ind], U[ind], P[ind], permute_l)
+            L = a1
+
+        else:  # Fat arrays, L will be created
+            L = np.zeros([*nd, k, k], dtype=a1.dtype)
+            for ind in product(*[range(x) for x in a1.shape[:-2]]):
+                lu_dispatcher(a1[ind], L[ind], P[ind], permute_l)
+            U = a1
+
+    # Convert permutation vecs to permutation arrays
+    # permute_l=False needed to enter here to avoid wasted efforts
+    if (not p_indices) and (not permute_l):
+        if nd:
+            Pa = np.zeros([*nd, m, m], dtype=real_dchar)
+            # An unreadable index hack - One-hot encoding for perm matrices
+            nd_ix = np.ix_(*([np.arange(x) for x in nd]+[np.arange(m)]))
+            Pa[(*nd_ix, P)] = 1
+            P = Pa
+        else:  # 2D case
+            Pa = np.zeros([m, m], dtype=real_dchar)
+            Pa[np.arange(m), P] = 1
+            P = Pa
+
+    return (L, U) if permute_l else (P, L, U)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0a175b1de32806102318cf69f7c5b4c3deddb03c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_lu_cython.pyi
@@ -0,0 +1,6 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def lu_decompose(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ...  # noqa: E501
+
+def lu_dispatcher(a: NDArray[Any], lu: NDArray[Any], perm: NDArray[Any], permute_l: bool) -> None: ...  # noqa: E501
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fc3652899bed607ab1dd5e3f1663345010e93c1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_polar.py
@@ -0,0 +1,111 @@
+import numpy as np
+from scipy.linalg import svd
+
+
+__all__ = ['polar']
+
+
+def polar(a, side="right"):
+    """
+    Compute the polar decomposition.
+
+    Returns the factors of the polar decomposition [1]_ `u` and `p` such
+    that ``a = up`` (if `side` is "right") or ``a = pu`` (if `side` is
+    "left"), where `p` is positive semidefinite. Depending on the shape
+    of `a`, either the rows or columns of `u` are orthonormal. When `a`
+    is a square array, `u` is a square unitary array. When `a` is not
+    square, the "canonical polar decomposition" [2]_ is computed.
+
+    Parameters
+    ----------
+    a : (m, n) array_like
+        The array to be factored.
+    side : {'left', 'right'}, optional
+        Determines whether a right or left polar decomposition is computed.
+        If `side` is "right", then ``a = up``.  If `side` is "left",  then
+        ``a = pu``.  The default is "right".
+
+    Returns
+    -------
+    u : (m, n) ndarray
+        If `a` is square, then `u` is unitary. If m > n, then the columns
+        of `a` are orthonormal, and if m < n, then the rows of `u` are
+        orthonormal.
+    p : ndarray
+        `p` is Hermitian positive semidefinite. If `a` is nonsingular, `p`
+        is positive definite. The shape of `p` is (n, n) or (m, m), depending
+        on whether `side` is "right" or "left", respectively.
+
+    References
+    ----------
+    .. [1] R. A. Horn and C. R. Johnson, "Matrix Analysis", Cambridge
+           University Press, 1985.
+    .. [2] N. J. Higham, "Functions of Matrices: Theory and Computation",
+           SIAM, 2008.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import polar
+    >>> a = np.array([[1, -1], [2, 4]])
+    >>> u, p = polar(a)
+    >>> u
+    array([[ 0.85749293, -0.51449576],
+           [ 0.51449576,  0.85749293]])
+    >>> p
+    array([[ 1.88648444,  1.2004901 ],
+           [ 1.2004901 ,  3.94446746]])
+
+    A non-square example, with m < n:
+
+    >>> b = np.array([[0.5, 1, 2], [1.5, 3, 4]])
+    >>> u, p = polar(b)
+    >>> u
+    array([[-0.21196618, -0.42393237,  0.88054056],
+           [ 0.39378971,  0.78757942,  0.4739708 ]])
+    >>> p
+    array([[ 0.48470147,  0.96940295,  1.15122648],
+           [ 0.96940295,  1.9388059 ,  2.30245295],
+           [ 1.15122648,  2.30245295,  3.65696431]])
+    >>> u.dot(p)   # Verify the decomposition.
+    array([[ 0.5,  1. ,  2. ],
+           [ 1.5,  3. ,  4. ]])
+    >>> u.dot(u.T)   # The rows of u are orthonormal.
+    array([[  1.00000000e+00,  -2.07353665e-17],
+           [ -2.07353665e-17,   1.00000000e+00]])
+
+    Another non-square example, with m > n:
+
+    >>> c = b.T
+    >>> u, p = polar(c)
+    >>> u
+    array([[-0.21196618,  0.39378971],
+           [-0.42393237,  0.78757942],
+           [ 0.88054056,  0.4739708 ]])
+    >>> p
+    array([[ 1.23116567,  1.93241587],
+           [ 1.93241587,  4.84930602]])
+    >>> u.dot(p)   # Verify the decomposition.
+    array([[ 0.5,  1.5],
+           [ 1. ,  3. ],
+           [ 2. ,  4. ]])
+    >>> u.T.dot(u)  # The columns of u are orthonormal.
+    array([[  1.00000000e+00,  -1.26363763e-16],
+           [ -1.26363763e-16,   1.00000000e+00]])
+
+    """
+    if side not in ['right', 'left']:
+        raise ValueError("`side` must be either 'right' or 'left'")
+    a = np.asarray(a)
+    if a.ndim != 2:
+        raise ValueError("`a` must be a 2-D array.")
+
+    w, s, vh = svd(a, full_matrices=False)
+    u = w.dot(vh)
+    if side == 'right':
+        # a = up
+        p = (vh.T.conj() * s).dot(vh)
+    else:
+        # a = pu
+        p = (w * s).dot(w.T.conj())
+    return u, p
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..a41ad90770e3d53c741d85e6f46d4040bf203e7a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qr.py
@@ -0,0 +1,490 @@
+"""QR decomposition functions."""
+import numpy as np
+
+# Local imports
+from .lapack import get_lapack_funcs
+from ._misc import _datacopied
+
+__all__ = ['qr', 'qr_multiply', 'rq']
+
+
+def safecall(f, name, *args, **kwargs):
+    """Call a LAPACK routine, determining lwork automatically and handling
+    error return values"""
+    lwork = kwargs.get("lwork", None)
+    if lwork in (None, -1):
+        kwargs['lwork'] = -1
+        ret = f(*args, **kwargs)
+        kwargs['lwork'] = ret[-2][0].real.astype(np.int_)
+    ret = f(*args, **kwargs)
+    if ret[-1] < 0:
+        raise ValueError("illegal value in %dth argument of internal %s"
+                         % (-ret[-1], name))
+    return ret[:-2]
+
+
+def qr(a, overwrite_a=False, lwork=None, mode='full', pivoting=False,
+       check_finite=True):
+    """
+    Compute QR decomposition of a matrix.
+
+    Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
+    and R upper triangular.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to be decomposed
+    overwrite_a : bool, optional
+        Whether data in `a` is overwritten (may improve performance if
+        `overwrite_a` is set to True by reusing the existing input data
+        structure rather than creating a new one.)
+    lwork : int, optional
+        Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
+        is computed.
+    mode : {'full', 'r', 'economic', 'raw'}, optional
+        Determines what information is to be returned: either both Q and R
+        ('full', default), only R ('r') or both Q and R but computed in
+        economy-size ('economic', see Notes). The final option 'raw'
+        (added in SciPy 0.11) makes the function return two matrices
+        (Q, TAU) in the internal format used by LAPACK.
+    pivoting : bool, optional
+        Whether or not factorization should include pivoting for rank-revealing
+        qr decomposition. If pivoting, compute the decomposition
+        ``A[:, P] = Q @ R`` as above, but where P is chosen such that the
+        diagonal of R is non-increasing. Equivalently, albeit less efficiently,
+        an explicit P matrix may be formed explicitly by permuting the rows or columns
+        (depending on the side of the equation on which it is to be used) of
+        an identity matrix. See Examples.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    Q : float or complex ndarray
+        Of shape (M, M), or (M, K) for ``mode='economic'``. Not returned
+        if ``mode='r'``. Replaced by tuple ``(Q, TAU)`` if ``mode='raw'``.
+    R : float or complex ndarray
+        Of shape (M, N), or (K, N) for ``mode in ['economic', 'raw']``.
+        ``K = min(M, N)``.
+    P : int ndarray
+        Of shape (N,) for ``pivoting=True``. Not returned if
+        ``pivoting=False``.
+
+    Raises
+    ------
+    LinAlgError
+        Raised if decomposition fails
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines dgeqrf, zgeqrf,
+    dorgqr, zungqr, dgeqp3, and zgeqp3.
+
+    If ``mode=economic``, the shapes of Q and R are (M, K) and (K, N) instead
+    of (M,M) and (M,N), with ``K=min(M,N)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> a = rng.standard_normal((9, 6))
+
+    >>> q, r = linalg.qr(a)
+    >>> np.allclose(a, np.dot(q, r))
+    True
+    >>> q.shape, r.shape
+    ((9, 9), (9, 6))
+
+    >>> r2 = linalg.qr(a, mode='r')
+    >>> np.allclose(r, r2)
+    True
+
+    >>> q3, r3 = linalg.qr(a, mode='economic')
+    >>> q3.shape, r3.shape
+    ((9, 6), (6, 6))
+
+    >>> q4, r4, p4 = linalg.qr(a, pivoting=True)
+    >>> d = np.abs(np.diag(r4))
+    >>> np.all(d[1:] <= d[:-1])
+    True
+    >>> np.allclose(a[:, p4], np.dot(q4, r4))
+    True
+    >>> P = np.eye(p4.size)[p4]
+    >>> np.allclose(a, np.dot(q4, r4) @ P)
+    True
+    >>> np.allclose(a @ P.T, np.dot(q4, r4))
+    True
+    >>> q4.shape, r4.shape, p4.shape
+    ((9, 9), (9, 6), (6,))
+
+    >>> q5, r5, p5 = linalg.qr(a, mode='economic', pivoting=True)
+    >>> q5.shape, r5.shape, p5.shape
+    ((9, 6), (6, 6), (6,))
+    >>> P = np.eye(6)[:, p5]
+    >>> np.allclose(a @ P, np.dot(q5, r5))
+    True
+
+    """
+    # 'qr' was the old default, equivalent to 'full'. Neither 'full' nor
+    # 'qr' are used below.
+    # 'raw' is used internally by qr_multiply
+    if mode not in ['full', 'qr', 'r', 'economic', 'raw']:
+        raise ValueError("Mode argument should be one of ['full', 'r', "
+                         "'economic', 'raw']")
+
+    if check_finite:
+        a1 = np.asarray_chkfinite(a)
+    else:
+        a1 = np.asarray(a)
+    if len(a1.shape) != 2:
+        raise ValueError("expected a 2-D array")
+
+    M, N = a1.shape
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        K = min(M, N)
+
+        if mode not in ['economic', 'raw']:
+            Q = np.empty_like(a1, shape=(M, M))
+            Q[...] = np.identity(M)
+            R = np.empty_like(a1)
+        else:
+            Q = np.empty_like(a1, shape=(M, K))
+            R = np.empty_like(a1, shape=(K, N))
+
+        if pivoting:
+            Rj = R, np.arange(N, dtype=np.int32)
+        else:
+            Rj = R,
+
+        if mode == 'r':
+            return Rj
+        elif mode == 'raw':
+            qr = np.empty_like(a1, shape=(M, N))
+            tau = np.zeros_like(a1, shape=(K,))
+            return ((qr, tau),) + Rj
+        return (Q,) + Rj
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    if pivoting:
+        geqp3, = get_lapack_funcs(('geqp3',), (a1,))
+        qr, jpvt, tau = safecall(geqp3, "geqp3", a1, overwrite_a=overwrite_a)
+        jpvt -= 1  # geqp3 returns a 1-based index array, so subtract 1
+    else:
+        geqrf, = get_lapack_funcs(('geqrf',), (a1,))
+        qr, tau = safecall(geqrf, "geqrf", a1, lwork=lwork,
+                           overwrite_a=overwrite_a)
+
+    if mode not in ['economic', 'raw'] or M < N:
+        R = np.triu(qr)
+    else:
+        R = np.triu(qr[:N, :])
+
+    if pivoting:
+        Rj = R, jpvt
+    else:
+        Rj = R,
+
+    if mode == 'r':
+        return Rj
+    elif mode == 'raw':
+        return ((qr, tau),) + Rj
+
+    gor_un_gqr, = get_lapack_funcs(('orgqr',), (qr,))
+
+    if M < N:
+        Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr[:, :M], tau,
+                      lwork=lwork, overwrite_a=1)
+    elif mode == 'economic':
+        Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qr, tau, lwork=lwork,
+                      overwrite_a=1)
+    else:
+        t = qr.dtype.char
+        qqr = np.empty((M, M), dtype=t)
+        qqr[:, :N] = qr
+        Q, = safecall(gor_un_gqr, "gorgqr/gungqr", qqr, tau, lwork=lwork,
+                      overwrite_a=1)
+
+    return (Q,) + Rj
+
+
+def qr_multiply(a, c, mode='right', pivoting=False, conjugate=False,
+                overwrite_a=False, overwrite_c=False):
+    """
+    Calculate the QR decomposition and multiply Q with a matrix.
+
+    Calculate the decomposition ``A = Q R`` where Q is unitary/orthogonal
+    and R upper triangular. Multiply Q with a vector or a matrix c.
+
+    Parameters
+    ----------
+    a : (M, N), array_like
+        Input array
+    c : array_like
+        Input array to be multiplied by ``q``.
+    mode : {'left', 'right'}, optional
+        ``Q @ c`` is returned if mode is 'left', ``c @ Q`` is returned if
+        mode is 'right'.
+        The shape of c must be appropriate for the matrix multiplications,
+        if mode is 'left', ``min(a.shape) == c.shape[0]``,
+        if mode is 'right', ``a.shape[0] == c.shape[1]``.
+    pivoting : bool, optional
+        Whether or not factorization should include pivoting for rank-revealing
+        qr decomposition, see the documentation of qr.
+    conjugate : bool, optional
+        Whether Q should be complex-conjugated. This might be faster
+        than explicit conjugation.
+    overwrite_a : bool, optional
+        Whether data in a is overwritten (may improve performance)
+    overwrite_c : bool, optional
+        Whether data in c is overwritten (may improve performance).
+        If this is used, c must be big enough to keep the result,
+        i.e. ``c.shape[0]`` = ``a.shape[0]`` if mode is 'left'.
+
+    Returns
+    -------
+    CQ : ndarray
+        The product of ``Q`` and ``c``.
+    R : (K, N), ndarray
+        R array of the resulting QR factorization where ``K = min(M, N)``.
+    P : (N,) ndarray
+        Integer pivot array. Only returned when ``pivoting=True``.
+
+    Raises
+    ------
+    LinAlgError
+        Raised if QR decomposition fails.
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines ``?GEQRF``, ``?ORMQR``,
+    ``?UNMQR``, and ``?GEQP3``.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import qr_multiply, qr
+    >>> A = np.array([[1, 3, 3], [2, 3, 2], [2, 3, 3], [1, 3, 2]])
+    >>> qc, r1, piv1 = qr_multiply(A, 2*np.eye(4), pivoting=1)
+    >>> qc
+    array([[-1.,  1., -1.],
+           [-1., -1.,  1.],
+           [-1., -1., -1.],
+           [-1.,  1.,  1.]])
+    >>> r1
+    array([[-6., -3., -5.            ],
+           [ 0., -1., -1.11022302e-16],
+           [ 0.,  0., -1.            ]])
+    >>> piv1
+    array([1, 0, 2], dtype=int32)
+    >>> q2, r2, piv2 = qr(A, mode='economic', pivoting=1)
+    >>> np.allclose(2*q2 - qc, np.zeros((4, 3)))
+    True
+
+    """
+    if mode not in ['left', 'right']:
+        raise ValueError("Mode argument can only be 'left' or 'right' but "
+                         f"not '{mode}'")
+    c = np.asarray_chkfinite(c)
+    if c.ndim < 2:
+        onedim = True
+        c = np.atleast_2d(c)
+        if mode == "left":
+            c = c.T
+    else:
+        onedim = False
+
+    a = np.atleast_2d(np.asarray(a))  # chkfinite done in qr
+    M, N = a.shape
+
+    if mode == 'left':
+        if c.shape[0] != min(M, N + overwrite_c*(M-N)):
+            raise ValueError('Array shapes are not compatible for Q @ c'
+                             f' operation: {a.shape} vs {c.shape}')
+    else:
+        if M != c.shape[1]:
+            raise ValueError('Array shapes are not compatible for c @ Q'
+                             f' operation: {c.shape} vs {a.shape}')
+
+    raw = qr(a, overwrite_a, None, "raw", pivoting)
+    Q, tau = raw[0]
+
+    # accommodate empty arrays
+    if c.size == 0:
+        return (np.empty_like(c),) + raw[1:]
+
+    gor_un_mqr, = get_lapack_funcs(('ormqr',), (Q,))
+    if gor_un_mqr.typecode in ('s', 'd'):
+        trans = "T"
+    else:
+        trans = "C"
+
+    Q = Q[:, :min(M, N)]
+    if M > N and mode == "left" and not overwrite_c:
+        if conjugate:
+            cc = np.zeros((c.shape[1], M), dtype=c.dtype, order="F")
+            cc[:, :N] = c.T
+        else:
+            cc = np.zeros((M, c.shape[1]), dtype=c.dtype, order="F")
+            cc[:N, :] = c
+            trans = "N"
+        if conjugate:
+            lr = "R"
+        else:
+            lr = "L"
+        overwrite_c = True
+    elif c.flags["C_CONTIGUOUS"] and trans == "T" or conjugate:
+        cc = c.T
+        if mode == "left":
+            lr = "R"
+        else:
+            lr = "L"
+    else:
+        trans = "N"
+        cc = c
+        if mode == "left":
+            lr = "L"
+        else:
+            lr = "R"
+    cQ, = safecall(gor_un_mqr, "gormqr/gunmqr", lr, trans, Q, tau, cc,
+                   overwrite_c=overwrite_c)
+    if trans != "N":
+        cQ = cQ.T
+    if mode == "right":
+        cQ = cQ[:, :min(M, N)]
+    if onedim:
+        cQ = cQ.ravel()
+
+    return (cQ,) + raw[1:]
+
+
+def rq(a, overwrite_a=False, lwork=None, mode='full', check_finite=True):
+    """
+    Compute RQ decomposition of a matrix.
+
+    Calculate the decomposition ``A = R Q`` where Q is unitary/orthogonal
+    and R upper triangular.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to be decomposed
+    overwrite_a : bool, optional
+        Whether data in a is overwritten (may improve performance)
+    lwork : int, optional
+        Work array size, lwork >= a.shape[1]. If None or -1, an optimal size
+        is computed.
+    mode : {'full', 'r', 'economic'}, optional
+        Determines what information is to be returned: either both Q and R
+        ('full', default), only R ('r') or both Q and R but computed in
+        economy-size ('economic', see Notes).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    R : float or complex ndarray
+        Of shape (M, N) or (M, K) for ``mode='economic'``. ``K = min(M, N)``.
+    Q : float or complex ndarray
+        Of shape (N, N) or (K, N) for ``mode='economic'``. Not returned
+        if ``mode='r'``.
+
+    Raises
+    ------
+    LinAlgError
+        If decomposition fails.
+
+    Notes
+    -----
+    This is an interface to the LAPACK routines sgerqf, dgerqf, cgerqf, zgerqf,
+    sorgrq, dorgrq, cungrq and zungrq.
+
+    If ``mode=economic``, the shapes of Q and R are (K, N) and (M, K) instead
+    of (N,N) and (M,N), with ``K=min(M,N)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> a = rng.standard_normal((6, 9))
+    >>> r, q = linalg.rq(a)
+    >>> np.allclose(a, r @ q)
+    True
+    >>> r.shape, q.shape
+    ((6, 9), (9, 9))
+    >>> r2 = linalg.rq(a, mode='r')
+    >>> np.allclose(r, r2)
+    True
+    >>> r3, q3 = linalg.rq(a, mode='economic')
+    >>> r3.shape, q3.shape
+    ((6, 6), (6, 9))
+
+    """
+    if mode not in ['full', 'r', 'economic']:
+        raise ValueError(
+                 "Mode argument should be one of ['full', 'r', 'economic']")
+
+    if check_finite:
+        a1 = np.asarray_chkfinite(a)
+    else:
+        a1 = np.asarray(a)
+    if len(a1.shape) != 2:
+        raise ValueError('expected matrix')
+
+    M, N = a1.shape
+
+    # accommodate empty arrays
+    if a1.size == 0:
+        K = min(M, N)
+
+        if not mode == 'economic':
+            R = np.empty_like(a1)
+            Q = np.empty_like(a1, shape=(N, N))
+            Q[...] = np.identity(N)
+        else:
+            R = np.empty_like(a1, shape=(M, K))
+            Q = np.empty_like(a1, shape=(K, N))
+
+        if mode == 'r':
+            return R
+        return R, Q
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    gerqf, = get_lapack_funcs(('gerqf',), (a1,))
+    rq, tau = safecall(gerqf, 'gerqf', a1, lwork=lwork,
+                       overwrite_a=overwrite_a)
+    if not mode == 'economic' or N < M:
+        R = np.triu(rq, N-M)
+    else:
+        R = np.triu(rq[-M:, -M:])
+
+    if mode == 'r':
+        return R
+
+    gor_un_grq, = get_lapack_funcs(('orgrq',), (rq,))
+
+    if N < M:
+        Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq[-N:], tau, lwork=lwork,
+                      overwrite_a=1)
+    elif mode == 'economic':
+        Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq, tau, lwork=lwork,
+                      overwrite_a=1)
+    else:
+        rq1 = np.empty((N, N), dtype=rq.dtype)
+        rq1[-M:] = rq
+        Q, = safecall(gor_un_grq, "gorgrq/gungrq", rq1, tau, lwork=lwork,
+                      overwrite_a=1)
+
+    return R, Q
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py
new file mode 100644
index 0000000000000000000000000000000000000000..39361f172df7f1985c7ed0fbc4d919b5c4545725
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_qz.py
@@ -0,0 +1,449 @@
+import warnings
+
+import numpy as np
+from numpy import asarray_chkfinite
+from ._misc import LinAlgError, _datacopied, LinAlgWarning
+from .lapack import get_lapack_funcs
+
+
+__all__ = ['qz', 'ordqz']
+
+_double_precision = ['i', 'l', 'd']
+
+
+def _select_function(sort):
+    if callable(sort):
+        # assume the user knows what they're doing
+        sfunction = sort
+    elif sort == 'lhp':
+        sfunction = _lhp
+    elif sort == 'rhp':
+        sfunction = _rhp
+    elif sort == 'iuc':
+        sfunction = _iuc
+    elif sort == 'ouc':
+        sfunction = _ouc
+    else:
+        raise ValueError("sort parameter must be None, a callable, or "
+                         "one of ('lhp','rhp','iuc','ouc')")
+
+    return sfunction
+
+
+def _lhp(x, y):
+    out = np.empty_like(x, dtype=bool)
+    nonzero = (y != 0)
+    # handles (x, y) = (0, 0) too
+    out[~nonzero] = False
+    out[nonzero] = (np.real(x[nonzero]/y[nonzero]) < 0.0)
+    return out
+
+
+def _rhp(x, y):
+    out = np.empty_like(x, dtype=bool)
+    nonzero = (y != 0)
+    # handles (x, y) = (0, 0) too
+    out[~nonzero] = False
+    out[nonzero] = (np.real(x[nonzero]/y[nonzero]) > 0.0)
+    return out
+
+
+def _iuc(x, y):
+    out = np.empty_like(x, dtype=bool)
+    nonzero = (y != 0)
+    # handles (x, y) = (0, 0) too
+    out[~nonzero] = False
+    out[nonzero] = (abs(x[nonzero]/y[nonzero]) < 1.0)
+    return out
+
+
+def _ouc(x, y):
+    out = np.empty_like(x, dtype=bool)
+    xzero = (x == 0)
+    yzero = (y == 0)
+    out[xzero & yzero] = False
+    out[~xzero & yzero] = True
+    out[~yzero] = (abs(x[~yzero]/y[~yzero]) > 1.0)
+    return out
+
+
+def _qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False,
+        overwrite_b=False, check_finite=True):
+    if sort is not None:
+        # Disabled due to segfaults on win32, see ticket 1717.
+        raise ValueError("The 'sort' input of qz() has to be None and will be "
+                         "removed in a future release. Use ordqz instead.")
+
+    if output not in ['real', 'complex', 'r', 'c']:
+        raise ValueError("argument must be 'real', or 'complex'")
+
+    if check_finite:
+        a1 = asarray_chkfinite(A)
+        b1 = asarray_chkfinite(B)
+    else:
+        a1 = np.asarray(A)
+        b1 = np.asarray(B)
+
+    a_m, a_n = a1.shape
+    b_m, b_n = b1.shape
+    if not (a_m == a_n == b_m == b_n):
+        raise ValueError("Array dimensions must be square and agree")
+
+    typa = a1.dtype.char
+    if output in ['complex', 'c'] and typa not in ['F', 'D']:
+        if typa in _double_precision:
+            a1 = a1.astype('D')
+            typa = 'D'
+        else:
+            a1 = a1.astype('F')
+            typa = 'F'
+    typb = b1.dtype.char
+    if output in ['complex', 'c'] and typb not in ['F', 'D']:
+        if typb in _double_precision:
+            b1 = b1.astype('D')
+            typb = 'D'
+        else:
+            b1 = b1.astype('F')
+            typb = 'F'
+
+    overwrite_a = overwrite_a or (_datacopied(a1, A))
+    overwrite_b = overwrite_b or (_datacopied(b1, B))
+
+    gges, = get_lapack_funcs(('gges',), (a1, b1))
+
+    if lwork is None or lwork == -1:
+        # get optimal work array size
+        result = gges(lambda x: None, a1, b1, lwork=-1)
+        lwork = result[-2][0].real.astype(int)
+
+    def sfunction(x):
+        return None
+    result = gges(sfunction, a1, b1, lwork=lwork, overwrite_a=overwrite_a,
+                  overwrite_b=overwrite_b, sort_t=0)
+
+    info = result[-1]
+    if info < 0:
+        raise ValueError(f"Illegal value in argument {-info} of gges")
+    elif info > 0 and info <= a_n:
+        warnings.warn("The QZ iteration failed. (a,b) are not in Schur "
+                      "form, but ALPHAR(j), ALPHAI(j), and BETA(j) should be "
+                      f"correct for J={info-1},...,N", LinAlgWarning,
+                      stacklevel=3)
+    elif info == a_n+1:
+        raise LinAlgError("Something other than QZ iteration failed")
+    elif info == a_n+2:
+        raise LinAlgError("After reordering, roundoff changed values of some "
+                          "complex eigenvalues so that leading eigenvalues "
+                          "in the Generalized Schur form no longer satisfy "
+                          "sort=True. This could also be due to scaling.")
+    elif info == a_n+3:
+        raise LinAlgError("Reordering failed in tgsen")
+
+    return result, gges.typecode
+
+
+def qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False,
+       overwrite_b=False, check_finite=True):
+    """
+    QZ decomposition for generalized eigenvalues of a pair of matrices.
+
+    The QZ, or generalized Schur, decomposition for a pair of n-by-n
+    matrices (A,B) is::
+
+        (A,B) = (Q @ AA @ Z*, Q @ BB @ Z*)
+
+    where AA, BB is in generalized Schur form if BB is upper-triangular
+    with non-negative diagonal and AA is upper-triangular, or for real QZ
+    decomposition (``output='real'``) block upper triangular with 1x1
+    and 2x2 blocks. In this case, the 1x1 blocks correspond to real
+    generalized eigenvalues and 2x2 blocks are 'standardized' by making
+    the corresponding elements of BB have the form::
+
+        [ a 0 ]
+        [ 0 b ]
+
+    and the pair of corresponding 2x2 blocks in AA and BB will have a complex
+    conjugate pair of generalized eigenvalues. If (``output='complex'``) or
+    A and B are complex matrices, Z' denotes the conjugate-transpose of Z.
+    Q and Z are unitary matrices.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        2-D array to decompose
+    B : (N, N) array_like
+        2-D array to decompose
+    output : {'real', 'complex'}, optional
+        Construct the real or complex QZ decomposition for real matrices.
+        Default is 'real'.
+    lwork : int, optional
+        Work array size. If None or -1, it is automatically computed.
+    sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
+        NOTE: THIS INPUT IS DISABLED FOR NOW. Use ordqz instead.
+
+        Specifies whether the upper eigenvalues should be sorted. A callable
+        may be passed that, given a eigenvalue, returns a boolean denoting
+        whether the eigenvalue should be sorted to the top-left (True). For
+        real matrix pairs, the sort function takes three real arguments
+        (alphar, alphai, beta). The eigenvalue
+        ``x = (alphar + alphai*1j)/beta``. For complex matrix pairs or
+        output='complex', the sort function takes two complex arguments
+        (alpha, beta). The eigenvalue ``x = (alpha/beta)``.  Alternatively,
+        string parameters may be used:
+
+            - 'lhp'   Left-hand plane (x.real < 0.0)
+            - 'rhp'   Right-hand plane (x.real > 0.0)
+            - 'iuc'   Inside the unit circle (x*x.conjugate() < 1.0)
+            - 'ouc'   Outside the unit circle (x*x.conjugate() > 1.0)
+
+        Defaults to None (no sorting).
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance)
+    overwrite_b : bool, optional
+        Whether to overwrite data in b (may improve performance)
+    check_finite : bool, optional
+        If true checks the elements of `A` and `B` are finite numbers. If
+        false does no checking and passes matrix through to
+        underlying algorithm.
+
+    Returns
+    -------
+    AA : (N, N) ndarray
+        Generalized Schur form of A.
+    BB : (N, N) ndarray
+        Generalized Schur form of B.
+    Q : (N, N) ndarray
+        The left Schur vectors.
+    Z : (N, N) ndarray
+        The right Schur vectors.
+
+    See Also
+    --------
+    ordqz
+
+    Notes
+    -----
+    Q is transposed versus the equivalent function in Matlab.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import qz
+
+    >>> A = np.array([[1, 2, -1], [5, 5, 5], [2, 4, -8]])
+    >>> B = np.array([[1, 1, -3], [3, 1, -1], [5, 6, -2]])
+
+    Compute the decomposition.  The QZ decomposition is not unique, so
+    depending on the underlying library that is used, there may be
+    differences in the signs of coefficients in the following output.
+
+    >>> AA, BB, Q, Z = qz(A, B)
+    >>> AA
+    array([[-1.36949157, -4.05459025,  7.44389431],
+           [ 0.        ,  7.65653432,  5.13476017],
+           [ 0.        , -0.65978437,  2.4186015 ]])  # may vary
+    >>> BB
+    array([[ 1.71890633, -1.64723705, -0.72696385],
+           [ 0.        ,  8.6965692 , -0.        ],
+           [ 0.        ,  0.        ,  2.27446233]])  # may vary
+    >>> Q
+    array([[-0.37048362,  0.1903278 ,  0.90912992],
+           [-0.90073232,  0.16534124, -0.40167593],
+           [ 0.22676676,  0.96769706, -0.11017818]])  # may vary
+    >>> Z
+    array([[-0.67660785,  0.63528924, -0.37230283],
+           [ 0.70243299,  0.70853819, -0.06753907],
+           [ 0.22088393, -0.30721526, -0.92565062]])  # may vary
+
+    Verify the QZ decomposition.  With real output, we only need the
+    transpose of ``Z`` in the following expressions.
+
+    >>> Q @ AA @ Z.T  # Should be A
+    array([[ 1.,  2., -1.],
+           [ 5.,  5.,  5.],
+           [ 2.,  4., -8.]])
+    >>> Q @ BB @ Z.T  # Should be B
+    array([[ 1.,  1., -3.],
+           [ 3.,  1., -1.],
+           [ 5.,  6., -2.]])
+
+    Repeat the decomposition, but with ``output='complex'``.
+
+    >>> AA, BB, Q, Z = qz(A, B, output='complex')
+
+    For conciseness in the output, we use ``np.set_printoptions()`` to set
+    the output precision of NumPy arrays to 3 and display tiny values as 0.
+
+    >>> np.set_printoptions(precision=3, suppress=True)
+    >>> AA
+    array([[-1.369+0.j   ,  2.248+4.237j,  4.861-5.022j],
+           [ 0.   +0.j   ,  7.037+2.922j,  0.794+4.932j],
+           [ 0.   +0.j   ,  0.   +0.j   ,  2.655-1.103j]])  # may vary
+    >>> BB
+    array([[ 1.719+0.j   , -1.115+1.j   , -0.763-0.646j],
+           [ 0.   +0.j   ,  7.24 +0.j   , -3.144+3.322j],
+           [ 0.   +0.j   ,  0.   +0.j   ,  2.732+0.j   ]])  # may vary
+    >>> Q
+    array([[ 0.326+0.175j, -0.273-0.029j, -0.886-0.052j],
+           [ 0.794+0.426j, -0.093+0.134j,  0.402-0.02j ],
+           [-0.2  -0.107j, -0.816+0.482j,  0.151-0.167j]])  # may vary
+    >>> Z
+    array([[ 0.596+0.32j , -0.31 +0.414j,  0.393-0.347j],
+           [-0.619-0.332j, -0.479+0.314j,  0.154-0.393j],
+           [-0.195-0.104j,  0.576+0.27j ,  0.715+0.187j]])  # may vary
+
+    With complex arrays, we must use ``Z.conj().T`` in the following
+    expressions to verify the decomposition.
+
+    >>> Q @ AA @ Z.conj().T  # Should be A
+    array([[ 1.-0.j,  2.-0.j, -1.-0.j],
+           [ 5.+0.j,  5.+0.j,  5.-0.j],
+           [ 2.+0.j,  4.+0.j, -8.+0.j]])
+    >>> Q @ BB @ Z.conj().T  # Should be B
+    array([[ 1.+0.j,  1.+0.j, -3.+0.j],
+           [ 3.-0.j,  1.-0.j, -1.+0.j],
+           [ 5.+0.j,  6.+0.j, -2.+0.j]])
+
+    """
+    # output for real
+    # AA, BB, sdim, alphar, alphai, beta, vsl, vsr, work, info
+    # output for complex
+    # AA, BB, sdim, alpha, beta, vsl, vsr, work, info
+    result, _ = _qz(A, B, output=output, lwork=lwork, sort=sort,
+                    overwrite_a=overwrite_a, overwrite_b=overwrite_b,
+                    check_finite=check_finite)
+    return result[0], result[1], result[-4], result[-3]
+
+
+def ordqz(A, B, sort='lhp', output='real', overwrite_a=False,
+          overwrite_b=False, check_finite=True):
+    """QZ decomposition for a pair of matrices with reordering.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        2-D array to decompose
+    B : (N, N) array_like
+        2-D array to decompose
+    sort : {callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
+        Specifies whether the upper eigenvalues should be sorted. A
+        callable may be passed that, given an ordered pair ``(alpha,
+        beta)`` representing the eigenvalue ``x = (alpha/beta)``,
+        returns a boolean denoting whether the eigenvalue should be
+        sorted to the top-left (True). For the real matrix pairs
+        ``beta`` is real while ``alpha`` can be complex, and for
+        complex matrix pairs both ``alpha`` and ``beta`` can be
+        complex. The callable must be able to accept a NumPy
+        array. Alternatively, string parameters may be used:
+
+            - 'lhp'   Left-hand plane (x.real < 0.0)
+            - 'rhp'   Right-hand plane (x.real > 0.0)
+            - 'iuc'   Inside the unit circle (x*x.conjugate() < 1.0)
+            - 'ouc'   Outside the unit circle (x*x.conjugate() > 1.0)
+
+        With the predefined sorting functions, an infinite eigenvalue
+        (i.e., ``alpha != 0`` and ``beta = 0``) is considered to lie in
+        neither the left-hand nor the right-hand plane, but it is
+        considered to lie outside the unit circle. For the eigenvalue
+        ``(alpha, beta) = (0, 0)``, the predefined sorting functions
+        all return `False`.
+    output : str {'real','complex'}, optional
+        Construct the real or complex QZ decomposition for real matrices.
+        Default is 'real'.
+    overwrite_a : bool, optional
+        If True, the contents of A are overwritten.
+    overwrite_b : bool, optional
+        If True, the contents of B are overwritten.
+    check_finite : bool, optional
+        If true checks the elements of `A` and `B` are finite numbers. If
+        false does no checking and passes matrix through to
+        underlying algorithm.
+
+    Returns
+    -------
+    AA : (N, N) ndarray
+        Generalized Schur form of A.
+    BB : (N, N) ndarray
+        Generalized Schur form of B.
+    alpha : (N,) ndarray
+        alpha = alphar + alphai * 1j. See notes.
+    beta : (N,) ndarray
+        See notes.
+    Q : (N, N) ndarray
+        The left Schur vectors.
+    Z : (N, N) ndarray
+        The right Schur vectors.
+
+    See Also
+    --------
+    qz
+
+    Notes
+    -----
+    On exit, ``(ALPHAR(j) + ALPHAI(j)*i)/BETA(j), j=1,...,N``, will be the
+    generalized eigenvalues.  ``ALPHAR(j) + ALPHAI(j)*i`` and
+    ``BETA(j),j=1,...,N`` are the diagonals of the complex Schur form (S,T)
+    that would result if the 2-by-2 diagonal blocks of the real generalized
+    Schur form of (A,B) were further reduced to triangular form using complex
+    unitary transformations. If ALPHAI(j) is zero, then the jth eigenvalue is
+    real; if positive, then the ``j``\\ th and ``(j+1)``\\ st eigenvalues are a
+    complex conjugate pair, with ``ALPHAI(j+1)`` negative.
+
+    .. versionadded:: 0.17.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import ordqz
+    >>> A = np.array([[2, 5, 8, 7], [5, 2, 2, 8], [7, 5, 6, 6], [5, 4, 4, 8]])
+    >>> B = np.array([[0, 6, 0, 0], [5, 0, 2, 1], [5, 2, 6, 6], [4, 7, 7, 7]])
+    >>> AA, BB, alpha, beta, Q, Z = ordqz(A, B, sort='lhp')
+
+    Since we have sorted for left half plane eigenvalues, negatives come first
+
+    >>> (alpha/beta).real < 0
+    array([ True,  True, False, False], dtype=bool)
+
+    """
+    (AA, BB, _, *ab, Q, Z, _, _), typ = _qz(A, B, output=output, sort=None,
+                                            overwrite_a=overwrite_a,
+                                            overwrite_b=overwrite_b,
+                                            check_finite=check_finite)
+
+    if typ == 's':
+        alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2]
+    elif typ == 'd':
+        alpha, beta = ab[0] + ab[1]*1.j, ab[2]
+    else:
+        alpha, beta = ab
+
+    sfunction = _select_function(sort)
+    select = sfunction(alpha, beta)
+
+    tgsen = get_lapack_funcs('tgsen', (AA, BB))
+    # the real case needs 4n + 16 lwork
+    lwork = 4*AA.shape[0] + 16 if typ in 'sd' else 1
+    AAA, BBB, *ab, QQ, ZZ, _, _, _, _, info = tgsen(select, AA, BB, Q, Z,
+                                                    ijob=0,
+                                                    lwork=lwork, liwork=1)
+
+    # Once more for tgsen output
+    if typ == 's':
+        alpha, beta = ab[0] + ab[1]*np.complex64(1j), ab[2]
+    elif typ == 'd':
+        alpha, beta = ab[0] + ab[1]*1.j, ab[2]
+    else:
+        alpha, beta = ab
+
+    if info < 0:
+        raise ValueError(f"Illegal value in argument {-info} of tgsen")
+    elif info == 1:
+        raise ValueError("Reordering of (A, B) failed because the transformed"
+                         " matrix pair (A, B) would be too far from "
+                         "generalized Schur form; the problem is very "
+                         "ill-conditioned. (A, B) may have been partially "
+                         "reordered.")
+
+    return AAA, BBB, alpha, beta, QQ, ZZ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..8609a175e16d663938386c6b45d190cd0e5dafd8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_schur.py
@@ -0,0 +1,334 @@
+"""Schur decomposition functions."""
+import numpy as np
+from numpy import asarray_chkfinite, single, asarray, array
+from numpy.linalg import norm
+
+
+# Local imports.
+from ._misc import LinAlgError, _datacopied
+from .lapack import get_lapack_funcs
+from ._decomp import eigvals
+
+__all__ = ['schur', 'rsf2csf']
+
+_double_precision = ['i', 'l', 'd']
+
+
+def schur(a, output='real', lwork=None, overwrite_a=False, sort=None,
+          check_finite=True):
+    """
+    Compute Schur decomposition of a matrix.
+
+    The Schur decomposition is::
+
+        A = Z T Z^H
+
+    where Z is unitary and T is either upper-triangular, or for real
+    Schur decomposition (output='real'), quasi-upper triangular. In
+    the quasi-triangular form, 2x2 blocks describing complex-valued
+    eigenvalue pairs may extrude from the diagonal.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Matrix to decompose
+    output : {'real', 'complex'}, optional
+        When the dtype of `a` is real, this specifies whether to compute
+        the real or complex Schur decomposition.
+        When the dtype of `a` is complex, this argument is ignored, and the
+        complex Schur decomposition is computed.
+    lwork : int, optional
+        Work array size. If None or -1, it is automatically computed.
+    overwrite_a : bool, optional
+        Whether to overwrite data in a (may improve performance).
+    sort : {None, callable, 'lhp', 'rhp', 'iuc', 'ouc'}, optional
+        Specifies whether the upper eigenvalues should be sorted. A callable
+        may be passed that, given an eigenvalue, returns a boolean denoting
+        whether the eigenvalue should be sorted to the top-left (True).
+
+        - If ``output='complex'`` OR the dtype of `a` is complex, the callable
+          should have one argument: the eigenvalue expressed as a complex number.
+        - If ``output='real'`` AND the dtype of `a` is real, the callable should have
+          two arguments: the real and imaginary parts of the eigenvalue, respectively.
+
+        Alternatively, string parameters may be used::
+
+            'lhp'   Left-hand plane (real(eigenvalue) < 0.0)
+            'rhp'   Right-hand plane (real(eigenvalue) >= 0.0)
+            'iuc'   Inside the unit circle (abs(eigenvalue) <= 1.0)
+            'ouc'   Outside the unit circle (abs(eigenvalue) > 1.0)
+
+        Defaults to None (no sorting).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    T : (M, M) ndarray
+        Schur form of A. It is real-valued for the real Schur decomposition.
+    Z : (M, M) ndarray
+        An unitary Schur transformation matrix for A.
+        It is real-valued for the real Schur decomposition.
+    sdim : int
+        If and only if sorting was requested, a third return value will
+        contain the number of eigenvalues satisfying the sort condition.
+        Note that complex conjugate pairs for which the condition is true
+        for either eigenvalue count as 2.
+
+    Raises
+    ------
+    LinAlgError
+        Error raised under three conditions:
+
+        1. The algorithm failed due to a failure of the QR algorithm to
+           compute all eigenvalues.
+        2. If eigenvalue sorting was requested, the eigenvalues could not be
+           reordered due to a failure to separate eigenvalues, usually because
+           of poor conditioning.
+        3. If eigenvalue sorting was requested, roundoff errors caused the
+           leading eigenvalues to no longer satisfy the sorting condition.
+
+    See Also
+    --------
+    rsf2csf : Convert real Schur form to complex Schur form
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import schur, eigvals
+    >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
+    >>> T, Z = schur(A)
+    >>> T
+    array([[ 2.65896708,  1.42440458, -1.92933439],
+           [ 0.        , -0.32948354, -0.49063704],
+           [ 0.        ,  1.31178921, -0.32948354]])
+    >>> Z
+    array([[0.72711591, -0.60156188, 0.33079564],
+           [0.52839428, 0.79801892, 0.28976765],
+           [0.43829436, 0.03590414, -0.89811411]])
+
+    >>> T2, Z2 = schur(A, output='complex')
+    >>> T2
+    array([[ 2.65896708, -1.22839825+1.32378589j,  0.42590089+1.51937378j], # may vary
+           [ 0.        , -0.32948354+0.80225456j, -0.59877807+0.56192146j],
+           [ 0.        ,  0.                    , -0.32948354-0.80225456j]])
+    >>> eigvals(T2)
+    array([2.65896708, -0.32948354+0.80225456j, -0.32948354-0.80225456j])   # may vary
+
+    A custom eigenvalue-sorting condition that sorts by positive imaginary part
+    is satisfied by only one eigenvalue.
+
+    >>> _, _, sdim = schur(A, output='complex', sort=lambda x: x.imag > 1e-15)
+    >>> sdim
+    1
+
+    When ``output='real'`` and the array `a` is real, the `sort` callable must accept
+    the real and imaginary parts as separate arguments. Note that now the complex
+    eigenvalues ``-0.32948354+0.80225456j`` and ``-0.32948354-0.80225456j`` will be
+    treated as a complex conjugate pair, and according to the `sdim` documentation,
+    complex conjugate pairs for which the condition is True for *either* eigenvalue
+    increase `sdim` by *two*.
+
+    >>> _, _, sdim = schur(A, output='real', sort=lambda x, y: y > 1e-15)
+    >>> sdim
+    2
+
+    """
+    if output not in ['real', 'complex', 'r', 'c']:
+        raise ValueError("argument must be 'real', or 'complex'")
+    if check_finite:
+        a1 = asarray_chkfinite(a)
+    else:
+        a1 = asarray(a)
+    if np.issubdtype(a1.dtype, np.integer):
+        a1 = asarray(a, dtype=np.dtype("long"))
+    if len(a1.shape) != 2 or (a1.shape[0] != a1.shape[1]):
+        raise ValueError('expected square matrix')
+
+    typ = a1.dtype.char
+    if output in ['complex', 'c'] and typ not in ['F', 'D']:
+        if typ in _double_precision:
+            a1 = a1.astype('D')
+        else:
+            a1 = a1.astype('F')
+
+    # accommodate empty matrix
+    if a1.size == 0:
+        t0, z0 = schur(np.eye(2, dtype=a1.dtype))
+        if sort is None:
+            return (np.empty_like(a1, dtype=t0.dtype),
+                    np.empty_like(a1, dtype=z0.dtype))
+        else:
+            return (np.empty_like(a1, dtype=t0.dtype),
+                    np.empty_like(a1, dtype=z0.dtype), 0)
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+    gees, = get_lapack_funcs(('gees',), (a1,))
+    if lwork is None or lwork == -1:
+        # get optimal work array
+        result = gees(lambda x: None, a1, lwork=-1)
+        lwork = result[-2][0].real.astype(np.int_)
+
+    if sort is None:
+        sort_t = 0
+        def sfunction(x, y=None):
+            return None
+    else:
+        sort_t = 1
+        if callable(sort):
+            sfunction = sort
+        elif sort == 'lhp':
+            def sfunction(x, y=None):
+                return x.real < 0.0
+        elif sort == 'rhp':
+            def sfunction(x, y=None):
+                return x.real >= 0.0
+        elif sort == 'iuc':
+            def sfunction(x, y=None):
+                z = x if y is None else x + y*1j
+                return abs(z) <= 1.0
+        elif sort == 'ouc':
+            def sfunction(x, y=None):
+                z = x if y is None else x + y*1j
+                return abs(z) > 1.0
+        else:
+            raise ValueError("'sort' parameter must either be 'None', or a "
+                             "callable, or one of ('lhp','rhp','iuc','ouc')")
+
+    result = gees(sfunction, a1, lwork=lwork, overwrite_a=overwrite_a,
+                  sort_t=sort_t)
+
+    info = result[-1]
+    if info < 0:
+        raise ValueError(f'illegal value in {-info}-th argument of internal gees')
+    elif info == a1.shape[0] + 1:
+        raise LinAlgError('Eigenvalues could not be separated for reordering.')
+    elif info == a1.shape[0] + 2:
+        raise LinAlgError('Leading eigenvalues do not satisfy sort condition.')
+    elif info > 0:
+        raise LinAlgError("Schur form not found. Possibly ill-conditioned.")
+
+    if sort is None:
+        return result[0], result[-3]
+    else:
+        return result[0], result[-3], result[1]
+
+
+eps = np.finfo(float).eps
+feps = np.finfo(single).eps
+
+_array_kind = {'b': 0, 'h': 0, 'B': 0, 'i': 0, 'l': 0,
+               'f': 0, 'd': 0, 'F': 1, 'D': 1}
+_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
+_array_type = [['f', 'd'], ['F', 'D']]
+
+
+def _commonType(*arrays):
+    kind = 0
+    precision = 0
+    for a in arrays:
+        t = a.dtype.char
+        kind = max(kind, _array_kind[t])
+        precision = max(precision, _array_precision[t])
+    return _array_type[kind][precision]
+
+
+def _castCopy(type, *arrays):
+    cast_arrays = ()
+    for a in arrays:
+        if a.dtype.char == type:
+            cast_arrays = cast_arrays + (a.copy(),)
+        else:
+            cast_arrays = cast_arrays + (a.astype(type),)
+    if len(cast_arrays) == 1:
+        return cast_arrays[0]
+    else:
+        return cast_arrays
+
+
+def rsf2csf(T, Z, check_finite=True):
+    """
+    Convert real Schur form to complex Schur form.
+
+    Convert a quasi-diagonal real-valued Schur form to the upper-triangular
+    complex-valued Schur form.
+
+    Parameters
+    ----------
+    T : (M, M) array_like
+        Real Schur form of the original array
+    Z : (M, M) array_like
+        Schur transformation matrix
+    check_finite : bool, optional
+        Whether to check that the input arrays contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    T : (M, M) ndarray
+        Complex Schur form of the original array
+    Z : (M, M) ndarray
+        Schur transformation matrix corresponding to the complex form
+
+    See Also
+    --------
+    schur : Schur decomposition of an array
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import schur, rsf2csf
+    >>> A = np.array([[0, 2, 2], [0, 1, 2], [1, 0, 1]])
+    >>> T, Z = schur(A)
+    >>> T
+    array([[ 2.65896708,  1.42440458, -1.92933439],
+           [ 0.        , -0.32948354, -0.49063704],
+           [ 0.        ,  1.31178921, -0.32948354]])
+    >>> Z
+    array([[0.72711591, -0.60156188, 0.33079564],
+           [0.52839428, 0.79801892, 0.28976765],
+           [0.43829436, 0.03590414, -0.89811411]])
+    >>> T2 , Z2 = rsf2csf(T, Z)
+    >>> T2
+    array([[2.65896708+0.j, -1.64592781+0.743164187j, -1.21516887+1.00660462j],
+           [0.+0.j , -0.32948354+8.02254558e-01j, -0.82115218-2.77555756e-17j],
+           [0.+0.j , 0.+0.j, -0.32948354-0.802254558j]])
+    >>> Z2
+    array([[0.72711591+0.j,  0.28220393-0.31385693j,  0.51319638-0.17258824j],
+           [0.52839428+0.j,  0.24720268+0.41635578j, -0.68079517-0.15118243j],
+           [0.43829436+0.j, -0.76618703+0.01873251j, -0.03063006+0.46857912j]])
+
+    """
+    if check_finite:
+        Z, T = map(asarray_chkfinite, (Z, T))
+    else:
+        Z, T = map(asarray, (Z, T))
+
+    for ind, X in enumerate([Z, T]):
+        if X.ndim != 2 or X.shape[0] != X.shape[1]:
+            raise ValueError(f"Input '{'ZT'[ind]}' must be square.")
+
+    if T.shape[0] != Z.shape[0]:
+        message = f"Input array shapes must match: Z: {Z.shape} vs. T: {T.shape}"
+        raise ValueError(message)
+    N = T.shape[0]
+    t = _commonType(Z, T, array([3.0], 'F'))
+    Z, T = _castCopy(t, Z, T)
+
+    for m in range(N-1, 0, -1):
+        if abs(T[m, m-1]) > eps*(abs(T[m-1, m-1]) + abs(T[m, m])):
+            mu = eigvals(T[m-1:m+1, m-1:m+1]) - T[m, m]
+            r = norm([mu[0], T[m, m-1]])
+            c = mu[0] / r
+            s = T[m, m-1] / r
+            G = array([[c.conj(), s], [-s, c]], dtype=t)
+
+            T[m-1:m+1, m-1:] = G.dot(T[m-1:m+1, m-1:])
+            T[:m+1, m-1:m+1] = T[:m+1, m-1:m+1].dot(G.conj().T)
+            Z[:, m-1:m+1] = Z[:, m-1:m+1].dot(G.conj().T)
+
+        T[m, m-1] = 0.0
+    return T, Z
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..98425f6c11e727d582102dce72baeb9cbdb6c40b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_decomp_svd.py
@@ -0,0 +1,534 @@
+"""SVD decomposition functions."""
+import numpy as np
+from numpy import zeros, r_, diag, dot, arccos, arcsin, where, clip
+
+# Local imports.
+from ._misc import LinAlgError, _datacopied
+from .lapack import get_lapack_funcs, _compute_lwork
+from ._decomp import _asarray_validated
+
+__all__ = ['svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space']
+
+
+def svd(a, full_matrices=True, compute_uv=True, overwrite_a=False,
+        check_finite=True, lapack_driver='gesdd'):
+    """
+    Singular Value Decomposition.
+
+    Factorizes the matrix `a` into two unitary matrices ``U`` and ``Vh``, and
+    a 1-D array ``s`` of singular values (real, non-negative) such that
+    ``a == U @ S @ Vh``, where ``S`` is a suitably shaped matrix of zeros with
+    main diagonal ``s``.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to decompose.
+    full_matrices : bool, optional
+        If True (default), `U` and `Vh` are of shape ``(M, M)``, ``(N, N)``.
+        If False, the shapes are ``(M, K)`` and ``(K, N)``, where
+        ``K = min(M, N)``.
+    compute_uv : bool, optional
+        Whether to compute also ``U`` and ``Vh`` in addition to ``s``.
+        Default is True.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.
+        Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    lapack_driver : {'gesdd', 'gesvd'}, optional
+        Whether to use the more efficient divide-and-conquer approach
+        (``'gesdd'``) or general rectangular approach (``'gesvd'``)
+        to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach.
+        Default is ``'gesdd'``.
+
+    Returns
+    -------
+    U : ndarray
+        Unitary matrix having left singular vectors as columns.
+        Of shape ``(M, M)`` or ``(M, K)``, depending on `full_matrices`.
+    s : ndarray
+        The singular values, sorted in non-increasing order.
+        Of shape (K,), with ``K = min(M, N)``.
+    Vh : ndarray
+        Unitary matrix having right singular vectors as rows.
+        Of shape ``(N, N)`` or ``(K, N)`` depending on `full_matrices`.
+
+    For ``compute_uv=False``, only ``s`` is returned.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    svdvals : Compute singular values of a matrix.
+    diagsvd : Construct the Sigma matrix, given the vector s.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+    >>> m, n = 9, 6
+    >>> a = rng.standard_normal((m, n)) + 1.j*rng.standard_normal((m, n))
+    >>> U, s, Vh = linalg.svd(a)
+    >>> U.shape,  s.shape, Vh.shape
+    ((9, 9), (6,), (6, 6))
+
+    Reconstruct the original matrix from the decomposition:
+
+    >>> sigma = np.zeros((m, n))
+    >>> for i in range(min(m, n)):
+    ...     sigma[i, i] = s[i]
+    >>> a1 = np.dot(U, np.dot(sigma, Vh))
+    >>> np.allclose(a, a1)
+    True
+
+    Alternatively, use ``full_matrices=False`` (notice that the shape of
+    ``U`` is then ``(m, n)`` instead of ``(m, m)``):
+
+    >>> U, s, Vh = linalg.svd(a, full_matrices=False)
+    >>> U.shape, s.shape, Vh.shape
+    ((9, 6), (6,), (6, 6))
+    >>> S = np.diag(s)
+    >>> np.allclose(a, np.dot(U, np.dot(S, Vh)))
+    True
+
+    >>> s2 = linalg.svd(a, compute_uv=False)
+    >>> np.allclose(s, s2)
+    True
+
+    """
+    a1 = _asarray_validated(a, check_finite=check_finite)
+    if len(a1.shape) != 2:
+        raise ValueError('expected matrix')
+    m, n = a1.shape
+
+    # accommodate empty matrix
+    if a1.size == 0:
+        u0, s0, v0 = svd(np.eye(2, dtype=a1.dtype))
+
+        s = np.empty_like(a1, shape=(0,), dtype=s0.dtype)
+        if full_matrices:
+            u = np.empty_like(a1, shape=(m, m), dtype=u0.dtype)
+            u[...] = np.identity(m)
+            v = np.empty_like(a1, shape=(n, n), dtype=v0.dtype)
+            v[...] = np.identity(n)
+        else:
+            u = np.empty_like(a1, shape=(m, 0), dtype=u0.dtype)
+            v = np.empty_like(a1, shape=(0, n), dtype=v0.dtype)
+        if compute_uv:
+            return u, s, v
+        else:
+            return s
+
+    overwrite_a = overwrite_a or (_datacopied(a1, a))
+
+    if not isinstance(lapack_driver, str):
+        raise TypeError('lapack_driver must be a string')
+    if lapack_driver not in ('gesdd', 'gesvd'):
+        message = f'lapack_driver must be "gesdd" or "gesvd", not "{lapack_driver}"'
+        raise ValueError(message)
+
+    if compute_uv:
+        # XXX: revisit int32 when ILP64 lapack becomes a thing
+        max_mn, min_mn = (m, n) if m > n else (n, m)
+        if full_matrices:
+            if max_mn*max_mn > np.iinfo(np.int32).max:
+                raise ValueError(f"Indexing a matrix size {max_mn} x {max_mn} "
+                                  "would incur integer overflow in LAPACK. "
+                                  "Try using numpy.linalg.svd instead.")
+        else:
+            sz = max(m * min_mn, n * min_mn)
+            if max(m * min_mn, n * min_mn) > np.iinfo(np.int32).max:
+                raise ValueError(f"Indexing a matrix of {sz} elements would "
+                                  "incur an in integer overflow in LAPACK. "
+                                  "Try using numpy.linalg.svd instead.")
+
+    funcs = (lapack_driver, lapack_driver + '_lwork')
+    # XXX: As of 1.14.1 it isn't possible to build SciPy with ILP64,
+    # so the following line always yields a LP64 (32-bit pointer size) variant
+    gesXd, gesXd_lwork = get_lapack_funcs(funcs, (a1,), ilp64="preferred")
+
+    # compute optimal lwork
+    lwork = _compute_lwork(gesXd_lwork, a1.shape[0], a1.shape[1],
+                           compute_uv=compute_uv, full_matrices=full_matrices)
+
+    # perform decomposition
+    u, s, v, info = gesXd(a1, compute_uv=compute_uv, lwork=lwork,
+                          full_matrices=full_matrices, overwrite_a=overwrite_a)
+
+    if info > 0:
+        raise LinAlgError("SVD did not converge")
+    if info < 0:
+        raise ValueError('illegal value in %dth argument of internal gesdd'
+                         % -info)
+    if compute_uv:
+        return u, s, v
+    else:
+        return s
+
+
+def svdvals(a, overwrite_a=False, check_finite=True):
+    """
+    Compute singular values of a matrix.
+
+    Parameters
+    ----------
+    a : (M, N) array_like
+        Matrix to decompose.
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.
+        Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    s : (min(M, N),) ndarray
+        The singular values, sorted in decreasing order.
+
+    Raises
+    ------
+    LinAlgError
+        If SVD computation does not converge.
+
+    See Also
+    --------
+    svd : Compute the full singular value decomposition of a matrix.
+    diagsvd : Construct the Sigma matrix, given the vector s.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import svdvals
+    >>> m = np.array([[1.0, 0.0],
+    ...               [2.0, 3.0],
+    ...               [1.0, 1.0],
+    ...               [0.0, 2.0],
+    ...               [1.0, 0.0]])
+    >>> svdvals(m)
+    array([ 4.28091555,  1.63516424])
+
+    We can verify the maximum singular value of `m` by computing the maximum
+    length of `m.dot(u)` over all the unit vectors `u` in the (x,y) plane.
+    We approximate "all" the unit vectors with a large sample. Because
+    of linearity, we only need the unit vectors with angles in [0, pi].
+
+    >>> t = np.linspace(0, np.pi, 2000)
+    >>> u = np.array([np.cos(t), np.sin(t)])
+    >>> np.linalg.norm(m.dot(u), axis=0).max()
+    4.2809152422538475
+
+    `p` is a projection matrix with rank 1. With exact arithmetic,
+    its singular values would be [1, 0, 0, 0].
+
+    >>> v = np.array([0.1, 0.3, 0.9, 0.3])
+    >>> p = np.outer(v, v)
+    >>> svdvals(p)
+    array([  1.00000000e+00,   2.02021698e-17,   1.56692500e-17,
+             8.15115104e-34])
+
+    The singular values of an orthogonal matrix are all 1. Here, we
+    create a random orthogonal matrix by using the `rvs()` method of
+    `scipy.stats.ortho_group`.
+
+    >>> from scipy.stats import ortho_group
+    >>> orth = ortho_group.rvs(4)
+    >>> svdvals(orth)
+    array([ 1.,  1.,  1.,  1.])
+
+    """
+    return svd(a, compute_uv=0, overwrite_a=overwrite_a,
+               check_finite=check_finite)
+
+
+def diagsvd(s, M, N):
+    """
+    Construct the sigma matrix in SVD from singular values and size M, N.
+
+    Parameters
+    ----------
+    s : (M,) or (N,) array_like
+        Singular values
+    M : int
+        Size of the matrix whose singular values are `s`.
+    N : int
+        Size of the matrix whose singular values are `s`.
+
+    Returns
+    -------
+    S : (M, N) ndarray
+        The S-matrix in the singular value decomposition
+
+    See Also
+    --------
+    svd : Singular value decomposition of a matrix
+    svdvals : Compute singular values of a matrix.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import diagsvd
+    >>> vals = np.array([1, 2, 3])  # The array representing the computed svd
+    >>> diagsvd(vals, 3, 4)
+    array([[1, 0, 0, 0],
+           [0, 2, 0, 0],
+           [0, 0, 3, 0]])
+    >>> diagsvd(vals, 4, 3)
+    array([[1, 0, 0],
+           [0, 2, 0],
+           [0, 0, 3],
+           [0, 0, 0]])
+
+    """
+    part = diag(s)
+    typ = part.dtype.char
+    MorN = len(s)
+    if MorN == M:
+        return np.hstack((part, zeros((M, N - M), dtype=typ)))
+    elif MorN == N:
+        return r_[part, zeros((M - N, N), dtype=typ)]
+    else:
+        raise ValueError("Length of s must be M or N.")
+
+
+# Orthonormal decomposition
+
+def orth(A, rcond=None):
+    """
+    Construct an orthonormal basis for the range of A using SVD
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        Input array
+    rcond : float, optional
+        Relative condition number. Singular values ``s`` smaller than
+        ``rcond * max(s)`` are considered zero.
+        Default: floating point eps * max(M,N).
+
+    Returns
+    -------
+    Q : (M, K) ndarray
+        Orthonormal basis for the range of A.
+        K = effective rank of A, as determined by rcond
+
+    See Also
+    --------
+    svd : Singular value decomposition of a matrix
+    null_space : Matrix null space
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import orth
+    >>> A = np.array([[2, 0, 0], [0, 5, 0]])  # rank 2 array
+    >>> orth(A)
+    array([[0., 1.],
+           [1., 0.]])
+    >>> orth(A.T)
+    array([[0., 1.],
+           [1., 0.],
+           [0., 0.]])
+
+    """
+    u, s, vh = svd(A, full_matrices=False)
+    M, N = u.shape[0], vh.shape[1]
+    if rcond is None:
+        rcond = np.finfo(s.dtype).eps * max(M, N)
+    tol = np.amax(s, initial=0.) * rcond
+    num = np.sum(s > tol, dtype=int)
+    Q = u[:, :num]
+    return Q
+
+
+def null_space(A, rcond=None, *, overwrite_a=False, check_finite=True,
+               lapack_driver='gesdd'):
+    """
+    Construct an orthonormal basis for the null space of A using SVD
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        Input array
+    rcond : float, optional
+        Relative condition number. Singular values ``s`` smaller than
+        ``rcond * max(s)`` are considered zero.
+        Default: floating point eps * max(M,N).
+    overwrite_a : bool, optional
+        Whether to overwrite `a`; may improve performance.
+        Default is False.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+    lapack_driver : {'gesdd', 'gesvd'}, optional
+        Whether to use the more efficient divide-and-conquer approach
+        (``'gesdd'``) or general rectangular approach (``'gesvd'``)
+        to compute the SVD. MATLAB and Octave use the ``'gesvd'`` approach.
+        Default is ``'gesdd'``.
+
+    Returns
+    -------
+    Z : (N, K) ndarray
+        Orthonormal basis for the null space of A.
+        K = dimension of effective null space, as determined by rcond
+
+    See Also
+    --------
+    svd : Singular value decomposition of a matrix
+    orth : Matrix range
+
+    Examples
+    --------
+    1-D null space:
+
+    >>> import numpy as np
+    >>> from scipy.linalg import null_space
+    >>> A = np.array([[1, 1], [1, 1]])
+    >>> ns = null_space(A)
+    >>> ns * np.copysign(1, ns[0,0])  # Remove the sign ambiguity of the vector
+    array([[ 0.70710678],
+           [-0.70710678]])
+
+    2-D null space:
+
+    >>> from numpy.random import default_rng
+    >>> rng = default_rng()
+    >>> B = rng.random((3, 5))
+    >>> Z = null_space(B)
+    >>> Z.shape
+    (5, 2)
+    >>> np.allclose(B.dot(Z), 0)
+    True
+
+    The basis vectors are orthonormal (up to rounding error):
+
+    >>> Z.T.dot(Z)
+    array([[  1.00000000e+00,   6.92087741e-17],
+           [  6.92087741e-17,   1.00000000e+00]])
+
+    """
+    u, s, vh = svd(A, full_matrices=True, overwrite_a=overwrite_a,
+                   check_finite=check_finite, lapack_driver=lapack_driver)
+    M, N = u.shape[0], vh.shape[1]
+    if rcond is None:
+        rcond = np.finfo(s.dtype).eps * max(M, N)
+    tol = np.amax(s, initial=0.) * rcond
+    num = np.sum(s > tol, dtype=int)
+    Q = vh[num:,:].T.conj()
+    return Q
+
+
+def subspace_angles(A, B):
+    r"""
+    Compute the subspace angles between two matrices.
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        The first input array.
+    B : (M, K) array_like
+        The second input array.
+
+    Returns
+    -------
+    angles : ndarray, shape (min(N, K),)
+        The subspace angles between the column spaces of `A` and `B` in
+        descending order.
+
+    See Also
+    --------
+    orth
+    svd
+
+    Notes
+    -----
+    This computes the subspace angles according to the formula
+    provided in [1]_. For equivalence with MATLAB and Octave behavior,
+    use ``angles[0]``.
+
+    .. versionadded:: 1.0
+
+    References
+    ----------
+    .. [1] Knyazev A, Argentati M (2002) Principal Angles between Subspaces
+           in an A-Based Scalar Product: Algorithms and Perturbation
+           Estimates. SIAM J. Sci. Comput. 23:2008-2040.
+
+    Examples
+    --------
+    An Hadamard matrix, which has orthogonal columns, so we expect that
+    the suspace angle to be :math:`\frac{\pi}{2}`:
+
+    >>> import numpy as np
+    >>> from scipy.linalg import hadamard, subspace_angles
+    >>> rng = np.random.default_rng()
+    >>> H = hadamard(4)
+    >>> print(H)
+    [[ 1  1  1  1]
+     [ 1 -1  1 -1]
+     [ 1  1 -1 -1]
+     [ 1 -1 -1  1]]
+    >>> np.rad2deg(subspace_angles(H[:, :2], H[:, 2:]))
+    array([ 90.,  90.])
+
+    And the subspace angle of a matrix to itself should be zero:
+
+    >>> subspace_angles(H[:, :2], H[:, :2]) <= 2 * np.finfo(float).eps
+    array([ True,  True], dtype=bool)
+
+    The angles between non-orthogonal subspaces are in between these extremes:
+
+    >>> x = rng.standard_normal((4, 3))
+    >>> np.rad2deg(subspace_angles(x[:, :2], x[:, [2]]))
+    array([ 55.832])  # random
+    """
+    # Steps here omit the U and V calculation steps from the paper
+
+    # 1. Compute orthonormal bases of column-spaces
+    A = _asarray_validated(A, check_finite=True)
+    if len(A.shape) != 2:
+        raise ValueError(f'expected 2D array, got shape {A.shape}')
+    QA = orth(A)
+    del A
+
+    B = _asarray_validated(B, check_finite=True)
+    if len(B.shape) != 2:
+        raise ValueError(f'expected 2D array, got shape {B.shape}')
+    if len(B) != len(QA):
+        raise ValueError('A and B must have the same number of rows, got '
+                         f'{QA.shape[0]} and {B.shape[0]}')
+    QB = orth(B)
+    del B
+
+    # 2. Compute SVD for cosine
+    QA_H_QB = dot(QA.T.conj(), QB)
+    sigma = svdvals(QA_H_QB)
+
+    # 3. Compute matrix B
+    if QA.shape[1] >= QB.shape[1]:
+        B = QB - dot(QA, QA_H_QB)
+    else:
+        B = QA - dot(QB, QA_H_QB.T.conj())
+    del QA, QB, QA_H_QB
+
+    # 4. Compute SVD for sine
+    mask = sigma ** 2 >= 0.5
+    if mask.any():
+        mu_arcsin = arcsin(clip(svdvals(B, overwrite_a=True), -1., 1.))
+    else:
+        mu_arcsin = 0.
+
+    # 5. Compute the principal angles
+    # with reverse ordering of sigma because smallest sigma belongs to largest
+    # angle theta
+    theta = where(mask, mu_arcsin, arccos(clip(sigma[::-1], -1., 1.)))
+    return theta
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py
new file mode 100644
index 0000000000000000000000000000000000000000..56ddbc45c3bc47f6beb122e2acadd274ebd9be95
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_expm_frechet.py
@@ -0,0 +1,413 @@
+"""Frechet derivative of the matrix exponential."""
+import numpy as np
+import scipy.linalg
+
+__all__ = ['expm_frechet', 'expm_cond']
+
+
+def expm_frechet(A, E, method=None, compute_expm=True, check_finite=True):
+    """
+    Frechet derivative of the matrix exponential of A in the direction E.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix of which to take the matrix exponential.
+    E : (N, N) array_like
+        Matrix direction in which to take the Frechet derivative.
+    method : str, optional
+        Choice of algorithm. Should be one of
+
+        - `SPS` (default)
+        - `blockEnlarge`
+
+    compute_expm : bool, optional
+        Whether to compute also `expm_A` in addition to `expm_frechet_AE`.
+        Default is True.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    expm_A : ndarray
+        Matrix exponential of A.
+    expm_frechet_AE : ndarray
+        Frechet derivative of the matrix exponential of A in the direction E.
+    For ``compute_expm = False``, only `expm_frechet_AE` is returned.
+
+    See Also
+    --------
+    expm : Compute the exponential of a matrix.
+
+    Notes
+    -----
+    This section describes the available implementations that can be selected
+    by the `method` parameter. The default method is *SPS*.
+
+    Method *blockEnlarge* is a naive algorithm.
+
+    Method *SPS* is Scaling-Pade-Squaring [1]_.
+    It is a sophisticated implementation which should take
+    only about 3/8 as much time as the naive implementation.
+    The asymptotics are the same.
+
+    .. versionadded:: 0.13.0
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
+           Computing the Frechet Derivative of the Matrix Exponential,
+           with an application to Condition Number Estimation.
+           SIAM Journal On Matrix Analysis and Applications.,
+           30 (4). pp. 1639-1657. ISSN 1095-7162
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> rng = np.random.default_rng()
+
+    >>> A = rng.standard_normal((3, 3))
+    >>> E = rng.standard_normal((3, 3))
+    >>> expm_A, expm_frechet_AE = linalg.expm_frechet(A, E)
+    >>> expm_A.shape, expm_frechet_AE.shape
+    ((3, 3), (3, 3))
+
+    Create a 6x6 matrix containing [[A, E], [0, A]]:
+
+    >>> M = np.zeros((6, 6))
+    >>> M[:3, :3] = A
+    >>> M[:3, 3:] = E
+    >>> M[3:, 3:] = A
+
+    >>> expm_M = linalg.expm(M)
+    >>> np.allclose(expm_A, expm_M[:3, :3])
+    True
+    >>> np.allclose(expm_frechet_AE, expm_M[:3, 3:])
+    True
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+        E = np.asarray_chkfinite(E)
+    else:
+        A = np.asarray(A)
+        E = np.asarray(E)
+    if A.ndim != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected A to be a square matrix')
+    if E.ndim != 2 or E.shape[0] != E.shape[1]:
+        raise ValueError('expected E to be a square matrix')
+    if A.shape != E.shape:
+        raise ValueError('expected A and E to be the same shape')
+    if method is None:
+        method = 'SPS'
+    if method == 'SPS':
+        expm_A, expm_frechet_AE = expm_frechet_algo_64(A, E)
+    elif method == 'blockEnlarge':
+        expm_A, expm_frechet_AE = expm_frechet_block_enlarge(A, E)
+    else:
+        raise ValueError(f'Unknown implementation {method}')
+    if compute_expm:
+        return expm_A, expm_frechet_AE
+    else:
+        return expm_frechet_AE
+
+
+def expm_frechet_block_enlarge(A, E):
+    """
+    This is a helper function, mostly for testing and profiling.
+    Return expm(A), frechet(A, E)
+    """
+    n = A.shape[0]
+    M = np.vstack([
+        np.hstack([A, E]),
+        np.hstack([np.zeros_like(A), A])])
+    expm_M = scipy.linalg.expm(M)
+    return expm_M[:n, :n], expm_M[:n, n:]
+
+
+"""
+Maximal values ell_m of ||2**-s A|| such that the backward error bound
+does not exceed 2**-53.
+"""
+ell_table_61 = (
+        None,
+        # 1
+        2.11e-8,
+        3.56e-4,
+        1.08e-2,
+        6.49e-2,
+        2.00e-1,
+        4.37e-1,
+        7.83e-1,
+        1.23e0,
+        1.78e0,
+        2.42e0,
+        # 11
+        3.13e0,
+        3.90e0,
+        4.74e0,
+        5.63e0,
+        6.56e0,
+        7.52e0,
+        8.53e0,
+        9.56e0,
+        1.06e1,
+        1.17e1,
+        )
+
+
+# The b vectors and U and V are copypasted
+# from scipy.sparse.linalg.matfuncs.py.
+# M, Lu, Lv follow (6.11), (6.12), (6.13), (3.3)
+
+def _diff_pade3(A, E, ident):
+    b = (120., 60., 12., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    U = A.dot(b[3]*A2 + b[1]*ident)
+    V = b[2]*A2 + b[0]*ident
+    Lu = A.dot(b[3]*M2) + E.dot(b[3]*A2 + b[1]*ident)
+    Lv = b[2]*M2
+    return U, V, Lu, Lv
+
+
+def _diff_pade5(A, E, ident):
+    b = (30240., 15120., 3360., 420., 30., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    A4 = np.dot(A2, A2)
+    M4 = np.dot(A2, M2) + np.dot(M2, A2)
+    U = A.dot(b[5]*A4 + b[3]*A2 + b[1]*ident)
+    V = b[4]*A4 + b[2]*A2 + b[0]*ident
+    Lu = (A.dot(b[5]*M4 + b[3]*M2) +
+            E.dot(b[5]*A4 + b[3]*A2 + b[1]*ident))
+    Lv = b[4]*M4 + b[2]*M2
+    return U, V, Lu, Lv
+
+
+def _diff_pade7(A, E, ident):
+    b = (17297280., 8648640., 1995840., 277200., 25200., 1512., 56., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    A4 = np.dot(A2, A2)
+    M4 = np.dot(A2, M2) + np.dot(M2, A2)
+    A6 = np.dot(A2, A4)
+    M6 = np.dot(A4, M2) + np.dot(M4, A2)
+    U = A.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)
+    V = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
+    Lu = (A.dot(b[7]*M6 + b[5]*M4 + b[3]*M2) +
+            E.dot(b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))
+    Lv = b[6]*M6 + b[4]*M4 + b[2]*M2
+    return U, V, Lu, Lv
+
+
+def _diff_pade9(A, E, ident):
+    b = (17643225600., 8821612800., 2075673600., 302702400., 30270240.,
+            2162160., 110880., 3960., 90., 1.)
+    A2 = A.dot(A)
+    M2 = np.dot(A, E) + np.dot(E, A)
+    A4 = np.dot(A2, A2)
+    M4 = np.dot(A2, M2) + np.dot(M2, A2)
+    A6 = np.dot(A2, A4)
+    M6 = np.dot(A4, M2) + np.dot(M4, A2)
+    A8 = np.dot(A4, A4)
+    M8 = np.dot(A4, M4) + np.dot(M4, A4)
+    U = A.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident)
+    V = b[8]*A8 + b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
+    Lu = (A.dot(b[9]*M8 + b[7]*M6 + b[5]*M4 + b[3]*M2) +
+            E.dot(b[9]*A8 + b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident))
+    Lv = b[8]*M8 + b[6]*M6 + b[4]*M4 + b[2]*M2
+    return U, V, Lu, Lv
+
+
+def expm_frechet_algo_64(A, E):
+    n = A.shape[0]
+    s = None
+    ident = np.identity(n)
+    A_norm_1 = scipy.linalg.norm(A, 1)
+    m_pade_pairs = (
+            (3, _diff_pade3),
+            (5, _diff_pade5),
+            (7, _diff_pade7),
+            (9, _diff_pade9))
+    for m, pade in m_pade_pairs:
+        if A_norm_1 <= ell_table_61[m]:
+            U, V, Lu, Lv = pade(A, E, ident)
+            s = 0
+            break
+    if s is None:
+        # scaling
+        s = max(0, int(np.ceil(np.log2(A_norm_1 / ell_table_61[13]))))
+        A = A * 2.0**-s
+        E = E * 2.0**-s
+        # pade order 13
+        A2 = np.dot(A, A)
+        M2 = np.dot(A, E) + np.dot(E, A)
+        A4 = np.dot(A2, A2)
+        M4 = np.dot(A2, M2) + np.dot(M2, A2)
+        A6 = np.dot(A2, A4)
+        M6 = np.dot(A4, M2) + np.dot(M4, A2)
+        b = (64764752532480000., 32382376266240000., 7771770303897600.,
+                1187353796428800., 129060195264000., 10559470521600.,
+                670442572800., 33522128640., 1323241920., 40840800., 960960.,
+                16380., 182., 1.)
+        W1 = b[13]*A6 + b[11]*A4 + b[9]*A2
+        W2 = b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*ident
+        Z1 = b[12]*A6 + b[10]*A4 + b[8]*A2
+        Z2 = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*ident
+        W = np.dot(A6, W1) + W2
+        U = np.dot(A, W)
+        V = np.dot(A6, Z1) + Z2
+        Lw1 = b[13]*M6 + b[11]*M4 + b[9]*M2
+        Lw2 = b[7]*M6 + b[5]*M4 + b[3]*M2
+        Lz1 = b[12]*M6 + b[10]*M4 + b[8]*M2
+        Lz2 = b[6]*M6 + b[4]*M4 + b[2]*M2
+        Lw = np.dot(A6, Lw1) + np.dot(M6, W1) + Lw2
+        Lu = np.dot(A, Lw) + np.dot(E, W)
+        Lv = np.dot(A6, Lz1) + np.dot(M6, Z1) + Lz2
+    # factor once and solve twice
+    lu_piv = scipy.linalg.lu_factor(-U + V)
+    R = scipy.linalg.lu_solve(lu_piv, U + V)
+    L = scipy.linalg.lu_solve(lu_piv, Lu + Lv + np.dot((Lu - Lv), R))
+    # squaring
+    for k in range(s):
+        L = np.dot(R, L) + np.dot(L, R)
+        R = np.dot(R, R)
+    return R, L
+
+
+def vec(M):
+    """
+    Stack columns of M to construct a single vector.
+
+    This is somewhat standard notation in linear algebra.
+
+    Parameters
+    ----------
+    M : 2-D array_like
+        Input matrix
+
+    Returns
+    -------
+    v : 1-D ndarray
+        Output vector
+
+    """
+    return M.T.ravel()
+
+
+def expm_frechet_kronform(A, method=None, check_finite=True):
+    """
+    Construct the Kronecker form of the Frechet derivative of expm.
+
+    Parameters
+    ----------
+    A : array_like with shape (N, N)
+        Matrix to be expm'd.
+    method : str, optional
+        Extra keyword to be passed to expm_frechet.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    K : 2-D ndarray with shape (N*N, N*N)
+        Kronecker form of the Frechet derivative of the matrix exponential.
+
+    Notes
+    -----
+    This function is used to help compute the condition number
+    of the matrix exponential.
+
+    See Also
+    --------
+    expm : Compute a matrix exponential.
+    expm_frechet : Compute the Frechet derivative of the matrix exponential.
+    expm_cond : Compute the relative condition number of the matrix exponential
+                in the Frobenius norm.
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+    else:
+        A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    n = A.shape[0]
+    ident = np.identity(n)
+    cols = []
+    for i in range(n):
+        for j in range(n):
+            E = np.outer(ident[i], ident[j])
+            F = expm_frechet(A, E,
+                    method=method, compute_expm=False, check_finite=False)
+            cols.append(vec(F))
+    return np.vstack(cols).T
+
+
+def expm_cond(A, check_finite=True):
+    """
+    Relative condition number of the matrix exponential in the Frobenius norm.
+
+    Parameters
+    ----------
+    A : 2-D array_like
+        Square input matrix with shape (N, N).
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    kappa : float
+        The relative condition number of the matrix exponential
+        in the Frobenius norm
+
+    See Also
+    --------
+    expm : Compute the exponential of a matrix.
+    expm_frechet : Compute the Frechet derivative of the matrix exponential.
+
+    Notes
+    -----
+    A faster estimate for the condition number in the 1-norm
+    has been published but is not yet implemented in SciPy.
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm_cond
+    >>> A = np.array([[-0.3, 0.2, 0.6], [0.6, 0.3, -0.1], [-0.7, 1.2, 0.9]])
+    >>> k = expm_cond(A)
+    >>> k
+    1.7787805864469866
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+    else:
+        A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    X = scipy.linalg.expm(A)
+    K = expm_frechet_kronform(A, check_finite=False)
+
+    # The following norm choices are deliberate.
+    # The norms of A and X are Frobenius norms,
+    # and the norm of K is the induced 2-norm.
+    A_norm = scipy.linalg.norm(A, 'fro')
+    X_norm = scipy.linalg.norm(X, 'fro')
+    K_norm = scipy.linalg.norm(K, 2)
+
+    kappa = (K_norm * A_norm) / X_norm
+    return kappa
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h
new file mode 100644
index 0000000000000000000000000000000000000000..676658205e41bcde69e3899e8e065c90738af246
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_lapack_subroutines.h
@@ -0,0 +1,1521 @@
+/*
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+*/
+
+#include "npy_cblas.h"
+#include "fortran_defs.h"
+
+typedef int (*_cselect1)(npy_complex64*);
+typedef int (*_cselect2)(npy_complex64*, npy_complex64*);
+typedef int (*_dselect2)(double*, double*);
+typedef int (*_dselect3)(double*, double*, double*);
+typedef int (*_sselect2)(float*, float*);
+typedef int (*_sselect3)(float*, float*, float*);
+typedef int (*_zselect1)(npy_complex128*);
+typedef int (*_zselect2)(npy_complex128*, npy_complex128*);
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void BLAS_FUNC(cbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, float *theta, float *phi, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, float *b11d, float *b11e, float *b12d, float *b12e, float *b21d, float *b21e, float *b22d, float *b22e, float *rwork, int *lrwork, int *info);
+void BLAS_FUNC(cbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, npy_complex64 *vt, int *ldvt, npy_complex64 *u, int *ldu, npy_complex64 *c, int *ldc, float *rwork, int *info);
+void BLAS_FUNC(cgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *pt, int *ldpt, npy_complex64 *c, int *ldc, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbcon)(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbequ)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgbequb)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbsv)(int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, char *equed, float *r, float *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgbtf2)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(cgbtrf)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(cgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgebak)(char *job, char *side, int *n, int *ilo, int *ihi, float *scale, int *m, npy_complex64 *v, int *ldv, int *info);
+void BLAS_FUNC(cgebal)(char *job, int *n, npy_complex64 *a, int *lda, int *ilo, int *ihi, float *scale, int *info);
+void BLAS_FUNC(cgebd2)(int *m, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgebrd)(int *m, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgecon)(char *norm, int *n, npy_complex64 *a, int *lda, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgeequ)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgeequb)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(cgees)(char *jobvs, char *sort, _cselect1 *select, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info);
+void BLAS_FUNC(cgeesx)(char *jobvs, char *sort, _cselect1 *select, char *sense, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info);
+void BLAS_FUNC(cgeev)(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, float *scale, float *abnrm, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgehd2)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgehrd)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgelq2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgelqf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgels)(char *trans, int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgelsd)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *s, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(cgelss)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *s, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgelsy)(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *jpvt, float *rcond, int *rank, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeql2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqlf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgeqp3)(int *m, int *n, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgeqr2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqr2p)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqrf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgeqrfp)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgeqrt)(int *m, int *n, int *nb, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgeqrt2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info);
+void BLAS_FUNC(cgeqrt3)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info);
+void BLAS_FUNC(cgerfs)(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgerq2)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgerqf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgesc2)(int *n, npy_complex64 *a, int *lda, npy_complex64 *rhs, int *ipiv, int *jpiv, float *scale);
+void BLAS_FUNC(cgesdd)(char *jobz, int *m, int *n, npy_complex64 *a, int *lda, float *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(cgesv)(int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgesvd)(char *jobu, char *jobvt, int *m, int *n, npy_complex64 *a, int *lda, float *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cgesvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, char *equed, float *r, float *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgetc2)(int *n, npy_complex64 *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(cgetf2)(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(cgetrf)(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(cgetri)(int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgetrs)(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cggbak)(char *job, char *side, int *n, int *ilo, int *ihi, float *lscale, float *rscale, int *m, npy_complex64 *v, int *ldv, int *info);
+void BLAS_FUNC(cggbal)(char *job, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *ilo, int *ihi, float *lscale, float *rscale, float *work, int *info);
+void BLAS_FUNC(cgges)(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, npy_complex64 *work, int *lwork, float *rwork, int *bwork, int *info);
+void BLAS_FUNC(cggesx)(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(cggev)(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, float *lscale, float *rscale, float *abnrm, float *bbnrm, float *rconde, float *rcondv, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(cggglm)(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *d, npy_complex64 *x, npy_complex64 *y, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *info);
+void BLAS_FUNC(cgglse)(int *m, int *n, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, npy_complex64 *d, npy_complex64 *x, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cggqrf)(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cggrqf)(int *m, int *p, int *n, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cgtcon)(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(cgtrfs)(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgtsv)(int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgtsvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cgttrf)(int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, int *info);
+void BLAS_FUNC(cgttrs)(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cgtts2)(int *itrans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(chbev)(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chbevd)(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *x, int *ldx, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chbtrd)(char *vect, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info);
+void BLAS_FUNC(checon)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(cheequb)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, npy_complex64 *work, int *info);
+void BLAS_FUNC(cheev)(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, float *w, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cheevd)(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, float *w, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cheevr)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, int *isuppz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cheevx)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chegs2)(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chegst)(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chegv)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *w, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(chegvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *w, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chegvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(cherfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chesv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chesvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(cheswapr)(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(chetd2)(char *uplo, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tau, int *info);
+void BLAS_FUNC(chetf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(chetrd)(char *uplo, int *n, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chetrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chetri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(chetri2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(chetri2x)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info);
+void BLAS_FUNC(chetrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chetrs2)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info);
+void BLAS_FUNC(chfrk)(char *transr, char *uplo, char *trans, int *n, int *k, float *alpha, npy_complex64 *a, int *lda, float *beta, npy_complex64 *c);
+void BLAS_FUNC(chgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *t, int *ldt, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *info);
+char BLAS_FUNC(chla_transtype)(int *trans);
+void BLAS_FUNC(chpcon)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(chpev)(char *jobz, char *uplo, int *n, npy_complex64 *ap, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chpevd)(char *jobz, char *uplo, int *n, npy_complex64 *ap, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chpevx)(char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chpgst)(int *itype, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, int *info);
+void BLAS_FUNC(chpgv)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chpgvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(chpgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, npy_complex64 *work, float *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(chprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chpsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chpsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(chptrd)(char *uplo, int *n, npy_complex64 *ap, float *d, float *e, npy_complex64 *tau, int *info);
+void BLAS_FUNC(chptrf)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info);
+void BLAS_FUNC(chptri)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(chptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(chsein)(char *side, char *eigsrc, char *initv, int *select, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(chseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(clabrd)(int *m, int *n, int *nb, npy_complex64 *a, int *lda, float *d, float *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *x, int *ldx, npy_complex64 *y, int *ldy);
+void BLAS_FUNC(clacgv)(int *n, npy_complex64 *x, int *incx);
+void BLAS_FUNC(clacn2)(int *n, npy_complex64 *v, npy_complex64 *x, float *est, int *kase, int *isave);
+void BLAS_FUNC(clacon)(int *n, npy_complex64 *v, npy_complex64 *x, float *est, int *kase);
+void BLAS_FUNC(clacp2)(char *uplo, int *m, int *n, float *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(clacpy)(char *uplo, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(clacrm)(int *m, int *n, npy_complex64 *a, int *lda, float *b, int *ldb, npy_complex64 *c, int *ldc, float *rwork);
+void BLAS_FUNC(clacrt)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, npy_complex64 *c, npy_complex64 *s);
+void F_FUNC(cladivwrp,CLADIVWRP)(npy_complex64 *out, npy_complex64 *x, npy_complex64 *y);
+void BLAS_FUNC(claed0)(int *qsiz, int *n, float *d, float *e, npy_complex64 *q, int *ldq, npy_complex64 *qstore, int *ldqs, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(claed7)(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, float *d, npy_complex64 *q, int *ldq, float *rho, int *indxq, float *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, npy_complex64 *work, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(claed8)(int *k, int *n, int *qsiz, npy_complex64 *q, int *ldq, float *d, float *rho, int *cutpnt, float *z, float *dlamda, npy_complex64 *q2, int *ldq2, float *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, float *givnum, int *info);
+void BLAS_FUNC(claein)(int *rightv, int *noinit, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *v, npy_complex64 *b, int *ldb, float *rwork, float *eps3, float *smlnum, int *info);
+void BLAS_FUNC(claesy)(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, npy_complex64 *rt1, npy_complex64 *rt2, npy_complex64 *evscal, npy_complex64 *cs1, npy_complex64 *sn1);
+void BLAS_FUNC(claev2)(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, float *rt1, float *rt2, float *cs1, npy_complex64 *sn1);
+void BLAS_FUNC(clag2z)(int *m, int *n, npy_complex64 *sa, int *ldsa, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(clags2)(int *upper, float *a1, npy_complex64 *a2, float *a3, float *b1, npy_complex64 *b2, float *b3, float *csu, npy_complex64 *snu, float *csv, npy_complex64 *snv, float *csq, npy_complex64 *snq);
+void BLAS_FUNC(clagtm)(char *trans, int *n, int *nrhs, float *alpha, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *x, int *ldx, float *beta, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(clahef)(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info);
+void BLAS_FUNC(clahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *info);
+void BLAS_FUNC(clahr2)(int *n, int *k, int *nb, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *t, int *ldt, npy_complex64 *y, int *ldy);
+void BLAS_FUNC(claic1)(int *job, int *j, npy_complex64 *x, float *sest, npy_complex64 *w, npy_complex64 *gamma, float *sestpr, npy_complex64 *s, npy_complex64 *c);
+void BLAS_FUNC(clals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *rwork, int *info);
+void BLAS_FUNC(clalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *rwork, int *iwork, int *info);
+void BLAS_FUNC(clalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, float *d, float *e, npy_complex64 *b, int *ldb, float *rcond, int *rank, npy_complex64 *work, float *rwork, int *iwork, int *info);
+float BLAS_FUNC(clangb)(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clange)(char *norm, int *m, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clangt)(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du);
+float BLAS_FUNC(clanhb)(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clanhe)(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clanhf)(char *norm, char *transr, char *uplo, int *n, npy_complex64 *a, float *work);
+float BLAS_FUNC(clanhp)(char *norm, char *uplo, int *n, npy_complex64 *ap, float *work);
+float BLAS_FUNC(clanhs)(char *norm, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clanht)(char *norm, int *n, float *d, npy_complex64 *e);
+float BLAS_FUNC(clansb)(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clansp)(char *norm, char *uplo, int *n, npy_complex64 *ap, float *work);
+float BLAS_FUNC(clansy)(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, float *work);
+float BLAS_FUNC(clantb)(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex64 *ab, int *ldab, float *work);
+float BLAS_FUNC(clantp)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, float *work);
+float BLAS_FUNC(clantr)(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex64 *a, int *lda, float *work);
+void BLAS_FUNC(clapll)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *ssmin);
+void BLAS_FUNC(clapmr)(int *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k);
+void BLAS_FUNC(clapmt)(int *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k);
+void BLAS_FUNC(claqgb)(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(claqge)(int *m, int *n, npy_complex64 *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(claqhb)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqhe)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqhp)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqp2)(int *m, int *n, int *offset, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, float *vn1, float *vn2, npy_complex64 *work);
+void BLAS_FUNC(claqps)(int *m, int *n, int *offset, int *nb, int *kb, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, float *vn1, float *vn2, npy_complex64 *auxv, npy_complex64 *f, int *ldf);
+void BLAS_FUNC(claqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(claqr1)(int *n, npy_complex64 *h, int *ldh, npy_complex64 *s1, npy_complex64 *s2, npy_complex64 *v);
+void BLAS_FUNC(claqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork);
+void BLAS_FUNC(claqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork);
+void BLAS_FUNC(claqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(claqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex64 *s, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *v, int *ldv, npy_complex64 *u, int *ldu, int *nv, npy_complex64 *wv, int *ldwv, int *nh, npy_complex64 *wh, int *ldwh);
+void BLAS_FUNC(claqsb)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqsp)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(claqsy)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(clar1v)(int *n, int *b1, int *bn, float *lambda_, float *d, float *l, float *ld, float *lld, float *pivmin, float *gaptol, npy_complex64 *z, int *wantnc, int *negcnt, float *ztz, float *mingma, int *r, int *isuppz, float *nrminv, float *resid, float *rqcorr, float *work);
+void BLAS_FUNC(clar2v)(int *n, npy_complex64 *x, npy_complex64 *y, npy_complex64 *z, int *incx, float *c, npy_complex64 *s, int *incc);
+void BLAS_FUNC(clarcm)(int *m, int *n, float *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, float *rwork);
+void BLAS_FUNC(clarf)(char *side, int *m, int *n, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work);
+void BLAS_FUNC(clarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork);
+void BLAS_FUNC(clarfg)(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau);
+void BLAS_FUNC(clarfgp)(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau);
+void BLAS_FUNC(clarft)(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt);
+void BLAS_FUNC(clarfx)(char *side, int *m, int *n, npy_complex64 *v, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work);
+void BLAS_FUNC(clargv)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *c, int *incc);
+void BLAS_FUNC(clarnv)(int *idist, int *iseed, int *n, npy_complex64 *x);
+void BLAS_FUNC(clarrv)(int *n, float *vl, float *vu, float *d, float *l, float *pivmin, int *isplit, int *m, int *dol, int *dou, float *minrgp, float *rtol1, float *rtol2, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, npy_complex64 *z, int *ldz, int *isuppz, float *work, int *iwork, int *info);
+void BLAS_FUNC(clartg)(npy_complex64 *f, npy_complex64 *g, float *cs, npy_complex64 *sn, npy_complex64 *r);
+void BLAS_FUNC(clartv)(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, float *c, npy_complex64 *s, int *incc);
+void BLAS_FUNC(clarz)(char *side, int *m, int *n, int *l, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work);
+void BLAS_FUNC(clarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork);
+void BLAS_FUNC(clarzt)(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt);
+void BLAS_FUNC(clascl)(char *type_bn, int *kl, int *ku, float *cfrom, float *cto, int *m, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(claset)(char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *a, int *lda);
+void BLAS_FUNC(clasr)(char *side, char *pivot, char *direct, int *m, int *n, float *c, float *s, npy_complex64 *a, int *lda);
+void BLAS_FUNC(classq)(int *n, npy_complex64 *x, int *incx, float *scale, float *sumsq);
+void BLAS_FUNC(claswp)(int *n, npy_complex64 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(clasyf)(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info);
+void BLAS_FUNC(clatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(clatdf)(int *ijob, int *n, npy_complex64 *z, int *ldz, npy_complex64 *rhs, float *rdsum, float *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(clatps)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *ap, npy_complex64 *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(clatrd)(char *uplo, int *n, int *nb, npy_complex64 *a, int *lda, float *e, npy_complex64 *tau, npy_complex64 *w, int *ldw);
+void BLAS_FUNC(clatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(clatrz)(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work);
+void BLAS_FUNC(clauu2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(clauum)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpbcon)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpbequ)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cpbrfs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpbstf)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info);
+void BLAS_FUNC(cpbsv)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpbtf2)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info);
+void BLAS_FUNC(cpbtrf)(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info);
+void BLAS_FUNC(cpbtrs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpftrf)(char *transr, char *uplo, int *n, npy_complex64 *a, int *info);
+void BLAS_FUNC(cpftri)(char *transr, char *uplo, int *n, npy_complex64 *a, int *info);
+void BLAS_FUNC(cpftrs)(char *transr, char *uplo, int *n, int *nrhs, npy_complex64 *a, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpocon)(char *uplo, int *n, npy_complex64 *a, int *lda, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpoequ)(int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cpoequb)(int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cporfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cposv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cposvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpotf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpotrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpotri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(cpotrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cppcon)(char *uplo, int *n, npy_complex64 *ap, float *anorm, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cppequ)(char *uplo, int *n, npy_complex64 *ap, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(cpprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cppsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cppsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, char *equed, float *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpptrf)(char *uplo, int *n, npy_complex64 *ap, int *info);
+void BLAS_FUNC(cpptri)(char *uplo, int *n, npy_complex64 *ap, int *info);
+void BLAS_FUNC(cpptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cpstf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(cpstrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(cptcon)(int *n, float *d, npy_complex64 *e, float *anorm, float *rcond, float *rwork, int *info);
+void BLAS_FUNC(cpteqr)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(cptrfs)(char *uplo, int *n, int *nrhs, float *d, npy_complex64 *e, float *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cptsv)(int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cptsvx)(char *fact, int *n, int *nrhs, float *d, npy_complex64 *e, float *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cpttrf)(int *n, float *d, npy_complex64 *e, int *info);
+void BLAS_FUNC(cpttrs)(char *uplo, int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cptts2)(int *iuplo, int *n, int *nrhs, float *d, npy_complex64 *e, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(crot)(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, float *c, npy_complex64 *s);
+void BLAS_FUNC(cspcon)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(cspmv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(cspr)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap);
+void BLAS_FUNC(csprfs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(cspsv)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(cspsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(csptrf)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info);
+void BLAS_FUNC(csptri)(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(csptrs)(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(csrscl)(int *n, float *sa, npy_complex64 *sx, int *incx);
+void BLAS_FUNC(cstedc)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cstegr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, npy_complex64 *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(cstein)(int *n, float *d, float *e, int *m, float *w, int *iblock, int *isplit, npy_complex64 *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(cstemr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, int *m, float *w, npy_complex64 *z, int *ldz, int *nzc, int *isuppz, int *tryrac, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(csteqr)(char *compz, int *n, float *d, float *e, npy_complex64 *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(csycon)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, float *anorm, float *rcond, npy_complex64 *work, int *info);
+void BLAS_FUNC(csyconv)(char *uplo, char *way, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(csyequb)(char *uplo, int *n, npy_complex64 *a, int *lda, float *s, float *scond, float *amax, npy_complex64 *work, int *info);
+void BLAS_FUNC(csymv)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy);
+void BLAS_FUNC(csyr)(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda);
+void BLAS_FUNC(csyrfs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(csysv)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(csysvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *rcond, float *ferr, float *berr, npy_complex64 *work, int *lwork, float *rwork, int *info);
+void BLAS_FUNC(csyswapr)(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(csytf2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(csytrf)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(csytri)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info);
+void BLAS_FUNC(csytri2)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(csytri2x)(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info);
+void BLAS_FUNC(csytrs)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(csytrs2)(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info);
+void BLAS_FUNC(ctbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex64 *ab, int *ldab, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(ctfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, npy_complex64 *b, int *ldb);
+void BLAS_FUNC(ctftri)(char *transr, char *uplo, char *diag, int *n, npy_complex64 *a, int *info);
+void BLAS_FUNC(ctfttp)(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *ap, int *info);
+void BLAS_FUNC(ctfttr)(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctgevc)(char *side, char *howmny, int *select, int *n, npy_complex64 *s, int *lds, npy_complex64 *p, int *ldp, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctgex2)(int *wantq, int *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *j1, int *info);
+void BLAS_FUNC(ctgexc)(int *wantq, int *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ctgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *m, float *pl, float *pr, float *dif, npy_complex64 *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ctgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, float *tola, float *tolb, float *alpha, float *beta, npy_complex64 *u, int *ldu, npy_complex64 *v, int *ldv, npy_complex64 *q, int *ldq, npy_complex64 *work, int *ncycle, int *info);
+void BLAS_FUNC(ctgsna)(char *job, char *howmny, int *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, float *s, float *dif, int *mm, int *m, npy_complex64 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ctgsy2)(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, float *scale, float *rdsum, float *rdscal, int *info);
+void BLAS_FUNC(ctgsyl)(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, float *scale, float *dif, npy_complex64 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ctpcon)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info);
+void BLAS_FUNC(ctpqrt)(int *m, int *n, int *l, int *nb, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info);
+void BLAS_FUNC(ctpqrt2)(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, int *info);
+void BLAS_FUNC(ctprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *ldwork);
+void BLAS_FUNC(ctprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctptri)(char *uplo, char *diag, int *n, npy_complex64 *ap, int *info);
+void BLAS_FUNC(ctptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(ctpttf)(char *transr, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *arf, int *info);
+void BLAS_FUNC(ctpttr)(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctrcon)(char *norm, char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, float *rcond, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctrevc)(char *side, char *howmny, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctrexc)(char *compq, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ctrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, float *ferr, float *berr, npy_complex64 *work, float *rwork, int *info);
+void BLAS_FUNC(ctrsen)(char *job, char *compq, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, npy_complex64 *w, int *m, float *s, float *sep, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(ctrsna)(char *job, char *howmny, int *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, float *s, float *sep, int *mm, int *m, npy_complex64 *work, int *ldwork, float *rwork, int *info);
+void BLAS_FUNC(ctrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, float *scale, int *info);
+void BLAS_FUNC(ctrti2)(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctrtri)(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info);
+void BLAS_FUNC(ctrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info);
+void BLAS_FUNC(ctrttf)(char *transr, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *arf, int *info);
+void BLAS_FUNC(ctrttp)(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *ap, int *info);
+void BLAS_FUNC(ctzrzf)(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunbdb)(char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, float *theta, float *phi, npy_complex64 *taup1, npy_complex64 *taup2, npy_complex64 *tauq1, npy_complex64 *tauq2, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cuncsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, float *theta, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, npy_complex64 *work, int *lwork, float *rwork, int *lrwork, int *iwork, int *info);
+void BLAS_FUNC(cung2l)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cung2r)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cungbr)(char *vect, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunghr)(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungl2)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunglq)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungql)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungqr)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungr2)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info);
+void BLAS_FUNC(cungrq)(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cungtr)(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunm2l)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunm2r)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunml2)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmlq)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmql)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmqr)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmr2)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmr3)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(cunmrq)(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmrz)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cunmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info);
+void BLAS_FUNC(cupgtr)(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info);
+void BLAS_FUNC(cupmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info);
+void BLAS_FUNC(dbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, double *theta, double *phi, double *u1, int *ldu1, double *u2, int *ldu2, double *v1t, int *ldv1t, double *v2t, int *ldv2t, double *b11d, double *b11e, double *b12d, double *b12e, double *b21d, double *b21e, double *b22d, double *b22e, double *work, int *lwork, int *info);
+void BLAS_FUNC(dbdsdc)(char *uplo, char *compq, int *n, double *d, double *e, double *u, int *ldu, double *vt, int *ldvt, double *q, int *iq, double *work, int *iwork, int *info);
+void BLAS_FUNC(dbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, double *vt, int *ldvt, double *u, int *ldu, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(ddisna)(char *job, int *m, int *n, double *d, double *sep, int *info);
+void BLAS_FUNC(dgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, double *ab, int *ldab, double *d, double *e, double *q, int *ldq, double *pt, int *ldpt, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dgbcon)(char *norm, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgbequ)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgbequb)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgbsv)(int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, int *ipiv, char *equed, double *r, double *c, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgbtf2)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(dgbtrf)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(dgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, double *ab, int *ldab, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgebak)(char *job, char *side, int *n, int *ilo, int *ihi, double *scale, int *m, double *v, int *ldv, int *info);
+void BLAS_FUNC(dgebal)(char *job, int *n, double *a, int *lda, int *ilo, int *ihi, double *scale, int *info);
+void BLAS_FUNC(dgebd2)(int *m, int *n, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *work, int *info);
+void BLAS_FUNC(dgebrd)(int *m, int *n, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgecon)(char *norm, int *n, double *a, int *lda, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgeequ)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgeequb)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(dgees)(char *jobvs, char *sort, _dselect2 *select, int *n, double *a, int *lda, int *sdim, double *wr, double *wi, double *vs, int *ldvs, double *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(dgeesx)(char *jobvs, char *sort, _dselect2 *select, char *sense, int *n, double *a, int *lda, int *sdim, double *wr, double *wi, double *vs, int *ldvs, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(dgeev)(char *jobvl, char *jobvr, int *n, double *a, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, double *a, int *lda, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, int *ilo, int *ihi, double *scale, double *abnrm, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgehd2)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgehrd)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgejsv)(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, double *a, int *lda, double *sva, double *u, int *ldu, double *v, int *ldv, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgelq2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgelqf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgels)(char *trans, int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgelsd)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *s, double *rcond, int *rank, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgelss)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *s, double *rcond, int *rank, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgelsy)(int *m, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *jpvt, double *rcond, int *rank, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dgeql2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgeqlf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqp3)(int *m, int *n, double *a, int *lda, int *jpvt, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqr2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgeqr2p)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgeqrf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqrfp)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgeqrt)(int *m, int *n, int *nb, double *a, int *lda, double *t, int *ldt, double *work, int *info);
+void BLAS_FUNC(dgeqrt2)(int *m, int *n, double *a, int *lda, double *t, int *ldt, int *info);
+void BLAS_FUNC(dgeqrt3)(int *m, int *n, double *a, int *lda, double *t, int *ldt, int *info);
+void BLAS_FUNC(dgerfs)(char *trans, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgerq2)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dgerqf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgesc2)(int *n, double *a, int *lda, double *rhs, int *ipiv, int *jpiv, double *scale);
+void BLAS_FUNC(dgesdd)(char *jobz, int *m, int *n, double *a, int *lda, double *s, double *u, int *ldu, double *vt, int *ldvt, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dgesv)(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgesvd)(char *jobu, char *jobvt, int *m, int *n, double *a, int *lda, double *s, double *u, int *ldu, double *vt, int *ldvt, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgesvj)(char *joba, char *jobu, char *jobv, int *m, int *n, double *a, int *lda, double *sva, int *mv, double *v, int *ldv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgesvx)(char *fact, char *trans, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, char *equed, double *r, double *c, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgetc2)(int *n, double *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(dgetf2)(int *m, int *n, double *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(dgetrf)(int *m, int *n, double *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(dgetri)(int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgetrs)(char *trans, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dggbak)(char *job, char *side, int *n, int *ilo, int *ihi, double *lscale, double *rscale, int *m, double *v, int *ldv, int *info);
+void BLAS_FUNC(dggbal)(char *job, int *n, double *a, int *lda, double *b, int *ldb, int *ilo, int *ihi, double *lscale, double *rscale, double *work, int *info);
+void BLAS_FUNC(dgges)(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, int *n, double *a, int *lda, double *b, int *ldb, int *sdim, double *alphar, double *alphai, double *beta, double *vsl, int *ldvsl, double *vsr, int *ldvsr, double *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(dggesx)(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, char *sense, int *n, double *a, int *lda, double *b, int *ldb, int *sdim, double *alphar, double *alphai, double *beta, double *vsl, int *ldvsl, double *vsr, int *ldvsr, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(dggev)(char *jobvl, char *jobvr, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *vl, int *ldvl, double *vr, int *ldvr, double *work, int *lwork, int *info);
+void BLAS_FUNC(dggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *vl, int *ldvl, double *vr, int *ldvr, int *ilo, int *ihi, double *lscale, double *rscale, double *abnrm, double *bbnrm, double *rconde, double *rcondv, double *work, int *lwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(dggglm)(int *n, int *m, int *p, double *a, int *lda, double *b, int *ldb, double *d, double *x, double *y, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *info);
+void BLAS_FUNC(dgglse)(int *m, int *n, int *p, double *a, int *lda, double *b, int *ldb, double *c, double *d, double *x, double *work, int *lwork, int *info);
+void BLAS_FUNC(dggqrf)(int *n, int *m, int *p, double *a, int *lda, double *taua, double *b, int *ldb, double *taub, double *work, int *lwork, int *info);
+void BLAS_FUNC(dggrqf)(int *m, int *p, int *n, double *a, int *lda, double *taua, double *b, int *ldb, double *taub, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgsvj0)(char *jobv, int *m, int *n, double *a, int *lda, double *d, double *sva, int *mv, double *v, int *ldv, double *eps, double *sfmin, double *tol, int *nsweep, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgsvj1)(char *jobv, int *m, int *n, int *n1, double *a, int *lda, double *d, double *sva, int *mv, double *v, int *ldv, double *eps, double *sfmin, double *tol, int *nsweep, double *work, int *lwork, int *info);
+void BLAS_FUNC(dgtcon)(char *norm, int *n, double *dl, double *d, double *du, double *du2, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgtrfs)(char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *dlf, double *df, double *duf, double *du2, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgtsv)(int *n, int *nrhs, double *dl, double *d, double *du, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgtsvx)(char *fact, char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *dlf, double *df, double *duf, double *du2, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dgttrf)(int *n, double *dl, double *d, double *du, double *du2, int *ipiv, int *info);
+void BLAS_FUNC(dgttrs)(char *trans, int *n, int *nrhs, double *dl, double *d, double *du, double *du2, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dgtts2)(int *itrans, int *n, int *nrhs, double *dl, double *d, double *du, double *du2, int *ipiv, double *b, int *ldb);
+void BLAS_FUNC(dhgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *t, int *ldt, double *alphar, double *alphai, double *beta, double *q, int *ldq, double *z, int *ldz, double *work, int *lwork, int *info);
+void BLAS_FUNC(dhsein)(char *side, char *eigsrc, char *initv, int *select, int *n, double *h, int *ldh, double *wr, double *wi, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(dhseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, double *z, int *ldz, double *work, int *lwork, int *info);
+int BLAS_FUNC(disnan)(double *din);
+void BLAS_FUNC(dlabad)(double *small, double *large);
+void BLAS_FUNC(dlabrd)(int *m, int *n, int *nb, double *a, int *lda, double *d, double *e, double *tauq, double *taup, double *x, int *ldx, double *y, int *ldy);
+void BLAS_FUNC(dlacn2)(int *n, double *v, double *x, int *isgn, double *est, int *kase, int *isave);
+void BLAS_FUNC(dlacon)(int *n, double *v, double *x, int *isgn, double *est, int *kase);
+void BLAS_FUNC(dlacpy)(char *uplo, int *m, int *n, double *a, int *lda, double *b, int *ldb);
+void BLAS_FUNC(dladiv)(double *a, double *b, double *c, double *d, double *p, double *q);
+void BLAS_FUNC(dlae2)(double *a, double *b, double *c, double *rt1, double *rt2);
+void BLAS_FUNC(dlaebz)(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, double *abstol, double *reltol, double *pivmin, double *d, double *e, double *e2, int *nval, double *ab, double *c, int *mout, int *nab, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed0)(int *icompq, int *qsiz, int *n, double *d, double *e, double *q, int *ldq, double *qstore, int *ldqs, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed1)(int *n, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed2)(int *k, int *n, int *n1, double *d, double *q, int *ldq, int *indxq, double *rho, double *z, double *dlamda, double *w, double *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info);
+void BLAS_FUNC(dlaed3)(int *k, int *n, int *n1, double *d, double *q, int *ldq, double *rho, double *dlamda, double *q2, int *indx, int *ctot, double *w, double *s, int *info);
+void BLAS_FUNC(dlaed4)(int *n, int *i, double *d, double *z, double *delta, double *rho, double *dlam, int *info);
+void BLAS_FUNC(dlaed5)(int *i, double *d, double *z, double *delta, double *rho, double *dlam);
+void BLAS_FUNC(dlaed6)(int *kniter, int *orgati, double *rho, double *d, double *z, double *finit, double *tau, int *info);
+void BLAS_FUNC(dlaed7)(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlaed8)(int *icompq, int *k, int *n, int *qsiz, double *d, double *q, int *ldq, int *indxq, double *rho, int *cutpnt, double *z, double *dlamda, double *q2, int *ldq2, double *w, int *perm, int *givptr, int *givcol, double *givnum, int *indxp, int *indx, int *info);
+void BLAS_FUNC(dlaed9)(int *k, int *kstart, int *kstop, int *n, double *d, double *q, int *ldq, double *rho, double *dlamda, double *w, double *s, int *lds, int *info);
+void BLAS_FUNC(dlaeda)(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, double *q, int *qptr, double *z, double *ztemp, int *info);
+void BLAS_FUNC(dlaein)(int *rightv, int *noinit, int *n, double *h, int *ldh, double *wr, double *wi, double *vr, double *vi, double *b, int *ldb, double *work, double *eps3, double *smlnum, double *bignum, int *info);
+void BLAS_FUNC(dlaev2)(double *a, double *b, double *c, double *rt1, double *rt2, double *cs1, double *sn1);
+void BLAS_FUNC(dlaexc)(int *wantq, int *n, double *t, int *ldt, double *q, int *ldq, int *j1, int *n1, int *n2, double *work, int *info);
+void BLAS_FUNC(dlag2)(double *a, int *lda, double *b, int *ldb, double *safmin, double *scale1, double *scale2, double *wr1, double *wr2, double *wi);
+void BLAS_FUNC(dlag2s)(int *m, int *n, double *a, int *lda, float *sa, int *ldsa, int *info);
+void BLAS_FUNC(dlags2)(int *upper, double *a1, double *a2, double *a3, double *b1, double *b2, double *b3, double *csu, double *snu, double *csv, double *snv, double *csq, double *snq);
+void BLAS_FUNC(dlagtf)(int *n, double *a, double *lambda_, double *b, double *c, double *tol, double *d, int *in_, int *info);
+void BLAS_FUNC(dlagtm)(char *trans, int *n, int *nrhs, double *alpha, double *dl, double *d, double *du, double *x, int *ldx, double *beta, double *b, int *ldb);
+void BLAS_FUNC(dlagts)(int *job, int *n, double *a, double *b, double *c, double *d, int *in_, double *y, double *tol, int *info);
+void BLAS_FUNC(dlagv2)(double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *csl, double *snl, double *csr, double *snr);
+void BLAS_FUNC(dlahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, int *info);
+void BLAS_FUNC(dlahr2)(int *n, int *k, int *nb, double *a, int *lda, double *tau, double *t, int *ldt, double *y, int *ldy);
+void BLAS_FUNC(dlaic1)(int *job, int *j, double *x, double *sest, double *w, double *gamma, double *sestpr, double *s, double *c);
+void BLAS_FUNC(dlaln2)(int *ltrans, int *na, int *nw, double *smin, double *ca, double *a, int *lda, double *d1, double *d2, double *b, int *ldb, double *wr, double *wi, double *x, int *ldx, double *scale, double *xnorm, int *info);
+void BLAS_FUNC(dlals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, double *b, int *ldb, double *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *work, int *info);
+void BLAS_FUNC(dlalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, double *b, int *ldb, double *bx, int *ldbx, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, double *d, double *e, double *b, int *ldb, double *rcond, int *rank, double *work, int *iwork, int *info);
+double BLAS_FUNC(dlamch)(char *cmach);
+void BLAS_FUNC(dlamrg)(int *n1, int *n2, double *a, int *dtrd1, int *dtrd2, int *index_bn);
+int BLAS_FUNC(dlaneg)(int *n, double *d, double *lld, double *sigma, double *pivmin, int *r);
+double BLAS_FUNC(dlangb)(char *norm, int *n, int *kl, int *ku, double *ab, int *ldab, double *work);
+double BLAS_FUNC(dlange)(char *norm, int *m, int *n, double *a, int *lda, double *work);
+double BLAS_FUNC(dlangt)(char *norm, int *n, double *dl, double *d_, double *du);
+double BLAS_FUNC(dlanhs)(char *norm, int *n, double *a, int *lda, double *work);
+double BLAS_FUNC(dlansb)(char *norm, char *uplo, int *n, int *k, double *ab, int *ldab, double *work);
+double BLAS_FUNC(dlansf)(char *norm, char *transr, char *uplo, int *n, double *a, double *work);
+double BLAS_FUNC(dlansp)(char *norm, char *uplo, int *n, double *ap, double *work);
+double BLAS_FUNC(dlanst)(char *norm, int *n, double *d_, double *e);
+double BLAS_FUNC(dlansy)(char *norm, char *uplo, int *n, double *a, int *lda, double *work);
+double BLAS_FUNC(dlantb)(char *norm, char *uplo, char *diag, int *n, int *k, double *ab, int *ldab, double *work);
+double BLAS_FUNC(dlantp)(char *norm, char *uplo, char *diag, int *n, double *ap, double *work);
+double BLAS_FUNC(dlantr)(char *norm, char *uplo, char *diag, int *m, int *n, double *a, int *lda, double *work);
+void BLAS_FUNC(dlanv2)(double *a, double *b, double *c, double *d, double *rt1r, double *rt1i, double *rt2r, double *rt2i, double *cs, double *sn);
+void BLAS_FUNC(dlapll)(int *n, double *x, int *incx, double *y, int *incy, double *ssmin);
+void BLAS_FUNC(dlapmr)(int *forwrd, int *m, int *n, double *x, int *ldx, int *k);
+void BLAS_FUNC(dlapmt)(int *forwrd, int *m, int *n, double *x, int *ldx, int *k);
+double BLAS_FUNC(dlapy2)(double *x, double *y);
+double BLAS_FUNC(dlapy3)(double *x, double *y, double *z);
+void BLAS_FUNC(dlaqgb)(int *m, int *n, int *kl, int *ku, double *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(dlaqge)(int *m, int *n, double *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(dlaqp2)(int *m, int *n, int *offset, double *a, int *lda, int *jpvt, double *tau, double *vn1, double *vn2, double *work);
+void BLAS_FUNC(dlaqps)(int *m, int *n, int *offset, int *nb, int *kb, double *a, int *lda, int *jpvt, double *tau, double *vn1, double *vn2, double *auxv, double *f, int *ldf);
+void BLAS_FUNC(dlaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, double *work, int *lwork, int *info);
+void BLAS_FUNC(dlaqr1)(int *n, double *h, int *ldh, double *sr1, double *si1, double *sr2, double *si2, double *v);
+void BLAS_FUNC(dlaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, int *ns, int *nd, double *sr, double *si, double *v, int *ldv, int *nh, double *t, int *ldt, int *nv, double *wv, int *ldwv, double *work, int *lwork);
+void BLAS_FUNC(dlaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, int *ns, int *nd, double *sr, double *si, double *v, int *ldv, int *nh, double *t, int *ldt, int *nv, double *wv, int *ldwv, double *work, int *lwork);
+void BLAS_FUNC(dlaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, double *h, int *ldh, double *wr, double *wi, int *iloz, int *ihiz, double *z, int *ldz, double *work, int *lwork, int *info);
+void BLAS_FUNC(dlaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, double *sr, double *si, double *h, int *ldh, int *iloz, int *ihiz, double *z, int *ldz, double *v, int *ldv, double *u, int *ldu, int *nv, double *wv, int *ldwv, int *nh, double *wh, int *ldwh);
+void BLAS_FUNC(dlaqsb)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(dlaqsp)(char *uplo, int *n, double *ap, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(dlaqsy)(char *uplo, int *n, double *a, int *lda, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(dlaqtr)(int *ltran, int *lreal, int *n, double *t, int *ldt, double *b, double *w, double *scale, double *x, double *work, int *info);
+void BLAS_FUNC(dlar1v)(int *n, int *b1, int *bn, double *lambda_, double *d, double *l, double *ld, double *lld, double *pivmin, double *gaptol, double *z, int *wantnc, int *negcnt, double *ztz, double *mingma, int *r, int *isuppz, double *nrminv, double *resid, double *rqcorr, double *work);
+void BLAS_FUNC(dlar2v)(int *n, double *x, double *y, double *z, int *incx, double *c, double *s, int *incc);
+void BLAS_FUNC(dlarf)(char *side, int *m, int *n, double *v, int *incv, double *tau, double *c, int *ldc, double *work);
+void BLAS_FUNC(dlarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *ldwork);
+void BLAS_FUNC(dlarfg)(int *n, double *alpha, double *x, int *incx, double *tau);
+void BLAS_FUNC(dlarfgp)(int *n, double *alpha, double *x, int *incx, double *tau);
+void BLAS_FUNC(dlarft)(char *direct, char *storev, int *n, int *k, double *v, int *ldv, double *tau, double *t, int *ldt);
+void BLAS_FUNC(dlarfx)(char *side, int *m, int *n, double *v, double *tau, double *c, int *ldc, double *work);
+void BLAS_FUNC(dlargv)(int *n, double *x, int *incx, double *y, int *incy, double *c, int *incc);
+void BLAS_FUNC(dlarnv)(int *idist, int *iseed, int *n, double *x);
+void BLAS_FUNC(dlarra)(int *n, double *d, double *e, double *e2, double *spltol, double *tnrm, int *nsplit, int *isplit, int *info);
+void BLAS_FUNC(dlarrb)(int *n, double *d, double *lld, int *ifirst, int *ilast, double *rtol1, double *rtol2, int *offset, double *w, double *wgap, double *werr, double *work, int *iwork, double *pivmin, double *spdiam, int *twist, int *info);
+void BLAS_FUNC(dlarrc)(char *jobt, int *n, double *vl, double *vu, double *d, double *e, double *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info);
+void BLAS_FUNC(dlarrd)(char *range, char *order, int *n, double *vl, double *vu, int *il, int *iu, double *gers, double *reltol, double *d, double *e, double *e2, double *pivmin, int *nsplit, int *isplit, int *m, double *w, double *werr, double *wl, double *wu, int *iblock, int *indexw, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlarre)(char *range, int *n, double *vl, double *vu, int *il, int *iu, double *d, double *e, double *e2, double *rtol1, double *rtol2, double *spltol, int *nsplit, int *isplit, int *m, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, double *pivmin, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlarrf)(int *n, double *d, double *l, double *ld, int *clstrt, int *clend, double *w, double *wgap, double *werr, double *spdiam, double *clgapl, double *clgapr, double *pivmin, double *sigma, double *dplus, double *lplus, double *work, int *info);
+void BLAS_FUNC(dlarrj)(int *n, double *d, double *e2, int *ifirst, int *ilast, double *rtol, int *offset, double *w, double *werr, double *work, int *iwork, double *pivmin, double *spdiam, int *info);
+void BLAS_FUNC(dlarrk)(int *n, int *iw, double *gl, double *gu, double *d, double *e2, double *pivmin, double *reltol, double *w, double *werr, int *info);
+void BLAS_FUNC(dlarrr)(int *n, double *d, double *e, int *info);
+void BLAS_FUNC(dlarrv)(int *n, double *vl, double *vu, double *d, double *l, double *pivmin, int *isplit, int *m, int *dol, int *dou, double *minrgp, double *rtol1, double *rtol2, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, double *z, int *ldz, int *isuppz, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlartg)(double *f, double *g, double *cs, double *sn, double *r);
+void BLAS_FUNC(dlartgp)(double *f, double *g, double *cs, double *sn, double *r);
+void BLAS_FUNC(dlartgs)(double *x, double *y, double *sigma, double *cs, double *sn);
+void BLAS_FUNC(dlartv)(int *n, double *x, int *incx, double *y, int *incy, double *c, double *s, int *incc);
+void BLAS_FUNC(dlaruv)(int *iseed, int *n, double *x);
+void BLAS_FUNC(dlarz)(char *side, int *m, int *n, int *l, double *v, int *incv, double *tau, double *c, int *ldc, double *work);
+void BLAS_FUNC(dlarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, double *v, int *ldv, double *t, int *ldt, double *c, int *ldc, double *work, int *ldwork);
+void BLAS_FUNC(dlarzt)(char *direct, char *storev, int *n, int *k, double *v, int *ldv, double *tau, double *t, int *ldt);
+void BLAS_FUNC(dlas2)(double *f, double *g, double *h, double *ssmin, double *ssmax);
+void BLAS_FUNC(dlascl)(char *type_bn, int *kl, int *ku, double *cfrom, double *cto, int *m, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dlasd0)(int *n, int *sqre, double *d, double *e, double *u, int *ldu, double *vt, int *ldvt, int *smlsiz, int *iwork, double *work, int *info);
+void BLAS_FUNC(dlasd1)(int *nl, int *nr, int *sqre, double *d, double *alpha, double *beta, double *u, int *ldu, double *vt, int *ldvt, int *idxq, int *iwork, double *work, int *info);
+void BLAS_FUNC(dlasd2)(int *nl, int *nr, int *sqre, int *k, double *d, double *z, double *alpha, double *beta, double *u, int *ldu, double *vt, int *ldvt, double *dsigma, double *u2, int *ldu2, double *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info);
+void BLAS_FUNC(dlasd3)(int *nl, int *nr, int *sqre, int *k, double *d, double *q, int *ldq, double *dsigma, double *u, int *ldu, double *u2, int *ldu2, double *vt, int *ldvt, double *vt2, int *ldvt2, int *idxc, int *ctot, double *z, int *info);
+void BLAS_FUNC(dlasd4)(int *n, int *i, double *d, double *z, double *delta, double *rho, double *sigma, double *work, int *info);
+void BLAS_FUNC(dlasd5)(int *i, double *d, double *z, double *delta, double *rho, double *dsigma, double *work);
+void BLAS_FUNC(dlasd6)(int *icompq, int *nl, int *nr, int *sqre, double *d, double *vf, double *vl, double *alpha, double *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlasd7)(int *icompq, int *nl, int *nr, int *sqre, int *k, double *d, double *z, double *zw, double *vf, double *vfw, double *vl, double *vlw, double *alpha, double *beta, double *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *c, double *s, int *info);
+void BLAS_FUNC(dlasd8)(int *icompq, int *k, double *d, double *z, double *vf, double *vl, double *difl, double *difr, int *lddifr, double *dsigma, double *work, int *info);
+void BLAS_FUNC(dlasda)(int *icompq, int *smlsiz, int *n, int *sqre, double *d, double *e, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *work, int *iwork, int *info);
+void BLAS_FUNC(dlasdq)(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, double *vt, int *ldvt, double *u, int *ldu, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dlasdt)(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub);
+void BLAS_FUNC(dlaset)(char *uplo, int *m, int *n, double *alpha, double *beta, double *a, int *lda);
+void BLAS_FUNC(dlasq1)(int *n, double *d, double *e, double *work, int *info);
+void BLAS_FUNC(dlasq2)(int *n, double *z, int *info);
+void BLAS_FUNC(dlasq3)(int *i0, int *n0, double *z, int *pp, double *dmin, double *sigma, double *desig, double *qmax, int *nfail, int *iter, int *ndiv, int *ieee, int *ttype, double *dmin1, double *dmin2, double *dn, double *dn1, double *dn2, double *g, double *tau);
+void BLAS_FUNC(dlasq4)(int *i0, int *n0, double *z, int *pp, int *n0in, double *dmin, double *dmin1, double *dmin2, double *dn, double *dn1, double *dn2, double *tau, int *ttype, double *g);
+void BLAS_FUNC(dlasq6)(int *i0, int *n0, double *z, int *pp, double *dmin, double *dmin1, double *dmin2, double *dn, double *dnm1, double *dnm2);
+void BLAS_FUNC(dlasr)(char *side, char *pivot, char *direct, int *m, int *n, double *c, double *s, double *a, int *lda);
+void BLAS_FUNC(dlasrt)(char *id, int *n, double *d, int *info);
+void BLAS_FUNC(dlassq)(int *n, double *x, int *incx, double *scale, double *sumsq);
+void BLAS_FUNC(dlasv2)(double *f, double *g, double *h, double *ssmin, double *ssmax, double *snr, double *csr, double *snl, double *csl);
+void BLAS_FUNC(dlaswp)(int *n, double *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(dlasy2)(int *ltranl, int *ltranr, int *isgn, int *n1, int *n2, double *tl, int *ldtl, double *tr, int *ldtr, double *b, int *ldb, double *scale, double *x, int *ldx, double *xnorm, int *info);
+void BLAS_FUNC(dlasyf)(char *uplo, int *n, int *nb, int *kb, double *a, int *lda, int *ipiv, double *w, int *ldw, int *info);
+void BLAS_FUNC(dlat2s)(char *uplo, int *n, double *a, int *lda, float *sa, int *ldsa, int *info);
+void BLAS_FUNC(dlatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, double *ab, int *ldab, double *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(dlatdf)(int *ijob, int *n, double *z, int *ldz, double *rhs, double *rdsum, double *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(dlatps)(char *uplo, char *trans, char *diag, char *normin, int *n, double *ap, double *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(dlatrd)(char *uplo, int *n, int *nb, double *a, int *lda, double *e, double *tau, double *w, int *ldw);
+void BLAS_FUNC(dlatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, double *a, int *lda, double *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(dlatrz)(int *m, int *n, int *l, double *a, int *lda, double *tau, double *work);
+void BLAS_FUNC(dlauu2)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dlauum)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dopgtr)(char *uplo, int *n, double *ap, double *tau, double *q, int *ldq, double *work, int *info);
+void BLAS_FUNC(dopmtr)(char *side, char *uplo, char *trans, int *m, int *n, double *ap, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dorbdb)(char *trans, char *signs, int *m, int *p, int *q, double *x11, int *ldx11, double *x12, int *ldx12, double *x21, int *ldx21, double *x22, int *ldx22, double *theta, double *phi, double *taup1, double *taup2, double *tauq1, double *tauq2, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, double *x11, int *ldx11, double *x12, int *ldx12, double *x21, int *ldx21, double *x22, int *ldx22, double *theta, double *u1, int *ldu1, double *u2, int *ldu2, double *v1t, int *ldv1t, double *v2t, int *ldv2t, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dorg2l)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorg2r)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorgbr)(char *vect, int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorghr)(int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgl2)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorglq)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgql)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgqr)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgr2)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *info);
+void BLAS_FUNC(dorgrq)(int *m, int *n, int *k, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorgtr)(char *uplo, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorm2l)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dorm2r)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dorml2)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormlq)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormql)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormqr)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormr2)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormr3)(char *side, char *trans, int *m, int *n, int *k, int *l, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *info);
+void BLAS_FUNC(dormrq)(char *side, char *trans, int *m, int *n, int *k, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormrz)(char *side, char *trans, int *m, int *n, int *k, int *l, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dormtr)(char *side, char *uplo, char *trans, int *m, int *n, double *a, int *lda, double *tau, double *c, int *ldc, double *work, int *lwork, int *info);
+void BLAS_FUNC(dpbcon)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpbequ)(char *uplo, int *n, int *kd, double *ab, int *ldab, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dpbrfs)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpbstf)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info);
+void BLAS_FUNC(dpbsv)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *afb, int *ldafb, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpbtf2)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info);
+void BLAS_FUNC(dpbtrf)(char *uplo, int *n, int *kd, double *ab, int *ldab, int *info);
+void BLAS_FUNC(dpbtrs)(char *uplo, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpftrf)(char *transr, char *uplo, int *n, double *a, int *info);
+void BLAS_FUNC(dpftri)(char *transr, char *uplo, int *n, double *a, int *info);
+void BLAS_FUNC(dpftrs)(char *transr, char *uplo, int *n, int *nrhs, double *a, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpocon)(char *uplo, int *n, double *a, int *lda, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpoequ)(int *n, double *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dpoequb)(int *n, double *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dporfs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dposv)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dposvx)(char *fact, char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpotf2)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dpotrf)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dpotri)(char *uplo, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dpotrs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dppcon)(char *uplo, int *n, double *ap, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dppequ)(char *uplo, int *n, double *ap, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(dpprfs)(char *uplo, int *n, int *nrhs, double *ap, double *afp, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dppsv)(char *uplo, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info);
+void BLAS_FUNC(dppsvx)(char *fact, char *uplo, int *n, int *nrhs, double *ap, double *afp, char *equed, double *s, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dpptrf)(char *uplo, int *n, double *ap, int *info);
+void BLAS_FUNC(dpptri)(char *uplo, int *n, double *ap, int *info);
+void BLAS_FUNC(dpptrs)(char *uplo, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info);
+void BLAS_FUNC(dpstf2)(char *uplo, int *n, double *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(dpstrf)(char *uplo, int *n, double *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(dptcon)(int *n, double *d, double *e, double *anorm, double *rcond, double *work, int *info);
+void BLAS_FUNC(dpteqr)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dptrfs)(int *n, int *nrhs, double *d, double *e, double *df, double *ef, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *info);
+void BLAS_FUNC(dptsv)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb, int *info);
+void BLAS_FUNC(dptsvx)(char *fact, int *n, int *nrhs, double *d, double *e, double *df, double *ef, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *info);
+void BLAS_FUNC(dpttrf)(int *n, double *d, double *e, int *info);
+void BLAS_FUNC(dpttrs)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb, int *info);
+void BLAS_FUNC(dptts2)(int *n, int *nrhs, double *d, double *e, double *b, int *ldb);
+void BLAS_FUNC(drscl)(int *n, double *sa, double *sx, int *incx);
+void BLAS_FUNC(dsbev)(char *jobz, char *uplo, int *n, int *kd, double *ab, int *ldab, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dsbevd)(char *jobz, char *uplo, int *n, int *kd, double *ab, int *ldab, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, double *ab, int *ldab, double *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *x, int *ldx, double *work, int *info);
+void BLAS_FUNC(dsbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dsbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, double *ab, int *ldab, double *bb, int *ldbb, double *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsbtrd)(char *vect, char *uplo, int *n, int *kd, double *ab, int *ldab, double *d, double *e, double *q, int *ldq, double *work, int *info);
+void BLAS_FUNC(dsfrk)(char *transr, char *uplo, char *trans, int *n, int *k, double *alpha, double *a, int *lda, double *beta, double *c);
+void BLAS_FUNC(dsgesv)(int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *work, float *swork, int *iter, int *info);
+void BLAS_FUNC(dspcon)(char *uplo, int *n, double *ap, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dspev)(char *jobz, char *uplo, int *n, double *ap, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dspevd)(char *jobz, char *uplo, int *n, double *ap, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dspevx)(char *jobz, char *range, char *uplo, int *n, double *ap, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dspgst)(int *itype, char *uplo, int *n, double *ap, double *bp, int *info);
+void BLAS_FUNC(dspgv)(int *itype, char *jobz, char *uplo, int *n, double *ap, double *bp, double *w, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dspgvd)(int *itype, char *jobz, char *uplo, int *n, double *ap, double *bp, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dspgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, double *ap, double *bp, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsposv)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *x, int *ldx, double *work, float *swork, int *iter, int *info);
+void BLAS_FUNC(dsprfs)(char *uplo, int *n, int *nrhs, double *ap, double *afp, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dspsv)(char *uplo, int *n, int *nrhs, double *ap, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dspsvx)(char *fact, char *uplo, int *n, int *nrhs, double *ap, double *afp, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dsptrd)(char *uplo, int *n, double *ap, double *d, double *e, double *tau, int *info);
+void BLAS_FUNC(dsptrf)(char *uplo, int *n, double *ap, int *ipiv, int *info);
+void BLAS_FUNC(dsptri)(char *uplo, int *n, double *ap, int *ipiv, double *work, int *info);
+void BLAS_FUNC(dsptrs)(char *uplo, int *n, int *nrhs, double *ap, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dstebz)(char *range, char *order, int *n, double *vl, double *vu, int *il, int *iu, double *abstol, double *d, double *e, int *m, int *nsplit, double *w, int *iblock, int *isplit, double *work, int *iwork, int *info);
+void BLAS_FUNC(dstedc)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstegr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstein)(int *n, double *d, double *e, int *m, double *w, int *iblock, int *isplit, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dstemr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, int *m, double *w, double *z, int *ldz, int *nzc, int *isuppz, int *tryrac, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsteqr)(char *compz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dsterf)(int *n, double *d, double *e, int *info);
+void BLAS_FUNC(dstev)(char *jobz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(dstevd)(char *jobz, int *n, double *d, double *e, double *z, int *ldz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstevr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dstevx)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsycon)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *anorm, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dsyconv)(char *uplo, char *way, int *n, double *a, int *lda, int *ipiv, double *work, int *info);
+void BLAS_FUNC(dsyequb)(char *uplo, int *n, double *a, int *lda, double *s, double *scond, double *amax, double *work, int *info);
+void BLAS_FUNC(dsyev)(char *jobz, char *uplo, int *n, double *a, int *lda, double *w, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsyevd)(char *jobz, char *uplo, int *n, double *a, int *lda, double *w, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsyevr)(char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsyevx)(char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsygs2)(int *itype, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dsygst)(int *itype, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dsygv)(int *itype, char *jobz, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *w, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsygvd)(int *itype, char *jobz, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *w, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dsygvx)(int *itype, char *jobz, char *range, char *uplo, int *n, double *a, int *lda, double *b, int *ldb, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, double *z, int *ldz, double *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(dsyrfs)(char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dsysv)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsysvx)(char *fact, char *uplo, int *n, int *nrhs, double *a, int *lda, double *af, int *ldaf, int *ipiv, double *b, int *ldb, double *x, int *ldx, double *rcond, double *ferr, double *berr, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dsyswapr)(char *uplo, int *n, double *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(dsytd2)(char *uplo, int *n, double *a, int *lda, double *d, double *e, double *tau, int *info);
+void BLAS_FUNC(dsytf2)(char *uplo, int *n, double *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(dsytrd)(char *uplo, int *n, double *a, int *lda, double *d, double *e, double *tau, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsytrf)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsytri)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *info);
+void BLAS_FUNC(dsytri2)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *lwork, int *info);
+void BLAS_FUNC(dsytri2x)(char *uplo, int *n, double *a, int *lda, int *ipiv, double *work, int *nb, int *info);
+void BLAS_FUNC(dsytrs)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, int *info);
+void BLAS_FUNC(dsytrs2)(char *uplo, int *n, int *nrhs, double *a, int *lda, int *ipiv, double *b, int *ldb, double *work, int *info);
+void BLAS_FUNC(dtbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, double *ab, int *ldab, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, double *ab, int *ldab, double *b, int *ldb, int *info);
+void BLAS_FUNC(dtfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, double *alpha, double *a, double *b, int *ldb);
+void BLAS_FUNC(dtftri)(char *transr, char *uplo, char *diag, int *n, double *a, int *info);
+void BLAS_FUNC(dtfttp)(char *transr, char *uplo, int *n, double *arf, double *ap, int *info);
+void BLAS_FUNC(dtfttr)(char *transr, char *uplo, int *n, double *arf, double *a, int *lda, int *info);
+void BLAS_FUNC(dtgevc)(char *side, char *howmny, int *select, int *n, double *s, int *lds, double *p, int *ldp, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *info);
+void BLAS_FUNC(dtgex2)(int *wantq, int *wantz, int *n, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *j1, int *n1, int *n2, double *work, int *lwork, int *info);
+void BLAS_FUNC(dtgexc)(int *wantq, int *wantz, int *n, double *a, int *lda, double *b, int *ldb, double *q, int *ldq, double *z, int *ldz, int *ifst, int *ilst, double *work, int *lwork, int *info);
+void BLAS_FUNC(dtgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, double *a, int *lda, double *b, int *ldb, double *alphar, double *alphai, double *beta, double *q, int *ldq, double *z, int *ldz, int *m, double *pl, double *pr, double *dif, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dtgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, double *a, int *lda, double *b, int *ldb, double *tola, double *tolb, double *alpha, double *beta, double *u, int *ldu, double *v, int *ldv, double *q, int *ldq, double *work, int *ncycle, int *info);
+void BLAS_FUNC(dtgsna)(char *job, char *howmny, int *select, int *n, double *a, int *lda, double *b, int *ldb, double *vl, int *ldvl, double *vr, int *ldvr, double *s, double *dif, int *mm, int *m, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dtgsy2)(char *trans, int *ijob, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *d, int *ldd, double *e, int *lde, double *f, int *ldf, double *scale, double *rdsum, double *rdscal, int *iwork, int *pq, int *info);
+void BLAS_FUNC(dtgsyl)(char *trans, int *ijob, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *d, int *ldd, double *e, int *lde, double *f, int *ldf, double *scale, double *dif, double *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(dtpcon)(char *norm, char *uplo, char *diag, int *n, double *ap, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, double *v, int *ldv, double *t, int *ldt, double *a, int *lda, double *b, int *ldb, double *work, int *info);
+void BLAS_FUNC(dtpqrt)(int *m, int *n, int *l, int *nb, double *a, int *lda, double *b, int *ldb, double *t, int *ldt, double *work, int *info);
+void BLAS_FUNC(dtpqrt2)(int *m, int *n, int *l, double *a, int *lda, double *b, int *ldb, double *t, int *ldt, int *info);
+void BLAS_FUNC(dtprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, double *v, int *ldv, double *t, int *ldt, double *a, int *lda, double *b, int *ldb, double *work, int *ldwork);
+void BLAS_FUNC(dtprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *ap, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtptri)(char *uplo, char *diag, int *n, double *ap, int *info);
+void BLAS_FUNC(dtptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *ap, double *b, int *ldb, int *info);
+void BLAS_FUNC(dtpttf)(char *transr, char *uplo, int *n, double *ap, double *arf, int *info);
+void BLAS_FUNC(dtpttr)(char *uplo, int *n, double *ap, double *a, int *lda, int *info);
+void BLAS_FUNC(dtrcon)(char *norm, char *uplo, char *diag, int *n, double *a, int *lda, double *rcond, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtrevc)(char *side, char *howmny, int *select, int *n, double *t, int *ldt, double *vl, int *ldvl, double *vr, int *ldvr, int *mm, int *m, double *work, int *info);
+void BLAS_FUNC(dtrexc)(char *compq, int *n, double *t, int *ldt, double *q, int *ldq, int *ifst, int *ilst, double *work, int *info);
+void BLAS_FUNC(dtrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, double *x, int *ldx, double *ferr, double *berr, double *work, int *iwork, int *info);
+void BLAS_FUNC(dtrsen)(char *job, char *compq, int *select, int *n, double *t, int *ldt, double *q, int *ldq, double *wr, double *wi, int *m, double *s, double *sep, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(dtrsna)(char *job, char *howmny, int *select, int *n, double *t, int *ldt, double *vl, int *ldvl, double *vr, int *ldvr, double *s, double *sep, int *mm, int *m, double *work, int *ldwork, int *iwork, int *info);
+void BLAS_FUNC(dtrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, double *a, int *lda, double *b, int *ldb, double *c, int *ldc, double *scale, int *info);
+void BLAS_FUNC(dtrti2)(char *uplo, char *diag, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dtrtri)(char *uplo, char *diag, int *n, double *a, int *lda, int *info);
+void BLAS_FUNC(dtrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, double *a, int *lda, double *b, int *ldb, int *info);
+void BLAS_FUNC(dtrttf)(char *transr, char *uplo, int *n, double *a, int *lda, double *arf, int *info);
+void BLAS_FUNC(dtrttp)(char *uplo, int *n, double *a, int *lda, double *ap, int *info);
+void BLAS_FUNC(dtzrzf)(int *m, int *n, double *a, int *lda, double *tau, double *work, int *lwork, int *info);
+double BLAS_FUNC(dzsum1)(int *n, npy_complex128 *cx, int *incx);
+int BLAS_FUNC(icmax1)(int *n, npy_complex64 *cx, int *incx);
+int BLAS_FUNC(ieeeck)(int *ispec, float *zero, float *one);
+int BLAS_FUNC(ilaclc)(int *m, int *n, npy_complex64 *a, int *lda);
+int BLAS_FUNC(ilaclr)(int *m, int *n, npy_complex64 *a, int *lda);
+int BLAS_FUNC(iladiag)(char *diag);
+int BLAS_FUNC(iladlc)(int *m, int *n, double *a, int *lda);
+int BLAS_FUNC(iladlr)(int *m, int *n, double *a, int *lda);
+int BLAS_FUNC(ilaprec)(char *prec);
+int BLAS_FUNC(ilaslc)(int *m, int *n, float *a, int *lda);
+int BLAS_FUNC(ilaslr)(int *m, int *n, float *a, int *lda);
+int BLAS_FUNC(ilatrans)(char *trans);
+int BLAS_FUNC(ilauplo)(char *uplo);
+void BLAS_FUNC(ilaver)(int *vers_major, int *vers_minor, int *vers_patch);
+int BLAS_FUNC(ilazlc)(int *m, int *n, npy_complex128 *a, int *lda);
+int BLAS_FUNC(ilazlr)(int *m, int *n, npy_complex128 *a, int *lda);
+int BLAS_FUNC(izmax1)(int *n, npy_complex128 *cx, int *incx);
+void BLAS_FUNC(sbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, float *theta, float *phi, float *u1, int *ldu1, float *u2, int *ldu2, float *v1t, int *ldv1t, float *v2t, int *ldv2t, float *b11d, float *b11e, float *b12d, float *b12e, float *b21d, float *b21e, float *b22d, float *b22e, float *work, int *lwork, int *info);
+void BLAS_FUNC(sbdsdc)(char *uplo, char *compq, int *n, float *d, float *e, float *u, int *ldu, float *vt, int *ldvt, float *q, int *iq, float *work, int *iwork, int *info);
+void BLAS_FUNC(sbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, float *vt, int *ldvt, float *u, int *ldu, float *c, int *ldc, float *work, int *info);
+float BLAS_FUNC(scsum1)(int *n, npy_complex64 *cx, int *incx);
+void BLAS_FUNC(sdisna)(char *job, int *m, int *n, float *d, float *sep, int *info);
+void BLAS_FUNC(sgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, float *ab, int *ldab, float *d, float *e, float *q, int *ldq, float *pt, int *ldpt, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sgbcon)(char *norm, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgbequ)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgbequb)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgbsv)(int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, int *ipiv, char *equed, float *r, float *c, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgbtf2)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(sgbtrf)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(sgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, float *ab, int *ldab, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgebak)(char *job, char *side, int *n, int *ilo, int *ihi, float *scale, int *m, float *v, int *ldv, int *info);
+void BLAS_FUNC(sgebal)(char *job, int *n, float *a, int *lda, int *ilo, int *ihi, float *scale, int *info);
+void BLAS_FUNC(sgebd2)(int *m, int *n, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *work, int *info);
+void BLAS_FUNC(sgebrd)(int *m, int *n, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgecon)(char *norm, int *n, float *a, int *lda, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgeequ)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgeequb)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, int *info);
+void BLAS_FUNC(sgees)(char *jobvs, char *sort, _sselect2 *select, int *n, float *a, int *lda, int *sdim, float *wr, float *wi, float *vs, int *ldvs, float *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(sgeesx)(char *jobvs, char *sort, _sselect2 *select, char *sense, int *n, float *a, int *lda, int *sdim, float *wr, float *wi, float *vs, int *ldvs, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(sgeev)(char *jobvl, char *jobvr, int *n, float *a, int *lda, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, float *a, int *lda, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, int *ilo, int *ihi, float *scale, float *abnrm, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgehd2)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgehrd)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgejsv)(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, float *a, int *lda, float *sva, float *u, int *ldu, float *v, int *ldv, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgelq2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgelqf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgels)(char *trans, int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgelsd)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *s, float *rcond, int *rank, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgelss)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *s, float *rcond, int *rank, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgelsy)(int *m, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *jpvt, float *rcond, int *rank, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sgeql2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgeqlf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqp3)(int *m, int *n, float *a, int *lda, int *jpvt, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqr2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgeqr2p)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgeqrf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqrfp)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgeqrt)(int *m, int *n, int *nb, float *a, int *lda, float *t, int *ldt, float *work, int *info);
+void BLAS_FUNC(sgeqrt2)(int *m, int *n, float *a, int *lda, float *t, int *ldt, int *info);
+void BLAS_FUNC(sgeqrt3)(int *m, int *n, float *a, int *lda, float *t, int *ldt, int *info);
+void BLAS_FUNC(sgerfs)(char *trans, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgerq2)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sgerqf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgesc2)(int *n, float *a, int *lda, float *rhs, int *ipiv, int *jpiv, float *scale);
+void BLAS_FUNC(sgesdd)(char *jobz, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sgesv)(int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgesvd)(char *jobu, char *jobvt, int *m, int *n, float *a, int *lda, float *s, float *u, int *ldu, float *vt, int *ldvt, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgesvj)(char *joba, char *jobu, char *jobv, int *m, int *n, float *a, int *lda, float *sva, int *mv, float *v, int *ldv, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgesvx)(char *fact, char *trans, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, char *equed, float *r, float *c, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgetc2)(int *n, float *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(sgetf2)(int *m, int *n, float *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(sgetrf)(int *m, int *n, float *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(sgetri)(int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgetrs)(char *trans, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sggbak)(char *job, char *side, int *n, int *ilo, int *ihi, float *lscale, float *rscale, int *m, float *v, int *ldv, int *info);
+void BLAS_FUNC(sggbal)(char *job, int *n, float *a, int *lda, float *b, int *ldb, int *ilo, int *ihi, float *lscale, float *rscale, float *work, int *info);
+void BLAS_FUNC(sgges)(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *work, int *lwork, int *bwork, int *info);
+void BLAS_FUNC(sggesx)(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, char *sense, int *n, float *a, int *lda, float *b, int *ldb, int *sdim, float *alphar, float *alphai, float *beta, float *vsl, int *ldvsl, float *vsr, int *ldvsr, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(sggev)(char *jobvl, char *jobvr, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *vl, int *ldvl, float *vr, int *ldvr, float *work, int *lwork, int *info);
+void BLAS_FUNC(sggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *vl, int *ldvl, float *vr, int *ldvr, int *ilo, int *ihi, float *lscale, float *rscale, float *abnrm, float *bbnrm, float *rconde, float *rcondv, float *work, int *lwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(sggglm)(int *n, int *m, int *p, float *a, int *lda, float *b, int *ldb, float *d, float *x, float *y, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *info);
+void BLAS_FUNC(sgglse)(int *m, int *n, int *p, float *a, int *lda, float *b, int *ldb, float *c, float *d, float *x, float *work, int *lwork, int *info);
+void BLAS_FUNC(sggqrf)(int *n, int *m, int *p, float *a, int *lda, float *taua, float *b, int *ldb, float *taub, float *work, int *lwork, int *info);
+void BLAS_FUNC(sggrqf)(int *m, int *p, int *n, float *a, int *lda, float *taua, float *b, int *ldb, float *taub, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgsvj0)(char *jobv, int *m, int *n, float *a, int *lda, float *d, float *sva, int *mv, float *v, int *ldv, float *eps, float *sfmin, float *tol, int *nsweep, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgsvj1)(char *jobv, int *m, int *n, int *n1, float *a, int *lda, float *d, float *sva, int *mv, float *v, int *ldv, float *eps, float *sfmin, float *tol, int *nsweep, float *work, int *lwork, int *info);
+void BLAS_FUNC(sgtcon)(char *norm, int *n, float *dl, float *d, float *du, float *du2, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgtrfs)(char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *dlf, float *df, float *duf, float *du2, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgtsv)(int *n, int *nrhs, float *dl, float *d, float *du, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgtsvx)(char *fact, char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *dlf, float *df, float *duf, float *du2, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sgttrf)(int *n, float *dl, float *d, float *du, float *du2, int *ipiv, int *info);
+void BLAS_FUNC(sgttrs)(char *trans, int *n, int *nrhs, float *dl, float *d, float *du, float *du2, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sgtts2)(int *itrans, int *n, int *nrhs, float *dl, float *d, float *du, float *du2, int *ipiv, float *b, int *ldb);
+void BLAS_FUNC(shgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *t, int *ldt, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(shsein)(char *side, char *eigsrc, char *initv, int *select, int *n, float *h, int *ldh, float *wr, float *wi, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(shseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(slabad)(float *small, float *large);
+void BLAS_FUNC(slabrd)(int *m, int *n, int *nb, float *a, int *lda, float *d, float *e, float *tauq, float *taup, float *x, int *ldx, float *y, int *ldy);
+void BLAS_FUNC(slacn2)(int *n, float *v, float *x, int *isgn, float *est, int *kase, int *isave);
+void BLAS_FUNC(slacon)(int *n, float *v, float *x, int *isgn, float *est, int *kase);
+void BLAS_FUNC(slacpy)(char *uplo, int *m, int *n, float *a, int *lda, float *b, int *ldb);
+void BLAS_FUNC(sladiv)(float *a, float *b, float *c, float *d, float *p, float *q);
+void BLAS_FUNC(slae2)(float *a, float *b, float *c, float *rt1, float *rt2);
+void BLAS_FUNC(slaebz)(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, float *abstol, float *reltol, float *pivmin, float *d, float *e, float *e2, int *nval, float *ab, float *c, int *mout, int *nab, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed0)(int *icompq, int *qsiz, int *n, float *d, float *e, float *q, int *ldq, float *qstore, int *ldqs, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed1)(int *n, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed2)(int *k, int *n, int *n1, float *d, float *q, int *ldq, int *indxq, float *rho, float *z, float *dlamda, float *w, float *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info);
+void BLAS_FUNC(slaed3)(int *k, int *n, int *n1, float *d, float *q, int *ldq, float *rho, float *dlamda, float *q2, int *indx, int *ctot, float *w, float *s, int *info);
+void BLAS_FUNC(slaed4)(int *n, int *i, float *d, float *z, float *delta, float *rho, float *dlam, int *info);
+void BLAS_FUNC(slaed5)(int *i, float *d, float *z, float *delta, float *rho, float *dlam);
+void BLAS_FUNC(slaed6)(int *kniter, int *orgati, float *rho, float *d, float *z, float *finit, float *tau, int *info);
+void BLAS_FUNC(slaed7)(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, float *work, int *iwork, int *info);
+void BLAS_FUNC(slaed8)(int *icompq, int *k, int *n, int *qsiz, float *d, float *q, int *ldq, int *indxq, float *rho, int *cutpnt, float *z, float *dlamda, float *q2, int *ldq2, float *w, int *perm, int *givptr, int *givcol, float *givnum, int *indxp, int *indx, int *info);
+void BLAS_FUNC(slaed9)(int *k, int *kstart, int *kstop, int *n, float *d, float *q, int *ldq, float *rho, float *dlamda, float *w, float *s, int *lds, int *info);
+void BLAS_FUNC(slaeda)(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, float *givnum, float *q, int *qptr, float *z, float *ztemp, int *info);
+void BLAS_FUNC(slaein)(int *rightv, int *noinit, int *n, float *h, int *ldh, float *wr, float *wi, float *vr, float *vi, float *b, int *ldb, float *work, float *eps3, float *smlnum, float *bignum, int *info);
+void BLAS_FUNC(slaev2)(float *a, float *b, float *c, float *rt1, float *rt2, float *cs1, float *sn1);
+void BLAS_FUNC(slaexc)(int *wantq, int *n, float *t, int *ldt, float *q, int *ldq, int *j1, int *n1, int *n2, float *work, int *info);
+void BLAS_FUNC(slag2)(float *a, int *lda, float *b, int *ldb, float *safmin, float *scale1, float *scale2, float *wr1, float *wr2, float *wi);
+void BLAS_FUNC(slag2d)(int *m, int *n, float *sa, int *ldsa, double *a, int *lda, int *info);
+void BLAS_FUNC(slags2)(int *upper, float *a1, float *a2, float *a3, float *b1, float *b2, float *b3, float *csu, float *snu, float *csv, float *snv, float *csq, float *snq);
+void BLAS_FUNC(slagtf)(int *n, float *a, float *lambda_, float *b, float *c, float *tol, float *d, int *in_, int *info);
+void BLAS_FUNC(slagtm)(char *trans, int *n, int *nrhs, float *alpha, float *dl, float *d, float *du, float *x, int *ldx, float *beta, float *b, int *ldb);
+void BLAS_FUNC(slagts)(int *job, int *n, float *a, float *b, float *c, float *d, int *in_, float *y, float *tol, int *info);
+void BLAS_FUNC(slagv2)(float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *csl, float *snl, float *csr, float *snr);
+void BLAS_FUNC(slahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, int *info);
+void BLAS_FUNC(slahr2)(int *n, int *k, int *nb, float *a, int *lda, float *tau, float *t, int *ldt, float *y, int *ldy);
+void BLAS_FUNC(slaic1)(int *job, int *j, float *x, float *sest, float *w, float *gamma, float *sestpr, float *s, float *c);
+void BLAS_FUNC(slaln2)(int *ltrans, int *na, int *nw, float *smin, float *ca, float *a, int *lda, float *d1, float *d2, float *b, int *ldb, float *wr, float *wi, float *x, int *ldx, float *scale, float *xnorm, int *info);
+void BLAS_FUNC(slals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, float *b, int *ldb, float *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *work, int *info);
+void BLAS_FUNC(slalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, float *b, int *ldb, float *bx, int *ldbx, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *work, int *iwork, int *info);
+void BLAS_FUNC(slalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, float *d, float *e, float *b, int *ldb, float *rcond, int *rank, float *work, int *iwork, int *info);
+float BLAS_FUNC(slamch)(char *cmach);
+void BLAS_FUNC(slamrg)(int *n1, int *n2, float *a, int *strd1, int *strd2, int *index_bn);
+float BLAS_FUNC(slangb)(char *norm, int *n, int *kl, int *ku, float *ab, int *ldab, float *work);
+float BLAS_FUNC(slange)(char *norm, int *m, int *n, float *a, int *lda, float *work);
+float BLAS_FUNC(slangt)(char *norm, int *n, float *dl, float *d, float *du);
+float BLAS_FUNC(slanhs)(char *norm, int *n, float *a, int *lda, float *work);
+float BLAS_FUNC(slansb)(char *norm, char *uplo, int *n, int *k, float *ab, int *ldab, float *work);
+float BLAS_FUNC(slansf)(char *norm, char *transr, char *uplo, int *n, float *a, float *work);
+float BLAS_FUNC(slansp)(char *norm, char *uplo, int *n, float *ap, float *work);
+float BLAS_FUNC(slanst)(char *norm, int *n, float *d, float *e);
+float BLAS_FUNC(slansy)(char *norm, char *uplo, int *n, float *a, int *lda, float *work);
+float BLAS_FUNC(slantb)(char *norm, char *uplo, char *diag, int *n, int *k, float *ab, int *ldab, float *work);
+float BLAS_FUNC(slantp)(char *norm, char *uplo, char *diag, int *n, float *ap, float *work);
+float BLAS_FUNC(slantr)(char *norm, char *uplo, char *diag, int *m, int *n, float *a, int *lda, float *work);
+void BLAS_FUNC(slanv2)(float *a, float *b, float *c, float *d, float *rt1r, float *rt1i, float *rt2r, float *rt2i, float *cs, float *sn);
+void BLAS_FUNC(slapll)(int *n, float *x, int *incx, float *y, int *incy, float *ssmin);
+void BLAS_FUNC(slapmr)(int *forwrd, int *m, int *n, float *x, int *ldx, int *k);
+void BLAS_FUNC(slapmt)(int *forwrd, int *m, int *n, float *x, int *ldx, int *k);
+float BLAS_FUNC(slapy2)(float *x, float *y);
+float BLAS_FUNC(slapy3)(float *x, float *y, float *z);
+void BLAS_FUNC(slaqgb)(int *m, int *n, int *kl, int *ku, float *ab, int *ldab, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(slaqge)(int *m, int *n, float *a, int *lda, float *r, float *c, float *rowcnd, float *colcnd, float *amax, char *equed);
+void BLAS_FUNC(slaqp2)(int *m, int *n, int *offset, float *a, int *lda, int *jpvt, float *tau, float *vn1, float *vn2, float *work);
+void BLAS_FUNC(slaqps)(int *m, int *n, int *offset, int *nb, int *kb, float *a, int *lda, int *jpvt, float *tau, float *vn1, float *vn2, float *auxv, float *f, int *ldf);
+void BLAS_FUNC(slaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(slaqr1)(int *n, float *h, int *ldh, float *sr1, float *si1, float *sr2, float *si2, float *v);
+void BLAS_FUNC(slaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, int *ns, int *nd, float *sr, float *si, float *v, int *ldv, int *nh, float *t, int *ldt, int *nv, float *wv, int *ldwv, float *work, int *lwork);
+void BLAS_FUNC(slaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, int *ns, int *nd, float *sr, float *si, float *v, int *ldv, int *nh, float *t, int *ldt, int *nv, float *wv, int *ldwv, float *work, int *lwork);
+void BLAS_FUNC(slaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, float *h, int *ldh, float *wr, float *wi, int *iloz, int *ihiz, float *z, int *ldz, float *work, int *lwork, int *info);
+void BLAS_FUNC(slaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, float *sr, float *si, float *h, int *ldh, int *iloz, int *ihiz, float *z, int *ldz, float *v, int *ldv, float *u, int *ldu, int *nv, float *wv, int *ldwv, int *nh, float *wh, int *ldwh);
+void BLAS_FUNC(slaqsb)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(slaqsp)(char *uplo, int *n, float *ap, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(slaqsy)(char *uplo, int *n, float *a, int *lda, float *s, float *scond, float *amax, char *equed);
+void BLAS_FUNC(slaqtr)(int *ltran, int *lreal, int *n, float *t, int *ldt, float *b, float *w, float *scale, float *x, float *work, int *info);
+void BLAS_FUNC(slar1v)(int *n, int *b1, int *bn, float *lambda_, float *d, float *l, float *ld, float *lld, float *pivmin, float *gaptol, float *z, int *wantnc, int *negcnt, float *ztz, float *mingma, int *r, int *isuppz, float *nrminv, float *resid, float *rqcorr, float *work);
+void BLAS_FUNC(slar2v)(int *n, float *x, float *y, float *z, int *incx, float *c, float *s, int *incc);
+void BLAS_FUNC(slarf)(char *side, int *m, int *n, float *v, int *incv, float *tau, float *c, int *ldc, float *work);
+void BLAS_FUNC(slarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *ldwork);
+void BLAS_FUNC(slarfg)(int *n, float *alpha, float *x, int *incx, float *tau);
+void BLAS_FUNC(slarfgp)(int *n, float *alpha, float *x, int *incx, float *tau);
+void BLAS_FUNC(slarft)(char *direct, char *storev, int *n, int *k, float *v, int *ldv, float *tau, float *t, int *ldt);
+void BLAS_FUNC(slarfx)(char *side, int *m, int *n, float *v, float *tau, float *c, int *ldc, float *work);
+void BLAS_FUNC(slargv)(int *n, float *x, int *incx, float *y, int *incy, float *c, int *incc);
+void BLAS_FUNC(slarnv)(int *idist, int *iseed, int *n, float *x);
+void BLAS_FUNC(slarra)(int *n, float *d, float *e, float *e2, float *spltol, float *tnrm, int *nsplit, int *isplit, int *info);
+void BLAS_FUNC(slarrb)(int *n, float *d, float *lld, int *ifirst, int *ilast, float *rtol1, float *rtol2, int *offset, float *w, float *wgap, float *werr, float *work, int *iwork, float *pivmin, float *spdiam, int *twist, int *info);
+void BLAS_FUNC(slarrc)(char *jobt, int *n, float *vl, float *vu, float *d, float *e, float *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info);
+void BLAS_FUNC(slarrd)(char *range, char *order, int *n, float *vl, float *vu, int *il, int *iu, float *gers, float *reltol, float *d, float *e, float *e2, float *pivmin, int *nsplit, int *isplit, int *m, float *w, float *werr, float *wl, float *wu, int *iblock, int *indexw, float *work, int *iwork, int *info);
+void BLAS_FUNC(slarre)(char *range, int *n, float *vl, float *vu, int *il, int *iu, float *d, float *e, float *e2, float *rtol1, float *rtol2, float *spltol, int *nsplit, int *isplit, int *m, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, float *pivmin, float *work, int *iwork, int *info);
+void BLAS_FUNC(slarrf)(int *n, float *d, float *l, float *ld, int *clstrt, int *clend, float *w, float *wgap, float *werr, float *spdiam, float *clgapl, float *clgapr, float *pivmin, float *sigma, float *dplus, float *lplus, float *work, int *info);
+void BLAS_FUNC(slarrj)(int *n, float *d, float *e2, int *ifirst, int *ilast, float *rtol, int *offset, float *w, float *werr, float *work, int *iwork, float *pivmin, float *spdiam, int *info);
+void BLAS_FUNC(slarrk)(int *n, int *iw, float *gl, float *gu, float *d, float *e2, float *pivmin, float *reltol, float *w, float *werr, int *info);
+void BLAS_FUNC(slarrr)(int *n, float *d, float *e, int *info);
+void BLAS_FUNC(slarrv)(int *n, float *vl, float *vu, float *d, float *l, float *pivmin, int *isplit, int *m, int *dol, int *dou, float *minrgp, float *rtol1, float *rtol2, float *w, float *werr, float *wgap, int *iblock, int *indexw, float *gers, float *z, int *ldz, int *isuppz, float *work, int *iwork, int *info);
+void BLAS_FUNC(slartg)(float *f, float *g, float *cs, float *sn, float *r);
+void BLAS_FUNC(slartgp)(float *f, float *g, float *cs, float *sn, float *r);
+void BLAS_FUNC(slartgs)(float *x, float *y, float *sigma, float *cs, float *sn);
+void BLAS_FUNC(slartv)(int *n, float *x, int *incx, float *y, int *incy, float *c, float *s, int *incc);
+void BLAS_FUNC(slaruv)(int *iseed, int *n, float *x);
+void BLAS_FUNC(slarz)(char *side, int *m, int *n, int *l, float *v, int *incv, float *tau, float *c, int *ldc, float *work);
+void BLAS_FUNC(slarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, float *v, int *ldv, float *t, int *ldt, float *c, int *ldc, float *work, int *ldwork);
+void BLAS_FUNC(slarzt)(char *direct, char *storev, int *n, int *k, float *v, int *ldv, float *tau, float *t, int *ldt);
+void BLAS_FUNC(slas2)(float *f, float *g, float *h, float *ssmin, float *ssmax);
+void BLAS_FUNC(slascl)(char *type_bn, int *kl, int *ku, float *cfrom, float *cto, int *m, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(slasd0)(int *n, int *sqre, float *d, float *e, float *u, int *ldu, float *vt, int *ldvt, int *smlsiz, int *iwork, float *work, int *info);
+void BLAS_FUNC(slasd1)(int *nl, int *nr, int *sqre, float *d, float *alpha, float *beta, float *u, int *ldu, float *vt, int *ldvt, int *idxq, int *iwork, float *work, int *info);
+void BLAS_FUNC(slasd2)(int *nl, int *nr, int *sqre, int *k, float *d, float *z, float *alpha, float *beta, float *u, int *ldu, float *vt, int *ldvt, float *dsigma, float *u2, int *ldu2, float *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info);
+void BLAS_FUNC(slasd3)(int *nl, int *nr, int *sqre, int *k, float *d, float *q, int *ldq, float *dsigma, float *u, int *ldu, float *u2, int *ldu2, float *vt, int *ldvt, float *vt2, int *ldvt2, int *idxc, int *ctot, float *z, int *info);
+void BLAS_FUNC(slasd4)(int *n, int *i, float *d, float *z, float *delta, float *rho, float *sigma, float *work, int *info);
+void BLAS_FUNC(slasd5)(int *i, float *d, float *z, float *delta, float *rho, float *dsigma, float *work);
+void BLAS_FUNC(slasd6)(int *icompq, int *nl, int *nr, int *sqre, float *d, float *vf, float *vl, float *alpha, float *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *poles, float *difl, float *difr, float *z, int *k, float *c, float *s, float *work, int *iwork, int *info);
+void BLAS_FUNC(slasd7)(int *icompq, int *nl, int *nr, int *sqre, int *k, float *d, float *z, float *zw, float *vf, float *vfw, float *vl, float *vlw, float *alpha, float *beta, float *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, float *givnum, int *ldgnum, float *c, float *s, int *info);
+void BLAS_FUNC(slasd8)(int *icompq, int *k, float *d, float *z, float *vf, float *vl, float *difl, float *difr, int *lddifr, float *dsigma, float *work, int *info);
+void BLAS_FUNC(slasda)(int *icompq, int *smlsiz, int *n, int *sqre, float *d, float *e, float *u, int *ldu, float *vt, int *k, float *difl, float *difr, float *z, float *poles, int *givptr, int *givcol, int *ldgcol, int *perm, float *givnum, float *c, float *s, float *work, int *iwork, int *info);
+void BLAS_FUNC(slasdq)(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, float *d, float *e, float *vt, int *ldvt, float *u, int *ldu, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(slasdt)(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub);
+void BLAS_FUNC(slaset)(char *uplo, int *m, int *n, float *alpha, float *beta, float *a, int *lda);
+void BLAS_FUNC(slasq1)(int *n, float *d, float *e, float *work, int *info);
+void BLAS_FUNC(slasq2)(int *n, float *z, int *info);
+void BLAS_FUNC(slasq3)(int *i0, int *n0, float *z, int *pp, float *dmin, float *sigma, float *desig, float *qmax, int *nfail, int *iter, int *ndiv, int *ieee, int *ttype, float *dmin1, float *dmin2, float *dn, float *dn1, float *dn2, float *g, float *tau);
+void BLAS_FUNC(slasq4)(int *i0, int *n0, float *z, int *pp, int *n0in, float *dmin, float *dmin1, float *dmin2, float *dn, float *dn1, float *dn2, float *tau, int *ttype, float *g);
+void BLAS_FUNC(slasq6)(int *i0, int *n0, float *z, int *pp, float *dmin, float *dmin1, float *dmin2, float *dn, float *dnm1, float *dnm2);
+void BLAS_FUNC(slasr)(char *side, char *pivot, char *direct, int *m, int *n, float *c, float *s, float *a, int *lda);
+void BLAS_FUNC(slasrt)(char *id, int *n, float *d, int *info);
+void BLAS_FUNC(slassq)(int *n, float *x, int *incx, float *scale, float *sumsq);
+void BLAS_FUNC(slasv2)(float *f, float *g, float *h, float *ssmin, float *ssmax, float *snr, float *csr, float *snl, float *csl);
+void BLAS_FUNC(slaswp)(int *n, float *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(slasy2)(int *ltranl, int *ltranr, int *isgn, int *n1, int *n2, float *tl, int *ldtl, float *tr, int *ldtr, float *b, int *ldb, float *scale, float *x, int *ldx, float *xnorm, int *info);
+void BLAS_FUNC(slasyf)(char *uplo, int *n, int *nb, int *kb, float *a, int *lda, int *ipiv, float *w, int *ldw, int *info);
+void BLAS_FUNC(slatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, float *ab, int *ldab, float *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(slatdf)(int *ijob, int *n, float *z, int *ldz, float *rhs, float *rdsum, float *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(slatps)(char *uplo, char *trans, char *diag, char *normin, int *n, float *ap, float *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(slatrd)(char *uplo, int *n, int *nb, float *a, int *lda, float *e, float *tau, float *w, int *ldw);
+void BLAS_FUNC(slatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, float *a, int *lda, float *x, float *scale, float *cnorm, int *info);
+void BLAS_FUNC(slatrz)(int *m, int *n, int *l, float *a, int *lda, float *tau, float *work);
+void BLAS_FUNC(slauu2)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(slauum)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(sopgtr)(char *uplo, int *n, float *ap, float *tau, float *q, int *ldq, float *work, int *info);
+void BLAS_FUNC(sopmtr)(char *side, char *uplo, char *trans, int *m, int *n, float *ap, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sorbdb)(char *trans, char *signs, int *m, int *p, int *q, float *x11, int *ldx11, float *x12, int *ldx12, float *x21, int *ldx21, float *x22, int *ldx22, float *theta, float *phi, float *taup1, float *taup2, float *tauq1, float *tauq2, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, float *x11, int *ldx11, float *x12, int *ldx12, float *x21, int *ldx21, float *x22, int *ldx22, float *theta, float *u1, int *ldu1, float *u2, int *ldu2, float *v1t, int *ldv1t, float *v2t, int *ldv2t, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(sorg2l)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorg2r)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorgbr)(char *vect, int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorghr)(int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgl2)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorglq)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgql)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgqr)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgr2)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *info);
+void BLAS_FUNC(sorgrq)(int *m, int *n, int *k, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorgtr)(char *uplo, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorm2l)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sorm2r)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sorml2)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormlq)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormql)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormqr)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormr2)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormr3)(char *side, char *trans, int *m, int *n, int *k, int *l, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *info);
+void BLAS_FUNC(sormrq)(char *side, char *trans, int *m, int *n, int *k, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormrz)(char *side, char *trans, int *m, int *n, int *k, int *l, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(sormtr)(char *side, char *uplo, char *trans, int *m, int *n, float *a, int *lda, float *tau, float *c, int *ldc, float *work, int *lwork, int *info);
+void BLAS_FUNC(spbcon)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(spbequ)(char *uplo, int *n, int *kd, float *ab, int *ldab, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(spbrfs)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spbstf)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info);
+void BLAS_FUNC(spbsv)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info);
+void BLAS_FUNC(spbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *afb, int *ldafb, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spbtf2)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info);
+void BLAS_FUNC(spbtrf)(char *uplo, int *n, int *kd, float *ab, int *ldab, int *info);
+void BLAS_FUNC(spbtrs)(char *uplo, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info);
+void BLAS_FUNC(spftrf)(char *transr, char *uplo, int *n, float *a, int *info);
+void BLAS_FUNC(spftri)(char *transr, char *uplo, int *n, float *a, int *info);
+void BLAS_FUNC(spftrs)(char *transr, char *uplo, int *n, int *nrhs, float *a, float *b, int *ldb, int *info);
+void BLAS_FUNC(spocon)(char *uplo, int *n, float *a, int *lda, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(spoequ)(int *n, float *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(spoequb)(int *n, float *a, int *lda, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(sporfs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sposv)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(sposvx)(char *fact, char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spotf2)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(spotrf)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(spotri)(char *uplo, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(spotrs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(sppcon)(char *uplo, int *n, float *ap, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sppequ)(char *uplo, int *n, float *ap, float *s, float *scond, float *amax, int *info);
+void BLAS_FUNC(spprfs)(char *uplo, int *n, int *nrhs, float *ap, float *afp, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sppsv)(char *uplo, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info);
+void BLAS_FUNC(sppsvx)(char *fact, char *uplo, int *n, int *nrhs, float *ap, float *afp, char *equed, float *s, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(spptrf)(char *uplo, int *n, float *ap, int *info);
+void BLAS_FUNC(spptri)(char *uplo, int *n, float *ap, int *info);
+void BLAS_FUNC(spptrs)(char *uplo, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info);
+void BLAS_FUNC(spstf2)(char *uplo, int *n, float *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(spstrf)(char *uplo, int *n, float *a, int *lda, int *piv, int *rank, float *tol, float *work, int *info);
+void BLAS_FUNC(sptcon)(int *n, float *d, float *e, float *anorm, float *rcond, float *work, int *info);
+void BLAS_FUNC(spteqr)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sptrfs)(int *n, int *nrhs, float *d, float *e, float *df, float *ef, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *info);
+void BLAS_FUNC(sptsv)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb, int *info);
+void BLAS_FUNC(sptsvx)(char *fact, int *n, int *nrhs, float *d, float *e, float *df, float *ef, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *info);
+void BLAS_FUNC(spttrf)(int *n, float *d, float *e, int *info);
+void BLAS_FUNC(spttrs)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb, int *info);
+void BLAS_FUNC(sptts2)(int *n, int *nrhs, float *d, float *e, float *b, int *ldb);
+void BLAS_FUNC(srscl)(int *n, float *sa, float *sx, int *incx);
+void BLAS_FUNC(ssbev)(char *jobz, char *uplo, int *n, int *kd, float *ab, int *ldab, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(ssbevd)(char *jobz, char *uplo, int *n, int *kd, float *ab, int *ldab, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, float *ab, int *ldab, float *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *x, int *ldx, float *work, int *info);
+void BLAS_FUNC(ssbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(ssbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, float *ab, int *ldab, float *bb, int *ldbb, float *q, int *ldq, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssbtrd)(char *vect, char *uplo, int *n, int *kd, float *ab, int *ldab, float *d, float *e, float *q, int *ldq, float *work, int *info);
+void BLAS_FUNC(ssfrk)(char *transr, char *uplo, char *trans, int *n, int *k, float *alpha, float *a, int *lda, float *beta, float *c);
+void BLAS_FUNC(sspcon)(char *uplo, int *n, float *ap, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(sspev)(char *jobz, char *uplo, int *n, float *ap, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sspevd)(char *jobz, char *uplo, int *n, float *ap, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sspevx)(char *jobz, char *range, char *uplo, int *n, float *ap, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(sspgst)(int *itype, char *uplo, int *n, float *ap, float *bp, int *info);
+void BLAS_FUNC(sspgv)(int *itype, char *jobz, char *uplo, int *n, float *ap, float *bp, float *w, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sspgvd)(int *itype, char *jobz, char *uplo, int *n, float *ap, float *bp, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sspgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, float *ap, float *bp, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssprfs)(char *uplo, int *n, int *nrhs, float *ap, float *afp, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(sspsv)(char *uplo, int *n, int *nrhs, float *ap, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sspsvx)(char *fact, char *uplo, int *n, int *nrhs, float *ap, float *afp, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(ssptrd)(char *uplo, int *n, float *ap, float *d, float *e, float *tau, int *info);
+void BLAS_FUNC(ssptrf)(char *uplo, int *n, float *ap, int *ipiv, int *info);
+void BLAS_FUNC(ssptri)(char *uplo, int *n, float *ap, int *ipiv, float *work, int *info);
+void BLAS_FUNC(ssptrs)(char *uplo, int *n, int *nrhs, float *ap, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(sstebz)(char *range, char *order, int *n, float *vl, float *vu, int *il, int *iu, float *abstol, float *d, float *e, int *m, int *nsplit, float *w, int *iblock, int *isplit, float *work, int *iwork, int *info);
+void BLAS_FUNC(sstedc)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstegr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstein)(int *n, float *d, float *e, int *m, float *w, int *iblock, int *isplit, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(sstemr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, int *m, float *w, float *z, int *ldz, int *nzc, int *isuppz, int *tryrac, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssteqr)(char *compz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(ssterf)(int *n, float *d, float *e, int *info);
+void BLAS_FUNC(sstev)(char *jobz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *info);
+void BLAS_FUNC(sstevd)(char *jobz, int *n, float *d, float *e, float *z, int *ldz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstevr)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(sstevx)(char *jobz, char *range, int *n, float *d, float *e, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssycon)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *anorm, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(ssyconv)(char *uplo, char *way, int *n, float *a, int *lda, int *ipiv, float *work, int *info);
+void BLAS_FUNC(ssyequb)(char *uplo, int *n, float *a, int *lda, float *s, float *scond, float *amax, float *work, int *info);
+void BLAS_FUNC(ssyev)(char *jobz, char *uplo, int *n, float *a, int *lda, float *w, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssyevd)(char *jobz, char *uplo, int *n, float *a, int *lda, float *w, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssyevr)(char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, int *isuppz, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssyevx)(char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssygs2)(int *itype, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(ssygst)(int *itype, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(ssygv)(int *itype, char *jobz, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *w, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssygvd)(int *itype, char *jobz, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *w, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ssygvx)(int *itype, char *jobz, char *range, char *uplo, int *n, float *a, int *lda, float *b, int *ldb, float *vl, float *vu, int *il, int *iu, float *abstol, int *m, float *w, float *z, int *ldz, float *work, int *lwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(ssyrfs)(char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(ssysv)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssysvx)(char *fact, char *uplo, int *n, int *nrhs, float *a, int *lda, float *af, int *ldaf, int *ipiv, float *b, int *ldb, float *x, int *ldx, float *rcond, float *ferr, float *berr, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ssyswapr)(char *uplo, int *n, float *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(ssytd2)(char *uplo, int *n, float *a, int *lda, float *d, float *e, float *tau, int *info);
+void BLAS_FUNC(ssytf2)(char *uplo, int *n, float *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(ssytrd)(char *uplo, int *n, float *a, int *lda, float *d, float *e, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssytrf)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssytri)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *info);
+void BLAS_FUNC(ssytri2)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *lwork, int *info);
+void BLAS_FUNC(ssytri2x)(char *uplo, int *n, float *a, int *lda, int *ipiv, float *work, int *nb, int *info);
+void BLAS_FUNC(ssytrs)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, int *info);
+void BLAS_FUNC(ssytrs2)(char *uplo, int *n, int *nrhs, float *a, int *lda, int *ipiv, float *b, int *ldb, float *work, int *info);
+void BLAS_FUNC(stbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, float *ab, int *ldab, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(stbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(stbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, float *ab, int *ldab, float *b, int *ldb, int *info);
+void BLAS_FUNC(stfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, float *alpha, float *a, float *b, int *ldb);
+void BLAS_FUNC(stftri)(char *transr, char *uplo, char *diag, int *n, float *a, int *info);
+void BLAS_FUNC(stfttp)(char *transr, char *uplo, int *n, float *arf, float *ap, int *info);
+void BLAS_FUNC(stfttr)(char *transr, char *uplo, int *n, float *arf, float *a, int *lda, int *info);
+void BLAS_FUNC(stgevc)(char *side, char *howmny, int *select, int *n, float *s, int *lds, float *p, int *ldp, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *info);
+void BLAS_FUNC(stgex2)(int *wantq, int *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *j1, int *n1, int *n2, float *work, int *lwork, int *info);
+void BLAS_FUNC(stgexc)(int *wantq, int *wantz, int *n, float *a, int *lda, float *b, int *ldb, float *q, int *ldq, float *z, int *ldz, int *ifst, int *ilst, float *work, int *lwork, int *info);
+void BLAS_FUNC(stgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, float *a, int *lda, float *b, int *ldb, float *alphar, float *alphai, float *beta, float *q, int *ldq, float *z, int *ldz, int *m, float *pl, float *pr, float *dif, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(stgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, float *a, int *lda, float *b, int *ldb, float *tola, float *tolb, float *alpha, float *beta, float *u, int *ldu, float *v, int *ldv, float *q, int *ldq, float *work, int *ncycle, int *info);
+void BLAS_FUNC(stgsna)(char *job, char *howmny, int *select, int *n, float *a, int *lda, float *b, int *ldb, float *vl, int *ldvl, float *vr, int *ldvr, float *s, float *dif, int *mm, int *m, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(stgsy2)(char *trans, int *ijob, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *d, int *ldd, float *e, int *lde, float *f, int *ldf, float *scale, float *rdsum, float *rdscal, int *iwork, int *pq, int *info);
+void BLAS_FUNC(stgsyl)(char *trans, int *ijob, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *d, int *ldd, float *e, int *lde, float *f, int *ldf, float *scale, float *dif, float *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(stpcon)(char *norm, char *uplo, char *diag, int *n, float *ap, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(stpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, float *v, int *ldv, float *t, int *ldt, float *a, int *lda, float *b, int *ldb, float *work, int *info);
+void BLAS_FUNC(stpqrt)(int *m, int *n, int *l, int *nb, float *a, int *lda, float *b, int *ldb, float *t, int *ldt, float *work, int *info);
+void BLAS_FUNC(stpqrt2)(int *m, int *n, int *l, float *a, int *lda, float *b, int *ldb, float *t, int *ldt, int *info);
+void BLAS_FUNC(stprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, float *v, int *ldv, float *t, int *ldt, float *a, int *lda, float *b, int *ldb, float *work, int *ldwork);
+void BLAS_FUNC(stprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *ap, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(stptri)(char *uplo, char *diag, int *n, float *ap, int *info);
+void BLAS_FUNC(stptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *ap, float *b, int *ldb, int *info);
+void BLAS_FUNC(stpttf)(char *transr, char *uplo, int *n, float *ap, float *arf, int *info);
+void BLAS_FUNC(stpttr)(char *uplo, int *n, float *ap, float *a, int *lda, int *info);
+void BLAS_FUNC(strcon)(char *norm, char *uplo, char *diag, int *n, float *a, int *lda, float *rcond, float *work, int *iwork, int *info);
+void BLAS_FUNC(strevc)(char *side, char *howmny, int *select, int *n, float *t, int *ldt, float *vl, int *ldvl, float *vr, int *ldvr, int *mm, int *m, float *work, int *info);
+void BLAS_FUNC(strexc)(char *compq, int *n, float *t, int *ldt, float *q, int *ldq, int *ifst, int *ilst, float *work, int *info);
+void BLAS_FUNC(strrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, float *x, int *ldx, float *ferr, float *berr, float *work, int *iwork, int *info);
+void BLAS_FUNC(strsen)(char *job, char *compq, int *select, int *n, float *t, int *ldt, float *q, int *ldq, float *wr, float *wi, int *m, float *s, float *sep, float *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(strsna)(char *job, char *howmny, int *select, int *n, float *t, int *ldt, float *vl, int *ldvl, float *vr, int *ldvr, float *s, float *sep, int *mm, int *m, float *work, int *ldwork, int *iwork, int *info);
+void BLAS_FUNC(strsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, float *a, int *lda, float *b, int *ldb, float *c, int *ldc, float *scale, int *info);
+void BLAS_FUNC(strti2)(char *uplo, char *diag, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(strtri)(char *uplo, char *diag, int *n, float *a, int *lda, int *info);
+void BLAS_FUNC(strtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, float *a, int *lda, float *b, int *ldb, int *info);
+void BLAS_FUNC(strttf)(char *transr, char *uplo, int *n, float *a, int *lda, float *arf, int *info);
+void BLAS_FUNC(strttp)(char *uplo, int *n, float *a, int *lda, float *ap, int *info);
+void BLAS_FUNC(stzrzf)(int *m, int *n, float *a, int *lda, float *tau, float *work, int *lwork, int *info);
+void BLAS_FUNC(xerbla_array)(char *srname_array, int *srname_len, int *info);
+void BLAS_FUNC(zbbcsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, double *theta, double *phi, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, double *b11d, double *b11e, double *b12d, double *b12e, double *b21d, double *b21e, double *b22d, double *b22e, double *rwork, int *lrwork, int *info);
+void BLAS_FUNC(zbdsqr)(char *uplo, int *n, int *ncvt, int *nru, int *ncc, double *d, double *e, npy_complex128 *vt, int *ldvt, npy_complex128 *u, int *ldu, npy_complex128 *c, int *ldc, double *rwork, int *info);
+void BLAS_FUNC(zcgesv)(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, double *rwork, int *iter, int *info);
+void BLAS_FUNC(zcposv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, double *rwork, int *iter, int *info);
+void BLAS_FUNC(zdrscl)(int *n, double *sa, npy_complex128 *sx, int *incx);
+void BLAS_FUNC(zgbbrd)(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *pt, int *ldpt, npy_complex128 *c, int *ldc, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbcon)(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbequ)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgbequb)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgbrfs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbsv)(int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgbsvx)(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, char *equed, double *r, double *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgbtf2)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(zgbtrf)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info);
+void BLAS_FUNC(zgbtrs)(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgebak)(char *job, char *side, int *n, int *ilo, int *ihi, double *scale, int *m, npy_complex128 *v, int *ldv, int *info);
+void BLAS_FUNC(zgebal)(char *job, int *n, npy_complex128 *a, int *lda, int *ilo, int *ihi, double *scale, int *info);
+void BLAS_FUNC(zgebd2)(int *m, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgebrd)(int *m, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgecon)(char *norm, int *n, npy_complex128 *a, int *lda, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgeequ)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgeequb)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, int *info);
+void BLAS_FUNC(zgees)(char *jobvs, char *sort, _zselect1 *select, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info);
+void BLAS_FUNC(zgeesx)(char *jobvs, char *sort, _zselect1 *select, char *sense, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info);
+void BLAS_FUNC(zgeev)(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgeevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, double *scale, double *abnrm, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgehd2)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgehrd)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgelq2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgelqf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgels)(char *trans, int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgelsd)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *s, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zgelss)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *s, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgelsy)(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *jpvt, double *rcond, int *rank, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgemqrt)(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeql2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqlf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgeqp3)(int *m, int *n, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgeqr2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqr2p)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqrf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgeqrfp)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgeqrt)(int *m, int *n, int *nb, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgeqrt2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info);
+void BLAS_FUNC(zgeqrt3)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info);
+void BLAS_FUNC(zgerfs)(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgerq2)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgerqf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgesc2)(int *n, npy_complex128 *a, int *lda, npy_complex128 *rhs, int *ipiv, int *jpiv, double *scale);
+void BLAS_FUNC(zgesdd)(char *jobz, int *m, int *n, npy_complex128 *a, int *lda, double *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zgesv)(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgesvd)(char *jobu, char *jobvt, int *m, int *n, npy_complex128 *a, int *lda, double *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zgesvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, char *equed, double *r, double *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgetc2)(int *n, npy_complex128 *a, int *lda, int *ipiv, int *jpiv, int *info);
+void BLAS_FUNC(zgetf2)(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zgetrf)(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zgetri)(int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgetrs)(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zggbak)(char *job, char *side, int *n, int *ilo, int *ihi, double *lscale, double *rscale, int *m, npy_complex128 *v, int *ldv, int *info);
+void BLAS_FUNC(zggbal)(char *job, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *ilo, int *ihi, double *lscale, double *rscale, double *work, int *info);
+void BLAS_FUNC(zgges)(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, npy_complex128 *work, int *lwork, double *rwork, int *bwork, int *info);
+void BLAS_FUNC(zggesx)(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *liwork, int *bwork, int *info);
+void BLAS_FUNC(zggev)(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zggevx)(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, double *lscale, double *rscale, double *abnrm, double *bbnrm, double *rconde, double *rcondv, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *bwork, int *info);
+void BLAS_FUNC(zggglm)(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *d, npy_complex128 *x, npy_complex128 *y, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgghrd)(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *info);
+void BLAS_FUNC(zgglse)(int *m, int *n, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, npy_complex128 *d, npy_complex128 *x, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zggqrf)(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zggrqf)(int *m, int *p, int *n, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zgtcon)(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zgtrfs)(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgtsv)(int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgtsvx)(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zgttrf)(int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, int *info);
+void BLAS_FUNC(zgttrs)(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zgtts2)(int *itrans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zhbev)(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhbevd)(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhbevx)(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhbgst)(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *x, int *ldx, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhbgv)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhbgvd)(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhbgvx)(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *q, int *ldq, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhbtrd)(char *vect, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhecon)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zheequb)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, npy_complex128 *work, int *info);
+void BLAS_FUNC(zheev)(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, double *w, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zheevd)(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, double *w, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zheevr)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, int *isuppz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zheevx)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhegs2)(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhegst)(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhegv)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *w, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zhegvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *w, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhegvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zherfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhesv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhesvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zheswapr)(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(zhetd2)(char *uplo, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tau, int *info);
+void BLAS_FUNC(zhetf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zhetrd)(char *uplo, int *n, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhetrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhetri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhetri2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zhetri2x)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info);
+void BLAS_FUNC(zhetrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhetrs2)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhfrk)(char *transr, char *uplo, char *trans, int *n, int *k, double *alpha, npy_complex128 *a, int *lda, double *beta, npy_complex128 *c);
+void BLAS_FUNC(zhgeqz)(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *t, int *ldt, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zhpcon)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhpev)(char *jobz, char *uplo, int *n, npy_complex128 *ap, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhpevd)(char *jobz, char *uplo, int *n, npy_complex128 *ap, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhpevx)(char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhpgst)(int *itype, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, int *info);
+void BLAS_FUNC(zhpgv)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhpgvd)(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zhpgvx)(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, npy_complex128 *work, double *rwork, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zhprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhpsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhpsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zhptrd)(char *uplo, int *n, npy_complex128 *ap, double *d, double *e, npy_complex128 *tau, int *info);
+void BLAS_FUNC(zhptrf)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info);
+void BLAS_FUNC(zhptri)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zhptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zhsein)(char *side, char *eigsrc, char *initv, int *select, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *ifaill, int *ifailr, int *info);
+void BLAS_FUNC(zhseqr)(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zlabrd)(int *m, int *n, int *nb, npy_complex128 *a, int *lda, double *d, double *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *x, int *ldx, npy_complex128 *y, int *ldy);
+void BLAS_FUNC(zlacgv)(int *n, npy_complex128 *x, int *incx);
+void BLAS_FUNC(zlacn2)(int *n, npy_complex128 *v, npy_complex128 *x, double *est, int *kase, int *isave);
+void BLAS_FUNC(zlacon)(int *n, npy_complex128 *v, npy_complex128 *x, double *est, int *kase);
+void BLAS_FUNC(zlacp2)(char *uplo, int *m, int *n, double *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zlacpy)(char *uplo, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zlacrm)(int *m, int *n, npy_complex128 *a, int *lda, double *b, int *ldb, npy_complex128 *c, int *ldc, double *rwork);
+void BLAS_FUNC(zlacrt)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, npy_complex128 *c, npy_complex128 *s);
+void F_FUNC(zladivwrp,ZLADIVWRP)(npy_complex128 *out, npy_complex128 *x, npy_complex128 *y);
+void BLAS_FUNC(zlaed0)(int *qsiz, int *n, double *d, double *e, npy_complex128 *q, int *ldq, npy_complex128 *qstore, int *ldqs, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zlaed7)(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, double *d, npy_complex128 *q, int *ldq, double *rho, int *indxq, double *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, double *givnum, npy_complex128 *work, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zlaed8)(int *k, int *n, int *qsiz, npy_complex128 *q, int *ldq, double *d, double *rho, int *cutpnt, double *z, double *dlamda, npy_complex128 *q2, int *ldq2, double *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, double *givnum, int *info);
+void BLAS_FUNC(zlaein)(int *rightv, int *noinit, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *v, npy_complex128 *b, int *ldb, double *rwork, double *eps3, double *smlnum, int *info);
+void BLAS_FUNC(zlaesy)(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, npy_complex128 *rt1, npy_complex128 *rt2, npy_complex128 *evscal, npy_complex128 *cs1, npy_complex128 *sn1);
+void BLAS_FUNC(zlaev2)(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, double *rt1, double *rt2, double *cs1, npy_complex128 *sn1);
+void BLAS_FUNC(zlag2c)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info);
+void BLAS_FUNC(zlags2)(int *upper, double *a1, npy_complex128 *a2, double *a3, double *b1, npy_complex128 *b2, double *b3, double *csu, npy_complex128 *snu, double *csv, npy_complex128 *snv, double *csq, npy_complex128 *snq);
+void BLAS_FUNC(zlagtm)(char *trans, int *n, int *nrhs, double *alpha, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *x, int *ldx, double *beta, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zlahef)(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info);
+void BLAS_FUNC(zlahqr)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *info);
+void BLAS_FUNC(zlahr2)(int *n, int *k, int *nb, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *t, int *ldt, npy_complex128 *y, int *ldy);
+void BLAS_FUNC(zlaic1)(int *job, int *j, npy_complex128 *x, double *sest, npy_complex128 *w, npy_complex128 *gamma, double *sestpr, npy_complex128 *s, npy_complex128 *c);
+void BLAS_FUNC(zlals0)(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, double *givnum, int *ldgnum, double *poles, double *difl, double *difr, double *z, int *k, double *c, double *s, double *rwork, int *info);
+void BLAS_FUNC(zlalsa)(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, double *u, int *ldu, double *vt, int *k, double *difl, double *difr, double *z, double *poles, int *givptr, int *givcol, int *ldgcol, int *perm, double *givnum, double *c, double *s, double *rwork, int *iwork, int *info);
+void BLAS_FUNC(zlalsd)(char *uplo, int *smlsiz, int *n, int *nrhs, double *d, double *e, npy_complex128 *b, int *ldb, double *rcond, int *rank, npy_complex128 *work, double *rwork, int *iwork, int *info);
+double BLAS_FUNC(zlangb)(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlange)(char *norm, int *m, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlangt)(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d_, npy_complex128 *du);
+double BLAS_FUNC(zlanhb)(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlanhe)(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlanhf)(char *norm, char *transr, char *uplo, int *n, npy_complex128 *a, double *work);
+double BLAS_FUNC(zlanhp)(char *norm, char *uplo, int *n, npy_complex128 *ap, double *work);
+double BLAS_FUNC(zlanhs)(char *norm, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlanht)(char *norm, int *n, double *d_, npy_complex128 *e);
+double BLAS_FUNC(zlansb)(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlansp)(char *norm, char *uplo, int *n, npy_complex128 *ap, double *work);
+double BLAS_FUNC(zlansy)(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, double *work);
+double BLAS_FUNC(zlantb)(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex128 *ab, int *ldab, double *work);
+double BLAS_FUNC(zlantp)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, double *work);
+double BLAS_FUNC(zlantr)(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex128 *a, int *lda, double *work);
+void BLAS_FUNC(zlapll)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *ssmin);
+void BLAS_FUNC(zlapmr)(int *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k);
+void BLAS_FUNC(zlapmt)(int *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k);
+void BLAS_FUNC(zlaqgb)(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(zlaqge)(int *m, int *n, npy_complex128 *a, int *lda, double *r, double *c, double *rowcnd, double *colcnd, double *amax, char *equed);
+void BLAS_FUNC(zlaqhb)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqhe)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqhp)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqp2)(int *m, int *n, int *offset, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, double *vn1, double *vn2, npy_complex128 *work);
+void BLAS_FUNC(zlaqps)(int *m, int *n, int *offset, int *nb, int *kb, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, double *vn1, double *vn2, npy_complex128 *auxv, npy_complex128 *f, int *ldf);
+void BLAS_FUNC(zlaqr0)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zlaqr1)(int *n, npy_complex128 *h, int *ldh, npy_complex128 *s1, npy_complex128 *s2, npy_complex128 *v);
+void BLAS_FUNC(zlaqr2)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork);
+void BLAS_FUNC(zlaqr3)(int *wantt, int *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork);
+void BLAS_FUNC(zlaqr4)(int *wantt, int *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zlaqr5)(int *wantt, int *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex128 *s, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *v, int *ldv, npy_complex128 *u, int *ldu, int *nv, npy_complex128 *wv, int *ldwv, int *nh, npy_complex128 *wh, int *ldwh);
+void BLAS_FUNC(zlaqsb)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqsp)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlaqsy)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, char *equed);
+void BLAS_FUNC(zlar1v)(int *n, int *b1, int *bn, double *lambda_, double *d, double *l, double *ld, double *lld, double *pivmin, double *gaptol, npy_complex128 *z, int *wantnc, int *negcnt, double *ztz, double *mingma, int *r, int *isuppz, double *nrminv, double *resid, double *rqcorr, double *work);
+void BLAS_FUNC(zlar2v)(int *n, npy_complex128 *x, npy_complex128 *y, npy_complex128 *z, int *incx, double *c, npy_complex128 *s, int *incc);
+void BLAS_FUNC(zlarcm)(int *m, int *n, double *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, double *rwork);
+void BLAS_FUNC(zlarf)(char *side, int *m, int *n, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work);
+void BLAS_FUNC(zlarfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork);
+void BLAS_FUNC(zlarfg)(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau);
+void BLAS_FUNC(zlarfgp)(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau);
+void BLAS_FUNC(zlarft)(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt);
+void BLAS_FUNC(zlarfx)(char *side, int *m, int *n, npy_complex128 *v, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work);
+void BLAS_FUNC(zlargv)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *c, int *incc);
+void BLAS_FUNC(zlarnv)(int *idist, int *iseed, int *n, npy_complex128 *x);
+void BLAS_FUNC(zlarrv)(int *n, double *vl, double *vu, double *d, double *l, double *pivmin, int *isplit, int *m, int *dol, int *dou, double *minrgp, double *rtol1, double *rtol2, double *w, double *werr, double *wgap, int *iblock, int *indexw, double *gers, npy_complex128 *z, int *ldz, int *isuppz, double *work, int *iwork, int *info);
+void BLAS_FUNC(zlartg)(npy_complex128 *f, npy_complex128 *g, double *cs, npy_complex128 *sn, npy_complex128 *r);
+void BLAS_FUNC(zlartv)(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, double *c, npy_complex128 *s, int *incc);
+void BLAS_FUNC(zlarz)(char *side, int *m, int *n, int *l, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work);
+void BLAS_FUNC(zlarzb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork);
+void BLAS_FUNC(zlarzt)(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt);
+void BLAS_FUNC(zlascl)(char *type_bn, int *kl, int *ku, double *cfrom, double *cto, int *m, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zlaset)(char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zlasr)(char *side, char *pivot, char *direct, int *m, int *n, double *c, double *s, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zlassq)(int *n, npy_complex128 *x, int *incx, double *scale, double *sumsq);
+void BLAS_FUNC(zlaswp)(int *n, npy_complex128 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx);
+void BLAS_FUNC(zlasyf)(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info);
+void BLAS_FUNC(zlat2c)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info);
+void BLAS_FUNC(zlatbs)(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(zlatdf)(int *ijob, int *n, npy_complex128 *z, int *ldz, npy_complex128 *rhs, double *rdsum, double *rdscal, int *ipiv, int *jpiv);
+void BLAS_FUNC(zlatps)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *ap, npy_complex128 *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(zlatrd)(char *uplo, int *n, int *nb, npy_complex128 *a, int *lda, double *e, npy_complex128 *tau, npy_complex128 *w, int *ldw);
+void BLAS_FUNC(zlatrs)(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, double *scale, double *cnorm, int *info);
+void BLAS_FUNC(zlatrz)(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work);
+void BLAS_FUNC(zlauu2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zlauum)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpbcon)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpbequ)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zpbrfs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpbstf)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info);
+void BLAS_FUNC(zpbsv)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpbsvx)(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpbtf2)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info);
+void BLAS_FUNC(zpbtrf)(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info);
+void BLAS_FUNC(zpbtrs)(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpftrf)(char *transr, char *uplo, int *n, npy_complex128 *a, int *info);
+void BLAS_FUNC(zpftri)(char *transr, char *uplo, int *n, npy_complex128 *a, int *info);
+void BLAS_FUNC(zpftrs)(char *transr, char *uplo, int *n, int *nrhs, npy_complex128 *a, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpocon)(char *uplo, int *n, npy_complex128 *a, int *lda, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpoequ)(int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zpoequb)(int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zporfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zposv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zposvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpotf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpotrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpotri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(zpotrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zppcon)(char *uplo, int *n, npy_complex128 *ap, double *anorm, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zppequ)(char *uplo, int *n, npy_complex128 *ap, double *s, double *scond, double *amax, int *info);
+void BLAS_FUNC(zpprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zppsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zppsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, char *equed, double *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpptrf)(char *uplo, int *n, npy_complex128 *ap, int *info);
+void BLAS_FUNC(zpptri)(char *uplo, int *n, npy_complex128 *ap, int *info);
+void BLAS_FUNC(zpptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zpstf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(zpstrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, double *tol, double *work, int *info);
+void BLAS_FUNC(zptcon)(int *n, double *d, npy_complex128 *e, double *anorm, double *rcond, double *rwork, int *info);
+void BLAS_FUNC(zpteqr)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(zptrfs)(char *uplo, int *n, int *nrhs, double *d, npy_complex128 *e, double *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zptsv)(int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zptsvx)(char *fact, int *n, int *nrhs, double *d, npy_complex128 *e, double *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zpttrf)(int *n, double *d, npy_complex128 *e, int *info);
+void BLAS_FUNC(zpttrs)(char *uplo, int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zptts2)(int *iuplo, int *n, int *nrhs, double *d, npy_complex128 *e, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(zrot)(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, double *c, npy_complex128 *s);
+void BLAS_FUNC(zspcon)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zspmv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zspr)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap);
+void BLAS_FUNC(zsprfs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zspsv)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zspsvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zsptrf)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info);
+void BLAS_FUNC(zsptri)(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsptrs)(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zstedc)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zstegr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, double *abstol, int *m, double *w, npy_complex128 *z, int *ldz, int *isuppz, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zstein)(int *n, double *d, double *e, int *m, double *w, int *iblock, int *isplit, npy_complex128 *z, int *ldz, double *work, int *iwork, int *ifail, int *info);
+void BLAS_FUNC(zstemr)(char *jobz, char *range, int *n, double *d, double *e, double *vl, double *vu, int *il, int *iu, int *m, double *w, npy_complex128 *z, int *ldz, int *nzc, int *isuppz, int *tryrac, double *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(zsteqr)(char *compz, int *n, double *d, double *e, npy_complex128 *z, int *ldz, double *work, int *info);
+void BLAS_FUNC(zsycon)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, double *anorm, double *rcond, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsyconv)(char *uplo, char *way, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsyequb)(char *uplo, int *n, npy_complex128 *a, int *lda, double *s, double *scond, double *amax, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsymv)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy);
+void BLAS_FUNC(zsyr)(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda);
+void BLAS_FUNC(zsyrfs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(zsysv)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zsysvx)(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *rcond, double *ferr, double *berr, npy_complex128 *work, int *lwork, double *rwork, int *info);
+void BLAS_FUNC(zsyswapr)(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2);
+void BLAS_FUNC(zsytf2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info);
+void BLAS_FUNC(zsytrf)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zsytri)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info);
+void BLAS_FUNC(zsytri2)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zsytri2x)(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info);
+void BLAS_FUNC(zsytrs)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(zsytrs2)(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info);
+void BLAS_FUNC(ztbcon)(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex128 *ab, int *ldab, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztbrfs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztbtrs)(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(ztfsm)(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, npy_complex128 *b, int *ldb);
+void BLAS_FUNC(ztftri)(char *transr, char *uplo, char *diag, int *n, npy_complex128 *a, int *info);
+void BLAS_FUNC(ztfttp)(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *ap, int *info);
+void BLAS_FUNC(ztfttr)(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztgevc)(char *side, char *howmny, int *select, int *n, npy_complex128 *s, int *lds, npy_complex128 *p, int *ldp, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztgex2)(int *wantq, int *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *j1, int *info);
+void BLAS_FUNC(ztgexc)(int *wantq, int *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ztgsen)(int *ijob, int *wantq, int *wantz, int *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *m, double *pl, double *pr, double *dif, npy_complex128 *work, int *lwork, int *iwork, int *liwork, int *info);
+void BLAS_FUNC(ztgsja)(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, double *tola, double *tolb, double *alpha, double *beta, npy_complex128 *u, int *ldu, npy_complex128 *v, int *ldv, npy_complex128 *q, int *ldq, npy_complex128 *work, int *ncycle, int *info);
+void BLAS_FUNC(ztgsna)(char *job, char *howmny, int *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, double *s, double *dif, int *mm, int *m, npy_complex128 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ztgsy2)(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, double *scale, double *rdsum, double *rdscal, int *info);
+void BLAS_FUNC(ztgsyl)(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, double *scale, double *dif, npy_complex128 *work, int *lwork, int *iwork, int *info);
+void BLAS_FUNC(ztpcon)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztpmqrt)(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info);
+void BLAS_FUNC(ztpqrt)(int *m, int *n, int *l, int *nb, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info);
+void BLAS_FUNC(ztpqrt2)(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, int *info);
+void BLAS_FUNC(ztprfb)(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *ldwork);
+void BLAS_FUNC(ztprfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztptri)(char *uplo, char *diag, int *n, npy_complex128 *ap, int *info);
+void BLAS_FUNC(ztptrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(ztpttf)(char *transr, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *arf, int *info);
+void BLAS_FUNC(ztpttr)(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztrcon)(char *norm, char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, double *rcond, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztrevc)(char *side, char *howmny, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztrexc)(char *compq, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, int *ifst, int *ilst, int *info);
+void BLAS_FUNC(ztrrfs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, double *ferr, double *berr, npy_complex128 *work, double *rwork, int *info);
+void BLAS_FUNC(ztrsen)(char *job, char *compq, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, npy_complex128 *w, int *m, double *s, double *sep, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(ztrsna)(char *job, char *howmny, int *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, double *s, double *sep, int *mm, int *m, npy_complex128 *work, int *ldwork, double *rwork, int *info);
+void BLAS_FUNC(ztrsyl)(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, double *scale, int *info);
+void BLAS_FUNC(ztrti2)(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztrtri)(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info);
+void BLAS_FUNC(ztrtrs)(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info);
+void BLAS_FUNC(ztrttf)(char *transr, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *arf, int *info);
+void BLAS_FUNC(ztrttp)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *ap, int *info);
+void BLAS_FUNC(ztzrzf)(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunbdb)(char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, double *theta, double *phi, npy_complex128 *taup1, npy_complex128 *taup2, npy_complex128 *tauq1, npy_complex128 *tauq2, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zuncsd)(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, double *theta, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, npy_complex128 *work, int *lwork, double *rwork, int *lrwork, int *iwork, int *info);
+void BLAS_FUNC(zung2l)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zung2r)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zungbr)(char *vect, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunghr)(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungl2)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunglq)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungql)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungqr)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungr2)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info);
+void BLAS_FUNC(zungrq)(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zungtr)(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunm2l)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunm2r)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmbr)(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmhr)(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunml2)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmlq)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmql)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmqr)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmr2)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmr3)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+void BLAS_FUNC(zunmrq)(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmrz)(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zunmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info);
+void BLAS_FUNC(zupgtr)(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info);
+void BLAS_FUNC(zupmtr)(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a0ba92af71f3f3188cc73ca441187db9701b052
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs.py
@@ -0,0 +1,867 @@
+#
+# Author: Travis Oliphant, March 2002
+#
+import warnings
+from itertools import product
+
+import numpy as np
+from numpy import (dot, diag, prod, logical_not, ravel, transpose,
+                   conjugate, absolute, amax, sign, isfinite, triu)
+
+# Local imports
+from scipy.linalg import LinAlgError, bandwidth
+from ._misc import norm
+from ._basic import solve, inv
+from ._decomp_svd import svd
+from ._decomp_schur import schur, rsf2csf
+from ._expm_frechet import expm_frechet, expm_cond
+from ._matfuncs_sqrtm import sqrtm
+from ._matfuncs_expm import pick_pade_structure, pade_UV_calc
+from ._linalg_pythran import _funm_loops  # type: ignore[import-not-found]
+
+__all__ = ['expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm', 'tanhm', 'logm',
+           'funm', 'signm', 'sqrtm', 'fractional_matrix_power', 'expm_frechet',
+           'expm_cond', 'khatri_rao']
+
+eps = np.finfo('d').eps
+feps = np.finfo('f').eps
+
+_array_precision = {'i': 1, 'l': 1, 'f': 0, 'd': 1, 'F': 0, 'D': 1}
+
+
+###############################################################################
+# Utility functions.
+
+
+def _asarray_square(A):
+    """
+    Wraps asarray with the extra requirement that the input be a square matrix.
+
+    The motivation is that the matfuncs module has real functions that have
+    been lifted to square matrix functions.
+
+    Parameters
+    ----------
+    A : array_like
+        A square matrix.
+
+    Returns
+    -------
+    out : ndarray
+        An ndarray copy or view or other representation of A.
+
+    """
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected square array_like input')
+    return A
+
+
+def _maybe_real(A, B, tol=None):
+    """
+    Return either B or the real part of B, depending on properties of A and B.
+
+    The motivation is that B has been computed as a complicated function of A,
+    and B may be perturbed by negligible imaginary components.
+    If A is real and B is complex with small imaginary components,
+    then return a real copy of B.  The assumption in that case would be that
+    the imaginary components of B are numerical artifacts.
+
+    Parameters
+    ----------
+    A : ndarray
+        Input array whose type is to be checked as real vs. complex.
+    B : ndarray
+        Array to be returned, possibly without its imaginary part.
+    tol : float
+        Absolute tolerance.
+
+    Returns
+    -------
+    out : real or complex array
+        Either the input array B or only the real part of the input array B.
+
+    """
+    # Note that booleans and integers compare as real.
+    if np.isrealobj(A) and np.iscomplexobj(B):
+        if tol is None:
+            tol = {0: feps*1e3, 1: eps*1e6}[_array_precision[B.dtype.char]]
+        if np.allclose(B.imag, 0.0, atol=tol):
+            B = B.real
+    return B
+
+
+###############################################################################
+# Matrix functions.
+
+
+def fractional_matrix_power(A, t):
+    """
+    Compute the fractional power of a matrix.
+
+    Proceeds according to the discussion in section (6) of [1]_.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose fractional power to evaluate.
+    t : float
+        Fractional power.
+
+    Returns
+    -------
+    X : (N, N) array_like
+        The fractional power of the matrix.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import fractional_matrix_power
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> b = fractional_matrix_power(a, 0.5)
+    >>> b
+    array([[ 0.75592895,  1.13389342],
+           [ 0.37796447,  1.88982237]])
+    >>> np.dot(b, b)      # Verify square root
+    array([[ 1.,  3.],
+           [ 1.,  4.]])
+
+    """
+    # This fixes some issue with imports;
+    # this function calls onenormest which is in scipy.sparse.
+    A = _asarray_square(A)
+    import scipy.linalg._matfuncs_inv_ssq
+    return scipy.linalg._matfuncs_inv_ssq._fractional_matrix_power(A, t)
+
+
+def logm(A, disp=True):
+    """
+    Compute matrix logarithm.
+
+    The matrix logarithm is the inverse of
+    expm: expm(logm(`A`)) == `A`
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose logarithm to evaluate
+    disp : bool, optional
+        Emit warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+
+    Returns
+    -------
+    logm : (N, N) ndarray
+        Matrix logarithm of `A`
+    errest : float
+        (if disp == False)
+
+        1-norm of the estimated error, ||err||_1 / ||A||_1
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
+           "Improved Inverse Scaling and Squaring Algorithms
+           for the Matrix Logarithm."
+           SIAM Journal on Scientific Computing, 34 (4). C152-C169.
+           ISSN 1095-7197
+
+    .. [2] Nicholas J. Higham (2008)
+           "Functions of Matrices: Theory and Computation"
+           ISBN 978-0-898716-46-7
+
+    .. [3] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import logm, expm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> b = logm(a)
+    >>> b
+    array([[-1.02571087,  2.05142174],
+           [ 0.68380725,  1.02571087]])
+    >>> expm(b)         # Verify expm(logm(a)) returns a
+    array([[ 1.,  3.],
+           [ 1.,  4.]])
+
+    """
+    A = np.asarray(A)  # squareness checked in `_logm`
+    # Avoid circular import ... this is OK, right?
+    import scipy.linalg._matfuncs_inv_ssq
+    F = scipy.linalg._matfuncs_inv_ssq._logm(A)
+    F = _maybe_real(A, F)
+    errtol = 1000*eps
+    # TODO use a better error approximation
+    with np.errstate(divide='ignore', invalid='ignore'):
+        errest = norm(expm(F)-A, 1) / np.asarray(norm(A, 1), dtype=A.dtype).real[()]
+    if disp:
+        if not isfinite(errest) or errest >= errtol:
+            message = f"logm result may be inaccurate, approximate err = {errest}"
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+        return F
+    else:
+        return F, errest
+
+
+def expm(A):
+    """Compute the matrix exponential of an array.
+
+    Parameters
+    ----------
+    A : ndarray
+        Input with last two dimensions are square ``(..., n, n)``.
+
+    Returns
+    -------
+    eA : ndarray
+        The resulting matrix exponential with the same shape of ``A``
+
+    Notes
+    -----
+    Implements the algorithm given in [1], which is essentially a Pade
+    approximation with a variable order that is decided based on the array
+    data.
+
+    For input with size ``n``, the memory usage is in the worst case in the
+    order of ``8*(n**2)``. If the input data is not of single and double
+    precision of real and complex dtypes, it is copied to a new array.
+
+    For cases ``n >= 400``, the exact 1-norm computation cost, breaks even with
+    1-norm estimation and from that point on the estimation scheme given in
+    [2] is used to decide on the approximation order.
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham, (2009), "A New Scaling
+           and Squaring Algorithm for the Matrix Exponential", SIAM J. Matrix
+           Anal. Appl. 31(3):970-989, :doi:`10.1137/09074721X`
+
+    .. [2] Nicholas J. Higham and Francoise Tisseur (2000), "A Block Algorithm
+           for Matrix 1-Norm Estimation, with an Application to 1-Norm
+           Pseudospectra." SIAM J. Matrix Anal. Appl. 21(4):1185-1201,
+           :doi:`10.1137/S0895479899356080`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm, sinm, cosm
+
+    Matrix version of the formula exp(0) = 1:
+
+    >>> expm(np.zeros((3, 2, 2)))
+    array([[[1., 0.],
+            [0., 1.]],
+    
+           [[1., 0.],
+            [0., 1.]],
+    
+           [[1., 0.],
+            [0., 1.]]])
+
+    Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
+    applied to a matrix:
+
+    >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
+    >>> expm(1j*a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+    >>> cosm(a) + 1j*sinm(a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+
+    """
+    a = np.asarray(A)
+    if a.size == 1 and a.ndim < 2:
+        return np.array([[np.exp(a.item())]])
+
+    if a.ndim < 2:
+        raise LinAlgError('The input array must be at least two-dimensional')
+    if a.shape[-1] != a.shape[-2]:
+        raise LinAlgError('Last 2 dimensions of the array must be square')
+
+    # Empty array
+    if min(*a.shape) == 0:
+        dtype = expm(np.eye(2, dtype=a.dtype)).dtype
+        return np.empty_like(a, dtype=dtype)
+
+    # Scalar case
+    if a.shape[-2:] == (1, 1):
+        return np.exp(a)
+
+    if not np.issubdtype(a.dtype, np.inexact):
+        a = a.astype(np.float64)
+    elif a.dtype == np.float16:
+        a = a.astype(np.float32)
+
+    # An explicit formula for 2x2 case exists (formula (2.2) in [1]). However, without
+    # Kahan's method, numerical instabilities can occur (See gh-19584). Hence removed
+    # here until we have a more stable implementation.
+
+    n = a.shape[-1]
+    eA = np.empty(a.shape, dtype=a.dtype)
+    # working memory to hold intermediate arrays
+    Am = np.empty((5, n, n), dtype=a.dtype)
+
+    # Main loop to go through the slices of an ndarray and passing to expm
+    for ind in product(*[range(x) for x in a.shape[:-2]]):
+        aw = a[ind]
+
+        lu = bandwidth(aw)
+        if not any(lu):  # a is diagonal?
+            eA[ind] = np.diag(np.exp(np.diag(aw)))
+            continue
+
+        # Generic/triangular case; copy the slice into scratch and send.
+        # Am will be mutated by pick_pade_structure
+        # If s != 0, scaled Am will be returned from pick_pade_structure.
+        Am[0, :, :] = aw
+        m, s = pick_pade_structure(Am)
+        if (m < 0):
+            raise MemoryError("scipy.linalg.expm could not allocate sufficient"
+                              " memory while trying to compute the Pade "
+                              f"structure (error code {m}).")
+        info = pade_UV_calc(Am, m)
+        if info != 0:
+            if info <= -11:
+                # We raise it from failed mallocs; negative LAPACK codes > -7
+                raise MemoryError("scipy.linalg.expm could not allocate "
+                              "sufficient memory while trying to compute the "
+                              f"exponential (error code {info}).")
+            else:
+                # LAPACK wrong argument error or exact singularity.
+                # Neither should happen.
+                raise RuntimeError("scipy.linalg.expm got an internal LAPACK "
+                                   "error during the exponential computation "
+                                   f"(error code {info})")
+        eAw = Am[0]
+
+        if s != 0:  # squaring needed
+
+            if (lu[1] == 0) or (lu[0] == 0):  # lower/upper triangular
+                # This branch implements Code Fragment 2.1 of [1]
+
+                diag_aw = np.diag(aw)
+                # einsum returns a writable view
+                np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2**(-s))
+                # super/sub diagonal
+                sd = np.diag(aw, k=-1 if lu[1] == 0 else 1)
+
+                for i in range(s-1, -1, -1):
+                    eAw = eAw @ eAw
+
+                    # diagonal
+                    np.einsum('ii->i', eAw)[:] = np.exp(diag_aw * 2.**(-i))
+                    exp_sd = _exp_sinch(diag_aw * (2.**(-i))) * (sd * 2**(-i))
+                    if lu[1] == 0:  # lower
+                        np.einsum('ii->i', eAw[1:, :-1])[:] = exp_sd
+                    else:  # upper
+                        np.einsum('ii->i', eAw[:-1, 1:])[:] = exp_sd
+
+            else:  # generic
+                for _ in range(s):
+                    eAw = eAw @ eAw
+
+        # Zero out the entries from np.empty in case of triangular input
+        if (lu[0] == 0) or (lu[1] == 0):
+            eA[ind] = np.triu(eAw) if lu[0] == 0 else np.tril(eAw)
+        else:
+            eA[ind] = eAw
+
+    return eA
+
+
+def _exp_sinch(x):
+    # Higham's formula (10.42), might overflow, see GH-11839
+    lexp_diff = np.diff(np.exp(x))
+    l_diff = np.diff(x)
+    mask_z = l_diff == 0.
+    lexp_diff[~mask_z] /= l_diff[~mask_z]
+    lexp_diff[mask_z] = np.exp(x[:-1][mask_z])
+    return lexp_diff
+
+
+def cosm(A):
+    """
+    Compute the matrix cosine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array
+
+    Returns
+    -------
+    cosm : (N, N) ndarray
+        Matrix cosine of A
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm, sinm, cosm
+
+    Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
+    applied to a matrix:
+
+    >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
+    >>> expm(1j*a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+    >>> cosm(a) + 1j*sinm(a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+
+    """
+    A = _asarray_square(A)
+    if np.iscomplexobj(A):
+        return 0.5*(expm(1j*A) + expm(-1j*A))
+    else:
+        return expm(1j*A).real
+
+
+def sinm(A):
+    """
+    Compute the matrix sine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    sinm : (N, N) ndarray
+        Matrix sine of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import expm, sinm, cosm
+
+    Euler's identity (exp(i*theta) = cos(theta) + i*sin(theta))
+    applied to a matrix:
+
+    >>> a = np.array([[1.0, 2.0], [-1.0, 3.0]])
+    >>> expm(1j*a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+    >>> cosm(a) + 1j*sinm(a)
+    array([[ 0.42645930+1.89217551j, -2.13721484-0.97811252j],
+           [ 1.06860742+0.48905626j, -1.71075555+0.91406299j]])
+
+    """
+    A = _asarray_square(A)
+    if np.iscomplexobj(A):
+        return -0.5j*(expm(1j*A) - expm(-1j*A))
+    else:
+        return expm(1j*A).imag
+
+
+def tanm(A):
+    """
+    Compute the matrix tangent.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    tanm : (N, N) ndarray
+        Matrix tangent of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanm, sinm, cosm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> t = tanm(a)
+    >>> t
+    array([[ -2.00876993,  -8.41880636],
+           [ -2.80626879, -10.42757629]])
+
+    Verify tanm(a) = sinm(a).dot(inv(cosm(a)))
+
+    >>> s = sinm(a)
+    >>> c = cosm(a)
+    >>> s.dot(np.linalg.inv(c))
+    array([[ -2.00876993,  -8.41880636],
+           [ -2.80626879, -10.42757629]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, solve(cosm(A), sinm(A)))
+
+
+def coshm(A):
+    """
+    Compute the hyperbolic matrix cosine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    coshm : (N, N) ndarray
+        Hyperbolic matrix cosine of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanhm, sinhm, coshm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> c = coshm(a)
+    >>> c
+    array([[ 11.24592233,  38.76236492],
+           [ 12.92078831,  50.00828725]])
+
+    Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
+
+    >>> t = tanhm(a)
+    >>> s = sinhm(a)
+    >>> t - s.dot(np.linalg.inv(c))
+    array([[  2.72004641e-15,   4.55191440e-15],
+           [  0.00000000e+00,  -5.55111512e-16]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, 0.5 * (expm(A) + expm(-A)))
+
+
+def sinhm(A):
+    """
+    Compute the hyperbolic matrix sine.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array.
+
+    Returns
+    -------
+    sinhm : (N, N) ndarray
+        Hyperbolic matrix sine of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanhm, sinhm, coshm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> s = sinhm(a)
+    >>> s
+    array([[ 10.57300653,  39.28826594],
+           [ 13.09608865,  49.86127247]])
+
+    Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
+
+    >>> t = tanhm(a)
+    >>> c = coshm(a)
+    >>> t - s.dot(np.linalg.inv(c))
+    array([[  2.72004641e-15,   4.55191440e-15],
+           [  0.00000000e+00,  -5.55111512e-16]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, 0.5 * (expm(A) - expm(-A)))
+
+
+def tanhm(A):
+    """
+    Compute the hyperbolic matrix tangent.
+
+    This routine uses expm to compute the matrix exponentials.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input array
+
+    Returns
+    -------
+    tanhm : (N, N) ndarray
+        Hyperbolic matrix tangent of `A`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import tanhm, sinhm, coshm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> t = tanhm(a)
+    >>> t
+    array([[ 0.3428582 ,  0.51987926],
+           [ 0.17329309,  0.86273746]])
+
+    Verify tanhm(a) = sinhm(a).dot(inv(coshm(a)))
+
+    >>> s = sinhm(a)
+    >>> c = coshm(a)
+    >>> t - s.dot(np.linalg.inv(c))
+    array([[  2.72004641e-15,   4.55191440e-15],
+           [  0.00000000e+00,  -5.55111512e-16]])
+
+    """
+    A = _asarray_square(A)
+    return _maybe_real(A, solve(coshm(A), sinhm(A)))
+
+
+def funm(A, func, disp=True):
+    """
+    Evaluate a matrix function specified by a callable.
+
+    Returns the value of matrix-valued function ``f`` at `A`. The
+    function ``f`` is an extension of the scalar-valued function `func`
+    to matrices.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix at which to evaluate the function
+    func : callable
+        Callable object that evaluates a scalar function f.
+        Must be vectorized (eg. using vectorize).
+    disp : bool, optional
+        Print warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+
+    Returns
+    -------
+    funm : (N, N) ndarray
+        Value of the matrix function specified by func evaluated at `A`
+    errest : float
+        (if disp == False)
+
+        1-norm of the estimated error, ||err||_1 / ||A||_1
+
+    Notes
+    -----
+    This function implements the general algorithm based on Schur decomposition
+    (Algorithm 9.1.1. in [1]_).
+
+    If the input matrix is known to be diagonalizable, then relying on the
+    eigendecomposition is likely to be faster. For example, if your matrix is
+    Hermitian, you can do
+
+    >>> from scipy.linalg import eigh
+    >>> def funm_herm(a, func, check_finite=False):
+    ...     w, v = eigh(a, check_finite=check_finite)
+    ...     ## if you further know that your matrix is positive semidefinite,
+    ...     ## you can optionally guard against precision errors by doing
+    ...     # w = np.maximum(w, 0)
+    ...     w = func(w)
+    ...     return (v * w).dot(v.conj().T)
+
+    References
+    ----------
+    .. [1] Gene H. Golub, Charles F. van Loan, Matrix Computations 4th ed.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import funm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> funm(a, lambda x: x*x)
+    array([[  4.,  15.],
+           [  5.,  19.]])
+    >>> a.dot(a)
+    array([[  4.,  15.],
+           [  5.,  19.]])
+
+    """
+    A = _asarray_square(A)
+    # Perform Shur decomposition (lapack ?gees)
+    T, Z = schur(A)
+    T, Z = rsf2csf(T, Z)
+    n, n = T.shape
+    F = diag(func(diag(T)))  # apply function to diagonal elements
+    F = F.astype(T.dtype.char)  # e.g., when F is real but T is complex
+
+    minden = abs(T[0, 0])
+
+    # implement Algorithm 11.1.1 from Golub and Van Loan
+    #                 "matrix Computations."
+    F, minden = _funm_loops(F, T, n, minden)
+
+    F = dot(dot(Z, F), transpose(conjugate(Z)))
+    F = _maybe_real(A, F)
+
+    tol = {0: feps, 1: eps}[_array_precision[F.dtype.char]]
+    if minden == 0.0:
+        minden = tol
+    err = min(1, max(tol, (tol/minden)*norm(triu(T, 1), 1)))
+    if prod(ravel(logical_not(isfinite(F))), axis=0):
+        err = np.inf
+    if disp:
+        if err > 1000*tol:
+            print("funm result may be inaccurate, approximate err =", err)
+        return F
+    else:
+        return F, err
+
+
+def signm(A, disp=True):
+    """
+    Matrix sign function.
+
+    Extension of the scalar sign(x) to matrices.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix at which to evaluate the sign function
+    disp : bool, optional
+        Print warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+
+    Returns
+    -------
+    signm : (N, N) ndarray
+        Value of the sign function at `A`
+    errest : float
+        (if disp == False)
+
+        1-norm of the estimated error, ||err||_1 / ||A||_1
+
+    Examples
+    --------
+    >>> from scipy.linalg import signm, eigvals
+    >>> a = [[1,2,3], [1,2,1], [1,1,1]]
+    >>> eigvals(a)
+    array([ 4.12488542+0.j, -0.76155718+0.j,  0.63667176+0.j])
+    >>> eigvals(signm(a))
+    array([-1.+0.j,  1.+0.j,  1.+0.j])
+
+    """
+    A = _asarray_square(A)
+
+    def rounded_sign(x):
+        rx = np.real(x)
+        if rx.dtype.char == 'f':
+            c = 1e3*feps*amax(x)
+        else:
+            c = 1e3*eps*amax(x)
+        return sign((absolute(rx) > c) * rx)
+    result, errest = funm(A, rounded_sign, disp=0)
+    errtol = {0: 1e3*feps, 1: 1e3*eps}[_array_precision[result.dtype.char]]
+    if errest < errtol:
+        return result
+
+    # Handle signm of defective matrices:
+
+    # See "E.D.Denman and J.Leyva-Ramos, Appl.Math.Comp.,
+    # 8:237-250,1981" for how to improve the following (currently a
+    # rather naive) iteration process:
+
+    # a = result # sometimes iteration converges faster but where??
+
+    # Shifting to avoid zero eigenvalues. How to ensure that shifting does
+    # not change the spectrum too much?
+    vals = svd(A, compute_uv=False)
+    max_sv = np.amax(vals)
+    # min_nonzero_sv = vals[(vals>max_sv*errtol).tolist().count(1)-1]
+    # c = 0.5/min_nonzero_sv
+    c = 0.5/max_sv
+    S0 = A + c*np.identity(A.shape[0])
+    prev_errest = errest
+    for i in range(100):
+        iS0 = inv(S0)
+        S0 = 0.5*(S0 + iS0)
+        Pp = 0.5*(dot(S0, S0)+S0)
+        errest = norm(dot(Pp, Pp)-Pp, 1)
+        if errest < errtol or prev_errest == errest:
+            break
+        prev_errest = errest
+    if disp:
+        if not isfinite(errest) or errest >= errtol:
+            print("signm result may be inaccurate, approximate err =", errest)
+        return S0
+    else:
+        return S0, errest
+
+
+def khatri_rao(a, b):
+    r"""
+    Khatri-rao product
+
+    A column-wise Kronecker product of two matrices
+
+    Parameters
+    ----------
+    a : (n, k) array_like
+        Input array
+    b : (m, k) array_like
+        Input array
+
+    Returns
+    -------
+    c:  (n*m, k) ndarray
+        Khatri-rao product of `a` and `b`.
+
+    Notes
+    -----
+    The mathematical definition of the Khatri-Rao product is:
+
+    .. math::
+
+        (A_{ij}  \bigotimes B_{ij})_{ij}
+
+    which is the Kronecker product of every column of A and B, e.g.::
+
+        c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[1, 2, 3], [4, 5, 6]])
+    >>> b = np.array([[3, 4, 5], [6, 7, 8], [2, 3, 9]])
+    >>> linalg.khatri_rao(a, b)
+    array([[ 3,  8, 15],
+           [ 6, 14, 24],
+           [ 2,  6, 27],
+           [12, 20, 30],
+           [24, 35, 48],
+           [ 8, 15, 54]])
+
+    """
+    a = np.asarray(a)
+    b = np.asarray(b)
+
+    if not (a.ndim == 2 and b.ndim == 2):
+        raise ValueError("The both arrays should be 2-dimensional.")
+
+    if not a.shape[1] == b.shape[1]:
+        raise ValueError("The number of columns for both arrays "
+                         "should be equal.")
+
+    # accommodate empty arrays
+    if a.size == 0 or b.size == 0:
+        m = a.shape[0] * b.shape[0]
+        n = a.shape[1]
+        return np.empty_like(a, shape=(m, n))
+
+    # c = np.vstack([np.kron(a[:, k], b[:, k]) for k in range(b.shape[1])]).T
+    c = a[..., :, np.newaxis, :] * b[..., np.newaxis, :, :]
+    return c.reshape((-1,) + c.shape[2:])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..98ca455c6eb06c1e95e6e11d3db2dc346a295fde
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_expm.pyi
@@ -0,0 +1,6 @@
+from numpy.typing import NDArray
+from typing import Any
+
+def pick_pade_structure(a: NDArray[Any]) -> tuple[int, int]: ...
+
+def pade_UV_calc(Am: NDArray[Any], m: int) -> int: ...
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
new file mode 100644
index 0000000000000000000000000000000000000000..1decffae2e521f0a9325b873cc33b095a4e3c166
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_inv_ssq.py
@@ -0,0 +1,886 @@
+"""
+Matrix functions that use Pade approximation with inverse scaling and squaring.
+
+"""
+import warnings
+
+import numpy as np
+
+from scipy.linalg._matfuncs_sqrtm import SqrtmError, _sqrtm_triu
+from scipy.linalg._decomp_schur import schur, rsf2csf
+from scipy.linalg._matfuncs import funm
+from scipy.linalg import svdvals, solve_triangular
+from scipy.sparse.linalg._interface import LinearOperator
+from scipy.sparse.linalg import onenormest
+import scipy.special
+
+
+class LogmRankWarning(UserWarning):
+    pass
+
+
+class LogmExactlySingularWarning(LogmRankWarning):
+    pass
+
+
+class LogmNearlySingularWarning(LogmRankWarning):
+    pass
+
+
+class LogmError(np.linalg.LinAlgError):
+    pass
+
+
+class FractionalMatrixPowerError(np.linalg.LinAlgError):
+    pass
+
+
+#TODO renovate or move this class when scipy operators are more mature
+class _MatrixM1PowerOperator(LinearOperator):
+    """
+    A representation of the linear operator (A - I)^p.
+    """
+
+    def __init__(self, A, p):
+        if A.ndim != 2 or A.shape[0] != A.shape[1]:
+            raise ValueError('expected A to be like a square matrix')
+        if p < 0 or p != int(p):
+            raise ValueError('expected p to be a non-negative integer')
+        self._A = A
+        self._p = p
+        self.ndim = A.ndim
+        self.shape = A.shape
+
+    def _matvec(self, x):
+        for i in range(self._p):
+            x = self._A.dot(x) - x
+        return x
+
+    def _rmatvec(self, x):
+        for i in range(self._p):
+            x = x.dot(self._A) - x
+        return x
+
+    def _matmat(self, X):
+        for i in range(self._p):
+            X = self._A.dot(X) - X
+        return X
+
+    def _adjoint(self):
+        return _MatrixM1PowerOperator(self._A.T, self._p)
+
+
+#TODO renovate or move this function when SciPy operators are more mature
+def _onenormest_m1_power(A, p,
+        t=2, itmax=5, compute_v=False, compute_w=False):
+    """
+    Efficiently estimate the 1-norm of (A - I)^p.
+
+    Parameters
+    ----------
+    A : ndarray
+        Matrix whose 1-norm of a power is to be computed.
+    p : int
+        Non-negative integer power.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+        Larger values take longer and use more memory
+        but give more accurate output.
+    itmax : int, optional
+        Use at most this many iterations.
+    compute_v : bool, optional
+        Request a norm-maximizing linear operator input vector if True.
+    compute_w : bool, optional
+        Request a norm-maximizing linear operator output vector if True.
+
+    Returns
+    -------
+    est : float
+        An underestimate of the 1-norm of the sparse matrix.
+    v : ndarray, optional
+        The vector such that ||Av||_1 == est*||v||_1.
+        It can be thought of as an input to the linear operator
+        that gives an output with particularly large norm.
+    w : ndarray, optional
+        The vector Av which has relatively large 1-norm.
+        It can be thought of as an output of the linear operator
+        that is relatively large in norm compared to the input.
+
+    """
+    return onenormest(_MatrixM1PowerOperator(A, p),
+            t=t, itmax=itmax, compute_v=compute_v, compute_w=compute_w)
+
+
+def _unwindk(z):
+    """
+    Compute the scalar unwinding number.
+
+    Uses Eq. (5.3) in [1]_, and should be equal to (z - log(exp(z)) / (2 pi i).
+    Note that this definition differs in sign from the original definition
+    in equations (5, 6) in [2]_.  The sign convention is justified in [3]_.
+
+    Parameters
+    ----------
+    z : complex
+        A complex number.
+
+    Returns
+    -------
+    unwinding_number : integer
+        The scalar unwinding number of z.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    .. [2] Robert M. Corless and David J. Jeffrey,
+           "The unwinding number." Newsletter ACM SIGSAM Bulletin
+           Volume 30, Issue 2, June 1996, Pages 28-35.
+
+    .. [3] Russell Bradford and Robert M. Corless and James H. Davenport and
+           David J. Jeffrey and Stephen M. Watt,
+           "Reasoning about the elementary functions of complex analysis"
+           Annals of Mathematics and Artificial Intelligence,
+           36: 303-318, 2002.
+
+    """
+    return int(np.ceil((z.imag - np.pi) / (2*np.pi)))
+
+
+def _briggs_helper_function(a, k):
+    """
+    Computes r = a^(1 / (2^k)) - 1.
+
+    This is algorithm (2) of [1]_.
+    The purpose is to avoid a danger of subtractive cancellation.
+    For more computational efficiency it should probably be cythonized.
+
+    Parameters
+    ----------
+    a : complex
+        A complex number.
+    k : integer
+        A nonnegative integer.
+
+    Returns
+    -------
+    r : complex
+        The value r = a^(1 / (2^k)) - 1 computed with less cancellation.
+
+    Notes
+    -----
+    The algorithm as formulated in the reference does not handle k=0 or k=1
+    correctly, so these are special-cased in this implementation.
+    This function is intended to not allow `a` to belong to the closed
+    negative real axis, but this constraint is relaxed.
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy (2012)
+           "A more accurate Briggs method for the logarithm",
+           Numerical Algorithms, 59 : 393--402.
+
+    """
+    if k < 0 or int(k) != k:
+        raise ValueError('expected a nonnegative integer k')
+    if k == 0:
+        return a - 1
+    elif k == 1:
+        return np.sqrt(a) - 1
+    else:
+        k_hat = k
+        if np.angle(a) >= np.pi / 2:
+            a = np.sqrt(a)
+            k_hat = k - 1
+        z0 = a - 1
+        a = np.sqrt(a)
+        r = 1 + a
+        for j in range(1, k_hat):
+            a = np.sqrt(a)
+            r = r * (1 + a)
+        r = z0 / r
+        return r
+
+
+def _fractional_power_superdiag_entry(l1, l2, t12, p):
+    """
+    Compute a superdiagonal entry of a fractional matrix power.
+
+    This is Eq. (5.6) in [1]_.
+
+    Parameters
+    ----------
+    l1 : complex
+        A diagonal entry of the matrix.
+    l2 : complex
+        A diagonal entry of the matrix.
+    t12 : complex
+        A superdiagonal entry of the matrix.
+    p : float
+        A fractional power.
+
+    Returns
+    -------
+    f12 : complex
+        A superdiagonal entry of the fractional matrix power.
+
+    Notes
+    -----
+    Care has been taken to return a real number if possible when
+    all of the inputs are real numbers.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    if l1 == l2:
+        f12 = t12 * p * l1**(p-1)
+    elif abs(l2 - l1) > abs(l1 + l2) / 2:
+        f12 = t12 * ((l2**p) - (l1**p)) / (l2 - l1)
+    else:
+        # This is Eq. (5.5) in [1].
+        z = (l2 - l1) / (l2 + l1)
+        log_l1 = np.log(l1)
+        log_l2 = np.log(l2)
+        arctanh_z = np.arctanh(z)
+        tmp_a = t12 * np.exp((p/2)*(log_l2 + log_l1))
+        tmp_u = _unwindk(log_l2 - log_l1)
+        if tmp_u:
+            tmp_b = p * (arctanh_z + np.pi * 1j * tmp_u)
+        else:
+            tmp_b = p * arctanh_z
+        tmp_c = 2 * np.sinh(tmp_b) / (l2 - l1)
+        f12 = tmp_a * tmp_c
+    return f12
+
+
+def _logm_superdiag_entry(l1, l2, t12):
+    """
+    Compute a superdiagonal entry of a matrix logarithm.
+
+    This is like Eq. (11.28) in [1]_, except the determination of whether
+    l1 and l2 are sufficiently far apart has been modified.
+
+    Parameters
+    ----------
+    l1 : complex
+        A diagonal entry of the matrix.
+    l2 : complex
+        A diagonal entry of the matrix.
+    t12 : complex
+        A superdiagonal entry of the matrix.
+
+    Returns
+    -------
+    f12 : complex
+        A superdiagonal entry of the matrix logarithm.
+
+    Notes
+    -----
+    Care has been taken to return a real number if possible when
+    all of the inputs are real numbers.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham (2008)
+           "Functions of Matrices: Theory and Computation"
+           ISBN 978-0-898716-46-7
+
+    """
+    if l1 == l2:
+        f12 = t12 / l1
+    elif abs(l2 - l1) > abs(l1 + l2) / 2:
+        f12 = t12 * (np.log(l2) - np.log(l1)) / (l2 - l1)
+    else:
+        z = (l2 - l1) / (l2 + l1)
+        u = _unwindk(np.log(l2) - np.log(l1))
+        if u:
+            f12 = t12 * 2 * (np.arctanh(z) + np.pi*1j*u) / (l2 - l1)
+        else:
+            f12 = t12 * 2 * np.arctanh(z) / (l2 - l1)
+    return f12
+
+
+def _inverse_squaring_helper(T0, theta):
+    """
+    A helper function for inverse scaling and squaring for Pade approximation.
+
+    Parameters
+    ----------
+    T0 : (N, N) array_like upper triangular
+        Matrix involved in inverse scaling and squaring.
+    theta : indexable
+        The values theta[1] .. theta[7] must be available.
+        They represent bounds related to Pade approximation, and they depend
+        on the matrix function which is being computed.
+        For example, different values of theta are required for
+        matrix logarithm than for fractional matrix power.
+
+    Returns
+    -------
+    R : (N, N) array_like upper triangular
+        Composition of zero or more matrix square roots of T0, minus I.
+    s : non-negative integer
+        Number of square roots taken.
+    m : positive integer
+        The degree of the Pade approximation.
+
+    Notes
+    -----
+    This subroutine appears as a chunk of lines within
+    a couple of published algorithms; for example it appears
+    as lines 4--35 in algorithm (3.1) of [1]_, and
+    as lines 3--34 in algorithm (4.1) of [2]_.
+    The instances of 'goto line 38' in algorithm (3.1) of [1]_
+    probably mean 'goto line 36' and have been interpreted accordingly.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2013)
+           "An Improved Schur-Pade Algorithm for Fractional Powers
+           of a Matrix and their Frechet Derivatives."
+
+    .. [2] Awad H. Al-Mohy and Nicholas J. Higham (2012)
+           "Improved Inverse Scaling and Squaring Algorithms
+           for the Matrix Logarithm."
+           SIAM Journal on Scientific Computing, 34 (4). C152-C169.
+           ISSN 1095-7197
+
+    """
+    if len(T0.shape) != 2 or T0.shape[0] != T0.shape[1]:
+        raise ValueError('expected an upper triangular square matrix')
+    n, n = T0.shape
+    T = T0
+
+    # Find s0, the smallest s such that the spectral radius
+    # of a certain diagonal matrix is at most theta[7].
+    # Note that because theta[7] < 1,
+    # this search will not terminate if any diagonal entry of T is zero.
+    s0 = 0
+    tmp_diag = np.diag(T)
+    if np.count_nonzero(tmp_diag) != n:
+        raise Exception('Diagonal entries of T must be nonzero')
+    while np.max(np.absolute(tmp_diag - 1), initial=0.) > theta[7]:
+        tmp_diag = np.sqrt(tmp_diag)
+        s0 += 1
+
+    # Take matrix square roots of T.
+    for i in range(s0):
+        T = _sqrtm_triu(T)
+
+    # Flow control in this section is a little odd.
+    # This is because I am translating algorithm descriptions
+    # which have GOTOs in the publication.
+    s = s0
+    k = 0
+    d2 = _onenormest_m1_power(T, 2) ** (1/2)
+    d3 = _onenormest_m1_power(T, 3) ** (1/3)
+    a2 = max(d2, d3)
+    m = None
+    for i in (1, 2):
+        if a2 <= theta[i]:
+            m = i
+            break
+    while m is None:
+        if s > s0:
+            d3 = _onenormest_m1_power(T, 3) ** (1/3)
+        d4 = _onenormest_m1_power(T, 4) ** (1/4)
+        a3 = max(d3, d4)
+        if a3 <= theta[7]:
+            j1 = min(i for i in (3, 4, 5, 6, 7) if a3 <= theta[i])
+            if j1 <= 6:
+                m = j1
+                break
+            elif a3 / 2 <= theta[5] and k < 2:
+                k += 1
+                T = _sqrtm_triu(T)
+                s += 1
+                continue
+        d5 = _onenormest_m1_power(T, 5) ** (1/5)
+        a4 = max(d4, d5)
+        eta = min(a3, a4)
+        for i in (6, 7):
+            if eta <= theta[i]:
+                m = i
+                break
+        if m is not None:
+            break
+        T = _sqrtm_triu(T)
+        s += 1
+
+    # The subtraction of the identity is redundant here,
+    # because the diagonal will be replaced for improved numerical accuracy,
+    # but this formulation should help clarify the meaning of R.
+    R = T - np.identity(n)
+
+    # Replace the diagonal and first superdiagonal of T0^(1/(2^s)) - I
+    # using formulas that have less subtractive cancellation.
+    # Skip this step if the principal branch
+    # does not exist at T0; this happens when a diagonal entry of T0
+    # is negative with imaginary part 0.
+    has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0))
+    if has_principal_branch:
+        for j in range(n):
+            a = T0[j, j]
+            r = _briggs_helper_function(a, s)
+            R[j, j] = r
+        p = np.exp2(-s)
+        for j in range(n-1):
+            l1 = T0[j, j]
+            l2 = T0[j+1, j+1]
+            t12 = T0[j, j+1]
+            f12 = _fractional_power_superdiag_entry(l1, l2, t12, p)
+            R[j, j+1] = f12
+
+    # Return the T-I matrix, the number of square roots, and the Pade degree.
+    if not np.array_equal(R, np.triu(R)):
+        raise Exception('R is not upper triangular')
+    return R, s, m
+
+
+def _fractional_power_pade_constant(i, t):
+    # A helper function for matrix fractional power.
+    if i < 1:
+        raise ValueError('expected a positive integer i')
+    if not (-1 < t < 1):
+        raise ValueError('expected -1 < t < 1')
+    if i == 1:
+        return -t
+    elif i % 2 == 0:
+        j = i // 2
+        return (-j + t) / (2 * (2*j - 1))
+    elif i % 2 == 1:
+        j = (i - 1) // 2
+        return (-j - t) / (2 * (2*j + 1))
+    else:
+        raise Exception(f'unnexpected value of i, i = {i}')
+
+
+def _fractional_power_pade(R, t, m):
+    """
+    Evaluate the Pade approximation of a fractional matrix power.
+
+    Evaluate the degree-m Pade approximation of R
+    to the fractional matrix power t using the continued fraction
+    in bottom-up fashion using algorithm (4.1) in [1]_.
+
+    Parameters
+    ----------
+    R : (N, N) array_like
+        Upper triangular matrix whose fractional power to evaluate.
+    t : float
+        Fractional power between -1 and 1 exclusive.
+    m : positive integer
+        Degree of Pade approximation.
+
+    Returns
+    -------
+    U : (N, N) array_like
+        The degree-m Pade approximation of R to the fractional power t.
+        This matrix will be upper triangular.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    if m < 1 or int(m) != m:
+        raise ValueError('expected a positive integer m')
+    if not (-1 < t < 1):
+        raise ValueError('expected -1 < t < 1')
+    R = np.asarray(R)
+    if len(R.shape) != 2 or R.shape[0] != R.shape[1]:
+        raise ValueError('expected an upper triangular square matrix')
+    n, n = R.shape
+    ident = np.identity(n)
+    Y = R * _fractional_power_pade_constant(2*m, t)
+    for j in range(2*m - 1, 0, -1):
+        rhs = R * _fractional_power_pade_constant(j, t)
+        Y = solve_triangular(ident + Y, rhs)
+    U = ident + Y
+    if not np.array_equal(U, np.triu(U)):
+        raise Exception('U is not upper triangular')
+    return U
+
+
+def _remainder_matrix_power_triu(T, t):
+    """
+    Compute a fractional power of an upper triangular matrix.
+
+    The fractional power is restricted to fractions -1 < t < 1.
+    This uses algorithm (3.1) of [1]_.
+    The Pade approximation itself uses algorithm (4.1) of [2]_.
+
+    Parameters
+    ----------
+    T : (N, N) array_like
+        Upper triangular matrix whose fractional power to evaluate.
+    t : float
+        Fractional power between -1 and 1 exclusive.
+
+    Returns
+    -------
+    X : (N, N) array_like
+        The fractional power of the matrix.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2013)
+           "An Improved Schur-Pade Algorithm for Fractional Powers
+           of a Matrix and their Frechet Derivatives."
+
+    .. [2] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    m_to_theta = {
+            1: 1.51e-5,
+            2: 2.24e-3,
+            3: 1.88e-2,
+            4: 6.04e-2,
+            5: 1.24e-1,
+            6: 2.00e-1,
+            7: 2.79e-1,
+            }
+    n, n = T.shape
+    T0 = T
+    T0_diag = np.diag(T0)
+    if np.array_equal(T0, np.diag(T0_diag)):
+        U = np.diag(T0_diag ** t)
+    else:
+        R, s, m = _inverse_squaring_helper(T0, m_to_theta)
+
+        # Evaluate the Pade approximation.
+        # Note that this function expects the negative of the matrix
+        # returned by the inverse squaring helper.
+        U = _fractional_power_pade(-R, t, m)
+
+        # Undo the inverse scaling and squaring.
+        # Be less clever about this
+        # if the principal branch does not exist at T0;
+        # this happens when a diagonal entry of T0
+        # is negative with imaginary part 0.
+        eivals = np.diag(T0)
+        has_principal_branch = all(x.real > 0 or x.imag != 0 for x in eivals)
+        for i in range(s, -1, -1):
+            if i < s:
+                U = U.dot(U)
+            else:
+                if has_principal_branch:
+                    p = t * np.exp2(-i)
+                    U[np.diag_indices(n)] = T0_diag ** p
+                    for j in range(n-1):
+                        l1 = T0[j, j]
+                        l2 = T0[j+1, j+1]
+                        t12 = T0[j, j+1]
+                        f12 = _fractional_power_superdiag_entry(l1, l2, t12, p)
+                        U[j, j+1] = f12
+    if not np.array_equal(U, np.triu(U)):
+        raise Exception('U is not upper triangular')
+    return U
+
+
+def _remainder_matrix_power(A, t):
+    """
+    Compute the fractional power of a matrix, for fractions -1 < t < 1.
+
+    This uses algorithm (3.1) of [1]_.
+    The Pade approximation itself uses algorithm (4.1) of [2]_.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose fractional power to evaluate.
+    t : float
+        Fractional power between -1 and 1 exclusive.
+
+    Returns
+    -------
+    X : (N, N) array_like
+        The fractional power of the matrix.
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Lijing Lin (2013)
+           "An Improved Schur-Pade Algorithm for Fractional Powers
+           of a Matrix and their Frechet Derivatives."
+
+    .. [2] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    # This code block is copied from numpy.matrix_power().
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('input must be a square array')
+
+    # Get the number of rows and columns.
+    n, n = A.shape
+
+    # Triangularize the matrix if necessary,
+    # attempting to preserve dtype if possible.
+    if np.array_equal(A, np.triu(A)):
+        Z = None
+        T = A
+    else:
+        if np.isrealobj(A):
+            T, Z = schur(A)
+            if not np.array_equal(T, np.triu(T)):
+                T, Z = rsf2csf(T, Z)
+        else:
+            T, Z = schur(A, output='complex')
+
+    # Zeros on the diagonal of the triangular matrix are forbidden,
+    # because the inverse scaling and squaring cannot deal with it.
+    T_diag = np.diag(T)
+    if np.count_nonzero(T_diag) != n:
+        raise FractionalMatrixPowerError(
+                'cannot use inverse scaling and squaring to find '
+                'the fractional matrix power of a singular matrix')
+
+    # If the triangular matrix is real and has a negative
+    # entry on the diagonal, then force the matrix to be complex.
+    if np.isrealobj(T) and np.min(T_diag) < 0:
+        T = T.astype(complex)
+
+    # Get the fractional power of the triangular matrix,
+    # and de-triangularize it if necessary.
+    U = _remainder_matrix_power_triu(T, t)
+    if Z is not None:
+        ZH = np.conjugate(Z).T
+        return Z.dot(U).dot(ZH)
+    else:
+        return U
+
+
+def _fractional_matrix_power(A, p):
+    """
+    Compute the fractional power of a matrix.
+
+    See the fractional_matrix_power docstring in matfuncs.py for more info.
+
+    """
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+    if p == int(p):
+        return np.linalg.matrix_power(A, int(p))
+    # Compute singular values.
+    s = svdvals(A)
+    # Inverse scaling and squaring cannot deal with a singular matrix,
+    # because the process of repeatedly taking square roots
+    # would not converge to the identity matrix.
+    if s[-1]:
+        # Compute the condition number relative to matrix inversion,
+        # and use this to decide between floor(p) and ceil(p).
+        k2 = s[0] / s[-1]
+        p1 = p - np.floor(p)
+        p2 = p - np.ceil(p)
+        if p1 * k2 ** (1 - p1) <= -p2 * k2:
+            a = int(np.floor(p))
+            b = p1
+        else:
+            a = int(np.ceil(p))
+            b = p2
+        try:
+            R = _remainder_matrix_power(A, b)
+            Q = np.linalg.matrix_power(A, a)
+            return Q.dot(R)
+        except np.linalg.LinAlgError:
+            pass
+    # If p is negative then we are going to give up.
+    # If p is non-negative then we can fall back to generic funm.
+    if p < 0:
+        X = np.empty_like(A)
+        X.fill(np.nan)
+        return X
+    else:
+        p1 = p - np.floor(p)
+        a = int(np.floor(p))
+        b = p1
+        R, info = funm(A, lambda x: pow(x, b), disp=False)
+        Q = np.linalg.matrix_power(A, a)
+        return Q.dot(R)
+
+
+def _logm_triu(T):
+    """
+    Compute matrix logarithm of an upper triangular matrix.
+
+    The matrix logarithm is the inverse of
+    expm: expm(logm(`T`)) == `T`
+
+    Parameters
+    ----------
+    T : (N, N) array_like
+        Upper triangular matrix whose logarithm to evaluate
+
+    Returns
+    -------
+    logm : (N, N) ndarray
+        Matrix logarithm of `T`
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
+           "Improved Inverse Scaling and Squaring Algorithms
+           for the Matrix Logarithm."
+           SIAM Journal on Scientific Computing, 34 (4). C152-C169.
+           ISSN 1095-7197
+
+    .. [2] Nicholas J. Higham (2008)
+           "Functions of Matrices: Theory and Computation"
+           ISBN 978-0-898716-46-7
+
+    .. [3] Nicholas J. Higham and Lijing lin (2011)
+           "A Schur-Pade Algorithm for Fractional Powers of a Matrix."
+           SIAM Journal on Matrix Analysis and Applications,
+           32 (3). pp. 1056-1078. ISSN 0895-4798
+
+    """
+    T = np.asarray(T)
+    if len(T.shape) != 2 or T.shape[0] != T.shape[1]:
+        raise ValueError('expected an upper triangular square matrix')
+    n, n = T.shape
+
+    # Construct T0 with the appropriate type,
+    # depending on the dtype and the spectrum of T.
+    T_diag = np.diag(T)
+    keep_it_real = np.isrealobj(T) and np.min(T_diag, initial=0.) >= 0
+    if keep_it_real:
+        T0 = T
+    else:
+        T0 = T.astype(complex)
+
+    # Define bounds given in Table (2.1).
+    theta = (None,
+            1.59e-5, 2.31e-3, 1.94e-2, 6.21e-2,
+            1.28e-1, 2.06e-1, 2.88e-1, 3.67e-1,
+            4.39e-1, 5.03e-1, 5.60e-1, 6.09e-1,
+            6.52e-1, 6.89e-1, 7.21e-1, 7.49e-1)
+
+    R, s, m = _inverse_squaring_helper(T0, theta)
+
+    # Evaluate U = 2**s r_m(T - I) using the partial fraction expansion (1.1).
+    # This requires the nodes and weights
+    # corresponding to degree-m Gauss-Legendre quadrature.
+    # These quadrature arrays need to be transformed from the [-1, 1] interval
+    # to the [0, 1] interval.
+    nodes, weights = scipy.special.p_roots(m)
+    nodes = nodes.real
+    if nodes.shape != (m,) or weights.shape != (m,):
+        raise Exception('internal error')
+    nodes = 0.5 + 0.5 * nodes
+    weights = 0.5 * weights
+    ident = np.identity(n)
+    U = np.zeros_like(R)
+    for alpha, beta in zip(weights, nodes):
+        U += solve_triangular(ident + beta*R, alpha*R)
+    U *= np.exp2(s)
+
+    # Skip this step if the principal branch
+    # does not exist at T0; this happens when a diagonal entry of T0
+    # is negative with imaginary part 0.
+    has_principal_branch = all(x.real > 0 or x.imag != 0 for x in np.diag(T0))
+    if has_principal_branch:
+
+        # Recompute diagonal entries of U.
+        U[np.diag_indices(n)] = np.log(np.diag(T0))
+
+        # Recompute superdiagonal entries of U.
+        # This indexing of this code should be renovated
+        # when newer np.diagonal() becomes available.
+        for i in range(n-1):
+            l1 = T0[i, i]
+            l2 = T0[i+1, i+1]
+            t12 = T0[i, i+1]
+            U[i, i+1] = _logm_superdiag_entry(l1, l2, t12)
+
+    # Return the logm of the upper triangular matrix.
+    if not np.array_equal(U, np.triu(U)):
+        raise Exception('U is not upper triangular')
+    return U
+
+
+def _logm_force_nonsingular_triangular_matrix(T, inplace=False):
+    # The input matrix should be upper triangular.
+    # The eps is ad hoc and is not meant to be machine precision.
+    tri_eps = 1e-20
+    abs_diag = np.absolute(np.diag(T))
+    if np.any(abs_diag == 0):
+        exact_singularity_msg = 'The logm input matrix is exactly singular.'
+        warnings.warn(exact_singularity_msg, LogmExactlySingularWarning, stacklevel=3)
+        if not inplace:
+            T = T.copy()
+        n = T.shape[0]
+        for i in range(n):
+            if not T[i, i]:
+                T[i, i] = tri_eps
+    elif np.any(abs_diag < tri_eps):
+        near_singularity_msg = 'The logm input matrix may be nearly singular.'
+        warnings.warn(near_singularity_msg, LogmNearlySingularWarning, stacklevel=3)
+    return T
+
+
+def _logm(A):
+    """
+    Compute the matrix logarithm.
+
+    See the logm docstring in matfuncs.py for more info.
+
+    Notes
+    -----
+    In this function we look at triangular matrices that are similar
+    to the input matrix. If any diagonal entry of such a triangular matrix
+    is exactly zero then the original matrix is singular.
+    The matrix logarithm does not exist for such matrices,
+    but in such cases we will pretend that the diagonal entries that are zero
+    are actually slightly positive by an ad-hoc amount, in the interest
+    of returning something more useful than NaN. This will cause a warning.
+
+    """
+    A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    # If the input matrix dtype is integer then copy to a float dtype matrix.
+    if issubclass(A.dtype.type, np.integer):
+        A = np.asarray(A, dtype=float)
+
+    keep_it_real = np.isrealobj(A)
+    try:
+        if np.array_equal(A, np.triu(A)):
+            A = _logm_force_nonsingular_triangular_matrix(A)
+            if np.min(np.diag(A), initial=0.) < 0:
+                A = A.astype(complex)
+            return _logm_triu(A)
+        else:
+            if keep_it_real:
+                T, Z = schur(A)
+                if not np.array_equal(T, np.triu(T)):
+                    T, Z = rsf2csf(T, Z)
+            else:
+                T, Z = schur(A, output='complex')
+            T = _logm_force_nonsingular_triangular_matrix(T, inplace=True)
+            U = _logm_triu(T)
+            ZH = np.conjugate(Z).T
+            return Z.dot(U).dot(ZH)
+    except (SqrtmError, LogmError):
+        X = np.empty_like(A)
+        X.fill(np.nan)
+        return X
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7da6ced474ee3db548a24ecc08d7e2627f0d7a4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_matfuncs_sqrtm.py
@@ -0,0 +1,205 @@
+"""
+Matrix square root for general matrices and for upper triangular matrices.
+
+This module exists to avoid cyclic imports.
+
+"""
+__all__ = ['sqrtm']
+
+import numpy as np
+
+from scipy._lib._util import _asarray_validated
+
+# Local imports
+from ._misc import norm
+from .lapack import ztrsyl, dtrsyl
+from ._decomp_schur import schur, rsf2csf
+from ._basic import _ensure_dtype_cdsz
+
+
+
+class SqrtmError(np.linalg.LinAlgError):
+    pass
+
+
+from ._matfuncs_sqrtm_triu import within_block_loop  # noqa: E402
+
+
+def _sqrtm_triu(T, blocksize=64):
+    """
+    Matrix square root of an upper triangular matrix.
+
+    This is a helper function for `sqrtm` and `logm`.
+
+    Parameters
+    ----------
+    T : (N, N) array_like upper triangular
+        Matrix whose square root to evaluate
+    blocksize : int, optional
+        If the blocksize is not degenerate with respect to the
+        size of the input array, then use a blocked algorithm. (Default: 64)
+
+    Returns
+    -------
+    sqrtm : (N, N) ndarray
+        Value of the sqrt function at `T`
+
+    References
+    ----------
+    .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
+           "Blocked Schur Algorithms for Computing the Matrix Square Root,
+           Lecture Notes in Computer Science, 7782. pp. 171-182.
+
+    """
+    T_diag = np.diag(T)
+    keep_it_real = np.isrealobj(T) and np.min(T_diag, initial=0.) >= 0
+
+    # Cast to complex as necessary + ensure double precision
+    if not keep_it_real:
+        T = np.asarray(T, dtype=np.complex128, order="C")
+        T_diag = np.asarray(T_diag, dtype=np.complex128)
+    else:
+        T = np.asarray(T, dtype=np.float64, order="C")
+        T_diag = np.asarray(T_diag, dtype=np.float64)
+
+    R = np.diag(np.sqrt(T_diag))
+
+    # Compute the number of blocks to use; use at least one block.
+    n, n = T.shape
+    nblocks = max(n // blocksize, 1)
+
+    # Compute the smaller of the two sizes of blocks that
+    # we will actually use, and compute the number of large blocks.
+    bsmall, nlarge = divmod(n, nblocks)
+    blarge = bsmall + 1
+    nsmall = nblocks - nlarge
+    if nsmall * bsmall + nlarge * blarge != n:
+        raise Exception('internal inconsistency')
+
+    # Define the index range covered by each block.
+    start_stop_pairs = []
+    start = 0
+    for count, size in ((nsmall, bsmall), (nlarge, blarge)):
+        for i in range(count):
+            start_stop_pairs.append((start, start + size))
+            start += size
+
+    # Within-block interactions (Cythonized)
+    try:
+        within_block_loop(R, T, start_stop_pairs, nblocks)
+    except RuntimeError as e:
+        raise SqrtmError(*e.args) from e
+
+    # Between-block interactions (Cython would give no significant speedup)
+    for j in range(nblocks):
+        jstart, jstop = start_stop_pairs[j]
+        for i in range(j-1, -1, -1):
+            istart, istop = start_stop_pairs[i]
+            S = T[istart:istop, jstart:jstop]
+            if j - i > 1:
+                S = S - R[istart:istop, istop:jstart].dot(R[istop:jstart,
+                                                            jstart:jstop])
+
+            # Invoke LAPACK.
+            # For more details, see the solve_sylvester implementation
+            # and the fortran dtrsyl and ztrsyl docs.
+            Rii = R[istart:istop, istart:istop]
+            Rjj = R[jstart:jstop, jstart:jstop]
+            if keep_it_real:
+                x, scale, info = dtrsyl(Rii, Rjj, S)
+            else:
+                x, scale, info = ztrsyl(Rii, Rjj, S)
+            R[istart:istop, jstart:jstop] = x * scale
+
+    # Return the matrix square root.
+    return R
+
+
+def sqrtm(A, disp=True, blocksize=64):
+    """
+    Matrix square root.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Matrix whose square root to evaluate
+    disp : bool, optional
+        Print warning if error in the result is estimated large
+        instead of returning estimated error. (Default: True)
+    blocksize : integer, optional
+        If the blocksize is not degenerate with respect to the
+        size of the input array, then use a blocked algorithm. (Default: 64)
+
+    Returns
+    -------
+    sqrtm : (N, N) ndarray
+        Value of the sqrt function at `A`. The dtype is float or complex.
+        The precision (data size) is determined based on the precision of
+        input `A`.
+
+    errest : float
+        (if disp == False)
+
+        Frobenius norm of the estimated error, ||err||_F / ||A||_F
+
+    References
+    ----------
+    .. [1] Edvin Deadman, Nicholas J. Higham, Rui Ralha (2013)
+           "Blocked Schur Algorithms for Computing the Matrix Square Root,
+           Lecture Notes in Computer Science, 7782. pp. 171-182.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import sqrtm
+    >>> a = np.array([[1.0, 3.0], [1.0, 4.0]])
+    >>> r = sqrtm(a)
+    >>> r
+    array([[ 0.75592895,  1.13389342],
+           [ 0.37796447,  1.88982237]])
+    >>> r.dot(r)
+    array([[ 1.,  3.],
+           [ 1.,  4.]])
+
+    """
+    A = _asarray_validated(A, check_finite=True, as_inexact=True)
+    if len(A.shape) != 2:
+        raise ValueError("Non-matrix input to matrix function.")
+    if blocksize < 1:
+        raise ValueError("The blocksize should be at least 1.")
+    A, = _ensure_dtype_cdsz(A)
+    keep_it_real = np.isrealobj(A)
+    if keep_it_real:
+        T, Z = schur(A)
+        d0 = np.diagonal(T)
+        d1 = np.diagonal(T, -1)
+        eps = np.finfo(T.dtype).eps
+        needs_conversion = abs(d1) > eps * (abs(d0[1:]) + abs(d0[:-1]))
+        if needs_conversion.any():
+            T, Z = rsf2csf(T, Z)
+    else:
+        T, Z = schur(A, output='complex')
+    failflag = False
+    try:
+        R = _sqrtm_triu(T, blocksize=blocksize)
+        ZH = np.conjugate(Z).T
+        X = Z.dot(R).dot(ZH)
+        dtype = np.result_type(A.dtype, 1j if np.iscomplexobj(X) else 1)
+        X = X.astype(dtype, copy=False)
+    except SqrtmError:
+        failflag = True
+        X = np.empty_like(A)
+        X.fill(np.nan)
+
+    if disp:
+        if failflag:
+            print("Failed to find a square root.")
+        return X
+    else:
+        try:
+            arg2 = norm(X.dot(X) - A, 'fro')**2 / norm(A, 'fro')
+        except ValueError:
+            # NaNs in matrix
+            arg2 = np.inf
+
+        return X, arg2
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_misc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..27cd442080c8569417694a8a612fe0a461c1a2ca
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_misc.py
@@ -0,0 +1,191 @@
+import numpy as np
+from numpy.linalg import LinAlgError
+from .blas import get_blas_funcs
+from .lapack import get_lapack_funcs
+
+__all__ = ['LinAlgError', 'LinAlgWarning', 'norm']
+
+
+class LinAlgWarning(RuntimeWarning):
+    """
+    The warning emitted when a linear algebra related operation is close
+    to fail conditions of the algorithm or loss of accuracy is expected.
+    """
+    pass
+
+
+def norm(a, ord=None, axis=None, keepdims=False, check_finite=True):
+    """
+    Matrix or vector norm.
+
+    This function is able to return one of eight different matrix norms,
+    or one of an infinite number of vector norms (described below), depending
+    on the value of the ``ord`` parameter. For tensors with rank different from
+    1 or 2, only `ord=None` is supported.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array. If `axis` is None, `a` must be 1-D or 2-D, unless `ord`
+        is None. If both `axis` and `ord` are None, the 2-norm of
+        ``a.ravel`` will be returned.
+    ord : {int, inf, -inf, 'fro', 'nuc', None}, optional
+        Order of the norm (see table under ``Notes``). inf means NumPy's
+        `inf` object.
+    axis : {int, 2-tuple of ints, None}, optional
+        If `axis` is an integer, it specifies the axis of `a` along which to
+        compute the vector norms. If `axis` is a 2-tuple, it specifies the
+        axes that hold 2-D matrices, and the matrix norms of these matrices
+        are computed. If `axis` is None then either a vector norm (when `a`
+        is 1-D) or a matrix norm (when `a` is 2-D) is returned.
+    keepdims : bool, optional
+        If this is set to True, the axes which are normed over are left in the
+        result as dimensions with size one. With this option the result will
+        broadcast correctly against the original `a`.
+    check_finite : bool, optional
+        Whether to check that the input matrix contains only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    n : float or ndarray
+        Norm of the matrix or vector(s).
+
+    Notes
+    -----
+    For values of ``ord <= 0``, the result is, strictly speaking, not a
+    mathematical 'norm', but it may still be useful for various numerical
+    purposes.
+
+    The following norms can be calculated:
+
+    =====  ============================  ==========================
+    ord    norm for matrices             norm for vectors
+    =====  ============================  ==========================
+    None   Frobenius norm                2-norm
+    'fro'  Frobenius norm                --
+    'nuc'  nuclear norm                  --
+    inf    max(sum(abs(a), axis=1))      max(abs(a))
+    -inf   min(sum(abs(a), axis=1))      min(abs(a))
+    0      --                            sum(a != 0)
+    1      max(sum(abs(a), axis=0))      as below
+    -1     min(sum(abs(a), axis=0))      as below
+    2      2-norm (largest sing. value)  as below
+    -2     smallest singular value       as below
+    other  --                            sum(abs(a)**ord)**(1./ord)
+    =====  ============================  ==========================
+
+    The Frobenius norm is given by [1]_:
+
+        :math:`||A||_F = [\\sum_{i,j} abs(a_{i,j})^2]^{1/2}`
+
+    The nuclear norm is the sum of the singular values.
+
+    Both the Frobenius and nuclear norm orders are only defined for
+    matrices.
+
+    References
+    ----------
+    .. [1] G. H. Golub and C. F. Van Loan, *Matrix Computations*,
+           Baltimore, MD, Johns Hopkins University Press, 1985, pg. 15
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import norm
+    >>> a = np.arange(9) - 4.0
+    >>> a
+    array([-4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.])
+    >>> b = a.reshape((3, 3))
+    >>> b
+    array([[-4., -3., -2.],
+           [-1.,  0.,  1.],
+           [ 2.,  3.,  4.]])
+
+    >>> norm(a)
+    7.745966692414834
+    >>> norm(b)
+    7.745966692414834
+    >>> norm(b, 'fro')
+    7.745966692414834
+    >>> norm(a, np.inf)
+    4.0
+    >>> norm(b, np.inf)
+    9.0
+    >>> norm(a, -np.inf)
+    0.0
+    >>> norm(b, -np.inf)
+    2.0
+
+    >>> norm(a, 1)
+    20.0
+    >>> norm(b, 1)
+    7.0
+    >>> norm(a, -1)
+    -4.6566128774142013e-010
+    >>> norm(b, -1)
+    6.0
+    >>> norm(a, 2)
+    7.745966692414834
+    >>> norm(b, 2)
+    7.3484692283495345
+
+    >>> norm(a, -2)
+    0.0
+    >>> norm(b, -2)
+    1.8570331885190563e-016
+    >>> norm(a, 3)
+    5.8480354764257312
+    >>> norm(a, -3)
+    0.0
+
+    """
+    # Differs from numpy only in non-finite handling and the use of blas.
+    if check_finite:
+        a = np.asarray_chkfinite(a)
+    else:
+        a = np.asarray(a)
+
+    if a.size and a.dtype.char in 'fdFD' and axis is None and not keepdims:
+
+        if ord in (None, 2) and (a.ndim == 1):
+            # use blas for fast and stable euclidean norm
+            nrm2 = get_blas_funcs('nrm2', dtype=a.dtype, ilp64='preferred')
+            return nrm2(a)
+
+        if a.ndim == 2:
+            # Use lapack for a couple fast matrix norms.
+            # For some reason the *lange frobenius norm is slow.
+            lange_args = None
+            # Make sure this works if the user uses the axis keywords
+            # to apply the norm to the transpose.
+            if ord == 1:
+                if np.isfortran(a):
+                    lange_args = '1', a
+                elif np.isfortran(a.T):
+                    lange_args = 'i', a.T
+            elif ord == np.inf:
+                if np.isfortran(a):
+                    lange_args = 'i', a
+                elif np.isfortran(a.T):
+                    lange_args = '1', a.T
+            if lange_args:
+                lange = get_lapack_funcs('lange', dtype=a.dtype, ilp64='preferred')
+                return lange(*lange_args)
+
+    # fall back to numpy in every other case
+    return np.linalg.norm(a, ord=ord, axis=axis, keepdims=keepdims)
+
+
+def _datacopied(arr, original):
+    """
+    Strict check for `arr` not sharing any data with `original`,
+    under the assumption that arr = asarray(original)
+
+    """
+    if arr is original:
+        return False
+    if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
+        return False
+    return arr.base is None
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_procrustes.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d68f0b737ead5d581095ad32a34ae88d153264c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_procrustes.py
@@ -0,0 +1,111 @@
+"""
+Solve the orthogonal Procrustes problem.
+
+"""
+import numpy as np
+from ._decomp_svd import svd
+
+
+__all__ = ['orthogonal_procrustes']
+
+
+def orthogonal_procrustes(A, B, check_finite=True):
+    """
+    Compute the matrix solution of the orthogonal (or unitary) Procrustes problem.
+
+    Given matrices `A` and `B` of the same shape, find an orthogonal (or unitary in
+    the case of complex input) matrix `R` that most closely maps `A` to `B` using the
+    algorithm given in [1]_.
+
+    Parameters
+    ----------
+    A : (M, N) array_like
+        Matrix to be mapped.
+    B : (M, N) array_like
+        Target matrix.
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite numbers.
+        Disabling may give a performance gain, but may result in problems
+        (crashes, non-termination) if the inputs do contain infinities or NaNs.
+
+    Returns
+    -------
+    R : (N, N) ndarray
+        The matrix solution of the orthogonal Procrustes problem.
+        Minimizes the Frobenius norm of ``(A @ R) - B``, subject to
+        ``R.conj().T @ R = I``.
+    scale : float
+        Sum of the singular values of ``A.conj().T @ B``.
+
+    Raises
+    ------
+    ValueError
+        If the input array shapes don't match or if check_finite is True and
+        the arrays contain Inf or NaN.
+
+    Notes
+    -----
+    Note that unlike higher level Procrustes analyses of spatial data, this
+    function only uses orthogonal transformations like rotations and
+    reflections, and it does not use scaling or translation.
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Peter H. Schonemann, "A generalized solution of the orthogonal
+           Procrustes problem", Psychometrica -- Vol. 31, No. 1, March, 1966.
+           :doi:`10.1007/BF02289451`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import orthogonal_procrustes
+    >>> A = np.array([[ 2,  0,  1], [-2,  0,  0]])
+
+    Flip the order of columns and check for the anti-diagonal mapping
+
+    >>> R, sca = orthogonal_procrustes(A, np.fliplr(A))
+    >>> R
+    array([[-5.34384992e-17,  0.00000000e+00,  1.00000000e+00],
+           [ 0.00000000e+00,  1.00000000e+00,  0.00000000e+00],
+           [ 1.00000000e+00,  0.00000000e+00, -7.85941422e-17]])
+    >>> sca
+    9.0
+
+    As an example of the unitary Procrustes problem, generate a
+    random complex matrix ``A``, a random unitary matrix ``Q``,
+    and their product ``B``.
+
+    >>> shape = (4, 4)
+    >>> rng = np.random.default_rng(589234981235)
+    >>> A = rng.random(shape) + rng.random(shape)*1j
+    >>> Q = rng.random(shape) + rng.random(shape)*1j
+    >>> Q, _ = np.linalg.qr(Q)
+    >>> B = A @ Q
+
+    `orthogonal_procrustes` recovers the unitary matrix ``Q``
+    from ``A`` and ``B``.
+
+    >>> R, _ = orthogonal_procrustes(A, B)
+    >>> np.allclose(R, Q)
+    True
+
+    """
+    if check_finite:
+        A = np.asarray_chkfinite(A)
+        B = np.asarray_chkfinite(B)
+    else:
+        A = np.asanyarray(A)
+        B = np.asanyarray(B)
+    if A.ndim != 2:
+        raise ValueError(f'expected ndim to be 2, but observed {A.ndim}')
+    if A.shape != B.shape:
+        raise ValueError(f'the shapes of A and B differ ({A.shape} vs {B.shape})')
+    # Be clever with transposes, with the intention to save memory.
+    # The conjugate has no effect for real inputs, but gives the correct solution
+    # for complex inputs.
+    u, w, vt = svd((B.T @ np.conjugate(A)).T)
+    R = u @ vt
+    scale = w.sum()
+    return R, scale
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_sketches.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_sketches.py
new file mode 100644
index 0000000000000000000000000000000000000000..589172827f528799203cb3e93a4a013e07dc5ff8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_sketches.py
@@ -0,0 +1,178 @@
+""" Sketching-based Matrix Computations """
+
+# Author: Jordi Montes 
+# August 28, 2017
+
+import numpy as np
+
+from scipy._lib._util import (check_random_state, rng_integers,
+                              _transition_to_rng)
+from scipy.sparse import csc_matrix
+
+__all__ = ['clarkson_woodruff_transform']
+
+
+def cwt_matrix(n_rows, n_columns, rng=None):
+    r"""
+    Generate a matrix S which represents a Clarkson-Woodruff transform.
+
+    Given the desired size of matrix, the method returns a matrix S of size
+    (n_rows, n_columns) where each column has all the entries set to 0
+    except for one position which has been randomly set to +1 or -1 with
+    equal probability.
+
+    Parameters
+    ----------
+    n_rows : int
+        Number of rows of S
+    n_columns : int
+        Number of columns of S
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+
+    Returns
+    -------
+    S : (n_rows, n_columns) csc_matrix
+        The returned matrix has ``n_columns`` nonzero entries.
+
+    Notes
+    -----
+    Given a matrix A, with probability at least 9/10,
+    .. math:: \|SA\| = (1 \pm \epsilon)\|A\|
+    Where the error epsilon is related to the size of S.
+    """
+    rng = check_random_state(rng)
+    rows = rng_integers(rng, 0, n_rows, n_columns)
+    cols = np.arange(n_columns+1)
+    signs = rng.choice([1, -1], n_columns)
+    S = csc_matrix((signs, rows, cols), shape=(n_rows, n_columns))
+    return S
+
+
+@_transition_to_rng("seed", position_num=2)
+def clarkson_woodruff_transform(input_matrix, sketch_size, rng=None):
+    r"""
+    Applies a Clarkson-Woodruff Transform/sketch to the input matrix.
+
+    Given an input_matrix ``A`` of size ``(n, d)``, compute a matrix ``A'`` of
+    size (sketch_size, d) so that
+
+    .. math:: \|Ax\| \approx \|A'x\|
+
+    with high probability via the Clarkson-Woodruff Transform, otherwise
+    known as the CountSketch matrix.
+
+    Parameters
+    ----------
+    input_matrix : array_like
+        Input matrix, of shape ``(n, d)``.
+    sketch_size : int
+        Number of rows for the sketch.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    A' : array_like
+        Sketch of the input matrix ``A``, of size ``(sketch_size, d)``.
+
+    Notes
+    -----
+    To make the statement
+
+    .. math:: \|Ax\| \approx \|A'x\|
+
+    precise, observe the following result which is adapted from the
+    proof of Theorem 14 of [2]_ via Markov's Inequality. If we have
+    a sketch size ``sketch_size=k`` which is at least
+
+    .. math:: k \geq \frac{2}{\epsilon^2\delta}
+
+    Then for any fixed vector ``x``,
+
+    .. math:: \|Ax\| = (1\pm\epsilon)\|A'x\|
+
+    with probability at least one minus delta.
+
+    This implementation takes advantage of sparsity: computing
+    a sketch takes time proportional to ``A.nnz``. Data ``A`` which
+    is in ``scipy.sparse.csc_matrix`` format gives the quickest
+    computation time for sparse input.
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> from scipy import sparse
+    >>> rng = np.random.default_rng()
+    >>> n_rows, n_columns, density, sketch_n_rows = 15000, 100, 0.01, 200
+    >>> A = sparse.rand(n_rows, n_columns, density=density, format='csc')
+    >>> B = sparse.rand(n_rows, n_columns, density=density, format='csr')
+    >>> C = sparse.rand(n_rows, n_columns, density=density, format='coo')
+    >>> D = rng.standard_normal((n_rows, n_columns))
+    >>> SA = linalg.clarkson_woodruff_transform(A, sketch_n_rows) # fastest
+    >>> SB = linalg.clarkson_woodruff_transform(B, sketch_n_rows) # fast
+    >>> SC = linalg.clarkson_woodruff_transform(C, sketch_n_rows) # slower
+    >>> SD = linalg.clarkson_woodruff_transform(D, sketch_n_rows) # slowest
+
+    That said, this method does perform well on dense inputs, just slower
+    on a relative scale.
+
+    References
+    ----------
+    .. [1] Kenneth L. Clarkson and David P. Woodruff. Low rank approximation
+           and regression in input sparsity time. In STOC, 2013.
+    .. [2] David P. Woodruff. Sketching as a tool for numerical linear algebra.
+           In Foundations and Trends in Theoretical Computer Science, 2014.
+
+    Examples
+    --------
+    Create a big dense matrix ``A`` for the example:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> n_rows, n_columns  = 15000, 100
+    >>> rng = np.random.default_rng()
+    >>> A = rng.standard_normal((n_rows, n_columns))
+
+    Apply the transform to create a new matrix with 200 rows:
+
+    >>> sketch_n_rows = 200
+    >>> sketch = linalg.clarkson_woodruff_transform(A, sketch_n_rows, seed=rng)
+    >>> sketch.shape
+    (200, 100)
+
+    Now with high probability, the true norm is close to the sketched norm
+    in absolute value.
+
+    >>> linalg.norm(A)
+    1224.2812927123198
+    >>> linalg.norm(sketch)
+    1226.518328407333
+
+    Similarly, applying our sketch preserves the solution to a linear
+    regression of :math:`\min \|Ax - b\|`.
+
+    >>> b = rng.standard_normal(n_rows)
+    >>> x = linalg.lstsq(A, b)[0]
+    >>> Ab = np.hstack((A, b.reshape(-1, 1)))
+    >>> SAb = linalg.clarkson_woodruff_transform(Ab, sketch_n_rows, seed=rng)
+    >>> SA, Sb = SAb[:, :-1], SAb[:, -1]
+    >>> x_sketched = linalg.lstsq(SA, Sb)[0]
+
+    As with the matrix norm example, ``linalg.norm(A @ x - b)`` is close
+    to ``linalg.norm(A @ x_sketched - b)`` with high probability.
+
+    >>> linalg.norm(A @ x - b)
+    122.83242365433877
+    >>> linalg.norm(A @ x_sketched - b)
+    166.58473879945151
+
+    """
+    S = cwt_matrix(sketch_size, input_matrix.shape[0], rng=rng)
+    return S.dot(input_matrix)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_solvers.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..60a6a73e7bf9cce36090137c0e884d3ed22c55a8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_solvers.py
@@ -0,0 +1,857 @@
+"""Matrix equation solver routines"""
+# Author: Jeffrey Armstrong 
+# February 24, 2012
+
+# Modified: Chad Fulton 
+# June 19, 2014
+
+# Modified: Ilhan Polat 
+# September 13, 2016
+
+import warnings
+import numpy as np
+from numpy.linalg import inv, LinAlgError, norm, cond, svd
+
+from ._basic import solve, solve_triangular, matrix_balance
+from .lapack import get_lapack_funcs
+from ._decomp_schur import schur
+from ._decomp_lu import lu
+from ._decomp_qr import qr
+from ._decomp_qz import ordqz
+from ._decomp import _asarray_validated
+from ._special_matrices import block_diag
+
+__all__ = ['solve_sylvester',
+           'solve_continuous_lyapunov', 'solve_discrete_lyapunov',
+           'solve_lyapunov',
+           'solve_continuous_are', 'solve_discrete_are']
+
+
+def solve_sylvester(a, b, q):
+    """
+    Computes a solution (X) to the Sylvester equation :math:`AX + XB = Q`.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Leading matrix of the Sylvester equation
+    b : (N, N) array_like
+        Trailing matrix of the Sylvester equation
+    q : (M, N) array_like
+        Right-hand side
+
+    Returns
+    -------
+    x : (M, N) ndarray
+        The solution to the Sylvester equation.
+
+    Raises
+    ------
+    LinAlgError
+        If solution was not found
+
+    Notes
+    -----
+    Computes a solution to the Sylvester matrix equation via the Bartels-
+    Stewart algorithm. The A and B matrices first undergo Schur
+    decompositions. The resulting matrices are used to construct an
+    alternative Sylvester equation (``RY + YS^T = F``) where the R and S
+    matrices are in quasi-triangular form (or, when R, S or F are complex,
+    triangular form). The simplified equation is then solved using
+    ``*TRSYL`` from LAPACK directly.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    Given `a`, `b`, and `q` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[-3, -2, 0], [-1, -1, 3], [3, -5, -1]])
+    >>> b = np.array([[1]])
+    >>> q = np.array([[1],[2],[3]])
+    >>> x = linalg.solve_sylvester(a, b, q)
+    >>> x
+    array([[ 0.0625],
+           [-0.5625],
+           [ 0.6875]])
+    >>> np.allclose(a.dot(x) + x.dot(b), q)
+    True
+
+    """
+    # Accommodate empty a
+    if a.size == 0 or b.size == 0:
+        tdict = {'s': np.float32, 'd': np.float64,
+                 'c': np.complex64, 'z': np.complex128}
+        func, = get_lapack_funcs(('trsyl',), arrays=(a, b, q))
+        return np.empty(q.shape, dtype=tdict[func.typecode])
+
+    # Compute the Schur decomposition form of a
+    r, u = schur(a, output='real')
+
+    # Compute the Schur decomposition of b
+    s, v = schur(b.conj().transpose(), output='real')
+
+    # Construct f = u'*q*v
+    f = np.dot(np.dot(u.conj().transpose(), q), v)
+
+    # Call the Sylvester equation solver
+    trsyl, = get_lapack_funcs(('trsyl',), (r, s, f))
+    if trsyl is None:
+        raise RuntimeError('LAPACK implementation does not contain a proper '
+                           'Sylvester equation solver (TRSYL)')
+    y, scale, info = trsyl(r, s, f, tranb='C')
+
+    y = scale*y
+
+    if info < 0:
+        raise LinAlgError("Illegal value encountered in "
+                          "the %d term" % (-info,))
+
+    return np.dot(np.dot(u, y), v.conj().transpose())
+
+
+def solve_continuous_lyapunov(a, q):
+    """
+    Solves the continuous Lyapunov equation :math:`AX + XA^H = Q`.
+
+    Uses the Bartels-Stewart algorithm to find :math:`X`.
+
+    Parameters
+    ----------
+    a : array_like
+        A square matrix
+
+    q : array_like
+        Right-hand side square matrix
+
+    Returns
+    -------
+    x : ndarray
+        Solution to the continuous Lyapunov equation
+
+    See Also
+    --------
+    solve_discrete_lyapunov : computes the solution to the discrete-time
+        Lyapunov equation
+    solve_sylvester : computes the solution to the Sylvester equation
+
+    Notes
+    -----
+    The continuous Lyapunov equation is a special form of the Sylvester
+    equation, hence this solver relies on LAPACK routine ?TRSYL.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    Given `a` and `q` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[-3, -2, 0], [-1, -1, 0], [0, -5, -1]])
+    >>> b = np.array([2, 4, -1])
+    >>> q = np.eye(3)
+    >>> x = linalg.solve_continuous_lyapunov(a, q)
+    >>> x
+    array([[ -0.75  ,   0.875 ,  -3.75  ],
+           [  0.875 ,  -1.375 ,   5.3125],
+           [ -3.75  ,   5.3125, -27.0625]])
+    >>> np.allclose(a.dot(x) + x.dot(a.T), q)
+    True
+    """
+
+    a = np.atleast_2d(_asarray_validated(a, check_finite=True))
+    q = np.atleast_2d(_asarray_validated(q, check_finite=True))
+
+    r_or_c = float
+
+    for ind, _ in enumerate((a, q)):
+        if np.iscomplexobj(_):
+            r_or_c = complex
+
+        if not np.equal(*_.shape):
+            raise ValueError(f"Matrix {'aq'[ind]} should be square.")
+
+    # Shape consistency check
+    if a.shape != q.shape:
+        raise ValueError("Matrix a and q should have the same shape.")
+
+    # Accommodate empty array
+    if a.size == 0:
+        tdict = {'s': np.float32, 'd': np.float64,
+                 'c': np.complex64, 'z': np.complex128}
+        func, = get_lapack_funcs(('trsyl',), arrays=(a, q))
+        return np.empty(a.shape, dtype=tdict[func.typecode])
+
+    # Compute the Schur decomposition form of a
+    r, u = schur(a, output='real')
+
+    # Construct f = u'*q*u
+    f = u.conj().T.dot(q.dot(u))
+
+    # Call the Sylvester equation solver
+    trsyl = get_lapack_funcs('trsyl', (r, f))
+
+    dtype_string = 'T' if r_or_c is float else 'C'
+    y, scale, info = trsyl(r, r, f, tranb=dtype_string)
+
+    if info < 0:
+        raise ValueError('?TRSYL exited with the internal error '
+                         f'"illegal value in argument number {-info}.". See '
+                         'LAPACK documentation for the ?TRSYL error codes.')
+    elif info == 1:
+        warnings.warn('Input "a" has an eigenvalue pair whose sum is '
+                      'very close to or exactly zero. The solution is '
+                      'obtained via perturbing the coefficients.',
+                      RuntimeWarning, stacklevel=2)
+    y *= scale
+
+    return u.dot(y).dot(u.conj().T)
+
+
+# For backwards compatibility, keep the old name
+solve_lyapunov = solve_continuous_lyapunov
+
+
+def _solve_discrete_lyapunov_direct(a, q):
+    """
+    Solves the discrete Lyapunov equation directly.
+
+    This function is called by the `solve_discrete_lyapunov` function with
+    `method=direct`. It is not supposed to be called directly.
+    """
+
+    lhs = np.kron(a, a.conj())
+    lhs = np.eye(lhs.shape[0]) - lhs
+    x = solve(lhs, q.flatten())
+
+    return np.reshape(x, q.shape)
+
+
+def _solve_discrete_lyapunov_bilinear(a, q):
+    """
+    Solves the discrete Lyapunov equation using a bilinear transformation.
+
+    This function is called by the `solve_discrete_lyapunov` function with
+    `method=bilinear`. It is not supposed to be called directly.
+    """
+    eye = np.eye(a.shape[0])
+    aH = a.conj().transpose()
+    aHI_inv = inv(aH + eye)
+    b = np.dot(aH - eye, aHI_inv)
+    c = 2*np.dot(np.dot(inv(a + eye), q), aHI_inv)
+    return solve_lyapunov(b.conj().transpose(), -c)
+
+
+def solve_discrete_lyapunov(a, q, method=None):
+    """
+    Solves the discrete Lyapunov equation :math:`AXA^H - X + Q = 0`.
+
+    Parameters
+    ----------
+    a, q : (M, M) array_like
+        Square matrices corresponding to A and Q in the equation
+        above respectively. Must have the same shape.
+
+    method : {'direct', 'bilinear'}, optional
+        Type of solver.
+
+        If not given, chosen to be ``direct`` if ``M`` is less than 10 and
+        ``bilinear`` otherwise.
+
+    Returns
+    -------
+    x : ndarray
+        Solution to the discrete Lyapunov equation
+
+    See Also
+    --------
+    solve_continuous_lyapunov : computes the solution to the continuous-time
+        Lyapunov equation
+
+    Notes
+    -----
+    This section describes the available solvers that can be selected by the
+    'method' parameter. The default method is *direct* if ``M`` is less than 10
+    and ``bilinear`` otherwise.
+
+    Method *direct* uses a direct analytical solution to the discrete Lyapunov
+    equation. The algorithm is given in, for example, [1]_. However, it requires
+    the linear solution of a system with dimension :math:`M^2` so that
+    performance degrades rapidly for even moderately sized matrices.
+
+    Method *bilinear* uses a bilinear transformation to convert the discrete
+    Lyapunov equation to a continuous Lyapunov equation :math:`(BX+XB'=-C)`
+    where :math:`B=(A-I)(A+I)^{-1}` and
+    :math:`C=2(A' + I)^{-1} Q (A + I)^{-1}`. The continuous equation can be
+    efficiently solved since it is a special case of a Sylvester equation.
+    The transformation algorithm is from Popov (1964) as described in [2]_.
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1] "Lyapunov equation", Wikipedia,
+       https://en.wikipedia.org/wiki/Lyapunov_equation#Discrete_time
+    .. [2] Gajic, Z., and M.T.J. Qureshi. 2008.
+       Lyapunov Matrix Equation in System Stability and Control.
+       Dover Books on Engineering Series. Dover Publications.
+
+    Examples
+    --------
+    Given `a` and `q` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[0.2, 0.5],[0.7, -0.9]])
+    >>> q = np.eye(2)
+    >>> x = linalg.solve_discrete_lyapunov(a, q)
+    >>> x
+    array([[ 0.70872893,  1.43518822],
+           [ 1.43518822, -2.4266315 ]])
+    >>> np.allclose(a.dot(x).dot(a.T)-x, -q)
+    True
+
+    """
+    a = np.asarray(a)
+    q = np.asarray(q)
+    if method is None:
+        # Select automatically based on size of matrices
+        if a.shape[0] >= 10:
+            method = 'bilinear'
+        else:
+            method = 'direct'
+
+    meth = method.lower()
+
+    if meth == 'direct':
+        x = _solve_discrete_lyapunov_direct(a, q)
+    elif meth == 'bilinear':
+        x = _solve_discrete_lyapunov_bilinear(a, q)
+    else:
+        raise ValueError(f'Unknown solver {method}')
+
+    return x
+
+
+def solve_continuous_are(a, b, q, r, e=None, s=None, balanced=True):
+    r"""
+    Solves the continuous-time algebraic Riccati equation (CARE).
+
+    The CARE is defined as
+
+    .. math::
+
+          X A + A^H X - X B R^{-1} B^H X + Q = 0
+
+    The limitations for a solution to exist are :
+
+        * All eigenvalues of :math:`A` on the right half plane, should be
+          controllable.
+
+        * The associated hamiltonian pencil (See Notes), should have
+          eigenvalues sufficiently away from the imaginary axis.
+
+    Moreover, if ``e`` or ``s`` is not precisely ``None``, then the
+    generalized version of CARE
+
+    .. math::
+
+          E^HXA + A^HXE - (E^HXB + S) R^{-1} (B^HXE + S^H) + Q = 0
+
+    is solved. When omitted, ``e`` is assumed to be the identity and ``s``
+    is assumed to be the zero matrix with sizes compatible with ``a`` and
+    ``b``, respectively.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Square matrix
+    b : (M, N) array_like
+        Input
+    q : (M, M) array_like
+        Input
+    r : (N, N) array_like
+        Nonsingular square matrix
+    e : (M, M) array_like, optional
+        Nonsingular square matrix
+    s : (M, N) array_like, optional
+        Input
+    balanced : bool, optional
+        The boolean that indicates whether a balancing step is performed
+        on the data. The default is set to True.
+
+    Returns
+    -------
+    x : (M, M) ndarray
+        Solution to the continuous-time algebraic Riccati equation.
+
+    Raises
+    ------
+    LinAlgError
+        For cases where the stable subspace of the pencil could not be
+        isolated. See Notes section and the references for details.
+
+    See Also
+    --------
+    solve_discrete_are : Solves the discrete-time algebraic Riccati equation
+
+    Notes
+    -----
+    The equation is solved by forming the extended hamiltonian matrix pencil,
+    as described in [1]_, :math:`H - \lambda J` given by the block matrices ::
+
+        [ A    0    B ]             [ E   0    0 ]
+        [-Q  -A^H  -S ] - \lambda * [ 0  E^H   0 ]
+        [ S^H B^H   R ]             [ 0   0    0 ]
+
+    and using a QZ decomposition method.
+
+    In this algorithm, the fail conditions are linked to the symmetry
+    of the product :math:`U_2 U_1^{-1}` and condition number of
+    :math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the
+    eigenvectors spanning the stable subspace with 2-m rows and partitioned
+    into two m-row matrices. See [1]_ and [2]_ for more details.
+
+    In order to improve the QZ decomposition accuracy, the pencil goes
+    through a balancing step where the sum of absolute values of
+    :math:`H` and :math:`J` entries (after removing the diagonal entries of
+    the sum) is balanced following the recipe given in [3]_.
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1]  P. van Dooren , "A Generalized Eigenvalue Approach For Solving
+       Riccati Equations.", SIAM Journal on Scientific and Statistical
+       Computing, Vol.2(2), :doi:`10.1137/0902010`
+
+    .. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati
+       Equations.", Massachusetts Institute of Technology. Laboratory for
+       Information and Decision Systems. LIDS-R ; 859. Available online :
+       http://hdl.handle.net/1721.1/1301
+
+    .. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001,
+       SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993`
+
+    Examples
+    --------
+    Given `a`, `b`, `q`, and `r` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg
+    >>> a = np.array([[4, 3], [-4.5, -3.5]])
+    >>> b = np.array([[1], [-1]])
+    >>> q = np.array([[9, 6], [6, 4.]])
+    >>> r = 1
+    >>> x = linalg.solve_continuous_are(a, b, q, r)
+    >>> x
+    array([[ 21.72792206,  14.48528137],
+           [ 14.48528137,   9.65685425]])
+    >>> np.allclose(a.T.dot(x) + x.dot(a)-x.dot(b).dot(b.T).dot(x), -q)
+    True
+
+    """
+
+    # Validate input arguments
+    a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args(
+                                                     a, b, q, r, e, s, 'care')
+
+    H = np.empty((2*m+n, 2*m+n), dtype=r_or_c)
+    H[:m, :m] = a
+    H[:m, m:2*m] = 0.
+    H[:m, 2*m:] = b
+    H[m:2*m, :m] = -q
+    H[m:2*m, m:2*m] = -a.conj().T
+    H[m:2*m, 2*m:] = 0. if s is None else -s
+    H[2*m:, :m] = 0. if s is None else s.conj().T
+    H[2*m:, m:2*m] = b.conj().T
+    H[2*m:, 2*m:] = r
+
+    if gen_are and e is not None:
+        J = block_diag(e, e.conj().T, np.zeros_like(r, dtype=r_or_c))
+    else:
+        J = block_diag(np.eye(2*m), np.zeros_like(r, dtype=r_or_c))
+
+    if balanced:
+        # xGEBAL does not remove the diagonals before scaling. Also
+        # to avoid destroying the Symplectic structure, we follow Ref.3
+        M = np.abs(H) + np.abs(J)
+        np.fill_diagonal(M, 0.)
+        _, (sca, _) = matrix_balance(M, separate=1, permute=0)
+        # do we need to bother?
+        if not np.allclose(sca, np.ones_like(sca)):
+            # Now impose diag(D,inv(D)) from Benner where D is
+            # square root of s_i/s_(n+i) for i=0,....
+            sca = np.log2(sca)
+            # NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !!
+            s = np.round((sca[m:2*m] - sca[:m])/2)
+            sca = 2 ** np.r_[s, -s, sca[2*m:]]
+            # Elementwise multiplication via broadcasting.
+            elwisescale = sca[:, None] * np.reciprocal(sca)
+            H *= elwisescale
+            J *= elwisescale
+
+    # Deflate the pencil to 2m x 2m ala Ref.1, eq.(55)
+    q, r = qr(H[:, -n:])
+    H = q[:, n:].conj().T.dot(H[:, :2*m])
+    J = q[:2*m, n:].conj().T.dot(J[:2*m, :2*m])
+
+    # Decide on which output type is needed for QZ
+    out_str = 'real' if r_or_c is float else 'complex'
+
+    _, _, _, _, _, u = ordqz(H, J, sort='lhp', overwrite_a=True,
+                             overwrite_b=True, check_finite=False,
+                             output=out_str)
+
+    # Get the relevant parts of the stable subspace basis
+    if e is not None:
+        u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m])))
+    u00 = u[:m, :m]
+    u10 = u[m:, :m]
+
+    # Solve via back-substituion after checking the condition of u00
+    up, ul, uu = lu(u00)
+    if 1/cond(uu) < np.spacing(1.):
+        raise LinAlgError('Failed to find a finite solution.')
+
+    # Exploit the triangular structure
+    x = solve_triangular(ul.conj().T,
+                         solve_triangular(uu.conj().T,
+                                          u10.conj().T,
+                                          lower=True),
+                         unit_diagonal=True,
+                         ).conj().T.dot(up.conj().T)
+    if balanced:
+        x *= sca[:m, None] * sca[:m]
+
+    # Check the deviation from symmetry for lack of success
+    # See proof of Thm.5 item 3 in [2]
+    u_sym = u00.conj().T.dot(u10)
+    n_u_sym = norm(u_sym, 1)
+    u_sym = u_sym - u_sym.conj().T
+    sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym])
+
+    if norm(u_sym, 1) > sym_threshold:
+        raise LinAlgError('The associated Hamiltonian pencil has eigenvalues '
+                          'too close to the imaginary axis')
+
+    return (x + x.conj().T)/2
+
+
+def solve_discrete_are(a, b, q, r, e=None, s=None, balanced=True):
+    r"""
+    Solves the discrete-time algebraic Riccati equation (DARE).
+
+    The DARE is defined as
+
+    .. math::
+
+          A^HXA - X - (A^HXB) (R + B^HXB)^{-1} (B^HXA) + Q = 0
+
+    The limitations for a solution to exist are :
+
+        * All eigenvalues of :math:`A` outside the unit disc, should be
+          controllable.
+
+        * The associated symplectic pencil (See Notes), should have
+          eigenvalues sufficiently away from the unit circle.
+
+    Moreover, if ``e`` and ``s`` are not both precisely ``None``, then the
+    generalized version of DARE
+
+    .. math::
+
+          A^HXA - E^HXE - (A^HXB+S) (R+B^HXB)^{-1} (B^HXA+S^H) + Q = 0
+
+    is solved. When omitted, ``e`` is assumed to be the identity and ``s``
+    is assumed to be the zero matrix.
+
+    Parameters
+    ----------
+    a : (M, M) array_like
+        Square matrix
+    b : (M, N) array_like
+        Input
+    q : (M, M) array_like
+        Input
+    r : (N, N) array_like
+        Square matrix
+    e : (M, M) array_like, optional
+        Nonsingular square matrix
+    s : (M, N) array_like, optional
+        Input
+    balanced : bool
+        The boolean that indicates whether a balancing step is performed
+        on the data. The default is set to True.
+
+    Returns
+    -------
+    x : (M, M) ndarray
+        Solution to the discrete algebraic Riccati equation.
+
+    Raises
+    ------
+    LinAlgError
+        For cases where the stable subspace of the pencil could not be
+        isolated. See Notes section and the references for details.
+
+    See Also
+    --------
+    solve_continuous_are : Solves the continuous algebraic Riccati equation
+
+    Notes
+    -----
+    The equation is solved by forming the extended symplectic matrix pencil,
+    as described in [1]_, :math:`H - \lambda J` given by the block matrices ::
+
+           [  A   0   B ]             [ E   0   B ]
+           [ -Q  E^H -S ] - \lambda * [ 0  A^H  0 ]
+           [ S^H  0   R ]             [ 0 -B^H  0 ]
+
+    and using a QZ decomposition method.
+
+    In this algorithm, the fail conditions are linked to the symmetry
+    of the product :math:`U_2 U_1^{-1}` and condition number of
+    :math:`U_1`. Here, :math:`U` is the 2m-by-m matrix that holds the
+    eigenvectors spanning the stable subspace with 2-m rows and partitioned
+    into two m-row matrices. See [1]_ and [2]_ for more details.
+
+    In order to improve the QZ decomposition accuracy, the pencil goes
+    through a balancing step where the sum of absolute values of
+    :math:`H` and :math:`J` rows/cols (after removing the diagonal entries)
+    is balanced following the recipe given in [3]_. If the data has small
+    numerical noise, balancing may amplify their effects and some clean up
+    is required.
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1]  P. van Dooren , "A Generalized Eigenvalue Approach For Solving
+       Riccati Equations.", SIAM Journal on Scientific and Statistical
+       Computing, Vol.2(2), :doi:`10.1137/0902010`
+
+    .. [2] A.J. Laub, "A Schur Method for Solving Algebraic Riccati
+       Equations.", Massachusetts Institute of Technology. Laboratory for
+       Information and Decision Systems. LIDS-R ; 859. Available online :
+       http://hdl.handle.net/1721.1/1301
+
+    .. [3] P. Benner, "Symplectic Balancing of Hamiltonian Matrices", 2001,
+       SIAM J. Sci. Comput., 2001, Vol.22(5), :doi:`10.1137/S1064827500367993`
+
+    Examples
+    --------
+    Given `a`, `b`, `q`, and `r` solve for `x`:
+
+    >>> import numpy as np
+    >>> from scipy import linalg as la
+    >>> a = np.array([[0, 1], [0, -1]])
+    >>> b = np.array([[1, 0], [2, 1]])
+    >>> q = np.array([[-4, -4], [-4, 7]])
+    >>> r = np.array([[9, 3], [3, 1]])
+    >>> x = la.solve_discrete_are(a, b, q, r)
+    >>> x
+    array([[-4., -4.],
+           [-4.,  7.]])
+    >>> R = la.solve(r + b.T.dot(x).dot(b), b.T.dot(x).dot(a))
+    >>> np.allclose(a.T.dot(x).dot(a) - x - a.T.dot(x).dot(b).dot(R), -q)
+    True
+
+    """
+
+    # Validate input arguments
+    a, b, q, r, e, s, m, n, r_or_c, gen_are = _are_validate_args(
+                                                     a, b, q, r, e, s, 'dare')
+
+    # Form the matrix pencil
+    H = np.zeros((2*m+n, 2*m+n), dtype=r_or_c)
+    H[:m, :m] = a
+    H[:m, 2*m:] = b
+    H[m:2*m, :m] = -q
+    H[m:2*m, m:2*m] = np.eye(m) if e is None else e.conj().T
+    H[m:2*m, 2*m:] = 0. if s is None else -s
+    H[2*m:, :m] = 0. if s is None else s.conj().T
+    H[2*m:, 2*m:] = r
+
+    J = np.zeros_like(H, dtype=r_or_c)
+    J[:m, :m] = np.eye(m) if e is None else e
+    J[m:2*m, m:2*m] = a.conj().T
+    J[2*m:, m:2*m] = -b.conj().T
+
+    if balanced:
+        # xGEBAL does not remove the diagonals before scaling. Also
+        # to avoid destroying the Symplectic structure, we follow Ref.3
+        M = np.abs(H) + np.abs(J)
+        np.fill_diagonal(M, 0.)
+        _, (sca, _) = matrix_balance(M, separate=1, permute=0)
+        # do we need to bother?
+        if not np.allclose(sca, np.ones_like(sca)):
+            # Now impose diag(D,inv(D)) from Benner where D is
+            # square root of s_i/s_(n+i) for i=0,....
+            sca = np.log2(sca)
+            # NOTE: Py3 uses "Bankers Rounding: round to the nearest even" !!
+            s = np.round((sca[m:2*m] - sca[:m])/2)
+            sca = 2 ** np.r_[s, -s, sca[2*m:]]
+            # Elementwise multiplication via broadcasting.
+            elwisescale = sca[:, None] * np.reciprocal(sca)
+            H *= elwisescale
+            J *= elwisescale
+
+    # Deflate the pencil by the R column ala Ref.1
+    q_of_qr, _ = qr(H[:, -n:])
+    H = q_of_qr[:, n:].conj().T.dot(H[:, :2*m])
+    J = q_of_qr[:, n:].conj().T.dot(J[:, :2*m])
+
+    # Decide on which output type is needed for QZ
+    out_str = 'real' if r_or_c is float else 'complex'
+
+    _, _, _, _, _, u = ordqz(H, J, sort='iuc',
+                             overwrite_a=True,
+                             overwrite_b=True,
+                             check_finite=False,
+                             output=out_str)
+
+    # Get the relevant parts of the stable subspace basis
+    if e is not None:
+        u, _ = qr(np.vstack((e.dot(u[:m, :m]), u[m:, :m])))
+    u00 = u[:m, :m]
+    u10 = u[m:, :m]
+
+    # Solve via back-substituion after checking the condition of u00
+    up, ul, uu = lu(u00)
+
+    if 1/cond(uu) < np.spacing(1.):
+        raise LinAlgError('Failed to find a finite solution.')
+
+    # Exploit the triangular structure
+    x = solve_triangular(ul.conj().T,
+                         solve_triangular(uu.conj().T,
+                                          u10.conj().T,
+                                          lower=True),
+                         unit_diagonal=True,
+                         ).conj().T.dot(up.conj().T)
+    if balanced:
+        x *= sca[:m, None] * sca[:m]
+
+    # Check the deviation from symmetry for lack of success
+    # See proof of Thm.5 item 3 in [2]
+    u_sym = u00.conj().T.dot(u10)
+    n_u_sym = norm(u_sym, 1)
+    u_sym = u_sym - u_sym.conj().T
+    sym_threshold = np.max([np.spacing(1000.), 0.1*n_u_sym])
+
+    if norm(u_sym, 1) > sym_threshold:
+        raise LinAlgError('The associated symplectic pencil has eigenvalues '
+                          'too close to the unit circle')
+
+    return (x + x.conj().T)/2
+
+
+def _are_validate_args(a, b, q, r, e, s, eq_type='care'):
+    """
+    A helper function to validate the arguments supplied to the
+    Riccati equation solvers. Any discrepancy found in the input
+    matrices leads to a ``ValueError`` exception.
+
+    Essentially, it performs:
+
+        - a check whether the input is free of NaN and Infs
+        - a pass for the data through ``numpy.atleast_2d()``
+        - squareness check of the relevant arrays
+        - shape consistency check of the arrays
+        - singularity check of the relevant arrays
+        - symmetricity check of the relevant matrices
+        - a check whether the regular or the generalized version is asked.
+
+    This function is used by ``solve_continuous_are`` and
+    ``solve_discrete_are``.
+
+    Parameters
+    ----------
+    a, b, q, r, e, s : array_like
+        Input data
+    eq_type : str
+        Accepted arguments are 'care' and 'dare'.
+
+    Returns
+    -------
+    a, b, q, r, e, s : ndarray
+        Regularized input data
+    m, n : int
+        shape of the problem
+    r_or_c : type
+        Data type of the problem, returns float or complex
+    gen_or_not : bool
+        Type of the equation, True for generalized and False for regular ARE.
+
+    """
+
+    if eq_type.lower() not in ("dare", "care"):
+        raise ValueError("Equation type unknown. "
+                         "Only 'care' and 'dare' is understood")
+
+    a = np.atleast_2d(_asarray_validated(a, check_finite=True))
+    b = np.atleast_2d(_asarray_validated(b, check_finite=True))
+    q = np.atleast_2d(_asarray_validated(q, check_finite=True))
+    r = np.atleast_2d(_asarray_validated(r, check_finite=True))
+
+    # Get the correct data types otherwise NumPy complains
+    # about pushing complex numbers into real arrays.
+    r_or_c = complex if np.iscomplexobj(b) else float
+
+    for ind, mat in enumerate((a, q, r)):
+        if np.iscomplexobj(mat):
+            r_or_c = complex
+
+        if not np.equal(*mat.shape):
+            raise ValueError(f"Matrix {'aqr'[ind]} should be square.")
+
+    # Shape consistency checks
+    m, n = b.shape
+    if m != a.shape[0]:
+        raise ValueError("Matrix a and b should have the same number of rows.")
+    if m != q.shape[0]:
+        raise ValueError("Matrix a and q should have the same shape.")
+    if n != r.shape[0]:
+        raise ValueError("Matrix b and r should have the same number of cols.")
+
+    # Check if the data matrices q, r are (sufficiently) hermitian
+    for ind, mat in enumerate((q, r)):
+        if norm(mat - mat.conj().T, 1) > np.spacing(norm(mat, 1))*100:
+            raise ValueError(f"Matrix {'qr'[ind]} should be symmetric/hermitian.")
+
+    # Continuous time ARE should have a nonsingular r matrix.
+    if eq_type == 'care':
+        min_sv = svd(r, compute_uv=False)[-1]
+        if min_sv == 0. or min_sv < np.spacing(1.)*norm(r, 1):
+            raise ValueError('Matrix r is numerically singular.')
+
+    # Check if the generalized case is required with omitted arguments
+    # perform late shape checking etc.
+    generalized_case = e is not None or s is not None
+
+    if generalized_case:
+        if e is not None:
+            e = np.atleast_2d(_asarray_validated(e, check_finite=True))
+            if not np.equal(*e.shape):
+                raise ValueError("Matrix e should be square.")
+            if m != e.shape[0]:
+                raise ValueError("Matrix a and e should have the same shape.")
+            # numpy.linalg.cond doesn't check for exact zeros and
+            # emits a runtime warning. Hence the following manual check.
+            min_sv = svd(e, compute_uv=False)[-1]
+            if min_sv == 0. or min_sv < np.spacing(1.) * norm(e, 1):
+                raise ValueError('Matrix e is numerically singular.')
+            if np.iscomplexobj(e):
+                r_or_c = complex
+        if s is not None:
+            s = np.atleast_2d(_asarray_validated(s, check_finite=True))
+            if s.shape != b.shape:
+                raise ValueError("Matrix b and s should have the same shape.")
+            if np.iscomplexobj(s):
+                r_or_c = complex
+
+    return a, b, q, r, e, s, m, n, r_or_c, generalized_case
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..7dca572f2d5a12a27ccb468425f03c75e86d5da7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_special_matrices.py
@@ -0,0 +1,1332 @@
+import math
+import warnings
+
+import numpy as np
+from numpy.lib.stride_tricks import as_strided
+
+
+__all__ = ['toeplitz', 'circulant', 'hankel',
+           'hadamard', 'leslie', 'kron', 'block_diag', 'companion',
+           'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft',
+           'fiedler', 'fiedler_companion', 'convolution_matrix']
+
+
+# -----------------------------------------------------------------------------
+#  matrix construction functions
+# -----------------------------------------------------------------------------
+
+
+def toeplitz(c, r=None):
+    r"""
+    Construct a Toeplitz matrix.
+
+    The Toeplitz matrix has constant diagonals, with c as its first column
+    and r as its first row. If r is not given, ``r == conjugate(c)`` is
+    assumed.
+
+    Parameters
+    ----------
+    c : array_like
+        First column of the matrix.
+    r : array_like, optional
+        First row of the matrix. If None, ``r = conjugate(c)`` is assumed;
+        in this case, if c[0] is real, the result is a Hermitian matrix.
+        r[0] is ignored; the first row of the returned matrix is
+        ``[c[0], r[1:]]``.
+
+        .. warning::
+
+            Beginning in SciPy 1.17, multidimensional input will be treated as a batch,
+            not ``ravel``\ ed. To preserve the existing behavior, ``ravel`` arguments
+            before passing them to `toeplitz`.
+
+    Returns
+    -------
+    A : (len(c), len(r)) ndarray
+        The Toeplitz matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
+
+    See Also
+    --------
+    circulant : circulant matrix
+    hankel : Hankel matrix
+    solve_toeplitz : Solve a Toeplitz system.
+
+    Notes
+    -----
+    The behavior when `c` or `r` is a scalar, or when `c` is complex and
+    `r` is None, was changed in version 0.8.0. The behavior in previous
+    versions was undocumented and is no longer supported.
+
+    Examples
+    --------
+    >>> from scipy.linalg import toeplitz
+    >>> toeplitz([1,2,3], [1,4,5,6])
+    array([[1, 4, 5, 6],
+           [2, 1, 4, 5],
+           [3, 2, 1, 4]])
+    >>> toeplitz([1.0, 2+3j, 4-1j])
+    array([[ 1.+0.j,  2.-3.j,  4.+1.j],
+           [ 2.+3.j,  1.+0.j,  2.-3.j],
+           [ 4.-1.j,  2.+3.j,  1.+0.j]])
+
+    """
+    c = np.asarray(c)
+    if r is None:
+        r = c.conjugate()
+    else:
+        r = np.asarray(r)
+
+    if c.ndim > 1 or r.ndim > 1:
+        msg = ("Beginning in SciPy 1.17, multidimensional input will be treated as a "
+               "batch, not `ravel`ed. To preserve the existing behavior and silence "
+               "this warning, `ravel` arguments before passing them to `toeplitz`.")
+        warnings.warn(msg, FutureWarning, stacklevel=2)
+
+    c, r = c.ravel(), r.ravel()
+    # Form a 1-D array containing a reversed c followed by r[1:] that could be
+    # strided to give us toeplitz matrix.
+    vals = np.concatenate((c[::-1], r[1:]))
+    out_shp = len(c), len(r)
+    n = vals.strides[0]
+    return as_strided(vals[len(c)-1:], shape=out_shp, strides=(-n, n)).copy()
+
+
+def circulant(c):
+    """
+    Construct a circulant matrix.
+
+    Parameters
+    ----------
+    c : (..., N,)  array_like
+        The first column(s) of the matrix. Multidimensional arrays are treated as a
+        batch: each slice along the last axis is the first column of an output matrix.
+
+    Returns
+    -------
+    A : (..., N, N) ndarray
+        A circulant matrix whose first column is given by `c`.  For batch input, each
+        slice of shape ``(N, N)`` along the last two dimensions of the output
+        corresponds with a slice of shape ``(N,)`` along the last dimension of the
+        input.
+
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+    hankel : Hankel matrix
+    solve_circulant : Solve a circulant system.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import circulant
+    >>> circulant([1, 2, 3])
+    array([[1, 3, 2],
+           [2, 1, 3],
+           [3, 2, 1]])
+
+    >>> circulant([[1, 2, 3], [4, 5, 6]])
+    array([[[1, 3, 2],
+            [2, 1, 3],
+            [3, 2, 1]],
+           [[4, 6, 5],
+            [5, 4, 6],
+            [6, 5, 4]]])
+    """
+    c = np.atleast_1d(c)
+    batch_shape, N = c.shape[:-1], c.shape[-1]
+    # Need to use `prod(batch_shape)` instead of `-1` in case array has zero size
+    c = c.reshape(math.prod(batch_shape), N) if batch_shape else c
+    # Form an extended array that could be strided to give circulant version
+    c_ext = np.concatenate((c[..., ::-1], c[..., :0:-1]), axis=-1).ravel()
+    L = c.shape[-1]
+    n = c_ext.strides[-1]
+    if c.ndim == 1:
+        A = as_strided(c_ext[L-1:], shape=(L, L), strides=(-n, n))
+    else:
+        m = c.shape[0]
+        A = as_strided(c_ext[L-1:], shape=(m, L, L), strides=(n*(2*L-1), -n, n))
+    return A.reshape(batch_shape + (N, N)).copy()
+
+
+def hankel(c, r=None):
+    """
+    Construct a Hankel matrix.
+
+    The Hankel matrix has constant anti-diagonals, with `c` as its
+    first column and `r` as its last row. If the first element of `r`
+    differs from the last element of `c`, the first element of `r` is
+    replaced by the last element of `c` to ensure that anti-diagonals
+    remain constant. If `r` is not given, then `r = zeros_like(c)` is
+    assumed.
+
+    Parameters
+    ----------
+    c : array_like
+        First column of the matrix. Whatever the actual shape of `c`, it
+        will be converted to a 1-D array.
+    r : array_like, optional
+        Last row of the matrix. If None, ``r = zeros_like(c)`` is assumed.
+        r[0] is ignored; the last row of the returned matrix is
+        ``[c[-1], r[1:]]``. Whatever the actual shape of `r`, it will be
+        converted to a 1-D array.
+
+    Returns
+    -------
+    A : (len(c), len(r)) ndarray
+        The Hankel matrix. Dtype is the same as ``(c[0] + r[0]).dtype``.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+    circulant : circulant matrix
+
+    Examples
+    --------
+    >>> from scipy.linalg import hankel
+    >>> hankel([1, 17, 99])
+    array([[ 1, 17, 99],
+           [17, 99,  0],
+           [99,  0,  0]])
+    >>> hankel([1,2,3,4], [4,7,7,8,9])
+    array([[1, 2, 3, 4, 7],
+           [2, 3, 4, 7, 7],
+           [3, 4, 7, 7, 8],
+           [4, 7, 7, 8, 9]])
+
+    """
+    c = np.asarray(c).ravel()
+    if r is None:
+        r = np.zeros_like(c)
+    else:
+        r = np.asarray(r).ravel()
+    # Form a 1-D array of values to be used in the matrix, containing `c`
+    # followed by r[1:].
+    vals = np.concatenate((c, r[1:]))
+    # Stride on concatenated array to get hankel matrix
+    out_shp = len(c), len(r)
+    n = vals.strides[0]
+    return as_strided(vals, shape=out_shp, strides=(n, n)).copy()
+
+
+def hadamard(n, dtype=int):
+    """
+    Construct an Hadamard matrix.
+
+    Constructs an n-by-n Hadamard matrix, using Sylvester's
+    construction. `n` must be a power of 2.
+
+    Parameters
+    ----------
+    n : int
+        The order of the matrix. `n` must be a power of 2.
+    dtype : dtype, optional
+        The data type of the array to be constructed.
+
+    Returns
+    -------
+    H : (n, n) ndarray
+        The Hadamard matrix.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import hadamard
+    >>> hadamard(2, dtype=complex)
+    array([[ 1.+0.j,  1.+0.j],
+           [ 1.+0.j, -1.-0.j]])
+    >>> hadamard(4)
+    array([[ 1,  1,  1,  1],
+           [ 1, -1,  1, -1],
+           [ 1,  1, -1, -1],
+           [ 1, -1, -1,  1]])
+
+    """
+
+    # This function is a slightly modified version of the
+    # function contributed by Ivo in ticket #675.
+
+    if n < 1:
+        lg2 = 0
+    else:
+        lg2 = int(math.log(n, 2))
+    if 2 ** lg2 != n:
+        raise ValueError("n must be an positive integer, and n must be "
+                         "a power of 2")
+
+    H = np.array([[1]], dtype=dtype)
+
+    # Sylvester's construction
+    for i in range(0, lg2):
+        H = np.vstack((np.hstack((H, H)), np.hstack((H, -H))))
+
+    return H
+
+
+def leslie(f, s):
+    """
+    Create a Leslie matrix.
+
+    Given the length n array of fecundity coefficients `f` and the length
+    n-1 array of survival coefficients `s`, return the associated Leslie
+    matrix.
+
+    Parameters
+    ----------
+    f : (..., N,) array_like
+        The "fecundity" coefficients.
+    s : (..., N-1,) array_like
+        The "survival" coefficients. The length of each slice of `s` (along the last
+        axis) must be one less than the length of `f`, and it must be at least 1.
+
+    Returns
+    -------
+    L : (..., N, N) ndarray
+        The array is zero except for the first row,
+        which is `f`, and the first sub-diagonal, which is `s`.
+        For 1-D input, the data-type of the array will be the data-type of
+        ``f[0]+s[0]``.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    The Leslie matrix is used to model discrete-time, age-structured
+    population growth [1]_ [2]_. In a population with `n` age classes, two sets
+    of parameters define a Leslie matrix: the `n` "fecundity coefficients",
+    which give the number of offspring per-capita produced by each age
+    class, and the `n` - 1 "survival coefficients", which give the
+    per-capita survival rate of each age class.
+
+    N-dimensional input are treated as a batches of coefficient arrays: each
+    slice along the last axis of the input arrays is a 1-D coefficient array,
+    and each slice along the last two dimensions of the output is the
+    corresponding Leslie matrix.
+
+    References
+    ----------
+    .. [1] P. H. Leslie, On the use of matrices in certain population
+           mathematics, Biometrika, Vol. 33, No. 3, 183--212 (Nov. 1945)
+    .. [2] P. H. Leslie, Some further notes on the use of matrices in
+           population mathematics, Biometrika, Vol. 35, No. 3/4, 213--245
+           (Dec. 1948)
+
+    Examples
+    --------
+    >>> from scipy.linalg import leslie
+    >>> leslie([0.1, 2.0, 1.0, 0.1], [0.2, 0.8, 0.7])
+    array([[ 0.1,  2. ,  1. ,  0.1],
+           [ 0.2,  0. ,  0. ,  0. ],
+           [ 0. ,  0.8,  0. ,  0. ],
+           [ 0. ,  0. ,  0.7,  0. ]])
+
+    """
+    f = np.atleast_1d(f)
+    s = np.atleast_1d(s)
+
+    if f.shape[-1] != s.shape[-1] + 1:
+        raise ValueError("Incorrect lengths for f and s. The length of s along "
+                         "the last axis must be one less than the length of f.")
+    if s.shape[-1] == 0:
+        raise ValueError("The length of s must be at least 1.")
+
+    n = f.shape[-1]
+
+    if f.ndim > 1 or s.ndim > 1:
+        from scipy.stats._resampling import _vectorize_statistic
+        _leslie_nd = _vectorize_statistic(leslie)
+        return np.moveaxis(_leslie_nd(f, s, axis=-1), [0, 1], [-2, -1])
+
+    tmp = f[0] + s[0]
+    a = np.zeros((n, n), dtype=tmp.dtype)
+    a[0] = f
+    a[list(range(1, n)), list(range(0, n - 1))] = s
+    return a
+
+
+def kron(a, b):
+    """
+    Kronecker product.
+
+    .. deprecated:: 1.15.0
+        `kron` has been deprecated in favour of `numpy.kron` and will be
+        removed in SciPy 1.17.0.
+
+    The result is the block matrix::
+
+        a[0,0]*b    a[0,1]*b  ... a[0,-1]*b
+        a[1,0]*b    a[1,1]*b  ... a[1,-1]*b
+        ...
+        a[-1,0]*b   a[-1,1]*b ... a[-1,-1]*b
+
+    Parameters
+    ----------
+    a : (M, N) ndarray
+        Input array
+    b : (P, Q) ndarray
+        Input array
+
+    Returns
+    -------
+    A : (M*P, N*Q) ndarray
+        Kronecker product of `a` and `b`.
+
+    Examples
+    --------
+    >>> from numpy import array
+    >>> from scipy.linalg import kron
+    >>> kron(array([[1,2],[3,4]]), array([[1,1,1]]))
+    array([[1, 1, 1, 2, 2, 2],
+           [3, 3, 3, 4, 4, 4]])
+
+    """
+    msg = ("`kron` has been deprecated in favour of `numpy.kron` in SciPy"
+           " 1.15.0 and will be removed in SciPy 1.17.0.")
+    warnings.warn(msg, DeprecationWarning, stacklevel=2)
+    # accommodate empty arrays
+    if a.size == 0 or b.size == 0:
+        m = a.shape[0] * b.shape[0]
+        n = a.shape[1] * b.shape[1]
+        return np.empty_like(a, shape=(m, n))
+
+    if not a.flags['CONTIGUOUS']:
+        a = np.reshape(a, a.shape)
+    if not b.flags['CONTIGUOUS']:
+        b = np.reshape(b, b.shape)
+    o = np.outer(a, b)
+    o = o.reshape(a.shape + b.shape)
+    return np.concatenate(np.concatenate(o, axis=1), axis=1)
+
+
+def block_diag(*arrs):
+    """
+    Create a block diagonal matrix from provided arrays.
+
+    Given the inputs `A`, `B` and `C`, the output will have these
+    arrays arranged on the diagonal::
+
+        [[A, 0, 0],
+         [0, B, 0],
+         [0, 0, C]]
+
+    Parameters
+    ----------
+    A, B, C, ... : array_like, up to 2-D
+        Input arrays.  A 1-D array or array_like sequence of length `n` is
+        treated as a 2-D array with shape ``(1,n)``.
+
+    Returns
+    -------
+    D : ndarray
+        Array with `A`, `B`, `C`, ... on the diagonal. `D` has the
+        same dtype as `A`.
+
+    Notes
+    -----
+    If all the input arrays are square, the output is known as a
+    block diagonal matrix.
+
+    Empty sequences (i.e., array-likes of zero size) will not be ignored.
+    Noteworthy, both [] and [[]] are treated as matrices with shape ``(1,0)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import block_diag
+    >>> A = [[1, 0],
+    ...      [0, 1]]
+    >>> B = [[3, 4, 5],
+    ...      [6, 7, 8]]
+    >>> C = [[7]]
+    >>> P = np.zeros((2, 0), dtype='int32')
+    >>> block_diag(A, B, C)
+    array([[1, 0, 0, 0, 0, 0],
+           [0, 1, 0, 0, 0, 0],
+           [0, 0, 3, 4, 5, 0],
+           [0, 0, 6, 7, 8, 0],
+           [0, 0, 0, 0, 0, 7]])
+    >>> block_diag(A, P, B, C)
+    array([[1, 0, 0, 0, 0, 0],
+           [0, 1, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 3, 4, 5, 0],
+           [0, 0, 6, 7, 8, 0],
+           [0, 0, 0, 0, 0, 7]])
+    >>> block_diag(1.0, [2, 3], [[4, 5], [6, 7]])
+    array([[ 1.,  0.,  0.,  0.,  0.],
+           [ 0.,  2.,  3.,  0.,  0.],
+           [ 0.,  0.,  0.,  4.,  5.],
+           [ 0.,  0.,  0.,  6.,  7.]])
+
+    """
+    if arrs == ():
+        arrs = ([],)
+    arrs = [np.atleast_2d(a) for a in arrs]
+
+    bad_args = [k for k in range(len(arrs)) if arrs[k].ndim > 2]
+    if bad_args:
+        raise ValueError("arguments in the following positions "
+                         f"have dimension greater than 2: {bad_args}")
+
+    shapes = np.array([a.shape for a in arrs])
+    out_dtype = np.result_type(*[arr.dtype for arr in arrs])
+    out = np.zeros(np.sum(shapes, axis=0), dtype=out_dtype)
+
+    r, c = 0, 0
+    for i, (rr, cc) in enumerate(shapes):
+        out[r:r + rr, c:c + cc] = arrs[i]
+        r += rr
+        c += cc
+    return out
+
+
+def companion(a):
+    """
+    Create a companion matrix.
+
+    Create the companion matrix [1]_ associated with the polynomial whose
+    coefficients are given in `a`.
+
+    Parameters
+    ----------
+    a : (..., N) array_like
+        1-D array of polynomial coefficients. The length of `a` must be
+        at least two, and ``a[0]`` must not be zero.
+        M-dimensional arrays are treated as a batch: each slice along the last
+        axis is a 1-D array of polynomial coefficients.
+
+    Returns
+    -------
+    c : (..., N-1, N-1) ndarray
+        For 1-D input, the first row of `c` is ``-a[1:]/a[0]``, and the first
+        sub-diagonal is all ones.  The data-type of the array is the same
+        as the data-type of ``1.0*a[0]``.
+        For batch input, each slice of shape ``(N-1, N-1)`` along the last two
+        dimensions of the output corresponds with a slice of shape ``(N,)``
+        along the last dimension of the input.
+
+    Raises
+    ------
+    ValueError
+        If any of the following are true: a) ``a.shape[-1] < 2``; b) ``a[..., 0] == 0``.
+
+    Notes
+    -----
+    .. versionadded:: 0.8.0
+
+    References
+    ----------
+    .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*.  Cambridge, UK:
+        Cambridge University Press, 1999, pp. 146-7.
+
+    Examples
+    --------
+    >>> from scipy.linalg import companion
+    >>> companion([1, -10, 31, -30])
+    array([[ 10., -31.,  30.],
+           [  1.,   0.,   0.],
+           [  0.,   1.,   0.]])
+
+    """
+    a = np.atleast_1d(a)
+    n = a.shape[-1]
+
+    if n < 2:
+        raise ValueError("The length of `a` along the last axis must be at least 2.")
+
+    if np.any(a[..., 0] == 0):
+        raise ValueError("The first coefficient(s) of `a` (i.e. elements "
+                         "of `a[..., 0]`) must not be zero.")
+
+    first_row = -a[..., 1:] / (1.0 * a[..., 0:1])
+    c = np.zeros(a.shape[:-1] + (n - 1, n - 1), dtype=first_row.dtype)
+    c[..., 0, :] = first_row
+    c[..., np.arange(1, n - 1), np.arange(0, n - 2)] = 1
+    return c
+
+
+def helmert(n, full=False):
+    """
+    Create an Helmert matrix of order `n`.
+
+    This has applications in statistics, compositional or simplicial analysis,
+    and in Aitchison geometry.
+
+    Parameters
+    ----------
+    n : int
+        The size of the array to create.
+    full : bool, optional
+        If True the (n, n) ndarray will be returned.
+        Otherwise the submatrix that does not include the first
+        row will be returned.
+        Default: False.
+
+    Returns
+    -------
+    M : ndarray
+        The Helmert matrix.
+        The shape is (n, n) or (n-1, n) depending on the `full` argument.
+
+    Examples
+    --------
+    >>> from scipy.linalg import helmert
+    >>> helmert(5, full=True)
+    array([[ 0.4472136 ,  0.4472136 ,  0.4472136 ,  0.4472136 ,  0.4472136 ],
+           [ 0.70710678, -0.70710678,  0.        ,  0.        ,  0.        ],
+           [ 0.40824829,  0.40824829, -0.81649658,  0.        ,  0.        ],
+           [ 0.28867513,  0.28867513,  0.28867513, -0.8660254 ,  0.        ],
+           [ 0.2236068 ,  0.2236068 ,  0.2236068 ,  0.2236068 , -0.89442719]])
+
+    """
+    H = np.tril(np.ones((n, n)), -1) - np.diag(np.arange(n))
+    d = np.arange(n) * np.arange(1, n+1)
+    H[0] = 1
+    d[0] = n
+    H_full = H / np.sqrt(d)[:, np.newaxis]
+    if full:
+        return H_full
+    else:
+        return H_full[1:]
+
+
+def hilbert(n):
+    """
+    Create a Hilbert matrix of order `n`.
+
+    Returns the `n` by `n` array with entries `h[i,j] = 1 / (i + j + 1)`.
+
+    Parameters
+    ----------
+    n : int
+        The size of the array to create.
+
+    Returns
+    -------
+    h : (n, n) ndarray
+        The Hilbert matrix.
+
+    See Also
+    --------
+    invhilbert : Compute the inverse of a Hilbert matrix.
+
+    Notes
+    -----
+    .. versionadded:: 0.10.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import hilbert
+    >>> hilbert(3)
+    array([[ 1.        ,  0.5       ,  0.33333333],
+           [ 0.5       ,  0.33333333,  0.25      ],
+           [ 0.33333333,  0.25      ,  0.2       ]])
+
+    """
+    values = 1.0 / (1.0 + np.arange(2 * n - 1))
+    h = hankel(values[:n], r=values[n - 1:])
+    return h
+
+
+def invhilbert(n, exact=False):
+    """
+    Compute the inverse of the Hilbert matrix of order `n`.
+
+    The entries in the inverse of a Hilbert matrix are integers. When `n`
+    is greater than 14, some entries in the inverse exceed the upper limit
+    of 64 bit integers. The `exact` argument provides two options for
+    dealing with these large integers.
+
+    Parameters
+    ----------
+    n : int
+        The order of the Hilbert matrix.
+    exact : bool, optional
+        If False, the data type of the array that is returned is np.float64,
+        and the array is an approximation of the inverse.
+        If True, the array is the exact integer inverse array. To represent
+        the exact inverse when n > 14, the returned array is an object array
+        of long integers. For n <= 14, the exact inverse is returned as an
+        array with data type np.int64.
+
+    Returns
+    -------
+    invh : (n, n) ndarray
+        The data type of the array is np.float64 if `exact` is False.
+        If `exact` is True, the data type is either np.int64 (for n <= 14)
+        or object (for n > 14). In the latter case, the objects in the
+        array will be long integers.
+
+    See Also
+    --------
+    hilbert : Create a Hilbert matrix.
+
+    Notes
+    -----
+    .. versionadded:: 0.10.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import invhilbert
+    >>> invhilbert(4)
+    array([[   16.,  -120.,   240.,  -140.],
+           [ -120.,  1200., -2700.,  1680.],
+           [  240., -2700.,  6480., -4200.],
+           [ -140.,  1680., -4200.,  2800.]])
+    >>> invhilbert(4, exact=True)
+    array([[   16,  -120,   240,  -140],
+           [ -120,  1200, -2700,  1680],
+           [  240, -2700,  6480, -4200],
+           [ -140,  1680, -4200,  2800]], dtype=int64)
+    >>> invhilbert(16)[7,7]
+    4.2475099528537506e+19
+    >>> invhilbert(16, exact=True)[7,7]
+    42475099528537378560
+
+    """
+    from scipy.special import comb
+    if exact:
+        if n > 14:
+            dtype = object
+        else:
+            dtype = np.int64
+    else:
+        dtype = np.float64
+    invh = np.empty((n, n), dtype=dtype)
+    for i in range(n):
+        for j in range(0, i + 1):
+            s = i + j
+            invh[i, j] = ((-1) ** s * (s + 1) *
+                          comb(n + i, n - j - 1, exact=exact) *
+                          comb(n + j, n - i - 1, exact=exact) *
+                          comb(s, i, exact=exact) ** 2)
+            if i != j:
+                invh[j, i] = invh[i, j]
+    return invh
+
+
+def pascal(n, kind='symmetric', exact=True):
+    """
+    Returns the n x n Pascal matrix.
+
+    The Pascal matrix is a matrix containing the binomial coefficients as
+    its elements.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrix to create; that is, the result is an n x n
+        matrix.
+    kind : str, optional
+        Must be one of 'symmetric', 'lower', or 'upper'.
+        Default is 'symmetric'.
+    exact : bool, optional
+        If `exact` is True, the result is either an array of type
+        numpy.uint64 (if n < 35) or an object array of Python long integers.
+        If `exact` is False, the coefficients in the matrix are computed using
+        `scipy.special.comb` with ``exact=False``. The result will be a floating
+        point array, and the values in the array will not be the exact
+        coefficients, but this version is much faster than ``exact=True``.
+
+    Returns
+    -------
+    p : (n, n) ndarray
+        The Pascal matrix.
+
+    See Also
+    --------
+    invpascal
+
+    Notes
+    -----
+    See https://en.wikipedia.org/wiki/Pascal_matrix for more information
+    about Pascal matrices.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> from scipy.linalg import pascal
+    >>> pascal(4)
+    array([[ 1,  1,  1,  1],
+           [ 1,  2,  3,  4],
+           [ 1,  3,  6, 10],
+           [ 1,  4, 10, 20]], dtype=uint64)
+    >>> pascal(4, kind='lower')
+    array([[1, 0, 0, 0],
+           [1, 1, 0, 0],
+           [1, 2, 1, 0],
+           [1, 3, 3, 1]], dtype=uint64)
+    >>> pascal(50)[-1, -1]
+    25477612258980856902730428600
+    >>> from scipy.special import comb
+    >>> comb(98, 49, exact=True)
+    25477612258980856902730428600
+
+    """
+
+    from scipy.special import comb
+    if kind not in ['symmetric', 'lower', 'upper']:
+        raise ValueError("kind must be 'symmetric', 'lower', or 'upper'")
+
+    if exact:
+        if n >= 35:
+            L_n = np.empty((n, n), dtype=object)
+            L_n.fill(0)
+        else:
+            L_n = np.zeros((n, n), dtype=np.uint64)
+        for i in range(n):
+            for j in range(i + 1):
+                L_n[i, j] = comb(i, j, exact=True)
+    else:
+        L_n = comb(*np.ogrid[:n, :n])
+
+    if kind == 'lower':
+        p = L_n
+    elif kind == 'upper':
+        p = L_n.T
+    else:
+        p = np.dot(L_n, L_n.T)
+
+    return p
+
+
+def invpascal(n, kind='symmetric', exact=True):
+    """
+    Returns the inverse of the n x n Pascal matrix.
+
+    The Pascal matrix is a matrix containing the binomial coefficients as
+    its elements.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrix to create; that is, the result is an n x n
+        matrix.
+    kind : str, optional
+        Must be one of 'symmetric', 'lower', or 'upper'.
+        Default is 'symmetric'.
+    exact : bool, optional
+        If `exact` is True, the result is either an array of type
+        ``numpy.int64`` (if `n` <= 35) or an object array of Python integers.
+        If `exact` is False, the coefficients in the matrix are computed using
+        `scipy.special.comb` with `exact=False`. The result will be a floating
+        point array, and for large `n`, the values in the array will not be the
+        exact coefficients.
+
+    Returns
+    -------
+    invp : (n, n) ndarray
+        The inverse of the Pascal matrix.
+
+    See Also
+    --------
+    pascal
+
+    Notes
+    -----
+
+    .. versionadded:: 0.16.0
+
+    References
+    ----------
+    .. [1] "Pascal matrix", https://en.wikipedia.org/wiki/Pascal_matrix
+    .. [2] Cohen, A. M., "The inverse of a Pascal matrix", Mathematical
+           Gazette, 59(408), pp. 111-112, 1975.
+
+    Examples
+    --------
+    >>> from scipy.linalg import invpascal, pascal
+    >>> invp = invpascal(5)
+    >>> invp
+    array([[  5, -10,  10,  -5,   1],
+           [-10,  30, -35,  19,  -4],
+           [ 10, -35,  46, -27,   6],
+           [ -5,  19, -27,  17,  -4],
+           [  1,  -4,   6,  -4,   1]])
+
+    >>> p = pascal(5)
+    >>> p.dot(invp)
+    array([[ 1.,  0.,  0.,  0.,  0.],
+           [ 0.,  1.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  1.,  0.],
+           [ 0.,  0.,  0.,  0.,  1.]])
+
+    An example of the use of `kind` and `exact`:
+
+    >>> invpascal(5, kind='lower', exact=False)
+    array([[ 1., -0.,  0., -0.,  0.],
+           [-1.,  1., -0.,  0., -0.],
+           [ 1., -2.,  1., -0.,  0.],
+           [-1.,  3., -3.,  1., -0.],
+           [ 1., -4.,  6., -4.,  1.]])
+
+    """
+    from scipy.special import comb
+
+    if kind not in ['symmetric', 'lower', 'upper']:
+        raise ValueError("'kind' must be 'symmetric', 'lower' or 'upper'.")
+
+    if kind == 'symmetric':
+        if exact:
+            if n > 34:
+                dt = object
+            else:
+                dt = np.int64
+        else:
+            dt = np.float64
+        invp = np.empty((n, n), dtype=dt)
+        for i in range(n):
+            for j in range(0, i + 1):
+                v = 0
+                for k in range(n - i):
+                    v += comb(i + k, k, exact=exact) * comb(i + k, i + k - j,
+                                                            exact=exact)
+                invp[i, j] = (-1)**(i - j) * v
+                if i != j:
+                    invp[j, i] = invp[i, j]
+    else:
+        # For the 'lower' and 'upper' cases, we computer the inverse by
+        # changing the sign of every other diagonal of the pascal matrix.
+        invp = pascal(n, kind=kind, exact=exact)
+        if invp.dtype == np.uint64:
+            # This cast from np.uint64 to int64 OK, because if `kind` is not
+            # "symmetric", the values in invp are all much less than 2**63.
+            invp = invp.view(np.int64)
+
+        # The toeplitz matrix has alternating bands of 1 and -1.
+        invp *= toeplitz((-1)**np.arange(n)).astype(invp.dtype)
+
+    return invp
+
+
+def dft(n, scale=None):
+    """
+    Discrete Fourier transform matrix.
+
+    Create the matrix that computes the discrete Fourier transform of a
+    sequence [1]_. The nth primitive root of unity used to generate the
+    matrix is exp(-2*pi*i/n), where i = sqrt(-1).
+
+    Parameters
+    ----------
+    n : int
+        Size the matrix to create.
+    scale : str, optional
+        Must be None, 'sqrtn', or 'n'.
+        If `scale` is 'sqrtn', the matrix is divided by `sqrt(n)`.
+        If `scale` is 'n', the matrix is divided by `n`.
+        If `scale` is None (the default), the matrix is not normalized, and the
+        return value is simply the Vandermonde matrix of the roots of unity.
+
+    Returns
+    -------
+    m : (n, n) ndarray
+        The DFT matrix.
+
+    Notes
+    -----
+    When `scale` is None, multiplying a vector by the matrix returned by
+    `dft` is mathematically equivalent to (but much less efficient than)
+    the calculation performed by `scipy.fft.fft`.
+
+    .. versionadded:: 0.14.0
+
+    References
+    ----------
+    .. [1] "DFT matrix", https://en.wikipedia.org/wiki/DFT_matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import dft
+    >>> np.set_printoptions(precision=2, suppress=True)  # for compact output
+    >>> m = dft(5)
+    >>> m
+    array([[ 1.  +0.j  ,  1.  +0.j  ,  1.  +0.j  ,  1.  +0.j  ,  1.  +0.j  ],
+           [ 1.  +0.j  ,  0.31-0.95j, -0.81-0.59j, -0.81+0.59j,  0.31+0.95j],
+           [ 1.  +0.j  , -0.81-0.59j,  0.31+0.95j,  0.31-0.95j, -0.81+0.59j],
+           [ 1.  +0.j  , -0.81+0.59j,  0.31-0.95j,  0.31+0.95j, -0.81-0.59j],
+           [ 1.  +0.j  ,  0.31+0.95j, -0.81+0.59j, -0.81-0.59j,  0.31-0.95j]])
+    >>> x = np.array([1, 2, 3, 0, 3])
+    >>> m @ x  # Compute the DFT of x
+    array([ 9.  +0.j  ,  0.12-0.81j, -2.12+3.44j, -2.12-3.44j,  0.12+0.81j])
+
+    Verify that ``m @ x`` is the same as ``fft(x)``.
+
+    >>> from scipy.fft import fft
+    >>> fft(x)     # Same result as m @ x
+    array([ 9.  +0.j  ,  0.12-0.81j, -2.12+3.44j, -2.12-3.44j,  0.12+0.81j])
+    """
+    if scale not in [None, 'sqrtn', 'n']:
+        raise ValueError("scale must be None, 'sqrtn', or 'n'; "
+                         f"{scale!r} is not valid.")
+
+    omegas = np.exp(-2j * np.pi * np.arange(n) / n).reshape(-1, 1)
+    m = omegas ** np.arange(n)
+    if scale == 'sqrtn':
+        m /= math.sqrt(n)
+    elif scale == 'n':
+        m /= n
+    return m
+
+
+def fiedler(a):
+    """Returns a symmetric Fiedler matrix
+
+    Given an sequence of numbers `a`, Fiedler matrices have the structure
+    ``F[i, j] = np.abs(a[i] - a[j])``, and hence zero diagonals and nonnegative
+    entries. A Fiedler matrix has a dominant positive eigenvalue and other
+    eigenvalues are negative. Although not valid generally, for certain inputs,
+    the inverse and the determinant can be derived explicitly as given in [1]_.
+
+    Parameters
+    ----------
+    a : (..., n,) array_like
+        Coefficient array. N-dimensional arrays are treated as a batch:
+        each slice along the last axis is a 1-D coefficient array.
+
+    Returns
+    -------
+    F : (..., n, n) ndarray
+        Fiedler matrix. For batch input, each slice of shape ``(n, n)``
+        along the last two dimensions of the output corresponds with a
+        slice of shape ``(n,)`` along the last dimension of the input.
+
+    See Also
+    --------
+    circulant, toeplitz
+
+    Notes
+    -----
+
+    .. versionadded:: 1.3.0
+
+    References
+    ----------
+    .. [1] J. Todd, "Basic Numerical Mathematics: Vol.2 : Numerical Algebra",
+        1977, Birkhauser, :doi:`10.1007/978-3-0348-7286-7`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import det, inv, fiedler
+    >>> a = [1, 4, 12, 45, 77]
+    >>> n = len(a)
+    >>> A = fiedler(a)
+    >>> A
+    array([[ 0,  3, 11, 44, 76],
+           [ 3,  0,  8, 41, 73],
+           [11,  8,  0, 33, 65],
+           [44, 41, 33,  0, 32],
+           [76, 73, 65, 32,  0]])
+
+    The explicit formulas for determinant and inverse seem to hold only for
+    monotonically increasing/decreasing arrays. Note the tridiagonal structure
+    and the corners.
+
+    >>> Ai = inv(A)
+    >>> Ai[np.abs(Ai) < 1e-12] = 0.  # cleanup the numerical noise for display
+    >>> Ai
+    array([[-0.16008772,  0.16666667,  0.        ,  0.        ,  0.00657895],
+           [ 0.16666667, -0.22916667,  0.0625    ,  0.        ,  0.        ],
+           [ 0.        ,  0.0625    , -0.07765152,  0.01515152,  0.        ],
+           [ 0.        ,  0.        ,  0.01515152, -0.03077652,  0.015625  ],
+           [ 0.00657895,  0.        ,  0.        ,  0.015625  , -0.00904605]])
+    >>> det(A)
+    15409151.999999998
+    >>> (-1)**(n-1) * 2**(n-2) * np.diff(a).prod() * (a[-1] - a[0])
+    15409152
+
+    """
+    a = np.atleast_1d(a)
+
+    if a.ndim > 1:
+        return np.apply_along_axis(fiedler, -1, a)
+
+    if a.size == 0:
+        return np.array([], dtype=float)
+    elif a.size == 1:
+        return np.array([[0.]])
+    else:
+        return np.abs(a[:, None] - a)
+
+
+def fiedler_companion(a):
+    """ Returns a Fiedler companion matrix
+
+    Given a polynomial coefficient array ``a``, this function forms a
+    pentadiagonal matrix with a special structure whose eigenvalues coincides
+    with the roots of ``a``.
+
+    Parameters
+    ----------
+    a : (..., N) array_like
+        1-D array of polynomial coefficients in descending order with a nonzero
+        leading coefficient. For ``N < 2``, an empty array is returned.
+        N-dimensional arrays are treated as a batch: each slice along the last
+        axis is a 1-D array of polynomial coefficients.
+
+    Returns
+    -------
+    c : (..., N-1, N-1) ndarray
+        Resulting companion matrix. For batch input, each slice of shape
+        ``(N-1, N-1)`` along the last two dimensions of the output corresponds
+        with a slice of shape ``(N,)`` along the last dimension of the input.
+
+    See Also
+    --------
+    companion
+
+    Notes
+    -----
+    Similar to `companion`, each leading coefficient along the last axis of the
+    input should be nonzero.
+    If the leading coefficient is not 1, other coefficients are rescaled before
+    the array generation. To avoid numerical issues, it is best to provide a
+    monic polynomial.
+
+    .. versionadded:: 1.3.0
+
+    References
+    ----------
+    .. [1] M. Fiedler, " A note on companion matrices", Linear Algebra and its
+        Applications, 2003, :doi:`10.1016/S0024-3795(03)00548-2`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import fiedler_companion, eigvals
+    >>> p = np.poly(np.arange(1, 9, 2))  # [1., -16., 86., -176., 105.]
+    >>> fc = fiedler_companion(p)
+    >>> fc
+    array([[  16.,  -86.,    1.,    0.],
+           [   1.,    0.,    0.,    0.],
+           [   0.,  176.,    0., -105.],
+           [   0.,    1.,    0.,    0.]])
+    >>> eigvals(fc)
+    array([7.+0.j, 5.+0.j, 3.+0.j, 1.+0.j])
+
+    """
+    a = np.atleast_1d(a)
+
+    if a.ndim > 1:
+        return np.apply_along_axis(fiedler_companion, -1, a)
+
+    if a.size <= 2:
+        if a.size == 2:
+            return np.array([[-(a/a[0])[-1]]])
+        return np.array([], dtype=a.dtype)
+
+    if a[0] == 0.:
+        raise ValueError('Leading coefficient is zero.')
+
+    a = a/a[0]
+    n = a.size - 1
+    c = np.zeros((n, n), dtype=a.dtype)
+    # subdiagonals
+    c[range(3, n, 2), range(1, n-2, 2)] = 1.
+    c[range(2, n, 2), range(1, n-1, 2)] = -a[3::2]
+    # superdiagonals
+    c[range(0, n-2, 2), range(2, n, 2)] = 1.
+    c[range(0, n-1, 2), range(1, n, 2)] = -a[2::2]
+    c[[0, 1], 0] = [-a[1], 1]
+
+    return c
+
+
+def convolution_matrix(a, n, mode='full'):
+    """
+    Construct a convolution matrix.
+
+    Constructs the Toeplitz matrix representing one-dimensional
+    convolution [1]_.  See the notes below for details.
+
+    Parameters
+    ----------
+    a : (..., m) array_like
+        The 1-D array to convolve. N-dimensional arrays are treated as a
+        batch: each slice along the last axis is a 1-D array to convolve.
+    n : int
+        The number of columns in the resulting matrix.  It gives the length
+        of the input to be convolved with `a`.  This is analogous to the
+        length of `v` in ``numpy.convolve(a, v)``.
+    mode : str
+        This is analogous to `mode` in ``numpy.convolve(v, a, mode)``.
+        It must be one of ('full', 'valid', 'same').
+        See below for how `mode` determines the shape of the result.
+
+    Returns
+    -------
+    A : (..., k, n) ndarray
+        The convolution matrix whose row count `k` depends on `mode`::
+
+            =======  =========================
+             mode    k
+            =======  =========================
+            'full'   m + n -1
+            'same'   max(m, n)
+            'valid'  max(m, n) - min(m, n) + 1
+            =======  =========================
+
+        For batch input, each slice of shape ``(k, n)`` along the last two
+        dimensions of the output corresponds with a slice of shape ``(m,)``
+        along the last dimension of the input.
+
+    See Also
+    --------
+    toeplitz : Toeplitz matrix
+
+    Notes
+    -----
+    The code::
+
+        A = convolution_matrix(a, n, mode)
+
+    creates a Toeplitz matrix `A` such that ``A @ v`` is equivalent to
+    using ``convolve(a, v, mode)``.  The returned array always has `n`
+    columns.  The number of rows depends on the specified `mode`, as
+    explained above.
+
+    In the default 'full' mode, the entries of `A` are given by::
+
+        A[i, j] == (a[i-j] if (0 <= (i-j) < m) else 0)
+
+    where ``m = len(a)``.  Suppose, for example, the input array is
+    ``[x, y, z]``.  The convolution matrix has the form::
+
+        [x, 0, 0, ..., 0, 0]
+        [y, x, 0, ..., 0, 0]
+        [z, y, x, ..., 0, 0]
+        ...
+        [0, 0, 0, ..., x, 0]
+        [0, 0, 0, ..., y, x]
+        [0, 0, 0, ..., z, y]
+        [0, 0, 0, ..., 0, z]
+
+    In 'valid' mode, the entries of `A` are given by::
+
+        A[i, j] == (a[i-j+m-1] if (0 <= (i-j+m-1) < m) else 0)
+
+    This corresponds to a matrix whose rows are the subset of those from
+    the 'full' case where all the coefficients in `a` are contained in the
+    row.  For input ``[x, y, z]``, this array looks like::
+
+        [z, y, x, 0, 0, ..., 0, 0, 0]
+        [0, z, y, x, 0, ..., 0, 0, 0]
+        [0, 0, z, y, x, ..., 0, 0, 0]
+        ...
+        [0, 0, 0, 0, 0, ..., x, 0, 0]
+        [0, 0, 0, 0, 0, ..., y, x, 0]
+        [0, 0, 0, 0, 0, ..., z, y, x]
+
+    In the 'same' mode, the entries of `A` are given by::
+
+        d = (m - 1) // 2
+        A[i, j] == (a[i-j+d] if (0 <= (i-j+d) < m) else 0)
+
+    The typical application of the 'same' mode is when one has a signal of
+    length `n` (with `n` greater than ``len(a)``), and the desired output
+    is a filtered signal that is still of length `n`.
+
+    For input ``[x, y, z]``, this array looks like::
+
+        [y, x, 0, 0, ..., 0, 0, 0]
+        [z, y, x, 0, ..., 0, 0, 0]
+        [0, z, y, x, ..., 0, 0, 0]
+        [0, 0, z, y, ..., 0, 0, 0]
+        ...
+        [0, 0, 0, 0, ..., y, x, 0]
+        [0, 0, 0, 0, ..., z, y, x]
+        [0, 0, 0, 0, ..., 0, z, y]
+
+    .. versionadded:: 1.5.0
+
+    References
+    ----------
+    .. [1] "Convolution", https://en.wikipedia.org/wiki/Convolution
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.linalg import convolution_matrix
+    >>> A = convolution_matrix([-1, 4, -2], 5, mode='same')
+    >>> A
+    array([[ 4, -1,  0,  0,  0],
+           [-2,  4, -1,  0,  0],
+           [ 0, -2,  4, -1,  0],
+           [ 0,  0, -2,  4, -1],
+           [ 0,  0,  0, -2,  4]])
+
+    Compare multiplication by `A` with the use of `numpy.convolve`.
+
+    >>> x = np.array([1, 2, 0, -3, 0.5])
+    >>> A @ x
+    array([  2. ,   6. ,  -1. , -12.5,   8. ])
+
+    Verify that ``A @ x`` produced the same result as applying the
+    convolution function.
+
+    >>> np.convolve([-1, 4, -2], x, mode='same')
+    array([  2. ,   6. ,  -1. , -12.5,   8. ])
+
+    For comparison to the case ``mode='same'`` shown above, here are the
+    matrices produced by ``mode='full'`` and ``mode='valid'`` for the
+    same coefficients and size.
+
+    >>> convolution_matrix([-1, 4, -2], 5, mode='full')
+    array([[-1,  0,  0,  0,  0],
+           [ 4, -1,  0,  0,  0],
+           [-2,  4, -1,  0,  0],
+           [ 0, -2,  4, -1,  0],
+           [ 0,  0, -2,  4, -1],
+           [ 0,  0,  0, -2,  4],
+           [ 0,  0,  0,  0, -2]])
+
+    >>> convolution_matrix([-1, 4, -2], 5, mode='valid')
+    array([[-2,  4, -1,  0,  0],
+           [ 0, -2,  4, -1,  0],
+           [ 0,  0, -2,  4, -1]])
+    """
+    if n <= 0:
+        raise ValueError('n must be a positive integer.')
+
+    a = np.asarray(a)
+
+    if a.size == 0:
+        raise ValueError('len(a) must be at least 1.')
+
+    if mode not in ('full', 'valid', 'same'):
+        raise ValueError(
+            "'mode' argument must be one of ('full', 'valid', 'same')")
+
+    if a.ndim > 1:
+        return np.apply_along_axis(lambda a: convolution_matrix(a, n, mode), -1, a)
+
+    # create zero padded versions of the array
+    az = np.pad(a, (0, n-1), 'constant')
+    raz = np.pad(a[::-1], (0, n-1), 'constant')
+
+    if mode == 'same':
+        trim = min(n, len(a)) - 1
+        tb = trim//2
+        te = trim - tb
+        col0 = az[tb:len(az)-te]
+        row0 = raz[-n-tb:len(raz)-tb]
+    elif mode == 'valid':
+        tb = min(n, len(a)) - 1
+        te = tb
+        col0 = az[tb:len(az)-te]
+        row0 = raz[-n-tb:len(raz)-tb]
+    else:  # 'full'
+        col0 = az
+        row0 = raz[-n:]
+    return toeplitz(col0, row0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_testutils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6d01d2b6e59b040f39c0b53cc2788bbd3d0888f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/_testutils.py
@@ -0,0 +1,65 @@
+import numpy as np
+
+
+class _FakeMatrix:
+    def __init__(self, data):
+        self._data = data
+        self.__array_interface__ = data.__array_interface__
+
+
+class _FakeMatrix2:
+    def __init__(self, data):
+        self._data = data
+
+    def __array__(self, dtype=None, copy=None):
+        if copy:
+            return self._data.copy()
+        return self._data
+
+
+def _get_array(shape, dtype):
+    """
+    Get a test array of given shape and data type.
+    Returned NxN matrices are posdef, and 2xN are banded-posdef.
+
+    """
+    if len(shape) == 2 and shape[0] == 2:
+        # yield a banded positive definite one
+        x = np.zeros(shape, dtype=dtype)
+        x[0, 1:] = -1
+        x[1] = 2
+        return x
+    elif len(shape) == 2 and shape[0] == shape[1]:
+        # always yield a positive definite matrix
+        x = np.zeros(shape, dtype=dtype)
+        j = np.arange(shape[0])
+        x[j, j] = 2
+        x[j[:-1], j[:-1]+1] = -1
+        x[j[:-1]+1, j[:-1]] = -1
+        return x
+    else:
+        np.random.seed(1234)
+        return np.random.randn(*shape).astype(dtype)
+
+
+def _id(x):
+    return x
+
+
+def assert_no_overwrite(call, shapes, dtypes=None):
+    """
+    Test that a call does not overwrite its input arguments
+    """
+
+    if dtypes is None:
+        dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+
+    for dtype in dtypes:
+        for order in ["C", "F"]:
+            for faker in [_id, _FakeMatrix, _FakeMatrix2]:
+                orig_inputs = [_get_array(s, dtype) for s in shapes]
+                inputs = [faker(x.copy(order)) for x in orig_inputs]
+                call(*inputs)
+                msg = f"call modified inputs [{dtype!r}, {faker!r}]"
+                for a, b in zip(inputs, orig_inputs):
+                    np.testing.assert_equal(a, b, err_msg=msg)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..04ef3645a2ed6a22106ed8ca1acf9e9ac93df5cf
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/basic.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
+    'solve_toeplitz', 'solve_circulant', 'inv', 'det', 'lstsq',
+    'pinv', 'pinvh', 'matrix_balance', 'matmul_toeplitz',
+    'get_lapack_funcs', 'LinAlgError', 'LinAlgWarning',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="basic",
+                                   private_modules=["_basic"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/blas.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..c943460e6bafcd9a382586d5a5155357382ea596
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/blas.py
@@ -0,0 +1,484 @@
+"""
+Low-level BLAS functions (:mod:`scipy.linalg.blas`)
+===================================================
+
+This module contains low-level functions from the BLAS library.
+
+.. versionadded:: 0.12.0
+
+.. note::
+
+   The common ``overwrite_<>`` option in many routines, allows the
+   input arrays to be overwritten to avoid extra memory allocation.
+   However this requires the array to satisfy two conditions
+   which are memory order and the data type to match exactly the
+   order and the type expected by the routine.
+
+   As an example, if you pass a double precision float array to any
+   ``S....`` routine which expects single precision arguments, f2py
+   will create an intermediate array to match the argument types and
+   overwriting will be performed on that intermediate array.
+
+   Similarly, if a C-contiguous array is passed, f2py will pass a
+   FORTRAN-contiguous array internally. Please make sure that these
+   details are satisfied. More information can be found in the f2py
+   documentation.
+
+.. warning::
+
+   These functions do little to no error checking.
+   It is possible to cause crashes by mis-using them,
+   so prefer using the higher-level routines in `scipy.linalg`.
+
+Finding functions
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   get_blas_funcs
+   find_best_blas_type
+
+BLAS Level 1 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   caxpy
+   ccopy
+   cdotc
+   cdotu
+   crotg
+   cscal
+   csrot
+   csscal
+   cswap
+   dasum
+   daxpy
+   dcopy
+   ddot
+   dnrm2
+   drot
+   drotg
+   drotm
+   drotmg
+   dscal
+   dswap
+   dzasum
+   dznrm2
+   icamax
+   idamax
+   isamax
+   izamax
+   sasum
+   saxpy
+   scasum
+   scnrm2
+   scopy
+   sdot
+   snrm2
+   srot
+   srotg
+   srotm
+   srotmg
+   sscal
+   sswap
+   zaxpy
+   zcopy
+   zdotc
+   zdotu
+   zdrot
+   zdscal
+   zrotg
+   zscal
+   zswap
+
+BLAS Level 2 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgbmv
+   sgemv
+   sger
+   ssbmv
+   sspr
+   sspr2
+   ssymv
+   ssyr
+   ssyr2
+   stbmv
+   stpsv
+   strmv
+   strsv
+   dgbmv
+   dgemv
+   dger
+   dsbmv
+   dspr
+   dspr2
+   dsymv
+   dsyr
+   dsyr2
+   dtbmv
+   dtpsv
+   dtrmv
+   dtrsv
+   cgbmv
+   cgemv
+   cgerc
+   cgeru
+   chbmv
+   chemv
+   cher
+   cher2
+   chpmv
+   chpr
+   chpr2
+   ctbmv
+   ctbsv
+   ctpmv
+   ctpsv
+   ctrmv
+   ctrsv
+   csyr
+   zgbmv
+   zgemv
+   zgerc
+   zgeru
+   zhbmv
+   zhemv
+   zher
+   zher2
+   zhpmv
+   zhpr
+   zhpr2
+   ztbmv
+   ztbsv
+   ztpmv
+   ztrmv
+   ztrsv
+   zsyr
+
+BLAS Level 3 functions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgemm
+   ssymm
+   ssyr2k
+   ssyrk
+   strmm
+   strsm
+   dgemm
+   dsymm
+   dsyr2k
+   dsyrk
+   dtrmm
+   dtrsm
+   cgemm
+   chemm
+   cher2k
+   cherk
+   csymm
+   csyr2k
+   csyrk
+   ctrmm
+   ctrsm
+   zgemm
+   zhemm
+   zher2k
+   zherk
+   zsymm
+   zsyr2k
+   zsyrk
+   ztrmm
+   ztrsm
+
+"""
+#
+# Author: Pearu Peterson, March 2002
+#         refactoring by Fabian Pedregosa, March 2010
+#
+
+__all__ = ['get_blas_funcs', 'find_best_blas_type']
+
+import numpy as np
+import functools
+
+from scipy.linalg import _fblas
+try:
+    from scipy.linalg import _cblas
+except ImportError:
+    _cblas = None
+
+try:
+    from scipy.linalg import _fblas_64
+    HAS_ILP64 = True
+except ImportError:
+    HAS_ILP64 = False
+    _fblas_64 = None
+
+# Expose all functions (only fblas --- cblas is an implementation detail)
+empty_module = None
+from scipy.linalg._fblas import *  # noqa: E402, F403
+del empty_module
+
+# all numeric dtypes '?bBhHiIlLqQefdgFDGO' that are safe to be converted to
+
+# single precision float   : '?bBhH!!!!!!ef!!!!!!'
+# double precision float   : '?bBhHiIlLqQefdg!!!!'
+# single precision complex : '?bBhH!!!!!!ef!!F!!!'
+# double precision complex : '?bBhHiIlLqQefdgFDG!'
+
+_type_score = {x: 1 for x in '?bBhHef'}
+_type_score.update({x: 2 for x in 'iIlLqQd'})
+
+# Handle float128(g) and complex256(G) separately in case non-Windows systems.
+# On Windows, the values will be rewritten to the same key with the same value.
+_type_score.update({'F': 3, 'D': 4, 'g': 2, 'G': 4})
+
+# Final mapping to the actual prefixes and dtypes
+_type_conv = {1: ('s', np.dtype('float32')),
+              2: ('d', np.dtype('float64')),
+              3: ('c', np.dtype('complex64')),
+              4: ('z', np.dtype('complex128'))}
+
+# some convenience alias for complex functions
+_blas_alias = {'cnrm2': 'scnrm2', 'znrm2': 'dznrm2',
+               'cdot': 'cdotc', 'zdot': 'zdotc',
+               'cger': 'cgerc', 'zger': 'zgerc',
+               'sdotc': 'sdot', 'sdotu': 'sdot',
+               'ddotc': 'ddot', 'ddotu': 'ddot'}
+
+
+def find_best_blas_type(arrays=(), dtype=None):
+    """Find best-matching BLAS/LAPACK type.
+
+    Arrays are used to determine the optimal prefix of BLAS routines.
+
+    Parameters
+    ----------
+    arrays : sequence of ndarrays, optional
+        Arrays can be given to determine optimal prefix of BLAS
+        routines. If not given, double-precision routines will be
+        used, otherwise the most generic type in arrays will be used.
+    dtype : str or dtype, optional
+        Data-type specifier. Not used if `arrays` is non-empty.
+
+    Returns
+    -------
+    prefix : str
+        BLAS/LAPACK prefix character.
+    dtype : dtype
+        Inferred Numpy data type.
+    prefer_fortran : bool
+        Whether to prefer Fortran order routines over C order.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.linalg.blas as bla
+    >>> rng = np.random.default_rng()
+    >>> a = rng.random((10,15))
+    >>> b = np.asfortranarray(a)  # Change the memory layout order
+    >>> bla.find_best_blas_type((a,))
+    ('d', dtype('float64'), False)
+    >>> bla.find_best_blas_type((a*1j,))
+    ('z', dtype('complex128'), False)
+    >>> bla.find_best_blas_type((b,))
+    ('d', dtype('float64'), True)
+
+    """
+    dtype = np.dtype(dtype)
+    max_score = _type_score.get(dtype.char, 5)
+    prefer_fortran = False
+
+    if arrays:
+        # In most cases, single element is passed through, quicker route
+        if len(arrays) == 1:
+            max_score = _type_score.get(arrays[0].dtype.char, 5)
+            prefer_fortran = arrays[0].flags['FORTRAN']
+        else:
+            # use the most generic type in arrays
+            scores = [_type_score.get(x.dtype.char, 5) for x in arrays]
+            max_score = max(scores)
+            ind_max_score = scores.index(max_score)
+            # safe upcasting for mix of float64 and complex64 --> prefix 'z'
+            if max_score == 3 and (2 in scores):
+                max_score = 4
+
+            if arrays[ind_max_score].flags['FORTRAN']:
+                # prefer Fortran for leading array with column major order
+                prefer_fortran = True
+
+    # Get the LAPACK prefix and the corresponding dtype if not fall back
+    # to 'd' and double precision float.
+    prefix, dtype = _type_conv.get(max_score, ('d', np.dtype('float64')))
+
+    return prefix, dtype, prefer_fortran
+
+
+def _get_funcs(names, arrays, dtype,
+               lib_name, fmodule, cmodule,
+               fmodule_name, cmodule_name, alias,
+               ilp64=False):
+    """
+    Return available BLAS/LAPACK functions.
+
+    Used also in lapack.py. See get_blas_funcs for docstring.
+    """
+
+    funcs = []
+    unpack = False
+    dtype = np.dtype(dtype)
+    module1 = (cmodule, cmodule_name)
+    module2 = (fmodule, fmodule_name)
+
+    if isinstance(names, str):
+        names = (names,)
+        unpack = True
+
+    prefix, dtype, prefer_fortran = find_best_blas_type(arrays, dtype)
+
+    if prefer_fortran:
+        module1, module2 = module2, module1
+
+    for name in names:
+        func_name = prefix + name
+        func_name = alias.get(func_name, func_name)
+        func = getattr(module1[0], func_name, None)
+        module_name = module1[1]
+        if func is None:
+            func = getattr(module2[0], func_name, None)
+            module_name = module2[1]
+        if func is None:
+            raise ValueError(
+                f'{lib_name} function {func_name} could not be found')
+        func.module_name, func.typecode = module_name, prefix
+        func.dtype = dtype
+        if not ilp64:
+            func.int_dtype = np.dtype(np.intc)
+        else:
+            func.int_dtype = np.dtype(np.int64)
+        func.prefix = prefix  # Backward compatibility
+        funcs.append(func)
+
+    if unpack:
+        return funcs[0]
+    else:
+        return funcs
+
+
+def _memoize_get_funcs(func):
+    """
+    Memoized fast path for _get_funcs instances
+    """
+    memo = {}
+    func.memo = memo
+
+    @functools.wraps(func)
+    def getter(names, arrays=(), dtype=None, ilp64=False):
+        key = (names, dtype, ilp64)
+        for array in arrays:
+            # cf. find_blas_funcs
+            key += (array.dtype.char, array.flags.fortran)
+
+        try:
+            value = memo.get(key)
+        except TypeError:
+            # unhashable key etc.
+            key = None
+            value = None
+
+        if value is not None:
+            return value
+
+        value = func(names, arrays, dtype, ilp64)
+
+        if key is not None:
+            memo[key] = value
+
+        return value
+
+    return getter
+
+
+@_memoize_get_funcs
+def get_blas_funcs(names, arrays=(), dtype=None, ilp64=False):
+    """Return available BLAS function objects from names.
+
+    Arrays are used to determine the optimal prefix of BLAS routines.
+
+    Parameters
+    ----------
+    names : str or sequence of str
+        Name(s) of BLAS functions without type prefix.
+
+    arrays : sequence of ndarrays, optional
+        Arrays can be given to determine optimal prefix of BLAS
+        routines. If not given, double-precision routines will be
+        used, otherwise the most generic type in arrays will be used.
+
+    dtype : str or dtype, optional
+        Data-type specifier. Not used if `arrays` is non-empty.
+
+    ilp64 : {True, False, 'preferred'}, optional
+        Whether to return ILP64 routine variant.
+        Choosing 'preferred' returns ILP64 routine if available,
+        and otherwise the 32-bit routine. Default: False
+
+    Returns
+    -------
+    funcs : list
+        List containing the found function(s).
+
+
+    Notes
+    -----
+    This routine automatically chooses between Fortran/C
+    interfaces. Fortran code is used whenever possible for arrays with
+    column major order. In all other cases, C code is preferred.
+
+    In BLAS, the naming convention is that all functions start with a
+    type prefix, which depends on the type of the principal
+    matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy
+    types {float32, float64, complex64, complex128} respectively.
+    The code and the dtype are stored in attributes `typecode` and `dtype`
+    of the returned functions.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.linalg as LA
+    >>> rng = np.random.default_rng()
+    >>> a = rng.random((3,2))
+    >>> x_gemv = LA.get_blas_funcs('gemv', (a,))
+    >>> x_gemv.typecode
+    'd'
+    >>> x_gemv = LA.get_blas_funcs('gemv',(a*1j,))
+    >>> x_gemv.typecode
+    'z'
+
+    """
+    if isinstance(ilp64, str):
+        if ilp64 == 'preferred':
+            ilp64 = HAS_ILP64
+        else:
+            raise ValueError("Invalid value for 'ilp64'")
+
+    if not ilp64:
+        return _get_funcs(names, arrays, dtype,
+                          "BLAS", _fblas, _cblas, "fblas", "cblas",
+                          _blas_alias, ilp64=False)
+    else:
+        if not HAS_ILP64:
+            raise RuntimeError("BLAS ILP64 routine requested, but Scipy "
+                               "compiled only with 32-bit BLAS")
+        return _get_funcs(names, arrays, dtype,
+                          "BLAS", _fblas_64, None, "fblas_64", None,
+                          _blas_alias, ilp64=True)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..7ed44f6ea8611f926e3ea5fd2670446cdf9b398c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pxd
@@ -0,0 +1,169 @@
+"""
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+"""
+
+# Within scipy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_blas
+# from scipy.linalg cimport cython_blas
+# cimport scipy.linalg.cython_blas as cython_blas
+# cimport ..linalg.cython_blas as cython_blas
+
+# Within SciPy, if BLAS functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+ctypedef float s
+ctypedef double d
+ctypedef float complex c
+ctypedef double complex z
+
+cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
+cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
+cdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil
+cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil
+cdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil
+cdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil
+cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil
+cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil
+cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil
+cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil
+cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil
+cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil
+cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil
+cdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil
+cdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil
+cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil
+cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil
+cdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil
+cdef d dasum(int *n, d *dx, int *incx) noexcept nogil
+cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef d dcabs1(z *z) noexcept nogil
+cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil
+cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil
+cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil
+cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil
+cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil
+cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil
+cdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil
+cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil
+cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil
+cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil
+cdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil
+cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil
+cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil
+cdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil
+cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil
+cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil
+cdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil
+cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil
+cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil
+cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil
+cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil
+cdef int icamax(int *n, c *cx, int *incx) noexcept nogil
+cdef int idamax(int *n, d *dx, int *incx) noexcept nogil
+cdef int isamax(int *n, s *sx, int *incx) noexcept nogil
+cdef int izamax(int *n, z *zx, int *incx) noexcept nogil
+cdef bint lsame(char *ca, char *cb) noexcept nogil
+cdef s sasum(int *n, s *sx, int *incx) noexcept nogil
+cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef s scasum(int *n, c *cx, int *incx) noexcept nogil
+cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil
+cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
+cdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil
+cdef s snrm2(int *n, s *x, int *incx) noexcept nogil
+cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil
+cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil
+cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil
+cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil
+cdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil
+cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil
+cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil
+cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil
+cdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
+cdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil
+cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil
+cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil
+cdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil
+cdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil
+cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil
+cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil
+cdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil
+cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil
+cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil
+cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil
+cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil
+cdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
+cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
+cdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil
+cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil
+cdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil
+cdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil
+cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil
+cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil
+cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil
+cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil
+cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil
+cdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil
+cdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil
+cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil
+cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil
+cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil
+cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil
+cdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil
+cdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..35286fe11d72226269c0e459d9a3109151f74a4a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_blas.pyx
@@ -0,0 +1,1432 @@
+# This file was generated by _generate_pyx.py.
+# Do not edit this file directly.
+# cython: boundscheck = False
+# cython: wraparound = False
+# cython: cdivision = True
+
+"""
+BLAS Functions for Cython
+=========================
+
+Usable from Cython via::
+
+    cimport scipy.linalg.cython_blas
+
+These wrappers do not check for alignment of arrays.
+Alignment should be checked before these wrappers are used.
+
+If using ``cdotu``, ``cdotc``, ``zdotu``, ``zdotc``, ``sladiv``, or ``dladiv``,
+the ``CYTHON_CCOMPLEX`` define must be set to 0 during compilation. For
+example, in a ``meson.build`` file when using Meson::
+
+    py.extension_module('ext_module'
+        'ext_module.pyx',
+        c_args: ['-DCYTHON_CCOMPLEX=0'],
+        ...
+    )
+
+Raw function pointers (Fortran-style pointer arguments):
+
+- caxpy
+- ccopy
+- cdotc
+- cdotu
+- cgbmv
+- cgemm
+- cgemv
+- cgerc
+- cgeru
+- chbmv
+- chemm
+- chemv
+- cher
+- cher2
+- cher2k
+- cherk
+- chpmv
+- chpr
+- chpr2
+- crotg
+- cscal
+- csrot
+- csscal
+- cswap
+- csymm
+- csyr2k
+- csyrk
+- ctbmv
+- ctbsv
+- ctpmv
+- ctpsv
+- ctrmm
+- ctrmv
+- ctrsm
+- ctrsv
+- dasum
+- daxpy
+- dcabs1
+- dcopy
+- ddot
+- dgbmv
+- dgemm
+- dgemv
+- dger
+- dnrm2
+- drot
+- drotg
+- drotm
+- drotmg
+- dsbmv
+- dscal
+- dsdot
+- dspmv
+- dspr
+- dspr2
+- dswap
+- dsymm
+- dsymv
+- dsyr
+- dsyr2
+- dsyr2k
+- dsyrk
+- dtbmv
+- dtbsv
+- dtpmv
+- dtpsv
+- dtrmm
+- dtrmv
+- dtrsm
+- dtrsv
+- dzasum
+- dznrm2
+- icamax
+- idamax
+- isamax
+- izamax
+- lsame
+- sasum
+- saxpy
+- scasum
+- scnrm2
+- scopy
+- sdot
+- sdsdot
+- sgbmv
+- sgemm
+- sgemv
+- sger
+- snrm2
+- srot
+- srotg
+- srotm
+- srotmg
+- ssbmv
+- sscal
+- sspmv
+- sspr
+- sspr2
+- sswap
+- ssymm
+- ssymv
+- ssyr
+- ssyr2
+- ssyr2k
+- ssyrk
+- stbmv
+- stbsv
+- stpmv
+- stpsv
+- strmm
+- strmv
+- strsm
+- strsv
+- zaxpy
+- zcopy
+- zdotc
+- zdotu
+- zdrot
+- zdscal
+- zgbmv
+- zgemm
+- zgemv
+- zgerc
+- zgeru
+- zhbmv
+- zhemm
+- zhemv
+- zher
+- zher2
+- zher2k
+- zherk
+- zhpmv
+- zhpr
+- zhpr2
+- zrotg
+- zscal
+- zswap
+- zsymm
+- zsyr2k
+- zsyrk
+- ztbmv
+- ztbsv
+- ztpmv
+- ztpsv
+- ztrmm
+- ztrmv
+- ztrsm
+- ztrsv
+
+
+"""
+
+# Within SciPy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_blas
+# from scipy.linalg cimport cython_blas
+# cimport scipy.linalg.cython_blas as cython_blas
+# cimport ..linalg.cython_blas as cython_blas
+
+# Within SciPy, if BLAS functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+cdef extern from "fortran_defs.h":
+    pass
+
+from numpy cimport npy_complex64, npy_complex128
+
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_caxpy "BLAS_FUNC(caxpy)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef void caxpy(int *n, c *ca, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    
+    _fortran_caxpy(n, ca, cx, incx, cy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ccopy "BLAS_FUNC(ccopy)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef void ccopy(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    
+    _fortran_ccopy(n, cx, incx, cy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cdotc "F_FUNC(cdotcwrp,CDOTCWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef c cdotc(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    cdef c out
+    _fortran_cdotc(&out, n, cx, incx, cy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cdotu "F_FUNC(cdotuwrp,CDOTUWRP)"(npy_complex64 *out, int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef c cdotu(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    cdef c out
+    _fortran_cdotu(&out, n, cx, incx, cy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgbmv "BLAS_FUNC(cgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void cgbmv(char *trans, int *m, int *n, int *kl, int *ku, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_cgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgemm "BLAS_FUNC(cgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void cgemm(char *transa, char *transb, int *m, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_cgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgemv "BLAS_FUNC(cgemv)"(char *trans, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void cgemv(char *trans, int *m, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_cgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgerc "BLAS_FUNC(cgerc)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
+cdef void cgerc(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cgerc(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cgeru "BLAS_FUNC(cgeru)"(int *m, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
+cdef void cgeru(int *m, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cgeru(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chbmv "BLAS_FUNC(chbmv)"(char *uplo, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void chbmv(char *uplo, int *n, int *k, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_chbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chemm "BLAS_FUNC(chemm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void chemm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_chemm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chemv "BLAS_FUNC(chemv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void chemv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_chemv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cher "BLAS_FUNC(cher)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogil
+cdef void cher(char *uplo, int *n, s *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cher(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cher2 "BLAS_FUNC(cher2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *a, int *lda) nogil
+cdef void cher2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *a, int *lda) noexcept nogil:
+    
+    _fortran_cher2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cher2k "BLAS_FUNC(cher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *beta, npy_complex64 *c, int *ldc) nogil
+cdef void cher2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, s *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_cher2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cherk "BLAS_FUNC(cherk)"(char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c, int *ldc) nogil
+cdef void cherk(char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_cherk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chpmv "BLAS_FUNC(chpmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void chpmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_chpmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chpr "BLAS_FUNC(chpr)"(char *uplo, int *n, s *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogil
+cdef void chpr(char *uplo, int *n, s *alpha, c *x, int *incx, c *ap) noexcept nogil:
+    
+    _fortran_chpr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_chpr2 "BLAS_FUNC(chpr2)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, npy_complex64 *ap) nogil
+cdef void chpr2(char *uplo, int *n, c *alpha, c *x, int *incx, c *y, int *incy, c *ap) noexcept nogil:
+    
+    _fortran_chpr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_crotg "BLAS_FUNC(crotg)"(npy_complex64 *ca, npy_complex64 *cb, s *c, npy_complex64 *s) nogil
+cdef void crotg(c *ca, c *cb, s *c, c *s) noexcept nogil:
+    
+    _fortran_crotg(ca, cb, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cscal "BLAS_FUNC(cscal)"(int *n, npy_complex64 *ca, npy_complex64 *cx, int *incx) nogil
+cdef void cscal(int *n, c *ca, c *cx, int *incx) noexcept nogil:
+    
+    _fortran_cscal(n, ca, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csrot "BLAS_FUNC(csrot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, s *s) nogil
+cdef void csrot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, s *s) noexcept nogil:
+    
+    _fortran_csrot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csscal "BLAS_FUNC(csscal)"(int *n, s *sa, npy_complex64 *cx, int *incx) nogil
+cdef void csscal(int *n, s *sa, c *cx, int *incx) noexcept nogil:
+    
+    _fortran_csscal(n, sa, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_cswap "BLAS_FUNC(cswap)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy) nogil
+cdef void cswap(int *n, c *cx, int *incx, c *cy, int *incy) noexcept nogil:
+    
+    _fortran_cswap(n, cx, incx, cy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csymm "BLAS_FUNC(csymm)"(char *side, char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void csymm(char *side, char *uplo, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_csymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csyr2k "BLAS_FUNC(csyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void csyr2k(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *b, int *ldb, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_csyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_csyrk "BLAS_FUNC(csyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *beta, npy_complex64 *c, int *ldc) nogil
+cdef void csyrk(char *uplo, char *trans, int *n, int *k, c *alpha, c *a, int *lda, c *beta, c *c, int *ldc) noexcept nogil:
+    
+    _fortran_csyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctbmv "BLAS_FUNC(ctbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctbmv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctbsv "BLAS_FUNC(ctbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctbsv(char *uplo, char *trans, char *diag, int *n, int *k, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctpmv "BLAS_FUNC(ctpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil
+cdef void ctpmv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctpsv "BLAS_FUNC(ctpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *ap, npy_complex64 *x, int *incx) nogil
+cdef void ctpsv(char *uplo, char *trans, char *diag, int *n, c *ap, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrmm "BLAS_FUNC(ctrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void ctrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_ctrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrmv "BLAS_FUNC(ctrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctrmv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctrmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrsm "BLAS_FUNC(ctrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void ctrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, c *alpha, c *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_ctrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ctrsv "BLAS_FUNC(ctrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx) nogil
+cdef void ctrsv(char *uplo, char *trans, char *diag, int *n, c *a, int *lda, c *x, int *incx) noexcept nogil:
+    
+    _fortran_ctrsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dasum "BLAS_FUNC(dasum)"(int *n, d *dx, int *incx) nogil
+cdef d dasum(int *n, d *dx, int *incx) noexcept nogil:
+    
+    return _fortran_dasum(n, dx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_daxpy "BLAS_FUNC(daxpy)"(int *n, d *da, d *dx, int *incx, d *dy, int *incy) nogil
+cdef void daxpy(int *n, d *da, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    _fortran_daxpy(n, da, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dcabs1 "BLAS_FUNC(dcabs1)"(npy_complex128 *z) nogil
+cdef d dcabs1(z *z) noexcept nogil:
+    
+    return _fortran_dcabs1(z)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dcopy "BLAS_FUNC(dcopy)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
+cdef void dcopy(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    _fortran_dcopy(n, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_ddot "BLAS_FUNC(ddot)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
+cdef d ddot(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    return _fortran_ddot(n, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dgbmv "BLAS_FUNC(dgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dgbmv(char *trans, int *m, int *n, int *kl, int *ku, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dgemm "BLAS_FUNC(dgemm)"(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil
+cdef void dgemm(char *transa, char *transb, int *m, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil:
+    
+    _fortran_dgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dgemv "BLAS_FUNC(dgemv)"(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dgemv(char *trans, int *m, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dger "BLAS_FUNC(dger)"(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil
+cdef void dger(int *m, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dger(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dnrm2 "BLAS_FUNC(dnrm2)"(int *n, d *x, int *incx) nogil
+cdef d dnrm2(int *n, d *x, int *incx) noexcept nogil:
+    
+    return _fortran_dnrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drot "BLAS_FUNC(drot)"(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) nogil
+cdef void drot(int *n, d *dx, int *incx, d *dy, int *incy, d *c, d *s) noexcept nogil:
+    
+    _fortran_drot(n, dx, incx, dy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drotg "BLAS_FUNC(drotg)"(d *da, d *db, d *c, d *s) nogil
+cdef void drotg(d *da, d *db, d *c, d *s) noexcept nogil:
+    
+    _fortran_drotg(da, db, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drotm "BLAS_FUNC(drotm)"(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) nogil
+cdef void drotm(int *n, d *dx, int *incx, d *dy, int *incy, d *dparam) noexcept nogil:
+    
+    _fortran_drotm(n, dx, incx, dy, incy, dparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_drotmg "BLAS_FUNC(drotmg)"(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) nogil
+cdef void drotmg(d *dd1, d *dd2, d *dx1, d *dy1, d *dparam) noexcept nogil:
+    
+    _fortran_drotmg(dd1, dd2, dx1, dy1, dparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsbmv "BLAS_FUNC(dsbmv)"(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dsbmv(char *uplo, int *n, int *k, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dsbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dscal "BLAS_FUNC(dscal)"(int *n, d *da, d *dx, int *incx) nogil
+cdef void dscal(int *n, d *da, d *dx, int *incx) noexcept nogil:
+    
+    _fortran_dscal(n, da, dx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dsdot "BLAS_FUNC(dsdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef d dsdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    return _fortran_dsdot(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dspmv "BLAS_FUNC(dspmv)"(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dspmv(char *uplo, int *n, d *alpha, d *ap, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dspr "BLAS_FUNC(dspr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) nogil
+cdef void dspr(char *uplo, int *n, d *alpha, d *x, int *incx, d *ap) noexcept nogil:
+    
+    _fortran_dspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dspr2 "BLAS_FUNC(dspr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) nogil
+cdef void dspr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *ap) noexcept nogil:
+    
+    _fortran_dspr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dswap "BLAS_FUNC(dswap)"(int *n, d *dx, int *incx, d *dy, int *incy) nogil
+cdef void dswap(int *n, d *dx, int *incx, d *dy, int *incy) noexcept nogil:
+    
+    _fortran_dswap(n, dx, incx, dy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsymm "BLAS_FUNC(dsymm)"(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil
+cdef void dsymm(char *side, char *uplo, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil:
+    
+    _fortran_dsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsymv "BLAS_FUNC(dsymv)"(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) nogil
+cdef void dsymv(char *uplo, int *n, d *alpha, d *a, int *lda, d *x, int *incx, d *beta, d *y, int *incy) noexcept nogil:
+    
+    _fortran_dsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyr "BLAS_FUNC(dsyr)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) nogil
+cdef void dsyr(char *uplo, int *n, d *alpha, d *x, int *incx, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dsyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyr2 "BLAS_FUNC(dsyr2)"(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) nogil
+cdef void dsyr2(char *uplo, int *n, d *alpha, d *x, int *incx, d *y, int *incy, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dsyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyr2k "BLAS_FUNC(dsyr2k)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) nogil
+cdef void dsyr2k(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *b, int *ldb, d *beta, d *c, int *ldc) noexcept nogil:
+    
+    _fortran_dsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dsyrk "BLAS_FUNC(dsyrk)"(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) nogil
+cdef void dsyrk(char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c, int *ldc) noexcept nogil:
+    
+    _fortran_dsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtbmv "BLAS_FUNC(dtbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtbmv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtbsv "BLAS_FUNC(dtbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtbsv(char *uplo, char *trans, char *diag, int *n, int *k, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtpmv "BLAS_FUNC(dtpmv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil
+cdef void dtpmv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtpsv "BLAS_FUNC(dtpsv)"(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) nogil
+cdef void dtpsv(char *uplo, char *trans, char *diag, int *n, d *ap, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrmm "BLAS_FUNC(dtrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogil
+cdef void dtrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dtrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrmv "BLAS_FUNC(dtrmv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtrmv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtrmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrsm "BLAS_FUNC(dtrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) nogil
+cdef void dtrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, d *alpha, d *a, int *lda, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dtrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_dtrsv "BLAS_FUNC(dtrsv)"(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) nogil
+cdef void dtrsv(char *uplo, char *trans, char *diag, int *n, d *a, int *lda, d *x, int *incx) noexcept nogil:
+    
+    _fortran_dtrsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dzasum "BLAS_FUNC(dzasum)"(int *n, npy_complex128 *zx, int *incx) nogil
+cdef d dzasum(int *n, z *zx, int *incx) noexcept nogil:
+    
+    return _fortran_dzasum(n, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    d _fortran_dznrm2 "BLAS_FUNC(dznrm2)"(int *n, npy_complex128 *x, int *incx) nogil
+cdef d dznrm2(int *n, z *x, int *incx) noexcept nogil:
+    
+    return _fortran_dznrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_icamax "BLAS_FUNC(icamax)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef int icamax(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_icamax(n, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_idamax "BLAS_FUNC(idamax)"(int *n, d *dx, int *incx) nogil
+cdef int idamax(int *n, d *dx, int *incx) noexcept nogil:
+    
+    return _fortran_idamax(n, dx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_isamax "BLAS_FUNC(isamax)"(int *n, s *sx, int *incx) nogil
+cdef int isamax(int *n, s *sx, int *incx) noexcept nogil:
+    
+    return _fortran_isamax(n, sx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    int _fortran_izamax "BLAS_FUNC(izamax)"(int *n, npy_complex128 *zx, int *incx) nogil
+cdef int izamax(int *n, z *zx, int *incx) noexcept nogil:
+    
+    return _fortran_izamax(n, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    bint _fortran_lsame "BLAS_FUNC(lsame)"(char *ca, char *cb) nogil
+cdef bint lsame(char *ca, char *cb) noexcept nogil:
+    
+    return _fortran_lsame(ca, cb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_sasum "BLAS_FUNC(sasum)"(int *n, s *sx, int *incx) nogil
+cdef s sasum(int *n, s *sx, int *incx) noexcept nogil:
+    
+    return _fortran_sasum(n, sx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_saxpy "BLAS_FUNC(saxpy)"(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) nogil
+cdef void saxpy(int *n, s *sa, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    _fortran_saxpy(n, sa, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_scasum "BLAS_FUNC(scasum)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef s scasum(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_scasum(n, cx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_scnrm2 "BLAS_FUNC(scnrm2)"(int *n, npy_complex64 *x, int *incx) nogil
+cdef s scnrm2(int *n, c *x, int *incx) noexcept nogil:
+    
+    return _fortran_scnrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_scopy "BLAS_FUNC(scopy)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef void scopy(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    _fortran_scopy(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_sdot "BLAS_FUNC(sdot)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef s sdot(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    return _fortran_sdot(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_sdsdot "BLAS_FUNC(sdsdot)"(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) nogil
+cdef s sdsdot(int *n, s *sb, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    return _fortran_sdsdot(n, sb, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sgbmv "BLAS_FUNC(sgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void sgbmv(char *trans, int *m, int *n, int *kl, int *ku, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_sgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sgemm "BLAS_FUNC(sgemm)"(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil
+cdef void sgemm(char *transa, char *transb, int *m, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil:
+    
+    _fortran_sgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sgemv "BLAS_FUNC(sgemv)"(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void sgemv(char *trans, int *m, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_sgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sger "BLAS_FUNC(sger)"(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil
+cdef void sger(int *m, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil:
+    
+    _fortran_sger(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    s _fortran_snrm2 "BLAS_FUNC(snrm2)"(int *n, s *x, int *incx) nogil
+cdef s snrm2(int *n, s *x, int *incx) noexcept nogil:
+    
+    return _fortran_snrm2(n, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srot "BLAS_FUNC(srot)"(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) nogil
+cdef void srot(int *n, s *sx, int *incx, s *sy, int *incy, s *c, s *s) noexcept nogil:
+    
+    _fortran_srot(n, sx, incx, sy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srotg "BLAS_FUNC(srotg)"(s *sa, s *sb, s *c, s *s) nogil
+cdef void srotg(s *sa, s *sb, s *c, s *s) noexcept nogil:
+    
+    _fortran_srotg(sa, sb, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srotm "BLAS_FUNC(srotm)"(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) nogil
+cdef void srotm(int *n, s *sx, int *incx, s *sy, int *incy, s *sparam) noexcept nogil:
+    
+    _fortran_srotm(n, sx, incx, sy, incy, sparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_srotmg "BLAS_FUNC(srotmg)"(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) nogil
+cdef void srotmg(s *sd1, s *sd2, s *sx1, s *sy1, s *sparam) noexcept nogil:
+    
+    _fortran_srotmg(sd1, sd2, sx1, sy1, sparam)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssbmv "BLAS_FUNC(ssbmv)"(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void ssbmv(char *uplo, int *n, int *k, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_ssbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sscal "BLAS_FUNC(sscal)"(int *n, s *sa, s *sx, int *incx) nogil
+cdef void sscal(int *n, s *sa, s *sx, int *incx) noexcept nogil:
+    
+    _fortran_sscal(n, sa, sx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sspmv "BLAS_FUNC(sspmv)"(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void sspmv(char *uplo, int *n, s *alpha, s *ap, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_sspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sspr "BLAS_FUNC(sspr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) nogil
+cdef void sspr(char *uplo, int *n, s *alpha, s *x, int *incx, s *ap) noexcept nogil:
+    
+    _fortran_sspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sspr2 "BLAS_FUNC(sspr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) nogil
+cdef void sspr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *ap) noexcept nogil:
+    
+    _fortran_sspr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_sswap "BLAS_FUNC(sswap)"(int *n, s *sx, int *incx, s *sy, int *incy) nogil
+cdef void sswap(int *n, s *sx, int *incx, s *sy, int *incy) noexcept nogil:
+    
+    _fortran_sswap(n, sx, incx, sy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssymm "BLAS_FUNC(ssymm)"(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil
+cdef void ssymm(char *side, char *uplo, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil:
+    
+    _fortran_ssymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssymv "BLAS_FUNC(ssymv)"(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) nogil
+cdef void ssymv(char *uplo, int *n, s *alpha, s *a, int *lda, s *x, int *incx, s *beta, s *y, int *incy) noexcept nogil:
+    
+    _fortran_ssymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyr "BLAS_FUNC(ssyr)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) nogil
+cdef void ssyr(char *uplo, int *n, s *alpha, s *x, int *incx, s *a, int *lda) noexcept nogil:
+    
+    _fortran_ssyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyr2 "BLAS_FUNC(ssyr2)"(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) nogil
+cdef void ssyr2(char *uplo, int *n, s *alpha, s *x, int *incx, s *y, int *incy, s *a, int *lda) noexcept nogil:
+    
+    _fortran_ssyr2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyr2k "BLAS_FUNC(ssyr2k)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) nogil
+cdef void ssyr2k(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *b, int *ldb, s *beta, s *c, int *ldc) noexcept nogil:
+    
+    _fortran_ssyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ssyrk "BLAS_FUNC(ssyrk)"(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) nogil
+cdef void ssyrk(char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c, int *ldc) noexcept nogil:
+    
+    _fortran_ssyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stbmv "BLAS_FUNC(stbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil
+cdef void stbmv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stbsv "BLAS_FUNC(stbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) nogil
+cdef void stbsv(char *uplo, char *trans, char *diag, int *n, int *k, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stpmv "BLAS_FUNC(stpmv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil
+cdef void stpmv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_stpsv "BLAS_FUNC(stpsv)"(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) nogil
+cdef void stpsv(char *uplo, char *trans, char *diag, int *n, s *ap, s *x, int *incx) noexcept nogil:
+    
+    _fortran_stpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strmm "BLAS_FUNC(strmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogil
+cdef void strmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_strmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strmv "BLAS_FUNC(strmv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil
+cdef void strmv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_strmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strsm "BLAS_FUNC(strsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) nogil
+cdef void strsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, s *alpha, s *a, int *lda, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_strsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_strsv "BLAS_FUNC(strsv)"(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) nogil
+cdef void strsv(char *uplo, char *trans, char *diag, int *n, s *a, int *lda, s *x, int *incx) noexcept nogil:
+    
+    _fortran_strsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zaxpy "BLAS_FUNC(zaxpy)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef void zaxpy(int *n, z *za, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    
+    _fortran_zaxpy(n, za, zx, incx, zy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zcopy "BLAS_FUNC(zcopy)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef void zcopy(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    
+    _fortran_zcopy(n, zx, incx, zy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdotc "F_FUNC(zdotcwrp,ZDOTCWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef z zdotc(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    cdef z out
+    _fortran_zdotc(&out, n, zx, incx, zy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdotu "F_FUNC(zdotuwrp,ZDOTUWRP)"(npy_complex128 *out, int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef z zdotu(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    cdef z out
+    _fortran_zdotu(&out, n, zx, incx, zy, incy)
+    return out
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdrot "BLAS_FUNC(zdrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, d *s) nogil
+cdef void zdrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, d *s) noexcept nogil:
+    
+    _fortran_zdrot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zdscal "BLAS_FUNC(zdscal)"(int *n, d *da, npy_complex128 *zx, int *incx) nogil
+cdef void zdscal(int *n, d *da, z *zx, int *incx) noexcept nogil:
+    
+    _fortran_zdscal(n, da, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgbmv "BLAS_FUNC(zgbmv)"(char *trans, int *m, int *n, int *kl, int *ku, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zgbmv(char *trans, int *m, int *n, int *kl, int *ku, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zgbmv(trans, m, n, kl, ku, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgemm "BLAS_FUNC(zgemm)"(char *transa, char *transb, int *m, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zgemm(char *transa, char *transb, int *m, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zgemm(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgemv "BLAS_FUNC(zgemv)"(char *trans, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zgemv(char *trans, int *m, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zgemv(trans, m, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgerc "BLAS_FUNC(zgerc)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
+cdef void zgerc(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zgerc(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zgeru "BLAS_FUNC(zgeru)"(int *m, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
+cdef void zgeru(int *m, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zgeru(m, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhbmv "BLAS_FUNC(zhbmv)"(char *uplo, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zhbmv(char *uplo, int *n, int *k, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zhbmv(uplo, n, k, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhemm "BLAS_FUNC(zhemm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zhemm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zhemm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhemv "BLAS_FUNC(zhemv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zhemv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zhemv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zher "BLAS_FUNC(zher)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogil
+cdef void zher(char *uplo, int *n, d *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zher(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zher2 "BLAS_FUNC(zher2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *a, int *lda) nogil
+cdef void zher2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zher2(uplo, n, alpha, x, incx, y, incy, a, lda)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zher2k "BLAS_FUNC(zher2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zher2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, d *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zher2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zherk "BLAS_FUNC(zherk)"(char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zherk(char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zherk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhpmv "BLAS_FUNC(zhpmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zhpmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zhpmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhpr "BLAS_FUNC(zhpr)"(char *uplo, int *n, d *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogil
+cdef void zhpr(char *uplo, int *n, d *alpha, z *x, int *incx, z *ap) noexcept nogil:
+    
+    _fortran_zhpr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zhpr2 "BLAS_FUNC(zhpr2)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, npy_complex128 *ap) nogil
+cdef void zhpr2(char *uplo, int *n, z *alpha, z *x, int *incx, z *y, int *incy, z *ap) noexcept nogil:
+    
+    _fortran_zhpr2(uplo, n, alpha, x, incx, y, incy, ap)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zrotg "BLAS_FUNC(zrotg)"(npy_complex128 *ca, npy_complex128 *cb, d *c, npy_complex128 *s) nogil
+cdef void zrotg(z *ca, z *cb, d *c, z *s) noexcept nogil:
+    
+    _fortran_zrotg(ca, cb, c, s)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zscal "BLAS_FUNC(zscal)"(int *n, npy_complex128 *za, npy_complex128 *zx, int *incx) nogil
+cdef void zscal(int *n, z *za, z *zx, int *incx) noexcept nogil:
+    
+    _fortran_zscal(n, za, zx, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zswap "BLAS_FUNC(zswap)"(int *n, npy_complex128 *zx, int *incx, npy_complex128 *zy, int *incy) nogil
+cdef void zswap(int *n, z *zx, int *incx, z *zy, int *incy) noexcept nogil:
+    
+    _fortran_zswap(n, zx, incx, zy, incy)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zsymm "BLAS_FUNC(zsymm)"(char *side, char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zsymm(char *side, char *uplo, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zsymm(side, uplo, m, n, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zsyr2k "BLAS_FUNC(zsyr2k)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zsyr2k(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *b, int *ldb, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zsyr2k(uplo, trans, n, k, alpha, a, lda, b, ldb, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_zsyrk "BLAS_FUNC(zsyrk)"(char *uplo, char *trans, int *n, int *k, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *beta, npy_complex128 *c, int *ldc) nogil
+cdef void zsyrk(char *uplo, char *trans, int *n, int *k, z *alpha, z *a, int *lda, z *beta, z *c, int *ldc) noexcept nogil:
+    
+    _fortran_zsyrk(uplo, trans, n, k, alpha, a, lda, beta, c, ldc)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztbmv "BLAS_FUNC(ztbmv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztbmv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztbmv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztbsv "BLAS_FUNC(ztbsv)"(char *uplo, char *trans, char *diag, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztbsv(char *uplo, char *trans, char *diag, int *n, int *k, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztbsv(uplo, trans, diag, n, k, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztpmv "BLAS_FUNC(ztpmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil
+cdef void ztpmv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztpmv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztpsv "BLAS_FUNC(ztpsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *ap, npy_complex128 *x, int *incx) nogil
+cdef void ztpsv(char *uplo, char *trans, char *diag, int *n, z *ap, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztpsv(uplo, trans, diag, n, ap, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrmm "BLAS_FUNC(ztrmm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void ztrmm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_ztrmm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrmv "BLAS_FUNC(ztrmv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztrmv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztrmv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrsm "BLAS_FUNC(ztrsm)"(char *side, char *uplo, char *transa, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void ztrsm(char *side, char *uplo, char *transa, char *diag, int *m, int *n, z *alpha, z *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_ztrsm(side, uplo, transa, diag, m, n, alpha, a, lda, b, ldb)
+    
+
+cdef extern from "_blas_subroutines.h":
+    void _fortran_ztrsv "BLAS_FUNC(ztrsv)"(char *uplo, char *trans, char *diag, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx) nogil
+cdef void ztrsv(char *uplo, char *trans, char *diag, int *n, z *a, int *lda, z *x, int *incx) noexcept nogil:
+    
+    _fortran_ztrsv(uplo, trans, diag, n, a, lda, x, incx)
+    
+
+
+# Python-accessible wrappers for testing:
+
+cdef inline bint _is_contiguous(double[:,:] a, int axis) noexcept nogil:
+    return (a.strides[axis] == sizeof(a[0,0]) or a.shape[axis] == 1)
+
+cpdef float complex _test_cdotc(float complex[:] cx, float complex[:] cy) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+        int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotc(&n, &cx[0], &incx, &cy[0], &incy)
+
+cpdef float complex _test_cdotu(float complex[:] cx, float complex[:] cy) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+        int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotu(&n, &cx[0], &incx, &cy[0], &incy)
+
+cpdef double _test_dasum(double[:] dx) noexcept nogil:
+    cdef:
+        int n = dx.shape[0]
+        int incx = dx.strides[0] // sizeof(dx[0])
+    return dasum(&n, &dx[0], &incx)
+
+cpdef double _test_ddot(double[:] dx, double[:] dy) noexcept nogil:
+    cdef:
+        int n = dx.shape[0]
+        int incx = dx.strides[0] // sizeof(dx[0])
+        int incy = dy.strides[0] // sizeof(dy[0])
+    return ddot(&n, &dx[0], &incx, &dy[0], &incy)
+
+cpdef int _test_dgemm(double alpha, double[:,:] a, double[:,:] b, double beta,
+                double[:,:] c) except -1 nogil:
+    cdef:
+        char *transa
+        char *transb
+        int m, n, k, lda, ldb, ldc
+        double *a0=&a[0,0]
+        double *b0=&b[0,0]
+        double *c0=&c[0,0]
+    # In the case that c is C contiguous, swap a and b and
+    # swap whether or not each of them is transposed.
+    # This can be done because a.dot(b) = b.T.dot(a.T).T.
+    if _is_contiguous(c, 1):
+        if _is_contiguous(a, 1):
+            transb = 'n'
+            ldb = (&a[1,0]) - a0 if a.shape[0] > 1 else 1
+        elif _is_contiguous(a, 0):
+            transb = 't'
+            ldb = (&a[0,1]) - a0 if a.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'a' is neither C nor Fortran contiguous.")
+        if _is_contiguous(b, 1):
+            transa = 'n'
+            lda = (&b[1,0]) - b0 if b.shape[0] > 1 else 1
+        elif _is_contiguous(b, 0):
+            transa = 't'
+            lda = (&b[0,1]) - b0 if b.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'b' is neither C nor Fortran contiguous.")
+        k = b.shape[0]
+        if k != a.shape[1]:
+            with gil:
+                raise ValueError("Shape mismatch in input arrays.")
+        m = b.shape[1]
+        n = a.shape[0]
+        if n != c.shape[0] or m != c.shape[1]:
+            with gil:
+                raise ValueError("Output array does not have the correct shape.")
+        ldc = (&c[1,0]) - c0 if c.shape[0] > 1 else 1
+        dgemm(transa, transb, &m, &n, &k, &alpha, b0, &lda, a0,
+                   &ldb, &beta, c0, &ldc)
+    elif _is_contiguous(c, 0):
+        if _is_contiguous(a, 1):
+            transa = 't'
+            lda = (&a[1,0]) - a0 if a.shape[0] > 1 else 1
+        elif _is_contiguous(a, 0):
+            transa = 'n'
+            lda = (&a[0,1]) - a0 if a.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'a' is neither C nor Fortran contiguous.")
+        if _is_contiguous(b, 1):
+            transb = 't'
+            ldb = (&b[1,0]) - b0 if b.shape[0] > 1 else 1
+        elif _is_contiguous(b, 0):
+            transb = 'n'
+            ldb = (&b[0,1]) - b0 if b.shape[1] > 1 else 1
+        else:
+            with gil:
+                raise ValueError("Input 'b' is neither C nor Fortran contiguous.")
+        m = a.shape[0]
+        k = a.shape[1]
+        if k != b.shape[0]:
+            with gil:
+                raise ValueError("Shape mismatch in input arrays.")
+        n = b.shape[1]
+        if m != c.shape[0] or n != c.shape[1]:
+            with gil:
+                raise ValueError("Output array does not have the correct shape.")
+        ldc = (&c[0,1]) - c0 if c.shape[1] > 1 else 1
+        dgemm(transa, transb, &m, &n, &k, &alpha, a0, &lda, b0,
+                   &ldb, &beta, c0, &ldc)
+    else:
+        with gil:
+            raise ValueError("Input 'c' is neither C nor Fortran contiguous.")
+    return 0
+
+cpdef double _test_dnrm2(double[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return dnrm2(&n, &x[0], &incx)
+
+cpdef double _test_dzasum(double complex[:] zx) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+    return dzasum(&n, &zx[0], &incx)
+
+cpdef double _test_dznrm2(double complex[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return dznrm2(&n, &x[0], &incx)
+
+cpdef int _test_icamax(float complex[:] cx) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+    return icamax(&n, &cx[0], &incx)
+
+cpdef int _test_idamax(double[:] dx) noexcept nogil:
+    cdef:
+        int n = dx.shape[0]
+        int incx = dx.strides[0] // sizeof(dx[0])
+    return idamax(&n, &dx[0], &incx)
+
+cpdef int _test_isamax(float[:] sx) noexcept nogil:
+    cdef:
+        int n = sx.shape[0]
+        int incx = sx.strides[0] // sizeof(sx[0])
+    return isamax(&n, &sx[0], &incx)
+
+cpdef int _test_izamax(double complex[:] zx) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+    return izamax(&n, &zx[0], &incx)
+
+cpdef float _test_sasum(float[:] sx) noexcept nogil:
+    cdef:
+        int n = sx.shape[0]
+        int incx = sx.strides[0] // sizeof(sx[0])
+    return sasum(&n, &sx[0], &incx)
+
+cpdef float _test_scasum(float complex[:] cx) noexcept nogil:
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+    return scasum(&n, &cx[0], &incx)
+
+cpdef float _test_scnrm2(float complex[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return scnrm2(&n, &x[0], &incx)
+
+cpdef float _test_sdot(float[:] sx, float[:] sy) noexcept nogil:
+    cdef:
+        int n = sx.shape[0]
+        int incx = sx.strides[0] // sizeof(sx[0])
+        int incy = sy.strides[0] // sizeof(sy[0])
+    return sdot(&n, &sx[0], &incx, &sy[0], &incy)
+
+cpdef float _test_snrm2(float[:] x) noexcept nogil:
+    cdef:
+        int n = x.shape[0]
+        int incx = x.strides[0] // sizeof(x[0])
+    return snrm2(&n, &x[0], &incx)
+
+cpdef double complex _test_zdotc(double complex[:] zx, double complex[:] zy) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+        int incy = zy.strides[0] // sizeof(zy[0])
+    return zdotc(&n, &zx[0], &incx, &zy[0], &incy)
+
+cpdef double complex _test_zdotu(double complex[:] zx, double complex[:] zy) noexcept nogil:
+    cdef:
+        int n = zx.shape[0]
+        int incx = zx.strides[0] // sizeof(zx[0])
+        int incy = zy.strides[0] // sizeof(zy[0])
+    return zdotu(&n, &zx[0], &incx, &zy[0], &incy)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..7964c52d766cd1b08bda6411960a29dbeb6bfe2d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pxd
@@ -0,0 +1,1528 @@
+"""
+This file was generated by _generate_pyx.py.
+Do not edit this file directly.
+"""
+
+# Within SciPy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_lapack
+# from scipy.linalg cimport cython_lapack
+# cimport scipy.linalg.cython_lapack as cython_lapack
+# cimport ..linalg.cython_lapack as cython_lapack
+
+# Within SciPy, if LAPACK functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+ctypedef float s
+ctypedef double d
+ctypedef float complex c
+ctypedef double complex z
+
+# Function pointer type declarations for
+# gees and gges families of functions.
+ctypedef bint cselect1(c*)
+ctypedef bint cselect2(c*, c*)
+ctypedef bint dselect2(d*, d*)
+ctypedef bint dselect3(d*, d*, d*)
+ctypedef bint sselect2(s*, s*)
+ctypedef bint sselect3(s*, s*, s*)
+ctypedef bint zselect1(z*)
+ctypedef bint zselect2(z*, z*)
+
+cdef void cbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) noexcept nogil
+cdef void cbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, c *vt, int *ldvt, c *u, int *ldu, c *c, int *ldc, s *rwork, int *info) noexcept nogil
+cdef void cgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *pt, int *ldpt, c *c, int *ldc, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbcon(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbequ(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgbequb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbsv(int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgbtf2(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void cgbtrf(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void cgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, c *v, int *ldv, int *info) noexcept nogil
+cdef void cgebal(char *job, int *n, c *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil
+cdef void cgebd2(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *info) noexcept nogil
+cdef void cgebrd(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgecon(char *norm, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgeequ(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgeequb(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void cgees(char *jobvs, char *sort, cselect1 *select, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil
+cdef void cgeesx(char *jobvs, char *sort, cselect1 *select, char *sense, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil
+cdef void cgeev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgehd2(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgehrd(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgelq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgelqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgels(char *trans, int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgelsd(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void cgelss(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgelsy(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *jpvt, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cgeql2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgeqlf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgeqp3(int *m, int *n, c *a, int *lda, int *jpvt, c *tau, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgeqr2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgeqr2p(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgeqrf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgeqrfp(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgeqrt(int *m, int *n, int *nb, c *a, int *lda, c *t, int *ldt, c *work, int *info) noexcept nogil
+cdef void cgeqrt2(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil
+cdef void cgeqrt3(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil
+cdef void cgerfs(char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgerq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cgerqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgesc2(int *n, c *a, int *lda, c *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil
+cdef void cgesdd(char *jobz, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void cgesv(int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgesvd(char *jobu, char *jobvt, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cgesvx(char *fact, char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgetc2(int *n, c *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void cgetf2(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void cgetrf(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void cgetri(int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgetrs(char *trans, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, c *v, int *ldv, int *info) noexcept nogil
+cdef void cggbal(char *job, int *n, c *a, int *lda, c *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil
+cdef void cgges(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil
+cdef void cggesx(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, char *sense, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void cggev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void cggglm(int *n, int *m, int *p, c *a, int *lda, c *b, int *ldb, c *d, c *x, c *y, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *info) noexcept nogil
+cdef void cgglse(int *m, int *n, int *p, c *a, int *lda, c *b, int *ldb, c *c, c *d, c *x, c *work, int *lwork, int *info) noexcept nogil
+cdef void cggqrf(int *n, int *m, int *p, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil
+cdef void cggrqf(int *m, int *p, int *n, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil
+cdef void cgtcon(char *norm, int *n, c *dl, c *d, c *du, c *du2, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void cgtrfs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgtsv(int *n, int *nrhs, c *dl, c *d, c *du, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgtsvx(char *fact, char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cgttrf(int *n, c *dl, c *d, c *du, c *du2, int *ipiv, int *info) noexcept nogil
+cdef void cgttrs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cgtts2(int *itrans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb) noexcept nogil
+cdef void chbev(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chbevd(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chbevx(char *jobz, char *range, char *uplo, int *n, int *kd, c *ab, int *ldab, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chbgst(char *vect, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *x, int *ldx, c *work, s *rwork, int *info) noexcept nogil
+cdef void chbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chbtrd(char *vect, char *uplo, int *n, int *kd, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *work, int *info) noexcept nogil
+cdef void checon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void cheequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil
+cdef void cheev(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cheevd(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cheevr(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cheevx(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chegs2(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void chegst(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void chegv(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void chegvd(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chegvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void cherfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void chesv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil
+cdef void chesvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void cheswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void chetd2(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, int *info) noexcept nogil
+cdef void chetf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void chetrd(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void chetrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void chetri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil
+cdef void chetri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void chetri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil
+cdef void chetrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void chetrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil
+cdef void chfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c) noexcept nogil
+cdef void chgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *t, int *ldt, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef char chla_transtype(int *trans) noexcept nogil
+cdef void chpcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void chpev(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chpevd(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chpevx(char *jobz, char *range, char *uplo, int *n, c *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chpgst(int *itype, char *uplo, int *n, c *ap, c *bp, int *info) noexcept nogil
+cdef void chpgv(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil
+cdef void chpgvd(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void chpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *ap, c *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void chprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void chpsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void chpsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void chptrd(char *uplo, int *n, c *ap, s *d, s *e, c *tau, int *info) noexcept nogil
+cdef void chptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil
+cdef void chptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil
+cdef void chptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void chsein(char *side, char *eigsrc, char *initv, bint *select, int *n, c *h, int *ldh, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void chseqr(char *job, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil
+cdef void clabrd(int *m, int *n, int *nb, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *x, int *ldx, c *y, int *ldy) noexcept nogil
+cdef void clacgv(int *n, c *x, int *incx) noexcept nogil
+cdef void clacn2(int *n, c *v, c *x, s *est, int *kase, int *isave) noexcept nogil
+cdef void clacon(int *n, c *v, c *x, s *est, int *kase) noexcept nogil
+cdef void clacp2(char *uplo, int *m, int *n, s *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void clacpy(char *uplo, int *m, int *n, c *a, int *lda, c *b, int *ldb) noexcept nogil
+cdef void clacrm(int *m, int *n, c *a, int *lda, s *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil
+cdef void clacrt(int *n, c *cx, int *incx, c *cy, int *incy, c *c, c *s) noexcept nogil
+cdef c cladiv(c *x, c *y) noexcept nogil
+cdef void claed0(int *qsiz, int *n, s *d, s *e, c *q, int *ldq, c *qstore, int *ldqs, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void claed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, c *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, c *work, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void claed8(int *k, int *n, int *qsiz, c *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, c *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) noexcept nogil
+cdef void claein(bint *rightv, bint *noinit, int *n, c *h, int *ldh, c *w, c *v, c *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) noexcept nogil
+cdef void claesy(c *a, c *b, c *c, c *rt1, c *rt2, c *evscal, c *cs1, c *sn1) noexcept nogil
+cdef void claev2(c *a, c *b, c *c, s *rt1, s *rt2, s *cs1, c *sn1) noexcept nogil
+cdef void clag2z(int *m, int *n, c *sa, int *ldsa, z *a, int *lda, int *info) noexcept nogil
+cdef void clags2(bint *upper, s *a1, c *a2, s *a3, s *b1, c *b2, s *b3, s *csu, c *snu, s *csv, c *snv, s *csq, c *snq) noexcept nogil
+cdef void clagtm(char *trans, int *n, int *nrhs, s *alpha, c *dl, c *d, c *du, c *x, int *ldx, s *beta, c *b, int *ldb) noexcept nogil
+cdef void clahef(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil
+cdef void clahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, int *info) noexcept nogil
+cdef void clahr2(int *n, int *k, int *nb, c *a, int *lda, c *tau, c *t, int *ldt, c *y, int *ldy) noexcept nogil
+cdef void claic1(int *job, int *j, c *x, s *sest, c *w, c *gamma, s *sestpr, c *s, c *c) noexcept nogil
+cdef void clals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) noexcept nogil
+cdef void clalsa(int *icompq, int *smlsiz, int *n, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) noexcept nogil
+cdef void clalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, c *b, int *ldb, s *rcond, int *rank, c *work, s *rwork, int *iwork, int *info) noexcept nogil
+cdef s clangb(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clange(char *norm, int *m, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clangt(char *norm, int *n, c *dl, c *d, c *du) noexcept nogil
+cdef s clanhb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clanhe(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clanhf(char *norm, char *transr, char *uplo, int *n, c *a, s *work) noexcept nogil
+cdef s clanhp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil
+cdef s clanhs(char *norm, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clanht(char *norm, int *n, s *d, c *e) noexcept nogil
+cdef s clansb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clansp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil
+cdef s clansy(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef s clantb(char *norm, char *uplo, char *diag, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil
+cdef s clantp(char *norm, char *uplo, char *diag, int *n, c *ap, s *work) noexcept nogil
+cdef s clantr(char *norm, char *uplo, char *diag, int *m, int *n, c *a, int *lda, s *work) noexcept nogil
+cdef void clapll(int *n, c *x, int *incx, c *y, int *incy, s *ssmin) noexcept nogil
+cdef void clapmr(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil
+cdef void clapmt(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil
+cdef void claqgb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void claqge(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void claqhb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqhe(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqhp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqp2(int *m, int *n, int *offset, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *work) noexcept nogil
+cdef void claqps(int *m, int *n, int *offset, int *nb, int *kb, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *auxv, c *f, int *ldf) noexcept nogil
+cdef void claqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil
+cdef void claqr1(int *n, c *h, int *ldh, c *s1, c *s2, c *v) noexcept nogil
+cdef void claqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil
+cdef void claqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil
+cdef void claqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil
+cdef void claqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, c *s, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, c *v, int *ldv, c *u, int *ldu, int *nv, c *wv, int *ldwv, int *nh, c *wh, int *ldwh) noexcept nogil
+cdef void claqsb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqsp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void claqsy(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void clar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, c *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil
+cdef void clar2v(int *n, c *x, c *y, c *z, int *incx, s *c, c *s, int *incc) noexcept nogil
+cdef void clarcm(int *m, int *n, s *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil
+cdef void clarf(char *side, int *m, int *n, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil
+cdef void clarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil
+cdef void clarfg(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil
+cdef void clarfgp(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil
+cdef void clarft(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil
+cdef void clarfx(char *side, int *m, int *n, c *v, c *tau, c *c, int *ldc, c *work) noexcept nogil
+cdef void clargv(int *n, c *x, int *incx, c *y, int *incy, s *c, int *incc) noexcept nogil
+cdef void clarnv(int *idist, int *iseed, int *n, c *x) noexcept nogil
+cdef void clarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, c *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil
+cdef void clartg(c *f, c *g, s *cs, c *sn, c *r) noexcept nogil
+cdef void clartv(int *n, c *x, int *incx, c *y, int *incy, s *c, c *s, int *incc) noexcept nogil
+cdef void clarz(char *side, int *m, int *n, int *l, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil
+cdef void clarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil
+cdef void clarzt(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil
+cdef void clascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void claset(char *uplo, int *m, int *n, c *alpha, c *beta, c *a, int *lda) noexcept nogil
+cdef void clasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, c *a, int *lda) noexcept nogil
+cdef void classq(int *n, c *x, int *incx, s *scale, s *sumsq) noexcept nogil
+cdef void claswp(int *n, c *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void clasyf(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil
+cdef void clatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, c *ab, int *ldab, c *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void clatdf(int *ijob, int *n, c *z, int *ldz, c *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void clatps(char *uplo, char *trans, char *diag, char *normin, int *n, c *ap, c *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void clatrd(char *uplo, int *n, int *nb, c *a, int *lda, s *e, c *tau, c *w, int *ldw) noexcept nogil
+cdef void clatrs(char *uplo, char *trans, char *diag, char *normin, int *n, c *a, int *lda, c *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void clatrz(int *m, int *n, int *l, c *a, int *lda, c *tau, c *work) noexcept nogil
+cdef void clauu2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void clauum(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpbcon(char *uplo, int *n, int *kd, c *ab, int *ldab, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpbequ(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cpbrfs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpbstf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil
+cdef void cpbsv(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpbtf2(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil
+cdef void cpbtrf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil
+cdef void cpbtrs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpftrf(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil
+cdef void cpftri(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil
+cdef void cpftrs(char *transr, char *uplo, int *n, int *nrhs, c *a, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpocon(char *uplo, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpoequ(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cpoequb(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cporfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cposv(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void cposvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpotf2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpotrf(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpotri(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void cpotrs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void cppcon(char *uplo, int *n, c *ap, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void cppequ(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void cpprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cppsv(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil
+cdef void cppsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpptrf(char *uplo, int *n, c *ap, int *info) noexcept nogil
+cdef void cpptri(char *uplo, int *n, c *ap, int *info) noexcept nogil
+cdef void cpptrs(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil
+cdef void cpstf2(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void cpstrf(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void cptcon(int *n, s *d, c *e, s *anorm, s *rcond, s *rwork, int *info) noexcept nogil
+cdef void cpteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void cptrfs(char *uplo, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cptsv(int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil
+cdef void cptsvx(char *fact, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cpttrf(int *n, s *d, c *e, int *info) noexcept nogil
+cdef void cpttrs(char *uplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil
+cdef void cptts2(int *iuplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb) noexcept nogil
+cdef void crot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, c *s) noexcept nogil
+cdef void cspcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void cspmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void cspr(char *uplo, int *n, c *alpha, c *x, int *incx, c *ap) noexcept nogil
+cdef void csprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void cspsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void cspsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void csptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil
+cdef void csptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil
+cdef void csptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void csrscl(int *n, s *sa, c *sx, int *incx) noexcept nogil
+cdef void cstedc(char *compz, int *n, s *d, s *e, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void cstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, c *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void cstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, c *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void csteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void csycon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil
+cdef void csyconv(char *uplo, char *way, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil
+cdef void csyequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil
+cdef void csymv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil
+cdef void csyr(char *uplo, int *n, c *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil
+cdef void csyrfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void csysv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil
+cdef void csysvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil
+cdef void csyswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void csytf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void csytrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void csytri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil
+cdef void csytri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil
+cdef void csytri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil
+cdef void csytrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil
+cdef void csytrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil
+cdef void ctbcon(char *norm, char *uplo, char *diag, int *n, int *kd, c *ab, int *ldab, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil
+cdef void ctfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, c *alpha, c *a, c *b, int *ldb) noexcept nogil
+cdef void ctftri(char *transr, char *uplo, char *diag, int *n, c *a, int *info) noexcept nogil
+cdef void ctfttp(char *transr, char *uplo, int *n, c *arf, c *ap, int *info) noexcept nogil
+cdef void ctfttr(char *transr, char *uplo, int *n, c *arf, c *a, int *lda, int *info) noexcept nogil
+cdef void ctgevc(char *side, char *howmny, bint *select, int *n, c *s, int *lds, c *p, int *ldp, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctgex2(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *j1, int *info) noexcept nogil
+cdef void ctgexc(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ctgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, int *m, s *pl, s *pr, s *dif, c *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ctgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, c *a, int *lda, c *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, c *u, int *ldu, c *v, int *ldv, c *q, int *ldq, c *work, int *ncycle, int *info) noexcept nogil
+cdef void ctgsna(char *job, char *howmny, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *dif, int *mm, int *m, c *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ctgsy2(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) noexcept nogil
+cdef void ctgsyl(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *dif, c *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ctpcon(char *norm, char *uplo, char *diag, int *n, c *ap, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *info) noexcept nogil
+cdef void ctpqrt(int *m, int *n, int *l, int *nb, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, c *work, int *info) noexcept nogil
+cdef void ctpqrt2(int *m, int *n, int *l, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, int *info) noexcept nogil
+cdef void ctprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *ldwork) noexcept nogil
+cdef void ctprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctptri(char *uplo, char *diag, int *n, c *ap, int *info) noexcept nogil
+cdef void ctptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil
+cdef void ctpttf(char *transr, char *uplo, int *n, c *ap, c *arf, int *info) noexcept nogil
+cdef void ctpttr(char *uplo, int *n, c *ap, c *a, int *lda, int *info) noexcept nogil
+cdef void ctrcon(char *norm, char *uplo, char *diag, int *n, c *a, int *lda, s *rcond, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctrevc(char *side, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctrexc(char *compq, int *n, c *t, int *ldt, c *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ctrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil
+cdef void ctrsen(char *job, char *compq, bint *select, int *n, c *t, int *ldt, c *q, int *ldq, c *w, int *m, s *s, s *sep, c *work, int *lwork, int *info) noexcept nogil
+cdef void ctrsna(char *job, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *sep, int *mm, int *m, c *work, int *ldwork, s *rwork, int *info) noexcept nogil
+cdef void ctrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *scale, int *info) noexcept nogil
+cdef void ctrti2(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void ctrtri(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil
+cdef void ctrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil
+cdef void ctrttf(char *transr, char *uplo, int *n, c *a, int *lda, c *arf, int *info) noexcept nogil
+cdef void ctrttp(char *uplo, int *n, c *a, int *lda, c *ap, int *info) noexcept nogil
+cdef void ctzrzf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunbdb(char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, s *phi, c *taup1, c *taup2, c *tauq1, c *tauq2, c *work, int *lwork, int *info) noexcept nogil
+cdef void cuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) noexcept nogil
+cdef void cung2l(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cung2r(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cungbr(char *vect, int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunghr(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungl2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cunglq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungql(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungqr(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungr2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil
+cdef void cungrq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cungtr(char *uplo, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunm2l(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunm2r(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunml2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmlq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmql(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmqr(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmr2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void cunmrq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cunmtr(char *side, char *uplo, char *trans, int *m, int *n, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil
+cdef void cupgtr(char *uplo, int *n, c *ap, c *tau, c *q, int *ldq, c *work, int *info) noexcept nogil
+cdef void cupmtr(char *side, char *uplo, char *trans, int *m, int *n, c *ap, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil
+cdef void dbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) noexcept nogil
+cdef void dbdsdc(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) noexcept nogil
+cdef void dbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void ddisna(char *job, int *m, int *n, d *d, d *sep, int *info) noexcept nogil
+cdef void dgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dgbcon(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgbequ(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgbequb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgbsv(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgbtf2(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void dgbtrf(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void dgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) noexcept nogil
+cdef void dgebal(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil
+cdef void dgebd2(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) noexcept nogil
+cdef void dgebrd(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgecon(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgeequ(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgeequb(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void dgees(char *jobvs, char *sort, dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void dgeesx(char *jobvs, char *sort, dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void dgeev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgehd2(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgehrd(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgelq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgelqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgels(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgelsd(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgelss(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgelsy(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dgeql2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgeqlf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqp3(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqr2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgeqr2p(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgeqrf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqrfp(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgeqrt(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) noexcept nogil
+cdef void dgeqrt2(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil
+cdef void dgeqrt3(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil
+cdef void dgerfs(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgerq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dgerqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgesc2(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil
+cdef void dgesdd(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgesvd(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgesvx(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgetc2(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void dgetf2(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void dgetrf(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void dgetri(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgetrs(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) noexcept nogil
+cdef void dggbal(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil
+cdef void dgges(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void dggesx(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void dggev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil
+cdef void dggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void dggglm(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) noexcept nogil
+cdef void dgglse(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) noexcept nogil
+cdef void dggqrf(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil
+cdef void dggrqf(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgsvj0(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgsvj1(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil
+cdef void dgtcon(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgtrfs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgtsv(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgtsvx(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dgttrf(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) noexcept nogil
+cdef void dgttrs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dgtts2(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) noexcept nogil
+cdef void dhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef void dhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void dhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef bint disnan(d *din) noexcept nogil
+cdef void dlabad(d *small, d *large) noexcept nogil
+cdef void dlabrd(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) noexcept nogil
+cdef void dlacn2(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) noexcept nogil
+cdef void dlacon(int *n, d *v, d *x, int *isgn, d *est, int *kase) noexcept nogil
+cdef void dlacpy(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) noexcept nogil
+cdef void dladiv(d *a, d *b, d *c, d *d, d *p, d *q) noexcept nogil
+cdef void dlae2(d *a, d *b, d *c, d *rt1, d *rt2) noexcept nogil
+cdef void dlaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed0(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed1(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed2(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil
+cdef void dlaed3(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) noexcept nogil
+cdef void dlaed4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) noexcept nogil
+cdef void dlaed5(int *i, d *d, d *z, d *delta, d *rho, d *dlam) noexcept nogil
+cdef void dlaed6(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) noexcept nogil
+cdef void dlaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlaed8(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) noexcept nogil
+cdef void dlaed9(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) noexcept nogil
+cdef void dlaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) noexcept nogil
+cdef void dlaein(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) noexcept nogil
+cdef void dlaev2(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) noexcept nogil
+cdef void dlaexc(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) noexcept nogil
+cdef void dlag2(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) noexcept nogil
+cdef void dlag2s(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil
+cdef void dlags2(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) noexcept nogil
+cdef void dlagtf(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) noexcept nogil
+cdef void dlagtm(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) noexcept nogil
+cdef void dlagts(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) noexcept nogil
+cdef void dlagv2(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) noexcept nogil
+cdef void dlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) noexcept nogil
+cdef void dlahr2(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) noexcept nogil
+cdef void dlaic1(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) noexcept nogil
+cdef void dlaln2(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) noexcept nogil
+cdef void dlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) noexcept nogil
+cdef void dlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) noexcept nogil
+cdef d dlamch(char *cmach) noexcept nogil
+cdef void dlamrg(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) noexcept nogil
+cdef int dlaneg(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) noexcept nogil
+cdef d dlangb(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) noexcept nogil
+cdef d dlange(char *norm, int *m, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef d dlangt(char *norm, int *n, d *dl, d *d_, d *du) noexcept nogil
+cdef d dlanhs(char *norm, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef d dlansb(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil
+cdef d dlansf(char *norm, char *transr, char *uplo, int *n, d *a, d *work) noexcept nogil
+cdef d dlansp(char *norm, char *uplo, int *n, d *ap, d *work) noexcept nogil
+cdef d dlanst(char *norm, int *n, d *d_, d *e) noexcept nogil
+cdef d dlansy(char *norm, char *uplo, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef d dlantb(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil
+cdef d dlantp(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) noexcept nogil
+cdef d dlantr(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) noexcept nogil
+cdef void dlanv2(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) noexcept nogil
+cdef void dlapll(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) noexcept nogil
+cdef void dlapmr(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil
+cdef void dlapmt(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil
+cdef d dlapy2(d *x, d *y) noexcept nogil
+cdef d dlapy3(d *x, d *y, d *z) noexcept nogil
+cdef void dlaqgb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void dlaqge(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void dlaqp2(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) noexcept nogil
+cdef void dlaqps(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) noexcept nogil
+cdef void dlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef void dlaqr1(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) noexcept nogil
+cdef void dlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil
+cdef void dlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil
+cdef void dlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil
+cdef void dlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) noexcept nogil
+cdef void dlaqsb(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void dlaqsp(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void dlaqsy(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void dlaqtr(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) noexcept nogil
+cdef void dlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil
+cdef void dlar2v(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) noexcept nogil
+cdef void dlarf(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil
+cdef void dlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil
+cdef void dlarfg(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil
+cdef void dlarfgp(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil
+cdef void dlarft(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil
+cdef void dlarfx(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) noexcept nogil
+cdef void dlargv(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) noexcept nogil
+cdef void dlarnv(int *idist, int *iseed, int *n, d *x) noexcept nogil
+cdef void dlarra(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil
+cdef void dlarrb(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) noexcept nogil
+cdef void dlarrc(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil
+cdef void dlarrd(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlarre(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlarrf(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) noexcept nogil
+cdef void dlarrj(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) noexcept nogil
+cdef void dlarrk(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) noexcept nogil
+cdef void dlarrr(int *n, d *d, d *e, int *info) noexcept nogil
+cdef void dlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlartg(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil
+cdef void dlartgp(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil
+cdef void dlartgs(d *x, d *y, d *sigma, d *cs, d *sn) noexcept nogil
+cdef void dlartv(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) noexcept nogil
+cdef void dlaruv(int *iseed, int *n, d *x) noexcept nogil
+cdef void dlarz(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil
+cdef void dlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil
+cdef void dlarzt(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil
+cdef void dlas2(d *f, d *g, d *h, d *ssmin, d *ssmax) noexcept nogil
+cdef void dlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dlasd0(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) noexcept nogil
+cdef void dlasd1(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) noexcept nogil
+cdef void dlasd2(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil
+cdef void dlasd3(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) noexcept nogil
+cdef void dlasd4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) noexcept nogil
+cdef void dlasd5(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) noexcept nogil
+cdef void dlasd6(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) noexcept nogil
+cdef void dlasd8(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) noexcept nogil
+cdef void dlasda(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil
+cdef void dlasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dlasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil
+cdef void dlaset(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) noexcept nogil
+cdef void dlasq1(int *n, d *d, d *e, d *work, int *info) noexcept nogil
+cdef void dlasq2(int *n, d *z, int *info) noexcept nogil
+cdef void dlasq3(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) noexcept nogil
+cdef void dlasq4(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) noexcept nogil
+cdef void dlasq6(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) noexcept nogil
+cdef void dlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) noexcept nogil
+cdef void dlasrt(char *id, int *n, d *d, int *info) noexcept nogil
+cdef void dlassq(int *n, d *x, int *incx, d *scale, d *sumsq) noexcept nogil
+cdef void dlasv2(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) noexcept nogil
+cdef void dlaswp(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void dlasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) noexcept nogil
+cdef void dlasyf(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) noexcept nogil
+cdef void dlat2s(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil
+cdef void dlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void dlatdf(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void dlatps(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void dlatrd(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) noexcept nogil
+cdef void dlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void dlatrz(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) noexcept nogil
+cdef void dlauu2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dlauum(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dopgtr(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) noexcept nogil
+cdef void dopmtr(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dorbdb(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dorg2l(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorg2r(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorgbr(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorghr(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgl2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorglq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgql(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgqr(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgr2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil
+cdef void dorgrq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorgtr(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorm2l(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dorm2r(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dorml2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormlq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormql(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormqr(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormr2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormr3(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil
+cdef void dormrq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormrz(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dormtr(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil
+cdef void dpbcon(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpbequ(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dpbrfs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpbstf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil
+cdef void dpbsv(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpbtf2(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil
+cdef void dpbtrf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil
+cdef void dpbtrs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpftrf(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil
+cdef void dpftri(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil
+cdef void dpftrs(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpocon(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpoequ(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dpoequb(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dporfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dposvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpotf2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dpotrf(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dpotri(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dpotrs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dppcon(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dppequ(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void dpprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dppsv(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil
+cdef void dppsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dpptrf(char *uplo, int *n, d *ap, int *info) noexcept nogil
+cdef void dpptri(char *uplo, int *n, d *ap, int *info) noexcept nogil
+cdef void dpptrs(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil
+cdef void dpstf2(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void dpstrf(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void dptcon(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) noexcept nogil
+cdef void dpteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dptrfs(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) noexcept nogil
+cdef void dptsv(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil
+cdef void dptsvx(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) noexcept nogil
+cdef void dpttrf(int *n, d *d, d *e, int *info) noexcept nogil
+cdef void dpttrs(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil
+cdef void dptts2(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) noexcept nogil
+cdef void drscl(int *n, d *sa, d *sx, int *incx) noexcept nogil
+cdef void dsbev(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dsbevd(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsbevx(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsbgst(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) noexcept nogil
+cdef void dsbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dsbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsbtrd(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) noexcept nogil
+cdef void dsfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) noexcept nogil
+cdef void dsgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil
+cdef void dspcon(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dspev(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dspevd(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dspevx(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dspgst(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) noexcept nogil
+cdef void dspgv(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dspgvd(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil
+cdef void dsprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dspsv(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dspsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dsptrd(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) noexcept nogil
+cdef void dsptrf(char *uplo, int *n, d *ap, int *ipiv, int *info) noexcept nogil
+cdef void dsptri(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) noexcept nogil
+cdef void dsptrs(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dstebz(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) noexcept nogil
+cdef void dstedc(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dsterf(int *n, d *d, d *e, int *info) noexcept nogil
+cdef void dstev(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void dstevd(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstevr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dstevx(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsycon(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dsyconv(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil
+cdef void dsyequb(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) noexcept nogil
+cdef void dsyev(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsyevd(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsyevr(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsyevx(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsygs2(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dsygst(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dsygv(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsygvd(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dsygvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void dsyrfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dsysv(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsysvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dsyswapr(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void dsytd2(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) noexcept nogil
+cdef void dsytf2(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void dsytrd(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsytrf(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsytri(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil
+cdef void dsytri2(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil
+cdef void dsytri2x(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) noexcept nogil
+cdef void dsytrs(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil
+cdef void dsytrs2(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) noexcept nogil
+cdef void dtbcon(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil
+cdef void dtfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) noexcept nogil
+cdef void dtftri(char *transr, char *uplo, char *diag, int *n, d *a, int *info) noexcept nogil
+cdef void dtfttp(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) noexcept nogil
+cdef void dtfttr(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) noexcept nogil
+cdef void dtgevc(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil
+cdef void dtgex2(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) noexcept nogil
+cdef void dtgexc(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) noexcept nogil
+cdef void dtgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dtgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) noexcept nogil
+cdef void dtgsna(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dtgsy2(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) noexcept nogil
+cdef void dtgsyl(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void dtpcon(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) noexcept nogil
+cdef void dtpqrt(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) noexcept nogil
+cdef void dtpqrt2(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) noexcept nogil
+cdef void dtprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) noexcept nogil
+cdef void dtprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtptri(char *uplo, char *diag, int *n, d *ap, int *info) noexcept nogil
+cdef void dtptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil
+cdef void dtpttf(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) noexcept nogil
+cdef void dtpttr(char *uplo, int *n, d *ap, d *a, int *lda, int *info) noexcept nogil
+cdef void dtrcon(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtrevc(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil
+cdef void dtrexc(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) noexcept nogil
+cdef void dtrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil
+cdef void dtrsen(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void dtrsna(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) noexcept nogil
+cdef void dtrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) noexcept nogil
+cdef void dtrti2(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dtrtri(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil
+cdef void dtrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil
+cdef void dtrttf(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) noexcept nogil
+cdef void dtrttp(char *uplo, int *n, d *a, int *lda, d *ap, int *info) noexcept nogil
+cdef void dtzrzf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil
+cdef d dzsum1(int *n, z *cx, int *incx) noexcept nogil
+cdef int icmax1(int *n, c *cx, int *incx) noexcept nogil
+cdef int ieeeck(int *ispec, s *zero, s *one) noexcept nogil
+cdef int ilaclc(int *m, int *n, c *a, int *lda) noexcept nogil
+cdef int ilaclr(int *m, int *n, c *a, int *lda) noexcept nogil
+cdef int iladiag(char *diag) noexcept nogil
+cdef int iladlc(int *m, int *n, d *a, int *lda) noexcept nogil
+cdef int iladlr(int *m, int *n, d *a, int *lda) noexcept nogil
+cdef int ilaprec(char *prec) noexcept nogil
+cdef int ilaslc(int *m, int *n, s *a, int *lda) noexcept nogil
+cdef int ilaslr(int *m, int *n, s *a, int *lda) noexcept nogil
+cdef int ilatrans(char *trans) noexcept nogil
+cdef int ilauplo(char *uplo) noexcept nogil
+cdef void ilaver(int *vers_major, int *vers_minor, int *vers_patch) noexcept nogil
+cdef int ilazlc(int *m, int *n, z *a, int *lda) noexcept nogil
+cdef int ilazlr(int *m, int *n, z *a, int *lda) noexcept nogil
+cdef int izmax1(int *n, z *cx, int *incx) noexcept nogil
+cdef void sbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) noexcept nogil
+cdef void sbdsdc(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) noexcept nogil
+cdef void sbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef s scsum1(int *n, c *cx, int *incx) noexcept nogil
+cdef void sdisna(char *job, int *m, int *n, s *d, s *sep, int *info) noexcept nogil
+cdef void sgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sgbcon(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgbequ(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgbequb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgbsv(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgbtf2(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void sgbtrf(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void sgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) noexcept nogil
+cdef void sgebal(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil
+cdef void sgebd2(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) noexcept nogil
+cdef void sgebrd(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgecon(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgeequ(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgeequb(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil
+cdef void sgees(char *jobvs, char *sort, sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void sgeesx(char *jobvs, char *sort, sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void sgeev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgehd2(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgehrd(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgelq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgelqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgels(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgelsd(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgelss(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgelsy(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sgeql2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgeqlf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqp3(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqr2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgeqr2p(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgeqrf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqrfp(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgeqrt(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) noexcept nogil
+cdef void sgeqrt2(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil
+cdef void sgeqrt3(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil
+cdef void sgerfs(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgerq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sgerqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgesc2(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil
+cdef void sgesdd(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sgesv(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgesvd(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgesvx(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgetc2(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void sgetf2(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void sgetrf(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void sgetri(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgetrs(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) noexcept nogil
+cdef void sggbal(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil
+cdef void sgges(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) noexcept nogil
+cdef void sggesx(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void sggev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil
+cdef void sggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void sggglm(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) noexcept nogil
+cdef void sgglse(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) noexcept nogil
+cdef void sggqrf(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil
+cdef void sggrqf(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgsvj0(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgsvj1(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil
+cdef void sgtcon(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgtrfs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgtsv(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgtsvx(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sgttrf(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) noexcept nogil
+cdef void sgttrs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sgtts2(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) noexcept nogil
+cdef void shgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void shsein(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void shseqr(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void slabad(s *small, s *large) noexcept nogil
+cdef void slabrd(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) noexcept nogil
+cdef void slacn2(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) noexcept nogil
+cdef void slacon(int *n, s *v, s *x, int *isgn, s *est, int *kase) noexcept nogil
+cdef void slacpy(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) noexcept nogil
+cdef void sladiv(s *a, s *b, s *c, s *d, s *p, s *q) noexcept nogil
+cdef void slae2(s *a, s *b, s *c, s *rt1, s *rt2) noexcept nogil
+cdef void slaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed0(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed1(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed2(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil
+cdef void slaed3(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) noexcept nogil
+cdef void slaed4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) noexcept nogil
+cdef void slaed5(int *i, s *d, s *z, s *delta, s *rho, s *dlam) noexcept nogil
+cdef void slaed6(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) noexcept nogil
+cdef void slaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) noexcept nogil
+cdef void slaed8(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) noexcept nogil
+cdef void slaed9(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) noexcept nogil
+cdef void slaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) noexcept nogil
+cdef void slaein(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) noexcept nogil
+cdef void slaev2(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) noexcept nogil
+cdef void slaexc(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) noexcept nogil
+cdef void slag2(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) noexcept nogil
+cdef void slag2d(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) noexcept nogil
+cdef void slags2(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) noexcept nogil
+cdef void slagtf(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) noexcept nogil
+cdef void slagtm(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) noexcept nogil
+cdef void slagts(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) noexcept nogil
+cdef void slagv2(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) noexcept nogil
+cdef void slahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) noexcept nogil
+cdef void slahr2(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) noexcept nogil
+cdef void slaic1(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) noexcept nogil
+cdef void slaln2(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) noexcept nogil
+cdef void slals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) noexcept nogil
+cdef void slalsa(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil
+cdef void slalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) noexcept nogil
+cdef s slamch(char *cmach) noexcept nogil
+cdef void slamrg(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) noexcept nogil
+cdef s slangb(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) noexcept nogil
+cdef s slange(char *norm, int *m, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef s slangt(char *norm, int *n, s *dl, s *d, s *du) noexcept nogil
+cdef s slanhs(char *norm, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef s slansb(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil
+cdef s slansf(char *norm, char *transr, char *uplo, int *n, s *a, s *work) noexcept nogil
+cdef s slansp(char *norm, char *uplo, int *n, s *ap, s *work) noexcept nogil
+cdef s slanst(char *norm, int *n, s *d, s *e) noexcept nogil
+cdef s slansy(char *norm, char *uplo, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef s slantb(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil
+cdef s slantp(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) noexcept nogil
+cdef s slantr(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) noexcept nogil
+cdef void slanv2(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) noexcept nogil
+cdef void slapll(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) noexcept nogil
+cdef void slapmr(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil
+cdef void slapmt(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil
+cdef s slapy2(s *x, s *y) noexcept nogil
+cdef s slapy3(s *x, s *y, s *z) noexcept nogil
+cdef void slaqgb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void slaqge(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil
+cdef void slaqp2(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) noexcept nogil
+cdef void slaqps(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) noexcept nogil
+cdef void slaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void slaqr1(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) noexcept nogil
+cdef void slaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil
+cdef void slaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil
+cdef void slaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil
+cdef void slaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) noexcept nogil
+cdef void slaqsb(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void slaqsp(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void slaqsy(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil
+cdef void slaqtr(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) noexcept nogil
+cdef void slar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil
+cdef void slar2v(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) noexcept nogil
+cdef void slarf(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil
+cdef void slarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil
+cdef void slarfg(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil
+cdef void slarfgp(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil
+cdef void slarft(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil
+cdef void slarfx(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) noexcept nogil
+cdef void slargv(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) noexcept nogil
+cdef void slarnv(int *idist, int *iseed, int *n, s *x) noexcept nogil
+cdef void slarra(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil
+cdef void slarrb(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) noexcept nogil
+cdef void slarrc(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil
+cdef void slarrd(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) noexcept nogil
+cdef void slarre(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) noexcept nogil
+cdef void slarrf(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) noexcept nogil
+cdef void slarrj(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) noexcept nogil
+cdef void slarrk(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) noexcept nogil
+cdef void slarrr(int *n, s *d, s *e, int *info) noexcept nogil
+cdef void slarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil
+cdef void slartg(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil
+cdef void slartgp(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil
+cdef void slartgs(s *x, s *y, s *sigma, s *cs, s *sn) noexcept nogil
+cdef void slartv(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) noexcept nogil
+cdef void slaruv(int *iseed, int *n, s *x) noexcept nogil
+cdef void slarz(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil
+cdef void slarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil
+cdef void slarzt(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil
+cdef void slas2(s *f, s *g, s *h, s *ssmin, s *ssmax) noexcept nogil
+cdef void slascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void slasd0(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) noexcept nogil
+cdef void slasd1(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) noexcept nogil
+cdef void slasd2(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil
+cdef void slasd3(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) noexcept nogil
+cdef void slasd4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) noexcept nogil
+cdef void slasd5(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) noexcept nogil
+cdef void slasd6(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil
+cdef void slasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) noexcept nogil
+cdef void slasd8(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) noexcept nogil
+cdef void slasda(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil
+cdef void slasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void slasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil
+cdef void slaset(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) noexcept nogil
+cdef void slasq1(int *n, s *d, s *e, s *work, int *info) noexcept nogil
+cdef void slasq2(int *n, s *z, int *info) noexcept nogil
+cdef void slasq3(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) noexcept nogil
+cdef void slasq4(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) noexcept nogil
+cdef void slasq6(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) noexcept nogil
+cdef void slasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) noexcept nogil
+cdef void slasrt(char *id, int *n, s *d, int *info) noexcept nogil
+cdef void slassq(int *n, s *x, int *incx, s *scale, s *sumsq) noexcept nogil
+cdef void slasv2(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) noexcept nogil
+cdef void slaswp(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void slasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) noexcept nogil
+cdef void slasyf(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) noexcept nogil
+cdef void slatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void slatdf(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void slatps(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void slatrd(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) noexcept nogil
+cdef void slatrs(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) noexcept nogil
+cdef void slatrz(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) noexcept nogil
+cdef void slauu2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void slauum(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void sopgtr(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) noexcept nogil
+cdef void sopmtr(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sorbdb(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void sorg2l(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorg2r(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorgbr(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorghr(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgl2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorglq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgql(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgqr(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgr2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil
+cdef void sorgrq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorgtr(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorm2l(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sorm2r(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sorml2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormlq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormql(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormqr(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormr2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormr3(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil
+cdef void sormrq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormrz(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void sormtr(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil
+cdef void spbcon(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void spbequ(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void spbrfs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spbstf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil
+cdef void spbsv(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil
+cdef void spbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spbtf2(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil
+cdef void spbtrf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil
+cdef void spbtrs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil
+cdef void spftrf(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil
+cdef void spftri(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil
+cdef void spftrs(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) noexcept nogil
+cdef void spocon(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void spoequ(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void spoequb(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void sporfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sposv(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void sposvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spotf2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void spotrf(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void spotri(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void spotrs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void sppcon(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sppequ(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) noexcept nogil
+cdef void spprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sppsv(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil
+cdef void sppsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void spptrf(char *uplo, int *n, s *ap, int *info) noexcept nogil
+cdef void spptri(char *uplo, int *n, s *ap, int *info) noexcept nogil
+cdef void spptrs(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil
+cdef void spstf2(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void spstrf(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil
+cdef void sptcon(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) noexcept nogil
+cdef void spteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sptrfs(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) noexcept nogil
+cdef void sptsv(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil
+cdef void sptsvx(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) noexcept nogil
+cdef void spttrf(int *n, s *d, s *e, int *info) noexcept nogil
+cdef void spttrs(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil
+cdef void sptts2(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) noexcept nogil
+cdef void srscl(int *n, s *sa, s *sx, int *incx) noexcept nogil
+cdef void ssbev(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void ssbevd(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssbevx(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssbgst(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) noexcept nogil
+cdef void ssbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void ssbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssbtrd(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) noexcept nogil
+cdef void ssfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) noexcept nogil
+cdef void sspcon(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void sspev(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sspevd(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sspevx(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void sspgst(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) noexcept nogil
+cdef void sspgv(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sspgvd(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void sspsv(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sspsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void ssptrd(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) noexcept nogil
+cdef void ssptrf(char *uplo, int *n, s *ap, int *ipiv, int *info) noexcept nogil
+cdef void ssptri(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) noexcept nogil
+cdef void ssptrs(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void sstebz(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) noexcept nogil
+cdef void sstedc(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void sstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void ssterf(int *n, s *d, s *e, int *info) noexcept nogil
+cdef void sstev(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil
+cdef void sstevd(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstevr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void sstevx(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssycon(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void ssyconv(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil
+cdef void ssyequb(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) noexcept nogil
+cdef void ssyev(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssyevd(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssyevr(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssyevx(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssygs2(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void ssygst(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void ssygv(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssygvd(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ssygvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void ssyrfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void ssysv(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssysvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ssyswapr(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void ssytd2(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) noexcept nogil
+cdef void ssytf2(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void ssytrd(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssytrf(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssytri(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil
+cdef void ssytri2(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil
+cdef void ssytri2x(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) noexcept nogil
+cdef void ssytrs(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil
+cdef void ssytrs2(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) noexcept nogil
+cdef void stbcon(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void stbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void stbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil
+cdef void stfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) noexcept nogil
+cdef void stftri(char *transr, char *uplo, char *diag, int *n, s *a, int *info) noexcept nogil
+cdef void stfttp(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) noexcept nogil
+cdef void stfttr(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) noexcept nogil
+cdef void stgevc(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil
+cdef void stgex2(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) noexcept nogil
+cdef void stgexc(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) noexcept nogil
+cdef void stgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void stgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) noexcept nogil
+cdef void stgsna(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void stgsy2(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) noexcept nogil
+cdef void stgsyl(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void stpcon(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void stpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) noexcept nogil
+cdef void stpqrt(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) noexcept nogil
+cdef void stpqrt2(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) noexcept nogil
+cdef void stprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) noexcept nogil
+cdef void stprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void stptri(char *uplo, char *diag, int *n, s *ap, int *info) noexcept nogil
+cdef void stptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil
+cdef void stpttf(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) noexcept nogil
+cdef void stpttr(char *uplo, int *n, s *ap, s *a, int *lda, int *info) noexcept nogil
+cdef void strcon(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) noexcept nogil
+cdef void strevc(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil
+cdef void strexc(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) noexcept nogil
+cdef void strrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil
+cdef void strsen(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void strsna(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) noexcept nogil
+cdef void strsyl(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) noexcept nogil
+cdef void strti2(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void strtri(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil
+cdef void strtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil
+cdef void strttf(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) noexcept nogil
+cdef void strttp(char *uplo, int *n, s *a, int *lda, s *ap, int *info) noexcept nogil
+cdef void stzrzf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil
+cdef void xerbla_array(char *srname_array, int *srname_len, int *info) noexcept nogil
+cdef void zbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) noexcept nogil
+cdef void zbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, z *vt, int *ldvt, z *u, int *ldu, z *c, int *ldc, d *rwork, int *info) noexcept nogil
+cdef void zcgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil
+cdef void zcposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil
+cdef void zdrscl(int *n, d *sa, z *sx, int *incx) noexcept nogil
+cdef void zgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *pt, int *ldpt, z *c, int *ldc, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbcon(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbequ(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgbequb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbsv(int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgbtf2(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void zgbtrf(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil
+cdef void zgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, z *v, int *ldv, int *info) noexcept nogil
+cdef void zgebal(char *job, int *n, z *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil
+cdef void zgebd2(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *info) noexcept nogil
+cdef void zgebrd(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgecon(char *norm, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgeequ(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgeequb(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil
+cdef void zgees(char *jobvs, char *sort, zselect1 *select, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil
+cdef void zgeesx(char *jobvs, char *sort, zselect1 *select, char *sense, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil
+cdef void zgeev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgehd2(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgehrd(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgelq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgelqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgels(char *trans, int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgelsd(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zgelss(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgelsy(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *jpvt, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zgeql2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgeqlf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgeqp3(int *m, int *n, z *a, int *lda, int *jpvt, z *tau, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgeqr2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgeqr2p(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgeqrf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgeqrfp(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgeqrt(int *m, int *n, int *nb, z *a, int *lda, z *t, int *ldt, z *work, int *info) noexcept nogil
+cdef void zgeqrt2(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil
+cdef void zgeqrt3(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil
+cdef void zgerfs(char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgerq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zgerqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgesc2(int *n, z *a, int *lda, z *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil
+cdef void zgesdd(char *jobz, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgesvd(char *jobu, char *jobvt, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zgesvx(char *fact, char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgetc2(int *n, z *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil
+cdef void zgetf2(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zgetrf(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zgetri(int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgetrs(char *trans, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, z *v, int *ldv, int *info) noexcept nogil
+cdef void zggbal(char *job, int *n, z *a, int *lda, z *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil
+cdef void zgges(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil
+cdef void zggesx(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, char *sense, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil
+cdef void zggev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) noexcept nogil
+cdef void zggglm(int *n, int *m, int *p, z *a, int *lda, z *b, int *ldb, z *d, z *x, z *y, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *info) noexcept nogil
+cdef void zgglse(int *m, int *n, int *p, z *a, int *lda, z *b, int *ldb, z *c, z *d, z *x, z *work, int *lwork, int *info) noexcept nogil
+cdef void zggqrf(int *n, int *m, int *p, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil
+cdef void zggrqf(int *m, int *p, int *n, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil
+cdef void zgtcon(char *norm, int *n, z *dl, z *d, z *du, z *du2, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zgtrfs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgtsv(int *n, int *nrhs, z *dl, z *d, z *du, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgtsvx(char *fact, char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zgttrf(int *n, z *dl, z *d, z *du, z *du2, int *ipiv, int *info) noexcept nogil
+cdef void zgttrs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zgtts2(int *itrans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb) noexcept nogil
+cdef void zhbev(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhbevd(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhbevx(char *jobz, char *range, char *uplo, int *n, int *kd, z *ab, int *ldab, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhbgst(char *vect, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *x, int *ldx, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhbtrd(char *vect, char *uplo, int *n, int *kd, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *work, int *info) noexcept nogil
+cdef void zhecon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zheequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil
+cdef void zheev(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zheevd(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zheevr(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zheevx(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhegs2(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhegst(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhegv(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zhegvd(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhegvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zherfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhesv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhesvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zheswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void zhetd2(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, int *info) noexcept nogil
+cdef void zhetf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zhetrd(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhetrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhetri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zhetri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zhetri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil
+cdef void zhetrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhetrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil
+cdef void zhfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c) noexcept nogil
+cdef void zhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *t, int *ldt, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zhpcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zhpev(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhpevd(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhpevx(char *jobz, char *range, char *uplo, int *n, z *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhpgst(int *itype, char *uplo, int *n, z *ap, z *bp, int *info) noexcept nogil
+cdef void zhpgv(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhpgvd(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zhpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *ap, z *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zhprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhpsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhpsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zhptrd(char *uplo, int *n, z *ap, d *d, d *e, z *tau, int *info) noexcept nogil
+cdef void zhptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil
+cdef void zhptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zhptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, z *h, int *ldh, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil
+cdef void zhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil
+cdef void zlabrd(int *m, int *n, int *nb, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *x, int *ldx, z *y, int *ldy) noexcept nogil
+cdef void zlacgv(int *n, z *x, int *incx) noexcept nogil
+cdef void zlacn2(int *n, z *v, z *x, d *est, int *kase, int *isave) noexcept nogil
+cdef void zlacon(int *n, z *v, z *x, d *est, int *kase) noexcept nogil
+cdef void zlacp2(char *uplo, int *m, int *n, d *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void zlacpy(char *uplo, int *m, int *n, z *a, int *lda, z *b, int *ldb) noexcept nogil
+cdef void zlacrm(int *m, int *n, z *a, int *lda, d *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil
+cdef void zlacrt(int *n, z *cx, int *incx, z *cy, int *incy, z *c, z *s) noexcept nogil
+cdef z zladiv(z *x, z *y) noexcept nogil
+cdef void zlaed0(int *qsiz, int *n, d *d, d *e, z *q, int *ldq, z *qstore, int *ldqs, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zlaed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, z *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, z *work, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zlaed8(int *k, int *n, int *qsiz, z *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, z *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) noexcept nogil
+cdef void zlaein(bint *rightv, bint *noinit, int *n, z *h, int *ldh, z *w, z *v, z *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) noexcept nogil
+cdef void zlaesy(z *a, z *b, z *c, z *rt1, z *rt2, z *evscal, z *cs1, z *sn1) noexcept nogil
+cdef void zlaev2(z *a, z *b, z *c, d *rt1, d *rt2, d *cs1, z *sn1) noexcept nogil
+cdef void zlag2c(int *m, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil
+cdef void zlags2(bint *upper, d *a1, z *a2, d *a3, d *b1, z *b2, d *b3, d *csu, z *snu, d *csv, z *snv, d *csq, z *snq) noexcept nogil
+cdef void zlagtm(char *trans, int *n, int *nrhs, d *alpha, z *dl, z *d, z *du, z *x, int *ldx, d *beta, z *b, int *ldb) noexcept nogil
+cdef void zlahef(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil
+cdef void zlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, int *info) noexcept nogil
+cdef void zlahr2(int *n, int *k, int *nb, z *a, int *lda, z *tau, z *t, int *ldt, z *y, int *ldy) noexcept nogil
+cdef void zlaic1(int *job, int *j, z *x, d *sest, z *w, z *gamma, d *sestpr, z *s, z *c) noexcept nogil
+cdef void zlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) noexcept nogil
+cdef void zlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) noexcept nogil
+cdef void zlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, z *b, int *ldb, d *rcond, int *rank, z *work, d *rwork, int *iwork, int *info) noexcept nogil
+cdef d zlangb(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlange(char *norm, int *m, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlangt(char *norm, int *n, z *dl, z *d_, z *du) noexcept nogil
+cdef d zlanhb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlanhe(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlanhf(char *norm, char *transr, char *uplo, int *n, z *a, d *work) noexcept nogil
+cdef d zlanhp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil
+cdef d zlanhs(char *norm, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlanht(char *norm, int *n, d *d_, z *e) noexcept nogil
+cdef d zlansb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlansp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil
+cdef d zlansy(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef d zlantb(char *norm, char *uplo, char *diag, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil
+cdef d zlantp(char *norm, char *uplo, char *diag, int *n, z *ap, d *work) noexcept nogil
+cdef d zlantr(char *norm, char *uplo, char *diag, int *m, int *n, z *a, int *lda, d *work) noexcept nogil
+cdef void zlapll(int *n, z *x, int *incx, z *y, int *incy, d *ssmin) noexcept nogil
+cdef void zlapmr(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil
+cdef void zlapmt(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil
+cdef void zlaqgb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void zlaqge(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil
+cdef void zlaqhb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqhe(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqhp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqp2(int *m, int *n, int *offset, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *work) noexcept nogil
+cdef void zlaqps(int *m, int *n, int *offset, int *nb, int *kb, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *auxv, z *f, int *ldf) noexcept nogil
+cdef void zlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil
+cdef void zlaqr1(int *n, z *h, int *ldh, z *s1, z *s2, z *v) noexcept nogil
+cdef void zlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil
+cdef void zlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil
+cdef void zlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil
+cdef void zlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, z *s, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, z *v, int *ldv, z *u, int *ldu, int *nv, z *wv, int *ldwv, int *nh, z *wh, int *ldwh) noexcept nogil
+cdef void zlaqsb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqsp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlaqsy(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil
+cdef void zlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, z *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil
+cdef void zlar2v(int *n, z *x, z *y, z *z, int *incx, d *c, z *s, int *incc) noexcept nogil
+cdef void zlarcm(int *m, int *n, d *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil
+cdef void zlarf(char *side, int *m, int *n, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil
+cdef void zlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil
+cdef void zlarfg(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil
+cdef void zlarfgp(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil
+cdef void zlarft(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil
+cdef void zlarfx(char *side, int *m, int *n, z *v, z *tau, z *c, int *ldc, z *work) noexcept nogil
+cdef void zlargv(int *n, z *x, int *incx, z *y, int *incy, d *c, int *incc) noexcept nogil
+cdef void zlarnv(int *idist, int *iseed, int *n, z *x) noexcept nogil
+cdef void zlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, z *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil
+cdef void zlartg(z *f, z *g, d *cs, z *sn, z *r) noexcept nogil
+cdef void zlartv(int *n, z *x, int *incx, z *y, int *incy, d *c, z *s, int *incc) noexcept nogil
+cdef void zlarz(char *side, int *m, int *n, int *l, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil
+cdef void zlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil
+cdef void zlarzt(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil
+cdef void zlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zlaset(char *uplo, int *m, int *n, z *alpha, z *beta, z *a, int *lda) noexcept nogil
+cdef void zlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, z *a, int *lda) noexcept nogil
+cdef void zlassq(int *n, z *x, int *incx, d *scale, d *sumsq) noexcept nogil
+cdef void zlaswp(int *n, z *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil
+cdef void zlasyf(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil
+cdef void zlat2c(char *uplo, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil
+cdef void zlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, z *ab, int *ldab, z *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void zlatdf(int *ijob, int *n, z *z, int *ldz, z *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil
+cdef void zlatps(char *uplo, char *trans, char *diag, char *normin, int *n, z *ap, z *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void zlatrd(char *uplo, int *n, int *nb, z *a, int *lda, d *e, z *tau, z *w, int *ldw) noexcept nogil
+cdef void zlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, z *a, int *lda, z *x, d *scale, d *cnorm, int *info) noexcept nogil
+cdef void zlatrz(int *m, int *n, int *l, z *a, int *lda, z *tau, z *work) noexcept nogil
+cdef void zlauu2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zlauum(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpbcon(char *uplo, int *n, int *kd, z *ab, int *ldab, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpbequ(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zpbrfs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpbstf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil
+cdef void zpbsv(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpbtf2(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil
+cdef void zpbtrf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil
+cdef void zpbtrs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpftrf(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil
+cdef void zpftri(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil
+cdef void zpftrs(char *transr, char *uplo, int *n, int *nrhs, z *a, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpocon(char *uplo, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpoequ(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zpoequb(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zporfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zposvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpotf2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpotrf(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpotri(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void zpotrs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void zppcon(char *uplo, int *n, z *ap, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void zppequ(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, int *info) noexcept nogil
+cdef void zpprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zppsv(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil
+cdef void zppsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpptrf(char *uplo, int *n, z *ap, int *info) noexcept nogil
+cdef void zpptri(char *uplo, int *n, z *ap, int *info) noexcept nogil
+cdef void zpptrs(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil
+cdef void zpstf2(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void zpstrf(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil
+cdef void zptcon(int *n, d *d, z *e, d *anorm, d *rcond, d *rwork, int *info) noexcept nogil
+cdef void zpteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void zptrfs(char *uplo, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zptsv(int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil
+cdef void zptsvx(char *fact, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zpttrf(int *n, d *d, z *e, int *info) noexcept nogil
+cdef void zpttrs(char *uplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil
+cdef void zptts2(int *iuplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb) noexcept nogil
+cdef void zrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, z *s) noexcept nogil
+cdef void zspcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zspmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zspr(char *uplo, int *n, z *alpha, z *x, int *incx, z *ap) noexcept nogil
+cdef void zsprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zspsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zspsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zsptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil
+cdef void zsptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zsptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zstedc(char *compz, int *n, d *d, d *e, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, z *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil
+cdef void zstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, z *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void zsteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil
+cdef void zsycon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil
+cdef void zsyconv(char *uplo, char *way, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zsyequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil
+cdef void zsymv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil
+cdef void zsyr(char *uplo, int *n, z *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil
+cdef void zsyrfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void zsysv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil
+cdef void zsysvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil
+cdef void zsyswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil
+cdef void zsytf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil
+cdef void zsytrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zsytri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil
+cdef void zsytri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil
+cdef void zsytri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil
+cdef void zsytrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil
+cdef void zsytrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil
+cdef void ztbcon(char *norm, char *uplo, char *diag, int *n, int *kd, z *ab, int *ldab, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil
+cdef void ztfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, z *alpha, z *a, z *b, int *ldb) noexcept nogil
+cdef void ztftri(char *transr, char *uplo, char *diag, int *n, z *a, int *info) noexcept nogil
+cdef void ztfttp(char *transr, char *uplo, int *n, z *arf, z *ap, int *info) noexcept nogil
+cdef void ztfttr(char *transr, char *uplo, int *n, z *arf, z *a, int *lda, int *info) noexcept nogil
+cdef void ztgevc(char *side, char *howmny, bint *select, int *n, z *s, int *lds, z *p, int *ldp, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztgex2(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *j1, int *info) noexcept nogil
+cdef void ztgexc(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ztgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, int *m, d *pl, d *pr, d *dif, z *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil
+cdef void ztgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, z *a, int *lda, z *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, z *u, int *ldu, z *v, int *ldv, z *q, int *ldq, z *work, int *ncycle, int *info) noexcept nogil
+cdef void ztgsna(char *job, char *howmny, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *dif, int *mm, int *m, z *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ztgsy2(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) noexcept nogil
+cdef void ztgsyl(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *dif, z *work, int *lwork, int *iwork, int *info) noexcept nogil
+cdef void ztpcon(char *norm, char *uplo, char *diag, int *n, z *ap, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *info) noexcept nogil
+cdef void ztpqrt(int *m, int *n, int *l, int *nb, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, z *work, int *info) noexcept nogil
+cdef void ztpqrt2(int *m, int *n, int *l, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, int *info) noexcept nogil
+cdef void ztprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *ldwork) noexcept nogil
+cdef void ztprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztptri(char *uplo, char *diag, int *n, z *ap, int *info) noexcept nogil
+cdef void ztptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil
+cdef void ztpttf(char *transr, char *uplo, int *n, z *ap, z *arf, int *info) noexcept nogil
+cdef void ztpttr(char *uplo, int *n, z *ap, z *a, int *lda, int *info) noexcept nogil
+cdef void ztrcon(char *norm, char *uplo, char *diag, int *n, z *a, int *lda, d *rcond, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztrevc(char *side, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztrexc(char *compq, int *n, z *t, int *ldt, z *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil
+cdef void ztrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil
+cdef void ztrsen(char *job, char *compq, bint *select, int *n, z *t, int *ldt, z *q, int *ldq, z *w, int *m, d *s, d *sep, z *work, int *lwork, int *info) noexcept nogil
+cdef void ztrsna(char *job, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *sep, int *mm, int *m, z *work, int *ldwork, d *rwork, int *info) noexcept nogil
+cdef void ztrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *scale, int *info) noexcept nogil
+cdef void ztrti2(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void ztrtri(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil
+cdef void ztrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil
+cdef void ztrttf(char *transr, char *uplo, int *n, z *a, int *lda, z *arf, int *info) noexcept nogil
+cdef void ztrttp(char *uplo, int *n, z *a, int *lda, z *ap, int *info) noexcept nogil
+cdef void ztzrzf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunbdb(char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, d *phi, z *taup1, z *taup2, z *tauq1, z *tauq2, z *work, int *lwork, int *info) noexcept nogil
+cdef void zuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) noexcept nogil
+cdef void zung2l(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zung2r(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zungbr(char *vect, int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunghr(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungl2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zunglq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungql(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungqr(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungr2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil
+cdef void zungrq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zungtr(char *uplo, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunm2l(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunm2r(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunml2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmlq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmql(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmqr(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmr2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
+cdef void zunmrq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zunmtr(char *side, char *uplo, char *trans, int *m, int *n, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil
+cdef void zupgtr(char *uplo, int *n, z *ap, z *tau, z *q, int *ldq, z *work, int *info) noexcept nogil
+cdef void zupmtr(char *side, char *uplo, char *trans, int *m, int *n, z *ap, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..7f9cbfbb519603d4107af51ac353e0650720cf8c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/cython_lapack.pyx
@@ -0,0 +1,12045 @@
+# This file was generated by _generate_pyx.py.
+# Do not edit this file directly.
+"""
+LAPACK functions for Cython
+===========================
+
+Usable from Cython via::
+
+    cimport scipy.linalg.cython_lapack
+
+This module provides Cython-level wrappers for all primary routines included
+in LAPACK 3.4.0 except for ``zcgesv`` since its interface is not consistent
+from LAPACK 3.4.0 to 3.6.0. It also provides some of the
+fixed-api auxiliary routines.
+
+These wrappers do not check for alignment of arrays.
+Alignment should be checked before these wrappers are used.
+
+Raw function pointers (Fortran-style pointer arguments):
+
+- cbbcsd
+- cbdsqr
+- cgbbrd
+- cgbcon
+- cgbequ
+- cgbequb
+- cgbrfs
+- cgbsv
+- cgbsvx
+- cgbtf2
+- cgbtrf
+- cgbtrs
+- cgebak
+- cgebal
+- cgebd2
+- cgebrd
+- cgecon
+- cgeequ
+- cgeequb
+- cgees
+- cgeesx
+- cgeev
+- cgeevx
+- cgehd2
+- cgehrd
+- cgelq2
+- cgelqf
+- cgels
+- cgelsd
+- cgelss
+- cgelsy
+- cgemqrt
+- cgeql2
+- cgeqlf
+- cgeqp3
+- cgeqr2
+- cgeqr2p
+- cgeqrf
+- cgeqrfp
+- cgeqrt
+- cgeqrt2
+- cgeqrt3
+- cgerfs
+- cgerq2
+- cgerqf
+- cgesc2
+- cgesdd
+- cgesv
+- cgesvd
+- cgesvx
+- cgetc2
+- cgetf2
+- cgetrf
+- cgetri
+- cgetrs
+- cggbak
+- cggbal
+- cgges
+- cggesx
+- cggev
+- cggevx
+- cggglm
+- cgghrd
+- cgglse
+- cggqrf
+- cggrqf
+- cgtcon
+- cgtrfs
+- cgtsv
+- cgtsvx
+- cgttrf
+- cgttrs
+- cgtts2
+- chbev
+- chbevd
+- chbevx
+- chbgst
+- chbgv
+- chbgvd
+- chbgvx
+- chbtrd
+- checon
+- cheequb
+- cheev
+- cheevd
+- cheevr
+- cheevx
+- chegs2
+- chegst
+- chegv
+- chegvd
+- chegvx
+- cherfs
+- chesv
+- chesvx
+- cheswapr
+- chetd2
+- chetf2
+- chetrd
+- chetrf
+- chetri
+- chetri2
+- chetri2x
+- chetrs
+- chetrs2
+- chfrk
+- chgeqz
+- chla_transtype
+- chpcon
+- chpev
+- chpevd
+- chpevx
+- chpgst
+- chpgv
+- chpgvd
+- chpgvx
+- chprfs
+- chpsv
+- chpsvx
+- chptrd
+- chptrf
+- chptri
+- chptrs
+- chsein
+- chseqr
+- clabrd
+- clacgv
+- clacn2
+- clacon
+- clacp2
+- clacpy
+- clacrm
+- clacrt
+- cladiv
+- claed0
+- claed7
+- claed8
+- claein
+- claesy
+- claev2
+- clag2z
+- clags2
+- clagtm
+- clahef
+- clahqr
+- clahr2
+- claic1
+- clals0
+- clalsa
+- clalsd
+- clangb
+- clange
+- clangt
+- clanhb
+- clanhe
+- clanhf
+- clanhp
+- clanhs
+- clanht
+- clansb
+- clansp
+- clansy
+- clantb
+- clantp
+- clantr
+- clapll
+- clapmr
+- clapmt
+- claqgb
+- claqge
+- claqhb
+- claqhe
+- claqhp
+- claqp2
+- claqps
+- claqr0
+- claqr1
+- claqr2
+- claqr3
+- claqr4
+- claqr5
+- claqsb
+- claqsp
+- claqsy
+- clar1v
+- clar2v
+- clarcm
+- clarf
+- clarfb
+- clarfg
+- clarfgp
+- clarft
+- clarfx
+- clargv
+- clarnv
+- clarrv
+- clartg
+- clartv
+- clarz
+- clarzb
+- clarzt
+- clascl
+- claset
+- clasr
+- classq
+- claswp
+- clasyf
+- clatbs
+- clatdf
+- clatps
+- clatrd
+- clatrs
+- clatrz
+- clauu2
+- clauum
+- cpbcon
+- cpbequ
+- cpbrfs
+- cpbstf
+- cpbsv
+- cpbsvx
+- cpbtf2
+- cpbtrf
+- cpbtrs
+- cpftrf
+- cpftri
+- cpftrs
+- cpocon
+- cpoequ
+- cpoequb
+- cporfs
+- cposv
+- cposvx
+- cpotf2
+- cpotrf
+- cpotri
+- cpotrs
+- cppcon
+- cppequ
+- cpprfs
+- cppsv
+- cppsvx
+- cpptrf
+- cpptri
+- cpptrs
+- cpstf2
+- cpstrf
+- cptcon
+- cpteqr
+- cptrfs
+- cptsv
+- cptsvx
+- cpttrf
+- cpttrs
+- cptts2
+- crot
+- cspcon
+- cspmv
+- cspr
+- csprfs
+- cspsv
+- cspsvx
+- csptrf
+- csptri
+- csptrs
+- csrscl
+- cstedc
+- cstegr
+- cstein
+- cstemr
+- csteqr
+- csycon
+- csyconv
+- csyequb
+- csymv
+- csyr
+- csyrfs
+- csysv
+- csysvx
+- csyswapr
+- csytf2
+- csytrf
+- csytri
+- csytri2
+- csytri2x
+- csytrs
+- csytrs2
+- ctbcon
+- ctbrfs
+- ctbtrs
+- ctfsm
+- ctftri
+- ctfttp
+- ctfttr
+- ctgevc
+- ctgex2
+- ctgexc
+- ctgsen
+- ctgsja
+- ctgsna
+- ctgsy2
+- ctgsyl
+- ctpcon
+- ctpmqrt
+- ctpqrt
+- ctpqrt2
+- ctprfb
+- ctprfs
+- ctptri
+- ctptrs
+- ctpttf
+- ctpttr
+- ctrcon
+- ctrevc
+- ctrexc
+- ctrrfs
+- ctrsen
+- ctrsna
+- ctrsyl
+- ctrti2
+- ctrtri
+- ctrtrs
+- ctrttf
+- ctrttp
+- ctzrzf
+- cunbdb
+- cuncsd
+- cung2l
+- cung2r
+- cungbr
+- cunghr
+- cungl2
+- cunglq
+- cungql
+- cungqr
+- cungr2
+- cungrq
+- cungtr
+- cunm2l
+- cunm2r
+- cunmbr
+- cunmhr
+- cunml2
+- cunmlq
+- cunmql
+- cunmqr
+- cunmr2
+- cunmr3
+- cunmrq
+- cunmrz
+- cunmtr
+- cupgtr
+- cupmtr
+- dbbcsd
+- dbdsdc
+- dbdsqr
+- ddisna
+- dgbbrd
+- dgbcon
+- dgbequ
+- dgbequb
+- dgbrfs
+- dgbsv
+- dgbsvx
+- dgbtf2
+- dgbtrf
+- dgbtrs
+- dgebak
+- dgebal
+- dgebd2
+- dgebrd
+- dgecon
+- dgeequ
+- dgeequb
+- dgees
+- dgeesx
+- dgeev
+- dgeevx
+- dgehd2
+- dgehrd
+- dgejsv
+- dgelq2
+- dgelqf
+- dgels
+- dgelsd
+- dgelss
+- dgelsy
+- dgemqrt
+- dgeql2
+- dgeqlf
+- dgeqp3
+- dgeqr2
+- dgeqr2p
+- dgeqrf
+- dgeqrfp
+- dgeqrt
+- dgeqrt2
+- dgeqrt3
+- dgerfs
+- dgerq2
+- dgerqf
+- dgesc2
+- dgesdd
+- dgesv
+- dgesvd
+- dgesvj
+- dgesvx
+- dgetc2
+- dgetf2
+- dgetrf
+- dgetri
+- dgetrs
+- dggbak
+- dggbal
+- dgges
+- dggesx
+- dggev
+- dggevx
+- dggglm
+- dgghrd
+- dgglse
+- dggqrf
+- dggrqf
+- dgsvj0
+- dgsvj1
+- dgtcon
+- dgtrfs
+- dgtsv
+- dgtsvx
+- dgttrf
+- dgttrs
+- dgtts2
+- dhgeqz
+- dhsein
+- dhseqr
+- disnan
+- dlabad
+- dlabrd
+- dlacn2
+- dlacon
+- dlacpy
+- dladiv
+- dlae2
+- dlaebz
+- dlaed0
+- dlaed1
+- dlaed2
+- dlaed3
+- dlaed4
+- dlaed5
+- dlaed6
+- dlaed7
+- dlaed8
+- dlaed9
+- dlaeda
+- dlaein
+- dlaev2
+- dlaexc
+- dlag2
+- dlag2s
+- dlags2
+- dlagtf
+- dlagtm
+- dlagts
+- dlagv2
+- dlahqr
+- dlahr2
+- dlaic1
+- dlaln2
+- dlals0
+- dlalsa
+- dlalsd
+- dlamch
+- dlamrg
+- dlaneg
+- dlangb
+- dlange
+- dlangt
+- dlanhs
+- dlansb
+- dlansf
+- dlansp
+- dlanst
+- dlansy
+- dlantb
+- dlantp
+- dlantr
+- dlanv2
+- dlapll
+- dlapmr
+- dlapmt
+- dlapy2
+- dlapy3
+- dlaqgb
+- dlaqge
+- dlaqp2
+- dlaqps
+- dlaqr0
+- dlaqr1
+- dlaqr2
+- dlaqr3
+- dlaqr4
+- dlaqr5
+- dlaqsb
+- dlaqsp
+- dlaqsy
+- dlaqtr
+- dlar1v
+- dlar2v
+- dlarf
+- dlarfb
+- dlarfg
+- dlarfgp
+- dlarft
+- dlarfx
+- dlargv
+- dlarnv
+- dlarra
+- dlarrb
+- dlarrc
+- dlarrd
+- dlarre
+- dlarrf
+- dlarrj
+- dlarrk
+- dlarrr
+- dlarrv
+- dlartg
+- dlartgp
+- dlartgs
+- dlartv
+- dlaruv
+- dlarz
+- dlarzb
+- dlarzt
+- dlas2
+- dlascl
+- dlasd0
+- dlasd1
+- dlasd2
+- dlasd3
+- dlasd4
+- dlasd5
+- dlasd6
+- dlasd7
+- dlasd8
+- dlasda
+- dlasdq
+- dlasdt
+- dlaset
+- dlasq1
+- dlasq2
+- dlasq3
+- dlasq4
+- dlasq6
+- dlasr
+- dlasrt
+- dlassq
+- dlasv2
+- dlaswp
+- dlasy2
+- dlasyf
+- dlat2s
+- dlatbs
+- dlatdf
+- dlatps
+- dlatrd
+- dlatrs
+- dlatrz
+- dlauu2
+- dlauum
+- dopgtr
+- dopmtr
+- dorbdb
+- dorcsd
+- dorg2l
+- dorg2r
+- dorgbr
+- dorghr
+- dorgl2
+- dorglq
+- dorgql
+- dorgqr
+- dorgr2
+- dorgrq
+- dorgtr
+- dorm2l
+- dorm2r
+- dormbr
+- dormhr
+- dorml2
+- dormlq
+- dormql
+- dormqr
+- dormr2
+- dormr3
+- dormrq
+- dormrz
+- dormtr
+- dpbcon
+- dpbequ
+- dpbrfs
+- dpbstf
+- dpbsv
+- dpbsvx
+- dpbtf2
+- dpbtrf
+- dpbtrs
+- dpftrf
+- dpftri
+- dpftrs
+- dpocon
+- dpoequ
+- dpoequb
+- dporfs
+- dposv
+- dposvx
+- dpotf2
+- dpotrf
+- dpotri
+- dpotrs
+- dppcon
+- dppequ
+- dpprfs
+- dppsv
+- dppsvx
+- dpptrf
+- dpptri
+- dpptrs
+- dpstf2
+- dpstrf
+- dptcon
+- dpteqr
+- dptrfs
+- dptsv
+- dptsvx
+- dpttrf
+- dpttrs
+- dptts2
+- drscl
+- dsbev
+- dsbevd
+- dsbevx
+- dsbgst
+- dsbgv
+- dsbgvd
+- dsbgvx
+- dsbtrd
+- dsfrk
+- dsgesv
+- dspcon
+- dspev
+- dspevd
+- dspevx
+- dspgst
+- dspgv
+- dspgvd
+- dspgvx
+- dsposv
+- dsprfs
+- dspsv
+- dspsvx
+- dsptrd
+- dsptrf
+- dsptri
+- dsptrs
+- dstebz
+- dstedc
+- dstegr
+- dstein
+- dstemr
+- dsteqr
+- dsterf
+- dstev
+- dstevd
+- dstevr
+- dstevx
+- dsycon
+- dsyconv
+- dsyequb
+- dsyev
+- dsyevd
+- dsyevr
+- dsyevx
+- dsygs2
+- dsygst
+- dsygv
+- dsygvd
+- dsygvx
+- dsyrfs
+- dsysv
+- dsysvx
+- dsyswapr
+- dsytd2
+- dsytf2
+- dsytrd
+- dsytrf
+- dsytri
+- dsytri2
+- dsytri2x
+- dsytrs
+- dsytrs2
+- dtbcon
+- dtbrfs
+- dtbtrs
+- dtfsm
+- dtftri
+- dtfttp
+- dtfttr
+- dtgevc
+- dtgex2
+- dtgexc
+- dtgsen
+- dtgsja
+- dtgsna
+- dtgsy2
+- dtgsyl
+- dtpcon
+- dtpmqrt
+- dtpqrt
+- dtpqrt2
+- dtprfb
+- dtprfs
+- dtptri
+- dtptrs
+- dtpttf
+- dtpttr
+- dtrcon
+- dtrevc
+- dtrexc
+- dtrrfs
+- dtrsen
+- dtrsna
+- dtrsyl
+- dtrti2
+- dtrtri
+- dtrtrs
+- dtrttf
+- dtrttp
+- dtzrzf
+- dzsum1
+- icmax1
+- ieeeck
+- ilaclc
+- ilaclr
+- iladiag
+- iladlc
+- iladlr
+- ilaprec
+- ilaslc
+- ilaslr
+- ilatrans
+- ilauplo
+- ilaver
+- ilazlc
+- ilazlr
+- izmax1
+- sbbcsd
+- sbdsdc
+- sbdsqr
+- scsum1
+- sdisna
+- sgbbrd
+- sgbcon
+- sgbequ
+- sgbequb
+- sgbrfs
+- sgbsv
+- sgbsvx
+- sgbtf2
+- sgbtrf
+- sgbtrs
+- sgebak
+- sgebal
+- sgebd2
+- sgebrd
+- sgecon
+- sgeequ
+- sgeequb
+- sgees
+- sgeesx
+- sgeev
+- sgeevx
+- sgehd2
+- sgehrd
+- sgejsv
+- sgelq2
+- sgelqf
+- sgels
+- sgelsd
+- sgelss
+- sgelsy
+- sgemqrt
+- sgeql2
+- sgeqlf
+- sgeqp3
+- sgeqr2
+- sgeqr2p
+- sgeqrf
+- sgeqrfp
+- sgeqrt
+- sgeqrt2
+- sgeqrt3
+- sgerfs
+- sgerq2
+- sgerqf
+- sgesc2
+- sgesdd
+- sgesv
+- sgesvd
+- sgesvj
+- sgesvx
+- sgetc2
+- sgetf2
+- sgetrf
+- sgetri
+- sgetrs
+- sggbak
+- sggbal
+- sgges
+- sggesx
+- sggev
+- sggevx
+- sggglm
+- sgghrd
+- sgglse
+- sggqrf
+- sggrqf
+- sgsvj0
+- sgsvj1
+- sgtcon
+- sgtrfs
+- sgtsv
+- sgtsvx
+- sgttrf
+- sgttrs
+- sgtts2
+- shgeqz
+- shsein
+- shseqr
+- slabad
+- slabrd
+- slacn2
+- slacon
+- slacpy
+- sladiv
+- slae2
+- slaebz
+- slaed0
+- slaed1
+- slaed2
+- slaed3
+- slaed4
+- slaed5
+- slaed6
+- slaed7
+- slaed8
+- slaed9
+- slaeda
+- slaein
+- slaev2
+- slaexc
+- slag2
+- slag2d
+- slags2
+- slagtf
+- slagtm
+- slagts
+- slagv2
+- slahqr
+- slahr2
+- slaic1
+- slaln2
+- slals0
+- slalsa
+- slalsd
+- slamch
+- slamrg
+- slangb
+- slange
+- slangt
+- slanhs
+- slansb
+- slansf
+- slansp
+- slanst
+- slansy
+- slantb
+- slantp
+- slantr
+- slanv2
+- slapll
+- slapmr
+- slapmt
+- slapy2
+- slapy3
+- slaqgb
+- slaqge
+- slaqp2
+- slaqps
+- slaqr0
+- slaqr1
+- slaqr2
+- slaqr3
+- slaqr4
+- slaqr5
+- slaqsb
+- slaqsp
+- slaqsy
+- slaqtr
+- slar1v
+- slar2v
+- slarf
+- slarfb
+- slarfg
+- slarfgp
+- slarft
+- slarfx
+- slargv
+- slarnv
+- slarra
+- slarrb
+- slarrc
+- slarrd
+- slarre
+- slarrf
+- slarrj
+- slarrk
+- slarrr
+- slarrv
+- slartg
+- slartgp
+- slartgs
+- slartv
+- slaruv
+- slarz
+- slarzb
+- slarzt
+- slas2
+- slascl
+- slasd0
+- slasd1
+- slasd2
+- slasd3
+- slasd4
+- slasd5
+- slasd6
+- slasd7
+- slasd8
+- slasda
+- slasdq
+- slasdt
+- slaset
+- slasq1
+- slasq2
+- slasq3
+- slasq4
+- slasq6
+- slasr
+- slasrt
+- slassq
+- slasv2
+- slaswp
+- slasy2
+- slasyf
+- slatbs
+- slatdf
+- slatps
+- slatrd
+- slatrs
+- slatrz
+- slauu2
+- slauum
+- sopgtr
+- sopmtr
+- sorbdb
+- sorcsd
+- sorg2l
+- sorg2r
+- sorgbr
+- sorghr
+- sorgl2
+- sorglq
+- sorgql
+- sorgqr
+- sorgr2
+- sorgrq
+- sorgtr
+- sorm2l
+- sorm2r
+- sormbr
+- sormhr
+- sorml2
+- sormlq
+- sormql
+- sormqr
+- sormr2
+- sormr3
+- sormrq
+- sormrz
+- sormtr
+- spbcon
+- spbequ
+- spbrfs
+- spbstf
+- spbsv
+- spbsvx
+- spbtf2
+- spbtrf
+- spbtrs
+- spftrf
+- spftri
+- spftrs
+- spocon
+- spoequ
+- spoequb
+- sporfs
+- sposv
+- sposvx
+- spotf2
+- spotrf
+- spotri
+- spotrs
+- sppcon
+- sppequ
+- spprfs
+- sppsv
+- sppsvx
+- spptrf
+- spptri
+- spptrs
+- spstf2
+- spstrf
+- sptcon
+- spteqr
+- sptrfs
+- sptsv
+- sptsvx
+- spttrf
+- spttrs
+- sptts2
+- srscl
+- ssbev
+- ssbevd
+- ssbevx
+- ssbgst
+- ssbgv
+- ssbgvd
+- ssbgvx
+- ssbtrd
+- ssfrk
+- sspcon
+- sspev
+- sspevd
+- sspevx
+- sspgst
+- sspgv
+- sspgvd
+- sspgvx
+- ssprfs
+- sspsv
+- sspsvx
+- ssptrd
+- ssptrf
+- ssptri
+- ssptrs
+- sstebz
+- sstedc
+- sstegr
+- sstein
+- sstemr
+- ssteqr
+- ssterf
+- sstev
+- sstevd
+- sstevr
+- sstevx
+- ssycon
+- ssyconv
+- ssyequb
+- ssyev
+- ssyevd
+- ssyevr
+- ssyevx
+- ssygs2
+- ssygst
+- ssygv
+- ssygvd
+- ssygvx
+- ssyrfs
+- ssysv
+- ssysvx
+- ssyswapr
+- ssytd2
+- ssytf2
+- ssytrd
+- ssytrf
+- ssytri
+- ssytri2
+- ssytri2x
+- ssytrs
+- ssytrs2
+- stbcon
+- stbrfs
+- stbtrs
+- stfsm
+- stftri
+- stfttp
+- stfttr
+- stgevc
+- stgex2
+- stgexc
+- stgsen
+- stgsja
+- stgsna
+- stgsy2
+- stgsyl
+- stpcon
+- stpmqrt
+- stpqrt
+- stpqrt2
+- stprfb
+- stprfs
+- stptri
+- stptrs
+- stpttf
+- stpttr
+- strcon
+- strevc
+- strexc
+- strrfs
+- strsen
+- strsna
+- strsyl
+- strti2
+- strtri
+- strtrs
+- strttf
+- strttp
+- stzrzf
+- xerbla_array
+- zbbcsd
+- zbdsqr
+- zcgesv
+- zcposv
+- zdrscl
+- zgbbrd
+- zgbcon
+- zgbequ
+- zgbequb
+- zgbrfs
+- zgbsv
+- zgbsvx
+- zgbtf2
+- zgbtrf
+- zgbtrs
+- zgebak
+- zgebal
+- zgebd2
+- zgebrd
+- zgecon
+- zgeequ
+- zgeequb
+- zgees
+- zgeesx
+- zgeev
+- zgeevx
+- zgehd2
+- zgehrd
+- zgelq2
+- zgelqf
+- zgels
+- zgelsd
+- zgelss
+- zgelsy
+- zgemqrt
+- zgeql2
+- zgeqlf
+- zgeqp3
+- zgeqr2
+- zgeqr2p
+- zgeqrf
+- zgeqrfp
+- zgeqrt
+- zgeqrt2
+- zgeqrt3
+- zgerfs
+- zgerq2
+- zgerqf
+- zgesc2
+- zgesdd
+- zgesv
+- zgesvd
+- zgesvx
+- zgetc2
+- zgetf2
+- zgetrf
+- zgetri
+- zgetrs
+- zggbak
+- zggbal
+- zgges
+- zggesx
+- zggev
+- zggevx
+- zggglm
+- zgghrd
+- zgglse
+- zggqrf
+- zggrqf
+- zgtcon
+- zgtrfs
+- zgtsv
+- zgtsvx
+- zgttrf
+- zgttrs
+- zgtts2
+- zhbev
+- zhbevd
+- zhbevx
+- zhbgst
+- zhbgv
+- zhbgvd
+- zhbgvx
+- zhbtrd
+- zhecon
+- zheequb
+- zheev
+- zheevd
+- zheevr
+- zheevx
+- zhegs2
+- zhegst
+- zhegv
+- zhegvd
+- zhegvx
+- zherfs
+- zhesv
+- zhesvx
+- zheswapr
+- zhetd2
+- zhetf2
+- zhetrd
+- zhetrf
+- zhetri
+- zhetri2
+- zhetri2x
+- zhetrs
+- zhetrs2
+- zhfrk
+- zhgeqz
+- zhpcon
+- zhpev
+- zhpevd
+- zhpevx
+- zhpgst
+- zhpgv
+- zhpgvd
+- zhpgvx
+- zhprfs
+- zhpsv
+- zhpsvx
+- zhptrd
+- zhptrf
+- zhptri
+- zhptrs
+- zhsein
+- zhseqr
+- zlabrd
+- zlacgv
+- zlacn2
+- zlacon
+- zlacp2
+- zlacpy
+- zlacrm
+- zlacrt
+- zladiv
+- zlaed0
+- zlaed7
+- zlaed8
+- zlaein
+- zlaesy
+- zlaev2
+- zlag2c
+- zlags2
+- zlagtm
+- zlahef
+- zlahqr
+- zlahr2
+- zlaic1
+- zlals0
+- zlalsa
+- zlalsd
+- zlangb
+- zlange
+- zlangt
+- zlanhb
+- zlanhe
+- zlanhf
+- zlanhp
+- zlanhs
+- zlanht
+- zlansb
+- zlansp
+- zlansy
+- zlantb
+- zlantp
+- zlantr
+- zlapll
+- zlapmr
+- zlapmt
+- zlaqgb
+- zlaqge
+- zlaqhb
+- zlaqhe
+- zlaqhp
+- zlaqp2
+- zlaqps
+- zlaqr0
+- zlaqr1
+- zlaqr2
+- zlaqr3
+- zlaqr4
+- zlaqr5
+- zlaqsb
+- zlaqsp
+- zlaqsy
+- zlar1v
+- zlar2v
+- zlarcm
+- zlarf
+- zlarfb
+- zlarfg
+- zlarfgp
+- zlarft
+- zlarfx
+- zlargv
+- zlarnv
+- zlarrv
+- zlartg
+- zlartv
+- zlarz
+- zlarzb
+- zlarzt
+- zlascl
+- zlaset
+- zlasr
+- zlassq
+- zlaswp
+- zlasyf
+- zlat2c
+- zlatbs
+- zlatdf
+- zlatps
+- zlatrd
+- zlatrs
+- zlatrz
+- zlauu2
+- zlauum
+- zpbcon
+- zpbequ
+- zpbrfs
+- zpbstf
+- zpbsv
+- zpbsvx
+- zpbtf2
+- zpbtrf
+- zpbtrs
+- zpftrf
+- zpftri
+- zpftrs
+- zpocon
+- zpoequ
+- zpoequb
+- zporfs
+- zposv
+- zposvx
+- zpotf2
+- zpotrf
+- zpotri
+- zpotrs
+- zppcon
+- zppequ
+- zpprfs
+- zppsv
+- zppsvx
+- zpptrf
+- zpptri
+- zpptrs
+- zpstf2
+- zpstrf
+- zptcon
+- zpteqr
+- zptrfs
+- zptsv
+- zptsvx
+- zpttrf
+- zpttrs
+- zptts2
+- zrot
+- zspcon
+- zspmv
+- zspr
+- zsprfs
+- zspsv
+- zspsvx
+- zsptrf
+- zsptri
+- zsptrs
+- zstedc
+- zstegr
+- zstein
+- zstemr
+- zsteqr
+- zsycon
+- zsyconv
+- zsyequb
+- zsymv
+- zsyr
+- zsyrfs
+- zsysv
+- zsysvx
+- zsyswapr
+- zsytf2
+- zsytrf
+- zsytri
+- zsytri2
+- zsytri2x
+- zsytrs
+- zsytrs2
+- ztbcon
+- ztbrfs
+- ztbtrs
+- ztfsm
+- ztftri
+- ztfttp
+- ztfttr
+- ztgevc
+- ztgex2
+- ztgexc
+- ztgsen
+- ztgsja
+- ztgsna
+- ztgsy2
+- ztgsyl
+- ztpcon
+- ztpmqrt
+- ztpqrt
+- ztpqrt2
+- ztprfb
+- ztprfs
+- ztptri
+- ztptrs
+- ztpttf
+- ztpttr
+- ztrcon
+- ztrevc
+- ztrexc
+- ztrrfs
+- ztrsen
+- ztrsna
+- ztrsyl
+- ztrti2
+- ztrtri
+- ztrtrs
+- ztrttf
+- ztrttp
+- ztzrzf
+- zunbdb
+- zuncsd
+- zung2l
+- zung2r
+- zungbr
+- zunghr
+- zungl2
+- zunglq
+- zungql
+- zungqr
+- zungr2
+- zungrq
+- zungtr
+- zunm2l
+- zunm2r
+- zunmbr
+- zunmhr
+- zunml2
+- zunmlq
+- zunmql
+- zunmqr
+- zunmr2
+- zunmr3
+- zunmrq
+- zunmrz
+- zunmtr
+- zupgtr
+- zupmtr
+
+
+"""
+
+# Within SciPy, these wrappers can be used via relative or absolute cimport.
+# Examples:
+# from ..linalg cimport cython_lapack
+# from scipy.linalg cimport cython_lapack
+# cimport scipy.linalg.cython_lapack as cython_lapack
+# cimport ..linalg.cython_lapack as cython_lapack
+
+# Within SciPy, if LAPACK functions are needed in C/C++/Fortran,
+# these wrappers should not be used.
+# The original libraries should be linked directly.
+
+cdef extern from "fortran_defs.h":
+    pass
+
+from numpy cimport npy_complex64, npy_complex128
+
+cdef extern from "_lapack_subroutines.h":
+    # Function pointer type declarations for
+    # gees and gges families of functions.
+    ctypedef bint _cselect1(npy_complex64*)
+    ctypedef bint _cselect2(npy_complex64*, npy_complex64*)
+    ctypedef bint _dselect2(d*, d*)
+    ctypedef bint _dselect3(d*, d*, d*)
+    ctypedef bint _sselect2(s*, s*)
+    ctypedef bint _sselect3(s*, s*, s*)
+    ctypedef bint _zselect1(npy_complex128*)
+    ctypedef bint _zselect2(npy_complex128*, npy_complex128*)
+
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cbbcsd "BLAS_FUNC(cbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) nogil
+cdef void cbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *rwork, int *lrwork, int *info) noexcept nogil:
+    
+    _fortran_cbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, rwork, lrwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cbdsqr "BLAS_FUNC(cbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, npy_complex64 *vt, int *ldvt, npy_complex64 *u, int *ldu, npy_complex64 *c, int *ldc, s *rwork, int *info) nogil
+cdef void cbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, c *vt, int *ldvt, c *u, int *ldu, c *c, int *ldc, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbbrd "BLAS_FUNC(cgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *pt, int *ldpt, npy_complex64 *c, int *ldc, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *pt, int *ldpt, c *c, int *ldc, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbcon "BLAS_FUNC(cgbcon)"(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgbcon(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbequ "BLAS_FUNC(cgbequ)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void cgbequ(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbequb "BLAS_FUNC(cgbequb)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void cgbequb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbrfs "BLAS_FUNC(cgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbsv "BLAS_FUNC(cgbsv)"(int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgbsv(int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbsvx "BLAS_FUNC(cgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbtf2 "BLAS_FUNC(cgbtf2)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void cgbtf2(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbtrf "BLAS_FUNC(cgbtrf)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void cgbtrf(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgbtrs "BLAS_FUNC(cgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex64 *ab, int *ldab, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, c *ab, int *ldab, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebak "BLAS_FUNC(cgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, npy_complex64 *v, int *ldv, int *info) nogil
+cdef void cgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, c *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_cgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebal "BLAS_FUNC(cgebal)"(char *job, int *n, npy_complex64 *a, int *lda, int *ilo, int *ihi, s *scale, int *info) nogil
+cdef void cgebal(char *job, int *n, c *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil:
+    
+    _fortran_cgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebd2 "BLAS_FUNC(cgebd2)"(int *m, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *info) nogil
+cdef void cgebd2(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgebrd "BLAS_FUNC(cgebrd)"(int *m, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgebrd(int *m, int *n, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgecon "BLAS_FUNC(cgecon)"(char *norm, int *n, npy_complex64 *a, int *lda, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgecon(char *norm, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgecon(norm, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeequ "BLAS_FUNC(cgeequ)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void cgeequ(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeequb "BLAS_FUNC(cgeequb)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void cgeequb(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgees "BLAS_FUNC(cgees)"(char *jobvs, char *sort, _cselect1 *select, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) nogil
+cdef void cgees(char *jobvs, char *sort, cselect1 *select, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cgees(jobvs, sort, <_cselect1*>select, n, a, lda, sdim, w, vs, ldvs, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeesx "BLAS_FUNC(cgeesx)"(char *jobvs, char *sort, _cselect1 *select, char *sense, int *n, npy_complex64 *a, int *lda, int *sdim, npy_complex64 *w, npy_complex64 *vs, int *ldvs, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) nogil
+cdef void cgeesx(char *jobvs, char *sort, cselect1 *select, char *sense, int *n, c *a, int *lda, int *sdim, c *w, c *vs, int *ldvs, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cgeesx(jobvs, sort, <_cselect1*>select, sense, n, a, lda, sdim, w, vs, ldvs, rconde, rcondv, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeev "BLAS_FUNC(cgeev)"(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgeev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgeev(jobvl, jobvr, n, a, lda, w, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeevx "BLAS_FUNC(cgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgeevx(balanc, jobvl, jobvr, sense, n, a, lda, w, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgehd2 "BLAS_FUNC(cgehd2)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgehd2(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgehrd "BLAS_FUNC(cgehrd)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgehrd(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelq2 "BLAS_FUNC(cgelq2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgelq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelqf "BLAS_FUNC(cgelqf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgelqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgels "BLAS_FUNC(cgels)"(char *trans, int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgels(char *trans, int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelsd "BLAS_FUNC(cgelsd)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *s, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *info) nogil
+cdef void cgelsd(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_cgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelss "BLAS_FUNC(cgelss)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *s, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgelss(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, s *s, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgelsy "BLAS_FUNC(cgelsy)"(int *m, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *jpvt, s *rcond, int *rank, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgelsy(int *m, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *jpvt, s *rcond, int *rank, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgemqrt "BLAS_FUNC(cgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeql2 "BLAS_FUNC(cgeql2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgeql2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqlf "BLAS_FUNC(cgeqlf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgeqlf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqp3 "BLAS_FUNC(cgeqp3)"(int *m, int *n, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgeqp3(int *m, int *n, c *a, int *lda, int *jpvt, c *tau, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqr2 "BLAS_FUNC(cgeqr2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgeqr2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqr2p "BLAS_FUNC(cgeqr2p)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgeqr2p(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrf "BLAS_FUNC(cgeqrf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgeqrf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrfp "BLAS_FUNC(cgeqrfp)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgeqrfp(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrt "BLAS_FUNC(cgeqrt)"(int *m, int *n, int *nb, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info) nogil
+cdef void cgeqrt(int *m, int *n, int *nb, c *a, int *lda, c *t, int *ldt, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrt2 "BLAS_FUNC(cgeqrt2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info) nogil
+cdef void cgeqrt2(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_cgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgeqrt3 "BLAS_FUNC(cgeqrt3)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *t, int *ldt, int *info) nogil
+cdef void cgeqrt3(int *m, int *n, c *a, int *lda, c *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_cgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgerfs "BLAS_FUNC(cgerfs)"(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgerfs(char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgerq2 "BLAS_FUNC(cgerq2)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cgerq2(int *m, int *n, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgerqf "BLAS_FUNC(cgerqf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgerqf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesc2 "BLAS_FUNC(cgesc2)"(int *n, npy_complex64 *a, int *lda, npy_complex64 *rhs, int *ipiv, int *jpiv, s *scale) nogil
+cdef void cgesc2(int *n, c *a, int *lda, c *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil:
+    
+    _fortran_cgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesdd "BLAS_FUNC(cgesdd)"(char *jobz, int *m, int *n, npy_complex64 *a, int *lda, s *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *info) nogil
+cdef void cgesdd(char *jobz, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_cgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesv "BLAS_FUNC(cgesv)"(int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgesv(int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesvd "BLAS_FUNC(cgesvd)"(char *jobu, char *jobvt, int *m, int *n, npy_complex64 *a, int *lda, s *s, npy_complex64 *u, int *ldu, npy_complex64 *vt, int *ldvt, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cgesvd(char *jobu, char *jobvt, int *m, int *n, c *a, int *lda, s *s, c *u, int *ldu, c *vt, int *ldvt, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgesvx "BLAS_FUNC(cgesvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgesvx(char *fact, char *trans, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetc2 "BLAS_FUNC(cgetc2)"(int *n, npy_complex64 *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void cgetc2(int *n, c *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_cgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetf2 "BLAS_FUNC(cgetf2)"(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void cgetf2(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetrf "BLAS_FUNC(cgetrf)"(int *m, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void cgetrf(int *m, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetri "BLAS_FUNC(cgetri)"(int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgetri(int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgetrs "BLAS_FUNC(cgetrs)"(char *trans, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgetrs(char *trans, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggbak "BLAS_FUNC(cggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, npy_complex64 *v, int *ldv, int *info) nogil
+cdef void cggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, c *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_cggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggbal "BLAS_FUNC(cggbal)"(char *job, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) nogil
+cdef void cggbal(char *job, int *n, c *a, int *lda, c *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil:
+    
+    _fortran_cggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgges "BLAS_FUNC(cgges)"(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, npy_complex64 *work, int *lwork, s *rwork, bint *bwork, int *info) nogil
+cdef void cgges(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, c *work, int *lwork, s *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cgges(jobvsl, jobvsr, sort, <_cselect2*>selctg, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggesx "BLAS_FUNC(cggesx)"(char *jobvsl, char *jobvsr, char *sort, _cselect2 *selctg, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *sdim, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vsl, int *ldvsl, npy_complex64 *vsr, int *ldvsr, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void cggesx(char *jobvsl, char *jobvsr, char *sort, cselect2 *selctg, char *sense, int *n, c *a, int *lda, c *b, int *ldb, int *sdim, c *alpha, c *beta, c *vsl, int *ldvsl, c *vsr, int *ldvsr, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cggesx(jobvsl, jobvsr, sort, <_cselect2*>selctg, sense, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, rwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggev "BLAS_FUNC(cggev)"(char *jobvl, char *jobvr, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cggev(char *jobvl, char *jobvr, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cggev(jobvl, jobvr, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggevx "BLAS_FUNC(cggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, npy_complex64 *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) nogil
+cdef void cggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *vl, int *ldvl, c *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, c *work, int *lwork, s *rwork, int *iwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_cggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, rwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggglm "BLAS_FUNC(cggglm)"(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *d, npy_complex64 *x, npy_complex64 *y, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cggglm(int *n, int *m, int *p, c *a, int *lda, c *b, int *ldb, c *d, c *x, c *y, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgghrd "BLAS_FUNC(cgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *info) nogil
+cdef void cgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_cgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgglse "BLAS_FUNC(cgglse)"(int *m, int *n, int *p, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, npy_complex64 *d, npy_complex64 *x, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cgglse(int *m, int *n, int *p, c *a, int *lda, c *b, int *ldb, c *c, c *d, c *x, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggqrf "BLAS_FUNC(cggqrf)"(int *n, int *m, int *p, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cggqrf(int *n, int *m, int *p, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cggrqf "BLAS_FUNC(cggrqf)"(int *m, int *p, int *n, npy_complex64 *a, int *lda, npy_complex64 *taua, npy_complex64 *b, int *ldb, npy_complex64 *taub, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cggrqf(int *m, int *p, int *n, c *a, int *lda, c *taua, c *b, int *ldb, c *taub, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtcon "BLAS_FUNC(cgtcon)"(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void cgtcon(char *norm, int *n, c *dl, c *d, c *du, c *du2, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_cgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtrfs "BLAS_FUNC(cgtrfs)"(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgtrfs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtsv "BLAS_FUNC(cgtsv)"(int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgtsv(int *n, int *nrhs, c *dl, c *d, c *du, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtsvx "BLAS_FUNC(cgtsvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *dlf, npy_complex64 *df, npy_complex64 *duf, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cgtsvx(char *fact, char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *dlf, c *df, c *duf, c *du2, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgttrf "BLAS_FUNC(cgttrf)"(int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, int *info) nogil
+cdef void cgttrf(int *n, c *dl, c *d, c *du, c *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_cgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgttrs "BLAS_FUNC(cgttrs)"(char *trans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cgttrs(char *trans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cgtts2 "BLAS_FUNC(cgtts2)"(int *itrans, int *n, int *nrhs, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *du2, int *ipiv, npy_complex64 *b, int *ldb) nogil
+cdef void cgtts2(int *itrans, int *n, int *nrhs, c *dl, c *d, c *du, c *du2, int *ipiv, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_cgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbev "BLAS_FUNC(chbev)"(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chbev(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbevd "BLAS_FUNC(chbevd)"(char *jobz, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chbevd(char *jobz, char *uplo, int *n, int *kd, c *ab, int *ldab, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbevx "BLAS_FUNC(chbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chbevx(char *jobz, char *range, char *uplo, int *n, int *kd, c *ab, int *ldab, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgst "BLAS_FUNC(chbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *x, int *ldx, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chbgst(char *vect, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *x, int *ldx, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgv "BLAS_FUNC(chbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgvd "BLAS_FUNC(chbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbgvx "BLAS_FUNC(chbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex64 *ab, int *ldab, npy_complex64 *bb, int *ldbb, npy_complex64 *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, c *ab, int *ldab, c *bb, int *ldbb, c *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chbtrd "BLAS_FUNC(chbtrd)"(char *vect, char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info) nogil
+cdef void chbtrd(char *vect, char *uplo, int *n, int *kd, c *ab, int *ldab, s *d, s *e, c *q, int *ldq, c *work, int *info) noexcept nogil:
+    
+    _fortran_chbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_checon "BLAS_FUNC(checon)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void checon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_checon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheequb "BLAS_FUNC(cheequb)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, npy_complex64 *work, int *info) nogil
+cdef void cheequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil:
+    
+    _fortran_cheequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheev "BLAS_FUNC(cheev)"(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, s *w, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void cheev(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cheev(jobz, uplo, n, a, lda, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheevd "BLAS_FUNC(cheevd)"(char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, s *w, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void cheevd(char *jobz, char *uplo, int *n, c *a, int *lda, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheevr "BLAS_FUNC(cheevr)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, int *isuppz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void cheevr(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cheevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheevx "BLAS_FUNC(cheevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void cheevx(char *jobz, char *range, char *uplo, int *n, c *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_cheevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegs2 "BLAS_FUNC(chegs2)"(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chegs2(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chegs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegst "BLAS_FUNC(chegst)"(int *itype, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chegst(int *itype, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chegst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegv "BLAS_FUNC(chegv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *w, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void chegv(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chegv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegvd "BLAS_FUNC(chegvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *w, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chegvd(int *itype, char *jobz, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *w, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chegvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chegvx "BLAS_FUNC(chegvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chegvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *a, int *lda, c *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chegvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cherfs "BLAS_FUNC(cherfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cherfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cherfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chesv "BLAS_FUNC(chesv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chesv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chesv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chesvx "BLAS_FUNC(chesvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void chesvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chesvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cheswapr "BLAS_FUNC(cheswapr)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2) nogil
+cdef void cheswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_cheswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetd2 "BLAS_FUNC(chetd2)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tau, int *info) nogil
+cdef void chetd2(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, int *info) noexcept nogil:
+    
+    _fortran_chetd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetf2 "BLAS_FUNC(chetf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void chetf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_chetf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrd "BLAS_FUNC(chetrd)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chetrd(char *uplo, int *n, c *a, int *lda, s *d, s *e, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrf "BLAS_FUNC(chetrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chetrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chetrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetri "BLAS_FUNC(chetri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void chetri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_chetri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetri2 "BLAS_FUNC(chetri2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chetri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chetri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetri2x "BLAS_FUNC(chetri2x)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info) nogil
+cdef void chetri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_chetri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrs "BLAS_FUNC(chetrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chetrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chetrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chetrs2 "BLAS_FUNC(chetrs2)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) nogil
+cdef void chetrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil:
+    
+    _fortran_chetrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chfrk "BLAS_FUNC(chfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, npy_complex64 *a, int *lda, s *beta, npy_complex64 *c) nogil
+cdef void chfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, c *a, int *lda, s *beta, c *c) noexcept nogil:
+    
+    _fortran_chfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chgeqz "BLAS_FUNC(chgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *t, int *ldt, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void chgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *t, int *ldt, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alpha, beta, q, ldq, z, ldz, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    char _fortran_chla_transtype "BLAS_FUNC(chla_transtype)"(int *trans) nogil
+cdef char chla_transtype(int *trans) noexcept nogil:
+    
+    return _fortran_chla_transtype(trans)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpcon "BLAS_FUNC(chpcon)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void chpcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_chpcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpev "BLAS_FUNC(chpev)"(char *jobz, char *uplo, int *n, npy_complex64 *ap, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chpev(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chpev(jobz, uplo, n, ap, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpevd "BLAS_FUNC(chpevd)"(char *jobz, char *uplo, int *n, npy_complex64 *ap, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chpevd(char *jobz, char *uplo, int *n, c *ap, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chpevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpevx "BLAS_FUNC(chpevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chpevx(char *jobz, char *range, char *uplo, int *n, c *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chpevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgst "BLAS_FUNC(chpgst)"(int *itype, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, int *info) nogil
+cdef void chpgst(int *itype, char *uplo, int *n, c *ap, c *bp, int *info) noexcept nogil:
+    
+    _fortran_chpgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgv "BLAS_FUNC(chpgv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chpgv(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chpgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgvd "BLAS_FUNC(chpgvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void chpgvd(int *itype, char *jobz, char *uplo, int *n, c *ap, c *bp, s *w, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_chpgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpgvx "BLAS_FUNC(chpgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, npy_complex64 *work, s *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void chpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, c *ap, c *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, c *work, s *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_chpgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chprfs "BLAS_FUNC(chprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpsv "BLAS_FUNC(chpsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chpsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chpsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chpsvx "BLAS_FUNC(chpsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void chpsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_chpsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptrd "BLAS_FUNC(chptrd)"(char *uplo, int *n, npy_complex64 *ap, s *d, s *e, npy_complex64 *tau, int *info) nogil
+cdef void chptrd(char *uplo, int *n, c *ap, s *d, s *e, c *tau, int *info) noexcept nogil:
+    
+    _fortran_chptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptrf "BLAS_FUNC(chptrf)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info) nogil
+cdef void chptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_chptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptri "BLAS_FUNC(chptri)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void chptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_chptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chptrs "BLAS_FUNC(chptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void chptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_chptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chsein "BLAS_FUNC(chsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *ifaill, int *ifailr, int *info) nogil
+cdef void chsein(char *side, char *eigsrc, char *initv, bint *select, int *n, c *h, int *ldh, c *w, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil:
+    
+    _fortran_chsein(side, eigsrc, initv, select, n, h, ldh, w, vl, ldvl, vr, ldvr, mm, m, work, rwork, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_chseqr "BLAS_FUNC(chseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void chseqr(char *job, char *compz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_chseqr(job, compz, n, ilo, ihi, h, ldh, w, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clabrd "BLAS_FUNC(clabrd)"(int *m, int *n, int *nb, npy_complex64 *a, int *lda, s *d, s *e, npy_complex64 *tauq, npy_complex64 *taup, npy_complex64 *x, int *ldx, npy_complex64 *y, int *ldy) nogil
+cdef void clabrd(int *m, int *n, int *nb, c *a, int *lda, s *d, s *e, c *tauq, c *taup, c *x, int *ldx, c *y, int *ldy) noexcept nogil:
+    
+    _fortran_clabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacgv "BLAS_FUNC(clacgv)"(int *n, npy_complex64 *x, int *incx) nogil
+cdef void clacgv(int *n, c *x, int *incx) noexcept nogil:
+    
+    _fortran_clacgv(n, x, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacn2 "BLAS_FUNC(clacn2)"(int *n, npy_complex64 *v, npy_complex64 *x, s *est, int *kase, int *isave) nogil
+cdef void clacn2(int *n, c *v, c *x, s *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_clacn2(n, v, x, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacon "BLAS_FUNC(clacon)"(int *n, npy_complex64 *v, npy_complex64 *x, s *est, int *kase) nogil
+cdef void clacon(int *n, c *v, c *x, s *est, int *kase) noexcept nogil:
+    
+    _fortran_clacon(n, v, x, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacp2 "BLAS_FUNC(clacp2)"(char *uplo, int *m, int *n, s *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void clacp2(char *uplo, int *m, int *n, s *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_clacp2(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacpy "BLAS_FUNC(clacpy)"(char *uplo, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb) nogil
+cdef void clacpy(char *uplo, int *m, int *n, c *a, int *lda, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_clacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacrm "BLAS_FUNC(clacrm)"(int *m, int *n, npy_complex64 *a, int *lda, s *b, int *ldb, npy_complex64 *c, int *ldc, s *rwork) nogil
+cdef void clacrm(int *m, int *n, c *a, int *lda, s *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil:
+    
+    _fortran_clacrm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clacrt "BLAS_FUNC(clacrt)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, npy_complex64 *c, npy_complex64 *s) nogil
+cdef void clacrt(int *n, c *cx, int *incx, c *cy, int *incy, c *c, c *s) noexcept nogil:
+    
+    _fortran_clacrt(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cladiv "F_FUNC(cladivwrp,CLADIVWRP)"(npy_complex64 *out, npy_complex64 *x, npy_complex64 *y) nogil
+cdef c cladiv(c *x, c *y) noexcept nogil:
+    cdef c out
+    _fortran_cladiv(&out, x, y)
+    return out
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claed0 "BLAS_FUNC(claed0)"(int *qsiz, int *n, s *d, s *e, npy_complex64 *q, int *ldq, npy_complex64 *qstore, int *ldqs, s *rwork, int *iwork, int *info) nogil
+cdef void claed0(int *qsiz, int *n, s *d, s *e, c *q, int *ldq, c *qstore, int *ldqs, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_claed0(qsiz, n, d, e, q, ldq, qstore, ldqs, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claed7 "BLAS_FUNC(claed7)"(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, npy_complex64 *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, npy_complex64 *work, s *rwork, int *iwork, int *info) nogil
+cdef void claed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, c *q, int *ldq, s *rho, int *indxq, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, c *work, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_claed7(n, cutpnt, qsiz, tlvls, curlvl, curpbm, d, q, ldq, rho, indxq, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claed8 "BLAS_FUNC(claed8)"(int *k, int *n, int *qsiz, npy_complex64 *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, npy_complex64 *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) nogil
+cdef void claed8(int *k, int *n, int *qsiz, c *q, int *ldq, s *d, s *rho, int *cutpnt, s *z, s *dlamda, c *q2, int *ldq2, s *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, s *givnum, int *info) noexcept nogil:
+    
+    _fortran_claed8(k, n, qsiz, q, ldq, d, rho, cutpnt, z, dlamda, q2, ldq2, w, indxp, indx, indxq, perm, givptr, givcol, givnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claein "BLAS_FUNC(claein)"(bint *rightv, bint *noinit, int *n, npy_complex64 *h, int *ldh, npy_complex64 *w, npy_complex64 *v, npy_complex64 *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) nogil
+cdef void claein(bint *rightv, bint *noinit, int *n, c *h, int *ldh, c *w, c *v, c *b, int *ldb, s *rwork, s *eps3, s *smlnum, int *info) noexcept nogil:
+    
+    _fortran_claein(rightv, noinit, n, h, ldh, w, v, b, ldb, rwork, eps3, smlnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claesy "BLAS_FUNC(claesy)"(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, npy_complex64 *rt1, npy_complex64 *rt2, npy_complex64 *evscal, npy_complex64 *cs1, npy_complex64 *sn1) nogil
+cdef void claesy(c *a, c *b, c *c, c *rt1, c *rt2, c *evscal, c *cs1, c *sn1) noexcept nogil:
+    
+    _fortran_claesy(a, b, c, rt1, rt2, evscal, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claev2 "BLAS_FUNC(claev2)"(npy_complex64 *a, npy_complex64 *b, npy_complex64 *c, s *rt1, s *rt2, s *cs1, npy_complex64 *sn1) nogil
+cdef void claev2(c *a, c *b, c *c, s *rt1, s *rt2, s *cs1, c *sn1) noexcept nogil:
+    
+    _fortran_claev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clag2z "BLAS_FUNC(clag2z)"(int *m, int *n, npy_complex64 *sa, int *ldsa, npy_complex128 *a, int *lda, int *info) nogil
+cdef void clag2z(int *m, int *n, c *sa, int *ldsa, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clag2z(m, n, sa, ldsa, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clags2 "BLAS_FUNC(clags2)"(bint *upper, s *a1, npy_complex64 *a2, s *a3, s *b1, npy_complex64 *b2, s *b3, s *csu, npy_complex64 *snu, s *csv, npy_complex64 *snv, s *csq, npy_complex64 *snq) nogil
+cdef void clags2(bint *upper, s *a1, c *a2, s *a3, s *b1, c *b2, s *b3, s *csu, c *snu, s *csv, c *snv, s *csq, c *snq) noexcept nogil:
+    
+    _fortran_clags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clagtm "BLAS_FUNC(clagtm)"(char *trans, int *n, int *nrhs, s *alpha, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du, npy_complex64 *x, int *ldx, s *beta, npy_complex64 *b, int *ldb) nogil
+cdef void clagtm(char *trans, int *n, int *nrhs, s *alpha, c *dl, c *d, c *du, c *x, int *ldx, s *beta, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_clagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clahef "BLAS_FUNC(clahef)"(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info) nogil
+cdef void clahef(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_clahef(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clahqr "BLAS_FUNC(clahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *info) nogil
+cdef void clahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_clahqr(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clahr2 "BLAS_FUNC(clahr2)"(int *n, int *k, int *nb, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *t, int *ldt, npy_complex64 *y, int *ldy) nogil
+cdef void clahr2(int *n, int *k, int *nb, c *a, int *lda, c *tau, c *t, int *ldt, c *y, int *ldy) noexcept nogil:
+    
+    _fortran_clahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claic1 "BLAS_FUNC(claic1)"(int *job, int *j, npy_complex64 *x, s *sest, npy_complex64 *w, npy_complex64 *gamma, s *sestpr, npy_complex64 *s, npy_complex64 *c) nogil
+cdef void claic1(int *job, int *j, c *x, s *sest, c *w, c *gamma, s *sestpr, c *s, c *c) noexcept nogil:
+    
+    _fortran_claic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clals0 "BLAS_FUNC(clals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) nogil
+cdef void clals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_clals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clalsa "BLAS_FUNC(clalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex64 *b, int *ldb, npy_complex64 *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) nogil
+cdef void clalsa(int *icompq, int *smlsiz, int *n, int *nrhs, c *b, int *ldb, c *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_clalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clalsd "BLAS_FUNC(clalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, npy_complex64 *b, int *ldb, s *rcond, int *rank, npy_complex64 *work, s *rwork, int *iwork, int *info) nogil
+cdef void clalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, c *b, int *ldb, s *rcond, int *rank, c *work, s *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_clalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clangb "BLAS_FUNC(clangb)"(char *norm, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clangb(char *norm, int *n, int *kl, int *ku, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clange "BLAS_FUNC(clange)"(char *norm, int *m, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clange(char *norm, int *m, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clangt "BLAS_FUNC(clangt)"(char *norm, int *n, npy_complex64 *dl, npy_complex64 *d, npy_complex64 *du) nogil
+cdef s clangt(char *norm, int *n, c *dl, c *d, c *du) noexcept nogil:
+    
+    return _fortran_clangt(norm, n, dl, d, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhb "BLAS_FUNC(clanhb)"(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clanhb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clanhb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhe "BLAS_FUNC(clanhe)"(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clanhe(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clanhe(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhf "BLAS_FUNC(clanhf)"(char *norm, char *transr, char *uplo, int *n, npy_complex64 *a, s *work) nogil
+cdef s clanhf(char *norm, char *transr, char *uplo, int *n, c *a, s *work) noexcept nogil:
+    
+    return _fortran_clanhf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhp "BLAS_FUNC(clanhp)"(char *norm, char *uplo, int *n, npy_complex64 *ap, s *work) nogil
+cdef s clanhp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil:
+    
+    return _fortran_clanhp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanhs "BLAS_FUNC(clanhs)"(char *norm, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clanhs(char *norm, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clanht "BLAS_FUNC(clanht)"(char *norm, int *n, s *d, npy_complex64 *e) nogil
+cdef s clanht(char *norm, int *n, s *d, c *e) noexcept nogil:
+    
+    return _fortran_clanht(norm, n, d, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clansb "BLAS_FUNC(clansb)"(char *norm, char *uplo, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clansb(char *norm, char *uplo, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clansp "BLAS_FUNC(clansp)"(char *norm, char *uplo, int *n, npy_complex64 *ap, s *work) nogil
+cdef s clansp(char *norm, char *uplo, int *n, c *ap, s *work) noexcept nogil:
+    
+    return _fortran_clansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clansy "BLAS_FUNC(clansy)"(char *norm, char *uplo, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clansy(char *norm, char *uplo, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clantb "BLAS_FUNC(clantb)"(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex64 *ab, int *ldab, s *work) nogil
+cdef s clantb(char *norm, char *uplo, char *diag, int *n, int *k, c *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_clantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clantp "BLAS_FUNC(clantp)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, s *work) nogil
+cdef s clantp(char *norm, char *uplo, char *diag, int *n, c *ap, s *work) noexcept nogil:
+    
+    return _fortran_clantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_clantr "BLAS_FUNC(clantr)"(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex64 *a, int *lda, s *work) nogil
+cdef s clantr(char *norm, char *uplo, char *diag, int *m, int *n, c *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_clantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clapll "BLAS_FUNC(clapll)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *ssmin) nogil
+cdef void clapll(int *n, c *x, int *incx, c *y, int *incy, s *ssmin) noexcept nogil:
+    
+    _fortran_clapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clapmr "BLAS_FUNC(clapmr)"(bint *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k) nogil
+cdef void clapmr(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_clapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clapmt "BLAS_FUNC(clapmt)"(bint *forwrd, int *m, int *n, npy_complex64 *x, int *ldx, int *k) nogil
+cdef void clapmt(bint *forwrd, int *m, int *n, c *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_clapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqgb "BLAS_FUNC(claqgb)"(int *m, int *n, int *kl, int *ku, npy_complex64 *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil
+cdef void claqgb(int *m, int *n, int *kl, int *ku, c *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqge "BLAS_FUNC(claqge)"(int *m, int *n, npy_complex64 *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil
+cdef void claqge(int *m, int *n, c *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqhb "BLAS_FUNC(claqhb)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqhb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqhb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqhe "BLAS_FUNC(claqhe)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqhe(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqhe(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqhp "BLAS_FUNC(claqhp)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqhp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqhp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqp2 "BLAS_FUNC(claqp2)"(int *m, int *n, int *offset, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, s *vn1, s *vn2, npy_complex64 *work) nogil
+cdef void claqp2(int *m, int *n, int *offset, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *work) noexcept nogil:
+    
+    _fortran_claqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqps "BLAS_FUNC(claqps)"(int *m, int *n, int *offset, int *nb, int *kb, npy_complex64 *a, int *lda, int *jpvt, npy_complex64 *tau, s *vn1, s *vn2, npy_complex64 *auxv, npy_complex64 *f, int *ldf) nogil
+cdef void claqps(int *m, int *n, int *offset, int *nb, int *kb, c *a, int *lda, int *jpvt, c *tau, s *vn1, s *vn2, c *auxv, c *f, int *ldf) noexcept nogil:
+    
+    _fortran_claqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr0 "BLAS_FUNC(claqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void claqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_claqr0(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr1 "BLAS_FUNC(claqr1)"(int *n, npy_complex64 *h, int *ldh, npy_complex64 *s1, npy_complex64 *s2, npy_complex64 *v) nogil
+cdef void claqr1(int *n, c *h, int *ldh, c *s1, c *s2, c *v) noexcept nogil:
+    
+    _fortran_claqr1(n, h, ldh, s1, s2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr2 "BLAS_FUNC(claqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork) nogil
+cdef void claqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil:
+    
+    _fortran_claqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr3 "BLAS_FUNC(claqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, int *ns, int *nd, npy_complex64 *sh, npy_complex64 *v, int *ldv, int *nh, npy_complex64 *t, int *ldt, int *nv, npy_complex64 *wv, int *ldwv, npy_complex64 *work, int *lwork) nogil
+cdef void claqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, int *ns, int *nd, c *sh, c *v, int *ldv, int *nh, c *t, int *ldt, int *nv, c *wv, int *ldwv, c *work, int *lwork) noexcept nogil:
+    
+    _fortran_claqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr4 "BLAS_FUNC(claqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex64 *h, int *ldh, npy_complex64 *w, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void claqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, c *h, int *ldh, c *w, int *iloz, int *ihiz, c *z, int *ldz, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_claqr4(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqr5 "BLAS_FUNC(claqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex64 *s, npy_complex64 *h, int *ldh, int *iloz, int *ihiz, npy_complex64 *z, int *ldz, npy_complex64 *v, int *ldv, npy_complex64 *u, int *ldu, int *nv, npy_complex64 *wv, int *ldwv, int *nh, npy_complex64 *wh, int *ldwh) nogil
+cdef void claqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, c *s, c *h, int *ldh, int *iloz, int *ihiz, c *z, int *ldz, c *v, int *ldv, c *u, int *ldu, int *nv, c *wv, int *ldwv, int *nh, c *wh, int *ldwh) noexcept nogil:
+    
+    _fortran_claqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, s, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqsb "BLAS_FUNC(claqsb)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqsb(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqsp "BLAS_FUNC(claqsp)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqsp(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claqsy "BLAS_FUNC(claqsy)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil
+cdef void claqsy(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_claqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clar1v "BLAS_FUNC(clar1v)"(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, npy_complex64 *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) nogil
+cdef void clar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, c *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil:
+    
+    _fortran_clar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clar2v "BLAS_FUNC(clar2v)"(int *n, npy_complex64 *x, npy_complex64 *y, npy_complex64 *z, int *incx, s *c, npy_complex64 *s, int *incc) nogil
+cdef void clar2v(int *n, c *x, c *y, c *z, int *incx, s *c, c *s, int *incc) noexcept nogil:
+    
+    _fortran_clar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarcm "BLAS_FUNC(clarcm)"(int *m, int *n, s *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, s *rwork) nogil
+cdef void clarcm(int *m, int *n, s *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *rwork) noexcept nogil:
+    
+    _fortran_clarcm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarf "BLAS_FUNC(clarf)"(char *side, int *m, int *n, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil
+cdef void clarf(char *side, int *m, int *n, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil:
+    
+    _fortran_clarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfb "BLAS_FUNC(clarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork) nogil
+cdef void clarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil:
+    
+    _fortran_clarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfg "BLAS_FUNC(clarfg)"(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau) nogil
+cdef void clarfg(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil:
+    
+    _fortran_clarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfgp "BLAS_FUNC(clarfgp)"(int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *tau) nogil
+cdef void clarfgp(int *n, c *alpha, c *x, int *incx, c *tau) noexcept nogil:
+    
+    _fortran_clarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarft "BLAS_FUNC(clarft)"(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt) nogil
+cdef void clarft(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil:
+    
+    _fortran_clarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarfx "BLAS_FUNC(clarfx)"(char *side, int *m, int *n, npy_complex64 *v, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil
+cdef void clarfx(char *side, int *m, int *n, c *v, c *tau, c *c, int *ldc, c *work) noexcept nogil:
+    
+    _fortran_clarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clargv "BLAS_FUNC(clargv)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *c, int *incc) nogil
+cdef void clargv(int *n, c *x, int *incx, c *y, int *incy, s *c, int *incc) noexcept nogil:
+    
+    _fortran_clargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarnv "BLAS_FUNC(clarnv)"(int *idist, int *iseed, int *n, npy_complex64 *x) nogil
+cdef void clarnv(int *idist, int *iseed, int *n, c *x) noexcept nogil:
+    
+    _fortran_clarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarrv "BLAS_FUNC(clarrv)"(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, npy_complex64 *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) nogil
+cdef void clarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, c *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_clarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clartg "BLAS_FUNC(clartg)"(npy_complex64 *f, npy_complex64 *g, s *cs, npy_complex64 *sn, npy_complex64 *r) nogil
+cdef void clartg(c *f, c *g, s *cs, c *sn, c *r) noexcept nogil:
+    
+    _fortran_clartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clartv "BLAS_FUNC(clartv)"(int *n, npy_complex64 *x, int *incx, npy_complex64 *y, int *incy, s *c, npy_complex64 *s, int *incc) nogil
+cdef void clartv(int *n, c *x, int *incx, c *y, int *incy, s *c, c *s, int *incc) noexcept nogil:
+    
+    _fortran_clartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarz "BLAS_FUNC(clarz)"(char *side, int *m, int *n, int *l, npy_complex64 *v, int *incv, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work) nogil
+cdef void clarz(char *side, int *m, int *n, int *l, c *v, int *incv, c *tau, c *c, int *ldc, c *work) noexcept nogil:
+    
+    _fortran_clarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarzb "BLAS_FUNC(clarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *c, int *ldc, npy_complex64 *work, int *ldwork) nogil
+cdef void clarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *c, int *ldc, c *work, int *ldwork) noexcept nogil:
+    
+    _fortran_clarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clarzt "BLAS_FUNC(clarzt)"(char *direct, char *storev, int *n, int *k, npy_complex64 *v, int *ldv, npy_complex64 *tau, npy_complex64 *t, int *ldt) nogil
+cdef void clarzt(char *direct, char *storev, int *n, int *k, c *v, int *ldv, c *tau, c *t, int *ldt) noexcept nogil:
+    
+    _fortran_clarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clascl "BLAS_FUNC(clascl)"(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void clascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claset "BLAS_FUNC(claset)"(char *uplo, int *m, int *n, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *a, int *lda) nogil
+cdef void claset(char *uplo, int *m, int *n, c *alpha, c *beta, c *a, int *lda) noexcept nogil:
+    
+    _fortran_claset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clasr "BLAS_FUNC(clasr)"(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, npy_complex64 *a, int *lda) nogil
+cdef void clasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, c *a, int *lda) noexcept nogil:
+    
+    _fortran_clasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_classq "BLAS_FUNC(classq)"(int *n, npy_complex64 *x, int *incx, s *scale, s *sumsq) nogil
+cdef void classq(int *n, c *x, int *incx, s *scale, s *sumsq) noexcept nogil:
+    
+    _fortran_classq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_claswp "BLAS_FUNC(claswp)"(int *n, npy_complex64 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void claswp(int *n, c *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_claswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clasyf "BLAS_FUNC(clasyf)"(char *uplo, int *n, int *nb, int *kb, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *w, int *ldw, int *info) nogil
+cdef void clasyf(char *uplo, int *n, int *nb, int *kb, c *a, int *lda, int *ipiv, c *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_clasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatbs "BLAS_FUNC(clatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex64 *ab, int *ldab, npy_complex64 *x, s *scale, s *cnorm, int *info) nogil
+cdef void clatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, c *ab, int *ldab, c *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_clatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatdf "BLAS_FUNC(clatdf)"(int *ijob, int *n, npy_complex64 *z, int *ldz, npy_complex64 *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) nogil
+cdef void clatdf(int *ijob, int *n, c *z, int *ldz, c *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_clatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatps "BLAS_FUNC(clatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *ap, npy_complex64 *x, s *scale, s *cnorm, int *info) nogil
+cdef void clatps(char *uplo, char *trans, char *diag, char *normin, int *n, c *ap, c *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_clatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatrd "BLAS_FUNC(clatrd)"(char *uplo, int *n, int *nb, npy_complex64 *a, int *lda, s *e, npy_complex64 *tau, npy_complex64 *w, int *ldw) nogil
+cdef void clatrd(char *uplo, int *n, int *nb, c *a, int *lda, s *e, c *tau, c *w, int *ldw) noexcept nogil:
+    
+    _fortran_clatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatrs "BLAS_FUNC(clatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex64 *a, int *lda, npy_complex64 *x, s *scale, s *cnorm, int *info) nogil
+cdef void clatrs(char *uplo, char *trans, char *diag, char *normin, int *n, c *a, int *lda, c *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_clatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clatrz "BLAS_FUNC(clatrz)"(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work) nogil
+cdef void clatrz(int *m, int *n, int *l, c *a, int *lda, c *tau, c *work) noexcept nogil:
+    
+    _fortran_clatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clauu2 "BLAS_FUNC(clauu2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void clauu2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_clauum "BLAS_FUNC(clauum)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void clauum(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_clauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbcon "BLAS_FUNC(cpbcon)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpbcon(char *uplo, int *n, int *kd, c *ab, int *ldab, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbequ "BLAS_FUNC(cpbequ)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, s *s, s *scond, s *amax, int *info) nogil
+cdef void cpbequ(char *uplo, int *n, int *kd, c *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbrfs "BLAS_FUNC(cpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpbrfs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbstf "BLAS_FUNC(cpbstf)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil
+cdef void cpbstf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_cpbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbsv "BLAS_FUNC(cpbsv)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpbsv(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbsvx "BLAS_FUNC(cpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *afb, int *ldafb, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *afb, int *ldafb, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbtf2 "BLAS_FUNC(cpbtf2)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil
+cdef void cpbtf2(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_cpbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbtrf "BLAS_FUNC(cpbtrf)"(char *uplo, int *n, int *kd, npy_complex64 *ab, int *ldab, int *info) nogil
+cdef void cpbtrf(char *uplo, int *n, int *kd, c *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_cpbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpbtrs "BLAS_FUNC(cpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpbtrs(char *uplo, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpftrf "BLAS_FUNC(cpftrf)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *info) nogil
+cdef void cpftrf(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil:
+    
+    _fortran_cpftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpftri "BLAS_FUNC(cpftri)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *info) nogil
+cdef void cpftri(char *transr, char *uplo, int *n, c *a, int *info) noexcept nogil:
+    
+    _fortran_cpftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpftrs "BLAS_FUNC(cpftrs)"(char *transr, char *uplo, int *n, int *nrhs, npy_complex64 *a, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpftrs(char *transr, char *uplo, int *n, int *nrhs, c *a, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpocon "BLAS_FUNC(cpocon)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpocon(char *uplo, int *n, c *a, int *lda, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpocon(uplo, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpoequ "BLAS_FUNC(cpoequ)"(int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void cpoequ(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cpoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpoequb "BLAS_FUNC(cpoequb)"(int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void cpoequb(int *n, c *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cpoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cporfs "BLAS_FUNC(cporfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cporfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cposv "BLAS_FUNC(cposv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cposv(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cposvx "BLAS_FUNC(cposvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cposvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotf2 "BLAS_FUNC(cpotf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void cpotf2(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_cpotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotrf "BLAS_FUNC(cpotrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void cpotrf(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_cpotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotri "BLAS_FUNC(cpotri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void cpotri(char *uplo, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_cpotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpotrs "BLAS_FUNC(cpotrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpotrs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppcon "BLAS_FUNC(cppcon)"(char *uplo, int *n, npy_complex64 *ap, s *anorm, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cppcon(char *uplo, int *n, c *ap, s *anorm, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cppcon(uplo, n, ap, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppequ "BLAS_FUNC(cppequ)"(char *uplo, int *n, npy_complex64 *ap, s *s, s *scond, s *amax, int *info) nogil
+cdef void cppequ(char *uplo, int *n, c *ap, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_cppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpprfs "BLAS_FUNC(cpprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cpprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppsv "BLAS_FUNC(cppsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cppsv(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cppsvx "BLAS_FUNC(cppsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, char *equed, s *s, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cppsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, char *equed, s *s, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpptrf "BLAS_FUNC(cpptrf)"(char *uplo, int *n, npy_complex64 *ap, int *info) nogil
+cdef void cpptrf(char *uplo, int *n, c *ap, int *info) noexcept nogil:
+    
+    _fortran_cpptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpptri "BLAS_FUNC(cpptri)"(char *uplo, int *n, npy_complex64 *ap, int *info) nogil
+cdef void cpptri(char *uplo, int *n, c *ap, int *info) noexcept nogil:
+    
+    _fortran_cpptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpptrs "BLAS_FUNC(cpptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpptrs(char *uplo, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpstf2 "BLAS_FUNC(cpstf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void cpstf2(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_cpstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpstrf "BLAS_FUNC(cpstrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void cpstrf(char *uplo, int *n, c *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_cpstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptcon "BLAS_FUNC(cptcon)"(int *n, s *d, npy_complex64 *e, s *anorm, s *rcond, s *rwork, int *info) nogil
+cdef void cptcon(int *n, s *d, c *e, s *anorm, s *rcond, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cptcon(n, d, e, anorm, rcond, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpteqr "BLAS_FUNC(cpteqr)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, s *work, int *info) nogil
+cdef void cpteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_cpteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptrfs "BLAS_FUNC(cptrfs)"(char *uplo, int *n, int *nrhs, s *d, npy_complex64 *e, s *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cptrfs(char *uplo, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cptrfs(uplo, n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptsv "BLAS_FUNC(cptsv)"(int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cptsv(int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptsvx "BLAS_FUNC(cptsvx)"(char *fact, int *n, int *nrhs, s *d, npy_complex64 *e, s *df, npy_complex64 *ef, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cptsvx(char *fact, int *n, int *nrhs, s *d, c *e, s *df, c *ef, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpttrf "BLAS_FUNC(cpttrf)"(int *n, s *d, npy_complex64 *e, int *info) nogil
+cdef void cpttrf(int *n, s *d, c *e, int *info) noexcept nogil:
+    
+    _fortran_cpttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cpttrs "BLAS_FUNC(cpttrs)"(char *uplo, int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cpttrs(char *uplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cpttrs(uplo, n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cptts2 "BLAS_FUNC(cptts2)"(int *iuplo, int *n, int *nrhs, s *d, npy_complex64 *e, npy_complex64 *b, int *ldb) nogil
+cdef void cptts2(int *iuplo, int *n, int *nrhs, s *d, c *e, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_cptts2(iuplo, n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_crot "BLAS_FUNC(crot)"(int *n, npy_complex64 *cx, int *incx, npy_complex64 *cy, int *incy, s *c, npy_complex64 *s) nogil
+cdef void crot(int *n, c *cx, int *incx, c *cy, int *incy, s *c, c *s) noexcept nogil:
+    
+    _fortran_crot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspcon "BLAS_FUNC(cspcon)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void cspcon(char *uplo, int *n, c *ap, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_cspcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspmv "BLAS_FUNC(cspmv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *ap, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void cspmv(char *uplo, int *n, c *alpha, c *ap, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_cspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspr "BLAS_FUNC(cspr)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *ap) nogil
+cdef void cspr(char *uplo, int *n, c *alpha, c *x, int *incx, c *ap) noexcept nogil:
+    
+    _fortran_cspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csprfs "BLAS_FUNC(csprfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void csprfs(char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_csprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspsv "BLAS_FUNC(cspsv)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void cspsv(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_cspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cspsvx "BLAS_FUNC(cspsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *afp, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void cspsvx(char *fact, char *uplo, int *n, int *nrhs, c *ap, c *afp, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_cspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csptrf "BLAS_FUNC(csptrf)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, int *info) nogil
+cdef void csptrf(char *uplo, int *n, c *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_csptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csptri "BLAS_FUNC(csptri)"(char *uplo, int *n, npy_complex64 *ap, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void csptri(char *uplo, int *n, c *ap, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_csptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csptrs "BLAS_FUNC(csptrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *ap, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void csptrs(char *uplo, int *n, int *nrhs, c *ap, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_csptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csrscl "BLAS_FUNC(csrscl)"(int *n, s *sa, npy_complex64 *sx, int *incx) nogil
+cdef void csrscl(int *n, s *sa, c *sx, int *incx) noexcept nogil:
+    
+    _fortran_csrscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstedc "BLAS_FUNC(cstedc)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void cstedc(char *compz, int *n, s *d, s *e, c *z, int *ldz, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cstedc(compz, n, d, e, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstegr "BLAS_FUNC(cstegr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, npy_complex64 *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void cstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, c *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstein "BLAS_FUNC(cstein)"(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, npy_complex64 *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void cstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, c *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_cstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cstemr "BLAS_FUNC(cstemr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, npy_complex64 *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void cstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, c *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_cstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csteqr "BLAS_FUNC(csteqr)"(char *compz, int *n, s *d, s *e, npy_complex64 *z, int *ldz, s *work, int *info) nogil
+cdef void csteqr(char *compz, int *n, s *d, s *e, c *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_csteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csycon "BLAS_FUNC(csycon)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, s *anorm, s *rcond, npy_complex64 *work, int *info) nogil
+cdef void csycon(char *uplo, int *n, c *a, int *lda, int *ipiv, s *anorm, s *rcond, c *work, int *info) noexcept nogil:
+    
+    _fortran_csycon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyconv "BLAS_FUNC(csyconv)"(char *uplo, char *way, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void csyconv(char *uplo, char *way, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_csyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyequb "BLAS_FUNC(csyequb)"(char *uplo, int *n, npy_complex64 *a, int *lda, s *s, s *scond, s *amax, npy_complex64 *work, int *info) nogil
+cdef void csyequb(char *uplo, int *n, c *a, int *lda, s *s, s *scond, s *amax, c *work, int *info) noexcept nogil:
+    
+    _fortran_csyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csymv "BLAS_FUNC(csymv)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *a, int *lda, npy_complex64 *x, int *incx, npy_complex64 *beta, npy_complex64 *y, int *incy) nogil
+cdef void csymv(char *uplo, int *n, c *alpha, c *a, int *lda, c *x, int *incx, c *beta, c *y, int *incy) noexcept nogil:
+    
+    _fortran_csymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyr "BLAS_FUNC(csyr)"(char *uplo, int *n, npy_complex64 *alpha, npy_complex64 *x, int *incx, npy_complex64 *a, int *lda) nogil
+cdef void csyr(char *uplo, int *n, c *alpha, c *x, int *incx, c *a, int *lda) noexcept nogil:
+    
+    _fortran_csyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyrfs "BLAS_FUNC(csyrfs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void csyrfs(char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_csyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csysv "BLAS_FUNC(csysv)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void csysv(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_csysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csysvx "BLAS_FUNC(csysvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *af, int *ldaf, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *rcond, s *ferr, s *berr, npy_complex64 *work, int *lwork, s *rwork, int *info) nogil
+cdef void csysvx(char *fact, char *uplo, int *n, int *nrhs, c *a, int *lda, c *af, int *ldaf, int *ipiv, c *b, int *ldb, c *x, int *ldx, s *rcond, s *ferr, s *berr, c *work, int *lwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_csysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csyswapr "BLAS_FUNC(csyswapr)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *i1, int *i2) nogil
+cdef void csyswapr(char *uplo, int *n, c *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_csyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytf2 "BLAS_FUNC(csytf2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, int *info) nogil
+cdef void csytf2(char *uplo, int *n, c *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_csytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytrf "BLAS_FUNC(csytrf)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void csytrf(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_csytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytri "BLAS_FUNC(csytri)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *info) nogil
+cdef void csytri(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *info) noexcept nogil:
+    
+    _fortran_csytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytri2 "BLAS_FUNC(csytri2)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void csytri2(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_csytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytri2x "BLAS_FUNC(csytri2x)"(char *uplo, int *n, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *work, int *nb, int *info) nogil
+cdef void csytri2x(char *uplo, int *n, c *a, int *lda, int *ipiv, c *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_csytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytrs "BLAS_FUNC(csytrs)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void csytrs(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_csytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_csytrs2 "BLAS_FUNC(csytrs2)"(char *uplo, int *n, int *nrhs, npy_complex64 *a, int *lda, int *ipiv, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) nogil
+cdef void csytrs2(char *uplo, int *n, int *nrhs, c *a, int *lda, int *ipiv, c *b, int *ldb, c *work, int *info) noexcept nogil:
+    
+    _fortran_csytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctbcon "BLAS_FUNC(ctbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex64 *ab, int *ldab, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctbcon(char *norm, char *uplo, char *diag, int *n, int *kd, c *ab, int *ldab, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctbrfs "BLAS_FUNC(ctbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctbtrs "BLAS_FUNC(ctbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex64 *ab, int *ldab, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void ctbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, c *ab, int *ldab, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ctbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctfsm "BLAS_FUNC(ctfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex64 *alpha, npy_complex64 *a, npy_complex64 *b, int *ldb) nogil
+cdef void ctfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, c *alpha, c *a, c *b, int *ldb) noexcept nogil:
+    
+    _fortran_ctfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctftri "BLAS_FUNC(ctftri)"(char *transr, char *uplo, char *diag, int *n, npy_complex64 *a, int *info) nogil
+cdef void ctftri(char *transr, char *uplo, char *diag, int *n, c *a, int *info) noexcept nogil:
+    
+    _fortran_ctftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctfttp "BLAS_FUNC(ctfttp)"(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *ap, int *info) nogil
+cdef void ctfttp(char *transr, char *uplo, int *n, c *arf, c *ap, int *info) noexcept nogil:
+    
+    _fortran_ctfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctfttr "BLAS_FUNC(ctfttr)"(char *transr, char *uplo, int *n, npy_complex64 *arf, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctfttr(char *transr, char *uplo, int *n, c *arf, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgevc "BLAS_FUNC(ctgevc)"(char *side, char *howmny, bint *select, int *n, npy_complex64 *s, int *lds, npy_complex64 *p, int *ldp, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctgevc(char *side, char *howmny, bint *select, int *n, c *s, int *lds, c *p, int *ldp, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgex2 "BLAS_FUNC(ctgex2)"(bint *wantq, bint *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *j1, int *info) nogil
+cdef void ctgex2(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *j1, int *info) noexcept nogil:
+    
+    _fortran_ctgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgexc "BLAS_FUNC(ctgexc)"(bint *wantq, bint *wantz, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *ifst, int *ilst, int *info) nogil
+cdef void ctgexc(bint *wantq, bint *wantz, int *n, c *a, int *lda, c *b, int *ldb, c *q, int *ldq, c *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ctgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsen "BLAS_FUNC(ctgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *alpha, npy_complex64 *beta, npy_complex64 *q, int *ldq, npy_complex64 *z, int *ldz, int *m, s *pl, s *pr, s *dif, npy_complex64 *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ctgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *alpha, c *beta, c *q, int *ldq, c *z, int *ldz, int *m, s *pl, s *pr, s *dif, c *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ctgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alpha, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsja "BLAS_FUNC(ctgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, npy_complex64 *u, int *ldu, npy_complex64 *v, int *ldv, npy_complex64 *q, int *ldq, npy_complex64 *work, int *ncycle, int *info) nogil
+cdef void ctgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, c *a, int *lda, c *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, c *u, int *ldu, c *v, int *ldv, c *q, int *ldq, c *work, int *ncycle, int *info) noexcept nogil:
+    
+    _fortran_ctgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsna "BLAS_FUNC(ctgsna)"(char *job, char *howmny, bint *select, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, s *s, s *dif, int *mm, int *m, npy_complex64 *work, int *lwork, int *iwork, int *info) nogil
+cdef void ctgsna(char *job, char *howmny, bint *select, int *n, c *a, int *lda, c *b, int *ldb, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *dif, int *mm, int *m, c *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ctgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsy2 "BLAS_FUNC(ctgsy2)"(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) nogil
+cdef void ctgsy2(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *info) noexcept nogil:
+    
+    _fortran_ctgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctgsyl "BLAS_FUNC(ctgsyl)"(char *trans, int *ijob, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, npy_complex64 *d, int *ldd, npy_complex64 *e, int *lde, npy_complex64 *f, int *ldf, s *scale, s *dif, npy_complex64 *work, int *lwork, int *iwork, int *info) nogil
+cdef void ctgsyl(char *trans, int *ijob, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, c *d, int *ldd, c *e, int *lde, c *f, int *ldf, s *scale, s *dif, c *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ctgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpcon "BLAS_FUNC(ctpcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *ap, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctpcon(char *norm, char *uplo, char *diag, int *n, c *ap, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctpcon(norm, uplo, diag, n, ap, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpmqrt "BLAS_FUNC(ctpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *info) nogil
+cdef void ctpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *info) noexcept nogil:
+    
+    _fortran_ctpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpqrt "BLAS_FUNC(ctpqrt)"(int *m, int *n, int *l, int *nb, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, npy_complex64 *work, int *info) nogil
+cdef void ctpqrt(int *m, int *n, int *l, int *nb, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, c *work, int *info) noexcept nogil:
+    
+    _fortran_ctpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpqrt2 "BLAS_FUNC(ctpqrt2)"(int *m, int *n, int *l, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *t, int *ldt, int *info) nogil
+cdef void ctpqrt2(int *m, int *n, int *l, c *a, int *lda, c *b, int *ldb, c *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_ctpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctprfb "BLAS_FUNC(ctprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex64 *v, int *ldv, npy_complex64 *t, int *ldt, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *work, int *ldwork) nogil
+cdef void ctprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, c *v, int *ldv, c *t, int *ldt, c *a, int *lda, c *b, int *ldb, c *work, int *ldwork) noexcept nogil:
+    
+    _fortran_ctprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctprfs "BLAS_FUNC(ctprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctptri "BLAS_FUNC(ctptri)"(char *uplo, char *diag, int *n, npy_complex64 *ap, int *info) nogil
+cdef void ctptri(char *uplo, char *diag, int *n, c *ap, int *info) noexcept nogil:
+    
+    _fortran_ctptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctptrs "BLAS_FUNC(ctptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *ap, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void ctptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *ap, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ctptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpttf "BLAS_FUNC(ctpttf)"(char *transr, char *uplo, int *n, npy_complex64 *ap, npy_complex64 *arf, int *info) nogil
+cdef void ctpttf(char *transr, char *uplo, int *n, c *ap, c *arf, int *info) noexcept nogil:
+    
+    _fortran_ctpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctpttr "BLAS_FUNC(ctpttr)"(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctpttr(char *uplo, int *n, c *ap, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrcon "BLAS_FUNC(ctrcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, s *rcond, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctrcon(char *norm, char *uplo, char *diag, int *n, c *a, int *lda, s *rcond, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctrcon(norm, uplo, diag, n, a, lda, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrevc "BLAS_FUNC(ctrevc)"(char *side, char *howmny, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, int *mm, int *m, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctrevc(char *side, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, int *mm, int *m, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrexc "BLAS_FUNC(ctrexc)"(char *compq, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, int *ifst, int *ilst, int *info) nogil
+cdef void ctrexc(char *compq, int *n, c *t, int *ldt, c *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ctrexc(compq, n, t, ldt, q, ldq, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrrfs "BLAS_FUNC(ctrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *x, int *ldx, s *ferr, s *berr, npy_complex64 *work, s *rwork, int *info) nogil
+cdef void ctrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, c *x, int *ldx, s *ferr, s *berr, c *work, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrsen "BLAS_FUNC(ctrsen)"(char *job, char *compq, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *q, int *ldq, npy_complex64 *w, int *m, s *s, s *sep, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void ctrsen(char *job, char *compq, bint *select, int *n, c *t, int *ldt, c *q, int *ldq, c *w, int *m, s *s, s *sep, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ctrsen(job, compq, select, n, t, ldt, q, ldq, w, m, s, sep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrsna "BLAS_FUNC(ctrsna)"(char *job, char *howmny, bint *select, int *n, npy_complex64 *t, int *ldt, npy_complex64 *vl, int *ldvl, npy_complex64 *vr, int *ldvr, s *s, s *sep, int *mm, int *m, npy_complex64 *work, int *ldwork, s *rwork, int *info) nogil
+cdef void ctrsna(char *job, char *howmny, bint *select, int *n, c *t, int *ldt, c *vl, int *ldvl, c *vr, int *ldvr, s *s, s *sep, int *mm, int *m, c *work, int *ldwork, s *rwork, int *info) noexcept nogil:
+    
+    _fortran_ctrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrsyl "BLAS_FUNC(ctrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, npy_complex64 *c, int *ldc, s *scale, int *info) nogil
+cdef void ctrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, c *a, int *lda, c *b, int *ldb, c *c, int *ldc, s *scale, int *info) noexcept nogil:
+    
+    _fortran_ctrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrti2 "BLAS_FUNC(ctrti2)"(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctrti2(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctrti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrtri "BLAS_FUNC(ctrtri)"(char *uplo, char *diag, int *n, npy_complex64 *a, int *lda, int *info) nogil
+cdef void ctrtri(char *uplo, char *diag, int *n, c *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ctrtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrtrs "BLAS_FUNC(ctrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex64 *a, int *lda, npy_complex64 *b, int *ldb, int *info) nogil
+cdef void ctrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, c *a, int *lda, c *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ctrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrttf "BLAS_FUNC(ctrttf)"(char *transr, char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *arf, int *info) nogil
+cdef void ctrttf(char *transr, char *uplo, int *n, c *a, int *lda, c *arf, int *info) noexcept nogil:
+    
+    _fortran_ctrttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctrttp "BLAS_FUNC(ctrttp)"(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *ap, int *info) nogil
+cdef void ctrttp(char *uplo, int *n, c *a, int *lda, c *ap, int *info) noexcept nogil:
+    
+    _fortran_ctrttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ctzrzf "BLAS_FUNC(ctzrzf)"(int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void ctzrzf(int *m, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ctzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunbdb "BLAS_FUNC(cunbdb)"(char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, s *theta, s *phi, npy_complex64 *taup1, npy_complex64 *taup2, npy_complex64 *tauq1, npy_complex64 *tauq2, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunbdb(char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, s *phi, c *taup1, c *taup2, c *tauq1, c *tauq2, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cuncsd "BLAS_FUNC(cuncsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex64 *x11, int *ldx11, npy_complex64 *x12, int *ldx12, npy_complex64 *x21, int *ldx21, npy_complex64 *x22, int *ldx22, s *theta, npy_complex64 *u1, int *ldu1, npy_complex64 *u2, int *ldu2, npy_complex64 *v1t, int *ldv1t, npy_complex64 *v2t, int *ldv2t, npy_complex64 *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) nogil
+cdef void cuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, c *x11, int *ldx11, c *x12, int *ldx12, c *x21, int *ldx21, c *x22, int *ldx22, s *theta, c *u1, int *ldu1, c *u2, int *ldu2, c *v1t, int *ldv1t, c *v2t, int *ldv2t, c *work, int *lwork, s *rwork, int *lrwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_cuncsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, rwork, lrwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cung2l "BLAS_FUNC(cung2l)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cung2l(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cung2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cung2r "BLAS_FUNC(cung2r)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cung2r(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cung2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungbr "BLAS_FUNC(cungbr)"(char *vect, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungbr(char *vect, int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunghr "BLAS_FUNC(cunghr)"(int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunghr(int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungl2 "BLAS_FUNC(cungl2)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cungl2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cungl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunglq "BLAS_FUNC(cunglq)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunglq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungql "BLAS_FUNC(cungql)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungql(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungqr "BLAS_FUNC(cungqr)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungqr(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungr2 "BLAS_FUNC(cungr2)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *info) nogil
+cdef void cungr2(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *info) noexcept nogil:
+    
+    _fortran_cungr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungrq "BLAS_FUNC(cungrq)"(int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungrq(int *m, int *n, int *k, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cungtr "BLAS_FUNC(cungtr)"(char *uplo, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cungtr(char *uplo, int *n, c *a, int *lda, c *tau, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cungtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunm2l "BLAS_FUNC(cunm2l)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunm2l(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunm2r "BLAS_FUNC(cunm2r)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunm2r(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmbr "BLAS_FUNC(cunmbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmhr "BLAS_FUNC(cunmhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunml2 "BLAS_FUNC(cunml2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunml2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmlq "BLAS_FUNC(cunmlq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmlq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmql "BLAS_FUNC(cunmql)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmql(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmqr "BLAS_FUNC(cunmqr)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmqr(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmr2 "BLAS_FUNC(cunmr2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunmr2(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunmr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmr3 "BLAS_FUNC(cunmr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cunmr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmrq "BLAS_FUNC(cunmrq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmrq(char *side, char *trans, int *m, int *n, int *k, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmrz "BLAS_FUNC(cunmrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cunmtr "BLAS_FUNC(cunmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *a, int *lda, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *lwork, int *info) nogil
+cdef void cunmtr(char *side, char *uplo, char *trans, int *m, int *n, c *a, int *lda, c *tau, c *c, int *ldc, c *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_cunmtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cupgtr "BLAS_FUNC(cupgtr)"(char *uplo, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *q, int *ldq, npy_complex64 *work, int *info) nogil
+cdef void cupgtr(char *uplo, int *n, c *ap, c *tau, c *q, int *ldq, c *work, int *info) noexcept nogil:
+    
+    _fortran_cupgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_cupmtr "BLAS_FUNC(cupmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex64 *ap, npy_complex64 *tau, npy_complex64 *c, int *ldc, npy_complex64 *work, int *info) nogil
+cdef void cupmtr(char *side, char *uplo, char *trans, int *m, int *n, c *ap, c *tau, c *c, int *ldc, c *work, int *info) noexcept nogil:
+    
+    _fortran_cupmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dbbcsd "BLAS_FUNC(dbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) nogil
+cdef void dbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dbdsdc "BLAS_FUNC(dbdsdc)"(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) nogil
+cdef void dbdsdc(char *uplo, char *compq, int *n, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, d *q, int *iq, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dbdsdc(uplo, compq, n, d, e, u, ldu, vt, ldvt, q, iq, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dbdsqr "BLAS_FUNC(dbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) nogil
+cdef void dbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ddisna "BLAS_FUNC(ddisna)"(char *job, int *m, int *n, d *d, d *sep, int *info) nogil
+cdef void ddisna(char *job, int *m, int *n, d *d, d *sep, int *info) noexcept nogil:
+    
+    _fortran_ddisna(job, m, n, d, sep, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbbrd "BLAS_FUNC(dgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) nogil
+cdef void dgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *pt, int *ldpt, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbcon "BLAS_FUNC(dgbcon)"(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dgbcon(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbequ "BLAS_FUNC(dgbequ)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void dgbequ(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbequb "BLAS_FUNC(dgbequb)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void dgbequb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbrfs "BLAS_FUNC(dgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbsv "BLAS_FUNC(dgbsv)"(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgbsv(int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbsvx "BLAS_FUNC(dgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbtf2 "BLAS_FUNC(dgbtf2)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void dgbtf2(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbtrf "BLAS_FUNC(dgbtrf)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void dgbtrf(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgbtrs "BLAS_FUNC(dgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, d *ab, int *ldab, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebak "BLAS_FUNC(dgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) nogil
+cdef void dgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, d *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_dgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebal "BLAS_FUNC(dgebal)"(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) nogil
+cdef void dgebal(char *job, int *n, d *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil:
+    
+    _fortran_dgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebd2 "BLAS_FUNC(dgebd2)"(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) nogil
+cdef void dgebd2(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgebrd "BLAS_FUNC(dgebrd)"(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) nogil
+cdef void dgebrd(int *m, int *n, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgecon "BLAS_FUNC(dgecon)"(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dgecon(char *norm, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgecon(norm, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeequ "BLAS_FUNC(dgeequ)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void dgeequ(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeequb "BLAS_FUNC(dgeequb)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void dgeequb(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgees "BLAS_FUNC(dgees)"(char *jobvs, char *sort, _dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) nogil
+cdef void dgees(char *jobvs, char *sort, dselect2 *select, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *work, int *lwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dgees(jobvs, sort, <_dselect2*>select, n, a, lda, sdim, wr, wi, vs, ldvs, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeesx "BLAS_FUNC(dgeesx)"(char *jobvs, char *sort, _dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void dgeesx(char *jobvs, char *sort, dselect2 *select, char *sense, int *n, d *a, int *lda, int *sdim, d *wr, d *wi, d *vs, int *ldvs, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dgeesx(jobvs, sort, <_dselect2*>select, sense, n, a, lda, sdim, wr, wi, vs, ldvs, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeev "BLAS_FUNC(dgeev)"(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) nogil
+cdef void dgeev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeevx "BLAS_FUNC(dgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgeevx(balanc, jobvl, jobvr, sense, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgehd2 "BLAS_FUNC(dgehd2)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgehd2(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgehrd "BLAS_FUNC(dgehrd)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgehrd(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgejsv "BLAS_FUNC(dgejsv)"(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, d *a, int *lda, d *sva, d *u, int *ldu, d *v, int *ldv, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgejsv(joba, jobu, jobv, jobr, jobt, jobp, m, n, a, lda, sva, u, ldu, v, ldv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelq2 "BLAS_FUNC(dgelq2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgelq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelqf "BLAS_FUNC(dgelqf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgelqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgels "BLAS_FUNC(dgels)"(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) nogil
+cdef void dgels(char *trans, int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelsd "BLAS_FUNC(dgelsd)"(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dgelsd(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelss "BLAS_FUNC(dgelss)"(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) nogil
+cdef void dgelss(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *s, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgelsy "BLAS_FUNC(dgelsy)"(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) nogil
+cdef void dgelsy(int *m, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *jpvt, d *rcond, int *rank, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgemqrt "BLAS_FUNC(dgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) nogil
+cdef void dgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeql2 "BLAS_FUNC(dgeql2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgeql2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqlf "BLAS_FUNC(dgeqlf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqlf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqp3 "BLAS_FUNC(dgeqp3)"(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqp3(int *m, int *n, d *a, int *lda, int *jpvt, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqr2 "BLAS_FUNC(dgeqr2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgeqr2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqr2p "BLAS_FUNC(dgeqr2p)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgeqr2p(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrf "BLAS_FUNC(dgeqrf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqrf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrfp "BLAS_FUNC(dgeqrfp)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgeqrfp(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrt "BLAS_FUNC(dgeqrt)"(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) nogil
+cdef void dgeqrt(int *m, int *n, int *nb, d *a, int *lda, d *t, int *ldt, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrt2 "BLAS_FUNC(dgeqrt2)"(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) nogil
+cdef void dgeqrt2(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_dgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgeqrt3 "BLAS_FUNC(dgeqrt3)"(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) nogil
+cdef void dgeqrt3(int *m, int *n, d *a, int *lda, d *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_dgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgerfs "BLAS_FUNC(dgerfs)"(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgerfs(char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgerq2 "BLAS_FUNC(dgerq2)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dgerq2(int *m, int *n, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgerqf "BLAS_FUNC(dgerqf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dgerqf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesc2 "BLAS_FUNC(dgesc2)"(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) nogil
+cdef void dgesc2(int *n, d *a, int *lda, d *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil:
+    
+    _fortran_dgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesdd "BLAS_FUNC(dgesdd)"(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dgesdd(char *jobz, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesv "BLAS_FUNC(dgesv)"(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesvd "BLAS_FUNC(dgesvd)"(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) nogil
+cdef void dgesvd(char *jobu, char *jobvt, int *m, int *n, d *a, int *lda, d *s, d *u, int *ldu, d *vt, int *ldvt, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesvj "BLAS_FUNC(dgesvj)"(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) nogil
+cdef void dgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, d *a, int *lda, d *sva, int *mv, d *v, int *ldv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgesvj(joba, jobu, jobv, m, n, a, lda, sva, mv, v, ldv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgesvx "BLAS_FUNC(dgesvx)"(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgesvx(char *fact, char *trans, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetc2 "BLAS_FUNC(dgetc2)"(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void dgetc2(int *n, d *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_dgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetf2 "BLAS_FUNC(dgetf2)"(int *m, int *n, d *a, int *lda, int *ipiv, int *info) nogil
+cdef void dgetf2(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetrf "BLAS_FUNC(dgetrf)"(int *m, int *n, d *a, int *lda, int *ipiv, int *info) nogil
+cdef void dgetrf(int *m, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetri "BLAS_FUNC(dgetri)"(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil
+cdef void dgetri(int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgetrs "BLAS_FUNC(dgetrs)"(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgetrs(char *trans, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggbak "BLAS_FUNC(dggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) nogil
+cdef void dggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, d *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_dggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggbal "BLAS_FUNC(dggbal)"(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) nogil
+cdef void dggbal(char *job, int *n, d *a, int *lda, d *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil:
+    
+    _fortran_dggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgges "BLAS_FUNC(dgges)"(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) nogil
+cdef void dgges(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *work, int *lwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dgges(jobvsl, jobvsr, sort, <_dselect3*>selctg, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggesx "BLAS_FUNC(dggesx)"(char *jobvsl, char *jobvsr, char *sort, _dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void dggesx(char *jobvsl, char *jobvsr, char *sort, dselect3 *selctg, char *sense, int *n, d *a, int *lda, d *b, int *ldb, int *sdim, d *alphar, d *alphai, d *beta, d *vsl, int *ldvsl, d *vsr, int *ldvsr, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dggesx(jobvsl, jobvsr, sort, <_dselect3*>selctg, sense, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggev "BLAS_FUNC(dggev)"(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) nogil
+cdef void dggev(char *jobvl, char *jobvr, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggevx "BLAS_FUNC(dggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) nogil
+cdef void dggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *vl, int *ldvl, d *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, d *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_dggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggglm "BLAS_FUNC(dggglm)"(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) nogil
+cdef void dggglm(int *n, int *m, int *p, d *a, int *lda, d *b, int *ldb, d *d, d *x, d *y, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgghrd "BLAS_FUNC(dgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) nogil
+cdef void dgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_dgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgglse "BLAS_FUNC(dgglse)"(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) nogil
+cdef void dgglse(int *m, int *n, int *p, d *a, int *lda, d *b, int *ldb, d *c, d *d, d *x, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggqrf "BLAS_FUNC(dggqrf)"(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) nogil
+cdef void dggqrf(int *n, int *m, int *p, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dggrqf "BLAS_FUNC(dggrqf)"(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) nogil
+cdef void dggrqf(int *m, int *p, int *n, d *a, int *lda, d *taua, d *b, int *ldb, d *taub, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgsvj0 "BLAS_FUNC(dgsvj0)"(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) nogil
+cdef void dgsvj0(char *jobv, int *m, int *n, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgsvj0(jobv, m, n, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgsvj1 "BLAS_FUNC(dgsvj1)"(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) nogil
+cdef void dgsvj1(char *jobv, int *m, int *n, int *n1, d *a, int *lda, d *d, d *sva, int *mv, d *v, int *ldv, d *eps, d *sfmin, d *tol, int *nsweep, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dgsvj1(jobv, m, n, n1, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtcon "BLAS_FUNC(dgtcon)"(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dgtcon(char *norm, int *n, d *dl, d *d, d *du, d *du2, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtrfs "BLAS_FUNC(dgtrfs)"(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgtrfs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtsv "BLAS_FUNC(dgtsv)"(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) nogil
+cdef void dgtsv(int *n, int *nrhs, d *dl, d *d, d *du, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtsvx "BLAS_FUNC(dgtsvx)"(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dgtsvx(char *fact, char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *dlf, d *df, d *duf, d *du2, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgttrf "BLAS_FUNC(dgttrf)"(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) nogil
+cdef void dgttrf(int *n, d *dl, d *d, d *du, d *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgttrs "BLAS_FUNC(dgttrs)"(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dgttrs(char *trans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dgtts2 "BLAS_FUNC(dgtts2)"(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) nogil
+cdef void dgtts2(int *itrans, int *n, int *nrhs, d *dl, d *d, d *du, d *du2, int *ipiv, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dhgeqz "BLAS_FUNC(dhgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) nogil
+cdef void dhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *t, int *ldt, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dhgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alphar, alphai, beta, q, ldq, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dhsein "BLAS_FUNC(dhsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) nogil
+cdef void dhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, d *h, int *ldh, d *wr, d *wi, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *ifaill, int *ifailr, int *info) noexcept nogil:
+    
+    _fortran_dhsein(side, eigsrc, initv, select, n, h, ldh, wr, wi, vl, ldvl, vr, ldvr, mm, m, work, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dhseqr "BLAS_FUNC(dhseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) nogil
+cdef void dhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dhseqr(job, compz, n, ilo, ihi, h, ldh, wr, wi, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    bint _fortran_disnan "BLAS_FUNC(disnan)"(d *din) nogil
+cdef bint disnan(d *din) noexcept nogil:
+    
+    return _fortran_disnan(din)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlabad "BLAS_FUNC(dlabad)"(d *small, d *large) nogil
+cdef void dlabad(d *small, d *large) noexcept nogil:
+    
+    _fortran_dlabad(small, large)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlabrd "BLAS_FUNC(dlabrd)"(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) nogil
+cdef void dlabrd(int *m, int *n, int *nb, d *a, int *lda, d *d, d *e, d *tauq, d *taup, d *x, int *ldx, d *y, int *ldy) noexcept nogil:
+    
+    _fortran_dlabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlacn2 "BLAS_FUNC(dlacn2)"(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) nogil
+cdef void dlacn2(int *n, d *v, d *x, int *isgn, d *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_dlacn2(n, v, x, isgn, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlacon "BLAS_FUNC(dlacon)"(int *n, d *v, d *x, int *isgn, d *est, int *kase) nogil
+cdef void dlacon(int *n, d *v, d *x, int *isgn, d *est, int *kase) noexcept nogil:
+    
+    _fortran_dlacon(n, v, x, isgn, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlacpy "BLAS_FUNC(dlacpy)"(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) nogil
+cdef void dlacpy(char *uplo, int *m, int *n, d *a, int *lda, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dlacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dladiv "BLAS_FUNC(dladiv)"(d *a, d *b, d *c, d *d, d *p, d *q) nogil
+cdef void dladiv(d *a, d *b, d *c, d *d, d *p, d *q) noexcept nogil:
+    
+    _fortran_dladiv(a, b, c, d, p, q)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlae2 "BLAS_FUNC(dlae2)"(d *a, d *b, d *c, d *rt1, d *rt2) nogil
+cdef void dlae2(d *a, d *b, d *c, d *rt1, d *rt2) noexcept nogil:
+    
+    _fortran_dlae2(a, b, c, rt1, rt2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaebz "BLAS_FUNC(dlaebz)"(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) nogil
+cdef void dlaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, d *abstol, d *reltol, d *pivmin, d *d, d *e, d *e2, int *nval, d *ab, d *c, int *mout, int *nab, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlaebz(ijob, nitmax, n, mmax, minp, nbmin, abstol, reltol, pivmin, d, e, e2, nval, ab, c, mout, nab, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed0 "BLAS_FUNC(dlaed0)"(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) nogil
+cdef void dlaed0(int *icompq, int *qsiz, int *n, d *d, d *e, d *q, int *ldq, d *qstore, int *ldqs, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlaed0(icompq, qsiz, n, d, e, q, ldq, qstore, ldqs, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed1 "BLAS_FUNC(dlaed1)"(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) nogil
+cdef void dlaed1(int *n, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlaed1(n, d, q, ldq, indxq, rho, cutpnt, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed2 "BLAS_FUNC(dlaed2)"(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) nogil
+cdef void dlaed2(int *k, int *n, int *n1, d *d, d *q, int *ldq, int *indxq, d *rho, d *z, d *dlamda, d *w, d *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil:
+    
+    _fortran_dlaed2(k, n, n1, d, q, ldq, indxq, rho, z, dlamda, w, q2, indx, indxc, indxp, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed3 "BLAS_FUNC(dlaed3)"(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) nogil
+cdef void dlaed3(int *k, int *n, int *n1, d *d, d *q, int *ldq, d *rho, d *dlamda, d *q2, int *indx, int *ctot, d *w, d *s, int *info) noexcept nogil:
+    
+    _fortran_dlaed3(k, n, n1, d, q, ldq, rho, dlamda, q2, indx, ctot, w, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed4 "BLAS_FUNC(dlaed4)"(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) nogil
+cdef void dlaed4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *dlam, int *info) noexcept nogil:
+    
+    _fortran_dlaed4(n, i, d, z, delta, rho, dlam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed5 "BLAS_FUNC(dlaed5)"(int *i, d *d, d *z, d *delta, d *rho, d *dlam) nogil
+cdef void dlaed5(int *i, d *d, d *z, d *delta, d *rho, d *dlam) noexcept nogil:
+    
+    _fortran_dlaed5(i, d, z, delta, rho, dlam)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed6 "BLAS_FUNC(dlaed6)"(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) nogil
+cdef void dlaed6(int *kniter, bint *orgati, d *rho, d *d, d *z, d *finit, d *tau, int *info) noexcept nogil:
+    
+    _fortran_dlaed6(kniter, orgati, rho, d, z, finit, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed7 "BLAS_FUNC(dlaed7)"(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) nogil
+cdef void dlaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlaed7(icompq, n, qsiz, tlvls, curlvl, curpbm, d, q, ldq, indxq, rho, cutpnt, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed8 "BLAS_FUNC(dlaed8)"(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) nogil
+cdef void dlaed8(int *icompq, int *k, int *n, int *qsiz, d *d, d *q, int *ldq, int *indxq, d *rho, int *cutpnt, d *z, d *dlamda, d *q2, int *ldq2, d *w, int *perm, int *givptr, int *givcol, d *givnum, int *indxp, int *indx, int *info) noexcept nogil:
+    
+    _fortran_dlaed8(icompq, k, n, qsiz, d, q, ldq, indxq, rho, cutpnt, z, dlamda, q2, ldq2, w, perm, givptr, givcol, givnum, indxp, indx, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaed9 "BLAS_FUNC(dlaed9)"(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) nogil
+cdef void dlaed9(int *k, int *kstart, int *kstop, int *n, d *d, d *q, int *ldq, d *rho, d *dlamda, d *w, d *s, int *lds, int *info) noexcept nogil:
+    
+    _fortran_dlaed9(k, kstart, kstop, n, d, q, ldq, rho, dlamda, w, s, lds, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaeda "BLAS_FUNC(dlaeda)"(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) nogil
+cdef void dlaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, d *q, int *qptr, d *z, d *ztemp, int *info) noexcept nogil:
+    
+    _fortran_dlaeda(n, tlvls, curlvl, curpbm, prmptr, perm, givptr, givcol, givnum, q, qptr, z, ztemp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaein "BLAS_FUNC(dlaein)"(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) nogil
+cdef void dlaein(bint *rightv, bint *noinit, int *n, d *h, int *ldh, d *wr, d *wi, d *vr, d *vi, d *b, int *ldb, d *work, d *eps3, d *smlnum, d *bignum, int *info) noexcept nogil:
+    
+    _fortran_dlaein(rightv, noinit, n, h, ldh, wr, wi, vr, vi, b, ldb, work, eps3, smlnum, bignum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaev2 "BLAS_FUNC(dlaev2)"(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) nogil
+cdef void dlaev2(d *a, d *b, d *c, d *rt1, d *rt2, d *cs1, d *sn1) noexcept nogil:
+    
+    _fortran_dlaev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaexc "BLAS_FUNC(dlaexc)"(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) nogil
+cdef void dlaexc(bint *wantq, int *n, d *t, int *ldt, d *q, int *ldq, int *j1, int *n1, int *n2, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlaexc(wantq, n, t, ldt, q, ldq, j1, n1, n2, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlag2 "BLAS_FUNC(dlag2)"(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) nogil
+cdef void dlag2(d *a, int *lda, d *b, int *ldb, d *safmin, d *scale1, d *scale2, d *wr1, d *wr2, d *wi) noexcept nogil:
+    
+    _fortran_dlag2(a, lda, b, ldb, safmin, scale1, scale2, wr1, wr2, wi)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlag2s "BLAS_FUNC(dlag2s)"(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) nogil
+cdef void dlag2s(int *m, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_dlag2s(m, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlags2 "BLAS_FUNC(dlags2)"(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) nogil
+cdef void dlags2(bint *upper, d *a1, d *a2, d *a3, d *b1, d *b2, d *b3, d *csu, d *snu, d *csv, d *snv, d *csq, d *snq) noexcept nogil:
+    
+    _fortran_dlags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagtf "BLAS_FUNC(dlagtf)"(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) nogil
+cdef void dlagtf(int *n, d *a, d *lambda_, d *b, d *c, d *tol, d *d, int *in_, int *info) noexcept nogil:
+    
+    _fortran_dlagtf(n, a, lambda_, b, c, tol, d, in_, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagtm "BLAS_FUNC(dlagtm)"(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) nogil
+cdef void dlagtm(char *trans, int *n, int *nrhs, d *alpha, d *dl, d *d, d *du, d *x, int *ldx, d *beta, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dlagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagts "BLAS_FUNC(dlagts)"(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) nogil
+cdef void dlagts(int *job, int *n, d *a, d *b, d *c, d *d, int *in_, d *y, d *tol, int *info) noexcept nogil:
+    
+    _fortran_dlagts(job, n, a, b, c, d, in_, y, tol, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlagv2 "BLAS_FUNC(dlagv2)"(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) nogil
+cdef void dlagv2(d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *csl, d *snl, d *csr, d *snr) noexcept nogil:
+    
+    _fortran_dlagv2(a, lda, b, ldb, alphar, alphai, beta, csl, snl, csr, snr)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlahqr "BLAS_FUNC(dlahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) nogil
+cdef void dlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_dlahqr(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlahr2 "BLAS_FUNC(dlahr2)"(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) nogil
+cdef void dlahr2(int *n, int *k, int *nb, d *a, int *lda, d *tau, d *t, int *ldt, d *y, int *ldy) noexcept nogil:
+    
+    _fortran_dlahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaic1 "BLAS_FUNC(dlaic1)"(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) nogil
+cdef void dlaic1(int *job, int *j, d *x, d *sest, d *w, d *gamma, d *sestpr, d *s, d *c) noexcept nogil:
+    
+    _fortran_dlaic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaln2 "BLAS_FUNC(dlaln2)"(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) nogil
+cdef void dlaln2(bint *ltrans, int *na, int *nw, d *smin, d *ca, d *a, int *lda, d *d1, d *d2, d *b, int *ldb, d *wr, d *wi, d *x, int *ldx, d *scale, d *xnorm, int *info) noexcept nogil:
+    
+    _fortran_dlaln2(ltrans, na, nw, smin, ca, a, lda, d1, d2, b, ldb, wr, wi, x, ldx, scale, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlals0 "BLAS_FUNC(dlals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) nogil
+cdef void dlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlalsa "BLAS_FUNC(dlalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) nogil
+cdef void dlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, d *b, int *ldb, d *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlalsd "BLAS_FUNC(dlalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) nogil
+cdef void dlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, d *b, int *ldb, d *rcond, int *rank, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlamch "BLAS_FUNC(dlamch)"(char *cmach) nogil
+cdef d dlamch(char *cmach) noexcept nogil:
+    
+    return _fortran_dlamch(cmach)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlamrg "BLAS_FUNC(dlamrg)"(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) nogil
+cdef void dlamrg(int *n1, int *n2, d *a, int *dtrd1, int *dtrd2, int *index_bn) noexcept nogil:
+    
+    _fortran_dlamrg(n1, n2, a, dtrd1, dtrd2, index_bn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_dlaneg "BLAS_FUNC(dlaneg)"(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) nogil
+cdef int dlaneg(int *n, d *d, d *lld, d *sigma, d *pivmin, int *r) noexcept nogil:
+    
+    return _fortran_dlaneg(n, d, lld, sigma, pivmin, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlangb "BLAS_FUNC(dlangb)"(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) nogil
+cdef d dlangb(char *norm, int *n, int *kl, int *ku, d *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_dlangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlange "BLAS_FUNC(dlange)"(char *norm, int *m, int *n, d *a, int *lda, d *work) nogil
+cdef d dlange(char *norm, int *m, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlangt "BLAS_FUNC(dlangt)"(char *norm, int *n, d *dl, d *d_, d *du) nogil
+cdef d dlangt(char *norm, int *n, d *dl, d *d_, d *du) noexcept nogil:
+    
+    return _fortran_dlangt(norm, n, dl, d_, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlanhs "BLAS_FUNC(dlanhs)"(char *norm, int *n, d *a, int *lda, d *work) nogil
+cdef d dlanhs(char *norm, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansb "BLAS_FUNC(dlansb)"(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) nogil
+cdef d dlansb(char *norm, char *uplo, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_dlansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansf "BLAS_FUNC(dlansf)"(char *norm, char *transr, char *uplo, int *n, d *a, d *work) nogil
+cdef d dlansf(char *norm, char *transr, char *uplo, int *n, d *a, d *work) noexcept nogil:
+    
+    return _fortran_dlansf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansp "BLAS_FUNC(dlansp)"(char *norm, char *uplo, int *n, d *ap, d *work) nogil
+cdef d dlansp(char *norm, char *uplo, int *n, d *ap, d *work) noexcept nogil:
+    
+    return _fortran_dlansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlanst "BLAS_FUNC(dlanst)"(char *norm, int *n, d *d_, d *e) nogil
+cdef d dlanst(char *norm, int *n, d *d_, d *e) noexcept nogil:
+    
+    return _fortran_dlanst(norm, n, d_, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlansy "BLAS_FUNC(dlansy)"(char *norm, char *uplo, int *n, d *a, int *lda, d *work) nogil
+cdef d dlansy(char *norm, char *uplo, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlantb "BLAS_FUNC(dlantb)"(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) nogil
+cdef d dlantb(char *norm, char *uplo, char *diag, int *n, int *k, d *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_dlantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlantp "BLAS_FUNC(dlantp)"(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) nogil
+cdef d dlantp(char *norm, char *uplo, char *diag, int *n, d *ap, d *work) noexcept nogil:
+    
+    return _fortran_dlantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlantr "BLAS_FUNC(dlantr)"(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) nogil
+cdef d dlantr(char *norm, char *uplo, char *diag, int *m, int *n, d *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_dlantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlanv2 "BLAS_FUNC(dlanv2)"(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) nogil
+cdef void dlanv2(d *a, d *b, d *c, d *d, d *rt1r, d *rt1i, d *rt2r, d *rt2i, d *cs, d *sn) noexcept nogil:
+    
+    _fortran_dlanv2(a, b, c, d, rt1r, rt1i, rt2r, rt2i, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlapll "BLAS_FUNC(dlapll)"(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) nogil
+cdef void dlapll(int *n, d *x, int *incx, d *y, int *incy, d *ssmin) noexcept nogil:
+    
+    _fortran_dlapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlapmr "BLAS_FUNC(dlapmr)"(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) nogil
+cdef void dlapmr(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_dlapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlapmt "BLAS_FUNC(dlapmt)"(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) nogil
+cdef void dlapmt(bint *forwrd, int *m, int *n, d *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_dlapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlapy2 "BLAS_FUNC(dlapy2)"(d *x, d *y) nogil
+cdef d dlapy2(d *x, d *y) noexcept nogil:
+    
+    return _fortran_dlapy2(x, y)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dlapy3 "BLAS_FUNC(dlapy3)"(d *x, d *y, d *z) nogil
+cdef d dlapy3(d *x, d *y, d *z) noexcept nogil:
+    
+    return _fortran_dlapy3(x, y, z)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqgb "BLAS_FUNC(dlaqgb)"(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil
+cdef void dlaqgb(int *m, int *n, int *kl, int *ku, d *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqge "BLAS_FUNC(dlaqge)"(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil
+cdef void dlaqge(int *m, int *n, d *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqp2 "BLAS_FUNC(dlaqp2)"(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) nogil
+cdef void dlaqp2(int *m, int *n, int *offset, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *work) noexcept nogil:
+    
+    _fortran_dlaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqps "BLAS_FUNC(dlaqps)"(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) nogil
+cdef void dlaqps(int *m, int *n, int *offset, int *nb, int *kb, d *a, int *lda, int *jpvt, d *tau, d *vn1, d *vn2, d *auxv, d *f, int *ldf) noexcept nogil:
+    
+    _fortran_dlaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr0 "BLAS_FUNC(dlaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) nogil
+cdef void dlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dlaqr0(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr1 "BLAS_FUNC(dlaqr1)"(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) nogil
+cdef void dlaqr1(int *n, d *h, int *ldh, d *sr1, d *si1, d *sr2, d *si2, d *v) noexcept nogil:
+    
+    _fortran_dlaqr1(n, h, ldh, sr1, si1, sr2, si2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr2 "BLAS_FUNC(dlaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) nogil
+cdef void dlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil:
+    
+    _fortran_dlaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr3 "BLAS_FUNC(dlaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) nogil
+cdef void dlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, int *ns, int *nd, d *sr, d *si, d *v, int *ldv, int *nh, d *t, int *ldt, int *nv, d *wv, int *ldwv, d *work, int *lwork) noexcept nogil:
+    
+    _fortran_dlaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr4 "BLAS_FUNC(dlaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) nogil
+cdef void dlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, d *h, int *ldh, d *wr, d *wi, int *iloz, int *ihiz, d *z, int *ldz, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dlaqr4(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqr5 "BLAS_FUNC(dlaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) nogil
+cdef void dlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, d *sr, d *si, d *h, int *ldh, int *iloz, int *ihiz, d *z, int *ldz, d *v, int *ldv, d *u, int *ldu, int *nv, d *wv, int *ldwv, int *nh, d *wh, int *ldwh) noexcept nogil:
+    
+    _fortran_dlaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, sr, si, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqsb "BLAS_FUNC(dlaqsb)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil
+cdef void dlaqsb(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqsp "BLAS_FUNC(dlaqsp)"(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) nogil
+cdef void dlaqsp(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqsy "BLAS_FUNC(dlaqsy)"(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil
+cdef void dlaqsy(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_dlaqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaqtr "BLAS_FUNC(dlaqtr)"(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) nogil
+cdef void dlaqtr(bint *ltran, bint *lreal, int *n, d *t, int *ldt, d *b, d *w, d *scale, d *x, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlaqtr(ltran, lreal, n, t, ldt, b, w, scale, x, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlar1v "BLAS_FUNC(dlar1v)"(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) nogil
+cdef void dlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, d *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil:
+    
+    _fortran_dlar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlar2v "BLAS_FUNC(dlar2v)"(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) nogil
+cdef void dlar2v(int *n, d *x, d *y, d *z, int *incx, d *c, d *s, int *incc) noexcept nogil:
+    
+    _fortran_dlar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarf "BLAS_FUNC(dlarf)"(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) nogil
+cdef void dlarf(char *side, int *m, int *n, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil:
+    
+    _fortran_dlarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfb "BLAS_FUNC(dlarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) nogil
+cdef void dlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil:
+    
+    _fortran_dlarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfg "BLAS_FUNC(dlarfg)"(int *n, d *alpha, d *x, int *incx, d *tau) nogil
+cdef void dlarfg(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil:
+    
+    _fortran_dlarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfgp "BLAS_FUNC(dlarfgp)"(int *n, d *alpha, d *x, int *incx, d *tau) nogil
+cdef void dlarfgp(int *n, d *alpha, d *x, int *incx, d *tau) noexcept nogil:
+    
+    _fortran_dlarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarft "BLAS_FUNC(dlarft)"(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) nogil
+cdef void dlarft(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil:
+    
+    _fortran_dlarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarfx "BLAS_FUNC(dlarfx)"(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) nogil
+cdef void dlarfx(char *side, int *m, int *n, d *v, d *tau, d *c, int *ldc, d *work) noexcept nogil:
+    
+    _fortran_dlarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlargv "BLAS_FUNC(dlargv)"(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) nogil
+cdef void dlargv(int *n, d *x, int *incx, d *y, int *incy, d *c, int *incc) noexcept nogil:
+    
+    _fortran_dlargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarnv "BLAS_FUNC(dlarnv)"(int *idist, int *iseed, int *n, d *x) nogil
+cdef void dlarnv(int *idist, int *iseed, int *n, d *x) noexcept nogil:
+    
+    _fortran_dlarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarra "BLAS_FUNC(dlarra)"(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) nogil
+cdef void dlarra(int *n, d *d, d *e, d *e2, d *spltol, d *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil:
+    
+    _fortran_dlarra(n, d, e, e2, spltol, tnrm, nsplit, isplit, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrb "BLAS_FUNC(dlarrb)"(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) nogil
+cdef void dlarrb(int *n, d *d, d *lld, int *ifirst, int *ilast, d *rtol1, d *rtol2, int *offset, d *w, d *wgap, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *twist, int *info) noexcept nogil:
+    
+    _fortran_dlarrb(n, d, lld, ifirst, ilast, rtol1, rtol2, offset, w, wgap, werr, work, iwork, pivmin, spdiam, twist, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrc "BLAS_FUNC(dlarrc)"(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) nogil
+cdef void dlarrc(char *jobt, int *n, d *vl, d *vu, d *d, d *e, d *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil:
+    
+    _fortran_dlarrc(jobt, n, vl, vu, d, e, pivmin, eigcnt, lcnt, rcnt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrd "BLAS_FUNC(dlarrd)"(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) nogil
+cdef void dlarrd(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *gers, d *reltol, d *d, d *e, d *e2, d *pivmin, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wl, d *wu, int *iblock, int *indexw, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlarrd(range, order, n, vl, vu, il, iu, gers, reltol, d, e, e2, pivmin, nsplit, isplit, m, w, werr, wl, wu, iblock, indexw, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarre "BLAS_FUNC(dlarre)"(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) nogil
+cdef void dlarre(char *range, int *n, d *vl, d *vu, int *il, int *iu, d *d, d *e, d *e2, d *rtol1, d *rtol2, d *spltol, int *nsplit, int *isplit, int *m, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *pivmin, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlarre(range, n, vl, vu, il, iu, d, e, e2, rtol1, rtol2, spltol, nsplit, isplit, m, w, werr, wgap, iblock, indexw, gers, pivmin, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrf "BLAS_FUNC(dlarrf)"(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) nogil
+cdef void dlarrf(int *n, d *d, d *l, d *ld, int *clstrt, int *clend, d *w, d *wgap, d *werr, d *spdiam, d *clgapl, d *clgapr, d *pivmin, d *sigma, d *dplus, d *lplus, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlarrf(n, d, l, ld, clstrt, clend, w, wgap, werr, spdiam, clgapl, clgapr, pivmin, sigma, dplus, lplus, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrj "BLAS_FUNC(dlarrj)"(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) nogil
+cdef void dlarrj(int *n, d *d, d *e2, int *ifirst, int *ilast, d *rtol, int *offset, d *w, d *werr, d *work, int *iwork, d *pivmin, d *spdiam, int *info) noexcept nogil:
+    
+    _fortran_dlarrj(n, d, e2, ifirst, ilast, rtol, offset, w, werr, work, iwork, pivmin, spdiam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrk "BLAS_FUNC(dlarrk)"(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) nogil
+cdef void dlarrk(int *n, int *iw, d *gl, d *gu, d *d, d *e2, d *pivmin, d *reltol, d *w, d *werr, int *info) noexcept nogil:
+    
+    _fortran_dlarrk(n, iw, gl, gu, d, e2, pivmin, reltol, w, werr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrr "BLAS_FUNC(dlarrr)"(int *n, d *d, d *e, int *info) nogil
+cdef void dlarrr(int *n, d *d, d *e, int *info) noexcept nogil:
+    
+    _fortran_dlarrr(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarrv "BLAS_FUNC(dlarrv)"(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) nogil
+cdef void dlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, d *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartg "BLAS_FUNC(dlartg)"(d *f, d *g, d *cs, d *sn, d *r) nogil
+cdef void dlartg(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil:
+    
+    _fortran_dlartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartgp "BLAS_FUNC(dlartgp)"(d *f, d *g, d *cs, d *sn, d *r) nogil
+cdef void dlartgp(d *f, d *g, d *cs, d *sn, d *r) noexcept nogil:
+    
+    _fortran_dlartgp(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartgs "BLAS_FUNC(dlartgs)"(d *x, d *y, d *sigma, d *cs, d *sn) nogil
+cdef void dlartgs(d *x, d *y, d *sigma, d *cs, d *sn) noexcept nogil:
+    
+    _fortran_dlartgs(x, y, sigma, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlartv "BLAS_FUNC(dlartv)"(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) nogil
+cdef void dlartv(int *n, d *x, int *incx, d *y, int *incy, d *c, d *s, int *incc) noexcept nogil:
+    
+    _fortran_dlartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaruv "BLAS_FUNC(dlaruv)"(int *iseed, int *n, d *x) nogil
+cdef void dlaruv(int *iseed, int *n, d *x) noexcept nogil:
+    
+    _fortran_dlaruv(iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarz "BLAS_FUNC(dlarz)"(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) nogil
+cdef void dlarz(char *side, int *m, int *n, int *l, d *v, int *incv, d *tau, d *c, int *ldc, d *work) noexcept nogil:
+    
+    _fortran_dlarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarzb "BLAS_FUNC(dlarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) nogil
+cdef void dlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *c, int *ldc, d *work, int *ldwork) noexcept nogil:
+    
+    _fortran_dlarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlarzt "BLAS_FUNC(dlarzt)"(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) nogil
+cdef void dlarzt(char *direct, char *storev, int *n, int *k, d *v, int *ldv, d *tau, d *t, int *ldt) noexcept nogil:
+    
+    _fortran_dlarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlas2 "BLAS_FUNC(dlas2)"(d *f, d *g, d *h, d *ssmin, d *ssmax) nogil
+cdef void dlas2(d *f, d *g, d *h, d *ssmin, d *ssmax) noexcept nogil:
+    
+    _fortran_dlas2(f, g, h, ssmin, ssmax)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlascl "BLAS_FUNC(dlascl)"(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) nogil
+cdef void dlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dlascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd0 "BLAS_FUNC(dlasd0)"(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) nogil
+cdef void dlasd0(int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *ldvt, int *smlsiz, int *iwork, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasd0(n, sqre, d, e, u, ldu, vt, ldvt, smlsiz, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd1 "BLAS_FUNC(dlasd1)"(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) nogil
+cdef void dlasd1(int *nl, int *nr, int *sqre, d *d, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, int *idxq, int *iwork, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasd1(nl, nr, sqre, d, alpha, beta, u, ldu, vt, ldvt, idxq, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd2 "BLAS_FUNC(dlasd2)"(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) nogil
+cdef void dlasd2(int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *alpha, d *beta, d *u, int *ldu, d *vt, int *ldvt, d *dsigma, d *u2, int *ldu2, d *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil:
+    
+    _fortran_dlasd2(nl, nr, sqre, k, d, z, alpha, beta, u, ldu, vt, ldvt, dsigma, u2, ldu2, vt2, ldvt2, idxp, idx, idxc, idxq, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd3 "BLAS_FUNC(dlasd3)"(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) nogil
+cdef void dlasd3(int *nl, int *nr, int *sqre, int *k, d *d, d *q, int *ldq, d *dsigma, d *u, int *ldu, d *u2, int *ldu2, d *vt, int *ldvt, d *vt2, int *ldvt2, int *idxc, int *ctot, d *z, int *info) noexcept nogil:
+    
+    _fortran_dlasd3(nl, nr, sqre, k, d, q, ldq, dsigma, u, ldu, u2, ldu2, vt, ldvt, vt2, ldvt2, idxc, ctot, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd4 "BLAS_FUNC(dlasd4)"(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) nogil
+cdef void dlasd4(int *n, int *i, d *d, d *z, d *delta, d *rho, d *sigma, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasd4(n, i, d, z, delta, rho, sigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd5 "BLAS_FUNC(dlasd5)"(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) nogil
+cdef void dlasd5(int *i, d *d, d *z, d *delta, d *rho, d *dsigma, d *work) noexcept nogil:
+    
+    _fortran_dlasd5(i, d, z, delta, rho, dsigma, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd6 "BLAS_FUNC(dlasd6)"(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) nogil
+cdef void dlasd6(int *icompq, int *nl, int *nr, int *sqre, d *d, d *vf, d *vl, d *alpha, d *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlasd6(icompq, nl, nr, sqre, d, vf, vl, alpha, beta, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd7 "BLAS_FUNC(dlasd7)"(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) nogil
+cdef void dlasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, d *d, d *z, d *zw, d *vf, d *vfw, d *vl, d *vlw, d *alpha, d *beta, d *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *c, d *s, int *info) noexcept nogil:
+    
+    _fortran_dlasd7(icompq, nl, nr, sqre, k, d, z, zw, vf, vfw, vl, vlw, alpha, beta, dsigma, idx, idxp, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, c, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasd8 "BLAS_FUNC(dlasd8)"(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) nogil
+cdef void dlasd8(int *icompq, int *k, d *d, d *z, d *vf, d *vl, d *difl, d *difr, int *lddifr, d *dsigma, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasd8(icompq, k, d, z, vf, vl, difl, difr, lddifr, dsigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasda "BLAS_FUNC(dlasda)"(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) nogil
+cdef void dlasda(int *icompq, int *smlsiz, int *n, int *sqre, d *d, d *e, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dlasda(icompq, smlsiz, n, sqre, d, e, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasdq "BLAS_FUNC(dlasdq)"(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) nogil
+cdef void dlasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, d *vt, int *ldvt, d *u, int *ldu, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasdq(uplo, sqre, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasdt "BLAS_FUNC(dlasdt)"(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) nogil
+cdef void dlasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil:
+    
+    _fortran_dlasdt(n, lvl, nd, inode, ndiml, ndimr, msub)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaset "BLAS_FUNC(dlaset)"(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) nogil
+cdef void dlaset(char *uplo, int *m, int *n, d *alpha, d *beta, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dlaset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq1 "BLAS_FUNC(dlasq1)"(int *n, d *d, d *e, d *work, int *info) nogil
+cdef void dlasq1(int *n, d *d, d *e, d *work, int *info) noexcept nogil:
+    
+    _fortran_dlasq1(n, d, e, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq2 "BLAS_FUNC(dlasq2)"(int *n, d *z, int *info) nogil
+cdef void dlasq2(int *n, d *z, int *info) noexcept nogil:
+    
+    _fortran_dlasq2(n, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq3 "BLAS_FUNC(dlasq3)"(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) nogil
+cdef void dlasq3(int *i0, int *n0, d *z, int *pp, d *dmin, d *sigma, d *desig, d *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *g, d *tau) noexcept nogil:
+    
+    _fortran_dlasq3(i0, n0, z, pp, dmin, sigma, desig, qmax, nfail, iter, ndiv, ieee, ttype, dmin1, dmin2, dn, dn1, dn2, g, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq4 "BLAS_FUNC(dlasq4)"(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) nogil
+cdef void dlasq4(int *i0, int *n0, d *z, int *pp, int *n0in, d *dmin, d *dmin1, d *dmin2, d *dn, d *dn1, d *dn2, d *tau, int *ttype, d *g) noexcept nogil:
+    
+    _fortran_dlasq4(i0, n0, z, pp, n0in, dmin, dmin1, dmin2, dn, dn1, dn2, tau, ttype, g)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasq6 "BLAS_FUNC(dlasq6)"(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) nogil
+cdef void dlasq6(int *i0, int *n0, d *z, int *pp, d *dmin, d *dmin1, d *dmin2, d *dn, d *dnm1, d *dnm2) noexcept nogil:
+    
+    _fortran_dlasq6(i0, n0, z, pp, dmin, dmin1, dmin2, dn, dnm1, dnm2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasr "BLAS_FUNC(dlasr)"(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) nogil
+cdef void dlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, d *a, int *lda) noexcept nogil:
+    
+    _fortran_dlasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasrt "BLAS_FUNC(dlasrt)"(char *id, int *n, d *d, int *info) nogil
+cdef void dlasrt(char *id, int *n, d *d, int *info) noexcept nogil:
+    
+    _fortran_dlasrt(id, n, d, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlassq "BLAS_FUNC(dlassq)"(int *n, d *x, int *incx, d *scale, d *sumsq) nogil
+cdef void dlassq(int *n, d *x, int *incx, d *scale, d *sumsq) noexcept nogil:
+    
+    _fortran_dlassq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasv2 "BLAS_FUNC(dlasv2)"(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) nogil
+cdef void dlasv2(d *f, d *g, d *h, d *ssmin, d *ssmax, d *snr, d *csr, d *snl, d *csl) noexcept nogil:
+    
+    _fortran_dlasv2(f, g, h, ssmin, ssmax, snr, csr, snl, csl)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlaswp "BLAS_FUNC(dlaswp)"(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void dlaswp(int *n, d *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_dlaswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasy2 "BLAS_FUNC(dlasy2)"(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) nogil
+cdef void dlasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, d *tl, int *ldtl, d *tr, int *ldtr, d *b, int *ldb, d *scale, d *x, int *ldx, d *xnorm, int *info) noexcept nogil:
+    
+    _fortran_dlasy2(ltranl, ltranr, isgn, n1, n2, tl, ldtl, tr, ldtr, b, ldb, scale, x, ldx, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlasyf "BLAS_FUNC(dlasyf)"(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) nogil
+cdef void dlasyf(char *uplo, int *n, int *nb, int *kb, d *a, int *lda, int *ipiv, d *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_dlasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlat2s "BLAS_FUNC(dlat2s)"(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) nogil
+cdef void dlat2s(char *uplo, int *n, d *a, int *lda, s *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_dlat2s(uplo, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatbs "BLAS_FUNC(dlatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) nogil
+cdef void dlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, d *ab, int *ldab, d *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_dlatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatdf "BLAS_FUNC(dlatdf)"(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) nogil
+cdef void dlatdf(int *ijob, int *n, d *z, int *ldz, d *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_dlatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatps "BLAS_FUNC(dlatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) nogil
+cdef void dlatps(char *uplo, char *trans, char *diag, char *normin, int *n, d *ap, d *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_dlatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatrd "BLAS_FUNC(dlatrd)"(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) nogil
+cdef void dlatrd(char *uplo, int *n, int *nb, d *a, int *lda, d *e, d *tau, d *w, int *ldw) noexcept nogil:
+    
+    _fortran_dlatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatrs "BLAS_FUNC(dlatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) nogil
+cdef void dlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, d *a, int *lda, d *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_dlatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlatrz "BLAS_FUNC(dlatrz)"(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) nogil
+cdef void dlatrz(int *m, int *n, int *l, d *a, int *lda, d *tau, d *work) noexcept nogil:
+    
+    _fortran_dlatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlauu2 "BLAS_FUNC(dlauu2)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dlauu2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dlauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dlauum "BLAS_FUNC(dlauum)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dlauum(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dlauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dopgtr "BLAS_FUNC(dopgtr)"(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) nogil
+cdef void dopgtr(char *uplo, int *n, d *ap, d *tau, d *q, int *ldq, d *work, int *info) noexcept nogil:
+    
+    _fortran_dopgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dopmtr "BLAS_FUNC(dopmtr)"(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dopmtr(char *side, char *uplo, char *trans, int *m, int *n, d *ap, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dopmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorbdb "BLAS_FUNC(dorbdb)"(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) nogil
+cdef void dorbdb(char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *phi, d *taup1, d *taup2, d *tauq1, d *tauq2, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorcsd "BLAS_FUNC(dorcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, d *x11, int *ldx11, d *x12, int *ldx12, d *x21, int *ldx21, d *x22, int *ldx22, d *theta, d *u1, int *ldu1, d *u2, int *ldu2, d *v1t, int *ldv1t, d *v2t, int *ldv2t, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dorcsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorg2l "BLAS_FUNC(dorg2l)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorg2l(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorg2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorg2r "BLAS_FUNC(dorg2r)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorg2r(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorg2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgbr "BLAS_FUNC(dorgbr)"(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgbr(char *vect, int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorghr "BLAS_FUNC(dorghr)"(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorghr(int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgl2 "BLAS_FUNC(dorgl2)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorgl2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorgl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorglq "BLAS_FUNC(dorglq)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorglq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgql "BLAS_FUNC(dorgql)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgql(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgqr "BLAS_FUNC(dorgqr)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgqr(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgr2 "BLAS_FUNC(dorgr2)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) nogil
+cdef void dorgr2(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorgr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgrq "BLAS_FUNC(dorgrq)"(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgrq(int *m, int *n, int *k, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorgtr "BLAS_FUNC(dorgtr)"(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dorgtr(char *uplo, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dorgtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorm2l "BLAS_FUNC(dorm2l)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dorm2l(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorm2r "BLAS_FUNC(dorm2r)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dorm2r(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormbr "BLAS_FUNC(dormbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormhr "BLAS_FUNC(dormhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dorml2 "BLAS_FUNC(dorml2)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dorml2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dorml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormlq "BLAS_FUNC(dormlq)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormlq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormql "BLAS_FUNC(dormql)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormql(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormqr "BLAS_FUNC(dormqr)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormqr(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormr2 "BLAS_FUNC(dormr2)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dormr2(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dormr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormr3 "BLAS_FUNC(dormr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) nogil
+cdef void dormr3(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *info) noexcept nogil:
+    
+    _fortran_dormr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormrq "BLAS_FUNC(dormrq)"(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormrq(char *side, char *trans, int *m, int *n, int *k, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormrz "BLAS_FUNC(dormrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormrz(char *side, char *trans, int *m, int *n, int *k, int *l, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dormtr "BLAS_FUNC(dormtr)"(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) nogil
+cdef void dormtr(char *side, char *uplo, char *trans, int *m, int *n, d *a, int *lda, d *tau, d *c, int *ldc, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dormtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbcon "BLAS_FUNC(dpbcon)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dpbcon(char *uplo, int *n, int *kd, d *ab, int *ldab, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbequ "BLAS_FUNC(dpbequ)"(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) nogil
+cdef void dpbequ(char *uplo, int *n, int *kd, d *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbrfs "BLAS_FUNC(dpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dpbrfs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbstf "BLAS_FUNC(dpbstf)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil
+cdef void dpbstf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_dpbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbsv "BLAS_FUNC(dpbsv)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil
+cdef void dpbsv(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbsvx "BLAS_FUNC(dpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *afb, int *ldafb, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbtf2 "BLAS_FUNC(dpbtf2)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil
+cdef void dpbtf2(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_dpbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbtrf "BLAS_FUNC(dpbtrf)"(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) nogil
+cdef void dpbtrf(char *uplo, int *n, int *kd, d *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_dpbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpbtrs "BLAS_FUNC(dpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil
+cdef void dpbtrs(char *uplo, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpftrf "BLAS_FUNC(dpftrf)"(char *transr, char *uplo, int *n, d *a, int *info) nogil
+cdef void dpftrf(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil:
+    
+    _fortran_dpftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpftri "BLAS_FUNC(dpftri)"(char *transr, char *uplo, int *n, d *a, int *info) nogil
+cdef void dpftri(char *transr, char *uplo, int *n, d *a, int *info) noexcept nogil:
+    
+    _fortran_dpftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpftrs "BLAS_FUNC(dpftrs)"(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) nogil
+cdef void dpftrs(char *transr, char *uplo, int *n, int *nrhs, d *a, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpocon "BLAS_FUNC(dpocon)"(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dpocon(char *uplo, int *n, d *a, int *lda, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpocon(uplo, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpoequ "BLAS_FUNC(dpoequ)"(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void dpoequ(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dpoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpoequb "BLAS_FUNC(dpoequb)"(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void dpoequb(int *n, d *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dpoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dporfs "BLAS_FUNC(dporfs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dporfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dposv "BLAS_FUNC(dposv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dposvx "BLAS_FUNC(dposvx)"(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dposvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotf2 "BLAS_FUNC(dpotf2)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dpotf2(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dpotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotrf "BLAS_FUNC(dpotrf)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dpotrf(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dpotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotri "BLAS_FUNC(dpotri)"(char *uplo, int *n, d *a, int *lda, int *info) nogil
+cdef void dpotri(char *uplo, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dpotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpotrs "BLAS_FUNC(dpotrs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dpotrs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppcon "BLAS_FUNC(dppcon)"(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dppcon(char *uplo, int *n, d *ap, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dppcon(uplo, n, ap, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppequ "BLAS_FUNC(dppequ)"(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) nogil
+cdef void dppequ(char *uplo, int *n, d *ap, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_dppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpprfs "BLAS_FUNC(dpprfs)"(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dpprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppsv "BLAS_FUNC(dppsv)"(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil
+cdef void dppsv(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dppsvx "BLAS_FUNC(dppsvx)"(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dppsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, char *equed, d *s, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpptrf "BLAS_FUNC(dpptrf)"(char *uplo, int *n, d *ap, int *info) nogil
+cdef void dpptrf(char *uplo, int *n, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dpptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpptri "BLAS_FUNC(dpptri)"(char *uplo, int *n, d *ap, int *info) nogil
+cdef void dpptri(char *uplo, int *n, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dpptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpptrs "BLAS_FUNC(dpptrs)"(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil
+cdef void dpptrs(char *uplo, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpstf2 "BLAS_FUNC(dpstf2)"(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void dpstf2(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_dpstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpstrf "BLAS_FUNC(dpstrf)"(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void dpstrf(char *uplo, int *n, d *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_dpstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptcon "BLAS_FUNC(dptcon)"(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) nogil
+cdef void dptcon(int *n, d *d, d *e, d *anorm, d *rcond, d *work, int *info) noexcept nogil:
+    
+    _fortran_dptcon(n, d, e, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpteqr "BLAS_FUNC(dpteqr)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil
+cdef void dpteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dpteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptrfs "BLAS_FUNC(dptrfs)"(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) nogil
+cdef void dptrfs(int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *info) noexcept nogil:
+    
+    _fortran_dptrfs(n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptsv "BLAS_FUNC(dptsv)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) nogil
+cdef void dptsv(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptsvx "BLAS_FUNC(dptsvx)"(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) nogil
+cdef void dptsvx(char *fact, int *n, int *nrhs, d *d, d *e, d *df, d *ef, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *info) noexcept nogil:
+    
+    _fortran_dptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpttrf "BLAS_FUNC(dpttrf)"(int *n, d *d, d *e, int *info) nogil
+cdef void dpttrf(int *n, d *d, d *e, int *info) noexcept nogil:
+    
+    _fortran_dpttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dpttrs "BLAS_FUNC(dpttrs)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) nogil
+cdef void dpttrs(int *n, int *nrhs, d *d, d *e, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dpttrs(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dptts2 "BLAS_FUNC(dptts2)"(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) nogil
+cdef void dptts2(int *n, int *nrhs, d *d, d *e, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dptts2(n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_drscl "BLAS_FUNC(drscl)"(int *n, d *sa, d *sx, int *incx) nogil
+cdef void drscl(int *n, d *sa, d *sx, int *incx) noexcept nogil:
+    
+    _fortran_drscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbev "BLAS_FUNC(dsbev)"(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) nogil
+cdef void dsbev(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbevd "BLAS_FUNC(dsbevd)"(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsbevd(char *jobz, char *uplo, int *n, int *kd, d *ab, int *ldab, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbevx "BLAS_FUNC(dsbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dsbevx(char *jobz, char *range, char *uplo, int *n, int *kd, d *ab, int *ldab, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dsbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgst "BLAS_FUNC(dsbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) nogil
+cdef void dsbgst(char *vect, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *x, int *ldx, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgv "BLAS_FUNC(dsbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) nogil
+cdef void dsbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgvd "BLAS_FUNC(dsbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbgvx "BLAS_FUNC(dsbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dsbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, d *ab, int *ldab, d *bb, int *ldbb, d *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dsbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsbtrd "BLAS_FUNC(dsbtrd)"(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) nogil
+cdef void dsbtrd(char *vect, char *uplo, int *n, int *kd, d *ab, int *ldab, d *d, d *e, d *q, int *ldq, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsfrk "BLAS_FUNC(dsfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) nogil
+cdef void dsfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, d *a, int *lda, d *beta, d *c) noexcept nogil:
+    
+    _fortran_dsfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsgesv "BLAS_FUNC(dsgesv)"(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) nogil
+cdef void dsgesv(int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil:
+    
+    _fortran_dsgesv(n, nrhs, a, lda, ipiv, b, ldb, x, ldx, work, swork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspcon "BLAS_FUNC(dspcon)"(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dspcon(char *uplo, int *n, d *ap, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dspcon(uplo, n, ap, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspev "BLAS_FUNC(dspev)"(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) nogil
+cdef void dspev(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dspev(jobz, uplo, n, ap, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspevd "BLAS_FUNC(dspevd)"(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dspevd(char *jobz, char *uplo, int *n, d *ap, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dspevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspevx "BLAS_FUNC(dspevx)"(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dspevx(char *jobz, char *range, char *uplo, int *n, d *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dspevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgst "BLAS_FUNC(dspgst)"(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) nogil
+cdef void dspgst(int *itype, char *uplo, int *n, d *ap, d *bp, int *info) noexcept nogil:
+    
+    _fortran_dspgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgv "BLAS_FUNC(dspgv)"(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) nogil
+cdef void dspgv(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dspgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgvd "BLAS_FUNC(dspgvd)"(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dspgvd(int *itype, char *jobz, char *uplo, int *n, d *ap, d *bp, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dspgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspgvx "BLAS_FUNC(dspgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *ap, d *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dspgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsposv "BLAS_FUNC(dsposv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) nogil
+cdef void dsposv(char *uplo, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *work, s *swork, int *iter, int *info) noexcept nogil:
+    
+    _fortran_dsposv(uplo, n, nrhs, a, lda, b, ldb, x, ldx, work, swork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsprfs "BLAS_FUNC(dsprfs)"(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dsprfs(char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspsv "BLAS_FUNC(dspsv)"(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dspsv(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dspsvx "BLAS_FUNC(dspsvx)"(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dspsvx(char *fact, char *uplo, int *n, int *nrhs, d *ap, d *afp, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptrd "BLAS_FUNC(dsptrd)"(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) nogil
+cdef void dsptrd(char *uplo, int *n, d *ap, d *d, d *e, d *tau, int *info) noexcept nogil:
+    
+    _fortran_dsptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptrf "BLAS_FUNC(dsptrf)"(char *uplo, int *n, d *ap, int *ipiv, int *info) nogil
+cdef void dsptrf(char *uplo, int *n, d *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dsptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptri "BLAS_FUNC(dsptri)"(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) nogil
+cdef void dsptri(char *uplo, int *n, d *ap, int *ipiv, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsptrs "BLAS_FUNC(dsptrs)"(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dsptrs(char *uplo, int *n, int *nrhs, d *ap, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstebz "BLAS_FUNC(dstebz)"(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) nogil
+cdef void dstebz(char *range, char *order, int *n, d *vl, d *vu, int *il, int *iu, d *abstol, d *d, d *e, int *m, int *nsplit, d *w, int *iblock, int *isplit, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dstebz(range, order, n, vl, vu, il, iu, abstol, d, e, m, nsplit, w, iblock, isplit, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstedc "BLAS_FUNC(dstedc)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstedc(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstedc(compz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstegr "BLAS_FUNC(dstegr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstein "BLAS_FUNC(dstein)"(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstemr "BLAS_FUNC(dstemr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, d *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsteqr "BLAS_FUNC(dsteqr)"(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil
+cdef void dsteqr(char *compz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsterf "BLAS_FUNC(dsterf)"(int *n, d *d, d *e, int *info) nogil
+cdef void dsterf(int *n, d *d, d *e, int *info) noexcept nogil:
+    
+    _fortran_dsterf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstev "BLAS_FUNC(dstev)"(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) nogil
+cdef void dstev(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_dstev(jobz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstevd "BLAS_FUNC(dstevd)"(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstevd(char *jobz, int *n, d *d, d *e, d *z, int *ldz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstevd(jobz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstevr "BLAS_FUNC(dstevr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dstevr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dstevr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dstevx "BLAS_FUNC(dstevx)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void dstevx(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dstevx(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsycon "BLAS_FUNC(dsycon)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dsycon(char *uplo, int *n, d *a, int *lda, int *ipiv, d *anorm, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyconv "BLAS_FUNC(dsyconv)"(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) nogil
+cdef void dsyconv(char *uplo, char *way, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyequb "BLAS_FUNC(dsyequb)"(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) nogil
+cdef void dsyequb(char *uplo, int *n, d *a, int *lda, d *s, d *scond, d *amax, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyev "BLAS_FUNC(dsyev)"(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) nogil
+cdef void dsyev(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsyev(jobz, uplo, n, a, lda, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyevd "BLAS_FUNC(dsyevd)"(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsyevd(char *jobz, char *uplo, int *n, d *a, int *lda, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyevr "BLAS_FUNC(dsyevr)"(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsyevr(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsyevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyevx "BLAS_FUNC(dsyevx)"(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) nogil
+cdef void dsyevx(char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dsyevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygs2 "BLAS_FUNC(dsygs2)"(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dsygs2(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsygs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygst "BLAS_FUNC(dsygst)"(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dsygst(int *itype, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsygst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygv "BLAS_FUNC(dsygv)"(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) nogil
+cdef void dsygv(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsygv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygvd "BLAS_FUNC(dsygvd)"(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dsygvd(int *itype, char *jobz, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *w, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dsygvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsygvx "BLAS_FUNC(dsygvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) nogil
+cdef void dsygvx(int *itype, char *jobz, char *range, char *uplo, int *n, d *a, int *lda, d *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, d *z, int *ldz, d *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_dsygvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyrfs "BLAS_FUNC(dsyrfs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dsyrfs(char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsysv "BLAS_FUNC(dsysv)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) nogil
+cdef void dsysv(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsysvx "BLAS_FUNC(dsysvx)"(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dsysvx(char *fact, char *uplo, int *n, int *nrhs, d *a, int *lda, d *af, int *ldaf, int *ipiv, d *b, int *ldb, d *x, int *ldx, d *rcond, d *ferr, d *berr, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dsysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsyswapr "BLAS_FUNC(dsyswapr)"(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) nogil
+cdef void dsyswapr(char *uplo, int *n, d *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_dsyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytd2 "BLAS_FUNC(dsytd2)"(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) nogil
+cdef void dsytd2(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, int *info) noexcept nogil:
+    
+    _fortran_dsytd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytf2 "BLAS_FUNC(dsytf2)"(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) nogil
+cdef void dsytf2(char *uplo, int *n, d *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_dsytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrd "BLAS_FUNC(dsytrd)"(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dsytrd(char *uplo, int *n, d *a, int *lda, d *d, d *e, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrf "BLAS_FUNC(dsytrf)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil
+cdef void dsytrf(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytri "BLAS_FUNC(dsytri)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) nogil
+cdef void dsytri(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytri2 "BLAS_FUNC(dsytri2)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) nogil
+cdef void dsytri2(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dsytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytri2x "BLAS_FUNC(dsytri2x)"(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) nogil
+cdef void dsytri2x(char *uplo, int *n, d *a, int *lda, int *ipiv, d *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_dsytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrs "BLAS_FUNC(dsytrs)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) nogil
+cdef void dsytrs(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dsytrs2 "BLAS_FUNC(dsytrs2)"(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) nogil
+cdef void dsytrs2(char *uplo, int *n, int *nrhs, d *a, int *lda, int *ipiv, d *b, int *ldb, d *work, int *info) noexcept nogil:
+    
+    _fortran_dsytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtbcon "BLAS_FUNC(dtbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dtbcon(char *norm, char *uplo, char *diag, int *n, int *kd, d *ab, int *ldab, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtbrfs "BLAS_FUNC(dtbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dtbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtbtrs "BLAS_FUNC(dtbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) nogil
+cdef void dtbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, d *ab, int *ldab, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dtbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtfsm "BLAS_FUNC(dtfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) nogil
+cdef void dtfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, d *alpha, d *a, d *b, int *ldb) noexcept nogil:
+    
+    _fortran_dtfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtftri "BLAS_FUNC(dtftri)"(char *transr, char *uplo, char *diag, int *n, d *a, int *info) nogil
+cdef void dtftri(char *transr, char *uplo, char *diag, int *n, d *a, int *info) noexcept nogil:
+    
+    _fortran_dtftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtfttp "BLAS_FUNC(dtfttp)"(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) nogil
+cdef void dtfttp(char *transr, char *uplo, int *n, d *arf, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dtfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtfttr "BLAS_FUNC(dtfttr)"(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) nogil
+cdef void dtfttr(char *transr, char *uplo, int *n, d *arf, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgevc "BLAS_FUNC(dtgevc)"(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) nogil
+cdef void dtgevc(char *side, char *howmny, bint *select, int *n, d *s, int *lds, d *p, int *ldp, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgex2 "BLAS_FUNC(dtgex2)"(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) nogil
+cdef void dtgex2(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *j1, int *n1, int *n2, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dtgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, n1, n2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgexc "BLAS_FUNC(dtgexc)"(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) nogil
+cdef void dtgexc(bint *wantq, bint *wantz, int *n, d *a, int *lda, d *b, int *ldb, d *q, int *ldq, d *z, int *ldz, int *ifst, int *ilst, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dtgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsen "BLAS_FUNC(dtgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dtgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *alphar, d *alphai, d *beta, d *q, int *ldq, d *z, int *ldz, int *m, d *pl, d *pr, d *dif, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dtgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alphar, alphai, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsja "BLAS_FUNC(dtgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) nogil
+cdef void dtgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, d *a, int *lda, d *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, d *u, int *ldu, d *v, int *ldv, d *q, int *ldq, d *work, int *ncycle, int *info) noexcept nogil:
+    
+    _fortran_dtgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsna "BLAS_FUNC(dtgsna)"(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dtgsna(char *job, char *howmny, bint *select, int *n, d *a, int *lda, d *b, int *ldb, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *dif, int *mm, int *m, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsy2 "BLAS_FUNC(dtgsy2)"(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) nogil
+cdef void dtgsy2(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *iwork, int *pq, int *info) noexcept nogil:
+    
+    _fortran_dtgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, iwork, pq, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtgsyl "BLAS_FUNC(dtgsyl)"(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) nogil
+cdef void dtgsyl(char *trans, int *ijob, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *d, int *ldd, d *e, int *lde, d *f, int *ldf, d *scale, d *dif, d *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpcon "BLAS_FUNC(dtpcon)"(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dtpcon(char *norm, char *uplo, char *diag, int *n, d *ap, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtpcon(norm, uplo, diag, n, ap, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpmqrt "BLAS_FUNC(dtpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) nogil
+cdef void dtpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpqrt "BLAS_FUNC(dtpqrt)"(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) nogil
+cdef void dtpqrt(int *m, int *n, int *l, int *nb, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpqrt2 "BLAS_FUNC(dtpqrt2)"(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) nogil
+cdef void dtpqrt2(int *m, int *n, int *l, d *a, int *lda, d *b, int *ldb, d *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_dtpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtprfb "BLAS_FUNC(dtprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) nogil
+cdef void dtprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, d *v, int *ldv, d *t, int *ldt, d *a, int *lda, d *b, int *ldb, d *work, int *ldwork) noexcept nogil:
+    
+    _fortran_dtprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtprfs "BLAS_FUNC(dtprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dtprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtptri "BLAS_FUNC(dtptri)"(char *uplo, char *diag, int *n, d *ap, int *info) nogil
+cdef void dtptri(char *uplo, char *diag, int *n, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dtptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtptrs "BLAS_FUNC(dtptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) nogil
+cdef void dtptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *ap, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dtptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpttf "BLAS_FUNC(dtpttf)"(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) nogil
+cdef void dtpttf(char *transr, char *uplo, int *n, d *ap, d *arf, int *info) noexcept nogil:
+    
+    _fortran_dtpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtpttr "BLAS_FUNC(dtpttr)"(char *uplo, int *n, d *ap, d *a, int *lda, int *info) nogil
+cdef void dtpttr(char *uplo, int *n, d *ap, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrcon "BLAS_FUNC(dtrcon)"(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) nogil
+cdef void dtrcon(char *norm, char *uplo, char *diag, int *n, d *a, int *lda, d *rcond, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtrcon(norm, uplo, diag, n, a, lda, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrevc "BLAS_FUNC(dtrevc)"(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) nogil
+cdef void dtrevc(char *side, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, int *mm, int *m, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrexc "BLAS_FUNC(dtrexc)"(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) nogil
+cdef void dtrexc(char *compq, int *n, d *t, int *ldt, d *q, int *ldq, int *ifst, int *ilst, d *work, int *info) noexcept nogil:
+    
+    _fortran_dtrexc(compq, n, t, ldt, q, ldq, ifst, ilst, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrrfs "BLAS_FUNC(dtrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) nogil
+cdef void dtrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, d *x, int *ldx, d *ferr, d *berr, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrsen "BLAS_FUNC(dtrsen)"(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void dtrsen(char *job, char *compq, bint *select, int *n, d *t, int *ldt, d *q, int *ldq, d *wr, d *wi, int *m, d *s, d *sep, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_dtrsen(job, compq, select, n, t, ldt, q, ldq, wr, wi, m, s, sep, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrsna "BLAS_FUNC(dtrsna)"(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) nogil
+cdef void dtrsna(char *job, char *howmny, bint *select, int *n, d *t, int *ldt, d *vl, int *ldvl, d *vr, int *ldvr, d *s, d *sep, int *mm, int *m, d *work, int *ldwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_dtrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrsyl "BLAS_FUNC(dtrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) nogil
+cdef void dtrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, d *a, int *lda, d *b, int *ldb, d *c, int *ldc, d *scale, int *info) noexcept nogil:
+    
+    _fortran_dtrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrti2 "BLAS_FUNC(dtrti2)"(char *uplo, char *diag, int *n, d *a, int *lda, int *info) nogil
+cdef void dtrti2(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtrti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrtri "BLAS_FUNC(dtrtri)"(char *uplo, char *diag, int *n, d *a, int *lda, int *info) nogil
+cdef void dtrtri(char *uplo, char *diag, int *n, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_dtrtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrtrs "BLAS_FUNC(dtrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) nogil
+cdef void dtrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, d *a, int *lda, d *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_dtrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrttf "BLAS_FUNC(dtrttf)"(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) nogil
+cdef void dtrttf(char *transr, char *uplo, int *n, d *a, int *lda, d *arf, int *info) noexcept nogil:
+    
+    _fortran_dtrttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtrttp "BLAS_FUNC(dtrttp)"(char *uplo, int *n, d *a, int *lda, d *ap, int *info) nogil
+cdef void dtrttp(char *uplo, int *n, d *a, int *lda, d *ap, int *info) noexcept nogil:
+    
+    _fortran_dtrttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_dtzrzf "BLAS_FUNC(dtzrzf)"(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) nogil
+cdef void dtzrzf(int *m, int *n, d *a, int *lda, d *tau, d *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_dtzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_dzsum1 "BLAS_FUNC(dzsum1)"(int *n, npy_complex128 *cx, int *incx) nogil
+cdef d dzsum1(int *n, z *cx, int *incx) noexcept nogil:
+    
+    return _fortran_dzsum1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_icmax1 "BLAS_FUNC(icmax1)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef int icmax1(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_icmax1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ieeeck "BLAS_FUNC(ieeeck)"(int *ispec, s *zero, s *one) nogil
+cdef int ieeeck(int *ispec, s *zero, s *one) noexcept nogil:
+    
+    return _fortran_ieeeck(ispec, zero, one)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaclc "BLAS_FUNC(ilaclc)"(int *m, int *n, npy_complex64 *a, int *lda) nogil
+cdef int ilaclc(int *m, int *n, c *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaclc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaclr "BLAS_FUNC(ilaclr)"(int *m, int *n, npy_complex64 *a, int *lda) nogil
+cdef int ilaclr(int *m, int *n, c *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaclr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_iladiag "BLAS_FUNC(iladiag)"(char *diag) nogil
+cdef int iladiag(char *diag) noexcept nogil:
+    
+    return _fortran_iladiag(diag)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_iladlc "BLAS_FUNC(iladlc)"(int *m, int *n, d *a, int *lda) nogil
+cdef int iladlc(int *m, int *n, d *a, int *lda) noexcept nogil:
+    
+    return _fortran_iladlc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_iladlr "BLAS_FUNC(iladlr)"(int *m, int *n, d *a, int *lda) nogil
+cdef int iladlr(int *m, int *n, d *a, int *lda) noexcept nogil:
+    
+    return _fortran_iladlr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaprec "BLAS_FUNC(ilaprec)"(char *prec) nogil
+cdef int ilaprec(char *prec) noexcept nogil:
+    
+    return _fortran_ilaprec(prec)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaslc "BLAS_FUNC(ilaslc)"(int *m, int *n, s *a, int *lda) nogil
+cdef int ilaslc(int *m, int *n, s *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaslc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilaslr "BLAS_FUNC(ilaslr)"(int *m, int *n, s *a, int *lda) nogil
+cdef int ilaslr(int *m, int *n, s *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilaslr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilatrans "BLAS_FUNC(ilatrans)"(char *trans) nogil
+cdef int ilatrans(char *trans) noexcept nogil:
+    
+    return _fortran_ilatrans(trans)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilauplo "BLAS_FUNC(ilauplo)"(char *uplo) nogil
+cdef int ilauplo(char *uplo) noexcept nogil:
+    
+    return _fortran_ilauplo(uplo)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ilaver "BLAS_FUNC(ilaver)"(int *vers_major, int *vers_minor, int *vers_patch) nogil
+cdef void ilaver(int *vers_major, int *vers_minor, int *vers_patch) noexcept nogil:
+    
+    _fortran_ilaver(vers_major, vers_minor, vers_patch)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilazlc "BLAS_FUNC(ilazlc)"(int *m, int *n, npy_complex128 *a, int *lda) nogil
+cdef int ilazlc(int *m, int *n, z *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilazlc(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_ilazlr "BLAS_FUNC(ilazlr)"(int *m, int *n, npy_complex128 *a, int *lda) nogil
+cdef int ilazlr(int *m, int *n, z *a, int *lda) noexcept nogil:
+    
+    return _fortran_ilazlr(m, n, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    int _fortran_izmax1 "BLAS_FUNC(izmax1)"(int *n, npy_complex128 *cx, int *incx) nogil
+cdef int izmax1(int *n, z *cx, int *incx) noexcept nogil:
+    
+    return _fortran_izmax1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sbbcsd "BLAS_FUNC(sbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) nogil
+cdef void sbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, s *theta, s *phi, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *b11d, s *b11e, s *b12d, s *b12e, s *b21d, s *b21e, s *b22d, s *b22e, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sbdsdc "BLAS_FUNC(sbdsdc)"(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) nogil
+cdef void sbdsdc(char *uplo, char *compq, int *n, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, s *q, int *iq, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sbdsdc(uplo, compq, n, d, e, u, ldu, vt, ldvt, q, iq, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sbdsqr "BLAS_FUNC(sbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) nogil
+cdef void sbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_scsum1 "BLAS_FUNC(scsum1)"(int *n, npy_complex64 *cx, int *incx) nogil
+cdef s scsum1(int *n, c *cx, int *incx) noexcept nogil:
+    
+    return _fortran_scsum1(n, cx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sdisna "BLAS_FUNC(sdisna)"(char *job, int *m, int *n, s *d, s *sep, int *info) nogil
+cdef void sdisna(char *job, int *m, int *n, s *d, s *sep, int *info) noexcept nogil:
+    
+    _fortran_sdisna(job, m, n, d, sep, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbbrd "BLAS_FUNC(sgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) nogil
+cdef void sgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *pt, int *ldpt, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbcon "BLAS_FUNC(sgbcon)"(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sgbcon(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbequ "BLAS_FUNC(sgbequ)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void sgbequ(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbequb "BLAS_FUNC(sgbequb)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void sgbequb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbrfs "BLAS_FUNC(sgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbsv "BLAS_FUNC(sgbsv)"(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgbsv(int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbsvx "BLAS_FUNC(sgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbtf2 "BLAS_FUNC(sgbtf2)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void sgbtf2(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbtrf "BLAS_FUNC(sgbtrf)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void sgbtrf(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgbtrs "BLAS_FUNC(sgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, s *ab, int *ldab, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebak "BLAS_FUNC(sgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) nogil
+cdef void sgebak(char *job, char *side, int *n, int *ilo, int *ihi, s *scale, int *m, s *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_sgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebal "BLAS_FUNC(sgebal)"(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) nogil
+cdef void sgebal(char *job, int *n, s *a, int *lda, int *ilo, int *ihi, s *scale, int *info) noexcept nogil:
+    
+    _fortran_sgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebd2 "BLAS_FUNC(sgebd2)"(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) nogil
+cdef void sgebd2(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgebrd "BLAS_FUNC(sgebrd)"(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) nogil
+cdef void sgebrd(int *m, int *n, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgecon "BLAS_FUNC(sgecon)"(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sgecon(char *norm, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgecon(norm, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeequ "BLAS_FUNC(sgeequ)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void sgeequ(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeequb "BLAS_FUNC(sgeequb)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) nogil
+cdef void sgeequb(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgees "BLAS_FUNC(sgees)"(char *jobvs, char *sort, _sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) nogil
+cdef void sgees(char *jobvs, char *sort, sselect2 *select, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *work, int *lwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sgees(jobvs, sort, <_sselect2*>select, n, a, lda, sdim, wr, wi, vs, ldvs, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeesx "BLAS_FUNC(sgeesx)"(char *jobvs, char *sort, _sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void sgeesx(char *jobvs, char *sort, sselect2 *select, char *sense, int *n, s *a, int *lda, int *sdim, s *wr, s *wi, s *vs, int *ldvs, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sgeesx(jobvs, sort, <_sselect2*>select, sense, n, a, lda, sdim, wr, wi, vs, ldvs, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeev "BLAS_FUNC(sgeev)"(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) nogil
+cdef void sgeev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeevx "BLAS_FUNC(sgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *scale, s *abnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgeevx(balanc, jobvl, jobvr, sense, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgehd2 "BLAS_FUNC(sgehd2)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgehd2(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgehrd "BLAS_FUNC(sgehrd)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgehrd(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgejsv "BLAS_FUNC(sgejsv)"(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sgejsv(char *joba, char *jobu, char *jobv, char *jobr, char *jobt, char *jobp, int *m, int *n, s *a, int *lda, s *sva, s *u, int *ldu, s *v, int *ldv, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgejsv(joba, jobu, jobv, jobr, jobt, jobp, m, n, a, lda, sva, u, ldu, v, ldv, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelq2 "BLAS_FUNC(sgelq2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgelq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelqf "BLAS_FUNC(sgelqf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgelqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgels "BLAS_FUNC(sgels)"(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) nogil
+cdef void sgels(char *trans, int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelsd "BLAS_FUNC(sgelsd)"(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sgelsd(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelss "BLAS_FUNC(sgelss)"(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) nogil
+cdef void sgelss(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *s, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgelsy "BLAS_FUNC(sgelsy)"(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) nogil
+cdef void sgelsy(int *m, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *jpvt, s *rcond, int *rank, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgemqrt "BLAS_FUNC(sgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) nogil
+cdef void sgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeql2 "BLAS_FUNC(sgeql2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgeql2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqlf "BLAS_FUNC(sgeqlf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqlf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqp3 "BLAS_FUNC(sgeqp3)"(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqp3(int *m, int *n, s *a, int *lda, int *jpvt, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqp3(m, n, a, lda, jpvt, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqr2 "BLAS_FUNC(sgeqr2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgeqr2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqr2p "BLAS_FUNC(sgeqr2p)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgeqr2p(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrf "BLAS_FUNC(sgeqrf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqrf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrfp "BLAS_FUNC(sgeqrfp)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgeqrfp(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrt "BLAS_FUNC(sgeqrt)"(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) nogil
+cdef void sgeqrt(int *m, int *n, int *nb, s *a, int *lda, s *t, int *ldt, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrt2 "BLAS_FUNC(sgeqrt2)"(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) nogil
+cdef void sgeqrt2(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_sgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgeqrt3 "BLAS_FUNC(sgeqrt3)"(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) nogil
+cdef void sgeqrt3(int *m, int *n, s *a, int *lda, s *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_sgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgerfs "BLAS_FUNC(sgerfs)"(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgerfs(char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgerq2 "BLAS_FUNC(sgerq2)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sgerq2(int *m, int *n, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgerqf "BLAS_FUNC(sgerqf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sgerqf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesc2 "BLAS_FUNC(sgesc2)"(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) nogil
+cdef void sgesc2(int *n, s *a, int *lda, s *rhs, int *ipiv, int *jpiv, s *scale) noexcept nogil:
+    
+    _fortran_sgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesdd "BLAS_FUNC(sgesdd)"(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sgesdd(char *jobz, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesv "BLAS_FUNC(sgesv)"(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgesv(int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesvd "BLAS_FUNC(sgesvd)"(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) nogil
+cdef void sgesvd(char *jobu, char *jobvt, int *m, int *n, s *a, int *lda, s *s, s *u, int *ldu, s *vt, int *ldvt, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesvj "BLAS_FUNC(sgesvj)"(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) nogil
+cdef void sgesvj(char *joba, char *jobu, char *jobv, int *m, int *n, s *a, int *lda, s *sva, int *mv, s *v, int *ldv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgesvj(joba, jobu, jobv, m, n, a, lda, sva, mv, v, ldv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgesvx "BLAS_FUNC(sgesvx)"(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgesvx(char *fact, char *trans, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, char *equed, s *r, s *c, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetc2 "BLAS_FUNC(sgetc2)"(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void sgetc2(int *n, s *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_sgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetf2 "BLAS_FUNC(sgetf2)"(int *m, int *n, s *a, int *lda, int *ipiv, int *info) nogil
+cdef void sgetf2(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetrf "BLAS_FUNC(sgetrf)"(int *m, int *n, s *a, int *lda, int *ipiv, int *info) nogil
+cdef void sgetrf(int *m, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetri "BLAS_FUNC(sgetri)"(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil
+cdef void sgetri(int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgetrs "BLAS_FUNC(sgetrs)"(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgetrs(char *trans, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggbak "BLAS_FUNC(sggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) nogil
+cdef void sggbak(char *job, char *side, int *n, int *ilo, int *ihi, s *lscale, s *rscale, int *m, s *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_sggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggbal "BLAS_FUNC(sggbal)"(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) nogil
+cdef void sggbal(char *job, int *n, s *a, int *lda, s *b, int *ldb, int *ilo, int *ihi, s *lscale, s *rscale, s *work, int *info) noexcept nogil:
+    
+    _fortran_sggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgges "BLAS_FUNC(sgges)"(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) nogil
+cdef void sgges(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *work, int *lwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sgges(jobvsl, jobvsr, sort, <_sselect3*>selctg, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggesx "BLAS_FUNC(sggesx)"(char *jobvsl, char *jobvsr, char *sort, _sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void sggesx(char *jobvsl, char *jobvsr, char *sort, sselect3 *selctg, char *sense, int *n, s *a, int *lda, s *b, int *ldb, int *sdim, s *alphar, s *alphai, s *beta, s *vsl, int *ldvsl, s *vsr, int *ldvsr, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sggesx(jobvsl, jobvsr, sort, <_sselect3*>selctg, sense, n, a, lda, b, ldb, sdim, alphar, alphai, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggev "BLAS_FUNC(sggev)"(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) nogil
+cdef void sggev(char *jobvl, char *jobvr, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggevx "BLAS_FUNC(sggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) nogil
+cdef void sggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *vl, int *ldvl, s *vr, int *ldvr, int *ilo, int *ihi, s *lscale, s *rscale, s *abnrm, s *bbnrm, s *rconde, s *rcondv, s *work, int *lwork, int *iwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_sggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggglm "BLAS_FUNC(sggglm)"(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) nogil
+cdef void sggglm(int *n, int *m, int *p, s *a, int *lda, s *b, int *ldb, s *d, s *x, s *y, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgghrd "BLAS_FUNC(sgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) nogil
+cdef void sgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_sgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgglse "BLAS_FUNC(sgglse)"(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) nogil
+cdef void sgglse(int *m, int *n, int *p, s *a, int *lda, s *b, int *ldb, s *c, s *d, s *x, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggqrf "BLAS_FUNC(sggqrf)"(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) nogil
+cdef void sggqrf(int *n, int *m, int *p, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sggrqf "BLAS_FUNC(sggrqf)"(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) nogil
+cdef void sggrqf(int *m, int *p, int *n, s *a, int *lda, s *taua, s *b, int *ldb, s *taub, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgsvj0 "BLAS_FUNC(sgsvj0)"(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) nogil
+cdef void sgsvj0(char *jobv, int *m, int *n, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgsvj0(jobv, m, n, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgsvj1 "BLAS_FUNC(sgsvj1)"(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) nogil
+cdef void sgsvj1(char *jobv, int *m, int *n, int *n1, s *a, int *lda, s *d, s *sva, int *mv, s *v, int *ldv, s *eps, s *sfmin, s *tol, int *nsweep, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sgsvj1(jobv, m, n, n1, a, lda, d, sva, mv, v, ldv, eps, sfmin, tol, nsweep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtcon "BLAS_FUNC(sgtcon)"(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sgtcon(char *norm, int *n, s *dl, s *d, s *du, s *du2, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtrfs "BLAS_FUNC(sgtrfs)"(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgtrfs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtsv "BLAS_FUNC(sgtsv)"(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) nogil
+cdef void sgtsv(int *n, int *nrhs, s *dl, s *d, s *du, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtsvx "BLAS_FUNC(sgtsvx)"(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sgtsvx(char *fact, char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *dlf, s *df, s *duf, s *du2, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgttrf "BLAS_FUNC(sgttrf)"(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) nogil
+cdef void sgttrf(int *n, s *dl, s *d, s *du, s *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_sgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgttrs "BLAS_FUNC(sgttrs)"(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sgttrs(char *trans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sgtts2 "BLAS_FUNC(sgtts2)"(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) nogil
+cdef void sgtts2(int *itrans, int *n, int *nrhs, s *dl, s *d, s *du, s *du2, int *ipiv, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_sgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_shgeqz "BLAS_FUNC(shgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) nogil
+cdef void shgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *t, int *ldt, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_shgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alphar, alphai, beta, q, ldq, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_shsein "BLAS_FUNC(shsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) nogil
+cdef void shsein(char *side, char *eigsrc, char *initv, bint *select, int *n, s *h, int *ldh, s *wr, s *wi, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *ifaill, int *ifailr, int *info) noexcept nogil:
+    
+    _fortran_shsein(side, eigsrc, initv, select, n, h, ldh, wr, wi, vl, ldvl, vr, ldvr, mm, m, work, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_shseqr "BLAS_FUNC(shseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) nogil
+cdef void shseqr(char *job, char *compz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_shseqr(job, compz, n, ilo, ihi, h, ldh, wr, wi, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slabad "BLAS_FUNC(slabad)"(s *small, s *large) nogil
+cdef void slabad(s *small, s *large) noexcept nogil:
+    
+    _fortran_slabad(small, large)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slabrd "BLAS_FUNC(slabrd)"(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) nogil
+cdef void slabrd(int *m, int *n, int *nb, s *a, int *lda, s *d, s *e, s *tauq, s *taup, s *x, int *ldx, s *y, int *ldy) noexcept nogil:
+    
+    _fortran_slabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slacn2 "BLAS_FUNC(slacn2)"(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) nogil
+cdef void slacn2(int *n, s *v, s *x, int *isgn, s *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_slacn2(n, v, x, isgn, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slacon "BLAS_FUNC(slacon)"(int *n, s *v, s *x, int *isgn, s *est, int *kase) nogil
+cdef void slacon(int *n, s *v, s *x, int *isgn, s *est, int *kase) noexcept nogil:
+    
+    _fortran_slacon(n, v, x, isgn, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slacpy "BLAS_FUNC(slacpy)"(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) nogil
+cdef void slacpy(char *uplo, int *m, int *n, s *a, int *lda, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_slacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sladiv "BLAS_FUNC(sladiv)"(s *a, s *b, s *c, s *d, s *p, s *q) nogil
+cdef void sladiv(s *a, s *b, s *c, s *d, s *p, s *q) noexcept nogil:
+    
+    _fortran_sladiv(a, b, c, d, p, q)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slae2 "BLAS_FUNC(slae2)"(s *a, s *b, s *c, s *rt1, s *rt2) nogil
+cdef void slae2(s *a, s *b, s *c, s *rt1, s *rt2) noexcept nogil:
+    
+    _fortran_slae2(a, b, c, rt1, rt2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaebz "BLAS_FUNC(slaebz)"(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) nogil
+cdef void slaebz(int *ijob, int *nitmax, int *n, int *mmax, int *minp, int *nbmin, s *abstol, s *reltol, s *pivmin, s *d, s *e, s *e2, int *nval, s *ab, s *c, int *mout, int *nab, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slaebz(ijob, nitmax, n, mmax, minp, nbmin, abstol, reltol, pivmin, d, e, e2, nval, ab, c, mout, nab, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed0 "BLAS_FUNC(slaed0)"(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) nogil
+cdef void slaed0(int *icompq, int *qsiz, int *n, s *d, s *e, s *q, int *ldq, s *qstore, int *ldqs, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slaed0(icompq, qsiz, n, d, e, q, ldq, qstore, ldqs, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed1 "BLAS_FUNC(slaed1)"(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) nogil
+cdef void slaed1(int *n, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slaed1(n, d, q, ldq, indxq, rho, cutpnt, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed2 "BLAS_FUNC(slaed2)"(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) nogil
+cdef void slaed2(int *k, int *n, int *n1, s *d, s *q, int *ldq, int *indxq, s *rho, s *z, s *dlamda, s *w, s *q2, int *indx, int *indxc, int *indxp, int *coltyp, int *info) noexcept nogil:
+    
+    _fortran_slaed2(k, n, n1, d, q, ldq, indxq, rho, z, dlamda, w, q2, indx, indxc, indxp, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed3 "BLAS_FUNC(slaed3)"(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) nogil
+cdef void slaed3(int *k, int *n, int *n1, s *d, s *q, int *ldq, s *rho, s *dlamda, s *q2, int *indx, int *ctot, s *w, s *s, int *info) noexcept nogil:
+    
+    _fortran_slaed3(k, n, n1, d, q, ldq, rho, dlamda, q2, indx, ctot, w, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed4 "BLAS_FUNC(slaed4)"(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) nogil
+cdef void slaed4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *dlam, int *info) noexcept nogil:
+    
+    _fortran_slaed4(n, i, d, z, delta, rho, dlam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed5 "BLAS_FUNC(slaed5)"(int *i, s *d, s *z, s *delta, s *rho, s *dlam) nogil
+cdef void slaed5(int *i, s *d, s *z, s *delta, s *rho, s *dlam) noexcept nogil:
+    
+    _fortran_slaed5(i, d, z, delta, rho, dlam)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed6 "BLAS_FUNC(slaed6)"(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) nogil
+cdef void slaed6(int *kniter, bint *orgati, s *rho, s *d, s *z, s *finit, s *tau, int *info) noexcept nogil:
+    
+    _fortran_slaed6(kniter, orgati, rho, d, z, finit, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed7 "BLAS_FUNC(slaed7)"(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) nogil
+cdef void slaed7(int *icompq, int *n, int *qsiz, int *tlvls, int *curlvl, int *curpbm, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slaed7(icompq, n, qsiz, tlvls, curlvl, curpbm, d, q, ldq, indxq, rho, cutpnt, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed8 "BLAS_FUNC(slaed8)"(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) nogil
+cdef void slaed8(int *icompq, int *k, int *n, int *qsiz, s *d, s *q, int *ldq, int *indxq, s *rho, int *cutpnt, s *z, s *dlamda, s *q2, int *ldq2, s *w, int *perm, int *givptr, int *givcol, s *givnum, int *indxp, int *indx, int *info) noexcept nogil:
+    
+    _fortran_slaed8(icompq, k, n, qsiz, d, q, ldq, indxq, rho, cutpnt, z, dlamda, q2, ldq2, w, perm, givptr, givcol, givnum, indxp, indx, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaed9 "BLAS_FUNC(slaed9)"(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) nogil
+cdef void slaed9(int *k, int *kstart, int *kstop, int *n, s *d, s *q, int *ldq, s *rho, s *dlamda, s *w, s *s, int *lds, int *info) noexcept nogil:
+    
+    _fortran_slaed9(k, kstart, kstop, n, d, q, ldq, rho, dlamda, w, s, lds, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaeda "BLAS_FUNC(slaeda)"(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) nogil
+cdef void slaeda(int *n, int *tlvls, int *curlvl, int *curpbm, int *prmptr, int *perm, int *givptr, int *givcol, s *givnum, s *q, int *qptr, s *z, s *ztemp, int *info) noexcept nogil:
+    
+    _fortran_slaeda(n, tlvls, curlvl, curpbm, prmptr, perm, givptr, givcol, givnum, q, qptr, z, ztemp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaein "BLAS_FUNC(slaein)"(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) nogil
+cdef void slaein(bint *rightv, bint *noinit, int *n, s *h, int *ldh, s *wr, s *wi, s *vr, s *vi, s *b, int *ldb, s *work, s *eps3, s *smlnum, s *bignum, int *info) noexcept nogil:
+    
+    _fortran_slaein(rightv, noinit, n, h, ldh, wr, wi, vr, vi, b, ldb, work, eps3, smlnum, bignum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaev2 "BLAS_FUNC(slaev2)"(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) nogil
+cdef void slaev2(s *a, s *b, s *c, s *rt1, s *rt2, s *cs1, s *sn1) noexcept nogil:
+    
+    _fortran_slaev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaexc "BLAS_FUNC(slaexc)"(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) nogil
+cdef void slaexc(bint *wantq, int *n, s *t, int *ldt, s *q, int *ldq, int *j1, int *n1, int *n2, s *work, int *info) noexcept nogil:
+    
+    _fortran_slaexc(wantq, n, t, ldt, q, ldq, j1, n1, n2, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slag2 "BLAS_FUNC(slag2)"(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) nogil
+cdef void slag2(s *a, int *lda, s *b, int *ldb, s *safmin, s *scale1, s *scale2, s *wr1, s *wr2, s *wi) noexcept nogil:
+    
+    _fortran_slag2(a, lda, b, ldb, safmin, scale1, scale2, wr1, wr2, wi)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slag2d "BLAS_FUNC(slag2d)"(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) nogil
+cdef void slag2d(int *m, int *n, s *sa, int *ldsa, d *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slag2d(m, n, sa, ldsa, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slags2 "BLAS_FUNC(slags2)"(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) nogil
+cdef void slags2(bint *upper, s *a1, s *a2, s *a3, s *b1, s *b2, s *b3, s *csu, s *snu, s *csv, s *snv, s *csq, s *snq) noexcept nogil:
+    
+    _fortran_slags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagtf "BLAS_FUNC(slagtf)"(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) nogil
+cdef void slagtf(int *n, s *a, s *lambda_, s *b, s *c, s *tol, s *d, int *in_, int *info) noexcept nogil:
+    
+    _fortran_slagtf(n, a, lambda_, b, c, tol, d, in_, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagtm "BLAS_FUNC(slagtm)"(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) nogil
+cdef void slagtm(char *trans, int *n, int *nrhs, s *alpha, s *dl, s *d, s *du, s *x, int *ldx, s *beta, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_slagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagts "BLAS_FUNC(slagts)"(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) nogil
+cdef void slagts(int *job, int *n, s *a, s *b, s *c, s *d, int *in_, s *y, s *tol, int *info) noexcept nogil:
+    
+    _fortran_slagts(job, n, a, b, c, d, in_, y, tol, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slagv2 "BLAS_FUNC(slagv2)"(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) nogil
+cdef void slagv2(s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *csl, s *snl, s *csr, s *snr) noexcept nogil:
+    
+    _fortran_slagv2(a, lda, b, ldb, alphar, alphai, beta, csl, snl, csr, snr)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slahqr "BLAS_FUNC(slahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) nogil
+cdef void slahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_slahqr(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slahr2 "BLAS_FUNC(slahr2)"(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) nogil
+cdef void slahr2(int *n, int *k, int *nb, s *a, int *lda, s *tau, s *t, int *ldt, s *y, int *ldy) noexcept nogil:
+    
+    _fortran_slahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaic1 "BLAS_FUNC(slaic1)"(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) nogil
+cdef void slaic1(int *job, int *j, s *x, s *sest, s *w, s *gamma, s *sestpr, s *s, s *c) noexcept nogil:
+    
+    _fortran_slaic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaln2 "BLAS_FUNC(slaln2)"(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) nogil
+cdef void slaln2(bint *ltrans, int *na, int *nw, s *smin, s *ca, s *a, int *lda, s *d1, s *d2, s *b, int *ldb, s *wr, s *wi, s *x, int *ldx, s *scale, s *xnorm, int *info) noexcept nogil:
+    
+    _fortran_slaln2(ltrans, na, nw, smin, ca, a, lda, d1, d2, b, ldb, wr, wi, x, ldx, scale, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slals0 "BLAS_FUNC(slals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) nogil
+cdef void slals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *info) noexcept nogil:
+    
+    _fortran_slals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slalsa "BLAS_FUNC(slalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) nogil
+cdef void slalsa(int *icompq, int *smlsiz, int *n, int *nrhs, s *b, int *ldb, s *bx, int *ldbx, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slalsd "BLAS_FUNC(slalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) nogil
+cdef void slalsd(char *uplo, int *smlsiz, int *n, int *nrhs, s *d, s *e, s *b, int *ldb, s *rcond, int *rank, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slamch "BLAS_FUNC(slamch)"(char *cmach) nogil
+cdef s slamch(char *cmach) noexcept nogil:
+    
+    return _fortran_slamch(cmach)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slamrg "BLAS_FUNC(slamrg)"(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) nogil
+cdef void slamrg(int *n1, int *n2, s *a, int *strd1, int *strd2, int *index_bn) noexcept nogil:
+    
+    _fortran_slamrg(n1, n2, a, strd1, strd2, index_bn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slangb "BLAS_FUNC(slangb)"(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) nogil
+cdef s slangb(char *norm, int *n, int *kl, int *ku, s *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_slangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slange "BLAS_FUNC(slange)"(char *norm, int *m, int *n, s *a, int *lda, s *work) nogil
+cdef s slange(char *norm, int *m, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slangt "BLAS_FUNC(slangt)"(char *norm, int *n, s *dl, s *d, s *du) nogil
+cdef s slangt(char *norm, int *n, s *dl, s *d, s *du) noexcept nogil:
+    
+    return _fortran_slangt(norm, n, dl, d, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slanhs "BLAS_FUNC(slanhs)"(char *norm, int *n, s *a, int *lda, s *work) nogil
+cdef s slanhs(char *norm, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansb "BLAS_FUNC(slansb)"(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) nogil
+cdef s slansb(char *norm, char *uplo, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_slansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansf "BLAS_FUNC(slansf)"(char *norm, char *transr, char *uplo, int *n, s *a, s *work) nogil
+cdef s slansf(char *norm, char *transr, char *uplo, int *n, s *a, s *work) noexcept nogil:
+    
+    return _fortran_slansf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansp "BLAS_FUNC(slansp)"(char *norm, char *uplo, int *n, s *ap, s *work) nogil
+cdef s slansp(char *norm, char *uplo, int *n, s *ap, s *work) noexcept nogil:
+    
+    return _fortran_slansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slanst "BLAS_FUNC(slanst)"(char *norm, int *n, s *d, s *e) nogil
+cdef s slanst(char *norm, int *n, s *d, s *e) noexcept nogil:
+    
+    return _fortran_slanst(norm, n, d, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slansy "BLAS_FUNC(slansy)"(char *norm, char *uplo, int *n, s *a, int *lda, s *work) nogil
+cdef s slansy(char *norm, char *uplo, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slantb "BLAS_FUNC(slantb)"(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) nogil
+cdef s slantb(char *norm, char *uplo, char *diag, int *n, int *k, s *ab, int *ldab, s *work) noexcept nogil:
+    
+    return _fortran_slantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slantp "BLAS_FUNC(slantp)"(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) nogil
+cdef s slantp(char *norm, char *uplo, char *diag, int *n, s *ap, s *work) noexcept nogil:
+    
+    return _fortran_slantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slantr "BLAS_FUNC(slantr)"(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) nogil
+cdef s slantr(char *norm, char *uplo, char *diag, int *m, int *n, s *a, int *lda, s *work) noexcept nogil:
+    
+    return _fortran_slantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slanv2 "BLAS_FUNC(slanv2)"(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) nogil
+cdef void slanv2(s *a, s *b, s *c, s *d, s *rt1r, s *rt1i, s *rt2r, s *rt2i, s *cs, s *sn) noexcept nogil:
+    
+    _fortran_slanv2(a, b, c, d, rt1r, rt1i, rt2r, rt2i, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slapll "BLAS_FUNC(slapll)"(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) nogil
+cdef void slapll(int *n, s *x, int *incx, s *y, int *incy, s *ssmin) noexcept nogil:
+    
+    _fortran_slapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slapmr "BLAS_FUNC(slapmr)"(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) nogil
+cdef void slapmr(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_slapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slapmt "BLAS_FUNC(slapmt)"(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) nogil
+cdef void slapmt(bint *forwrd, int *m, int *n, s *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_slapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slapy2 "BLAS_FUNC(slapy2)"(s *x, s *y) nogil
+cdef s slapy2(s *x, s *y) noexcept nogil:
+    
+    return _fortran_slapy2(x, y)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    s _fortran_slapy3 "BLAS_FUNC(slapy3)"(s *x, s *y, s *z) nogil
+cdef s slapy3(s *x, s *y, s *z) noexcept nogil:
+    
+    return _fortran_slapy3(x, y, z)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqgb "BLAS_FUNC(slaqgb)"(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil
+cdef void slaqgb(int *m, int *n, int *kl, int *ku, s *ab, int *ldab, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqge "BLAS_FUNC(slaqge)"(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) nogil
+cdef void slaqge(int *m, int *n, s *a, int *lda, s *r, s *c, s *rowcnd, s *colcnd, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqp2 "BLAS_FUNC(slaqp2)"(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) nogil
+cdef void slaqp2(int *m, int *n, int *offset, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *work) noexcept nogil:
+    
+    _fortran_slaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqps "BLAS_FUNC(slaqps)"(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) nogil
+cdef void slaqps(int *m, int *n, int *offset, int *nb, int *kb, s *a, int *lda, int *jpvt, s *tau, s *vn1, s *vn2, s *auxv, s *f, int *ldf) noexcept nogil:
+    
+    _fortran_slaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr0 "BLAS_FUNC(slaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) nogil
+cdef void slaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_slaqr0(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr1 "BLAS_FUNC(slaqr1)"(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) nogil
+cdef void slaqr1(int *n, s *h, int *ldh, s *sr1, s *si1, s *sr2, s *si2, s *v) noexcept nogil:
+    
+    _fortran_slaqr1(n, h, ldh, sr1, si1, sr2, si2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr2 "BLAS_FUNC(slaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) nogil
+cdef void slaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil:
+    
+    _fortran_slaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr3 "BLAS_FUNC(slaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) nogil
+cdef void slaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, int *ns, int *nd, s *sr, s *si, s *v, int *ldv, int *nh, s *t, int *ldt, int *nv, s *wv, int *ldwv, s *work, int *lwork) noexcept nogil:
+    
+    _fortran_slaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sr, si, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr4 "BLAS_FUNC(slaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) nogil
+cdef void slaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, s *h, int *ldh, s *wr, s *wi, int *iloz, int *ihiz, s *z, int *ldz, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_slaqr4(wantt, wantz, n, ilo, ihi, h, ldh, wr, wi, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqr5 "BLAS_FUNC(slaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) nogil
+cdef void slaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, s *sr, s *si, s *h, int *ldh, int *iloz, int *ihiz, s *z, int *ldz, s *v, int *ldv, s *u, int *ldu, int *nv, s *wv, int *ldwv, int *nh, s *wh, int *ldwh) noexcept nogil:
+    
+    _fortran_slaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, sr, si, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqsb "BLAS_FUNC(slaqsb)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) nogil
+cdef void slaqsb(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqsp "BLAS_FUNC(slaqsp)"(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) nogil
+cdef void slaqsp(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqsy "BLAS_FUNC(slaqsy)"(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) nogil
+cdef void slaqsy(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, char *equed) noexcept nogil:
+    
+    _fortran_slaqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaqtr "BLAS_FUNC(slaqtr)"(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) nogil
+cdef void slaqtr(bint *ltran, bint *lreal, int *n, s *t, int *ldt, s *b, s *w, s *scale, s *x, s *work, int *info) noexcept nogil:
+    
+    _fortran_slaqtr(ltran, lreal, n, t, ldt, b, w, scale, x, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slar1v "BLAS_FUNC(slar1v)"(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) nogil
+cdef void slar1v(int *n, int *b1, int *bn, s *lambda_, s *d, s *l, s *ld, s *lld, s *pivmin, s *gaptol, s *z, bint *wantnc, int *negcnt, s *ztz, s *mingma, int *r, int *isuppz, s *nrminv, s *resid, s *rqcorr, s *work) noexcept nogil:
+    
+    _fortran_slar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slar2v "BLAS_FUNC(slar2v)"(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) nogil
+cdef void slar2v(int *n, s *x, s *y, s *z, int *incx, s *c, s *s, int *incc) noexcept nogil:
+    
+    _fortran_slar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarf "BLAS_FUNC(slarf)"(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) nogil
+cdef void slarf(char *side, int *m, int *n, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil:
+    
+    _fortran_slarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfb "BLAS_FUNC(slarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) nogil
+cdef void slarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil:
+    
+    _fortran_slarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfg "BLAS_FUNC(slarfg)"(int *n, s *alpha, s *x, int *incx, s *tau) nogil
+cdef void slarfg(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil:
+    
+    _fortran_slarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfgp "BLAS_FUNC(slarfgp)"(int *n, s *alpha, s *x, int *incx, s *tau) nogil
+cdef void slarfgp(int *n, s *alpha, s *x, int *incx, s *tau) noexcept nogil:
+    
+    _fortran_slarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarft "BLAS_FUNC(slarft)"(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) nogil
+cdef void slarft(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil:
+    
+    _fortran_slarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarfx "BLAS_FUNC(slarfx)"(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) nogil
+cdef void slarfx(char *side, int *m, int *n, s *v, s *tau, s *c, int *ldc, s *work) noexcept nogil:
+    
+    _fortran_slarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slargv "BLAS_FUNC(slargv)"(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) nogil
+cdef void slargv(int *n, s *x, int *incx, s *y, int *incy, s *c, int *incc) noexcept nogil:
+    
+    _fortran_slargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarnv "BLAS_FUNC(slarnv)"(int *idist, int *iseed, int *n, s *x) nogil
+cdef void slarnv(int *idist, int *iseed, int *n, s *x) noexcept nogil:
+    
+    _fortran_slarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarra "BLAS_FUNC(slarra)"(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) nogil
+cdef void slarra(int *n, s *d, s *e, s *e2, s *spltol, s *tnrm, int *nsplit, int *isplit, int *info) noexcept nogil:
+    
+    _fortran_slarra(n, d, e, e2, spltol, tnrm, nsplit, isplit, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrb "BLAS_FUNC(slarrb)"(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) nogil
+cdef void slarrb(int *n, s *d, s *lld, int *ifirst, int *ilast, s *rtol1, s *rtol2, int *offset, s *w, s *wgap, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *twist, int *info) noexcept nogil:
+    
+    _fortran_slarrb(n, d, lld, ifirst, ilast, rtol1, rtol2, offset, w, wgap, werr, work, iwork, pivmin, spdiam, twist, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrc "BLAS_FUNC(slarrc)"(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) nogil
+cdef void slarrc(char *jobt, int *n, s *vl, s *vu, s *d, s *e, s *pivmin, int *eigcnt, int *lcnt, int *rcnt, int *info) noexcept nogil:
+    
+    _fortran_slarrc(jobt, n, vl, vu, d, e, pivmin, eigcnt, lcnt, rcnt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrd "BLAS_FUNC(slarrd)"(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) nogil
+cdef void slarrd(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *gers, s *reltol, s *d, s *e, s *e2, s *pivmin, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wl, s *wu, int *iblock, int *indexw, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slarrd(range, order, n, vl, vu, il, iu, gers, reltol, d, e, e2, pivmin, nsplit, isplit, m, w, werr, wl, wu, iblock, indexw, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarre "BLAS_FUNC(slarre)"(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) nogil
+cdef void slarre(char *range, int *n, s *vl, s *vu, int *il, int *iu, s *d, s *e, s *e2, s *rtol1, s *rtol2, s *spltol, int *nsplit, int *isplit, int *m, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *pivmin, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slarre(range, n, vl, vu, il, iu, d, e, e2, rtol1, rtol2, spltol, nsplit, isplit, m, w, werr, wgap, iblock, indexw, gers, pivmin, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrf "BLAS_FUNC(slarrf)"(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) nogil
+cdef void slarrf(int *n, s *d, s *l, s *ld, int *clstrt, int *clend, s *w, s *wgap, s *werr, s *spdiam, s *clgapl, s *clgapr, s *pivmin, s *sigma, s *dplus, s *lplus, s *work, int *info) noexcept nogil:
+    
+    _fortran_slarrf(n, d, l, ld, clstrt, clend, w, wgap, werr, spdiam, clgapl, clgapr, pivmin, sigma, dplus, lplus, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrj "BLAS_FUNC(slarrj)"(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) nogil
+cdef void slarrj(int *n, s *d, s *e2, int *ifirst, int *ilast, s *rtol, int *offset, s *w, s *werr, s *work, int *iwork, s *pivmin, s *spdiam, int *info) noexcept nogil:
+    
+    _fortran_slarrj(n, d, e2, ifirst, ilast, rtol, offset, w, werr, work, iwork, pivmin, spdiam, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrk "BLAS_FUNC(slarrk)"(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) nogil
+cdef void slarrk(int *n, int *iw, s *gl, s *gu, s *d, s *e2, s *pivmin, s *reltol, s *w, s *werr, int *info) noexcept nogil:
+    
+    _fortran_slarrk(n, iw, gl, gu, d, e2, pivmin, reltol, w, werr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrr "BLAS_FUNC(slarrr)"(int *n, s *d, s *e, int *info) nogil
+cdef void slarrr(int *n, s *d, s *e, int *info) noexcept nogil:
+    
+    _fortran_slarrr(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarrv "BLAS_FUNC(slarrv)"(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) nogil
+cdef void slarrv(int *n, s *vl, s *vu, s *d, s *l, s *pivmin, int *isplit, int *m, int *dol, int *dou, s *minrgp, s *rtol1, s *rtol2, s *w, s *werr, s *wgap, int *iblock, int *indexw, s *gers, s *z, int *ldz, int *isuppz, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartg "BLAS_FUNC(slartg)"(s *f, s *g, s *cs, s *sn, s *r) nogil
+cdef void slartg(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil:
+    
+    _fortran_slartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartgp "BLAS_FUNC(slartgp)"(s *f, s *g, s *cs, s *sn, s *r) nogil
+cdef void slartgp(s *f, s *g, s *cs, s *sn, s *r) noexcept nogil:
+    
+    _fortran_slartgp(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartgs "BLAS_FUNC(slartgs)"(s *x, s *y, s *sigma, s *cs, s *sn) nogil
+cdef void slartgs(s *x, s *y, s *sigma, s *cs, s *sn) noexcept nogil:
+    
+    _fortran_slartgs(x, y, sigma, cs, sn)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slartv "BLAS_FUNC(slartv)"(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) nogil
+cdef void slartv(int *n, s *x, int *incx, s *y, int *incy, s *c, s *s, int *incc) noexcept nogil:
+    
+    _fortran_slartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaruv "BLAS_FUNC(slaruv)"(int *iseed, int *n, s *x) nogil
+cdef void slaruv(int *iseed, int *n, s *x) noexcept nogil:
+    
+    _fortran_slaruv(iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarz "BLAS_FUNC(slarz)"(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) nogil
+cdef void slarz(char *side, int *m, int *n, int *l, s *v, int *incv, s *tau, s *c, int *ldc, s *work) noexcept nogil:
+    
+    _fortran_slarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarzb "BLAS_FUNC(slarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) nogil
+cdef void slarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *c, int *ldc, s *work, int *ldwork) noexcept nogil:
+    
+    _fortran_slarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slarzt "BLAS_FUNC(slarzt)"(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) nogil
+cdef void slarzt(char *direct, char *storev, int *n, int *k, s *v, int *ldv, s *tau, s *t, int *ldt) noexcept nogil:
+    
+    _fortran_slarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slas2 "BLAS_FUNC(slas2)"(s *f, s *g, s *h, s *ssmin, s *ssmax) nogil
+cdef void slas2(s *f, s *g, s *h, s *ssmin, s *ssmax) noexcept nogil:
+    
+    _fortran_slas2(f, g, h, ssmin, ssmax)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slascl "BLAS_FUNC(slascl)"(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) nogil
+cdef void slascl(char *type_bn, int *kl, int *ku, s *cfrom, s *cto, int *m, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd0 "BLAS_FUNC(slasd0)"(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) nogil
+cdef void slasd0(int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *ldvt, int *smlsiz, int *iwork, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasd0(n, sqre, d, e, u, ldu, vt, ldvt, smlsiz, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd1 "BLAS_FUNC(slasd1)"(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) nogil
+cdef void slasd1(int *nl, int *nr, int *sqre, s *d, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, int *idxq, int *iwork, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasd1(nl, nr, sqre, d, alpha, beta, u, ldu, vt, ldvt, idxq, iwork, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd2 "BLAS_FUNC(slasd2)"(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) nogil
+cdef void slasd2(int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *alpha, s *beta, s *u, int *ldu, s *vt, int *ldvt, s *dsigma, s *u2, int *ldu2, s *vt2, int *ldvt2, int *idxp, int *idx, int *idxc, int *idxq, int *coltyp, int *info) noexcept nogil:
+    
+    _fortran_slasd2(nl, nr, sqre, k, d, z, alpha, beta, u, ldu, vt, ldvt, dsigma, u2, ldu2, vt2, ldvt2, idxp, idx, idxc, idxq, coltyp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd3 "BLAS_FUNC(slasd3)"(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) nogil
+cdef void slasd3(int *nl, int *nr, int *sqre, int *k, s *d, s *q, int *ldq, s *dsigma, s *u, int *ldu, s *u2, int *ldu2, s *vt, int *ldvt, s *vt2, int *ldvt2, int *idxc, int *ctot, s *z, int *info) noexcept nogil:
+    
+    _fortran_slasd3(nl, nr, sqre, k, d, q, ldq, dsigma, u, ldu, u2, ldu2, vt, ldvt, vt2, ldvt2, idxc, ctot, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd4 "BLAS_FUNC(slasd4)"(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) nogil
+cdef void slasd4(int *n, int *i, s *d, s *z, s *delta, s *rho, s *sigma, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasd4(n, i, d, z, delta, rho, sigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd5 "BLAS_FUNC(slasd5)"(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) nogil
+cdef void slasd5(int *i, s *d, s *z, s *delta, s *rho, s *dsigma, s *work) noexcept nogil:
+    
+    _fortran_slasd5(i, d, z, delta, rho, dsigma, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd6 "BLAS_FUNC(slasd6)"(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) nogil
+cdef void slasd6(int *icompq, int *nl, int *nr, int *sqre, s *d, s *vf, s *vl, s *alpha, s *beta, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *poles, s *difl, s *difr, s *z, int *k, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slasd6(icompq, nl, nr, sqre, d, vf, vl, alpha, beta, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd7 "BLAS_FUNC(slasd7)"(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) nogil
+cdef void slasd7(int *icompq, int *nl, int *nr, int *sqre, int *k, s *d, s *z, s *zw, s *vf, s *vfw, s *vl, s *vlw, s *alpha, s *beta, s *dsigma, int *idx, int *idxp, int *idxq, int *perm, int *givptr, int *givcol, int *ldgcol, s *givnum, int *ldgnum, s *c, s *s, int *info) noexcept nogil:
+    
+    _fortran_slasd7(icompq, nl, nr, sqre, k, d, z, zw, vf, vfw, vl, vlw, alpha, beta, dsigma, idx, idxp, idxq, perm, givptr, givcol, ldgcol, givnum, ldgnum, c, s, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasd8 "BLAS_FUNC(slasd8)"(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) nogil
+cdef void slasd8(int *icompq, int *k, s *d, s *z, s *vf, s *vl, s *difl, s *difr, int *lddifr, s *dsigma, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasd8(icompq, k, d, z, vf, vl, difl, difr, lddifr, dsigma, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasda "BLAS_FUNC(slasda)"(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) nogil
+cdef void slasda(int *icompq, int *smlsiz, int *n, int *sqre, s *d, s *e, s *u, int *ldu, s *vt, int *k, s *difl, s *difr, s *z, s *poles, int *givptr, int *givcol, int *ldgcol, int *perm, s *givnum, s *c, s *s, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_slasda(icompq, smlsiz, n, sqre, d, e, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasdq "BLAS_FUNC(slasdq)"(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) nogil
+cdef void slasdq(char *uplo, int *sqre, int *n, int *ncvt, int *nru, int *ncc, s *d, s *e, s *vt, int *ldvt, s *u, int *ldu, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasdq(uplo, sqre, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasdt "BLAS_FUNC(slasdt)"(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) nogil
+cdef void slasdt(int *n, int *lvl, int *nd, int *inode, int *ndiml, int *ndimr, int *msub) noexcept nogil:
+    
+    _fortran_slasdt(n, lvl, nd, inode, ndiml, ndimr, msub)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaset "BLAS_FUNC(slaset)"(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) nogil
+cdef void slaset(char *uplo, int *m, int *n, s *alpha, s *beta, s *a, int *lda) noexcept nogil:
+    
+    _fortran_slaset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq1 "BLAS_FUNC(slasq1)"(int *n, s *d, s *e, s *work, int *info) nogil
+cdef void slasq1(int *n, s *d, s *e, s *work, int *info) noexcept nogil:
+    
+    _fortran_slasq1(n, d, e, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq2 "BLAS_FUNC(slasq2)"(int *n, s *z, int *info) nogil
+cdef void slasq2(int *n, s *z, int *info) noexcept nogil:
+    
+    _fortran_slasq2(n, z, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq3 "BLAS_FUNC(slasq3)"(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) nogil
+cdef void slasq3(int *i0, int *n0, s *z, int *pp, s *dmin, s *sigma, s *desig, s *qmax, int *nfail, int *iter, int *ndiv, bint *ieee, int *ttype, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *g, s *tau) noexcept nogil:
+    
+    _fortran_slasq3(i0, n0, z, pp, dmin, sigma, desig, qmax, nfail, iter, ndiv, ieee, ttype, dmin1, dmin2, dn, dn1, dn2, g, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq4 "BLAS_FUNC(slasq4)"(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) nogil
+cdef void slasq4(int *i0, int *n0, s *z, int *pp, int *n0in, s *dmin, s *dmin1, s *dmin2, s *dn, s *dn1, s *dn2, s *tau, int *ttype, s *g) noexcept nogil:
+    
+    _fortran_slasq4(i0, n0, z, pp, n0in, dmin, dmin1, dmin2, dn, dn1, dn2, tau, ttype, g)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasq6 "BLAS_FUNC(slasq6)"(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) nogil
+cdef void slasq6(int *i0, int *n0, s *z, int *pp, s *dmin, s *dmin1, s *dmin2, s *dn, s *dnm1, s *dnm2) noexcept nogil:
+    
+    _fortran_slasq6(i0, n0, z, pp, dmin, dmin1, dmin2, dn, dnm1, dnm2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasr "BLAS_FUNC(slasr)"(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) nogil
+cdef void slasr(char *side, char *pivot, char *direct, int *m, int *n, s *c, s *s, s *a, int *lda) noexcept nogil:
+    
+    _fortran_slasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasrt "BLAS_FUNC(slasrt)"(char *id, int *n, s *d, int *info) nogil
+cdef void slasrt(char *id, int *n, s *d, int *info) noexcept nogil:
+    
+    _fortran_slasrt(id, n, d, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slassq "BLAS_FUNC(slassq)"(int *n, s *x, int *incx, s *scale, s *sumsq) nogil
+cdef void slassq(int *n, s *x, int *incx, s *scale, s *sumsq) noexcept nogil:
+    
+    _fortran_slassq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasv2 "BLAS_FUNC(slasv2)"(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) nogil
+cdef void slasv2(s *f, s *g, s *h, s *ssmin, s *ssmax, s *snr, s *csr, s *snl, s *csl) noexcept nogil:
+    
+    _fortran_slasv2(f, g, h, ssmin, ssmax, snr, csr, snl, csl)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slaswp "BLAS_FUNC(slaswp)"(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void slaswp(int *n, s *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_slaswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasy2 "BLAS_FUNC(slasy2)"(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) nogil
+cdef void slasy2(bint *ltranl, bint *ltranr, int *isgn, int *n1, int *n2, s *tl, int *ldtl, s *tr, int *ldtr, s *b, int *ldb, s *scale, s *x, int *ldx, s *xnorm, int *info) noexcept nogil:
+    
+    _fortran_slasy2(ltranl, ltranr, isgn, n1, n2, tl, ldtl, tr, ldtr, b, ldb, scale, x, ldx, xnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slasyf "BLAS_FUNC(slasyf)"(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) nogil
+cdef void slasyf(char *uplo, int *n, int *nb, int *kb, s *a, int *lda, int *ipiv, s *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_slasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatbs "BLAS_FUNC(slatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) nogil
+cdef void slatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, s *ab, int *ldab, s *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_slatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatdf "BLAS_FUNC(slatdf)"(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) nogil
+cdef void slatdf(int *ijob, int *n, s *z, int *ldz, s *rhs, s *rdsum, s *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_slatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatps "BLAS_FUNC(slatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) nogil
+cdef void slatps(char *uplo, char *trans, char *diag, char *normin, int *n, s *ap, s *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_slatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatrd "BLAS_FUNC(slatrd)"(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) nogil
+cdef void slatrd(char *uplo, int *n, int *nb, s *a, int *lda, s *e, s *tau, s *w, int *ldw) noexcept nogil:
+    
+    _fortran_slatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatrs "BLAS_FUNC(slatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) nogil
+cdef void slatrs(char *uplo, char *trans, char *diag, char *normin, int *n, s *a, int *lda, s *x, s *scale, s *cnorm, int *info) noexcept nogil:
+    
+    _fortran_slatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slatrz "BLAS_FUNC(slatrz)"(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) nogil
+cdef void slatrz(int *m, int *n, int *l, s *a, int *lda, s *tau, s *work) noexcept nogil:
+    
+    _fortran_slatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slauu2 "BLAS_FUNC(slauu2)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void slauu2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_slauum "BLAS_FUNC(slauum)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void slauum(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_slauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sopgtr "BLAS_FUNC(sopgtr)"(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) nogil
+cdef void sopgtr(char *uplo, int *n, s *ap, s *tau, s *q, int *ldq, s *work, int *info) noexcept nogil:
+    
+    _fortran_sopgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sopmtr "BLAS_FUNC(sopmtr)"(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sopmtr(char *side, char *uplo, char *trans, int *m, int *n, s *ap, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sopmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorbdb "BLAS_FUNC(sorbdb)"(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) nogil
+cdef void sorbdb(char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *phi, s *taup1, s *taup2, s *tauq1, s *tauq2, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorcsd "BLAS_FUNC(sorcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void sorcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, s *x11, int *ldx11, s *x12, int *ldx12, s *x21, int *ldx21, s *x22, int *ldx22, s *theta, s *u1, int *ldu1, s *u2, int *ldu2, s *v1t, int *ldv1t, s *v2t, int *ldv2t, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sorcsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorg2l "BLAS_FUNC(sorg2l)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorg2l(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorg2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorg2r "BLAS_FUNC(sorg2r)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorg2r(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorg2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgbr "BLAS_FUNC(sorgbr)"(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgbr(char *vect, int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorghr "BLAS_FUNC(sorghr)"(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorghr(int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgl2 "BLAS_FUNC(sorgl2)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorgl2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorgl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorglq "BLAS_FUNC(sorglq)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorglq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgql "BLAS_FUNC(sorgql)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgql(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgqr "BLAS_FUNC(sorgqr)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgqr(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgr2 "BLAS_FUNC(sorgr2)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) nogil
+cdef void sorgr2(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorgr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgrq "BLAS_FUNC(sorgrq)"(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgrq(int *m, int *n, int *k, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorgtr "BLAS_FUNC(sorgtr)"(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void sorgtr(char *uplo, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sorgtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorm2l "BLAS_FUNC(sorm2l)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sorm2l(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorm2r "BLAS_FUNC(sorm2r)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sorm2r(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormbr "BLAS_FUNC(sormbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormbr(char *vect, char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormhr "BLAS_FUNC(sormhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sorml2 "BLAS_FUNC(sorml2)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sorml2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sorml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormlq "BLAS_FUNC(sormlq)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormlq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormql "BLAS_FUNC(sormql)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormql(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormqr "BLAS_FUNC(sormqr)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormqr(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormr2 "BLAS_FUNC(sormr2)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sormr2(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sormr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormr3 "BLAS_FUNC(sormr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) nogil
+cdef void sormr3(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *info) noexcept nogil:
+    
+    _fortran_sormr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormrq "BLAS_FUNC(sormrq)"(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormrq(char *side, char *trans, int *m, int *n, int *k, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormrz "BLAS_FUNC(sormrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormrz(char *side, char *trans, int *m, int *n, int *k, int *l, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sormtr "BLAS_FUNC(sormtr)"(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) nogil
+cdef void sormtr(char *side, char *uplo, char *trans, int *m, int *n, s *a, int *lda, s *tau, s *c, int *ldc, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_sormtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbcon "BLAS_FUNC(spbcon)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void spbcon(char *uplo, int *n, int *kd, s *ab, int *ldab, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbequ "BLAS_FUNC(spbequ)"(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) nogil
+cdef void spbequ(char *uplo, int *n, int *kd, s *ab, int *ldab, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_spbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbrfs "BLAS_FUNC(spbrfs)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void spbrfs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbstf "BLAS_FUNC(spbstf)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil
+cdef void spbstf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_spbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbsv "BLAS_FUNC(spbsv)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil
+cdef void spbsv(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbsvx "BLAS_FUNC(spbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void spbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *afb, int *ldafb, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbtf2 "BLAS_FUNC(spbtf2)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil
+cdef void spbtf2(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_spbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbtrf "BLAS_FUNC(spbtrf)"(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) nogil
+cdef void spbtrf(char *uplo, int *n, int *kd, s *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_spbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spbtrs "BLAS_FUNC(spbtrs)"(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil
+cdef void spbtrs(char *uplo, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spftrf "BLAS_FUNC(spftrf)"(char *transr, char *uplo, int *n, s *a, int *info) nogil
+cdef void spftrf(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil:
+    
+    _fortran_spftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spftri "BLAS_FUNC(spftri)"(char *transr, char *uplo, int *n, s *a, int *info) nogil
+cdef void spftri(char *transr, char *uplo, int *n, s *a, int *info) noexcept nogil:
+    
+    _fortran_spftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spftrs "BLAS_FUNC(spftrs)"(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) nogil
+cdef void spftrs(char *transr, char *uplo, int *n, int *nrhs, s *a, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spocon "BLAS_FUNC(spocon)"(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void spocon(char *uplo, int *n, s *a, int *lda, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spocon(uplo, n, a, lda, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spoequ "BLAS_FUNC(spoequ)"(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void spoequ(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_spoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spoequb "BLAS_FUNC(spoequb)"(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) nogil
+cdef void spoequb(int *n, s *a, int *lda, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_spoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sporfs "BLAS_FUNC(sporfs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sporfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sposv "BLAS_FUNC(sposv)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void sposv(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sposvx "BLAS_FUNC(sposvx)"(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sposvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotf2 "BLAS_FUNC(spotf2)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void spotf2(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_spotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotrf "BLAS_FUNC(spotrf)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void spotrf(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_spotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotri "BLAS_FUNC(spotri)"(char *uplo, int *n, s *a, int *lda, int *info) nogil
+cdef void spotri(char *uplo, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_spotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spotrs "BLAS_FUNC(spotrs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void spotrs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppcon "BLAS_FUNC(sppcon)"(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sppcon(char *uplo, int *n, s *ap, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sppcon(uplo, n, ap, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppequ "BLAS_FUNC(sppequ)"(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) nogil
+cdef void sppequ(char *uplo, int *n, s *ap, s *s, s *scond, s *amax, int *info) noexcept nogil:
+    
+    _fortran_sppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spprfs "BLAS_FUNC(spprfs)"(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void spprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_spprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppsv "BLAS_FUNC(sppsv)"(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil
+cdef void sppsv(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sppsvx "BLAS_FUNC(sppsvx)"(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sppsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, char *equed, s *s, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spptrf "BLAS_FUNC(spptrf)"(char *uplo, int *n, s *ap, int *info) nogil
+cdef void spptrf(char *uplo, int *n, s *ap, int *info) noexcept nogil:
+    
+    _fortran_spptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spptri "BLAS_FUNC(spptri)"(char *uplo, int *n, s *ap, int *info) nogil
+cdef void spptri(char *uplo, int *n, s *ap, int *info) noexcept nogil:
+    
+    _fortran_spptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spptrs "BLAS_FUNC(spptrs)"(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil
+cdef void spptrs(char *uplo, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spstf2 "BLAS_FUNC(spstf2)"(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void spstf2(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_spstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spstrf "BLAS_FUNC(spstrf)"(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) nogil
+cdef void spstrf(char *uplo, int *n, s *a, int *lda, int *piv, int *rank, s *tol, s *work, int *info) noexcept nogil:
+    
+    _fortran_spstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptcon "BLAS_FUNC(sptcon)"(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) nogil
+cdef void sptcon(int *n, s *d, s *e, s *anorm, s *rcond, s *work, int *info) noexcept nogil:
+    
+    _fortran_sptcon(n, d, e, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spteqr "BLAS_FUNC(spteqr)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil
+cdef void spteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_spteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptrfs "BLAS_FUNC(sptrfs)"(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) nogil
+cdef void sptrfs(int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *info) noexcept nogil:
+    
+    _fortran_sptrfs(n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptsv "BLAS_FUNC(sptsv)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) nogil
+cdef void sptsv(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptsvx "BLAS_FUNC(sptsvx)"(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) nogil
+cdef void sptsvx(char *fact, int *n, int *nrhs, s *d, s *e, s *df, s *ef, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *info) noexcept nogil:
+    
+    _fortran_sptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spttrf "BLAS_FUNC(spttrf)"(int *n, s *d, s *e, int *info) nogil
+cdef void spttrf(int *n, s *d, s *e, int *info) noexcept nogil:
+    
+    _fortran_spttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_spttrs "BLAS_FUNC(spttrs)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) nogil
+cdef void spttrs(int *n, int *nrhs, s *d, s *e, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_spttrs(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sptts2 "BLAS_FUNC(sptts2)"(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) nogil
+cdef void sptts2(int *n, int *nrhs, s *d, s *e, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_sptts2(n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_srscl "BLAS_FUNC(srscl)"(int *n, s *sa, s *sx, int *incx) nogil
+cdef void srscl(int *n, s *sa, s *sx, int *incx) noexcept nogil:
+    
+    _fortran_srscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbev "BLAS_FUNC(ssbev)"(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) nogil
+cdef void ssbev(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbevd "BLAS_FUNC(ssbevd)"(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssbevd(char *jobz, char *uplo, int *n, int *kd, s *ab, int *ldab, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbevx "BLAS_FUNC(ssbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void ssbevx(char *jobz, char *range, char *uplo, int *n, int *kd, s *ab, int *ldab, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_ssbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgst "BLAS_FUNC(ssbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) nogil
+cdef void ssbgst(char *vect, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *x, int *ldx, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgv "BLAS_FUNC(ssbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) nogil
+cdef void ssbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgvd "BLAS_FUNC(ssbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbgvx "BLAS_FUNC(ssbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void ssbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, s *ab, int *ldab, s *bb, int *ldbb, s *q, int *ldq, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_ssbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssbtrd "BLAS_FUNC(ssbtrd)"(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) nogil
+cdef void ssbtrd(char *vect, char *uplo, int *n, int *kd, s *ab, int *ldab, s *d, s *e, s *q, int *ldq, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssfrk "BLAS_FUNC(ssfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) nogil
+cdef void ssfrk(char *transr, char *uplo, char *trans, int *n, int *k, s *alpha, s *a, int *lda, s *beta, s *c) noexcept nogil:
+    
+    _fortran_ssfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspcon "BLAS_FUNC(sspcon)"(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void sspcon(char *uplo, int *n, s *ap, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sspcon(uplo, n, ap, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspev "BLAS_FUNC(sspev)"(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) nogil
+cdef void sspev(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_sspev(jobz, uplo, n, ap, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspevd "BLAS_FUNC(sspevd)"(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sspevd(char *jobz, char *uplo, int *n, s *ap, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sspevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspevx "BLAS_FUNC(sspevx)"(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void sspevx(char *jobz, char *range, char *uplo, int *n, s *ap, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_sspevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgst "BLAS_FUNC(sspgst)"(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) nogil
+cdef void sspgst(int *itype, char *uplo, int *n, s *ap, s *bp, int *info) noexcept nogil:
+    
+    _fortran_sspgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgv "BLAS_FUNC(sspgv)"(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) nogil
+cdef void sspgv(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_sspgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgvd "BLAS_FUNC(sspgvd)"(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sspgvd(int *itype, char *jobz, char *uplo, int *n, s *ap, s *bp, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sspgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspgvx "BLAS_FUNC(sspgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void sspgvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *ap, s *bp, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_sspgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssprfs "BLAS_FUNC(ssprfs)"(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void ssprfs(char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ssprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspsv "BLAS_FUNC(sspsv)"(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void sspsv(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_sspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sspsvx "BLAS_FUNC(sspsvx)"(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void sspsvx(char *fact, char *uplo, int *n, int *nrhs, s *ap, s *afp, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptrd "BLAS_FUNC(ssptrd)"(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) nogil
+cdef void ssptrd(char *uplo, int *n, s *ap, s *d, s *e, s *tau, int *info) noexcept nogil:
+    
+    _fortran_ssptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptrf "BLAS_FUNC(ssptrf)"(char *uplo, int *n, s *ap, int *ipiv, int *info) nogil
+cdef void ssptrf(char *uplo, int *n, s *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_ssptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptri "BLAS_FUNC(ssptri)"(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) nogil
+cdef void ssptri(char *uplo, int *n, s *ap, int *ipiv, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssptrs "BLAS_FUNC(ssptrs)"(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void ssptrs(char *uplo, int *n, int *nrhs, s *ap, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstebz "BLAS_FUNC(sstebz)"(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) nogil
+cdef void sstebz(char *range, char *order, int *n, s *vl, s *vu, int *il, int *iu, s *abstol, s *d, s *e, int *m, int *nsplit, s *w, int *iblock, int *isplit, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_sstebz(range, order, n, vl, vu, il, iu, abstol, d, e, m, nsplit, w, iblock, isplit, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstedc "BLAS_FUNC(sstedc)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstedc(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstedc(compz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstegr "BLAS_FUNC(sstegr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstegr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstein "BLAS_FUNC(sstein)"(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void sstein(int *n, s *d, s *e, int *m, s *w, int *iblock, int *isplit, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_sstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstemr "BLAS_FUNC(sstemr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstemr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, int *m, s *w, s *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssteqr "BLAS_FUNC(ssteqr)"(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil
+cdef void ssteqr(char *compz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssterf "BLAS_FUNC(ssterf)"(int *n, s *d, s *e, int *info) nogil
+cdef void ssterf(int *n, s *d, s *e, int *info) noexcept nogil:
+    
+    _fortran_ssterf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstev "BLAS_FUNC(sstev)"(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) nogil
+cdef void sstev(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *info) noexcept nogil:
+    
+    _fortran_sstev(jobz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstevd "BLAS_FUNC(sstevd)"(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstevd(char *jobz, int *n, s *d, s *e, s *z, int *ldz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstevd(jobz, n, d, e, z, ldz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstevr "BLAS_FUNC(sstevr)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void sstevr(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_sstevr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_sstevx "BLAS_FUNC(sstevx)"(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) nogil
+cdef void sstevx(char *jobz, char *range, int *n, s *d, s *e, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_sstevx(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssycon "BLAS_FUNC(ssycon)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void ssycon(char *uplo, int *n, s *a, int *lda, int *ipiv, s *anorm, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ssycon(uplo, n, a, lda, ipiv, anorm, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyconv "BLAS_FUNC(ssyconv)"(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) nogil
+cdef void ssyconv(char *uplo, char *way, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyequb "BLAS_FUNC(ssyequb)"(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) nogil
+cdef void ssyequb(char *uplo, int *n, s *a, int *lda, s *s, s *scond, s *amax, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyev "BLAS_FUNC(ssyev)"(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) nogil
+cdef void ssyev(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssyev(jobz, uplo, n, a, lda, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyevd "BLAS_FUNC(ssyevd)"(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssyevd(char *jobz, char *uplo, int *n, s *a, int *lda, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssyevd(jobz, uplo, n, a, lda, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyevr "BLAS_FUNC(ssyevr)"(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssyevr(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, int *isuppz, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssyevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyevx "BLAS_FUNC(ssyevx)"(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) nogil
+cdef void ssyevx(char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_ssyevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygs2 "BLAS_FUNC(ssygs2)"(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void ssygs2(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssygs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygst "BLAS_FUNC(ssygst)"(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void ssygst(int *itype, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssygst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygv "BLAS_FUNC(ssygv)"(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) nogil
+cdef void ssygv(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssygv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygvd "BLAS_FUNC(ssygvd)"(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ssygvd(int *itype, char *jobz, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *w, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ssygvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssygvx "BLAS_FUNC(ssygvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) nogil
+cdef void ssygvx(int *itype, char *jobz, char *range, char *uplo, int *n, s *a, int *lda, s *b, int *ldb, s *vl, s *vu, int *il, int *iu, s *abstol, int *m, s *w, s *z, int *ldz, s *work, int *lwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_ssygvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyrfs "BLAS_FUNC(ssyrfs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void ssyrfs(char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ssyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssysv "BLAS_FUNC(ssysv)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) nogil
+cdef void ssysv(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssysvx "BLAS_FUNC(ssysvx)"(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void ssysvx(char *fact, char *uplo, int *n, int *nrhs, s *a, int *lda, s *af, int *ldaf, int *ipiv, s *b, int *ldb, s *x, int *ldx, s *rcond, s *ferr, s *berr, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ssysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssyswapr "BLAS_FUNC(ssyswapr)"(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) nogil
+cdef void ssyswapr(char *uplo, int *n, s *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_ssyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytd2 "BLAS_FUNC(ssytd2)"(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) nogil
+cdef void ssytd2(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, int *info) noexcept nogil:
+    
+    _fortran_ssytd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytf2 "BLAS_FUNC(ssytf2)"(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) nogil
+cdef void ssytf2(char *uplo, int *n, s *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_ssytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrd "BLAS_FUNC(ssytrd)"(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) nogil
+cdef void ssytrd(char *uplo, int *n, s *a, int *lda, s *d, s *e, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssytrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrf "BLAS_FUNC(ssytrf)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil
+cdef void ssytrf(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytri "BLAS_FUNC(ssytri)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) nogil
+cdef void ssytri(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytri2 "BLAS_FUNC(ssytri2)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) nogil
+cdef void ssytri2(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ssytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytri2x "BLAS_FUNC(ssytri2x)"(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) nogil
+cdef void ssytri2x(char *uplo, int *n, s *a, int *lda, int *ipiv, s *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_ssytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrs "BLAS_FUNC(ssytrs)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) nogil
+cdef void ssytrs(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ssytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ssytrs2 "BLAS_FUNC(ssytrs2)"(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) nogil
+cdef void ssytrs2(char *uplo, int *n, int *nrhs, s *a, int *lda, int *ipiv, s *b, int *ldb, s *work, int *info) noexcept nogil:
+    
+    _fortran_ssytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stbcon "BLAS_FUNC(stbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void stbcon(char *norm, char *uplo, char *diag, int *n, int *kd, s *ab, int *ldab, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stbrfs "BLAS_FUNC(stbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void stbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stbtrs "BLAS_FUNC(stbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) nogil
+cdef void stbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, s *ab, int *ldab, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_stbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stfsm "BLAS_FUNC(stfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) nogil
+cdef void stfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, s *alpha, s *a, s *b, int *ldb) noexcept nogil:
+    
+    _fortran_stfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stftri "BLAS_FUNC(stftri)"(char *transr, char *uplo, char *diag, int *n, s *a, int *info) nogil
+cdef void stftri(char *transr, char *uplo, char *diag, int *n, s *a, int *info) noexcept nogil:
+    
+    _fortran_stftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stfttp "BLAS_FUNC(stfttp)"(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) nogil
+cdef void stfttp(char *transr, char *uplo, int *n, s *arf, s *ap, int *info) noexcept nogil:
+    
+    _fortran_stfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stfttr "BLAS_FUNC(stfttr)"(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) nogil
+cdef void stfttr(char *transr, char *uplo, int *n, s *arf, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_stfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgevc "BLAS_FUNC(stgevc)"(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) nogil
+cdef void stgevc(char *side, char *howmny, bint *select, int *n, s *s, int *lds, s *p, int *ldp, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil:
+    
+    _fortran_stgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgex2 "BLAS_FUNC(stgex2)"(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) nogil
+cdef void stgex2(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *j1, int *n1, int *n2, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_stgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, n1, n2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgexc "BLAS_FUNC(stgexc)"(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) nogil
+cdef void stgexc(bint *wantq, bint *wantz, int *n, s *a, int *lda, s *b, int *ldb, s *q, int *ldq, s *z, int *ldz, int *ifst, int *ilst, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_stgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsen "BLAS_FUNC(stgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void stgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *alphar, s *alphai, s *beta, s *q, int *ldq, s *z, int *ldz, int *m, s *pl, s *pr, s *dif, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_stgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alphar, alphai, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsja "BLAS_FUNC(stgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) nogil
+cdef void stgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, s *a, int *lda, s *b, int *ldb, s *tola, s *tolb, s *alpha, s *beta, s *u, int *ldu, s *v, int *ldv, s *q, int *ldq, s *work, int *ncycle, int *info) noexcept nogil:
+    
+    _fortran_stgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsna "BLAS_FUNC(stgsna)"(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void stgsna(char *job, char *howmny, bint *select, int *n, s *a, int *lda, s *b, int *ldb, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *dif, int *mm, int *m, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsy2 "BLAS_FUNC(stgsy2)"(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) nogil
+cdef void stgsy2(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *rdsum, s *rdscal, int *iwork, int *pq, int *info) noexcept nogil:
+    
+    _fortran_stgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, iwork, pq, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stgsyl "BLAS_FUNC(stgsyl)"(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) nogil
+cdef void stgsyl(char *trans, int *ijob, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *d, int *ldd, s *e, int *lde, s *f, int *ldf, s *scale, s *dif, s *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpcon "BLAS_FUNC(stpcon)"(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void stpcon(char *norm, char *uplo, char *diag, int *n, s *ap, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stpcon(norm, uplo, diag, n, ap, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpmqrt "BLAS_FUNC(stpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) nogil
+cdef void stpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *info) noexcept nogil:
+    
+    _fortran_stpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpqrt "BLAS_FUNC(stpqrt)"(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) nogil
+cdef void stpqrt(int *m, int *n, int *l, int *nb, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, s *work, int *info) noexcept nogil:
+    
+    _fortran_stpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpqrt2 "BLAS_FUNC(stpqrt2)"(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) nogil
+cdef void stpqrt2(int *m, int *n, int *l, s *a, int *lda, s *b, int *ldb, s *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_stpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stprfb "BLAS_FUNC(stprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) nogil
+cdef void stprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, s *v, int *ldv, s *t, int *ldt, s *a, int *lda, s *b, int *ldb, s *work, int *ldwork) noexcept nogil:
+    
+    _fortran_stprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stprfs "BLAS_FUNC(stprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void stprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_stprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stptri "BLAS_FUNC(stptri)"(char *uplo, char *diag, int *n, s *ap, int *info) nogil
+cdef void stptri(char *uplo, char *diag, int *n, s *ap, int *info) noexcept nogil:
+    
+    _fortran_stptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stptrs "BLAS_FUNC(stptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) nogil
+cdef void stptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *ap, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_stptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpttf "BLAS_FUNC(stpttf)"(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) nogil
+cdef void stpttf(char *transr, char *uplo, int *n, s *ap, s *arf, int *info) noexcept nogil:
+    
+    _fortran_stpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stpttr "BLAS_FUNC(stpttr)"(char *uplo, int *n, s *ap, s *a, int *lda, int *info) nogil
+cdef void stpttr(char *uplo, int *n, s *ap, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_stpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strcon "BLAS_FUNC(strcon)"(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) nogil
+cdef void strcon(char *norm, char *uplo, char *diag, int *n, s *a, int *lda, s *rcond, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_strcon(norm, uplo, diag, n, a, lda, rcond, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strevc "BLAS_FUNC(strevc)"(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) nogil
+cdef void strevc(char *side, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, int *mm, int *m, s *work, int *info) noexcept nogil:
+    
+    _fortran_strevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strexc "BLAS_FUNC(strexc)"(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) nogil
+cdef void strexc(char *compq, int *n, s *t, int *ldt, s *q, int *ldq, int *ifst, int *ilst, s *work, int *info) noexcept nogil:
+    
+    _fortran_strexc(compq, n, t, ldt, q, ldq, ifst, ilst, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strrfs "BLAS_FUNC(strrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) nogil
+cdef void strrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, s *x, int *ldx, s *ferr, s *berr, s *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_strrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strsen "BLAS_FUNC(strsen)"(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void strsen(char *job, char *compq, bint *select, int *n, s *t, int *ldt, s *q, int *ldq, s *wr, s *wi, int *m, s *s, s *sep, s *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_strsen(job, compq, select, n, t, ldt, q, ldq, wr, wi, m, s, sep, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strsna "BLAS_FUNC(strsna)"(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) nogil
+cdef void strsna(char *job, char *howmny, bint *select, int *n, s *t, int *ldt, s *vl, int *ldvl, s *vr, int *ldvr, s *s, s *sep, int *mm, int *m, s *work, int *ldwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_strsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strsyl "BLAS_FUNC(strsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) nogil
+cdef void strsyl(char *trana, char *tranb, int *isgn, int *m, int *n, s *a, int *lda, s *b, int *ldb, s *c, int *ldc, s *scale, int *info) noexcept nogil:
+    
+    _fortran_strsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strti2 "BLAS_FUNC(strti2)"(char *uplo, char *diag, int *n, s *a, int *lda, int *info) nogil
+cdef void strti2(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_strti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strtri "BLAS_FUNC(strtri)"(char *uplo, char *diag, int *n, s *a, int *lda, int *info) nogil
+cdef void strtri(char *uplo, char *diag, int *n, s *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_strtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strtrs "BLAS_FUNC(strtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) nogil
+cdef void strtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, s *a, int *lda, s *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_strtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strttf "BLAS_FUNC(strttf)"(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) nogil
+cdef void strttf(char *transr, char *uplo, int *n, s *a, int *lda, s *arf, int *info) noexcept nogil:
+    
+    _fortran_strttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_strttp "BLAS_FUNC(strttp)"(char *uplo, int *n, s *a, int *lda, s *ap, int *info) nogil
+cdef void strttp(char *uplo, int *n, s *a, int *lda, s *ap, int *info) noexcept nogil:
+    
+    _fortran_strttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_stzrzf "BLAS_FUNC(stzrzf)"(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) nogil
+cdef void stzrzf(int *m, int *n, s *a, int *lda, s *tau, s *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_stzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_xerbla_array "BLAS_FUNC(xerbla_array)"(char *srname_array, int *srname_len, int *info) nogil
+cdef void xerbla_array(char *srname_array, int *srname_len, int *info) noexcept nogil:
+    
+    _fortran_xerbla_array(srname_array, srname_len, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zbbcsd "BLAS_FUNC(zbbcsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) nogil
+cdef void zbbcsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, int *m, int *p, int *q, d *theta, d *phi, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, d *b11d, d *b11e, d *b12d, d *b12e, d *b21d, d *b21e, d *b22d, d *b22e, d *rwork, int *lrwork, int *info) noexcept nogil:
+    
+    _fortran_zbbcsd(jobu1, jobu2, jobv1t, jobv2t, trans, m, p, q, theta, phi, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, b11d, b11e, b12d, b12e, b21d, b21e, b22d, b22e, rwork, lrwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zbdsqr "BLAS_FUNC(zbdsqr)"(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, npy_complex128 *vt, int *ldvt, npy_complex128 *u, int *ldu, npy_complex128 *c, int *ldc, d *rwork, int *info) nogil
+cdef void zbdsqr(char *uplo, int *n, int *ncvt, int *nru, int *ncc, d *d, d *e, z *vt, int *ldvt, z *u, int *ldu, z *c, int *ldc, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zbdsqr(uplo, n, ncvt, nru, ncc, d, e, vt, ldvt, u, ldu, c, ldc, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zcgesv "BLAS_FUNC(zcgesv)"(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, d *rwork, int *iter, int *info) nogil
+cdef void zcgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil:
+    
+    _fortran_zcgesv(n, nrhs, a, lda, ipiv, b, ldb, x, ldx, work, swork, rwork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zcposv "BLAS_FUNC(zcposv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, npy_complex128 *work, npy_complex64 *swork, d *rwork, int *iter, int *info) nogil
+cdef void zcposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, z *work, c *swork, d *rwork, int *iter, int *info) noexcept nogil:
+    
+    _fortran_zcposv(uplo, n, nrhs, a, lda, b, ldb, x, ldx, work, swork, rwork, iter, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zdrscl "BLAS_FUNC(zdrscl)"(int *n, d *sa, npy_complex128 *sx, int *incx) nogil
+cdef void zdrscl(int *n, d *sa, z *sx, int *incx) noexcept nogil:
+    
+    _fortran_zdrscl(n, sa, sx, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbbrd "BLAS_FUNC(zgbbrd)"(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *pt, int *ldpt, npy_complex128 *c, int *ldc, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgbbrd(char *vect, int *m, int *n, int *ncc, int *kl, int *ku, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *pt, int *ldpt, z *c, int *ldc, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgbbrd(vect, m, n, ncc, kl, ku, ab, ldab, d, e, q, ldq, pt, ldpt, c, ldc, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbcon "BLAS_FUNC(zgbcon)"(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgbcon(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgbcon(norm, n, kl, ku, ab, ldab, ipiv, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbequ "BLAS_FUNC(zgbequ)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void zgbequ(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zgbequ(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbequb "BLAS_FUNC(zgbequb)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void zgbequb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zgbequb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbrfs "BLAS_FUNC(zgbrfs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgbrfs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgbrfs(trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbsv "BLAS_FUNC(zgbsv)"(int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgbsv(int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgbsv(n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbsvx "BLAS_FUNC(zgbsvx)"(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgbsvx(char *fact, char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgbsvx(fact, trans, n, kl, ku, nrhs, ab, ldab, afb, ldafb, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbtf2 "BLAS_FUNC(zgbtf2)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void zgbtf2(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgbtf2(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbtrf "BLAS_FUNC(zgbtrf)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, int *ipiv, int *info) nogil
+cdef void zgbtrf(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgbtrf(m, n, kl, ku, ab, ldab, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgbtrs "BLAS_FUNC(zgbtrs)"(char *trans, int *n, int *kl, int *ku, int *nrhs, npy_complex128 *ab, int *ldab, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgbtrs(char *trans, int *n, int *kl, int *ku, int *nrhs, z *ab, int *ldab, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgbtrs(trans, n, kl, ku, nrhs, ab, ldab, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebak "BLAS_FUNC(zgebak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, npy_complex128 *v, int *ldv, int *info) nogil
+cdef void zgebak(char *job, char *side, int *n, int *ilo, int *ihi, d *scale, int *m, z *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_zgebak(job, side, n, ilo, ihi, scale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebal "BLAS_FUNC(zgebal)"(char *job, int *n, npy_complex128 *a, int *lda, int *ilo, int *ihi, d *scale, int *info) nogil
+cdef void zgebal(char *job, int *n, z *a, int *lda, int *ilo, int *ihi, d *scale, int *info) noexcept nogil:
+    
+    _fortran_zgebal(job, n, a, lda, ilo, ihi, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebd2 "BLAS_FUNC(zgebd2)"(int *m, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *info) nogil
+cdef void zgebd2(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgebd2(m, n, a, lda, d, e, tauq, taup, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgebrd "BLAS_FUNC(zgebrd)"(int *m, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgebrd(int *m, int *n, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgebrd(m, n, a, lda, d, e, tauq, taup, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgecon "BLAS_FUNC(zgecon)"(char *norm, int *n, npy_complex128 *a, int *lda, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgecon(char *norm, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgecon(norm, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeequ "BLAS_FUNC(zgeequ)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void zgeequ(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zgeequ(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeequb "BLAS_FUNC(zgeequb)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) nogil
+cdef void zgeequb(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zgeequb(m, n, a, lda, r, c, rowcnd, colcnd, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgees "BLAS_FUNC(zgees)"(char *jobvs, char *sort, _zselect1 *select, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) nogil
+cdef void zgees(char *jobvs, char *sort, zselect1 *select, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zgees(jobvs, sort, <_zselect1*>select, n, a, lda, sdim, w, vs, ldvs, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeesx "BLAS_FUNC(zgeesx)"(char *jobvs, char *sort, _zselect1 *select, char *sense, int *n, npy_complex128 *a, int *lda, int *sdim, npy_complex128 *w, npy_complex128 *vs, int *ldvs, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) nogil
+cdef void zgeesx(char *jobvs, char *sort, zselect1 *select, char *sense, int *n, z *a, int *lda, int *sdim, z *w, z *vs, int *ldvs, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zgeesx(jobvs, sort, <_zselect1*>select, sense, n, a, lda, sdim, w, vs, ldvs, rconde, rcondv, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeev "BLAS_FUNC(zgeev)"(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgeev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgeev(jobvl, jobvr, n, a, lda, w, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeevx "BLAS_FUNC(zgeevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgeevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *scale, d *abnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgeevx(balanc, jobvl, jobvr, sense, n, a, lda, w, vl, ldvl, vr, ldvr, ilo, ihi, scale, abnrm, rconde, rcondv, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgehd2 "BLAS_FUNC(zgehd2)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgehd2(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgehd2(n, ilo, ihi, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgehrd "BLAS_FUNC(zgehrd)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgehrd(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgehrd(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelq2 "BLAS_FUNC(zgelq2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgelq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgelq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelqf "BLAS_FUNC(zgelqf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgelqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgelqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgels "BLAS_FUNC(zgels)"(char *trans, int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgels(char *trans, int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgels(trans, m, n, nrhs, a, lda, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelsd "BLAS_FUNC(zgelsd)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *s, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *info) nogil
+cdef void zgelsd(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zgelsd(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelss "BLAS_FUNC(zgelss)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *s, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgelss(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, d *s, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgelss(m, n, nrhs, a, lda, b, ldb, s, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgelsy "BLAS_FUNC(zgelsy)"(int *m, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *jpvt, d *rcond, int *rank, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgelsy(int *m, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *jpvt, d *rcond, int *rank, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgelsy(m, n, nrhs, a, lda, b, ldb, jpvt, rcond, rank, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgemqrt "BLAS_FUNC(zgemqrt)"(char *side, char *trans, int *m, int *n, int *k, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zgemqrt(char *side, char *trans, int *m, int *n, int *k, int *nb, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgemqrt(side, trans, m, n, k, nb, v, ldv, t, ldt, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeql2 "BLAS_FUNC(zgeql2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgeql2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeql2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqlf "BLAS_FUNC(zgeqlf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgeqlf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqlf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqp3 "BLAS_FUNC(zgeqp3)"(int *m, int *n, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgeqp3(int *m, int *n, z *a, int *lda, int *jpvt, z *tau, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqp3(m, n, a, lda, jpvt, tau, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqr2 "BLAS_FUNC(zgeqr2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgeqr2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeqr2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqr2p "BLAS_FUNC(zgeqr2p)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgeqr2p(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeqr2p(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrf "BLAS_FUNC(zgeqrf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgeqrf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqrf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrfp "BLAS_FUNC(zgeqrfp)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgeqrfp(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgeqrfp(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrt "BLAS_FUNC(zgeqrt)"(int *m, int *n, int *nb, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info) nogil
+cdef void zgeqrt(int *m, int *n, int *nb, z *a, int *lda, z *t, int *ldt, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgeqrt(m, n, nb, a, lda, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrt2 "BLAS_FUNC(zgeqrt2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info) nogil
+cdef void zgeqrt2(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_zgeqrt2(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgeqrt3 "BLAS_FUNC(zgeqrt3)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *t, int *ldt, int *info) nogil
+cdef void zgeqrt3(int *m, int *n, z *a, int *lda, z *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_zgeqrt3(m, n, a, lda, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgerfs "BLAS_FUNC(zgerfs)"(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgerfs(char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgerfs(trans, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgerq2 "BLAS_FUNC(zgerq2)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zgerq2(int *m, int *n, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgerq2(m, n, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgerqf "BLAS_FUNC(zgerqf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgerqf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgerqf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesc2 "BLAS_FUNC(zgesc2)"(int *n, npy_complex128 *a, int *lda, npy_complex128 *rhs, int *ipiv, int *jpiv, d *scale) nogil
+cdef void zgesc2(int *n, z *a, int *lda, z *rhs, int *ipiv, int *jpiv, d *scale) noexcept nogil:
+    
+    _fortran_zgesc2(n, a, lda, rhs, ipiv, jpiv, scale)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesdd "BLAS_FUNC(zgesdd)"(char *jobz, int *m, int *n, npy_complex128 *a, int *lda, d *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *info) nogil
+cdef void zgesdd(char *jobz, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zgesdd(jobz, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesv "BLAS_FUNC(zgesv)"(int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgesv(int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgesv(n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesvd "BLAS_FUNC(zgesvd)"(char *jobu, char *jobvt, int *m, int *n, npy_complex128 *a, int *lda, d *s, npy_complex128 *u, int *ldu, npy_complex128 *vt, int *ldvt, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zgesvd(char *jobu, char *jobvt, int *m, int *n, z *a, int *lda, d *s, z *u, int *ldu, z *vt, int *ldvt, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgesvx "BLAS_FUNC(zgesvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgesvx(char *fact, char *trans, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, char *equed, d *r, d *c, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgesvx(fact, trans, n, nrhs, a, lda, af, ldaf, ipiv, equed, r, c, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetc2 "BLAS_FUNC(zgetc2)"(int *n, npy_complex128 *a, int *lda, int *ipiv, int *jpiv, int *info) nogil
+cdef void zgetc2(int *n, z *a, int *lda, int *ipiv, int *jpiv, int *info) noexcept nogil:
+    
+    _fortran_zgetc2(n, a, lda, ipiv, jpiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetf2 "BLAS_FUNC(zgetf2)"(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zgetf2(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgetf2(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetrf "BLAS_FUNC(zgetrf)"(int *m, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zgetrf(int *m, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgetrf(m, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetri "BLAS_FUNC(zgetri)"(int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgetri(int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgetri(n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgetrs "BLAS_FUNC(zgetrs)"(char *trans, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgetrs(char *trans, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgetrs(trans, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggbak "BLAS_FUNC(zggbak)"(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, npy_complex128 *v, int *ldv, int *info) nogil
+cdef void zggbak(char *job, char *side, int *n, int *ilo, int *ihi, d *lscale, d *rscale, int *m, z *v, int *ldv, int *info) noexcept nogil:
+    
+    _fortran_zggbak(job, side, n, ilo, ihi, lscale, rscale, m, v, ldv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggbal "BLAS_FUNC(zggbal)"(char *job, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) nogil
+cdef void zggbal(char *job, int *n, z *a, int *lda, z *b, int *ldb, int *ilo, int *ihi, d *lscale, d *rscale, d *work, int *info) noexcept nogil:
+    
+    _fortran_zggbal(job, n, a, lda, b, ldb, ilo, ihi, lscale, rscale, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgges "BLAS_FUNC(zgges)"(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, npy_complex128 *work, int *lwork, d *rwork, bint *bwork, int *info) nogil
+cdef void zgges(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, z *work, int *lwork, d *rwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zgges(jobvsl, jobvsr, sort, <_zselect2*>selctg, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, work, lwork, rwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggesx "BLAS_FUNC(zggesx)"(char *jobvsl, char *jobvsr, char *sort, _zselect2 *selctg, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *sdim, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vsl, int *ldvsl, npy_complex128 *vsr, int *ldvsr, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) nogil
+cdef void zggesx(char *jobvsl, char *jobvsr, char *sort, zselect2 *selctg, char *sense, int *n, z *a, int *lda, z *b, int *ldb, int *sdim, z *alpha, z *beta, z *vsl, int *ldvsl, z *vsr, int *ldvsr, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, int *liwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zggesx(jobvsl, jobvsr, sort, <_zselect2*>selctg, sense, n, a, lda, b, ldb, sdim, alpha, beta, vsl, ldvsl, vsr, ldvsr, rconde, rcondv, work, lwork, rwork, iwork, liwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggev "BLAS_FUNC(zggev)"(char *jobvl, char *jobvr, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zggev(char *jobvl, char *jobvr, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zggev(jobvl, jobvr, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggevx "BLAS_FUNC(zggevx)"(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, npy_complex128 *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) nogil
+cdef void zggevx(char *balanc, char *jobvl, char *jobvr, char *sense, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *vl, int *ldvl, z *vr, int *ldvr, int *ilo, int *ihi, d *lscale, d *rscale, d *abnrm, d *bbnrm, d *rconde, d *rcondv, z *work, int *lwork, d *rwork, int *iwork, bint *bwork, int *info) noexcept nogil:
+    
+    _fortran_zggevx(balanc, jobvl, jobvr, sense, n, a, lda, b, ldb, alpha, beta, vl, ldvl, vr, ldvr, ilo, ihi, lscale, rscale, abnrm, bbnrm, rconde, rcondv, work, lwork, rwork, iwork, bwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggglm "BLAS_FUNC(zggglm)"(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *d, npy_complex128 *x, npy_complex128 *y, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zggglm(int *n, int *m, int *p, z *a, int *lda, z *b, int *ldb, z *d, z *x, z *y, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zggglm(n, m, p, a, lda, b, ldb, d, x, y, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgghrd "BLAS_FUNC(zgghrd)"(char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *info) nogil
+cdef void zgghrd(char *compq, char *compz, int *n, int *ilo, int *ihi, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_zgghrd(compq, compz, n, ilo, ihi, a, lda, b, ldb, q, ldq, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgglse "BLAS_FUNC(zgglse)"(int *m, int *n, int *p, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, npy_complex128 *d, npy_complex128 *x, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zgglse(int *m, int *n, int *p, z *a, int *lda, z *b, int *ldb, z *c, z *d, z *x, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zgglse(m, n, p, a, lda, b, ldb, c, d, x, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggqrf "BLAS_FUNC(zggqrf)"(int *n, int *m, int *p, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zggqrf(int *n, int *m, int *p, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zggqrf(n, m, p, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zggrqf "BLAS_FUNC(zggrqf)"(int *m, int *p, int *n, npy_complex128 *a, int *lda, npy_complex128 *taua, npy_complex128 *b, int *ldb, npy_complex128 *taub, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zggrqf(int *m, int *p, int *n, z *a, int *lda, z *taua, z *b, int *ldb, z *taub, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zggrqf(m, p, n, a, lda, taua, b, ldb, taub, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtcon "BLAS_FUNC(zgtcon)"(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zgtcon(char *norm, int *n, z *dl, z *d, z *du, z *du2, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zgtcon(norm, n, dl, d, du, du2, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtrfs "BLAS_FUNC(zgtrfs)"(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgtrfs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgtrfs(trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtsv "BLAS_FUNC(zgtsv)"(int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgtsv(int *n, int *nrhs, z *dl, z *d, z *du, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgtsv(n, nrhs, dl, d, du, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtsvx "BLAS_FUNC(zgtsvx)"(char *fact, char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *dlf, npy_complex128 *df, npy_complex128 *duf, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zgtsvx(char *fact, char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *dlf, z *df, z *duf, z *du2, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zgtsvx(fact, trans, n, nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgttrf "BLAS_FUNC(zgttrf)"(int *n, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, int *info) nogil
+cdef void zgttrf(int *n, z *dl, z *d, z *du, z *du2, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zgttrf(n, dl, d, du, du2, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgttrs "BLAS_FUNC(zgttrs)"(char *trans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zgttrs(char *trans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zgttrs(trans, n, nrhs, dl, d, du, du2, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zgtts2 "BLAS_FUNC(zgtts2)"(int *itrans, int *n, int *nrhs, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *du2, int *ipiv, npy_complex128 *b, int *ldb) nogil
+cdef void zgtts2(int *itrans, int *n, int *nrhs, z *dl, z *d, z *du, z *du2, int *ipiv, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zgtts2(itrans, n, nrhs, dl, d, du, du2, ipiv, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbev "BLAS_FUNC(zhbev)"(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhbev(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhbev(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbevd "BLAS_FUNC(zhbevd)"(char *jobz, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhbevd(char *jobz, char *uplo, int *n, int *kd, z *ab, int *ldab, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhbevd(jobz, uplo, n, kd, ab, ldab, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbevx "BLAS_FUNC(zhbevx)"(char *jobz, char *range, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhbevx(char *jobz, char *range, char *uplo, int *n, int *kd, z *ab, int *ldab, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhbevx(jobz, range, uplo, n, kd, ab, ldab, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgst "BLAS_FUNC(zhbgst)"(char *vect, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *x, int *ldx, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhbgst(char *vect, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *x, int *ldx, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhbgst(vect, uplo, n, ka, kb, ab, ldab, bb, ldbb, x, ldx, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgv "BLAS_FUNC(zhbgv)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhbgv(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhbgv(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgvd "BLAS_FUNC(zhbgvd)"(char *jobz, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhbgvd(char *jobz, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhbgvd(jobz, uplo, n, ka, kb, ab, ldab, bb, ldbb, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbgvx "BLAS_FUNC(zhbgvx)"(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, npy_complex128 *ab, int *ldab, npy_complex128 *bb, int *ldbb, npy_complex128 *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhbgvx(char *jobz, char *range, char *uplo, int *n, int *ka, int *kb, z *ab, int *ldab, z *bb, int *ldbb, z *q, int *ldq, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhbgvx(jobz, range, uplo, n, ka, kb, ab, ldab, bb, ldbb, q, ldq, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhbtrd "BLAS_FUNC(zhbtrd)"(char *vect, char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info) nogil
+cdef void zhbtrd(char *vect, char *uplo, int *n, int *kd, z *ab, int *ldab, d *d, d *e, z *q, int *ldq, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhbtrd(vect, uplo, n, kd, ab, ldab, d, e, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhecon "BLAS_FUNC(zhecon)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zhecon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhecon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheequb "BLAS_FUNC(zheequb)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, npy_complex128 *work, int *info) nogil
+cdef void zheequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil:
+    
+    _fortran_zheequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheev "BLAS_FUNC(zheev)"(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, d *w, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zheev(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zheev(jobz, uplo, n, a, lda, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheevd "BLAS_FUNC(zheevd)"(char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, d *w, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zheevd(char *jobz, char *uplo, int *n, z *a, int *lda, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zheevd(jobz, uplo, n, a, lda, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheevr "BLAS_FUNC(zheevr)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, int *isuppz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zheevr(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zheevr(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheevx "BLAS_FUNC(zheevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zheevx(char *jobz, char *range, char *uplo, int *n, z *a, int *lda, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zheevx(jobz, range, uplo, n, a, lda, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegs2 "BLAS_FUNC(zhegs2)"(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhegs2(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhegs2(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegst "BLAS_FUNC(zhegst)"(int *itype, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhegst(int *itype, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhegst(itype, uplo, n, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegv "BLAS_FUNC(zhegv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *w, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zhegv(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhegv(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegvd "BLAS_FUNC(zhegvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *w, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhegvd(int *itype, char *jobz, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *w, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhegvd(itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhegvx "BLAS_FUNC(zhegvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhegvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *a, int *lda, z *b, int *ldb, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhegvx(itype, jobz, range, uplo, n, a, lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, ldz, work, lwork, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zherfs "BLAS_FUNC(zherfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zherfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zherfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhesv "BLAS_FUNC(zhesv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhesv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhesv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhesvx "BLAS_FUNC(zhesvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zhesvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhesvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zheswapr "BLAS_FUNC(zheswapr)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2) nogil
+cdef void zheswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_zheswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetd2 "BLAS_FUNC(zhetd2)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tau, int *info) nogil
+cdef void zhetd2(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, int *info) noexcept nogil:
+    
+    _fortran_zhetd2(uplo, n, a, lda, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetf2 "BLAS_FUNC(zhetf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zhetf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zhetf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrd "BLAS_FUNC(zhetrd)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhetrd(char *uplo, int *n, z *a, int *lda, d *d, d *e, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhetrd(uplo, n, a, lda, d, e, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrf "BLAS_FUNC(zhetrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhetrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhetrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetri "BLAS_FUNC(zhetri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zhetri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhetri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetri2 "BLAS_FUNC(zhetri2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhetri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhetri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetri2x "BLAS_FUNC(zhetri2x)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info) nogil
+cdef void zhetri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_zhetri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrs "BLAS_FUNC(zhetrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhetrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhetrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhetrs2 "BLAS_FUNC(zhetrs2)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) nogil
+cdef void zhetrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhetrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhfrk "BLAS_FUNC(zhfrk)"(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, npy_complex128 *a, int *lda, d *beta, npy_complex128 *c) nogil
+cdef void zhfrk(char *transr, char *uplo, char *trans, int *n, int *k, d *alpha, z *a, int *lda, d *beta, z *c) noexcept nogil:
+    
+    _fortran_zhfrk(transr, uplo, trans, n, k, alpha, a, lda, beta, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhgeqz "BLAS_FUNC(zhgeqz)"(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *t, int *ldt, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zhgeqz(char *job, char *compq, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *t, int *ldt, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhgeqz(job, compq, compz, n, ilo, ihi, h, ldh, t, ldt, alpha, beta, q, ldq, z, ldz, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpcon "BLAS_FUNC(zhpcon)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zhpcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhpcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpev "BLAS_FUNC(zhpev)"(char *jobz, char *uplo, int *n, npy_complex128 *ap, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhpev(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhpev(jobz, uplo, n, ap, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpevd "BLAS_FUNC(zhpevd)"(char *jobz, char *uplo, int *n, npy_complex128 *ap, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhpevd(char *jobz, char *uplo, int *n, z *ap, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhpevd(jobz, uplo, n, ap, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpevx "BLAS_FUNC(zhpevx)"(char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhpevx(char *jobz, char *range, char *uplo, int *n, z *ap, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhpevx(jobz, range, uplo, n, ap, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgst "BLAS_FUNC(zhpgst)"(int *itype, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, int *info) nogil
+cdef void zhpgst(int *itype, char *uplo, int *n, z *ap, z *bp, int *info) noexcept nogil:
+    
+    _fortran_zhpgst(itype, uplo, n, ap, bp, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgv "BLAS_FUNC(zhpgv)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhpgv(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhpgv(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgvd "BLAS_FUNC(zhpgvd)"(int *itype, char *jobz, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zhpgvd(int *itype, char *jobz, char *uplo, int *n, z *ap, z *bp, d *w, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zhpgvd(itype, jobz, uplo, n, ap, bp, w, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpgvx "BLAS_FUNC(zhpgvx)"(int *itype, char *jobz, char *range, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, npy_complex128 *work, d *rwork, int *iwork, int *ifail, int *info) nogil
+cdef void zhpgvx(int *itype, char *jobz, char *range, char *uplo, int *n, z *ap, z *bp, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, z *work, d *rwork, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zhpgvx(itype, jobz, range, uplo, n, ap, bp, vl, vu, il, iu, abstol, m, w, z, ldz, work, rwork, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhprfs "BLAS_FUNC(zhprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpsv "BLAS_FUNC(zhpsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhpsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhpsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhpsvx "BLAS_FUNC(zhpsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zhpsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zhpsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptrd "BLAS_FUNC(zhptrd)"(char *uplo, int *n, npy_complex128 *ap, d *d, d *e, npy_complex128 *tau, int *info) nogil
+cdef void zhptrd(char *uplo, int *n, z *ap, d *d, d *e, z *tau, int *info) noexcept nogil:
+    
+    _fortran_zhptrd(uplo, n, ap, d, e, tau, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptrf "BLAS_FUNC(zhptrf)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info) nogil
+cdef void zhptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zhptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptri "BLAS_FUNC(zhptri)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zhptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zhptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhptrs "BLAS_FUNC(zhptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zhptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zhptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhsein "BLAS_FUNC(zhsein)"(char *side, char *eigsrc, char *initv, bint *select, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *ifaill, int *ifailr, int *info) nogil
+cdef void zhsein(char *side, char *eigsrc, char *initv, bint *select, int *n, z *h, int *ldh, z *w, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *ifaill, int *ifailr, int *info) noexcept nogil:
+    
+    _fortran_zhsein(side, eigsrc, initv, select, n, h, ldh, w, vl, ldvl, vr, ldvr, mm, m, work, rwork, ifaill, ifailr, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zhseqr "BLAS_FUNC(zhseqr)"(char *job, char *compz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zhseqr(char *job, char *compz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zhseqr(job, compz, n, ilo, ihi, h, ldh, w, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlabrd "BLAS_FUNC(zlabrd)"(int *m, int *n, int *nb, npy_complex128 *a, int *lda, d *d, d *e, npy_complex128 *tauq, npy_complex128 *taup, npy_complex128 *x, int *ldx, npy_complex128 *y, int *ldy) nogil
+cdef void zlabrd(int *m, int *n, int *nb, z *a, int *lda, d *d, d *e, z *tauq, z *taup, z *x, int *ldx, z *y, int *ldy) noexcept nogil:
+    
+    _fortran_zlabrd(m, n, nb, a, lda, d, e, tauq, taup, x, ldx, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacgv "BLAS_FUNC(zlacgv)"(int *n, npy_complex128 *x, int *incx) nogil
+cdef void zlacgv(int *n, z *x, int *incx) noexcept nogil:
+    
+    _fortran_zlacgv(n, x, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacn2 "BLAS_FUNC(zlacn2)"(int *n, npy_complex128 *v, npy_complex128 *x, d *est, int *kase, int *isave) nogil
+cdef void zlacn2(int *n, z *v, z *x, d *est, int *kase, int *isave) noexcept nogil:
+    
+    _fortran_zlacn2(n, v, x, est, kase, isave)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacon "BLAS_FUNC(zlacon)"(int *n, npy_complex128 *v, npy_complex128 *x, d *est, int *kase) nogil
+cdef void zlacon(int *n, z *v, z *x, d *est, int *kase) noexcept nogil:
+    
+    _fortran_zlacon(n, v, x, est, kase)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacp2 "BLAS_FUNC(zlacp2)"(char *uplo, int *m, int *n, d *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void zlacp2(char *uplo, int *m, int *n, d *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zlacp2(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacpy "BLAS_FUNC(zlacpy)"(char *uplo, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb) nogil
+cdef void zlacpy(char *uplo, int *m, int *n, z *a, int *lda, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zlacpy(uplo, m, n, a, lda, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacrm "BLAS_FUNC(zlacrm)"(int *m, int *n, npy_complex128 *a, int *lda, d *b, int *ldb, npy_complex128 *c, int *ldc, d *rwork) nogil
+cdef void zlacrm(int *m, int *n, z *a, int *lda, d *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil:
+    
+    _fortran_zlacrm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlacrt "BLAS_FUNC(zlacrt)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, npy_complex128 *c, npy_complex128 *s) nogil
+cdef void zlacrt(int *n, z *cx, int *incx, z *cy, int *incy, z *c, z *s) noexcept nogil:
+    
+    _fortran_zlacrt(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zladiv "F_FUNC(zladivwrp,ZLADIVWRP)"(npy_complex128 *out, npy_complex128 *x, npy_complex128 *y) nogil
+cdef z zladiv(z *x, z *y) noexcept nogil:
+    cdef z out
+    _fortran_zladiv(&out, x, y)
+    return out
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaed0 "BLAS_FUNC(zlaed0)"(int *qsiz, int *n, d *d, d *e, npy_complex128 *q, int *ldq, npy_complex128 *qstore, int *ldqs, d *rwork, int *iwork, int *info) nogil
+cdef void zlaed0(int *qsiz, int *n, d *d, d *e, z *q, int *ldq, z *qstore, int *ldqs, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlaed0(qsiz, n, d, e, q, ldq, qstore, ldqs, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaed7 "BLAS_FUNC(zlaed7)"(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, npy_complex128 *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, npy_complex128 *work, d *rwork, int *iwork, int *info) nogil
+cdef void zlaed7(int *n, int *cutpnt, int *qsiz, int *tlvls, int *curlvl, int *curpbm, d *d, z *q, int *ldq, d *rho, int *indxq, d *qstore, int *qptr, int *prmptr, int *perm, int *givptr, int *givcol, d *givnum, z *work, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlaed7(n, cutpnt, qsiz, tlvls, curlvl, curpbm, d, q, ldq, rho, indxq, qstore, qptr, prmptr, perm, givptr, givcol, givnum, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaed8 "BLAS_FUNC(zlaed8)"(int *k, int *n, int *qsiz, npy_complex128 *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, npy_complex128 *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) nogil
+cdef void zlaed8(int *k, int *n, int *qsiz, z *q, int *ldq, d *d, d *rho, int *cutpnt, d *z, d *dlamda, z *q2, int *ldq2, d *w, int *indxp, int *indx, int *indxq, int *perm, int *givptr, int *givcol, d *givnum, int *info) noexcept nogil:
+    
+    _fortran_zlaed8(k, n, qsiz, q, ldq, d, rho, cutpnt, z, dlamda, q2, ldq2, w, indxp, indx, indxq, perm, givptr, givcol, givnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaein "BLAS_FUNC(zlaein)"(bint *rightv, bint *noinit, int *n, npy_complex128 *h, int *ldh, npy_complex128 *w, npy_complex128 *v, npy_complex128 *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) nogil
+cdef void zlaein(bint *rightv, bint *noinit, int *n, z *h, int *ldh, z *w, z *v, z *b, int *ldb, d *rwork, d *eps3, d *smlnum, int *info) noexcept nogil:
+    
+    _fortran_zlaein(rightv, noinit, n, h, ldh, w, v, b, ldb, rwork, eps3, smlnum, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaesy "BLAS_FUNC(zlaesy)"(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, npy_complex128 *rt1, npy_complex128 *rt2, npy_complex128 *evscal, npy_complex128 *cs1, npy_complex128 *sn1) nogil
+cdef void zlaesy(z *a, z *b, z *c, z *rt1, z *rt2, z *evscal, z *cs1, z *sn1) noexcept nogil:
+    
+    _fortran_zlaesy(a, b, c, rt1, rt2, evscal, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaev2 "BLAS_FUNC(zlaev2)"(npy_complex128 *a, npy_complex128 *b, npy_complex128 *c, d *rt1, d *rt2, d *cs1, npy_complex128 *sn1) nogil
+cdef void zlaev2(z *a, z *b, z *c, d *rt1, d *rt2, d *cs1, z *sn1) noexcept nogil:
+    
+    _fortran_zlaev2(a, b, c, rt1, rt2, cs1, sn1)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlag2c "BLAS_FUNC(zlag2c)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info) nogil
+cdef void zlag2c(int *m, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_zlag2c(m, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlags2 "BLAS_FUNC(zlags2)"(bint *upper, d *a1, npy_complex128 *a2, d *a3, d *b1, npy_complex128 *b2, d *b3, d *csu, npy_complex128 *snu, d *csv, npy_complex128 *snv, d *csq, npy_complex128 *snq) nogil
+cdef void zlags2(bint *upper, d *a1, z *a2, d *a3, d *b1, z *b2, d *b3, d *csu, z *snu, d *csv, z *snv, d *csq, z *snq) noexcept nogil:
+    
+    _fortran_zlags2(upper, a1, a2, a3, b1, b2, b3, csu, snu, csv, snv, csq, snq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlagtm "BLAS_FUNC(zlagtm)"(char *trans, int *n, int *nrhs, d *alpha, npy_complex128 *dl, npy_complex128 *d, npy_complex128 *du, npy_complex128 *x, int *ldx, d *beta, npy_complex128 *b, int *ldb) nogil
+cdef void zlagtm(char *trans, int *n, int *nrhs, d *alpha, z *dl, z *d, z *du, z *x, int *ldx, d *beta, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zlagtm(trans, n, nrhs, alpha, dl, d, du, x, ldx, beta, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlahef "BLAS_FUNC(zlahef)"(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info) nogil
+cdef void zlahef(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_zlahef(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlahqr "BLAS_FUNC(zlahqr)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *info) nogil
+cdef void zlahqr(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, int *info) noexcept nogil:
+    
+    _fortran_zlahqr(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlahr2 "BLAS_FUNC(zlahr2)"(int *n, int *k, int *nb, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *t, int *ldt, npy_complex128 *y, int *ldy) nogil
+cdef void zlahr2(int *n, int *k, int *nb, z *a, int *lda, z *tau, z *t, int *ldt, z *y, int *ldy) noexcept nogil:
+    
+    _fortran_zlahr2(n, k, nb, a, lda, tau, t, ldt, y, ldy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaic1 "BLAS_FUNC(zlaic1)"(int *job, int *j, npy_complex128 *x, d *sest, npy_complex128 *w, npy_complex128 *gamma, d *sestpr, npy_complex128 *s, npy_complex128 *c) nogil
+cdef void zlaic1(int *job, int *j, z *x, d *sest, z *w, z *gamma, d *sestpr, z *s, z *c) noexcept nogil:
+    
+    _fortran_zlaic1(job, j, x, sest, w, gamma, sestpr, s, c)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlals0 "BLAS_FUNC(zlals0)"(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) nogil
+cdef void zlals0(int *icompq, int *nl, int *nr, int *sqre, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, int *perm, int *givptr, int *givcol, int *ldgcol, d *givnum, int *ldgnum, d *poles, d *difl, d *difr, d *z, int *k, d *c, d *s, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zlals0(icompq, nl, nr, sqre, nrhs, b, ldb, bx, ldbx, perm, givptr, givcol, ldgcol, givnum, ldgnum, poles, difl, difr, z, k, c, s, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlalsa "BLAS_FUNC(zlalsa)"(int *icompq, int *smlsiz, int *n, int *nrhs, npy_complex128 *b, int *ldb, npy_complex128 *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) nogil
+cdef void zlalsa(int *icompq, int *smlsiz, int *n, int *nrhs, z *b, int *ldb, z *bx, int *ldbx, d *u, int *ldu, d *vt, int *k, d *difl, d *difr, d *z, d *poles, int *givptr, int *givcol, int *ldgcol, int *perm, d *givnum, d *c, d *s, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlalsa(icompq, smlsiz, n, nrhs, b, ldb, bx, ldbx, u, ldu, vt, k, difl, difr, z, poles, givptr, givcol, ldgcol, perm, givnum, c, s, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlalsd "BLAS_FUNC(zlalsd)"(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, npy_complex128 *b, int *ldb, d *rcond, int *rank, npy_complex128 *work, d *rwork, int *iwork, int *info) nogil
+cdef void zlalsd(char *uplo, int *smlsiz, int *n, int *nrhs, d *d, d *e, z *b, int *ldb, d *rcond, int *rank, z *work, d *rwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlalsd(uplo, smlsiz, n, nrhs, d, e, b, ldb, rcond, rank, work, rwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlangb "BLAS_FUNC(zlangb)"(char *norm, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlangb(char *norm, int *n, int *kl, int *ku, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlangb(norm, n, kl, ku, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlange "BLAS_FUNC(zlange)"(char *norm, int *m, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlange(char *norm, int *m, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlange(norm, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlangt "BLAS_FUNC(zlangt)"(char *norm, int *n, npy_complex128 *dl, npy_complex128 *d_, npy_complex128 *du) nogil
+cdef d zlangt(char *norm, int *n, z *dl, z *d_, z *du) noexcept nogil:
+    
+    return _fortran_zlangt(norm, n, dl, d_, du)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhb "BLAS_FUNC(zlanhb)"(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlanhb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlanhb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhe "BLAS_FUNC(zlanhe)"(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlanhe(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlanhe(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhf "BLAS_FUNC(zlanhf)"(char *norm, char *transr, char *uplo, int *n, npy_complex128 *a, d *work) nogil
+cdef d zlanhf(char *norm, char *transr, char *uplo, int *n, z *a, d *work) noexcept nogil:
+    
+    return _fortran_zlanhf(norm, transr, uplo, n, a, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhp "BLAS_FUNC(zlanhp)"(char *norm, char *uplo, int *n, npy_complex128 *ap, d *work) nogil
+cdef d zlanhp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil:
+    
+    return _fortran_zlanhp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanhs "BLAS_FUNC(zlanhs)"(char *norm, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlanhs(char *norm, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlanhs(norm, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlanht "BLAS_FUNC(zlanht)"(char *norm, int *n, d *d_, npy_complex128 *e) nogil
+cdef d zlanht(char *norm, int *n, d *d_, z *e) noexcept nogil:
+    
+    return _fortran_zlanht(norm, n, d_, e)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlansb "BLAS_FUNC(zlansb)"(char *norm, char *uplo, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlansb(char *norm, char *uplo, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlansb(norm, uplo, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlansp "BLAS_FUNC(zlansp)"(char *norm, char *uplo, int *n, npy_complex128 *ap, d *work) nogil
+cdef d zlansp(char *norm, char *uplo, int *n, z *ap, d *work) noexcept nogil:
+    
+    return _fortran_zlansp(norm, uplo, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlansy "BLAS_FUNC(zlansy)"(char *norm, char *uplo, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlansy(char *norm, char *uplo, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlansy(norm, uplo, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlantb "BLAS_FUNC(zlantb)"(char *norm, char *uplo, char *diag, int *n, int *k, npy_complex128 *ab, int *ldab, d *work) nogil
+cdef d zlantb(char *norm, char *uplo, char *diag, int *n, int *k, z *ab, int *ldab, d *work) noexcept nogil:
+    
+    return _fortran_zlantb(norm, uplo, diag, n, k, ab, ldab, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlantp "BLAS_FUNC(zlantp)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, d *work) nogil
+cdef d zlantp(char *norm, char *uplo, char *diag, int *n, z *ap, d *work) noexcept nogil:
+    
+    return _fortran_zlantp(norm, uplo, diag, n, ap, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    d _fortran_zlantr "BLAS_FUNC(zlantr)"(char *norm, char *uplo, char *diag, int *m, int *n, npy_complex128 *a, int *lda, d *work) nogil
+cdef d zlantr(char *norm, char *uplo, char *diag, int *m, int *n, z *a, int *lda, d *work) noexcept nogil:
+    
+    return _fortran_zlantr(norm, uplo, diag, m, n, a, lda, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlapll "BLAS_FUNC(zlapll)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *ssmin) nogil
+cdef void zlapll(int *n, z *x, int *incx, z *y, int *incy, d *ssmin) noexcept nogil:
+    
+    _fortran_zlapll(n, x, incx, y, incy, ssmin)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlapmr "BLAS_FUNC(zlapmr)"(bint *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k) nogil
+cdef void zlapmr(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_zlapmr(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlapmt "BLAS_FUNC(zlapmt)"(bint *forwrd, int *m, int *n, npy_complex128 *x, int *ldx, int *k) nogil
+cdef void zlapmt(bint *forwrd, int *m, int *n, z *x, int *ldx, int *k) noexcept nogil:
+    
+    _fortran_zlapmt(forwrd, m, n, x, ldx, k)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqgb "BLAS_FUNC(zlaqgb)"(int *m, int *n, int *kl, int *ku, npy_complex128 *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil
+cdef void zlaqgb(int *m, int *n, int *kl, int *ku, z *ab, int *ldab, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqgb(m, n, kl, ku, ab, ldab, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqge "BLAS_FUNC(zlaqge)"(int *m, int *n, npy_complex128 *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) nogil
+cdef void zlaqge(int *m, int *n, z *a, int *lda, d *r, d *c, d *rowcnd, d *colcnd, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqge(m, n, a, lda, r, c, rowcnd, colcnd, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqhb "BLAS_FUNC(zlaqhb)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqhb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqhb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqhe "BLAS_FUNC(zlaqhe)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqhe(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqhe(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqhp "BLAS_FUNC(zlaqhp)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqhp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqhp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqp2 "BLAS_FUNC(zlaqp2)"(int *m, int *n, int *offset, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, d *vn1, d *vn2, npy_complex128 *work) nogil
+cdef void zlaqp2(int *m, int *n, int *offset, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *work) noexcept nogil:
+    
+    _fortran_zlaqp2(m, n, offset, a, lda, jpvt, tau, vn1, vn2, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqps "BLAS_FUNC(zlaqps)"(int *m, int *n, int *offset, int *nb, int *kb, npy_complex128 *a, int *lda, int *jpvt, npy_complex128 *tau, d *vn1, d *vn2, npy_complex128 *auxv, npy_complex128 *f, int *ldf) nogil
+cdef void zlaqps(int *m, int *n, int *offset, int *nb, int *kb, z *a, int *lda, int *jpvt, z *tau, d *vn1, d *vn2, z *auxv, z *f, int *ldf) noexcept nogil:
+    
+    _fortran_zlaqps(m, n, offset, nb, kb, a, lda, jpvt, tau, vn1, vn2, auxv, f, ldf)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr0 "BLAS_FUNC(zlaqr0)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zlaqr0(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zlaqr0(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr1 "BLAS_FUNC(zlaqr1)"(int *n, npy_complex128 *h, int *ldh, npy_complex128 *s1, npy_complex128 *s2, npy_complex128 *v) nogil
+cdef void zlaqr1(int *n, z *h, int *ldh, z *s1, z *s2, z *v) noexcept nogil:
+    
+    _fortran_zlaqr1(n, h, ldh, s1, s2, v)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr2 "BLAS_FUNC(zlaqr2)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork) nogil
+cdef void zlaqr2(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil:
+    
+    _fortran_zlaqr2(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr3 "BLAS_FUNC(zlaqr3)"(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, int *ns, int *nd, npy_complex128 *sh, npy_complex128 *v, int *ldv, int *nh, npy_complex128 *t, int *ldt, int *nv, npy_complex128 *wv, int *ldwv, npy_complex128 *work, int *lwork) nogil
+cdef void zlaqr3(bint *wantt, bint *wantz, int *n, int *ktop, int *kbot, int *nw, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, int *ns, int *nd, z *sh, z *v, int *ldv, int *nh, z *t, int *ldt, int *nv, z *wv, int *ldwv, z *work, int *lwork) noexcept nogil:
+    
+    _fortran_zlaqr3(wantt, wantz, n, ktop, kbot, nw, h, ldh, iloz, ihiz, z, ldz, ns, nd, sh, v, ldv, nh, t, ldt, nv, wv, ldwv, work, lwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr4 "BLAS_FUNC(zlaqr4)"(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, npy_complex128 *h, int *ldh, npy_complex128 *w, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zlaqr4(bint *wantt, bint *wantz, int *n, int *ilo, int *ihi, z *h, int *ldh, z *w, int *iloz, int *ihiz, z *z, int *ldz, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zlaqr4(wantt, wantz, n, ilo, ihi, h, ldh, w, iloz, ihiz, z, ldz, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqr5 "BLAS_FUNC(zlaqr5)"(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, npy_complex128 *s, npy_complex128 *h, int *ldh, int *iloz, int *ihiz, npy_complex128 *z, int *ldz, npy_complex128 *v, int *ldv, npy_complex128 *u, int *ldu, int *nv, npy_complex128 *wv, int *ldwv, int *nh, npy_complex128 *wh, int *ldwh) nogil
+cdef void zlaqr5(bint *wantt, bint *wantz, int *kacc22, int *n, int *ktop, int *kbot, int *nshfts, z *s, z *h, int *ldh, int *iloz, int *ihiz, z *z, int *ldz, z *v, int *ldv, z *u, int *ldu, int *nv, z *wv, int *ldwv, int *nh, z *wh, int *ldwh) noexcept nogil:
+    
+    _fortran_zlaqr5(wantt, wantz, kacc22, n, ktop, kbot, nshfts, s, h, ldh, iloz, ihiz, z, ldz, v, ldv, u, ldu, nv, wv, ldwv, nh, wh, ldwh)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqsb "BLAS_FUNC(zlaqsb)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqsb(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqsb(uplo, n, kd, ab, ldab, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqsp "BLAS_FUNC(zlaqsp)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqsp(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqsp(uplo, n, ap, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaqsy "BLAS_FUNC(zlaqsy)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, char *equed) nogil
+cdef void zlaqsy(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, char *equed) noexcept nogil:
+    
+    _fortran_zlaqsy(uplo, n, a, lda, s, scond, amax, equed)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlar1v "BLAS_FUNC(zlar1v)"(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, npy_complex128 *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) nogil
+cdef void zlar1v(int *n, int *b1, int *bn, d *lambda_, d *d, d *l, d *ld, d *lld, d *pivmin, d *gaptol, z *z, bint *wantnc, int *negcnt, d *ztz, d *mingma, int *r, int *isuppz, d *nrminv, d *resid, d *rqcorr, d *work) noexcept nogil:
+    
+    _fortran_zlar1v(n, b1, bn, lambda_, d, l, ld, lld, pivmin, gaptol, z, wantnc, negcnt, ztz, mingma, r, isuppz, nrminv, resid, rqcorr, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlar2v "BLAS_FUNC(zlar2v)"(int *n, npy_complex128 *x, npy_complex128 *y, npy_complex128 *z, int *incx, d *c, npy_complex128 *s, int *incc) nogil
+cdef void zlar2v(int *n, z *x, z *y, z *z, int *incx, d *c, z *s, int *incc) noexcept nogil:
+    
+    _fortran_zlar2v(n, x, y, z, incx, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarcm "BLAS_FUNC(zlarcm)"(int *m, int *n, d *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, d *rwork) nogil
+cdef void zlarcm(int *m, int *n, d *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *rwork) noexcept nogil:
+    
+    _fortran_zlarcm(m, n, a, lda, b, ldb, c, ldc, rwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarf "BLAS_FUNC(zlarf)"(char *side, int *m, int *n, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil
+cdef void zlarf(char *side, int *m, int *n, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil:
+    
+    _fortran_zlarf(side, m, n, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfb "BLAS_FUNC(zlarfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork) nogil
+cdef void zlarfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil:
+    
+    _fortran_zlarfb(side, trans, direct, storev, m, n, k, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfg "BLAS_FUNC(zlarfg)"(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau) nogil
+cdef void zlarfg(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil:
+    
+    _fortran_zlarfg(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfgp "BLAS_FUNC(zlarfgp)"(int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *tau) nogil
+cdef void zlarfgp(int *n, z *alpha, z *x, int *incx, z *tau) noexcept nogil:
+    
+    _fortran_zlarfgp(n, alpha, x, incx, tau)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarft "BLAS_FUNC(zlarft)"(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt) nogil
+cdef void zlarft(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil:
+    
+    _fortran_zlarft(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarfx "BLAS_FUNC(zlarfx)"(char *side, int *m, int *n, npy_complex128 *v, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil
+cdef void zlarfx(char *side, int *m, int *n, z *v, z *tau, z *c, int *ldc, z *work) noexcept nogil:
+    
+    _fortran_zlarfx(side, m, n, v, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlargv "BLAS_FUNC(zlargv)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *c, int *incc) nogil
+cdef void zlargv(int *n, z *x, int *incx, z *y, int *incy, d *c, int *incc) noexcept nogil:
+    
+    _fortran_zlargv(n, x, incx, y, incy, c, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarnv "BLAS_FUNC(zlarnv)"(int *idist, int *iseed, int *n, npy_complex128 *x) nogil
+cdef void zlarnv(int *idist, int *iseed, int *n, z *x) noexcept nogil:
+    
+    _fortran_zlarnv(idist, iseed, n, x)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarrv "BLAS_FUNC(zlarrv)"(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, npy_complex128 *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) nogil
+cdef void zlarrv(int *n, d *vl, d *vu, d *d, d *l, d *pivmin, int *isplit, int *m, int *dol, int *dou, d *minrgp, d *rtol1, d *rtol2, d *w, d *werr, d *wgap, int *iblock, int *indexw, d *gers, z *z, int *ldz, int *isuppz, d *work, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zlarrv(n, vl, vu, d, l, pivmin, isplit, m, dol, dou, minrgp, rtol1, rtol2, w, werr, wgap, iblock, indexw, gers, z, ldz, isuppz, work, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlartg "BLAS_FUNC(zlartg)"(npy_complex128 *f, npy_complex128 *g, d *cs, npy_complex128 *sn, npy_complex128 *r) nogil
+cdef void zlartg(z *f, z *g, d *cs, z *sn, z *r) noexcept nogil:
+    
+    _fortran_zlartg(f, g, cs, sn, r)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlartv "BLAS_FUNC(zlartv)"(int *n, npy_complex128 *x, int *incx, npy_complex128 *y, int *incy, d *c, npy_complex128 *s, int *incc) nogil
+cdef void zlartv(int *n, z *x, int *incx, z *y, int *incy, d *c, z *s, int *incc) noexcept nogil:
+    
+    _fortran_zlartv(n, x, incx, y, incy, c, s, incc)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarz "BLAS_FUNC(zlarz)"(char *side, int *m, int *n, int *l, npy_complex128 *v, int *incv, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work) nogil
+cdef void zlarz(char *side, int *m, int *n, int *l, z *v, int *incv, z *tau, z *c, int *ldc, z *work) noexcept nogil:
+    
+    _fortran_zlarz(side, m, n, l, v, incv, tau, c, ldc, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarzb "BLAS_FUNC(zlarzb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *c, int *ldc, npy_complex128 *work, int *ldwork) nogil
+cdef void zlarzb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *c, int *ldc, z *work, int *ldwork) noexcept nogil:
+    
+    _fortran_zlarzb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, c, ldc, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlarzt "BLAS_FUNC(zlarzt)"(char *direct, char *storev, int *n, int *k, npy_complex128 *v, int *ldv, npy_complex128 *tau, npy_complex128 *t, int *ldt) nogil
+cdef void zlarzt(char *direct, char *storev, int *n, int *k, z *v, int *ldv, z *tau, z *t, int *ldt) noexcept nogil:
+    
+    _fortran_zlarzt(direct, storev, n, k, v, ldv, tau, t, ldt)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlascl "BLAS_FUNC(zlascl)"(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zlascl(char *type_bn, int *kl, int *ku, d *cfrom, d *cto, int *m, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zlascl(type_bn, kl, ku, cfrom, cto, m, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaset "BLAS_FUNC(zlaset)"(char *uplo, int *m, int *n, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *a, int *lda) nogil
+cdef void zlaset(char *uplo, int *m, int *n, z *alpha, z *beta, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zlaset(uplo, m, n, alpha, beta, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlasr "BLAS_FUNC(zlasr)"(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, npy_complex128 *a, int *lda) nogil
+cdef void zlasr(char *side, char *pivot, char *direct, int *m, int *n, d *c, d *s, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zlasr(side, pivot, direct, m, n, c, s, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlassq "BLAS_FUNC(zlassq)"(int *n, npy_complex128 *x, int *incx, d *scale, d *sumsq) nogil
+cdef void zlassq(int *n, z *x, int *incx, d *scale, d *sumsq) noexcept nogil:
+    
+    _fortran_zlassq(n, x, incx, scale, sumsq)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlaswp "BLAS_FUNC(zlaswp)"(int *n, npy_complex128 *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) nogil
+cdef void zlaswp(int *n, z *a, int *lda, int *k1, int *k2, int *ipiv, int *incx) noexcept nogil:
+    
+    _fortran_zlaswp(n, a, lda, k1, k2, ipiv, incx)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlasyf "BLAS_FUNC(zlasyf)"(char *uplo, int *n, int *nb, int *kb, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *w, int *ldw, int *info) nogil
+cdef void zlasyf(char *uplo, int *n, int *nb, int *kb, z *a, int *lda, int *ipiv, z *w, int *ldw, int *info) noexcept nogil:
+    
+    _fortran_zlasyf(uplo, n, nb, kb, a, lda, ipiv, w, ldw, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlat2c "BLAS_FUNC(zlat2c)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex64 *sa, int *ldsa, int *info) nogil
+cdef void zlat2c(char *uplo, int *n, z *a, int *lda, c *sa, int *ldsa, int *info) noexcept nogil:
+    
+    _fortran_zlat2c(uplo, n, a, lda, sa, ldsa, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatbs "BLAS_FUNC(zlatbs)"(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, npy_complex128 *ab, int *ldab, npy_complex128 *x, d *scale, d *cnorm, int *info) nogil
+cdef void zlatbs(char *uplo, char *trans, char *diag, char *normin, int *n, int *kd, z *ab, int *ldab, z *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_zlatbs(uplo, trans, diag, normin, n, kd, ab, ldab, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatdf "BLAS_FUNC(zlatdf)"(int *ijob, int *n, npy_complex128 *z, int *ldz, npy_complex128 *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) nogil
+cdef void zlatdf(int *ijob, int *n, z *z, int *ldz, z *rhs, d *rdsum, d *rdscal, int *ipiv, int *jpiv) noexcept nogil:
+    
+    _fortran_zlatdf(ijob, n, z, ldz, rhs, rdsum, rdscal, ipiv, jpiv)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatps "BLAS_FUNC(zlatps)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *ap, npy_complex128 *x, d *scale, d *cnorm, int *info) nogil
+cdef void zlatps(char *uplo, char *trans, char *diag, char *normin, int *n, z *ap, z *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_zlatps(uplo, trans, diag, normin, n, ap, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatrd "BLAS_FUNC(zlatrd)"(char *uplo, int *n, int *nb, npy_complex128 *a, int *lda, d *e, npy_complex128 *tau, npy_complex128 *w, int *ldw) nogil
+cdef void zlatrd(char *uplo, int *n, int *nb, z *a, int *lda, d *e, z *tau, z *w, int *ldw) noexcept nogil:
+    
+    _fortran_zlatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatrs "BLAS_FUNC(zlatrs)"(char *uplo, char *trans, char *diag, char *normin, int *n, npy_complex128 *a, int *lda, npy_complex128 *x, d *scale, d *cnorm, int *info) nogil
+cdef void zlatrs(char *uplo, char *trans, char *diag, char *normin, int *n, z *a, int *lda, z *x, d *scale, d *cnorm, int *info) noexcept nogil:
+    
+    _fortran_zlatrs(uplo, trans, diag, normin, n, a, lda, x, scale, cnorm, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlatrz "BLAS_FUNC(zlatrz)"(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work) nogil
+cdef void zlatrz(int *m, int *n, int *l, z *a, int *lda, z *tau, z *work) noexcept nogil:
+    
+    _fortran_zlatrz(m, n, l, a, lda, tau, work)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlauu2 "BLAS_FUNC(zlauu2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zlauu2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zlauu2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zlauum "BLAS_FUNC(zlauum)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zlauum(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zlauum(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbcon "BLAS_FUNC(zpbcon)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpbcon(char *uplo, int *n, int *kd, z *ab, int *ldab, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpbcon(uplo, n, kd, ab, ldab, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbequ "BLAS_FUNC(zpbequ)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, d *s, d *scond, d *amax, int *info) nogil
+cdef void zpbequ(char *uplo, int *n, int *kd, z *ab, int *ldab, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zpbequ(uplo, n, kd, ab, ldab, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbrfs "BLAS_FUNC(zpbrfs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpbrfs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpbrfs(uplo, n, kd, nrhs, ab, ldab, afb, ldafb, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbstf "BLAS_FUNC(zpbstf)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil
+cdef void zpbstf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_zpbstf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbsv "BLAS_FUNC(zpbsv)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpbsv(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpbsv(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbsvx "BLAS_FUNC(zpbsvx)"(char *fact, char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *afb, int *ldafb, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpbsvx(char *fact, char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *afb, int *ldafb, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpbsvx(fact, uplo, n, kd, nrhs, ab, ldab, afb, ldafb, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbtf2 "BLAS_FUNC(zpbtf2)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil
+cdef void zpbtf2(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_zpbtf2(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbtrf "BLAS_FUNC(zpbtrf)"(char *uplo, int *n, int *kd, npy_complex128 *ab, int *ldab, int *info) nogil
+cdef void zpbtrf(char *uplo, int *n, int *kd, z *ab, int *ldab, int *info) noexcept nogil:
+    
+    _fortran_zpbtrf(uplo, n, kd, ab, ldab, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpbtrs "BLAS_FUNC(zpbtrs)"(char *uplo, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpbtrs(char *uplo, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpbtrs(uplo, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpftrf "BLAS_FUNC(zpftrf)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *info) nogil
+cdef void zpftrf(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil:
+    
+    _fortran_zpftrf(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpftri "BLAS_FUNC(zpftri)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *info) nogil
+cdef void zpftri(char *transr, char *uplo, int *n, z *a, int *info) noexcept nogil:
+    
+    _fortran_zpftri(transr, uplo, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpftrs "BLAS_FUNC(zpftrs)"(char *transr, char *uplo, int *n, int *nrhs, npy_complex128 *a, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpftrs(char *transr, char *uplo, int *n, int *nrhs, z *a, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpftrs(transr, uplo, n, nrhs, a, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpocon "BLAS_FUNC(zpocon)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpocon(char *uplo, int *n, z *a, int *lda, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpocon(uplo, n, a, lda, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpoequ "BLAS_FUNC(zpoequ)"(int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void zpoequ(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zpoequ(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpoequb "BLAS_FUNC(zpoequb)"(int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, int *info) nogil
+cdef void zpoequb(int *n, z *a, int *lda, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zpoequb(n, a, lda, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zporfs "BLAS_FUNC(zporfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zporfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zporfs(uplo, n, nrhs, a, lda, af, ldaf, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zposv "BLAS_FUNC(zposv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zposv(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zposv(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zposvx "BLAS_FUNC(zposvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zposvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zposvx(fact, uplo, n, nrhs, a, lda, af, ldaf, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotf2 "BLAS_FUNC(zpotf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zpotf2(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zpotf2(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotrf "BLAS_FUNC(zpotrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zpotrf(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zpotrf(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotri "BLAS_FUNC(zpotri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void zpotri(char *uplo, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_zpotri(uplo, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpotrs "BLAS_FUNC(zpotrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpotrs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpotrs(uplo, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppcon "BLAS_FUNC(zppcon)"(char *uplo, int *n, npy_complex128 *ap, d *anorm, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zppcon(char *uplo, int *n, z *ap, d *anorm, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zppcon(uplo, n, ap, anorm, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppequ "BLAS_FUNC(zppequ)"(char *uplo, int *n, npy_complex128 *ap, d *s, d *scond, d *amax, int *info) nogil
+cdef void zppequ(char *uplo, int *n, z *ap, d *s, d *scond, d *amax, int *info) noexcept nogil:
+    
+    _fortran_zppequ(uplo, n, ap, s, scond, amax, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpprfs "BLAS_FUNC(zpprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zpprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zpprfs(uplo, n, nrhs, ap, afp, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppsv "BLAS_FUNC(zppsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zppsv(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zppsv(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zppsvx "BLAS_FUNC(zppsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, char *equed, d *s, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zppsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, char *equed, d *s, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zppsvx(fact, uplo, n, nrhs, ap, afp, equed, s, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpptrf "BLAS_FUNC(zpptrf)"(char *uplo, int *n, npy_complex128 *ap, int *info) nogil
+cdef void zpptrf(char *uplo, int *n, z *ap, int *info) noexcept nogil:
+    
+    _fortran_zpptrf(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpptri "BLAS_FUNC(zpptri)"(char *uplo, int *n, npy_complex128 *ap, int *info) nogil
+cdef void zpptri(char *uplo, int *n, z *ap, int *info) noexcept nogil:
+    
+    _fortran_zpptri(uplo, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpptrs "BLAS_FUNC(zpptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpptrs(char *uplo, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpptrs(uplo, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpstf2 "BLAS_FUNC(zpstf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void zpstf2(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_zpstf2(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpstrf "BLAS_FUNC(zpstrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) nogil
+cdef void zpstrf(char *uplo, int *n, z *a, int *lda, int *piv, int *rank, d *tol, d *work, int *info) noexcept nogil:
+    
+    _fortran_zpstrf(uplo, n, a, lda, piv, rank, tol, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptcon "BLAS_FUNC(zptcon)"(int *n, d *d, npy_complex128 *e, d *anorm, d *rcond, d *rwork, int *info) nogil
+cdef void zptcon(int *n, d *d, z *e, d *anorm, d *rcond, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zptcon(n, d, e, anorm, rcond, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpteqr "BLAS_FUNC(zpteqr)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, d *work, int *info) nogil
+cdef void zpteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_zpteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptrfs "BLAS_FUNC(zptrfs)"(char *uplo, int *n, int *nrhs, d *d, npy_complex128 *e, d *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zptrfs(char *uplo, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zptrfs(uplo, n, nrhs, d, e, df, ef, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptsv "BLAS_FUNC(zptsv)"(int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zptsv(int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zptsv(n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptsvx "BLAS_FUNC(zptsvx)"(char *fact, int *n, int *nrhs, d *d, npy_complex128 *e, d *df, npy_complex128 *ef, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zptsvx(char *fact, int *n, int *nrhs, d *d, z *e, d *df, z *ef, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zptsvx(fact, n, nrhs, d, e, df, ef, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpttrf "BLAS_FUNC(zpttrf)"(int *n, d *d, npy_complex128 *e, int *info) nogil
+cdef void zpttrf(int *n, d *d, z *e, int *info) noexcept nogil:
+    
+    _fortran_zpttrf(n, d, e, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zpttrs "BLAS_FUNC(zpttrs)"(char *uplo, int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zpttrs(char *uplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zpttrs(uplo, n, nrhs, d, e, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zptts2 "BLAS_FUNC(zptts2)"(int *iuplo, int *n, int *nrhs, d *d, npy_complex128 *e, npy_complex128 *b, int *ldb) nogil
+cdef void zptts2(int *iuplo, int *n, int *nrhs, d *d, z *e, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_zptts2(iuplo, n, nrhs, d, e, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zrot "BLAS_FUNC(zrot)"(int *n, npy_complex128 *cx, int *incx, npy_complex128 *cy, int *incy, d *c, npy_complex128 *s) nogil
+cdef void zrot(int *n, z *cx, int *incx, z *cy, int *incy, d *c, z *s) noexcept nogil:
+    
+    _fortran_zrot(n, cx, incx, cy, incy, c, s)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspcon "BLAS_FUNC(zspcon)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zspcon(char *uplo, int *n, z *ap, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zspcon(uplo, n, ap, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspmv "BLAS_FUNC(zspmv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *ap, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zspmv(char *uplo, int *n, z *alpha, z *ap, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zspmv(uplo, n, alpha, ap, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspr "BLAS_FUNC(zspr)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *ap) nogil
+cdef void zspr(char *uplo, int *n, z *alpha, z *x, int *incx, z *ap) noexcept nogil:
+    
+    _fortran_zspr(uplo, n, alpha, x, incx, ap)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsprfs "BLAS_FUNC(zsprfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zsprfs(char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zsprfs(uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspsv "BLAS_FUNC(zspsv)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zspsv(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zspsv(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zspsvx "BLAS_FUNC(zspsvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *afp, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zspsvx(char *fact, char *uplo, int *n, int *nrhs, z *ap, z *afp, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zspsvx(fact, uplo, n, nrhs, ap, afp, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsptrf "BLAS_FUNC(zsptrf)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, int *info) nogil
+cdef void zsptrf(char *uplo, int *n, z *ap, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zsptrf(uplo, n, ap, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsptri "BLAS_FUNC(zsptri)"(char *uplo, int *n, npy_complex128 *ap, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zsptri(char *uplo, int *n, z *ap, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsptri(uplo, n, ap, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsptrs "BLAS_FUNC(zsptrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *ap, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zsptrs(char *uplo, int *n, int *nrhs, z *ap, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zsptrs(uplo, n, nrhs, ap, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstedc "BLAS_FUNC(zstedc)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) nogil
+cdef void zstedc(char *compz, int *n, d *d, d *e, z *z, int *ldz, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zstedc(compz, n, d, e, z, ldz, work, lwork, rwork, lrwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstegr "BLAS_FUNC(zstegr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, npy_complex128 *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void zstegr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, d *abstol, int *m, d *w, z *z, int *ldz, int *isuppz, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zstegr(jobz, range, n, d, e, vl, vu, il, iu, abstol, m, w, z, ldz, isuppz, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstein "BLAS_FUNC(zstein)"(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, npy_complex128 *z, int *ldz, d *work, int *iwork, int *ifail, int *info) nogil
+cdef void zstein(int *n, d *d, d *e, int *m, d *w, int *iblock, int *isplit, z *z, int *ldz, d *work, int *iwork, int *ifail, int *info) noexcept nogil:
+    
+    _fortran_zstein(n, d, e, m, w, iblock, isplit, z, ldz, work, iwork, ifail, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zstemr "BLAS_FUNC(zstemr)"(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, npy_complex128 *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void zstemr(char *jobz, char *range, int *n, d *d, d *e, d *vl, d *vu, int *il, int *iu, int *m, d *w, z *z, int *ldz, int *nzc, int *isuppz, bint *tryrac, d *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_zstemr(jobz, range, n, d, e, vl, vu, il, iu, m, w, z, ldz, nzc, isuppz, tryrac, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsteqr "BLAS_FUNC(zsteqr)"(char *compz, int *n, d *d, d *e, npy_complex128 *z, int *ldz, d *work, int *info) nogil
+cdef void zsteqr(char *compz, int *n, d *d, d *e, z *z, int *ldz, d *work, int *info) noexcept nogil:
+    
+    _fortran_zsteqr(compz, n, d, e, z, ldz, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsycon "BLAS_FUNC(zsycon)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, d *anorm, d *rcond, npy_complex128 *work, int *info) nogil
+cdef void zsycon(char *uplo, int *n, z *a, int *lda, int *ipiv, d *anorm, d *rcond, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsycon(uplo, n, a, lda, ipiv, anorm, rcond, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyconv "BLAS_FUNC(zsyconv)"(char *uplo, char *way, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zsyconv(char *uplo, char *way, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsyconv(uplo, way, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyequb "BLAS_FUNC(zsyequb)"(char *uplo, int *n, npy_complex128 *a, int *lda, d *s, d *scond, d *amax, npy_complex128 *work, int *info) nogil
+cdef void zsyequb(char *uplo, int *n, z *a, int *lda, d *s, d *scond, d *amax, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsyequb(uplo, n, a, lda, s, scond, amax, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsymv "BLAS_FUNC(zsymv)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *a, int *lda, npy_complex128 *x, int *incx, npy_complex128 *beta, npy_complex128 *y, int *incy) nogil
+cdef void zsymv(char *uplo, int *n, z *alpha, z *a, int *lda, z *x, int *incx, z *beta, z *y, int *incy) noexcept nogil:
+    
+    _fortran_zsymv(uplo, n, alpha, a, lda, x, incx, beta, y, incy)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyr "BLAS_FUNC(zsyr)"(char *uplo, int *n, npy_complex128 *alpha, npy_complex128 *x, int *incx, npy_complex128 *a, int *lda) nogil
+cdef void zsyr(char *uplo, int *n, z *alpha, z *x, int *incx, z *a, int *lda) noexcept nogil:
+    
+    _fortran_zsyr(uplo, n, alpha, x, incx, a, lda)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyrfs "BLAS_FUNC(zsyrfs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void zsyrfs(char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zsyrfs(uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsysv "BLAS_FUNC(zsysv)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zsysv(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zsysv(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsysvx "BLAS_FUNC(zsysvx)"(char *fact, char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *af, int *ldaf, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *rcond, d *ferr, d *berr, npy_complex128 *work, int *lwork, d *rwork, int *info) nogil
+cdef void zsysvx(char *fact, char *uplo, int *n, int *nrhs, z *a, int *lda, z *af, int *ldaf, int *ipiv, z *b, int *ldb, z *x, int *ldx, d *rcond, d *ferr, d *berr, z *work, int *lwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_zsysvx(fact, uplo, n, nrhs, a, lda, af, ldaf, ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, lwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsyswapr "BLAS_FUNC(zsyswapr)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *i1, int *i2) nogil
+cdef void zsyswapr(char *uplo, int *n, z *a, int *lda, int *i1, int *i2) noexcept nogil:
+    
+    _fortran_zsyswapr(uplo, n, a, lda, i1, i2)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytf2 "BLAS_FUNC(zsytf2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, int *info) nogil
+cdef void zsytf2(char *uplo, int *n, z *a, int *lda, int *ipiv, int *info) noexcept nogil:
+    
+    _fortran_zsytf2(uplo, n, a, lda, ipiv, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytrf "BLAS_FUNC(zsytrf)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zsytrf(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zsytrf(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytri "BLAS_FUNC(zsytri)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *info) nogil
+cdef void zsytri(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsytri(uplo, n, a, lda, ipiv, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytri2 "BLAS_FUNC(zsytri2)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zsytri2(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zsytri2(uplo, n, a, lda, ipiv, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytri2x "BLAS_FUNC(zsytri2x)"(char *uplo, int *n, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *work, int *nb, int *info) nogil
+cdef void zsytri2x(char *uplo, int *n, z *a, int *lda, int *ipiv, z *work, int *nb, int *info) noexcept nogil:
+    
+    _fortran_zsytri2x(uplo, n, a, lda, ipiv, work, nb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytrs "BLAS_FUNC(zsytrs)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void zsytrs(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_zsytrs(uplo, n, nrhs, a, lda, ipiv, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zsytrs2 "BLAS_FUNC(zsytrs2)"(char *uplo, int *n, int *nrhs, npy_complex128 *a, int *lda, int *ipiv, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) nogil
+cdef void zsytrs2(char *uplo, int *n, int *nrhs, z *a, int *lda, int *ipiv, z *b, int *ldb, z *work, int *info) noexcept nogil:
+    
+    _fortran_zsytrs2(uplo, n, nrhs, a, lda, ipiv, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztbcon "BLAS_FUNC(ztbcon)"(char *norm, char *uplo, char *diag, int *n, int *kd, npy_complex128 *ab, int *ldab, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztbcon(char *norm, char *uplo, char *diag, int *n, int *kd, z *ab, int *ldab, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztbcon(norm, uplo, diag, n, kd, ab, ldab, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztbrfs "BLAS_FUNC(ztbrfs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztbrfs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztbrfs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztbtrs "BLAS_FUNC(ztbtrs)"(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, npy_complex128 *ab, int *ldab, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void ztbtrs(char *uplo, char *trans, char *diag, int *n, int *kd, int *nrhs, z *ab, int *ldab, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ztbtrs(uplo, trans, diag, n, kd, nrhs, ab, ldab, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztfsm "BLAS_FUNC(ztfsm)"(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, npy_complex128 *alpha, npy_complex128 *a, npy_complex128 *b, int *ldb) nogil
+cdef void ztfsm(char *transr, char *side, char *uplo, char *trans, char *diag, int *m, int *n, z *alpha, z *a, z *b, int *ldb) noexcept nogil:
+    
+    _fortran_ztfsm(transr, side, uplo, trans, diag, m, n, alpha, a, b, ldb)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztftri "BLAS_FUNC(ztftri)"(char *transr, char *uplo, char *diag, int *n, npy_complex128 *a, int *info) nogil
+cdef void ztftri(char *transr, char *uplo, char *diag, int *n, z *a, int *info) noexcept nogil:
+    
+    _fortran_ztftri(transr, uplo, diag, n, a, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztfttp "BLAS_FUNC(ztfttp)"(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *ap, int *info) nogil
+cdef void ztfttp(char *transr, char *uplo, int *n, z *arf, z *ap, int *info) noexcept nogil:
+    
+    _fortran_ztfttp(transr, uplo, n, arf, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztfttr "BLAS_FUNC(ztfttr)"(char *transr, char *uplo, int *n, npy_complex128 *arf, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztfttr(char *transr, char *uplo, int *n, z *arf, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztfttr(transr, uplo, n, arf, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgevc "BLAS_FUNC(ztgevc)"(char *side, char *howmny, bint *select, int *n, npy_complex128 *s, int *lds, npy_complex128 *p, int *ldp, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztgevc(char *side, char *howmny, bint *select, int *n, z *s, int *lds, z *p, int *ldp, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztgevc(side, howmny, select, n, s, lds, p, ldp, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgex2 "BLAS_FUNC(ztgex2)"(bint *wantq, bint *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *j1, int *info) nogil
+cdef void ztgex2(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *j1, int *info) noexcept nogil:
+    
+    _fortran_ztgex2(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, j1, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgexc "BLAS_FUNC(ztgexc)"(bint *wantq, bint *wantz, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *ifst, int *ilst, int *info) nogil
+cdef void ztgexc(bint *wantq, bint *wantz, int *n, z *a, int *lda, z *b, int *ldb, z *q, int *ldq, z *z, int *ldz, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ztgexc(wantq, wantz, n, a, lda, b, ldb, q, ldq, z, ldz, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsen "BLAS_FUNC(ztgsen)"(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *alpha, npy_complex128 *beta, npy_complex128 *q, int *ldq, npy_complex128 *z, int *ldz, int *m, d *pl, d *pr, d *dif, npy_complex128 *work, int *lwork, int *iwork, int *liwork, int *info) nogil
+cdef void ztgsen(int *ijob, bint *wantq, bint *wantz, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *alpha, z *beta, z *q, int *ldq, z *z, int *ldz, int *m, d *pl, d *pr, d *dif, z *work, int *lwork, int *iwork, int *liwork, int *info) noexcept nogil:
+    
+    _fortran_ztgsen(ijob, wantq, wantz, select, n, a, lda, b, ldb, alpha, beta, q, ldq, z, ldz, m, pl, pr, dif, work, lwork, iwork, liwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsja "BLAS_FUNC(ztgsja)"(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, npy_complex128 *u, int *ldu, npy_complex128 *v, int *ldv, npy_complex128 *q, int *ldq, npy_complex128 *work, int *ncycle, int *info) nogil
+cdef void ztgsja(char *jobu, char *jobv, char *jobq, int *m, int *p, int *n, int *k, int *l, z *a, int *lda, z *b, int *ldb, d *tola, d *tolb, d *alpha, d *beta, z *u, int *ldu, z *v, int *ldv, z *q, int *ldq, z *work, int *ncycle, int *info) noexcept nogil:
+    
+    _fortran_ztgsja(jobu, jobv, jobq, m, p, n, k, l, a, lda, b, ldb, tola, tolb, alpha, beta, u, ldu, v, ldv, q, ldq, work, ncycle, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsna "BLAS_FUNC(ztgsna)"(char *job, char *howmny, bint *select, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, d *s, d *dif, int *mm, int *m, npy_complex128 *work, int *lwork, int *iwork, int *info) nogil
+cdef void ztgsna(char *job, char *howmny, bint *select, int *n, z *a, int *lda, z *b, int *ldb, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *dif, int *mm, int *m, z *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ztgsna(job, howmny, select, n, a, lda, b, ldb, vl, ldvl, vr, ldvr, s, dif, mm, m, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsy2 "BLAS_FUNC(ztgsy2)"(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) nogil
+cdef void ztgsy2(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *rdsum, d *rdscal, int *info) noexcept nogil:
+    
+    _fortran_ztgsy2(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, rdsum, rdscal, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztgsyl "BLAS_FUNC(ztgsyl)"(char *trans, int *ijob, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, npy_complex128 *d, int *ldd, npy_complex128 *e, int *lde, npy_complex128 *f, int *ldf, d *scale, d *dif, npy_complex128 *work, int *lwork, int *iwork, int *info) nogil
+cdef void ztgsyl(char *trans, int *ijob, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, z *d, int *ldd, z *e, int *lde, z *f, int *ldf, d *scale, d *dif, z *work, int *lwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_ztgsyl(trans, ijob, m, n, a, lda, b, ldb, c, ldc, d, ldd, e, lde, f, ldf, scale, dif, work, lwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpcon "BLAS_FUNC(ztpcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *ap, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztpcon(char *norm, char *uplo, char *diag, int *n, z *ap, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztpcon(norm, uplo, diag, n, ap, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpmqrt "BLAS_FUNC(ztpmqrt)"(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *info) nogil
+cdef void ztpmqrt(char *side, char *trans, int *m, int *n, int *k, int *l, int *nb, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *info) noexcept nogil:
+    
+    _fortran_ztpmqrt(side, trans, m, n, k, l, nb, v, ldv, t, ldt, a, lda, b, ldb, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpqrt "BLAS_FUNC(ztpqrt)"(int *m, int *n, int *l, int *nb, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, npy_complex128 *work, int *info) nogil
+cdef void ztpqrt(int *m, int *n, int *l, int *nb, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, z *work, int *info) noexcept nogil:
+    
+    _fortran_ztpqrt(m, n, l, nb, a, lda, b, ldb, t, ldt, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpqrt2 "BLAS_FUNC(ztpqrt2)"(int *m, int *n, int *l, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *t, int *ldt, int *info) nogil
+cdef void ztpqrt2(int *m, int *n, int *l, z *a, int *lda, z *b, int *ldb, z *t, int *ldt, int *info) noexcept nogil:
+    
+    _fortran_ztpqrt2(m, n, l, a, lda, b, ldb, t, ldt, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztprfb "BLAS_FUNC(ztprfb)"(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, npy_complex128 *v, int *ldv, npy_complex128 *t, int *ldt, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *work, int *ldwork) nogil
+cdef void ztprfb(char *side, char *trans, char *direct, char *storev, int *m, int *n, int *k, int *l, z *v, int *ldv, z *t, int *ldt, z *a, int *lda, z *b, int *ldb, z *work, int *ldwork) noexcept nogil:
+    
+    _fortran_ztprfb(side, trans, direct, storev, m, n, k, l, v, ldv, t, ldt, a, lda, b, ldb, work, ldwork)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztprfs "BLAS_FUNC(ztprfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztprfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztprfs(uplo, trans, diag, n, nrhs, ap, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztptri "BLAS_FUNC(ztptri)"(char *uplo, char *diag, int *n, npy_complex128 *ap, int *info) nogil
+cdef void ztptri(char *uplo, char *diag, int *n, z *ap, int *info) noexcept nogil:
+    
+    _fortran_ztptri(uplo, diag, n, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztptrs "BLAS_FUNC(ztptrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *ap, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void ztptrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *ap, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ztptrs(uplo, trans, diag, n, nrhs, ap, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpttf "BLAS_FUNC(ztpttf)"(char *transr, char *uplo, int *n, npy_complex128 *ap, npy_complex128 *arf, int *info) nogil
+cdef void ztpttf(char *transr, char *uplo, int *n, z *ap, z *arf, int *info) noexcept nogil:
+    
+    _fortran_ztpttf(transr, uplo, n, ap, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztpttr "BLAS_FUNC(ztpttr)"(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztpttr(char *uplo, int *n, z *ap, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztpttr(uplo, n, ap, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrcon "BLAS_FUNC(ztrcon)"(char *norm, char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, d *rcond, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztrcon(char *norm, char *uplo, char *diag, int *n, z *a, int *lda, d *rcond, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztrcon(norm, uplo, diag, n, a, lda, rcond, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrevc "BLAS_FUNC(ztrevc)"(char *side, char *howmny, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, int *mm, int *m, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztrevc(char *side, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, int *mm, int *m, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztrevc(side, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, mm, m, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrexc "BLAS_FUNC(ztrexc)"(char *compq, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, int *ifst, int *ilst, int *info) nogil
+cdef void ztrexc(char *compq, int *n, z *t, int *ldt, z *q, int *ldq, int *ifst, int *ilst, int *info) noexcept nogil:
+    
+    _fortran_ztrexc(compq, n, t, ldt, q, ldq, ifst, ilst, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrrfs "BLAS_FUNC(ztrrfs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *x, int *ldx, d *ferr, d *berr, npy_complex128 *work, d *rwork, int *info) nogil
+cdef void ztrrfs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, z *x, int *ldx, d *ferr, d *berr, z *work, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztrrfs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, x, ldx, ferr, berr, work, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrsen "BLAS_FUNC(ztrsen)"(char *job, char *compq, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *q, int *ldq, npy_complex128 *w, int *m, d *s, d *sep, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void ztrsen(char *job, char *compq, bint *select, int *n, z *t, int *ldt, z *q, int *ldq, z *w, int *m, d *s, d *sep, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ztrsen(job, compq, select, n, t, ldt, q, ldq, w, m, s, sep, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrsna "BLAS_FUNC(ztrsna)"(char *job, char *howmny, bint *select, int *n, npy_complex128 *t, int *ldt, npy_complex128 *vl, int *ldvl, npy_complex128 *vr, int *ldvr, d *s, d *sep, int *mm, int *m, npy_complex128 *work, int *ldwork, d *rwork, int *info) nogil
+cdef void ztrsna(char *job, char *howmny, bint *select, int *n, z *t, int *ldt, z *vl, int *ldvl, z *vr, int *ldvr, d *s, d *sep, int *mm, int *m, z *work, int *ldwork, d *rwork, int *info) noexcept nogil:
+    
+    _fortran_ztrsna(job, howmny, select, n, t, ldt, vl, ldvl, vr, ldvr, s, sep, mm, m, work, ldwork, rwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrsyl "BLAS_FUNC(ztrsyl)"(char *trana, char *tranb, int *isgn, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, npy_complex128 *c, int *ldc, d *scale, int *info) nogil
+cdef void ztrsyl(char *trana, char *tranb, int *isgn, int *m, int *n, z *a, int *lda, z *b, int *ldb, z *c, int *ldc, d *scale, int *info) noexcept nogil:
+    
+    _fortran_ztrsyl(trana, tranb, isgn, m, n, a, lda, b, ldb, c, ldc, scale, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrti2 "BLAS_FUNC(ztrti2)"(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztrti2(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztrti2(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrtri "BLAS_FUNC(ztrtri)"(char *uplo, char *diag, int *n, npy_complex128 *a, int *lda, int *info) nogil
+cdef void ztrtri(char *uplo, char *diag, int *n, z *a, int *lda, int *info) noexcept nogil:
+    
+    _fortran_ztrtri(uplo, diag, n, a, lda, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrtrs "BLAS_FUNC(ztrtrs)"(char *uplo, char *trans, char *diag, int *n, int *nrhs, npy_complex128 *a, int *lda, npy_complex128 *b, int *ldb, int *info) nogil
+cdef void ztrtrs(char *uplo, char *trans, char *diag, int *n, int *nrhs, z *a, int *lda, z *b, int *ldb, int *info) noexcept nogil:
+    
+    _fortran_ztrtrs(uplo, trans, diag, n, nrhs, a, lda, b, ldb, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrttf "BLAS_FUNC(ztrttf)"(char *transr, char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *arf, int *info) nogil
+cdef void ztrttf(char *transr, char *uplo, int *n, z *a, int *lda, z *arf, int *info) noexcept nogil:
+    
+    _fortran_ztrttf(transr, uplo, n, a, lda, arf, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztrttp "BLAS_FUNC(ztrttp)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *ap, int *info) nogil
+cdef void ztrttp(char *uplo, int *n, z *a, int *lda, z *ap, int *info) noexcept nogil:
+    
+    _fortran_ztrttp(uplo, n, a, lda, ap, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_ztzrzf "BLAS_FUNC(ztzrzf)"(int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void ztzrzf(int *m, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_ztzrzf(m, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunbdb "BLAS_FUNC(zunbdb)"(char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, d *theta, d *phi, npy_complex128 *taup1, npy_complex128 *taup2, npy_complex128 *tauq1, npy_complex128 *tauq2, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunbdb(char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, d *phi, z *taup1, z *taup2, z *tauq1, z *tauq2, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunbdb(trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, phi, taup1, taup2, tauq1, tauq2, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zuncsd "BLAS_FUNC(zuncsd)"(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, npy_complex128 *x11, int *ldx11, npy_complex128 *x12, int *ldx12, npy_complex128 *x21, int *ldx21, npy_complex128 *x22, int *ldx22, d *theta, npy_complex128 *u1, int *ldu1, npy_complex128 *u2, int *ldu2, npy_complex128 *v1t, int *ldv1t, npy_complex128 *v2t, int *ldv2t, npy_complex128 *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) nogil
+cdef void zuncsd(char *jobu1, char *jobu2, char *jobv1t, char *jobv2t, char *trans, char *signs, int *m, int *p, int *q, z *x11, int *ldx11, z *x12, int *ldx12, z *x21, int *ldx21, z *x22, int *ldx22, d *theta, z *u1, int *ldu1, z *u2, int *ldu2, z *v1t, int *ldv1t, z *v2t, int *ldv2t, z *work, int *lwork, d *rwork, int *lrwork, int *iwork, int *info) noexcept nogil:
+    
+    _fortran_zuncsd(jobu1, jobu2, jobv1t, jobv2t, trans, signs, m, p, q, x11, ldx11, x12, ldx12, x21, ldx21, x22, ldx22, theta, u1, ldu1, u2, ldu2, v1t, ldv1t, v2t, ldv2t, work, lwork, rwork, lrwork, iwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zung2l "BLAS_FUNC(zung2l)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zung2l(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zung2l(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zung2r "BLAS_FUNC(zung2r)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zung2r(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zung2r(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungbr "BLAS_FUNC(zungbr)"(char *vect, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungbr(char *vect, int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungbr(vect, m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunghr "BLAS_FUNC(zunghr)"(int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunghr(int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunghr(n, ilo, ihi, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungl2 "BLAS_FUNC(zungl2)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zungl2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zungl2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunglq "BLAS_FUNC(zunglq)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunglq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunglq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungql "BLAS_FUNC(zungql)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungql(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungql(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungqr "BLAS_FUNC(zungqr)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungqr(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungqr(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungr2 "BLAS_FUNC(zungr2)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *info) nogil
+cdef void zungr2(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *info) noexcept nogil:
+    
+    _fortran_zungr2(m, n, k, a, lda, tau, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungrq "BLAS_FUNC(zungrq)"(int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungrq(int *m, int *n, int *k, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungrq(m, n, k, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zungtr "BLAS_FUNC(zungtr)"(char *uplo, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zungtr(char *uplo, int *n, z *a, int *lda, z *tau, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zungtr(uplo, n, a, lda, tau, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunm2l "BLAS_FUNC(zunm2l)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunm2l(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunm2l(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunm2r "BLAS_FUNC(zunm2r)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunm2r(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunm2r(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmbr "BLAS_FUNC(zunmbr)"(char *vect, char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmbr(char *vect, char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmbr(vect, side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmhr "BLAS_FUNC(zunmhr)"(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmhr(char *side, char *trans, int *m, int *n, int *ilo, int *ihi, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmhr(side, trans, m, n, ilo, ihi, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunml2 "BLAS_FUNC(zunml2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunml2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunml2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmlq "BLAS_FUNC(zunmlq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmlq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmlq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmql "BLAS_FUNC(zunmql)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmql(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmql(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmqr "BLAS_FUNC(zunmqr)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmqr(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmqr(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmr2 "BLAS_FUNC(zunmr2)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunmr2(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunmr2(side, trans, m, n, k, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmr3 "BLAS_FUNC(zunmr3)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zunmr3(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zunmr3(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmrq "BLAS_FUNC(zunmrq)"(char *side, char *trans, int *m, int *n, int *k, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmrq(char *side, char *trans, int *m, int *n, int *k, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmrq(side, trans, m, n, k, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmrz "BLAS_FUNC(zunmrz)"(char *side, char *trans, int *m, int *n, int *k, int *l, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmrz(char *side, char *trans, int *m, int *n, int *k, int *l, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmrz(side, trans, m, n, k, l, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zunmtr "BLAS_FUNC(zunmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *a, int *lda, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *lwork, int *info) nogil
+cdef void zunmtr(char *side, char *uplo, char *trans, int *m, int *n, z *a, int *lda, z *tau, z *c, int *ldc, z *work, int *lwork, int *info) noexcept nogil:
+    
+    _fortran_zunmtr(side, uplo, trans, m, n, a, lda, tau, c, ldc, work, lwork, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zupgtr "BLAS_FUNC(zupgtr)"(char *uplo, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *q, int *ldq, npy_complex128 *work, int *info) nogil
+cdef void zupgtr(char *uplo, int *n, z *ap, z *tau, z *q, int *ldq, z *work, int *info) noexcept nogil:
+    
+    _fortran_zupgtr(uplo, n, ap, tau, q, ldq, work, info)
+    
+
+cdef extern from "_lapack_subroutines.h":
+    void _fortran_zupmtr "BLAS_FUNC(zupmtr)"(char *side, char *uplo, char *trans, int *m, int *n, npy_complex128 *ap, npy_complex128 *tau, npy_complex128 *c, int *ldc, npy_complex128 *work, int *info) nogil
+cdef void zupmtr(char *side, char *uplo, char *trans, int *m, int *n, z *ap, z *tau, z *c, int *ldc, z *work, int *info) noexcept nogil:
+    
+    _fortran_zupmtr(side, uplo, trans, m, n, ap, tau, c, ldc, work, info)
+    
+
+
+# Python accessible wrappers for testing:
+
+def _test_dlamch(cmach):
+    # This conversion is necessary to handle Python 3 strings.
+    cmach_bytes = bytes(cmach)
+    # Now that it is a bytes representation, a non-temporary variable
+    # must be passed as a part of the function call.
+    cdef char* cmach_char = cmach_bytes
+    return dlamch(cmach_char)
+
+def _test_slamch(cmach):
+    # This conversion is necessary to handle Python 3 strings.
+    cmach_bytes = bytes(cmach)
+    # Now that it is a bytes representation, a non-temporary variable
+    # must be passed as a part of the function call.
+    cdef char* cmach_char = cmach_bytes
+    return slamch(cmach_char)
+
+cpdef double complex _test_zladiv(double complex zx, double complex zy) noexcept nogil:
+    return zladiv(&zx, &zy)
+
+cpdef float complex _test_cladiv(float complex cx, float complex cy) noexcept nogil:
+    return cladiv(&cx, &cy)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d82ab157ce3be763f63e453c9a6fee064557c85
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'eig', 'eigvals', 'eigh', 'eigvalsh',
+    'eig_banded', 'eigvals_banded',
+    'eigh_tridiagonal', 'eigvalsh_tridiagonal', 'hessenberg', 'cdf2rdf',
+    'LinAlgError', 'norm', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp",
+                                   private_modules=["_decomp"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..92545a5c6af5fe7a4de13f8746b96696d68b5bd2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_cholesky.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'cholesky', 'cho_factor', 'cho_solve', 'cholesky_banded',
+    'cho_solve_banded', 'LinAlgError', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_cholesky",
+                                   private_modules=["_decomp_cholesky"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d5d9a98a04a689fb735f81299e129dc7f307590
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_lu.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'lu', 'lu_solve', 'lu_factor',
+    'LinAlgWarning', 'get_lapack_funcs',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_lu",
+                                   private_modules=["_decomp_lu"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ef58729412ce2c83310b7817a143d14b8f28c19
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_qr.py
@@ -0,0 +1,20 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'qr', 'qr_multiply', 'rq', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_qr",
+                                   private_modules=["_decomp_qr"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3c6cc494db9b35dce8e4007c8c30d823b03881f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_schur.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'schur', 'rsf2csf', 'norm', 'LinAlgError', 'get_lapack_funcs', 'eigvals',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_schur",
+                                   private_modules=["_decomp_schur"], all=__all__,
+                                   attribute=name)
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py
new file mode 100644
index 0000000000000000000000000000000000000000..64d0ce8562f06a3837df050f0ea6b8b15a2b359e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/decomp_svd.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'svd', 'svdvals', 'diagsvd', 'orth', 'subspace_angles', 'null_space',
+    'LinAlgError', 'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="decomp_svd",
+                                   private_modules=["_decomp_svd"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/interpolative.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/interpolative.py
new file mode 100644
index 0000000000000000000000000000000000000000..38070863aa515266b0b130dbbdbd3d645da4aa0c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/interpolative.py
@@ -0,0 +1,989 @@
+#  ******************************************************************************
+#   Copyright (C) 2013 Kenneth L. Ho
+#
+#   Redistribution and use in source and binary forms, with or without
+#   modification, are permitted provided that the following conditions are met:
+#
+#   Redistributions of source code must retain the above copyright notice, this
+#   list of conditions and the following disclaimer. Redistributions in binary
+#   form must reproduce the above copyright notice, this list of conditions and
+#   the following disclaimer in the documentation and/or other materials
+#   provided with the distribution.
+#
+#   None of the names of the copyright holders may be used to endorse or
+#   promote products derived from this software without specific prior written
+#   permission.
+#
+#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+#   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+#   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+#   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+#   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+#   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+#   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+#   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+#   POSSIBILITY OF SUCH DAMAGE.
+#  ******************************************************************************
+
+r"""
+======================================================================
+Interpolative matrix decomposition (:mod:`scipy.linalg.interpolative`)
+======================================================================
+
+.. versionadded:: 0.13
+
+.. versionchanged:: 1.15.0
+    The underlying algorithms have been ported to Python from the original Fortran77
+    code. See references below for more details.
+
+.. currentmodule:: scipy.linalg.interpolative
+
+An interpolative decomposition (ID) of a matrix :math:`A \in
+\mathbb{C}^{m \times n}` of rank :math:`k \leq \min \{ m, n \}` is a
+factorization
+
+.. math::
+  A \Pi =
+  \begin{bmatrix}
+   A \Pi_{1} & A \Pi_{2}
+  \end{bmatrix} =
+  A \Pi_{1}
+  \begin{bmatrix}
+   I & T
+  \end{bmatrix},
+
+where :math:`\Pi = [\Pi_{1}, \Pi_{2}]` is a permutation matrix with
+:math:`\Pi_{1} \in \{ 0, 1 \}^{n \times k}`, i.e., :math:`A \Pi_{2} =
+A \Pi_{1} T`. This can equivalently be written as :math:`A = BP`,
+where :math:`B = A \Pi_{1}` and :math:`P = [I, T] \Pi^{\mathsf{T}}`
+are the *skeleton* and *interpolation matrices*, respectively.
+
+If :math:`A` does not have exact rank :math:`k`, then there exists an
+approximation in the form of an ID such that :math:`A = BP + E`, where
+:math:`\| E \| \sim \sigma_{k + 1}` is on the order of the :math:`(k +
+1)`-th largest singular value of :math:`A`. Note that :math:`\sigma_{k
++ 1}` is the best possible error for a rank-:math:`k` approximation
+and, in fact, is achieved by the singular value decomposition (SVD)
+:math:`A \approx U S V^{*}`, where :math:`U \in \mathbb{C}^{m \times
+k}` and :math:`V \in \mathbb{C}^{n \times k}` have orthonormal columns
+and :math:`S = \mathop{\mathrm{diag}} (\sigma_{i}) \in \mathbb{C}^{k
+\times k}` is diagonal with nonnegative entries. The principal
+advantages of using an ID over an SVD are that:
+
+- it is cheaper to construct;
+- it preserves the structure of :math:`A`; and
+- it is more efficient to compute with in light of the identity submatrix of :math:`P`.
+
+Routines
+========
+
+Main functionality:
+
+.. autosummary::
+   :toctree: generated/
+
+   interp_decomp
+   reconstruct_matrix_from_id
+   reconstruct_interp_matrix
+   reconstruct_skel_matrix
+   id_to_svd
+   svd
+   estimate_spectral_norm
+   estimate_spectral_norm_diff
+   estimate_rank
+
+Following support functions are deprecated and will be removed in SciPy 1.17.0:
+
+.. autosummary::
+   :toctree: generated/
+
+   seed
+   rand
+
+
+References
+==========
+
+This module uses the algorithms found in ID software package [1]_ by Martinsson,
+Rokhlin, Shkolnisky, and Tygert, which is a Fortran library for computing IDs using
+various algorithms, including the rank-revealing QR approach of [2]_ and the more
+recent randomized methods described in [3]_, [4]_, and [5]_.
+
+We advise the user to consult also the documentation for the `ID package
+`_.
+
+.. [1] P.G. Martinsson, V. Rokhlin, Y. Shkolnisky, M. Tygert. "ID: a
+    software package for low-rank approximation of matrices via interpolative
+    decompositions, version 0.2." http://tygert.com/id_doc.4.pdf.
+
+.. [2] H. Cheng, Z. Gimbutas, P.G. Martinsson, V. Rokhlin. "On the
+    compression of low rank matrices." *SIAM J. Sci. Comput.* 26 (4): 1389--1404,
+    2005. :doi:`10.1137/030602678`.
+
+.. [3] E. Liberty, F. Woolfe, P.G. Martinsson, V. Rokhlin, M.
+    Tygert. "Randomized algorithms for the low-rank approximation of matrices."
+    *Proc. Natl. Acad. Sci. U.S.A.* 104 (51): 20167--20172, 2007.
+    :doi:`10.1073/pnas.0709640104`.
+
+.. [4] P.G. Martinsson, V. Rokhlin, M. Tygert. "A randomized
+    algorithm for the decomposition of matrices." *Appl. Comput. Harmon. Anal.* 30
+    (1): 47--68,  2011. :doi:`10.1016/j.acha.2010.02.003`.
+
+.. [5] F. Woolfe, E. Liberty, V. Rokhlin, M. Tygert. "A fast
+    randomized algorithm for the approximation of matrices." *Appl. Comput.
+    Harmon. Anal.* 25 (3): 335--366, 2008. :doi:`10.1016/j.acha.2007.12.002`.
+
+
+Tutorial
+========
+
+Initializing
+------------
+
+The first step is to import :mod:`scipy.linalg.interpolative` by issuing the
+command:
+
+>>> import scipy.linalg.interpolative as sli
+
+Now let's build a matrix. For this, we consider a Hilbert matrix, which is well
+know to have low rank:
+
+>>> from scipy.linalg import hilbert
+>>> n = 1000
+>>> A = hilbert(n)
+
+We can also do this explicitly via:
+
+>>> import numpy as np
+>>> n = 1000
+>>> A = np.empty((n, n), order='F')
+>>> for j in range(n):
+...     for i in range(n):
+...         A[i,j] = 1. / (i + j + 1)
+
+Note the use of the flag ``order='F'`` in :func:`numpy.empty`. This
+instantiates the matrix in Fortran-contiguous order and is important for
+avoiding data copying when passing to the backend.
+
+We then define multiplication routines for the matrix by regarding it as a
+:class:`scipy.sparse.linalg.LinearOperator`:
+
+>>> from scipy.sparse.linalg import aslinearoperator
+>>> L = aslinearoperator(A)
+
+This automatically sets up methods describing the action of the matrix and its
+adjoint on a vector.
+
+Computing an ID
+---------------
+
+We have several choices of algorithm to compute an ID. These fall largely
+according to two dichotomies:
+
+1. how the matrix is represented, i.e., via its entries or via its action on a
+   vector; and
+2. whether to approximate it to a fixed relative precision or to a fixed rank.
+
+We step through each choice in turn below.
+
+In all cases, the ID is represented by three parameters:
+
+1. a rank ``k``;
+2. an index array ``idx``; and
+3. interpolation coefficients ``proj``.
+
+The ID is specified by the relation
+``np.dot(A[:,idx[:k]], proj) == A[:,idx[k:]]``.
+
+From matrix entries
+...................
+
+We first consider a matrix given in terms of its entries.
+
+To compute an ID to a fixed precision, type:
+
+>>> eps = 1e-3
+>>> k, idx, proj = sli.interp_decomp(A, eps)
+
+where ``eps < 1`` is the desired precision.
+
+To compute an ID to a fixed rank, use:
+
+>>> idx, proj = sli.interp_decomp(A, k)
+
+where ``k >= 1`` is the desired rank.
+
+Both algorithms use random sampling and are usually faster than the
+corresponding older, deterministic algorithms, which can be accessed via the
+commands:
+
+>>> k, idx, proj = sli.interp_decomp(A, eps, rand=False)
+
+and:
+
+>>> idx, proj = sli.interp_decomp(A, k, rand=False)
+
+respectively.
+
+From matrix action
+..................
+
+Now consider a matrix given in terms of its action on a vector as a
+:class:`scipy.sparse.linalg.LinearOperator`.
+
+To compute an ID to a fixed precision, type:
+
+>>> k, idx, proj = sli.interp_decomp(L, eps)
+
+To compute an ID to a fixed rank, use:
+
+>>> idx, proj = sli.interp_decomp(L, k)
+
+These algorithms are randomized.
+
+Reconstructing an ID
+--------------------
+
+The ID routines above do not output the skeleton and interpolation matrices
+explicitly but instead return the relevant information in a more compact (and
+sometimes more useful) form. To build these matrices, write:
+
+>>> B = sli.reconstruct_skel_matrix(A, k, idx)
+
+for the skeleton matrix and:
+
+>>> P = sli.reconstruct_interp_matrix(idx, proj)
+
+for the interpolation matrix. The ID approximation can then be computed as:
+
+>>> C = np.dot(B, P)
+
+This can also be constructed directly using:
+
+>>> C = sli.reconstruct_matrix_from_id(B, idx, proj)
+
+without having to first compute ``P``.
+
+Alternatively, this can be done explicitly as well using:
+
+>>> B = A[:,idx[:k]]
+>>> P = np.hstack([np.eye(k), proj])[:,np.argsort(idx)]
+>>> C = np.dot(B, P)
+
+Computing an SVD
+----------------
+
+An ID can be converted to an SVD via the command:
+
+>>> U, S, V = sli.id_to_svd(B, idx, proj)
+
+The SVD approximation is then:
+
+>>> approx = U @ np.diag(S) @ V.conj().T
+
+The SVD can also be computed "fresh" by combining both the ID and conversion
+steps into one command. Following the various ID algorithms above, there are
+correspondingly various SVD algorithms that one can employ.
+
+From matrix entries
+...................
+
+We consider first SVD algorithms for a matrix given in terms of its entries.
+
+To compute an SVD to a fixed precision, type:
+
+>>> U, S, V = sli.svd(A, eps)
+
+To compute an SVD to a fixed rank, use:
+
+>>> U, S, V = sli.svd(A, k)
+
+Both algorithms use random sampling; for the deterministic versions, issue the
+keyword ``rand=False`` as above.
+
+From matrix action
+..................
+
+Now consider a matrix given in terms of its action on a vector.
+
+To compute an SVD to a fixed precision, type:
+
+>>> U, S, V = sli.svd(L, eps)
+
+To compute an SVD to a fixed rank, use:
+
+>>> U, S, V = sli.svd(L, k)
+
+Utility routines
+----------------
+
+Several utility routines are also available.
+
+To estimate the spectral norm of a matrix, use:
+
+>>> snorm = sli.estimate_spectral_norm(A)
+
+This algorithm is based on the randomized power method and thus requires only
+matrix-vector products. The number of iterations to take can be set using the
+keyword ``its`` (default: ``its=20``). The matrix is interpreted as a
+:class:`scipy.sparse.linalg.LinearOperator`, but it is also valid to supply it
+as a :class:`numpy.ndarray`, in which case it is trivially converted using
+:func:`scipy.sparse.linalg.aslinearoperator`.
+
+The same algorithm can also estimate the spectral norm of the difference of two
+matrices ``A1`` and ``A2`` as follows:
+
+>>> A1, A2 = A**2, A
+>>> diff = sli.estimate_spectral_norm_diff(A1, A2)
+
+This is often useful for checking the accuracy of a matrix approximation.
+
+Some routines in :mod:`scipy.linalg.interpolative` require estimating the rank
+of a matrix as well. This can be done with either:
+
+>>> k = sli.estimate_rank(A, eps)
+
+or:
+
+>>> k = sli.estimate_rank(L, eps)
+
+depending on the representation. The parameter ``eps`` controls the definition
+of the numerical rank.
+
+Finally, the random number generation required for all randomized routines can
+be controlled via providing NumPy pseudo-random generators with a fixed seed. See
+:class:`numpy.random.Generator` and :func:`numpy.random.default_rng` for more details.
+
+Remarks
+-------
+
+The above functions all automatically detect the appropriate interface and work
+with both real and complex data types, passing input arguments to the proper
+backend routine.
+
+"""
+
+import scipy.linalg._decomp_interpolative as _backend
+import numpy as np
+import warnings
+
+__all__ = [
+    'estimate_rank',
+    'estimate_spectral_norm',
+    'estimate_spectral_norm_diff',
+    'id_to_svd',
+    'interp_decomp',
+    'rand',
+    'reconstruct_interp_matrix',
+    'reconstruct_matrix_from_id',
+    'reconstruct_skel_matrix',
+    'seed',
+    'svd',
+]
+
+_DTYPE_ERROR = ValueError("invalid input dtype (input must be float64 or complex128)")
+_TYPE_ERROR = TypeError("invalid input type (must be array or LinearOperator)")
+
+
+def _C_contiguous_copy(A):
+    """
+    Same as np.ascontiguousarray, but ensure a copy
+    """
+    A = np.asarray(A)
+    if A.flags.c_contiguous:
+        A = A.copy()
+    else:
+        A = np.ascontiguousarray(A)
+    return A
+
+
+def _is_real(A):
+    try:
+        if A.dtype == np.complex128:
+            return False
+        elif A.dtype == np.float64:
+            return True
+        else:
+            raise _DTYPE_ERROR
+    except AttributeError as e:
+        raise _TYPE_ERROR from e
+
+
+def seed(seed=None):
+    """
+    This function, historically, used to set the seed of the randomization algorithms
+    used in the `scipy.linalg.interpolative` functions written in Fortran77.
+
+    The library has been ported to Python and now the functions use the native NumPy
+    generators and this function has no content and returns None. Thus this function
+    should not be used and will be removed in SciPy version 1.17.0.
+    """
+    warnings.warn("`scipy.linalg.interpolative.seed` is deprecated and will be "
+                  "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3)
+
+
+def rand(*shape):
+    """
+    This function, historically, used to generate uniformly distributed random number
+    for the randomization algorithms used in the `scipy.linalg.interpolative` functions
+    written in Fortran77.
+
+    The library has been ported to Python and now the functions use the native NumPy
+    generators. Thus this function should not be used and will be removed in the
+    SciPy version 1.17.0.
+
+    If pseudo-random numbers are needed, NumPy pseudo-random generators should be used
+    instead.
+
+    Parameters
+    ----------
+    *shape
+        Shape of output array
+
+    """
+    warnings.warn("`scipy.linalg.interpolative.rand` is deprecated and will be "
+                  "removed in SciPy 1.17.0.", DeprecationWarning, stacklevel=3)
+    rng = np.random.default_rng()
+    return rng.uniform(low=0., high=1.0, size=shape)
+
+
+def interp_decomp(A, eps_or_k, rand=True, rng=None):
+    """
+    Compute ID of a matrix.
+
+    An ID of a matrix `A` is a factorization defined by a rank `k`, a column
+    index array `idx`, and interpolation coefficients `proj` such that::
+
+        numpy.dot(A[:,idx[:k]], proj) = A[:,idx[k:]]
+
+    The original matrix can then be reconstructed as::
+
+        numpy.hstack([A[:,idx[:k]],
+                                    numpy.dot(A[:,idx[:k]], proj)]
+                                )[:,numpy.argsort(idx)]
+
+    or via the routine :func:`reconstruct_matrix_from_id`. This can
+    equivalently be written as::
+
+        numpy.dot(A[:,idx[:k]],
+                            numpy.hstack([numpy.eye(k), proj])
+                          )[:,np.argsort(idx)]
+
+    in terms of the skeleton and interpolation matrices::
+
+        B = A[:,idx[:k]]
+
+    and::
+
+        P = numpy.hstack([numpy.eye(k), proj])[:,np.argsort(idx)]
+
+    respectively. See also :func:`reconstruct_interp_matrix` and
+    :func:`reconstruct_skel_matrix`.
+
+    The ID can be computed to any relative precision or rank (depending on the
+    value of `eps_or_k`). If a precision is specified (`eps_or_k < 1`), then
+    this function has the output signature::
+
+        k, idx, proj = interp_decomp(A, eps_or_k)
+
+    Otherwise, if a rank is specified (`eps_or_k >= 1`), then the output
+    signature is::
+
+        idx, proj = interp_decomp(A, eps_or_k)
+
+    ..  This function automatically detects the form of the input parameters
+        and passes them to the appropriate backend. For details, see
+        :func:`_backend.iddp_id`, :func:`_backend.iddp_aid`,
+        :func:`_backend.iddp_rid`, :func:`_backend.iddr_id`,
+        :func:`_backend.iddr_aid`, :func:`_backend.iddr_rid`,
+        :func:`_backend.idzp_id`, :func:`_backend.idzp_aid`,
+        :func:`_backend.idzp_rid`, :func:`_backend.idzr_id`,
+        :func:`_backend.idzr_aid`, and :func:`_backend.idzr_rid`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator` with `rmatvec`
+        Matrix to be factored
+    eps_or_k : float or int
+        Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of
+        approximation.
+    rand : bool, optional
+        Whether to use random sampling if `A` is of type :class:`numpy.ndarray`
+        (randomized algorithms are always used if `A` is of type
+        :class:`scipy.sparse.linalg.LinearOperator`).
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    k : int
+        Rank required to achieve specified relative precision if
+        ``eps_or_k < 1``.
+    idx : :class:`numpy.ndarray`
+        Column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+    """  # numpy/numpydoc#87  # noqa: E501
+    from scipy.sparse.linalg import LinearOperator
+    rng = np.random.default_rng(rng)
+    real = _is_real(A)
+
+    if isinstance(A, np.ndarray):
+        A = _C_contiguous_copy(A)
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if rand:
+                if real:
+                    k, idx, proj = _backend.iddp_aid(A, eps, rng=rng)
+                else:
+                    k, idx, proj = _backend.idzp_aid(A, eps, rng=rng)
+            else:
+                if real:
+                    k, idx, proj = _backend.iddp_id(A, eps)
+                else:
+                    k, idx, proj = _backend.idzp_id(A, eps)
+            return k, idx, proj
+        else:
+            k = int(eps_or_k)
+            if rand:
+                if real:
+                    idx, proj = _backend.iddr_aid(A, k, rng=rng)
+                else:
+                    idx, proj = _backend.idzr_aid(A, k, rng=rng)
+            else:
+                if real:
+                    idx, proj = _backend.iddr_id(A, k)
+                else:
+                    idx, proj = _backend.idzr_id(A, k)
+            return idx, proj
+    elif isinstance(A, LinearOperator):
+
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if real:
+                k, idx, proj = _backend.iddp_rid(A, eps, rng=rng)
+            else:
+                k, idx, proj = _backend.idzp_rid(A, eps, rng=rng)
+            return k, idx, proj
+        else:
+            k = int(eps_or_k)
+            if real:
+                idx, proj = _backend.iddr_rid(A, k, rng=rng)
+            else:
+                idx, proj = _backend.idzr_rid(A, k, rng=rng)
+            return idx, proj
+    else:
+        raise _TYPE_ERROR
+
+
+def reconstruct_matrix_from_id(B, idx, proj):
+    """
+    Reconstruct matrix from its ID.
+
+    A matrix `A` with skeleton matrix `B` and ID indices and coefficients `idx`
+    and `proj`, respectively, can be reconstructed as::
+
+        numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
+
+    See also :func:`reconstruct_interp_matrix` and
+    :func:`reconstruct_skel_matrix`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_reconid` and
+        :func:`_backend.idz_reconid`.
+
+    Parameters
+    ----------
+    B : :class:`numpy.ndarray`
+        Skeleton matrix.
+    idx : :class:`numpy.ndarray`
+        Column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+
+    Returns
+    -------
+    :class:`numpy.ndarray`
+        Reconstructed matrix.
+    """
+    if _is_real(B):
+        return _backend.idd_reconid(B, idx, proj)
+    else:
+        return _backend.idz_reconid(B, idx, proj)
+
+
+def reconstruct_interp_matrix(idx, proj):
+    """
+    Reconstruct interpolation matrix from ID.
+
+    The interpolation matrix can be reconstructed from the ID indices and
+    coefficients `idx` and `proj`, respectively, as::
+
+        P = numpy.hstack([numpy.eye(proj.shape[0]), proj])[:,numpy.argsort(idx)]
+
+    The original matrix can then be reconstructed from its skeleton matrix ``B``
+    via ``A = B @ P``
+
+    See also :func:`reconstruct_matrix_from_id` and
+    :func:`reconstruct_skel_matrix`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_reconint` and
+        :func:`_backend.idz_reconint`.
+
+    Parameters
+    ----------
+    idx : :class:`numpy.ndarray`
+        1D column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+
+    Returns
+    -------
+    :class:`numpy.ndarray`
+        Interpolation matrix.
+    """
+    n, krank = len(idx), proj.shape[0]
+    if _is_real(proj):
+        p = np.zeros([krank, n], dtype=np.float64)
+    else:
+        p = np.zeros([krank, n], dtype=np.complex128)
+
+    for ci in range(krank):
+        p[ci, idx[ci]] = 1.0
+    p[:, idx[krank:]] = proj[:, :]
+
+    return p
+
+
+def reconstruct_skel_matrix(A, k, idx):
+    """
+    Reconstruct skeleton matrix from ID.
+
+    The skeleton matrix can be reconstructed from the original matrix `A` and its
+    ID rank and indices `k` and `idx`, respectively, as::
+
+        B = A[:,idx[:k]]
+
+    The original matrix can then be reconstructed via::
+
+        numpy.hstack([B, numpy.dot(B, proj)])[:,numpy.argsort(idx)]
+
+    See also :func:`reconstruct_matrix_from_id` and
+    :func:`reconstruct_interp_matrix`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_copycols` and
+        :func:`_backend.idz_copycols`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray`
+        Original matrix.
+    k : int
+        Rank of ID.
+    idx : :class:`numpy.ndarray`
+        Column index array.
+
+    Returns
+    -------
+    :class:`numpy.ndarray`
+        Skeleton matrix.
+    """
+    return A[:, idx[:k]]
+
+
+def id_to_svd(B, idx, proj):
+    """
+    Convert ID to SVD.
+
+    The SVD reconstruction of a matrix with skeleton matrix `B` and ID indices and
+    coefficients `idx` and `proj`, respectively, is::
+
+        U, S, V = id_to_svd(B, idx, proj)
+        A = numpy.dot(U, numpy.dot(numpy.diag(S), V.conj().T))
+
+    See also :func:`svd`.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_id2svd` and
+        :func:`_backend.idz_id2svd`.
+
+    Parameters
+    ----------
+    B : :class:`numpy.ndarray`
+        Skeleton matrix.
+    idx : :class:`numpy.ndarray`
+        1D column index array.
+    proj : :class:`numpy.ndarray`
+        Interpolation coefficients.
+
+    Returns
+    -------
+    U : :class:`numpy.ndarray`
+        Left singular vectors.
+    S : :class:`numpy.ndarray`
+        Singular values.
+    V : :class:`numpy.ndarray`
+        Right singular vectors.
+    """
+    B = _C_contiguous_copy(B)
+    if _is_real(B):
+        U, S, V = _backend.idd_id2svd(B, idx, proj)
+    else:
+        U, S, V = _backend.idz_id2svd(B, idx, proj)
+
+    return U, S, V
+
+
+def estimate_spectral_norm(A, its=20, rng=None):
+    """
+    Estimate spectral norm of a matrix by the randomized power method.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_snorm` and
+        :func:`_backend.idz_snorm`.
+
+    Parameters
+    ----------
+    A : :class:`scipy.sparse.linalg.LinearOperator`
+        Matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
+        `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
+    its : int, optional
+        Number of power method iterations.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    float
+        Spectral norm estimate.
+    """
+    from scipy.sparse.linalg import aslinearoperator
+    rng = np.random.default_rng(rng)
+    A = aslinearoperator(A)
+
+    if _is_real(A):
+        return _backend.idd_snorm(A, its=its, rng=rng)
+    else:
+        return _backend.idz_snorm(A, its=its, rng=rng)
+
+
+def estimate_spectral_norm_diff(A, B, its=20, rng=None):
+    """
+    Estimate spectral norm of the difference of two matrices by the randomized
+    power method.
+
+    ..  This function automatically detects the matrix data type and calls the
+        appropriate backend. For details, see :func:`_backend.idd_diffsnorm` and
+        :func:`_backend.idz_diffsnorm`.
+
+    Parameters
+    ----------
+    A : :class:`scipy.sparse.linalg.LinearOperator`
+        First matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with the
+        `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
+    B : :class:`scipy.sparse.linalg.LinearOperator`
+        Second matrix given as a :class:`scipy.sparse.linalg.LinearOperator` with
+        the `matvec` and `rmatvec` methods (to apply the matrix and its adjoint).
+    its : int, optional
+        Number of power method iterations.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    float
+        Spectral norm estimate of matrix difference.
+    """
+    from scipy.sparse.linalg import aslinearoperator
+    rng = np.random.default_rng(rng)
+    A = aslinearoperator(A)
+    B = aslinearoperator(B)
+
+    if _is_real(A):
+        return _backend.idd_diffsnorm(A, B, its=its, rng=rng)
+    else:
+        return _backend.idz_diffsnorm(A, B, its=its, rng=rng)
+
+
+def svd(A, eps_or_k, rand=True, rng=None):
+    """
+    Compute SVD of a matrix via an ID.
+
+    An SVD of a matrix `A` is a factorization::
+
+        A = U @ np.diag(S) @ V.conj().T
+
+    where `U` and `V` have orthonormal columns and `S` is nonnegative.
+
+    The SVD can be computed to any relative precision or rank (depending on the
+    value of `eps_or_k`).
+
+    See also :func:`interp_decomp` and :func:`id_to_svd`.
+
+    ..  This function automatically detects the form of the input parameters and
+        passes them to the appropriate backend. For details, see
+        :func:`_backend.iddp_svd`, :func:`_backend.iddp_asvd`,
+        :func:`_backend.iddp_rsvd`, :func:`_backend.iddr_svd`,
+        :func:`_backend.iddr_asvd`, :func:`_backend.iddr_rsvd`,
+        :func:`_backend.idzp_svd`, :func:`_backend.idzp_asvd`,
+        :func:`_backend.idzp_rsvd`, :func:`_backend.idzr_svd`,
+        :func:`_backend.idzr_asvd`, and :func:`_backend.idzr_rsvd`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator`
+        Matrix to be factored, given as either a :class:`numpy.ndarray` or a
+        :class:`scipy.sparse.linalg.LinearOperator` with the `matvec` and
+        `rmatvec` methods (to apply the matrix and its adjoint).
+    eps_or_k : float or int
+        Relative error (if ``eps_or_k < 1``) or rank (if ``eps_or_k >= 1``) of
+        approximation.
+    rand : bool, optional
+        Whether to use random sampling if `A` is of type :class:`numpy.ndarray`
+        (randomized algorithms are always used if `A` is of type
+        :class:`scipy.sparse.linalg.LinearOperator`).
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    U : :class:`numpy.ndarray`
+        2D array of left singular vectors.
+    S : :class:`numpy.ndarray`
+        1D array of singular values.
+    V : :class:`numpy.ndarray`
+        2D array right singular vectors.
+    """
+    from scipy.sparse.linalg import LinearOperator
+    rng = np.random.default_rng(rng)
+
+    real = _is_real(A)
+
+    if isinstance(A, np.ndarray):
+        A = _C_contiguous_copy(A)
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if rand:
+                if real:
+                    U, S, V = _backend.iddp_asvd(A, eps, rng=rng)
+                else:
+                    U, S, V = _backend.idzp_asvd(A, eps, rng=rng)
+            else:
+                if real:
+                    U, S, V = _backend.iddp_svd(A, eps)
+                    V = V.T.conj()
+                else:
+                    U, S, V = _backend.idzp_svd(A, eps)
+                    V = V.T.conj()
+        else:
+            k = int(eps_or_k)
+            if k > min(A.shape):
+                raise ValueError(f"Approximation rank {k} exceeds min(A.shape) = "
+                                 f" {min(A.shape)} ")
+            if rand:
+                if real:
+                    U, S, V = _backend.iddr_asvd(A, k, rng=rng)
+                else:
+                    U, S, V = _backend.idzr_asvd(A, k, rng=rng)
+            else:
+                if real:
+                    U, S, V = _backend.iddr_svd(A, k)
+                    V = V.T.conj()
+                else:
+                    U, S, V = _backend.idzr_svd(A, k)
+                    V = V.T.conj()
+    elif isinstance(A, LinearOperator):
+        if eps_or_k < 1:
+            eps = eps_or_k
+            if real:
+                U, S, V = _backend.iddp_rsvd(A, eps, rng=rng)
+            else:
+                U, S, V = _backend.idzp_rsvd(A, eps, rng=rng)
+        else:
+            k = int(eps_or_k)
+            if real:
+                U, S, V = _backend.iddr_rsvd(A, k, rng=rng)
+            else:
+                U, S, V = _backend.idzr_rsvd(A, k, rng=rng)
+    else:
+        raise _TYPE_ERROR
+    return U, S, V
+
+
+def estimate_rank(A, eps, rng=None):
+    """
+    Estimate matrix rank to a specified relative precision using randomized
+    methods.
+
+    The matrix `A` can be given as either a :class:`numpy.ndarray` or a
+    :class:`scipy.sparse.linalg.LinearOperator`, with different algorithms used
+    for each case. If `A` is of type :class:`numpy.ndarray`, then the output
+    rank is typically about 8 higher than the actual numerical rank.
+
+    ..  This function automatically detects the form of the input parameters and
+        passes them to the appropriate backend. For details,
+        see :func:`_backend.idd_estrank`, :func:`_backend.idd_findrank`,
+        :func:`_backend.idz_estrank`, and :func:`_backend.idz_findrank`.
+
+    Parameters
+    ----------
+    A : :class:`numpy.ndarray` or :class:`scipy.sparse.linalg.LinearOperator`
+        Matrix whose rank is to be estimated, given as either a
+        :class:`numpy.ndarray` or a :class:`scipy.sparse.linalg.LinearOperator`
+        with the `rmatvec` method (to apply the matrix adjoint).
+    eps : float
+        Relative error for numerical rank definition.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+        If `rand` is ``False``, the argument is ignored.
+
+    Returns
+    -------
+    int
+        Estimated matrix rank.
+    """
+    from scipy.sparse.linalg import LinearOperator
+
+    rng = np.random.default_rng(rng)
+    real = _is_real(A)
+
+    if isinstance(A, np.ndarray):
+        A = _C_contiguous_copy(A)
+        if real:
+            rank, _ = _backend.idd_estrank(A, eps, rng=rng)
+        else:
+            rank, _ = _backend.idz_estrank(A, eps, rng=rng)
+        if rank == 0:
+            # special return value for nearly full rank
+            rank = min(A.shape)
+        return rank
+    elif isinstance(A, LinearOperator):
+        if real:
+            return _backend.idd_findrank(A, eps, rng=rng)[0]
+        else:
+            return _backend.idz_findrank(A, eps, rng=rng)[0]
+    else:
+        raise _TYPE_ERROR
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/lapack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d15cf4d72d19f4b7949cd80bc77aa31553841c1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/lapack.py
@@ -0,0 +1,1061 @@
+"""
+Low-level LAPACK functions (:mod:`scipy.linalg.lapack`)
+=======================================================
+
+This module contains low-level functions from the LAPACK library.
+
+.. versionadded:: 0.12.0
+
+.. note::
+
+    The common ``overwrite_<>`` option in many routines, allows the
+    input arrays to be overwritten to avoid extra memory allocation.
+    However this requires the array to satisfy two conditions
+    which are memory order and the data type to match exactly the
+    order and the type expected by the routine.
+
+    As an example, if you pass a double precision float array to any
+    ``S....`` routine which expects single precision arguments, f2py
+    will create an intermediate array to match the argument types and
+    overwriting will be performed on that intermediate array.
+
+    Similarly, if a C-contiguous array is passed, f2py will pass a
+    FORTRAN-contiguous array internally. Please make sure that these
+    details are satisfied. More information can be found in the f2py
+    documentation.
+
+.. warning::
+
+   These functions do little to no error checking.
+   It is possible to cause crashes by mis-using them,
+   so prefer using the higher-level routines in `scipy.linalg`.
+
+Finding functions
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   get_lapack_funcs
+
+All functions
+-------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sgbsv
+   dgbsv
+   cgbsv
+   zgbsv
+
+   sgbtrf
+   dgbtrf
+   cgbtrf
+   zgbtrf
+
+   sgbtrs
+   dgbtrs
+   cgbtrs
+   zgbtrs
+
+   sgebal
+   dgebal
+   cgebal
+   zgebal
+
+   sgecon
+   dgecon
+   cgecon
+   zgecon
+
+   sgeequ
+   dgeequ
+   cgeequ
+   zgeequ
+
+   sgeequb
+   dgeequb
+   cgeequb
+   zgeequb
+
+   sgees
+   dgees
+   cgees
+   zgees
+
+   sgeev
+   dgeev
+   cgeev
+   zgeev
+
+   sgeev_lwork
+   dgeev_lwork
+   cgeev_lwork
+   zgeev_lwork
+
+   sgehrd
+   dgehrd
+   cgehrd
+   zgehrd
+
+   sgehrd_lwork
+   dgehrd_lwork
+   cgehrd_lwork
+   zgehrd_lwork
+
+   sgejsv
+   dgejsv
+
+   sgels
+   dgels
+   cgels
+   zgels
+
+   sgels_lwork
+   dgels_lwork
+   cgels_lwork
+   zgels_lwork
+
+   sgelsd
+   dgelsd
+   cgelsd
+   zgelsd
+
+   sgelsd_lwork
+   dgelsd_lwork
+   cgelsd_lwork
+   zgelsd_lwork
+
+   sgelss
+   dgelss
+   cgelss
+   zgelss
+
+   sgelss_lwork
+   dgelss_lwork
+   cgelss_lwork
+   zgelss_lwork
+
+   sgelsy
+   dgelsy
+   cgelsy
+   zgelsy
+
+   sgelsy_lwork
+   dgelsy_lwork
+   cgelsy_lwork
+   zgelsy_lwork
+
+   sgeqp3
+   dgeqp3
+   cgeqp3
+   zgeqp3
+
+   sgeqrf
+   dgeqrf
+   cgeqrf
+   zgeqrf
+
+   sgeqrf_lwork
+   dgeqrf_lwork
+   cgeqrf_lwork
+   zgeqrf_lwork
+
+   sgeqrfp
+   dgeqrfp
+   cgeqrfp
+   zgeqrfp
+
+   sgeqrfp_lwork
+   dgeqrfp_lwork
+   cgeqrfp_lwork
+   zgeqrfp_lwork
+
+   sgerqf
+   dgerqf
+   cgerqf
+   zgerqf
+
+   sgesdd
+   dgesdd
+   cgesdd
+   zgesdd
+
+   sgesdd_lwork
+   dgesdd_lwork
+   cgesdd_lwork
+   zgesdd_lwork
+
+   sgesv
+   dgesv
+   cgesv
+   zgesv
+
+   sgesvd
+   dgesvd
+   cgesvd
+   zgesvd
+
+   sgesvd_lwork
+   dgesvd_lwork
+   cgesvd_lwork
+   zgesvd_lwork
+
+   sgesvx
+   dgesvx
+   cgesvx
+   zgesvx
+
+   sgetrf
+   dgetrf
+   cgetrf
+   zgetrf
+
+   sgetc2
+   dgetc2
+   cgetc2
+   zgetc2
+
+   sgetri
+   dgetri
+   cgetri
+   zgetri
+
+   sgetri_lwork
+   dgetri_lwork
+   cgetri_lwork
+   zgetri_lwork
+
+   sgetrs
+   dgetrs
+   cgetrs
+   zgetrs
+
+   sgesc2
+   dgesc2
+   cgesc2
+   zgesc2
+
+   sgges
+   dgges
+   cgges
+   zgges
+
+   sggev
+   dggev
+   cggev
+   zggev
+
+   sgglse
+   dgglse
+   cgglse
+   zgglse
+
+   sgglse_lwork
+   dgglse_lwork
+   cgglse_lwork
+   zgglse_lwork
+
+   sgtsv
+   dgtsv
+   cgtsv
+   zgtsv
+
+   sgtsvx
+   dgtsvx
+   cgtsvx
+   zgtsvx
+
+   chbevd
+   zhbevd
+
+   chbevx
+   zhbevx
+
+   checon
+   zhecon
+
+   cheequb
+   zheequb
+
+   cheev
+   zheev
+
+   cheev_lwork
+   zheev_lwork
+
+   cheevd
+   zheevd
+
+   cheevd_lwork
+   zheevd_lwork
+
+   cheevr
+   zheevr
+
+   cheevr_lwork
+   zheevr_lwork
+
+   cheevx
+   zheevx
+
+   cheevx_lwork
+   zheevx_lwork
+
+   chegst
+   zhegst
+
+   chegv
+   zhegv
+
+   chegv_lwork
+   zhegv_lwork
+
+   chegvd
+   zhegvd
+
+   chegvx
+   zhegvx
+
+   chegvx_lwork
+   zhegvx_lwork
+
+   chesv
+   zhesv
+
+   chesv_lwork
+   zhesv_lwork
+
+   chesvx
+   zhesvx
+
+   chesvx_lwork
+   zhesvx_lwork
+
+   chetrd
+   zhetrd
+
+   chetrd_lwork
+   zhetrd_lwork
+
+   chetrf
+   zhetrf
+
+   chetrf_lwork
+   zhetrf_lwork
+
+   chetrs
+   zhetrs
+
+   chfrk
+   zhfrk
+
+   slamch
+   dlamch
+
+   slange
+   dlange
+   clange
+   zlange
+
+   slantr
+   dlantr
+   clantr
+   zlantr
+
+   slarf
+   dlarf
+   clarf
+   zlarf
+
+   slarfg
+   dlarfg
+   clarfg
+   zlarfg
+
+   slartg
+   dlartg
+   clartg
+   zlartg
+
+   slasd4
+   dlasd4
+
+   slaswp
+   dlaswp
+   claswp
+   zlaswp
+
+   slauum
+   dlauum
+   clauum
+   zlauum
+
+   sorcsd
+   dorcsd
+   sorcsd_lwork
+   dorcsd_lwork
+
+   sorghr
+   dorghr
+   sorghr_lwork
+   dorghr_lwork
+
+   sorgqr
+   dorgqr
+
+   sorgrq
+   dorgrq
+
+   sormqr
+   dormqr
+
+   sormrz
+   dormrz
+
+   sormrz_lwork
+   dormrz_lwork
+
+   spbsv
+   dpbsv
+   cpbsv
+   zpbsv
+
+   spbtrf
+   dpbtrf
+   cpbtrf
+   zpbtrf
+
+   spbtrs
+   dpbtrs
+   cpbtrs
+   zpbtrs
+
+   spftrf
+   dpftrf
+   cpftrf
+   zpftrf
+
+   spftri
+   dpftri
+   cpftri
+   zpftri
+
+   spftrs
+   dpftrs
+   cpftrs
+   zpftrs
+
+   spocon
+   dpocon
+   cpocon
+   zpocon
+
+   spstrf
+   dpstrf
+   cpstrf
+   zpstrf
+
+   spstf2
+   dpstf2
+   cpstf2
+   zpstf2
+
+   sposv
+   dposv
+   cposv
+   zposv
+
+   sposvx
+   dposvx
+   cposvx
+   zposvx
+
+   spotrf
+   dpotrf
+   cpotrf
+   zpotrf
+
+   spotri
+   dpotri
+   cpotri
+   zpotri
+
+   spotrs
+   dpotrs
+   cpotrs
+   zpotrs
+
+   sppcon
+   dppcon
+   cppcon
+   zppcon
+
+   sppsv
+   dppsv
+   cppsv
+   zppsv
+
+   spptrf
+   dpptrf
+   cpptrf
+   zpptrf
+
+   spptri
+   dpptri
+   cpptri
+   zpptri
+
+   spptrs
+   dpptrs
+   cpptrs
+   zpptrs
+
+   sptsv
+   dptsv
+   cptsv
+   zptsv
+
+   sptsvx
+   dptsvx
+   cptsvx
+   zptsvx
+
+   spttrf
+   dpttrf
+   cpttrf
+   zpttrf
+
+   spttrs
+   dpttrs
+   cpttrs
+   zpttrs
+
+   spteqr
+   dpteqr
+   cpteqr
+   zpteqr
+
+   crot
+   zrot
+
+   ssbev
+   dsbev
+
+   ssbevd
+   dsbevd
+
+   ssbevx
+   dsbevx
+
+   ssfrk
+   dsfrk
+
+   sstebz
+   dstebz
+
+   sstein
+   dstein
+
+   sstemr
+   dstemr
+
+   sstemr_lwork
+   dstemr_lwork
+
+   ssterf
+   dsterf
+
+   sstev
+   dstev
+
+   ssycon
+   dsycon
+   csycon
+   zsycon
+
+   ssyconv
+   dsyconv
+   csyconv
+   zsyconv
+
+   ssyequb
+   dsyequb
+   csyequb
+   zsyequb
+
+   ssyev
+   dsyev
+
+   ssyev_lwork
+   dsyev_lwork
+
+   ssyevd
+   dsyevd
+
+   ssyevd_lwork
+   dsyevd_lwork
+
+   ssyevr
+   dsyevr
+
+   ssyevr_lwork
+   dsyevr_lwork
+
+   ssyevx
+   dsyevx
+
+   ssyevx_lwork
+   dsyevx_lwork
+
+   ssygst
+   dsygst
+
+   ssygv
+   dsygv
+
+   ssygv_lwork
+   dsygv_lwork
+
+   ssygvd
+   dsygvd
+
+   ssygvx
+   dsygvx
+
+   ssygvx_lwork
+   dsygvx_lwork
+
+   ssysv
+   dsysv
+   csysv
+   zsysv
+
+   ssysv_lwork
+   dsysv_lwork
+   csysv_lwork
+   zsysv_lwork
+
+   ssysvx
+   dsysvx
+   csysvx
+   zsysvx
+
+   ssysvx_lwork
+   dsysvx_lwork
+   csysvx_lwork
+   zsysvx_lwork
+
+   ssytf2
+   dsytf2
+   csytf2
+   zsytf2
+
+   ssytrd
+   dsytrd
+
+   ssytrd_lwork
+   dsytrd_lwork
+
+   ssytrf
+   dsytrf
+   csytrf
+   zsytrf
+
+   ssytrf_lwork
+   dsytrf_lwork
+   csytrf_lwork
+   zsytrf_lwork
+
+   ssytrs
+   dsytrs
+   csytrs
+   zsytrs
+
+   stbtrs
+   dtbtrs
+   ctbtrs
+   ztbtrs
+
+   stfsm
+   dtfsm
+   ctfsm
+   ztfsm
+
+   stfttp
+   dtfttp
+   ctfttp
+   ztfttp
+
+   stfttr
+   dtfttr
+   ctfttr
+   ztfttr
+
+   stgexc
+   dtgexc
+   ctgexc
+   ztgexc
+
+   stgsen
+   dtgsen
+   ctgsen
+   ztgsen
+
+   stgsen_lwork
+   dtgsen_lwork
+   ctgsen_lwork
+   ztgsen_lwork
+
+   stgsyl
+   dtgsyl
+
+   stpttf
+   dtpttf
+   ctpttf
+   ztpttf
+
+   stpttr
+   dtpttr
+   ctpttr
+   ztpttr
+
+   strcon
+   dtrcon
+   ctrcon
+   ztrcon
+
+   strexc
+   dtrexc
+   ctrexc
+   ztrexc
+
+   strsen
+   dtrsen
+   ctrsen
+   ztrsen
+
+   strsen_lwork
+   dtrsen_lwork
+   ctrsen_lwork
+   ztrsen_lwork
+
+   strsyl
+   dtrsyl
+   ctrsyl
+   ztrsyl
+
+   strtri
+   dtrtri
+   ctrtri
+   ztrtri
+
+   strtrs
+   dtrtrs
+   ctrtrs
+   ztrtrs
+
+   strttf
+   dtrttf
+   ctrttf
+   ztrttf
+
+   strttp
+   dtrttp
+   ctrttp
+   ztrttp
+
+   stzrzf
+   dtzrzf
+   ctzrzf
+   ztzrzf
+
+   stzrzf_lwork
+   dtzrzf_lwork
+   ctzrzf_lwork
+   ztzrzf_lwork
+
+   cunghr
+   zunghr
+
+   cunghr_lwork
+   zunghr_lwork
+
+   cungqr
+   zungqr
+
+   cungrq
+   zungrq
+
+   cunmqr
+   zunmqr
+
+   sgeqrt
+   dgeqrt
+   cgeqrt
+   zgeqrt
+
+   sgemqrt
+   dgemqrt
+   cgemqrt
+   zgemqrt
+
+   sgttrf
+   dgttrf
+   cgttrf
+   zgttrf
+
+   sgttrs
+   dgttrs
+   cgttrs
+   zgttrs
+
+   sgtcon
+   dgtcon
+   cgtcon
+   zgtcon
+
+   stpqrt
+   dtpqrt
+   ctpqrt
+   ztpqrt
+
+   stpmqrt
+   dtpmqrt
+   ctpmqrt
+   ztpmqrt
+
+   cuncsd
+   zuncsd
+
+   cuncsd_lwork
+   zuncsd_lwork
+
+   cunmrz
+   zunmrz
+
+   cunmrz_lwork
+   zunmrz_lwork
+
+   ilaver
+
+"""
+#
+# Author: Pearu Peterson, March 2002
+#
+
+import numpy as np
+from .blas import _get_funcs, _memoize_get_funcs
+from scipy.linalg import _flapack
+from re import compile as regex_compile
+try:
+    from scipy.linalg import _clapack
+except ImportError:
+    _clapack = None
+
+try:
+    from scipy.linalg import _flapack_64
+    HAS_ILP64 = True
+except ImportError:
+    HAS_ILP64 = False
+    _flapack_64 = None
+
+
+# Expose all functions (only flapack --- clapack is an implementation detail)
+empty_module = None
+from scipy.linalg._flapack import *  # noqa: E402, F403
+del empty_module
+
+__all__ = ['get_lapack_funcs']
+
+# some convenience alias for complex functions
+_lapack_alias = {
+    'corghr': 'cunghr', 'zorghr': 'zunghr',
+    'corghr_lwork': 'cunghr_lwork', 'zorghr_lwork': 'zunghr_lwork',
+    'corgqr': 'cungqr', 'zorgqr': 'zungqr',
+    'cormqr': 'cunmqr', 'zormqr': 'zunmqr',
+    'corgrq': 'cungrq', 'zorgrq': 'zungrq',
+}
+
+
+# Place guards against docstring rendering issues with special characters
+p1 = regex_compile(r'with bounds (?P.*?)( and (?P.*?) storage){0,1}\n')
+p2 = regex_compile(r'Default: (?P.*?)\n')
+
+
+def backtickrepl(m):
+    if m.group('s'):
+        return (f"with bounds ``{m.group('b')}`` with ``{m.group('s')}`` storage\n")
+    else:
+        return f"with bounds ``{m.group('b')}``\n"
+
+
+for routine in [ssyevr, dsyevr, cheevr, zheevr,
+                ssyevx, dsyevx, cheevx, zheevx,
+                ssygvd, dsygvd, chegvd, zhegvd]:
+    if routine.__doc__:
+        routine.__doc__ = p1.sub(backtickrepl, routine.__doc__)
+        routine.__doc__ = p2.sub('Default ``\\1``\n', routine.__doc__)
+    else:
+        continue
+
+del regex_compile, p1, p2, backtickrepl
+
+
+@_memoize_get_funcs
+def get_lapack_funcs(names, arrays=(), dtype=None, ilp64=False):
+    """Return available LAPACK function objects from names.
+
+    Arrays are used to determine the optimal prefix of LAPACK routines.
+
+    Parameters
+    ----------
+    names : str or sequence of str
+        Name(s) of LAPACK functions without type prefix.
+
+    arrays : sequence of ndarrays, optional
+        Arrays can be given to determine optimal prefix of LAPACK
+        routines. If not given, double-precision routines will be
+        used, otherwise the most generic type in arrays will be used.
+
+    dtype : str or dtype, optional
+        Data-type specifier. Not used if `arrays` is non-empty.
+
+    ilp64 : {True, False, 'preferred'}, optional
+        Whether to return ILP64 routine variant.
+        Choosing 'preferred' returns ILP64 routine if available, and
+        otherwise the 32-bit routine. Default: False
+
+    Returns
+    -------
+    funcs : list
+        List containing the found function(s).
+
+    Notes
+    -----
+    This routine automatically chooses between Fortran/C
+    interfaces. Fortran code is used whenever possible for arrays with
+    column major order. In all other cases, C code is preferred.
+
+    In LAPACK, the naming convention is that all functions start with a
+    type prefix, which depends on the type of the principal
+    matrix. These can be one of {'s', 'd', 'c', 'z'} for the NumPy
+    types {float32, float64, complex64, complex128} respectively, and
+    are stored in attribute ``typecode`` of the returned functions.
+
+    Examples
+    --------
+    Suppose we would like to use '?lange' routine which computes the selected
+    norm of an array. We pass our array in order to get the correct 'lange'
+    flavor.
+
+    >>> import numpy as np
+    >>> import scipy.linalg as LA
+    >>> rng = np.random.default_rng()
+
+    >>> a = rng.random((3,2))
+    >>> x_lange = LA.get_lapack_funcs('lange', (a,))
+    >>> x_lange.typecode
+    'd'
+    >>> x_lange = LA.get_lapack_funcs('lange',(a*1j,))
+    >>> x_lange.typecode
+    'z'
+
+    Several LAPACK routines work best when its internal WORK array has
+    the optimal size (big enough for fast computation and small enough to
+    avoid waste of memory). This size is determined also by a dedicated query
+    to the function which is often wrapped as a standalone function and
+    commonly denoted as ``###_lwork``. Below is an example for ``?sysv``
+
+    >>> a = rng.random((1000, 1000))
+    >>> b = rng.random((1000, 1)) * 1j
+    >>> # We pick up zsysv and zsysv_lwork due to b array
+    ... xsysv, xlwork = LA.get_lapack_funcs(('sysv', 'sysv_lwork'), (a, b))
+    >>> opt_lwork, _ = xlwork(a.shape[0])  # returns a complex for 'z' prefix
+    >>> udut, ipiv, x, info = xsysv(a, b, lwork=int(opt_lwork.real))
+
+    """
+    if isinstance(ilp64, str):
+        if ilp64 == 'preferred':
+            ilp64 = HAS_ILP64
+        else:
+            raise ValueError("Invalid value for 'ilp64'")
+
+    if not ilp64:
+        return _get_funcs(names, arrays, dtype,
+                          "LAPACK", _flapack, _clapack,
+                          "flapack", "clapack", _lapack_alias,
+                          ilp64=False)
+    else:
+        if not HAS_ILP64:
+            raise RuntimeError("LAPACK ILP64 routine requested, but Scipy "
+                               "compiled only with 32-bit BLAS")
+        return _get_funcs(names, arrays, dtype,
+                          "LAPACK", _flapack_64, None,
+                          "flapack_64", None, _lapack_alias,
+                          ilp64=True)
+
+
+_int32_max = np.iinfo(np.int32).max
+_int64_max = np.iinfo(np.int64).max
+
+
+def _compute_lwork(routine, *args, **kwargs):
+    """
+    Round floating-point lwork returned by lapack to integer.
+
+    Several LAPACK routines compute optimal values for LWORK, which
+    they return in a floating-point variable. However, for large
+    values of LWORK, single-precision floating point is not sufficient
+    to hold the exact value --- some LAPACK versions (<= 3.5.0 at
+    least) truncate the returned integer to single precision and in
+    some cases this can be smaller than the required value.
+
+    Examples
+    --------
+    >>> from scipy.linalg import lapack
+    >>> n = 5000
+    >>> s_r, s_lw = lapack.get_lapack_funcs(('sysvx', 'sysvx_lwork'))
+    >>> lwork = lapack._compute_lwork(s_lw, n)
+    >>> lwork
+    32000
+
+    """
+    dtype = getattr(routine, 'dtype', None)
+    int_dtype = getattr(routine, 'int_dtype', None)
+    ret = routine(*args, **kwargs)
+    if ret[-1] != 0:
+        raise ValueError("Internal work array size computation failed: "
+                         "%d" % (ret[-1],))
+
+    if len(ret) == 2:
+        return _check_work_float(ret[0].real, dtype, int_dtype)
+    else:
+        return tuple(_check_work_float(x.real, dtype, int_dtype)
+                     for x in ret[:-1])
+
+
+def _check_work_float(value, dtype, int_dtype):
+    """
+    Convert LAPACK-returned work array size float to integer,
+    carefully for single-precision types.
+    """
+
+    if dtype == np.float32 or dtype == np.complex64:
+        # Single-precision routine -- take next fp value to work
+        # around possible truncation in LAPACK code
+        value = np.nextafter(value, np.inf, dtype=np.float32)
+
+    value = int(value)
+    if int_dtype.itemsize == 4:
+        if value < 0 or value > _int32_max:
+            raise ValueError("Too large work array required -- computation "
+                             "cannot be performed with standard 32-bit"
+                             " LAPACK.")
+    elif int_dtype.itemsize == 8:
+        if value < 0 or value > _int64_max:
+            raise ValueError("Too large work array required -- computation"
+                             " cannot be performed with standard 64-bit"
+                             " LAPACK.")
+    return value
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/matfuncs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ec8123b3ad8df096d5791c29bb28cce8271d4ad
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/matfuncs.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'expm', 'cosm', 'sinm', 'tanm', 'coshm', 'sinhm',
+    'tanhm', 'logm', 'funm', 'signm', 'sqrtm',
+    'expm_frechet', 'expm_cond', 'fractional_matrix_power',
+    'khatri_rao', 'norm', 'solve', 'inv', 'svd', 'schur', 'rsf2csf'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="matfuncs",
+                                   private_modules=["_matfuncs"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/misc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fad087489c6a24c8e33df54b811b6c37a3a46d4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/misc.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'LinAlgError', 'LinAlgWarning', 'norm', 'get_blas_funcs',
+    'get_lapack_funcs'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="misc",
+                                   private_modules=["_misc"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/special_matrices.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..a881ce765dfa3a3c4c2853c405f8129aafc615b5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/special_matrices.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'toeplitz', 'circulant', 'hankel',
+    'hadamard', 'leslie', 'kron', 'block_diag', 'companion',
+    'helmert', 'hilbert', 'invhilbert', 'pascal', 'invpascal', 'dft',
+    'fiedler', 'fiedler_companion', 'convolution_matrix'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="linalg", module="special_matrices",
+                                   private_modules=["_special_matrices"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..3954d08791cceb3a2b66669fe3c0ec4180089208
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/extending.pyx
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+#cython: language_level=3
+#cython: boundscheck=False
+#cython: wraparound=False
+
+cimport scipy.linalg
+from scipy.linalg.cython_blas cimport cdotu
+from scipy.linalg.cython_lapack cimport dgtsv
+
+cpdef tridiag(double[:] a, double[:] b, double[:] c, double[:] x):
+    """ Solve the system A y = x for y where A is the tridiagonal matrix with
+    subdiagonal 'a', diagonal 'b', and superdiagonal 'c'. """
+    cdef int n=b.shape[0], nrhs=1, info
+    # Solution is written over the values in x.
+    dgtsv(&n, &nrhs, &a[0], &b[0], &c[0], &x[0], &n, &info)
+
+cpdef float complex complex_dot(float complex[:] cx, float complex[:] cy):
+    """ Take dot product of two complex vectors """
+    cdef:
+        int n = cx.shape[0]
+        int incx = cx.strides[0] // sizeof(cx[0])
+        int incy = cy.strides[0] // sizeof(cy[0])
+    return cdotu(&n, &cx[0], &incx, &cy[0], &incy)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..88f23170ac0bbe382d8470bd22a42a92d9473008
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/_cython_examples/meson.build
@@ -0,0 +1,27 @@
+project('random-build-examples', 'c', 'cpp', 'cython')
+
+fs = import('fs')
+
+py3 = import('python').find_installation(pure: false)
+
+cy = meson.get_compiler('cython')
+
+if not cy.version().version_compare('>=3.0.8')
+  error('tests requires Cython >= 3.0.8')
+endif
+
+py3.extension_module(
+  'extending',
+  'extending.pyx',
+  install: false,
+  c_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this
+)
+
+extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx')
+py3.extension_module(
+  'extending_cpp',
+  extending_cpp,
+  install: false,
+  override_options : ['cython_language=cpp'],
+  cpp_args: ['-DCYTHON_CCOMPLEX=0'] # see gh-18975 for why we need this
+)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe51dcc21824ae122a17376940d43e34ec9ac22c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_basic.py
@@ -0,0 +1,2059 @@
+import itertools
+
+import numpy as np
+from numpy import (arange, array, dot, zeros, identity, conjugate, transpose,
+                   float32)
+from numpy.random import random
+
+from numpy.testing import (assert_equal, assert_almost_equal, assert_,
+                           assert_array_almost_equal, assert_allclose,
+                           assert_array_equal, suppress_warnings)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.linalg import (solve, inv, det, lstsq, pinv, pinvh, norm,
+                          solve_banded, solveh_banded, solve_triangular,
+                          solve_circulant, circulant, LinAlgError, block_diag,
+                          matrix_balance, qr, LinAlgWarning)
+
+from scipy.linalg._testutils import assert_no_overwrite
+from scipy._lib._testutils import check_free_memory, IS_MUSL
+from scipy.linalg.blas import HAS_ILP64
+
+REAL_DTYPES = (np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+def _eps_cast(dtyp):
+    """Get the epsilon for dtype, possibly downcast to BLAS types."""
+    dt = dtyp
+    if dt == np.longdouble:
+        dt = np.float64
+    elif dt == np.clongdouble:
+        dt = np.complex128
+    return np.finfo(dt).eps
+
+
+class TestSolveBanded:
+
+    def test_real(self):
+        a = array([[1.0, 20, 0, 0],
+                   [-30, 4, 6, 0],
+                   [2, 1, 20, 2],
+                   [0, -1, 7, 14]])
+        ab = array([[0.0, 20, 6, 2],
+                    [1, 4, 20, 14],
+                    [-30, 1, 7, 0],
+                    [2, -1, 0, 0]])
+        l, u = 2, 1
+        b4 = array([10.0, 0.0, 2.0, 14.0])
+        b4by1 = b4.reshape(-1, 1)
+        b4by2 = array([[2, 1],
+                       [-30, 4],
+                       [2, 3],
+                       [1, 3]])
+        b4by4 = array([[1, 0, 0, 0],
+                       [0, 0, 0, 1],
+                       [0, 1, 0, 0],
+                       [0, 1, 0, 0]])
+        for b in [b4, b4by1, b4by2, b4by4]:
+            x = solve_banded((l, u), ab, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_complex(self):
+        a = array([[1.0, 20, 0, 0],
+                   [-30, 4, 6, 0],
+                   [2j, 1, 20, 2j],
+                   [0, -1, 7, 14]])
+        ab = array([[0.0, 20, 6, 2j],
+                    [1, 4, 20, 14],
+                    [-30, 1, 7, 0],
+                    [2j, -1, 0, 0]])
+        l, u = 2, 1
+        b4 = array([10.0, 0.0, 2.0, 14.0j])
+        b4by1 = b4.reshape(-1, 1)
+        b4by2 = array([[2, 1],
+                       [-30, 4],
+                       [2, 3],
+                       [1, 3]])
+        b4by4 = array([[1, 0, 0, 0],
+                       [0, 0, 0, 1j],
+                       [0, 1, 0, 0],
+                       [0, 1, 0, 0]])
+        for b in [b4, b4by1, b4by2, b4by4]:
+            x = solve_banded((l, u), ab, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_tridiag_real(self):
+        ab = array([[0.0, 20, 6, 2],
+                   [1, 4, 20, 14],
+                   [-30, 1, 7, 0]])
+        a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag(
+                                                                ab[2, :-1], -1)
+        b4 = array([10.0, 0.0, 2.0, 14.0])
+        b4by1 = b4.reshape(-1, 1)
+        b4by2 = array([[2, 1],
+                       [-30, 4],
+                       [2, 3],
+                       [1, 3]])
+        b4by4 = array([[1, 0, 0, 0],
+                       [0, 0, 0, 1],
+                       [0, 1, 0, 0],
+                       [0, 1, 0, 0]])
+        for b in [b4, b4by1, b4by2, b4by4]:
+            x = solve_banded((1, 1), ab, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_tridiag_complex(self):
+        ab = array([[0.0, 20, 6, 2j],
+                   [1, 4, 20, 14],
+                   [-30, 1, 7, 0]])
+        a = np.diag(ab[0, 1:], 1) + np.diag(ab[1, :], 0) + np.diag(
+                                                               ab[2, :-1], -1)
+        b4 = array([10.0, 0.0, 2.0, 14.0j])
+        b4by1 = b4.reshape(-1, 1)
+        b4by2 = array([[2, 1],
+                       [-30, 4],
+                       [2, 3],
+                       [1, 3]])
+        b4by4 = array([[1, 0, 0, 0],
+                       [0, 0, 0, 1],
+                       [0, 1, 0, 0],
+                       [0, 1, 0, 0]])
+        for b in [b4, b4by1, b4by2, b4by4]:
+            x = solve_banded((1, 1), ab, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_check_finite(self):
+        a = array([[1.0, 20, 0, 0],
+                   [-30, 4, 6, 0],
+                   [2, 1, 20, 2],
+                   [0, -1, 7, 14]])
+        ab = array([[0.0, 20, 6, 2],
+                    [1, 4, 20, 14],
+                    [-30, 1, 7, 0],
+                    [2, -1, 0, 0]])
+        l, u = 2, 1
+        b4 = array([10.0, 0.0, 2.0, 14.0])
+        x = solve_banded((l, u), ab, b4, check_finite=False)
+        assert_array_almost_equal(dot(a, x), b4)
+
+    def test_bad_shape(self):
+        ab = array([[0.0, 20, 6, 2],
+                    [1, 4, 20, 14],
+                    [-30, 1, 7, 0],
+                    [2, -1, 0, 0]])
+        l, u = 2, 1
+        bad = array([1.0, 2.0, 3.0, 4.0]).reshape(-1, 4)
+        assert_raises(ValueError, solve_banded, (l, u), ab, bad)
+        assert_raises(ValueError, solve_banded, (l, u), ab, [1.0, 2.0])
+
+        # Values of (l,u) are not compatible with ab.
+        assert_raises(ValueError, solve_banded, (1, 1), ab, [1.0, 2.0])
+
+    def test_1x1(self):
+        # gh-8906 noted that the case of A@x = b with 1x1 A was handled
+        # incorrectly; check that this is resolved. Typical case:
+        # nupper == nlower == 0
+        # A = [[2]]
+        b = array([[1., 2., 3.]])
+        ref = array([[0.5, 1.0, 1.5]])
+        x = solve_banded((0, 0), [[2]], b)
+        assert_allclose(x, ref, rtol=1e-15)
+
+        # However, the user *can* represent the same system with garbage rows
+        # in `ab`. Test the case with `nupper == 1, nlower == 1`.
+        x = solve_banded((1, 1), [[0], [2], [0]], b)
+        assert_allclose(x, ref, rtol=1e-15)
+        assert_equal(x.dtype, np.dtype('f8'))
+        assert_array_equal(b, [[1.0, 2.0, 3.0]])
+
+    def test_native_list_arguments(self):
+        a = [[1.0, 20, 0, 0],
+             [-30, 4, 6, 0],
+             [2, 1, 20, 2],
+             [0, -1, 7, 14]]
+        ab = [[0.0, 20, 6, 2],
+              [1, 4, 20, 14],
+              [-30, 1, 7, 0],
+              [2, -1, 0, 0]]
+        l, u = 2, 1
+        b = [10.0, 0.0, 2.0, 14.0]
+        x = solve_banded((l, u), ab, b)
+        assert_array_almost_equal(dot(a, x), b)
+
+    @pytest.mark.thread_unsafe  # due to Cython fused types, see cython#6506
+    @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_ab, dt_b):
+        # ab contains one empty row corresponding to the diagonal
+        ab = np.array([[]], dtype=dt_ab)
+        b = np.array([], dtype=dt_b)
+        x = solve_banded((0, 0), ab, b)
+
+        assert x.shape == (0,)
+        assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+        b = np.empty((0, 0), dtype=dt_b)
+        x = solve_banded((0, 0), ab, b)
+
+        assert x.shape == (0, 0)
+        assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+
+class TestSolveHBanded:
+
+    def test_01_upper(self):
+        # Solve
+        # [ 4 1 2 0]     [1]
+        # [ 1 4 1 2] X = [4]
+        # [ 2 1 4 1]     [1]
+        # [ 0 2 1 4]     [2]
+        # with the RHS as a 1D array.
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0, 2.0])
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+    def test_02_upper(self):
+        # Solve
+        # [ 4 1 2 0]     [1 6]
+        # [ 1 4 1 2] X = [4 2]
+        # [ 2 1 4 1]     [1 6]
+        # [ 0 2 1 4]     [2 1]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([[1.0, 6.0],
+                   [4.0, 2.0],
+                   [1.0, 6.0],
+                   [2.0, 1.0]])
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0],
+                          [0.0, 0.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_03_upper(self):
+        # Solve
+        # [ 4 1 2 0]     [1]
+        # [ 1 4 1 2] X = [4]
+        # [ 2 1 4 1]     [1]
+        # [ 0 2 1 4]     [2]
+        # with the RHS as a 2D array with shape (3,1).
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0, 2.0]).reshape(-1, 1)
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, array([0., 1., 0., 0.]).reshape(-1, 1))
+
+    def test_01_lower(self):
+        # Solve
+        # [ 4 1 2 0]     [1]
+        # [ 1 4 1 2] X = [4]
+        # [ 2 1 4 1]     [1]
+        # [ 0 2 1 4]     [2]
+        #
+        ab = array([[4.0, 4.0, 4.0, 4.0],
+                    [1.0, 1.0, 1.0, -99],
+                    [2.0, 2.0, 0.0, 0.0]])
+        b = array([1.0, 4.0, 1.0, 2.0])
+        x = solveh_banded(ab, b, lower=True)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+    def test_02_lower(self):
+        # Solve
+        # [ 4 1 2 0]     [1 6]
+        # [ 1 4 1 2] X = [4 2]
+        # [ 2 1 4 1]     [1 6]
+        # [ 0 2 1 4]     [2 1]
+        #
+        ab = array([[4.0, 4.0, 4.0, 4.0],
+                    [1.0, 1.0, 1.0, -99],
+                    [2.0, 2.0, 0.0, 0.0]])
+        b = array([[1.0, 6.0],
+                   [4.0, 2.0],
+                   [1.0, 6.0],
+                   [2.0, 1.0]])
+        x = solveh_banded(ab, b, lower=True)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0],
+                          [0.0, 0.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_01_float32(self):
+        # Solve
+        # [ 4 1 2 0]     [1]
+        # [ 1 4 1 2] X = [4]
+        # [ 2 1 4 1]     [1]
+        # [ 0 2 1 4]     [2]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]], dtype=float32)
+        b = array([1.0, 4.0, 1.0, 2.0], dtype=float32)
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+    def test_02_float32(self):
+        # Solve
+        # [ 4 1 2 0]     [1 6]
+        # [ 1 4 1 2] X = [4 2]
+        # [ 2 1 4 1]     [1 6]
+        # [ 0 2 1 4]     [2 1]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, 1.0, 1.0, 1.0],
+                    [4.0, 4.0, 4.0, 4.0]], dtype=float32)
+        b = array([[1.0, 6.0],
+                   [4.0, 2.0],
+                   [1.0, 6.0],
+                   [2.0, 1.0]], dtype=float32)
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0],
+                          [0.0, 0.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_01_complex(self):
+        # Solve
+        # [ 4 -j  2  0]     [2-j]
+        # [ j  4 -j  2] X = [4-j]
+        # [ 2  j  4 -j]     [4+j]
+        # [ 0  2  j  4]     [2+j]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, -1.0j, -1.0j, -1.0j],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([2-1.0j, 4.0-1j, 4+1j, 2+1j])
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0])
+
+    def test_02_complex(self):
+        # Solve
+        # [ 4 -j  2  0]     [2-j 2+4j]
+        # [ j  4 -j  2] X = [4-j -1-j]
+        # [ 2  j  4 -j]     [4+j 4+2j]
+        # [ 0  2  j  4]     [2+j j]
+        #
+        ab = array([[0.0, 0.0, 2.0, 2.0],
+                    [-99, -1.0j, -1.0j, -1.0j],
+                    [4.0, 4.0, 4.0, 4.0]])
+        b = array([[2-1j, 2+4j],
+                   [4.0-1j, -1-1j],
+                   [4.0+1j, 4+2j],
+                   [2+1j, 1j]])
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0j],
+                          [1.0, 0.0],
+                          [1.0, 1.0],
+                          [0.0, 0.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_tridiag_01_upper(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        # with the RHS as a 1D array.
+        ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0])
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+    def test_tridiag_02_upper(self):
+        # Solve
+        # [ 4 1 0]     [1 4]
+        # [ 1 4 1] X = [4 2]
+        # [ 0 1 4]     [1 4]
+        #
+        ab = array([[-99, 1.0, 1.0],
+                    [4.0, 4.0, 4.0]])
+        b = array([[1.0, 4.0],
+                   [4.0, 2.0],
+                   [1.0, 4.0]])
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_tridiag_03_upper(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        # with the RHS as a 2D array with shape (3,1).
+        ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0]).reshape(-1, 1)
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1))
+
+    def test_tridiag_01_lower(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        #
+        ab = array([[4.0, 4.0, 4.0],
+                    [1.0, 1.0, -99]])
+        b = array([1.0, 4.0, 1.0])
+        x = solveh_banded(ab, b, lower=True)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+    def test_tridiag_02_lower(self):
+        # Solve
+        # [ 4 1 0]     [1 4]
+        # [ 1 4 1] X = [4 2]
+        # [ 0 1 4]     [1 4]
+        #
+        ab = array([[4.0, 4.0, 4.0],
+                    [1.0, 1.0, -99]])
+        b = array([[1.0, 4.0],
+                   [4.0, 2.0],
+                   [1.0, 4.0]])
+        x = solveh_banded(ab, b, lower=True)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_tridiag_01_float32(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        #
+        ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
+        b = array([1.0, 4.0, 1.0], dtype=float32)
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+    def test_tridiag_02_float32(self):
+        # Solve
+        # [ 4 1 0]     [1 4]
+        # [ 1 4 1] X = [4 2]
+        # [ 0 1 4]     [1 4]
+        #
+        ab = array([[-99, 1.0, 1.0],
+                    [4.0, 4.0, 4.0]], dtype=float32)
+        b = array([[1.0, 4.0],
+                   [4.0, 2.0],
+                   [1.0, 4.0]], dtype=float32)
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0],
+                          [1.0, 0.0],
+                          [0.0, 1.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_tridiag_01_complex(self):
+        # Solve
+        # [ 4 -j 0]     [ -j]
+        # [ j 4 -j] X = [4-j]
+        # [ 0 j  4]     [4+j]
+        #
+        ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
+        b = array([-1.0j, 4.0-1j, 4+1j])
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 1.0])
+
+    def test_tridiag_02_complex(self):
+        # Solve
+        # [ 4 -j 0]     [ -j    4j]
+        # [ j 4 -j] X = [4-j  -1-j]
+        # [ 0 j  4]     [4+j   4  ]
+        #
+        ab = array([[-99, -1.0j, -1.0j],
+                    [4.0, 4.0, 4.0]])
+        b = array([[-1j, 4.0j],
+                   [4.0-1j, -1.0-1j],
+                   [4.0+1j, 4.0]])
+        x = solveh_banded(ab, b)
+        expected = array([[0.0, 1.0j],
+                          [1.0, 0.0],
+                          [1.0, 1.0]])
+        assert_array_almost_equal(x, expected)
+
+    def test_check_finite(self):
+        # Solve
+        # [ 4 1 0]     [1]
+        # [ 1 4 1] X = [4]
+        # [ 0 1 4]     [1]
+        # with the RHS as a 1D array.
+        ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
+        b = array([1.0, 4.0, 1.0])
+        x = solveh_banded(ab, b, check_finite=False)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0])
+
+    def test_bad_shapes(self):
+        ab = array([[-99, 1.0, 1.0],
+                    [4.0, 4.0, 4.0]])
+        b = array([[1.0, 4.0],
+                   [4.0, 2.0]])
+        assert_raises(ValueError, solveh_banded, ab, b)
+        assert_raises(ValueError, solveh_banded, ab, [1.0, 2.0])
+        assert_raises(ValueError, solveh_banded, ab, [1.0])
+
+    def test_1x1(self):
+        x = solveh_banded([[1]], [[1, 2, 3]])
+        assert_array_equal(x, [[1.0, 2.0, 3.0]])
+        assert_equal(x.dtype, np.dtype('f8'))
+
+    def test_native_list_arguments(self):
+        # Same as test_01_upper, using python's native list.
+        ab = [[0.0, 0.0, 2.0, 2.0],
+              [-99, 1.0, 1.0, 1.0],
+              [4.0, 4.0, 4.0, 4.0]]
+        b = [1.0, 4.0, 1.0, 2.0]
+        x = solveh_banded(ab, b)
+        assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
+
+    @pytest.mark.parametrize('dt_ab', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_ab, dt_b):
+        # ab contains one empty row corresponding to the diagonal
+        ab = np.array([[]], dtype=dt_ab)
+        b = np.array([], dtype=dt_b)
+        x = solveh_banded(ab, b)
+
+        assert x.shape == (0,)
+        assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+        b = np.empty((0, 0), dtype=dt_b)
+        x = solveh_banded(ab, b)
+
+        assert x.shape == (0, 0)
+        assert x.dtype == solve(np.eye(1, dtype=dt_ab), np.ones(1, dtype=dt_b)).dtype
+
+
+class TestSolve:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.thread_unsafe
+    def test_20Feb04_bug(self):
+        a = [[1, 1], [1.0, 0]]  # ok
+        x0 = solve(a, [1, 0j])
+        assert_array_almost_equal(dot(a, x0), [1, 0])
+
+        # gives failure with clapack.zgesv(..,rowmajor=0)
+        a = [[1, 1], [1.2, 0]]
+        b = [1, 0j]
+        x0 = solve(a, b)
+        assert_array_almost_equal(dot(a, x0), [1, 0])
+
+    def test_simple(self):
+        a = [[1, 20], [-30, 4]]
+        for b in ([[1, 0], [0, 1]],
+                  [1, 0],
+                  [[2, 1], [-30, 4]]
+                  ):
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_complex(self):
+        a = array([[5, 2], [2j, 4]], 'D')
+        for b in ([1j, 0],
+                  [[1j, 1j], [0, 2]],
+                  [1, 0j],
+                  array([1, 0], 'D'),
+                  ):
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_pos(self):
+        a = [[2, 3], [3, 5]]
+        for lower in [0, 1]:
+            for b in ([[1, 0], [0, 1]],
+                      [1, 0]
+                      ):
+                x = solve(a, b, assume_a='pos', lower=lower)
+                assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_pos_complexb(self):
+        a = [[5, 2], [2, 4]]
+        for b in ([1j, 0],
+                  [[1j, 1j], [0, 2]],
+                  ):
+            x = solve(a, b, assume_a='pos')
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_sym(self):
+        a = [[2, 3], [3, -5]]
+        for lower in [0, 1]:
+            for b in ([[1, 0], [0, 1]],
+                      [1, 0]
+                      ):
+                x = solve(a, b, assume_a='sym', lower=lower)
+                assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_sym_complexb(self):
+        a = [[5, 2], [2, -4]]
+        for b in ([1j, 0],
+                  [[1j, 1j], [0, 2]]
+                  ):
+            x = solve(a, b, assume_a='sym')
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_sym_complex(self):
+        a = [[5, 2+1j], [2+1j, -4]]
+        for b in ([1j, 0],
+                  [1, 0],
+                  [[1j, 1j], [0, 2]]
+                  ):
+            x = solve(a, b, assume_a='sym')
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_her_actuallysym(self):
+        a = [[2, 3], [3, -5]]
+        for lower in [0, 1]:
+            for b in ([[1, 0], [0, 1]],
+                      [1, 0],
+                      [1j, 0],
+                      ):
+                x = solve(a, b, assume_a='her', lower=lower)
+                assert_array_almost_equal(dot(a, x), b)
+
+    def test_simple_her(self):
+        a = [[5, 2+1j], [2-1j, -4]]
+        for b in ([1j, 0],
+                  [1, 0],
+                  [[1j, 1j], [0, 2]]
+                  ):
+            x = solve(a, b, assume_a='her')
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_nils_20Feb04(self):
+        n = 2
+        A = random([n, n])+random([n, n])*1j
+        X = zeros((n, n), 'D')
+        Ainv = inv(A)
+        R = identity(n)+identity(n)*0j
+        for i in arange(0, n):
+            r = R[:, i]
+            X[:, i] = solve(A, r)
+        assert_array_almost_equal(X, Ainv)
+
+    def test_random(self):
+
+        n = 20
+        a = random([n, n])
+        for i in range(n):
+            a[i, i] = 20*(.1+a[i, i])
+        for i in range(4):
+            b = random([n, 3])
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_random_complex(self):
+        n = 20
+        a = random([n, n]) + 1j * random([n, n])
+        for i in range(n):
+            a[i, i] = 20*(.1+a[i, i])
+        for i in range(2):
+            b = random([n, 3])
+            x = solve(a, b)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_random_sym(self):
+        n = 20
+        a = random([n, n])
+        for i in range(n):
+            a[i, i] = abs(20*(.1+a[i, i]))
+            for j in range(i):
+                a[i, j] = a[j, i]
+        for i in range(4):
+            b = random([n])
+            x = solve(a, b, assume_a="pos")
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_random_sym_complex(self):
+        n = 20
+        a = random([n, n])
+        a = a + 1j*random([n, n])
+        for i in range(n):
+            a[i, i] = abs(20*(.1+a[i, i]))
+            for j in range(i):
+                a[i, j] = conjugate(a[j, i])
+        b = random([n])+2j*random([n])
+        for i in range(2):
+            x = solve(a, b, assume_a="pos")
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_check_finite(self):
+        a = [[1, 20], [-30, 4]]
+        for b in ([[1, 0], [0, 1]], [1, 0],
+                  [[2, 1], [-30, 4]]):
+            x = solve(a, b, check_finite=False)
+            assert_array_almost_equal(dot(a, x), b)
+
+    def test_scalar_a_and_1D_b(self):
+        a = 1
+        b = [1, 2, 3]
+        x = solve(a, b)
+        assert_array_almost_equal(x.ravel(), b)
+        assert_(x.shape == (3,), 'Scalar_a_1D_b test returned wrong shape')
+
+    def test_simple2(self):
+        a = np.array([[1.80, 2.88, 2.05, -0.89],
+                      [525.00, -295.00, -95.00, -380.00],
+                      [1.58, -2.69, -2.90, -1.04],
+                      [-1.11, -0.66, -0.59, 0.80]])
+
+        b = np.array([[9.52, 18.47],
+                      [2435.00, 225.00],
+                      [0.77, -13.28],
+                      [-6.22, -6.21]])
+
+        x = solve(a, b)
+        assert_array_almost_equal(x, np.array([[1., -1, 3, -5],
+                                               [3, 2, 4, 1]]).T)
+
+    def test_simple_complex2(self):
+        a = np.array([[-1.34+2.55j, 0.28+3.17j, -6.39-2.20j, 0.72-0.92j],
+                      [-1.70-14.10j, 33.10-1.50j, -1.50+13.40j, 12.90+13.80j],
+                      [-3.29-2.39j, -1.91+4.42j, -0.14-1.35j, 1.72+1.35j],
+                      [2.41+0.39j, -0.56+1.47j, -0.83-0.69j, -1.96+0.67j]])
+
+        b = np.array([[26.26+51.78j, 31.32-6.70j],
+                      [64.30-86.80j, 158.60-14.20j],
+                      [-5.75+25.31j, -2.15+30.19j],
+                      [1.16+2.57j, -2.56+7.55j]])
+
+        x = solve(a, b)
+        assert_array_almost_equal(x, np. array([[1+1.j, -1-2.j],
+                                                [2-3.j, 5+1.j],
+                                                [-4-5.j, -3+4.j],
+                                                [6.j, 2-3.j]]))
+
+    def test_hermitian(self):
+        # An upper triangular matrix will be used for hermitian matrix a
+        a = np.array([[-1.84, 0.11-0.11j, -1.78-1.18j, 3.91-1.50j],
+                      [0, -4.63, -1.84+0.03j, 2.21+0.21j],
+                      [0, 0, -8.87, 1.58-0.90j],
+                      [0, 0, 0, -1.36]])
+        b = np.array([[2.98-10.18j, 28.68-39.89j],
+                      [-9.58+3.88j, -24.79-8.40j],
+                      [-0.77-16.05j, 4.23-70.02j],
+                      [7.79+5.48j, -35.39+18.01j]])
+        res = np.array([[2.+1j, -8+6j],
+                        [3.-2j, 7-2j],
+                        [-1+2j, -1+5j],
+                        [1.-1j, 3-4j]])
+        x = solve(a, b, assume_a='her')
+        assert_array_almost_equal(x, res)
+        # Also conjugate a and test for lower triangular data
+        x = solve(a.conj().T, b, assume_a='her', lower=True)
+        assert_array_almost_equal(x, res)
+
+    def test_pos_and_sym(self):
+        A = np.arange(1, 10).reshape(3, 3)
+        x = solve(np.tril(A)/9, np.ones(3), assume_a='pos')
+        assert_array_almost_equal(x, [9., 1.8, 1.])
+        x = solve(np.tril(A)/9, np.ones(3), assume_a='sym')
+        assert_array_almost_equal(x, [9., 1.8, 1.])
+
+    def test_singularity(self):
+        a = np.array([[1, 0, 0, 0, 0, 0, 1, 0, 1],
+                      [1, 1, 1, 0, 0, 0, 1, 0, 1],
+                      [0, 1, 1, 0, 0, 0, 1, 0, 1],
+                      [1, 0, 1, 1, 1, 1, 0, 0, 0],
+                      [1, 0, 1, 1, 1, 1, 0, 0, 0],
+                      [1, 0, 1, 1, 1, 1, 0, 0, 0],
+                      [1, 0, 1, 1, 1, 1, 0, 0, 0],
+                      [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                      [1, 1, 1, 1, 1, 1, 1, 1, 1]])
+        b = np.arange(9)[:, None]
+        assert_raises(LinAlgError, solve, a, b)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize('structure',
+                             ('diagonal', 'tridiagonal', 'lower triangular',
+                              'upper triangular', 'symmetric', 'hermitian',
+                              'positive definite', 'general', None))
+    def test_ill_condition_warning(self, structure):
+        rng = np.random.default_rng(234859349452)
+        n = 10
+        d = np.logspace(0, 50, n)
+        A = np.diag(d)
+        b = rng.random(size=n)
+        message = "Ill-conditioned matrix..."
+        with pytest.warns(LinAlgWarning, match=message):
+            solve(A, b, assume_a=structure)
+
+    def test_multiple_rhs(self):
+        a = np.eye(2)
+        b = np.random.rand(2, 3, 4)
+        x = solve(a, b)
+        assert_array_almost_equal(x, b)
+
+    def test_transposed_keyword(self):
+        A = np.arange(9).reshape(3, 3) + 1
+        x = solve(np.tril(A)/9, np.ones(3), transposed=True)
+        assert_array_almost_equal(x, [1.2, 0.2, 1])
+        x = solve(np.tril(A)/9, np.ones(3), transposed=False)
+        assert_array_almost_equal(x, [9, -5.4, -1.2])
+
+    def test_transposed_notimplemented(self):
+        a = np.eye(3).astype(complex)
+        with assert_raises(NotImplementedError):
+            solve(a, a, transposed=True)
+
+    def test_nonsquare_a(self):
+        assert_raises(ValueError, solve, [1, 2], 1)
+
+    def test_size_mismatch_with_1D_b(self):
+        assert_array_almost_equal(solve(np.eye(3), np.ones(3)), np.ones(3))
+        assert_raises(ValueError, solve, np.eye(3), np.ones(4))
+
+    def test_assume_a_keyword(self):
+        assert_raises(ValueError, solve, 1, 1, assume_a='zxcv')
+
+    @pytest.mark.skip(reason="Failure on OS X (gh-7500), "
+                             "crash on Windows (gh-8064)")
+    def test_all_type_size_routine_combinations(self):
+        sizes = [10, 100]
+        assume_as = ['gen', 'sym', 'pos', 'her']
+        dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+        for size, assume_a, dtype in itertools.product(sizes, assume_as,
+                                                       dtypes):
+            is_complex = dtype in (np.complex64, np.complex128)
+            if assume_a == 'her' and not is_complex:
+                continue
+
+            err_msg = (f"Failed for size: {size}, assume_a: {assume_a},"
+                       f"dtype: {dtype}")
+
+            a = np.random.randn(size, size).astype(dtype)
+            b = np.random.randn(size).astype(dtype)
+            if is_complex:
+                a = a + (1j*np.random.randn(size, size)).astype(dtype)
+
+            if assume_a == 'sym':  # Can still be complex but only symmetric
+                a = a + a.T
+            elif assume_a == 'her':  # Handle hermitian matrices here instead
+                a = a + a.T.conj()
+            elif assume_a == 'pos':
+                a = a.conj().T.dot(a) + 0.1*np.eye(size)
+
+            tol = 1e-12 if dtype in (np.float64, np.complex128) else 1e-6
+
+            if assume_a in ['gen', 'sym', 'her']:
+                # We revert the tolerance from before
+                #   4b4a6e7c34fa4060533db38f9a819b98fa81476c
+                if dtype in (np.float32, np.complex64):
+                    tol *= 10
+
+            x = solve(a, b, assume_a=assume_a)
+            assert_allclose(a.dot(x), b,
+                            atol=tol * size,
+                            rtol=tol * size,
+                            err_msg=err_msg)
+
+            if assume_a == 'sym' and dtype not in (np.complex64,
+                                                   np.complex128):
+                x = solve(a, b, assume_a=assume_a, transposed=True)
+                assert_allclose(a.dot(x), b,
+                                atol=tol * size,
+                                rtol=tol * size,
+                                err_msg=err_msg)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_a, dt_b):
+        a = np.empty((0, 0), dtype=dt_a)
+        b = np.empty(0, dtype=dt_b)
+        x = solve(a, b)
+
+        assert x.size == 0
+        dt_nonempty = solve(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b)).dtype
+        assert x.dtype == dt_nonempty
+
+    def test_empty_rhs(self):
+        a = np.eye(2)
+        b = [[], []]
+        x = solve(a, b)
+        assert_(x.size == 0, 'Returned array is not empty')
+        assert_(x.shape == (2, 0), 'Returned empty array shape is wrong')
+
+    @pytest.mark.parametrize('dtype', [np.float64, np.complex128])
+    # "pos" and "positive definite" need to be added
+    @pytest.mark.parametrize('assume_a', ['diagonal', 'tridiagonal', 'banded',
+                                          'lower triangular', 'upper triangular',
+                                          'symmetric', 'hermitian',
+                                          'general', 'sym', 'her', 'gen'])
+    @pytest.mark.parametrize('nrhs', [(), (5,)])
+    @pytest.mark.parametrize('transposed', [True, False])
+    @pytest.mark.parametrize('overwrite', [True, False])
+    @pytest.mark.parametrize('fortran', [True, False])
+    def test_structure_detection(self, dtype, assume_a, nrhs, transposed,
+                                 overwrite, fortran):
+        rng = np.random.default_rng(982345982439826)
+        n = 5 if not assume_a == 'banded' else 20
+        b = rng.random(size=(n,) + nrhs)
+        A = rng.random(size=(n, n))
+
+        if np.issubdtype(dtype, np.complexfloating):
+            b = b + rng.random(size=(n,) + nrhs) * 1j
+            A = A + rng.random(size=(n, n)) * 1j
+
+        if assume_a == 'diagonal':
+            A = np.diag(np.diag(A))
+        elif assume_a == 'lower triangular':
+            A = np.tril(A)
+        elif assume_a == 'upper triangular':
+            A = np.triu(A)
+        elif assume_a == 'tridiagonal':
+            A = (np.diag(np.diag(A))
+                 + np.diag(np.diag(A, -1), -1)
+                 + np.diag(np.diag(A, 1), 1))
+        elif assume_a == 'banded':
+            A = np.triu(np.tril(A, 2), -1)
+        elif assume_a in {'symmetric', 'sym'}:
+            A = A + A.T
+        elif assume_a in {'hermitian', 'her'}:
+            A = A + A.conj().T
+        elif assume_a in {'positive definite', 'pos'}:
+            A = A + A.T
+            A += np.diag(A.sum(axis=1))
+
+        if fortran:
+            A = np.asfortranarray(A)
+
+        A_copy = A.copy(order='A')
+        b_copy = b.copy()
+
+        if np.issubdtype(dtype, np.complexfloating) and transposed:
+            message = "scipy.linalg.solve can currently..."
+            with pytest.raises(NotImplementedError, match=message):
+                solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite,
+                      transposed=transposed)
+            return
+
+        res = solve(A, b, overwrite_a=overwrite, overwrite_b=overwrite,
+                    transposed=transposed, assume_a=assume_a)
+
+        # Check that solution this solution is *correct*
+        ref = np.linalg.solve(A_copy.T if transposed else A_copy, b_copy)
+        assert_allclose(res, ref)
+
+        # Check that `solve` correctly identifies the structure and returns
+        # *exactly* the same solution whether `assume_a` is specified or not
+        if assume_a != 'banded':  # structure detection removed for banded
+            assert_equal(solve(A_copy, b_copy, transposed=transposed), res)
+
+        # Check that overwrite was respected
+        if not overwrite:
+            assert_equal(A, A_copy)
+            assert_equal(b, b_copy)
+
+
+class TestSolveTriangular:
+
+    def test_simple(self):
+        """
+        solve_triangular on a simple 2x2 matrix.
+        """
+        A = array([[1, 0], [1, 2]])
+        b = [1, 1]
+        sol = solve_triangular(A, b, lower=True)
+        assert_array_almost_equal(sol, [1, 0])
+
+        # check that it works also for non-contiguous matrices
+        sol = solve_triangular(A.T, b, lower=False)
+        assert_array_almost_equal(sol, [.5, .5])
+
+        # and that it gives the same result as trans=1
+        sol = solve_triangular(A, b, lower=True, trans=1)
+        assert_array_almost_equal(sol, [.5, .5])
+
+        b = identity(2)
+        sol = solve_triangular(A, b, lower=True, trans=1)
+        assert_array_almost_equal(sol, [[1., -.5], [0, 0.5]])
+
+    def test_simple_complex(self):
+        """
+        solve_triangular on a simple 2x2 complex matrix
+        """
+        A = array([[1+1j, 0], [1j, 2]])
+        b = identity(2)
+        sol = solve_triangular(A, b, lower=True, trans=1)
+        assert_array_almost_equal(sol, [[.5-.5j, -.25-.25j], [0, 0.5]])
+
+        # check other option combinations with complex rhs
+        b = np.diag([1+1j, 1+2j])
+        sol = solve_triangular(A, b, lower=True, trans=0)
+        assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
+
+        sol = solve_triangular(A, b, lower=True, trans=1)
+        assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
+
+        sol = solve_triangular(A, b, lower=True, trans=2)
+        assert_array_almost_equal(sol, [[1j, -0.75-0.25j], [0, 0.5+1j]])
+
+        sol = solve_triangular(A.T, b, lower=False, trans=0)
+        assert_array_almost_equal(sol, [[1, 0.25-0.75j], [0, 0.5+1j]])
+
+        sol = solve_triangular(A.T, b, lower=False, trans=1)
+        assert_array_almost_equal(sol, [[1, 0], [-0.5j, 0.5+1j]])
+
+        sol = solve_triangular(A.T, b, lower=False, trans=2)
+        assert_array_almost_equal(sol, [[1j, 0], [-0.5, 0.5+1j]])
+
+    def test_check_finite(self):
+        """
+        solve_triangular on a simple 2x2 matrix.
+        """
+        A = array([[1, 0], [1, 2]])
+        b = [1, 1]
+        sol = solve_triangular(A, b, lower=True, check_finite=False)
+        assert_array_almost_equal(sol, [1, 0])
+
+    @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_a, dt_b):
+        a = np.empty((0, 0), dtype=dt_a)
+        b = np.empty(0, dtype=dt_b)
+        x = solve_triangular(a, b)
+
+        assert x.size == 0
+        dt_nonempty = solve_triangular(
+            np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b)
+        ).dtype
+        assert x.dtype == dt_nonempty
+
+    def test_empty_rhs(self):
+        a = np.eye(2)
+        b = [[], []]
+        x = solve_triangular(a, b)
+        assert_(x.size == 0, 'Returned array is not empty')
+        assert_(x.shape == (2, 0), 'Returned empty array shape is wrong')
+
+
+class TestInv:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_simple(self):
+        a = [[1, 2], [3, 4]]
+        a_inv = inv(a)
+        assert_array_almost_equal(dot(a, a_inv), np.eye(2))
+        a = [[1, 2, 3], [4, 5, 6], [7, 8, 10]]
+        a_inv = inv(a)
+        assert_array_almost_equal(dot(a, a_inv), np.eye(3))
+
+    def test_random(self):
+        n = 20
+        for i in range(4):
+            a = random([n, n])
+            for i in range(n):
+                a[i, i] = 20*(.1+a[i, i])
+            a_inv = inv(a)
+            assert_array_almost_equal(dot(a, a_inv),
+                                      identity(n))
+
+    def test_simple_complex(self):
+        a = [[1, 2], [3, 4j]]
+        a_inv = inv(a)
+        assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
+
+    def test_random_complex(self):
+        n = 20
+        for i in range(4):
+            a = random([n, n])+2j*random([n, n])
+            for i in range(n):
+                a[i, i] = 20*(.1+a[i, i])
+            a_inv = inv(a)
+            assert_array_almost_equal(dot(a, a_inv),
+                                      identity(n))
+
+    def test_check_finite(self):
+        a = [[1, 2], [3, 4]]
+        a_inv = inv(a, check_finite=False)
+        assert_array_almost_equal(dot(a, a_inv), [[1, 0], [0, 1]])
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        a_inv = inv(a)
+        assert a_inv.size == 0
+        assert a_inv.dtype == inv(np.eye(2, dtype=dt)).dtype
+
+
+class TestDet:
+    def setup_method(self):
+        self.rng = np.random.default_rng(1680305949878959)
+
+    def test_1x1_all_singleton_dims(self):
+        a = np.array([[1]])
+        deta = det(a)
+        assert deta.dtype.char == 'd'
+        assert np.isscalar(deta)
+        assert deta == 1.
+        a = np.array([[[[1]]]], dtype='f')
+        deta = det(a)
+        assert deta.dtype.char == 'd'
+        assert deta.shape == (1, 1)
+        assert_equal(deta, [[1.0]])
+        a = np.array([[[1 + 3.j]]], dtype=np.complex64)
+        deta = det(a)
+        assert deta.dtype.char == 'D'
+        assert deta.shape == (1,)
+        assert_equal(deta, [1.+3.j])
+
+    def test_1by1_stacked_input_output(self):
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
+        deta = det(a)
+        assert deta.dtype.char == 'd'
+        assert deta.shape == (4, 5)
+        assert_allclose(deta, np.squeeze(a))
+
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j)
+        deta = det(a)
+        assert deta.dtype.char == 'D'
+        assert deta.shape == (4, 5)
+        assert_allclose(deta, np.squeeze(a))
+
+    @pytest.mark.parametrize('shape', [[2, 2], [20, 20], [3, 2, 20, 20]])
+    def test_simple_det_shapes_real_complex(self, shape):
+        a = self.rng.uniform(-1., 1., size=shape)
+        d1, d2 = det(a), np.linalg.det(a)
+        assert_allclose(d1, d2)
+
+        b = self.rng.uniform(-1., 1., size=shape)*1j
+        b += self.rng.uniform(-0.5, 0.5, size=shape)
+        d3, d4 = det(b), np.linalg.det(b)
+        assert_allclose(d3, d4)
+
+    def test_for_known_det_values(self):
+        # Hadamard8
+        a = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
+                      [1, -1, 1, -1, 1, -1, 1, -1],
+                      [1, 1, -1, -1, 1, 1, -1, -1],
+                      [1, -1, -1, 1, 1, -1, -1, 1],
+                      [1, 1, 1, 1, -1, -1, -1, -1],
+                      [1, -1, 1, -1, -1, 1, -1, 1],
+                      [1, 1, -1, -1, -1, -1, 1, 1],
+                      [1, -1, -1, 1, -1, 1, 1, -1]])
+        assert_allclose(det(a), 4096.)
+
+        # consecutive number array always singular
+        assert_allclose(det(np.arange(25).reshape(5, 5)), 0.)
+
+        # simple anti-diagonal block array
+        # Upper right has det (-2+1j) and lower right has (-2-1j)
+        # det(a) = - (-2+1j) (-2-1j) = 5.
+        a = np.array([[0.+0.j, 0.+0.j, 0.-1.j, 1.-1.j],
+                      [0.+0.j, 0.+0.j, 1.+0.j, 0.-1.j],
+                      [0.+1.j, 1.+1.j, 0.+0.j, 0.+0.j],
+                      [1.+0.j, 0.+1.j, 0.+0.j, 0.+0.j]], dtype=np.complex64)
+        assert_allclose(det(a), 5.+0.j)
+
+        # Fiedler companion complexified
+        # >>> a = scipy.linalg.fiedler_companion(np.arange(1, 10))
+        a = np.array([[-2., -3., 1., 0., 0., 0., 0., 0.],
+                      [1., 0., 0., 0., 0., 0., 0., 0.],
+                      [0., -4., 0., -5., 1., 0., 0., 0.],
+                      [0., 1., 0., 0., 0., 0., 0., 0.],
+                      [0., 0., 0., -6., 0., -7., 1., 0.],
+                      [0., 0., 0., 1., 0., 0., 0., 0.],
+                      [0., 0., 0., 0., 0., -8., 0., -9.],
+                      [0., 0., 0., 0., 0., 1., 0., 0.]])*1.j
+        assert_allclose(det(a), 9.)
+
+    # g and G dtypes are handled differently in windows and other platforms
+    @pytest.mark.parametrize('typ', [x for x in np.typecodes['All'][:20]
+                                     if x not in 'gG'])
+    def test_sample_compatible_dtype_input(self, typ):
+        n = 4
+        a = self.rng.random([n, n]).astype(typ)  # value is not important
+        assert isinstance(det(a), (np.float64 | np.complex128))
+
+    def test_incompatible_dtype_input(self):
+        # Double backslashes needed for escaping pytest regex.
+        msg = 'cannot be cast to float\\(32, 64\\)'
+
+        for c, t in zip('SUO', ['bytes8', 'str32', 'object']):
+            with assert_raises(TypeError, match=msg):
+                det(np.array([['a', 'b']]*2, dtype=c))
+        with assert_raises(TypeError, match=msg):
+            det(np.array([[b'a', b'b']]*2, dtype='V'))
+        with assert_raises(TypeError, match=msg):
+            det(np.array([[100, 200]]*2, dtype='datetime64[s]'))
+        with assert_raises(TypeError, match=msg):
+            det(np.array([[100, 200]]*2, dtype='timedelta64[s]'))
+
+    def test_empty_edge_cases(self):
+        assert_allclose(det(np.empty([0, 0])), 1.)
+        assert_allclose(det(np.empty([0, 0, 0])), np.array([]))
+        assert_allclose(det(np.empty([3, 0, 0])), np.array([1., 1., 1.]))
+        with assert_raises(ValueError, match='Last 2 dimensions'):
+            det(np.empty([0, 0, 3]))
+        with assert_raises(ValueError, match='at least two-dimensional'):
+            det(np.array([]))
+        with assert_raises(ValueError, match='Last 2 dimensions'):
+            det(np.array([[]]))
+        with assert_raises(ValueError, match='Last 2 dimensions'):
+            det(np.array([[[]]]))
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty_dtype(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        d = det(a)
+        assert d.shape == ()
+        assert d.dtype == det(np.eye(2, dtype=dt)).dtype
+
+        a = np.empty((3, 0, 0), dtype=dt)
+        d = det(a)
+        assert d.shape == (3,)
+        assert d.dtype == det(np.zeros((3, 1, 1), dtype=dt)).dtype
+
+    def test_overwrite_a(self):
+        # If all conditions are met then input should be overwritten;
+        #   - dtype is one of 'fdFD'
+        #   - C-contiguous
+        #   - writeable
+        a = np.arange(9).reshape(3, 3).astype(np.float32)
+        ac = a.copy()
+        deta = det(ac, overwrite_a=True)
+        assert_allclose(deta, 0.)
+        assert not (a == ac).all()
+
+    def test_readonly_array(self):
+        a = np.array([[2., 0., 1.], [5., 3., -1.], [1., 1., 1.]])
+        a.setflags(write=False)
+        # overwrite_a will be overridden
+        assert_allclose(det(a, overwrite_a=True), 10.)
+
+    def test_simple_check_finite(self):
+        a = [[1, 2], [3, np.inf]]
+        with assert_raises(ValueError, match='array must not contain'):
+            det(a)
+
+
+def direct_lstsq(a, b, cmplx=0):
+    at = transpose(a)
+    if cmplx:
+        at = conjugate(at)
+    a1 = dot(at, a)
+    b1 = dot(at, b)
+    return solve(a1, b1)
+
+
+class TestLstsq:
+    lapack_drivers = ('gelsd', 'gelss', 'gelsy', None)
+
+    def test_simple_exact(self):
+        for dtype in REAL_DTYPES:
+            a = np.array([[1, 20], [-30, 4]], dtype=dtype)
+            for lapack_driver in TestLstsq.lapack_drivers:
+                for overwrite in (True, False):
+                    for bt in (((1, 0), (0, 1)), (1, 0),
+                               ((2, 1), (-30, 4))):
+                        # Store values in case they are overwritten
+                        # later
+                        a1 = a.copy()
+                        b = np.array(bt, dtype=dtype)
+                        b1 = b.copy()
+                        out = lstsq(a1, b1,
+                                    lapack_driver=lapack_driver,
+                                    overwrite_a=overwrite,
+                                    overwrite_b=overwrite)
+                        x = out[0]
+                        r = out[2]
+                        assert_(r == 2,
+                                f'expected efficient rank 2, got {r}')
+                        assert_allclose(dot(a, x), b,
+                                        atol=25 * _eps_cast(a1.dtype),
+                                        rtol=25 * _eps_cast(a1.dtype),
+                                        err_msg=f"driver: {lapack_driver}")
+
+    def test_simple_overdet(self):
+        for dtype in REAL_DTYPES:
+            a = np.array([[1, 2], [4, 5], [3, 4]], dtype=dtype)
+            b = np.array([1, 2, 3], dtype=dtype)
+            for lapack_driver in TestLstsq.lapack_drivers:
+                for overwrite in (True, False):
+                    # Store values in case they are overwritten later
+                    a1 = a.copy()
+                    b1 = b.copy()
+                    out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                                overwrite_a=overwrite,
+                                overwrite_b=overwrite)
+                    x = out[0]
+                    if lapack_driver == 'gelsy':
+                        residuals = np.sum((b - a.dot(x))**2)
+                    else:
+                        residuals = out[1]
+                    r = out[2]
+                    assert_(r == 2, f'expected efficient rank 2, got {r}')
+                    assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0),
+                                    residuals,
+                                    rtol=25 * _eps_cast(a1.dtype),
+                                    atol=25 * _eps_cast(a1.dtype),
+                                    err_msg=f"driver: {lapack_driver}")
+                    assert_allclose(x, (-0.428571428571429, 0.85714285714285),
+                                    rtol=25 * _eps_cast(a1.dtype),
+                                    atol=25 * _eps_cast(a1.dtype),
+                                    err_msg=f"driver: {lapack_driver}")
+
+    def test_simple_overdet_complex(self):
+        for dtype in COMPLEX_DTYPES:
+            a = np.array([[1+2j, 2], [4, 5], [3, 4]], dtype=dtype)
+            b = np.array([1, 2+4j, 3], dtype=dtype)
+            for lapack_driver in TestLstsq.lapack_drivers:
+                for overwrite in (True, False):
+                    # Store values in case they are overwritten later
+                    a1 = a.copy()
+                    b1 = b.copy()
+                    out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                                overwrite_a=overwrite,
+                                overwrite_b=overwrite)
+
+                    x = out[0]
+                    if lapack_driver == 'gelsy':
+                        res = b - a.dot(x)
+                        residuals = np.sum(res * res.conj())
+                    else:
+                        residuals = out[1]
+                    r = out[2]
+                    assert_(r == 2, f'expected efficient rank 2, got {r}')
+                    assert_allclose(abs((dot(a, x) - b)**2).sum(axis=0),
+                                    residuals,
+                                    rtol=25 * _eps_cast(a1.dtype),
+                                    atol=25 * _eps_cast(a1.dtype),
+                                    err_msg=f"driver: {lapack_driver}")
+                    assert_allclose(
+                                x, (-0.4831460674157303 + 0.258426966292135j,
+                                    0.921348314606741 + 0.292134831460674j),
+                                rtol=25 * _eps_cast(a1.dtype),
+                                atol=25 * _eps_cast(a1.dtype),
+                                err_msg=f"driver: {lapack_driver}")
+
+    def test_simple_underdet(self):
+        for dtype in REAL_DTYPES:
+            a = np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype)
+            b = np.array([1, 2], dtype=dtype)
+            for lapack_driver in TestLstsq.lapack_drivers:
+                for overwrite in (True, False):
+                    # Store values in case they are overwritten later
+                    a1 = a.copy()
+                    b1 = b.copy()
+                    out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                                overwrite_a=overwrite,
+                                overwrite_b=overwrite)
+
+                    x = out[0]
+                    r = out[2]
+                    assert_(r == 2, f'expected efficient rank 2, got {r}')
+                    assert_allclose(x, (-0.055555555555555, 0.111111111111111,
+                                        0.277777777777777),
+                                    rtol=25 * _eps_cast(a1.dtype),
+                                    atol=25 * _eps_cast(a1.dtype),
+                                    err_msg=f"driver: {lapack_driver}")
+
+    @pytest.mark.parametrize("dtype", REAL_DTYPES)
+    @pytest.mark.parametrize("n", (20, 200))
+    @pytest.mark.parametrize("lapack_driver", lapack_drivers)
+    @pytest.mark.parametrize("overwrite", (True, False))
+    def test_random_exact(self, dtype, n, lapack_driver, overwrite):
+        rng = np.random.RandomState(1234)
+
+        a = np.asarray(rng.random([n, n]), dtype=dtype)
+        for i in range(n):
+            a[i, i] = 20 * (0.1 + a[i, i])
+        for i in range(4):
+            b = np.asarray(rng.random([n, 3]), dtype=dtype)
+            # Store values in case they are overwritten later
+            a1 = a.copy()
+            b1 = b.copy()
+            out = lstsq(a1, b1,
+                        lapack_driver=lapack_driver,
+                        overwrite_a=overwrite,
+                        overwrite_b=overwrite)
+            x = out[0]
+            r = out[2]
+            assert_(r == n, f'expected efficient rank {n}, '
+                    f'got {r}')
+            if dtype is np.float32:
+                assert_allclose(
+                          dot(a, x), b,
+                          rtol=500 * _eps_cast(a1.dtype),
+                          atol=500 * _eps_cast(a1.dtype),
+                          err_msg=f"driver: {lapack_driver}")
+            else:
+                assert_allclose(
+                          dot(a, x), b,
+                          rtol=1000 * _eps_cast(a1.dtype),
+                          atol=1000 * _eps_cast(a1.dtype),
+                          err_msg=f"driver: {lapack_driver}")
+
+    @pytest.mark.skipif(IS_MUSL, reason="may segfault on Alpine, see gh-17630")
+    @pytest.mark.parametrize("dtype", COMPLEX_DTYPES)
+    @pytest.mark.parametrize("n", (20, 200))
+    @pytest.mark.parametrize("lapack_driver", lapack_drivers)
+    @pytest.mark.parametrize("overwrite", (True, False))
+    def test_random_complex_exact(self, dtype, n, lapack_driver, overwrite):
+        rng = np.random.RandomState(1234)
+
+        a = np.asarray(rng.random([n, n]) + 1j*rng.random([n, n]),
+                       dtype=dtype)
+        for i in range(n):
+            a[i, i] = 20 * (0.1 + a[i, i])
+        for i in range(2):
+            b = np.asarray(rng.random([n, 3]), dtype=dtype)
+            # Store values in case they are overwritten later
+            a1 = a.copy()
+            b1 = b.copy()
+            out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                        overwrite_a=overwrite,
+                        overwrite_b=overwrite)
+            x = out[0]
+            r = out[2]
+            assert_(r == n, f'expected efficient rank {n}, '
+                    f'got {r}')
+            if dtype is np.complex64:
+                assert_allclose(
+                          dot(a, x), b,
+                          rtol=400 * _eps_cast(a1.dtype),
+                          atol=400 * _eps_cast(a1.dtype),
+                          err_msg=f"driver: {lapack_driver}")
+            else:
+                assert_allclose(
+                          dot(a, x), b,
+                          rtol=1000 * _eps_cast(a1.dtype),
+                          atol=1000 * _eps_cast(a1.dtype),
+                          err_msg=f"driver: {lapack_driver}")
+
+    def test_random_overdet(self):
+        rng = np.random.RandomState(1234)
+        for dtype in REAL_DTYPES:
+            for (n, m) in ((20, 15), (200, 2)):
+                for lapack_driver in TestLstsq.lapack_drivers:
+                    for overwrite in (True, False):
+                        a = np.asarray(rng.random([n, m]), dtype=dtype)
+                        for i in range(m):
+                            a[i, i] = 20 * (0.1 + a[i, i])
+                        for i in range(4):
+                            b = np.asarray(rng.random([n, 3]), dtype=dtype)
+                            # Store values in case they are overwritten later
+                            a1 = a.copy()
+                            b1 = b.copy()
+                            out = lstsq(a1, b1,
+                                        lapack_driver=lapack_driver,
+                                        overwrite_a=overwrite,
+                                        overwrite_b=overwrite)
+                            x = out[0]
+                            r = out[2]
+                            assert_(r == m, f'expected efficient rank {m}, '
+                                    f'got {r}')
+                            assert_allclose(
+                                          x, direct_lstsq(a, b, cmplx=0),
+                                          rtol=25 * _eps_cast(a1.dtype),
+                                          atol=25 * _eps_cast(a1.dtype),
+                                          err_msg=f"driver: {lapack_driver}")
+
+    def test_random_complex_overdet(self):
+        rng = np.random.RandomState(1234)
+        for dtype in COMPLEX_DTYPES:
+            for (n, m) in ((20, 15), (200, 2)):
+                for lapack_driver in TestLstsq.lapack_drivers:
+                    for overwrite in (True, False):
+                        a = np.asarray(rng.random([n, m]) + 1j*rng.random([n, m]),
+                                       dtype=dtype)
+                        for i in range(m):
+                            a[i, i] = 20 * (0.1 + a[i, i])
+                        for i in range(2):
+                            b = np.asarray(rng.random([n, 3]), dtype=dtype)
+                            # Store values in case they are overwritten
+                            # later
+                            a1 = a.copy()
+                            b1 = b.copy()
+                            out = lstsq(a1, b1,
+                                        lapack_driver=lapack_driver,
+                                        overwrite_a=overwrite,
+                                        overwrite_b=overwrite)
+                            x = out[0]
+                            r = out[2]
+                            assert_(r == m, f'expected efficient rank {m}, '
+                                    f'got {r}')
+                            assert_allclose(
+                                      x, direct_lstsq(a, b, cmplx=1),
+                                      rtol=25 * _eps_cast(a1.dtype),
+                                      atol=25 * _eps_cast(a1.dtype),
+                                      err_msg=f"driver: {lapack_driver}")
+
+    def test_check_finite(self):
+        with suppress_warnings() as sup:
+            # On (some) OSX this tests triggers a warning (gh-7538)
+            sup.filter(RuntimeWarning,
+                       "internal gelsd driver lwork query error,.*"
+                       "Falling back to 'gelss' driver.")
+
+        at = np.array(((1, 20), (-30, 4)))
+        for dtype, bt, lapack_driver, overwrite, check_finite in \
+            itertools.product(REAL_DTYPES,
+                              (((1, 0), (0, 1)), (1, 0), ((2, 1), (-30, 4))),
+                              TestLstsq.lapack_drivers,
+                              (True, False),
+                              (True, False)):
+
+            a = at.astype(dtype)
+            b = np.array(bt, dtype=dtype)
+            # Store values in case they are overwritten
+            # later
+            a1 = a.copy()
+            b1 = b.copy()
+            out = lstsq(a1, b1, lapack_driver=lapack_driver,
+                        check_finite=check_finite, overwrite_a=overwrite,
+                        overwrite_b=overwrite)
+            x = out[0]
+            r = out[2]
+            assert_(r == 2, f'expected efficient rank 2, got {r}')
+            assert_allclose(dot(a, x), b,
+                            rtol=25 * _eps_cast(a.dtype),
+                            atol=25 * _eps_cast(a.dtype),
+                            err_msg=f"driver: {lapack_driver}")
+
+    def test_empty(self):
+        for a_shape, b_shape in (((0, 2), (0,)),
+                                 ((0, 4), (0, 2)),
+                                 ((4, 0), (4,)),
+                                 ((4, 0), (4, 2))):
+            b = np.ones(b_shape)
+            x, residues, rank, s = lstsq(np.zeros(a_shape), b)
+            assert_equal(x, np.zeros((a_shape[1],) + b_shape[1:]))
+            residues_should_be = (np.empty((0,)) if a_shape[1]
+                                  else np.linalg.norm(b, axis=0)**2)
+            assert_equal(residues, residues_should_be)
+            assert_(rank == 0, 'expected rank 0')
+            assert_equal(s, np.empty((0,)))
+
+    @pytest.mark.parametrize('dt_a', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty_dtype(self, dt_a, dt_b):
+        a = np.empty((0, 0), dtype=dt_a)
+        b = np.empty(0, dtype=dt_b)
+        x, residues, rank, s = lstsq(a, b)
+
+        assert x.size == 0
+        dt_nonempty = lstsq(np.eye(2, dtype=dt_a), np.ones(2, dtype=dt_b))[0].dtype
+        assert x.dtype == dt_nonempty
+
+
+class TestPinv:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_simple_real(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+        a_pinv = pinv(a)
+        assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
+
+    def test_simple_complex(self):
+        a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]],
+             dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]],
+                                       dtype=float))
+        a_pinv = pinv(a)
+        assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
+
+    def test_simple_singular(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
+        a_pinv = pinv(a)
+        expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01],
+                          [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02],
+                          [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]])
+        assert_array_almost_equal(a_pinv, expected)
+
+    def test_simple_cols(self):
+        a = array([[1, 2, 3], [4, 5, 6]], dtype=float)
+        a_pinv = pinv(a)
+        expected = array([[-0.94444444, 0.44444444],
+                          [-0.11111111, 0.11111111],
+                          [0.72222222, -0.22222222]])
+        assert_array_almost_equal(a_pinv, expected)
+
+    def test_simple_rows(self):
+        a = array([[1, 2], [3, 4], [5, 6]], dtype=float)
+        a_pinv = pinv(a)
+        expected = array([[-1.33333333, -0.33333333, 0.66666667],
+                          [1.08333333, 0.33333333, -0.41666667]])
+        assert_array_almost_equal(a_pinv, expected)
+
+    def test_check_finite(self):
+        a = array([[1, 2, 3], [4, 5, 6.], [7, 8, 10]])
+        a_pinv = pinv(a, check_finite=False)
+        assert_array_almost_equal(dot(a, a_pinv), np.eye(3))
+
+    def test_native_list_argument(self):
+        a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+        a_pinv = pinv(a)
+        expected = array([[-6.38888889e-01, -1.66666667e-01, 3.05555556e-01],
+                          [-5.55555556e-02, 1.30136518e-16, 5.55555556e-02],
+                          [5.27777778e-01, 1.66666667e-01, -1.94444444e-01]])
+        assert_array_almost_equal(a_pinv, expected)
+
+    def test_atol_rtol(self):
+        n = 12
+        # get a random ortho matrix for shuffling
+        q, _ = qr(np.random.rand(n, n))
+        a_m = np.arange(35.0).reshape(7, 5)
+        a = a_m.copy()
+        a[0, 0] = 0.001
+        atol = 1e-5
+        rtol = 0.05
+        # svds of a_m is ~ [116.906, 4.234, tiny, tiny, tiny]
+        # svds of a is ~ [116.906, 4.234, 4.62959e-04, tiny, tiny]
+        # Just abs cutoff such that we arrive at a_modified
+        a_p = pinv(a_m, atol=atol, rtol=0.)
+        adiff1 = a @ a_p @ a - a
+        adiff2 = a_m @ a_p @ a_m - a_m
+        # Now adiff1 should be around atol value while adiff2 should be
+        # relatively tiny
+        assert_allclose(np.linalg.norm(adiff1), 5e-4, atol=5.e-4)
+        assert_allclose(np.linalg.norm(adiff2), 5e-14, atol=5.e-14)
+
+        # Now do the same but remove another sv ~4.234 via rtol
+        a_p = pinv(a_m, atol=atol, rtol=rtol)
+        adiff1 = a @ a_p @ a - a
+        adiff2 = a_m @ a_p @ a_m - a_m
+        assert_allclose(np.linalg.norm(adiff1), 4.233, rtol=0.01)
+        assert_allclose(np.linalg.norm(adiff2), 4.233, rtol=0.01)
+
+    @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        a_pinv = pinv(a)
+        assert a_pinv.size == 0
+        assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype
+
+
+class TestPinvSymmetric:
+
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_simple_real(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+        a = np.dot(a, a.T)
+        a_pinv = pinvh(a)
+        assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
+
+    def test_nonpositive(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=float)
+        a = np.dot(a, a.T)
+        u, s, vt = np.linalg.svd(a)
+        s[0] *= -1
+        a = np.dot(u * s, vt)  # a is now symmetric non-positive and singular
+        a_pinv = pinv(a)
+        a_pinvh = pinvh(a)
+        assert_array_almost_equal(a_pinv, a_pinvh)
+
+    def test_simple_complex(self):
+        a = (array([[1, 2, 3], [4, 5, 6], [7, 8, 10]],
+             dtype=float) + 1j * array([[10, 8, 7], [6, 5, 4], [3, 2, 1]],
+                                       dtype=float))
+        a = np.dot(a, a.conj().T)
+        a_pinv = pinvh(a)
+        assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
+
+    def test_native_list_argument(self):
+        a = array([[1, 2, 3], [4, 5, 6], [7, 8, 10]], dtype=float)
+        a = np.dot(a, a.T)
+        a_pinv = pinvh(a.tolist())
+        assert_array_almost_equal(np.dot(a, a_pinv), np.eye(3))
+
+    def test_zero_eigenvalue(self):
+        # https://github.com/scipy/scipy/issues/12515
+        # the SYEVR eigh driver may give the zero eigenvalue > eps
+        a = np.array([[1, -1, 0], [-1, 2, -1], [0, -1, 1]])
+        p = pinvh(a)
+        assert_allclose(p @ a @ p, p, atol=1e-15)
+        assert_allclose(a @ p @ a, a, atol=1e-15)
+
+    def test_atol_rtol(self):
+        n = 12
+        # get a random ortho matrix for shuffling
+        q, _ = qr(np.random.rand(n, n))
+        a = np.diag([4, 3, 2, 1, 0.99e-4, 0.99e-5] + [0.99e-6]*(n-6))
+        a = q.T @ a @ q
+        a_m = np.diag([4, 3, 2, 1, 0.99e-4, 0.] + [0.]*(n-6))
+        a_m = q.T @ a_m @ q
+        atol = 1e-5
+        rtol = (4.01e-4 - 4e-5)/4
+        # Just abs cutoff such that we arrive at a_modified
+        a_p = pinvh(a, atol=atol, rtol=0.)
+        adiff1 = a @ a_p @ a - a
+        adiff2 = a_m @ a_p @ a_m - a_m
+        # Now adiff1 should dance around atol value since truncation
+        # while adiff2 should be relatively tiny
+        assert_allclose(norm(adiff1), atol, rtol=0.1)
+        assert_allclose(norm(adiff2), 1e-12, atol=1e-11)
+
+        # Now do the same but through rtol cancelling atol value
+        a_p = pinvh(a, atol=atol, rtol=rtol)
+        adiff1 = a @ a_p @ a - a
+        adiff2 = a_m @ a_p @ a_m - a_m
+        # adiff1 and adiff2 should be elevated to ~1e-4 due to mismatch
+        assert_allclose(norm(adiff1), 1e-4, rtol=0.1)
+        assert_allclose(norm(adiff2), 1e-4, rtol=0.1)
+
+    @pytest.mark.parametrize('dt', [float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        a_pinv = pinvh(a)
+        assert a_pinv.size == 0
+        assert a_pinv.dtype == pinv(np.eye(2, dtype=dt)).dtype
+
+
+@pytest.mark.parametrize('scale', (1e-20, 1., 1e20))
+@pytest.mark.parametrize('pinv_', (pinv, pinvh))
+def test_auto_rcond(scale, pinv_):
+    x = np.array([[1, 0], [0, 1e-10]]) * scale
+    expected = np.diag(1. / np.diag(x))
+    x_inv = pinv_(x)
+    assert_allclose(x_inv, expected)
+
+
+class TestVectorNorms:
+
+    def test_types(self):
+        for dtype in np.typecodes['AllFloat']:
+            x = np.array([1, 2, 3], dtype=dtype)
+            tol = max(1e-15, np.finfo(dtype).eps.real * 20)
+            assert_allclose(norm(x), np.sqrt(14), rtol=tol)
+            assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
+
+        for dtype in np.typecodes['Complex']:
+            x = np.array([1j, 2j, 3j], dtype=dtype)
+            tol = max(1e-15, np.finfo(dtype).eps.real * 20)
+            assert_allclose(norm(x), np.sqrt(14), rtol=tol)
+            assert_allclose(norm(x, 2), np.sqrt(14), rtol=tol)
+
+    def test_overflow(self):
+        # unlike numpy's norm, this one is
+        # safer on overflow
+        a = array([1e20], dtype=float32)
+        assert_almost_equal(norm(a), a)
+
+    def test_stable(self):
+        # more stable than numpy's norm
+        a = array([1e4] + [1]*10000, dtype=float32)
+        try:
+            # snrm in double precision; we obtain the same as for float64
+            # -- large atol needed due to varying blas implementations
+            assert_allclose(norm(a) - 1e4, 0.5, atol=1e-2)
+        except AssertionError:
+            # snrm implemented in single precision, == np.linalg.norm result
+            msg = ": Result should equal either 0.0 or 0.5 (depending on " \
+                  "implementation of snrm2)."
+            assert_almost_equal(norm(a) - 1e4, 0.0, err_msg=msg)
+
+    def test_zero_norm(self):
+        assert_equal(norm([1, 0, 3], 0), 2)
+        assert_equal(norm([1, 2, 3], 0), 3)
+
+    def test_axis_kwd(self):
+        a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
+        assert_allclose(norm(a, axis=1), [[3.60555128, 4.12310563]] * 2)
+        assert_allclose(norm(a, 1, axis=1), [[5.] * 2] * 2)
+
+    def test_keepdims_kwd(self):
+        a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
+        b = norm(a, axis=1, keepdims=True)
+        assert_allclose(b, [[[3.60555128, 4.12310563]]] * 2)
+        assert_(b.shape == (2, 1, 2))
+        assert_allclose(norm(a, 1, axis=2, keepdims=True), [[[3.], [7.]]] * 2)
+
+    @pytest.mark.skipif(not HAS_ILP64, reason="64-bit BLAS required")
+    def test_large_vector(self):
+        check_free_memory(free_mb=17000)
+        x = np.zeros([2**31], dtype=np.float64)
+        x[-1] = 1
+        res = norm(x)
+        del x
+        assert_allclose(res, 1.0)
+
+
+class TestMatrixNorms:
+
+    def test_matrix_norms(self):
+        # Not all of these are matrix norms in the most technical sense.
+        np.random.seed(1234)
+        for n, m in (1, 1), (1, 3), (3, 1), (4, 4), (4, 5), (5, 4):
+            for t in np.float32, np.float64, np.complex64, np.complex128, np.int64:
+                A = 10 * np.random.randn(n, m).astype(t)
+                if np.issubdtype(A.dtype, np.complexfloating):
+                    A = (A + 10j * np.random.randn(n, m)).astype(t)
+                    t_high = np.complex128
+                else:
+                    t_high = np.float64
+                for order in (None, 'fro', 1, -1, 2, -2, np.inf, -np.inf):
+                    actual = norm(A, ord=order)
+                    desired = np.linalg.norm(A, ord=order)
+                    # SciPy may return higher precision matrix norms.
+                    # This is a consequence of using LAPACK.
+                    if not np.allclose(actual, desired):
+                        desired = np.linalg.norm(A.astype(t_high), ord=order)
+                        assert_allclose(actual, desired)
+
+    def test_axis_kwd(self):
+        a = np.array([[[2, 1], [3, 4]]] * 2, 'd')
+        b = norm(a, ord=np.inf, axis=(1, 0))
+        c = norm(np.swapaxes(a, 0, 1), ord=np.inf, axis=(0, 1))
+        d = norm(a, ord=1, axis=(0, 1))
+        assert_allclose(b, c)
+        assert_allclose(c, d)
+        assert_allclose(b, d)
+        assert_(b.shape == c.shape == d.shape)
+        b = norm(a, ord=1, axis=(1, 0))
+        c = norm(np.swapaxes(a, 0, 1), ord=1, axis=(0, 1))
+        d = norm(a, ord=np.inf, axis=(0, 1))
+        assert_allclose(b, c)
+        assert_allclose(c, d)
+        assert_allclose(b, d)
+        assert_(b.shape == c.shape == d.shape)
+
+    def test_keepdims_kwd(self):
+        a = np.arange(120, dtype='d').reshape(2, 3, 4, 5)
+        b = norm(a, ord=np.inf, axis=(1, 0), keepdims=True)
+        c = norm(a, ord=1, axis=(0, 1), keepdims=True)
+        assert_allclose(b, c)
+        assert_(b.shape == c.shape)
+
+    def test_empty(self):
+        a = np.empty((0, 0))
+        assert_allclose(norm(a), 0.)
+        assert_allclose(norm(a, axis=0), np.zeros((0,)))
+        assert_allclose(norm(a, keepdims=True), np.zeros((1, 1)))
+
+        a = np.empty((0, 3))
+        assert_allclose(norm(a), 0.)
+        assert_allclose(norm(a, axis=0), np.zeros((3,)))
+        assert_allclose(norm(a, keepdims=True), np.zeros((1, 1)))
+
+
+class TestOverwrite:
+    def test_solve(self):
+        assert_no_overwrite(solve, [(3, 3), (3,)])
+
+    def test_solve_triangular(self):
+        assert_no_overwrite(solve_triangular, [(3, 3), (3,)])
+
+    def test_solve_banded(self):
+        assert_no_overwrite(lambda ab, b: solve_banded((2, 1), ab, b),
+                            [(4, 6), (6,)])
+
+    def test_solveh_banded(self):
+        assert_no_overwrite(solveh_banded, [(2, 6), (6,)])
+
+    def test_inv(self):
+        assert_no_overwrite(inv, [(3, 3)])
+
+    def test_det(self):
+        assert_no_overwrite(det, [(3, 3)])
+
+    def test_lstsq(self):
+        assert_no_overwrite(lstsq, [(3, 2), (3,)])
+
+    def test_pinv(self):
+        assert_no_overwrite(pinv, [(3, 3)])
+
+    def test_pinvh(self):
+        assert_no_overwrite(pinvh, [(3, 3)])
+
+
+class TestSolveCirculant:
+
+    def test_basic1(self):
+        c = np.array([1, 2, 3, 5])
+        b = np.array([1, -1, 1, 0])
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_basic2(self):
+        # b is a 2-d matrix.
+        c = np.array([1, 2, -3, -5])
+        b = np.arange(12).reshape(4, 3)
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_basic3(self):
+        # b is a 3-d matrix.
+        c = np.array([1, 2, -3, -5])
+        b = np.arange(24).reshape(4, 3, 2)
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_complex(self):
+        # Complex b and c
+        c = np.array([1+2j, -3, 4j, 5])
+        b = np.arange(8).reshape(4, 2) + 0.5j
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_random_b_and_c(self):
+        # Random b and c
+        rng = np.random.RandomState(54321)
+        c = rng.randn(50)
+        b = rng.randn(50)
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    def test_singular(self):
+        # c gives a singular circulant matrix.
+        c = np.array([1, 1, 0, 0])
+        b = np.array([1, 2, 3, 4])
+        x = solve_circulant(c, b, singular='lstsq')
+        y, res, rnk, s = lstsq(circulant(c), b)
+        assert_allclose(x, y)
+        assert_raises(LinAlgError, solve_circulant, x, y)
+
+    def test_axis_args(self):
+        # Test use of caxis, baxis and outaxis.
+
+        # c has shape (2, 1, 4)
+        c = np.array([[[-1, 2.5, 3, 3.5]], [[1, 6, 6, 6.5]]])
+
+        # b has shape (3, 4)
+        b = np.array([[0, 0, 1, 1], [1, 1, 0, 0], [1, -1, 0, 0]])
+
+        x = solve_circulant(c, b, baxis=1)
+        assert_equal(x.shape, (4, 2, 3))
+        expected = np.empty_like(x)
+        expected[:, 0, :] = solve(circulant(c[0].ravel()), b.T)
+        expected[:, 1, :] = solve(circulant(c[1].ravel()), b.T)
+        assert_allclose(x, expected)
+
+        x = solve_circulant(c, b, baxis=1, outaxis=-1)
+        assert_equal(x.shape, (2, 3, 4))
+        assert_allclose(np.moveaxis(x, -1, 0), expected)
+
+        # np.swapaxes(c, 1, 2) has shape (2, 4, 1); b.T has shape (4, 3).
+        x = solve_circulant(np.swapaxes(c, 1, 2), b.T, caxis=1)
+        assert_equal(x.shape, (4, 2, 3))
+        assert_allclose(x, expected)
+
+    def test_native_list_arguments(self):
+        # Same as test_basic1 using python's native list.
+        c = [1, 2, 3, 5]
+        b = [1, -1, 1, 0]
+        x = solve_circulant(c, b)
+        y = solve(circulant(c), b)
+        assert_allclose(x, y)
+
+    @pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt_c, dt_b):
+        c = np.array([], dtype=dt_c)
+        b = np.array([], dtype=dt_b)
+        x = solve_circulant(c, b)
+        assert x.shape == (0,)
+        assert x.dtype == solve_circulant(np.arange(3, dtype=dt_c),
+                                          np.ones(3, dtype=dt_b)).dtype
+
+        b = np.empty((0, 0), dtype=dt_b)
+        x1 = solve_circulant(c, b)
+        assert x1.shape == (0, 0)
+        assert x1.dtype == x.dtype
+
+
+class TestMatrix_Balance:
+
+    def test_string_arg(self):
+        assert_raises(ValueError, matrix_balance, 'Some string for fail')
+
+    def test_infnan_arg(self):
+        assert_raises(ValueError, matrix_balance,
+                      np.array([[1, 2], [3, np.inf]]))
+        assert_raises(ValueError, matrix_balance,
+                      np.array([[1, 2], [3, np.nan]]))
+
+    def test_scaling(self):
+        _, y = matrix_balance(np.array([[1000, 1], [1000, 0]]))
+        # Pre/post LAPACK 3.5.0 gives the same result up to an offset
+        # since in each case col norm is x1000 greater and
+        # 1000 / 32 ~= 1 * 32 hence balanced with 2 ** 5.
+        assert_allclose(np.diff(np.log2(np.diag(y))), [5])
+
+    def test_scaling_order(self):
+        A = np.array([[1, 0, 1e-4], [1, 1, 1e-2], [1e4, 1e2, 1]])
+        x, y = matrix_balance(A)
+        assert_allclose(solve(y, A).dot(y), x)
+
+    def test_separate(self):
+        _, (y, z) = matrix_balance(np.array([[1000, 1], [1000, 0]]),
+                                   separate=1)
+        assert_equal(np.diff(np.log2(y)), [5])
+        assert_allclose(z, np.arange(2))
+
+    def test_permutation(self):
+        A = block_diag(np.ones((2, 2)), np.tril(np.ones((2, 2))),
+                       np.ones((3, 3)))
+        x, (y, z) = matrix_balance(A, separate=1)
+        assert_allclose(y, np.ones_like(y))
+        assert_allclose(z, np.array([0, 1, 6, 5, 4, 3, 2]))
+
+    def test_perm_and_scaling(self):
+        # Matrix with its diagonal removed
+        cases = (  # Case 0
+                 np.array([[0., 0., 0., 0., 0.000002],
+                           [0., 0., 0., 0., 0.],
+                           [2., 2., 0., 0., 0.],
+                           [2., 2., 0., 0., 0.],
+                           [0., 0., 0.000002, 0., 0.]]),
+                 #  Case 1 user reported GH-7258
+                 np.array([[-0.5, 0., 0., 0.],
+                           [0., -1., 0., 0.],
+                           [1., 0., -0.5, 0.],
+                           [0., 1., 0., -1.]]),
+                 #  Case 2 user reported GH-7258
+                 np.array([[-3., 0., 1., 0.],
+                           [-1., -1., -0., 1.],
+                           [-3., -0., -0., 0.],
+                           [-1., -0., 1., -1.]])
+                 )
+
+        for A in cases:
+            x, y = matrix_balance(A)
+            x, (s, p) = matrix_balance(A, separate=1)
+            ip = np.empty_like(p)
+            ip[p] = np.arange(A.shape[0])
+            assert_allclose(y, np.diag(s)[ip, :])
+            assert_allclose(solve(y, A).dot(y), x)
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        b, t = matrix_balance(a)
+
+        assert b.size == 0
+        assert t.size == 0
+
+        b_n, t_n = matrix_balance(np.eye(2, dtype=dt))
+        assert b.dtype == b_n.dtype
+        assert t.dtype == t_n.dtype
+
+        b, (scale, perm) = matrix_balance(a, separate=True)
+        assert b.size == 0
+        assert scale.size == 0
+        assert perm.size == 0
+
+        b_n, (scale_n, perm_n) = matrix_balance(a, separate=True)
+        assert b.dtype == b_n.dtype
+        assert scale.dtype == scale_n.dtype
+        assert perm.dtype == perm_n.dtype
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6645d0ad5d967ca00a2a5193d51e7ee74b8ad73
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_blas.py
@@ -0,0 +1,1127 @@
+#
+# Created by: Pearu Peterson, April 2002
+#
+
+import math
+import pytest
+import numpy as np
+import numpy.random
+from numpy.testing import (assert_equal, assert_almost_equal, assert_,
+                           assert_array_almost_equal, assert_allclose)
+from pytest import raises as assert_raises
+
+from numpy import float32, float64, complex64, complex128, arange, triu, \
+                  tril, zeros, tril_indices, ones, mod, diag, append, eye, \
+                  nonzero
+
+import scipy
+from scipy.linalg import _fblas as fblas, get_blas_funcs, toeplitz, solve
+
+try:
+    from scipy.linalg import _cblas as cblas
+except ImportError:
+    cblas = None
+
+REAL_DTYPES = [float32, float64]
+COMPLEX_DTYPES = [complex64, complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+def test_get_blas_funcs():
+    # check that it returns Fortran code for arrays that are
+    # fortran-ordered
+    f1, f2, f3 = get_blas_funcs(
+        ('axpy', 'axpy', 'axpy'),
+        (np.empty((2, 2), dtype=np.complex64, order='F'),
+         np.empty((2, 2), dtype=np.complex128, order='C'))
+        )
+
+    # get_blas_funcs will choose libraries depending on most generic
+    # array
+    assert_equal(f1.typecode, 'z')
+    assert_equal(f2.typecode, 'z')
+    if cblas is not None:
+        assert_equal(f1.module_name, 'cblas')
+        assert_equal(f2.module_name, 'cblas')
+
+    # check defaults.
+    f1 = get_blas_funcs('rotg')
+    assert_equal(f1.typecode, 'd')
+
+    # check also dtype interface
+    f1 = get_blas_funcs('gemm', dtype=np.complex64)
+    assert_equal(f1.typecode, 'c')
+    f1 = get_blas_funcs('gemm', dtype='F')
+    assert_equal(f1.typecode, 'c')
+
+    # extended precision complex
+    f1 = get_blas_funcs('gemm', dtype=np.clongdouble)
+    assert_equal(f1.typecode, 'z')
+
+    # check safe complex upcasting
+    f1 = get_blas_funcs('axpy',
+                        (np.empty((2, 2), dtype=np.float64),
+                         np.empty((2, 2), dtype=np.complex64))
+                        )
+    assert_equal(f1.typecode, 'z')
+
+
+def test_get_blas_funcs_alias():
+    # check alias for get_blas_funcs
+    f, g = get_blas_funcs(('nrm2', 'dot'), dtype=np.complex64)
+    assert f.typecode == 'c'
+    assert g.typecode == 'c'
+
+    f, g, h = get_blas_funcs(('dot', 'dotc', 'dotu'), dtype=np.float64)
+    assert f is g
+    assert f is h
+
+
+class TestCBLAS1Simple:
+
+    def test_axpy(self):
+        for p in 'sd':
+            f = getattr(cblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
+                                      [7, 9, 18])
+        for p in 'cz':
+            f = getattr(cblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
+                                      [7, 10j-1, 18])
+
+
+class TestFBLAS1Simple:
+
+    def test_axpy(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2, 3], [2, -1, 3], a=5),
+                                      [7, 9, 18])
+        for p in 'cz':
+            f = getattr(fblas, p+'axpy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([1, 2j, 3], [2, -1, 3], a=5),
+                                      [7, 10j-1, 18])
+
+    def test_copy(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'copy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([3, 4, 5], [8]*3), [3, 4, 5])
+        for p in 'cz':
+            f = getattr(fblas, p+'copy', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f([3, 4j, 5+3j], [8]*3), [3, 4j, 5+3j])
+
+    def test_asum(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'asum', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3, -4, 5]), 12)
+        for p in ['sc', 'dz']:
+            f = getattr(fblas, p+'asum', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j]), 14)
+
+    def test_dot(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'dot', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3, -4, 5], [2, 5, 1]), -9)
+
+    def test_complex_dotu(self):
+        for p in 'cz':
+            f = getattr(fblas, p+'dotu', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j], [2, 3, 1]), -9+2j)
+
+    def test_complex_dotc(self):
+        for p in 'cz':
+            f = getattr(fblas, p+'dotc', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j], [2, 3j, 1]), 3-14j)
+
+    def test_nrm2(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'nrm2', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3, -4, 5]), math.sqrt(50))
+        for p in ['c', 'z', 'sc', 'dz']:
+            f = getattr(fblas, p+'nrm2', None)
+            if f is None:
+                continue
+            assert_almost_equal(f([3j, -4, 3-4j]), math.sqrt(50))
+
+    def test_scal(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'scal', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(2, [3, -4, 5]), [6, -8, 10])
+        for p in 'cz':
+            f = getattr(fblas, p+'scal', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3j, [3j, -4, 3-4j]), [-9, -12j, 12+9j])
+        for p in ['cs', 'zd']:
+            f = getattr(fblas, p+'scal', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3, [3j, -4, 3-4j]), [9j, -12, 9-12j])
+
+    def test_swap(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'swap', None)
+            if f is None:
+                continue
+            x, y = [2, 3, 1], [-2, 3, 7]
+            x1, y1 = f(x, y)
+            assert_array_almost_equal(x1, y)
+            assert_array_almost_equal(y1, x)
+        for p in 'cz':
+            f = getattr(fblas, p+'swap', None)
+            if f is None:
+                continue
+            x, y = [2, 3j, 1], [-2, 3, 7-3j]
+            x1, y1 = f(x, y)
+            assert_array_almost_equal(x1, y)
+            assert_array_almost_equal(y1, x)
+
+    def test_amax(self):
+        for p in 'sd':
+            f = getattr(fblas, 'i'+p+'amax')
+            assert_equal(f([-2, 4, 3]), 1)
+        for p in 'cz':
+            f = getattr(fblas, 'i'+p+'amax')
+            assert_equal(f([-5, 4+3j, 6]), 1)
+    # XXX: need tests for rot,rotm,rotg,rotmg
+
+
+class TestFBLAS2Simple:
+
+    def test_gemv(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'gemv', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3, [[3]], [-4]), [-36])
+            assert_array_almost_equal(f(3, [[3]], [-4], 3, [5]), [-21])
+        for p in 'cz':
+            f = getattr(fblas, p+'gemv', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3j, [[3-4j]], [-4]), [-48-36j])
+            assert_array_almost_equal(f(3j, [[3-4j]], [-4], 3, [5j]),
+                                      [-48-21j])
+
+    # All of these *ger* functions are segfaulting when called from multiple
+    # threads under free-threaded CPython, see gh-21936.
+    @pytest.mark.thread_unsafe
+    def test_ger(self):
+
+        for p in 'sd':
+            f = getattr(fblas, p+'ger', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(1, [1, 2], [3, 4]), [[3, 4], [6, 8]])
+            assert_array_almost_equal(f(2, [1, 2, 3], [3, 4]),
+                                      [[6, 8], [12, 16], [18, 24]])
+
+            assert_array_almost_equal(f(1, [1, 2], [3, 4],
+                                        a=[[1, 2], [3, 4]]), [[4, 6], [9, 12]])
+
+        for p in 'cz':
+            f = getattr(fblas, p+'geru', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
+                                      [[3j, 4j], [6, 8]])
+            assert_array_almost_equal(f(-2, [1j, 2j, 3j], [3j, 4j]),
+                                      [[6, 8], [12, 16], [18, 24]])
+
+        for p in 'cz':
+            for name in ('ger', 'gerc'):
+                f = getattr(fblas, p+name, None)
+                if f is None:
+                    continue
+                assert_array_almost_equal(f(1, [1j, 2], [3, 4]),
+                                          [[3j, 4j], [6, 8]])
+                assert_array_almost_equal(f(2, [1j, 2j, 3j], [3j, 4j]),
+                                          [[6, 8], [12, 16], [18, 24]])
+
+    def test_syr_her(self):
+        x = np.arange(1, 5, dtype='d')
+        resx = np.triu(x[:, np.newaxis] * x)
+        resx_reverse = np.triu(x[::-1, np.newaxis] * x[::-1])
+
+        y = np.linspace(0, 8.5, 17, endpoint=False)
+
+        z = np.arange(1, 9, dtype='d').view('D')
+        resz = np.triu(z[:, np.newaxis] * z)
+        resz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1])
+        rehz = np.triu(z[:, np.newaxis] * z.conj())
+        rehz_reverse = np.triu(z[::-1, np.newaxis] * z[::-1].conj())
+
+        w = np.c_[np.zeros(4), z, np.zeros(4)].ravel()
+
+        for p, rtol in zip('sd', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'syr', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, x), resx, rtol=rtol)
+            assert_allclose(f(1.0, x, lower=True), resx.T, rtol=rtol)
+            assert_allclose(f(1.0, y, incx=2, offx=2, n=4), resx, rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, y, incx=-2, offx=2, n=4),
+                            resx_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F')
+            b = f(1.0, x, a=a, overwrite_a=True)
+            assert_allclose(a, resx, rtol=rtol)
+
+            b = f(2.0, x, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*resx, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, incx=0)
+            assert_raises(Exception, f, 1.0, x, offx=5)
+            assert_raises(Exception, f, 1.0, x, offx=-2)
+            assert_raises(Exception, f, 1.0, x, n=-2)
+            assert_raises(Exception, f, 1.0, x, n=5)
+            assert_raises(Exception, f, 1.0, x, lower=2)
+            assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
+
+        for p, rtol in zip('cz', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'syr', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, z), resz, rtol=rtol)
+            assert_allclose(f(1.0, z, lower=True), resz.T, rtol=rtol)
+            assert_allclose(f(1.0, w, incx=3, offx=1, n=4), resz, rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
+                            resz_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
+            b = f(1.0, z, a=a, overwrite_a=True)
+            assert_allclose(a, resz, rtol=rtol)
+
+            b = f(2.0, z, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*resz, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, incx=0)
+            assert_raises(Exception, f, 1.0, x, offx=5)
+            assert_raises(Exception, f, 1.0, x, offx=-2)
+            assert_raises(Exception, f, 1.0, x, n=-2)
+            assert_raises(Exception, f, 1.0, x, n=5)
+            assert_raises(Exception, f, 1.0, x, lower=2)
+            assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
+
+        for p, rtol in zip('cz', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'her', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, z), rehz, rtol=rtol)
+            assert_allclose(f(1.0, z, lower=True), rehz.T.conj(), rtol=rtol)
+            assert_allclose(f(1.0, w, incx=3, offx=1, n=4), rehz, rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, w, incx=-3, offx=1, n=4),
+                            rehz_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
+            b = f(1.0, z, a=a, overwrite_a=True)
+            assert_allclose(a, rehz, rtol=rtol)
+
+            b = f(2.0, z, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*rehz, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, incx=0)
+            assert_raises(Exception, f, 1.0, x, offx=5)
+            assert_raises(Exception, f, 1.0, x, offx=-2)
+            assert_raises(Exception, f, 1.0, x, n=-2)
+            assert_raises(Exception, f, 1.0, x, n=5)
+            assert_raises(Exception, f, 1.0, x, lower=2)
+            assert_raises(Exception, f, 1.0, x, a=np.zeros((2, 2), 'd', 'F'))
+
+    def test_syr2(self):
+        x = np.arange(1, 5, dtype='d')
+        y = np.arange(5, 9, dtype='d')
+        resxy = np.triu(x[:, np.newaxis] * y + y[:, np.newaxis] * x)
+        resxy_reverse = np.triu(x[::-1, np.newaxis] * y[::-1]
+                                + y[::-1, np.newaxis] * x[::-1])
+
+        q = np.linspace(0, 8.5, 17, endpoint=False)
+
+        for p, rtol in zip('sd', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'syr2', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
+            assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
+            assert_allclose(f(1.0, x, y, lower=True), resxy.T, rtol=rtol)
+
+            assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10),
+                            resxy, rtol=rtol)
+            assert_allclose(f(1.0, q, q, incx=2, offx=2, incy=2, offy=10, n=3),
+                            resxy[:3, :3], rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, q, q, incx=-2, offx=2, incy=-2, offy=10),
+                            resxy_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'f' if p == 's' else 'd', 'F')
+            b = f(1.0, x, y, a=a, overwrite_a=True)
+            assert_allclose(a, resxy, rtol=rtol)
+
+            b = f(2.0, x, y, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*resxy, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, y, incx=0)
+            assert_raises(Exception, f, 1.0, x, y, offx=5)
+            assert_raises(Exception, f, 1.0, x, y, offx=-2)
+            assert_raises(Exception, f, 1.0, x, y, incy=0)
+            assert_raises(Exception, f, 1.0, x, y, offy=5)
+            assert_raises(Exception, f, 1.0, x, y, offy=-2)
+            assert_raises(Exception, f, 1.0, x, y, n=-2)
+            assert_raises(Exception, f, 1.0, x, y, n=5)
+            assert_raises(Exception, f, 1.0, x, y, lower=2)
+            assert_raises(Exception, f, 1.0, x, y,
+                          a=np.zeros((2, 2), 'd', 'F'))
+
+    def test_her2(self):
+        x = np.arange(1, 9, dtype='d').view('D')
+        y = np.arange(9, 17, dtype='d').view('D')
+        resxy = x[:, np.newaxis] * y.conj() + y[:, np.newaxis] * x.conj()
+        resxy = np.triu(resxy)
+
+        resxy_reverse = x[::-1, np.newaxis] * y[::-1].conj()
+        resxy_reverse += y[::-1, np.newaxis] * x[::-1].conj()
+        resxy_reverse = np.triu(resxy_reverse)
+
+        u = np.c_[np.zeros(4), x, np.zeros(4)].ravel()
+        v = np.c_[np.zeros(4), y, np.zeros(4)].ravel()
+
+        for p, rtol in zip('cz', [1e-7, 1e-14]):
+            f = getattr(fblas, p+'her2', None)
+            if f is None:
+                continue
+            assert_allclose(f(1.0, x, y), resxy, rtol=rtol)
+            assert_allclose(f(1.0, x, y, n=3), resxy[:3, :3], rtol=rtol)
+            assert_allclose(f(1.0, x, y, lower=True), resxy.T.conj(),
+                            rtol=rtol)
+
+            assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1),
+                            resxy, rtol=rtol)
+            assert_allclose(f(1.0, u, v, incx=3, offx=1, incy=3, offy=1, n=3),
+                            resxy[:3, :3], rtol=rtol)
+            # negative increments imply reversed vectors in blas
+            assert_allclose(f(1.0, u, v, incx=-3, offx=1, incy=-3, offy=1),
+                            resxy_reverse, rtol=rtol)
+
+            a = np.zeros((4, 4), 'F' if p == 'c' else 'D', 'F')
+            b = f(1.0, x, y, a=a, overwrite_a=True)
+            assert_allclose(a, resxy, rtol=rtol)
+
+            b = f(2.0, x, y, a=a)
+            assert_(a is not b)
+            assert_allclose(b, 3*resxy, rtol=rtol)
+
+            assert_raises(Exception, f, 1.0, x, y, incx=0)
+            assert_raises(Exception, f, 1.0, x, y, offx=5)
+            assert_raises(Exception, f, 1.0, x, y, offx=-2)
+            assert_raises(Exception, f, 1.0, x, y, incy=0)
+            assert_raises(Exception, f, 1.0, x, y, offy=5)
+            assert_raises(Exception, f, 1.0, x, y, offy=-2)
+            assert_raises(Exception, f, 1.0, x, y, n=-2)
+            assert_raises(Exception, f, 1.0, x, y, n=5)
+            assert_raises(Exception, f, 1.0, x, y, lower=2)
+            assert_raises(Exception, f, 1.0, x, y,
+                          a=np.zeros((2, 2), 'd', 'F'))
+
+    def test_gbmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 7
+            m = 5
+            kl = 1
+            ku = 2
+            # fake a banded matrix via toeplitz
+            A = toeplitz(append(rng.random(kl+1), zeros(m-kl-1)),
+                         append(rng.random(ku+1), zeros(n-ku-1)))
+            A = A.astype(dtype)
+            Ab = zeros((kl+ku+1, n), dtype=dtype)
+
+            # Form the banded storage
+            Ab[2, :5] = A[0, 0]  # diag
+            Ab[1, 1:6] = A[0, 1]  # sup1
+            Ab[0, 2:7] = A[0, 2]  # sup2
+            Ab[3, :4] = A[1, 0]  # sub1
+
+            x = rng.random(n).astype(dtype)
+            y = rng.random(m).astype(dtype)
+            alpha, beta = dtype(3), dtype(-5)
+
+            func, = get_blas_funcs(('gbmv',), dtype=dtype)
+            y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
+                      x=x, y=y, beta=beta)
+            y2 = alpha * A.dot(x) + beta * y
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(m=m, n=n, ku=ku, kl=kl, alpha=alpha, a=Ab,
+                      x=y, y=x, beta=beta, trans=1)
+            y2 = alpha * A.T.dot(y) + beta * x
+            assert_array_almost_equal(y1, y2)
+
+    def test_sbmv_hbmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 6
+            k = 2
+            A = zeros((n, n), dtype=dtype)
+            Ab = zeros((k+1, n), dtype=dtype)
+
+            # Form the array and its packed banded storage
+            A[arange(n), arange(n)] = rng.random(n)
+            for ind2 in range(1, k+1):
+                temp = rng.random(n-ind2)
+                A[arange(n-ind2), arange(ind2, n)] = temp
+                Ab[-1-ind2, ind2:] = temp
+            A = A.astype(dtype)
+            A = A + A.T if ind < 2 else A + A.conj().T
+            Ab[-1, :] = diag(A)
+            x = rng.random(n).astype(dtype)
+            y = rng.random(n).astype(dtype)
+            alpha, beta = dtype(1.25), dtype(3)
+
+            if ind > 1:
+                func, = get_blas_funcs(('hbmv',), dtype=dtype)
+            else:
+                func, = get_blas_funcs(('sbmv',), dtype=dtype)
+            y1 = func(k=k, alpha=alpha, a=Ab, x=x, y=y, beta=beta)
+            y2 = alpha * A.dot(x) + beta * y
+            assert_array_almost_equal(y1, y2)
+
+    def test_spmv_hpmv(self):
+        rng = np.random.default_rng(12345698)
+        for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
+            n = 3
+            A = rng.random((n, n)).astype(dtype)
+            if ind > 1:
+                A += rng.random((n, n))*1j
+            A = A.astype(dtype)
+            A = A + A.T if ind < 4 else A + A.conj().T
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            x = rng.random(n).astype(dtype)
+            y = rng.random(n).astype(dtype)
+            xlong = arange(2*n).astype(dtype)
+            ylong = ones(2*n).astype(dtype)
+            alpha, beta = dtype(1.25), dtype(2)
+
+            if ind > 3:
+                func, = get_blas_funcs(('hpmv',), dtype=dtype)
+            else:
+                func, = get_blas_funcs(('spmv',), dtype=dtype)
+            y1 = func(n=n, alpha=alpha, ap=Ap, x=x, y=y, beta=beta)
+            y2 = alpha * A.dot(x) + beta * y
+            assert_array_almost_equal(y1, y2)
+
+            # Test inc and offsets
+            y1 = func(n=n-1, alpha=alpha, beta=beta, x=xlong, y=ylong, ap=Ap,
+                      incx=2, incy=2, offx=n, offy=n)
+            y2 = (alpha * A[:-1, :-1]).dot(xlong[3::2]) + beta * ylong[3::2]
+            assert_array_almost_equal(y1[3::2], y2)
+            assert_almost_equal(y1[4], ylong[4])
+
+    def test_spr_hpr(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
+            n = 3
+            A = rng.random((n, n)).astype(dtype)
+            if ind > 1:
+                A += rng.random((n, n))*1j
+            A = A.astype(dtype)
+            A = A + A.T if ind < 4 else A + A.conj().T
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            x = rng.random(n).astype(dtype)
+            alpha = (DTYPES+COMPLEX_DTYPES)[mod(ind, 4)](2.5)
+
+            if ind > 3:
+                func, = get_blas_funcs(('hpr',), dtype=dtype)
+                y2 = alpha * x[:, None].dot(x[None, :].conj()) + A
+            else:
+                func, = get_blas_funcs(('spr',), dtype=dtype)
+                y2 = alpha * x[:, None].dot(x[None, :]) + A
+
+            y1 = func(n=n, alpha=alpha, ap=Ap, x=x)
+            y1f = zeros((3, 3), dtype=dtype)
+            y1f[r, c] = y1
+            y1f[c, r] = y1.conj() if ind > 3 else y1
+            assert_array_almost_equal(y1f, y2)
+
+    def test_spr2_hpr2(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 3
+            A = rng.random((n, n)).astype(dtype)
+            if ind > 1:
+                A += rng.random((n, n))*1j
+            A = A.astype(dtype)
+            A = A + A.T if ind < 2 else A + A.conj().T
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            x = rng.random(n).astype(dtype)
+            y = rng.random(n).astype(dtype)
+            alpha = dtype(2)
+
+            if ind > 1:
+                func, = get_blas_funcs(('hpr2',), dtype=dtype)
+            else:
+                func, = get_blas_funcs(('spr2',), dtype=dtype)
+
+            u = alpha.conj() * x[:, None].dot(y[None, :].conj())
+            y2 = A + u + u.conj().T
+            y1 = func(n=n, alpha=alpha, x=x, y=y, ap=Ap)
+            y1f = zeros((3, 3), dtype=dtype)
+            y1f[r, c] = y1
+            y1f[[1, 2, 2], [0, 0, 1]] = y1[[1, 3, 4]].conj()
+            assert_array_almost_equal(y1f, y2)
+
+    def test_tbmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 10
+            k = 3
+            x = rng.random(n).astype(dtype)
+            A = zeros((n, n), dtype=dtype)
+            # Banded upper triangular array
+            for sup in range(k+1):
+                A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
+
+            # Add complex parts for c,z
+            if ind > 1:
+                A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
+
+            # Form the banded storage
+            Ab = zeros((k+1, n), dtype=dtype)
+            for row in range(k+1):
+                Ab[-row-1, row:] = diag(A, k=row)
+            func, = get_blas_funcs(('tbmv',), dtype=dtype)
+
+            y1 = func(k=k, a=Ab, x=x)
+            y2 = A.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = A.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
+            y2 = A.T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
+            y2 = A.conj().T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_tbsv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 6
+            k = 3
+            x = rng.random(n).astype(dtype)
+            A = zeros((n, n), dtype=dtype)
+            # Banded upper triangular array
+            for sup in range(k+1):
+                A[arange(n-sup), arange(sup, n)] = rng.random(n-sup)
+
+            # Add complex parts for c,z
+            if ind > 1:
+                A[nonzero(A)] += 1j * rng.random((k+1)*n-(k*(k+1)//2)).astype(dtype)
+
+            # Form the banded storage
+            Ab = zeros((k+1, n), dtype=dtype)
+            for row in range(k+1):
+                Ab[-row-1, row:] = diag(A, k=row)
+            func, = get_blas_funcs(('tbsv',), dtype=dtype)
+
+            y1 = func(k=k, a=Ab, x=x)
+            y2 = solve(A, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = solve(A, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1, trans=1)
+            y2 = solve(A.T, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(k=k, a=Ab, x=x, diag=1, trans=2)
+            y2 = solve(A.conj().T, x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_tpmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 10
+            x = rng.random(n).astype(dtype)
+            # Upper triangular array
+            if ind < 2:
+                A = triu(rng.random((n, n)))
+            else:
+                A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
+
+            # Form the packed storage
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            func, = get_blas_funcs(('tpmv',), dtype=dtype)
+
+            y1 = func(n=n, ap=Ap, x=x)
+            y2 = A.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = A.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
+            y2 = A.T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
+            y2 = A.conj().T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_tpsv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 10
+            x = rng.random(n).astype(dtype)
+            # Upper triangular array
+            if ind < 2:
+                A = triu(rng.random((n, n)))
+            else:
+                A = triu(rng.random((n, n)) + rng.random((n, n))*1j)
+            A += eye(n)
+            # Form the packed storage
+            c, r = tril_indices(n)
+            Ap = A[r, c]
+            func, = get_blas_funcs(('tpsv',), dtype=dtype)
+
+            y1 = func(n=n, ap=Ap, x=x)
+            y2 = solve(A, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = solve(A, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1, trans=1)
+            y2 = solve(A.T, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(n=n, ap=Ap, x=x, diag=1, trans=2)
+            y2 = solve(A.conj().T, x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_trmv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 3
+            A = (rng.random((n, n))+eye(n)).astype(dtype)
+            x = rng.random(3).astype(dtype)
+            func, = get_blas_funcs(('trmv',), dtype=dtype)
+
+            y1 = func(a=A, x=x)
+            y2 = triu(A).dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = triu(A).dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1, trans=1)
+            y2 = triu(A).T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1, trans=2)
+            y2 = triu(A).conj().T.dot(x)
+            assert_array_almost_equal(y1, y2)
+
+    def test_trsv(self):
+        rng = np.random.default_rng(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 15
+            A = (rng.random((n, n))+eye(n)).astype(dtype)
+            x = rng.random(n).astype(dtype)
+            func, = get_blas_funcs(('trsv',), dtype=dtype)
+
+            y1 = func(a=A, x=x)
+            y2 = solve(triu(A), x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, lower=1)
+            y2 = solve(tril(A), x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1)
+            A[arange(n), arange(n)] = dtype(1)
+            y2 = solve(triu(A), x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1, trans=1)
+            y2 = solve(triu(A).T, x)
+            assert_array_almost_equal(y1, y2)
+
+            y1 = func(a=A, x=x, diag=1, trans=2)
+            y2 = solve(triu(A).conj().T, x)
+            assert_array_almost_equal(y1, y2)
+
+
+class TestFBLAS3Simple:
+
+    def test_gemm(self):
+        for p in 'sd':
+            f = getattr(fblas, p+'gemm', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3, [3], [-4]), [[-36]])
+            assert_array_almost_equal(f(3, [3], [-4], 3, [5]), [-21])
+        for p in 'cz':
+            f = getattr(fblas, p+'gemm', None)
+            if f is None:
+                continue
+            assert_array_almost_equal(f(3j, [3-4j], [-4]), [[-48-36j]])
+            assert_array_almost_equal(f(3j, [3-4j], [-4], 3, [5j]), [-48-21j])
+
+
+def _get_func(func, ps='sdzc'):
+    """Just a helper: return a specified BLAS function w/typecode."""
+    for p in ps:
+        f = getattr(fblas, p+func, None)
+        if f is None:
+            continue
+        yield f
+
+
+class TestBLAS3Symm:
+
+    def setup_method(self):
+        self.a = np.array([[1., 2.],
+                           [0., 1.]])
+        self.b = np.array([[1., 0., 3.],
+                           [0., -1., 2.]])
+        self.c = np.ones((2, 3))
+        self.t = np.array([[2., -1., 8.],
+                           [3., 0., 9.]])
+
+    def test_symm(self):
+        for f in _get_func('symm'):
+            res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
+            assert_array_almost_equal(res, self.t)
+
+            res = f(a=self.a.T, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
+            assert_array_almost_equal(res, self.t)
+
+            res = f(a=self.a, b=self.b.T, side=1, c=self.c.T,
+                    alpha=1., beta=1.)
+            assert_array_almost_equal(res, self.t.T)
+
+    def test_summ_wrong_side(self):
+        f = getattr(fblas, 'dsymm', None)
+        if f is not None:
+            assert_raises(Exception, f, **{'a': self.a, 'b': self.b,
+                                           'alpha': 1, 'side': 1})
+            # `side=1` means C <- B*A, hence shapes of A and B are to be
+            #  compatible. Otherwise, f2py exception is raised
+
+    def test_symm_wrong_uplo(self):
+        """SYMM only considers the upper/lower part of A. Hence setting
+        wrong value for `lower` (default is lower=0, meaning upper triangle)
+        gives a wrong result.
+        """
+        f = getattr(fblas, 'dsymm', None)
+        if f is not None:
+            res = f(a=self.a, b=self.b, c=self.c, alpha=1., beta=1.)
+            assert np.allclose(res, self.t)
+
+            res = f(a=self.a, b=self.b, lower=1, c=self.c, alpha=1., beta=1.)
+            assert not np.allclose(res, self.t)
+
+
+class TestBLAS3Syrk:
+    def setup_method(self):
+        self.a = np.array([[1., 0.],
+                           [0., -2.],
+                           [2., 3.]])
+        self.t = np.array([[1., 0., 2.],
+                           [0., 4., -6.],
+                           [2., -6., 13.]])
+        self.tt = np.array([[5., 6.],
+                            [6., 13.]])
+
+    def test_syrk(self):
+        for f in _get_func('syrk'):
+            c = f(a=self.a, alpha=1.)
+            assert_array_almost_equal(np.triu(c), np.triu(self.t))
+
+            c = f(a=self.a, alpha=1., lower=1)
+            assert_array_almost_equal(np.tril(c), np.tril(self.t))
+
+            c0 = np.ones(self.t.shape)
+            c = f(a=self.a, alpha=1., beta=1., c=c0)
+            assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
+
+            c = f(a=self.a, alpha=1., trans=1)
+            assert_array_almost_equal(np.triu(c), np.triu(self.tt))
+
+    # prints '0-th dimension must be fixed to 3 but got 5',
+    # FIXME: suppress?
+    # FIXME: how to catch the _fblas.error?
+    def test_syrk_wrong_c(self):
+        f = getattr(fblas, 'dsyrk', None)
+        if f is not None:
+            assert_raises(Exception, f, **{'a': self.a, 'alpha': 1.,
+                                           'c': np.ones((5, 8))})
+        # if C is supplied, it must have compatible dimensions
+
+
+class TestBLAS3Syr2k:
+    def setup_method(self):
+        self.a = np.array([[1., 0.],
+                           [0., -2.],
+                           [2., 3.]])
+        self.b = np.array([[0., 1.],
+                           [1., 0.],
+                           [0, 1.]])
+        self.t = np.array([[0., -1., 3.],
+                           [-1., 0., 0.],
+                           [3., 0., 6.]])
+        self.tt = np.array([[0., 1.],
+                            [1., 6]])
+
+    def test_syr2k(self):
+        for f in _get_func('syr2k'):
+            c = f(a=self.a, b=self.b, alpha=1.)
+            assert_array_almost_equal(np.triu(c), np.triu(self.t))
+
+            c = f(a=self.a, b=self.b, alpha=1., lower=1)
+            assert_array_almost_equal(np.tril(c), np.tril(self.t))
+
+            c0 = np.ones(self.t.shape)
+            c = f(a=self.a, b=self.b, alpha=1., beta=1., c=c0)
+            assert_array_almost_equal(np.triu(c), np.triu(self.t+c0))
+
+            c = f(a=self.a, b=self.b, alpha=1., trans=1)
+            assert_array_almost_equal(np.triu(c), np.triu(self.tt))
+
+    # prints '0-th dimension must be fixed to 3 but got 5', FIXME: suppress?
+    def test_syr2k_wrong_c(self):
+        f = getattr(fblas, 'dsyr2k', None)
+        if f is not None:
+            assert_raises(Exception, f, **{'a': self.a,
+                                           'b': self.b,
+                                           'alpha': 1.,
+                                           'c': np.zeros((15, 8))})
+        # if C is supplied, it must have compatible dimensions
+
+
+class TestSyHe:
+    """Quick and simple tests for (zc)-symm, syrk, syr2k."""
+
+    def setup_method(self):
+        self.sigma_y = np.array([[0., -1.j],
+                                 [1.j, 0.]])
+
+    def test_symm_zc(self):
+        for f in _get_func('symm', 'zc'):
+            # NB: a is symmetric w/upper diag of ONLY
+            res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([1, -1]))
+
+    def test_hemm_zc(self):
+        for f in _get_func('hemm', 'zc'):
+            # NB: a is hermitian w/upper diag of ONLY
+            res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
+
+    def test_syrk_zr(self):
+        for f in _get_func('syrk', 'zc'):
+            res = f(a=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([-1, -1]))
+
+    def test_herk_zr(self):
+        for f in _get_func('herk', 'zc'):
+            res = f(a=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), np.diag([1, 1]))
+
+    def test_syr2k_zr(self):
+        for f in _get_func('syr2k', 'zc'):
+            res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), 2.*np.diag([-1, -1]))
+
+    def test_her2k_zr(self):
+        for f in _get_func('her2k', 'zc'):
+            res = f(a=self.sigma_y, b=self.sigma_y, alpha=1.)
+            assert_array_almost_equal(np.triu(res), 2.*np.diag([1, 1]))
+
+
+class TestTRMM:
+    """Quick and simple tests for dtrmm."""
+
+    def setup_method(self):
+        self.a = np.array([[1., 2., ],
+                           [-2., 1.]])
+        self.b = np.array([[3., 4., -1.],
+                           [5., 6., -2.]])
+
+        self.a2 = np.array([[1, 1, 2, 3],
+                            [0, 1, 4, 5],
+                            [0, 0, 1, 6],
+                            [0, 0, 0, 1]], order="f")
+        self.b2 = np.array([[1, 4], [2, 5], [3, 6], [7, 8], [9, 10]],
+                           order="f")
+
+    @pytest.mark.parametrize("dtype_", DTYPES)
+    def test_side(self, dtype_):
+        trmm = get_blas_funcs("trmm", dtype=dtype_)
+        # Provide large A array that works for side=1 but not 0 (see gh-10841)
+        assert_raises(Exception, trmm, 1.0, self.a2, self.b2)
+        res = trmm(1.0, self.a2.astype(dtype_), self.b2.astype(dtype_),
+                   side=1)
+        k = self.b2.shape[1]
+        assert_allclose(res, self.b2 @ self.a2[:k, :k], rtol=0.,
+                        atol=100*np.finfo(dtype_).eps)
+
+    def test_ab(self):
+        f = getattr(fblas, 'dtrmm', None)
+        if f is not None:
+            result = f(1., self.a, self.b)
+            # default a is upper triangular
+            expected = np.array([[13., 16., -5.],
+                                 [5., 6., -2.]])
+            assert_array_almost_equal(result, expected)
+
+    def test_ab_lower(self):
+        f = getattr(fblas, 'dtrmm', None)
+        if f is not None:
+            result = f(1., self.a, self.b, lower=True)
+            expected = np.array([[3., 4., -1.],
+                                 [-1., -2., 0.]])  # now a is lower triangular
+            assert_array_almost_equal(result, expected)
+
+    def test_b_overwrites(self):
+        # BLAS dtrmm modifies B argument in-place.
+        # Here the default is to copy, but this can be overridden
+        f = getattr(fblas, 'dtrmm', None)
+        if f is not None:
+            for overwr in [True, False]:
+                bcopy = self.b.copy()
+                result = f(1., self.a, bcopy, overwrite_b=overwr)
+                # C-contiguous arrays are copied
+                assert_(bcopy.flags.f_contiguous is False and
+                        np.may_share_memory(bcopy, result) is False)
+                assert_equal(bcopy, self.b)
+
+            bcopy = np.asfortranarray(self.b.copy())  # or just transpose it
+            result = f(1., self.a, bcopy, overwrite_b=True)
+            assert_(bcopy.flags.f_contiguous is True and
+                    np.may_share_memory(bcopy, result) is True)
+            assert_array_almost_equal(bcopy, result)
+
+
+def test_trsm():
+    rng = np.random.default_rng(1234)
+    for ind, dtype in enumerate(DTYPES):
+        tol = np.finfo(dtype).eps*1000
+        func, = get_blas_funcs(('trsm',), dtype=dtype)
+
+        # Test protection against size mismatches
+        A = rng.random((4, 5)).astype(dtype)
+        B = rng.random((4, 4)).astype(dtype)
+        alpha = dtype(1)
+        assert_raises(Exception, func, alpha, A, B)
+        assert_raises(Exception, func, alpha, A.T, B)
+
+        n = 8
+        m = 7
+        alpha = dtype(-2.5)
+        if ind < 2:
+            A = rng.random((m, m)) + eye(m)
+        else:
+            A = (rng.random((m, m)) + rng.random((m, m))*1j) + eye(m)
+        A = A.astype(dtype)
+        Au = triu(A)
+        Al = tril(A)
+        B1 = rng.random((m, n)).astype(dtype)
+        B2 = rng.random((n, m)).astype(dtype)
+
+        x1 = func(alpha=alpha, a=A, b=B1)
+        assert_equal(B1.shape, x1.shape)
+        x2 = solve(Au, alpha*B1)
+        assert_allclose(x1, x2, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B1, trans_a=1)
+        x2 = solve(Au.T, alpha*B1)
+        assert_allclose(x1, x2, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B1, trans_a=2)
+        x2 = solve(Au.conj().T, alpha*B1)
+        assert_allclose(x1, x2, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B1, diag=1)
+        Au[arange(m), arange(m)] = dtype(1)
+        x2 = solve(Au, alpha*B1)
+        assert_allclose(x1, x2, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1)
+        x2 = solve(Au.conj().T, alpha*B2.conj().T)
+        assert_allclose(x1, x2.conj().T, atol=tol)
+
+        x1 = func(alpha=alpha, a=A, b=B2, diag=1, side=1, lower=1)
+        Al[arange(m), arange(m)] = dtype(1)
+        x2 = solve(Al.conj().T, alpha*B2.conj().T)
+        assert_allclose(x1, x2.conj().T, atol=tol)
+
+
+@pytest.mark.xfail(run=False,
+                   reason="gh-16930")
+def test_gh_169309():
+    x = np.repeat(10, 9)
+    actual = scipy.linalg.blas.dnrm2(x, 5, 3, -1)
+    expected = math.sqrt(500)
+    assert_allclose(actual, expected)
+
+
+def test_dnrm2_neg_incx():
+    # check that dnrm2(..., incx < 0) raises
+    # XXX: remove the test after the lowest supported BLAS implements
+    # negative incx (new in LAPACK 3.10)
+    x = np.repeat(10, 9)
+    incx = -1
+    with assert_raises(fblas.__fblas_error):
+        scipy.linalg.blas.dnrm2(x, 5, 3, incx)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py
new file mode 100644
index 0000000000000000000000000000000000000000..284e214d38ed331cf0493d1e3bba6e1214939b2c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_blas.py
@@ -0,0 +1,118 @@
+import numpy as np
+from numpy.testing import (assert_allclose,
+                           assert_equal)
+import scipy.linalg.cython_blas as blas
+
+class TestDGEMM:
+    
+    def test_transposes(self):
+
+        a = np.arange(12, dtype='d').reshape((3, 4))[:2,:2]
+        b = np.arange(1, 13, dtype='d').reshape((4, 3))[:2,:2]
+        c = np.empty((2, 4))[:2,:2]
+
+        blas._test_dgemm(1., a, b, 0., c)
+        assert_allclose(c, a.dot(b))
+
+        blas._test_dgemm(1., a.T, b, 0., c)
+        assert_allclose(c, a.T.dot(b))
+
+        blas._test_dgemm(1., a, b.T, 0., c)
+        assert_allclose(c, a.dot(b.T))
+
+        blas._test_dgemm(1., a.T, b.T, 0., c)
+        assert_allclose(c, a.T.dot(b.T))
+
+        blas._test_dgemm(1., a, b, 0., c.T)
+        assert_allclose(c, a.dot(b).T)
+
+        blas._test_dgemm(1., a.T, b, 0., c.T)
+        assert_allclose(c, a.T.dot(b).T)
+
+        blas._test_dgemm(1., a, b.T, 0., c.T)
+        assert_allclose(c, a.dot(b.T).T)
+
+        blas._test_dgemm(1., a.T, b.T, 0., c.T)
+        assert_allclose(c, a.T.dot(b.T).T)
+    
+    def test_shapes(self):
+        a = np.arange(6, dtype='d').reshape((3, 2))
+        b = np.arange(-6, 2, dtype='d').reshape((2, 4))
+        c = np.empty((3, 4))
+
+        blas._test_dgemm(1., a, b, 0., c)
+        assert_allclose(c, a.dot(b))
+
+        blas._test_dgemm(1., b.T, a.T, 0., c.T)
+        assert_allclose(c, b.T.dot(a.T).T)
+        
+class TestWfuncPointers:
+    """ Test the function pointers that are expected to fail on
+    Mac OS X without the additional entry statement in their definitions
+    in fblas_l1.pyf.src. """
+
+    def test_complex_args(self):
+
+        cx = np.array([.5 + 1.j, .25 - .375j, 12.5 - 4.j], np.complex64)
+        cy = np.array([.8 + 2.j, .875 - .625j, -1. + 2.j], np.complex64)
+
+        assert_allclose(blas._test_cdotc(cx, cy),
+                        -17.6468753815+21.3718757629j)
+        assert_allclose(blas._test_cdotu(cx, cy),
+                        -6.11562538147+30.3156242371j)
+
+        assert_equal(blas._test_icamax(cx), 3)
+
+        assert_allclose(blas._test_scasum(cx), 18.625)
+        assert_allclose(blas._test_scnrm2(cx), 13.1796483994)
+
+        assert_allclose(blas._test_cdotc(cx[::2], cy[::2]),
+                        -18.1000003815+21.2000007629j)
+        assert_allclose(blas._test_cdotu(cx[::2], cy[::2]),
+                        -6.10000038147+30.7999992371j)
+        assert_allclose(blas._test_scasum(cx[::2]), 18.)
+        assert_allclose(blas._test_scnrm2(cx[::2]), 13.1719398499)
+    
+    def test_double_args(self):
+
+        x = np.array([5., -3, -.5], np.float64)
+        y = np.array([2, 1, .5], np.float64)
+
+        assert_allclose(blas._test_dasum(x), 8.5)
+        assert_allclose(blas._test_ddot(x, y), 6.75)
+        assert_allclose(blas._test_dnrm2(x), 5.85234975815)
+
+        assert_allclose(blas._test_dasum(x[::2]), 5.5)
+        assert_allclose(blas._test_ddot(x[::2], y[::2]), 9.75)
+        assert_allclose(blas._test_dnrm2(x[::2]), 5.0249376297)
+
+        assert_equal(blas._test_idamax(x), 1)
+
+    def test_float_args(self):
+
+        x = np.array([5., -3, -.5], np.float32)
+        y = np.array([2, 1, .5], np.float32)
+
+        assert_equal(blas._test_isamax(x), 1)
+
+        assert_allclose(blas._test_sasum(x), 8.5)
+        assert_allclose(blas._test_sdot(x, y), 6.75)
+        assert_allclose(blas._test_snrm2(x), 5.85234975815)
+
+        assert_allclose(blas._test_sasum(x[::2]), 5.5)
+        assert_allclose(blas._test_sdot(x[::2], y[::2]), 9.75)
+        assert_allclose(blas._test_snrm2(x[::2]), 5.0249376297)
+
+    def test_double_complex_args(self):
+
+        cx = np.array([.5 + 1.j, .25 - .375j, 13. - 4.j], np.complex128)
+        cy = np.array([.875 + 2.j, .875 - .625j, -1. + 2.j], np.complex128)
+
+        assert_equal(blas._test_izamax(cx), 3)
+
+        assert_allclose(blas._test_zdotc(cx, cy), -18.109375+22.296875j)
+        assert_allclose(blas._test_zdotu(cx, cy), -6.578125+31.390625j)
+
+        assert_allclose(blas._test_zdotc(cx[::2], cy[::2]), -18.5625+22.125j)
+        assert_allclose(blas._test_zdotu(cx[::2], cy[::2]), -6.5625+31.875j)
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a4e7b34b62042efdb0ce0f8ee61ce0189320995
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cython_lapack.py
@@ -0,0 +1,22 @@
+from numpy.testing import assert_allclose
+from scipy.linalg import cython_lapack as cython_lapack
+from scipy.linalg import lapack
+
+
+class TestLamch:
+
+    def test_slamch(self):
+        for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
+            assert_allclose(cython_lapack._test_slamch(c),
+                            lapack.slamch(c))
+
+    def test_dlamch(self):
+        for c in [b'e', b's', b'b', b'p', b'n', b'r', b'm', b'u', b'l', b'o']:
+            assert_allclose(cython_lapack._test_dlamch(c),
+                            lapack.dlamch(c))
+
+    def test_complex_ladiv(self):
+        cx = .5 + 1.j
+        cy = .875 + 2.j
+        assert_allclose(cython_lapack._test_zladiv(cy, cx), 1.95+0.1j)
+        assert_allclose(cython_lapack._test_cladiv(cy, cx), 1.95+0.1j)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d52c93950b6398c010b8bb8e5312153b3102fdf4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_cythonized_array_utils.py
@@ -0,0 +1,132 @@
+import numpy as np
+from scipy.linalg import bandwidth, issymmetric, ishermitian
+import pytest
+from pytest import raises
+
+
+def test_bandwidth_dtypes():
+    n = 5
+    for t in np.typecodes['All']:
+        A = np.zeros([n, n], dtype=t)
+        if t in 'eUVOMm':
+            raises(TypeError, bandwidth, A)
+        elif t == 'G':  # No-op test. On win these pass on others fail.
+            pass
+        else:
+            _ = bandwidth(A)
+
+
+def test_bandwidth_non2d_input():
+    A = np.array([1, 2, 3])
+    raises(ValueError, bandwidth, A)
+    A = np.array([[[1, 2, 3], [4, 5, 6]]])
+    raises(ValueError, bandwidth, A)
+
+
+@pytest.mark.parametrize('T', [x for x in np.typecodes['All']
+                               if x not in 'eGUVOMm'])
+def test_bandwidth_square_inputs(T):
+    n = 20
+    k = 4
+    R = np.zeros([n, n], dtype=T, order='F')
+    # form a banded matrix inplace
+    R[[x for x in range(n)], [x for x in range(n)]] = 1
+    R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
+    R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
+    R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
+    assert bandwidth(R) == (k, k)
+    A = np.array([
+        [1, 1, 0, 0, 0, 0, 0, 0],
+        [1, 0, 0, 0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 0, 1, 1, 1],
+        [0, 0, 0, 0, 0, 1, 0, 0],
+        [0, 0, 0, 0, 0, 1, 0, 0],
+    ])
+    assert bandwidth(A) == (2, 2)
+
+
+@pytest.mark.parametrize('T', [x for x in np.typecodes['All']
+                               if x not in 'eGUVOMm'])
+def test_bandwidth_rect_inputs(T):
+    n, m = 10, 20
+    k = 5
+    R = np.zeros([n, m], dtype=T, order='F')
+    # form a banded matrix inplace
+    R[[x for x in range(n)], [x for x in range(n)]] = 1
+    R[[x for x in range(n-k)], [x for x in range(k, n)]] = 1
+    R[[x for x in range(1, n)], [x for x in range(n-1)]] = 1
+    R[[x for x in range(k, n)], [x for x in range(n-k)]] = 1
+    assert bandwidth(R) == (k, k)
+
+
+def test_issymetric_ishermitian_dtypes():
+    n = 5
+    for t in np.typecodes['All']:
+        A = np.zeros([n, n], dtype=t)
+        if t in 'eUVOMm':
+            raises(TypeError, issymmetric, A)
+            raises(TypeError, ishermitian, A)
+        elif t == 'G':  # No-op test. On win these pass on others fail.
+            pass
+        else:
+            assert issymmetric(A)
+            assert ishermitian(A)
+
+
+def test_issymmetric_ishermitian_invalid_input():
+    A = np.array([1, 2, 3])
+    raises(ValueError, issymmetric, A)
+    raises(ValueError, ishermitian, A)
+    A = np.array([[[1, 2, 3], [4, 5, 6]]])
+    raises(ValueError, issymmetric, A)
+    raises(ValueError, ishermitian, A)
+    A = np.array([[1, 2, 3], [4, 5, 6]])
+    raises(ValueError, issymmetric, A)
+    raises(ValueError, ishermitian, A)
+
+
+def test_issymetric_complex_decimals():
+    A = np.arange(1, 10).astype(complex).reshape(3, 3)
+    A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
+    # make entries decimal
+    A /= np.pi
+    A = A + A.T
+    assert issymmetric(A)
+
+
+def test_ishermitian_complex_decimals():
+    A = np.arange(1, 10).astype(complex).reshape(3, 3)
+    A += np.arange(-4, 5).astype(complex).reshape(3, 3)*1j
+    # make entries decimal
+    A /= np.pi
+    A = A + A.T.conj()
+    assert ishermitian(A)
+
+
+def test_issymmetric_approximate_results():
+    n = 20
+    rng = np.random.RandomState(123456789)
+    x = rng.uniform(high=5., size=[n, n])
+    y = x @ x.T  # symmetric
+    p = rng.standard_normal([n, n])
+    z = p @ y @ p.T
+    assert issymmetric(z, atol=1e-10)
+    assert issymmetric(z, atol=1e-10, rtol=0.)
+    assert issymmetric(z, atol=0., rtol=1e-12)
+    assert issymmetric(z, atol=1e-13, rtol=1e-12)
+
+
+def test_ishermitian_approximate_results():
+    n = 20
+    rng = np.random.RandomState(987654321)
+    x = rng.uniform(high=5., size=[n, n])
+    y = x @ x.T  # symmetric
+    p = rng.standard_normal([n, n]) + rng.standard_normal([n, n])*1j
+    z = p @ y @ p.conj().T
+    assert ishermitian(z, atol=1e-10)
+    assert ishermitian(z, atol=1e-10, rtol=0.)
+    assert ishermitian(z, atol=0., rtol=1e-12)
+    assert ishermitian(z, atol=1e-13, rtol=1e-12)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..605496721f8eec7a522fbba0a77ed33d6c1fdeaf
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp.py
@@ -0,0 +1,3152 @@
+import itertools
+import platform
+import sys
+
+import numpy as np
+from numpy.testing import (assert_equal, assert_almost_equal,
+                           assert_array_almost_equal, assert_array_equal,
+                           assert_, assert_allclose)
+
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.linalg import (eig, eigvals, lu, svd, svdvals, cholesky, qr,
+                          schur, rsf2csf, lu_solve, lu_factor, solve, diagsvd,
+                          hessenberg, rq, eig_banded, eigvals_banded, eigh,
+                          eigvalsh, qr_multiply, qz, orth, ordqz,
+                          subspace_angles, hadamard, eigvalsh_tridiagonal,
+                          eigh_tridiagonal, null_space, cdf2rdf, LinAlgError)
+
+from scipy.linalg.lapack import (dgbtrf, dgbtrs, zgbtrf, zgbtrs, dsbev,
+                                 dsbevd, dsbevx, zhbevd, zhbevx)
+
+from scipy.linalg._misc import norm
+from scipy.linalg._decomp_qz import _select_function
+from scipy.stats import ortho_group
+
+from numpy import (array, diag, full, linalg, argsort, zeros, arange,
+                   float32, complex64, ravel, sqrt, iscomplex, shape, sort,
+                   sign, asarray, isfinite, ndarray, eye,)
+
+from scipy.linalg._testutils import assert_no_overwrite
+from scipy.sparse._sputils import matrix
+
+from scipy._lib._testutils import check_free_memory
+from scipy.linalg.blas import HAS_ILP64
+try:
+    from scipy.__config__ import CONFIG
+except ImportError:
+    CONFIG = None
+
+IS_WASM = (sys.platform == "emscripten" or platform.machine() in ["wasm32", "wasm64"])
+
+
+def _random_hermitian_matrix(n, posdef=False, dtype=float):
+    "Generate random sym/hermitian array of the given size n"
+    if dtype in COMPLEX_DTYPES:
+        A = np.random.rand(n, n) + np.random.rand(n, n)*1.0j
+        A = (A + A.conj().T)/2
+    else:
+        A = np.random.rand(n, n)
+        A = (A + A.T)/2
+
+    if posdef:
+        A += sqrt(2*n)*np.eye(n)
+
+    return A.astype(dtype)
+
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+# XXX: This function should not be defined here, but somewhere in
+#      scipy.linalg namespace
+def symrand(dim_or_eigv, rng):
+    """Return a random symmetric (Hermitian) matrix.
+
+    If 'dim_or_eigv' is an integer N, return a NxN matrix, with eigenvalues
+        uniformly distributed on (-1,1).
+
+    If 'dim_or_eigv' is  1-D real array 'a', return a matrix whose
+                      eigenvalues are 'a'.
+    """
+    if isinstance(dim_or_eigv, int):
+        dim = dim_or_eigv
+        d = rng.random(dim)*2 - 1
+    elif (isinstance(dim_or_eigv, ndarray) and
+          len(dim_or_eigv.shape) == 1):
+        dim = dim_or_eigv.shape[0]
+        d = dim_or_eigv
+    else:
+        raise TypeError("input type not supported.")
+
+    v = ortho_group.rvs(dim)
+    h = v.T.conj() @ diag(d) @ v
+    # to avoid roundoff errors, symmetrize the matrix (again)
+    h = 0.5*(h.T+h)
+    return h
+
+
+class TestEigVals:
+
+    def test_simple(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        w = eigvals(a)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        assert_array_almost_equal(w, exact_w)
+
+    def test_simple_tr(self):
+        a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]], 'd').T
+        a = a.copy()
+        a = a.T
+        w = eigvals(a)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        assert_array_almost_equal(w, exact_w)
+
+    def test_simple_complex(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]]
+        w = eigvals(a)
+        exact_w = [(9+1j+sqrt(92+6j))/2,
+                   0,
+                   (9+1j-sqrt(92+6j))/2]
+        assert_array_almost_equal(w, exact_w)
+
+    def test_finite(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        w = eigvals(a, check_finite=False)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        assert_array_almost_equal(w, exact_w)
+
+    @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        w = eigvals(a)
+        assert w.shape == (0,)
+        assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype
+
+        w = eigvals(a, homogeneous_eigvals=True)
+        assert w.shape == (2, 0)
+        assert w.dtype == eigvals(np.eye(2, dtype=dt)).dtype
+
+
+class TestEig:
+
+    def test_simple(self):
+        a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+        w, v = eig(a)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        v0 = array([1, 1, (1+sqrt(93)/3)/2])
+        v1 = array([3., 0, -1])
+        v2 = array([1, 1, (1-sqrt(93)/3)/2])
+        v0 = v0 / norm(v0)
+        v1 = v1 / norm(v1)
+        v2 = v2 / norm(v2)
+        assert_array_almost_equal(w, exact_w)
+        assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0]))
+        assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1]))
+        assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2]))
+        for i in range(3):
+            assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i])
+        w, v = eig(a, left=1, right=0)
+        for i in range(3):
+            assert_array_almost_equal(a.T @ v[:, i], w[i]*v[:, i])
+
+    def test_simple_complex_eig(self):
+        a = array([[1, 2], [-2, 1]])
+        w, vl, vr = eig(a, left=1, right=1)
+        assert_array_almost_equal(w, array([1+2j, 1-2j]))
+        for i in range(2):
+            assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i])
+        for i in range(2):
+            assert_array_almost_equal(a.conj().T @ vl[:, i],
+                                      w[i].conj()*vl[:, i])
+
+    def test_simple_complex(self):
+        a = array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]])
+        w, vl, vr = eig(a, left=1, right=1)
+        for i in range(3):
+            assert_array_almost_equal(a @ vr[:, i], w[i]*vr[:, i])
+        for i in range(3):
+            assert_array_almost_equal(a.conj().T @ vl[:, i],
+                                      w[i].conj()*vl[:, i])
+
+    def test_gh_3054(self):
+        a = [[1]]
+        b = [[0]]
+        w, vr = eig(a, b, homogeneous_eigvals=True)
+        assert_allclose(w[1, 0], 0)
+        assert_(w[0, 0] != 0)
+        assert_allclose(vr, 1)
+
+        w, vr = eig(a, b)
+        assert_equal(w, np.inf)
+        assert_allclose(vr, 1)
+
+    def _check_gen_eig(self, A, B, atol_homog=1e-13, rtol_homog=1e-13,
+                                   atol=1e-13, rtol=1e-13):
+        if B is not None:
+            A, B = asarray(A), asarray(B)
+            B0 = B
+        else:
+            A = asarray(A)
+            B0 = B
+            B = np.eye(*A.shape)
+        msg = f"\n{A!r}\n{B!r}"
+
+        # Eigenvalues in homogeneous coordinates
+        w, vr = eig(A, B0, homogeneous_eigvals=True)
+        wt = eigvals(A, B0, homogeneous_eigvals=True)
+        val1 = A @ vr * w[1, :]
+        val2 = B @ vr * w[0, :]
+        for i in range(val1.shape[1]):
+            assert_allclose(val1[:, i], val2[:, i],
+                            rtol=rtol_homog, atol=atol_homog, err_msg=msg)
+
+        if B0 is None:
+            assert_allclose(w[1, :], 1)
+            assert_allclose(wt[1, :], 1)
+
+        perm = np.lexsort(w)
+        permt = np.lexsort(wt)
+        assert_allclose(w[:, perm], wt[:, permt], atol=1e-7, rtol=1e-7,
+                        err_msg=msg)
+
+        length = np.empty(len(vr))
+
+        for i in range(len(vr)):
+            length[i] = norm(vr[:, i])
+
+        assert_allclose(length, np.ones(length.size), err_msg=msg,
+                        atol=1e-7, rtol=1e-7)
+
+        # Convert homogeneous coordinates
+        beta_nonzero = (w[1, :] != 0)
+        wh = w[0, beta_nonzero] / w[1, beta_nonzero]
+
+        # Eigenvalues in standard coordinates
+        w, vr = eig(A, B0)
+        wt = eigvals(A, B0)
+        val1 = A @ vr
+        val2 = B @ vr * w
+        res = val1 - val2
+        for i in range(res.shape[1]):
+            if np.all(isfinite(res[:, i])):
+                assert_allclose(res[:, i], 0,
+                                rtol=rtol, atol=atol, err_msg=msg)
+
+        # try to consistently order eigenvalues, including complex conjugate pairs
+        w_fin = w[isfinite(w)]
+        wt_fin = wt[isfinite(wt)]
+
+        # prune noise in the real parts
+        w_fin = -1j * np.real_if_close(1j*w_fin, tol=1e-10)
+        wt_fin = -1j * np.real_if_close(1j*wt_fin, tol=1e-10)
+
+        perm = argsort(abs(w_fin) + w_fin.imag)
+        permt = argsort(abs(wt_fin) + wt_fin.imag)
+
+        assert_allclose(w_fin[perm], wt_fin[permt],
+                        atol=1e-7, rtol=1e-7, err_msg=msg)
+
+        length = np.empty(len(vr))
+        for i in range(len(vr)):
+            length[i] = norm(vr[:, i])
+        assert_allclose(length, np.ones(length.size), err_msg=msg)
+
+        # Compare homogeneous and nonhomogeneous versions
+        assert_allclose(sort(wh), sort(w[np.isfinite(w)]))
+
+    def test_singular(self):
+        # Example taken from
+        # https://web.archive.org/web/20040903121217/http://www.cs.umu.se/research/nla/singular_pairs/guptri/matlab.html
+        A = array([[22, 34, 31, 31, 17],
+                   [45, 45, 42, 19, 29],
+                   [39, 47, 49, 26, 34],
+                   [27, 31, 26, 21, 15],
+                   [38, 44, 44, 24, 30]])
+        B = array([[13, 26, 25, 17, 24],
+                   [31, 46, 40, 26, 37],
+                   [26, 40, 19, 25, 25],
+                   [16, 25, 27, 14, 23],
+                   [24, 35, 18, 21, 22]])
+
+        with np.errstate(all='ignore'):
+            self._check_gen_eig(A, B, atol_homog=5e-13, atol=5e-13)
+
+    def test_falker(self):
+        # Test matrices giving some Nan generalized eigenvalues.
+        M = diag(array([1, 0, 3]))
+        K = array(([2, -1, -1], [-1, 2, -1], [-1, -1, 2]))
+        D = array(([1, -1, 0], [-1, 1, 0], [0, 0, 0]))
+        Z = zeros((3, 3))
+        I3 = eye(3)
+        A = np.block([[I3, Z], [Z, -K]])
+        B = np.block([[Z, I3], [M, D]])
+
+        with np.errstate(all='ignore'):
+            self._check_gen_eig(A, B)
+
+    def test_bad_geneig(self):
+        # Ticket #709 (strange return values from DGGEV)
+
+        def matrices(omega):
+            c1 = -9 + omega**2
+            c2 = 2*omega
+            A = [[1, 0, 0, 0],
+                 [0, 1, 0, 0],
+                 [0, 0, c1, 0],
+                 [0, 0, 0, c1]]
+            B = [[0, 0, 1, 0],
+                 [0, 0, 0, 1],
+                 [1, 0, 0, -c2],
+                 [0, 1, c2, 0]]
+            return A, B
+
+        # With a buggy LAPACK, this can fail for different omega on different
+        # machines -- so we need to test several values
+        with np.errstate(all='ignore'):
+            for k in range(100):
+                A, B = matrices(omega=k*5./100)
+                self._check_gen_eig(A, B)
+
+    def test_make_eigvals(self):
+        # Step through all paths in _make_eigvals
+        # Real eigenvalues
+        rng = np.random.RandomState(1234)
+        A = symrand(3, rng)
+        self._check_gen_eig(A, None)
+        B = symrand(3, rng)
+        self._check_gen_eig(A, B)
+        # Complex eigenvalues
+        A = rng.random((3, 3)) + 1j*rng.random((3, 3))
+        self._check_gen_eig(A, None)
+        B = rng.random((3, 3)) + 1j*rng.random((3, 3))
+        self._check_gen_eig(A, B)
+
+    def test_check_finite(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        w, v = eig(a, check_finite=False)
+        exact_w = [(9+sqrt(93))/2, 0, (9-sqrt(93))/2]
+        v0 = array([1, 1, (1+sqrt(93)/3)/2])
+        v1 = array([3., 0, -1])
+        v2 = array([1, 1, (1-sqrt(93)/3)/2])
+        v0 = v0 / norm(v0)
+        v1 = v1 / norm(v1)
+        v2 = v2 / norm(v2)
+        assert_array_almost_equal(w, exact_w)
+        assert_array_almost_equal(v0, v[:, 0]*sign(v[0, 0]))
+        assert_array_almost_equal(v1, v[:, 1]*sign(v[0, 1]))
+        assert_array_almost_equal(v2, v[:, 2]*sign(v[0, 2]))
+        for i in range(3):
+            assert_array_almost_equal(a @ v[:, i], w[i]*v[:, i])
+
+    def test_not_square_error(self):
+        """Check that passing a non-square array raises a ValueError."""
+        A = np.arange(6).reshape(3, 2)
+        assert_raises(ValueError, eig, A)
+
+    def test_shape_mismatch(self):
+        """Check that passing arrays of with different shapes
+        raises a ValueError."""
+        A = eye(2)
+        B = np.arange(9.0).reshape(3, 3)
+        assert_raises(ValueError, eig, A, B)
+        assert_raises(ValueError, eig, B, A)
+
+    def test_gh_11577(self):
+        # https://github.com/scipy/scipy/issues/11577
+        # `A - lambda B` should have 4 and 8 among the eigenvalues, and this
+        # was apparently broken on some platforms
+        A = np.array([[12.0, 28.0, 76.0, 220.0],
+                      [16.0, 32.0, 80.0, 224.0],
+                      [24.0, 40.0, 88.0, 232.0],
+                      [40.0, 56.0, 104.0, 248.0]], dtype='float64')
+        B = np.array([[2.0, 4.0, 10.0, 28.0],
+                      [3.0, 5.0, 11.0, 29.0],
+                      [5.0, 7.0, 13.0, 31.0],
+                      [9.0, 11.0, 17.0, 35.0]], dtype='float64')
+
+        D, V = eig(A, B)
+
+        # The problem is ill-conditioned, and two other eigenvalues
+        # depend on ATLAS/OpenBLAS version, compiler version etc
+        # see gh-11577 for discussion
+        #
+        # NB: it is tempting to use `assert_allclose(D[:2], [4, 8])` instead but
+        # the ordering of eigenvalues also comes out different on different
+        # systems depending on who knows what.
+        with np.testing.suppress_warnings() as sup:
+            # isclose chokes on inf/nan values
+            sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+            assert np.isclose(D, 4.0, atol=1e-14).any()
+            assert np.isclose(D, 8.0, atol=1e-14).any()
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        w, vr = eig(a)
+
+        w_n, vr_n = eig(np.eye(2, dtype=dt))
+
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype  #eigvals(np.eye(2, dtype=dt)).dtype
+
+        assert_allclose(vr, np.empty((0, 0)))
+        assert vr.shape == (0, 0)
+        assert vr.dtype == vr_n.dtype
+
+        w, vr = eig(a, homogeneous_eigvals=True)
+        assert w.shape == (2, 0)
+        assert w.dtype == w_n.dtype
+
+        assert vr.shape == (0, 0)
+        assert vr.dtype == vr_n.dtype
+
+
+
+class TestEigBanded:
+    def setup_method(self):
+        self.create_bandmat()
+
+    def create_bandmat(self):
+        """Create the full matrix `self.fullmat` and
+           the corresponding band matrix `self.bandmat`."""
+        N = 10
+        self.KL = 2   # number of subdiagonals (below the diagonal)
+        self.KU = 2   # number of superdiagonals (above the diagonal)
+
+        # symmetric band matrix
+        self.sym_mat = (diag(full(N, 1.0))
+                        + diag(full(N-1, -1.0), -1) + diag(full(N-1, -1.0), 1)
+                        + diag(full(N-2, -2.0), -2) + diag(full(N-2, -2.0), 2))
+
+        # hermitian band matrix
+        self.herm_mat = (diag(full(N, -1.0))
+                         + 1j*diag(full(N-1, 1.0), -1)
+                         - 1j*diag(full(N-1, 1.0), 1)
+                         + diag(full(N-2, -2.0), -2)
+                         + diag(full(N-2, -2.0), 2))
+
+        # general real band matrix
+        self.real_mat = (diag(full(N, 1.0))
+                         + diag(full(N-1, -1.0), -1) + diag(full(N-1, -3.0), 1)
+                         + diag(full(N-2, 2.0), -2) + diag(full(N-2, -2.0), 2))
+
+        # general complex band matrix
+        self.comp_mat = (1j*diag(full(N, 1.0))
+                         + diag(full(N-1, -1.0), -1)
+                         + 1j*diag(full(N-1, -3.0), 1)
+                         + diag(full(N-2, 2.0), -2)
+                         + diag(full(N-2, -2.0), 2))
+
+        # Eigenvalues and -vectors from linalg.eig
+        ew, ev = linalg.eig(self.sym_mat)
+        ew = ew.real
+        args = argsort(ew)
+        self.w_sym_lin = ew[args]
+        self.evec_sym_lin = ev[:, args]
+
+        ew, ev = linalg.eig(self.herm_mat)
+        ew = ew.real
+        args = argsort(ew)
+        self.w_herm_lin = ew[args]
+        self.evec_herm_lin = ev[:, args]
+
+        # Extract upper bands from symmetric and hermitian band matrices
+        # (for use in dsbevd, dsbevx, zhbevd, zhbevx
+        #  and their single precision versions)
+        LDAB = self.KU + 1
+        self.bandmat_sym = zeros((LDAB, N), dtype=float)
+        self.bandmat_herm = zeros((LDAB, N), dtype=complex)
+        for i in range(LDAB):
+            self.bandmat_sym[LDAB-i-1, i:N] = diag(self.sym_mat, i)
+            self.bandmat_herm[LDAB-i-1, i:N] = diag(self.herm_mat, i)
+
+        # Extract bands from general real and complex band matrix
+        # (for use in dgbtrf, dgbtrs and their single precision versions)
+        LDAB = 2*self.KL + self.KU + 1
+        self.bandmat_real = zeros((LDAB, N), dtype=float)
+        self.bandmat_real[2*self.KL, :] = diag(self.real_mat)  # diagonal
+        for i in range(self.KL):
+            # superdiagonals
+            self.bandmat_real[2*self.KL-1-i, i+1:N] = diag(self.real_mat, i+1)
+            # subdiagonals
+            self.bandmat_real[2*self.KL+1+i, 0:N-1-i] = diag(self.real_mat,
+                                                             -i-1)
+
+        self.bandmat_comp = zeros((LDAB, N), dtype=complex)
+        self.bandmat_comp[2*self.KL, :] = diag(self.comp_mat)  # diagonal
+        for i in range(self.KL):
+            # superdiagonals
+            self.bandmat_comp[2*self.KL-1-i, i+1:N] = diag(self.comp_mat, i+1)
+            # subdiagonals
+            self.bandmat_comp[2*self.KL+1+i, 0:N-1-i] = diag(self.comp_mat,
+                                                             -i-1)
+
+        # absolute value for linear equation system A*x = b
+        self.b = 1.0*arange(N)
+        self.bc = self.b * (1 + 1j)
+
+    #####################################################################
+
+    def test_dsbev(self):
+        """Compare dsbev eigenvalues and eigenvectors with
+           the result of linalg.eig."""
+        w, evec, info = dsbev(self.bandmat_sym, compute_v=1)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin))
+
+    def test_dsbevd(self):
+        """Compare dsbevd eigenvalues and eigenvectors with
+           the result of linalg.eig."""
+        w, evec, info = dsbevd(self.bandmat_sym, compute_v=1)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin))
+
+    def test_dsbevx(self):
+        """Compare dsbevx eigenvalues and eigenvectors
+           with the result of linalg.eig."""
+        N, N = shape(self.sym_mat)
+        # Achtung: Argumente 0.0,0.0,range?
+        w, evec, num, ifail, info = dsbevx(self.bandmat_sym, 0.0, 0.0, 1, N,
+                                           compute_v=1, range=2)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_sym_lin))
+
+    def test_zhbevd(self):
+        """Compare zhbevd eigenvalues and eigenvectors
+           with the result of linalg.eig."""
+        w, evec, info = zhbevd(self.bandmat_herm, compute_v=1)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_herm_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin))
+
+    def test_zhbevx(self):
+        """Compare zhbevx eigenvalues and eigenvectors
+           with the result of linalg.eig."""
+        N, N = shape(self.herm_mat)
+        # Achtung: Argumente 0.0,0.0,range?
+        w, evec, num, ifail, info = zhbevx(self.bandmat_herm, 0.0, 0.0, 1, N,
+                                           compute_v=1, range=2)
+        evec_ = evec[:, argsort(w)]
+        assert_array_almost_equal(sort(w), self.w_herm_lin)
+        assert_array_almost_equal(abs(evec_), abs(self.evec_herm_lin))
+
+    def test_eigvals_banded(self):
+        """Compare eigenvalues of eigvals_banded with those of linalg.eig."""
+        w_sym = eigvals_banded(self.bandmat_sym)
+        w_sym = w_sym.real
+        assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+
+        w_herm = eigvals_banded(self.bandmat_herm)
+        w_herm = w_herm.real
+        assert_array_almost_equal(sort(w_herm), self.w_herm_lin)
+
+        # extracting eigenvalues with respect to an index range
+        ind1 = 2
+        ind2 = np.longlong(6)
+        w_sym_ind = eigvals_banded(self.bandmat_sym,
+                                   select='i', select_range=(ind1, ind2))
+        assert_array_almost_equal(sort(w_sym_ind),
+                                  self.w_sym_lin[ind1:ind2+1])
+        w_herm_ind = eigvals_banded(self.bandmat_herm,
+                                    select='i', select_range=(ind1, ind2))
+        assert_array_almost_equal(sort(w_herm_ind),
+                                  self.w_herm_lin[ind1:ind2+1])
+
+        # extracting eigenvalues with respect to a value range
+        v_lower = self.w_sym_lin[ind1] - 1.0e-5
+        v_upper = self.w_sym_lin[ind2] + 1.0e-5
+        w_sym_val = eigvals_banded(self.bandmat_sym,
+                                   select='v', select_range=(v_lower, v_upper))
+        assert_array_almost_equal(sort(w_sym_val),
+                                  self.w_sym_lin[ind1:ind2+1])
+
+        v_lower = self.w_herm_lin[ind1] - 1.0e-5
+        v_upper = self.w_herm_lin[ind2] + 1.0e-5
+        w_herm_val = eigvals_banded(self.bandmat_herm,
+                                    select='v',
+                                    select_range=(v_lower, v_upper))
+        assert_array_almost_equal(sort(w_herm_val),
+                                  self.w_herm_lin[ind1:ind2+1])
+
+        w_sym = eigvals_banded(self.bandmat_sym, check_finite=False)
+        w_sym = w_sym.real
+        assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+
+    def test_eig_banded(self):
+        """Compare eigenvalues and eigenvectors of eig_banded
+           with those of linalg.eig. """
+        w_sym, evec_sym = eig_banded(self.bandmat_sym)
+        evec_sym_ = evec_sym[:, argsort(w_sym.real)]
+        assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin))
+
+        w_herm, evec_herm = eig_banded(self.bandmat_herm)
+        evec_herm_ = evec_herm[:, argsort(w_herm.real)]
+        assert_array_almost_equal(sort(w_herm), self.w_herm_lin)
+        assert_array_almost_equal(abs(evec_herm_), abs(self.evec_herm_lin))
+
+        # extracting eigenvalues with respect to an index range
+        ind1 = 2
+        ind2 = 6
+        w_sym_ind, evec_sym_ind = eig_banded(self.bandmat_sym,
+                                             select='i',
+                                             select_range=(ind1, ind2))
+        assert_array_almost_equal(sort(w_sym_ind),
+                                  self.w_sym_lin[ind1:ind2+1])
+        assert_array_almost_equal(abs(evec_sym_ind),
+                                  abs(self.evec_sym_lin[:, ind1:ind2+1]))
+
+        w_herm_ind, evec_herm_ind = eig_banded(self.bandmat_herm,
+                                               select='i',
+                                               select_range=(ind1, ind2))
+        assert_array_almost_equal(sort(w_herm_ind),
+                                  self.w_herm_lin[ind1:ind2+1])
+        assert_array_almost_equal(abs(evec_herm_ind),
+                                  abs(self.evec_herm_lin[:, ind1:ind2+1]))
+
+        # extracting eigenvalues with respect to a value range
+        v_lower = self.w_sym_lin[ind1] - 1.0e-5
+        v_upper = self.w_sym_lin[ind2] + 1.0e-5
+        w_sym_val, evec_sym_val = eig_banded(self.bandmat_sym,
+                                             select='v',
+                                             select_range=(v_lower, v_upper))
+        assert_array_almost_equal(sort(w_sym_val),
+                                  self.w_sym_lin[ind1:ind2+1])
+        assert_array_almost_equal(abs(evec_sym_val),
+                                  abs(self.evec_sym_lin[:, ind1:ind2+1]))
+
+        v_lower = self.w_herm_lin[ind1] - 1.0e-5
+        v_upper = self.w_herm_lin[ind2] + 1.0e-5
+        w_herm_val, evec_herm_val = eig_banded(self.bandmat_herm,
+                                               select='v',
+                                               select_range=(v_lower, v_upper))
+        assert_array_almost_equal(sort(w_herm_val),
+                                  self.w_herm_lin[ind1:ind2+1])
+        assert_array_almost_equal(abs(evec_herm_val),
+                                  abs(self.evec_herm_lin[:, ind1:ind2+1]))
+
+        w_sym, evec_sym = eig_banded(self.bandmat_sym, check_finite=False)
+        evec_sym_ = evec_sym[:, argsort(w_sym.real)]
+        assert_array_almost_equal(sort(w_sym), self.w_sym_lin)
+        assert_array_almost_equal(abs(evec_sym_), abs(self.evec_sym_lin))
+
+    def test_dgbtrf(self):
+        """Compare dgbtrf  LU factorisation with the LU factorisation result
+           of linalg.lu."""
+        M, N = shape(self.real_mat)
+        lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU)
+
+        # extract matrix u from lu_symm_band
+        u = diag(lu_symm_band[2*self.KL, :])
+        for i in range(self.KL + self.KU):
+            u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1)
+
+        p_lin, l_lin, u_lin = lu(self.real_mat, permute_l=0)
+        assert_array_almost_equal(u, u_lin)
+
+    def test_zgbtrf(self):
+        """Compare zgbtrf  LU factorisation with the LU factorisation result
+           of linalg.lu."""
+        M, N = shape(self.comp_mat)
+        lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU)
+
+        # extract matrix u from lu_symm_band
+        u = diag(lu_symm_band[2*self.KL, :])
+        for i in range(self.KL + self.KU):
+            u += diag(lu_symm_band[2*self.KL-1-i, i+1:N], i+1)
+
+        p_lin, l_lin, u_lin = lu(self.comp_mat, permute_l=0)
+        assert_array_almost_equal(u, u_lin)
+
+    def test_dgbtrs(self):
+        """Compare dgbtrs  solutions for linear equation system  A*x = b
+           with solutions of linalg.solve."""
+
+        lu_symm_band, ipiv, info = dgbtrf(self.bandmat_real, self.KL, self.KU)
+        y, info = dgbtrs(lu_symm_band, self.KL, self.KU, self.b, ipiv)
+
+        y_lin = linalg.solve(self.real_mat, self.b)
+        assert_array_almost_equal(y, y_lin)
+
+    def test_zgbtrs(self):
+        """Compare zgbtrs  solutions for linear equation system  A*x = b
+           with solutions of linalg.solve."""
+
+        lu_symm_band, ipiv, info = zgbtrf(self.bandmat_comp, self.KL, self.KU)
+        y, info = zgbtrs(lu_symm_band, self.KL, self.KU, self.bc, ipiv)
+
+        y_lin = linalg.solve(self.comp_mat, self.bc)
+        assert_array_almost_equal(y, y_lin)
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a_band = np.empty((0, 0), dtype=dt)
+        w, v = eig_banded(a_band)
+
+        w_n, v_n = eig_banded(np.array([[0, 0], [1, 1]], dtype=dt))
+
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype
+
+        assert v.shape == (0, 0)
+        assert v.dtype == v_n.dtype
+
+        w = eig_banded(a_band, eigvals_only=True)
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype
+
+class TestEigTridiagonal:
+    def setup_method(self):
+        self.create_trimat()
+
+    def create_trimat(self):
+        """Create the full matrix `self.fullmat`, `self.d`, and `self.e`."""
+        N = 10
+
+        # symmetric band matrix
+        self.d = full(N, 1.0)
+        self.e = full(N-1, -1.0)
+        self.full_mat = (diag(self.d) + diag(self.e, -1) + diag(self.e, 1))
+
+        ew, ev = linalg.eig(self.full_mat)
+        ew = ew.real
+        args = argsort(ew)
+        self.w = ew[args]
+        self.evec = ev[:, args]
+
+    def test_degenerate(self):
+        """Test error conditions."""
+        # Wrong sizes
+        assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e[:-1])
+        # Must be real
+        assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e * 1j)
+        # Bad driver
+        assert_raises(TypeError, eigvalsh_tridiagonal, self.d, self.e,
+                      lapack_driver=1.)
+        assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e,
+                      lapack_driver='foo')
+        # Bad bounds
+        assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e,
+                      select='i', select_range=(0, -1))
+
+    def test_eigvalsh_tridiagonal(self):
+        """Compare eigenvalues of eigvalsh_tridiagonal with those of eig."""
+        # can't use ?STERF with subselection
+        for driver in ('sterf', 'stev', 'stebz', 'stemr', 'auto'):
+            w = eigvalsh_tridiagonal(self.d, self.e, lapack_driver=driver)
+            assert_array_almost_equal(sort(w), self.w)
+
+        for driver in ('sterf', 'stev'):
+            assert_raises(ValueError, eigvalsh_tridiagonal, self.d, self.e,
+                          lapack_driver=driver, select='i',
+                          select_range=(0, 1))
+        for driver in ('stebz', 'stemr', 'auto'):
+            # extracting eigenvalues with respect to the full index range
+            w_ind = eigvalsh_tridiagonal(
+                self.d, self.e, select='i', select_range=(0, len(self.d)-1),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w_ind), self.w)
+
+            # extracting eigenvalues with respect to an index range
+            ind1 = 2
+            ind2 = 6
+            w_ind = eigvalsh_tridiagonal(
+                self.d, self.e, select='i', select_range=(ind1, ind2),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w_ind), self.w[ind1:ind2+1])
+
+            # extracting eigenvalues with respect to a value range
+            v_lower = self.w[ind1] - 1.0e-5
+            v_upper = self.w[ind2] + 1.0e-5
+            w_val = eigvalsh_tridiagonal(
+                self.d, self.e, select='v', select_range=(v_lower, v_upper),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w_val), self.w[ind1:ind2+1])
+
+    def test_eigh_tridiagonal(self):
+        """Compare eigenvalues and eigenvectors of eigh_tridiagonal
+           with those of eig. """
+        # can't use ?STERF when eigenvectors are requested
+        assert_raises(ValueError, eigh_tridiagonal, self.d, self.e,
+                      lapack_driver='sterf')
+        for driver in ('stebz', 'stev', 'stemr', 'auto'):
+            w, evec = eigh_tridiagonal(self.d, self.e, lapack_driver=driver)
+            evec_ = evec[:, argsort(w)]
+            assert_array_almost_equal(sort(w), self.w)
+            assert_array_almost_equal(abs(evec_), abs(self.evec))
+
+        assert_raises(ValueError, eigh_tridiagonal, self.d, self.e,
+                      lapack_driver='stev', select='i', select_range=(0, 1))
+        for driver in ('stebz', 'stemr', 'auto'):
+            # extracting eigenvalues with respect to an index range
+            ind1 = 0
+            ind2 = len(self.d)-1
+            w, evec = eigh_tridiagonal(
+                self.d, self.e, select='i', select_range=(ind1, ind2),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w), self.w)
+            assert_array_almost_equal(abs(evec), abs(self.evec))
+            ind1 = 2
+            ind2 = 6
+            w, evec = eigh_tridiagonal(
+                self.d, self.e, select='i', select_range=(ind1, ind2),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w), self.w[ind1:ind2+1])
+            assert_array_almost_equal(abs(evec),
+                                      abs(self.evec[:, ind1:ind2+1]))
+
+            # extracting eigenvalues with respect to a value range
+            v_lower = self.w[ind1] - 1.0e-5
+            v_upper = self.w[ind2] + 1.0e-5
+            w, evec = eigh_tridiagonal(
+                self.d, self.e, select='v', select_range=(v_lower, v_upper),
+                lapack_driver=driver)
+            assert_array_almost_equal(sort(w), self.w[ind1:ind2+1])
+            assert_array_almost_equal(abs(evec),
+                                      abs(self.evec[:, ind1:ind2+1]))
+
+    def test_eigh_tridiagonal_1x1(self):
+        """See gh-20075"""
+        a = np.array([-2.0])
+        b = np.array([])
+        x = eigh_tridiagonal(a, b, eigvals_only=True)
+        assert x.ndim == 1
+        assert_allclose(x, a)
+        x, V = eigh_tridiagonal(a, b, select="i", select_range=(0, 0))
+        assert x.ndim == 1
+        assert V.ndim == 2
+        assert_allclose(x, a)
+        assert_allclose(V, array([[1.]]))
+
+        x, V = eigh_tridiagonal(a, b, select="v", select_range=(-2, 0))
+        assert x.size == 0
+        assert x.shape == (0,)
+        assert V.shape == (1, 0)
+
+
+class TestEigh:
+    def setup_class(self):
+        np.random.seed(1234)
+
+    def test_wrong_inputs(self):
+        # Nonsquare a
+        assert_raises(ValueError, eigh, np.ones([1, 2]))
+        # Nonsquare b
+        assert_raises(ValueError, eigh, np.ones([2, 2]), np.ones([2, 1]))
+        # Incompatible a, b sizes
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([2, 2]))
+        # Wrong type parameter for generalized problem
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      type=4)
+        # Both value and index subsets requested
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_value=[1, 2], subset_by_index=[2, 4])
+        # Invalid upper index spec
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_index=[0, 4])
+        # Invalid lower index
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_index=[-2, 2])
+        # Invalid index spec #2
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_index=[2, 0])
+        # Invalid value spec
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      subset_by_value=[2, 0])
+        # Invalid driver name
+        assert_raises(ValueError, eigh, np.ones([2, 2]), driver='wrong')
+        # Generalized driver selection without b
+        assert_raises(ValueError, eigh, np.ones([3, 3]), None, driver='gvx')
+        # Standard driver with b
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      driver='evr')
+        # Subset request from invalid driver
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      driver='gvd', subset_by_index=[1, 2])
+        assert_raises(ValueError, eigh, np.ones([3, 3]), np.ones([3, 3]),
+                      driver='gvd', subset_by_index=[1, 2])
+
+    def test_nonpositive_b(self):
+        assert_raises(LinAlgError, eigh, np.ones([3, 3]), np.ones([3, 3]))
+
+    # index based subsets are done in the legacy test_eigh()
+    def test_value_subsets(self):
+        for ind, dt in enumerate(DTYPES):
+
+            a = _random_hermitian_matrix(20, dtype=dt)
+            w, v = eigh(a, subset_by_value=[-2, 2])
+            assert_equal(v.shape[1], len(w))
+            assert all((w > -2) & (w < 2))
+
+            b = _random_hermitian_matrix(20, posdef=True, dtype=dt)
+            w, v = eigh(a, b, subset_by_value=[-2, 2])
+            assert_equal(v.shape[1], len(w))
+            assert all((w > -2) & (w < 2))
+
+    def test_eigh_integer(self):
+        a = array([[1, 2], [2, 7]])
+        b = array([[3, 1], [1, 5]])
+        w, z = eigh(a)
+        w, z = eigh(a, b)
+
+    def test_eigh_of_sparse(self):
+        # This tests the rejection of inputs that eigh cannot currently handle.
+        import scipy.sparse
+        a = scipy.sparse.identity(2).tocsc()
+        b = np.atleast_2d(a)
+        assert_raises(ValueError, eigh, a)
+        assert_raises(ValueError, eigh, b)
+
+    @pytest.mark.parametrize('dtype_', DTYPES)
+    @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx"))
+    def test_various_drivers_standard(self, driver, dtype_):
+        a = _random_hermitian_matrix(n=20, dtype=dtype_)
+        w, v = eigh(a, driver=driver)
+        assert_allclose(a @ v - (v * w), 0.,
+                        atol=1000*np.finfo(dtype_).eps,
+                        rtol=0.)
+
+    @pytest.mark.parametrize('driver', ("ev", "evd", "evr", "evx"))
+    def test_1x1_lwork(self, driver):
+        w, v = eigh([[1]], driver=driver)
+        assert_allclose(w, array([1.]), atol=1e-15)
+        assert_allclose(v, array([[1.]]), atol=1e-15)
+
+        # complex case now
+        w, v = eigh([[1j]], driver=driver)
+        assert_allclose(w, array([0]), atol=1e-15)
+        assert_allclose(v, array([[1.]]), atol=1e-15)
+
+    @pytest.mark.parametrize('type', (1, 2, 3))
+    @pytest.mark.parametrize('driver', ("gv", "gvd", "gvx"))
+    def test_various_drivers_generalized(self, driver, type):
+        atol = np.spacing(5000.)
+        a = _random_hermitian_matrix(20)
+        b = _random_hermitian_matrix(20, posdef=True)
+        w, v = eigh(a=a, b=b, driver=driver, type=type)
+        if type == 1:
+            assert_allclose(a @ v - w*(b @ v), 0., atol=atol, rtol=0.)
+        elif type == 2:
+            assert_allclose(a @ b @ v - v * w, 0., atol=atol, rtol=0.)
+        else:
+            assert_allclose(b @ a @ v - v * w, 0., atol=atol, rtol=0.)
+
+    def test_eigvalsh_new_args(self):
+        a = _random_hermitian_matrix(5)
+        w = eigvalsh(a, subset_by_index=[1, 2])
+        assert_equal(len(w), 2)
+
+        w2 = eigvalsh(a, subset_by_index=[1, 2])
+        assert_equal(len(w2), 2)
+        assert_allclose(w, w2)
+
+        b = np.diag([1, 1.2, 1.3, 1.5, 2])
+        w3 = eigvalsh(b, subset_by_value=[1, 1.4])
+        assert_equal(len(w3), 2)
+        assert_allclose(w3, np.array([1.2, 1.3]))
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        w, v = eigh(a)
+
+        w_n, v_n = eigh(np.eye(2, dtype=dt))
+
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype
+
+        assert v.shape == (0, 0)
+        assert v.dtype == v_n.dtype
+
+        w = eigh(a, eigvals_only=True)
+        assert_allclose(w, np.empty((0,)))
+
+        assert w.shape == (0,)
+        assert w.dtype == w_n.dtype
+
+class TestSVD_GESDD:
+    lapack_driver = 'gesdd'
+
+    def test_degenerate(self):
+        assert_raises(TypeError, svd, [[1.]], lapack_driver=1.)
+        assert_raises(ValueError, svd, [[1.]], lapack_driver='foo')
+
+    def test_simple(self):
+        a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.T @ u, eye(3))
+            assert_array_almost_equal(vh.T @ vh, eye(3))
+            sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_simple_singular(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.T @ u, eye(3))
+            assert_array_almost_equal(vh.T @ vh, eye(3))
+            sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_simple_underdet(self):
+        a = [[1, 2, 3], [4, 5, 6]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.T @ u, eye(u.shape[0]))
+            sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_simple_overdet(self):
+        a = [[1, 2], [4, 5], [3, 4]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.T @ u, eye(u.shape[1]))
+            assert_array_almost_equal(vh.T @ vh, eye(2))
+            sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_random(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        m = 15
+        for i in range(3):
+            for a in [rng.random([n, m]), rng.random([m, n])]:
+                for full_matrices in (True, False):
+                    u, s, vh = svd(a, full_matrices=full_matrices,
+                                   lapack_driver=self.lapack_driver)
+                    assert_array_almost_equal(u.T @ u, eye(u.shape[1]))
+                    assert_array_almost_equal(vh @ vh.T, eye(vh.shape[0]))
+                    sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char)
+                    for i in range(len(s)):
+                        sigma[i, i] = s[i]
+                    assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_simple_complex(self):
+        a = [[1, 2, 3], [1, 2j, 3], [2, 5, 6]]
+        for full_matrices in (True, False):
+            u, s, vh = svd(a, full_matrices=full_matrices,
+                           lapack_driver=self.lapack_driver)
+            assert_array_almost_equal(u.conj().T @ u, eye(u.shape[1]))
+            assert_array_almost_equal(vh.conj().T @ vh, eye(vh.shape[0]))
+            sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+            for i in range(len(s)):
+                sigma[i, i] = s[i]
+            assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_random_complex(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        m = 15
+        for i in range(3):
+            for full_matrices in (True, False):
+                for a in [rng.random([n, m]), rng.random([m, n])]:
+                    a = a + 1j*rng.random(list(a.shape))
+                    u, s, vh = svd(a, full_matrices=full_matrices,
+                                   lapack_driver=self.lapack_driver)
+                    assert_array_almost_equal(u.conj().T @ u,
+                                              eye(u.shape[1]))
+                    # This fails when [m,n]
+                    # assert_array_almost_equal(vh.conj().T @ vh,
+                    #                        eye(len(vh),dtype=vh.dtype.char))
+                    sigma = zeros((u.shape[1], vh.shape[0]), s.dtype.char)
+                    for i in range(len(s)):
+                        sigma[i, i] = s[i]
+                    assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_crash_1580(self):
+        rng = np.random.RandomState(1234)
+        sizes = [(13, 23), (30, 50), (60, 100)]
+        for sz in sizes:
+            for dt in [np.float32, np.float64, np.complex64, np.complex128]:
+                a = rng.rand(*sz).astype(dt)
+                # should not crash
+                svd(a, lapack_driver=self.lapack_driver)
+
+    def test_check_finite(self):
+        a = [[1, 2, 3], [1, 20, 3], [2, 5, 6]]
+        u, s, vh = svd(a, check_finite=False, lapack_driver=self.lapack_driver)
+        assert_array_almost_equal(u.T @ u, eye(3))
+        assert_array_almost_equal(vh.T @ vh, eye(3))
+        sigma = zeros((u.shape[0], vh.shape[0]), s.dtype.char)
+        for i in range(len(s)):
+            sigma[i, i] = s[i]
+        assert_array_almost_equal(u @ sigma @ vh, a)
+
+    def test_gh_5039(self):
+        # This is a smoke test for https://github.com/scipy/scipy/issues/5039
+        #
+        # The following is reported to raise "ValueError: On entry to DGESDD
+        # parameter number 12 had an illegal value".
+        # `interp1d([1,2,3,4], [1,2,3,4], kind='cubic')`
+        # This is reported to only show up on LAPACK 3.0.3.
+        #
+        # The matrix below is taken from the call to
+        # `B = _fitpack._bsplmat(order, xk)` in interpolate._find_smoothest
+        b = np.array(
+            [[0.16666667, 0.66666667, 0.16666667, 0., 0., 0.],
+             [0., 0.16666667, 0.66666667, 0.16666667, 0., 0.],
+             [0., 0., 0.16666667, 0.66666667, 0.16666667, 0.],
+             [0., 0., 0., 0.16666667, 0.66666667, 0.16666667]])
+        svd(b, lapack_driver=self.lapack_driver)
+
+    @pytest.mark.skipif(not HAS_ILP64, reason="64-bit LAPACK required")
+    @pytest.mark.slow
+    def test_large_matrix(self):
+        check_free_memory(free_mb=17000)
+        A = np.zeros([1, 2**31], dtype=np.float32)
+        A[0, -1] = 1
+        u, s, vh = svd(A, full_matrices=False)
+        assert_allclose(s[0], 1.0)
+        assert_allclose(u[0, 0] * vh[0, -1], 1.0)
+
+    @pytest.mark.parametrize("m", [0, 1, 2])
+    @pytest.mark.parametrize("n", [0, 1, 2])
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_shape_dtype(self, m, n, dtype):
+        a = np.zeros((m, n), dtype=dtype)
+        k = min(m, n)
+        dchar = a.dtype.char
+        real_dchar = dchar.lower() if dchar in 'FD' else dchar
+
+        u, s, v = svd(a)
+        assert_equal(u.shape, (m, m))
+        assert_equal(u.dtype, dtype)
+        assert_equal(s.shape, (k,))
+        assert_equal(s.dtype, np.dtype(real_dchar))
+        assert_equal(v.shape, (n, n))
+        assert_equal(v.dtype, dtype)
+
+        u, s, v = svd(a, full_matrices=False)
+        assert_equal(u.shape, (m, k))
+        assert_equal(u.dtype, dtype)
+        assert_equal(s.shape, (k,))
+        assert_equal(s.dtype, np.dtype(real_dchar))
+        assert_equal(v.shape, (k, n))
+        assert_equal(v.dtype, dtype)
+
+        s = svd(a, compute_uv=False)
+        assert_equal(s.shape, (k,))
+        assert_equal(s.dtype, np.dtype(real_dchar))
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+    def test_empty(self, dt, m, n):
+        a0 = np.eye(3, dtype=dt)
+        u0, s0, v0 = svd(a0)
+
+        a = np.empty((m, n), dtype=dt)
+        u, s, v = svd(a)
+        assert_allclose(u, np.identity(m))
+        assert_allclose(s, np.empty((0,)))
+        assert_allclose(v, np.identity(n))
+
+        assert u.dtype == u0.dtype
+        assert v.dtype == v0.dtype
+        assert s.dtype == s0.dtype
+
+        u, s, v = svd(a, full_matrices=False)
+        assert_allclose(u, np.empty((m, 0)))
+        assert_allclose(s, np.empty((0,)))
+        assert_allclose(v, np.empty((0, n)))
+
+        assert u.dtype == u0.dtype
+        assert v.dtype == v0.dtype
+        assert s.dtype == s0.dtype
+
+        s = svd(a, compute_uv=False)
+        assert_allclose(s, np.empty((0,)))
+
+        assert s.dtype == s0.dtype
+
+class TestSVD_GESVD(TestSVD_GESDD):
+    lapack_driver = 'gesvd'
+
+
+# Allocating an array of such a size leads to _ArrayMemoryError(s)
+# since the maximum memory that can be in 32-bit (WASM) is 4GB
+@pytest.mark.skipif(IS_WASM, reason="out of memory in WASM")
+@pytest.mark.fail_slow(10)
+def test_svd_gesdd_nofegfault():
+    # svd(a) with {U,VT}.size > INT_MAX does not segfault
+    # cf https://github.com/scipy/scipy/issues/14001
+    df=np.ones((4799, 53130), dtype=np.float64)
+    with assert_raises(ValueError):
+        svd(df)
+
+
+class TestSVDVals:
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        for a in [[]], np.empty((2, 0)), np.ones((0, 3)):
+            a = np.array(a, dtype=dt)
+            s = svdvals(a)
+            assert_equal(s, np.empty(0))
+
+            s0 = svdvals(np.eye(2, dtype=dt))
+            assert s.dtype == s0.dtype
+
+    def test_simple(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        s = svdvals(a)
+        assert_(len(s) == 3)
+        assert_(s[0] >= s[1] >= s[2])
+
+    def test_simple_underdet(self):
+        a = [[1, 2, 3], [4, 5, 6]]
+        s = svdvals(a)
+        assert_(len(s) == 2)
+        assert_(s[0] >= s[1])
+
+    def test_simple_overdet(self):
+        a = [[1, 2], [4, 5], [3, 4]]
+        s = svdvals(a)
+        assert_(len(s) == 2)
+        assert_(s[0] >= s[1])
+
+    def test_simple_complex(self):
+        a = [[1, 2, 3], [1, 20, 3j], [2, 5, 6]]
+        s = svdvals(a)
+        assert_(len(s) == 3)
+        assert_(s[0] >= s[1] >= s[2])
+
+    def test_simple_underdet_complex(self):
+        a = [[1, 2, 3], [4, 5j, 6]]
+        s = svdvals(a)
+        assert_(len(s) == 2)
+        assert_(s[0] >= s[1])
+
+    def test_simple_overdet_complex(self):
+        a = [[1, 2], [4, 5], [3j, 4]]
+        s = svdvals(a)
+        assert_(len(s) == 2)
+        assert_(s[0] >= s[1])
+
+    def test_check_finite(self):
+        a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
+        s = svdvals(a, check_finite=False)
+        assert_(len(s) == 3)
+        assert_(s[0] >= s[1] >= s[2])
+
+    @pytest.mark.slow
+    def test_crash_2609(self):
+        np.random.seed(1234)
+        a = np.random.rand(1500, 2800)
+        # Shouldn't crash:
+        svdvals(a)
+
+
+class TestDiagSVD:
+
+    def test_simple(self):
+        assert_array_almost_equal(diagsvd([1, 0, 0], 3, 3),
+                                  [[1, 0, 0], [0, 0, 0], [0, 0, 0]])
+
+
+class TestQR:
+    def test_simple(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_simple_left(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r = qr(a)
+        c = [1, 2, 3]
+        qc, r2 = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        assert_array_almost_equal(r, r2)
+        qc, r2 = qr_multiply(a, eye(3), "left")
+        assert_array_almost_equal(q, qc)
+
+    def test_simple_right(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r = qr(a)
+        c = [1, 2, 3]
+        qc, r2 = qr_multiply(a, c)
+        assert_array_almost_equal(c @ q, qc)
+        assert_array_almost_equal(r, r2)
+        qc, r = qr_multiply(a, eye(3))
+        assert_array_almost_equal(q, qc)
+
+    def test_simple_pivoting(self):
+        a = np.asarray([[8, 2, 3], [2, 9, 3], [5, 3, 6]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_left_pivoting(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r, jpvt = qr(a, pivoting=True)
+        c = [1, 2, 3]
+        qc, r, jpvt = qr_multiply(a, c, "left", True)
+        assert_array_almost_equal(q @ c, qc)
+
+    def test_simple_right_pivoting(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r, jpvt = qr(a, pivoting=True)
+        c = [1, 2, 3]
+        qc, r, jpvt = qr_multiply(a, c, pivoting=True)
+        assert_array_almost_equal(c @ q, qc)
+
+    def test_simple_trap(self):
+        a = [[8, 2, 3], [2, 9, 3]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_simple_trap_pivoting(self):
+        a = np.asarray([[8, 2, 3], [2, 9, 3]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_tall(self):
+        # full version
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_simple_tall_pivoting(self):
+        # full version pivoting
+        a = np.asarray([[8, 2], [2, 9], [5, 3]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_tall_e(self):
+        # economy version
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r = qr(a, mode='economic')
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a)
+        assert_equal(q.shape, (3, 2))
+        assert_equal(r.shape, (2, 2))
+
+    def test_simple_tall_e_pivoting(self):
+        # economy version pivoting
+        a = np.asarray([[8, 2], [2, 9], [5, 3]])
+        q, r, p = qr(a, pivoting=True, mode='economic')
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p], mode='economic')
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_tall_left(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2]
+        qc, r2 = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        assert_array_almost_equal(r, r2)
+        c = array([1, 2, 0])
+        qc, r2 = qr_multiply(a, c, "left", overwrite_c=True)
+        assert_array_almost_equal(q @ c[:2], qc)
+        qc, r = qr_multiply(a, eye(2), "left")
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_tall_left_pivoting(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r, jpvt = qr(a, mode="economic", pivoting=True)
+        c = [1, 2]
+        qc, r, kpvt = qr_multiply(a, c, "left", True)
+        assert_array_equal(jpvt, kpvt)
+        assert_array_almost_equal(q @ c, qc)
+        qc, r, jpvt = qr_multiply(a, eye(2), "left", True)
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_tall_right(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2, 3]
+        cq, r2 = qr_multiply(a, c)
+        assert_array_almost_equal(c @ q, cq)
+        assert_array_almost_equal(r, r2)
+        cq, r = qr_multiply(a, eye(3))
+        assert_array_almost_equal(cq, q)
+
+    def test_simple_tall_right_pivoting(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        q, r, jpvt = qr(a, pivoting=True, mode="economic")
+        c = [1, 2, 3]
+        cq, r, jpvt = qr_multiply(a, c, pivoting=True)
+        assert_array_almost_equal(c @ q, cq)
+        cq, r, jpvt = qr_multiply(a, eye(3), pivoting=True)
+        assert_array_almost_equal(cq, q)
+
+    def test_simple_fat(self):
+        # full version
+        a = [[8, 2, 5], [2, 9, 3]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a)
+        assert_equal(q.shape, (2, 2))
+        assert_equal(r.shape, (2, 3))
+
+    def test_simple_fat_pivoting(self):
+        # full version pivoting
+        a = np.asarray([[8, 2, 5], [2, 9, 3]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a[:, p])
+        assert_equal(q.shape, (2, 2))
+        assert_equal(r.shape, (2, 3))
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_fat_e(self):
+        # economy version
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r = qr(a, mode='economic')
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a)
+        assert_equal(q.shape, (2, 2))
+        assert_equal(r.shape, (2, 3))
+
+    def test_simple_fat_e_pivoting(self):
+        # economy version pivoting
+        a = np.asarray([[8, 2, 3], [2, 9, 5]])
+        q, r, p = qr(a, pivoting=True, mode='economic')
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(q @ r, a[:, p])
+        assert_equal(q.shape, (2, 2))
+        assert_equal(r.shape, (2, 3))
+        q2, r2 = qr(a[:, p], mode='economic')
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_fat_left(self):
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2]
+        qc, r2 = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        assert_array_almost_equal(r, r2)
+        qc, r = qr_multiply(a, eye(2), "left")
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_fat_left_pivoting(self):
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r, jpvt = qr(a, mode="economic", pivoting=True)
+        c = [1, 2]
+        qc, r, jpvt = qr_multiply(a, c, "left", True)
+        assert_array_almost_equal(q @ c, qc)
+        qc, r, jpvt = qr_multiply(a, eye(2), "left", True)
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_fat_right(self):
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2]
+        cq, r2 = qr_multiply(a, c)
+        assert_array_almost_equal(c @ q, cq)
+        assert_array_almost_equal(r, r2)
+        cq, r = qr_multiply(a, eye(2))
+        assert_array_almost_equal(cq, q)
+
+    def test_simple_fat_right_pivoting(self):
+        a = [[8, 2, 3], [2, 9, 5]]
+        q, r, jpvt = qr(a, pivoting=True, mode="economic")
+        c = [1, 2]
+        cq, r, jpvt = qr_multiply(a, c, pivoting=True)
+        assert_array_almost_equal(c @ q, cq)
+        cq, r, jpvt = qr_multiply(a, eye(2), pivoting=True)
+        assert_array_almost_equal(cq, q)
+
+    def test_simple_complex(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        assert_array_almost_equal(q.conj().T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_simple_complex_left(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        c = [1, 2, 3+4j]
+        qc, r = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        qc, r = qr_multiply(a, eye(3), "left")
+        assert_array_almost_equal(q, qc)
+
+    def test_simple_complex_right(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        c = [1, 2, 3+4j]
+        qc, r = qr_multiply(a, c)
+        assert_array_almost_equal(c @ q, qc)
+        qc, r = qr_multiply(a, eye(3))
+        assert_array_almost_equal(q, qc)
+
+    def test_simple_tall_complex_left(self):
+        a = [[8, 2+3j], [2, 9], [5+7j, 3]]
+        q, r = qr(a, mode="economic")
+        c = [1, 2+2j]
+        qc, r2 = qr_multiply(a, c, "left")
+        assert_array_almost_equal(q @ c, qc)
+        assert_array_almost_equal(r, r2)
+        c = array([1, 2, 0])
+        qc, r2 = qr_multiply(a, c, "left", overwrite_c=True)
+        assert_array_almost_equal(q @ c[:2], qc)
+        qc, r = qr_multiply(a, eye(2), "left")
+        assert_array_almost_equal(qc, q)
+
+    def test_simple_complex_left_conjugate(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        c = [1, 2, 3+4j]
+        qc, r = qr_multiply(a, c, "left", conjugate=True)
+        assert_array_almost_equal(q.conj() @ c, qc)
+
+    def test_simple_complex_tall_left_conjugate(self):
+        a = [[3, 3+4j], [5, 2+2j], [3, 2]]
+        q, r = qr(a, mode='economic')
+        c = [1, 3+4j]
+        qc, r = qr_multiply(a, c, "left", conjugate=True)
+        assert_array_almost_equal(q.conj() @ c, qc)
+
+    def test_simple_complex_right_conjugate(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        q, r = qr(a)
+        c = np.array([1, 2, 3+4j])
+        qc, r = qr_multiply(a, c, conjugate=True)
+        assert_array_almost_equal(c @ q.conj(), qc)
+
+    def test_simple_complex_pivoting(self):
+        a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]])
+        q, r, p = qr(a, pivoting=True)
+        d = abs(diag(r))
+        assert_(np.all(d[1:] <= d[:-1]))
+        assert_array_almost_equal(q.conj().T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a[:, p])
+        q2, r2 = qr(a[:, p])
+        assert_array_almost_equal(q, q2)
+        assert_array_almost_equal(r, r2)
+
+    def test_simple_complex_left_pivoting(self):
+        a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]])
+        q, r, jpvt = qr(a, pivoting=True)
+        c = [1, 2, 3+4j]
+        qc, r, jpvt = qr_multiply(a, c, "left", True)
+        assert_array_almost_equal(q @ c, qc)
+
+    def test_simple_complex_right_pivoting(self):
+        a = array([[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]])
+        q, r, jpvt = qr(a, pivoting=True)
+        c = [1, 2, 3+4j]
+        qc, r, jpvt = qr_multiply(a, c, pivoting=True)
+        assert_array_almost_equal(c @ q, qc)
+
+    def test_random(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            q, r = qr(a)
+            assert_array_almost_equal(q.T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a)
+
+    def test_random_left(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            q, r = qr(a)
+            c = rng.random([n])
+            qc, r = qr_multiply(a, c, "left")
+            assert_array_almost_equal(q @ c, qc)
+            qc, r = qr_multiply(a, eye(n), "left")
+            assert_array_almost_equal(q, qc)
+
+    def test_random_right(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            q, r = qr(a)
+            c = rng.random([n])
+            cq, r = qr_multiply(a, c)
+            assert_array_almost_equal(c @ q, cq)
+            cq, r = qr_multiply(a, eye(n))
+            assert_array_almost_equal(q, cq)
+
+    def test_random_pivoting(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            q, r, p = qr(a, pivoting=True)
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a[:, p])
+            q2, r2 = qr(a[:, p])
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_random_tall(self):
+        rng = np.random.RandomState(1234)
+        # full version
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a)
+            assert_array_almost_equal(q.T @ q, eye(m))
+            assert_array_almost_equal(q @ r, a)
+
+    def test_random_tall_left(self):
+        rng = np.random.RandomState(1234)
+        # full version
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a, mode="economic")
+            c = rng.random([n])
+            qc, r = qr_multiply(a, c, "left")
+            assert_array_almost_equal(q @ c, qc)
+            qc, r = qr_multiply(a, eye(n), "left")
+            assert_array_almost_equal(qc, q)
+
+    def test_random_tall_right(self):
+        rng = np.random.RandomState(1234)
+        # full version
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a, mode="economic")
+            c = rng.random([m])
+            cq, r = qr_multiply(a, c)
+            assert_array_almost_equal(c @ q, cq)
+            cq, r = qr_multiply(a, eye(m))
+            assert_array_almost_equal(cq, q)
+
+    def test_random_tall_pivoting(self):
+        rng = np.random.RandomState(1234)
+        # full version pivoting
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r, p = qr(a, pivoting=True)
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.T @ q, eye(m))
+            assert_array_almost_equal(q @ r, a[:, p])
+            q2, r2 = qr(a[:, p])
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_random_tall_e(self):
+        rng = np.random.RandomState(1234)
+        # economy version
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a, mode='economic')
+            assert_array_almost_equal(q.T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a)
+            assert_equal(q.shape, (m, n))
+            assert_equal(r.shape, (n, n))
+
+    def test_random_tall_e_pivoting(self):
+        rng = np.random.RandomState(1234)
+        # economy version pivoting
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r, p = qr(a, pivoting=True, mode='economic')
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a[:, p])
+            assert_equal(q.shape, (m, n))
+            assert_equal(r.shape, (n, n))
+            q2, r2 = qr(a[:, p], mode='economic')
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_random_trap(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r = qr(a)
+            assert_array_almost_equal(q.T @ q, eye(m))
+            assert_array_almost_equal(q @ r, a)
+
+    def test_random_trap_pivoting(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n])
+            q, r, p = qr(a, pivoting=True)
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.T @ q, eye(m))
+            assert_array_almost_equal(q @ r, a[:, p])
+            q2, r2 = qr(a[:, p])
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_random_complex(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            q, r = qr(a)
+            assert_array_almost_equal(q.conj().T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a)
+
+    def test_random_complex_left(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            q, r = qr(a)
+            c = rng.random([n]) + 1j*rng.random([n])
+            qc, r = qr_multiply(a, c, "left")
+            assert_array_almost_equal(q @ c, qc)
+            qc, r = qr_multiply(a, eye(n), "left")
+            assert_array_almost_equal(q, qc)
+
+    def test_random_complex_right(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            q, r = qr(a)
+            c = rng.random([n]) + 1j*rng.random([n])
+            cq, r = qr_multiply(a, c)
+            assert_array_almost_equal(c @ q, cq)
+            cq, r = qr_multiply(a, eye(n))
+            assert_array_almost_equal(q, cq)
+
+    def test_random_complex_pivoting(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            q, r, p = qr(a, pivoting=True)
+            d = abs(diag(r))
+            assert_(np.all(d[1:] <= d[:-1]))
+            assert_array_almost_equal(q.conj().T @ q, eye(n))
+            assert_array_almost_equal(q @ r, a[:, p])
+            q2, r2 = qr(a[:, p])
+            assert_array_almost_equal(q, q2)
+            assert_array_almost_equal(r, r2)
+
+    def test_check_finite(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        q, r = qr(a, check_finite=False)
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(q @ r, a)
+
+    def test_lwork(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        # Get comparison values
+        q, r = qr(a, lwork=None)
+
+        # Test against minimum valid lwork
+        q2, r2 = qr(a, lwork=3)
+        assert_array_almost_equal(q2, q)
+        assert_array_almost_equal(r2, r)
+
+        # Test against larger lwork
+        q3, r3 = qr(a, lwork=10)
+        assert_array_almost_equal(q3, q)
+        assert_array_almost_equal(r3, r)
+
+        # Test against explicit lwork=-1
+        q4, r4 = qr(a, lwork=-1)
+        assert_array_almost_equal(q4, q)
+        assert_array_almost_equal(r4, r)
+
+        # Test against invalid lwork
+        assert_raises(Exception, qr, (a,), {'lwork': 0})
+        assert_raises(Exception, qr, (a,), {'lwork': 2})
+
+    @pytest.mark.parametrize("m", [0, 1, 2])
+    @pytest.mark.parametrize("n", [0, 1, 2])
+    @pytest.mark.parametrize("pivoting", [False, True])
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_shape_dtype(self, m, n, pivoting, dtype):
+        k = min(m, n)
+
+        a = np.zeros((m, n), dtype=dtype)
+        q, r, *other = qr(a, pivoting=pivoting)
+        assert_equal(q.shape, (m, m))
+        assert_equal(q.dtype, dtype)
+        assert_equal(r.shape, (m, n))
+        assert_equal(r.dtype, dtype)
+        assert len(other) == (1 if pivoting else 0)
+        if pivoting:
+            p, = other
+            assert_equal(p.shape, (n,))
+            assert_equal(p.dtype, np.int32)
+
+        r, *other = qr(a, mode='r', pivoting=pivoting)
+        assert_equal(r.shape, (m, n))
+        assert_equal(r.dtype, dtype)
+        assert len(other) == (1 if pivoting else 0)
+        if pivoting:
+            p, = other
+            assert_equal(p.shape, (n,))
+            assert_equal(p.dtype, np.int32)
+
+        q, r, *other = qr(a, mode='economic', pivoting=pivoting)
+        assert_equal(q.shape, (m, k))
+        assert_equal(q.dtype, dtype)
+        assert_equal(r.shape, (k, n))
+        assert_equal(r.dtype, dtype)
+        assert len(other) == (1 if pivoting else 0)
+        if pivoting:
+            p, = other
+            assert_equal(p.shape, (n,))
+            assert_equal(p.dtype, np.int32)
+
+        (raw, tau), r, *other = qr(a, mode='raw', pivoting=pivoting)
+        assert_equal(raw.shape, (m, n))
+        assert_equal(raw.dtype, dtype)
+        assert_equal(tau.shape, (k,))
+        assert_equal(tau.dtype, dtype)
+        assert_equal(r.shape, (k, n))
+        assert_equal(r.dtype, dtype)
+        assert len(other) == (1 if pivoting else 0)
+        if pivoting:
+            p, = other
+            assert_equal(p.shape, (n,))
+            assert_equal(p.dtype, np.int32)
+
+    @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+    def test_empty(self, m, n):
+        k = min(m, n)
+
+        a = np.empty((m, n))
+        q, r = qr(a)
+        assert_allclose(q, np.identity(m))
+        assert_allclose(r, np.empty((m, n)))
+
+        q, r, p = qr(a, pivoting=True)
+        assert_allclose(q, np.identity(m))
+        assert_allclose(r, np.empty((m, n)))
+        assert_allclose(p, np.arange(n))
+
+        r, = qr(a, mode='r')
+        assert_allclose(r, np.empty((m, n)))
+
+        q, r = qr(a, mode='economic')
+        assert_allclose(q, np.empty((m, k)))
+        assert_allclose(r, np.empty((k, n)))
+
+        (raw, tau), r = qr(a, mode='raw')
+        assert_allclose(raw, np.empty((m, n)))
+        assert_allclose(tau, np.empty((k,)))
+        assert_allclose(r, np.empty((k, n)))
+
+    def test_multiply_empty(self):
+        a = np.empty((0, 0))
+        c = np.empty((0, 0))
+        cq, r = qr_multiply(a, c)
+        assert_allclose(cq, np.empty((0, 0)))
+
+        a = np.empty((0, 2))
+        c = np.empty((2, 0))
+        cq, r = qr_multiply(a, c)
+        assert_allclose(cq, np.empty((2, 0)))
+
+        a = np.empty((2, 0))
+        c = np.empty((0, 2))
+        cq, r = qr_multiply(a, c)
+        assert_allclose(cq, np.empty((0, 2)))
+
+
+class TestRQ:
+    def test_simple(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        r, q = rq(a)
+        assert_array_almost_equal(q @ q.T, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_r(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        r, q = rq(a)
+        r2 = rq(a, mode='r')
+        assert_array_almost_equal(r, r2)
+
+    def test_random(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            r, q = rq(a)
+            assert_array_almost_equal(q @ q.T, eye(n))
+            assert_array_almost_equal(r @ q, a)
+
+    def test_simple_trap(self):
+        a = [[8, 2, 3], [2, 9, 3]]
+        r, q = rq(a)
+        assert_array_almost_equal(q.T @ q, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_simple_tall(self):
+        a = [[8, 2], [2, 9], [5, 3]]
+        r, q = rq(a)
+        assert_array_almost_equal(q.T @ q, eye(2))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_simple_fat(self):
+        a = [[8, 2, 5], [2, 9, 3]]
+        r, q = rq(a)
+        assert_array_almost_equal(q @ q.T, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_simple_complex(self):
+        a = [[3, 3+4j, 5], [5, 2, 2+7j], [3, 2, 7]]
+        r, q = rq(a)
+        assert_array_almost_equal(q @ q.conj().T, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    def test_random_tall(self):
+        rng = np.random.RandomState(1234)
+        m = 200
+        n = 100
+        for k in range(2):
+            a = rng.random([m, n])
+            r, q = rq(a)
+            assert_array_almost_equal(q @ q.T, eye(n))
+            assert_array_almost_equal(r @ q, a)
+
+    def test_random_trap(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n])
+            r, q = rq(a)
+            assert_array_almost_equal(q @ q.T, eye(n))
+            assert_array_almost_equal(r @ q, a)
+
+    def test_random_trap_economic(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n])
+            r, q = rq(a, mode='economic')
+            assert_array_almost_equal(q @ q.T, eye(m))
+            assert_array_almost_equal(r @ q, a)
+            assert_equal(q.shape, (m, n))
+            assert_equal(r.shape, (m, m))
+
+    def test_random_complex(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            r, q = rq(a)
+            assert_array_almost_equal(q @ q.conj().T, eye(n))
+            assert_array_almost_equal(r @ q, a)
+
+    def test_random_complex_economic(self):
+        rng = np.random.RandomState(1234)
+        m = 100
+        n = 200
+        for k in range(2):
+            a = rng.random([m, n]) + 1j*rng.random([m, n])
+            r, q = rq(a, mode='economic')
+            assert_array_almost_equal(q @ q.conj().T, eye(m))
+            assert_array_almost_equal(r @ q, a)
+            assert_equal(q.shape, (m, n))
+            assert_equal(r.shape, (m, m))
+
+    def test_check_finite(self):
+        a = [[8, 2, 3], [2, 9, 3], [5, 3, 6]]
+        r, q = rq(a, check_finite=False)
+        assert_array_almost_equal(q @ q.T, eye(3))
+        assert_array_almost_equal(r @ q, a)
+
+    @pytest.mark.parametrize("m", [0, 1, 2])
+    @pytest.mark.parametrize("n", [0, 1, 2])
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_shape_dtype(self, m, n, dtype):
+        k = min(m, n)
+
+        a = np.zeros((m, n), dtype=dtype)
+        r, q = rq(a)
+        assert_equal(q.shape, (n, n))
+        assert_equal(r.shape, (m, n))
+        assert_equal(r.dtype, dtype)
+        assert_equal(q.dtype, dtype)
+
+        r = rq(a, mode='r')
+        assert_equal(r.shape, (m, n))
+        assert_equal(r.dtype, dtype)
+
+        r, q = rq(a, mode='economic')
+        assert_equal(r.shape, (m, k))
+        assert_equal(r.dtype, dtype)
+        assert_equal(q.shape, (k, n))
+        assert_equal(q.dtype, dtype)
+
+    @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+    def test_empty(self, m, n):
+        k = min(m, n)
+
+        a = np.empty((m, n))
+        r, q = rq(a)
+        assert_allclose(r, np.empty((m, n)))
+        assert_allclose(q, np.identity(n))
+
+        r = rq(a, mode='r')
+        assert_allclose(r, np.empty((m, n)))
+
+        r, q = rq(a, mode='economic')
+        assert_allclose(r, np.empty((m, k)))
+        assert_allclose(q, np.empty((k, n)))
+
+
+class TestSchur:
+
+    def check_schur(self, a, t, u, rtol, atol):
+        # Check that the Schur decomposition is correct.
+        assert_allclose(u @ t @ u.conj().T, a, rtol=rtol, atol=atol,
+                        err_msg="Schur decomposition does not match 'a'")
+        # The expected value of u @ u.H - I is all zeros, so test
+        # with absolute tolerance only.
+        assert_allclose(u @ u.conj().T - np.eye(len(u)), 0, rtol=0, atol=atol,
+                        err_msg="u is not unitary")
+
+    def test_simple(self):
+        a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]]
+        t, z = schur(a)
+        self.check_schur(a, t, z, rtol=1e-14, atol=5e-15)
+        tc, zc = schur(a, 'complex')
+        assert_(np.any(ravel(iscomplex(zc))) and np.any(ravel(iscomplex(tc))))
+        self.check_schur(a, tc, zc, rtol=1e-14, atol=5e-15)
+        tc2, zc2 = rsf2csf(tc, zc)
+        self.check_schur(a, tc2, zc2, rtol=1e-14, atol=5e-15)
+
+    @pytest.mark.parametrize(
+        'sort, expected_diag',
+        [('lhp', [-np.sqrt(2), -0.5, np.sqrt(2), 0.5]),
+         ('rhp', [np.sqrt(2), 0.5, -np.sqrt(2), -0.5]),
+         ('iuc', [-0.5, 0.5, np.sqrt(2), -np.sqrt(2)]),
+         ('ouc', [np.sqrt(2), -np.sqrt(2), -0.5, 0.5]),
+         (lambda x: x >= 0.0, [np.sqrt(2), 0.5, -np.sqrt(2), -0.5])]
+    )
+    def test_sort(self, sort, expected_diag):
+        # The exact eigenvalues of this matrix are
+        #   -sqrt(2), sqrt(2), -1/2, 1/2.
+        a = [[4., 3., 1., -1.],
+             [-4.5, -3.5, -1., 1.],
+             [9., 6., -4., 4.5],
+             [6., 4., -3., 3.5]]
+        t, u, sdim = schur(a, sort=sort)
+        self.check_schur(a, t, u, rtol=1e-14, atol=5e-15)
+        assert_allclose(np.diag(t), expected_diag, rtol=1e-12)
+        assert_equal(2, sdim)
+
+    def test_sort_errors(self):
+        a = [[4., 3., 1., -1.],
+             [-4.5, -3.5, -1., 1.],
+             [9., 6., -4., 4.5],
+             [6., 4., -3., 3.5]]
+        assert_raises(ValueError, schur, a, sort='unsupported')
+        assert_raises(ValueError, schur, a, sort=1)
+
+    def test_check_finite(self):
+        a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]]
+        t, z = schur(a, check_finite=False)
+        assert_array_almost_equal(z @ t @ z.conj().T, a)
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        t, z = schur(a)
+        t0, z0 = schur(np.eye(2, dtype=dt))
+        assert_allclose(t, np.empty((0, 0)))
+        assert_allclose(z, np.empty((0, 0)))
+        assert t.dtype == t0.dtype
+        assert z.dtype == z0.dtype
+
+        t, z, sdim = schur(a, sort='lhp')
+        assert_allclose(t, np.empty((0, 0)))
+        assert_allclose(z, np.empty((0, 0)))
+        assert_equal(sdim, 0)
+        assert t.dtype == t0.dtype
+        assert z.dtype == z0.dtype
+
+    @pytest.mark.parametrize('sort', ['iuc', 'ouc'])
+    @pytest.mark.parametrize('output', ['real', 'complex'])
+    @pytest.mark.parametrize('dtype', [np.float32, np.float64,
+                                       np.complex64, np.complex128])
+    def test_gh_13137_sort_str(self, sort, output, dtype):
+        # gh-13137 reported that sort values 'iuc' and 'ouc' were not
+        # correct because the callables assumed that the eigenvalues would
+        # always be expressed as a single complex number.
+        # In fact, when `output='real'` and the dtype is real, the
+        # eigenvalues are passed as separate real and imaginary components
+        # (yet no error is raised if the callable accepts only one argument).
+        #
+        # This tests these sort values by counting the number of eigenvalues
+        # `schur` reports as being inside/outside the unit circle.
+
+        # Real matrix with eigenvalues 0.1 +- 2j
+        A = np.asarray([[0.1, -2], [2, 0.1]])
+
+        # Previously, this would fail for `output='real'` with real dtypes
+        sdim = schur(A.astype(dtype), sort=sort, output=output)[-1]
+        assert sdim == 0 if sort == 'iuc' else sdim == 2
+
+    @pytest.mark.parametrize('output', ['real', 'complex'])
+    @pytest.mark.parametrize('dtype', [np.float32, np.float64,
+                                       np.complex64, np.complex128])
+    def test_gh_13137_sort_custom(self, output, dtype):
+        # This simply tests our understanding of how eigenvalues are
+        # passed to a sort callable. If `output='real'` and the dtype is real,
+        # real and imaginary parts are passed as separate real arguments;
+        # otherwise, they are passed a single complex argument.
+        # Also, if `output='real'` and the dtype is real, when either
+        # eigenvalue in a complex conjugate pair satisfies the sort condition,
+        # `sdim` is incremented by TWO.
+
+        # Real matrix with eigenvalues 0.1 +- 2j
+        A = np.asarray([[0.1, -2], [2, 0.1]])
+
+        all_real = output=='real' and dtype in {np.float32, np.float64}
+
+        def sort(x, y=None):
+            if all_real:
+                assert not np.iscomplexobj(x)
+                assert y is not None and np.isreal(y)
+                z = x + y*1j
+            else:
+                assert np.iscomplexobj(x)
+                assert y is None
+                z = x
+            return z.imag > 1e-15
+
+        # Only one complex eigenvalue satisfies the condition, but when
+        # `all_real` applies, both eigenvalues in the complex conjugate pair
+        # are counted.
+        sdim = schur(A.astype(dtype), sort=sort, output=output)[-1]
+        assert sdim == 2 if all_real else sdim == 1
+
+
+class TestHessenberg:
+
+    def test_simple(self):
+        a = [[-149, -50, -154],
+             [537, 180, 546],
+             [-27, -9, -25]]
+        h1 = [[-149.0000, 42.2037, -156.3165],
+              [-537.6783, 152.5511, -554.9272],
+              [0, 0.0728, 2.4489]]
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q.T @ a @ q, h)
+        assert_array_almost_equal(h, h1, decimal=4)
+
+    def test_simple_complex(self):
+        a = [[-149, -50, -154],
+             [537, 180j, 546],
+             [-27j, -9, -25]]
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q.conj().T @ a @ q, h)
+
+    def test_simple2(self):
+        a = [[1, 2, 3, 4, 5, 6, 7],
+             [0, 2, 3, 4, 6, 7, 2],
+             [0, 2, 2, 3, 0, 3, 2],
+             [0, 0, 2, 8, 0, 0, 2],
+             [0, 3, 1, 2, 0, 1, 2],
+             [0, 1, 2, 3, 0, 1, 0],
+             [0, 0, 0, 0, 0, 1, 2]]
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q.T @ a @ q, h)
+
+    def test_simple3(self):
+        a = np.eye(3)
+        a[-1, 0] = 2
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q.T @ a @ q, h)
+
+    def test_random(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n])
+            h, q = hessenberg(a, calc_q=1)
+            assert_array_almost_equal(q.T @ a @ q, h)
+
+    def test_random_complex(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        for k in range(2):
+            a = rng.random([n, n]) + 1j*rng.random([n, n])
+            h, q = hessenberg(a, calc_q=1)
+            assert_array_almost_equal(q.conj().T @ a @ q, h)
+
+    def test_check_finite(self):
+        a = [[-149, -50, -154],
+             [537, 180, 546],
+             [-27, -9, -25]]
+        h1 = [[-149.0000, 42.2037, -156.3165],
+              [-537.6783, 152.5511, -554.9272],
+              [0, 0.0728, 2.4489]]
+        h, q = hessenberg(a, calc_q=1, check_finite=False)
+        assert_array_almost_equal(q.T @ a @ q, h)
+        assert_array_almost_equal(h, h1, decimal=4)
+
+    def test_2x2(self):
+        a = [[2, 1], [7, 12]]
+
+        h, q = hessenberg(a, calc_q=1)
+        assert_array_almost_equal(q, np.eye(2))
+        assert_array_almost_equal(h, a)
+
+        b = [[2-7j, 1+2j], [7+3j, 12-2j]]
+        h2, q2 = hessenberg(b, calc_q=1)
+        assert_array_almost_equal(q2, np.eye(2))
+        assert_array_almost_equal(h2, b)
+
+    @pytest.mark.parametrize('dt', [int, float, float32, complex, complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        h = hessenberg(a)
+        assert h.shape == (0, 0)
+        assert h.dtype == hessenberg(np.eye(3, dtype=dt)).dtype
+
+        h, q = hessenberg(a, calc_q=True)
+        h3, q3 = hessenberg(a, calc_q=True)
+        assert h.shape == (0, 0)
+        assert h.dtype == h3.dtype
+
+        assert q.shape == (0, 0)
+        assert q.dtype == q3.dtype
+
+
+blas_provider = blas_version = None
+if CONFIG is not None:
+    blas_provider = CONFIG['Build Dependencies']['blas']['name']
+    blas_version = CONFIG['Build Dependencies']['blas']['version']
+
+
+class TestQZ:
+    def test_qz_single(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n]).astype(float32)
+        B = rng.random([n, n]).astype(float32)
+        AA, BB, Q, Z = qz(A, B)
+        assert_array_almost_equal(Q @ AA @ Z.T, A, decimal=5)
+        assert_array_almost_equal(Q @ BB @ Z.T, B, decimal=5)
+        assert_array_almost_equal(Q @ Q.T, eye(n), decimal=5)
+        assert_array_almost_equal(Z @ Z.T, eye(n), decimal=5)
+        assert_(np.all(diag(BB) >= 0))
+
+    def test_qz_double(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n])
+        B = rng.random([n, n])
+        AA, BB, Q, Z = qz(A, B)
+        assert_array_almost_equal(Q @ AA @ Z.T, A)
+        assert_array_almost_equal(Q @ BB @ Z.T, B)
+        assert_array_almost_equal(Q @ Q.T, eye(n))
+        assert_array_almost_equal(Z @ Z.T, eye(n))
+        assert_(np.all(diag(BB) >= 0))
+
+    def test_qz_complex(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n]) + 1j*rng.random([n, n])
+        B = rng.random([n, n]) + 1j*rng.random([n, n])
+        AA, BB, Q, Z = qz(A, B)
+        assert_array_almost_equal(Q @ AA @ Z.conj().T, A)
+        assert_array_almost_equal(Q @ BB @ Z.conj().T, B)
+        assert_array_almost_equal(Q @ Q.conj().T, eye(n))
+        assert_array_almost_equal(Z @ Z.conj().T, eye(n))
+        assert_(np.all(diag(BB) >= 0))
+        assert_(np.all(diag(BB).imag == 0))
+
+    def test_qz_complex64(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64)
+        B = (rng.random([n, n]) + 1j*rng.random([n, n])).astype(complex64)
+        AA, BB, Q, Z = qz(A, B)
+        assert_array_almost_equal(Q @ AA @ Z.conj().T, A, decimal=5)
+        assert_array_almost_equal(Q @ BB @ Z.conj().T, B, decimal=5)
+        assert_array_almost_equal(Q @ Q.conj().T, eye(n), decimal=5)
+        assert_array_almost_equal(Z @ Z.conj().T, eye(n), decimal=5)
+        assert_(np.all(diag(BB) >= 0))
+        assert_(np.all(diag(BB).imag == 0))
+
+    def test_qz_double_complex(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n])
+        B = rng.random([n, n])
+        AA, BB, Q, Z = qz(A, B, output='complex')
+        aa = Q @ AA @ Z.conj().T
+        assert_array_almost_equal(aa.real, A)
+        assert_array_almost_equal(aa.imag, 0)
+        bb = Q @ BB @ Z.conj().T
+        assert_array_almost_equal(bb.real, B)
+        assert_array_almost_equal(bb.imag, 0)
+        assert_array_almost_equal(Q @ Q.conj().T, eye(n))
+        assert_array_almost_equal(Z @ Z.conj().T, eye(n))
+        assert_(np.all(diag(BB) >= 0))
+
+    def test_qz_double_sort(self):
+        # from https://www.nag.com/lapack-ex/node119.html
+        # NOTE: These matrices may be ill-conditioned and lead to a
+        # seg fault on certain python versions when compiled with
+        # sse2 or sse3 older ATLAS/LAPACK binaries for windows
+        # A =   np.array([[3.9,  12.5, -34.5,  -0.5],
+        #                [ 4.3,  21.5, -47.5,   7.5],
+        #                [ 4.3,  21.5, -43.5,   3.5],
+        #                [ 4.4,  26.0, -46.0,   6.0 ]])
+
+        # B = np.array([[ 1.0,   2.0,  -3.0,   1.0],
+        #              [1.0,   3.0,  -5.0,   4.0],
+        #              [1.0,   3.0,  -4.0,   3.0],
+        #              [1.0,   3.0,  -4.0,   4.0]])
+        A = np.array([[3.9, 12.5, -34.5, 2.5],
+                      [4.3, 21.5, -47.5, 7.5],
+                      [4.3, 1.5, -43.5, 3.5],
+                      [4.4, 6.0, -46.0, 6.0]])
+
+        B = np.array([[1.0, 1.0, -3.0, 1.0],
+                      [1.0, 3.0, -5.0, 4.4],
+                      [1.0, 2.0, -4.0, 1.0],
+                      [1.2, 3.0, -4.0, 4.0]])
+
+        assert_raises(ValueError, qz, A, B, sort=lambda ar, ai, beta: ai == 0)
+        if False:
+            AA, BB, Q, Z, sdim = qz(A, B, sort=lambda ar, ai, beta: ai == 0)
+            # assert_(sdim == 2)
+            assert_(sdim == 4)
+            assert_array_almost_equal(Q @ AA @ Z.T, A)
+            assert_array_almost_equal(Q @ BB @ Z.T, B)
+
+            # test absolute values bc the sign is ambiguous and
+            # might be platform dependent
+            assert_array_almost_equal(np.abs(AA), np.abs(np.array(
+                            [[35.7864, -80.9061, -12.0629, -9.498],
+                             [0., 2.7638, -2.3505, 7.3256],
+                             [0., 0., 0.6258, -0.0398],
+                             [0., 0., 0., -12.8217]])), 4)
+            assert_array_almost_equal(np.abs(BB), np.abs(np.array(
+                            [[4.5324, -8.7878, 3.2357, -3.5526],
+                             [0., 1.4314, -2.1894, 0.9709],
+                             [0., 0., 1.3126, -0.3468],
+                             [0., 0., 0., 0.559]])), 4)
+            assert_array_almost_equal(np.abs(Q), np.abs(np.array(
+                            [[-0.4193, -0.605, -0.1894, -0.6498],
+                             [-0.5495, 0.6987, 0.2654, -0.3734],
+                             [-0.4973, -0.3682, 0.6194, 0.4832],
+                             [-0.5243, 0.1008, -0.7142, 0.4526]])), 4)
+            assert_array_almost_equal(np.abs(Z), np.abs(np.array(
+                            [[-0.9471, -0.2971, -0.1217, 0.0055],
+                             [-0.0367, 0.1209, 0.0358, 0.9913],
+                             [0.3171, -0.9041, -0.2547, 0.1312],
+                             [0.0346, 0.2824, -0.9587, 0.0014]])), 4)
+
+        # test absolute values bc the sign is ambiguous and might be platform
+        # dependent
+        # assert_array_almost_equal(abs(AA), abs(np.array([
+        #                [3.8009, -69.4505, 50.3135, -43.2884],
+        #                [0.0000, 9.2033, -0.2001, 5.9881],
+        #                [0.0000, 0.0000, 1.4279, 4.4453],
+        #                [0.0000, 0.0000, 0.9019, -1.1962]])), 4)
+        # assert_array_almost_equal(abs(BB), abs(np.array([
+        #                [1.9005, -10.2285, 0.8658, -5.2134],
+        #                [0.0000,   2.3008, 0.7915,  0.4262],
+        #                [0.0000,   0.0000, 0.8101,  0.0000],
+        #                [0.0000,   0.0000, 0.0000, -0.2823]])), 4)
+        # assert_array_almost_equal(abs(Q), abs(np.array([
+        #                [0.4642,  0.7886,  0.2915, -0.2786],
+        #                [0.5002, -0.5986,  0.5638, -0.2713],
+        #                [0.5002,  0.0154, -0.0107,  0.8657],
+        #                [0.5331, -0.1395, -0.7727, -0.3151]])), 4)
+        # assert_array_almost_equal(dot(Q,Q.T), eye(4))
+        # assert_array_almost_equal(abs(Z), abs(np.array([
+        #                [0.9961, -0.0014,  0.0887, -0.0026],
+        #                [0.0057, -0.0404, -0.0938, -0.9948],
+        #                [0.0626,  0.7194, -0.6908,  0.0363],
+        #                [0.0626, -0.6934, -0.7114,  0.0956]])), 4)
+        # assert_array_almost_equal(dot(Z,Z.T), eye(4))
+
+    # def test_qz_complex_sort(self):
+    #    cA = np.array([
+    #   [-21.10+22.50*1j, 53.50+-50.50*1j, -34.50+127.50*1j, 7.50+  0.50*1j],
+    #   [-0.46+ -7.78*1j, -3.50+-37.50*1j, -15.50+ 58.50*1j,-10.50+ -1.50*1j],
+    #   [ 4.30+ -5.50*1j, 39.70+-17.10*1j, -68.50+ 12.50*1j, -7.50+ -3.50*1j],
+    #   [ 5.50+  4.40*1j, 14.40+ 43.30*1j, -32.50+-46.00*1j,-19.00+-32.50*1j]])
+
+    #    cB =  np.array([
+    #   [1.00+ -5.00*1j, 1.60+  1.20*1j,-3.00+  0.00*1j, 0.00+ -1.00*1j],
+    #   [0.80+ -0.60*1j, 3.00+ -5.00*1j,-4.00+  3.00*1j,-2.40+ -3.20*1j],
+    #   [1.00+  0.00*1j, 2.40+  1.80*1j,-4.00+ -5.00*1j, 0.00+ -3.00*1j],
+    #   [0.00+  1.00*1j,-1.80+  2.40*1j, 0.00+ -4.00*1j, 4.00+ -5.00*1j]])
+
+    #    AAS,BBS,QS,ZS,sdim = qz(cA,cB,sort='lhp')
+
+    #    eigenvalues = diag(AAS)/diag(BBS)
+    #    assert_(np.all(np.real(eigenvalues[:sdim] < 0)))
+    #    assert_(np.all(np.real(eigenvalues[sdim:] > 0)))
+
+    def test_check_finite(self):
+        rng = np.random.RandomState(12345)
+        n = 5
+        A = rng.random([n, n])
+        B = rng.random([n, n])
+        AA, BB, Q, Z = qz(A, B, check_finite=False)
+        assert_array_almost_equal(Q @ AA @ Z.T, A)
+        assert_array_almost_equal(Q @ BB @ Z.T, B)
+        assert_array_almost_equal(Q @ Q.T, eye(n))
+        assert_array_almost_equal(Z @ Z.T, eye(n))
+        assert_(np.all(diag(BB) >= 0))
+
+
+class TestOrdQZ:
+    @classmethod
+    def setup_class(cls):
+        # https://www.nag.com/lapack-ex/node119.html
+        A1 = np.array([[-21.10 - 22.50j, 53.5 - 50.5j, -34.5 + 127.5j,
+                        7.5 + 0.5j],
+                       [-0.46 - 7.78j, -3.5 - 37.5j, -15.5 + 58.5j,
+                        -10.5 - 1.5j],
+                       [4.30 - 5.50j, 39.7 - 17.1j, -68.5 + 12.5j,
+                        -7.5 - 3.5j],
+                       [5.50 + 4.40j, 14.4 + 43.3j, -32.5 - 46.0j,
+                        -19.0 - 32.5j]])
+
+        B1 = np.array([[1.0 - 5.0j, 1.6 + 1.2j, -3 + 0j, 0.0 - 1.0j],
+                       [0.8 - 0.6j, .0 - 5.0j, -4 + 3j, -2.4 - 3.2j],
+                       [1.0 + 0.0j, 2.4 + 1.8j, -4 - 5j, 0.0 - 3.0j],
+                       [0.0 + 1.0j, -1.8 + 2.4j, 0 - 4j, 4.0 - 5.0j]])
+
+        # https://www.nag.com/numeric/fl/nagdoc_fl23/xhtml/F08/f08yuf.xml
+        A2 = np.array([[3.9, 12.5, -34.5, -0.5],
+                       [4.3, 21.5, -47.5, 7.5],
+                       [4.3, 21.5, -43.5, 3.5],
+                       [4.4, 26.0, -46.0, 6.0]])
+
+        B2 = np.array([[1, 2, -3, 1],
+                       [1, 3, -5, 4],
+                       [1, 3, -4, 3],
+                       [1, 3, -4, 4]])
+
+        # example with the eigenvalues
+        # -0.33891648, 1.61217396+0.74013521j, 1.61217396-0.74013521j,
+        # 0.61244091
+        # thus featuring:
+        #  * one complex conjugate eigenvalue pair,
+        #  * one eigenvalue in the lhp
+        #  * 2 eigenvalues in the unit circle
+        #  * 2 non-real eigenvalues
+        A3 = np.array([[5., 1., 3., 3.],
+                       [4., 4., 2., 7.],
+                       [7., 4., 1., 3.],
+                       [0., 4., 8., 7.]])
+        B3 = np.array([[8., 10., 6., 10.],
+                       [7., 7., 2., 9.],
+                       [9., 1., 6., 6.],
+                       [5., 1., 4., 7.]])
+
+        # example with infinite eigenvalues
+        A4 = np.eye(2)
+        B4 = np.diag([0, 1])
+
+        # example with (alpha, beta) = (0, 0)
+        A5 = np.diag([1, 0])
+
+        cls.A = [A1, A2, A3, A4, A5]
+        cls.B = [B1, B2, B3, B4, A5]
+
+    def qz_decomp(self, sort):
+        with np.errstate(all='raise'):
+            ret = [ordqz(Ai, Bi, sort=sort) for Ai, Bi in zip(self.A, self.B)]
+        return tuple(ret)
+
+    def check(self, A, B, sort, AA, BB, alpha, beta, Q, Z):
+        Id = np.eye(*A.shape)
+        # make sure Q and Z are orthogonal
+        assert_array_almost_equal(Q @ Q.T.conj(), Id)
+        assert_array_almost_equal(Z @ Z.T.conj(), Id)
+        # check factorization
+        assert_array_almost_equal(Q @ AA, A @ Z)
+        assert_array_almost_equal(Q @ BB, B @ Z)
+        # check shape of AA and BB
+        assert_array_equal(np.tril(AA, -2), np.zeros(AA.shape))
+        assert_array_equal(np.tril(BB, -1), np.zeros(BB.shape))
+        # check eigenvalues
+        for i in range(A.shape[0]):
+            # does the current diagonal element belong to a 2-by-2 block
+            # that was already checked?
+            if i > 0 and A[i, i - 1] != 0:
+                continue
+            # take care of 2-by-2 blocks
+            if i < AA.shape[0] - 1 and AA[i + 1, i] != 0:
+                evals, _ = eig(AA[i:i + 2, i:i + 2], BB[i:i + 2, i:i + 2])
+                # make sure the pair of complex conjugate eigenvalues
+                # is ordered consistently (positive imaginary part first)
+                if evals[0].imag < 0:
+                    evals = evals[[1, 0]]
+                tmp = alpha[i:i + 2]/beta[i:i + 2]
+                if tmp[0].imag < 0:
+                    tmp = tmp[[1, 0]]
+                assert_array_almost_equal(evals, tmp)
+            else:
+                if alpha[i] == 0 and beta[i] == 0:
+                    assert_equal(AA[i, i], 0)
+                    assert_equal(BB[i, i], 0)
+                elif beta[i] == 0:
+                    assert_equal(BB[i, i], 0)
+                else:
+                    assert_almost_equal(AA[i, i]/BB[i, i], alpha[i]/beta[i])
+        sortfun = _select_function(sort)
+        lastsort = True
+        for i in range(A.shape[0]):
+            cursort = sortfun(np.array([alpha[i]]), np.array([beta[i]]))
+            # once the sorting criterion was not matched all subsequent
+            # eigenvalues also shouldn't match
+            if not lastsort:
+                assert not cursort
+            lastsort = cursort
+
+    def check_all(self, sort):
+        ret = self.qz_decomp(sort)
+
+        for reti, Ai, Bi in zip(ret, self.A, self.B):
+            self.check(Ai, Bi, sort, *reti)
+
+    def test_lhp(self):
+        self.check_all('lhp')
+
+    def test_rhp(self):
+        self.check_all('rhp')
+
+    def test_iuc(self):
+        self.check_all('iuc')
+
+    def test_ouc(self):
+        self.check_all('ouc')
+
+    def test_ref(self):
+        # real eigenvalues first (top-left corner)
+        def sort(x, y):
+            out = np.empty_like(x, dtype=bool)
+            nonzero = (y != 0)
+            out[~nonzero] = False
+            out[nonzero] = (x[nonzero]/y[nonzero]).imag == 0
+            return out
+
+        self.check_all(sort)
+
+    def test_cef(self):
+        # complex eigenvalues first (top-left corner)
+        def sort(x, y):
+            out = np.empty_like(x, dtype=bool)
+            nonzero = (y != 0)
+            out[~nonzero] = False
+            out[nonzero] = (x[nonzero]/y[nonzero]).imag != 0
+            return out
+
+        self.check_all(sort)
+
+    def test_diff_input_types(self):
+        ret = ordqz(self.A[1], self.B[2], sort='lhp')
+        self.check(self.A[1], self.B[2], 'lhp', *ret)
+
+        ret = ordqz(self.B[2], self.A[1], sort='lhp')
+        self.check(self.B[2], self.A[1], 'lhp', *ret)
+
+    def test_sort_explicit(self):
+        # Test order of the eigenvalues in the 2 x 2 case where we can
+        # explicitly compute the solution
+        A1 = np.eye(2)
+        B1 = np.diag([-2, 0.5])
+        expected1 = [('lhp', [-0.5, 2]),
+                     ('rhp', [2, -0.5]),
+                     ('iuc', [-0.5, 2]),
+                     ('ouc', [2, -0.5])]
+        A2 = np.eye(2)
+        B2 = np.diag([-2 + 1j, 0.5 + 0.5j])
+        expected2 = [('lhp', [1/(-2 + 1j), 1/(0.5 + 0.5j)]),
+                     ('rhp', [1/(0.5 + 0.5j), 1/(-2 + 1j)]),
+                     ('iuc', [1/(-2 + 1j), 1/(0.5 + 0.5j)]),
+                     ('ouc', [1/(0.5 + 0.5j), 1/(-2 + 1j)])]
+        # 'lhp' is ambiguous so don't test it
+        A3 = np.eye(2)
+        B3 = np.diag([2, 0])
+        expected3 = [('rhp', [0.5, np.inf]),
+                     ('iuc', [0.5, np.inf]),
+                     ('ouc', [np.inf, 0.5])]
+        # 'rhp' is ambiguous so don't test it
+        A4 = np.eye(2)
+        B4 = np.diag([-2, 0])
+        expected4 = [('lhp', [-0.5, np.inf]),
+                     ('iuc', [-0.5, np.inf]),
+                     ('ouc', [np.inf, -0.5])]
+        A5 = np.diag([0, 1])
+        B5 = np.diag([0, 0.5])
+        # 'lhp' and 'iuc' are ambiguous so don't test them
+        expected5 = [('rhp', [2, np.nan]),
+                     ('ouc', [2, np.nan])]
+
+        A = [A1, A2, A3, A4, A5]
+        B = [B1, B2, B3, B4, B5]
+        expected = [expected1, expected2, expected3, expected4, expected5]
+        for Ai, Bi, expectedi in zip(A, B, expected):
+            for sortstr, expected_eigvals in expectedi:
+                _, _, alpha, beta, _, _ = ordqz(Ai, Bi, sort=sortstr)
+                azero = (alpha == 0)
+                bzero = (beta == 0)
+                x = np.empty_like(alpha)
+                x[azero & bzero] = np.nan
+                x[~azero & bzero] = np.inf
+                x[~bzero] = alpha[~bzero]/beta[~bzero]
+                assert_allclose(expected_eigvals, x)
+
+
+class TestOrdQZWorkspaceSize:
+    @pytest.mark.fail_slow(5)
+    def test_decompose(self):
+        rng = np.random.RandomState(12345)
+        N = 202
+        # raises error if lwork parameter to dtrsen is too small
+        for ddtype in [np.float32, np.float64]:
+            A = rng.random((N, N)).astype(ddtype)
+            B = rng.random((N, N)).astype(ddtype)
+            # sort = lambda ar, ai, b: ar**2 + ai**2 < b**2
+            _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta,
+                      output='real')
+
+        for ddtype in [np.complex128, np.complex64]:
+            A = rng.random((N, N)).astype(ddtype)
+            B = rng.random((N, N)).astype(ddtype)
+            _ = ordqz(A, B, sort=lambda alpha, beta: alpha < beta,
+                      output='complex')
+
+    @pytest.mark.slow
+    def test_decompose_ouc(self):
+        rng = np.random.RandomState(12345)
+        N = 202
+        # segfaults if lwork parameter to dtrsen is too small
+        for ddtype in [np.float32, np.float64, np.complex128, np.complex64]:
+            A = rng.random((N, N)).astype(ddtype)
+            B = rng.random((N, N)).astype(ddtype)
+            S, T, alpha, beta, U, V = ordqz(A, B, sort='ouc')
+
+
+class TestDatacopied:
+
+    def test_datacopied(self):
+        from scipy.linalg._decomp import _datacopied
+
+        M = matrix([[0, 1], [2, 3]])
+        A = asarray(M)
+        L = M.tolist()
+        M2 = M.copy()
+
+        class Fake1:
+            def __array__(self, dtype=None, copy=None):
+                return A
+
+        class Fake2:
+            __array_interface__ = A.__array_interface__
+
+        F1 = Fake1()
+        F2 = Fake2()
+
+        for item, status in [(M, False), (A, False), (L, True),
+                             (M2, False), (F1, False), (F2, False)]:
+            arr = asarray(item)
+            assert_equal(_datacopied(arr, item), status,
+                         err_msg=repr(item))
+
+
+def test_aligned_mem_float():
+    """Check linalg works with non-aligned memory (float32)"""
+    # Allocate 402 bytes of memory (allocated on boundary)
+    a = arange(402, dtype=np.uint8)
+
+    # Create an array with boundary offset 4
+    z = np.frombuffer(a.data, offset=2, count=100, dtype=float32)
+    z.shape = 10, 10
+
+    eig(z, overwrite_a=True)
+    eig(z.T, overwrite_a=True)
+
+
+@pytest.mark.skipif(platform.machine() == 'ppc64le',
+                    reason="crashes on ppc64le")
+def test_aligned_mem():
+    """Check linalg works with non-aligned memory (float64)"""
+    # Allocate 804 bytes of memory (allocated on boundary)
+    a = arange(804, dtype=np.uint8)
+
+    # Create an array with boundary offset 4
+    z = np.frombuffer(a.data, offset=4, count=100, dtype=float)
+    z.shape = 10, 10
+
+    eig(z, overwrite_a=True)
+    eig(z.T, overwrite_a=True)
+
+
+def test_aligned_mem_complex():
+    """Check that complex objects don't need to be completely aligned"""
+    # Allocate 1608 bytes of memory (allocated on boundary)
+    a = zeros(1608, dtype=np.uint8)
+
+    # Create an array with boundary offset 8
+    z = np.frombuffer(a.data, offset=8, count=100, dtype=complex)
+    z.shape = 10, 10
+
+    eig(z, overwrite_a=True)
+    # This does not need special handling
+    eig(z.T, overwrite_a=True)
+
+
+def check_lapack_misaligned(func, args, kwargs):
+    args = list(args)
+    for i in range(len(args)):
+        a = args[:]
+        if isinstance(a[i], np.ndarray):
+            # Try misaligning a[i]
+            aa = np.zeros(a[i].size*a[i].dtype.itemsize+8, dtype=np.uint8)
+            aa = np.frombuffer(aa.data, offset=4, count=a[i].size,
+                               dtype=a[i].dtype)
+            aa.shape = a[i].shape
+            aa[...] = a[i]
+            a[i] = aa
+            func(*a, **kwargs)
+            if len(a[i].shape) > 1:
+                a[i] = a[i].T
+                func(*a, **kwargs)
+
+
+@pytest.mark.xfail(run=False,
+                   reason="Ticket #1152, triggers a segfault in rare cases.")
+def test_lapack_misaligned():
+    M = np.eye(10, dtype=float)
+    R = np.arange(100)
+    R.shape = 10, 10
+    S = np.arange(20000, dtype=np.uint8)
+    S = np.frombuffer(S.data, offset=4, count=100, dtype=float)
+    S.shape = 10, 10
+    b = np.ones(10)
+    LU, piv = lu_factor(S)
+    for (func, args, kwargs) in [
+            (eig, (S,), dict(overwrite_a=True)),  # crash
+            (eigvals, (S,), dict(overwrite_a=True)),  # no crash
+            (lu, (S,), dict(overwrite_a=True)),  # no crash
+            (lu_factor, (S,), dict(overwrite_a=True)),  # no crash
+            (lu_solve, ((LU, piv), b), dict(overwrite_b=True)),
+            (solve, (S, b), dict(overwrite_a=True, overwrite_b=True)),
+            (svd, (M,), dict(overwrite_a=True)),  # no crash
+            (svd, (R,), dict(overwrite_a=True)),  # no crash
+            (svd, (S,), dict(overwrite_a=True)),  # crash
+            (svdvals, (S,), dict()),  # no crash
+            (svdvals, (S,), dict(overwrite_a=True)),  # crash
+            (cholesky, (M,), dict(overwrite_a=True)),  # no crash
+            (qr, (S,), dict(overwrite_a=True)),  # crash
+            (rq, (S,), dict(overwrite_a=True)),  # crash
+            (hessenberg, (S,), dict(overwrite_a=True)),  # crash
+            (schur, (S,), dict(overwrite_a=True)),  # crash
+            ]:
+        check_lapack_misaligned(func, args, kwargs)
+# not properly tested
+# cholesky, rsf2csf, lu_solve, solve, eig_banded, eigvals_banded, eigh, diagsvd
+
+
+class TestOverwrite:
+    def test_eig(self):
+        assert_no_overwrite(eig, [(3, 3)])
+        assert_no_overwrite(eig, [(3, 3), (3, 3)])
+
+    def test_eigh(self):
+        assert_no_overwrite(eigh, [(3, 3)])
+        assert_no_overwrite(eigh, [(3, 3), (3, 3)])
+
+    def test_eig_banded(self):
+        assert_no_overwrite(eig_banded, [(3, 2)])
+
+    def test_eigvals(self):
+        assert_no_overwrite(eigvals, [(3, 3)])
+
+    def test_eigvalsh(self):
+        assert_no_overwrite(eigvalsh, [(3, 3)])
+
+    def test_eigvals_banded(self):
+        assert_no_overwrite(eigvals_banded, [(3, 2)])
+
+    def test_hessenberg(self):
+        assert_no_overwrite(hessenberg, [(3, 3)])
+
+    def test_lu_factor(self):
+        assert_no_overwrite(lu_factor, [(3, 3)])
+
+    def test_lu_solve(self):
+        x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 8]])
+        xlu = lu_factor(x)
+        assert_no_overwrite(lambda b: lu_solve(xlu, b), [(3,)])
+
+    def test_lu(self):
+        assert_no_overwrite(lu, [(3, 3)])
+
+    def test_qr(self):
+        assert_no_overwrite(qr, [(3, 3)])
+
+    def test_rq(self):
+        assert_no_overwrite(rq, [(3, 3)])
+
+    def test_schur(self):
+        assert_no_overwrite(schur, [(3, 3)])
+
+    def test_schur_complex(self):
+        assert_no_overwrite(lambda a: schur(a, 'complex'), [(3, 3)],
+                            dtypes=[np.float32, np.float64])
+
+    def test_svd(self):
+        assert_no_overwrite(svd, [(3, 3)])
+        assert_no_overwrite(lambda a: svd(a, lapack_driver='gesvd'), [(3, 3)])
+
+    def test_svdvals(self):
+        assert_no_overwrite(svdvals, [(3, 3)])
+
+
+def _check_orth(n, dtype, skip_big=False):
+    X = np.ones((n, 2), dtype=float).astype(dtype)
+
+    eps = np.finfo(dtype).eps
+    tol = 1000 * eps
+
+    Y = orth(X)
+    assert_equal(Y.shape, (n, 1))
+    assert_allclose(Y, Y.mean(), atol=tol)
+
+    Y = orth(X.T)
+    assert_equal(Y.shape, (2, 1))
+    assert_allclose(Y, Y.mean(), atol=tol)
+
+    if n > 5 and not skip_big:
+        rng = np.random.RandomState(1)
+        X = rng.rand(n, 5) @ rng.rand(5, n)
+        X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n)
+        X = X.astype(dtype)
+
+        Y = orth(X, rcond=1e-3)
+        assert_equal(Y.shape, (n, 5))
+
+        Y = orth(X, rcond=1e-6)
+        assert_equal(Y.shape, (n, 5 + 1))
+
+
+@pytest.mark.slow
+@pytest.mark.skipif(np.dtype(np.intp).itemsize < 8,
+                    reason="test only on 64-bit, else too slow")
+def test_orth_memory_efficiency():
+    # Pick n so that 16*n bytes is reasonable but 8*n*n bytes is unreasonable.
+    # Keep in mind that @pytest.mark.slow tests are likely to be running
+    # under configurations that support 4Gb+ memory for tests related to
+    # 32 bit overflow.
+    n = 10*1000*1000
+    try:
+        _check_orth(n, np.float64, skip_big=True)
+    except MemoryError as e:
+        raise AssertionError(
+            'memory error perhaps caused by orth regression'
+        ) from e
+
+
+def test_orth():
+    dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+    sizes = [1, 2, 3, 10, 100]
+    for dt, n in itertools.product(dtypes, sizes):
+        _check_orth(n, dt)
+
+@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+def test_orth_empty(dt):
+    a = np.empty((0, 0), dtype=dt)
+    a0 = np.eye(2, dtype=dt)
+
+    oa = orth(a)
+    assert oa.dtype == orth(a0).dtype
+    assert oa.shape == (0, 0)
+
+
+class TestNullSpace:
+    def test_null_space(self):
+        rng = np.random.RandomState(1)
+
+        dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+        sizes = [1, 2, 3, 10, 100]
+
+        for dt, n in itertools.product(dtypes, sizes):
+            X = np.ones((2, n), dtype=dt)
+
+            eps = np.finfo(dt).eps
+            tol = 1000 * eps
+
+            Y = null_space(X)
+            assert_equal(Y.shape, (n, n-1))
+            assert_allclose(X @ Y, 0, atol=tol)
+
+            Y = null_space(X.T)
+            assert_equal(Y.shape, (2, 1))
+            assert_allclose(X.T @ Y, 0, atol=tol)
+
+            X = rng.randn(1 + n//2, n)
+            Y = null_space(X)
+            assert_equal(Y.shape, (n, n - 1 - n//2))
+            assert_allclose(X @ Y, 0, atol=tol)
+
+            if n > 5:
+                rng = np.random.RandomState(1)
+                X = rng.rand(n, 5) @ rng.rand(5, n)
+                X = X + 1e-4 * rng.rand(n, 1) @ rng.rand(1, n)
+                X = X.astype(dt)
+
+                Y = null_space(X, rcond=1e-3)
+                assert_equal(Y.shape, (n, n - 5))
+
+                Y = null_space(X, rcond=1e-6)
+                assert_equal(Y.shape, (n, n - 6))
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_null_space_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        a0 = np.eye(2, dtype=dt)
+        nsa = null_space(a)
+
+        assert nsa.shape == (0, 0)
+        assert nsa.dtype == null_space(a0).dtype
+
+    @pytest.mark.parametrize("overwrite_a", [True, False])
+    @pytest.mark.parametrize("check_finite", [True, False])
+    @pytest.mark.parametrize("lapack_driver", ["gesdd", "gesvd"])
+    def test_null_space_options(self, overwrite_a, check_finite, lapack_driver):
+        rng = np.random.default_rng(42887289350573064398746)
+        n = 10
+        X = rng.standard_normal((1 + n//2, n))
+        Y = null_space(X.copy(), overwrite_a=overwrite_a, check_finite=check_finite,
+                       lapack_driver=lapack_driver)
+        assert_allclose(X @ Y, 0, atol=np.finfo(X.dtype).eps*100)
+
+
+def test_subspace_angles():
+    H = hadamard(8, float)
+    A = H[:, :3]
+    B = H[:, 3:]
+    assert_allclose(subspace_angles(A, B), [np.pi / 2.] * 3, atol=1e-14)
+    assert_allclose(subspace_angles(B, A), [np.pi / 2.] * 3, atol=1e-14)
+    for x in (A, B):
+        assert_allclose(subspace_angles(x, x), np.zeros(x.shape[1]),
+                        atol=1e-14)
+    # From MATLAB function "subspace", which effectively only returns the
+    # last value that we calculate
+    x = np.array(
+        [[0.537667139546100, 0.318765239858981, 3.578396939725760, 0.725404224946106],  # noqa: E501
+         [1.833885014595086, -1.307688296305273, 2.769437029884877, -0.063054873189656],  # noqa: E501
+         [-2.258846861003648, -0.433592022305684, -1.349886940156521, 0.714742903826096],  # noqa: E501
+         [0.862173320368121, 0.342624466538650, 3.034923466331855, -0.204966058299775]])  # noqa: E501
+    expected = 1.481454682101605
+    assert_allclose(subspace_angles(x[:, :2], x[:, 2:])[0], expected,
+                    rtol=1e-12)
+    assert_allclose(subspace_angles(x[:, 2:], x[:, :2])[0], expected,
+                    rtol=1e-12)
+    expected = 0.746361174247302
+    assert_allclose(subspace_angles(x[:, :2], x[:, [2]]), expected, rtol=1e-12)
+    assert_allclose(subspace_angles(x[:, [2]], x[:, :2]), expected, rtol=1e-12)
+    expected = 0.487163718534313
+    assert_allclose(subspace_angles(x[:, :3], x[:, [3]]), expected, rtol=1e-12)
+    assert_allclose(subspace_angles(x[:, [3]], x[:, :3]), expected, rtol=1e-12)
+    expected = 0.328950515907756
+    assert_allclose(subspace_angles(x[:, :2], x[:, 1:]), [expected, 0],
+                    atol=1e-12)
+    # Degenerate conditions
+    assert_raises(ValueError, subspace_angles, x[0], x)
+    assert_raises(ValueError, subspace_angles, x, x[0])
+    assert_raises(ValueError, subspace_angles, x[:-1], x)
+
+    # Test branch if mask.any is True:
+    A = np.array([[1, 0, 0],
+                  [0, 1, 0],
+                  [0, 0, 1],
+                  [0, 0, 0],
+                  [0, 0, 0]])
+    B = np.array([[1, 0, 0],
+                  [0, 1, 0],
+                  [0, 0, 0],
+                  [0, 0, 0],
+                  [0, 0, 1]])
+    expected = np.array([np.pi/2, 0, 0])
+    assert_allclose(subspace_angles(A, B), expected, rtol=1e-12)
+
+    # Complex
+    # second column in "b" does not affect result, just there so that
+    # b can have more cols than a, and vice-versa (both conditional code paths)
+    a = [[1 + 1j], [0]]
+    b = [[1 - 1j, 0], [0, 1]]
+    assert_allclose(subspace_angles(a, b), 0., atol=1e-14)
+    assert_allclose(subspace_angles(b, a), 0., atol=1e-14)
+
+    # Empty
+    a = np.empty((0, 0))
+    b = np.empty((0, 0))
+    assert_allclose(subspace_angles(a, b), np.empty((0,)))
+    a = np.empty((2, 0))
+    b = np.empty((2, 0))
+    assert_allclose(subspace_angles(a, b), np.empty((0,)))
+    a = np.empty((0, 2))
+    b = np.empty((0, 3))
+    assert_allclose(subspace_angles(a, b), np.empty((0,)))
+
+
+class TestCDF2RDF:
+
+    def matmul(self, a, b):
+        return np.einsum('...ij,...jk->...ik', a, b)
+
+    def assert_eig_valid(self, w, v, x):
+        assert_array_almost_equal(
+            self.matmul(v, w),
+            self.matmul(x, v)
+        )
+
+    def test_single_array0x0real(self):
+        # eig doesn't support 0x0 in old versions of numpy
+        X = np.empty((0, 0))
+        w, v = np.empty(0), np.empty((0, 0))
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_single_array2x2_real(self):
+        X = np.array([[1, 2], [3, -1]])
+        w, v = np.linalg.eig(X)
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_single_array2x2_complex(self):
+        X = np.array([[1, 2], [-2, 1]])
+        w, v = np.linalg.eig(X)
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_single_array3x3_real(self):
+        X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+        w, v = np.linalg.eig(X)
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_single_array3x3_complex(self):
+        X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
+        w, v = np.linalg.eig(X)
+        wr, vr = cdf2rdf(w, v)
+        self.assert_eig_valid(wr, vr, X)
+
+    def test_random_1d_stacked_arrays(self):
+        # cannot test M == 0 due to bug in old numpy
+        for M in range(1, 7):
+            np.random.seed(999999999)
+            X = np.random.rand(100, M, M)
+            w, v = np.linalg.eig(X)
+            wr, vr = cdf2rdf(w, v)
+            self.assert_eig_valid(wr, vr, X)
+
+    def test_random_2d_stacked_arrays(self):
+        # cannot test M == 0 due to bug in old numpy
+        for M in range(1, 7):
+            X = np.random.rand(10, 10, M, M)
+            w, v = np.linalg.eig(X)
+            wr, vr = cdf2rdf(w, v)
+            self.assert_eig_valid(wr, vr, X)
+
+    def test_low_dimensionality_error(self):
+        w, v = np.empty(()), np.array((2,))
+        assert_raises(ValueError, cdf2rdf, w, v)
+
+    def test_not_square_error(self):
+        # Check that passing a non-square array raises a ValueError.
+        w, v = np.arange(3), np.arange(6).reshape(3, 2)
+        assert_raises(ValueError, cdf2rdf, w, v)
+
+    def test_swapped_v_w_error(self):
+        # Check that exchanging places of w and v raises ValueError.
+        X = np.array([[1, 2, 3], [0, 4, 5], [0, -5, 4]])
+        w, v = np.linalg.eig(X)
+        assert_raises(ValueError, cdf2rdf, v, w)
+
+    def test_non_associated_error(self):
+        # Check that passing non-associated eigenvectors raises a ValueError.
+        w, v = np.arange(3), np.arange(16).reshape(4, 4)
+        assert_raises(ValueError, cdf2rdf, w, v)
+
+    def test_not_conjugate_pairs(self):
+        # Check that passing non-conjugate pairs raises a ValueError.
+        X = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]])
+        w, v = np.linalg.eig(X)
+        assert_raises(ValueError, cdf2rdf, w, v)
+
+        # different arrays in the stack, so not conjugate
+        X = np.array([
+            [[1, 2, 3], [1, 2, 3], [2, 5, 6+1j]],
+            [[1, 2, 3], [1, 2, 3], [2, 5, 6-1j]],
+        ])
+        w, v = np.linalg.eig(X)
+        assert_raises(ValueError, cdf2rdf, w, v)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py
new file mode 100644
index 0000000000000000000000000000000000000000..61bbc7e544f10fc834034fbadd7141f6deb1d423
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cholesky.py
@@ -0,0 +1,268 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_array_almost_equal
+from pytest import raises as assert_raises
+
+from numpy import array, transpose, dot, conjugate, zeros_like, empty
+from numpy.random import random
+from scipy.linalg import (cholesky, cholesky_banded, cho_solve_banded,
+     cho_factor, cho_solve)
+
+from scipy.linalg._testutils import assert_no_overwrite
+
+
+class TestCholesky:
+
+    def test_simple(self):
+        a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
+        c = cholesky(a)
+        assert_array_almost_equal(dot(transpose(c), c), a)
+        c = transpose(c)
+        a = dot(c, transpose(c))
+        assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    def test_check_finite(self):
+        a = [[8, 2, 3], [2, 9, 3], [3, 3, 6]]
+        c = cholesky(a, check_finite=False)
+        assert_array_almost_equal(dot(transpose(c), c), a)
+        c = transpose(c)
+        a = dot(c, transpose(c))
+        assert_array_almost_equal(cholesky(a, lower=1, check_finite=False), c)
+
+    def test_simple_complex(self):
+        m = array([[3+1j, 3+4j, 5], [0, 2+2j, 2+7j], [0, 0, 7+4j]])
+        a = dot(transpose(conjugate(m)), m)
+        c = cholesky(a)
+        a1 = dot(transpose(conjugate(c)), c)
+        assert_array_almost_equal(a, a1)
+        c = transpose(c)
+        a = dot(c, transpose(conjugate(c)))
+        assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    def test_random(self):
+        n = 20
+        for k in range(2):
+            m = random([n, n])
+            for i in range(n):
+                m[i, i] = 20*(.1+m[i, i])
+            a = dot(transpose(m), m)
+            c = cholesky(a)
+            a1 = dot(transpose(c), c)
+            assert_array_almost_equal(a, a1)
+            c = transpose(c)
+            a = dot(c, transpose(c))
+            assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    def test_random_complex(self):
+        n = 20
+        for k in range(2):
+            m = random([n, n])+1j*random([n, n])
+            for i in range(n):
+                m[i, i] = 20*(.1+abs(m[i, i]))
+            a = dot(transpose(conjugate(m)), m)
+            c = cholesky(a)
+            a1 = dot(transpose(conjugate(c)), c)
+            assert_array_almost_equal(a, a1)
+            c = transpose(c)
+            a = dot(c, transpose(conjugate(c)))
+            assert_array_almost_equal(cholesky(a, lower=1), c)
+
+    @pytest.mark.xslow
+    def test_int_overflow(self):
+       # regression test for
+       # https://github.com/scipy/scipy/issues/17436
+       # the problem was an int overflow in zeroing out
+       # the unused triangular part
+       n = 47_000
+       x = np.eye(n, dtype=np.float64, order='F')
+       x[:4, :4] = np.array([[4, -2, 3, -1],
+                             [-2, 4, -3, 1],
+                             [3, -3, 5, 0],
+                             [-1, 1, 0, 5]])
+
+       cholesky(x, check_finite=False, overwrite_a=True)  # should not segfault
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt, dt_b):
+        a = empty((0, 0), dtype=dt)
+
+        c = cholesky(a)
+        assert c.shape == (0, 0)
+        assert c.dtype == cholesky(np.eye(2, dtype=dt)).dtype
+
+        c_and_lower = (c, True)
+        b = np.asarray([], dtype=dt_b)
+        x = cho_solve(c_and_lower, b)
+        assert x.shape == (0,)
+        assert x.dtype == cho_solve((np.eye(2, dtype=dt), True),
+                                     np.ones(2, dtype=dt_b)).dtype
+
+        b = empty((0, 0), dtype=dt_b)
+        x = cho_solve(c_and_lower, b)
+        assert x.shape == (0, 0)
+        assert x.dtype == cho_solve((np.eye(2, dtype=dt), True),
+                                     np.ones(2, dtype=dt_b)).dtype
+
+        a1 = array([])
+        a2 = array([[]])
+        a3 = []
+        a4 = [[]]
+        for x in ([a1, a2, a3, a4]):
+            assert_raises(ValueError, cholesky, x)
+
+
+class TestCholeskyBanded:
+    """Tests for cholesky_banded() and cho_solve_banded."""
+
+    def test_check_finite(self):
+        # Symmetric positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, 0.2],
+                   [0.0, 0.0, 0.2, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[-1.0, 1.0, 0.5, 0.2],
+                    [4.0, 4.0, 4.0, 4.0]])
+        c = cholesky_banded(ab, lower=False, check_finite=False)
+        ufac = zeros_like(a)
+        ufac[list(range(4)), list(range(4))] = c[-1]
+        ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
+        assert_array_almost_equal(a, dot(ufac.T, ufac))
+
+        b = array([0.0, 0.5, 4.2, 4.2])
+        x = cho_solve_banded((c, False), b, check_finite=False)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    def test_upper_real(self):
+        # Symmetric positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, 0.2],
+                   [0.0, 0.0, 0.2, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[-1.0, 1.0, 0.5, 0.2],
+                    [4.0, 4.0, 4.0, 4.0]])
+        c = cholesky_banded(ab, lower=False)
+        ufac = zeros_like(a)
+        ufac[list(range(4)), list(range(4))] = c[-1]
+        ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
+        assert_array_almost_equal(a, dot(ufac.T, ufac))
+
+        b = array([0.0, 0.5, 4.2, 4.2])
+        x = cho_solve_banded((c, False), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    def test_upper_complex(self):
+        # Hermitian positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, -0.2j],
+                   [0.0, 0.0, 0.2j, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[-1.0, 1.0, 0.5, -0.2j],
+                    [4.0, 4.0, 4.0, 4.0]])
+        c = cholesky_banded(ab, lower=False)
+        ufac = zeros_like(a)
+        ufac[list(range(4)), list(range(4))] = c[-1]
+        ufac[(0, 1, 2), (1, 2, 3)] = c[0, 1:]
+        assert_array_almost_equal(a, dot(ufac.conj().T, ufac))
+
+        b = array([0.0, 0.5, 4.0-0.2j, 0.2j + 4.0])
+        x = cho_solve_banded((c, False), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    def test_lower_real(self):
+        # Symmetric positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, 0.2],
+                   [0.0, 0.0, 0.2, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[4.0, 4.0, 4.0, 4.0],
+                    [1.0, 0.5, 0.2, -1.0]])
+        c = cholesky_banded(ab, lower=True)
+        lfac = zeros_like(a)
+        lfac[list(range(4)), list(range(4))] = c[0]
+        lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
+        assert_array_almost_equal(a, dot(lfac, lfac.T))
+
+        b = array([0.0, 0.5, 4.2, 4.2])
+        x = cho_solve_banded((c, True), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0, 1.0])
+
+    def test_lower_complex(self):
+        # Hermitian positive definite banded matrix `a`
+        a = array([[4.0, 1.0, 0.0, 0.0],
+                   [1.0, 4.0, 0.5, 0.0],
+                   [0.0, 0.5, 4.0, -0.2j],
+                   [0.0, 0.0, 0.2j, 4.0]])
+        # Banded storage form of `a`.
+        ab = array([[4.0, 4.0, 4.0, 4.0],
+                    [1.0, 0.5, 0.2j, -1.0]])
+        c = cholesky_banded(ab, lower=True)
+        lfac = zeros_like(a)
+        lfac[list(range(4)), list(range(4))] = c[0]
+        lfac[(1, 2, 3), (0, 1, 2)] = c[1, :3]
+        assert_array_almost_equal(a, dot(lfac, lfac.conj().T))
+
+        b = array([0.0, 0.5j, 3.8j, 3.8])
+        x = cho_solve_banded((c, True), b)
+        assert_array_almost_equal(x, [0.0, 0.0, 1.0j, 1.0])
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt, dt_b):
+        ab = empty((0, 0), dtype=dt)
+
+        cb = cholesky_banded(ab)
+        assert cb.shape == (0, 0)
+
+        m = cholesky_banded(np.array([[0, 0], [1, 1]], dtype=dt))
+        assert cb.dtype == m.dtype
+
+        cb_and_lower = (cb, True)
+        b = np.asarray([], dtype=dt_b)
+        x = cho_solve_banded(cb_and_lower, b)
+        assert x.shape == (0,)
+
+        dtype_nonempty = cho_solve_banded((m, True), np.ones(2, dtype=dt_b)).dtype
+        assert x.dtype == dtype_nonempty
+
+        b = empty((0, 0), dtype=dt_b)
+        x = cho_solve_banded(cb_and_lower, b)
+        assert x.shape == (0, 0)
+        assert x.dtype == dtype_nonempty
+
+
+class TestOverwrite:
+    def test_cholesky(self):
+        assert_no_overwrite(cholesky, [(3, 3)])
+
+    def test_cho_factor(self):
+        assert_no_overwrite(cho_factor, [(3, 3)])
+
+    def test_cho_solve(self):
+        x = array([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
+        xcho = cho_factor(x)
+        assert_no_overwrite(lambda b: cho_solve(xcho, b), [(3,)])
+
+    def test_cholesky_banded(self):
+        assert_no_overwrite(cholesky_banded, [(2, 3)])
+
+    def test_cho_solve_banded(self):
+        x = array([[0, -1, -1], [2, 2, 2]])
+        xcho = cholesky_banded(x)
+        assert_no_overwrite(lambda b: cho_solve_banded((xcho, False), b),
+                            [(3,)])
+
+class TestChoFactor:
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        x, lower = cho_factor(a)
+
+        assert x.shape == (0, 0)
+
+        xx, lower = cho_factor(np.eye(2, dtype=dt))
+        assert x.dtype == xx.dtype
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py
new file mode 100644
index 0000000000000000000000000000000000000000..df112f0e4cf75d03d2787c24306665b7027967ee
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_cossin.py
@@ -0,0 +1,300 @@
+import pytest
+import numpy as np
+from numpy.random import default_rng
+from numpy.testing import assert_allclose
+
+from scipy import linalg
+from scipy.linalg.lapack import _compute_lwork
+from scipy.stats import ortho_group, unitary_group
+from scipy.linalg import cossin, get_lapack_funcs
+
+REAL_DTYPES = (np.float32, np.float64)
+COMPLEX_DTYPES = (np.complex64, np.complex128)
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+@pytest.mark.parametrize('dtype_', DTYPES)
+@pytest.mark.parametrize('m, p, q',
+                         [
+                             (2, 1, 1),
+                             (3, 2, 1),
+                             (3, 1, 2),
+                             (4, 2, 2),
+                             (4, 1, 2),
+                             (40, 12, 20),
+                             (40, 30, 1),
+                             (40, 1, 30),
+                             (100, 50, 1),
+                             (100, 50, 50),
+                         ])
+@pytest.mark.parametrize('swap_sign', [True, False])
+def test_cossin(dtype_, m, p, q, swap_sign):
+    rng = default_rng(1708093570726217)
+    if dtype_ in COMPLEX_DTYPES:
+        x = np.array(unitary_group.rvs(m, random_state=rng), dtype=dtype_)
+    else:
+        x = np.array(ortho_group.rvs(m, random_state=rng), dtype=dtype_)
+
+    u, cs, vh = cossin(x, p, q,
+                       swap_sign=swap_sign)
+    assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
+    assert u.dtype == dtype_
+    # Test for float32 or float 64
+    assert cs.dtype == np.real(u).dtype
+    assert vh.dtype == dtype_
+
+    u, cs, vh = cossin([x[:p, :q], x[:p, q:], x[p:, :q], x[p:, q:]],
+                       swap_sign=swap_sign)
+    assert_allclose(x, u @ cs @ vh, rtol=0., atol=m*1e3*np.finfo(dtype_).eps)
+    assert u.dtype == dtype_
+    assert cs.dtype == np.real(u).dtype
+    assert vh.dtype == dtype_
+
+    _, cs2, vh2 = cossin(x, p, q,
+                         compute_u=False,
+                         swap_sign=swap_sign)
+    assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
+    assert_allclose(vh, vh2, rtol=0., atol=10*np.finfo(dtype_).eps)
+
+    u2, cs2, _ = cossin(x, p, q,
+                        compute_vh=False,
+                        swap_sign=swap_sign)
+    assert_allclose(u, u2, rtol=0., atol=10*np.finfo(dtype_).eps)
+    assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
+
+    _, cs2, _ = cossin(x, p, q,
+                       compute_u=False,
+                       compute_vh=False,
+                       swap_sign=swap_sign)
+    assert_allclose(cs, cs2, rtol=0., atol=10*np.finfo(dtype_).eps)
+
+
+def test_cossin_mixed_types():
+    rng = default_rng(1708093736390459)
+    x = np.array(ortho_group.rvs(4, random_state=rng), dtype=np.float64)
+    u, cs, vh = cossin([x[:2, :2],
+                        np.array(x[:2, 2:], dtype=np.complex128),
+                        x[2:, :2],
+                        x[2:, 2:]])
+
+    assert u.dtype == np.complex128
+    assert cs.dtype == np.float64
+    assert vh.dtype == np.complex128
+    assert_allclose(x, u @ cs @ vh, rtol=0.,
+                    atol=1e4 * np.finfo(np.complex128).eps)
+
+
+def test_cossin_error_incorrect_subblocks():
+    with pytest.raises(ValueError, match="be due to missing p, q arguments."):
+        cossin(([1, 2], [3, 4, 5], [6, 7], [8, 9, 10]))
+
+
+def test_cossin_error_empty_subblocks():
+    with pytest.raises(ValueError, match="x11.*empty"):
+        cossin(([], [], [], []))
+    with pytest.raises(ValueError, match="x12.*empty"):
+        cossin(([1, 2], [], [6, 7], [8, 9, 10]))
+    with pytest.raises(ValueError, match="x21.*empty"):
+        cossin(([1, 2], [3, 4, 5], [], [8, 9, 10]))
+    with pytest.raises(ValueError, match="x22.*empty"):
+        cossin(([1, 2], [3, 4, 5], [2], []))
+
+
+def test_cossin_error_missing_partitioning():
+    with pytest.raises(ValueError, match=".*exactly four arrays.* got 2"):
+        cossin(unitary_group.rvs(2))
+
+    with pytest.raises(ValueError, match=".*might be due to missing p, q"):
+        cossin(unitary_group.rvs(4))
+
+
+def test_cossin_error_non_iterable():
+    with pytest.raises(ValueError, match="containing the subblocks of X"):
+        cossin(12j)
+
+
+def test_cossin_error_non_square():
+    with pytest.raises(ValueError, match="only supports square"):
+        cossin(np.array([[1, 2]]), 1, 1)
+
+
+def test_cossin_error_partitioning():
+    x = np.array(ortho_group.rvs(4), dtype=np.float64)
+    with pytest.raises(ValueError, match="invalid p=0.*0= m) or (q >= m):
+        pytest.skip("`0 < p < m` and `0 < q < m` must hold")
+
+    # Generate unitary input
+    rng = np.random.default_rng(329548272348596421)
+    X = unitary_group.rvs(m, random_state=rng)
+    np.testing.assert_allclose(X @ X.conj().T, np.eye(m), atol=1e-15)
+
+    # Perform the decomposition
+    u0, cs0, vh0 = linalg.cossin(X, p=p, q=q, separate=True, swap_sign=swap_sign)
+    u1, u2 = u0
+    v1, v2 = vh0
+    v1, v2 = v1.conj().T, v2.conj().T
+
+    # "U1, U2, V1, V2 are square orthogonal/unitary matrices
+    # of dimensions (p,p), (m-p,m-p), (q,q), and (m-q,m-q) respectively"
+    np.testing.assert_allclose(u1 @ u1.conj().T, np.eye(p), atol=1e-13)
+    np.testing.assert_allclose(u2 @ u2.conj().T, np.eye(m-p), atol=1e-13)
+    np.testing.assert_allclose(v1 @ v1.conj().T, np.eye(q), atol=1e-13)
+    np.testing.assert_allclose(v2 @ v2.conj().T, np.eye(m-q), atol=1e-13)
+
+    # "and C and S are (r, r) nonnegative diagonal matrices..."
+    C = np.diag(np.cos(cs0))
+    S = np.diag(np.sin(cs0))
+    # "...satisfying C^2 + S^2 = I where r = min(p, m-p, q, m-q)."
+    r = min(p, m-p, q, m-q)
+    np.testing.assert_allclose(C**2 + S**2, np.eye(r))
+
+    # "Moreover, the rank of the identity matrices are
+    # min(p, q) - r, min(p, m - q) - r, min(m - p, q) - r,
+    # and min(m - p, m - q) - r respectively."
+    I11 = np.eye(min(p, q) - r)
+    I12 = np.eye(min(p, m - q) - r)
+    I21 = np.eye(min(m - p, q) - r)
+    I22 = np.eye(min(m - p, m - q) - r)
+
+    # From:
+    #                            ┌                   ┐
+    #                            │ I  0  0 │ 0  0  0 │
+    # ┌           ┐   ┌         ┐│ 0  C  0 │ 0 -S  0 │┌         ┐*
+    # │ X11 │ X12 │   │ U1 │    ││ 0  0  0 │ 0  0 -I ││ V1 │    │
+    # │ ────┼──── │ = │────┼────││─────────┼─────────││────┼────│
+    # │ X21 │ X22 │   │    │ U2 ││ 0  0  0 │ I  0  0 ││    │ V2 │
+    # └           ┘   └         ┘│ 0  S  0 │ 0  C  0 │└         ┘
+    #                            │ 0  0  I │ 0  0  0 │
+    #                            └                   ┘
+
+    # We can see that U and V are block diagonal matrices like so:
+    U = linalg.block_diag(u1, u2)
+    V = linalg.block_diag(v1, v2)
+
+    # And the center matrix, which we'll call Q here, must be:
+    Q11 = np.zeros((u1.shape[1], v1.shape[0]))
+    IC11 = linalg.block_diag(I11, C)
+    Q11[:IC11.shape[0], :IC11.shape[1]] = IC11
+
+    Q12 = np.zeros((u1.shape[1], v2.shape[0]))
+    SI12 = linalg.block_diag(S, I12) if swap_sign else linalg.block_diag(-S, -I12)
+    Q12[-SI12.shape[0]:, -SI12.shape[1]:] = SI12
+
+    Q21 = np.zeros((u2.shape[1], v1.shape[0]))
+    SI21 = linalg.block_diag(-S, -I21) if swap_sign else linalg.block_diag(S, I21)
+    Q21[-SI21.shape[0]:, -SI21.shape[1]:] = SI21
+
+    Q22 = np.zeros((u2.shape[1], v2.shape[0]))
+    IC22 = linalg.block_diag(I22, C)
+    Q22[:IC22.shape[0], :IC22.shape[1]] = IC22
+
+    Q = np.block([[Q11, Q12], [Q21, Q22]])
+
+    # Confirm that `cossin` decomposes `X` as shown
+    np.testing.assert_allclose(X, U @ Q @ V.conj().T)
+
+    # And check that `separate=False` agrees
+    U0, CS0, Vh0 = linalg.cossin(X, p=p, q=q, swap_sign=swap_sign)
+    np.testing.assert_allclose(U, U0)
+    np.testing.assert_allclose(Q, CS0)
+    np.testing.assert_allclose(V, Vh0.conj().T)
+
+    # Confirm that `compute_u`/`compute_vh` don't affect the results
+    kwargs = dict(p=p, q=q, swap_sign=swap_sign)
+
+    # `compute_u=False`
+    u, cs, vh = linalg.cossin(X, separate=True, compute_u=False, **kwargs)
+    assert u[0].shape == (0, 0)  # probably not ideal, but this is what it does
+    assert u[1].shape == (0, 0)
+    assert_allclose(cs, cs0, rtol=1e-15)
+    assert_allclose(vh[0], vh0[0], rtol=1e-15)
+    assert_allclose(vh[1], vh0[1], rtol=1e-15)
+
+    U, CS, Vh = linalg.cossin(X, compute_u=False, **kwargs)
+    assert U.shape == (0, 0)
+    assert_allclose(CS, CS0, rtol=1e-15)
+    assert_allclose(Vh, Vh0, rtol=1e-15)
+
+    # `compute_vh=False`
+    u, cs, vh = linalg.cossin(X, separate=True, compute_vh=False, **kwargs)
+    assert_allclose(u[0], u[0], rtol=1e-15)
+    assert_allclose(u[1], u[1], rtol=1e-15)
+    assert_allclose(cs, cs0, rtol=1e-15)
+    assert vh[0].shape == (0, 0)
+    assert vh[1].shape == (0, 0)
+
+    U, CS, Vh = linalg.cossin(X, compute_vh=False, **kwargs)
+    assert_allclose(U, U0, rtol=1e-15)
+    assert_allclose(CS, CS0, rtol=1e-15)
+    assert Vh.shape == (0, 0)
+
+    # `compute_u=False, compute_vh=False`
+    u, cs, vh = linalg.cossin(X, separate=True, compute_u=False,
+                              compute_vh=False, **kwargs)
+    assert u[0].shape == (0, 0)
+    assert u[1].shape == (0, 0)
+    assert_allclose(cs, cs0, rtol=1e-15)
+    assert vh[0].shape == (0, 0)
+    assert vh[1].shape == (0, 0)
+
+    U, CS, Vh = linalg.cossin(X, compute_u=False, compute_vh=False, **kwargs)
+    assert U.shape == (0, 0)
+    assert_allclose(CS, CS0, rtol=1e-15)
+    assert Vh.shape == (0, 0)
+
+
+def test_indexing_bug_gh19365():
+    # Regression test for gh-19365, which reported a bug with `separate=False`
+    rng = np.random.default_rng(32954827234421)
+    m = rng.integers(50, high=100)
+    p = rng.integers(10, 40)  # always p < m
+    q = rng.integers(m - p + 1, m - 1)  # always m-p < q < m
+    X = unitary_group.rvs(m, random_state=rng)  # random unitary matrix
+    U, D, Vt = linalg.cossin(X, p=p, q=q, separate=False)
+    assert np.allclose(U @ D @ Vt, X)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d74a746b4dd7bb6367500b4c893aa9f767de51f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_ldl.py
@@ -0,0 +1,137 @@
+from numpy.testing import assert_array_almost_equal, assert_allclose, assert_
+from numpy import (array, eye, zeros, empty_like, empty, tril_indices_from,
+                   tril, triu_indices_from, spacing, float32, float64,
+                   complex64, complex128)
+from numpy.random import rand, randint, seed
+from scipy.linalg import ldl
+from scipy._lib._util import ComplexWarning
+import pytest
+from pytest import raises as assert_raises, warns
+
+
+@pytest.mark.thread_unsafe
+def test_args():
+    A = eye(3)
+    # Nonsquare array
+    assert_raises(ValueError, ldl, A[:, :2])
+    # Complex matrix with imaginary diagonal entries with "hermitian=True"
+    with warns(ComplexWarning):
+        ldl(A*1j)
+
+
+def test_empty_array():
+    a = empty((0, 0), dtype=complex)
+    l, d, p = ldl(empty((0, 0)))
+    assert_array_almost_equal(l, empty_like(a))
+    assert_array_almost_equal(d, empty_like(a))
+    assert_array_almost_equal(p, array([], dtype=int))
+
+
+def test_simple():
+    a = array([[-0.39-0.71j, 5.14-0.64j, -7.86-2.96j, 3.80+0.92j],
+               [5.14-0.64j, 8.86+1.81j, -3.52+0.58j, 5.32-1.59j],
+               [-7.86-2.96j, -3.52+0.58j, -2.83-0.03j, -1.54-2.86j],
+               [3.80+0.92j, 5.32-1.59j, -1.54-2.86j, -0.56+0.12j]])
+    b = array([[5., 10, 1, 18],
+               [10., 2, 11, 1],
+               [1., 11, 19, 9],
+               [18., 1, 9, 0]])
+    c = array([[52., 97, 112, 107, 50],
+               [97., 114, 89, 98, 13],
+               [112., 89, 64, 33, 6],
+               [107., 98, 33, 60, 73],
+               [50., 13, 6, 73, 77]])
+
+    d = array([[2., 2, -4, 0, 4],
+               [2., -2, -2, 10, -8],
+               [-4., -2, 6, -8, -4],
+               [0., 10, -8, 6, -6],
+               [4., -8, -4, -6, 10]])
+    e = array([[-1.36+0.00j, 0+0j, 0+0j, 0+0j],
+               [1.58-0.90j, -8.87+0j, 0+0j, 0+0j],
+               [2.21+0.21j, -1.84+0.03j, -4.63+0j, 0+0j],
+               [3.91-1.50j, -1.78-1.18j, 0.11-0.11j, -1.84+0.00j]])
+    for x in (b, c, d):
+        l, d, p = ldl(x)
+        assert_allclose(l.dot(d).dot(l.T), x, atol=spacing(1000.), rtol=0)
+
+        u, d, p = ldl(x, lower=False)
+        assert_allclose(u.dot(d).dot(u.T), x, atol=spacing(1000.), rtol=0)
+
+    l, d, p = ldl(a, hermitian=False)
+    assert_allclose(l.dot(d).dot(l.T), a, atol=spacing(1000.), rtol=0)
+
+    u, d, p = ldl(a, lower=False, hermitian=False)
+    assert_allclose(u.dot(d).dot(u.T), a, atol=spacing(1000.), rtol=0)
+
+    # Use upper part for the computation and use the lower part for comparison
+    l, d, p = ldl(e.conj().T, lower=0)
+    assert_allclose(tril(l.dot(d).dot(l.conj().T)-e), zeros((4, 4)),
+                    atol=spacing(1000.), rtol=0)
+
+
+def test_permutations():
+    seed(1234)
+    for _ in range(10):
+        n = randint(1, 100)
+        # Random real/complex array
+        x = rand(n, n) if randint(2) else rand(n, n) + rand(n, n)*1j
+        x = x + x.conj().T
+        x += eye(n)*randint(5, 1e6)
+        l_ind = tril_indices_from(x, k=-1)
+        u_ind = triu_indices_from(x, k=1)
+
+        # Test whether permutations lead to a triangular array
+        u, d, p = ldl(x, lower=0)
+        # lower part should be zero
+        assert_(not any(u[p, :][l_ind]), f'Spin {_} failed')
+
+        l, d, p = ldl(x, lower=1)
+        # upper part should be zero
+        assert_(not any(l[p, :][u_ind]), f'Spin {_} failed')
+
+
+@pytest.mark.parametrize("dtype", [float32, float64])
+@pytest.mark.parametrize("n", [30, 150])
+def test_ldl_type_size_combinations_real(n, dtype):
+    seed(1234)
+    msg = (f"Failed for size: {n}, dtype: {dtype}")
+
+    x = rand(n, n).astype(dtype)
+    x = x + x.T
+    x += eye(n, dtype=dtype)*dtype(randint(5, 1e6))
+
+    l, d1, p = ldl(x)
+    u, d2, p = ldl(x, lower=0)
+    rtol = 1e-4 if dtype is float32 else 1e-10
+    assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg)
+    assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg)
+
+
+@pytest.mark.parametrize("dtype", [complex64, complex128])
+@pytest.mark.parametrize("n", [30, 150])
+def test_ldl_type_size_combinations_complex(n, dtype):
+    seed(1234)
+    msg1 = (f"Her failed for size: {n}, dtype: {dtype}")
+    msg2 = (f"Sym failed for size: {n}, dtype: {dtype}")
+
+    # Complex hermitian upper/lower
+    x = (rand(n, n)+1j*rand(n, n)).astype(dtype)
+    x = x+x.conj().T
+    x += eye(n, dtype=dtype)*dtype(randint(5, 1e6))
+
+    l, d1, p = ldl(x)
+    u, d2, p = ldl(x, lower=0)
+    rtol = 2e-4 if dtype is complex64 else 1e-10
+    assert_allclose(l.dot(d1).dot(l.conj().T), x, rtol=rtol, err_msg=msg1)
+    assert_allclose(u.dot(d2).dot(u.conj().T), x, rtol=rtol, err_msg=msg1)
+
+    # Complex symmetric upper/lower
+    x = (rand(n, n)+1j*rand(n, n)).astype(dtype)
+    x = x+x.T
+    x += eye(n, dtype=dtype)*dtype(randint(5, 1e6))
+
+    l, d1, p = ldl(x, hermitian=0)
+    u, d2, p = ldl(x, lower=0, hermitian=0)
+    assert_allclose(l.dot(d1).dot(l.T), x, rtol=rtol, err_msg=msg2)
+    assert_allclose(u.dot(d2).dot(u.T), x, rtol=rtol, err_msg=msg2)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py
new file mode 100644
index 0000000000000000000000000000000000000000..da0beccf1f0e66baf4ac4ec80d7ff7129b2df345
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_lu.py
@@ -0,0 +1,308 @@
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from scipy.linalg import lu, lu_factor, lu_solve, get_lapack_funcs, solve
+from numpy.testing import assert_allclose, assert_array_equal, assert_equal
+
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+class TestLU:
+    def setup_method(self):
+        self.rng = np.random.default_rng(1682281250228846)
+
+    def test_old_lu_smoke_tests(self):
+        "Tests from old fortran based lu test suite"
+        a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+        p, l, u = lu(a)
+        result_lu = np.array([[2., 5., 6.], [0.5, -0.5, 0.], [0.5, 1., 0.]])
+        assert_allclose(p, np.rot90(np.eye(3)))
+        assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3))
+        assert_allclose(u, np.triu(result_lu))
+
+        a = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]])
+        p, l, u = lu(a)
+        result_lu = np.array([[2., 5.j, 6.], [0.5, 2-2.5j, 0.], [0.5, 1., 0.]])
+        assert_allclose(p, np.rot90(np.eye(3)))
+        assert_allclose(l, np.tril(result_lu, k=-1)+np.eye(3))
+        assert_allclose(u, np.triu(result_lu))
+
+        b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+        p, l, u = lu(b)
+        assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+        assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]]))
+        assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]]),
+                        rtol=0., atol=1e-14)
+
+        cb = np.array([[1.j, 2.j, 3.j], [4j, 5j, 6j], [7j, 8j, 9j]])
+        p, l, u = lu(cb)
+        assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+        assert_allclose(l, np.array([[1, 0, 0], [1/7, 1, 0], [4/7, 0.5, 1]]))
+        assert_allclose(u, np.array([[7, 8, 9], [0, 6/7, 12/7], [0, 0, 0]])*1j,
+                        rtol=0., atol=1e-14)
+
+        # Rectangular matrices
+        hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])
+        p, l, u = lu(hrect)
+        assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+        assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]]))
+        assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9,  15/9,  24/9],
+                                     [0, 0, -0.5, 0]]), rtol=0., atol=1e-14)
+
+        chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])*1.j
+        p, l, u = lu(chrect)
+        assert_allclose(p, np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]))
+        assert_allclose(l, np.array([[1, 0, 0], [1/9, 1, 0], [5/9, 0.5, 1]]))
+        assert_allclose(u, np.array([[9, 10, 12, 12], [0, 8/9,  15/9,  24/9],
+                                     [0, 0, -0.5, 0]])*1j, rtol=0., atol=1e-14)
+
+        vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])
+        p, l, u = lu(vrect)
+        assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :])
+        assert_allclose(l, np.array([[1., 0, 0], [0.1, 1, 0], [0.7, -0.5, 1],
+                                     [0.4, 0.25, 0.5]]))
+        assert_allclose(u, np.array([[10, 12, 12],
+                                     [0, 0.8, 1.8],
+                                     [0, 0,  1.5]]))
+
+        cvrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])*1j
+        p, l, u = lu(cvrect)
+        assert_allclose(p, np.eye(4)[[1, 3, 2, 0], :])
+        assert_allclose(l, np.array([[1., 0, 0],
+                                     [0.1, 1, 0],
+                                     [0.7, -0.5, 1],
+                                     [0.4, 0.25, 0.5]]))
+        assert_allclose(u, np.array([[10, 12, 12],
+                                     [0, 0.8, 1.8],
+                                     [0, 0,  1.5]])*1j)
+
+    @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20],
+                                       [20, 4], [4, 20], [3, 2, 9, 9],
+                                       [2, 2, 17, 5], [2, 2, 11, 7]])
+    def test_simple_lu_shapes_real_complex(self, shape):
+        a = self.rng.uniform(-10., 10., size=shape)
+        p, l, u = lu(a)
+        assert_allclose(a, p @ l @ u)
+        pl, u = lu(a, permute_l=True)
+        assert_allclose(a, pl @ u)
+
+        b = self.rng.uniform(-10., 10., size=shape)*1j
+        b += self.rng.uniform(-10, 10, size=shape)
+        pl, u = lu(b, permute_l=True)
+        assert_allclose(b, pl @ u)
+
+    @pytest.mark.parametrize('shape', [[2, 2], [2, 4], [4, 2], [20, 20],
+                                       [20, 4], [4, 20]])
+    def test_simple_lu_shapes_real_complex_2d_indices(self, shape):
+        a = self.rng.uniform(-10., 10., size=shape)
+        p, l, u = lu(a, p_indices=True)
+        assert_allclose(a, l[p, :] @ u)
+
+    def test_1by1_input_output(self):
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
+        p, l, u = lu(a, p_indices=True)
+        assert_allclose(p, np.zeros(shape=(4, 5, 1), dtype=int))
+        assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+        assert_allclose(u, a)
+
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)
+        p, l, u = lu(a)
+        assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+        assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+        assert_allclose(u, a)
+
+        pl, u = lu(a, permute_l=True)
+        assert_allclose(pl, np.ones(shape=(4, 5, 1, 1), dtype=np.float32))
+        assert_allclose(u, a)
+
+        a = self.rng.random([4, 5, 1, 1], dtype=np.float32)*np.complex64(1.j)
+        p, l, u = lu(a)
+        assert_allclose(p, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64))
+        assert_allclose(l, np.ones(shape=(4, 5, 1, 1), dtype=np.complex64))
+        assert_allclose(u, a)
+
+    def test_empty_edge_cases(self):
+        a = np.empty([0, 0])
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float64))
+        assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float64))
+        assert_allclose(u, np.empty(shape=(0, 0), dtype=np.float64))
+
+        a = np.empty([0, 3], dtype=np.float16)
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32))
+        assert_allclose(l, np.empty(shape=(0, 0), dtype=np.float32))
+        assert_allclose(u, np.empty(shape=(0, 3), dtype=np.float32))
+
+        a = np.empty([3, 0], dtype=np.complex64)
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0), dtype=np.float32))
+        assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64))
+        assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
+        p, l, u = lu(a, p_indices=True)
+        assert_allclose(p, np.empty(shape=(0,), dtype=int))
+        assert_allclose(l, np.empty(shape=(3, 0), dtype=np.complex64))
+        assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
+        pl, u = lu(a, permute_l=True)
+        assert_allclose(pl, np.empty(shape=(3, 0), dtype=np.complex64))
+        assert_allclose(u, np.empty(shape=(0, 0), dtype=np.complex64))
+
+        a = np.empty([3, 0, 0], dtype=np.complex64)
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(3, 0, 0), dtype=np.float32))
+        assert_allclose(l, np.empty(shape=(3, 0, 0), dtype=np.complex64))
+        assert_allclose(u, np.empty(shape=(3, 0, 0), dtype=np.complex64))
+
+        a = np.empty([0, 0, 3])
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0, 0)))
+        assert_allclose(l, np.empty(shape=(0, 0, 0)))
+        assert_allclose(u, np.empty(shape=(0, 0, 3)))
+
+        with assert_raises(ValueError, match='at least two-dimensional'):
+            lu(np.array([]))
+
+        a = np.array([[]])
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(0, 0)))
+        assert_allclose(l, np.empty(shape=(1, 0)))
+        assert_allclose(u, np.empty(shape=(0, 0)))
+
+        a = np.array([[[]]])
+        p, l, u = lu(a)
+        assert_allclose(p, np.empty(shape=(1, 0, 0)))
+        assert_allclose(l, np.empty(shape=(1, 1, 0)))
+        assert_allclose(u, np.empty(shape=(1, 0, 0)))
+
+
+class TestLUFactor:
+    def setup_method(self):
+        self.rng = np.random.default_rng(1682281250228846)
+
+        self.a = np.array([[1, 2, 3], [1, 2, 3], [2, 5, 6]])
+        self.ca = np.array([[1, 2, 3], [1, 2, 3], [2, 5j, 6]])
+        # Those matrices are more robust to detect problems in permutation
+        # matrices than the ones above
+        self.b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+        self.cb = np.array([[1j, 2j, 3j], [4j, 5j, 6j], [7j, 8j, 9j]])
+
+        # Rectangular matrices
+        self.hrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 12, 12]])
+        self.chrect = np.array([[1, 2, 3, 4], [5, 6, 7, 8],
+                                [9, 10, 12, 12]]) * 1.j
+
+        self.vrect = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 12]])
+        self.cvrect = 1.j * np.array([[1, 2, 3],
+                                      [4, 5, 6],
+                                      [7, 8, 9],
+                                      [10, 12, 12]])
+
+        # Medium sizes matrices
+        self.med = self.rng.random((30, 40))
+        self.cmed = self.rng.random((30, 40)) + 1.j*self.rng.random((30, 40))
+
+    def _test_common_lu_factor(self, data):
+        l_and_u1, piv1 = lu_factor(data)
+        (getrf,) = get_lapack_funcs(("getrf",), (data,))
+        l_and_u2, piv2, _ = getrf(data, overwrite_a=False)
+        assert_allclose(l_and_u1, l_and_u2)
+        assert_allclose(piv1, piv2)
+
+    # Simple tests.
+    # For lu_factor gives a LinAlgWarning because these matrices are singular
+    def test_hrectangular(self):
+        self._test_common_lu_factor(self.hrect)
+
+    def test_vrectangular(self):
+        self._test_common_lu_factor(self.vrect)
+
+    def test_hrectangular_complex(self):
+        self._test_common_lu_factor(self.chrect)
+
+    def test_vrectangular_complex(self):
+        self._test_common_lu_factor(self.cvrect)
+
+    # Bigger matrices
+    def test_medium1(self):
+        """Check lu decomposition on medium size, rectangular matrix."""
+        self._test_common_lu_factor(self.med)
+
+    def test_medium1_complex(self):
+        """Check lu decomposition on medium size, rectangular matrix."""
+        self._test_common_lu_factor(self.cmed)
+
+    def test_check_finite(self):
+        p, l, u = lu(self.a, check_finite=False)
+        assert_allclose(p @ l @ u, self.a)
+
+    def test_simple_known(self):
+        # Ticket #1458
+        for order in ['C', 'F']:
+            A = np.array([[2, 1], [0, 1.]], order=order)
+            LU, P = lu_factor(A)
+            assert_allclose(LU, np.array([[2, 1], [0, 1]]))
+            assert_array_equal(P, np.array([0, 1]))
+
+    @pytest.mark.parametrize("m", [0, 1, 2])
+    @pytest.mark.parametrize("n", [0, 1, 2])
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_shape_dtype(self, m, n,  dtype):
+        k = min(m, n)
+
+        a = np.eye(m, n, dtype=dtype)
+        lu, p = lu_factor(a)
+        assert_equal(lu.shape, (m, n))
+        assert_equal(lu.dtype, dtype)
+        assert_equal(p.shape, (k,))
+        assert_equal(p.dtype, np.int32)
+
+    @pytest.mark.parametrize(("m", "n"), [(0, 0), (0, 2), (2, 0)])
+    def test_empty(self, m, n):
+        a = np.zeros((m, n))
+        lu, p = lu_factor(a)
+        assert_allclose(lu, np.empty((m, n)))
+        assert_allclose(p, np.arange(0))
+
+
+class TestLUSolve:
+    def setup_method(self):
+        self.rng = np.random.default_rng(1682281250228846)
+
+    def test_lu(self):
+        a0 = self.rng.random((10, 10))
+        b = self.rng.random((10,))
+
+        for order in ['C', 'F']:
+            a = np.array(a0, order=order)
+            x1 = solve(a, b)
+            lu_a = lu_factor(a)
+            x2 = lu_solve(lu_a, b)
+            assert_allclose(x1, x2)
+
+    def test_check_finite(self):
+        a = self.rng.random((10, 10))
+        b = self.rng.random((10,))
+        x1 = solve(a, b)
+        lu_a = lu_factor(a, check_finite=False)
+        x2 = lu_solve(lu_a, b, check_finite=False)
+        assert_allclose(x1, x2)
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt, dt_b):
+        lu_and_piv = (np.empty((0, 0), dtype=dt), np.array([]))
+        b = np.asarray([], dtype=dt_b)
+        x = lu_solve(lu_and_piv, b)
+        assert x.shape == (0,)
+
+        m = lu_solve((np.eye(2, dtype=dt), [0, 1]), np.ones(2, dtype=dt_b))
+        assert x.dtype == m.dtype
+
+        b = np.empty((0, 0), dtype=dt_b)
+        x = lu_solve(lu_and_piv, b)
+        assert x.shape == (0, 0)
+        assert x.dtype == m.dtype
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py
new file mode 100644
index 0000000000000000000000000000000000000000..607238842b3cc643d9665e40f29e41b15d8951a1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_polar.py
@@ -0,0 +1,110 @@
+import pytest
+import numpy as np
+from numpy.linalg import norm
+from numpy.testing import (assert_, assert_allclose, assert_equal)
+from scipy.linalg import polar, eigh
+
+
+diag2 = np.array([[2, 0], [0, 3]])
+a13 = np.array([[1, 2, 2]])
+
+precomputed_cases = [
+    [[[0]], 'right', [[1]], [[0]]],
+    [[[0]], 'left', [[1]], [[0]]],
+    [[[9]], 'right', [[1]], [[9]]],
+    [[[9]], 'left', [[1]], [[9]]],
+    [diag2, 'right', np.eye(2), diag2],
+    [diag2, 'left', np.eye(2), diag2],
+    [a13, 'right', a13/norm(a13[0]), a13.T.dot(a13)/norm(a13[0])],
+]
+
+verify_cases = [
+    [[1, 2], [3, 4]],
+    [[1, 2, 3]],
+    [[1], [2], [3]],
+    [[1, 2, 3], [3, 4, 0]],
+    [[1, 2], [3, 4], [5, 5]],
+    [[1, 2], [3, 4+5j]],
+    [[1, 2, 3j]],
+    [[1], [2], [3j]],
+    [[1, 2, 3+2j], [3, 4-1j, -4j]],
+    [[1, 2], [3-2j, 4+0.5j], [5, 5]],
+    [[10000, 10, 1], [-1, 2, 3j], [0, 1, 2]],
+    np.empty((0, 0)),
+    np.empty((0, 2)),
+    np.empty((2, 0)),
+]
+
+
+def check_precomputed_polar(a, side, expected_u, expected_p):
+    # Compare the result of the polar decomposition to a
+    # precomputed result.
+    u, p = polar(a, side=side)
+    assert_allclose(u, expected_u, atol=1e-15)
+    assert_allclose(p, expected_p, atol=1e-15)
+
+
+def verify_polar(a):
+    # Compute the polar decomposition, and then verify that
+    # the result has all the expected properties.
+    product_atol = np.sqrt(np.finfo(float).eps)
+
+    aa = np.asarray(a)
+    m, n = aa.shape
+
+    u, p = polar(a, side='right')
+    assert_equal(u.shape, (m, n))
+    assert_equal(p.shape, (n, n))
+    # a = up
+    assert_allclose(u.dot(p), a, atol=product_atol)
+    if m >= n:
+        assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
+    else:
+        assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
+    # p is Hermitian positive semidefinite.
+    assert_allclose(p.conj().T, p)
+    evals = eigh(p, eigvals_only=True)
+    nonzero_evals = evals[abs(evals) > 1e-14]
+    assert_((nonzero_evals >= 0).all())
+
+    u, p = polar(a, side='left')
+    assert_equal(u.shape, (m, n))
+    assert_equal(p.shape, (m, m))
+    # a = pu
+    assert_allclose(p.dot(u), a, atol=product_atol)
+    if m >= n:
+        assert_allclose(u.conj().T.dot(u), np.eye(n), atol=1e-15)
+    else:
+        assert_allclose(u.dot(u.conj().T), np.eye(m), atol=1e-15)
+    # p is Hermitian positive semidefinite.
+    assert_allclose(p.conj().T, p)
+    evals = eigh(p, eigvals_only=True)
+    nonzero_evals = evals[abs(evals) > 1e-14]
+    assert_((nonzero_evals >= 0).all())
+
+
+def test_precomputed_cases():
+    for a, side, expected_u, expected_p in precomputed_cases:
+        check_precomputed_polar(a, side, expected_u, expected_p)
+
+
+def test_verify_cases():
+    for a in verify_cases:
+        verify_polar(a)
+
+@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+@pytest.mark.parametrize('shape',  [(0, 0), (0, 2), (2, 0)])
+@pytest.mark.parametrize('side', ['left', 'right'])
+def test_empty(dt, shape, side):
+    a = np.empty(shape, dtype=dt)
+    m, n = shape
+    p_shape = (m, m) if side == 'left' else (n, n)
+
+    u, p = polar(a, side=side)
+    u_n, p_n = polar(np.eye(5, dtype=dt))
+
+    assert_equal(u.dtype, u_n.dtype)
+    assert_equal(p.dtype, p_n.dtype)
+    assert u.shape == shape
+    assert p.shape == p_shape
+    assert np.all(p == 0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py
new file mode 100644
index 0000000000000000000000000000000000000000..7553e21d61ceaa774d24c48d9d4bc2e3a8e3cc00
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_decomp_update.py
@@ -0,0 +1,1701 @@
+import itertools
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal
+from pytest import raises as assert_raises
+from scipy import linalg
+import scipy.linalg._decomp_update as _decomp_update
+from scipy.linalg._decomp_update import qr_delete, qr_update, qr_insert
+
+def assert_unitary(a, rtol=None, atol=None, assert_sqr=True):
+    if rtol is None:
+        rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
+    if atol is None:
+        atol = 10*np.finfo(a.dtype).eps
+
+    if assert_sqr:
+        assert_(a.shape[0] == a.shape[1], 'unitary matrices must be square')
+    aTa = np.dot(a.T.conj(), a)
+    assert_allclose(aTa, np.eye(a.shape[1]), rtol=rtol, atol=atol)
+
+def assert_upper_tri(a, rtol=None, atol=None):
+    if rtol is None:
+        rtol = 10.0 ** -(np.finfo(a.dtype).precision-2)
+    if atol is None:
+        atol = 2*np.finfo(a.dtype).eps
+    mask = np.tri(a.shape[0], a.shape[1], -1, np.bool_)
+    assert_allclose(a[mask], 0.0, rtol=rtol, atol=atol)
+
+def check_qr(q, r, a, rtol, atol, assert_sqr=True):
+    assert_unitary(q, rtol, atol, assert_sqr)
+    assert_upper_tri(r, rtol, atol)
+    assert_allclose(q.dot(r), a, rtol=rtol, atol=atol)
+
+def make_strided(arrs):
+    strides = [(3, 7), (2, 2), (3, 4), (4, 2), (5, 4), (2, 3), (2, 1), (4, 5)]
+    kmax = len(strides)
+    k = 0
+    ret = []
+    for a in arrs:
+        if a.ndim == 1:
+            s = strides[k % kmax]
+            k += 1
+            base = np.zeros(s[0]*a.shape[0]+s[1], a.dtype)
+            view = base[s[1]::s[0]]
+            view[...] = a
+        elif a.ndim == 2:
+            s = strides[k % kmax]
+            t = strides[(k+1) % kmax]
+            k += 2
+            base = np.zeros((s[0]*a.shape[0]+s[1], t[0]*a.shape[1]+t[1]),
+                            a.dtype)
+            view = base[s[1]::s[0], t[1]::t[0]]
+            view[...] = a
+        else:
+            raise ValueError('make_strided only works for ndim = 1 or'
+                             ' 2 arrays')
+        ret.append(view)
+    return ret
+
+def negate_strides(arrs):
+    ret = []
+    for a in arrs:
+        b = np.zeros_like(a)
+        if b.ndim == 2:
+            b = b[::-1, ::-1]
+        elif b.ndim == 1:
+            b = b[::-1]
+        else:
+            raise ValueError('negate_strides only works for ndim = 1 or'
+                             ' 2 arrays')
+        b[...] = a
+        ret.append(b)
+    return ret
+
+def nonitemsize_strides(arrs):
+    out = []
+    for a in arrs:
+        a_dtype = a.dtype
+        b = np.zeros(a.shape, [('a', a_dtype), ('junk', 'S1')])
+        c = b.getfield(a_dtype)
+        c[...] = a
+        out.append(c)
+    return out
+
+
+def make_nonnative(arrs):
+    return [a.astype(a.dtype.newbyteorder()) for a in arrs]
+
+
+class BaseQRdeltas:
+    def setup_method(self):
+        self.rtol = 10.0 ** -(np.finfo(self.dtype).precision-2)
+        self.atol = 10 * np.finfo(self.dtype).eps
+
+    def generate(self, type, mode='full'):
+        np.random.seed(29382)
+        shape = {'sqr': (8, 8), 'tall': (12, 7), 'fat': (7, 12),
+                 'Mx1': (8, 1), '1xN': (1, 8), '1x1': (1, 1)}[type]
+        a = np.random.random(shape)
+        if np.iscomplexobj(self.dtype.type(1)):
+            b = np.random.random(shape)
+            a = a + 1j * b
+        a = a.astype(self.dtype)
+        q, r = linalg.qr(a, mode=mode)
+        return a, q, r
+
+class BaseQRdelete(BaseQRdeltas):
+    def test_sqr_1_row(self):
+        a, q, r = self.generate('sqr')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_p_row(self):
+        a, q, r = self.generate('sqr')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_1_col(self):
+        a, q, r = self.generate('sqr')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_p_col(self):
+        a, q, r = self.generate('sqr')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_1_row(self):
+        a, q, r = self.generate('tall')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_p_row(self):
+        a, q, r = self.generate('tall')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_1_col(self):
+        a, q, r = self.generate('tall')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_p_col(self):
+        a, q, r = self.generate('tall')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_1_row(self):
+        a, q, r = self.generate('fat')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_p_row(self):
+        a, q, r = self.generate('fat')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_1_col(self):
+        a, q, r = self.generate('fat')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_p_col(self):
+        a, q, r = self.generate('fat')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_economic_1_row(self):
+        # this test always starts and ends with an economic decomp.
+        a, q, r = self.generate('tall', 'economic')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    # for economic row deletes
+    # eco - prow = eco
+    # eco - prow = sqr
+    # eco - prow = fat
+    def base_economic_p_row_xxx(self, ndel):
+        a, q, r = self.generate('tall', 'economic')
+        for row in range(a.shape[0]-ndel):
+            q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+            a1 = np.delete(a, slice(row, row+ndel), 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_p_row_economic(self):
+        # (12, 7) - (3, 7) = (9,7) --> stays economic
+        self.base_economic_p_row_xxx(3)
+
+    def test_economic_p_row_sqr(self):
+        # (12, 7) - (5, 7) = (7, 7) --> becomes square
+        self.base_economic_p_row_xxx(5)
+
+    def test_economic_p_row_fat(self):
+        # (12, 7) - (7,7) = (5, 7) --> becomes fat
+        self.base_economic_p_row_xxx(7)
+
+    def test_economic_1_col(self):
+        a, q, r = self.generate('tall', 'economic')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_p_col(self):
+        a, q, r = self.generate('tall', 'economic')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_1_row(self):
+        a, q, r = self.generate('Mx1')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_p_row(self):
+        a, q, r = self.generate('Mx1')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_1_col(self):
+        a, q, r = self.generate('1xN')
+        for col in range(r.shape[1]):
+            q1, r1 = qr_delete(q, r, col, which='col', overwrite_qr=False)
+            a1 = np.delete(a, col, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_p_col(self):
+        a, q, r = self.generate('1xN')
+        for ndel in range(2, 6):
+            for col in range(r.shape[1]-ndel):
+                q1, r1 = qr_delete(q, r, col, ndel, which='col',
+                                   overwrite_qr=False)
+                a1 = np.delete(a, slice(col, col+ndel), 1)
+                check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_economic_1_row(self):
+        a, q, r = self.generate('Mx1', 'economic')
+        for row in range(r.shape[0]):
+            q1, r1 = qr_delete(q, r, row, overwrite_qr=False)
+            a1 = np.delete(a, row, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_p_row(self):
+        a, q, r = self.generate('Mx1', 'economic')
+        for ndel in range(2, 6):
+            for row in range(a.shape[0]-ndel):
+                q1, r1 = qr_delete(q, r, row, ndel, overwrite_qr=False)
+                a1 = np.delete(a, slice(row, row+ndel), 0)
+                check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_delete_last_1_row(self):
+        # full and eco are the same for 1xN
+        a, q, r = self.generate('1xN')
+        q1, r1 = qr_delete(q, r, 0, 1, 'row')
+        assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+    def test_delete_last_p_row(self):
+        a, q, r = self.generate('tall', 'full')
+        q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
+        assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+        a, q, r = self.generate('tall', 'economic')
+        q1, r1 = qr_delete(q, r, 0, a.shape[0], 'row')
+        assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+    def test_delete_last_1_col(self):
+        a, q, r = self.generate('Mx1', 'economic')
+        q1, r1 = qr_delete(q, r, 0, 1, 'col')
+        assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
+
+        a, q, r = self.generate('Mx1', 'full')
+        q1, r1 = qr_delete(q, r, 0, 1, 'col')
+        assert_unitary(q1)
+        assert_(q1.dtype == q.dtype)
+        assert_(q1.shape == q.shape)
+        assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
+
+    def test_delete_last_p_col(self):
+        a, q, r = self.generate('tall', 'full')
+        q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
+        assert_unitary(q1)
+        assert_(q1.dtype == q.dtype)
+        assert_(q1.shape == q.shape)
+        assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
+
+        a, q, r = self.generate('tall', 'economic')
+        q1, r1 = qr_delete(q, r, 0, a.shape[1], 'col')
+        assert_equal(q1, np.ndarray(shape=(q.shape[0], 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, 0), dtype=r.dtype))
+
+    def test_delete_1x1_row_col(self):
+        a, q, r = self.generate('1x1')
+        q1, r1 = qr_delete(q, r, 0, 1, 'row')
+        assert_equal(q1, np.ndarray(shape=(0, 0), dtype=q.dtype))
+        assert_equal(r1, np.ndarray(shape=(0, r.shape[1]), dtype=r.dtype))
+
+        a, q, r = self.generate('1x1')
+        q1, r1 = qr_delete(q, r, 0, 1, 'col')
+        assert_unitary(q1)
+        assert_(q1.dtype == q.dtype)
+        assert_(q1.shape == q.shape)
+        assert_equal(r1, np.ndarray(shape=(r.shape[0], 0), dtype=r.dtype))
+
+    # all full qr, row deletes and single column deletes should be able to
+    # handle any non negative strides. (only row and column vector
+    # operations are used.) p column delete require fortran ordered
+    # Q and R and will make a copy as necessary.  Economic qr row deletes
+    # require a contiguous q.
+
+    def base_non_simple_strides(self, adjust_strides, ks, p, which,
+                                overwriteable):
+        if which == 'row':
+            qind = (slice(p,None), slice(p,None))
+            rind = (slice(p,None), slice(None))
+        else:
+            qind = (slice(None), slice(None))
+            rind = (slice(None), slice(None,-p))
+
+        for type, k in itertools.product(['sqr', 'tall', 'fat'], ks):
+            a, q0, r0, = self.generate(type)
+            qs, rs = adjust_strides((q0, r0))
+            if p == 1:
+                a1 = np.delete(a, k, 0 if which == 'row' else 1)
+            else:
+                s = slice(k,k+p)
+                if k < 0:
+                    s = slice(k, k + p +
+                              (a.shape[0] if which == 'row' else a.shape[1]))
+                a1 = np.delete(a, s, 0 if which == 'row' else 1)
+
+            # for each variable, q, r we try with it strided and
+            # overwrite=False. Then we try with overwrite=True, and make
+            # sure that q and r are still overwritten.
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            q1, r1 = qr_delete(qs, r, k, p, which, False)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+            q1o, r1o = qr_delete(qs, r, k, p, which, True)
+            check_qr(q1o, r1o, a1, self.rtol, self.atol)
+            if overwriteable:
+                assert_allclose(q1o, qs[qind], rtol=self.rtol, atol=self.atol)
+                assert_allclose(r1o, r[rind], rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            q2, r2 = qr_delete(q, rs, k, p, which, False)
+            check_qr(q2, r2, a1, self.rtol, self.atol)
+            q2o, r2o = qr_delete(q, rs, k, p, which, True)
+            check_qr(q2o, r2o, a1, self.rtol, self.atol)
+            if overwriteable:
+                assert_allclose(q2o, q[qind], rtol=self.rtol, atol=self.atol)
+                assert_allclose(r2o, rs[rind], rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            # since some of these were consumed above
+            qs, rs = adjust_strides((q, r))
+            q3, r3 = qr_delete(qs, rs, k, p, which, False)
+            check_qr(q3, r3, a1, self.rtol, self.atol)
+            q3o, r3o = qr_delete(qs, rs, k, p, which, True)
+            check_qr(q3o, r3o, a1, self.rtol, self.atol)
+            if overwriteable:
+                assert_allclose(q2o, qs[qind], rtol=self.rtol, atol=self.atol)
+                assert_allclose(r3o, rs[rind], rtol=self.rtol, atol=self.atol)
+
+    def test_non_unit_strides_1_row(self):
+        self.base_non_simple_strides(make_strided, [0], 1, 'row', True)
+
+    def test_non_unit_strides_p_row(self):
+        self.base_non_simple_strides(make_strided, [0], 3, 'row', True)
+
+    def test_non_unit_strides_1_col(self):
+        self.base_non_simple_strides(make_strided, [0], 1, 'col', True)
+
+    def test_non_unit_strides_p_col(self):
+        self.base_non_simple_strides(make_strided, [0], 3, 'col', False)
+
+    def test_neg_strides_1_row(self):
+        self.base_non_simple_strides(negate_strides, [0], 1, 'row', False)
+
+    def test_neg_strides_p_row(self):
+        self.base_non_simple_strides(negate_strides, [0], 3, 'row', False)
+
+    def test_neg_strides_1_col(self):
+        self.base_non_simple_strides(negate_strides, [0], 1, 'col', False)
+
+    def test_neg_strides_p_col(self):
+        self.base_non_simple_strides(negate_strides, [0], 3, 'col', False)
+
+    def test_non_itemize_strides_1_row(self):
+        self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'row', False)
+
+    def test_non_itemize_strides_p_row(self):
+        self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'row', False)
+
+    def test_non_itemize_strides_1_col(self):
+        self.base_non_simple_strides(nonitemsize_strides, [0], 1, 'col', False)
+
+    def test_non_itemize_strides_p_col(self):
+        self.base_non_simple_strides(nonitemsize_strides, [0], 3, 'col', False)
+
+    def test_non_native_byte_order_1_row(self):
+        self.base_non_simple_strides(make_nonnative, [0], 1, 'row', False)
+
+    def test_non_native_byte_order_p_row(self):
+        self.base_non_simple_strides(make_nonnative, [0], 3, 'row', False)
+
+    def test_non_native_byte_order_1_col(self):
+        self.base_non_simple_strides(make_nonnative, [0], 1, 'col', False)
+
+    def test_non_native_byte_order_p_col(self):
+        self.base_non_simple_strides(make_nonnative, [0], 3, 'col', False)
+
+    def test_neg_k(self):
+        a, q, r = self.generate('sqr')
+        for k, p, w in itertools.product([-3, -7], [1, 3], ['row', 'col']):
+            q1, r1 = qr_delete(q, r, k, p, w, overwrite_qr=False)
+            if w == 'row':
+                a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[0]), 0)
+            else:
+                a1 = np.delete(a, slice(k+a.shape[0], k+p+a.shape[1]), 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def base_overwrite_qr(self, which, p, test_C, test_F, mode='full'):
+        assert_sqr = True if mode == 'full' else False
+        if which == 'row':
+            qind = (slice(p,None), slice(p,None))
+            rind = (slice(p,None), slice(None))
+        else:
+            qind = (slice(None), slice(None))
+            rind = (slice(None), slice(None,-p))
+        a, q0, r0 = self.generate('sqr', mode)
+        if p == 1:
+            a1 = np.delete(a, 3, 0 if which == 'row' else 1)
+        else:
+            a1 = np.delete(a, slice(3, 3+p), 0 if which == 'row' else 1)
+
+        # don't overwrite
+        q = q0.copy('F')
+        r = r0.copy('F')
+        q1, r1 = qr_delete(q, r, 3, p, which, False)
+        check_qr(q1, r1, a1, self.rtol, self.atol, assert_sqr)
+        check_qr(q, r, a, self.rtol, self.atol, assert_sqr)
+
+        if test_F:
+            q = q0.copy('F')
+            r = r0.copy('F')
+            q2, r2 = qr_delete(q, r, 3, p, which, True)
+            check_qr(q2, r2, a1, self.rtol, self.atol, assert_sqr)
+            # verify the overwriting
+            assert_allclose(q2, q[qind], rtol=self.rtol, atol=self.atol)
+            assert_allclose(r2, r[rind], rtol=self.rtol, atol=self.atol)
+
+        if test_C:
+            q = q0.copy('C')
+            r = r0.copy('C')
+            q3, r3 = qr_delete(q, r, 3, p, which, True)
+            check_qr(q3, r3, a1, self.rtol, self.atol, assert_sqr)
+            assert_allclose(q3, q[qind], rtol=self.rtol, atol=self.atol)
+            assert_allclose(r3, r[rind], rtol=self.rtol, atol=self.atol)
+
+    def test_overwrite_qr_1_row(self):
+        # any positively strided q and r.
+        self.base_overwrite_qr('row', 1, True, True)
+
+    def test_overwrite_economic_qr_1_row(self):
+        # Any contiguous q and positively strided r.
+        self.base_overwrite_qr('row', 1, True, True, 'economic')
+
+    def test_overwrite_qr_1_col(self):
+        # any positively strided q and r.
+        # full and eco share code paths
+        self.base_overwrite_qr('col', 1, True, True)
+
+    def test_overwrite_qr_p_row(self):
+        # any positively strided q and r.
+        self.base_overwrite_qr('row', 3, True, True)
+
+    def test_overwrite_economic_qr_p_row(self):
+        # any contiguous q and positively strided r
+        self.base_overwrite_qr('row', 3, True, True, 'economic')
+
+    def test_overwrite_qr_p_col(self):
+        # only F ordered q and r can be overwritten for cols
+        # full and eco share code paths
+        self.base_overwrite_qr('col', 3, False, True)
+
+    def test_bad_which(self):
+        a, q, r = self.generate('sqr')
+        assert_raises(ValueError, qr_delete, q, r, 0, which='foo')
+
+    def test_bad_k(self):
+        a, q, r = self.generate('tall')
+        assert_raises(ValueError, qr_delete, q, r, q.shape[0], 1)
+        assert_raises(ValueError, qr_delete, q, r, -q.shape[0]-1, 1)
+        assert_raises(ValueError, qr_delete, q, r, r.shape[0], 1, 'col')
+        assert_raises(ValueError, qr_delete, q, r, -r.shape[0]-1, 1, 'col')
+
+    def test_bad_p(self):
+        a, q, r = self.generate('tall')
+        # p must be positive
+        assert_raises(ValueError, qr_delete, q, r, 0, -1)
+        assert_raises(ValueError, qr_delete, q, r, 0, -1, 'col')
+
+        # and nonzero
+        assert_raises(ValueError, qr_delete, q, r, 0, 0)
+        assert_raises(ValueError, qr_delete, q, r, 0, 0, 'col')
+
+        # must have at least k+p rows or cols, depending.
+        assert_raises(ValueError, qr_delete, q, r, 3, q.shape[0]-2)
+        assert_raises(ValueError, qr_delete, q, r, 3, r.shape[1]-2, 'col')
+
+    def test_empty_q(self):
+        a, q, r = self.generate('tall')
+        # same code path for 'row' and 'col'
+        assert_raises(ValueError, qr_delete, np.array([]), r, 0, 1)
+
+    def test_empty_r(self):
+        a, q, r = self.generate('tall')
+        # same code path for 'row' and 'col'
+        assert_raises(ValueError, qr_delete, q, np.array([]), 0, 1)
+
+    def test_mismatched_q_and_r(self):
+        a, q, r = self.generate('tall')
+        r = r[1:]
+        assert_raises(ValueError, qr_delete, q, r, 0, 1)
+
+    def test_unsupported_dtypes(self):
+        dts = ['int8', 'int16', 'int32', 'int64',
+               'uint8', 'uint16', 'uint32', 'uint64',
+               'float16', 'longdouble', 'clongdouble',
+               'bool']
+        a, q0, r0 = self.generate('tall')
+        for dtype in dts:
+            q = q0.real.astype(dtype)
+            with np.errstate(invalid="ignore"):
+                r = r0.real.astype(dtype)
+            assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
+            assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'row')
+            assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
+            assert_raises(ValueError, qr_delete, q, r0, 0, 2, 'col')
+
+            assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
+            assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'row')
+            assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
+            assert_raises(ValueError, qr_delete, q0, r, 0, 2, 'col')
+
+    def test_check_finite(self):
+        a0, q0, r0 = self.generate('tall')
+
+        q = q0.copy('F')
+        q[1,1] = np.nan
+        assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'row')
+        assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'row')
+        assert_raises(ValueError, qr_delete, q, r0, 0, 1, 'col')
+        assert_raises(ValueError, qr_delete, q, r0, 0, 3, 'col')
+
+        r = r0.copy('F')
+        r[1,1] = np.nan
+        assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'row')
+        assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'row')
+        assert_raises(ValueError, qr_delete, q0, r, 0, 1, 'col')
+        assert_raises(ValueError, qr_delete, q0, r, 0, 3, 'col')
+
+    def test_qr_scalar(self):
+        a, q, r = self.generate('1x1')
+        assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'row')
+        assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'row')
+        assert_raises(ValueError, qr_delete, q[0, 0], r, 0, 1, 'col')
+        assert_raises(ValueError, qr_delete, q, r[0, 0], 0, 1, 'col')
+
+class TestQRdelete_f(BaseQRdelete):
+    dtype = np.dtype('f')
+
+class TestQRdelete_F(BaseQRdelete):
+    dtype = np.dtype('F')
+
+class TestQRdelete_d(BaseQRdelete):
+    dtype = np.dtype('d')
+
+class TestQRdelete_D(BaseQRdelete):
+    dtype = np.dtype('D')
+
+class BaseQRinsert(BaseQRdeltas):
+    def generate(self, type, mode='full', which='row', p=1):
+        a, q, r = super().generate(type, mode)
+
+        assert_(p > 0)
+        rng = np.random.RandomState(1234)
+
+        # super call set the seed...
+        if which == 'row':
+            if p == 1:
+                u = rng.random(a.shape[1])
+            else:
+                u = rng.random((p, a.shape[1]))
+        elif which == 'col':
+            if p == 1:
+                u = rng.random(a.shape[0])
+            else:
+                u = rng.random((a.shape[0], p))
+        else:
+            ValueError('which should be either "row" or "col"')
+
+        if np.iscomplexobj(self.dtype.type(1)):
+            b = rng.random(u.shape)
+            u = u + 1j * b
+
+        u = u.astype(self.dtype)
+        return a, q, r, u
+
+    def test_sqr_1_row(self):
+        a, q, r, u = self.generate('sqr', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_p_row(self):
+        # sqr + rows --> fat always
+        a, q, r, u = self.generate('sqr', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_1_col(self):
+        a, q, r, u = self.generate('sqr', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_p_col(self):
+        # sqr + cols --> fat always
+        a, q, r, u = self.generate('sqr', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_1_row(self):
+        a, q, r, u = self.generate('tall', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_p_row(self):
+        # tall + rows --> tall always
+        a, q, r, u = self.generate('tall', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_1_col(self):
+        a, q, r, u = self.generate('tall', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    # for column adds to tall matrices there are three cases to test
+    # tall + pcol --> tall
+    # tall + pcol --> sqr
+    # tall + pcol --> fat
+    def base_tall_p_col_xxx(self, p):
+        a, q, r, u = self.generate('tall', which='col', p=p)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_p_col_tall(self):
+        # 12x7 + 12x3 = 12x10 --> stays tall
+        self.base_tall_p_col_xxx(3)
+
+    def test_tall_p_col_sqr(self):
+        # 12x7 + 12x5 = 12x12 --> becomes sqr
+        self.base_tall_p_col_xxx(5)
+
+    def test_tall_p_col_fat(self):
+        # 12x7 + 12x7 = 12x14 --> becomes fat
+        self.base_tall_p_col_xxx(7)
+
+    def test_fat_1_row(self):
+        a, q, r, u = self.generate('fat', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    # for row adds to fat matrices there are three cases to test
+    # fat + prow --> fat
+    # fat + prow --> sqr
+    # fat + prow --> tall
+    def base_fat_p_row_xxx(self, p):
+        a, q, r, u = self.generate('fat', which='row', p=p)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(p, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_p_row_fat(self):
+        # 7x12 + 3x12 = 10x12 --> stays fat
+        self.base_fat_p_row_xxx(3)
+
+    def test_fat_p_row_sqr(self):
+        # 7x12 + 5x12 = 12x12 --> becomes sqr
+        self.base_fat_p_row_xxx(5)
+
+    def test_fat_p_row_tall(self):
+        # 7x12 + 7x12 = 14x12 --> becomes tall
+        self.base_fat_p_row_xxx(7)
+
+    def test_fat_1_col(self):
+        a, q, r, u = self.generate('fat', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_p_col(self):
+        # fat + cols --> fat always
+        a, q, r, u = self.generate('fat', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_economic_1_row(self):
+        a, q, r, u = self.generate('tall', 'economic', 'row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_p_row(self):
+        # tall + rows --> tall always
+        a, q, r, u = self.generate('tall', 'economic', 'row', 3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row, overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_1_col(self):
+        a, q, r, u = self.generate('tall', 'economic', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u.copy(), col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_1_col_bad_update(self):
+        # When the column to be added lies in the span of Q, the update is
+        # not meaningful.  This is detected, and a LinAlgError is issued.
+        q = np.eye(5, 3, dtype=self.dtype)
+        r = np.eye(3, dtype=self.dtype)
+        u = np.array([1, 0, 0, 0, 0], self.dtype)
+        assert_raises(linalg.LinAlgError, qr_insert, q, r, u, 0, 'col')
+
+    # for column adds to economic matrices there are three cases to test
+    # eco + pcol --> eco
+    # eco + pcol --> sqr
+    # eco + pcol --> fat
+    def base_economic_p_col_xxx(self, p):
+        a, q, r, u = self.generate('tall', 'economic', which='col', p=p)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(p, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_p_col_eco(self):
+        # 12x7 + 12x3 = 12x10 --> stays eco
+        self.base_economic_p_col_xxx(3)
+
+    def test_economic_p_col_sqr(self):
+        # 12x7 + 12x5 = 12x12 --> becomes sqr
+        self.base_economic_p_col_xxx(5)
+
+    def test_economic_p_col_fat(self):
+        # 12x7 + 12x7 = 12x14 --> becomes fat
+        self.base_economic_p_col_xxx(7)
+
+    def test_Mx1_1_row(self):
+        a, q, r, u = self.generate('Mx1', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_p_row(self):
+        a, q, r, u = self.generate('Mx1', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_1_col(self):
+        a, q, r, u = self.generate('Mx1', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_p_col(self):
+        a, q, r, u = self.generate('Mx1', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_economic_1_row(self):
+        a, q, r, u = self.generate('Mx1', 'economic', 'row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_p_row(self):
+        a, q, r, u = self.generate('Mx1', 'economic', 'row', 3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_1_col(self):
+        a, q, r, u = self.generate('Mx1', 'economic', 'col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_p_col(self):
+        a, q, r, u = self.generate('Mx1', 'economic', 'col', 3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_1xN_1_row(self):
+        a, q, r, u = self.generate('1xN', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_p_row(self):
+        a, q, r, u = self.generate('1xN', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_1_col(self):
+        a, q, r, u = self.generate('1xN', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_p_col(self):
+        a, q, r, u = self.generate('1xN', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_1_row(self):
+        a, q, r, u = self.generate('1x1', which='row')
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, row, u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_p_row(self):
+        a, q, r, u = self.generate('1x1', which='row', p=3)
+        for row in range(r.shape[0] + 1):
+            q1, r1 = qr_insert(q, r, u, row)
+            a1 = np.insert(a, np.full(3, row, np.intp), u, 0)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_1_col(self):
+        a, q, r, u = self.generate('1x1', which='col')
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, col, u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_p_col(self):
+        a, q, r, u = self.generate('1x1', which='col', p=3)
+        for col in range(r.shape[1] + 1):
+            q1, r1 = qr_insert(q, r, u, col, 'col', overwrite_qru=False)
+            a1 = np.insert(a, np.full(3, col, np.intp), u, 1)
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_1_scalar(self):
+        a, q, r, u = self.generate('1x1', which='row')
+        assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'row')
+
+        assert_raises(ValueError, qr_insert, q[0, 0], r, u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r[0, 0], u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r, u[0], 0, 'col')
+
+    def base_non_simple_strides(self, adjust_strides, k, p, which):
+        for type in ['sqr', 'tall', 'fat']:
+            a, q0, r0, u0 = self.generate(type, which=which, p=p)
+            qs, rs, us = adjust_strides((q0, r0, u0))
+            if p == 1:
+                ai = np.insert(a, k, u0, 0 if which == 'row' else 1)
+            else:
+                ai = np.insert(a, np.full(p, k, np.intp),
+                        u0 if which == 'row' else u0,
+                        0 if which == 'row' else 1)
+
+            # for each variable, q, r, u we try with it strided and
+            # overwrite=False. Then we try with overwrite=True. Nothing
+            # is checked to see if it can be overwritten, since only
+            # F ordered Q can be overwritten when adding columns.
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            q1, r1 = qr_insert(qs, r, u, k, which, overwrite_qru=False)
+            check_qr(q1, r1, ai, self.rtol, self.atol)
+            q1o, r1o = qr_insert(qs, r, u, k, which, overwrite_qru=True)
+            check_qr(q1o, r1o, ai, self.rtol, self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            q2, r2 = qr_insert(q, rs, u, k, which, overwrite_qru=False)
+            check_qr(q2, r2, ai, self.rtol, self.atol)
+            q2o, r2o = qr_insert(q, rs, u, k, which, overwrite_qru=True)
+            check_qr(q2o, r2o, ai, self.rtol, self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            q3, r3 = qr_insert(q, r, us, k, which, overwrite_qru=False)
+            check_qr(q3, r3, ai, self.rtol, self.atol)
+            q3o, r3o = qr_insert(q, r, us, k, which, overwrite_qru=True)
+            check_qr(q3o, r3o, ai, self.rtol, self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            # since some of these were consumed above
+            qs, rs, us = adjust_strides((q, r, u))
+            q5, r5 = qr_insert(qs, rs, us, k, which, overwrite_qru=False)
+            check_qr(q5, r5, ai, self.rtol, self.atol)
+            q5o, r5o = qr_insert(qs, rs, us, k, which, overwrite_qru=True)
+            check_qr(q5o, r5o, ai, self.rtol, self.atol)
+
+    def test_non_unit_strides_1_row(self):
+        self.base_non_simple_strides(make_strided, 0, 1, 'row')
+
+    def test_non_unit_strides_p_row(self):
+        self.base_non_simple_strides(make_strided, 0, 3, 'row')
+
+    def test_non_unit_strides_1_col(self):
+        self.base_non_simple_strides(make_strided, 0, 1, 'col')
+
+    def test_non_unit_strides_p_col(self):
+        self.base_non_simple_strides(make_strided, 0, 3, 'col')
+
+    def test_neg_strides_1_row(self):
+        self.base_non_simple_strides(negate_strides, 0, 1, 'row')
+
+    def test_neg_strides_p_row(self):
+        self.base_non_simple_strides(negate_strides, 0, 3, 'row')
+
+    def test_neg_strides_1_col(self):
+        self.base_non_simple_strides(negate_strides, 0, 1, 'col')
+
+    def test_neg_strides_p_col(self):
+        self.base_non_simple_strides(negate_strides, 0, 3, 'col')
+
+    def test_non_itemsize_strides_1_row(self):
+        self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'row')
+
+    def test_non_itemsize_strides_p_row(self):
+        self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'row')
+
+    def test_non_itemsize_strides_1_col(self):
+        self.base_non_simple_strides(nonitemsize_strides, 0, 1, 'col')
+
+    def test_non_itemsize_strides_p_col(self):
+        self.base_non_simple_strides(nonitemsize_strides, 0, 3, 'col')
+
+    def test_non_native_byte_order_1_row(self):
+        self.base_non_simple_strides(make_nonnative, 0, 1, 'row')
+
+    def test_non_native_byte_order_p_row(self):
+        self.base_non_simple_strides(make_nonnative, 0, 3, 'row')
+
+    def test_non_native_byte_order_1_col(self):
+        self.base_non_simple_strides(make_nonnative, 0, 1, 'col')
+
+    def test_non_native_byte_order_p_col(self):
+        self.base_non_simple_strides(make_nonnative, 0, 3, 'col')
+
+    def test_overwrite_qu_rank_1(self):
+        # when inserting rows, the size of both Q and R change, so only
+        # column inserts can overwrite q. Only complex column inserts
+        # with C ordered Q overwrite u. Any contiguous Q is overwritten
+        # when inserting 1 column
+        a, q0, r, u, = self.generate('sqr', which='col', p=1)
+        q = q0.copy('C')
+        u0 = u.copy()
+        # don't overwrite
+        q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
+        a1 = np.insert(a, 0, u0, 1)
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+        check_qr(q, r, a, self.rtol, self.atol)
+
+        # try overwriting
+        q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
+        check_qr(q2, r2, a1, self.rtol, self.atol)
+        # verify the overwriting
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(u, u0.conj(), self.rtol, self.atol)
+
+        # now try with a fortran ordered Q
+        qF = q0.copy('F')
+        u1 = u0.copy()
+        q3, r3 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=False)
+        check_qr(q3, r3, a1, self.rtol, self.atol)
+        check_qr(qF, r, a, self.rtol, self.atol)
+
+        # try overwriting
+        q4, r4 = qr_insert(qF, r, u1, 0, 'col', overwrite_qru=True)
+        check_qr(q4, r4, a1, self.rtol, self.atol)
+        assert_allclose(q4, qF, rtol=self.rtol, atol=self.atol)
+
+    def test_overwrite_qu_rank_p(self):
+        # when inserting rows, the size of both Q and R change, so only
+        # column inserts can potentially overwrite Q.  In practice, only
+        # F ordered Q are overwritten with a rank p update.
+        a, q0, r, u, = self.generate('sqr', which='col', p=3)
+        q = q0.copy('F')
+        a1 = np.insert(a, np.zeros(3, np.intp), u, 1)
+
+        # don't overwrite
+        q1, r1 = qr_insert(q, r, u, 0, 'col', overwrite_qru=False)
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+        check_qr(q, r, a, self.rtol, self.atol)
+
+        # try overwriting
+        q2, r2 = qr_insert(q, r, u, 0, 'col', overwrite_qru=True)
+        check_qr(q2, r2, a1, self.rtol, self.atol)
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+
+    def test_empty_inputs(self):
+        a, q, r, u = self.generate('sqr', which='row')
+        assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'row')
+        assert_raises(ValueError, qr_insert, np.array([]), r, u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, np.array([]), u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r, np.array([]), 0, 'col')
+
+    def test_mismatched_shapes(self):
+        a, q, r, u = self.generate('tall', which='row')
+        assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r[1:], u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q[:-2], r, u, 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r, u[1:], 0, 'col')
+
+    def test_unsupported_dtypes(self):
+        dts = ['int8', 'int16', 'int32', 'int64',
+               'uint8', 'uint16', 'uint32', 'uint64',
+               'float16', 'longdouble', 'clongdouble',
+               'bool']
+        a, q0, r0, u0 = self.generate('sqr', which='row')
+        for dtype in dts:
+            q = q0.real.astype(dtype)
+            with np.errstate(invalid="ignore"):
+                r = r0.real.astype(dtype)
+            u = u0.real.astype(dtype)
+            assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
+            assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
+            assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
+            assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
+            assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
+            assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
+
+    def test_check_finite(self):
+        a0, q0, r0, u0 = self.generate('sqr', which='row', p=3)
+
+        q = q0.copy('F')
+        q[1,1] = np.nan
+        assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'row')
+        assert_raises(ValueError, qr_insert, q, r0, u0[:,0], 0, 'col')
+        assert_raises(ValueError, qr_insert, q, r0, u0, 0, 'col')
+
+        r = r0.copy('F')
+        r[1,1] = np.nan
+        assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'row')
+        assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'row')
+        assert_raises(ValueError, qr_insert, q0, r, u0[:,0], 0, 'col')
+        assert_raises(ValueError, qr_insert, q0, r, u0, 0, 'col')
+
+        u = u0.copy('F')
+        u[0,0] = np.nan
+        assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'row')
+        assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'row')
+        assert_raises(ValueError, qr_insert, q0, r0, u[:,0], 0, 'col')
+        assert_raises(ValueError, qr_insert, q0, r0, u, 0, 'col')
+
+class TestQRinsert_f(BaseQRinsert):
+    dtype = np.dtype('f')
+
+class TestQRinsert_F(BaseQRinsert):
+    dtype = np.dtype('F')
+
+class TestQRinsert_d(BaseQRinsert):
+    dtype = np.dtype('d')
+
+class TestQRinsert_D(BaseQRinsert):
+    dtype = np.dtype('D')
+
+class BaseQRupdate(BaseQRdeltas):
+    def generate(self, type, mode='full', p=1):
+        a, q, r = super().generate(type, mode)
+
+        # super call set the seed...
+        if p == 1:
+            u = np.random.random(q.shape[0])
+            v = np.random.random(r.shape[1])
+        else:
+            u = np.random.random((q.shape[0], p))
+            v = np.random.random((r.shape[1], p))
+
+        if np.iscomplexobj(self.dtype.type(1)):
+            b = np.random.random(u.shape)
+            u = u + 1j * b
+
+            c = np.random.random(v.shape)
+            v = v + 1j * c
+
+        u = u.astype(self.dtype)
+        v = v.astype(self.dtype)
+        return a, q, r, u, v
+
+    def test_sqr_rank_1(self):
+        a, q, r, u, v = self.generate('sqr')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_sqr_rank_p(self):
+        # test ndim = 2, rank 1 updates here too
+        for p in [1, 2, 3, 5]:
+            a, q, r, u, v = self.generate('sqr', p=p)
+            if p == 1:
+                u = u.reshape(u.size, 1)
+                v = v.reshape(v.size, 1)
+            q1, r1 = qr_update(q, r, u, v, False)
+            a1 = a + np.dot(u, v.T.conj())
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_rank_1(self):
+        a, q, r, u, v = self.generate('tall')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_tall_rank_p(self):
+        for p in [1, 2, 3, 5]:
+            a, q, r, u, v = self.generate('tall', p=p)
+            if p == 1:
+                u = u.reshape(u.size, 1)
+                v = v.reshape(v.size, 1)
+            q1, r1 = qr_update(q, r, u, v, False)
+            a1 = a + np.dot(u, v.T.conj())
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_rank_1(self):
+        a, q, r, u, v = self.generate('fat')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_fat_rank_p(self):
+        for p in [1, 2, 3, 5]:
+            a, q, r, u, v = self.generate('fat', p=p)
+            if p == 1:
+                u = u.reshape(u.size, 1)
+                v = v.reshape(v.size, 1)
+            q1, r1 = qr_update(q, r, u, v, False)
+            a1 = a + np.dot(u, v.T.conj())
+            check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_economic_rank_1(self):
+        a, q, r, u, v = self.generate('tall', 'economic')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_economic_rank_p(self):
+        for p in [1, 2, 3, 5]:
+            a, q, r, u, v = self.generate('tall', 'economic', p)
+            if p == 1:
+                u = u.reshape(u.size, 1)
+                v = v.reshape(v.size, 1)
+            q1, r1 = qr_update(q, r, u, v, False)
+            a1 = a + np.dot(u, v.T.conj())
+            check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_rank_1(self):
+        a, q, r, u, v = self.generate('Mx1')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_rank_p(self):
+        # when M or N == 1, only a rank 1 update is allowed. This isn't
+        # fundamental limitation, but the code does not support it.
+        a, q, r, u, v = self.generate('Mx1', p=1)
+        u = u.reshape(u.size, 1)
+        v = v.reshape(v.size, 1)
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.dot(u, v.T.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_Mx1_economic_rank_1(self):
+        a, q, r, u, v = self.generate('Mx1', 'economic')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_Mx1_economic_rank_p(self):
+        # when M or N == 1, only a rank 1 update is allowed. This isn't
+        # fundamental limitation, but the code does not support it.
+        a, q, r, u, v = self.generate('Mx1', 'economic', p=1)
+        u = u.reshape(u.size, 1)
+        v = v.reshape(v.size, 1)
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.dot(u, v.T.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+    def test_1xN_rank_1(self):
+        a, q, r, u, v = self.generate('1xN')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1xN_rank_p(self):
+        # when M or N == 1, only a rank 1 update is allowed. This isn't
+        # fundamental limitation, but the code does not support it.
+        a, q, r, u, v = self.generate('1xN', p=1)
+        u = u.reshape(u.size, 1)
+        v = v.reshape(v.size, 1)
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.dot(u, v.T.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_rank_1(self):
+        a, q, r, u, v = self.generate('1x1')
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_rank_p(self):
+        # when M or N == 1, only a rank 1 update is allowed. This isn't
+        # fundamental limitation, but the code does not support it.
+        a, q, r, u, v = self.generate('1x1', p=1)
+        u = u.reshape(u.size, 1)
+        v = v.reshape(v.size, 1)
+        q1, r1 = qr_update(q, r, u, v, False)
+        a1 = a + np.dot(u, v.T.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+
+    def test_1x1_rank_1_scalar(self):
+        a, q, r, u, v = self.generate('1x1')
+        assert_raises(ValueError, qr_update, q[0, 0], r, u, v)
+        assert_raises(ValueError, qr_update, q, r[0, 0], u, v)
+        assert_raises(ValueError, qr_update, q, r, u[0], v)
+        assert_raises(ValueError, qr_update, q, r, u, v[0])
+
+    def base_non_simple_strides(self, adjust_strides, mode, p, overwriteable):
+        assert_sqr = False if mode == 'economic' else True
+        for type in ['sqr', 'tall', 'fat']:
+            a, q0, r0, u0, v0 = self.generate(type, mode, p)
+            qs, rs, us, vs = adjust_strides((q0, r0, u0, v0))
+            if p == 1:
+                aup = a + np.outer(u0, v0.conj())
+            else:
+                aup = a + np.dot(u0, v0.T.conj())
+
+            # for each variable, q, r, u, v we try with it strided and
+            # overwrite=False. Then we try with overwrite=True, and make
+            # sure that if p == 1, r and v are still overwritten.
+            # a strided q and u must always be copied.
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            q1, r1 = qr_update(qs, r, u, v, False)
+            check_qr(q1, r1, aup, self.rtol, self.atol, assert_sqr)
+            q1o, r1o = qr_update(qs, r, u, v, True)
+            check_qr(q1o, r1o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r1o, r, rtol=self.rtol, atol=self.atol)
+                assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            q2, r2 = qr_update(q, rs, u, v, False)
+            check_qr(q2, r2, aup, self.rtol, self.atol, assert_sqr)
+            q2o, r2o = qr_update(q, rs, u, v, True)
+            check_qr(q2o, r2o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r2o, rs, rtol=self.rtol, atol=self.atol)
+                assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            q3, r3 = qr_update(q, r, us, v, False)
+            check_qr(q3, r3, aup, self.rtol, self.atol, assert_sqr)
+            q3o, r3o = qr_update(q, r, us, v, True)
+            check_qr(q3o, r3o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r3o, r, rtol=self.rtol, atol=self.atol)
+                assert_allclose(v, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            q4, r4 = qr_update(q, r, u, vs, False)
+            check_qr(q4, r4, aup, self.rtol, self.atol, assert_sqr)
+            q4o, r4o = qr_update(q, r, u, vs, True)
+            check_qr(q4o, r4o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r4o, r, rtol=self.rtol, atol=self.atol)
+                assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+            q = q0.copy('F')
+            r = r0.copy('F')
+            u = u0.copy('F')
+            v = v0.copy('C')
+            # since some of these were consumed above
+            qs, rs, us, vs = adjust_strides((q, r, u, v))
+            q5, r5 = qr_update(qs, rs, us, vs, False)
+            check_qr(q5, r5, aup, self.rtol, self.atol, assert_sqr)
+            q5o, r5o = qr_update(qs, rs, us, vs, True)
+            check_qr(q5o, r5o, aup, self.rtol, self.atol, assert_sqr)
+            if overwriteable:
+                assert_allclose(r5o, rs, rtol=self.rtol, atol=self.atol)
+                assert_allclose(vs, v0.conj(), rtol=self.rtol, atol=self.atol)
+
+    def test_non_unit_strides_rank_1(self):
+        self.base_non_simple_strides(make_strided, 'full', 1, True)
+
+    def test_non_unit_strides_economic_rank_1(self):
+        self.base_non_simple_strides(make_strided, 'economic', 1, True)
+
+    def test_non_unit_strides_rank_p(self):
+        self.base_non_simple_strides(make_strided, 'full', 3, False)
+
+    def test_non_unit_strides_economic_rank_p(self):
+        self.base_non_simple_strides(make_strided, 'economic', 3, False)
+
+    def test_neg_strides_rank_1(self):
+        self.base_non_simple_strides(negate_strides, 'full', 1, False)
+
+    def test_neg_strides_economic_rank_1(self):
+        self.base_non_simple_strides(negate_strides, 'economic', 1, False)
+
+    def test_neg_strides_rank_p(self):
+        self.base_non_simple_strides(negate_strides, 'full', 3, False)
+
+    def test_neg_strides_economic_rank_p(self):
+        self.base_non_simple_strides(negate_strides, 'economic', 3, False)
+
+    def test_non_itemsize_strides_rank_1(self):
+        self.base_non_simple_strides(nonitemsize_strides, 'full', 1, False)
+
+    def test_non_itemsize_strides_economic_rank_1(self):
+        self.base_non_simple_strides(nonitemsize_strides, 'economic', 1, False)
+
+    def test_non_itemsize_strides_rank_p(self):
+        self.base_non_simple_strides(nonitemsize_strides, 'full', 3, False)
+
+    def test_non_itemsize_strides_economic_rank_p(self):
+        self.base_non_simple_strides(nonitemsize_strides, 'economic', 3, False)
+
+    def test_non_native_byte_order_rank_1(self):
+        self.base_non_simple_strides(make_nonnative, 'full', 1, False)
+
+    def test_non_native_byte_order_economic_rank_1(self):
+        self.base_non_simple_strides(make_nonnative, 'economic', 1, False)
+
+    def test_non_native_byte_order_rank_p(self):
+        self.base_non_simple_strides(make_nonnative, 'full', 3, False)
+
+    def test_non_native_byte_order_economic_rank_p(self):
+        self.base_non_simple_strides(make_nonnative, 'economic', 3, False)
+
+    def test_overwrite_qruv_rank_1(self):
+        # Any positive strided q, r, u, and v can be overwritten for a rank 1
+        # update, only checking C and F contiguous.
+        a, q0, r0, u0, v0 = self.generate('sqr')
+        a1 = a + np.outer(u0, v0.conj())
+        q = q0.copy('F')
+        r = r0.copy('F')
+        u = u0.copy('F')
+        v = v0.copy('F')
+
+        # don't overwrite
+        q1, r1 = qr_update(q, r, u, v, False)
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+        check_qr(q, r, a, self.rtol, self.atol)
+
+        q2, r2 = qr_update(q, r, u, v, True)
+        check_qr(q2, r2, a1, self.rtol, self.atol)
+        # verify the overwriting, no good way to check u and v.
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
+
+        q = q0.copy('C')
+        r = r0.copy('C')
+        u = u0.copy('C')
+        v = v0.copy('C')
+        q3, r3 = qr_update(q, r, u, v, True)
+        check_qr(q3, r3, a1, self.rtol, self.atol)
+        assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
+
+    def test_overwrite_qruv_rank_1_economic(self):
+        # updating economic decompositions can overwrite any contiguous r,
+        # and positively strided r and u. V is only ever read.
+        # only checking C and F contiguous.
+        a, q0, r0, u0, v0 = self.generate('tall', 'economic')
+        a1 = a + np.outer(u0, v0.conj())
+        q = q0.copy('F')
+        r = r0.copy('F')
+        u = u0.copy('F')
+        v = v0.copy('F')
+
+        # don't overwrite
+        q1, r1 = qr_update(q, r, u, v, False)
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+        check_qr(q, r, a, self.rtol, self.atol, False)
+
+        q2, r2 = qr_update(q, r, u, v, True)
+        check_qr(q2, r2, a1, self.rtol, self.atol, False)
+        # verify the overwriting, no good way to check u and v.
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
+
+        q = q0.copy('C')
+        r = r0.copy('C')
+        u = u0.copy('C')
+        v = v0.copy('C')
+        q3, r3 = qr_update(q, r, u, v, True)
+        check_qr(q3, r3, a1, self.rtol, self.atol, False)
+        assert_allclose(q3, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r3, r, rtol=self.rtol, atol=self.atol)
+
+    def test_overwrite_qruv_rank_p(self):
+        # for rank p updates, q r must be F contiguous, v must be C (v.T --> F)
+        # and u can be C or F, but is only overwritten if Q is C and complex
+        a, q0, r0, u0, v0 = self.generate('sqr', p=3)
+        a1 = a + np.dot(u0, v0.T.conj())
+        q = q0.copy('F')
+        r = r0.copy('F')
+        u = u0.copy('F')
+        v = v0.copy('C')
+
+        # don't overwrite
+        q1, r1 = qr_update(q, r, u, v, False)
+        check_qr(q1, r1, a1, self.rtol, self.atol)
+        check_qr(q, r, a, self.rtol, self.atol)
+
+        q2, r2 = qr_update(q, r, u, v, True)
+        check_qr(q2, r2, a1, self.rtol, self.atol)
+        # verify the overwriting, no good way to check u and v.
+        assert_allclose(q2, q, rtol=self.rtol, atol=self.atol)
+        assert_allclose(r2, r, rtol=self.rtol, atol=self.atol)
+
+    def test_empty_inputs(self):
+        a, q, r, u, v = self.generate('tall')
+        assert_raises(ValueError, qr_update, np.array([]), r, u, v)
+        assert_raises(ValueError, qr_update, q, np.array([]), u, v)
+        assert_raises(ValueError, qr_update, q, r, np.array([]), v)
+        assert_raises(ValueError, qr_update, q, r, u, np.array([]))
+
+    def test_mismatched_shapes(self):
+        a, q, r, u, v = self.generate('tall')
+        assert_raises(ValueError, qr_update, q, r[1:], u, v)
+        assert_raises(ValueError, qr_update, q[:-2], r, u, v)
+        assert_raises(ValueError, qr_update, q, r, u[1:], v)
+        assert_raises(ValueError, qr_update, q, r, u, v[1:])
+
+    def test_unsupported_dtypes(self):
+        dts = ['int8', 'int16', 'int32', 'int64',
+               'uint8', 'uint16', 'uint32', 'uint64',
+               'float16', 'longdouble', 'clongdouble',
+               'bool']
+        a, q0, r0, u0, v0 = self.generate('tall')
+        for dtype in dts:
+            q = q0.real.astype(dtype)
+            with np.errstate(invalid="ignore"):
+                r = r0.real.astype(dtype)
+            u = u0.real.astype(dtype)
+            v = v0.real.astype(dtype)
+            assert_raises(ValueError, qr_update, q, r0, u0, v0)
+            assert_raises(ValueError, qr_update, q0, r, u0, v0)
+            assert_raises(ValueError, qr_update, q0, r0, u, v0)
+            assert_raises(ValueError, qr_update, q0, r0, u0, v)
+
+    def test_integer_input(self):
+        q = np.arange(16).reshape(4, 4)
+        r = q.copy()  # doesn't matter
+        u = q[:, 0].copy()
+        v = r[0, :].copy()
+        assert_raises(ValueError, qr_update, q, r, u, v)
+
+    def test_check_finite(self):
+        a0, q0, r0, u0, v0 = self.generate('tall', p=3)
+
+        q = q0.copy('F')
+        q[1,1] = np.nan
+        assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q, r0, u0, v0)
+
+        r = r0.copy('F')
+        r[1,1] = np.nan
+        assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q0, r, u0, v0)
+
+        u = u0.copy('F')
+        u[0,0] = np.nan
+        assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q0, r0, u, v0)
+
+        v = v0.copy('F')
+        v[0,0] = np.nan
+        assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
+        assert_raises(ValueError, qr_update, q0, r0, u, v)
+
+    def test_economic_check_finite(self):
+        a0, q0, r0, u0, v0 = self.generate('tall', mode='economic', p=3)
+
+        q = q0.copy('F')
+        q[1,1] = np.nan
+        assert_raises(ValueError, qr_update, q, r0, u0[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q, r0, u0, v0)
+
+        r = r0.copy('F')
+        r[1,1] = np.nan
+        assert_raises(ValueError, qr_update, q0, r, u0[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q0, r, u0, v0)
+
+        u = u0.copy('F')
+        u[0,0] = np.nan
+        assert_raises(ValueError, qr_update, q0, r0, u[:,0], v0[:,0])
+        assert_raises(ValueError, qr_update, q0, r0, u, v0)
+
+        v = v0.copy('F')
+        v[0,0] = np.nan
+        assert_raises(ValueError, qr_update, q0, r0, u[:,0], v[:,0])
+        assert_raises(ValueError, qr_update, q0, r0, u, v)
+
+    def test_u_exactly_in_span_q(self):
+        q = np.array([[0, 0], [0, 0], [1, 0], [0, 1]], self.dtype)
+        r = np.array([[1, 0], [0, 1]], self.dtype)
+        u = np.array([0, 0, 0, -1], self.dtype)
+        v = np.array([1, 2], self.dtype)
+        q1, r1 = qr_update(q, r, u, v)
+        a1 = np.dot(q, r) + np.outer(u, v.conj())
+        check_qr(q1, r1, a1, self.rtol, self.atol, False)
+
+class TestQRupdate_f(BaseQRupdate):
+    dtype = np.dtype('f')
+
+class TestQRupdate_F(BaseQRupdate):
+    dtype = np.dtype('F')
+
+class TestQRupdate_d(BaseQRupdate):
+    dtype = np.dtype('d')
+
+class TestQRupdate_D(BaseQRupdate):
+    dtype = np.dtype('D')
+
+def test_form_qTu():
+    # We want to ensure that all of the code paths through this function are
+    # tested. Most of them should be hit with the rest of test suite, but
+    # explicit tests make clear precisely what is being tested.
+    #
+    # This function expects that Q is either C or F contiguous and square.
+    # Economic mode decompositions (Q is (M, N), M != N) do not go through this
+    # function. U may have any positive strides.
+    #
+    # Some of these test are duplicates, since contiguous 1d arrays are both C
+    # and F.
+
+    q_order = ['F', 'C']
+    q_shape = [(8, 8), ]
+    u_order = ['F', 'C', 'A']  # here A means is not F not C
+    u_shape = [1, 3]
+    dtype = ['f', 'd', 'F', 'D']
+
+    for qo, qs, uo, us, d in \
+            itertools.product(q_order, q_shape, u_order, u_shape, dtype):
+        if us == 1:
+            check_form_qTu(qo, qs, uo, us, 1, d)
+            check_form_qTu(qo, qs, uo, us, 2, d)
+        else:
+            check_form_qTu(qo, qs, uo, us, 2, d)
+
+def check_form_qTu(q_order, q_shape, u_order, u_shape, u_ndim, dtype):
+    np.random.seed(47)
+    if u_shape == 1 and u_ndim == 1:
+        u_shape = (q_shape[0],)
+    else:
+        u_shape = (q_shape[0], u_shape)
+    dtype = np.dtype(dtype)
+
+    if dtype.char in 'fd':
+        q = np.random.random(q_shape)
+        u = np.random.random(u_shape)
+    elif dtype.char in 'FD':
+        q = np.random.random(q_shape) + 1j*np.random.random(q_shape)
+        u = np.random.random(u_shape) + 1j*np.random.random(u_shape)
+    else:
+        ValueError("form_qTu doesn't support this dtype")
+
+    q = np.require(q, dtype, q_order)
+    if u_order != 'A':
+        u = np.require(u, dtype, u_order)
+    else:
+        u, = make_strided((u.astype(dtype),))
+
+    rtol = 10.0 ** -(np.finfo(dtype).precision-2)
+    atol = 2*np.finfo(dtype).eps
+
+    expected = np.dot(q.T.conj(), u)
+    res = _decomp_update._form_qTu(q, u)
+    assert_allclose(res, expected, rtol=rtol, atol=atol)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..36e4692cd9717a221cc683a663e8ee23a81aa5b6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_extending.py
@@ -0,0 +1,46 @@
+import os
+import platform
+import sysconfig
+
+import numpy as np
+import pytest
+
+from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython
+from scipy.linalg.blas import cdotu  # type: ignore[attr-defined]
+from scipy.linalg.lapack import dgtsv  # type: ignore[attr-defined]
+
+
+@pytest.mark.fail_slow(120)
+# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247
+@pytest.mark.skipif(IS_EDITABLE,
+                    reason='Editable install cannot find .pxd headers.')
+@pytest.mark.skipif((platform.system() == 'Windows' and
+                     sysconfig.get_config_var('Py_GIL_DISABLED')),
+                    reason='gh-22039')
+@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"],
+                    reason="Can't start subprocess")
+@pytest.mark.skipif(cython is None, reason="requires cython")
+def test_cython(tmp_path):
+    srcdir = os.path.dirname(os.path.dirname(__file__))
+    extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir)
+    # actually test the cython c-extensions
+    a = np.ones(8) * 3
+    b = np.ones(9)
+    c = np.ones(8) * 4
+    x = np.ones(9)
+    _, _, _, x, _ = dgtsv(a, b, c, x)
+    a = np.ones(8) * 3
+    b = np.ones(9)
+    c = np.ones(8) * 4
+    x_c = np.ones(9)
+    extensions.tridiag(a, b, c, x_c)
+    a = np.ones(8) * 3
+    b = np.ones(9)
+    c = np.ones(8) * 4
+    x_cpp = np.ones(9)
+    extensions_cpp.tridiag(a, b, c, x_cpp)
+    np.testing.assert_array_equal(x, x_cpp)
+    cx = np.array([1-1j, 2+2j, 3-3j], dtype=np.complex64)
+    cy = np.array([4+4j, 5-5j, 6+6j], dtype=np.complex64)
+    np.testing.assert_array_equal(cdotu(cx, cy), extensions.complex_dot(cx, cy))
+    np.testing.assert_array_equal(cdotu(cx, cy), extensions_cpp.complex_dot(cx, cy))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c5ada830043af0eecb6d04bf39aef13d29d777c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_fblas.py
@@ -0,0 +1,607 @@
+# Test interfaces to fortran blas.
+#
+# The tests are more of interface than they are of the underlying blas.
+# Only very small matrices checked -- N=3 or so.
+#
+# !! Complex calculations really aren't checked that carefully.
+# !! Only real valued complex numbers are used in tests.
+
+from numpy import float32, float64, complex64, complex128, arange, array, \
+                  zeros, shape, transpose, newaxis, common_type, conjugate
+
+from scipy.linalg import _fblas as fblas
+
+from numpy.testing import assert_array_equal, \
+    assert_allclose, assert_array_almost_equal, assert_
+
+import pytest
+
+# decimal accuracy to require between Python and LAPACK/BLAS calculations
+accuracy = 5
+
+# Since numpy.dot likely uses the same blas, use this routine
+# to check.
+
+
+def matrixmultiply(a, b):
+    if len(b.shape) == 1:
+        b_is_vector = True
+        b = b[:, newaxis]
+    else:
+        b_is_vector = False
+    assert_(a.shape[1] == b.shape[0])
+    c = zeros((a.shape[0], b.shape[1]), common_type(a, b))
+    for i in range(a.shape[0]):
+        for j in range(b.shape[1]):
+            s = 0
+            for k in range(a.shape[1]):
+                s += a[i, k] * b[k, j]
+            c[i, j] = s
+    if b_is_vector:
+        c = c.reshape((a.shape[0],))
+    return c
+
+##################################################
+# Test blas ?axpy
+
+
+class BaseAxpy:
+    ''' Mixin class for axpy tests '''
+
+    def test_default_a(self):
+        x = arange(3., dtype=self.dtype)
+        y = arange(3., dtype=x.dtype)
+        real_y = x*1.+y
+        y = self.blas_func(x, y)
+        assert_array_equal(real_y, y)
+
+    def test_simple(self):
+        x = arange(3., dtype=self.dtype)
+        y = arange(3., dtype=x.dtype)
+        real_y = x*3.+y
+        y = self.blas_func(x, y, a=3.)
+        assert_array_equal(real_y, y)
+
+    def test_x_stride(self):
+        x = arange(6., dtype=self.dtype)
+        y = zeros(3, x.dtype)
+        y = arange(3., dtype=x.dtype)
+        real_y = x[::2]*3.+y
+        y = self.blas_func(x, y, a=3., n=3, incx=2)
+        assert_array_equal(real_y, y)
+
+    def test_y_stride(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        real_y = x*3.+y[::2]
+        y = self.blas_func(x, y, a=3., n=3, incy=2)
+        assert_array_equal(real_y, y[::2])
+
+    def test_x_and_y_stride(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        real_y = x[::4]*3.+y[::2]
+        y = self.blas_func(x, y, a=3., n=3, incx=4, incy=2)
+        assert_array_equal(real_y, y[::2])
+
+    def test_x_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=4, incx=5)
+
+    def test_y_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=3, incy=5)
+
+
+try:
+    class TestSaxpy(BaseAxpy):
+        blas_func = fblas.saxpy
+        dtype = float32
+except AttributeError:
+    class TestSaxpy:
+        pass
+
+
+class TestDaxpy(BaseAxpy):
+    blas_func = fblas.daxpy
+    dtype = float64
+
+
+try:
+    class TestCaxpy(BaseAxpy):
+        blas_func = fblas.caxpy
+        dtype = complex64
+except AttributeError:
+    class TestCaxpy:
+        pass
+
+
+class TestZaxpy(BaseAxpy):
+    blas_func = fblas.zaxpy
+    dtype = complex128
+
+
+##################################################
+# Test blas ?scal
+
+class BaseScal:
+    ''' Mixin class for scal testing '''
+
+    def test_simple(self):
+        x = arange(3., dtype=self.dtype)
+        real_x = x*3.
+        x = self.blas_func(3., x)
+        assert_array_equal(real_x, x)
+
+    def test_x_stride(self):
+        x = arange(6., dtype=self.dtype)
+        real_x = x.copy()
+        real_x[::2] = x[::2]*array(3., self.dtype)
+        x = self.blas_func(3., x, n=3, incx=2)
+        assert_array_equal(real_x, x)
+
+    def test_x_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(2., x, n=4, incx=5)
+
+
+try:
+    class TestSscal(BaseScal):
+        blas_func = fblas.sscal
+        dtype = float32
+except AttributeError:
+    class TestSscal:
+        pass
+
+
+class TestDscal(BaseScal):
+    blas_func = fblas.dscal
+    dtype = float64
+
+
+try:
+    class TestCscal(BaseScal):
+        blas_func = fblas.cscal
+        dtype = complex64
+except AttributeError:
+    class TestCscal:
+        pass
+
+
+class TestZscal(BaseScal):
+    blas_func = fblas.zscal
+    dtype = complex128
+
+
+##################################################
+# Test blas ?copy
+
+class BaseCopy:
+    ''' Mixin class for copy testing '''
+
+    def test_simple(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(shape(x), x.dtype)
+        y = self.blas_func(x, y)
+        assert_array_equal(x, y)
+
+    def test_x_stride(self):
+        x = arange(6., dtype=self.dtype)
+        y = zeros(3, x.dtype)
+        y = self.blas_func(x, y, n=3, incx=2)
+        assert_array_equal(x[::2], y)
+
+    def test_y_stride(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        y = self.blas_func(x, y, n=3, incy=2)
+        assert_array_equal(x, y[::2])
+
+    def test_x_and_y_stride(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        y = self.blas_func(x, y, n=3, incx=4, incy=2)
+        assert_array_equal(x[::4], y[::2])
+
+    def test_x_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=4, incx=5)
+
+    def test_y_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=3, incy=5)
+
+    # def test_y_bad_type(self):
+    ##   Hmmm. Should this work?  What should be the output.
+    #    x = arange(3.,dtype=self.dtype)
+    #    y = zeros(shape(x))
+    #    self.blas_func(x,y)
+    #    assert_array_equal(x,y)
+
+
+try:
+    class TestScopy(BaseCopy):
+        blas_func = fblas.scopy
+        dtype = float32
+except AttributeError:
+    class TestScopy:
+        pass
+
+
+class TestDcopy(BaseCopy):
+    blas_func = fblas.dcopy
+    dtype = float64
+
+
+try:
+    class TestCcopy(BaseCopy):
+        blas_func = fblas.ccopy
+        dtype = complex64
+except AttributeError:
+    class TestCcopy:
+        pass
+
+
+class TestZcopy(BaseCopy):
+    blas_func = fblas.zcopy
+    dtype = complex128
+
+
+##################################################
+# Test blas ?swap
+
+class BaseSwap:
+    ''' Mixin class for swap tests '''
+
+    def test_simple(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(shape(x), x.dtype)
+        desired_x = y.copy()
+        desired_y = x.copy()
+        x, y = self.blas_func(x, y)
+        assert_array_equal(desired_x, x)
+        assert_array_equal(desired_y, y)
+
+    def test_x_stride(self):
+        x = arange(6., dtype=self.dtype)
+        y = zeros(3, x.dtype)
+        desired_x = y.copy()
+        desired_y = x.copy()[::2]
+        x, y = self.blas_func(x, y, n=3, incx=2)
+        assert_array_equal(desired_x, x[::2])
+        assert_array_equal(desired_y, y)
+
+    def test_y_stride(self):
+        x = arange(3., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        desired_x = y.copy()[::2]
+        desired_y = x.copy()
+        x, y = self.blas_func(x, y, n=3, incy=2)
+        assert_array_equal(desired_x, x)
+        assert_array_equal(desired_y, y[::2])
+
+    def test_x_and_y_stride(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        desired_x = y.copy()[::2]
+        desired_y = x.copy()[::4]
+        x, y = self.blas_func(x, y, n=3, incx=4, incy=2)
+        assert_array_equal(desired_x, x[::4])
+        assert_array_equal(desired_y, y[::2])
+
+    def test_x_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=4, incx=5)
+
+    def test_y_bad_size(self):
+        x = arange(12., dtype=self.dtype)
+        y = zeros(6, x.dtype)
+        with pytest.raises(Exception, match='failed for 1st keyword'):
+            self.blas_func(x, y, n=3, incy=5)
+
+
+try:
+    class TestSswap(BaseSwap):
+        blas_func = fblas.sswap
+        dtype = float32
+except AttributeError:
+    class TestSswap:
+        pass
+
+
+class TestDswap(BaseSwap):
+    blas_func = fblas.dswap
+    dtype = float64
+
+
+try:
+    class TestCswap(BaseSwap):
+        blas_func = fblas.cswap
+        dtype = complex64
+except AttributeError:
+    class TestCswap:
+        pass
+
+
+class TestZswap(BaseSwap):
+    blas_func = fblas.zswap
+    dtype = complex128
+
+##################################################
+# Test blas ?gemv
+# This will be a mess to test all cases.
+
+
+class BaseGemv:
+    ''' Mixin class for gemv tests '''
+
+    def get_data(self, x_stride=1, y_stride=1):
+        mult = array(1, dtype=self.dtype)
+        if self.dtype in [complex64, complex128]:
+            mult = array(1+1j, dtype=self.dtype)
+        from numpy.random import normal, seed
+        seed(1234)
+        alpha = array(1., dtype=self.dtype) * mult
+        beta = array(1., dtype=self.dtype) * mult
+        a = normal(0., 1., (3, 3)).astype(self.dtype) * mult
+        x = arange(shape(a)[0]*x_stride, dtype=self.dtype) * mult
+        y = arange(shape(a)[1]*y_stride, dtype=self.dtype) * mult
+        return alpha, beta, a, x, y
+
+    def test_simple(self):
+        alpha, beta, a, x, y = self.get_data()
+        desired_y = alpha*matrixmultiply(a, x)+beta*y
+        y = self.blas_func(alpha, a, x, beta, y)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_default_beta_y(self):
+        alpha, beta, a, x, y = self.get_data()
+        desired_y = matrixmultiply(a, x)
+        y = self.blas_func(1, a, x)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_simple_transpose(self):
+        alpha, beta, a, x, y = self.get_data()
+        desired_y = alpha*matrixmultiply(transpose(a), x)+beta*y
+        y = self.blas_func(alpha, a, x, beta, y, trans=1)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_simple_transpose_conj(self):
+        alpha, beta, a, x, y = self.get_data()
+        desired_y = alpha*matrixmultiply(transpose(conjugate(a)), x)+beta*y
+        y = self.blas_func(alpha, a, x, beta, y, trans=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_x_stride(self):
+        alpha, beta, a, x, y = self.get_data(x_stride=2)
+        desired_y = alpha*matrixmultiply(a, x[::2])+beta*y
+        y = self.blas_func(alpha, a, x, beta, y, incx=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_x_stride_transpose(self):
+        alpha, beta, a, x, y = self.get_data(x_stride=2)
+        desired_y = alpha*matrixmultiply(transpose(a), x[::2])+beta*y
+        y = self.blas_func(alpha, a, x, beta, y, trans=1, incx=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_x_stride_assert(self):
+        # What is the use of this test?
+        alpha, beta, a, x, y = self.get_data(x_stride=2)
+        with pytest.raises(Exception, match='failed for 3rd argument'):
+            y = self.blas_func(1, a, x, 1, y, trans=0, incx=3)
+        with pytest.raises(Exception, match='failed for 3rd argument'):
+            y = self.blas_func(1, a, x, 1, y, trans=1, incx=3)
+
+    def test_y_stride(self):
+        alpha, beta, a, x, y = self.get_data(y_stride=2)
+        desired_y = y.copy()
+        desired_y[::2] = alpha*matrixmultiply(a, x)+beta*y[::2]
+        y = self.blas_func(alpha, a, x, beta, y, incy=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_y_stride_transpose(self):
+        alpha, beta, a, x, y = self.get_data(y_stride=2)
+        desired_y = y.copy()
+        desired_y[::2] = alpha*matrixmultiply(transpose(a), x)+beta*y[::2]
+        y = self.blas_func(alpha, a, x, beta, y, trans=1, incy=2)
+        assert_array_almost_equal(desired_y, y)
+
+    def test_y_stride_assert(self):
+        # What is the use of this test?
+        alpha, beta, a, x, y = self.get_data(y_stride=2)
+        with pytest.raises(Exception, match='failed for 2nd keyword'):
+            y = self.blas_func(1, a, x, 1, y, trans=0, incy=3)
+        with pytest.raises(Exception, match='failed for 2nd keyword'):
+            y = self.blas_func(1, a, x, 1, y, trans=1, incy=3)
+
+
+try:
+    class TestSgemv(BaseGemv):
+        blas_func = fblas.sgemv
+        dtype = float32
+
+        def test_sgemv_on_osx(self):
+            from itertools import product
+            import sys
+            import numpy as np
+
+            if sys.platform != 'darwin':
+                return
+
+            def aligned_array(shape, align, dtype, order='C'):
+                # Make array shape `shape` with aligned at `align` bytes
+                d = dtype()
+                # Make array of correct size with `align` extra bytes
+                N = np.prod(shape)
+                tmp = np.zeros(N * d.nbytes + align, dtype=np.uint8)
+                address = tmp.__array_interface__["data"][0]
+                # Find offset into array giving desired alignment
+                for offset in range(align):
+                    if (address + offset) % align == 0:
+                        break
+                tmp = tmp[offset:offset+N*d.nbytes].view(dtype=dtype)
+                return tmp.reshape(shape, order=order)
+
+            def as_aligned(arr, align, dtype, order='C'):
+                # Copy `arr` into an aligned array with same shape
+                aligned = aligned_array(arr.shape, align, dtype, order)
+                aligned[:] = arr[:]
+                return aligned
+
+            def assert_dot_close(A, X, desired):
+                assert_allclose(self.blas_func(1.0, A, X), desired,
+                                rtol=1e-5, atol=1e-7)
+
+            testdata = product((15, 32), (10000,), (200, 89), ('C', 'F'))
+            for align, m, n, a_order in testdata:
+                A_d = np.random.rand(m, n)
+                X_d = np.random.rand(n)
+                desired = np.dot(A_d, X_d)
+                # Calculation with aligned single precision
+                A_f = as_aligned(A_d, align, np.float32, order=a_order)
+                X_f = as_aligned(X_d, align, np.float32, order=a_order)
+                assert_dot_close(A_f, X_f, desired)
+
+except AttributeError:
+    class TestSgemv:
+        pass
+
+
+class TestDgemv(BaseGemv):
+    blas_func = fblas.dgemv
+    dtype = float64
+
+
+try:
+    class TestCgemv(BaseGemv):
+        blas_func = fblas.cgemv
+        dtype = complex64
+except AttributeError:
+    class TestCgemv:
+        pass
+
+
+class TestZgemv(BaseGemv):
+    blas_func = fblas.zgemv
+    dtype = complex128
+
+
+"""
+##################################################
+### Test blas ?ger
+### This will be a mess to test all cases.
+
+class BaseGer:
+    def get_data(self,x_stride=1,y_stride=1):
+        from numpy.random import normal, seed
+        seed(1234)
+        alpha = array(1., dtype = self.dtype)
+        a = normal(0.,1.,(3,3)).astype(self.dtype)
+        x = arange(shape(a)[0]*x_stride,dtype=self.dtype)
+        y = arange(shape(a)[1]*y_stride,dtype=self.dtype)
+        return alpha,a,x,y
+    def test_simple(self):
+        alpha,a,x,y = self.get_data()
+        # transpose takes care of Fortran vs. C(and Python) memory layout
+        desired_a = alpha*transpose(x[:,newaxis]*y) + a
+        self.blas_func(x,y,a)
+        assert_array_almost_equal(desired_a,a)
+    def test_x_stride(self):
+        alpha,a,x,y = self.get_data(x_stride=2)
+        desired_a = alpha*transpose(x[::2,newaxis]*y) + a
+        self.blas_func(x,y,a,incx=2)
+        assert_array_almost_equal(desired_a,a)
+    def test_x_stride_assert(self):
+        alpha,a,x,y = self.get_data(x_stride=2)
+        with pytest.raises(ValueError, match='foo'):
+            self.blas_func(x,y,a,incx=3)
+    def test_y_stride(self):
+        alpha,a,x,y = self.get_data(y_stride=2)
+        desired_a = alpha*transpose(x[:,newaxis]*y[::2]) + a
+        self.blas_func(x,y,a,incy=2)
+        assert_array_almost_equal(desired_a,a)
+
+    def test_y_stride_assert(self):
+        alpha,a,x,y = self.get_data(y_stride=2)
+        with pytest.raises(ValueError, match='foo'):
+            self.blas_func(a,x,y,incy=3)
+
+class TestSger(BaseGer):
+    blas_func = fblas.sger
+    dtype = float32
+class TestDger(BaseGer):
+    blas_func = fblas.dger
+    dtype = float64
+"""
+##################################################
+# Test blas ?gerc
+# This will be a mess to test all cases.
+
+"""
+class BaseGerComplex(BaseGer):
+    def get_data(self,x_stride=1,y_stride=1):
+        from numpy.random import normal, seed
+        seed(1234)
+        alpha = array(1+1j, dtype = self.dtype)
+        a = normal(0.,1.,(3,3)).astype(self.dtype)
+        a = a + normal(0.,1.,(3,3)) * array(1j, dtype = self.dtype)
+        x = normal(0.,1.,shape(a)[0]*x_stride).astype(self.dtype)
+        x = x + x * array(1j, dtype = self.dtype)
+        y = normal(0.,1.,shape(a)[1]*y_stride).astype(self.dtype)
+        y = y + y * array(1j, dtype = self.dtype)
+        return alpha,a,x,y
+    def test_simple(self):
+        alpha,a,x,y = self.get_data()
+        # transpose takes care of Fortran vs. C(and Python) memory layout
+        a = a * array(0.,dtype = self.dtype)
+        #desired_a = alpha*transpose(x[:,newaxis]*self.transform(y)) + a
+        desired_a = alpha*transpose(x[:,newaxis]*y) + a
+        #self.blas_func(x,y,a,alpha = alpha)
+        fblas.cgeru(x,y,a,alpha = alpha)
+        assert_array_almost_equal(desired_a,a)
+
+    #def test_x_stride(self):
+    #    alpha,a,x,y = self.get_data(x_stride=2)
+    #    desired_a = alpha*transpose(x[::2,newaxis]*self.transform(y)) + a
+    #    self.blas_func(x,y,a,incx=2)
+    #    assert_array_almost_equal(desired_a,a)
+    #def test_y_stride(self):
+    #    alpha,a,x,y = self.get_data(y_stride=2)
+    #    desired_a = alpha*transpose(x[:,newaxis]*self.transform(y[::2])) + a
+    #    self.blas_func(x,y,a,incy=2)
+    #    assert_array_almost_equal(desired_a,a)
+
+class TestCgeru(BaseGerComplex):
+    blas_func = fblas.cgeru
+    dtype = complex64
+    def transform(self,x):
+        return x
+class TestZgeru(BaseGerComplex):
+    blas_func = fblas.zgeru
+    dtype = complex128
+    def transform(self,x):
+        return x
+
+class TestCgerc(BaseGerComplex):
+    blas_func = fblas.cgerc
+    dtype = complex64
+    def transform(self,x):
+        return conjugate(x)
+
+class TestZgerc(BaseGerComplex):
+    blas_func = fblas.zgerc
+    dtype = complex128
+    def transform(self,x):
+        return conjugate(x)
+"""
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e1cc5496eafe19ced81ea546e3bad386148ae7b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_interpolative.py
@@ -0,0 +1,232 @@
+#  ******************************************************************************
+#   Copyright (C) 2013 Kenneth L. Ho
+#   Redistribution and use in source and binary forms, with or without
+#   modification, are permitted provided that the following conditions are met:
+#
+#   Redistributions of source code must retain the above copyright notice, this
+#   list of conditions and the following disclaimer. Redistributions in binary
+#   form must reproduce the above copyright notice, this list of conditions and
+#   the following disclaimer in the documentation and/or other materials
+#   provided with the distribution.
+#
+#   None of the names of the copyright holders may be used to endorse or
+#   promote products derived from this software without specific prior written
+#   permission.
+#
+#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+#   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+#   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+#   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+#   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+#   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+#   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+#   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+#   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+#   POSSIBILITY OF SUCH DAMAGE.
+#  ******************************************************************************
+
+import scipy.linalg.interpolative as pymatrixid
+import numpy as np
+from scipy.linalg import hilbert, svdvals, norm
+from scipy.sparse.linalg import aslinearoperator
+from scipy.linalg.interpolative import interp_decomp
+
+from numpy.testing import (assert_, assert_allclose, assert_equal,
+                           assert_array_equal)
+import pytest
+from pytest import raises as assert_raises
+
+
+@pytest.fixture()
+def eps():
+    yield 1e-12
+
+
+@pytest.fixture()
+def rng():
+    rng = np.random.default_rng(1718313768084012)
+    yield rng
+
+
+@pytest.fixture(params=[np.float64, np.complex128])
+def A(request):
+    # construct Hilbert matrix
+    # set parameters
+    n = 300
+    yield hilbert(n).astype(request.param)
+
+
+@pytest.fixture()
+def L(A):
+    yield aslinearoperator(A)
+
+
+@pytest.fixture()
+def rank(A, eps):
+    S = np.linalg.svd(A, compute_uv=False)
+    try:
+        rank = np.nonzero(S < eps)[0][0]
+    except IndexError:
+        rank = A.shape[0]
+    return rank
+
+
+class TestInterpolativeDecomposition:
+
+    @pytest.mark.parametrize(
+        "rand,lin_op",
+        [(False, False), (True, False), (True, True)])
+    def test_real_id_fixed_precision(self, A, L, eps, rand, lin_op, rng):
+        # Test ID routines on a Hilbert matrix.
+        A_or_L = A if not lin_op else L
+
+        k, idx, proj = pymatrixid.interp_decomp(A_or_L, eps, rand=rand, rng=rng)
+        B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj)
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    @pytest.mark.parametrize(
+        "rand,lin_op",
+        [(False, False), (True, False), (True, True)])
+    def test_real_id_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng):
+        k = rank
+        A_or_L = A if not lin_op else L
+
+        idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng)
+        B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj)
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    @pytest.mark.parametrize("rand,lin_op", [(False, False)])
+    def test_real_id_skel_and_interp_matrices(
+            self, A, L, eps, rank, rand, lin_op, rng):
+        k = rank
+        A_or_L = A if not lin_op else L
+
+        idx, proj = pymatrixid.interp_decomp(A_or_L, k, rand=rand, rng=rng)
+        P = pymatrixid.reconstruct_interp_matrix(idx, proj)
+        B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
+        assert_allclose(B, A[:, idx[:k]], rtol=eps, atol=1e-08)
+        assert_allclose(B @ P, A, rtol=eps, atol=1e-08)
+
+    @pytest.mark.parametrize(
+        "rand,lin_op",
+        [(False, False), (True, False), (True, True)])
+    def test_svd_fixed_precision(self, A, L, eps, rand, lin_op, rng):
+        A_or_L = A if not lin_op else L
+
+        U, S, V = pymatrixid.svd(A_or_L, eps, rand=rand, rng=rng)
+        B = U * S @ V.T.conj()
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    @pytest.mark.parametrize(
+        "rand,lin_op",
+        [(False, False), (True, False), (True, True)])
+    def test_svd_fixed_rank(self, A, L, eps, rank, rand, lin_op, rng):
+        k = rank
+        A_or_L = A if not lin_op else L
+
+        U, S, V = pymatrixid.svd(A_or_L, k, rand=rand, rng=rng)
+        B = U * S @ V.T.conj()
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    def test_id_to_svd(self, A, eps, rank):
+        k = rank
+
+        idx, proj = pymatrixid.interp_decomp(A, k, rand=False)
+        U, S, V = pymatrixid.id_to_svd(A[:, idx[:k]], idx, proj)
+        B = U * S @ V.T.conj()
+        assert_allclose(A, B, rtol=eps, atol=1e-08)
+
+    def test_estimate_spectral_norm(self, A, rng):
+        s = svdvals(A)
+        norm_2_est = pymatrixid.estimate_spectral_norm(A, rng=rng)
+        assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
+
+    def test_estimate_spectral_norm_diff(self, A, rng):
+        B = A.copy()
+        B[:, 0] *= 1.2
+        s = svdvals(A - B)
+        norm_2_est = pymatrixid.estimate_spectral_norm_diff(A, B, rng=rng)
+        assert_allclose(norm_2_est, s[0], rtol=1e-6, atol=1e-8)
+
+    def test_rank_estimates_array(self, A, rng):
+        B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
+
+        for M in [A, B]:
+            rank_tol = 1e-9
+            rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol)
+            rank_est = pymatrixid.estimate_rank(M, rank_tol, rng=rng)
+            assert_(rank_est >= rank_np)
+            assert_(rank_est <= rank_np + 10)
+
+    def test_rank_estimates_lin_op(self, A, rng):
+        B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=A.dtype)
+
+        for M in [A, B]:
+            ML = aslinearoperator(M)
+            rank_tol = 1e-9
+            rank_np = np.linalg.matrix_rank(M, norm(M, 2) * rank_tol)
+            rank_est = pymatrixid.estimate_rank(ML, rank_tol, rng=rng)
+            assert_(rank_est >= rank_np - 4)
+            assert_(rank_est <= rank_np + 4)
+
+    def test_badcall(self):
+        A = hilbert(5).astype(np.float32)
+        with assert_raises(ValueError):
+            pymatrixid.interp_decomp(A, 1e-6, rand=False)
+
+    def test_rank_too_large(self):
+        # svd(array, k) should not segfault
+        a = np.ones((4, 3))
+        with assert_raises(ValueError):
+            pymatrixid.svd(a, 4)
+
+    def test_full_rank(self):
+        eps = 1.0e-12
+
+        # fixed precision
+        A = np.random.rand(16, 8)
+        k, idx, proj = pymatrixid.interp_decomp(A, eps)
+        assert_equal(k, A.shape[1])
+
+        P = pymatrixid.reconstruct_interp_matrix(idx, proj)
+        B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
+        assert_allclose(A, B @ P)
+
+        # fixed rank
+        idx, proj = pymatrixid.interp_decomp(A, k)
+
+        P = pymatrixid.reconstruct_interp_matrix(idx, proj)
+        B = pymatrixid.reconstruct_skel_matrix(A, k, idx)
+        assert_allclose(A, B @ P)
+
+    @pytest.mark.parametrize("dtype", [np.float64, np.complex128])
+    @pytest.mark.parametrize("rand", [True, False])
+    @pytest.mark.parametrize("eps", [1, 0.1])
+    def test_bug_9793(self, dtype, rand, eps):
+        A = np.array([[-1, -1, -1, 0, 0, 0],
+                      [0, 0, 0, 1, 1, 1],
+                      [1, 0, 0, 1, 0, 0],
+                      [0, 1, 0, 0, 1, 0],
+                      [0, 0, 1, 0, 0, 1]],
+                     dtype=dtype, order="C")
+        B = A.copy()
+        interp_decomp(A.T, eps, rand=rand)
+        assert_array_equal(A, B)
+
+    def test_svd_aslinearoperator_shape_check(self):
+        # See gh-issue #22451
+        rng = np.random.default_rng(1744580941832515)
+        x = rng.uniform(size=[7, 5])
+        xl = aslinearoperator(x)
+        u, s, v = pymatrixid.svd(xl, 3)
+        assert_equal(u.shape, (7, 3))
+        assert_equal(s.shape, (3,))
+        assert_equal(v.shape, (5, 3))
+
+        x = rng.uniform(size=[4, 9])
+        xl = aslinearoperator(x)
+        u, s, v = pymatrixid.svd(xl, 2)
+        assert_equal(u.shape, (4, 2))
+        assert_equal(s.shape, (2,))
+        assert_equal(v.shape, (9, 2))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py
new file mode 100644
index 0000000000000000000000000000000000000000..86555d6c19916c8ae1f6a796fb009a6b803b2159
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_lapack.py
@@ -0,0 +1,3508 @@
+#
+# Created by: Pearu Peterson, September 2002
+#
+
+from functools import reduce
+import random
+
+from numpy.testing import (assert_equal, assert_array_almost_equal, assert_,
+                           assert_allclose, assert_almost_equal,
+                           assert_array_equal)
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from numpy import (eye, ones, zeros, zeros_like, triu, tril, tril_indices,
+                   triu_indices)
+
+from numpy.random import rand, randint, seed
+
+from scipy.linalg import (_flapack as flapack, lapack, inv, svd, cholesky,
+                          solve, ldl, norm, block_diag, qr, eigh, qz)
+
+from scipy.linalg.lapack import _compute_lwork
+from scipy.stats import ortho_group, unitary_group
+
+import scipy.sparse as sps
+try:
+    from scipy.__config__ import CONFIG
+except ImportError:
+    CONFIG = None
+
+try:
+    from scipy.linalg import _clapack as clapack
+except ImportError:
+    clapack = None
+from scipy.linalg.lapack import get_lapack_funcs
+from scipy.linalg.blas import get_blas_funcs
+
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+blas_provider = blas_version = None
+if CONFIG is not None:
+    blas_provider = CONFIG['Build Dependencies']['blas']['name']
+    blas_version = CONFIG['Build Dependencies']['blas']['version']
+
+
+def generate_random_dtype_array(shape, dtype, rng):
+    # generates a random matrix of desired data type of shape
+    if dtype in COMPLEX_DTYPES:
+        return (rng.rand(*shape)
+                + rng.rand(*shape)*1.0j).astype(dtype)
+    return rng.rand(*shape).astype(dtype)
+
+
+def test_lapack_documented():
+    """Test that all entries are in the doc."""
+    if lapack.__doc__ is None:  # just in case there is a python -OO
+        pytest.skip('lapack.__doc__ is None')
+    names = set(lapack.__doc__.split())
+    ignore_list = {
+        "absolute_import",
+        "clapack",
+        "division",
+        "find_best_lapack_type",
+        "flapack",
+        "print_function",
+        "HAS_ILP64",
+        "np",
+    }
+    missing = list()
+    for name in dir(lapack):
+        if (not name.startswith('_') and name not in ignore_list and
+                name not in names):
+            missing.append(name)
+    assert missing == [], 'Name(s) missing from lapack.__doc__ or ignore_list'
+
+
+class TestFlapackSimple:
+
+    def test_gebal(self):
+        a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
+        a1 = [[1, 0, 0, 3e-4],
+              [4, 0, 0, 2e-3],
+              [7, 1, 0, 0],
+              [0, 1, 0, 0]]
+        for p in 'sdzc':
+            f = getattr(flapack, p+'gebal', None)
+            if f is None:
+                continue
+            ba, lo, hi, pivscale, info = f(a)
+            assert_(not info, repr(info))
+            assert_array_almost_equal(ba, a)
+            assert_equal((lo, hi), (0, len(a[0])-1))
+            assert_array_almost_equal(pivscale, np.ones(len(a)))
+
+            ba, lo, hi, pivscale, info = f(a1, permute=1, scale=1)
+            assert_(not info, repr(info))
+            # print(a1)
+            # print(ba, lo, hi, pivscale)
+
+    def test_gehrd(self):
+        a = [[-149, -50, -154],
+             [537, 180, 546],
+             [-27, -9, -25]]
+        for p in 'd':
+            f = getattr(flapack, p+'gehrd', None)
+            if f is None:
+                continue
+            ht, tau, info = f(a)
+            assert_(not info, repr(info))
+
+    def test_trsyl(self):
+        a = np.array([[1, 2], [0, 4]])
+        b = np.array([[5, 6], [0, 8]])
+        c = np.array([[9, 10], [11, 12]])
+        trans = 'T'
+
+        # Test single and double implementations, including most
+        # of the options
+        for dtype in 'fdFD':
+            a1, b1, c1 = a.astype(dtype), b.astype(dtype), c.astype(dtype)
+            trsyl, = get_lapack_funcs(('trsyl',), (a1,))
+            if dtype.isupper():  # is complex dtype
+                a1[0] += 1j
+                trans = 'C'
+
+            x, scale, info = trsyl(a1, b1, c1)
+            assert_array_almost_equal(np.dot(a1, x) + np.dot(x, b1),
+                                      scale * c1)
+
+            x, scale, info = trsyl(a1, b1, c1, trana=trans, tranb=trans)
+            assert_array_almost_equal(
+                    np.dot(a1.conjugate().T, x) + np.dot(x, b1.conjugate().T),
+                    scale * c1, decimal=4)
+
+            x, scale, info = trsyl(a1, b1, c1, isgn=-1)
+            assert_array_almost_equal(np.dot(a1, x) - np.dot(x, b1),
+                                      scale * c1, decimal=4)
+
+    def test_lange(self):
+        a = np.array([
+            [-149, -50, -154],
+            [537, 180, 546],
+            [-27, -9, -25]])
+
+        for dtype in 'fdFD':
+            for norm_str in 'Mm1OoIiFfEe':
+                a1 = a.astype(dtype)
+                if dtype.isupper():
+                    # is complex dtype
+                    a1[0, 0] += 1j
+
+                lange, = get_lapack_funcs(('lange',), (a1,))
+                value = lange(norm_str, a1)
+
+                if norm_str in 'FfEe':
+                    if dtype in 'Ff':
+                        decimal = 3
+                    else:
+                        decimal = 7
+                    ref = np.sqrt(np.sum(np.square(np.abs(a1))))
+                    assert_almost_equal(value, ref, decimal)
+                else:
+                    if norm_str in 'Mm':
+                        ref = np.max(np.abs(a1))
+                    elif norm_str in '1Oo':
+                        ref = np.max(np.sum(np.abs(a1), axis=0))
+                    elif norm_str in 'Ii':
+                        ref = np.max(np.sum(np.abs(a1), axis=1))
+
+                    assert_equal(value, ref)
+
+
+class TestLapack:
+
+    def test_flapack(self):
+        if hasattr(flapack, 'empty_module'):
+            # flapack module is empty
+            pass
+
+    def test_clapack(self):
+        if hasattr(clapack, 'empty_module'):
+            # clapack module is empty
+            pass
+
+
+class TestLeastSquaresSolvers:
+
+    def test_gels(self):
+        seed(1234)
+        # Test fat/tall matrix argument handling - gh-issue #8329
+        for ind, dtype in enumerate(DTYPES):
+            m = 10
+            n = 20
+            nrhs = 1
+            a1 = rand(m, n).astype(dtype)
+            b1 = rand(n).astype(dtype)
+            gls, glslw = get_lapack_funcs(('gels', 'gels_lwork'), dtype=dtype)
+
+            # Request of sizes
+            lwork = _compute_lwork(glslw, m, n, nrhs)
+            _, _, info = gls(a1, b1, lwork=lwork)
+            assert_(info >= 0)
+            _, _, info = gls(a1, b1, trans='TTCC'[ind], lwork=lwork)
+            assert_(info >= 0)
+
+        for dtype in REAL_DTYPES:
+            a1 = np.array([[1.0, 2.0],
+                           [4.0, 5.0],
+                           [7.0, 8.0]], dtype=dtype)
+            b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+            gels, gels_lwork, geqrf = get_lapack_funcs(
+                    ('gels', 'gels_lwork', 'geqrf'), (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            lwork = _compute_lwork(gels_lwork, m, n, nrhs)
+
+            lqr, x, info = gels(a1, b1, lwork=lwork)
+            assert_allclose(x[:-1], np.array([-14.333333333333323,
+                                              14.999999999999991],
+                                             dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+            lqr_truth, _, _, _ = geqrf(a1)
+            assert_array_equal(lqr, lqr_truth)
+
+        for dtype in COMPLEX_DTYPES:
+            a1 = np.array([[1.0+4.0j, 2.0],
+                           [4.0+0.5j, 5.0-3.0j],
+                           [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+            b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+            gels, gels_lwork, geqrf = get_lapack_funcs(
+                    ('gels', 'gels_lwork', 'geqrf'), (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            lwork = _compute_lwork(gels_lwork, m, n, nrhs)
+
+            lqr, x, info = gels(a1, b1, lwork=lwork)
+            assert_allclose(x[:-1],
+                            np.array([1.161753632288328-1.901075709391912j,
+                                      1.735882340522193+1.521240901196909j],
+                                     dtype=dtype), rtol=25*np.finfo(dtype).eps)
+            lqr_truth, _, _, _ = geqrf(a1)
+            assert_array_equal(lqr, lqr_truth)
+
+    def test_gelsd(self):
+        for dtype in REAL_DTYPES:
+            a1 = np.array([[1.0, 2.0],
+                           [4.0, 5.0],
+                           [7.0, 8.0]], dtype=dtype)
+            b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+            gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, iwork, info = gelsd_lwork(m, n, nrhs, -1)
+            lwork = int(np.real(work))
+            iwork_size = iwork
+
+            x, s, rank, info = gelsd(a1, b1, lwork, iwork_size,
+                                     -1, False, False)
+            assert_allclose(x[:-1], np.array([-14.333333333333323,
+                                              14.999999999999991],
+                                             dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+            assert_allclose(s, np.array([12.596017180511966,
+                                         0.583396253199685], dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+        for dtype in COMPLEX_DTYPES:
+            a1 = np.array([[1.0+4.0j, 2.0],
+                           [4.0+0.5j, 5.0-3.0j],
+                           [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+            b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+            gelsd, gelsd_lwork = get_lapack_funcs(('gelsd', 'gelsd_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, rwork, iwork, info = gelsd_lwork(m, n, nrhs, -1)
+            lwork = int(np.real(work))
+            rwork_size = int(rwork)
+            iwork_size = iwork
+
+            x, s, rank, info = gelsd(a1, b1, lwork, rwork_size, iwork_size,
+                                     -1, False, False)
+            assert_allclose(x[:-1],
+                            np.array([1.161753632288328-1.901075709391912j,
+                                      1.735882340522193+1.521240901196909j],
+                                     dtype=dtype), rtol=25*np.finfo(dtype).eps)
+            assert_allclose(s,
+                            np.array([13.035514762572043, 4.337666985231382],
+                                     dtype=dtype), rtol=25*np.finfo(dtype).eps)
+
+    def test_gelss(self):
+
+        for dtype in REAL_DTYPES:
+            a1 = np.array([[1.0, 2.0],
+                           [4.0, 5.0],
+                           [7.0, 8.0]], dtype=dtype)
+            b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+            gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, info = gelss_lwork(m, n, nrhs, -1)
+            lwork = int(np.real(work))
+
+            v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False)
+            assert_allclose(x[:-1], np.array([-14.333333333333323,
+                                              14.999999999999991],
+                                             dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+            assert_allclose(s, np.array([12.596017180511966,
+                                         0.583396253199685], dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+        for dtype in COMPLEX_DTYPES:
+            a1 = np.array([[1.0+4.0j, 2.0],
+                           [4.0+0.5j, 5.0-3.0j],
+                           [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+            b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+            gelss, gelss_lwork = get_lapack_funcs(('gelss', 'gelss_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, info = gelss_lwork(m, n, nrhs, -1)
+            lwork = int(np.real(work))
+
+            v, x, s, rank, work, info = gelss(a1, b1, -1, lwork, False, False)
+            assert_allclose(x[:-1],
+                            np.array([1.161753632288328-1.901075709391912j,
+                                      1.735882340522193+1.521240901196909j],
+                                     dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+            assert_allclose(s, np.array([13.035514762572043,
+                                         4.337666985231382], dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+    def test_gelsy(self):
+
+        for dtype in REAL_DTYPES:
+            a1 = np.array([[1.0, 2.0],
+                           [4.0, 5.0],
+                           [7.0, 8.0]], dtype=dtype)
+            b1 = np.array([16.0, 17.0, 20.0], dtype=dtype)
+            gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps)
+            lwork = int(np.real(work))
+
+            jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
+            v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps,
+                                        lwork, False, False)
+            assert_allclose(x[:-1], np.array([-14.333333333333323,
+                                              14.999999999999991],
+                                             dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+        for dtype in COMPLEX_DTYPES:
+            a1 = np.array([[1.0+4.0j, 2.0],
+                           [4.0+0.5j, 5.0-3.0j],
+                           [7.0-2.0j, 8.0+0.7j]], dtype=dtype)
+            b1 = np.array([16.0, 17.0+2.0j, 20.0-4.0j], dtype=dtype)
+            gelsy, gelsy_lwork = get_lapack_funcs(('gelsy', 'gelss_lwork'),
+                                                  (a1, b1))
+
+            m, n = a1.shape
+            if len(b1.shape) == 2:
+                nrhs = b1.shape[1]
+            else:
+                nrhs = 1
+
+            # Request of sizes
+            work, info = gelsy_lwork(m, n, nrhs, 10*np.finfo(dtype).eps)
+            lwork = int(np.real(work))
+
+            jptv = np.zeros((a1.shape[1], 1), dtype=np.int32)
+            v, x, j, rank, info = gelsy(a1, b1, jptv, np.finfo(dtype).eps,
+                                        lwork, False, False)
+            assert_allclose(x[:-1],
+                            np.array([1.161753632288328-1.901075709391912j,
+                                      1.735882340522193+1.521240901196909j],
+                                     dtype=dtype),
+                            rtol=25*np.finfo(dtype).eps)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('shape', [(3, 4), (5, 2), (2**18, 2**18)])
+def test_geqrf_lwork(dtype, shape):
+    geqrf_lwork = get_lapack_funcs(('geqrf_lwork'), dtype=dtype)
+    m, n = shape
+    lwork, info = geqrf_lwork(m=m, n=n)
+    assert_equal(info, 0)
+
+
+class TestRegression:
+
+    def test_ticket_1645(self):
+        # Check that RQ routines have correct lwork
+        for dtype in DTYPES:
+            a = np.zeros((300, 2), dtype=dtype)
+
+            gerqf, = get_lapack_funcs(['gerqf'], [a])
+            assert_raises(Exception, gerqf, a, lwork=2)
+            rq, tau, work, info = gerqf(a)
+
+            if dtype in REAL_DTYPES:
+                orgrq, = get_lapack_funcs(['orgrq'], [a])
+                assert_raises(Exception, orgrq, rq[-2:], tau, lwork=1)
+                orgrq(rq[-2:], tau, lwork=2)
+            elif dtype in COMPLEX_DTYPES:
+                ungrq, = get_lapack_funcs(['ungrq'], [a])
+                assert_raises(Exception, ungrq, rq[-2:], tau, lwork=1)
+                ungrq(rq[-2:], tau, lwork=2)
+
+
+class TestDpotr:
+    def test_gh_2691(self):
+        # 'lower' argument of dportf/dpotri
+        for lower in [True, False]:
+            for clean in [True, False]:
+                np.random.seed(42)
+                x = np.random.normal(size=(3, 3))
+                a = x.dot(x.T)
+
+                dpotrf, dpotri = get_lapack_funcs(("potrf", "potri"), (a, ))
+
+                c, info = dpotrf(a, lower, clean=clean)
+                dpt = dpotri(c, lower)[0]
+
+                if lower:
+                    assert_allclose(np.tril(dpt), np.tril(inv(a)))
+                else:
+                    assert_allclose(np.triu(dpt), np.triu(inv(a)))
+
+
+class TestDlasd4:
+    def test_sing_val_update(self):
+
+        sigmas = np.array([4., 3., 2., 0])
+        m_vec = np.array([3.12, 5.7, -4.8, -2.2])
+
+        M = np.hstack((np.vstack((np.diag(sigmas[0:-1]),
+                                  np.zeros((1, len(m_vec) - 1)))),
+                       m_vec[:, np.newaxis]))
+        SM = svd(M, full_matrices=False, compute_uv=False, overwrite_a=False,
+                 check_finite=False)
+
+        it_len = len(sigmas)
+        sgm = np.concatenate((sigmas[::-1], [sigmas[0] + it_len*norm(m_vec)]))
+        mvc = np.concatenate((m_vec[::-1], (0,)))
+
+        lasd4 = get_lapack_funcs('lasd4', (sigmas,))
+
+        roots = []
+        for i in range(0, it_len):
+            res = lasd4(i, sgm, mvc)
+            roots.append(res[1])
+
+            assert_((res[3] <= 0), "LAPACK root finding dlasd4 failed to find \
+                                    the singular value %i" % i)
+        roots = np.array(roots)[::-1]
+
+        assert_((not np.any(np.isnan(roots)), "There are NaN roots"))
+        assert_allclose(SM, roots, atol=100*np.finfo(np.float64).eps,
+                        rtol=100*np.finfo(np.float64).eps)
+
+
+class TestTbtrs:
+
+    @pytest.mark.parametrize('dtype', DTYPES)
+    def test_nag_example_f07vef_f07vsf(self, dtype):
+        """Test real (f07vef) and complex (f07vsf) examples from NAG
+
+        Examples available from:
+        * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vef.html
+        * https://www.nag.com/numeric/fl/nagdoc_latest/html/f07/f07vsf.html
+
+        """
+        if dtype in REAL_DTYPES:
+            ab = np.array([[-4.16, 4.78, 6.32, 0.16],
+                           [-2.25, 5.86, -4.82, 0]],
+                          dtype=dtype)
+            b = np.array([[-16.64, -4.16],
+                          [-13.78, -16.59],
+                          [13.10, -4.94],
+                          [-14.14, -9.96]],
+                         dtype=dtype)
+            x_out = np.array([[4, 1],
+                              [-1, -3],
+                              [3, 2],
+                              [2, -2]],
+                             dtype=dtype)
+        elif dtype in COMPLEX_DTYPES:
+            ab = np.array([[-1.94+4.43j, 4.12-4.27j, 0.43-2.66j, 0.44+0.1j],
+                           [-3.39+3.44j, -1.84+5.52j, 1.74 - 0.04j, 0],
+                           [1.62+3.68j, -2.77-1.93j, 0, 0]],
+                          dtype=dtype)
+            b = np.array([[-8.86 - 3.88j, -24.09 - 5.27j],
+                          [-15.57 - 23.41j, -57.97 + 8.14j],
+                          [-7.63 + 22.78j, 19.09 - 29.51j],
+                          [-14.74 - 2.40j, 19.17 + 21.33j]],
+                         dtype=dtype)
+            x_out = np.array([[2j, 1 + 5j],
+                              [1 - 3j, -7 - 2j],
+                              [-4.001887 - 4.988417j, 3.026830 + 4.003182j],
+                              [1.996158 - 1.045105j, -6.103357 - 8.986653j]],
+                             dtype=dtype)
+        else:
+            raise ValueError(f"Datatype {dtype} not understood.")
+
+        tbtrs = get_lapack_funcs(('tbtrs'), dtype=dtype)
+        x, info = tbtrs(ab=ab, b=b, uplo='L')
+        assert_equal(info, 0)
+        assert_allclose(x, x_out, rtol=0, atol=1e-5)
+
+    @pytest.mark.parametrize('dtype,trans',
+                             [(dtype, trans)
+                              for dtype in DTYPES for trans in ['N', 'T', 'C']
+                              if not (trans == 'C' and dtype in REAL_DTYPES)])
+    @pytest.mark.parametrize('uplo', ['U', 'L'])
+    @pytest.mark.parametrize('diag', ['N', 'U'])
+    def test_random_matrices(self, dtype, trans, uplo, diag):
+        rng = np.random.RandomState(1724)
+
+        # n, nrhs, kd are used to specify A and b.
+        # A is of shape n x n with kd super/sub-diagonals
+        # b is of shape n x nrhs matrix
+        n, nrhs, kd = 4, 3, 2
+        tbtrs = get_lapack_funcs('tbtrs', dtype=dtype)
+
+        is_upper = (uplo == 'U')
+        ku = kd * is_upper
+        kl = kd - ku
+
+        # Construct the diagonal and kd super/sub diagonals of A with
+        # the corresponding offsets.
+        band_offsets = range(ku, -kl - 1, -1)
+        band_widths = [n - abs(x) for x in band_offsets]
+        bands = [generate_random_dtype_array((width,), dtype, rng)
+                 for width in band_widths]
+
+        if diag == 'U':  # A must be unit triangular
+            bands[ku] = np.ones(n, dtype=dtype)
+
+        # Construct the diagonal banded matrix A from the bands and offsets.
+        a = sps.diags(bands, band_offsets, format='dia')
+
+        # Convert A into banded storage form
+        ab = np.zeros((kd + 1, n), dtype)
+        for row, k in enumerate(band_offsets):
+            ab[row, max(k, 0):min(n+k, n)] = a.diagonal(k)
+
+        # The RHS values.
+        b = generate_random_dtype_array((n, nrhs), dtype, rng)
+
+        x, info = tbtrs(ab=ab, b=b, uplo=uplo, trans=trans, diag=diag)
+        assert_equal(info, 0)
+
+        if trans == 'N':
+            assert_allclose(a @ x, b, rtol=5e-5)
+        elif trans == 'T':
+            assert_allclose(a.T @ x, b, rtol=5e-5)
+        elif trans == 'C':
+            assert_allclose(a.T.conjugate() @ x, b, rtol=5e-5)
+        else:
+            raise ValueError('Invalid trans argument')
+
+    @pytest.mark.parametrize('uplo,trans,diag',
+                             [['U', 'N', 'Invalid'],
+                              ['U', 'Invalid', 'N'],
+                              ['Invalid', 'N', 'N']])
+    def test_invalid_argument_raises_exception(self, uplo, trans, diag):
+        """Test if invalid values of uplo, trans and diag raise exceptions"""
+        # Argument checks occur independently of used datatype.
+        # This mean we must not parameterize all available datatypes.
+        tbtrs = get_lapack_funcs('tbtrs', dtype=np.float64)
+        ab = rand(4, 2)
+        b = rand(2, 4)
+        assert_raises(Exception, tbtrs, ab, b, uplo, trans, diag)
+
+    def test_zero_element_in_diagonal(self):
+        """Test if a matrix with a zero diagonal element is singular
+
+        If the i-th diagonal of A is zero, ?tbtrs should return `i` in `info`
+        indicating the provided matrix is singular.
+
+        Note that ?tbtrs requires the matrix A to be stored in banded form.
+        In this form the diagonal corresponds to the last row."""
+        ab = np.ones((3, 4), dtype=float)
+        b = np.ones(4, dtype=float)
+        tbtrs = get_lapack_funcs('tbtrs', dtype=float)
+
+        ab[-1, 3] = 0
+        _, info = tbtrs(ab=ab, b=b, uplo='U')
+        assert_equal(info, 4)
+
+    @pytest.mark.parametrize('ldab,n,ldb,nrhs', [
+                              (5, 5, 0, 5),
+                              (5, 5, 3, 5)
+    ])
+    def test_invalid_matrix_shapes(self, ldab, n, ldb, nrhs):
+        """Test ?tbtrs fails correctly if shapes are invalid."""
+        ab = np.ones((ldab, n), dtype=float)
+        b = np.ones((ldb, nrhs), dtype=float)
+        tbtrs = get_lapack_funcs('tbtrs', dtype=float)
+        assert_raises(Exception, tbtrs, ab, b)
+
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('norm', ['I', '1', 'O'])
+@pytest.mark.parametrize('uplo', ['U', 'L'])
+@pytest.mark.parametrize('diag', ['N', 'U'])
+@pytest.mark.parametrize('n', [3, 10])
+def test_trcon(dtype, norm, uplo, diag, n):
+    # Simple way to get deterministic (unlike `hash`) integer seed based on arguments
+    random.seed(f"{dtype}{norm}{uplo}{diag}{n}")
+    rng = np.random.default_rng(random.randint(0, 9999999999999))
+
+    A = rng.random(size=(n, n)) + rng.random(size=(n, n))*1j
+    # make the condition numbers more interesting
+    offset = rng.permuted(np.logspace(0, rng.integers(0, 10), n))
+    A += offset
+    A = A.real if np.issubdtype(dtype, np.floating) else A
+    A = np.triu(A) if uplo == 'U' else np.tril(A)
+    if diag == 'U':
+        A /= np.diag(A)[:, np.newaxis]
+    A = A.astype(dtype)
+
+    trcon = get_lapack_funcs('trcon', (A,))
+    res, _ = trcon(A, norm=norm, uplo=uplo, diag=diag)
+
+    if norm == 'I':
+        norm_A = np.linalg.norm(A, ord=np.inf)
+        norm_inv_A = np.linalg.norm(np.linalg.inv(A), ord=np.inf)
+        ref = 1 / (norm_A * norm_inv_A)
+    else:
+        anorm = np.abs(A).sum(axis=0).max()
+        gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
+        lu, ipvt, info = getrf(A)
+        ref, _ = gecon(lu, anorm, norm=norm)
+
+    # This is an estimate of reciprocal condition number; we just need order of
+    # magnitude. In testing, we observed that much smaller rtol is OK in almost
+    # all cases... but sometimes it isn't.
+    rtol = 1  # np.finfo(dtype).eps**0.75
+    assert_allclose(res, ref, rtol=rtol)
+
+
+def test_lartg():
+    for dtype in 'fdFD':
+        lartg = get_lapack_funcs('lartg', dtype=dtype)
+
+        f = np.array(3, dtype)
+        g = np.array(4, dtype)
+
+        if np.iscomplexobj(g):
+            g *= 1j
+
+        cs, sn, r = lartg(f, g)
+
+        assert_allclose(cs, 3.0/5.0)
+        assert_allclose(r, 5.0)
+
+        if np.iscomplexobj(g):
+            assert_allclose(sn, -4.0j/5.0)
+            assert_(isinstance(r, complex))
+            assert_(isinstance(cs, float))
+        else:
+            assert_allclose(sn, 4.0/5.0)
+
+
+def test_rot():
+    # srot, drot from blas and crot and zrot from lapack.
+
+    for dtype in 'fdFD':
+        c = 0.6
+        s = 0.8
+
+        u = np.full(4, 3, dtype)
+        v = np.full(4, 4, dtype)
+        atol = 10**-(np.finfo(dtype).precision-1)
+
+        if dtype in 'fd':
+            rot = get_blas_funcs('rot', dtype=dtype)
+            f = 4
+        else:
+            rot = get_lapack_funcs('rot', dtype=dtype)
+            s *= -1j
+            v *= 1j
+            f = 4j
+
+        assert_allclose(rot(u, v, c, s), [[5, 5, 5, 5],
+                                          [0, 0, 0, 0]], atol=atol)
+        assert_allclose(rot(u, v, c, s, n=2), [[5, 5, 3, 3],
+                                               [0, 0, f, f]], atol=atol)
+        assert_allclose(rot(u, v, c, s, offx=2, offy=2),
+                        [[3, 3, 5, 5], [f, f, 0, 0]], atol=atol)
+        assert_allclose(rot(u, v, c, s, incx=2, offy=2, n=2),
+                        [[5, 3, 5, 3], [f, f, 0, 0]], atol=atol)
+        assert_allclose(rot(u, v, c, s, offx=2, incy=2, n=2),
+                        [[3, 3, 5, 5], [0, f, 0, f]], atol=atol)
+        assert_allclose(rot(u, v, c, s, offx=2, incx=2, offy=2, incy=2, n=1),
+                        [[3, 3, 5, 3], [f, f, 0, f]], atol=atol)
+        assert_allclose(rot(u, v, c, s, incx=-2, incy=-2, n=2),
+                        [[5, 3, 5, 3], [0, f, 0, f]], atol=atol)
+
+        a, b = rot(u, v, c, s, overwrite_x=1, overwrite_y=1)
+        assert_(a is u)
+        assert_(b is v)
+        assert_allclose(a, [5, 5, 5, 5], atol=atol)
+        assert_allclose(b, [0, 0, 0, 0], atol=atol)
+
+
+def test_larfg_larf():
+    np.random.seed(1234)
+    a0 = np.random.random((4, 4))
+    a0 = a0.T.dot(a0)
+
+    a0j = np.random.random((4, 4)) + 1j*np.random.random((4, 4))
+    a0j = a0j.T.conj().dot(a0j)
+
+    # our test here will be to do one step of reducing a hermetian matrix to
+    # tridiagonal form using householder transforms.
+
+    for dtype in 'fdFD':
+        larfg, larf = get_lapack_funcs(['larfg', 'larf'], dtype=dtype)
+
+        if dtype in 'FD':
+            a = a0j.copy()
+        else:
+            a = a0.copy()
+
+        # generate a householder transform to clear a[2:,0]
+        alpha, x, tau = larfg(a.shape[0]-1, a[1, 0], a[2:, 0])
+
+        # create expected output
+        expected = np.zeros_like(a[:, 0])
+        expected[0] = a[0, 0]
+        expected[1] = alpha
+
+        # assemble householder vector
+        v = np.zeros_like(a[1:, 0])
+        v[0] = 1.0
+        v[1:] = x
+
+        # apply transform from the left
+        a[1:, :] = larf(v, tau.conjugate(), a[1:, :], np.zeros(a.shape[1]))
+
+        # apply transform from the right
+        a[:, 1:] = larf(v, tau, a[:, 1:], np.zeros(a.shape[0]), side='R')
+
+        assert_allclose(a[:, 0], expected, atol=1e-5)
+        assert_allclose(a[0, :], expected, atol=1e-5)
+
+
+def test_sgesdd_lwork_bug_workaround():
+    # Test that SGESDD lwork is sufficiently large for LAPACK.
+    #
+    # This checks that _compute_lwork() correctly works around a bug in
+    # LAPACK versions older than 3.10.1.
+
+    sgesdd_lwork = get_lapack_funcs('gesdd_lwork', dtype=np.float32,
+                                    ilp64='preferred')
+    n = 9537
+    lwork = _compute_lwork(sgesdd_lwork, n, n,
+                           compute_uv=True, full_matrices=True)
+    # If we called the Fortran function SGESDD directly with IWORK=-1, the
+    # LAPACK bug would result in lwork being 272929856, which was too small.
+    # (The result was returned in a single precision float, which does not
+    # have sufficient precision to represent the exact integer value that it
+    # computed internally.)  The work-around implemented in _compute_lwork()
+    # will convert that to 272929888.  If we are using LAPACK 3.10.1 or later
+    # (such as in OpenBLAS 0.3.21 or later), the work-around will return
+    # 272929920, because it does not know which version of LAPACK is being
+    # used, so it always applies the correction to whatever it is given.  We
+    # will accept either 272929888 or 272929920.
+    # Note that the acceptable values are a LAPACK implementation detail.
+    # If a future version of LAPACK changes how SGESDD works, and therefore
+    # changes the required LWORK size, the acceptable values might have to
+    # be updated.
+    assert lwork == 272929888 or lwork == 272929920
+
+
+class TestSytrd:
+    @pytest.mark.parametrize('dtype', REAL_DTYPES)
+    def test_sytrd_with_zero_dim_array(self, dtype):
+        # Assert that a 0x0 matrix raises an error
+        A = np.zeros((0, 0), dtype=dtype)
+        sytrd = get_lapack_funcs('sytrd', (A,))
+        assert_raises(ValueError, sytrd, A)
+
+    @pytest.mark.parametrize('dtype', REAL_DTYPES)
+    @pytest.mark.parametrize('n', (1, 3))
+    def test_sytrd(self, dtype, n):
+        A = np.zeros((n, n), dtype=dtype)
+
+        sytrd, sytrd_lwork = \
+            get_lapack_funcs(('sytrd', 'sytrd_lwork'), (A,))
+
+        # some upper triangular array
+        A[np.triu_indices_from(A)] = \
+            np.arange(1, n*(n+1)//2+1, dtype=dtype)
+
+        # query lwork
+        lwork, info = sytrd_lwork(n)
+        assert_equal(info, 0)
+
+        # check lower=1 behavior (shouldn't do much since the matrix is
+        # upper triangular)
+        data, d, e, tau, info = sytrd(A, lower=1, lwork=lwork)
+        assert_equal(info, 0)
+
+        assert_allclose(data, A, atol=5*np.finfo(dtype).eps, rtol=1.0)
+        assert_allclose(d, np.diag(A))
+        assert_allclose(e, 0.0)
+        assert_allclose(tau, 0.0)
+
+        # and now for the proper test (lower=0 is the default)
+        data, d, e, tau, info = sytrd(A, lwork=lwork)
+        assert_equal(info, 0)
+
+        # assert Q^T*A*Q = tridiag(e, d, e)
+
+        # build tridiagonal matrix
+        T = np.zeros_like(A, dtype=dtype)
+        k = np.arange(A.shape[0])
+        T[k, k] = d
+        k2 = np.arange(A.shape[0]-1)
+        T[k2+1, k2] = e
+        T[k2, k2+1] = e
+
+        # build Q
+        Q = np.eye(n, n, dtype=dtype)
+        for i in range(n-1):
+            v = np.zeros(n, dtype=dtype)
+            v[:i] = data[:i, i+1]
+            v[i] = 1.0
+            H = np.eye(n, n, dtype=dtype) - tau[i] * np.outer(v, v)
+            Q = np.dot(H, Q)
+
+        # Make matrix fully symmetric
+        i_lower = np.tril_indices(n, -1)
+        A[i_lower] = A.T[i_lower]
+
+        QTAQ = np.dot(Q.T, np.dot(A, Q))
+
+        # disable rtol here since some values in QTAQ and T are very close
+        # to 0.
+        assert_allclose(QTAQ, T, atol=5*np.finfo(dtype).eps, rtol=1.0)
+
+
+class TestHetrd:
+    @pytest.mark.parametrize('complex_dtype', COMPLEX_DTYPES)
+    def test_hetrd_with_zero_dim_array(self, complex_dtype):
+        # Assert that a 0x0 matrix raises an error
+        A = np.zeros((0, 0), dtype=complex_dtype)
+        hetrd = get_lapack_funcs('hetrd', (A,))
+        assert_raises(ValueError, hetrd, A)
+
+    @pytest.mark.parametrize('real_dtype,complex_dtype',
+                             zip(REAL_DTYPES, COMPLEX_DTYPES))
+    @pytest.mark.parametrize('n', (1, 3))
+    def test_hetrd(self, n, real_dtype, complex_dtype):
+        A = np.zeros((n, n), dtype=complex_dtype)
+        hetrd, hetrd_lwork = \
+            get_lapack_funcs(('hetrd', 'hetrd_lwork'), (A,))
+
+        # some upper triangular array
+        A[np.triu_indices_from(A)] = (
+            np.arange(1, n*(n+1)//2+1, dtype=real_dtype)
+            + 1j * np.arange(1, n*(n+1)//2+1, dtype=real_dtype)
+            )
+        np.fill_diagonal(A, np.real(np.diag(A)))
+
+        # test query lwork
+        for x in [0, 1]:
+            _, info = hetrd_lwork(n, lower=x)
+            assert_equal(info, 0)
+        # lwork returns complex which segfaults hetrd call (gh-10388)
+        # use the safe and recommended option
+        lwork = _compute_lwork(hetrd_lwork, n)
+
+        # check lower=1 behavior (shouldn't do much since the matrix is
+        # upper triangular)
+        data, d, e, tau, info = hetrd(A, lower=1, lwork=lwork)
+        assert_equal(info, 0)
+
+        assert_allclose(data, A, atol=5*np.finfo(real_dtype).eps, rtol=1.0)
+
+        assert_allclose(d, np.real(np.diag(A)))
+        assert_allclose(e, 0.0)
+        assert_allclose(tau, 0.0)
+
+        # and now for the proper test (lower=0 is the default)
+        data, d, e, tau, info = hetrd(A, lwork=lwork)
+        assert_equal(info, 0)
+
+        # assert Q^T*A*Q = tridiag(e, d, e)
+
+        # build tridiagonal matrix
+        T = np.zeros_like(A, dtype=real_dtype)
+        k = np.arange(A.shape[0], dtype=int)
+        T[k, k] = d
+        k2 = np.arange(A.shape[0]-1, dtype=int)
+        T[k2+1, k2] = e
+        T[k2, k2+1] = e
+
+        # build Q
+        Q = np.eye(n, n, dtype=complex_dtype)
+        for i in range(n-1):
+            v = np.zeros(n, dtype=complex_dtype)
+            v[:i] = data[:i, i+1]
+            v[i] = 1.0
+            H = np.eye(n, n, dtype=complex_dtype) \
+                - tau[i] * np.outer(v, np.conj(v))
+            Q = np.dot(H, Q)
+
+        # Make matrix fully Hermitian
+        i_lower = np.tril_indices(n, -1)
+        A[i_lower] = np.conj(A.T[i_lower])
+
+        QHAQ = np.dot(np.conj(Q.T), np.dot(A, Q))
+
+        # disable rtol here since some values in QTAQ and T are very close
+        # to 0.
+        assert_allclose(
+            QHAQ, T, atol=10*np.finfo(real_dtype).eps, rtol=1.0
+            )
+
+
+def test_gglse():
+    # Example data taken from NAG manual
+    for ind, dtype in enumerate(DTYPES):
+        # DTYPES =  gglse
+        func, func_lwork = get_lapack_funcs(('gglse', 'gglse_lwork'),
+                                            dtype=dtype)
+        lwork = _compute_lwork(func_lwork, m=6, n=4, p=2)
+        # For gglse
+        if ind < 2:
+            a = np.array([[-0.57, -1.28, -0.39, 0.25],
+                          [-1.93, 1.08, -0.31, -2.14],
+                          [2.30, 0.24, 0.40, -0.35],
+                          [-1.93, 0.64, -0.66, 0.08],
+                          [0.15, 0.30, 0.15, -2.13],
+                          [-0.02, 1.03, -1.43, 0.50]], dtype=dtype)
+            c = np.array([-1.50, -2.14, 1.23, -0.54, -1.68, 0.82], dtype=dtype)
+            d = np.array([0., 0.], dtype=dtype)
+        # For gglse
+        else:
+            a = np.array([[0.96-0.81j, -0.03+0.96j, -0.91+2.06j, -0.05+0.41j],
+                          [-0.98+1.98j, -1.20+0.19j, -0.66+0.42j, -0.81+0.56j],
+                          [0.62-0.46j, 1.01+0.02j, 0.63-0.17j, -1.11+0.60j],
+                          [0.37+0.38j, 0.19-0.54j, -0.98-0.36j, 0.22-0.20j],
+                          [0.83+0.51j, 0.20+0.01j, -0.17-0.46j, 1.47+1.59j],
+                          [1.08-0.28j, 0.20-0.12j, -0.07+1.23j, 0.26+0.26j]])
+            c = np.array([[-2.54+0.09j],
+                          [1.65-2.26j],
+                          [-2.11-3.96j],
+                          [1.82+3.30j],
+                          [-6.41+3.77j],
+                          [2.07+0.66j]])
+            d = np.zeros(2, dtype=dtype)
+
+        b = np.array([[1., 0., -1., 0.], [0., 1., 0., -1.]], dtype=dtype)
+
+        _, _, _, result, _ = func(a, b, c, d, lwork=lwork)
+        if ind < 2:
+            expected = np.array([0.48904455,
+                                 0.99754786,
+                                 0.48904455,
+                                 0.99754786])
+        else:
+            expected = np.array([1.08742917-1.96205783j,
+                                 -0.74093902+3.72973919j,
+                                 1.08742917-1.96205759j,
+                                 -0.74093896+3.72973895j])
+        assert_array_almost_equal(result, expected, decimal=4)
+
+
+def test_sycon_hecon():
+    seed(1234)
+    for ind, dtype in enumerate(DTYPES+COMPLEX_DTYPES):
+        # DTYPES + COMPLEX DTYPES =  sycon + hecon
+        n = 10
+        # For sycon
+        if ind < 4:
+            func_lwork = get_lapack_funcs('sytrf_lwork', dtype=dtype)
+            funcon, functrf = get_lapack_funcs(('sycon', 'sytrf'), dtype=dtype)
+            A = (rand(n, n)).astype(dtype)
+        # For hecon
+        else:
+            func_lwork = get_lapack_funcs('hetrf_lwork', dtype=dtype)
+            funcon, functrf = get_lapack_funcs(('hecon', 'hetrf'), dtype=dtype)
+            A = (rand(n, n) + rand(n, n)*1j).astype(dtype)
+
+        # Since sycon only refers to upper/lower part, conj() is safe here.
+        A = (A + A.conj().T)/2 + 2*np.eye(n, dtype=dtype)
+
+        anorm = norm(A, 1)
+        lwork = _compute_lwork(func_lwork, n)
+        ldu, ipiv, _ = functrf(A, lwork=lwork, lower=1)
+        rcond, _ = funcon(a=ldu, ipiv=ipiv, anorm=anorm, lower=1)
+        # The error is at most 1-fold
+        assert_(abs(1/rcond - np.linalg.cond(A, p=1))*rcond < 1)
+
+
+def test_sygst():
+    seed(1234)
+    for ind, dtype in enumerate(REAL_DTYPES):
+        # DTYPES =  sygst
+        n = 10
+
+        potrf, sygst, syevd, sygvd = get_lapack_funcs(('potrf', 'sygst',
+                                                       'syevd', 'sygvd'),
+                                                      dtype=dtype)
+
+        A = rand(n, n).astype(dtype)
+        A = (A + A.T)/2
+        # B must be positive definite
+        B = rand(n, n).astype(dtype)
+        B = (B + B.T)/2 + 2 * np.eye(n, dtype=dtype)
+
+        # Perform eig (sygvd)
+        eig_gvd, _, info = sygvd(A, B)
+        assert_(info == 0)
+
+        # Convert to std problem potrf
+        b, info = potrf(B)
+        assert_(info == 0)
+        a, info = sygst(A, b)
+        assert_(info == 0)
+
+        eig, _, info = syevd(a)
+        assert_(info == 0)
+        assert_allclose(eig, eig_gvd, rtol=1.2e-4)
+
+
+def test_hegst():
+    seed(1234)
+    for ind, dtype in enumerate(COMPLEX_DTYPES):
+        # DTYPES =  hegst
+        n = 10
+
+        potrf, hegst, heevd, hegvd = get_lapack_funcs(('potrf', 'hegst',
+                                                       'heevd', 'hegvd'),
+                                                      dtype=dtype)
+
+        A = rand(n, n).astype(dtype) + 1j * rand(n, n).astype(dtype)
+        A = (A + A.conj().T)/2
+        # B must be positive definite
+        B = rand(n, n).astype(dtype) + 1j * rand(n, n).astype(dtype)
+        B = (B + B.conj().T)/2 + 2 * np.eye(n, dtype=dtype)
+
+        # Perform eig (hegvd)
+        eig_gvd, _, info = hegvd(A, B)
+        assert_(info == 0)
+
+        # Convert to std problem potrf
+        b, info = potrf(B)
+        assert_(info == 0)
+        a, info = hegst(A, b)
+        assert_(info == 0)
+
+        eig, _, info = heevd(a)
+        assert_(info == 0)
+        assert_allclose(eig, eig_gvd, rtol=1e-4)
+
+
+def test_tzrzf():
+    """
+    This test performs an RZ decomposition in which an m x n upper trapezoidal
+    array M (m <= n) is factorized as M = [R 0] * Z where R is upper triangular
+    and Z is unitary.
+    """
+    rng = np.random.RandomState(1234)
+    m, n = 10, 15
+    for ind, dtype in enumerate(DTYPES):
+        tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'),
+                                           dtype=dtype)
+        lwork = _compute_lwork(tzrzf_lw, m, n)
+
+        if ind < 2:
+            A = triu(rng.rand(m, n).astype(dtype))
+        else:
+            A = triu((rng.rand(m, n) + rng.rand(m, n)*1j).astype(dtype))
+
+        # assert wrong shape arg, f2py returns generic error
+        assert_raises(Exception, tzrzf, A.T)
+        rz, tau, info = tzrzf(A, lwork=lwork)
+        # Check success
+        assert_(info == 0)
+
+        # Get Z manually for comparison
+        R = np.hstack((rz[:, :m], np.zeros((m, n-m), dtype=dtype)))
+        V = np.hstack((np.eye(m, dtype=dtype), rz[:, m:]))
+        Id = np.eye(n, dtype=dtype)
+        ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(m)]
+        Z = reduce(np.dot, ref)
+        assert_allclose(R.dot(Z) - A, zeros_like(A, dtype=dtype),
+                        atol=10*np.spacing(dtype(1.0).real), rtol=0.)
+
+
+def test_tfsm():
+    """
+    Test for solving a linear system with the coefficient matrix is a
+    triangular array stored in Full Packed (RFP) format.
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = triu(rng.rand(n, n) + rng.rand(n, n)*1j + eye(n)).astype(dtype)
+            trans = 'C'
+        else:
+            A = triu(rng.rand(n, n) + eye(n)).astype(dtype)
+            trans = 'T'
+
+        trttf, tfttr, tfsm = get_lapack_funcs(('trttf', 'tfttr', 'tfsm'),
+                                              dtype=dtype)
+
+        Afp, _ = trttf(A)
+        B = rng.rand(n, 2).astype(dtype)
+        soln = tfsm(-1, Afp, B)
+        assert_array_almost_equal(soln, solve(-A, B),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+        soln = tfsm(-1, Afp, B, trans=trans)
+        assert_array_almost_equal(soln, solve(-A.conj().T, B),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+        # Make A, unit diagonal
+        A[np.arange(n), np.arange(n)] = dtype(1.)
+        soln = tfsm(-1, Afp, B, trans=trans, diag='U')
+        assert_array_almost_equal(soln, solve(-A.conj().T, B),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+        # Change side
+        B2 = rng.rand(3, n).astype(dtype)
+        soln = tfsm(-1, Afp, B2, trans=trans, diag='U', side='R')
+        assert_array_almost_equal(soln, solve(-A, B2.T).conj().T,
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_ormrz_unmrz():
+    """
+    This test performs a matrix multiplication with an arbitrary m x n matrix C
+    and a unitary matrix Q without explicitly forming the array. The array data
+    is encoded in the rectangular part of A which is obtained from ?TZRZF. Q
+    size is inferred by m, n, side keywords.
+    """
+    rng = np.random.RandomState(1234)
+    qm, qn, cn = 10, 15, 15
+    for ind, dtype in enumerate(DTYPES):
+        tzrzf, tzrzf_lw = get_lapack_funcs(('tzrzf', 'tzrzf_lwork'),
+                                           dtype=dtype)
+        lwork_rz = _compute_lwork(tzrzf_lw, qm, qn)
+
+        if ind < 2:
+            A = triu(rng.rand(qm, qn).astype(dtype))
+            C = rng.rand(cn, cn).astype(dtype)
+            orun_mrz, orun_mrz_lw = get_lapack_funcs(('ormrz', 'ormrz_lwork'),
+                                                     dtype=dtype)
+        else:
+            A = triu((rng.rand(qm, qn) + rng.rand(qm, qn)*1j).astype(dtype))
+            C = (rng.rand(cn, cn) + rand(cn, cn)*1j).astype(dtype)
+            orun_mrz, orun_mrz_lw = get_lapack_funcs(('unmrz', 'unmrz_lwork'),
+                                                     dtype=dtype)
+
+        lwork_mrz = _compute_lwork(orun_mrz_lw, cn, cn)
+        rz, tau, info = tzrzf(A, lwork=lwork_rz)
+
+        # Get Q manually for comparison
+        V = np.hstack((np.eye(qm, dtype=dtype), rz[:, qm:]))
+        Id = np.eye(qn, dtype=dtype)
+        ref = [Id-tau[x]*V[[x], :].T.dot(V[[x], :].conj()) for x in range(qm)]
+        Q = reduce(np.dot, ref)
+
+        # Now that we have Q, we can test whether lapack results agree with
+        # each case of CQ, CQ^H, QC, and QC^H
+        trans = 'T' if ind < 2 else 'C'
+        tol = 10*np.spacing(dtype(1.0).real)
+
+        cq, info = orun_mrz(rz, tau, C, lwork=lwork_mrz)
+        assert_(info == 0)
+        assert_allclose(cq - Q.dot(C), zeros_like(C), atol=tol, rtol=0.)
+
+        cq, info = orun_mrz(rz, tau, C, trans=trans, lwork=lwork_mrz)
+        assert_(info == 0)
+        assert_allclose(cq - Q.conj().T.dot(C), zeros_like(C), atol=tol,
+                        rtol=0.)
+
+        cq, info = orun_mrz(rz, tau, C, side='R', lwork=lwork_mrz)
+        assert_(info == 0)
+        assert_allclose(cq - C.dot(Q), zeros_like(C), atol=tol, rtol=0.)
+
+        cq, info = orun_mrz(rz, tau, C, side='R', trans=trans, lwork=lwork_mrz)
+        assert_(info == 0)
+        assert_allclose(cq - C.dot(Q.conj().T), zeros_like(C), atol=tol,
+                        rtol=0.)
+
+
+def test_tfttr_trttf():
+    """
+    Test conversion routines between the Rectangular Full Packed (RFP) format
+    and Standard Triangular Array (TR)
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            transr = 'C'
+        else:
+            A_full = (rng.rand(n, n)).astype(dtype)
+            transr = 'T'
+
+        trttf, tfttr = get_lapack_funcs(('trttf', 'tfttr'), dtype=dtype)
+        A_tf_U, info = trttf(A_full)
+        assert_(info == 0)
+        A_tf_L, info = trttf(A_full, uplo='L')
+        assert_(info == 0)
+        A_tf_U_T, info = trttf(A_full, transr=transr, uplo='U')
+        assert_(info == 0)
+        A_tf_L_T, info = trttf(A_full, transr=transr, uplo='L')
+        assert_(info == 0)
+
+        # Create the RFP array manually (n is even!)
+        A_tf_U_m = zeros((n+1, n//2), dtype=dtype)
+        A_tf_U_m[:-1, :] = triu(A_full)[:, n//2:]
+        A_tf_U_m[n//2+1:, :] += triu(A_full)[:n//2, :n//2].conj().T
+
+        A_tf_L_m = zeros((n+1, n//2), dtype=dtype)
+        A_tf_L_m[1:, :] = tril(A_full)[:, :n//2]
+        A_tf_L_m[:n//2, :] += tril(A_full)[n//2:, n//2:].conj().T
+
+        assert_array_almost_equal(A_tf_U, A_tf_U_m.reshape(-1, order='F'))
+        assert_array_almost_equal(A_tf_U_T,
+                                  A_tf_U_m.conj().T.reshape(-1, order='F'))
+
+        assert_array_almost_equal(A_tf_L, A_tf_L_m.reshape(-1, order='F'))
+        assert_array_almost_equal(A_tf_L_T,
+                                  A_tf_L_m.conj().T.reshape(-1, order='F'))
+
+        # Get the original array from RFP
+        A_tr_U, info = tfttr(n, A_tf_U)
+        assert_(info == 0)
+        A_tr_L, info = tfttr(n, A_tf_L, uplo='L')
+        assert_(info == 0)
+        A_tr_U_T, info = tfttr(n, A_tf_U_T, transr=transr, uplo='U')
+        assert_(info == 0)
+        A_tr_L_T, info = tfttr(n, A_tf_L_T, transr=transr, uplo='L')
+        assert_(info == 0)
+
+        assert_array_almost_equal(A_tr_U, triu(A_full))
+        assert_array_almost_equal(A_tr_U_T, triu(A_full))
+        assert_array_almost_equal(A_tr_L, tril(A_full))
+        assert_array_almost_equal(A_tr_L_T, tril(A_full))
+
+
+def test_tpttr_trttp():
+    """
+    Test conversion routines between the Rectangular Full Packed (RFP) format
+    and Standard Triangular Array (TR)
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A_full = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+        else:
+            A_full = (rng.rand(n, n)).astype(dtype)
+
+        trttp, tpttr = get_lapack_funcs(('trttp', 'tpttr'), dtype=dtype)
+        A_tp_U, info = trttp(A_full)
+        assert_(info == 0)
+        A_tp_L, info = trttp(A_full, uplo='L')
+        assert_(info == 0)
+
+        # Create the TP array manually
+        inds = tril_indices(n)
+        A_tp_U_m = zeros(n*(n+1)//2, dtype=dtype)
+        A_tp_U_m[:] = (triu(A_full).T)[inds]
+
+        inds = triu_indices(n)
+        A_tp_L_m = zeros(n*(n+1)//2, dtype=dtype)
+        A_tp_L_m[:] = (tril(A_full).T)[inds]
+
+        assert_array_almost_equal(A_tp_U, A_tp_U_m)
+        assert_array_almost_equal(A_tp_L, A_tp_L_m)
+
+        # Get the original array from TP
+        A_tr_U, info = tpttr(n, A_tp_U)
+        assert_(info == 0)
+        A_tr_L, info = tpttr(n, A_tp_L, uplo='L')
+        assert_(info == 0)
+
+        assert_array_almost_equal(A_tr_U, triu(A_full))
+        assert_array_almost_equal(A_tr_L, tril(A_full))
+
+
+def test_pftrf():
+    """
+    Test Cholesky factorization of a positive definite Rectangular Full
+    Packed (RFP) format array
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            A = A + A.conj().T + n*eye(n)
+        else:
+            A = (rng.rand(n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        pftrf, trttf, tfttr = get_lapack_funcs(('pftrf', 'trttf', 'tfttr'),
+                                               dtype=dtype)
+
+        # Get the original array from TP
+        Afp, info = trttf(A)
+        Achol_rfp, info = pftrf(n, Afp)
+        assert_(info == 0)
+        A_chol_r, _ = tfttr(n, Achol_rfp)
+        Achol = cholesky(A)
+        assert_array_almost_equal(A_chol_r, Achol)
+
+
+def test_pftri():
+    """
+    Test Cholesky factorization of a positive definite Rectangular Full
+    Packed (RFP) format array to find its inverse
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            A = A + A.conj().T + n*eye(n)
+        else:
+            A = (rng.rand(n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        pftri, pftrf, trttf, tfttr = get_lapack_funcs(('pftri',
+                                                       'pftrf',
+                                                       'trttf',
+                                                       'tfttr'),
+                                                      dtype=dtype)
+
+        # Get the original array from TP
+        Afp, info = trttf(A)
+        A_chol_rfp, info = pftrf(n, Afp)
+        A_inv_rfp, info = pftri(n, A_chol_rfp)
+        assert_(info == 0)
+        A_inv_r, _ = tfttr(n, A_inv_rfp)
+        Ainv = inv(A)
+        assert_array_almost_equal(A_inv_r, triu(Ainv),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_pftrs():
+    """
+    Test Cholesky factorization of a positive definite Rectangular Full
+    Packed (RFP) format array and solve a linear system
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            A = A + A.conj().T + n*eye(n)
+        else:
+            A = (rng.rand(n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        B = ones((n, 3), dtype=dtype)
+        Bf1 = ones((n+2, 3), dtype=dtype)
+        Bf2 = ones((n-2, 3), dtype=dtype)
+        pftrs, pftrf, trttf, tfttr = get_lapack_funcs(('pftrs',
+                                                       'pftrf',
+                                                       'trttf',
+                                                       'tfttr'),
+                                                      dtype=dtype)
+
+        # Get the original array from TP
+        Afp, info = trttf(A)
+        A_chol_rfp, info = pftrf(n, Afp)
+        # larger B arrays shouldn't segfault
+        soln, info = pftrs(n, A_chol_rfp, Bf1)
+        assert_(info == 0)
+        assert_raises(Exception, pftrs, n, A_chol_rfp, Bf2)
+        soln, info = pftrs(n, A_chol_rfp, B)
+        assert_(info == 0)
+        assert_array_almost_equal(solve(A, B), soln,
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_sfrk_hfrk():
+    """
+    Test for performing a symmetric rank-k operation for matrix in RFP format.
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 20
+        if ind > 1:
+            A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            A = A + A.conj().T + n*eye(n)
+        else:
+            A = (rng.rand(n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        prefix = 's'if ind < 2 else 'h'
+        trttf, tfttr, shfrk = get_lapack_funcs(('trttf', 'tfttr', f'{prefix}frk'),
+                                               dtype=dtype)
+
+        Afp, _ = trttf(A)
+        C = rng.rand(n, 2).astype(dtype)
+        Afp_out = shfrk(n, 2, -1, C, 2, Afp)
+        A_out, _ = tfttr(n, Afp_out)
+        assert_array_almost_equal(A_out, triu(-C.dot(C.conj().T) + 2*A),
+                                  decimal=4 if ind % 2 == 0 else 6)
+
+
+def test_syconv():
+    """
+    Test for going back and forth between the returned format of he/sytrf to
+    L and D factors/permutations.
+    """
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        n = 10
+
+        if ind > 1:
+            A = (rng.randint(-30, 30, (n, n)) +
+                 rng.randint(-30, 30, (n, n))*1j).astype(dtype)
+
+            A = A + A.conj().T
+        else:
+            A = rng.randint(-30, 30, (n, n)).astype(dtype)
+            A = A + A.T + n*eye(n)
+
+        tol = 100*np.spacing(dtype(1.0).real)
+        syconv, trf, trf_lwork = get_lapack_funcs(('syconv', 'sytrf',
+                                                   'sytrf_lwork'), dtype=dtype)
+        lw = _compute_lwork(trf_lwork, n, lower=1)
+        L, D, perm = ldl(A, lower=1, hermitian=False)
+        lw = _compute_lwork(trf_lwork, n, lower=1)
+        ldu, ipiv, info = trf(A, lower=1, lwork=lw)
+        a, e, info = syconv(ldu, ipiv, lower=1)
+        assert_allclose(tril(a, -1,), tril(L[perm, :], -1), atol=tol, rtol=0.)
+
+        # Test also upper
+        U, D, perm = ldl(A, lower=0, hermitian=False)
+        ldu, ipiv, info = trf(A, lower=0)
+        a, e, info = syconv(ldu, ipiv, lower=0)
+        assert_allclose(triu(a, 1), triu(U[perm, :], 1), atol=tol, rtol=0.)
+
+
+class TestBlockedQR:
+    """
+    Tests for the blocked QR factorization, namely through geqrt, gemqrt, tpqrt
+    and tpmqr.
+    """
+
+    def test_geqrt_gemqrt(self):
+        rng = np.random.RandomState(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 20
+
+            if ind > 1:
+                A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            else:
+                A = (rng.rand(n, n)).astype(dtype)
+
+            tol = 100*np.spacing(dtype(1.0).real)
+            geqrt, gemqrt = get_lapack_funcs(('geqrt', 'gemqrt'), dtype=dtype)
+
+            a, t, info = geqrt(n, A)
+            assert info == 0
+
+            # Extract elementary reflectors from lower triangle, adding the
+            # main diagonal of ones.
+            v = np.tril(a, -1) + np.eye(n, dtype=dtype)
+            # Generate the block Householder transform I - VTV^H
+            Q = np.eye(n, dtype=dtype) - v @ t @ v.T.conj()
+            R = np.triu(a)
+
+            # Test columns of Q are orthogonal
+            assert_allclose(Q.T.conj() @ Q, np.eye(n, dtype=dtype), atol=tol,
+                            rtol=0.)
+            assert_allclose(Q @ R, A, atol=tol, rtol=0.)
+
+            if ind > 1:
+                C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+                transpose = 'C'
+            else:
+                C = (rng.rand(n, n)).astype(dtype)
+                transpose = 'T'
+
+            for side in ('L', 'R'):
+                for trans in ('N', transpose):
+                    c, info = gemqrt(a, t, C, side=side, trans=trans)
+                    assert info == 0
+
+                    if trans == transpose:
+                        q = Q.T.conj()
+                    else:
+                        q = Q
+
+                    if side == 'L':
+                        qC = q @ C
+                    else:
+                        qC = C @ q
+
+                    assert_allclose(c, qC, atol=tol, rtol=0.)
+
+                    # Test default arguments
+                    if (side, trans) == ('L', 'N'):
+                        c_default, info = gemqrt(a, t, C)
+                        assert info == 0
+                        assert_equal(c_default, c)
+
+            # Test invalid side/trans
+            assert_raises(Exception, gemqrt, a, t, C, side='A')
+            assert_raises(Exception, gemqrt, a, t, C, trans='A')
+
+    def test_tpqrt_tpmqrt(self):
+        rng = np.random.RandomState(1234)
+        for ind, dtype in enumerate(DTYPES):
+            n = 20
+
+            if ind > 1:
+                A = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+                B = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+            else:
+                A = (rng.rand(n, n)).astype(dtype)
+                B = (rng.rand(n, n)).astype(dtype)
+
+            tol = 100*np.spacing(dtype(1.0).real)
+            tpqrt, tpmqrt = get_lapack_funcs(('tpqrt', 'tpmqrt'), dtype=dtype)
+
+            # Test for the range of pentagonal B, from square to upper
+            # triangular
+            for l in (0, n // 2, n):
+                a, b, t, info = tpqrt(l, n, A, B)
+                assert info == 0
+
+                # Check that lower triangular part of A has not been modified
+                assert_equal(np.tril(a, -1), np.tril(A, -1))
+                # Check that elements not part of the pentagonal portion of B
+                # have not been modified.
+                assert_equal(np.tril(b, l - n - 1), np.tril(B, l - n - 1))
+
+                # Extract pentagonal portion of B
+                B_pent, b_pent = np.triu(B, l - n), np.triu(b, l - n)
+
+                # Generate elementary reflectors
+                v = np.concatenate((np.eye(n, dtype=dtype), b_pent))
+                # Generate the block Householder transform I - VTV^H
+                Q = np.eye(2 * n, dtype=dtype) - v @ t @ v.T.conj()
+                R = np.concatenate((np.triu(a), np.zeros_like(a)))
+
+                # Test columns of Q are orthogonal
+                assert_allclose(Q.T.conj() @ Q, np.eye(2 * n, dtype=dtype),
+                                atol=tol, rtol=0.)
+                assert_allclose(Q @ R, np.concatenate((np.triu(A), B_pent)),
+                                atol=tol, rtol=0.)
+
+                if ind > 1:
+                    C = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+                    D = (rng.rand(n, n) + rng.rand(n, n)*1j).astype(dtype)
+                    transpose = 'C'
+                else:
+                    C = (rng.rand(n, n)).astype(dtype)
+                    D = (rng.rand(n, n)).astype(dtype)
+                    transpose = 'T'
+
+                for side in ('L', 'R'):
+                    for trans in ('N', transpose):
+                        c, d, info = tpmqrt(l, b, t, C, D, side=side,
+                                            trans=trans)
+                        assert info == 0
+
+                        if trans == transpose:
+                            q = Q.T.conj()
+                        else:
+                            q = Q
+
+                        if side == 'L':
+                            cd = np.concatenate((c, d), axis=0)
+                            CD = np.concatenate((C, D), axis=0)
+                            qCD = q @ CD
+                        else:
+                            cd = np.concatenate((c, d), axis=1)
+                            CD = np.concatenate((C, D), axis=1)
+                            qCD = CD @ q
+
+                        assert_allclose(cd, qCD, atol=tol, rtol=0.)
+
+                        if (side, trans) == ('L', 'N'):
+                            c_default, d_default, info = tpmqrt(l, b, t, C, D)
+                            assert info == 0
+                            assert_equal(c_default, c)
+                            assert_equal(d_default, d)
+
+                # Test invalid side/trans
+                assert_raises(Exception, tpmqrt, l, b, t, C, D, side='A')
+                assert_raises(Exception, tpmqrt, l, b, t, C, D, trans='A')
+
+
+def test_pstrf():
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        # DTYPES =  pstrf
+        n = 10
+        r = 2
+        pstrf = get_lapack_funcs('pstrf', dtype=dtype)
+
+        # Create positive semidefinite A
+        if ind > 1:
+            A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype)
+            A = A @ A.conj().T
+        else:
+            A = rng.rand(n, n-r).astype(dtype)
+            A = A @ A.T
+
+        c, piv, r_c, info = pstrf(A)
+        U = triu(c)
+        U[r_c - n:, r_c - n:] = 0.
+
+        assert_equal(info, 1)
+        # python-dbg 3.5.2 runs cause trouble with the following assertion.
+        # assert_equal(r_c, n - r)
+        single_atol = 1000 * np.finfo(np.float32).eps
+        double_atol = 1000 * np.finfo(np.float64).eps
+        atol = single_atol if ind in [0, 2] else double_atol
+        assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol)
+
+        c, piv, r_c, info = pstrf(A, lower=1)
+        L = tril(c)
+        L[r_c - n:, r_c - n:] = 0.
+
+        assert_equal(info, 1)
+        # assert_equal(r_c, n - r)
+        single_atol = 1000 * np.finfo(np.float32).eps
+        double_atol = 1000 * np.finfo(np.float64).eps
+        atol = single_atol if ind in [0, 2] else double_atol
+        assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol)
+
+
+def test_pstf2():
+    rng = np.random.RandomState(1234)
+    for ind, dtype in enumerate(DTYPES):
+        # DTYPES =  pstf2
+        n = 10
+        r = 2
+        pstf2 = get_lapack_funcs('pstf2', dtype=dtype)
+
+        # Create positive semidefinite A
+        if ind > 1:
+            A = rng.rand(n, n-r).astype(dtype) + 1j * rng.rand(n, n-r).astype(dtype)
+            A = A @ A.conj().T
+        else:
+            A = rng.rand(n, n-r).astype(dtype)
+            A = A @ A.T
+
+        c, piv, r_c, info = pstf2(A)
+        U = triu(c)
+        U[r_c - n:, r_c - n:] = 0.
+
+        assert_equal(info, 1)
+        # python-dbg 3.5.2 runs cause trouble with the commented assertions.
+        # assert_equal(r_c, n - r)
+        single_atol = 1000 * np.finfo(np.float32).eps
+        double_atol = 1000 * np.finfo(np.float64).eps
+        atol = single_atol if ind in [0, 2] else double_atol
+        assert_allclose(A[piv-1][:, piv-1], U.conj().T @ U, rtol=0., atol=atol)
+
+        c, piv, r_c, info = pstf2(A, lower=1)
+        L = tril(c)
+        L[r_c - n:, r_c - n:] = 0.
+
+        assert_equal(info, 1)
+        # assert_equal(r_c, n - r)
+        single_atol = 1000 * np.finfo(np.float32).eps
+        double_atol = 1000 * np.finfo(np.float64).eps
+        atol = single_atol if ind in [0, 2] else double_atol
+        assert_allclose(A[piv-1][:, piv-1], L @ L.conj().T, rtol=0., atol=atol)
+
+
+def test_geequ():
+    desired_real = np.array([[0.6250, 1.0000, 0.0393, -0.4269],
+                             [1.0000, -0.5619, -1.0000, -1.0000],
+                             [0.5874, -1.0000, -0.0596, -0.5341],
+                             [-1.0000, -0.5946, -0.0294, 0.9957]])
+
+    desired_cplx = np.array([[-0.2816+0.5359*1j,
+                              0.0812+0.9188*1j,
+                              -0.7439-0.2561*1j],
+                             [-0.3562-0.2954*1j,
+                              0.9566-0.0434*1j,
+                              -0.0174+0.1555*1j],
+                             [0.8607+0.1393*1j,
+                              -0.2759+0.7241*1j,
+                              -0.1642-0.1365*1j]])
+
+    for ind, dtype in enumerate(DTYPES):
+        if ind < 2:
+            # Use examples from the NAG documentation
+            A = np.array([[1.80e+10, 2.88e+10, 2.05e+00, -8.90e+09],
+                          [5.25e+00, -2.95e+00, -9.50e-09, -3.80e+00],
+                          [1.58e+00, -2.69e+00, -2.90e-10, -1.04e+00],
+                          [-1.11e+00, -6.60e-01, -5.90e-11, 8.00e-01]])
+            A = A.astype(dtype)
+        else:
+            A = np.array([[-1.34e+00, 0.28e+10, -6.39e+00],
+                          [-1.70e+00, 3.31e+10, -0.15e+00],
+                          [2.41e-10, -0.56e+00, -0.83e-10]], dtype=dtype)
+            A += np.array([[2.55e+00, 3.17e+10, -2.20e+00],
+                           [-1.41e+00, -0.15e+10, 1.34e+00],
+                           [0.39e-10, 1.47e+00, -0.69e-10]])*1j
+
+            A = A.astype(dtype)
+
+        geequ = get_lapack_funcs('geequ', dtype=dtype)
+        r, c, rowcnd, colcnd, amax, info = geequ(A)
+
+        if ind < 2:
+            assert_allclose(desired_real.astype(dtype), r[:, None]*A*c,
+                            rtol=0, atol=1e-4)
+        else:
+            assert_allclose(desired_cplx.astype(dtype), r[:, None]*A*c,
+                            rtol=0, atol=1e-4)
+
+
+def test_syequb():
+    desired_log2s = np.array([0, 0, 0, 0, 0, 0, -1, -1, -2, -3])
+
+    for ind, dtype in enumerate(DTYPES):
+        A = np.eye(10, dtype=dtype)
+        alpha = dtype(1. if ind < 2 else 1.j)
+        d = np.array([alpha * 2.**x for x in range(-5, 5)], dtype=dtype)
+        A += np.rot90(np.diag(d))
+
+        syequb = get_lapack_funcs('syequb', dtype=dtype)
+        s, scond, amax, info = syequb(A)
+
+        assert_equal(np.log2(s).astype(int), desired_log2s)
+
+
+@pytest.mark.skipif(True,
+                    reason="Failing on some OpenBLAS version, see gh-12276")
+def test_heequb():
+    # zheequb has a bug for versions =< LAPACK 3.9.0
+    # See Reference-LAPACK gh-61 and gh-408
+    # Hence the zheequb test is customized accordingly to avoid
+    # work scaling.
+    A = np.diag([2]*5 + [1002]*5) + np.diag(np.ones(9), k=1)*1j
+    s, scond, amax, info = lapack.zheequb(A)
+    assert_equal(info, 0)
+    assert_allclose(np.log2(s), [0., -1.]*2 + [0.] + [-4]*5)
+
+    A = np.diag(2**np.abs(np.arange(-5, 6)) + 0j)
+    A[5, 5] = 1024
+    A[5, 0] = 16j
+    s, scond, amax, info = lapack.cheequb(A.astype(np.complex64), lower=1)
+    assert_equal(info, 0)
+    assert_allclose(np.log2(s), [-2, -1, -1, 0, 0, -5, 0, -1, -1, -2, -2])
+
+
+def test_getc2_gesc2():
+    rng = np.random.RandomState(42)
+    n = 10
+    desired_real = rng.rand(n)
+    desired_cplx = rng.rand(n) + rng.rand(n)*1j
+
+    for ind, dtype in enumerate(DTYPES):
+        if ind < 2:
+            A = rng.rand(n, n)
+            A = A.astype(dtype)
+            b = A @ desired_real
+            b = b.astype(dtype)
+        else:
+            A = rng.rand(n, n) + rng.rand(n, n)*1j
+            A = A.astype(dtype)
+            b = A @ desired_cplx
+            b = b.astype(dtype)
+
+        getc2 = get_lapack_funcs('getc2', dtype=dtype)
+        gesc2 = get_lapack_funcs('gesc2', dtype=dtype)
+        lu, ipiv, jpiv, info = getc2(A, overwrite_a=0)
+        x, scale = gesc2(lu, b, ipiv, jpiv, overwrite_rhs=0)
+
+        if ind < 2:
+            assert_array_almost_equal(desired_real.astype(dtype),
+                                      x/scale, decimal=4)
+        else:
+            assert_array_almost_equal(desired_cplx.astype(dtype),
+                                      x/scale, decimal=4)
+
+
+@pytest.mark.parametrize('size', [(6, 5), (5, 5)])
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+@pytest.mark.parametrize('joba', range(6))  # 'C', 'E', 'F', 'G', 'A', 'R'
+@pytest.mark.parametrize('jobu', range(4))  # 'U', 'F', 'W', 'N'
+@pytest.mark.parametrize('jobv', range(4))  # 'V', 'J', 'W', 'N'
+@pytest.mark.parametrize('jobr', [0, 1])
+@pytest.mark.parametrize('jobp', [0, 1])
+def test_gejsv_general(size, dtype, joba, jobu, jobv, jobr, jobp, jobt=0):
+    """Test the lapack routine ?gejsv.
+
+    This function tests that a singular value decomposition can be performed
+    on the random M-by-N matrix A. The test performs the SVD using ?gejsv
+    then performs the following checks:
+
+    * ?gejsv exist successfully (info == 0)
+    * The returned singular values are correct
+    * `A` can be reconstructed from `u`, `SIGMA`, `v`
+    * Ensure that u.T @ u is the identity matrix
+    * Ensure that v.T @ v is the identity matrix
+    * The reported matrix rank
+    * The reported number of singular values
+    * If denormalized floats are required
+
+    Notes
+    -----
+    joba specifies several choices effecting the calculation's accuracy
+    Although all arguments are tested, the tests only check that the correct
+    solution is returned - NOT that the prescribed actions are performed
+    internally.
+
+    jobt is, as of v3.9.0, still experimental and removed to cut down number of
+    test cases. However keyword itself is tested externally.
+    """
+    rng = np.random.RandomState(42)
+
+    # Define some constants for later use:
+    m, n = size
+    atol = 100 * np.finfo(dtype).eps
+    A = generate_random_dtype_array(size, dtype, rng)
+    gejsv = get_lapack_funcs('gejsv', dtype=dtype)
+
+    # Set up checks for invalid job? combinations
+    # if an invalid combination occurs we set the appropriate
+    # exit status.
+    lsvec = jobu < 2  # Calculate left singular vectors
+    rsvec = jobv < 2  # Calculate right singular vectors
+    l2tran = (jobt == 1) and (m == n)
+    is_complex = np.iscomplexobj(A)
+
+    invalid_real_jobv = (jobv == 1) and (not lsvec) and (not is_complex)
+    invalid_cplx_jobu = (jobu == 2) and not (rsvec and l2tran) and is_complex
+    invalid_cplx_jobv = (jobv == 2) and not (lsvec and l2tran) and is_complex
+
+    # Set the exit status to the expected value.
+    # Here we only check for invalid combinations, not individual
+    # parameters.
+    if invalid_cplx_jobu:
+        exit_status = -2
+    elif invalid_real_jobv or invalid_cplx_jobv:
+        exit_status = -3
+    else:
+        exit_status = 0
+
+    if (jobu > 1) and (jobv == 1):
+        assert_raises(Exception, gejsv, A, joba, jobu, jobv, jobr, jobt, jobp)
+    else:
+        sva, u, v, work, iwork, info = gejsv(A,
+                                             joba=joba,
+                                             jobu=jobu,
+                                             jobv=jobv,
+                                             jobr=jobr,
+                                             jobt=jobt,
+                                             jobp=jobp)
+
+        # Check that ?gejsv exited successfully/as expected
+        assert_equal(info, exit_status)
+
+        # If exit_status is non-zero the combination of jobs is invalid.
+        # We test this above but no calculations are performed.
+        if not exit_status:
+
+            # Check the returned singular values
+            sigma = (work[0] / work[1]) * sva[:n]
+            assert_allclose(sigma, svd(A, compute_uv=False), atol=atol)
+
+            if jobu == 1:
+                # If JOBU = 'F', then u contains the M-by-M matrix of
+                # the left singular vectors, including an ONB of the orthogonal
+                # complement of the Range(A)
+                # However, to recalculate A we are concerned about the
+                # first n singular values and so can ignore the latter.
+                # TODO: Add a test for ONB?
+                u = u[:, :n]
+
+            if lsvec and rsvec:
+                assert_allclose(u @ np.diag(sigma) @ v.conj().T, A, atol=atol)
+            if lsvec:
+                assert_allclose(u.conj().T @ u, np.identity(n), atol=atol)
+            if rsvec:
+                assert_allclose(v.conj().T @ v, np.identity(n), atol=atol)
+
+            assert_equal(iwork[0], np.linalg.matrix_rank(A))
+            assert_equal(iwork[1], np.count_nonzero(sigma))
+            # iwork[2] is non-zero if requested accuracy is not warranted for
+            # the data. This should never occur for these tests.
+            assert_equal(iwork[2], 0)
+
+
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+def test_gejsv_edge_arguments(dtype):
+    """Test edge arguments return expected status"""
+    gejsv = get_lapack_funcs('gejsv', dtype=dtype)
+
+    # scalar A
+    sva, u, v, work, iwork, info = gejsv(1.)
+    assert_equal(info, 0)
+    assert_equal(u.shape, (1, 1))
+    assert_equal(v.shape, (1, 1))
+    assert_equal(sva, np.array([1.], dtype=dtype))
+
+    # 1d A
+    A = np.ones((1,), dtype=dtype)
+    sva, u, v, work, iwork, info = gejsv(A)
+    assert_equal(info, 0)
+    assert_equal(u.shape, (1, 1))
+    assert_equal(v.shape, (1, 1))
+    assert_equal(sva, np.array([1.], dtype=dtype))
+
+    # 2d empty A
+    A = np.ones((1, 0), dtype=dtype)
+    sva, u, v, work, iwork, info = gejsv(A)
+    assert_equal(info, 0)
+    assert_equal(u.shape, (1, 0))
+    assert_equal(v.shape, (1, 0))
+    assert_equal(sva, np.array([], dtype=dtype))
+
+    # make sure "overwrite_a" is respected - user reported in gh-13191
+    A = np.sin(np.arange(100).reshape(10, 10)).astype(dtype)
+    A = np.asfortranarray(A + A.T)  # make it symmetric and column major
+    Ac = A.copy('A')
+    _ = gejsv(A)
+    assert_allclose(A, Ac)
+
+
+@pytest.mark.parametrize(('kwargs'),
+                         ({'joba': 9},
+                          {'jobu': 9},
+                          {'jobv': 9},
+                          {'jobr': 9},
+                          {'jobt': 9},
+                          {'jobp': 9})
+                         )
+def test_gejsv_invalid_job_arguments(kwargs):
+    """Test invalid job arguments raise an Exception"""
+    A = np.ones((2, 2), dtype=float)
+    gejsv = get_lapack_funcs('gejsv', dtype=float)
+    assert_raises(Exception, gejsv, A, **kwargs)
+
+
+@pytest.mark.parametrize("A,sva_expect,u_expect,v_expect",
+                         [(np.array([[2.27, -1.54, 1.15, -1.94],
+                                     [0.28, -1.67, 0.94, -0.78],
+                                     [-0.48, -3.09, 0.99, -0.21],
+                                     [1.07, 1.22, 0.79, 0.63],
+                                     [-2.35, 2.93, -1.45, 2.30],
+                                     [0.62, -7.39, 1.03, -2.57]]),
+                           np.array([9.9966, 3.6831, 1.3569, 0.5000]),
+                           np.array([[0.2774, -0.6003, -0.1277, 0.1323],
+                                     [0.2020, -0.0301, 0.2805, 0.7034],
+                                     [0.2918, 0.3348, 0.6453, 0.1906],
+                                     [-0.0938, -0.3699, 0.6781, -0.5399],
+                                     [-0.4213, 0.5266, 0.0413, -0.0575],
+                                     [0.7816, 0.3353, -0.1645, -0.3957]]),
+                           np.array([[0.1921, -0.8030, 0.0041, -0.5642],
+                                     [-0.8794, -0.3926, -0.0752, 0.2587],
+                                     [0.2140, -0.2980, 0.7827, 0.5027],
+                                     [-0.3795, 0.3351, 0.6178, -0.6017]]))])
+def test_gejsv_NAG(A, sva_expect, u_expect, v_expect):
+    """
+    This test implements the example found in the NAG manual, f08khf.
+    An example was not found for the complex case.
+    """
+    # NAG manual provides accuracy up to 4 decimals
+    atol = 1e-4
+    gejsv = get_lapack_funcs('gejsv', dtype=A.dtype)
+
+    sva, u, v, work, iwork, info = gejsv(A)
+
+    assert_allclose(sva_expect, sva, atol=atol)
+    assert_allclose(u_expect, u, atol=atol)
+    assert_allclose(v_expect, v, atol=atol)
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+def test_gttrf_gttrs(dtype):
+    # The test uses ?gttrf and ?gttrs to solve a random system for each dtype,
+    # tests that the output of ?gttrf define LU matrices, that input
+    # parameters are unmodified, transposal options function correctly, that
+    # incompatible matrix shapes raise an error, and singular matrices return
+    # non zero info.
+
+    rng = np.random.RandomState(42)
+    n = 10
+    atol = 100 * np.finfo(dtype).eps
+
+    # create the matrix in accordance with the data type
+    du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+    dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+
+    diag_cpy = [dl.copy(), d.copy(), du.copy()]
+
+    A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1)
+    x = np.random.rand(n)
+    b = A @ x
+
+    gttrf, gttrs = get_lapack_funcs(('gttrf', 'gttrs'), dtype=dtype)
+
+    _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du)
+    # test to assure that the inputs of ?gttrf are unmodified
+    assert_array_equal(dl, diag_cpy[0])
+    assert_array_equal(d, diag_cpy[1])
+    assert_array_equal(du, diag_cpy[2])
+
+    # generate L and U factors from ?gttrf return values
+    # L/U are lower/upper triangular by construction (initially and at end)
+    U = np.diag(_d, 0) + np.diag(_du, 1) + np.diag(du2, 2)
+    L = np.eye(n, dtype=dtype)
+
+    for i, m in enumerate(_dl):
+        # L is given in a factored form.
+        # See
+        # www.hpcavf.uclan.ac.uk/softwaredoc/sgi_scsl_html/sgi_html/ch03.html
+        piv = ipiv[i] - 1
+        # right multiply by permutation matrix
+        L[:, [i, piv]] = L[:, [piv, i]]
+        # right multiply by Li, rank-one modification of identity
+        L[:, i] += L[:, i+1]*m
+
+    # one last permutation
+    i, piv = -1, ipiv[-1] - 1
+    # right multiply by final permutation matrix
+    L[:, [i, piv]] = L[:, [piv, i]]
+
+    # check that the outputs of ?gttrf define an LU decomposition of A
+    assert_allclose(A, L @ U, atol=atol)
+
+    b_cpy = b.copy()
+    x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b)
+    # test that the inputs of ?gttrs are unmodified
+    assert_array_equal(b, b_cpy)
+    # test that the result of ?gttrs matches the expected input
+    assert_allclose(x, x_gttrs, atol=atol)
+
+    # test that ?gttrf and ?gttrs work with transposal options
+    if dtype in REAL_DTYPES:
+        trans = "T"
+        b_trans = A.T @ x
+    else:
+        trans = "C"
+        b_trans = A.conj().T @ x
+
+    x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b_trans, trans=trans)
+    assert_allclose(x, x_gttrs, atol=atol)
+
+    # test that ValueError is raised with incompatible matrix shapes
+    with assert_raises(ValueError):
+        gttrf(dl[:-1], d, du)
+    with assert_raises(ValueError):
+        gttrf(dl, d[:-1], du)
+    with assert_raises(ValueError):
+        gttrf(dl, d, du[:-1])
+
+    # test that matrix of size n=2 raises exception
+    with assert_raises(ValueError):
+        gttrf(dl[0], d[:1], du[0])
+
+    # test that singular (row of all zeroes) matrix fails via info
+    du[0] = 0
+    d[0] = 0
+    __dl, __d, __du, _du2, _ipiv, _info = gttrf(dl, d, du)
+    np.testing.assert_(__d[info - 1] == 0, (f"?gttrf: _d[info-1] is {__d[info - 1]},"
+                                            " not the illegal value :0."))
+
+
+@pytest.mark.parametrize("du, d, dl, du_exp, d_exp, du2_exp, ipiv_exp, b, x",
+                         [(np.array([2.1, -1.0, 1.9, 8.0]),
+                             np.array([3.0, 2.3, -5.0, -.9, 7.1]),
+                             np.array([3.4, 3.6, 7.0, -6.0]),
+                             np.array([2.3, -5, -.9, 7.1]),
+                             np.array([3.4, 3.6, 7, -6, -1.015373]),
+                             np.array([-1, 1.9, 8]),
+                             np.array([2, 3, 4, 5, 5]),
+                             np.array([[2.7, 6.6],
+                                       [-0.5, 10.8],
+                                       [2.6, -3.2],
+                                       [0.6, -11.2],
+                                       [2.7, 19.1]
+                                       ]),
+                             np.array([[-4, 5],
+                                       [7, -4],
+                                       [3, -3],
+                                       [-4, -2],
+                                       [-3, 1]])),
+                          (
+                             np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]),
+                             np.array([-1.3 + 1.3j, -1.3 + 1.3j,
+                                       -1.3 + 3.3j, - .3 + 4.3j,
+                                       -3.3 + 1.3j]),
+                             np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]),
+                             # du exp
+                             np.array([-1.3 + 1.3j, -1.3 + 3.3j,
+                                       -0.3 + 4.3j, -3.3 + 1.3j]),
+                             np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j,
+                                       -1.3399 + 0.2875j]),
+                             np.array([2 + 1j, -1 + 1j, 1 - 1j]),
+                             np.array([2, 3, 4, 5, 5]),
+                             np.array([[2.4 - 5j, 2.7 + 6.9j],
+                                       [3.4 + 18.2j, - 6.9 - 5.3j],
+                                       [-14.7 + 9.7j, - 6 - .6j],
+                                       [31.9 - 7.7j, -3.9 + 9.3j],
+                                       [-1 + 1.6j, -3 + 12.2j]]),
+                             np.array([[1 + 1j, 2 - 1j],
+                                       [3 - 1j, 1 + 2j],
+                                       [4 + 5j, -1 + 1j],
+                                       [-1 - 2j, 2 + 1j],
+                                       [1 - 1j, 2 - 2j]])
+                            )])
+def test_gttrf_gttrs_NAG_f07cdf_f07cef_f07crf_f07csf(du, d, dl, du_exp, d_exp,
+                                                     du2_exp, ipiv_exp, b, x):
+    # test to assure that wrapper is consistent with NAG Library Manual Mark 26
+    # example problems: f07cdf and f07cef (real)
+    # examples: f07crf and f07csf (complex)
+    # (Links may expire, so search for "NAG Library Manual Mark 26" online)
+
+    gttrf, gttrs = get_lapack_funcs(('gttrf', "gttrs"), (du[0], du[0]))
+
+    _dl, _d, _du, du2, ipiv, info = gttrf(dl, d, du)
+    assert_allclose(du2, du2_exp)
+    assert_allclose(_du, du_exp)
+    assert_allclose(_d, d_exp, atol=1e-4)  # NAG examples provide 4 decimals.
+    assert_allclose(ipiv, ipiv_exp)
+
+    x_gttrs, info = gttrs(_dl, _d, _du, du2, ipiv, b)
+
+    assert_allclose(x_gttrs, x)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('norm', ['1', 'I', 'O'])
+@pytest.mark.parametrize('n', [3, 10])
+def test_gtcon(dtype, norm, n):
+    rng = np.random.default_rng(23498324)
+
+    d = rng.random(n) + rng.random(n)*1j
+    dl = rng.random(n - 1) + rng.random(n - 1)*1j
+    du = rng.random(n - 1) + rng.random(n - 1)*1j
+    A = np.diag(d) + np.diag(dl, -1) + np.diag(du, 1)
+    if np.issubdtype(dtype, np.floating):
+        A, d, dl, du = A.real, d.real, dl.real, du.real
+    A, d, dl, du = A.astype(dtype), d.astype(dtype), dl.astype(dtype), du.astype(dtype)
+
+    anorm = np.abs(A).sum(axis=0).max()
+
+    gttrf, gtcon = get_lapack_funcs(('gttrf', 'gtcon'), (A,))
+    dl, d, du, du2, ipiv, info = gttrf(dl, d, du)
+    res, _ = gtcon(dl, d, du, du2, ipiv, anorm, norm=norm)
+
+    gecon, getrf = get_lapack_funcs(('gecon', 'getrf'), (A,))
+    lu, ipvt, info = getrf(A)
+    ref, _ = gecon(lu, anorm, norm=norm)
+
+    rtol = np.finfo(dtype).eps**0.75
+    assert_allclose(res, ref, rtol=rtol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('shape', [(3, 7), (7, 3), (2**18, 2**18)])
+def test_geqrfp_lwork(dtype, shape):
+    geqrfp_lwork = get_lapack_funcs(('geqrfp_lwork'), dtype=dtype)
+    m, n = shape
+    lwork, info = geqrfp_lwork(m=m, n=n)
+    assert_equal(info, 0)
+
+
+@pytest.mark.parametrize("ddtype,dtype",
+                         zip(REAL_DTYPES + REAL_DTYPES, DTYPES))
+def test_pttrf_pttrs(ddtype, dtype):
+    rng = np.random.RandomState(42)
+    # set test tolerance appropriate for dtype
+    atol = 100*np.finfo(dtype).eps
+    # n is the length diagonal of A
+    n = 10
+    # create diagonals according to size and dtype
+
+    # diagonal d should always be real.
+    # add 4 to d so it will be dominant for all dtypes
+    d = generate_random_dtype_array((n,), ddtype, rng) + 4
+    # diagonal e may be real or complex.
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+
+    # assemble diagonals together into matrix
+    A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+    # store a copy of diagonals to later verify
+    diag_cpy = [d.copy(), e.copy()]
+
+    pttrf = get_lapack_funcs('pttrf', dtype=dtype)
+
+    _d, _e, info = pttrf(d, e)
+    # test to assure that the inputs of ?pttrf are unmodified
+    assert_array_equal(d, diag_cpy[0])
+    assert_array_equal(e, diag_cpy[1])
+    assert_equal(info, 0, err_msg=f"pttrf: info = {info}, should be 0")
+
+    # test that the factors from pttrf can be recombined to make A
+    L = np.diag(_e, -1) + np.diag(np.ones(n))
+    D = np.diag(_d)
+
+    assert_allclose(A, L@D@L.conjugate().T, atol=atol)
+
+    # generate random solution x
+    x = generate_random_dtype_array((n,), dtype, rng)
+    # determine accompanying b to get soln x
+    b = A@x
+
+    # determine _x from pttrs
+    pttrs = get_lapack_funcs('pttrs', dtype=dtype)
+    _x, info = pttrs(_d, _e.conj(), b)
+    assert_equal(info, 0, err_msg=f"pttrs: info = {info}, should be 0")
+
+    # test that _x from pttrs matches the expected x
+    assert_allclose(x, _x, atol=atol)
+
+
+@pytest.mark.parametrize("ddtype,dtype",
+                         zip(REAL_DTYPES + REAL_DTYPES, DTYPES))
+def test_pttrf_pttrs_errors_incompatible_shape(ddtype, dtype):
+    n = 10
+    rng = np.random.RandomState(1234)
+    pttrf = get_lapack_funcs('pttrf', dtype=dtype)
+    d = generate_random_dtype_array((n,), ddtype, rng) + 2
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    # test that ValueError is raised with incompatible matrix shapes
+    assert_raises(ValueError, pttrf, d[:-1], e)
+    assert_raises(ValueError, pttrf, d, e[:-1])
+
+
+@pytest.mark.parametrize("ddtype,dtype",
+                         zip(REAL_DTYPES + REAL_DTYPES, DTYPES))
+def test_pttrf_pttrs_errors_singular_nonSPD(ddtype, dtype):
+    n = 10
+    rng = np.random.RandomState(42)
+    pttrf = get_lapack_funcs('pttrf', dtype=dtype)
+    d = generate_random_dtype_array((n,), ddtype, rng) + 2
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    # test that singular (row of all zeroes) matrix fails via info
+    d[0] = 0
+    e[0] = 0
+    _d, _e, info = pttrf(d, e)
+    assert_equal(_d[info - 1], 0,
+                 f"?pttrf: _d[info-1] is {_d[info - 1]}, not the illegal value :0.")
+
+    # test with non-spd matrix
+    d = generate_random_dtype_array((n,), ddtype, rng)
+    _d, _e, info = pttrf(d, e)
+    assert_(info != 0, "?pttrf should fail with non-spd matrix, but didn't")
+
+
+@pytest.mark.parametrize(("d, e, d_expect, e_expect, b, x_expect"), [
+                         (np.array([4, 10, 29, 25, 5]),
+                          np.array([-2, -6, 15, 8]),
+                          np.array([4, 9, 25, 16, 1]),
+                          np.array([-.5, -.6667, .6, .5]),
+                          np.array([[6, 10], [9, 4], [2, 9], [14, 65],
+                                    [7, 23]]),
+                          np.array([[2.5, 2], [2, -1], [1, -3], [-1, 6],
+                                    [3, -5]])
+                          ), (
+                          np.array([16, 41, 46, 21]),
+                          np.array([16 + 16j, 18 - 9j, 1 - 4j]),
+                          np.array([16, 9, 1, 4]),
+                          np.array([1+1j, 2-1j, 1-4j]),
+                          np.array([[64+16j, -16-32j], [93+62j, 61-66j],
+                                    [78-80j, 71-74j], [14-27j, 35+15j]]),
+                          np.array([[2+1j, -3-2j], [1+1j, 1+1j], [1-2j, 1-2j],
+                                    [1-1j, 2+1j]])
+                         )])
+def test_pttrf_pttrs_NAG(d, e, d_expect, e_expect, b, x_expect):
+    # test to assure that wrapper is consistent with NAG Manual Mark 26
+    # example problems: f07jdf and f07jef (real)
+    # examples: f07jrf and f07csf (complex)
+    # NAG examples provide 4 decimals.
+    # (Links expire, so please search for "NAG Library Manual Mark 26" online)
+
+    atol = 1e-4
+    pttrf = get_lapack_funcs('pttrf', dtype=e[0])
+    _d, _e, info = pttrf(d, e)
+    assert_allclose(_d, d_expect, atol=atol)
+    assert_allclose(_e, e_expect, atol=atol)
+
+    pttrs = get_lapack_funcs('pttrs', dtype=e[0])
+    _x, info = pttrs(_d, _e.conj(), b)
+    assert_allclose(_x, x_expect, atol=atol)
+
+    # also test option `lower`
+    if e.dtype in COMPLEX_DTYPES:
+        _x, info = pttrs(_d, _e, b, lower=1)
+        assert_allclose(_x, x_expect, atol=atol)
+
+
+def pteqr_get_d_e_A_z(dtype, realtype, n, compute_z):
+    # used by ?pteqr tests to build parameters
+    # returns tuple of (d, e, A, z)
+    rng = np.random.RandomState(42)
+    if compute_z == 1:
+        # build Hermitian A from Q**T * tri * Q = A by creating Q and tri
+        A_eig = generate_random_dtype_array((n, n), dtype, rng)
+        A_eig = A_eig + np.diag(np.zeros(n) + 4*n)
+        A_eig = (A_eig + A_eig.conj().T) / 2
+        # obtain right eigenvectors (orthogonal)
+        vr = eigh(A_eig)[1]
+        # create tridiagonal matrix
+        d = generate_random_dtype_array((n,), realtype, rng) + 4
+        e = generate_random_dtype_array((n-1,), realtype, rng)
+        tri = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
+        # Build A using these factors that sytrd would: (Q**T * tri * Q = A)
+        A = vr @ tri @ vr.conj().T
+        # vr is orthogonal
+        z = vr
+
+    else:
+        # d and e are always real per lapack docs.
+        d = generate_random_dtype_array((n,), realtype, rng)
+        e = generate_random_dtype_array((n-1,), realtype, rng)
+
+        # make SPD
+        d = d + 4
+        A = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
+        z = np.diag(d) + np.diag(e, -1) + np.diag(e, 1)
+    return (d, e, A, z)
+
+
+@pytest.mark.parametrize("dtype,realtype",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr(dtype, realtype, compute_z):
+    '''
+    Tests the ?pteqr lapack routine for all dtypes and compute_z parameters.
+    It generates random SPD matrix diagonals d and e, and then confirms
+    correct eigenvalues with scipy.linalg.eig. With applicable compute_z=2 it
+    tests that z can reform A.
+    '''
+    seed(42)
+    atol = 1000*np.finfo(dtype).eps
+    pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+
+    n = 10
+
+    d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+
+    d_pteqr, e_pteqr, z_pteqr, info = pteqr(d=d, e=e, z=z, compute_z=compute_z)
+    assert_equal(info, 0, f"info = {info}, should be 0.")
+
+    # compare the routine's eigenvalues with scipy.linalg.eig's.
+    assert_allclose(np.sort(eigh(A)[0]), np.sort(d_pteqr), atol=atol)
+
+    if compute_z:
+        # verify z_pteqr as orthogonal
+        assert_allclose(z_pteqr @ np.conj(z_pteqr).T, np.identity(n),
+                        atol=atol)
+        # verify that z_pteqr recombines to A
+        assert_allclose(z_pteqr @ np.diag(d_pteqr) @ np.conj(z_pteqr).T,
+                        A, atol=atol)
+
+
+@pytest.mark.parametrize("dtype,realtype",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr_error_non_spd(dtype, realtype, compute_z):
+    seed(42)
+    pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+
+    n = 10
+    d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+
+    # test with non-spd matrix
+    d_pteqr, e_pteqr, z_pteqr, info = pteqr(d - 4, e, z=z, compute_z=compute_z)
+    assert info > 0
+
+
+@pytest.mark.parametrize("dtype,realtype",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr_raise_error_wrong_shape(dtype, realtype, compute_z):
+    seed(42)
+    pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+    n = 10
+    d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+    # test with incorrect/incompatible array sizes
+    assert_raises(ValueError, pteqr, d[:-1], e, z=z, compute_z=compute_z)
+    assert_raises(ValueError, pteqr, d, e[:-1], z=z, compute_z=compute_z)
+    if compute_z:
+        assert_raises(ValueError, pteqr, d, e, z=z[:-1], compute_z=compute_z)
+
+
+@pytest.mark.parametrize("dtype,realtype",
+                         zip(DTYPES, REAL_DTYPES + REAL_DTYPES))
+@pytest.mark.parametrize("compute_z", range(3))
+def test_pteqr_error_singular(dtype, realtype, compute_z):
+    seed(42)
+    pteqr = get_lapack_funcs(('pteqr'), dtype=dtype)
+    n = 10
+    d, e, A, z = pteqr_get_d_e_A_z(dtype, realtype, n, compute_z)
+    # test with singular matrix
+    d[0] = 0
+    e[0] = 0
+    d_pteqr, e_pteqr, z_pteqr, info = pteqr(d, e, z=z, compute_z=compute_z)
+    assert info > 0
+
+
+@pytest.mark.parametrize("compute_z,d,e,d_expect,z_expect",
+                         [(2,  # "I"
+                           np.array([4.16, 5.25, 1.09, .62]),
+                           np.array([3.17, -.97, .55]),
+                           np.array([8.0023, 1.9926, 1.0014, 0.1237]),
+                           np.array([[0.6326, 0.6245, -0.4191, 0.1847],
+                                     [0.7668, -0.4270, 0.4176, -0.2352],
+                                     [-0.1082, 0.6071, 0.4594, -0.6393],
+                                     [-0.0081, 0.2432, 0.6625, 0.7084]])),
+                          ])
+def test_pteqr_NAG_f08jgf(compute_z, d, e, d_expect, z_expect):
+    '''
+    Implements real (f08jgf) example from NAG Manual Mark 26.
+    Tests for correct outputs.
+    '''
+    # the NAG manual has 4 decimals accuracy
+    atol = 1e-4
+    pteqr = get_lapack_funcs(('pteqr'), dtype=d.dtype)
+
+    z = np.diag(d) + np.diag(e, 1) + np.diag(e, -1)
+    _d, _e, _z, info = pteqr(d=d, e=e, z=z, compute_z=compute_z)
+    assert_allclose(_d, d_expect, atol=atol)
+    assert_allclose(np.abs(_z), np.abs(z_expect), atol=atol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('matrix_size', [(3, 4), (7, 6), (6, 6)])
+def test_geqrfp(dtype, matrix_size):
+    # Tests for all dytpes, tall, wide, and square matrices.
+    # Using the routine with random matrix A, Q and R are obtained and then
+    # tested such that R is upper triangular and non-negative on the diagonal,
+    # and Q is an orthogonal matrix. Verifies that A=Q@R. It also
+    # tests against a matrix that for which the  linalg.qr method returns
+    # negative diagonals, and for error messaging.
+
+    # set test tolerance appropriate for dtype
+    rng = np.random.RandomState(42)
+    rtol = 250*np.finfo(dtype).eps
+    atol = 100*np.finfo(dtype).eps
+    # get appropriate ?geqrfp for dtype
+    geqrfp = get_lapack_funcs(('geqrfp'), dtype=dtype)
+    gqr = get_lapack_funcs(("orgqr"), dtype=dtype)
+
+    m, n = matrix_size
+
+    # create random matrix of dimensions m x n
+    A = generate_random_dtype_array((m, n), dtype=dtype, rng=rng)
+    # create qr matrix using geqrfp
+    qr_A, tau, info = geqrfp(A)
+
+    # obtain r from the upper triangular area
+    r = np.triu(qr_A)
+
+    # obtain q from the orgqr lapack routine
+    # based on linalg.qr's extraction strategy of q with orgqr
+
+    if m > n:
+        # this adds an extra column to the end of qr_A
+        # let qqr be an empty m x m matrix
+        qqr = np.zeros((m, m), dtype=dtype)
+        # set first n columns of qqr to qr_A
+        qqr[:, :n] = qr_A
+        # determine q from this qqr
+        # note that m is a sufficient for lwork based on LAPACK documentation
+        q = gqr(qqr, tau=tau, lwork=m)[0]
+    else:
+        q = gqr(qr_A[:, :m], tau=tau, lwork=m)[0]
+
+    # test that q and r still make A
+    assert_allclose(q@r, A, rtol=rtol)
+    # ensure that q is orthogonal (that q @ transposed q is the identity)
+    assert_allclose(np.eye(q.shape[0]), q@(q.conj().T), rtol=rtol,
+                    atol=atol)
+    # ensure r is upper tri by comparing original r to r as upper triangular
+    assert_allclose(r, np.triu(r), rtol=rtol)
+    # make sure diagonals of r are positive for this random solution
+    assert_(np.all(np.diag(r) > np.zeros(len(np.diag(r)))))
+    # ensure that info is zero for this success
+    assert_(info == 0)
+
+    # test that this routine gives r diagonals that are positive for a
+    # matrix that returns negatives in the diagonal with scipy.linalg.rq
+    A_negative = generate_random_dtype_array((n, m), dtype=dtype, rng=rng) * -1
+    r_rq_neg, q_rq_neg = qr(A_negative)
+    rq_A_neg, tau_neg, info_neg = geqrfp(A_negative)
+    # assert that any of the entries on the diagonal from linalg.qr
+    #   are negative and that all of geqrfp are positive.
+    assert_(np.any(np.diag(r_rq_neg) < 0) and
+            np.all(np.diag(r) > 0))
+
+
+def test_geqrfp_errors_with_empty_array():
+    # check that empty array raises good error message
+    A_empty = np.array([])
+    geqrfp = get_lapack_funcs('geqrfp', dtype=A_empty.dtype)
+    assert_raises(Exception, geqrfp, A_empty)
+
+
+@pytest.mark.parametrize("driver", ['ev', 'evd', 'evr', 'evx'])
+@pytest.mark.parametrize("pfx", ['sy', 'he'])
+def test_standard_eigh_lworks(pfx, driver):
+    n = 1200  # Some sufficiently big arbitrary number
+    dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES
+    sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0])
+    dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1])
+    try:
+        _compute_lwork(sc_dlw, n, lower=1)
+        _compute_lwork(dz_dlw, n, lower=1)
+    except Exception as e:
+        pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}")
+
+
+@pytest.mark.parametrize("driver", ['gv', 'gvx'])
+@pytest.mark.parametrize("pfx", ['sy', 'he'])
+def test_generalized_eigh_lworks(pfx, driver):
+    n = 1200  # Some sufficiently big arbitrary number
+    dtype = REAL_DTYPES if pfx == 'sy' else COMPLEX_DTYPES
+    sc_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[0])
+    dz_dlw = get_lapack_funcs(pfx+driver+'_lwork', dtype=dtype[1])
+    # Shouldn't raise any exceptions
+    try:
+        _compute_lwork(sc_dlw, n, uplo="L")
+        _compute_lwork(dz_dlw, n, uplo="L")
+    except Exception as e:
+        pytest.fail(f"{pfx+driver}_lwork raised unexpected exception: {e}")
+
+
+@pytest.mark.parametrize("dtype_", DTYPES)
+@pytest.mark.parametrize("m", [1, 10, 100, 1000])
+def test_orcsd_uncsd_lwork(dtype_, m):
+    seed(1234)
+    p = randint(0, m)
+    q = m - p
+    pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
+    dlw = pfx + 'csd_lwork'
+    lw = get_lapack_funcs(dlw, dtype=dtype_)
+    lwval = _compute_lwork(lw, m, p, q)
+    lwval = lwval if pfx == 'un' else (lwval,)
+    assert all([x > 0 for x in lwval])
+
+
+@pytest.mark.parametrize("dtype_", DTYPES)
+def test_orcsd_uncsd(dtype_):
+    m, p, q = 250, 80, 170
+
+    pfx = 'or' if dtype_ in REAL_DTYPES else 'un'
+    X = ortho_group.rvs(m) if pfx == 'or' else unitary_group.rvs(m)
+
+    drv, dlw = get_lapack_funcs((pfx + 'csd', pfx + 'csd_lwork'), dtype=dtype_)
+    lwval = _compute_lwork(dlw, m, p, q)
+    lwvals = {'lwork': lwval} if pfx == 'or' else dict(zip(['lwork',
+                                                            'lrwork'], lwval))
+
+    cs11, cs12, cs21, cs22, theta, u1, u2, v1t, v2t, info =\
+        drv(X[:p, :q], X[:p, q:], X[p:, :q], X[p:, q:], **lwvals)
+
+    assert info == 0
+
+    U = block_diag(u1, u2)
+    VH = block_diag(v1t, v2t)
+    r = min(min(p, q), min(m-p, m-q))
+    n11 = min(p, q) - r
+    n12 = min(p, m-q) - r
+    n21 = min(m-p, q) - r
+    n22 = min(m-p, m-q) - r
+
+    S = np.zeros((m, m), dtype=dtype_)
+    one = dtype_(1.)
+    for i in range(n11):
+        S[i, i] = one
+    for i in range(n22):
+        S[p+i, q+i] = one
+    for i in range(n12):
+        S[i+n11+r, i+n11+r+n21+n22+r] = -one
+    for i in range(n21):
+        S[p+n22+r+i, n11+r+i] = one
+
+    for i in range(r):
+        S[i+n11, i+n11] = np.cos(theta[i])
+        S[p+n22+i, i+r+n21+n22] = np.cos(theta[i])
+
+        S[i+n11, i+n11+n21+n22+r] = -np.sin(theta[i])
+        S[p+n22+i, i+n11] = np.sin(theta[i])
+
+    Xc = U @ S @ VH
+    assert_allclose(X, Xc, rtol=0., atol=1e4*np.finfo(dtype_).eps)
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("trans_bool", [False, True])
+@pytest.mark.parametrize("fact", ["F", "N"])
+def test_gtsvx(dtype, trans_bool, fact):
+    """
+    These tests uses ?gtsvx to solve a random Ax=b system for each dtype.
+    It tests that the outputs define an LU matrix, that inputs are unmodified,
+    transposal options, incompatible shapes, singular matrices, and
+    singular factorizations. It parametrizes DTYPES and the 'fact' value along
+    with the fact related inputs.
+    """
+    rng = np.random.RandomState(42)
+    # set test tolerance appropriate for dtype
+    atol = 100 * np.finfo(dtype).eps
+    # obtain routine
+    gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
+    # Generate random tridiagonal matrix A
+    n = 10
+    dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+    du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
+    # generate random solution x
+    x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    # create b from x for equation Ax=b
+    trans = ("T" if dtype in REAL_DTYPES else "C") if trans_bool else "N"
+    b = (A.conj().T if trans_bool else A) @ x
+
+    # store a copy of the inputs to check they haven't been modified later
+    inputs_cpy = [dl.copy(), d.copy(), du.copy(), b.copy()]
+
+    # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
+    dlf_, df_, duf_, du2f_, ipiv_, info_ = \
+        gttrf(dl, d, du) if fact == 'F' else [None]*6
+
+    gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+    dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+    assert_(info == 0, f"?gtsvx info = {info}, should be zero")
+
+    # assure that inputs are unmodified
+    assert_array_equal(dl, inputs_cpy[0])
+    assert_array_equal(d, inputs_cpy[1])
+    assert_array_equal(du, inputs_cpy[2])
+    assert_array_equal(b, inputs_cpy[3])
+
+    # test that x_soln matches the expected x
+    assert_allclose(x, x_soln, atol=atol)
+
+    # assert that the outputs are of correct type or shape
+    # rcond should be a scalar
+    assert_(hasattr(rcond, "__len__") is not True,
+            f"rcond should be scalar but is {rcond}")
+    # ferr should be length of # of cols in x
+    assert_(ferr.shape[0] == b.shape[1], (f"ferr.shape is {ferr.shape[0]} but should"
+                                          f" be {b.shape[1]}"))
+    # berr should be length of # of cols in x
+    assert_(berr.shape[0] == b.shape[1], (f"berr.shape is {berr.shape[0]} but should"
+                                          f" be {b.shape[1]}"))
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("trans_bool", [0, 1])
+@pytest.mark.parametrize("fact", ["F", "N"])
+def test_gtsvx_error_singular(dtype, trans_bool, fact):
+    rng = np.random.RandomState(42)
+    # obtain routine
+    gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
+    # Generate random tridiagonal matrix A
+    n = 10
+    dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+    du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
+    # generate random solution x
+    x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    # create b from x for equation Ax=b
+    trans = "T" if dtype in REAL_DTYPES else "C"
+    b = (A.conj().T if trans_bool else A) @ x
+
+    # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
+    dlf_, df_, duf_, du2f_, ipiv_, info_ = \
+        gttrf(dl, d, du) if fact == 'F' else [None]*6
+
+    gtsvx_out = gtsvx(dl, d, du, b, fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+    dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+    # test with singular matrix
+    # no need to test inputs with fact "F" since ?gttrf already does.
+    if fact == "N":
+        # Construct a singular example manually
+        d[-1] = 0
+        dl[-1] = 0
+        # solve using routine
+        gtsvx_out = gtsvx(dl, d, du, b)
+        dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+        # test for the singular matrix.
+        assert info > 0, "info should be > 0 for singular matrix"
+
+    elif fact == 'F':
+        # assuming that a singular factorization is input
+        df_[-1] = 0
+        duf_[-1] = 0
+        du2f_[-1] = 0
+
+        gtsvx_out = gtsvx(dl, d, du, b, fact=fact, dlf=dlf_, df=df_, duf=duf_,
+                          du2=du2f_, ipiv=ipiv_)
+        dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+        # info should not be zero and should provide index of illegal value
+        assert info > 0, "info should be > 0 for singular matrix"
+
+
+@pytest.mark.parametrize("dtype", DTYPES*2)
+@pytest.mark.parametrize("trans_bool", [False, True])
+@pytest.mark.parametrize("fact", ["F", "N"])
+def test_gtsvx_error_incompatible_size(dtype, trans_bool, fact):
+    rng = np.random.RandomState(42)
+    # obtain routine
+    gtsvx, gttrf = get_lapack_funcs(('gtsvx', 'gttrf'), dtype=dtype)
+    # Generate random tridiagonal matrix A
+    n = 10
+    dl = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    d = generate_random_dtype_array((n,), dtype=dtype, rng=rng)
+    du = generate_random_dtype_array((n-1,), dtype=dtype, rng=rng)
+    A = np.diag(dl, -1) + np.diag(d) + np.diag(du, 1)
+    # generate random solution x
+    x = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    # create b from x for equation Ax=b
+    trans = "T" if dtype in REAL_DTYPES else "C"
+    b = (A.conj().T if trans_bool else A) @ x
+
+    # set these to None if fact = 'N', or the output of gttrf is fact = 'F'
+    dlf_, df_, duf_, du2f_, ipiv_, info_ = \
+        gttrf(dl, d, du) if fact == 'F' else [None]*6
+
+    if fact == "N":
+        assert_raises(ValueError, gtsvx, dl[:-1], d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d[:-1], du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d, du[:-1], b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(Exception, gtsvx, dl, d, du, b[:-1],
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+    else:
+        assert_raises(ValueError, gtsvx, dl, d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_[:-1], df=df_,
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_[:-1],
+                      duf=duf_, du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_[:-1], du2=du2f_, ipiv=ipiv_)
+        assert_raises(ValueError, gtsvx, dl, d, du, b,
+                      fact=fact, trans=trans, dlf=dlf_, df=df_,
+                      duf=duf_, du2=du2f_[:-1], ipiv=ipiv_)
+
+
+@pytest.mark.parametrize("du,d,dl,b,x",
+                         [(np.array([2.1, -1.0, 1.9, 8.0]),
+                           np.array([3.0, 2.3, -5.0, -0.9, 7.1]),
+                           np.array([3.4, 3.6, 7.0, -6.0]),
+                           np.array([[2.7, 6.6], [-.5, 10.8], [2.6, -3.2],
+                                     [.6, -11.2], [2.7, 19.1]]),
+                           np.array([[-4, 5], [7, -4], [3, -3], [-4, -2],
+                                     [-3, 1]])),
+                          (np.array([2 - 1j, 2 + 1j, -1 + 1j, 1 - 1j]),
+                           np.array([-1.3 + 1.3j, -1.3 + 1.3j, -1.3 + 3.3j,
+                                     -.3 + 4.3j, -3.3 + 1.3j]),
+                           np.array([1 - 2j, 1 + 1j, 2 - 3j, 1 + 1j]),
+                           np.array([[2.4 - 5j, 2.7 + 6.9j],
+                                     [3.4 + 18.2j, -6.9 - 5.3j],
+                                     [-14.7 + 9.7j, -6 - .6j],
+                                     [31.9 - 7.7j, -3.9 + 9.3j],
+                                     [-1 + 1.6j, -3 + 12.2j]]),
+                           np.array([[1 + 1j, 2 - 1j], [3 - 1j, 1 + 2j],
+                                     [4 + 5j, -1 + 1j], [-1 - 2j, 2 + 1j],
+                                     [1 - 1j, 2 - 2j]]))])
+def test_gtsvx_NAG(du, d, dl, b, x):
+    # Test to ensure wrapper is consistent with NAG Manual Mark 26
+    # example problems: real (f07cbf) and complex (f07cpf)
+    gtsvx = get_lapack_funcs('gtsvx', dtype=d.dtype)
+
+    gtsvx_out = gtsvx(dl, d, du, b)
+    dlf, df, duf, du2f, ipiv, x_soln, rcond, ferr, berr, info = gtsvx_out
+
+    assert_array_almost_equal(x, x_soln)
+
+
+@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES
+                                               + REAL_DTYPES))
+@pytest.mark.parametrize("fact,df_de_lambda",
+                         [("F",
+                           lambda d, e: get_lapack_funcs('pttrf',
+                                                         dtype=e.dtype)(d, e)),
+                          ("N", lambda d, e: (None, None, None))])
+def test_ptsvx(dtype, realtype, fact, df_de_lambda):
+    '''
+    This tests the ?ptsvx lapack routine wrapper to solve a random system
+    Ax = b for all dtypes and input variations. Tests for: unmodified
+    input parameters, fact options, incompatible matrix shapes raise an error,
+    and singular matrices return info of illegal value.
+    '''
+    rng = np.random.RandomState(42)
+    # set test tolerance appropriate for dtype
+    atol = 100 * np.finfo(dtype).eps
+    ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
+    n = 5
+    # create diagonals according to size and dtype
+    d = generate_random_dtype_array((n,), realtype, rng) + 4
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+    x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    b = A @ x_soln
+
+    # use lambda to determine what df, ef are
+    df, ef, info = df_de_lambda(d, e)
+
+    # create copy to later test that they are unmodified
+    diag_cpy = [d.copy(), e.copy(), b.copy()]
+
+    # solve using routine
+    df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact,
+                                               df=df, ef=ef)
+    # d, e, and b should be unmodified
+    assert_array_equal(d, diag_cpy[0])
+    assert_array_equal(e, diag_cpy[1])
+    assert_array_equal(b, diag_cpy[2])
+    assert_(info == 0, f"info should be 0 but is {info}.")
+    assert_array_almost_equal(x_soln, x)
+
+    # test that the factors from ptsvx can be recombined to make A
+    L = np.diag(ef, -1) + np.diag(np.ones(n))
+    D = np.diag(df)
+    assert_allclose(A, L@D@(np.conj(L).T), atol=atol)
+
+    # assert that the outputs are of correct type or shape
+    # rcond should be a scalar
+    assert not hasattr(rcond, "__len__"), \
+        f"rcond should be scalar but is {rcond}"
+    # ferr should be length of # of cols in x
+    assert_(ferr.shape == (2,), (f"ferr.shape is {ferr.shape} but should be "
+                                 "({x_soln.shape[1]},)"))
+    # berr should be length of # of cols in x
+    assert_(berr.shape == (2,), (f"berr.shape is {berr.shape} but should be "
+                                 "({x_soln.shape[1]},)"))
+
+
+@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES
+                                               + REAL_DTYPES))
+@pytest.mark.parametrize("fact,df_de_lambda",
+                         [("F",
+                           lambda d, e: get_lapack_funcs('pttrf',
+                                                         dtype=e.dtype)(d, e)),
+                          ("N", lambda d, e: (None, None, None))])
+def test_ptsvx_error_raise_errors(dtype, realtype, fact, df_de_lambda):
+    rng = np.random.RandomState(42)
+    ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
+    n = 5
+    # create diagonals according to size and dtype
+    d = generate_random_dtype_array((n,), realtype, rng) + 4
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+    x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    b = A @ x_soln
+
+    # use lambda to determine what df, ef are
+    df, ef, info = df_de_lambda(d, e)
+
+    # test with malformatted array sizes
+    assert_raises(ValueError, ptsvx, d[:-1], e, b, fact=fact, df=df, ef=ef)
+    assert_raises(ValueError, ptsvx, d, e[:-1], b, fact=fact, df=df, ef=ef)
+    assert_raises(Exception, ptsvx, d, e, b[:-1], fact=fact, df=df, ef=ef)
+
+
+@pytest.mark.parametrize("dtype,realtype", zip(DTYPES, REAL_DTYPES
+                                               + REAL_DTYPES))
+@pytest.mark.parametrize("fact,df_de_lambda",
+                         [("F",
+                           lambda d, e: get_lapack_funcs('pttrf',
+                                                         dtype=e.dtype)(d, e)),
+                          ("N", lambda d, e: (None, None, None))])
+def test_ptsvx_non_SPD_singular(dtype, realtype, fact, df_de_lambda):
+    rng = np.random.RandomState(42)
+    ptsvx = get_lapack_funcs('ptsvx', dtype=dtype)
+    n = 5
+    # create diagonals according to size and dtype
+    d = generate_random_dtype_array((n,), realtype, rng) + 4
+    e = generate_random_dtype_array((n-1,), dtype, rng)
+    A = np.diag(d) + np.diag(e, -1) + np.diag(np.conj(e), 1)
+    x_soln = generate_random_dtype_array((n, 2), dtype=dtype, rng=rng)
+    b = A @ x_soln
+
+    # use lambda to determine what df, ef are
+    df, ef, info = df_de_lambda(d, e)
+
+    if fact == "N":
+        d[3] = 0
+        # obtain new df, ef
+        df, ef, info = df_de_lambda(d, e)
+        # solve using routine
+        df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b)
+        # test for the singular matrix.
+        assert info > 0 and info <= n
+
+        # non SPD matrix
+        d = generate_random_dtype_array((n,), realtype, rng)
+        df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b)
+        assert info > 0 and info <= n
+    else:
+        # assuming that someone is using a singular factorization
+        df, ef, info = df_de_lambda(d, e)
+        df[0] = 0
+        ef[0] = 0
+        df, ef, x, rcond, ferr, berr, info = ptsvx(d, e, b, fact=fact,
+                                                   df=df, ef=ef)
+        assert info > 0
+
+
+@pytest.mark.parametrize('d,e,b,x',
+                         [(np.array([4, 10, 29, 25, 5]),
+                           np.array([-2, -6, 15, 8]),
+                           np.array([[6, 10], [9, 4], [2, 9], [14, 65],
+                                     [7, 23]]),
+                           np.array([[2.5, 2], [2, -1], [1, -3],
+                                     [-1, 6], [3, -5]])),
+                          (np.array([16, 41, 46, 21]),
+                           np.array([16 + 16j, 18 - 9j, 1 - 4j]),
+                           np.array([[64 + 16j, -16 - 32j],
+                                     [93 + 62j, 61 - 66j],
+                                     [78 - 80j, 71 - 74j],
+                                     [14 - 27j, 35 + 15j]]),
+                           np.array([[2 + 1j, -3 - 2j],
+                                     [1 + 1j, 1 + 1j],
+                                     [1 - 2j, 1 - 2j],
+                                     [1 - 1j, 2 + 1j]]))])
+def test_ptsvx_NAG(d, e, b, x):
+    # test to assure that wrapper is consistent with NAG Manual Mark 26
+    # example problems: f07jbf, f07jpf
+    # (Links expire, so please search for "NAG Library Manual Mark 26" online)
+
+    # obtain routine with correct type based on e.dtype
+    ptsvx = get_lapack_funcs('ptsvx', dtype=e.dtype)
+    # solve using routine
+    df, ef, x_ptsvx, rcond, ferr, berr, info = ptsvx(d, e, b)
+    # determine ptsvx's solution and x are the same.
+    assert_array_almost_equal(x, x_ptsvx)
+
+
+@pytest.mark.parametrize('lower', [False, True])
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_pptrs_pptri_pptrf_ppsv_ppcon(dtype, lower):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+    # Manual conversion to/from packed format is feasible here.
+    n, nrhs = 10, 4
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+    b = generate_random_dtype_array([n, nrhs], dtype=dtype, rng=rng)
+
+    a = a.conj().T + a + np.eye(n, dtype=dtype) * dtype(5.)
+    if lower:
+        inds = ([x for y in range(n) for x in range(y, n)],
+                [y for y in range(n) for x in range(y, n)])
+    else:
+        inds = ([x for y in range(1, n+1) for x in range(y)],
+                [y-1 for y in range(1, n+1) for x in range(y)])
+    ap = a[inds]
+    ppsv, pptrf, pptrs, pptri, ppcon = get_lapack_funcs(
+        ('ppsv', 'pptrf', 'pptrs', 'pptri', 'ppcon'),
+        dtype=dtype,
+        ilp64="preferred")
+
+    ul, info = pptrf(n, ap, lower=lower)
+    assert_equal(info, 0)
+    aul = cholesky(a, lower=lower)[inds]
+    assert_allclose(ul, aul, rtol=0, atol=atol)
+
+    uli, info = pptri(n, ul, lower=lower)
+    assert_equal(info, 0)
+    auli = inv(a)[inds]
+    assert_allclose(uli, auli, rtol=0, atol=atol)
+
+    x, info = pptrs(n, ul, b, lower=lower)
+    assert_equal(info, 0)
+    bx = solve(a, b)
+    assert_allclose(x, bx, rtol=0, atol=atol)
+
+    xv, info = ppsv(n, ap, b, lower=lower)
+    assert_equal(info, 0)
+    assert_allclose(xv, bx, rtol=0, atol=atol)
+
+    anorm = np.linalg.norm(a, 1)
+    rcond, info = ppcon(n, ap, anorm=anorm, lower=lower)
+    assert_equal(info, 0)
+    assert_(abs(1/rcond - np.linalg.cond(a, p=1))*rcond < 1)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gees_trexc(dtype):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+
+    n = 10
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+    gees, trexc = get_lapack_funcs(('gees', 'trexc'), dtype=dtype)
+
+    result = gees(lambda x: None, a, overwrite_a=False)
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    z = result[-3]
+
+    d2 = t[6, 6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+    result = trexc(t, z, 7, 1)
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    z = result[-2]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+    assert_allclose(t[0, 0], d2, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize(
+    "t, expect, ifst, ilst",
+    [(np.array([[0.80, -0.11, 0.01, 0.03],
+                [0.00, -0.10, 0.25, 0.35],
+                [0.00, -0.65, -0.10, 0.20],
+                [0.00, 0.00, 0.00, -0.10]]),
+      np.array([[-0.1000, -0.6463, 0.0874, 0.2010],
+                [0.2514, -0.1000, 0.0927, 0.3505],
+                [0.0000, 0.0000, 0.8000, -0.0117],
+                [0.0000, 0.0000, 0.0000, -0.1000]]),
+      2, 1),
+     (np.array([[-6.00 - 7.00j, 0.36 - 0.36j, -0.19 + 0.48j, 0.88 - 0.25j],
+                [0.00 + 0.00j, -5.00 + 2.00j, -0.03 - 0.72j, -0.23 + 0.13j],
+                [0.00 + 0.00j, 0.00 + 0.00j, 8.00 - 1.00j, 0.94 + 0.53j],
+                [0.00 + 0.00j, 0.00 + 0.00j, 0.00 + 0.00j, 3.00 - 4.00j]]),
+      np.array([[-5.0000 + 2.0000j, -0.1574 + 0.7143j,
+                 0.1781 - 0.1913j, 0.3950 + 0.3861j],
+                [0.0000 + 0.0000j, 8.0000 - 1.0000j,
+                 1.0742 + 0.1447j, 0.2515 - 0.3397j],
+                [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+                 3.0000 - 4.0000j, 0.2264 + 0.8962j],
+                [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+                 0.0000 + 0.0000j, -6.0000 - 7.0000j]]),
+      1, 4)])
+def test_trexc_NAG(t, ifst, ilst, expect):
+    """
+    This test implements the example found in the NAG manual,
+    f08qfc, f08qtc, f08qgc, f08quc.
+    """
+    # NAG manual provides accuracy up to 4 decimals
+    atol = 1e-4
+    trexc = get_lapack_funcs('trexc', dtype=t.dtype)
+
+    result = trexc(t, t, ifst, ilst, wantq=0)
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    assert_allclose(expect, t, atol=atol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gges_tgexc(dtype):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+
+    n = 10
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+    b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+    gges, tgexc = get_lapack_funcs(('gges', 'tgexc'), dtype=dtype)
+
+    result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False)
+    assert_equal(result[-1], 0)
+
+    s = result[0]
+    t = result[1]
+    q = result[-4]
+    z = result[-3]
+
+    d1 = s[0, 0] / t[0, 0]
+    d2 = s[6, 6] / t[6, 6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+    assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+    result = tgexc(s, t, q, z, 7, 1)
+    assert_equal(result[-1], 0)
+
+    s = result[0]
+    t = result[1]
+    q = result[2]
+    z = result[3]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+    assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+    assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol)
+    assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gees_trsen(dtype):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+
+    n = 10
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+    gees, trsen, trsen_lwork = get_lapack_funcs(
+        ('gees', 'trsen', 'trsen_lwork'), dtype=dtype)
+
+    result = gees(lambda x: None, a, overwrite_a=False)
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    z = result[-3]
+
+    d2 = t[6, 6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+    select = np.zeros(n)
+    select[6] = 1
+
+    lwork = _compute_lwork(trsen_lwork, select, t)
+
+    if dtype in COMPLEX_DTYPES:
+        result = trsen(select, t, z, lwork=lwork)
+    else:
+        result = trsen(select, t, z, lwork=lwork, liwork=lwork[1])
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    z = result[1]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(z @ t @ z.conj().T, a, rtol=0, atol=atol)
+
+    assert_allclose(t[0, 0], d2, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize(
+    "t, q, expect, select, expect_s, expect_sep",
+    [(np.array([[0.7995, -0.1144, 0.0060, 0.0336],
+                [0.0000, -0.0994, 0.2478, 0.3474],
+                [0.0000, -0.6483, -0.0994, 0.2026],
+                [0.0000, 0.0000, 0.0000, -0.1007]]),
+      np.array([[0.6551, 0.1037, 0.3450, 0.6641],
+                [0.5236, -0.5807, -0.6141, -0.1068],
+                [-0.5362, -0.3073, -0.2935, 0.7293],
+                [0.0956, 0.7467, -0.6463, 0.1249]]),
+      np.array([[0.3500, 0.4500, -0.1400, -0.1700],
+                [0.0900, 0.0700, -0.5399, 0.3500],
+                [-0.4400, -0.3300, -0.0300, 0.1700],
+                [0.2500, -0.3200, -0.1300, 0.1100]]),
+      np.array([1, 0, 0, 1]),
+      1.75e+00, 3.22e+00),
+     (np.array([[-6.0004 - 6.9999j, 0.3637 - 0.3656j,
+                 -0.1880 + 0.4787j, 0.8785 - 0.2539j],
+                [0.0000 + 0.0000j, -5.0000 + 2.0060j,
+                 -0.0307 - 0.7217j, -0.2290 + 0.1313j],
+                [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+                 7.9982 - 0.9964j, 0.9357 + 0.5359j],
+                [0.0000 + 0.0000j, 0.0000 + 0.0000j,
+                 0.0000 + 0.0000j, 3.0023 - 3.9998j]]),
+      np.array([[-0.8347 - 0.1364j, -0.0628 + 0.3806j,
+                 0.2765 - 0.0846j, 0.0633 - 0.2199j],
+                [0.0664 - 0.2968j, 0.2365 + 0.5240j,
+                 -0.5877 - 0.4208j, 0.0835 + 0.2183j],
+                [-0.0362 - 0.3215j, 0.3143 - 0.5473j,
+                 0.0576 - 0.5736j, 0.0057 - 0.4058j],
+                [0.0086 + 0.2958j, -0.3416 - 0.0757j,
+                 -0.1900 - 0.1600j, 0.8327 - 0.1868j]]),
+      np.array([[-3.9702 - 5.0406j, -4.1108 + 3.7002j,
+                 -0.3403 + 1.0098j, 1.2899 - 0.8590j],
+                [0.3397 - 1.5006j, 1.5201 - 0.4301j,
+                 1.8797 - 5.3804j, 3.3606 + 0.6498j],
+                [3.3101 - 3.8506j, 2.4996 + 3.4504j,
+                 0.8802 - 1.0802j, 0.6401 - 1.4800j],
+                [-1.0999 + 0.8199j, 1.8103 - 1.5905j,
+                 3.2502 + 1.3297j, 1.5701 - 3.4397j]]),
+      np.array([1, 0, 0, 1]),
+      1.02e+00, 1.82e-01)])
+def test_trsen_NAG(t, q, select, expect, expect_s, expect_sep):
+    """
+    This test implements the example found in the NAG manual,
+    f08qgc, f08quc.
+    """
+    # NAG manual provides accuracy up to 4 and 2 decimals
+    atol = 1e-4
+    atol2 = 1e-2
+    trsen, trsen_lwork = get_lapack_funcs(
+        ('trsen', 'trsen_lwork'), dtype=t.dtype)
+
+    lwork = _compute_lwork(trsen_lwork, select, t)
+
+    if t.dtype in COMPLEX_DTYPES:
+        result = trsen(select, t, q, lwork=lwork)
+    else:
+        result = trsen(select, t, q, lwork=lwork, liwork=lwork[1])
+    assert_equal(result[-1], 0)
+
+    t = result[0]
+    q = result[1]
+    if t.dtype in COMPLEX_DTYPES:
+        s = result[4]
+        sep = result[5]
+    else:
+        s = result[5]
+        sep = result[6]
+
+    assert_allclose(expect, q @ t @ q.conj().T, atol=atol)
+    assert_allclose(expect_s, 1 / s, atol=atol2)
+    assert_allclose(expect_sep, 1 / sep, atol=atol2)
+
+
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_gges_tgsen(dtype):
+    rng = np.random.RandomState(1234)
+    atol = np.finfo(dtype).eps*100
+
+    n = 10
+    a = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+    b = generate_random_dtype_array([n, n], dtype=dtype, rng=rng)
+
+    gges, tgsen, tgsen_lwork = get_lapack_funcs(
+        ('gges', 'tgsen', 'tgsen_lwork'), dtype=dtype)
+
+    result = gges(lambda x: None, a, b, overwrite_a=False, overwrite_b=False)
+    assert_equal(result[-1], 0)
+
+    s = result[0]
+    t = result[1]
+    q = result[-4]
+    z = result[-3]
+
+    d1 = s[0, 0] / t[0, 0]
+    d2 = s[6, 6] / t[6, 6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+    assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+    select = np.zeros(n)
+    select[6] = 1
+
+    lwork = _compute_lwork(tgsen_lwork, select, s, t)
+
+    # off-by-one error in LAPACK, see gh-issue #13397
+    lwork = (lwork[0]+1, lwork[1])
+
+    result = tgsen(select, s, t, q, z, lwork=lwork)
+    assert_equal(result[-1], 0)
+
+    s = result[0]
+    t = result[1]
+    q = result[-7]
+    z = result[-6]
+
+    if dtype in COMPLEX_DTYPES:
+        assert_allclose(s, np.triu(s), rtol=0, atol=atol)
+        assert_allclose(t, np.triu(t), rtol=0, atol=atol)
+
+    assert_allclose(q @ s @ z.conj().T, a, rtol=0, atol=atol)
+    assert_allclose(q @ t @ z.conj().T, b, rtol=0, atol=atol)
+
+    assert_allclose(s[0, 0] / t[0, 0], d2, rtol=0, atol=atol)
+    assert_allclose(s[1, 1] / t[1, 1], d1, rtol=0, atol=atol)
+
+
+@pytest.mark.parametrize(
+    "a, b, c, d, e, f, rans, lans",
+    [(np.array([[4.0,   1.0,  1.0,  2.0],
+                [0.0,   3.0,  4.0,  1.0],
+                [0.0,   1.0,  3.0,  1.0],
+                [0.0,   0.0,  0.0,  6.0]]),
+      np.array([[1.0,   1.0,  1.0,  1.0],
+                [0.0,   3.0,  4.0,  1.0],
+                [0.0,   1.0,  3.0,  1.0],
+                [0.0,   0.0,  0.0,  4.0]]),
+      np.array([[-4.0,  7.0,  1.0, 12.0],
+                [-9.0,  2.0, -2.0, -2.0],
+                [-4.0,  2.0, -2.0,  8.0],
+                [-7.0,  7.0, -6.0, 19.0]]),
+      np.array([[2.0,   1.0,  1.0,  3.0],
+                [0.0,   1.0,  2.0,  1.0],
+                [0.0,   0.0,  1.0,  1.0],
+                [0.0,   0.0,  0.0,  2.0]]),
+      np.array([[1.0,   1.0,  1.0,  2.0],
+                [0.0,   1.0,  4.0,  1.0],
+                [0.0,   0.0,  1.0,  1.0],
+                [0.0,   0.0,  0.0,  1.0]]),
+      np.array([[-7.0,  5.0,  0.0,  7.0],
+                [-5.0,  1.0, -8.0,  0.0],
+                [-1.0,  2.0, -3.0,  5.0],
+                [-3.0,  2.0,  0.0,  5.0]]),
+      np.array([[1.0,   1.0,  1.0,  1.0],
+                [-1.0,  2.0, -1.0, -1.0],
+                [-1.0,  1.0,  3.0,  1.0],
+                [-1.0,  1.0, -1.0,  4.0]]),
+      np.array([[4.0,  -1.0,  1.0, -1.0],
+                [1.0,   3.0, -1.0,  1.0],
+                [-1.0,  1.0,  2.0, -1.0],
+                [1.0,  -1.0,  1.0,  1.0]]))])
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+def test_tgsyl_NAG(a, b, c, d, e, f, rans, lans, dtype):
+    atol = 1e-4
+
+    tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype)
+    rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f)
+
+    assert_equal(info, 0)
+    assert_allclose(scale, 1.0, rtol=0, atol=np.finfo(dtype).eps*100,
+                    err_msg="SCALE must be 1.0")
+    assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100,
+                    err_msg="DIF must be nearly 0")
+    assert_allclose(rout, rans, atol=atol,
+                    err_msg="Solution for R is incorrect")
+    assert_allclose(lout, lans, atol=atol,
+                    err_msg="Solution for L is incorrect")
+
+
+@pytest.mark.parametrize('dtype', REAL_DTYPES)
+@pytest.mark.parametrize('trans', ('N', 'T'))
+@pytest.mark.parametrize('ijob', [0, 1, 2, 3, 4])
+def test_tgsyl(dtype, trans, ijob):
+
+    atol = 1e-3 if dtype == np.float32 else 1e-10
+    rng = np.random.default_rng(1685779866898198)
+    m, n = 10, 15
+
+    a, d, *_ = qz(rng.uniform(-10, 10, [m, m]).astype(dtype),
+                  rng.uniform(-10, 10, [m, m]).astype(dtype),
+                  output='real')
+
+    b, e, *_ = qz(rng.uniform(-10, 10, [n, n]).astype(dtype),
+                  rng.uniform(-10, 10, [n, n]).astype(dtype),
+                  output='real')
+
+    c = rng.uniform(-2, 2, [m, n]).astype(dtype)
+    f = rng.uniform(-2, 2, [m, n]).astype(dtype)
+
+    tgsyl = get_lapack_funcs(('tgsyl'), dtype=dtype)
+    rout, lout, scale, dif, info = tgsyl(a, b, c, d, e, f,
+                                         trans=trans, ijob=ijob)
+
+    assert info == 0, "INFO is non-zero"
+    assert scale >= 0.0, "SCALE must be non-negative"
+    if ijob == 0:
+        assert_allclose(dif, 0.0, rtol=0, atol=np.finfo(dtype).eps*100,
+                        err_msg="DIF must be 0 for ijob =0")
+    else:
+        assert dif >= 0.0, "DIF must be non-negative"
+
+    # Only DIF is calculated for ijob = 3/4
+    if ijob <= 2:
+        if trans == 'N':
+            lhs1 = a @ rout - lout @ b
+            rhs1 = scale*c
+            lhs2 = d @ rout - lout @ e
+            rhs2 = scale*f
+        elif trans == 'T':
+            lhs1 = np.transpose(a) @ rout + np.transpose(d) @ lout
+            rhs1 = scale*c
+            lhs2 = rout @ np.transpose(b) + lout @ np.transpose(e)
+            rhs2 = -1.0*scale*f
+
+        assert_allclose(lhs1, rhs1, atol=atol, rtol=0.,
+                        err_msg='lhs1 and rhs1 do not match')
+        assert_allclose(lhs2, rhs2, atol=atol, rtol=0.,
+                        err_msg='lhs2 and rhs2 do not match')
+
+
+@pytest.mark.parametrize('mtype', ['sy', 'he'])  # matrix type
+@pytest.mark.parametrize('dtype', DTYPES)
+@pytest.mark.parametrize('lower', (0, 1))
+def test_sy_hetrs(mtype, dtype, lower):
+    if mtype == 'he' and dtype in REAL_DTYPES:
+        pytest.skip("hetrs not for real dtypes.")
+    rng = np.random.default_rng(1723059677121834)
+    n, nrhs = 20, 5
+    if dtype in COMPLEX_DTYPES:
+        A = (rng.uniform(size=(n, n)) + rng.uniform(size=(n, n))*1j).astype(dtype)
+    else:
+        A = rng.uniform(size=(n, n)).astype(dtype)
+
+    A = A + A.T if mtype == 'sy' else A + A.conj().T
+    b = rng.uniform(size=(n, nrhs)).astype(dtype)
+    names = f'{mtype}trf', f'{mtype}trf_lwork', f'{mtype}trs'
+    trf, trf_lwork, trs = get_lapack_funcs(names, dtype=dtype)
+    lwork = trf_lwork(n, lower=lower)
+    ldu, ipiv, info = trf(A, lwork=lwork)
+    assert info == 0
+    x, info = trs(a=ldu, ipiv=ipiv, b=b)
+    assert info == 0
+    eps = np.finfo(dtype).eps
+    assert_allclose(A@x, b, atol=100*n*eps)
+
+
+@pytest.mark.parametrize('norm', list('Mm1OoIiFfEe'))
+@pytest.mark.parametrize('uplo, m, n', [('U', 5, 10), ('U', 10, 10),
+                                        ('L', 10, 5), ('L', 10, 10)])
+@pytest.mark.parametrize('diag', ['N', 'U'])
+@pytest.mark.parametrize('dtype', DTYPES)
+def test_lantr(norm, uplo, m, n, diag, dtype):
+    rng = np.random.default_rng(98426598246982456)
+    A = rng.random(size=(m, n)).astype(dtype)
+    lantr, lange = get_lapack_funcs(('lantr', 'lange'), (A,))
+    res = lantr(norm, A, uplo=uplo, diag=diag)
+
+    # now modify the matrix according to assumptions made by `lantr`
+    A = np.triu(A) if uplo == 'U' else np.tril(A)
+    if diag == 'U':
+        i = np.arange(min(m, n))
+        A[i, i] = 1
+    ref = lange(norm, A)
+
+    assert_allclose(res, ref, rtol=2e-6)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e87333c40b64d3f54024779dfb959be7a599178
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matfuncs.py
@@ -0,0 +1,1063 @@
+#
+# Created by: Pearu Peterson, March 2002
+#
+""" Test functions for linalg.matfuncs module
+
+"""
+import functools
+
+import numpy as np
+from numpy import array, identity, dot, sqrt
+from numpy.testing import (assert_array_almost_equal, assert_allclose, assert_,
+                           assert_array_less, assert_array_equal, assert_warns)
+import pytest
+
+import scipy.linalg
+from scipy.linalg import (funm, signm, logm, sqrtm, fractional_matrix_power,
+                          expm, expm_frechet, expm_cond, norm, khatri_rao,
+                          cosm, sinm, tanm, coshm, sinhm, tanhm)
+from scipy.linalg import _matfuncs_inv_ssq
+from scipy.linalg._matfuncs import pick_pade_structure
+from scipy.linalg._matfuncs_inv_ssq import LogmExactlySingularWarning
+import scipy.linalg._expm_frechet
+
+from scipy.optimize import minimize
+
+
+def _get_al_mohy_higham_2012_experiment_1():
+    """
+    Return the test matrix from Experiment (1) of [1]_.
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2012)
+           "Improved Inverse Scaling and Squaring Algorithms
+           for the Matrix Logarithm."
+           SIAM Journal on Scientific Computing, 34 (4). C152-C169.
+           ISSN 1095-7197
+
+    """
+    A = np.array([
+        [3.2346e-1, 3e4, 3e4, 3e4],
+        [0, 3.0089e-1, 3e4, 3e4],
+        [0, 0, 3.2210e-1, 3e4],
+        [0, 0, 0, 3.0744e-1]], dtype=float)
+    return A
+
+
+class TestSignM:
+
+    def test_nils(self):
+        a = array([[29.2, -24.2, 69.5, 49.8, 7.],
+                   [-9.2, 5.2, -18., -16.8, -2.],
+                   [-10., 6., -20., -18., -2.],
+                   [-9.6, 9.6, -25.5, -15.4, -2.],
+                   [9.8, -4.8, 18., 18.2, 2.]])
+        cr = array([[11.94933333,-2.24533333,15.31733333,21.65333333,-2.24533333],
+                    [-3.84266667,0.49866667,-4.59066667,-7.18666667,0.49866667],
+                    [-4.08,0.56,-4.92,-7.6,0.56],
+                    [-4.03466667,1.04266667,-5.59866667,-7.02666667,1.04266667],
+                    [4.15733333,-0.50133333,4.90933333,7.81333333,-0.50133333]])
+        r = signm(a)
+        assert_array_almost_equal(r,cr)
+
+    def test_defective1(self):
+        a = array([[0.0,1,0,0],[1,0,1,0],[0,0,0,1],[0,0,1,0]])
+        signm(a, disp=False)
+        #XXX: what would be the correct result?
+
+    def test_defective2(self):
+        a = array((
+            [29.2,-24.2,69.5,49.8,7.0],
+            [-9.2,5.2,-18.0,-16.8,-2.0],
+            [-10.0,6.0,-20.0,-18.0,-2.0],
+            [-9.6,9.6,-25.5,-15.4,-2.0],
+            [9.8,-4.8,18.0,18.2,2.0]))
+        signm(a, disp=False)
+        #XXX: what would be the correct result?
+
+    def test_defective3(self):
+        a = array([[-2., 25., 0., 0., 0., 0., 0.],
+                   [0., -3., 10., 3., 3., 3., 0.],
+                   [0., 0., 2., 15., 3., 3., 0.],
+                   [0., 0., 0., 0., 15., 3., 0.],
+                   [0., 0., 0., 0., 3., 10., 0.],
+                   [0., 0., 0., 0., 0., -2., 25.],
+                   [0., 0., 0., 0., 0., 0., -3.]])
+        signm(a, disp=False)
+        #XXX: what would be the correct result?
+
+
+class TestLogM:
+
+    def test_nils(self):
+        a = array([[-2., 25., 0., 0., 0., 0., 0.],
+                   [0., -3., 10., 3., 3., 3., 0.],
+                   [0., 0., 2., 15., 3., 3., 0.],
+                   [0., 0., 0., 0., 15., 3., 0.],
+                   [0., 0., 0., 0., 3., 10., 0.],
+                   [0., 0., 0., 0., 0., -2., 25.],
+                   [0., 0., 0., 0., 0., 0., -3.]])
+        m = (identity(7)*3.1+0j)-a
+        logm(m, disp=False)
+        #XXX: what would be the correct result?
+
+    def test_al_mohy_higham_2012_experiment_1_logm(self):
+        # The logm completes the round trip successfully.
+        # Note that the expm leg of the round trip is badly conditioned.
+        A = _get_al_mohy_higham_2012_experiment_1()
+        A_logm, info = logm(A, disp=False)
+        A_round_trip = expm(A_logm)
+        assert_allclose(A_round_trip, A, rtol=5e-5, atol=1e-14)
+
+    def test_al_mohy_higham_2012_experiment_1_funm_log(self):
+        # The raw funm with np.log does not complete the round trip.
+        # Note that the expm leg of the round trip is badly conditioned.
+        A = _get_al_mohy_higham_2012_experiment_1()
+        A_funm_log, info = funm(A, np.log, disp=False)
+        A_round_trip = expm(A_funm_log)
+        assert_(not np.allclose(A_round_trip, A, rtol=1e-5, atol=1e-14))
+
+    def test_round_trip_random_float(self):
+        np.random.seed(1234)
+        for n in range(1, 6):
+            M_unscaled = np.random.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+
+                # Eigenvalues are related to the branch cut.
+                W = np.linalg.eigvals(M)
+                err_msg = f'M:{M} eivals:{W}'
+
+                # Check sqrtm round trip because it is used within logm.
+                M_sqrtm, info = sqrtm(M, disp=False)
+                M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
+                assert_allclose(M_sqrtm_round_trip, M)
+
+                # Check logm round trip.
+                M_logm, info = logm(M, disp=False)
+                M_logm_round_trip = expm(M_logm)
+                assert_allclose(M_logm_round_trip, M, err_msg=err_msg)
+
+    def test_round_trip_random_complex(self):
+        np.random.seed(1234)
+        for n in range(1, 6):
+            M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+                M_logm, info = logm(M, disp=False)
+                M_round_trip = expm(M_logm)
+                assert_allclose(M_round_trip, M)
+
+    def test_logm_type_preservation_and_conversion(self):
+        # The logm matrix function should preserve the type of a matrix
+        # whose eigenvalues are positive with zero imaginary part.
+        # Test this preservation for variously structured matrices.
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, 1]],
+                [[1, 0], [1, 1]],
+                [[2, 1], [1, 1]],
+                [[2, 3], [1, 2]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(not any(w.imag or w.real < 0 for w in W))
+
+            # check float type preservation
+            A = np.array(matrix_as_list, dtype=float)
+            A_logm, info = logm(A, disp=False)
+            assert_(A_logm.dtype.char not in complex_dtype_chars)
+
+            # check complex type preservation
+            A = np.array(matrix_as_list, dtype=complex)
+            A_logm, info = logm(A, disp=False)
+            assert_(A_logm.dtype.char in complex_dtype_chars)
+
+            # check float->complex type conversion for the matrix negation
+            A = -np.array(matrix_as_list, dtype=float)
+            A_logm, info = logm(A, disp=False)
+            assert_(A_logm.dtype.char in complex_dtype_chars)
+
+    def test_complex_spectrum_real_logm(self):
+        # This matrix has complex eigenvalues and real logm.
+        # Its output dtype depends on its input dtype.
+        M = [[1, 1, 2], [2, 1, 1], [1, 2, 1]]
+        for dt in float, complex:
+            X = np.array(M, dtype=dt)
+            w = scipy.linalg.eigvals(X)
+            assert_(1e-2 < np.absolute(w.imag).sum())
+            Y, info = logm(X, disp=False)
+            assert_(np.issubdtype(Y.dtype, np.inexact))
+            assert_allclose(expm(Y), X)
+
+    def test_real_mixed_sign_spectrum(self):
+        # These matrices have real eigenvalues with mixed signs.
+        # The output logm dtype is complex, regardless of input dtype.
+        for M in (
+                [[1, 0], [0, -1]],
+                [[0, 1], [1, 0]]):
+            for dt in float, complex:
+                A = np.array(M, dtype=dt)
+                A_logm, info = logm(A, disp=False)
+                assert_(np.issubdtype(A_logm.dtype, np.complexfloating))
+
+    @pytest.mark.thread_unsafe
+    def test_exactly_singular(self):
+        A = np.array([[0, 0], [1j, 1j]])
+        B = np.asarray([[1, 1], [0, 0]])
+        for M in A, A.T, B, B.T:
+            expected_warning = _matfuncs_inv_ssq.LogmExactlySingularWarning
+            L, info = assert_warns(expected_warning, logm, M, disp=False)
+            E = expm(L)
+            assert_allclose(E, M, atol=1e-14)
+
+    @pytest.mark.thread_unsafe
+    def test_nearly_singular(self):
+        M = np.array([[1e-100]])
+        expected_warning = _matfuncs_inv_ssq.LogmNearlySingularWarning
+        L, info = assert_warns(expected_warning, logm, M, disp=False)
+        E = expm(L)
+        assert_allclose(E, M, atol=1e-14)
+
+    def test_opposite_sign_complex_eigenvalues(self):
+        # See gh-6113
+        E = [[0, 1], [-1, 0]]
+        L = [[0, np.pi*0.5], [-np.pi*0.5, 0]]
+        assert_allclose(expm(L), E, atol=1e-14)
+        assert_allclose(logm(E), L, atol=1e-14)
+        E = [[1j, 4], [0, -1j]]
+        L = [[1j*np.pi*0.5, 2*np.pi], [0, -1j*np.pi*0.5]]
+        assert_allclose(expm(L), E, atol=1e-14)
+        assert_allclose(logm(E), L, atol=1e-14)
+        E = [[1j, 0], [0, -1j]]
+        L = [[1j*np.pi*0.5, 0], [0, -1j*np.pi*0.5]]
+        assert_allclose(expm(L), E, atol=1e-14)
+        assert_allclose(logm(E), L, atol=1e-14)
+
+    def test_readonly(self):
+        n = 5
+        a = np.ones((n, n)) + np.identity(n)
+        a.flags.writeable = False
+        logm(a)
+
+    @pytest.mark.xfail(reason="ValueError: attempt to get argmax of an empty sequence")
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        log_a = logm(a)
+        a0 = np.eye(2, dtype=dt)
+        log_a0 = logm(a0)
+
+        assert log_a.shape == (0, 0)
+        assert log_a.dtype == log_a0.dtype
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize('dtype', [int, float, np.float32, complex, np.complex64])
+    def test_no_ZeroDivisionError(self, dtype):
+        # gh-17136 reported inconsistent behavior in `logm` depending on input dtype:
+        # sometimes it raised an error, and sometimes it printed a warning message.
+        # check that this is resolved and that the warning is emitted properly.
+        with (pytest.warns(RuntimeWarning, match="logm result may be inaccurate"),
+              pytest.warns(LogmExactlySingularWarning)):
+            logm(np.zeros((2, 2), dtype=dtype))
+
+
+class TestSqrtM:
+    def test_round_trip_random_float(self):
+        rng = np.random.RandomState(1234)
+        for n in range(1, 6):
+            M_unscaled = rng.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+                M_sqrtm, info = sqrtm(M, disp=False)
+                M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
+                assert_allclose(M_sqrtm_round_trip, M)
+
+    def test_round_trip_random_complex(self):
+        rng = np.random.RandomState(1234)
+        for n in range(1, 6):
+            M_unscaled = rng.randn(n, n) + 1j * rng.randn(n, n)
+            for scale in np.logspace(-4, 4, 9):
+                M = M_unscaled * scale
+                M_sqrtm, info = sqrtm(M, disp=False)
+                M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
+                assert_allclose(M_sqrtm_round_trip, M)
+
+    def test_bad(self):
+        # See https://web.archive.org/web/20051220232650/http://www.maths.man.ac.uk/~nareports/narep336.ps.gz
+        e = 2**-5
+        se = sqrt(e)
+        a = array([[1.0,0,0,1],
+                   [0,e,0,0],
+                   [0,0,e,0],
+                   [0,0,0,1]])
+        sa = array([[1,0,0,0.5],
+                    [0,se,0,0],
+                    [0,0,se,0],
+                    [0,0,0,1]])
+        n = a.shape[0]
+        assert_array_almost_equal(dot(sa,sa),a)
+        # Check default sqrtm.
+        esa = sqrtm(a, disp=False, blocksize=n)[0]
+        assert_array_almost_equal(dot(esa,esa),a)
+        # Check sqrtm with 2x2 blocks.
+        esa = sqrtm(a, disp=False, blocksize=2)[0]
+        assert_array_almost_equal(dot(esa,esa),a)
+
+    def test_sqrtm_type_preservation_and_conversion(self):
+        # The sqrtm matrix function should preserve the type of a matrix
+        # whose eigenvalues are nonnegative with zero imaginary part.
+        # Test this preservation for variously structured matrices.
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, 1]],
+                [[1, 0], [1, 1]],
+                [[2, 1], [1, 1]],
+                [[2, 3], [1, 2]],
+                [[1, 1], [1, 1]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(not any(w.imag or w.real < 0 for w in W))
+
+            # check float type preservation
+            A = np.array(matrix_as_list, dtype=float)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char not in complex_dtype_chars)
+
+            # check complex type preservation
+            A = np.array(matrix_as_list, dtype=complex)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+            # check float->complex type conversion for the matrix negation
+            A = -np.array(matrix_as_list, dtype=float)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+    def test_sqrtm_type_conversion_mixed_sign_or_complex_spectrum(self):
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, -1]],
+                [[0, 1], [1, 0]],
+                [[0, 1, 0], [0, 0, 1], [1, 0, 0]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(any(w.imag or w.real < 0 for w in W))
+
+            # check complex->complex
+            A = np.array(matrix_as_list, dtype=complex)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+            # check float->complex
+            A = np.array(matrix_as_list, dtype=float)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(A_sqrtm.dtype.char in complex_dtype_chars)
+
+    def test_blocksizes(self):
+        # Make sure I do not goof up the blocksizes when they do not divide n.
+        np.random.seed(1234)
+        for n in range(1, 8):
+            A = np.random.rand(n, n) + 1j*np.random.randn(n, n)
+            A_sqrtm_default, info = sqrtm(A, disp=False, blocksize=n)
+            assert_allclose(A, np.linalg.matrix_power(A_sqrtm_default, 2))
+            for blocksize in range(1, 10):
+                A_sqrtm_new, info = sqrtm(A, disp=False, blocksize=blocksize)
+                assert_allclose(A_sqrtm_default, A_sqrtm_new)
+
+    def test_al_mohy_higham_2012_experiment_1(self):
+        # Matrix square root of a tricky upper triangular matrix.
+        A = _get_al_mohy_higham_2012_experiment_1()
+        A_sqrtm, info = sqrtm(A, disp=False)
+        A_round_trip = A_sqrtm.dot(A_sqrtm)
+        assert_allclose(A_round_trip, A, rtol=1e-5)
+        assert_allclose(np.tril(A_round_trip), np.tril(A))
+
+    def test_strict_upper_triangular(self):
+        # This matrix has no square root.
+        for dt in int, float:
+            A = np.array([
+                [0, 3, 0, 0],
+                [0, 0, 3, 0],
+                [0, 0, 0, 3],
+                [0, 0, 0, 0]], dtype=dt)
+            A_sqrtm, info = sqrtm(A, disp=False)
+            assert_(np.isnan(A_sqrtm).all())
+
+    def test_weird_matrix(self):
+        # The square root of matrix B exists.
+        for dt in int, float:
+            A = np.array([
+                [0, 0, 1],
+                [0, 0, 0],
+                [0, 1, 0]], dtype=dt)
+            B = np.array([
+                [0, 1, 0],
+                [0, 0, 0],
+                [0, 0, 0]], dtype=dt)
+            assert_array_equal(B, A.dot(A))
+
+            # But scipy sqrtm is not clever enough to find it.
+            B_sqrtm, info = sqrtm(B, disp=False)
+            assert_(np.isnan(B_sqrtm).all())
+
+    def test_disp(self):
+        np.random.seed(1234)
+
+        A = np.random.rand(3, 3)
+        B = sqrtm(A, disp=True)
+        assert_allclose(B.dot(B), A)
+
+    def test_opposite_sign_complex_eigenvalues(self):
+        M = [[2j, 4], [0, -2j]]
+        R = [[1+1j, 2], [0, 1-1j]]
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    def test_gh4866(self):
+        M = np.array([[1, 0, 0, 1],
+                      [0, 0, 0, 0],
+                      [0, 0, 0, 0],
+                      [1, 0, 0, 1]])
+        R = np.array([[sqrt(0.5), 0, 0, sqrt(0.5)],
+                      [0, 0, 0, 0],
+                      [0, 0, 0, 0],
+                      [sqrt(0.5), 0, 0, sqrt(0.5)]])
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    def test_gh5336(self):
+        M = np.diag([2, 1, 0])
+        R = np.diag([sqrt(2), 1, 0])
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    def test_gh7839(self):
+        M = np.zeros((2, 2))
+        R = np.zeros((2, 2))
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(sqrtm(M), R, atol=1e-14)
+
+    @pytest.mark.xfail(reason="failing on macOS after gh-20212")
+    def test_gh17918(self):
+        M = np.empty((19, 19))
+        M.fill(0.94)
+        np.fill_diagonal(M, 1)
+        assert np.isrealobj(sqrtm(M))
+
+    def test_data_size_preservation_uint_in_float_out(self):
+        M = np.zeros((10, 10), dtype=np.uint8)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.uint16)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.uint32)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.uint64)
+        assert sqrtm(M).dtype == np.float64
+
+    def test_data_size_preservation_int_in_float_out(self):
+        M = np.zeros((10, 10), dtype=np.int8)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.int16)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.int32)
+        assert sqrtm(M).dtype == np.float64
+        M = np.zeros((10, 10), dtype=np.int64)
+        assert sqrtm(M).dtype == np.float64
+
+    def test_data_size_preservation_int_in_comp_out(self):
+        M = np.array([[2, 4], [0, -2]], dtype=np.int8)
+        assert sqrtm(M).dtype == np.complex128
+        M = np.array([[2, 4], [0, -2]], dtype=np.int16)
+        assert sqrtm(M).dtype == np.complex128
+        M = np.array([[2, 4], [0, -2]], dtype=np.int32)
+        assert sqrtm(M).dtype == np.complex128
+        M = np.array([[2, 4], [0, -2]], dtype=np.int64)
+        assert sqrtm(M).dtype == np.complex128
+
+    def test_data_size_preservation_float_in_float_out(self):
+        M = np.zeros((10, 10), dtype=np.float16)
+        assert sqrtm(M).dtype == np.float32
+        M = np.zeros((10, 10), dtype=np.float32)
+        assert sqrtm(M).dtype == np.float32
+        M = np.zeros((10, 10), dtype=np.float64)
+        assert sqrtm(M).dtype == np.float64
+        if hasattr(np, 'float128'):
+            M = np.zeros((10, 10), dtype=np.float128)
+            assert sqrtm(M).dtype == np.float64
+
+    def test_data_size_preservation_float_in_comp_out(self):
+        M = np.array([[2, 4], [0, -2]], dtype=np.float16)
+        assert sqrtm(M).dtype == np.complex64
+        M = np.array([[2, 4], [0, -2]], dtype=np.float32)
+        assert sqrtm(M).dtype == np.complex64
+        M = np.array([[2, 4], [0, -2]], dtype=np.float64)
+        assert sqrtm(M).dtype == np.complex128
+        if hasattr(np, 'float128') and hasattr(np, 'complex256'):
+            M = np.array([[2, 4], [0, -2]], dtype=np.float128)
+            assert sqrtm(M).dtype == np.complex128
+
+    def test_data_size_preservation_comp_in_comp_out(self):
+        M = np.array([[2j, 4], [0, -2j]], dtype=np.complex64)
+        assert sqrtm(M).dtype == np.complex64
+        M = np.array([[2j, 4], [0, -2j]], dtype=np.complex128)
+        assert sqrtm(M).dtype == np.complex128
+        if hasattr(np, 'complex256'):
+            M = np.array([[2j, 4], [0, -2j]], dtype=np.complex256)
+            assert sqrtm(M).dtype == np.complex128
+
+    @pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
+    def test_empty(self, dt):
+        a = np.empty((0, 0), dtype=dt)
+        s = sqrtm(a)
+        a0 = np.eye(2, dtype=dt)
+        s0 = sqrtm(a0)
+
+        assert s.shape == (0, 0)
+        assert s.dtype == s0.dtype
+
+
+class TestFractionalMatrixPower:
+    def test_round_trip_random_complex(self):
+        np.random.seed(1234)
+        for p in range(1, 5):
+            for n in range(1, 5):
+                M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n)
+                for scale in np.logspace(-4, 4, 9):
+                    M = M_unscaled * scale
+                    M_root = fractional_matrix_power(M, 1/p)
+                    M_round_trip = np.linalg.matrix_power(M_root, p)
+                    assert_allclose(M_round_trip, M)
+
+    def test_round_trip_random_float(self):
+        # This test is more annoying because it can hit the branch cut;
+        # this happens when the matrix has an eigenvalue
+        # with no imaginary component and with a real negative component,
+        # and it means that the principal branch does not exist.
+        np.random.seed(1234)
+        for p in range(1, 5):
+            for n in range(1, 5):
+                M_unscaled = np.random.randn(n, n)
+                for scale in np.logspace(-4, 4, 9):
+                    M = M_unscaled * scale
+                    M_root = fractional_matrix_power(M, 1/p)
+                    M_round_trip = np.linalg.matrix_power(M_root, p)
+                    assert_allclose(M_round_trip, M)
+
+    def test_larger_abs_fractional_matrix_powers(self):
+        np.random.seed(1234)
+        for n in (2, 3, 5):
+            for i in range(10):
+                M = np.random.randn(n, n) + 1j * np.random.randn(n, n)
+                M_one_fifth = fractional_matrix_power(M, 0.2)
+                # Test the round trip.
+                M_round_trip = np.linalg.matrix_power(M_one_fifth, 5)
+                assert_allclose(M, M_round_trip)
+                # Test a large abs fractional power.
+                X = fractional_matrix_power(M, -5.4)
+                Y = np.linalg.matrix_power(M_one_fifth, -27)
+                assert_allclose(X, Y)
+                # Test another large abs fractional power.
+                X = fractional_matrix_power(M, 3.8)
+                Y = np.linalg.matrix_power(M_one_fifth, 19)
+                assert_allclose(X, Y)
+
+    def test_random_matrices_and_powers(self):
+        # Each independent iteration of this fuzz test picks random parameters.
+        # It tries to hit some edge cases.
+        rng = np.random.default_rng(1726500458620605)
+        nsamples = 20
+        for i in range(nsamples):
+            # Sample a matrix size and a random real power.
+            n = rng.integers(1, 5)
+            p = rng.random()
+
+            # Sample a random real or complex matrix.
+            matrix_scale = np.exp(rng.integers(-4, 5))
+            A = rng.random(size=[n, n])
+            if [True, False][rng.choice(2)]:
+                A = A + 1j * rng.random(size=[n, n])
+            A = A * matrix_scale
+
+            # Check a couple of analytically equivalent ways
+            # to compute the fractional matrix power.
+            # These can be compared because they both use the principal branch.
+            A_power = fractional_matrix_power(A, p)
+            A_logm, info = logm(A, disp=False)
+            A_power_expm_logm = expm(A_logm * p)
+            assert_allclose(A_power, A_power_expm_logm)
+
+    def test_al_mohy_higham_2012_experiment_1(self):
+        # Fractional powers of a tricky upper triangular matrix.
+        A = _get_al_mohy_higham_2012_experiment_1()
+
+        # Test remainder matrix power.
+        A_funm_sqrt, info = funm(A, np.sqrt, disp=False)
+        A_sqrtm, info = sqrtm(A, disp=False)
+        A_rem_power = _matfuncs_inv_ssq._remainder_matrix_power(A, 0.5)
+        A_power = fractional_matrix_power(A, 0.5)
+        assert_allclose(A_rem_power, A_power, rtol=1e-11)
+        assert_allclose(A_sqrtm, A_power)
+        assert_allclose(A_sqrtm, A_funm_sqrt)
+
+        # Test more fractional powers.
+        for p in (1/2, 5/3):
+            A_power = fractional_matrix_power(A, p)
+            A_round_trip = fractional_matrix_power(A_power, 1/p)
+            assert_allclose(A_round_trip, A, rtol=1e-2)
+            assert_allclose(np.tril(A_round_trip, 1), np.tril(A, 1))
+
+    def test_briggs_helper_function(self):
+        np.random.seed(1234)
+        for a in np.random.randn(10) + 1j * np.random.randn(10):
+            for k in range(5):
+                x_observed = _matfuncs_inv_ssq._briggs_helper_function(a, k)
+                x_expected = a ** np.exp2(-k) - 1
+                assert_allclose(x_observed, x_expected)
+
+    def test_type_preservation_and_conversion(self):
+        # The fractional_matrix_power matrix function should preserve
+        # the type of a matrix whose eigenvalues
+        # are positive with zero imaginary part.
+        # Test this preservation for variously structured matrices.
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, 1]],
+                [[1, 0], [1, 1]],
+                [[2, 1], [1, 1]],
+                [[2, 3], [1, 2]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(not any(w.imag or w.real < 0 for w in W))
+
+            # Check various positive and negative powers
+            # with absolute values bigger and smaller than 1.
+            for p in (-2.4, -0.9, 0.2, 3.3):
+
+                # check float type preservation
+                A = np.array(matrix_as_list, dtype=float)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char not in complex_dtype_chars)
+
+                # check complex type preservation
+                A = np.array(matrix_as_list, dtype=complex)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char in complex_dtype_chars)
+
+                # check float->complex for the matrix negation
+                A = -np.array(matrix_as_list, dtype=float)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char in complex_dtype_chars)
+
+    def test_type_conversion_mixed_sign_or_complex_spectrum(self):
+        complex_dtype_chars = ('F', 'D', 'G')
+        for matrix_as_list in (
+                [[1, 0], [0, -1]],
+                [[0, 1], [1, 0]],
+                [[0, 1, 0], [0, 0, 1], [1, 0, 0]]):
+
+            # check that the spectrum has the expected properties
+            W = scipy.linalg.eigvals(matrix_as_list)
+            assert_(any(w.imag or w.real < 0 for w in W))
+
+            # Check various positive and negative powers
+            # with absolute values bigger and smaller than 1.
+            for p in (-2.4, -0.9, 0.2, 3.3):
+
+                # check complex->complex
+                A = np.array(matrix_as_list, dtype=complex)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char in complex_dtype_chars)
+
+                # check float->complex
+                A = np.array(matrix_as_list, dtype=float)
+                A_power = fractional_matrix_power(A, p)
+                assert_(A_power.dtype.char in complex_dtype_chars)
+
+    @pytest.mark.xfail(reason='Too unstable across LAPACKs.')
+    def test_singular(self):
+        # Negative fractional powers do not work with singular matrices.
+        for matrix_as_list in (
+                [[0, 0], [0, 0]],
+                [[1, 1], [1, 1]],
+                [[1, 2], [3, 6]],
+                [[0, 0, 0], [0, 1, 1], [0, -1, 1]]):
+
+            # Check fractional powers both for float and for complex types.
+            for newtype in (float, complex):
+                A = np.array(matrix_as_list, dtype=newtype)
+                for p in (-0.7, -0.9, -2.4, -1.3):
+                    A_power = fractional_matrix_power(A, p)
+                    assert_(np.isnan(A_power).all())
+                for p in (0.2, 1.43):
+                    A_power = fractional_matrix_power(A, p)
+                    A_round_trip = fractional_matrix_power(A_power, 1/p)
+                    assert_allclose(A_round_trip, A)
+
+    def test_opposite_sign_complex_eigenvalues(self):
+        M = [[2j, 4], [0, -2j]]
+        R = [[1+1j, 2], [0, 1-1j]]
+        assert_allclose(np.dot(R, R), M, atol=1e-14)
+        assert_allclose(fractional_matrix_power(M, 0.5), R, atol=1e-14)
+
+
+class TestExpM:
+    def test_zero(self):
+        a = array([[0.,0],[0,0]])
+        assert_array_almost_equal(expm(a),[[1,0],[0,1]])
+
+    def test_single_elt(self):
+        elt = expm(1)
+        assert_allclose(elt, np.array([[np.e]]))
+
+    @pytest.mark.parametrize('func', [expm, cosm, sinm, tanm, coshm, sinhm, tanhm])
+    @pytest.mark.parametrize('dt',[int, float, np.float32, complex, np.complex64])
+    @pytest.mark.parametrize('shape', [(0, 0), (1, 1)])
+    def test_small_empty_matrix_input(self, func, dt, shape):
+        # regression test for gh-11082 / gh-20372 - test behavior of expm
+        # and related functions for small and zero-sized arrays.
+        A = np.zeros(shape, dtype=dt)
+        A0 = np.zeros((10, 10), dtype=dt)
+        result = func(A)
+        result0 = func(A0)
+        assert result.shape == shape
+        assert result.dtype == result0.dtype
+
+    def test_2x2_input(self):
+        E = np.e
+        a = array([[1, 4], [1, 1]])
+        aa = (E**4 + 1)/(2*E)
+        bb = (E**4 - 1)/E
+        assert_allclose(expm(a), array([[aa, bb], [bb/4, aa]]))
+        assert expm(a.astype(np.complex64)).dtype.char == 'F'
+        assert expm(a.astype(np.float32)).dtype.char == 'f'
+
+    def test_nx2x2_input(self):
+        E = np.e
+        # These are integer matrices with integer eigenvalues
+        a = np.array([[[1, 4], [1, 1]],
+                      [[1, 3], [1, -1]],
+                      [[1, 3], [4, 5]],
+                      [[1, 3], [5, 3]],
+                      [[4, 5], [-3, -4]]], order='F')
+        # Exact results are computed symbolically
+        a_res = np.array([
+                          [[(E**4+1)/(2*E), (E**4-1)/E],
+                           [(E**4-1)/4/E, (E**4+1)/(2*E)]],
+                          [[1/(4*E**2)+(3*E**2)/4, (3*E**2)/4-3/(4*E**2)],
+                           [E**2/4-1/(4*E**2), 3/(4*E**2)+E**2/4]],
+                          [[3/(4*E)+E**7/4, -3/(8*E)+(3*E**7)/8],
+                           [-1/(2*E)+E**7/2, 1/(4*E)+(3*E**7)/4]],
+                          [[5/(8*E**2)+(3*E**6)/8, -3/(8*E**2)+(3*E**6)/8],
+                           [-5/(8*E**2)+(5*E**6)/8, 3/(8*E**2)+(5*E**6)/8]],
+                          [[-3/(2*E)+(5*E)/2, -5/(2*E)+(5*E)/2],
+                           [3/(2*E)-(3*E)/2, 5/(2*E)-(3*E)/2]]
+                         ])
+        assert_allclose(expm(a), a_res)
+
+    def test_readonly(self):
+        n = 7
+        a = np.ones((n, n))
+        a.flags.writeable = False
+        expm(a)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.fail_slow(5)
+    def test_gh18086(self):
+        A = np.zeros((400, 400), dtype=float)
+        rng = np.random.default_rng(100)
+        i = rng.integers(0, 399, 500)
+        j = rng.integers(0, 399, 500)
+        A[i, j] = rng.random(500)
+        # Problem appears when m = 9
+        Am = np.empty((5, 400, 400), dtype=float)
+        Am[0] = A.copy()
+        m, s = pick_pade_structure(Am)
+        assert m == 9
+        # Check that result is accurate
+        first_res = expm(A)
+        np.testing.assert_array_almost_equal(logm(first_res), A)
+        # Check that result is consistent
+        for i in range(5):
+            next_res = expm(A)
+            np.testing.assert_array_almost_equal(first_res, next_res)
+
+
+class TestExpmFrechet:
+
+    def test_expm_frechet(self):
+        # a test of the basic functionality
+        M = np.array([
+            [1, 2, 3, 4],
+            [5, 6, 7, 8],
+            [0, 0, 1, 2],
+            [0, 0, 5, 6],
+            ], dtype=float)
+        A = np.array([
+            [1, 2],
+            [5, 6],
+            ], dtype=float)
+        E = np.array([
+            [3, 4],
+            [7, 8],
+            ], dtype=float)
+        expected_expm = scipy.linalg.expm(A)
+        expected_frechet = scipy.linalg.expm(M)[:2, 2:]
+        for kwargs in ({}, {'method':'SPS'}, {'method':'blockEnlarge'}):
+            observed_expm, observed_frechet = expm_frechet(A, E, **kwargs)
+            assert_allclose(expected_expm, observed_expm)
+            assert_allclose(expected_frechet, observed_frechet)
+
+    def test_small_norm_expm_frechet(self):
+        # methodically test matrices with a range of norms, for better coverage
+        M_original = np.array([
+            [1, 2, 3, 4],
+            [5, 6, 7, 8],
+            [0, 0, 1, 2],
+            [0, 0, 5, 6],
+            ], dtype=float)
+        A_original = np.array([
+            [1, 2],
+            [5, 6],
+            ], dtype=float)
+        E_original = np.array([
+            [3, 4],
+            [7, 8],
+            ], dtype=float)
+        A_original_norm_1 = scipy.linalg.norm(A_original, 1)
+        selected_m_list = [1, 3, 5, 7, 9, 11, 13, 15]
+        m_neighbor_pairs = zip(selected_m_list[:-1], selected_m_list[1:])
+        for ma, mb in m_neighbor_pairs:
+            ell_a = scipy.linalg._expm_frechet.ell_table_61[ma]
+            ell_b = scipy.linalg._expm_frechet.ell_table_61[mb]
+            target_norm_1 = 0.5 * (ell_a + ell_b)
+            scale = target_norm_1 / A_original_norm_1
+            M = scale * M_original
+            A = scale * A_original
+            E = scale * E_original
+            expected_expm = scipy.linalg.expm(A)
+            expected_frechet = scipy.linalg.expm(M)[:2, 2:]
+            observed_expm, observed_frechet = expm_frechet(A, E)
+            assert_allclose(expected_expm, observed_expm)
+            assert_allclose(expected_frechet, observed_frechet)
+
+    def test_fuzz(self):
+        rng = np.random.default_rng(1726500908359153)
+        # try a bunch of crazy inputs
+        rfuncs = (
+                np.random.uniform,
+                np.random.normal,
+                np.random.standard_cauchy,
+                np.random.exponential)
+        ntests = 100
+        for i in range(ntests):
+            rfunc = rfuncs[rng.choice(4)]
+            target_norm_1 = rng.exponential()
+            n = rng.integers(2, 16)
+            A_original = rfunc(size=(n,n))
+            E_original = rfunc(size=(n,n))
+            A_original_norm_1 = scipy.linalg.norm(A_original, 1)
+            scale = target_norm_1 / A_original_norm_1
+            A = scale * A_original
+            E = scale * E_original
+            M = np.vstack([
+                np.hstack([A, E]),
+                np.hstack([np.zeros_like(A), A])])
+            expected_expm = scipy.linalg.expm(A)
+            expected_frechet = scipy.linalg.expm(M)[:n, n:]
+            observed_expm, observed_frechet = expm_frechet(A, E)
+            assert_allclose(expected_expm, observed_expm, atol=5e-8)
+            assert_allclose(expected_frechet, observed_frechet, atol=1e-7)
+
+    def test_problematic_matrix(self):
+        # this test case uncovered a bug which has since been fixed
+        A = np.array([
+                [1.50591997, 1.93537998],
+                [0.41203263, 0.23443516],
+                ], dtype=float)
+        E = np.array([
+                [1.87864034, 2.07055038],
+                [1.34102727, 0.67341123],
+                ], dtype=float)
+        scipy.linalg.norm(A, 1)
+        sps_expm, sps_frechet = expm_frechet(
+                A, E, method='SPS')
+        blockEnlarge_expm, blockEnlarge_frechet = expm_frechet(
+                A, E, method='blockEnlarge')
+        assert_allclose(sps_expm, blockEnlarge_expm)
+        assert_allclose(sps_frechet, blockEnlarge_frechet)
+
+    @pytest.mark.slow
+    @pytest.mark.skip(reason='this test is deliberately slow')
+    def test_medium_matrix(self):
+        # profile this to see the speed difference
+        n = 1000
+        A = np.random.exponential(size=(n, n))
+        E = np.random.exponential(size=(n, n))
+        sps_expm, sps_frechet = expm_frechet(
+                A, E, method='SPS')
+        blockEnlarge_expm, blockEnlarge_frechet = expm_frechet(
+                A, E, method='blockEnlarge')
+        assert_allclose(sps_expm, blockEnlarge_expm)
+        assert_allclose(sps_frechet, blockEnlarge_frechet)
+
+
+def _help_expm_cond_search(A, A_norm, X, X_norm, eps, p):
+    p = np.reshape(p, A.shape)
+    p_norm = norm(p)
+    perturbation = eps * p * (A_norm / p_norm)
+    X_prime = expm(A + perturbation)
+    scaled_relative_error = norm(X_prime - X) / (X_norm * eps)
+    return -scaled_relative_error
+
+
+def _normalized_like(A, B):
+    return A * (scipy.linalg.norm(B) / scipy.linalg.norm(A))
+
+
+def _relative_error(f, A, perturbation):
+    X = f(A)
+    X_prime = f(A + perturbation)
+    return norm(X_prime - X) / norm(X)
+
+
+class TestExpmConditionNumber:
+    def test_expm_cond_smoke(self):
+        np.random.seed(1234)
+        for n in range(1, 4):
+            A = np.random.randn(n, n)
+            kappa = expm_cond(A)
+            assert_array_less(0, kappa)
+
+    def test_expm_bad_condition_number(self):
+        A = np.array([
+            [-1.128679820, 9.614183771e4, -4.524855739e9, 2.924969411e14],
+            [0, -1.201010529, 9.634696872e4, -4.681048289e9],
+            [0, 0, -1.132893222, 9.532491830e4],
+            [0, 0, 0, -1.179475332],
+            ])
+        kappa = expm_cond(A)
+        assert_array_less(1e36, kappa)
+
+    def test_univariate(self):
+        np.random.seed(12345)
+        for x in np.linspace(-5, 5, num=11):
+            A = np.array([[x]])
+            assert_allclose(expm_cond(A), abs(x))
+        for x in np.logspace(-2, 2, num=11):
+            A = np.array([[x]])
+            assert_allclose(expm_cond(A), abs(x))
+        for i in range(10):
+            A = np.random.randn(1, 1)
+            assert_allclose(expm_cond(A), np.absolute(A)[0, 0])
+
+    @pytest.mark.slow
+    def test_expm_cond_fuzz(self):
+        rng = np.random.RandomState(12345)
+        eps = 1e-5
+        nsamples = 10
+        for i in range(nsamples):
+            n = rng.randint(2, 5)
+            A = rng.randn(n, n)
+            A_norm = scipy.linalg.norm(A)
+            X = expm(A)
+            X_norm = scipy.linalg.norm(X)
+            kappa = expm_cond(A)
+
+            # Look for the small perturbation that gives the greatest
+            # relative error.
+            f = functools.partial(_help_expm_cond_search,
+                    A, A_norm, X, X_norm, eps)
+            guess = np.ones(n*n)
+            out = minimize(f, guess, method='L-BFGS-B')
+            xopt = out.x
+            yopt = f(xopt)
+            p_best = eps * _normalized_like(np.reshape(xopt, A.shape), A)
+            p_best_relerr = _relative_error(expm, A, p_best)
+            assert_allclose(p_best_relerr, -yopt * eps)
+
+            # Check that the identified perturbation indeed gives greater
+            # relative error than random perturbations with similar norms.
+            for j in range(5):
+                p_rand = eps * _normalized_like(rng.randn(*A.shape), A)
+                assert_allclose(norm(p_best), norm(p_rand))
+                p_rand_relerr = _relative_error(expm, A, p_rand)
+                assert_array_less(p_rand_relerr, p_best_relerr)
+
+            # The greatest relative error should not be much greater than
+            # eps times the condition number kappa.
+            # In the limit as eps approaches zero it should never be greater.
+            assert_array_less(p_best_relerr, (1 + 2*eps) * eps * kappa)
+
+
+class TestKhatriRao:
+
+    def test_basic(self):
+        a = khatri_rao(array([[1, 2], [3, 4]]),
+                       array([[5, 6], [7, 8]]))
+
+        assert_array_equal(a, array([[5, 12],
+                                     [7, 16],
+                                     [15, 24],
+                                     [21, 32]]))
+
+        b = khatri_rao(np.empty([2, 2]), np.empty([2, 2]))
+        assert_array_equal(b.shape, (4, 2))
+
+    def test_number_of_columns_equality(self):
+        with pytest.raises(ValueError):
+            a = array([[1, 2, 3],
+                       [4, 5, 6]])
+            b = array([[1, 2],
+                       [3, 4]])
+            khatri_rao(a, b)
+
+    def test_to_assure_2d_array(self):
+        with pytest.raises(ValueError):
+            # both arrays are 1-D
+            a = array([1, 2, 3])
+            b = array([4, 5, 6])
+            khatri_rao(a, b)
+
+        with pytest.raises(ValueError):
+            # first array is 1-D
+            a = array([1, 2, 3])
+            b = array([
+                [1, 2, 3],
+                [4, 5, 6]
+            ])
+            khatri_rao(a, b)
+
+        with pytest.raises(ValueError):
+            # second array is 1-D
+            a = array([
+                [1, 2, 3],
+                [7, 8, 9]
+            ])
+            b = array([4, 5, 6])
+            khatri_rao(a, b)
+
+    def test_equality_of_two_equations(self):
+        a = array([[1, 2], [3, 4]])
+        b = array([[5, 6], [7, 8]])
+
+        res1 = khatri_rao(a, b)
+        res2 = np.vstack([np.kron(a[:, k], b[:, k])
+                          for k in range(b.shape[1])]).T
+
+        assert_array_equal(res1, res2)
+
+    def test_empty(self):
+        a = np.empty((0, 2))
+        b = np.empty((3, 2))
+        res = khatri_rao(a, b)
+        assert_allclose(res, np.empty((0, 2)))
+
+        a = np.empty((3, 0))
+        b = np.empty((5, 0))
+        res = khatri_rao(a, b)
+        assert_allclose(res, np.empty((15, 0)))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f8f94fd10a5404d4013adf995bba54f76ff803
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_matmul_toeplitz.py
@@ -0,0 +1,136 @@
+"""Test functions for linalg.matmul_toeplitz function
+"""
+
+import numpy as np
+from scipy.linalg import toeplitz, matmul_toeplitz
+
+from pytest import raises as assert_raises
+from numpy.testing import assert_allclose
+
+
+class TestMatmulToeplitz:
+
+    def setup_method(self):
+        self.rng = np.random.RandomState(42)
+        self.tolerance = 1.5e-13
+
+    def test_real(self):
+        cases = []
+
+        n = 1
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, 1))
+        cases.append((x, c, r, False))
+
+        n = 2
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, 1))
+        cases.append((x, c, r, False))
+
+        n = 101
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, 1))
+        cases.append((x, c, r, True))
+
+        n = 1000
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, 1))
+        cases.append((x, c, r, False))
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
+        cases.append((x, c, r, False))
+
+        n = 100
+        c = self.rng.normal(size=(n, 1))
+        r = self.rng.normal(size=(n, 1))
+        x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
+        cases.append((x, c, r, True))
+
+        n = 100
+        c = self.rng.normal(size=(n, 1))
+        r = None
+        x = self.rng.normal(size=(n, self.rng.randint(1, 10)))
+        cases.append((x, c, r, True, -1))
+
+        n = 100
+        c = self.rng.normal(size=(n, 1))
+        r = None
+        x = self.rng.normal(size=n)
+        cases.append((x, c, r, False))
+
+        n = 101
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n-27)
+        x = self.rng.normal(size=(n-27, 1))
+        cases.append((x, c, r, True))
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n//4)
+        x = self.rng.normal(size=(n//4, self.rng.randint(1, 10)))
+        cases.append((x, c, r, True))
+
+        [self.do(*i) for i in cases]
+
+    def test_complex(self):
+        n = 127
+        c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
+        r = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
+        x = self.rng.normal(size=(n, 3)) + self.rng.normal(size=(n, 3))*1j
+        self.do(x, c, r, False)
+
+        n = 100
+        c = self.rng.normal(size=(n, 1)) + self.rng.normal(size=(n, 1))*1j
+        r = self.rng.normal(size=(n//2, 1)) +\
+            self.rng.normal(size=(n//2, 1))*1j
+        x = self.rng.normal(size=(n//2, 3)) +\
+            self.rng.normal(size=(n//2, 3))*1j
+        self.do(x, c, r, False)
+
+    def test_empty(self):
+        c = []
+        r = []
+        x = []
+        self.do(x, c, r, False)
+
+        x = np.empty((0, 0))
+        self.do(x, c, r, False)
+
+    def test_exceptions(self):
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=2*n)
+        x = self.rng.normal(size=n)
+        assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n)
+        x = self.rng.normal(size=n-1)
+        assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
+
+        n = 100
+        c = self.rng.normal(size=n)
+        r = self.rng.normal(size=n//2)
+        x = self.rng.normal(size=n//2-1)
+        assert_raises(ValueError, matmul_toeplitz, (c, r), x, True)
+
+    # For toeplitz matrices, matmul_toeplitz() should be equivalent to @.
+    def do(self, x, c, r=None, check_finite=False, workers=None):
+        c = np.ravel(c)
+        if r is None:
+            actual = matmul_toeplitz(c, x, check_finite, workers)
+        else:
+            r = np.ravel(r)
+            actual = matmul_toeplitz((c, r), x, check_finite)
+        desired = toeplitz(c, r) @ x
+        assert_allclose(actual, desired,
+            rtol=self.tolerance, atol=self.tolerance)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py
new file mode 100644
index 0000000000000000000000000000000000000000..4efa433c2cab01a4f77ef1c4f1bde3ab4d5c421b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_procrustes.py
@@ -0,0 +1,221 @@
+from itertools import product, permutations
+
+import numpy as np
+import pytest
+from numpy.testing import assert_array_less, assert_allclose
+from pytest import raises as assert_raises
+
+from scipy.linalg import inv, eigh, norm, svd
+from scipy.linalg import orthogonal_procrustes
+from scipy.sparse._sputils import matrix
+
+
+def test_orthogonal_procrustes_ndim_too_large():
+    rng = np.random.RandomState(1234)
+    A = rng.randn(3, 4, 5)
+    B = rng.randn(3, 4, 5)
+    assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_ndim_too_small():
+    rng = np.random.RandomState(1234)
+    A = rng.randn(3)
+    B = rng.randn(3)
+    assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_shape_mismatch():
+    rng = np.random.RandomState(1234)
+    shapes = ((3, 3), (3, 4), (4, 3), (4, 4))
+    for a, b in permutations(shapes, 2):
+        A = rng.randn(*a)
+        B = rng.randn(*b)
+        assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_checkfinite_exception():
+    rng = np.random.RandomState(1234)
+    m, n = 2, 3
+    A_good = rng.randn(m, n)
+    B_good = rng.randn(m, n)
+    for bad_value in np.inf, -np.inf, np.nan:
+        A_bad = A_good.copy()
+        A_bad[1, 2] = bad_value
+        B_bad = B_good.copy()
+        B_bad[1, 2] = bad_value
+        for A, B in ((A_good, B_bad), (A_bad, B_good), (A_bad, B_bad)):
+            assert_raises(ValueError, orthogonal_procrustes, A, B)
+
+
+def test_orthogonal_procrustes_scale_invariance():
+    rng = np.random.RandomState(1234)
+    m, n = 4, 3
+    for i in range(3):
+        A_orig = rng.randn(m, n)
+        B_orig = rng.randn(m, n)
+        R_orig, s = orthogonal_procrustes(A_orig, B_orig)
+        for A_scale in np.square(rng.randn(3)):
+            for B_scale in np.square(rng.randn(3)):
+                R, s = orthogonal_procrustes(A_orig * A_scale, B_orig * B_scale)
+                assert_allclose(R, R_orig)
+
+
+def test_orthogonal_procrustes_array_conversion():
+    rng = np.random.RandomState(1234)
+    for m, n in ((6, 4), (4, 4), (4, 6)):
+        A_arr = rng.randn(m, n)
+        B_arr = rng.randn(m, n)
+        As = (A_arr, A_arr.tolist(), matrix(A_arr))
+        Bs = (B_arr, B_arr.tolist(), matrix(B_arr))
+        R_arr, s = orthogonal_procrustes(A_arr, B_arr)
+        AR_arr = A_arr.dot(R_arr)
+        for A, B in product(As, Bs):
+            R, s = orthogonal_procrustes(A, B)
+            AR = A_arr.dot(R)
+            assert_allclose(AR, AR_arr)
+
+
+def test_orthogonal_procrustes():
+    rng = np.random.RandomState(1234)
+    for m, n in ((6, 4), (4, 4), (4, 6)):
+        # Sample a random target matrix.
+        B = rng.randn(m, n)
+        # Sample a random orthogonal matrix
+        # by computing eigh of a sampled symmetric matrix.
+        X = rng.randn(n, n)
+        w, V = eigh(X.T + X)
+        assert_allclose(inv(V), V.T)
+        # Compute a matrix with a known orthogonal transformation that gives B.
+        A = np.dot(B, V.T)
+        # Check that an orthogonal transformation from A to B can be recovered.
+        R, s = orthogonal_procrustes(A, B)
+        assert_allclose(inv(R), R.T)
+        assert_allclose(A.dot(R), B)
+        # Create a perturbed input matrix.
+        A_perturbed = A + 1e-2 * rng.randn(m, n)
+        # Check that the orthogonal procrustes function can find an orthogonal
+        # transformation that is better than the orthogonal transformation
+        # computed from the original input matrix.
+        R_prime, s = orthogonal_procrustes(A_perturbed, B)
+        assert_allclose(inv(R_prime), R_prime.T)
+        # Compute the naive and optimal transformations of the perturbed input.
+        naive_approx = A_perturbed.dot(R)
+        optim_approx = A_perturbed.dot(R_prime)
+        # Compute the Frobenius norm errors of the matrix approximations.
+        naive_approx_error = norm(naive_approx - B, ord='fro')
+        optim_approx_error = norm(optim_approx - B, ord='fro')
+        # Check that the orthogonal Procrustes approximation is better.
+        assert_array_less(optim_approx_error, naive_approx_error)
+
+
+def _centered(A):
+    mu = A.mean(axis=0)
+    return A - mu, mu
+
+
+def test_orthogonal_procrustes_exact_example():
+    # Check a small application.
+    # It uses translation, scaling, reflection, and rotation.
+    #
+    #         |
+    #   a  b  |
+    #         |
+    #   d  c  |        w
+    #         |
+    # --------+--- x ----- z ---
+    #         |
+    #         |        y
+    #         |
+    #
+    A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float)
+    B_orig = np.array([[3, 2], [1, 0], [3, -2], [5, 0]], dtype=float)
+    A, A_mu = _centered(A_orig)
+    B, B_mu = _centered(B_orig)
+    R, s = orthogonal_procrustes(A, B)
+    scale = s / np.square(norm(A))
+    B_approx = scale * np.dot(A, R) + B_mu
+    assert_allclose(B_approx, B_orig, atol=1e-8)
+
+
+def test_orthogonal_procrustes_stretched_example():
+    # Try again with a target with a stretched y axis.
+    A_orig = np.array([[-3, 3], [-2, 3], [-2, 2], [-3, 2]], dtype=float)
+    B_orig = np.array([[3, 40], [1, 0], [3, -40], [5, 0]], dtype=float)
+    A, A_mu = _centered(A_orig)
+    B, B_mu = _centered(B_orig)
+    R, s = orthogonal_procrustes(A, B)
+    scale = s / np.square(norm(A))
+    B_approx = scale * np.dot(A, R) + B_mu
+    expected = np.array([[3, 21], [-18, 0], [3, -21], [24, 0]], dtype=float)
+    assert_allclose(B_approx, expected, atol=1e-8)
+    # Check disparity symmetry.
+    expected_disparity = 0.4501246882793018
+    AB_disparity = np.square(norm(B_approx - B_orig) / norm(B))
+    assert_allclose(AB_disparity, expected_disparity)
+    R, s = orthogonal_procrustes(B, A)
+    scale = s / np.square(norm(B))
+    A_approx = scale * np.dot(B, R) + A_mu
+    BA_disparity = np.square(norm(A_approx - A_orig) / norm(A))
+    assert_allclose(BA_disparity, expected_disparity)
+
+
+def test_orthogonal_procrustes_skbio_example():
+    # This transformation is also exact.
+    # It uses translation, scaling, and reflection.
+    #
+    #   |
+    #   | a
+    #   | b
+    #   | c d
+    # --+---------
+    #   |
+    #   |       w
+    #   |
+    #   |       x
+    #   |
+    #   |   z   y
+    #   |
+    #
+    A_orig = np.array([[4, -2], [4, -4], [4, -6], [2, -6]], dtype=float)
+    B_orig = np.array([[1, 3], [1, 2], [1, 1], [2, 1]], dtype=float)
+    B_standardized = np.array([
+        [-0.13363062, 0.6681531],
+        [-0.13363062, 0.13363062],
+        [-0.13363062, -0.40089186],
+        [0.40089186, -0.40089186]])
+    A, A_mu = _centered(A_orig)
+    B, B_mu = _centered(B_orig)
+    R, s = orthogonal_procrustes(A, B)
+    scale = s / np.square(norm(A))
+    B_approx = scale * np.dot(A, R) + B_mu
+    assert_allclose(B_approx, B_orig)
+    assert_allclose(B / norm(B), B_standardized)
+
+
+def test_empty():
+    a = np.empty((0, 0))
+    r, s = orthogonal_procrustes(a, a)
+    assert_allclose(r, np.empty((0, 0)))
+
+    a = np.empty((0, 3))
+    r, s = orthogonal_procrustes(a, a)
+    assert_allclose(r, np.identity(3))
+
+
+@pytest.mark.parametrize('shape', [(4, 5), (5, 5), (5, 4)])
+def test_unitary(shape):
+    # gh-12071 added support for unitary matrices; check that it
+    # works as intended.
+    m, n = shape
+    rng = np.random.default_rng(589234981235)
+    A = rng.random(shape) + rng.random(shape) * 1j
+    Q = rng.random((n, n)) + rng.random((n, n)) * 1j
+    Q, _ = np.linalg.qr(Q)
+    B = A @ Q
+    R, scale = orthogonal_procrustes(A, B)
+    assert_allclose(R @ R.conj().T, np.eye(n), atol=1e-14)
+    assert_allclose(A @ Q, B)
+    if shape != (4, 5):  # solution is unique
+        assert_allclose(R, Q)
+    _, s, _ = svd(A.conj().T @ B)
+    assert_allclose(scale, np.sum(s))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fc5a8540510f57a2b00334b5e190d4ddd474d09
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_sketches.py
@@ -0,0 +1,118 @@
+"""Tests for _sketches.py."""
+
+import numpy as np
+from numpy.testing import assert_, assert_equal
+from scipy.linalg import clarkson_woodruff_transform
+from scipy.linalg._sketches import cwt_matrix
+from scipy.sparse import issparse, rand
+from scipy.sparse.linalg import norm
+
+
+class TestClarksonWoodruffTransform:
+    """
+    Testing the Clarkson Woodruff Transform
+    """
+    # set seed for generating test matrices
+    rng = np.random.default_rng(1179103485)
+
+    # Test matrix parameters
+    n_rows = 2000
+    n_cols = 100
+    density = 0.1
+
+    # Sketch matrix dimensions
+    n_sketch_rows = 200
+
+    # Seeds to test with
+    seeds = [1755490010, 934377150, 1391612830, 1752708722, 2008891431,
+             1302443994, 1521083269, 1501189312, 1126232505, 1533465685]
+
+    A_dense = rng.random((n_rows, n_cols))
+    A_csc = rand(
+        n_rows, n_cols, density=density, format='csc', random_state=rng,
+    )
+    A_csr = rand(
+        n_rows, n_cols, density=density, format='csr', random_state=rng,
+    )
+    A_coo = rand(
+        n_rows, n_cols, density=density, format='coo', random_state=rng,
+    )
+
+    # Collect the test matrices
+    test_matrices = [
+        A_dense, A_csc, A_csr, A_coo,
+    ]
+
+    # Test vector with norm ~1
+    x = rng.random((n_rows, 1)) / np.sqrt(n_rows)
+
+    def test_sketch_dimensions(self):
+        for A in self.test_matrices:
+            for seed in self.seeds:
+                # seed to ensure backwards compatibility post SPEC7
+                sketch = clarkson_woodruff_transform(
+                    A, self.n_sketch_rows, seed=seed
+                )
+                assert_(sketch.shape == (self.n_sketch_rows, self.n_cols))
+
+    def test_seed_returns_identical_transform_matrix(self):
+        for seed in self.seeds:
+            S1 = cwt_matrix(
+                self.n_sketch_rows, self.n_rows, rng=seed
+            ).toarray()
+            S2 = cwt_matrix(
+                self.n_sketch_rows, self.n_rows, rng=seed
+            ).toarray()
+            assert_equal(S1, S2)
+
+    def test_seed_returns_identically(self):
+        for A in self.test_matrices:
+            for seed in self.seeds:
+                sketch1 = clarkson_woodruff_transform(
+                    A, self.n_sketch_rows, rng=seed
+                )
+                sketch2 = clarkson_woodruff_transform(
+                    A, self.n_sketch_rows, rng=seed
+                )
+                if issparse(sketch1):
+                    sketch1 = sketch1.toarray()
+                if issparse(sketch2):
+                    sketch2 = sketch2.toarray()
+                assert_equal(sketch1, sketch2)
+
+    def test_sketch_preserves_frobenius_norm(self):
+        # Given the probabilistic nature of the sketches
+        # we run the test multiple times and check that
+        # we pass all/almost all the tries.
+        n_errors = 0
+        for A in self.test_matrices:
+            if issparse(A):
+                true_norm = norm(A)
+            else:
+                true_norm = np.linalg.norm(A)
+            for seed in self.seeds:
+                sketch = clarkson_woodruff_transform(
+                    A, self.n_sketch_rows, rng=seed,
+                )
+                if issparse(sketch):
+                    sketch_norm = norm(sketch)
+                else:
+                    sketch_norm = np.linalg.norm(sketch)
+
+                if np.abs(true_norm - sketch_norm) > 0.1 * true_norm:
+                    n_errors += 1
+        assert_(n_errors == 0)
+
+    def test_sketch_preserves_vector_norm(self):
+        n_errors = 0
+        n_sketch_rows = int(np.ceil(2. / (0.01 * 0.5**2)))
+        true_norm = np.linalg.norm(self.x)
+        for seed in self.seeds:
+            sketch = clarkson_woodruff_transform(
+                self.x, n_sketch_rows, rng=seed,
+            )
+            sketch_norm = np.linalg.norm(sketch)
+
+            if np.abs(true_norm - sketch_norm) > 0.5 * true_norm:
+                n_errors += 1
+        assert_(n_errors == 0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py
new file mode 100644
index 0000000000000000000000000000000000000000..440a73abc8c83bc32887c37c75577b790f3f1be9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solve_toeplitz.py
@@ -0,0 +1,150 @@
+"""Test functions for linalg._solve_toeplitz module
+"""
+import numpy as np
+from scipy.linalg._solve_toeplitz import levinson
+from scipy.linalg import solve, toeplitz, solve_toeplitz, matmul_toeplitz
+from numpy.testing import assert_equal, assert_allclose
+
+import pytest
+from pytest import raises as assert_raises
+
+
+def test_solve_equivalence():
+    # For toeplitz matrices, solve_toeplitz() should be equivalent to solve().
+    random = np.random.RandomState(1234)
+    for n in (1, 2, 3, 10):
+        c = random.randn(n)
+        if random.rand() < 0.5:
+            c = c + 1j * random.randn(n)
+        r = random.randn(n)
+        if random.rand() < 0.5:
+            r = r + 1j * random.randn(n)
+        y = random.randn(n)
+        if random.rand() < 0.5:
+            y = y + 1j * random.randn(n)
+
+        # Check equivalence when both the column and row are provided.
+        actual = solve_toeplitz((c,r), y)
+        desired = solve(toeplitz(c, r=r), y)
+        assert_allclose(actual, desired)
+
+        # Check equivalence when the column is provided but not the row.
+        actual = solve_toeplitz(c, b=y)
+        desired = solve(toeplitz(c), y)
+        assert_allclose(actual, desired)
+
+
+def test_multiple_rhs():
+    random = np.random.RandomState(1234)
+    c = random.randn(4)
+    r = random.randn(4)
+    for offset in [0, 1j]:
+        for yshape in ((4,), (4, 3), (4, 3, 2)):
+            y = random.randn(*yshape) + offset
+            actual = solve_toeplitz((c,r), b=y)
+            desired = solve(toeplitz(c, r=r), y)
+            assert_equal(actual.shape, yshape)
+            assert_equal(desired.shape, yshape)
+            assert_allclose(actual, desired)
+
+
+def test_native_list_arguments():
+    c = [1,2,4,7]
+    r = [1,3,9,12]
+    y = [5,1,4,2]
+    actual = solve_toeplitz((c,r), y)
+    desired = solve(toeplitz(c, r=r), y)
+    assert_allclose(actual, desired)
+
+
+def test_zero_diag_error():
+    # The Levinson-Durbin implementation fails when the diagonal is zero.
+    random = np.random.RandomState(1234)
+    n = 4
+    c = random.randn(n)
+    r = random.randn(n)
+    y = random.randn(n)
+    c[0] = 0
+    assert_raises(np.linalg.LinAlgError,
+        solve_toeplitz, (c, r), b=y)
+
+
+def test_wikipedia_counterexample():
+    # The Levinson-Durbin implementation also fails in other cases.
+    # This example is from the talk page of the wikipedia article.
+    random = np.random.RandomState(1234)
+    c = [2, 2, 1]
+    y = random.randn(3)
+    assert_raises(np.linalg.LinAlgError, solve_toeplitz, c, b=y)
+
+
+def test_reflection_coeffs():
+    # check that the partial solutions are given by the reflection
+    # coefficients
+
+    random = np.random.RandomState(1234)
+    y_d = random.randn(10)
+    y_z = random.randn(10) + 1j
+    reflection_coeffs_d = [1]
+    reflection_coeffs_z = [1]
+    for i in range(2, 10):
+        reflection_coeffs_d.append(solve_toeplitz(y_d[:(i-1)], b=y_d[1:i])[-1])
+        reflection_coeffs_z.append(solve_toeplitz(y_z[:(i-1)], b=y_z[1:i])[-1])
+
+    y_d_concat = np.concatenate((y_d[-2:0:-1], y_d[:-1]))
+    y_z_concat = np.concatenate((y_z[-2:0:-1].conj(), y_z[:-1]))
+    _, ref_d = levinson(y_d_concat, b=y_d[1:])
+    _, ref_z = levinson(y_z_concat, b=y_z[1:])
+
+    assert_allclose(reflection_coeffs_d, ref_d[:-1])
+    assert_allclose(reflection_coeffs_z, ref_z[:-1])
+
+
+@pytest.mark.xfail(reason='Instability of Levinson iteration')
+def test_unstable():
+    # this is a "Gaussian Toeplitz matrix", as mentioned in Example 2 of
+    # I. Gohbert, T. Kailath and V. Olshevsky "Fast Gaussian Elimination with
+    # Partial Pivoting for Matrices with Displacement Structure"
+    # Mathematics of Computation, 64, 212 (1995), pp 1557-1576
+    # which can be unstable for levinson recursion.
+
+    # other fast toeplitz solvers such as GKO or Burg should be better.
+    random = np.random.RandomState(1234)
+    n = 100
+    c = 0.9 ** (np.arange(n)**2)
+    y = random.randn(n)
+
+    solution1 = solve_toeplitz(c, b=y)
+    solution2 = solve(toeplitz(c), y)
+
+    assert_allclose(solution1, solution2)
+
+
+@pytest.mark.parametrize('dt_c', [int, float, np.float32, complex, np.complex64])
+@pytest.mark.parametrize('dt_b', [int, float, np.float32, complex, np.complex64])
+def test_empty(dt_c, dt_b):
+    c = np.array([], dtype=dt_c)
+    b = np.array([], dtype=dt_b)
+    x = solve_toeplitz(c, b)
+    assert x.shape == (0,)
+    assert x.dtype == solve_toeplitz(np.array([2, 1], dtype=dt_c),
+                                      np.ones(2, dtype=dt_b)).dtype
+
+    b = np.empty((0, 0), dtype=dt_b)
+    x1 = solve_toeplitz(c, b)
+    assert x1.shape == (0, 0)
+    assert x1.dtype == x.dtype
+
+
+@pytest.mark.parametrize('fun', [solve_toeplitz, matmul_toeplitz])
+def test_nd_FutureWarning(fun):
+    # Test future warnings with n-D `c`/`r`
+    rng = np.random.default_rng(283592436523456)
+    c = rng.random((2, 3, 4))
+    r = rng.random((2, 3, 4))
+    b_or_x = rng.random(24)
+    message = "Beginning in SciPy 1.17, multidimensional input will be..."
+    with pytest.warns(FutureWarning, match=message):
+         fun(c, b_or_x)
+    with pytest.warns(FutureWarning, match=message):
+         fun((c, r), b_or_x)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4a39c5e86939bddabafaaf87c643c0a4ad570fe
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_solvers.py
@@ -0,0 +1,844 @@
+import os
+import numpy as np
+
+from numpy.testing import assert_array_almost_equal, assert_allclose
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.linalg import solve_sylvester
+from scipy.linalg import solve_continuous_lyapunov, solve_discrete_lyapunov
+from scipy.linalg import solve_continuous_are, solve_discrete_are
+from scipy.linalg import block_diag, solve, LinAlgError
+from scipy.sparse._sputils import matrix
+
+
+# dtypes for testing size-0 case following precedent set in gh-20295
+dtypes = [int, float, np.float32, complex, np.complex64]
+
+
+def _load_data(name):
+    """
+    Load npz data file under data/
+    Returns a copy of the data, rather than keeping the npz file open.
+    """
+    filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),
+                            'data', name)
+    with np.load(filename) as f:
+        return dict(f.items())
+
+
+class TestSolveLyapunov:
+
+    cases = [
+        # empty case
+        (np.empty((0, 0)),
+         np.empty((0, 0))),
+        (np.array([[1, 2], [3, 4]]),
+         np.array([[9, 10], [11, 12]])),
+        # a, q all complex.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a real; q complex.
+        (np.array([[1.0, 2.0], [3.0, 5.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a complex; q real.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[2.0, 2.0], [-1.0, 2.0]])),
+        # An example from Kitagawa, 1977
+        (np.array([[3, 9, 5, 1, 4], [1, 2, 3, 8, 4], [4, 6, 6, 6, 3],
+                   [1, 5, 2, 0, 7], [5, 3, 3, 1, 5]]),
+         np.array([[2, 4, 1, 0, 1], [4, 1, 0, 2, 0], [1, 0, 3, 0, 3],
+                   [0, 2, 0, 1, 0], [1, 0, 3, 0, 4]])),
+        # Companion matrix example. a complex; q real; a.shape[0] = 11
+        (np.array([[0.100+0.j, 0.091+0.j, 0.082+0.j, 0.073+0.j, 0.064+0.j,
+                    0.055+0.j, 0.046+0.j, 0.037+0.j, 0.028+0.j, 0.019+0.j,
+                    0.010+0.j],
+                   [1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j, 0.000+0.j,
+                    0.000+0.j],
+                   [0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j,
+                    0.000+0.j, 0.000+0.j, 0.000+0.j, 0.000+0.j, 1.000+0.j,
+                    0.000+0.j]]),
+         np.eye(11)),
+        # https://github.com/scipy/scipy/issues/4176
+        (matrix([[0, 1], [-1/2, -1]]),
+         (matrix([0, 3]).T @ matrix([0, 3]).T.T)),
+        # https://github.com/scipy/scipy/issues/4176
+        (matrix([[0, 1], [-1/2, -1]]),
+         (np.array(matrix([0, 3]).T @ matrix([0, 3]).T.T))),
+        ]
+
+    def test_continuous_squareness_and_shape(self):
+        nsq = np.ones((3, 2))
+        sq = np.eye(3)
+        assert_raises(ValueError, solve_continuous_lyapunov, nsq, sq)
+        assert_raises(ValueError, solve_continuous_lyapunov, sq, nsq)
+        assert_raises(ValueError, solve_continuous_lyapunov, sq, np.eye(2))
+
+    def check_continuous_case(self, a, q):
+        x = solve_continuous_lyapunov(a, q)
+        assert_array_almost_equal(
+                          np.dot(a, x) + np.dot(x, a.conj().transpose()), q)
+
+    def check_discrete_case(self, a, q, method=None):
+        x = solve_discrete_lyapunov(a, q, method=method)
+        assert_array_almost_equal(
+                      np.dot(np.dot(a, x), a.conj().transpose()) - x, -1.0*q)
+
+    def test_cases(self):
+        for case in self.cases:
+            self.check_continuous_case(case[0], case[1])
+            self.check_discrete_case(case[0], case[1])
+            self.check_discrete_case(case[0], case[1], method='direct')
+            self.check_discrete_case(case[0], case[1], method='bilinear')
+
+    @pytest.mark.parametrize("dtype_a", dtypes)
+    @pytest.mark.parametrize("dtype_q", dtypes)
+    def test_size_0(self, dtype_a, dtype_q):
+        rng = np.random.default_rng(234598235)
+
+        a = np.zeros((0, 0), dtype=dtype_a)
+        q = np.zeros((0, 0), dtype=dtype_q)
+        res = solve_continuous_lyapunov(a, q)
+
+        a = (rng.random((5, 5))*100).astype(dtype_a)
+        q = (rng.random((5, 5))*100).astype(dtype_q)
+        ref = solve_continuous_lyapunov(a, q)
+
+        assert res.shape == (0, 0)
+        assert res.dtype == ref.dtype
+
+
+class TestSolveContinuousAre:
+    mat6 = _load_data('carex_6_data.npz')
+    mat15 = _load_data('carex_15_data.npz')
+    mat18 = _load_data('carex_18_data.npz')
+    mat19 = _load_data('carex_19_data.npz')
+    mat20 = _load_data('carex_20_data.npz')
+    cases = [
+        # Carex examples taken from (with default parameters):
+        # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark
+        #     Examples for the Numerical Solution of Algebraic Riccati
+        #     Equations II: Continuous-Time Case', Tech. Report SPC 95_23,
+        #     Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.
+        #
+        # The format of the data is (a, b, q, r, knownfailure), where
+        # knownfailure is None if the test passes or a string
+        # indicating the reason for failure.
+        #
+        # Test Case 0: carex #1
+        (np.diag([1.], 1),
+         np.array([[0], [1]]),
+         block_diag(1., 2.),
+         1,
+         None),
+        # Test Case 1: carex #2
+        (np.array([[4, 3], [-4.5, -3.5]]),
+         np.array([[1], [-1]]),
+         np.array([[9, 6], [6, 4.]]),
+         1,
+         None),
+        # Test Case 2: carex #3
+        (np.array([[0, 1, 0, 0],
+                   [0, -1.89, 0.39, -5.53],
+                   [0, -0.034, -2.98, 2.43],
+                   [0.034, -0.0011, -0.99, -0.21]]),
+         np.array([[0, 0], [0.36, -1.6], [-0.95, -0.032], [0.03, 0]]),
+         np.array([[2.313, 2.727, 0.688, 0.023],
+                   [2.727, 4.271, 1.148, 0.323],
+                   [0.688, 1.148, 0.313, 0.102],
+                   [0.023, 0.323, 0.102, 0.083]]),
+         np.eye(2),
+         None),
+        # Test Case 3: carex #4
+        (np.array([[-0.991, 0.529, 0, 0, 0, 0, 0, 0],
+                   [0.522, -1.051, 0.596, 0, 0, 0, 0, 0],
+                   [0, 0.522, -1.118, 0.596, 0, 0, 0, 0],
+                   [0, 0, 0.522, -1.548, 0.718, 0, 0, 0],
+                   [0, 0, 0, 0.922, -1.64, 0.799, 0, 0],
+                   [0, 0, 0, 0, 0.922, -1.721, 0.901, 0],
+                   [0, 0, 0, 0, 0, 0.922, -1.823, 1.021],
+                   [0, 0, 0, 0, 0, 0, 0.922, -1.943]]),
+         np.array([[3.84, 4.00, 37.60, 3.08, 2.36, 2.88, 3.08, 3.00],
+                   [-2.88, -3.04, -2.80, -2.32, -3.32, -3.82, -4.12, -3.96]]
+                  ).T * 0.001,
+         np.array([[1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.1],
+                   [0.0, 1.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],
+                   [0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0],
+                   [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
+                   [0.5, 0.1, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0],
+                   [0.0, 0.0, 0.5, 0.0, 0.0, 0.1, 0.0, 0.0],
+                   [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0],
+                   [0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1]]),
+         np.eye(2),
+         None),
+        # Test Case 4: carex #5
+        (np.array(
+          [[-4.019, 5.120, 0., 0., -2.082, 0., 0., 0., 0.870],
+           [-0.346, 0.986, 0., 0., -2.340, 0., 0., 0., 0.970],
+           [-7.909, 15.407, -4.069, 0., -6.450, 0., 0., 0., 2.680],
+           [-21.816, 35.606, -0.339, -3.870, -17.800, 0., 0., 0., 7.390],
+           [-60.196, 98.188, -7.907, 0.340, -53.008, 0., 0., 0., 20.400],
+           [0, 0, 0, 0, 94.000, -147.200, 0., 53.200, 0.],
+           [0, 0, 0, 0, 0, 94.000, -147.200, 0, 0],
+           [0, 0, 0, 0, 0, 12.800, 0.000, -31.600, 0],
+           [0, 0, 0, 0, 12.800, 0.000, 0.000, 18.800, -31.600]]),
+         np.array([[0.010, -0.011, -0.151],
+                   [0.003, -0.021, 0.000],
+                   [0.009, -0.059, 0.000],
+                   [0.024, -0.162, 0.000],
+                   [0.068, -0.445, 0.000],
+                   [0.000, 0.000, 0.000],
+                   [0.000, 0.000, 0.000],
+                   [0.000, 0.000, 0.000],
+                   [0.000, 0.000, 0.000]]),
+         np.eye(9),
+         np.eye(3),
+         None),
+        # Test Case 5: carex #6
+        (mat6['A'], mat6['B'], mat6['Q'], mat6['R'], None),
+        # Test Case 6: carex #7
+        (np.array([[1, 0], [0, -2.]]),
+         np.array([[1e-6], [0]]),
+         np.ones((2, 2)),
+         1.,
+         'Bad residual accuracy'),
+        # Test Case 7: carex #8
+        (block_diag(-0.1, -0.02),
+         np.array([[0.100, 0.000], [0.001, 0.010]]),
+         np.array([[100, 1000], [1000, 10000]]),
+         np.ones((2, 2)) + block_diag(1e-6, 0),
+         None),
+        # Test Case 8: carex #9
+        (np.array([[0, 1e6], [0, 0]]),
+         np.array([[0], [1.]]),
+         np.eye(2),
+         1.,
+         None),
+        # Test Case 9: carex #10
+        (np.array([[1.0000001, 1], [1., 1.0000001]]),
+         np.eye(2),
+         np.eye(2),
+         np.eye(2),
+         None),
+        # Test Case 10: carex #11
+        (np.array([[3, 1.], [4, 2]]),
+         np.array([[1], [1]]),
+         np.array([[-11, -5], [-5, -2.]]),
+         1.,
+         None),
+        # Test Case 11: carex #12
+        (np.array([[7000000., 2000000., -0.],
+                   [2000000., 6000000., -2000000.],
+                   [0., -2000000., 5000000.]]) / 3,
+         np.eye(3),
+         np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]]).dot(
+                np.diag([1e-6, 1, 1e6])).dot(
+            np.array([[1., -2., -2.], [-2., 1., -2.], [-2., -2., 1.]])) / 9,
+         np.eye(3) * 1e6,
+         'Bad Residual Accuracy'),
+        # Test Case 12: carex #13
+        (np.array([[0, 0.4, 0, 0],
+                   [0, 0, 0.345, 0],
+                   [0, -0.524e6, -0.465e6, 0.262e6],
+                   [0, 0, 0, -1e6]]),
+         np.array([[0, 0, 0, 1e6]]).T,
+         np.diag([1, 0, 1, 0]),
+         1.,
+         None),
+        # Test Case 13: carex #14
+        (np.array([[-1e-6, 1, 0, 0],
+                   [-1, -1e-6, 0, 0],
+                   [0, 0, 1e-6, 1],
+                   [0, 0, -1, 1e-6]]),
+         np.ones((4, 1)),
+         np.ones((4, 4)),
+         1.,
+         None),
+        # Test Case 14: carex #15
+        (mat15['A'], mat15['B'], mat15['Q'], mat15['R'], None),
+        # Test Case 15: carex #16
+        (np.eye(64, 64, k=-1) + np.eye(64, 64)*(-2.) + np.rot90(
+                 block_diag(1, np.zeros((62, 62)), 1)) + np.eye(64, 64, k=1),
+         np.eye(64),
+         np.eye(64),
+         np.eye(64),
+         None),
+        # Test Case 16: carex #17
+        (np.diag(np.ones((20, )), 1),
+         np.flipud(np.eye(21, 1)),
+         np.eye(21, 1) * np.eye(21, 1).T,
+         1,
+         'Bad Residual Accuracy'),
+        # Test Case 17: carex #18
+        (mat18['A'], mat18['B'], mat18['Q'], mat18['R'], None),
+        # Test Case 18: carex #19
+        (mat19['A'], mat19['B'], mat19['Q'], mat19['R'],
+         'Bad Residual Accuracy'),
+        # Test Case 19: carex #20
+        (mat20['A'], mat20['B'], mat20['Q'], mat20['R'],
+         'Bad Residual Accuracy')
+        ]
+    # Makes the minimum precision requirements customized to the test.
+    # Here numbers represent the number of decimals that agrees with zero
+    # matrix when the solution x is plugged in to the equation.
+    #
+    # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2
+    #
+    # If the test is failing use "None" for that entry.
+    #
+    min_decimal = (14, 12, 13, 14, 11, 6, None, 5, 7, 14, 14,
+                   None, 9, 14, 13, 14, None, 12, None, None)
+
+    @pytest.mark.parametrize("j, case", enumerate(cases))
+    def test_solve_continuous_are(self, j, case):
+        """Checks if 0 = XA + A'X - XB(R)^{-1} B'X + Q is true"""
+        a, b, q, r, knownfailure = case
+        if knownfailure:
+            pytest.xfail(reason=knownfailure)
+
+        dec = self.min_decimal[j]
+        x = solve_continuous_are(a, b, q, r)
+        res = x @ a + a.conj().T @ x + q
+        out_fact = x @ b
+        res -= out_fact @ solve(np.atleast_2d(r), out_fact.conj().T)
+        assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+
+
+class TestSolveDiscreteAre:
+    cases = [
+        # Darex examples taken from (with default parameters):
+        # [1] P.BENNER, A.J. LAUB, V. MEHRMANN: 'A Collection of Benchmark
+        #     Examples for the Numerical Solution of Algebraic Riccati
+        #     Equations II: Discrete-Time Case', Tech. Report SPC 95_23,
+        #     Fak. f. Mathematik, TU Chemnitz-Zwickau (Germany), 1995.
+        # [2] T. GUDMUNDSSON, C. KENNEY, A.J. LAUB: 'Scaling of the
+        #     Discrete-Time Algebraic Riccati Equation to Enhance Stability
+        #     of the Schur Solution Method', IEEE Trans.Aut.Cont., vol.37(4)
+        #
+        # The format of the data is (a, b, q, r, knownfailure), where
+        # knownfailure is None if the test passes or a string
+        # indicating the reason for failure.
+        #
+        # TEST CASE 0 : Complex a; real b, q, r
+        (np.array([[2, 1-2j], [0, -3j]]),
+         np.array([[0], [1]]),
+         np.array([[1, 0], [0, 2]]),
+         np.array([[1]]),
+         None),
+        # TEST CASE 1 :Real a, q, r; complex b
+        (np.array([[2, 1], [0, -1]]),
+         np.array([[-2j], [1j]]),
+         np.array([[1, 0], [0, 2]]),
+         np.array([[1]]),
+         None),
+        # TEST CASE 2 : Real a, b; complex q, r
+        (np.array([[3, 1], [0, -1]]),
+         np.array([[1, 2], [1, 3]]),
+         np.array([[1, 1+1j], [1-1j, 2]]),
+         np.array([[2, -2j], [2j, 3]]),
+         None),
+        # TEST CASE 3 : User-reported gh-2251 (Trac #1732)
+        (np.array([[0.63399379, 0.54906824, 0.76253406],
+                   [0.5404729, 0.53745766, 0.08731853],
+                   [0.27524045, 0.84922129, 0.4681622]]),
+         np.array([[0.96861695], [0.05532739], [0.78934047]]),
+         np.eye(3),
+         np.eye(1),
+         None),
+        # TEST CASE 4 : darex #1
+        (np.array([[4, 3], [-4.5, -3.5]]),
+         np.array([[1], [-1]]),
+         np.array([[9, 6], [6, 4]]),
+         np.array([[1]]),
+         None),
+        # TEST CASE 5 : darex #2
+        (np.array([[0.9512, 0], [0, 0.9048]]),
+         np.array([[4.877, 4.877], [-1.1895, 3.569]]),
+         np.array([[0.005, 0], [0, 0.02]]),
+         np.array([[1/3, 0], [0, 3]]),
+         None),
+        # TEST CASE 6 : darex #3
+        (np.array([[2, -1], [1, 0]]),
+         np.array([[1], [0]]),
+         np.array([[0, 0], [0, 1]]),
+         np.array([[0]]),
+         None),
+        # TEST CASE 7 : darex #4 (skipped the gen. Ric. term S)
+        (np.array([[0, 1], [0, -1]]),
+         np.array([[1, 0], [2, 1]]),
+         np.array([[-4, -4], [-4, 7]]) * (1/11),
+         np.array([[9, 3], [3, 1]]),
+         None),
+        # TEST CASE 8 : darex #5
+        (np.array([[0, 1], [0, 0]]),
+         np.array([[0], [1]]),
+         np.array([[1, 2], [2, 4]]),
+         np.array([[1]]),
+         None),
+        # TEST CASE 9 : darex #6
+        (np.array([[0.998, 0.067, 0, 0],
+                   [-.067, 0.998, 0, 0],
+                   [0, 0, 0.998, 0.153],
+                   [0, 0, -.153, 0.998]]),
+         np.array([[0.0033, 0.0200],
+                   [0.1000, -.0007],
+                   [0.0400, 0.0073],
+                   [-.0028, 0.1000]]),
+         np.array([[1.87, 0, 0, -0.244],
+                   [0, 0.744, 0.205, 0],
+                   [0, 0.205, 0.589, 0],
+                   [-0.244, 0, 0, 1.048]]),
+         np.eye(2),
+         None),
+        # TEST CASE 10 : darex #7
+        (np.array([[0.984750, -.079903, 0.0009054, -.0010765],
+                   [0.041588, 0.998990, -.0358550, 0.0126840],
+                   [-.546620, 0.044916, -.3299100, 0.1931800],
+                   [2.662400, -.100450, -.9245500, -.2632500]]),
+         np.array([[0.0037112, 0.0007361],
+                   [-.0870510, 9.3411e-6],
+                   [-1.198440, -4.1378e-4],
+                   [-3.192700, 9.2535e-4]]),
+         np.eye(4)*1e-2,
+         np.eye(2),
+         None),
+        # TEST CASE 11 : darex #8
+        (np.array([[-0.6000000, -2.2000000, -3.6000000, -5.4000180],
+                   [1.0000000, 0.6000000, 0.8000000, 3.3999820],
+                   [0.0000000, 1.0000000, 1.8000000, 3.7999820],
+                   [0.0000000, 0.0000000, 0.0000000, -0.9999820]]),
+         np.array([[1.0, -1.0, -1.0, -1.0],
+                   [0.0, 1.0, -1.0, -1.0],
+                   [0.0, 0.0, 1.0, -1.0],
+                   [0.0, 0.0, 0.0, 1.0]]),
+         np.array([[2, 1, 3, 6],
+                   [1, 2, 2, 5],
+                   [3, 2, 6, 11],
+                   [6, 5, 11, 22]]),
+         np.eye(4),
+         None),
+        # TEST CASE 12 : darex #9
+        (np.array([[95.4070, 1.9643, 0.3597, 0.0673, 0.0190],
+                   [40.8490, 41.3170, 16.0840, 4.4679, 1.1971],
+                   [12.2170, 26.3260, 36.1490, 15.9300, 12.3830],
+                   [4.1118, 12.8580, 27.2090, 21.4420, 40.9760],
+                   [0.1305, 0.5808, 1.8750, 3.6162, 94.2800]]) * 0.01,
+         np.array([[0.0434, -0.0122],
+                   [2.6606, -1.0453],
+                   [3.7530, -5.5100],
+                   [3.6076, -6.6000],
+                   [0.4617, -0.9148]]) * 0.01,
+         np.eye(5),
+         np.eye(2),
+         None),
+        # TEST CASE 13 : darex #10
+        (np.kron(np.eye(2), np.diag([1, 1], k=1)),
+         np.kron(np.eye(2), np.array([[0], [0], [1]])),
+         np.array([[1, 1, 0, 0, 0, 0],
+                   [1, 1, 0, 0, 0, 0],
+                   [0, 0, 0, 0, 0, 0],
+                   [0, 0, 0, 1, -1, 0],
+                   [0, 0, 0, -1, 1, 0],
+                   [0, 0, 0, 0, 0, 0]]),
+         np.array([[3, 0], [0, 1]]),
+         None),
+        # TEST CASE 14 : darex #11
+        (0.001 * np.array(
+         [[870.1, 135.0, 11.59, .5014, -37.22, .3484, 0, 4.242, 7.249],
+          [76.55, 897.4, 12.72, 0.5504, -40.16, .3743, 0, 4.53, 7.499],
+          [-127.2, 357.5, 817, 1.455, -102.8, .987, 0, 11.85, 18.72],
+          [-363.5, 633.9, 74.91, 796.6, -273.5, 2.653, 0, 31.72, 48.82],
+          [-960, 1645.9, -128.9, -5.597, 71.42, 7.108, 0, 84.52, 125.9],
+          [-664.4, 112.96, -88.89, -3.854, 84.47, 13.6, 0, 144.3, 101.6],
+          [-410.2, 693, -54.71, -2.371, 66.49, 12.49, .1063, 99.97, 69.67],
+          [-179.9, 301.7, -23.93, -1.035, 60.59, 22.16, 0, 213.9, 35.54],
+          [-345.1, 580.4, -45.96, -1.989, 105.6, 19.86, 0, 219.1, 215.2]]),
+         np.array([[4.7600, -0.5701, -83.6800],
+                   [0.8790, -4.7730, -2.7300],
+                   [1.4820, -13.1200, 8.8760],
+                   [3.8920, -35.1300, 24.8000],
+                   [10.3400, -92.7500, 66.8000],
+                   [7.2030, -61.5900, 38.3400],
+                   [4.4540, -36.8300, 20.2900],
+                   [1.9710, -15.5400, 6.9370],
+                   [3.7730, -30.2800, 14.6900]]) * 0.001,
+         np.diag([50, 0, 0, 0, 50, 0, 0, 0, 0]),
+         np.eye(3),
+         None),
+        # TEST CASE 15 : darex #12 - numerically least accurate example
+        (np.array([[0, 1e6], [0, 0]]),
+         np.array([[0], [1]]),
+         np.eye(2),
+         np.array([[1]]),
+        None),
+        # TEST CASE 16 : darex #13
+        (np.array([[16, 10, -2],
+                  [10, 13, -8],
+                  [-2, -8, 7]]) * (1/9),
+         np.eye(3),
+         1e6 * np.eye(3),
+         1e6 * np.eye(3),
+        None),
+        # TEST CASE 17 : darex #14
+        (np.array([[1 - 1/1e8, 0, 0, 0],
+                  [1, 0, 0, 0],
+                  [0, 1, 0, 0],
+                  [0, 0, 1, 0]]),
+         np.array([[1e-08], [0], [0], [0]]),
+         np.diag([0, 0, 0, 1]),
+         np.array([[0.25]]),
+         None),
+        # TEST CASE 18 : darex #15
+        (np.eye(100, k=1),
+         np.flipud(np.eye(100, 1)),
+         np.eye(100),
+         np.array([[1]]),
+         None)
+        ]
+
+    # Makes the minimum precision requirements customized to the test.
+    # Here numbers represent the number of decimals that agrees with zero
+    # matrix when the solution x is plugged in to the equation.
+    #
+    # res = array([[8e-3,1e-16],[1e-16,1e-20]]) --> min_decimal[k] = 2
+    #
+    # If the test is failing use "None" for that entry.
+    #
+    min_decimal = (12, 14, 13, 14, 13, 16, 18, 14, 14, 13,
+                   14, 13, 13, 14, 12, 2, 4, 6, 10)
+    max_tol = [1.5 * 10**-ind for ind in min_decimal]
+    # relaxed tolerance in gh-18012 after bump to OpenBLAS
+    max_tol[11] = 2.5e-13
+
+    # relaxed tolerance in gh-20335 for linux-aarch64 build on Cirrus
+    # with OpenBLAS from ubuntu jammy
+    max_tol[15] = 2.0e-2
+
+    # relaxed tolerance in gh-20335 for OpenBLAS 3.20 on ubuntu jammy
+    # bump not needed for OpenBLAS 3.26
+    max_tol[16] = 2.0e-4
+
+    @pytest.mark.parametrize("j, case", enumerate(cases))
+    def test_solve_discrete_are(self, j, case):
+        """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
+        a, b, q, r, knownfailure = case
+        if knownfailure:
+            pytest.xfail(reason=knownfailure)
+
+        atol = self.max_tol[j]
+
+        x = solve_discrete_are(a, b, q, r)
+        bH = b.conj().T
+        xa, xb = x @ a, x @ b
+
+        res = a.conj().T @ xa - x + q
+        res -= a.conj().T @ xb @ (solve(r + bH @ xb, bH) @ xa)
+
+        # changed from
+        # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+        # in gh-18012 as it's easier to relax a tolerance and allclose is
+        # preferred
+        assert_allclose(res, np.zeros_like(res), atol=atol)
+
+    def test_infeasible(self):
+        # An infeasible example taken from https://arxiv.org/abs/1505.04861v1
+        A = np.triu(np.ones((3, 3)))
+        A[0, 1] = -1
+        B = np.array([[1, 1, 0], [0, 0, 1]]).T
+        Q = np.full_like(A, -2) + np.diag([8, -1, -1.9])
+        R = np.diag([-10, 0.1])
+        assert_raises(LinAlgError, solve_continuous_are, A, B, Q, R)
+
+
+def test_solve_generalized_continuous_are():
+    cases = [
+        # Two random examples differ by s term
+        # in the absence of any literature for demanding examples.
+        (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+                   [4.617139e-02, 6.948286e-01, 3.444608e-02],
+                   [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+         np.array([[3.815585e-01, 1.868726e-01],
+                   [7.655168e-01, 4.897644e-01],
+                   [7.951999e-01, 4.455862e-01]]),
+         np.eye(3),
+         np.eye(2),
+         np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+                   [7.093648e-01, 6.797027e-01, 1.189977e-01],
+                   [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+         np.zeros((3, 2)),
+         None),
+        (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+                   [4.617139e-02, 6.948286e-01, 3.444608e-02],
+                   [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+         np.array([[3.815585e-01, 1.868726e-01],
+                   [7.655168e-01, 4.897644e-01],
+                   [7.951999e-01, 4.455862e-01]]),
+         np.eye(3),
+         np.eye(2),
+         np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+                   [7.093648e-01, 6.797027e-01, 1.189977e-01],
+                   [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+         np.ones((3, 2)),
+         None)
+        ]
+
+    min_decimal = (10, 10)
+
+    def _test_factory(case, dec):
+        """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
+        a, b, q, r, e, s, knownfailure = case
+        if knownfailure:
+            pytest.xfail(reason=knownfailure)
+
+        x = solve_continuous_are(a, b, q, r, e, s)
+        res = a.conj().T.dot(x.dot(e)) + e.conj().T.dot(x.dot(a)) + q
+        out_fact = e.conj().T.dot(x).dot(b) + s
+        res -= out_fact.dot(solve(np.atleast_2d(r), out_fact.conj().T))
+        assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+
+    for ind, case in enumerate(cases):
+        _test_factory(case, min_decimal[ind])
+
+
+def test_solve_generalized_discrete_are():
+    mat20170120 = _load_data('gendare_20170120_data.npz')
+
+    cases = [
+        # Two random examples differ by s term
+        # in the absence of any literature for demanding examples.
+        (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+                   [4.617139e-02, 6.948286e-01, 3.444608e-02],
+                   [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+         np.array([[3.815585e-01, 1.868726e-01],
+                   [7.655168e-01, 4.897644e-01],
+                   [7.951999e-01, 4.455862e-01]]),
+         np.eye(3),
+         np.eye(2),
+         np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+                   [7.093648e-01, 6.797027e-01, 1.189977e-01],
+                   [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+         np.zeros((3, 2)),
+         None),
+        (np.array([[2.769230e-01, 8.234578e-01, 9.502220e-01],
+                   [4.617139e-02, 6.948286e-01, 3.444608e-02],
+                   [9.713178e-02, 3.170995e-01, 4.387444e-01]]),
+         np.array([[3.815585e-01, 1.868726e-01],
+                   [7.655168e-01, 4.897644e-01],
+                   [7.951999e-01, 4.455862e-01]]),
+         np.eye(3),
+         np.eye(2),
+         np.array([[6.463130e-01, 2.760251e-01, 1.626117e-01],
+                   [7.093648e-01, 6.797027e-01, 1.189977e-01],
+                   [7.546867e-01, 6.550980e-01, 4.983641e-01]]),
+         np.ones((3, 2)),
+         None),
+        # user-reported (under PR-6616) 20-Jan-2017
+        # tests against the case where E is None but S is provided
+        (mat20170120['A'],
+         mat20170120['B'],
+         mat20170120['Q'],
+         mat20170120['R'],
+         None,
+         mat20170120['S'],
+         None),
+        ]
+
+    max_atol = (1.5e-11, 1.5e-11, 3.5e-16)
+
+    def _test_factory(case, atol):
+        """Checks if X = A'XA-(A'XB)(R+B'XB)^-1(B'XA)+Q) is true"""
+        a, b, q, r, e, s, knownfailure = case
+        if knownfailure:
+            pytest.xfail(reason=knownfailure)
+
+        x = solve_discrete_are(a, b, q, r, e, s)
+        if e is None:
+            e = np.eye(a.shape[0])
+        if s is None:
+            s = np.zeros_like(b)
+        res = a.conj().T.dot(x.dot(a)) - e.conj().T.dot(x.dot(e)) + q
+        res -= (a.conj().T.dot(x.dot(b)) + s).dot(
+                    solve(r+b.conj().T.dot(x.dot(b)),
+                          (b.conj().T.dot(x.dot(a)) + s.conj().T)
+                          )
+                )
+        # changed from:
+        # assert_array_almost_equal(res, np.zeros_like(res), decimal=dec)
+        # in gh-17950 because of a Linux 32 bit fail.
+        assert_allclose(res, np.zeros_like(res), atol=atol)
+
+    for ind, case in enumerate(cases):
+        _test_factory(case, max_atol[ind])
+
+
+def test_are_validate_args():
+
+    def test_square_shape():
+        nsq = np.ones((3, 2))
+        sq = np.eye(3)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, nsq, 1, 1, 1)
+            assert_raises(ValueError, x, sq, sq, nsq, 1)
+            assert_raises(ValueError, x, sq, sq, sq, nsq)
+            assert_raises(ValueError, x, sq, sq, sq, sq, nsq)
+
+    def test_compatible_sizes():
+        nsq = np.ones((3, 2))
+        sq = np.eye(4)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, sq, nsq, 1, 1)
+            assert_raises(ValueError, x, sq, sq, sq, sq, sq, nsq)
+            assert_raises(ValueError, x, sq, sq, np.eye(3), sq)
+            assert_raises(ValueError, x, sq, sq, sq, np.eye(3))
+            assert_raises(ValueError, x, sq, sq, sq, sq, np.eye(3))
+
+    def test_symmetry():
+        nsym = np.arange(9).reshape(3, 3)
+        sym = np.eye(3)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, sym, sym, nsym, sym)
+            assert_raises(ValueError, x, sym, sym, sym, nsym)
+
+    def test_singularity():
+        sing = np.full((3, 3), 1e12)
+        sing[2, 2] -= 1
+        sq = np.eye(3)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, sq, sq, sq, sq, sing)
+
+        assert_raises(ValueError, solve_continuous_are, sq, sq, sq, sing)
+
+    def test_finiteness():
+        nm = np.full((2, 2), np.nan)
+        sq = np.eye(2)
+        for x in (solve_continuous_are, solve_discrete_are):
+            assert_raises(ValueError, x, nm, sq, sq, sq)
+            assert_raises(ValueError, x, sq, nm, sq, sq)
+            assert_raises(ValueError, x, sq, sq, nm, sq)
+            assert_raises(ValueError, x, sq, sq, sq, nm)
+            assert_raises(ValueError, x, sq, sq, sq, sq, nm)
+            assert_raises(ValueError, x, sq, sq, sq, sq, sq, nm)
+
+
+class TestSolveSylvester:
+    cases = [
+        # empty cases
+        (np.empty((0, 0)),
+         np.empty((0, 0)),
+         np.empty((0, 0))),
+         (np.empty((0, 0)),
+         np.empty((2, 2)),
+         np.empty((0, 2))),
+         (np.empty((2, 2)),
+         np.empty((0, 0)),
+         np.empty((2, 0))),
+        # a, b, c all real.
+        (np.array([[1, 2], [0, 4]]),
+         np.array([[5, 6], [0, 8]]),
+         np.array([[9, 10], [11, 12]])),
+        # a, b, c all real, 4x4. a and b have non-trivial 2x2 blocks in their
+        # quasi-triangular form.
+        (np.array([[1.0, 0, 0, 0],
+                   [0, 1.0, 2.0, 0.0],
+                   [0, 0, 3.0, -4],
+                   [0, 0, 2, 5]]),
+         np.array([[2.0, 0, 0, 1.0],
+                   [0, 1.0, 0.0, 0.0],
+                   [0, 0, 1.0, -1],
+                   [0, 0, 1, 1]]),
+         np.array([[1.0, 0, 0, 0],
+                   [0, 1.0, 0, 0],
+                   [0, 0, 1.0, 0],
+                   [0, 0, 0, 1.0]])),
+        # a, b, c all complex.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[-1.0, 2j], [3.0, 4.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a and b real; c complex.
+        (np.array([[1.0, 2.0], [3.0, 5.0]]),
+         np.array([[-1.0, 0], [3.0, 4.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a and c complex; b real.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[-1.0, 0], [3.0, 4.0]]),
+         np.array([[2.0-2j, 2.0+2j], [-1.0-1j, 2.0]])),
+        # a complex; b and c real.
+        (np.array([[1.0+1j, 2.0], [3.0-4.0j, 5.0]]),
+         np.array([[-1.0, 0], [3.0, 4.0]]),
+         np.array([[2.0, 2.0], [-1.0, 2.0]])),
+        # not square matrices, real
+        (np.array([[8, 1, 6], [3, 5, 7], [4, 9, 2]]),
+         np.array([[2, 3], [4, 5]]),
+         np.array([[1, 2], [3, 4], [5, 6]])),
+        # not square matrices, complex
+        (np.array([[8, 1j, 6+2j], [3, 5, 7], [4, 9, 2]]),
+         np.array([[2, 3], [4, 5-1j]]),
+         np.array([[1, 2j], [3, 4j], [5j, 6+7j]])),
+    ]
+
+    def check_case(self, a, b, c):
+        x = solve_sylvester(a, b, c)
+        assert_array_almost_equal(np.dot(a, x) + np.dot(x, b), c)
+
+    def test_cases(self):
+        for case in self.cases:
+            self.check_case(case[0], case[1], case[2])
+
+    def test_trivial(self):
+        a = np.array([[1.0, 0.0], [0.0, 1.0]])
+        b = np.array([[1.0]])
+        c = np.array([2.0, 2.0]).reshape(-1, 1)
+        x = solve_sylvester(a, b, c)
+        assert_array_almost_equal(x, np.array([1.0, 1.0]).reshape(-1, 1))
+
+    # Feel free to adjust this to test fewer dtypes or random selections rather than
+    # the Cartesian product. It doesn't take very long to test all combinations,
+    # though, so we'll start there and trim it down as we see fit.
+    @pytest.mark.parametrize("dtype_a", dtypes)
+    @pytest.mark.parametrize("dtype_b", dtypes)
+    @pytest.mark.parametrize("dtype_q", dtypes)
+    @pytest.mark.parametrize("m", [0, 3])
+    @pytest.mark.parametrize("n", [0, 3])
+    def test_size_0(self, m, n, dtype_a, dtype_b, dtype_q):
+        if m == n != 0:
+            pytest.skip('m = n != 0 is not a case that needs to be tested here.')
+
+        rng = np.random.default_rng(598435298262546)
+
+        a = np.zeros((m, m), dtype=dtype_a)
+        b = np.zeros((n, n), dtype=dtype_b)
+        q = np.zeros((m, n), dtype=dtype_q)
+        res = solve_sylvester(a, b, q)
+
+        a = (rng.random((5, 5))*100).astype(dtype_a)
+        b = (rng.random((6, 6))*100).astype(dtype_b)
+        q = (rng.random((5, 6))*100).astype(dtype_q)
+        ref = solve_sylvester(a, b, q)
+
+        assert res.shape == (m, n)
+        assert res.dtype == ref.dtype
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py
new file mode 100644
index 0000000000000000000000000000000000000000..d32e7ed4b4016924c60b3ed6287888a0372e8791
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/linalg/tests/test_special_matrices.py
@@ -0,0 +1,640 @@
+import pytest
+import numpy as np
+from numpy import arange, array, eye, copy, sqrt
+from numpy.testing import (assert_equal, assert_array_equal,
+                           assert_array_almost_equal, assert_allclose)
+from pytest import raises as assert_raises
+
+from scipy.fft import fft
+from scipy.special import comb
+from scipy.linalg import (toeplitz, hankel, circulant, hadamard, leslie, dft,
+                          companion, kron, block_diag,
+                          helmert, hilbert, invhilbert, pascal, invpascal,
+                          fiedler, fiedler_companion, eigvals,
+                          convolution_matrix)
+from numpy.linalg import cond
+
+
+class TestToeplitz:
+
+    def test_basic(self):
+        y = toeplitz([1, 2, 3])
+        assert_array_equal(y, [[1, 2, 3], [2, 1, 2], [3, 2, 1]])
+        y = toeplitz([1, 2, 3], [1, 4, 5])
+        assert_array_equal(y, [[1, 4, 5], [2, 1, 4], [3, 2, 1]])
+
+    def test_complex_01(self):
+        data = (1.0 + arange(3.0)) * (1.0 + 1.0j)
+        x = copy(data)
+        t = toeplitz(x)
+        # Calling toeplitz should not change x.
+        assert_array_equal(x, data)
+        # According to the docstring, x should be the first column of t.
+        col0 = t[:, 0]
+        assert_array_equal(col0, data)
+        assert_array_equal(t[0, 1:], data[1:].conj())
+
+    def test_scalar_00(self):
+        """Scalar arguments still produce a 2D array."""
+        t = toeplitz(10)
+        assert_array_equal(t, [[10]])
+        t = toeplitz(10, 20)
+        assert_array_equal(t, [[10]])
+
+    def test_scalar_01(self):
+        c = array([1, 2, 3])
+        t = toeplitz(c, 1)
+        assert_array_equal(t, [[1], [2], [3]])
+
+    def test_scalar_02(self):
+        c = array([1, 2, 3])
+        t = toeplitz(c, array(1))
+        assert_array_equal(t, [[1], [2], [3]])
+
+    def test_scalar_03(self):
+        c = array([1, 2, 3])
+        t = toeplitz(c, array([1]))
+        assert_array_equal(t, [[1], [2], [3]])
+
+    def test_scalar_04(self):
+        r = array([10, 2, 3])
+        t = toeplitz(1, r)
+        assert_array_equal(t, [[1, 2, 3]])
+
+
+class TestHankel:
+    def test_basic(self):
+        y = hankel([1, 2, 3])
+        assert_array_equal(y, [[1, 2, 3], [2, 3, 0], [3, 0, 0]])
+        y = hankel([1, 2, 3], [3, 4, 5])
+        assert_array_equal(y, [[1, 2, 3], [2, 3, 4], [3, 4, 5]])
+
+
+class TestCirculant:
+    def test_basic(self):
+        y = circulant([1, 2, 3])
+        assert_array_equal(y, [[1, 3, 2], [2, 1, 3], [3, 2, 1]])
+
+
+class TestHadamard:
+
+    def test_basic(self):
+
+        y = hadamard(1)
+        assert_array_equal(y, [[1]])
+
+        y = hadamard(2, dtype=float)
+        assert_array_equal(y, [[1.0, 1.0], [1.0, -1.0]])
+
+        y = hadamard(4)
+        assert_array_equal(y, [[1, 1, 1, 1],
+                               [1, -1, 1, -1],
+                               [1, 1, -1, -1],
+                               [1, -1, -1, 1]])
+
+        assert_raises(ValueError, hadamard, 0)
+        assert_raises(ValueError, hadamard, 5)
+
+
+class TestLeslie:
+
+    def test_bad_shapes(self):
+        assert_raises(ValueError, leslie, [[1, 1], [2, 2]], [3, 4, 5])
+        assert_raises(ValueError, leslie, [1, 2], [1, 2])
+        assert_raises(ValueError, leslie, [1], [])
+
+    def test_basic(self):
+        a = leslie([1, 2, 3], [0.25, 0.5])
+        expected = array([[1.0, 2.0, 3.0],
+                          [0.25, 0.0, 0.0],
+                          [0.0, 0.5, 0.0]])
+        assert_array_equal(a, expected)
+
+
+class TestCompanion:
+
+    def test_bad_shapes(self):
+        assert_raises(ValueError, companion, [0, 4, 5])
+        assert_raises(ValueError, companion, [1])
+        assert_raises(ValueError, companion, [])
+
+    def test_basic(self):
+        c = companion([1, 2, 3])
+        expected = array([
+            [-2.0, -3.0],
+            [1.0, 0.0]])
+        assert_array_equal(c, expected)
+
+        c = companion([2.0, 5.0, -10.0])
+        expected = array([
+            [-2.5, 5.0],
+            [1.0, 0.0]])
+        assert_array_equal(c, expected)
+
+        c = companion([(1.0, 2.0, 3.0),
+                       (4.0, 5.0, 6.0)])
+        expected = array([
+            ([-2.00, -3.00],
+             [+1.00, +0.00]),
+            ([-1.25, -1.50],
+             [+1.00, +0.00])
+        ])
+        assert_array_equal(c, expected)
+
+
+class TestBlockDiag:
+    def test_basic(self):
+        x = block_diag(eye(2), [[1, 2], [3, 4], [5, 6]], [[1, 2, 3]])
+        assert_array_equal(x, [[1, 0, 0, 0, 0, 0, 0],
+                               [0, 1, 0, 0, 0, 0, 0],
+                               [0, 0, 1, 2, 0, 0, 0],
+                               [0, 0, 3, 4, 0, 0, 0],
+                               [0, 0, 5, 6, 0, 0, 0],
+                               [0, 0, 0, 0, 1, 2, 3]])
+
+    def test_dtype(self):
+        x = block_diag([[1.5]])
+        assert_equal(x.dtype, float)
+
+        x = block_diag([[True]])
+        assert_equal(x.dtype, bool)
+
+    def test_mixed_dtypes(self):
+        actual = block_diag([[1]], [[1j]])
+        desired = np.array([[1, 0], [0, 1j]])
+        assert_array_equal(actual, desired)
+
+    def test_scalar_and_1d_args(self):
+        a = block_diag(1)
+        assert_equal(a.shape, (1, 1))
+        assert_array_equal(a, [[1]])
+
+        a = block_diag([2, 3], 4)
+        assert_array_equal(a, [[2, 3, 0], [0, 0, 4]])
+
+    def test_bad_arg(self):
+        assert_raises(ValueError, block_diag, [[[1]]])
+
+    def test_no_args(self):
+        a = block_diag()
+        assert_equal(a.ndim, 2)
+        assert_equal(a.nbytes, 0)
+
+    def test_empty_matrix_arg(self):
+        # regression test for gh-4596: check the shape of the result
+        # for empty matrix inputs. Empty matrices are no longer ignored
+        # (gh-4908) it is viewed as a shape (1, 0) matrix.
+        a = block_diag([[1, 0], [0, 1]],
+                       [],
+                       [[2, 3], [4, 5], [6, 7]])
+        assert_array_equal(a, [[1, 0, 0, 0],
+                               [0, 1, 0, 0],
+                               [0, 0, 0, 0],
+                               [0, 0, 2, 3],
+                               [0, 0, 4, 5],
+                               [0, 0, 6, 7]])
+
+    def test_zerosized_matrix_arg(self):
+        # test for gh-4908: check the shape of the result for
+        # zero-sized matrix inputs, i.e. matrices with shape (0,n) or (n,0).
+        # note that [[]] takes shape (1,0)
+        a = block_diag([[1, 0], [0, 1]],
+                       [[]],
+                       [[2, 3], [4, 5], [6, 7]],
+                       np.zeros([0, 2], dtype='int32'))
+        assert_array_equal(a, [[1, 0, 0, 0, 0, 0],
+                               [0, 1, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0],
+                               [0, 0, 2, 3, 0, 0],
+                               [0, 0, 4, 5, 0, 0],
+                               [0, 0, 6, 7, 0, 0]])
+
+
+class TestKron:
+    @pytest.mark.thread_unsafe
+    def test_dep(self):
+        with pytest.deprecated_call(match="`kron`"):
+            kron(np.array([[1, 2],[3, 4]]),np.array([[1, 1, 1]]))
+
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_basic(self):
+
+        a = kron(array([[1, 2], [3, 4]]), array([[1, 1, 1]]))
+        assert_array_equal(a, array([[1, 1, 1, 2, 2, 2],
+                                     [3, 3, 3, 4, 4, 4]]))
+
+        m1 = array([[1, 2], [3, 4]])
+        m2 = array([[10], [11]])
+        a = kron(m1, m2)
+        expected = array([[10, 20],
+                          [11, 22],
+                          [30, 40],
+                          [33, 44]])
+        assert_array_equal(a, expected)
+
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_empty(self):
+        m1 = np.empty((0, 2))
+        m2 = np.empty((1, 3))
+        a = kron(m1, m2)
+        assert_allclose(a, np.empty((0, 6)))
+
+
+class TestHelmert:
+
+    def test_orthogonality(self):
+        for n in range(1, 7):
+            H = helmert(n, full=True)
+            Id = np.eye(n)
+            assert_allclose(H.dot(H.T), Id, atol=1e-12)
+            assert_allclose(H.T.dot(H), Id, atol=1e-12)
+
+    def test_subspace(self):
+        for n in range(2, 7):
+            H_full = helmert(n, full=True)
+            H_partial = helmert(n)
+            for U in H_full[1:, :].T, H_partial.T:
+                C = np.eye(n) - np.full((n, n), 1 / n)
+                assert_allclose(U.dot(U.T), C)
+                assert_allclose(U.T.dot(U), np.eye(n-1), atol=1e-12)
+
+
+class TestHilbert:
+
+    def test_basic(self):
+        h3 = array([[1.0, 1/2., 1/3.],
+                    [1/2., 1/3., 1/4.],
+                    [1/3., 1/4., 1/5.]])
+        assert_array_almost_equal(hilbert(3), h3)
+
+        assert_array_equal(hilbert(1), [[1.0]])
+
+        h0 = hilbert(0)
+        assert_equal(h0.shape, (0, 0))
+
+
+class TestInvHilbert:
+
+    def test_basic(self):
+        invh1 = array([[1]])
+        assert_array_equal(invhilbert(1, exact=True), invh1)
+        assert_array_equal(invhilbert(1), invh1)
+
+        invh2 = array([[4, -6],
+                       [-6, 12]])
+        assert_array_equal(invhilbert(2, exact=True), invh2)
+        assert_array_almost_equal(invhilbert(2), invh2)
+
+        invh3 = array([[9, -36, 30],
+                       [-36, 192, -180],
+                       [30, -180, 180]])
+        assert_array_equal(invhilbert(3, exact=True), invh3)
+        assert_array_almost_equal(invhilbert(3), invh3)
+
+        invh4 = array([[16, -120, 240, -140],
+                       [-120, 1200, -2700, 1680],
+                       [240, -2700, 6480, -4200],
+                       [-140, 1680, -4200, 2800]])
+        assert_array_equal(invhilbert(4, exact=True), invh4)
+        assert_array_almost_equal(invhilbert(4), invh4)
+
+        invh5 = array([[25, -300, 1050, -1400, 630],
+                       [-300, 4800, -18900, 26880, -12600],
+                       [1050, -18900, 79380, -117600, 56700],
+                       [-1400, 26880, -117600, 179200, -88200],
+                       [630, -12600, 56700, -88200, 44100]])
+        assert_array_equal(invhilbert(5, exact=True), invh5)
+        assert_array_almost_equal(invhilbert(5), invh5)
+
+        invh17 = array([
+            [289, -41616, 1976760, -46124400, 629598060, -5540462928,
+             33374693352, -143034400080, 446982500250, -1033026222800,
+             1774926873720, -2258997839280, 2099709530100, -1384423866000,
+             613101997800, -163493866080, 19835652870],
+            [-41616, 7990272, -426980160, 10627061760, -151103534400,
+             1367702848512, -8410422724704, 36616806420480, -115857864064800,
+             270465047424000, -468580694662080, 600545887119360,
+             -561522320049600, 372133135180800, -165537539406000,
+             44316454993920, -5395297580640],
+            [1976760, -426980160, 24337869120, -630981792000, 9228108708000,
+             -85267724461920, 532660105897920, -2348052711713280,
+             7504429831470000, -17664748409880000, 30818191841236800,
+             -39732544853164800, 37341234283298400, -24857330514030000,
+             11100752642520000, -2982128117299200, 364182586693200],
+            [-46124400, 10627061760, -630981792000, 16826181120000,
+             -251209625940000, 2358021022156800, -14914482965141760,
+             66409571644416000, -214015221119700000, 507295338950400000,
+             -890303319857952000, 1153715376477081600, -1089119333262870000,
+             727848632044800000, -326170262829600000, 87894302404608000,
+             -10763618673376800],
+            [629598060, -151103534400, 9228108708000,
+             -251209625940000, 3810012660090000, -36210360321495360,
+             231343968720664800, -1038687206500944000, 3370739732635275000,
+             -8037460526495400000, 14178080368737885600, -18454939322943942000,
+             17489975175339030000, -11728977435138600000, 5272370630081100000,
+             -1424711708039692800, 174908803442373000],
+            [-5540462928, 1367702848512, -85267724461920, 2358021022156800,
+             -36210360321495360, 347619459086355456, -2239409617216035264,
+             10124803292907663360, -33052510749726468000,
+             79217210949138662400, -140362995650505067440,
+             183420385176741672960, -174433352415381259200,
+             117339159519533952000, -52892422160973595200,
+             14328529177999196160, -1763080738699119840],
+            [33374693352, -8410422724704, 532660105897920,
+             -14914482965141760, 231343968720664800, -2239409617216035264,
+             14527452132196331328, -66072377044391477760,
+             216799987176909536400, -521925895055522958000,
+             928414062734059661760, -1217424500995626443520,
+             1161358898976091015200, -783401860847777371200,
+             354015418167362952000, -96120549902411274240,
+             11851820521255194480],
+            [-143034400080, 36616806420480, -2348052711713280,
+             66409571644416000, -1038687206500944000, 10124803292907663360,
+             -66072377044391477760, 302045152202932469760,
+             -995510145200094810000, 2405996923185123840000,
+             -4294704507885446054400, 5649058909023744614400,
+             -5403874060541811254400, 3654352703663101440000,
+             -1655137020003255360000, 450325202737117593600,
+             -55630994283442749600],
+            [446982500250, -115857864064800, 7504429831470000,
+             -214015221119700000, 3370739732635275000, -33052510749726468000,
+             216799987176909536400, -995510145200094810000,
+             3293967392206196062500, -7988661659013106500000,
+             14303908928401362270000, -18866974090684772052000,
+             18093328327706957325000, -12263364009096700500000,
+             5565847995255512250000, -1517208935002984080000,
+             187754605706619279900],
+            [-1033026222800, 270465047424000, -17664748409880000,
+             507295338950400000, -8037460526495400000, 79217210949138662400,
+             -521925895055522958000, 2405996923185123840000,
+             -7988661659013106500000, 19434404971634224000000,
+             -34894474126569249192000, 46141453390504792320000,
+             -44349976506971935800000, 30121928988527376000000,
+             -13697025107665828500000, 3740200989399948902400,
+             -463591619028689580000],
+            [1774926873720, -468580694662080,
+             30818191841236800, -890303319857952000, 14178080368737885600,
+             -140362995650505067440, 928414062734059661760,
+             -4294704507885446054400, 14303908928401362270000,
+             -34894474126569249192000, 62810053427824648545600,
+             -83243376594051600326400, 80177044485212743068000,
+             -54558343880470209780000, 24851882355348879230400,
+             -6797096028813368678400, 843736746632215035600],
+            [-2258997839280, 600545887119360, -39732544853164800,
+             1153715376477081600, -18454939322943942000, 183420385176741672960,
+             -1217424500995626443520, 5649058909023744614400,
+             -18866974090684772052000, 46141453390504792320000,
+             -83243376594051600326400, 110552468520163390156800,
+             -106681852579497947388000, 72720410752415168870400,
+             -33177973900974346080000, 9087761081682520473600,
+             -1129631016152221783200],
+            [2099709530100, -561522320049600, 37341234283298400,
+             -1089119333262870000, 17489975175339030000,
+             -174433352415381259200, 1161358898976091015200,
+             -5403874060541811254400, 18093328327706957325000,
+             -44349976506971935800000, 80177044485212743068000,
+             -106681852579497947388000, 103125790826848015808400,
+             -70409051543137015800000, 32171029219823375700000,
+             -8824053728865840192000, 1098252376814660067000],
+            [-1384423866000, 372133135180800,
+             -24857330514030000, 727848632044800000, -11728977435138600000,
+             117339159519533952000, -783401860847777371200,
+             3654352703663101440000, -12263364009096700500000,
+             30121928988527376000000, -54558343880470209780000,
+             72720410752415168870400, -70409051543137015800000,
+             48142941226076592000000, -22027500987368499000000,
+             6049545098753157120000, -753830033789944188000],
+            [613101997800, -165537539406000,
+             11100752642520000, -326170262829600000, 5272370630081100000,
+             -52892422160973595200, 354015418167362952000,
+             -1655137020003255360000, 5565847995255512250000,
+             -13697025107665828500000, 24851882355348879230400,
+             -33177973900974346080000, 32171029219823375700000,
+             -22027500987368499000000, 10091416708498869000000,
+             -2774765838662800128000, 346146444087219270000],
+            [-163493866080, 44316454993920, -2982128117299200,
+             87894302404608000, -1424711708039692800,
+             14328529177999196160, -96120549902411274240,
+             450325202737117593600, -1517208935002984080000,
+             3740200989399948902400, -6797096028813368678400,
+             9087761081682520473600, -8824053728865840192000,
+             6049545098753157120000, -2774765838662800128000,
+             763806510427609497600, -95382575704033754400],
+            [19835652870, -5395297580640, 364182586693200, -10763618673376800,
+             174908803442373000, -1763080738699119840, 11851820521255194480,
+             -55630994283442749600, 187754605706619279900,
+             -463591619028689580000, 843736746632215035600,
+             -1129631016152221783200, 1098252376814660067000,
+             -753830033789944188000, 346146444087219270000,
+             -95382575704033754400, 11922821963004219300]
+        ])
+        assert_array_equal(invhilbert(17, exact=True), invh17)
+        assert_allclose(invhilbert(17), invh17.astype(float), rtol=1e-12)
+
+    def test_inverse(self):
+        for n in range(1, 10):
+            a = hilbert(n)
+            b = invhilbert(n)
+            # The Hilbert matrix is increasingly badly conditioned,
+            # so take that into account in the test
+            c = cond(a)
+            assert_allclose(a.dot(b), eye(n), atol=1e-15*c, rtol=1e-15*c)
+
+
+class TestPascal:
+
+    cases = [
+        (1, array([[1]]), array([[1]])),
+        (2, array([[1, 1],
+                   [1, 2]]),
+            array([[1, 0],
+                   [1, 1]])),
+        (3, array([[1, 1, 1],
+                   [1, 2, 3],
+                   [1, 3, 6]]),
+            array([[1, 0, 0],
+                   [1, 1, 0],
+                   [1, 2, 1]])),
+        (4, array([[1, 1, 1, 1],
+                   [1, 2, 3, 4],
+                   [1, 3, 6, 10],
+                   [1, 4, 10, 20]]),
+            array([[1, 0, 0, 0],
+                   [1, 1, 0, 0],
+                   [1, 2, 1, 0],
+                   [1, 3, 3, 1]])),
+    ]
+
+    def check_case(self, n, sym, low):
+        assert_array_equal(pascal(n), sym)
+        assert_array_equal(pascal(n, kind='lower'), low)
+        assert_array_equal(pascal(n, kind='upper'), low.T)
+        assert_array_almost_equal(pascal(n, exact=False), sym)
+        assert_array_almost_equal(pascal(n, exact=False, kind='lower'), low)
+        assert_array_almost_equal(pascal(n, exact=False, kind='upper'), low.T)
+
+    def test_cases(self):
+        for n, sym, low in self.cases:
+            self.check_case(n, sym, low)
+
+    def test_big(self):
+        p = pascal(50)
+        assert p[-1, -1] == comb(98, 49, exact=True)
+
+    def test_threshold(self):
+        # Regression test.  An early version of `pascal` returned an
+        # array of type np.uint64 for n=35, but that data type is too small
+        # to hold p[-1, -1].  The second assert_equal below would fail
+        # because p[-1, -1] overflowed.
+        p = pascal(34)
+        assert_equal(2*p.item(-1, -2), p.item(-1, -1), err_msg="n = 34")
+        p = pascal(35)
+        assert_equal(2.*p.item(-1, -2), 1.*p.item(-1, -1), err_msg="n = 35")
+
+
+def test_invpascal():
+
+    def check_invpascal(n, kind, exact):
+        ip = invpascal(n, kind=kind, exact=exact)
+        p = pascal(n, kind=kind, exact=exact)
+        # Matrix-multiply ip and p, and check that we get the identity matrix.
+        # We can't use the simple expression e = ip.dot(p), because when
+        # n < 35 and exact is True, p.dtype is np.uint64 and ip.dtype is
+        # np.int64. The product of those dtypes is np.float64, which loses
+        # precision when n is greater than 18.  Instead we'll cast both to
+        # object arrays, and then multiply.
+        e = ip.astype(object).dot(p.astype(object))
+        assert_array_equal(e, eye(n), err_msg="n=%d  kind=%r exact=%r" %
+                                              (n, kind, exact))
+
+    kinds = ['symmetric', 'lower', 'upper']
+
+    ns = [1, 2, 5, 18]
+    for n in ns:
+        for kind in kinds:
+            for exact in [True, False]:
+                check_invpascal(n, kind, exact)
+
+    ns = [19, 34, 35, 50]
+    for n in ns:
+        for kind in kinds:
+            check_invpascal(n, kind, True)
+
+
+def test_dft():
+    m = dft(2)
+    expected = array([[1.0, 1.0], [1.0, -1.0]])
+    assert_array_almost_equal(m, expected)
+    m = dft(2, scale='n')
+    assert_array_almost_equal(m, expected/2.0)
+    m = dft(2, scale='sqrtn')
+    assert_array_almost_equal(m, expected/sqrt(2.0))
+
+    x = array([0, 1, 2, 3, 4, 5, 0, 1])
+    m = dft(8)
+    mx = m.dot(x)
+    fx = fft(x)
+    assert_array_almost_equal(mx, fx)
+
+
+def test_fiedler():
+    f = fiedler([])
+    assert_equal(f.size, 0)
+    f = fiedler([123.])
+    assert_array_equal(f, np.array([[0.]]))
+    f = fiedler(np.arange(1, 7))
+    des = np.array([[0, 1, 2, 3, 4, 5],
+                    [1, 0, 1, 2, 3, 4],
+                    [2, 1, 0, 1, 2, 3],
+                    [3, 2, 1, 0, 1, 2],
+                    [4, 3, 2, 1, 0, 1],
+                    [5, 4, 3, 2, 1, 0]])
+    assert_array_equal(f, des)
+
+
+def test_fiedler_companion():
+    fc = fiedler_companion([])
+    assert_equal(fc.size, 0)
+    fc = fiedler_companion([1.])
+    assert_equal(fc.size, 0)
+    fc = fiedler_companion([1., 2.])
+    assert_array_equal(fc, np.array([[-2.]]))
+    fc = fiedler_companion([1e-12, 2., 3.])
+    assert_array_almost_equal(fc, companion([1e-12, 2., 3.]))
+    with assert_raises(ValueError):
+        fiedler_companion([0, 1, 2])
+    fc = fiedler_companion([1., -16., 86., -176., 105.])
+    assert_array_almost_equal(eigvals(fc),
+                              np.array([7., 5., 3., 1.]))
+
+
+class TestConvolutionMatrix:
+    """
+    Test convolution_matrix vs. numpy.convolve for various parameters.
+    """
+
+    def create_vector(self, n, cpx):
+        """Make a complex or real test vector of length n."""
+        x = np.linspace(-2.5, 2.2, n)
+        if cpx:
+            x = x + 1j*np.linspace(-1.5, 3.1, n)
+        return x
+
+    def test_bad_n(self):
+        # n must be a positive integer
+        with pytest.raises(ValueError, match='n must be a positive integer'):
+            convolution_matrix([1, 2, 3], 0)
+
+    def test_empty_first_arg(self):
+        # first arg must have at least one value
+        with pytest.raises(ValueError, match=r'len\(a\)'):
+            convolution_matrix([], 4)
+
+    def test_bad_mode(self):
+        # mode must be in ('full', 'valid', 'same')
+        with pytest.raises(ValueError, match='mode.*must be one of'):
+            convolution_matrix((1, 1), 4, mode='invalid argument')
+
+    @pytest.mark.parametrize('cpx', [False, True])
+    @pytest.mark.parametrize('na', [1, 2, 9])
+    @pytest.mark.parametrize('nv', [1, 2, 9])
+    @pytest.mark.parametrize('mode', [None, 'full', 'valid', 'same'])
+    def test_against_numpy_convolve(self, cpx, na, nv, mode):
+        a = self.create_vector(na, cpx)
+        v = self.create_vector(nv, cpx)
+        if mode is None:
+            y1 = np.convolve(v, a)
+            A = convolution_matrix(a, nv)
+        else:
+            y1 = np.convolve(v, a, mode)
+            A = convolution_matrix(a, nv, mode)
+        y2 = A @ v
+        assert_array_almost_equal(y1, y2)
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.fail_slow(5)  # `leslie` has an import in the function
+@pytest.mark.parametrize('f, args', [(circulant, ()),
+                                     (companion, ()),
+                                     (convolution_matrix, (5, 'same')),
+                                     (fiedler, ()),
+                                     (fiedler_companion, ()),
+                                     (leslie, (np.arange(9),)),
+                                     (toeplitz, (np.arange(9),)),
+                                     ])
+def test_batch(f, args):
+    rng = np.random.default_rng(283592436523456)
+    batch_shape = (2, 3)
+    m = 10
+    A = rng.random(batch_shape + (m,))
+
+    if f in {toeplitz}:
+        message = "Beginning in SciPy 1.17, multidimensional input will be..."
+        with pytest.warns(FutureWarning, match=message):
+            f(A, *args)
+        return
+
+    res = f(A, *args)
+    ref = np.asarray([f(a, *args) for a in A.reshape(-1, m)])
+    ref = ref.reshape(A.shape[:-1] + ref.shape[-2:])
+    assert_allclose(res, ref)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/misc/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/misc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2eb2f71afd54a67b54d7012347e5d1a983fac7be
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/misc/__init__.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+    "scipy.misc is deprecated and will be removed in 2.0.0",
+    DeprecationWarning,
+    stacklevel=2
+)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/misc/common.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/misc/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..e85acca3ac49d1cb84792bdf369cffe69a5d8ad8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/misc/common.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+    "scipy.misc.common is deprecated and will be removed in 2.0.0",
+    DeprecationWarning,
+    stacklevel=2
+)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/misc/doccer.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/misc/doccer.py
new file mode 100644
index 0000000000000000000000000000000000000000..74cabc8c2fd14fe6424b8aad828c329ecdaee4b2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/misc/doccer.py
@@ -0,0 +1,6 @@
+import warnings
+warnings.warn(
+    "scipy.misc.doccer is deprecated and will be removed in 2.0.0",
+    DeprecationWarning,
+    stacklevel=2
+)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e9d9f6ff99218088fd9e693aaca00ca8a070040
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__init__.py
@@ -0,0 +1,173 @@
+"""
+=========================================================
+Multidimensional image processing (:mod:`scipy.ndimage`)
+=========================================================
+
+.. currentmodule:: scipy.ndimage
+
+This package contains various functions for multidimensional image
+processing.
+
+
+Filters
+=======
+
+.. autosummary::
+   :toctree: generated/
+
+   convolve - Multidimensional convolution
+   convolve1d - 1-D convolution along the given axis
+   correlate - Multidimensional correlation
+   correlate1d - 1-D correlation along the given axis
+   gaussian_filter
+   gaussian_filter1d
+   gaussian_gradient_magnitude
+   gaussian_laplace
+   generic_filter - Multidimensional filter using a given function
+   generic_filter1d - 1-D generic filter along the given axis
+   generic_gradient_magnitude
+   generic_laplace
+   laplace - N-D Laplace filter based on approximate second derivatives
+   maximum_filter
+   maximum_filter1d
+   median_filter - Calculates a multidimensional median filter
+   minimum_filter
+   minimum_filter1d
+   percentile_filter - Calculates a multidimensional percentile filter
+   prewitt
+   rank_filter - Calculates a multidimensional rank filter
+   sobel
+   uniform_filter - Multidimensional uniform filter
+   uniform_filter1d - 1-D uniform filter along the given axis
+
+Fourier filters
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   fourier_ellipsoid
+   fourier_gaussian
+   fourier_shift
+   fourier_uniform
+
+Interpolation
+=============
+
+.. autosummary::
+   :toctree: generated/
+
+   affine_transform - Apply an affine transformation
+   geometric_transform - Apply an arbitrary geometric transform
+   map_coordinates - Map input array to new coordinates by interpolation
+   rotate - Rotate an array
+   shift - Shift an array
+   spline_filter
+   spline_filter1d
+   zoom - Zoom an array
+
+Measurements
+============
+
+.. autosummary::
+   :toctree: generated/
+
+   center_of_mass - The center of mass of the values of an array at labels
+   extrema - Min's and max's of an array at labels, with their positions
+   find_objects - Find objects in a labeled array
+   histogram - Histogram of the values of an array, optionally at labels
+   label - Label features in an array
+   labeled_comprehension
+   maximum
+   maximum_position
+   mean - Mean of the values of an array at labels
+   median
+   minimum
+   minimum_position
+   standard_deviation - Standard deviation of an N-D image array
+   sum_labels - Sum of the values of the array
+   value_indices - Find indices of each distinct value in given array
+   variance - Variance of the values of an N-D image array
+   watershed_ift
+
+Morphology
+==========
+
+.. autosummary::
+   :toctree: generated/
+
+   binary_closing
+   binary_dilation
+   binary_erosion
+   binary_fill_holes
+   binary_hit_or_miss
+   binary_opening
+   binary_propagation
+   black_tophat
+   distance_transform_bf
+   distance_transform_cdt
+   distance_transform_edt
+   generate_binary_structure
+   grey_closing
+   grey_dilation
+   grey_erosion
+   grey_opening
+   iterate_structure
+   morphological_gradient
+   morphological_laplace
+   white_tophat
+
+"""
+
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+#    copyright notice, this list of conditions and the following
+#    disclaimer in the documentation and/or other materials provided
+#    with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+#    products derived from this software without specific prior
+#    written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+# bring in the public functionality from private namespaces
+
+# mypy: ignore-errors
+
+from ._support_alternative_backends import *
+
+# adjust __all__ and do not leak implementation details
+from . import _support_alternative_backends
+__all__ = _support_alternative_backends.__all__
+del _support_alternative_backends, _ndimage_api, _delegators  # noqa: F821
+
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import filters
+from . import fourier
+from . import interpolation
+from . import measurements
+from . import morphology
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ad575c98350259341e88b7d0fa45745b9ec00ef
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76576571dbe2470a13a8e971490937cb5d880f6b
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_delegators.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25f914ed8e992ea7ea9e983f13bedf257bdb3684
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c147ee2c8b689cad24e899a0f0765495a32941a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cdff507e57ce7233ac500c60a5ccf2db65b2406f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ca6797113abb994120c9cbaae1a4ed33e886fd5f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c61e06655a797ce545e6f65e6ad430c6c1574573
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e42a73cdd7e31304d2c6e557b5ea851322e70000
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ndimage_api.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbeb448433c543403a5f8cf0c1e99cb26d731d65
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b91dd88125f4dddb361a25adf71e0f2aec049797
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e99f3ce755892226aeeabf08fa6bc5d8c226dc0a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_support_alternative_backends.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbf8b8db9a65fd2a1198adfc40e54a9b9e150b0f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea025be32a6094a8a3fc59d281f47a823e35f3de
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d3ac9c7ddbb501cb2a835047a0ab413c913acc32
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8aafbbcf85b22e13a1548a266020a5ebd00fd661
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb21ba09fdc7239e48eabd986ff576de0b0809a9
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..0d05e123ba1f7f45c1f37795e7ba5cd0257018b4
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..7898248eb4d089b5ffa726ff39de4d0ec4637272
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_delegators.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_delegators.py
new file mode 100644
index 0000000000000000000000000000000000000000..9647ea6456426c9a62178ff277b0f35017a8310b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_delegators.py
@@ -0,0 +1,297 @@
+"""Delegators for alternative backends in scipy.ndimage.
+
+The signature of `func_signature` must match the signature of ndimage.func.
+The job of a `func_signature` is to know which arguments of `ndimage.func`
+are arrays.
+
+* signatures are generated by
+
+--------------
+import inspect
+from scipy import ndimage
+
+names = [x for x in dir(ndimage) if not x.startswith('_')]
+objs = [getattr(ndimage, name) for name in names]
+funcs = [obj for obj in objs if inspect.isroutine(obj)]
+
+for func in funcs:
+    sig = inspect.signature(func)
+    print(f"def {func.__name__}_signature{sig}:\n\tpass\n\n")
+---------------
+
+* which arguments to delegate on: manually trawled the documentation for
+  array-like and array arguments
+
+"""
+import numpy as np
+from scipy._lib._array_api import array_namespace
+from scipy.ndimage._ni_support import _skip_if_dtype, _skip_if_int
+
+
+def affine_transform_signature(
+    input, matrix, offset=0.0, output_shape=None, output=None, *args, **kwds
+):
+    return array_namespace(input, matrix, _skip_if_dtype(output))
+
+
+def binary_closing_signature(
+    input, structure=None, iterations=1, output=None, *args, **kwds
+):
+    return array_namespace(input, structure, _skip_if_dtype(output))
+
+binary_opening_signature = binary_closing_signature
+
+
+def binary_dilation_signature(
+    input, structure=None, iterations=1, mask=None, output=None, *args, **kwds
+):
+    return array_namespace(input, structure, _skip_if_dtype(output), mask)
+
+binary_erosion_signature = binary_dilation_signature
+
+
+def binary_fill_holes_signature(
+    input, structure=None, output=None, origin=0, *args, **kwargs
+):
+    return array_namespace(input, structure, _skip_if_dtype(output))
+
+
+def label_signature(input, structure=None, output=None, origin=0):
+    return array_namespace(input, structure, _skip_if_dtype(output))
+
+
+def binary_hit_or_miss_signature(
+    input, structure1=None, structure2=None, output=None, *args, **kwds
+):
+    return array_namespace(input, structure1, structure2, _skip_if_dtype(output))
+
+
+def binary_propagation_signature(
+    input, structure=None, mask=None, output=None, *args, **kwds
+):
+    return array_namespace(input, structure, mask, _skip_if_dtype(output))
+
+
+def convolve_signature(input, weights, output=None, *args, **kwds):
+    return array_namespace(input, weights, _skip_if_dtype(output))
+
+correlate_signature = convolve_signature
+
+
+def convolve1d_signature(input, weights, axis=-1, output=None, *args, **kwds):
+    return array_namespace(input, weights, _skip_if_dtype(output))
+
+correlate1d_signature = convolve1d_signature
+
+
+def distance_transform_bf_signature(
+    input, metric='euclidean', sampling=None, return_distances=True,
+    return_indices=False, distances=None, indices=None
+):
+    return array_namespace(input, distances, indices)
+
+
+def distance_transform_cdt_signature(
+    input, metric='chessboard', return_distances=True, return_indices=False,
+    distances=None, indices=None
+):
+    return array_namespace(input, distances, indices)
+
+
+def distance_transform_edt_signature(
+    input, sampling=None, return_distances=True, return_indices=False,
+    distances=None, indices=None
+):
+    return array_namespace(input, distances, indices)
+
+
+def find_objects_signature(input, max_label=0):
+    return array_namespace(input)
+
+
+def fourier_ellipsoid_signature(input, size, n=-1, axis=-1, output=None):
+    return array_namespace(input, _skip_if_dtype(output))
+
+fourier_uniform_signature = fourier_ellipsoid_signature
+
+
+def fourier_gaussian_signature(input, sigma, n=-1, axis=-1, output=None):
+    return array_namespace(input, _skip_if_dtype(output))
+
+def fourier_shift_signature(input, shift, n=-1, axis=-1, output=None):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_filter_signature(input, sigma, order=0, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_filter1d_signature(
+    input, sigma, axis=-1, order=0, output=None, *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_gradient_magnitude_signature(input, sigma, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+gaussian_laplace_signature = gaussian_gradient_magnitude_signature
+
+
+def generate_binary_structure_signature(rank, connectivity):
+    # XXX: no input arrays; always return numpy
+    return np
+
+
+def generic_filter_signature(
+    input, function, size=None, footprint=None, output=None, *args, **kwds
+):
+    # XXX: function LowLevelCallable w/backends
+    return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def generic_filter1d_signature(
+    input, function, filter_size, axis=-1, output=None, *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def generic_gradient_magnitude_signature(
+    input, derivative, output=None, *args, **kwds
+):
+    # XXX: function LowLevelCallable w/backends
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def generic_laplace_signature(input, derivative2, output=None, *args, **kwds):
+    # XXX: function LowLevelCallable w/backends
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def geometric_transform_signature(
+    input, mapping, output_shape=None, output=None, *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def histogram_signature(input, min, max, bins, labels=None, index=None):
+    return array_namespace(input, labels)
+
+
+def iterate_structure_signature(structure, iterations, origin=None):
+    return array_namespace(structure)
+
+
+def labeled_comprehension_signature(input, labels, *args, **kwds):
+    return array_namespace(input, labels)
+
+
+def laplace_signature(input, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def map_coordinates_signature(input, coordinates, output=None, *args, **kwds):
+    return array_namespace(input, coordinates, _skip_if_dtype(output))
+
+
+def maximum_filter1d_signature(input, size, axis=-1, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+minimum_filter1d_signature = maximum_filter1d_signature
+uniform_filter1d_signature = maximum_filter1d_signature
+
+
+def maximum_signature(input, labels=None, index=None):
+    return array_namespace(input, labels, _skip_if_int(index))
+
+minimum_signature = maximum_signature
+median_signature = maximum_signature
+mean_signature = maximum_signature
+variance_signature = maximum_signature
+standard_deviation_signature = maximum_signature
+sum_labels_signature = maximum_signature
+sum_signature = maximum_signature  # ndimage.sum is sum_labels
+
+maximum_position_signature = maximum_signature
+minimum_position_signature = maximum_signature
+
+extrema_signature = maximum_signature
+center_of_mass_signature = extrema_signature
+
+
+def median_filter_signature(
+    input, size=None, footprint=None, output=None, *args, **kwds
+):
+    return array_namespace(input, footprint, _skip_if_dtype(output))
+
+minimum_filter_signature = median_filter_signature
+maximum_filter_signature = median_filter_signature
+
+
+def morphological_gradient_signature(
+    input, size=None, footprint=None, structure=None, output=None, *args, **kwds
+):
+    return array_namespace(input, footprint, structure, _skip_if_dtype(output))
+
+morphological_laplace_signature = morphological_gradient_signature
+white_tophat_signature = morphological_gradient_signature
+black_tophat_signature = morphological_gradient_signature
+grey_closing_signature = morphological_gradient_signature
+grey_dilation_signature = morphological_gradient_signature
+grey_erosion_signature = morphological_gradient_signature
+grey_opening_signature = morphological_gradient_signature
+
+
+def percentile_filter_signature(
+    input, percentile, size=None, footprint=None, output=None, *args, **kwds
+):
+    return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def prewitt_signature(input, axis=-1, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+sobel_signature = prewitt_signature
+
+
+def rank_filter_signature(
+    input, rank, size=None, footprint=None, output=None, *args, **kwds
+):
+    return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def rotate_signature(
+    input, angle, axes=(1, 0), reshape=True, output=None , *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def shift_signature(input, shift, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def spline_filter_signature(input, order=3, output=np.float64, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def spline_filter1d_signature(
+    input, order=3, axis=-1, output=np.float64, *args, **kwds
+):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def uniform_filter_signature(input, size=3, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
+
+def value_indices_signature(arr, *args, **kwds):
+    return array_namespace(arr)
+
+
+def watershed_ift_signature(input, markers, structure=None, output=None):
+    return array_namespace(input, markers, structure, _skip_if_dtype(output))
+
+
+def zoom_signature(input, zoom, output=None, *args, **kwds):
+    return array_namespace(input, _skip_if_dtype(output))
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_filters.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..710ea60c03653cc80ac3bd1eefd425b4268a5246
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_filters.py
@@ -0,0 +1,1965 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+#    copyright notice, this list of conditions and the following
+#    disclaimer in the documentation and/or other materials provided
+#    with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+#    products derived from this software without specific prior
+#    written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+from collections.abc import Iterable
+import numbers
+import warnings
+import numpy as np
+import operator
+
+from scipy._lib._util import normalize_axis_index
+from . import _ni_support
+from . import _nd_image
+from . import _ni_docstrings
+from . import _rank_filter_1d
+
+__all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter',
+           'prewitt', 'sobel', 'generic_laplace', 'laplace',
+           'gaussian_laplace', 'generic_gradient_magnitude',
+           'gaussian_gradient_magnitude', 'correlate', 'convolve',
+           'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
+           'maximum_filter1d', 'minimum_filter', 'maximum_filter',
+           'rank_filter', 'median_filter', 'percentile_filter',
+           'generic_filter1d', 'generic_filter']
+
+
+def _invalid_origin(origin, lenw):
+    return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2)
+
+
+def _complex_via_real_components(func, input, weights, output, cval, **kwargs):
+    """Complex convolution via a linear combination of real convolutions."""
+    complex_input = input.dtype.kind == 'c'
+    complex_weights = weights.dtype.kind == 'c'
+    if complex_input and complex_weights:
+        # real component of the output
+        func(input.real, weights.real, output=output.real,
+             cval=np.real(cval), **kwargs)
+        output.real -= func(input.imag, weights.imag, output=None,
+                            cval=np.imag(cval), **kwargs)
+        # imaginary component of the output
+        func(input.real, weights.imag, output=output.imag,
+             cval=np.real(cval), **kwargs)
+        output.imag += func(input.imag, weights.real, output=None,
+                            cval=np.imag(cval), **kwargs)
+    elif complex_input:
+        func(input.real, weights, output=output.real, cval=np.real(cval),
+             **kwargs)
+        func(input.imag, weights, output=output.imag, cval=np.imag(cval),
+             **kwargs)
+    else:
+        if np.iscomplexobj(cval):
+            raise ValueError("Cannot provide a complex-valued cval when the "
+                             "input is real.")
+        func(input, weights.real, output=output.real, cval=cval, **kwargs)
+        func(input, weights.imag, output=output.imag, cval=cval, **kwargs)
+    return output
+
+
+def _expand_origin(ndim_image, axes, origin):
+    num_axes = len(axes)
+    origins = _ni_support._normalize_sequence(origin, num_axes)
+    if num_axes < ndim_image:
+        # set origin = 0 for any axes not being filtered
+        origins_temp = [0,] * ndim_image
+        for o, ax in zip(origins, axes):
+            origins_temp[ax] = o
+        origins = origins_temp
+    return origins
+
+
+def _expand_footprint(ndim_image, axes, footprint,
+                      footprint_name="footprint"):
+    num_axes = len(axes)
+    if num_axes < ndim_image:
+        if footprint.ndim != num_axes:
+            raise RuntimeError(f"{footprint_name}.ndim ({footprint.ndim}) "
+                               f"must match len(axes) ({num_axes})")
+
+        footprint = np.expand_dims(
+            footprint,
+            tuple(ax for ax in range(ndim_image) if ax not in axes)
+        )
+    return footprint
+
+
+def _expand_mode(ndim_image, axes, mode):
+    num_axes = len(axes)
+    if not isinstance(mode, str) and isinstance(mode, Iterable):
+        # set mode = 'constant' for any axes not being filtered
+        modes = _ni_support._normalize_sequence(mode, num_axes)
+        modes_temp = ['constant'] * ndim_image
+        for m, ax in zip(modes, axes):
+            modes_temp[ax] = m
+        mode = modes_temp
+    return mode
+
+
+@_ni_docstrings.docfiller
+def correlate1d(input, weights, axis=-1, output=None, mode="reflect",
+                cval=0.0, origin=0):
+    """Calculate a 1-D correlation along the given axis.
+
+    The lines of the array along the given axis are correlated with the
+    given weights.
+
+    Parameters
+    ----------
+    %(input)s
+    weights : array
+        1-D sequence of numbers.
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    result : ndarray
+        Correlation result. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy.ndimage import correlate1d
+    >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
+    array([ 8, 26,  8, 12,  7, 28, 36,  9])
+    """
+    input = np.asarray(input)
+    weights = np.asarray(weights)
+    complex_input = input.dtype.kind == 'c'
+    complex_weights = weights.dtype.kind == 'c'
+    if complex_input or complex_weights:
+        if complex_weights:
+            weights = weights.conj()
+            weights = weights.astype(np.complex128, copy=False)
+        kwargs = dict(axis=axis, mode=mode, origin=origin)
+        output = _ni_support._get_output(output, input, complex_output=True)
+        return _complex_via_real_components(correlate1d, input, weights,
+                                            output, cval, **kwargs)
+
+    output = _ni_support._get_output(output, input)
+    weights = np.asarray(weights, dtype=np.float64)
+    if weights.ndim != 1 or weights.shape[0] < 1:
+        raise RuntimeError('no filter weights given')
+    if not weights.flags.contiguous:
+        weights = weights.copy()
+    axis = normalize_axis_index(axis, input.ndim)
+    if _invalid_origin(origin, len(weights)):
+        raise ValueError('Invalid origin; origin must satisfy '
+                         '-(len(weights) // 2) <= origin <= '
+                         '(len(weights)-1) // 2')
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.correlate1d(input, weights, axis, output, mode, cval,
+                          origin)
+    return output
+
+
+@_ni_docstrings.docfiller
+def convolve1d(input, weights, axis=-1, output=None, mode="reflect",
+               cval=0.0, origin=0):
+    """Calculate a 1-D convolution along the given axis.
+
+    The lines of the array along the given axis are convolved with the
+    given weights.
+
+    Parameters
+    ----------
+    %(input)s
+    weights : ndarray
+        1-D sequence of numbers.
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    convolve1d : ndarray
+        Convolved array with same shape as input
+
+    Examples
+    --------
+    >>> from scipy.ndimage import convolve1d
+    >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
+    array([14, 24,  4, 13, 12, 36, 27,  0])
+    """
+    weights = np.asarray(weights)
+    weights = weights[::-1]
+    origin = -origin
+    if not weights.shape[0] & 1:
+        origin -= 1
+    if weights.dtype.kind == 'c':
+        # pre-conjugate here to counteract the conjugation in correlate1d
+        weights = weights.conj()
+    return correlate1d(input, weights, axis, output, mode, cval, origin)
+
+
+def _gaussian_kernel1d(sigma, order, radius):
+    """
+    Computes a 1-D Gaussian convolution kernel.
+    """
+    if order < 0:
+        raise ValueError('order must be non-negative')
+    exponent_range = np.arange(order + 1)
+    sigma2 = sigma * sigma
+    x = np.arange(-radius, radius+1)
+    phi_x = np.exp(-0.5 / sigma2 * x ** 2)
+    phi_x = phi_x / phi_x.sum()
+
+    if order == 0:
+        return phi_x
+    else:
+        # f(x) = q(x) * phi(x) = q(x) * exp(p(x))
+        # f'(x) = (q'(x) + q(x) * p'(x)) * phi(x)
+        # p'(x) = -1 / sigma ** 2
+        # Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the
+        # coefficients of q(x)
+        q = np.zeros(order + 1)
+        q[0] = 1
+        D = np.diag(exponent_range[1:], 1)  # D @ q(x) = q'(x)
+        P = np.diag(np.ones(order)/-sigma2, -1)  # P @ q(x) = q(x) * p'(x)
+        Q_deriv = D + P
+        for _ in range(order):
+            q = Q_deriv.dot(q)
+        q = (x[:, None] ** exponent_range).dot(q)
+        return q * phi_x
+
+
+@_ni_docstrings.docfiller
+def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None,
+                      mode="reflect", cval=0.0, truncate=4.0, *, radius=None):
+    """1-D Gaussian filter.
+
+    Parameters
+    ----------
+    %(input)s
+    sigma : scalar
+        standard deviation for Gaussian kernel
+    %(axis)s
+    order : int, optional
+        An order of 0 corresponds to convolution with a Gaussian
+        kernel. A positive order corresponds to convolution with
+        that derivative of a Gaussian.
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    truncate : float, optional
+        Truncate the filter at this many standard deviations.
+        Default is 4.0.
+    radius : None or int, optional
+        Radius of the Gaussian kernel. If specified, the size of
+        the kernel will be ``2*radius + 1``, and `truncate` is ignored.
+        Default is None.
+
+    Returns
+    -------
+    gaussian_filter1d : ndarray
+
+    Notes
+    -----
+    The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
+    `radius` is None, a default ``radius = round(truncate * sigma)`` will be
+    used.
+
+    Examples
+    --------
+    >>> from scipy.ndimage import gaussian_filter1d
+    >>> import numpy as np
+    >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 1)
+    array([ 1.42704095,  2.06782203,  3.        ,  3.93217797,  4.57295905])
+    >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 4)
+    array([ 2.91948343,  2.95023502,  3.        ,  3.04976498,  3.08051657])
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> x = rng.standard_normal(101).cumsum()
+    >>> y3 = gaussian_filter1d(x, 3)
+    >>> y6 = gaussian_filter1d(x, 6)
+    >>> plt.plot(x, 'k', label='original data')
+    >>> plt.plot(y3, '--', label='filtered, sigma=3')
+    >>> plt.plot(y6, ':', label='filtered, sigma=6')
+    >>> plt.legend()
+    >>> plt.grid()
+    >>> plt.show()
+
+    """
+    sd = float(sigma)
+    # make the radius of the filter equal to truncate standard deviations
+    lw = int(truncate * sd + 0.5)
+    if radius is not None:
+        lw = radius
+    if not isinstance(lw, numbers.Integral) or lw < 0:
+        raise ValueError('Radius must be a nonnegative integer.')
+    # Since we are calling correlate, not convolve, revert the kernel
+    weights = _gaussian_kernel1d(sigma, order, lw)[::-1]
+    return correlate1d(input, weights, axis, output, mode, cval, 0)
+
+
+@_ni_docstrings.docfiller
+def gaussian_filter(input, sigma, order=0, output=None,
+                    mode="reflect", cval=0.0, truncate=4.0, *, radius=None,
+                    axes=None):
+    """Multidimensional Gaussian filter.
+
+    Parameters
+    ----------
+    %(input)s
+    sigma : scalar or sequence of scalars
+        Standard deviation for Gaussian kernel. The standard
+        deviations of the Gaussian filter are given for each axis as a
+        sequence, or as a single number, in which case it is equal for
+        all axes.
+    order : int or sequence of ints, optional
+        The order of the filter along each axis is given as a sequence
+        of integers, or as a single number. An order of 0 corresponds
+        to convolution with a Gaussian kernel. A positive order
+        corresponds to convolution with that derivative of a Gaussian.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    truncate : float, optional
+        Truncate the filter at this many standard deviations.
+        Default is 4.0.
+    radius : None or int or sequence of ints, optional
+        Radius of the Gaussian kernel. The radius are given for each axis
+        as a sequence, or as a single number, in which case it is equal
+        for all axes. If specified, the size of the kernel along each axis
+        will be ``2*radius + 1``, and `truncate` is ignored.
+        Default is None.
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `sigma`, `order`, `mode` and/or `radius`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    gaussian_filter : ndarray
+        Returned array of same shape as `input`.
+
+    Notes
+    -----
+    The multidimensional filter is implemented as a sequence of
+    1-D convolution filters. The intermediate arrays are
+    stored in the same data type as the output. Therefore, for output
+    types with a limited precision, the results may be imprecise
+    because intermediate results may be stored with insufficient
+    precision.
+
+    The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
+    `radius` is None, the default ``radius = round(truncate * sigma)`` will be
+    used.
+
+    Examples
+    --------
+    >>> from scipy.ndimage import gaussian_filter
+    >>> import numpy as np
+    >>> a = np.arange(50, step=2).reshape((5,5))
+    >>> a
+    array([[ 0,  2,  4,  6,  8],
+           [10, 12, 14, 16, 18],
+           [20, 22, 24, 26, 28],
+           [30, 32, 34, 36, 38],
+           [40, 42, 44, 46, 48]])
+    >>> gaussian_filter(a, sigma=1)
+    array([[ 4,  6,  8,  9, 11],
+           [10, 12, 14, 15, 17],
+           [20, 22, 24, 25, 27],
+           [29, 31, 33, 34, 36],
+           [35, 37, 39, 40, 42]])
+
+    >>> from scipy import datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = gaussian_filter(ascent, sigma=5)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _ni_support._get_output(output, input)
+
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    orders = _ni_support._normalize_sequence(order, num_axes)
+    sigmas = _ni_support._normalize_sequence(sigma, num_axes)
+    modes = _ni_support._normalize_sequence(mode, num_axes)
+    radiuses = _ni_support._normalize_sequence(radius, num_axes)
+    axes = [(axes[ii], sigmas[ii], orders[ii], modes[ii], radiuses[ii])
+            for ii in range(num_axes) if sigmas[ii] > 1e-15]
+    if len(axes) > 0:
+        for axis, sigma, order, mode, radius in axes:
+            gaussian_filter1d(input, sigma, axis, order, output,
+                              mode, cval, truncate, radius=radius)
+            input = output
+    else:
+        output[...] = input[...]
+    return output
+
+
+@_ni_docstrings.docfiller
+def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0):
+    """Calculate a Prewitt filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(axis)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+
+    Returns
+    -------
+    prewitt : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    See Also
+    --------
+    sobel: Sobel filter
+
+    Notes
+    -----
+    This function computes the one-dimensional Prewitt filter.
+    Horizontal edges are emphasised with the horizontal transform (axis=0),
+    vertical edges with the vertical transform (axis=1), and so on for higher
+    dimensions. These can be combined to give the magnitude.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> ascent = datasets.ascent()
+    >>> prewitt_h = ndimage.prewitt(ascent, axis=0)
+    >>> prewitt_v = ndimage.prewitt(ascent, axis=1)
+    >>> magnitude = np.sqrt(prewitt_h ** 2 + prewitt_v ** 2)
+    >>> magnitude *= 255 / np.max(magnitude) # Normalization
+    >>> fig, axes = plt.subplots(2, 2, figsize = (8, 8))
+    >>> plt.gray()
+    >>> axes[0, 0].imshow(ascent)
+    >>> axes[0, 1].imshow(prewitt_h)
+    >>> axes[1, 0].imshow(prewitt_v)
+    >>> axes[1, 1].imshow(magnitude)
+    >>> titles = ["original", "horizontal", "vertical", "magnitude"]
+    >>> for i, ax in enumerate(axes.ravel()):
+    ...     ax.set_title(titles[i])
+    ...     ax.axis("off")
+    >>> plt.show()
+
+    """
+    input = np.asarray(input)
+    axis = normalize_axis_index(axis, input.ndim)
+    output = _ni_support._get_output(output, input)
+    modes = _ni_support._normalize_sequence(mode, input.ndim)
+    correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
+    axes = [ii for ii in range(input.ndim) if ii != axis]
+    for ii in axes:
+        correlate1d(output, [1, 1, 1], ii, output, modes[ii], cval, 0,)
+    return output
+
+
+@_ni_docstrings.docfiller
+def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0):
+    """Calculate a Sobel filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(axis)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+
+    Returns
+    -------
+    sobel : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    This function computes the axis-specific Sobel gradient.
+    The horizontal edges can be emphasised with the horizontal transform (axis=0),
+    the vertical edges with the vertical transform (axis=1) and so on for higher
+    dimensions. These can be combined to give the magnitude.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+    >>> ascent = datasets.ascent().astype('int32')
+    >>> sobel_h = ndimage.sobel(ascent, 0)  # horizontal gradient
+    >>> sobel_v = ndimage.sobel(ascent, 1)  # vertical gradient
+    >>> magnitude = np.sqrt(sobel_h**2 + sobel_v**2)
+    >>> magnitude *= 255.0 / np.max(magnitude)  # normalization
+    >>> fig, axs = plt.subplots(2, 2, figsize=(8, 8))
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> axs[0, 0].imshow(ascent)
+    >>> axs[0, 1].imshow(sobel_h)
+    >>> axs[1, 0].imshow(sobel_v)
+    >>> axs[1, 1].imshow(magnitude)
+    >>> titles = ["original", "horizontal", "vertical", "magnitude"]
+    >>> for i, ax in enumerate(axs.ravel()):
+    ...     ax.set_title(titles[i])
+    ...     ax.axis("off")
+    >>> plt.show()
+
+    """
+    input = np.asarray(input)
+    axis = normalize_axis_index(axis, input.ndim)
+    output = _ni_support._get_output(output, input)
+    modes = _ni_support._normalize_sequence(mode, input.ndim)
+    correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
+    axes = [ii for ii in range(input.ndim) if ii != axis]
+    for ii in axes:
+        correlate1d(output, [1, 2, 1], ii, output, modes[ii], cval, 0)
+    return output
+
+
+@_ni_docstrings.docfiller
+def generic_laplace(input, derivative2, output=None, mode="reflect",
+                    cval=0.0,
+                    extra_arguments=(),
+                    extra_keywords=None,
+                    *, axes=None):
+    """
+    N-D Laplace filter using a provided second derivative function.
+
+    Parameters
+    ----------
+    %(input)s
+    derivative2 : callable
+        Callable with the following signature::
+
+            derivative2(input, axis, output, mode, cval,
+                        *extra_arguments, **extra_keywords)
+
+        See `extra_arguments`, `extra_keywords` below.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(extra_keywords)s
+    %(extra_arguments)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If a `mode` tuple is
+        provided, its length must match the number of axes.
+
+    Returns
+    -------
+    generic_laplace : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    """
+    if extra_keywords is None:
+        extra_keywords = {}
+    input = np.asarray(input)
+    output = _ni_support._get_output(output, input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    if len(axes) > 0:
+        modes = _ni_support._normalize_sequence(mode, len(axes))
+        derivative2(input, axes[0], output, modes[0], cval,
+                    *extra_arguments, **extra_keywords)
+        for ii in range(1, len(axes)):
+            tmp = derivative2(input, axes[ii], output.dtype, modes[ii], cval,
+                              *extra_arguments, **extra_keywords)
+            output += tmp
+    else:
+        output[...] = input[...]
+    return output
+
+
+@_ni_docstrings.docfiller
+def laplace(input, output=None, mode="reflect", cval=0.0, *, axes=None):
+    """N-D Laplace filter based on approximate second derivatives.
+
+    Parameters
+    ----------
+    %(input)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If a `mode` tuple is
+        provided, its length must match the number of axes.
+
+    Returns
+    -------
+    laplace : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.laplace(ascent)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    def derivative2(input, axis, output, mode, cval):
+        return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)
+    return generic_laplace(input, derivative2, output, mode, cval, axes=axes)
+
+
+@_ni_docstrings.docfiller
+def gaussian_laplace(input, sigma, output=None, mode="reflect",
+                     cval=0.0, *, axes=None, **kwargs):
+    """Multidimensional Laplace filter using Gaussian second derivatives.
+
+    Parameters
+    ----------
+    %(input)s
+    sigma : scalar or sequence of scalars
+        The standard deviations of the Gaussian filter are given for
+        each axis as a sequence, or as a single number, in which case
+        it is equal for all axes.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If `sigma` or `mode` tuples
+        are provided, their length must match the number of axes.
+    Extra keyword arguments will be passed to gaussian_filter().
+
+    Returns
+    -------
+    gaussian_laplace : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> ascent = datasets.ascent()
+
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+
+    >>> result = ndimage.gaussian_laplace(ascent, sigma=1)
+    >>> ax1.imshow(result)
+
+    >>> result = ndimage.gaussian_laplace(ascent, sigma=3)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+
+    def derivative2(input, axis, output, mode, cval, sigma, **kwargs):
+        order = [0] * input.ndim
+        order[axis] = 2
+        return gaussian_filter(input, sigma, order, output, mode, cval,
+                               **kwargs)
+
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    sigma = _ni_support._normalize_sequence(sigma, num_axes)
+    if num_axes < input.ndim:
+        # set sigma = 0 for any axes not being filtered
+        sigma_temp = [0,] * input.ndim
+        for s, ax in zip(sigma, axes):
+            sigma_temp[ax] = s
+        sigma = sigma_temp
+
+    return generic_laplace(input, derivative2, output, mode, cval,
+                           extra_arguments=(sigma,),
+                           extra_keywords=kwargs,
+                           axes=axes)
+
+
+@_ni_docstrings.docfiller
+def generic_gradient_magnitude(input, derivative, output=None,
+                               mode="reflect", cval=0.0,
+                               extra_arguments=(), extra_keywords=None,
+                               *, axes=None):
+    """Gradient magnitude using a provided gradient function.
+
+    Parameters
+    ----------
+    %(input)s
+    derivative : callable
+        Callable with the following signature::
+
+            derivative(input, axis, output, mode, cval,
+                       *extra_arguments, **extra_keywords)
+
+        See `extra_arguments`, `extra_keywords` below.
+        `derivative` can assume that `input` and `output` are ndarrays.
+        Note that the output from `derivative` is modified inplace;
+        be careful to copy important inputs before returning them.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(extra_keywords)s
+    %(extra_arguments)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If a `mode` tuple is
+        provided, its length must match the number of axes.
+
+    Returns
+    -------
+    generic_gradient_matnitude : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    """
+    if extra_keywords is None:
+        extra_keywords = {}
+    input = np.asarray(input)
+    output = _ni_support._get_output(output, input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    if len(axes) > 0:
+        modes = _ni_support._normalize_sequence(mode, len(axes))
+        derivative(input, axes[0], output, modes[0], cval,
+                   *extra_arguments, **extra_keywords)
+        np.multiply(output, output, output)
+        for ii in range(1, len(axes)):
+            tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval,
+                             *extra_arguments, **extra_keywords)
+            np.multiply(tmp, tmp, tmp)
+            output += tmp
+        # This allows the sqrt to work with a different default casting
+        np.sqrt(output, output, casting='unsafe')
+    else:
+        output[...] = input[...]
+    return output
+
+
+@_ni_docstrings.docfiller
+def gaussian_gradient_magnitude(input, sigma, output=None,
+                                mode="reflect", cval=0.0, *, axes=None,
+                                **kwargs):
+    """Multidimensional gradient magnitude using Gaussian derivatives.
+
+    Parameters
+    ----------
+    %(input)s
+    sigma : scalar or sequence of scalars
+        The standard deviations of the Gaussian filter are given for
+        each axis as a sequence, or as a single number, in which case
+        it is equal for all axes.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    axes : tuple of int or None
+        The axes over which to apply the filter. If `sigma` or `mode` tuples
+        are provided, their length must match the number of axes.
+    Extra keyword arguments will be passed to gaussian_filter().
+
+    Returns
+    -------
+    gaussian_gradient_magnitude : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+
+    def derivative(input, axis, output, mode, cval, sigma, **kwargs):
+        order = [0] * input.ndim
+        order[axis] = 1
+        return gaussian_filter(input, sigma, order, output, mode,
+                               cval, **kwargs)
+
+    return generic_gradient_magnitude(input, derivative, output, mode,
+                                      cval, extra_arguments=(sigma,),
+                                      extra_keywords=kwargs, axes=axes)
+
+
+def _correlate_or_convolve(input, weights, output, mode, cval, origin,
+                           convolution, axes):
+    input = np.asarray(input)
+    weights = np.asarray(weights)
+    complex_input = input.dtype.kind == 'c'
+    complex_weights = weights.dtype.kind == 'c'
+    if complex_input or complex_weights:
+        if complex_weights and not convolution:
+            # As for np.correlate, conjugate weights rather than input.
+            weights = weights.conj()
+        kwargs = dict(
+            mode=mode, origin=origin, convolution=convolution, axes=axes
+        )
+        output = _ni_support._get_output(output, input, complex_output=True)
+
+        return _complex_via_real_components(_correlate_or_convolve, input,
+                                            weights, output, cval, **kwargs)
+
+    axes = _ni_support._check_axes(axes, input.ndim)
+    weights = np.asarray(weights, dtype=np.float64)
+
+    # expand weights and origins if num_axes < input.ndim
+    weights = _expand_footprint(input.ndim, axes, weights, "weights")
+    origins = _expand_origin(input.ndim, axes, origin)
+
+    wshape = [ii for ii in weights.shape if ii > 0]
+    if len(wshape) != input.ndim:
+        raise RuntimeError(f"weights.ndim ({len(wshape)}) must match "
+                           f"len(axes) ({len(axes)})")
+    if convolution:
+        weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
+        for ii in range(len(origins)):
+            origins[ii] = -origins[ii]
+            if not weights.shape[ii] & 1:
+                origins[ii] -= 1
+    for origin, lenw in zip(origins, wshape):
+        if _invalid_origin(origin, lenw):
+            raise ValueError('Invalid origin; origin must satisfy '
+                             '-(weights.shape[k] // 2) <= origin[k] <= '
+                             '(weights.shape[k]-1) // 2')
+
+    if not weights.flags.contiguous:
+        weights = weights.copy()
+    output = _ni_support._get_output(output, input)
+    temp_needed = np.may_share_memory(input, output)
+    if temp_needed:
+        # input and output arrays cannot share memory
+        temp = output
+        output = _ni_support._get_output(output.dtype, input)
+    if not isinstance(mode, str) and isinstance(mode, Iterable):
+        raise RuntimeError("A sequence of modes is not supported")
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.correlate(input, weights, output, mode, cval, origins)
+    if temp_needed:
+        temp[...] = output
+        output = temp
+    return output
+
+
+@_ni_docstrings.docfiller
+def correlate(input, weights, output=None, mode='reflect', cval=0.0,
+              origin=0, *, axes=None):
+    """
+    Multidimensional correlation.
+
+    The array is correlated with the given kernel.
+
+    Parameters
+    ----------
+    %(input)s
+    weights : ndarray
+        array of weights, same number of dimensions as input
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `mode` or `origin` must match the length
+        of `axes`. The ith entry in any of these tuples corresponds to the ith
+        entry in `axes`.
+
+    Returns
+    -------
+    result : ndarray
+        The result of correlation of `input` with `weights`.
+
+    See Also
+    --------
+    convolve : Convolve an image with a kernel.
+
+    Examples
+    --------
+    Correlation is the process of moving a filter mask often referred to
+    as kernel over the image and computing the sum of products at each location.
+
+    >>> from scipy.ndimage import correlate
+    >>> import numpy as np
+    >>> input_img = np.arange(25).reshape(5,5)
+    >>> print(input_img)
+    [[ 0  1  2  3  4]
+    [ 5  6  7  8  9]
+    [10 11 12 13 14]
+    [15 16 17 18 19]
+    [20 21 22 23 24]]
+
+    Define a kernel (weights) for correlation. In this example, it is for sum of
+    center and up, down, left and right next elements.
+
+    >>> weights = [[0, 1, 0],
+    ...            [1, 1, 1],
+    ...            [0, 1, 0]]
+
+    We can calculate a correlation result:
+    For example, element ``[2,2]`` is ``7 + 11 + 12 + 13 + 17 = 60``.
+
+    >>> correlate(input_img, weights)
+    array([[  6,  10,  15,  20,  24],
+        [ 26,  30,  35,  40,  44],
+        [ 51,  55,  60,  65,  69],
+        [ 76,  80,  85,  90,  94],
+        [ 96, 100, 105, 110, 114]])
+
+    """
+    return _correlate_or_convolve(input, weights, output, mode, cval,
+                                  origin, False, axes)
+
+
+@_ni_docstrings.docfiller
+def convolve(input, weights, output=None, mode='reflect', cval=0.0,
+             origin=0, *, axes=None):
+    """
+    Multidimensional convolution.
+
+    The array is convolved with the given kernel.
+
+    Parameters
+    ----------
+    %(input)s
+    weights : array_like
+        Array of weights, same number of dimensions as input
+    %(output)s
+    %(mode_reflect)s
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0
+    origin : int or sequence, optional
+        Controls the placement of the filter on the input array's pixels.
+        A value of 0 (the default) centers the filter over the pixel, with
+        positive values shifting the filter to the right, and negative ones
+        to the left. By passing a sequence of origins with length equal to
+        the number of dimensions of the input array, different shifts can
+        be specified along each axis.
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `mode` or `origin` must match the length
+        of `axes`. The ith entry in any of these tuples corresponds to the ith
+        entry in `axes`.
+
+    Returns
+    -------
+    result : ndarray
+        The result of convolution of `input` with `weights`.
+
+    See Also
+    --------
+    correlate : Correlate an image with a kernel.
+
+    Notes
+    -----
+    Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where
+    W is the `weights` kernel,
+    j is the N-D spatial index over :math:`W`,
+    I is the `input` and k is the coordinate of the center of
+    W, specified by `origin` in the input parameters.
+
+    Examples
+    --------
+    Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
+    because in this case borders (i.e., where the `weights` kernel, centered
+    on any one value, extends beyond an edge of `input`) are treated as zeros.
+
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
+    >>> from scipy import ndimage
+    >>> ndimage.convolve(a, k, mode='constant', cval=0.0)
+    array([[11, 10,  7,  4],
+           [10,  3, 11, 11],
+           [15, 12, 14,  7],
+           [12,  3,  7,  0]])
+
+    Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
+    with 1.0's (and then extracting only the original region of the result).
+
+    >>> ndimage.convolve(a, k, mode='constant', cval=1.0)
+    array([[13, 11,  8,  7],
+           [11,  3, 11, 14],
+           [16, 12, 14, 10],
+           [15,  6, 10,  5]])
+
+    With ``mode='reflect'`` (the default), outer values are reflected at the
+    edge of `input` to fill in missing values.
+
+    >>> b = np.array([[2, 0, 0],
+    ...               [1, 0, 0],
+    ...               [0, 0, 0]])
+    >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]])
+    >>> ndimage.convolve(b, k, mode='reflect')
+    array([[5, 0, 0],
+           [3, 0, 0],
+           [1, 0, 0]])
+
+    This includes diagonally at the corners.
+
+    >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
+    >>> ndimage.convolve(b, k)
+    array([[4, 2, 0],
+           [3, 2, 0],
+           [1, 1, 0]])
+
+    With ``mode='nearest'``, the single nearest value in to an edge in
+    `input` is repeated as many times as needed to match the overlapping
+    `weights`.
+
+    >>> c = np.array([[2, 0, 1],
+    ...               [1, 0, 0],
+    ...               [0, 0, 0]])
+    >>> k = np.array([[0, 1, 0],
+    ...               [0, 1, 0],
+    ...               [0, 1, 0],
+    ...               [0, 1, 0],
+    ...               [0, 1, 0]])
+    >>> ndimage.convolve(c, k, mode='nearest')
+    array([[7, 0, 3],
+           [5, 0, 2],
+           [3, 0, 1]])
+
+    """
+    return _correlate_or_convolve(input, weights, output, mode, cval,
+                                  origin, True, axes)
+
+
+@_ni_docstrings.docfiller
+def uniform_filter1d(input, size, axis=-1, output=None,
+                     mode="reflect", cval=0.0, origin=0):
+    """Calculate a 1-D uniform filter along the given axis.
+
+    The lines of the array along the given axis are filtered with a
+    uniform filter of given size.
+
+    Parameters
+    ----------
+    %(input)s
+    size : int
+        length of uniform filter
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    result : ndarray
+        Filtered array. Has same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy.ndimage import uniform_filter1d
+    >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+    array([4, 3, 4, 1, 4, 6, 6, 3])
+    """
+    input = np.asarray(input)
+    axis = normalize_axis_index(axis, input.ndim)
+    if size < 1:
+        raise RuntimeError('incorrect filter size')
+    complex_output = input.dtype.kind == 'c'
+    output = _ni_support._get_output(output, input,
+                                     complex_output=complex_output)
+    if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+        raise ValueError('invalid origin')
+    mode = _ni_support._extend_mode_to_code(mode)
+    if not complex_output:
+        _nd_image.uniform_filter1d(input, size, axis, output, mode, cval,
+                                   origin)
+    else:
+        _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode,
+                                   np.real(cval), origin)
+        _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode,
+                                   np.imag(cval), origin)
+    return output
+
+
+@_ni_docstrings.docfiller
+def uniform_filter(input, size=3, output=None, mode="reflect",
+                   cval=0.0, origin=0, *, axes=None):
+    """Multidimensional uniform filter.
+
+    Parameters
+    ----------
+    %(input)s
+    size : int or sequence of ints, optional
+        The sizes of the uniform filter are given for each axis as a
+        sequence, or as a single number, in which case the size is
+        equal for all axes.
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    uniform_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    The multidimensional filter is implemented as a sequence of
+    1-D uniform filters. The intermediate arrays are stored
+    in the same data type as the output. Therefore, for output types
+    with a limited precision, the results may be imprecise because
+    intermediate results may be stored with insufficient precision.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.uniform_filter(ascent, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _ni_support._get_output(output, input,
+                                     complex_output=input.dtype.kind == 'c')
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    sizes = _ni_support._normalize_sequence(size, num_axes)
+    origins = _ni_support._normalize_sequence(origin, num_axes)
+    modes = _ni_support._normalize_sequence(mode, num_axes)
+    axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
+            for ii in range(num_axes) if sizes[ii] > 1]
+    if len(axes) > 0:
+        for axis, size, origin, mode in axes:
+            uniform_filter1d(input, int(size), axis, output, mode,
+                             cval, origin)
+            input = output
+    else:
+        output[...] = input[...]
+    return output
+
+
+@_ni_docstrings.docfiller
+def minimum_filter1d(input, size, axis=-1, output=None,
+                     mode="reflect", cval=0.0, origin=0):
+    """Calculate a 1-D minimum filter along the given axis.
+
+    The lines of the array along the given axis are filtered with a
+    minimum filter of given size.
+
+    Parameters
+    ----------
+    %(input)s
+    size : int
+        length along which to calculate 1D minimum
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    result : ndarray.
+        Filtered image. Has the same shape as `input`.
+
+    Notes
+    -----
+    This function implements the MINLIST algorithm [1]_, as described by
+    Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
+    the `input` length, regardless of filter size.
+
+    References
+    ----------
+    .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
+    .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
+
+
+    Examples
+    --------
+    >>> from scipy.ndimage import minimum_filter1d
+    >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+    array([2, 0, 0, 0, 1, 1, 0, 0])
+    """
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axis = normalize_axis_index(axis, input.ndim)
+    if size < 1:
+        raise RuntimeError('incorrect filter size')
+    output = _ni_support._get_output(output, input)
+    if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+        raise ValueError('invalid origin')
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
+                                  origin, 1)
+    return output
+
+
+@_ni_docstrings.docfiller
+def maximum_filter1d(input, size, axis=-1, output=None,
+                     mode="reflect", cval=0.0, origin=0):
+    """Calculate a 1-D maximum filter along the given axis.
+
+    The lines of the array along the given axis are filtered with a
+    maximum filter of given size.
+
+    Parameters
+    ----------
+    %(input)s
+    size : int
+        Length along which to calculate the 1-D maximum.
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+
+    Returns
+    -------
+    maximum1d : ndarray, None
+        Maximum-filtered array with same shape as input.
+        None if `output` is not None
+
+    Notes
+    -----
+    This function implements the MAXLIST algorithm [1]_, as described by
+    Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
+    the `input` length, regardless of filter size.
+
+    References
+    ----------
+    .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
+    .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
+
+    Examples
+    --------
+    >>> from scipy.ndimage import maximum_filter1d
+    >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+    array([8, 8, 8, 4, 9, 9, 9, 9])
+    """
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axis = normalize_axis_index(axis, input.ndim)
+    if size < 1:
+        raise RuntimeError('incorrect filter size')
+    output = _ni_support._get_output(output, input)
+    if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+        raise ValueError('invalid origin')
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
+                                  origin, 0)
+    return output
+
+
+def _min_or_max_filter(input, size, footprint, structure, output, mode,
+                       cval, origin, minimum, axes=None):
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=3)
+    if structure is None:
+        if footprint is None:
+            if size is None:
+                raise RuntimeError("no footprint provided")
+            separable = True
+        else:
+            footprint = np.asarray(footprint, dtype=bool)
+            if not footprint.any():
+                raise ValueError("All-zero footprint is not supported.")
+            if footprint.all():
+                size = footprint.shape
+                footprint = None
+                separable = True
+            else:
+                separable = False
+    else:
+        structure = np.asarray(structure, dtype=np.float64)
+        separable = False
+        if footprint is None:
+            footprint = np.ones(structure.shape, bool)
+        else:
+            footprint = np.asarray(footprint, dtype=bool)
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError("Complex type not supported")
+    output = _ni_support._get_output(output, input)
+    temp_needed = np.may_share_memory(input, output)
+    if temp_needed:
+        # input and output arrays cannot share memory
+        temp = output
+        output = _ni_support._get_output(output.dtype, input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if separable:
+        origins = _ni_support._normalize_sequence(origin, num_axes)
+        sizes = _ni_support._normalize_sequence(size, num_axes)
+        modes = _ni_support._normalize_sequence(mode, num_axes)
+        axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
+                for ii in range(len(axes)) if sizes[ii] > 1]
+        if minimum:
+            filter_ = minimum_filter1d
+        else:
+            filter_ = maximum_filter1d
+        if len(axes) > 0:
+            for axis, size, origin, mode in axes:
+                filter_(input, int(size), axis, output, mode, cval, origin)
+                input = output
+        else:
+            output[...] = input[...]
+    else:
+        # expand origins and footprint if num_axes < input.ndim
+        footprint = _expand_footprint(input.ndim, axes, footprint)
+        origins = _expand_origin(input.ndim, axes, origin)
+
+        fshape = [ii for ii in footprint.shape if ii > 0]
+        if len(fshape) != input.ndim:
+            raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
+                               f"len(axes) ({len(axes)})")
+        for origin, lenf in zip(origins, fshape):
+            if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+                raise ValueError("invalid origin")
+        if not footprint.flags.contiguous:
+            footprint = footprint.copy()
+        if structure is not None:
+            if len(structure.shape) != num_axes:
+                raise RuntimeError("structure array has incorrect shape")
+            if num_axes != structure.ndim:
+                structure = np.expand_dims(
+                    structure,
+                    tuple(ax for ax in range(structure.ndim) if ax not in axes)
+                )
+            if not structure.flags.contiguous:
+                structure = structure.copy()
+        if not isinstance(mode, str) and isinstance(mode, Iterable):
+            raise RuntimeError(
+                "A sequence of modes is not supported for non-separable "
+                "footprints")
+        mode = _ni_support._extend_mode_to_code(mode)
+        _nd_image.min_or_max_filter(input, footprint, structure, output,
+                                    mode, cval, origins, minimum)
+    if temp_needed:
+        temp[...] = output
+        output = temp
+    return output
+
+
+@_ni_docstrings.docfiller
+def minimum_filter(input, size=None, footprint=None, output=None,
+                   mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """Calculate a multidimensional minimum filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(size_foot)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    minimum_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    A sequence of modes (one per axis) is only supported when the footprint is
+    separable. Otherwise, a single mode string must be provided.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.minimum_filter(ascent, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    return _min_or_max_filter(input, size, footprint, None, output, mode,
+                              cval, origin, 1, axes)
+
+
+@_ni_docstrings.docfiller
+def maximum_filter(input, size=None, footprint=None, output=None,
+                   mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """Calculate a multidimensional maximum filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(size_foot)s
+    %(output)s
+    %(mode_multiple)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    maximum_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    A sequence of modes (one per axis) is only supported when the footprint is
+    separable. Otherwise, a single mode string must be provided.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.maximum_filter(ascent, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    return _min_or_max_filter(input, size, footprint, None, output, mode,
+                              cval, origin, 0, axes)
+
+
+@_ni_docstrings.docfiller
+def _rank_filter(input, rank, size=None, footprint=None, output=None,
+                 mode="reflect", cval=0.0, origin=0, operation='rank',
+                 axes=None):
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=3)
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if footprint is None:
+        if size is None:
+            raise RuntimeError("no footprint or filter size provided")
+        sizes = _ni_support._normalize_sequence(size, num_axes)
+        footprint = np.ones(sizes, dtype=bool)
+    else:
+        footprint = np.asarray(footprint, dtype=bool)
+    # expand origins, footprint and modes if num_axes < input.ndim
+    footprint = _expand_footprint(input.ndim, axes, footprint)
+    origins = _expand_origin(input.ndim, axes, origin)
+    mode = _expand_mode(input.ndim, axes, mode)
+
+    fshape = [ii for ii in footprint.shape if ii > 0]
+    if len(fshape) != input.ndim:
+        raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
+                           f"len(axes) ({len(axes)})")
+    for origin, lenf in zip(origins, fshape):
+        if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+            raise ValueError('invalid origin')
+    if not footprint.flags.contiguous:
+        footprint = footprint.copy()
+    filter_size = np.where(footprint, 1, 0).sum()
+    if operation == 'median':
+        rank = filter_size // 2
+    elif operation == 'percentile':
+        percentile = rank
+        if percentile < 0.0:
+            percentile += 100.0
+        if percentile < 0 or percentile > 100:
+            raise RuntimeError('invalid percentile')
+        if percentile == 100.0:
+            rank = filter_size - 1
+        else:
+            rank = int(float(filter_size) * percentile / 100.0)
+    if rank < 0:
+        rank += filter_size
+    if rank < 0 or rank >= filter_size:
+        raise RuntimeError('rank not within filter footprint size')
+    if rank == 0:
+        return minimum_filter(input, None, footprint, output, mode, cval,
+                              origins, axes=None)
+    elif rank == filter_size - 1:
+        return maximum_filter(input, None, footprint, output, mode, cval,
+                              origins, axes=None)
+    else:
+        output = _ni_support._get_output(output, input)
+        temp_needed = np.may_share_memory(input, output)
+        if temp_needed:
+            # input and output arrays cannot share memory
+            temp = output
+            output = _ni_support._get_output(output.dtype, input)
+        if not isinstance(mode, str) and isinstance(mode, Iterable):
+            raise RuntimeError(
+                "A sequence of modes is not supported by non-separable rank "
+                "filters")
+        mode = _ni_support._extend_mode_to_code(mode, is_filter=True)
+        if input.ndim == 1:
+            if input.dtype in (np.int64, np.float64, np.float32):
+                x = input
+                x_out = output
+            elif input.dtype == np.float16:
+                x = input.astype('float32')
+                x_out = np.empty(x.shape, dtype='float32')
+            elif np.result_type(input, np.int64) == np.int64:
+                x = input.astype('int64')
+                x_out = np.empty(x.shape, dtype='int64')
+            elif input.dtype.kind in 'biu':
+                # cast any other boolean, integer or unsigned type to int64
+                x = input.astype('int64')
+                x_out = np.empty(x.shape, dtype='int64')
+            else:
+                raise RuntimeError('Unsupported array type')
+            cval = x.dtype.type(cval)
+            _rank_filter_1d.rank_filter(x, rank, footprint.size, x_out, mode, cval,
+                                        origin)
+            if input.dtype not in (np.int64, np.float64, np.float32):
+                np.copyto(output, x_out, casting='unsafe')
+        else:
+            _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins)
+        if temp_needed:
+            temp[...] = output
+            output = temp
+        return output
+
+
+@_ni_docstrings.docfiller
+def rank_filter(input, rank, size=None, footprint=None, output=None,
+                mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """Calculate a multidimensional rank filter.
+
+    Parameters
+    ----------
+    %(input)s
+    rank : int
+        The rank parameter may be less than zero, i.e., rank = -1
+        indicates the largest element.
+    %(size_foot)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    rank_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.rank_filter(ascent, rank=42, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    rank = operator.index(rank)
+    return _rank_filter(input, rank, size, footprint, output, mode, cval,
+                        origin, 'rank', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def median_filter(input, size=None, footprint=None, output=None,
+                  mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """
+    Calculate a multidimensional median filter.
+
+    Parameters
+    ----------
+    %(input)s
+    %(size_foot)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    median_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    See Also
+    --------
+    scipy.signal.medfilt2d
+
+    Notes
+    -----
+    For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes
+    the specialised function `scipy.signal.medfilt2d` may be faster. It is
+    however limited to constant mode with ``cval=0``.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.median_filter(ascent, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    return _rank_filter(input, 0, size, footprint, output, mode, cval,
+                        origin, 'median', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def percentile_filter(input, percentile, size=None, footprint=None,
+                      output=None, mode="reflect", cval=0.0, origin=0, *,
+                      axes=None):
+    """Calculate a multidimensional percentile filter.
+
+    Parameters
+    ----------
+    %(input)s
+    percentile : scalar
+        The percentile parameter may be less than zero, i.e.,
+        percentile = -20 equals percentile = 80
+    %(size_foot)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size`, `origin`, and/or `mode`
+        must match the length of `axes`. The ith entry in any of these tuples
+        corresponds to the ith entry in `axes`.
+
+    Returns
+    -------
+    percentile_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result)
+    >>> plt.show()
+    """
+    return _rank_filter(input, percentile, size, footprint, output, mode,
+                        cval, origin, 'percentile', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def generic_filter1d(input, function, filter_size, axis=-1,
+                     output=None, mode="reflect", cval=0.0, origin=0,
+                     extra_arguments=(), extra_keywords=None):
+    """Calculate a 1-D filter along the given axis.
+
+    `generic_filter1d` iterates over the lines of the array, calling the
+    given function at each line. The arguments of the line are the
+    input line, and the output line. The input and output lines are 1-D
+    double arrays. The input line is extended appropriately according
+    to the filter size and origin. The output line must be modified
+    in-place with the result.
+
+    Parameters
+    ----------
+    %(input)s
+    function : {callable, scipy.LowLevelCallable}
+        Function to apply along given axis.
+    filter_size : scalar
+        Length of the filter.
+    %(axis)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin)s
+    %(extra_arguments)s
+    %(extra_keywords)s
+
+    Returns
+    -------
+    generic_filter1d : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    This function also accepts low-level callback functions with one of
+    the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+    .. code:: c
+
+       int function(double *input_line, npy_intp input_length,
+                    double *output_line, npy_intp output_length,
+                    void *user_data)
+       int function(double *input_line, intptr_t input_length,
+                    double *output_line, intptr_t output_length,
+                    void *user_data)
+
+    The calling function iterates over the lines of the input and output
+    arrays, calling the callback function at each line. The current line
+    is extended according to the border conditions set by the calling
+    function, and the result is copied into the array that is passed
+    through ``input_line``. The length of the input line (after extension)
+    is passed through ``input_length``. The callback function should apply
+    the filter and store the result in the array passed through
+    ``output_line``. The length of the output line is passed through
+    ``output_length``. ``user_data`` is the data pointer provided
+    to `scipy.LowLevelCallable` as-is.
+
+    The callback function must return an integer error status that is zero
+    if something went wrong and one otherwise. If an error occurs, you should
+    normally set the python error status with an informative message
+    before returning, otherwise a default error message is set by the
+    calling function.
+
+    In addition, some other low-level function pointer specifications
+    are accepted, but these are for backward compatibility only and should
+    not be used in new code.
+
+    """
+    if extra_keywords is None:
+        extra_keywords = {}
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    output = _ni_support._get_output(output, input)
+    if filter_size < 1:
+        raise RuntimeError('invalid filter size')
+    axis = normalize_axis_index(axis, input.ndim)
+    if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >=
+                                           filter_size):
+        raise ValueError('invalid origin')
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.generic_filter1d(input, function, filter_size, axis, output,
+                               mode, cval, origin, extra_arguments,
+                               extra_keywords)
+    return output
+
+
+@_ni_docstrings.docfiller
+def generic_filter(input, function, size=None, footprint=None,
+                   output=None, mode="reflect", cval=0.0, origin=0,
+                   extra_arguments=(), extra_keywords=None, *, axes=None):
+    """Calculate a multidimensional filter using the given function.
+
+    At each element the provided function is called. The input values
+    within the filter footprint at that element are passed to the function
+    as a 1-D array of double values.
+
+    Parameters
+    ----------
+    %(input)s
+    function : {callable, scipy.LowLevelCallable}
+        Function to apply at each element.
+    %(size_foot)s
+    %(output)s
+    %(mode_reflect)s
+    %(cval)s
+    %(origin_multiple)s
+    %(extra_arguments)s
+    %(extra_keywords)s
+    axes : tuple of int or None, optional
+        If None, `input` is filtered along all axes. Otherwise,
+        `input` is filtered along the specified axes. When `axes` is
+        specified, any tuples used for `size` or `origin` must match the length
+        of `axes`. The ith entry in any of these tuples corresponds to the ith
+        entry in `axes`.
+
+    Returns
+    -------
+    generic_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    Notes
+    -----
+    This function also accepts low-level callback functions with one of
+    the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+    .. code:: c
+
+       int callback(double *buffer, npy_intp filter_size,
+                    double *return_value, void *user_data)
+       int callback(double *buffer, intptr_t filter_size,
+                    double *return_value, void *user_data)
+
+    The calling function iterates over the elements of the input and
+    output arrays, calling the callback function at each element. The
+    elements within the footprint of the filter at the current element are
+    passed through the ``buffer`` parameter, and the number of elements
+    within the footprint through ``filter_size``. The calculated value is
+    returned in ``return_value``. ``user_data`` is the data pointer provided
+    to `scipy.LowLevelCallable` as-is.
+
+    The callback function must return an integer error status that is zero
+    if something went wrong and one otherwise. If an error occurs, you should
+    normally set the python error status with an informative message
+    before returning, otherwise a default error message is set by the
+    calling function.
+
+    In addition, some other low-level function pointer specifications
+    are accepted, but these are for backward compatibility only and should
+    not be used in new code.
+
+    Examples
+    --------
+    Import the necessary modules and load the example image used for
+    filtering.
+
+    >>> import numpy as np
+    >>> from scipy import datasets
+    >>> from scipy.ndimage import zoom, generic_filter
+    >>> import matplotlib.pyplot as plt
+    >>> ascent = zoom(datasets.ascent(), 0.5)
+
+    Compute a maximum filter with kernel size 5 by passing a simple NumPy
+    aggregation function as argument to `function`.
+
+    >>> maximum_filter_result = generic_filter(ascent, np.amax, [5, 5])
+
+    While a maximum filter could also directly be obtained using
+    `maximum_filter`, `generic_filter` allows generic Python function or
+    `scipy.LowLevelCallable` to be used as a filter. Here, we compute the
+    range between maximum and minimum value as an example for a kernel size
+    of 5.
+
+    >>> def custom_filter(image):
+    ...     return np.amax(image) - np.amin(image)
+    >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5])
+
+    Plot the original and filtered images.
+
+    >>> fig, axes = plt.subplots(3, 1, figsize=(3, 9))
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> top, middle, bottom = axes
+    >>> for ax in axes:
+    ...     ax.set_axis_off()  # remove coordinate system
+    >>> top.imshow(ascent)
+    >>> top.set_title("Original image")
+    >>> middle.imshow(maximum_filter_result)
+    >>> middle.set_title("Maximum filter, Kernel: 5x5")
+    >>> bottom.imshow(custom_filter_result)
+    >>> bottom.set_title("Custom filter, Kernel: 5x5")
+    >>> fig.tight_layout()
+
+    """
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    if extra_keywords is None:
+        extra_keywords = {}
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if footprint is None:
+        if size is None:
+            raise RuntimeError("no footprint or filter size provided")
+        sizes = _ni_support._normalize_sequence(size, num_axes)
+        footprint = np.ones(sizes, dtype=bool)
+    else:
+        footprint = np.asarray(footprint, dtype=bool)
+
+    # expand origins, footprint if num_axes < input.ndim
+    footprint = _expand_footprint(input.ndim, axes, footprint)
+    origins = _expand_origin(input.ndim, axes, origin)
+
+    fshape = [ii for ii in footprint.shape if ii > 0]
+    if len(fshape) != input.ndim:
+        raise RuntimeError(f"footprint.ndim ({footprint.ndim}) "
+                           f"must match len(axes) ({num_axes})")
+    for origin, lenf in zip(origins, fshape):
+        if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+            raise ValueError('invalid origin')
+    if not footprint.flags.contiguous:
+        footprint = footprint.copy()
+    output = _ni_support._get_output(output, input)
+
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.generic_filter(input, function, footprint, output, mode,
+                             cval, origins, extra_arguments, extra_keywords)
+    return output
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_fourier.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb5ffa6b9287cb740611aefba5f1f322011518cf
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_fourier.py
@@ -0,0 +1,306 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+#    copyright notice, this list of conditions and the following
+#    disclaimer in the documentation and/or other materials provided
+#    with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+#    products derived from this software without specific prior
+#    written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+from . import _ni_support
+from . import _nd_image
+
+__all__ = ['fourier_gaussian', 'fourier_uniform', 'fourier_ellipsoid',
+           'fourier_shift']
+
+
+def _get_output_fourier(output, input):
+    if output is None:
+        if input.dtype.type in [np.complex64, np.complex128, np.float32]:
+            output = np.zeros(input.shape, dtype=input.dtype)
+        else:
+            output = np.zeros(input.shape, dtype=np.float64)
+    elif type(output) is type:
+        if output not in [np.complex64, np.complex128,
+                          np.float32, np.float64]:
+            raise RuntimeError("output type not supported")
+        output = np.zeros(input.shape, dtype=output)
+    elif output.shape != input.shape:
+        raise RuntimeError("output shape not correct")
+    return output
+
+
+def _get_output_fourier_complex(output, input):
+    if output is None:
+        if input.dtype.type in [np.complex64, np.complex128]:
+            output = np.zeros(input.shape, dtype=input.dtype)
+        else:
+            output = np.zeros(input.shape, dtype=np.complex128)
+    elif type(output) is type:
+        if output not in [np.complex64, np.complex128]:
+            raise RuntimeError("output type not supported")
+        output = np.zeros(input.shape, dtype=output)
+    elif output.shape != input.shape:
+        raise RuntimeError("output shape not correct")
+    return output
+
+
+def fourier_gaussian(input, sigma, n=-1, axis=-1, output=None):
+    """
+    Multidimensional Gaussian fourier filter.
+
+    The array is multiplied with the fourier transform of a Gaussian
+    kernel.
+
+    Parameters
+    ----------
+    input : array_like
+        The input array.
+    sigma : float or sequence
+        The sigma of the Gaussian kernel. If a float, `sigma` is the same for
+        all axes. If a sequence, `sigma` has to contain one value for each
+        axis.
+    n : int, optional
+        If `n` is negative (default), then the input is assumed to be the
+        result of a complex fft.
+        If `n` is larger than or equal to zero, the input is assumed to be the
+        result of a real fft, and `n` gives the length of the array before
+        transformation along the real transform direction.
+    axis : int, optional
+        The axis of the real transform.
+    output : ndarray, optional
+        If given, the result of filtering the input is placed in this array.
+
+    Returns
+    -------
+    fourier_gaussian : ndarray
+        The filtered input.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import numpy.fft
+    >>> import matplotlib.pyplot as plt
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ascent = datasets.ascent()
+    >>> input_ = numpy.fft.fft2(ascent)
+    >>> result = ndimage.fourier_gaussian(input_, sigma=4)
+    >>> result = numpy.fft.ifft2(result)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result.real)  # the imaginary part is an artifact
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _get_output_fourier(output, input)
+    axis = normalize_axis_index(axis, input.ndim)
+    sigmas = _ni_support._normalize_sequence(sigma, input.ndim)
+    sigmas = np.asarray(sigmas, dtype=np.float64)
+    if not sigmas.flags.contiguous:
+        sigmas = sigmas.copy()
+
+    _nd_image.fourier_filter(input, sigmas, n, axis, output, 0)
+    return output
+
+
+def fourier_uniform(input, size, n=-1, axis=-1, output=None):
+    """
+    Multidimensional uniform fourier filter.
+
+    The array is multiplied with the Fourier transform of a box of given
+    size.
+
+    Parameters
+    ----------
+    input : array_like
+        The input array.
+    size : float or sequence
+        The size of the box used for filtering.
+        If a float, `size` is the same for all axes. If a sequence, `size` has
+        to contain one value for each axis.
+    n : int, optional
+        If `n` is negative (default), then the input is assumed to be the
+        result of a complex fft.
+        If `n` is larger than or equal to zero, the input is assumed to be the
+        result of a real fft, and `n` gives the length of the array before
+        transformation along the real transform direction.
+    axis : int, optional
+        The axis of the real transform.
+    output : ndarray, optional
+        If given, the result of filtering the input is placed in this array.
+
+    Returns
+    -------
+    fourier_uniform : ndarray
+        The filtered input.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import numpy.fft
+    >>> import matplotlib.pyplot as plt
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ascent = datasets.ascent()
+    >>> input_ = numpy.fft.fft2(ascent)
+    >>> result = ndimage.fourier_uniform(input_, size=20)
+    >>> result = numpy.fft.ifft2(result)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result.real)  # the imaginary part is an artifact
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _get_output_fourier(output, input)
+    axis = normalize_axis_index(axis, input.ndim)
+    sizes = _ni_support._normalize_sequence(size, input.ndim)
+    sizes = np.asarray(sizes, dtype=np.float64)
+    if not sizes.flags.contiguous:
+        sizes = sizes.copy()
+    _nd_image.fourier_filter(input, sizes, n, axis, output, 1)
+    return output
+
+
+def fourier_ellipsoid(input, size, n=-1, axis=-1, output=None):
+    """
+    Multidimensional ellipsoid Fourier filter.
+
+    The array is multiplied with the fourier transform of an ellipsoid of
+    given sizes.
+
+    Parameters
+    ----------
+    input : array_like
+        The input array.
+    size : float or sequence
+        The size of the box used for filtering.
+        If a float, `size` is the same for all axes. If a sequence, `size` has
+        to contain one value for each axis.
+    n : int, optional
+        If `n` is negative (default), then the input is assumed to be the
+        result of a complex fft.
+        If `n` is larger than or equal to zero, the input is assumed to be the
+        result of a real fft, and `n` gives the length of the array before
+        transformation along the real transform direction.
+    axis : int, optional
+        The axis of the real transform.
+    output : ndarray, optional
+        If given, the result of filtering the input is placed in this array.
+
+    Returns
+    -------
+    fourier_ellipsoid : ndarray
+        The filtered input.
+
+    Notes
+    -----
+    This function is implemented for arrays of rank 1, 2, or 3.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import numpy.fft
+    >>> import matplotlib.pyplot as plt
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ascent = datasets.ascent()
+    >>> input_ = numpy.fft.fft2(ascent)
+    >>> result = ndimage.fourier_ellipsoid(input_, size=20)
+    >>> result = numpy.fft.ifft2(result)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result.real)  # the imaginary part is an artifact
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    if input.ndim > 3:
+        raise NotImplementedError("Only 1d, 2d and 3d inputs are supported")
+    output = _get_output_fourier(output, input)
+    if output.size == 0:
+        # The C code has a bug that can result in a segfault with arrays
+        # that have size 0 (gh-17270), so check here.
+        return output
+    axis = normalize_axis_index(axis, input.ndim)
+    sizes = _ni_support._normalize_sequence(size, input.ndim)
+    sizes = np.asarray(sizes, dtype=np.float64)
+    if not sizes.flags.contiguous:
+        sizes = sizes.copy()
+    _nd_image.fourier_filter(input, sizes, n, axis, output, 2)
+    return output
+
+
+def fourier_shift(input, shift, n=-1, axis=-1, output=None):
+    """
+    Multidimensional Fourier shift filter.
+
+    The array is multiplied with the Fourier transform of a shift operation.
+
+    Parameters
+    ----------
+    input : array_like
+        The input array.
+    shift : float or sequence
+        The size of the box used for filtering.
+        If a float, `shift` is the same for all axes. If a sequence, `shift`
+        has to contain one value for each axis.
+    n : int, optional
+        If `n` is negative (default), then the input is assumed to be the
+        result of a complex fft.
+        If `n` is larger than or equal to zero, the input is assumed to be the
+        result of a real fft, and `n` gives the length of the array before
+        transformation along the real transform direction.
+    axis : int, optional
+        The axis of the real transform.
+    output : ndarray, optional
+        If given, the result of shifting the input is placed in this array.
+
+    Returns
+    -------
+    fourier_shift : ndarray
+        The shifted input.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy.fft
+    >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> ascent = datasets.ascent()
+    >>> input_ = numpy.fft.fft2(ascent)
+    >>> result = ndimage.fourier_shift(input_, shift=200)
+    >>> result = numpy.fft.ifft2(result)
+    >>> ax1.imshow(ascent)
+    >>> ax2.imshow(result.real)  # the imaginary part is an artifact
+    >>> plt.show()
+    """
+    input = np.asarray(input)
+    output = _get_output_fourier_complex(output, input)
+    axis = normalize_axis_index(axis, input.ndim)
+    shifts = _ni_support._normalize_sequence(shift, input.ndim)
+    shifts = np.asarray(shifts, dtype=np.float64)
+    if not shifts.flags.contiguous:
+        shifts = shifts.copy()
+    _nd_image.fourier_shift(input, shifts, n, axis, output)
+    return output
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e4ea94184871fe87f848532b21e2def29bd406b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py
@@ -0,0 +1,1003 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+#    copyright notice, this list of conditions and the following
+#    disclaimer in the documentation and/or other materials provided
+#    with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+#    products derived from this software without specific prior
+#    written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import itertools
+import warnings
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+
+from scipy import special
+from . import _ni_support
+from . import _nd_image
+from ._ni_docstrings import docfiller
+
+
+__all__ = ['spline_filter1d', 'spline_filter', 'geometric_transform',
+           'map_coordinates', 'affine_transform', 'shift', 'zoom', 'rotate']
+
+
+@docfiller
+def spline_filter1d(input, order=3, axis=-1, output=np.float64,
+                    mode='mirror'):
+    """
+    Calculate a 1-D spline filter along the given axis.
+
+    The lines of the array along the given axis are filtered by a
+    spline filter. The order of the spline must be >= 2 and <= 5.
+
+    Parameters
+    ----------
+    %(input)s
+    order : int, optional
+        The order of the spline, default is 3.
+    axis : int, optional
+        The axis along which the spline filter is applied. Default is the last
+        axis.
+    output : ndarray or dtype, optional
+        The array in which to place the output, or the dtype of the returned
+        array. Default is ``numpy.float64``.
+    %(mode_interp_mirror)s
+
+    Returns
+    -------
+    spline_filter1d : ndarray
+        The filtered input.
+
+    See Also
+    --------
+    spline_filter : Multidimensional spline filter.
+
+    Notes
+    -----
+    All of the interpolation functions in `ndimage` do spline interpolation of
+    the input image. If using B-splines of `order > 1`, the input image
+    values have to be converted to B-spline coefficients first, which is
+    done by applying this 1-D filter sequentially along all
+    axes of the input. All functions that require B-spline coefficients
+    will automatically filter their inputs, a behavior controllable with
+    the `prefilter` keyword argument. For functions that accept a `mode`
+    parameter, the result will only be correct if it matches the `mode`
+    used when filtering.
+
+    For complex-valued `input`, this function processes the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    We can filter an image using 1-D spline along the given axis:
+
+    >>> from scipy.ndimage import spline_filter1d
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> orig_img = np.eye(20)  # create an image
+    >>> orig_img[10, :] = 1.0
+    >>> sp_filter_axis_0 = spline_filter1d(orig_img, axis=0)
+    >>> sp_filter_axis_1 = spline_filter1d(orig_img, axis=1)
+    >>> f, ax = plt.subplots(1, 3, sharex=True)
+    >>> for ind, data in enumerate([[orig_img, "original image"],
+    ...             [sp_filter_axis_0, "spline filter (axis=0)"],
+    ...             [sp_filter_axis_1, "spline filter (axis=1)"]]):
+    ...     ax[ind].imshow(data[0], cmap='gray_r')
+    ...     ax[ind].set_title(data[1])
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input,
+                                     complex_output=complex_output)
+    if complex_output:
+        spline_filter1d(input.real, order, axis, output.real, mode)
+        spline_filter1d(input.imag, order, axis, output.imag, mode)
+        return output
+    if order in [0, 1]:
+        output[...] = np.array(input)
+    else:
+        mode = _ni_support._extend_mode_to_code(mode)
+        axis = normalize_axis_index(axis, input.ndim)
+        _nd_image.spline_filter1d(input, order, axis, output, mode)
+    return output
+
+@docfiller
+def spline_filter(input, order=3, output=np.float64, mode='mirror'):
+    """
+    Multidimensional spline filter.
+
+    Parameters
+    ----------
+    %(input)s
+    order : int, optional
+        The order of the spline, default is 3.
+    output : ndarray or dtype, optional
+        The array in which to place the output, or the dtype of the returned
+        array. Default is ``numpy.float64``.
+    %(mode_interp_mirror)s
+
+    Returns
+    -------
+    spline_filter : ndarray
+        Filtered array. Has the same shape as `input`.
+
+    See Also
+    --------
+    spline_filter1d : Calculate a 1-D spline filter along the given axis.
+
+    Notes
+    -----
+    The multidimensional filter is implemented as a sequence of
+    1-D spline filters. The intermediate arrays are stored
+    in the same data type as the output. Therefore, for output types
+    with a limited precision, the results may be imprecise because
+    intermediate results may be stored with insufficient precision.
+
+    For complex-valued `input`, this function processes the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    We can filter an image using multidimensional splines:
+
+    >>> from scipy.ndimage import spline_filter
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> orig_img = np.eye(20)  # create an image
+    >>> orig_img[10, :] = 1.0
+    >>> sp_filter = spline_filter(orig_img, order=3)
+    >>> f, ax = plt.subplots(1, 2, sharex=True)
+    >>> for ind, data in enumerate([[orig_img, "original image"],
+    ...                             [sp_filter, "spline filter"]]):
+    ...     ax[ind].imshow(data[0], cmap='gray_r')
+    ...     ax[ind].set_title(data[1])
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    """
+    if order < 2 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input,
+                                     complex_output=complex_output)
+    if complex_output:
+        spline_filter(input.real, order, output.real, mode)
+        spline_filter(input.imag, order, output.imag, mode)
+        return output
+    if order not in [0, 1] and input.ndim > 0:
+        for axis in range(input.ndim):
+            spline_filter1d(input, order, axis, output=output, mode=mode)
+            input = output
+    else:
+        output[...] = input[...]
+    return output
+
+
+def _prepad_for_spline_filter(input, mode, cval):
+    if mode in ['nearest', 'grid-constant']:
+        npad = 12
+        if mode == 'grid-constant':
+            padded = np.pad(input, npad, mode='constant',
+                               constant_values=cval)
+        elif mode == 'nearest':
+            padded = np.pad(input, npad, mode='edge')
+    else:
+        # other modes have exact boundary conditions implemented so
+        # no prepadding is needed
+        npad = 0
+        padded = input
+    return padded, npad
+
+
+@docfiller
+def geometric_transform(input, mapping, output_shape=None,
+                        output=None, order=3,
+                        mode='constant', cval=0.0, prefilter=True,
+                        extra_arguments=(), extra_keywords=None):
+    """
+    Apply an arbitrary geometric transform.
+
+    The given mapping function is used to find, for each point in the
+    output, the corresponding coordinates in the input. The value of the
+    input at those coordinates is determined by spline interpolation of
+    the requested order.
+
+    Parameters
+    ----------
+    %(input)s
+    mapping : {callable, scipy.LowLevelCallable}
+        A callable object that accepts a tuple of length equal to the output
+        array rank, and returns the corresponding input coordinates as a tuple
+        of length equal to the input array rank.
+    output_shape : tuple of ints, optional
+        Shape tuple.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+    extra_arguments : tuple, optional
+        Extra arguments passed to `mapping`.
+    extra_keywords : dict, optional
+        Extra keywords passed to `mapping`.
+
+    Returns
+    -------
+    output : ndarray
+        The filtered input.
+
+    See Also
+    --------
+    map_coordinates, affine_transform, spline_filter1d
+
+
+    Notes
+    -----
+    This function also accepts low-level callback functions with one
+    the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+    .. code:: c
+
+       int mapping(npy_intp *output_coordinates, double *input_coordinates,
+                   int output_rank, int input_rank, void *user_data)
+       int mapping(intptr_t *output_coordinates, double *input_coordinates,
+                   int output_rank, int input_rank, void *user_data)
+
+    The calling function iterates over the elements of the output array,
+    calling the callback function at each element. The coordinates of the
+    current output element are passed through ``output_coordinates``. The
+    callback function must return the coordinates at which the input must
+    be interpolated in ``input_coordinates``. The rank of the input and
+    output arrays are given by ``input_rank`` and ``output_rank``
+    respectively. ``user_data`` is the data pointer provided
+    to `scipy.LowLevelCallable` as-is.
+
+    The callback function must return an integer error status that is zero
+    if something went wrong and one otherwise. If an error occurs, you should
+    normally set the Python error status with an informative message
+    before returning, otherwise a default error message is set by the
+    calling function.
+
+    In addition, some other low-level function pointer specifications
+    are accepted, but these are for backward compatibility only and should
+    not be used in new code.
+
+    For complex-valued `input`, this function transforms the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.ndimage import geometric_transform
+    >>> a = np.arange(12.).reshape((4, 3))
+    >>> def shift_func(output_coords):
+    ...     return (output_coords[0] - 0.5, output_coords[1] - 0.5)
+    ...
+    >>> geometric_transform(a, shift_func)
+    array([[ 0.   ,  0.   ,  0.   ],
+           [ 0.   ,  1.362,  2.738],
+           [ 0.   ,  4.812,  6.187],
+           [ 0.   ,  8.263,  9.637]])
+
+    >>> b = [1, 2, 3, 4, 5]
+    >>> def shift_func(output_coords):
+    ...     return (output_coords[0] - 3,)
+    ...
+    >>> geometric_transform(b, shift_func, mode='constant')
+    array([0, 0, 0, 1, 2])
+    >>> geometric_transform(b, shift_func, mode='nearest')
+    array([1, 1, 1, 1, 2])
+    >>> geometric_transform(b, shift_func, mode='reflect')
+    array([3, 2, 1, 1, 2])
+    >>> geometric_transform(b, shift_func, mode='wrap')
+    array([2, 3, 4, 1, 2])
+
+    """
+    if extra_keywords is None:
+        extra_keywords = {}
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    if output_shape is None:
+        output_shape = input.shape
+    if input.ndim < 1 or len(output_shape) < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, shape=output_shape,
+                                     complex_output=complex_output)
+    if complex_output:
+        kwargs = dict(order=order, mode=mode, prefilter=prefilter,
+                      output_shape=output_shape,
+                      extra_arguments=extra_arguments,
+                      extra_keywords=extra_keywords)
+        geometric_transform(input.real, mapping, output=output.real,
+                            cval=np.real(cval), **kwargs)
+        geometric_transform(input.imag, mapping, output=output.imag,
+                            cval=np.imag(cval), **kwargs)
+        return output
+
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64,
+                                 mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.geometric_transform(filtered, mapping, None, None, None, output,
+                                  order, mode, cval, npad, extra_arguments,
+                                  extra_keywords)
+    return output
+
+
+@docfiller
+def map_coordinates(input, coordinates, output=None, order=3,
+                    mode='constant', cval=0.0, prefilter=True):
+    """
+    Map the input array to new coordinates by interpolation.
+
+    The array of coordinates is used to find, for each point in the output,
+    the corresponding coordinates in the input. The value of the input at
+    those coordinates is determined by spline interpolation of the
+    requested order.
+
+    The shape of the output is derived from that of the coordinate
+    array by dropping the first axis. The values of the array along
+    the first axis are the coordinates in the input array at which the
+    output value is found.
+
+    Parameters
+    ----------
+    %(input)s
+    coordinates : array_like
+        The coordinates at which `input` is evaluated.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+
+    Returns
+    -------
+    map_coordinates : ndarray
+        The result of transforming the input. The shape of the output is
+        derived from that of `coordinates` by dropping the first axis.
+
+    See Also
+    --------
+    spline_filter, geometric_transform, scipy.interpolate
+
+    Notes
+    -----
+    For complex-valued `input`, this function maps the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.arange(12.).reshape((4, 3))
+    >>> a
+    array([[  0.,   1.,   2.],
+           [  3.,   4.,   5.],
+           [  6.,   7.,   8.],
+           [  9.,  10.,  11.]])
+    >>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
+    array([ 2.,  7.])
+
+    Above, the interpolated value of a[0.5, 0.5] gives output[0], while
+    a[2, 1] is output[1].
+
+    >>> inds = np.array([[0.5, 2], [0.5, 4]])
+    >>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)
+    array([  2. , -33.3])
+    >>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
+    array([ 2.,  8.])
+    >>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
+    array([ True, False], dtype=bool)
+
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    coordinates = np.asarray(coordinates)
+    if np.iscomplexobj(coordinates):
+        raise TypeError('Complex type not supported')
+    output_shape = coordinates.shape[1:]
+    if input.ndim < 1 or len(output_shape) < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    if coordinates.shape[0] != input.ndim:
+        raise RuntimeError('invalid shape for coordinate array')
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, shape=output_shape,
+                                     complex_output=complex_output)
+    if complex_output:
+        kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+        map_coordinates(input.real, coordinates, output=output.real,
+                        cval=np.real(cval), **kwargs)
+        map_coordinates(input.imag, coordinates, output=output.imag,
+                        cval=np.imag(cval), **kwargs)
+        return output
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    mode = _ni_support._extend_mode_to_code(mode)
+    _nd_image.geometric_transform(filtered, None, coordinates, None, None,
+                                  output, order, mode, cval, npad, None, None)
+    return output
+
+
+@docfiller
+def affine_transform(input, matrix, offset=0.0, output_shape=None,
+                     output=None, order=3,
+                     mode='constant', cval=0.0, prefilter=True):
+    """
+    Apply an affine transformation.
+
+    Given an output image pixel index vector ``o``, the pixel value
+    is determined from the input image at position
+    ``np.dot(matrix, o) + offset``.
+
+    This does 'pull' (or 'backward') resampling, transforming the output space
+    to the input to locate data. Affine transformations are often described in
+    the 'push' (or 'forward') direction, transforming input to output. If you
+    have a matrix for the 'push' transformation, use its inverse
+    (:func:`numpy.linalg.inv`) in this function.
+
+    Parameters
+    ----------
+    %(input)s
+    matrix : ndarray
+        The inverse coordinate transformation matrix, mapping output
+        coordinates to input coordinates. If ``ndim`` is the number of
+        dimensions of ``input``, the given matrix must have one of the
+        following shapes:
+
+            - ``(ndim, ndim)``: the linear transformation matrix for each
+              output coordinate.
+            - ``(ndim,)``: assume that the 2-D transformation matrix is
+              diagonal, with the diagonal specified by the given value. A more
+              efficient algorithm is then used that exploits the separability
+              of the problem.
+            - ``(ndim + 1, ndim + 1)``: assume that the transformation is
+              specified using homogeneous coordinates [1]_. In this case, any
+              value passed to ``offset`` is ignored.
+            - ``(ndim, ndim + 1)``: as above, but the bottom row of a
+              homogeneous transformation matrix is always ``[0, 0, ..., 1]``,
+              and may be omitted.
+
+    offset : float or sequence, optional
+        The offset into the array where the transform is applied. If a float,
+        `offset` is the same for each axis. If a sequence, `offset` should
+        contain one value for each axis.
+    output_shape : tuple of ints, optional
+        Shape tuple.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+
+    Returns
+    -------
+    affine_transform : ndarray
+        The transformed input.
+
+    Notes
+    -----
+    The given matrix and offset are used to find for each point in the
+    output the corresponding coordinates in the input by an affine
+    transformation. The value of the input at those coordinates is
+    determined by spline interpolation of the requested order. Points
+    outside the boundaries of the input are filled according to the given
+    mode.
+
+    .. versionchanged:: 0.18.0
+        Previously, the exact interpretation of the affine transformation
+        depended on whether the matrix was supplied as a 1-D or a
+        2-D array. If a 1-D array was supplied
+        to the matrix parameter, the output pixel value at index ``o``
+        was determined from the input image at position
+        ``matrix * (o + offset)``.
+
+    For complex-valued `input`, this function transforms the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Homogeneous_coordinates
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    if output_shape is None:
+        if isinstance(output, np.ndarray):
+            output_shape = output.shape
+        else:
+            output_shape = input.shape
+    if input.ndim < 1 or len(output_shape) < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, shape=output_shape,
+                                     complex_output=complex_output)
+    if complex_output:
+        kwargs = dict(offset=offset, output_shape=output_shape, order=order,
+                      mode=mode, prefilter=prefilter)
+        affine_transform(input.real, matrix, output=output.real,
+                         cval=np.real(cval), **kwargs)
+        affine_transform(input.imag, matrix, output=output.imag,
+                         cval=np.imag(cval), **kwargs)
+        return output
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    mode = _ni_support._extend_mode_to_code(mode)
+    matrix = np.asarray(matrix, dtype=np.float64)
+    if matrix.ndim not in [1, 2] or matrix.shape[0] < 1:
+        raise RuntimeError('no proper affine matrix provided')
+    if (matrix.ndim == 2 and matrix.shape[1] == input.ndim + 1 and
+            (matrix.shape[0] in [input.ndim, input.ndim + 1])):
+        if matrix.shape[0] == input.ndim + 1:
+            exptd = [0] * input.ndim + [1]
+            if not np.all(matrix[input.ndim] == exptd):
+                msg = (f'Expected homogeneous transformation matrix with '
+                       f'shape {matrix.shape} for image shape {input.shape}, '
+                       f'but bottom row was not equal to {exptd}')
+                raise ValueError(msg)
+        # assume input is homogeneous coordinate transformation matrix
+        offset = matrix[:input.ndim, input.ndim]
+        matrix = matrix[:input.ndim, :input.ndim]
+    if matrix.shape[0] != input.ndim:
+        raise RuntimeError('affine matrix has wrong number of rows')
+    if matrix.ndim == 2 and matrix.shape[1] != output.ndim:
+        raise RuntimeError('affine matrix has wrong number of columns')
+    if not matrix.flags.contiguous:
+        matrix = matrix.copy()
+    offset = _ni_support._normalize_sequence(offset, input.ndim)
+    offset = np.asarray(offset, dtype=np.float64)
+    if offset.ndim != 1 or offset.shape[0] < 1:
+        raise RuntimeError('no proper offset provided')
+    if not offset.flags.contiguous:
+        offset = offset.copy()
+    if matrix.ndim == 1:
+        warnings.warn(
+            "The behavior of affine_transform with a 1-D "
+            "array supplied for the matrix parameter has changed in "
+            "SciPy 0.18.0.",
+            stacklevel=2
+        )
+        _nd_image.zoom_shift(filtered, matrix, offset/matrix, output, order,
+                             mode, cval, npad, False)
+    else:
+        _nd_image.geometric_transform(filtered, None, None, matrix, offset,
+                                      output, order, mode, cval, npad, None,
+                                      None)
+    return output
+
+
+@docfiller
+def shift(input, shift, output=None, order=3, mode='constant', cval=0.0,
+          prefilter=True):
+    """
+    Shift an array.
+
+    The array is shifted using spline interpolation of the requested order.
+    Points outside the boundaries of the input are filled according to the
+    given mode.
+
+    Parameters
+    ----------
+    %(input)s
+    shift : float or sequence
+        The shift along the axes. If a float, `shift` is the same for each
+        axis. If a sequence, `shift` should contain one value for each axis.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+
+    Returns
+    -------
+    shift : ndarray
+        The shifted input.
+
+    See Also
+    --------
+    affine_transform : Affine transformations
+
+    Notes
+    -----
+    For complex-valued `input`, this function shifts the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    Import the necessary modules and an exemplary image.
+
+    >>> from scipy.ndimage import shift
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import datasets
+    >>> image = datasets.ascent()
+
+    Shift the image vertically by 20 pixels.
+
+    >>> image_shifted_vertically = shift(image, (20, 0))
+
+    Shift the image vertically by -200 pixels and horizontally by 100 pixels.
+
+    >>> image_shifted_both_directions = shift(image, (-200, 100))
+
+    Plot the original and the shifted images.
+
+    >>> fig, axes = plt.subplots(3, 1, figsize=(4, 12))
+    >>> plt.gray()  # show the filtered result in grayscale
+    >>> top, middle, bottom = axes
+    >>> for ax in axes:
+    ...     ax.set_axis_off()  # remove coordinate system
+    >>> top.imshow(image)
+    >>> top.set_title("Original image")
+    >>> middle.imshow(image_shifted_vertically)
+    >>> middle.set_title("Vertically shifted image")
+    >>> bottom.imshow(image_shifted_both_directions)
+    >>> bottom.set_title("Image shifted in both directions")
+    >>> fig.tight_layout()
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    if input.ndim < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, complex_output=complex_output)
+    if complex_output:
+        # import under different name to avoid confusion with shift parameter
+        from scipy.ndimage._interpolation import shift as _shift
+
+        kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+        _shift(input.real, shift, output=output.real, cval=np.real(cval), **kwargs)
+        _shift(input.imag, shift, output=output.imag, cval=np.imag(cval), **kwargs)
+        return output
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    mode = _ni_support._extend_mode_to_code(mode)
+    shift = _ni_support._normalize_sequence(shift, input.ndim)
+    shift = [-ii for ii in shift]
+    shift = np.asarray(shift, dtype=np.float64)
+    if not shift.flags.contiguous:
+        shift = shift.copy()
+    _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval,
+                         npad, False)
+    return output
+
+
+@docfiller
+def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0,
+         prefilter=True, *, grid_mode=False):
+    """
+    Zoom an array.
+
+    The array is zoomed using spline interpolation of the requested order.
+
+    Parameters
+    ----------
+    %(input)s
+    zoom : float or sequence
+        The zoom factor along the axes. If a float, `zoom` is the same for each
+        axis. If a sequence, `zoom` should contain one value for each axis.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+    grid_mode : bool, optional
+        If False, the distance from the pixel centers is zoomed. Otherwise, the
+        distance including the full pixel extent is used. For example, a 1d
+        signal of length 5 is considered to have length 4 when `grid_mode` is
+        False, but length 5 when `grid_mode` is True. See the following
+        visual illustration:
+
+        .. code-block:: text
+
+                | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 |
+                     |<-------------------------------------->|
+                                        vs.
+                |<----------------------------------------------->|
+
+        The starting point of the arrow in the diagram above corresponds to
+        coordinate location 0 in each mode.
+
+    Returns
+    -------
+    zoom : ndarray
+        The zoomed input.
+
+    Notes
+    -----
+    For complex-valued `input`, this function zooms the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(121)  # left side
+    >>> ax2 = fig.add_subplot(122)  # right side
+    >>> ascent = datasets.ascent()
+    >>> result = ndimage.zoom(ascent, 3.0)
+    >>> ax1.imshow(ascent, vmin=0, vmax=255)
+    >>> ax2.imshow(result, vmin=0, vmax=255)
+    >>> plt.show()
+
+    >>> print(ascent.shape)
+    (512, 512)
+
+    >>> print(result.shape)
+    (1536, 1536)
+    """
+    if order < 0 or order > 5:
+        raise RuntimeError('spline order not supported')
+    input = np.asarray(input)
+    if input.ndim < 1:
+        raise RuntimeError('input and output rank must be > 0')
+    zoom = _ni_support._normalize_sequence(zoom, input.ndim)
+    output_shape = tuple(
+            [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)])
+    complex_output = np.iscomplexobj(input)
+    output = _ni_support._get_output(output, input, shape=output_shape,
+                                     complex_output=complex_output)
+    if complex_output:
+        # import under different name to avoid confusion with zoom parameter
+        from scipy.ndimage._interpolation import zoom as _zoom
+
+        kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+        _zoom(input.real, zoom, output=output.real, cval=np.real(cval), **kwargs)
+        _zoom(input.imag, zoom, output=output.imag, cval=np.imag(cval), **kwargs)
+        return output
+    if prefilter and order > 1:
+        padded, npad = _prepad_for_spline_filter(input, mode, cval)
+        filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+    else:
+        npad = 0
+        filtered = input
+    if grid_mode:
+        # warn about modes that may have surprising behavior
+        suggest_mode = None
+        if mode == 'constant':
+            suggest_mode = 'grid-constant'
+        elif mode == 'wrap':
+            suggest_mode = 'grid-wrap'
+        if suggest_mode is not None:
+            warnings.warn(
+                (f"It is recommended to use mode = {suggest_mode} instead of {mode} "
+                 f"when grid_mode is True."),
+                stacklevel=2
+            )
+    mode = _ni_support._extend_mode_to_code(mode)
+
+    zoom_div = np.array(output_shape)
+    zoom_nominator = np.array(input.shape)
+    if not grid_mode:
+        zoom_div -= 1
+        zoom_nominator -= 1
+
+    # Zooming to infinite values is unpredictable, so just choose
+    # zoom factor 1 instead
+    zoom = np.divide(zoom_nominator, zoom_div,
+                     out=np.ones_like(input.shape, dtype=np.float64),
+                     where=zoom_div != 0)
+    zoom = np.ascontiguousarray(zoom)
+    _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval, npad,
+                         grid_mode)
+    return output
+
+
+@docfiller
+def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=3,
+           mode='constant', cval=0.0, prefilter=True):
+    """
+    Rotate an array.
+
+    The array is rotated in the plane defined by the two axes given by the
+    `axes` parameter using spline interpolation of the requested order.
+
+    Parameters
+    ----------
+    %(input)s
+    angle : float
+        The rotation angle in degrees.
+    axes : tuple of 2 ints, optional
+        The two axes that define the plane of rotation. Default is the first
+        two axes.
+    reshape : bool, optional
+        If `reshape` is true, the output shape is adapted so that the input
+        array is contained completely in the output. Default is True.
+    %(output)s
+    order : int, optional
+        The order of the spline interpolation, default is 3.
+        The order has to be in the range 0-5.
+    %(mode_interp_constant)s
+    %(cval)s
+    %(prefilter)s
+
+    Returns
+    -------
+    rotate : ndarray
+        The rotated input.
+
+    Notes
+    -----
+    For complex-valued `input`, this function rotates the real and imaginary
+    components independently.
+
+    .. versionadded:: 1.6.0
+        Complex-valued support added.
+
+    Examples
+    --------
+    >>> from scipy import ndimage, datasets
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure(figsize=(10, 3))
+    >>> ax1, ax2, ax3 = fig.subplots(1, 3)
+    >>> img = datasets.ascent()
+    >>> img_45 = ndimage.rotate(img, 45, reshape=False)
+    >>> full_img_45 = ndimage.rotate(img, 45, reshape=True)
+    >>> ax1.imshow(img, cmap='gray')
+    >>> ax1.set_axis_off()
+    >>> ax2.imshow(img_45, cmap='gray')
+    >>> ax2.set_axis_off()
+    >>> ax3.imshow(full_img_45, cmap='gray')
+    >>> ax3.set_axis_off()
+    >>> fig.set_layout_engine('tight')
+    >>> plt.show()
+    >>> print(img.shape)
+    (512, 512)
+    >>> print(img_45.shape)
+    (512, 512)
+    >>> print(full_img_45.shape)
+    (724, 724)
+
+    """
+    input_arr = np.asarray(input)
+    ndim = input_arr.ndim
+
+    if ndim < 2:
+        raise ValueError('input array should be at least 2D')
+
+    axes = list(axes)
+
+    if len(axes) != 2:
+        raise ValueError('axes should contain exactly two values')
+
+    if not all([float(ax).is_integer() for ax in axes]):
+        raise ValueError('axes should contain only integer values')
+
+    if axes[0] < 0:
+        axes[0] += ndim
+    if axes[1] < 0:
+        axes[1] += ndim
+    if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim:
+        raise ValueError('invalid rotation plane specified')
+
+    axes.sort()
+
+    c, s = special.cosdg(angle), special.sindg(angle)
+
+    rot_matrix = np.array([[c, s],
+                           [-s, c]])
+
+    img_shape = np.asarray(input_arr.shape)
+    in_plane_shape = img_shape[axes]
+    if reshape:
+        # Compute transformed input bounds
+        iy, ix = in_plane_shape
+        out_bounds = rot_matrix @ [[0, 0, iy, iy],
+                                   [0, ix, 0, ix]]
+        # Compute the shape of the transformed input plane
+        out_plane_shape = (np.ptp(out_bounds, axis=1) + 0.5).astype(int)
+    else:
+        out_plane_shape = img_shape[axes]
+
+    out_center = rot_matrix @ ((out_plane_shape - 1) / 2)
+    in_center = (in_plane_shape - 1) / 2
+    offset = in_center - out_center
+
+    output_shape = img_shape
+    output_shape[axes] = out_plane_shape
+    output_shape = tuple(output_shape)
+
+    complex_output = np.iscomplexobj(input_arr)
+    output = _ni_support._get_output(output, input_arr, shape=output_shape,
+                                     complex_output=complex_output)
+
+    if ndim <= 2:
+        affine_transform(input_arr, rot_matrix, offset, output_shape, output,
+                         order, mode, cval, prefilter)
+    else:
+        # If ndim > 2, the rotation is applied over all the planes
+        # parallel to axes
+        planes_coord = itertools.product(
+            *[[slice(None)] if ax in axes else range(img_shape[ax])
+              for ax in range(ndim)])
+
+        out_plane_shape = tuple(out_plane_shape)
+
+        for coordinates in planes_coord:
+            ia = input_arr[coordinates]
+            oa = output[coordinates]
+            affine_transform(ia, rot_matrix, offset, out_plane_shape,
+                             oa, order, mode, cval, prefilter)
+
+    return output
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_measurements.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..67ec12870ccf1dfe52624da05787b197542a0253
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_measurements.py
@@ -0,0 +1,1687 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+#    copyright notice, this list of conditions and the following
+#    disclaimer in the documentation and/or other materials provided
+#    with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+#    products derived from this software without specific prior
+#    written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import numpy as np
+from . import _ni_support
+from . import _ni_label
+from . import _nd_image
+from . import _morphology
+
+__all__ = ['label', 'find_objects', 'labeled_comprehension', 'sum', 'mean',
+           'variance', 'standard_deviation', 'minimum', 'maximum', 'median',
+           'minimum_position', 'maximum_position', 'extrema', 'center_of_mass',
+           'histogram', 'watershed_ift', 'sum_labels', 'value_indices']
+
+
+def label(input, structure=None, output=None):
+    """
+    Label features in an array.
+
+    Parameters
+    ----------
+    input : array_like
+        An array-like object to be labeled. Any non-zero values in `input` are
+        counted as features and zero values are considered the background.
+    structure : array_like, optional
+        A structuring element that defines feature connections.
+        `structure` must be centrosymmetric
+        (see Notes).
+        If no structuring element is provided,
+        one is automatically generated with a squared connectivity equal to
+        one.  That is, for a 2-D `input` array, the default structuring element
+        is::
+
+            [[0,1,0],
+             [1,1,1],
+             [0,1,0]]
+
+    output : (None, data-type, array_like), optional
+        If `output` is a data type, it specifies the type of the resulting
+        labeled feature array.
+        If `output` is an array-like object, then `output` will be updated
+        with the labeled features from this function.  This function can
+        operate in-place, by passing output=input.
+        Note that the output must be able to store the largest label, or this
+        function will raise an Exception.
+
+    Returns
+    -------
+    label : ndarray or int
+        An integer ndarray where each unique feature in `input` has a unique
+        label in the returned array.
+    num_features : int
+        How many objects were found.
+
+        If `output` is None, this function returns a tuple of
+        (`labeled_array`, `num_features`).
+
+        If `output` is a ndarray, then it will be updated with values in
+        `labeled_array` and only `num_features` will be returned by this
+        function.
+
+    See Also
+    --------
+    find_objects : generate a list of slices for the labeled features (or
+                   objects); useful for finding features' position or
+                   dimensions
+
+    Notes
+    -----
+    A centrosymmetric matrix is a matrix that is symmetric about the center.
+    See [1]_ for more information.
+
+    The `structure` matrix must be centrosymmetric to ensure
+    two-way connections.
+    For instance, if the `structure` matrix is not centrosymmetric
+    and is defined as::
+
+        [[0,1,0],
+         [1,1,0],
+         [0,0,0]]
+
+    and the `input` is::
+
+        [[1,2],
+         [0,3]]
+
+    then the structure matrix would indicate the
+    entry 2 in the input is connected to 1,
+    but 1 is not connected to 2.
+
+    References
+    ----------
+    .. [1] James R. Weaver, "Centrosymmetric (cross-symmetric)
+       matrices, their basic properties, eigenvalues, and
+       eigenvectors." The American Mathematical Monthly 92.10
+       (1985): 711-717.
+
+    Examples
+    --------
+    Create an image with some features, then label it using the default
+    (cross-shaped) structuring element:
+
+    >>> from scipy.ndimage import label, generate_binary_structure
+    >>> import numpy as np
+    >>> a = np.array([[0,0,1,1,0,0],
+    ...               [0,0,0,1,0,0],
+    ...               [1,1,0,0,1,0],
+    ...               [0,0,0,1,0,0]])
+    >>> labeled_array, num_features = label(a)
+
+    Each of the 4 features are labeled with a different integer:
+
+    >>> num_features
+    4
+    >>> labeled_array
+    array([[0, 0, 1, 1, 0, 0],
+           [0, 0, 0, 1, 0, 0],
+           [2, 2, 0, 0, 3, 0],
+           [0, 0, 0, 4, 0, 0]], dtype=int32)
+
+    Generate a structuring element that will consider features connected even
+    if they touch diagonally:
+
+    >>> s = generate_binary_structure(2,2)
+
+    or,
+
+    >>> s = [[1,1,1],
+    ...      [1,1,1],
+    ...      [1,1,1]]
+
+    Label the image using the new structuring element:
+
+    >>> labeled_array, num_features = label(a, structure=s)
+
+    Show the 2 labeled features (note that features 1, 3, and 4 from above are
+    now considered a single feature):
+
+    >>> num_features
+    2
+    >>> labeled_array
+    array([[0, 0, 1, 1, 0, 0],
+           [0, 0, 0, 1, 0, 0],
+           [2, 2, 0, 0, 1, 0],
+           [0, 0, 0, 1, 0, 0]], dtype=int32)
+
+    """
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    if structure is None:
+        structure = _morphology.generate_binary_structure(input.ndim, 1)
+    structure = np.asarray(structure, dtype=bool)
+    if structure.ndim != input.ndim:
+        raise RuntimeError('structure and input must have equal rank')
+    for ii in structure.shape:
+        if ii != 3:
+            raise ValueError('structure dimensions must be equal to 3')
+
+    # Use 32 bits if it's large enough for this image.
+    # _ni_label.label() needs two entries for background and
+    # foreground tracking
+    need_64bits = input.size >= (2**31 - 2)
+
+    if isinstance(output, np.ndarray):
+        if output.shape != input.shape:
+            raise ValueError("output shape not correct")
+        caller_provided_output = True
+    else:
+        caller_provided_output = False
+        if output is None:
+            output = np.empty(input.shape, np.intp if need_64bits else np.int32)
+        else:
+            output = np.empty(input.shape, output)
+
+    # handle scalars, 0-D arrays
+    if input.ndim == 0 or input.size == 0:
+        if input.ndim == 0:
+            # scalar
+            maxlabel = 1 if (input != 0) else 0
+            output[...] = maxlabel
+        else:
+            # 0-D
+            maxlabel = 0
+        if caller_provided_output:
+            return maxlabel
+        else:
+            return output, maxlabel
+
+    try:
+        max_label = _ni_label._label(input, structure, output)
+    except _ni_label.NeedMoreBits as e:
+        # Make another attempt with enough bits, then try to cast to the
+        # new type.
+        tmp_output = np.empty(input.shape, np.intp if need_64bits else np.int32)
+        max_label = _ni_label._label(input, structure, tmp_output)
+        output[...] = tmp_output[...]
+        if not np.all(output == tmp_output):
+            # refuse to return bad results
+            raise RuntimeError(
+                "insufficient bit-depth in requested output type"
+            ) from e
+
+    if caller_provided_output:
+        # result was written in-place
+        return max_label
+    else:
+        return output, max_label
+
+
+def find_objects(input, max_label=0):
+    """
+    Find objects in a labeled array.
+
+    Parameters
+    ----------
+    input : ndarray of ints
+        Array containing objects defined by different labels. Labels with
+        value 0 are ignored.
+    max_label : int, optional
+        Maximum label to be searched for in `input`. If max_label is not
+        given, the positions of all objects are returned.
+
+    Returns
+    -------
+    object_slices : list of tuples
+        A list of tuples, with each tuple containing N slices (with N the
+        dimension of the input array). Slices correspond to the minimal
+        parallelepiped that contains the object. If a number is missing,
+        None is returned instead of a slice. The label ``l`` corresponds to
+        the index ``l-1`` in the returned list.
+
+    See Also
+    --------
+    label, center_of_mass
+
+    Notes
+    -----
+    This function is very useful for isolating a volume of interest inside
+    a 3-D array, that cannot be "seen through".
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((6,6), dtype=int)
+    >>> a[2:4, 2:4] = 1
+    >>> a[4, 4] = 1
+    >>> a[:2, :3] = 2
+    >>> a[0, 5] = 3
+    >>> a
+    array([[2, 2, 2, 0, 0, 3],
+           [2, 2, 2, 0, 0, 0],
+           [0, 0, 1, 1, 0, 0],
+           [0, 0, 1, 1, 0, 0],
+           [0, 0, 0, 0, 1, 0],
+           [0, 0, 0, 0, 0, 0]])
+    >>> ndimage.find_objects(a)
+    [(slice(2, 5, None), slice(2, 5, None)),
+     (slice(0, 2, None), slice(0, 3, None)),
+     (slice(0, 1, None), slice(5, 6, None))]
+    >>> ndimage.find_objects(a, max_label=2)
+    [(slice(2, 5, None), slice(2, 5, None)), (slice(0, 2, None), slice(0, 3, None))]
+    >>> ndimage.find_objects(a == 1, max_label=2)
+    [(slice(2, 5, None), slice(2, 5, None)), None]
+
+    >>> loc = ndimage.find_objects(a)[0]
+    >>> a[loc]
+    array([[1, 1, 0],
+           [1, 1, 0],
+           [0, 0, 1]])
+
+    """
+    input = np.asarray(input)
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+
+    if max_label < 1:
+        max_label = input.max()
+
+    return _nd_image.find_objects(input, max_label)
+
+
+def value_indices(arr, *, ignore_value=None):
+    """
+    Find indices of each distinct value in given array.
+
+    Parameters
+    ----------
+    arr : ndarray of ints
+        Array containing integer values.
+    ignore_value : int, optional
+        This value will be ignored in searching the `arr` array. If not
+        given, all values found will be included in output. Default
+        is None.
+
+    Returns
+    -------
+    indices : dictionary
+        A Python dictionary of array indices for each distinct value. The
+        dictionary is keyed by the distinct values, the entries are array
+        index tuples covering all occurrences of the value within the
+        array.
+
+        This dictionary can occupy significant memory, usually several times
+        the size of the input array.
+
+    See Also
+    --------
+    label, maximum, median, minimum_position, extrema, sum, mean, variance,
+    standard_deviation, numpy.where, numpy.unique
+
+    Notes
+    -----
+    For a small array with few distinct values, one might use
+    `numpy.unique()` to find all possible values, and ``(arr == val)`` to
+    locate each value within that array. However, for large arrays,
+    with many distinct values, this can become extremely inefficient,
+    as locating each value would require a new search through the entire
+    array. Using this function, there is essentially one search, with
+    the indices saved for all distinct values.
+
+    This is useful when matching a categorical image (e.g. a segmentation
+    or classification) to an associated image of other data, allowing
+    any per-class statistic(s) to then be calculated. Provides a
+    more flexible alternative to functions like ``scipy.ndimage.mean()``
+    and ``scipy.ndimage.variance()``.
+
+    Some other closely related functionality, with different strengths and
+    weaknesses, can also be found in ``scipy.stats.binned_statistic()`` and
+    the `scikit-image `_ function
+    ``skimage.measure.regionprops()``.
+
+    Note for IDL users: this provides functionality equivalent to IDL's
+    REVERSE_INDICES option (as per the IDL documentation for the
+    `HISTOGRAM `_
+    function).
+
+    .. versionadded:: 1.10.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import ndimage
+    >>> a = np.zeros((6, 6), dtype=int)
+    >>> a[2:4, 2:4] = 1
+    >>> a[4, 4] = 1
+    >>> a[:2, :3] = 2
+    >>> a[0, 5] = 3
+    >>> a
+    array([[2, 2, 2, 0, 0, 3],
+           [2, 2, 2, 0, 0, 0],
+           [0, 0, 1, 1, 0, 0],
+           [0, 0, 1, 1, 0, 0],
+           [0, 0, 0, 0, 1, 0],
+           [0, 0, 0, 0, 0, 0]])
+    >>> val_indices = ndimage.value_indices(a)
+
+    The dictionary `val_indices` will have an entry for each distinct
+    value in the input array.
+
+    >>> val_indices.keys()
+    dict_keys([np.int64(0), np.int64(1), np.int64(2), np.int64(3)])
+
+    The entry for each value is an index tuple, locating the elements
+    with that value.
+
+    >>> ndx1 = val_indices[1]
+    >>> ndx1
+    (array([2, 2, 3, 3, 4]), array([2, 3, 2, 3, 4]))
+
+    This can be used to index into the original array, or any other
+    array with the same shape.
+
+    >>> a[ndx1]
+    array([1, 1, 1, 1, 1])
+
+    If the zeros were to be ignored, then the resulting dictionary
+    would no longer have an entry for zero.
+
+    >>> val_indices = ndimage.value_indices(a, ignore_value=0)
+    >>> val_indices.keys()
+    dict_keys([np.int64(1), np.int64(2), np.int64(3)])
+
+    """
+    # Cope with ignore_value being None, without too much extra complexity
+    # in the C code. If not None, the value is passed in as a numpy array
+    # with the same dtype as arr.
+    arr = np.asarray(arr)
+    ignore_value_arr = np.zeros((1,), dtype=arr.dtype)
+    ignoreIsNone = (ignore_value is None)
+    if not ignoreIsNone:
+        ignore_value_arr[0] = ignore_value_arr.dtype.type(ignore_value)
+
+    val_indices = _nd_image.value_indices(arr, ignoreIsNone, ignore_value_arr)
+    return val_indices
+
+
+def labeled_comprehension(input, labels, index, func, out_dtype, default,
+                          pass_positions=False):
+    """
+    Roughly equivalent to [func(input[labels == i]) for i in index].
+
+    Sequentially applies an arbitrary function (that works on array_like input)
+    to subsets of an N-D image array specified by `labels` and `index`.
+    The option exists to provide the function with positional parameters as the
+    second argument.
+
+    Parameters
+    ----------
+    input : array_like
+        Data from which to select `labels` to process.
+    labels : array_like or None
+        Labels to objects in `input`.
+        If not None, array must be same shape as `input`.
+        If None, `func` is applied to raveled `input`.
+    index : int, sequence of ints or None
+        Subset of `labels` to which to apply `func`.
+        If a scalar, a single value is returned.
+        If None, `func` is applied to all non-zero values of `labels`.
+    func : callable
+        Python function to apply to `labels` from `input`.
+    out_dtype : dtype
+        Dtype to use for `result`.
+    default : int, float or None
+        Default return value when a element of `index` does not exist
+        in `labels`.
+    pass_positions : bool, optional
+        If True, pass linear indices to `func` as a second argument.
+        Default is False.
+
+    Returns
+    -------
+    result : ndarray
+        Result of applying `func` to each of `labels` to `input` in `index`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> from scipy import ndimage
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> lbls = np.arange(1, nlbl+1)
+    >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0)
+    array([ 2.75,  5.5 ,  6.  ])
+
+    Falling back to `default`:
+
+    >>> lbls = np.arange(1, nlbl+2)
+    >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1)
+    array([ 2.75,  5.5 ,  6.  , -1.  ])
+
+    Passing positions:
+
+    >>> def fn(val, pos):
+    ...     print("fn says: %s : %s" % (val, pos))
+    ...     return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum())
+    ...
+    >>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True)
+    fn says: [1 2 5 3] : [0 1 4 5]
+    fn says: [4 7] : [ 7 11]
+    fn says: [9 3] : [12 13]
+    array([ 11.,  11., -12.,   0.])
+
+    """
+
+    as_scalar = np.isscalar(index)
+    input = np.asarray(input)
+
+    if pass_positions:
+        positions = np.arange(input.size).reshape(input.shape)
+
+    if labels is None:
+        if index is not None:
+            raise ValueError("index without defined labels")
+        if not pass_positions:
+            return func(input.ravel())
+        else:
+            return func(input.ravel(), positions.ravel())
+
+    labels = np.asarray(labels)
+
+    try:
+        input, labels = np.broadcast_arrays(input, labels)
+    except ValueError as e:
+        raise ValueError("input and labels must have the same shape "
+                            "(excepting dimensions with width 1)") from e
+
+    if index is None:
+        if not pass_positions:
+            return func(input[labels > 0])
+        else:
+            return func(input[labels > 0], positions[labels > 0])
+
+    index = np.atleast_1d(index)
+    if np.any(index.astype(labels.dtype).astype(index.dtype) != index):
+        raise ValueError(f"Cannot convert index values from <{index.dtype}> to "
+                         f"<{labels.dtype}> (labels' type) without loss of precision")
+
+    index = index.astype(labels.dtype)
+
+    # optimization: find min/max in index,
+    # and select those parts of labels, input, and positions
+    lo = index.min()
+    hi = index.max()
+    mask = (labels >= lo) & (labels <= hi)
+
+    # this also ravels the arrays
+    labels = labels[mask]
+    input = input[mask]
+    if pass_positions:
+        positions = positions[mask]
+
+    # sort everything by labels
+    label_order = labels.argsort()
+    labels = labels[label_order]
+    input = input[label_order]
+    if pass_positions:
+        positions = positions[label_order]
+
+    index_order = index.argsort()
+    sorted_index = index[index_order]
+
+    def do_map(inputs, output):
+        """labels must be sorted"""
+        nidx = sorted_index.size
+
+        # Find boundaries for each stretch of constant labels
+        # This could be faster, but we already paid N log N to sort labels.
+        lo = np.searchsorted(labels, sorted_index, side='left')
+        hi = np.searchsorted(labels, sorted_index, side='right')
+
+        for i, l, h in zip(range(nidx), lo, hi):
+            if l == h:
+                continue
+            output[i] = func(*[inp[l:h] for inp in inputs])
+
+    temp = np.empty(index.shape, out_dtype)
+    temp[:] = default
+    if not pass_positions:
+        do_map([input], temp)
+    else:
+        do_map([input, positions], temp)
+
+    output = np.zeros(index.shape, out_dtype)
+    output[index_order] = temp
+    if as_scalar:
+        output = output[0]
+
+    return output
+
+
+def _safely_castable_to_int(dt):
+    """Test whether the NumPy data type `dt` can be safely cast to an int."""
+    int_size = np.dtype(int).itemsize
+    safe = ((np.issubdtype(dt, np.signedinteger) and dt.itemsize <= int_size) or
+            (np.issubdtype(dt, np.unsignedinteger) and dt.itemsize < int_size))
+    return safe
+
+
+def _stats(input, labels=None, index=None, centered=False):
+    """Count, sum, and optionally compute (sum - centre)^2 of input by label
+
+    Parameters
+    ----------
+    input : array_like, N-D
+        The input data to be analyzed.
+    labels : array_like (N-D), optional
+        The labels of the data in `input`. This array must be broadcast
+        compatible with `input`; typically, it is the same shape as `input`.
+        If `labels` is None, all nonzero values in `input` are treated as
+        the single labeled group.
+    index : label or sequence of labels, optional
+        These are the labels of the groups for which the stats are computed.
+        If `index` is None, the stats are computed for the single group where
+        `labels` is greater than 0.
+    centered : bool, optional
+        If True, the centered sum of squares for each labeled group is
+        also returned. Default is False.
+
+    Returns
+    -------
+    counts : int or ndarray of ints
+        The number of elements in each labeled group.
+    sums : scalar or ndarray of scalars
+        The sums of the values in each labeled group.
+    sums_c : scalar or ndarray of scalars, optional
+        The sums of mean-centered squares of the values in each labeled group.
+        This is only returned if `centered` is True.
+
+    """
+    def single_group(vals):
+        if centered:
+            vals_c = vals - vals.mean()
+            return vals.size, vals.sum(), (vals_c * vals_c.conjugate()).sum()
+        else:
+            return vals.size, vals.sum()
+
+    input = np.asarray(input)
+    if labels is None:
+        return single_group(input)
+
+    # ensure input and labels match sizes
+    input, labels = np.broadcast_arrays(input, labels)
+
+    if index is None:
+        return single_group(input[labels > 0])
+
+    if np.isscalar(index):
+        return single_group(input[labels == index])
+
+    def _sum_centered(labels):
+        # `labels` is expected to be an ndarray with the same shape as `input`.
+        # It must contain the label indices (which are not necessarily the labels
+        # themselves).
+        means = sums / counts
+        centered_input = input - means[labels]
+        # bincount expects 1-D inputs, so we ravel the arguments.
+        bc = np.bincount(labels.ravel(),
+                              weights=(centered_input *
+                                       centered_input.conjugate()).ravel())
+        return bc
+
+    # Remap labels to unique integers if necessary, or if the largest
+    # label is larger than the number of values.
+
+    if (not _safely_castable_to_int(labels.dtype) or
+            labels.min() < 0 or labels.max() > labels.size):
+        # Use np.unique to generate the label indices.  `new_labels` will
+        # be 1-D, but it should be interpreted as the flattened N-D array of
+        # label indices.
+        unique_labels, new_labels = np.unique(labels, return_inverse=True)
+        new_labels = np.reshape(new_labels, (-1,))  # flatten, since it may be >1-D
+        counts = np.bincount(new_labels)
+        sums = np.bincount(new_labels, weights=input.ravel())
+        if centered:
+            # Compute the sum of the mean-centered squares.
+            # We must reshape new_labels to the N-D shape of `input` before
+            # passing it _sum_centered.
+            sums_c = _sum_centered(new_labels.reshape(labels.shape))
+        idxs = np.searchsorted(unique_labels, index)
+        # make all of idxs valid
+        idxs[idxs >= unique_labels.size] = 0
+        found = (unique_labels[idxs] == index)
+    else:
+        # labels are an integer type allowed by bincount, and there aren't too
+        # many, so call bincount directly.
+        counts = np.bincount(labels.ravel())
+        sums = np.bincount(labels.ravel(), weights=input.ravel())
+        if centered:
+            sums_c = _sum_centered(labels)
+        # make sure all index values are valid
+        idxs = np.asanyarray(index, np.int_).copy()
+        found = (idxs >= 0) & (idxs < counts.size)
+        idxs[~found] = 0
+
+    counts = counts[idxs]
+    counts[~found] = 0
+    sums = sums[idxs]
+    sums[~found] = 0
+
+    if not centered:
+        return (counts, sums)
+    else:
+        sums_c = sums_c[idxs]
+        sums_c[~found] = 0
+        return (counts, sums, sums_c)
+
+
+def sum(input, labels=None, index=None):
+    """
+    Calculate the sum of the values of the array.
+
+    Notes
+    -----
+    This is an alias for `ndimage.sum_labels` kept for backwards compatibility
+    reasons, for new code please prefer `sum_labels`.  See the `sum_labels`
+    docstring for more details.
+
+    """
+    return sum_labels(input, labels, index)
+
+
+def sum_labels(input, labels=None, index=None):
+    """
+    Calculate the sum of the values of the array.
+
+    Parameters
+    ----------
+    input : array_like
+        Values of `input` inside the regions defined by `labels`
+        are summed together.
+    labels : array_like of ints, optional
+        Assign labels to the values of the array. Has to have the same shape as
+        `input`.
+    index : array_like, optional
+        A single label number or a sequence of label numbers of
+        the objects to be measured.
+
+    Returns
+    -------
+    sum : ndarray or scalar
+        An array of the sums of values of `input` inside the regions defined
+        by `labels` with the same shape as `index`. If 'index' is None or scalar,
+        a scalar is returned.
+
+    See Also
+    --------
+    mean, median
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> input =  [0,1,2,3]
+    >>> labels = [1,1,2,2]
+    >>> ndimage.sum_labels(input, labels, index=[1,2])
+    [1.0, 5.0]
+    >>> ndimage.sum_labels(input, labels, index=1)
+    1
+    >>> ndimage.sum_labels(input, labels)
+    6
+
+
+    """
+    count, sum = _stats(input, labels, index)
+    return sum
+
+
+def mean(input, labels=None, index=None):
+    """
+    Calculate the mean of the values of an array at labels.
+
+    Parameters
+    ----------
+    input : array_like
+        Array on which to compute the mean of elements over distinct
+        regions.
+    labels : array_like, optional
+        Array of labels of same shape, or broadcastable to the same shape as
+        `input`. All elements sharing the same label form one region over
+        which the mean of the elements is computed.
+    index : int or sequence of ints, optional
+        Labels of the objects over which the mean is to be computed.
+        Default is None, in which case the mean for all values where label is
+        greater than 0 is calculated.
+
+    Returns
+    -------
+    out : list
+        Sequence of same length as `index`, with the mean of the different
+        regions labeled by the labels in `index`.
+
+    See Also
+    --------
+    variance, standard_deviation, minimum, maximum, sum, label
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.arange(25).reshape((5,5))
+    >>> labels = np.zeros_like(a)
+    >>> labels[3:5,3:5] = 1
+    >>> index = np.unique(labels)
+    >>> labels
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 1],
+           [0, 0, 0, 1, 1]])
+    >>> index
+    array([0, 1])
+    >>> ndimage.mean(a, labels=labels, index=index)
+    [10.285714285714286, 21.0]
+
+    """
+
+    count, sum = _stats(input, labels, index)
+    return sum / np.asanyarray(count).astype(np.float64)
+
+
+def variance(input, labels=None, index=None):
+    """
+    Calculate the variance of the values of an N-D image array, optionally at
+    specified sub-regions.
+
+    Parameters
+    ----------
+    input : array_like
+        Nd-image data to process.
+    labels : array_like, optional
+        Labels defining sub-regions in `input`.
+        If not None, must be same shape as `input`.
+    index : int or sequence of ints, optional
+        `labels` to include in output.  If None (default), all values where
+        `labels` is non-zero are used.
+
+    Returns
+    -------
+    variance : float or ndarray
+        Values of variance, for each sub-region if `labels` and `index` are
+        specified.
+
+    See Also
+    --------
+    label, standard_deviation, maximum, minimum, extrema
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> from scipy import ndimage
+    >>> ndimage.variance(a)
+    7.609375
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> ndimage.variance(a, lbl, index=np.arange(1, nlbl+1))
+    array([ 2.1875,  2.25  ,  9.    ])
+
+    If no index is given, all non-zero `labels` are processed:
+
+    >>> ndimage.variance(a, lbl)
+    6.1875
+
+    """
+    count, sum, sum_c_sq = _stats(input, labels, index, centered=True)
+    return sum_c_sq / np.asanyarray(count).astype(float)
+
+
+def standard_deviation(input, labels=None, index=None):
+    """
+    Calculate the standard deviation of the values of an N-D image array,
+    optionally at specified sub-regions.
+
+    Parameters
+    ----------
+    input : array_like
+        N-D image data to process.
+    labels : array_like, optional
+        Labels to identify sub-regions in `input`.
+        If not None, must be same shape as `input`.
+    index : int or sequence of ints, optional
+        `labels` to include in output. If None (default), all values where
+        `labels` is non-zero are used.
+
+    Returns
+    -------
+    standard_deviation : float or ndarray
+        Values of standard deviation, for each sub-region if `labels` and
+        `index` are specified.
+
+    See Also
+    --------
+    label, variance, maximum, minimum, extrema
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> from scipy import ndimage
+    >>> ndimage.standard_deviation(a)
+    2.7585095613392387
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> ndimage.standard_deviation(a, lbl, index=np.arange(1, nlbl+1))
+    array([ 1.479,  1.5  ,  3.   ])
+
+    If no index is given, non-zero `labels` are processed:
+
+    >>> ndimage.standard_deviation(a, lbl)
+    2.4874685927665499
+
+    """
+    return np.sqrt(variance(input, labels, index))
+
+
+def _select(input, labels=None, index=None, find_min=False, find_max=False,
+            find_min_positions=False, find_max_positions=False,
+            find_median=False):
+    """Returns min, max, or both, plus their positions (if requested), and
+    median."""
+
+    input = np.asanyarray(input)
+
+    find_positions = find_min_positions or find_max_positions
+    positions = None
+    if find_positions:
+        positions = np.arange(input.size).reshape(input.shape)
+
+    def single_group(vals, positions):
+        result = []
+        if find_min:
+            result += [vals.min()]
+        if find_min_positions:
+            result += [positions[vals == vals.min()][0]]
+        if find_max:
+            result += [vals.max()]
+        if find_max_positions:
+            result += [positions[vals == vals.max()][0]]
+        if find_median:
+            result += [np.median(vals)]
+        return result
+
+    if labels is None:
+        return single_group(input, positions)
+
+    # ensure input and labels match sizes
+    input, labels = np.broadcast_arrays(input, labels)
+
+    if index is None:
+        mask = (labels > 0)
+        masked_positions = None
+        if find_positions:
+            masked_positions = positions[mask]
+        return single_group(input[mask], masked_positions)
+
+    if np.isscalar(index):
+        mask = (labels == index)
+        masked_positions = None
+        if find_positions:
+            masked_positions = positions[mask]
+        return single_group(input[mask], masked_positions)
+
+    index = np.asarray(index)
+
+    # remap labels to unique integers if necessary, or if the largest
+    # label is larger than the number of values.
+    if (not _safely_castable_to_int(labels.dtype) or
+            labels.min() < 0 or labels.max() > labels.size):
+        # remap labels, and indexes
+        unique_labels, labels = np.unique(labels, return_inverse=True)
+        idxs = np.searchsorted(unique_labels, index)
+
+        # make all of idxs valid
+        idxs[idxs >= unique_labels.size] = 0
+        found = (unique_labels[idxs] == index)
+    else:
+        # labels are an integer type, and there aren't too many
+        idxs = np.asanyarray(index, np.int_).copy()
+        found = (idxs >= 0) & (idxs <= labels.max())
+
+    idxs[~ found] = labels.max() + 1
+
+    if find_median:
+        order = np.lexsort((input.ravel(), labels.ravel()))
+    else:
+        order = input.ravel().argsort()
+    input = input.ravel()[order]
+    labels = labels.ravel()[order]
+    if find_positions:
+        positions = positions.ravel()[order]
+
+    result = []
+    if find_min:
+        mins = np.zeros(labels.max() + 2, input.dtype)
+        mins[labels[::-1]] = input[::-1]
+        result += [mins[idxs]]
+    if find_min_positions:
+        minpos = np.zeros(labels.max() + 2, int)
+        minpos[labels[::-1]] = positions[::-1]
+        result += [minpos[idxs]]
+    if find_max:
+        maxs = np.zeros(labels.max() + 2, input.dtype)
+        maxs[labels] = input
+        result += [maxs[idxs]]
+    if find_max_positions:
+        maxpos = np.zeros(labels.max() + 2, int)
+        maxpos[labels] = positions
+        result += [maxpos[idxs]]
+    if find_median:
+        locs = np.arange(len(labels))
+        lo = np.zeros(labels.max() + 2, np.int_)
+        lo[labels[::-1]] = locs[::-1]
+        hi = np.zeros(labels.max() + 2, np.int_)
+        hi[labels] = locs
+        lo = lo[idxs]
+        hi = hi[idxs]
+        # lo is an index to the lowest value in input for each label,
+        # hi is an index to the largest value.
+        # move them to be either the same ((hi - lo) % 2 == 0) or next
+        # to each other ((hi - lo) % 2 == 1), then average.
+        step = (hi - lo) // 2
+        lo += step
+        hi -= step
+        if (np.issubdtype(input.dtype, np.integer)
+                or np.issubdtype(input.dtype, np.bool_)):
+            # avoid integer overflow or boolean addition (gh-12836)
+            result += [(input[lo].astype('d') + input[hi].astype('d')) / 2.0]
+        else:
+            result += [(input[lo] + input[hi]) / 2.0]
+
+    return result
+
+
+def minimum(input, labels=None, index=None):
+    """
+    Calculate the minimum of the values of an array over labeled regions.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values. For each region specified by `labels`, the
+        minimal values of `input` over the region is computed.
+    labels : array_like, optional
+        An array_like of integers marking different regions over which the
+        minimum value of `input` is to be computed. `labels` must have the
+        same shape as `input`. If `labels` is not specified, the minimum
+        over the whole array is returned.
+    index : array_like, optional
+        A list of region labels that are taken into account for computing the
+        minima. If index is None, the minimum over all elements where `labels`
+        is non-zero is returned.
+
+    Returns
+    -------
+    minimum : float or list of floats
+        List of minima of `input` over the regions determined by `labels` and
+        whose index is in `index`. If `index` or `labels` are not specified, a
+        float is returned: the minimal value of `input` if `labels` is None,
+        and the minimal value of elements where `labels` is greater than zero
+        if `index` is None.
+
+    See Also
+    --------
+    label, maximum, median, minimum_position, extrema, sum, mean, variance,
+    standard_deviation
+
+    Notes
+    -----
+    The function returns a Python list and not a NumPy array, use
+    `np.array` to convert the list to an array.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> labels, labels_nb = ndimage.label(a)
+    >>> labels
+    array([[1, 1, 0, 0],
+           [1, 1, 0, 2],
+           [0, 0, 0, 2],
+           [3, 3, 0, 0]], dtype=int32)
+    >>> ndimage.minimum(a, labels=labels, index=np.arange(1, labels_nb + 1))
+    [1, 4, 3]
+    >>> ndimage.minimum(a)
+    0
+    >>> ndimage.minimum(a, labels=labels)
+    1
+
+    """
+    return _select(input, labels, index, find_min=True)[0]
+
+
+def maximum(input, labels=None, index=None):
+    """
+    Calculate the maximum of the values of an array over labeled regions.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values. For each region specified by `labels`, the
+        maximal values of `input` over the region is computed.
+    labels : array_like, optional
+        An array of integers marking different regions over which the
+        maximum value of `input` is to be computed. `labels` must have the
+        same shape as `input`. If `labels` is not specified, the maximum
+        over the whole array is returned.
+    index : array_like, optional
+        A list of region labels that are taken into account for computing the
+        maxima. If index is None, the maximum over all elements where `labels`
+        is non-zero is returned.
+
+    Returns
+    -------
+    output : float or list of floats
+        List of maxima of `input` over the regions determined by `labels` and
+        whose index is in `index`. If `index` or `labels` are not specified, a
+        float is returned: the maximal value of `input` if `labels` is None,
+        and the maximal value of elements where `labels` is greater than zero
+        if `index` is None.
+
+    See Also
+    --------
+    label, minimum, median, maximum_position, extrema, sum, mean, variance,
+    standard_deviation
+
+    Notes
+    -----
+    The function returns a Python list and not a NumPy array, use
+    `np.array` to convert the list to an array.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.arange(16).reshape((4,4))
+    >>> a
+    array([[ 0,  1,  2,  3],
+           [ 4,  5,  6,  7],
+           [ 8,  9, 10, 11],
+           [12, 13, 14, 15]])
+    >>> labels = np.zeros_like(a)
+    >>> labels[:2,:2] = 1
+    >>> labels[2:, 1:3] = 2
+    >>> labels
+    array([[1, 1, 0, 0],
+           [1, 1, 0, 0],
+           [0, 2, 2, 0],
+           [0, 2, 2, 0]])
+    >>> from scipy import ndimage
+    >>> ndimage.maximum(a)
+    15
+    >>> ndimage.maximum(a, labels=labels, index=[1,2])
+    [5, 14]
+    >>> ndimage.maximum(a, labels=labels)
+    14
+
+    >>> b = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> labels, labels_nb = ndimage.label(b)
+    >>> labels
+    array([[1, 1, 0, 0],
+           [1, 1, 0, 2],
+           [0, 0, 0, 2],
+           [3, 3, 0, 0]], dtype=int32)
+    >>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1))
+    [5, 7, 9]
+
+    """
+    return _select(input, labels, index, find_max=True)[0]
+
+
+def median(input, labels=None, index=None):
+    """
+    Calculate the median of the values of an array over labeled regions.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values. For each region specified by `labels`, the
+        median value of `input` over the region is computed.
+    labels : array_like, optional
+        An array_like of integers marking different regions over which the
+        median value of `input` is to be computed. `labels` must have the
+        same shape as `input`. If `labels` is not specified, the median
+        over the whole array is returned.
+    index : array_like, optional
+        A list of region labels that are taken into account for computing the
+        medians. If index is None, the median over all elements where `labels`
+        is non-zero is returned.
+
+    Returns
+    -------
+    median : float or list of floats
+        List of medians of `input` over the regions determined by `labels` and
+        whose index is in `index`. If `index` or `labels` are not specified, a
+        float is returned: the median value of `input` if `labels` is None,
+        and the median value of elements where `labels` is greater than zero
+        if `index` is None.
+
+    See Also
+    --------
+    label, minimum, maximum, extrema, sum, mean, variance, standard_deviation
+
+    Notes
+    -----
+    The function returns a Python list and not a NumPy array, use
+    `np.array` to convert the list to an array.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 1],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> labels, labels_nb = ndimage.label(a)
+    >>> labels
+    array([[1, 1, 0, 2],
+           [1, 1, 0, 2],
+           [0, 0, 0, 2],
+           [3, 3, 0, 0]], dtype=int32)
+    >>> ndimage.median(a, labels=labels, index=np.arange(1, labels_nb + 1))
+    [2.5, 4.0, 6.0]
+    >>> ndimage.median(a)
+    1.0
+    >>> ndimage.median(a, labels=labels)
+    3.0
+
+    """
+    return _select(input, labels, index, find_median=True)[0]
+
+
+def minimum_position(input, labels=None, index=None):
+    """
+    Find the positions of the minimums of the values of an array at labels.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values.
+    labels : array_like, optional
+        An array of integers marking different regions over which the
+        position of the minimum value of `input` is to be computed.
+        `labels` must have the same shape as `input`. If `labels` is not
+        specified, the location of the first minimum over the whole
+        array is returned.
+
+        The `labels` argument only works when `index` is specified.
+    index : array_like, optional
+        A list of region labels that are taken into account for finding the
+        location of the minima. If `index` is None, the ``first`` minimum
+        over all elements where `labels` is non-zero is returned.
+
+        The `index` argument only works when `labels` is specified.
+
+    Returns
+    -------
+    output : list of tuples of ints
+        Tuple of ints or list of tuples of ints that specify the location
+        of minima of `input` over the regions determined by `labels` and
+        whose index is in `index`.
+
+        If `index` or `labels` are not specified, a tuple of ints is
+        returned specifying the location of the first minimal value of `input`.
+
+    See Also
+    --------
+    label, minimum, median, maximum_position, extrema, sum, mean, variance,
+    standard_deviation
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[10, 20, 30],
+    ...               [40, 80, 100],
+    ...               [1, 100, 200]])
+    >>> b = np.array([[1, 2, 0, 1],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+
+    >>> from scipy import ndimage
+
+    >>> ndimage.minimum_position(a)
+    (2, 0)
+    >>> ndimage.minimum_position(b)
+    (0, 2)
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> label, pos = ndimage.label(a)
+    >>> ndimage.minimum_position(a, label, index=np.arange(1, pos+1))
+    [(2, 0)]
+
+    >>> label, pos = ndimage.label(b)
+    >>> ndimage.minimum_position(b, label, index=np.arange(1, pos+1))
+    [(0, 0), (0, 3), (3, 1)]
+
+    """
+    dims = np.array(np.asarray(input).shape)
+    # see np.unravel_index to understand this line.
+    dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+    result = _select(input, labels, index, find_min_positions=True)[0]
+
+    if np.isscalar(result):
+        return tuple((result // dim_prod) % dims)
+
+    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
+
+
+def maximum_position(input, labels=None, index=None):
+    """
+    Find the positions of the maximums of the values of an array at labels.
+
+    For each region specified by `labels`, the position of the maximum
+    value of `input` within the region is returned.
+
+    Parameters
+    ----------
+    input : array_like
+        Array_like of values.
+    labels : array_like, optional
+        An array of integers marking different regions over which the
+        position of the maximum value of `input` is to be computed.
+        `labels` must have the same shape as `input`. If `labels` is not
+        specified, the location of the first maximum over the whole
+        array is returned.
+
+        The `labels` argument only works when `index` is specified.
+    index : array_like, optional
+        A list of region labels that are taken into account for finding the
+        location of the maxima. If `index` is None, the first maximum
+        over all elements where `labels` is non-zero is returned.
+
+        The `index` argument only works when `labels` is specified.
+
+    Returns
+    -------
+    output : list of tuples of ints
+        List of tuples of ints that specify the location of maxima of
+        `input` over the regions determined by `labels` and whose index
+        is in `index`.
+
+        If `index` or `labels` are not specified, a tuple of ints is
+        returned specifying the location of the ``first`` maximal value
+        of `input`.
+
+    See Also
+    --------
+    label, minimum, median, maximum_position, extrema, sum, mean, variance,
+    standard_deviation
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> ndimage.maximum_position(a)
+    (3, 0)
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> lbl = np.array([[0, 1, 2, 3],
+    ...                 [0, 1, 2, 3],
+    ...                 [0, 1, 2, 3],
+    ...                 [0, 1, 2, 3]])
+    >>> ndimage.maximum_position(a, lbl, 1)
+    (1, 1)
+
+    If no index is given, non-zero `labels` are processed:
+
+    >>> ndimage.maximum_position(a, lbl)
+    (2, 3)
+
+    If there are no maxima, the position of the first element is returned:
+
+    >>> ndimage.maximum_position(a, lbl, 2)
+    (0, 2)
+
+    """
+    dims = np.array(np.asarray(input).shape)
+    # see np.unravel_index to understand this line.
+    dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+    result = _select(input, labels, index, find_max_positions=True)[0]
+
+    if np.isscalar(result):
+        return tuple((result // dim_prod) % dims)
+
+    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
+
+
+def extrema(input, labels=None, index=None):
+    """
+    Calculate the minimums and maximums of the values of an array
+    at labels, along with their positions.
+
+    Parameters
+    ----------
+    input : ndarray
+        N-D image data to process.
+    labels : ndarray, optional
+        Labels of features in input.
+        If not None, must be same shape as `input`.
+    index : int or sequence of ints, optional
+        Labels to include in output.  If None (default), all values where
+        non-zero `labels` are used.
+
+    Returns
+    -------
+    minimums, maximums : int or ndarray
+        Values of minimums and maximums in each feature.
+    min_positions, max_positions : tuple or list of tuples
+        Each tuple gives the N-D coordinates of the corresponding minimum
+        or maximum.
+
+    See Also
+    --------
+    maximum, minimum, maximum_position, minimum_position, center_of_mass
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[1, 2, 0, 0],
+    ...               [5, 3, 0, 4],
+    ...               [0, 0, 0, 7],
+    ...               [9, 3, 0, 0]])
+    >>> from scipy import ndimage
+    >>> ndimage.extrema(a)
+    (0, 9, (0, 2), (3, 0))
+
+    Features to process can be specified using `labels` and `index`:
+
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> ndimage.extrema(a, lbl, index=np.arange(1, nlbl+1))
+    (array([1, 4, 3]),
+     array([5, 7, 9]),
+     [(0, 0), (1, 3), (3, 1)],
+     [(1, 0), (2, 3), (3, 0)])
+
+    If no index is given, non-zero `labels` are processed:
+
+    >>> ndimage.extrema(a, lbl)
+    (1, 9, (0, 0), (3, 0))
+
+    """
+    dims = np.array(np.asarray(input).shape)
+    # see np.unravel_index to understand this line.
+    dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+    minimums, min_positions, maximums, max_positions = _select(input, labels,
+                                                               index,
+                                                               find_min=True,
+                                                               find_max=True,
+                                                               find_min_positions=True,
+                                                               find_max_positions=True)
+
+    if np.isscalar(minimums):
+        return (minimums, maximums, tuple((min_positions // dim_prod) % dims),
+                tuple((max_positions // dim_prod) % dims))
+
+    min_positions = [
+        tuple(v) for v in (min_positions.reshape(-1, 1) // dim_prod) % dims
+    ]
+    max_positions = [
+        tuple(v) for v in (max_positions.reshape(-1, 1) // dim_prod) % dims
+    ]
+
+    return minimums, maximums, min_positions, max_positions
+
+
+def center_of_mass(input, labels=None, index=None):
+    """
+    Calculate the center of mass of the values of an array at labels.
+
+    Parameters
+    ----------
+    input : ndarray
+        Data from which to calculate center-of-mass. The masses can either
+        be positive or negative.
+    labels : ndarray, optional
+        Labels for objects in `input`, as generated by `ndimage.label`.
+        Only used with `index`. Dimensions must be the same as `input`.
+    index : int or sequence of ints, optional
+        Labels for which to calculate centers-of-mass. If not specified,
+        the combined center of mass of all labels greater than zero
+        will be calculated. Only used with `labels`.
+
+    Returns
+    -------
+    center_of_mass : tuple, or list of tuples
+        Coordinates of centers-of-mass.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array(([0,0,0,0],
+    ...               [0,1,1,0],
+    ...               [0,1,1,0],
+    ...               [0,1,1,0]))
+    >>> from scipy import ndimage
+    >>> ndimage.center_of_mass(a)
+    (2.0, 1.5)
+
+    Calculation of multiple objects in an image
+
+    >>> b = np.array(([0,1,1,0],
+    ...               [0,1,0,0],
+    ...               [0,0,0,0],
+    ...               [0,0,1,1],
+    ...               [0,0,1,1]))
+    >>> lbl = ndimage.label(b)[0]
+    >>> ndimage.center_of_mass(b, lbl, [1,2])
+    [(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)]
+
+    Negative masses are also accepted, which can occur for example when
+    bias is removed from measured data due to random noise.
+
+    >>> c = np.array(([-1,0,0,0],
+    ...               [0,-1,-1,0],
+    ...               [0,1,-1,0],
+    ...               [0,1,1,0]))
+    >>> ndimage.center_of_mass(c)
+    (-4.0, 1.0)
+
+    If there are division by zero issues, the function does not raise an
+    error but rather issues a RuntimeWarning before returning inf and/or NaN.
+
+    >>> d = np.array([-1, 1])
+    >>> ndimage.center_of_mass(d)
+    (inf,)
+    """
+    input = np.asarray(input)
+    normalizer = sum_labels(input, labels, index)
+    grids = np.ogrid[[slice(0, i) for i in input.shape]]
+
+    results = [sum_labels(input * grids[dir].astype(float), labels, index) / normalizer
+               for dir in range(input.ndim)]
+
+    if np.isscalar(results[0]):
+        return tuple(results)
+
+    return [tuple(v) for v in np.array(results).T]
+
+
+def histogram(input, min, max, bins, labels=None, index=None):
+    """
+    Calculate the histogram of the values of an array, optionally at labels.
+
+    Histogram calculates the frequency of values in an array within bins
+    determined by `min`, `max`, and `bins`. The `labels` and `index`
+    keywords can limit the scope of the histogram to specified sub-regions
+    within the array.
+
+    Parameters
+    ----------
+    input : array_like
+        Data for which to calculate histogram.
+    min, max : int
+        Minimum and maximum values of range of histogram bins.
+    bins : int
+        Number of bins.
+    labels : array_like, optional
+        Labels for objects in `input`.
+        If not None, must be same shape as `input`.
+    index : int or sequence of ints, optional
+        Label or labels for which to calculate histogram. If None, all values
+        where label is greater than zero are used
+
+    Returns
+    -------
+    hist : ndarray
+        Histogram counts.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[ 0.    ,  0.2146,  0.5962,  0.    ],
+    ...               [ 0.    ,  0.7778,  0.    ,  0.    ],
+    ...               [ 0.    ,  0.    ,  0.    ,  0.    ],
+    ...               [ 0.    ,  0.    ,  0.7181,  0.2787],
+    ...               [ 0.    ,  0.    ,  0.6573,  0.3094]])
+    >>> from scipy import ndimage
+    >>> ndimage.histogram(a, 0, 1, 10)
+    array([13,  0,  2,  1,  0,  1,  1,  2,  0,  0])
+
+    With labels and no indices, non-zero elements are counted:
+
+    >>> lbl, nlbl = ndimage.label(a)
+    >>> ndimage.histogram(a, 0, 1, 10, lbl)
+    array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0])
+
+    Indices can be used to count only certain objects:
+
+    >>> ndimage.histogram(a, 0, 1, 10, lbl, 2)
+    array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])
+
+    """
+    _bins = np.linspace(min, max, bins + 1)
+
+    def _hist(vals):
+        return np.histogram(vals, _bins)[0]
+
+    return labeled_comprehension(input, labels, index, _hist, object, None,
+                                 pass_positions=False)
+
+
+def watershed_ift(input, markers, structure=None, output=None):
+    """
+    Apply watershed from markers using image foresting transform algorithm.
+
+    Parameters
+    ----------
+    input : array_like
+        Input.
+    markers : array_like
+        Markers are points within each watershed that form the beginning
+        of the process. Negative markers are considered background markers
+        which are processed after the other markers.
+    structure : structure element, optional
+        A structuring element defining the connectivity of the object can be
+        provided. If None, an element is generated with a squared
+        connectivity equal to one.
+    output : ndarray, optional
+        An output array can optionally be provided. The same shape as input.
+
+    Returns
+    -------
+    watershed_ift : ndarray
+        Output.  Same shape as `input`.
+
+    References
+    ----------
+    .. [1] A.X. Falcao, J. Stolfi and R. de Alencar Lotufo, "The image
+           foresting transform: theory, algorithms, and applications",
+           Pattern Analysis and Machine Intelligence, vol. 26, pp. 19-29, 2004.
+
+    """
+    input = np.asarray(input)
+    if input.dtype.type not in [np.uint8, np.uint16]:
+        raise TypeError('only 8 and 16 unsigned inputs are supported')
+
+    if structure is None:
+        structure = _morphology.generate_binary_structure(input.ndim, 1)
+    structure = np.asarray(structure, dtype=bool)
+    if structure.ndim != input.ndim:
+        raise RuntimeError('structure and input must have equal rank')
+    for ii in structure.shape:
+        if ii != 3:
+            raise RuntimeError('structure dimensions must be equal to 3')
+
+    if not structure.flags.contiguous:
+        structure = structure.copy()
+    markers = np.asarray(markers)
+    if input.shape != markers.shape:
+        raise RuntimeError('input and markers must have equal shape')
+
+    integral_types = [np.int8,
+                      np.int16,
+                      np.int32,
+                      np.int64,
+                      np.intc,
+                      np.intp]
+
+    if markers.dtype.type not in integral_types:
+        raise RuntimeError('marker should be of integer type')
+
+    if isinstance(output, np.ndarray):
+        if output.dtype.type not in integral_types:
+            raise RuntimeError('output should be of integer type')
+    else:
+        output = markers.dtype
+
+    output = _ni_support._get_output(output, input)
+    _nd_image.watershed_ift(input, markers, structure, output)
+    return output
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_morphology.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..12972c09a7cd5de0ca059814281fb9d210fbd395
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_morphology.py
@@ -0,0 +1,2629 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+#    copyright notice, this list of conditions and the following
+#    disclaimer in the documentation and/or other materials provided
+#    with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+#    products derived from this software without specific prior
+#    written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import warnings
+import operator
+
+import numpy as np
+from . import _ni_support
+from . import _nd_image
+from . import _filters
+
+__all__ = ['iterate_structure', 'generate_binary_structure', 'binary_erosion',
+           'binary_dilation', 'binary_opening', 'binary_closing',
+           'binary_hit_or_miss', 'binary_propagation', 'binary_fill_holes',
+           'grey_erosion', 'grey_dilation', 'grey_opening', 'grey_closing',
+           'morphological_gradient', 'morphological_laplace', 'white_tophat',
+           'black_tophat', 'distance_transform_bf', 'distance_transform_cdt',
+           'distance_transform_edt']
+
+
+def _center_is_true(structure, origin):
+    structure = np.asarray(structure)
+    coor = tuple([oo + ss // 2 for ss, oo in zip(structure.shape,
+                                                 origin)])
+    return bool(structure[coor])
+
+
+def iterate_structure(structure, iterations, origin=None):
+    """
+    Iterate a structure by dilating it with itself.
+
+    Parameters
+    ----------
+    structure : array_like
+       Structuring element (an array of bools, for example), to be dilated with
+       itself.
+    iterations : int
+       number of dilations performed on the structure with itself
+    origin : optional
+        If origin is None, only the iterated structure is returned. If
+        not, a tuple of the iterated structure and the modified origin is
+        returned.
+
+    Returns
+    -------
+    iterate_structure : ndarray of bools
+        A new structuring element obtained by dilating `structure`
+        (`iterations` - 1) times with itself.
+
+    See Also
+    --------
+    generate_binary_structure
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> struct = ndimage.generate_binary_structure(2, 1)
+    >>> struct.astype(int)
+    array([[0, 1, 0],
+           [1, 1, 1],
+           [0, 1, 0]])
+    >>> ndimage.iterate_structure(struct, 2).astype(int)
+    array([[0, 0, 1, 0, 0],
+           [0, 1, 1, 1, 0],
+           [1, 1, 1, 1, 1],
+           [0, 1, 1, 1, 0],
+           [0, 0, 1, 0, 0]])
+    >>> ndimage.iterate_structure(struct, 3).astype(int)
+    array([[0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [1, 1, 1, 1, 1, 1, 1],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 1, 0, 0, 0]])
+
+    """
+    structure = np.asarray(structure)
+    if iterations < 2:
+        return structure.copy()
+    ni = iterations - 1
+    shape = [ii + ni * (ii - 1) for ii in structure.shape]
+    pos = [ni * (structure.shape[ii] // 2) for ii in range(len(shape))]
+    slc = tuple(slice(pos[ii], pos[ii] + structure.shape[ii], None)
+                for ii in range(len(shape)))
+    out = np.zeros(shape, bool)
+    out[slc] = structure != 0
+    out = binary_dilation(out, structure, iterations=ni)
+    if origin is None:
+        return out
+    else:
+        origin = _ni_support._normalize_sequence(origin, structure.ndim)
+        origin = [iterations * o for o in origin]
+        return out, origin
+
+
+def generate_binary_structure(rank, connectivity):
+    """
+    Generate a binary structure for binary morphological operations.
+
+    Parameters
+    ----------
+    rank : int
+         Number of dimensions of the array to which the structuring element
+         will be applied, as returned by `np.ndim`.
+    connectivity : int
+         `connectivity` determines which elements of the output array belong
+         to the structure, i.e., are considered as neighbors of the central
+         element. Elements up to a squared distance of `connectivity` from
+         the center are considered neighbors. `connectivity` may range from 1
+         (no diagonal elements are neighbors) to `rank` (all elements are
+         neighbors).
+
+    Returns
+    -------
+    output : ndarray of bools
+         Structuring element which may be used for binary morphological
+         operations, with `rank` dimensions and all dimensions equal to 3.
+
+    See Also
+    --------
+    iterate_structure, binary_dilation, binary_erosion
+
+    Notes
+    -----
+    `generate_binary_structure` can only create structuring elements with
+    dimensions equal to 3, i.e., minimal dimensions. For larger structuring
+    elements, that are useful e.g., for eroding large objects, one may either
+    use `iterate_structure`, or create directly custom arrays with
+    numpy functions such as `numpy.ones`.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> struct = ndimage.generate_binary_structure(2, 1)
+    >>> struct
+    array([[False,  True, False],
+           [ True,  True,  True],
+           [False,  True, False]], dtype=bool)
+    >>> a = np.zeros((5,5))
+    >>> a[2, 2] = 1
+    >>> a
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype)
+    >>> b
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype)
+    array([[ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 1.,  1.,  1.,  1.,  1.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.]])
+    >>> struct = ndimage.generate_binary_structure(2, 2)
+    >>> struct
+    array([[ True,  True,  True],
+           [ True,  True,  True],
+           [ True,  True,  True]], dtype=bool)
+    >>> struct = ndimage.generate_binary_structure(3, 1)
+    >>> struct # no diagonal elements
+    array([[[False, False, False],
+            [False,  True, False],
+            [False, False, False]],
+           [[False,  True, False],
+            [ True,  True,  True],
+            [False,  True, False]],
+           [[False, False, False],
+            [False,  True, False],
+            [False, False, False]]], dtype=bool)
+
+    """
+    if connectivity < 1:
+        connectivity = 1
+    if rank < 1:
+        return np.array(True, dtype=bool)
+    output = np.fabs(np.indices([3] * rank) - 1)
+    output = np.add.reduce(output, 0)
+    return output <= connectivity
+
+
+def _binary_erosion(input, structure, iterations, mask, output,
+                    border_value, origin, invert, brute_force, axes):
+    try:
+        iterations = operator.index(iterations)
+    except TypeError as e:
+        raise TypeError('iterations parameter should be an integer') from e
+
+    input = np.asarray(input)
+    ndim = input.ndim
+    if np.iscomplexobj(input):
+        raise TypeError('Complex type not supported')
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure is None:
+        structure = generate_binary_structure(num_axes, 1)
+    else:
+        structure = np.asarray(structure, dtype=bool)
+    if ndim > num_axes:
+        structure = _filters._expand_footprint(ndim, axes, structure,
+                                               footprint_name="structure")
+
+    if structure.ndim != input.ndim:
+        raise RuntimeError('structure and input must have same dimensionality')
+    if not structure.flags.contiguous:
+        structure = structure.copy()
+    if structure.size < 1:
+        raise RuntimeError('structure must not be empty')
+    if mask is not None:
+        mask = np.asarray(mask)
+        if mask.shape != input.shape:
+            raise RuntimeError('mask and input must have equal sizes')
+    origin = _ni_support._normalize_sequence(origin, num_axes)
+    origin = _filters._expand_origin(ndim, axes, origin)
+    cit = _center_is_true(structure, origin)
+    if isinstance(output, np.ndarray):
+        if np.iscomplexobj(output):
+            raise TypeError('Complex output type not supported')
+    else:
+        output = bool
+    output = _ni_support._get_output(output, input)
+    temp_needed = np.may_share_memory(input, output)
+    if temp_needed:
+        # input and output arrays cannot share memory
+        temp = output
+        output = _ni_support._get_output(output.dtype, input)
+    if iterations == 1:
+        _nd_image.binary_erosion(input, structure, mask, output,
+                                 border_value, origin, invert, cit, 0)
+    elif cit and not brute_force:
+        changed, coordinate_list = _nd_image.binary_erosion(
+            input, structure, mask, output,
+            border_value, origin, invert, cit, 1)
+        structure = structure[tuple([slice(None, None, -1)] *
+                                    structure.ndim)]
+        for ii in range(len(origin)):
+            origin[ii] = -origin[ii]
+            if not structure.shape[ii] & 1:
+                origin[ii] -= 1
+        if mask is not None:
+            mask = np.asarray(mask, dtype=np.int8)
+        if not structure.flags.contiguous:
+            structure = structure.copy()
+        _nd_image.binary_erosion2(output, structure, mask, iterations - 1,
+                                  origin, invert, coordinate_list)
+    else:
+        tmp_in = np.empty_like(input, dtype=bool)
+        tmp_out = output
+        if iterations >= 1 and not iterations & 1:
+            tmp_in, tmp_out = tmp_out, tmp_in
+        changed = _nd_image.binary_erosion(
+            input, structure, mask, tmp_out,
+            border_value, origin, invert, cit, 0)
+        ii = 1
+        while ii < iterations or (iterations < 1 and changed):
+            tmp_in, tmp_out = tmp_out, tmp_in
+            changed = _nd_image.binary_erosion(
+                tmp_in, structure, mask, tmp_out,
+                border_value, origin, invert, cit, 0)
+            ii += 1
+    if temp_needed:
+        temp[...] = output
+        output = temp
+    return output
+
+
+def binary_erosion(input, structure=None, iterations=1, mask=None, output=None,
+                   border_value=0, origin=0, brute_force=False, *, axes=None):
+    """
+    Multidimensional binary erosion with a given structuring element.
+
+    Binary erosion is a mathematical morphology operation used for image
+    processing.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary image to be eroded. Non-zero (True) elements form
+        the subset to be eroded.
+    structure : array_like, optional
+        Structuring element used for the erosion. Non-zero elements are
+        considered True. If no structuring element is provided, an element
+        is generated with a square connectivity equal to one.
+    iterations : int, optional
+        The erosion is repeated `iterations` times (one, by default).
+        If iterations is less than 1, the erosion is repeated until the
+        result does not change anymore.
+    mask : array_like, optional
+        If a mask is given, only those elements with a True value at
+        the corresponding mask element are modified at each iteration.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    brute_force : boolean, optional
+        Memory condition: if False, only the pixels whose value was changed in
+        the last iteration are tracked as candidates to be updated (eroded) in
+        the current iteration; if True all pixels are considered as candidates
+        for erosion, regardless of what happened in the previous iteration.
+        False by default.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_erosion : ndarray of bools
+        Erosion of the input by the structuring element.
+
+    See Also
+    --------
+    grey_erosion, binary_dilation, binary_closing, binary_opening,
+    generate_binary_structure
+
+    Notes
+    -----
+    Erosion [1]_ is a mathematical morphology operation [2]_ that uses a
+    structuring element for shrinking the shapes in an image. The binary
+    erosion of an image by a structuring element is the locus of the points
+    where a superimposition of the structuring element centered on the point
+    is entirely contained in the set of non-zero elements of the image.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[1:6, 2:5] = 1
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.binary_erosion(a).astype(a.dtype)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> #Erosion removes objects smaller than the structure
+    >>> ndimage.binary_erosion(a, structure=np.ones((5,5))).astype(a.dtype)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+
+    """
+    return _binary_erosion(input, structure, iterations, mask,
+                           output, border_value, origin, 0, brute_force, axes)
+
+
+def binary_dilation(input, structure=None, iterations=1, mask=None,
+                    output=None, border_value=0, origin=0,
+                    brute_force=False, *, axes=None):
+    """
+    Multidimensional binary dilation with the given structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary array_like to be dilated. Non-zero (True) elements form
+        the subset to be dilated.
+    structure : array_like, optional
+        Structuring element used for the dilation. Non-zero elements are
+        considered True. If no structuring element is provided an element
+        is generated with a square connectivity equal to one.
+    iterations : int, optional
+        The dilation is repeated `iterations` times (one, by default).
+        If iterations is less than 1, the dilation is repeated until the
+        result does not change anymore. Only an integer of iterations is
+        accepted.
+    mask : array_like, optional
+        If a mask is given, only those elements with a True value at
+        the corresponding mask element are modified at each iteration.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    brute_force : boolean, optional
+        Memory condition: if False, only the pixels whose value was changed in
+        the last iteration are tracked as candidates to be updated (dilated)
+        in the current iteration; if True all pixels are considered as
+        candidates for dilation, regardless of what happened in the previous
+        iteration. False by default.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_dilation : ndarray of bools
+        Dilation of the input by the structuring element.
+
+    See Also
+    --------
+    grey_dilation, binary_erosion, binary_closing, binary_opening,
+    generate_binary_structure
+
+    Notes
+    -----
+    Dilation [1]_ is a mathematical morphology operation [2]_ that uses a
+    structuring element for expanding the shapes in an image. The binary
+    dilation of an image by a structuring element is the locus of the points
+    covered by the structuring element, when its center lies within the
+    non-zero points of the image.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((5, 5))
+    >>> a[2, 2] = 1
+    >>> a
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> ndimage.binary_dilation(a)
+    array([[False, False, False, False, False],
+           [False, False,  True, False, False],
+           [False,  True,  True,  True, False],
+           [False, False,  True, False, False],
+           [False, False, False, False, False]], dtype=bool)
+    >>> ndimage.binary_dilation(a).astype(a.dtype)
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> # 3x3 structuring element with connectivity 1, used by default
+    >>> struct1 = ndimage.generate_binary_structure(2, 1)
+    >>> struct1
+    array([[False,  True, False],
+           [ True,  True,  True],
+           [False,  True, False]], dtype=bool)
+    >>> # 3x3 structuring element with connectivity 2
+    >>> struct2 = ndimage.generate_binary_structure(2, 2)
+    >>> struct2
+    array([[ True,  True,  True],
+           [ True,  True,  True],
+           [ True,  True,  True]], dtype=bool)
+    >>> ndimage.binary_dilation(a, structure=struct1).astype(a.dtype)
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> ndimage.binary_dilation(a, structure=struct2).astype(a.dtype)
+    array([[ 0.,  0.,  0.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  0.,  0.,  0.]])
+    >>> ndimage.binary_dilation(a, structure=struct1,\\
+    ... iterations=2).astype(a.dtype)
+    array([[ 0.,  0.,  1.,  0.,  0.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 1.,  1.,  1.,  1.,  1.],
+           [ 0.,  1.,  1.,  1.,  0.],
+           [ 0.,  0.,  1.,  0.,  0.]])
+
+    """
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure is None:
+        structure = generate_binary_structure(num_axes, 1)
+    origin = _ni_support._normalize_sequence(origin, num_axes)
+    structure = np.asarray(structure)
+    structure = structure[tuple([slice(None, None, -1)] *
+                                structure.ndim)]
+    for ii in range(len(origin)):
+        origin[ii] = -origin[ii]
+        if not structure.shape[ii] & 1:
+            origin[ii] -= 1
+
+    return _binary_erosion(input, structure, iterations, mask,
+                           output, border_value, origin, 1, brute_force, axes)
+
+
+def binary_opening(input, structure=None, iterations=1, output=None,
+                   origin=0, mask=None, border_value=0, brute_force=False, *,
+                   axes=None):
+    """
+    Multidimensional binary opening with the given structuring element.
+
+    The *opening* of an input image by a structuring element is the
+    *dilation* of the *erosion* of the image by the structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary array_like to be opened. Non-zero (True) elements form
+        the subset to be opened.
+    structure : array_like, optional
+        Structuring element used for the opening. Non-zero elements are
+        considered True. If no structuring element is provided an element
+        is generated with a square connectivity equal to one (i.e., only
+        nearest neighbors are connected to the center, diagonally-connected
+        elements are not considered neighbors).
+    iterations : int, optional
+        The erosion step of the opening, then the dilation step are each
+        repeated `iterations` times (one, by default). If `iterations` is
+        less than 1, each operation is repeated until the result does
+        not change anymore. Only an integer of iterations is accepted.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    mask : array_like, optional
+        If a mask is given, only those elements with a True value at
+        the corresponding mask element are modified at each iteration.
+
+        .. versionadded:: 1.1.0
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+
+        .. versionadded:: 1.1.0
+    brute_force : boolean, optional
+        Memory condition: if False, only the pixels whose value was changed in
+        the last iteration are tracked as candidates to be updated in the
+        current iteration; if true all pixels are considered as candidates for
+        update, regardless of what happened in the previous iteration.
+        False by default.
+
+        .. versionadded:: 1.1.0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_opening : ndarray of bools
+        Opening of the input by the structuring element.
+
+    See Also
+    --------
+    grey_opening, binary_closing, binary_erosion, binary_dilation,
+    generate_binary_structure
+
+    Notes
+    -----
+    *Opening* [1]_ is a mathematical morphology operation [2]_ that
+    consists in the succession of an erosion and a dilation of the
+    input with the same structuring element. Opening, therefore, removes
+    objects smaller than the structuring element.
+
+    Together with *closing* (`binary_closing`), opening can be used for
+    noise removal.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Opening_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((5,5), dtype=int)
+    >>> a[1:4, 1:4] = 1; a[4, 4] = 1
+    >>> a
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 1]])
+    >>> # Opening removes small objects
+    >>> ndimage.binary_opening(a, structure=np.ones((3,3))).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Opening can also smooth corners
+    >>> ndimage.binary_opening(a).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Opening is the dilation of the erosion of the input
+    >>> ndimage.binary_erosion(a).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0]])
+    >>> ndimage.binary_dilation(ndimage.binary_erosion(a)).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure is None:
+        structure = generate_binary_structure(num_axes, 1)
+
+    tmp = binary_erosion(input, structure, iterations, mask, None,
+                         border_value, origin, brute_force, axes=axes)
+    return binary_dilation(tmp, structure, iterations, mask, output,
+                           border_value, origin, brute_force, axes=axes)
+
+
+def binary_closing(input, structure=None, iterations=1, output=None,
+                   origin=0, mask=None, border_value=0, brute_force=False, *,
+                   axes=None):
+    """
+    Multidimensional binary closing with the given structuring element.
+
+    The *closing* of an input image by a structuring element is the
+    *erosion* of the *dilation* of the image by the structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary array_like to be closed. Non-zero (True) elements form
+        the subset to be closed.
+    structure : array_like, optional
+        Structuring element used for the closing. Non-zero elements are
+        considered True. If no structuring element is provided an element
+        is generated with a square connectivity equal to one (i.e., only
+        nearest neighbors are connected to the center, diagonally-connected
+        elements are not considered neighbors).
+    iterations : int, optional
+        The dilation step of the closing, then the erosion step are each
+        repeated `iterations` times (one, by default). If iterations is
+        less than 1, each operations is repeated until the result does
+        not change anymore. Only an integer of iterations is accepted.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    mask : array_like, optional
+        If a mask is given, only those elements with a True value at
+        the corresponding mask element are modified at each iteration.
+
+        .. versionadded:: 1.1.0
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+
+        .. versionadded:: 1.1.0
+    brute_force : boolean, optional
+        Memory condition: if False, only the pixels whose value was changed in
+        the last iteration are tracked as candidates to be updated in the
+        current iteration; if true al pixels are considered as candidates for
+        update, regardless of what happened in the previous iteration.
+        False by default.
+
+        .. versionadded:: 1.1.0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_closing : ndarray of bools
+        Closing of the input by the structuring element.
+
+    See Also
+    --------
+    grey_closing, binary_opening, binary_dilation, binary_erosion,
+    generate_binary_structure
+
+    Notes
+    -----
+    *Closing* [1]_ is a mathematical morphology operation [2]_ that
+    consists in the succession of a dilation and an erosion of the
+    input with the same structuring element. Closing therefore fills
+    holes smaller than the structuring element.
+
+    Together with *opening* (`binary_opening`), closing can be used for
+    noise removal.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Closing_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((5,5), dtype=int)
+    >>> a[1:-1, 1:-1] = 1; a[2,2] = 0
+    >>> a
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 0, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Closing removes small holes
+    >>> ndimage.binary_closing(a).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Closing is the erosion of the dilation of the input
+    >>> ndimage.binary_dilation(a).astype(int)
+    array([[0, 1, 1, 1, 0],
+           [1, 1, 1, 1, 1],
+           [1, 1, 1, 1, 1],
+           [1, 1, 1, 1, 1],
+           [0, 1, 1, 1, 0]])
+    >>> ndimage.binary_erosion(ndimage.binary_dilation(a)).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+
+
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[1:6, 2:5] = 1; a[1:3,3] = 0
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 1, 0, 0],
+           [0, 0, 1, 0, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> # In addition to removing holes, closing can also
+    >>> # coarsen boundaries with fine hollows.
+    >>> ndimage.binary_closing(a).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.binary_closing(a, structure=np.ones((2,2))).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure is None:
+        structure = generate_binary_structure(num_axes, 1)
+
+    tmp = binary_dilation(input, structure, iterations, mask, None,
+                          border_value, origin, brute_force, axes=axes)
+    return binary_erosion(tmp, structure, iterations, mask, output,
+                          border_value, origin, brute_force, axes=axes)
+
+
+def binary_hit_or_miss(input, structure1=None, structure2=None,
+                       output=None, origin1=0, origin2=None, *, axes=None):
+    """
+    Multidimensional binary hit-or-miss transform.
+
+    The hit-or-miss transform finds the locations of a given pattern
+    inside the input image.
+
+    Parameters
+    ----------
+    input : array_like (cast to booleans)
+        Binary image where a pattern is to be detected.
+    structure1 : array_like (cast to booleans), optional
+        Part of the structuring element to be fitted to the foreground
+        (non-zero elements) of `input`. If no value is provided, a
+        structure of square connectivity 1 is chosen.
+    structure2 : array_like (cast to booleans), optional
+        Second part of the structuring element that has to miss completely
+        the foreground. If no value is provided, the complementary of
+        `structure1` is taken.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    origin1 : int or tuple of ints, optional
+        Placement of the first part of the structuring element `structure1`,
+        by default 0 for a centered structure.
+    origin2 : int or tuple of ints, optional
+        Placement of the second part of the structuring element `structure2`,
+        by default 0 for a centered structure. If a value is provided for
+        `origin1` and not for `origin2`, then `origin2` is set to `origin1`.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If `origin1` or `origin2` tuples are provided, their
+        length must match the number of axes.
+
+    Returns
+    -------
+    binary_hit_or_miss : ndarray
+        Hit-or-miss transform of `input` with the given structuring
+        element (`structure1`, `structure2`).
+
+    See Also
+    --------
+    binary_erosion
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Hit-or-miss_transform
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[1, 1] = 1; a[2:4, 2:4] = 1; a[4:6, 4:6] = 1
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 0, 0, 0],
+           [0, 0, 1, 1, 0, 0, 0],
+           [0, 0, 0, 0, 1, 1, 0],
+           [0, 0, 0, 0, 1, 1, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> structure1 = np.array([[1, 0, 0], [0, 1, 1], [0, 1, 1]])
+    >>> structure1
+    array([[1, 0, 0],
+           [0, 1, 1],
+           [0, 1, 1]])
+    >>> # Find the matches of structure1 in the array a
+    >>> ndimage.binary_hit_or_miss(a, structure1=structure1).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> # Change the origin of the filter
+    >>> # origin1=1 is equivalent to origin1=(1,1) here
+    >>> ndimage.binary_hit_or_miss(a, structure1=structure1,\\
+    ... origin1=1).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 1, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    num_axes = len(axes)
+    if structure1 is None:
+        structure1 = generate_binary_structure(num_axes, 1)
+    else:
+        structure1 = np.asarray(structure1)
+    if structure2 is None:
+        structure2 = np.logical_not(structure1)
+    origin1 = _ni_support._normalize_sequence(origin1, num_axes)
+    if origin2 is None:
+        origin2 = origin1
+    else:
+        origin2 = _ni_support._normalize_sequence(origin2, num_axes)
+
+    tmp1 = _binary_erosion(input, structure1, 1, None, None, 0, origin1,
+                           0, False, axes)
+    inplace = isinstance(output, np.ndarray)
+    result = _binary_erosion(input, structure2, 1, None, output, 0,
+                             origin2, 1, False, axes)
+    if inplace:
+        np.logical_not(output, output)
+        np.logical_and(tmp1, output, output)
+    else:
+        np.logical_not(result, result)
+        return np.logical_and(tmp1, result)
+
+
+def binary_propagation(input, structure=None, mask=None,
+                       output=None, border_value=0, origin=0, *, axes=None):
+    """
+    Multidimensional binary propagation with the given structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Binary image to be propagated inside `mask`.
+    structure : array_like, optional
+        Structuring element used in the successive dilations. The output
+        may depend on the structuring element, especially if `mask` has
+        several connex components. If no structuring element is
+        provided, an element is generated with a squared connectivity equal
+        to one.
+    mask : array_like, optional
+        Binary mask defining the region into which `input` is allowed to
+        propagate.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    border_value : int (cast to 0 or 1), optional
+        Value at the border in the output array.
+    origin : int or tuple of ints, optional
+        Placement of the filter, by default 0.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    binary_propagation : ndarray
+        Binary propagation of `input` inside `mask`.
+
+    Notes
+    -----
+    This function is functionally equivalent to calling binary_dilation
+    with the number of iterations less than one: iterative dilation until
+    the result does not change anymore.
+
+    The succession of an erosion and propagation inside the original image
+    can be used instead of an *opening* for deleting small objects while
+    keeping the contours of larger objects untouched.
+
+    References
+    ----------
+    .. [1] http://cmm.ensmp.fr/~serra/cours/pdf/en/ch6en.pdf, slide 15.
+    .. [2] I.T. Young, J.J. Gerbrands, and L.J. van Vliet, "Fundamentals of
+        image processing", 1998
+        ftp://qiftp.tudelft.nl/DIPimage/docs/FIP2.3.pdf
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> input = np.zeros((8, 8), dtype=int)
+    >>> input[2, 2] = 1
+    >>> mask = np.zeros((8, 8), dtype=int)
+    >>> mask[1:4, 1:4] = mask[4, 4]  = mask[6:8, 6:8] = 1
+    >>> input
+    array([[0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0]])
+    >>> mask
+    array([[0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 1, 1],
+           [0, 0, 0, 0, 0, 0, 1, 1]])
+    >>> ndimage.binary_propagation(input, mask=mask).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.binary_propagation(input, mask=mask,\\
+    ... structure=np.ones((3,3))).astype(int)
+    array([[0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0, 0, 0, 0],
+           [0, 0, 0, 0, 1, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0, 0]])
+
+    >>> # Comparison between opening and erosion+propagation
+    >>> a = np.zeros((6,6), dtype=int)
+    >>> a[2:5, 2:5] = 1; a[0, 0] = 1; a[5, 5] = 1
+    >>> a
+    array([[1, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0, 1]])
+    >>> ndimage.binary_opening(a).astype(int)
+    array([[0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0]])
+    >>> b = ndimage.binary_erosion(a)
+    >>> b.astype(int)
+    array([[0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0]])
+    >>> ndimage.binary_propagation(b, mask=a).astype(int)
+    array([[0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0, 0]])
+
+    """
+    return binary_dilation(input, structure, -1, mask, output,
+                           border_value, origin, axes=axes)
+
+
+def binary_fill_holes(input, structure=None, output=None, origin=0, *,
+                      axes=None):
+    """
+    Fill the holes in binary objects.
+
+
+    Parameters
+    ----------
+    input : array_like
+        N-D binary array with holes to be filled
+    structure : array_like, optional
+        Structuring element used in the computation; large-size elements
+        make computations faster but may miss holes separated from the
+        background by thin regions. The default element (with a square
+        connectivity equal to one) yields the intuitive result where all
+        holes in the input have been filled.
+    output : ndarray, optional
+        Array of the same shape as input, into which the output is placed.
+        By default, a new array is created.
+    origin : int, tuple of ints, optional
+        Position of the structuring element.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    out : ndarray
+        Transformation of the initial image `input` where holes have been
+        filled.
+
+    See Also
+    --------
+    binary_dilation, binary_propagation, label
+
+    Notes
+    -----
+    The algorithm used in this function consists in invading the complementary
+    of the shapes in `input` from the outer boundary of the image,
+    using binary dilations. Holes are not connected to the boundary and are
+    therefore not invaded. The result is the complementary subset of the
+    invaded region.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((5, 5), dtype=int)
+    >>> a[1:4, 1:4] = 1
+    >>> a[2,2] = 0
+    >>> a
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 0, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> ndimage.binary_fill_holes(a).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+    >>> # Too big structuring element
+    >>> ndimage.binary_fill_holes(a, structure=np.ones((5,5))).astype(int)
+    array([[0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 0],
+           [0, 1, 0, 1, 0],
+           [0, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+    mask = np.logical_not(input)
+    tmp = np.zeros(mask.shape, bool)
+    inplace = isinstance(output, np.ndarray)
+    if inplace:
+        binary_dilation(tmp, structure, -1, mask, output, 1, origin, axes=axes)
+        np.logical_not(output, output)
+    else:
+        output = binary_dilation(tmp, structure, -1, mask, None, 1,
+                                 origin, axes=axes)
+        np.logical_not(output, output)
+        return output
+
+
+def grey_erosion(input, size=None, footprint=None, structure=None,
+                 output=None, mode="reflect", cval=0.0, origin=0, *,
+                 axes=None):
+    """
+    Calculate a greyscale erosion, using either a structuring element,
+    or a footprint corresponding to a flat structuring element.
+
+    Grayscale erosion is a mathematical morphology operation. For the
+    simple case of a full and flat structuring element, it can be viewed
+    as a minimum filter over a sliding window.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which the grayscale erosion is to be computed.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the grayscale
+        erosion. Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the grayscale erosion. Non-zero values give the set of
+        neighbors of the center over which the minimum is chosen.
+    structure : array of ints, optional
+        Structuring element used for the grayscale erosion. `structure`
+        may be a non-flat structuring element. The `structure` array applies a
+        subtractive offset for each pixel in the neighborhood.
+    output : array, optional
+        An array used for storing the output of the erosion may be provided.
+    mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    output : ndarray
+        Grayscale erosion of `input`.
+
+    See Also
+    --------
+    binary_erosion, grey_dilation, grey_opening, grey_closing
+    generate_binary_structure, minimum_filter
+
+    Notes
+    -----
+    The grayscale erosion of an image input by a structuring element s defined
+    over a domain E is given by:
+
+    (input+s)(x) = min {input(y) - s(x-y), for y in E}
+
+    In particular, for structuring elements defined as
+    s(y) = 0 for y in E, the grayscale erosion computes the minimum of the
+    input image inside a sliding window defined by E.
+
+    Grayscale erosion [1]_ is a *mathematical morphology* operation [2]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Erosion_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[1:6, 1:6] = 3
+    >>> a[4,4] = 2; a[2,3] = 1
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 3, 3, 3, 3, 3, 0],
+           [0, 3, 3, 1, 3, 3, 0],
+           [0, 3, 3, 3, 3, 3, 0],
+           [0, 3, 3, 3, 2, 3, 0],
+           [0, 3, 3, 3, 3, 3, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.grey_erosion(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 3, 2, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> footprint = ndimage.generate_binary_structure(2, 1)
+    >>> footprint
+    array([[False,  True, False],
+           [ True,  True,  True],
+           [False,  True, False]], dtype=bool)
+    >>> # Diagonally-connected elements are not considered neighbors
+    >>> ndimage.grey_erosion(a, footprint=footprint)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 3, 1, 2, 0, 0],
+           [0, 0, 3, 2, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+
+    """
+    if size is None and footprint is None and structure is None:
+        raise ValueError("size, footprint, or structure must be specified")
+
+    return _filters._min_or_max_filter(input, size, footprint, structure,
+                                       output, mode, cval, origin, 1,
+                                       axes=axes)
+
+
+def grey_dilation(input, size=None, footprint=None, structure=None,
+                  output=None, mode="reflect", cval=0.0, origin=0, *,
+                  axes=None):
+    """
+    Calculate a greyscale dilation, using either a structuring element,
+    or a footprint corresponding to a flat structuring element.
+
+    Grayscale dilation is a mathematical morphology operation. For the
+    simple case of a full and flat structuring element, it can be viewed
+    as a maximum filter over a sliding window.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which the grayscale dilation is to be computed.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the grayscale
+        dilation. Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the grayscale dilation. Non-zero values give the set of
+        neighbors of the center over which the maximum is chosen.
+    structure : array of ints, optional
+        Structuring element used for the grayscale dilation. `structure`
+        may be a non-flat structuring element. The `structure` array applies an
+        additive offset for each pixel in the neighborhood.
+    output : array, optional
+        An array used for storing the output of the dilation may be provided.
+    mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    grey_dilation : ndarray
+        Grayscale dilation of `input`.
+
+    See Also
+    --------
+    binary_dilation, grey_erosion, grey_closing, grey_opening
+    generate_binary_structure, maximum_filter
+
+    Notes
+    -----
+    The grayscale dilation of an image input by a structuring element s defined
+    over a domain E is given by:
+
+    (input+s)(x) = max {input(y) + s(x-y), for y in E}
+
+    In particular, for structuring elements defined as
+    s(y) = 0 for y in E, the grayscale dilation computes the maximum of the
+    input image inside a sliding window defined by E.
+
+    Grayscale dilation [1]_ is a *mathematical morphology* operation [2]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Dilation_%28morphology%29
+    .. [2] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[2:5, 2:5] = 1
+    >>> a[4,4] = 2; a[2,3] = 3
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 3, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.grey_dilation(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.grey_dilation(a, footprint=np.ones((3,3)))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> s = ndimage.generate_binary_structure(2,1)
+    >>> s
+    array([[False,  True, False],
+           [ True,  True,  True],
+           [False,  True, False]], dtype=bool)
+    >>> ndimage.grey_dilation(a, footprint=s)
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 3, 1, 0, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 1, 3, 2, 1, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 0, 1, 1, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.grey_dilation(a, size=(3,3), structure=np.ones((3,3)))
+    array([[1, 1, 1, 1, 1, 1, 1],
+           [1, 2, 4, 4, 4, 2, 1],
+           [1, 2, 4, 4, 4, 2, 1],
+           [1, 2, 4, 4, 4, 3, 1],
+           [1, 2, 2, 3, 3, 3, 1],
+           [1, 2, 2, 3, 3, 3, 1],
+           [1, 1, 1, 1, 1, 1, 1]])
+
+    """
+    if size is None and footprint is None and structure is None:
+        raise ValueError("size, footprint, or structure must be specified")
+    if structure is not None:
+        structure = np.asarray(structure)
+        structure = structure[tuple([slice(None, None, -1)] *
+                                    structure.ndim)]
+    if footprint is not None:
+        footprint = np.asarray(footprint)
+        footprint = footprint[tuple([slice(None, None, -1)] *
+                                    footprint.ndim)]
+
+    input = np.asarray(input)
+    axes = _ni_support._check_axes(axes, input.ndim)
+    origin = _ni_support._normalize_sequence(origin, len(axes))
+    for ii in range(len(origin)):
+        origin[ii] = -origin[ii]
+        if footprint is not None:
+            sz = footprint.shape[ii]
+        elif structure is not None:
+            sz = structure.shape[ii]
+        elif np.isscalar(size):
+            sz = size
+        else:
+            sz = size[ii]
+        if not sz & 1:
+            origin[ii] -= 1
+
+    return _filters._min_or_max_filter(input, size, footprint, structure,
+                                       output, mode, cval, origin, 0,
+                                       axes=axes)
+
+
+def grey_opening(input, size=None, footprint=None, structure=None,
+                 output=None, mode="reflect", cval=0.0, origin=0, *,
+                 axes=None):
+    """
+    Multidimensional grayscale opening.
+
+    A grayscale opening consists in the succession of a grayscale erosion,
+    and a grayscale dilation.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which the grayscale opening is to be computed.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the grayscale
+        opening. Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the grayscale opening.
+    structure : array of ints, optional
+        Structuring element used for the grayscale opening. `structure`
+        may be a non-flat structuring element. The `structure` array applies
+        offsets to the pixels in a neighborhood (the offset is additive during
+        dilation and subtractive during erosion).
+    output : array, optional
+        An array used for storing the output of the opening may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    grey_opening : ndarray
+        Result of the grayscale opening of `input` with `structure`.
+
+    See Also
+    --------
+    binary_opening, grey_dilation, grey_erosion, grey_closing
+    generate_binary_structure
+
+    Notes
+    -----
+    The action of a grayscale opening with a flat structuring element amounts
+    to smoothen high local maxima, whereas binary opening erases small objects.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.arange(36).reshape((6,6))
+    >>> a[3, 3] = 50
+    >>> a
+    array([[ 0,  1,  2,  3,  4,  5],
+           [ 6,  7,  8,  9, 10, 11],
+           [12, 13, 14, 15, 16, 17],
+           [18, 19, 20, 50, 22, 23],
+           [24, 25, 26, 27, 28, 29],
+           [30, 31, 32, 33, 34, 35]])
+    >>> ndimage.grey_opening(a, size=(3,3))
+    array([[ 0,  1,  2,  3,  4,  4],
+           [ 6,  7,  8,  9, 10, 10],
+           [12, 13, 14, 15, 16, 16],
+           [18, 19, 20, 22, 22, 22],
+           [24, 25, 26, 27, 28, 28],
+           [24, 25, 26, 27, 28, 28]])
+    >>> # Note that the local maximum a[3,3] has disappeared
+
+    """
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    tmp = grey_erosion(input, size, footprint, structure, None, mode,
+                       cval, origin, axes=axes)
+    return grey_dilation(tmp, size, footprint, structure, output, mode,
+                         cval, origin, axes=axes)
+
+
+def grey_closing(input, size=None, footprint=None, structure=None,
+                 output=None, mode="reflect", cval=0.0, origin=0, *,
+                 axes=None):
+    """
+    Multidimensional grayscale closing.
+
+    A grayscale closing consists in the succession of a grayscale dilation,
+    and a grayscale erosion.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which the grayscale closing is to be computed.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the grayscale
+        closing. Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the grayscale closing.
+    structure : array of ints, optional
+        Structuring element used for the grayscale closing. `structure`
+        may be a non-flat structuring element. The `structure` array applies
+        offsets to the pixels in a neighborhood (the offset is additive during
+        dilation and subtractive during erosion)
+    output : array, optional
+        An array used for storing the output of the closing may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    grey_closing : ndarray
+        Result of the grayscale closing of `input` with `structure`.
+
+    See Also
+    --------
+    binary_closing, grey_dilation, grey_erosion, grey_opening,
+    generate_binary_structure
+
+    Notes
+    -----
+    The action of a grayscale closing with a flat structuring element amounts
+    to smoothen deep local minima, whereas binary closing fills small holes.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.arange(36).reshape((6,6))
+    >>> a[3,3] = 0
+    >>> a
+    array([[ 0,  1,  2,  3,  4,  5],
+           [ 6,  7,  8,  9, 10, 11],
+           [12, 13, 14, 15, 16, 17],
+           [18, 19, 20,  0, 22, 23],
+           [24, 25, 26, 27, 28, 29],
+           [30, 31, 32, 33, 34, 35]])
+    >>> ndimage.grey_closing(a, size=(3,3))
+    array([[ 7,  7,  8,  9, 10, 11],
+           [ 7,  7,  8,  9, 10, 11],
+           [13, 13, 14, 15, 16, 17],
+           [19, 19, 20, 20, 22, 23],
+           [25, 25, 26, 27, 28, 29],
+           [31, 31, 32, 33, 34, 35]])
+    >>> # Note that the local minimum a[3,3] has disappeared
+
+    """
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    tmp = grey_dilation(input, size, footprint, structure, None, mode,
+                        cval, origin, axes=axes)
+    return grey_erosion(tmp, size, footprint, structure, output, mode,
+                        cval, origin, axes=axes)
+
+
+def morphological_gradient(input, size=None, footprint=None, structure=None,
+                           output=None, mode="reflect", cval=0.0, origin=0, *,
+                           axes=None):
+    """
+    Multidimensional morphological gradient.
+
+    The morphological gradient is calculated as the difference between a
+    dilation and an erosion of the input with a given structuring element.
+
+    Parameters
+    ----------
+    input : array_like
+        Array over which to compute the morphlogical gradient.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the mathematical
+        morphology operations. Optional if `footprint` or `structure` is
+        provided. A larger `size` yields a more blurred gradient.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the morphology operations. Larger footprints
+        give a more blurred morphological gradient.
+    structure : array of ints, optional
+        Structuring element used for the morphology operations. `structure` may
+        be a non-flat structuring element. The `structure` array applies
+        offsets to the pixels in a neighborhood (the offset is additive during
+        dilation and subtractive during erosion)
+    output : array, optional
+        An array used for storing the output of the morphological gradient
+        may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    morphological_gradient : ndarray
+        Morphological gradient of `input`.
+
+    See Also
+    --------
+    grey_dilation, grey_erosion, gaussian_gradient_magnitude
+
+    Notes
+    -----
+    For a flat structuring element, the morphological gradient
+    computed at a given point corresponds to the maximal difference
+    between elements of the input among the elements covered by the
+    structuring element centered on the point.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Mathematical_morphology
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[2:5, 2:5] = 1
+    >>> ndimage.morphological_gradient(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 0, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> # The morphological gradient is computed as the difference
+    >>> # between a dilation and an erosion
+    >>> ndimage.grey_dilation(a, size=(3,3)) -\\
+    ...  ndimage.grey_erosion(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 0, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 1, 1, 1, 1, 1, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> a = np.zeros((7,7), dtype=int)
+    >>> a[2:5, 2:5] = 1
+    >>> a[4,4] = 2; a[2,3] = 3
+    >>> a
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 1, 3, 1, 0, 0],
+           [0, 0, 1, 1, 1, 0, 0],
+           [0, 0, 1, 1, 2, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+    >>> ndimage.morphological_gradient(a, size=(3,3))
+    array([[0, 0, 0, 0, 0, 0, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 3, 3, 1, 0],
+           [0, 1, 3, 2, 3, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 1, 1, 2, 2, 2, 0],
+           [0, 0, 0, 0, 0, 0, 0]])
+
+    """
+    tmp = grey_dilation(input, size, footprint, structure, None, mode,
+                        cval, origin, axes=axes)
+    if isinstance(output, np.ndarray):
+        grey_erosion(input, size, footprint, structure, output, mode,
+                     cval, origin, axes=axes)
+        return np.subtract(tmp, output, output)
+    else:
+        return (tmp - grey_erosion(input, size, footprint, structure,
+                                   None, mode, cval, origin, axes=axes))
+
+
+def morphological_laplace(input, size=None, footprint=None, structure=None,
+                          output=None, mode="reflect", cval=0.0, origin=0, *,
+                          axes=None):
+    """
+    Multidimensional morphological laplace.
+
+    Parameters
+    ----------
+    input : array_like
+        Input.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the mathematical
+        morphology operations. Optional if `footprint` or `structure` is
+        provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the morphology operations.
+    structure : array of ints, optional
+        Structuring element used for the morphology operations. `structure` may
+        be a non-flat structuring element. The `structure` array applies
+        offsets to the pixels in a neighborhood (the offset is additive during
+        dilation and subtractive during erosion)
+    output : ndarray, optional
+        An output array can optionally be provided.
+    mode : {'reflect','constant','nearest','mirror', 'wrap'}, optional
+        The mode parameter determines how the array borders are handled.
+        For 'constant' mode, values beyond borders are set to be `cval`.
+        Default is 'reflect'.
+    cval : scalar, optional
+        Value to fill past edges of input if mode is 'constant'.
+        Default is 0.0
+    origin : origin, optional
+        The origin parameter controls the placement of the filter.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    morphological_laplace : ndarray
+        Output
+
+    """
+    tmp1 = grey_dilation(input, size, footprint, structure, None, mode,
+                         cval, origin, axes=axes)
+    if isinstance(output, np.ndarray):
+        grey_erosion(input, size, footprint, structure, output, mode,
+                     cval, origin, axes=axes)
+        np.add(tmp1, output, output)
+        np.subtract(output, input, output)
+        return np.subtract(output, input, output)
+    else:
+        tmp2 = grey_erosion(input, size, footprint, structure, None, mode,
+                            cval, origin, axes=axes)
+        np.add(tmp1, tmp2, tmp2)
+        np.subtract(tmp2, input, tmp2)
+        np.subtract(tmp2, input, tmp2)
+        return tmp2
+
+
+def white_tophat(input, size=None, footprint=None, structure=None,
+                 output=None, mode="reflect", cval=0.0, origin=0, *,
+                 axes=None):
+    """
+    Multidimensional white tophat filter.
+
+    Parameters
+    ----------
+    input : array_like
+        Input.
+    size : tuple of ints
+        Shape of a flat and full structuring element used for the filter.
+        Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of elements of a flat structuring element
+        used for the white tophat filter.
+    structure : array of ints, optional
+        Structuring element used for the filter. `structure` may be a non-flat
+        structuring element. The `structure` array applies offsets to the
+        pixels in a neighborhood (the offset is additive during dilation and
+        subtractive during erosion)
+    output : array, optional
+        An array used for storing the output of the filter may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'.
+        Default is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default is 0.
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    output : ndarray
+        Result of the filter of `input` with `structure`.
+
+    See Also
+    --------
+    black_tophat
+
+    Examples
+    --------
+    Subtract gray background from a bright peak.
+
+    >>> from scipy.ndimage import generate_binary_structure, white_tophat
+    >>> import numpy as np
+    >>> square = generate_binary_structure(rank=2, connectivity=3)
+    >>> bright_on_gray = np.array([[2, 3, 3, 3, 2],
+    ...                            [3, 4, 5, 4, 3],
+    ...                            [3, 5, 9, 5, 3],
+    ...                            [3, 4, 5, 4, 3],
+    ...                            [2, 3, 3, 3, 2]])
+    >>> white_tophat(input=bright_on_gray, structure=square)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 1, 5, 1, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    tmp = grey_erosion(input, size, footprint, structure, None, mode,
+                       cval, origin, axes=axes)
+    tmp = grey_dilation(tmp, size, footprint, structure, output, mode,
+                        cval, origin, axes=axes)
+    if tmp is None:
+        tmp = output
+
+    if input.dtype == np.bool_ and tmp.dtype == np.bool_:
+        np.bitwise_xor(input, tmp, out=tmp)
+    else:
+        np.subtract(input, tmp, out=tmp)
+    return tmp
+
+
+def black_tophat(input, size=None, footprint=None, structure=None, output=None,
+                 mode="reflect", cval=0.0, origin=0, *, axes=None):
+    """
+    Multidimensional black tophat filter.
+
+    Parameters
+    ----------
+    input : array_like
+        Input.
+    size : tuple of ints, optional
+        Shape of a flat and full structuring element used for the filter.
+        Optional if `footprint` or `structure` is provided.
+    footprint : array of ints, optional
+        Positions of non-infinite elements of a flat structuring element
+        used for the black tophat filter.
+    structure : array of ints, optional
+        Structuring element used for the filter. `structure` may be a non-flat
+        structuring element. The `structure` array applies offsets to the
+        pixels in a neighborhood (the offset is additive during dilation and
+        subtractive during erosion)
+    output : array, optional
+        An array used for storing the output of the filter may be provided.
+    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+        The `mode` parameter determines how the array borders are
+        handled, where `cval` is the value when mode is equal to
+        'constant'. Default is 'reflect'
+    cval : scalar, optional
+        Value to fill past edges of input if `mode` is 'constant'. Default
+        is 0.0.
+    origin : scalar, optional
+        The `origin` parameter controls the placement of the filter.
+        Default 0
+    axes : tuple of int or None
+        The axes over which to apply the filter. If None, `input` is filtered
+        along all axes. If an `origin` tuple is provided, its length must match
+        the number of axes.
+
+    Returns
+    -------
+    black_tophat : ndarray
+        Result of the filter of `input` with `structure`.
+
+    See Also
+    --------
+    white_tophat, grey_opening, grey_closing
+
+    Examples
+    --------
+    Change dark peak to bright peak and subtract background.
+
+    >>> from scipy.ndimage import generate_binary_structure, black_tophat
+    >>> import numpy as np
+    >>> square = generate_binary_structure(rank=2, connectivity=3)
+    >>> dark_on_gray = np.array([[7, 6, 6, 6, 7],
+    ...                          [6, 5, 4, 5, 6],
+    ...                          [6, 4, 0, 4, 6],
+    ...                          [6, 5, 4, 5, 6],
+    ...                          [7, 6, 6, 6, 7]])
+    >>> black_tophat(input=dark_on_gray, structure=square)
+    array([[0, 0, 0, 0, 0],
+           [0, 0, 1, 0, 0],
+           [0, 1, 5, 1, 0],
+           [0, 0, 1, 0, 0],
+           [0, 0, 0, 0, 0]])
+
+    """
+    input = np.asarray(input)
+
+    if (size is not None) and (footprint is not None):
+        warnings.warn("ignoring size because footprint is set",
+                      UserWarning, stacklevel=2)
+    tmp = grey_dilation(input, size, footprint, structure, None, mode,
+                        cval, origin, axes=axes)
+    tmp = grey_erosion(tmp, size, footprint, structure, output, mode,
+                       cval, origin, axes=axes)
+    if tmp is None:
+        tmp = output
+
+    if input.dtype == np.bool_ and tmp.dtype == np.bool_:
+        np.bitwise_xor(tmp, input, out=tmp)
+    else:
+        np.subtract(tmp, input, out=tmp)
+    return tmp
+
+
+def distance_transform_bf(input, metric="euclidean", sampling=None,
+                          return_distances=True, return_indices=False,
+                          distances=None, indices=None):
+    """
+    Distance transform function by a brute force algorithm.
+
+    This function calculates the distance transform of the `input`, by
+    replacing each foreground (non-zero) element, with its
+    shortest distance to the background (any zero-valued element).
+
+    In addition to the distance transform, the feature transform can
+    be calculated. In this case the index of the closest background
+    element to each foreground element is returned in a separate array.
+
+    Parameters
+    ----------
+    input : array_like
+        Input
+    metric : {'euclidean', 'taxicab', 'chessboard'}, optional
+        'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
+        The default is 'euclidean'.
+    sampling : float, or sequence of float, optional
+        This parameter is only used when `metric` is 'euclidean'.
+        Spacing of elements along each dimension. If a sequence, must be of
+        length equal to the input rank; if a single number, this is used for
+        all axes. If not specified, a grid spacing of unity is implied.
+    return_distances : bool, optional
+        Whether to calculate the distance transform.
+        Default is True.
+    return_indices : bool, optional
+        Whether to calculate the feature transform.
+        Default is False.
+    distances : ndarray, optional
+        An output array to store the calculated distance transform, instead of
+        returning it.
+        `return_distances` must be True.
+        It must be the same shape as `input`, and of type float64 if `metric`
+        is 'euclidean', uint32 otherwise.
+    indices : int32 ndarray, optional
+        An output array to store the calculated feature transform, instead of
+        returning it.
+        `return_indicies` must be True.
+        Its shape must be ``(input.ndim,) + input.shape``.
+
+    Returns
+    -------
+    distances : ndarray, optional
+        The calculated distance transform. Returned only when
+        `return_distances` is True and `distances` is not supplied.
+        It will have the same shape as the input array.
+    indices : int32 ndarray, optional
+        The calculated feature transform. It has an input-shaped array for each
+        dimension of the input. See distance_transform_edt documentation for an
+        example.
+        Returned only when `return_indices` is True and `indices` is not
+        supplied.
+
+    See Also
+    --------
+    distance_transform_cdt : Faster distance transform for taxicab and
+                             chessboard metrics
+    distance_transform_edt : Faster distance transform for euclidean metric
+
+    Notes
+    -----
+    This function employs a slow brute force algorithm. See also the
+    function `distance_transform_cdt` for more efficient taxicab [1]_ and
+    chessboard algorithms [2]_.
+
+    References
+    ----------
+    .. [1] Taxicab distance. Wikipedia, 2023.
+           https://en.wikipedia.org/wiki/Taxicab_geometry
+    .. [2] Chessboard distance. Wikipedia, 2023.
+           https://en.wikipedia.org/wiki/Chebyshev_distance
+
+    Examples
+    --------
+    Import the necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.ndimage import distance_transform_bf
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.axes_grid1 import ImageGrid
+
+    First, we create a toy binary image.
+
+    >>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
+    ...     # fill circular area with 1
+    ...     xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
+    ...     circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
+    ...     circle_shape = np.sqrt(circle) < radius
+    ...     image[circle_shape] = fillvalue
+    ...     return image
+    >>> image = np.zeros((100, 100), dtype=np.uint8)
+    >>> image[35:65, 20:80] = 1
+    >>> image = add_circle(28, 65, 10, image)
+    >>> image = add_circle(37, 30, 10, image)
+    >>> image = add_circle(70, 45, 20, image)
+    >>> image = add_circle(45, 80, 10, image)
+
+    Next, we set up the figure.
+
+    >>> fig = plt.figure(figsize=(8, 8))  # set up the figure structure
+    >>> grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=(0.4, 0.3),
+    ...                  label_mode="1", share_all=True,
+    ...                  cbar_location="right", cbar_mode="each",
+    ...                  cbar_size="7%", cbar_pad="2%")
+    >>> for ax in grid:
+    ...     ax.axis('off')  # remove axes from images
+
+    The top left image is the original binary image.
+
+    >>> binary_image = grid[0].imshow(image, cmap='gray')
+    >>> cbar_binary_image = grid.cbar_axes[0].colorbar(binary_image)
+    >>> cbar_binary_image.set_ticks([0, 1])
+    >>> grid[0].set_title("Binary image: foreground in white")
+
+    The distance transform calculates the distance between foreground pixels
+    and the image background according to a distance metric. Available metrics
+    in `distance_transform_bf` are: ``euclidean`` (default), ``taxicab``
+    and ``chessboard``. The top right image contains the distance transform
+    based on the ``euclidean`` metric.
+
+    >>> distance_transform_euclidean = distance_transform_bf(image)
+    >>> euclidean_transform = grid[1].imshow(distance_transform_euclidean,
+    ...                                      cmap='gray')
+    >>> cbar_euclidean = grid.cbar_axes[1].colorbar(euclidean_transform)
+    >>> colorbar_ticks = [0, 10, 20]
+    >>> cbar_euclidean.set_ticks(colorbar_ticks)
+    >>> grid[1].set_title("Euclidean distance")
+
+    The lower left image contains the distance transform using the ``taxicab``
+    metric.
+
+    >>> distance_transform_taxicab = distance_transform_bf(image,
+    ...                                                    metric='taxicab')
+    >>> taxicab_transformation = grid[2].imshow(distance_transform_taxicab,
+    ...                                         cmap='gray')
+    >>> cbar_taxicab = grid.cbar_axes[2].colorbar(taxicab_transformation)
+    >>> cbar_taxicab.set_ticks(colorbar_ticks)
+    >>> grid[2].set_title("Taxicab distance")
+
+    Finally, the lower right image contains the distance transform using the
+    ``chessboard`` metric.
+
+    >>> distance_transform_cb = distance_transform_bf(image,
+    ...                                               metric='chessboard')
+    >>> chessboard_transformation = grid[3].imshow(distance_transform_cb,
+    ...                                            cmap='gray')
+    >>> cbar_taxicab = grid.cbar_axes[3].colorbar(chessboard_transformation)
+    >>> cbar_taxicab.set_ticks(colorbar_ticks)
+    >>> grid[3].set_title("Chessboard distance")
+    >>> plt.show()
+
+    """
+    ft_inplace = isinstance(indices, np.ndarray)
+    dt_inplace = isinstance(distances, np.ndarray)
+    _distance_tranform_arg_check(
+        dt_inplace, ft_inplace, return_distances, return_indices
+    )
+
+    tmp1 = np.asarray(input) != 0
+    struct = generate_binary_structure(tmp1.ndim, tmp1.ndim)
+    tmp2 = binary_dilation(tmp1, struct)
+    tmp2 = np.logical_xor(tmp1, tmp2)
+    tmp1 = tmp1.astype(np.int8) - tmp2.astype(np.int8)
+    metric = metric.lower()
+    if metric == 'euclidean':
+        metric = 1
+    elif metric in ['taxicab', 'cityblock', 'manhattan']:
+        metric = 2
+    elif metric == 'chessboard':
+        metric = 3
+    else:
+        raise RuntimeError('distance metric not supported')
+    if sampling is not None:
+        sampling = _ni_support._normalize_sequence(sampling, tmp1.ndim)
+        sampling = np.asarray(sampling, dtype=np.float64)
+        if not sampling.flags.contiguous:
+            sampling = sampling.copy()
+    if return_indices:
+        ft = np.zeros(tmp1.shape, dtype=np.int32)
+    else:
+        ft = None
+    if return_distances:
+        if distances is None:
+            if metric == 1:
+                dt = np.zeros(tmp1.shape, dtype=np.float64)
+            else:
+                dt = np.zeros(tmp1.shape, dtype=np.uint32)
+        else:
+            if distances.shape != tmp1.shape:
+                raise RuntimeError('distances array has wrong shape')
+            if metric == 1:
+                if distances.dtype.type != np.float64:
+                    raise RuntimeError('distances array must be float64')
+            else:
+                if distances.dtype.type != np.uint32:
+                    raise RuntimeError('distances array must be uint32')
+            dt = distances
+    else:
+        dt = None
+
+    _nd_image.distance_transform_bf(tmp1, metric, sampling, dt, ft)
+    if return_indices:
+        if isinstance(indices, np.ndarray):
+            if indices.dtype.type != np.int32:
+                raise RuntimeError('indices array must be int32')
+            if indices.shape != (tmp1.ndim,) + tmp1.shape:
+                raise RuntimeError('indices array has wrong shape')
+            tmp2 = indices
+        else:
+            tmp2 = np.indices(tmp1.shape, dtype=np.int32)
+        ft = np.ravel(ft)
+        for ii in range(tmp2.shape[0]):
+            rtmp = np.ravel(tmp2[ii, ...])[ft]
+            rtmp.shape = tmp1.shape
+            tmp2[ii, ...] = rtmp
+        ft = tmp2
+
+    # construct and return the result
+    result = []
+    if return_distances and not dt_inplace:
+        result.append(dt)
+    if return_indices and not ft_inplace:
+        result.append(ft)
+
+    if len(result) == 2:
+        return tuple(result)
+    elif len(result) == 1:
+        return result[0]
+    else:
+        return None
+
+
+def distance_transform_cdt(input, metric='chessboard', return_distances=True,
+                           return_indices=False, distances=None, indices=None):
+    """
+    Distance transform for chamfer type of transforms.
+
+    This function calculates the distance transform of the `input`, by
+    replacing each foreground (non-zero) element, with its
+    shortest distance to the background (any zero-valued element).
+
+    In addition to the distance transform, the feature transform can
+    be calculated. In this case the index of the closest background
+    element to each foreground element is returned in a separate array.
+
+    Parameters
+    ----------
+    input : array_like
+        Input. Values of 0 are treated as background.
+    metric : {'chessboard', 'taxicab'} or array_like, optional
+        The `metric` determines the type of chamfering that is done. If the
+        `metric` is equal to 'taxicab' a structure is generated using
+        `generate_binary_structure` with a squared distance equal to 1. If
+        the `metric` is equal to 'chessboard', a `metric` is generated
+        using `generate_binary_structure` with a squared distance equal to
+        the dimensionality of the array. These choices correspond to the
+        common interpretations of the 'taxicab' and the 'chessboard'
+        distance metrics in two dimensions.
+        A custom metric may be provided, in the form of a matrix where
+        each dimension has a length of three.
+        'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
+        The default is 'chessboard'.
+    return_distances : bool, optional
+        Whether to calculate the distance transform.
+        Default is True.
+    return_indices : bool, optional
+        Whether to calculate the feature transform.
+        Default is False.
+    distances : int32 ndarray, optional
+        An output array to store the calculated distance transform, instead of
+        returning it.
+        `return_distances` must be True.
+        It must be the same shape as `input`.
+    indices : int32 ndarray, optional
+        An output array to store the calculated feature transform, instead of
+        returning it.
+        `return_indicies` must be True.
+        Its shape must be ``(input.ndim,) + input.shape``.
+
+    Returns
+    -------
+    distances : int32 ndarray, optional
+        The calculated distance transform. Returned only when
+        `return_distances` is True, and `distances` is not supplied.
+        It will have the same shape as the input array.
+    indices : int32 ndarray, optional
+        The calculated feature transform. It has an input-shaped array for each
+        dimension of the input. See distance_transform_edt documentation for an
+        example.
+        Returned only when `return_indices` is True, and `indices` is not
+        supplied.
+
+    See Also
+    --------
+    distance_transform_edt : Fast distance transform for euclidean metric
+    distance_transform_bf : Distance transform for different metrics using
+                            a slower brute force algorithm
+
+    Examples
+    --------
+    Import the necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.ndimage import distance_transform_cdt
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.axes_grid1 import ImageGrid
+
+    First, we create a toy binary image.
+
+    >>> def add_circle(center_x, center_y, radius, image, fillvalue=1):
+    ...     # fill circular area with 1
+    ...     xx, yy = np.mgrid[:image.shape[0], :image.shape[1]]
+    ...     circle = (xx - center_x) ** 2 + (yy - center_y) ** 2
+    ...     circle_shape = np.sqrt(circle) < radius
+    ...     image[circle_shape] = fillvalue
+    ...     return image
+    >>> image = np.zeros((100, 100), dtype=np.uint8)
+    >>> image[35:65, 20:80] = 1
+    >>> image = add_circle(28, 65, 10, image)
+    >>> image = add_circle(37, 30, 10, image)
+    >>> image = add_circle(70, 45, 20, image)
+    >>> image = add_circle(45, 80, 10, image)
+
+    Next, we set up the figure.
+
+    >>> fig = plt.figure(figsize=(5, 15))
+    >>> grid = ImageGrid(fig, 111, nrows_ncols=(3, 1), axes_pad=(0.5, 0.3),
+    ...                  label_mode="1", share_all=True,
+    ...                  cbar_location="right", cbar_mode="each",
+    ...                  cbar_size="7%", cbar_pad="2%")
+    >>> for ax in grid:
+    ...     ax.axis('off')
+    >>> top, middle, bottom = grid
+    >>> colorbar_ticks = [0, 10, 20]
+
+    The top image contains the original binary image.
+
+    >>> binary_image = top.imshow(image, cmap='gray')
+    >>> cbar_binary_image = top.cax.colorbar(binary_image)
+    >>> cbar_binary_image.set_ticks([0, 1])
+    >>> top.set_title("Binary image: foreground in white")
+
+    The middle image contains the distance transform using the ``taxicab``
+    metric.
+
+    >>> distance_taxicab = distance_transform_cdt(image, metric="taxicab")
+    >>> taxicab_transform = middle.imshow(distance_taxicab, cmap='gray')
+    >>> cbar_taxicab = middle.cax.colorbar(taxicab_transform)
+    >>> cbar_taxicab.set_ticks(colorbar_ticks)
+    >>> middle.set_title("Taxicab metric")
+
+    The bottom image contains the distance transform using the ``chessboard``
+    metric.
+
+    >>> distance_chessboard = distance_transform_cdt(image,
+    ...                                              metric="chessboard")
+    >>> chessboard_transform = bottom.imshow(distance_chessboard, cmap='gray')
+    >>> cbar_chessboard = bottom.cax.colorbar(chessboard_transform)
+    >>> cbar_chessboard.set_ticks(colorbar_ticks)
+    >>> bottom.set_title("Chessboard metric")
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    """
+    ft_inplace = isinstance(indices, np.ndarray)
+    dt_inplace = isinstance(distances, np.ndarray)
+    _distance_tranform_arg_check(
+        dt_inplace, ft_inplace, return_distances, return_indices
+    )
+    input = np.asarray(input)
+    if isinstance(metric, str):
+        if metric in ['taxicab', 'cityblock', 'manhattan']:
+            rank = input.ndim
+            metric = generate_binary_structure(rank, 1)
+        elif metric == 'chessboard':
+            rank = input.ndim
+            metric = generate_binary_structure(rank, rank)
+        else:
+            raise ValueError('invalid metric provided')
+    else:
+        try:
+            metric = np.asarray(metric)
+        except Exception as e:
+            raise ValueError('invalid metric provided') from e
+        for s in metric.shape:
+            if s != 3:
+                raise ValueError('metric sizes must be equal to 3')
+
+    if not metric.flags.contiguous:
+        metric = metric.copy()
+    if dt_inplace:
+        if distances.dtype.type != np.int32:
+            raise ValueError('distances must be of int32 type')
+        if distances.shape != input.shape:
+            raise ValueError('distances has wrong shape')
+        dt = distances
+        dt[...] = np.where(input, -1, 0).astype(np.int32)
+    else:
+        dt = np.where(input, -1, 0).astype(np.int32)
+
+    rank = dt.ndim
+    if return_indices:
+        ft = np.arange(dt.size, dtype=np.int32)
+        ft.shape = dt.shape
+    else:
+        ft = None
+
+    _nd_image.distance_transform_op(metric, dt, ft)
+    dt = dt[tuple([slice(None, None, -1)] * rank)]
+    if return_indices:
+        ft = ft[tuple([slice(None, None, -1)] * rank)]
+    _nd_image.distance_transform_op(metric, dt, ft)
+    dt = dt[tuple([slice(None, None, -1)] * rank)]
+    if return_indices:
+        ft = ft[tuple([slice(None, None, -1)] * rank)]
+        ft = np.ravel(ft)
+        if ft_inplace:
+            if indices.dtype.type != np.int32:
+                raise ValueError('indices array must be int32')
+            if indices.shape != (dt.ndim,) + dt.shape:
+                raise ValueError('indices array has wrong shape')
+            tmp = indices
+        else:
+            tmp = np.indices(dt.shape, dtype=np.int32)
+        for ii in range(tmp.shape[0]):
+            rtmp = np.ravel(tmp[ii, ...])[ft]
+            rtmp.shape = dt.shape
+            tmp[ii, ...] = rtmp
+        ft = tmp
+
+    # construct and return the result
+    result = []
+    if return_distances and not dt_inplace:
+        result.append(dt)
+    if return_indices and not ft_inplace:
+        result.append(ft)
+
+    if len(result) == 2:
+        return tuple(result)
+    elif len(result) == 1:
+        return result[0]
+    else:
+        return None
+
+
+def distance_transform_edt(input, sampling=None, return_distances=True,
+                           return_indices=False, distances=None, indices=None):
+    """
+    Exact Euclidean distance transform.
+
+    This function calculates the distance transform of the `input`, by
+    replacing each foreground (non-zero) element, with its
+    shortest distance to the background (any zero-valued element).
+
+    In addition to the distance transform, the feature transform can
+    be calculated. In this case the index of the closest background
+    element to each foreground element is returned in a separate array.
+
+    Parameters
+    ----------
+    input : array_like
+        Input data to transform. Can be any type but will be converted
+        into binary: 1 wherever input equates to True, 0 elsewhere.
+    sampling : float, or sequence of float, optional
+        Spacing of elements along each dimension. If a sequence, must be of
+        length equal to the input rank; if a single number, this is used for
+        all axes. If not specified, a grid spacing of unity is implied.
+    return_distances : bool, optional
+        Whether to calculate the distance transform.
+        Default is True.
+    return_indices : bool, optional
+        Whether to calculate the feature transform.
+        Default is False.
+    distances : float64 ndarray, optional
+        An output array to store the calculated distance transform, instead of
+        returning it.
+        `return_distances` must be True.
+        It must be the same shape as `input`.
+    indices : int32 ndarray, optional
+        An output array to store the calculated feature transform, instead of
+        returning it.
+        `return_indicies` must be True.
+        Its shape must be ``(input.ndim,) + input.shape``.
+
+    Returns
+    -------
+    distances : float64 ndarray, optional
+        The calculated distance transform. Returned only when
+        `return_distances` is True and `distances` is not supplied.
+        It will have the same shape as the input array.
+    indices : int32 ndarray, optional
+        The calculated feature transform. It has an input-shaped array for each
+        dimension of the input. See example below.
+        Returned only when `return_indices` is True and `indices` is not
+        supplied.
+
+    Notes
+    -----
+    The Euclidean distance transform gives values of the Euclidean
+    distance::
+
+                    n
+      y_i = sqrt(sum (x[i]-b[i])**2)
+                    i
+
+    where b[i] is the background point (value 0) with the smallest
+    Euclidean distance to input points x[i], and n is the
+    number of dimensions.
+
+    Examples
+    --------
+    >>> from scipy import ndimage
+    >>> import numpy as np
+    >>> a = np.array(([0,1,1,1,1],
+    ...               [0,0,1,1,1],
+    ...               [0,1,1,1,1],
+    ...               [0,1,1,1,0],
+    ...               [0,1,1,0,0]))
+    >>> ndimage.distance_transform_edt(a)
+    array([[ 0.    ,  1.    ,  1.4142,  2.2361,  3.    ],
+           [ 0.    ,  0.    ,  1.    ,  2.    ,  2.    ],
+           [ 0.    ,  1.    ,  1.4142,  1.4142,  1.    ],
+           [ 0.    ,  1.    ,  1.4142,  1.    ,  0.    ],
+           [ 0.    ,  1.    ,  1.    ,  0.    ,  0.    ]])
+
+    With a sampling of 2 units along x, 1 along y:
+
+    >>> ndimage.distance_transform_edt(a, sampling=[2,1])
+    array([[ 0.    ,  1.    ,  2.    ,  2.8284,  3.6056],
+           [ 0.    ,  0.    ,  1.    ,  2.    ,  3.    ],
+           [ 0.    ,  1.    ,  2.    ,  2.2361,  2.    ],
+           [ 0.    ,  1.    ,  2.    ,  1.    ,  0.    ],
+           [ 0.    ,  1.    ,  1.    ,  0.    ,  0.    ]])
+
+    Asking for indices as well:
+
+    >>> edt, inds = ndimage.distance_transform_edt(a, return_indices=True)
+    >>> inds
+    array([[[0, 0, 1, 1, 3],
+            [1, 1, 1, 1, 3],
+            [2, 2, 1, 3, 3],
+            [3, 3, 4, 4, 3],
+            [4, 4, 4, 4, 4]],
+           [[0, 0, 1, 1, 4],
+            [0, 1, 1, 1, 4],
+            [0, 0, 1, 4, 4],
+            [0, 0, 3, 3, 4],
+            [0, 0, 3, 3, 4]]], dtype=int32)
+
+    With arrays provided for inplace outputs:
+
+    >>> indices = np.zeros(((np.ndim(a),) + a.shape), dtype=np.int32)
+    >>> ndimage.distance_transform_edt(a, return_indices=True, indices=indices)
+    array([[ 0.    ,  1.    ,  1.4142,  2.2361,  3.    ],
+           [ 0.    ,  0.    ,  1.    ,  2.    ,  2.    ],
+           [ 0.    ,  1.    ,  1.4142,  1.4142,  1.    ],
+           [ 0.    ,  1.    ,  1.4142,  1.    ,  0.    ],
+           [ 0.    ,  1.    ,  1.    ,  0.    ,  0.    ]])
+    >>> indices
+    array([[[0, 0, 1, 1, 3],
+            [1, 1, 1, 1, 3],
+            [2, 2, 1, 3, 3],
+            [3, 3, 4, 4, 3],
+            [4, 4, 4, 4, 4]],
+           [[0, 0, 1, 1, 4],
+            [0, 1, 1, 1, 4],
+            [0, 0, 1, 4, 4],
+            [0, 0, 3, 3, 4],
+            [0, 0, 3, 3, 4]]], dtype=int32)
+
+    """
+    ft_inplace = isinstance(indices, np.ndarray)
+    dt_inplace = isinstance(distances, np.ndarray)
+    _distance_tranform_arg_check(
+        dt_inplace, ft_inplace, return_distances, return_indices
+    )
+
+    # calculate the feature transform
+    input = np.atleast_1d(np.where(input, 1, 0).astype(np.int8))
+    if sampling is not None:
+        sampling = _ni_support._normalize_sequence(sampling, input.ndim)
+        sampling = np.asarray(sampling, dtype=np.float64)
+        if not sampling.flags.contiguous:
+            sampling = sampling.copy()
+
+    if ft_inplace:
+        ft = indices
+        if ft.shape != (input.ndim,) + input.shape:
+            raise RuntimeError('indices array has wrong shape')
+        if ft.dtype.type != np.int32:
+            raise RuntimeError('indices array must be int32')
+    else:
+        ft = np.zeros((input.ndim,) + input.shape, dtype=np.int32)
+
+    _nd_image.euclidean_feature_transform(input, sampling, ft)
+    # if requested, calculate the distance transform
+    if return_distances:
+        dt = ft - np.indices(input.shape, dtype=ft.dtype)
+        dt = dt.astype(np.float64)
+        if sampling is not None:
+            for ii in range(len(sampling)):
+                dt[ii, ...] *= sampling[ii]
+        np.multiply(dt, dt, dt)
+        if dt_inplace:
+            dt = np.add.reduce(dt, axis=0)
+            if distances.shape != dt.shape:
+                raise RuntimeError('distances array has wrong shape')
+            if distances.dtype.type != np.float64:
+                raise RuntimeError('distances array must be float64')
+            np.sqrt(dt, distances)
+        else:
+            dt = np.add.reduce(dt, axis=0)
+            dt = np.sqrt(dt)
+
+    # construct and return the result
+    result = []
+    if return_distances and not dt_inplace:
+        result.append(dt)
+    if return_indices and not ft_inplace:
+        result.append(ft)
+
+    if len(result) == 2:
+        return tuple(result)
+    elif len(result) == 1:
+        return result[0]
+    else:
+        return None
+
+
+def _distance_tranform_arg_check(distances_out, indices_out,
+                                 return_distances, return_indices):
+    """Raise a RuntimeError if the arguments are invalid"""
+    error_msgs = []
+    if (not return_distances) and (not return_indices):
+        error_msgs.append(
+            'at least one of return_distances/return_indices must be True')
+    if distances_out and not return_distances:
+        error_msgs.append(
+            'return_distances must be True if distances is supplied'
+        )
+    if indices_out and not return_indices:
+        error_msgs.append('return_indices must be True if indices is supplied')
+    if error_msgs:
+        raise RuntimeError(', '.join(error_msgs))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1673391726a4070af4814d04be16e29e01d9f29b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ndimage_api.py
@@ -0,0 +1,16 @@
+"""This is the 'bare' ndimage API.
+
+This --- private! --- module only collects implementations of public ndimage API
+for _support_alternative_backends.
+The latter --- also private! --- module adds delegation to CuPy etc and
+re-exports decorated names to __init__.py
+"""
+
+from ._filters import *    # noqa: F403
+from ._fourier import *   # noqa: F403
+from ._interpolation import *   # noqa: F403
+from ._measurements import *   # noqa: F403
+from ._morphology import *   # noqa: F403
+
+# '@' due to pytest bug, scipy/scipy#22236
+__all__ = [s for s in dir() if not s.startswith(('_', '@'))]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c0d977500574b73f168296645fb36d10c1320de
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py
@@ -0,0 +1,210 @@
+"""Docstring components common to several ndimage functions."""
+from typing import Final
+
+from scipy._lib import doccer
+
+__all__ = ['docfiller']
+
+
+_input_doc = (
+"""input : array_like
+    The input array.""")
+_axis_doc = (
+"""axis : int, optional
+    The axis of `input` along which to calculate. Default is -1.""")
+_output_doc = (
+"""output : array or dtype, optional
+    The array in which to place the output, or the dtype of the
+    returned array. By default an array of the same dtype as input
+    will be created.""")
+_size_foot_doc = (
+"""size : scalar or tuple, optional
+    See footprint, below. Ignored if footprint is given.
+footprint : array, optional
+    Either `size` or `footprint` must be defined. `size` gives
+    the shape that is taken from the input array, at every element
+    position, to define the input to the filter function.
+    `footprint` is a boolean array that specifies (implicitly) a
+    shape, but also which of the elements within this shape will get
+    passed to the filter function. Thus ``size=(n,m)`` is equivalent
+    to ``footprint=np.ones((n,m))``.  We adjust `size` to the number
+    of dimensions of the input array, so that, if the input array is
+    shape (10,10,10), and `size` is 2, then the actual size used is
+    (2,2,2). When `footprint` is given, `size` is ignored.""")
+_mode_reflect_doc = (
+"""mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+    The `mode` parameter determines how the input array is extended
+    beyond its boundaries. Default is 'reflect'. Behavior for each valid
+    value is as follows:
+
+    'reflect' (`d c b a | a b c d | d c b a`)
+        The input is extended by reflecting about the edge of the last
+        pixel. This mode is also sometimes referred to as half-sample
+        symmetric.
+
+    'constant' (`k k k k | a b c d | k k k k`)
+        The input is extended by filling all values beyond the edge with
+        the same constant value, defined by the `cval` parameter.
+
+    'nearest' (`a a a a | a b c d | d d d d`)
+        The input is extended by replicating the last pixel.
+
+    'mirror' (`d c b | a b c d | c b a`)
+        The input is extended by reflecting about the center of the last
+        pixel. This mode is also sometimes referred to as whole-sample
+        symmetric.
+
+    'wrap' (`a b c d | a b c d | a b c d`)
+        The input is extended by wrapping around to the opposite edge.
+
+    For consistency with the interpolation functions, the following mode
+    names can also be used:
+
+    'grid-mirror'
+        This is a synonym for 'reflect'.
+
+    'grid-constant'
+        This is a synonym for 'constant'.
+
+    'grid-wrap'
+        This is a synonym for 'wrap'.""")
+
+_mode_interp_constant_doc = (
+"""mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \
+'mirror', 'grid-wrap', 'wrap'}, optional
+    The `mode` parameter determines how the input array is extended
+    beyond its boundaries. Default is 'constant'. Behavior for each valid
+    value is as follows (see additional plots and details on
+    :ref:`boundary modes `):
+
+    'reflect' (`d c b a | a b c d | d c b a`)
+        The input is extended by reflecting about the edge of the last
+        pixel. This mode is also sometimes referred to as half-sample
+        symmetric.
+
+    'grid-mirror'
+        This is a synonym for 'reflect'.
+
+    'constant' (`k k k k | a b c d | k k k k`)
+        The input is extended by filling all values beyond the edge with
+        the same constant value, defined by the `cval` parameter. No
+        interpolation is performed beyond the edges of the input.
+
+    'grid-constant' (`k k k k | a b c d | k k k k`)
+        The input is extended by filling all values beyond the edge with
+        the same constant value, defined by the `cval` parameter. Interpolation
+        occurs for samples outside the input's extent  as well.
+
+    'nearest' (`a a a a | a b c d | d d d d`)
+        The input is extended by replicating the last pixel.
+
+    'mirror' (`d c b | a b c d | c b a`)
+        The input is extended by reflecting about the center of the last
+        pixel. This mode is also sometimes referred to as whole-sample
+        symmetric.
+
+    'grid-wrap' (`a b c d | a b c d | a b c d`)
+        The input is extended by wrapping around to the opposite edge.
+
+    'wrap' (`d b c d | a b c d | b c a b`)
+        The input is extended by wrapping around to the opposite edge, but in a
+        way such that the last point and initial point exactly overlap. In this
+        case it is not well defined which sample will be chosen at the point of
+        overlap.""")
+_mode_interp_mirror_doc = (
+    _mode_interp_constant_doc.replace("Default is 'constant'",
+                                      "Default is 'mirror'")
+)
+assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \
+    'Default not replaced'
+
+_mode_multiple_doc = (
+"""mode : str or sequence, optional
+    The `mode` parameter determines how the input array is extended
+    when the filter overlaps a border. By passing a sequence of modes
+    with length equal to the number of dimensions of the input array,
+    different modes can be specified along each axis. Default value is
+    'reflect'. The valid values and their behavior is as follows:
+
+    'reflect' (`d c b a | a b c d | d c b a`)
+        The input is extended by reflecting about the edge of the last
+        pixel. This mode is also sometimes referred to as half-sample
+        symmetric.
+
+    'constant' (`k k k k | a b c d | k k k k`)
+        The input is extended by filling all values beyond the edge with
+        the same constant value, defined by the `cval` parameter.
+
+    'nearest' (`a a a a | a b c d | d d d d`)
+        The input is extended by replicating the last pixel.
+
+    'mirror' (`d c b | a b c d | c b a`)
+        The input is extended by reflecting about the center of the last
+        pixel. This mode is also sometimes referred to as whole-sample
+        symmetric.
+
+    'wrap' (`a b c d | a b c d | a b c d`)
+        The input is extended by wrapping around to the opposite edge.
+
+    For consistency with the interpolation functions, the following mode
+    names can also be used:
+
+    'grid-constant'
+        This is a synonym for 'constant'.
+
+    'grid-mirror'
+        This is a synonym for 'reflect'.
+
+    'grid-wrap'
+        This is a synonym for 'wrap'.""")
+_cval_doc = (
+"""cval : scalar, optional
+    Value to fill past edges of input if `mode` is 'constant'. Default
+    is 0.0.""")
+_origin_doc = (
+"""origin : int, optional
+    Controls the placement of the filter on the input array's pixels.
+    A value of 0 (the default) centers the filter over the pixel, with
+    positive values shifting the filter to the left, and negative ones
+    to the right.""")
+_origin_multiple_doc = (
+"""origin : int or sequence, optional
+    Controls the placement of the filter on the input array's pixels.
+    A value of 0 (the default) centers the filter over the pixel, with
+    positive values shifting the filter to the left, and negative ones
+    to the right. By passing a sequence of origins with length equal to
+    the number of dimensions of the input array, different shifts can
+    be specified along each axis.""")
+_extra_arguments_doc = (
+"""extra_arguments : sequence, optional
+    Sequence of extra positional arguments to pass to passed function.""")
+_extra_keywords_doc = (
+"""extra_keywords : dict, optional
+    dict of extra keyword arguments to pass to passed function.""")
+_prefilter_doc = (
+"""prefilter : bool, optional
+    Determines if the input array is prefiltered with `spline_filter`
+    before interpolation. The default is True, which will create a
+    temporary `float64` array of filtered values if ``order > 1``. If
+    setting this to False, the output will be slightly blurred if
+    ``order > 1``, unless the input is prefiltered, i.e. it is the result
+    of calling `spline_filter` on the original input.""")
+
+docdict = {
+    'input': _input_doc,
+    'axis': _axis_doc,
+    'output': _output_doc,
+    'size_foot': _size_foot_doc,
+    'mode_interp_constant': _mode_interp_constant_doc,
+    'mode_interp_mirror': _mode_interp_mirror_doc,
+    'mode_reflect': _mode_reflect_doc,
+    'mode_multiple': _mode_multiple_doc,
+    'cval': _cval_doc,
+    'origin': _origin_doc,
+    'origin_multiple': _origin_multiple_doc,
+    'extra_arguments': _extra_arguments_doc,
+    'extra_keywords': _extra_keywords_doc,
+    'prefilter': _prefilter_doc
+    }
+
+docfiller: Final = doccer.filldoc(docdict)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8d41d00d9edf8d347c4ffc95598210489fed5e9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_ni_support.py
@@ -0,0 +1,143 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+#    notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+#    copyright notice, this list of conditions and the following
+#    disclaimer in the documentation and/or other materials provided
+#    with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+#    products derived from this software without specific prior
+#    written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+from collections.abc import Iterable
+import operator
+import warnings
+import numpy as np
+
+
+def _extend_mode_to_code(mode, is_filter=False):
+    """Convert an extension mode to the corresponding integer code.
+    """
+    if mode == 'nearest':
+        return 0
+    elif mode == 'wrap':
+        return 1
+    elif mode in ['reflect', 'grid-mirror']:
+        return 2
+    elif mode == 'mirror':
+        return 3
+    elif mode == 'constant':
+        return 4
+    elif mode == 'grid-wrap' and is_filter:
+        return 1
+    elif mode == 'grid-wrap':
+        return 5
+    elif mode == 'grid-constant' and is_filter:
+        return 4
+    elif mode == 'grid-constant':
+        return 6
+    else:
+        raise RuntimeError('boundary mode not supported')
+
+
+def _normalize_sequence(input, rank):
+    """If input is a scalar, create a sequence of length equal to the
+    rank by duplicating the input. If input is a sequence,
+    check if its length is equal to the length of array.
+    """
+    is_str = isinstance(input, str)
+    if not is_str and np.iterable(input):
+        normalized = list(input)
+        if len(normalized) != rank:
+            err = "sequence argument must have length equal to input rank"
+            raise RuntimeError(err)
+    else:
+        normalized = [input] * rank
+    return normalized
+
+
+def _get_output(output, input, shape=None, complex_output=False):
+    if shape is None:
+        shape = input.shape
+    if output is None:
+        if not complex_output:
+            output = np.zeros(shape, dtype=input.dtype.name)
+        else:
+            complex_type = np.promote_types(input.dtype, np.complex64)
+            output = np.zeros(shape, dtype=complex_type)
+    elif isinstance(output, (type, np.dtype)):
+        # Classes (like `np.float32`) and dtypes are interpreted as dtype
+        if complex_output and np.dtype(output).kind != 'c':
+            warnings.warn("promoting specified output dtype to complex", stacklevel=3)
+            output = np.promote_types(output, np.complex64)
+        output = np.zeros(shape, dtype=output)
+    elif isinstance(output, str):
+        output = np.dtype(output)
+        if complex_output and output.kind != 'c':
+            raise RuntimeError("output must have complex dtype")
+        elif not issubclass(output.type, np.number):
+            raise RuntimeError("output must have numeric dtype")
+        output = np.zeros(shape, dtype=output)
+    else:
+        # output was supplied as an array
+        output = np.asarray(output)
+        if output.shape != shape:
+            raise RuntimeError("output shape not correct")
+        elif complex_output and output.dtype.kind != 'c':
+            raise RuntimeError("output must have complex dtype")
+    return output
+
+
+def _check_axes(axes, ndim):
+    if axes is None:
+        return tuple(range(ndim))
+    elif np.isscalar(axes):
+        axes = (operator.index(axes),)
+    elif isinstance(axes, Iterable):
+        for ax in axes:
+            axes = tuple(operator.index(ax) for ax in axes)
+            if ax < -ndim or ax > ndim - 1:
+                raise ValueError(f"specified axis: {ax} is out of range")
+        axes = tuple(ax % ndim if ax < 0 else ax for ax in axes)
+    else:
+        message = "axes must be an integer, iterable of integers, or None"
+        raise ValueError(message)
+    if len(tuple(set(axes))) != len(axes):
+        raise ValueError("axes must be unique")
+    return axes
+
+def _skip_if_dtype(arg):
+    """'array or dtype' polymorphism.
+
+    Return None for np.int8, dtype('float32') or 'f' etc
+           arg for np.empty(3) etc
+    """
+    if isinstance(arg, str):
+        return None
+    if type(arg) is type:
+        return None if issubclass(arg, np.generic) else arg
+    else:
+        return None if isinstance(arg, np.dtype) else arg
+
+
+def _skip_if_int(arg):
+    return None if (arg is None or isinstance(arg, int)) else arg
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..6d998aa648b493336d9871117e687e8f8d5279aa
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_rank_filter_1d.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbb913b14c76873202fce8eaabe2d08f778abe94
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/_support_alternative_backends.py
@@ -0,0 +1,72 @@
+import functools
+from scipy._lib._array_api import (
+    is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API
+)
+
+import numpy as np
+from ._ndimage_api import *   # noqa: F403
+from . import _ndimage_api
+from . import _delegators
+__all__ = _ndimage_api.__all__
+
+
+MODULE_NAME = 'ndimage'
+
+
+def delegate_xp(delegator, module_name):
+    def inner(func):
+        @functools.wraps(func)
+        def wrapper(*args, **kwds):
+            xp = delegator(*args, **kwds)
+
+            # try delegating to a cupyx/jax namesake
+            if is_cupy(xp):
+                # https://github.com/cupy/cupy/issues/8336
+                import importlib
+                cupyx_module = importlib.import_module(f"cupyx.scipy.{module_name}")
+                cupyx_func = getattr(cupyx_module, func.__name__)
+                return cupyx_func(*args, **kwds)
+            elif is_jax(xp) and func.__name__ == "map_coordinates":
+                spx = scipy_namespace_for(xp)
+                jax_module = getattr(spx, module_name)
+                jax_func = getattr(jax_module, func.__name__)
+                return jax_func(*args, **kwds)
+            else:
+                # the original function (does all np.asarray internally)
+                # XXX: output arrays
+                result = func(*args, **kwds)
+
+                if isinstance(result, (np.ndarray, np.generic)):
+                    # XXX: np.int32->np.array_0D
+                    return xp.asarray(result)
+                elif isinstance(result, int):
+                    return result
+                elif isinstance(result, dict):
+                    # value_indices: result is {np.int64(1): (array(0), array(1))} etc
+                    return {
+                        k.item(): tuple(xp.asarray(vv) for vv in v)
+                        for k,v in result.items()
+                    }
+                elif result is None:
+                    # inplace operations
+                    return result
+                else:
+                    # lists/tuples
+                    return type(result)(
+                        xp.asarray(x) if isinstance(x, np.ndarray) else x
+                        for x in result
+                    )
+        return wrapper
+    return inner
+
+# ### decorate ###
+for func_name in _ndimage_api.__all__:
+    bare_func = getattr(_ndimage_api, func_name)
+    delegator = getattr(_delegators, func_name + "_signature")
+
+    f = (delegate_xp(delegator, MODULE_NAME)(bare_func)
+         if SCIPY_ARRAY_API
+         else bare_func)
+
+    # add the decorated function to the namespace, to be imported in __init__.py
+    vars()[func_name] = f
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/filters.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..e16d9d279a9585b2454c46ee09cf22143de833a6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/filters.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'correlate1d', 'convolve1d', 'gaussian_filter1d',
+    'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace',
+    'laplace', 'gaussian_laplace', 'generic_gradient_magnitude',
+    'gaussian_gradient_magnitude', 'correlate', 'convolve',
+    'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
+    'maximum_filter1d', 'minimum_filter', 'maximum_filter',
+    'rank_filter', 'median_filter', 'percentile_filter',
+    'generic_filter1d', 'generic_filter'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='filters',
+                                   private_modules=['_filters'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/fourier.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..73c49bd52d9a446ce0fe25d9e15b8de68fbd46fb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/fourier.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'fourier_gaussian', 'fourier_uniform',
+    'fourier_ellipsoid', 'fourier_shift'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='fourier',
+                                   private_modules=['_fourier'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/interpolation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2739c60c51037487ae8892c407e2f3d7870d5da
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/interpolation.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'spline_filter1d', 'spline_filter',
+    'geometric_transform', 'map_coordinates',
+    'affine_transform', 'shift', 'zoom', 'rotate',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='interpolation',
+                                   private_modules=['_interpolation'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/measurements.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f76b01840ffb829205bd1d28a7ad1f9ac5db61
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/measurements.py
@@ -0,0 +1,24 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'label', 'find_objects', 'labeled_comprehension',
+    'sum', 'mean', 'variance', 'standard_deviation',
+    'minimum', 'maximum', 'median', 'minimum_position',
+    'maximum_position', 'extrema', 'center_of_mass',
+    'histogram', 'watershed_ift', 'sum_labels'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='measurements',
+                                   private_modules=['_measurements'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/morphology.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..e522e7df3a4b06b7e04ed8c2d0ecaff2a98b951d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/morphology.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'iterate_structure', 'generate_binary_structure',
+    'binary_erosion', 'binary_dilation', 'binary_opening',
+    'binary_closing', 'binary_hit_or_miss', 'binary_propagation',
+    'binary_fill_holes', 'grey_erosion', 'grey_dilation',
+    'grey_opening', 'grey_closing', 'morphological_gradient',
+    'morphological_laplace', 'white_tophat', 'black_tophat',
+    'distance_transform_bf', 'distance_transform_cdt',
+    'distance_transform_edt'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package='ndimage', module='morphology',
+                                   private_modules=['_morphology'], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d8fd292b537a84fe48d0c8ae8bee75bab2b3353
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py
@@ -0,0 +1,12 @@
+import numpy as np
+
+# list of numarray data types
+integer_types: list[str] = [
+    "int8", "uint8", "int16", "uint16",
+    "int32", "uint32", "int64", "uint64"]
+
+float_types: list[str] = ["float32", "float64"]
+
+complex_types: list[str] = ["complex64", "complex128"]
+
+types: list[str] = integer_types + float_types
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6c3cff3b12cec4ad050b31cc5d5c327f32784447
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_inputs.txt
@@ -0,0 +1,21 @@
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 0 1 1 1
+1 1 0 0 0 1 1
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+1 1 0 0 0 1 1
+1 1 1 0 1 1 1
+1 0 1 1 1 0 1
+0 0 0 1 0 0 0
+1 0 0 1 0 0 1
+1 1 1 1 1 1 1
+1 0 0 1 0 0 1
+0 0 0 1 0 0 0
+1 0 1 1 1 0 1
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c239b0369c9df3e06df9a2fbf048faec2f84941f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_results.txt
@@ -0,0 +1,294 @@
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+2 2 2 2 2 2 2
+3 3 3 3 3 3 3
+4 4 4 4 4 4 4
+5 5 5 5 5 5 5
+6 6 6 6 6 6 6
+7 7 7 7 7 7 7
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 2 3 4 5 6 7
+8 9 10 11 12 13 14
+15 16 17 18 19 20 21
+22 23 24 25 26 27 28
+29 30 31 32 33 34 35
+36 37 38 39 40 41 42
+43 44 45 46 47 48 49
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 2 3 4 5 6 7
+8 1 2 3 4 5 6
+9 8 1 2 3 4 5
+10 9 8 1 2 3 4
+11 10 9 8 1 2 3
+12 11 10 9 8 1 2
+13 12 11 10 9 8 1
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+1 2 3 4 5 6 7
+2 3 4 5 6 7 8
+3 4 5 6 7 8 9
+4 5 6 7 8 9 10
+5 6 7 8 9 10 11
+6 7 8 9 10 11 12
+7 8 9 10 11 12 13
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 2 0 4
+0 0 0 2 0 0 0
+5 0 2 0 6 0 7
+2 2 0 0 0 7 7
+2 2 2 0 7 7 7
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+3 0 1 0 4 0 2
+0 0 0 1 0 0 0
+5 0 6 0 1 0 7
+5 5 0 0 0 1 1
+5 5 5 0 1 1 1
+1 1 1 0 2 2 2
+3 3 0 0 0 4 4
+5 0 6 0 7 0 8
+0 0 0 9 0 0 0
+10 0 11 0 12 0 13
+14 14 0 0 0 15 15
+16 16 16 0 17 17 17
+1 1 1 0 2 3 3
+1 1 0 0 0 3 3
+1 0 4 0 3 0 3
+0 0 0 3 0 0 0
+3 0 3 0 5 0 6
+3 3 0 0 0 6 6
+3 3 7 0 6 6 6
+1 2 3 0 4 5 6
+7 8 0 0 0 9 10
+11 0 12 0 13 0 14
+0 0 0 15 0 0 0
+16 0 17 0 18 0 19
+20 21 0 0 0 22 23
+24 25 26 0 27 28 29
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 2 0 2
+0 0 0 2 0 0 0
+2 0 2 0 4 0 5
+2 2 0 0 0 5 5
+2 2 2 0 5 5 5
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 4 0 2
+0 0 0 5 0 0 0
+6 0 7 0 8 0 9
+6 6 0 0 0 9 9
+6 6 6 0 9 9 9
+1 2 3 0 4 5 6
+7 1 0 0 0 4 5
+8 0 1 0 9 0 4
+0 0 0 1 0 0 0
+10 0 11 0 1 0 12
+13 10 0 0 0 1 14
+15 13 10 0 16 17 1
+1 2 3 0 4 5 6
+1 2 0 0 0 5 6
+1 0 7 0 8 0 6
+0 0 0 9 0 0 0
+10 0 11 0 12 0 13
+10 14 0 0 0 15 13
+10 14 16 0 17 15 13
+1 1 1 0 1 1 1
+1 1 0 0 0 1 1
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+1 1 0 0 0 1 1
+1 1 1 0 1 1 1
+1 1 2 0 3 3 3
+1 1 0 0 0 3 3
+1 0 1 0 4 0 3
+0 0 0 1 0 0 0
+5 0 6 0 1 0 1
+5 5 0 0 0 1 1
+5 5 5 0 7 1 1
+1 2 1 0 1 3 1
+2 1 0 0 0 1 3
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+4 1 0 0 0 1 5
+1 4 1 0 1 5 1
+1 2 3 0 4 5 6
+2 3 0 0 0 6 7
+3 0 8 0 6 0 9
+0 0 0 6 0 0 0
+10 0 6 0 11 0 12
+13 6 0 0 0 12 14
+6 15 16 0 12 14 17
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 1 0 3 0 2
+0 0 0 1 0 0 0
+4 0 5 0 1 0 1
+4 4 0 0 0 1 1
+4 4 4 0 1 1 1
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+4 0 0 5 0 0 5
+5 5 5 5 5 5 5
+5 0 0 5 0 0 6
+0 0 0 7 0 0 0
+8 0 7 7 7 0 9
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+4 0 0 4 0 0 5
+4 4 4 4 4 4 4
+6 0 0 4 0 0 4
+0 0 0 7 0 0 0
+8 0 7 7 7 0 9
+1 0 2 2 2 0 3
+0 0 0 4 0 0 0
+5 0 0 6 0 0 7
+8 8 8 8 8 8 8
+9 0 0 10 0 0 11
+0 0 0 12 0 0 0
+13 0 14 14 14 0 15
+1 0 2 3 3 0 4
+0 0 0 3 0 0 0
+5 0 0 3 0 0 6
+5 5 3 3 3 6 6
+5 0 0 3 0 0 6
+0 0 0 3 0 0 0
+7 0 3 3 8 0 9
+1 0 2 3 4 0 5
+0 0 0 6 0 0 0
+7 0 0 8 0 0 9
+10 11 12 13 14 15 16
+17 0 0 18 0 0 19
+0 0 0 20 0 0 0
+21 0 22 23 24 0 25
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 3 4 0 5
+0 0 0 2 0 0 0
+6 0 0 7 0 0 8
+9 6 10 11 7 12 13
+14 0 0 10 0 0 12
+0 0 0 15 0 0 0
+16 0 17 18 15 0 19
+1 0 2 3 4 0 5
+0 0 0 3 0 0 0
+6 0 0 3 0 0 7
+6 8 9 3 10 11 7
+6 0 0 3 0 0 7
+0 0 0 3 0 0 0
+12 0 13 3 14 0 15
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 2 3 0 4
+0 0 0 2 0 0 0
+5 0 0 2 0 0 6
+5 5 2 2 2 6 6
+5 0 0 2 0 0 6
+0 0 0 2 0 0 0
+7 0 8 2 2 0 9
+1 0 2 3 2 0 4
+0 0 0 2 0 0 0
+5 0 0 6 0 0 7
+8 5 6 9 6 7 10
+5 0 0 6 0 0 7
+0 0 0 11 0 0 0
+12 0 11 13 11 0 14
+1 0 2 3 4 0 5
+0 0 0 4 0 0 0
+6 0 0 7 0 0 8
+9 10 7 11 12 8 13
+10 0 0 12 0 0 14
+0 0 0 15 0 0 0
+16 0 15 17 18 0 19
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt
new file mode 100644
index 0000000000000000000000000000000000000000..35ae8121364d4fb3292c11f2a72333f456fa9c0a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/data/label_strels.txt
@@ -0,0 +1,42 @@
+0 0 1
+1 1 1
+1 0 0
+1 0 0
+1 1 1
+0 0 1
+0 0 0
+1 1 1
+0 0 0
+0 1 1
+0 1 0
+1 1 0
+0 0 0
+0 0 0
+0 0 0
+0 1 1
+1 1 1
+1 1 0
+0 1 0
+1 1 1
+0 1 0
+1 0 0
+0 1 0
+0 0 1
+0 1 0
+0 1 0
+0 1 0
+1 1 1
+1 1 1
+1 1 1
+1 1 0
+0 1 0
+0 1 1
+1 0 1
+0 1 0
+1 0 1
+0 0 1
+0 1 0
+1 0 0
+1 1 0
+1 1 1
+0 1 1
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..61a5a0f70262ef9f21fe8593a64f155bd583cab1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py
@@ -0,0 +1,102 @@
+import numpy as np
+from scipy._lib._array_api import xp_assert_close
+
+from scipy import ndimage
+from scipy.ndimage import _ctest
+from scipy.ndimage import _cytest
+from scipy._lib._ccallback import LowLevelCallable
+
+FILTER1D_FUNCTIONS = [
+    lambda filter_size: _ctest.filter1d(filter_size),
+    lambda filter_size: _cytest.filter1d(filter_size, with_signature=False),
+    lambda filter_size: LowLevelCallable(
+                            _cytest.filter1d(filter_size, with_signature=True)
+                        ),
+    lambda filter_size: LowLevelCallable.from_cython(
+                            _cytest, "_filter1d",
+                            _cytest.filter1d_capsule(filter_size),
+                        ),
+]
+
+FILTER2D_FUNCTIONS = [
+    lambda weights: _ctest.filter2d(weights),
+    lambda weights: _cytest.filter2d(weights, with_signature=False),
+    lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)),
+    lambda weights: LowLevelCallable.from_cython(_cytest,
+                                                 "_filter2d",
+                                                 _cytest.filter2d_capsule(weights),),
+]
+
+TRANSFORM_FUNCTIONS = [
+    lambda shift: _ctest.transform(shift),
+    lambda shift: _cytest.transform(shift, with_signature=False),
+    lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)),
+    lambda shift: LowLevelCallable.from_cython(_cytest,
+                                               "_transform",
+                                               _cytest.transform_capsule(shift),),
+]
+
+
+def test_generic_filter():
+    def filter2d(footprint_elements, weights):
+        return (weights*footprint_elements).sum()
+
+    def check(j):
+        func = FILTER2D_FUNCTIONS[j]
+
+        im = np.ones((20, 20))
+        im[:10,:10] = 0
+        footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
+        footprint_size = np.count_nonzero(footprint)
+        weights = np.ones(footprint_size)/footprint_size
+
+        res = ndimage.generic_filter(im, func(weights),
+                                     footprint=footprint)
+        std = ndimage.generic_filter(im, filter2d, footprint=footprint,
+                                     extra_arguments=(weights,))
+        xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+    for j, func in enumerate(FILTER2D_FUNCTIONS):
+        check(j)
+
+
+def test_generic_filter1d():
+    def filter1d(input_line, output_line, filter_size):
+        for i in range(output_line.size):
+            output_line[i] = 0
+            for j in range(filter_size):
+                output_line[i] += input_line[i+j]
+        output_line /= filter_size
+
+    def check(j):
+        func = FILTER1D_FUNCTIONS[j]
+
+        im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1))
+        filter_size = 3
+
+        res = ndimage.generic_filter1d(im, func(filter_size),
+                                       filter_size)
+        std = ndimage.generic_filter1d(im, filter1d, filter_size,
+                                       extra_arguments=(filter_size,))
+        xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+    for j, func in enumerate(FILTER1D_FUNCTIONS):
+        check(j)
+
+
+def test_geometric_transform():
+    def transform(output_coordinates, shift):
+        return output_coordinates[0] - shift, output_coordinates[1] - shift
+
+    def check(j):
+        func = TRANSFORM_FUNCTIONS[j]
+
+        im = np.arange(12).reshape(4, 3).astype(np.float64)
+        shift = 0.5
+
+        res = ndimage.geometric_transform(im, func(shift))
+        std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,))
+        xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+    for j, func in enumerate(TRANSFORM_FUNCTIONS):
+        check(j)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..a82de456bb92c96d5b9a599d4b33c987e134fdc8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py
@@ -0,0 +1,67 @@
+""" Testing data types for ndimage calls
+"""
+import numpy as np
+
+from scipy._lib._array_api import assert_array_almost_equal
+import pytest
+
+from scipy import ndimage
+
+
+def test_map_coordinates_dts():
+    # check that ndimage accepts different data types for interpolation
+    data = np.array([[4, 1, 3, 2],
+                     [7, 6, 8, 5],
+                     [3, 5, 3, 6]])
+    shifted_data = np.array([[0, 0, 0, 0],
+                             [0, 4, 1, 3],
+                             [0, 7, 6, 8]])
+    idx = np.indices(data.shape)
+    dts = (np.uint8, np.uint16, np.uint32, np.uint64,
+           np.int8, np.int16, np.int32, np.int64,
+           np.intp, np.uintp, np.float32, np.float64)
+    for order in range(0, 6):
+        for data_dt in dts:
+            these_data = data.astype(data_dt)
+            for coord_dt in dts:
+                # affine mapping
+                mat = np.eye(2, dtype=coord_dt)
+                off = np.zeros((2,), dtype=coord_dt)
+                out = ndimage.affine_transform(these_data, mat, off)
+                assert_array_almost_equal(these_data, out)
+                # map coordinates
+                coords_m1 = idx.astype(coord_dt) - 1
+                coords_p10 = idx.astype(coord_dt) + 10
+                out = ndimage.map_coordinates(these_data, coords_m1, order=order)
+                assert_array_almost_equal(out, shifted_data)
+                # check constant fill works
+                out = ndimage.map_coordinates(these_data, coords_p10, order=order)
+                assert_array_almost_equal(out, np.zeros((3,4)))
+            # check shift and zoom
+            out = ndimage.shift(these_data, 1)
+            assert_array_almost_equal(out, shifted_data)
+            out = ndimage.zoom(these_data, 1)
+            assert_array_almost_equal(these_data, out)
+
+
+@pytest.mark.xfail(True, reason="Broken on many platforms")
+def test_uint64_max():
+    # Test interpolation respects uint64 max.  Reported to fail at least on
+    # win32 (due to the 32 bit visual C compiler using signed int64 when
+    # converting between uint64 to double) and Debian on s390x.
+    # Interpolation is always done in double precision floating point, so
+    # we use the largest uint64 value for which int(float(big)) still fits
+    # in a uint64.
+    # This test was last enabled on macOS only, and there it started failing
+    # on arm64 as well (see gh-19117).
+    big = 2**64 - 1025
+    arr = np.array([big, big, big], dtype=np.uint64)
+    # Tests geometric transform (map_coordinates, affine_transform)
+    inds = np.indices(arr.shape) - 0.1
+    x = ndimage.map_coordinates(arr, inds)
+    assert x[1] == int(float(big))
+    assert x[2] == int(float(big))
+    # Tests zoom / shift
+    x = ndimage.shift(arr, 0.1)
+    assert x[1] == int(float(big))
+    assert x[2] == int(float(big))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d5cb39f566827f41037e34a5a63ce874996c36f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py
@@ -0,0 +1,2920 @@
+''' Some tests for filters '''
+import functools
+import itertools
+import re
+
+import numpy as np
+import pytest
+from numpy.testing import suppress_warnings, assert_allclose, assert_array_equal
+from hypothesis import strategies as st
+from hypothesis import given
+import hypothesis.extra.numpy as npst
+from pytest import raises as assert_raises
+from scipy import ndimage
+from scipy._lib._array_api import (
+    assert_almost_equal,
+    assert_array_almost_equal,
+    xp_assert_close,
+    xp_assert_equal,
+)
+from scipy._lib._array_api import is_cupy, is_numpy, is_torch, array_namespace
+from scipy.conftest import array_api_compatible
+from scipy.ndimage._filters import _gaussian_kernel1d
+
+from . import types, float_types, complex_types
+
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              pytest.mark.usefixtures("xfail_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy']),]
+
+
+def sumsq(a, b, xp=None):
+    xp = array_namespace(a, b) if xp is None else xp
+    return xp.sqrt(xp.sum((a - b)**2))
+
+
+def _complex_correlate(xp, array, kernel, real_dtype, convolve=False,
+                       mode="reflect", cval=0, ):
+    """Utility to perform a reference complex-valued convolutions.
+
+    When convolve==False, correlation is performed instead
+    """
+    array = xp.asarray(array)
+    kernel = xp.asarray(kernel)
+    isdtype = array_namespace(array, kernel).isdtype
+    complex_array = isdtype(array.dtype, 'complex floating')
+    complex_kernel = isdtype(kernel.dtype, 'complex floating')
+    if array.ndim == 1:
+        func = ndimage.convolve1d if convolve else ndimage.correlate1d
+    else:
+        func = ndimage.convolve if convolve else ndimage.correlate
+    if not convolve:
+        kernel = xp.conj(kernel)
+    if complex_array and complex_kernel:
+        # use: real(cval) for array.real component
+        #      imag(cval) for array.imag component
+        re_cval = cval.real if isinstance(cval, complex) else xp.real(cval)
+        im_cval = cval.imag if isinstance(cval, complex) else xp.imag(cval)
+
+        output = (
+            func(xp.real(array), xp.real(kernel), output=real_dtype,
+                 mode=mode, cval=re_cval) -
+            func(xp.imag(array), xp.imag(kernel), output=real_dtype,
+                 mode=mode, cval=im_cval) +
+            1j * func(xp.imag(array), xp.real(kernel), output=real_dtype,
+                      mode=mode, cval=im_cval) +
+            1j * func(xp.real(array), xp.imag(kernel), output=real_dtype,
+                      mode=mode, cval=re_cval)
+        )
+    elif complex_array:
+        re_cval = xp.real(cval)
+        re_cval = re_cval.item() if isinstance(re_cval, xp.ndarray) else re_cval
+        im_cval = xp.imag(cval)
+        im_cval = im_cval.item() if isinstance(im_cval, xp.ndarray) else im_cval
+
+        output = (
+            func(xp.real(array), kernel, output=real_dtype, mode=mode,
+                 cval=re_cval) +
+            1j * func(xp.imag(array), kernel, output=real_dtype, mode=mode,
+                      cval=im_cval)
+        )
+    elif complex_kernel:
+        # real array so cval is real too
+        output = (
+            func(array, xp.real(kernel), output=real_dtype, mode=mode, cval=cval) +
+            1j * func(array, xp.imag(kernel), output=real_dtype, mode=mode,
+                      cval=cval)
+        )
+    return output
+
+
+def _cases_axes_tuple_length_mismatch():
+    # Generate combinations of filter function, valid kwargs, and
+    # keyword-value pairs for which the value will become with mismatched
+    # (invalid) size
+    filter_func = ndimage.gaussian_filter
+    kwargs = dict(radius=3, mode='constant', sigma=1.0, order=0)
+    for key, val in kwargs.items():
+        yield filter_func, kwargs, key, val
+
+    filter_funcs = [ndimage.uniform_filter, ndimage.minimum_filter,
+                    ndimage.maximum_filter]
+    kwargs = dict(size=3, mode='constant', origin=0)
+    for filter_func in filter_funcs:
+        for key, val in kwargs.items():
+            yield filter_func, kwargs, key, val
+
+    filter_funcs = [ndimage.correlate, ndimage.convolve]
+    # sequence of mode not supported for correlate or convolve
+    kwargs = dict(origin=0)
+    for filter_func in filter_funcs:
+        for key, val in kwargs.items():
+            yield filter_func, kwargs, key, val
+
+
+class TestNdimageFilters:
+
+    def _validate_complex(self, xp, array, kernel, type2, mode='reflect',
+                          cval=0, check_warnings=True):
+        # utility for validating complex-valued correlations
+        real_dtype = xp.real(xp.asarray([], dtype=type2)).dtype
+        expected = _complex_correlate(
+            xp, array, kernel, real_dtype, convolve=False, mode=mode, cval=cval
+        )
+
+        if array.ndim == 1:
+            correlate = functools.partial(ndimage.correlate1d, axis=-1,
+                                          mode=mode, cval=cval)
+            convolve = functools.partial(ndimage.convolve1d, axis=-1,
+                                         mode=mode, cval=cval)
+        else:
+            correlate = functools.partial(ndimage.correlate, mode=mode,
+                                          cval=cval)
+            convolve = functools.partial(ndimage.convolve, mode=mode,
+                                          cval=cval)
+
+        # test correlate output dtype
+        output = correlate(array, kernel, output=type2)
+        assert_array_almost_equal(expected, output)
+        assert output.dtype.type == type2
+
+        # test correlate with pre-allocated output
+        output = xp.zeros_like(array, dtype=type2)
+        correlate(array, kernel, output=output)
+        assert_array_almost_equal(expected, output)
+
+        # test convolve output dtype
+        output = convolve(array, kernel, output=type2)
+        expected = _complex_correlate(
+            xp, array, kernel, real_dtype, convolve=True, mode=mode, cval=cval,
+        )
+        assert_array_almost_equal(expected, output)
+        assert output.dtype.type == type2
+
+        # convolve with pre-allocated output
+        convolve(array, kernel, output=output)
+        assert_array_almost_equal(expected, output)
+        assert output.dtype.type == type2
+
+        if check_warnings:
+            # warns if the output is not a complex dtype
+            with pytest.warns(UserWarning,
+                              match="promoting specified output dtype to "
+                              "complex"):
+                correlate(array, kernel, output=real_dtype)
+
+            with pytest.warns(UserWarning,
+                              match="promoting specified output dtype to "
+                              "complex"):
+                convolve(array, kernel, output=real_dtype)
+
+        # raises if output array is provided, but is not complex-valued
+        output_real = xp.zeros_like(array, dtype=real_dtype)
+        with assert_raises(RuntimeError):
+            correlate(array, kernel, output=output_real)
+
+        with assert_raises(RuntimeError):
+            convolve(array, kernel, output=output_real)
+
+    def test_correlate01(self, xp):
+        array = xp.asarray([1, 2])
+        weights = xp.asarray([2])
+        expected = xp.asarray([2, 4])
+
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+    @xfail_xp_backends('cupy', reason="Differs by a factor of two?")
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_correlate01_overlap(self, xp):
+        array = xp.reshape(xp.arange(256), (16, 16))
+        weights = xp.asarray([2])
+        expected = 2 * array
+
+        ndimage.correlate1d(array, weights, output=array)
+        assert_array_almost_equal(array, expected)
+
+    def test_correlate02(self, xp):
+        array = xp.asarray([1, 2, 3])
+        kernel = xp.asarray([1])
+
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(array, output)
+
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(array, output)
+
+        output = ndimage.correlate1d(array, kernel)
+        assert_array_almost_equal(array, output)
+
+        output = ndimage.convolve1d(array, kernel)
+        assert_array_almost_equal(array, output)
+
+    def test_correlate03(self, xp):
+        array = xp.asarray([1])
+        weights = xp.asarray([1, 1])
+        expected = xp.asarray([2])
+
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+    def test_correlate04(self, xp):
+        array = xp.asarray([1, 2])
+        tcor = xp.asarray([2, 3])
+        tcov = xp.asarray([3, 4])
+        weights = xp.asarray([1, 1])
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, tcov)
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, tcov)
+
+    def test_correlate05(self, xp):
+        array = xp.asarray([1, 2, 3])
+        tcor = xp.asarray([2, 3, 5])
+        tcov = xp.asarray([3, 5, 6])
+        kernel = xp.asarray([1, 1])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(tcor, output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(tcov, output)
+        output = ndimage.correlate1d(array, kernel)
+        assert_array_almost_equal(tcor, output)
+        output = ndimage.convolve1d(array, kernel)
+        assert_array_almost_equal(tcov, output)
+
+    def test_correlate06(self, xp):
+        array = xp.asarray([1, 2, 3])
+        tcor = xp.asarray([9, 14, 17])
+        tcov = xp.asarray([7, 10, 15])
+        weights = xp.asarray([1, 2, 3])
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, tcov)
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, tcov)
+
+    def test_correlate07(self, xp):
+        array = xp.asarray([1, 2, 3])
+        expected = xp.asarray([5, 8, 11])
+        weights = xp.asarray([1, 2, 1])
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, expected)
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, expected)
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, expected)
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, expected)
+
+    def test_correlate08(self, xp):
+        array = xp.asarray([1, 2, 3])
+        tcor = xp.asarray([1, 2, 5])
+        tcov = xp.asarray([3, 6, 7])
+        weights = xp.asarray([1, 2, -1])
+        output = ndimage.correlate(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve(array, weights)
+        assert_array_almost_equal(output, tcov)
+        output = ndimage.correlate1d(array, weights)
+        assert_array_almost_equal(output, tcor)
+        output = ndimage.convolve1d(array, weights)
+        assert_array_almost_equal(output, tcov)
+
+    def test_correlate09(self, xp):
+        array = xp.asarray([])
+        kernel = xp.asarray([1, 1])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(array, output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(array, output)
+        output = ndimage.correlate1d(array, kernel)
+        assert_array_almost_equal(array, output)
+        output = ndimage.convolve1d(array, kernel)
+        assert_array_almost_equal(array, output)
+
+    def test_correlate10(self, xp):
+        array = xp.asarray([[]])
+        kernel = xp.asarray([[1, 1]])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(array, output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(array, output)
+
+    def test_correlate11(self, xp):
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]])
+        kernel = xp.asarray([[1, 1],
+                             [1, 1]])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(xp.asarray([[12, 16, 18], [18, 22, 24]]), output)
+
+    def test_correlate12(self, xp):
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]])
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        output = ndimage.correlate(array, kernel)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        output = ndimage.convolve(array, kernel)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_kernel', types)
+    def test_correlate13(self, dtype_array, dtype_kernel, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_kernel = getattr(xp, dtype_kernel)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel, output=dtype_kernel)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        assert output.dtype.type == dtype_kernel
+
+        output = ndimage.convolve(array, kernel,
+                                  output=dtype_kernel)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+        assert output.dtype.type == dtype_kernel
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate14(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = xp.zeros(array.shape, dtype=dtype_output)
+        ndimage.correlate(array, kernel, output=output)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        assert output.dtype.type == dtype_output
+
+        ndimage.convolve(array, kernel, output=output)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+        assert output.dtype.type == dtype_output
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    def test_correlate15(self, dtype_array, xp):
+        dtype_array = getattr(xp, dtype_array)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel, output=xp.float32)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        assert output.dtype.type == xp.float32
+
+        output = ndimage.convolve(array, kernel, output=xp.float32)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+        assert output.dtype.type == xp.float32
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    def test_correlate16(self, dtype_array, xp):
+        dtype_array = getattr(xp, dtype_array)
+
+        kernel = xp.asarray([[0.5, 0],
+                             [0, 0.5]])
+        array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel, output=xp.float32)
+        assert_array_almost_equal(xp.asarray([[1, 1.5, 2.5], [2.5, 3, 4]]), output)
+        assert output.dtype.type == xp.float32
+
+        output = ndimage.convolve(array, kernel, output=xp.float32)
+        assert_array_almost_equal(xp.asarray([[3, 4, 4.5], [4.5, 5.5, 6]]), output)
+        assert output.dtype.type == xp.float32
+
+    def test_correlate17(self, xp):
+        array = xp.asarray([1, 2, 3])
+        tcor = xp.asarray([3, 5, 6])
+        tcov = xp.asarray([2, 3, 5])
+        kernel = xp.asarray([1, 1])
+        output = ndimage.correlate(array, kernel, origin=-1)
+        assert_array_almost_equal(tcor, output)
+        output = ndimage.convolve(array, kernel, origin=-1)
+        assert_array_almost_equal(tcov, output)
+        output = ndimage.correlate1d(array, kernel, origin=-1)
+        assert_array_almost_equal(tcor, output)
+        output = ndimage.convolve1d(array, kernel, origin=-1)
+        assert_array_almost_equal(tcov, output)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    def test_correlate18(self, dtype_array, xp):
+        dtype_array = getattr(xp, dtype_array)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel,
+                                   output=xp.float32,
+                                   mode='nearest', origin=-1)
+        assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+        assert output.dtype.type == xp.float32
+
+        output = ndimage.convolve(array, kernel,
+                                  output=xp.float32,
+                                  mode='nearest', origin=-1)
+        assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+        assert output.dtype.type == xp.float32
+
+    def test_correlate_mode_sequence(self, xp):
+        kernel = xp.ones((2, 2))
+        array = xp.ones((3, 3), dtype=xp.float64)
+        with assert_raises(RuntimeError):
+            ndimage.correlate(array, kernel, mode=['nearest', 'reflect'])
+        with assert_raises(RuntimeError):
+            ndimage.convolve(array, kernel, mode=['nearest', 'reflect'])
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    def test_correlate19(self, dtype_array, xp):
+        dtype_array = getattr(xp, dtype_array)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]])
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_array)
+        output = ndimage.correlate(array, kernel,
+                                   output=xp.float32,
+                                   mode='nearest', origin=[-1, 0])
+        assert_array_almost_equal(xp.asarray([[5, 6, 8], [8, 9, 11]]), output)
+        assert output.dtype.type == xp.float32
+
+        output = ndimage.convolve(array, kernel,
+                                  output=xp.float32,
+                                  mode='nearest', origin=[-1, 0])
+        assert_array_almost_equal(xp.asarray([[3, 5, 6], [6, 8, 9]]), output)
+        assert output.dtype.type == xp.float32
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate20(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0, output=output)
+        assert_array_almost_equal(output, expected)
+        ndimage.convolve1d(array, weights, axis=0, output=output)
+        assert_array_almost_equal(output, expected)
+
+    def test_correlate21(self, xp):
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]])
+        expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+        weights = xp.asarray([1, 2, 1])
+        output = ndimage.correlate1d(array, weights, axis=0)
+        assert_array_almost_equal(output, expected)
+        output = ndimage.convolve1d(array, weights, axis=0)
+        assert_array_almost_equal(output, expected)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate22(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        expected = xp.asarray([[6, 12, 18], [6, 12, 18]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0,
+                            mode='wrap', output=output)
+        assert_array_almost_equal(output, expected)
+        ndimage.convolve1d(array, weights, axis=0,
+                           mode='wrap', output=output)
+        assert_array_almost_equal(output, expected)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate23(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0,
+                            mode='nearest', output=output)
+        assert_array_almost_equal(output, expected)
+        ndimage.convolve1d(array, weights, axis=0,
+                           mode='nearest', output=output)
+        assert_array_almost_equal(output, expected)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate24(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        tcor = xp.asarray([[7, 14, 21], [8, 16, 24]])
+        tcov = xp.asarray([[4, 8, 12], [5, 10, 15]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0,
+                            mode='nearest', output=output, origin=-1)
+        assert_array_almost_equal(output, tcor)
+        ndimage.convolve1d(array, weights, axis=0,
+                           mode='nearest', output=output, origin=-1)
+        assert_array_almost_equal(output, tcov)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_correlate25(self, dtype_array, dtype_output, xp):
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        weights = xp.asarray([1, 2, 1])
+        tcor = xp.asarray([[4, 8, 12], [5, 10, 15]])
+        tcov = xp.asarray([[7, 14, 21], [8, 16, 24]])
+        array = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=dtype_array)
+        output = xp.zeros((2, 3), dtype=dtype_output)
+        ndimage.correlate1d(array, weights, axis=0,
+                            mode='nearest', output=output, origin=1)
+        assert_array_almost_equal(output, tcor)
+        ndimage.convolve1d(array, weights, axis=0,
+                           mode='nearest', output=output, origin=1)
+        assert_array_almost_equal(output, tcov)
+
+    def test_correlate26(self, xp):
+        # test fix for gh-11661 (mirror extension of a length 1 signal)
+        y = ndimage.convolve1d(xp.ones(1), xp.ones(5), mode='mirror')
+        xp_assert_equal(y, xp.asarray([5.]))
+
+        y = ndimage.correlate1d(xp.ones(1), xp.ones(5), mode='mirror')
+        xp_assert_equal(y, xp.asarray([5.]))
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate_complex_kernel(self, dtype_input, dtype_kernel,
+                                      dtype_output, xp, num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype_kernel)
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @xfail_xp_backends(np_only=True,
+                       reason="output=dtype is numpy-specific",
+                       exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    @pytest.mark.parametrize('mode', ['grid-constant', 'constant'])
+    def test_correlate_complex_kernel_cval(self, dtype_input, dtype_kernel,
+                                           dtype_output, mode, xp,
+                                           num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        if is_cupy(xp) and mode == 'grid-constant':
+            pytest.xfail('https://github.com/cupy/cupy/issues/8404')
+
+        # test use of non-zero cval with complex inputs
+        # also verifies that mode 'grid-constant' does not segfault
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype_kernel)
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output, mode=mode,
+                               cval=5.0,
+                               check_warnings=num_parallel_threads == 1)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.thread_unsafe
+    def test_correlate_complex_kernel_invalid_cval(self, dtype_input,
+                                                   dtype_kernel, xp):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+
+        # cannot give complex cval with a real image
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype_kernel)
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype_input)
+        for func in [ndimage.convolve, ndimage.correlate, ndimage.convolve1d,
+                     ndimage.correlate1d]:
+            with pytest.raises((ValueError, TypeError)):
+                func(array, kernel, mode='constant', cval=5.0 + 1.0j,
+                     output=xp.complex64)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_kernel(self, dtype_input, dtype_kernel,
+                                        dtype_output, xp, num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel)
+        array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', complex_types)
+    @pytest.mark.parametrize('dtype_input', types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_kernel_cval(self, dtype_input, dtype_kernel,
+                                             dtype_output, xp,
+                                             num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel)
+        array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+                               cval=5.0,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', types)
+    @pytest.mark.parametrize('dtype_input', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate_complex_input(self, dtype_input, dtype_kernel,
+                                     dtype_output, xp, num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1]], dtype=dtype_kernel)
+        array = xp.asarray([[1, 2j, 3],
+                            [1 + 4j, 5, 6j]], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype_kernel', types)
+    @pytest.mark.parametrize('dtype_input', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_input(self, dtype_input, dtype_kernel,
+                                       dtype_output, xp, num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel)
+        array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+    @skip_xp_backends(np_only=True,
+                      reason='output=dtype is numpy-specific',
+                      exceptions=['cupy'])
+    @pytest.mark.parametrize('dtype_kernel', types)
+    @pytest.mark.parametrize('dtype_input', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_input_cval(self, dtype_input, dtype_kernel,
+                                            dtype_output, xp,
+                                            num_parallel_threads):
+        dtype_input = getattr(xp, dtype_input)
+        dtype_kernel = getattr(xp, dtype_kernel)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel)
+        array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input)
+        self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+                               cval=5 - 3j,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate_complex_input_and_kernel(self, dtype, dtype_output, xp,
+                                                num_parallel_threads):
+        dtype = getattr(xp, dtype)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype)
+        array = xp.asarray([[1, 2j, 3],
+                            [1 + 4j, 5, 6j]], dtype=dtype)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+    @skip_xp_backends(np_only=True,
+                      reason="output=dtype is numpy-specific",
+                      exceptions=['cupy'],)
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate_complex_input_and_kernel_cval(self, dtype,
+                                                     dtype_output, xp,
+                                                     num_parallel_threads):
+        dtype = getattr(xp, dtype)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([[1, 0],
+                             [0, 1 + 1j]], dtype=dtype)
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6]], dtype=dtype)
+        self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+                               cval=5.0 + 2.0j,
+                               check_warnings=num_parallel_threads == 1)
+
+    @skip_xp_backends(np_only=True, reason="output=dtype is numpy-specific")
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    @pytest.mark.thread_unsafe
+    def test_correlate1d_complex_input_and_kernel(self, dtype, dtype_output, xp,
+                                                  num_parallel_threads):
+        dtype = getattr(xp, dtype)
+        dtype_output = getattr(xp, dtype_output)
+
+        kernel = xp.asarray([1, 1 + 1j], dtype=dtype)
+        array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype)
+        self._validate_complex(xp, array, kernel, dtype_output,
+                               check_warnings=num_parallel_threads == 1)
+
+    @pytest.mark.parametrize('dtype', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_correlate1d_complex_input_and_kernel_cval(self, dtype,
+                                                       dtype_output, xp,
+                                                       num_parallel_threads):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        dtype = getattr(xp, dtype)
+        dtype_output = getattr(xp, dtype_output)
+
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8405")
+
+        kernel = xp.asarray([1, 1 + 1j], dtype=dtype)
+        array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype)
+        self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+                               cval=5.0 + 2.0j,
+                               check_warnings=num_parallel_threads == 1)
+
+    def test_gauss01(self, xp):
+        input = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=xp.float32)
+        output = ndimage.gaussian_filter(input, 0)
+        assert_array_almost_equal(output, input)
+
+    def test_gauss02(self, xp):
+        input = xp.asarray([[1, 2, 3],
+                            [2, 4, 6]], dtype=xp.float32)
+        output = ndimage.gaussian_filter(input, 1.0)
+        assert input.dtype == output.dtype
+        assert input.shape == output.shape
+
+    def test_gauss03(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8403")
+
+        # single precision data
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        output = ndimage.gaussian_filter(input, [1.0, 1.0])
+
+        assert input.dtype == output.dtype
+        assert input.shape == output.shape
+
+        # input.sum() is 49995000.0.  With single precision floats, we can't
+        # expect more than 8 digits of accuracy, so use decimal=0 in this test.
+        o_sum = xp.sum(output, dtype=xp.float64)
+        i_sum = xp.sum(input, dtype=xp.float64)
+        assert_almost_equal(o_sum, i_sum, decimal=0)
+        assert sumsq(input, output) > 1.0
+
+    def test_gauss04(self, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        otype = xp.float64
+        output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype)
+        assert output.dtype.type == xp.float64
+        assert input.shape == output.shape
+        assert sumsq(input, output) > 1.0
+
+    def test_gauss05(self, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        otype = xp.float64
+        output = ndimage.gaussian_filter(input, [1.0, 1.0],
+                                         order=1, output=otype)
+        assert output.dtype.type == xp.float64
+        assert input.shape == output.shape
+        assert sumsq(input, output) > 1.0
+
+    def test_gauss06(self, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        otype = xp.float64
+        output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype)
+        output2 = ndimage.gaussian_filter(input, 1.0, output=otype)
+        assert_array_almost_equal(output1, output2)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_gauss_memory_overlap(self, xp):
+        input = xp.arange(100 * 100, dtype=xp.float32)
+        input = xp.reshape(input, (100, 100))
+        output1 = ndimage.gaussian_filter(input, 1.0)
+        ndimage.gaussian_filter(input, 1.0, output=input)
+        assert_array_almost_equal(output1, input)
+
+    @pytest.mark.parametrize(('filter_func', 'extra_args', 'size0', 'size'),
+                             [(ndimage.gaussian_filter, (), 0, 1.0),
+                              (ndimage.uniform_filter, (), 1, 3),
+                              (ndimage.minimum_filter, (), 1, 3),
+                              (ndimage.maximum_filter, (), 1, 3),
+                              (ndimage.median_filter, (), 1, 3),
+                              (ndimage.rank_filter, (1,), 1, 3),
+                              (ndimage.percentile_filter, (40,), 1, 3)])
+    @pytest.mark.parametrize(
+        'axes',
+        tuple(itertools.combinations(range(-3, 3), 1))
+        + tuple(itertools.combinations(range(-3, 3), 2))
+        + ((0, 1, 2),))
+    def test_filter_axes(self, filter_func, extra_args, size0, size, axes, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        # Note: `size` is called `sigma` in `gaussian_filter`
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+
+        if len(set(ax % array.ndim for ax in axes)) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError, match="axes must be unique"):
+                filter_func(array, *extra_args, size, axes=axes)
+            return
+        output = filter_func(array, *extra_args, size, axes=axes)
+
+        # result should be equivalent to sigma=0.0/size=1 on unfiltered axes
+        axes = xp.asarray(axes)
+        all_sizes = tuple(size if ax in (axes % array.ndim) else size0
+                          for ax in range(array.ndim))
+        expected = filter_func(array, *extra_args, all_sizes)
+        xp_assert_close(output, expected)
+
+    @skip_xp_backends("cupy",
+                      reason="these filters do not yet have axes support",
+    )
+    @pytest.mark.parametrize(('filter_func', 'kwargs'),
+                             [(ndimage.laplace, {}),
+                              (ndimage.gaussian_gradient_magnitude,
+                               {"sigma": 1.0}),
+                              (ndimage.gaussian_laplace, {"sigma": 0.5})])
+    def test_derivative_filter_axes(self, xp, filter_func, kwargs):
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+
+        # duplicate axes raises an error
+        with pytest.raises(ValueError, match="axes must be unique"):
+            filter_func(array, axes=(1, 1), **kwargs)
+
+        # compare results to manually looping over the non-filtered axes
+        output = filter_func(array, axes=(1, 2), **kwargs)
+        expected = xp.empty_like(output)
+        expected = []
+        for i in range(array.shape[0]):
+            expected.append(filter_func(array[i, ...], **kwargs))
+        expected = xp.stack(expected, axis=0)
+        xp_assert_close(output, expected)
+
+        output = filter_func(array, axes=(0, -1), **kwargs)
+        expected = []
+        for i in range(array.shape[1]):
+            expected.append(filter_func(array[:, i, :], **kwargs))
+        expected = xp.stack(expected, axis=1)
+        xp_assert_close(output, expected)
+
+        output = filter_func(array, axes=(1), **kwargs)
+        expected = []
+        for i in range(array.shape[0]):
+            exp_inner = []
+            for j in range(array.shape[2]):
+                exp_inner.append(filter_func(array[i, :, j], **kwargs))
+            expected.append(xp.stack(exp_inner, axis=-1))
+        expected = xp.stack(expected, axis=0)
+        xp_assert_close(output, expected)
+
+    @skip_xp_backends("cupy",
+                      reason="generic_filter does not yet have axes support",
+    )
+    @pytest.mark.parametrize(
+        'axes',
+        tuple(itertools.combinations(range(-3, 3), 1))
+        + tuple(itertools.combinations(range(-3, 3), 2))
+        + ((0, 1, 2),))
+    def test_generic_filter_axes(self, xp, axes):
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+        size = 3
+        if len(set(ax % array.ndim for ax in axes)) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError, match="axes must be unique"):
+                ndimage.generic_filter(array, np.amax, size=size, axes=axes)
+            return
+
+        # choose np.amax as the function so we can compare to maximum_filter
+        output = ndimage.generic_filter(array, np.amax, size=size, axes=axes)
+        expected = ndimage.maximum_filter(array, size=size, axes=axes)
+        xp_assert_close(output, expected)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8339",
+    )
+    @pytest.mark.parametrize('func', [ndimage.correlate, ndimage.convolve])
+    @pytest.mark.parametrize(
+        'dtype', [np.float32, np.float64, np.complex64, np.complex128]
+    )
+    @pytest.mark.parametrize(
+        'axes', tuple(itertools.combinations(range(-3, 3), 2))
+    )
+    @pytest.mark.parametrize('origin', [(0, 0), (-1, 1)])
+    def test_correlate_convolve_axes(self, xp, func, dtype, axes, origin):
+        array = xp.asarray(np.arange(6 * 8 * 12, dtype=dtype).reshape(6, 8, 12))
+        weights = xp.arange(3 * 5)
+        weights = xp.reshape(weights, (3, 5))
+        axes = tuple(ax % array.ndim for ax in axes)
+        if len(tuple(set(axes))) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError):
+                func(array, weights=weights, axes=axes, origin=origin)
+            return
+        output = func(array, weights=weights, axes=axes, origin=origin)
+
+        missing_axis = tuple(set(range(3)) - set(axes))[0]
+        # module 'torch' has no attribute 'expand_dims' so use reshape instead
+        #    weights_3d = xp.expand_dims(weights, axis=missing_axis)
+        shape_3d = (
+            weights.shape[:missing_axis] + (1,) + weights.shape[missing_axis:]
+        )
+        weights_3d = xp.reshape(weights, shape_3d)
+        origin_3d = [0, 0, 0]
+        for i, ax in enumerate(axes):
+            origin_3d[ax] = origin[i]
+        expected = func(array, weights=weights_3d, origin=origin_3d)
+        xp_assert_close(output, expected)
+
+    kwargs_gauss = dict(radius=[4, 2, 3], order=[0, 1, 2],
+                        mode=['reflect', 'nearest', 'constant'])
+    kwargs_other = dict(origin=(-1, 0, 1),
+                        mode=['reflect', 'nearest', 'constant'])
+    kwargs_rank = dict(origin=(-1, 0, 1))
+
+    @skip_xp_backends("array_api_strict",
+         reason="fancy indexing is only available in 2024 version",
+    )
+    @pytest.mark.parametrize("filter_func, size0, size, kwargs",
+                             [(ndimage.gaussian_filter, 0, 1.0, kwargs_gauss),
+                              (ndimage.uniform_filter, 1, 3, kwargs_other),
+                              (ndimage.maximum_filter, 1, 3, kwargs_other),
+                              (ndimage.minimum_filter, 1, 3, kwargs_other),
+                              (ndimage.median_filter, 1, 3, kwargs_rank),
+                              (ndimage.rank_filter, 1, 3, kwargs_rank),
+                              (ndimage.percentile_filter, 1, 3, kwargs_rank)])
+    @pytest.mark.parametrize('axes', itertools.combinations(range(-3, 3), 2))
+    def test_filter_axes_kwargs(self, filter_func, size0, size, kwargs, axes, xp):
+
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+
+        kwargs = {key: np.array(val) for key, val in kwargs.items()}
+        axes = np.array(axes)
+        n_axes = axes.size
+
+        if filter_func == ndimage.rank_filter:
+            args = (2,)  # (rank,)
+        elif filter_func == ndimage.percentile_filter:
+            args = (30,)  # (percentile,)
+        else:
+            args = ()
+
+        # form kwargs that specify only the axes in `axes`
+        reduced_kwargs = {key: val[axes] for key, val in kwargs.items()}
+        if len(set(axes % array.ndim)) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError, match="axes must be unique"):
+                filter_func(array, *args, [size]*n_axes, axes=axes,
+                            **reduced_kwargs)
+            return
+
+        output = filter_func(array, *args, [size]*n_axes, axes=axes,
+                             **reduced_kwargs)
+
+        # result should be equivalent to sigma=0.0/size=1 on unfiltered axes
+        size_3d = np.full(array.ndim, fill_value=size0)
+        size_3d[axes] = size
+        size_3d = [size_3d[i] for i in range(size_3d.shape[0])]
+        if 'origin' in kwargs:
+            # origin should be zero on the axis that has size 0
+            origin = np.asarray([0, 0, 0])
+            origin[axes] = reduced_kwargs['origin']
+            origin = xp.asarray(origin)
+            kwargs['origin'] = origin
+        expected = filter_func(array, *args, size_3d, **kwargs)
+        xp_assert_close(output, expected)
+
+
+    @pytest.mark.parametrize("filter_func, kwargs",
+                             [(ndimage.convolve, {}),
+                              (ndimage.correlate, {}),
+                              (ndimage.minimum_filter, {}),
+                              (ndimage.maximum_filter, {}),
+                              (ndimage.median_filter, {}),
+                              (ndimage.rank_filter, {"rank": 1}),
+                              (ndimage.percentile_filter, {"percentile": 30})])
+    def test_filter_weights_subset_axes_origins(self, filter_func, kwargs, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        axes = (-2, -1)
+        origins = (0, 1)
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+
+        # weights with ndim matching len(axes)
+        footprint = np.ones((3, 5), dtype=bool)
+        footprint[0, 1] = 0  # make non-separable
+        footprint = xp.asarray(footprint)
+
+        if filter_func in (ndimage.convolve, ndimage.correlate):
+            kwargs["weights"] = footprint
+        else:
+            kwargs["footprint"] = footprint
+        kwargs["axes"] = axes
+
+        output = filter_func(array, origin=origins, **kwargs)
+
+        output0 = filter_func(array, origin=0, **kwargs)
+
+        # output has origin shift on last axis relative to output0, so
+        # expect shifted arrays to be equal.
+        if filter_func == ndimage.convolve:
+            # shift is in the opposite direction for convolve because it
+            # flips the weights array and negates the origin values.
+            xp_assert_equal(
+                output[:, :, :-origins[1]], output0[:, :, origins[1]:])
+        else:
+            xp_assert_equal(
+                output[:, :, origins[1]:], output0[:, :, :-origins[1]])
+
+
+    @pytest.mark.parametrize(
+        'filter_func, args',
+        [(ndimage.convolve, (np.ones((3, 3, 3)),)),  # args = (weights,)
+         (ndimage.correlate,(np.ones((3, 3, 3)),)),  # args = (weights,)
+         (ndimage.gaussian_filter, (1.0,)),      # args = (sigma,)
+         (ndimage.uniform_filter, (3,)),         # args = (size,)
+         (ndimage.minimum_filter, (3,)),         # args = (size,)
+         (ndimage.maximum_filter, (3,)),         # args = (size,)
+         (ndimage.median_filter, (3,)),          # args = (size,)
+         (ndimage.rank_filter, (2, 3)),          # args = (rank, size)
+         (ndimage.percentile_filter, (30, 3))])  # args = (percentile, size)
+    @pytest.mark.parametrize(
+        'axes', [(1.5,), (0, 1, 2, 3), (3,), (-4,)]
+    )
+    def test_filter_invalid_axes(self, filter_func, args, axes, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+        args = [
+            xp.asarray(arg) if isinstance(arg, np.ndarray) else arg
+            for arg in args
+        ]
+        if any(isinstance(ax, float) for ax in axes):
+            error_class = TypeError
+            match = "cannot be interpreted as an integer"
+        else:
+            error_class = ValueError
+            match = "out of range"
+        with pytest.raises(error_class, match=match):
+            filter_func(array, *args, axes=axes)
+
+    @pytest.mark.parametrize(
+        'filter_func, kwargs',
+        [(ndimage.convolve, {}),
+         (ndimage.correlate, {}),
+         (ndimage.minimum_filter, {}),
+         (ndimage.maximum_filter, {}),
+         (ndimage.median_filter, {}),
+         (ndimage.rank_filter, dict(rank=3)),
+         (ndimage.percentile_filter, dict(percentile=30))])
+    @pytest.mark.parametrize(
+        'axes', [(0, ), (1, 2), (0, 1, 2)]
+    )
+    @pytest.mark.parametrize('separable_footprint', [False, True])
+    def test_filter_invalid_footprint_ndim(self, filter_func, kwargs, axes,
+                                           separable_footprint, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+        # create a footprint with one too many dimensions
+        footprint = np.ones((3,) * (len(axes) + 1))
+        if not separable_footprint:
+            footprint[(0,) * footprint.ndim] = 0
+        footprint = xp.asarray(footprint)
+        if (filter_func in [ndimage.minimum_filter, ndimage.maximum_filter]
+            and separable_footprint):
+            match = "sequence argument must have length equal to input rank"
+        elif filter_func in [ndimage.convolve, ndimage.correlate]:
+            match = re.escape(f"weights.ndim ({footprint.ndim}) must match "
+                              f"len(axes) ({len(axes)})")
+        else:
+            match = re.escape(f"footprint.ndim ({footprint.ndim}) must match "
+                              f"len(axes) ({len(axes)})")
+        if filter_func in [ndimage.convolve, ndimage.correlate]:
+            kwargs["weights"] = footprint
+        else:
+            kwargs["footprint"] = footprint
+        with pytest.raises(RuntimeError, match=match):
+            filter_func(array, axes=axes, **kwargs)
+
+    @pytest.mark.parametrize('n_mismatch', [1, 3])
+    @pytest.mark.parametrize('filter_func, kwargs, key, val',
+                             _cases_axes_tuple_length_mismatch())
+    def test_filter_tuple_length_mismatch(self, n_mismatch, filter_func,
+                                          kwargs, key, val, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        # Test for the intended RuntimeError when a kwargs has an invalid size
+        array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+        array = xp.reshape(array, (6, 8, 12))
+        axes = (0, 1)
+        kwargs = dict(**kwargs, axes=axes)
+        kwargs[key] = (val,) * n_mismatch
+        if filter_func in [ndimage.convolve, ndimage.correlate]:
+            kwargs["weights"] = xp.ones((5,) * len(axes))
+        err_msg = "sequence argument must have length equal to input rank"
+        with pytest.raises(RuntimeError, match=err_msg):
+            filter_func(array, **kwargs)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_prewitt01(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1)
+        output = ndimage.prewitt(array, 0)
+        assert_array_almost_equal(t, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_prewitt02(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1)
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.prewitt(array, 0, output)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_prewitt03(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp) and dtype in [xp.uint32, xp.uint64]:
+            pytest.xfail("uint UB? XXX")
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 0)
+        output = ndimage.prewitt(array, 1)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_prewitt04(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.prewitt(array, -1)
+        output = ndimage.prewitt(array, 1)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_sobel01(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1)
+        output = ndimage.sobel(array, 0)
+        assert_array_almost_equal(t, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.",)
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_sobel02(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1)
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.sobel(array, 0, output)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_sobel03(self, dtype, xp):
+        if is_cupy(xp) and dtype in ["uint32", "uint64"]:
+            pytest.xfail("uint UB? XXX")
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1)
+        t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 0)
+        output = xp.zeros(array.shape, dtype=dtype)
+        output = ndimage.sobel(array, 1)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_sobel04(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        t = ndimage.sobel(array, -1)
+        output = ndimage.sobel(array, 1)
+        assert_array_almost_equal(t, output)
+
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_laplace01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0)
+        tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1)
+        output = ndimage.laplace(array)
+        assert_array_almost_equal(tmp1 + tmp2, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only",)
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_laplace02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0)
+        tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1)
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.laplace(array, output=output)
+        assert_array_almost_equal(tmp1 + tmp2, output)
+
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_gaussian_laplace01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0])
+        tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2])
+        output = ndimage.gaussian_laplace(array, 1.0)
+        assert_array_almost_equal(tmp1 + tmp2, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only")
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_gaussian_laplace02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0])
+        tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2])
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.gaussian_laplace(array, 1.0, output)
+        assert_array_almost_equal(tmp1 + tmp2, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @pytest.mark.parametrize('dtype', types + complex_types)
+    def test_generic_laplace01(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        def derivative2(input, axis, output, mode, cval, a, b):
+            sigma = np.asarray([a, b / 2.0])
+            order = [0] * input.ndim
+            order[axis] = 2
+            return ndimage.gaussian_filter(input, sigma, order,
+                                           output, mode, cval)
+
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = xp.zeros(array.shape, dtype=dtype)
+        tmp = ndimage.generic_laplace(array, derivative2,
+                                      extra_arguments=(1.0,),
+                                      extra_keywords={'b': 2.0})
+        ndimage.gaussian_laplace(array, 1.0, output)
+        assert_array_almost_equal(tmp, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only")
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_gaussian_gradient_magnitude01(self, dtype, xp):
+        is_int_dtype = dtype == "int32"
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0])
+        tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1])
+        output = ndimage.gaussian_gradient_magnitude(array, 1.0)
+        expected = tmp1 * tmp1 + tmp2 * tmp2
+
+        astype = array_namespace(expected).astype
+        expected_float = astype(expected, xp.float64) if is_int_dtype else expected
+        expected = astype(xp.sqrt(expected_float), dtype)
+        xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only")
+    @pytest.mark.parametrize('dtype',
+                             ["int32", "float32", "float64",
+                              "complex64", "complex128"])
+    def test_gaussian_gradient_magnitude02(self, dtype, xp):
+        is_int_dtype = dtype == 'int32'
+        dtype = getattr(xp, dtype)
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype) * 100
+        tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0])
+        tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1])
+        output = xp.zeros(array.shape, dtype=dtype)
+        ndimage.gaussian_gradient_magnitude(array, 1.0, output)
+        expected = tmp1 * tmp1 + tmp2 * tmp2
+
+        astype = array_namespace(expected).astype
+        fl_expected = astype(expected, xp.float64) if is_int_dtype else expected
+
+        expected = astype(xp.sqrt(fl_expected), dtype)
+        xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+    def test_generic_gradient_magnitude01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=xp.float64)
+
+        def derivative(input, axis, output, mode, cval, a, b):
+            sigma = [a, b / 2.0]
+            order = [0] * input.ndim
+            order[axis] = 1
+            return ndimage.gaussian_filter(input, sigma, order, output, mode, cval)
+
+        tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0)
+        tmp2 = ndimage.generic_gradient_magnitude(
+            array, derivative, extra_arguments=(1.0,),
+            extra_keywords={'b': 2.0})
+        assert_array_almost_equal(tmp1, tmp2)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    def test_uniform01(self, xp):
+        array = xp.asarray([2, 4, 6])
+        size = 2
+        output = ndimage.uniform_filter1d(array, size, origin=-1)
+        assert_array_almost_equal(xp.asarray([3, 5, 6]), output)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    def test_uniform01_complex(self, xp):
+        array = xp.asarray([2 + 1j, 4 + 2j, 6 + 3j], dtype=xp.complex128)
+        size = 2
+        output = ndimage.uniform_filter1d(array, size, origin=-1)
+        assert_array_almost_equal(xp.real(output), xp.asarray([3., 5, 6]))
+        assert_array_almost_equal(xp.imag(output), xp.asarray([1.5, 2.5, 3]))
+
+    def test_uniform02(self, xp):
+        array = xp.asarray([1, 2, 3])
+        filter_shape = [0]
+        output = ndimage.uniform_filter(array, filter_shape)
+        assert_array_almost_equal(array, output)
+
+    def test_uniform03(self, xp):
+        array = xp.asarray([1, 2, 3])
+        filter_shape = [1]
+        output = ndimage.uniform_filter(array, filter_shape)
+        assert_array_almost_equal(array, output)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    def test_uniform04(self, xp):
+        array = xp.asarray([2, 4, 6])
+        filter_shape = [2]
+        output = ndimage.uniform_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([2, 3, 5]), output)
+
+    def test_uniform05(self, xp):
+        array = xp.asarray([])
+        filter_shape = [1]
+        output = ndimage.uniform_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([]), output)
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    @pytest.mark.parametrize('dtype_array', types)
+    @pytest.mark.parametrize('dtype_output', types)
+    def test_uniform06(self, dtype_array, dtype_output, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        filter_shape = [2, 2]
+        array = xp.asarray([[4, 8, 12],
+                            [16, 20, 24]], dtype=dtype_array)
+        output = ndimage.uniform_filter(
+            array, filter_shape, output=dtype_output)
+        assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output)
+        assert output.dtype.type == dtype_output
+
+    @skip_xp_backends("cupy",
+                      reason="https://github.com/cupy/cupy/pull/8430",
+    )
+    @pytest.mark.parametrize('dtype_array', complex_types)
+    @pytest.mark.parametrize('dtype_output', complex_types)
+    def test_uniform06_complex(self, dtype_array, dtype_output, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("output=dtype is numpy-specific")
+
+        dtype_array = getattr(xp, dtype_array)
+        dtype_output = getattr(xp, dtype_output)
+
+        filter_shape = [2, 2]
+        array = xp.asarray([[4, 8 + 5j, 12],
+                            [16, 20, 24]], dtype=dtype_array)
+        output = ndimage.uniform_filter(
+            array, filter_shape, output=dtype_output)
+        assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output.real)
+        assert output.dtype.type == dtype_output
+
+    def test_minimum_filter01(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        filter_shape = xp.asarray([2])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output)
+
+    def test_minimum_filter02(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        filter_shape = xp.asarray([3])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output)
+
+    def test_minimum_filter03(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        filter_shape = xp.asarray([2])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([3, 2, 2, 1, 1]), output)
+
+    def test_minimum_filter04(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        filter_shape = xp.asarray([3])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([2, 2, 1, 1, 1]), output)
+
+    def test_minimum_filter05(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        filter_shape = xp.asarray([2, 3])
+        output = ndimage.minimum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 2, 1, 1, 1],
+                                              [5, 3, 3, 1, 1]]), output)
+
+    @skip_xp_backends("jax.numpy", reason="assignment destination is read-only")
+    def test_minimum_filter05_overlap(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        filter_shape = xp.asarray([2, 3])
+        ndimage.minimum_filter(array, filter_shape, output=array)
+        assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 2, 1, 1, 1],
+                                              [5, 3, 3, 1, 1]]), array)
+
+    def test_minimum_filter06(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 1, 1], [1, 1, 1]])
+        output = ndimage.minimum_filter(array, footprint=footprint)
+        assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 2, 1, 1, 1],
+                                              [5, 3, 3, 1, 1]]), output)
+        # separable footprint should allow mode sequence
+        output2 = ndimage.minimum_filter(array, footprint=footprint,
+                                         mode=['reflect', 'reflect'])
+        assert_array_almost_equal(output2, output)
+
+    def test_minimum_filter07(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.minimum_filter(array, footprint=footprint)
+        assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1]]), output)
+        with assert_raises(RuntimeError):
+            ndimage.minimum_filter(array, footprint=footprint,
+                                   mode=['reflect', 'constant'])
+
+    def test_minimum_filter08(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.minimum_filter(array, footprint=footprint, origin=-1)
+        assert_array_almost_equal(xp.asarray([[3, 1, 3, 1, 1],
+                                              [5, 3, 3, 1, 1],
+                                              [3, 3, 1, 1, 1]]), output)
+
+    def test_minimum_filter09(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.minimum_filter(array, footprint=footprint,
+                                        origin=[-1, 0])
+        assert_array_almost_equal(xp.asarray([[2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1],
+                                              [5, 3, 3, 1, 1]]), output)
+
+    def test_maximum_filter01(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        filter_shape = xp.asarray([2])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([1, 2, 3, 4, 5]), output)
+
+    def test_maximum_filter02(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        filter_shape = xp.asarray([3])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([2, 3, 4, 5, 5]), output)
+
+    def test_maximum_filter03(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        filter_shape = xp.asarray([2])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+
+    def test_maximum_filter04(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        filter_shape = xp.asarray([3])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([3, 5, 5, 5, 4]), output)
+
+    def test_maximum_filter05(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        filter_shape = xp.asarray([2, 3])
+        output = ndimage.maximum_filter(array, filter_shape)
+        assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+                                              [7, 9, 9, 9, 5],
+                                              [8, 9, 9, 9, 7]]), output)
+
+    def test_maximum_filter06(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 1, 1], [1, 1, 1]])
+        output = ndimage.maximum_filter(array, footprint=footprint)
+        assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+                                              [7, 9, 9, 9, 5],
+                                              [8, 9, 9, 9, 7]]), output)
+        # separable footprint should allow mode sequence
+        output2 = ndimage.maximum_filter(array, footprint=footprint,
+                                         mode=['reflect', 'reflect'])
+        assert_array_almost_equal(output2, output)
+
+    def test_maximum_filter07(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.maximum_filter(array, footprint=footprint)
+        assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+                                              [7, 7, 9, 9, 5],
+                                              [7, 9, 8, 9, 7]]), output)
+        # non-separable footprint should not allow mode sequence
+        with assert_raises(RuntimeError):
+            ndimage.maximum_filter(array, footprint=footprint,
+                                   mode=['reflect', 'reflect'])
+
+    def test_maximum_filter08(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.maximum_filter(array, footprint=footprint, origin=-1)
+        assert_array_almost_equal(xp.asarray([[7, 9, 9, 5, 5],
+                                              [9, 8, 9, 7, 5],
+                                              [8, 8, 7, 7, 7]]), output)
+
+    def test_maximum_filter09(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.maximum_filter(array, footprint=footprint,
+                                        origin=[-1, 0])
+        assert_array_almost_equal(xp.asarray([[7, 7, 9, 9, 5],
+                                              [7, 9, 8, 9, 7],
+                                              [8, 8, 8, 7, 7]]), output)
+
+    @pytest.mark.parametrize(
+        'axes', tuple(itertools.combinations(range(-3, 3), 2))
+    )
+    @pytest.mark.parametrize(
+        'filter_func, kwargs',
+        [(ndimage.minimum_filter, {}),
+         (ndimage.maximum_filter, {}),
+         (ndimage.median_filter, {}),
+         (ndimage.rank_filter, dict(rank=3)),
+         (ndimage.percentile_filter, dict(percentile=60))]
+    )
+    def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/pull/8339")
+
+        array = xp.arange(6 * 8 * 12, dtype=xp.float32)
+        array = xp.reshape(array, (6, 8, 12))
+        # use 2D triangular footprint because it is non-separable
+        footprint = xp.asarray(np.tri(5))
+        axes = np.asarray(axes)
+
+        if len(set(axes % array.ndim)) != len(axes):
+            # parametrized cases with duplicate axes raise an error
+            with pytest.raises(ValueError):
+                filter_func(array, footprint=footprint, axes=axes, **kwargs)
+            return
+        output = filter_func(array, footprint=footprint, axes=axes, **kwargs)
+
+        missing_axis = tuple(set(range(3)) - set(axes % array.ndim))[0]
+
+        expand_dims = array_namespace(footprint).expand_dims
+        footprint_3d = expand_dims(footprint, axis=missing_axis)
+        expected = filter_func(array, footprint=footprint_3d, **kwargs)
+        xp_assert_close(output, expected)
+
+    def test_rank01(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        output = ndimage.rank_filter(array, 1, size=2)
+        xp_assert_equal(array, output)
+        output = ndimage.percentile_filter(array, 100, size=2)
+        xp_assert_equal(array, output)
+        output = ndimage.median_filter(array, 2)
+        xp_assert_equal(array, output)
+
+    def test_rank02(self, xp):
+        array = xp.asarray([1, 2, 3, 4, 5])
+        output = ndimage.rank_filter(array, 1, size=[3])
+        xp_assert_equal(array, output)
+        output = ndimage.percentile_filter(array, 50, size=3)
+        xp_assert_equal(array, output)
+        output = ndimage.median_filter(array, (3,))
+        xp_assert_equal(array, output)
+
+    def test_rank03(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        output = ndimage.rank_filter(array, 1, size=[2])
+        xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+        output = ndimage.percentile_filter(array, 100, size=2)
+        xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+
+    def test_rank04(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        expected = xp.asarray([3, 3, 2, 4, 4])
+        output = ndimage.rank_filter(array, 1, size=3)
+        xp_assert_equal(expected, output)
+        output = ndimage.percentile_filter(array, 50, size=3)
+        xp_assert_equal(expected, output)
+        output = ndimage.median_filter(array, size=3)
+        xp_assert_equal(expected, output)
+
+    def test_rank05(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        expected = xp.asarray([3, 3, 2, 4, 4])
+        output = ndimage.rank_filter(array, -2, size=3)
+        xp_assert_equal(expected, output)
+
+    def test_rank06(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]])
+        expected = [[2, 2, 1, 1, 1],
+                    [3, 3, 2, 1, 1],
+                    [5, 5, 3, 3, 1]]
+        expected = xp.asarray(expected)
+        output = ndimage.rank_filter(array, 1, size=[2, 3])
+        xp_assert_equal(expected, output)
+        output = ndimage.percentile_filter(array, 17, size=(2, 3))
+        xp_assert_equal(expected, output)
+
+    @skip_xp_backends("jax.numpy",
+        reason="assignment destination is read-only",
+    )
+    def test_rank06_overlap(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8406")
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]])
+
+        asarray = array_namespace(array).asarray
+        array_copy = asarray(array, copy=True)
+        expected = [[2, 2, 1, 1, 1],
+                    [3, 3, 2, 1, 1],
+                    [5, 5, 3, 3, 1]]
+        expected = xp.asarray(expected)
+        ndimage.rank_filter(array, 1, size=[2, 3], output=array)
+        xp_assert_equal(expected, array)
+
+        ndimage.percentile_filter(array_copy, 17, size=(2, 3),
+                                  output=array_copy)
+        xp_assert_equal(expected, array_copy)
+
+    def test_rank07(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]])
+        expected = [[3, 5, 5, 5, 4],
+                    [5, 5, 7, 5, 4],
+                    [6, 8, 8, 7, 5]]
+        expected = xp.asarray(expected)
+        output = ndimage.rank_filter(array, -2, size=[2, 3])
+        xp_assert_equal(expected, output)
+
+    def test_rank08(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]])
+        expected = [[3, 3, 2, 4, 4],
+                    [5, 5, 5, 4, 4],
+                    [5, 6, 7, 5, 5]]
+        expected = xp.asarray(expected)
+        output = ndimage.percentile_filter(array, 50.0, size=(2, 3))
+        xp_assert_equal(expected, output)
+        output = ndimage.rank_filter(array, 3, size=(2, 3))
+        xp_assert_equal(expected, output)
+        output = ndimage.median_filter(array, size=(2, 3))
+        xp_assert_equal(expected, output)
+
+        # non-separable: does not allow mode sequence
+        with assert_raises(RuntimeError):
+            ndimage.percentile_filter(array, 50.0, size=(2, 3),
+                                      mode=['reflect', 'constant'])
+        with assert_raises(RuntimeError):
+            ndimage.rank_filter(array, 3, size=(2, 3), mode=['reflect']*2)
+        with assert_raises(RuntimeError):
+            ndimage.median_filter(array, size=(2, 3), mode=['reflect']*2)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank09(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[3, 3, 2, 4, 4],
+                    [3, 5, 2, 5, 1],
+                    [5, 5, 8, 3, 5]]
+        expected = xp.asarray(expected)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 1, footprint=footprint)
+        assert_array_almost_equal(expected, output)
+        output = ndimage.percentile_filter(array, 35, footprint=footprint)
+        assert_array_almost_equal(expected, output)
+
+    def test_rank10(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        expected = [[2, 2, 1, 1, 1],
+                    [2, 3, 1, 3, 1],
+                    [5, 5, 3, 3, 1]]
+        expected = xp.asarray(expected)
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.rank_filter(array, 0, footprint=footprint)
+        xp_assert_equal(expected, output)
+        output = ndimage.percentile_filter(array, 0.0, footprint=footprint)
+        xp_assert_equal(expected, output)
+
+    def test_rank11(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        expected = [[3, 5, 5, 5, 4],
+                    [7, 7, 9, 9, 5],
+                    [7, 9, 8, 9, 7]]
+        expected = xp.asarray(expected)
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.rank_filter(array, -1, footprint=footprint)
+        xp_assert_equal(expected, output)
+        output = ndimage.percentile_filter(array, 100.0, footprint=footprint)
+        xp_assert_equal(expected, output)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank12(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        expected = [[3, 3, 2, 4, 4],
+                    [3, 5, 2, 5, 1],
+                    [5, 5, 8, 3, 5]]
+        expected = xp.asarray(expected, dtype=dtype)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 1, footprint=footprint)
+        assert_array_almost_equal(expected, output)
+        output = ndimage.percentile_filter(array, 50.0,
+                                           footprint=footprint)
+        xp_assert_equal(expected, output)
+        output = ndimage.median_filter(array, footprint=footprint)
+        xp_assert_equal(expected, output)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank13(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        expected = [[5, 2, 5, 1, 1],
+                    [5, 8, 3, 5, 5],
+                    [6, 6, 5, 5, 5]]
+        expected = xp.asarray(expected, dtype=dtype)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 1, footprint=footprint,
+                                     origin=-1)
+        xp_assert_equal(expected, output)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank14(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        expected = [[3, 5, 2, 5, 1],
+                    [5, 5, 8, 3, 5],
+                    [5, 6, 6, 5, 5]]
+        expected = xp.asarray(expected, dtype=dtype)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 1, footprint=footprint,
+                                     origin=[-1, 0])
+        xp_assert_equal(expected, output)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_rank15(self, dtype, xp):
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, dtype)
+        expected = [[2, 3, 1, 4, 1],
+                    [5, 3, 7, 1, 1],
+                    [5, 5, 3, 3, 3]]
+        expected = xp.asarray(expected, dtype=dtype)
+        footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [5, 8, 3, 7, 1],
+                            [5, 6, 9, 3, 5]], dtype=dtype)
+        output = ndimage.rank_filter(array, 0, footprint=footprint,
+                                     origin=[-1, 0])
+        xp_assert_equal(expected, output)
+
+    def test_rank16(self, xp):
+        # test that lists are accepted and interpreted as numpy arrays
+        array = [3, 2, 5, 1, 4]
+        # expected values are: median(3, 2, 5) = 3, median(2, 5, 1) = 2, etc
+        expected = np.asarray([3, 3, 2, 4, 4])
+        output = ndimage.rank_filter(array, -2, size=3)
+        xp_assert_equal(expected, output)
+
+    def test_rank17(self, xp):
+        array = xp.asarray([3, 2, 5, 1, 4])
+        if not hasattr(array, 'flags'):
+            return
+        array.flags.writeable = False
+        expected = xp.asarray([3, 3, 2, 4, 4])
+        output = ndimage.rank_filter(array, -2, size=3)
+        xp_assert_equal(expected, output)
+
+    def test_rank18(self, xp):
+        # module 'array_api_strict' has no attribute 'float16'
+        tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64',
+                         'uint8', 'uint16', 'uint32', 'uint64']
+        for dtype_str in tested_dtypes:
+            dtype = getattr(xp, dtype_str)
+            x = xp.asarray([3, 2, 5, 1, 4], dtype=dtype)
+            y = ndimage.rank_filter(x, -2, size=3)
+            assert y.dtype == x.dtype
+
+    def test_rank19(self, xp):
+        # module 'array_api_strict' has no attribute 'float16'
+        tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64',
+                         'uint8', 'uint16', 'uint32', 'uint64']
+        for dtype_str in tested_dtypes:
+            dtype = getattr(xp, dtype_str)
+            x = xp.asarray([[3, 2, 5, 1, 4], [3, 2, 5, 1, 4]], dtype=dtype)
+            y = ndimage.rank_filter(x, -2, size=3)
+            assert y.dtype == x.dtype
+
+    @skip_xp_backends(np_only=True, reason="off-by-ones on alt backends")
+    @pytest.mark.parametrize('dtype', types)
+    def test_generic_filter1d01(self, dtype, xp):
+        weights = xp.asarray([1.1, 2.2, 3.3])
+
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not support extra_arguments")
+
+        def _filter_func(input, output, fltr, total):
+            fltr = fltr / total
+            for ii in range(input.shape[0] - 2):
+                output[ii] = input[ii] * fltr[0]
+                output[ii] += input[ii + 1] * fltr[1]
+                output[ii] += input[ii + 2] * fltr[2]
+        a = np.arange(12, dtype=dtype).reshape(3, 4)
+        a = xp.asarray(a)
+        dtype = getattr(xp, dtype)
+
+        r1 = ndimage.correlate1d(a, weights / xp.sum(weights), 0, origin=-1)
+        r2 = ndimage.generic_filter1d(
+            a, _filter_func, 3, axis=0, origin=-1,
+            extra_arguments=(weights,),
+            extra_keywords={'total': xp.sum(weights)})
+        assert_array_almost_equal(r1, r2)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_generic_filter01(self, dtype, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not support extra_arguments")
+        if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+            pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype_str = dtype
+        dtype = getattr(xp, dtype_str)
+
+        filter_ = xp.asarray([[1.0, 2.0], [3.0, 4.0]])
+        footprint = xp.asarray([[1.0, 0.0], [0.0, 1.0]])
+        cf = xp.asarray([1., 4.])
+
+        def _filter_func(buffer, weights, total=1.0):
+            weights = np.asarray(cf) / np.asarray(total)
+            return np.sum(buffer * weights)
+
+        a = np.arange(12, dtype=dtype_str).reshape(3, 4)
+        a = xp.asarray(a)
+        r1 = ndimage.correlate(a, filter_ * footprint)
+        if dtype_str in float_types:
+            r1 /= 5
+        else:
+            r1 //= 5
+        r2 = ndimage.generic_filter(
+            a, _filter_func, footprint=footprint, extra_arguments=(cf,),
+            extra_keywords={'total': xp.sum(cf)})
+        assert_array_almost_equal(r1, r2)
+
+        # generic_filter doesn't allow mode sequence
+        with assert_raises(RuntimeError):
+            r2 = ndimage.generic_filter(
+                a, _filter_func, mode=['reflect', 'reflect'],
+                footprint=footprint, extra_arguments=(cf,),
+                extra_keywords={'total': xp.sum(cf)})
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [1, 1, 2]),
+         ('wrap', [3, 1, 2]),
+         ('reflect', [1, 1, 2]),
+         ('mirror', [2, 1, 2]),
+         ('constant', [0, 1, 2])]
+    )
+    def test_extend01(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([1, 0])
+        output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [1, 1, 1]),
+         ('wrap', [3, 1, 2]),
+         ('reflect', [3, 3, 2]),
+         ('mirror', [1, 2, 3]),
+         ('constant', [0, 0, 0])]
+    )
+    def test_extend02(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([1, 0, 0, 0, 0, 0, 0, 0])
+        output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [2, 3, 3]),
+         ('wrap', [2, 3, 1]),
+         ('reflect', [2, 3, 3]),
+         ('mirror', [2, 3, 2]),
+         ('constant', [2, 3, 0])]
+    )
+    def test_extend03(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([0, 0, 1])
+        output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [3, 3, 3]),
+         ('wrap', [2, 3, 1]),
+         ('reflect', [2, 1, 1]),
+         ('mirror', [1, 2, 3]),
+         ('constant', [0, 0, 0])]
+    )
+    def test_extend04(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+        output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]),
+         ('wrap', [[9, 7, 8], [3, 1, 2], [6, 4, 5]]),
+         ('reflect', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]),
+         ('mirror', [[5, 4, 5], [2, 1, 2], [5, 4, 5]]),
+         ('constant', [[0, 0, 0], [0, 1, 2], [0, 4, 5]])]
+    )
+    def test_extend05(self, mode, expected_value, xp):
+        array = xp.asarray([[1, 2, 3],
+                            [4, 5, 6],
+                            [7, 8, 9]])
+        weights = xp.asarray([[1, 0], [0, 0]])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]),
+         ('wrap', [[5, 6, 4], [8, 9, 7], [2, 3, 1]]),
+         ('reflect', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]),
+         ('mirror', [[5, 6, 5], [8, 9, 8], [5, 6, 5]]),
+         ('constant', [[5, 6, 0], [8, 9, 0], [0, 0, 0]])]
+    )
+    def test_extend06(self, mode, expected_value, xp):
+        array = xp.asarray([[1, 2, 3],
+                          [4, 5, 6],
+                          [7, 8, 9]])
+        weights = xp.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 1]])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [3, 3, 3]),
+         ('wrap', [2, 3, 1]),
+         ('reflect', [2, 1, 1]),
+         ('mirror', [1, 2, 3]),
+         ('constant', [0, 0, 0])]
+    )
+    def test_extend07(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [[3], [3], [3]]),
+         ('wrap', [[2], [3], [1]]),
+         ('reflect', [[2], [1], [1]]),
+         ('mirror', [[1], [2], [3]]),
+         ('constant', [[0], [0], [0]])]
+    )
+    def test_extend08(self, mode, expected_value, xp):
+        array = xp.asarray([[1], [2], [3]])
+        weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [3, 3, 3]),
+         ('wrap', [2, 3, 1]),
+         ('reflect', [2, 1, 1]),
+         ('mirror', [1, 2, 3]),
+         ('constant', [0, 0, 0])]
+    )
+    def test_extend09(self, mode, expected_value, xp):
+        array = xp.asarray([1, 2, 3])
+        weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [[3], [3], [3]]),
+         ('wrap', [[2], [3], [1]]),
+         ('reflect', [[2], [1], [1]]),
+         ('mirror', [[1], [2], [3]]),
+         ('constant', [[0], [0], [0]])]
+    )
+    def test_extend10(self, mode, expected_value, xp):
+        array = xp.asarray([[1], [2], [3]])
+        weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]])
+        output = ndimage.correlate(array, weights, mode=mode, cval=0)
+        expected_value = xp.asarray(expected_value)
+        xp_assert_equal(output, expected_value)
+
+
+def test_ticket_701(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy raises a TypeError.")
+
+    # Test generic filter sizes
+    arr = xp.asarray(np.arange(4).reshape(2, 2))
+    def func(x):
+        return np.min(x)  # NB: np.min not xp.min for callables
+    res = ndimage.generic_filter(arr, func, size=(1, 1))
+    # The following raises an error unless ticket 701 is fixed
+    res2 = ndimage.generic_filter(arr, func, size=1)
+    xp_assert_equal(res, res2)
+
+
+def test_gh_5430():
+    # At least one of these raises an error unless gh-5430 is
+    # fixed. In py2k an int is implemented using a C long, so
+    # which one fails depends on your system. In py3k there is only
+    # one arbitrary precision integer type, so both should fail.
+    sigma = np.int32(1)
+    out = ndimage._ni_support._normalize_sequence(sigma, 1)
+    assert out == [sigma]
+    sigma = np.int64(1)
+    out = ndimage._ni_support._normalize_sequence(sigma, 1)
+    assert out == [sigma]
+    # This worked before; make sure it still works
+    sigma = 1
+    out = ndimage._ni_support._normalize_sequence(sigma, 1)
+    assert out == [sigma]
+    # This worked before; make sure it still works
+    sigma = [1, 1]
+    out = ndimage._ni_support._normalize_sequence(sigma, 2)
+    assert out == sigma
+    # Also include the OPs original example to make sure we fixed the issue
+    x = np.random.normal(size=(256, 256))
+    perlin = np.zeros_like(x)
+    for i in 2**np.arange(6):
+        perlin += ndimage.gaussian_filter(x, i, mode="wrap") * i**2
+    # This also fixes gh-4106, show that the OPs example now runs.
+    x = np.int64(21)
+    ndimage._ni_support._normalize_sequence(x, 0)
+
+
+def test_gaussian_kernel1d(xp):
+    if is_cupy(xp):
+        pytest.skip("This test tests a private scipy utility.")
+    radius = 10
+    sigma = 2
+    sigma2 = sigma * sigma
+    x = np.arange(-radius, radius + 1, dtype=np.float64)
+    x = xp.asarray(x)
+    phi_x = xp.exp(-0.5 * x * x / sigma2)
+    phi_x /= xp.sum(phi_x)
+    xp_assert_close(phi_x,
+                    xp.asarray(_gaussian_kernel1d(sigma, 0, radius)))
+    xp_assert_close(-phi_x * x / sigma2,
+                    xp.asarray(_gaussian_kernel1d(sigma, 1, radius)))
+    xp_assert_close(phi_x * (x * x / sigma2 - 1) / sigma2,
+                    xp.asarray(_gaussian_kernel1d(sigma, 2, radius)))
+    xp_assert_close(phi_x * (3 - x * x / sigma2) * x / (sigma2 * sigma2),
+                    xp.asarray(_gaussian_kernel1d(sigma, 3, radius)))
+
+
+def test_orders_gauss(xp):
+    # Check order inputs to Gaussians
+    arr = xp.zeros((1,))
+    xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=0), xp.asarray([0.]))
+    xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=3), xp.asarray([0.]))
+    assert_raises(ValueError, ndimage.gaussian_filter, arr, 1, -1)
+    xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=0),
+                    xp.asarray([0.]))
+    xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=3),
+                    xp.asarray([0.]))
+    assert_raises(ValueError, ndimage.gaussian_filter1d, arr, 1, -1, -1)
+
+
+def test_valid_origins(xp):
+    """Regression test for #1311."""
+    if is_cupy(xp):
+        pytest.xfail("CuPy raises a TypeError.")
+
+    def func(x):
+        return xp.mean(x)
+    data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64)
+    assert_raises(ValueError, ndimage.generic_filter, data, func, size=3,
+                  origin=2)
+    assert_raises(ValueError, ndimage.generic_filter1d, data, func,
+                  filter_size=3, origin=2)
+    assert_raises(ValueError, ndimage.percentile_filter, data, 0.2, size=3,
+                  origin=2)
+
+    for filter in [ndimage.uniform_filter, ndimage.minimum_filter,
+                   ndimage.maximum_filter, ndimage.maximum_filter1d,
+                   ndimage.median_filter, ndimage.minimum_filter1d]:
+        # This should work, since for size == 3, the valid range for origin is
+        # -1 to 1.
+        list(filter(data, 3, origin=-1))
+        list(filter(data, 3, origin=1))
+        # Just check this raises an error instead of silently accepting or
+        # segfaulting.
+        assert_raises(ValueError, filter, data, 3, origin=2)
+
+
+def test_bad_convolve_and_correlate_origins(xp):
+    """Regression test for gh-822."""
+    # Before gh-822 was fixed, these would generate seg. faults or
+    # other crashes on many system.
+    assert_raises(ValueError, ndimage.correlate1d,
+                  [0, 1, 2, 3, 4, 5], [1, 1, 2, 0], origin=2)
+    assert_raises(ValueError, ndimage.correlate,
+                  [0, 1, 2, 3, 4, 5], [0, 1, 2], origin=[2])
+    assert_raises(ValueError, ndimage.correlate,
+                  xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, 1])
+
+    assert_raises(ValueError, ndimage.convolve1d,
+                  xp.arange(10), xp.ones(3), origin=-2)
+    assert_raises(ValueError, ndimage.convolve,
+                  xp.arange(10), xp.ones(3), origin=[-2])
+    assert_raises(ValueError, ndimage.convolve,
+                  xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, -2])
+
+@skip_xp_backends("cupy",
+                  reason="https://github.com/cupy/cupy/pull/8430",
+)
+def test_multiple_modes(xp):
+    # Test that the filters with multiple mode capabilities for different
+    # dimensions give the same result as applying a single mode.
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    mode1 = 'reflect'
+    mode2 = ['reflect', 'reflect']
+
+    xp_assert_equal(ndimage.gaussian_filter(arr, 1, mode=mode1),
+                 ndimage.gaussian_filter(arr, 1, mode=mode2))
+    xp_assert_equal(ndimage.prewitt(arr, mode=mode1),
+                 ndimage.prewitt(arr, mode=mode2))
+    xp_assert_equal(ndimage.sobel(arr, mode=mode1),
+                 ndimage.sobel(arr, mode=mode2))
+    xp_assert_equal(ndimage.laplace(arr, mode=mode1),
+                 ndimage.laplace(arr, mode=mode2))
+    xp_assert_equal(ndimage.gaussian_laplace(arr, 1, mode=mode1),
+                 ndimage.gaussian_laplace(arr, 1, mode=mode2))
+    xp_assert_equal(ndimage.maximum_filter(arr, size=5, mode=mode1),
+                 ndimage.maximum_filter(arr, size=5, mode=mode2))
+    xp_assert_equal(ndimage.minimum_filter(arr, size=5, mode=mode1),
+                 ndimage.minimum_filter(arr, size=5, mode=mode2))
+    xp_assert_equal(ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode1),
+                 ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode2))
+    xp_assert_equal(ndimage.uniform_filter(arr, 5, mode=mode1),
+                 ndimage.uniform_filter(arr, 5, mode=mode2))
+
+
+@skip_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8430")
+@skip_xp_backends("jax.numpy", reason="output array is read-only.")
+def test_multiple_modes_sequentially(xp):
+    # Test that the filters with multiple mode capabilities for different
+    # dimensions give the same result as applying the filters with
+    # different modes sequentially
+    arr = xp.asarray([[1., 0., 0.],
+                    [1., 1., 0.],
+                    [0., 0., 0.]])
+
+    modes = ['reflect', 'wrap']
+
+    expected = ndimage.gaussian_filter1d(arr, 1, axis=0, mode=modes[0])
+    expected = ndimage.gaussian_filter1d(expected, 1, axis=1, mode=modes[1])
+    xp_assert_equal(expected,
+                 ndimage.gaussian_filter(arr, 1, mode=modes))
+
+    expected = ndimage.uniform_filter1d(arr, 5, axis=0, mode=modes[0])
+    expected = ndimage.uniform_filter1d(expected, 5, axis=1, mode=modes[1])
+    xp_assert_equal(expected,
+                 ndimage.uniform_filter(arr, 5, mode=modes))
+
+    expected = ndimage.maximum_filter1d(arr, size=5, axis=0, mode=modes[0])
+    expected = ndimage.maximum_filter1d(expected, size=5, axis=1,
+                                        mode=modes[1])
+    xp_assert_equal(expected,
+                 ndimage.maximum_filter(arr, size=5, mode=modes))
+
+    expected = ndimage.minimum_filter1d(arr, size=5, axis=0, mode=modes[0])
+    expected = ndimage.minimum_filter1d(expected, size=5, axis=1,
+                                        mode=modes[1])
+    xp_assert_equal(expected,
+                 ndimage.minimum_filter(arr, size=5, mode=modes))
+
+
+def test_multiple_modes_prewitt(xp):
+    # Test prewitt filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[1., -3., 2.],
+                           [1., -2., 1.],
+                           [1., -1., 0.]])
+
+    modes = ['reflect', 'wrap']
+
+    xp_assert_equal(expected,
+                 ndimage.prewitt(arr, mode=modes))
+
+
+def test_multiple_modes_sobel(xp):
+    # Test sobel filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[1., -4., 3.],
+                           [2., -3., 1.],
+                           [1., -1., 0.]])
+
+    modes = ['reflect', 'wrap']
+
+    xp_assert_equal(expected,
+                 ndimage.sobel(arr, mode=modes))
+
+
+def test_multiple_modes_laplace(xp):
+    # Test laplace filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[-2., 2., 1.],
+                           [-2., -3., 2.],
+                           [1., 1., 0.]])
+
+    modes = ['reflect', 'wrap']
+
+    xp_assert_equal(expected,
+                 ndimage.laplace(arr, mode=modes))
+
+
+def test_multiple_modes_gaussian_laplace(xp):
+    # Test gaussian_laplace filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[-0.28438687, 0.01559809, 0.19773499],
+                           [-0.36630503, -0.20069774, 0.07483620],
+                           [0.15849176, 0.18495566, 0.21934094]])
+
+    modes = ['reflect', 'wrap']
+
+    assert_almost_equal(expected,
+                        ndimage.gaussian_laplace(arr, 1, mode=modes))
+
+
+def test_multiple_modes_gaussian_gradient_magnitude(xp):
+    # Test gaussian_gradient_magnitude filter for multiple
+    # extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[0.04928965, 0.09745625, 0.06405368],
+                           [0.23056905, 0.14025305, 0.04550846],
+                           [0.19894369, 0.14950060, 0.06796850]])
+
+    modes = ['reflect', 'wrap']
+
+    calculated = ndimage.gaussian_gradient_magnitude(arr, 1, mode=modes)
+
+    assert_almost_equal(expected, calculated)
+
+@skip_xp_backends("cupy",
+                  reason="https://github.com/cupy/cupy/pull/8430",
+)
+def test_multiple_modes_uniform(xp):
+    # Test uniform filter for multiple extrapolation modes
+    arr = xp.asarray([[1., 0., 0.],
+                      [1., 1., 0.],
+                      [0., 0., 0.]])
+
+    expected = xp.asarray([[0.32, 0.40, 0.48],
+                           [0.20, 0.28, 0.32],
+                           [0.28, 0.32, 0.40]])
+
+    modes = ['reflect', 'wrap']
+
+    assert_almost_equal(expected,
+                        ndimage.uniform_filter(arr, 5, mode=modes))
+
+
+def _count_nonzero(arr):
+    # XXX: a simplified count_nonzero replacement; replace once
+    # https://github.com/data-apis/array-api/pull/803/ is in
+
+    # this assumes arr.dtype == xp.bool
+    xp = array_namespace(arr)
+    return xp.sum(xp.astype(arr, xp.int8))
+
+
+def test_gaussian_truncate(xp):
+    # Test that Gaussian filters can be truncated at different widths.
+    # These tests only check that the result has the expected number
+    # of nonzero elements.
+    arr = np.zeros((100, 100), dtype=np.float64)
+    arr[50, 50] = 1
+    arr = xp.asarray(arr)
+    num_nonzeros_2 = _count_nonzero(ndimage.gaussian_filter(arr, 5, truncate=2) > 0)
+    assert num_nonzeros_2 == 21**2
+
+    num_nonzeros_5 = _count_nonzero(
+        ndimage.gaussian_filter(arr, 5, truncate=5) > 0
+    )
+    assert num_nonzeros_5 == 51**2
+
+    nnz_kw = {'as_tuple': True} if is_torch(xp) else {}
+
+    # Test truncate when sigma is a sequence.
+    f = ndimage.gaussian_filter(arr, [0.5, 2.5], truncate=3.5)
+    fpos = f > 0
+    n0 = _count_nonzero(xp.any(fpos, axis=0))
+    assert n0 == 19
+    n1 = _count_nonzero(xp.any(fpos, axis=1))
+    assert n1 == 5
+
+    # Test gaussian_filter1d.
+    x = np.zeros(51)
+    x[25] = 1
+    x = xp.asarray(x)
+    f = ndimage.gaussian_filter1d(x, sigma=2, truncate=3.5)
+    n = _count_nonzero(f > 0)
+    assert n == 15
+
+    # Test gaussian_laplace
+    y = ndimage.gaussian_laplace(x, sigma=2, truncate=3.5)
+    nonzero_indices = xp.nonzero(y != 0, **nnz_kw)[0]
+
+    n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1
+    assert n == 15
+
+    # Test gaussian_gradient_magnitude
+    y = ndimage.gaussian_gradient_magnitude(x, sigma=2, truncate=3.5)
+    nonzero_indices = xp.nonzero(y != 0, **nnz_kw)[0]
+    n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1
+    assert n == 15
+
+
+def test_gaussian_radius(xp):
+    if is_cupy(xp):
+        pytest.xfail("https://github.com/cupy/cupy/issues/8402")
+
+    # Test that Gaussian filters with radius argument produce the same
+    # results as the filters with corresponding truncate argument.
+    # radius = int(truncate * sigma + 0.5)
+    # Test gaussian_filter1d
+    x = np.zeros(7)
+    x[3] = 1
+    x = xp.asarray(x)
+    f1 = ndimage.gaussian_filter1d(x, sigma=2, truncate=1.5)
+    f2 = ndimage.gaussian_filter1d(x, sigma=2, radius=3)
+    xp_assert_equal(f1, f2)
+
+    # Test gaussian_filter when sigma is a number.
+    a = np.zeros((9, 9))
+    a[4, 4] = 1
+    a = xp.asarray(a)
+    f1 = ndimage.gaussian_filter(a, sigma=0.5, truncate=3.5)
+    f2 = ndimage.gaussian_filter(a, sigma=0.5, radius=2)
+    xp_assert_equal(f1, f2)
+
+    # Test gaussian_filter when sigma is a sequence.
+    a = np.zeros((50, 50))
+    a[25, 25] = 1
+    a = xp.asarray(a)
+    f1 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], truncate=3.5)
+    f2 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], radius=[2, 9])
+    xp_assert_equal(f1, f2)
+
+
+def test_gaussian_radius_invalid(xp):
+    if is_cupy(xp):
+        pytest.xfail("https://github.com/cupy/cupy/issues/8402")
+
+    # radius must be a nonnegative integer
+    with assert_raises(ValueError):
+        ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=-1)
+    with assert_raises(ValueError):
+        ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=1.1)
+
+
+@skip_xp_backends("jax.numpy", reason="output array is read-only")
+class TestThreading:
+    def check_func_thread(self, n, fun, args, out):
+        from threading import Thread
+        thrds = [Thread(target=fun, args=args, kwargs={'output': out[x, ...]})
+                 for x in range(n)]
+        [t.start() for t in thrds]
+        [t.join() for t in thrds]
+
+    def check_func_serial(self, n, fun, args, out):
+        for i in range(n):
+            fun(*args, output=out[i, ...])
+
+    def test_correlate1d(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = np.random.randn(5000)
+        os = np.empty((4, d.size))
+        ot = np.empty_like(os)
+        d = xp.asarray(d)
+        os = xp.asarray(os)
+        ot = xp.asarray(ot)
+        k = xp.arange(5)
+        self.check_func_serial(4, ndimage.correlate1d, (d, k), os)
+        self.check_func_thread(4, ndimage.correlate1d, (d, k), ot)
+        xp_assert_equal(os, ot)
+
+    def test_correlate(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = xp.asarray(np.random.randn(500, 500))
+        k = xp.asarray(np.random.randn(10, 10))
+        os = xp.empty([4] + list(d.shape))
+        ot = xp.empty_like(os)
+        self.check_func_serial(4, ndimage.correlate, (d, k), os)
+        self.check_func_thread(4, ndimage.correlate, (d, k), ot)
+        xp_assert_equal(os, ot)
+
+    def test_median_filter(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = xp.asarray(np.random.randn(500, 500))
+        os = xp.empty([4] + list(d.shape))
+        ot = xp.empty_like(os)
+        self.check_func_serial(4, ndimage.median_filter, (d, 3), os)
+        self.check_func_thread(4, ndimage.median_filter, (d, 3), ot)
+        xp_assert_equal(os, ot)
+
+    def test_uniform_filter1d(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = np.random.randn(5000)
+        os = np.empty((4, d.size))
+        ot = np.empty_like(os)
+        d = xp.asarray(d)
+        os = xp.asarray(os)
+        ot = xp.asarray(ot)
+        self.check_func_serial(4, ndimage.uniform_filter1d, (d, 5), os)
+        self.check_func_thread(4, ndimage.uniform_filter1d, (d, 5), ot)
+        xp_assert_equal(os, ot)
+
+    def test_minmax_filter(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("XXX thread exception; cannot repro outside of pytest")
+
+        d = xp.asarray(np.random.randn(500, 500))
+        os = xp.empty([4] + list(d.shape))
+        ot = xp.empty_like(os)
+        self.check_func_serial(4, ndimage.maximum_filter, (d, 3), os)
+        self.check_func_thread(4, ndimage.maximum_filter, (d, 3), ot)
+        xp_assert_equal(os, ot)
+        self.check_func_serial(4, ndimage.minimum_filter, (d, 3), os)
+        self.check_func_thread(4, ndimage.minimum_filter, (d, 3), ot)
+        xp_assert_equal(os, ot)
+
+
+def test_minmaximum_filter1d(xp):
+    # Regression gh-3898
+    in_ = xp.arange(10)
+    out = ndimage.minimum_filter1d(in_, 1)
+    xp_assert_equal(in_, out)
+    out = ndimage.maximum_filter1d(in_, 1)
+    xp_assert_equal(in_, out)
+    # Test reflect
+    out = ndimage.minimum_filter1d(in_, 5, mode='reflect')
+    xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out)
+    out = ndimage.maximum_filter1d(in_, 5, mode='reflect')
+    xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+    # Test constant
+    out = ndimage.minimum_filter1d(in_, 5, mode='constant', cval=-1)
+    xp_assert_equal(xp.asarray([-1, -1, 0, 1, 2, 3, 4, 5, -1, -1]), out)
+    out = ndimage.maximum_filter1d(in_, 5, mode='constant', cval=10)
+    xp_assert_equal(xp.asarray([10, 10, 4, 5, 6, 7, 8, 9, 10, 10]), out)
+    # Test nearest
+    out = ndimage.minimum_filter1d(in_, 5, mode='nearest')
+    xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out)
+    out = ndimage.maximum_filter1d(in_, 5, mode='nearest')
+    xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+    # Test wrap
+    out = ndimage.minimum_filter1d(in_, 5, mode='wrap')
+    xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 0, 0]), out)
+    out = ndimage.maximum_filter1d(in_, 5, mode='wrap')
+    xp_assert_equal(xp.asarray([9, 9, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+
+
+def test_uniform_filter1d_roundoff_errors(xp):
+    if is_cupy(xp):
+        pytest.xfail("https://github.com/cupy/cupy/issues/8401")
+    # gh-6930
+    in_ = np.repeat([0, 1, 0], [9, 9, 9])
+    in_ = xp.asarray(in_)
+
+    for filter_size in range(3, 10):
+        out = ndimage.uniform_filter1d(in_, filter_size)
+        xp_assert_equal(xp.sum(out), xp.asarray(10 - filter_size), check_0d=False)
+
+
+def test_footprint_all_zeros(xp):
+    # regression test for gh-6876: footprint of all zeros segfaults
+    arr = xp.asarray(np.random.randint(0, 100, (100, 100)))
+    kernel = xp.asarray(np.zeros((3, 3), dtype=bool))
+    with assert_raises(ValueError):
+        ndimage.maximum_filter(arr, footprint=kernel)
+
+
+def test_gaussian_filter(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy does not raise")
+
+    if not hasattr(xp, "float16"):
+        pytest.xfail(f"{xp} does not have float16")
+
+    # Test gaussian filter with xp.float16
+    # gh-8207
+    data = xp.asarray([1], dtype=xp.float16)
+    sigma = 1.0
+    with assert_raises(RuntimeError):
+        ndimage.gaussian_filter(data, sigma)
+
+
+def test_rank_filter_noninteger_rank(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy does not raise")
+
+    # regression test for issue 9388: ValueError for
+    # non integer rank when performing rank_filter
+    arr = xp.asarray(np.random.random((10, 20, 30)))
+    footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool))
+    assert_raises(TypeError, ndimage.rank_filter, arr, 0.5,
+                  footprint=footprint)
+
+
+def test_size_footprint_both_set(xp):
+    # test for input validation, expect user warning when
+    # size and footprint is set
+    with suppress_warnings() as sup:
+        sup.filter(UserWarning,
+                   "ignoring size because footprint is set")
+        arr = xp.asarray(np.random.random((10, 20, 30)))
+        footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool))
+        ndimage.rank_filter(
+            arr, 5, size=2, footprint=footprint
+        )
+
+
+@skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+def test_byte_order_median(xp):
+    """Regression test for #413: median_filter does not handle bytes orders."""
+    a = xp.arange(9, dtype='1 makes sense too
+     (3,
+      np.array([0.25266576, 0.30958242, 0.27894721, 0.27894721, 0.27894721, 0.30445588,
+                0.31442572, 0.30445588, 0.18015438, 0.14831921, 0.18015438, 0.25754605,
+                0.32910465, 0.25754605, 0.17736568, 0.17736568, 0.09089549, 0.22183391,
+                0.25266576, 0.30958242]),
+     ),
+     (15,
+      np.array([0.27894721, 0.25266576, 0.25266576, 0.25266576, 0.27894721, 0.27894721,
+                0.27894721, 0.27894721, 0.25754605, 0.25754605, 0.22183391, 0.22183391,
+                0.25266576, 0.25266576, 0.22183391, 0.22183391, 0.25266576, 0.25266576,
+                0.25754605, 0.25754605]),
+     ),
+])
+def test_gh_22250(filter_size, exp):
+    rng = np.random.default_rng(42)
+    image = np.zeros((20,))
+    noisy_image = image + 0.4 * rng.random(image.shape)
+    result = ndimage.median_filter(noisy_image, size=filter_size, mode='wrap')
+    assert_allclose(result, exp)
+
+
+def test_gh_22333():
+    x = np.array([272, 58, 67, 163, 463, 608, 87, 108, 1378])
+    expected = [58, 67, 87, 108, 163, 108, 108, 108, 87]
+    actual = ndimage.median_filter(x, size=9, mode='constant')
+    assert_array_equal(actual, expected)
+
+
+@given(x=npst.arrays(dtype=np.float64,
+                     shape=st.integers(min_value=1, max_value=1000)),
+       size=st.integers(min_value=1, max_value=50),
+       mode=st.sampled_from(["constant", "mirror", "wrap", "reflect",
+                             "nearest"]),
+      )
+def test_gh_22586_crash_property(x, size, mode):
+    # property-based test for median_filter resilience to hard crashing
+    ndimage.median_filter(x, size=size, mode=mode)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..be544eaab9ce00b2e9802cf8f9a4819c4f1d2731
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_fourier.py
@@ -0,0 +1,189 @@
+import math
+import numpy as np
+
+from scipy._lib._array_api import (
+    xp_assert_equal,
+    assert_array_almost_equal,
+    assert_almost_equal,
+    is_cupy,
+)
+
+import pytest
+
+from scipy import ndimage
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+@skip_xp_backends('jax.numpy', reason="jax-ml/jax#23827")
+class TestNdimageFourier:
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+    @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
+    def test_fourier_gaussian_real01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.rfft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.irfft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(a), xp.asarray(1), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
+    def test_fourier_gaussian_complex01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.fft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.ifft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+    @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
+    def test_fourier_uniform_real01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.rfft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.irfft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
+    def test_fourier_uniform_complex01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.fft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.ifft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("float32", 4), ("float64", 11)])
+    def test_fourier_shift_real01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
+        expected = xp.asarray(expected)
+
+        a = fft.rfft(expected, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_shift(a, [1, 1], shape[0], 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.irfft(a, n=shape[0], axis=0)
+        assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("complex64", 4), ("complex128", 11)])
+    def test_fourier_shift_complex01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
+        expected = xp.asarray(expected)
+
+        a = fft.fft(expected, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_shift(a, [1, 1], -1, 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.ifft(a, n=shape[0], axis=0)
+        assert_array_almost_equal(xp.real(a)[1:, 1:], expected[:-1, :-1], decimal=dec)
+        assert_array_almost_equal(xp.imag(a), xp.zeros(shape), decimal=dec)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+    @pytest.mark.parametrize('dtype, dec', [("float32", 5), ("float64", 14)])
+    def test_fourier_ellipsoid_real01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.rfft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.irfft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+    @pytest.mark.parametrize('dtype, dec', [("complex64", 5), ("complex128", 14)])
+    def test_fourier_ellipsoid_complex01(self, shape, dtype, dec, xp):
+        fft = getattr(xp, 'fft')
+
+        a = np.zeros(shape, dtype=dtype)
+        a[0, 0] = 1.0
+        a = xp.asarray(a)
+
+        a = fft.fft(a, n=shape[0], axis=0)
+        a = fft.fft(a, n=shape[1], axis=1)
+        a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0)
+        a = fft.ifft(a, n=shape[1], axis=1)
+        a = fft.ifft(a, n=shape[0], axis=0)
+        assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+                            check_0d=False)
+
+    def test_fourier_ellipsoid_unimplemented_ndim(self, xp):
+        # arrays with ndim > 3 raise NotImplementedError
+        x = xp.ones((4, 6, 8, 10), dtype=xp.complex128)
+        with pytest.raises(NotImplementedError):
+            ndimage.fourier_ellipsoid(x, 3)
+
+    def test_fourier_ellipsoid_1d_complex(self, xp):
+        # expected result of 1d ellipsoid is the same as for fourier_uniform
+        for shape in [(32, ), (31, )]:
+            for type_, dec in zip([xp.complex64, xp.complex128], [5, 14]):
+                x = xp.ones(shape, dtype=type_)
+                a = ndimage.fourier_ellipsoid(x, 5, -1, 0)
+                b = ndimage.fourier_uniform(x, 5, -1, 0)
+                assert_array_almost_equal(a, b, decimal=dec)
+
+    @pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)])
+    @pytest.mark.parametrize('dtype', ["float32", "float64",
+                                       "complex64", "complex128"])
+    @pytest.mark.parametrize('test_func',
+                             [ndimage.fourier_ellipsoid,
+                              ndimage.fourier_gaussian,
+                              ndimage.fourier_uniform])
+    def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp):
+        if is_cupy(xp):
+           if (test_func.__name__ == "fourier_ellipsoid" and
+               math.prod(shape) == 0):
+               pytest.xfail(
+                   "CuPy's fourier_ellipsoid does not accept size==0 arrays"
+               )
+        dtype = getattr(xp, dtype)
+        a = xp.ones(shape, dtype=dtype)
+        b = test_func(a, 3)
+        xp_assert_equal(a, b)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..51e8441e244f46642a07102e297b4d72513514d0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py
@@ -0,0 +1,1484 @@
+import sys
+
+import numpy as np
+from numpy.testing import suppress_warnings
+from scipy._lib._array_api import (
+    xp_assert_equal, xp_assert_close,
+    assert_array_almost_equal,
+)
+from scipy._lib._array_api import is_cupy, is_jax, _asarray, array_namespace
+
+import pytest
+from pytest import raises as assert_raises
+import scipy.ndimage as ndimage
+
+from . import types
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+eps = 1e-12
+
+ndimage_to_numpy_mode = {
+    'mirror': 'reflect',
+    'reflect': 'symmetric',
+    'grid-mirror': 'symmetric',
+    'grid-wrap': 'wrap',
+    'nearest': 'edge',
+    'grid-constant': 'constant',
+}
+
+
+class TestBoundaries:
+
+    @skip_xp_backends("cupy", reason="CuPy does not have geometric_transform")
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]),
+         ('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]),
+         ('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]),
+         ('mirror', [1.5, 2.5, 3.5, 3.5, 2.5, 1.5, 1.5]),
+         ('reflect', [1.5, 2.5, 3.5, 4, 3.5, 2.5, 1.5]),
+         ('constant', [1.5, 2.5, 3.5, -1, -1, -1, -1]),
+         ('grid-constant', [1.5, 2.5, 3.5, 1.5, -1, -1, -1])]
+    )
+    def test_boundaries(self, mode, expected_value, xp):
+        def shift(x):
+            return (x[0] + 0.5,)
+
+        data = xp.asarray([1, 2, 3, 4.])
+        xp_assert_equal(
+            ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
+                                        output_shape=(7,), order=1),
+            xp.asarray(expected_value))
+
+    @skip_xp_backends("cupy", reason="CuPy does not have geometric_transform")
+    @pytest.mark.parametrize(
+        'mode, expected_value',
+        [('nearest', [1, 1, 2, 3]),
+         ('wrap', [3, 1, 2, 3]),
+         ('grid-wrap', [4, 1, 2, 3]),
+         ('mirror', [2, 1, 2, 3]),
+         ('reflect', [1, 1, 2, 3]),
+         ('constant', [-1, 1, 2, 3]),
+         ('grid-constant', [-1, 1, 2, 3])]
+    )
+    def test_boundaries2(self, mode, expected_value, xp):
+        def shift(x):
+            return (x[0] - 0.9,)
+
+        data = xp.asarray([1, 2, 3, 4])
+        xp_assert_equal(
+            ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
+                                        output_shape=(4,)),
+            xp.asarray(expected_value))
+
+    @pytest.mark.parametrize('mode', ['mirror', 'reflect', 'grid-mirror',
+                                      'grid-wrap', 'grid-constant',
+                                      'nearest'])
+    @pytest.mark.parametrize('order', range(6))
+    def test_boundary_spline_accuracy(self, mode, order, xp):
+        """Tests based on examples from gh-2640"""
+        if (is_jax(xp) and
+            (mode not in ['mirror', 'reflect', 'constant', 'wrap', 'nearest']
+             or order > 1)
+        ):
+            pytest.xfail("Jax does not support grid- modes or order > 1")
+
+        np_data = np.arange(-6, 7, dtype=np.float64)
+        data = xp.asarray(np_data)
+        x = xp.asarray(np.linspace(-8, 15, num=1000))
+        newaxis = array_namespace(x).newaxis
+        y = ndimage.map_coordinates(data, x[newaxis, ...], order=order, mode=mode)
+
+        # compute expected value using explicit padding via np.pad
+        npad = 32
+        pad_mode = ndimage_to_numpy_mode.get(mode)
+        padded = xp.asarray(np.pad(np_data, npad, mode=pad_mode))
+        coords = xp.asarray(npad + x)[newaxis, ...]
+        expected = ndimage.map_coordinates(padded, coords, order=order, mode=mode)
+
+        atol = 1e-5 if mode == 'grid-constant' else 1e-12
+        xp_assert_close(y, expected, rtol=1e-7, atol=atol)
+
+
+@pytest.mark.parametrize('order', range(2, 6))
+@pytest.mark.parametrize('dtype', types)
+class TestSpline:
+
+    def test_spline01(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.spline_filter(data, order=order)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    def test_spline02(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([1], dtype=dtype)
+        out = ndimage.spline_filter(data, order=order)
+        assert_array_almost_equal(out, xp.asarray([1]))
+
+    @skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+    def test_spline03(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.spline_filter(data, order, output=dtype)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    def test_spline04(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([4], dtype=dtype)
+        out = ndimage.spline_filter(data, order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
+
+    def test_spline05(self, dtype, order, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([4, 4], dtype=dtype)
+        out = ndimage.spline_filter(data, order=order)
+        expected = xp.asarray([[1, 1, 1, 1],
+                               [1, 1, 1, 1],
+                               [1, 1, 1, 1],
+                               [1, 1, 1, 1]])
+        assert_array_almost_equal(out, expected)
+
+
+@skip_xp_backends("cupy", reason="CuPy does not have geometric_transform")
+@pytest.mark.parametrize('order', range(0, 6))
+class TestGeometricTransform:
+
+    def test_geometric_transform01(self, order, xp):
+        data = xp.asarray([1])
+
+        def mapping(x):
+            return x
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
+
+    def test_geometric_transform02(self, order, xp):
+        data = xp.ones([4])
+
+        def mapping(x):
+            return x
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
+
+    def test_geometric_transform03(self, order, xp):
+        data = xp.ones([4])
+
+        def mapping(x):
+            return (x[0] - 1,)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1], dtype=out.dtype))
+
+    def test_geometric_transform04(self, order, xp):
+        data = xp.asarray([4, 1, 3, 2])
+
+        def mapping(x):
+            return (x[0] - 1,)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3], dtype=out.dtype))
+
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_geometric_transform05(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[1, 1, 1, 1],
+                           [1, 1, 1, 1],
+                           [1, 1, 1, 1]], dtype=dtype)
+        expected = xp.asarray([[0, 1, 1, 1],
+                               [0, 1, 1, 1],
+                               [0, 1, 1, 1]], dtype=dtype)
+
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+
+        def mapping(x):
+            return (x[0], x[1] - 1)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform06(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+
+        def mapping(x):
+            return (x[0], x[1] - 1)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        expected = xp.asarray([[0, 4, 1, 3],
+                               [0, 7, 6, 8],
+                               [0, 3, 5, 3]], dtype=out.dtype)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform07(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+
+        def mapping(x):
+            return (x[0] - 1, x[1])
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [4, 1, 3, 2],
+                               [7, 6, 8, 5]], dtype=out.dtype)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform08(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+
+        def mapping(x):
+            return (x[0] - 1, x[1] - 1)
+
+        out = ndimage.geometric_transform(data, mapping, data.shape,
+                                          order=order)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 4, 1, 3],
+                               [0, 7, 6, 8]], dtype=out.dtype)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform10(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+
+        def mapping(x):
+            return (x[0] - 1, x[1] - 1)
+
+        if (order > 1):
+            filtered = ndimage.spline_filter(data, order=order)
+        else:
+            filtered = data
+        out = ndimage.geometric_transform(filtered, mapping, data.shape,
+                                          order=order, prefilter=False)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 4, 1, 3],
+                               [0, 7, 6, 8]], dtype=out.dtype)
+        assert_array_almost_equal(out, expected)
+
+    def test_geometric_transform13(self, order, xp):
+        data = xp.ones([2], dtype=xp.float64)
+
+        def mapping(x):
+            return (x[0] // 2,)
+
+        out = ndimage.geometric_transform(data, mapping, [4], order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
+
+    def test_geometric_transform14(self, order, xp):
+        data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
+
+        def mapping(x):
+            return (2 * x[0],)
+
+        out = ndimage.geometric_transform(data, mapping, [4], order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4], dtype=out.dtype))
+
+    def test_geometric_transform15(self, order, xp):
+        data = [1, 2, 3, 4]
+
+        def mapping(x):
+            return (x[0] / 2,)
+
+        out = ndimage.geometric_transform(data, mapping, [8], order=order)
+        assert_array_almost_equal(out[::2], [1, 2, 3, 4])
+
+    def test_geometric_transform16(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9.0, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0], x[1] * 2)
+
+        out = ndimage.geometric_transform(data, mapping, (3, 2),
+                                          order=order)
+        assert_array_almost_equal(out, [[1, 3], [5, 7], [9, 11]])
+
+    def test_geometric_transform17(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0] * 2, x[1])
+
+        out = ndimage.geometric_transform(data, mapping, (1, 4),
+                                          order=order)
+        assert_array_almost_equal(out, [[1, 2, 3, 4]])
+
+    def test_geometric_transform18(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0] * 2, x[1] * 2)
+
+        out = ndimage.geometric_transform(data, mapping, (1, 2),
+                                          order=order)
+        assert_array_almost_equal(out, [[1, 3]])
+
+    def test_geometric_transform19(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0], x[1] / 2)
+
+        out = ndimage.geometric_transform(data, mapping, (3, 8),
+                                          order=order)
+        assert_array_almost_equal(out[..., ::2], data)
+
+    def test_geometric_transform20(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0] / 2, x[1])
+
+        out = ndimage.geometric_transform(data, mapping, (6, 4),
+                                          order=order)
+        assert_array_almost_equal(out[::2, ...], data)
+
+    def test_geometric_transform21(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (x[0] / 2, x[1] / 2)
+
+        out = ndimage.geometric_transform(data, mapping, (6, 8),
+                                          order=order)
+        assert_array_almost_equal(out[::2, ::2], data)
+
+    def test_geometric_transform22(self, order, xp):
+        data = xp.asarray([[1, 2, 3, 4],
+                           [5, 6, 7, 8],
+                           [9, 10, 11, 12]], dtype=xp.float64)
+
+        def mapping1(x):
+            return (x[0] / 2, x[1] / 2)
+
+        def mapping2(x):
+            return (x[0] * 2, x[1] * 2)
+
+        out = ndimage.geometric_transform(data, mapping1,
+                                          (6, 8), order=order)
+        out = ndimage.geometric_transform(out, mapping2,
+                                          (3, 4), order=order)
+        assert_array_almost_equal(out, data)
+
+    def test_geometric_transform23(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x):
+            return (1, x[0] * 2)
+
+        out = ndimage.geometric_transform(data, mapping, (2,), order=order)
+        out = out.astype(np.int32)
+        assert_array_almost_equal(out, [5, 7])
+
+    def test_geometric_transform24(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+
+        def mapping(x, a, b):
+            return (a, x[0] * b)
+
+        out = ndimage.geometric_transform(
+            data, mapping, (2,), order=order, extra_arguments=(1,),
+            extra_keywords={'b': 2})
+        assert_array_almost_equal(out, [5, 7])
+
+
+@skip_xp_backends("cupy", reason="CuPy does not have geometric_transform")
+class TestGeometricTransformExtra:
+
+    def test_geometric_transform_grid_constant_order1(self, xp):
+
+        # verify interpolation outside the original bounds
+        x = xp.asarray([[1, 2, 3],
+                        [4, 5, 6]], dtype=xp.float64)
+
+        def mapping(x):
+            return (x[0] - 0.5), (x[1] - 0.5)
+
+        expected_result = xp.asarray([[0.25, 0.75, 1.25],
+                                      [1.25, 3.00, 4.00]])
+        assert_array_almost_equal(
+            ndimage.geometric_transform(x, mapping, mode='grid-constant',
+                                        order=1),
+            expected_result,
+        )
+
+    @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
+                                      'mirror', 'reflect'])
+    @pytest.mark.parametrize('order', range(6))
+    def test_geometric_transform_vs_padded(self, order, mode, xp):
+
+        def mapping(x):
+            return (x[0] - 0.4), (x[1] + 2.3)
+
+        # Manually pad and then extract center after the transform to get the
+        # expected result.
+        x = np.arange(144, dtype=float).reshape(12, 12)
+        npad = 24
+        pad_mode = ndimage_to_numpy_mode.get(mode)
+        x_padded = np.pad(x, npad, mode=pad_mode)
+
+        x = xp.asarray(x)
+        x_padded = xp.asarray(x_padded)
+
+        center_slice = tuple([slice(npad, -npad)] * x.ndim)
+        expected_result = ndimage.geometric_transform(
+            x_padded, mapping, mode=mode, order=order)[center_slice]
+
+        xp_assert_close(
+            ndimage.geometric_transform(x, mapping, mode=mode,
+                                        order=order),
+            expected_result,
+            rtol=1e-7,
+        )
+
+    @skip_xp_backends(np_only=True, reason='endianness is numpy-specific')
+    def test_geometric_transform_endianness_with_output_parameter(self, xp):
+        # geometric transform given output ndarray or dtype with
+        # non-native endianness. see issue #4127
+        data = np.asarray([1])
+
+        def mapping(x):
+            return x
+
+        for out in [data.dtype, data.dtype.newbyteorder(),
+                    np.empty_like(data),
+                    np.empty_like(data).astype(data.dtype.newbyteorder())]:
+            returned = ndimage.geometric_transform(data, mapping, data.shape,
+                                                   output=out)
+            result = out if returned is None else returned
+            assert_array_almost_equal(result, [1])
+
+    @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+    def test_geometric_transform_with_string_output(self, xp):
+        data = xp.asarray([1])
+
+        def mapping(x):
+            return x
+
+        out = ndimage.geometric_transform(data, mapping, output='f')
+        assert out.dtype is np.dtype('f')
+        assert_array_almost_equal(out, [1])
+
+
+class TestMapCoordinates:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', [np.float64, np.complex128])
+    def test_map_coordinates01(self, order, dtype, xp):
+        if is_jax(xp) and order > 1:
+            pytest.xfail("jax map_coordinates requires order <= 1")
+
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 4, 1, 3],
+                               [0, 7, 6, 8]])
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data = data - 1j * data
+            expected = expected - 1j * expected
+
+        idx = np.indices(data.shape)
+        idx -= 1
+        idx = xp.asarray(idx)
+
+        out = ndimage.map_coordinates(data, idx, order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_map_coordinates02(self, order, xp):
+        if is_jax(xp):
+            if order > 1:
+               pytest.xfail("jax map_coordinates requires order <= 1")
+            if order == 1:
+               pytest.xfail("output differs. jax bug?")
+
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        idx = np.indices(data.shape, np.float64)
+        idx -= 0.5
+        idx = xp.asarray(idx)
+
+        out1 = ndimage.shift(data, 0.5, order=order)
+        out2 = ndimage.map_coordinates(data, idx, order=order)
+        assert_array_almost_equal(out1, out2)
+
+    @skip_xp_backends("jax.numpy", reason="`order` is required in jax")
+    def test_map_coordinates03(self, xp):
+        data = _asarray([[4, 1, 3, 2],
+                         [7, 6, 8, 5],
+                         [3, 5, 3, 6]], order='F', xp=xp)
+        idx = np.indices(data.shape) - 1
+        idx = xp.asarray(idx)
+        out = ndimage.map_coordinates(data, idx)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 4, 1, 3],
+                               [0, 7, 6, 8]])
+        assert_array_almost_equal(out, expected)
+        assert_array_almost_equal(out, ndimage.shift(data, (1, 1)))
+
+        idx = np.indices(data[::2, ...].shape) - 1
+        idx = xp.asarray(idx)
+        out = ndimage.map_coordinates(data[::2, ...], idx)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3]]))
+        assert_array_almost_equal(out, ndimage.shift(data[::2, ...], (1, 1)))
+
+        idx = np.indices(data[:, ::2].shape) - 1
+        idx = xp.asarray(idx)
+        out = ndimage.map_coordinates(data[:, ::2], idx)
+        assert_array_almost_equal(out, xp.asarray([[0, 0], [0, 4], [0, 7]]))
+        assert_array_almost_equal(out, ndimage.shift(data[:, ::2], (1, 1)))
+
+    @skip_xp_backends(np_only=True)
+    def test_map_coordinates_endianness_with_output_parameter(self, xp):
+        # output parameter given as array or dtype with either endianness
+        # see issue #4127
+        # NB: NumPy-only
+
+        data = np.asarray([[1, 2], [7, 6]])
+        expected = np.asarray([[0, 0], [0, 1]])
+        idx = np.indices(data.shape)
+        idx -= 1
+        for out in [
+            data.dtype,
+            data.dtype.newbyteorder(),
+            np.empty_like(expected),
+            np.empty_like(expected).astype(expected.dtype.newbyteorder())
+        ]:
+            returned = ndimage.map_coordinates(data, idx, output=out)
+            result = out if returned is None else returned
+            assert_array_almost_equal(result, expected)
+
+    @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+    def test_map_coordinates_with_string_output(self, xp):
+        data = xp.asarray([[1]])
+        idx = np.indices(data.shape)
+        idx = xp.asarray(idx)
+        out = ndimage.map_coordinates(data, idx, output='f')
+        assert out.dtype is np.dtype('f')
+        assert_array_almost_equal(out, xp.asarray([[1]]))
+
+    @pytest.mark.skipif('win32' in sys.platform or np.intp(0).itemsize < 8,
+                        reason='do not run on 32 bit or windows '
+                               '(no sparse memory)')
+    def test_map_coordinates_large_data(self, xp):
+        # check crash on large data
+        try:
+            n = 30000
+            # a = xp.reshape(xp.empty(n**2, dtype=xp.float32), (n, n))
+            a = np.empty(n**2, dtype=np.float32).reshape(n, n)
+            # fill the part we might read
+            a[n - 3:, n - 3:] = 0
+            ndimage.map_coordinates(
+                xp.asarray(a), xp.asarray([[n - 1.5], [n - 1.5]]), order=1
+            )
+        except MemoryError as e:
+            raise pytest.skip('Not enough memory available') from e
+
+
+class TestAffineTransform:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform01(self, order, xp):
+        data = xp.asarray([1])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
+        assert_array_almost_equal(out, xp.asarray([1]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform02(self, order, xp):
+        data = xp.ones([4])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform03(self, order, xp):
+        data = xp.ones([4])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform04(self, order, xp):
+        data = xp.asarray([4, 1, 3, 2])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_affine_transform05(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[1, 1, 1, 1],
+                           [1, 1, 1, 1],
+                           [1, 1, 1, 1]], dtype=dtype)
+        expected = xp.asarray([[0, 1, 1, 1],
+                               [0, 1, 1, 1],
+                               [0, 1, 1, 1]], dtype=dtype)
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+                                       [0, -1], order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform06(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+                                       [0, -1], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
+                                                   [0, 7, 6, 8],
+                                                   [0, 3, 5, 3]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform07(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+                                       [-1, 0], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [4, 1, 3, 2],
+                                                   [7, 6, 8, 5]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform08(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+                                       [-1, -1], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3],
+                                                   [0, 7, 6, 8]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform09(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        if (order > 1):
+            filtered = ndimage.spline_filter(data, order=order)
+        else:
+            filtered = data
+        out = ndimage.affine_transform(filtered, xp.asarray([[1, 0], [0, 1]]),
+                                       [-1, -1], order=order,
+                                       prefilter=False)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3],
+                                                   [0, 7, 6, 8]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform10(self, order, xp):
+        data = xp.ones([2], dtype=xp.float64)
+        out = ndimage.affine_transform(data, xp.asarray([[0.5]]), output_shape=(4,),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform11(self, order, xp):
+        data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
+        out = ndimage.affine_transform(data, xp.asarray([[2]]), 0, (4,), order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform12(self, order, xp):
+        data = xp.asarray([1, 2, 3, 4])
+        out = ndimage.affine_transform(data, xp.asarray([[0.5]]), 0, (8,), order=order)
+        assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform13(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9.0, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 2]]), 0, (3, 2),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform14(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 1]]), 0, (1, 4),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform15(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 2]]), 0, (1, 2),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([[1, 3]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform16(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[1, 0.0], [0, 0.5]]), 0,
+                                       (3, 8), order=order)
+        assert_array_almost_equal(out[..., ::2], data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform17(self, order, xp):
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 1]]), 0,
+                                       (6, 4), order=order)
+        assert_array_almost_equal(out[::2, ...], data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform18(self, order, xp):
+        data = xp.asarray([[1, 2, 3, 4],
+                           [5, 6, 7, 8],
+                           [9, 10, 11, 12]])
+        out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
+                                       (6, 8), order=order)
+        assert_array_almost_equal(out[::2, ::2], data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform19(self, order, xp):
+        data = xp.asarray([[1, 2, 3, 4],
+                           [5, 6, 7, 8],
+                           [9, 10, 11, 12]], dtype=xp.float64)
+        out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
+                                       (6, 8), order=order)
+        out = ndimage.affine_transform(out, xp.asarray([[2.0, 0], [0, 2.0]]), 0,
+                                       (3, 4), order=order)
+        assert_array_almost_equal(out, data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform20(self, order, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8394")
+
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[0], [2]]), 0, (2,),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 3]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform21(self, order, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8394")
+
+        data = [[1, 2, 3, 4],
+                [5, 6, 7, 8],
+                [9, 10, 11, 12]]
+        data = xp.asarray(data)
+        out = ndimage.affine_transform(data, xp.asarray([[2], [0]]), 0, (2,),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 9]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform22(self, order, xp):
+        # shift and offset interaction; see issue #1547
+        data = xp.asarray([4, 1, 3, 2])
+        out = ndimage.affine_transform(data, xp.asarray([[2]]), [-1], (3,),
+                                       order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 2]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform23(self, order, xp):
+        # shift and offset interaction; see issue #1547
+        data = xp.asarray([4, 1, 3, 2])
+        out = ndimage.affine_transform(data, xp.asarray([[0.5]]), [-1], (8,),
+                                       order=order)
+        assert_array_almost_equal(out[::2], xp.asarray([0, 4, 1, 3]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform24(self, order, xp):
+        # consistency between diagonal and non-diagonal case; see issue #1547
+        data = xp.asarray([4, 1, 3, 2])
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       'The behavior of affine_transform with a 1-D array .* '
+                       'has changed')
+            out1 = ndimage.affine_transform(data, xp.asarray([2]), -1, order=order)
+        out2 = ndimage.affine_transform(data, xp.asarray([[2]]), -1, order=order)
+        assert_array_almost_equal(out1, out2)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform25(self, order, xp):
+        # consistency between diagonal and non-diagonal case; see issue #1547
+        data = xp.asarray([4, 1, 3, 2])
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       'The behavior of affine_transform with a 1-D array .* '
+                       'has changed')
+            out1 = ndimage.affine_transform(data, xp.asarray([0.5]), -1, order=order)
+        out2 = ndimage.affine_transform(data, xp.asarray([[0.5]]), -1, order=order)
+        assert_array_almost_equal(out1, out2)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform26(self, order, xp):
+        # test homogeneous coordinates
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        if (order > 1):
+            filtered = ndimage.spline_filter(data, order=order)
+        else:
+            filtered = data
+        tform_original = xp.eye(2)
+        offset_original = -xp.ones((2, 1))
+
+        concat = array_namespace(tform_original, offset_original).concat
+        tform_h1 = concat((tform_original, offset_original), axis=1)  # hstack
+        tform_h2 = concat( (tform_h1, xp.asarray([[0.0, 0, 1]])), axis=0)  # vstack
+
+        offs = [float(x) for x in xp.reshape(offset_original, (-1,))]
+
+        out1 = ndimage.affine_transform(filtered, tform_original,
+                                        offs,
+                                        order=order, prefilter=False)
+        out2 = ndimage.affine_transform(filtered, tform_h1, order=order,
+                                        prefilter=False)
+        out3 = ndimage.affine_transform(filtered, tform_h2, order=order,
+                                        prefilter=False)
+        for out in [out1, out2, out3]:
+            assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                       [0, 4, 1, 3],
+                                                       [0, 7, 6, 8]]))
+
+    def test_affine_transform27(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not raise")
+
+        # test valid homogeneous transformation matrix
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        concat = array_namespace(data).concat
+        tform_h1 = concat( (xp.eye(2), -xp.ones((2, 1))) , axis=1)  # vstack
+        tform_h2 = concat((tform_h1, xp.asarray([[5.0, 2, 1]])), axis=0)  # hstack
+
+        assert_raises(ValueError, ndimage.affine_transform, data, tform_h2)
+
+    @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+    def test_affine_transform_1d_endianness_with_output_parameter(self, xp):
+        # 1d affine transform given output ndarray or dtype with
+        # either endianness. see issue #7388
+        data = xp.ones((2, 2))
+        for out in [xp.empty_like(data),
+                    xp.empty_like(data).astype(data.dtype.newbyteorder()),
+                    data.dtype, data.dtype.newbyteorder()]:
+            with suppress_warnings() as sup:
+                sup.filter(UserWarning,
+                           'The behavior of affine_transform with a 1-D array '
+                           '.* has changed')
+                matrix = xp.asarray([1, 1])
+                returned = ndimage.affine_transform(data, matrix, output=out)
+            result = out if returned is None else returned
+            assert_array_almost_equal(result, xp.asarray([[1, 1], [1, 1]]))
+
+    @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+    def test_affine_transform_multi_d_endianness_with_output_parameter(self, xp):
+        # affine transform given output ndarray or dtype with either endianness
+        # see issue #4127
+        # NB: byteorder is numpy-specific
+        data = np.asarray([1])
+        for out in [data.dtype, data.dtype.newbyteorder(),
+                    np.empty_like(data),
+                    np.empty_like(data).astype(data.dtype.newbyteorder())]:
+            returned = ndimage.affine_transform(data, np.asarray([[1]]), output=out)
+            result = out if returned is None else returned
+            assert_array_almost_equal(result, np.asarray([1]))
+
+    @skip_xp_backends(np_only=True,
+        reason='`out` of a different size is numpy-specific'
+    )
+    def test_affine_transform_output_shape(self, xp):
+        # don't require output_shape when out of a different size is given
+        data = xp.arange(8, dtype=xp.float64)
+        out = xp.ones((16,))
+
+        ndimage.affine_transform(data, xp.asarray([[1]]), output=out)
+        assert_array_almost_equal(out[:8], data)
+
+        # mismatched output shape raises an error
+        with pytest.raises(RuntimeError):
+            ndimage.affine_transform(
+                data, [[1]], output=out, output_shape=(12,))
+
+    @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+    def test_affine_transform_with_string_output(self, xp):
+        data = xp.asarray([1])
+        out = ndimage.affine_transform(data, xp.asarray([[1]]), output='f')
+        assert out.dtype is np.dtype('f')
+        assert_array_almost_equal(out, xp.asarray([1]))
+
+    @pytest.mark.parametrize('shift',
+                             [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform_shift_via_grid_wrap(self, shift, order, xp):
+        # For mode 'grid-wrap', integer shifts should match np.roll
+        x = np.asarray([[0, 1],
+                        [2, 3]])
+        affine = np.zeros((2, 3))
+        affine[:2, :2] = np.eye(2)
+        affine[:, 2] = np.asarray(shift)
+
+        expected = np.roll(x, shift, axis=(0, 1))
+
+        x = xp.asarray(x)
+        affine = xp.asarray(affine)
+        expected = xp.asarray(expected)
+
+        assert_array_almost_equal(
+            ndimage.affine_transform(x, affine, mode='grid-wrap', order=order),
+            expected
+        )
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_affine_transform_shift_reflect(self, order, xp):
+        # shift by x.shape results in reflection
+        x = np.asarray([[0, 1, 2],
+                        [3, 4, 5]])
+        expected = x[::-1, ::-1].copy()   # strides >0 for torch
+        x = xp.asarray(x)
+        expected = xp.asarray(expected)
+
+        affine = np.zeros([2, 3])
+        affine[:2, :2] = np.eye(2)
+        affine[:, 2] = np.asarray(x.shape)
+        affine = xp.asarray(affine)
+
+        assert_array_almost_equal(
+            ndimage.affine_transform(x, affine, mode='reflect', order=order),
+            expected,
+        )
+
+
+class TestShift:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift01(self, order, xp):
+        data = xp.asarray([1])
+        out = ndimage.shift(data, [1], order=order)
+        assert_array_almost_equal(out, xp.asarray([0]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift02(self, order, xp):
+        data = xp.ones([4])
+        out = ndimage.shift(data, [1], order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift03(self, order, xp):
+        data = xp.ones([4])
+        out = ndimage.shift(data, -1, order=order)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift04(self, order, xp):
+        data = xp.asarray([4, 1, 3, 2])
+        out = ndimage.shift(data, 1, order=order)
+        assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_shift05(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[1, 1, 1, 1],
+                           [1, 1, 1, 1],
+                           [1, 1, 1, 1]], dtype=dtype)
+        expected = xp.asarray([[0, 1, 1, 1],
+                               [0, 1, 1, 1],
+                               [0, 1, 1, 1]], dtype=dtype)
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+        out = ndimage.shift(data, [0, 1], order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('mode', ['constant', 'grid-constant'])
+    @pytest.mark.parametrize('dtype', ['float64', 'complex128'])
+    def test_shift_with_nonzero_cval(self, order, mode, dtype, xp):
+        data = np.asarray([[1, 1, 1, 1],
+                           [1, 1, 1, 1],
+                           [1, 1, 1, 1]], dtype=dtype)
+
+        expected = np.asarray([[0, 1, 1, 1],
+                               [0, 1, 1, 1],
+                               [0, 1, 1, 1]], dtype=dtype)
+
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+        cval = 5.0
+        expected[:, 0] = cval  # specific to shift of [0, 1] used below
+
+        data = xp.asarray(data)
+        expected = xp.asarray(expected)
+        out = ndimage.shift(data, [0, 1], order=order, mode=mode, cval=cval)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift06(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.shift(data, [0, 1], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
+                                                   [0, 7, 6, 8],
+                                                   [0, 3, 5, 3]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift07(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.shift(data, [1, 0], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [4, 1, 3, 2],
+                                                   [7, 6, 8, 5]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift08(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        out = ndimage.shift(data, [1, 1], order=order)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3],
+                                                   [0, 7, 6, 8]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift09(self, order, xp):
+        data = xp.asarray([[4, 1, 3, 2],
+                           [7, 6, 8, 5],
+                           [3, 5, 3, 6]])
+        if (order > 1):
+            filtered = ndimage.spline_filter(data, order=order)
+        else:
+            filtered = data
+        out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+                                                   [0, 4, 1, 3],
+                                                   [0, 7, 6, 8]]))
+
+    @pytest.mark.parametrize('shift',
+                             [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift_grid_wrap(self, shift, order, xp):
+        # For mode 'grid-wrap', integer shifts should match np.roll
+        x = np.asarray([[0, 1],
+                        [2, 3]])
+        expected = np.roll(x, shift, axis=(0,1))
+
+        x = xp.asarray(x)
+        expected = xp.asarray(expected)
+
+        assert_array_almost_equal(
+            ndimage.shift(x, shift, mode='grid-wrap', order=order),
+            expected
+        )
+
+    @pytest.mark.parametrize('shift',
+                             [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift_grid_constant1(self, shift, order, xp):
+        # For integer shifts, 'constant' and 'grid-constant' should be equal
+        x = xp.reshape(xp.arange(20), (5, 4))
+        assert_array_almost_equal(
+            ndimage.shift(x, shift, mode='grid-constant', order=order),
+            ndimage.shift(x, shift, mode='constant', order=order),
+        )
+
+    def test_shift_grid_constant_order1(self, xp):
+        x = xp.asarray([[1, 2, 3],
+                        [4, 5, 6]], dtype=xp.float64)
+        expected_result = xp.asarray([[0.25, 0.75, 1.25],
+                                      [1.25, 3.00, 4.00]])
+        assert_array_almost_equal(
+            ndimage.shift(x, (0.5, 0.5), mode='grid-constant', order=1),
+            expected_result,
+        )
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_shift_reflect(self, order, xp):
+        # shift by x.shape results in reflection
+        x = np.asarray([[0, 1, 2],
+                        [3, 4, 5]])
+        expected = x[::-1, ::-1].copy()   # strides > 0 for torch
+
+        x = xp.asarray(x)
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(
+            ndimage.shift(x, x.shape, mode='reflect', order=order),
+            expected,
+        )
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('prefilter', [False, True])
+    def test_shift_nearest_boundary(self, order, prefilter, xp):
+        # verify that shifting at least order // 2 beyond the end of the array
+        # gives a value equal to the edge value.
+        x = xp.arange(16)
+        kwargs = dict(mode='nearest', order=order, prefilter=prefilter)
+        assert_array_almost_equal(
+            ndimage.shift(x, order // 2 + 1, **kwargs)[0], x[0],
+        )
+        assert_array_almost_equal(
+            ndimage.shift(x, -order // 2 - 1, **kwargs)[-1], x[-1],
+        )
+
+    @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
+                                      'mirror', 'reflect'])
+    @pytest.mark.parametrize('order', range(6))
+    def test_shift_vs_padded(self, order, mode, xp):
+        x_np = np.arange(144, dtype=float).reshape(12, 12)
+        shift = (0.4, -2.3)
+
+        # manually pad and then extract center to get expected result
+        npad = 32
+        pad_mode = ndimage_to_numpy_mode.get(mode)
+        x_padded = xp.asarray(np.pad(x_np, npad, mode=pad_mode))
+        x = xp.asarray(x_np)
+
+        center_slice = tuple([slice(npad, -npad)] * x.ndim)
+        expected_result = ndimage.shift(
+            x_padded, shift, mode=mode, order=order)[center_slice]
+
+        xp_assert_close(
+            ndimage.shift(x, shift, mode=mode, order=order),
+            expected_result,
+            rtol=1e-7,
+        )
+
+
+class TestZoom:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_zoom1(self, order, xp):
+        for z in [2, [2, 2]]:
+            arr = xp.reshape(xp.arange(25, dtype=xp.float64), (5, 5))
+            arr = ndimage.zoom(arr, z, order=order)
+            assert arr.shape == (10, 10)
+            assert xp.all(arr[-1, :] != 0)
+            assert xp.all(arr[-1, :] >= (20 - eps))
+            assert xp.all(arr[0, :] <= (5 + eps))
+            assert xp.all(arr >= (0 - eps))
+            assert xp.all(arr <= (24 + eps))
+
+    def test_zoom2(self, xp):
+        arr = xp.reshape(xp.arange(12), (3, 4))
+        out = ndimage.zoom(ndimage.zoom(arr, 2), 0.5)
+        xp_assert_equal(out, arr)
+
+    def test_zoom3(self, xp):
+        arr = xp.asarray([[1, 2]])
+        out1 = ndimage.zoom(arr, (2, 1))
+        out2 = ndimage.zoom(arr, (1, 2))
+
+        assert_array_almost_equal(out1, xp.asarray([[1, 2], [1, 2]]))
+        assert_array_almost_equal(out2, xp.asarray([[1, 1, 2, 2]]))
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_zoom_affine01(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[1, 2, 3, 4],
+                           [5, 6, 7, 8],
+                           [9, 10, 11, 12]], dtype=dtype)
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning,
+                       'The behavior of affine_transform with a 1-D array .* '
+                       'has changed')
+            out = ndimage.affine_transform(data, xp.asarray([0.5, 0.5]), 0,
+                                           (6, 8), order=order)
+        assert_array_almost_equal(out[::2, ::2], data)
+
+    def test_zoom_infinity(self, xp):
+        # Ticket #1419 regression test
+        dim = 8
+        ndimage.zoom(xp.zeros((dim, dim)), 1. / dim, mode='nearest')
+
+    def test_zoom_zoomfactor_one(self, xp):
+        # Ticket #1122 regression test
+        arr = xp.zeros((1, 5, 5))
+        zoom = (1.0, 2.0, 2.0)
+
+        out = ndimage.zoom(arr, zoom, cval=7)
+        ref = xp.zeros((1, 10, 10))
+        assert_array_almost_equal(out, ref)
+
+    def test_zoom_output_shape_roundoff(self, xp):
+        arr = xp.zeros((3, 11, 25))
+        zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25)
+        out = ndimage.zoom(arr, zoom)
+        assert out.shape == (4, 15, 29)
+
+    @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
+    @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect',
+                                      'mirror', 'grid-wrap', 'grid-mirror',
+                                      'grid-constant'])
+    def test_zoom_by_int_order0(self, zoom, mode, xp):
+        # order 0 zoom should be the same as replication via np.kron
+        # Note: This is not True for general x shapes when grid_mode is False,
+        #       but works here for all modes because the size ratio happens to
+        #       always be an integer when x.shape = (2, 2).
+        x_np = np.asarray([[0, 1],
+                           [2, 3]], dtype=np.float64)
+        expected = np.kron(x_np, np.ones(zoom))
+
+        x = xp.asarray(x_np)
+        expected = xp.asarray(expected)
+
+        assert_array_almost_equal(
+            ndimage.zoom(x, zoom, order=0, mode=mode),
+            expected
+        )
+
+    @pytest.mark.parametrize('shape', [(2, 3), (4, 4)])
+    @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
+    @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror',
+                                      'grid-wrap', 'grid-constant'])
+    def test_zoom_grid_by_int_order0(self, shape, zoom, mode, xp):
+        # When grid_mode is True,  order 0 zoom should be the same as
+        # replication via np.kron. The only exceptions to this are the
+        # non-grid modes 'constant' and 'wrap'.
+        x_np = np.arange(np.prod(shape), dtype=float).reshape(shape)
+
+        x = xp.asarray(x_np)
+        assert_array_almost_equal(
+            ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True),
+            xp.asarray(np.kron(x_np, np.ones(zoom)))
+        )
+
+    @pytest.mark.parametrize('mode', ['constant', 'wrap'])
+    @pytest.mark.thread_unsafe
+    def test_zoom_grid_mode_warnings(self, mode, xp):
+        # Warn on use of non-grid modes when grid_mode is True
+        x = xp.reshape(xp.arange(9, dtype=xp.float64), (3, 3))
+        with pytest.warns(UserWarning,
+                          match="It is recommended to use mode"):
+            ndimage.zoom(x, 2, mode=mode, grid_mode=True),
+
+    @skip_xp_backends(np_only=True, reason='inplace output= is numpy-specific')
+    def test_zoom_output_shape(self, xp):
+        """Ticket #643"""
+        x = xp.reshape(xp.arange(12), (3, 4))
+        ndimage.zoom(x, 2, output=xp.zeros((6, 8)))
+
+    def test_zoom_0d_array(self, xp):
+        # Ticket #21670 regression test
+        a = xp.arange(10.)
+        factor = 2
+        actual = ndimage.zoom(a, np.array(factor))
+        expected = ndimage.zoom(a, factor)
+        xp_assert_close(actual, expected)
+
+
+class TestRotate:
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate01(self, order, xp):
+        data = xp.asarray([[0, 0, 0, 0],
+                           [0, 1, 1, 0],
+                           [0, 0, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 0, order=order)
+        assert_array_almost_equal(out, data)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate02(self, order, xp):
+        data = xp.asarray([[0, 0, 0, 0],
+                           [0, 1, 0, 0],
+                           [0, 0, 0, 0]], dtype=xp.float64)
+        expected = xp.asarray([[0, 0, 0],
+                               [0, 0, 0],
+                               [0, 1, 0],
+                               [0, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 90, order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+    def test_rotate03(self, order, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0]], dtype=dtype)
+        expected = xp.asarray([[0, 0, 0],
+                               [0, 0, 0],
+                               [0, 1, 0],
+                               [0, 1, 0],
+                               [0, 0, 0]], dtype=dtype)
+        isdtype = array_namespace(data).isdtype
+        if isdtype(data.dtype, 'complex floating'):
+            data -= 1j * data
+            expected -= 1j * expected
+        out = ndimage.rotate(data, 90, order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate04(self, order, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0]], dtype=xp.float64)
+        expected = xp.asarray([[0, 0, 0, 0, 0],
+                               [0, 0, 1, 0, 0],
+                               [0, 0, 1, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 90, reshape=False, order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate05(self, order, xp):
+        data = np.empty((4, 3, 3))
+        for i in range(3):
+            data[:, :, i] = np.asarray([[0, 0, 0],
+                                        [0, 1, 0],
+                                        [0, 1, 0],
+                                        [0, 0, 0]], dtype=np.float64)
+        data = xp.asarray(data)
+        expected = xp.asarray([[0, 0, 0, 0],
+                               [0, 1, 1, 0],
+                               [0, 0, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 90, order=order)
+        for i in range(3):
+            assert_array_almost_equal(out[:, :, i], expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate06(self, order, xp):
+        data = np.empty((3, 4, 3))
+        for i in range(3):
+            data[:, :, i] = np.asarray([[0, 0, 0, 0],
+                                        [0, 1, 1, 0],
+                                        [0, 0, 0, 0]], dtype=np.float64)
+        data = xp.asarray(data)
+        expected = xp.asarray([[0, 0, 0],
+                               [0, 1, 0],
+                               [0, 1, 0],
+                               [0, 0, 0]], dtype=xp.float64)
+        out = ndimage.rotate(data, 90, order=order)
+        for i in range(3):
+            assert_array_almost_equal(out[:, :, i], expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate07(self, order, xp):
+        data = xp.asarray([[[0, 0, 0, 0, 0],
+                            [0, 1, 1, 0, 0],
+                            [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+        permute_dims = array_namespace(data).permute_dims
+        data = permute_dims(data, (2, 1, 0))
+        expected = xp.asarray([[[0, 0, 0],
+                                [0, 1, 0],
+                                [0, 1, 0],
+                                [0, 0, 0],
+                                [0, 0, 0]]] * 2, dtype=xp.float64)
+        expected = permute_dims(expected, (2, 1, 0))
+        out = ndimage.rotate(data, 90, axes=(0, 1), order=order)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('order', range(0, 6))
+    def test_rotate08(self, order, xp):
+        data = xp.asarray([[[0, 0, 0, 0, 0],
+                            [0, 1, 1, 0, 0],
+                            [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+        permute_dims = array_namespace(data).permute_dims
+        data = permute_dims(data, (2, 1, 0))  # == np.transpose
+        expected = xp.asarray([[[0, 0, 1, 0, 0],
+                                [0, 0, 1, 0, 0],
+                                [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+        permute_dims = array_namespace(data).permute_dims
+        expected = permute_dims(expected, (2, 1, 0))
+        out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False, order=order)
+        assert_array_almost_equal(out, expected)
+
+    def test_rotate09(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0]] * 2, dtype=xp.float64)
+        with assert_raises(ValueError):
+            ndimage.rotate(data, 90, axes=(0, data.ndim))
+
+    def test_rotate10(self, xp):
+        data = xp.reshape(xp.arange(45, dtype=xp.float64), (3, 5, 3))
+
+	# The output of ndimage.rotate before refactoring
+        expected = xp.asarray([[[0.0, 0.0, 0.0],
+                                [0.0, 0.0, 0.0],
+                                [6.54914793, 7.54914793, 8.54914793],
+                                [10.84520162, 11.84520162, 12.84520162],
+                                [0.0, 0.0, 0.0]],
+                               [[6.19286575, 7.19286575, 8.19286575],
+                                [13.4730712, 14.4730712, 15.4730712],
+                                [21.0, 22.0, 23.0],
+                                [28.5269288, 29.5269288, 30.5269288],
+                                [35.80713425, 36.80713425, 37.80713425]],
+                               [[0.0, 0.0, 0.0],
+                                [31.15479838, 32.15479838, 33.15479838],
+                                [35.45085207, 36.45085207, 37.45085207],
+                                [0.0, 0.0, 0.0],
+                                [0.0, 0.0, 0.0]]], dtype=xp.float64)
+
+        out = ndimage.rotate(data, angle=12, reshape=False)
+        #assert_array_almost_equal(out, expected)
+        xp_assert_close(out, expected, rtol=1e-6, atol=2e-6)
+
+    def test_rotate_exact_180(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("https://github.com/cupy/cupy/issues/8400")
+
+        a = np.tile(xp.arange(5), (5, 1))
+        b = ndimage.rotate(ndimage.rotate(a, 180), -180)
+        xp_assert_equal(a, b)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8175ba309dd223a6d0fd46df017ea1fbc797a4e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_measurements.py
@@ -0,0 +1,1609 @@
+import os
+import os.path
+
+import numpy as np
+from numpy.testing import suppress_warnings
+
+from scipy._lib._array_api import (
+    is_jax,
+    is_torch,
+    array_namespace,
+    xp_assert_equal,
+    xp_assert_close,
+    assert_array_almost_equal,
+    assert_almost_equal,
+)
+
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.ndimage as ndimage
+
+from . import types
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+IS_WINDOWS_AND_NP1 = os.name == 'nt' and np.__version__ < '2'
+
+
+@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
+class Test_measurements_stats:
+    """ndimage._measurements._stats() is a utility used by other functions.
+
+        Since internal ndimage/_measurements.py code is NumPy-only,
+        so is this this test class.
+    """
+    def test_a(self, xp):
+        x = [0, 1, 2, 6]
+        labels = [0, 0, 1, 1]
+        index = [0, 1]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums = ndimage._measurements._stats(
+                x, labels=labels, index=index)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+
+    def test_b(self, xp):
+        # Same data as test_a, but different labels.  The label 9 exceeds the
+        # length of 'labels', so this test will follow a different code path.
+        x = [0, 1, 2, 6]
+        labels = [0, 0, 9, 9]
+        index = [0, 9]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums = ndimage._measurements._stats(
+                x, labels=labels, index=index)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+
+    def test_a_centered(self, xp):
+        x = [0, 1, 2, 6]
+        labels = [0, 0, 1, 1]
+        index = [0, 1]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums, centers = ndimage._measurements._stats(
+                x, labels=labels, index=index, centered=True)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+            xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+    def test_b_centered(self, xp):
+        x = [0, 1, 2, 6]
+        labels = [0, 0, 9, 9]
+        index = [0, 9]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums, centers = ndimage._measurements._stats(
+                x, labels=labels, index=index, centered=True)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+            xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+    def test_nonint_labels(self, xp):
+        x = [0, 1, 2, 6]
+        labels = [0.0, 0.0, 9.0, 9.0]
+        index = [0.0, 9.0]
+        for shp in [(4,), (2, 2)]:
+            x = np.array(x).reshape(shp)
+            labels = np.array(labels).reshape(shp)
+            counts, sums, centers = ndimage._measurements._stats(
+                x, labels=labels, index=index, centered=True)
+
+            dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+            xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+            xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+            xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+
+class Test_measurements_select:
+    """ndimage._measurements._select() is a utility used by other functions."""
+
+    def test_basic(self, xp):
+        x = [0, 1, 6, 2]
+        cases = [
+            ([0, 0, 1, 1], [0, 1]),           # "Small" integer labels
+            ([0, 0, 9, 9], [0, 9]),           # A label larger than len(labels)
+            ([0.0, 0.0, 7.0, 7.0], [0.0, 7.0]),   # Non-integer labels
+        ]
+        for labels, index in cases:
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index)
+            assert len(result) == 0
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index, find_max=True)
+            assert len(result) == 1
+            xp_assert_equal(result[0], [1, 6])
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index, find_min=True)
+            assert len(result) == 1
+            xp_assert_equal(result[0], [0, 2])
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index, find_min=True,
+                find_min_positions=True)
+            assert len(result) == 2
+            xp_assert_equal(result[0], [0, 2])
+            xp_assert_equal(result[1], [0, 3])
+            assert result[1].dtype.kind == 'i'
+            result = ndimage._measurements._select(
+                x, labels=labels, index=index, find_max=True,
+                find_max_positions=True)
+            assert len(result) == 2
+            xp_assert_equal(result[0], [1, 6])
+            xp_assert_equal(result[1], [1, 2])
+            assert result[1].dtype.kind == 'i'
+
+
+def test_label01(xp):
+    data = xp.ones([])
+    out, n = ndimage.label(data)
+    assert out == 1
+    assert n == 1
+
+
+def test_label02(xp):
+    data = xp.zeros([])
+    out, n = ndimage.label(data)
+    assert out == 0
+    assert n == 0
+
+
+@pytest.mark.thread_unsafe  # due to Cython fused types, see cython#6506
+def test_label03(xp):
+    data = xp.ones([1])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([1]))
+    assert n == 1
+
+
+def test_label04(xp):
+    data = xp.zeros([1])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([0]))
+    assert n == 0
+
+
+def test_label05(xp):
+    data = xp.ones([5])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+    assert n == 1
+
+
+def test_label06(xp):
+    data = xp.asarray([1, 0, 1, 1, 0, 1])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([1, 0, 2, 2, 0, 3]))
+    assert n == 3
+
+
+def test_label07(xp):
+    data = xp.asarray([[0, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0]])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray(
+                                    [[0, 0, 0, 0, 0, 0],
+                                     [0, 0, 0, 0, 0, 0],
+                                     [0, 0, 0, 0, 0, 0],
+                                     [0, 0, 0, 0, 0, 0],
+                                     [0, 0, 0, 0, 0, 0],
+                                     [0, 0, 0, 0, 0, 0]]))
+    assert n == 0
+
+
+def test_label08(xp):
+    data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                       [0, 0, 1, 1, 0, 0],
+                       [0, 0, 1, 1, 1, 0],
+                       [1, 1, 0, 0, 0, 0],
+                       [1, 1, 0, 0, 0, 0],
+                       [0, 0, 0, 1, 1, 0]])
+    out, n = ndimage.label(data)
+    assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
+                                               [0, 0, 2, 2, 0, 0],
+                                               [0, 0, 2, 2, 2, 0],
+                                               [3, 3, 0, 0, 0, 0],
+                                               [3, 3, 0, 0, 0, 0],
+                                               [0, 0, 0, 4, 4, 0]]))
+    assert n == 4
+
+
+def test_label09(xp):
+    data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                       [0, 0, 1, 1, 0, 0],
+                       [0, 0, 1, 1, 1, 0],
+                       [1, 1, 0, 0, 0, 0],
+                       [1, 1, 0, 0, 0, 0],
+                       [0, 0, 0, 1, 1, 0]])
+    struct = ndimage.generate_binary_structure(2, 2)
+    struct = xp.asarray(struct)
+    out, n = ndimage.label(data, struct)
+    assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
+                                               [0, 0, 2, 2, 0, 0],
+                                               [0, 0, 2, 2, 2, 0],
+                                               [2, 2, 0, 0, 0, 0],
+                                               [2, 2, 0, 0, 0, 0],
+                                               [0, 0, 0, 3, 3, 0]]))
+    assert n == 3
+
+
+def test_label10(xp):
+    data = xp.asarray([[0, 0, 0, 0, 0, 0],
+                       [0, 1, 1, 0, 1, 0],
+                       [0, 1, 1, 1, 1, 0],
+                       [0, 0, 0, 0, 0, 0]])
+    struct = ndimage.generate_binary_structure(2, 2)
+    struct = xp.asarray(struct)
+    out, n = ndimage.label(data, struct)
+    assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0, 0, 0],
+                                               [0, 1, 1, 0, 1, 0],
+                                               [0, 1, 1, 1, 1, 0],
+                                               [0, 0, 0, 0, 0, 0]]))
+    assert n == 1
+
+
+def test_label11(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0],
+                           [1, 1, 0, 0, 0, 0],
+                           [1, 1, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 0]], dtype=dtype)
+        out, n = ndimage.label(data)
+        expected = [[1, 0, 0, 0, 0, 0],
+                    [0, 0, 2, 2, 0, 0],
+                    [0, 0, 2, 2, 2, 0],
+                    [3, 3, 0, 0, 0, 0],
+                    [3, 3, 0, 0, 0, 0],
+                    [0, 0, 0, 4, 4, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+        assert n == 4
+
+
+@skip_xp_backends(np_only=True, reason='inplace output is numpy-specific')
+def test_label11_inplace(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0],
+                           [1, 1, 0, 0, 0, 0],
+                           [1, 1, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 0]], dtype=dtype)
+        n = ndimage.label(data, output=data)
+        expected = [[1, 0, 0, 0, 0, 0],
+                    [0, 0, 2, 2, 0, 0],
+                    [0, 0, 2, 2, 2, 0],
+                    [3, 3, 0, 0, 0, 0],
+                    [3, 3, 0, 0, 0, 0],
+                    [0, 0, 0, 4, 4, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(data, expected)
+        assert n == 4
+
+
+def test_label12(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        data = xp.asarray([[0, 0, 0, 0, 1, 1],
+                           [0, 0, 0, 0, 0, 1],
+                           [0, 0, 1, 0, 1, 1],
+                           [0, 0, 1, 1, 1, 1],
+                           [0, 0, 0, 1, 1, 0]], dtype=dtype)
+        out, n = ndimage.label(data)
+        expected = [[0, 0, 0, 0, 1, 1],
+                    [0, 0, 0, 0, 0, 1],
+                    [0, 0, 1, 0, 1, 1],
+                    [0, 0, 1, 1, 1, 1],
+                    [0, 0, 0, 1, 1, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+        assert n == 1
+
+
+def test_label13(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        data = xp.asarray([[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
+                           [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
+                           [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+                           [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]],
+                          dtype=dtype)
+        out, n = ndimage.label(data)
+        expected = [[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
+                    [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
+                    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+        assert n == 1
+
+
+@skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+def test_label_output_typed(xp):
+    data = xp.ones([5])
+    for t in types:
+        dtype = getattr(xp, t)
+        output = xp.zeros([5], dtype=dtype)
+        n = ndimage.label(data, output=output)
+        assert_array_almost_equal(output,
+                                  xp.ones(output.shape, dtype=output.dtype))
+        assert n == 1
+
+
+@skip_xp_backends(np_only=True, reason='output=dtype is numpy-specific')
+def test_label_output_dtype(xp):
+    data = xp.ones([5])
+    for t in types:
+        dtype = getattr(xp, t)
+        output, n = ndimage.label(data, output=dtype)
+        assert_array_almost_equal(output,
+                                  xp.ones(output.shape, dtype=output.dtype))
+        assert output.dtype == t
+
+
+def test_label_output_wrong_size(xp):
+    if is_jax(xp):
+        pytest.xfail("JAX does not raise")
+
+    data = xp.ones([5])
+    for t in types:
+        dtype = getattr(xp, t)
+        output = xp.zeros([10], dtype=dtype)
+        # TypeError is from non-numpy arrays as output
+        assert_raises((ValueError, TypeError),
+                      ndimage.label, data, output=output)
+
+
+def test_label_structuring_elements(xp):
+    data = np.loadtxt(os.path.join(os.path.dirname(
+        __file__), "data", "label_inputs.txt"))
+    strels = np.loadtxt(os.path.join(
+        os.path.dirname(__file__), "data", "label_strels.txt"))
+    results = np.loadtxt(os.path.join(
+        os.path.dirname(__file__), "data", "label_results.txt"))
+    data = data.reshape((-1, 7, 7))
+    strels = strels.reshape((-1, 3, 3))
+    results = results.reshape((-1, 7, 7))
+
+    data = xp.asarray(data)
+    strels = xp.asarray(strels)
+    results = xp.asarray(results)
+    r = 0
+    for i in range(data.shape[0]):
+        d = data[i, :, :]
+        for j in range(strels.shape[0]):
+            s = strels[j, :, :]
+            xp_assert_equal(ndimage.label(d, s)[0], results[r, :, :], check_dtype=False)
+            r += 1
+
+@skip_xp_backends("cupy",
+                  reason="`cupyx.scipy.ndimage` does not have `find_objects`"
+)
+def test_ticket_742(xp):
+    def SE(img, thresh=.7, size=4):
+        mask = img > thresh
+        rank = len(mask.shape)
+        struct = ndimage.generate_binary_structure(rank, rank)
+        struct = xp.asarray(struct)
+        la, co = ndimage.label(mask,
+                               struct)
+        _ = ndimage.find_objects(la)
+
+    if np.dtype(np.intp) != np.dtype('i'):
+        shape = (3, 1240, 1240)
+        a = np.random.rand(np.prod(shape)).reshape(shape)
+        a = xp.asarray(a)
+        # shouldn't crash
+        SE(a)
+
+
+def test_gh_issue_3025(xp):
+    """Github issue #3025 - improper merging of labels"""
+    d = np.zeros((60, 320))
+    d[:, :257] = 1
+    d[:, 260:] = 1
+    d[36, 257] = 1
+    d[35, 258] = 1
+    d[35, 259] = 1
+    d = xp.asarray(d)
+    assert ndimage.label(d, xp.ones((3, 3)))[1] == 1
+
+
+@skip_xp_backends("cupy", reason="cupyx.scipy.ndimage does not have find_object")
+class TestFindObjects:
+    def test_label_default_dtype(self, xp):
+        test_array = np.random.rand(10, 10)
+        test_array = xp.asarray(test_array)
+        label, no_features = ndimage.label(test_array > 0.5)
+        assert label.dtype in (xp.int32, xp.int64)
+        # Shouldn't raise an exception
+        ndimage.find_objects(label)
+
+
+    def test_find_objects01(self, xp):
+        data = xp.ones([], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == [()]
+
+
+    def test_find_objects02(self, xp):
+        data = xp.zeros([], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == []
+
+
+    def test_find_objects03(self, xp):
+        data = xp.ones([1], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 1, None),)]
+
+
+    def test_find_objects04(self, xp):
+        data = xp.zeros([1], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == []
+
+
+    def test_find_objects05(self, xp):
+        data = xp.ones([5], dtype=xp.int64)
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 5, None),)]
+
+
+    def test_find_objects06(self, xp):
+        data = xp.asarray([1, 0, 2, 2, 0, 3])
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 1, None),),
+                       (slice(2, 4, None),),
+                       (slice(5, 6, None),)]
+
+
+    def test_find_objects07(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0]])
+        out = ndimage.find_objects(data)
+        assert out == []
+
+
+    def test_find_objects08(self, xp):
+        data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                           [0, 0, 2, 2, 0, 0],
+                           [0, 0, 2, 2, 2, 0],
+                           [3, 3, 0, 0, 0, 0],
+                           [3, 3, 0, 0, 0, 0],
+                           [0, 0, 0, 4, 4, 0]])
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 1, None), slice(0, 1, None)),
+                           (slice(1, 3, None), slice(2, 5, None)),
+                           (slice(3, 5, None), slice(0, 2, None)),
+                           (slice(5, 6, None), slice(3, 5, None))]
+
+
+    def test_find_objects09(self, xp):
+        data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                           [0, 0, 2, 2, 0, 0],
+                           [0, 0, 2, 2, 2, 0],
+                           [0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 4, 4, 0]])
+        out = ndimage.find_objects(data)
+        assert out == [(slice(0, 1, None), slice(0, 1, None)),
+                           (slice(1, 3, None), slice(2, 5, None)),
+                           None,
+                           (slice(5, 6, None), slice(3, 5, None))]
+
+
+def test_value_indices01(xp):
+    "Test dictionary keys and entries"
+    data = xp.asarray([[1, 0, 0, 0, 0, 0],
+                       [0, 0, 2, 2, 0, 0],
+                       [0, 0, 2, 2, 2, 0],
+                       [0, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 4, 4, 0]])
+    vi = ndimage.value_indices(data, ignore_value=0)
+    true_keys = [1, 2, 4]
+    assert list(vi.keys()) == true_keys
+
+    nnz_kwd = {'as_tuple': True} if is_torch(xp) else {}
+
+    truevi = {}
+    for k in true_keys:
+        truevi[k] = xp.nonzero(data == k, **nnz_kwd)
+
+    vi = ndimage.value_indices(data, ignore_value=0)
+    assert vi.keys() == truevi.keys()
+    for key in vi.keys():
+        assert len(vi[key]) == len(truevi[key])
+        for v, true_v in zip(vi[key], truevi[key]):
+            xp_assert_equal(v, true_v)
+
+
+def test_value_indices02(xp):
+    "Test input checking"
+    data = xp.zeros((5, 4), dtype=xp.float32)
+    msg = "Parameter 'arr' must be an integer array"
+    with assert_raises(ValueError, match=msg):
+        ndimage.value_indices(data)
+
+
+def test_value_indices03(xp):
+    "Test different input array shapes, from 1-D to 4-D"
+    for shape in [(36,), (18, 2), (3, 3, 4), (3, 3, 2, 2)]:
+        a = xp.asarray((12*[1]+12*[2]+12*[3]), dtype=xp.int32)
+        a = xp.reshape(a, shape)
+
+        nnz_kwd = {'as_tuple': True} if is_torch(xp) else {}
+
+        unique_values = array_namespace(a).unique_values
+        trueKeys = unique_values(a)
+        vi = ndimage.value_indices(a)
+        assert list(vi.keys()) == list(trueKeys)
+        for k in [int(x) for x in trueKeys]:
+            trueNdx = xp.nonzero(a == k, **nnz_kwd)
+            assert len(vi[k]) == len(trueNdx)
+            for vik, true_vik in zip(vi[k], trueNdx):
+                xp_assert_equal(vik, true_vik)
+
+
+def test_sum01(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([], dtype=dtype)
+        output = ndimage.sum(input)
+        assert output == 0
+
+
+def test_sum02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.zeros([0, 4], dtype=dtype)
+        output = ndimage.sum(input)
+        assert output == 0
+
+
+def test_sum03(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.ones([], dtype=dtype)
+        output = ndimage.sum(input)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_sum04(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 2], dtype=dtype)
+        output = ndimage.sum(input)
+        assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+def test_sum05(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.sum(input)
+        assert_almost_equal(output, xp.asarray(10.0), check_0d=False)
+
+
+def test_sum06(xp):
+    labels = np.asarray([], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([], dtype=dtype)
+        output = ndimage.sum(input, labels=labels)
+        assert output == 0
+
+
+def test_sum07(xp):
+    labels = np.ones([0, 4], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.zeros([0, 4], dtype=dtype)
+        output = ndimage.sum(input, labels=labels)
+        assert output == 0
+
+
+def test_sum08(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 2], dtype=dtype)
+        output = ndimage.sum(input, labels=labels)
+        assert output == 1
+
+
+def test_sum09(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.sum(input, labels=labels)
+        assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
+
+
+def test_sum10(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    input = np.asarray([[1, 2], [3, 4]], dtype=bool)
+
+    labels = xp.asarray(labels)
+    input = xp.asarray(input)
+    output = ndimage.sum(input, labels=labels)
+    assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+def test_sum11(xp):
+    labels = xp.asarray([1, 2], dtype=xp.int8)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.sum(input, labels=labels,
+                             index=2)
+        assert_almost_equal(output, xp.asarray(6.0), check_0d=False)
+
+
+def test_sum12(xp):
+    labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
+        assert_array_almost_equal(output, xp.asarray([4.0, 0.0, 5.0]))
+
+
+def test_sum_labels(xp):
+    labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output_sum = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
+        output_labels = ndimage.sum_labels(
+            input, labels=labels, index=xp.asarray([4, 8, 2]))
+
+        assert xp.all(output_sum == output_labels)
+        assert_array_almost_equal(output_labels, xp.asarray([4.0, 0.0, 5.0]))
+
+
+def test_mean01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.mean(input, labels=labels)
+        assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+def test_mean02(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    input = np.asarray([[1, 2], [3, 4]], dtype=bool)
+
+    labels = xp.asarray(labels)
+    input = xp.asarray(input)
+    output = ndimage.mean(input, labels=labels)
+    assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_mean03(xp):
+    labels = xp.asarray([1, 2])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.mean(input, labels=labels,
+                              index=2)
+        assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+def test_mean04(xp):
+    labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+            output = ndimage.mean(input, labels=labels,
+                                  index=xp.asarray([4, 8, 2]))
+            # XXX: output[[0, 2]] does not work in array-api-strict; annoying
+            # assert_array_almost_equal(output[[0, 2]], xp.asarray([4.0, 2.5]))
+            assert output[0] == 4.0
+            assert output[2] == 2.5
+            assert xp.isnan(output[1])
+
+
+def test_minimum01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.minimum(input, labels=labels)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_minimum02(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    input = np.asarray([[2, 2], [2, 4]], dtype=bool)
+
+    labels = xp.asarray(labels)
+    input = xp.asarray(input)
+    output = ndimage.minimum(input, labels=labels)
+    assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_minimum03(xp):
+    labels = xp.asarray([1, 2])
+    for type in types:
+        dtype = getattr(xp, type)
+
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.minimum(input, labels=labels,
+                                 index=2)
+        assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+def test_minimum04(xp):
+    labels = xp.asarray([[1, 2], [2, 3]])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.minimum(input, labels=labels,
+                                 index=xp.asarray([2, 3, 8]))
+        assert_array_almost_equal(output, xp.asarray([2.0, 4.0, 0.0]))
+
+
+def test_maximum01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.maximum(input, labels=labels)
+        assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+def test_maximum02(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    input = np.asarray([[2, 2], [2, 4]], dtype=bool)
+    labels = xp.asarray(labels)
+    input = xp.asarray(input)
+    output = ndimage.maximum(input, labels=labels)
+    assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_maximum03(xp):
+    labels = xp.asarray([1, 2])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.maximum(input, labels=labels,
+                                 index=2)
+        assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
+
+
+def test_maximum04(xp):
+    labels = xp.asarray([[1, 2], [2, 3]])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.maximum(input, labels=labels,
+                                 index=xp.asarray([2, 3, 8]))
+        assert_array_almost_equal(output, xp.asarray([3.0, 4.0, 0.0]))
+
+
+def test_maximum05(xp):
+    # Regression test for ticket #501 (Trac)
+    x = xp.asarray([-3, -2, -1])
+    assert ndimage.maximum(x) == -1
+
+
+def test_median01(xp):
+    a = xp.asarray([[1, 2, 0, 1],
+                    [5, 3, 0, 4],
+                    [0, 0, 0, 7],
+                    [9, 3, 0, 0]])
+    labels = xp.asarray([[1, 1, 0, 2],
+                         [1, 1, 0, 2],
+                         [0, 0, 0, 2],
+                         [3, 3, 0, 0]])
+    output = ndimage.median(a, labels=labels, index=xp.asarray([1, 2, 3]))
+    assert_array_almost_equal(output, xp.asarray([2.5, 4.0, 6.0]))
+
+
+def test_median02(xp):
+    a = xp.asarray([[1, 2, 0, 1],
+                    [5, 3, 0, 4],
+                    [0, 0, 0, 7],
+                    [9, 3, 0, 0]])
+    output = ndimage.median(a)
+    assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_median03(xp):
+    a = xp.asarray([[1, 2, 0, 1],
+                    [5, 3, 0, 4],
+                    [0, 0, 0, 7],
+                    [9, 3, 0, 0]])
+    labels = xp.asarray([[1, 1, 0, 2],
+                         [1, 1, 0, 2],
+                         [0, 0, 0, 2],
+                         [3, 3, 0, 0]])
+    output = ndimage.median(a, labels=labels)
+    assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+def test_median_gh12836_bool(xp):
+    # test boolean addition fix on example from gh-12836
+    a = np.asarray([1, 1], dtype=bool)
+    a = xp.asarray(a)
+    output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
+    assert_array_almost_equal(output, xp.asarray([1.0]))
+
+
+def test_median_no_int_overflow(xp):
+    # test integer overflow fix on example from gh-12836
+    a = xp.asarray([65, 70], dtype=xp.int8)
+    output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
+    assert_array_almost_equal(output, xp.asarray([67.5]))
+
+
+def test_variance01(xp):
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([], dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                output = ndimage.variance(input)
+            assert xp.isnan(output)
+
+
+def test_variance02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1], dtype=dtype)
+        output = ndimage.variance(input)
+        assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
+
+
+def test_variance03(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 3], dtype=dtype)
+        output = ndimage.variance(input)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_variance04(xp):
+    input = np.asarray([1, 0], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.variance(input)
+    assert_almost_equal(output, xp.asarray(0.25), check_0d=False)
+
+
+def test_variance05(xp):
+    labels = xp.asarray([2, 2, 3])
+    for type in types:
+        dtype = getattr(xp, type)
+
+        input = xp.asarray([1, 3, 8], dtype=dtype)
+        output = ndimage.variance(input, labels, 2)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_variance06(xp):
+    labels = xp.asarray([2, 2, 3, 3, 4])
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
+            output = ndimage.variance(input, labels, xp.asarray([2, 3, 4]))
+            assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
+
+
+def test_standard_deviation01(xp):
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([], dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                output = ndimage.standard_deviation(input)
+            assert xp.isnan(output)
+
+
+def test_standard_deviation02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1], dtype=dtype)
+        output = ndimage.standard_deviation(input)
+        assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
+
+
+def test_standard_deviation03(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 3], dtype=dtype)
+        output = ndimage.standard_deviation(input)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_standard_deviation04(xp):
+    input = np.asarray([1, 0], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.standard_deviation(input)
+    assert_almost_equal(output, xp.asarray(0.5), check_0d=False)
+
+
+def test_standard_deviation05(xp):
+    labels = xp.asarray([2, 2, 3])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([1, 3, 8], dtype=dtype)
+        output = ndimage.standard_deviation(input, labels, 2)
+        assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+def test_standard_deviation06(xp):
+    labels = xp.asarray([2, 2, 3, 3, 4])
+    with np.errstate(all='ignore'):
+        for type in types:
+            dtype = getattr(xp, type)
+            input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
+            output = ndimage.standard_deviation(
+                input, labels, xp.asarray([2, 3, 4])
+            )
+            assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
+
+
+def test_standard_deviation07(xp):
+    labels = xp.asarray([1])
+    with np.errstate(all='ignore'):
+        for type in types:
+            if is_torch(xp) and type == 'uint8':
+                pytest.xfail("value cannot be converted to type uint8 "
+                             "without overflow")
+            dtype = getattr(xp, type)
+            input = xp.asarray([-0.00619519], dtype=dtype)
+            output = ndimage.standard_deviation(input, labels, xp.asarray([1]))
+            assert_array_almost_equal(output, xp.asarray([0]))
+
+
+def test_minimum_position01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.minimum_position(input, labels=labels)
+        assert output == (0, 0)
+
+
+def test_minimum_position02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 0, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.minimum_position(input)
+        assert output == (1, 2)
+
+
+def test_minimum_position03(xp):
+    input = np.asarray([[5, 4, 2, 5],
+                        [3, 7, 0, 2],
+                        [1, 5, 1, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.minimum_position(input)
+    assert output == (1, 2)
+
+
+def test_minimum_position04(xp):
+    input = np.asarray([[5, 4, 2, 5],
+                        [3, 7, 1, 2],
+                        [1, 5, 1, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.minimum_position(input)
+    assert output == (0, 0)
+
+
+def test_minimum_position05(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 0, 2],
+                            [1, 5, 2, 3]], dtype=dtype)
+        output = ndimage.minimum_position(input, labels)
+        assert output == (2, 0)
+
+
+def test_minimum_position06(xp):
+    labels = xp.asarray([1, 2, 3, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 0, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.minimum_position(input, labels, 2)
+        assert output == (0, 1)
+
+
+def test_minimum_position07(xp):
+    labels = xp.asarray([1, 2, 3, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 0, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.minimum_position(input, labels,
+                                          xp.asarray([2, 3]))
+        assert output[0] == (0, 1)
+        assert output[1] == (1, 2)
+
+
+def test_maximum_position01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output = ndimage.maximum_position(input,
+                                          labels=labels)
+        assert output == (1, 0)
+
+
+def test_maximum_position02(xp):
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input)
+        assert output == (1, 2)
+
+
+def test_maximum_position03(xp):
+    input = np.asarray([[5, 4, 2, 5],
+                        [3, 7, 8, 2],
+                        [1, 5, 1, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.maximum_position(input)
+    assert output == (0, 0)
+
+
+def test_maximum_position04(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input, labels)
+        assert output == (1, 1)
+
+
+def test_maximum_position05(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input, labels, 1)
+        assert output == (0, 0)
+
+
+def test_maximum_position06(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input, labels,
+                                          xp.asarray([1, 2]))
+        assert output[0] == (0, 0)
+        assert output[1] == (1, 1)
+
+
+def test_maximum_position07(xp):
+    # Test float labels
+    if is_torch(xp):
+        pytest.xfail("output[1] is wrong on pytorch")
+
+    labels = xp.asarray([1.0, 2.5, 0.0, 4.5])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output = ndimage.maximum_position(input, labels,
+                                          xp.asarray([1.0, 4.5]))
+        assert output[0] == (0, 0)
+        assert output[1] == (0, 3)
+
+
+def test_extrema01(xp):
+    labels = np.asarray([1, 0], dtype=bool)
+    labels = xp.asarray(labels)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output1 = ndimage.extrema(input, labels=labels)
+        output2 = ndimage.minimum(input, labels=labels)
+        output3 = ndimage.maximum(input, labels=labels)
+        output4 = ndimage.minimum_position(input,
+                                           labels=labels)
+        output5 = ndimage.maximum_position(input,
+                                           labels=labels)
+        assert output1 == (output2, output3, output4, output5)
+
+
+def test_extrema02(xp):
+    labels = xp.asarray([1, 2])
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output1 = ndimage.extrema(input, labels=labels,
+                                  index=2)
+        output2 = ndimage.minimum(input, labels=labels,
+                                  index=2)
+        output3 = ndimage.maximum(input, labels=labels,
+                                  index=2)
+        output4 = ndimage.minimum_position(input,
+                                           labels=labels, index=2)
+        output5 = ndimage.maximum_position(input,
+                                           labels=labels, index=2)
+        assert output1 == (output2, output3, output4, output5)
+
+
+def test_extrema03(xp):
+    labels = xp.asarray([[1, 2], [2, 3]])
+    for type in types:
+        if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
+             pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+        output1 = ndimage.extrema(input,
+                                  labels=labels,
+                                  index=xp.asarray([2, 3, 8]))
+        output2 = ndimage.minimum(input,
+                                  labels=labels,
+                                  index=xp.asarray([2, 3, 8]))
+        output3 = ndimage.maximum(input, labels=labels,
+                                  index=xp.asarray([2, 3, 8]))
+        output4 = ndimage.minimum_position(input,
+                                           labels=labels,
+                                           index=xp.asarray([2, 3, 8]))
+        output5 = ndimage.maximum_position(input,
+                                           labels=labels,
+                                           index=xp.asarray([2, 3, 8]))
+        assert_array_almost_equal(output1[0], output2)
+        assert_array_almost_equal(output1[1], output3)
+        assert output1[2] == output4
+        assert output1[3] == output5
+
+
+def test_extrema04(xp):
+    labels = xp.asarray([1, 2, 0, 4])
+    for type in types:
+        if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
+             pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+        dtype = getattr(xp, type)
+        input = xp.asarray([[5, 4, 2, 5],
+                            [3, 7, 8, 2],
+                            [1, 5, 1, 1]], dtype=dtype)
+        output1 = ndimage.extrema(input, labels, xp.asarray([1, 2]))
+        output2 = ndimage.minimum(input, labels, xp.asarray([1, 2]))
+        output3 = ndimage.maximum(input, labels, xp.asarray([1, 2]))
+        output4 = ndimage.minimum_position(input, labels,
+                                           xp.asarray([1, 2]))
+        output5 = ndimage.maximum_position(input, labels,
+                                           xp.asarray([1, 2]))
+        assert_array_almost_equal(output1[0], output2)
+        assert_array_almost_equal(output1[1], output3)
+        assert output1[2] == output4
+        assert output1[3] == output5
+
+
+def test_center_of_mass01(xp):
+    expected = (0.0, 0.0)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 0], [0, 0]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass02(xp):
+    expected = (1, 0)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[0, 0], [1, 0]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass03(xp):
+    expected = (0, 1)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[0, 1], [0, 0]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass04(xp):
+    expected = (1, 1)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[0, 0], [0, 1]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass05(xp):
+    expected = (0.5, 0.5)
+    for type in types:
+        dtype = getattr(xp, type)
+        input = xp.asarray([[1, 1], [1, 1]], dtype=dtype)
+        output = ndimage.center_of_mass(input)
+        assert output == expected
+
+
+def test_center_of_mass06(xp):
+    expected = (0.5, 0.5)
+    input = np.asarray([[1, 2], [3, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.center_of_mass(input)
+    assert output == expected
+
+
+def test_center_of_mass07(xp):
+    labels = xp.asarray([1, 0])
+    expected = (0.5, 0.0)
+    input = np.asarray([[1, 2], [3, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.center_of_mass(input, labels)
+    assert output == expected
+
+
+def test_center_of_mass08(xp):
+    labels = xp.asarray([1, 2])
+    expected = (0.5, 1.0)
+    input = np.asarray([[5, 2], [3, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.center_of_mass(input, labels, 2)
+    assert output == expected
+
+
+def test_center_of_mass09(xp):
+    labels = xp.asarray((1, 2))
+    expected = xp.asarray([(0.5, 0.0), (0.5, 1.0)], dtype=xp.float64)
+    input = np.asarray([[1, 2], [1, 1]], dtype=bool)
+    input = xp.asarray(input)
+    output = ndimage.center_of_mass(input, labels, xp.asarray([1, 2]))
+    xp_assert_equal(xp.asarray(output), xp.asarray(expected))
+
+
+def test_histogram01(xp):
+    expected = xp.ones(10)
+    input = xp.arange(10)
+    output = ndimage.histogram(input, 0, 10, 10)
+    assert_array_almost_equal(output, expected)
+
+
+def test_histogram02(xp):
+    labels = xp.asarray([1, 1, 1, 1, 2, 2, 2, 2])
+    expected = xp.asarray([0, 2, 0, 1, 1])
+    input = xp.asarray([1, 1, 3, 4, 3, 3, 3, 3])
+    output = ndimage.histogram(input, 0, 4, 5, labels, 1)
+    assert_array_almost_equal(output, expected)
+
+
+@skip_xp_backends(np_only=True, reason='object arrays')
+def test_histogram03(xp):
+    labels = xp.asarray([1, 0, 1, 1, 2, 2, 2, 2])
+    expected1 = xp.asarray([0, 1, 0, 1, 1])
+    expected2 = xp.asarray([0, 0, 0, 3, 0])
+    input = xp.asarray([1, 1, 3, 4, 3, 5, 3, 3])
+
+    output = ndimage.histogram(input, 0, 4, 5, labels, (1, 2))
+
+    assert_array_almost_equal(output[0], expected1)
+    assert_array_almost_equal(output[1], expected2)
+
+
+def test_stat_funcs_2d(xp):
+    a = xp.asarray([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]])
+    lbl = xp.asarray([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]])
+
+    mean = ndimage.mean(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(mean, xp.asarray([7.0, 4.0], dtype=xp.float64))
+
+    var = ndimage.variance(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(var, xp.asarray([2.5, 1.0], dtype=xp.float64))
+
+    std = ndimage.standard_deviation(a, labels=lbl, index=xp.asarray([1, 2]))
+    assert_array_almost_equal(std, xp.sqrt(xp.asarray([2.5, 1.0], dtype=xp.float64)))
+
+    med = ndimage.median(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(med, xp.asarray([7.0, 4.0], dtype=xp.float64))
+
+    min = ndimage.minimum(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(min, xp.asarray([5, 3]), check_dtype=False)
+
+    max = ndimage.maximum(a, labels=lbl, index=xp.asarray([1, 2]))
+    xp_assert_equal(max, xp.asarray([9, 5]), check_dtype=False)
+
+
+@skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+class TestWatershedIft:
+
+    def test_watershed_ift01(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 1, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+        structure=xp.asarray([[1, 1, 1],
+                              [1, 1, 1],
+                              [1, 1, 1]])
+        out = ndimage.watershed_ift(data, markers, structure=structure)
+        expected = [[-1, -1, -1, -1, -1, -1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift02(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 1, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+        out = ndimage.watershed_ift(data, markers)
+        expected = [[-1, -1, -1, -1, -1, -1, -1],
+                    [-1, -1, 1, 1, 1, -1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, -1, 1, 1, 1, -1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift03(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 2, 0, 3, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, -1]], dtype=xp.int8)
+        out = ndimage.watershed_ift(data, markers)
+        expected = [[-1, -1, -1, -1, -1, -1, -1],
+                    [-1, -1, 2, -1, 3, -1, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, -1, 2, -1, 3, -1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift04(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 2, 0, 3, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, -1]],
+                             dtype=xp.int8)
+
+        structure=xp.asarray([[1, 1, 1],
+                              [1, 1, 1],
+                              [1, 1, 1]])
+        out = ndimage.watershed_ift(data, markers, structure=structure)
+        expected = [[-1, -1, -1, -1, -1, -1, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, 2, 2, 3, 3, 3, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift05(self, xp):
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 3, 0, 2, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, -1]],
+                             dtype=xp.int8)
+        structure = xp.asarray([[1, 1, 1],
+                                [1, 1, 1],
+                                [1, 1, 1]])
+        out = ndimage.watershed_ift(data, markers, structure=structure)
+        expected = [[-1, -1, -1, -1, -1, -1, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, 3, 3, 2, 2, 2, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    def test_watershed_ift06(self, xp):
+        data = xp.asarray([[0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 0, 0, 0, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+        markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 1, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+        structure=xp.asarray([[1, 1, 1],
+                              [1, 1, 1],
+                              [1, 1, 1]])
+        out = ndimage.watershed_ift(data, markers, structure=structure)
+        expected = [[-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    @skip_xp_backends(np_only=True, reason="inplace ops are numpy-specific")
+    def test_watershed_ift07(self, xp):
+        shape = (7, 6)
+        data = np.zeros(shape, dtype=np.uint8)
+        data = data.transpose()
+        data[...] = np.asarray([[0, 1, 0, 0, 0, 1, 0],
+                                [0, 1, 0, 0, 0, 1, 0],
+                                [0, 1, 0, 0, 0, 1, 0],
+                                [0, 1, 1, 1, 1, 1, 0],
+                                [0, 0, 0, 0, 0, 0, 0],
+                                [0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
+        data = xp.asarray(data)
+        markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 1, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0],
+                              [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+        out = xp.zeros(shape, dtype=xp.int16)
+        out = out.T
+        structure=xp.asarray([[1, 1, 1],
+                              [1, 1, 1],
+                              [1, 1, 1]])
+        ndimage.watershed_ift(data, markers, structure=structure,
+                              output=out)
+        expected = [[-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, 1, 1, 1, 1, 1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1],
+                    [-1, -1, -1, -1, -1, -1, -1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+    def test_watershed_ift08(self, xp):
+        # Test cost larger than uint8. See gh-10069.
+        data = xp.asarray([[256, 0],
+                           [0, 0]], dtype=xp.uint16)
+        markers = xp.asarray([[1, 0],
+                              [0, 0]], dtype=xp.int8)
+        out = ndimage.watershed_ift(data, markers)
+        expected = [[1, 1],
+                    [1, 1]]
+        assert_array_almost_equal(out, xp.asarray(expected))
+
+    @skip_xp_backends("cupy", reason="no watershed_ift on CuPy"	)
+    def test_watershed_ift09(self, xp):
+        # Test large cost. See gh-19575
+        data = xp.asarray([[xp.iinfo(xp.uint16).max, 0],
+                           [0, 0]], dtype=xp.uint16)
+        markers = xp.asarray([[1, 0],
+                              [0, 0]], dtype=xp.int8)
+        out = ndimage.watershed_ift(data, markers)
+        expected = [[1, 1],
+                    [1, 1]]
+        xp_assert_close(out, xp.asarray(expected), check_dtype=False)
+
+
+@skip_xp_backends(np_only=True)
+@pytest.mark.parametrize("dt", [np.intc, np.uintc])
+def test_gh_19423(dt, xp):
+    rng = np.random.default_rng(123)
+    max_val = 8
+    image = rng.integers(low=0, high=max_val, size=(10, 12)).astype(dtype=dt)
+    val_idx = ndimage.value_indices(image)
+    assert len(val_idx.keys()) == max_val
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..9eff9a2c0f4a05295b7565761292b4ecaac007ac
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_morphology.py
@@ -0,0 +1,2938 @@
+import numpy as np
+from scipy._lib._array_api import (
+    is_cupy, is_numpy, is_torch, array_namespace,
+    xp_assert_close, xp_assert_equal, assert_array_almost_equal
+)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy import ndimage
+
+from . import types
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              pytest.mark.usefixtures("xfail_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+class TestNdimageMorphology:
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        # brute force (bf) distance transform
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(data, 'euclidean',
+                                                return_indices=True)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 2, 4, 2, 1, 0, 0],
+                    [0, 0, 1, 4, 8, 4, 1, 0, 0],
+                    [0, 0, 1, 2, 4, 2, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out * out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 1, 2, 2, 2, 2],
+                     [3, 3, 3, 2, 1, 2, 3, 3, 3],
+                     [4, 4, 4, 4, 6, 4, 4, 4, 4],
+                     [5, 5, 6, 6, 7, 6, 6, 5, 5],
+                     [6, 6, 6, 7, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 1, 2, 4, 6, 7, 7, 8],
+                     [0, 1, 1, 1, 6, 7, 7, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(data, 'cityblock',
+                                                return_indices=True)
+
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 2, 2, 2, 1, 0, 0],
+                    [0, 0, 1, 2, 3, 2, 1, 0, 0],
+                    [0, 0, 1, 2, 2, 2, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 1, 2, 2, 2, 2],
+                     [3, 3, 3, 3, 1, 3, 3, 3, 3],
+                     [4, 4, 4, 4, 7, 4, 4, 4, 4],
+                     [5, 5, 6, 7, 7, 7, 6, 5, 5],
+                     [6, 6, 6, 7, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 1, 1, 4, 7, 7, 7, 8],
+                     [0, 1, 1, 1, 4, 7, 7, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(expected, ft)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(data, 'chessboard',
+                                                return_indices=True)
+
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 1, 2, 1, 1, 0, 0],
+                    [0, 0, 1, 2, 2, 2, 1, 0, 0],
+                    [0, 0, 1, 1, 2, 1, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 1, 2, 2, 2, 2],
+                     [3, 3, 4, 2, 2, 2, 4, 3, 3],
+                     [4, 4, 5, 6, 6, 6, 5, 4, 4],
+                     [5, 5, 6, 6, 7, 6, 6, 5, 5],
+                     [6, 6, 6, 7, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 5, 6, 6, 7, 8],
+                     [0, 1, 1, 2, 6, 6, 7, 7, 8],
+                     [0, 1, 1, 2, 6, 7, 7, 7, 8],
+                     [0, 1, 2, 2, 6, 6, 7, 7, 8],
+                     [0, 1, 2, 4, 5, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace distances= arrays are numpy-specific'
+    )
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf04(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        tdt, tft = ndimage.distance_transform_bf(data, return_indices=1)
+        dts = []
+        fts = []
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ndimage.distance_transform_bf(data, distances=dt)
+        dts.append(dt)
+        ft = ndimage.distance_transform_bf(
+            data, return_distances=False, return_indices=1)
+        fts.append(ft)
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ndimage.distance_transform_bf(
+            data, return_distances=False, return_indices=True, indices=ft)
+        fts.append(ft)
+        dt, ft = ndimage.distance_transform_bf(
+            data, return_indices=1)
+        dts.append(dt)
+        fts.append(ft)
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ft = ndimage.distance_transform_bf(
+            data, distances=dt, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+        ft = np.indices(data.shape, dtype=xp.int32)
+        dt = ndimage.distance_transform_bf(
+            data, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ndimage.distance_transform_bf(
+            data, distances=dt, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+        for dt in dts:
+            assert_array_almost_equal(tdt, dt)
+        for ft in fts:
+            assert_array_almost_equal(tft, ft)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf05(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(
+            data, 'euclidean', return_indices=True, sampling=[2, 2])
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 4, 4, 4, 0, 0, 0],
+                    [0, 0, 4, 8, 16, 8, 4, 0, 0],
+                    [0, 0, 4, 16, 32, 16, 4, 0, 0],
+                    [0, 0, 4, 8, 16, 8, 4, 0, 0],
+                    [0, 0, 0, 4, 4, 4, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out * out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 1, 2, 2, 2, 2],
+                     [3, 3, 3, 2, 1, 2, 3, 3, 3],
+                     [4, 4, 4, 4, 6, 4, 4, 4, 4],
+                     [5, 5, 6, 6, 7, 6, 6, 5, 5],
+                     [6, 6, 6, 7, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 1, 2, 4, 6, 7, 7, 8],
+                     [0, 1, 1, 1, 6, 7, 7, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf.')
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_bf06(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_bf(
+            data, 'euclidean', return_indices=True, sampling=[2, 1])
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 4, 1, 0, 0, 0],
+                    [0, 0, 1, 4, 8, 4, 1, 0, 0],
+                    [0, 0, 1, 4, 9, 4, 1, 0, 0],
+                    [0, 0, 1, 4, 8, 4, 1, 0, 0],
+                    [0, 0, 0, 1, 4, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out * out, expected)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 2, 2, 2, 2, 2, 2],
+                     [3, 3, 3, 3, 2, 3, 3, 3, 3],
+                     [4, 4, 4, 4, 4, 4, 4, 4, 4],
+                     [5, 5, 5, 5, 6, 5, 5, 5, 5],
+                     [6, 6, 6, 6, 7, 6, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 6, 6, 6, 7, 8],
+                     [0, 1, 1, 1, 6, 7, 7, 7, 8],
+                     [0, 1, 1, 1, 7, 7, 7, 7, 8],
+                     [0, 1, 1, 1, 6, 7, 7, 7, 8],
+                     [0, 1, 2, 2, 4, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    def test_distance_transform_bf07(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf.")
+
+        # test input validation per discussion on PR #13302
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+        with assert_raises(RuntimeError):
+            ndimage.distance_transform_bf(
+                data, return_distances=False, return_indices=False
+            )
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_cdt.")
+
+        # chamfer type distance (cdt) transform
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_cdt(
+            data, 'cityblock', return_indices=True)
+        bf = ndimage.distance_transform_bf(data, 'cityblock')
+        assert_array_almost_equal(bf, out)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 1, 1, 1, 2, 2, 2],
+                     [3, 3, 2, 1, 1, 1, 2, 3, 3],
+                     [4, 4, 4, 4, 1, 4, 4, 4, 4],
+                     [5, 5, 5, 5, 7, 7, 6, 5, 5],
+                     [6, 6, 6, 6, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 1, 1, 4, 7, 7, 7, 8],
+                     [0, 1, 1, 1, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_cdt.")
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_cdt(data, 'chessboard',
+                                                 return_indices=True)
+        bf = ndimage.distance_transform_bf(data, 'chessboard')
+        assert_array_almost_equal(bf, out)
+
+        expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                     [1, 1, 1, 1, 1, 1, 1, 1, 1],
+                     [2, 2, 2, 1, 1, 1, 2, 2, 2],
+                     [3, 3, 2, 2, 1, 2, 2, 3, 3],
+                     [4, 4, 3, 2, 2, 2, 3, 4, 4],
+                     [5, 5, 4, 6, 7, 6, 4, 5, 5],
+                     [6, 6, 6, 6, 7, 7, 6, 6, 6],
+                     [7, 7, 7, 7, 7, 7, 7, 7, 7],
+                     [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+                    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 2, 3, 4, 6, 7, 8],
+                     [0, 1, 1, 2, 2, 6, 6, 7, 8],
+                     [0, 1, 1, 1, 2, 6, 7, 7, 8],
+                     [0, 1, 1, 2, 6, 6, 7, 7, 8],
+                     [0, 1, 2, 2, 5, 6, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8],
+                     [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(ft, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace indices= arrays are numpy-specific'
+    )
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        tdt, tft = ndimage.distance_transform_cdt(data, return_indices=True)
+        dts = []
+        fts = []
+        dt = xp.zeros(data.shape, dtype=xp.int32)
+        ndimage.distance_transform_cdt(data, distances=dt)
+        dts.append(dt)
+        ft = ndimage.distance_transform_cdt(
+            data, return_distances=False, return_indices=True)
+        fts.append(ft)
+        ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+        ndimage.distance_transform_cdt(
+            data, return_distances=False, return_indices=True, indices=ft)
+        fts.append(ft)
+        dt, ft = ndimage.distance_transform_cdt(
+            data, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+        dt = xp.zeros(data.shape, dtype=xp.int32)
+        ft = ndimage.distance_transform_cdt(
+            data, distances=dt, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+        ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+        dt = ndimage.distance_transform_cdt(
+            data, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+        dt = xp.zeros(data.shape, dtype=xp.int32)
+        ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+        ndimage.distance_transform_cdt(data, distances=dt,
+                                       return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+        for dt in dts:
+            assert_array_almost_equal(tdt, dt)
+        for ft in fts:
+            assert_array_almost_equal(tft, ft)
+
+    @skip_xp_backends(
+        np_only=True, reason='XXX: does not raise unless indices is a numpy array'
+    )
+    def test_distance_transform_cdt04(self, xp):
+        # test input validation per discussion on PR #13302
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+        indices_out = xp.zeros((data.ndim,) + data.shape, dtype=xp.int32)
+        with assert_raises(RuntimeError):
+            ndimage.distance_transform_bf(
+                data,
+                return_distances=True,
+                return_indices=False,
+                indices=indices_out
+            )
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_cdt05(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_cdt.")
+        elif is_torch(xp):
+            pytest.xfail("int overflow")
+
+        # test custom metric type per discussion on issue #17381
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        metric_arg = xp.ones((3, 3))
+        actual = ndimage.distance_transform_cdt(data, metric=metric_arg)
+        assert xp.sum(actual) == -21
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf")
+
+        # euclidean distance transform (edt)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out, ft = ndimage.distance_transform_edt(data, return_indices=True)
+        bf = ndimage.distance_transform_bf(data, 'euclidean')
+        assert_array_almost_equal(bf, out)
+
+        # np-specific check
+        np_ft = np.asarray(ft)
+        dt = np_ft - np.indices(np_ft.shape[1:], dtype=np_ft.dtype)
+        dt = dt.astype(np.float64)
+        np.multiply(dt, dt, dt)
+        dt = np.add.reduce(dt, axis=0)
+        np.sqrt(dt, dt)
+
+        dt = xp.asarray(dt)
+        assert_array_almost_equal(bf, dt)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace distances= are numpy-specific'
+    )
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        tdt, tft = ndimage.distance_transform_edt(data, return_indices=True)
+        dts = []
+        fts = []
+
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ndimage.distance_transform_edt(data, distances=dt)
+        dts.append(dt)
+
+        ft = ndimage.distance_transform_edt(
+            data, return_distances=0, return_indices=True)
+        fts.append(ft)
+
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ft = xp.asarray(ft)
+        ndimage.distance_transform_edt(
+            data, return_distances=False, return_indices=True, indices=ft)
+        fts.append(ft)
+
+        dt, ft = ndimage.distance_transform_edt(
+            data, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ft = ndimage.distance_transform_edt(
+            data, distances=dt, return_indices=True)
+        dts.append(dt)
+        fts.append(ft)
+
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ft = xp.asarray(ft)
+        dt = ndimage.distance_transform_edt(
+            data, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+
+        dt = xp.zeros(data.shape, dtype=xp.float64)
+        ft = np.indices(data.shape, dtype=xp.int32)
+        ft = xp.asarray(ft)
+        ndimage.distance_transform_edt(
+            data, distances=dt, return_indices=True, indices=ft)
+        dts.append(dt)
+        fts.append(ft)
+
+        for dt in dts:
+            assert_array_almost_equal(tdt, dt)
+        for ft in fts:
+            assert_array_almost_equal(tft, ft)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf")
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 2])
+        out = ndimage.distance_transform_edt(data, sampling=[2, 2])
+        assert_array_almost_equal(ref, out)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_distance_transform_edt4(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        if is_cupy(xp):
+            pytest.xfail("CuPy does not have distance_transform_bf")
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 1])
+        out = ndimage.distance_transform_edt(data, sampling=[2, 1])
+        assert_array_almost_equal(ref, out)
+
+    def test_distance_transform_edt5(self, xp):
+        # Ticket #954 regression test
+        out = ndimage.distance_transform_edt(False)
+        assert_array_almost_equal(out, [0.])
+
+    @skip_xp_backends(
+        np_only=True, reason='XXX: does not raise unless indices is a numpy array'
+    )
+    def test_distance_transform_edt6(self, xp):
+        # test input validation per discussion on PR #13302
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+        distances_out = xp.zeros(data.shape, dtype=xp.float64)
+        with assert_raises(RuntimeError):
+            ndimage.distance_transform_bf(
+                data,
+                return_indices=True,
+                return_distances=False,
+                distances=distances_out
+            )
+
+    def test_generate_structure01(self, xp):
+        struct = ndimage.generate_binary_structure(0, 1)
+        assert struct == 1
+
+    def test_generate_structure02(self, xp):
+        struct = ndimage.generate_binary_structure(1, 1)
+        assert_array_almost_equal(struct, [1, 1, 1])
+
+    def test_generate_structure03(self, xp):
+        struct = ndimage.generate_binary_structure(2, 1)
+        assert_array_almost_equal(struct, [[0, 1, 0],
+                                           [1, 1, 1],
+                                           [0, 1, 0]])
+
+    def test_generate_structure04(self, xp):
+        struct = ndimage.generate_binary_structure(2, 2)
+        assert_array_almost_equal(struct, [[1, 1, 1],
+                                           [1, 1, 1],
+                                           [1, 1, 1]])
+
+    def test_iterate_structure01(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        out = ndimage.iterate_structure(struct, 2)
+        expected = np.asarray([[0, 0, 1, 0, 0],
+                               [0, 1, 1, 1, 0],
+                               [1, 1, 1, 1, 1],
+                               [0, 1, 1, 1, 0],
+                               [0, 0, 1, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out, expected)
+
+    def test_iterate_structure02(self, xp):
+        struct = [[0, 1],
+                  [1, 1],
+                  [0, 1]]
+        struct = xp.asarray(struct)
+        out = ndimage.iterate_structure(struct, 2)
+        expected = np.asarray([[0, 0, 1],
+                               [0, 1, 1],
+                               [1, 1, 1],
+                               [0, 1, 1],
+                               [0, 0, 1]], dtype=bool)
+        expected = xp.asarray(expected)
+
+        assert_array_almost_equal(out, expected)
+
+    def test_iterate_structure03(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        out = ndimage.iterate_structure(struct, 2, 1)
+        expected = [[0, 0, 1, 0, 0],
+                    [0, 1, 1, 1, 0],
+                    [1, 1, 1, 1, 1],
+                    [0, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        assert_array_almost_equal(out[0], expected)
+        assert out[1] == [2, 2]
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion04(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion05(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion06(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion07(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([5], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion08(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([5], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion09(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([0, 0, 0, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion10(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 0, 0, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion11(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion12(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion13(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1, origin=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion14(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion15(self, dtype, xp):
+        data = np.ones([5], dtype=dtype)
+        data[2] = 0
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 1])
+        out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 0, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion16(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 1], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([[1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion17(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 1], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([[0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion18(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 3], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion19(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 3], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion20(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3, 3], dtype=dtype)
+        out = ndimage.binary_erosion(data)
+        assert_array_almost_equal(out, xp.asarray([[0, 0, 0],
+                                                   [0, 1, 0],
+                                                   [0, 0, 0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion21(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3, 3], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+                                                   [1, 1, 1],
+                                                   [1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion22(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion23(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = ndimage.generate_binary_structure(2, 2)
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion24(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = xp.asarray([[0, 1],
+                             [1, 1]])
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 1, 1, 1],
+                    [0, 0, 0, 1, 1, 1, 0, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 1, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion25(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1, 0],
+                  [1, 0, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 0, 1, 1],
+                           [0, 0, 1, 0, 1, 1, 0, 0],
+                           [0, 1, 0, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, struct, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_erosion26(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1, 0],
+                  [1, 0, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 1],
+                    [0, 0, 0, 0, 1, 0, 0, 1],
+                    [0, 0, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 1]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 1, 1],
+                           [0, 0, 1, 1, 1, 0, 1, 1],
+                           [0, 0, 1, 0, 1, 1, 0, 0],
+                           [0, 1, 0, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 0, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_erosion(data, struct, border_value=1,
+                                     origin=(-1, -1))
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion27(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct, border_value=1,
+                                     iterations=2)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion28(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=2, output=out)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion29(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct,
+                                     border_value=1, iterations=3)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion30(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=3, output=out)
+        assert_array_almost_equal(out, expected)
+
+        # test with output memory overlap
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=3, output=data)
+        assert_array_almost_equal(data, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion31(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 1, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 0, 0],
+                    [1, 1, 1, 1, 1, 0, 1],
+                    [0, 1, 1, 1, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 1]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=1, output=out, origin=(-1, -1))
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion32(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct,
+                                     border_value=1, iterations=2)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion33(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 1, 1],
+                    [0, 0, 0, 0, 0, 0, 1],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        mask = [[1, 1, 1, 1, 1, 0, 0],
+                [1, 1, 1, 1, 1, 1, 0],
+                [1, 1, 1, 1, 1, 1, 1],
+                [1, 1, 1, 1, 1, 1, 1],
+                [1, 1, 1, 1, 1, 1, 1],
+                [1, 1, 1, 1, 1, 1, 1],
+                [1, 1, 1, 1, 1, 1, 1]]
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 0, 0, 0, 0, 1, 1],
+                           [0, 0, 0, 1, 0, 0, 1],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct,
+                                     border_value=1, mask=mask, iterations=-1)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion34(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        mask = [[0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0],
+                [0, 0, 1, 0, 1, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0]]
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_erosion(data, struct,
+                                     border_value=1, mask=mask)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion35(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        mask = [[0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0],
+                [0, 0, 1, 0, 1, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0]]
+        mask = np.asarray(mask, dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        tmp = [[0, 0, 1, 0, 0, 0, 0],
+               [0, 1, 1, 1, 0, 0, 0],
+               [1, 1, 1, 1, 1, 0, 1],
+               [0, 1, 1, 1, 0, 0, 0],
+               [0, 0, 1, 0, 0, 0, 0],
+               [0, 0, 0, 0, 0, 0, 0],
+               [0, 0, 1, 0, 0, 0, 1]]
+        tmp = np.asarray(tmp, dtype=bool)
+        tmp = xp.asarray(tmp)
+        expected = xp.logical_and(tmp, mask)
+        tmp = xp.logical_and(data, xp.logical_not(mask))
+        expected = xp.logical_or(expected, tmp)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=1, output=out,
+                               origin=(-1, -1), mask=mask)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_erosion36(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 0, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        mask = [[0, 0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0, 0],
+                [0, 0, 1, 0, 1, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0, 0],
+                [0, 0, 1, 1, 1, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0]]
+        mask = np.asarray(mask, dtype=bool)
+        mask = xp.asarray(mask)
+        tmp = [[0, 0, 0, 0, 0, 0, 0, 0],
+               [0, 0, 0, 0, 0, 0, 0, 1],
+               [0, 0, 0, 0, 1, 0, 0, 1],
+               [0, 0, 1, 0, 0, 0, 0, 0],
+               [0, 1, 0, 0, 1, 0, 0, 0],
+               [0, 0, 0, 0, 0, 0, 0, 0],
+               [0, 0, 0, 0, 0, 0, 0, 0],
+               [0, 0, 0, 0, 0, 0, 0, 1]]
+        tmp = np.asarray(tmp, dtype=bool)
+        tmp = xp.asarray(tmp)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                            [0, 1, 0, 0, 0, 0, 0, 0],
+                            [0, 0, 0, 0, 0, 1, 1, 1],
+                            [0, 0, 1, 1, 1, 0, 1, 1],
+                            [0, 0, 1, 0, 1, 1, 0, 0],
+                            [0, 1, 0, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 0, 0, 1, 1, 0],
+                            [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        expected = xp.logical_and(tmp, mask)
+        tmp = xp.logical_and(data, xp.logical_not(mask))
+        expected = xp.logical_or(expected, tmp)
+        out = ndimage.binary_erosion(data, struct, mask=mask,
+                                     border_value=1, origin=(-1, -1))
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion37(self, xp):
+        a = np.asarray([[1, 0, 1],
+                        [0, 1, 0],
+                        [1, 0, 1]], dtype=bool)
+        a = xp.asarray(a)
+        b = xp.zeros_like(a)
+        out = ndimage.binary_erosion(a, structure=a, output=b, iterations=0,
+                                     border_value=True, brute_force=True)
+        assert out is b
+        xp_assert_equal(
+            ndimage.binary_erosion(a, structure=a, iterations=0,
+                                   border_value=True),
+            b)
+
+    def test_binary_erosion38(self, xp):
+        data = np.asarray([[1, 0, 1],
+                           [0, 1, 0],
+                           [1, 0, 1]], dtype=bool)
+        data = xp.asarray(data)
+        iterations = 2.0
+        with assert_raises(TypeError):
+            _ = ndimage.binary_erosion(data, iterations=iterations)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion39(self, xp):
+        iterations = np.int32(3)
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=iterations, output=out)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace out= arguments are numpy-specific'
+    )
+    def test_binary_erosion40(self, xp):
+        iterations = np.int64(3)
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0]]
+        expected = np.asarray(expected, dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [1, 1, 1, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_erosion(data, struct, border_value=1,
+                               iterations=iterations, output=out)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert out == xp.asarray(1, dtype=out.dtype)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.zeros([], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert out == xp.asarray(False)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation04(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.zeros([1], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation05(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation06(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.zeros([3], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([0, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation07(self, dtype, xp):
+        data = np.zeros([3], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation08(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data[3] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation09(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation10(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, origin=-1)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation11(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, origin=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation12(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_dilation(data, struct)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation13(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_dilation(data, struct, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation14(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_dilation(data, struct, origin=-1)
+        assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation15(self, dtype, xp):
+        data = np.zeros([5], dtype=dtype)
+        data[1] = 1
+        data = xp.asarray(data)
+        struct = xp.asarray([1, 0, 1])
+        out = ndimage.binary_dilation(data, struct,
+                                      origin=-1, border_value=1)
+        assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation16(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 1], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation17(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.zeros([1, 1], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation18(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([1, 3], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation19(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        data = xp.ones([3, 3], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+                                                   [1, 1, 1],
+                                                   [1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation20(self, dtype, xp):
+        data = np.zeros([3, 3], dtype=dtype)
+        data[1, 1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, xp.asarray([[0, 1, 0],
+                                                   [1, 1, 1],
+                                                   [0, 1, 0]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation21(self, dtype, xp):
+        struct = ndimage.generate_binary_structure(2, 2)
+        struct = xp.asarray(struct)
+        data = np.zeros([3, 3], dtype=dtype)
+        data[1, 1] = 1
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, struct)
+        assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+                                                   [1, 1, 1],
+                                                   [1, 1, 1]]))
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation22(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 0, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation23(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[1, 1, 1, 1, 1, 1, 1, 1],
+                    [1, 1, 1, 0, 0, 0, 0, 1],
+                    [1, 1, 0, 0, 0, 1, 0, 1],
+                    [1, 0, 0, 1, 1, 1, 1, 1],
+                    [1, 0, 1, 1, 1, 1, 0, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1],
+                    [1, 0, 1, 0, 0, 1, 0, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation24(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[1, 1, 0, 0, 0, 0, 0, 0],
+                    [1, 0, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 1, 1, 1, 0, 0, 0],
+                    [1, 1, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 0, 0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, origin=(1, 1))
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation25(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[1, 1, 0, 0, 0, 0, 1, 1],
+                    [1, 0, 0, 0, 1, 0, 1, 1],
+                    [0, 0, 1, 1, 1, 1, 1, 1],
+                    [0, 1, 1, 1, 1, 0, 1, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1],
+                    [0, 1, 0, 0, 1, 0, 1, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1],
+                    [1, 1, 1, 1, 1, 1, 1, 1]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, origin=(1, 1), border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation26(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = ndimage.generate_binary_structure(2, 2)
+        expected = [[1, 1, 1, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 1, 1, 1, 0],
+                    [0, 0, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, struct)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation27(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [1, 1, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 1, 1, 1, 0, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 1, 0, 1, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, struct)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation28(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[1, 1, 1, 1],
+                    [1, 0, 0, 1],
+                    [1, 0, 0, 1],
+                    [1, 1, 1, 1]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0],
+                           [0, 0, 0, 0],
+                           [0, 0, 0, 0],
+                           [0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_dilation29(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0],
+                    [0, 0, 1, 1, 0],
+                    [0, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, struct, iterations=2)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    def test_binary_dilation30(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 0, 0, 0, 0],
+                    [0, 0, 0, 1, 0],
+                    [0, 0, 1, 1, 0],
+                    [0, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_dilation(data, struct, iterations=2, output=out)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_dilation31(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 0, 0, 1, 0],
+                    [0, 0, 1, 1, 0],
+                    [0, 1, 1, 1, 0],
+                    [1, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, struct, iterations=3)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    def test_binary_dilation32(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1],
+                  [1, 1]]
+        expected = [[0, 0, 0, 1, 0],
+                    [0, 0, 1, 1, 0],
+                    [0, 1, 1, 1, 0],
+                    [1, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = np.zeros(data.shape, dtype=bool)
+        out = xp.asarray(out)
+        ndimage.binary_dilation(data, struct, iterations=3, output=out)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_dilation33(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 0, 0, 0],
+                               [0, 1, 1, 0, 1, 1, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 1, 1, 0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+
+        out = ndimage.binary_dilation(data, struct, iterations=-1,
+                                      mask=mask, border_value=0)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(
+        np_only=True, reason='inplace output= arrays are numpy-specific',
+    )
+    def test_binary_dilation34(self, xp):
+        if is_cupy(xp):
+            pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.zeros(mask.shape, dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, struct, iterations=-1,
+                                      mask=mask, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_dilation35(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        tmp = [[1, 1, 0, 0, 0, 0, 1, 1],
+               [1, 0, 0, 0, 1, 0, 1, 1],
+               [0, 0, 1, 1, 1, 1, 1, 1],
+               [0, 1, 1, 1, 1, 0, 1, 1],
+               [1, 1, 1, 1, 1, 1, 1, 1],
+               [0, 1, 0, 0, 1, 0, 1, 1],
+               [1, 1, 1, 1, 1, 1, 1, 1],
+               [1, 1, 1, 1, 1, 1, 1, 1]]
+
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]])
+        mask = [[0, 0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 1, 1, 1, 1, 0, 0],
+                [0, 0, 1, 1, 1, 1, 0, 0],
+                [0, 0, 1, 1, 1, 1, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0, 0, 0]]
+        mask = np.asarray(mask, dtype=bool)
+
+        expected = np.logical_and(tmp, mask)
+        tmp = np.logical_and(data, np.logical_not(mask))
+        expected = np.logical_or(expected, tmp)
+
+        mask = xp.asarray(mask)
+        expected = xp.asarray(expected)
+
+        data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_dilation(data, mask=mask,
+                                      origin=(1, 1), border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_dilation36(self, xp):
+        # gh-21009
+        data = np.zeros([], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_dilation(data, iterations=-1)
+        assert out == xp.asarray(False)
+
+    def test_binary_propagation01(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 0, 0, 0],
+                               [0, 1, 1, 0, 1, 1, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 1, 0],
+                           [0, 0, 0, 0, 1, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 0, 0, 0],
+                           [0, 1, 1, 0, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_propagation(data, struct,
+                                         mask=mask, border_value=0)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_propagation02(self, xp):
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        struct = xp.asarray(struct)
+        mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [0, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        mask = xp.asarray(mask)
+        data = np.zeros(mask.shape, dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_propagation(data, struct,
+                                         mask=mask, border_value=1)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_propagation03(self, xp):
+        # gh-21009
+        data = xp.asarray(np.zeros([], dtype=bool))
+        expected = xp.asarray(np.zeros([], dtype=bool))
+        out = ndimage.binary_propagation(data)
+        assert out == expected
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_opening01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 0, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 0, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_opening(data)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_opening02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = ndimage.generate_binary_structure(2, 2)
+        expected = [[1, 1, 1, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [1, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        struct = xp.asarray(struct)
+        data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 0, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_opening(data, struct)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_closing01(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 0, 1, 0, 0],
+                    [0, 0, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 1, 1, 1, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 1, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 0, 1, 0, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_closing(data)
+        assert_array_almost_equal(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_binary_closing02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = ndimage.generate_binary_structure(2, 2)
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 0, 0, 0, 0, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 1, 1, 1, 1, 1, 1, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        struct = xp.asarray(struct)
+        data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [1, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 0, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_closing(data, struct)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_fill_holes01(self, xp):
+        expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 1, 1, 1, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+
+        out = ndimage.binary_fill_holes(data)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_fill_holes02(self, xp):
+        expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 0, 1, 1, 0, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 1, 1, 1, 1, 0, 0],
+                               [0, 0, 0, 1, 1, 0, 0, 0],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 1, 0, 0, 1, 0, 0],
+                           [0, 0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_fill_holes(data)
+        assert_array_almost_equal(out, expected)
+
+    def test_binary_fill_holes03(self, xp):
+        expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                               [0, 0, 1, 0, 0, 0, 0, 0],
+                               [0, 1, 1, 1, 0, 1, 1, 1],
+                               [0, 1, 1, 1, 0, 1, 1, 1],
+                               [0, 1, 1, 1, 0, 1, 1, 1],
+                               [0, 0, 1, 0, 0, 1, 1, 1],
+                               [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+        data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+                           [0, 0, 1, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 1, 0, 1, 1, 1],
+                           [0, 1, 0, 1, 0, 1, 0, 1],
+                           [0, 1, 0, 1, 0, 1, 0, 1],
+                           [0, 0, 1, 0, 0, 1, 1, 1],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+        data = xp.asarray(data)
+        out = ndimage.binary_fill_holes(data)
+        assert_array_almost_equal(out, expected)
+
+    @skip_xp_backends(cpu_only=True)
+    @skip_xp_backends(
+        "cupy", reason="these filters do not yet have axes support in CuPy")
+    @skip_xp_backends(
+        "jax.numpy", reason="these filters are not implemented in JAX.numpy")
+    @pytest.mark.parametrize('border_value',[0, 1])
+    @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)])
+    @pytest.mark.parametrize('expand_axis', [0, 1, 2])
+    @pytest.mark.parametrize('func_name', ["binary_erosion",
+                                           "binary_dilation",
+                                           "binary_opening",
+                                           "binary_closing",
+                                           "binary_hit_or_miss",
+                                           "binary_propagation",
+                                           "binary_fill_holes"])
+    def test_binary_axes(self, xp, func_name, expand_axis, origin, border_value):
+        struct = np.asarray([[0, 1, 0],
+                             [1, 1, 1],
+                             [0, 1, 0]], bool)
+        struct = xp.asarray(struct)
+
+        data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 1, 1, 0, 1, 0],
+                           [0, 1, 0, 1, 1, 0, 1],
+                           [0, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 0, 0, 0],
+                           [0, 0, 0, 1, 0, 0, 0]], bool)
+        data = xp.asarray(data)
+        if func_name == "binary_hit_or_miss":
+            kwargs = dict(origin1=origin, origin2=origin)
+        else:
+            kwargs = dict(origin=origin)
+        border_supported = func_name not in ["binary_hit_or_miss",
+                                             "binary_fill_holes"]
+        if border_supported:
+            kwargs['border_value'] = border_value
+        elif border_value != 0:
+            pytest.skip('border_value !=0 unsupported by this function')
+        func = getattr(ndimage, func_name)
+        expected = func(data, struct, **kwargs)
+
+        # replicate data and expected result along a new axis
+        n_reps = 5
+        expected = xp.stack([expected] * n_reps, axis=expand_axis)
+        data = xp.stack([data] * n_reps, axis=expand_axis)
+
+        # filter all axes except expand_axis
+        axes = [0, 1, 2]
+        axes.remove(expand_axis)
+        if is_numpy(xp) or is_cupy(xp):
+            out = xp.asarray(np.zeros(data.shape, bool))
+            func(data, struct, output=out, axes=axes, **kwargs)
+        else:
+            # inplace output= is unsupported by JAX
+            out = func(data, struct, axes=axes, **kwargs)
+        xp_assert_close(out, expected)
+
+    def test_grey_erosion01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        output = ndimage.grey_erosion(array, footprint=footprint)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1]]))
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8398")
+    def test_grey_erosion01_overlap(self, xp):
+
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        ndimage.grey_erosion(array, footprint=footprint, output=array)
+        assert_array_almost_equal(array,
+                                  xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1]])
+        )
+
+    def test_grey_erosion02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        output = ndimage.grey_erosion(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[2, 2, 1, 1, 1],
+                                              [2, 3, 1, 3, 1],
+                                              [5, 5, 3, 3, 1]])
+        )
+
+    def test_grey_erosion03(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[1, 1, 1], [1, 1, 1]])
+        output = ndimage.grey_erosion(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[1, 1, 0, 0, 0],
+                                              [1, 2, 0, 2, 0],
+                                              [4, 4, 2, 2, 0]])
+        )
+
+    def test_grey_dilation01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+        output = ndimage.grey_dilation(array, footprint=footprint)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[7, 7, 9, 9, 5],
+                                              [7, 9, 8, 9, 7],
+                                              [8, 8, 8, 7, 7]]),
+        )
+
+    def test_grey_dilation02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        output = ndimage.grey_dilation(array, footprint=footprint,
+                                       structure=structure)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[7, 7, 9, 9, 5],
+                                              [7, 9, 8, 9, 7],
+                                              [8, 8, 8, 7, 7]]),
+        )
+
+    def test_grey_dilation03(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+        structure = xp.asarray([[1, 1, 1], [1, 1, 1]])
+        output = ndimage.grey_dilation(array, footprint=footprint,
+                                       structure=structure)
+        assert_array_almost_equal(output,
+                                  xp.asarray([[8, 8, 10, 10, 6],
+                                              [8, 10, 9, 10, 8],
+                                              [9, 9, 9, 8, 8]]),
+        )
+
+    def test_grey_opening01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        tmp = ndimage.grey_erosion(array, footprint=footprint)
+        expected = ndimage.grey_dilation(tmp, footprint=footprint)
+        output = ndimage.grey_opening(array, footprint=footprint)
+        assert_array_almost_equal(output, expected)
+
+    def test_grey_opening02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_erosion(array, footprint=footprint,
+                                   structure=structure)
+        expected = ndimage.grey_dilation(tmp, footprint=footprint,
+                                         structure=structure)
+        output = ndimage.grey_opening(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(output, expected)
+
+    def test_grey_closing01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        tmp = ndimage.grey_dilation(array, footprint=footprint)
+        expected = ndimage.grey_erosion(tmp, footprint=footprint)
+        output = ndimage.grey_closing(array, footprint=footprint)
+        assert_array_almost_equal(expected, output)
+
+    def test_grey_closing02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_dilation(array, footprint=footprint,
+                                    structure=structure)
+        expected = ndimage.grey_erosion(tmp, footprint=footprint,
+                                        structure=structure)
+        output = ndimage.grey_closing(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    def test_morphological_gradient01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+                                     structure=structure)
+        tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+                                    structure=structure)
+        expected = tmp1 - tmp2
+        output = xp.zeros(array.shape, dtype=array.dtype)
+        ndimage.morphological_gradient(array, footprint=footprint,
+                                       structure=structure, output=output)
+        assert_array_almost_equal(expected, output)
+
+    def test_morphological_gradient02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+                                     structure=structure)
+        tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+                                    structure=structure)
+        expected = tmp1 - tmp2
+        output = ndimage.morphological_gradient(array, footprint=footprint,
+                                                structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+    def test_morphological_laplace01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+                                     structure=structure)
+        tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+                                    structure=structure)
+        expected = tmp1 + tmp2 - 2 * array
+        output = xp.zeros(array.shape, dtype=array.dtype)
+        ndimage.morphological_laplace(array, footprint=footprint,
+                                      structure=structure, output=output)
+        assert_array_almost_equal(expected, output)
+
+    def test_morphological_laplace02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+                                     structure=structure)
+        tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+                                    structure=structure)
+        expected = tmp1 + tmp2 - 2 * array
+        output = ndimage.morphological_laplace(array, footprint=footprint,
+                                               structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_white_tophat01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_opening(array, footprint=footprint,
+                                   structure=structure)
+        expected = array - tmp
+        output = xp.zeros(array.shape, dtype=array.dtype)
+        ndimage.white_tophat(array, footprint=footprint,
+                             structure=structure, output=output)
+        assert_array_almost_equal(expected, output)
+
+    def test_white_tophat02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_opening(array, footprint=footprint,
+                                   structure=structure)
+        expected = array - tmp
+        output = ndimage.white_tophat(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @xfail_xp_backends('cupy', reason="cupy#8399")
+    def test_white_tophat03(self, xp):
+
+        array = np.asarray([[1, 0, 0, 0, 0, 0, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 0, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 0, 0, 0, 0, 0, 1]], dtype=bool)
+        array = xp.asarray(array)
+        structure = np.ones((3, 3), dtype=bool)
+        structure = xp.asarray(structure)
+        expected = np.asarray([[0, 1, 1, 0, 0, 0, 0],
+                               [1, 0, 0, 1, 1, 1, 0],
+                               [1, 0, 0, 1, 1, 1, 0],
+                               [0, 1, 1, 0, 0, 0, 1],
+                               [0, 1, 1, 0, 1, 0, 1],
+                               [0, 1, 1, 0, 0, 0, 1],
+                               [0, 0, 0, 1, 1, 1, 1]], dtype=bool)
+        expected = xp.asarray(expected)
+
+        output = ndimage.white_tophat(array, structure=structure)
+        xp_assert_equal(expected, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_white_tophat04(self, xp):
+        array = np.eye(5, dtype=bool)
+        structure = np.ones((3, 3), dtype=bool)
+
+        array = xp.asarray(array)
+        structure = xp.asarray(structure)
+
+        # Check that type mismatch is properly handled
+        output = xp.empty_like(array, dtype=xp.float64)
+        ndimage.white_tophat(array, structure=structure, output=output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_black_tophat01(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_closing(array, footprint=footprint,
+                                   structure=structure)
+        expected = tmp - array
+        output = xp.zeros(array.shape, dtype=array.dtype)
+        ndimage.black_tophat(array, footprint=footprint,
+                             structure=structure, output=output)
+        assert_array_almost_equal(expected, output)
+
+    def test_black_tophat02(self, xp):
+        array = xp.asarray([[3, 2, 5, 1, 4],
+                            [7, 6, 9, 3, 5],
+                            [5, 8, 3, 7, 1]])
+        footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+        tmp = ndimage.grey_closing(array, footprint=footprint,
+                                   structure=structure)
+        expected = tmp - array
+        output = ndimage.black_tophat(array, footprint=footprint,
+                                      structure=structure)
+        assert_array_almost_equal(expected, output)
+
+    @xfail_xp_backends('cupy', reason="cupy/cupy#8399")
+    def test_black_tophat03(self, xp):
+
+        array = np.asarray([[1, 0, 0, 0, 0, 0, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 1, 1, 1, 0, 1, 0],
+                            [0, 1, 1, 1, 1, 1, 0],
+                            [0, 0, 0, 0, 0, 0, 1]], dtype=bool)
+        array = xp.asarray(array)
+        structure = np.ones((3, 3), dtype=bool)
+        structure = xp.asarray(structure)
+        expected = np.asarray([[0, 1, 1, 1, 1, 1, 1],
+                               [1, 0, 0, 0, 0, 0, 1],
+                               [1, 0, 0, 0, 0, 0, 1],
+                               [1, 0, 0, 0, 0, 0, 1],
+                               [1, 0, 0, 0, 1, 0, 1],
+                               [1, 0, 0, 0, 0, 0, 1],
+                               [1, 1, 1, 1, 1, 1, 0]], dtype=bool)
+        expected = xp.asarray(expected)
+
+        output = ndimage.black_tophat(array, structure=structure)
+        xp_assert_equal(expected, output)
+
+    @skip_xp_backends("jax.numpy", reason="output array is read-only.")
+    def test_black_tophat04(self, xp):
+        array = xp.asarray(np.eye(5, dtype=bool))
+        structure = xp.asarray(np.ones((3, 3), dtype=bool))
+
+        # Check that type mismatch is properly handled
+        output = xp.empty_like(array, dtype=xp.float64)
+        ndimage.black_tophat(array, structure=structure, output=output)
+
+    @skip_xp_backends(cpu_only=True)
+    @skip_xp_backends(
+        "cupy", reason="these filters do not yet have axes support in CuPy")
+    @skip_xp_backends(
+        "jax.numpy", reason="these filters are not implemented in JAX.numpy")
+    @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)])
+    @pytest.mark.parametrize('expand_axis', [0, 1, 2])
+    @pytest.mark.parametrize('mode', ['reflect', 'constant', 'nearest',
+                                      'mirror', 'wrap'])
+    @pytest.mark.parametrize('footprint_mode', ['size', 'footprint',
+                                                'structure'])
+    @pytest.mark.parametrize('func_name', ["grey_erosion",
+                                           "grey_dilation",
+                                           "grey_opening",
+                                           "grey_closing",
+                                           "morphological_laplace",
+                                           "morphological_gradient",
+                                           "white_tophat",
+                                           "black_tophat"])
+    def test_grey_axes(self, xp, func_name, expand_axis, origin, footprint_mode,
+                       mode):
+
+        data = xp.asarray([[0, 0, 0, 1, 0, 0, 0],
+                           [0, 0, 0, 4, 0, 0, 0],
+                           [0, 0, 2, 1, 0, 2, 0],
+                           [0, 3, 0, 6, 5, 0, 1],
+                           [0, 4, 5, 3, 3, 4, 0],
+                           [0, 0, 9, 3, 0, 0, 0],
+                           [0, 0, 0, 2, 0, 0, 0]])
+        kwargs = dict(origin=origin, mode=mode)
+        if footprint_mode == 'size':
+            kwargs['size'] = (2, 3)
+        else:
+            kwargs['footprint'] = xp.asarray([[1, 0, 1], [1, 1, 0]])
+        if footprint_mode == 'structure':
+            kwargs['structure'] = xp.ones_like(kwargs['footprint'])
+        func = getattr(ndimage, func_name)
+        expected = func(data, **kwargs)
+
+        # replicate data and expected result along a new axis
+        n_reps = 5
+        expected = xp.stack([expected] * n_reps, axis=expand_axis)
+        data = xp.stack([data] * n_reps, axis=expand_axis)
+
+        # filter all axes except expand_axis
+        axes = [0, 1, 2]
+        axes.remove(expand_axis)
+
+        if is_numpy(xp) or is_cupy(xp):
+            out = xp.zeros(expected.shape, dtype=expected.dtype)
+            func(data, output=out, axes=axes, **kwargs)
+        else:
+            # inplace output= is unsupported by JAX
+            out = func(data, axes=axes, **kwargs)
+        xp_assert_close(out, expected)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_hit_or_miss01(self, dtype, xp):
+        if not (is_numpy(xp) or is_cupy(xp)):
+            pytest.xfail("inplace output= is numpy-specific")
+
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        struct = xp.asarray(struct)
+        expected = [[0, 0, 0, 0, 0],
+                    [0, 1, 0, 0, 0],
+                    [0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0]]
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 0],
+                           [1, 1, 1, 0, 0],
+                           [0, 1, 0, 1, 1],
+                           [0, 0, 1, 1, 1],
+                           [0, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 1],
+                           [0, 1, 1, 1, 1],
+                           [0, 0, 0, 0, 0]], dtype=dtype)
+        out = xp.asarray(np.zeros(data.shape, dtype=bool))
+        ndimage.binary_hit_or_miss(data, struct, output=out)
+        assert_array_almost_equal(expected, out)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_hit_or_miss02(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct = [[0, 1, 0],
+                  [1, 1, 1],
+                  [0, 1, 0]]
+        expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 1, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        struct = xp.asarray(struct)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0],
+                           [1, 1, 1, 0, 0, 1, 0, 0],
+                           [0, 1, 0, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_hit_or_miss(data, struct)
+        assert_array_almost_equal(expected, out)
+
+    @pytest.mark.parametrize('dtype', types)
+    def test_hit_or_miss03(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        struct1 = [[0, 0, 0],
+                   [1, 1, 1],
+                   [0, 0, 0]]
+        struct2 = [[1, 1, 1],
+                   [0, 0, 0],
+                   [1, 1, 1]]
+        expected = [[0, 0, 0, 0, 0, 1, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0],
+                    [0, 0, 1, 0, 0, 0, 0, 0],
+                    [0, 0, 0, 0, 0, 0, 0, 0]]
+        struct1 = xp.asarray(struct1)
+        struct2 = xp.asarray(struct2)
+        expected = xp.asarray(expected)
+        data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0],
+                           [1, 1, 1, 0, 0, 0, 0, 0],
+                           [0, 1, 0, 1, 1, 1, 1, 0],
+                           [0, 0, 1, 1, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 0, 1, 1, 0],
+                           [0, 0, 0, 0, 1, 1, 1, 0],
+                           [0, 1, 1, 1, 1, 1, 1, 0],
+                           [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+        out = ndimage.binary_hit_or_miss(data, struct1, struct2)
+        assert_array_almost_equal(expected, out)
+
+
+class TestDilateFix:
+
+    # pytest's setup_method seems to clash with the autouse `xp` fixture
+    # so call _setup manually from all methods
+    def _setup(self, xp):
+        # dilation related setup
+        self.array = xp.asarray([[0, 0, 0, 0, 0],
+                                 [0, 0, 0, 0, 0],
+                                 [0, 0, 0, 1, 0],
+                                 [0, 0, 1, 1, 0],
+                                 [0, 0, 0, 0, 0]], dtype=xp.uint8)
+
+        self.sq3x3 = xp.ones((3, 3))
+        dilated3x3 = ndimage.binary_dilation(self.array, structure=self.sq3x3)
+
+        if is_numpy(xp):
+            self.dilated3x3 = dilated3x3.view(xp.uint8)
+        else:
+            astype = array_namespace(dilated3x3).astype
+            self.dilated3x3 = astype(dilated3x3, xp.uint8)
+
+
+    def test_dilation_square_structure(self, xp):
+        self._setup(xp)
+        result = ndimage.grey_dilation(self.array, structure=self.sq3x3)
+        # +1 accounts for difference between grey and binary dilation
+        assert_array_almost_equal(result, self.dilated3x3 + 1)
+
+    def test_dilation_scalar_size(self, xp):
+        self._setup(xp)
+        result = ndimage.grey_dilation(self.array, size=3)
+        assert_array_almost_equal(result, self.dilated3x3)
+
+
+class TestBinaryOpeningClosing:
+
+    def _setup(self, xp):
+        a = np.zeros((5, 5), dtype=bool)
+        a[1:4, 1:4] = True
+        a[4, 4] = True
+        self.array = xp.asarray(a)
+        self.sq3x3 = xp.ones((3, 3))
+        self.opened_old = ndimage.binary_opening(self.array, self.sq3x3,
+                                                 1, None, 0)
+        self.closed_old = ndimage.binary_closing(self.array, self.sq3x3,
+                                                 1, None, 0)
+
+    def test_opening_new_arguments(self, xp):
+        self._setup(xp)
+        opened_new = ndimage.binary_opening(self.array, self.sq3x3, 1, None,
+                                            0, None, 0, False)
+        xp_assert_equal(opened_new, self.opened_old)
+
+    def test_closing_new_arguments(self, xp):
+        self._setup(xp)
+        closed_new = ndimage.binary_closing(self.array, self.sq3x3, 1, None,
+                                            0, None, 0, False)
+        xp_assert_equal(closed_new, self.closed_old)
+
+
+def test_binary_erosion_noninteger_iterations(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    data = xp.ones([1])
+    assert_raises(TypeError, ndimage.binary_erosion, data, iterations=0.5)
+    assert_raises(TypeError, ndimage.binary_erosion, data, iterations=1.5)
+
+
+def test_binary_dilation_noninteger_iterations(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    data = xp.ones([1])
+    assert_raises(TypeError, ndimage.binary_dilation, data, iterations=0.5)
+    assert_raises(TypeError, ndimage.binary_dilation, data, iterations=1.5)
+
+
+def test_binary_opening_noninteger_iterations(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    data = xp.ones([1])
+    assert_raises(TypeError, ndimage.binary_opening, data, iterations=0.5)
+    assert_raises(TypeError, ndimage.binary_opening, data, iterations=1.5)
+
+
+def test_binary_closing_noninteger_iterations(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    data = xp.ones([1])
+    assert_raises(TypeError, ndimage.binary_closing, data, iterations=0.5)
+    assert_raises(TypeError, ndimage.binary_closing, data, iterations=1.5)
+
+
+def test_binary_closing_noninteger_brute_force_passes_when_true(xp):
+    # regression test for gh-9905, gh-9909: ValueError for
+    # non integer iterations
+    if is_cupy(xp):
+        pytest.xfail("CuPy: NotImplementedError: only brute_force iteration")
+
+    data = xp.ones([1])
+
+    xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=1.5),
+                    ndimage.binary_erosion(data, iterations=2, brute_force=bool(1.5))
+    )
+    xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=0.0),
+                    ndimage.binary_erosion(data, iterations=2, brute_force=bool(0.0))
+    )
+
+
+@pytest.mark.parametrize(
+    'function',
+    ['binary_erosion', 'binary_dilation', 'binary_opening', 'binary_closing'],
+)
+@pytest.mark.parametrize('iterations', [1, 5])
+@pytest.mark.parametrize('brute_force', [False, True])
+def test_binary_input_as_output(function, iterations, brute_force, xp):
+    rstate = np.random.RandomState(123)
+    data = rstate.randint(low=0, high=2, size=100).astype(bool)
+    ndi_func = getattr(ndimage, function)
+
+    # input data is not modified
+    data_orig = data.copy()
+    expected = ndi_func(data, brute_force=brute_force, iterations=iterations)
+    xp_assert_equal(data, data_orig)
+
+    # data should now contain the expected result
+    ndi_func(data, brute_force=brute_force, iterations=iterations, output=data)
+    xp_assert_equal(expected, data)
+
+
+def test_binary_hit_or_miss_input_as_output(xp):
+    if not (is_numpy(xp) or is_cupy(xp)):
+        pytest.xfail("inplace output= is numpy-specific")
+
+    rstate = np.random.RandomState(123)
+    data = rstate.randint(low=0, high=2, size=100).astype(bool)
+
+    # input data is not modified
+    data_orig = data.copy()
+    expected = ndimage.binary_hit_or_miss(data)
+    xp_assert_equal(data, data_orig)
+
+    # data should now contain the expected result
+    ndimage.binary_hit_or_miss(data, output=data)
+    xp_assert_equal(expected, data)
+
+
+def test_distance_transform_cdt_invalid_metric(xp):
+    if is_cupy(xp):
+        pytest.xfail("CuPy does not have distance_transform_cdt")
+
+    msg = 'invalid metric provided'
+    with pytest.raises(ValueError, match=msg):
+        ndimage.distance_transform_cdt(xp.ones((5, 5)),
+                                       metric="garbage")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..426d1cf0eccd1ac0f10a90412f008f4b3463c333
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py
@@ -0,0 +1,78 @@
+import pytest
+
+import numpy as np
+from .._ni_support import _get_output
+
+
+@pytest.mark.parametrize(
+    'dtype',
+    [
+        # String specifiers
+        'f4', 'float32', 'complex64', 'complex128',
+        # Type and dtype specifiers
+        np.float32, float, np.dtype('f4'),
+        # Derive from input
+        None,
+    ],
+)
+def test_get_output_basic(dtype):
+    shape = (2, 3)
+
+    input_ = np.zeros(shape, dtype='float32')
+
+    # For None, derive dtype from input
+    expected_dtype = 'float32' if dtype is None else dtype
+
+    # Output is dtype-specifier, retrieve shape from input
+    result = _get_output(dtype, input_)
+    assert result.shape == shape
+    assert result.dtype == np.dtype(expected_dtype)
+
+    # Output is dtype specifier, with explicit shape, overriding input
+    result = _get_output(dtype, input_, shape=(3, 2))
+    assert result.shape == (3, 2)
+    assert result.dtype == np.dtype(expected_dtype)
+
+    # Output is pre-allocated array, return directly
+    output = np.zeros(shape, dtype=dtype)
+    result = _get_output(output, input_)
+    assert result is output
+
+
+@pytest.mark.thread_unsafe
+def test_get_output_complex():
+    shape = (2, 3)
+
+    input_ = np.zeros(shape)
+
+    # None, promote input type to complex
+    result = _get_output(None, input_, complex_output=True)
+    assert result.shape == shape
+    assert result.dtype == np.dtype('complex128')
+
+    # Explicit type, promote type to complex
+    with pytest.warns(UserWarning, match='promoting specified output dtype to complex'):
+        result = _get_output(float, input_, complex_output=True)
+    assert result.shape == shape
+    assert result.dtype == np.dtype('complex128')
+
+    # String specifier, simply verify complex output
+    result = _get_output('complex64', input_, complex_output=True)
+    assert result.shape == shape
+    assert result.dtype == np.dtype('complex64')
+
+
+def test_get_output_error_cases():
+    input_ = np.zeros((2, 3), 'float32')
+
+    # Two separate paths can raise the same error
+    with pytest.raises(RuntimeError, match='output must have complex dtype'):
+        _get_output('float32', input_, complex_output=True)
+    with pytest.raises(RuntimeError, match='output must have complex dtype'):
+        _get_output(np.zeros((2, 3)), input_, complex_output=True)
+
+    with pytest.raises(RuntimeError, match='output must have numeric dtype'):
+        _get_output('void', input_)
+
+    with pytest.raises(RuntimeError, match='shape not correct'):
+        _get_output(np.zeros((3, 2)), input_)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py
new file mode 100644
index 0000000000000000000000000000000000000000..2561ba5acef20ac340e06164bae96f187486c06a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/ndimage/tests/test_splines.py
@@ -0,0 +1,72 @@
+"""Tests for spline filtering."""
+import pytest
+
+import numpy as np
+from scipy._lib._array_api import assert_almost_equal
+
+from scipy import ndimage
+
+from scipy.conftest import array_api_compatible
+skip_xp_backends = pytest.mark.skip_xp_backends
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),
+              skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'],)]
+
+
+def get_spline_knot_values(order):
+    """Knot values to the right of a B-spline's center."""
+    knot_values = {0: [1],
+                   1: [1],
+                   2: [6, 1],
+                   3: [4, 1],
+                   4: [230, 76, 1],
+                   5: [66, 26, 1]}
+
+    return knot_values[order]
+
+
+def make_spline_knot_matrix(xp, n, order, mode='mirror'):
+    """Matrix to invert to find the spline coefficients."""
+    knot_values = get_spline_knot_values(order)
+
+    # NB: do computations with numpy, convert to xp as the last step only
+
+    matrix = np.zeros((n, n))
+    for diag, knot_value in enumerate(knot_values):
+        indices = np.arange(diag, n)
+        if diag == 0:
+            matrix[indices, indices] = knot_value
+        else:
+            matrix[indices, indices - diag] = knot_value
+            matrix[indices - diag, indices] = knot_value
+
+    knot_values_sum = knot_values[0] + 2 * sum(knot_values[1:])
+
+    if mode == 'mirror':
+        start, step = 1, 1
+    elif mode == 'reflect':
+        start, step = 0, 1
+    elif mode == 'grid-wrap':
+        start, step = -1, -1
+    else:
+        raise ValueError(f'unsupported mode {mode}')
+
+    for row in range(len(knot_values) - 1):
+        for idx, knot_value in enumerate(knot_values[row + 1:]):
+            matrix[row, start + step*idx] += knot_value
+            matrix[-row - 1, -start - 1 - step*idx] += knot_value
+
+    return xp.asarray(matrix / knot_values_sum)
+
+
+@pytest.mark.parametrize('order', [0, 1, 2, 3, 4, 5])
+@pytest.mark.parametrize('mode', ['mirror', 'grid-wrap', 'reflect'])
+def test_spline_filter_vs_matrix_solution(order, mode, xp):
+    n = 100
+    eye = xp.eye(n, dtype=xp.float64)
+    spline_filter_axis_0 = ndimage.spline_filter1d(eye, axis=0, order=order,
+                                                   mode=mode)
+    spline_filter_axis_1 = ndimage.spline_filter1d(eye, axis=1, order=order,
+                                                   mode=mode)
+    matrix = make_spline_knot_matrix(xp, n, order, mode=mode)
+    assert_almost_equal(eye, spline_filter_axis_0 @ matrix)
+    assert_almost_equal(eye, spline_filter_axis_1 @ matrix.T)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64f865bca80e01795f7ce75657b91914512c3941
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_base.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e3a81fbc68d06cbde09e50e8f680dc5524041eda
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_base.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93c70371c50bc027c9befa4f5a5656ab1c5470a3
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_bsr.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..946bc5e8914024e2ac8a665f576d220e4642343a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_compressed.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec4f254713c2dfe36cd68d9069d370097ccc1ea8
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8cac8846246fc9f3256c072c1a14cf705676320
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_coo.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84f8ff2b655e7d787c430ea403c8639443b0906d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csc.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db5515e8175d440a3848062f007cbf69ee380093
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_csr.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85087d9f4ee6e8535c7350722e3f952f45eefaae
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd636f87bb767d644a96e019f5f515a2df87cc08
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e0c8c72a8d1a27cd3e18e580b26db6e24123e5bb
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dok.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..800f810c0675ddd2e5e5df80549cd986465b57dd
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..229bf93685af3de6d77ee4ceb2f6d50e0b109465
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_index.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5edc8bcd01125088a6b8856cddba5db5565ac0c5
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c7154f01b857e6b7fcadfac6657316ff47f001b
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..09c8aa5dff5ebe8cebdcb4d0601bbac7a3aebd24
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix_io.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d521021d7c0d2041b630875f2b87f55d569e859e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/_sputils.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c621e98ea7bc044d85d67bd0e1ae310b335f342
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc13de3c2614472a906d78c171b60d0f5991f1fa
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed05796a68f913b260ef5ffdc7e553565fa2804a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bae572793977ca367883caccb3a1ee765c080b98
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/construct.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d63359ec0ccd152ab6da6354971ef09b59fe5fdc
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/coo.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c2f1c589e629694b4539de8ec063f196273bd78
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8055ca820f03f7277228fcd4f19201ad9112352
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/csr.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb1710a66e539140f993be178f8ad6667bb7f712
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/data.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40c015888f2ac68f8c7fecc97c07a64031c92d76
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa7314ea2c017ccdb5a3e6cb04d763bb93d50928
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/dok.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/extract.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/extract.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed84a3e8192bf5382425cac52dfb06f6caf1633e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/extract.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..265df5cde503d9fa4e635ead814367ca31fdf459
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/lil.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..75a2c9c90bd2238b2852d4388bb347185f99b0d9
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7452d97287f9cebcb15111367ec43caddacc7ae7
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/__pycache__/sputils.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ab19af4748147d748fccb51a3710d5c711f4b4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__init__.py
@@ -0,0 +1,210 @@
+r"""
+Compressed sparse graph routines (:mod:`scipy.sparse.csgraph`)
+==============================================================
+
+.. currentmodule:: scipy.sparse.csgraph
+
+Fast graph algorithms based on sparse matrix representations.
+
+Contents
+--------
+
+.. autosummary::
+   :toctree: generated/
+
+   connected_components -- determine connected components of a graph
+   laplacian -- compute the laplacian of a graph
+   shortest_path -- compute the shortest path between points on a positive graph
+   dijkstra -- use Dijkstra's algorithm for shortest path
+   floyd_warshall -- use the Floyd-Warshall algorithm for shortest path
+   bellman_ford -- use the Bellman-Ford algorithm for shortest path
+   johnson -- use Johnson's algorithm for shortest path
+   yen -- use Yen's algorithm for K-shortest paths between to nodes.
+   breadth_first_order -- compute a breadth-first order of nodes
+   depth_first_order -- compute a depth-first order of nodes
+   breadth_first_tree -- construct the breadth-first tree from a given node
+   depth_first_tree -- construct a depth-first tree from a given node
+   minimum_spanning_tree -- construct the minimum spanning tree of a graph
+   reverse_cuthill_mckee -- compute permutation for reverse Cuthill-McKee ordering
+   maximum_flow -- solve the maximum flow problem for a graph
+   maximum_bipartite_matching -- compute a maximum matching of a bipartite graph
+   min_weight_full_bipartite_matching - compute a minimum weight full matching of a bipartite graph
+   structural_rank -- compute the structural rank of a graph
+   NegativeCycleError
+
+.. autosummary::
+   :toctree: generated/
+
+   construct_dist_matrix
+   csgraph_from_dense
+   csgraph_from_masked
+   csgraph_masked_from_dense
+   csgraph_to_dense
+   csgraph_to_masked
+   reconstruct_path
+
+Graph Representations
+---------------------
+This module uses graphs which are stored in a matrix format. A
+graph with N nodes can be represented by an (N x N) adjacency matrix G.
+If there is a connection from node i to node j, then G[i, j] = w, where
+w is the weight of the connection. For nodes i and j which are
+not connected, the value depends on the representation:
+
+- for dense array representations, non-edges are represented by
+  G[i, j] = 0, infinity, or NaN.
+
+- for dense masked representations (of type np.ma.MaskedArray), non-edges
+  are represented by masked values. This can be useful when graphs with
+  zero-weight edges are desired.
+
+- for sparse array representations, non-edges are represented by
+  non-entries in the matrix. This sort of sparse representation also
+  allows for edges with zero weights.
+
+As a concrete example, imagine that you would like to represent the following
+undirected graph::
+
+              G
+
+             (0)
+            /   \
+           1     2
+          /       \
+        (2)       (1)
+
+This graph has three nodes, where node 0 and 1 are connected by an edge of
+weight 2, and nodes 0 and 2 are connected by an edge of weight 1.
+We can construct the dense, masked, and sparse representations as follows,
+keeping in mind that an undirected graph is represented by a symmetric matrix::
+
+    >>> import numpy as np
+    >>> G_dense = np.array([[0, 2, 1],
+    ...                     [2, 0, 0],
+    ...                     [1, 0, 0]])
+    >>> G_masked = np.ma.masked_values(G_dense, 0)
+    >>> from scipy.sparse import csr_array
+    >>> G_sparse = csr_array(G_dense)
+
+This becomes more difficult when zero edges are significant. For example,
+consider the situation when we slightly modify the above graph::
+
+             G2
+
+             (0)
+            /   \
+           0     2
+          /       \
+        (2)       (1)
+
+This is identical to the previous graph, except nodes 0 and 2 are connected
+by an edge of zero weight. In this case, the dense representation above
+leads to ambiguities: how can non-edges be represented if zero is a meaningful
+value? In this case, either a masked or sparse representation must be used
+to eliminate the ambiguity::
+
+    >>> import numpy as np
+    >>> G2_data = np.array([[np.inf, 2,      0     ],
+    ...                     [2,      np.inf, np.inf],
+    ...                     [0,      np.inf, np.inf]])
+    >>> G2_masked = np.ma.masked_invalid(G2_data)
+    >>> from scipy.sparse.csgraph import csgraph_from_dense
+    >>> # G2_sparse = csr_array(G2_data) would give the wrong result
+    >>> G2_sparse = csgraph_from_dense(G2_data, null_value=np.inf)
+    >>> G2_sparse.data
+    array([ 2.,  0.,  2.,  0.])
+
+Here we have used a utility routine from the csgraph submodule in order to
+convert the dense representation to a sparse representation which can be
+understood by the algorithms in submodule. By viewing the data array, we
+can see that the zero values are explicitly encoded in the graph.
+
+Directed vs. undirected
+^^^^^^^^^^^^^^^^^^^^^^^
+Matrices may represent either directed or undirected graphs. This is
+specified throughout the csgraph module by a boolean keyword. Graphs are
+assumed to be directed by default. In a directed graph, traversal from node
+i to node j can be accomplished over the edge G[i, j], but not the edge
+G[j, i].  Consider the following dense graph::
+
+    >>> import numpy as np
+    >>> G_dense = np.array([[0, 1, 0],
+    ...                     [2, 0, 3],
+    ...                     [0, 4, 0]])
+
+When ``directed=True`` we get the graph::
+
+      ---1--> ---3-->
+    (0)     (1)     (2)
+      <--2--- <--4---
+
+In a non-directed graph, traversal from node i to node j can be
+accomplished over either G[i, j] or G[j, i].  If both edges are not null,
+and the two have unequal weights, then the smaller of the two is used.
+
+So for the same graph, when ``directed=False`` we get the graph::
+
+    (0)--1--(1)--3--(2)
+
+Note that a symmetric matrix will represent an undirected graph, regardless
+of whether the 'directed' keyword is set to True or False. In this case,
+using ``directed=True`` generally leads to more efficient computation.
+
+The routines in this module accept as input either scipy.sparse representations
+(csr, csc, or lil format), masked representations, or dense representations
+with non-edges indicated by zeros, infinities, and NaN entries.
+"""  # noqa: E501
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['connected_components',
+           'laplacian',
+           'shortest_path',
+           'floyd_warshall',
+           'dijkstra',
+           'bellman_ford',
+           'johnson',
+           'yen',
+           'breadth_first_order',
+           'depth_first_order',
+           'breadth_first_tree',
+           'depth_first_tree',
+           'minimum_spanning_tree',
+           'reverse_cuthill_mckee',
+           'maximum_flow',
+           'maximum_bipartite_matching',
+           'min_weight_full_bipartite_matching',
+           'structural_rank',
+           'construct_dist_matrix',
+           'reconstruct_path',
+           'csgraph_masked_from_dense',
+           'csgraph_from_dense',
+           'csgraph_from_masked',
+           'csgraph_to_dense',
+           'csgraph_to_masked',
+           'NegativeCycleError']
+
+from ._laplacian import laplacian
+from ._shortest_path import (
+    shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, yen,
+    NegativeCycleError
+)
+from ._traversal import (
+    breadth_first_order, depth_first_order, breadth_first_tree,
+    depth_first_tree, connected_components
+)
+from ._min_spanning_tree import minimum_spanning_tree
+from ._flow import maximum_flow
+from ._matching import (
+    maximum_bipartite_matching, min_weight_full_bipartite_matching
+)
+from ._reordering import reverse_cuthill_mckee, structural_rank
+from ._tools import (
+    construct_dist_matrix, reconstruct_path, csgraph_from_dense,
+    csgraph_to_dense, csgraph_masked_from_dense, csgraph_from_masked,
+    csgraph_to_masked
+)
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..428a01141bf47a028ce41e92b098d24f24edb649
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91963b75333816e174a8e238c977bf56c02775db
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_laplacian.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_validation.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_validation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c0337d8c0c09097c0b2680b928e0c4647eae69a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/__pycache__/_validation.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5529a0662a3f9db006bc5411664908f10d8fe23
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py
@@ -0,0 +1,563 @@
+"""
+Laplacian of a compressed-sparse graph
+"""
+
+import numpy as np
+from scipy.sparse import issparse
+from scipy.sparse.linalg import LinearOperator
+from scipy.sparse._sputils import convert_pydata_sparse_to_scipy, is_pydata_spmatrix
+
+
+###############################################################################
+# Graph laplacian
+def laplacian(
+    csgraph,
+    normed=False,
+    return_diag=False,
+    use_out_degree=False,
+    *,
+    copy=True,
+    form="array",
+    dtype=None,
+    symmetrized=False,
+):
+    """
+    Return the Laplacian of a directed graph.
+
+    Parameters
+    ----------
+    csgraph : array_like or sparse array or matrix, 2 dimensions
+        compressed-sparse graph, with shape (N, N).
+    normed : bool, optional
+        If True, then compute symmetrically normalized Laplacian.
+        Default: False.
+    return_diag : bool, optional
+        If True, then also return an array related to vertex degrees.
+        Default: False.
+    use_out_degree : bool, optional
+        If True, then use out-degree instead of in-degree.
+        This distinction matters only if the graph is asymmetric.
+        Default: False.
+    copy: bool, optional
+        If False, then change `csgraph` in place if possible,
+        avoiding doubling the memory use.
+        Default: True, for backward compatibility.
+    form: 'array', or 'function', or 'lo'
+        Determines the format of the output Laplacian:
+
+        * 'array' is a numpy array;
+        * 'function' is a pointer to evaluating the Laplacian-vector
+          or Laplacian-matrix product;
+        * 'lo' results in the format of the `LinearOperator`.
+
+        Choosing 'function' or 'lo' always avoids doubling
+        the memory use, ignoring `copy` value.
+        Default: 'array', for backward compatibility.
+    dtype: None or one of numeric numpy dtypes, optional
+        The dtype of the output. If ``dtype=None``, the dtype of the
+        output matches the dtype of the input csgraph, except for
+        the case ``normed=True`` and integer-like csgraph, where
+        the output dtype is 'float' allowing accurate normalization,
+        but dramatically increasing the memory use.
+        Default: None, for backward compatibility.
+    symmetrized: bool, optional
+        If True, then the output Laplacian is symmetric/Hermitian.
+        The symmetrization is done by ``csgraph + csgraph.T.conj``
+        without dividing by 2 to preserve integer dtypes if possible
+        prior to the construction of the Laplacian.
+        The symmetrization will increase the memory footprint of
+        sparse matrices unless the sparsity pattern is symmetric or
+        `form` is 'function' or 'lo'.
+        Default: False, for backward compatibility.
+
+    Returns
+    -------
+    lap : ndarray, or sparse array or matrix, or `LinearOperator`
+        The N x N Laplacian of csgraph. It will be a NumPy array (dense)
+        if the input was dense, or a sparse array otherwise, or
+        the format of a function or `LinearOperator` if
+        `form` equals 'function' or 'lo', respectively.
+    diag : ndarray, optional
+        The length-N main diagonal of the Laplacian matrix.
+        For the normalized Laplacian, this is the array of square roots
+        of vertex degrees or 1 if the degree is zero.
+
+    Notes
+    -----
+    The Laplacian matrix of a graph is sometimes referred to as the
+    "Kirchhoff matrix" or just the "Laplacian", and is useful in many
+    parts of spectral graph theory.
+    In particular, the eigen-decomposition of the Laplacian can give
+    insight into many properties of the graph, e.g.,
+    is commonly used for spectral data embedding and clustering.
+
+    The constructed Laplacian doubles the memory use if ``copy=True`` and
+    ``form="array"`` which is the default.
+    Choosing ``copy=False`` has no effect unless ``form="array"``
+    or the matrix is sparse in the ``coo`` format, or dense array, except
+    for the integer input with ``normed=True`` that forces the float output.
+
+    Sparse input is reformatted into ``coo`` if ``form="array"``,
+    which is the default.
+
+    If the input adjacency matrix is not symmetric, the Laplacian is
+    also non-symmetric unless ``symmetrized=True`` is used.
+
+    Diagonal entries of the input adjacency matrix are ignored and
+    replaced with zeros for the purpose of normalization where ``normed=True``.
+    The normalization uses the inverse square roots of row-sums of the input
+    adjacency matrix, and thus may fail if the row-sums contain
+    negative or complex with a non-zero imaginary part values.
+
+    The normalization is symmetric, making the normalized Laplacian also
+    symmetric if the input csgraph was symmetric.
+
+    References
+    ----------
+    .. [1] Laplacian matrix. https://en.wikipedia.org/wiki/Laplacian_matrix
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csgraph
+
+    Our first illustration is the symmetric graph
+
+    >>> G = np.arange(4) * np.arange(4)[:, np.newaxis]
+    >>> G
+    array([[0, 0, 0, 0],
+           [0, 1, 2, 3],
+           [0, 2, 4, 6],
+           [0, 3, 6, 9]])
+
+    and its symmetric Laplacian matrix
+
+    >>> csgraph.laplacian(G)
+    array([[ 0,  0,  0,  0],
+           [ 0,  5, -2, -3],
+           [ 0, -2,  8, -6],
+           [ 0, -3, -6,  9]])
+
+    The non-symmetric graph
+
+    >>> G = np.arange(9).reshape(3, 3)
+    >>> G
+    array([[0, 1, 2],
+           [3, 4, 5],
+           [6, 7, 8]])
+
+    has different row- and column sums, resulting in two varieties
+    of the Laplacian matrix, using an in-degree, which is the default
+
+    >>> L_in_degree = csgraph.laplacian(G)
+    >>> L_in_degree
+    array([[ 9, -1, -2],
+           [-3,  8, -5],
+           [-6, -7,  7]])
+
+    or alternatively an out-degree
+
+    >>> L_out_degree = csgraph.laplacian(G, use_out_degree=True)
+    >>> L_out_degree
+    array([[ 3, -1, -2],
+           [-3,  8, -5],
+           [-6, -7, 13]])
+
+    Constructing a symmetric Laplacian matrix, one can add the two as
+
+    >>> L_in_degree + L_out_degree.T
+    array([[ 12,  -4,  -8],
+            [ -4,  16, -12],
+            [ -8, -12,  20]])
+
+    or use the ``symmetrized=True`` option
+
+    >>> csgraph.laplacian(G, symmetrized=True)
+    array([[ 12,  -4,  -8],
+           [ -4,  16, -12],
+           [ -8, -12,  20]])
+
+    that is equivalent to symmetrizing the original graph
+
+    >>> csgraph.laplacian(G + G.T)
+    array([[ 12,  -4,  -8],
+           [ -4,  16, -12],
+           [ -8, -12,  20]])
+
+    The goal of normalization is to make the non-zero diagonal entries
+    of the Laplacian matrix to be all unit, also scaling off-diagonal
+    entries correspondingly. The normalization can be done manually, e.g.,
+
+    >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]])
+    >>> L, d = csgraph.laplacian(G, return_diag=True)
+    >>> L
+    array([[ 2, -1, -1],
+           [-1,  2, -1],
+           [-1, -1,  2]])
+    >>> d
+    array([2, 2, 2])
+    >>> scaling = np.sqrt(d)
+    >>> scaling
+    array([1.41421356, 1.41421356, 1.41421356])
+    >>> (1/scaling)*L*(1/scaling)
+    array([[ 1. , -0.5, -0.5],
+           [-0.5,  1. , -0.5],
+           [-0.5, -0.5,  1. ]])
+
+    Or using ``normed=True`` option
+
+    >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True)
+    >>> L
+    array([[ 1. , -0.5, -0.5],
+           [-0.5,  1. , -0.5],
+           [-0.5, -0.5,  1. ]])
+
+    which now instead of the diagonal returns the scaling coefficients
+
+    >>> d
+    array([1.41421356, 1.41421356, 1.41421356])
+
+    Zero scaling coefficients are substituted with 1s, where scaling
+    has thus no effect, e.g.,
+
+    >>> G = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]])
+    >>> G
+    array([[0, 0, 0],
+           [0, 0, 1],
+           [0, 1, 0]])
+    >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True)
+    >>> L
+    array([[ 0., -0., -0.],
+           [-0.,  1., -1.],
+           [-0., -1.,  1.]])
+    >>> d
+    array([1., 1., 1.])
+
+    Only the symmetric normalization is implemented, resulting
+    in a symmetric Laplacian matrix if and only if its graph is symmetric
+    and has all non-negative degrees, like in the examples above.
+
+    The output Laplacian matrix is by default a dense array or a sparse
+    array or matrix inferring its class, shape, format, and dtype from
+    the input graph matrix:
+
+    >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]).astype(np.float32)
+    >>> G
+    array([[0., 1., 1.],
+           [1., 0., 1.],
+           [1., 1., 0.]], dtype=float32)
+    >>> csgraph.laplacian(G)
+    array([[ 2., -1., -1.],
+           [-1.,  2., -1.],
+           [-1., -1.,  2.]], dtype=float32)
+
+    but can alternatively be generated matrix-free as a LinearOperator:
+
+    >>> L = csgraph.laplacian(G, form="lo")
+    >>> L
+    <3x3 _CustomLinearOperator with dtype=float32>
+    >>> L(np.eye(3))
+    array([[ 2., -1., -1.],
+           [-1.,  2., -1.],
+           [-1., -1.,  2.]])
+
+    or as a lambda-function:
+
+    >>> L = csgraph.laplacian(G, form="function")
+    >>> L
+    . at 0x0000012AE6F5A598>
+    >>> L(np.eye(3))
+    array([[ 2., -1., -1.],
+           [-1.,  2., -1.],
+           [-1., -1.,  2.]])
+
+    The Laplacian matrix is used for
+    spectral data clustering and embedding
+    as well as for spectral graph partitioning.
+    Our final example illustrates the latter
+    for a noisy directed linear graph.
+
+    >>> from scipy.sparse import diags_array, random_array
+    >>> from scipy.sparse.linalg import lobpcg
+
+    Create a directed linear graph with ``N=35`` vertices
+    using a sparse adjacency matrix ``G``:
+
+    >>> N = 35
+    >>> G = diags_array(np.ones(N - 1), offsets=1, format="csr")
+
+    Fix a random seed ``rng`` and add a random sparse noise to the graph ``G``:
+
+    >>> rng = np.random.default_rng()
+    >>> G += 1e-2 * random_array((N, N), density=0.1, rng=rng)
+
+    Set initial approximations for eigenvectors:
+
+    >>> X = rng.random((N, 2))
+
+    The constant vector of ones is always a trivial eigenvector
+    of the non-normalized Laplacian to be filtered out:
+
+    >>> Y = np.ones((N, 1))
+
+    Alternating (1) the sign of the graph weights allows determining
+    labels for spectral max- and min- cuts in a single loop.
+    Since the graph is undirected, the option ``symmetrized=True``
+    must be used in the construction of the Laplacian.
+    The option ``normed=True`` cannot be used in (2) for the negative weights
+    here as the symmetric normalization evaluates square roots.
+    The option ``form="lo"`` in (2) is matrix-free, i.e., guarantees
+    a fixed memory footprint and read-only access to the graph.
+    Calling the eigenvalue solver ``lobpcg`` (3) computes the Fiedler vector
+    that determines the labels as the signs of its components in (5).
+    Since the sign in an eigenvector is not deterministic and can flip,
+    we fix the sign of the first component to be always +1 in (4).
+
+    >>> for cut in ["max", "min"]:
+    ...     G = -G  # 1.
+    ...     L = csgraph.laplacian(G, symmetrized=True, form="lo")  # 2.
+    ...     _, eves = lobpcg(L, X, Y=Y, largest=False, tol=1e-2)  # 3.
+    ...     eves *= np.sign(eves[0, 0])  # 4.
+    ...     print(cut + "-cut labels:\\n", 1 * (eves[:, 0]>0))  # 5.
+    max-cut labels:
+    [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
+    min-cut labels:
+    [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
+
+    As anticipated for a (slightly noisy) linear graph,
+    the max-cut strips all the edges of the graph coloring all
+    odd vertices into one color and all even vertices into another one,
+    while the balanced min-cut partitions the graph
+    in the middle by deleting a single edge.
+    Both determined partitions are optimal.
+    """
+    is_pydata_sparse = is_pydata_spmatrix(csgraph)
+    if is_pydata_sparse:
+        pydata_sparse_cls = csgraph.__class__
+        csgraph = convert_pydata_sparse_to_scipy(csgraph)
+    if csgraph.ndim != 2 or csgraph.shape[0] != csgraph.shape[1]:
+        raise ValueError('csgraph must be a square matrix or array')
+
+    if normed and (
+        np.issubdtype(csgraph.dtype, np.signedinteger)
+        or np.issubdtype(csgraph.dtype, np.uint)
+    ):
+        csgraph = csgraph.astype(np.float64)
+
+    if form == "array":
+        create_lap = (
+            _laplacian_sparse if issparse(csgraph) else _laplacian_dense
+        )
+    else:
+        create_lap = (
+            _laplacian_sparse_flo
+            if issparse(csgraph)
+            else _laplacian_dense_flo
+        )
+
+    degree_axis = 1 if use_out_degree else 0
+
+    lap, d = create_lap(
+        csgraph,
+        normed=normed,
+        axis=degree_axis,
+        copy=copy,
+        form=form,
+        dtype=dtype,
+        symmetrized=symmetrized,
+    )
+    if is_pydata_sparse:
+        lap = pydata_sparse_cls.from_scipy_sparse(lap)
+    if return_diag:
+        return lap, d
+    return lap
+
+
+def _setdiag_dense(m, d):
+    step = len(d) + 1
+    m.flat[::step] = d
+
+
+def _laplace(m, d):
+    return lambda v: v * d[:, np.newaxis] - m @ v
+
+
+def _laplace_normed(m, d, nd):
+    laplace = _laplace(m, d)
+    return lambda v: nd[:, np.newaxis] * laplace(v * nd[:, np.newaxis])
+
+
+def _laplace_sym(m, d):
+    return (
+        lambda v: v * d[:, np.newaxis]
+        - m @ v
+        - np.transpose(np.conjugate(np.transpose(np.conjugate(v)) @ m))
+    )
+
+
+def _laplace_normed_sym(m, d, nd):
+    laplace_sym = _laplace_sym(m, d)
+    return lambda v: nd[:, np.newaxis] * laplace_sym(v * nd[:, np.newaxis])
+
+
+def _linearoperator(mv, shape, dtype):
+    return LinearOperator(matvec=mv, matmat=mv, shape=shape, dtype=dtype)
+
+
+def _laplacian_sparse_flo(graph, normed, axis, copy, form, dtype, symmetrized):
+    # The keyword argument `copy` is unused and has no effect here.
+    del copy
+
+    if dtype is None:
+        dtype = graph.dtype
+
+    graph_sum = np.asarray(graph.sum(axis=axis)).ravel()
+    graph_diagonal = graph.diagonal()
+    diag = graph_sum - graph_diagonal
+    if symmetrized:
+        graph_sum += np.asarray(graph.sum(axis=1 - axis)).ravel()
+        diag = graph_sum - graph_diagonal - graph_diagonal
+
+    if normed:
+        isolated_node_mask = diag == 0
+        w = np.where(isolated_node_mask, 1, np.sqrt(diag))
+        if symmetrized:
+            md = _laplace_normed_sym(graph, graph_sum, 1.0 / w)
+        else:
+            md = _laplace_normed(graph, graph_sum, 1.0 / w)
+        if form == "function":
+            return md, w.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, w.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+    else:
+        if symmetrized:
+            md = _laplace_sym(graph, graph_sum)
+        else:
+            md = _laplace(graph, graph_sum)
+        if form == "function":
+            return md, diag.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, diag.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+
+
+def _laplacian_sparse(graph, normed, axis, copy, form, dtype, symmetrized):
+    # The keyword argument `form` is unused and has no effect here.
+    del form
+
+    if dtype is None:
+        dtype = graph.dtype
+
+    needs_copy = False
+    if graph.format in ('lil', 'dok'):
+        m = graph.tocoo()
+    else:
+        m = graph
+        if copy:
+            needs_copy = True
+
+    if symmetrized:
+        m += m.T.conj()
+
+    w = np.asarray(m.sum(axis=axis)).ravel() - m.diagonal()
+    if normed:
+        m = m.tocoo(copy=needs_copy)
+        isolated_node_mask = (w == 0)
+        w = np.where(isolated_node_mask, 1, np.sqrt(w))
+        m.data /= w[m.row]
+        m.data /= w[m.col]
+        m.data *= -1
+        m.setdiag(1 - isolated_node_mask)
+    else:
+        if m.format == 'dia':
+            m = m.copy()
+        else:
+            m = m.tocoo(copy=needs_copy)
+        m.data *= -1
+        m.setdiag(w)
+
+    return m.astype(dtype, copy=False), w.astype(dtype)
+
+
+def _laplacian_dense_flo(graph, normed, axis, copy, form, dtype, symmetrized):
+
+    if copy:
+        m = np.array(graph)
+    else:
+        m = np.asarray(graph)
+
+    if dtype is None:
+        dtype = m.dtype
+
+    graph_sum = m.sum(axis=axis)
+    graph_diagonal = m.diagonal()
+    diag = graph_sum - graph_diagonal
+    if symmetrized:
+        graph_sum += m.sum(axis=1 - axis)
+        diag = graph_sum - graph_diagonal - graph_diagonal
+
+    if normed:
+        isolated_node_mask = diag == 0
+        w = np.where(isolated_node_mask, 1, np.sqrt(diag))
+        if symmetrized:
+            md = _laplace_normed_sym(m, graph_sum, 1.0 / w)
+        else:
+            md = _laplace_normed(m, graph_sum, 1.0 / w)
+        if form == "function":
+            return md, w.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, w.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+    else:
+        if symmetrized:
+            md = _laplace_sym(m, graph_sum)
+        else:
+            md = _laplace(m, graph_sum)
+        if form == "function":
+            return md, diag.astype(dtype, copy=False)
+        elif form == "lo":
+            m = _linearoperator(md, shape=graph.shape, dtype=dtype)
+            return m, diag.astype(dtype, copy=False)
+        else:
+            raise ValueError(f"Invalid form: {form!r}")
+
+
+def _laplacian_dense(graph, normed, axis, copy, form, dtype, symmetrized):
+
+    if form != "array":
+        raise ValueError(f'{form!r} must be "array"')
+
+    if dtype is None:
+        dtype = graph.dtype
+
+    if copy:
+        m = np.array(graph)
+    else:
+        m = np.asarray(graph)
+
+    if dtype is None:
+        dtype = m.dtype
+
+    if symmetrized:
+        m += m.T.conj()
+    np.fill_diagonal(m, 0)
+    w = m.sum(axis=axis)
+    if normed:
+        isolated_node_mask = (w == 0)
+        w = np.where(isolated_node_mask, 1, np.sqrt(w))
+        m /= w
+        m /= w[:, np.newaxis]
+        m *= -1
+        _setdiag_dense(m, 1 - isolated_node_mask)
+    else:
+        m *= -1
+        _setdiag_dense(m, w)
+
+    return m.astype(dtype, copy=False), w.astype(dtype, copy=False)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..6eb9ce811b73e751ebb1cd6b226b73f7bcfe7ceb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/_validation.py
@@ -0,0 +1,66 @@
+import numpy as np
+from scipy.sparse import issparse
+from scipy.sparse._sputils import convert_pydata_sparse_to_scipy
+from scipy.sparse.csgraph._tools import (
+    csgraph_to_dense, csgraph_from_dense,
+    csgraph_masked_from_dense, csgraph_from_masked
+)
+
+DTYPE = np.float64
+
+
+def validate_graph(csgraph, directed, dtype=DTYPE,
+                   csr_output=True, dense_output=True,
+                   copy_if_dense=False, copy_if_sparse=False,
+                   null_value_in=0, null_value_out=np.inf,
+                   infinity_null=True, nan_null=True):
+    """Routine for validation and conversion of csgraph inputs"""
+    if not (csr_output or dense_output):
+        raise ValueError("Internal: dense or csr output must be true")
+
+    accept_fv = [null_value_in]
+    if infinity_null:
+        accept_fv.append(np.inf)
+    if nan_null:
+        accept_fv.append(np.nan)
+    csgraph = convert_pydata_sparse_to_scipy(csgraph, accept_fv=accept_fv)
+
+    # if undirected and csc storage, then transposing in-place
+    # is quicker than later converting to csr.
+    if (not directed) and issparse(csgraph) and csgraph.format == "csc":
+        csgraph = csgraph.T
+
+    if issparse(csgraph):
+        if csr_output:
+            csgraph = csgraph.tocsr(copy=copy_if_sparse).astype(DTYPE, copy=False)
+        else:
+            csgraph = csgraph_to_dense(csgraph, null_value=null_value_out)
+    elif np.ma.isMaskedArray(csgraph):
+        if dense_output:
+            mask = csgraph.mask
+            csgraph = np.array(csgraph.data, dtype=DTYPE, copy=copy_if_dense)
+            csgraph[mask] = null_value_out
+        else:
+            csgraph = csgraph_from_masked(csgraph)
+    else:
+        if dense_output:
+            csgraph = csgraph_masked_from_dense(csgraph,
+                                                copy=copy_if_dense,
+                                                null_value=null_value_in,
+                                                nan_null=nan_null,
+                                                infinity_null=infinity_null)
+            mask = csgraph.mask
+            csgraph = np.asarray(csgraph.data, dtype=DTYPE)
+            csgraph[mask] = null_value_out
+        else:
+            csgraph = csgraph_from_dense(csgraph, null_value=null_value_in,
+                                         infinity_null=infinity_null,
+                                         nan_null=nan_null)
+
+    if csgraph.ndim != 2:
+        raise ValueError("compressed-sparse graph must be 2-D")
+
+    if csgraph.shape[0] != csgraph.shape[1]:
+        raise ValueError("compressed-sparse graph must be shape (N, N)")
+
+    return csgraph
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b190a24deb9f2818893a120f8ea376fbfb8d6fe
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_connected_components.py
@@ -0,0 +1,119 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_array_almost_equal
+from scipy.sparse import csgraph, csr_array
+
+
+def test_weak_connections():
+    Xde = np.array([[0, 1, 0],
+                    [0, 0, 0],
+                    [0, 0, 0]])
+
+    Xsp = csgraph.csgraph_from_dense(Xde, null_value=0)
+
+    for X in Xsp, Xde:
+        n_components, labels =\
+            csgraph.connected_components(X, directed=True,
+                                         connection='weak')
+
+        assert_equal(n_components, 2)
+        assert_array_almost_equal(labels, [0, 0, 1])
+
+
+def test_strong_connections():
+    X1de = np.array([[0, 1, 0],
+                     [0, 0, 0],
+                     [0, 0, 0]])
+    X2de = X1de + X1de.T
+
+    X1sp = csgraph.csgraph_from_dense(X1de, null_value=0)
+    X2sp = csgraph.csgraph_from_dense(X2de, null_value=0)
+
+    for X in X1sp, X1de:
+        n_components, labels =\
+            csgraph.connected_components(X, directed=True,
+                                         connection='strong')
+
+        assert_equal(n_components, 3)
+        labels.sort()
+        assert_array_almost_equal(labels, [0, 1, 2])
+
+    for X in X2sp, X2de:
+        n_components, labels =\
+            csgraph.connected_components(X, directed=True,
+                                         connection='strong')
+
+        assert_equal(n_components, 2)
+        labels.sort()
+        assert_array_almost_equal(labels, [0, 0, 1])
+
+
+def test_strong_connections2():
+    X = np.array([[0, 0, 0, 0, 0, 0],
+                  [1, 0, 1, 0, 0, 0],
+                  [0, 0, 0, 1, 0, 0],
+                  [0, 0, 1, 0, 1, 0],
+                  [0, 0, 0, 0, 0, 0],
+                  [0, 0, 0, 0, 1, 0]])
+    n_components, labels =\
+        csgraph.connected_components(X, directed=True,
+                                     connection='strong')
+    assert_equal(n_components, 5)
+    labels.sort()
+    assert_array_almost_equal(labels, [0, 1, 2, 2, 3, 4])
+
+
+def test_weak_connections2():
+    X = np.array([[0, 0, 0, 0, 0, 0],
+                  [1, 0, 0, 0, 0, 0],
+                  [0, 0, 0, 1, 0, 0],
+                  [0, 0, 1, 0, 1, 0],
+                  [0, 0, 0, 0, 0, 0],
+                  [0, 0, 0, 0, 1, 0]])
+    n_components, labels =\
+        csgraph.connected_components(X, directed=True,
+                                     connection='weak')
+    assert_equal(n_components, 2)
+    labels.sort()
+    assert_array_almost_equal(labels, [0, 0, 1, 1, 1, 1])
+
+
+def test_ticket1876():
+    # Regression test: this failed in the original implementation
+    # There should be two strongly-connected components; previously gave one
+    g = np.array([[0, 1, 1, 0],
+                  [1, 0, 0, 1],
+                  [0, 0, 0, 1],
+                  [0, 0, 1, 0]])
+    n_components, labels = csgraph.connected_components(g, connection='strong')
+
+    assert_equal(n_components, 2)
+    assert_equal(labels[0], labels[1])
+    assert_equal(labels[2], labels[3])
+
+
+def test_fully_connected_graph():
+    # Fully connected dense matrices raised an exception.
+    # https://github.com/scipy/scipy/issues/3818
+    g = np.ones((4, 4))
+    n_components, labels = csgraph.connected_components(g)
+    assert_equal(n_components, 1)
+
+
+def test_int64_indices_undirected():
+    # See https://github.com/scipy/scipy/issues/18716
+    g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
+    assert g.indices.dtype == np.int64
+    n, labels = csgraph.connected_components(g, directed=False)
+    assert n == 1
+    assert_array_almost_equal(labels, [0, 0])
+
+
+def test_int64_indices_directed():
+    # See https://github.com/scipy/scipy/issues/18716
+    g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
+    assert g.indices.dtype == np.int64
+    n, labels = csgraph.connected_components(g, directed=True,
+                                             connection='strong')
+    assert n == 2
+    assert_array_almost_equal(labels, [1, 0])
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py
new file mode 100644
index 0000000000000000000000000000000000000000..65f141e5b371367018a6e9985f8325850d8972da
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_conversions.py
@@ -0,0 +1,61 @@
+import numpy as np
+from numpy.testing import assert_array_almost_equal
+from scipy.sparse import csr_array
+from scipy.sparse.csgraph import csgraph_from_dense, csgraph_to_dense
+
+
+def test_csgraph_from_dense():
+    np.random.seed(1234)
+    G = np.random.random((10, 10))
+    some_nulls = (G < 0.4)
+    all_nulls = (G < 0.8)
+
+    for null_value in [0, np.nan, np.inf]:
+        G[all_nulls] = null_value
+        with np.errstate(invalid="ignore"):
+            G_csr = csgraph_from_dense(G, null_value=0)
+
+        G[all_nulls] = 0
+        assert_array_almost_equal(G, G_csr.toarray())
+
+    for null_value in [np.nan, np.inf]:
+        G[all_nulls] = 0
+        G[some_nulls] = null_value
+        with np.errstate(invalid="ignore"):
+            G_csr = csgraph_from_dense(G, null_value=0)
+
+        G[all_nulls] = 0
+        assert_array_almost_equal(G, G_csr.toarray())
+
+
+def test_csgraph_to_dense():
+    np.random.seed(1234)
+    G = np.random.random((10, 10))
+    nulls = (G < 0.8)
+    G[nulls] = np.inf
+
+    G_csr = csgraph_from_dense(G)
+
+    for null_value in [0, 10, -np.inf, np.inf]:
+        G[nulls] = null_value
+        assert_array_almost_equal(G, csgraph_to_dense(G_csr, null_value))
+
+
+def test_multiple_edges():
+    # create a random square matrix with an even number of elements
+    np.random.seed(1234)
+    X = np.random.random((10, 10))
+    Xcsr = csr_array(X)
+
+    # now double-up every other column
+    Xcsr.indices[::2] = Xcsr.indices[1::2]
+
+    # normal sparse toarray() will sum the duplicated edges
+    Xdense = Xcsr.toarray()
+    assert_array_almost_equal(Xdense[:, 1::2],
+                              X[:, ::2] + X[:, 1::2])
+
+    # csgraph_to_dense chooses the minimum of each duplicated edge
+    Xdense = csgraph_to_dense(Xcsr)
+    assert_array_almost_equal(Xdense[:, 1::2],
+                              np.minimum(X[:, ::2], X[:, 1::2]))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py
new file mode 100644
index 0000000000000000000000000000000000000000..c92eb985a1145c4b7c1777f0449bb423402f6d66
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_flow.py
@@ -0,0 +1,209 @@
+import numpy as np
+from numpy.testing import assert_array_equal
+import pytest
+
+from scipy.sparse import csr_array, csc_array, csr_matrix
+from scipy.sparse.csgraph import maximum_flow
+from scipy.sparse.csgraph._flow import (
+    _add_reverse_edges, _make_edge_pointers, _make_tails
+)
+
+methods = ['edmonds_karp', 'dinic']
+
+def test_raises_on_dense_input():
+    with pytest.raises(TypeError):
+        graph = np.array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, 1)
+        maximum_flow(graph, 0, 1, method='edmonds_karp')
+
+
+def test_raises_on_csc_input():
+    with pytest.raises(TypeError):
+        graph = csc_array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, 1)
+        maximum_flow(graph, 0, 1, method='edmonds_karp')
+
+
+def test_raises_on_floating_point_input():
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1.5], [0, 0]], dtype=np.float64)
+        maximum_flow(graph, 0, 1)
+        maximum_flow(graph, 0, 1, method='edmonds_karp')
+
+
+def test_raises_on_non_square_input():
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1, 2], [2, 1, 0]])
+        maximum_flow(graph, 0, 1)
+
+
+def test_raises_when_source_is_sink():
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, 0)
+        maximum_flow(graph, 0, 0, method='edmonds_karp')
+
+
+@pytest.mark.parametrize('method', methods)
+@pytest.mark.parametrize('source', [-1, 2, 3])
+def test_raises_when_source_is_out_of_bounds(source, method):
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1], [0, 0]])
+        maximum_flow(graph, source, 1, method=method)
+
+
+@pytest.mark.parametrize('method', methods)
+@pytest.mark.parametrize('sink', [-1, 2, 3])
+def test_raises_when_sink_is_out_of_bounds(sink, method):
+    with pytest.raises(ValueError):
+        graph = csr_array([[0, 1], [0, 0]])
+        maximum_flow(graph, 0, sink, method=method)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_simple_graph(method):
+    # This graph looks as follows:
+    #     (0) --5--> (1)
+    graph = csr_array([[0, 5], [0, 0]])
+    res = maximum_flow(graph, 0, 1, method=method)
+    assert res.flow_value == 5
+    expected_flow = np.array([[0, 5], [-5, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_return_type(method):
+    graph = csr_array([[0, 5], [0, 0]])
+    assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_array)
+    graph = csr_matrix([[0, 5], [0, 0]])
+    assert isinstance(maximum_flow(graph, 0, 1, method=method).flow, csr_matrix)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_bottle_neck_graph(method):
+    # This graph cannot use the full capacity between 0 and 1:
+    #     (0) --5--> (1) --3--> (2)
+    graph = csr_array([[0, 5, 0], [0, 0, 3], [0, 0, 0]])
+    res = maximum_flow(graph, 0, 2, method=method)
+    assert res.flow_value == 3
+    expected_flow = np.array([[0, 3, 0], [-3, 0, 3], [0, -3, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_backwards_flow(method):
+    # This example causes backwards flow between vertices 3 and 4,
+    # and so this test ensures that we handle that accordingly. See
+    #     https://stackoverflow.com/q/38843963/5085211
+    # for more information.
+    graph = csr_array([[0, 10, 0, 0, 10, 0, 0, 0],
+                       [0, 0, 10, 0, 0, 0, 0, 0],
+                       [0, 0, 0, 10, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0, 0, 0, 10],
+                       [0, 0, 0, 10, 0, 10, 0, 0],
+                       [0, 0, 0, 0, 0, 0, 10, 0],
+                       [0, 0, 0, 0, 0, 0, 0, 10],
+                       [0, 0, 0, 0, 0, 0, 0, 0]])
+    res = maximum_flow(graph, 0, 7, method=method)
+    assert res.flow_value == 20
+    expected_flow = np.array([[0, 10, 0, 0, 10, 0, 0, 0],
+                              [-10, 0, 10, 0, 0, 0, 0, 0],
+                              [0, -10, 0, 10, 0, 0, 0, 0],
+                              [0, 0, -10, 0, 0, 0, 0, 10],
+                              [-10, 0, 0, 0, 0, 10, 0, 0],
+                              [0, 0, 0, 0, -10, 0, 10, 0],
+                              [0, 0, 0, 0, 0, -10, 0, 10],
+                              [0, 0, 0, -10, 0, 0, -10, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_example_from_clrs_chapter_26_1(method):
+    # See page 659 in CLRS second edition, but note that the maximum flow
+    # we find is slightly different than the one in CLRS; we push a flow of
+    # 12 to v_1 instead of v_2.
+    graph = csr_array([[0, 16, 13, 0, 0, 0],
+                       [0, 0, 10, 12, 0, 0],
+                       [0, 4, 0, 0, 14, 0],
+                       [0, 0, 9, 0, 0, 20],
+                       [0, 0, 0, 7, 0, 4],
+                       [0, 0, 0, 0, 0, 0]])
+    res = maximum_flow(graph, 0, 5, method=method)
+    assert res.flow_value == 23
+    expected_flow = np.array([[0, 12, 11, 0, 0, 0],
+                              [-12, 0, 0, 12, 0, 0],
+                              [-11, 0, 0, 0, 11, 0],
+                              [0, -12, 0, 0, -7, 19],
+                              [0, 0, -11, 7, 0, 4],
+                              [0, 0, 0, -19, -4, 0]])
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_disconnected_graph(method):
+    # This tests the following disconnected graph:
+    #     (0) --5--> (1)    (2) --3--> (3)
+    graph = csr_array([[0, 5, 0, 0],
+                       [0, 0, 0, 0],
+                       [0, 0, 9, 3],
+                       [0, 0, 0, 0]])
+    res = maximum_flow(graph, 0, 3, method=method)
+    assert res.flow_value == 0
+    expected_flow = np.zeros((4, 4), dtype=np.int32)
+    assert_array_equal(res.flow.toarray(), expected_flow)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_add_reverse_edges_large_graph(method):
+    # Regression test for https://github.com/scipy/scipy/issues/14385
+    n = 100_000
+    indices = np.arange(1, n)
+    indptr = np.array(list(range(n)) + [n - 1])
+    data = np.ones(n - 1, dtype=np.int32)
+    graph = csr_array((data, indices, indptr), shape=(n, n))
+    res = maximum_flow(graph, 0, n - 1, method=method)
+    assert res.flow_value == 1
+    expected_flow = graph - graph.transpose()
+    assert_array_equal(res.flow.data, expected_flow.data)
+    assert_array_equal(res.flow.indices, expected_flow.indices)
+    assert_array_equal(res.flow.indptr, expected_flow.indptr)
+
+
+@pytest.mark.parametrize("a,b_data_expected", [
+    ([[]], []),
+    ([[0], [0]], []),
+    ([[1, 0, 2], [0, 0, 0], [0, 3, 0]], [1, 2, 0, 0, 3]),
+    ([[9, 8, 7], [4, 5, 6], [0, 0, 0]], [9, 8, 7, 4, 5, 6, 0, 0])])
+def test_add_reverse_edges(a, b_data_expected):
+    """Test that the reversal of the edges of the input graph works
+    as expected.
+    """
+    a = csr_array(a, dtype=np.int32, shape=(len(a), len(a)))
+    b = _add_reverse_edges(a)
+    assert_array_equal(b.data, b_data_expected)
+
+
+@pytest.mark.parametrize("a,expected", [
+    ([[]], []),
+    ([[0]], []),
+    ([[1]], [0]),
+    ([[0, 1], [10, 0]], [1, 0]),
+    ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 3, 4, 1, 2])
+])
+def test_make_edge_pointers(a, expected):
+    a = csr_array(a, dtype=np.int32)
+    rev_edge_ptr = _make_edge_pointers(a)
+    assert_array_equal(rev_edge_ptr, expected)
+
+
+@pytest.mark.parametrize("a,expected", [
+    ([[]], []),
+    ([[0]], []),
+    ([[1]], [0]),
+    ([[0, 1], [10, 0]], [0, 1]),
+    ([[1, 0, 2], [0, 0, 3], [4, 5, 0]], [0, 0, 1, 2, 2])
+])
+def test_make_tails(a, expected):
+    a = csr_array(a, dtype=np.int32)
+    tails = _make_tails(a)
+    assert_array_equal(tails, expected)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ed5e2edf92ef0cacc819fcbd06bc6d4e195cb44
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_graph_laplacian.py
@@ -0,0 +1,368 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+from pytest import raises as assert_raises
+from scipy import sparse
+
+from scipy.sparse import csgraph
+from scipy._lib._util import np_long, np_ulong
+
+
+def check_int_type(mat):
+    return np.issubdtype(mat.dtype, np.signedinteger) or np.issubdtype(
+        mat.dtype, np_ulong
+    )
+
+
+def test_laplacian_value_error():
+    for t in int, float, complex:
+        for m in ([1, 1],
+                  [[[1]]],
+                  [[1, 2, 3], [4, 5, 6]],
+                  [[1, 2], [3, 4], [5, 5]]):
+            A = np.array(m, dtype=t)
+            assert_raises(ValueError, csgraph.laplacian, A)
+
+
+def _explicit_laplacian(x, normed=False):
+    if sparse.issparse(x):
+        x = x.toarray()
+    x = np.asarray(x)
+    y = -1.0 * x
+    for j in range(y.shape[0]):
+        y[j,j] = x[j,j+1:].sum() + x[j,:j].sum()
+    if normed:
+        d = np.diag(y).copy()
+        d[d == 0] = 1.0
+        y /= d[:,None]**.5
+        y /= d[None,:]**.5
+    return y
+
+
+def _check_symmetric_graph_laplacian(mat, normed, copy=True):
+    if not hasattr(mat, 'shape'):
+        mat = eval(mat, dict(np=np, sparse=sparse))
+
+    if sparse.issparse(mat):
+        sp_mat = mat
+        mat = sp_mat.toarray()
+    else:
+        sp_mat = sparse.csr_array(mat)
+
+    mat_copy = np.copy(mat)
+    sp_mat_copy = sparse.csr_array(sp_mat, copy=True)
+
+    n_nodes = mat.shape[0]
+    explicit_laplacian = _explicit_laplacian(mat, normed=normed)
+    laplacian = csgraph.laplacian(mat, normed=normed, copy=copy)
+    sp_laplacian = csgraph.laplacian(sp_mat, normed=normed,
+                                     copy=copy)
+
+    if copy:
+        assert_allclose(mat, mat_copy)
+        _assert_allclose_sparse(sp_mat, sp_mat_copy)
+    else:
+        if not (normed and check_int_type(mat)):
+            assert_allclose(laplacian, mat)
+            if sp_mat.format == 'coo':
+                _assert_allclose_sparse(sp_laplacian, sp_mat)
+
+    assert_allclose(laplacian, sp_laplacian.toarray())
+
+    for tested in [laplacian, sp_laplacian.toarray()]:
+        if not normed:
+            assert_allclose(tested.sum(axis=0), np.zeros(n_nodes))
+        assert_allclose(tested.T, tested)
+        assert_allclose(tested, explicit_laplacian)
+
+
+def test_symmetric_graph_laplacian():
+    symmetric_mats = (
+        'np.arange(10) * np.arange(10)[:, np.newaxis]',
+        'np.ones((7, 7))',
+        'np.eye(19)',
+        'sparse.diags([1, 1], [-1, 1], shape=(4, 4))',
+        'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).toarray()',
+        'sparse.diags([1, 1], [-1, 1], shape=(4, 4)).todense()',
+        'np.vander(np.arange(4)) + np.vander(np.arange(4)).T'
+    )
+    for mat in symmetric_mats:
+        for normed in True, False:
+            for copy in True, False:
+                _check_symmetric_graph_laplacian(mat, normed, copy)
+
+
+def _assert_allclose_sparse(a, b, **kwargs):
+    # helper function that can deal with sparse matrices
+    if sparse.issparse(a):
+        a = a.toarray()
+    if sparse.issparse(b):
+        b = b.toarray()
+    assert_allclose(a, b, **kwargs)
+
+
+def _check_laplacian_dtype_none(
+    A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type
+):
+    mat = arr_type(A, dtype=dtype)
+    L, d = csgraph.laplacian(
+        mat,
+        normed=normed,
+        return_diag=True,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=None,
+    )
+    if normed and check_int_type(mat):
+        assert L.dtype == np.float64
+        assert d.dtype == np.float64
+        _assert_allclose_sparse(L, desired_L, atol=1e-12)
+        _assert_allclose_sparse(d, desired_d, atol=1e-12)
+    else:
+        assert L.dtype == dtype
+        assert d.dtype == dtype
+        desired_L = np.asarray(desired_L).astype(dtype)
+        desired_d = np.asarray(desired_d).astype(dtype)
+        _assert_allclose_sparse(L, desired_L, atol=1e-12)
+        _assert_allclose_sparse(d, desired_d, atol=1e-12)
+
+    if not copy:
+        if not (normed and check_int_type(mat)):
+            if type(mat) is np.ndarray:
+                assert_allclose(L, mat)
+            elif mat.format == "coo":
+                _assert_allclose_sparse(L, mat)
+
+
+def _check_laplacian_dtype(
+    A, desired_L, desired_d, normed, use_out_degree, copy, dtype, arr_type
+):
+    mat = arr_type(A, dtype=dtype)
+    L, d = csgraph.laplacian(
+        mat,
+        normed=normed,
+        return_diag=True,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=dtype,
+    )
+    assert L.dtype == dtype
+    assert d.dtype == dtype
+    desired_L = np.asarray(desired_L).astype(dtype)
+    desired_d = np.asarray(desired_d).astype(dtype)
+    _assert_allclose_sparse(L, desired_L, atol=1e-12)
+    _assert_allclose_sparse(d, desired_d, atol=1e-12)
+
+    if not copy:
+        if not (normed and check_int_type(mat)):
+            if type(mat) is np.ndarray:
+                assert_allclose(L, mat)
+            elif mat.format == 'coo':
+                _assert_allclose_sparse(L, mat)
+
+
+INT_DTYPES = (np.intc, np_long, np.longlong)
+REAL_DTYPES = (np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+DTYPES = INT_DTYPES + REAL_DTYPES + COMPLEX_DTYPES
+
+
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("arr_type", [np.array,
+                                      sparse.csr_matrix,
+                                      sparse.coo_matrix,
+                                      sparse.csr_array,
+                                      sparse.coo_array])
+@pytest.mark.parametrize("copy", [True, False])
+@pytest.mark.parametrize("normed", [True, False])
+@pytest.mark.parametrize("use_out_degree", [True, False])
+def test_asymmetric_laplacian(use_out_degree, normed,
+                              copy, dtype, arr_type):
+    # adjacency matrix
+    A = [[0, 1, 0],
+         [4, 2, 0],
+         [0, 0, 0]]
+    A = arr_type(np.array(A), dtype=dtype)
+    A_copy = A.copy()
+
+    if not normed and use_out_degree:
+        # Laplacian matrix using out-degree
+        L = [[1, -1, 0],
+             [-4, 4, 0],
+             [0, 0, 0]]
+        d = [1, 4, 0]
+
+    if normed and use_out_degree:
+        # normalized Laplacian matrix using out-degree
+        L = [[1, -0.5, 0],
+             [-2, 1, 0],
+             [0, 0, 0]]
+        d = [1, 2, 1]
+
+    if not normed and not use_out_degree:
+        # Laplacian matrix using in-degree
+        L = [[4, -1, 0],
+             [-4, 1, 0],
+             [0, 0, 0]]
+        d = [4, 1, 0]
+
+    if normed and not use_out_degree:
+        # normalized Laplacian matrix using in-degree
+        L = [[1, -0.5, 0],
+             [-2, 1, 0],
+             [0, 0, 0]]
+        d = [2, 1, 1]
+
+    _check_laplacian_dtype_none(
+        A,
+        L,
+        d,
+        normed=normed,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=dtype,
+        arr_type=arr_type,
+    )
+
+    _check_laplacian_dtype(
+        A_copy,
+        L,
+        d,
+        normed=normed,
+        use_out_degree=use_out_degree,
+        copy=copy,
+        dtype=dtype,
+        arr_type=arr_type,
+    )
+
+
+@pytest.mark.parametrize("fmt", ['csr', 'csc', 'coo', 'lil',
+                                 'dok', 'dia', 'bsr'])
+@pytest.mark.parametrize("normed", [True, False])
+@pytest.mark.parametrize("copy", [True, False])
+def test_sparse_formats(fmt, normed, copy):
+    mat = sparse.diags_array([1, 1], offsets=[-1, 1], shape=(4, 4), format=fmt)
+    _check_symmetric_graph_laplacian(mat, normed, copy)
+
+
+@pytest.mark.parametrize(
+    "arr_type", [np.asarray,
+                 sparse.csr_matrix,
+                 sparse.coo_matrix,
+                 sparse.csr_array,
+                 sparse.coo_array]
+)
+@pytest.mark.parametrize("form", ["array", "function", "lo"])
+def test_laplacian_symmetrized(arr_type, form):
+    # adjacency matrix
+    n = 3
+    mat = arr_type(np.arange(n * n).reshape(n, n))
+    L_in, d_in = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        form=form,
+    )
+    L_out, d_out = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        use_out_degree=True,
+        form=form,
+    )
+    Ls, ds = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        symmetrized=True,
+        form=form,
+    )
+    Ls_normed, ds_normed = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        symmetrized=True,
+        normed=True,
+        form=form,
+    )
+    mat += mat.T
+    Lss, dss = csgraph.laplacian(mat, return_diag=True, form=form)
+    Lss_normed, dss_normed = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=True,
+        form=form,
+    )
+
+    assert_allclose(ds, d_in + d_out)
+    assert_allclose(ds, dss)
+    assert_allclose(ds_normed, dss_normed)
+
+    d = {}
+    for L in ["L_in", "L_out", "Ls", "Ls_normed", "Lss", "Lss_normed"]:
+        if form == "array":
+            d[L] = eval(L)
+        else:
+            d[L] = eval(L)(np.eye(n, dtype=mat.dtype))
+
+    _assert_allclose_sparse(d["Ls"], d["L_in"] + d["L_out"].T)
+    _assert_allclose_sparse(d["Ls"], d["Lss"])
+    _assert_allclose_sparse(d["Ls_normed"], d["Lss_normed"])
+
+
+@pytest.mark.parametrize(
+    "arr_type", [np.asarray,
+                 sparse.csr_matrix,
+                 sparse.coo_matrix,
+                 sparse.csr_array,
+                 sparse.coo_array]
+)
+@pytest.mark.parametrize("dtype", DTYPES)
+@pytest.mark.parametrize("normed", [True, False])
+@pytest.mark.parametrize("symmetrized", [True, False])
+@pytest.mark.parametrize("use_out_degree", [True, False])
+@pytest.mark.parametrize("form", ["function", "lo"])
+def test_format(dtype, arr_type, normed, symmetrized, use_out_degree, form):
+    n = 3
+    mat = [[0, 1, 0], [4, 2, 0], [0, 0, 0]]
+    mat = arr_type(np.array(mat), dtype=dtype)
+    Lo, do = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=normed,
+        symmetrized=symmetrized,
+        use_out_degree=use_out_degree,
+        dtype=dtype,
+    )
+    La, da = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=normed,
+        symmetrized=symmetrized,
+        use_out_degree=use_out_degree,
+        dtype=dtype,
+        form="array",
+    )
+    assert_allclose(do, da)
+    _assert_allclose_sparse(Lo, La)
+
+    L, d = csgraph.laplacian(
+        mat,
+        return_diag=True,
+        normed=normed,
+        symmetrized=symmetrized,
+        use_out_degree=use_out_degree,
+        dtype=dtype,
+        form=form,
+    )
+    assert_allclose(d, do)
+    assert d.dtype == dtype
+    Lm = L(np.eye(n, dtype=mat.dtype)).astype(dtype)
+    _assert_allclose_sparse(Lm, Lo, rtol=2e-7, atol=2e-7)
+    x = np.arange(6).reshape(3, 2)
+    if not (normed and dtype in INT_DTYPES):
+        assert_allclose(L(x), Lo @ x)
+    else:
+        # Normalized Lo is casted to integer, but L() is not
+        pass
+
+
+def test_format_error_message():
+    with pytest.raises(ValueError, match="Invalid form: 'toto'"):
+        _ = csgraph.laplacian(np.eye(1), form='toto')
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..8477861d3e563c43379c615ec0913f47a4349abd
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_matching.py
@@ -0,0 +1,295 @@
+from itertools import product
+
+import numpy as np
+from numpy.testing import assert_array_equal, assert_equal
+import pytest
+
+from scipy.sparse import csr_array, diags_array
+from scipy.sparse.csgraph import (
+    maximum_bipartite_matching, min_weight_full_bipartite_matching
+)
+
+
+def test_maximum_bipartite_matching_raises_on_dense_input():
+    with pytest.raises(TypeError):
+        graph = np.array([[0, 1], [0, 0]])
+        maximum_bipartite_matching(graph)
+
+
+def test_maximum_bipartite_matching_empty_graph():
+    graph = csr_array((0, 0))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    expected_matching = np.array([])
+    assert_array_equal(expected_matching, x)
+    assert_array_equal(expected_matching, y)
+
+
+def test_maximum_bipartite_matching_empty_left_partition():
+    graph = csr_array((2, 0))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    assert_array_equal(np.array([]), x)
+    assert_array_equal(np.array([-1, -1]), y)
+
+
+def test_maximum_bipartite_matching_empty_right_partition():
+    graph = csr_array((0, 3))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    assert_array_equal(np.array([-1, -1, -1]), x)
+    assert_array_equal(np.array([]), y)
+
+
+def test_maximum_bipartite_matching_graph_with_no_edges():
+    graph = csr_array((2, 2))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    assert_array_equal(np.array([-1, -1]), x)
+    assert_array_equal(np.array([-1, -1]), y)
+
+
+def test_maximum_bipartite_matching_graph_that_causes_augmentation():
+    # In this graph, column 1 is initially assigned to row 1, but it should be
+    # reassigned to make room for row 2.
+    graph = csr_array([[1, 1], [1, 0]])
+    x = maximum_bipartite_matching(graph, perm_type='column')
+    y = maximum_bipartite_matching(graph, perm_type='row')
+    expected_matching = np.array([1, 0])
+    assert_array_equal(expected_matching, x)
+    assert_array_equal(expected_matching, y)
+
+
+def test_maximum_bipartite_matching_graph_with_more_rows_than_columns():
+    graph = csr_array([[1, 1], [1, 0], [0, 1]])
+    x = maximum_bipartite_matching(graph, perm_type='column')
+    y = maximum_bipartite_matching(graph, perm_type='row')
+    assert_array_equal(np.array([0, -1, 1]), x)
+    assert_array_equal(np.array([0, 2]), y)
+
+
+def test_maximum_bipartite_matching_graph_with_more_columns_than_rows():
+    graph = csr_array([[1, 1, 0], [0, 0, 1]])
+    x = maximum_bipartite_matching(graph, perm_type='column')
+    y = maximum_bipartite_matching(graph, perm_type='row')
+    assert_array_equal(np.array([0, 2]), x)
+    assert_array_equal(np.array([0, -1, 1]), y)
+
+
+def test_maximum_bipartite_matching_explicit_zeros_count_as_edges():
+    data = [0, 0]
+    indices = [1, 0]
+    indptr = [0, 1, 2]
+    graph = csr_array((data, indices, indptr), shape=(2, 2))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    expected_matching = np.array([1, 0])
+    assert_array_equal(expected_matching, x)
+    assert_array_equal(expected_matching, y)
+
+
+def test_maximum_bipartite_matching_feasibility_of_result():
+    # This is a regression test for GitHub issue #11458
+    data = np.ones(50, dtype=int)
+    indices = [11, 12, 19, 22, 23, 5, 22, 3, 8, 10, 5, 6, 11, 12, 13, 5, 13,
+               14, 20, 22, 3, 15, 3, 13, 14, 11, 12, 19, 22, 23, 5, 22, 3, 8,
+               10, 5, 6, 11, 12, 13, 5, 13, 14, 20, 22, 3, 15, 3, 13, 14]
+    indptr = [0, 5, 7, 10, 10, 15, 20, 22, 22, 23, 25, 30, 32, 35, 35, 40, 45,
+              47, 47, 48, 50]
+    graph = csr_array((data, indices, indptr), shape=(20, 25))
+    x = maximum_bipartite_matching(graph, perm_type='row')
+    y = maximum_bipartite_matching(graph, perm_type='column')
+    assert (x != -1).sum() == 13
+    assert (y != -1).sum() == 13
+    # Ensure that each element of the matching is in fact an edge in the graph.
+    for u, v in zip(range(graph.shape[0]), y):
+        if v != -1:
+            assert graph[u, v]
+    for u, v in zip(x, range(graph.shape[1])):
+        if u != -1:
+            assert graph[u, v]
+
+
+def test_matching_large_random_graph_with_one_edge_incident_to_each_vertex():
+    np.random.seed(42)
+    A = diags_array(np.ones(25), offsets=0, format='csr')
+    rand_perm = np.random.permutation(25)
+    rand_perm2 = np.random.permutation(25)
+
+    Rrow = np.arange(25)
+    Rcol = rand_perm
+    Rdata = np.ones(25, dtype=int)
+    Rmat = csr_array((Rdata, (Rrow, Rcol)))
+
+    Crow = rand_perm2
+    Ccol = np.arange(25)
+    Cdata = np.ones(25, dtype=int)
+    Cmat = csr_array((Cdata, (Crow, Ccol)))
+    # Randomly permute identity matrix
+    B = Rmat @ A @ Cmat
+
+    # Row permute
+    perm = maximum_bipartite_matching(B, perm_type='row')
+    Rrow = np.arange(25)
+    Rcol = perm
+    Rdata = np.ones(25, dtype=int)
+    Rmat = csr_array((Rdata, (Rrow, Rcol)))
+    C1 = Rmat @ B
+
+    # Column permute
+    perm2 = maximum_bipartite_matching(B, perm_type='column')
+    Crow = perm2
+    Ccol = np.arange(25)
+    Cdata = np.ones(25, dtype=int)
+    Cmat = csr_array((Cdata, (Crow, Ccol)))
+    C2 = B @ Cmat
+
+    # Should get identity matrix back
+    assert_equal(any(C1.diagonal() == 0), False)
+    assert_equal(any(C2.diagonal() == 0), False)
+
+
+@pytest.mark.parametrize('num_rows,num_cols', [(0, 0), (2, 0), (0, 3)])
+def test_min_weight_full_matching_trivial_graph(num_rows, num_cols):
+    biadjacency = csr_array((num_cols, num_rows))
+    row_ind, col_ind = min_weight_full_bipartite_matching(biadjacency)
+    assert len(row_ind) == 0
+    assert len(col_ind) == 0
+
+
+@pytest.mark.parametrize('biadjacency',
+                         [
+                            [[1, 1, 1], [1, 0, 0], [1, 0, 0]],
+                            [[1, 1, 1], [0, 0, 1], [0, 0, 1]],
+                            [[1, 0, 0, 1], [1, 1, 0, 1], [0, 0, 0, 0]],
+                            [[1, 0, 0], [2, 0, 0]],
+                            [[0, 1, 0], [0, 2, 0]],
+                            [[1, 0], [2, 0], [5, 0]]
+                         ])
+def test_min_weight_full_matching_infeasible_problems(biadjacency):
+    with pytest.raises(ValueError):
+        min_weight_full_bipartite_matching(csr_array(biadjacency))
+
+
+def test_min_weight_full_matching_large_infeasible():
+    # Regression test for GitHub issue #17269
+    a = np.asarray([
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.001],
+        [0.0, 0.11687445, 0.0, 0.0, 0.01319788, 0.07509257, 0.0,
+         0.0, 0.0, 0.74228317, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.81087935, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.8408466, 0.0, 0.0, 0.0, 0.0, 0.01194389,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.82994211, 0.0, 0.0, 0.0, 0.11468516, 0.0, 0.0, 0.0,
+         0.11173505, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.0, 0.0],
+        [0.18796507, 0.0, 0.04002318, 0.0, 0.0, 0.0, 0.0, 0.0, 0.75883335,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.71545464, 0.0, 0.0, 0.0, 0.0, 0.0, 0.02748488,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.78470564, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.14829198,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.10870609, 0.0, 0.0, 0.0, 0.8918677, 0.0, 0.0, 0.0, 0.06306644,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+         0.63844085, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.7442354, 0.0, 0.0, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09850549, 0.0, 0.0, 0.18638258,
+         0.2769244, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.73182464, 0.0, 0.0, 0.46443561,
+         0.38589284, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+        [0.29510278, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09666032, 0.0,
+         0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
+        ])
+    with pytest.raises(ValueError, match='no full matching exists'):
+        min_weight_full_bipartite_matching(csr_array(a))
+
+
+@pytest.mark.thread_unsafe
+def test_explicit_zero_causes_warning():
+    with pytest.warns(UserWarning):
+        biadjacency = csr_array(((2, 0, 3), (0, 1, 1), (0, 2, 3)))
+        min_weight_full_bipartite_matching(biadjacency)
+
+
+# General test for linear sum assignment solvers to make it possible to rely
+# on the same tests for scipy.optimize.linear_sum_assignment.
+def linear_sum_assignment_assertions(
+    solver, array_type, sign, test_case
+):
+    cost_matrix, expected_cost = test_case
+    maximize = sign == -1
+    cost_matrix = sign * array_type(cost_matrix)
+    expected_cost = sign * np.array(expected_cost)
+
+    row_ind, col_ind = solver(cost_matrix, maximize=maximize)
+    assert_array_equal(row_ind, np.sort(row_ind))
+    assert_array_equal(expected_cost,
+                       np.array(cost_matrix[row_ind, col_ind]).flatten())
+
+    cost_matrix = cost_matrix.T
+    row_ind, col_ind = solver(cost_matrix, maximize=maximize)
+    assert_array_equal(row_ind, np.sort(row_ind))
+    assert_array_equal(np.sort(expected_cost),
+                       np.sort(np.array(
+                           cost_matrix[row_ind, col_ind])).flatten())
+
+
+linear_sum_assignment_test_cases = product(
+    [-1, 1],
+    [
+        # Square
+        ([[400, 150, 400],
+          [400, 450, 600],
+          [300, 225, 300]],
+         [150, 400, 300]),
+
+        # Rectangular variant
+        ([[400, 150, 400, 1],
+          [400, 450, 600, 2],
+          [300, 225, 300, 3]],
+         [150, 2, 300]),
+
+        ([[10, 10, 8],
+          [9, 8, 1],
+          [9, 7, 4]],
+         [10, 1, 7]),
+
+        # Square
+        ([[10, 10, 8, 11],
+          [9, 8, 1, 1],
+          [9, 7, 4, 10]],
+         [10, 1, 4]),
+
+        # Rectangular variant
+        ([[10, float("inf"), float("inf")],
+          [float("inf"), float("inf"), 1],
+          [float("inf"), 7, float("inf")]],
+         [10, 1, 7])
+    ])
+
+
+@pytest.mark.parametrize('sign,test_case', linear_sum_assignment_test_cases)
+def test_min_weight_full_matching_small_inputs(sign, test_case):
+    linear_sum_assignment_assertions(
+        min_weight_full_bipartite_matching, csr_array, sign, test_case)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..1476c29a3ba97869c6c38be4d717641a494c1183
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_pydata_sparse.py
@@ -0,0 +1,194 @@
+import pytest
+
+import numpy as np
+import scipy.sparse as sp
+import scipy.sparse.csgraph as spgraph
+from scipy._lib import _pep440
+
+from numpy.testing import assert_equal
+
+try:
+    import sparse
+except Exception:
+    sparse = None
+
+pytestmark = pytest.mark.skipif(sparse is None,
+                                reason="pydata/sparse not installed")
+
+
+msg = "pydata/sparse (0.15.1) does not implement necessary operations"
+
+
+sparse_params = (pytest.param("COO"),
+                 pytest.param("DOK", marks=[pytest.mark.xfail(reason=msg)]))
+
+
+def check_sparse_version(min_ver):
+    if sparse is None:
+        return pytest.mark.skip(reason="sparse is not installed")
+    return pytest.mark.skipif(
+        _pep440.parse(sparse.__version__) < _pep440.Version(min_ver),
+        reason=f"sparse version >= {min_ver} required"
+    )
+
+
+@pytest.fixture(params=sparse_params)
+def sparse_cls(request):
+    return getattr(sparse, request.param)
+
+
+@pytest.fixture
+def graphs(sparse_cls):
+    graph = [
+        [0, 1, 1, 0, 0],
+        [0, 0, 1, 0, 0],
+        [0, 0, 0, 0, 0],
+        [0, 0, 0, 0, 1],
+        [0, 0, 0, 0, 0],
+    ]
+    A_dense = np.array(graph)
+    A_sparse = sparse_cls(A_dense)
+    return A_dense, A_sparse
+
+
+@pytest.mark.parametrize(
+    "func",
+    [
+        spgraph.shortest_path,
+        spgraph.dijkstra,
+        spgraph.floyd_warshall,
+        spgraph.bellman_ford,
+        spgraph.johnson,
+        spgraph.reverse_cuthill_mckee,
+        spgraph.maximum_bipartite_matching,
+        spgraph.structural_rank,
+    ]
+)
+def test_csgraph_equiv(func, graphs):
+    A_dense, A_sparse = graphs
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+    assert_equal(actual, desired)
+
+
+def test_connected_components(graphs):
+    A_dense, A_sparse = graphs
+    func = spgraph.connected_components
+
+    actual_comp, actual_labels = func(A_sparse)
+    desired_comp, desired_labels, = func(sp.csc_array(A_dense))
+
+    assert actual_comp == desired_comp
+    assert_equal(actual_labels, desired_labels)
+
+
+def test_laplacian(graphs):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+    func = spgraph.laplacian
+
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+
+    assert isinstance(actual, sparse_cls)
+
+    assert_equal(actual.todense(), desired.todense())
+
+
+@pytest.mark.parametrize(
+    "func", [spgraph.breadth_first_order, spgraph.depth_first_order]
+)
+def test_order_search(graphs, func):
+    A_dense, A_sparse = graphs
+
+    actual = func(A_sparse, 0)
+    desired = func(sp.csc_array(A_dense), 0)
+
+    assert_equal(actual, desired)
+
+
+@pytest.mark.parametrize(
+    "func", [spgraph.breadth_first_tree, spgraph.depth_first_tree]
+)
+def test_tree_search(graphs, func):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+
+    actual = func(A_sparse, 0)
+    desired = func(sp.csc_array(A_dense), 0)
+
+    assert isinstance(actual, sparse_cls)
+
+    assert_equal(actual.todense(), desired.todense())
+
+
+def test_minimum_spanning_tree(graphs):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+    func = spgraph.minimum_spanning_tree
+
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+
+    assert isinstance(actual, sparse_cls)
+
+    assert_equal(actual.todense(), desired.todense())
+
+
+def test_maximum_flow(graphs):
+    A_dense, A_sparse = graphs
+    sparse_cls = type(A_sparse)
+    func = spgraph.maximum_flow
+
+    actual = func(A_sparse, 0, 2)
+    desired = func(sp.csr_array(A_dense), 0, 2)
+
+    assert actual.flow_value == desired.flow_value
+    assert isinstance(actual.flow, sparse_cls)
+
+    assert_equal(actual.flow.todense(), desired.flow.todense())
+
+
+def test_min_weight_full_bipartite_matching(graphs):
+    A_dense, A_sparse = graphs
+    func = spgraph.min_weight_full_bipartite_matching
+
+    actual = func(A_sparse[0:2, 1:3])
+    desired = func(sp.csc_array(A_dense)[0:2, 1:3])
+
+    assert_equal(actual, desired)
+
+
+@check_sparse_version("0.15.4")
+@pytest.mark.parametrize(
+    "func",
+    [
+        spgraph.shortest_path,
+        spgraph.dijkstra,
+        spgraph.floyd_warshall,
+        spgraph.bellman_ford,
+        spgraph.johnson,
+        spgraph.minimum_spanning_tree,
+    ]
+)
+@pytest.mark.parametrize(
+    "fill_value, comp_func",
+    [(np.inf, np.isposinf), (np.nan, np.isnan)],
+)
+def test_nonzero_fill_value(graphs, func, fill_value, comp_func):
+    A_dense, A_sparse = graphs
+    A_sparse = A_sparse.astype(float)
+    A_sparse.fill_value = fill_value
+    sparse_cls = type(A_sparse)
+
+    actual = func(A_sparse)
+    desired = func(sp.csc_array(A_dense))
+
+    if func == spgraph.minimum_spanning_tree:
+        assert isinstance(actual, sparse_cls)
+        assert comp_func(actual.fill_value)
+        actual = actual.todense()
+        actual[comp_func(actual)] = 0.0
+        assert_equal(actual, desired.todense())
+    else:
+        assert_equal(actual, desired)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py
new file mode 100644
index 0000000000000000000000000000000000000000..add76cdc29c39c079f386a6ca73075bb90b0a6e8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_reordering.py
@@ -0,0 +1,70 @@
+import numpy as np
+from numpy.testing import assert_equal
+from scipy.sparse.csgraph import reverse_cuthill_mckee, structural_rank
+from scipy.sparse import csc_array, csr_array, coo_array
+
+
+def test_graph_reverse_cuthill_mckee():
+    A = np.array([[1, 0, 0, 0, 1, 0, 0, 0],
+                [0, 1, 1, 0, 0, 1, 0, 1],
+                [0, 1, 1, 0, 1, 0, 0, 0],
+                [0, 0, 0, 1, 0, 0, 1, 0],
+                [1, 0, 1, 0, 1, 0, 0, 0],
+                [0, 1, 0, 0, 0, 1, 0, 1],
+                [0, 0, 0, 1, 0, 0, 1, 0],
+                [0, 1, 0, 0, 0, 1, 0, 1]], dtype=int)
+
+    graph = csr_array(A)
+    perm = reverse_cuthill_mckee(graph)
+    correct_perm = np.array([6, 3, 7, 5, 1, 2, 4, 0])
+    assert_equal(perm, correct_perm)
+
+    # Test int64 indices input
+    graph.indices = graph.indices.astype('int64')
+    graph.indptr = graph.indptr.astype('int64')
+    perm = reverse_cuthill_mckee(graph, True)
+    assert_equal(perm, correct_perm)
+
+
+def test_graph_reverse_cuthill_mckee_ordering():
+    data = np.ones(63,dtype=int)
+    rows = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2,
+                2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5,
+                6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9,
+                9, 10, 10, 10, 10, 10, 11, 11, 11, 11,
+                12, 12, 12, 13, 13, 13, 13, 14, 14, 14,
+                14, 15, 15, 15, 15, 15])
+    cols = np.array([0, 2, 5, 8, 10, 1, 3, 9, 11, 0, 2,
+                7, 10, 1, 3, 11, 4, 6, 12, 14, 0, 7, 13,
+                15, 4, 6, 14, 2, 5, 7, 15, 0, 8, 10, 13,
+                1, 9, 11, 0, 2, 8, 10, 15, 1, 3, 9, 11,
+                4, 12, 14, 5, 8, 13, 15, 4, 6, 12, 14,
+                5, 7, 10, 13, 15])
+    graph = csr_array((data, (rows,cols)))
+    perm = reverse_cuthill_mckee(graph)
+    correct_perm = np.array([12, 14, 4, 6, 10, 8, 2, 15,
+                0, 13, 7, 5, 9, 11, 1, 3])
+    assert_equal(perm, correct_perm)
+
+
+def test_graph_structural_rank():
+    # Test square matrix #1
+    A = csc_array([[1, 1, 0],
+                   [1, 0, 1],
+                   [0, 1, 0]])
+    assert_equal(structural_rank(A), 3)
+
+    # Test square matrix #2
+    rows = np.array([0,0,0,0,0,1,1,2,2,3,3,3,3,3,3,4,4,5,5,6,6,7,7])
+    cols = np.array([0,1,2,3,4,2,5,2,6,0,1,3,5,6,7,4,5,5,6,2,6,2,4])
+    data = np.ones_like(rows)
+    B = coo_array((data,(rows,cols)), shape=(8,8))
+    assert_equal(structural_rank(B), 6)
+
+    #Test non-square matrix
+    C = csc_array([[1, 0, 2, 0],
+                   [2, 0, 4, 0]])
+    assert_equal(structural_rank(C), 2)
+
+    #Test tall matrix
+    assert_equal(structural_rank(C.T), 2)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba50f760e750ce1dbdec3624c2ab985fca1af7d1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_shortest_path.py
@@ -0,0 +1,484 @@
+from io import StringIO
+import warnings
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_allclose
+from pytest import raises as assert_raises
+from scipy.sparse.csgraph import (shortest_path, dijkstra, johnson,
+                                  bellman_ford, construct_dist_matrix, yen,
+                                  NegativeCycleError)
+import scipy.sparse
+from scipy.io import mmread
+import pytest
+
+directed_G = np.array([[0, 3, 3, 0, 0],
+                       [0, 0, 0, 2, 4],
+                       [0, 0, 0, 0, 0],
+                       [1, 0, 0, 0, 0],
+                       [2, 0, 0, 2, 0]], dtype=float)
+
+undirected_G = np.array([[0, 3, 3, 1, 2],
+                         [3, 0, 0, 2, 4],
+                         [3, 0, 0, 0, 0],
+                         [1, 2, 0, 0, 2],
+                         [2, 4, 0, 2, 0]], dtype=float)
+
+unweighted_G = (directed_G > 0).astype(float)
+
+directed_SP = [[0, 3, 3, 5, 7],
+               [3, 0, 6, 2, 4],
+               [np.inf, np.inf, 0, np.inf, np.inf],
+               [1, 4, 4, 0, 8],
+               [2, 5, 5, 2, 0]]
+
+directed_2SP_0_to_3 = [[-9999, 0, -9999, 1, -9999],
+                       [-9999, 0, -9999, 4, 1]]
+
+directed_sparse_zero_G = scipy.sparse.csr_array(
+    (
+        [0, 1, 2, 3, 1],
+        ([0, 1, 2, 3, 4], [1, 2, 0, 4, 3]),
+    ),
+    shape=(5, 5),
+)
+
+directed_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf],
+                      [3, 0, 1, np.inf, np.inf],
+                      [2, 2, 0, np.inf, np.inf],
+                      [np.inf, np.inf, np.inf, 0, 3],
+                      [np.inf, np.inf, np.inf, 1, 0]]
+
+undirected_sparse_zero_G = scipy.sparse.csr_array(
+    (
+        [0, 0, 1, 1, 2, 2, 1, 1],
+        ([0, 1, 1, 2, 2, 0, 3, 4], [1, 0, 2, 1, 0, 2, 4, 3])
+    ),
+    shape=(5, 5),
+)
+
+undirected_sparse_zero_SP = [[0, 0, 1, np.inf, np.inf],
+                        [0, 0, 1, np.inf, np.inf],
+                        [1, 1, 0, np.inf, np.inf],
+                        [np.inf, np.inf, np.inf, 0, 1],
+                        [np.inf, np.inf, np.inf, 1, 0]]
+
+directed_pred = np.array([[-9999, 0, 0, 1, 1],
+                          [3, -9999, 0, 1, 1],
+                          [-9999, -9999, -9999, -9999, -9999],
+                          [3, 0, 0, -9999, 1],
+                          [4, 0, 0, 4, -9999]], dtype=float)
+
+undirected_SP = np.array([[0, 3, 3, 1, 2],
+                          [3, 0, 6, 2, 4],
+                          [3, 6, 0, 4, 5],
+                          [1, 2, 4, 0, 2],
+                          [2, 4, 5, 2, 0]], dtype=float)
+
+undirected_SP_limit_2 = np.array([[0, np.inf, np.inf, 1, 2],
+                                  [np.inf, 0, np.inf, 2, np.inf],
+                                  [np.inf, np.inf, 0, np.inf, np.inf],
+                                  [1, 2, np.inf, 0, 2],
+                                  [2, np.inf, np.inf, 2, 0]], dtype=float)
+
+undirected_SP_limit_0 = np.ones((5, 5), dtype=float) - np.eye(5)
+undirected_SP_limit_0[undirected_SP_limit_0 > 0] = np.inf
+
+undirected_pred = np.array([[-9999, 0, 0, 0, 0],
+                            [1, -9999, 0, 1, 1],
+                            [2, 0, -9999, 0, 0],
+                            [3, 3, 0, -9999, 3],
+                            [4, 4, 0, 4, -9999]], dtype=float)
+
+directed_negative_weighted_G = np.array([[0, 0, 0],
+                                         [-1, 0, 0],
+                                         [0, -1, 0]], dtype=float)
+
+directed_negative_weighted_SP = np.array([[0, np.inf, np.inf],
+                                          [-1, 0, np.inf],
+                                          [-2, -1, 0]], dtype=float)
+
+methods = ['auto', 'FW', 'D', 'BF', 'J']
+
+
+def test_dijkstra_limit():
+    limits = [0, 2, np.inf]
+    results = [undirected_SP_limit_0,
+               undirected_SP_limit_2,
+               undirected_SP]
+
+    def check(limit, result):
+        SP = dijkstra(undirected_G, directed=False, limit=limit)
+        assert_array_almost_equal(SP, result)
+
+    for limit, result in zip(limits, results):
+        check(limit, result)
+
+
+def test_directed():
+    def check(method):
+        SP = shortest_path(directed_G, method=method, directed=True,
+                           overwrite=False)
+        assert_array_almost_equal(SP, directed_SP)
+
+    for method in methods:
+        check(method)
+
+
+def test_undirected():
+    def check(method, directed_in):
+        if directed_in:
+            SP1 = shortest_path(directed_G, method=method, directed=False,
+                                overwrite=False)
+            assert_array_almost_equal(SP1, undirected_SP)
+        else:
+            SP2 = shortest_path(undirected_G, method=method, directed=True,
+                                overwrite=False)
+            assert_array_almost_equal(SP2, undirected_SP)
+
+    for method in methods:
+        for directed_in in (True, False):
+            check(method, directed_in)
+
+
+def test_directed_sparse_zero():
+    # test directed sparse graph with zero-weight edge and two connected components
+    def check(method):
+        SP = shortest_path(directed_sparse_zero_G, method=method, directed=True,
+                           overwrite=False)
+        assert_array_almost_equal(SP, directed_sparse_zero_SP)
+
+    for method in methods:
+        check(method)
+
+
+def test_undirected_sparse_zero():
+    def check(method, directed_in):
+        if directed_in:
+            SP1 = shortest_path(directed_sparse_zero_G, method=method, directed=False,
+                                overwrite=False)
+            assert_array_almost_equal(SP1, undirected_sparse_zero_SP)
+        else:
+            SP2 = shortest_path(undirected_sparse_zero_G, method=method, directed=True,
+                                overwrite=False)
+            assert_array_almost_equal(SP2, undirected_sparse_zero_SP)
+
+    for method in methods:
+        for directed_in in (True, False):
+            check(method, directed_in)
+
+
+@pytest.mark.parametrize('directed, SP_ans',
+                         ((True, directed_SP),
+                          (False, undirected_SP)))
+@pytest.mark.parametrize('indices', ([0, 2, 4], [0, 4], [3, 4], [0, 0]))
+def test_dijkstra_indices_min_only(directed, SP_ans, indices):
+    SP_ans = np.array(SP_ans)
+    indices = np.array(indices, dtype=np.int64)
+    min_ind_ans = indices[np.argmin(SP_ans[indices, :], axis=0)]
+    min_d_ans = np.zeros(SP_ans.shape[0], SP_ans.dtype)
+    for k in range(SP_ans.shape[0]):
+        min_d_ans[k] = SP_ans[min_ind_ans[k], k]
+    min_ind_ans[np.isinf(min_d_ans)] = -9999
+
+    SP, pred, sources = dijkstra(directed_G,
+                                 directed=directed,
+                                 indices=indices,
+                                 min_only=True,
+                                 return_predecessors=True)
+    assert_array_almost_equal(SP, min_d_ans)
+    assert_array_equal(min_ind_ans, sources)
+    SP = dijkstra(directed_G,
+                  directed=directed,
+                  indices=indices,
+                  min_only=True,
+                  return_predecessors=False)
+    assert_array_almost_equal(SP, min_d_ans)
+
+
+@pytest.mark.parametrize('n', (10, 100, 1000))
+def test_dijkstra_min_only_random(n):
+    rng = np.random.default_rng(7345782358920239234)
+    data = scipy.sparse.random_array((n, n), density=0.5, format='lil',
+                                     rng=rng, dtype=np.float64)
+    data.setdiag(np.zeros(n, dtype=np.bool_))
+    # choose some random vertices
+    v = np.arange(n)
+    rng.shuffle(v)
+    indices = v[:int(n*.1)]
+    ds, pred, sources = dijkstra(data,
+                                 directed=True,
+                                 indices=indices,
+                                 min_only=True,
+                                 return_predecessors=True)
+    for k in range(n):
+        p = pred[k]
+        s = sources[k]
+        while p != -9999:
+            assert sources[p] == s
+            p = pred[p]
+
+
+def test_dijkstra_random():
+    # reproduces the hang observed in gh-17782
+    n = 10
+    indices = [0, 4, 4, 5, 7, 9, 0, 6, 2, 3, 7, 9, 1, 2, 9, 2, 5, 6]
+    indptr = [0, 0, 2, 5, 6, 7, 8, 12, 15, 18, 18]
+    data = [0.33629, 0.40458, 0.47493, 0.42757, 0.11497, 0.91653, 0.69084,
+            0.64979, 0.62555, 0.743, 0.01724, 0.99945, 0.31095, 0.15557,
+            0.02439, 0.65814, 0.23478, 0.24072]
+    graph = scipy.sparse.csr_array((data, indices, indptr), shape=(n, n))
+    dijkstra(graph, directed=True, return_predecessors=True)
+
+
+def test_gh_17782_segfault():
+    text = """%%MatrixMarket matrix coordinate real general
+                84 84 22
+                2 1 4.699999809265137e+00
+                6 14 1.199999973177910e-01
+                9 6 1.199999973177910e-01
+                10 16 2.012000083923340e+01
+                11 10 1.422000026702881e+01
+                12 1 9.645999908447266e+01
+                13 18 2.012000083923340e+01
+                14 13 4.679999828338623e+00
+                15 11 1.199999973177910e-01
+                16 12 1.199999973177910e-01
+                18 15 1.199999973177910e-01
+                32 2 2.299999952316284e+00
+                33 20 6.000000000000000e+00
+                33 32 5.000000000000000e+00
+                36 9 3.720000028610229e+00
+                36 37 3.720000028610229e+00
+                36 38 3.720000028610229e+00
+                37 44 8.159999847412109e+00
+                38 32 7.903999328613281e+01
+                43 20 2.400000000000000e+01
+                43 33 4.000000000000000e+00
+                44 43 6.028000259399414e+01
+    """
+    data = mmread(StringIO(text), spmatrix=False)
+    dijkstra(data, directed=True, return_predecessors=True)
+
+
+def test_shortest_path_indices():
+    indices = np.arange(4)
+
+    def check(func, indshape):
+        outshape = indshape + (5,)
+        SP = func(directed_G, directed=False,
+                  indices=indices.reshape(indshape))
+        assert_array_almost_equal(SP, undirected_SP[indices].reshape(outshape))
+
+    for indshape in [(4,), (4, 1), (2, 2)]:
+        for func in (dijkstra, bellman_ford, johnson, shortest_path):
+            check(func, indshape)
+
+    assert_raises(ValueError, shortest_path, directed_G, method='FW',
+                  indices=indices)
+
+
+def test_predecessors():
+    SP_res = {True: directed_SP,
+              False: undirected_SP}
+    pred_res = {True: directed_pred,
+                False: undirected_pred}
+
+    def check(method, directed):
+        SP, pred = shortest_path(directed_G, method, directed=directed,
+                                 overwrite=False,
+                                 return_predecessors=True)
+        assert_array_almost_equal(SP, SP_res[directed])
+        assert_array_almost_equal(pred, pred_res[directed])
+
+    for method in methods:
+        for directed in (True, False):
+            check(method, directed)
+
+
+def test_construct_shortest_path():
+    def check(method, directed):
+        SP1, pred = shortest_path(directed_G,
+                                  directed=directed,
+                                  overwrite=False,
+                                  return_predecessors=True)
+        SP2 = construct_dist_matrix(directed_G, pred, directed=directed)
+        assert_array_almost_equal(SP1, SP2)
+
+    for method in methods:
+        for directed in (True, False):
+            check(method, directed)
+
+
+def test_unweighted_path():
+    def check(method, directed):
+        SP1 = shortest_path(directed_G,
+                            directed=directed,
+                            overwrite=False,
+                            unweighted=True)
+        SP2 = shortest_path(unweighted_G,
+                            directed=directed,
+                            overwrite=False,
+                            unweighted=False)
+        assert_array_almost_equal(SP1, SP2)
+
+    for method in methods:
+        for directed in (True, False):
+            check(method, directed)
+
+
+def test_negative_cycles():
+    # create a small graph with a negative cycle
+    graph = np.ones([5, 5])
+    graph.flat[::6] = 0
+    graph[1, 2] = -2
+
+    def check(method, directed):
+        assert_raises(NegativeCycleError, shortest_path, graph, method,
+                      directed)
+
+    for directed in (True, False):
+        for method in ['FW', 'J', 'BF']:
+            check(method, directed)
+
+        assert_raises(NegativeCycleError, yen, graph, 0, 1, 1,
+                      directed=directed)
+
+
+@pytest.mark.parametrize("method", ['FW', 'J', 'BF'])
+def test_negative_weights(method):
+    SP = shortest_path(directed_negative_weighted_G, method, directed=True)
+    assert_allclose(SP, directed_negative_weighted_SP, atol=1e-10)
+
+
+def test_masked_input():
+    np.ma.masked_equal(directed_G, 0)
+
+    def check(method):
+        SP = shortest_path(directed_G, method=method, directed=True,
+                           overwrite=False)
+        assert_array_almost_equal(SP, directed_SP)
+
+    for method in methods:
+        check(method)
+
+
+def test_overwrite():
+    G = np.array([[0, 3, 3, 1, 2],
+                  [3, 0, 0, 2, 4],
+                  [3, 0, 0, 0, 0],
+                  [1, 2, 0, 0, 2],
+                  [2, 4, 0, 2, 0]], dtype=float)
+    foo = G.copy()
+    shortest_path(foo, overwrite=False)
+    assert_array_equal(foo, G)
+
+
+@pytest.mark.parametrize('method', methods)
+def test_buffer(method):
+    # Smoke test that sparse matrices with read-only buffers (e.g., those from
+    # joblib workers) do not cause::
+    #
+    #     ValueError: buffer source array is read-only
+    #
+    G = scipy.sparse.csr_array([[1.]])
+    G.data.flags['WRITEABLE'] = False
+    shortest_path(G, method=method)
+
+
+def test_NaN_warnings():
+    with warnings.catch_warnings(record=True) as record:
+        shortest_path(np.array([[0, 1], [np.nan, 0]]))
+    for r in record:
+        assert r.category is not RuntimeWarning
+
+
+def test_sparse_matrices():
+    # Test that using lil,csr and csc sparse matrix do not cause error
+    G_dense = np.array([[0, 3, 0, 0, 0],
+                        [0, 0, -1, 0, 0],
+                        [0, 0, 0, 2, 0],
+                        [0, 0, 0, 0, 4],
+                        [0, 0, 0, 0, 0]], dtype=float)
+    SP = shortest_path(G_dense)
+    G_csr = scipy.sparse.csr_array(G_dense)
+    G_csc = scipy.sparse.csc_array(G_dense)
+    G_lil = scipy.sparse.lil_array(G_dense)
+    assert_array_almost_equal(SP, shortest_path(G_csr))
+    assert_array_almost_equal(SP, shortest_path(G_csc))
+    assert_array_almost_equal(SP, shortest_path(G_lil))
+
+
+def test_yen_directed():
+    distances, predecessors = yen(
+                            directed_G,
+                            source=0,
+                            sink=3,
+                            K=2,
+                            return_predecessors=True
+                        )
+    assert_allclose(distances, [5., 9.])
+    assert_allclose(predecessors, directed_2SP_0_to_3)
+
+
+def test_yen_undirected():
+    distances = yen(
+        undirected_G,
+        source=0,
+        sink=3,
+        K=4,
+    )
+    assert_allclose(distances, [1., 4., 5., 8.])
+
+def test_yen_unweighted():
+    # Ask for more paths than there are, verify only the available paths are returned
+    distances, predecessors = yen(
+        directed_G,
+        source=0,
+        sink=3,
+        K=4,
+        unweighted=True,
+        return_predecessors=True,
+    )
+    assert_allclose(distances, [2., 3.])
+    assert_allclose(predecessors, directed_2SP_0_to_3)
+
+def test_yen_no_paths():
+    distances = yen(
+        directed_G,
+        source=2,
+        sink=3,
+        K=1,
+    )
+    assert distances.size == 0
+
+def test_yen_negative_weights():
+    distances = yen(
+        directed_negative_weighted_G,
+        source=2,
+        sink=0,
+        K=1,
+    )
+    assert_allclose(distances, [-2.])
+
+
+@pytest.mark.parametrize("min_only", (True, False))
+@pytest.mark.parametrize("directed", (True, False))
+@pytest.mark.parametrize("return_predecessors", (True, False))
+@pytest.mark.parametrize("index_dtype", (np.int32, np.int64))
+@pytest.mark.parametrize("indices", (None, [1]))
+def test_20904(min_only, directed, return_predecessors, index_dtype, indices):
+    """Test two failures from gh-20904: int32 and indices-as-None."""
+    adj_mat = scipy.sparse.eye_array(4, format="csr")
+    adj_mat = scipy.sparse.csr_array(
+        (
+            adj_mat.data,
+            adj_mat.indices.astype(index_dtype),
+            adj_mat.indptr.astype(index_dtype),
+        ),
+    )
+    dijkstra(
+        adj_mat,
+        directed,
+        indices=indices,
+        min_only=min_only,
+        return_predecessors=return_predecessors,
+    )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py
new file mode 100644
index 0000000000000000000000000000000000000000..3237a14584d42022184a54f174b809a2b06d16ed
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_spanning_tree.py
@@ -0,0 +1,66 @@
+"""Test the minimum spanning tree function"""
+import numpy as np
+from numpy.testing import assert_
+import numpy.testing as npt
+from scipy.sparse import csr_array
+from scipy.sparse.csgraph import minimum_spanning_tree
+
+
+def test_minimum_spanning_tree():
+
+    # Create a graph with two connected components.
+    graph = [[0,1,0,0,0],
+             [1,0,0,0,0],
+             [0,0,0,8,5],
+             [0,0,8,0,1],
+             [0,0,5,1,0]]
+    graph = np.asarray(graph)
+
+    # Create the expected spanning tree.
+    expected = [[0,1,0,0,0],
+                [0,0,0,0,0],
+                [0,0,0,0,5],
+                [0,0,0,0,1],
+                [0,0,0,0,0]]
+    expected = np.asarray(expected)
+
+    # Ensure minimum spanning tree code gives this expected output.
+    csgraph = csr_array(graph)
+    mintree = minimum_spanning_tree(csgraph)
+    mintree_array = mintree.toarray()
+    npt.assert_array_equal(mintree_array, expected,
+                           'Incorrect spanning tree found.')
+
+    # Ensure that the original graph was not modified.
+    npt.assert_array_equal(csgraph.toarray(), graph,
+        'Original graph was modified.')
+
+    # Now let the algorithm modify the csgraph in place.
+    mintree = minimum_spanning_tree(csgraph, overwrite=True)
+    npt.assert_array_equal(mintree.toarray(), expected,
+        'Graph was not properly modified to contain MST.')
+
+    np.random.seed(1234)
+    for N in (5, 10, 15, 20):
+
+        # Create a random graph.
+        graph = 3 + np.random.random((N, N))
+        csgraph = csr_array(graph)
+
+        # The spanning tree has at most N - 1 edges.
+        mintree = minimum_spanning_tree(csgraph)
+        assert_(mintree.nnz < N)
+
+        # Set the sub diagonal to 1 to create a known spanning tree.
+        idx = np.arange(N-1)
+        graph[idx,idx+1] = 1
+        csgraph = csr_array(graph)
+        mintree = minimum_spanning_tree(csgraph)
+
+        # We expect to see this pattern in the spanning tree and otherwise
+        # have this zero.
+        expected = np.zeros((N, N))
+        expected[idx, idx+1] = 1
+
+        npt.assert_array_equal(mintree.toarray(), expected,
+            'Incorrect spanning tree found.')
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py
new file mode 100644
index 0000000000000000000000000000000000000000..aef6def21b61ff6b8d8bfb990a3a69136349d7c5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py
@@ -0,0 +1,148 @@
+import numpy as np
+import pytest
+from numpy.testing import assert_array_almost_equal
+from scipy.sparse import csr_array, csr_matrix, coo_array, coo_matrix
+from scipy.sparse.csgraph import (breadth_first_tree, depth_first_tree,
+    csgraph_to_dense, csgraph_from_dense, csgraph_masked_from_dense)
+
+
+def test_graph_breadth_first():
+    csgraph = np.array([[0, 1, 2, 0, 0],
+                        [1, 0, 0, 0, 3],
+                        [2, 0, 0, 7, 0],
+                        [0, 0, 7, 0, 1],
+                        [0, 3, 0, 1, 0]])
+    csgraph = csgraph_from_dense(csgraph, null_value=0)
+
+    bfirst = np.array([[0, 1, 2, 0, 0],
+                       [0, 0, 0, 0, 3],
+                       [0, 0, 0, 7, 0],
+                       [0, 0, 0, 0, 0],
+                       [0, 0, 0, 0, 0]])
+
+    for directed in [True, False]:
+        bfirst_test = breadth_first_tree(csgraph, 0, directed)
+        assert_array_almost_equal(csgraph_to_dense(bfirst_test),
+                                  bfirst)
+
+
+def test_graph_depth_first():
+    csgraph = np.array([[0, 1, 2, 0, 0],
+                        [1, 0, 0, 0, 3],
+                        [2, 0, 0, 7, 0],
+                        [0, 0, 7, 0, 1],
+                        [0, 3, 0, 1, 0]])
+    csgraph = csgraph_from_dense(csgraph, null_value=0)
+
+    dfirst = np.array([[0, 1, 0, 0, 0],
+                       [0, 0, 0, 0, 3],
+                       [0, 0, 0, 0, 0],
+                       [0, 0, 7, 0, 0],
+                       [0, 0, 0, 1, 0]])
+
+    for directed in [True, False]:
+        dfirst_test = depth_first_tree(csgraph, 0, directed)
+        assert_array_almost_equal(csgraph_to_dense(dfirst_test), dfirst)
+
+
+def test_return_type():
+    from .._laplacian import laplacian
+    from .._min_spanning_tree import minimum_spanning_tree
+
+    np_csgraph = np.array([[0, 1, 2, 0, 0],
+                           [1, 0, 0, 0, 3],
+                           [2, 0, 0, 7, 0],
+                           [0, 0, 7, 0, 1],
+                           [0, 3, 0, 1, 0]])
+    csgraph = csr_array(np_csgraph)
+    assert isinstance(laplacian(csgraph), coo_array)
+    assert isinstance(minimum_spanning_tree(csgraph), csr_array)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array)
+
+    csgraph = csgraph_from_dense(np_csgraph, null_value=0)
+    assert isinstance(csgraph, csr_array)
+    assert isinstance(laplacian(csgraph), coo_array)
+    assert isinstance(minimum_spanning_tree(csgraph), csr_array)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array)
+
+    csgraph = csgraph_masked_from_dense(np_csgraph, null_value=0)
+    assert isinstance(csgraph, np.ma.MaskedArray)
+    assert csgraph._baseclass is np.ndarray
+    # laplacian doesnt work with masked arrays so not here
+    assert isinstance(minimum_spanning_tree(csgraph), csr_array)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_array)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_array)
+
+    # start of testing with matrix/spmatrix types
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(DeprecationWarning, "the matrix subclass.*")
+        sup.filter(PendingDeprecationWarning, "the matrix subclass.*")
+
+        nm_csgraph = np.matrix([[0, 1, 2, 0, 0],
+                                [1, 0, 0, 0, 3],
+                                [2, 0, 0, 7, 0],
+                                [0, 0, 7, 0, 1],
+                                [0, 3, 0, 1, 0]])
+
+    csgraph = csr_matrix(nm_csgraph)
+    assert isinstance(laplacian(csgraph), coo_matrix)
+    assert isinstance(minimum_spanning_tree(csgraph), csr_matrix)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix)
+
+    csgraph = csgraph_from_dense(nm_csgraph, null_value=0)
+    assert isinstance(csgraph, csr_matrix)
+    assert isinstance(laplacian(csgraph), coo_matrix)
+    assert isinstance(minimum_spanning_tree(csgraph), csr_matrix)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix)
+
+    mm_csgraph = csgraph_masked_from_dense(nm_csgraph, null_value=0)
+    assert isinstance(mm_csgraph, np.ma.MaskedArray)
+    # laplacian doesnt work with masked arrays so not here
+    assert isinstance(minimum_spanning_tree(csgraph), csr_matrix)
+    for directed in [True, False]:
+        assert isinstance(depth_first_tree(csgraph, 0, directed), csr_matrix)
+        assert isinstance(breadth_first_tree(csgraph, 0, directed), csr_matrix)
+    # end of testing with matrix/spmatrix types
+
+
+def test_graph_breadth_first_trivial_graph():
+    csgraph = np.array([[0]])
+    csgraph = csgraph_from_dense(csgraph, null_value=0)
+
+    bfirst = np.array([[0]])
+
+    for directed in [True, False]:
+        bfirst_test = breadth_first_tree(csgraph, 0, directed)
+        assert_array_almost_equal(csgraph_to_dense(bfirst_test), bfirst)
+
+
+def test_graph_depth_first_trivial_graph():
+    csgraph = np.array([[0]])
+    csgraph = csgraph_from_dense(csgraph, null_value=0)
+
+    bfirst = np.array([[0]])
+
+    for directed in [True, False]:
+        bfirst_test = depth_first_tree(csgraph, 0, directed)
+        assert_array_almost_equal(csgraph_to_dense(bfirst_test),
+                                  bfirst)
+
+
+@pytest.mark.parametrize('directed', [True, False])
+@pytest.mark.parametrize('tree_func', [breadth_first_tree, depth_first_tree])
+def test_int64_indices(tree_func, directed):
+    # See https://github.com/scipy/scipy/issues/18716
+    g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
+    assert g.indices.dtype == np.int64
+    tree = tree_func(g, 0, directed=directed)
+    assert_array_almost_equal(csgraph_to_dense(tree), [[0, 1], [0, 0]])
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae19314d48b3689a556b2a795689a3a1b75458da
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__init__.py
@@ -0,0 +1,148 @@
+"""
+Sparse linear algebra (:mod:`scipy.sparse.linalg`)
+==================================================
+
+.. currentmodule:: scipy.sparse.linalg
+
+Abstract linear operators
+-------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   LinearOperator -- abstract representation of a linear operator
+   aslinearoperator -- convert an object to an abstract linear operator
+
+Matrix Operations
+-----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   inv -- compute the sparse matrix inverse
+   expm -- compute the sparse matrix exponential
+   expm_multiply -- compute the product of a matrix exponential and a matrix
+   matrix_power -- compute the matrix power by raising a matrix to an exponent
+
+Matrix norms
+------------
+
+.. autosummary::
+   :toctree: generated/
+
+   norm -- Norm of a sparse matrix
+   onenormest -- Estimate the 1-norm of a sparse matrix
+
+Solving linear problems
+-----------------------
+
+Direct methods for linear equation systems:
+
+.. autosummary::
+   :toctree: generated/
+
+   spsolve -- Solve the sparse linear system Ax=b
+   spsolve_triangular -- Solve sparse linear system Ax=b for a triangular A.
+   is_sptriangular -- Check if sparse A is triangular.
+   spbandwidth -- Find the bandwidth of a sparse matrix.
+   factorized -- Pre-factorize matrix to a function solving a linear system
+   MatrixRankWarning -- Warning on exactly singular matrices
+   use_solver -- Select direct solver to use
+
+Iterative methods for linear equation systems:
+
+.. autosummary::
+   :toctree: generated/
+
+   bicg -- Use BIConjugate Gradient iteration to solve Ax = b
+   bicgstab -- Use BIConjugate Gradient STABilized iteration to solve Ax = b
+   cg -- Use Conjugate Gradient iteration to solve Ax = b
+   cgs -- Use Conjugate Gradient Squared iteration to solve Ax = b
+   gmres -- Use Generalized Minimal RESidual iteration to solve Ax = b
+   lgmres -- Solve a matrix equation using the LGMRES algorithm
+   minres -- Use MINimum RESidual iteration to solve Ax = b
+   qmr -- Use Quasi-Minimal Residual iteration to solve Ax = b
+   gcrotmk -- Solve a matrix equation using the GCROT(m,k) algorithm
+   tfqmr -- Use Transpose-Free Quasi-Minimal Residual iteration to solve Ax = b
+
+Iterative methods for least-squares problems:
+
+.. autosummary::
+   :toctree: generated/
+
+   lsqr -- Find the least-squares solution to a sparse linear equation system
+   lsmr -- Find the least-squares solution to a sparse linear equation system
+
+Matrix factorizations
+---------------------
+
+Eigenvalue problems:
+
+.. autosummary::
+   :toctree: generated/
+
+   eigs -- Find k eigenvalues and eigenvectors of the square matrix A
+   eigsh -- Find k eigenvalues and eigenvectors of a symmetric matrix
+   lobpcg -- Solve symmetric partial eigenproblems with optional preconditioning
+
+Singular values problems:
+
+.. autosummary::
+   :toctree: generated/
+
+   svds -- Compute k singular values/vectors for a sparse matrix
+
+The `svds` function supports the following solvers:
+
+.. toctree::
+
+    sparse.linalg.svds-arpack
+    sparse.linalg.svds-lobpcg
+    sparse.linalg.svds-propack
+
+Complete or incomplete LU factorizations
+
+.. autosummary::
+   :toctree: generated/
+
+   splu -- Compute a LU decomposition for a sparse matrix
+   spilu -- Compute an incomplete LU decomposition for a sparse matrix
+   SuperLU -- Object representing an LU factorization
+
+Sparse arrays with structure
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   LaplacianNd -- Laplacian on a uniform rectangular grid in ``N`` dimensions
+
+Exceptions
+----------
+
+.. autosummary::
+   :toctree: generated/
+
+   ArpackNoConvergence
+   ArpackError
+
+"""
+
+from ._isolve import *
+from ._dsolve import *
+from ._interface import *
+from ._eigen import *
+from ._matfuncs import *
+from ._onenormest import *
+from ._norm import *
+from ._expm_multiply import *
+from ._special_sparse_arrays import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import isolve, dsolve, interface, eigen, matfuncs
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..86888ce64888c5ee39d7ef1aaff9c3dbcdf8a146
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_expm_multiply.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_expm_multiply.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a49bcec9cb4742868408a59a4165c31ff5feb890
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_expm_multiply.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_interface.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_interface.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a42a61c08ec2fd3d26813a433415ebf15e74bfd7
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_interface.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_matfuncs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_matfuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ceddcaedbd479dc3c2d319a1bb89bc2aa758813f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_matfuncs.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_norm.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_norm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d61359fba277c943d488cb5cb2cc48f2a76cfe00
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_norm.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_onenormest.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_onenormest.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed44fc59d1e2edc7158c3ed2935494c720abd168
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_onenormest.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_special_sparse_arrays.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_special_sparse_arrays.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b28697a683e8aaf252af2f8972d7049593d81932
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_special_sparse_arrays.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_svdp.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_svdp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b96ca840f2ded3177a12e82193a0e6475294c780
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/_svdp.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/dsolve.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/dsolve.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..183278db368d8350ab238145f249079a710ba988
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/dsolve.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/eigen.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/eigen.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..530d05565c9f963175d5a0b552df11e57933ec58
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/eigen.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/interface.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/interface.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f68bb4d5b61db099acc2300fdb274b538f56619d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/interface.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/isolve.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/isolve.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc8952018bb9c5431bbefe04a03976016cc92a89
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/isolve.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/matfuncs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/matfuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7969fd1549c8f3a6493719973e7c6f86d92bf0c8
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/__pycache__/matfuncs.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..90005e3af863d2f7913e6fc4ea8de85962a3efdf
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__init__.py
@@ -0,0 +1,71 @@
+"""
+Linear Solvers
+==============
+
+The default solver is SuperLU (included in the scipy distribution),
+which can solve real or complex linear systems in both single and
+double precisions.  It is automatically replaced by UMFPACK, if
+available.  Note that UMFPACK works in double precision only, so
+switch it off by::
+
+    >>> from scipy.sparse.linalg import spsolve, use_solver
+    >>> use_solver(useUmfpack=False)
+
+to solve in the single precision. See also use_solver documentation.
+
+Example session::
+
+    >>> from scipy.sparse import csc_array, dia_array
+    >>> from numpy import array
+    >>>
+    >>> print("Inverting a sparse linear system:")
+    >>> print("The sparse matrix (constructed from diagonals):")
+    >>> a = dia_array(([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1]), shape=(5, 5))
+    >>> b = array([1, 2, 3, 4, 5])
+    >>> print("Solve: single precision complex:")
+    >>> use_solver( useUmfpack = False )
+    >>> a = a.astype('F')
+    >>> x = spsolve(a, b)
+    >>> print(x)
+    >>> print("Error: ", a@x-b)
+    >>>
+    >>> print("Solve: double precision complex:")
+    >>> use_solver( useUmfpack = True )
+    >>> a = a.astype('D')
+    >>> x = spsolve(a, b)
+    >>> print(x)
+    >>> print("Error: ", a@x-b)
+    >>>
+    >>> print("Solve: double precision:")
+    >>> a = a.astype('d')
+    >>> x = spsolve(a, b)
+    >>> print(x)
+    >>> print("Error: ", a@x-b)
+    >>>
+    >>> print("Solve: single precision:")
+    >>> use_solver( useUmfpack = False )
+    >>> a = a.astype('f')
+    >>> x = spsolve(a, b.astype('f'))
+    >>> print(x)
+    >>> print("Error: ", a@x-b)
+
+"""
+
+#import umfpack
+#__doc__ = '\n\n'.join( (__doc__,  umfpack.__doc__) )
+#del umfpack
+
+from .linsolve import *
+from ._superlu import SuperLU
+from . import _add_newdocs
+from . import linsolve
+
+__all__ = [
+    'MatrixRankWarning', 'SuperLU', 'factorized',
+    'spilu', 'splu', 'spsolve', 'is_sptriangular',
+    'spsolve_triangular', 'use_solver', 'spbandwidth',
+]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1368d01a36a206d73ef52a7c9f5899162c7b435b
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__pycache__/_add_newdocs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__pycache__/_add_newdocs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a9d5588e756a27427d07475f436b5287fbc7533
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__pycache__/_add_newdocs.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__pycache__/linsolve.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__pycache__/linsolve.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4c43e7f85fb2a037ee5e39e23b0befb383aa06e2
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/__pycache__/linsolve.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/_add_newdocs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..cec34dca456b36a1f77e64f853fc1d821f5215eb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/_add_newdocs.py
@@ -0,0 +1,147 @@
+from numpy.lib import add_newdoc
+
+add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU',
+    """
+    LU factorization of a sparse matrix.
+
+    Factorization is represented as::
+
+        Pr @ A @ Pc = L @ U
+
+    To construct these `SuperLU` objects, call the `splu` and `spilu`
+    functions.
+
+    Attributes
+    ----------
+    shape
+    nnz
+    perm_c
+    perm_r
+    L
+    U
+
+    Methods
+    -------
+    solve
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    The LU decomposition can be used to solve matrix equations. Consider:
+
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import splu
+    >>> A = csc_array([[1,2,0,4], [1,0,0,1], [1,0,2,1], [2,2,1,0.]])
+
+    This can be solved for a given right-hand side:
+
+    >>> lu = splu(A)
+    >>> b = np.array([1, 2, 3, 4])
+    >>> x = lu.solve(b)
+    >>> A.dot(x)
+    array([ 1.,  2.,  3.,  4.])
+
+    The ``lu`` object also contains an explicit representation of the
+    decomposition. The permutations are represented as mappings of
+    indices:
+
+    >>> lu.perm_r
+    array([2, 1, 3, 0], dtype=int32)  # may vary
+    >>> lu.perm_c
+    array([0, 1, 3, 2], dtype=int32)  # may vary
+
+    The L and U factors are sparse matrices in CSC format:
+
+    >>> lu.L.toarray()
+    array([[ 1. ,  0. ,  0. ,  0. ],  # may vary
+           [ 0.5,  1. ,  0. ,  0. ],
+           [ 0.5, -1. ,  1. ,  0. ],
+           [ 0.5,  1. ,  0. ,  1. ]])
+    >>> lu.U.toarray()
+    array([[ 2. ,  2. ,  0. ,  1. ],  # may vary
+           [ 0. , -1. ,  1. , -0.5],
+           [ 0. ,  0. ,  5. , -1. ],
+           [ 0. ,  0. ,  0. ,  2. ]])
+
+    The permutation matrices can be constructed:
+
+    >>> Pr = csc_array((np.ones(4), (lu.perm_r, np.arange(4))))
+    >>> Pc = csc_array((np.ones(4), (np.arange(4), lu.perm_c)))
+
+    We can reassemble the original matrix:
+
+    >>> (Pr.T @ (lu.L @ lu.U) @ Pc.T).toarray()
+    array([[ 1.,  2.,  0.,  4.],
+           [ 1.,  0.,  0.,  1.],
+           [ 1.,  0.,  2.,  1.],
+           [ 2.,  2.,  1.,  0.]])
+    """)
+
+add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('solve',
+    """
+    solve(rhs[, trans])
+
+    Solves linear system of equations with one or several right-hand sides.
+
+    Parameters
+    ----------
+    rhs : ndarray, shape (n,) or (n, k)
+        Right hand side(s) of equation
+    trans : {'N', 'T', 'H'}, optional
+        Type of system to solve::
+
+            'N':   A   @ x == rhs  (default)
+            'T':   A^T @ x == rhs
+            'H':   A^H @ x == rhs
+
+        i.e., normal, transposed, and hermitian conjugate.
+
+    Returns
+    -------
+    x : ndarray, shape ``rhs.shape``
+        Solution vector(s)
+    """))
+
+add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('L',
+    """
+    Lower triangular factor with unit diagonal as a
+    `scipy.sparse.csc_array`.
+
+    .. versionadded:: 0.14.0
+    """))
+
+add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('U',
+    """
+    Upper triangular factor as a `scipy.sparse.csc_array`.
+
+    .. versionadded:: 0.14.0
+    """))
+
+add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('shape',
+    """
+    Shape of the original matrix as a tuple of ints.
+    """))
+
+add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('nnz',
+    """
+    Number of nonzero elements in the matrix.
+    """))
+
+add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('perm_c',
+    """
+    Permutation Pc represented as an array of indices.
+
+    See the `SuperLU` docstring for details.
+    """))
+
+add_newdoc('scipy.sparse.linalg._dsolve._superlu', 'SuperLU', ('perm_r',
+    """
+    Permutation Pr represented as an array of indices.
+
+    See the `SuperLU` docstring for details.
+    """))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/linsolve.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/linsolve.py
new file mode 100644
index 0000000000000000000000000000000000000000..192da969d89300d1c616f8f795d91ee4bf65ff8e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/linsolve.py
@@ -0,0 +1,873 @@
+from warnings import warn, catch_warnings, simplefilter
+
+import numpy as np
+from numpy import asarray
+from scipy.sparse import (issparse, SparseEfficiencyWarning,
+                          csr_array, csc_array, eye_array, diags_array)
+from scipy.sparse._sputils import (is_pydata_spmatrix, convert_pydata_sparse_to_scipy,
+                                   get_index_dtype, safely_cast_index_arrays)
+from scipy.linalg import LinAlgError
+import copy
+import threading
+
+from . import _superlu
+
+noScikit = False
+try:
+    import scikits.umfpack as umfpack
+except ImportError:
+    noScikit = True
+
+useUmfpack = threading.local()
+
+
+__all__ = ['use_solver', 'spsolve', 'splu', 'spilu', 'factorized',
+           'MatrixRankWarning', 'spsolve_triangular', 'is_sptriangular', 'spbandwidth']
+
+
+class MatrixRankWarning(UserWarning):
+    pass
+
+
+def use_solver(**kwargs):
+    """
+    Select default sparse direct solver to be used.
+
+    Parameters
+    ----------
+    useUmfpack : bool, optional
+        Use UMFPACK [1]_, [2]_, [3]_, [4]_. over SuperLU. Has effect only
+        if ``scikits.umfpack`` is installed. Default: True
+    assumeSortedIndices : bool, optional
+        Allow UMFPACK to skip the step of sorting indices for a CSR/CSC matrix.
+        Has effect only if useUmfpack is True and ``scikits.umfpack`` is
+        installed. Default: False
+
+    Notes
+    -----
+    The default sparse solver is UMFPACK when available
+    (``scikits.umfpack`` is installed). This can be changed by passing
+    useUmfpack = False, which then causes the always present SuperLU
+    based solver to be used.
+
+    UMFPACK requires a CSR/CSC matrix to have sorted column/row indices. If
+    sure that the matrix fulfills this, pass ``assumeSortedIndices=True``
+    to gain some speed.
+
+    References
+    ----------
+    .. [1] T. A. Davis, Algorithm 832:  UMFPACK - an unsymmetric-pattern
+           multifrontal method with a column pre-ordering strategy, ACM
+           Trans. on Mathematical Software, 30(2), 2004, pp. 196--199.
+           https://dl.acm.org/doi/abs/10.1145/992200.992206
+
+    .. [2] T. A. Davis, A column pre-ordering strategy for the
+           unsymmetric-pattern multifrontal method, ACM Trans.
+           on Mathematical Software, 30(2), 2004, pp. 165--195.
+           https://dl.acm.org/doi/abs/10.1145/992200.992205
+
+    .. [3] T. A. Davis and I. S. Duff, A combined unifrontal/multifrontal
+           method for unsymmetric sparse matrices, ACM Trans. on
+           Mathematical Software, 25(1), 1999, pp. 1--19.
+           https://doi.org/10.1145/305658.287640
+
+    .. [4] T. A. Davis and I. S. Duff, An unsymmetric-pattern multifrontal
+           method for sparse LU factorization, SIAM J. Matrix Analysis and
+           Computations, 18(1), 1997, pp. 140--158.
+           https://doi.org/10.1137/S0895479894246905T.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import use_solver, spsolve
+    >>> from scipy.sparse import csc_array
+    >>> R = np.random.randn(5, 5)
+    >>> A = csc_array(R)
+    >>> b = np.random.randn(5)
+    >>> use_solver(useUmfpack=False) # enforce superLU over UMFPACK
+    >>> x = spsolve(A, b)
+    >>> np.allclose(A.dot(x), b)
+    True
+    >>> use_solver(useUmfpack=True) # reset umfPack usage to default
+    """
+    global useUmfpack
+    if 'useUmfpack' in kwargs:
+        useUmfpack.u = kwargs['useUmfpack']
+    if useUmfpack.u and 'assumeSortedIndices' in kwargs:
+        umfpack.configure(assumeSortedIndices=kwargs['assumeSortedIndices'])
+
+def _get_umf_family(A):
+    """Get umfpack family string given the sparse matrix dtype."""
+    _families = {
+        (np.float64, np.int32): 'di',
+        (np.complex128, np.int32): 'zi',
+        (np.float64, np.int64): 'dl',
+        (np.complex128, np.int64): 'zl'
+    }
+
+    # A.dtype.name can only be "float64" or
+    # "complex128" in control flow
+    f_type = getattr(np, A.dtype.name)
+    # control flow may allow for more index
+    # types to get through here
+    i_type = getattr(np, A.indices.dtype.name)
+
+    try:
+        family = _families[(f_type, i_type)]
+
+    except KeyError as e:
+        msg = ('only float64 or complex128 matrices with int32 or int64 '
+               f'indices are supported! (got: matrix: {f_type}, indices: {i_type})')
+        raise ValueError(msg) from e
+
+    # See gh-8278. Considered converting only if
+    # A.shape[0]*A.shape[1] > np.iinfo(np.int32).max,
+    # but that didn't always fix the issue.
+    family = family[0] + "l"
+    A_new = copy.copy(A)
+    A_new.indptr = np.asarray(A.indptr, dtype=np.int64)
+    A_new.indices = np.asarray(A.indices, dtype=np.int64)
+
+    return family, A_new
+
+def spsolve(A, b, permc_spec=None, use_umfpack=True):
+    """Solve the sparse linear system Ax=b, where b may be a vector or a matrix.
+
+    Parameters
+    ----------
+    A : ndarray or sparse array or matrix
+        The square matrix A will be converted into CSC or CSR form
+    b : ndarray or sparse array or matrix
+        The matrix or vector representing the right hand side of the equation.
+        If a vector, b.shape must be (n,) or (n, 1).
+    permc_spec : str, optional
+        How to permute the columns of the matrix for sparsity preservation.
+        (default: 'COLAMD')
+
+        - ``NATURAL``: natural ordering.
+        - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+        - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+        - ``COLAMD``: approximate minimum degree column ordering [1]_, [2]_.
+
+    use_umfpack : bool, optional
+        if True (default) then use UMFPACK for the solution [3]_, [4]_, [5]_,
+        [6]_ . This is only referenced if b is a vector and
+        ``scikits.umfpack`` is installed.
+
+    Returns
+    -------
+    x : ndarray or sparse array or matrix
+        the solution of the sparse linear equation.
+        If b is a vector, then x is a vector of size A.shape[1]
+        If b is a matrix, then x is a matrix of size (A.shape[1], b.shape[1])
+
+    Notes
+    -----
+    For solving the matrix expression AX = B, this solver assumes the resulting
+    matrix X is sparse, as is often the case for very sparse inputs.  If the
+    resulting X is dense, the construction of this sparse result will be
+    relatively expensive.  In that case, consider converting A to a dense
+    matrix and using scipy.linalg.solve or its variants.
+
+    References
+    ----------
+    .. [1] T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, Algorithm 836:
+           COLAMD, an approximate column minimum degree ordering algorithm,
+           ACM Trans. on Mathematical Software, 30(3), 2004, pp. 377--380.
+           :doi:`10.1145/1024074.1024080`
+
+    .. [2] T. A. Davis, J. R. Gilbert, S. Larimore, E. Ng, A column approximate
+           minimum degree ordering algorithm, ACM Trans. on Mathematical
+           Software, 30(3), 2004, pp. 353--376. :doi:`10.1145/1024074.1024079`
+
+    .. [3] T. A. Davis, Algorithm 832:  UMFPACK - an unsymmetric-pattern
+           multifrontal method with a column pre-ordering strategy, ACM
+           Trans. on Mathematical Software, 30(2), 2004, pp. 196--199.
+           https://dl.acm.org/doi/abs/10.1145/992200.992206
+
+    .. [4] T. A. Davis, A column pre-ordering strategy for the
+           unsymmetric-pattern multifrontal method, ACM Trans.
+           on Mathematical Software, 30(2), 2004, pp. 165--195.
+           https://dl.acm.org/doi/abs/10.1145/992200.992205
+
+    .. [5] T. A. Davis and I. S. Duff, A combined unifrontal/multifrontal
+           method for unsymmetric sparse matrices, ACM Trans. on
+           Mathematical Software, 25(1), 1999, pp. 1--19.
+           https://doi.org/10.1145/305658.287640
+
+    .. [6] T. A. Davis and I. S. Duff, An unsymmetric-pattern multifrontal
+           method for sparse LU factorization, SIAM J. Matrix Analysis and
+           Computations, 18(1), 1997, pp. 140--158.
+           https://doi.org/10.1137/S0895479894246905T.
+
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import spsolve
+    >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
+    >>> B = csc_array([[2, 0], [-1, 0], [2, 0]], dtype=float)
+    >>> x = spsolve(A, B)
+    >>> np.allclose(A.dot(x).toarray(), B.toarray())
+    True
+    """
+    is_pydata_sparse = is_pydata_spmatrix(b)
+    pydata_sparse_cls = b.__class__ if is_pydata_sparse else None
+    A = convert_pydata_sparse_to_scipy(A)
+    b = convert_pydata_sparse_to_scipy(b)
+
+    if not (issparse(A) and A.format in ("csc", "csr")):
+        A = csc_array(A)
+        warn('spsolve requires A be CSC or CSR matrix format',
+             SparseEfficiencyWarning, stacklevel=2)
+
+    # b is a vector only if b have shape (n,) or (n, 1)
+    b_is_sparse = issparse(b)
+    if not b_is_sparse:
+        b = asarray(b)
+    b_is_vector = ((b.ndim == 1) or (b.ndim == 2 and b.shape[1] == 1))
+
+    # sum duplicates for non-canonical format
+    A.sum_duplicates()
+    A = A._asfptype()  # upcast to a floating point format
+    result_dtype = np.promote_types(A.dtype, b.dtype)
+    if A.dtype != result_dtype:
+        A = A.astype(result_dtype)
+    if b.dtype != result_dtype:
+        b = b.astype(result_dtype)
+
+    # validate input shapes
+    M, N = A.shape
+    if (M != N):
+        raise ValueError(f"matrix must be square (has shape {(M, N)})")
+
+    if M != b.shape[0]:
+        raise ValueError(f"matrix - rhs dimension mismatch ({A.shape} - {b.shape[0]})")
+
+    if not hasattr(useUmfpack, 'u'):
+        useUmfpack.u = not noScikit
+
+    use_umfpack = use_umfpack and useUmfpack.u
+
+    if b_is_vector and use_umfpack:
+        if b_is_sparse:
+            b_vec = b.toarray()
+        else:
+            b_vec = b
+        b_vec = asarray(b_vec, dtype=A.dtype).ravel()
+
+        if noScikit:
+            raise RuntimeError('Scikits.umfpack not installed.')
+
+        if A.dtype.char not in 'dD':
+            raise ValueError("convert matrix data to double, please, using"
+                  " .astype(), or set linsolve.useUmfpack.u = False")
+
+        umf_family, A = _get_umf_family(A)
+        umf = umfpack.UmfpackContext(umf_family)
+        x = umf.linsolve(umfpack.UMFPACK_A, A, b_vec,
+                         autoTranspose=True)
+    else:
+        if b_is_vector and b_is_sparse:
+            b = b.toarray()
+            b_is_sparse = False
+
+        if not b_is_sparse:
+            if A.format == "csc":
+                flag = 1  # CSC format
+            else:
+                flag = 0  # CSR format
+
+            indices = A.indices.astype(np.intc, copy=False)
+            indptr = A.indptr.astype(np.intc, copy=False)
+            options = dict(ColPerm=permc_spec)
+            x, info = _superlu.gssv(N, A.nnz, A.data, indices, indptr,
+                                    b, flag, options=options)
+            if info != 0:
+                warn("Matrix is exactly singular", MatrixRankWarning, stacklevel=2)
+                x.fill(np.nan)
+            if b_is_vector:
+                x = x.ravel()
+        else:
+            # b is sparse
+            Afactsolve = factorized(A)
+
+            if not (b.format == "csc" or is_pydata_spmatrix(b)):
+                warn('spsolve is more efficient when sparse b '
+                     'is in the CSC matrix format',
+                     SparseEfficiencyWarning, stacklevel=2)
+                b = csc_array(b)
+
+            # Create a sparse output matrix by repeatedly applying
+            # the sparse factorization to solve columns of b.
+            data_segs = []
+            row_segs = []
+            col_segs = []
+            for j in range(b.shape[1]):
+                bj = b[:, j].toarray().ravel()
+                xj = Afactsolve(bj)
+                w = np.flatnonzero(xj)
+                segment_length = w.shape[0]
+                row_segs.append(w)
+                col_segs.append(np.full(segment_length, j, dtype=int))
+                data_segs.append(np.asarray(xj[w], dtype=A.dtype))
+            sparse_data = np.concatenate(data_segs)
+            idx_dtype = get_index_dtype(maxval=max(b.shape))
+            sparse_row = np.concatenate(row_segs, dtype=idx_dtype)
+            sparse_col = np.concatenate(col_segs, dtype=idx_dtype)
+            x = A.__class__((sparse_data, (sparse_row, sparse_col)),
+                           shape=b.shape, dtype=A.dtype)
+
+            if is_pydata_sparse:
+                x = pydata_sparse_cls.from_scipy_sparse(x)
+
+    return x
+
+
+def splu(A, permc_spec=None, diag_pivot_thresh=None,
+         relax=None, panel_size=None, options=None):
+    """
+    Compute the LU decomposition of a sparse, square matrix.
+
+    Parameters
+    ----------
+    A : sparse array or matrix
+        Sparse array to factorize. Most efficient when provided in CSC
+        format. Other formats will be converted to CSC before factorization.
+    permc_spec : str, optional
+        How to permute the columns of the matrix for sparsity preservation.
+        (default: 'COLAMD')
+
+        - ``NATURAL``: natural ordering.
+        - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+        - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+        - ``COLAMD``: approximate minimum degree column ordering
+
+    diag_pivot_thresh : float, optional
+        Threshold used for a diagonal entry to be an acceptable pivot.
+        See SuperLU user's guide for details [1]_
+    relax : int, optional
+        Expert option for customizing the degree of relaxing supernodes.
+        See SuperLU user's guide for details [1]_
+    panel_size : int, optional
+        Expert option for customizing the panel size.
+        See SuperLU user's guide for details [1]_
+    options : dict, optional
+        Dictionary containing additional expert options to SuperLU.
+        See SuperLU user guide [1]_ (section 2.4 on the 'Options' argument)
+        for more details. For example, you can specify
+        ``options=dict(Equil=False, IterRefine='SINGLE'))``
+        to turn equilibration off and perform a single iterative refinement.
+
+    Returns
+    -------
+    invA : scipy.sparse.linalg.SuperLU
+        Object, which has a ``solve`` method.
+
+    See also
+    --------
+    spilu : incomplete LU decomposition
+
+    Notes
+    -----
+    This function uses the SuperLU library.
+
+    References
+    ----------
+    .. [1] SuperLU https://portal.nersc.gov/project/sparse/superlu/
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import splu
+    >>> A = csc_array([[1., 0., 0.], [5., 0., 2.], [0., -1., 0.]], dtype=float)
+    >>> B = splu(A)
+    >>> x = np.array([1., 2., 3.], dtype=float)
+    >>> B.solve(x)
+    array([ 1. , -3. , -1.5])
+    >>> A.dot(B.solve(x))
+    array([ 1.,  2.,  3.])
+    >>> B.solve(A.dot(x))
+    array([ 1.,  2.,  3.])
+    """
+
+    if is_pydata_spmatrix(A):
+        A_cls = type(A)
+        def csc_construct_func(*a, cls=A_cls):
+            return cls.from_scipy_sparse(csc_array(*a))
+        A = A.to_scipy_sparse().tocsc()
+    else:
+        csc_construct_func = csc_array
+
+    if not (issparse(A) and A.format == "csc"):
+        A = csc_array(A)
+        warn('splu converted its input to CSC format',
+             SparseEfficiencyWarning, stacklevel=2)
+
+    # sum duplicates for non-canonical format
+    A.sum_duplicates()
+    A = A._asfptype()  # upcast to a floating point format
+
+    M, N = A.shape
+    if (M != N):
+        raise ValueError("can only factor square matrices")  # is this true?
+
+    indices, indptr = safely_cast_index_arrays(A, np.intc, "SuperLU")
+
+    _options = dict(DiagPivotThresh=diag_pivot_thresh, ColPerm=permc_spec,
+                    PanelSize=panel_size, Relax=relax)
+    if options is not None:
+        _options.update(options)
+
+    # Ensure that no column permutations are applied
+    if (_options["ColPerm"] == "NATURAL"):
+        _options["SymmetricMode"] = True
+
+    return _superlu.gstrf(N, A.nnz, A.data, indices, indptr,
+                          csc_construct_func=csc_construct_func,
+                          ilu=False, options=_options)
+
+
+def spilu(A, drop_tol=None, fill_factor=None, drop_rule=None, permc_spec=None,
+          diag_pivot_thresh=None, relax=None, panel_size=None, options=None):
+    """
+    Compute an incomplete LU decomposition for a sparse, square matrix.
+
+    The resulting object is an approximation to the inverse of `A`.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Sparse array to factorize. Most efficient when provided in CSC format.
+        Other formats will be converted to CSC before factorization.
+    drop_tol : float, optional
+        Drop tolerance (0 <= tol <= 1) for an incomplete LU decomposition.
+        (default: 1e-4)
+    fill_factor : float, optional
+        Specifies the fill ratio upper bound (>= 1.0) for ILU. (default: 10)
+    drop_rule : str, optional
+        Comma-separated string of drop rules to use.
+        Available rules: ``basic``, ``prows``, ``column``, ``area``,
+        ``secondary``, ``dynamic``, ``interp``. (Default: ``basic,area``)
+
+        See SuperLU documentation for details.
+
+    Remaining other options
+        Same as for `splu`
+
+    Returns
+    -------
+    invA_approx : scipy.sparse.linalg.SuperLU
+        Object, which has a ``solve`` method.
+
+    See also
+    --------
+    splu : complete LU decomposition
+
+    Notes
+    -----
+    To improve the better approximation to the inverse, you may need to
+    increase `fill_factor` AND decrease `drop_tol`.
+
+    This function uses the SuperLU library.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import spilu
+    >>> A = csc_array([[1., 0., 0.], [5., 0., 2.], [0., -1., 0.]], dtype=float)
+    >>> B = spilu(A)
+    >>> x = np.array([1., 2., 3.], dtype=float)
+    >>> B.solve(x)
+    array([ 1. , -3. , -1.5])
+    >>> A.dot(B.solve(x))
+    array([ 1.,  2.,  3.])
+    >>> B.solve(A.dot(x))
+    array([ 1.,  2.,  3.])
+    """
+
+    if is_pydata_spmatrix(A):
+        A_cls = type(A)
+        def csc_construct_func(*a, cls=A_cls):
+            return cls.from_scipy_sparse(csc_array(*a))
+        A = A.to_scipy_sparse().tocsc()
+    else:
+        csc_construct_func = csc_array
+
+    if not (issparse(A) and A.format == "csc"):
+        A = csc_array(A)
+        warn('spilu converted its input to CSC format',
+             SparseEfficiencyWarning, stacklevel=2)
+
+    # sum duplicates for non-canonical format
+    A.sum_duplicates()
+    A = A._asfptype()  # upcast to a floating point format
+
+    M, N = A.shape
+    if (M != N):
+        raise ValueError("can only factor square matrices")  # is this true?
+
+    indices, indptr = safely_cast_index_arrays(A, np.intc, "SuperLU")
+
+    _options = dict(ILU_DropRule=drop_rule, ILU_DropTol=drop_tol,
+                    ILU_FillFactor=fill_factor,
+                    DiagPivotThresh=diag_pivot_thresh, ColPerm=permc_spec,
+                    PanelSize=panel_size, Relax=relax)
+    if options is not None:
+        _options.update(options)
+
+    # Ensure that no column permutations are applied
+    if (_options["ColPerm"] == "NATURAL"):
+        _options["SymmetricMode"] = True
+
+    return _superlu.gstrf(N, A.nnz, A.data, indices, indptr,
+                          csc_construct_func=csc_construct_func,
+                          ilu=True, options=_options)
+
+
+def factorized(A):
+    """
+    Return a function for solving a sparse linear system, with A pre-factorized.
+
+    Parameters
+    ----------
+    A : (N, N) array_like
+        Input. A in CSC format is most efficient. A CSR format matrix will
+        be converted to CSC before factorization.
+
+    Returns
+    -------
+    solve : callable
+        To solve the linear system of equations given in `A`, the `solve`
+        callable should be passed an ndarray of shape (N,).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import factorized
+    >>> from scipy.sparse import csc_array
+    >>> A = np.array([[ 3. ,  2. , -1. ],
+    ...               [ 2. , -2. ,  4. ],
+    ...               [-1. ,  0.5, -1. ]])
+    >>> solve = factorized(csc_array(A)) # Makes LU decomposition.
+    >>> rhs1 = np.array([1, -2, 0])
+    >>> solve(rhs1) # Uses the LU factors.
+    array([ 1., -2., -2.])
+
+    """
+    if is_pydata_spmatrix(A):
+        A = A.to_scipy_sparse().tocsc()
+
+    if not hasattr(useUmfpack, 'u'):
+        useUmfpack.u = not noScikit
+
+    if useUmfpack.u:
+        if noScikit:
+            raise RuntimeError('Scikits.umfpack not installed.')
+
+        if not (issparse(A) and A.format == "csc"):
+            A = csc_array(A)
+            warn('splu converted its input to CSC format',
+                 SparseEfficiencyWarning, stacklevel=2)
+
+        A = A._asfptype()  # upcast to a floating point format
+
+        if A.dtype.char not in 'dD':
+            raise ValueError("convert matrix data to double, please, using"
+                  " .astype(), or set linsolve.useUmfpack.u = False")
+
+        umf_family, A = _get_umf_family(A)
+        umf = umfpack.UmfpackContext(umf_family)
+
+        # Make LU decomposition.
+        umf.numeric(A)
+
+        def solve(b):
+            with np.errstate(divide="ignore", invalid="ignore"):
+                # Ignoring warnings with numpy >= 1.23.0, see gh-16523
+                result = umf.solve(umfpack.UMFPACK_A, A, b, autoTranspose=True)
+
+            return result
+
+        return solve
+    else:
+        return splu(A).solve
+
+
+def spsolve_triangular(A, b, lower=True, overwrite_A=False, overwrite_b=False,
+                       unit_diagonal=False):
+    """
+    Solve the equation ``A x = b`` for `x`, assuming A is a triangular matrix.
+
+    Parameters
+    ----------
+    A : (M, M) sparse array or matrix
+        A sparse square triangular matrix. Should be in CSR or CSC format.
+    b : (M,) or (M, N) array_like
+        Right-hand side matrix in ``A x = b``
+    lower : bool, optional
+        Whether `A` is a lower or upper triangular matrix.
+        Default is lower triangular matrix.
+    overwrite_A : bool, optional
+        Allow changing `A`.
+        Enabling gives a performance gain. Default is False.
+    overwrite_b : bool, optional
+        Allow overwriting data in `b`.
+        Enabling gives a performance gain. Default is False.
+        If `overwrite_b` is True, it should be ensured that
+        `b` has an appropriate dtype to be able to store the result.
+    unit_diagonal : bool, optional
+        If True, diagonal elements of `a` are assumed to be 1.
+
+        .. versionadded:: 1.4.0
+
+    Returns
+    -------
+    x : (M,) or (M, N) ndarray
+        Solution to the system ``A x = b``. Shape of return matches shape
+        of `b`.
+
+    Raises
+    ------
+    LinAlgError
+        If `A` is singular or not triangular.
+    ValueError
+        If shape of `A` or shape of `b` do not match the requirements.
+
+    Notes
+    -----
+    .. versionadded:: 0.19.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import spsolve_triangular
+    >>> A = csc_array([[3, 0, 0], [1, -1, 0], [2, 0, 1]], dtype=float)
+    >>> B = np.array([[2, 0], [-1, 0], [2, 0]], dtype=float)
+    >>> x = spsolve_triangular(A, B)
+    >>> np.allclose(A.dot(x), B)
+    True
+    """
+
+    if is_pydata_spmatrix(A):
+        A = A.to_scipy_sparse().tocsc()
+
+    trans = "N"
+    if issparse(A) and A.format == "csr":
+        A = A.T
+        trans = "T"
+        lower = not lower
+
+    if not (issparse(A) and A.format == "csc"):
+        warn('CSC or CSR matrix format is required. Converting to CSC matrix.',
+             SparseEfficiencyWarning, stacklevel=2)
+        A = csc_array(A)
+    elif not overwrite_A:
+        A = A.copy()
+
+
+    M, N = A.shape
+    if M != N:
+        raise ValueError(
+            f'A must be a square matrix but its shape is {A.shape}.')
+
+    if unit_diagonal:
+        with catch_warnings():
+            simplefilter('ignore', SparseEfficiencyWarning)
+            A.setdiag(1)
+    else:
+        diag = A.diagonal()
+        if np.any(diag == 0):
+            raise LinAlgError(
+                'A is singular: zero entry on diagonal.')
+        invdiag = 1/diag
+        if trans == "N":
+            A = A @ diags_array(invdiag)
+        else:
+            A = (A.T @ diags_array(invdiag)).T
+
+    # sum duplicates for non-canonical format
+    A.sum_duplicates()
+
+    b = np.asanyarray(b)
+
+    if b.ndim not in [1, 2]:
+        raise ValueError(
+            f'b must have 1 or 2 dims but its shape is {b.shape}.')
+    if M != b.shape[0]:
+        raise ValueError(
+            'The size of the dimensions of A must be equal to '
+            'the size of the first dimension of b but the shape of A is '
+            f'{A.shape} and the shape of b is {b.shape}.'
+        )
+
+    result_dtype = np.promote_types(np.promote_types(A.dtype, np.float32), b.dtype)
+    if A.dtype != result_dtype:
+        A = A.astype(result_dtype)
+    if b.dtype != result_dtype:
+        b = b.astype(result_dtype)
+    elif not overwrite_b:
+        b = b.copy()
+
+    if lower:
+        L = A
+        U = csc_array((N, N), dtype=result_dtype)
+    else:
+        L = eye_array(N, dtype=result_dtype, format='csc')
+        U = A
+        U.setdiag(0)
+
+    x, info = _superlu.gstrs(trans,
+                             N, L.nnz, L.data, L.indices, L.indptr,
+                             N, U.nnz, U.data, U.indices, U.indptr,
+                             b)
+    if info:
+        raise LinAlgError('A is singular.')
+
+    if not unit_diagonal:
+        invdiag = invdiag.reshape(-1, *([1] * (len(x.shape) - 1)))
+        x = x * invdiag
+
+    return x
+
+
+def is_sptriangular(A):
+    """Returns 2-tuple indicating lower/upper triangular structure for sparse ``A``
+
+    Checks for triangular structure in ``A``. The result is summarized in
+    two boolean values ``lower`` and ``upper`` to designate whether ``A`` is
+    lower triangular or upper triangular respectively. Diagonal ``A`` will
+    result in both being True. Non-triangular structure results in False for both.
+
+    Only the sparse structure is used here. Values are not checked for zeros.
+
+    This function will convert a copy of ``A`` to CSC format if it is not already
+    CSR or CSC format. So it may be more efficient to convert it yourself if you
+    have other uses for the CSR/CSC version.
+
+    If ``A`` is not square, the portions outside the upper left square of the
+    matrix do not affect its triangular structure. You probably want to work
+    with the square portion of the matrix, though it is not requred here.
+
+    Parameters
+    ----------
+    A : SciPy sparse array or matrix
+        A sparse matrix preferrably in CSR or CSC format.
+
+    Returns
+    -------
+    lower, upper : 2-tuple of bool
+
+        .. versionadded:: 1.15.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array, eye_array
+    >>> from scipy.sparse.linalg import is_sptriangular
+    >>> A = csc_array([[3, 0, 0], [1, -1, 0], [2, 0, 1]], dtype=float)
+    >>> is_sptriangular(A)
+    (True, False)
+    >>> D = eye_array(3, format='csr')
+    >>> is_sptriangular(D)
+    (True, True)
+    """
+    if not (issparse(A) and A.format in ("csc", "csr", "coo", "dia", "dok", "lil")):
+        warn('is_sptriangular needs sparse and not BSR format. Converting to CSR.',
+             SparseEfficiencyWarning, stacklevel=2)
+        A = csr_array(A)
+
+    # bsr is better off converting to csr
+    if A.format == "dia":
+        return A.offsets.max() <= 0, A.offsets.min() >= 0
+    elif A.format == "coo":
+        rows, cols = A.coords
+        return (cols <= rows).all(), (cols >= rows).all()
+    elif A.format == "dok":
+        return all(c <= r for r, c in A.keys()), all(c >= r for r, c in A.keys())
+    elif A.format == "lil":
+        lower = all(col <= row for row, cols in enumerate(A.rows) for col in cols)
+        upper = all(col >= row for row, cols in enumerate(A.rows) for col in cols)
+        return lower, upper
+    # format in ("csc", "csr")
+    indptr, indices = A.indptr, A.indices
+    N = len(indptr) - 1
+
+    lower, upper = True, True
+    # check middle, 1st, last col (treat as CSC and switch at end if CSR)
+    for col in [N // 2, 0, -1]:
+        rows = indices[indptr[col]:indptr[col + 1]]
+        upper = upper and (col >= rows).all()
+        lower = lower and (col <= rows).all()
+        if not upper and not lower:
+            return False, False
+    # check all cols
+    cols = np.repeat(np.arange(N), np.diff(indptr))
+    rows = indices
+    upper = upper and (cols >= rows).all()
+    lower = lower and (cols <= rows).all()
+    if A.format == 'csr':
+        return upper, lower
+    return lower, upper
+
+
+def spbandwidth(A):
+    """Return the lower and upper bandwidth of a 2D numeric array.
+
+    Computes the lower and upper limits on the bandwidth of the
+    sparse 2D array ``A``. The result is summarized as a 2-tuple
+    of positive integers ``(lo, hi)``. A zero denotes no sub/super
+    diagonal entries on that side (tringular). The maximum value
+    for ``lo``(``hi``) is one less than the number of rows(cols).
+
+    Only the sparse structure is used here. Values are not checked for zeros.
+
+    Parameters
+    ----------
+    A : SciPy sparse array or matrix
+        A sparse matrix preferrably in CSR or CSC format.
+
+    Returns
+    -------
+    below, above : 2-tuple of int
+        The distance to the farthest non-zero diagonal below/above the
+        main diagonal.
+
+        .. versionadded:: 1.15.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import spbandwidth
+    >>> from scipy.sparse import csc_array, eye_array
+    >>> A = csc_array([[3, 0, 0], [1, -1, 0], [2, 0, 1]], dtype=float)
+    >>> spbandwidth(A)
+    (2, 0)
+    >>> D = eye_array(3, format='csr')
+    >>> spbandwidth(D)
+    (0, 0)
+    """
+    if not (issparse(A) and A.format in ("csc", "csr", "coo", "dia", "dok")):
+        warn('spbandwidth needs sparse format not LIL and BSR. Converting to CSR.',
+             SparseEfficiencyWarning, stacklevel=2)
+        A = csr_array(A)
+
+    # bsr and lil are better off converting to csr
+    if A.format == "dia":
+        return max(0, -A.offsets.min().item()), max(0, A.offsets.max().item())
+    if A.format in ("csc", "csr"):
+        indptr, indices = A.indptr, A.indices
+        N = len(indptr) - 1
+        gap = np.repeat(np.arange(N), np.diff(indptr)) - indices
+        if A.format == 'csr':
+            gap = -gap
+    elif A.format == "coo":
+        gap = A.coords[1] - A.coords[0]
+    elif A.format == "dok":
+        gap = [(c - r) for r, c in A.keys()] + [0]
+        return -min(gap), max(gap)
+    return max(-np.min(gap).item(), 0), max(np.max(gap).item(), 0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/tests/test_linsolve.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/tests/test_linsolve.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9c5bfed1b5458a8c43ee2234087f164f2a37a80
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_dsolve/tests/test_linsolve.py
@@ -0,0 +1,921 @@
+import sys
+import threading
+
+import numpy as np
+from numpy import array, finfo, arange, eye, all, unique, ones, dot
+import numpy.random as random
+from numpy.testing import (
+        assert_array_almost_equal, assert_almost_equal,
+        assert_equal, assert_array_equal, assert_, assert_allclose,
+        assert_warns, suppress_warnings)
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.linalg
+from scipy.linalg import norm, inv
+from scipy.sparse import (dia_array, SparseEfficiencyWarning, csc_array,
+        csr_array, eye_array, issparse, dok_array, lil_array, bsr_array, kron)
+from scipy.sparse.linalg import SuperLU
+from scipy.sparse.linalg._dsolve import (spsolve, use_solver, splu, spilu,
+        MatrixRankWarning, _superlu, spsolve_triangular, factorized,
+        is_sptriangular, spbandwidth)
+import scipy.sparse
+
+from scipy._lib._testutils import check_free_memory
+from scipy._lib._util import ComplexWarning
+
+
+sup_sparse_efficiency = suppress_warnings()
+sup_sparse_efficiency.filter(SparseEfficiencyWarning)
+
+# scikits.umfpack is not a SciPy dependency but it is optionally used in
+# dsolve, so check whether it's available
+try:
+    import scikits.umfpack as umfpack
+    has_umfpack = True
+except ImportError:
+    has_umfpack = False
+
+def toarray(a):
+    if issparse(a):
+        return a.toarray()
+    else:
+        return a
+
+
+def setup_bug_8278():
+    N = 2 ** 6
+    h = 1/N
+    Ah1D = dia_array(([-1, 2, -1], [-1, 0, 1]), shape=(N-1, N-1))/(h**2)
+    eyeN = eye_array(N - 1)
+    A = (kron(eyeN, kron(eyeN, Ah1D))
+         + kron(eyeN, kron(Ah1D, eyeN))
+         + kron(Ah1D, kron(eyeN, eyeN)))
+    b = np.random.rand((N-1)**3)
+    return A, b
+
+
+class TestFactorized:
+    def setup_method(self):
+        n = 5
+        d = arange(n) + 1
+        self.n = n
+        self.A = dia_array(((d, 2*d, d[::-1]), (-3, 0, 5)), shape=(n,n)).tocsc()
+        random.seed(1234)
+
+    def _check_singular(self):
+        A = csc_array((5,5), dtype='d')
+        b = ones(5)
+        assert_array_almost_equal(0. * b, factorized(A)(b))
+
+    def _check_non_singular(self):
+        # Make a diagonal dominant, to make sure it is not singular
+        n = 5
+        a = csc_array(random.rand(n, n))
+        b = ones(n)
+
+        expected = splu(a).solve(b)
+        assert_array_almost_equal(factorized(a)(b), expected)
+
+    def test_singular_without_umfpack(self):
+        use_solver(useUmfpack=False)
+        with assert_raises(RuntimeError, match="Factor is exactly singular"):
+            self._check_singular()
+
+    @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
+    def test_singular_with_umfpack(self):
+        use_solver(useUmfpack=True)
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "divide by zero encountered in double_scalars")
+            assert_warns(umfpack.UmfpackWarning, self._check_singular)
+
+    def test_non_singular_without_umfpack(self):
+        use_solver(useUmfpack=False)
+        self._check_non_singular()
+
+    @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
+    def test_non_singular_with_umfpack(self):
+        use_solver(useUmfpack=True)
+        self._check_non_singular()
+
+    def test_cannot_factorize_nonsquare_matrix_without_umfpack(self):
+        use_solver(useUmfpack=False)
+        msg = "can only factor square matrices"
+        with assert_raises(ValueError, match=msg):
+            factorized(self.A[:, :4])
+
+    @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
+    def test_factorizes_nonsquare_matrix_with_umfpack(self):
+        use_solver(useUmfpack=True)
+        # does not raise
+        factorized(self.A[:,:4])
+
+    def test_call_with_incorrectly_sized_matrix_without_umfpack(self):
+        use_solver(useUmfpack=False)
+        solve = factorized(self.A)
+        b = random.rand(4)
+        B = random.rand(4, 3)
+        BB = random.rand(self.n, 3, 9)
+
+        with assert_raises(ValueError, match="is of incompatible size"):
+            solve(b)
+        with assert_raises(ValueError, match="is of incompatible size"):
+            solve(B)
+        with assert_raises(ValueError,
+                           match="object too deep for desired array"):
+            solve(BB)
+
+    @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
+    def test_call_with_incorrectly_sized_matrix_with_umfpack(self):
+        use_solver(useUmfpack=True)
+        solve = factorized(self.A)
+        b = random.rand(4)
+        B = random.rand(4, 3)
+        BB = random.rand(self.n, 3, 9)
+
+        # does not raise
+        solve(b)
+        msg = "object too deep for desired array"
+        with assert_raises(ValueError, match=msg):
+            solve(B)
+        with assert_raises(ValueError, match=msg):
+            solve(BB)
+
+    def test_call_with_cast_to_complex_without_umfpack(self):
+        use_solver(useUmfpack=False)
+        solve = factorized(self.A)
+        b = random.rand(4)
+        for t in [np.complex64, np.complex128]:
+            with assert_raises(TypeError, match="Cannot cast array data"):
+                solve(b.astype(t))
+
+    @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
+    def test_call_with_cast_to_complex_with_umfpack(self):
+        use_solver(useUmfpack=True)
+        solve = factorized(self.A)
+        b = random.rand(4)
+        for t in [np.complex64, np.complex128]:
+            assert_warns(ComplexWarning, solve, b.astype(t))
+
+    @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
+    def test_assume_sorted_indices_flag(self):
+        # a sparse matrix with unsorted indices
+        unsorted_inds = np.array([2, 0, 1, 0])
+        data = np.array([10, 16, 5, 0.4])
+        indptr = np.array([0, 1, 2, 4])
+        A = csc_array((data, unsorted_inds, indptr), (3, 3))
+        b = ones(3)
+
+        # should raise when incorrectly assuming indices are sorted
+        use_solver(useUmfpack=True, assumeSortedIndices=True)
+        with assert_raises(RuntimeError,
+                           match="UMFPACK_ERROR_invalid_matrix"):
+            factorized(A)
+
+        # should sort indices and succeed when not assuming indices are sorted
+        use_solver(useUmfpack=True, assumeSortedIndices=False)
+        expected = splu(A.copy()).solve(b)
+
+        assert_equal(A.has_sorted_indices, 0)
+        assert_array_almost_equal(factorized(A)(b), expected)
+
+    @pytest.mark.slow
+    @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
+    def test_bug_8278(self):
+        check_free_memory(8000)
+        use_solver(useUmfpack=True)
+        A, b = setup_bug_8278()
+        A = A.tocsc()
+        f = factorized(A)
+        x = f(b)
+        assert_array_almost_equal(A @ x, b)
+
+
+class TestLinsolve:
+    def setup_method(self):
+        use_solver(useUmfpack=False)
+
+    def test_singular(self):
+        A = csc_array((5,5), dtype='d')
+        b = array([1, 2, 3, 4, 5],dtype='d')
+        with suppress_warnings() as sup:
+            sup.filter(MatrixRankWarning, "Matrix is exactly singular")
+            x = spsolve(A, b)
+        assert_(not np.isfinite(x).any())
+
+    def test_singular_gh_3312(self):
+        # "Bad" test case that leads SuperLU to call LAPACK with invalid
+        # arguments. Check that it fails moderately gracefully.
+        ij = np.array([(17, 0), (17, 6), (17, 12), (10, 13)], dtype=np.int32)
+        v = np.array([0.284213, 0.94933781, 0.15767017, 0.38797296])
+        A = csc_array((v, ij.T), shape=(20, 20))
+        b = np.arange(20)
+
+        try:
+            # should either raise a runtime error or return value
+            # appropriate for singular input (which yields the warning)
+            with suppress_warnings() as sup:
+                sup.filter(MatrixRankWarning, "Matrix is exactly singular")
+                x = spsolve(A, b)
+            assert not np.isfinite(x).any()
+        except RuntimeError:
+            pass
+
+    @pytest.mark.parametrize('format', ['csc', 'csr'])
+    @pytest.mark.parametrize('idx_dtype', [np.int32, np.int64])
+    def test_twodiags(self, format: str, idx_dtype: np.dtype):
+        A = dia_array(([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1]),
+                        shape=(5, 5)).asformat(format)
+        b = array([1, 2, 3, 4, 5])
+
+        # condition number of A
+        cond_A = norm(A.toarray(), 2) * norm(inv(A.toarray()), 2)
+
+        for t in ['f','d','F','D']:
+            eps = finfo(t).eps  # floating point epsilon
+            b = b.astype(t)
+            Asp = A.astype(t)
+            Asp.indices = Asp.indices.astype(idx_dtype, copy=False)
+            Asp.indptr = Asp.indptr.astype(idx_dtype, copy=False)
+
+            x = spsolve(Asp, b)
+            assert_(norm(b - Asp@x) < 10 * cond_A * eps)
+
+    def test_bvector_smoketest(self):
+        Adense = array([[0., 1., 1.],
+                        [1., 0., 1.],
+                        [0., 0., 1.]])
+        As = csc_array(Adense)
+        random.seed(1234)
+        x = random.randn(3)
+        b = As@x
+        x2 = spsolve(As, b)
+
+        assert_array_almost_equal(x, x2)
+
+    def test_bmatrix_smoketest(self):
+        Adense = array([[0., 1., 1.],
+                        [1., 0., 1.],
+                        [0., 0., 1.]])
+        As = csc_array(Adense)
+        random.seed(1234)
+        x = random.randn(3, 4)
+        Bdense = As.dot(x)
+        Bs = csc_array(Bdense)
+        x2 = spsolve(As, Bs)
+        assert_array_almost_equal(x, x2.toarray())
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_non_square(self):
+        # A is not square.
+        A = ones((3, 4))
+        b = ones((4, 1))
+        assert_raises(ValueError, spsolve, A, b)
+        # A2 and b2 have incompatible shapes.
+        A2 = csc_array(eye(3))
+        b2 = array([1.0, 2.0])
+        assert_raises(ValueError, spsolve, A2, b2)
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_example_comparison(self):
+        row = array([0,0,1,2,2,2])
+        col = array([0,2,2,0,1,2])
+        data = array([1,2,3,-4,5,6])
+        sM = csr_array((data,(row,col)), shape=(3,3), dtype=float)
+        M = sM.toarray()
+
+        row = array([0,0,1,1,0,0])
+        col = array([0,2,1,1,0,0])
+        data = array([1,1,1,1,1,1])
+        sN = csr_array((data, (row,col)), shape=(3,3), dtype=float)
+        N = sN.toarray()
+
+        sX = spsolve(sM, sN)
+        X = scipy.linalg.solve(M, N)
+
+        assert_array_almost_equal(X, sX.toarray())
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
+    def test_shape_compatibility(self):
+        use_solver(useUmfpack=True)
+        A = csc_array([[1., 0], [0, 2]])
+        bs = [
+            [1, 6],
+            array([1, 6]),
+            [[1], [6]],
+            array([[1], [6]]),
+            csc_array([[1], [6]]),
+            csr_array([[1], [6]]),
+            dok_array([[1], [6]]),
+            bsr_array([[1], [6]]),
+            array([[1., 2., 3.], [6., 8., 10.]]),
+            csc_array([[1., 2., 3.], [6., 8., 10.]]),
+            csr_array([[1., 2., 3.], [6., 8., 10.]]),
+            dok_array([[1., 2., 3.], [6., 8., 10.]]),
+            bsr_array([[1., 2., 3.], [6., 8., 10.]]),
+            ]
+
+        for b in bs:
+            x = np.linalg.solve(A.toarray(), toarray(b))
+            for spmattype in [csc_array, csr_array, dok_array, lil_array]:
+                x1 = spsolve(spmattype(A), b, use_umfpack=True)
+                x2 = spsolve(spmattype(A), b, use_umfpack=False)
+
+                # check solution
+                if x.ndim == 2 and x.shape[1] == 1:
+                    # interprets also these as "vectors"
+                    x = x.ravel()
+
+                assert_array_almost_equal(toarray(x1), x,
+                                          err_msg=repr((b, spmattype, 1)))
+                assert_array_almost_equal(toarray(x2), x,
+                                          err_msg=repr((b, spmattype, 2)))
+
+                # dense vs. sparse output  ("vectors" are always dense)
+                if issparse(b) and x.ndim > 1:
+                    assert_(issparse(x1), repr((b, spmattype, 1)))
+                    assert_(issparse(x2), repr((b, spmattype, 2)))
+                else:
+                    assert_(isinstance(x1, np.ndarray), repr((b, spmattype, 1)))
+                    assert_(isinstance(x2, np.ndarray), repr((b, spmattype, 2)))
+
+                # check output shape
+                if x.ndim == 1:
+                    # "vector"
+                    assert_equal(x1.shape, (A.shape[1],))
+                    assert_equal(x2.shape, (A.shape[1],))
+                else:
+                    # "matrix"
+                    assert_equal(x1.shape, x.shape)
+                    assert_equal(x2.shape, x.shape)
+
+        A = csc_array((3, 3))
+        b = csc_array((1, 3))
+        assert_raises(ValueError, spsolve, A, b)
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_ndarray_support(self):
+        A = array([[1., 2.], [2., 0.]])
+        x = array([[1., 1.], [0.5, -0.5]])
+        b = array([[2., 0.], [2., 2.]])
+
+        assert_array_almost_equal(x, spsolve(A, b))
+
+    def test_gssv_badinput(self):
+        N = 10
+        d = arange(N) + 1.0
+        A = dia_array(((d, 2*d, d[::-1]), (-3, 0, 5)), shape=(N, N))
+
+        for container in (csc_array, csr_array):
+            A = container(A)
+            b = np.arange(N)
+
+            def not_c_contig(x):
+                return x.repeat(2)[::2]
+
+            def not_1dim(x):
+                return x[:,None]
+
+            def bad_type(x):
+                return x.astype(bool)
+
+            def too_short(x):
+                return x[:-1]
+
+            badops = [not_c_contig, not_1dim, bad_type, too_short]
+
+            for badop in badops:
+                msg = f"{container!r} {badop!r}"
+                # Not C-contiguous
+                assert_raises((ValueError, TypeError), _superlu.gssv,
+                              N, A.nnz, badop(A.data), A.indices, A.indptr,
+                              b, int(A.format == 'csc'), err_msg=msg)
+                assert_raises((ValueError, TypeError), _superlu.gssv,
+                              N, A.nnz, A.data, badop(A.indices), A.indptr,
+                              b, int(A.format == 'csc'), err_msg=msg)
+                assert_raises((ValueError, TypeError), _superlu.gssv,
+                              N, A.nnz, A.data, A.indices, badop(A.indptr),
+                              b, int(A.format == 'csc'), err_msg=msg)
+
+    def test_sparsity_preservation(self):
+        ident = csc_array([
+            [1, 0, 0],
+            [0, 1, 0],
+            [0, 0, 1]])
+        b = csc_array([
+            [0, 1],
+            [1, 0],
+            [0, 0]])
+        x = spsolve(ident, b)
+        assert_equal(ident.nnz, 3)
+        assert_equal(b.nnz, 2)
+        assert_equal(x.nnz, 2)
+        assert_allclose(x.toarray(), b.toarray(), atol=1e-12, rtol=1e-12)
+
+    def test_dtype_cast(self):
+        A_real = scipy.sparse.csr_array([[1, 2, 0],
+                                          [0, 0, 3],
+                                          [4, 0, 5]])
+        A_complex = scipy.sparse.csr_array([[1, 2, 0],
+                                             [0, 0, 3],
+                                             [4, 0, 5 + 1j]])
+        b_real = np.array([1,1,1])
+        b_complex = np.array([1,1,1]) + 1j*np.array([1,1,1])
+        x = spsolve(A_real, b_real)
+        assert_(np.issubdtype(x.dtype, np.floating))
+        x = spsolve(A_real, b_complex)
+        assert_(np.issubdtype(x.dtype, np.complexfloating))
+        x = spsolve(A_complex, b_real)
+        assert_(np.issubdtype(x.dtype, np.complexfloating))
+        x = spsolve(A_complex, b_complex)
+        assert_(np.issubdtype(x.dtype, np.complexfloating))
+
+    @pytest.mark.slow
+    @pytest.mark.skipif(not has_umfpack, reason="umfpack not available")
+    def test_bug_8278(self):
+        check_free_memory(8000)
+        use_solver(useUmfpack=True)
+        A, b = setup_bug_8278()
+        x = spsolve(A, b)
+        assert_array_almost_equal(A @ x, b)
+
+
+class TestSplu:
+    def setup_method(self):
+        use_solver(useUmfpack=False)
+        n = 40
+        d = arange(n) + 1
+        self.n = n
+        self.A = dia_array(((d, 2*d, d[::-1]), (-3, 0, 5)), shape=(n, n)).tocsc()
+        random.seed(1234)
+
+    def _smoketest(self, spxlu, check, dtype, idx_dtype):
+        if np.issubdtype(dtype, np.complexfloating):
+            A = self.A + 1j*self.A.T
+        else:
+            A = self.A
+
+        A = A.astype(dtype)
+        A.indices = A.indices.astype(idx_dtype, copy=False)
+        A.indptr = A.indptr.astype(idx_dtype, copy=False)
+        lu = spxlu(A)
+
+        rng = random.RandomState(1234)
+
+        # Input shapes
+        for k in [None, 1, 2, self.n, self.n+2]:
+            msg = f"k={k!r}"
+
+            if k is None:
+                b = rng.rand(self.n)
+            else:
+                b = rng.rand(self.n, k)
+
+            if np.issubdtype(dtype, np.complexfloating):
+                b = b + 1j*rng.rand(*b.shape)
+            b = b.astype(dtype)
+
+            x = lu.solve(b)
+            check(A, b, x, msg)
+
+            x = lu.solve(b, 'T')
+            check(A.T, b, x, msg)
+
+            x = lu.solve(b, 'H')
+            check(A.T.conj(), b, x, msg)
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_splu_smoketest(self):
+        self._internal_test_splu_smoketest()
+
+    def _internal_test_splu_smoketest(self):
+        # Check that splu works at all
+        def check(A, b, x, msg=""):
+            eps = np.finfo(A.dtype).eps
+            r = A @ x
+            assert_(abs(r - b).max() < 1e3*eps, msg)
+
+        for dtype in [np.float32, np.float64, np.complex64, np.complex128]:
+            for idx_dtype in [np.int32, np.int64]:
+                self._smoketest(splu, check, dtype, idx_dtype)
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_spilu_smoketest(self):
+        self._internal_test_spilu_smoketest()
+
+    def _internal_test_spilu_smoketest(self):
+        errors = []
+
+        def check(A, b, x, msg=""):
+            r = A @ x
+            err = abs(r - b).max()
+            assert_(err < 1e-2, msg)
+            if b.dtype in (np.float64, np.complex128):
+                errors.append(err)
+
+        for dtype in [np.float32, np.float64, np.complex64, np.complex128]:
+            for idx_dtype in [np.int32, np.int64]:
+                self._smoketest(spilu, check, dtype, idx_dtype)
+
+        assert_(max(errors) > 1e-5)
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_spilu_drop_rule(self):
+        # Test passing in the drop_rule argument to spilu.
+        A = eye_array(2)
+
+        rules = [
+            b'basic,area'.decode('ascii'),  # unicode
+            b'basic,area',  # ascii
+            [b'basic', b'area'.decode('ascii')]
+        ]
+        for rule in rules:
+            # Argument should be accepted
+            assert_(isinstance(spilu(A, drop_rule=rule), SuperLU))
+
+    def test_splu_nnz0(self):
+        A = csc_array((5,5), dtype='d')
+        assert_raises(RuntimeError, splu, A)
+
+    def test_spilu_nnz0(self):
+        A = csc_array((5,5), dtype='d')
+        assert_raises(RuntimeError, spilu, A)
+
+    def test_splu_basic(self):
+        # Test basic splu functionality.
+        n = 30
+        rng = random.RandomState(12)
+        a = rng.rand(n, n)
+        a[a < 0.95] = 0
+        # First test with a singular matrix
+        a[:, 0] = 0
+        a_ = csc_array(a)
+        # Matrix is exactly singular
+        assert_raises(RuntimeError, splu, a_)
+
+        # Make a diagonal dominant, to make sure it is not singular
+        a += 4*eye(n)
+        a_ = csc_array(a)
+        lu = splu(a_)
+        b = ones(n)
+        x = lu.solve(b)
+        assert_almost_equal(dot(a, x), b)
+
+    def test_splu_perm(self):
+        # Test the permutation vectors exposed by splu.
+        n = 30
+        a = random.random((n, n))
+        a[a < 0.95] = 0
+        # Make a diagonal dominant, to make sure it is not singular
+        a += 4*eye(n)
+        a_ = csc_array(a)
+        lu = splu(a_)
+        # Check that the permutation indices do belong to [0, n-1].
+        for perm in (lu.perm_r, lu.perm_c):
+            assert_(all(perm > -1))
+            assert_(all(perm < n))
+            assert_equal(len(unique(perm)), len(perm))
+
+        # Now make a symmetric, and test that the two permutation vectors are
+        # the same
+        # Note: a += a.T relies on undefined behavior.
+        a = a + a.T
+        a_ = csc_array(a)
+        lu = splu(a_)
+        assert_array_equal(lu.perm_r, lu.perm_c)
+
+    @pytest.mark.parametrize("splu_fun, rtol", [(splu, 1e-7), (spilu, 1e-1)])
+    def test_natural_permc(self, splu_fun, rtol):
+        # Test that the "NATURAL" permc_spec does not permute the matrix
+        rng = np.random.RandomState(42)
+        n = 500
+        p = 0.01
+        A = scipy.sparse.random(n, n, p, random_state=rng)
+        x = rng.rand(n)
+        # Make A diagonal dominant to make sure it is not singular
+        A += (n+1)*scipy.sparse.eye_array(n)
+        A_ = csc_array(A)
+        b = A_ @ x
+
+        # without permc_spec, permutation is not identity
+        lu = splu_fun(A_)
+        assert_(np.any(lu.perm_c != np.arange(n)))
+
+        # with permc_spec="NATURAL", permutation is identity
+        lu = splu_fun(A_, permc_spec="NATURAL")
+        assert_array_equal(lu.perm_c, np.arange(n))
+
+        # Also, lu decomposition is valid
+        x2 = lu.solve(b)
+        assert_allclose(x, x2, rtol=rtol)
+
+    @pytest.mark.skipif(not hasattr(sys, 'getrefcount'), reason="no sys.getrefcount")
+    def test_lu_refcount(self):
+        # Test that we are keeping track of the reference count with splu.
+        n = 30
+        a = random.random((n, n))
+        a[a < 0.95] = 0
+        # Make a diagonal dominant, to make sure it is not singular
+        a += 4*eye(n)
+        a_ = csc_array(a)
+        lu = splu(a_)
+
+        # And now test that we don't have a refcount bug
+        rc = sys.getrefcount(lu)
+        for attr in ('perm_r', 'perm_c'):
+            perm = getattr(lu, attr)
+            assert_equal(sys.getrefcount(lu), rc + 1)
+            del perm
+            assert_equal(sys.getrefcount(lu), rc)
+
+    def test_bad_inputs(self):
+        A = self.A.tocsc()
+
+        assert_raises(ValueError, splu, A[:,:4])
+        assert_raises(ValueError, spilu, A[:,:4])
+
+        for lu in [splu(A), spilu(A)]:
+            b = random.rand(42)
+            B = random.rand(42, 3)
+            BB = random.rand(self.n, 3, 9)
+            assert_raises(ValueError, lu.solve, b)
+            assert_raises(ValueError, lu.solve, B)
+            assert_raises(ValueError, lu.solve, BB)
+            assert_raises(TypeError, lu.solve,
+                          b.astype(np.complex64))
+            assert_raises(TypeError, lu.solve,
+                          b.astype(np.complex128))
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_superlu_dlamch_i386_nan(self):
+        # SuperLU 4.3 calls some functions returning floats without
+        # declaring them. On i386@linux call convention, this fails to
+        # clear floating point registers after call. As a result, NaN
+        # can appear in the next floating point operation made.
+        #
+        # Here's a test case that triggered the issue.
+        n = 8
+        d = np.arange(n) + 1
+        A = dia_array(((d, 2*d, d[::-1]), (-3, 0, 5)), shape=(n, n))
+        A = A.astype(np.float32)
+        spilu(A)
+        A = A + 1j*A
+        B = A.toarray()
+        assert_(not np.isnan(B).any())
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_lu_attr(self):
+
+        def check(dtype, complex_2=False):
+            A = self.A.astype(dtype)
+
+            if complex_2:
+                A = A + 1j*A.T
+
+            n = A.shape[0]
+            lu = splu(A)
+
+            # Check that the decomposition is as advertised
+
+            Pc = np.zeros((n, n))
+            Pc[np.arange(n), lu.perm_c] = 1
+
+            Pr = np.zeros((n, n))
+            Pr[lu.perm_r, np.arange(n)] = 1
+
+            Ad = A.toarray()
+            lhs = Pr.dot(Ad).dot(Pc)
+            rhs = (lu.L @ lu.U).toarray()
+
+            eps = np.finfo(dtype).eps
+
+            assert_allclose(lhs, rhs, atol=100*eps)
+
+        check(np.float32)
+        check(np.float64)
+        check(np.complex64)
+        check(np.complex128)
+        check(np.complex64, True)
+        check(np.complex128, True)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.slow
+    @sup_sparse_efficiency
+    def test_threads_parallel(self):
+        oks = []
+
+        def worker():
+            try:
+                self.test_splu_basic()
+                self._internal_test_splu_smoketest()
+                self._internal_test_spilu_smoketest()
+                oks.append(True)
+            except Exception:
+                pass
+
+        threads = [threading.Thread(target=worker)
+                   for k in range(20)]
+        for t in threads:
+            t.start()
+        for t in threads:
+            t.join()
+
+        assert_equal(len(oks), 20)
+
+    @pytest.mark.thread_unsafe
+    def test_singular_matrix(self):
+        # Test that SuperLU does not print to stdout when a singular matrix is
+        # passed. See gh-20993.
+        A = eye_array(10, format='csr')
+        A[-1, -1] = 0
+        b = np.zeros(10)
+        with pytest.warns(MatrixRankWarning):
+            res = spsolve(A, b)
+            assert np.isnan(res).all()
+
+
+class TestGstrsErrors:
+    def setup_method(self):
+      self.A = array([[1.0,2.0,3.0],[4.0,5.0,6.0],[7.0,8.0,9.0]], dtype=np.float64)
+      self.b = np.array([[1.0],[2.0],[3.0]], dtype=np.float64)
+
+    def test_trans(self):
+        L = scipy.sparse.tril(self.A, format='csc')
+        U = scipy.sparse.triu(self.A, k=1, format='csc')
+        with assert_raises(ValueError, match="trans must be N, T, or H"):
+            _superlu.gstrs('X', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
+                                U.shape[0], U.nnz, U.data, U.indices, U.indptr, self.b)
+
+    def test_shape_LU(self):
+        L = scipy.sparse.tril(self.A[0:2,0:2], format='csc')
+        U = scipy.sparse.triu(self.A, k=1, format='csc')
+        with assert_raises(ValueError, match="L and U must have the same dimension"):
+            _superlu.gstrs('N', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
+                                U.shape[0], U.nnz, U.data, U.indices, U.indptr, self.b)
+
+    def test_shape_b(self):
+        L = scipy.sparse.tril(self.A, format='csc')
+        U = scipy.sparse.triu(self.A, k=1, format='csc')
+        with assert_raises(ValueError, match="right hand side array has invalid shape"):
+            _superlu.gstrs('N', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
+                                U.shape[0], U.nnz, U.data, U.indices, U.indptr,
+                                self.b[0:2])
+
+    def test_types_differ(self):
+        L = scipy.sparse.tril(self.A.astype(np.float32), format='csc')
+        U = scipy.sparse.triu(self.A, k=1, format='csc')
+        with assert_raises(TypeError, match="nzvals types of L and U differ"):
+            _superlu.gstrs('N', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
+                                U.shape[0], U.nnz, U.data, U.indices, U.indptr, self.b)
+
+    def test_types_unsupported(self):
+        L = scipy.sparse.tril(self.A.astype(np.uint8), format='csc')
+        U = scipy.sparse.triu(self.A.astype(np.uint8), k=1, format='csc')
+        with assert_raises(TypeError, match="nzvals is not of a type supported"):
+            _superlu.gstrs('N', L.shape[0], L.nnz, L.data, L.indices, L.indptr,
+                                U.shape[0], U.nnz, U.data, U.indices, U.indptr,
+                                self.b.astype(np.uint8))
+
+class TestSpsolveTriangular:
+    def setup_method(self):
+        use_solver(useUmfpack=False)
+
+    @pytest.mark.parametrize("fmt",["csr","csc"])
+    def test_zero_diagonal(self,fmt):
+        n = 5
+        rng = np.random.default_rng(43876432987)
+        A = rng.standard_normal((n, n))
+        b = np.arange(n)
+        A = scipy.sparse.tril(A, k=0, format=fmt)
+
+        x = spsolve_triangular(A, b, unit_diagonal=True, lower=True)
+
+        A.setdiag(1)
+        assert_allclose(A.dot(x), b)
+
+        # Regression test from gh-15199
+        A = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0]], dtype=np.float64)
+        b = np.array([1., 2., 3.])
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "CSC or CSR matrix format is")
+            spsolve_triangular(A, b, unit_diagonal=True)
+
+    @pytest.mark.parametrize("fmt",["csr","csc"])
+    def test_singular(self,fmt):
+        n = 5
+        if fmt == "csr":
+            A = csr_array((n, n))
+        else:
+            A = csc_array((n, n))
+        b = np.arange(n)
+        for lower in (True, False):
+            assert_raises(scipy.linalg.LinAlgError,
+                          spsolve_triangular, A, b, lower=lower)
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_bad_shape(self):
+        # A is not square.
+        A = np.zeros((3, 4))
+        b = ones((4, 1))
+        assert_raises(ValueError, spsolve_triangular, A, b)
+        # A2 and b2 have incompatible shapes.
+        A2 = csr_array(eye(3))
+        b2 = array([1.0, 2.0])
+        assert_raises(ValueError, spsolve_triangular, A2, b2)
+
+    @pytest.mark.thread_unsafe
+    @sup_sparse_efficiency
+    def test_input_types(self):
+        A = array([[1., 0.], [1., 2.]])
+        b = array([[2., 0.], [2., 2.]])
+        for matrix_type in (array, csc_array, csr_array):
+            x = spsolve_triangular(matrix_type(A), b, lower=True)
+            assert_array_almost_equal(A.dot(x), b)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.slow
+    @sup_sparse_efficiency
+    @pytest.mark.parametrize("n", [10, 10**2, 10**3])
+    @pytest.mark.parametrize("m", [1, 10])
+    @pytest.mark.parametrize("lower", [True, False])
+    @pytest.mark.parametrize("format", ["csr", "csc"])
+    @pytest.mark.parametrize("unit_diagonal", [False, True])
+    @pytest.mark.parametrize("choice_of_A", ["real", "complex"])
+    @pytest.mark.parametrize("choice_of_b", ["floats", "ints", "complexints"])
+    def test_random(self, n, m, lower, format, unit_diagonal, choice_of_A, choice_of_b):
+        def random_triangle_matrix(n, lower=True, format="csr", choice_of_A="real"):
+            if choice_of_A == "real":
+                dtype = np.float64
+            elif choice_of_A == "complex":
+                dtype = np.complex128
+            else:
+                raise ValueError("choice_of_A must be 'real' or 'complex'.")
+            rng = np.random.default_rng(789002319)
+            rvs = rng.random
+            A = scipy.sparse.random(n, n, density=0.1, format='lil', dtype=dtype,
+                    random_state=rng, data_rvs=rvs)
+            if lower:
+                A = scipy.sparse.tril(A, format="lil")
+            else:
+                A = scipy.sparse.triu(A, format="lil")
+            for i in range(n):
+                A[i, i] = np.random.rand() + 1
+            if format == "csc":
+                A = A.tocsc(copy=False)
+            else:
+                A = A.tocsr(copy=False)
+            return A
+
+        np.random.seed(1234)
+        A = random_triangle_matrix(n, lower=lower)
+        if choice_of_b == "floats":
+            b = np.random.rand(n, m)
+        elif choice_of_b == "ints":
+            b = np.random.randint(-9, 9, (n, m))
+        elif choice_of_b == "complexints":
+            b = np.random.randint(-9, 9, (n, m)) + np.random.randint(-9, 9, (n, m)) * 1j
+        else:
+            raise ValueError(
+                "choice_of_b must be 'floats', 'ints', or 'complexints'.")
+        x = spsolve_triangular(A, b, lower=lower, unit_diagonal=unit_diagonal)
+        if unit_diagonal:
+            A.setdiag(1)
+        assert_allclose(A.dot(x), b, atol=1.5e-6)
+
+
+@pytest.mark.thread_unsafe
+@sup_sparse_efficiency
+@pytest.mark.parametrize("nnz", [10, 10**2, 10**3])
+@pytest.mark.parametrize("fmt", ["csr", "csc", "coo", "dia", "dok", "lil"])
+def test_is_sptriangular_and_spbandwidth(nnz, fmt):
+    rng = np.random.default_rng(42)
+
+    N = nnz // 2
+    dens = 0.1
+    A = scipy.sparse.random_array((N, N), density=dens, format="csr", rng=rng)
+    A[1, 3] = A[3, 1] = 22  # ensure not upper or lower
+    A = A.asformat(fmt)
+    AU = scipy.sparse.triu(A, format=fmt)
+    AL = scipy.sparse.tril(A, format=fmt)
+    D = 0.1 * scipy.sparse.eye_array(N, format=fmt)
+
+    assert is_sptriangular(A) == (False, False)
+    assert is_sptriangular(AL) == (True, False)
+    assert is_sptriangular(AU) == (False, True)
+    assert is_sptriangular(D) == (True, True)
+
+    assert spbandwidth(A) == scipy.linalg.bandwidth(A.toarray())
+    assert spbandwidth(AU) == scipy.linalg.bandwidth(AU.toarray())
+    assert spbandwidth(AL) == scipy.linalg.bandwidth(AL.toarray())
+    assert spbandwidth(D) == scipy.linalg.bandwidth(D.toarray())
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..25278d34ecd3353d409a25f7a94797902fe6ef93
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__init__.py
@@ -0,0 +1,22 @@
+"""
+Sparse Eigenvalue Solvers
+-------------------------
+
+The submodules of sparse.linalg._eigen:
+    1. lobpcg: Locally Optimal Block Preconditioned Conjugate Gradient Method
+
+"""
+from .arpack import *
+from .lobpcg import *
+from ._svds import svds
+
+from . import arpack
+
+__all__ = [
+    'ArpackError', 'ArpackNoConvergence',
+    'eigs', 'eigsh', 'lobpcg', 'svds'
+]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4551b9e5776fd2b723d44af39447cbe8093d8318
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/_svds.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/_svds.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0dddcbef034668a35e188785864372d7cf589921
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/__pycache__/_svds.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce57e841f9f163edd3945f248a653c94acd2a93c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds.py
@@ -0,0 +1,540 @@
+import math
+import numpy as np
+
+from .arpack import _arpack  # type: ignore[attr-defined]
+from . import eigsh
+
+from scipy._lib._util import check_random_state, _transition_to_rng
+from scipy.sparse.linalg._interface import LinearOperator, aslinearoperator
+from scipy.sparse.linalg._eigen.lobpcg import lobpcg  # type: ignore[no-redef]
+from scipy.sparse.linalg._svdp import _svdp
+from scipy.linalg import svd
+
+arpack_int = _arpack.timing.nbx.dtype
+__all__ = ['svds']
+
+
+def _herm(x):
+    return x.T.conj()
+
+
+def _iv(A, k, ncv, tol, which, v0, maxiter,
+        return_singular, solver, rng):
+
+    # input validation/standardization for `solver`
+    # out of order because it's needed for other parameters
+    solver = str(solver).lower()
+    solvers = {"arpack", "lobpcg", "propack"}
+    if solver not in solvers:
+        raise ValueError(f"solver must be one of {solvers}.")
+
+    # input validation/standardization for `A`
+    A = aslinearoperator(A)  # this takes care of some input validation
+    if not np.issubdtype(A.dtype, np.number):
+        message = "`A` must be of numeric data type."
+        raise ValueError(message)
+    if math.prod(A.shape) == 0:
+        message = "`A` must not be empty."
+        raise ValueError(message)
+
+    # input validation/standardization for `k`
+    kmax = min(A.shape) if solver == 'propack' else min(A.shape) - 1
+    if int(k) != k or not (0 < k <= kmax):
+        message = "`k` must be an integer satisfying `0 < k < min(A.shape)`."
+        raise ValueError(message)
+    k = int(k)
+
+    # input validation/standardization for `ncv`
+    if solver == "arpack" and ncv is not None:
+        if int(ncv) != ncv or not (k < ncv < min(A.shape)):
+            message = ("`ncv` must be an integer satisfying "
+                       "`k < ncv < min(A.shape)`.")
+            raise ValueError(message)
+        ncv = int(ncv)
+
+    # input validation/standardization for `tol`
+    if tol < 0 or not np.isfinite(tol):
+        message = "`tol` must be a non-negative floating point value."
+        raise ValueError(message)
+    tol = float(tol)
+
+    # input validation/standardization for `which`
+    which = str(which).upper()
+    whichs = {'LM', 'SM'}
+    if which not in whichs:
+        raise ValueError(f"`which` must be in {whichs}.")
+
+    # input validation/standardization for `v0`
+    if v0 is not None:
+        v0 = np.atleast_1d(v0)
+        if not (np.issubdtype(v0.dtype, np.complexfloating)
+                or np.issubdtype(v0.dtype, np.floating)):
+            message = ("`v0` must be of floating or complex floating "
+                       "data type.")
+            raise ValueError(message)
+
+        shape = (A.shape[0],) if solver == 'propack' else (min(A.shape),)
+        if v0.shape != shape:
+            message = f"`v0` must have shape {shape}."
+            raise ValueError(message)
+
+    # input validation/standardization for `maxiter`
+    if maxiter is not None and (int(maxiter) != maxiter or maxiter <= 0):
+        message = "`maxiter` must be a positive integer."
+        raise ValueError(message)
+    maxiter = int(maxiter) if maxiter is not None else maxiter
+
+    # input validation/standardization for `return_singular_vectors`
+    # not going to be flexible with this; too complicated for little gain
+    rs_options = {True, False, "vh", "u"}
+    if return_singular not in rs_options:
+        raise ValueError(f"`return_singular_vectors` must be in {rs_options}.")
+
+    rng = check_random_state(rng)
+
+    return (A, k, ncv, tol, which, v0, maxiter,
+            return_singular, solver, rng)
+
+
+@_transition_to_rng("random_state", position_num=9)
+def svds(A, k=6, ncv=None, tol=0, which='LM', v0=None,
+         maxiter=None, return_singular_vectors=True,
+         solver='arpack', rng=None, options=None):
+    """
+    Partial singular value decomposition of a sparse matrix.
+
+    Compute the largest or smallest `k` singular values and corresponding
+    singular vectors of a sparse matrix `A`. The order in which the singular
+    values are returned is not guaranteed.
+
+    In the descriptions below, let ``M, N = A.shape``.
+
+    Parameters
+    ----------
+    A : ndarray, sparse matrix, or LinearOperator
+        Matrix to decompose of a floating point numeric dtype.
+    k : int, default: 6
+        Number of singular values and singular vectors to compute.
+        Must satisfy ``1 <= k <= kmax``, where ``kmax=min(M, N)`` for
+        ``solver='propack'`` and ``kmax=min(M, N) - 1`` otherwise.
+    ncv : int, optional
+        When ``solver='arpack'``, this is the number of Lanczos vectors
+        generated. See :ref:`'arpack' ` for details.
+        When ``solver='lobpcg'`` or ``solver='propack'``, this parameter is
+        ignored.
+    tol : float, optional
+        Tolerance for singular values. Zero (default) means machine precision.
+    which : {'LM', 'SM'}
+        Which `k` singular values to find: either the largest magnitude ('LM')
+        or smallest magnitude ('SM') singular values.
+    v0 : ndarray, optional
+        The starting vector for iteration; see method-specific
+        documentation (:ref:`'arpack' `,
+        :ref:`'lobpcg' `), or
+        :ref:`'propack' ` for details.
+    maxiter : int, optional
+        Maximum number of iterations; see method-specific
+        documentation (:ref:`'arpack' `,
+        :ref:`'lobpcg' `), or
+        :ref:`'propack' ` for details.
+    return_singular_vectors : {True, False, "u", "vh"}
+        Singular values are always computed and returned; this parameter
+        controls the computation and return of singular vectors.
+
+        - ``True``: return singular vectors.
+        - ``False``: do not return singular vectors.
+        - ``"u"``: if ``M <= N``, compute only the left singular vectors and
+          return ``None`` for the right singular vectors. Otherwise, compute
+          all singular vectors.
+        - ``"vh"``: if ``M > N``, compute only the right singular vectors and
+          return ``None`` for the left singular vectors. Otherwise, compute
+          all singular vectors.
+
+        If ``solver='propack'``, the option is respected regardless of the
+        matrix shape.
+
+    solver :  {'arpack', 'propack', 'lobpcg'}, optional
+            The solver used.
+            :ref:`'arpack' `,
+            :ref:`'lobpcg' `, and
+            :ref:`'propack' ` are supported.
+            Default: `'arpack'`.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+    options : dict, optional
+        A dictionary of solver-specific options. No solver-specific options
+        are currently supported; this parameter is reserved for future use.
+
+    Returns
+    -------
+    u : ndarray, shape=(M, k)
+        Unitary matrix having left singular vectors as columns.
+    s : ndarray, shape=(k,)
+        The singular values.
+    vh : ndarray, shape=(k, N)
+        Unitary matrix having right singular vectors as rows.
+
+    Notes
+    -----
+    This is a naive implementation using ARPACK or LOBPCG as an eigensolver
+    on the matrix ``A.conj().T @ A`` or ``A @ A.conj().T``, depending on
+    which one is smaller size, followed by the Rayleigh-Ritz method
+    as postprocessing; see
+    Using the normal matrix, in Rayleigh-Ritz method, (2022, Nov. 19),
+    Wikipedia, https://w.wiki/4zms.
+
+    Alternatively, the PROPACK solver can be called.
+
+    Choices of the input matrix `A` numeric dtype may be limited.
+    Only ``solver="lobpcg"`` supports all floating point dtypes
+    real: 'np.float32', 'np.float64', 'np.longdouble' and
+    complex: 'np.complex64', 'np.complex128', 'np.clongdouble'.
+    The ``solver="arpack"`` supports only
+    'np.float32', 'np.float64', and 'np.complex128'.
+
+    Examples
+    --------
+    Construct a matrix `A` from singular values and vectors.
+
+    >>> import numpy as np
+    >>> from scipy import sparse, linalg, stats
+    >>> from scipy.sparse.linalg import svds, aslinearoperator, LinearOperator
+
+    Construct a dense matrix `A` from singular values and vectors.
+
+    >>> rng = np.random.default_rng(258265244568965474821194062361901728911)
+    >>> orthogonal = stats.ortho_group.rvs(10, random_state=rng)
+    >>> s = [1e-3, 1, 2, 3, 4]  # non-zero singular values
+    >>> u = orthogonal[:, :5]         # left singular vectors
+    >>> vT = orthogonal[:, 5:].T      # right singular vectors
+    >>> A = u @ np.diag(s) @ vT
+
+    With only four singular values/vectors, the SVD approximates the original
+    matrix.
+
+    >>> u4, s4, vT4 = svds(A, k=4)
+    >>> A4 = u4 @ np.diag(s4) @ vT4
+    >>> np.allclose(A4, A, atol=1e-3)
+    True
+
+    With all five non-zero singular values/vectors, we can reproduce
+    the original matrix more accurately.
+
+    >>> u5, s5, vT5 = svds(A, k=5)
+    >>> A5 = u5 @ np.diag(s5) @ vT5
+    >>> np.allclose(A5, A)
+    True
+
+    The singular values match the expected singular values.
+
+    >>> np.allclose(s5, s)
+    True
+
+    Since the singular values are not close to each other in this example,
+    every singular vector matches as expected up to a difference in sign.
+
+    >>> (np.allclose(np.abs(u5), np.abs(u)) and
+    ...  np.allclose(np.abs(vT5), np.abs(vT)))
+    True
+
+    The singular vectors are also orthogonal.
+
+    >>> (np.allclose(u5.T @ u5, np.eye(5)) and
+    ...  np.allclose(vT5 @ vT5.T, np.eye(5)))
+    True
+
+    If there are (nearly) multiple singular values, the corresponding
+    individual singular vectors may be unstable, but the whole invariant
+    subspace containing all such singular vectors is computed accurately
+    as can be measured by angles between subspaces via 'subspace_angles'.
+
+    >>> rng = np.random.default_rng(178686584221410808734965903901790843963)
+    >>> s = [1, 1 + 1e-6]  # non-zero singular values
+    >>> u, _ = np.linalg.qr(rng.standard_normal((99, 2)))
+    >>> v, _ = np.linalg.qr(rng.standard_normal((99, 2)))
+    >>> vT = v.T
+    >>> A = u @ np.diag(s) @ vT
+    >>> A = A.astype(np.float32)
+    >>> u2, s2, vT2 = svds(A, k=2, rng=rng)
+    >>> np.allclose(s2, s)
+    True
+
+    The angles between the individual exact and computed singular vectors
+    may not be so small. To check use:
+
+    >>> (linalg.subspace_angles(u2[:, :1], u[:, :1]) +
+    ...  linalg.subspace_angles(u2[:, 1:], u[:, 1:]))
+    array([0.06562513])  # may vary
+    >>> (linalg.subspace_angles(vT2[:1, :].T, vT[:1, :].T) +
+    ...  linalg.subspace_angles(vT2[1:, :].T, vT[1:, :].T))
+    array([0.06562507])  # may vary
+
+    As opposed to the angles between the 2-dimensional invariant subspaces
+    that these vectors span, which are small for rights singular vectors
+
+    >>> linalg.subspace_angles(u2, u).sum() < 1e-6
+    True
+
+    as well as for left singular vectors.
+
+    >>> linalg.subspace_angles(vT2.T, vT.T).sum() < 1e-6
+    True
+
+    The next example follows that of 'sklearn.decomposition.TruncatedSVD'.
+
+    >>> rng = np.random.default_rng(0)
+    >>> X_dense = rng.random(size=(100, 100))
+    >>> X_dense[:, 2 * np.arange(50)] = 0
+    >>> X = sparse.csr_array(X_dense)
+    >>> _, singular_values, _ = svds(X, k=5, rng=rng)
+    >>> print(singular_values)
+    [ 4.3221...  4.4043...  4.4907...  4.5858... 35.4549...]
+
+    The function can be called without the transpose of the input matrix
+    ever explicitly constructed.
+
+    >>> rng = np.random.default_rng(102524723947864966825913730119128190974)
+    >>> G = sparse.random_array((8, 9), density=0.5, rng=rng)
+    >>> Glo = aslinearoperator(G)
+    >>> _, singular_values_svds, _ = svds(Glo, k=5, rng=rng)
+    >>> _, singular_values_svd, _ = linalg.svd(G.toarray())
+    >>> np.allclose(singular_values_svds, singular_values_svd[-4::-1])
+    True
+
+    The most memory efficient scenario is where neither
+    the original matrix, nor its transpose, is explicitly constructed.
+    Our example computes the smallest singular values and vectors
+    of 'LinearOperator' constructed from the numpy function 'np.diff' used
+    column-wise to be consistent with 'LinearOperator' operating on columns.
+
+    >>> diff0 = lambda a: np.diff(a, axis=0)
+
+    Let us create the matrix from 'diff0' to be used for validation only.
+
+    >>> n = 5  # The dimension of the space.
+    >>> M_from_diff0 = diff0(np.eye(n))
+    >>> print(M_from_diff0.astype(int))
+    [[-1  1  0  0  0]
+     [ 0 -1  1  0  0]
+     [ 0  0 -1  1  0]
+     [ 0  0  0 -1  1]]
+
+    The matrix 'M_from_diff0' is bi-diagonal and could be alternatively
+    created directly by
+
+    >>> M = - np.eye(n - 1, n, dtype=int)
+    >>> np.fill_diagonal(M[:,1:], 1)
+    >>> np.allclose(M, M_from_diff0)
+    True
+
+    Its transpose
+
+    >>> print(M.T)
+    [[-1  0  0  0]
+     [ 1 -1  0  0]
+     [ 0  1 -1  0]
+     [ 0  0  1 -1]
+     [ 0  0  0  1]]
+
+    can be viewed as the incidence matrix; see
+    Incidence matrix, (2022, Nov. 19), Wikipedia, https://w.wiki/5YXU,
+    of a linear graph with 5 vertices and 4 edges. The 5x5 normal matrix
+    ``M.T @ M`` thus is
+
+    >>> print(M.T @ M)
+    [[ 1 -1  0  0  0]
+     [-1  2 -1  0  0]
+     [ 0 -1  2 -1  0]
+     [ 0  0 -1  2 -1]
+     [ 0  0  0 -1  1]]
+
+    the graph Laplacian, while the actually used in 'svds' smaller size
+    4x4 normal matrix ``M @ M.T``
+
+    >>> print(M @ M.T)
+    [[ 2 -1  0  0]
+     [-1  2 -1  0]
+     [ 0 -1  2 -1]
+     [ 0  0 -1  2]]
+
+    is the so-called edge-based Laplacian; see
+    Symmetric Laplacian via the incidence matrix, in Laplacian matrix,
+    (2022, Nov. 19), Wikipedia, https://w.wiki/5YXW.
+
+    The 'LinearOperator' setup needs the options 'rmatvec' and 'rmatmat'
+    of multiplication by the matrix transpose ``M.T``, but we want to be
+    matrix-free to save memory, so knowing how ``M.T`` looks like, we
+    manually construct the following function to be
+    used in ``rmatmat=diff0t``.
+
+    >>> def diff0t(a):
+    ...     if a.ndim == 1:
+    ...         a = a[:,np.newaxis]  # Turn 1D into 2D array
+    ...     d = np.zeros((a.shape[0] + 1, a.shape[1]), dtype=a.dtype)
+    ...     d[0, :] = - a[0, :]
+    ...     d[1:-1, :] = a[0:-1, :] - a[1:, :]
+    ...     d[-1, :] = a[-1, :]
+    ...     return d
+
+    We check that our function 'diff0t' for the matrix transpose is valid.
+
+    >>> np.allclose(M.T, diff0t(np.eye(n-1)))
+    True
+
+    Now we setup our matrix-free 'LinearOperator' called 'diff0_func_aslo'
+    and for validation the matrix-based 'diff0_matrix_aslo'.
+
+    >>> def diff0_func_aslo_def(n):
+    ...     return LinearOperator(matvec=diff0,
+    ...                           matmat=diff0,
+    ...                           rmatvec=diff0t,
+    ...                           rmatmat=diff0t,
+    ...                           shape=(n - 1, n))
+    >>> diff0_func_aslo = diff0_func_aslo_def(n)
+    >>> diff0_matrix_aslo = aslinearoperator(M_from_diff0)
+
+    And validate both the matrix and its transpose in 'LinearOperator'.
+
+    >>> np.allclose(diff0_func_aslo(np.eye(n)),
+    ...             diff0_matrix_aslo(np.eye(n)))
+    True
+    >>> np.allclose(diff0_func_aslo.T(np.eye(n-1)),
+    ...             diff0_matrix_aslo.T(np.eye(n-1)))
+    True
+
+    Having the 'LinearOperator' setup validated, we run the solver.
+
+    >>> n = 100
+    >>> diff0_func_aslo = diff0_func_aslo_def(n)
+    >>> u, s, vT = svds(diff0_func_aslo, k=3, which='SM')
+
+    The singular values squared and the singular vectors are known
+    explicitly; see
+    Pure Dirichlet boundary conditions, in
+    Eigenvalues and eigenvectors of the second derivative,
+    (2022, Nov. 19), Wikipedia, https://w.wiki/5YX6,
+    since 'diff' corresponds to first
+    derivative, and its smaller size n-1 x n-1 normal matrix
+    ``M @ M.T`` represent the discrete second derivative with the Dirichlet
+    boundary conditions. We use these analytic expressions for validation.
+
+    >>> se = 2. * np.sin(np.pi * np.arange(1, 4) / (2. * n))
+    >>> ue = np.sqrt(2 / n) * np.sin(np.pi * np.outer(np.arange(1, n),
+    ...                              np.arange(1, 4)) / n)
+    >>> np.allclose(s, se, atol=1e-3)
+    True
+    >>> np.allclose(np.abs(u), np.abs(ue), atol=1e-6)
+    True
+
+    """
+    args = _iv(A, k, ncv, tol, which, v0, maxiter, return_singular_vectors,
+               solver, rng)
+    (A, k, ncv, tol, which, v0, maxiter,
+     return_singular_vectors, solver, rng) = args
+
+    largest = (which == 'LM')
+    n, m = A.shape
+
+    if n >= m:
+        X_dot = A.matvec
+        X_matmat = A.matmat
+        XH_dot = A.rmatvec
+        XH_mat = A.rmatmat
+        transpose = False
+    else:
+        X_dot = A.rmatvec
+        X_matmat = A.rmatmat
+        XH_dot = A.matvec
+        XH_mat = A.matmat
+        transpose = True
+
+        dtype = getattr(A, 'dtype', None)
+        if dtype is None:
+            dtype = A.dot(np.zeros([m, 1])).dtype
+
+    def matvec_XH_X(x):
+        return XH_dot(X_dot(x))
+
+    def matmat_XH_X(x):
+        return XH_mat(X_matmat(x))
+
+    XH_X = LinearOperator(matvec=matvec_XH_X, dtype=A.dtype,
+                          matmat=matmat_XH_X,
+                          shape=(min(A.shape), min(A.shape)))
+
+    # Get a low rank approximation of the implicitly defined gramian matrix.
+    # This is not a stable way to approach the problem.
+    if solver == 'lobpcg':
+
+        if k == 1 and v0 is not None:
+            X = np.reshape(v0, (-1, 1))
+        else:
+            X = rng.standard_normal(size=(min(A.shape), k))
+
+        _, eigvec = lobpcg(XH_X, X, tol=tol ** 2, maxiter=maxiter,
+                           largest=largest)
+
+    elif solver == 'propack':
+        jobu = return_singular_vectors in {True, 'u'}
+        jobv = return_singular_vectors in {True, 'vh'}
+        irl_mode = (which == 'SM')
+        res = _svdp(A, k=k, tol=tol**2, which=which, maxiter=None,
+                    compute_u=jobu, compute_v=jobv, irl_mode=irl_mode,
+                    kmax=maxiter, v0=v0, rng=rng)
+
+        u, s, vh, _ = res  # but we'll ignore bnd, the last output
+
+        # PROPACK order appears to be largest first. `svds` output order is not
+        # guaranteed, according to documentation, but for ARPACK and LOBPCG
+        # they actually are ordered smallest to largest, so reverse for
+        # consistency.
+        s = s[::-1]
+        u = u[:, ::-1]
+        vh = vh[::-1]
+
+        u = u if jobu else None
+        vh = vh if jobv else None
+
+        if return_singular_vectors:
+            return u, s, vh
+        else:
+            return s
+
+    elif solver == 'arpack' or solver is None:
+        if v0 is None:
+            v0 = rng.standard_normal(size=(min(A.shape),))
+        _, eigvec = eigsh(XH_X, k=k, tol=tol ** 2, maxiter=maxiter,
+                          ncv=ncv, which=which, v0=v0)
+        # arpack do not guarantee exactly orthonormal eigenvectors
+        # for clustered eigenvalues, especially in complex arithmetic
+        eigvec, _ = np.linalg.qr(eigvec)
+
+    # the eigenvectors eigvec must be orthonomal here; see gh-16712
+    Av = X_matmat(eigvec)
+    if not return_singular_vectors:
+        s = svd(Av, compute_uv=False, overwrite_a=True)
+        return s[::-1]
+
+    # compute the left singular vectors of X and update the right ones
+    # accordingly
+    u, s, vh = svd(Av, full_matrices=False, overwrite_a=True)
+    u = u[:, ::-1]
+    s = s[::-1]
+    vh = vh[::-1]
+
+    jobu = return_singular_vectors in {True, 'u'}
+    jobv = return_singular_vectors in {True, 'vh'}
+
+    if transpose:
+        u_tmp = eigvec @ _herm(vh) if jobu else None
+        vh = _herm(u) if jobv else None
+        u = u_tmp
+    else:
+        if not jobu:
+            u = None
+        vh = vh @ _herm(eigvec) if jobv else None
+
+    return u, s, vh
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds_doc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds_doc.py
new file mode 100644
index 0000000000000000000000000000000000000000..90b85876d2a69dd3c2efa56445e46c93bf0eaa9e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/_svds_doc.py
@@ -0,0 +1,382 @@
+def _svds_arpack_doc(A, k=6, ncv=None, tol=0, which='LM', v0=None,
+                     maxiter=None, return_singular_vectors=True,
+                     solver='arpack', rng=None):
+    """
+    Partial singular value decomposition of a sparse matrix using ARPACK.
+
+    Compute the largest or smallest `k` singular values and corresponding
+    singular vectors of a sparse matrix `A`. The order in which the singular
+    values are returned is not guaranteed.
+
+    In the descriptions below, let ``M, N = A.shape``.
+
+    Parameters
+    ----------
+    A : sparse matrix or LinearOperator
+        Matrix to decompose.
+    k : int, optional
+        Number of singular values and singular vectors to compute.
+        Must satisfy ``1 <= k <= min(M, N) - 1``.
+        Default is 6.
+    ncv : int, optional
+        The number of Lanczos vectors generated.
+        The default is ``min(n, max(2*k + 1, 20))``.
+        If specified, must satisfy ``k + 1 < ncv < min(M, N)``; ``ncv > 2*k``
+        is recommended.
+    tol : float, optional
+        Tolerance for singular values. Zero (default) means machine precision.
+    which : {'LM', 'SM'}
+        Which `k` singular values to find: either the largest magnitude ('LM')
+        or smallest magnitude ('SM') singular values.
+    v0 : ndarray, optional
+        The starting vector for iteration:
+        an (approximate) left singular vector if ``N > M`` and a right singular
+        vector otherwise. Must be of length ``min(M, N)``.
+        Default: random
+    maxiter : int, optional
+        Maximum number of Arnoldi update iterations allowed;
+        default is ``min(M, N) * 10``.
+    return_singular_vectors : {True, False, "u", "vh"}
+        Singular values are always computed and returned; this parameter
+        controls the computation and return of singular vectors.
+
+        - ``True``: return singular vectors.
+        - ``False``: do not return singular vectors.
+        - ``"u"``: if ``M <= N``, compute only the left singular vectors and
+          return ``None`` for the right singular vectors. Otherwise, compute
+          all singular vectors.
+        - ``"vh"``: if ``M > N``, compute only the right singular vectors and
+          return ``None`` for the left singular vectors. Otherwise, compute
+          all singular vectors.
+
+    solver :  {'arpack', 'propack', 'lobpcg'}, optional
+            This is the solver-specific documentation for ``solver='arpack'``.
+            :ref:`'lobpcg' ` and
+            :ref:`'propack' `
+            are also supported.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+    options : dict, optional
+        A dictionary of solver-specific options. No solver-specific options
+        are currently supported; this parameter is reserved for future use.
+
+    Returns
+    -------
+    u : ndarray, shape=(M, k)
+        Unitary matrix having left singular vectors as columns.
+    s : ndarray, shape=(k,)
+        The singular values.
+    vh : ndarray, shape=(k, N)
+        Unitary matrix having right singular vectors as rows.
+
+    Notes
+    -----
+    This is a naive implementation using ARPACK as an eigensolver
+    on ``A.conj().T @ A`` or ``A @ A.conj().T``, depending on which one is more
+    efficient.
+
+    Examples
+    --------
+    Construct a matrix ``A`` from singular values and vectors.
+
+    >>> import numpy as np
+    >>> from scipy.stats import ortho_group
+    >>> from scipy.sparse import csc_array, diags_array
+    >>> from scipy.sparse.linalg import svds
+    >>> rng = np.random.default_rng()
+    >>> orthogonal = csc_array(ortho_group.rvs(10, random_state=rng))
+    >>> s = [0.0001, 0.001, 3, 4, 5]  # singular values
+    >>> u = orthogonal[:, :5]         # left singular vectors
+    >>> vT = orthogonal[:, 5:].T      # right singular vectors
+    >>> A = u @ diags_array(s) @ vT
+
+    With only three singular values/vectors, the SVD approximates the original
+    matrix.
+
+    >>> u2, s2, vT2 = svds(A, k=3, solver='arpack')
+    >>> A2 = u2 @ np.diag(s2) @ vT2
+    >>> np.allclose(A2, A.toarray(), atol=1e-3)
+    True
+
+    With all five singular values/vectors, we can reproduce the original
+    matrix.
+
+    >>> u3, s3, vT3 = svds(A, k=5, solver='arpack')
+    >>> A3 = u3 @ np.diag(s3) @ vT3
+    >>> np.allclose(A3, A.toarray())
+    True
+
+    The singular values match the expected singular values, and the singular
+    vectors are as expected up to a difference in sign.
+
+    >>> (np.allclose(s3, s) and
+    ...  np.allclose(np.abs(u3), np.abs(u.toarray())) and
+    ...  np.allclose(np.abs(vT3), np.abs(vT.toarray())))
+    True
+
+    The singular vectors are also orthogonal.
+
+    >>> (np.allclose(u3.T @ u3, np.eye(5)) and
+    ...  np.allclose(vT3 @ vT3.T, np.eye(5)))
+    True
+    """
+    pass
+
+
+def _svds_lobpcg_doc(A, k=6, ncv=None, tol=0, which='LM', v0=None,
+                     maxiter=None, return_singular_vectors=True,
+                     solver='lobpcg', rng=None):
+    """
+    Partial singular value decomposition of a sparse matrix using LOBPCG.
+
+    Compute the largest or smallest `k` singular values and corresponding
+    singular vectors of a sparse matrix `A`. The order in which the singular
+    values are returned is not guaranteed.
+
+    In the descriptions below, let ``M, N = A.shape``.
+
+    Parameters
+    ----------
+    A : sparse matrix or LinearOperator
+        Matrix to decompose.
+    k : int, default: 6
+        Number of singular values and singular vectors to compute.
+        Must satisfy ``1 <= k <= min(M, N) - 1``.
+    ncv : int, optional
+        Ignored.
+    tol : float, optional
+        Tolerance for singular values. Zero (default) means machine precision.
+    which : {'LM', 'SM'}
+        Which `k` singular values to find: either the largest magnitude ('LM')
+        or smallest magnitude ('SM') singular values.
+    v0 : ndarray, optional
+        If `k` is 1, the starting vector for iteration:
+        an (approximate) left singular vector if ``N > M`` and a right singular
+        vector otherwise. Must be of length ``min(M, N)``.
+        Ignored otherwise.
+        Default: random
+    maxiter : int, default: 20
+        Maximum number of iterations.
+    return_singular_vectors : {True, False, "u", "vh"}
+        Singular values are always computed and returned; this parameter
+        controls the computation and return of singular vectors.
+
+        - ``True``: return singular vectors.
+        - ``False``: do not return singular vectors.
+        - ``"u"``: if ``M <= N``, compute only the left singular vectors and
+          return ``None`` for the right singular vectors. Otherwise, compute
+          all singular vectors.
+        - ``"vh"``: if ``M > N``, compute only the right singular vectors and
+          return ``None`` for the left singular vectors. Otherwise, compute
+          all singular vectors.
+
+    solver :  {'arpack', 'propack', 'lobpcg'}, optional
+            This is the solver-specific documentation for ``solver='lobpcg'``.
+            :ref:`'arpack' ` and
+            :ref:`'propack' `
+            are also supported.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+    options : dict, optional
+        A dictionary of solver-specific options. No solver-specific options
+        are currently supported; this parameter is reserved for future use.
+
+    Returns
+    -------
+    u : ndarray, shape=(M, k)
+        Unitary matrix having left singular vectors as columns.
+    s : ndarray, shape=(k,)
+        The singular values.
+    vh : ndarray, shape=(k, N)
+        Unitary matrix having right singular vectors as rows.
+
+    Notes
+    -----
+    This is a naive implementation using LOBPCG as an eigensolver
+    on ``A.conj().T @ A`` or ``A @ A.conj().T``, depending on which one is more
+    efficient.
+
+    Examples
+    --------
+    Construct a matrix ``A`` from singular values and vectors.
+
+    >>> import numpy as np
+    >>> from scipy.stats import ortho_group
+    >>> from scipy.sparse import csc_array, diags_array
+    >>> from scipy.sparse.linalg import svds
+    >>> rng = np.random.default_rng()
+    >>> orthogonal = csc_array(ortho_group.rvs(10, random_state=rng))
+    >>> s = [0.0001, 0.001, 3, 4, 5]  # singular values
+    >>> u = orthogonal[:, :5]         # left singular vectors
+    >>> vT = orthogonal[:, 5:].T      # right singular vectors
+    >>> A = u @ diags_array(s) @ vT
+
+    With only three singular values/vectors, the SVD approximates the original
+    matrix.
+
+    >>> u2, s2, vT2 = svds(A, k=3, solver='lobpcg')
+    >>> A2 = u2 @ np.diag(s2) @ vT2
+    >>> np.allclose(A2, A.toarray(), atol=1e-3)
+    True
+
+    With all five singular values/vectors, we can reproduce the original
+    matrix.
+
+    >>> u3, s3, vT3 = svds(A, k=5, solver='lobpcg')
+    >>> A3 = u3 @ np.diag(s3) @ vT3
+    >>> np.allclose(A3, A.toarray())
+    True
+
+    The singular values match the expected singular values, and the singular
+    vectors are as expected up to a difference in sign.
+
+    >>> (np.allclose(s3, s) and
+    ...  np.allclose(np.abs(u3), np.abs(u.todense())) and
+    ...  np.allclose(np.abs(vT3), np.abs(vT.todense())))
+    True
+
+    The singular vectors are also orthogonal.
+
+    >>> (np.allclose(u3.T @ u3, np.eye(5)) and
+    ...  np.allclose(vT3 @ vT3.T, np.eye(5)))
+    True
+
+    """
+    pass
+
+
+def _svds_propack_doc(A, k=6, ncv=None, tol=0, which='LM', v0=None,
+                      maxiter=None, return_singular_vectors=True,
+                      solver='propack', rng=None):
+    """
+    Partial singular value decomposition of a sparse matrix using PROPACK.
+
+    Compute the largest or smallest `k` singular values and corresponding
+    singular vectors of a sparse matrix `A`. The order in which the singular
+    values are returned is not guaranteed.
+
+    In the descriptions below, let ``M, N = A.shape``.
+
+    Parameters
+    ----------
+    A : sparse matrix or LinearOperator
+        Matrix to decompose. If `A` is a ``LinearOperator``
+        object, it must define both ``matvec`` and ``rmatvec`` methods.
+    k : int, default: 6
+        Number of singular values and singular vectors to compute.
+        Must satisfy ``1 <= k <= min(M, N)``.
+    ncv : int, optional
+        Ignored.
+    tol : float, optional
+        The desired relative accuracy for computed singular values.
+        Zero (default) means machine precision.
+    which : {'LM', 'SM'}
+        Which `k` singular values to find: either the largest magnitude ('LM')
+        or smallest magnitude ('SM') singular values. Note that choosing
+        ``which='SM'`` will force the ``irl`` option to be set ``True``.
+    v0 : ndarray, optional
+        Starting vector for iterations: must be of length ``A.shape[0]``.
+        If not specified, PROPACK will generate a starting vector.
+    maxiter : int, optional
+        Maximum number of iterations / maximal dimension of the Krylov
+        subspace. Default is ``10 * k``.
+    return_singular_vectors : {True, False, "u", "vh"}
+        Singular values are always computed and returned; this parameter
+        controls the computation and return of singular vectors.
+
+        - ``True``: return singular vectors.
+        - ``False``: do not return singular vectors.
+        - ``"u"``: compute only the left singular vectors; return ``None`` for
+          the right singular vectors.
+        - ``"vh"``: compute only the right singular vectors; return ``None``
+          for the left singular vectors.
+
+    solver :  {'arpack', 'propack', 'lobpcg'}, optional
+            This is the solver-specific documentation for ``solver='propack'``.
+            :ref:`'arpack' ` and
+            :ref:`'lobpcg' `
+            are also supported.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+    options : dict, optional
+        A dictionary of solver-specific options. No solver-specific options
+        are currently supported; this parameter is reserved for future use.
+
+    Returns
+    -------
+    u : ndarray, shape=(M, k)
+        Unitary matrix having left singular vectors as columns.
+    s : ndarray, shape=(k,)
+        The singular values.
+    vh : ndarray, shape=(k, N)
+        Unitary matrix having right singular vectors as rows.
+
+    Notes
+    -----
+    This is an interface to the Fortran library PROPACK [1]_.
+    The current default is to run with IRL mode disabled unless seeking the
+    smallest singular values/vectors (``which='SM'``).
+
+    References
+    ----------
+
+    .. [1] Larsen, Rasmus Munk. "PROPACK-Software for large and sparse SVD
+       calculations." Available online. URL
+       http://sun.stanford.edu/~rmunk/PROPACK (2004): 2008-2009.
+
+    Examples
+    --------
+    Construct a matrix ``A`` from singular values and vectors.
+
+    >>> import numpy as np
+    >>> from scipy.stats import ortho_group
+    >>> from scipy.sparse import csc_array, diags_array
+    >>> from scipy.sparse.linalg import svds
+    >>> rng = np.random.default_rng()
+    >>> orthogonal = csc_array(ortho_group.rvs(10, random_state=rng))
+    >>> s = [0.0001, 0.001, 3, 4, 5]  # singular values
+    >>> u = orthogonal[:, :5]         # left singular vectors
+    >>> vT = orthogonal[:, 5:].T      # right singular vectors
+    >>> A = u @ diags_array(s) @ vT
+
+    With only three singular values/vectors, the SVD approximates the original
+    matrix.
+
+    >>> u2, s2, vT2 = svds(A, k=3, solver='propack')
+    >>> A2 = u2 @ np.diag(s2) @ vT2
+    >>> np.allclose(A2, A.todense(), atol=1e-3)
+    True
+
+    With all five singular values/vectors, we can reproduce the original
+    matrix.
+
+    >>> u3, s3, vT3 = svds(A, k=5, solver='propack')
+    >>> A3 = u3 @ np.diag(s3) @ vT3
+    >>> np.allclose(A3, A.todense())
+    True
+
+    The singular values match the expected singular values, and the singular
+    vectors are as expected up to a difference in sign.
+
+    >>> (np.allclose(s3, s) and
+    ...  np.allclose(np.abs(u3), np.abs(u.toarray())) and
+    ...  np.allclose(np.abs(vT3), np.abs(vT.toarray())))
+    True
+
+    The singular vectors are also orthogonal.
+
+    >>> (np.allclose(u3.T @ u3, np.eye(5)) and
+    ...  np.allclose(vT3 @ vT3.T, np.eye(5)))
+    True
+
+    """
+    pass
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/COPYING b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/COPYING
new file mode 100644
index 0000000000000000000000000000000000000000..e87667e1b8c178e53c6a7c6268ebc09ab4b0476c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/COPYING
@@ -0,0 +1,45 @@
+
+BSD Software License
+
+Pertains to ARPACK and P_ARPACK
+
+Copyright (c) 1996-2008 Rice University.
+Developed by D.C. Sorensen, R.B. Lehoucq, C. Yang, and K. Maschhoff.
+All rights reserved.
+
+Arpack has been renamed to arpack-ng.
+
+Copyright (c) 2001-2011 - Scilab Enterprises
+Updated by Allan Cornet, Sylvestre Ledru.
+
+Copyright (c) 2010 - Jordi Gutiérrez Hermoso (Octave patch)
+
+Copyright (c) 2007 - Sébastien Fabbro (gentoo patch)
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+- Redistributions of source code must retain the above copyright
+  notice, this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright
+  notice, this list of conditions and the following disclaimer listed
+  in this license in the documentation and/or other materials
+  provided with the distribution.
+
+- Neither the name of the copyright holders nor the names of its
+  contributors may be used to endorse or promote products derived from
+  this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..679b94480d7ff5a11e037ffb758f2214c6e5097f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__init__.py
@@ -0,0 +1,20 @@
+"""
+Eigenvalue solver using iterative methods.
+
+Find k eigenvectors and eigenvalues of a matrix A using the
+Arnoldi/Lanczos iterative methods from ARPACK [1]_,[2]_.
+
+These methods are most useful for large sparse matrices.
+
+  - eigs(A,k)
+  - eigsh(A,k)
+
+References
+----------
+.. [1] ARPACK Software, http://www.caam.rice.edu/software/ARPACK/
+.. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang,  ARPACK USERS GUIDE:
+   Solution of Large Scale Eigenvalue Problems by Implicitly Restarted
+   Arnoldi Methods. SIAM, Philadelphia, PA, 1998.
+
+"""
+from .arpack import *
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c446a5b8899f873311bc41b3b5231adb55c37b8c
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__pycache__/arpack.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__pycache__/arpack.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06029e1991129757b21af951a82c35484427eccd
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/__pycache__/arpack.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/arpack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/arpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..623b605b2da51b462c88b97c8083bc1a135cc161
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/arpack.py
@@ -0,0 +1,1700 @@
+"""
+Find a few eigenvectors and eigenvalues of a matrix.
+
+
+Uses ARPACK: https://github.com/opencollab/arpack-ng
+
+"""
+# Wrapper implementation notes
+#
+# ARPACK Entry Points
+# -------------------
+# The entry points to ARPACK are
+# - (s,d)seupd : single and double precision symmetric matrix
+# - (s,d,c,z)neupd: single,double,complex,double complex general matrix
+# This wrapper puts the *neupd (general matrix) interfaces in eigs()
+# and the *seupd (symmetric matrix) in eigsh().
+# There is no specialized interface for complex Hermitian matrices.
+# To find eigenvalues of a complex Hermitian matrix you
+# may use eigsh(), but eigsh() will simply call eigs()
+# and return the real part of the eigenvalues thus obtained.
+
+# Number of eigenvalues returned and complex eigenvalues
+# ------------------------------------------------------
+# The ARPACK nonsymmetric real and double interface (s,d)naupd return
+# eigenvalues and eigenvectors in real (float,double) arrays.
+# Since the eigenvalues and eigenvectors are, in general, complex
+# ARPACK puts the real and imaginary parts in consecutive entries
+# in real-valued arrays.   This wrapper puts the real entries
+# into complex data types and attempts to return the requested eigenvalues
+# and eigenvectors.
+
+
+# Solver modes
+# ------------
+# ARPACK and handle shifted and shift-inverse computations
+# for eigenvalues by providing a shift (sigma) and a solver.
+
+import numpy as np
+import warnings
+from scipy.sparse.linalg._interface import aslinearoperator, LinearOperator
+from scipy.sparse import eye, issparse
+from scipy.linalg import eig, eigh, lu_factor, lu_solve
+from scipy.sparse._sputils import (
+    convert_pydata_sparse_to_scipy, isdense, is_pydata_spmatrix,
+)
+from scipy.sparse.linalg import gmres, splu
+from scipy._lib._util import _aligned_zeros
+from scipy._lib._threadsafety import ReentrancyLock
+from . import _arpack
+arpack_int = _arpack.timing.nbx.dtype
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['eigs', 'eigsh', 'ArpackError', 'ArpackNoConvergence']
+
+
+_type_conv = {'f': 's', 'd': 'd', 'F': 'c', 'D': 'z'}
+_ndigits = {'f': 5, 'd': 12, 'F': 5, 'D': 12}
+
+DNAUPD_ERRORS = {
+    0: "Normal exit.",
+    1: "Maximum number of iterations taken. "
+       "All possible eigenvalues of OP has been found. IPARAM(5) "
+       "returns the number of wanted converged Ritz values.",
+    2: "No longer an informational error. Deprecated starting "
+       "with release 2 of ARPACK.",
+    3: "No shifts could be applied during a cycle of the "
+       "Implicitly restarted Arnoldi iteration. One possibility "
+       "is to increase the size of NCV relative to NEV. ",
+    -1: "N must be positive.",
+    -2: "NEV must be positive.",
+    -3: "NCV-NEV >= 2 and less than or equal to N.",
+    -4: "The maximum number of Arnoldi update iterations allowed "
+        "must be greater than zero.",
+    -5: " WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'",
+    -6: "BMAT must be one of 'I' or 'G'.",
+    -7: "Length of private work array WORKL is not sufficient.",
+    -8: "Error return from LAPACK eigenvalue calculation;",
+    -9: "Starting vector is zero.",
+    -10: "IPARAM(7) must be 1,2,3,4.",
+    -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
+    -12: "IPARAM(1) must be equal to 0 or 1.",
+    -13: "NEV and WHICH = 'BE' are incompatible.",
+    -9999: "Could not build an Arnoldi factorization. "
+           "IPARAM(5) returns the size of the current Arnoldi "
+           "factorization. The user is advised to check that "
+           "enough workspace and array storage has been allocated."
+}
+
+SNAUPD_ERRORS = DNAUPD_ERRORS
+
+ZNAUPD_ERRORS = DNAUPD_ERRORS.copy()
+ZNAUPD_ERRORS[-10] = "IPARAM(7) must be 1,2,3."
+
+CNAUPD_ERRORS = ZNAUPD_ERRORS
+
+DSAUPD_ERRORS = {
+    0: "Normal exit.",
+    1: "Maximum number of iterations taken. "
+       "All possible eigenvalues of OP has been found.",
+    2: "No longer an informational error. Deprecated starting with "
+       "release 2 of ARPACK.",
+    3: "No shifts could be applied during a cycle of the Implicitly "
+       "restarted Arnoldi iteration. One possibility is to increase "
+       "the size of NCV relative to NEV. ",
+    -1: "N must be positive.",
+    -2: "NEV must be positive.",
+    -3: "NCV must be greater than NEV and less than or equal to N.",
+    -4: "The maximum number of Arnoldi update iterations allowed "
+        "must be greater than zero.",
+    -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.",
+    -6: "BMAT must be one of 'I' or 'G'.",
+    -7: "Length of private work array WORKL is not sufficient.",
+    -8: "Error return from trid. eigenvalue calculation; "
+        "Informational error from LAPACK routine dsteqr .",
+    -9: "Starting vector is zero.",
+    -10: "IPARAM(7) must be 1,2,3,4,5.",
+    -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
+    -12: "IPARAM(1) must be equal to 0 or 1.",
+    -13: "NEV and WHICH = 'BE' are incompatible. ",
+    -9999: "Could not build an Arnoldi factorization. "
+           "IPARAM(5) returns the size of the current Arnoldi "
+           "factorization. The user is advised to check that "
+           "enough workspace and array storage has been allocated.",
+}
+
+SSAUPD_ERRORS = DSAUPD_ERRORS
+
+DNEUPD_ERRORS = {
+    0: "Normal exit.",
+    1: "The Schur form computed by LAPACK routine dlahqr "
+       "could not be reordered by LAPACK routine dtrsen. "
+       "Re-enter subroutine dneupd  with IPARAM(5)NCV and "
+       "increase the size of the arrays DR and DI to have "
+       "dimension at least dimension NCV and allocate at least NCV "
+       "columns for Z. NOTE: Not necessary if Z and V share "
+       "the same space. Please notify the authors if this error"
+       "occurs.",
+    -1: "N must be positive.",
+    -2: "NEV must be positive.",
+    -3: "NCV-NEV >= 2 and less than or equal to N.",
+    -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'",
+    -6: "BMAT must be one of 'I' or 'G'.",
+    -7: "Length of private work WORKL array is not sufficient.",
+    -8: "Error return from calculation of a real Schur form. "
+        "Informational error from LAPACK routine dlahqr .",
+    -9: "Error return from calculation of eigenvectors. "
+        "Informational error from LAPACK routine dtrevc.",
+    -10: "IPARAM(7) must be 1,2,3,4.",
+    -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
+    -12: "HOWMNY = 'S' not yet implemented",
+    -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.",
+    -14: "DNAUPD  did not find any eigenvalues to sufficient "
+         "accuracy.",
+    -15: "DNEUPD got a different count of the number of converged "
+         "Ritz values than DNAUPD got.  This indicates the user "
+         "probably made an error in passing data from DNAUPD to "
+         "DNEUPD or that the data was modified before entering "
+         "DNEUPD",
+}
+
+SNEUPD_ERRORS = DNEUPD_ERRORS.copy()
+SNEUPD_ERRORS[1] = ("The Schur form computed by LAPACK routine slahqr "
+                    "could not be reordered by LAPACK routine strsen . "
+                    "Re-enter subroutine dneupd  with IPARAM(5)=NCV and "
+                    "increase the size of the arrays DR and DI to have "
+                    "dimension at least dimension NCV and allocate at least "
+                    "NCV columns for Z. NOTE: Not necessary if Z and V share "
+                    "the same space. Please notify the authors if this error "
+                    "occurs.")
+SNEUPD_ERRORS[-14] = ("SNAUPD did not find any eigenvalues to sufficient "
+                      "accuracy.")
+SNEUPD_ERRORS[-15] = ("SNEUPD got a different count of the number of "
+                      "converged Ritz values than SNAUPD got.  This indicates "
+                      "the user probably made an error in passing data from "
+                      "SNAUPD to SNEUPD or that the data was modified before "
+                      "entering SNEUPD")
+
+ZNEUPD_ERRORS = {0: "Normal exit.",
+                 1: "The Schur form computed by LAPACK routine csheqr "
+                    "could not be reordered by LAPACK routine ztrsen. "
+                    "Re-enter subroutine zneupd with IPARAM(5)=NCV and "
+                    "increase the size of the array D to have "
+                    "dimension at least dimension NCV and allocate at least "
+                    "NCV columns for Z. NOTE: Not necessary if Z and V share "
+                    "the same space. Please notify the authors if this error "
+                    "occurs.",
+                 -1: "N must be positive.",
+                 -2: "NEV must be positive.",
+                 -3: "NCV-NEV >= 1 and less than or equal to N.",
+                 -5: "WHICH must be one of 'LM', 'SM', 'LR', 'SR', 'LI', 'SI'",
+                 -6: "BMAT must be one of 'I' or 'G'.",
+                 -7: "Length of private work WORKL array is not sufficient.",
+                 -8: "Error return from LAPACK eigenvalue calculation. "
+                     "This should never happened.",
+                 -9: "Error return from calculation of eigenvectors. "
+                     "Informational error from LAPACK routine ztrevc.",
+                 -10: "IPARAM(7) must be 1,2,3",
+                 -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
+                 -12: "HOWMNY = 'S' not yet implemented",
+                 -13: "HOWMNY must be one of 'A' or 'P' if RVEC = .true.",
+                 -14: "ZNAUPD did not find any eigenvalues to sufficient "
+                      "accuracy.",
+                 -15: "ZNEUPD got a different count of the number of "
+                      "converged Ritz values than ZNAUPD got.  This "
+                      "indicates the user probably made an error in passing "
+                      "data from ZNAUPD to ZNEUPD or that the data was "
+                      "modified before entering ZNEUPD"
+                 }
+
+CNEUPD_ERRORS = ZNEUPD_ERRORS.copy()
+CNEUPD_ERRORS[-14] = ("CNAUPD did not find any eigenvalues to sufficient "
+                      "accuracy.")
+CNEUPD_ERRORS[-15] = ("CNEUPD got a different count of the number of "
+                      "converged Ritz values than CNAUPD got.  This indicates "
+                      "the user probably made an error in passing data from "
+                      "CNAUPD to CNEUPD or that the data was modified before "
+                      "entering CNEUPD")
+
+DSEUPD_ERRORS = {
+    0: "Normal exit.",
+    -1: "N must be positive.",
+    -2: "NEV must be positive.",
+    -3: "NCV must be greater than NEV and less than or equal to N.",
+    -5: "WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'.",
+    -6: "BMAT must be one of 'I' or 'G'.",
+    -7: "Length of private work WORKL array is not sufficient.",
+    -8: ("Error return from trid. eigenvalue calculation; "
+         "Information error from LAPACK routine dsteqr."),
+    -9: "Starting vector is zero.",
+    -10: "IPARAM(7) must be 1,2,3,4,5.",
+    -11: "IPARAM(7) = 1 and BMAT = 'G' are incompatible.",
+    -12: "NEV and WHICH = 'BE' are incompatible.",
+    -14: "DSAUPD  did not find any eigenvalues to sufficient accuracy.",
+    -15: "HOWMNY must be one of 'A' or 'S' if RVEC = .true.",
+    -16: "HOWMNY = 'S' not yet implemented",
+    -17: ("DSEUPD  got a different count of the number of converged "
+          "Ritz values than DSAUPD  got.  This indicates the user "
+          "probably made an error in passing data from DSAUPD  to "
+          "DSEUPD  or that the data was modified before entering  "
+          "DSEUPD.")
+}
+
+SSEUPD_ERRORS = DSEUPD_ERRORS.copy()
+SSEUPD_ERRORS[-14] = ("SSAUPD  did not find any eigenvalues "
+                      "to sufficient accuracy.")
+SSEUPD_ERRORS[-17] = ("SSEUPD  got a different count of the number of "
+                      "converged "
+                      "Ritz values than SSAUPD  got.  This indicates the user "
+                      "probably made an error in passing data from SSAUPD  to "
+                      "SSEUPD  or that the data was modified before entering  "
+                      "SSEUPD.")
+
+_SAUPD_ERRORS = {'d': DSAUPD_ERRORS,
+                 's': SSAUPD_ERRORS}
+_NAUPD_ERRORS = {'d': DNAUPD_ERRORS,
+                 's': SNAUPD_ERRORS,
+                 'z': ZNAUPD_ERRORS,
+                 'c': CNAUPD_ERRORS}
+_SEUPD_ERRORS = {'d': DSEUPD_ERRORS,
+                 's': SSEUPD_ERRORS}
+_NEUPD_ERRORS = {'d': DNEUPD_ERRORS,
+                 's': SNEUPD_ERRORS,
+                 'z': ZNEUPD_ERRORS,
+                 'c': CNEUPD_ERRORS}
+
+# accepted values of parameter WHICH in _SEUPD
+_SEUPD_WHICH = ['LM', 'SM', 'LA', 'SA', 'BE']
+
+# accepted values of parameter WHICH in _NAUPD
+_NEUPD_WHICH = ['LM', 'SM', 'LR', 'SR', 'LI', 'SI']
+
+
+class ArpackError(RuntimeError):
+    """
+    ARPACK error
+    """
+
+    def __init__(self, info, infodict=None):
+        if infodict is None:
+            infodict = _NAUPD_ERRORS
+
+        msg = infodict.get(info, "Unknown error")
+        super().__init__(f"ARPACK error {info}: {msg}")
+
+
+class ArpackNoConvergence(ArpackError):
+    """
+    ARPACK iteration did not converge
+
+    Attributes
+    ----------
+    eigenvalues : ndarray
+        Partial result. Converged eigenvalues.
+    eigenvectors : ndarray
+        Partial result. Converged eigenvectors.
+
+    """
+
+    def __init__(self, msg, eigenvalues, eigenvectors):
+        ArpackError.__init__(self, -1, {-1: msg})
+        self.eigenvalues = eigenvalues
+        self.eigenvectors = eigenvectors
+
+
+def choose_ncv(k):
+    """
+    Choose number of lanczos vectors based on target number
+    of singular/eigen values and vectors to compute, k.
+    """
+    return max(2 * k + 1, 20)
+
+
+class _ArpackParams:
+    def __init__(self, n, k, tp, mode=1, sigma=None,
+                 ncv=None, v0=None, maxiter=None, which="LM", tol=0):
+        if k <= 0:
+            raise ValueError("k must be positive, k=%d" % k)
+
+        if maxiter is None:
+            maxiter = n * 10
+        if maxiter <= 0:
+            raise ValueError("maxiter must be positive, maxiter=%d" % maxiter)
+
+        if tp not in 'fdFD':
+            # Use `float64` libraries from integer dtypes.
+            if np.can_cast(tp, 'd'):
+                tp = 'd'
+            else:
+                raise ValueError("matrix type must be 'f', 'd', 'F', or 'D'")
+
+        if v0 is not None:
+            # ARPACK overwrites its initial resid,  make a copy
+            self.resid = np.array(v0, copy=True)
+            info = 1
+        else:
+            # ARPACK will use a random initial vector.
+            self.resid = np.zeros(n, tp)
+            info = 0
+
+        if sigma is None:
+            #sigma not used
+            self.sigma = 0
+        else:
+            self.sigma = sigma
+
+        if ncv is None:
+            ncv = choose_ncv(k)
+        ncv = min(ncv, n)
+
+        self.v = np.zeros((n, ncv), tp)  # holds Ritz vectors
+        self.iparam = np.zeros(11, arpack_int)
+
+        # set solver mode and parameters
+        ishfts = 1
+        self.mode = mode
+        self.iparam[0] = ishfts
+        self.iparam[2] = maxiter
+        self.iparam[3] = 1
+        self.iparam[6] = mode
+
+        self.n = n
+        self.tol = tol
+        self.k = k
+        self.maxiter = maxiter
+        self.ncv = ncv
+        self.which = which
+        self.tp = tp
+        self.info = info
+
+        self.converged = False
+        self.ido = 0
+
+    def _raise_no_convergence(self):
+        msg = "No convergence (%d iterations, %d/%d eigenvectors converged)"
+        k_ok = self.iparam[4]
+        num_iter = self.iparam[2]
+        try:
+            ev, vec = self.extract(True)
+        except ArpackError as err:
+            msg = f"{msg} [{err}]"
+            ev = np.zeros((0,))
+            vec = np.zeros((self.n, 0))
+            k_ok = 0
+        raise ArpackNoConvergence(msg % (num_iter, k_ok, self.k), ev, vec)
+
+
+class _SymmetricArpackParams(_ArpackParams):
+    def __init__(self, n, k, tp, matvec, mode=1, M_matvec=None,
+                 Minv_matvec=None, sigma=None,
+                 ncv=None, v0=None, maxiter=None, which="LM", tol=0):
+        # The following modes are supported:
+        #  mode = 1:
+        #    Solve the standard eigenvalue problem:
+        #      A*x = lambda*x :
+        #       A - symmetric
+        #    Arguments should be
+        #       matvec      = left multiplication by A
+        #       M_matvec    = None [not used]
+        #       Minv_matvec = None [not used]
+        #
+        #  mode = 2:
+        #    Solve the general eigenvalue problem:
+        #      A*x = lambda*M*x
+        #       A - symmetric
+        #       M - symmetric positive definite
+        #    Arguments should be
+        #       matvec      = left multiplication by A
+        #       M_matvec    = left multiplication by M
+        #       Minv_matvec = left multiplication by M^-1
+        #
+        #  mode = 3:
+        #    Solve the general eigenvalue problem in shift-invert mode:
+        #      A*x = lambda*M*x
+        #       A - symmetric
+        #       M - symmetric positive semi-definite
+        #    Arguments should be
+        #       matvec      = None [not used]
+        #       M_matvec    = left multiplication by M
+        #                     or None, if M is the identity
+        #       Minv_matvec = left multiplication by [A-sigma*M]^-1
+        #
+        #  mode = 4:
+        #    Solve the general eigenvalue problem in Buckling mode:
+        #      A*x = lambda*AG*x
+        #       A  - symmetric positive semi-definite
+        #       AG - symmetric indefinite
+        #    Arguments should be
+        #       matvec      = left multiplication by A
+        #       M_matvec    = None [not used]
+        #       Minv_matvec = left multiplication by [A-sigma*AG]^-1
+        #
+        #  mode = 5:
+        #    Solve the general eigenvalue problem in Cayley-transformed mode:
+        #      A*x = lambda*M*x
+        #       A - symmetric
+        #       M - symmetric positive semi-definite
+        #    Arguments should be
+        #       matvec      = left multiplication by A
+        #       M_matvec    = left multiplication by M
+        #                     or None, if M is the identity
+        #       Minv_matvec = left multiplication by [A-sigma*M]^-1
+        if mode == 1:
+            if matvec is None:
+                raise ValueError("matvec must be specified for mode=1")
+            if M_matvec is not None:
+                raise ValueError("M_matvec cannot be specified for mode=1")
+            if Minv_matvec is not None:
+                raise ValueError("Minv_matvec cannot be specified for mode=1")
+
+            self.OP = matvec
+            self.B = lambda x: x
+            self.bmat = 'I'
+        elif mode == 2:
+            if matvec is None:
+                raise ValueError("matvec must be specified for mode=2")
+            if M_matvec is None:
+                raise ValueError("M_matvec must be specified for mode=2")
+            if Minv_matvec is None:
+                raise ValueError("Minv_matvec must be specified for mode=2")
+
+            self.OP = lambda x: Minv_matvec(matvec(x))
+            self.OPa = Minv_matvec
+            self.OPb = matvec
+            self.B = M_matvec
+            self.bmat = 'G'
+        elif mode == 3:
+            if matvec is not None:
+                raise ValueError("matvec must not be specified for mode=3")
+            if Minv_matvec is None:
+                raise ValueError("Minv_matvec must be specified for mode=3")
+
+            if M_matvec is None:
+                self.OP = Minv_matvec
+                self.OPa = Minv_matvec
+                self.B = lambda x: x
+                self.bmat = 'I'
+            else:
+                self.OP = lambda x: Minv_matvec(M_matvec(x))
+                self.OPa = Minv_matvec
+                self.B = M_matvec
+                self.bmat = 'G'
+        elif mode == 4:
+            if matvec is None:
+                raise ValueError("matvec must be specified for mode=4")
+            if M_matvec is not None:
+                raise ValueError("M_matvec must not be specified for mode=4")
+            if Minv_matvec is None:
+                raise ValueError("Minv_matvec must be specified for mode=4")
+            self.OPa = Minv_matvec
+            self.OP = lambda x: self.OPa(matvec(x))
+            self.B = matvec
+            self.bmat = 'G'
+        elif mode == 5:
+            if matvec is None:
+                raise ValueError("matvec must be specified for mode=5")
+            if Minv_matvec is None:
+                raise ValueError("Minv_matvec must be specified for mode=5")
+
+            self.OPa = Minv_matvec
+            self.A_matvec = matvec
+
+            if M_matvec is None:
+                self.OP = lambda x: Minv_matvec(matvec(x) + sigma * x)
+                self.B = lambda x: x
+                self.bmat = 'I'
+            else:
+                self.OP = lambda x: Minv_matvec(matvec(x)
+                                                + sigma * M_matvec(x))
+                self.B = M_matvec
+                self.bmat = 'G'
+        else:
+            raise ValueError("mode=%i not implemented" % mode)
+
+        if which not in _SEUPD_WHICH:
+            raise ValueError(f"which must be one of {' '.join(_SEUPD_WHICH)}")
+        if k >= n:
+            raise ValueError("k must be less than ndim(A), k=%d" % k)
+
+        _ArpackParams.__init__(self, n, k, tp, mode, sigma,
+                               ncv, v0, maxiter, which, tol)
+
+        if self.ncv > n or self.ncv <= k:
+            raise ValueError(f"ncv must be k= n - 1:
+            raise ValueError("k must be less than ndim(A)-1, k=%d" % k)
+
+        _ArpackParams.__init__(self, n, k, tp, mode, sigma,
+                               ncv, v0, maxiter, which, tol)
+
+        if self.ncv > n or self.ncv <= k + 1:
+            raise ValueError(f"ncv must be k+1 k, so we'll
+                            # throw out this case.
+                            nreturned -= 1
+                    i += 1
+
+            else:
+                # real matrix, mode 3 or 4, imag(sigma) is nonzero:
+                # see remark 3 in neupd.f
+                # Build complex eigenvalues from real and imaginary parts
+                i = 0
+                while i <= k:
+                    if abs(d[i].imag) == 0:
+                        d[i] = np.dot(zr[:, i], self.matvec(zr[:, i]))
+                    else:
+                        if i < k:
+                            z[:, i] = zr[:, i] + 1.0j * zr[:, i + 1]
+                            z[:, i + 1] = z[:, i].conjugate()
+                            d[i] = ((np.dot(zr[:, i],
+                                            self.matvec(zr[:, i]))
+                                     + np.dot(zr[:, i + 1],
+                                              self.matvec(zr[:, i + 1])))
+                                    + 1j * (np.dot(zr[:, i],
+                                                   self.matvec(zr[:, i + 1]))
+                                            - np.dot(zr[:, i + 1],
+                                                     self.matvec(zr[:, i]))))
+                            d[i + 1] = d[i].conj()
+                            i += 1
+                        else:
+                            #last eigenvalue is complex: the imaginary part of
+                            # the eigenvector has not been returned
+                            #this can only happen if nreturned > k, so we'll
+                            # throw out this case.
+                            nreturned -= 1
+                    i += 1
+
+            # Now we have k+1 possible eigenvalues and eigenvectors
+            # Return the ones specified by the keyword "which"
+
+            if nreturned <= k:
+                # we got less or equal as many eigenvalues we wanted
+                d = d[:nreturned]
+                z = z[:, :nreturned]
+            else:
+                # we got one extra eigenvalue (likely a cc pair, but which?)
+                if self.mode in (1, 2):
+                    rd = d
+                elif self.mode in (3, 4):
+                    rd = 1 / (d - self.sigma)
+
+                if self.which in ['LR', 'SR']:
+                    ind = np.argsort(rd.real)
+                elif self.which in ['LI', 'SI']:
+                    # for LI,SI ARPACK returns largest,smallest
+                    # abs(imaginary) (complex pairs come together)
+                    ind = np.argsort(abs(rd.imag))
+                else:
+                    ind = np.argsort(abs(rd))
+
+                if self.which in ['LR', 'LM', 'LI']:
+                    ind = ind[-k:][::-1]
+                elif self.which in ['SR', 'SM', 'SI']:
+                    ind = ind[:k]
+
+                d = d[ind]
+                z = z[:, ind]
+        else:
+            # complex is so much simpler...
+            d, z, ierr =\
+                    self._arpack_extract(return_eigenvectors,
+                           howmny, sselect, self.sigma, workev,
+                           self.bmat, self.which, k, self.tol, self.resid,
+                           self.v, self.iparam, self.ipntr,
+                           self.workd, self.workl, self.rwork, ierr)
+
+            if ierr != 0:
+                raise ArpackError(ierr, infodict=self.extract_infodict)
+
+            k_ok = self.iparam[4]
+            d = d[:k_ok]
+            z = z[:, :k_ok]
+
+        if return_eigenvectors:
+            return d, z
+        else:
+            return d
+
+class SpLuInv(LinearOperator):
+    """
+    SpLuInv:
+       helper class to repeatedly solve M*x=b
+       using a sparse LU-decomposition of M
+    """
+
+    def __init__(self, M):
+        self.M_lu = splu(M)
+        self.shape = M.shape
+        self.dtype = M.dtype
+        self.isreal = not np.issubdtype(self.dtype, np.complexfloating)
+
+    def _matvec(self, x):
+        # careful here: splu.solve will throw away imaginary
+        # part of x if M is real
+        x = np.asarray(x)
+        if self.isreal and np.issubdtype(x.dtype, np.complexfloating):
+            return (self.M_lu.solve(np.real(x).astype(self.dtype))
+                    + 1j * self.M_lu.solve(np.imag(x).astype(self.dtype)))
+        else:
+            return self.M_lu.solve(x.astype(self.dtype))
+
+
+class LuInv(LinearOperator):
+    """
+    LuInv:
+       helper class to repeatedly solve M*x=b
+       using an LU-decomposition of M
+    """
+
+    def __init__(self, M):
+        self.M_lu = lu_factor(M)
+        self.shape = M.shape
+        self.dtype = M.dtype
+
+    def _matvec(self, x):
+        return lu_solve(self.M_lu, x)
+
+
+def gmres_loose(A, b, tol):
+    """
+    gmres with looser termination condition.
+    """
+    b = np.asarray(b)
+    min_tol = 1000 * np.sqrt(b.size) * np.finfo(b.dtype).eps
+    return gmres(A, b, rtol=max(tol, min_tol), atol=0)
+
+
+class IterInv(LinearOperator):
+    """
+    IterInv:
+       helper class to repeatedly solve M*x=b
+       using an iterative method.
+    """
+
+    def __init__(self, M, ifunc=gmres_loose, tol=0):
+        self.M = M
+        if hasattr(M, 'dtype'):
+            self.dtype = M.dtype
+        else:
+            x = np.zeros(M.shape[1])
+            self.dtype = (M * x).dtype
+        self.shape = M.shape
+
+        if tol <= 0:
+            # when tol=0, ARPACK uses machine tolerance as calculated
+            # by LAPACK's _LAMCH function.  We should match this
+            tol = 2 * np.finfo(self.dtype).eps
+        self.ifunc = ifunc
+        self.tol = tol
+
+    def _matvec(self, x):
+        b, info = self.ifunc(self.M, x, tol=self.tol)
+        if info != 0:
+            raise ValueError("Error in inverting M: function "
+                             "%s did not converge (info = %i)."
+                             % (self.ifunc.__name__, info))
+        return b
+
+
+class IterOpInv(LinearOperator):
+    """
+    IterOpInv:
+       helper class to repeatedly solve [A-sigma*M]*x = b
+       using an iterative method
+    """
+
+    def __init__(self, A, M, sigma, ifunc=gmres_loose, tol=0):
+        self.A = A
+        self.M = M
+        self.sigma = sigma
+
+        def mult_func(x):
+            return A.matvec(x) - sigma * M.matvec(x)
+
+        def mult_func_M_None(x):
+            return A.matvec(x) - sigma * x
+
+        x = np.zeros(A.shape[1])
+        if M is None:
+            dtype = mult_func_M_None(x).dtype
+            self.OP = LinearOperator(self.A.shape,
+                                     mult_func_M_None,
+                                     dtype=dtype)
+        else:
+            dtype = mult_func(x).dtype
+            self.OP = LinearOperator(self.A.shape,
+                                     mult_func,
+                                     dtype=dtype)
+        self.shape = A.shape
+
+        if tol <= 0:
+            # when tol=0, ARPACK uses machine tolerance as calculated
+            # by LAPACK's _LAMCH function.  We should match this
+            tol = 2 * np.finfo(self.OP.dtype).eps
+        self.ifunc = ifunc
+        self.tol = tol
+
+    def _matvec(self, x):
+        b, info = self.ifunc(self.OP, x, tol=self.tol)
+        if info != 0:
+            raise ValueError("Error in inverting [A-sigma*M]: function "
+                             "%s did not converge (info = %i)."
+                             % (self.ifunc.__name__, info))
+        return b
+
+    @property
+    def dtype(self):
+        return self.OP.dtype
+
+
+def _fast_spmatrix_to_csc(A, hermitian=False):
+    """Convert sparse matrix to CSC (by transposing, if possible)"""
+    if (A.format == "csr" and hermitian
+            and not np.issubdtype(A.dtype, np.complexfloating)):
+        return A.T
+    elif is_pydata_spmatrix(A):
+        # No need to convert
+        return A
+    else:
+        return A.tocsc()
+
+
+def get_inv_matvec(M, hermitian=False, tol=0):
+    if isdense(M):
+        return LuInv(M).matvec
+    elif issparse(M) or is_pydata_spmatrix(M):
+        M = _fast_spmatrix_to_csc(M, hermitian=hermitian)
+        return SpLuInv(M).matvec
+    else:
+        return IterInv(M, tol=tol).matvec
+
+
+def get_OPinv_matvec(A, M, sigma, hermitian=False, tol=0):
+    if sigma == 0:
+        return get_inv_matvec(A, hermitian=hermitian, tol=tol)
+
+    if M is None:
+        #M is the identity matrix
+        if isdense(A):
+            if (np.issubdtype(A.dtype, np.complexfloating)
+                    or np.imag(sigma) == 0):
+                A = np.copy(A)
+            else:
+                A = A + 0j
+            A.flat[::A.shape[1] + 1] -= sigma
+            return LuInv(A).matvec
+        elif issparse(A) or is_pydata_spmatrix(A):
+            A = A - sigma * eye(A.shape[0])
+            A = _fast_spmatrix_to_csc(A, hermitian=hermitian)
+            return SpLuInv(A).matvec
+        else:
+            return IterOpInv(aslinearoperator(A),
+                             M, sigma, tol=tol).matvec
+    else:
+        if ((not isdense(A) and not issparse(A) and not is_pydata_spmatrix(A)) or
+                (not isdense(M) and not issparse(M) and not is_pydata_spmatrix(A))):
+            return IterOpInv(aslinearoperator(A),
+                             aslinearoperator(M),
+                             sigma, tol=tol).matvec
+        elif isdense(A) or isdense(M):
+            return LuInv(A - sigma * M).matvec
+        else:
+            OP = A - sigma * M
+            OP = _fast_spmatrix_to_csc(OP, hermitian=hermitian)
+            return SpLuInv(OP).matvec
+
+
+# ARPACK is not threadsafe or reentrant (SAVE variables), so we need a
+# lock and a re-entering check.
+_ARPACK_LOCK = ReentrancyLock("Nested calls to eigs/eighs not allowed: "
+                              "ARPACK is not re-entrant")
+
+
+def eigs(A, k=6, M=None, sigma=None, which='LM', v0=None,
+         ncv=None, maxiter=None, tol=0, return_eigenvectors=True,
+         Minv=None, OPinv=None, OPpart=None):
+    """
+    Find k eigenvalues and eigenvectors of the square matrix A.
+
+    Solves ``A @ x[i] = w[i] * x[i]``, the standard eigenvalue problem
+    for w[i] eigenvalues with corresponding eigenvectors x[i].
+
+    If M is specified, solves ``A @ x[i] = w[i] * M @ x[i]``, the
+    generalized eigenvalue problem for w[i] eigenvalues
+    with corresponding eigenvectors x[i]
+
+    Parameters
+    ----------
+    A : ndarray, sparse matrix or LinearOperator
+        An array, sparse matrix, or LinearOperator representing
+        the operation ``A @ x``, where A is a real or complex square matrix.
+    k : int, optional
+        The number of eigenvalues and eigenvectors desired.
+        `k` must be smaller than N-1. It is not possible to compute all
+        eigenvectors of a matrix.
+    M : ndarray, sparse matrix or LinearOperator, optional
+        An array, sparse matrix, or LinearOperator representing
+        the operation M@x for the generalized eigenvalue problem
+
+            A @ x = w * M @ x.
+
+        M must represent a real symmetric matrix if A is real, and must
+        represent a complex Hermitian matrix if A is complex. For best
+        results, the data type of M should be the same as that of A.
+        Additionally:
+
+            If `sigma` is None, M is positive definite
+
+            If sigma is specified, M is positive semi-definite
+
+        If sigma is None, eigs requires an operator to compute the solution
+        of the linear equation ``M @ x = b``.  This is done internally via a
+        (sparse) LU decomposition for an explicit matrix M, or via an
+        iterative solver for a general linear operator.  Alternatively,
+        the user can supply the matrix or operator Minv, which gives
+        ``x = Minv @ b = M^-1 @ b``.
+    sigma : real or complex, optional
+        Find eigenvalues near sigma using shift-invert mode.  This requires
+        an operator to compute the solution of the linear system
+        ``[A - sigma * M] @ x = b``, where M is the identity matrix if
+        unspecified. This is computed internally via a (sparse) LU
+        decomposition for explicit matrices A & M, or via an iterative
+        solver if either A or M is a general linear operator.
+        Alternatively, the user can supply the matrix or operator OPinv,
+        which gives ``x = OPinv @ b = [A - sigma * M]^-1 @ b``.
+        For a real matrix A, shift-invert can either be done in imaginary
+        mode or real mode, specified by the parameter OPpart ('r' or 'i').
+        Note that when sigma is specified, the keyword 'which' (below)
+        refers to the shifted eigenvalues ``w'[i]`` where:
+
+            If A is real and OPpart == 'r' (default),
+              ``w'[i] = 1/2 * [1/(w[i]-sigma) + 1/(w[i]-conj(sigma))]``.
+
+            If A is real and OPpart == 'i',
+              ``w'[i] = 1/2i * [1/(w[i]-sigma) - 1/(w[i]-conj(sigma))]``.
+
+            If A is complex, ``w'[i] = 1/(w[i]-sigma)``.
+
+    v0 : ndarray, optional
+        Starting vector for iteration.
+        Default: random
+    ncv : int, optional
+        The number of Lanczos vectors generated
+        `ncv` must be greater than `k`; it is recommended that ``ncv > 2*k``.
+        Default: ``min(n, max(2*k + 1, 20))``
+    which : str, ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'], optional
+        Which `k` eigenvectors and eigenvalues to find:
+
+            'LM' : largest magnitude
+
+            'SM' : smallest magnitude
+
+            'LR' : largest real part
+
+            'SR' : smallest real part
+
+            'LI' : largest imaginary part
+
+            'SI' : smallest imaginary part
+
+        When sigma != None, 'which' refers to the shifted eigenvalues w'[i]
+        (see discussion in 'sigma', above).  ARPACK is generally better
+        at finding large values than small values.  If small eigenvalues are
+        desired, consider using shift-invert mode for better performance.
+    maxiter : int, optional
+        Maximum number of Arnoldi update iterations allowed
+        Default: ``n*10``
+    tol : float, optional
+        Relative accuracy for eigenvalues (stopping criterion)
+        The default value of 0 implies machine precision.
+    return_eigenvectors : bool, optional
+        Return eigenvectors (True) in addition to eigenvalues
+    Minv : ndarray, sparse matrix or LinearOperator, optional
+        See notes in M, above.
+    OPinv : ndarray, sparse matrix or LinearOperator, optional
+        See notes in sigma, above.
+    OPpart : {'r' or 'i'}, optional
+        See notes in sigma, above
+
+    Returns
+    -------
+    w : ndarray
+        Array of k eigenvalues.
+    v : ndarray
+        An array of `k` eigenvectors.
+        ``v[:, i]`` is the eigenvector corresponding to the eigenvalue w[i].
+
+    Raises
+    ------
+    ArpackNoConvergence
+        When the requested convergence is not obtained.
+        The currently converged eigenvalues and eigenvectors can be found
+        as ``eigenvalues`` and ``eigenvectors`` attributes of the exception
+        object.
+
+    See Also
+    --------
+    eigsh : eigenvalues and eigenvectors for symmetric matrix A
+    svds : singular value decomposition for a matrix A
+
+    Notes
+    -----
+    This function is a wrapper to the ARPACK [1]_ SNEUPD, DNEUPD, CNEUPD,
+    ZNEUPD, functions which use the Implicitly Restarted Arnoldi Method to
+    find the eigenvalues and eigenvectors [2]_.
+
+    References
+    ----------
+    .. [1] ARPACK Software, https://github.com/opencollab/arpack-ng
+    .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang,  ARPACK USERS GUIDE:
+       Solution of Large Scale Eigenvalue Problems by Implicitly Restarted
+       Arnoldi Methods. SIAM, Philadelphia, PA, 1998.
+
+    Examples
+    --------
+    Find 6 eigenvectors of the identity matrix:
+
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import eigs
+    >>> id = np.eye(13)
+    >>> vals, vecs = eigs(id, k=6)
+    >>> vals
+    array([ 1.+0.j,  1.+0.j,  1.+0.j,  1.+0.j,  1.+0.j,  1.+0.j])
+    >>> vecs.shape
+    (13, 6)
+
+    """
+    A = convert_pydata_sparse_to_scipy(A)
+    M = convert_pydata_sparse_to_scipy(M)
+    if A.shape[0] != A.shape[1]:
+        raise ValueError(f'expected square matrix (shape={A.shape})')
+    if M is not None:
+        if M.shape != A.shape:
+            raise ValueError(f'wrong M dimensions {M.shape}, should be {A.shape}')
+        if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower():
+            warnings.warn('M does not have the same type precision as A. '
+                          'This may adversely affect ARPACK convergence',
+                          stacklevel=2)
+
+    n = A.shape[0]
+
+    if k <= 0:
+        raise ValueError("k=%d must be greater than 0." % k)
+
+    if k >= n - 1:
+        warnings.warn("k >= N - 1 for N * N square matrix. "
+                      "Attempting to use scipy.linalg.eig instead.",
+                      RuntimeWarning, stacklevel=2)
+
+        if issparse(A):
+            raise TypeError("Cannot use scipy.linalg.eig for sparse A with "
+                            "k >= N - 1. Use scipy.linalg.eig(A.toarray()) or"
+                            " reduce k.")
+        if isinstance(A, LinearOperator):
+            raise TypeError("Cannot use scipy.linalg.eig for LinearOperator "
+                            "A with k >= N - 1.")
+        if isinstance(M, LinearOperator):
+            raise TypeError("Cannot use scipy.linalg.eig for LinearOperator "
+                            "M with k >= N - 1.")
+
+        return eig(A, b=M, right=return_eigenvectors)
+
+    if sigma is None:
+        matvec = aslinearoperator(A).matvec
+
+        if OPinv is not None:
+            raise ValueError("OPinv should not be specified "
+                             "with sigma = None.")
+        if OPpart is not None:
+            raise ValueError("OPpart should not be specified with "
+                             "sigma = None or complex A")
+
+        if M is None:
+            #standard eigenvalue problem
+            mode = 1
+            M_matvec = None
+            Minv_matvec = None
+            if Minv is not None:
+                raise ValueError("Minv should not be "
+                                 "specified with M = None.")
+        else:
+            #general eigenvalue problem
+            mode = 2
+            if Minv is None:
+                Minv_matvec = get_inv_matvec(M, hermitian=True, tol=tol)
+            else:
+                Minv = aslinearoperator(Minv)
+                Minv_matvec = Minv.matvec
+            M_matvec = aslinearoperator(M).matvec
+    else:
+        #sigma is not None: shift-invert mode
+        if np.issubdtype(A.dtype, np.complexfloating):
+            if OPpart is not None:
+                raise ValueError("OPpart should not be specified "
+                                 "with sigma=None or complex A")
+            mode = 3
+        elif OPpart is None or OPpart.lower() == 'r':
+            mode = 3
+        elif OPpart.lower() == 'i':
+            if np.imag(sigma) == 0:
+                raise ValueError("OPpart cannot be 'i' if sigma is real")
+            mode = 4
+        else:
+            raise ValueError("OPpart must be one of ('r','i')")
+
+        matvec = aslinearoperator(A).matvec
+        if Minv is not None:
+            raise ValueError("Minv should not be specified when sigma is")
+        if OPinv is None:
+            Minv_matvec = get_OPinv_matvec(A, M, sigma,
+                                           hermitian=False, tol=tol)
+        else:
+            OPinv = aslinearoperator(OPinv)
+            Minv_matvec = OPinv.matvec
+        if M is None:
+            M_matvec = None
+        else:
+            M_matvec = aslinearoperator(M).matvec
+
+    params = _UnsymmetricArpackParams(n, k, A.dtype.char, matvec, mode,
+                                      M_matvec, Minv_matvec, sigma,
+                                      ncv, v0, maxiter, which, tol)
+
+    with _ARPACK_LOCK:
+        while not params.converged:
+            params.iterate()
+
+        return params.extract(return_eigenvectors)
+
+
+def eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None,
+          ncv=None, maxiter=None, tol=0, return_eigenvectors=True,
+          Minv=None, OPinv=None, mode='normal'):
+    """
+    Find k eigenvalues and eigenvectors of the real symmetric square matrix
+    or complex Hermitian matrix A.
+
+    Solves ``A @ x[i] = w[i] * x[i]``, the standard eigenvalue problem for
+    w[i] eigenvalues with corresponding eigenvectors x[i].
+
+    If M is specified, solves ``A @ x[i] = w[i] * M @ x[i]``, the
+    generalized eigenvalue problem for w[i] eigenvalues
+    with corresponding eigenvectors x[i].
+
+    Note that there is no specialized routine for the case when A is a complex
+    Hermitian matrix. In this case, ``eigsh()`` will call ``eigs()`` and return the
+    real parts of the eigenvalues thus obtained.
+
+    Parameters
+    ----------
+    A : ndarray, sparse matrix or LinearOperator
+        A square operator representing the operation ``A @ x``, where ``A`` is
+        real symmetric or complex Hermitian. For buckling mode (see below)
+        ``A`` must additionally be positive-definite.
+    k : int, optional
+        The number of eigenvalues and eigenvectors desired.
+        `k` must be smaller than N. It is not possible to compute all
+        eigenvectors of a matrix.
+
+    Returns
+    -------
+    w : array
+        Array of k eigenvalues.
+    v : array
+        An array representing the `k` eigenvectors.  The column ``v[:, i]`` is
+        the eigenvector corresponding to the eigenvalue ``w[i]``.
+
+    Other Parameters
+    ----------------
+    M : An N x N matrix, array, sparse matrix, or linear operator representing
+        the operation ``M @ x`` for the generalized eigenvalue problem
+
+            A @ x = w * M @ x.
+
+        M must represent a real symmetric matrix if A is real, and must
+        represent a complex Hermitian matrix if A is complex. For best
+        results, the data type of M should be the same as that of A.
+        Additionally:
+
+            If sigma is None, M is symmetric positive definite.
+
+            If sigma is specified, M is symmetric positive semi-definite.
+
+            In buckling mode, M is symmetric indefinite.
+
+        If sigma is None, eigsh requires an operator to compute the solution
+        of the linear equation ``M @ x = b``. This is done internally via a
+        (sparse) LU decomposition for an explicit matrix M, or via an
+        iterative solver for a general linear operator.  Alternatively,
+        the user can supply the matrix or operator Minv, which gives
+        ``x = Minv @ b = M^-1 @ b``.
+    sigma : real
+        Find eigenvalues near sigma using shift-invert mode.  This requires
+        an operator to compute the solution of the linear system
+        ``[A - sigma * M] x = b``, where M is the identity matrix if
+        unspecified.  This is computed internally via a (sparse) LU
+        decomposition for explicit matrices A & M, or via an iterative
+        solver if either A or M is a general linear operator.
+        Alternatively, the user can supply the matrix or operator OPinv,
+        which gives ``x = OPinv @ b = [A - sigma * M]^-1 @ b``.
+        Note that when sigma is specified, the keyword 'which' refers to
+        the shifted eigenvalues ``w'[i]`` where:
+
+            if mode == 'normal', ``w'[i] = 1 / (w[i] - sigma)``.
+
+            if mode == 'cayley', ``w'[i] = (w[i] + sigma) / (w[i] - sigma)``.
+
+            if mode == 'buckling', ``w'[i] = w[i] / (w[i] - sigma)``.
+
+        (see further discussion in 'mode' below)
+    v0 : ndarray, optional
+        Starting vector for iteration.
+        Default: random
+    ncv : int, optional
+        The number of Lanczos vectors generated ncv must be greater than k and
+        smaller than n; it is recommended that ``ncv > 2*k``.
+        Default: ``min(n, max(2*k + 1, 20))``
+    which : str ['LM' | 'SM' | 'LA' | 'SA' | 'BE']
+        If A is a complex Hermitian matrix, 'BE' is invalid.
+        Which `k` eigenvectors and eigenvalues to find:
+
+            'LM' : Largest (in magnitude) eigenvalues.
+
+            'SM' : Smallest (in magnitude) eigenvalues.
+
+            'LA' : Largest (algebraic) eigenvalues.
+
+            'SA' : Smallest (algebraic) eigenvalues.
+
+            'BE' : Half (k/2) from each end of the spectrum.
+
+        When k is odd, return one more (k/2+1) from the high end.
+        When sigma != None, 'which' refers to the shifted eigenvalues ``w'[i]``
+        (see discussion in 'sigma', above).  ARPACK is generally better
+        at finding large values than small values.  If small eigenvalues are
+        desired, consider using shift-invert mode for better performance.
+    maxiter : int, optional
+        Maximum number of Arnoldi update iterations allowed.
+        Default: ``n*10``
+    tol : float
+        Relative accuracy for eigenvalues (stopping criterion).
+        The default value of 0 implies machine precision.
+    Minv : N x N matrix, array, sparse matrix, or LinearOperator
+        See notes in M, above.
+    OPinv : N x N matrix, array, sparse matrix, or LinearOperator
+        See notes in sigma, above.
+    return_eigenvectors : bool
+        Return eigenvectors (True) in addition to eigenvalues.
+        This value determines the order in which eigenvalues are sorted.
+        The sort order is also dependent on the `which` variable.
+
+            For which = 'LM' or 'SA':
+                If `return_eigenvectors` is True, eigenvalues are sorted by
+                algebraic value.
+
+                If `return_eigenvectors` is False, eigenvalues are sorted by
+                absolute value.
+
+            For which = 'BE' or 'LA':
+                eigenvalues are always sorted by algebraic value.
+
+            For which = 'SM':
+                If `return_eigenvectors` is True, eigenvalues are sorted by
+                algebraic value.
+
+                If `return_eigenvectors` is False, eigenvalues are sorted by
+                decreasing absolute value.
+
+    mode : string ['normal' | 'buckling' | 'cayley']
+        Specify strategy to use for shift-invert mode.  This argument applies
+        only for real-valued A and sigma != None.  For shift-invert mode,
+        ARPACK internally solves the eigenvalue problem
+        ``OP @ x'[i] = w'[i] * B @ x'[i]``
+        and transforms the resulting Ritz vectors x'[i] and Ritz values w'[i]
+        into the desired eigenvectors and eigenvalues of the problem
+        ``A @ x[i] = w[i] * M @ x[i]``.
+        The modes are as follows:
+
+            'normal' :
+                OP = [A - sigma * M]^-1 @ M,
+                B = M,
+                w'[i] = 1 / (w[i] - sigma)
+
+            'buckling' :
+                OP = [A - sigma * M]^-1 @ A,
+                B = A,
+                w'[i] = w[i] / (w[i] - sigma)
+
+            'cayley' :
+                OP = [A - sigma * M]^-1 @ [A + sigma * M],
+                B = M,
+                w'[i] = (w[i] + sigma) / (w[i] - sigma)
+
+        The choice of mode will affect which eigenvalues are selected by
+        the keyword 'which', and can also impact the stability of
+        convergence (see [2] for a discussion).
+
+    Raises
+    ------
+    ArpackNoConvergence
+        When the requested convergence is not obtained.
+
+        The currently converged eigenvalues and eigenvectors can be found
+        as ``eigenvalues`` and ``eigenvectors`` attributes of the exception
+        object.
+
+    See Also
+    --------
+    eigs : eigenvalues and eigenvectors for a general (nonsymmetric) matrix A
+    svds : singular value decomposition for a matrix A
+
+    Notes
+    -----
+    This function is a wrapper to the ARPACK [1]_ SSEUPD and DSEUPD
+    functions which use the Implicitly Restarted Lanczos Method to
+    find the eigenvalues and eigenvectors [2]_.
+
+    References
+    ----------
+    .. [1] ARPACK Software, https://github.com/opencollab/arpack-ng
+    .. [2] R. B. Lehoucq, D. C. Sorensen, and C. Yang,  ARPACK USERS GUIDE:
+       Solution of Large Scale Eigenvalue Problems by Implicitly Restarted
+       Arnoldi Methods. SIAM, Philadelphia, PA, 1998.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import eigsh
+    >>> identity = np.eye(13)
+    >>> eigenvalues, eigenvectors = eigsh(identity, k=6)
+    >>> eigenvalues
+    array([1., 1., 1., 1., 1., 1.])
+    >>> eigenvectors.shape
+    (13, 6)
+
+    """
+    # complex Hermitian matrices should be solved with eigs
+    if np.issubdtype(A.dtype, np.complexfloating):
+        if mode != 'normal':
+            raise ValueError(f"mode={mode} cannot be used with complex matrix A")
+        if which == 'BE':
+            raise ValueError("which='BE' cannot be used with complex matrix A")
+        elif which == 'LA':
+            which = 'LR'
+        elif which == 'SA':
+            which = 'SR'
+        ret = eigs(A, k, M=M, sigma=sigma, which=which, v0=v0,
+                   ncv=ncv, maxiter=maxiter, tol=tol,
+                   return_eigenvectors=return_eigenvectors, Minv=Minv,
+                   OPinv=OPinv)
+
+        if return_eigenvectors:
+            return ret[0].real, ret[1]
+        else:
+            return ret.real
+
+    if A.shape[0] != A.shape[1]:
+        raise ValueError(f'expected square matrix (shape={A.shape})')
+    if M is not None:
+        if M.shape != A.shape:
+            raise ValueError(f'wrong M dimensions {M.shape}, should be {A.shape}')
+        if np.dtype(M.dtype).char.lower() != np.dtype(A.dtype).char.lower():
+            warnings.warn('M does not have the same type precision as A. '
+                          'This may adversely affect ARPACK convergence',
+                          stacklevel=2)
+
+    n = A.shape[0]
+
+    if k <= 0:
+        raise ValueError("k must be greater than 0.")
+
+    if k >= n:
+        warnings.warn("k >= N for N * N square matrix. "
+                      "Attempting to use scipy.linalg.eigh instead.",
+                      RuntimeWarning, stacklevel=2)
+
+        if issparse(A):
+            raise TypeError("Cannot use scipy.linalg.eigh for sparse A with "
+                            "k >= N. Use scipy.linalg.eigh(A.toarray()) or"
+                            " reduce k.")
+        if isinstance(A, LinearOperator):
+            raise TypeError("Cannot use scipy.linalg.eigh for LinearOperator "
+                            "A with k >= N.")
+        if isinstance(M, LinearOperator):
+            raise TypeError("Cannot use scipy.linalg.eigh for LinearOperator "
+                            "M with k >= N.")
+
+        return eigh(A, b=M, eigvals_only=not return_eigenvectors)
+
+    if sigma is None:
+        A = aslinearoperator(A)
+        matvec = A.matvec
+
+        if OPinv is not None:
+            raise ValueError("OPinv should not be specified "
+                             "with sigma = None.")
+        if M is None:
+            #standard eigenvalue problem
+            mode = 1
+            M_matvec = None
+            Minv_matvec = None
+            if Minv is not None:
+                raise ValueError("Minv should not be "
+                                 "specified with M = None.")
+        else:
+            #general eigenvalue problem
+            mode = 2
+            if Minv is None:
+                Minv_matvec = get_inv_matvec(M, hermitian=True, tol=tol)
+            else:
+                Minv = aslinearoperator(Minv)
+                Minv_matvec = Minv.matvec
+            M_matvec = aslinearoperator(M).matvec
+    else:
+        # sigma is not None: shift-invert mode
+        if Minv is not None:
+            raise ValueError("Minv should not be specified when sigma is")
+
+        # normal mode
+        if mode == 'normal':
+            mode = 3
+            matvec = None
+            if OPinv is None:
+                Minv_matvec = get_OPinv_matvec(A, M, sigma,
+                                               hermitian=True, tol=tol)
+            else:
+                OPinv = aslinearoperator(OPinv)
+                Minv_matvec = OPinv.matvec
+            if M is None:
+                M_matvec = None
+            else:
+                M = aslinearoperator(M)
+                M_matvec = M.matvec
+
+        # buckling mode
+        elif mode == 'buckling':
+            mode = 4
+            if OPinv is None:
+                Minv_matvec = get_OPinv_matvec(A, M, sigma,
+                                               hermitian=True, tol=tol)
+            else:
+                Minv_matvec = aslinearoperator(OPinv).matvec
+            matvec = aslinearoperator(A).matvec
+            M_matvec = None
+
+        # cayley-transform mode
+        elif mode == 'cayley':
+            mode = 5
+            matvec = aslinearoperator(A).matvec
+            if OPinv is None:
+                Minv_matvec = get_OPinv_matvec(A, M, sigma,
+                                               hermitian=True, tol=tol)
+            else:
+                Minv_matvec = aslinearoperator(OPinv).matvec
+            if M is None:
+                M_matvec = None
+            else:
+                M_matvec = aslinearoperator(M).matvec
+
+        # unrecognized mode
+        else:
+            raise ValueError(f"unrecognized mode '{mode}'")
+
+    params = _SymmetricArpackParams(n, k, A.dtype.char, matvec, mode,
+                                    M_matvec, Minv_matvec, sigma,
+                                    ncv, v0, maxiter, which, tol)
+
+    with _ARPACK_LOCK:
+        while not params.converged:
+            params.iterate()
+
+        return params.extract(return_eigenvectors)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/tests/test_arpack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/tests/test_arpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..e962798a9ffce0b380c17cdf1f9deb4d6fa83159
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/arpack/tests/test_arpack.py
@@ -0,0 +1,717 @@
+__usage__ = """
+To run tests locally:
+  python tests/test_arpack.py [-l] [-v]
+
+"""
+
+import threading
+import itertools
+
+import numpy as np
+
+from numpy.testing import assert_allclose, assert_equal, suppress_warnings
+from pytest import raises as assert_raises
+import pytest
+
+from numpy import dot, conj, random
+from scipy.linalg import eig, eigh
+from scipy.sparse import csc_array, csr_array, diags_array, random_array
+from scipy.sparse.linalg import LinearOperator, aslinearoperator
+from scipy.sparse.linalg._eigen.arpack import (eigs, eigsh, arpack,
+                                              ArpackNoConvergence)
+
+
+from scipy._lib._gcutils import assert_deallocated, IS_PYPY
+
+
+# precision for tests
+_ndigits = {'f': 3, 'd': 11, 'F': 3, 'D': 11}
+
+
+def _get_test_tolerance(type_char, mattype=None, D_type=None, which=None):
+    """
+    Return tolerance values suitable for a given test:
+
+    Parameters
+    ----------
+    type_char : {'f', 'd', 'F', 'D'}
+        Data type in ARPACK eigenvalue problem
+    mattype : {csr_array, aslinearoperator, asarray}, optional
+        Linear operator type
+
+    Returns
+    -------
+    tol
+        Tolerance to pass to the ARPACK routine
+    rtol
+        Relative tolerance for outputs
+    atol
+        Absolute tolerance for outputs
+
+    """
+
+    rtol = {'f': 3000 * np.finfo(np.float32).eps,
+            'F': 3000 * np.finfo(np.float32).eps,
+            'd': 2000 * np.finfo(np.float64).eps,
+            'D': 2000 * np.finfo(np.float64).eps}[type_char]
+    atol = rtol
+    tol = 0
+
+    if mattype is aslinearoperator and type_char in ('f', 'F'):
+        # iterative methods in single precision: worse errors
+        # also: bump ARPACK tolerance so that the iterative method converges
+        tol = 30 * np.finfo(np.float32).eps
+        rtol *= 5
+
+    if (
+        isinstance(mattype, type) and issubclass(mattype, csr_array)
+        and type_char in ('f', 'F')
+    ):
+        # sparse in single precision: worse errors
+        rtol *= 5
+
+    if (
+        which in ('LM', 'SM', 'LA')
+        and D_type.name == "gen-hermitian-Mc"
+    ):
+        if type_char == 'F':
+            # missing case 1, 2, and more, from PR 14798
+            rtol *= 5
+
+        if type_char == 'D':
+            # missing more cases, from PR 14798
+            rtol *= 10
+            atol *= 10
+
+    return tol, rtol, atol
+
+
+def generate_matrix(N, complex_=False, hermitian=False,
+                    pos_definite=False, sparse=False, rng=None):
+    M = rng.random((N, N))
+    if complex_:
+        M = M + 1j * rng.random((N, N))
+
+    if hermitian:
+        if pos_definite:
+            if sparse:
+                i = np.arange(N)
+                j = rng.randint(N, size=N-2)
+                i, j = np.meshgrid(i, j)
+                M[i, j] = 0
+            M = np.dot(M.conj(), M.T)
+        else:
+            M = np.dot(M.conj(), M.T)
+            if sparse:
+                i = rng.randint(N, size=N * N // 4)
+                j = rng.randint(N, size=N * N // 4)
+                ind = np.nonzero(i == j)
+                j[ind] = (j[ind] + 1) % N
+                M[i, j] = 0
+                M[j, i] = 0
+    else:
+        if sparse:
+            i = rng.randint(N, size=N * N // 2)
+            j = rng.randint(N, size=N * N // 2)
+            M[i, j] = 0
+    return M
+
+
+def generate_matrix_symmetric(N, pos_definite=False, sparse=False, rng=None):
+    M = rng.random((N, N))
+
+    M = 0.5 * (M + M.T)  # Make M symmetric
+
+    if pos_definite:
+        Id = N * np.eye(N)
+        if sparse:
+            M = csr_array(M)
+        M += Id
+    else:
+        if sparse:
+            M = csr_array(M)
+
+    return M
+
+
+def assert_allclose_cc(actual, desired, **kw):
+    """Almost equal or complex conjugates almost equal"""
+    try:
+        assert_allclose(actual, desired, **kw)
+    except AssertionError:
+        assert_allclose(actual, conj(desired), **kw)
+
+
+def argsort_which(eigenvalues, typ, k, which,
+                  sigma=None, OPpart=None, mode=None):
+    """Return sorted indices of eigenvalues using the "which" keyword
+    from eigs and eigsh"""
+    if sigma is None:
+        reval = np.round(eigenvalues, decimals=_ndigits[typ])
+    else:
+        if mode is None or mode == 'normal':
+            if OPpart is None:
+                reval = 1. / (eigenvalues - sigma)
+            elif OPpart == 'r':
+                reval = 0.5 * (1. / (eigenvalues - sigma)
+                               + 1. / (eigenvalues - np.conj(sigma)))
+            elif OPpart == 'i':
+                reval = -0.5j * (1. / (eigenvalues - sigma)
+                                 - 1. / (eigenvalues - np.conj(sigma)))
+        elif mode == 'cayley':
+            reval = (eigenvalues + sigma) / (eigenvalues - sigma)
+        elif mode == 'buckling':
+            reval = eigenvalues / (eigenvalues - sigma)
+        else:
+            raise ValueError(f"mode='{mode}' not recognized")
+
+        reval = np.round(reval, decimals=_ndigits[typ])
+
+    if which in ['LM', 'SM']:
+        ind = np.argsort(abs(reval))
+    elif which in ['LR', 'SR', 'LA', 'SA', 'BE']:
+        ind = np.argsort(np.real(reval))
+    elif which in ['LI', 'SI']:
+        # for LI,SI ARPACK returns largest,smallest abs(imaginary) why?
+        if typ.islower():
+            ind = np.argsort(abs(np.imag(reval)))
+        else:
+            ind = np.argsort(np.imag(reval))
+    else:
+        raise ValueError(f"which='{which}' is unrecognized")
+
+    if which in ['LM', 'LA', 'LR', 'LI']:
+        return ind[-k:]
+    elif which in ['SM', 'SA', 'SR', 'SI']:
+        return ind[:k]
+    elif which == 'BE':
+        return np.concatenate((ind[:k//2], ind[k//2-k:]))
+
+
+def eval_evec(symmetric, d, typ, k, which, v0=None, sigma=None,
+              mattype=np.asarray, OPpart=None, mode='normal'):
+    general = ('bmat' in d)
+
+    if symmetric:
+        eigs_func = eigsh
+    else:
+        eigs_func = eigs
+
+    if general:
+        err = (f"error for {eigs_func.__name__}:general, typ={typ}, which={which}, "
+               f"sigma={sigma}, mattype={mattype.__name__},"
+               f" OPpart={OPpart}, mode={mode}")
+    else:
+        err = (f"error for {eigs_func.__name__}:standard, typ={typ}, which={which}, "
+               f"sigma={sigma}, mattype={mattype.__name__}, "
+               f"OPpart={OPpart}, mode={mode}")
+
+    a = d['mat'].astype(typ)
+    ac = mattype(a)
+
+    if general:
+        b = d['bmat'].astype(typ)
+        bc = mattype(b)
+
+    # get exact eigenvalues
+    exact_eval = d['eval'].astype(typ.upper())
+    ind = argsort_which(exact_eval, typ, k, which,
+                        sigma, OPpart, mode)
+    exact_eval = exact_eval[ind]
+
+    # compute arpack eigenvalues
+    kwargs = dict(which=which, v0=v0, sigma=sigma)
+    if eigs_func is eigsh:
+        kwargs['mode'] = mode
+    else:
+        kwargs['OPpart'] = OPpart
+
+    # compute suitable tolerances
+    kwargs['tol'], rtol, atol = _get_test_tolerance(typ, mattype, d, which)
+    # on rare occasions, ARPACK routines return results that are proper
+    # eigenvalues and -vectors, but not necessarily the ones requested in
+    # the parameter which. This is inherent to the Krylov methods, and
+    # should not be treated as a failure. If such a rare situation
+    # occurs, the calculation is tried again (but at most a few times).
+    ntries = 0
+    while ntries < 5:
+        # solve
+        if general:
+            try:
+                eigenvalues, evec = eigs_func(ac, k, bc, **kwargs)
+            except ArpackNoConvergence:
+                kwargs['maxiter'] = 20*a.shape[0]
+                eigenvalues, evec = eigs_func(ac, k, bc, **kwargs)
+        else:
+            try:
+                eigenvalues, evec = eigs_func(ac, k, **kwargs)
+            except ArpackNoConvergence:
+                kwargs['maxiter'] = 20*a.shape[0]
+                eigenvalues, evec = eigs_func(ac, k, **kwargs)
+
+        ind = argsort_which(eigenvalues, typ, k, which,
+                            sigma, OPpart, mode)
+        eigenvalues = eigenvalues[ind]
+        evec = evec[:, ind]
+
+        try:
+            # check eigenvalues
+            assert_allclose_cc(eigenvalues, exact_eval, rtol=rtol, atol=atol,
+                               err_msg=err)
+            check_evecs = True
+        except AssertionError:
+            check_evecs = False
+            ntries += 1
+
+        if check_evecs:
+            # check eigenvectors
+            LHS = np.dot(a, evec)
+            if general:
+                RHS = eigenvalues * np.dot(b, evec)
+            else:
+                RHS = eigenvalues * evec
+
+            assert_allclose(LHS, RHS, rtol=rtol, atol=atol, err_msg=err)
+            break
+
+    # check eigenvalues
+    assert_allclose_cc(eigenvalues, exact_eval, rtol=rtol, atol=atol, err_msg=err)
+
+
+class DictWithRepr(dict):
+    def __init__(self, name):
+        self.name = name
+
+    def __repr__(self):
+        return f"<{self.name}>"
+
+
+class SymmetricParams:
+    def __init__(self):
+        self.eigs = eigsh
+        self.which = ['LM', 'SM', 'LA', 'SA', 'BE']
+        self.mattypes = [csr_array, aslinearoperator, np.asarray]
+        self.sigmas_modes = {None: ['normal'],
+                             0.5: ['normal', 'buckling', 'cayley']}
+
+        # generate matrices
+        # these should all be float32 so that the eigenvalues
+        # are the same in float32 and float64
+        N = 6
+        rng = np.random.RandomState(2300)
+        Ar = generate_matrix(N, hermitian=True,
+                             pos_definite=True,
+                             rng=rng).astype('f').astype('d')
+        M = generate_matrix(N, hermitian=True,
+                            pos_definite=True,
+                            rng=rng).astype('f').astype('d')
+        Ac = generate_matrix(N, hermitian=True, pos_definite=True,
+                             complex_=True, rng=rng).astype('F').astype('D')
+        Mc = generate_matrix(N, hermitian=True, pos_definite=True,
+                             complex_=True, rng=rng).astype('F').astype('D')
+        v0 = rng.random(N)
+
+        # standard symmetric problem
+        SS = DictWithRepr("std-symmetric")
+        SS['mat'] = Ar
+        SS['v0'] = v0
+        SS['eval'] = eigh(SS['mat'], eigvals_only=True)
+
+        # general symmetric problem
+        GS = DictWithRepr("gen-symmetric")
+        GS['mat'] = Ar
+        GS['bmat'] = M
+        GS['v0'] = v0
+        GS['eval'] = eigh(GS['mat'], GS['bmat'], eigvals_only=True)
+
+        # standard hermitian problem
+        SH = DictWithRepr("std-hermitian")
+        SH['mat'] = Ac
+        SH['v0'] = v0
+        SH['eval'] = eigh(SH['mat'], eigvals_only=True)
+
+        # general hermitian problem
+        GH = DictWithRepr("gen-hermitian")
+        GH['mat'] = Ac
+        GH['bmat'] = M
+        GH['v0'] = v0
+        GH['eval'] = eigh(GH['mat'], GH['bmat'], eigvals_only=True)
+
+        # general hermitian problem with hermitian M
+        GHc = DictWithRepr("gen-hermitian-Mc")
+        GHc['mat'] = Ac
+        GHc['bmat'] = Mc
+        GHc['v0'] = v0
+        GHc['eval'] = eigh(GHc['mat'], GHc['bmat'], eigvals_only=True)
+
+        self.real_test_cases = [SS, GS]
+        self.complex_test_cases = [SH, GH, GHc]
+
+
+class NonSymmetricParams:
+    def __init__(self):
+        self.eigs = eigs
+        self.which = ['LM', 'LR', 'LI']  # , 'SM', 'LR', 'SR', 'LI', 'SI']
+        self.mattypes = [csr_array, aslinearoperator, np.asarray]
+        self.sigmas_OPparts = {None: [None],
+                               0.1: ['r'],
+                               0.1 + 0.1j: ['r', 'i']}
+
+        # generate matrices
+        # these should all be float32 so that the eigenvalues
+        # are the same in float32 and float64
+        N = 6
+        rng = np.random.RandomState(2300)
+        Ar = generate_matrix(N, rng=rng).astype('f').astype('d')
+        M = generate_matrix(N, hermitian=True,
+                            pos_definite=True, rng=rng).astype('f').astype('d')
+        Ac = generate_matrix(N, complex_=True, rng=rng).astype('F').astype('D')
+        v0 = rng.random(N)
+
+        # standard real nonsymmetric problem
+        SNR = DictWithRepr("std-real-nonsym")
+        SNR['mat'] = Ar
+        SNR['v0'] = v0
+        SNR['eval'] = eig(SNR['mat'], left=False, right=False)
+
+        # general real nonsymmetric problem
+        GNR = DictWithRepr("gen-real-nonsym")
+        GNR['mat'] = Ar
+        GNR['bmat'] = M
+        GNR['v0'] = v0
+        GNR['eval'] = eig(GNR['mat'], GNR['bmat'], left=False, right=False)
+
+        # standard complex nonsymmetric problem
+        SNC = DictWithRepr("std-cmplx-nonsym")
+        SNC['mat'] = Ac
+        SNC['v0'] = v0
+        SNC['eval'] = eig(SNC['mat'], left=False, right=False)
+
+        # general complex nonsymmetric problem
+        GNC = DictWithRepr("gen-cmplx-nonsym")
+        GNC['mat'] = Ac
+        GNC['bmat'] = M
+        GNC['v0'] = v0
+        GNC['eval'] = eig(GNC['mat'], GNC['bmat'], left=False, right=False)
+
+        self.real_test_cases = [SNR, GNR]
+        self.complex_test_cases = [SNC, GNC]
+
+
+@pytest.mark.iterations(1)
+@pytest.mark.thread_unsafe
+def test_symmetric_modes(num_parallel_threads):
+    assert num_parallel_threads == 1
+    params = SymmetricParams()
+    k = 2
+    symmetric = True
+    for D in params.real_test_cases:
+        for typ in 'fd':
+            for which in params.which:
+                for mattype in params.mattypes:
+                    for (sigma, modes) in params.sigmas_modes.items():
+                        for mode in modes:
+                            eval_evec(symmetric, D, typ, k, which,
+                                      None, sigma, mattype, None, mode)
+
+
+def test_hermitian_modes():
+    params = SymmetricParams()
+    k = 2
+    symmetric = True
+    for D in params.complex_test_cases:
+        for typ in 'FD':
+            for which in params.which:
+                if which == 'BE':
+                    continue  # BE invalid for complex
+                for mattype in params.mattypes:
+                    for sigma in params.sigmas_modes:
+                        eval_evec(symmetric, D, typ, k, which,
+                                  None, sigma, mattype)
+
+
+def test_symmetric_starting_vector():
+    params = SymmetricParams()
+    symmetric = True
+    for k in [1, 2, 3, 4, 5]:
+        for D in params.real_test_cases:
+            for typ in 'fd':
+                v0 = random.rand(len(D['v0'])).astype(typ)
+                eval_evec(symmetric, D, typ, k, 'LM', v0)
+
+
+def test_symmetric_no_convergence():
+    rng = np.random.RandomState(1234)
+    m = generate_matrix(30, hermitian=True, pos_definite=True, rng=rng)
+    tol, rtol, atol = _get_test_tolerance('d')
+    try:
+        w, v = eigsh(m, 4, which='LM', v0=m[:, 0], maxiter=5, tol=tol, ncv=9)
+        raise AssertionError("Spurious no-error exit")
+    except ArpackNoConvergence as err:
+        k = len(err.eigenvalues)
+        if k <= 0:
+            raise AssertionError("Spurious no-eigenvalues-found case") from err
+        w, v = err.eigenvalues, err.eigenvectors
+        assert_allclose(dot(m, v), w * v, rtol=rtol, atol=atol)
+
+
+def test_real_nonsymmetric_modes():
+    params = NonSymmetricParams()
+    k = 2
+    symmetric = False
+    for D in params.real_test_cases:
+        for typ in 'fd':
+            for which in params.which:
+                for mattype in params.mattypes:
+                    for sigma, OPparts in params.sigmas_OPparts.items():
+                        for OPpart in OPparts:
+                            eval_evec(symmetric, D, typ, k, which,
+                                      None, sigma, mattype, OPpart)
+
+
+def test_complex_nonsymmetric_modes():
+    params = NonSymmetricParams()
+    k = 2
+    symmetric = False
+    for D in params.complex_test_cases:
+        for typ in 'DF':
+            for which in params.which:
+                for mattype in params.mattypes:
+                    for sigma in params.sigmas_OPparts:
+                        eval_evec(symmetric, D, typ, k, which,
+                                  None, sigma, mattype)
+
+
+def test_standard_nonsymmetric_starting_vector():
+    params = NonSymmetricParams()
+    sigma = None
+    symmetric = False
+    for k in [1, 2, 3, 4]:
+        for d in params.complex_test_cases:
+            for typ in 'FD':
+                A = d['mat']
+                n = A.shape[0]
+                v0 = random.rand(n).astype(typ)
+                eval_evec(symmetric, d, typ, k, "LM", v0, sigma)
+
+
+def test_general_nonsymmetric_starting_vector():
+    params = NonSymmetricParams()
+    sigma = None
+    symmetric = False
+    for k in [1, 2, 3, 4]:
+        for d in params.complex_test_cases:
+            for typ in 'FD':
+                A = d['mat']
+                n = A.shape[0]
+                v0 = random.rand(n).astype(typ)
+                eval_evec(symmetric, d, typ, k, "LM", v0, sigma)
+
+
+def test_standard_nonsymmetric_no_convergence():
+    rng = np.random.RandomState(1234)
+    m = generate_matrix(30, complex_=True, rng=rng)
+    tol, rtol, atol = _get_test_tolerance('d')
+    try:
+        w, v = eigs(m, 4, which='LM', v0=m[:, 0], maxiter=5, tol=tol)
+        raise AssertionError("Spurious no-error exit")
+    except ArpackNoConvergence as err:
+        k = len(err.eigenvalues)
+        if k <= 0:
+            raise AssertionError("Spurious no-eigenvalues-found case") from err
+        w, v = err.eigenvalues, err.eigenvectors
+        for ww, vv in zip(w, v.T):
+            assert_allclose(dot(m, vv), ww * vv, rtol=rtol, atol=atol)
+
+
+def test_eigen_bad_shapes():
+    # A is not square.
+    A = csc_array(np.zeros((2, 3)))
+    assert_raises(ValueError, eigs, A)
+
+
+def test_eigen_bad_kwargs():
+    # Test eigen on wrong keyword argument
+    A = csc_array(np.zeros((8, 8)))
+    assert_raises(ValueError, eigs, A, which='XX')
+
+
+def test_ticket_1459_arpack_crash():
+    for dtype in [np.float32, np.float64]:
+        # This test does not seem to catch the issue for float32,
+        # but we made the same fix there, just to be sure
+
+        N = 6
+        k = 2
+
+        np.random.seed(2301)
+        A = np.random.random((N, N)).astype(dtype)
+        v0 = np.array([-0.71063568258907849895, -0.83185111795729227424,
+                       -0.34365925382227402451, 0.46122533684552280420,
+                       -0.58001341115969040629, -0.78844877570084292984e-01],
+                      dtype=dtype)
+
+        # Should not crash:
+        evals, evecs = eigs(A, k, v0=v0)
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_linearoperator_deallocation():
+    # Check that the linear operators used by the Arpack wrappers are
+    # deallocatable by reference counting -- they are big objects, so
+    # Python's cyclic GC may not collect them fast enough before
+    # running out of memory if eigs/eigsh are called in a tight loop.
+
+    M_d = np.eye(10)
+    M_s = csc_array(M_d)
+    M_o = aslinearoperator(M_d)
+
+    with assert_deallocated(lambda: arpack.SpLuInv(M_s)):
+        pass
+    with assert_deallocated(lambda: arpack.LuInv(M_d)):
+        pass
+    with assert_deallocated(lambda: arpack.IterInv(M_s)):
+        pass
+    with assert_deallocated(lambda: arpack.IterOpInv(M_o, None, 0.3)):
+        pass
+    with assert_deallocated(lambda: arpack.IterOpInv(M_o, M_o, 0.3)):
+        pass
+
+
+@pytest.mark.thread_unsafe
+def test_parallel_threads():
+    results = []
+    v0 = np.random.rand(50)
+
+    def worker():
+        x = diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(50, 50))
+        w, v = eigs(x, k=3, v0=v0)
+        results.append(w)
+
+        w, v = eigsh(x, k=3, v0=v0)
+        results.append(w)
+
+    threads = [threading.Thread(target=worker) for k in range(10)]
+    for t in threads:
+        t.start()
+    for t in threads:
+        t.join()
+
+    worker()
+
+    for r in results:
+        assert_allclose(r, results[-1])
+
+
+def test_reentering():
+    # Just some linear operator that calls eigs recursively
+    def A_matvec(x):
+        x = diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(50, 50))
+        w, v = eigs(x, k=1)
+        return v / w[0]
+    A = LinearOperator(matvec=A_matvec, dtype=float, shape=(50, 50))
+
+    # The Fortran code is not reentrant, so this fails (gracefully, not crashing)
+    assert_raises(RuntimeError, eigs, A, k=1)
+    assert_raises(RuntimeError, eigsh, A, k=1)
+
+
+def test_regression_arpackng_1315():
+    # Check that issue arpack-ng/#1315 is not present.
+    # Adapted from arpack-ng/TESTS/bug_1315_single.c
+    # If this fails, then the installed ARPACK library is faulty.
+
+    for dtype in [np.float32, np.float64]:
+        np.random.seed(1234)
+
+        w0 = np.arange(1, 1000+1).astype(dtype)
+        A = diags_array([w0], offsets=[0], shape=(1000, 1000))
+
+        v0 = np.random.rand(1000).astype(dtype)
+        w, v = eigs(A, k=9, ncv=2*9+1, which="LM", v0=v0)
+
+        assert_allclose(np.sort(w), np.sort(w0[-9:]),
+                        rtol=1e-4)
+
+
+def test_eigs_for_k_greater():
+    # Test eigs() for k beyond limits.
+    rng = np.random.RandomState(1234)
+    A_sparse = diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4))  # sparse
+    A = generate_matrix(4, sparse=False, rng=rng)
+    M_dense = rng.random((4, 4))
+    M_sparse = generate_matrix(4, sparse=True, rng=rng)
+    M_linop = aslinearoperator(M_dense)
+    eig_tuple1 = eig(A, b=M_dense)
+    eig_tuple2 = eig(A, b=M_sparse)
+
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning)
+
+        assert_equal(eigs(A, M=M_dense, k=3), eig_tuple1)
+        assert_equal(eigs(A, M=M_dense, k=4), eig_tuple1)
+        assert_equal(eigs(A, M=M_dense, k=5), eig_tuple1)
+        assert_equal(eigs(A, M=M_sparse, k=5), eig_tuple2)
+
+        # M as LinearOperator
+        assert_raises(TypeError, eigs, A, M=M_linop, k=3)
+
+        # Test 'A' for different types
+        assert_raises(TypeError, eigs, aslinearoperator(A), k=3)
+        assert_raises(TypeError, eigs, A_sparse, k=3)
+
+
+def test_eigsh_for_k_greater():
+    # Test eigsh() for k beyond limits.
+    rng = np.random.RandomState(1234)
+    A_sparse = diags_array([1, -2, 1], offsets=[-1, 0, 1], shape=(4, 4))  # sparse
+    A = generate_matrix(4, sparse=False, rng=rng)
+    M_dense = generate_matrix_symmetric(4, pos_definite=True, rng=rng)
+    M_sparse = generate_matrix_symmetric(
+        4, pos_definite=True, sparse=True, rng=rng)
+    M_linop = aslinearoperator(M_dense)
+    eig_tuple1 = eigh(A, b=M_dense)
+    eig_tuple2 = eigh(A, b=M_sparse)
+
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning)
+
+        assert_equal(eigsh(A, M=M_dense, k=4), eig_tuple1)
+        assert_equal(eigsh(A, M=M_dense, k=5), eig_tuple1)
+        assert_equal(eigsh(A, M=M_sparse, k=5), eig_tuple2)
+
+        # M as LinearOperator
+        assert_raises(TypeError, eigsh, A, M=M_linop, k=4)
+
+        # Test 'A' for different types
+        assert_raises(TypeError, eigsh, aslinearoperator(A), k=4)
+        assert_raises(TypeError, eigsh, A_sparse, M=M_dense, k=4)
+
+
+def test_real_eigs_real_k_subset():
+    rng = np.random.default_rng(2)
+
+    n = 10
+    A = random_array(shape=(n, n), density=0.5, rng=rng)
+    A.data *= 2
+    A.data -= 1
+    A += A.T  # make symmetric to test real eigenvalues
+
+    v0 = np.ones(n)
+
+    whichs = ['LM', 'SM', 'LR', 'SR', 'LI', 'SI']
+    dtypes = [np.float32, np.float64]
+
+    for which, sigma, dtype in itertools.product(whichs, [None, 0, 5], dtypes):
+        prev_w = np.array([], dtype=dtype)
+        eps = np.finfo(dtype).eps
+        for k in range(1, 9):
+            w, z = eigs(A.astype(dtype), k=k, which=which, sigma=sigma,
+                        v0=v0.astype(dtype), tol=0)
+            assert_allclose(np.linalg.norm(A.dot(z) - z * w), 0, atol=np.sqrt(eps))
+
+            # Check that the set of eigenvalues for `k` is a subset of that for `k+1`
+            dist = abs(prev_w[:,None] - w).min(axis=1)
+            assert_allclose(dist, 0, atol=np.sqrt(eps))
+
+            prev_w = w
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ab5330361a6bcc2a8403f9b3788aedae750d57f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__init__.py
@@ -0,0 +1,16 @@
+"""
+Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG)
+
+LOBPCG is a preconditioned eigensolver for large symmetric positive definite
+(SPD) generalized eigenproblems.
+
+Call the function lobpcg - see help for lobpcg.lobpcg.
+
+"""
+from .lobpcg import *
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6163c79201b4188d234277d9cfdbfe55f3547209
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__pycache__/lobpcg.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__pycache__/lobpcg.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9279abf1da7f4a0adcb9edc9d0e07466288f9041
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/__pycache__/lobpcg.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/lobpcg.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/lobpcg.py
new file mode 100644
index 0000000000000000000000000000000000000000..3bace8c76ccd11be7bb25f02806382a60ac5e9c7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/lobpcg.py
@@ -0,0 +1,1110 @@
+"""
+Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG).
+
+References
+----------
+.. [1] A. V. Knyazev (2001),
+       Toward the Optimal Preconditioned Eigensolver: Locally Optimal
+       Block Preconditioned Conjugate Gradient Method.
+       SIAM Journal on Scientific Computing 23, no. 2,
+       pp. 517-541. :doi:`10.1137/S1064827500366124`
+
+.. [2] A. V. Knyazev, I. Lashuk, M. E. Argentati, and E. Ovchinnikov (2007),
+       Block Locally Optimal Preconditioned Eigenvalue Xolvers (BLOPEX)
+       in hypre and PETSc.  :arxiv:`0705.2626`
+
+.. [3] A. V. Knyazev's C and MATLAB implementations:
+       https://github.com/lobpcg/blopex
+"""
+
+import warnings
+import numpy as np
+from scipy.linalg import (inv, eigh, cho_factor, cho_solve,
+                          cholesky, LinAlgError)
+from scipy.sparse.linalg import LinearOperator
+from scipy.sparse import issparse
+
+__all__ = ["lobpcg"]
+
+
+def _report_nonhermitian(M, name):
+    """
+    Report if `M` is not a Hermitian matrix given its type.
+    """
+    from scipy.linalg import norm
+
+    md = M - M.T.conj()
+    nmd = norm(md, 1)
+    tol = 10 * np.finfo(M.dtype).eps
+    tol = max(tol, tol * norm(M, 1))
+    if nmd > tol:
+        warnings.warn(
+              f"Matrix {name} of the type {M.dtype} is not Hermitian: "
+              f"condition: {nmd} < {tol} fails.",
+              UserWarning, stacklevel=4
+         )
+
+def _as2d(ar):
+    """
+    If the input array is 2D return it, if it is 1D, append a dimension,
+    making it a column vector.
+    """
+    if ar.ndim == 2:
+        return ar
+    else:  # Assume 1!
+        aux = np.asarray(ar)
+        aux.shape = (ar.shape[0], 1)
+        return aux
+
+
+def _makeMatMat(m):
+    if m is None:
+        return None
+    elif callable(m):
+        return lambda v: m(v)
+    else:
+        return lambda v: m @ v
+
+
+def _matmul_inplace(x, y, verbosityLevel=0):
+    """Perform 'np.matmul' in-place if possible.
+
+    If some sufficient conditions for inplace matmul are met, do so.
+    Otherwise try inplace update and fall back to overwrite if that fails.
+    """
+    if x.flags["CARRAY"] and x.shape[1] == y.shape[1] and x.dtype == y.dtype:
+        # conditions where we can guarantee that inplace updates will work;
+        # i.e. x is not a view/slice, x & y have compatible dtypes, and the
+        # shape of the result of x @ y matches the shape of x.
+        np.matmul(x, y, out=x)
+    else:
+        # ideally, we'd have an exhaustive list of conditions above when
+        # inplace updates are possible; since we don't, we opportunistically
+        # try if it works, and fall back to overwriting if necessary
+        try:
+            np.matmul(x, y, out=x)
+        except Exception:
+            if verbosityLevel:
+                warnings.warn(
+                    "Inplace update of x = x @ y failed, "
+                    "x needs to be overwritten.",
+                    UserWarning, stacklevel=3
+                )
+            x = x @ y
+    return x
+
+
+def _applyConstraints(blockVectorV, factYBY, blockVectorBY, blockVectorY):
+    """Changes blockVectorV in-place."""
+    YBV = blockVectorBY.T.conj() @ blockVectorV
+    tmp = cho_solve(factYBY, YBV)
+    blockVectorV -= blockVectorY @ tmp
+
+
+def _b_orthonormalize(B, blockVectorV, blockVectorBV=None,
+                      verbosityLevel=0):
+    """in-place B-orthonormalize the given block vector using Cholesky."""
+    if blockVectorBV is None:
+        if B is None:
+            blockVectorBV = blockVectorV
+        else:
+            try:
+                blockVectorBV = B(blockVectorV)
+            except Exception as e:
+                if verbosityLevel:
+                    warnings.warn(
+                        f"Secondary MatMul call failed with error\n"
+                        f"{e}\n",
+                        UserWarning, stacklevel=3
+                    )
+                    return None, None, None
+            if blockVectorBV.shape != blockVectorV.shape:
+                raise ValueError(
+                    f"The shape {blockVectorV.shape} "
+                    f"of the orthogonalized matrix not preserved\n"
+                    f"and changed to {blockVectorBV.shape} "
+                    f"after multiplying by the secondary matrix.\n"
+                )
+
+    VBV = blockVectorV.T.conj() @ blockVectorBV
+    try:
+        # VBV is a Cholesky factor from now on...
+        VBV = cholesky(VBV, overwrite_a=True)
+        VBV = inv(VBV, overwrite_a=True)
+        blockVectorV = _matmul_inplace(
+            blockVectorV, VBV,
+            verbosityLevel=verbosityLevel
+        )
+        if B is not None:
+            blockVectorBV = _matmul_inplace(
+                blockVectorBV, VBV,
+                verbosityLevel=verbosityLevel
+            )
+        return blockVectorV, blockVectorBV, VBV
+    except LinAlgError:
+        if verbosityLevel:
+            warnings.warn(
+                "Cholesky has failed.",
+                UserWarning, stacklevel=3
+            )
+        return None, None, None
+
+
+def _get_indx(_lambda, num, largest):
+    """Get `num` indices into `_lambda` depending on `largest` option."""
+    ii = np.argsort(_lambda)
+    if largest:
+        ii = ii[:-num - 1:-1]
+    else:
+        ii = ii[:num]
+
+    return ii
+
+
+def _handle_gramA_gramB_verbosity(gramA, gramB, verbosityLevel):
+    if verbosityLevel:
+        _report_nonhermitian(gramA, "gramA")
+        _report_nonhermitian(gramB, "gramB")
+
+
+def lobpcg(
+    A,
+    X,
+    B=None,
+    M=None,
+    Y=None,
+    tol=None,
+    maxiter=None,
+    largest=True,
+    verbosityLevel=0,
+    retLambdaHistory=False,
+    retResidualNormsHistory=False,
+    restartControl=20,
+):
+    """Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG).
+
+    LOBPCG is a preconditioned eigensolver for large real symmetric and complex
+    Hermitian definite generalized eigenproblems.
+
+    Parameters
+    ----------
+    A : {sparse matrix, ndarray, LinearOperator, callable object}
+        The Hermitian linear operator of the problem, usually given by a
+        sparse matrix.  Often called the "stiffness matrix".
+    X : ndarray, float32 or float64
+        Initial approximation to the ``k`` eigenvectors (non-sparse).
+        If `A` has ``shape=(n,n)`` then `X` must have ``shape=(n,k)``.
+    B : {sparse matrix, ndarray, LinearOperator, callable object}
+        Optional. By default ``B = None``, which is equivalent to identity.
+        The right hand side operator in a generalized eigenproblem if present.
+        Often called the "mass matrix". Must be Hermitian positive definite.
+    M : {sparse matrix, ndarray, LinearOperator, callable object}
+        Optional. By default ``M = None``, which is equivalent to identity.
+        Preconditioner aiming to accelerate convergence.
+    Y : ndarray, float32 or float64, default: None
+        An ``n-by-sizeY`` ndarray of constraints with ``sizeY < n``.
+        The iterations will be performed in the ``B``-orthogonal complement
+        of the column-space of `Y`. `Y` must be full rank if present.
+    tol : scalar, optional
+        The default is ``tol=n*sqrt(eps)``.
+        Solver tolerance for the stopping criterion.
+    maxiter : int, default: 20
+        Maximum number of iterations.
+    largest : bool, default: True
+        When True, solve for the largest eigenvalues, otherwise the smallest.
+    verbosityLevel : int, optional
+        By default ``verbosityLevel=0`` no output.
+        Controls the solver standard/screen output.
+    retLambdaHistory : bool, default: False
+        Whether to return iterative eigenvalue history.
+    retResidualNormsHistory : bool, default: False
+        Whether to return iterative history of residual norms.
+    restartControl : int, optional.
+        Iterations restart if the residuals jump ``2**restartControl`` times
+        compared to the smallest recorded in ``retResidualNormsHistory``.
+        The default is ``restartControl=20``, making the restarts rare for
+        backward compatibility.
+
+    Returns
+    -------
+    lambda : ndarray of the shape ``(k, )``.
+        Array of ``k`` approximate eigenvalues.
+    v : ndarray of the same shape as ``X.shape``.
+        An array of ``k`` approximate eigenvectors.
+    lambdaHistory : ndarray, optional.
+        The eigenvalue history, if `retLambdaHistory` is ``True``.
+    ResidualNormsHistory : ndarray, optional.
+        The history of residual norms, if `retResidualNormsHistory`
+        is ``True``.
+
+    Notes
+    -----
+    The iterative loop runs ``maxit=maxiter`` (20 if ``maxit=None``)
+    iterations at most and finishes earlier if the tolerance is met.
+    Breaking backward compatibility with the previous version, LOBPCG
+    now returns the block of iterative vectors with the best accuracy rather
+    than the last one iterated, as a cure for possible divergence.
+
+    If ``X.dtype == np.float32`` and user-provided operations/multiplications
+    by `A`, `B`, and `M` all preserve the ``np.float32`` data type,
+    all the calculations and the output are in ``np.float32``.
+
+    The size of the iteration history output equals to the number of the best
+    (limited by `maxit`) iterations plus 3: initial, final, and postprocessing.
+
+    If both `retLambdaHistory` and `retResidualNormsHistory` are ``True``,
+    the return tuple has the following format
+    ``(lambda, V, lambda history, residual norms history)``.
+
+    In the following ``n`` denotes the matrix size and ``k`` the number
+    of required eigenvalues (smallest or largest).
+
+    The LOBPCG code internally solves eigenproblems of the size ``3k`` on every
+    iteration by calling the dense eigensolver `eigh`, so if ``k`` is not
+    small enough compared to ``n``, it makes no sense to call the LOBPCG code.
+    Moreover, if one calls the LOBPCG algorithm for ``5k > n``, it would likely
+    break internally, so the code calls the standard function `eigh` instead.
+    It is not that ``n`` should be large for the LOBPCG to work, but rather the
+    ratio ``n / k`` should be large. It you call LOBPCG with ``k=1``
+    and ``n=10``, it works though ``n`` is small. The method is intended
+    for extremely large ``n / k``.
+
+    The convergence speed depends basically on three factors:
+
+    1. Quality of the initial approximations `X` to the seeking eigenvectors.
+       Randomly distributed around the origin vectors work well if no better
+       choice is known.
+
+    2. Relative separation of the desired eigenvalues from the rest
+       of the eigenvalues. One can vary ``k`` to improve the separation.
+
+    3. Proper preconditioning to shrink the spectral spread.
+       For example, a rod vibration test problem (under tests
+       directory) is ill-conditioned for large ``n``, so convergence will be
+       slow, unless efficient preconditioning is used. For this specific
+       problem, a good simple preconditioner function would be a linear solve
+       for `A`, which is easy to code since `A` is tridiagonal.
+
+    References
+    ----------
+    .. [1] A. V. Knyazev (2001),
+           Toward the Optimal Preconditioned Eigensolver: Locally Optimal
+           Block Preconditioned Conjugate Gradient Method.
+           SIAM Journal on Scientific Computing 23, no. 2,
+           pp. 517-541. :doi:`10.1137/S1064827500366124`
+
+    .. [2] A. V. Knyazev, I. Lashuk, M. E. Argentati, and E. Ovchinnikov
+           (2007), Block Locally Optimal Preconditioned Eigenvalue Xolvers
+           (BLOPEX) in hypre and PETSc. :arxiv:`0705.2626`
+
+    .. [3] A. V. Knyazev's C and MATLAB implementations:
+           https://github.com/lobpcg/blopex
+
+    Examples
+    --------
+    Our first example is minimalistic - find the largest eigenvalue of
+    a diagonal matrix by solving the non-generalized eigenvalue problem
+    ``A x = lambda x`` without constraints or preconditioning.
+
+    >>> import numpy as np
+    >>> from scipy.sparse import spdiags
+    >>> from scipy.sparse.linalg import LinearOperator, aslinearoperator
+    >>> from scipy.sparse.linalg import lobpcg
+
+    The square matrix size is
+
+    >>> n = 100
+
+    and its diagonal entries are 1, ..., 100 defined by
+
+    >>> vals = np.arange(1, n + 1).astype(np.int16)
+
+    The first mandatory input parameter in this test is
+    the sparse diagonal matrix `A`
+    of the eigenvalue problem ``A x = lambda x`` to solve.
+
+    >>> A = spdiags(vals, 0, n, n)
+    >>> A = A.astype(np.int16)
+    >>> A.toarray()
+    array([[  1,   0,   0, ...,   0,   0,   0],
+           [  0,   2,   0, ...,   0,   0,   0],
+           [  0,   0,   3, ...,   0,   0,   0],
+           ...,
+           [  0,   0,   0, ...,  98,   0,   0],
+           [  0,   0,   0, ...,   0,  99,   0],
+           [  0,   0,   0, ...,   0,   0, 100]], shape=(100, 100), dtype=int16)
+
+    The second mandatory input parameter `X` is a 2D array with the
+    row dimension determining the number of requested eigenvalues.
+    `X` is an initial guess for targeted eigenvectors.
+    `X` must have linearly independent columns.
+    If no initial approximations available, randomly oriented vectors
+    commonly work best, e.g., with components normally distributed
+    around zero or uniformly distributed on the interval [-1 1].
+    Setting the initial approximations to dtype ``np.float32``
+    forces all iterative values to dtype ``np.float32`` speeding up
+    the run while still allowing accurate eigenvalue computations.
+
+    >>> k = 1
+    >>> rng = np.random.default_rng()
+    >>> X = rng.normal(size=(n, k))
+    >>> X = X.astype(np.float32)
+
+    >>> eigenvalues, _ = lobpcg(A, X, maxiter=60)
+    >>> eigenvalues
+    array([100.], dtype=float32)
+
+    `lobpcg` needs only access the matrix product with `A` rather
+    then the matrix itself. Since the matrix `A` is diagonal in
+    this example, one can write a function of the matrix product
+    ``A @ X`` using the diagonal values ``vals`` only, e.g., by
+    element-wise multiplication with broadcasting in the lambda-function
+
+    >>> A_lambda = lambda X: vals[:, np.newaxis] * X
+
+    or the regular function
+
+    >>> def A_matmat(X):
+    ...     return vals[:, np.newaxis] * X
+
+    and use the handle to one of these callables as an input
+
+    >>> eigenvalues, _ = lobpcg(A_lambda, X, maxiter=60)
+    >>> eigenvalues
+    array([100.], dtype=float32)
+    >>> eigenvalues, _ = lobpcg(A_matmat, X, maxiter=60)
+    >>> eigenvalues
+    array([100.], dtype=float32)
+
+    The traditional callable `LinearOperator` is no longer
+    necessary but still supported as the input to `lobpcg`.
+    Specifying ``matmat=A_matmat`` explicitly improves performance. 
+
+    >>> A_lo = LinearOperator((n, n), matvec=A_matmat, matmat=A_matmat, dtype=np.int16)
+    >>> eigenvalues, _ = lobpcg(A_lo, X, maxiter=80)
+    >>> eigenvalues
+    array([100.], dtype=float32)
+
+    The least efficient callable option is `aslinearoperator`:
+
+    >>> eigenvalues, _ = lobpcg(aslinearoperator(A), X, maxiter=80)
+    >>> eigenvalues
+    array([100.], dtype=float32)
+
+    We now switch to computing the three smallest eigenvalues specifying
+
+    >>> k = 3
+    >>> X = np.random.default_rng().normal(size=(n, k))
+
+    and ``largest=False`` parameter
+
+    >>> eigenvalues, _ = lobpcg(A, X, largest=False, maxiter=90)
+    >>> print(eigenvalues)  
+    [1. 2. 3.]
+
+    The next example illustrates computing 3 smallest eigenvalues of
+    the same matrix `A` given by the function handle ``A_matmat`` but
+    with constraints and preconditioning.
+
+    Constraints - an optional input parameter is a 2D array comprising
+    of column vectors that the eigenvectors must be orthogonal to
+
+    >>> Y = np.eye(n, 3)
+
+    The preconditioner acts as the inverse of `A` in this example, but
+    in the reduced precision ``np.float32`` even though the initial `X`
+    and thus all iterates and the output are in full ``np.float64``.
+
+    >>> inv_vals = 1./vals
+    >>> inv_vals = inv_vals.astype(np.float32)
+    >>> M = lambda X: inv_vals[:, np.newaxis] * X
+
+    Let us now solve the eigenvalue problem for the matrix `A` first
+    without preconditioning requesting 80 iterations
+
+    >>> eigenvalues, _ = lobpcg(A_matmat, X, Y=Y, largest=False, maxiter=80)
+    >>> eigenvalues
+    array([4., 5., 6.])
+    >>> eigenvalues.dtype
+    dtype('float64')
+
+    With preconditioning we need only 20 iterations from the same `X`
+
+    >>> eigenvalues, _ = lobpcg(A_matmat, X, Y=Y, M=M, largest=False, maxiter=20)
+    >>> eigenvalues
+    array([4., 5., 6.])
+
+    Note that the vectors passed in `Y` are the eigenvectors of the 3
+    smallest eigenvalues. The results returned above are orthogonal to those.
+
+    The primary matrix `A` may be indefinite, e.g., after shifting
+    ``vals`` by 50 from 1, ..., 100 to -49, ..., 50, we still can compute
+    the 3 smallest or largest eigenvalues.
+
+    >>> vals = vals - 50
+    >>> X = rng.normal(size=(n, k))
+    >>> eigenvalues, _ = lobpcg(A_matmat, X, largest=False, maxiter=99)
+    >>> eigenvalues
+    array([-49., -48., -47.])
+    >>> eigenvalues, _ = lobpcg(A_matmat, X, largest=True, maxiter=99)
+    >>> eigenvalues
+    array([50., 49., 48.])
+
+    """
+    blockVectorX = X
+    bestblockVectorX = blockVectorX
+    blockVectorY = Y
+    residualTolerance = tol
+    if maxiter is None:
+        maxiter = 20
+
+    bestIterationNumber = maxiter
+
+    sizeY = 0
+    if blockVectorY is not None:
+        if len(blockVectorY.shape) != 2:
+            warnings.warn(
+                f"Expected rank-2 array for argument Y, instead got "
+                f"{len(blockVectorY.shape)}, "
+                f"so ignore it and use no constraints.",
+                UserWarning, stacklevel=2
+            )
+            blockVectorY = None
+        else:
+            sizeY = blockVectorY.shape[1]
+
+    # Block size.
+    if blockVectorX is None:
+        raise ValueError("The mandatory initial matrix X cannot be None")
+    if len(blockVectorX.shape) != 2:
+        raise ValueError("expected rank-2 array for argument X")
+
+    n, sizeX = blockVectorX.shape
+
+    # Data type of iterates, determined by X, must be inexact
+    if not np.issubdtype(blockVectorX.dtype, np.inexact):
+        warnings.warn(
+            f"Data type for argument X is {blockVectorX.dtype}, "
+            f"which is not inexact, so casted to np.float32.",
+            UserWarning, stacklevel=2
+        )
+        blockVectorX = np.asarray(blockVectorX, dtype=np.float32)
+
+    if retLambdaHistory:
+        lambdaHistory = np.zeros((maxiter + 3, sizeX),
+                                 dtype=blockVectorX.dtype)
+    if retResidualNormsHistory:
+        residualNormsHistory = np.zeros((maxiter + 3, sizeX),
+                                        dtype=blockVectorX.dtype)
+
+    if verbosityLevel:
+        aux = "Solving "
+        if B is None:
+            aux += "standard"
+        else:
+            aux += "generalized"
+        aux += " eigenvalue problem with"
+        if M is None:
+            aux += "out"
+        aux += " preconditioning\n\n"
+        aux += "matrix size %d\n" % n
+        aux += "block size %d\n\n" % sizeX
+        if blockVectorY is None:
+            aux += "No constraints\n\n"
+        else:
+            if sizeY > 1:
+                aux += "%d constraints\n\n" % sizeY
+            else:
+                aux += "%d constraint\n\n" % sizeY
+        print(aux)
+
+    if (n - sizeY) < (5 * sizeX):
+        warnings.warn(
+            f"The problem size {n} minus the constraints size {sizeY} "
+            f"is too small relative to the block size {sizeX}. "
+            f"Using a dense eigensolver instead of LOBPCG iterations."
+            f"No output of the history of the iterations.",
+            UserWarning, stacklevel=2
+        )
+
+        sizeX = min(sizeX, n)
+
+        if blockVectorY is not None:
+            raise NotImplementedError(
+                "The dense eigensolver does not support constraints."
+            )
+
+        # Define the closed range of indices of eigenvalues to return.
+        if largest:
+            eigvals = (n - sizeX, n - 1)
+        else:
+            eigvals = (0, sizeX - 1)
+
+        try:
+            if isinstance(A, LinearOperator):
+                A = A(np.eye(n, dtype=int))
+            elif callable(A):
+                A = A(np.eye(n, dtype=int))
+                if A.shape != (n, n):
+                    raise ValueError(
+                        f"The shape {A.shape} of the primary matrix\n"
+                        f"defined by a callable object is wrong.\n"
+                    )
+            elif issparse(A):
+                A = A.toarray()
+            else:
+                A = np.asarray(A)
+        except Exception as e:
+            raise Exception(
+                f"Primary MatMul call failed with error\n"
+                f"{e}\n")
+
+        if B is not None:
+            try:
+                if isinstance(B, LinearOperator):
+                    B = B(np.eye(n, dtype=int))
+                elif callable(B):
+                    B = B(np.eye(n, dtype=int))
+                    if B.shape != (n, n):
+                        raise ValueError(
+                            f"The shape {B.shape} of the secondary matrix\n"
+                            f"defined by a callable object is wrong.\n"
+                        )
+                elif issparse(B):
+                    B = B.toarray()
+                else:
+                    B = np.asarray(B)
+            except Exception as e:
+                raise Exception(
+                    f"Secondary MatMul call failed with error\n"
+                    f"{e}\n")
+
+        try:
+            vals, vecs = eigh(A,
+                              B,
+                              subset_by_index=eigvals,
+                              check_finite=False)
+            if largest:
+                # Reverse order to be compatible with eigs() in 'LM' mode.
+                vals = vals[::-1]
+                vecs = vecs[:, ::-1]
+
+            return vals, vecs
+        except Exception as e:
+            raise Exception(
+                f"Dense eigensolver failed with error\n"
+                f"{e}\n"
+            )
+
+    if (residualTolerance is None) or (residualTolerance <= 0.0):
+        residualTolerance = np.sqrt(np.finfo(blockVectorX.dtype).eps) * n
+
+    A = _makeMatMat(A)
+    B = _makeMatMat(B)
+    M = _makeMatMat(M)
+
+    # Apply constraints to X.
+    if blockVectorY is not None:
+
+        if B is not None:
+            blockVectorBY = B(blockVectorY)
+            if blockVectorBY.shape != blockVectorY.shape:
+                raise ValueError(
+                    f"The shape {blockVectorY.shape} "
+                    f"of the constraint not preserved\n"
+                    f"and changed to {blockVectorBY.shape} "
+                    f"after multiplying by the secondary matrix.\n"
+                )
+        else:
+            blockVectorBY = blockVectorY
+
+        # gramYBY is a dense array.
+        gramYBY = blockVectorY.T.conj() @ blockVectorBY
+        try:
+            # gramYBY is a Cholesky factor from now on...
+            gramYBY = cho_factor(gramYBY, overwrite_a=True)
+        except LinAlgError as e:
+            raise ValueError("Linearly dependent constraints") from e
+
+        _applyConstraints(blockVectorX, gramYBY, blockVectorBY, blockVectorY)
+
+    ##
+    # B-orthonormalize X.
+    blockVectorX, blockVectorBX, _ = _b_orthonormalize(
+        B, blockVectorX, verbosityLevel=verbosityLevel)
+    if blockVectorX is None:
+        raise ValueError("Linearly dependent initial approximations")
+
+    ##
+    # Compute the initial Ritz vectors: solve the eigenproblem.
+    blockVectorAX = A(blockVectorX)
+    if blockVectorAX.shape != blockVectorX.shape:
+        raise ValueError(
+            f"The shape {blockVectorX.shape} "
+            f"of the initial approximations not preserved\n"
+            f"and changed to {blockVectorAX.shape} "
+            f"after multiplying by the primary matrix.\n"
+        )
+
+    gramXAX = blockVectorX.T.conj() @ blockVectorAX
+
+    _lambda, eigBlockVector = eigh(gramXAX, check_finite=False)
+    ii = _get_indx(_lambda, sizeX, largest)
+    _lambda = _lambda[ii]
+    if retLambdaHistory:
+        lambdaHistory[0, :] = _lambda
+
+    eigBlockVector = np.asarray(eigBlockVector[:, ii])
+    blockVectorX = _matmul_inplace(
+        blockVectorX, eigBlockVector,
+        verbosityLevel=verbosityLevel
+    )
+    blockVectorAX = _matmul_inplace(
+        blockVectorAX, eigBlockVector,
+        verbosityLevel=verbosityLevel
+    )
+    if B is not None:
+        blockVectorBX = _matmul_inplace(
+            blockVectorBX, eigBlockVector,
+            verbosityLevel=verbosityLevel
+        )
+
+    ##
+    # Active index set.
+    activeMask = np.ones((sizeX,), dtype=bool)
+
+    ##
+    # Main iteration loop.
+
+    blockVectorP = None  # set during iteration
+    blockVectorAP = None
+    blockVectorBP = None
+
+    smallestResidualNorm = np.abs(np.finfo(blockVectorX.dtype).max)
+
+    iterationNumber = -1
+    restart = True
+    forcedRestart = False
+    explicitGramFlag = False
+    while iterationNumber < maxiter:
+        iterationNumber += 1
+
+        if B is not None:
+            aux = blockVectorBX * _lambda[np.newaxis, :]
+        else:
+            aux = blockVectorX * _lambda[np.newaxis, :]
+
+        blockVectorR = blockVectorAX - aux
+
+        aux = np.sum(blockVectorR.conj() * blockVectorR, 0)
+        residualNorms = np.sqrt(np.abs(aux))
+        if retResidualNormsHistory:
+            residualNormsHistory[iterationNumber, :] = residualNorms
+        residualNorm = np.sum(np.abs(residualNorms)) / sizeX
+
+        if residualNorm < smallestResidualNorm:
+            smallestResidualNorm = residualNorm
+            bestIterationNumber = iterationNumber
+            bestblockVectorX = blockVectorX
+        elif residualNorm > 2**restartControl * smallestResidualNorm:
+            forcedRestart = True
+            blockVectorAX = A(blockVectorX)
+            if blockVectorAX.shape != blockVectorX.shape:
+                raise ValueError(
+                    f"The shape {blockVectorX.shape} "
+                    f"of the restarted iterate not preserved\n"
+                    f"and changed to {blockVectorAX.shape} "
+                    f"after multiplying by the primary matrix.\n"
+                )
+            if B is not None:
+                blockVectorBX = B(blockVectorX)
+                if blockVectorBX.shape != blockVectorX.shape:
+                    raise ValueError(
+                        f"The shape {blockVectorX.shape} "
+                        f"of the restarted iterate not preserved\n"
+                        f"and changed to {blockVectorBX.shape} "
+                        f"after multiplying by the secondary matrix.\n"
+                    )
+
+        ii = np.where(residualNorms > residualTolerance, True, False)
+        activeMask = activeMask & ii
+        currentBlockSize = activeMask.sum()
+
+        if verbosityLevel:
+            print(f"iteration {iterationNumber}")
+            print(f"current block size: {currentBlockSize}")
+            print(f"eigenvalue(s):\n{_lambda}")
+            print(f"residual norm(s):\n{residualNorms}")
+
+        if currentBlockSize == 0:
+            break
+
+        activeBlockVectorR = _as2d(blockVectorR[:, activeMask])
+
+        if iterationNumber > 0:
+            activeBlockVectorP = _as2d(blockVectorP[:, activeMask])
+            activeBlockVectorAP = _as2d(blockVectorAP[:, activeMask])
+            if B is not None:
+                activeBlockVectorBP = _as2d(blockVectorBP[:, activeMask])
+
+        if M is not None:
+            # Apply preconditioner T to the active residuals.
+            activeBlockVectorR = M(activeBlockVectorR)
+
+        ##
+        # Apply constraints to the preconditioned residuals.
+        if blockVectorY is not None:
+            _applyConstraints(activeBlockVectorR,
+                              gramYBY,
+                              blockVectorBY,
+                              blockVectorY)
+
+        ##
+        # B-orthogonalize the preconditioned residuals to X.
+        if B is not None:
+            activeBlockVectorR = activeBlockVectorR - (
+                blockVectorX @
+                (blockVectorBX.T.conj() @ activeBlockVectorR)
+            )
+        else:
+            activeBlockVectorR = activeBlockVectorR - (
+                blockVectorX @
+                (blockVectorX.T.conj() @ activeBlockVectorR)
+            )
+
+        ##
+        # B-orthonormalize the preconditioned residuals.
+        aux = _b_orthonormalize(
+            B, activeBlockVectorR, verbosityLevel=verbosityLevel)
+        activeBlockVectorR, activeBlockVectorBR, _ = aux
+
+        if activeBlockVectorR is None:
+            warnings.warn(
+                f"Failed at iteration {iterationNumber} with accuracies "
+                f"{residualNorms}\n not reaching the requested "
+                f"tolerance {residualTolerance}.",
+                UserWarning, stacklevel=2
+            )
+            break
+        activeBlockVectorAR = A(activeBlockVectorR)
+
+        if iterationNumber > 0:
+            if B is not None:
+                aux = _b_orthonormalize(
+                    B, activeBlockVectorP, activeBlockVectorBP,
+                    verbosityLevel=verbosityLevel
+                )
+                activeBlockVectorP, activeBlockVectorBP, invR = aux
+            else:
+                aux = _b_orthonormalize(B, activeBlockVectorP,
+                                        verbosityLevel=verbosityLevel)
+                activeBlockVectorP, _, invR = aux
+            # Function _b_orthonormalize returns None if Cholesky fails
+            if activeBlockVectorP is not None:
+                activeBlockVectorAP = _matmul_inplace(
+                    activeBlockVectorAP, invR,
+                    verbosityLevel=verbosityLevel
+                )
+                restart = forcedRestart
+            else:
+                restart = True
+
+        ##
+        # Perform the Rayleigh Ritz Procedure:
+        # Compute symmetric Gram matrices:
+
+        if activeBlockVectorAR.dtype == "float32":
+            myeps = 1
+        else:
+            myeps = np.sqrt(np.finfo(activeBlockVectorR.dtype).eps)
+
+        if residualNorms.max() > myeps and not explicitGramFlag:
+            explicitGramFlag = False
+        else:
+            # Once explicitGramFlag, forever explicitGramFlag.
+            explicitGramFlag = True
+
+        # Shared memory assignments to simplify the code
+        if B is None:
+            blockVectorBX = blockVectorX
+            activeBlockVectorBR = activeBlockVectorR
+            if not restart:
+                activeBlockVectorBP = activeBlockVectorP
+
+        # Common submatrices:
+        gramXAR = np.dot(blockVectorX.T.conj(), activeBlockVectorAR)
+        gramRAR = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorAR)
+
+        gramDtype = activeBlockVectorAR.dtype
+        if explicitGramFlag:
+            gramRAR = (gramRAR + gramRAR.T.conj()) / 2
+            gramXAX = np.dot(blockVectorX.T.conj(), blockVectorAX)
+            gramXAX = (gramXAX + gramXAX.T.conj()) / 2
+            gramXBX = np.dot(blockVectorX.T.conj(), blockVectorBX)
+            gramRBR = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorBR)
+            gramXBR = np.dot(blockVectorX.T.conj(), activeBlockVectorBR)
+        else:
+            gramXAX = np.diag(_lambda).astype(gramDtype)
+            gramXBX = np.eye(sizeX, dtype=gramDtype)
+            gramRBR = np.eye(currentBlockSize, dtype=gramDtype)
+            gramXBR = np.zeros((sizeX, currentBlockSize), dtype=gramDtype)
+
+        if not restart:
+            gramXAP = np.dot(blockVectorX.T.conj(), activeBlockVectorAP)
+            gramRAP = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorAP)
+            gramPAP = np.dot(activeBlockVectorP.T.conj(), activeBlockVectorAP)
+            gramXBP = np.dot(blockVectorX.T.conj(), activeBlockVectorBP)
+            gramRBP = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorBP)
+            if explicitGramFlag:
+                gramPAP = (gramPAP + gramPAP.T.conj()) / 2
+                gramPBP = np.dot(activeBlockVectorP.T.conj(),
+                                 activeBlockVectorBP)
+            else:
+                gramPBP = np.eye(currentBlockSize, dtype=gramDtype)
+
+            gramA = np.block(
+                [
+                    [gramXAX, gramXAR, gramXAP],
+                    [gramXAR.T.conj(), gramRAR, gramRAP],
+                    [gramXAP.T.conj(), gramRAP.T.conj(), gramPAP],
+                ]
+            )
+            gramB = np.block(
+                [
+                    [gramXBX, gramXBR, gramXBP],
+                    [gramXBR.T.conj(), gramRBR, gramRBP],
+                    [gramXBP.T.conj(), gramRBP.T.conj(), gramPBP],
+                ]
+            )
+
+            _handle_gramA_gramB_verbosity(gramA, gramB, verbosityLevel)
+
+            try:
+                _lambda, eigBlockVector = eigh(gramA,
+                                               gramB,
+                                               check_finite=False)
+            except LinAlgError as e:
+                # raise ValueError("eigh failed in lobpcg iterations") from e
+                if verbosityLevel:
+                    warnings.warn(
+                        f"eigh failed at iteration {iterationNumber} \n"
+                        f"with error {e} causing a restart.\n",
+                        UserWarning, stacklevel=2
+                    )
+                # try again after dropping the direction vectors P from RR
+                restart = True
+
+        if restart:
+            gramA = np.block([[gramXAX, gramXAR], [gramXAR.T.conj(), gramRAR]])
+            gramB = np.block([[gramXBX, gramXBR], [gramXBR.T.conj(), gramRBR]])
+
+            _handle_gramA_gramB_verbosity(gramA, gramB, verbosityLevel)
+
+            try:
+                _lambda, eigBlockVector = eigh(gramA,
+                                               gramB,
+                                               check_finite=False)
+            except LinAlgError as e:
+                # raise ValueError("eigh failed in lobpcg iterations") from e
+                warnings.warn(
+                    f"eigh failed at iteration {iterationNumber} with error\n"
+                    f"{e}\n",
+                    UserWarning, stacklevel=2
+                )
+                break
+
+        ii = _get_indx(_lambda, sizeX, largest)
+        _lambda = _lambda[ii]
+        eigBlockVector = eigBlockVector[:, ii]
+        if retLambdaHistory:
+            lambdaHistory[iterationNumber + 1, :] = _lambda
+
+        # Compute Ritz vectors.
+        if B is not None:
+            if not restart:
+                eigBlockVectorX = eigBlockVector[:sizeX]
+                eigBlockVectorR = eigBlockVector[sizeX:
+                                                 sizeX + currentBlockSize]
+                eigBlockVectorP = eigBlockVector[sizeX + currentBlockSize:]
+
+                pp = np.dot(activeBlockVectorR, eigBlockVectorR)
+                pp += np.dot(activeBlockVectorP, eigBlockVectorP)
+
+                app = np.dot(activeBlockVectorAR, eigBlockVectorR)
+                app += np.dot(activeBlockVectorAP, eigBlockVectorP)
+
+                bpp = np.dot(activeBlockVectorBR, eigBlockVectorR)
+                bpp += np.dot(activeBlockVectorBP, eigBlockVectorP)
+            else:
+                eigBlockVectorX = eigBlockVector[:sizeX]
+                eigBlockVectorR = eigBlockVector[sizeX:]
+
+                pp = np.dot(activeBlockVectorR, eigBlockVectorR)
+                app = np.dot(activeBlockVectorAR, eigBlockVectorR)
+                bpp = np.dot(activeBlockVectorBR, eigBlockVectorR)
+
+            blockVectorX = np.dot(blockVectorX, eigBlockVectorX) + pp
+            blockVectorAX = np.dot(blockVectorAX, eigBlockVectorX) + app
+            blockVectorBX = np.dot(blockVectorBX, eigBlockVectorX) + bpp
+
+            blockVectorP, blockVectorAP, blockVectorBP = pp, app, bpp
+
+        else:
+            if not restart:
+                eigBlockVectorX = eigBlockVector[:sizeX]
+                eigBlockVectorR = eigBlockVector[sizeX:
+                                                 sizeX + currentBlockSize]
+                eigBlockVectorP = eigBlockVector[sizeX + currentBlockSize:]
+
+                pp = np.dot(activeBlockVectorR, eigBlockVectorR)
+                pp += np.dot(activeBlockVectorP, eigBlockVectorP)
+
+                app = np.dot(activeBlockVectorAR, eigBlockVectorR)
+                app += np.dot(activeBlockVectorAP, eigBlockVectorP)
+            else:
+                eigBlockVectorX = eigBlockVector[:sizeX]
+                eigBlockVectorR = eigBlockVector[sizeX:]
+
+                pp = np.dot(activeBlockVectorR, eigBlockVectorR)
+                app = np.dot(activeBlockVectorAR, eigBlockVectorR)
+
+            blockVectorX = np.dot(blockVectorX, eigBlockVectorX) + pp
+            blockVectorAX = np.dot(blockVectorAX, eigBlockVectorX) + app
+
+            blockVectorP, blockVectorAP = pp, app
+
+    if B is not None:
+        aux = blockVectorBX * _lambda[np.newaxis, :]
+    else:
+        aux = blockVectorX * _lambda[np.newaxis, :]
+
+    blockVectorR = blockVectorAX - aux
+
+    aux = np.sum(blockVectorR.conj() * blockVectorR, 0)
+    residualNorms = np.sqrt(np.abs(aux))
+    # Use old lambda in case of early loop exit.
+    if retLambdaHistory:
+        lambdaHistory[iterationNumber + 1, :] = _lambda
+    if retResidualNormsHistory:
+        residualNormsHistory[iterationNumber + 1, :] = residualNorms
+    residualNorm = np.sum(np.abs(residualNorms)) / sizeX
+    if residualNorm < smallestResidualNorm:
+        smallestResidualNorm = residualNorm
+        bestIterationNumber = iterationNumber + 1
+        bestblockVectorX = blockVectorX
+
+    if np.max(np.abs(residualNorms)) > residualTolerance:
+        warnings.warn(
+            f"Exited at iteration {iterationNumber} with accuracies \n"
+            f"{residualNorms}\n"
+            f"not reaching the requested tolerance {residualTolerance}.\n"
+            f"Use iteration {bestIterationNumber} instead with accuracy \n"
+            f"{smallestResidualNorm}.\n",
+            UserWarning, stacklevel=2
+        )
+
+    if verbosityLevel:
+        print(f"Final iterative eigenvalue(s):\n{_lambda}")
+        print(f"Final iterative residual norm(s):\n{residualNorms}")
+
+    blockVectorX = bestblockVectorX
+    # Making eigenvectors "exactly" satisfy the blockVectorY constrains
+    if blockVectorY is not None:
+        _applyConstraints(blockVectorX,
+                          gramYBY,
+                          blockVectorBY,
+                          blockVectorY)
+
+    # Making eigenvectors "exactly" othonormalized by final "exact" RR
+    blockVectorAX = A(blockVectorX)
+    if blockVectorAX.shape != blockVectorX.shape:
+        raise ValueError(
+            f"The shape {blockVectorX.shape} "
+            f"of the postprocessing iterate not preserved\n"
+            f"and changed to {blockVectorAX.shape} "
+            f"after multiplying by the primary matrix.\n"
+        )
+    gramXAX = np.dot(blockVectorX.T.conj(), blockVectorAX)
+
+    blockVectorBX = blockVectorX
+    if B is not None:
+        blockVectorBX = B(blockVectorX)
+        if blockVectorBX.shape != blockVectorX.shape:
+            raise ValueError(
+                f"The shape {blockVectorX.shape} "
+                f"of the postprocessing iterate not preserved\n"
+                f"and changed to {blockVectorBX.shape} "
+                f"after multiplying by the secondary matrix.\n"
+            )
+
+    gramXBX = np.dot(blockVectorX.T.conj(), blockVectorBX)
+    _handle_gramA_gramB_verbosity(gramXAX, gramXBX, verbosityLevel)
+    gramXAX = (gramXAX + gramXAX.T.conj()) / 2
+    gramXBX = (gramXBX + gramXBX.T.conj()) / 2
+    try:
+        _lambda, eigBlockVector = eigh(gramXAX,
+                                       gramXBX,
+                                       check_finite=False)
+    except LinAlgError as e:
+        raise ValueError("eigh has failed in lobpcg postprocessing") from e
+
+    ii = _get_indx(_lambda, sizeX, largest)
+    _lambda = _lambda[ii]
+    eigBlockVector = np.asarray(eigBlockVector[:, ii])
+
+    blockVectorX = np.dot(blockVectorX, eigBlockVector)
+    blockVectorAX = np.dot(blockVectorAX, eigBlockVector)
+
+    if B is not None:
+        blockVectorBX = np.dot(blockVectorBX, eigBlockVector)
+        aux = blockVectorBX * _lambda[np.newaxis, :]
+    else:
+        aux = blockVectorX * _lambda[np.newaxis, :]
+
+    blockVectorR = blockVectorAX - aux
+
+    aux = np.sum(blockVectorR.conj() * blockVectorR, 0)
+    residualNorms = np.sqrt(np.abs(aux))
+
+    if retLambdaHistory:
+        lambdaHistory[bestIterationNumber + 1, :] = _lambda
+    if retResidualNormsHistory:
+        residualNormsHistory[bestIterationNumber + 1, :] = residualNorms
+
+    if retLambdaHistory:
+        lambdaHistory = lambdaHistory[
+            : bestIterationNumber + 2, :]
+    if retResidualNormsHistory:
+        residualNormsHistory = residualNormsHistory[
+            : bestIterationNumber + 2, :]
+
+    if np.max(np.abs(residualNorms)) > residualTolerance:
+        warnings.warn(
+            f"Exited postprocessing with accuracies \n"
+            f"{residualNorms}\n"
+            f"not reaching the requested tolerance {residualTolerance}.",
+            UserWarning, stacklevel=2
+        )
+
+    if verbosityLevel:
+        print(f"Final postprocessing eigenvalue(s):\n{_lambda}")
+        print(f"Final residual norm(s):\n{residualNorms}")
+
+    if retLambdaHistory:
+        lambdaHistory = np.vsplit(lambdaHistory, np.shape(lambdaHistory)[0])
+        lambdaHistory = [np.squeeze(i) for i in lambdaHistory]
+    if retResidualNormsHistory:
+        residualNormsHistory = np.vsplit(residualNormsHistory,
+                                         np.shape(residualNormsHistory)[0])
+        residualNormsHistory = [np.squeeze(i) for i in residualNormsHistory]
+
+    if retLambdaHistory:
+        if retResidualNormsHistory:
+            return _lambda, blockVectorX, lambdaHistory, residualNormsHistory
+        else:
+            return _lambda, blockVectorX, lambdaHistory
+    else:
+        if retResidualNormsHistory:
+            return _lambda, blockVectorX, residualNormsHistory
+        else:
+            return _lambda, blockVectorX
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/tests/test_lobpcg.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/tests/test_lobpcg.py
new file mode 100644
index 0000000000000000000000000000000000000000..850aa0c1b3f5d0c47c1ba66d518b8a7059c85e95
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/lobpcg/tests/test_lobpcg.py
@@ -0,0 +1,725 @@
+""" Test functions for the sparse.linalg._eigen.lobpcg module
+"""
+
+import itertools
+import platform
+import sys
+import pytest
+import numpy as np
+from numpy import ones, r_, diag
+from numpy.testing import (assert_almost_equal, assert_equal,
+                           assert_allclose, assert_array_less)
+
+from scipy import sparse
+from scipy.linalg import (eigh, toeplitz,
+                          cholesky_banded, cho_solve_banded)
+from scipy.sparse import dia_array, eye_array, csr_array
+from scipy.sparse.linalg import eigsh, LinearOperator
+from scipy.sparse.linalg._eigen.lobpcg import lobpcg
+from scipy.sparse.linalg._eigen.lobpcg.lobpcg import _b_orthonormalize
+from scipy._lib._util import np_long, np_ulong
+from scipy.sparse.linalg._special_sparse_arrays import (Sakurai,
+                                                        MikotaPair)
+
+_IS_32BIT = (sys.maxsize < 2**32)
+
+INT_DTYPES = (np.intc, np_long, np.longlong, np.uintc, np_ulong, np.ulonglong)
+# np.half is unsupported on many test systems so excluded
+REAL_DTYPES = (np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+INEXACTDTYPES = REAL_DTYPES + COMPLEX_DTYPES
+ALLDTYPES = INT_DTYPES + INEXACTDTYPES
+
+
+def sign_align(A, B):
+    """Align signs of columns of A match those of B: column-wise remove
+    sign of A by multiplying with its sign then multiply in sign of B.
+    """
+    return np.array([col_A * np.sign(col_A[0]) * np.sign(col_B[0])
+                     for col_A, col_B in zip(A.T, B.T)]).T
+
+def ElasticRod(n):
+    """Build the matrices for the generalized eigenvalue problem of the
+    fixed-free elastic rod vibration model.
+    """
+    L = 1.0
+    le = L/n
+    rho = 7.85e3
+    S = 1.e-4
+    E = 2.1e11
+    mass = rho*S*le/6.
+    k = E*S/le
+    A = k*(diag(r_[2.*ones(n-1), 1])-diag(ones(n-1), 1)-diag(ones(n-1), -1))
+    B = mass*(diag(r_[4.*ones(n-1), 2])+diag(ones(n-1), 1)+diag(ones(n-1), -1))
+    return A, B
+
+
+@pytest.mark.filterwarnings("ignore:The problem size")
+@pytest.mark.parametrize("n", [10, 20])
+@pytest.mark.filterwarnings("ignore:Exited at iteration")
+@pytest.mark.filterwarnings("ignore:Exited postprocessing")
+def test_ElasticRod(n):
+    """Check eigh vs. lobpcg consistency for elastic rod model.
+    """
+    A, B = ElasticRod(n)
+    m = 2
+    rnd = np.random.RandomState(0)
+    X = rnd.standard_normal((n, m))
+    eigvals, _ = lobpcg(A, X, B=B, tol=1e-2, maxiter=50, largest=False)
+    eigvals.sort()
+    w, _ = eigh(A, b=B)
+    w.sort()
+    assert_almost_equal(w[:int(m/2)], eigvals[:int(m/2)], decimal=2)
+
+
+@pytest.mark.parametrize("n", [50])
+@pytest.mark.parametrize("m", [1, 2, 10])
+@pytest.mark.filterwarnings("ignore:Casting complex values to real")
+@pytest.mark.parametrize("Vdtype", INEXACTDTYPES)
+@pytest.mark.parametrize("Bdtype", ALLDTYPES)
+@pytest.mark.parametrize("BVdtype", INEXACTDTYPES)
+def test_b_orthonormalize(n, m, Vdtype, Bdtype, BVdtype):
+    """Test B-orthonormalization by Cholesky with callable 'B'.
+    The function '_b_orthonormalize' is key in LOBPCG but may
+    lead to numerical instabilities. The input vectors are often
+    badly scaled, so the function needs scale-invariant Cholesky;
+    see https://netlib.org/lapack/lawnspdf/lawn14.pdf.
+    """
+    rnd = np.random.RandomState(0)
+    X = rnd.standard_normal((n, m)).astype(Vdtype)
+    Xcopy = np.copy(X)
+    vals = np.arange(1, n+1, dtype=float)
+    B = dia_array(([vals], [0]), shape=(n, n)).astype(Bdtype)
+    BX = B @ X
+    BX = BX.astype(BVdtype)
+    is_all_complex = (np.issubdtype(Vdtype, np.complexfloating) and
+                     np.issubdtype(BVdtype, np.complexfloating))
+    is_all_notcomplex = (not np.issubdtype(Vdtype, np.complexfloating) and
+                        not np.issubdtype(Bdtype, np.complexfloating) and
+                        not np.issubdtype(BVdtype, np.complexfloating))
+
+    # All complex or all not complex can calculate in-place
+    check_inplace = is_all_complex or is_all_notcomplex
+    # np.longdouble tol cannot be achieved on most systems
+    atol = m * n * max(np.finfo(Vdtype).eps,
+                       np.finfo(BVdtype).eps,
+                       np.finfo(np.float64).eps)
+
+    Xo, BXo, _ = _b_orthonormalize(lambda v: B @ v, X, BX)
+    if check_inplace:
+        # Check in-place
+        assert_equal(X, Xo)
+        assert_equal(id(X), id(Xo))
+        assert_equal(BX, BXo)
+        assert_equal(id(BX), id(BXo))
+    # Check BXo
+    assert_allclose(B @ Xo, BXo, atol=atol, rtol=atol)
+    # Check B-orthonormality
+    assert_allclose(Xo.T.conj() @ B @ Xo, np.identity(m),
+                    atol=atol, rtol=atol)
+    # Repeat without BX in outputs
+    X = np.copy(Xcopy)
+    Xo1, BXo1, _ = _b_orthonormalize(lambda v: B @ v, X)
+    assert_allclose(Xo, Xo1, atol=atol, rtol=atol)
+    assert_allclose(BXo, BXo1, atol=atol, rtol=atol)
+    if check_inplace:
+        # Check in-place.
+        assert_equal(X, Xo1)
+        assert_equal(id(X), id(Xo1))
+    # Check BXo1
+    assert_allclose(B @ Xo1, BXo1, atol=atol, rtol=atol)
+
+    # Introduce column-scaling in X
+    scaling = 1.0 / np.geomspace(10, 1e10, num=m)
+    X = Xcopy * scaling
+    X = X.astype(Vdtype)
+    BX = B @ X
+    BX = BX.astype(BVdtype)
+    # Check scaling-invariance of Cholesky-based orthonormalization
+    Xo1, BXo1, _ = _b_orthonormalize(lambda v: B @ v, X, BX)
+    # The output should be the same, up the signs of the columns
+    Xo1 =  sign_align(Xo1, Xo)
+    assert_allclose(Xo, Xo1, atol=atol, rtol=atol)
+    BXo1 =  sign_align(BXo1, BXo)
+    assert_allclose(BXo, BXo1, atol=atol, rtol=atol)
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.filterwarnings("ignore:Exited at iteration 0")
+@pytest.mark.filterwarnings("ignore:Exited postprocessing")
+def test_nonhermitian_warning(capsys):
+    """Check the warning of a Ritz matrix being not Hermitian
+    by feeding a non-Hermitian input matrix.
+    Also check stdout since verbosityLevel=1 and lack of stderr.
+    """
+    n = 10
+    X = np.arange(n * 2).reshape(n, 2).astype(np.float32)
+    A = np.arange(n * n).reshape(n, n).astype(np.float32)
+    with pytest.warns(UserWarning, match="Matrix gramA"):
+        _, _ = lobpcg(A, X, verbosityLevel=1, maxiter=0)
+    out, err = capsys.readouterr()  # Capture output
+    assert out.startswith("Solving standard eigenvalue")  # Test stdout
+    assert err == ''  # Test empty stderr
+    # Make the matrix symmetric and the UserWarning disappears.
+    A += A.T
+    _, _ = lobpcg(A, X, verbosityLevel=1, maxiter=0)
+    out, err = capsys.readouterr()  # Capture output
+    assert out.startswith("Solving standard eigenvalue")  # Test stdout
+    assert err == ''  # Test empty stderr
+
+
+def test_regression():
+    """Check the eigenvalue of the identity matrix is one.
+    """
+    # https://mail.python.org/pipermail/scipy-user/2010-October/026944.html
+    n = 10
+    X = np.ones((n, 1))
+    A = np.identity(n)
+    w, _ = lobpcg(A, X)
+    assert_allclose(w, [1])
+
+
+@pytest.mark.filterwarnings("ignore:The problem size")
+@pytest.mark.parametrize('n, m, m_excluded', [(30, 4, 3), (4, 2, 0)])
+def test_diagonal(n, m, m_excluded):
+    """Test ``m - m_excluded`` eigenvalues and eigenvectors of
+    diagonal matrices of the size ``n`` varying matrix formats:
+    dense array, spare matrix, and ``LinearOperator`` for both
+    matrixes in the generalized eigenvalue problem ``Av = cBv``
+    and for the preconditioner.
+    """
+    rnd = np.random.RandomState(0)
+
+    # Define the generalized eigenvalue problem Av = cBv
+    # where (c, v) is a generalized eigenpair,
+    # A is the diagonal matrix whose entries are 1,...n,
+    # B is the identity matrix.
+    vals = np.arange(1, n+1, dtype=float)
+    A_s = dia_array(([vals], [0]), shape=(n, n))
+    A_a = A_s.toarray()
+
+    def A_f(x):
+        return A_s @ x
+
+    A_lo = LinearOperator(matvec=A_f,
+                          matmat=A_f,
+                          shape=(n, n), dtype=float)
+
+    B_a = eye_array(n)
+    B_s = csr_array(B_a)
+
+    def B_f(x):
+        return B_a @ x
+
+    B_lo = LinearOperator(matvec=B_f,
+                          matmat=B_f,
+                          shape=(n, n), dtype=float)
+
+    # Let the preconditioner M be the inverse of A.
+    M_s = dia_array(([1./vals], [0]), shape=(n, n))
+    M_a = M_s.toarray()
+
+    def M_f(x):
+        return M_s @ x
+
+    M_lo = LinearOperator(matvec=M_f,
+                          matmat=M_f,
+                          shape=(n, n), dtype=float)
+
+    # Pick random initial vectors.
+    X = rnd.normal(size=(n, m))
+
+    # Require that the returned eigenvectors be in the orthogonal complement
+    # of the first few standard basis vectors.
+    if m_excluded > 0:
+        Y = np.eye(n, m_excluded)
+    else:
+        Y = None
+
+    for A in [A_a, A_s, A_lo]:
+        for B in [B_a, B_s, B_lo]:
+            for M in [M_a, M_s, M_lo]:
+                eigvals, vecs = lobpcg(A, X, B, M=M, Y=Y,
+                                       maxiter=40, largest=False)
+
+                assert_allclose(eigvals, np.arange(1+m_excluded,
+                                                   1+m_excluded+m))
+                _check_eigen(A, eigvals, vecs, rtol=1e-3, atol=1e-3)
+
+
+def _check_eigen(M, w, V, rtol=1e-8, atol=1e-14):
+    """Check if the eigenvalue residual is small.
+    """
+    mult_wV = np.multiply(w, V)
+    dot_MV = M.dot(V)
+    assert_allclose(mult_wV, dot_MV, rtol=rtol, atol=atol)
+
+
+def _check_fiedler(n, p):
+    """Check the Fiedler vector computation.
+    """
+    # This is not necessarily the recommended way to find the Fiedler vector.
+    col = np.zeros(n)
+    col[1] = 1
+    A = toeplitz(col)
+    D = np.diag(A.sum(axis=1))
+    L = D - A
+    # Compute the full eigendecomposition using tricks, e.g.
+    # http://www.cs.yale.edu/homes/spielman/561/2009/lect02-09.pdf
+    tmp = np.pi * np.arange(n) / n
+    analytic_w = 2 * (1 - np.cos(tmp))
+    analytic_V = np.cos(np.outer(np.arange(n) + 1/2, tmp))
+    _check_eigen(L, analytic_w, analytic_V)
+    # Compute the full eigendecomposition using eigh.
+    eigh_w, eigh_V = eigh(L)
+    _check_eigen(L, eigh_w, eigh_V)
+    # Check that the first eigenvalue is near zero and that the rest agree.
+    assert_array_less(np.abs([eigh_w[0], analytic_w[0]]), 1e-14)
+    assert_allclose(eigh_w[1:], analytic_w[1:])
+
+    # Check small lobpcg eigenvalues.
+    X = analytic_V[:, :p]
+    lobpcg_w, lobpcg_V = lobpcg(L, X, largest=False)
+    assert_equal(lobpcg_w.shape, (p,))
+    assert_equal(lobpcg_V.shape, (n, p))
+    _check_eigen(L, lobpcg_w, lobpcg_V)
+    assert_array_less(np.abs(np.min(lobpcg_w)), 1e-14)
+    assert_allclose(np.sort(lobpcg_w)[1:], analytic_w[1:p])
+
+    # Check large lobpcg eigenvalues.
+    X = analytic_V[:, -p:]
+    lobpcg_w, lobpcg_V = lobpcg(L, X, largest=True)
+    assert_equal(lobpcg_w.shape, (p,))
+    assert_equal(lobpcg_V.shape, (n, p))
+    _check_eigen(L, lobpcg_w, lobpcg_V)
+    assert_allclose(np.sort(lobpcg_w), analytic_w[-p:])
+
+    # Look for the Fiedler vector using good but not exactly correct guesses.
+    fiedler_guess = np.concatenate((np.ones(n//2), -np.ones(n-n//2)))
+    X = np.vstack((np.ones(n), fiedler_guess)).T
+    lobpcg_w, _ = lobpcg(L, X, largest=False)
+    # Mathematically, the smaller eigenvalue should be zero
+    # and the larger should be the algebraic connectivity.
+    lobpcg_w = np.sort(lobpcg_w)
+    assert_allclose(lobpcg_w, analytic_w[:2], atol=1e-14)
+
+
+@pytest.mark.thread_unsafe
+def test_fiedler_small_8():
+    """Check the dense workaround path for small matrices.
+    """
+    # This triggers the dense path because 8 < 2*5.
+    with pytest.warns(UserWarning, match="The problem size"):
+        _check_fiedler(8, 2)
+
+
+def test_fiedler_large_12():
+    """Check the dense workaround path avoided for non-small matrices.
+    """
+    # This does not trigger the dense path, because 2*5 <= 12.
+    _check_fiedler(12, 2)
+
+
+@pytest.mark.filterwarnings("ignore:Failed at iteration")
+@pytest.mark.filterwarnings("ignore:Exited at iteration")
+@pytest.mark.filterwarnings("ignore:Exited postprocessing")
+def test_failure_to_run_iterations():
+    """Check that the code exits gracefully without breaking. Issue #10974.
+    The code may or not issue a warning, filtered out. Issue #15935, #17954.
+    """
+    rnd = np.random.RandomState(0)
+    X = rnd.standard_normal((100, 10))
+    A = X @ X.T
+    Q = rnd.standard_normal((X.shape[0], 4))
+    eigenvalues, _ = lobpcg(A, Q, maxiter=40, tol=1e-12)
+    assert np.max(eigenvalues) > 0
+
+
+@pytest.mark.thread_unsafe
+def test_failure_to_run_iterations_nonsymmetric():
+    """Check that the code exists gracefully without breaking
+    if the matrix in not symmetric.
+    """
+    A = np.zeros((10, 10))
+    A[0, 1] = 1
+    Q = np.ones((10, 1))
+    msg = "Exited at iteration 2|Exited postprocessing with accuracies.*"
+    with pytest.warns(UserWarning, match=msg):
+        eigenvalues, _ = lobpcg(A, Q, maxiter=20)
+    assert np.max(eigenvalues) > 0
+
+
+@pytest.mark.filterwarnings("ignore:The problem size")
+def test_hermitian():
+    """Check complex-value Hermitian cases.
+    """
+    rnd = np.random.RandomState(0)
+
+    sizes = [3, 12]
+    ks = [1, 2]
+    gens = [True, False]
+
+    for s, k, gen, dh, dx, db in (
+        itertools.product(sizes, ks, gens, gens, gens, gens)
+    ):
+        H = rnd.random((s, s)) + 1.j * rnd.random((s, s))
+        H = 10 * np.eye(s) + H + H.T.conj()
+        H = H.astype(np.complex128) if dh else H.astype(np.complex64)
+
+        X = rnd.standard_normal((s, k))
+        X = X + 1.j * rnd.standard_normal((s, k))
+        X = X.astype(np.complex128) if dx else X.astype(np.complex64)
+
+        if not gen:
+            B = np.eye(s)
+            w, v = lobpcg(H, X, maxiter=99, verbosityLevel=0)
+            # Also test mixing complex H with real B.
+            wb, _ = lobpcg(H, X, B, maxiter=99, verbosityLevel=0)
+            assert_allclose(w, wb, rtol=1e-6)
+            w0, _ = eigh(H)
+        else:
+            B = rnd.random((s, s)) + 1.j * rnd.random((s, s))
+            B = 10 * np.eye(s) + B.dot(B.T.conj())
+            B = B.astype(np.complex128) if db else B.astype(np.complex64)
+            w, v = lobpcg(H, X, B, maxiter=99, verbosityLevel=0)
+            w0, _ = eigh(H, B)
+
+        for wx, vx in zip(w, v.T):
+            # Check eigenvector
+            assert_allclose(np.linalg.norm(H.dot(vx) - B.dot(vx) * wx)
+                            / np.linalg.norm(H.dot(vx)),
+                            0, atol=5e-2, rtol=0)
+
+            # Compare eigenvalues
+            j = np.argmin(abs(w0 - wx))
+            assert_allclose(wx, w0[j], rtol=1e-4)
+
+
+# The n=5 case tests the alternative small matrix code path that uses eigh().
+@pytest.mark.filterwarnings("ignore:The problem size")
+@pytest.mark.parametrize('n, atol', [(20, 1e-3), (5, 1e-8)])
+def test_eigsh_consistency(n, atol):
+    """Check eigsh vs. lobpcg consistency.
+    """
+    vals = np.arange(1, n+1, dtype=np.float64)
+    A = dia_array((vals, 0), shape=(n, n))
+    rnd = np.random.RandomState(0)
+    X = rnd.standard_normal((n, 2))
+    lvals, lvecs = lobpcg(A, X, largest=True, maxiter=100)
+    vals, _ = eigsh(A, k=2)
+
+    _check_eigen(A, lvals, lvecs, atol=atol, rtol=0)
+    assert_allclose(np.sort(vals), np.sort(lvals), atol=1e-14)
+
+
+@pytest.mark.thread_unsafe
+def test_verbosity():
+    """Check that nonzero verbosity level code runs.
+    """
+    rnd = np.random.RandomState(0)
+    X = rnd.standard_normal((10, 10))
+    A = X @ X.T
+    Q = rnd.standard_normal((X.shape[0], 1))
+    msg = "Exited at iteration.*|Exited postprocessing with accuracies.*"
+    with pytest.warns(UserWarning, match=msg):
+        _, _ = lobpcg(A, Q, maxiter=3, verbosityLevel=9)
+
+
+@pytest.mark.xfail(_IS_32BIT and sys.platform == 'win32',
+                   reason="tolerance violation on windows")
+@pytest.mark.xfail(platform.machine() == 'ppc64le',
+                   reason="fails on ppc64le")
+@pytest.mark.filterwarnings("ignore:Exited postprocessing")
+def test_tolerance_float32():
+    """Check lobpcg for attainable tolerance in float32.
+    """
+    rnd = np.random.RandomState(0)
+    n = 50
+    m = 3
+    vals = -np.arange(1, n + 1)
+    A = dia_array(([vals], [0]), shape=(n, n))
+    A = A.astype(np.float32)
+    X = rnd.standard_normal((n, m))
+    X = X.astype(np.float32)
+    eigvals, _ = lobpcg(A, X, tol=1.25e-5, maxiter=50, verbosityLevel=0)
+    assert_allclose(eigvals, -np.arange(1, 1 + m), atol=2e-5, rtol=1e-5)
+
+
+@pytest.mark.parametrize("vdtype", INEXACTDTYPES)
+@pytest.mark.parametrize("mdtype", ALLDTYPES)
+@pytest.mark.parametrize("arr_type", [np.array,
+                                      sparse.csr_array,
+                                      sparse.coo_array])
+def test_dtypes(vdtype, mdtype, arr_type):
+    """Test lobpcg in various dtypes.
+    """
+    rnd = np.random.RandomState(0)
+    n = 12
+    m = 2
+    A = arr_type(np.diag(np.arange(1, n + 1)).astype(mdtype))
+    X = rnd.random((n, m))
+    X = X.astype(vdtype)
+    eigvals, eigvecs = lobpcg(A, X, tol=1e-2, largest=False)
+    assert_allclose(eigvals, np.arange(1, 1 + m), atol=1e-1)
+    # eigenvectors must be nearly real in any case
+    assert_allclose(np.sum(np.abs(eigvecs - eigvecs.conj())), 0, atol=1e-2)
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.filterwarnings("ignore:Exited at iteration")
+@pytest.mark.filterwarnings("ignore:Exited postprocessing")
+def test_inplace_warning():
+    """Check lobpcg gives a warning in '_b_orthonormalize'
+    that in-place orthogonalization is impossible due to dtype mismatch.
+    """
+    rnd = np.random.RandomState(0)
+    n = 6
+    m = 1
+    vals = -np.arange(1, n + 1)
+    A = dia_array(([vals], [0]), shape=(n, n))
+    A = A.astype(np.cdouble)
+    X = rnd.standard_normal((n, m))
+    with pytest.warns(UserWarning, match="Inplace update"):
+        eigvals, _ = lobpcg(A, X, maxiter=2, verbosityLevel=1)
+
+
+@pytest.mark.thread_unsafe
+def test_maxit():
+    """Check lobpcg if maxit=maxiter runs maxiter iterations and
+    if maxit=None runs 20 iterations (the default)
+    by checking the size of the iteration history output, which should
+    be the number of iterations plus 3 (initial, final, and postprocessing)
+    typically when maxiter is small and the choice of the best is passive.
+    """
+    rnd = np.random.RandomState(0)
+    n = 50
+    m = 4
+    vals = -np.arange(1, n + 1)
+    A = dia_array(([vals], [0]), shape=(n, n))
+    A = A.astype(np.float32)
+    X = rnd.standard_normal((n, m))
+    X = X.astype(np.float64)
+    msg = "Exited at iteration.*|Exited postprocessing with accuracies.*"
+    for maxiter in range(1, 4):
+        with pytest.warns(UserWarning, match=msg):
+            _, _, l_h, r_h = lobpcg(A, X, tol=1e-8, maxiter=maxiter,
+                                    retLambdaHistory=True,
+                                    retResidualNormsHistory=True)
+        assert_allclose(np.shape(l_h)[0], maxiter+3)
+        assert_allclose(np.shape(r_h)[0], maxiter+3)
+    with pytest.warns(UserWarning, match=msg):
+        l, _, l_h, r_h = lobpcg(A, X, tol=1e-8,
+                                retLambdaHistory=True,
+                                retResidualNormsHistory=True)
+    assert_allclose(np.shape(l_h)[0], 20+3)
+    assert_allclose(np.shape(r_h)[0], 20+3)
+    # Check that eigenvalue output is the last one in history
+    assert_allclose(l, l_h[-1])
+    # Make sure that both history outputs are lists
+    assert isinstance(l_h, list)
+    assert isinstance(r_h, list)
+    # Make sure that both history lists are arrays-like
+    assert_allclose(np.shape(l_h), np.shape(np.asarray(l_h)))
+    assert_allclose(np.shape(r_h), np.shape(np.asarray(r_h)))
+
+
+@pytest.mark.xslow
+@pytest.mark.filterwarnings("ignore:Exited at iteration")
+@pytest.mark.filterwarnings("ignore:Exited postprocessing")
+def test_sakurai():
+    """Check lobpcg and eighs accuracy for the Sakurai example
+    already used in `benchmarks/benchmarks/sparse_linalg_lobpcg.py`.
+    """
+    n = 50
+    tol = 100 * n * n * n* np.finfo(float).eps
+    sakurai_obj = Sakurai(n, dtype='int')
+    A = sakurai_obj
+    m = 3
+    ee = sakurai_obj.eigenvalues(3)
+    rng = np.random.default_rng(0)
+    X = rng.normal(size=(n, m))
+    el, _ = lobpcg(A, X, tol=1e-9, maxiter=5000, largest=False)
+    accuracy = max(abs(ee - el) / ee)
+    assert_allclose(accuracy, 0., atol=tol)
+    a_l = LinearOperator((n, n), matvec=A, matmat=A, dtype='float64')
+    ea, _ = eigsh(a_l, k=m, which='SA', tol=1e-9, maxiter=15000,
+                  v0 = rng.normal(size=(n, 1)))
+    accuracy = max(abs(ee - ea) / ee)
+    assert_allclose(accuracy, 0., atol=tol)
+
+
+@pytest.mark.parametrize("n", [500, 1000])
+@pytest.mark.filterwarnings("ignore:Exited at iteration")
+@pytest.mark.filterwarnings("ignore:Exited postprocessing")
+def test_sakurai_inverse(n):
+    """Check lobpcg and eighs accuracy for the sakurai_inverse example
+    already used in `benchmarks/benchmarks/sparse_linalg_lobpcg.py`.
+    """
+    def a(x):
+        return cho_solve_banded((c, False), x)
+    tol = 100 * n * n * n* np.finfo(float).eps
+    sakurai_obj = Sakurai(n)
+    A = sakurai_obj.tobanded().astype(np.float64)
+    m = 3
+    ee = sakurai_obj.eigenvalues(3)
+    rng = np.random.default_rng(0)
+    X = rng.normal(size=(n, m))
+    c = cholesky_banded(A)
+    el, _ = lobpcg(a, X, tol=1e-9, maxiter=8)
+    accuracy = max(abs(ee - 1. / el) / ee)
+    assert_allclose(accuracy, 0., atol=tol)
+    a_l = LinearOperator((n, n), matvec=a, matmat=a, dtype='float64')
+    ea, _ = eigsh(a_l, k=m, which='LA', tol=1e-9, maxiter=8,
+                  v0 = rng.normal(size=(n, 1)))
+    accuracy = max(abs(ee - np.sort(1. / ea)) / ee)
+    assert_allclose(accuracy, 0., atol=tol)
+
+
+@pytest.mark.filterwarnings("ignore:The problem size")
+@pytest.mark.parametrize("n", [10, 20, 128, 256, 512, 1024, 2048])
+@pytest.mark.filterwarnings("ignore:Exited at iteration")
+@pytest.mark.filterwarnings("ignore:Exited postprocessing")
+def test_MikotaPair(n):
+    """Check lobpcg and eighs accuracy for the Mikota example
+    already used in `benchmarks/benchmarks/sparse_linalg_lobpcg.py`.
+    """
+    def a(x):
+        return cho_solve_banded((c, False), x)
+    mik = MikotaPair(n)
+    mik_k = mik.k
+    mik_m = mik.m
+    Ac = mik_k
+    Bc = mik_m
+    Ab = mik_k.tobanded()
+    eigenvalues = mik.eigenvalues
+    if n == 10:
+        m = 3 # lobpcg calls eigh
+    elif n == 20:
+        m = 2
+    else:
+        m = 10
+    ee = eigenvalues(m)
+    tol = 100 * m * n * n * np.finfo(float).eps
+    rng = np.random.default_rng(0)
+    X = rng.normal(size=(n, m))
+    c = cholesky_banded(Ab.astype(np.float32))
+    el, _ = lobpcg(Ac, X, Bc, M=a, tol=1e-4,
+                   maxiter=40, largest=False)
+    accuracy = max(abs(ee - el) / ee)
+    assert_allclose(accuracy, 0., atol=tol)
+    B = LinearOperator((n, n), matvec=Bc, matmat=Bc, dtype='float64')
+    A = LinearOperator((n, n), matvec=Ac, matmat=Ac, dtype='float64')
+    c = cholesky_banded(Ab)
+    a_l = LinearOperator((n, n), matvec=a, matmat=a, dtype='float64')
+    ea, _ = eigsh(B, k=m, M=A, Minv=a_l, which='LA', tol=1e-4, maxiter=50,
+                  v0 = rng.normal(size=(n, 1)))
+    accuracy = max(abs(ee - np.sort(1./ea)) / ee)
+    assert_allclose(accuracy, 0., atol=tol)
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize("n", [15])
+@pytest.mark.parametrize("m", [1, 2])
+@pytest.mark.filterwarnings("ignore:Exited at iteration")
+@pytest.mark.filterwarnings("ignore:Exited postprocessing")
+def test_diagonal_data_types(n, m):
+    """Check lobpcg for diagonal matrices for all matrix types.
+    Constraints are imposed, so a dense eigensolver eig cannot run.
+    """
+    rnd = np.random.RandomState(0)
+    # Define the generalized eigenvalue problem Av = cBv
+    # where (c, v) is a generalized eigenpair,
+    # and where we choose A  and B to be diagonal.
+    vals = np.arange(1, n + 1)
+
+    list_sparse_format = ['bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil']
+    for s_f_i, s_f in enumerate(list_sparse_format):
+
+        As64 = dia_array(([vals * vals], [0]), shape=(n, n)).asformat(s_f)
+        As32 = As64.astype(np.float32)
+        Af64 = As64.toarray()
+        Af32 = Af64.astype(np.float32)
+
+        def As32f(x):
+            return As32 @ x
+        As32LO = LinearOperator(matvec=As32f,
+                                matmat=As32f,
+                                shape=(n, n),
+                                dtype=As32.dtype)
+
+        listA = [Af64, As64, Af32, As32, As32f, As32LO, lambda v: As32 @ v]
+
+        Bs64 = dia_array(([vals], [0]), shape=(n, n)).asformat(s_f)
+        Bf64 = Bs64.toarray()
+        Bs32 = Bs64.astype(np.float32)
+
+        def Bs32f(x):
+            return Bs32 @ x
+        Bs32LO = LinearOperator(matvec=Bs32f,
+                                matmat=Bs32f,
+                                shape=(n, n),
+                                dtype=Bs32.dtype)
+        listB = [Bf64, Bs64, Bs32, Bs32f, Bs32LO, lambda v: Bs32 @ v]
+
+        # Define the preconditioner function as LinearOperator.
+        Ms64 = dia_array(([1./vals], [0]), shape=(n, n)).asformat(s_f)
+
+        def Ms64precond(x):
+            return Ms64 @ x
+        Ms64precondLO = LinearOperator(matvec=Ms64precond,
+                                       matmat=Ms64precond,
+                                       shape=(n, n),
+                                       dtype=Ms64.dtype)
+        Mf64 = Ms64.toarray()
+
+        def Mf64precond(x):
+            return Mf64 @ x
+        Mf64precondLO = LinearOperator(matvec=Mf64precond,
+                                       matmat=Mf64precond,
+                                       shape=(n, n),
+                                       dtype=Mf64.dtype)
+        Ms32 = Ms64.astype(np.float32)
+
+        def Ms32precond(x):
+            return Ms32 @ x
+        Ms32precondLO = LinearOperator(matvec=Ms32precond,
+                                       matmat=Ms32precond,
+                                       shape=(n, n),
+                                       dtype=Ms32.dtype)
+        Mf32 = Ms32.toarray()
+
+        def Mf32precond(x):
+            return Mf32 @ x
+        Mf32precondLO = LinearOperator(matvec=Mf32precond,
+                                       matmat=Mf32precond,
+                                       shape=(n, n),
+                                       dtype=Mf32.dtype)
+        listM = [None, Ms64, Ms64precondLO, Mf64precondLO, Ms64precond,
+                 Ms32, Ms32precondLO, Mf32precondLO, Ms32precond]
+
+        # Setup matrix of the initial approximation to the eigenvectors
+        # (cannot be sparse array).
+        Xf64 = rnd.random((n, m))
+        Xf32 = Xf64.astype(np.float32)
+        listX = [Xf64, Xf32]
+
+        # Require that the returned eigenvectors be in the orthogonal complement
+        # of the first few standard basis vectors (cannot be sparse array).
+        m_excluded = 3
+        Yf64 = np.eye(n, m_excluded, dtype=float)
+        Yf32 = np.eye(n, m_excluded, dtype=np.float32)
+        listY = [Yf64, Yf32]
+
+        tests = list(itertools.product(listA, listB, listM, listX, listY))
+
+        for A, B, M, X, Y in tests:
+            # This is one of the slower tests because there are >1,000 configs
+            # to test here. Flip a biased coin to decide whether to run  each
+            # test to get decent coverage in less time.
+            if rnd.random() < 0.98:
+                continue  # too many tests
+            eigvals, _ = lobpcg(A, X, B=B, M=M, Y=Y, tol=1e-4,
+                                maxiter=100, largest=False)
+            assert_allclose(eigvals,
+                            np.arange(1 + m_excluded, 1 + m_excluded + m),
+                            atol=1e-5)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/tests/test_svds.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/tests/test_svds.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fddf19af26811364ca8551021244e20c6da2239
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_eigen/tests/test_svds.py
@@ -0,0 +1,886 @@
+import re
+import copy
+import numpy as np
+
+from numpy.testing import assert_allclose, assert_equal, assert_array_equal
+import pytest
+
+from scipy.linalg import svd, null_space
+from scipy.sparse import csc_array, issparse, dia_array, random_array
+from scipy.sparse.linalg import LinearOperator, aslinearoperator
+from scipy.sparse.linalg import svds
+from scipy.sparse.linalg._eigen.arpack import ArpackNoConvergence
+
+
+# --- Helper Functions / Classes ---
+
+
+def sorted_svd(m, k, which='LM'):
+    # Compute svd of a dense matrix m, and return singular vectors/values
+    # sorted.
+    if issparse(m):
+        m = m.toarray()
+    u, s, vh = svd(m)
+    if which == 'LM':
+        ii = np.argsort(s)[-k:]
+    elif which == 'SM':
+        ii = np.argsort(s)[:k]
+    else:
+        raise ValueError(f"unknown which={which!r}")
+
+    return u[:, ii], s[ii], vh[ii]
+
+
+def _check_svds(A, k, u, s, vh, which="LM", check_usvh_A=False,
+                check_svd=True, atol=1e-10, rtol=1e-7):
+    n, m = A.shape
+
+    # Check shapes.
+    assert_equal(u.shape, (n, k))
+    assert_equal(s.shape, (k,))
+    assert_equal(vh.shape, (k, m))
+
+    # Check that the original matrix can be reconstituted.
+    A_rebuilt = (u*s).dot(vh)
+    assert_equal(A_rebuilt.shape, A.shape)
+    if check_usvh_A:
+        assert_allclose(A_rebuilt, A, atol=atol, rtol=rtol)
+
+    # Check that u is a semi-orthogonal matrix.
+    uh_u = np.dot(u.T.conj(), u)
+    assert_equal(uh_u.shape, (k, k))
+    assert_allclose(uh_u, np.identity(k), atol=atol, rtol=rtol)
+
+    # Check that vh is a semi-orthogonal matrix.
+    vh_v = np.dot(vh, vh.T.conj())
+    assert_equal(vh_v.shape, (k, k))
+    assert_allclose(vh_v, np.identity(k), atol=atol, rtol=rtol)
+
+    # Check that scipy.sparse.linalg.svds ~ scipy.linalg.svd
+    if check_svd:
+        u2, s2, vh2 = sorted_svd(A, k, which)
+        assert_allclose(np.abs(u), np.abs(u2), atol=atol, rtol=rtol)
+        assert_allclose(s, s2, atol=atol, rtol=rtol)
+        assert_allclose(np.abs(vh), np.abs(vh2), atol=atol, rtol=rtol)
+
+
+def _check_svds_n(A, k, u, s, vh, which="LM", check_res=True,
+                  check_svd=True, atol=1e-10, rtol=1e-7):
+    n, m = A.shape
+
+    # Check shapes.
+    assert_equal(u.shape, (n, k))
+    assert_equal(s.shape, (k,))
+    assert_equal(vh.shape, (k, m))
+
+    # Check that u is a semi-orthogonal matrix.
+    uh_u = np.dot(u.T.conj(), u)
+    assert_equal(uh_u.shape, (k, k))
+    error = np.sum(np.abs(uh_u - np.identity(k))) / (k * k)
+    assert_allclose(error, 0.0, atol=atol, rtol=rtol)
+
+    # Check that vh is a semi-orthogonal matrix.
+    vh_v = np.dot(vh, vh.T.conj())
+    assert_equal(vh_v.shape, (k, k))
+    error = np.sum(np.abs(vh_v - np.identity(k))) / (k * k)
+    assert_allclose(error, 0.0, atol=atol, rtol=rtol)
+
+    # Check residuals
+    if check_res:
+        ru = A.T.conj() @ u - vh.T.conj() * s
+        rus = np.sum(np.abs(ru)) / (n * k)
+        rvh = A @ vh.T.conj() - u * s
+        rvhs = np.sum(np.abs(rvh)) / (m * k)
+        assert_allclose(rus, 0.0, atol=atol, rtol=rtol)
+        assert_allclose(rvhs, 0.0, atol=atol, rtol=rtol)
+
+    # Check that scipy.sparse.linalg.svds ~ scipy.linalg.svd
+    if check_svd:
+        u2, s2, vh2 = sorted_svd(A, k, which)
+        assert_allclose(s, s2, atol=atol, rtol=rtol)
+        A_rebuilt_svd = (u2*s2).dot(vh2)
+        A_rebuilt = (u*s).dot(vh)
+        assert_equal(A_rebuilt.shape, A.shape)
+        error = np.sum(np.abs(A_rebuilt_svd - A_rebuilt)) / (k * k)
+        assert_allclose(error, 0.0, atol=atol, rtol=rtol)
+
+
+class CheckingLinearOperator(LinearOperator):
+    def __init__(self, A):
+        self.A = A
+        self.dtype = A.dtype
+        self.shape = A.shape
+
+    def _matvec(self, x):
+        assert_equal(max(x.shape), np.size(x))
+        return self.A.dot(x)
+
+    def _rmatvec(self, x):
+        assert_equal(max(x.shape), np.size(x))
+        return self.A.T.conjugate().dot(x)
+
+
+# --- Test Input Validation ---
+# Tests input validation on parameters `k` and `which`.
+# Needs better input validation checks for all other parameters.
+
+class SVDSCommonTests:
+
+    solver = None
+
+    # some of these IV tests could run only once, say with solver=None
+
+    _A_empty_msg = "`A` must not be empty."
+    _A_dtype_msg = "`A` must be of numeric data type"
+    _A_type_msg = "type not understood"
+    _A_ndim_msg = "array must have ndim <= 2"
+    _A_validation_inputs = [
+        (np.asarray([[]]), ValueError, _A_empty_msg),
+        (np.array([['a', 'b'], ['c', 'd']], dtype='object'), ValueError, _A_dtype_msg),
+        ("hi", TypeError, _A_type_msg),
+        (np.asarray([[[1., 2.], [3., 4.]]]), ValueError, _A_ndim_msg)]
+
+    @pytest.mark.parametrize("args", _A_validation_inputs)
+    def test_svds_input_validation_A(self, args):
+        A, error_type, message = args
+        with pytest.raises(error_type, match=message):
+            svds(A, k=1, solver=self.solver, rng=0)
+
+    @pytest.mark.parametrize("which", ["LM", "SM"])
+    def test_svds_int_A(self, which):
+        A = np.asarray([[1, 2], [3, 4]])
+        if self.solver == 'lobpcg':
+            with pytest.warns(UserWarning, match="The problem size"):
+                res = svds(A, k=1, which=which, solver=self.solver, rng=0)
+        else:
+            res = svds(A, k=1, which=which, solver=self.solver, rng=0)
+        _check_svds(A, 1, *res, which=which, atol=8e-10)
+
+    def test_svds_diff0_docstring_example(self):
+        def diff0(a):
+            return np.diff(a, axis=0)
+        def diff0t(a):
+            if a.ndim == 1:
+                a = a[:,np.newaxis]  # Turn 1D into 2D array
+            d = np.zeros((a.shape[0] + 1, a.shape[1]), dtype=a.dtype)
+            d[0, :] = - a[0, :]
+            d[1:-1, :] = a[0:-1, :] - a[1:, :]
+            d[-1, :] = a[-1, :]
+            return d
+        def diff0_func_aslo_def(n):
+            return LinearOperator(matvec=diff0,
+                                  matmat=diff0,
+                                  rmatvec=diff0t,
+                                  rmatmat=diff0t,
+                                  shape=(n - 1, n))
+        n = 100
+        diff0_func_aslo = diff0_func_aslo_def(n)
+        # preserve a use of legacy keyword `random_state` during SPEC 7 transition
+        u, s, _ = svds(diff0_func_aslo, k=3, which='SM', random_state=0)
+        se = 2. * np.sin(np.pi * np.arange(1, 4) / (2. * n))
+        ue = np.sqrt(2 / n) * np.sin(np.pi * np.outer(np.arange(1, n),
+                                     np.arange(1, 4)) / n)
+        assert_allclose(s, se, atol=1e-3)
+        assert_allclose(np.abs(u), np.abs(ue), atol=1e-6)
+
+    @pytest.mark.parametrize("k", [-1, 0, 3, 4, 5, 1.5, "1"])
+    def test_svds_input_validation_k_1(self, k):
+        rng = np.random.default_rng(0)
+        A = rng.random((4, 3))
+
+        # propack can do complete SVD
+        if self.solver == 'propack' and k == 3:
+            res = svds(A, k=k, solver=self.solver, rng=0)
+            _check_svds(A, k, *res, check_usvh_A=True, check_svd=True)
+            return
+
+        message = ("`k` must be an integer satisfying")
+        with pytest.raises(ValueError, match=message):
+            svds(A, k=k, solver=self.solver, rng=0)
+
+    def test_svds_input_validation_k_2(self):
+        # I think the stack trace is reasonable when `k` can't be converted
+        # to an int.
+        message = "int() argument must be a"
+        with pytest.raises(TypeError, match=re.escape(message)):
+            svds(np.eye(10), k=[], solver=self.solver, rng=0)
+
+        message = "invalid literal for int()"
+        with pytest.raises(ValueError, match=message):
+            svds(np.eye(10), k="hi", solver=self.solver, rng=0)
+
+    @pytest.mark.parametrize("tol", (-1, np.inf, np.nan))
+    def test_svds_input_validation_tol_1(self, tol):
+        message = "`tol` must be a non-negative floating point value."
+        with pytest.raises(ValueError, match=message):
+            svds(np.eye(10), tol=tol, solver=self.solver, rng=0)
+
+    @pytest.mark.parametrize("tol", ([], 'hi'))
+    def test_svds_input_validation_tol_2(self, tol):
+        # I think the stack trace is reasonable here
+        message = "'<' not supported between instances"
+        with pytest.raises(TypeError, match=message):
+            svds(np.eye(10), tol=tol, solver=self.solver, rng=0)
+
+    @pytest.mark.parametrize("which", ('LA', 'SA', 'ekki', 0))
+    def test_svds_input_validation_which(self, which):
+        # Regression test for a github issue.
+        # https://github.com/scipy/scipy/issues/4590
+        # Function was not checking for eigenvalue type and unintended
+        # values could be returned.
+        with pytest.raises(ValueError, match="`which` must be in"):
+            svds(np.eye(10), which=which, solver=self.solver, rng=0)
+
+    @pytest.mark.parametrize("transpose", (True, False))
+    @pytest.mark.parametrize("n", range(4, 9))
+    def test_svds_input_validation_v0_1(self, transpose, n):
+        rng = np.random.default_rng(0)
+        A = rng.random((5, 7))
+        v0 = rng.random(n)
+        if transpose:
+            A = A.T
+        k = 2
+        message = "`v0` must have shape"
+
+        required_length = (A.shape[0] if self.solver == 'propack'
+                           else min(A.shape))
+        if n != required_length:
+            with pytest.raises(ValueError, match=message):
+                svds(A, k=k, v0=v0, solver=self.solver, rng=0)
+
+    def test_svds_input_validation_v0_2(self):
+        A = np.ones((10, 10))
+        v0 = np.ones((1, 10))
+        message = "`v0` must have shape"
+        with pytest.raises(ValueError, match=message):
+            svds(A, k=1, v0=v0, solver=self.solver, rng=0)
+
+    @pytest.mark.parametrize("v0", ("hi", 1, np.ones(10, dtype=int)))
+    def test_svds_input_validation_v0_3(self, v0):
+        A = np.ones((10, 10))
+        message = "`v0` must be of floating or complex floating data type."
+        with pytest.raises(ValueError, match=message):
+            svds(A, k=1, v0=v0, solver=self.solver, rng=0)
+
+    @pytest.mark.parametrize("maxiter", (-1, 0, 5.5))
+    def test_svds_input_validation_maxiter_1(self, maxiter):
+        message = ("`maxiter` must be a positive integer.")
+        with pytest.raises(ValueError, match=message):
+            svds(np.eye(10), maxiter=maxiter, solver=self.solver, rng=0)
+
+    def test_svds_input_validation_maxiter_2(self):
+        # I think the stack trace is reasonable when `k` can't be converted
+        # to an int.
+        message = "int() argument must be a"
+        with pytest.raises(TypeError, match=re.escape(message)):
+            svds(np.eye(10), maxiter=[], solver=self.solver, rng=0)
+
+        message = "invalid literal for int()"
+        with pytest.raises(ValueError, match=message):
+            svds(np.eye(10), maxiter="hi", solver=self.solver, rng=0)
+
+    @pytest.mark.parametrize("rsv", ('ekki', 10))
+    def test_svds_input_validation_return_singular_vectors(self, rsv):
+        message = "`return_singular_vectors` must be in"
+        with pytest.raises(ValueError, match=message):
+            svds(np.eye(10), return_singular_vectors=rsv, solver=self.solver, rng=0)
+
+    # --- Test Parameters ---
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize("k", [3, 5])
+    @pytest.mark.parametrize("which", ["LM", "SM"])
+    def test_svds_parameter_k_which(self, k, which):
+        # check that the `k` parameter sets the number of eigenvalues/
+        # eigenvectors returned.
+        # Also check that the `which` parameter sets whether the largest or
+        # smallest eigenvalues are returned
+        rng = np.random.default_rng(0)
+        A = rng.random((10, 10))
+        if self.solver == 'lobpcg':
+            with pytest.warns(UserWarning, match="The problem size"):
+                res = svds(A, k=k, which=which, solver=self.solver, rng=0)
+        else:
+            res = svds(A, k=k, which=which, solver=self.solver, rng=0)
+        _check_svds(A, k, *res, which=which, atol=1e-9, rtol=2e-13)
+
+    @pytest.mark.filterwarnings("ignore:Exited",
+                                reason="Ignore LOBPCG early exit.")
+    # loop instead of parametrize for simplicity
+    def test_svds_parameter_tol(self):
+        # check the effect of the `tol` parameter on solver accuracy by solving
+        # the same problem with varying `tol` and comparing the eigenvalues
+        # against ground truth computed
+        n = 100  # matrix size
+        k = 3    # number of eigenvalues to check
+
+        # generate a random, sparse-ish matrix
+        # effect isn't apparent for matrices that are too small
+        rng = np.random.default_rng(0)
+        A = rng.random((n, n))
+        A[A > .1] = 0
+        A = A @ A.T
+
+        _, s, _ = svd(A)  # calculate ground truth
+
+        # calculate the error as a function of `tol`
+        A = csc_array(A)
+
+        def err(tol):
+            _, s2, _ = svds(A, k=k, v0=np.ones(n), maxiter=1000,
+                            solver=self.solver, tol=tol, rng=0)
+            return np.linalg.norm((s2 - s[k-1::-1])/s[k-1::-1])
+
+        tols = [1e-4, 1e-2, 1e0]  # tolerance levels to check
+        # for 'arpack' and 'propack', accuracies make discrete steps
+        accuracies = {'propack': [1e-12, 1e-6, 1e-4],
+                      'arpack': [2.5e-15, 1e-10, 1e-10],
+                      'lobpcg': [2e-12, 4e-2, 2]}
+
+        for tol, accuracy in zip(tols, accuracies[self.solver]):
+            error = err(tol)
+            assert error < accuracy
+
+    def test_svd_v0(self):
+        # check that the `v0` parameter affects the solution
+        n = 100
+        k = 1
+        # If k != 1, LOBPCG needs more initial vectors, which are generated
+        # with rng, so it does not pass w/ k >= 2.
+        # For some other values of `n`, the AssertionErrors are not raised
+        # with different v0s, which is reasonable.
+
+        rng = np.random.default_rng(0)
+        A = rng.random((n, n))
+
+        # with the same v0, solutions are the same, and they are accurate
+        # v0 takes precedence over rng
+        v0a = rng.random(n)
+        res1a = svds(A, k, v0=v0a, solver=self.solver, rng=0)
+        res2a = svds(A, k, v0=v0a, solver=self.solver, rng=1)
+        for idx in range(3):
+            assert_allclose(res1a[idx], res2a[idx], rtol=1e-15, atol=2e-16)
+        _check_svds(A, k, *res1a)
+
+        # with the same v0, solutions are the same, and they are accurate
+        v0b = rng.random(n)
+        res1b = svds(A, k, v0=v0b, solver=self.solver, rng=2)
+        res2b = svds(A, k, v0=v0b, solver=self.solver, rng=3)
+        for idx in range(3):
+            assert_allclose(res1b[idx], res2b[idx], rtol=1e-15, atol=2e-16)
+        _check_svds(A, k, *res1b)
+
+        # with different v0, solutions can be numerically different
+        message = "Arrays are not equal"
+        with pytest.raises(AssertionError, match=message):
+            assert_equal(res1a, res1b)
+
+    def test_svd_rng(self):
+        # check that the `rng` parameter affects the solution
+        # Admittedly, `n` and `k` are chosen so that all solver pass all
+        # these checks. That's a tall order, since LOBPCG doesn't want to
+        # achieve the desired accuracy and ARPACK often returns the same
+        # singular values/vectors for different v0.
+        n = 100
+        k = 1
+
+        rng = np.random.default_rng(0)
+        A = rng.random((n, n))
+
+        # with the same rng, solutions are the same and accurate
+        res1a = svds(A, k, solver=self.solver, rng=0)
+        res2a = svds(A, k, solver=self.solver, rng=0)
+        for idx in range(3):
+            assert_allclose(res1a[idx], res2a[idx], rtol=1e-15, atol=2e-16)
+        _check_svds(A, k, *res1a)
+
+        # with the same rng, solutions are the same and accurate
+        res1b = svds(A, k, solver=self.solver, rng=1)
+        res2b = svds(A, k, solver=self.solver, rng=1)
+        for idx in range(3):
+            assert_allclose(res1b[idx], res2b[idx], rtol=1e-15, atol=2e-16)
+        _check_svds(A, k, *res1b)
+
+        # with different rng, solutions can be numerically different
+        message = "Arrays are not equal"
+        with pytest.raises(AssertionError, match=message):
+            assert_equal(res1a, res1b)
+
+    def test_svd_rng_2(self):
+        n = 100
+        k = 1
+
+        rng = np.random.default_rng(234981)
+        A = rng.random((n, n))
+        rng_2 = copy.deepcopy(rng)
+
+        # with the same rng, solutions are the same and accurate
+        res1a = svds(A, k, solver=self.solver, rng=rng)
+        res2a = svds(A, k, solver=self.solver, rng=rng_2)
+        for idx in range(3):
+            assert_allclose(res1a[idx], res2a[idx], rtol=1e-15, atol=2e-16)
+        _check_svds(A, k, *res1a)
+
+    @pytest.mark.filterwarnings("ignore:Exited",
+                                reason="Ignore LOBPCG early exit.")
+    def test_svd_rng_3(self):
+        n = 100
+        k = 5
+
+        rng1 = np.random.default_rng(0)
+        rng2 = np.random.default_rng(234832)
+        A = rng1.random((n, n))
+
+        # rng in different state produces accurate - but not
+        # not necessarily identical - results
+        res1a = svds(A, k, solver=self.solver, rng=rng1, maxiter=1000)
+        res2a = svds(A, k, solver=self.solver, rng=rng2, maxiter=1000)
+        _check_svds(A, k, *res1a, atol=2e-7)
+        _check_svds(A, k, *res2a, atol=2e-7)
+
+        message = "Arrays are not equal"
+        with pytest.raises(AssertionError, match=message):
+            assert_equal(res1a, res2a)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.filterwarnings("ignore:Exited postprocessing")
+    def test_svd_maxiter(self):
+        # check that maxiter works as expected: should not return accurate
+        # solution after 1 iteration, but should with default `maxiter`
+        A = np.diag(np.arange(9)).astype(np.float64)
+        k = 1
+        u, s, vh = sorted_svd(A, k)
+        # Use default maxiter by default
+        maxiter = None
+
+        if self.solver == 'arpack':
+            message = "ARPACK error -1: No convergence"
+            with pytest.raises(ArpackNoConvergence, match=message):
+                svds(A, k, ncv=3, maxiter=1, solver=self.solver, rng=0)
+        elif self.solver == 'lobpcg':
+            # Set maxiter higher so test passes without changing
+            # default and breaking backward compatibility (gh-20221)
+            maxiter = 30
+            with pytest.warns(UserWarning, match="Exited at iteration"):
+                svds(A, k, maxiter=1, solver=self.solver, rng=0)
+        elif self.solver == 'propack':
+            message = "k=1 singular triplets did not converge within"
+            with pytest.raises(np.linalg.LinAlgError, match=message):
+                svds(A, k, maxiter=1, solver=self.solver, rng=0)
+
+        ud, sd, vhd = svds(A, k, solver=self.solver, maxiter=maxiter, rng=0)
+        _check_svds(A, k, ud, sd, vhd, atol=1e-8)
+        assert_allclose(np.abs(ud), np.abs(u), atol=1e-8)
+        assert_allclose(np.abs(vhd), np.abs(vh), atol=1e-8)
+        assert_allclose(np.abs(sd), np.abs(s), atol=1e-9)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize("rsv", (True, False, 'u', 'vh'))
+    @pytest.mark.parametrize("shape", ((5, 7), (6, 6), (7, 5)))
+    def test_svd_return_singular_vectors(self, rsv, shape):
+        # check that the return_singular_vectors parameter works as expected
+        rng = np.random.default_rng(0)
+        A = rng.random(shape)
+        k = 2
+        M, N = shape
+        u, s, vh = sorted_svd(A, k)
+
+        respect_u = True if self.solver == 'propack' else M <= N
+        respect_vh = True if self.solver == 'propack' else M > N
+
+        if self.solver == 'lobpcg':
+            with pytest.warns(UserWarning, match="The problem size"):
+                if rsv is False:
+                    s2 = svds(A, k, return_singular_vectors=rsv,
+                              solver=self.solver, rng=rng)
+                    assert_allclose(s2, s)
+                elif rsv == 'u' and respect_u:
+                    u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
+                                       solver=self.solver, rng=rng)
+                    assert_allclose(np.abs(u2), np.abs(u))
+                    assert_allclose(s2, s)
+                    assert vh2 is None
+                elif rsv == 'vh' and respect_vh:
+                    u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
+                                       solver=self.solver, rng=rng)
+                    assert u2 is None
+                    assert_allclose(s2, s)
+                    assert_allclose(np.abs(vh2), np.abs(vh))
+                else:
+                    u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
+                                       solver=self.solver, rng=rng)
+                    if u2 is not None:
+                        assert_allclose(np.abs(u2), np.abs(u))
+                    assert_allclose(s2, s)
+                    if vh2 is not None:
+                        assert_allclose(np.abs(vh2), np.abs(vh))
+        else:
+            if rsv is False:
+                s2 = svds(A, k, return_singular_vectors=rsv,
+                          solver=self.solver, rng=rng)
+                assert_allclose(s2, s)
+            elif rsv == 'u' and respect_u:
+                u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
+                                   solver=self.solver, rng=rng)
+                assert_allclose(np.abs(u2), np.abs(u))
+                assert_allclose(s2, s)
+                assert vh2 is None
+            elif rsv == 'vh' and respect_vh:
+                u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
+                                   solver=self.solver, rng=rng)
+                assert u2 is None
+                assert_allclose(s2, s)
+                assert_allclose(np.abs(vh2), np.abs(vh))
+            else:
+                u2, s2, vh2 = svds(A, k, return_singular_vectors=rsv,
+                                   solver=self.solver, rng=rng)
+                if u2 is not None:
+                    assert_allclose(np.abs(u2), np.abs(u))
+                assert_allclose(s2, s)
+                if vh2 is not None:
+                    assert_allclose(np.abs(vh2), np.abs(vh))
+
+    # --- Test Basic Functionality ---
+    # Tests the accuracy of each solver for real and complex matrices provided
+    # as list, dense array, sparse matrix, and LinearOperator.
+
+    A1 = [[1, 2, 3], [3, 4, 3], [1 + 1j, 0, 2], [0, 0, 1]]
+    A2 = [[1, 2, 3, 8 + 5j], [3 - 2j, 4, 3, 5], [1, 0, 2, 3], [0, 0, 1, 0]]
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.filterwarnings("ignore:k >= N - 1",
+                                reason="needed to demonstrate #16725")
+    @pytest.mark.parametrize('A', (A1, A2))
+    @pytest.mark.parametrize('k', range(1, 5))
+    # PROPACK fails a lot if @pytest.mark.parametrize('which', ("SM", "LM"))
+    @pytest.mark.parametrize('real', (True, False))
+    @pytest.mark.parametrize('transpose', (False, True))
+    # In gh-14299, it was suggested the `svds` should _not_ work with lists
+    @pytest.mark.parametrize('lo_type', (np.asarray, csc_array,
+                                         aslinearoperator))
+    def test_svd_simple(self, A, k, real, transpose, lo_type):
+
+        A = np.asarray(A)
+        A = np.real(A) if real else A
+        A = A.T if transpose else A
+        A2 = lo_type(A)
+
+        # could check for the appropriate errors, but that is tested above
+        if k > min(A.shape):
+            pytest.skip("`k` cannot be greater than `min(A.shape)`")
+        if self.solver != 'propack' and k >= min(A.shape):
+            pytest.skip("Only PROPACK supports complete SVD")
+        if self.solver == 'arpack' and not real and k == min(A.shape) - 1:
+            pytest.skip("#16725")
+
+        atol = 3e-10
+        if self.solver == 'propack':
+            atol = 3e-9  # otherwise test fails on Linux aarch64 (see gh-19855)
+
+        if self.solver == 'lobpcg':
+            with pytest.warns(UserWarning, match="The problem size"):
+                u, s, vh = svds(A2, k, solver=self.solver, rng=0)
+        else:
+            u, s, vh = svds(A2, k, solver=self.solver, rng=0)
+        _check_svds(A, k, u, s, vh, atol=atol)
+
+    @pytest.mark.thread_unsafe
+    def test_svd_linop(self):
+        solver = self.solver
+
+        nmks = [(6, 7, 3),
+                (9, 5, 4),
+                (10, 8, 5)]
+
+        def reorder(args):
+            U, s, VH = args
+            j = np.argsort(s)
+            return U[:, j], s[j], VH[j, :]
+
+        for n, m, k in nmks:
+            # Test svds on a LinearOperator.
+            A = np.random.RandomState(52).randn(n, m)
+            L = CheckingLinearOperator(A)
+
+            if solver == 'propack':
+                v0 = np.ones(n)
+            else:
+                v0 = np.ones(min(A.shape))
+            if solver == 'lobpcg':
+                with pytest.warns(UserWarning, match="The problem size"):
+                    U1, s1, VH1 = reorder(svds(A, k, v0=v0, solver=solver, rng=0))
+                    U2, s2, VH2 = reorder(svds(L, k, v0=v0, solver=solver, rng=0))
+            else:
+                U1, s1, VH1 = reorder(svds(A, k, v0=v0, solver=solver, rng=0))
+                U2, s2, VH2 = reorder(svds(L, k, v0=v0, solver=solver, rng=0))
+
+            assert_allclose(np.abs(U1), np.abs(U2))
+            assert_allclose(s1, s2)
+            assert_allclose(np.abs(VH1), np.abs(VH2))
+            assert_allclose(np.dot(U1, np.dot(np.diag(s1), VH1)),
+                            np.dot(U2, np.dot(np.diag(s2), VH2)))
+
+            # Try again with which="SM".
+            A = np.random.RandomState(1909).randn(n, m)
+            L = CheckingLinearOperator(A)
+
+            # TODO: arpack crashes when v0=v0, which="SM"
+            kwargs = {'v0': v0} if solver not in {None, 'arpack'} else {}
+            if self.solver == 'lobpcg':
+                with pytest.warns(UserWarning, match="The problem size"):
+                    U1, s1, VH1 = reorder(svds(A, k, which="SM", solver=solver,
+                                               rng=0, **kwargs))
+                    U2, s2, VH2 = reorder(svds(L, k, which="SM", solver=solver,
+                                               rng=0, **kwargs))
+            else:
+                U1, s1, VH1 = reorder(svds(A, k, which="SM", solver=solver,
+                                           rng=0, **kwargs))
+                U2, s2, VH2 = reorder(svds(L, k, which="SM", solver=solver,
+                                           rng=0, **kwargs))
+
+            assert_allclose(np.abs(U1), np.abs(U2))
+            assert_allclose(s1 + 1, s2 + 1)
+            assert_allclose(np.abs(VH1), np.abs(VH2))
+            assert_allclose(np.dot(U1, np.dot(np.diag(s1), VH1)),
+                            np.dot(U2, np.dot(np.diag(s2), VH2)))
+
+            if k < min(n, m) - 1:
+                # Complex input and explicit which="LM".
+                for (dt, eps) in [(complex, 1e-7), (np.complex64, 3e-3)]:
+                    rng = np.random.RandomState(1648)
+                    A = (rng.randn(n, m) + 1j * rng.randn(n, m)).astype(dt)
+                    L = CheckingLinearOperator(A)
+
+                    if self.solver == 'lobpcg':
+                        with pytest.warns(UserWarning,
+                                          match="The problem size"):
+                            U1, s1, VH1 = reorder(svds(A, k, which="LM",
+                                                       solver=solver, rng=0))
+                            U2, s2, VH2 = reorder(svds(L, k, which="LM",
+                                                       solver=solver, rng=0))
+                    else:
+                        U1, s1, VH1 = reorder(svds(A, k, which="LM",
+                                                   solver=solver, rng=0))
+                        U2, s2, VH2 = reorder(svds(L, k, which="LM",
+                                                   solver=solver, rng=0))
+
+                    assert_allclose(np.abs(U1), np.abs(U2), rtol=eps)
+                    assert_allclose(s1, s2, rtol=eps)
+                    assert_allclose(np.abs(VH1), np.abs(VH2), rtol=eps)
+                    assert_allclose(np.dot(U1, np.dot(np.diag(s1), VH1)),
+                                    np.dot(U2, np.dot(np.diag(s2), VH2)),
+                                    rtol=eps)
+
+    SHAPES = ((100, 100), (100, 101), (101, 100))
+
+    @pytest.mark.filterwarnings("ignore:Exited at iteration")
+    @pytest.mark.filterwarnings("ignore:Exited postprocessing")
+    @pytest.mark.parametrize("shape", SHAPES)
+    # ARPACK supports only dtype float, complex, or np.float32
+    @pytest.mark.parametrize("dtype", (float, complex, np.float32))
+    def test_small_sigma_sparse(self, shape, dtype):
+        # https://github.com/scipy/scipy/pull/11829
+        solver = self.solver
+        # 2do: PROPACK fails orthogonality of singular vectors
+        # if dtype == complex and self.solver == 'propack':
+        #    pytest.skip("PROPACK unsupported for complex dtype")
+        rng = np.random.default_rng(0)
+        k = 5
+        (m, n) = shape
+        S = random_array(shape=(m, n), density=0.1, rng=rng)
+        if dtype is complex:
+            S = + 1j * random_array(shape=(m, n), density=0.1, rng=rng)
+        e = np.ones(m)
+        e[0:5] *= 1e1 ** np.arange(-5, 0, 1)
+        S = dia_array((e, 0), shape=(m, m)) @ S
+        S = S.astype(dtype)
+        u, s, vh = svds(S, k, which='SM', solver=solver, maxiter=1000, rng=0)
+        c_svd = False  # partial SVD can be different from full SVD
+        _check_svds_n(S, k, u, s, vh, which="SM", check_svd=c_svd, atol=2e-1)
+
+    # --- Test Edge Cases ---
+    # Checks a few edge cases.
+    @pytest.mark.thread_unsafe
+    @pytest.mark.parametrize("shape", ((6, 5), (5, 5), (5, 6)))
+    @pytest.mark.parametrize("dtype", (float, complex))
+    def test_svd_LM_ones_matrix(self, shape, dtype):
+        # Check that svds can deal with matrix_rank less than k in LM mode.
+        k = 3
+        n, m = shape
+        A = np.ones((n, m), dtype=dtype)
+
+        if self.solver == 'lobpcg':
+            with pytest.warns(UserWarning, match="The problem size"):
+                U, s, VH = svds(A, k, solver=self.solver, rng=0)
+        else:
+            U, s, VH = svds(A, k, solver=self.solver, rng=0)
+
+        _check_svds(A, k, U, s, VH, check_usvh_A=True, check_svd=False)
+
+        # Check that the largest singular value is near sqrt(n*m)
+        # and the other singular values have been forced to zero.
+        assert_allclose(np.max(s), np.sqrt(n*m))
+        s = np.array(sorted(s)[:-1]) + 1
+        z = np.ones_like(s)
+        assert_allclose(s, z)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.filterwarnings("ignore:k >= N - 1",
+                                reason="needed to demonstrate #16725")
+    @pytest.mark.parametrize("shape", ((3, 4), (4, 4), (4, 3), (4, 2)))
+    @pytest.mark.parametrize("dtype", (float, complex))
+    def test_zero_matrix(self, shape, dtype):
+        # Check that svds can deal with matrices containing only zeros;
+        # see https://github.com/scipy/scipy/issues/3452/
+        # shape = (4, 2) is included because it is the particular case
+        # reported in the issue
+        k = 1
+        n, m = shape
+        A = np.zeros((n, m), dtype=dtype)
+
+        if (self.solver == 'arpack'):
+            pytest.skip('See gh-21110.')
+
+        if (self.solver == 'arpack' and dtype is complex
+                and k == min(A.shape) - 1):
+            pytest.skip("#16725")
+
+        if self.solver == 'propack':
+            pytest.skip("PROPACK failures unrelated to PR #16712")
+
+        if self.solver == 'lobpcg':
+            with pytest.warns(UserWarning, match="The problem size"):
+                U, s, VH = svds(A, k, solver=self.solver, rng=0)
+        else:
+            U, s, VH = svds(A, k, solver=self.solver, rng=0)
+
+        # Check some generic properties of svd.
+        _check_svds(A, k, U, s, VH, check_usvh_A=True, check_svd=False)
+
+        # Check that the singular values are zero.
+        assert_array_equal(s, 0)
+
+    @pytest.mark.parametrize("shape", ((20, 20), (20, 21), (21, 20)))
+    # ARPACK supports only dtype float, complex, or np.float32
+    @pytest.mark.parametrize("dtype", (float, complex, np.float32))
+    @pytest.mark.filterwarnings("ignore:Exited",
+                                reason="Ignore LOBPCG early exit.")
+    def test_small_sigma(self, shape, dtype):
+        rng = np.random.default_rng(179847540)
+        A = rng.random(shape).astype(dtype)
+        u, _, vh = svd(A, full_matrices=False)
+        if dtype == np.float32:
+            e = 10.0
+        else:
+            e = 100.0
+        t = e**(-np.arange(len(vh))).astype(dtype)
+        A = (u*t).dot(vh)
+        k = 4
+        u, s, vh = svds(A, k, solver=self.solver, maxiter=100, rng=0)
+        t = np.sum(s > 0)
+        assert_equal(t, k)
+        # LOBPCG needs larger atol and rtol to pass
+        _check_svds_n(A, k, u, s, vh, atol=1e-3, rtol=1e0, check_svd=False)
+
+    # ARPACK supports only dtype float, complex, or np.float32
+    @pytest.mark.filterwarnings("ignore:The problem size")
+    @pytest.mark.parametrize("dtype", (float, complex, np.float32))
+    def test_small_sigma2(self, dtype):
+        rng = np.random.default_rng(179847540)
+        # create a 10x10 singular matrix with a 4-dim null space
+        dim = 4
+        size = 10
+        x = rng.random((size, size-dim))
+        y = x[:, :dim] * rng.random(dim)
+        mat = np.hstack((x, y))
+        mat = mat.astype(dtype)
+
+        nz = null_space(mat)
+        assert_equal(nz.shape[1], dim)
+
+        # Tolerances atol and rtol adjusted to pass np.float32
+        # Use non-sparse svd
+        u, s, vh = svd(mat)
+        # Singular values are 0:
+        assert_allclose(s[-dim:], 0, atol=1e-6, rtol=1e0)
+        # Smallest right singular vectors in null space:
+        assert_allclose(mat @ vh[-dim:, :].T, 0, atol=1e-6, rtol=1e0)
+
+        # Smallest singular values should be 0
+        sp_mat = csc_array(mat)
+        su, ss, svh = svds(sp_mat, k=dim, which='SM', solver=self.solver, rng=0)
+        # Smallest dim singular values are 0:
+        assert_allclose(ss, 0, atol=1e-5, rtol=1e0)
+        # Smallest singular vectors via svds in null space:
+        n, m = mat.shape
+        if n < m:  # else the assert fails with some libraries unclear why
+            assert_allclose(sp_mat.transpose() @ su, 0, atol=1e-5, rtol=1e0)
+        assert_allclose(sp_mat @ svh.T, 0, atol=1e-5, rtol=1e0)
+
+# --- Perform tests with each solver ---
+
+
+class Test_SVDS_once:
+    @pytest.mark.parametrize("solver", ['ekki', object])
+    def test_svds_input_validation_solver(self, solver):
+        message = "solver must be one of"
+        with pytest.raises(ValueError, match=message):
+            svds(np.ones((3, 4)), k=2, solver=solver, rng=0)
+
+
+class Test_SVDS_ARPACK(SVDSCommonTests):
+
+    def setup_method(self):
+        self.solver = 'arpack'
+
+    @pytest.mark.parametrize("ncv", list(range(-1, 8)) + [4.5, "5"])
+    def test_svds_input_validation_ncv_1(self, ncv):
+        rng = np.random.default_rng(0)
+        A = rng.random((6, 7))
+        k = 3
+        if ncv in {4, 5}:
+            u, s, vh = svds(A, k=k, ncv=ncv, solver=self.solver, rng=0)
+        # partial decomposition, so don't check that u@diag(s)@vh=A;
+        # do check that scipy.sparse.linalg.svds ~ scipy.linalg.svd
+            _check_svds(A, k, u, s, vh)
+        else:
+            message = ("`ncv` must be an integer satisfying")
+            with pytest.raises(ValueError, match=message):
+                svds(A, k=k, ncv=ncv, solver=self.solver, rng=0)
+
+    def test_svds_input_validation_ncv_2(self):
+        # I think the stack trace is reasonable when `ncv` can't be converted
+        # to an int.
+        message = "int() argument must be a"
+        with pytest.raises(TypeError, match=re.escape(message)):
+            svds(np.eye(10), ncv=[], solver=self.solver, rng=0)
+
+        message = "invalid literal for int()"
+        with pytest.raises(ValueError, match=message):
+            svds(np.eye(10), ncv="hi", solver=self.solver, rng=0)
+
+    # I can't see a robust relationship between `ncv` and relevant outputs
+    # (e.g. accuracy, time), so no test of the parameter.
+
+
+class Test_SVDS_LOBPCG(SVDSCommonTests):
+
+    def setup_method(self):
+        self.solver = 'lobpcg'
+
+
+class Test_SVDS_PROPACK(SVDSCommonTests):
+
+    def setup_method(self):
+        self.solver = 'propack'
+
+    def test_svd_LM_ones_matrix(self):
+        message = ("PROPACK does not return orthonormal singular vectors "
+                   "associated with zero singular values.")
+        # There are some other issues with this matrix of all ones, e.g.
+        # `which='sm'` and `k=1` returns the largest singular value
+        pytest.xfail(message)
+
+    def test_svd_LM_zeros_matrix(self):
+        message = ("PROPACK does not return orthonormal singular vectors "
+                   "associated with zero singular values.")
+        pytest.xfail(message)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b57274542928e79c234bb6955849a90be21990e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__init__.py
@@ -0,0 +1,20 @@
+"Iterative Solvers for Sparse Linear Systems"
+
+#from info import __doc__
+from .iterative import *
+from .minres import minres
+from .lgmres import lgmres
+from .lsqr import lsqr
+from .lsmr import lsmr
+from ._gcrotmk import gcrotmk
+from .tfqmr import tfqmr
+
+__all__ = [
+    'bicg', 'bicgstab', 'cg', 'cgs', 'gcrotmk', 'gmres',
+    'lgmres', 'lsmr', 'lsqr',
+    'minres', 'qmr', 'tfqmr'
+]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c96a390039da7136cb8d360e3804a8232f484c9c
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/_gcrotmk.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/_gcrotmk.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..889a5f9dfd5a8fe87cb404622999fc78d63f3a0d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/_gcrotmk.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/iterative.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/iterative.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf81102afe11f602edff7ab796414cca3a4d7871
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/iterative.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lgmres.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lgmres.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c217d0acef91ad11610b1424bbe407c2bee750d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lgmres.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsmr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsmr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0c08d913529d54b0a9a8af22ae1bfd94b68ca77
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsmr.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsqr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsqr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fec34c6259e72aebb9884eeec6a354c0405e1f3
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/lsqr.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/minres.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/minres.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce800d1ecc6d028cc28814ea883586ae12037fbb
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/minres.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/tfqmr.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/tfqmr.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e85ae4e9da680c4eaf6b2b25d4f5c32c902e91e6
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/tfqmr.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/utils.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/utils.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c07f2e6cd63f17de1ccfad37c5ff0141057d17aa
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/utils.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/_gcrotmk.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/_gcrotmk.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5c1fe9daee2c5a955dd71de3e82f33e3dc02179
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/_gcrotmk.py
@@ -0,0 +1,503 @@
+# Copyright (C) 2015, Pauli Virtanen 
+# Distributed under the same license as SciPy.
+
+import numpy as np
+from numpy.linalg import LinAlgError
+from scipy.linalg import (get_blas_funcs, qr, solve, svd, qr_insert, lstsq)
+from .iterative import _get_atol_rtol
+from scipy.sparse.linalg._isolve.utils import make_system
+
+
+__all__ = ['gcrotmk']
+
+
+def _fgmres(matvec, v0, m, atol, lpsolve=None, rpsolve=None, cs=(), outer_v=(),
+            prepend_outer_v=False):
+    """
+    FGMRES Arnoldi process, with optional projection or augmentation
+
+    Parameters
+    ----------
+    matvec : callable
+        Operation A*x
+    v0 : ndarray
+        Initial vector, normalized to nrm2(v0) == 1
+    m : int
+        Number of GMRES rounds
+    atol : float
+        Absolute tolerance for early exit
+    lpsolve : callable
+        Left preconditioner L
+    rpsolve : callable
+        Right preconditioner R
+    cs : list of (ndarray, ndarray)
+        Columns of matrices C and U in GCROT
+    outer_v : list of ndarrays
+        Augmentation vectors in LGMRES
+    prepend_outer_v : bool, optional
+        Whether augmentation vectors come before or after
+        Krylov iterates
+
+    Raises
+    ------
+    LinAlgError
+        If nans encountered
+
+    Returns
+    -------
+    Q, R : ndarray
+        QR decomposition of the upper Hessenberg H=QR
+    B : ndarray
+        Projections corresponding to matrix C
+    vs : list of ndarray
+        Columns of matrix V
+    zs : list of ndarray
+        Columns of matrix Z
+    y : ndarray
+        Solution to ||H y - e_1||_2 = min!
+    res : float
+        The final (preconditioned) residual norm
+
+    """
+
+    if lpsolve is None:
+        def lpsolve(x):
+            return x
+    if rpsolve is None:
+        def rpsolve(x):
+            return x
+
+    axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'], (v0,))
+
+    vs = [v0]
+    zs = []
+    y = None
+    res = np.nan
+
+    m = m + len(outer_v)
+
+    # Orthogonal projection coefficients
+    B = np.zeros((len(cs), m), dtype=v0.dtype)
+
+    # H is stored in QR factorized form
+    Q = np.ones((1, 1), dtype=v0.dtype)
+    R = np.zeros((1, 0), dtype=v0.dtype)
+
+    eps = np.finfo(v0.dtype).eps
+
+    breakdown = False
+
+    # FGMRES Arnoldi process
+    for j in range(m):
+        # L A Z = C B + V H
+
+        if prepend_outer_v and j < len(outer_v):
+            z, w = outer_v[j]
+        elif prepend_outer_v and j == len(outer_v):
+            z = rpsolve(v0)
+            w = None
+        elif not prepend_outer_v and j >= m - len(outer_v):
+            z, w = outer_v[j - (m - len(outer_v))]
+        else:
+            z = rpsolve(vs[-1])
+            w = None
+
+        if w is None:
+            w = lpsolve(matvec(z))
+        else:
+            # w is clobbered below
+            w = w.copy()
+
+        w_norm = nrm2(w)
+
+        # GCROT projection: L A -> (1 - C C^H) L A
+        # i.e. orthogonalize against C
+        for i, c in enumerate(cs):
+            alpha = dot(c, w)
+            B[i,j] = alpha
+            w = axpy(c, w, c.shape[0], -alpha)  # w -= alpha*c
+
+        # Orthogonalize against V
+        hcur = np.zeros(j+2, dtype=Q.dtype)
+        for i, v in enumerate(vs):
+            alpha = dot(v, w)
+            hcur[i] = alpha
+            w = axpy(v, w, v.shape[0], -alpha)  # w -= alpha*v
+        hcur[i+1] = nrm2(w)
+
+        with np.errstate(over='ignore', divide='ignore'):
+            # Careful with denormals
+            alpha = 1/hcur[-1]
+
+        if np.isfinite(alpha):
+            w = scal(alpha, w)
+
+        if not (hcur[-1] > eps * w_norm):
+            # w essentially in the span of previous vectors,
+            # or we have nans. Bail out after updating the QR
+            # solution.
+            breakdown = True
+
+        vs.append(w)
+        zs.append(z)
+
+        # Arnoldi LSQ problem
+
+        # Add new column to H=Q@R, padding other columns with zeros
+        Q2 = np.zeros((j+2, j+2), dtype=Q.dtype, order='F')
+        Q2[:j+1,:j+1] = Q
+        Q2[j+1,j+1] = 1
+
+        R2 = np.zeros((j+2, j), dtype=R.dtype, order='F')
+        R2[:j+1,:] = R
+
+        Q, R = qr_insert(Q2, R2, hcur, j, which='col',
+                         overwrite_qru=True, check_finite=False)
+
+        # Transformed least squares problem
+        # || Q R y - inner_res_0 * e_1 ||_2 = min!
+        # Since R = [R'; 0], solution is y = inner_res_0 (R')^{-1} (Q^H)[:j,0]
+
+        # Residual is immediately known
+        res = abs(Q[0,-1])
+
+        # Check for termination
+        if res < atol or breakdown:
+            break
+
+    if not np.isfinite(R[j,j]):
+        # nans encountered, bail out
+        raise LinAlgError()
+
+    # -- Get the LSQ problem solution
+
+    # The problem is triangular, but the condition number may be
+    # bad (or in case of breakdown the last diagonal entry may be
+    # zero), so use lstsq instead of trtrs.
+    y, _, _, _, = lstsq(R[:j+1,:j+1], Q[0,:j+1].conj())
+
+    B = B[:,:j+1]
+
+    return Q, R, B, vs, zs, y, res
+
+
+def gcrotmk(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=1000, M=None, callback=None,
+            m=20, k=None, CU=None, discard_C=False, truncate='oldest'):
+    """
+    Solve a matrix equation using flexible GCROT(m,k) algorithm.
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real or complex N-by-N matrix of the linear system.
+        Alternatively, `A` can be a linear operator which can
+        produce ``Ax`` using, e.g.,
+        `LinearOperator`.
+    b : ndarray
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+    x0 : ndarray
+        Starting guess for the solution.
+    rtol, atol : float, optional
+        Parameters for the convergence test. For convergence,
+        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
+        The default is ``rtol=1e-5`` and ``atol=0.0``.
+    maxiter : int, optional
+        Maximum number of iterations.  Iteration will stop after maxiter
+        steps even if the specified tolerance has not been achieved. The
+        default is ``1000``.
+    M : {sparse array, ndarray, LinearOperator}, optional
+        Preconditioner for `A`.  The preconditioner should approximate the
+        inverse of `A`. gcrotmk is a 'flexible' algorithm and the preconditioner
+        can vary from iteration to iteration. Effective preconditioning
+        dramatically improves the rate of convergence, which implies that
+        fewer iterations are needed to reach a given error tolerance.
+    callback : function, optional
+        User-supplied function to call after each iteration.  It is called
+        as ``callback(xk)``, where ``xk`` is the current solution vector.
+    m : int, optional
+        Number of inner FGMRES iterations per each outer iteration.
+        Default: 20
+    k : int, optional
+        Number of vectors to carry between inner FGMRES iterations.
+        According to [2]_, good values are around `m`.
+        Default: `m`
+    CU : list of tuples, optional
+        List of tuples ``(c, u)`` which contain the columns of the matrices
+        C and U in the GCROT(m,k) algorithm. For details, see [2]_.
+        The list given and vectors contained in it are modified in-place.
+        If not given, start from empty matrices. The ``c`` elements in the
+        tuples can be ``None``, in which case the vectors are recomputed
+        via ``c = A u`` on start and orthogonalized as described in [3]_.
+    discard_C : bool, optional
+        Discard the C-vectors at the end. Useful if recycling Krylov subspaces
+        for different linear systems.
+    truncate : {'oldest', 'smallest'}, optional
+        Truncation scheme to use. Drop: oldest vectors, or vectors with
+        smallest singular values using the scheme discussed in [1,2].
+        See [2]_ for detailed comparison.
+        Default: 'oldest'
+
+    Returns
+    -------
+    x : ndarray
+        The solution found.
+    info : int
+        Provides convergence information:
+
+        * 0  : successful exit
+        * >0 : convergence to tolerance not achieved, number of iterations
+
+    References
+    ----------
+    .. [1] E. de Sturler, ''Truncation strategies for optimal Krylov subspace
+           methods'', SIAM J. Numer. Anal. 36, 864 (1999).
+    .. [2] J.E. Hicken and D.W. Zingg, ''A simplified and flexible variant
+           of GCROT for solving nonsymmetric linear systems'',
+           SIAM J. Sci. Comput. 32, 172 (2010).
+    .. [3] M.L. Parks, E. de Sturler, G. Mackey, D.D. Johnson, S. Maiti,
+           ''Recycling Krylov subspaces for sequences of linear systems'',
+           SIAM J. Sci. Comput. 28, 1651 (2006).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import gcrotmk
+    >>> R = np.random.randn(5, 5)
+    >>> A = csc_array(R)
+    >>> b = np.random.randn(5)
+    >>> x, exit_code = gcrotmk(A, b, atol=1e-5)
+    >>> print(exit_code)
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+
+    """
+    A,M,x,b,postprocess = make_system(A,M,x0,b)
+
+    if not np.isfinite(b).all():
+        raise ValueError("RHS must contain only finite numbers")
+
+    if truncate not in ('oldest', 'smallest'):
+        raise ValueError(f"Invalid value for 'truncate': {truncate!r}")
+
+    matvec = A.matvec
+    psolve = M.matvec
+
+    if CU is None:
+        CU = []
+
+    if k is None:
+        k = m
+
+    axpy, dot, scal = None, None, None
+
+    if x0 is None:
+        r = b.copy()
+    else:
+        r = b - matvec(x)
+
+    axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'], (x, r))
+
+    b_norm = nrm2(b)
+
+    # we call this to get the right atol/rtol and raise errors as necessary
+    atol, rtol = _get_atol_rtol('gcrotmk', b_norm, atol, rtol)
+
+    if b_norm == 0:
+        x = b
+        return (postprocess(x), 0)
+
+    if discard_C:
+        CU[:] = [(None, u) for c, u in CU]
+
+    # Reorthogonalize old vectors
+    if CU:
+        # Sort already existing vectors to the front
+        CU.sort(key=lambda cu: cu[0] is not None)
+
+        # Fill-in missing ones
+        C = np.empty((A.shape[0], len(CU)), dtype=r.dtype, order='F')
+        us = []
+        j = 0
+        while CU:
+            # More memory-efficient: throw away old vectors as we go
+            c, u = CU.pop(0)
+            if c is None:
+                c = matvec(u)
+            C[:,j] = c
+            j += 1
+            us.append(u)
+
+        # Orthogonalize
+        Q, R, P = qr(C, overwrite_a=True, mode='economic', pivoting=True)
+        del C
+
+        # C := Q
+        cs = list(Q.T)
+
+        # U := U P R^-1,  back-substitution
+        new_us = []
+        for j in range(len(cs)):
+            u = us[P[j]]
+            for i in range(j):
+                u = axpy(us[P[i]], u, u.shape[0], -R[i,j])
+            if abs(R[j,j]) < 1e-12 * abs(R[0,0]):
+                # discard rest of the vectors
+                break
+            u = scal(1.0/R[j,j], u)
+            new_us.append(u)
+
+        # Form the new CU lists
+        CU[:] = list(zip(cs, new_us))[::-1]
+
+    if CU:
+        axpy, dot = get_blas_funcs(['axpy', 'dot'], (r,))
+
+        # Solve first the projection operation with respect to the CU
+        # vectors. This corresponds to modifying the initial guess to
+        # be
+        #
+        #     x' = x + U y
+        #     y = argmin_y || b - A (x + U y) ||^2
+        #
+        # The solution is y = C^H (b - A x)
+        for c, u in CU:
+            yc = dot(c, r)
+            x = axpy(u, x, x.shape[0], yc)
+            r = axpy(c, r, r.shape[0], -yc)
+
+    # GCROT main iteration
+    for j_outer in range(maxiter):
+        # -- callback
+        if callback is not None:
+            callback(x)
+
+        beta = nrm2(r)
+
+        # -- check stopping condition
+        beta_tol = max(atol, rtol * b_norm)
+
+        if beta <= beta_tol and (j_outer > 0 or CU):
+            # recompute residual to avoid rounding error
+            r = b - matvec(x)
+            beta = nrm2(r)
+
+        if beta <= beta_tol:
+            j_outer = -1
+            break
+
+        ml = m + max(k - len(CU), 0)
+
+        cs = [c for c, u in CU]
+
+        try:
+            Q, R, B, vs, zs, y, pres = _fgmres(matvec,
+                                               r/beta,
+                                               ml,
+                                               rpsolve=psolve,
+                                               atol=max(atol, rtol*b_norm)/beta,
+                                               cs=cs)
+            y *= beta
+        except LinAlgError:
+            # Floating point over/underflow, non-finite result from
+            # matmul etc. -- report failure.
+            break
+
+        #
+        # At this point,
+        #
+        #     [A U, A Z] = [C, V] G;   G =  [ I  B ]
+        #                                   [ 0  H ]
+        #
+        # where [C, V] has orthonormal columns, and r = beta v_0. Moreover,
+        #
+        #     || b - A (x + Z y + U q) ||_2 = || r - C B y - V H y - C q ||_2 = min!
+        #
+        # from which y = argmin_y || beta e_1 - H y ||_2, and q = -B y
+        #
+
+        #
+        # GCROT(m,k) update
+        #
+
+        # Define new outer vectors
+
+        # ux := (Z - U B) y
+        ux = zs[0]*y[0]
+        for z, yc in zip(zs[1:], y[1:]):
+            ux = axpy(z, ux, ux.shape[0], yc)  # ux += z*yc
+        by = B.dot(y)
+        for cu, byc in zip(CU, by):
+            c, u = cu
+            ux = axpy(u, ux, ux.shape[0], -byc)  # ux -= u*byc
+
+        # cx := V H y
+        with np.errstate(invalid="ignore"):
+            hy = Q.dot(R.dot(y))
+        cx = vs[0] * hy[0]
+        for v, hyc in zip(vs[1:], hy[1:]):
+            cx = axpy(v, cx, cx.shape[0], hyc)  # cx += v*hyc
+
+        # Normalize cx, maintaining cx = A ux
+        # This new cx is orthogonal to the previous C, by construction
+        try:
+            alpha = 1/nrm2(cx)
+            if not np.isfinite(alpha):
+                raise FloatingPointError()
+        except (FloatingPointError, ZeroDivisionError):
+            # Cannot update, so skip it
+            continue
+
+        cx = scal(alpha, cx)
+        ux = scal(alpha, ux)
+
+        # Update residual and solution
+        gamma = dot(cx, r)
+        r = axpy(cx, r, r.shape[0], -gamma)  # r -= gamma*cx
+        x = axpy(ux, x, x.shape[0], gamma)  # x += gamma*ux
+
+        # Truncate CU
+        if truncate == 'oldest':
+            while len(CU) >= k and CU:
+                del CU[0]
+        elif truncate == 'smallest':
+            if len(CU) >= k and CU:
+                # cf. [1,2]
+                D = solve(R[:-1,:].T, B.T).T
+                W, sigma, V = svd(D)
+
+                # C := C W[:,:k-1],  U := U W[:,:k-1]
+                new_CU = []
+                for j, w in enumerate(W[:,:k-1].T):
+                    c, u = CU[0]
+                    c = c * w[0]
+                    u = u * w[0]
+                    for cup, wp in zip(CU[1:], w[1:]):
+                        cp, up = cup
+                        c = axpy(cp, c, c.shape[0], wp)
+                        u = axpy(up, u, u.shape[0], wp)
+
+                    # Reorthogonalize at the same time; not necessary
+                    # in exact arithmetic, but floating point error
+                    # tends to accumulate here
+                    for cp, up in new_CU:
+                        alpha = dot(cp, c)
+                        c = axpy(cp, c, c.shape[0], -alpha)
+                        u = axpy(up, u, u.shape[0], -alpha)
+                    alpha = nrm2(c)
+                    c = scal(1.0/alpha, c)
+                    u = scal(1.0/alpha, u)
+
+                    new_CU.append((c, u))
+                CU[:] = new_CU
+
+        # Add new vector to CU
+        CU.append((cx, ux))
+
+    # Include the solution vector to the span
+    CU.append((None, x.copy()))
+    if discard_C:
+        CU[:] = [(None, uz) for cz, uz in CU]
+
+    return postprocess(x), j_outer + 1
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/iterative.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/iterative.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b91ef8fe4b37191e76710670eccd9557a397964
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/iterative.py
@@ -0,0 +1,1045 @@
+import warnings
+import numpy as np
+from scipy.sparse.linalg._interface import LinearOperator
+from .utils import make_system
+from scipy.linalg import get_lapack_funcs
+
+__all__ = ['bicg', 'bicgstab', 'cg', 'cgs', 'gmres', 'qmr']
+
+
+def _get_atol_rtol(name, b_norm, atol=0., rtol=1e-5):
+    """
+    A helper function to handle tolerance normalization
+    """
+    if atol == 'legacy' or atol is None or atol < 0:
+        msg = (f"'scipy.sparse.linalg.{name}' called with invalid `atol`={atol}; "
+               "if set, `atol` must be a real, non-negative number.")
+        raise ValueError(msg)
+
+    atol = max(float(atol), float(rtol) * float(b_norm))
+
+    return atol, rtol
+
+
+def bicg(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, callback=None):
+    """Use BIConjugate Gradient iteration to solve ``Ax = b``.
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real or complex N-by-N matrix of the linear system.
+        Alternatively, `A` can be a linear operator which can
+        produce ``Ax`` and ``A^T x`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : ndarray
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+    x0 : ndarray
+        Starting guess for the solution.
+    rtol, atol : float, optional
+        Parameters for the convergence test. For convergence,
+        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
+        The default is ``atol=0.`` and ``rtol=1e-5``.
+    maxiter : integer
+        Maximum number of iterations.  Iteration will stop after maxiter
+        steps even if the specified tolerance has not been achieved.
+    M : {sparse array, ndarray, LinearOperator}
+        Preconditioner for `A`. It should approximate the
+        inverse of `A` (see Notes). Effective preconditioning dramatically improves the
+        rate of convergence, which implies that fewer iterations are needed
+        to reach a given error tolerance.
+    callback : function
+        User-supplied function to call after each iteration.  It is called
+        as ``callback(xk)``, where ``xk`` is the current solution vector.
+
+    Returns
+    -------
+    x : ndarray
+        The converged solution.
+    info : integer
+        Provides convergence information:
+            0  : successful exit
+            >0 : convergence to tolerance not achieved, number of iterations
+            <0 : parameter breakdown
+
+    Notes
+    -----
+    The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller
+    condition number than `A`, see [1]_ .
+
+    References
+    ----------
+    .. [1] "Preconditioner", Wikipedia, 
+           https://en.wikipedia.org/wiki/Preconditioner
+    .. [2] "Biconjugate gradient method", Wikipedia, 
+           https://en.wikipedia.org/wiki/Biconjugate_gradient_method
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import bicg
+    >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1.]])
+    >>> b = np.array([2., 4., -1.])
+    >>> x, exitCode = bicg(A, b, atol=1e-5)
+    >>> print(exitCode)  # 0 indicates successful convergence
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+    """
+    A, M, x, b, postprocess = make_system(A, M, x0, b)
+    bnrm2 = np.linalg.norm(b)
+
+    atol, _ = _get_atol_rtol('bicg', bnrm2, atol, rtol)
+
+    if bnrm2 == 0:
+        return postprocess(b), 0
+
+    n = len(b)
+    dotprod = np.vdot if np.iscomplexobj(x) else np.dot
+
+    if maxiter is None:
+        maxiter = n*10
+
+    matvec, rmatvec = A.matvec, A.rmatvec
+    psolve, rpsolve = M.matvec, M.rmatvec
+
+    rhotol = np.finfo(x.dtype.char).eps**2
+
+    # Dummy values to initialize vars, silence linter warnings
+    rho_prev, p, ptilde = None, None, None
+
+    r = b - matvec(x) if x.any() else b.copy()
+    rtilde = r.copy()
+
+    for iteration in range(maxiter):
+        if np.linalg.norm(r) < atol:  # Are we done?
+            return postprocess(x), 0
+
+        z = psolve(r)
+        ztilde = rpsolve(rtilde)
+        # order matters in this dot product
+        rho_cur = dotprod(rtilde, z)
+
+        if np.abs(rho_cur) < rhotol:  # Breakdown case
+            return postprocess, -10
+
+        if iteration > 0:
+            beta = rho_cur / rho_prev
+            p *= beta
+            p += z
+            ptilde *= beta.conj()
+            ptilde += ztilde
+        else:  # First spin
+            p = z.copy()
+            ptilde = ztilde.copy()
+
+        q = matvec(p)
+        qtilde = rmatvec(ptilde)
+        rv = dotprod(ptilde, q)
+
+        if rv == 0:
+            return postprocess(x), -11
+
+        alpha = rho_cur / rv
+        x += alpha*p
+        r -= alpha*q
+        rtilde -= alpha.conj()*qtilde
+        rho_prev = rho_cur
+
+        if callback:
+            callback(x)
+
+    else:  # for loop exhausted
+        # Return incomplete progress
+        return postprocess(x), maxiter
+
+
+def bicgstab(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None,
+             callback=None):
+    """Use BIConjugate Gradient STABilized iteration to solve ``Ax = b``.
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real or complex N-by-N matrix of the linear system.
+        Alternatively, `A` can be a linear operator which can
+        produce ``Ax`` and ``A^T x`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : ndarray
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+    x0 : ndarray
+        Starting guess for the solution.
+    rtol, atol : float, optional
+        Parameters for the convergence test. For convergence,
+        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
+        The default is ``atol=0.`` and ``rtol=1e-5``.
+    maxiter : integer
+        Maximum number of iterations.  Iteration will stop after maxiter
+        steps even if the specified tolerance has not been achieved.
+    M : {sparse array, ndarray, LinearOperator}
+        Preconditioner for `A`. It should approximate the
+        inverse of `A` (see Notes). Effective preconditioning dramatically improves the
+        rate of convergence, which implies that fewer iterations are needed
+        to reach a given error tolerance.
+    callback : function
+        User-supplied function to call after each iteration.  It is called
+        as ``callback(xk)``, where ``xk`` is the current solution vector.
+
+    Returns
+    -------
+    x : ndarray
+        The converged solution.
+    info : integer
+        Provides convergence information:
+            0  : successful exit
+            >0 : convergence to tolerance not achieved, number of iterations
+            <0 : parameter breakdown
+
+    Notes
+    -----
+    The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller
+    condition number than `A`, see [1]_ .
+
+    References
+    ----------
+    .. [1] "Preconditioner", Wikipedia, 
+           https://en.wikipedia.org/wiki/Preconditioner
+    .. [2] "Biconjugate gradient stabilized method", 
+           Wikipedia, https://en.wikipedia.org/wiki/Biconjugate_gradient_stabilized_method
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import bicgstab
+    >>> R = np.array([[4, 2, 0, 1],
+    ...               [3, 0, 0, 2],
+    ...               [0, 1, 1, 1],
+    ...               [0, 2, 1, 0]])
+    >>> A = csc_array(R)
+    >>> b = np.array([-1, -0.5, -1, 2])
+    >>> x, exit_code = bicgstab(A, b, atol=1e-5)
+    >>> print(exit_code)  # 0 indicates successful convergence
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+    """
+    A, M, x, b, postprocess = make_system(A, M, x0, b)
+    bnrm2 = np.linalg.norm(b)
+
+    atol, _ = _get_atol_rtol('bicgstab', bnrm2, atol, rtol)
+
+    if bnrm2 == 0:
+        return postprocess(b), 0
+
+    n = len(b)
+
+    dotprod = np.vdot if np.iscomplexobj(x) else np.dot
+
+    if maxiter is None:
+        maxiter = n*10
+
+    matvec = A.matvec
+    psolve = M.matvec
+
+    # These values make no sense but coming from original Fortran code
+    # sqrt might have been meant instead.
+    rhotol = np.finfo(x.dtype.char).eps**2
+    omegatol = rhotol
+
+    # Dummy values to initialize vars, silence linter warnings
+    rho_prev, omega, alpha, p, v = None, None, None, None, None
+
+    r = b - matvec(x) if x.any() else b.copy()
+    rtilde = r.copy()
+
+    for iteration in range(maxiter):
+        if np.linalg.norm(r) < atol:  # Are we done?
+            return postprocess(x), 0
+
+        rho = dotprod(rtilde, r)
+        if np.abs(rho) < rhotol:  # rho breakdown
+            return postprocess(x), -10
+
+        if iteration > 0:
+            if np.abs(omega) < omegatol:  # omega breakdown
+                return postprocess(x), -11
+
+            beta = (rho / rho_prev) * (alpha / omega)
+            p -= omega*v
+            p *= beta
+            p += r
+        else:  # First spin
+            s = np.empty_like(r)
+            p = r.copy()
+
+        phat = psolve(p)
+        v = matvec(phat)
+        rv = dotprod(rtilde, v)
+        if rv == 0:
+            return postprocess(x), -11
+        alpha = rho / rv
+        r -= alpha*v
+        s[:] = r[:]
+
+        if np.linalg.norm(s) < atol:
+            x += alpha*phat
+            return postprocess(x), 0
+
+        shat = psolve(s)
+        t = matvec(shat)
+        omega = dotprod(t, s) / dotprod(t, t)
+        x += alpha*phat
+        x += omega*shat
+        r -= omega*t
+        rho_prev = rho
+
+        if callback:
+            callback(x)
+
+    else:  # for loop exhausted
+        # Return incomplete progress
+        return postprocess(x), maxiter
+
+
+def cg(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, callback=None):
+    """Use Conjugate Gradient iteration to solve ``Ax = b``.
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real or complex N-by-N matrix of the linear system.
+        `A` must represent a hermitian, positive definite matrix.
+        Alternatively, `A` can be a linear operator which can
+        produce ``Ax`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : ndarray
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+    x0 : ndarray
+        Starting guess for the solution.
+    rtol, atol : float, optional
+        Parameters for the convergence test. For convergence,
+        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
+        The default is ``atol=0.`` and ``rtol=1e-5``.
+    maxiter : integer
+        Maximum number of iterations.  Iteration will stop after maxiter
+        steps even if the specified tolerance has not been achieved.
+    M : {sparse array, ndarray, LinearOperator}
+        Preconditioner for `A`. `M` must represent a hermitian, positive definite
+        matrix. It should approximate the inverse of `A` (see Notes).
+        Effective preconditioning dramatically improves the
+        rate of convergence, which implies that fewer iterations are needed
+        to reach a given error tolerance.
+    callback : function
+        User-supplied function to call after each iteration.  It is called
+        as ``callback(xk)``, where ``xk`` is the current solution vector.
+
+    Returns
+    -------
+    x : ndarray
+        The converged solution.
+    info : integer
+        Provides convergence information:
+            0  : successful exit
+            >0 : convergence to tolerance not achieved, number of iterations
+
+    Notes
+    -----
+    The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller
+    condition number than `A`, see [2]_.
+
+    References
+    ----------
+    .. [1] "Conjugate Gradient Method, Wikipedia, 
+           https://en.wikipedia.org/wiki/Conjugate_gradient_method
+    .. [2] "Preconditioner", 
+           Wikipedia, https://en.wikipedia.org/wiki/Preconditioner
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import cg
+    >>> P = np.array([[4, 0, 1, 0],
+    ...               [0, 5, 0, 0],
+    ...               [1, 0, 3, 2],
+    ...               [0, 0, 2, 4]])
+    >>> A = csc_array(P)
+    >>> b = np.array([-1, -0.5, -1, 2])
+    >>> x, exit_code = cg(A, b, atol=1e-5)
+    >>> print(exit_code)    # 0 indicates successful convergence
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+    """
+    A, M, x, b, postprocess = make_system(A, M, x0, b)
+    bnrm2 = np.linalg.norm(b)
+
+    atol, _ = _get_atol_rtol('cg', bnrm2, atol, rtol)
+
+    if bnrm2 == 0:
+        return postprocess(b), 0
+
+    n = len(b)
+
+    if maxiter is None:
+        maxiter = n*10
+
+    dotprod = np.vdot if np.iscomplexobj(x) else np.dot
+
+    matvec = A.matvec
+    psolve = M.matvec
+    r = b - matvec(x) if x.any() else b.copy()
+
+    # Dummy value to initialize var, silences warnings
+    rho_prev, p = None, None
+
+    for iteration in range(maxiter):
+        if np.linalg.norm(r) < atol:  # Are we done?
+            return postprocess(x), 0
+
+        z = psolve(r)
+        rho_cur = dotprod(r, z)
+        if iteration > 0:
+            beta = rho_cur / rho_prev
+            p *= beta
+            p += z
+        else:  # First spin
+            p = np.empty_like(r)
+            p[:] = z[:]
+
+        q = matvec(p)
+        alpha = rho_cur / dotprod(p, q)
+        x += alpha*p
+        r -= alpha*q
+        rho_prev = rho_cur
+
+        if callback:
+            callback(x)
+
+    else:  # for loop exhausted
+        # Return incomplete progress
+        return postprocess(x), maxiter
+
+
+def cgs(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None, callback=None):
+    """Use Conjugate Gradient Squared iteration to solve ``Ax = b``.
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real-valued N-by-N matrix of the linear system.
+        Alternatively, `A` can be a linear operator which can
+        produce ``Ax`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : ndarray
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+    x0 : ndarray
+        Starting guess for the solution.
+    rtol, atol : float, optional
+        Parameters for the convergence test. For convergence,
+        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
+        The default is ``atol=0.`` and ``rtol=1e-5``.
+    maxiter : integer
+        Maximum number of iterations.  Iteration will stop after maxiter
+        steps even if the specified tolerance has not been achieved.
+    M : {sparse array, ndarray, LinearOperator}
+        Preconditioner for ``A``. It should approximate the
+        inverse of `A` (see Notes). Effective preconditioning dramatically improves the
+        rate of convergence, which implies that fewer iterations are needed
+        to reach a given error tolerance.
+    callback : function
+        User-supplied function to call after each iteration.  It is called
+        as ``callback(xk)``, where ``xk`` is the current solution vector.
+
+    Returns
+    -------
+    x : ndarray
+        The converged solution.
+    info : integer
+        Provides convergence information:
+            0  : successful exit
+            >0 : convergence to tolerance not achieved, number of iterations
+            <0 : parameter breakdown
+
+    Notes
+    -----
+    The preconditioner `M` should be a matrix such that ``M @ A`` has a smaller
+    condition number than `A`, see [1]_.
+
+    References
+    ----------
+    .. [1] "Preconditioner", Wikipedia, 
+           https://en.wikipedia.org/wiki/Preconditioner
+    .. [2] "Conjugate gradient squared", Wikipedia,
+           https://en.wikipedia.org/wiki/Conjugate_gradient_squared_method
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import cgs
+    >>> R = np.array([[4, 2, 0, 1],
+    ...               [3, 0, 0, 2],
+    ...               [0, 1, 1, 1],
+    ...               [0, 2, 1, 0]])
+    >>> A = csc_array(R)
+    >>> b = np.array([-1, -0.5, -1, 2])
+    >>> x, exit_code = cgs(A, b)
+    >>> print(exit_code)  # 0 indicates successful convergence
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+    """
+    A, M, x, b, postprocess = make_system(A, M, x0, b)
+    bnrm2 = np.linalg.norm(b)
+
+    atol, _ = _get_atol_rtol('cgs', bnrm2, atol, rtol)
+
+    if bnrm2 == 0:
+        return postprocess(b), 0
+
+    n = len(b)
+
+    dotprod = np.vdot if np.iscomplexobj(x) else np.dot
+
+    if maxiter is None:
+        maxiter = n*10
+
+    matvec = A.matvec
+    psolve = M.matvec
+
+    rhotol = np.finfo(x.dtype.char).eps**2
+
+    r = b - matvec(x) if x.any() else b.copy()
+
+    rtilde = r.copy()
+    bnorm = np.linalg.norm(b)
+    if bnorm == 0:
+        bnorm = 1
+
+    # Dummy values to initialize vars, silence linter warnings
+    rho_prev, p, u, q = None, None, None, None
+
+    for iteration in range(maxiter):
+        rnorm = np.linalg.norm(r)
+        if rnorm < atol:  # Are we done?
+            return postprocess(x), 0
+
+        rho_cur = dotprod(rtilde, r)
+        if np.abs(rho_cur) < rhotol:  # Breakdown case
+            return postprocess, -10
+
+        if iteration > 0:
+            beta = rho_cur / rho_prev
+
+            # u = r + beta * q
+            # p = u + beta * (q + beta * p);
+            u[:] = r[:]
+            u += beta*q
+
+            p *= beta
+            p += q
+            p *= beta
+            p += u
+
+        else:  # First spin
+            p = r.copy()
+            u = r.copy()
+            q = np.empty_like(r)
+
+        phat = psolve(p)
+        vhat = matvec(phat)
+        rv = dotprod(rtilde, vhat)
+
+        if rv == 0:  # Dot product breakdown
+            return postprocess(x), -11
+
+        alpha = rho_cur / rv
+        q[:] = u[:]
+        q -= alpha*vhat
+        uhat = psolve(u + q)
+        x += alpha*uhat
+
+        # Due to numerical error build-up the actual residual is computed
+        # instead of the following two lines that were in the original
+        # FORTRAN templates, still using a single matvec.
+
+        # qhat = matvec(uhat)
+        # r -= alpha*qhat
+        r = b - matvec(x)
+
+        rho_prev = rho_cur
+
+        if callback:
+            callback(x)
+
+    else:  # for loop exhausted
+        # Return incomplete progress
+        return postprocess(x), maxiter
+
+
+def gmres(A, b, x0=None, *, rtol=1e-5, atol=0., restart=None, maxiter=None, M=None,
+          callback=None, callback_type=None):
+    """
+    Use Generalized Minimal RESidual iteration to solve ``Ax = b``.
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real or complex N-by-N matrix of the linear system.
+        Alternatively, `A` can be a linear operator which can
+        produce ``Ax`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : ndarray
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+    x0 : ndarray
+        Starting guess for the solution (a vector of zeros by default).
+    atol, rtol : float
+        Parameters for the convergence test. For convergence,
+        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
+        The default is ``atol=0.`` and ``rtol=1e-5``.
+    restart : int, optional
+        Number of iterations between restarts. Larger values increase
+        iteration cost, but may be necessary for convergence.
+        If omitted, ``min(20, n)`` is used.
+    maxiter : int, optional
+        Maximum number of iterations (restart cycles).  Iteration will stop
+        after maxiter steps even if the specified tolerance has not been
+        achieved. See `callback_type`.
+    M : {sparse array, ndarray, LinearOperator}
+        Inverse of the preconditioner of `A`.  `M` should approximate the
+        inverse of `A` and be easy to solve for (see Notes).  Effective
+        preconditioning dramatically improves the rate of convergence,
+        which implies that fewer iterations are needed to reach a given
+        error tolerance.  By default, no preconditioner is used.
+        In this implementation, left preconditioning is used,
+        and the preconditioned residual is minimized. However, the final
+        convergence is tested with respect to the ``b - A @ x`` residual.
+    callback : function
+        User-supplied function to call after each iteration.  It is called
+        as ``callback(args)``, where ``args`` are selected by `callback_type`.
+    callback_type : {'x', 'pr_norm', 'legacy'}, optional
+        Callback function argument requested:
+          - ``x``: current iterate (ndarray), called on every restart
+          - ``pr_norm``: relative (preconditioned) residual norm (float),
+            called on every inner iteration
+          - ``legacy`` (default): same as ``pr_norm``, but also changes the
+            meaning of `maxiter` to count inner iterations instead of restart
+            cycles.
+
+        This keyword has no effect if `callback` is not set.
+
+    Returns
+    -------
+    x : ndarray
+        The converged solution.
+    info : int
+        Provides convergence information:
+            0  : successful exit
+            >0 : convergence to tolerance not achieved, number of iterations
+
+    See Also
+    --------
+    LinearOperator
+
+    Notes
+    -----
+    A preconditioner, P, is chosen such that P is close to A but easy to solve
+    for. The preconditioner parameter required by this routine is
+    ``M = P^-1``. The inverse should preferably not be calculated
+    explicitly.  Rather, use the following template to produce M::
+
+      # Construct a linear operator that computes P^-1 @ x.
+      import scipy.sparse.linalg as spla
+      M_x = lambda x: spla.spsolve(P, x)
+      M = spla.LinearOperator((n, n), M_x)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import gmres
+    >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
+    >>> b = np.array([2, 4, -1], dtype=float)
+    >>> x, exitCode = gmres(A, b, atol=1e-5)
+    >>> print(exitCode)            # 0 indicates successful convergence
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+    """
+    if callback is not None and callback_type is None:
+        # Warn about 'callback_type' semantic changes.
+        # Probably should be removed only in far future, Scipy 2.0 or so.
+        msg = ("scipy.sparse.linalg.gmres called without specifying "
+               "`callback_type`. The default value will be changed in"
+               " a future release. For compatibility, specify a value "
+               "for `callback_type` explicitly, e.g., "
+               "``gmres(..., callback_type='pr_norm')``, or to retain the "
+               "old behavior ``gmres(..., callback_type='legacy')``"
+               )
+        warnings.warn(msg, category=DeprecationWarning, stacklevel=3)
+
+    if callback_type is None:
+        callback_type = 'legacy'
+
+    if callback_type not in ('x', 'pr_norm', 'legacy'):
+        raise ValueError(f"Unknown callback_type: {callback_type!r}")
+
+    if callback is None:
+        callback_type = None
+
+    A, M, x, b, postprocess = make_system(A, M, x0, b)
+    matvec = A.matvec
+    psolve = M.matvec
+    n = len(b)
+    bnrm2 = np.linalg.norm(b)
+
+    atol, _ = _get_atol_rtol('gmres', bnrm2, atol, rtol)
+
+    if bnrm2 == 0:
+        return postprocess(b), 0
+
+    eps = np.finfo(x.dtype.char).eps
+
+    dotprod = np.vdot if np.iscomplexobj(x) else np.dot
+
+    if maxiter is None:
+        maxiter = n*10
+
+    if restart is None:
+        restart = 20
+    restart = min(restart, n)
+
+    Mb_nrm2 = np.linalg.norm(psolve(b))
+
+    # ====================================================
+    # =========== Tolerance control from gh-8400 =========
+    # ====================================================
+    # Tolerance passed to GMRESREVCOM applies to the inner
+    # iteration and deals with the left-preconditioned
+    # residual.
+    ptol_max_factor = 1.
+    ptol = Mb_nrm2 * min(ptol_max_factor, atol / bnrm2)
+    presid = 0.
+    # ====================================================
+    lartg = get_lapack_funcs('lartg', dtype=x.dtype)
+
+    # allocate internal variables
+    v = np.empty([restart+1, n], dtype=x.dtype)
+    h = np.zeros([restart, restart+1], dtype=x.dtype)
+    givens = np.zeros([restart, 2], dtype=x.dtype)
+
+    # legacy iteration count
+    inner_iter = 0
+
+    for iteration in range(maxiter):
+        if iteration == 0:
+            r = b - matvec(x) if x.any() else b.copy()
+            if np.linalg.norm(r) < atol:  # Are we done?
+                return postprocess(x), 0
+
+        v[0, :] = psolve(r)
+        tmp = np.linalg.norm(v[0, :])
+        v[0, :] *= (1 / tmp)
+        # RHS of the Hessenberg problem
+        S = np.zeros(restart+1, dtype=x.dtype)
+        S[0] = tmp
+
+        breakdown = False
+        for col in range(restart):
+            av = matvec(v[col, :])
+            w = psolve(av)
+
+            # Modified Gram-Schmidt
+            h0 = np.linalg.norm(w)
+            for k in range(col+1):
+                tmp = dotprod(v[k, :], w)
+                h[col, k] = tmp
+                w -= tmp*v[k, :]
+
+            h1 = np.linalg.norm(w)
+            h[col, col + 1] = h1
+            v[col + 1, :] = w[:]
+
+            # Exact solution indicator
+            if h1 <= eps*h0:
+                h[col, col + 1] = 0
+                breakdown = True
+            else:
+                v[col + 1, :] *= (1 / h1)
+
+            # apply past Givens rotations to current h column
+            for k in range(col):
+                c, s = givens[k, 0], givens[k, 1]
+                n0, n1 = h[col, [k, k+1]]
+                h[col, [k, k + 1]] = [c*n0 + s*n1, -s.conj()*n0 + c*n1]
+
+            # get and apply current rotation to h and S
+            c, s, mag = lartg(h[col, col], h[col, col+1])
+            givens[col, :] = [c, s]
+            h[col, [col, col+1]] = mag, 0
+
+            # S[col+1] component is always 0
+            tmp = -np.conjugate(s)*S[col]
+            S[[col, col + 1]] = [c*S[col], tmp]
+            presid = np.abs(tmp)
+            inner_iter += 1
+
+            if callback_type in ('legacy', 'pr_norm'):
+                callback(presid / bnrm2)
+            # Legacy behavior
+            if callback_type == 'legacy' and inner_iter == maxiter:
+                break
+            if presid <= ptol or breakdown:
+                break
+
+        # Solve h(col, col) upper triangular system and allow pseudo-solve
+        # singular cases as in (but without the f2py copies):
+        # y = trsv(h[:col+1, :col+1].T, S[:col+1])
+
+        if h[col, col] == 0:
+            S[col] = 0
+
+        y = np.zeros([col+1], dtype=x.dtype)
+        y[:] = S[:col+1]
+        for k in range(col, 0, -1):
+            if y[k] != 0:
+                y[k] /= h[k, k]
+                tmp = y[k]
+                y[:k] -= tmp*h[k, :k]
+        if y[0] != 0:
+            y[0] /= h[0, 0]
+
+        x += y @ v[:col+1, :]
+
+        r = b - matvec(x)
+        rnorm = np.linalg.norm(r)
+
+        # Legacy exit
+        if callback_type == 'legacy' and inner_iter == maxiter:
+            return postprocess(x), 0 if rnorm <= atol else maxiter
+
+        if callback_type == 'x':
+            callback(x)
+
+        if rnorm <= atol:
+            break
+        elif breakdown:
+            # Reached breakdown (= exact solution), but the external
+            # tolerance check failed. Bail out with failure.
+            break
+        elif presid <= ptol:
+            # Inner loop passed but outer didn't
+            ptol_max_factor = max(eps, 0.25 * ptol_max_factor)
+        else:
+            ptol_max_factor = min(1.0, 1.5 * ptol_max_factor)
+
+        ptol = presid * min(ptol_max_factor, atol / rnorm)
+
+    info = 0 if (rnorm <= atol) else maxiter
+    return postprocess(x), info
+
+
+def qmr(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M1=None, M2=None,
+        callback=None):
+    """Use Quasi-Minimal Residual iteration to solve ``Ax = b``.
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real-valued N-by-N matrix of the linear system.
+        Alternatively, ``A`` can be a linear operator which can
+        produce ``Ax`` and ``A^T x`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : ndarray
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+    x0 : ndarray
+        Starting guess for the solution.
+    atol, rtol : float, optional
+        Parameters for the convergence test. For convergence,
+        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
+        The default is ``atol=0.`` and ``rtol=1e-5``.
+    maxiter : integer
+        Maximum number of iterations.  Iteration will stop after maxiter
+        steps even if the specified tolerance has not been achieved.
+    M1 : {sparse array, ndarray, LinearOperator}
+        Left preconditioner for A.
+    M2 : {sparse array, ndarray, LinearOperator}
+        Right preconditioner for A. Used together with the left
+        preconditioner M1.  The matrix M1@A@M2 should have better
+        conditioned than A alone.
+    callback : function
+        User-supplied function to call after each iteration.  It is called
+        as callback(xk), where xk is the current solution vector.
+
+    Returns
+    -------
+    x : ndarray
+        The converged solution.
+    info : integer
+        Provides convergence information:
+            0  : successful exit
+            >0 : convergence to tolerance not achieved, number of iterations
+            <0 : parameter breakdown
+
+    See Also
+    --------
+    LinearOperator
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import qmr
+    >>> A = csc_array([[3., 2., 0.], [1., -1., 0.], [0., 5., 1.]])
+    >>> b = np.array([2., 4., -1.])
+    >>> x, exitCode = qmr(A, b, atol=1e-5)
+    >>> print(exitCode)            # 0 indicates successful convergence
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+    """
+    A_ = A
+    A, M, x, b, postprocess = make_system(A, None, x0, b)
+    bnrm2 = np.linalg.norm(b)
+
+    atol, _ = _get_atol_rtol('qmr', bnrm2, atol, rtol)
+
+    if bnrm2 == 0:
+        return postprocess(b), 0
+
+    if M1 is None and M2 is None:
+        if hasattr(A_, 'psolve'):
+            def left_psolve(b):
+                return A_.psolve(b, 'left')
+
+            def right_psolve(b):
+                return A_.psolve(b, 'right')
+
+            def left_rpsolve(b):
+                return A_.rpsolve(b, 'left')
+
+            def right_rpsolve(b):
+                return A_.rpsolve(b, 'right')
+            M1 = LinearOperator(A.shape,
+                                matvec=left_psolve,
+                                rmatvec=left_rpsolve)
+            M2 = LinearOperator(A.shape,
+                                matvec=right_psolve,
+                                rmatvec=right_rpsolve)
+        else:
+            def id(b):
+                return b
+            M1 = LinearOperator(A.shape, matvec=id, rmatvec=id)
+            M2 = LinearOperator(A.shape, matvec=id, rmatvec=id)
+
+    n = len(b)
+    if maxiter is None:
+        maxiter = n*10
+
+    dotprod = np.vdot if np.iscomplexobj(x) else np.dot
+
+    rhotol = np.finfo(x.dtype.char).eps
+    betatol = rhotol
+    gammatol = rhotol
+    deltatol = rhotol
+    epsilontol = rhotol
+    xitol = rhotol
+
+    r = b - A.matvec(x) if x.any() else b.copy()
+
+    vtilde = r.copy()
+    y = M1.matvec(vtilde)
+    rho = np.linalg.norm(y)
+    wtilde = r.copy()
+    z = M2.rmatvec(wtilde)
+    xi = np.linalg.norm(z)
+    gamma, eta, theta = 1, -1, 0
+    v = np.empty_like(vtilde)
+    w = np.empty_like(wtilde)
+
+    # Dummy values to initialize vars, silence linter warnings
+    epsilon, q, d, p, s = None, None, None, None, None
+
+    for iteration in range(maxiter):
+        if np.linalg.norm(r) < atol:  # Are we done?
+            return postprocess(x), 0
+        if np.abs(rho) < rhotol:  # rho breakdown
+            return postprocess(x), -10
+        if np.abs(xi) < xitol:  # xi breakdown
+            return postprocess(x), -15
+
+        v[:] = vtilde[:]
+        v *= (1 / rho)
+        y *= (1 / rho)
+        w[:] = wtilde[:]
+        w *= (1 / xi)
+        z *= (1 / xi)
+        delta = dotprod(z, y)
+
+        if np.abs(delta) < deltatol:  # delta breakdown
+            return postprocess(x), -13
+
+        ytilde = M2.matvec(y)
+        ztilde = M1.rmatvec(z)
+
+        if iteration > 0:
+            ytilde -= (xi * delta / epsilon) * p
+            p[:] = ytilde[:]
+            ztilde -= (rho * (delta / epsilon).conj()) * q
+            q[:] = ztilde[:]
+        else:  # First spin
+            p = ytilde.copy()
+            q = ztilde.copy()
+
+        ptilde = A.matvec(p)
+        epsilon = dotprod(q, ptilde)
+        if np.abs(epsilon) < epsilontol:  # epsilon breakdown
+            return postprocess(x), -14
+
+        beta = epsilon / delta
+        if np.abs(beta) < betatol:  # beta breakdown
+            return postprocess(x), -11
+
+        vtilde[:] = ptilde[:]
+        vtilde -= beta*v
+        y = M1.matvec(vtilde)
+
+        rho_prev = rho
+        rho = np.linalg.norm(y)
+        wtilde[:] = w[:]
+        wtilde *= - beta.conj()
+        wtilde += A.rmatvec(q)
+        z = M2.rmatvec(wtilde)
+        xi = np.linalg.norm(z)
+        gamma_prev = gamma
+        theta_prev = theta
+        theta = rho / (gamma_prev * np.abs(beta))
+        gamma = 1 / np.sqrt(1 + theta**2)
+
+        if np.abs(gamma) < gammatol:  # gamma breakdown
+            return postprocess(x), -12
+
+        eta *= -(rho_prev / beta) * (gamma / gamma_prev)**2
+
+        if iteration > 0:
+            d *= (theta_prev * gamma) ** 2
+            d += eta*p
+            s *= (theta_prev * gamma) ** 2
+            s += eta*ptilde
+        else:
+            d = p.copy()
+            d *= eta
+            s = ptilde.copy()
+            s *= eta
+
+        x += d
+        r -= s
+
+        if callback:
+            callback(x)
+
+    else:  # for loop exhausted
+        # Return incomplete progress
+        return postprocess(x), maxiter
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lgmres.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lgmres.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce368e81a07f282d091cd9bc8281c98e720a206b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lgmres.py
@@ -0,0 +1,230 @@
+# Copyright (C) 2009, Pauli Virtanen 
+# Distributed under the same license as SciPy.
+
+import numpy as np
+from numpy.linalg import LinAlgError
+from scipy.linalg import get_blas_funcs
+from .iterative import _get_atol_rtol
+from .utils import make_system
+
+from ._gcrotmk import _fgmres
+
+__all__ = ['lgmres']
+
+
+def lgmres(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=1000, M=None, callback=None,
+           inner_m=30, outer_k=3, outer_v=None, store_outer_Av=True,
+           prepend_outer_v=False):
+    """
+    Solve a matrix equation using the LGMRES algorithm.
+
+    The LGMRES algorithm [1]_ [2]_ is designed to avoid some problems
+    in the convergence in restarted GMRES, and often converges in fewer
+    iterations.
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real or complex N-by-N matrix of the linear system.
+        Alternatively, ``A`` can be a linear operator which can
+        produce ``Ax`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : ndarray
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+    x0 : ndarray
+        Starting guess for the solution.
+    rtol, atol : float, optional
+        Parameters for the convergence test. For convergence,
+        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
+        The default is ``rtol=1e-5``, the default for ``atol`` is ``0.0``.
+    maxiter : int, optional
+        Maximum number of iterations.  Iteration will stop after maxiter
+        steps even if the specified tolerance has not been achieved.
+    M : {sparse array, ndarray, LinearOperator}, optional
+        Preconditioner for A.  The preconditioner should approximate the
+        inverse of A.  Effective preconditioning dramatically improves the
+        rate of convergence, which implies that fewer iterations are needed
+        to reach a given error tolerance.
+    callback : function, optional
+        User-supplied function to call after each iteration.  It is called
+        as callback(xk), where xk is the current solution vector.
+    inner_m : int, optional
+        Number of inner GMRES iterations per each outer iteration.
+    outer_k : int, optional
+        Number of vectors to carry between inner GMRES iterations.
+        According to [1]_, good values are in the range of 1...3.
+        However, note that if you want to use the additional vectors to
+        accelerate solving multiple similar problems, larger values may
+        be beneficial.
+    outer_v : list of tuples, optional
+        List containing tuples ``(v, Av)`` of vectors and corresponding
+        matrix-vector products, used to augment the Krylov subspace, and
+        carried between inner GMRES iterations. The element ``Av`` can
+        be `None` if the matrix-vector product should be re-evaluated.
+        This parameter is modified in-place by `lgmres`, and can be used
+        to pass "guess" vectors in and out of the algorithm when solving
+        similar problems.
+    store_outer_Av : bool, optional
+        Whether LGMRES should store also A@v in addition to vectors `v`
+        in the `outer_v` list. Default is True.
+    prepend_outer_v : bool, optional
+        Whether to put outer_v augmentation vectors before Krylov iterates.
+        In standard LGMRES, prepend_outer_v=False.
+
+    Returns
+    -------
+    x : ndarray
+        The converged solution.
+    info : int
+        Provides convergence information:
+
+            - 0  : successful exit
+            - >0 : convergence to tolerance not achieved, number of iterations
+            - <0 : illegal input or breakdown
+
+    Notes
+    -----
+    The LGMRES algorithm [1]_ [2]_ is designed to avoid the
+    slowing of convergence in restarted GMRES, due to alternating
+    residual vectors. Typically, it often outperforms GMRES(m) of
+    comparable memory requirements by some measure, or at least is not
+    much worse.
+
+    Another advantage in this algorithm is that you can supply it with
+    'guess' vectors in the `outer_v` argument that augment the Krylov
+    subspace. If the solution lies close to the span of these vectors,
+    the algorithm converges faster. This can be useful if several very
+    similar matrices need to be inverted one after another, such as in
+    Newton-Krylov iteration where the Jacobian matrix often changes
+    little in the nonlinear steps.
+
+    References
+    ----------
+    .. [1] A.H. Baker and E.R. Jessup and T. Manteuffel, "A Technique for
+             Accelerating the Convergence of Restarted GMRES", SIAM J. Matrix
+             Anal. Appl. 26, 962 (2005).
+    .. [2] A.H. Baker, "On Improving the Performance of the Linear Solver
+             restarted GMRES", PhD thesis, University of Colorado (2003).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import lgmres
+    >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
+    >>> b = np.array([2, 4, -1], dtype=float)
+    >>> x, exitCode = lgmres(A, b, atol=1e-5)
+    >>> print(exitCode)            # 0 indicates successful convergence
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+    """
+    A,M,x,b,postprocess = make_system(A,M,x0,b)
+
+    if not np.isfinite(b).all():
+        raise ValueError("RHS must contain only finite numbers")
+
+    matvec = A.matvec
+    psolve = M.matvec
+
+    if outer_v is None:
+        outer_v = []
+
+    axpy, dot, scal = None, None, None
+    nrm2 = get_blas_funcs('nrm2', [b])
+
+    b_norm = nrm2(b)
+
+    # we call this to get the right atol/rtol and raise errors as necessary
+    atol, rtol = _get_atol_rtol('lgmres', b_norm, atol, rtol)
+
+    if b_norm == 0:
+        x = b
+        return (postprocess(x), 0)
+
+    ptol_max_factor = 1.0
+
+    for k_outer in range(maxiter):
+        r_outer = matvec(x) - b
+
+        # -- callback
+        if callback is not None:
+            callback(x)
+
+        # -- determine input type routines
+        if axpy is None:
+            if np.iscomplexobj(r_outer) and not np.iscomplexobj(x):
+                x = x.astype(r_outer.dtype)
+            axpy, dot, scal, nrm2 = get_blas_funcs(['axpy', 'dot', 'scal', 'nrm2'],
+                                                   (x, r_outer))
+
+        # -- check stopping condition
+        r_norm = nrm2(r_outer)
+        if r_norm <= max(atol, rtol * b_norm):
+            break
+
+        # -- inner LGMRES iteration
+        v0 = -psolve(r_outer)
+        inner_res_0 = nrm2(v0)
+
+        if inner_res_0 == 0:
+            rnorm = nrm2(r_outer)
+            raise RuntimeError("Preconditioner returned a zero vector; "
+                               f"|v| ~ {rnorm:.1g}, |M v| = 0")
+
+        v0 = scal(1.0/inner_res_0, v0)
+
+        ptol = min(ptol_max_factor, max(atol, rtol*b_norm)/r_norm)
+
+        try:
+            Q, R, B, vs, zs, y, pres = _fgmres(matvec,
+                                               v0,
+                                               inner_m,
+                                               lpsolve=psolve,
+                                               atol=ptol,
+                                               outer_v=outer_v,
+                                               prepend_outer_v=prepend_outer_v)
+            y *= inner_res_0
+            if not np.isfinite(y).all():
+                # Overflow etc. in computation. There's no way to
+                # recover from this, so we have to bail out.
+                raise LinAlgError()
+        except LinAlgError:
+            # Floating point over/underflow, non-finite result from
+            # matmul etc. -- report failure.
+            return postprocess(x), k_outer + 1
+
+        # Inner loop tolerance control
+        if pres > ptol:
+            ptol_max_factor = min(1.0, 1.5 * ptol_max_factor)
+        else:
+            ptol_max_factor = max(1e-16, 0.25 * ptol_max_factor)
+
+        # -- GMRES terminated: eval solution
+        dx = zs[0]*y[0]
+        for w, yc in zip(zs[1:], y[1:]):
+            dx = axpy(w, dx, dx.shape[0], yc)  # dx += w*yc
+
+        # -- Store LGMRES augmentation vectors
+        nx = nrm2(dx)
+        if nx > 0:
+            if store_outer_Av:
+                q = Q.dot(R.dot(y))
+                ax = vs[0]*q[0]
+                for v, qc in zip(vs[1:], q[1:]):
+                    ax = axpy(v, ax, ax.shape[0], qc)
+                outer_v.append((dx/nx, ax/nx))
+            else:
+                outer_v.append((dx/nx, None))
+
+        # -- Retain only a finite number of augmentation vectors
+        while len(outer_v) > outer_k:
+            del outer_v[0]
+
+        # -- Apply step
+        x += dx
+    else:
+        # didn't converge ...
+        return postprocess(x), maxiter
+
+    return postprocess(x), 0
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsmr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsmr.py
new file mode 100644
index 0000000000000000000000000000000000000000..97eb734aa64c3145044a81e97b0e1b8df9506ce2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsmr.py
@@ -0,0 +1,486 @@
+"""
+Copyright (C) 2010 David Fong and Michael Saunders
+
+LSMR uses an iterative method.
+
+07 Jun 2010: Documentation updated
+03 Jun 2010: First release version in Python
+
+David Chin-lung Fong            clfong@stanford.edu
+Institute for Computational and Mathematical Engineering
+Stanford University
+
+Michael Saunders                saunders@stanford.edu
+Systems Optimization Laboratory
+Dept of MS&E, Stanford University.
+
+"""
+
+__all__ = ['lsmr']
+
+from numpy import zeros, inf, atleast_1d, result_type
+from numpy.linalg import norm
+from math import sqrt
+from scipy.sparse.linalg._interface import aslinearoperator
+
+from scipy.sparse.linalg._isolve.lsqr import _sym_ortho
+
+
+def lsmr(A, b, damp=0.0, atol=1e-6, btol=1e-6, conlim=1e8,
+         maxiter=None, show=False, x0=None):
+    """Iterative solver for least-squares problems.
+
+    lsmr solves the system of linear equations ``Ax = b``. If the system
+    is inconsistent, it solves the least-squares problem ``min ||b - Ax||_2``.
+    ``A`` is a rectangular matrix of dimension m-by-n, where all cases are
+    allowed: m = n, m > n, or m < n. ``b`` is a vector of length m.
+    The matrix A may be dense or sparse (usually sparse).
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        Matrix A in the linear system.
+        Alternatively, ``A`` can be a linear operator which can
+        produce ``Ax`` and ``A^H x`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : array_like, shape (m,)
+        Vector ``b`` in the linear system.
+    damp : float
+        Damping factor for regularized least-squares. `lsmr` solves
+        the regularized least-squares problem::
+
+         min ||(b) - (  A   )x||
+             ||(0)   (damp*I) ||_2
+
+        where damp is a scalar.  If damp is None or 0, the system
+        is solved without regularization. Default is 0.
+    atol, btol : float, optional
+        Stopping tolerances. `lsmr` continues iterations until a
+        certain backward error estimate is smaller than some quantity
+        depending on atol and btol.  Let ``r = b - Ax`` be the
+        residual vector for the current approximate solution ``x``.
+        If ``Ax = b`` seems to be consistent, `lsmr` terminates
+        when ``norm(r) <= atol * norm(A) * norm(x) + btol * norm(b)``.
+        Otherwise, `lsmr` terminates when ``norm(A^H r) <=
+        atol * norm(A) * norm(r)``.  If both tolerances are 1.0e-6 (default),
+        the final ``norm(r)`` should be accurate to about 6
+        digits. (The final ``x`` will usually have fewer correct digits,
+        depending on ``cond(A)`` and the size of LAMBDA.)  If `atol`
+        or `btol` is None, a default value of 1.0e-6 will be used.
+        Ideally, they should be estimates of the relative error in the
+        entries of ``A`` and ``b`` respectively.  For example, if the entries
+        of ``A`` have 7 correct digits, set ``atol = 1e-7``. This prevents
+        the algorithm from doing unnecessary work beyond the
+        uncertainty of the input data.
+    conlim : float, optional
+        `lsmr` terminates if an estimate of ``cond(A)`` exceeds
+        `conlim`.  For compatible systems ``Ax = b``, conlim could be
+        as large as 1.0e+12 (say).  For least-squares problems,
+        `conlim` should be less than 1.0e+8. If `conlim` is None, the
+        default value is 1e+8.  Maximum precision can be obtained by
+        setting ``atol = btol = conlim = 0``, but the number of
+        iterations may then be excessive. Default is 1e8.
+    maxiter : int, optional
+        `lsmr` terminates if the number of iterations reaches
+        `maxiter`.  The default is ``maxiter = min(m, n)``.  For
+        ill-conditioned systems, a larger value of `maxiter` may be
+        needed. Default is False.
+    show : bool, optional
+        Print iterations logs if ``show=True``. Default is False.
+    x0 : array_like, shape (n,), optional
+        Initial guess of ``x``, if None zeros are used. Default is None.
+
+        .. versionadded:: 1.0.0
+
+    Returns
+    -------
+    x : ndarray of float
+        Least-square solution returned.
+    istop : int
+        istop gives the reason for stopping::
+
+          istop   = 0 means x=0 is a solution.  If x0 was given, then x=x0 is a
+                      solution.
+                  = 1 means x is an approximate solution to A@x = B,
+                      according to atol and btol.
+                  = 2 means x approximately solves the least-squares problem
+                      according to atol.
+                  = 3 means COND(A) seems to be greater than CONLIM.
+                  = 4 is the same as 1 with atol = btol = eps (machine
+                      precision)
+                  = 5 is the same as 2 with atol = eps.
+                  = 6 is the same as 3 with CONLIM = 1/eps.
+                  = 7 means ITN reached maxiter before the other stopping
+                      conditions were satisfied.
+
+    itn : int
+        Number of iterations used.
+    normr : float
+        ``norm(b-Ax)``
+    normar : float
+        ``norm(A^H (b - Ax))``
+    norma : float
+        ``norm(A)``
+    conda : float
+        Condition number of A.
+    normx : float
+        ``norm(x)``
+
+    Notes
+    -----
+
+    .. versionadded:: 0.11.0
+
+    References
+    ----------
+    .. [1] D. C.-L. Fong and M. A. Saunders,
+           "LSMR: An iterative algorithm for sparse least-squares problems",
+           SIAM J. Sci. Comput., vol. 33, pp. 2950-2971, 2011.
+           :arxiv:`1006.0758`
+    .. [2] LSMR Software, https://web.stanford.edu/group/SOL/software/lsmr/
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import lsmr
+    >>> A = csc_array([[1., 0.], [1., 1.], [0., 1.]], dtype=float)
+
+    The first example has the trivial solution ``[0, 0]``
+
+    >>> b = np.array([0., 0., 0.], dtype=float)
+    >>> x, istop, itn, normr = lsmr(A, b)[:4]
+    >>> istop
+    0
+    >>> x
+    array([0., 0.])
+
+    The stopping code ``istop=0`` returned indicates that a vector of zeros was
+    found as a solution. The returned solution `x` indeed contains
+    ``[0., 0.]``. The next example has a non-trivial solution:
+
+    >>> b = np.array([1., 0., -1.], dtype=float)
+    >>> x, istop, itn, normr = lsmr(A, b)[:4]
+    >>> istop
+    1
+    >>> x
+    array([ 1., -1.])
+    >>> itn
+    1
+    >>> normr
+    4.440892098500627e-16
+
+    As indicated by ``istop=1``, `lsmr` found a solution obeying the tolerance
+    limits. The given solution ``[1., -1.]`` obviously solves the equation. The
+    remaining return values include information about the number of iterations
+    (`itn=1`) and the remaining difference of left and right side of the solved
+    equation.
+    The final example demonstrates the behavior in the case where there is no
+    solution for the equation:
+
+    >>> b = np.array([1., 0.01, -1.], dtype=float)
+    >>> x, istop, itn, normr = lsmr(A, b)[:4]
+    >>> istop
+    2
+    >>> x
+    array([ 1.00333333, -0.99666667])
+    >>> A.dot(x)-b
+    array([ 0.00333333, -0.00333333,  0.00333333])
+    >>> normr
+    0.005773502691896255
+
+    `istop` indicates that the system is inconsistent and thus `x` is rather an
+    approximate solution to the corresponding least-squares problem. `normr`
+    contains the minimal distance that was found.
+    """
+
+    A = aslinearoperator(A)
+    b = atleast_1d(b)
+    if b.ndim > 1:
+        b = b.squeeze()
+
+    msg = ('The exact solution is x = 0, or x = x0, if x0 was given  ',
+           'Ax - b is small enough, given atol, btol                  ',
+           'The least-squares solution is good enough, given atol     ',
+           'The estimate of cond(Abar) has exceeded conlim            ',
+           'Ax - b is small enough for this machine                   ',
+           'The least-squares solution is good enough for this machine',
+           'Cond(Abar) seems to be too large for this machine         ',
+           'The iteration limit has been reached                      ')
+
+    hdg1 = '   itn      x(1)       norm r    norm Ar'
+    hdg2 = ' compatible   LS      norm A   cond A'
+    pfreq = 20   # print frequency (for repeating the heading)
+    pcount = 0   # print counter
+
+    m, n = A.shape
+
+    # stores the num of singular values
+    minDim = min([m, n])
+
+    if maxiter is None:
+        maxiter = minDim
+
+    if x0 is None:
+        dtype = result_type(A, b, float)
+    else:
+        dtype = result_type(A, b, x0, float)
+
+    if show:
+        print(' ')
+        print('LSMR            Least-squares solution of  Ax = b\n')
+        print(f'The matrix A has {m} rows and {n} columns')
+        print(f'damp = {damp:20.14e}\n')
+        print(f'atol = {atol:8.2e}                 conlim = {conlim:8.2e}\n')
+        print(f'btol = {btol:8.2e}             maxiter = {maxiter:8g}\n')
+
+    u = b
+    normb = norm(b)
+    if x0 is None:
+        x = zeros(n, dtype)
+        beta = normb.copy()
+    else:
+        x = atleast_1d(x0.copy())
+        u = u - A.matvec(x)
+        beta = norm(u)
+
+    if beta > 0:
+        u = (1 / beta) * u
+        v = A.rmatvec(u)
+        alpha = norm(v)
+    else:
+        v = zeros(n, dtype)
+        alpha = 0
+
+    if alpha > 0:
+        v = (1 / alpha) * v
+
+    # Initialize variables for 1st iteration.
+
+    itn = 0
+    zetabar = alpha * beta
+    alphabar = alpha
+    rho = 1
+    rhobar = 1
+    cbar = 1
+    sbar = 0
+
+    h = v.copy()
+    hbar = zeros(n, dtype)
+
+    # Initialize variables for estimation of ||r||.
+
+    betadd = beta
+    betad = 0
+    rhodold = 1
+    tautildeold = 0
+    thetatilde = 0
+    zeta = 0
+    d = 0
+
+    # Initialize variables for estimation of ||A|| and cond(A)
+
+    normA2 = alpha * alpha
+    maxrbar = 0
+    minrbar = 1e+100
+    normA = sqrt(normA2)
+    condA = 1
+    normx = 0
+
+    # Items for use in stopping rules, normb set earlier
+    istop = 0
+    ctol = 0
+    if conlim > 0:
+        ctol = 1 / conlim
+    normr = beta
+
+    # Reverse the order here from the original matlab code because
+    # there was an error on return when arnorm==0
+    normar = alpha * beta
+    if normar == 0:
+        if show:
+            print(msg[0])
+        return x, istop, itn, normr, normar, normA, condA, normx
+
+    if normb == 0:
+        x[()] = 0
+        return x, istop, itn, normr, normar, normA, condA, normx
+
+    if show:
+        print(' ')
+        print(hdg1, hdg2)
+        test1 = 1
+        test2 = alpha / beta
+        str1 = f'{itn:6g} {x[0]:12.5e}'
+        str2 = f' {normr:10.3e} {normar:10.3e}'
+        str3 = f'  {test1:8.1e} {test2:8.1e}'
+        print(''.join([str1, str2, str3]))
+
+    # Main iteration loop.
+    while itn < maxiter:
+        itn = itn + 1
+
+        # Perform the next step of the bidiagonalization to obtain the
+        # next  beta, u, alpha, v.  These satisfy the relations
+        #         beta*u  =  A@v   -  alpha*u,
+        #        alpha*v  =  A'@u  -  beta*v.
+
+        u *= -alpha
+        u += A.matvec(v)
+        beta = norm(u)
+
+        if beta > 0:
+            u *= (1 / beta)
+            v *= -beta
+            v += A.rmatvec(u)
+            alpha = norm(v)
+            if alpha > 0:
+                v *= (1 / alpha)
+
+        # At this point, beta = beta_{k+1}, alpha = alpha_{k+1}.
+
+        # Construct rotation Qhat_{k,2k+1}.
+
+        chat, shat, alphahat = _sym_ortho(alphabar, damp)
+
+        # Use a plane rotation (Q_i) to turn B_i to R_i
+
+        rhoold = rho
+        c, s, rho = _sym_ortho(alphahat, beta)
+        thetanew = s*alpha
+        alphabar = c*alpha
+
+        # Use a plane rotation (Qbar_i) to turn R_i^T to R_i^bar
+
+        rhobarold = rhobar
+        zetaold = zeta
+        thetabar = sbar * rho
+        rhotemp = cbar * rho
+        cbar, sbar, rhobar = _sym_ortho(cbar * rho, thetanew)
+        zeta = cbar * zetabar
+        zetabar = - sbar * zetabar
+
+        # Update h, h_hat, x.
+
+        hbar *= - (thetabar * rho / (rhoold * rhobarold))
+        hbar += h
+        x += (zeta / (rho * rhobar)) * hbar
+        h *= - (thetanew / rho)
+        h += v
+
+        # Estimate of ||r||.
+
+        # Apply rotation Qhat_{k,2k+1}.
+        betaacute = chat * betadd
+        betacheck = -shat * betadd
+
+        # Apply rotation Q_{k,k+1}.
+        betahat = c * betaacute
+        betadd = -s * betaacute
+
+        # Apply rotation Qtilde_{k-1}.
+        # betad = betad_{k-1} here.
+
+        thetatildeold = thetatilde
+        ctildeold, stildeold, rhotildeold = _sym_ortho(rhodold, thetabar)
+        thetatilde = stildeold * rhobar
+        rhodold = ctildeold * rhobar
+        betad = - stildeold * betad + ctildeold * betahat
+
+        # betad   = betad_k here.
+        # rhodold = rhod_k  here.
+
+        tautildeold = (zetaold - thetatildeold * tautildeold) / rhotildeold
+        taud = (zeta - thetatilde * tautildeold) / rhodold
+        d = d + betacheck * betacheck
+        normr = sqrt(d + (betad - taud)**2 + betadd * betadd)
+
+        # Estimate ||A||.
+        normA2 = normA2 + beta * beta
+        normA = sqrt(normA2)
+        normA2 = normA2 + alpha * alpha
+
+        # Estimate cond(A).
+        maxrbar = max(maxrbar, rhobarold)
+        if itn > 1:
+            minrbar = min(minrbar, rhobarold)
+        condA = max(maxrbar, rhotemp) / min(minrbar, rhotemp)
+
+        # Test for convergence.
+
+        # Compute norms for convergence testing.
+        normar = abs(zetabar)
+        normx = norm(x)
+
+        # Now use these norms to estimate certain other quantities,
+        # some of which will be small near a solution.
+
+        test1 = normr / normb
+        if (normA * normr) != 0:
+            test2 = normar / (normA * normr)
+        else:
+            test2 = inf
+        test3 = 1 / condA
+        t1 = test1 / (1 + normA * normx / normb)
+        rtol = btol + atol * normA * normx / normb
+
+        # The following tests guard against extremely small values of
+        # atol, btol or ctol.  (The user may have set any or all of
+        # the parameters atol, btol, conlim  to 0.)
+        # The effect is equivalent to the normAl tests using
+        # atol = eps,  btol = eps,  conlim = 1/eps.
+
+        if itn >= maxiter:
+            istop = 7
+        if 1 + test3 <= 1:
+            istop = 6
+        if 1 + test2 <= 1:
+            istop = 5
+        if 1 + t1 <= 1:
+            istop = 4
+
+        # Allow for tolerances set by the user.
+
+        if test3 <= ctol:
+            istop = 3
+        if test2 <= atol:
+            istop = 2
+        if test1 <= rtol:
+            istop = 1
+
+        # See if it is time to print something.
+
+        if show:
+            if (n <= 40) or (itn <= 10) or (itn >= maxiter - 10) or \
+               (itn % 10 == 0) or (test3 <= 1.1 * ctol) or \
+               (test2 <= 1.1 * atol) or (test1 <= 1.1 * rtol) or \
+               (istop != 0):
+
+                if pcount >= pfreq:
+                    pcount = 0
+                    print(' ')
+                    print(hdg1, hdg2)
+                pcount = pcount + 1
+                str1 = f'{itn:6g} {x[0]:12.5e}'
+                str2 = f' {normr:10.3e} {normar:10.3e}'
+                str3 = f'  {test1:8.1e} {test2:8.1e}'
+                str4 = f' {normA:8.1e} {condA:8.1e}'
+                print(''.join([str1, str2, str3, str4]))
+
+        if istop > 0:
+            break
+
+    # Print the stopping condition.
+
+    if show:
+        print(' ')
+        print('LSMR finished')
+        print(msg[istop])
+        print(f'istop ={istop:8g}    normr ={normr:8.1e}')
+        print(f'    normA ={normA:8.1e}    normAr ={normar:8.1e}')
+        print(f'itn   ={itn:8g}    condA ={condA:8.1e}')
+        print(f'    normx ={normx:8.1e}')
+        print(str1, str2)
+        print(str3, str4)
+
+    return x, istop, itn, normr, normar, normA, condA, normx
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsqr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsqr.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e490a0769e6d20303b1e5fdd111237b72d3abc9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/lsqr.py
@@ -0,0 +1,589 @@
+"""Sparse Equations and Least Squares.
+
+The original Fortran code was written by C. C. Paige and M. A. Saunders as
+described in
+
+C. C. Paige and M. A. Saunders, LSQR: An algorithm for sparse linear
+equations and sparse least squares, TOMS 8(1), 43--71 (1982).
+
+C. C. Paige and M. A. Saunders, Algorithm 583; LSQR: Sparse linear
+equations and least-squares problems, TOMS 8(2), 195--209 (1982).
+
+It is licensed under the following BSD license:
+
+Copyright (c) 2006, Systems Optimization Laboratory
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+    * Redistributions in binary form must reproduce the above
+      copyright notice, this list of conditions and the following
+      disclaimer in the documentation and/or other materials provided
+      with the distribution.
+
+    * Neither the name of Stanford University nor the names of its
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+The Fortran code was translated to Python for use in CVXOPT by Jeffery
+Kline with contributions by Mridul Aanjaneya and Bob Myhill.
+
+Adapted for SciPy by Stefan van der Walt.
+
+"""
+
+__all__ = ['lsqr']
+
+import numpy as np
+from math import sqrt
+from scipy.sparse.linalg._interface import aslinearoperator
+from scipy.sparse._sputils import convert_pydata_sparse_to_scipy
+
+eps = np.finfo(np.float64).eps
+
+
+def _sym_ortho(a, b):
+    """
+    Stable implementation of Givens rotation.
+
+    Notes
+    -----
+    The routine 'SymOrtho' was added for numerical stability. This is
+    recommended by S.-C. Choi in [1]_.  It removes the unpleasant potential of
+    ``1/eps`` in some important places (see, for example text following
+    "Compute the next plane rotation Qk" in minres.py).
+
+    References
+    ----------
+    .. [1] S.-C. Choi, "Iterative Methods for Singular Linear Equations
+           and Least-Squares Problems", Dissertation,
+           http://www.stanford.edu/group/SOL/dissertations/sou-cheng-choi-thesis.pdf
+
+    """
+    if b == 0:
+        return np.sign(a), 0, abs(a)
+    elif a == 0:
+        return 0, np.sign(b), abs(b)
+    elif abs(b) > abs(a):
+        tau = a / b
+        s = np.sign(b) / sqrt(1 + tau * tau)
+        c = s * tau
+        r = b / s
+    else:
+        tau = b / a
+        c = np.sign(a) / sqrt(1+tau*tau)
+        s = c * tau
+        r = a / c
+    return c, s, r
+
+
+def lsqr(A, b, damp=0.0, atol=1e-6, btol=1e-6, conlim=1e8,
+         iter_lim=None, show=False, calc_var=False, x0=None):
+    """Find the least-squares solution to a large, sparse, linear system
+    of equations.
+
+    The function solves ``Ax = b``  or  ``min ||Ax - b||^2`` or
+    ``min ||Ax - b||^2 + d^2 ||x - x0||^2``.
+
+    The matrix A may be square or rectangular (over-determined or
+    under-determined), and may have any rank.
+
+    ::
+
+      1. Unsymmetric equations --    solve  Ax = b
+
+      2. Linear least squares  --    solve  Ax = b
+                                     in the least-squares sense
+
+      3. Damped least squares  --    solve  (   A    )*x = (    b    )
+                                            ( damp*I )     ( damp*x0 )
+                                     in the least-squares sense
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        Representation of an m-by-n matrix.
+        Alternatively, ``A`` can be a linear operator which can
+        produce ``Ax`` and ``A^T x`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : array_like, shape (m,)
+        Right-hand side vector ``b``.
+    damp : float
+        Damping coefficient. Default is 0.
+    atol, btol : float, optional
+        Stopping tolerances. `lsqr` continues iterations until a
+        certain backward error estimate is smaller than some quantity
+        depending on atol and btol.  Let ``r = b - Ax`` be the
+        residual vector for the current approximate solution ``x``.
+        If ``Ax = b`` seems to be consistent, `lsqr` terminates
+        when ``norm(r) <= atol * norm(A) * norm(x) + btol * norm(b)``.
+        Otherwise, `lsqr` terminates when ``norm(A^H r) <=
+        atol * norm(A) * norm(r)``.  If both tolerances are 1.0e-6 (default),
+        the final ``norm(r)`` should be accurate to about 6
+        digits. (The final ``x`` will usually have fewer correct digits,
+        depending on ``cond(A)`` and the size of LAMBDA.)  If `atol`
+        or `btol` is None, a default value of 1.0e-6 will be used.
+        Ideally, they should be estimates of the relative error in the
+        entries of ``A`` and ``b`` respectively.  For example, if the entries
+        of ``A`` have 7 correct digits, set ``atol = 1e-7``. This prevents
+        the algorithm from doing unnecessary work beyond the
+        uncertainty of the input data.
+    conlim : float, optional
+        Another stopping tolerance.  lsqr terminates if an estimate of
+        ``cond(A)`` exceeds `conlim`.  For compatible systems ``Ax =
+        b``, `conlim` could be as large as 1.0e+12 (say).  For
+        least-squares problems, conlim should be less than 1.0e+8.
+        Maximum precision can be obtained by setting ``atol = btol =
+        conlim = zero``, but the number of iterations may then be
+        excessive. Default is 1e8.
+    iter_lim : int, optional
+        Explicit limitation on number of iterations (for safety).
+    show : bool, optional
+        Display an iteration log. Default is False.
+    calc_var : bool, optional
+        Whether to estimate diagonals of ``(A'A + damp^2*I)^{-1}``.
+    x0 : array_like, shape (n,), optional
+        Initial guess of x, if None zeros are used. Default is None.
+
+        .. versionadded:: 1.0.0
+
+    Returns
+    -------
+    x : ndarray of float
+        The final solution.
+    istop : int
+        Gives the reason for termination.
+        1 means x is an approximate solution to Ax = b.
+        2 means x approximately solves the least-squares problem.
+    itn : int
+        Iteration number upon termination.
+    r1norm : float
+        ``norm(r)``, where ``r = b - Ax``.
+    r2norm : float
+        ``sqrt( norm(r)^2  +  damp^2 * norm(x - x0)^2 )``.  Equal to `r1norm`
+        if ``damp == 0``.
+    anorm : float
+        Estimate of Frobenius norm of ``Abar = [[A]; [damp*I]]``.
+    acond : float
+        Estimate of ``cond(Abar)``.
+    arnorm : float
+        Estimate of ``norm(A'@r - damp^2*(x - x0))``.
+    xnorm : float
+        ``norm(x)``
+    var : ndarray of float
+        If ``calc_var`` is True, estimates all diagonals of
+        ``(A'A)^{-1}`` (if ``damp == 0``) or more generally ``(A'A +
+        damp^2*I)^{-1}``.  This is well defined if A has full column
+        rank or ``damp > 0``.  (Not sure what var means if ``rank(A)
+        < n`` and ``damp = 0.``)
+
+    Notes
+    -----
+    LSQR uses an iterative method to approximate the solution.  The
+    number of iterations required to reach a certain accuracy depends
+    strongly on the scaling of the problem.  Poor scaling of the rows
+    or columns of A should therefore be avoided where possible.
+
+    For example, in problem 1 the solution is unaltered by
+    row-scaling.  If a row of A is very small or large compared to
+    the other rows of A, the corresponding row of ( A  b ) should be
+    scaled up or down.
+
+    In problems 1 and 2, the solution x is easily recovered
+    following column-scaling.  Unless better information is known,
+    the nonzero columns of A should be scaled so that they all have
+    the same Euclidean norm (e.g., 1.0).
+
+    In problem 3, there is no freedom to re-scale if damp is
+    nonzero.  However, the value of damp should be assigned only
+    after attention has been paid to the scaling of A.
+
+    The parameter damp is intended to help regularize
+    ill-conditioned systems, by preventing the true solution from
+    being very large.  Another aid to regularization is provided by
+    the parameter acond, which may be used to terminate iterations
+    before the computed solution becomes very large.
+
+    If some initial estimate ``x0`` is known and if ``damp == 0``,
+    one could proceed as follows:
+
+      1. Compute a residual vector ``r0 = b - A@x0``.
+      2. Use LSQR to solve the system  ``A@dx = r0``.
+      3. Add the correction dx to obtain a final solution ``x = x0 + dx``.
+
+    This requires that ``x0`` be available before and after the call
+    to LSQR.  To judge the benefits, suppose LSQR takes k1 iterations
+    to solve A@x = b and k2 iterations to solve A@dx = r0.
+    If x0 is "good", norm(r0) will be smaller than norm(b).
+    If the same stopping tolerances atol and btol are used for each
+    system, k1 and k2 will be similar, but the final solution x0 + dx
+    should be more accurate.  The only way to reduce the total work
+    is to use a larger stopping tolerance for the second system.
+    If some value btol is suitable for A@x = b, the larger value
+    btol*norm(b)/norm(r0)  should be suitable for A@dx = r0.
+
+    Preconditioning is another way to reduce the number of iterations.
+    If it is possible to solve a related system ``M@x = b``
+    efficiently, where M approximates A in some helpful way (e.g. M -
+    A has low rank or its elements are small relative to those of A),
+    LSQR may converge more rapidly on the system ``A@M(inverse)@z =
+    b``, after which x can be recovered by solving M@x = z.
+
+    If A is symmetric, LSQR should not be used!
+
+    Alternatives are the symmetric conjugate-gradient method (cg)
+    and/or SYMMLQ.  SYMMLQ is an implementation of symmetric cg that
+    applies to any symmetric A and will converge more rapidly than
+    LSQR.  If A is positive definite, there are other implementations
+    of symmetric cg that require slightly less work per iteration than
+    SYMMLQ (but will take the same number of iterations).
+
+    References
+    ----------
+    .. [1] C. C. Paige and M. A. Saunders (1982a).
+           "LSQR: An algorithm for sparse linear equations and
+           sparse least squares", ACM TOMS 8(1), 43-71.
+    .. [2] C. C. Paige and M. A. Saunders (1982b).
+           "Algorithm 583.  LSQR: Sparse linear equations and least
+           squares problems", ACM TOMS 8(2), 195-209.
+    .. [3] M. A. Saunders (1995).  "Solution of sparse rectangular
+           systems using LSQR and CRAIG", BIT 35, 588-604.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import lsqr
+    >>> A = csc_array([[1., 0.], [1., 1.], [0., 1.]], dtype=float)
+
+    The first example has the trivial solution ``[0, 0]``
+
+    >>> b = np.array([0., 0., 0.], dtype=float)
+    >>> x, istop, itn, normr = lsqr(A, b)[:4]
+    >>> istop
+    0
+    >>> x
+    array([ 0.,  0.])
+
+    The stopping code ``istop=0`` returned indicates that a vector of zeros was
+    found as a solution. The returned solution `x` indeed contains
+    ``[0., 0.]``. The next example has a non-trivial solution:
+
+    >>> b = np.array([1., 0., -1.], dtype=float)
+    >>> x, istop, itn, r1norm = lsqr(A, b)[:4]
+    >>> istop
+    1
+    >>> x
+    array([ 1., -1.])
+    >>> itn
+    1
+    >>> r1norm
+    4.440892098500627e-16
+
+    As indicated by ``istop=1``, `lsqr` found a solution obeying the tolerance
+    limits. The given solution ``[1., -1.]`` obviously solves the equation. The
+    remaining return values include information about the number of iterations
+    (`itn=1`) and the remaining difference of left and right side of the solved
+    equation.
+    The final example demonstrates the behavior in the case where there is no
+    solution for the equation:
+
+    >>> b = np.array([1., 0.01, -1.], dtype=float)
+    >>> x, istop, itn, r1norm = lsqr(A, b)[:4]
+    >>> istop
+    2
+    >>> x
+    array([ 1.00333333, -0.99666667])
+    >>> A.dot(x)-b
+    array([ 0.00333333, -0.00333333,  0.00333333])
+    >>> r1norm
+    0.005773502691896255
+
+    `istop` indicates that the system is inconsistent and thus `x` is rather an
+    approximate solution to the corresponding least-squares problem. `r1norm`
+    contains the norm of the minimal residual that was found.
+    """
+    A = convert_pydata_sparse_to_scipy(A)
+    A = aslinearoperator(A)
+    b = np.atleast_1d(b)
+    if b.ndim > 1:
+        b = b.squeeze()
+
+    m, n = A.shape
+    if iter_lim is None:
+        iter_lim = 2 * n
+    var = np.zeros(n)
+
+    msg = ('The exact solution is  x = 0                              ',
+           'Ax - b is small enough, given atol, btol                  ',
+           'The least-squares solution is good enough, given atol     ',
+           'The estimate of cond(Abar) has exceeded conlim            ',
+           'Ax - b is small enough for this machine                   ',
+           'The least-squares solution is good enough for this machine',
+           'Cond(Abar) seems to be too large for this machine         ',
+           'The iteration limit has been reached                      ')
+
+    if show:
+        print(' ')
+        print('LSQR            Least-squares solution of  Ax = b')
+        str1 = f'The matrix A has {m} rows and {n} columns'
+        str2 = f'damp = {damp:20.14e}   calc_var = {calc_var:8g}'
+        str3 = f'atol = {atol:8.2e}                 conlim = {conlim:8.2e}'
+        str4 = f'btol = {btol:8.2e}               iter_lim = {iter_lim:8g}'
+        print(str1)
+        print(str2)
+        print(str3)
+        print(str4)
+
+    itn = 0
+    istop = 0
+    ctol = 0
+    if conlim > 0:
+        ctol = 1/conlim
+    anorm = 0
+    acond = 0
+    dampsq = damp**2
+    ddnorm = 0
+    res2 = 0
+    xnorm = 0
+    xxnorm = 0
+    z = 0
+    cs2 = -1
+    sn2 = 0
+
+    # Set up the first vectors u and v for the bidiagonalization.
+    # These satisfy  beta*u = b - A@x,  alfa*v = A'@u.
+    u = b
+    bnorm = np.linalg.norm(b)
+
+    if x0 is None:
+        x = np.zeros(n)
+        beta = bnorm.copy()
+    else:
+        x = np.asarray(x0)
+        u = u - A.matvec(x)
+        beta = np.linalg.norm(u)
+
+    if beta > 0:
+        u = (1/beta) * u
+        v = A.rmatvec(u)
+        alfa = np.linalg.norm(v)
+    else:
+        v = x.copy()
+        alfa = 0
+
+    if alfa > 0:
+        v = (1/alfa) * v
+    w = v.copy()
+
+    rhobar = alfa
+    phibar = beta
+    rnorm = beta
+    r1norm = rnorm
+    r2norm = rnorm
+
+    # Reverse the order here from the original matlab code because
+    # there was an error on return when arnorm==0
+    arnorm = alfa * beta
+    if arnorm == 0:
+        if show:
+            print(msg[0])
+        return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var
+
+    head1 = '   Itn      x[0]       r1norm     r2norm '
+    head2 = ' Compatible    LS      Norm A   Cond A'
+
+    if show:
+        print(' ')
+        print(head1, head2)
+        test1 = 1
+        test2 = alfa / beta
+        str1 = f'{itn:6g} {x[0]:12.5e}'
+        str2 = f' {r1norm:10.3e} {r2norm:10.3e}'
+        str3 = f'  {test1:8.1e} {test2:8.1e}'
+        print(str1, str2, str3)
+
+    # Main iteration loop.
+    while itn < iter_lim:
+        itn = itn + 1
+        # Perform the next step of the bidiagonalization to obtain the
+        # next  beta, u, alfa, v. These satisfy the relations
+        #     beta*u  =  a@v   -  alfa*u,
+        #     alfa*v  =  A'@u  -  beta*v.
+        u = A.matvec(v) - alfa * u
+        beta = np.linalg.norm(u)
+
+        if beta > 0:
+            u = (1/beta) * u
+            anorm = sqrt(anorm**2 + alfa**2 + beta**2 + dampsq)
+            v = A.rmatvec(u) - beta * v
+            alfa = np.linalg.norm(v)
+            if alfa > 0:
+                v = (1 / alfa) * v
+
+        # Use a plane rotation to eliminate the damping parameter.
+        # This alters the diagonal (rhobar) of the lower-bidiagonal matrix.
+        if damp > 0:
+            rhobar1 = sqrt(rhobar**2 + dampsq)
+            cs1 = rhobar / rhobar1
+            sn1 = damp / rhobar1
+            psi = sn1 * phibar
+            phibar = cs1 * phibar
+        else:
+            # cs1 = 1 and sn1 = 0
+            rhobar1 = rhobar
+            psi = 0.
+
+        # Use a plane rotation to eliminate the subdiagonal element (beta)
+        # of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix.
+        cs, sn, rho = _sym_ortho(rhobar1, beta)
+
+        theta = sn * alfa
+        rhobar = -cs * alfa
+        phi = cs * phibar
+        phibar = sn * phibar
+        tau = sn * phi
+
+        # Update x and w.
+        t1 = phi / rho
+        t2 = -theta / rho
+        dk = (1 / rho) * w
+
+        x = x + t1 * w
+        w = v + t2 * w
+        ddnorm = ddnorm + np.linalg.norm(dk)**2
+
+        if calc_var:
+            var = var + dk**2
+
+        # Use a plane rotation on the right to eliminate the
+        # super-diagonal element (theta) of the upper-bidiagonal matrix.
+        # Then use the result to estimate norm(x).
+        delta = sn2 * rho
+        gambar = -cs2 * rho
+        rhs = phi - delta * z
+        zbar = rhs / gambar
+        xnorm = sqrt(xxnorm + zbar**2)
+        gamma = sqrt(gambar**2 + theta**2)
+        cs2 = gambar / gamma
+        sn2 = theta / gamma
+        z = rhs / gamma
+        xxnorm = xxnorm + z**2
+
+        # Test for convergence.
+        # First, estimate the condition of the matrix  Abar,
+        # and the norms of  rbar  and  Abar'rbar.
+        acond = anorm * sqrt(ddnorm)
+        res1 = phibar**2
+        res2 = res2 + psi**2
+        rnorm = sqrt(res1 + res2)
+        arnorm = alfa * abs(tau)
+
+        # Distinguish between
+        #    r1norm = ||b - Ax|| and
+        #    r2norm = rnorm in current code
+        #           = sqrt(r1norm^2 + damp^2*||x - x0||^2).
+        #    Estimate r1norm from
+        #    r1norm = sqrt(r2norm^2 - damp^2*||x - x0||^2).
+        # Although there is cancellation, it might be accurate enough.
+        if damp > 0:
+            r1sq = rnorm**2 - dampsq * xxnorm
+            r1norm = sqrt(abs(r1sq))
+            if r1sq < 0:
+                r1norm = -r1norm
+        else:
+            r1norm = rnorm
+        r2norm = rnorm
+
+        # Now use these norms to estimate certain other quantities,
+        # some of which will be small near a solution.
+        test1 = rnorm / bnorm
+        test2 = arnorm / (anorm * rnorm + eps)
+        test3 = 1 / (acond + eps)
+        t1 = test1 / (1 + anorm * xnorm / bnorm)
+        rtol = btol + atol * anorm * xnorm / bnorm
+
+        # The following tests guard against extremely small values of
+        # atol, btol  or  ctol.  (The user may have set any or all of
+        # the parameters  atol, btol, conlim  to 0.)
+        # The effect is equivalent to the normal tests using
+        # atol = eps,  btol = eps,  conlim = 1/eps.
+        if itn >= iter_lim:
+            istop = 7
+        if 1 + test3 <= 1:
+            istop = 6
+        if 1 + test2 <= 1:
+            istop = 5
+        if 1 + t1 <= 1:
+            istop = 4
+
+        # Allow for tolerances set by the user.
+        if test3 <= ctol:
+            istop = 3
+        if test2 <= atol:
+            istop = 2
+        if test1 <= rtol:
+            istop = 1
+
+        if show:
+            # See if it is time to print something.
+            prnt = False
+            if n <= 40:
+                prnt = True
+            if itn <= 10:
+                prnt = True
+            if itn >= iter_lim-10:
+                prnt = True
+            # if itn%10 == 0: prnt = True
+            if test3 <= 2*ctol:
+                prnt = True
+            if test2 <= 10*atol:
+                prnt = True
+            if test1 <= 10*rtol:
+                prnt = True
+            if istop != 0:
+                prnt = True
+
+            if prnt:
+                str1 = f'{itn:6g} {x[0]:12.5e}'
+                str2 = f' {r1norm:10.3e} {r2norm:10.3e}'
+                str3 = f'  {test1:8.1e} {test2:8.1e}'
+                str4 = f' {anorm:8.1e} {acond:8.1e}'
+                print(str1, str2, str3, str4)
+
+        if istop != 0:
+            break
+
+    # End of iteration loop.
+    # Print the stopping condition.
+    if show:
+        print(' ')
+        print('LSQR finished')
+        print(msg[istop])
+        print(' ')
+        str1 = f'istop ={istop:8g}   r1norm ={r1norm:8.1e}'
+        str2 = f'anorm ={anorm:8.1e}   arnorm ={arnorm:8.1e}'
+        str3 = f'itn   ={itn:8g}   r2norm ={r2norm:8.1e}'
+        str4 = f'acond ={acond:8.1e}   xnorm  ={xnorm:8.1e}'
+        print(str1 + '   ' + str2)
+        print(str3 + '   ' + str4)
+        print(' ')
+
+    return x, istop, itn, r1norm, r2norm, anorm, acond, arnorm, xnorm, var
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/minres.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/minres.py
new file mode 100644
index 0000000000000000000000000000000000000000..719d4eed991f15dda61da2c01f28d7f2244fc97d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/minres.py
@@ -0,0 +1,372 @@
+from numpy import inner, zeros, inf, finfo
+from numpy.linalg import norm
+from math import sqrt
+
+from .utils import make_system
+
+__all__ = ['minres']
+
+
+def minres(A, b, x0=None, *, rtol=1e-5, shift=0.0, maxiter=None,
+           M=None, callback=None, show=False, check=False):
+    """
+    Use MINimum RESidual iteration to solve Ax=b
+
+    MINRES minimizes norm(Ax - b) for a real symmetric matrix A.  Unlike
+    the Conjugate Gradient method, A can be indefinite or singular.
+
+    If shift != 0 then the method solves (A - shift*I)x = b
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real symmetric N-by-N matrix of the linear system
+        Alternatively, ``A`` can be a linear operator which can
+        produce ``Ax`` using, e.g.,
+        ``scipy.sparse.linalg.LinearOperator``.
+    b : ndarray
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+
+    Returns
+    -------
+    x : ndarray
+        The converged solution.
+    info : integer
+        Provides convergence information:
+            0  : successful exit
+            >0 : convergence to tolerance not achieved, number of iterations
+            <0 : illegal input or breakdown
+
+    Other Parameters
+    ----------------
+    x0 : ndarray
+        Starting guess for the solution.
+    shift : float
+        Value to apply to the system ``(A - shift * I)x = b``. Default is 0.
+    rtol : float
+        Tolerance to achieve. The algorithm terminates when the relative
+        residual is below ``rtol``.
+    maxiter : integer
+        Maximum number of iterations.  Iteration will stop after maxiter
+        steps even if the specified tolerance has not been achieved.
+    M : {sparse array, ndarray, LinearOperator}
+        Preconditioner for A.  The preconditioner should approximate the
+        inverse of A.  Effective preconditioning dramatically improves the
+        rate of convergence, which implies that fewer iterations are needed
+        to reach a given error tolerance.
+    callback : function
+        User-supplied function to call after each iteration.  It is called
+        as callback(xk), where xk is the current solution vector.
+    show : bool
+        If ``True``, print out a summary and metrics related to the solution
+        during iterations. Default is ``False``.
+    check : bool
+        If ``True``, run additional input validation to check that `A` and
+        `M` (if specified) are symmetric. Default is ``False``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import minres
+    >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
+    >>> A = A + A.T
+    >>> b = np.array([2, 4, -1], dtype=float)
+    >>> x, exitCode = minres(A, b)
+    >>> print(exitCode)            # 0 indicates successful convergence
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+
+    References
+    ----------
+    Solution of sparse indefinite systems of linear equations,
+        C. C. Paige and M. A. Saunders (1975),
+        SIAM J. Numer. Anal. 12(4), pp. 617-629.
+        https://web.stanford.edu/group/SOL/software/minres/
+
+    This file is a translation of the following MATLAB implementation:
+        https://web.stanford.edu/group/SOL/software/minres/minres-matlab.zip
+
+    """
+    A, M, x, b, postprocess = make_system(A, M, x0, b)
+
+    matvec = A.matvec
+    psolve = M.matvec
+
+    first = 'Enter minres.   '
+    last = 'Exit  minres.   '
+
+    n = A.shape[0]
+
+    if maxiter is None:
+        maxiter = 5 * n
+
+    msg = [' beta2 = 0.  If M = I, b and x are eigenvectors    ',   # -1
+            ' beta1 = 0.  The exact solution is x0          ',   # 0
+            ' A solution to Ax = b was found, given rtol        ',   # 1
+            ' A least-squares solution was found, given rtol    ',   # 2
+            ' Reasonable accuracy achieved, given eps           ',   # 3
+            ' x has converged to an eigenvector                 ',   # 4
+            ' acond has exceeded 0.1/eps                        ',   # 5
+            ' The iteration limit was reached                   ',   # 6
+            ' A  does not define a symmetric matrix             ',   # 7
+            ' M  does not define a symmetric matrix             ',   # 8
+            ' M  does not define a pos-def preconditioner       ']   # 9
+
+    if show:
+        print(first + 'Solution of symmetric Ax = b')
+        print(first + f'n      =  {n:3g}     shift  =  {shift:23.14e}')
+        print(first + f'itnlim =  {maxiter:3g}     rtol   =  {rtol:11.2e}')
+        print()
+
+    istop = 0
+    itn = 0
+    Anorm = 0
+    Acond = 0
+    rnorm = 0
+    ynorm = 0
+
+    xtype = x.dtype
+
+    eps = finfo(xtype).eps
+
+    # Set up y and v for the first Lanczos vector v1.
+    # y  =  beta1 P' v1,  where  P = C**(-1).
+    # v is really P' v1.
+
+    if x0 is None:
+        r1 = b.copy()
+    else:
+        r1 = b - A@x
+    y = psolve(r1)
+
+    beta1 = inner(r1, y)
+
+    if beta1 < 0:
+        raise ValueError('indefinite preconditioner')
+    elif beta1 == 0:
+        return (postprocess(x), 0)
+
+    bnorm = norm(b)
+    if bnorm == 0:
+        x = b
+        return (postprocess(x), 0)
+
+    beta1 = sqrt(beta1)
+
+    if check:
+        # are these too strict?
+
+        # see if A is symmetric
+        w = matvec(y)
+        r2 = matvec(w)
+        s = inner(w,w)
+        t = inner(y,r2)
+        z = abs(s - t)
+        epsa = (s + eps) * eps**(1.0/3.0)
+        if z > epsa:
+            raise ValueError('non-symmetric matrix')
+
+        # see if M is symmetric
+        r2 = psolve(y)
+        s = inner(y,y)
+        t = inner(r1,r2)
+        z = abs(s - t)
+        epsa = (s + eps) * eps**(1.0/3.0)
+        if z > epsa:
+            raise ValueError('non-symmetric preconditioner')
+
+    # Initialize other quantities
+    oldb = 0
+    beta = beta1
+    dbar = 0
+    epsln = 0
+    qrnorm = beta1
+    phibar = beta1
+    rhs1 = beta1
+    rhs2 = 0
+    tnorm2 = 0
+    gmax = 0
+    gmin = finfo(xtype).max
+    cs = -1
+    sn = 0
+    w = zeros(n, dtype=xtype)
+    w2 = zeros(n, dtype=xtype)
+    r2 = r1
+
+    if show:
+        print()
+        print()
+        print('   Itn     x(1)     Compatible    LS       norm(A)  cond(A) gbar/|A|')
+
+    while itn < maxiter:
+        itn += 1
+
+        s = 1.0/beta
+        v = s*y
+
+        y = matvec(v)
+        y = y - shift * v
+
+        if itn >= 2:
+            y = y - (beta/oldb)*r1
+
+        alfa = inner(v,y)
+        y = y - (alfa/beta)*r2
+        r1 = r2
+        r2 = y
+        y = psolve(r2)
+        oldb = beta
+        beta = inner(r2,y)
+        if beta < 0:
+            raise ValueError('non-symmetric matrix')
+        beta = sqrt(beta)
+        tnorm2 += alfa**2 + oldb**2 + beta**2
+
+        if itn == 1:
+            if beta/beta1 <= 10*eps:
+                istop = -1  # Terminate later
+
+        # Apply previous rotation Qk-1 to get
+        #   [deltak epslnk+1] = [cs  sn][dbark    0   ]
+        #   [gbar k dbar k+1]   [sn -cs][alfak betak+1].
+
+        oldeps = epsln
+        delta = cs * dbar + sn * alfa   # delta1 = 0         deltak
+        gbar = sn * dbar - cs * alfa   # gbar 1 = alfa1     gbar k
+        epsln = sn * beta     # epsln2 = 0         epslnk+1
+        dbar = - cs * beta   # dbar 2 = beta2     dbar k+1
+        root = norm([gbar, dbar])
+        Arnorm = phibar * root
+
+        # Compute the next plane rotation Qk
+
+        gamma = norm([gbar, beta])       # gammak
+        gamma = max(gamma, eps)
+        cs = gbar / gamma             # ck
+        sn = beta / gamma             # sk
+        phi = cs * phibar              # phik
+        phibar = sn * phibar              # phibark+1
+
+        # Update  x.
+
+        denom = 1.0/gamma
+        w1 = w2
+        w2 = w
+        w = (v - oldeps*w1 - delta*w2) * denom
+        x = x + phi*w
+
+        # Go round again.
+
+        gmax = max(gmax, gamma)
+        gmin = min(gmin, gamma)
+        z = rhs1 / gamma
+        rhs1 = rhs2 - delta*z
+        rhs2 = - epsln*z
+
+        # Estimate various norms and test for convergence.
+
+        Anorm = sqrt(tnorm2)
+        ynorm = norm(x)
+        epsa = Anorm * eps
+        epsx = Anorm * ynorm * eps
+        epsr = Anorm * ynorm * rtol
+        diag = gbar
+
+        if diag == 0:
+            diag = epsa
+
+        qrnorm = phibar
+        rnorm = qrnorm
+        if ynorm == 0 or Anorm == 0:
+            test1 = inf
+        else:
+            test1 = rnorm / (Anorm*ynorm)    # ||r||  / (||A|| ||x||)
+        if Anorm == 0:
+            test2 = inf
+        else:
+            test2 = root / Anorm            # ||Ar|| / (||A|| ||r||)
+
+        # Estimate  cond(A).
+        # In this version we look at the diagonals of  R  in the
+        # factorization of the lower Hessenberg matrix,  Q @ H = R,
+        # where H is the tridiagonal matrix from Lanczos with one
+        # extra row, beta(k+1) e_k^T.
+
+        Acond = gmax/gmin
+
+        # See if any of the stopping criteria are satisfied.
+        # In rare cases, istop is already -1 from above (Abar = const*I).
+
+        if istop == 0:
+            t1 = 1 + test1      # These tests work if rtol < eps
+            t2 = 1 + test2
+            if t2 <= 1:
+                istop = 2
+            if t1 <= 1:
+                istop = 1
+
+            if itn >= maxiter:
+                istop = 6
+            if Acond >= 0.1/eps:
+                istop = 4
+            if epsx >= beta1:
+                istop = 3
+            # if rnorm <= epsx   : istop = 2
+            # if rnorm <= epsr   : istop = 1
+            if test2 <= rtol:
+                istop = 2
+            if test1 <= rtol:
+                istop = 1
+
+        # See if it is time to print something.
+
+        prnt = False
+        if n <= 40:
+            prnt = True
+        if itn <= 10:
+            prnt = True
+        if itn >= maxiter-10:
+            prnt = True
+        if itn % 10 == 0:
+            prnt = True
+        if qrnorm <= 10*epsx:
+            prnt = True
+        if qrnorm <= 10*epsr:
+            prnt = True
+        if Acond <= 1e-2/eps:
+            prnt = True
+        if istop != 0:
+            prnt = True
+
+        if show and prnt:
+            str1 = f'{itn:6g} {x[0]:12.5e} {test1:10.3e}'
+            str2 = f' {test2:10.3e}'
+            str3 = f' {Anorm:8.1e} {Acond:8.1e} {gbar/Anorm:8.1e}'
+
+            print(str1 + str2 + str3)
+
+            if itn % 10 == 0:
+                print()
+
+        if callback is not None:
+            callback(x)
+
+        if istop != 0:
+            break  # TODO check this
+
+    if show:
+        print()
+        print(last + f' istop   =  {istop:3g}               itn   ={itn:5g}')
+        print(last + f' Anorm   =  {Anorm:12.4e}      Acond =  {Acond:12.4e}')
+        print(last + f' rnorm   =  {rnorm:12.4e}      ynorm =  {ynorm:12.4e}')
+        print(last + f' Arnorm  =  {Arnorm:12.4e}')
+        print(last + msg[istop+1])
+
+    if istop == 6:
+        info = maxiter
+    else:
+        info = 0
+
+    return (postprocess(x),info)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py
new file mode 100644
index 0000000000000000000000000000000000000000..6523f0b344e86bdcb1e520a61cbaed0a28e77e70
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_gcrotmk.py
@@ -0,0 +1,183 @@
+#!/usr/bin/env python
+"""Tests for the linalg._isolve.gcrotmk module
+"""
+
+import threading
+from numpy.testing import (assert_, assert_allclose, assert_equal,
+                           suppress_warnings)
+
+import numpy as np
+from numpy import zeros, array, allclose
+from scipy.linalg import norm
+from scipy.sparse import csr_array, eye_array, random_array
+
+from scipy.sparse.linalg._interface import LinearOperator
+from scipy.sparse.linalg import splu
+from scipy.sparse.linalg._isolve import gcrotmk, gmres
+
+
+Am = csr_array(array([[-2,1,0,0,0,9],
+                       [1,-2,1,0,5,0],
+                       [0,1,-2,1,0,0],
+                       [0,0,1,-2,1,0],
+                       [0,3,0,1,-2,1],
+                       [1,0,0,0,1,-2]]))
+b = array([1,2,3,4,5,6])
+count = threading.local()  # [0]
+niter = threading.local()  # [0]
+
+
+def matvec(v):
+    if not hasattr(count, 'c'):
+        count.c = [0]
+    count.c[0] += 1
+    return Am@v
+
+
+def cb(v):
+    if not hasattr(niter, 'n'):
+        niter.n = [0]
+    niter.n[0] += 1
+
+
+A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype)
+
+
+def do_solve(**kw):
+    if not hasattr(niter, 'n'):
+        niter.n = [0]
+
+    if not hasattr(count, 'c'):
+        count.c = [0]
+
+    count.c[0] = 0
+    with suppress_warnings() as sup:
+        sup.filter(DeprecationWarning, ".*called without specifying.*")
+        x0, flag = gcrotmk(A, b, x0=zeros(A.shape[0]), rtol=1e-14, **kw)
+    count_0 = count.c[0]
+    assert_(allclose(A@x0, b, rtol=1e-12, atol=1e-12), norm(A@x0-b))
+    return x0, count_0
+
+
+class TestGCROTMK:
+    def test_preconditioner(self):
+        # Check that preconditioning works
+        pc = splu(Am.tocsc())
+        M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype)
+
+        x0, count_0 = do_solve()
+        niter.n[0] = 0
+        x1, count_1 = do_solve(M=M, callback=cb)
+
+        assert_equal(count_1, 3)
+        assert count_1 < count_0/2
+        assert allclose(x1, x0, rtol=1e-14)
+        assert niter.n[0] < 3
+
+    def test_arnoldi(self):
+        rng = np.random.default_rng(1)
+
+        A = eye_array(2000) + random_array((2000, 2000), density=5e-4, rng=rng)
+        b = rng.random(2000)
+
+        # The inner arnoldi should be equivalent to gmres
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, ".*called without specifying.*")
+            x0, flag0 = gcrotmk(A, b, x0=zeros(A.shape[0]), m=10, k=0, maxiter=1)
+            x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=10, maxiter=1)
+
+        assert_equal(flag0, 1)
+        assert_equal(flag1, 1)
+        assert np.linalg.norm(A.dot(x0) - b) > 1e-4
+
+        assert_allclose(x0, x1)
+
+    def test_cornercase(self):
+        np.random.seed(1234)
+
+        # Rounding error may prevent convergence with tol=0 --- ensure
+        # that the return values in this case are correct, and no
+        # exceptions are raised
+
+        for n in [3, 5, 10, 100]:
+            A = 2*eye_array(n)
+
+            with suppress_warnings() as sup:
+                sup.filter(DeprecationWarning, ".*called without specifying.*")
+                b = np.ones(n)
+                x, info = gcrotmk(A, b, maxiter=10)
+                assert_equal(info, 0)
+                assert_allclose(A.dot(x) - b, 0, atol=1e-14)
+
+                x, info = gcrotmk(A, b, rtol=0, maxiter=10)
+                if info == 0:
+                    assert_allclose(A.dot(x) - b, 0, atol=1e-14)
+
+                b = np.random.rand(n)
+                x, info = gcrotmk(A, b, maxiter=10)
+                assert_equal(info, 0)
+                assert_allclose(A.dot(x) - b, 0, atol=1e-14)
+
+                x, info = gcrotmk(A, b, rtol=0, maxiter=10)
+                if info == 0:
+                    assert_allclose(A.dot(x) - b, 0, atol=1e-14)
+
+    def test_nans(self):
+        A = eye_array(3, format='lil')
+        A[1,1] = np.nan
+        b = np.ones(3)
+
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, ".*called without specifying.*")
+            x, info = gcrotmk(A, b, rtol=0, maxiter=10)
+            assert_equal(info, 1)
+
+    def test_truncate(self):
+        np.random.seed(1234)
+        A = np.random.rand(30, 30) + np.eye(30)
+        b = np.random.rand(30)
+
+        for truncate in ['oldest', 'smallest']:
+            with suppress_warnings() as sup:
+                sup.filter(DeprecationWarning, ".*called without specifying.*")
+                x, info = gcrotmk(A, b, m=10, k=10, truncate=truncate,
+                                  rtol=1e-4, maxiter=200)
+            assert_equal(info, 0)
+            assert_allclose(A.dot(x) - b, 0, atol=1e-3)
+
+    def test_CU(self):
+        for discard_C in (True, False):
+            # Check that C,U behave as expected
+            CU = []
+            x0, count_0 = do_solve(CU=CU, discard_C=discard_C)
+            assert_(len(CU) > 0)
+            assert_(len(CU) <= 6)
+
+            if discard_C:
+                for c, u in CU:
+                    assert_(c is None)
+
+            # should converge immediately
+            x1, count_1 = do_solve(CU=CU, discard_C=discard_C)
+            if discard_C:
+                assert_equal(count_1, 2 + len(CU))
+            else:
+                assert_equal(count_1, 3)
+            assert_(count_1 <= count_0/2)
+            assert_allclose(x1, x0, atol=1e-14)
+
+    def test_denormals(self):
+        # Check that no warnings are emitted if the matrix contains
+        # numbers for which 1/x has no float representation, and that
+        # the solver behaves properly.
+        A = np.array([[1, 2], [3, 4]], dtype=float)
+        A *= 100 * np.nextafter(0, 1)
+
+        b = np.array([1, 1])
+
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, ".*called without specifying.*")
+            xp, info = gcrotmk(A, b)
+
+        if info == 0:
+            assert_allclose(A.dot(xp), b)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py
new file mode 100644
index 0000000000000000000000000000000000000000..7daff5fc854a0a53fea80f7e5d7fde8736ceb2e7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_iterative.py
@@ -0,0 +1,809 @@
+""" Test functions for the sparse.linalg._isolve module
+"""
+
+import itertools
+import platform
+import pytest
+
+import numpy as np
+from numpy.testing import assert_array_equal, assert_allclose
+from numpy import zeros, arange, array, ones, eye, iscomplexobj
+from numpy.linalg import norm
+
+from scipy.sparse import dia_array, csr_array, kronsum
+
+from scipy.sparse.linalg import LinearOperator, aslinearoperator
+from scipy.sparse.linalg._isolve import (bicg, bicgstab, cg, cgs,
+                                         gcrotmk, gmres, lgmres,
+                                         minres, qmr, tfqmr)
+
+# TODO check that method preserve shape and type
+# TODO test both preconditioner methods
+
+
+# list of all solvers under test
+_SOLVERS = [bicg, bicgstab, cg, cgs, gcrotmk, gmres, lgmres,
+            minres, qmr, tfqmr]
+
+CB_TYPE_FILTER = ".*called without specifying `callback_type`.*"
+
+
+# create parametrized fixture for easy reuse in tests
+@pytest.fixture(params=_SOLVERS, scope="session")
+def solver(request):
+    """
+    Fixture for all solvers in scipy.sparse.linalg._isolve
+    """
+    return request.param
+
+
+class Case:
+    def __init__(self, name, A, b=None, skip=None, nonconvergence=None):
+        self.name = name
+        self.A = A
+        if b is None:
+            self.b = arange(A.shape[0], dtype=float)
+        else:
+            self.b = b
+        if skip is None:
+            self.skip = []
+        else:
+            self.skip = skip
+        if nonconvergence is None:
+            self.nonconvergence = []
+        else:
+            self.nonconvergence = nonconvergence
+
+
+class SingleTest:
+    def __init__(self, A, b, solver, casename, convergence=True):
+        self.A = A
+        self.b = b
+        self.solver = solver
+        self.name = casename + '-' + solver.__name__
+        self.convergence = convergence
+
+    def __repr__(self):
+        return f"<{self.name}>"
+
+
+class IterativeParams:
+    def __init__(self):
+        sym_solvers = [minres, cg]
+        posdef_solvers = [cg]
+        real_solvers = [minres]
+
+        # list of Cases
+        self.cases = []
+
+        # Symmetric and Positive Definite
+        N = 40
+        data = ones((3, N))
+        data[0, :] = 2
+        data[1, :] = -1
+        data[2, :] = -1
+        Poisson1D = dia_array((data, [0, -1, 1]), shape=(N, N)).tocsr()
+        self.cases.append(Case("poisson1d", Poisson1D))
+        # note: minres fails for single precision
+        self.cases.append(Case("poisson1d-F", Poisson1D.astype('f'),
+                               skip=[minres]))
+
+        # Symmetric and Negative Definite
+        self.cases.append(Case("neg-poisson1d", -Poisson1D,
+                               skip=posdef_solvers))
+        # note: minres fails for single precision
+        self.cases.append(Case("neg-poisson1d-F", (-Poisson1D).astype('f'),
+                               skip=posdef_solvers + [minres]))
+
+        # 2-dimensional Poisson equations
+        Poisson2D = kronsum(Poisson1D, Poisson1D)
+        # note: minres fails for 2-d poisson problem,
+        # it will be fixed in the future PR
+        self.cases.append(Case("poisson2d", Poisson2D, skip=[minres]))
+        # note: minres fails for single precision
+        self.cases.append(Case("poisson2d-F", Poisson2D.astype('f'),
+                               skip=[minres]))
+
+        # Symmetric and Indefinite
+        data = array([[6, -5, 2, 7, -1, 10, 4, -3, -8, 9]], dtype='d')
+        RandDiag = dia_array((data, [0]), shape=(10, 10)).tocsr()
+        self.cases.append(Case("rand-diag", RandDiag, skip=posdef_solvers))
+        self.cases.append(Case("rand-diag-F", RandDiag.astype('f'),
+                               skip=posdef_solvers))
+
+        # Random real-valued
+        rng = np.random.RandomState(1234)
+        data = rng.rand(4, 4)
+        self.cases.append(Case("rand", data,
+                               skip=posdef_solvers + sym_solvers))
+        self.cases.append(Case("rand-F", data.astype('f'),
+                               skip=posdef_solvers + sym_solvers))
+
+        # Random symmetric real-valued
+        rng = np.random.RandomState(1234)
+        data = rng.rand(4, 4)
+        data = data + data.T
+        self.cases.append(Case("rand-sym", data, skip=posdef_solvers))
+        self.cases.append(Case("rand-sym-F", data.astype('f'),
+                               skip=posdef_solvers))
+
+        # Random pos-def symmetric real
+        np.random.seed(1234)
+        data = np.random.rand(9, 9)
+        data = np.dot(data.conj(), data.T)
+        self.cases.append(Case("rand-sym-pd", data))
+        # note: minres fails for single precision
+        self.cases.append(Case("rand-sym-pd-F", data.astype('f'),
+                               skip=[minres]))
+
+        # Random complex-valued
+        rng = np.random.RandomState(1234)
+        data = rng.rand(4, 4) + 1j * rng.rand(4, 4)
+        skip_cmplx = posdef_solvers + sym_solvers + real_solvers
+        self.cases.append(Case("rand-cmplx", data, skip=skip_cmplx))
+        self.cases.append(Case("rand-cmplx-F", data.astype('F'),
+                               skip=skip_cmplx))
+
+        # Random hermitian complex-valued
+        rng = np.random.RandomState(1234)
+        data = rng.rand(4, 4) + 1j * rng.rand(4, 4)
+        data = data + data.T.conj()
+        self.cases.append(Case("rand-cmplx-herm", data,
+                               skip=posdef_solvers + real_solvers))
+        self.cases.append(Case("rand-cmplx-herm-F", data.astype('F'),
+                               skip=posdef_solvers + real_solvers))
+
+        # Random pos-def hermitian complex-valued
+        rng = np.random.RandomState(1234)
+        data = rng.rand(9, 9) + 1j * rng.rand(9, 9)
+        data = np.dot(data.conj(), data.T)
+        self.cases.append(Case("rand-cmplx-sym-pd", data, skip=real_solvers))
+        self.cases.append(Case("rand-cmplx-sym-pd-F", data.astype('F'),
+                               skip=real_solvers))
+
+        # Non-symmetric and Positive Definite
+        #
+        # cgs, qmr, bicg and tfqmr fail to converge on this one
+        #   -- algorithmic limitation apparently
+        data = ones((2, 10))
+        data[0, :] = 2
+        data[1, :] = -1
+        A = dia_array((data, [0, -1]), shape=(10, 10)).tocsr()
+        self.cases.append(Case("nonsymposdef", A,
+                               skip=sym_solvers + [cgs, qmr, bicg, tfqmr]))
+        self.cases.append(Case("nonsymposdef-F", A.astype('F'),
+                               skip=sym_solvers + [cgs, qmr, bicg, tfqmr]))
+
+        # Symmetric, non-pd, hitting cgs/bicg/bicgstab/qmr/tfqmr breakdown
+        A = np.array([[0, 0, 0, 0, 0, 1, -1, -0, -0, -0, -0],
+                      [0, 0, 0, 0, 0, 2, -0, -1, -0, -0, -0],
+                      [0, 0, 0, 0, 0, 2, -0, -0, -1, -0, -0],
+                      [0, 0, 0, 0, 0, 2, -0, -0, -0, -1, -0],
+                      [0, 0, 0, 0, 0, 1, -0, -0, -0, -0, -1],
+                      [1, 2, 2, 2, 1, 0, -0, -0, -0, -0, -0],
+                      [-1, 0, 0, 0, 0, 0, -1, -0, -0, -0, -0],
+                      [0, -1, 0, 0, 0, 0, -0, -1, -0, -0, -0],
+                      [0, 0, -1, 0, 0, 0, -0, -0, -1, -0, -0],
+                      [0, 0, 0, -1, 0, 0, -0, -0, -0, -1, -0],
+                      [0, 0, 0, 0, -1, 0, -0, -0, -0, -0, -1]], dtype=float)
+        b = np.array([0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], dtype=float)
+        assert (A == A.T).all()
+        self.cases.append(Case("sym-nonpd", A, b,
+                               skip=posdef_solvers,
+                               nonconvergence=[cgs, bicg, bicgstab, qmr, tfqmr]
+                               )
+                          )
+
+    def generate_tests(self):
+        # generate test cases with skips applied
+        tests = []
+        for case in self.cases:
+            for solver in _SOLVERS:
+                if (solver in case.skip):
+                    continue
+                if solver in case.nonconvergence:
+                    tests += [SingleTest(case.A, case.b, solver, case.name,
+                                         convergence=False)]
+                else:
+                    tests += [SingleTest(case.A, case.b, solver, case.name)]
+        return tests
+
+
+cases = IterativeParams().generate_tests()
+
+
+@pytest.fixture(params=cases, ids=[x.name for x in cases], scope="module")
+def case(request):
+    """
+    Fixture for all cases in IterativeParams
+    """
+    return request.param
+
+@pytest.mark.thread_unsafe
+def test_maxiter(case):
+    if not case.convergence:
+        pytest.skip("Solver - Breakdown case, see gh-8829")
+    A = case.A
+    rtol = 1e-12
+
+    b = case.b
+    x0 = 0 * b
+
+    residuals = []
+
+    def callback(x):
+        if x.ndim == 0:
+            residuals.append(norm(b - case.A * x))
+        else:
+            residuals.append(norm(b - case.A @ x))
+
+    if case.solver == gmres:
+        with pytest.warns(DeprecationWarning, match=CB_TYPE_FILTER):
+            x, info = case.solver(A, b, x0=x0, rtol=rtol, maxiter=1, callback=callback)
+    else:
+        x, info = case.solver(A, b, x0=x0, rtol=rtol, maxiter=1, callback=callback)
+
+    assert len(residuals) == 1
+    assert info == 1
+
+
+def test_convergence(case):
+    A = case.A
+
+    if A.dtype.char in "dD":
+        rtol = 1e-8
+    else:
+        rtol = 1e-2
+
+    b = case.b
+    x0 = 0 * b
+
+    x, info = case.solver(A, b, x0=x0, rtol=rtol)
+
+    assert_array_equal(x0, 0 * b)  # ensure that x0 is not overwritten
+    if case.convergence:
+        assert info == 0
+        assert norm(A @ x - b) <= norm(b) * rtol
+    else:
+        assert info != 0
+        assert norm(A @ x - b) <= norm(b)
+
+
+def test_precond_dummy(case):
+    if not case.convergence:
+        pytest.skip("Solver - Breakdown case, see gh-8829")
+
+    rtol = 1e-8
+
+    def identity(b, which=None):
+        """trivial preconditioner"""
+        return b
+
+    A = case.A
+
+    M, N = A.shape
+    # Ensure the diagonal elements of A are non-zero before calculating
+    # 1.0/A.diagonal()
+    diagOfA = A.diagonal()
+    if np.count_nonzero(diagOfA) == len(diagOfA):
+        dia_array(([1.0 / diagOfA], [0]), shape=(M, N))
+
+    b = case.b
+    x0 = 0 * b
+
+    precond = LinearOperator(A.shape, identity, rmatvec=identity)
+
+    if case.solver is qmr:
+        x, info = case.solver(A, b, M1=precond, M2=precond, x0=x0, rtol=rtol)
+    else:
+        x, info = case.solver(A, b, M=precond, x0=x0, rtol=rtol)
+    assert info == 0
+    assert norm(A @ x - b) <= norm(b) * rtol
+
+    A = aslinearoperator(A)
+    A.psolve = identity
+    A.rpsolve = identity
+
+    x, info = case.solver(A, b, x0=x0, rtol=rtol)
+    assert info == 0
+    assert norm(A @ x - b) <= norm(b) * rtol
+
+
+# Specific test for poisson1d and poisson2d cases
+@pytest.mark.fail_slow(10)
+@pytest.mark.parametrize('case', [x for x in IterativeParams().cases
+                                  if x.name in ('poisson1d', 'poisson2d')],
+                         ids=['poisson1d', 'poisson2d'])
+def test_precond_inverse(case):
+    for solver in _SOLVERS:
+        if solver in case.skip or solver is qmr:
+            continue
+
+        rtol = 1e-8
+
+        def inverse(b, which=None):
+            """inverse preconditioner"""
+            A = case.A
+            if not isinstance(A, np.ndarray):
+                A = A.toarray()
+            return np.linalg.solve(A, b)
+
+        def rinverse(b, which=None):
+            """inverse preconditioner"""
+            A = case.A
+            if not isinstance(A, np.ndarray):
+                A = A.toarray()
+            return np.linalg.solve(A.T, b)
+
+        matvec_count = [0]
+
+        def matvec(b):
+            matvec_count[0] += 1
+            return case.A @ b
+
+        def rmatvec(b):
+            matvec_count[0] += 1
+            return case.A.T @ b
+
+        b = case.b
+        x0 = 0 * b
+
+        A = LinearOperator(case.A.shape, matvec, rmatvec=rmatvec)
+        precond = LinearOperator(case.A.shape, inverse, rmatvec=rinverse)
+
+        # Solve with preconditioner
+        matvec_count = [0]
+        x, info = solver(A, b, M=precond, x0=x0, rtol=rtol)
+
+        assert info == 0
+        assert norm(case.A @ x - b) <= norm(b) * rtol
+
+        # Solution should be nearly instant
+        assert matvec_count[0] <= 3
+
+
+def test_atol(solver):
+    # TODO: minres / tfqmr. It didn't historically use absolute tolerances, so
+    # fixing it is less urgent.
+    if solver in (minres, tfqmr):
+        pytest.skip("TODO: Add atol to minres/tfqmr")
+
+    # Historically this is tested as below, all pass but for some reason
+    # gcrotmk is over-sensitive to difference between random.seed/rng.random
+    # Hence tol lower bound is changed from -10 to -9
+    # np.random.seed(1234)
+    # A = np.random.rand(10, 10)
+    # A = A @ A.T + 10 * np.eye(10)
+    # b = 1e3*np.random.rand(10)
+
+    rng = np.random.default_rng(168441431005389)
+    A = rng.uniform(size=[10, 10])
+    A = A @ A.T + 10*np.eye(10)
+    b = 1e3 * rng.uniform(size=10)
+
+    b_norm = np.linalg.norm(b)
+
+    tols = np.r_[0, np.logspace(-9, 2, 7), np.inf]
+
+    # Check effect of badly scaled preconditioners
+    M0 = rng.standard_normal(size=(10, 10))
+    M0 = M0 @ M0.T
+    Ms = [None, 1e-6 * M0, 1e6 * M0]
+
+    for M, rtol, atol in itertools.product(Ms, tols, tols):
+        if rtol == 0 and atol == 0:
+            continue
+
+        if solver is qmr:
+            if M is not None:
+                M = aslinearoperator(M)
+                M2 = aslinearoperator(np.eye(10))
+            else:
+                M2 = None
+            x, info = solver(A, b, M1=M, M2=M2, rtol=rtol, atol=atol)
+        else:
+            x, info = solver(A, b, M=M, rtol=rtol, atol=atol)
+
+        assert info == 0
+        residual = A @ x - b
+        err = np.linalg.norm(residual)
+        atol2 = rtol * b_norm
+        # Added 1.00025 fudge factor because of `err` exceeding `atol` just
+        # very slightly on s390x (see gh-17839)
+        assert err <= 1.00025 * max(atol, atol2)
+
+
+def test_zero_rhs(solver):
+    rng = np.random.default_rng(1684414984100503)
+    A = rng.random(size=[10, 10])
+    A = A @ A.T + 10 * np.eye(10)
+
+    b = np.zeros(10)
+    tols = np.r_[np.logspace(-10, 2, 7)]
+
+    for tol in tols:
+        x, info = solver(A, b, rtol=tol)
+        assert info == 0
+        assert_allclose(x, 0., atol=1e-15)
+
+        x, info = solver(A, b, rtol=tol, x0=ones(10))
+        assert info == 0
+        assert_allclose(x, 0., atol=tol)
+
+        if solver is not minres:
+            x, info = solver(A, b, rtol=tol, atol=0, x0=ones(10))
+            if info == 0:
+                assert_allclose(x, 0)
+
+            x, info = solver(A, b, rtol=tol, atol=tol)
+            assert info == 0
+            assert_allclose(x, 0, atol=1e-300)
+
+            x, info = solver(A, b, rtol=tol, atol=0)
+            assert info == 0
+            assert_allclose(x, 0, atol=1e-300)
+
+
+@pytest.mark.xfail(reason="see gh-18697")
+def test_maxiter_worsening(solver):
+    if solver not in (gmres, lgmres, qmr):
+        # these were skipped from the very beginning, see gh-9201; gh-14160
+        pytest.skip("Solver breakdown case")
+    # Check error does not grow (boundlessly) with increasing maxiter.
+    # This can occur due to the solvers hitting close to breakdown,
+    # which they should detect and halt as necessary.
+    # cf. gh-9100
+    if (solver is lgmres and
+            platform.machine() not in ['x86_64' 'x86', 'aarch64', 'arm64']):
+        # see gh-17839
+        pytest.xfail(reason="fails on at least ppc64le, ppc64 and riscv64")
+
+    # Singular matrix, rhs numerically not in range
+    A = np.array([[-0.1112795288033378, 0, 0, 0.16127952880333685],
+                  [0, -0.13627952880333782 + 6.283185307179586j, 0, 0],
+                  [0, 0, -0.13627952880333782 - 6.283185307179586j, 0],
+                  [0.1112795288033368, 0j, 0j, -0.16127952880333785]])
+    v = np.ones(4)
+    best_error = np.inf
+
+    # Unable to match the Fortran code tolerance levels with this example
+    # Original tolerance values
+
+    # slack_tol = 7 if platform.machine() == 'aarch64' else 5
+    slack_tol = 9
+
+    for maxiter in range(1, 20):
+        x, info = solver(A, v, maxiter=maxiter, rtol=1e-8, atol=0)
+
+        if info == 0:
+            assert norm(A @ x - v) <= 1e-8 * norm(v)
+
+        error = np.linalg.norm(A @ x - v)
+        best_error = min(best_error, error)
+
+        # Check with slack
+        assert error <= slack_tol * best_error
+
+
+def test_x0_working(solver):
+    # Easy problem
+    rng = np.random.default_rng(1685363802304750)
+    n = 10
+    A = rng.random(size=[n, n])
+    A = A @ A.T
+    b = rng.random(n)
+    x0 = rng.random(n)
+
+    if solver is minres:
+        kw = dict(rtol=1e-6)
+    else:
+        kw = dict(atol=0, rtol=1e-6)
+
+    x, info = solver(A, b, **kw)
+    assert info == 0
+    assert norm(A @ x - b) <= 1e-6 * norm(b)
+
+    x, info = solver(A, b, x0=x0, **kw)
+    assert info == 0
+    assert norm(A @ x - b) <= 4.5e-6*norm(b)
+
+
+def test_x0_equals_Mb(case):
+    if (case.solver is bicgstab) and (case.name == 'nonsymposdef-bicgstab'):
+        pytest.skip("Solver fails due to numerical noise "
+                    "on some architectures (see gh-15533).")
+    if case.solver is tfqmr:
+        pytest.skip("Solver does not support x0='Mb'")
+
+    A = case.A
+    b = case.b
+    x0 = 'Mb'
+    rtol = 1e-8
+    x, info = case.solver(A, b, x0=x0, rtol=rtol)
+
+    assert_array_equal(x0, 'Mb')  # ensure that x0 is not overwritten
+    assert info == 0
+    assert norm(A @ x - b) <= rtol * norm(b)
+
+
+@pytest.mark.parametrize('solver', _SOLVERS)
+def test_x0_solves_problem_exactly(solver):
+    # See gh-19948
+    mat = np.eye(2)
+    rhs = np.array([-1., -1.])
+
+    sol, info = solver(mat, rhs, x0=rhs)
+    assert_allclose(sol, rhs)
+    assert info == 0
+
+
+# Specific tfqmr test
+@pytest.mark.thread_unsafe
+@pytest.mark.parametrize('case', IterativeParams().cases)
+def test_show(case, capsys):
+    def cb(x):
+        pass
+
+    x, info = tfqmr(case.A, case.b, callback=cb, show=True)
+    out, err = capsys.readouterr()
+
+    if case.name == "sym-nonpd":
+        # no logs for some reason
+        exp = ""
+    elif case.name in ("nonsymposdef", "nonsymposdef-F"):
+        # Asymmetric and Positive Definite
+        exp = "TFQMR: Linear solve not converged due to reach MAXIT iterations"
+    else:  # all other cases
+        exp = "TFQMR: Linear solve converged due to reach TOL iterations"
+
+    assert out.startswith(exp)
+    assert err == ""
+
+
+def test_positional_error(solver):
+    # from test_x0_working
+    rng = np.random.default_rng(1685363802304750)
+    n = 10
+    A = rng.random(size=[n, n])
+    A = A @ A.T
+    b = rng.random(n)
+    x0 = rng.random(n)
+    with pytest.raises(TypeError):
+        solver(A, b, x0, 1e-5)
+
+
+@pytest.mark.parametrize("atol", ["legacy", None, -1])
+def test_invalid_atol(solver, atol):
+    if solver == minres:
+        pytest.skip("minres has no `atol` argument")
+    # from test_x0_working
+    rng = np.random.default_rng(1685363802304750)
+    n = 10
+    A = rng.random(size=[n, n])
+    A = A @ A.T
+    b = rng.random(n)
+    x0 = rng.random(n)
+    with pytest.raises(ValueError):
+        solver(A, b, x0, atol=atol)
+
+
+class TestQMR:
+    @pytest.mark.filterwarnings('ignore::scipy.sparse.SparseEfficiencyWarning')
+    def test_leftright_precond(self):
+        """Check that QMR works with left and right preconditioners"""
+
+        from scipy.sparse.linalg._dsolve import splu
+        from scipy.sparse.linalg._interface import LinearOperator
+
+        n = 100
+
+        dat = ones(n)
+        A = dia_array(([-2 * dat, 4 * dat, -dat], [-1, 0, 1]), shape=(n, n))
+        b = arange(n, dtype='d')
+
+        L = dia_array(([-dat / 2, dat], [-1, 0]), shape=(n, n))
+        U = dia_array(([4 * dat, -dat], [0, 1]), shape=(n, n))
+        L_solver = splu(L)
+        U_solver = splu(U)
+
+        def L_solve(b):
+            return L_solver.solve(b)
+
+        def U_solve(b):
+            return U_solver.solve(b)
+
+        def LT_solve(b):
+            return L_solver.solve(b, 'T')
+
+        def UT_solve(b):
+            return U_solver.solve(b, 'T')
+
+        M1 = LinearOperator((n, n), matvec=L_solve, rmatvec=LT_solve)
+        M2 = LinearOperator((n, n), matvec=U_solve, rmatvec=UT_solve)
+
+        rtol = 1e-8
+        x, info = qmr(A, b, rtol=rtol, maxiter=15, M1=M1, M2=M2)
+
+        assert info == 0
+        assert norm(A @ x - b) <= rtol * norm(b)
+
+
+class TestGMRES:
+    def test_basic(self):
+        A = np.vander(np.arange(10) + 1)[:, ::-1]
+        b = np.zeros(10)
+        b[0] = 1
+
+        x_gm, err = gmres(A, b, restart=5, maxiter=1)
+
+        assert_allclose(x_gm[0], 0.359, rtol=1e-2)
+
+    @pytest.mark.filterwarnings(f"ignore:{CB_TYPE_FILTER}:DeprecationWarning")
+    def test_callback(self):
+
+        def store_residual(r, rvec):
+            rvec[rvec.nonzero()[0].max() + 1] = r
+
+        # Define, A,b
+        A = csr_array(array([[-2, 1, 0, 0, 0, 0],
+                             [1, -2, 1, 0, 0, 0],
+                             [0, 1, -2, 1, 0, 0],
+                             [0, 0, 1, -2, 1, 0],
+                             [0, 0, 0, 1, -2, 1],
+                             [0, 0, 0, 0, 1, -2]]))
+        b = ones((A.shape[0],))
+        maxiter = 1
+        rvec = zeros(maxiter + 1)
+        rvec[0] = 1.0
+
+        def callback(r):
+            return store_residual(r, rvec)
+
+        x, flag = gmres(A, b, x0=zeros(A.shape[0]), rtol=1e-16,
+                        maxiter=maxiter, callback=callback)
+
+        # Expected output from SciPy 1.0.0
+        assert_allclose(rvec, array([1.0, 0.81649658092772603]), rtol=1e-10)
+
+        # Test preconditioned callback
+        M = 1e-3 * np.eye(A.shape[0])
+        rvec = zeros(maxiter + 1)
+        rvec[0] = 1.0
+        x, flag = gmres(A, b, M=M, rtol=1e-16, maxiter=maxiter,
+                        callback=callback)
+
+        # Expected output from SciPy 1.0.0
+        # (callback has preconditioned residual!)
+        assert_allclose(rvec, array([1.0, 1e-3 * 0.81649658092772603]),
+                        rtol=1e-10)
+
+    def test_abi(self):
+        # Check we don't segfault on gmres with complex argument
+        A = eye(2)
+        b = ones(2)
+        r_x, r_info = gmres(A, b)
+        r_x = r_x.astype(complex)
+        x, info = gmres(A.astype(complex), b.astype(complex))
+
+        assert iscomplexobj(x)
+        assert_allclose(r_x, x)
+        assert r_info == info
+
+    @pytest.mark.fail_slow(10)
+    def test_atol_legacy(self):
+
+        A = eye(2)
+        b = ones(2)
+        x, info = gmres(A, b, rtol=1e-5)
+        assert np.linalg.norm(A @ x - b) <= 1e-5 * np.linalg.norm(b)
+        assert_allclose(x, b, atol=0, rtol=1e-8)
+
+        rndm = np.random.RandomState(12345)
+        A = rndm.rand(30, 30)
+        b = 1e-6 * ones(30)
+        x, info = gmres(A, b, rtol=1e-7, restart=20)
+        assert np.linalg.norm(A @ x - b) > 1e-7
+
+        A = eye(2)
+        b = 1e-10 * ones(2)
+        x, info = gmres(A, b, rtol=1e-8, atol=0)
+        assert np.linalg.norm(A @ x - b) <= 1e-8 * np.linalg.norm(b)
+
+    def test_defective_precond_breakdown(self):
+        # Breakdown due to defective preconditioner
+        M = np.eye(3)
+        M[2, 2] = 0
+
+        b = np.array([0, 1, 1])
+        x = np.array([1, 0, 0])
+        A = np.diag([2, 3, 4])
+
+        x, info = gmres(A, b, x0=x, M=M, rtol=1e-15, atol=0)
+
+        # Should not return nans, nor terminate with false success
+        assert not np.isnan(x).any()
+        if info == 0:
+            assert np.linalg.norm(A @ x - b) <= 1e-15 * np.linalg.norm(b)
+
+        # The solution should be OK outside null space of M
+        assert_allclose(M @ (A @ x), M @ b)
+
+    def test_defective_matrix_breakdown(self):
+        # Breakdown due to defective matrix
+        A = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 0]])
+        b = np.array([1, 0, 1])
+        rtol = 1e-8
+        x, info = gmres(A, b, rtol=rtol, atol=0)
+
+        # Should not return nans, nor terminate with false success
+        assert not np.isnan(x).any()
+        if info == 0:
+            assert np.linalg.norm(A @ x - b) <= rtol * np.linalg.norm(b)
+
+        # The solution should be OK outside null space of A
+        assert_allclose(A @ (A @ x), A @ b)
+
+    @pytest.mark.filterwarnings(f"ignore:{CB_TYPE_FILTER}:DeprecationWarning")
+    def test_callback_type(self):
+        # The legacy callback type changes meaning of 'maxiter'
+        np.random.seed(1)
+        A = np.random.rand(20, 20)
+        b = np.random.rand(20)
+
+        cb_count = [0]
+
+        def pr_norm_cb(r):
+            cb_count[0] += 1
+            assert isinstance(r, float)
+
+        def x_cb(x):
+            cb_count[0] += 1
+            assert isinstance(x, np.ndarray)
+
+        # 2 iterations is not enough to solve the problem
+        cb_count = [0]
+        x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb,
+                        maxiter=2, restart=50)
+        assert info == 2
+        assert cb_count[0] == 2
+
+        # With `callback_type` specified, no warning should be raised
+        cb_count = [0]
+        x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb,
+                        maxiter=2, restart=50, callback_type='legacy')
+        assert info == 2
+        assert cb_count[0] == 2
+
+        # 2 restart cycles is enough to solve the problem
+        cb_count = [0]
+        x, info = gmres(A, b, rtol=1e-6, atol=0, callback=pr_norm_cb,
+                        maxiter=2, restart=50, callback_type='pr_norm')
+        assert info == 0
+        assert cb_count[0] > 2
+
+        # 2 restart cycles is enough to solve the problem
+        cb_count = [0]
+        x, info = gmres(A, b, rtol=1e-6, atol=0, callback=x_cb, maxiter=2,
+                        restart=50, callback_type='x')
+        assert info == 0
+        assert cb_count[0] == 1
+
+    def test_callback_x_monotonic(self):
+        # Check that callback_type='x' gives monotonic norm decrease
+        rng = np.random.RandomState(1)
+        A = rng.rand(20, 20) + np.eye(20)
+        b = rng.rand(20)
+
+        prev_r = [np.inf]
+        count = [0]
+
+        def x_cb(x):
+            r = np.linalg.norm(A @ x - b)
+            assert r <= prev_r[0]
+            prev_r[0] = r
+            count[0] += 1
+
+        x, info = gmres(A, b, rtol=1e-6, atol=0, callback=x_cb, maxiter=20,
+                        restart=10, callback_type='x')
+        assert info == 20
+        assert count[0] == 20
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lgmres.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lgmres.py
new file mode 100644
index 0000000000000000000000000000000000000000..a33fc9bc13b36faef48f04388b76ed33eac775d6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lgmres.py
@@ -0,0 +1,225 @@
+"""Tests for the linalg._isolve.lgmres module
+"""
+
+import threading
+from numpy.testing import (assert_, assert_allclose, assert_equal,
+                           suppress_warnings)
+
+import pytest
+from platform import python_implementation
+
+import numpy as np
+from numpy import zeros, array, allclose
+from scipy.linalg import norm
+from scipy.sparse import csr_array, eye_array, random_array
+
+from scipy.sparse.linalg._interface import LinearOperator
+from scipy.sparse.linalg import splu
+from scipy.sparse.linalg._isolve import lgmres, gmres
+
+
+Am = csr_array(array([[-2, 1, 0, 0, 0, 9],
+                      [1, -2, 1, 0, 5, 0],
+                      [0, 1, -2, 1, 0, 0],
+                      [0, 0, 1, -2, 1, 0],
+                      [0, 3, 0, 1, -2, 1],
+                      [1, 0, 0, 0, 1, -2]]))
+b = array([1, 2, 3, 4, 5, 6])
+count = threading.local()  # [0]
+niter = threading.local()  # [0]
+
+
+def matvec(v):
+    if not hasattr(count, 'c'):
+        count.c = [0]
+    count.c[0] += 1
+    return Am@v
+
+
+def cb(v):
+    if not hasattr(niter, 'n'):
+        niter.n = [0]
+    niter.n[0] += 1
+
+
+A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype)
+
+
+def do_solve(**kw):
+    if not hasattr(niter, 'n'):
+        niter.n = [0]
+    if not hasattr(count, 'c'):
+        count.c = [0]
+    count.c[0] = 0
+    with suppress_warnings() as sup:
+        sup.filter(DeprecationWarning, ".*called without specifying.*")
+        x0, flag = lgmres(A, b, x0=zeros(A.shape[0]),
+                          inner_m=6, rtol=1e-14, **kw)
+    count_0 = count.c[0]
+    assert_(allclose(A@x0, b, rtol=1e-12, atol=1e-12), norm(A@x0-b))
+    return x0, count_0
+
+
+class TestLGMRES:
+    def test_preconditioner(self):
+        # Check that preconditioning works
+        pc = splu(Am.tocsc())
+        M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype)
+
+        x0, count_0 = do_solve()
+        niter.n[0] = 0
+        x1, count_1 = do_solve(M=M, callback=cb)
+
+        assert count_1 == 3
+        assert count_1 < count_0/2
+        assert allclose(x1, x0, rtol=1e-14)
+        assert niter.n[0] < 3
+
+    def test_outer_v(self):
+        # Check that the augmentation vectors behave as expected
+
+        outer_v = []
+        x0, count_0 = do_solve(outer_k=6, outer_v=outer_v)
+        assert_(len(outer_v) > 0)
+        assert_(len(outer_v) <= 6)
+
+        x1, count_1 = do_solve(outer_k=6, outer_v=outer_v,
+                               prepend_outer_v=True)
+        assert_(count_1 == 2, count_1)
+        assert_(count_1 < count_0/2)
+        assert_(allclose(x1, x0, rtol=1e-14))
+
+        # ---
+
+        outer_v = []
+        x0, count_0 = do_solve(outer_k=6, outer_v=outer_v,
+                               store_outer_Av=False)
+        assert_(array([v[1] is None for v in outer_v]).all())
+        assert_(len(outer_v) > 0)
+        assert_(len(outer_v) <= 6)
+
+        x1, count_1 = do_solve(outer_k=6, outer_v=outer_v,
+                               prepend_outer_v=True)
+        assert_(count_1 == 3, count_1)
+        assert_(count_1 < count_0/2)
+        assert_(allclose(x1, x0, rtol=1e-14))
+
+    @pytest.mark.skipif(python_implementation() == 'PyPy',
+                        reason="Fails on PyPy CI runs. See #9507")
+    def test_arnoldi(self):
+        rng = np.random.default_rng(123)
+
+        A = eye_array(2000) + random_array((2000, 2000), density=5e-4, rng=rng)
+        b = rng.random(2000)
+
+        # The inner arnoldi should be equivalent to gmres
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, ".*called without specifying.*")
+            x0, flag0 = lgmres(A, b, x0=zeros(A.shape[0]), inner_m=10, maxiter=1)
+            x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=10, maxiter=1)
+
+        assert_equal(flag0, 1)
+        assert_equal(flag1, 1)
+        norm = np.linalg.norm(A.dot(x0) - b)
+        assert_(norm > 1e-4)
+        assert_allclose(x0, x1)
+
+    def test_cornercase(self):
+        rng = np.random.RandomState(1234)
+
+        # Rounding error may prevent convergence with tol=0 --- ensure
+        # that the return values in this case are correct, and no
+        # exceptions are raised
+
+        for n in [3, 5, 10, 100]:
+            A = 2*eye_array(n)
+
+            with suppress_warnings() as sup:
+                sup.filter(DeprecationWarning, ".*called without specifying.*")
+
+                b = np.ones(n)
+                x, info = lgmres(A, b, maxiter=10)
+                assert_equal(info, 0)
+                assert_allclose(A.dot(x) - b, 0, atol=1e-14)
+
+                x, info = lgmres(A, b, rtol=0, maxiter=10)
+                if info == 0:
+                    assert_allclose(A.dot(x) - b, 0, atol=1e-14)
+
+                b = rng.rand(n)
+                x, info = lgmres(A, b, maxiter=10)
+                assert_equal(info, 0)
+                assert_allclose(A.dot(x) - b, 0, atol=1e-14)
+
+                x, info = lgmres(A, b, rtol=0, maxiter=10)
+                if info == 0:
+                    assert_allclose(A.dot(x) - b, 0, atol=1e-14)
+
+    def test_nans(self):
+        A = eye_array(3, format='lil')
+        A[1, 1] = np.nan
+        b = np.ones(3)
+
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, ".*called without specifying.*")
+            x, info = lgmres(A, b, rtol=0, maxiter=10)
+            assert_equal(info, 1)
+
+    def test_breakdown_with_outer_v(self):
+        A = np.array([[1, 2], [3, 4]], dtype=float)
+        b = np.array([1, 2])
+
+        x = np.linalg.solve(A, b)
+        v0 = np.array([1, 0])
+
+        # The inner iteration should converge to the correct solution,
+        # since it's in the outer vector list
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, ".*called without specifying.*")
+            xp, info = lgmres(A, b, outer_v=[(v0, None), (x, None)], maxiter=1)
+
+        assert_allclose(xp, x, atol=1e-12)
+
+    def test_breakdown_underdetermined(self):
+        # Should find LSQ solution in the Krylov span in one inner
+        # iteration, despite solver breakdown from nilpotent A.
+        A = np.array([[0, 1, 1, 1],
+                      [0, 0, 1, 1],
+                      [0, 0, 0, 1],
+                      [0, 0, 0, 0]], dtype=float)
+
+        bs = [
+            np.array([1, 1, 1, 1]),
+            np.array([1, 1, 1, 0]),
+            np.array([1, 1, 0, 0]),
+            np.array([1, 0, 0, 0]),
+        ]
+
+        for b in bs:
+            with suppress_warnings() as sup:
+                sup.filter(DeprecationWarning, ".*called without specifying.*")
+                xp, info = lgmres(A, b, maxiter=1)
+            resp = np.linalg.norm(A.dot(xp) - b)
+
+            K = np.c_[b, A.dot(b), A.dot(A.dot(b)), A.dot(A.dot(A.dot(b)))]
+            y, _, _, _ = np.linalg.lstsq(A.dot(K), b, rcond=-1)
+            x = K.dot(y)
+            res = np.linalg.norm(A.dot(x) - b)
+
+            assert_allclose(resp, res, err_msg=repr(b))
+
+    def test_denormals(self):
+        # Check that no warnings are emitted if the matrix contains
+        # numbers for which 1/x has no float representation, and that
+        # the solver behaves properly.
+        A = np.array([[1, 2], [3, 4]], dtype=float)
+        A *= 100 * np.nextafter(0, 1)
+
+        b = np.array([1, 1])
+
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, ".*called without specifying.*")
+            xp, info = lgmres(A, b)
+
+        if info == 0:
+            assert_allclose(A.dot(xp), b)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsmr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsmr.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d1196b23e0b7a24513850116ee134193709619e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsmr.py
@@ -0,0 +1,185 @@
+"""
+Copyright (C) 2010 David Fong and Michael Saunders
+Distributed under the same license as SciPy
+
+Testing Code for LSMR.
+
+03 Jun 2010: First version release with lsmr.py
+
+David Chin-lung Fong            clfong@stanford.edu
+Institute for Computational and Mathematical Engineering
+Stanford University
+
+Michael Saunders                saunders@stanford.edu
+Systems Optimization Laboratory
+Dept of MS&E, Stanford University.
+
+"""
+
+from numpy import array, arange, eye, zeros, ones, transpose, hstack
+from numpy.linalg import norm
+from numpy.testing import assert_allclose
+import pytest
+from scipy.sparse import coo_array
+from scipy.sparse.linalg._interface import aslinearoperator
+from scipy.sparse.linalg import lsmr
+from .test_lsqr import G, b
+
+
+class TestLSMR:
+    def setup_method(self):
+        self.n = 10
+        self.m = 10
+
+    def assertCompatibleSystem(self, A, xtrue):
+        Afun = aslinearoperator(A)
+        b = Afun.matvec(xtrue)
+        x = lsmr(A, b)[0]
+        assert norm(x - xtrue) == pytest.approx(0, abs=1e-5)
+
+    def testIdentityACase1(self):
+        A = eye(self.n)
+        xtrue = zeros((self.n, 1))
+        self.assertCompatibleSystem(A, xtrue)
+
+    def testIdentityACase2(self):
+        A = eye(self.n)
+        xtrue = ones((self.n,1))
+        self.assertCompatibleSystem(A, xtrue)
+
+    def testIdentityACase3(self):
+        A = eye(self.n)
+        xtrue = transpose(arange(self.n,0,-1))
+        self.assertCompatibleSystem(A, xtrue)
+
+    def testBidiagonalA(self):
+        A = lowerBidiagonalMatrix(20,self.n)
+        xtrue = transpose(arange(self.n,0,-1))
+        self.assertCompatibleSystem(A,xtrue)
+
+    def testScalarB(self):
+        A = array([[1.0, 2.0]])
+        b = 3.0
+        x = lsmr(A, b)[0]
+        assert norm(A.dot(x) - b) == pytest.approx(0)
+
+    def testComplexX(self):
+        A = eye(self.n)
+        xtrue = transpose(arange(self.n, 0, -1) * (1 + 1j))
+        self.assertCompatibleSystem(A, xtrue)
+
+    def testComplexX0(self):
+        A = 4 * eye(self.n) + ones((self.n, self.n))
+        xtrue = transpose(arange(self.n, 0, -1))
+        b = aslinearoperator(A).matvec(xtrue)
+        x0 = zeros(self.n, dtype=complex)
+        x = lsmr(A, b, x0=x0)[0]
+        assert norm(x - xtrue) == pytest.approx(0, abs=1e-5)
+
+    def testComplexA(self):
+        A = 4 * eye(self.n) + 1j * ones((self.n, self.n))
+        xtrue = transpose(arange(self.n, 0, -1).astype(complex))
+        self.assertCompatibleSystem(A, xtrue)
+
+    def testComplexB(self):
+        A = 4 * eye(self.n) + ones((self.n, self.n))
+        xtrue = transpose(arange(self.n, 0, -1) * (1 + 1j))
+        b = aslinearoperator(A).matvec(xtrue)
+        x = lsmr(A, b)[0]
+        assert norm(x - xtrue) == pytest.approx(0, abs=1e-5)
+
+    def testColumnB(self):
+        A = eye(self.n)
+        b = ones((self.n, 1))
+        x = lsmr(A, b)[0]
+        assert norm(A.dot(x) - b.ravel()) == pytest.approx(0)
+
+    def testInitialization(self):
+        # Test that the default setting is not modified
+        x_ref, _, itn_ref, normr_ref, *_ = lsmr(G, b)
+        assert_allclose(norm(b - G@x_ref), normr_ref, atol=1e-6)
+
+        # Test passing zeros yields similar result
+        x0 = zeros(b.shape)
+        x = lsmr(G, b, x0=x0)[0]
+        assert_allclose(x, x_ref)
+
+        # Test warm-start with single iteration
+        x0 = lsmr(G, b, maxiter=1)[0]
+
+        x, _, itn, normr, *_ = lsmr(G, b, x0=x0)
+        assert_allclose(norm(b - G@x), normr, atol=1e-6)
+
+        # NOTE(gh-12139): This doesn't always converge to the same value as
+        # ref because error estimates will be slightly different when calculated
+        # from zeros vs x0 as a result only compare norm and itn (not x).
+
+        # x generally converges 1 iteration faster because it started at x0.
+        # itn == itn_ref means that lsmr(x0) took an extra iteration see above.
+        # -1 is technically possible but is rare (1 in 100000) so it's more
+        # likely to be an error elsewhere.
+        assert itn - itn_ref in (0, 1)
+
+        # If an extra iteration is performed normr may be 0, while normr_ref
+        # may be much larger.
+        assert normr < normr_ref * (1 + 1e-6)
+
+
+class TestLSMRReturns:
+    def setup_method(self):
+        self.n = 10
+        self.A = lowerBidiagonalMatrix(20, self.n)
+        self.xtrue = transpose(arange(self.n, 0, -1))
+        self.Afun = aslinearoperator(self.A)
+        self.b = self.Afun.matvec(self.xtrue)
+        self.x0 = ones(self.n)
+        self.x00 = self.x0.copy()
+        self.returnValues = lsmr(self.A, self.b)
+        self.returnValuesX0 = lsmr(self.A, self.b, x0=self.x0)
+
+    def test_unchanged_x0(self):
+        x, istop, itn, normr, normar, normA, condA, normx = self.returnValuesX0
+        assert_allclose(self.x00, self.x0)
+
+    def testNormr(self):
+        x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
+        assert norm(self.b - self.Afun.matvec(x)) == pytest.approx(normr)
+
+    def testNormar(self):
+        x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
+        assert (norm(self.Afun.rmatvec(self.b - self.Afun.matvec(x)))
+                == pytest.approx(normar))
+
+    def testNormx(self):
+        x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
+        assert norm(x) == pytest.approx(normx)
+
+
+def lowerBidiagonalMatrix(m, n):
+    # This is a simple example for testing LSMR.
+    # It uses the leading m*n submatrix from
+    # A = [ 1
+    #       1 2
+    #         2 3
+    #           3 4
+    #             ...
+    #               n ]
+    # suitably padded by zeros.
+    #
+    # 04 Jun 2010: First version for distribution with lsmr.py
+    if m <= n:
+        row = hstack((arange(m, dtype=int),
+                      arange(1, m, dtype=int)))
+        col = hstack((arange(m, dtype=int),
+                      arange(m-1, dtype=int)))
+        data = hstack((arange(1, m+1, dtype=float),
+                       arange(1,m, dtype=float)))
+        return coo_array((data, (row, col)), shape=(m,n))
+    else:
+        row = hstack((arange(n, dtype=int),
+                      arange(1, n+1, dtype=int)))
+        col = hstack((arange(n, dtype=int),
+                      arange(n, dtype=int)))
+        data = hstack((arange(1, n+1, dtype=float),
+                       arange(1,n+1, dtype=float)))
+        return coo_array((data,(row, col)), shape=(m,n))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsqr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsqr.py
new file mode 100644
index 0000000000000000000000000000000000000000..d77048af48a6b4495d23c9bc9a3b2d71466bade6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_lsqr.py
@@ -0,0 +1,120 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_equal, assert_equal
+import pytest
+import scipy.sparse
+import scipy.sparse.linalg
+from scipy.sparse.linalg import lsqr
+
+# Set up a test problem
+n = 35
+G = np.eye(n)
+normal = np.random.normal
+norm = np.linalg.norm
+
+for jj in range(5):
+    gg = normal(size=n)
+    hh = gg * gg.T
+    G += (hh + hh.T) * 0.5
+    G += normal(size=n) * normal(size=n)
+
+b = normal(size=n)
+
+# tolerance for atol/btol keywords of lsqr()
+tol = 2e-10
+# tolerances for testing the results of the lsqr() call with assert_allclose
+# These tolerances are a bit fragile - see discussion in gh-15301.
+atol_test = 4e-10
+rtol_test = 2e-8
+show = False
+maxit = None
+
+
+def test_lsqr_basic():
+    b_copy = b.copy()
+    xo, *_ = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit)
+    assert_array_equal(b_copy, b)
+
+    svx = np.linalg.solve(G, b)
+    assert_allclose(xo, svx, atol=atol_test, rtol=rtol_test)
+
+    # Now the same but with damp > 0.
+    # This is equivalent to solving the extended system:
+    # ( G      ) @ x = ( b )
+    # ( damp*I )       ( 0 )
+    damp = 1.5
+    xo, *_ = lsqr(
+        G, b, damp=damp, show=show, atol=tol, btol=tol, iter_lim=maxit)
+
+    Gext = np.r_[G, damp * np.eye(G.shape[1])]
+    bext = np.r_[b, np.zeros(G.shape[1])]
+    svx, *_ = np.linalg.lstsq(Gext, bext, rcond=None)
+    assert_allclose(xo, svx, atol=atol_test, rtol=rtol_test)
+
+
+def test_gh_2466():
+    row = np.array([0, 0])
+    col = np.array([0, 1])
+    val = np.array([1, -1])
+    A = scipy.sparse.coo_array((val, (row, col)), shape=(1, 2))
+    b = np.asarray([4])
+    lsqr(A, b)
+
+
+def test_well_conditioned_problems():
+    # Test that sparse the lsqr solver returns the right solution
+    # on various problems with different random seeds.
+    # This is a non-regression test for a potential ZeroDivisionError
+    # raised when computing the `test2` & `test3` convergence conditions.
+    n = 10
+    A_sparse = scipy.sparse.eye_array(n, n)
+    A_dense = A_sparse.toarray()
+
+    with np.errstate(invalid='raise'):
+        for seed in range(30):
+            rng = np.random.RandomState(seed + 10)
+            beta = rng.rand(n)
+            beta[beta == 0] = 0.00001  # ensure that all the betas are not null
+            b = A_sparse @ beta[:, np.newaxis]
+            output = lsqr(A_sparse, b, show=show)
+
+            # Check that the termination condition corresponds to an approximate
+            # solution to Ax = b
+            assert_equal(output[1], 1)
+            solution = output[0]
+
+            # Check that we recover the ground truth solution
+            assert_allclose(solution, beta)
+
+            # Sanity check: compare to the dense array solver
+            reference_solution = np.linalg.solve(A_dense, b).ravel()
+            assert_allclose(solution, reference_solution)
+
+
+def test_b_shapes():
+    # Test b being a scalar.
+    A = np.array([[1.0, 2.0]])
+    b = 3.0
+    x = lsqr(A, b)[0]
+    assert norm(A.dot(x) - b) == pytest.approx(0)
+
+    # Test b being a column vector.
+    A = np.eye(10)
+    b = np.ones((10, 1))
+    x = lsqr(A, b)[0]
+    assert norm(A.dot(x) - b.ravel()) == pytest.approx(0)
+
+
+def test_initialization():
+    # Test the default setting is the same as zeros
+    b_copy = b.copy()
+    x_ref = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit)
+    x0 = np.zeros(x_ref[0].shape)
+    x = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit, x0=x0)
+    assert_array_equal(b_copy, b)
+    assert_allclose(x_ref[0], x[0])
+
+    # Test warm-start with single iteration
+    x0 = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=1)[0]
+    x = lsqr(G, b, show=show, atol=tol, btol=tol, iter_lim=maxit, x0=x0)
+    assert_allclose(x_ref[0], x[0])
+    assert_array_equal(b_copy, b)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_minres.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_minres.py
new file mode 100644
index 0000000000000000000000000000000000000000..cae169e14f0306b195bca73ce86547391851aab6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_minres.py
@@ -0,0 +1,97 @@
+import numpy as np
+from numpy.linalg import norm
+from numpy.testing import assert_equal, assert_allclose, assert_
+from scipy.sparse.linalg._isolve import minres
+
+from pytest import raises as assert_raises
+
+
+def get_sample_problem():
+    # A random 10 x 10 symmetric matrix
+    rng = np.random.RandomState(1234)
+    matrix = rng.rand(10, 10)
+    matrix = matrix + matrix.T
+    # A random vector of length 10
+    vector = rng.rand(10)
+    return matrix, vector
+
+
+def test_singular():
+    A, b = get_sample_problem()
+    A[0, ] = 0
+    b[0] = 0
+    xp, info = minres(A, b)
+    assert_equal(info, 0)
+    assert norm(A @ xp - b) <= 1e-5 * norm(b)
+
+
+def test_x0_is_used_by():
+    A, b = get_sample_problem()
+    # Random x0 to feed minres
+    rng = np.random.RandomState(12345)
+    x0 = rng.rand(10)
+    trace = []
+
+    def trace_iterates(xk):
+        trace.append(xk)
+    minres(A, b, x0=x0, callback=trace_iterates)
+    trace_with_x0 = trace
+
+    trace = []
+    minres(A, b, callback=trace_iterates)
+    assert_(not np.array_equal(trace_with_x0[0], trace[0]))
+
+
+def test_shift():
+    A, b = get_sample_problem()
+    shift = 0.5
+    shifted_A = A - shift * np.eye(10)
+    x1, info1 = minres(A, b, shift=shift)
+    x2, info2 = minres(shifted_A, b)
+    assert_equal(info1, 0)
+    assert_allclose(x1, x2, rtol=1e-5)
+
+
+def test_asymmetric_fail():
+    """Asymmetric matrix should raise `ValueError` when check=True"""
+    A, b = get_sample_problem()
+    A[1, 2] = 1
+    A[2, 1] = 2
+    with assert_raises(ValueError):
+        xp, info = minres(A, b, check=True)
+
+
+def test_minres_non_default_x0():
+    rng = np.random.RandomState(1234)
+    rtol = 1e-6
+    a = rng.randn(5, 5)
+    a = np.dot(a, a.T)
+    b = rng.randn(5)
+    c = rng.randn(5)
+    x = minres(a, b, x0=c, rtol=rtol)[0]
+    assert norm(a @ x - b) <= rtol * norm(b)
+
+
+def test_minres_precond_non_default_x0():
+    rng = np.random.RandomState(12345)
+    rtol = 1e-6
+    a = rng.randn(5, 5)
+    a = np.dot(a, a.T)
+    b = rng.randn(5)
+    c = rng.randn(5)
+    m = rng.randn(5, 5)
+    m = np.dot(m, m.T)
+    x = minres(a, b, M=m, x0=c, rtol=rtol)[0]
+    assert norm(a @ x - b) <= rtol * norm(b)
+
+
+def test_minres_precond_exact_x0():
+    rng = np.random.RandomState(1234)
+    rtol = 1e-6
+    a = np.eye(10)
+    b = np.ones(10)
+    c = np.ones(10)
+    m = rng.randn(10, 10)
+    m = np.dot(m, m.T)
+    x = minres(a, b, M=m, x0=c, rtol=rtol)[0]
+    assert norm(a @ x - b) <= rtol * norm(b)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_utils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb62e2223d515288bd5aa6c5a70028279c4f6d30
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tests/test_utils.py
@@ -0,0 +1,9 @@
+import numpy as np
+from pytest import raises as assert_raises
+
+import scipy.sparse.linalg._isolve.utils as utils
+
+
+def test_make_system_bad_shape():
+    assert_raises(ValueError,
+                  utils.make_system, np.zeros((5,3)), None, np.zeros(4), np.zeros(4))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tfqmr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tfqmr.py
new file mode 100644
index 0000000000000000000000000000000000000000..efec0302d53f107d8ffb3fcfe82f65cfa37ada5f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/tfqmr.py
@@ -0,0 +1,179 @@
+import numpy as np
+from .iterative import _get_atol_rtol
+from .utils import make_system
+
+
+__all__ = ['tfqmr']
+
+
+def tfqmr(A, b, x0=None, *, rtol=1e-5, atol=0., maxiter=None, M=None,
+          callback=None, show=False):
+    """
+    Use Transpose-Free Quasi-Minimal Residual iteration to solve ``Ax = b``.
+
+    Parameters
+    ----------
+    A : {sparse array, ndarray, LinearOperator}
+        The real or complex N-by-N matrix of the linear system.
+        Alternatively, `A` can be a linear operator which can
+        produce ``Ax`` using, e.g.,
+        `scipy.sparse.linalg.LinearOperator`.
+    b : {ndarray}
+        Right hand side of the linear system. Has shape (N,) or (N,1).
+    x0 : {ndarray}
+        Starting guess for the solution.
+    rtol, atol : float, optional
+        Parameters for the convergence test. For convergence,
+        ``norm(b - A @ x) <= max(rtol*norm(b), atol)`` should be satisfied.
+        The default is ``rtol=1e-5``, the default for ``atol`` is ``0.0``.
+    maxiter : int, optional
+        Maximum number of iterations.  Iteration will stop after maxiter
+        steps even if the specified tolerance has not been achieved.
+        Default is ``min(10000, ndofs * 10)``, where ``ndofs = A.shape[0]``.
+    M : {sparse array, ndarray, LinearOperator}
+        Inverse of the preconditioner of A.  M should approximate the
+        inverse of A and be easy to solve for (see Notes).  Effective
+        preconditioning dramatically improves the rate of convergence,
+        which implies that fewer iterations are needed to reach a given
+        error tolerance.  By default, no preconditioner is used.
+    callback : function, optional
+        User-supplied function to call after each iteration.  It is called
+        as ``callback(xk)``, where ``xk`` is the current solution vector.
+    show : bool, optional
+        Specify ``show = True`` to show the convergence, ``show = False`` is
+        to close the output of the convergence.
+        Default is `False`.
+
+    Returns
+    -------
+    x : ndarray
+        The converged solution.
+    info : int
+        Provides convergence information:
+
+            - 0  : successful exit
+            - >0 : convergence to tolerance not achieved, number of iterations
+            - <0 : illegal input or breakdown
+
+    Notes
+    -----
+    The Transpose-Free QMR algorithm is derived from the CGS algorithm.
+    However, unlike CGS, the convergence curves for the TFQMR method is
+    smoothed by computing a quasi minimization of the residual norm. The
+    implementation supports left preconditioner, and the "residual norm"
+    to compute in convergence criterion is actually an upper bound on the
+    actual residual norm ``||b - Axk||``.
+
+    References
+    ----------
+    .. [1] R. W. Freund, A Transpose-Free Quasi-Minimal Residual Algorithm for
+           Non-Hermitian Linear Systems, SIAM J. Sci. Comput., 14(2), 470-482,
+           1993.
+    .. [2] Y. Saad, Iterative Methods for Sparse Linear Systems, 2nd edition,
+           SIAM, Philadelphia, 2003.
+    .. [3] C. T. Kelley, Iterative Methods for Linear and Nonlinear Equations,
+           number 16 in Frontiers in Applied Mathematics, SIAM, Philadelphia,
+           1995.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import tfqmr
+    >>> A = csc_array([[3, 2, 0], [1, -1, 0], [0, 5, 1]], dtype=float)
+    >>> b = np.array([2, 4, -1], dtype=float)
+    >>> x, exitCode = tfqmr(A, b, atol=0.0)
+    >>> print(exitCode)            # 0 indicates successful convergence
+    0
+    >>> np.allclose(A.dot(x), b)
+    True
+    """
+
+    # Check data type
+    dtype = A.dtype
+    if np.issubdtype(dtype, np.int64):
+        dtype = float
+        A = A.astype(dtype)
+    if np.issubdtype(b.dtype, np.int64):
+        b = b.astype(dtype)
+
+    A, M, x, b, postprocess = make_system(A, M, x0, b)
+
+    # Check if the R.H.S is a zero vector
+    if np.linalg.norm(b) == 0.:
+        x = b.copy()
+        return (postprocess(x), 0)
+
+    ndofs = A.shape[0]
+    if maxiter is None:
+        maxiter = min(10000, ndofs * 10)
+
+    if x0 is None:
+        r = b.copy()
+    else:
+        r = b - A.matvec(x)
+    u = r
+    w = r.copy()
+    # Take rstar as b - Ax0, that is rstar := r = b - Ax0 mathematically
+    rstar = r
+    v = M.matvec(A.matvec(r))
+    uhat = v
+    d = theta = eta = 0.
+    # at this point we know rstar == r, so rho is always real
+    rho = np.inner(rstar.conjugate(), r).real
+    rhoLast = rho
+    r0norm = np.sqrt(rho)
+    tau = r0norm
+    if r0norm == 0:
+        return (postprocess(x), 0)
+
+    # we call this to get the right atol and raise errors as necessary
+    atol, _ = _get_atol_rtol('tfqmr', r0norm, atol, rtol)
+
+    for iter in range(maxiter):
+        even = iter % 2 == 0
+        if (even):
+            vtrstar = np.inner(rstar.conjugate(), v)
+            # Check breakdown
+            if vtrstar == 0.:
+                return (postprocess(x), -1)
+            alpha = rho / vtrstar
+            uNext = u - alpha * v  # [1]-(5.6)
+        w -= alpha * uhat  # [1]-(5.8)
+        d = u + (theta**2 / alpha) * eta * d  # [1]-(5.5)
+        # [1]-(5.2)
+        theta = np.linalg.norm(w) / tau
+        c = np.sqrt(1. / (1 + theta**2))
+        tau *= theta * c
+        # Calculate step and direction [1]-(5.4)
+        eta = (c**2) * alpha
+        z = M.matvec(d)
+        x += eta * z
+
+        if callback is not None:
+            callback(x)
+
+        # Convergence criterion
+        if tau * np.sqrt(iter+1) < atol:
+            if (show):
+                print("TFQMR: Linear solve converged due to reach TOL "
+                      f"iterations {iter+1}")
+            return (postprocess(x), 0)
+
+        if (not even):
+            # [1]-(5.7)
+            rho = np.inner(rstar.conjugate(), w)
+            beta = rho / rhoLast
+            u = w + beta * u
+            v = beta * uhat + (beta**2) * v
+            uhat = M.matvec(A.matvec(u))
+            v += uhat
+        else:
+            uhat = M.matvec(A.matvec(uNext))
+            u = uNext
+            rhoLast = rho
+
+    if (show):
+        print("TFQMR: Linear solve not converged due to reach MAXIT "
+              f"iterations {iter+1}")
+    return (postprocess(x), maxiter)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/utils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..80f37fc1cf63fa0352fd93d62be758f87c065db5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/utils.py
@@ -0,0 +1,127 @@
+__docformat__ = "restructuredtext en"
+
+__all__ = []
+
+
+from numpy import asanyarray, asarray, array, zeros
+
+from scipy.sparse.linalg._interface import aslinearoperator, LinearOperator, \
+     IdentityOperator
+
+_coerce_rules = {('f','f'):'f', ('f','d'):'d', ('f','F'):'F',
+                 ('f','D'):'D', ('d','f'):'d', ('d','d'):'d',
+                 ('d','F'):'D', ('d','D'):'D', ('F','f'):'F',
+                 ('F','d'):'D', ('F','F'):'F', ('F','D'):'D',
+                 ('D','f'):'D', ('D','d'):'D', ('D','F'):'D',
+                 ('D','D'):'D'}
+
+
+def coerce(x,y):
+    if x not in 'fdFD':
+        x = 'd'
+    if y not in 'fdFD':
+        y = 'd'
+    return _coerce_rules[x,y]
+
+
+def id(x):
+    return x
+
+
+def make_system(A, M, x0, b):
+    """Make a linear system Ax=b
+
+    Parameters
+    ----------
+    A : LinearOperator
+        sparse or dense matrix (or any valid input to aslinearoperator)
+    M : {LinearOperator, Nones}
+        preconditioner
+        sparse or dense matrix (or any valid input to aslinearoperator)
+    x0 : {array_like, str, None}
+        initial guess to iterative method.
+        ``x0 = 'Mb'`` means using the nonzero initial guess ``M @ b``.
+        Default is `None`, which means using the zero initial guess.
+    b : array_like
+        right hand side
+
+    Returns
+    -------
+    (A, M, x, b, postprocess)
+        A : LinearOperator
+            matrix of the linear system
+        M : LinearOperator
+            preconditioner
+        x : rank 1 ndarray
+            initial guess
+        b : rank 1 ndarray
+            right hand side
+        postprocess : function
+            converts the solution vector to the appropriate
+            type and dimensions (e.g. (N,1) matrix)
+
+    """
+    A_ = A
+    A = aslinearoperator(A)
+
+    if A.shape[0] != A.shape[1]:
+        raise ValueError(f'expected square matrix, but got shape={(A.shape,)}')
+
+    N = A.shape[0]
+
+    b = asanyarray(b)
+
+    if not (b.shape == (N,1) or b.shape == (N,)):
+        raise ValueError(f'shapes of A {A.shape} and b {b.shape} are '
+                         'incompatible')
+
+    if b.dtype.char not in 'fdFD':
+        b = b.astype('d')  # upcast non-FP types to double
+
+    def postprocess(x):
+        return x
+
+    if hasattr(A,'dtype'):
+        xtype = A.dtype.char
+    else:
+        xtype = A.matvec(b).dtype.char
+    xtype = coerce(xtype, b.dtype.char)
+
+    b = asarray(b,dtype=xtype)  # make b the same type as x
+    b = b.ravel()
+
+    # process preconditioner
+    if M is None:
+        if hasattr(A_,'psolve'):
+            psolve = A_.psolve
+        else:
+            psolve = id
+        if hasattr(A_,'rpsolve'):
+            rpsolve = A_.rpsolve
+        else:
+            rpsolve = id
+        if psolve is id and rpsolve is id:
+            M = IdentityOperator(shape=A.shape, dtype=A.dtype)
+        else:
+            M = LinearOperator(A.shape, matvec=psolve, rmatvec=rpsolve,
+                               dtype=A.dtype)
+    else:
+        M = aslinearoperator(M)
+        if A.shape != M.shape:
+            raise ValueError('matrix and preconditioner have different shapes')
+
+    # set initial guess
+    if x0 is None:
+        x = zeros(N, dtype=xtype)
+    elif isinstance(x0, str):
+        if x0 == 'Mb':  # use nonzero initial guess ``M @ b``
+            bCopy = b.copy()
+            x = M.matvec(bCopy)
+    else:
+        x = array(x0, dtype=xtype)
+        if not (x.shape == (N, 1) or x.shape == (N,)):
+            raise ValueError(f'shapes of A {A.shape} and '
+                             f'x0 {x.shape} are incompatible')
+        x = x.ravel()
+
+    return A, M, x, b, postprocess
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_matfuncs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dff48df52d8b95eb12c64c0117ac57101d9f031
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_matfuncs.py
@@ -0,0 +1,940 @@
+"""
+Sparse matrix functions
+"""
+
+#
+# Authors: Travis Oliphant, March 2002
+#          Anthony Scopatz, August 2012 (Sparse Updates)
+#          Jake Vanderplas, August 2012 (Sparse Updates)
+#
+
+__all__ = ['expm', 'inv', 'matrix_power']
+
+import numpy as np
+from scipy.linalg._basic import solve, solve_triangular
+
+from scipy.sparse._base import issparse
+from scipy.sparse.linalg import spsolve
+from scipy.sparse._sputils import is_pydata_spmatrix, isintlike
+
+import scipy.sparse
+import scipy.sparse.linalg
+from scipy.sparse.linalg._interface import LinearOperator
+from scipy.sparse._construct import eye_array
+
+from ._expm_multiply import _ident_like, _exact_1_norm as _onenorm
+
+
+UPPER_TRIANGULAR = 'upper_triangular'
+
+
+def inv(A):
+    """
+    Compute the inverse of a sparse arrays
+
+    Parameters
+    ----------
+    A : (M, M) sparse arrays
+        square matrix to be inverted
+
+    Returns
+    -------
+    Ainv : (M, M) sparse arrays
+        inverse of `A`
+
+    Notes
+    -----
+    This computes the sparse inverse of `A`. If the inverse of `A` is expected
+    to be non-sparse, it will likely be faster to convert `A` to dense and use
+    `scipy.linalg.inv`.
+
+    Examples
+    --------
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import inv
+    >>> A = csc_array([[1., 0.], [1., 2.]])
+    >>> Ainv = inv(A)
+    >>> Ainv
+    
+    >>> A.dot(Ainv)
+    
+    >>> A.dot(Ainv).toarray()
+    array([[ 1.,  0.],
+           [ 0.,  1.]])
+
+    .. versionadded:: 0.12.0
+
+    """
+    # Check input
+    if not (issparse(A) or is_pydata_spmatrix(A)):
+        raise TypeError('Input must be a sparse arrays')
+
+    # Use sparse direct solver to solve "AX = I" accurately
+    I = _ident_like(A)
+    Ainv = spsolve(A, I)
+    return Ainv
+
+
+def _onenorm_matrix_power_nnm(A, p):
+    """
+    Compute the 1-norm of a non-negative integer power of a non-negative matrix.
+
+    Parameters
+    ----------
+    A : a square ndarray or matrix or sparse arrays
+        Input matrix with non-negative entries.
+    p : non-negative integer
+        The power to which the matrix is to be raised.
+
+    Returns
+    -------
+    out : float
+        The 1-norm of the matrix power p of A.
+
+    """
+    # Check input
+    if int(p) != p or p < 0:
+        raise ValueError('expected non-negative integer p')
+    p = int(p)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected A to be like a square matrix')
+
+    # Explicitly make a column vector so that this works when A is a
+    # numpy matrix (in addition to ndarray and sparse arrays).
+    v = np.ones((A.shape[0], 1), dtype=float)
+    M = A.T
+    for i in range(p):
+        v = M.dot(v)
+    return np.max(v)
+
+
+def _is_upper_triangular(A):
+    # This function could possibly be of wider interest.
+    if issparse(A):
+        lower_part = scipy.sparse.tril(A, -1)
+        # Check structural upper triangularity,
+        # then coincidental upper triangularity if needed.
+        return lower_part.nnz == 0 or lower_part.count_nonzero() == 0
+    elif is_pydata_spmatrix(A):
+        import sparse
+        lower_part = sparse.tril(A, -1)
+        return lower_part.nnz == 0
+    else:
+        return not np.tril(A, -1).any()
+
+
+def _smart_matrix_product(A, B, alpha=None, structure=None):
+    """
+    A matrix product that knows about sparse and structured matrices.
+
+    Parameters
+    ----------
+    A : 2d ndarray
+        First matrix.
+    B : 2d ndarray
+        Second matrix.
+    alpha : float
+        The matrix product will be scaled by this constant.
+    structure : str, optional
+        A string describing the structure of both matrices `A` and `B`.
+        Only `upper_triangular` is currently supported.
+
+    Returns
+    -------
+    M : 2d ndarray
+        Matrix product of A and B.
+
+    """
+    if len(A.shape) != 2:
+        raise ValueError('expected A to be a rectangular matrix')
+    if len(B.shape) != 2:
+        raise ValueError('expected B to be a rectangular matrix')
+    f = None
+    if structure == UPPER_TRIANGULAR:
+        if (not issparse(A) and not issparse(B)
+                and not is_pydata_spmatrix(A) and not is_pydata_spmatrix(B)):
+            f, = scipy.linalg.get_blas_funcs(('trmm',), (A, B))
+    if f is not None:
+        if alpha is None:
+            alpha = 1.
+        out = f(alpha, A, B)
+    else:
+        if alpha is None:
+            out = A.dot(B)
+        else:
+            out = alpha * A.dot(B)
+    return out
+
+
+class MatrixPowerOperator(LinearOperator):
+
+    def __init__(self, A, p, structure=None):
+        if A.ndim != 2 or A.shape[0] != A.shape[1]:
+            raise ValueError('expected A to be like a square matrix')
+        if p < 0:
+            raise ValueError('expected p to be a non-negative integer')
+        self._A = A
+        self._p = p
+        self._structure = structure
+        self.dtype = A.dtype
+        self.ndim = A.ndim
+        self.shape = A.shape
+
+    def _matvec(self, x):
+        for i in range(self._p):
+            x = self._A.dot(x)
+        return x
+
+    def _rmatvec(self, x):
+        A_T = self._A.T
+        x = x.ravel()
+        for i in range(self._p):
+            x = A_T.dot(x)
+        return x
+
+    def _matmat(self, X):
+        for i in range(self._p):
+            X = _smart_matrix_product(self._A, X, structure=self._structure)
+        return X
+
+    @property
+    def T(self):
+        return MatrixPowerOperator(self._A.T, self._p)
+
+
+class ProductOperator(LinearOperator):
+    """
+    For now, this is limited to products of multiple square matrices.
+    """
+
+    def __init__(self, *args, **kwargs):
+        self._structure = kwargs.get('structure', None)
+        for A in args:
+            if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+                raise ValueError(
+                        'For now, the ProductOperator implementation is '
+                        'limited to the product of multiple square matrices.')
+        if args:
+            n = args[0].shape[0]
+            for A in args:
+                for d in A.shape:
+                    if d != n:
+                        raise ValueError(
+                                'The square matrices of the ProductOperator '
+                                'must all have the same shape.')
+            self.shape = (n, n)
+            self.ndim = len(self.shape)
+        self.dtype = np.result_type(*[x.dtype for x in args])
+        self._operator_sequence = args
+
+    def _matvec(self, x):
+        for A in reversed(self._operator_sequence):
+            x = A.dot(x)
+        return x
+
+    def _rmatvec(self, x):
+        x = x.ravel()
+        for A in self._operator_sequence:
+            x = A.T.dot(x)
+        return x
+
+    def _matmat(self, X):
+        for A in reversed(self._operator_sequence):
+            X = _smart_matrix_product(A, X, structure=self._structure)
+        return X
+
+    @property
+    def T(self):
+        T_args = [A.T for A in reversed(self._operator_sequence)]
+        return ProductOperator(*T_args)
+
+
+def _onenormest_matrix_power(A, p,
+        t=2, itmax=5, compute_v=False, compute_w=False, structure=None):
+    """
+    Efficiently estimate the 1-norm of A^p.
+
+    Parameters
+    ----------
+    A : ndarray
+        Matrix whose 1-norm of a power is to be computed.
+    p : int
+        Non-negative integer power.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+        Larger values take longer and use more memory
+        but give more accurate output.
+    itmax : int, optional
+        Use at most this many iterations.
+    compute_v : bool, optional
+        Request a norm-maximizing linear operator input vector if True.
+    compute_w : bool, optional
+        Request a norm-maximizing linear operator output vector if True.
+
+    Returns
+    -------
+    est : float
+        An underestimate of the 1-norm of the sparse arrays.
+    v : ndarray, optional
+        The vector such that ||Av||_1 == est*||v||_1.
+        It can be thought of as an input to the linear operator
+        that gives an output with particularly large norm.
+    w : ndarray, optional
+        The vector Av which has relatively large 1-norm.
+        It can be thought of as an output of the linear operator
+        that is relatively large in norm compared to the input.
+
+    """
+    return scipy.sparse.linalg.onenormest(
+            MatrixPowerOperator(A, p, structure=structure))
+
+
+def _onenormest_product(operator_seq,
+        t=2, itmax=5, compute_v=False, compute_w=False, structure=None):
+    """
+    Efficiently estimate the 1-norm of the matrix product of the args.
+
+    Parameters
+    ----------
+    operator_seq : linear operator sequence
+        Matrices whose 1-norm of product is to be computed.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+        Larger values take longer and use more memory
+        but give more accurate output.
+    itmax : int, optional
+        Use at most this many iterations.
+    compute_v : bool, optional
+        Request a norm-maximizing linear operator input vector if True.
+    compute_w : bool, optional
+        Request a norm-maximizing linear operator output vector if True.
+    structure : str, optional
+        A string describing the structure of all operators.
+        Only `upper_triangular` is currently supported.
+
+    Returns
+    -------
+    est : float
+        An underestimate of the 1-norm of the sparse arrays.
+    v : ndarray, optional
+        The vector such that ||Av||_1 == est*||v||_1.
+        It can be thought of as an input to the linear operator
+        that gives an output with particularly large norm.
+    w : ndarray, optional
+        The vector Av which has relatively large 1-norm.
+        It can be thought of as an output of the linear operator
+        that is relatively large in norm compared to the input.
+
+    """
+    return scipy.sparse.linalg.onenormest(
+            ProductOperator(*operator_seq, structure=structure))
+
+
+class _ExpmPadeHelper:
+    """
+    Help lazily evaluate a matrix exponential.
+
+    The idea is to not do more work than we need for high expm precision,
+    so we lazily compute matrix powers and store or precompute
+    other properties of the matrix.
+
+    """
+
+    def __init__(self, A, structure=None, use_exact_onenorm=False):
+        """
+        Initialize the object.
+
+        Parameters
+        ----------
+        A : a dense or sparse square numpy matrix or ndarray
+            The matrix to be exponentiated.
+        structure : str, optional
+            A string describing the structure of matrix `A`.
+            Only `upper_triangular` is currently supported.
+        use_exact_onenorm : bool, optional
+            If True then only the exact one-norm of matrix powers and products
+            will be used. Otherwise, the one-norm of powers and products
+            may initially be estimated.
+        """
+        self.A = A
+        self._A2 = None
+        self._A4 = None
+        self._A6 = None
+        self._A8 = None
+        self._A10 = None
+        self._d4_exact = None
+        self._d6_exact = None
+        self._d8_exact = None
+        self._d10_exact = None
+        self._d4_approx = None
+        self._d6_approx = None
+        self._d8_approx = None
+        self._d10_approx = None
+        self.ident = _ident_like(A)
+        self.structure = structure
+        self.use_exact_onenorm = use_exact_onenorm
+
+    @property
+    def A2(self):
+        if self._A2 is None:
+            self._A2 = _smart_matrix_product(
+                    self.A, self.A, structure=self.structure)
+        return self._A2
+
+    @property
+    def A4(self):
+        if self._A4 is None:
+            self._A4 = _smart_matrix_product(
+                    self.A2, self.A2, structure=self.structure)
+        return self._A4
+
+    @property
+    def A6(self):
+        if self._A6 is None:
+            self._A6 = _smart_matrix_product(
+                    self.A4, self.A2, structure=self.structure)
+        return self._A6
+
+    @property
+    def A8(self):
+        if self._A8 is None:
+            self._A8 = _smart_matrix_product(
+                    self.A6, self.A2, structure=self.structure)
+        return self._A8
+
+    @property
+    def A10(self):
+        if self._A10 is None:
+            self._A10 = _smart_matrix_product(
+                    self.A4, self.A6, structure=self.structure)
+        return self._A10
+
+    @property
+    def d4_tight(self):
+        if self._d4_exact is None:
+            self._d4_exact = _onenorm(self.A4)**(1/4.)
+        return self._d4_exact
+
+    @property
+    def d6_tight(self):
+        if self._d6_exact is None:
+            self._d6_exact = _onenorm(self.A6)**(1/6.)
+        return self._d6_exact
+
+    @property
+    def d8_tight(self):
+        if self._d8_exact is None:
+            self._d8_exact = _onenorm(self.A8)**(1/8.)
+        return self._d8_exact
+
+    @property
+    def d10_tight(self):
+        if self._d10_exact is None:
+            self._d10_exact = _onenorm(self.A10)**(1/10.)
+        return self._d10_exact
+
+    @property
+    def d4_loose(self):
+        if self.use_exact_onenorm:
+            return self.d4_tight
+        if self._d4_exact is not None:
+            return self._d4_exact
+        else:
+            if self._d4_approx is None:
+                self._d4_approx = _onenormest_matrix_power(self.A2, 2,
+                        structure=self.structure)**(1/4.)
+            return self._d4_approx
+
+    @property
+    def d6_loose(self):
+        if self.use_exact_onenorm:
+            return self.d6_tight
+        if self._d6_exact is not None:
+            return self._d6_exact
+        else:
+            if self._d6_approx is None:
+                self._d6_approx = _onenormest_matrix_power(self.A2, 3,
+                        structure=self.structure)**(1/6.)
+            return self._d6_approx
+
+    @property
+    def d8_loose(self):
+        if self.use_exact_onenorm:
+            return self.d8_tight
+        if self._d8_exact is not None:
+            return self._d8_exact
+        else:
+            if self._d8_approx is None:
+                self._d8_approx = _onenormest_matrix_power(self.A4, 2,
+                        structure=self.structure)**(1/8.)
+            return self._d8_approx
+
+    @property
+    def d10_loose(self):
+        if self.use_exact_onenorm:
+            return self.d10_tight
+        if self._d10_exact is not None:
+            return self._d10_exact
+        else:
+            if self._d10_approx is None:
+                self._d10_approx = _onenormest_product((self.A4, self.A6),
+                        structure=self.structure)**(1/10.)
+            return self._d10_approx
+
+    def pade3(self):
+        b = (120., 60., 12., 1.)
+        U = _smart_matrix_product(self.A,
+                b[3]*self.A2 + b[1]*self.ident,
+                structure=self.structure)
+        V = b[2]*self.A2 + b[0]*self.ident
+        return U, V
+
+    def pade5(self):
+        b = (30240., 15120., 3360., 420., 30., 1.)
+        U = _smart_matrix_product(self.A,
+                b[5]*self.A4 + b[3]*self.A2 + b[1]*self.ident,
+                structure=self.structure)
+        V = b[4]*self.A4 + b[2]*self.A2 + b[0]*self.ident
+        return U, V
+
+    def pade7(self):
+        b = (17297280., 8648640., 1995840., 277200., 25200., 1512., 56., 1.)
+        U = _smart_matrix_product(self.A,
+                b[7]*self.A6 + b[5]*self.A4 + b[3]*self.A2 + b[1]*self.ident,
+                structure=self.structure)
+        V = b[6]*self.A6 + b[4]*self.A4 + b[2]*self.A2 + b[0]*self.ident
+        return U, V
+
+    def pade9(self):
+        b = (17643225600., 8821612800., 2075673600., 302702400., 30270240.,
+                2162160., 110880., 3960., 90., 1.)
+        U = _smart_matrix_product(self.A,
+                (b[9]*self.A8 + b[7]*self.A6 + b[5]*self.A4 +
+                    b[3]*self.A2 + b[1]*self.ident),
+                structure=self.structure)
+        V = (b[8]*self.A8 + b[6]*self.A6 + b[4]*self.A4 +
+                b[2]*self.A2 + b[0]*self.ident)
+        return U, V
+
+    def pade13_scaled(self, s):
+        b = (64764752532480000., 32382376266240000., 7771770303897600.,
+                1187353796428800., 129060195264000., 10559470521600.,
+                670442572800., 33522128640., 1323241920., 40840800., 960960.,
+                16380., 182., 1.)
+        B = self.A * 2**-s
+        B2 = self.A2 * 2**(-2*s)
+        B4 = self.A4 * 2**(-4*s)
+        B6 = self.A6 * 2**(-6*s)
+        U2 = _smart_matrix_product(B6,
+                b[13]*B6 + b[11]*B4 + b[9]*B2,
+                structure=self.structure)
+        U = _smart_matrix_product(B,
+                (U2 + b[7]*B6 + b[5]*B4 +
+                    b[3]*B2 + b[1]*self.ident),
+                structure=self.structure)
+        V2 = _smart_matrix_product(B6,
+                b[12]*B6 + b[10]*B4 + b[8]*B2,
+                structure=self.structure)
+        V = V2 + b[6]*B6 + b[4]*B4 + b[2]*B2 + b[0]*self.ident
+        return U, V
+
+
+def expm(A):
+    """
+    Compute the matrix exponential using Pade approximation.
+
+    Parameters
+    ----------
+    A : (M,M) array_like or sparse array
+        2D Array or Matrix (sparse or dense) to be exponentiated
+
+    Returns
+    -------
+    expA : (M,M) ndarray
+        Matrix exponential of `A`
+
+    Notes
+    -----
+    This is algorithm (6.1) which is a simplification of algorithm (5.1).
+
+    .. versionadded:: 0.12.0
+
+    References
+    ----------
+    .. [1] Awad H. Al-Mohy and Nicholas J. Higham (2009)
+           "A New Scaling and Squaring Algorithm for the Matrix Exponential."
+           SIAM Journal on Matrix Analysis and Applications.
+           31 (3). pp. 970-989. ISSN 1095-7162
+
+    Examples
+    --------
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import expm
+    >>> A = csc_array([[1, 0, 0], [0, 2, 0], [0, 0, 3]])
+    >>> A.toarray()
+    array([[1, 0, 0],
+           [0, 2, 0],
+           [0, 0, 3]], dtype=int64)
+    >>> Aexp = expm(A)
+    >>> Aexp
+    
+    >>> Aexp.toarray()
+    array([[  2.71828183,   0.        ,   0.        ],
+           [  0.        ,   7.3890561 ,   0.        ],
+           [  0.        ,   0.        ,  20.08553692]])
+    """
+    return _expm(A, use_exact_onenorm='auto')
+
+
+def _expm(A, use_exact_onenorm):
+    # Core of expm, separated to allow testing exact and approximate
+    # algorithms.
+
+    # Avoid indiscriminate asarray() to allow sparse or other strange arrays.
+    if isinstance(A, (list, tuple, np.matrix)):
+        A = np.asarray(A)
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected a square matrix')
+
+    # gracefully handle size-0 input,
+    # carefully handling sparse scenario
+    if A.shape == (0, 0):
+        out = np.zeros([0, 0], dtype=A.dtype)
+        if issparse(A) or is_pydata_spmatrix(A):
+            return A.__class__(out)
+        return out
+
+    # Trivial case
+    if A.shape == (1, 1):
+        out = [[np.exp(A[0, 0])]]
+
+        # Avoid indiscriminate casting to ndarray to
+        # allow for sparse or other strange arrays
+        if issparse(A) or is_pydata_spmatrix(A):
+            return A.__class__(out)
+
+        return np.array(out)
+
+    # Ensure input is of float type, to avoid integer overflows etc.
+    if ((isinstance(A, np.ndarray) or issparse(A) or is_pydata_spmatrix(A))
+            and not np.issubdtype(A.dtype, np.inexact)):
+        A = A.astype(float)
+
+    # Detect upper triangularity.
+    structure = UPPER_TRIANGULAR if _is_upper_triangular(A) else None
+
+    if use_exact_onenorm == "auto":
+        # Hardcode a matrix order threshold for exact vs. estimated one-norms.
+        use_exact_onenorm = A.shape[0] < 200
+
+    # Track functions of A to help compute the matrix exponential.
+    h = _ExpmPadeHelper(
+            A, structure=structure, use_exact_onenorm=use_exact_onenorm)
+
+    # Try Pade order 3.
+    eta_1 = max(h.d4_loose, h.d6_loose)
+    if eta_1 < 1.495585217958292e-002 and _ell(h.A, 3) == 0:
+        U, V = h.pade3()
+        return _solve_P_Q(U, V, structure=structure)
+
+    # Try Pade order 5.
+    eta_2 = max(h.d4_tight, h.d6_loose)
+    if eta_2 < 2.539398330063230e-001 and _ell(h.A, 5) == 0:
+        U, V = h.pade5()
+        return _solve_P_Q(U, V, structure=structure)
+
+    # Try Pade orders 7 and 9.
+    eta_3 = max(h.d6_tight, h.d8_loose)
+    if eta_3 < 9.504178996162932e-001 and _ell(h.A, 7) == 0:
+        U, V = h.pade7()
+        return _solve_P_Q(U, V, structure=structure)
+    if eta_3 < 2.097847961257068e+000 and _ell(h.A, 9) == 0:
+        U, V = h.pade9()
+        return _solve_P_Q(U, V, structure=structure)
+
+    # Use Pade order 13.
+    eta_4 = max(h.d8_loose, h.d10_loose)
+    eta_5 = min(eta_3, eta_4)
+    theta_13 = 4.25
+
+    # Choose smallest s>=0 such that 2**(-s) eta_5 <= theta_13
+    if eta_5 == 0:
+        # Nilpotent special case
+        s = 0
+    else:
+        s = max(int(np.ceil(np.log2(eta_5 / theta_13))), 0)
+    s = s + _ell(2**-s * h.A, 13)
+    U, V = h.pade13_scaled(s)
+    X = _solve_P_Q(U, V, structure=structure)
+    if structure == UPPER_TRIANGULAR:
+        # Invoke Code Fragment 2.1.
+        X = _fragment_2_1(X, h.A, s)
+    else:
+        # X = r_13(A)^(2^s) by repeated squaring.
+        for i in range(s):
+            X = X.dot(X)
+    return X
+
+
+def _solve_P_Q(U, V, structure=None):
+    """
+    A helper function for expm_2009.
+
+    Parameters
+    ----------
+    U : ndarray
+        Pade numerator.
+    V : ndarray
+        Pade denominator.
+    structure : str, optional
+        A string describing the structure of both matrices `U` and `V`.
+        Only `upper_triangular` is currently supported.
+
+    Notes
+    -----
+    The `structure` argument is inspired by similar args
+    for theano and cvxopt functions.
+
+    """
+    P = U + V
+    Q = -U + V
+    if issparse(U) or is_pydata_spmatrix(U):
+        return spsolve(Q, P)
+    elif structure is None:
+        return solve(Q, P)
+    elif structure == UPPER_TRIANGULAR:
+        return solve_triangular(Q, P)
+    else:
+        raise ValueError('unsupported matrix structure: ' + str(structure))
+
+
+def _exp_sinch(a, x):
+    """
+    Stably evaluate exp(a)*sinh(x)/x
+
+    Notes
+    -----
+    The strategy of falling back to a sixth order Taylor expansion
+    was suggested by the Spallation Neutron Source docs
+    which was found on the internet by google search.
+    http://www.ornl.gov/~t6p/resources/xal/javadoc/gov/sns/tools/math/ElementaryFunction.html
+    The details of the cutoff point and the Horner-like evaluation
+    was picked without reference to anything in particular.
+
+    Note that sinch is not currently implemented in scipy.special,
+    whereas the "engineer's" definition of sinc is implemented.
+    The implementation of sinc involves a scaling factor of pi
+    that distinguishes it from the "mathematician's" version of sinc.
+
+    """
+
+    # If x is small then use sixth order Taylor expansion.
+    # How small is small? I am using the point where the relative error
+    # of the approximation is less than 1e-14.
+    # If x is large then directly evaluate sinh(x) / x.
+    if abs(x) < 0.0135:
+        x2 = x*x
+        return np.exp(a) * (1 + (x2/6.)*(1 + (x2/20.)*(1 + (x2/42.))))
+    else:
+        return (np.exp(a + x) - np.exp(a - x)) / (2*x)
+
+
+def _eq_10_42(lam_1, lam_2, t_12):
+    """
+    Equation (10.42) of Functions of Matrices: Theory and Computation.
+
+    Notes
+    -----
+    This is a helper function for _fragment_2_1 of expm_2009.
+    Equation (10.42) is on page 251 in the section on Schur algorithms.
+    In particular, section 10.4.3 explains the Schur-Parlett algorithm.
+    expm([[lam_1, t_12], [0, lam_1])
+    =
+    [[exp(lam_1), t_12*exp((lam_1 + lam_2)/2)*sinch((lam_1 - lam_2)/2)],
+    [0, exp(lam_2)]
+    """
+
+    # The plain formula t_12 * (exp(lam_2) - exp(lam_2)) / (lam_2 - lam_1)
+    # apparently suffers from cancellation, according to Higham's textbook.
+    # A nice implementation of sinch, defined as sinh(x)/x,
+    # will apparently work around the cancellation.
+    a = 0.5 * (lam_1 + lam_2)
+    b = 0.5 * (lam_1 - lam_2)
+    return t_12 * _exp_sinch(a, b)
+
+
+def _fragment_2_1(X, T, s):
+    """
+    A helper function for expm_2009.
+
+    Notes
+    -----
+    The argument X is modified in-place, but this modification is not the same
+    as the returned value of the function.
+    This function also takes pains to do things in ways that are compatible
+    with sparse arrays, for example by avoiding fancy indexing
+    and by using methods of the matrices whenever possible instead of
+    using functions of the numpy or scipy libraries themselves.
+
+    """
+    # Form X = r_m(2^-s T)
+    # Replace diag(X) by exp(2^-s diag(T)).
+    n = X.shape[0]
+    diag_T = np.ravel(T.diagonal().copy())
+
+    # Replace diag(X) by exp(2^-s diag(T)).
+    scale = 2 ** -s
+    exp_diag = np.exp(scale * diag_T)
+    for k in range(n):
+        X[k, k] = exp_diag[k]
+
+    for i in range(s-1, -1, -1):
+        X = X.dot(X)
+
+        # Replace diag(X) by exp(2^-i diag(T)).
+        scale = 2 ** -i
+        exp_diag = np.exp(scale * diag_T)
+        for k in range(n):
+            X[k, k] = exp_diag[k]
+
+        # Replace (first) superdiagonal of X by explicit formula
+        # for superdiagonal of exp(2^-i T) from Eq (10.42) of
+        # the author's 2008 textbook
+        # Functions of Matrices: Theory and Computation.
+        for k in range(n-1):
+            lam_1 = scale * diag_T[k]
+            lam_2 = scale * diag_T[k+1]
+            t_12 = scale * T[k, k+1]
+            value = _eq_10_42(lam_1, lam_2, t_12)
+            X[k, k+1] = value
+
+    # Return the updated X matrix.
+    return X
+
+
+def _ell(A, m):
+    """
+    A helper function for expm_2009.
+
+    Parameters
+    ----------
+    A : linear operator
+        A linear operator whose norm of power we care about.
+    m : int
+        The power of the linear operator
+
+    Returns
+    -------
+    value : int
+        A value related to a bound.
+
+    """
+    if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
+        raise ValueError('expected A to be like a square matrix')
+
+    # The c_i are explained in (2.2) and (2.6) of the 2005 expm paper.
+    # They are coefficients of terms of a generating function series expansion.
+    c_i = {3: 100800.,
+           5: 10059033600.,
+           7: 4487938430976000.,
+           9: 5914384781877411840000.,
+           13: 113250775606021113483283660800000000.
+           }
+    abs_c_recip = c_i[m]
+
+    # This is explained after Eq. (1.2) of the 2009 expm paper.
+    # It is the "unit roundoff" of IEEE double precision arithmetic.
+    u = 2**-53
+
+    # Compute the one-norm of matrix power p of abs(A).
+    A_abs_onenorm = _onenorm_matrix_power_nnm(abs(A), 2*m + 1)
+
+    # Treat zero norm as a special case.
+    if not A_abs_onenorm:
+        return 0
+
+    alpha = A_abs_onenorm / (_onenorm(A) * abs_c_recip)
+    log2_alpha_div_u = np.log2(alpha/u)
+    value = int(np.ceil(log2_alpha_div_u / (2 * m)))
+    return max(value, 0)
+
+def matrix_power(A, power):
+    """
+    Raise a square matrix to the integer power, `power`.
+
+    For non-negative integers, ``A**power`` is computed using repeated
+    matrix multiplications. Negative integers are not supported. 
+
+    Parameters
+    ----------
+    A : (M, M) square sparse array or matrix
+        sparse array that will be raised to power `power`
+    power : int
+        Exponent used to raise sparse array `A`
+
+    Returns
+    -------
+    A**power : (M, M) sparse array or matrix
+        The output matrix will be the same shape as A, and will preserve
+        the class of A, but the format of the output may be changed.
+    
+    Notes
+    -----
+    This uses a recursive implementation of the matrix power. For computing
+    the matrix power using a reasonably large `power`, this may be less efficient
+    than computing the product directly, using A @ A @ ... @ A.
+    This is contingent upon the number of nonzero entries in the matrix. 
+
+    .. versionadded:: 1.12.0
+
+    Examples
+    --------
+    >>> from scipy import sparse
+    >>> A = sparse.csc_array([[0,1,0],[1,0,1],[0,1,0]])
+    >>> A.todense()
+    array([[0, 1, 0],
+           [1, 0, 1],
+           [0, 1, 0]])
+    >>> (A @ A).todense()
+    array([[1, 0, 1],
+           [0, 2, 0],
+           [1, 0, 1]])
+    >>> A2 = sparse.linalg.matrix_power(A, 2)
+    >>> A2.todense()
+    array([[1, 0, 1],
+           [0, 2, 0],
+           [1, 0, 1]])
+    >>> A4 = sparse.linalg.matrix_power(A, 4)
+    >>> A4.todense()
+    array([[2, 0, 2],
+           [0, 4, 0],
+           [2, 0, 2]])
+
+    """
+    M, N = A.shape
+    if M != N:
+        raise TypeError('sparse matrix is not square')
+
+    if isintlike(power):
+        power = int(power)
+        if power < 0:
+            raise ValueError('exponent must be >= 0')
+
+        if power == 0:
+            return eye_array(M, dtype=A.dtype)
+
+        if power == 1:
+            return A.copy()
+
+        tmp = matrix_power(A, power // 2)
+        if power % 2:
+            return A @ tmp @ tmp
+        else:
+            return tmp @ tmp
+    else:
+        raise ValueError("exponent must be an integer")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_onenormest.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_onenormest.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9e806ab6fbd5a2910de823a1046bce225d60a13
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_onenormest.py
@@ -0,0 +1,467 @@
+"""Sparse block 1-norm estimator.
+"""
+
+import numpy as np
+from scipy.sparse.linalg import aslinearoperator
+
+
+__all__ = ['onenormest']
+
+
+def onenormest(A, t=2, itmax=5, compute_v=False, compute_w=False):
+    """
+    Compute a lower bound of the 1-norm of a sparse array.
+
+    Parameters
+    ----------
+    A : ndarray or other linear operator
+        A linear operator that can be transposed and that can
+        produce matrix products.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+        Larger values take longer and use more memory
+        but give more accurate output.
+    itmax : int, optional
+        Use at most this many iterations.
+    compute_v : bool, optional
+        Request a norm-maximizing linear operator input vector if True.
+    compute_w : bool, optional
+        Request a norm-maximizing linear operator output vector if True.
+
+    Returns
+    -------
+    est : float
+        An underestimate of the 1-norm of the sparse array.
+    v : ndarray, optional
+        The vector such that ||Av||_1 == est*||v||_1.
+        It can be thought of as an input to the linear operator
+        that gives an output with particularly large norm.
+    w : ndarray, optional
+        The vector Av which has relatively large 1-norm.
+        It can be thought of as an output of the linear operator
+        that is relatively large in norm compared to the input.
+
+    Notes
+    -----
+    This is algorithm 2.4 of [1].
+
+    In [2] it is described as follows.
+    "This algorithm typically requires the evaluation of
+    about 4t matrix-vector products and almost invariably
+    produces a norm estimate (which is, in fact, a lower
+    bound on the norm) correct to within a factor 3."
+
+    .. versionadded:: 0.13.0
+
+    References
+    ----------
+    .. [1] Nicholas J. Higham and Francoise Tisseur (2000),
+           "A Block Algorithm for Matrix 1-Norm Estimation,
+           with an Application to 1-Norm Pseudospectra."
+           SIAM J. Matrix Anal. Appl. Vol. 21, No. 4, pp. 1185-1201.
+
+    .. [2] Awad H. Al-Mohy and Nicholas J. Higham (2009),
+           "A new scaling and squaring algorithm for the matrix exponential."
+           SIAM J. Matrix Anal. Appl. Vol. 31, No. 3, pp. 970-989.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse import csc_array
+    >>> from scipy.sparse.linalg import onenormest
+    >>> A = csc_array([[1., 0., 0.], [5., 8., 2.], [0., -1., 0.]], dtype=float)
+    >>> A.toarray()
+    array([[ 1.,  0.,  0.],
+           [ 5.,  8.,  2.],
+           [ 0., -1.,  0.]])
+    >>> onenormest(A)
+    9.0
+    >>> np.linalg.norm(A.toarray(), ord=1)
+    9.0
+    """
+
+    # Check the input.
+    A = aslinearoperator(A)
+    if A.shape[0] != A.shape[1]:
+        raise ValueError('expected the operator to act like a square matrix')
+
+    # If the operator size is small compared to t,
+    # then it is easier to compute the exact norm.
+    # Otherwise estimate the norm.
+    n = A.shape[1]
+    if t >= n:
+        A_explicit = np.asarray(aslinearoperator(A).matmat(np.identity(n)))
+        if A_explicit.shape != (n, n):
+            raise Exception('internal error: ',
+                    'unexpected shape ' + str(A_explicit.shape))
+        col_abs_sums = abs(A_explicit).sum(axis=0)
+        if col_abs_sums.shape != (n, ):
+            raise Exception('internal error: ',
+                    'unexpected shape ' + str(col_abs_sums.shape))
+        argmax_j = np.argmax(col_abs_sums)
+        v = elementary_vector(n, argmax_j)
+        w = A_explicit[:, argmax_j]
+        est = col_abs_sums[argmax_j]
+    else:
+        est, v, w, nmults, nresamples = _onenormest_core(A, A.H, t, itmax)
+
+    # Report the norm estimate along with some certificates of the estimate.
+    if compute_v or compute_w:
+        result = (est,)
+        if compute_v:
+            result += (v,)
+        if compute_w:
+            result += (w,)
+        return result
+    else:
+        return est
+
+
+def _blocked_elementwise(func):
+    """
+    Decorator for an elementwise function, to apply it blockwise along
+    first dimension, to avoid excessive memory usage in temporaries.
+    """
+    block_size = 2**20
+
+    def wrapper(x):
+        if x.shape[0] < block_size:
+            return func(x)
+        else:
+            y0 = func(x[:block_size])
+            y = np.zeros((x.shape[0],) + y0.shape[1:], dtype=y0.dtype)
+            y[:block_size] = y0
+            del y0
+            for j in range(block_size, x.shape[0], block_size):
+                y[j:j+block_size] = func(x[j:j+block_size])
+            return y
+    return wrapper
+
+
+@_blocked_elementwise
+def sign_round_up(X):
+    """
+    This should do the right thing for both real and complex matrices.
+
+    From Higham and Tisseur:
+    "Everything in this section remains valid for complex matrices
+    provided that sign(A) is redefined as the matrix (aij / |aij|)
+    (and sign(0) = 1) transposes are replaced by conjugate transposes."
+
+    """
+    Y = X.copy()
+    Y[Y == 0] = 1
+    Y /= np.abs(Y)
+    return Y
+
+
+@_blocked_elementwise
+def _max_abs_axis1(X):
+    return np.max(np.abs(X), axis=1)
+
+
+def _sum_abs_axis0(X):
+    block_size = 2**20
+    r = None
+    for j in range(0, X.shape[0], block_size):
+        y = np.sum(np.abs(X[j:j+block_size]), axis=0)
+        if r is None:
+            r = y
+        else:
+            r += y
+    return r
+
+
+def elementary_vector(n, i):
+    v = np.zeros(n, dtype=float)
+    v[i] = 1
+    return v
+
+
+def vectors_are_parallel(v, w):
+    # Columns are considered parallel when they are equal or negative.
+    # Entries are required to be in {-1, 1},
+    # which guarantees that the magnitudes of the vectors are identical.
+    if v.ndim != 1 or v.shape != w.shape:
+        raise ValueError('expected conformant vectors with entries in {-1,1}')
+    n = v.shape[0]
+    return np.dot(v, w) == n
+
+
+def every_col_of_X_is_parallel_to_a_col_of_Y(X, Y):
+    for v in X.T:
+        if not any(vectors_are_parallel(v, w) for w in Y.T):
+            return False
+    return True
+
+
+def column_needs_resampling(i, X, Y=None):
+    # column i of X needs resampling if either
+    # it is parallel to a previous column of X or
+    # it is parallel to a column of Y
+    n, t = X.shape
+    v = X[:, i]
+    if any(vectors_are_parallel(v, X[:, j]) for j in range(i)):
+        return True
+    if Y is not None:
+        if any(vectors_are_parallel(v, w) for w in Y.T):
+            return True
+    return False
+
+
+def resample_column(i, X):
+    X[:, i] = np.random.randint(0, 2, size=X.shape[0])*2 - 1
+
+
+def less_than_or_close(a, b):
+    return np.allclose(a, b) or (a < b)
+
+
+def _algorithm_2_2(A, AT, t):
+    """
+    This is Algorithm 2.2.
+
+    Parameters
+    ----------
+    A : ndarray or other linear operator
+        A linear operator that can produce matrix products.
+    AT : ndarray or other linear operator
+        The transpose of A.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+
+    Returns
+    -------
+    g : sequence
+        A non-negative decreasing vector
+        such that g[j] is a lower bound for the 1-norm
+        of the column of A of jth largest 1-norm.
+        The first entry of this vector is therefore a lower bound
+        on the 1-norm of the linear operator A.
+        This sequence has length t.
+    ind : sequence
+        The ith entry of ind is the index of the column A whose 1-norm
+        is given by g[i].
+        This sequence of indices has length t, and its entries are
+        chosen from range(n), possibly with repetition,
+        where n is the order of the operator A.
+
+    Notes
+    -----
+    This algorithm is mainly for testing.
+    It uses the 'ind' array in a way that is similar to
+    its usage in algorithm 2.4. This algorithm 2.2 may be easier to test,
+    so it gives a chance of uncovering bugs related to indexing
+    which could have propagated less noticeably to algorithm 2.4.
+
+    """
+    A_linear_operator = aslinearoperator(A)
+    AT_linear_operator = aslinearoperator(AT)
+    n = A_linear_operator.shape[0]
+
+    # Initialize the X block with columns of unit 1-norm.
+    X = np.ones((n, t))
+    if t > 1:
+        X[:, 1:] = np.random.randint(0, 2, size=(n, t-1))*2 - 1
+    X /= float(n)
+
+    # Iteratively improve the lower bounds.
+    # Track extra things, to assert invariants for debugging.
+    g_prev = None
+    h_prev = None
+    k = 1
+    ind = range(t)
+    while True:
+        Y = np.asarray(A_linear_operator.matmat(X))
+        g = _sum_abs_axis0(Y)
+        best_j = np.argmax(g)
+        g.sort()
+        g = g[::-1]
+        S = sign_round_up(Y)
+        Z = np.asarray(AT_linear_operator.matmat(S))
+        h = _max_abs_axis1(Z)
+
+        # If this algorithm runs for fewer than two iterations,
+        # then its return values do not have the properties indicated
+        # in the description of the algorithm.
+        # In particular, the entries of g are not 1-norms of any
+        # column of A until the second iteration.
+        # Therefore we will require the algorithm to run for at least
+        # two iterations, even though this requirement is not stated
+        # in the description of the algorithm.
+        if k >= 2:
+            if less_than_or_close(max(h), np.dot(Z[:, best_j], X[:, best_j])):
+                break
+        ind = np.argsort(h)[::-1][:t]
+        h = h[ind]
+        for j in range(t):
+            X[:, j] = elementary_vector(n, ind[j])
+
+        # Check invariant (2.2).
+        if k >= 2:
+            if not less_than_or_close(g_prev[0], h_prev[0]):
+                raise Exception('invariant (2.2) is violated')
+            if not less_than_or_close(h_prev[0], g[0]):
+                raise Exception('invariant (2.2) is violated')
+
+        # Check invariant (2.3).
+        if k >= 3:
+            for j in range(t):
+                if not less_than_or_close(g[j], g_prev[j]):
+                    raise Exception('invariant (2.3) is violated')
+
+        # Update for the next iteration.
+        g_prev = g
+        h_prev = h
+        k += 1
+
+    # Return the lower bounds and the corresponding column indices.
+    return g, ind
+
+
+def _onenormest_core(A, AT, t, itmax):
+    """
+    Compute a lower bound of the 1-norm of a sparse array.
+
+    Parameters
+    ----------
+    A : ndarray or other linear operator
+        A linear operator that can produce matrix products.
+    AT : ndarray or other linear operator
+        The transpose of A.
+    t : int, optional
+        A positive parameter controlling the tradeoff between
+        accuracy versus time and memory usage.
+    itmax : int, optional
+        Use at most this many iterations.
+
+    Returns
+    -------
+    est : float
+        An underestimate of the 1-norm of the sparse array.
+    v : ndarray, optional
+        The vector such that ||Av||_1 == est*||v||_1.
+        It can be thought of as an input to the linear operator
+        that gives an output with particularly large norm.
+    w : ndarray, optional
+        The vector Av which has relatively large 1-norm.
+        It can be thought of as an output of the linear operator
+        that is relatively large in norm compared to the input.
+    nmults : int, optional
+        The number of matrix products that were computed.
+    nresamples : int, optional
+        The number of times a parallel column was observed,
+        necessitating a re-randomization of the column.
+
+    Notes
+    -----
+    This is algorithm 2.4.
+
+    """
+    # This function is a more or less direct translation
+    # of Algorithm 2.4 from the Higham and Tisseur (2000) paper.
+    A_linear_operator = aslinearoperator(A)
+    AT_linear_operator = aslinearoperator(AT)
+    if itmax < 2:
+        raise ValueError('at least two iterations are required')
+    if t < 1:
+        raise ValueError('at least one column is required')
+    n = A.shape[0]
+    if t >= n:
+        raise ValueError('t should be smaller than the order of A')
+    # Track the number of big*small matrix multiplications
+    # and the number of resamplings.
+    nmults = 0
+    nresamples = 0
+    # "We now explain our choice of starting matrix.  We take the first
+    # column of X to be the vector of 1s [...] This has the advantage that
+    # for a matrix with nonnegative elements the algorithm converges
+    # with an exact estimate on the second iteration, and such matrices
+    # arise in applications [...]"
+    X = np.ones((n, t), dtype=float)
+    # "The remaining columns are chosen as rand{-1,1},
+    # with a check for and correction of parallel columns,
+    # exactly as for S in the body of the algorithm."
+    if t > 1:
+        for i in range(1, t):
+            # These are technically initial samples, not resamples,
+            # so the resampling count is not incremented.
+            resample_column(i, X)
+        for i in range(t):
+            while column_needs_resampling(i, X):
+                resample_column(i, X)
+                nresamples += 1
+    # "Choose starting matrix X with columns of unit 1-norm."
+    X /= float(n)
+    # "indices of used unit vectors e_j"
+    ind_hist = np.zeros(0, dtype=np.intp)
+    est_old = 0
+    S = np.zeros((n, t), dtype=float)
+    k = 1
+    ind = None
+    while True:
+        Y = np.asarray(A_linear_operator.matmat(X))
+        nmults += 1
+        mags = _sum_abs_axis0(Y)
+        est = np.max(mags)
+        best_j = np.argmax(mags)
+        if est > est_old or k == 2:
+            if k >= 2:
+                ind_best = ind[best_j]
+            w = Y[:, best_j]
+        # (1)
+        if k >= 2 and est <= est_old:
+            est = est_old
+            break
+        est_old = est
+        S_old = S
+        if k > itmax:
+            break
+        S = sign_round_up(Y)
+        del Y
+        # (2)
+        if every_col_of_X_is_parallel_to_a_col_of_Y(S, S_old):
+            break
+        if t > 1:
+            # "Ensure that no column of S is parallel to another column of S
+            # or to a column of S_old by replacing columns of S by rand{-1,1}."
+            for i in range(t):
+                while column_needs_resampling(i, S, S_old):
+                    resample_column(i, S)
+                    nresamples += 1
+        del S_old
+        # (3)
+        Z = np.asarray(AT_linear_operator.matmat(S))
+        nmults += 1
+        h = _max_abs_axis1(Z)
+        del Z
+        # (4)
+        if k >= 2 and max(h) == h[ind_best]:
+            break
+        # "Sort h so that h_first >= ... >= h_last
+        # and re-order ind correspondingly."
+        #
+        # Later on, we will need at most t+len(ind_hist) largest
+        # entries, so drop the rest
+        ind = np.argsort(h)[::-1][:t+len(ind_hist)].copy()
+        del h
+        if t > 1:
+            # (5)
+            # Break if the most promising t vectors have been visited already.
+            if np.isin(ind[:t], ind_hist).all():
+                break
+            # Put the most promising unvisited vectors at the front of the list
+            # and put the visited vectors at the end of the list.
+            # Preserve the order of the indices induced by the ordering of h.
+            seen = np.isin(ind, ind_hist)
+            ind = np.concatenate((ind[~seen], ind[seen]))
+        for j in range(t):
+            X[:, j] = elementary_vector(n, ind[j])
+
+        new_ind = ind[:t][~np.isin(ind[:t], ind_hist)]
+        ind_hist = np.concatenate((ind_hist, new_ind))
+        k += 1
+    v = elementary_vector(n, ind_best)
+    return est, v, w, nmults, nresamples
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d7415e1ec9a7e03b94dd8893935d46294b4b215
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_special_sparse_arrays.py
@@ -0,0 +1,948 @@
+import numpy as np
+from scipy.sparse.linalg import LinearOperator
+from scipy.sparse import kron, eye, dia_array
+
+__all__ = ['LaplacianNd']
+# Sakurai and Mikota classes are intended for tests and benchmarks
+# and explicitly not included in the public API of this module.
+
+
+class LaplacianNd(LinearOperator):
+    """
+    The grid Laplacian in ``N`` dimensions and its eigenvalues/eigenvectors.
+
+    Construct Laplacian on a uniform rectangular grid in `N` dimensions
+    and output its eigenvalues and eigenvectors.
+    The Laplacian ``L`` is square, negative definite, real symmetric array
+    with signed integer entries and zeros otherwise.
+
+    Parameters
+    ----------
+    grid_shape : tuple
+        A tuple of integers of length ``N`` (corresponding to the dimension of
+        the Lapacian), where each entry gives the size of that dimension. The
+        Laplacian matrix is square of the size ``np.prod(grid_shape)``.
+    boundary_conditions : {'neumann', 'dirichlet', 'periodic'}, optional
+        The type of the boundary conditions on the boundaries of the grid.
+        Valid values are ``'dirichlet'`` or ``'neumann'``(default) or
+        ``'periodic'``.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.int8``.
+
+    Methods
+    -------
+    toarray()
+        Construct a dense array from Laplacian data
+    tosparse()
+        Construct a sparse array from Laplacian data
+    eigenvalues(m=None)
+        Construct a 1D array of `m` largest (smallest in absolute value)
+        eigenvalues of the Laplacian matrix in ascending order.
+    eigenvectors(m=None):
+        Construct the array with columns made of `m` eigenvectors (``float``)
+        of the ``Nd`` Laplacian corresponding to the `m` ordered eigenvalues.
+
+    .. versionadded:: 1.12.0
+
+    Notes
+    -----
+    Compared to the MATLAB/Octave implementation [1] of 1-, 2-, and 3-D
+    Laplacian, this code allows the arbitrary N-D case and the matrix-free
+    callable option, but is currently limited to pure Dirichlet, Neumann or
+    Periodic boundary conditions only.
+
+    The Laplacian matrix of a graph (`scipy.sparse.csgraph.laplacian`) of a
+    rectangular grid corresponds to the negative Laplacian with the Neumann
+    conditions, i.e., ``boundary_conditions = 'neumann'``.
+
+    All eigenvalues and eigenvectors of the discrete Laplacian operator for
+    an ``N``-dimensional  regular grid of shape `grid_shape` with the grid
+    step size ``h=1`` are analytically known [2].
+
+    References
+    ----------
+    .. [1] https://github.com/lobpcg/blopex/blob/master/blopex_\
+tools/matlab/laplacian/laplacian.m
+    .. [2] "Eigenvalues and eigenvectors of the second derivative", Wikipedia
+           https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors_\
+of_the_second_derivative
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg import LaplacianNd
+    >>> from scipy.sparse import diags, csgraph
+    >>> from scipy.linalg import eigvalsh
+
+    The one-dimensional Laplacian demonstrated below for pure Neumann boundary
+    conditions on a regular grid with ``n=6`` grid points is exactly the
+    negative graph Laplacian for the undirected linear graph with ``n``
+    vertices using the sparse adjacency matrix ``G`` represented by the
+    famous tri-diagonal matrix:
+
+    >>> n = 6
+    >>> G = diags(np.ones(n - 1), 1, format='csr')
+    >>> Lf = csgraph.laplacian(G, symmetrized=True, form='function')
+    >>> grid_shape = (n, )
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann')
+    >>> np.array_equal(lap.matmat(np.eye(n)), -Lf(np.eye(n)))
+    True
+
+    Since all matrix entries of the Laplacian are integers, ``'int8'`` is
+    the default dtype for storing matrix representations.
+
+    >>> lap.tosparse()
+    
+    >>> lap.toarray()
+    array([[-1,  1,  0,  0,  0,  0],
+           [ 1, -2,  1,  0,  0,  0],
+           [ 0,  1, -2,  1,  0,  0],
+           [ 0,  0,  1, -2,  1,  0],
+           [ 0,  0,  0,  1, -2,  1],
+           [ 0,  0,  0,  0,  1, -1]], dtype=int8)
+    >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
+    True
+    >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
+    True
+
+    Any number of extreme eigenvalues and/or eigenvectors can be computed.
+    
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic')
+    >>> lap.eigenvalues()
+    array([-4., -3., -3., -1., -1.,  0.])
+    >>> lap.eigenvalues()[-2:]
+    array([-1.,  0.])
+    >>> lap.eigenvalues(2)
+    array([-1.,  0.])
+    >>> lap.eigenvectors(1)
+    array([[0.40824829],
+           [0.40824829],
+           [0.40824829],
+           [0.40824829],
+           [0.40824829],
+           [0.40824829]])
+    >>> lap.eigenvectors(2)
+    array([[ 0.5       ,  0.40824829],
+           [ 0.        ,  0.40824829],
+           [-0.5       ,  0.40824829],
+           [-0.5       ,  0.40824829],
+           [ 0.        ,  0.40824829],
+           [ 0.5       ,  0.40824829]])
+    >>> lap.eigenvectors()
+    array([[ 0.40824829,  0.28867513,  0.28867513,  0.5       ,  0.5       ,
+             0.40824829],
+           [-0.40824829, -0.57735027, -0.57735027,  0.        ,  0.        ,
+             0.40824829],
+           [ 0.40824829,  0.28867513,  0.28867513, -0.5       , -0.5       ,
+             0.40824829],
+           [-0.40824829,  0.28867513,  0.28867513, -0.5       , -0.5       ,
+             0.40824829],
+           [ 0.40824829, -0.57735027, -0.57735027,  0.        ,  0.        ,
+             0.40824829],
+           [-0.40824829,  0.28867513,  0.28867513,  0.5       ,  0.5       ,
+             0.40824829]])
+
+    The two-dimensional Laplacian is illustrated on a regular grid with
+    ``grid_shape = (2, 3)`` points in each dimension.
+
+    >>> grid_shape = (2, 3)
+    >>> n = np.prod(grid_shape)
+
+    Numeration of grid points is as follows:
+
+    >>> np.arange(n).reshape(grid_shape + (-1,))
+    array([[[0],
+            [1],
+            [2]],
+    
+           [[3],
+            [4],
+            [5]]])
+
+    Each of the boundary conditions ``'dirichlet'``, ``'periodic'``, and
+    ``'neumann'`` is illustrated separately; with ``'dirichlet'``
+
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='dirichlet')
+    >>> lap.tosparse()
+    
+    >>> lap.toarray()
+    array([[-4,  1,  0,  1,  0,  0],
+           [ 1, -4,  1,  0,  1,  0],
+           [ 0,  1, -4,  0,  0,  1],
+           [ 1,  0,  0, -4,  1,  0],
+           [ 0,  1,  0,  1, -4,  1],
+           [ 0,  0,  1,  0,  1, -4]], dtype=int8)
+    >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
+    True
+    >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
+    True
+    >>> lap.eigenvalues()
+    array([-6.41421356, -5.        , -4.41421356, -3.58578644, -3.        ,
+           -1.58578644])
+    >>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
+    >>> np.allclose(lap.eigenvalues(), eigvals)
+    True
+    >>> np.allclose(lap.toarray() @ lap.eigenvectors(),
+    ...             lap.eigenvectors() @ np.diag(lap.eigenvalues()))
+    True
+
+    with ``'periodic'``
+
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='periodic')
+    >>> lap.tosparse()
+    
+    >>> lap.toarray()
+        array([[-4,  1,  1,  2,  0,  0],
+               [ 1, -4,  1,  0,  2,  0],
+               [ 1,  1, -4,  0,  0,  2],
+               [ 2,  0,  0, -4,  1,  1],
+               [ 0,  2,  0,  1, -4,  1],
+               [ 0,  0,  2,  1,  1, -4]], dtype=int8)
+    >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
+    True
+    >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
+    True
+    >>> lap.eigenvalues()
+    array([-7., -7., -4., -3., -3.,  0.])
+    >>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
+    >>> np.allclose(lap.eigenvalues(), eigvals)
+    True
+    >>> np.allclose(lap.toarray() @ lap.eigenvectors(),
+    ...             lap.eigenvectors() @ np.diag(lap.eigenvalues()))
+    True
+
+    and with ``'neumann'``
+
+    >>> lap = LaplacianNd(grid_shape, boundary_conditions='neumann')
+    >>> lap.tosparse()
+    
+    >>> lap.toarray()
+    array([[-2,  1,  0,  1,  0,  0],
+           [ 1, -3,  1,  0,  1,  0],
+           [ 0,  1, -2,  0,  0,  1],
+           [ 1,  0,  0, -2,  1,  0],
+           [ 0,  1,  0,  1, -3,  1],
+           [ 0,  0,  1,  0,  1, -2]], dtype=int8)
+    >>> np.array_equal(lap.matmat(np.eye(n)), lap.toarray())
+    True
+    >>> np.array_equal(lap.tosparse().toarray(), lap.toarray())
+    True
+    >>> lap.eigenvalues()
+    array([-5., -3., -3., -2., -1.,  0.])
+    >>> eigvals = eigvalsh(lap.toarray().astype(np.float64))
+    >>> np.allclose(lap.eigenvalues(), eigvals)
+    True
+    >>> np.allclose(lap.toarray() @ lap.eigenvectors(),
+    ...             lap.eigenvectors() @ np.diag(lap.eigenvalues()))
+    True
+
+    """
+
+    def __init__(self, grid_shape, *,
+                 boundary_conditions='neumann',
+                 dtype=np.int8):
+
+        if boundary_conditions not in ('dirichlet', 'neumann', 'periodic'):
+            raise ValueError(
+                f"Unknown value {boundary_conditions!r} is given for "
+                "'boundary_conditions' parameter. The valid options are "
+                "'dirichlet', 'periodic', and 'neumann' (default)."
+            )
+
+        self.grid_shape = grid_shape
+        self.boundary_conditions = boundary_conditions
+        # LaplacianNd folds all dimensions in `grid_shape` into a single one
+        N = np.prod(grid_shape)
+        super().__init__(dtype=dtype, shape=(N, N))
+
+    def _eigenvalue_ordering(self, m):
+        """Compute `m` largest eigenvalues in each of the ``N`` directions,
+        i.e., up to ``m * N`` total, order them and return `m` largest.
+        """
+        grid_shape = self.grid_shape
+        if m is None:
+            indices = np.indices(grid_shape)
+            Leig = np.zeros(grid_shape)
+        else:
+            grid_shape_min = min(grid_shape,
+                                 tuple(np.ones_like(grid_shape) * m))
+            indices = np.indices(grid_shape_min)
+            Leig = np.zeros(grid_shape_min)
+
+        for j, n in zip(indices, grid_shape):
+            if self.boundary_conditions == 'dirichlet':
+                Leig += -4 * np.sin(np.pi * (j + 1) / (2 * (n + 1))) ** 2
+            elif self.boundary_conditions == 'neumann':
+                Leig += -4 * np.sin(np.pi * j / (2 * n)) ** 2
+            else:  # boundary_conditions == 'periodic'
+                Leig += -4 * np.sin(np.pi * np.floor((j + 1) / 2) / n) ** 2
+
+        Leig_ravel = Leig.ravel()
+        ind = np.argsort(Leig_ravel)
+        eigenvalues = Leig_ravel[ind]
+        if m is not None:
+            eigenvalues = eigenvalues[-m:]
+            ind = ind[-m:]
+
+        return eigenvalues, ind
+
+    def eigenvalues(self, m=None):
+        """Return the requested number of eigenvalues.
+        
+        Parameters
+        ----------
+        m : int, optional
+            The positive number of smallest eigenvalues to return.
+            If not provided, then all eigenvalues will be returned.
+            
+        Returns
+        -------
+        eigenvalues : float array
+            The requested `m` smallest or all eigenvalues, in ascending order.
+        """
+        eigenvalues, _ = self._eigenvalue_ordering(m)
+        return eigenvalues
+
+    def _ev1d(self, j, n):
+        """Return 1 eigenvector in 1d with index `j`
+        and number of grid points `n` where ``j < n``. 
+        """
+        if self.boundary_conditions == 'dirichlet':
+            i = np.pi * (np.arange(n) + 1) / (n + 1)
+            ev = np.sqrt(2. / (n + 1.)) * np.sin(i * (j + 1))
+        elif self.boundary_conditions == 'neumann':
+            i = np.pi * (np.arange(n) + 0.5) / n
+            ev = np.sqrt((1. if j == 0 else 2.) / n) * np.cos(i * j)
+        else:  # boundary_conditions == 'periodic'
+            if j == 0:
+                ev = np.sqrt(1. / n) * np.ones(n)
+            elif j + 1 == n and n % 2 == 0:
+                ev = np.sqrt(1. / n) * np.tile([1, -1], n//2)
+            else:
+                i = 2. * np.pi * (np.arange(n) + 0.5) / n
+                ev = np.sqrt(2. / n) * np.cos(i * np.floor((j + 1) / 2))
+        # make small values exact zeros correcting round-off errors
+        # due to symmetry of eigenvectors the exact 0. is correct 
+        ev[np.abs(ev) < np.finfo(np.float64).eps] = 0.
+        return ev
+
+    def _one_eve(self, k):
+        """Return 1 eigenvector in Nd with multi-index `j`
+        as a tensor product of the corresponding 1d eigenvectors. 
+        """
+        phi = [self._ev1d(j, n) for j, n in zip(k, self.grid_shape)]
+        result = phi[0]
+        for phi in phi[1:]:
+            result = np.tensordot(result, phi, axes=0)
+        return np.asarray(result).ravel()
+
+    def eigenvectors(self, m=None):
+        """Return the requested number of eigenvectors for ordered eigenvalues.
+        
+        Parameters
+        ----------
+        m : int, optional
+            The positive number of eigenvectors to return. If not provided,
+            then all eigenvectors will be returned.
+            
+        Returns
+        -------
+        eigenvectors : float array
+            An array with columns made of the requested `m` or all eigenvectors.
+            The columns are ordered according to the `m` ordered eigenvalues. 
+        """
+        _, ind = self._eigenvalue_ordering(m)
+        if m is None:
+            grid_shape_min = self.grid_shape
+        else:
+            grid_shape_min = min(self.grid_shape,
+                                tuple(np.ones_like(self.grid_shape) * m))
+
+        N_indices = np.unravel_index(ind, grid_shape_min)
+        N_indices = [tuple(x) for x in zip(*N_indices)]
+        eigenvectors_list = [self._one_eve(k) for k in N_indices]
+        return np.column_stack(eigenvectors_list)
+
+    def toarray(self):
+        """
+        Converts the Laplacian data to a dense array.
+
+        Returns
+        -------
+        L : ndarray
+            The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``.
+
+        """
+        grid_shape = self.grid_shape
+        n = np.prod(grid_shape)
+        L = np.zeros([n, n], dtype=np.int8)
+        # Scratch arrays
+        L_i = np.empty_like(L)
+        Ltemp = np.empty_like(L)
+
+        for ind, dim in enumerate(grid_shape):
+            # Start zeroing out L_i
+            L_i[:] = 0
+            # Allocate the top left corner with the kernel of L_i
+            # Einsum returns writable view of arrays
+            np.einsum("ii->i", L_i[:dim, :dim])[:] = -2
+            np.einsum("ii->i", L_i[: dim - 1, 1:dim])[:] = 1
+            np.einsum("ii->i", L_i[1:dim, : dim - 1])[:] = 1
+
+            if self.boundary_conditions == 'neumann':
+                L_i[0, 0] = -1
+                L_i[dim - 1, dim - 1] = -1
+            elif self.boundary_conditions == 'periodic':
+                if dim > 1:
+                    L_i[0, dim - 1] += 1
+                    L_i[dim - 1, 0] += 1
+                else:
+                    L_i[0, 0] += 1
+
+            # kron is too slow for large matrices hence the next two tricks
+            # 1- kron(eye, mat) is block_diag(mat, mat, ...)
+            # 2- kron(mat, eye) can be performed by 4d stride trick
+
+            # 1-
+            new_dim = dim
+            # for block_diag we tile the top left portion on the diagonal
+            if ind > 0:
+                tiles = np.prod(grid_shape[:ind])
+                for j in range(1, tiles):
+                    L_i[j*dim:(j+1)*dim, j*dim:(j+1)*dim] = L_i[:dim, :dim]
+                    new_dim += dim
+            # 2-
+            # we need the keep L_i, but reset the array
+            Ltemp[:new_dim, :new_dim] = L_i[:new_dim, :new_dim]
+            tiles = int(np.prod(grid_shape[ind+1:]))
+            # Zero out the top left, the rest is already 0
+            L_i[:new_dim, :new_dim] = 0
+            idx = [x for x in range(tiles)]
+            L_i.reshape(
+                (new_dim, tiles,
+                 new_dim, tiles)
+                )[:, idx, :, idx] = Ltemp[:new_dim, :new_dim]
+
+            L += L_i
+
+        return L.astype(self.dtype)
+
+    def tosparse(self):
+        """
+        Constructs a sparse array from the Laplacian data. The returned sparse
+        array format is dependent on the selected boundary conditions.
+
+        Returns
+        -------
+        L : scipy.sparse.sparray
+            The shape is ``(N, N)`` where ``N = np.prod(grid_shape)``.
+
+        """
+        N = len(self.grid_shape)
+        p = np.prod(self.grid_shape)
+        L = dia_array((p, p), dtype=np.int8)
+
+        for i in range(N):
+            dim = self.grid_shape[i]
+            data = np.ones([3, dim], dtype=np.int8)
+            data[1, :] *= -2
+
+            if self.boundary_conditions == 'neumann':
+                data[1, 0] = -1
+                data[1, -1] = -1
+
+            L_i = dia_array((data, [-1, 0, 1]), shape=(dim, dim),
+                            dtype=np.int8
+                            )
+
+            if self.boundary_conditions == 'periodic':
+                t = dia_array((dim, dim), dtype=np.int8)
+                t.setdiag([1], k=-dim+1)
+                t.setdiag([1], k=dim-1)
+                L_i += t
+
+            for j in range(i):
+                L_i = kron(eye(self.grid_shape[j], dtype=np.int8), L_i)
+            for j in range(i + 1, N):
+                L_i = kron(L_i, eye(self.grid_shape[j], dtype=np.int8))
+            L += L_i
+        return L.astype(self.dtype)
+
+    def _matvec(self, x):
+        grid_shape = self.grid_shape
+        N = len(grid_shape)
+        X = x.reshape(grid_shape + (-1,))
+        Y = -2 * N * X
+        for i in range(N):
+            Y += np.roll(X, 1, axis=i)
+            Y += np.roll(X, -1, axis=i)
+            if self.boundary_conditions in ('neumann', 'dirichlet'):
+                Y[(slice(None),)*i + (0,) + (slice(None),)*(N-i-1)
+                  ] -= np.roll(X, 1, axis=i)[
+                    (slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
+                ]
+                Y[
+                    (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
+                ] -= np.roll(X, -1, axis=i)[
+                    (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
+                ]
+
+                if self.boundary_conditions == 'neumann':
+                    Y[
+                        (slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
+                    ] += np.roll(X, 0, axis=i)[
+                        (slice(None),) * i + (0,) + (slice(None),) * (N-i-1)
+                    ]
+                    Y[
+                        (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
+                    ] += np.roll(X, 0, axis=i)[
+                        (slice(None),) * i + (-1,) + (slice(None),) * (N-i-1)
+                    ]
+
+        return Y.reshape(-1, X.shape[-1])
+
+    def _matmat(self, x):
+        return self._matvec(x)
+
+    def _adjoint(self):
+        return self
+
+    def _transpose(self):
+        return self
+
+
+class Sakurai(LinearOperator):
+    """
+    Construct a Sakurai matrix in various formats and its eigenvalues.
+
+    Constructs the "Sakurai" matrix motivated by reference [1]_:
+    square real symmetric positive definite and 5-diagonal
+    with the main diagonal ``[5, 6, 6, ..., 6, 6, 5], the ``+1`` and ``-1``
+    diagonals filled with ``-4``, and the ``+2`` and ``-2`` diagonals
+    made of ``1``. Its eigenvalues are analytically known to be
+    ``16. * np.power(np.cos(0.5 * k * np.pi / (n + 1)), 4)``.
+    The matrix gets ill-conditioned with its size growing.
+    It is useful for testing and benchmarking sparse eigenvalue solvers
+    especially those taking advantage of its banded 5-diagonal structure.
+    See the notes below for details.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrix.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.int8``.
+
+    Methods
+    -------
+    toarray()
+        Construct a dense array from Laplacian data
+    tosparse()
+        Construct a sparse array from Laplacian data
+    tobanded()
+        The Sakurai matrix in the format for banded symmetric matrices,
+        i.e., (3, n) ndarray with 3 upper diagonals
+        placing the main diagonal at the bottom.
+    eigenvalues
+        All eigenvalues of the Sakurai matrix ordered ascending.
+
+    Notes
+    -----
+    Reference [1]_ introduces a generalized eigenproblem for the matrix pair
+    `A` and `B` where `A` is the identity so we turn it into an eigenproblem
+    just for the matrix `B` that this function outputs in various formats
+    together with its eigenvalues.
+    
+    .. versionadded:: 1.12.0
+
+    References
+    ----------
+    .. [1] T. Sakurai, H. Tadano, Y. Inadomi, and U. Nagashima,
+       "A moment-based method for large-scale generalized
+       eigenvalue problems",
+       Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg._special_sparse_arrays import Sakurai
+    >>> from scipy.linalg import eig_banded
+    >>> n = 6
+    >>> sak = Sakurai(n)
+
+    Since all matrix entries are small integers, ``'int8'`` is
+    the default dtype for storing matrix representations.
+
+    >>> sak.toarray()
+    array([[ 5, -4,  1,  0,  0,  0],
+           [-4,  6, -4,  1,  0,  0],
+           [ 1, -4,  6, -4,  1,  0],
+           [ 0,  1, -4,  6, -4,  1],
+           [ 0,  0,  1, -4,  6, -4],
+           [ 0,  0,  0,  1, -4,  5]], dtype=int8)
+    >>> sak.tobanded()
+    array([[ 1,  1,  1,  1,  1,  1],
+           [-4, -4, -4, -4, -4, -4],
+           [ 5,  6,  6,  6,  6,  5]], dtype=int8)
+    >>> sak.tosparse()
+    
+    >>> np.array_equal(sak.dot(np.eye(n)), sak.tosparse().toarray())
+    True
+    >>> sak.eigenvalues()
+    array([0.03922866, 0.56703972, 2.41789479, 5.97822974,
+           10.54287655, 14.45473055])
+    >>> sak.eigenvalues(2)
+    array([0.03922866, 0.56703972])
+
+    The banded form can be used in scipy functions for banded matrices, e.g.,
+
+    >>> e = eig_banded(sak.tobanded(), eigvals_only=True)
+    >>> np.allclose(sak.eigenvalues, e, atol= n * n * n * np.finfo(float).eps)
+    True
+
+    """
+    def __init__(self, n, dtype=np.int8):
+        self.n = n
+        self.dtype = dtype
+        shape = (n, n)
+        super().__init__(dtype, shape)
+
+    def eigenvalues(self, m=None):
+        """Return the requested number of eigenvalues.
+        
+        Parameters
+        ----------
+        m : int, optional
+            The positive number of smallest eigenvalues to return.
+            If not provided, then all eigenvalues will be returned.
+            
+        Returns
+        -------
+        eigenvalues : `np.float64` array
+            The requested `m` smallest or all eigenvalues, in ascending order.
+        """
+        if m is None:
+            m = self.n
+        k = np.arange(self.n + 1 -m, self.n + 1)
+        return np.flip(16. * np.power(np.cos(0.5 * k * np.pi / (self.n + 1)), 4))
+
+    def tobanded(self):
+        """
+        Construct the Sakurai matrix as a banded array.
+        """
+        d0 = np.r_[5, 6 * np.ones(self.n - 2, dtype=self.dtype), 5]
+        d1 = -4 * np.ones(self.n, dtype=self.dtype)
+        d2 = np.ones(self.n, dtype=self.dtype)
+        return np.array([d2, d1, d0]).astype(self.dtype)
+
+    def tosparse(self):
+        """
+        Construct the Sakurai matrix is a sparse format.
+        """
+        from scipy.sparse import spdiags
+        d = self.tobanded()
+        # the banded format has the main diagonal at the bottom
+        # `spdiags` has no `dtype` parameter so inherits dtype from banded
+        return spdiags([d[0], d[1], d[2], d[1], d[0]], [-2, -1, 0, 1, 2],
+                       self.n, self.n)
+
+    def toarray(self):
+        return self.tosparse().toarray()
+    
+    def _matvec(self, x):
+        """
+        Construct matrix-free callable banded-matrix-vector multiplication by
+        the Sakurai matrix without constructing or storing the matrix itself
+        using the knowledge of its entries and the 5-diagonal format.
+        """
+        x = x.reshape(self.n, -1)
+        result_dtype = np.promote_types(x.dtype, self.dtype)
+        sx = np.zeros_like(x, dtype=result_dtype)
+        sx[0, :] = 5 * x[0, :] - 4 * x[1, :] + x[2, :]
+        sx[-1, :] = 5 * x[-1, :] - 4 * x[-2, :] + x[-3, :]
+        sx[1: -1, :] = (6 * x[1: -1, :] - 4 * (x[:-2, :] + x[2:, :])
+                      + np.pad(x[:-3, :], ((1, 0), (0, 0)))
+                      + np.pad(x[3:, :], ((0, 1), (0, 0))))
+        return sx
+
+    def _matmat(self, x):
+        """
+        Construct matrix-free callable matrix-matrix multiplication by
+        the Sakurai matrix without constructing or storing the matrix itself
+        by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
+        """        
+        return self._matvec(x)
+
+    def _adjoint(self):
+        return self
+
+    def _transpose(self):
+        return self
+
+
+class MikotaM(LinearOperator):
+    """
+    Construct a mass matrix in various formats of Mikota pair.
+
+    The mass matrix `M` is square real diagonal
+    positive definite with entries that are reciprocal to integers.
+
+    Parameters
+    ----------
+    shape : tuple of int
+        The shape of the matrix.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.float64``.
+
+    Methods
+    -------
+    toarray()
+        Construct a dense array from Mikota data
+    tosparse()
+        Construct a sparse array from Mikota data
+    tobanded()
+        The format for banded symmetric matrices,
+        i.e., (1, n) ndarray with the main diagonal.
+    """
+    def __init__(self, shape, dtype=np.float64):
+        self.shape = shape
+        self.dtype = dtype
+        super().__init__(dtype, shape)
+
+    def _diag(self):
+        # The matrix is constructed from its diagonal 1 / [1, ..., N+1];
+        # compute in a function to avoid duplicated code & storage footprint
+        return (1. / np.arange(1, self.shape[0] + 1)).astype(self.dtype)
+
+    def tobanded(self):
+        return self._diag()
+
+    def tosparse(self):
+        from scipy.sparse import diags
+        return diags([self._diag()], [0], shape=self.shape, dtype=self.dtype)
+
+    def toarray(self):
+        return np.diag(self._diag()).astype(self.dtype)
+
+    def _matvec(self, x):
+        """
+        Construct matrix-free callable banded-matrix-vector multiplication by
+        the Mikota mass matrix without constructing or storing the matrix itself
+        using the knowledge of its entries and the diagonal format.
+        """
+        x = x.reshape(self.shape[0], -1)
+        return self._diag()[:, np.newaxis] * x
+
+    def _matmat(self, x):
+        """
+        Construct matrix-free callable matrix-matrix multiplication by
+        the Mikota mass matrix without constructing or storing the matrix itself
+        by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
+        """     
+        return self._matvec(x)
+
+    def _adjoint(self):
+        return self
+
+    def _transpose(self):
+        return self
+
+
+class MikotaK(LinearOperator):
+    """
+    Construct a stiffness matrix in various formats of Mikota pair.
+
+    The stiffness matrix `K` is square real tri-diagonal symmetric
+    positive definite with integer entries. 
+
+    Parameters
+    ----------
+    shape : tuple of int
+        The shape of the matrix.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.int32``.
+
+    Methods
+    -------
+    toarray()
+        Construct a dense array from Mikota data
+    tosparse()
+        Construct a sparse array from Mikota data
+    tobanded()
+        The format for banded symmetric matrices,
+        i.e., (2, n) ndarray with 2 upper diagonals
+        placing the main diagonal at the bottom.
+    """
+    def __init__(self, shape, dtype=np.int32):
+        self.shape = shape
+        self.dtype = dtype
+        super().__init__(dtype, shape)
+        # The matrix is constructed from its diagonals;
+        # we precompute these to avoid duplicating the computation
+        n = shape[0]
+        self._diag0 = np.arange(2 * n - 1, 0, -2, dtype=self.dtype)
+        self._diag1 = - np.arange(n - 1, 0, -1, dtype=self.dtype)
+
+    def tobanded(self):
+        return np.array([np.pad(self._diag1, (1, 0), 'constant'), self._diag0])
+
+    def tosparse(self):
+        from scipy.sparse import diags
+        return diags([self._diag1, self._diag0, self._diag1], [-1, 0, 1],
+                     shape=self.shape, dtype=self.dtype)
+
+    def toarray(self):
+        return self.tosparse().toarray()
+
+    def _matvec(self, x):
+        """
+        Construct matrix-free callable banded-matrix-vector multiplication by
+        the Mikota stiffness matrix without constructing or storing the matrix
+        itself using the knowledge of its entries and the 3-diagonal format.
+        """
+        x = x.reshape(self.shape[0], -1)
+        result_dtype = np.promote_types(x.dtype, self.dtype)
+        kx = np.zeros_like(x, dtype=result_dtype)
+        d1 = self._diag1
+        d0 = self._diag0
+        kx[0, :] = d0[0] * x[0, :] + d1[0] * x[1, :]
+        kx[-1, :] = d1[-1] * x[-2, :] + d0[-1] * x[-1, :]
+        kx[1: -1, :] = (d1[:-1, None] * x[: -2, :]
+                        + d0[1: -1, None] * x[1: -1, :]
+                        + d1[1:, None] * x[2:, :])
+        return kx
+
+    def _matmat(self, x):
+        """
+        Construct matrix-free callable matrix-matrix multiplication by
+        the Stiffness mass matrix without constructing or storing the matrix itself
+        by reusing the ``_matvec(x)`` that supports both 1D and 2D arrays ``x``.
+        """  
+        return self._matvec(x)
+
+    def _adjoint(self):
+        return self
+
+    def _transpose(self):
+        return self
+
+
+class MikotaPair:
+    """
+    Construct the Mikota pair of matrices in various formats and
+    eigenvalues of the generalized eigenproblem with them.
+
+    The Mikota pair of matrices [1, 2]_ models a vibration problem
+    of a linear mass-spring system with the ends attached where
+    the stiffness of the springs and the masses increase along
+    the system length such that vibration frequencies are subsequent
+    integers 1, 2, ..., `n` where `n` is the number of the masses. Thus,
+    eigenvalues of the generalized eigenvalue problem for
+    the matrix pair `K` and `M` where `K` is the system stiffness matrix
+    and `M` is the system mass matrix are the squares of the integers,
+    i.e., 1, 4, 9, ..., ``n * n``.
+
+    The stiffness matrix `K` is square real tri-diagonal symmetric
+    positive definite. The mass matrix `M` is diagonal with diagonal
+    entries 1, 1/2, 1/3, ...., ``1/n``. Both matrices get
+    ill-conditioned with `n` growing.
+
+    Parameters
+    ----------
+    n : int
+        The size of the matrices of the Mikota pair.
+    dtype : dtype
+        Numerical type of the array. Default is ``np.float64``.
+
+    Attributes
+    ----------
+    eigenvalues : 1D ndarray, ``np.uint64``
+        All eigenvalues of the Mikota pair ordered ascending.
+
+    Methods
+    -------
+    MikotaK()
+        A `LinearOperator` custom object for the stiffness matrix.
+    MikotaM()
+        A `LinearOperator` custom object for the mass matrix.
+    
+    .. versionadded:: 1.12.0
+
+    References
+    ----------
+    .. [1] J. Mikota, "Frequency tuning of chain structure multibody oscillators
+       to place the natural frequencies at omega1 and N-1 integer multiples
+       omega2,..., omegaN", Z. Angew. Math. Mech. 81 (2001), S2, S201-S202.
+       Appl. Num. Anal. Comp. Math. Vol. 1 No. 2 (2004).
+    .. [2] Peter C. Muller and Metin Gurgoze,
+       "Natural frequencies of a multi-degree-of-freedom vibration system",
+       Proc. Appl. Math. Mech. 6, 319-320 (2006).
+       http://dx.doi.org/10.1002/pamm.200610141.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.sparse.linalg._special_sparse_arrays import MikotaPair
+    >>> n = 6
+    >>> mik = MikotaPair(n)
+    >>> mik_k = mik.k
+    >>> mik_m = mik.m
+    >>> mik_k.toarray()
+    array([[11., -5.,  0.,  0.,  0.,  0.],
+           [-5.,  9., -4.,  0.,  0.,  0.],
+           [ 0., -4.,  7., -3.,  0.,  0.],
+           [ 0.,  0., -3.,  5., -2.,  0.],
+           [ 0.,  0.,  0., -2.,  3., -1.],
+           [ 0.,  0.,  0.,  0., -1.,  1.]])
+    >>> mik_k.tobanded()
+    array([[ 0., -5., -4., -3., -2., -1.],
+           [11.,  9.,  7.,  5.,  3.,  1.]])
+    >>> mik_m.tobanded()
+    array([1.        , 0.5       , 0.33333333, 0.25      , 0.2       ,
+        0.16666667])
+    >>> mik_k.tosparse()
+    
+    >>> mik_m.tosparse()
+    
+    >>> np.array_equal(mik_k(np.eye(n)), mik_k.toarray())
+    True
+    >>> np.array_equal(mik_m(np.eye(n)), mik_m.toarray())
+    True
+    >>> mik.eigenvalues()
+    array([ 1,  4,  9, 16, 25, 36])  
+    >>> mik.eigenvalues(2)
+    array([ 1,  4])
+
+    """
+    def __init__(self, n, dtype=np.float64):
+        self.n = n
+        self.dtype = dtype
+        self.shape = (n, n)
+        self.m = MikotaM(self.shape, self.dtype)
+        self.k = MikotaK(self.shape, self.dtype)
+
+    def eigenvalues(self, m=None):
+        """Return the requested number of eigenvalues.
+        
+        Parameters
+        ----------
+        m : int, optional
+            The positive number of smallest eigenvalues to return.
+            If not provided, then all eigenvalues will be returned.
+            
+        Returns
+        -------
+        eigenvalues : `np.uint64` array
+            The requested `m` smallest or all eigenvalues, in ascending order.
+        """
+        if m is None:
+            m = self.n
+        arange_plus1 = np.arange(1, m + 1, dtype=np.uint64)
+        return arange_plus1 * arange_plus1
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_svdp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_svdp.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd64c6d0c3069eceb5a347111f1ac77bea8ea942
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/_svdp.py
@@ -0,0 +1,309 @@
+"""
+Python wrapper for PROPACK
+--------------------------
+
+PROPACK is a collection of Fortran routines for iterative computation
+of partial SVDs of large matrices or linear operators.
+
+Based on BSD licensed pypropack project:
+  http://github.com/jakevdp/pypropack
+  Author: Jake Vanderplas 
+
+PROPACK source is BSD licensed, and available at
+  http://soi.stanford.edu/~rmunk/PROPACK/
+"""
+
+__all__ = ['_svdp']
+
+import numpy as np
+
+from scipy.sparse.linalg import aslinearoperator
+from scipy.linalg import LinAlgError
+
+from ._propack import _spropack  # type: ignore[attr-defined]
+from ._propack import _dpropack  # type: ignore[attr-defined]
+from ._propack import _cpropack  # type: ignore[attr-defined]
+from ._propack import _zpropack  # type: ignore[attr-defined]
+
+
+_lansvd_dict = {
+    'f': _spropack.slansvd,
+    'd': _dpropack.dlansvd,
+    'F': _cpropack.clansvd,
+    'D': _zpropack.zlansvd,
+}
+
+
+_lansvd_irl_dict = {
+    'f': _spropack.slansvd_irl,
+    'd': _dpropack.dlansvd_irl,
+    'F': _cpropack.clansvd_irl,
+    'D': _zpropack.zlansvd_irl,
+}
+
+_which_converter = {
+    'LM': 'L',
+    'SM': 'S',
+}
+
+
+class _AProd:
+    """
+    Wrapper class for linear operator
+
+    The call signature of the __call__ method matches the callback of
+    the PROPACK routines.
+    """
+    def __init__(self, A):
+        try:
+            self.A = aslinearoperator(A)
+        except TypeError:
+            self.A = aslinearoperator(np.asarray(A))
+
+    def __call__(self, transa, m, n, x, y, sparm, iparm):
+        if transa == 'n':
+            y[:] = self.A.matvec(x)
+        else:
+            y[:] = self.A.rmatvec(x)
+
+    @property
+    def shape(self):
+        return self.A.shape
+
+    @property
+    def dtype(self):
+        try:
+            return self.A.dtype
+        except AttributeError:
+            return self.A.matvec(np.zeros(self.A.shape[1])).dtype
+
+
+def _svdp(A, k, which='LM', irl_mode=True, kmax=None,
+          compute_u=True, compute_v=True, v0=None, full_output=False, tol=0,
+          delta=None, eta=None, anorm=0, cgs=False, elr=True,
+          min_relgap=0.002, shifts=None, maxiter=None, rng=None):
+    """
+    Compute the singular value decomposition of a linear operator using PROPACK
+
+    Parameters
+    ----------
+    A : array_like, sparse matrix, or LinearOperator
+        Operator for which SVD will be computed.  If `A` is a LinearOperator
+        object, it must define both ``matvec`` and ``rmatvec`` methods.
+    k : int
+        Number of singular values/vectors to compute
+    which : {"LM", "SM"}
+        Which singular triplets to compute:
+        - 'LM': compute triplets corresponding to the `k` largest singular
+                values
+        - 'SM': compute triplets corresponding to the `k` smallest singular
+                values
+        `which='SM'` requires `irl_mode=True`.  Computes largest singular
+        values by default.
+    irl_mode : bool, optional
+        If `True`, then compute SVD using IRL (implicitly restarted Lanczos)
+        mode.  Default is `True`.
+    kmax : int, optional
+        Maximal number of iterations / maximal dimension of the Krylov
+        subspace. Default is ``10 * k``.
+    compute_u : bool, optional
+        If `True` (default) then compute left singular vectors, `u`.
+    compute_v : bool, optional
+        If `True` (default) then compute right singular vectors, `v`.
+    tol : float, optional
+        The desired relative accuracy for computed singular values.
+        If not specified, it will be set based on machine precision.
+    v0 : array_like, optional
+        Starting vector for iterations: must be of length ``A.shape[0]``.
+        If not specified, PROPACK will generate a starting vector.
+    full_output : bool, optional
+        If `True`, then return sigma_bound.  Default is `False`.
+    delta : float, optional
+        Level of orthogonality to maintain between Lanczos vectors.
+        Default is set based on machine precision.
+    eta : float, optional
+        Orthogonality cutoff.  During reorthogonalization, vectors with
+        component larger than `eta` along the Lanczos vector will be purged.
+        Default is set based on machine precision.
+    anorm : float, optional
+        Estimate of ``||A||``.  Default is ``0``.
+    cgs : bool, optional
+        If `True`, reorthogonalization is done using classical Gram-Schmidt.
+        If `False` (default), it is done using modified Gram-Schmidt.
+    elr : bool, optional
+        If `True` (default), then extended local orthogonality is enforced
+        when obtaining singular vectors.
+    min_relgap : float, optional
+        The smallest relative gap allowed between any shift in IRL mode.
+        Default is ``0.001``.  Accessed only if ``irl_mode=True``.
+    shifts : int, optional
+        Number of shifts per restart in IRL mode.  Default is determined
+        to satisfy ``k <= min(kmax-shifts, m, n)``.  Must be
+        >= 0, but choosing 0 might lead to performance degradation.
+        Accessed only if ``irl_mode=True``.
+    maxiter : int, optional
+        Maximum number of restarts in IRL mode.  Default is ``1000``.
+        Accessed only if ``irl_mode=True``.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    u : ndarray
+        The `k` largest (``which="LM"``) or smallest (``which="SM"``) left
+        singular vectors, ``shape == (A.shape[0], 3)``, returned only if
+        ``compute_u=True``.
+    sigma : ndarray
+        The top `k` singular values, ``shape == (k,)``
+    vt : ndarray
+        The `k` largest (``which="LM"``) or smallest (``which="SM"``) right
+        singular vectors, ``shape == (3, A.shape[1])``, returned only if
+        ``compute_v=True``.
+    sigma_bound : ndarray
+        the error bounds on the singular values sigma, returned only if
+        ``full_output=True``.
+
+    """
+    if rng is None:
+        raise ValueError("`rng` must be a normalized numpy.random.Generator instance")
+
+    which = which.upper()
+    if which not in {'LM', 'SM'}:
+        raise ValueError("`which` must be either 'LM' or 'SM'")
+    if not irl_mode and which == 'SM':
+        raise ValueError("`which`='SM' requires irl_mode=True")
+
+    aprod = _AProd(A)
+    typ = aprod.dtype.char
+
+    try:
+        lansvd_irl = _lansvd_irl_dict[typ]
+        lansvd = _lansvd_dict[typ]
+    except KeyError:
+        # work with non-supported types using native system precision
+        if np.iscomplexobj(np.empty(0, dtype=typ)):
+            typ = np.dtype(complex).char
+        else:
+            typ = np.dtype(float).char
+        lansvd_irl = _lansvd_irl_dict[typ]
+        lansvd = _lansvd_dict[typ]
+
+    m, n = aprod.shape
+    if (k < 1) or (k > min(m, n)):
+        raise ValueError("k must be positive and not greater than m or n")
+
+    if kmax is None:
+        kmax = 10*k
+    if maxiter is None:
+        maxiter = 1000
+
+    # guard against unnecessarily large kmax
+    kmax = min(m + 1, n + 1, kmax)
+    if kmax < k:
+        raise ValueError(
+            "kmax must be greater than or equal to k, "
+            f"but kmax ({kmax}) < k ({k})")
+
+    # convert python args to fortran args
+    jobu = 'y' if compute_u else 'n'
+    jobv = 'y' if compute_v else 'n'
+
+    # these will be the output arrays
+    u = np.zeros((m, kmax + 1), order='F', dtype=typ)
+    v = np.zeros((n, kmax), order='F', dtype=typ)
+
+    # Specify the starting vector.  if v0 is all zero, PROPACK will generate
+    # a random starting vector: the random seed cannot be controlled in that
+    # case, so we'll instead use numpy to generate a random vector
+    if v0 is None:
+        u[:, 0] = rng.uniform(size=m)
+        if np.iscomplexobj(np.empty(0, dtype=typ)):  # complex type
+            u[:, 0] += 1j * rng.uniform(size=m)
+    else:
+        try:
+            u[:, 0] = v0
+        except ValueError:
+            raise ValueError(f"v0 must be of length {m}")
+
+    # process options for the fit
+    if delta is None:
+        delta = np.sqrt(np.finfo(typ).eps)
+    if eta is None:
+        eta = np.finfo(typ).eps ** 0.75
+
+    if irl_mode:
+        doption = np.array((delta, eta, anorm, min_relgap), dtype=typ.lower())
+
+        # validate or find default shifts
+        if shifts is None:
+            shifts = kmax - k
+        if k > min(kmax - shifts, m, n):
+            raise ValueError('shifts must satisfy '
+                             'k <= min(kmax-shifts, m, n)!')
+        elif shifts < 0:
+            raise ValueError('shifts must be >= 0!')
+
+    else:
+        doption = np.array((delta, eta, anorm), dtype=typ.lower())
+
+    ioption = np.array((int(bool(cgs)), int(bool(elr))), dtype='i')
+
+    # If computing `u` or `v` (left and right singular vectors,
+    # respectively), `blocksize` controls how large a fraction of the
+    # work is done via fast BLAS level 3 operations.  A larger blocksize
+    # may lead to faster computation at the expense of greater memory
+    # consumption.  `blocksize` must be ``>= 1``.  Choosing blocksize
+    # of 16, but docs don't specify; it's almost surely a
+    # power of 2.
+    blocksize = 16
+
+    # Determine lwork & liwork:
+    # the required lengths are specified in the PROPACK documentation
+    if compute_u or compute_v:
+        lwork = m + n + 9*kmax + 5*kmax*kmax + 4 + max(
+            3*kmax*kmax + 4*kmax + 4,
+            blocksize*max(m, n))
+        liwork = 8*kmax
+    else:
+        lwork = m + n + 9*kmax + 2*kmax*kmax + 4 + max(m + n, 4*kmax + 4)
+        liwork = 2*kmax + 1
+    work = np.empty(lwork, dtype=typ.lower())
+    iwork = np.empty(liwork, dtype=np.int32)
+
+    # dummy arguments: these are passed to aprod, and not used in this wrapper
+    dparm = np.empty(1, dtype=typ.lower())
+    iparm = np.empty(1, dtype=np.int32)
+
+    if typ.isupper():
+        # PROPACK documentation is unclear on the required length of zwork.
+        # Use the same length Julia's wrapper uses
+        # see https://github.com/JuliaSmoothOptimizers/PROPACK.jl/
+        zwork = np.empty(m + n + 32*m, dtype=typ)
+        works = work, zwork, iwork
+    else:
+        works = work, iwork
+
+    if irl_mode:
+        u, sigma, bnd, v, info = lansvd_irl(_which_converter[which], jobu,
+                                            jobv, m, n, shifts, k, maxiter,
+                                            aprod, u, v, tol, *works, doption,
+                                            ioption, dparm, iparm)
+    else:
+        u, sigma, bnd, v, info = lansvd(jobu, jobv, m, n, k, aprod, u, v, tol,
+                                        *works, doption, ioption, dparm, iparm)
+
+    if info > 0:
+        raise LinAlgError(
+            f"An invariant subspace of dimension {info} was found.")
+    elif info < 0:
+        raise LinAlgError(
+            f"k={k} singular triplets did not converge within "
+            f"kmax={kmax} iterations")
+
+    # info == 0: The K largest (or smallest) singular triplets were computed
+    # successfully!
+
+    return u[:, :k], sigma, v[:, :k].conj().T, bnd
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/dsolve.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/dsolve.py
new file mode 100644
index 0000000000000000000000000000000000000000..45139f6b280d047386652577d9e1c8d2aaeb7033
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/dsolve.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'MatrixRankWarning', 'SuperLU', 'factorized',
+    'spilu', 'splu', 'spsolve',
+    'spsolve_triangular', 'use_solver', 'test'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse.linalg", module="dsolve",
+                                   private_modules=["_dsolve"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/interface.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..24f40f185b1328b16e7e239e5a165cc6b1ed4317
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/interface.py
@@ -0,0 +1,20 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'LinearOperator', 'aslinearoperator',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse.linalg", module="interface",
+                                   private_modules=["_interface"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/matfuncs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ed877ff1aa6f5a5466ce94729b9225dcce37b36
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/matfuncs.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.sparse.linalg` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["expm", "inv", "spsolve", "LinearOperator"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="sparse.linalg", module="matfuncs",
+                                   private_modules=["_matfuncs"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_expm_multiply.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_expm_multiply.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6d3661e99580906501dac66c9960d8d4671137f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_expm_multiply.py
@@ -0,0 +1,367 @@
+"""Test functions for the sparse.linalg._expm_multiply module."""
+from functools import partial
+from itertools import product
+
+import numpy as np
+import pytest
+from numpy.testing import (assert_allclose, assert_, assert_equal,
+                           suppress_warnings)
+from scipy.sparse import SparseEfficiencyWarning
+import scipy.sparse
+from scipy.sparse.linalg import aslinearoperator
+import scipy.linalg
+from scipy.sparse.linalg import expm as sp_expm
+from scipy.sparse.linalg._expm_multiply import (_theta, _compute_p_max,
+        _onenormest_matrix_power, expm_multiply, _expm_multiply_simple,
+        _expm_multiply_interval)
+from scipy._lib._util import np_long
+
+
+IMPRECISE = {np.single, np.csingle}
+REAL_DTYPES = (np.intc, np_long, np.longlong,
+               np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+DTYPES = REAL_DTYPES + COMPLEX_DTYPES
+
+
+def estimated(func):
+    """If trace is estimated, it should warn.
+
+    We warn that estimation of trace might impact performance.
+    All result have to be correct nevertheless!
+
+    """
+    def wrapped(*args, **kwds):
+        with pytest.warns(UserWarning,
+                          match="Trace of LinearOperator not available"):
+            return func(*args, **kwds)
+    return wrapped
+
+
+def less_than_or_close(a, b):
+    return np.allclose(a, b) or (a < b)
+
+
+class TestExpmActionSimple:
+    """
+    These tests do not consider the case of multiple time steps in one call.
+    """
+
+    def test_theta_monotonicity(self):
+        pairs = sorted(_theta.items())
+        for (m_a, theta_a), (m_b, theta_b) in zip(pairs[:-1], pairs[1:]):
+            assert_(theta_a < theta_b)
+
+    def test_p_max_default(self):
+        m_max = 55
+        expected_p_max = 8
+        observed_p_max = _compute_p_max(m_max)
+        assert_equal(observed_p_max, expected_p_max)
+
+    def test_p_max_range(self):
+        for m_max in range(1, 55+1):
+            p_max = _compute_p_max(m_max)
+            assert_(p_max*(p_max - 1) <= m_max + 1)
+            p_too_big = p_max + 1
+            assert_(p_too_big*(p_too_big - 1) > m_max + 1)
+
+    def test_onenormest_matrix_power(self):
+        rng = np.random.RandomState(1234)
+        n = 40
+        nsamples = 10
+        for i in range(nsamples):
+            A = scipy.linalg.inv(rng.randn(n, n))
+            for p in range(4):
+                if not p:
+                    M = np.identity(n)
+                else:
+                    M = np.dot(M, A)
+                estimated = _onenormest_matrix_power(A, p)
+                exact = np.linalg.norm(M, 1)
+                assert_(less_than_or_close(estimated, exact))
+                assert_(less_than_or_close(exact, 3*estimated))
+
+    @pytest.mark.thread_unsafe
+    def test_expm_multiply(self):
+        np.random.seed(1234)
+        n = 40
+        k = 3
+        nsamples = 10
+        for i in range(nsamples):
+            A = scipy.linalg.inv(np.random.randn(n, n))
+            B = np.random.randn(n, k)
+            observed = expm_multiply(A, B)
+            expected = np.dot(sp_expm(A), B)
+            assert_allclose(observed, expected)
+            observed = estimated(expm_multiply)(aslinearoperator(A), B)
+            assert_allclose(observed, expected)
+            traceA = np.trace(A)
+            observed = expm_multiply(aslinearoperator(A), B, traceA=traceA)
+            assert_allclose(observed, expected)
+
+    @pytest.mark.thread_unsafe
+    def test_matrix_vector_multiply(self):
+        np.random.seed(1234)
+        n = 40
+        nsamples = 10
+        for i in range(nsamples):
+            A = scipy.linalg.inv(np.random.randn(n, n))
+            v = np.random.randn(n)
+            observed = expm_multiply(A, v)
+            expected = np.dot(sp_expm(A), v)
+            assert_allclose(observed, expected)
+            observed = estimated(expm_multiply)(aslinearoperator(A), v)
+            assert_allclose(observed, expected)
+
+    @pytest.mark.thread_unsafe
+    def test_scaled_expm_multiply(self):
+        np.random.seed(1234)
+        n = 40
+        k = 3
+        nsamples = 10
+        for i, t in product(range(nsamples), [0.2, 1.0, 1.5]):
+            with np.errstate(invalid='ignore'):
+                A = scipy.linalg.inv(np.random.randn(n, n))
+                B = np.random.randn(n, k)
+                observed = _expm_multiply_simple(A, B, t=t)
+                expected = np.dot(sp_expm(t*A), B)
+                assert_allclose(observed, expected)
+                observed = estimated(_expm_multiply_simple)(
+                    aslinearoperator(A), B, t=t
+                )
+                assert_allclose(observed, expected)
+
+    @pytest.mark.thread_unsafe
+    def test_scaled_expm_multiply_single_timepoint(self):
+        np.random.seed(1234)
+        t = 0.1
+        n = 5
+        k = 2
+        A = np.random.randn(n, n)
+        B = np.random.randn(n, k)
+        observed = _expm_multiply_simple(A, B, t=t)
+        expected = sp_expm(t*A).dot(B)
+        assert_allclose(observed, expected)
+        observed = estimated(_expm_multiply_simple)(
+            aslinearoperator(A), B, t=t
+        )
+        assert_allclose(observed, expected)
+
+    @pytest.mark.thread_unsafe
+    def test_sparse_expm_multiply(self):
+        rng = np.random.default_rng(1234)
+        n = 40
+        k = 3
+        nsamples = 10
+        for i in range(nsamples):
+            A = scipy.sparse.random_array((n, n), density=0.05, rng=rng)
+            B = rng.standard_normal((n, k))
+            observed = expm_multiply(A, B)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning,
+                           "splu converted its input to CSC format")
+                sup.filter(SparseEfficiencyWarning,
+                           "spsolve is more efficient when sparse b is in the"
+                           " CSC matrix format")
+                expected = sp_expm(A).dot(B)
+            assert_allclose(observed, expected)
+            observed = estimated(expm_multiply)(aslinearoperator(A), B)
+            assert_allclose(observed, expected)
+
+    @pytest.mark.thread_unsafe
+    def test_complex(self):
+        A = np.array([
+            [1j, 1j],
+            [0, 1j]], dtype=complex)
+        B = np.array([1j, 1j])
+        observed = expm_multiply(A, B)
+        expected = np.array([
+            1j * np.exp(1j) + 1j * (1j*np.cos(1) - np.sin(1)),
+            1j * np.exp(1j)], dtype=complex)
+        assert_allclose(observed, expected)
+        observed = estimated(expm_multiply)(aslinearoperator(A), B)
+        assert_allclose(observed, expected)
+
+
+class TestExpmActionInterval:
+
+    @pytest.mark.fail_slow(20)
+    def test_sparse_expm_multiply_interval(self):
+        rng = np.random.default_rng(1234)
+        start = 0.1
+        stop = 3.2
+        n = 40
+        k = 3
+        endpoint = True
+        for num in (14, 13, 2):
+            A = scipy.sparse.random_array((n, n), density=0.05, rng=rng)
+            B = rng.standard_normal((n, k))
+            v = rng.standard_normal((n,))
+            for target in (B, v):
+                X = expm_multiply(A, target, start=start, stop=stop,
+                                  num=num, endpoint=endpoint)
+                samples = np.linspace(start=start, stop=stop,
+                                      num=num, endpoint=endpoint)
+                with suppress_warnings() as sup:
+                    sup.filter(SparseEfficiencyWarning,
+                               "splu converted its input to CSC format")
+                    sup.filter(SparseEfficiencyWarning,
+                               "spsolve is more efficient when sparse b is in"
+                               " the CSC matrix format")
+                    for solution, t in zip(X, samples):
+                        assert_allclose(solution, sp_expm(t*A).dot(target))
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.fail_slow(20)
+    def test_expm_multiply_interval_vector(self):
+        np.random.seed(1234)
+        interval = {'start': 0.1, 'stop': 3.2, 'endpoint': True}
+        for num, n in product([14, 13, 2], [1, 2, 5, 20, 40]):
+            A = scipy.linalg.inv(np.random.randn(n, n))
+            v = np.random.randn(n)
+            samples = np.linspace(num=num, **interval)
+            X = expm_multiply(A, v, num=num, **interval)
+            for solution, t in zip(X, samples):
+                assert_allclose(solution, sp_expm(t*A).dot(v))
+            # test for linear operator with unknown trace -> estimate trace
+            Xguess = estimated(expm_multiply)(aslinearoperator(A), v,
+                                              num=num, **interval)
+            # test for linear operator with given trace
+            Xgiven = expm_multiply(aslinearoperator(A), v, num=num, **interval,
+                                   traceA=np.trace(A))
+            # test robustness for linear operator with wrong trace
+            Xwrong = expm_multiply(aslinearoperator(A), v, num=num, **interval,
+                                   traceA=np.trace(A)*5)
+            for sol_guess, sol_given, sol_wrong, t in zip(Xguess, Xgiven,
+                                                          Xwrong, samples):
+                correct = sp_expm(t*A).dot(v)
+                assert_allclose(sol_guess, correct)
+                assert_allclose(sol_given, correct)
+                assert_allclose(sol_wrong, correct)
+
+    @pytest.mark.thread_unsafe
+    @pytest.mark.fail_slow(20)
+    def test_expm_multiply_interval_matrix(self):
+        np.random.seed(1234)
+        interval = {'start': 0.1, 'stop': 3.2, 'endpoint': True}
+        for num, n, k in product([14, 13, 2], [1, 2, 5, 20, 40], [1, 2]):
+            A = scipy.linalg.inv(np.random.randn(n, n))
+            B = np.random.randn(n, k)
+            samples = np.linspace(num=num, **interval)
+            X = expm_multiply(A, B, num=num, **interval)
+            for solution, t in zip(X, samples):
+                assert_allclose(solution, sp_expm(t*A).dot(B))
+            X = estimated(expm_multiply)(aslinearoperator(A), B, num=num,
+                                         **interval)
+            for solution, t in zip(X, samples):
+                assert_allclose(solution, sp_expm(t*A).dot(B))
+
+    def test_sparse_expm_multiply_interval_dtypes(self):
+        # Test A & B int
+        A = scipy.sparse.diags_array(np.arange(5),format='csr', dtype=int)
+        B = np.ones(5, dtype=int)
+        Aexpm = scipy.sparse.diags_array(np.exp(np.arange(5)),format='csr')
+        BI = np.identity(5, dtype=int)
+        BI_sparse = scipy.sparse.csr_array(BI)
+        assert_allclose(expm_multiply(A,B,0,1)[-1], Aexpm.dot(B))
+        assert_allclose(np.diag(expm_multiply(A, BI_sparse, 0, 1)[-1]), Aexpm.dot(B))
+
+        # Test A complex, B int
+        A = scipy.sparse.diags_array(-1j*np.arange(5),format='csr', dtype=complex)
+        B = np.ones(5, dtype=int)
+        Aexpm = scipy.sparse.diags_array(np.exp(-1j*np.arange(5)),format='csr')
+        assert_allclose(expm_multiply(A,B,0,1)[-1], Aexpm.dot(B))
+        assert_allclose(np.diag(expm_multiply(A, BI_sparse, 0, 1)[-1]), Aexpm.dot(B))
+
+        # Test A int, B complex
+        A = scipy.sparse.diags_array(np.arange(5),format='csr', dtype=int)
+        B = np.full(5, 1j, dtype=complex)
+        Aexpm = scipy.sparse.diags_array(np.exp(np.arange(5)),format='csr')
+        assert_allclose(expm_multiply(A,B,0,1)[-1], Aexpm.dot(B))
+        BI = np.identity(5, dtype=complex)*1j
+        assert_allclose(
+            np.diag(expm_multiply(A, scipy.sparse.csr_array(BI), 0, 1)[-1]),
+            Aexpm.dot(B)
+        )
+
+    def test_expm_multiply_interval_status_0(self):
+        self._help_test_specific_expm_interval_status(0)
+
+    def test_expm_multiply_interval_status_1(self):
+        self._help_test_specific_expm_interval_status(1)
+
+    def test_expm_multiply_interval_status_2(self):
+        self._help_test_specific_expm_interval_status(2)
+
+    def _help_test_specific_expm_interval_status(self, target_status):
+        rng = np.random.RandomState(1234)
+        start = 0.1
+        stop = 3.2
+        num = 13
+        endpoint = True
+        n = 5
+        k = 2
+        nrepeats = 10
+        nsuccesses = 0
+        for num in [14, 13, 2] * nrepeats:
+            A = rng.randn(n, n)
+            B = rng.randn(n, k)
+            status = _expm_multiply_interval(A, B,
+                    start=start, stop=stop, num=num, endpoint=endpoint,
+                    status_only=True)
+            if status == target_status:
+                X, status = _expm_multiply_interval(A, B,
+                        start=start, stop=stop, num=num, endpoint=endpoint,
+                        status_only=False)
+                assert_equal(X.shape, (num, n, k))
+                samples = np.linspace(start=start, stop=stop,
+                        num=num, endpoint=endpoint)
+                for solution, t in zip(X, samples):
+                    assert_allclose(solution, sp_expm(t*A).dot(B))
+                nsuccesses += 1
+        if not nsuccesses:
+            msg = 'failed to find a status-' + str(target_status) + ' interval'
+            raise Exception(msg)
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.parametrize("dtype_a", DTYPES)
+@pytest.mark.parametrize("dtype_b", DTYPES)
+@pytest.mark.parametrize("b_is_matrix", [False, True])
+def test_expm_multiply_dtype(dtype_a, dtype_b, b_is_matrix):
+    """Make sure `expm_multiply` handles all numerical dtypes correctly."""
+    assert_allclose_ = (partial(assert_allclose, rtol=1.8e-3, atol=1e-5)
+                        if {dtype_a, dtype_b} & IMPRECISE else assert_allclose)
+    rng = np.random.default_rng(1234)
+    # test data
+    n = 7
+    b_shape = (n, 3) if b_is_matrix else (n, )
+    if dtype_a in REAL_DTYPES:
+        A = scipy.linalg.inv(rng.random([n, n])).astype(dtype_a)
+    else:
+        A = scipy.linalg.inv(
+            rng.random([n, n]) + 1j*rng.random([n, n])
+        ).astype(dtype_a)
+    if dtype_b in REAL_DTYPES:
+        B = (2*rng.random(b_shape)).astype(dtype_b)
+    else:
+        B = (rng.random(b_shape) + 1j*rng.random(b_shape)).astype(dtype_b)
+
+    # single application
+    sol_mat = expm_multiply(A, B)
+    sol_op = estimated(expm_multiply)(aslinearoperator(A), B)
+    direct_sol = np.dot(sp_expm(A), B)
+    assert_allclose_(sol_mat, direct_sol)
+    assert_allclose_(sol_op, direct_sol)
+    sol_op = expm_multiply(aslinearoperator(A), B, traceA=np.trace(A))
+    assert_allclose_(sol_op, direct_sol)
+
+    # for time points
+    interval = {'start': 0.1, 'stop': 3.2, 'num': 13, 'endpoint': True}
+    samples = np.linspace(**interval)
+    X_mat = expm_multiply(A, B, **interval)
+    X_op = estimated(expm_multiply)(aslinearoperator(A), B, **interval)
+    for sol_mat, sol_op, t in zip(X_mat, X_op, samples):
+        direct_sol = sp_expm(t*A).dot(B)
+        assert_allclose_(sol_mat, direct_sol)
+        assert_allclose_(sol_op, direct_sol)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_interface.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_interface.py
new file mode 100644
index 0000000000000000000000000000000000000000..13bbcf16dbfc391a7e1b6fab666221d4c21b4c64
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_interface.py
@@ -0,0 +1,561 @@
+"""Test functions for the sparse.linalg._interface module
+"""
+
+from functools import partial
+from itertools import product
+import operator
+import pytest
+from pytest import raises as assert_raises, warns
+from numpy.testing import assert_, assert_equal
+
+import numpy as np
+import scipy.sparse as sparse
+
+import scipy.sparse.linalg._interface as interface
+from scipy.sparse._sputils import matrix
+from scipy._lib._gcutils import assert_deallocated, IS_PYPY
+
+
+class TestLinearOperator:
+    def setup_method(self):
+        self.A = np.array([[1,2,3],
+                           [4,5,6]])
+        self.B = np.array([[1,2],
+                           [3,4],
+                           [5,6]])
+        self.C = np.array([[1,2],
+                           [3,4]])
+
+    def test_matvec(self):
+        def get_matvecs(A):
+            return [{
+                        'shape': A.shape,
+                        'matvec': lambda x: np.dot(A, x).reshape(A.shape[0]),
+                        'rmatvec': lambda x: np.dot(A.T.conj(),
+                                                    x).reshape(A.shape[1])
+                    },
+                    {
+                        'shape': A.shape,
+                        'matvec': lambda x: np.dot(A, x),
+                        'rmatvec': lambda x: np.dot(A.T.conj(), x),
+                        'rmatmat': lambda x: np.dot(A.T.conj(), x),
+                        'matmat': lambda x: np.dot(A, x)
+                    }]
+
+        for matvecs in get_matvecs(self.A):
+            A = interface.LinearOperator(**matvecs)
+
+            assert_(A.args == ())
+
+            assert_equal(A.matvec(np.array([1,2,3])), [14,32])
+            assert_equal(A.matvec(np.array([[1],[2],[3]])), [[14],[32]])
+            assert_equal(A @ np.array([1,2,3]), [14,32])
+            assert_equal(A @ np.array([[1],[2],[3]]), [[14],[32]])
+            assert_equal(A.dot(np.array([1,2,3])), [14,32])
+            assert_equal(A.dot(np.array([[1],[2],[3]])), [[14],[32]])
+
+            assert_equal(A.matvec(matrix([[1],[2],[3]])), [[14],[32]])
+            assert_equal(A @ matrix([[1],[2],[3]]), [[14],[32]])
+            assert_equal(A.dot(matrix([[1],[2],[3]])), [[14],[32]])
+
+            assert_equal((2*A)@[1,1,1], [12,30])
+            assert_equal((2 * A).rmatvec([1, 1]), [10, 14, 18])
+            assert_equal((2*A).H.matvec([1,1]), [10, 14, 18])
+            assert_equal((2*A).adjoint().matvec([1,1]), [10, 14, 18])
+            assert_equal((2*A)@[[1],[1],[1]], [[12],[30]])
+            assert_equal((2 * A).matmat([[1], [1], [1]]), [[12], [30]])
+            assert_equal((A*2)@[1,1,1], [12,30])
+            assert_equal((A*2)@[[1],[1],[1]], [[12],[30]])
+            assert_equal((2j*A)@[1,1,1], [12j,30j])
+            assert_equal((A+A)@[1,1,1], [12, 30])
+            assert_equal((A + A).rmatvec([1, 1]), [10, 14, 18])
+            assert_equal((A+A).H.matvec([1,1]), [10, 14, 18])
+            assert_equal((A+A).adjoint().matvec([1,1]), [10, 14, 18])
+            assert_equal((A+A)@[[1],[1],[1]], [[12], [30]])
+            assert_equal((A+A).matmat([[1],[1],[1]]), [[12], [30]])
+            assert_equal((-A)@[1,1,1], [-6,-15])
+            assert_equal((-A)@[[1],[1],[1]], [[-6],[-15]])
+            assert_equal((A-A)@[1,1,1], [0,0])
+            assert_equal((A - A) @ [[1], [1], [1]], [[0], [0]])
+
+            X = np.array([[1, 2], [3, 4]])
+            # A_asarray = np.array([[1, 2, 3], [4, 5, 6]])
+            assert_equal((2 * A).rmatmat(X), np.dot((2 * self.A).T, X))
+            assert_equal((A * 2).rmatmat(X), np.dot((self.A * 2).T, X))
+            assert_equal((2j * A).rmatmat(X),
+                         np.dot((2j * self.A).T.conj(), X))
+            assert_equal((A * 2j).rmatmat(X),
+                         np.dot((self.A * 2j).T.conj(), X))
+            assert_equal((A + A).rmatmat(X),
+                         np.dot((self.A + self.A).T, X))
+            assert_equal((A + 2j * A).rmatmat(X),
+                         np.dot((self.A + 2j * self.A).T.conj(), X))
+            assert_equal((-A).rmatmat(X), np.dot((-self.A).T, X))
+            assert_equal((A - A).rmatmat(X),
+                         np.dot((self.A - self.A).T, X))
+            assert_equal((2j * A).rmatmat(2j * X),
+                         np.dot((2j * self.A).T.conj(), 2j * X))
+
+            z = A+A
+            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is A)
+            z = 2*A
+            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] == 2)
+
+            assert_(isinstance(A.matvec([1, 2, 3]), np.ndarray))
+            assert_(isinstance(A.matvec(np.array([[1],[2],[3]])), np.ndarray))
+            assert_(isinstance(A @ np.array([1,2,3]), np.ndarray))
+            assert_(isinstance(A @ np.array([[1],[2],[3]]), np.ndarray))
+            assert_(isinstance(A.dot(np.array([1,2,3])), np.ndarray))
+            assert_(isinstance(A.dot(np.array([[1],[2],[3]])), np.ndarray))
+
+            assert_(isinstance(A.matvec(matrix([[1],[2],[3]])), np.ndarray))
+            assert_(isinstance(A @ matrix([[1],[2],[3]]), np.ndarray))
+            assert_(isinstance(A.dot(matrix([[1],[2],[3]])), np.ndarray))
+
+            assert_(isinstance(2*A, interface._ScaledLinearOperator))
+            assert_(isinstance(2j*A, interface._ScaledLinearOperator))
+            assert_(isinstance(A+A, interface._SumLinearOperator))
+            assert_(isinstance(-A, interface._ScaledLinearOperator))
+            assert_(isinstance(A-A, interface._SumLinearOperator))
+            assert_(isinstance(A/2, interface._ScaledLinearOperator))
+            assert_(isinstance(A/2j, interface._ScaledLinearOperator))
+            assert_(((A * 3) / 3).args[0] is A)  # check for simplification
+
+            # Test that prefactor is of _ScaledLinearOperator is not mutated
+            # when the operator is multiplied by a number
+            result = A @ np.array([1, 2, 3])
+            B = A * 3
+            C = A / 5
+            assert_equal(A @ np.array([1, 2, 3]), result)
+
+            assert_((2j*A).dtype == np.complex128)
+
+            # Test division by non-scalar
+            msg = "Can only divide a linear operator by a scalar."
+            with assert_raises(ValueError, match=msg):
+                A / np.array([1, 2])
+
+            assert_raises(ValueError, A.matvec, np.array([1,2]))
+            assert_raises(ValueError, A.matvec, np.array([1,2,3,4]))
+            assert_raises(ValueError, A.matvec, np.array([[1],[2]]))
+            assert_raises(ValueError, A.matvec, np.array([[1],[2],[3],[4]]))
+
+            assert_raises(ValueError, lambda: A@A)
+            assert_raises(ValueError, lambda: A**2)
+
+        for matvecsA, matvecsB in product(get_matvecs(self.A),
+                                          get_matvecs(self.B)):
+            A = interface.LinearOperator(**matvecsA)
+            B = interface.LinearOperator(**matvecsB)
+            # AtimesB = np.array([[22, 28], [49, 64]])
+            AtimesB = self.A.dot(self.B)
+            X = np.array([[1, 2], [3, 4]])
+
+            assert_equal((A @ B).rmatmat(X), np.dot((AtimesB).T, X))
+            assert_equal((2j * A @ B).rmatmat(X),
+                         np.dot((2j * AtimesB).T.conj(), X))
+
+            assert_equal((A@B)@[1,1], [50,113])
+            assert_equal((A@B)@[[1],[1]], [[50],[113]])
+            assert_equal((A@B).matmat([[1],[1]]), [[50],[113]])
+
+            assert_equal((A @ B).rmatvec([1, 1]), [71, 92])
+            assert_equal((A @ B).H.matvec([1, 1]), [71, 92])
+            assert_equal((A @ B).adjoint().matvec([1, 1]), [71, 92])
+
+            assert_(isinstance(A@B, interface._ProductLinearOperator))
+
+            assert_raises(ValueError, lambda: A+B)
+            assert_raises(ValueError, lambda: A**2)
+
+            z = A@B
+            assert_(len(z.args) == 2 and z.args[0] is A and z.args[1] is B)
+
+        for matvecsC in get_matvecs(self.C):
+            C = interface.LinearOperator(**matvecsC)
+            X = np.array([[1, 2], [3, 4]])
+
+            assert_equal(C.rmatmat(X), np.dot((self.C).T, X))
+            assert_equal((C**2).rmatmat(X),
+                         np.dot((np.dot(self.C, self.C)).T, X))
+
+            assert_equal((C**2)@[1,1], [17,37])
+            assert_equal((C**2).rmatvec([1, 1]), [22, 32])
+            assert_equal((C**2).H.matvec([1, 1]), [22, 32])
+            assert_equal((C**2).adjoint().matvec([1, 1]), [22, 32])
+            assert_equal((C**2).matmat([[1],[1]]), [[17],[37]])
+
+            assert_(isinstance(C**2, interface._PowerLinearOperator))
+
+    def test_matmul(self):
+        D = {'shape': self.A.shape,
+             'matvec': lambda x: np.dot(self.A, x).reshape(self.A.shape[0]),
+             'rmatvec': lambda x: np.dot(self.A.T.conj(),
+                                         x).reshape(self.A.shape[1]),
+             'rmatmat': lambda x: np.dot(self.A.T.conj(), x),
+             'matmat': lambda x: np.dot(self.A, x)}
+        A = interface.LinearOperator(**D)
+        B = np.array([[1 + 1j, 2, 3],
+                      [4, 5, 6],
+                      [7, 8, 9]])
+        b = B[0]
+
+        assert_equal(operator.matmul(A, b), A * b)
+        assert_equal(operator.matmul(A, b.reshape(-1, 1)), A * b.reshape(-1, 1))
+        assert_equal(operator.matmul(A, B), A @ B)
+        assert_equal(operator.matmul(b, A.H), b * A.H)
+        assert_equal(operator.matmul(b, A.adjoint()), b * A.adjoint())
+        assert_equal(operator.matmul(b.reshape(1, -1), A.H), b.reshape(1, -1) * A.H)
+        assert_equal(operator.matmul(b.reshape(1, -1), A.adjoint()),
+                     b.reshape(1, -1) * A.adjoint())
+        assert_equal(operator.matmul(B, A.H), B @ A.H)
+        assert_equal(operator.matmul(B, A.adjoint()), B @ A.adjoint())
+        assert_raises(ValueError, operator.matmul, A, 2)
+        assert_raises(ValueError, operator.matmul, 2, A)
+
+
+class TestAsLinearOperator:
+    def setup_method(self):
+        self.cases = []
+
+        def make_cases(original, dtype):
+            cases = []
+
+            cases.append((matrix(original, dtype=dtype), original))
+            cases.append((np.array(original, dtype=dtype), original))
+            cases.append((sparse.csr_array(original, dtype=dtype), original))
+
+            # Test default implementations of _adjoint and _rmatvec, which
+            # refer to each other.
+            def mv(x, dtype):
+                y = original.dot(x)
+                if len(x.shape) == 2:
+                    y = y.reshape(-1, 1)
+                return y
+
+            def rmv(x, dtype):
+                return original.T.conj().dot(x)
+
+            class BaseMatlike(interface.LinearOperator):
+                args = ()
+
+                def __init__(self, dtype):
+                    self.dtype = np.dtype(dtype)
+                    self.shape = original.shape
+
+                def _matvec(self, x):
+                    return mv(x, self.dtype)
+
+            class HasRmatvec(BaseMatlike):
+                args = ()
+
+                def _rmatvec(self,x):
+                    return rmv(x, self.dtype)
+
+            class HasAdjoint(BaseMatlike):
+                args = ()
+
+                def _adjoint(self):
+                    shape = self.shape[1], self.shape[0]
+                    matvec = partial(rmv, dtype=self.dtype)
+                    rmatvec = partial(mv, dtype=self.dtype)
+                    return interface.LinearOperator(matvec=matvec,
+                                                    rmatvec=rmatvec,
+                                                    dtype=self.dtype,
+                                                    shape=shape)
+
+            class HasRmatmat(HasRmatvec):
+                def _matmat(self, x):
+                    return original.dot(x)
+
+                def _rmatmat(self, x):
+                    return original.T.conj().dot(x)
+
+            cases.append((HasRmatvec(dtype), original))
+            cases.append((HasAdjoint(dtype), original))
+            cases.append((HasRmatmat(dtype), original))
+            return cases
+
+        original = np.array([[1,2,3], [4,5,6]])
+        self.cases += make_cases(original, np.int32)
+        self.cases += make_cases(original, np.float32)
+        self.cases += make_cases(original, np.float64)
+        self.cases += [(interface.aslinearoperator(M).T, A.T)
+                       for M, A in make_cases(original.T, np.float64)]
+        self.cases += [(interface.aslinearoperator(M).H, A.T.conj())
+                       for M, A in make_cases(original.T, np.float64)]
+        self.cases += [(interface.aslinearoperator(M).adjoint(), A.T.conj())
+                       for M, A in make_cases(original.T, np.float64)]
+
+        original = np.array([[1, 2j, 3j], [4j, 5j, 6]])
+        self.cases += make_cases(original, np.complex128)
+        self.cases += [(interface.aslinearoperator(M).T, A.T)
+                       for M, A in make_cases(original.T, np.complex128)]
+        self.cases += [(interface.aslinearoperator(M).H, A.T.conj())
+                       for M, A in make_cases(original.T, np.complex128)]
+        self.cases += [(interface.aslinearoperator(M).adjoint(), A.T.conj())
+                       for M, A in make_cases(original.T, np.complex128)]
+
+    def test_basic(self):
+
+        for M, A_array in self.cases:
+            A = interface.aslinearoperator(M)
+            M,N = A.shape
+
+            xs = [np.array([1, 2, 3]),
+                  np.array([[1], [2], [3]])]
+            ys = [np.array([1, 2]), np.array([[1], [2]])]
+
+            if A.dtype == np.complex128:
+                xs += [np.array([1, 2j, 3j]),
+                       np.array([[1], [2j], [3j]])]
+                ys += [np.array([1, 2j]), np.array([[1], [2j]])]
+
+            x2 = np.array([[1, 4], [2, 5], [3, 6]])
+
+            for x in xs:
+                assert_equal(A.matvec(x), A_array.dot(x))
+                assert_equal(A @ x, A_array.dot(x))
+
+            assert_equal(A.matmat(x2), A_array.dot(x2))
+            assert_equal(A @ x2, A_array.dot(x2))
+
+            for y in ys:
+                assert_equal(A.rmatvec(y), A_array.T.conj().dot(y))
+                assert_equal(A.T.matvec(y), A_array.T.dot(y))
+                assert_equal(A.H.matvec(y), A_array.T.conj().dot(y))
+                assert_equal(A.adjoint().matvec(y), A_array.T.conj().dot(y))
+
+            for y in ys:
+                if y.ndim < 2:
+                    continue
+                assert_equal(A.rmatmat(y), A_array.T.conj().dot(y))
+                assert_equal(A.T.matmat(y), A_array.T.dot(y))
+                assert_equal(A.H.matmat(y), A_array.T.conj().dot(y))
+                assert_equal(A.adjoint().matmat(y), A_array.T.conj().dot(y))
+
+            if hasattr(M,'dtype'):
+                assert_equal(A.dtype, M.dtype)
+
+            assert_(hasattr(A, 'args'))
+
+    def test_dot(self):
+
+        for M, A_array in self.cases:
+            A = interface.aslinearoperator(M)
+            M,N = A.shape
+
+            x0 = np.array([1, 2, 3])
+            x1 = np.array([[1], [2], [3]])
+            x2 = np.array([[1, 4], [2, 5], [3, 6]])
+
+            assert_equal(A.dot(x0), A_array.dot(x0))
+            assert_equal(A.dot(x1), A_array.dot(x1))
+            assert_equal(A.dot(x2), A_array.dot(x2))
+
+
+def test_repr():
+    A = interface.LinearOperator(shape=(1, 1), matvec=lambda x: 1)
+    repr_A = repr(A)
+    assert_('unspecified dtype' not in repr_A, repr_A)
+
+
+def test_identity():
+    ident = interface.IdentityOperator((3, 3))
+    assert_equal(ident @ [1, 2, 3], [1, 2, 3])
+    assert_equal(ident.dot(np.arange(9).reshape(3, 3)).ravel(), np.arange(9))
+
+    assert_raises(ValueError, ident.matvec, [1, 2, 3, 4])
+
+
+def test_attributes():
+    A = interface.aslinearoperator(np.arange(16).reshape(4, 4))
+
+    def always_four_ones(x):
+        x = np.asarray(x)
+        assert_(x.shape == (3,) or x.shape == (3, 1))
+        return np.ones(4)
+
+    B = interface.LinearOperator(shape=(4, 3), matvec=always_four_ones)
+
+    ops = [A, B, A * B, A @ B, A.H, A.adjoint(), A + A, B + B, A**4]
+    for op in ops:
+        assert_(hasattr(op, "dtype"))
+        assert_(hasattr(op, "shape"))
+        assert_(hasattr(op, "_matvec"))
+
+def matvec(x):
+    """ Needed for test_pickle as local functions are not pickleable """
+    return np.zeros(3)
+
+def test_pickle():
+    import pickle
+
+    for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+        A = interface.LinearOperator((3, 3), matvec)
+        s = pickle.dumps(A, protocol=protocol)
+        B = pickle.loads(s)
+
+        for k in A.__dict__:
+            assert_equal(getattr(A, k), getattr(B, k))
+
+
+@pytest.mark.thread_unsafe
+def test_inheritance():
+    class Empty(interface.LinearOperator):
+        pass
+
+    with warns(RuntimeWarning, match="should implement at least"):
+        assert_raises(TypeError, Empty)
+
+    class Identity(interface.LinearOperator):
+        def __init__(self, n):
+            super().__init__(dtype=None, shape=(n, n))
+
+        def _matvec(self, x):
+            return x
+
+    id3 = Identity(3)
+    assert_equal(id3.matvec([1, 2, 3]), [1, 2, 3])
+    assert_raises(NotImplementedError, id3.rmatvec, [4, 5, 6])
+
+    class MatmatOnly(interface.LinearOperator):
+        def __init__(self, A):
+            super().__init__(A.dtype, A.shape)
+            self.A = A
+
+        def _matmat(self, x):
+            return self.A.dot(x)
+
+    mm = MatmatOnly(np.random.randn(5, 3))
+    assert_equal(mm.matvec(np.random.randn(3)).shape, (5,))
+
+def test_dtypes_of_operator_sum():
+    # gh-6078
+
+    mat_complex = np.random.rand(2,2) + 1j * np.random.rand(2,2)
+    mat_real = np.random.rand(2,2)
+
+    complex_operator = interface.aslinearoperator(mat_complex)
+    real_operator = interface.aslinearoperator(mat_real)
+
+    sum_complex = complex_operator + complex_operator
+    sum_real = real_operator + real_operator
+
+    assert_equal(sum_real.dtype, np.float64)
+    assert_equal(sum_complex.dtype, np.complex128)
+
+def test_no_double_init():
+    call_count = [0]
+
+    def matvec(v):
+        call_count[0] += 1
+        return v
+
+    # It should call matvec exactly once (in order to determine the
+    # operator dtype)
+    interface.LinearOperator((2, 2), matvec=matvec)
+    assert_equal(call_count[0], 1)
+
+INT_DTYPES = (np.int8, np.int16, np.int32, np.int64)
+REAL_DTYPES = (np.float32, np.float64, np.longdouble)
+COMPLEX_DTYPES = (np.complex64, np.complex128, np.clongdouble)
+INEXACTDTYPES = REAL_DTYPES + COMPLEX_DTYPES
+ALLDTYPES = INT_DTYPES + INEXACTDTYPES
+
+
+@pytest.mark.parametrize("test_dtype", ALLDTYPES)
+def test_determine_lo_dtype_from_matvec(test_dtype):
+    # gh-19209
+    scalar = np.array(1, dtype=test_dtype)
+    def mv(v):
+        return np.array([scalar * v[0], v[1]])
+
+    lo = interface.LinearOperator((2, 2), matvec=mv)
+    assert lo.dtype == np.dtype(test_dtype)
+
+def test_determine_lo_dtype_for_int():
+    # gh-19209
+    # test Python int larger than int8 max cast to some int
+    def mv(v):
+        return np.array([128 * v[0], v[1]])
+
+    lo = interface.LinearOperator((2, 2), matvec=mv)
+    assert lo.dtype in INT_DTYPES
+
+def test_adjoint_conjugate():
+    X = np.array([[1j]])
+    A = interface.aslinearoperator(X)
+
+    B = 1j * A
+    Y = 1j * X
+
+    v = np.array([1])
+
+    assert_equal(B.dot(v), Y.dot(v))
+    assert_equal(B.H.dot(v), Y.T.conj().dot(v))
+    assert_equal(B.adjoint().dot(v), Y.T.conj().dot(v))
+
+def test_ndim():
+    X = np.array([[1]])
+    A = interface.aslinearoperator(X)
+    assert_equal(A.ndim, 2)
+
+def test_transpose_noconjugate():
+    X = np.array([[1j]])
+    A = interface.aslinearoperator(X)
+
+    B = 1j * A
+    Y = 1j * X
+
+    v = np.array([1])
+
+    assert_equal(B.dot(v), Y.dot(v))
+    assert_equal(B.T.dot(v), Y.T.dot(v))
+
+def test_transpose_multiplication():
+    class MyMatrix(interface.LinearOperator):
+        def __init__(self, A):
+            super().__init__(A.dtype, A.shape)
+            self.A = A
+        def _matmat(self, other): return self.A @ other
+        def _rmatmat(self, other): return self.A.T @ other
+
+    A = MyMatrix(np.array([[1, 2], [3, 4]]))
+    X = np.array([1, 2])
+    B = np.array([[10, 20], [30, 40]])
+    X2 = X.reshape(-1, 1)
+    Y = np.array([[1, 2], [3, 4]])
+
+    assert_equal(A @ B, Y @ B)
+    assert_equal(B.T @ A, B.T @ Y)
+    assert_equal(A.T @ B, Y.T @ B)
+    assert_equal(A @ X, Y @ X)
+    assert_equal(X.T @ A, X.T @ Y)
+    assert_equal(A.T @ X, Y.T @ X)
+    assert_equal(A @ X2, Y @ X2)
+    assert_equal(X2.T @ A, X2.T @ Y)
+    assert_equal(A.T @ X2, Y.T @ X2)
+
+def test_sparse_matmat_exception():
+    A = interface.LinearOperator((2, 2), matvec=lambda x: x)
+    B = sparse.eye_array(2)
+    msg = "Unable to multiply a LinearOperator with a sparse matrix."
+    with assert_raises(TypeError, match=msg):
+        A @ B
+    with assert_raises(TypeError, match=msg):
+        B @ A
+    with assert_raises(ValueError):
+        A @ np.identity(4)
+    with assert_raises(ValueError):
+        np.identity(4) @ A
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_MatrixLinearOperator_refcycle():
+    # gh-10634
+    # Test that MatrixLinearOperator can be automatically garbage collected
+    A = np.eye(2)
+    with assert_deallocated(interface.MatrixLinearOperator, A) as op:
+        op.adjoint()
+        del op
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_matfuncs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_matfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a468c39cad30f6f852cc6df64b98588fa70b5ff
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_matfuncs.py
@@ -0,0 +1,592 @@
+#
+# Created by: Pearu Peterson, March 2002
+#
+""" Test functions for scipy.linalg._matfuncs module
+
+"""
+import math
+
+import numpy as np
+from numpy import array, eye, exp, random
+from numpy.testing import (
+        assert_allclose, assert_, assert_array_almost_equal, assert_equal,
+        assert_array_almost_equal_nulp, suppress_warnings)
+
+from scipy.sparse import csc_array, SparseEfficiencyWarning
+from scipy.sparse._construct import eye_array
+from scipy.sparse.linalg._matfuncs import (expm, _expm,
+        ProductOperator, MatrixPowerOperator,
+        _onenorm_matrix_power_nnm, matrix_power)
+from scipy.sparse._sputils import matrix
+from scipy.linalg import logm
+from scipy.special import factorial, binom
+import scipy.sparse
+import scipy.sparse.linalg
+
+
+def _burkardt_13_power(n, p):
+    """
+    A helper function for testing matrix functions.
+
+    Parameters
+    ----------
+    n : integer greater than 1
+        Order of the square matrix to be returned.
+    p : non-negative integer
+        Power of the matrix.
+
+    Returns
+    -------
+    out : ndarray representing a square matrix
+        A Forsythe matrix of order n, raised to the power p.
+
+    """
+    # Input validation.
+    if n != int(n) or n < 2:
+        raise ValueError('n must be an integer greater than 1')
+    n = int(n)
+    if p != int(p) or p < 0:
+        raise ValueError('p must be a non-negative integer')
+    p = int(p)
+
+    # Construct the matrix explicitly.
+    a, b = divmod(p, n)
+    large = np.power(10.0, -n*a)
+    small = large * np.power(10.0, -n)
+    return np.diag([large]*(n-b), b) + np.diag([small]*b, b-n)
+
+
+def test_onenorm_matrix_power_nnm():
+    np.random.seed(1234)
+    for n in range(1, 5):
+        for p in range(5):
+            M = np.random.random((n, n))
+            Mp = np.linalg.matrix_power(M, p)
+            observed = _onenorm_matrix_power_nnm(M, p)
+            expected = np.linalg.norm(Mp, 1)
+            assert_allclose(observed, expected)
+
+def test_matrix_power():
+    np.random.seed(1234)
+    row, col = np.random.randint(0, 4, size=(2, 6))
+    data = np.random.random(size=(6,))
+    Amat = csc_array((data, (row, col)), shape=(4, 4))
+    A = csc_array((data, (row, col)), shape=(4, 4))
+    Adense = A.toarray()
+    for power in (2, 5, 6):
+        Apow = matrix_power(A, power).toarray()
+        Amat_pow = matrix_power(Amat, power).toarray()
+        Adense_pow = np.linalg.matrix_power(Adense, power)
+        assert_allclose(Apow, Adense_pow)
+        assert_allclose(Apow, Amat_pow)
+
+
+class TestExpM:
+    def test_zero_ndarray(self):
+        a = array([[0.,0],[0,0]])
+        assert_array_almost_equal(expm(a),[[1,0],[0,1]])
+
+    def test_zero_sparse(self):
+        a = csc_array([[0.,0],[0,0]])
+        assert_array_almost_equal(expm(a).toarray(),[[1,0],[0,1]])
+
+    def test_zero_matrix(self):
+        a = matrix([[0.,0],[0,0]])
+        assert_array_almost_equal(expm(a),[[1,0],[0,1]])
+
+    def test_misc_types(self):
+        A = expm(np.array([[1]]))
+        assert_allclose(expm(((1,),)), A)
+        assert_allclose(expm([[1]]), A)
+        assert_allclose(expm(matrix([[1]])), A)
+        assert_allclose(expm(np.array([[1]])), A)
+        assert_allclose(expm(csc_array([[1]])).toarray(), A)
+        B = expm(np.array([[1j]]))
+        assert_allclose(expm(((1j,),)), B)
+        assert_allclose(expm([[1j]]), B)
+        assert_allclose(expm(matrix([[1j]])), B)
+        assert_allclose(expm(csc_array([[1j]])).toarray(), B)
+
+    def test_bidiagonal_sparse(self):
+        A = csc_array([
+            [1, 3, 0],
+            [0, 1, 5],
+            [0, 0, 2]], dtype=float)
+        e1 = math.exp(1)
+        e2 = math.exp(2)
+        expected = np.array([
+            [e1, 3*e1, 15*(e2 - 2*e1)],
+            [0, e1, 5*(e2 - e1)],
+            [0, 0, e2]], dtype=float)
+        observed = expm(A).toarray()
+        assert_array_almost_equal(observed, expected)
+
+    def test_padecases_dtype_float(self):
+        for dtype in [np.float32, np.float64]:
+            for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
+                A = scale * eye(3, dtype=dtype)
+                observed = expm(A)
+                expected = exp(scale, dtype=dtype) * eye(3, dtype=dtype)
+                assert_array_almost_equal_nulp(observed, expected, nulp=100)
+
+    def test_padecases_dtype_complex(self):
+        for dtype in [np.complex64, np.complex128]:
+            for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
+                A = scale * eye(3, dtype=dtype)
+                observed = expm(A)
+                expected = exp(scale, dtype=dtype) * eye(3, dtype=dtype)
+                assert_array_almost_equal_nulp(observed, expected, nulp=100)
+
+    def test_padecases_dtype_sparse_float(self):
+        # float32 and complex64 lead to errors in spsolve/UMFpack
+        dtype = np.float64
+        for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
+            a = scale * eye_array(3, 3, dtype=dtype, format='csc')
+            e = exp(scale, dtype=dtype) * eye(3, dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                exact_onenorm = _expm(a, use_exact_onenorm=True).toarray()
+                inexact_onenorm = _expm(a, use_exact_onenorm=False).toarray()
+            assert_array_almost_equal_nulp(exact_onenorm, e, nulp=100)
+            assert_array_almost_equal_nulp(inexact_onenorm, e, nulp=100)
+
+    def test_padecases_dtype_sparse_complex(self):
+        # float32 and complex64 lead to errors in spsolve/UMFpack
+        dtype = np.complex128
+        for scale in [1e-2, 1e-1, 5e-1, 1, 10]:
+            a = scale * eye_array(3, 3, dtype=dtype, format='csc')
+            e = exp(scale) * eye(3, dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                assert_array_almost_equal_nulp(expm(a).toarray(), e, nulp=100)
+
+    def test_logm_consistency(self):
+        random.seed(1234)
+        for dtype in [np.float64, np.complex128]:
+            for n in range(1, 10):
+                for scale in [1e-4, 1e-3, 1e-2, 1e-1, 1, 1e1, 1e2]:
+                    # make logm(A) be of a given scale
+                    A = (eye(n) + random.rand(n, n) * scale).astype(dtype)
+                    if np.iscomplexobj(A):
+                        A = A + 1j * random.rand(n, n) * scale
+                    assert_array_almost_equal(expm(logm(A)), A)
+
+    def test_integer_matrix(self):
+        Q = np.array([
+            [-3, 1, 1, 1],
+            [1, -3, 1, 1],
+            [1, 1, -3, 1],
+            [1, 1, 1, -3]])
+        assert_allclose(expm(Q), expm(1.0 * Q))
+
+    def test_integer_matrix_2(self):
+        # Check for integer overflows
+        Q = np.array([[-500, 500, 0, 0],
+                      [0, -550, 360, 190],
+                      [0, 630, -630, 0],
+                      [0, 0, 0, 0]], dtype=np.int16)
+        assert_allclose(expm(Q), expm(1.0 * Q))
+
+        Q = csc_array(Q)
+        assert_allclose(expm(Q).toarray(), expm(1.0 * Q).toarray())
+
+    def test_triangularity_perturbation(self):
+        # Experiment (1) of
+        # Awad H. Al-Mohy and Nicholas J. Higham (2012)
+        # Improved Inverse Scaling and Squaring Algorithms
+        # for the Matrix Logarithm.
+        A = np.array([
+            [3.2346e-1, 3e4, 3e4, 3e4],
+            [0, 3.0089e-1, 3e4, 3e4],
+            [0, 0, 3.221e-1, 3e4],
+            [0, 0, 0, 3.0744e-1]],
+            dtype=float)
+        A_logm = np.array([
+            [-1.12867982029050462e+00, 9.61418377142025565e+04,
+             -4.52485573953179264e+09, 2.92496941103871812e+14],
+            [0.00000000000000000e+00, -1.20101052953082288e+00,
+             9.63469687211303099e+04, -4.68104828911105442e+09],
+            [0.00000000000000000e+00, 0.00000000000000000e+00,
+             -1.13289322264498393e+00, 9.53249183094775653e+04],
+            [0.00000000000000000e+00, 0.00000000000000000e+00,
+             0.00000000000000000e+00, -1.17947533272554850e+00]],
+            dtype=float)
+        assert_allclose(expm(A_logm), A, rtol=1e-4)
+
+        # Perturb the upper triangular matrix by tiny amounts,
+        # so that it becomes technically not upper triangular.
+        random.seed(1234)
+        tiny = 1e-17
+        A_logm_perturbed = A_logm.copy()
+        A_logm_perturbed[1, 0] = tiny
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "Ill-conditioned.*")
+            A_expm_logm_perturbed = expm(A_logm_perturbed)
+        rtol = 1e-4
+        atol = 100 * tiny
+        assert_(not np.allclose(A_expm_logm_perturbed, A, rtol=rtol, atol=atol))
+
+    def test_burkardt_1(self):
+        # This matrix is diagonal.
+        # The calculation of the matrix exponential is simple.
+        #
+        # This is the first of a series of matrix exponential tests
+        # collected by John Burkardt from the following sources.
+        #
+        # Alan Laub,
+        # Review of "Linear System Theory" by Joao Hespanha,
+        # SIAM Review,
+        # Volume 52, Number 4, December 2010, pages 779--781.
+        #
+        # Cleve Moler and Charles Van Loan,
+        # Nineteen Dubious Ways to Compute the Exponential of a Matrix,
+        # Twenty-Five Years Later,
+        # SIAM Review,
+        # Volume 45, Number 1, March 2003, pages 3--49.
+        #
+        # Cleve Moler,
+        # Cleve's Corner: A Balancing Act for the Matrix Exponential,
+        # 23 July 2012.
+        #
+        # Robert Ward,
+        # Numerical computation of the matrix exponential
+        # with accuracy estimate,
+        # SIAM Journal on Numerical Analysis,
+        # Volume 14, Number 4, September 1977, pages 600--610.
+        exp1 = np.exp(1)
+        exp2 = np.exp(2)
+        A = np.array([
+            [1, 0],
+            [0, 2],
+            ], dtype=float)
+        desired = np.array([
+            [exp1, 0],
+            [0, exp2],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_2(self):
+        # This matrix is symmetric.
+        # The calculation of the matrix exponential is straightforward.
+        A = np.array([
+            [1, 3],
+            [3, 2],
+            ], dtype=float)
+        desired = np.array([
+            [39.322809708033859, 46.166301438885753],
+            [46.166301438885768, 54.711576854329110],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_3(self):
+        # This example is due to Laub.
+        # This matrix is ill-suited for the Taylor series approach.
+        # As powers of A are computed, the entries blow up too quickly.
+        exp1 = np.exp(1)
+        exp39 = np.exp(39)
+        A = np.array([
+            [0, 1],
+            [-39, -40],
+            ], dtype=float)
+        desired = np.array([
+            [
+                39/(38*exp1) - 1/(38*exp39),
+                -np.expm1(-38) / (38*exp1)],
+            [
+                39*np.expm1(-38) / (38*exp1),
+                -1/(38*exp1) + 39/(38*exp39)],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_4(self):
+        # This example is due to Moler and Van Loan.
+        # The example will cause problems for the series summation approach,
+        # as well as for diagonal Pade approximations.
+        A = np.array([
+            [-49, 24],
+            [-64, 31],
+            ], dtype=float)
+        U = np.array([[3, 1], [4, 2]], dtype=float)
+        V = np.array([[1, -1/2], [-2, 3/2]], dtype=float)
+        w = np.array([-17, -1], dtype=float)
+        desired = np.dot(U * np.exp(w), V)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_5(self):
+        # This example is due to Moler and Van Loan.
+        # This matrix is strictly upper triangular
+        # All powers of A are zero beyond some (low) limit.
+        # This example will cause problems for Pade approximations.
+        A = np.array([
+            [0, 6, 0, 0],
+            [0, 0, 6, 0],
+            [0, 0, 0, 6],
+            [0, 0, 0, 0],
+            ], dtype=float)
+        desired = np.array([
+            [1, 6, 18, 36],
+            [0, 1, 6, 18],
+            [0, 0, 1, 6],
+            [0, 0, 0, 1],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_6(self):
+        # This example is due to Moler and Van Loan.
+        # This matrix does not have a complete set of eigenvectors.
+        # That means the eigenvector approach will fail.
+        exp1 = np.exp(1)
+        A = np.array([
+            [1, 1],
+            [0, 1],
+            ], dtype=float)
+        desired = np.array([
+            [exp1, exp1],
+            [0, exp1],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_7(self):
+        # This example is due to Moler and Van Loan.
+        # This matrix is very close to example 5.
+        # Mathematically, it has a complete set of eigenvectors.
+        # Numerically, however, the calculation will be suspect.
+        exp1 = np.exp(1)
+        eps = np.spacing(1)
+        A = np.array([
+            [1 + eps, 1],
+            [0, 1 - eps],
+            ], dtype=float)
+        desired = np.array([
+            [exp1, exp1],
+            [0, exp1],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_8(self):
+        # This matrix was an example in Wikipedia.
+        exp4 = np.exp(4)
+        exp16 = np.exp(16)
+        A = np.array([
+            [21, 17, 6],
+            [-5, -1, -6],
+            [4, 4, 16],
+            ], dtype=float)
+        desired = np.array([
+            [13*exp16 - exp4, 13*exp16 - 5*exp4, 2*exp16 - 2*exp4],
+            [-9*exp16 + exp4, -9*exp16 + 5*exp4, -2*exp16 + 2*exp4],
+            [16*exp16, 16*exp16, 4*exp16],
+            ], dtype=float) * 0.25
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_9(self):
+        # This matrix is due to the NAG Library.
+        # It is an example for function F01ECF.
+        A = np.array([
+            [1, 2, 2, 2],
+            [3, 1, 1, 2],
+            [3, 2, 1, 2],
+            [3, 3, 3, 1],
+            ], dtype=float)
+        desired = np.array([
+            [740.7038, 610.8500, 542.2743, 549.1753],
+            [731.2510, 603.5524, 535.0884, 542.2743],
+            [823.7630, 679.4257, 603.5524, 610.8500],
+            [998.4355, 823.7630, 731.2510, 740.7038],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_10(self):
+        # This is Ward's example #1.
+        # It is defective and nonderogatory.
+        A = np.array([
+            [4, 2, 0],
+            [1, 4, 1],
+            [1, 1, 4],
+            ], dtype=float)
+        assert_allclose(sorted(scipy.linalg.eigvals(A)), (3, 3, 6))
+        desired = np.array([
+            [147.8666224463699, 183.7651386463682, 71.79703239999647],
+            [127.7810855231823, 183.7651386463682, 91.88256932318415],
+            [127.7810855231824, 163.6796017231806, 111.9681062463718],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_11(self):
+        # This is Ward's example #2.
+        # It is a symmetric matrix.
+        A = np.array([
+            [29.87942128909879, 0.7815750847907159, -2.289519314033932],
+            [0.7815750847907159, 25.72656945571064, 8.680737820540137],
+            [-2.289519314033932, 8.680737820540137, 34.39400925519054],
+            ], dtype=float)
+        assert_allclose(scipy.linalg.eigvalsh(A), (20, 30, 40))
+        desired = np.array([
+             [
+                 5.496313853692378E+15,
+                 -1.823188097200898E+16,
+                 -3.047577080858001E+16],
+             [
+                -1.823188097200899E+16,
+                6.060522870222108E+16,
+                1.012918429302482E+17],
+             [
+                -3.047577080858001E+16,
+                1.012918429302482E+17,
+                1.692944112408493E+17],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_12(self):
+        # This is Ward's example #3.
+        # Ward's algorithm has difficulty estimating the accuracy
+        # of its results.
+        A = np.array([
+            [-131, 19, 18],
+            [-390, 56, 54],
+            [-387, 57, 52],
+            ], dtype=float)
+        assert_allclose(sorted(scipy.linalg.eigvals(A)), (-20, -2, -1))
+        desired = np.array([
+            [-1.509644158793135, 0.3678794391096522, 0.1353352811751005],
+            [-5.632570799891469, 1.471517758499875, 0.4060058435250609],
+            [-4.934938326088363, 1.103638317328798, 0.5413411267617766],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_burkardt_13(self):
+        # This is Ward's example #4.
+        # This is a version of the Forsythe matrix.
+        # The eigenvector problem is badly conditioned.
+        # Ward's algorithm has difficulty estimating the accuracy
+        # of its results for this problem.
+        #
+        # Check the construction of one instance of this family of matrices.
+        A4_actual = _burkardt_13_power(4, 1)
+        A4_desired = [[0, 1, 0, 0],
+                      [0, 0, 1, 0],
+                      [0, 0, 0, 1],
+                      [1e-4, 0, 0, 0]]
+        assert_allclose(A4_actual, A4_desired)
+        # Check the expm for a few instances.
+        for n in (2, 3, 4, 10):
+            # Approximate expm using Taylor series.
+            # This works well for this matrix family
+            # because each matrix in the summation,
+            # even before dividing by the factorial,
+            # is entrywise positive with max entry 10**(-floor(p/n)*n).
+            k = max(1, int(np.ceil(16/n)))
+            desired = np.zeros((n, n), dtype=float)
+            for p in range(n*k):
+                Ap = _burkardt_13_power(n, p)
+                assert_equal(np.min(Ap), 0)
+                assert_allclose(np.max(Ap), np.power(10, -np.floor(p/n)*n))
+                desired += Ap / factorial(p)
+            actual = expm(_burkardt_13_power(n, 1))
+            assert_allclose(actual, desired)
+
+    def test_burkardt_14(self):
+        # This is Moler's example.
+        # This badly scaled matrix caused problems for MATLAB's expm().
+        A = np.array([
+            [0, 1e-8, 0],
+            [-(2e10 + 4e8/6.), -3, 2e10],
+            [200./3., 0, -200./3.],
+            ], dtype=float)
+        desired = np.array([
+            [0.446849468283175, 1.54044157383952e-09, 0.462811453558774],
+            [-5743067.77947947, -0.0152830038686819, -4526542.71278401],
+            [0.447722977849494, 1.54270484519591e-09, 0.463480648837651],
+            ], dtype=float)
+        actual = expm(A)
+        assert_allclose(actual, desired)
+
+    def test_pascal(self):
+        # Test pascal triangle.
+        # Nilpotent exponential, used to trigger a failure (gh-8029)
+
+        for scale in [1.0, 1e-3, 1e-6]:
+            for n in range(0, 80, 3):
+                sc = scale ** np.arange(n, -1, -1)
+                if np.any(sc < 1e-300):
+                    break
+
+                A = np.diag(np.arange(1, n + 1), -1) * scale
+                B = expm(A)
+
+                got = B
+                expected = binom(np.arange(n + 1)[:,None],
+                                 np.arange(n + 1)[None,:]) * sc[None,:] / sc[:,None]
+                atol = 1e-13 * abs(expected).max()
+                assert_allclose(got, expected, atol=atol)
+
+    def test_matrix_input(self):
+        # Large np.matrix inputs should work, gh-5546
+        A = np.zeros((200, 200))
+        A[-1,0] = 1
+        B0 = expm(A)
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning, "the matrix subclass.*")
+            sup.filter(PendingDeprecationWarning, "the matrix subclass.*")
+            B = expm(np.matrix(A))
+        assert_allclose(B, B0)
+
+    def test_exp_sinch_overflow(self):
+        # Check overflow in intermediate steps is fixed (gh-11839)
+        L = np.array([[1.0, -0.5, -0.5, 0.0, 0.0, 0.0, 0.0],
+                      [0.0, 1.0, 0.0, -0.5, -0.5, 0.0, 0.0],
+                      [0.0, 0.0, 1.0, 0.0, 0.0, -0.5, -0.5],
+                      [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+                      [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+                      [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+                      [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]])
+
+        E0 = expm(-L)
+        E1 = expm(-2**11 * L)
+        E2 = E0
+        for j in range(11):
+            E2 = E2 @ E2
+
+        assert_allclose(E1, E2)
+
+
+class TestOperators:
+
+    def test_product_operator(self):
+        random.seed(1234)
+        n = 5
+        k = 2
+        nsamples = 10
+        for i in range(nsamples):
+            A = np.random.randn(n, n)
+            B = np.random.randn(n, n)
+            C = np.random.randn(n, n)
+            D = np.random.randn(n, k)
+            op = ProductOperator(A, B, C)
+            assert_allclose(op.matmat(D), A.dot(B).dot(C).dot(D))
+            assert_allclose(op.T.matmat(D), (A.dot(B).dot(C)).T.dot(D))
+
+    def test_matrix_power_operator(self):
+        random.seed(1234)
+        n = 5
+        k = 2
+        p = 3
+        nsamples = 10
+        for i in range(nsamples):
+            A = np.random.randn(n, n)
+            B = np.random.randn(n, k)
+            op = MatrixPowerOperator(A, p)
+            assert_allclose(op.matmat(B), np.linalg.matrix_power(A, p).dot(B))
+            assert_allclose(op.T.matmat(B), np.linalg.matrix_power(A, p).T.dot(B))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_norm.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_norm.py
new file mode 100644
index 0000000000000000000000000000000000000000..7350f7f61d8d32b24930e063d705031b4e94a419
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_norm.py
@@ -0,0 +1,154 @@
+"""Test functions for the sparse.linalg.norm module
+"""
+
+import pytest
+import numpy as np
+from numpy.linalg import norm as npnorm
+from numpy.testing import assert_allclose, assert_equal
+from pytest import raises as assert_raises
+
+import scipy.sparse
+from scipy.sparse.linalg import norm as spnorm
+
+
+# https://github.com/scipy/scipy/issues/16031
+# https://github.com/scipy/scipy/issues/21690
+def test_sparray_norm():
+    row = np.array([0, 0, 1, 1])
+    col = np.array([0, 1, 2, 3])
+    data = np.array([4, 5, 7, 9])
+    test_arr = scipy.sparse.coo_array((data, (row, col)), shape=(2, 4))
+    test_mat = scipy.sparse.coo_matrix((data, (row, col)), shape=(2, 4))
+    for ord in (1, np.inf, None):
+        for ax in [0, 1, None, (0, 1), (1, 0)]:
+            for A in (test_arr, test_mat):
+                expected = npnorm(A.toarray(), ord=ord, axis=ax)
+                actual = spnorm(A, ord=ord, axis=ax)
+                assert hasattr(actual, "dtype")
+                assert_equal(actual, expected)
+    # test 1d array and 1d-like (column) matrix
+    test_arr_1d = scipy.sparse.coo_array((data, (col,)), shape=(4,))
+    test_mat_col = scipy.sparse.coo_matrix((data, (col, [0, 0, 0, 0])), shape=(4, 1))
+    for ord in (1, np.inf, None):
+        for ax in [0, None]:
+            for A in (test_arr_1d, test_mat_col):
+                expected = npnorm(A.toarray(), ord=ord, axis=ax)
+                assert_equal(spnorm(A, ord=ord, axis=ax), expected)
+
+
+class TestNorm:
+    def setup_method(self):
+        a = np.arange(9) - 4
+        b = a.reshape((3, 3))
+        self.b = scipy.sparse.csr_array(b)
+
+    @pytest.mark.thread_unsafe
+    def test_matrix_norm(self):
+
+        # Frobenius norm is the default
+        assert_allclose(spnorm(self.b), 7.745966692414834)
+        assert_allclose(spnorm(self.b, 'fro'), 7.745966692414834)
+
+        assert_allclose(spnorm(self.b, np.inf), 9)
+        assert_allclose(spnorm(self.b, -np.inf), 2)
+        assert_allclose(spnorm(self.b, 1), 7)
+        assert_allclose(spnorm(self.b, -1), 6)
+        # Only floating or complex floating dtype supported by svds.
+        with pytest.warns(UserWarning, match="The problem size"):
+            assert_allclose(spnorm(self.b.astype(np.float64), 2),
+                            7.348469228349534)
+
+        # _multi_svd_norm is not implemented for sparse array
+        assert_raises(NotImplementedError, spnorm, self.b, -2)
+
+    def test_matrix_norm_axis(self):
+        for m, axis in ((self.b, None), (self.b, (0, 1)), (self.b.T, (1, 0))):
+            assert_allclose(spnorm(m, axis=axis), 7.745966692414834)
+            assert_allclose(spnorm(m, 'fro', axis=axis), 7.745966692414834)
+            assert_allclose(spnorm(m, np.inf, axis=axis), 9)
+            assert_allclose(spnorm(m, -np.inf, axis=axis), 2)
+            assert_allclose(spnorm(m, 1, axis=axis), 7)
+            assert_allclose(spnorm(m, -1, axis=axis), 6)
+
+    def test_vector_norm(self):
+        v = [4.5825756949558398, 4.2426406871192848, 4.5825756949558398]
+        for m, a in (self.b, 0), (self.b.T, 1):
+            for axis in a, (a, ), a-2, (a-2, ):
+                assert_allclose(spnorm(m, 1, axis=axis), [7, 6, 7])
+                assert_allclose(spnorm(m, np.inf, axis=axis), [4, 3, 4])
+                assert_allclose(spnorm(m, axis=axis), v)
+                assert_allclose(spnorm(m, ord=2, axis=axis), v)
+                assert_allclose(spnorm(m, ord=None, axis=axis), v)
+
+    def test_norm_exceptions(self):
+        m = self.b
+        assert_raises(TypeError, spnorm, m, None, 1.5)
+        assert_raises(TypeError, spnorm, m, None, [2])
+        assert_raises(ValueError, spnorm, m, None, ())
+        assert_raises(ValueError, spnorm, m, None, (0, 1, 2))
+        assert_raises(ValueError, spnorm, m, None, (0, 0))
+        assert_raises(ValueError, spnorm, m, None, (0, 2))
+        assert_raises(ValueError, spnorm, m, None, (-3, 0))
+        assert_raises(ValueError, spnorm, m, None, 2)
+        assert_raises(ValueError, spnorm, m, None, -3)
+        assert_raises(ValueError, spnorm, m, 'plate_of_shrimp', 0)
+        assert_raises(ValueError, spnorm, m, 'plate_of_shrimp', (0, 1))
+
+
+class TestVsNumpyNorm:
+    _sparse_types = (
+            scipy.sparse.bsr_array,
+            scipy.sparse.coo_array,
+            scipy.sparse.csc_array,
+            scipy.sparse.csr_array,
+            scipy.sparse.dia_array,
+            scipy.sparse.dok_array,
+            scipy.sparse.lil_array,
+            )
+    _test_matrices = (
+            (np.arange(9) - 4).reshape((3, 3)),
+            [
+                [1, 2, 3],
+                [-1, 1, 4]],
+            [
+                [1, 0, 3],
+                [-1, 1, 4j]],
+            )
+
+    def test_sparse_matrix_norms(self):
+        for sparse_type in self._sparse_types:
+            for M in self._test_matrices:
+                S = sparse_type(M)
+                assert_allclose(spnorm(S), npnorm(M))
+                assert_allclose(spnorm(S, 'fro'), npnorm(M, 'fro'))
+                assert_allclose(spnorm(S, np.inf), npnorm(M, np.inf))
+                assert_allclose(spnorm(S, -np.inf), npnorm(M, -np.inf))
+                assert_allclose(spnorm(S, 1), npnorm(M, 1))
+                assert_allclose(spnorm(S, -1), npnorm(M, -1))
+
+    def test_sparse_matrix_norms_with_axis(self):
+        for sparse_type in self._sparse_types:
+            for M in self._test_matrices:
+                S = sparse_type(M)
+                for axis in None, (0, 1), (1, 0):
+                    assert_allclose(spnorm(S, axis=axis), npnorm(M, axis=axis))
+                    for ord in 'fro', np.inf, -np.inf, 1, -1:
+                        assert_allclose(spnorm(S, ord, axis=axis),
+                                        npnorm(M, ord, axis=axis))
+                # Some numpy matrix norms are allergic to negative axes.
+                for axis in (-2, -1), (-1, -2), (1, -2):
+                    assert_allclose(spnorm(S, axis=axis), npnorm(M, axis=axis))
+                    assert_allclose(spnorm(S, 'f', axis=axis),
+                                    npnorm(M, 'f', axis=axis))
+                    assert_allclose(spnorm(S, 'fro', axis=axis),
+                                    npnorm(M, 'fro', axis=axis))
+
+    def test_sparse_vector_norms(self):
+        for sparse_type in self._sparse_types:
+            for M in self._test_matrices:
+                S = sparse_type(M)
+                for axis in (0, 1, -1, -2, (0, ), (1, ), (-1, ), (-2, )):
+                    assert_allclose(spnorm(S, axis=axis), npnorm(M, axis=axis))
+                    for ord in None, 2, np.inf, -np.inf, 1, 0.5, 0.42:
+                        assert_allclose(spnorm(S, ord, axis=axis),
+                                        npnorm(M, ord, axis=axis))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_onenormest.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_onenormest.py
new file mode 100644
index 0000000000000000000000000000000000000000..d306e8177568d8db31189a5c67b5862e37e8a0fc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_onenormest.py
@@ -0,0 +1,252 @@
+"""Test functions for the sparse.linalg._onenormest module
+"""
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, assert_
+import pytest
+import scipy.linalg
+import scipy.sparse.linalg
+from scipy.sparse.linalg._onenormest import _onenormest_core, _algorithm_2_2
+
+
+class MatrixProductOperator(scipy.sparse.linalg.LinearOperator):
+    """
+    This is purely for onenormest testing.
+    """
+
+    def __init__(self, A, B):
+        if A.ndim != 2 or B.ndim != 2:
+            raise ValueError('expected ndarrays representing matrices')
+        if A.shape[1] != B.shape[0]:
+            raise ValueError('incompatible shapes')
+        self.A = A
+        self.B = B
+        self.ndim = 2
+        self.shape = (A.shape[0], B.shape[1])
+
+    def _matvec(self, x):
+        return np.dot(self.A, np.dot(self.B, x))
+
+    def _rmatvec(self, x):
+        return np.dot(np.dot(x, self.A), self.B)
+
+    def _matmat(self, X):
+        return np.dot(self.A, np.dot(self.B, X))
+
+    @property
+    def T(self):
+        return MatrixProductOperator(self.B.T, self.A.T)
+
+
+class TestOnenormest:
+
+    @pytest.mark.xslow
+    def test_onenormest_table_3_t_2(self):
+        # This will take multiple seconds if your computer is slow like mine.
+        # It is stochastic, so the tolerance could be too strict.
+        np.random.seed(1234)
+        t = 2
+        n = 100
+        itmax = 5
+        nsamples = 5000
+        observed = []
+        expected = []
+        nmult_list = []
+        nresample_list = []
+        for i in range(nsamples):
+            A = scipy.linalg.inv(np.random.randn(n, n))
+            est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)
+            observed.append(est)
+            expected.append(scipy.linalg.norm(A, 1))
+            nmult_list.append(nmults)
+            nresample_list.append(nresamples)
+        observed = np.array(observed, dtype=float)
+        expected = np.array(expected, dtype=float)
+        relative_errors = np.abs(observed - expected) / expected
+
+        # check the mean underestimation ratio
+        underestimation_ratio = observed / expected
+        assert_(0.99 < np.mean(underestimation_ratio) < 1.0)
+
+        # check the max and mean required column resamples
+        assert_equal(np.max(nresample_list), 2)
+        assert_(0.05 < np.mean(nresample_list) < 0.2)
+
+        # check the proportion of norms computed exactly correctly
+        nexact = np.count_nonzero(relative_errors < 1e-14)
+        proportion_exact = nexact / float(nsamples)
+        assert_(0.9 < proportion_exact < 0.95)
+
+        # check the average number of matrix*vector multiplications
+        assert_(3.5 < np.mean(nmult_list) < 4.5)
+
+    @pytest.mark.xslow
+    def test_onenormest_table_4_t_7(self):
+        # This will take multiple seconds if your computer is slow like mine.
+        # It is stochastic, so the tolerance could be too strict.
+        np.random.seed(1234)
+        t = 7
+        n = 100
+        itmax = 5
+        nsamples = 5000
+        observed = []
+        expected = []
+        nmult_list = []
+        nresample_list = []
+        for i in range(nsamples):
+            A = np.random.randint(-1, 2, size=(n, n))
+            est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)
+            observed.append(est)
+            expected.append(scipy.linalg.norm(A, 1))
+            nmult_list.append(nmults)
+            nresample_list.append(nresamples)
+        observed = np.array(observed, dtype=float)
+        expected = np.array(expected, dtype=float)
+        relative_errors = np.abs(observed - expected) / expected
+
+        # check the mean underestimation ratio
+        underestimation_ratio = observed / expected
+        assert_(0.90 < np.mean(underestimation_ratio) < 0.99)
+
+        # check the required column resamples
+        assert_equal(np.max(nresample_list), 0)
+
+        # check the proportion of norms computed exactly correctly
+        nexact = np.count_nonzero(relative_errors < 1e-14)
+        proportion_exact = nexact / float(nsamples)
+        assert_(0.15 < proportion_exact < 0.25)
+
+        # check the average number of matrix*vector multiplications
+        assert_(3.5 < np.mean(nmult_list) < 4.5)
+
+    def test_onenormest_table_5_t_1(self):
+        # "note that there is no randomness and hence only one estimate for t=1"
+        t = 1
+        n = 100
+        itmax = 5
+        alpha = 1 - 1e-6
+        A = -scipy.linalg.inv(np.identity(n) + alpha*np.eye(n, k=1))
+        first_col = np.array([1] + [0]*(n-1))
+        first_row = np.array([(-alpha)**i for i in range(n)])
+        B = -scipy.linalg.toeplitz(first_col, first_row)
+        assert_allclose(A, B)
+        est, v, w, nmults, nresamples = _onenormest_core(B, B.T, t, itmax)
+        exact_value = scipy.linalg.norm(B, 1)
+        underest_ratio = est / exact_value
+        assert_allclose(underest_ratio, 0.05, rtol=1e-4)
+        assert_equal(nmults, 11)
+        assert_equal(nresamples, 0)
+        # check the non-underscored version of onenormest
+        est_plain = scipy.sparse.linalg.onenormest(B, t=t, itmax=itmax)
+        assert_allclose(est, est_plain)
+
+    @pytest.mark.xslow
+    def test_onenormest_table_6_t_2(self):
+        #TODO this test seems to give estimates that match the table,
+        #TODO even though no attempt has been made to deal with
+        #TODO complex numbers in the one-norm estimation.
+        # This will take multiple seconds if your computer is slow like mine.
+        # It is stochastic, so the tolerance could be too strict.
+        np.random.seed(1234)
+        t = 2
+        n = 100
+        itmax = 5
+        nsamples = 5000
+        observed = []
+        expected = []
+        nmult_list = []
+        nresample_list = []
+        for i in range(nsamples):
+            A_inv = np.random.rand(n, n) + 1j * np.random.rand(n, n)
+            A = scipy.linalg.inv(A_inv)
+            est, v, w, nmults, nresamples = _onenormest_core(A, A.T, t, itmax)
+            observed.append(est)
+            expected.append(scipy.linalg.norm(A, 1))
+            nmult_list.append(nmults)
+            nresample_list.append(nresamples)
+        observed = np.array(observed, dtype=float)
+        expected = np.array(expected, dtype=float)
+        relative_errors = np.abs(observed - expected) / expected
+
+        # check the mean underestimation ratio
+        underestimation_ratio = observed / expected
+        underestimation_ratio_mean = np.mean(underestimation_ratio)
+        assert_(0.90 < underestimation_ratio_mean < 0.99)
+
+        # check the required column resamples
+        max_nresamples = np.max(nresample_list)
+        assert_equal(max_nresamples, 0)
+
+        # check the proportion of norms computed exactly correctly
+        nexact = np.count_nonzero(relative_errors < 1e-14)
+        proportion_exact = nexact / float(nsamples)
+        assert_(0.7 < proportion_exact < 0.8)
+
+        # check the average number of matrix*vector multiplications
+        mean_nmult = np.mean(nmult_list)
+        assert_(4 < mean_nmult < 5)
+
+    def _help_product_norm_slow(self, A, B):
+        # for profiling
+        C = np.dot(A, B)
+        return scipy.linalg.norm(C, 1)
+
+    def _help_product_norm_fast(self, A, B):
+        # for profiling
+        t = 2
+        itmax = 5
+        D = MatrixProductOperator(A, B)
+        est, v, w, nmults, nresamples = _onenormest_core(D, D.T, t, itmax)
+        return est
+
+    @pytest.mark.slow
+    def test_onenormest_linear_operator(self):
+        # Define a matrix through its product A B.
+        # Depending on the shapes of A and B,
+        # it could be easy to multiply this product by a small matrix,
+        # but it could be annoying to look at all of
+        # the entries of the product explicitly.
+        np.random.seed(1234)
+        n = 6000
+        k = 3
+        A = np.random.randn(n, k)
+        B = np.random.randn(k, n)
+        fast_estimate = self._help_product_norm_fast(A, B)
+        exact_value = self._help_product_norm_slow(A, B)
+        assert_(fast_estimate <= exact_value <= 3*fast_estimate,
+                f'fast: {fast_estimate:g}\nexact:{exact_value:g}')
+
+    def test_returns(self):
+        np.random.seed(1234)
+        A = scipy.sparse.rand(50, 50, 0.1)
+
+        s0 = scipy.linalg.norm(A.toarray(), 1)
+        s1, v = scipy.sparse.linalg.onenormest(A, compute_v=True)
+        s2, w = scipy.sparse.linalg.onenormest(A, compute_w=True)
+        s3, v2, w2 = scipy.sparse.linalg.onenormest(A, compute_w=True, compute_v=True)
+
+        assert_allclose(s1, s0, rtol=1e-9)
+        assert_allclose(np.linalg.norm(A.dot(v), 1), s0*np.linalg.norm(v, 1), rtol=1e-9)
+        assert_allclose(A.dot(v), w, rtol=1e-9)
+
+
+class TestAlgorithm_2_2:
+
+    @pytest.mark.thread_unsafe
+    def test_randn_inv(self):
+        rng = np.random.RandomState(1234)
+        n = 20
+        nsamples = 100
+        for i in range(nsamples):
+
+            # Choose integer t uniformly between 1 and 3 inclusive.
+            t = rng.randint(1, 4)
+
+            # Choose n uniformly between 10 and 40 inclusive.
+            n = rng.randint(10, 41)
+
+            # Sample the inverse of a matrix with random normal entries.
+            A = scipy.linalg.inv(rng.randn(n, n))
+
+            # Compute the 1-norm bounds.
+            g, ind = _algorithm_2_2(A, A.T, t)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_propack.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_propack.py
new file mode 100644
index 0000000000000000000000000000000000000000..f13905de08470a410b5aa83d33b6e29ec87e905c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_propack.py
@@ -0,0 +1,165 @@
+import os
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+from pytest import raises as assert_raises
+from scipy.sparse.linalg._svdp import _svdp
+from scipy.sparse import csr_array, csc_array
+
+
+# dtype_flavour to tolerance
+TOLS = {
+    np.float32: 1e-4,
+    np.float64: 1e-8,
+    np.complex64: 1e-4,
+    np.complex128: 1e-8,
+}
+
+
+def is_complex_type(dtype):
+    return np.dtype(dtype).kind == "c"
+
+
+_dtypes = []
+for dtype_flavour in TOLS.keys():
+    marks = []
+    if is_complex_type(dtype_flavour):
+        marks = [pytest.mark.slow]
+    _dtypes.append(pytest.param(dtype_flavour, marks=marks,
+                                id=dtype_flavour.__name__))
+_dtypes = tuple(_dtypes)  # type: ignore[assignment]
+
+
+def generate_matrix(constructor, n, m, f,
+                    dtype=float, rseed=0, **kwargs):
+    """Generate a random sparse array"""
+    rng = np.random.RandomState(rseed)
+    if is_complex_type(dtype):
+        M = (- 5 + 10 * rng.rand(n, m)
+             - 5j + 10j * rng.rand(n, m)).astype(dtype)
+    else:
+        M = (-5 + 10 * rng.rand(n, m)).astype(dtype)
+    M[M.real > 10 * f - 5] = 0
+    return constructor(M, **kwargs)
+
+
+def assert_orthogonal(u1, u2, rtol, atol):
+    """Check that the first k rows of u1 and u2 are orthogonal"""
+    A = abs(np.dot(u1.conj().T, u2))
+    assert_allclose(A, np.eye(u1.shape[1], u2.shape[1]), rtol=rtol, atol=atol)
+
+
+def check_svdp(n, m, constructor, dtype, k, irl_mode, which, f=0.8):
+    tol = TOLS[dtype]
+
+    M = generate_matrix(np.asarray, n, m, f, dtype)
+    Msp = constructor(M)
+
+    u1, sigma1, vt1 = np.linalg.svd(M, full_matrices=False)
+    u2, sigma2, vt2, _ = _svdp(Msp, k=k, which=which, irl_mode=irl_mode,
+                               tol=tol, rng=np.random.default_rng(0))
+
+    # check the which
+    if which.upper() == 'SM':
+        u1 = np.roll(u1, k, 1)
+        vt1 = np.roll(vt1, k, 0)
+        sigma1 = np.roll(sigma1, k)
+
+    # check that singular values agree
+    assert_allclose(sigma1[:k], sigma2, rtol=tol, atol=tol)
+
+    # check that singular vectors are orthogonal
+    assert_orthogonal(u1, u2, rtol=tol, atol=tol)
+    assert_orthogonal(vt1.T, vt2.T, rtol=tol, atol=tol)
+
+
+@pytest.mark.parametrize('ctor', (np.array, csr_array, csc_array))
+@pytest.mark.parametrize('dtype', _dtypes)
+@pytest.mark.parametrize('irl', (True, False))
+@pytest.mark.parametrize('which', ('LM', 'SM'))
+def test_svdp(ctor, dtype, irl, which):
+    np.random.seed(0)
+    n, m, k = 10, 20, 3
+    if which == 'SM' and not irl:
+        message = "`which`='SM' requires irl_mode=True"
+        with assert_raises(ValueError, match=message):
+            check_svdp(n, m, ctor, dtype, k, irl, which)
+    else:
+        check_svdp(n, m, ctor, dtype, k, irl, which)
+
+
+@pytest.mark.xslow
+@pytest.mark.parametrize('dtype', _dtypes)
+@pytest.mark.parametrize('irl', (False, True))
+def test_examples(dtype, irl):
+    # Note: atol for complex64 bumped from 1e-4 to 1e-3 due to test failures
+    # with BLIS, Netlib, and MKL+AVX512 - see
+    # https://github.com/conda-forge/scipy-feedstock/pull/198#issuecomment-999180432
+    atol = {
+        np.float32: 1.3e-4,
+        np.float64: 1e-9,
+        np.complex64: 1e-3,
+        np.complex128: 1e-9,
+    }[dtype]
+
+    path_prefix = os.path.dirname(__file__)
+    # Test matrices from `illc1850.coord` and `mhd1280b.cua` distributed with
+    # PROPACK 2.1: http://sun.stanford.edu/~rmunk/PROPACK/
+    relative_path = "propack_test_data.npz"
+    filename = os.path.join(path_prefix, relative_path)
+    with np.load(filename, allow_pickle=True) as data:
+        if is_complex_type(dtype):
+            A = data['A_complex'].item().astype(dtype)
+        else:
+            A = data['A_real'].item().astype(dtype)
+
+    k = 200
+    u, s, vh, _ = _svdp(A, k, irl_mode=irl, rng=np.random.default_rng(0))
+
+    # complex example matrix has many repeated singular values, so check only
+    # beginning non-repeated singular vectors to avoid permutations
+    sv_check = 27 if is_complex_type(dtype) else k
+    u = u[:, :sv_check]
+    vh = vh[:sv_check, :]
+    s = s[:sv_check]
+
+    # Check orthogonality of singular vectors
+    assert_allclose(np.eye(u.shape[1]), u.conj().T @ u, atol=atol)
+    assert_allclose(np.eye(vh.shape[0]), vh @ vh.conj().T, atol=atol)
+
+    # Ensure the norm of the difference between the np.linalg.svd and
+    # PROPACK reconstructed matrices is small
+    u3, s3, vh3 = np.linalg.svd(A.todense())
+    u3 = u3[:, :sv_check]
+    s3 = s3[:sv_check]
+    vh3 = vh3[:sv_check, :]
+    A3 = u3 @ np.diag(s3) @ vh3
+    recon = u @ np.diag(s) @ vh
+    assert_allclose(np.linalg.norm(A3 - recon), 0, atol=atol)
+
+
+@pytest.mark.parametrize('shifts', (None, -10, 0, 1, 10, 70))
+@pytest.mark.parametrize('dtype', _dtypes[:2])
+def test_shifts(shifts, dtype):
+    rng = np.random.default_rng(0)
+    n, k = 70, 10
+    A = rng.random((n, n))
+    if shifts is not None and ((shifts < 0) or (k > min(n-1-shifts, n))):
+        with pytest.raises(ValueError):
+            _svdp(A, k, shifts=shifts, kmax=5*k, irl_mode=True, rng=rng)
+    else:
+        _svdp(A, k, shifts=shifts, kmax=5*k, irl_mode=True, rng=rng)
+
+
+@pytest.mark.slow
+@pytest.mark.xfail()
+def test_shifts_accuracy():
+    rng = np.random.default_rng(0)
+    n, k = 70, 10
+    A = rng.random((n, n)).astype(np.float64)
+    u1, s1, vt1, _ = _svdp(A, k, shifts=None, which='SM', irl_mode=True, rng=rng)
+    u2, s2, vt2, _ = _svdp(A, k, shifts=32, which='SM', irl_mode=True, rng=rng)
+    # shifts <= 32 doesn't agree with shifts > 32
+    # Does agree when which='LM' instead of 'SM'
+    assert_allclose(s1, s2)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_pydata_sparse.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_pydata_sparse.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6b855271063ee769c70095c62dd8a09bd05bd95
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_pydata_sparse.py
@@ -0,0 +1,258 @@
+import pytest
+
+import numpy as np
+import scipy.sparse as sp
+import scipy.sparse.linalg as splin
+
+from numpy.testing import assert_allclose, assert_equal
+
+try:
+    import sparse
+except Exception:
+    sparse = None
+
+pytestmark = pytest.mark.skipif(sparse is None,
+                                reason="pydata/sparse not installed")
+
+
+msg = "pydata/sparse (0.15.1) does not implement necessary operations"
+
+
+sparse_params = (pytest.param("COO"),
+                 pytest.param("DOK", marks=[pytest.mark.xfail(reason=msg)]))
+
+scipy_sparse_classes = [
+    sp.bsr_array,
+    sp.csr_array,
+    sp.coo_array,
+    sp.csc_array,
+    sp.dia_array,
+    sp.dok_array
+]
+
+
+@pytest.fixture(params=sparse_params)
+def sparse_cls(request):
+    return getattr(sparse, request.param)
+
+
+@pytest.fixture(params=scipy_sparse_classes)
+def sp_sparse_cls(request):
+    return request.param
+
+
+@pytest.fixture
+def same_matrix(sparse_cls, sp_sparse_cls):
+    np.random.seed(1234)
+    A_dense = np.random.rand(9, 9)
+    return sp_sparse_cls(A_dense), sparse_cls(A_dense)
+
+
+@pytest.fixture
+def matrices(sparse_cls):
+    np.random.seed(1234)
+    A_dense = np.random.rand(9, 9)
+    A_dense = A_dense @ A_dense.T
+    A_sparse = sparse_cls(A_dense)
+    b = np.random.rand(9)
+    return A_dense, A_sparse, b
+
+
+def test_isolve_gmres(matrices):
+    # Several of the iterative solvers use the same
+    # isolve.utils.make_system wrapper code, so test just one of them.
+    A_dense, A_sparse, b = matrices
+    x, info = splin.gmres(A_sparse, b, atol=1e-15)
+    assert info == 0
+    assert isinstance(x, np.ndarray)
+    assert_allclose(A_sparse @ x, b)
+
+
+def test_lsmr(matrices):
+    A_dense, A_sparse, b = matrices
+    res0 = splin.lsmr(A_dense, b)
+    res = splin.lsmr(A_sparse, b)
+    assert_allclose(res[0], res0[0], atol=1e-3)
+
+
+# test issue 17012
+def test_lsmr_output_shape():
+    x = splin.lsmr(A=np.ones((10, 1)), b=np.zeros(10), x0=np.ones(1))[0]
+    assert_equal(x.shape, (1,))
+
+
+def test_lsqr(matrices):
+    A_dense, A_sparse, b = matrices
+    res0 = splin.lsqr(A_dense, b)
+    res = splin.lsqr(A_sparse, b)
+    assert_allclose(res[0], res0[0], atol=1e-5)
+
+
+def test_eigs(matrices):
+    A_dense, A_sparse, v0 = matrices
+
+    M_dense = np.diag(v0**2)
+    M_sparse = A_sparse.__class__(M_dense)
+
+    w_dense, v_dense = splin.eigs(A_dense, k=3, v0=v0)
+    w, v = splin.eigs(A_sparse, k=3, v0=v0)
+
+    assert_allclose(w, w_dense)
+    assert_allclose(v, v_dense)
+
+    for M in [M_sparse, M_dense]:
+        w_dense, v_dense = splin.eigs(A_dense, M=M_dense, k=3, v0=v0)
+        w, v = splin.eigs(A_sparse, M=M, k=3, v0=v0)
+
+        assert_allclose(w, w_dense)
+        assert_allclose(v, v_dense)
+
+        w_dense, v_dense = splin.eigsh(A_dense, M=M_dense, k=3, v0=v0)
+        w, v = splin.eigsh(A_sparse, M=M, k=3, v0=v0)
+
+        assert_allclose(w, w_dense)
+        assert_allclose(v, v_dense)
+
+
+def test_svds(matrices):
+    A_dense, A_sparse, v0 = matrices
+
+    u0, s0, vt0 = splin.svds(A_dense, k=2, v0=v0)
+    u, s, vt = splin.svds(A_sparse, k=2, v0=v0)
+
+    assert_allclose(s, s0)
+    assert_allclose(np.abs(u), np.abs(u0))
+    assert_allclose(np.abs(vt), np.abs(vt0))
+
+
+def test_lobpcg(matrices):
+    A_dense, A_sparse, x = matrices
+    X = x[:,None]
+
+    w_dense, v_dense = splin.lobpcg(A_dense, X)
+    w, v = splin.lobpcg(A_sparse, X)
+
+    assert_allclose(w, w_dense)
+    assert_allclose(v, v_dense)
+
+
+def test_spsolve(matrices):
+    A_dense, A_sparse, b = matrices
+    b2 = np.random.rand(len(b), 3)
+
+    x0 = splin.spsolve(sp.csc_array(A_dense), b)
+    x = splin.spsolve(A_sparse, b)
+    assert isinstance(x, np.ndarray)
+    assert_allclose(x, x0)
+
+    x0 = splin.spsolve(sp.csc_array(A_dense), b)
+    x = splin.spsolve(A_sparse, b, use_umfpack=True)
+    assert isinstance(x, np.ndarray)
+    assert_allclose(x, x0)
+
+    x0 = splin.spsolve(sp.csc_array(A_dense), b2)
+    x = splin.spsolve(A_sparse, b2)
+    assert isinstance(x, np.ndarray)
+    assert_allclose(x, x0)
+
+    x0 = splin.spsolve(sp.csc_array(A_dense),
+                       sp.csc_array(A_dense))
+    x = splin.spsolve(A_sparse, A_sparse)
+    assert isinstance(x, type(A_sparse))
+    assert_allclose(x.todense(), x0.todense())
+
+
+def test_splu(matrices):
+    A_dense, A_sparse, b = matrices
+    n = len(b)
+    sparse_cls = type(A_sparse)
+
+    lu = splin.splu(A_sparse)
+
+    assert isinstance(lu.L, sparse_cls)
+    assert isinstance(lu.U, sparse_cls)
+
+    _Pr_scipy = sp.csc_array((np.ones(n), (lu.perm_r, np.arange(n))))
+    _Pc_scipy = sp.csc_array((np.ones(n), (np.arange(n), lu.perm_c)))
+    Pr = sparse_cls.from_scipy_sparse(_Pr_scipy)
+    Pc = sparse_cls.from_scipy_sparse(_Pc_scipy)
+    A2 = Pr.T @ lu.L @ lu.U @ Pc.T
+
+    assert_allclose(A2.todense(), A_sparse.todense())
+
+    z = lu.solve(A_sparse.todense())
+    assert_allclose(z, np.eye(n), atol=1e-10)
+
+
+def test_spilu(matrices):
+    A_dense, A_sparse, b = matrices
+    sparse_cls = type(A_sparse)
+
+    lu = splin.spilu(A_sparse)
+
+    assert isinstance(lu.L, sparse_cls)
+    assert isinstance(lu.U, sparse_cls)
+
+    z = lu.solve(A_sparse.todense())
+    assert_allclose(z, np.eye(len(b)), atol=1e-3)
+
+
+def test_spsolve_triangular(matrices):
+    A_dense, A_sparse, b = matrices
+    A_sparse = sparse.tril(A_sparse)
+
+    x = splin.spsolve_triangular(A_sparse, b)
+    assert_allclose(A_sparse @ x, b)
+
+
+def test_onenormest(matrices):
+    A_dense, A_sparse, b = matrices
+    est0 = splin.onenormest(A_dense)
+    est = splin.onenormest(A_sparse)
+    assert_allclose(est, est0)
+
+
+def test_norm(matrices):
+    A_dense, A_sparse, b = matrices
+    norm0 = splin.norm(sp.csr_array(A_dense))
+    norm = splin.norm(A_sparse)
+    assert_allclose(norm, norm0)
+
+
+def test_inv(matrices):
+    A_dense, A_sparse, b = matrices
+    x0 = splin.inv(sp.csc_array(A_dense))
+    x = splin.inv(A_sparse)
+    assert_allclose(x.todense(), x0.todense())
+
+
+def test_expm(matrices):
+    A_dense, A_sparse, b = matrices
+    x0 = splin.expm(sp.csc_array(A_dense))
+    x = splin.expm(A_sparse)
+    assert_allclose(x.todense(), x0.todense())
+
+
+def test_expm_multiply(matrices):
+    A_dense, A_sparse, b = matrices
+    x0 = splin.expm_multiply(A_dense, b)
+    x = splin.expm_multiply(A_sparse, b)
+    assert_allclose(x, x0)
+
+    x0 = splin.expm_multiply(A_dense, A_dense)
+    x = splin.expm_multiply(A_sparse, A_sparse)
+    assert_allclose(x.todense(), x0)
+
+
+def test_eq(same_matrix):
+    sp_sparse, pd_sparse = same_matrix
+    # temporary splint until pydata sparse support sparray equality
+    sp_sparse = sp.coo_matrix(sp_sparse).asformat(sp_sparse.format)
+    assert (sp_sparse == pd_sparse).all()
+
+
+def test_ne(same_matrix):
+    sp_sparse, pd_sparse = same_matrix
+    # temporary splint until pydata sparse support sparray equality
+    sp_sparse = sp.coo_matrix(sp_sparse).asformat(sp_sparse.format)
+    assert not (sp_sparse != pd_sparse).any()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_special_sparse_arrays.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_special_sparse_arrays.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9d1c4001af6697233380edf0047409a41847834
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/linalg/tests/test_special_sparse_arrays.py
@@ -0,0 +1,337 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_array_equal, assert_allclose
+
+from scipy.sparse import diags, csgraph
+from scipy.linalg import eigh
+
+from scipy.sparse.linalg import LaplacianNd
+from scipy.sparse.linalg._special_sparse_arrays import Sakurai
+from scipy.sparse.linalg._special_sparse_arrays import MikotaPair
+
+INT_DTYPES = [np.int8, np.int16, np.int32, np.int64]
+REAL_DTYPES = [np.float32, np.float64]
+COMPLEX_DTYPES = [np.complex64, np.complex128]
+ALLDTYPES = INT_DTYPES + REAL_DTYPES + COMPLEX_DTYPES
+
+
+class TestLaplacianNd:
+    """
+    LaplacianNd tests
+    """
+
+    @pytest.mark.parametrize('bc', ['neumann', 'dirichlet', 'periodic'])
+    def test_1d_specific_shape(self, bc):
+        lap = LaplacianNd(grid_shape=(6, ), boundary_conditions=bc)
+        lapa = lap.toarray()
+        if bc == 'neumann':
+            a = np.array(
+                [
+                    [-1, 1, 0, 0, 0, 0],
+                    [1, -2, 1, 0, 0, 0],
+                    [0, 1, -2, 1, 0, 0],
+                    [0, 0, 1, -2, 1, 0],
+                    [0, 0, 0, 1, -2, 1],
+                    [0, 0, 0, 0, 1, -1],
+                ]
+            )
+        elif bc == 'dirichlet':
+            a = np.array(
+                [
+                    [-2, 1, 0, 0, 0, 0],
+                    [1, -2, 1, 0, 0, 0],
+                    [0, 1, -2, 1, 0, 0],
+                    [0, 0, 1, -2, 1, 0],
+                    [0, 0, 0, 1, -2, 1],
+                    [0, 0, 0, 0, 1, -2],
+                ]
+            )
+        else:
+            a = np.array(
+                [
+                    [-2, 1, 0, 0, 0, 1],
+                    [1, -2, 1, 0, 0, 0],
+                    [0, 1, -2, 1, 0, 0],
+                    [0, 0, 1, -2, 1, 0],
+                    [0, 0, 0, 1, -2, 1],
+                    [1, 0, 0, 0, 1, -2],
+                ]
+            )
+        assert_array_equal(a, lapa)
+
+    def test_1d_with_graph_laplacian(self):
+        n = 6
+        G = diags(np.ones(n - 1), 1, format='dia')
+        Lf = csgraph.laplacian(G, symmetrized=True, form='function')
+        La = csgraph.laplacian(G, symmetrized=True, form='array')
+        grid_shape = (n,)
+        bc = 'neumann'
+        lap = LaplacianNd(grid_shape, boundary_conditions=bc)
+        assert_array_equal(lap(np.eye(n)), -Lf(np.eye(n)))
+        assert_array_equal(lap.toarray(), -La.toarray())
+        # https://github.com/numpy/numpy/issues/24351
+        assert_array_equal(lap.tosparse().toarray(), -La.toarray())
+
+    @pytest.mark.parametrize('grid_shape', [(6, ), (2, 3), (2, 3, 4)])
+    @pytest.mark.parametrize('bc', ['neumann', 'dirichlet', 'periodic'])
+    def test_eigenvalues(self, grid_shape, bc):
+        lap = LaplacianNd(grid_shape, boundary_conditions=bc, dtype=np.float64)
+        L = lap.toarray()
+        eigvals = eigh(L, eigvals_only=True)
+        n = np.prod(grid_shape)
+        eigenvalues = lap.eigenvalues()
+        dtype = eigenvalues.dtype
+        atol = n * n * np.finfo(dtype).eps
+        # test the default ``m = None``
+        assert_allclose(eigenvalues, eigvals, atol=atol)
+        # test every ``m > 0``
+        for m in np.arange(1, n + 1):
+            assert_array_equal(lap.eigenvalues(m), eigenvalues[-m:])
+
+    @pytest.mark.parametrize('grid_shape', [(6, ), (2, 3), (2, 3, 4)])
+    @pytest.mark.parametrize('bc', ['neumann', 'dirichlet', 'periodic'])
+    def test_eigenvectors(self, grid_shape, bc):
+        lap = LaplacianNd(grid_shape, boundary_conditions=bc, dtype=np.float64)
+        n = np.prod(grid_shape)
+        eigenvalues = lap.eigenvalues()
+        eigenvectors = lap.eigenvectors()
+        dtype = eigenvectors.dtype
+        atol = n * n * max(np.finfo(dtype).eps, np.finfo(np.double).eps)
+        # test the default ``m = None`` every individual eigenvector
+        for i in np.arange(n):
+            r = lap.toarray() @ eigenvectors[:, i] - eigenvectors[:, i] * eigenvalues[i]
+            assert_allclose(r, np.zeros_like(r), atol=atol)
+        # test every ``m > 0``
+        for m in np.arange(1, n + 1):
+            e = lap.eigenvalues(m)
+            ev = lap.eigenvectors(m)
+            r = lap.toarray() @ ev - ev @ np.diag(e)
+            assert_allclose(r, np.zeros_like(r), atol=atol)
+
+    @pytest.mark.parametrize('grid_shape', [(6, ), (2, 3), (2, 3, 4)])
+    @pytest.mark.parametrize('bc', ['neumann', 'dirichlet', 'periodic'])
+    def test_toarray_tosparse_consistency(self, grid_shape, bc):
+        lap = LaplacianNd(grid_shape, boundary_conditions=bc)
+        n = np.prod(grid_shape)
+        assert_array_equal(lap.toarray(), lap(np.eye(n)))
+        assert_array_equal(lap.tosparse().toarray(), lap.toarray())
+
+    @pytest.mark.parametrize('dtype', ALLDTYPES)
+    @pytest.mark.parametrize('grid_shape', [(6, ), (2, 3), (2, 3, 4)])
+    @pytest.mark.parametrize('bc', ['neumann', 'dirichlet', 'periodic'])
+    def test_linearoperator_shape_dtype(self, grid_shape, bc, dtype):
+        lap = LaplacianNd(grid_shape, boundary_conditions=bc, dtype=dtype)
+        n = np.prod(grid_shape)
+        assert lap.shape == (n, n)
+        assert lap.dtype == dtype
+        assert_array_equal(
+            LaplacianNd(
+                grid_shape, boundary_conditions=bc, dtype=dtype
+            ).toarray(),
+            LaplacianNd(grid_shape, boundary_conditions=bc)
+            .toarray()
+            .astype(dtype),
+        )
+        assert_array_equal(
+            LaplacianNd(grid_shape, boundary_conditions=bc, dtype=dtype)
+            .tosparse()
+            .toarray(),
+            LaplacianNd(grid_shape, boundary_conditions=bc)
+            .tosparse()
+            .toarray()
+            .astype(dtype),
+        )
+
+    @pytest.mark.parametrize('dtype', ALLDTYPES)
+    @pytest.mark.parametrize('grid_shape', [(6, ), (2, 3), (2, 3, 4)])
+    @pytest.mark.parametrize('bc', ['neumann', 'dirichlet', 'periodic'])
+    def test_dot(self, grid_shape, bc, dtype):
+        """ Test the dot-product for type preservation and consistency.
+        """
+        lap = LaplacianNd(grid_shape, boundary_conditions=bc)
+        n = np.prod(grid_shape)
+        x0 = np.arange(n)
+        x1 = x0.reshape((-1, 1))
+        x2 = np.arange(2 * n).reshape((n, 2))
+        input_set = [x0, x1, x2]
+        for x in input_set:
+            y = lap.dot(x.astype(dtype))
+            assert x.shape == y.shape
+            assert y.dtype == dtype
+            if x.ndim == 2:
+                yy = lap.toarray() @ x.astype(dtype)
+                assert yy.dtype == dtype
+                np.array_equal(y, yy)
+
+    def test_boundary_conditions_value_error(self):
+        with pytest.raises(ValueError, match="Unknown value 'robin'"):
+            LaplacianNd(grid_shape=(6, ), boundary_conditions='robin')
+
+            
+class TestSakurai:
+    """
+    Sakurai tests
+    """
+
+    def test_specific_shape(self):
+        sak = Sakurai(6)
+        assert_array_equal(sak.toarray(), sak(np.eye(6)))
+        a = np.array(
+            [
+                [ 5, -4,  1,  0,  0,  0],
+                [-4,  6, -4,  1,  0,  0],
+                [ 1, -4,  6, -4,  1,  0],
+                [ 0,  1, -4,  6, -4,  1],
+                [ 0,  0,  1, -4,  6, -4],
+                [ 0,  0,  0,  1, -4,  5]
+            ]
+        )
+
+        np.array_equal(a, sak.toarray())
+        np.array_equal(sak.tosparse().toarray(), sak.toarray())
+        ab = np.array(
+            [
+                [ 1,  1,  1,  1,  1,  1],
+                [-4, -4, -4, -4, -4, -4],
+                [ 5,  6,  6,  6,  6,  5]
+            ]
+        )
+        np.array_equal(ab, sak.tobanded())
+        e = np.array(
+                [0.03922866, 0.56703972, 2.41789479, 5.97822974,
+                 10.54287655, 14.45473055]
+            )
+        np.array_equal(e, sak.eigenvalues())
+        np.array_equal(e[:2], sak.eigenvalues(2))
+
+    # `Sakurai` default `dtype` is `np.int8` as its entries are small integers
+    @pytest.mark.parametrize('dtype', ALLDTYPES)
+    def test_linearoperator_shape_dtype(self, dtype):
+        n = 7
+        sak = Sakurai(n, dtype=dtype)
+        assert sak.shape == (n, n)
+        assert sak.dtype == dtype
+        assert_array_equal(sak.toarray(), Sakurai(n).toarray().astype(dtype))
+        assert_array_equal(sak.tosparse().toarray(),
+                           Sakurai(n).tosparse().toarray().astype(dtype))
+
+    @pytest.mark.parametrize('dtype', ALLDTYPES)
+    @pytest.mark.parametrize('argument_dtype', ALLDTYPES)
+    def test_dot(self, dtype, argument_dtype):
+        """ Test the dot-product for type preservation and consistency.
+        """
+        result_dtype = np.promote_types(argument_dtype, dtype)
+        n = 5
+        sak = Sakurai(n)
+        x0 = np.arange(n)
+        x1 = x0.reshape((-1, 1))
+        x2 = np.arange(2 * n).reshape((n, 2))
+        input_set = [x0, x1, x2]
+        for x in input_set:
+            y = sak.dot(x.astype(argument_dtype))
+            assert x.shape == y.shape
+            assert np.can_cast(y.dtype, result_dtype)
+            if x.ndim == 2:
+                ya = sak.toarray() @ x.astype(argument_dtype)
+                np.array_equal(y, ya)
+                assert np.can_cast(ya.dtype, result_dtype)
+                ys = sak.tosparse() @ x.astype(argument_dtype)
+                np.array_equal(y, ys)
+                assert np.can_cast(ys.dtype, result_dtype)
+
+class TestMikotaPair:
+    """
+    MikotaPair tests
+    """
+    # both MikotaPair `LinearOperator`s share the same dtype
+    # while `MikotaK` `dtype` can be as small as its default `np.int32`
+    # since its entries are integers, the `MikotaM` involves inverses
+    # so its smallest still accurate `dtype` is `np.float32`
+    tested_types = REAL_DTYPES + COMPLEX_DTYPES
+
+    def test_specific_shape(self):
+        n = 6
+        mik = MikotaPair(n)
+        mik_k = mik.k
+        mik_m = mik.m
+        assert_array_equal(mik_k.toarray(), mik_k(np.eye(n)))
+        assert_array_equal(mik_m.toarray(), mik_m(np.eye(n)))
+
+        k = np.array(
+            [
+                [11, -5,  0,  0,  0,  0],
+                [-5,  9, -4,  0,  0,  0],
+                [ 0, -4,  7, -3,  0,  0],
+                [ 0,  0, -3,  5, -2,  0],
+                [ 0,  0,  0, -2,  3, -1],
+                [ 0,  0,  0,  0, -1,  1]
+            ]
+        )
+        np.array_equal(k, mik_k.toarray())
+        np.array_equal(mik_k.tosparse().toarray(), k)
+        kb = np.array(
+            [
+                [ 0, -5, -4, -3, -2, -1],
+                [11,  9,  7,  5,  3,  1]
+            ]
+        )
+        np.array_equal(kb, mik_k.tobanded())
+
+        minv = np.arange(1, n + 1)
+        np.array_equal(np.diag(1. / minv), mik_m.toarray())
+        np.array_equal(mik_m.tosparse().toarray(), mik_m.toarray())
+        np.array_equal(1. / minv, mik_m.tobanded())
+
+        e = np.array([ 1,  4,  9, 16, 25, 36])
+        np.array_equal(e, mik.eigenvalues())
+        np.array_equal(e[:2], mik.eigenvalues(2))
+
+    @pytest.mark.parametrize('dtype', tested_types)
+    def test_linearoperator_shape_dtype(self, dtype):
+        n = 7
+        mik = MikotaPair(n, dtype=dtype)
+        mik_k = mik.k
+        mik_m = mik.m
+        assert mik_k.shape == (n, n)
+        assert mik_k.dtype == dtype
+        assert mik_m.shape == (n, n)
+        assert mik_m.dtype == dtype
+        mik_default_dtype = MikotaPair(n)
+        mikd_k = mik_default_dtype.k
+        mikd_m = mik_default_dtype.m
+        assert mikd_k.shape == (n, n)
+        assert mikd_k.dtype == np.float64
+        assert mikd_m.shape == (n, n)
+        assert mikd_m.dtype == np.float64
+        assert_array_equal(mik_k.toarray(),
+                           mikd_k.toarray().astype(dtype))
+        assert_array_equal(mik_k.tosparse().toarray(),
+                           mikd_k.tosparse().toarray().astype(dtype))
+
+    @pytest.mark.parametrize('dtype', tested_types)
+    @pytest.mark.parametrize('argument_dtype', ALLDTYPES)
+    def test_dot(self, dtype, argument_dtype):
+        """ Test the dot-product for type preservation and consistency.
+        """
+        result_dtype = np.promote_types(argument_dtype, dtype)
+        n = 5
+        mik = MikotaPair(n, dtype=dtype)
+        mik_k = mik.k
+        mik_m = mik.m
+        x0 = np.arange(n)
+        x1 = x0.reshape((-1, 1))
+        x2 = np.arange(2 * n).reshape((n, 2))
+        lo_set = [mik_k, mik_m]
+        input_set = [x0, x1, x2]
+        for lo in lo_set:
+            for x in input_set:
+                y = lo.dot(x.astype(argument_dtype))
+                assert x.shape == y.shape
+                assert np.can_cast(y.dtype, result_dtype)
+                if x.ndim == 2:
+                    ya = lo.toarray() @ x.astype(argument_dtype)
+                    np.array_equal(y, ya)
+                    assert np.can_cast(ya.dtype, result_dtype)
+                    ys = lo.tosparse() @ x.astype(argument_dtype)
+                    np.array_equal(y, ys)
+                    assert np.can_cast(ys.dtype, result_dtype)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d5d2ee2f1bc2c3fef03c71fc0206cd06f3f8618
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_arithmetic1d.py
@@ -0,0 +1,338 @@
+"""Test of 1D arithmetic operations"""
+
+import pytest
+
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+
+from scipy.sparse import coo_array, csr_array
+from scipy.sparse._sputils import isscalarlike
+
+
+spcreators = [coo_array, csr_array]
+math_dtypes = [np.int64, np.float64, np.complex128]
+
+
+def toarray(a):
+    if isinstance(a, np.ndarray) or isscalarlike(a):
+        return a
+    return a.toarray()
+
+@pytest.fixture
+def dat1d():
+    return np.array([3, 0, 1, 0], 'd')
+
+
+@pytest.fixture
+def datsp_math_dtypes(dat1d):
+    dat_dtypes = {dtype: dat1d.astype(dtype) for dtype in math_dtypes}
+    return {
+        sp: [(dtype, dat, sp(dat)) for dtype, dat in dat_dtypes.items()]
+        for sp in spcreators
+    }
+
+
+@pytest.mark.parametrize("spcreator", spcreators)
+class TestArithmetic1D:
+    def test_empty_arithmetic(self, spcreator):
+        shape = (5,)
+        for mytype in [
+            np.dtype('int32'),
+            np.dtype('float32'),
+            np.dtype('float64'),
+            np.dtype('complex64'),
+            np.dtype('complex128'),
+        ]:
+            a = spcreator(shape, dtype=mytype)
+            b = a + a
+            c = 2 * a
+            assert isinstance(a @ a.tocsr(), np.ndarray)
+            assert isinstance(a @ a.tocoo(), np.ndarray)
+            for m in [a, b, c]:
+                assert m @ m == a.toarray() @ a.toarray()
+                assert m.dtype == mytype
+                assert toarray(m).dtype == mytype
+
+    def test_abs(self, spcreator):
+        A = np.array([-1, 0, 17, 0, -5, 0, 1, -4, 0, 0, 0, 0], 'd')
+        assert_equal(abs(A), abs(spcreator(A)).toarray())
+
+    def test_round(self, spcreator):
+        A = np.array([-1.35, 0.56, 17.25, -5.98], 'd')
+        Asp = spcreator(A)
+        assert_equal(np.around(A, decimals=1), round(Asp, ndigits=1).toarray())
+
+    def test_elementwise_power(self, spcreator):
+        A = np.array([-4, -3, -2, -1, 0, 1, 2, 3, 4], 'd')
+        Asp = spcreator(A)
+        assert_equal(np.power(A, 2), Asp.power(2).toarray())
+
+        # element-wise power function needs a scalar power
+        with pytest.raises(NotImplementedError, match='input is not scalar'):
+            spcreator(A).power(A)
+
+    def test_real(self, spcreator):
+        D = np.array([1 + 3j, 2 - 4j])
+        A = spcreator(D)
+        assert_equal(A.real.toarray(), D.real)
+
+    def test_imag(self, spcreator):
+        D = np.array([1 + 3j, 2 - 4j])
+        A = spcreator(D)
+        assert_equal(A.imag.toarray(), D.imag)
+
+    def test_mul_scalar(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            assert_equal(dat * 2, (datsp * 2).toarray())
+            assert_equal(dat * 17.3, (datsp * 17.3).toarray())
+
+    def test_rmul_scalar(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            assert_equal(2 * dat, (2 * datsp).toarray())
+            assert_equal(17.3 * dat, (17.3 * datsp).toarray())
+
+    def test_sub(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            assert_equal((datsp - datsp).toarray(), np.zeros(4))
+            assert_equal((datsp - 0).toarray(), dat)
+
+            A = spcreator([1, -4, 0, 2], dtype='d')
+            assert_equal((datsp - A).toarray(), dat - A.toarray())
+            assert_equal((A - datsp).toarray(), A.toarray() - dat)
+
+            # test broadcasting
+            assert_equal(datsp.toarray() - dat[0], dat - dat[0])
+
+    def test_add0(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            # Adding 0 to a sparse matrix
+            assert_equal((datsp + 0).toarray(), dat)
+            # use sum (which takes 0 as a starting value)
+            sumS = sum([k * datsp for k in range(1, 3)])
+            sumD = sum([k * dat for k in range(1, 3)])
+            assert_allclose(sumS.toarray(), sumD)
+
+    def test_elementwise_multiply(self, spcreator):
+        # real/real
+        A = np.array([4, 0, 9])
+        B = np.array([0, 7, -1])
+        Asp = spcreator(A)
+        Bsp = spcreator(B)
+        assert_allclose(Asp.multiply(Bsp).toarray(), A * B)  # sparse/sparse
+        assert_allclose(Asp.multiply(B).toarray(), A * B)  # sparse/dense
+
+        # complex/complex
+        C = np.array([1 - 2j, 0 + 5j, -1 + 0j])
+        D = np.array([5 + 2j, 7 - 3j, -2 + 1j])
+        Csp = spcreator(C)
+        Dsp = spcreator(D)
+        assert_allclose(Csp.multiply(Dsp).toarray(), C * D)  # sparse/sparse
+        assert_allclose(Csp.multiply(D).toarray(), C * D)  # sparse/dense
+
+        # real/complex
+        assert_allclose(Asp.multiply(Dsp).toarray(), A * D)  # sparse/sparse
+        assert_allclose(Asp.multiply(D).toarray(), A * D)  # sparse/dense
+
+    def test_elementwise_multiply_broadcast(self, spcreator):
+        A = np.array([4])
+        B = np.array([[-9]])
+        C = np.array([1, -1, 0])
+        D = np.array([[7, 9, -9]])
+        E = np.array([[3], [2], [1]])
+        F = np.array([[8, 6, 3], [-4, 3, 2], [6, 6, 6]])
+        G = [1, 2, 3]
+        H = np.ones((3, 4))
+        J = H.T
+        K = np.array([[0]])
+        L = np.array([[[1, 2], [0, 1]]])
+
+        # Some arrays can't be cast as spmatrices (A, C, L) so leave
+        # them out.
+        Asp = spcreator(A)
+        Csp = spcreator(C)
+        Gsp = spcreator(G)
+        # 2d arrays
+        Bsp = spcreator(B)
+        Dsp = spcreator(D)
+        Esp = spcreator(E)
+        Fsp = spcreator(F)
+        Hsp = spcreator(H)
+        Hspp = spcreator(H[0, None])
+        Jsp = spcreator(J)
+        Jspp = spcreator(J[:, 0, None])
+        Ksp = spcreator(K)
+
+        matrices = [A, B, C, D, E, F, G, H, J, K, L]
+        spmatrices = [Asp, Bsp, Csp, Dsp, Esp, Fsp, Gsp, Hsp, Hspp, Jsp, Jspp, Ksp]
+        sp1dmatrices = [Asp, Csp, Gsp]
+
+        # sparse/sparse
+        for i in sp1dmatrices:
+            for j in spmatrices:
+                try:
+                    dense_mult = i.toarray() * j.toarray()
+                except ValueError:
+                    with pytest.raises(ValueError, match='inconsistent shapes'):
+                        i.multiply(j)
+                    continue
+                sp_mult = i.multiply(j)
+                assert_allclose(sp_mult.toarray(), dense_mult)
+
+        # sparse/dense
+        for i in sp1dmatrices:
+            for j in matrices:
+                try:
+                    dense_mult = i.toarray() * j
+                except TypeError:
+                    continue
+                except ValueError:
+                    matchme = 'broadcast together|inconsistent shapes'
+                    with pytest.raises(ValueError, match=matchme):
+                        i.multiply(j)
+                    continue
+                sp_mult = i.multiply(j)
+                assert_allclose(toarray(sp_mult), dense_mult)
+
+    def test_elementwise_divide(self, spcreator, dat1d):
+        datsp = spcreator(dat1d)
+        expected = np.array([1, np.nan, 1, np.nan])
+        actual = datsp / datsp
+        # need assert_array_equal to handle nan values
+        np.testing.assert_array_equal(actual, expected)
+
+        denom = spcreator([1, 0, 0, 4], dtype='d')
+        expected = [3, np.nan, np.inf, 0]
+        np.testing.assert_array_equal(datsp / denom, expected)
+
+        # complex
+        A = np.array([1 - 2j, 0 + 5j, -1 + 0j])
+        B = np.array([5 + 2j, 7 - 3j, -2 + 1j])
+        Asp = spcreator(A)
+        Bsp = spcreator(B)
+        assert_allclose(Asp / Bsp, A / B)
+
+        # integer
+        A = np.array([1, 2, 3])
+        B = np.array([0, 1, 2])
+        Asp = spcreator(A)
+        Bsp = spcreator(B)
+        with np.errstate(divide='ignore'):
+            assert_equal(Asp / Bsp, A / B)
+
+        # mismatching sparsity patterns
+        A = np.array([0, 1])
+        B = np.array([1, 0])
+        Asp = spcreator(A)
+        Bsp = spcreator(B)
+        with np.errstate(divide='ignore', invalid='ignore'):
+            assert_equal(Asp / Bsp, A / B)
+
+    def test_pow(self, spcreator):
+        A = np.array([1, 0, 2, 0])
+        B = spcreator(A)
+
+        # unusual exponents
+        with pytest.raises(ValueError, match='negative integer powers'):
+            B**-1
+        with pytest.raises(NotImplementedError, match='zero power'):
+            B**0
+
+        for exponent in [1, 2, 3, 2.2]:
+            ret_sp = B**exponent
+            ret_np = A**exponent
+            assert_equal(ret_sp.toarray(), ret_np)
+            assert_equal(ret_sp.dtype, ret_np.dtype)
+
+    def test_dot_scalar(self, spcreator, dat1d):
+        A = spcreator(dat1d)
+        scalar = 10
+        actual = A.dot(scalar)
+        expected = A * scalar
+
+        assert_allclose(actual.toarray(), expected.toarray())
+
+    def test_matmul(self, spcreator):
+        Msp = spcreator([2, 0, 3.0])
+        B = spcreator(np.array([[0, 1], [1, 0], [0, 2]], 'd'))
+        col = np.array([[1, 2, 3]]).T
+
+        # check sparse @ dense 2d column
+        assert_allclose(Msp @ col, Msp.toarray() @ col)
+
+        # check sparse1d @ sparse2d, sparse1d @ dense2d, dense1d @ sparse2d
+        assert_allclose((Msp @ B).toarray(), (Msp @ B).toarray())
+        assert_allclose(Msp.toarray() @ B, (Msp @ B).toarray())
+        assert_allclose(Msp @ B.toarray(), (Msp @ B).toarray())
+
+        # check sparse1d @ dense1d, sparse1d @ sparse1d
+        V = np.array([0, 0, 1])
+        assert_allclose(Msp @ V, Msp.toarray() @ V)
+
+        Vsp = spcreator(V)
+        Msp_Vsp = Msp @ Vsp
+        assert isinstance(Msp_Vsp, np.ndarray)
+        assert Msp_Vsp.shape == ()
+
+        # output is 0-dim ndarray
+        assert_allclose(np.array(3), Msp_Vsp)
+        assert_allclose(np.array(3), Msp.toarray() @ Vsp)
+        assert_allclose(np.array(3), Msp @ Vsp.toarray())
+        assert_allclose(np.array(3), Msp.toarray() @ Vsp.toarray())
+
+        # check error on matrix-scalar
+        with pytest.raises(ValueError, match='Scalar operands are not allowed'):
+            Msp @ 1
+        with pytest.raises(ValueError, match='Scalar operands are not allowed'):
+            1 @ Msp
+
+    def test_sub_dense(self, spcreator, datsp_math_dtypes):
+        # subtracting a dense matrix to/from a sparse matrix
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            # Manually add to avoid upcasting from scalar
+            # multiplication.
+            sum1 = (dat + dat + dat) - datsp
+            assert_equal(sum1, dat + dat)
+            sum2 = (datsp + datsp + datsp) - dat
+            assert_equal(sum2, dat + dat)
+
+    def test_size_zero_matrix_arithmetic(self, spcreator):
+        # Test basic matrix arithmetic with shapes like 0, (1, 0), (0, 3), etc.
+        mat = np.array([])
+        a = mat.reshape(0)
+        d = mat.reshape((1, 0))
+        f = np.ones([5, 5])
+
+        asp = spcreator(a)
+        dsp = spcreator(d)
+        # bad shape for addition
+        with pytest.raises(ValueError, match='inconsistent shapes'):
+            asp.__add__(dsp)
+
+        # matrix product.
+        assert_equal(asp.dot(asp), np.dot(a, a))
+
+        # bad matrix products
+        with pytest.raises(ValueError, match='dimension mismatch'):
+            asp.dot(f)
+
+        # elemente-wise multiplication
+        assert_equal(asp.multiply(asp).toarray(), np.multiply(a, a))
+
+        assert_equal(asp.multiply(a).toarray(), np.multiply(a, a))
+
+        assert_equal(asp.multiply(6).toarray(), np.multiply(a, 6))
+
+        # bad element-wise multiplication
+        with pytest.raises(ValueError, match='inconsistent shapes'):
+            asp.multiply(f)
+
+        # Addition
+        assert_equal(asp.__add__(asp).toarray(), a.__add__(a))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_array_api.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_array_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..96ca22939df371c0d11b06fb06f2920c705f4578
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_array_api.py
@@ -0,0 +1,561 @@
+import pytest
+import numpy as np
+import numpy.testing as npt
+import scipy.sparse
+import scipy.sparse.linalg as spla
+
+
+sparray_types = ('bsr', 'coo', 'csc', 'csr', 'dia', 'dok', 'lil')
+
+sparray_classes = [
+    getattr(scipy.sparse, f'{T}_array') for T in sparray_types
+]
+
+A = np.array([
+    [0, 1, 2, 0],
+    [2, 0, 0, 3],
+    [1, 4, 0, 0]
+])
+
+B = np.array([
+    [0, 1],
+    [2, 0]
+])
+
+X = np.array([
+    [1, 0, 0, 1],
+    [2, 1, 2, 0],
+    [0, 2, 1, 0],
+    [0, 0, 1, 2]
+], dtype=float)
+
+
+sparrays = [sparray(A) for sparray in sparray_classes]
+square_sparrays = [sparray(B) for sparray in sparray_classes]
+eig_sparrays = [sparray(X) for sparray in sparray_classes]
+
+parametrize_sparrays = pytest.mark.parametrize(
+    "A", sparrays, ids=sparray_types
+)
+parametrize_square_sparrays = pytest.mark.parametrize(
+    "B", square_sparrays, ids=sparray_types
+)
+parametrize_eig_sparrays = pytest.mark.parametrize(
+    "X", eig_sparrays, ids=sparray_types
+)
+
+
+@parametrize_sparrays
+def test_sum(A):
+    assert not isinstance(A.sum(axis=0), np.matrix), \
+        "Expected array, got matrix"
+    assert A.sum(axis=0).shape == (4,)
+    assert A.sum(axis=1).shape == (3,)
+
+
+@parametrize_sparrays
+def test_mean(A):
+    assert not isinstance(A.mean(axis=1), np.matrix), \
+        "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_min_max(A):
+    # Some formats don't support min/max operations, so we skip those here.
+    if hasattr(A, 'min'):
+        assert not isinstance(A.min(axis=1), np.matrix), \
+            "Expected array, got matrix"
+    if hasattr(A, 'max'):
+        assert not isinstance(A.max(axis=1), np.matrix), \
+            "Expected array, got matrix"
+    if hasattr(A, 'argmin'):
+        assert not isinstance(A.argmin(axis=1), np.matrix), \
+            "Expected array, got matrix"
+    if hasattr(A, 'argmax'):
+        assert not isinstance(A.argmax(axis=1), np.matrix), \
+            "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_todense(A):
+    assert not isinstance(A.todense(), np.matrix), \
+        "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_indexing(A):
+    if A.__class__.__name__[:3] in ('dia', 'coo', 'bsr'):
+        return
+
+    all_res = (
+        A[1, :],
+        A[:, 1],
+        A[1, [1, 2]],
+        A[[1, 2], 1],
+        A[[0]],
+        A[:, [1, 2]],
+        A[[1, 2], :],
+        A[1, [[1, 2]]],
+        A[[[1, 2]], 1],
+    )
+
+    for res in all_res:
+        assert isinstance(res, scipy.sparse.sparray), \
+            f"Expected sparse array, got {res._class__.__name__}"
+
+
+@parametrize_sparrays
+def test_dense_addition(A):
+    X = np.random.random(A.shape)
+    assert not isinstance(A + X, np.matrix), "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_sparse_addition(A):
+    assert isinstance((A + A), scipy.sparse.sparray), "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_elementwise_mul(A):
+    assert np.all((A * A).todense() == A.power(2).todense())
+
+
+@parametrize_sparrays
+def test_elementwise_rmul(A):
+    with pytest.raises(TypeError):
+        None * A
+
+    with pytest.raises(ValueError):
+        np.eye(3) * scipy.sparse.csr_array(np.arange(6).reshape(2, 3))
+
+    assert np.all((2 * A) == (A.todense() * 2))
+
+    assert np.all((A.todense() * A) == (A.todense() ** 2))
+
+
+@parametrize_sparrays
+def test_matmul(A):
+    assert np.all((A @ A.T).todense() == A.dot(A.T).todense())
+
+
+@parametrize_sparrays
+def test_power_operator(A):
+    assert isinstance((A**2), scipy.sparse.sparray), "Expected array, got matrix"
+
+    # https://github.com/scipy/scipy/issues/15948
+    npt.assert_equal((A**2).todense(), (A.todense())**2)
+
+    # power of zero is all ones (dense) so helpful msg exception
+    with pytest.raises(NotImplementedError, match="zero power"):
+        A**0
+
+
+@parametrize_sparrays
+def test_sparse_divide(A):
+    assert isinstance(A / A, np.ndarray)
+
+@parametrize_sparrays
+@pytest.mark.thread_unsafe
+def test_sparse_dense_divide(A):
+    with pytest.warns(RuntimeWarning):
+        assert isinstance((A / A.todense()), scipy.sparse.sparray)
+
+@parametrize_sparrays
+def test_dense_divide(A):
+    assert isinstance((A / 2), scipy.sparse.sparray), "Expected array, got matrix"
+
+
+@parametrize_sparrays
+def test_no_A_attr(A):
+    with pytest.raises(AttributeError):
+        A.A
+
+
+@parametrize_sparrays
+def test_no_H_attr(A):
+    with pytest.raises(AttributeError):
+        A.H
+
+
+@parametrize_sparrays
+def test_getrow_getcol(A):
+    assert isinstance(A._getcol(0), scipy.sparse.sparray)
+    assert isinstance(A._getrow(0), scipy.sparse.sparray)
+
+
+# -- linalg --
+
+@parametrize_sparrays
+def test_as_linearoperator(A):
+    L = spla.aslinearoperator(A)
+    npt.assert_allclose(L * [1, 2, 3, 4], A @ [1, 2, 3, 4])
+
+
+@parametrize_square_sparrays
+def test_inv(B):
+    if B.__class__.__name__[:3] != 'csc':
+        return
+
+    C = spla.inv(B)
+
+    assert isinstance(C, scipy.sparse.sparray)
+    npt.assert_allclose(C.todense(), np.linalg.inv(B.todense()))
+
+
+@parametrize_square_sparrays
+def test_expm(B):
+    if B.__class__.__name__[:3] != 'csc':
+        return
+
+    Bmat = scipy.sparse.csc_matrix(B)
+
+    C = spla.expm(B)
+
+    assert isinstance(C, scipy.sparse.sparray)
+    npt.assert_allclose(
+        C.todense(),
+        spla.expm(Bmat).todense()
+    )
+
+
+@parametrize_square_sparrays
+def test_expm_multiply(B):
+    if B.__class__.__name__[:3] != 'csc':
+        return
+
+    npt.assert_allclose(
+        spla.expm_multiply(B, np.array([1, 2])),
+        spla.expm(B) @ [1, 2]
+    )
+
+
+@parametrize_sparrays
+def test_norm(A):
+    C = spla.norm(A)
+    npt.assert_allclose(C, np.linalg.norm(A.todense()))
+
+
+@parametrize_square_sparrays
+def test_onenormest(B):
+    C = spla.onenormest(B)
+    npt.assert_allclose(C, np.linalg.norm(B.todense(), 1))
+
+
+@parametrize_square_sparrays
+def test_spsolve(B):
+    if B.__class__.__name__[:3] not in ('csc', 'csr'):
+        return
+
+    npt.assert_allclose(
+        spla.spsolve(B, [1, 2]),
+        np.linalg.solve(B.todense(), [1, 2])
+    )
+
+
+@pytest.mark.parametrize("fmt",["csr","csc"])
+def test_spsolve_triangular(fmt):
+    arr = [
+        [1, 0, 0, 0],
+        [2, 1, 0, 0],
+        [3, 2, 1, 0],
+        [4, 3, 2, 1],
+    ]
+    if fmt == "csr":
+      X = scipy.sparse.csr_array(arr)
+    else:
+      X = scipy.sparse.csc_array(arr)
+    spla.spsolve_triangular(X, [1, 2, 3, 4])
+
+
+@parametrize_square_sparrays
+def test_factorized(B):
+    if B.__class__.__name__[:3] != 'csc':
+        return
+
+    LU = spla.factorized(B)
+    npt.assert_allclose(
+        LU(np.array([1, 2])),
+        np.linalg.solve(B.todense(), [1, 2])
+    )
+
+
+@parametrize_square_sparrays
+@pytest.mark.parametrize(
+    "solver",
+    ["bicg", "bicgstab", "cg", "cgs", "gmres", "lgmres", "minres", "qmr",
+     "gcrotmk", "tfqmr"]
+)
+def test_solvers(B, solver):
+    if solver == "minres":
+        kwargs = {}
+    else:
+        kwargs = {'atol': 1e-5}
+
+    x, info = getattr(spla, solver)(B, np.array([1, 2]), **kwargs)
+    assert info >= 0  # no errors, even if perhaps did not converge fully
+    npt.assert_allclose(x, [1, 1], atol=1e-1)
+
+
+@parametrize_sparrays
+@pytest.mark.parametrize(
+    "solver",
+    ["lsqr", "lsmr"]
+)
+def test_lstsqr(A, solver):
+    x, *_ = getattr(spla, solver)(A, [1, 2, 3])
+    npt.assert_allclose(A @ x, [1, 2, 3])
+
+
+@parametrize_eig_sparrays
+def test_eigs(X):
+    e, v = spla.eigs(X, k=1)
+    npt.assert_allclose(
+        X @ v,
+        e[0] * v
+    )
+
+
+@parametrize_eig_sparrays
+def test_eigsh(X):
+    X = X + X.T
+    e, v = spla.eigsh(X, k=1)
+    npt.assert_allclose(
+        X @ v,
+        e[0] * v
+    )
+
+
+@parametrize_eig_sparrays
+def test_svds(X):
+    u, s, vh = spla.svds(X, k=3)
+    u2, s2, vh2 = np.linalg.svd(X.todense())
+    s = np.sort(s)
+    s2 = np.sort(s2[:3])
+    npt.assert_allclose(s, s2, atol=1e-3)
+
+
+def test_splu():
+    X = scipy.sparse.csc_array([
+        [1, 0, 0, 0],
+        [2, 1, 0, 0],
+        [3, 2, 1, 0],
+        [4, 3, 2, 1],
+    ])
+    LU = spla.splu(X)
+    npt.assert_allclose(
+        LU.solve(np.array([1, 2, 3, 4])),
+        np.asarray([1, 0, 0, 0], dtype=np.float64),
+        rtol=1e-14, atol=3e-16
+    )
+
+
+def test_spilu():
+    X = scipy.sparse.csc_array([
+        [1, 0, 0, 0],
+        [2, 1, 0, 0],
+        [3, 2, 1, 0],
+        [4, 3, 2, 1],
+    ])
+    LU = spla.spilu(X)
+    npt.assert_allclose(
+        LU.solve(np.array([1, 2, 3, 4])),
+        np.asarray([1, 0, 0, 0], dtype=np.float64),
+        rtol=1e-14, atol=3e-16
+    )
+
+
+@pytest.mark.parametrize(
+    "cls,indices_attrs",
+    [
+        (
+            scipy.sparse.csr_array,
+            ["indices", "indptr"],
+        ),
+        (
+            scipy.sparse.csc_array,
+            ["indices", "indptr"],
+        ),
+        (
+            scipy.sparse.coo_array,
+            ["row", "col"],
+        ),
+    ]
+)
+@pytest.mark.parametrize("expected_dtype", [np.int64, np.int32])
+def test_index_dtype_compressed(cls, indices_attrs, expected_dtype):
+    input_array = scipy.sparse.coo_array(np.arange(9).reshape(3, 3))
+    coo_tuple = (
+        input_array.data,
+        (
+            input_array.row.astype(expected_dtype),
+            input_array.col.astype(expected_dtype),
+        )
+    )
+
+    result = cls(coo_tuple)
+    for attr in indices_attrs:
+        assert getattr(result, attr).dtype == expected_dtype
+
+    result = cls(coo_tuple, shape=(3, 3))
+    for attr in indices_attrs:
+        assert getattr(result, attr).dtype == expected_dtype
+
+    if issubclass(cls, scipy.sparse._compressed._cs_matrix):
+        input_array_csr = input_array.tocsr()
+        csr_tuple = (
+            input_array_csr.data,
+            input_array_csr.indices.astype(expected_dtype),
+            input_array_csr.indptr.astype(expected_dtype),
+        )
+
+        result = cls(csr_tuple)
+        for attr in indices_attrs:
+            assert getattr(result, attr).dtype == expected_dtype
+
+        result = cls(csr_tuple, shape=(3, 3))
+        for attr in indices_attrs:
+            assert getattr(result, attr).dtype == expected_dtype
+
+
+def test_default_is_matrix_diags():
+    m = scipy.sparse.diags([0, 1, 2])
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_eye():
+    m = scipy.sparse.eye(3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_spdiags():
+    m = scipy.sparse.spdiags([1, 2, 3], 0, 3, 3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_identity():
+    m = scipy.sparse.identity(3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_kron_dense():
+    m = scipy.sparse.kron(
+        np.array([[1, 2], [3, 4]]), np.array([[4, 3], [2, 1]])
+    )
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_kron_sparse():
+    m = scipy.sparse.kron(
+        np.array([[1, 2], [3, 4]]), np.array([[1, 0], [0, 0]])
+    )
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_kronsum():
+    m = scipy.sparse.kronsum(
+        np.array([[1, 0], [0, 1]]), np.array([[0, 1], [1, 0]])
+    )
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_random():
+    m = scipy.sparse.random(3, 3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_default_is_matrix_rand():
+    m = scipy.sparse.rand(3, 3)
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+@pytest.mark.parametrize("fn", (scipy.sparse.hstack, scipy.sparse.vstack))
+def test_default_is_matrix_stacks(fn):
+    """Same idea as `test_default_construction_fn_matrices`, but for the
+    stacking creation functions."""
+    A = scipy.sparse.coo_matrix(np.eye(2))
+    B = scipy.sparse.coo_matrix([[0, 1], [1, 0]])
+    m = fn([A, B])
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_blocks_default_construction_fn_matrices():
+    """Same idea as `test_default_construction_fn_matrices`, but for the block
+    creation function"""
+    A = scipy.sparse.coo_matrix(np.eye(2))
+    B = scipy.sparse.coo_matrix([[2], [0]])
+    C = scipy.sparse.coo_matrix([[3]])
+
+    # block diag
+    m = scipy.sparse.block_diag((A, B, C))
+    assert not isinstance(m, scipy.sparse.sparray)
+
+    # bmat
+    m = scipy.sparse.bmat([[A, None], [None, C]])
+    assert not isinstance(m, scipy.sparse.sparray)
+
+
+def test_format_property():
+    for fmt in sparray_types:
+        arr_cls = getattr(scipy.sparse, f"{fmt}_array")
+        M = arr_cls([[1, 2]])
+        assert M.format == fmt
+        assert M._format == fmt
+        with pytest.raises(AttributeError):
+            M.format = "qqq"
+
+
+def test_issparse():
+    m = scipy.sparse.eye(3)
+    a = scipy.sparse.csr_array(m)
+    assert not isinstance(m, scipy.sparse.sparray)
+    assert isinstance(a, scipy.sparse.sparray)
+
+    # Both sparse arrays and sparse matrices should be sparse
+    assert scipy.sparse.issparse(a)
+    assert scipy.sparse.issparse(m)
+
+    # ndarray and array_likes are not sparse
+    assert not scipy.sparse.issparse(a.todense())
+    assert not scipy.sparse.issparse(m.todense())
+
+
+def test_isspmatrix():
+    m = scipy.sparse.eye(3)
+    a = scipy.sparse.csr_array(m)
+    assert not isinstance(m, scipy.sparse.sparray)
+    assert isinstance(a, scipy.sparse.sparray)
+
+    # Should only be true for sparse matrices, not sparse arrays
+    assert not scipy.sparse.isspmatrix(a)
+    assert scipy.sparse.isspmatrix(m)
+
+    # ndarray and array_likes are not sparse
+    assert not scipy.sparse.isspmatrix(a.todense())
+    assert not scipy.sparse.isspmatrix(m.todense())
+
+
+@pytest.mark.parametrize(
+    ("fmt", "fn"),
+    (
+        ("bsr", scipy.sparse.isspmatrix_bsr),
+        ("coo", scipy.sparse.isspmatrix_coo),
+        ("csc", scipy.sparse.isspmatrix_csc),
+        ("csr", scipy.sparse.isspmatrix_csr),
+        ("dia", scipy.sparse.isspmatrix_dia),
+        ("dok", scipy.sparse.isspmatrix_dok),
+        ("lil", scipy.sparse.isspmatrix_lil),
+    ),
+)
+def test_isspmatrix_format(fmt, fn):
+    m = scipy.sparse.eye(3, format=fmt)
+    a = scipy.sparse.csr_array(m).asformat(fmt)
+    assert not isinstance(m, scipy.sparse.sparray)
+    assert isinstance(a, scipy.sparse.sparray)
+
+    # Should only be true for sparse matrices, not sparse arrays
+    assert not fn(a)
+    assert fn(m)
+
+    # ndarray and array_likes are not sparse
+    assert not fn(a.todense())
+    assert not fn(m.todense())
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f7ead8b134dc2e09bb0cef8441cb2b75a5aee8b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_base.py
@@ -0,0 +1,5695 @@
+#
+# Authors: Travis Oliphant, Ed Schofield, Robert Cimrman, Nathan Bell, and others
+
+""" Test functions for sparse matrices. Each class in the "Matrix class
+based tests" section become subclasses of the classes in the "Generic
+tests" section. This is done by the functions in the "Tailored base
+class for generic tests" section.
+
+"""
+
+
+import contextlib
+import functools
+import operator
+import platform
+import itertools
+import sys
+
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from numpy import (arange, zeros, array, dot, asarray,
+                   vstack, ndarray, transpose, diag, kron, inf, conjugate,
+                   int8)
+
+import random
+from numpy.testing import (assert_equal, assert_array_equal,
+        assert_array_almost_equal, assert_almost_equal, assert_,
+        assert_allclose, suppress_warnings)
+
+import scipy.linalg
+
+import scipy.sparse as sparse
+from scipy.sparse import (csc_matrix, csr_matrix, dok_matrix,
+        coo_matrix, lil_matrix, dia_matrix, bsr_matrix,
+        csc_array, csr_array, dok_array,
+        coo_array, lil_array, dia_array, bsr_array,
+        eye, issparse, SparseEfficiencyWarning, sparray)
+from scipy.sparse._base import _formats
+from scipy.sparse._sputils import (supported_dtypes, isscalarlike,
+                                   get_index_dtype, asmatrix, matrix)
+from scipy.sparse.linalg import splu, expm, inv
+
+from scipy._lib.decorator import decorator
+from scipy._lib._util import ComplexWarning
+
+IS_COLAB = ('google.colab' in sys.modules)
+
+
+def assert_in(member, collection, msg=None):
+    message = msg if msg is not None else f"{member!r} not found in {collection!r}"
+    assert_(member in collection, msg=message)
+
+
+def assert_array_equal_dtype(x, y, **kwargs):
+    assert_(x.dtype == y.dtype)
+    assert_array_equal(x, y, **kwargs)
+
+
+NON_ARRAY_BACKED_FORMATS = frozenset(['dok'])
+
+def sparse_may_share_memory(A, B):
+    # Checks if A and B have any numpy array sharing memory.
+
+    def _underlying_arrays(x):
+        # Given any object (e.g. a sparse array), returns all numpy arrays
+        # stored in any attribute.
+
+        arrays = []
+        for a in x.__dict__.values():
+            if isinstance(a, np.ndarray | np.generic):
+                arrays.append(a)
+        return arrays
+
+    for a in _underlying_arrays(A):
+        for b in _underlying_arrays(B):
+            if np.may_share_memory(a, b):
+                return True
+    return False
+
+
+sup_complex = suppress_warnings()
+sup_complex.filter(ComplexWarning)
+
+
+def with_64bit_maxval_limit(maxval_limit=None, random=False, fixed_dtype=None,
+                            downcast_maxval=None, assert_32bit=False):
+    """
+    Monkeypatch the maxval threshold at which scipy.sparse switches to
+    64-bit index arrays, or make it (pseudo-)random.
+
+    """
+    if maxval_limit is None:
+        maxval_limit = np.int64(10)
+    else:
+        # Ensure we use numpy scalars rather than Python scalars (matters for
+        # NEP 50 casting rule changes)
+        maxval_limit = np.int64(maxval_limit)
+
+    if assert_32bit:
+        def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
+            tp = get_index_dtype(arrays, maxval, check_contents)
+            assert_equal(np.iinfo(tp).max, np.iinfo(np.int32).max)
+            assert_(tp == np.int32 or tp == np.intc)
+            return tp
+    elif fixed_dtype is not None:
+        def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
+            return fixed_dtype
+    elif random:
+        counter = np.random.RandomState(seed=1234)
+
+        def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
+            return (np.int32, np.int64)[counter.randint(2)]
+    else:
+        def new_get_index_dtype(arrays=(), maxval=None, check_contents=False):
+            dtype = np.int32
+            if maxval is not None:
+                if maxval > maxval_limit:
+                    dtype = np.int64
+            for arr in arrays:
+                arr = np.asarray(arr)
+                if arr.dtype > np.int32:
+                    if check_contents:
+                        if arr.size == 0:
+                            # a bigger type not needed
+                            continue
+                        elif np.issubdtype(arr.dtype, np.integer):
+                            maxval = arr.max()
+                            minval = arr.min()
+                            if minval >= -maxval_limit and maxval <= maxval_limit:
+                                # a bigger type not needed
+                                continue
+                    dtype = np.int64
+            return dtype
+
+    if downcast_maxval is not None:
+        def new_downcast_intp_index(arr):
+            if arr.max() > downcast_maxval:
+                raise AssertionError("downcast limited")
+            return arr.astype(np.intp)
+
+    @decorator
+    def deco(func, *a, **kw):
+        backup = []
+        modules = [scipy.sparse._bsr, scipy.sparse._coo, scipy.sparse._csc,
+                   scipy.sparse._csr, scipy.sparse._dia, scipy.sparse._dok,
+                   scipy.sparse._lil, scipy.sparse._sputils,
+                   scipy.sparse._compressed, scipy.sparse._construct]
+        try:
+            for mod in modules:
+                backup.append((mod, 'get_index_dtype',
+                               getattr(mod, 'get_index_dtype', None)))
+                setattr(mod, 'get_index_dtype', new_get_index_dtype)
+                if downcast_maxval is not None:
+                    backup.append((mod, 'downcast_intp_index',
+                                   getattr(mod, 'downcast_intp_index', None)))
+                    setattr(mod, 'downcast_intp_index', new_downcast_intp_index)
+            return func(*a, **kw)
+        finally:
+            for mod, name, oldfunc in backup:
+                if oldfunc is not None:
+                    setattr(mod, name, oldfunc)
+
+    return deco
+
+
+def toarray(a):
+    if isinstance(a, np.ndarray) or isscalarlike(a):
+        return a
+    return a.toarray()
+
+
+class BinopTester:
+    # Custom type to test binary operations on sparse matrices.
+
+    def __add__(self, mat):
+        return "matrix on the right"
+
+    def __mul__(self, mat):
+        return "matrix on the right"
+
+    def __sub__(self, mat):
+        return "matrix on the right"
+
+    def __radd__(self, mat):
+        return "matrix on the left"
+
+    def __rmul__(self, mat):
+        return "matrix on the left"
+
+    def __rsub__(self, mat):
+        return "matrix on the left"
+
+    def __matmul__(self, mat):
+        return "matrix on the right"
+
+    def __rmatmul__(self, mat):
+        return "matrix on the left"
+
+class BinopTester_with_shape:
+    # Custom type to test binary operations on sparse matrices
+    # with object which has shape attribute.
+    def __init__(self,shape):
+        self._shape = shape
+
+    def shape(self):
+        return self._shape
+
+    def ndim(self):
+        return len(self._shape)
+
+    def __add__(self, mat):
+        return "matrix on the right"
+
+    def __mul__(self, mat):
+        return "matrix on the right"
+
+    def __sub__(self, mat):
+        return "matrix on the right"
+
+    def __radd__(self, mat):
+        return "matrix on the left"
+
+    def __rmul__(self, mat):
+        return "matrix on the left"
+
+    def __rsub__(self, mat):
+        return "matrix on the left"
+
+    def __matmul__(self, mat):
+        return "matrix on the right"
+
+    def __rmatmul__(self, mat):
+        return "matrix on the left"
+
+class ComparisonTester:
+    # Custom type to test comparison operations on sparse matrices.
+    def __eq__(self, other):
+        return "eq"
+
+    def __ne__(self, other):
+        return "ne"
+
+    def __lt__(self, other):
+        return "lt"
+
+    def __le__(self, other):
+        return "le"
+
+    def __gt__(self, other):
+        return "gt"
+
+    def __ge__(self, other):
+        return "ge"
+
+
+#------------------------------------------------------------------------------
+# Generic tests
+#------------------------------------------------------------------------------
+
+
+class _MatrixMixin:
+    """mixin to easily allow tests of both sparray and spmatrix"""
+    bsr_container = bsr_matrix
+    coo_container = coo_matrix
+    csc_container = csc_matrix
+    csr_container = csr_matrix
+    dia_container = dia_matrix
+    dok_container = dok_matrix
+    lil_container = lil_matrix
+    asdense = staticmethod(asmatrix)
+
+    def test_getrow(self):
+        assert_array_equal(self.datsp.getrow(1).toarray(), self.dat[[1], :])
+        assert_array_equal(self.datsp.getrow(-1).toarray(), self.dat[[-1], :])
+
+    def test_getcol(self):
+        assert_array_equal(self.datsp.getcol(1).toarray(), self.dat[:, [1]])
+        assert_array_equal(self.datsp.getcol(-1).toarray(), self.dat[:, [-1]])
+
+    def test_asfptype(self):
+        A = self.spcreator(arange(6,dtype='int32').reshape(2,3))
+
+        assert_equal(A.asfptype().dtype, np.dtype('float64'))
+        assert_equal(A.asfptype().format, A.format)
+        assert_equal(A.astype('int16').asfptype().dtype, np.dtype('float32'))
+        assert_equal(A.astype('complex128').asfptype().dtype, np.dtype('complex128'))
+
+        B = A.asfptype()
+        C = B.asfptype()
+        assert_(B is C)
+
+
+# TODO test prune
+# TODO test has_sorted_indices
+class _TestCommon:
+    """test common functionality shared by all sparse formats"""
+    math_dtypes = supported_dtypes
+
+    bsr_container = bsr_array
+    coo_container = coo_array
+    csc_container = csc_array
+    csr_container = csr_array
+    dia_container = dia_array
+    dok_container = dok_array
+    lil_container = lil_array
+    asdense = array
+
+    @classmethod
+    def init_class(cls):
+        # Canonical data.
+        cls.dat = array([[1, 0, 0, 2], [3, 0, 1, 0], [0, 2, 0, 0]], 'd')
+        cls.datsp = cls.spcreator(cls.dat)
+
+        # Some sparse and dense matrices with data for every supported dtype.
+        # This set union is a workaround for numpy#6295, which means that
+        # two np.int64 dtypes don't hash to the same value.
+        cls.checked_dtypes = set(supported_dtypes).union(cls.math_dtypes)
+        cls.dat_dtypes = {}
+        cls.datsp_dtypes = {}
+        for dtype in cls.checked_dtypes:
+            cls.dat_dtypes[dtype] = cls.dat.astype(dtype)
+            cls.datsp_dtypes[dtype] = cls.spcreator(cls.dat.astype(dtype))
+
+        # Check that the original data is equivalent to the
+        # corresponding dat_dtypes & datsp_dtypes.
+        assert_equal(cls.dat, cls.dat_dtypes[np.float64])
+        assert_equal(cls.datsp.toarray(),
+                     cls.datsp_dtypes[np.float64].toarray())
+
+        cls.is_array_test = isinstance(cls.datsp, sparray)
+
+    def test_bool(self):
+        def check(dtype):
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_raises(ValueError, bool, datsp)
+            assert_(self.spcreator([[1]]))
+            assert_(not self.spcreator([[0]]))
+
+        if isinstance(self, TestDOK):
+            pytest.skip("Cannot create a rank <= 2 DOK matrix.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_bool_rollover(self):
+        # bool's underlying dtype is 1 byte, check that it does not
+        # rollover True -> False at 256.
+        dat = array([[True, False]])
+        datsp = self.spcreator(dat)
+
+        for _ in range(10):
+            datsp = datsp + datsp
+            dat = dat + dat
+        assert_array_equal(dat, datsp.toarray())
+
+    def test_eq(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datbsr = self.bsr_container(dat)
+            datcsr = self.csr_container(dat)
+            datcsc = self.csc_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat == dat2, (datsp == datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype(dat == dat2, (datbsr == datsp2).toarray())
+            assert_array_equal_dtype(dat == dat2, (datcsr == datsp2).toarray())
+            assert_array_equal_dtype(dat == dat2, (datcsc == datsp2).toarray())
+            assert_array_equal_dtype(dat == dat2, (datlil == datsp2).toarray())
+            # sparse/dense
+            assert_array_equal_dtype(dat == datsp2, datsp2 == dat)
+            # sparse/scalar
+            assert_array_equal_dtype(dat == 0, (datsp == 0).toarray())
+            assert_array_equal_dtype(dat == 1, (datsp == 1).toarray())
+            assert_array_equal_dtype(dat == np.nan,
+                                     (datsp == np.nan).toarray())
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_ne(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat != dat2, (datsp != datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype(dat != dat2, (datbsr != datsp2).toarray())
+            assert_array_equal_dtype(dat != dat2, (datcsc != datsp2).toarray())
+            assert_array_equal_dtype(dat != dat2, (datcsr != datsp2).toarray())
+            assert_array_equal_dtype(dat != dat2, (datlil != datsp2).toarray())
+            # sparse/dense
+            assert_array_equal_dtype(dat != datsp2, datsp2 != dat)
+            # sparse/scalar
+            assert_array_equal_dtype(dat != 0, (datsp != 0).toarray())
+            assert_array_equal_dtype(dat != 1, (datsp != 1).toarray())
+            assert_array_equal_dtype(0 != dat, (0 != datsp).toarray())
+            assert_array_equal_dtype(1 != dat, (1 != datsp).toarray())
+            assert_array_equal_dtype(dat != np.nan,
+                                     (datsp != np.nan).toarray())
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_lt(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            # data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datcomplex = dat.astype(complex)
+            datcomplex[:,0] = 1 + 1j
+            datspcomplex = self.spcreator(datcomplex)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat < dat2, (datsp < datsp2).toarray())
+            assert_array_equal_dtype(datcomplex < dat2,
+                                     (datspcomplex < datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype(dat < dat2, (datbsr < datsp2).toarray())
+            assert_array_equal_dtype(dat < dat2, (datcsc < datsp2).toarray())
+            assert_array_equal_dtype(dat < dat2, (datcsr < datsp2).toarray())
+            assert_array_equal_dtype(dat < dat2, (datlil < datsp2).toarray())
+
+            assert_array_equal_dtype(dat2 < dat, (datsp2 < datbsr).toarray())
+            assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsc).toarray())
+            assert_array_equal_dtype(dat2 < dat, (datsp2 < datcsr).toarray())
+            assert_array_equal_dtype(dat2 < dat, (datsp2 < datlil).toarray())
+            # sparse/dense
+            assert_array_equal_dtype(dat < dat2, datsp < dat2)
+            assert_array_equal_dtype(datcomplex < dat2, datspcomplex < dat2)
+            # sparse/scalar
+            for val in [2, 1, 0, -1, -2]:
+                val = np.int64(val)  # avoid Python scalar (due to NEP 50 changes)
+                assert_array_equal_dtype((datsp < val).toarray(), dat < val)
+                assert_array_equal_dtype((val < datsp).toarray(), val < dat)
+
+            with np.errstate(invalid='ignore'):
+                assert_array_equal_dtype((datsp < np.nan).toarray(),
+                                         dat < np.nan)
+
+            # data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+
+            # dense rhs
+            assert_array_equal_dtype(dat < datsp2, datsp < dat2)
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_gt(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datcomplex = dat.astype(complex)
+            datcomplex[:,0] = 1 + 1j
+            datspcomplex = self.spcreator(datcomplex)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat > dat2, (datsp > datsp2).toarray())
+            assert_array_equal_dtype(datcomplex > dat2,
+                                     (datspcomplex > datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype(dat > dat2, (datbsr > datsp2).toarray())
+            assert_array_equal_dtype(dat > dat2, (datcsc > datsp2).toarray())
+            assert_array_equal_dtype(dat > dat2, (datcsr > datsp2).toarray())
+            assert_array_equal_dtype(dat > dat2, (datlil > datsp2).toarray())
+
+            assert_array_equal_dtype(dat2 > dat, (datsp2 > datbsr).toarray())
+            assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsc).toarray())
+            assert_array_equal_dtype(dat2 > dat, (datsp2 > datcsr).toarray())
+            assert_array_equal_dtype(dat2 > dat, (datsp2 > datlil).toarray())
+            # sparse/dense
+            assert_array_equal_dtype(dat > dat2, datsp > dat2)
+            assert_array_equal_dtype(datcomplex > dat2, datspcomplex > dat2)
+            # sparse/scalar
+            for val in [2, 1, 0, -1, -2]:
+                val = np.int64(val)  # avoid Python scalar (due to NEP 50 changes)
+                assert_array_equal_dtype((datsp > val).toarray(), dat > val)
+                assert_array_equal_dtype((val > datsp).toarray(), val > dat)
+
+            with np.errstate(invalid='ignore'):
+                assert_array_equal_dtype((datsp > np.nan).toarray(),
+                                         dat > np.nan)
+
+            # data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+
+            # dense rhs
+            assert_array_equal_dtype(dat > datsp2, datsp > dat2)
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_le(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datcomplex = dat.astype(complex)
+            datcomplex[:,0] = 1 + 1j
+            datspcomplex = self.spcreator(datcomplex)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat <= dat2, (datsp <= datsp2).toarray())
+            assert_array_equal_dtype(datcomplex <= dat2,
+                                     (datspcomplex <= datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype((datbsr <= datsp2).toarray(), dat <= dat2)
+            assert_array_equal_dtype((datcsc <= datsp2).toarray(), dat <= dat2)
+            assert_array_equal_dtype((datcsr <= datsp2).toarray(), dat <= dat2)
+            assert_array_equal_dtype((datlil <= datsp2).toarray(), dat <= dat2)
+
+            assert_array_equal_dtype((datsp2 <= datbsr).toarray(), dat2 <= dat)
+            assert_array_equal_dtype((datsp2 <= datcsc).toarray(), dat2 <= dat)
+            assert_array_equal_dtype((datsp2 <= datcsr).toarray(), dat2 <= dat)
+            assert_array_equal_dtype((datsp2 <= datlil).toarray(), dat2 <= dat)
+            # sparse/dense
+            assert_array_equal_dtype(datsp <= dat2, dat <= dat2)
+            assert_array_equal_dtype(datspcomplex <= dat2, datcomplex <= dat2)
+            # sparse/scalar
+            for val in [2, 1, -1, -2]:
+                val = np.int64(val)  # avoid Python scalar (due to NEP 50 changes)
+                assert_array_equal_dtype((datsp <= val).toarray(), dat <= val)
+                assert_array_equal_dtype((val <= datsp).toarray(), val <= dat)
+
+            # data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+
+            # dense rhs
+            assert_array_equal_dtype(dat <= datsp2, datsp <= dat2)
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_ge(self):
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        @sup_complex
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+            datcomplex = dat.astype(complex)
+            datcomplex[:,0] = 1 + 1j
+            datspcomplex = self.spcreator(datcomplex)
+            datbsr = self.bsr_container(dat)
+            datcsc = self.csc_container(dat)
+            datcsr = self.csr_container(dat)
+            datlil = self.lil_container(dat)
+
+            # sparse/sparse
+            assert_array_equal_dtype(dat >= dat2, (datsp >= datsp2).toarray())
+            assert_array_equal_dtype(datcomplex >= dat2,
+                                     (datspcomplex >= datsp2).toarray())
+            # mix sparse types
+            assert_array_equal_dtype((datbsr >= datsp2).toarray(), dat >= dat2)
+            assert_array_equal_dtype((datcsc >= datsp2).toarray(), dat >= dat2)
+            assert_array_equal_dtype((datcsr >= datsp2).toarray(), dat >= dat2)
+            assert_array_equal_dtype((datlil >= datsp2).toarray(), dat >= dat2)
+
+            assert_array_equal_dtype((datsp2 >= datbsr).toarray(), dat2 >= dat)
+            assert_array_equal_dtype((datsp2 >= datcsc).toarray(), dat2 >= dat)
+            assert_array_equal_dtype((datsp2 >= datcsr).toarray(), dat2 >= dat)
+            assert_array_equal_dtype((datsp2 >= datlil).toarray(), dat2 >= dat)
+            # sparse/dense
+            assert_array_equal_dtype(datsp >= dat2, dat >= dat2)
+            assert_array_equal_dtype(datspcomplex >= dat2, datcomplex >= dat2)
+            # sparse/scalar
+            for val in [2, 1, -1, -2]:
+                val = np.int64(val)  # avoid Python scalar (due to NEP 50 changes)
+                assert_array_equal_dtype((datsp >= val).toarray(), dat >= val)
+                assert_array_equal_dtype((val >= datsp).toarray(), val >= dat)
+
+            # dense data
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+            dat2 = dat.copy()
+            dat2[:,0] = 0
+            datsp2 = self.spcreator(dat2)
+
+            # dense rhs
+            assert_array_equal_dtype(dat >= datsp2, datsp >= dat2)
+
+        if self.datsp.format not in ['bsr', 'csc', 'csr']:
+            pytest.skip("Bool comparisons only implemented for BSR, CSC, and CSR.")
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_empty(self):
+        # create empty matrices
+        assert_equal(self.spcreator((3, 3)).toarray(), zeros((3, 3)))
+        assert_equal(self.spcreator((3, 3)).nnz, 0)
+        assert_equal(self.spcreator((3, 3)).count_nonzero(), 0)
+        if self.datsp.format in ["coo", "csr", "csc", "lil"]:
+            assert_equal(self.spcreator((3, 3)).count_nonzero(axis=0), array([0, 0, 0]))
+
+    def test_count_nonzero(self):
+        axis_support = self.datsp.format in ["coo", "csr", "csc", "lil"]
+        axes = [None, 0, 1, -1, -2] if axis_support else [None]
+
+        for A in (self.datsp, self.datsp.T):
+            for ax in axes:
+                expected = np.count_nonzero(A.toarray(), axis=ax)
+                assert_equal(A.count_nonzero(axis=ax), expected)
+
+        if not axis_support:
+            with assert_raises(NotImplementedError, match="not implemented .* format"):
+                self.datsp.count_nonzero(axis=0)
+
+    def test_invalid_shapes(self):
+        assert_raises(ValueError, self.spcreator, (-1,3))
+        assert_raises(ValueError, self.spcreator, (3,-1))
+        assert_raises(ValueError, self.spcreator, (-1,-1))
+
+    def test_repr(self):
+        datsp = self.spcreator([[1, 0, 0], [0, 0, 0], [0, 0, -2]])
+        extra = (
+            "(1 diagonals) " if datsp.format == "dia"
+            else "(blocksize=1x1) " if datsp.format == "bsr"
+            else ""
+        )
+        _, fmt = _formats[datsp.format]
+        sparse_cls = "array" if self.is_array_test else "matrix"
+        expected = (
+            f"<{fmt} sparse {sparse_cls} of dtype '{datsp.dtype}'\n"
+            f"\twith {datsp.nnz} stored elements {extra}and shape {datsp.shape}>"
+        )
+        assert repr(datsp) == expected
+
+    def test_str_maxprint(self):
+        datsp = self.spcreator(np.arange(75).reshape(5, 15))
+        assert datsp.maxprint == 50
+        assert len(str(datsp).split('\n')) == 51 + 3
+
+        dat = np.arange(15).reshape(5,3)
+        datsp = self.spcreator(dat)
+        # format dia reports nnz=15, but we want 14
+        nnz_small = 14 if datsp.format == 'dia' else datsp.nnz
+        datsp_mp6 = self.spcreator(dat, maxprint=6)
+
+        assert len(str(datsp).split('\n')) == nnz_small + 3
+        assert len(str(datsp_mp6).split('\n')) == 6 + 4
+
+        # Check parameter `maxprint` is keyword only
+        datsp = self.spcreator(dat, shape=(5, 3), dtype='i', copy=False, maxprint=4)
+        datsp = self.spcreator(dat, (5, 3), 'i', False, maxprint=4)
+        with pytest.raises(TypeError, match="positional argument|unpack non-iterable"):
+            self.spcreator(dat, (5, 3), 'i', False, 4)
+
+    def test_str(self):
+        datsp = self.spcreator([[1, 0, 0], [0, 0, 0], [0, 0, -2]])
+        if datsp.nnz != 2:
+            return
+        extra = (
+            "(1 diagonals) " if datsp.format == "dia"
+            else "(blocksize=1x1) " if datsp.format == "bsr"
+            else ""
+        )
+        _, fmt = _formats[datsp.format]
+        sparse_cls = "array" if self.is_array_test else "matrix"
+        expected = (
+            f"<{fmt} sparse {sparse_cls} of dtype '{datsp.dtype}'\n"
+            f"\twith {datsp.nnz} stored elements {extra}and shape {datsp.shape}>"
+            "\n  Coords\tValues"
+            "\n  (0, 0)\t1"
+            "\n  (2, 2)\t-2"
+        )
+        assert str(datsp) == expected
+
+    def test_empty_arithmetic(self):
+        # Test manipulating empty matrices. Fails in SciPy SVN <= r1768
+        shape = (5, 5)
+        for mytype in [np.dtype('int32'), np.dtype('float32'),
+                np.dtype('float64'), np.dtype('complex64'),
+                np.dtype('complex128')]:
+            a = self.spcreator(shape, dtype=mytype)
+            b = a + a
+            c = 2 * a
+            d = a @ a.tocsc()
+            e = a @ a.tocsr()
+            f = a @ a.tocoo()
+            for m in [a,b,c,d,e,f]:
+                assert_equal(m.toarray(), a.toarray()@a.toarray())
+                # These fail in all revisions <= r1768:
+                assert_equal(m.dtype,mytype)
+                assert_equal(m.toarray().dtype,mytype)
+
+    def test_abs(self):
+        A = array([[-1, 0, 17], [0, -5, 0], [1, -4, 0], [0, 0, 0]], 'd')
+        assert_equal(abs(A), abs(self.spcreator(A)).toarray())
+
+    def test_round(self):
+        decimal = 1
+        A = array([[-1.35, 0.56], [17.25, -5.98]], 'd')
+        assert_equal(np.around(A, decimals=decimal),
+                     round(self.spcreator(A), ndigits=decimal).toarray())
+
+    def test_elementwise_power(self):
+        A = array([[-4, -3, -2], [-1, 0, 1], [2, 3, 4]], 'd')
+        assert_equal(np.power(A, 2), self.spcreator(A).power(2).toarray())
+
+        #it's element-wise power function, input has to be a scalar
+        assert_raises(NotImplementedError, self.spcreator(A).power, A)
+
+    def test_neg(self):
+        A = array([[-1, 0, 17], [0, -5, 0], [1, -4, 0], [0, 0, 0]], 'd')
+        assert_equal(-A, (-self.spcreator(A)).toarray())
+
+        # see gh-5843
+        A = array([[True, False, False], [False, False, True]])
+        assert_raises(NotImplementedError, self.spcreator(A).__neg__)
+
+    def test_real(self):
+        D = array([[1 + 3j, 2 - 4j]])
+        A = self.spcreator(D)
+        assert_equal(A.real.toarray(), D.real)
+
+    def test_imag(self):
+        D = array([[1 + 3j, 2 - 4j]])
+        A = self.spcreator(D)
+        assert_equal(A.imag.toarray(), D.imag)
+
+    def test_diagonal(self):
+        # Does the matrix's .diagonal() method work?
+        mats = []
+        mats.append([[1,0,2]])
+        mats.append([[1],[0],[2]])
+        mats.append([[0,1],[0,2],[0,3]])
+        mats.append([[0,0,1],[0,0,2],[0,3,0]])
+        mats.append([[1,0],[0,0]])
+
+        mats.append(kron(mats[0],[[1,2]]))
+        mats.append(kron(mats[0],[[1],[2]]))
+        mats.append(kron(mats[1],[[1,2],[3,4]]))
+        mats.append(kron(mats[2],[[1,2],[3,4]]))
+        mats.append(kron(mats[3],[[1,2],[3,4]]))
+        mats.append(kron(mats[3],[[1,2,3,4]]))
+
+        for m in mats:
+            rows, cols = array(m).shape
+            sparse_mat = self.spcreator(m)
+            for k in range(-rows-1, cols+2):
+                assert_equal(sparse_mat.diagonal(k=k), diag(m, k=k))
+            # Test for k beyond boundaries(issue #11949)
+            assert_equal(sparse_mat.diagonal(k=10), diag(m, k=10))
+            assert_equal(sparse_mat.diagonal(k=-99), diag(m, k=-99))
+
+        # Test all-zero matrix.
+        assert_equal(self.spcreator((40, 16130)).diagonal(), np.zeros(40))
+        # Test empty matrix
+        # https://github.com/scipy/scipy/issues/11949
+        assert_equal(self.spcreator((0, 0)).diagonal(), np.empty(0))
+        assert_equal(self.spcreator((15, 0)).diagonal(), np.empty(0))
+        assert_equal(self.spcreator((0, 5)).diagonal(10), np.empty(0))
+
+    def test_trace(self):
+        # For square matrix
+        A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+        B = self.spcreator(A)
+        for k in range(-2, 3):
+            assert_equal(A.trace(offset=k), B.trace(offset=k))
+
+        # For rectangular matrix
+        A = np.array([[1, 2, 3], [4, 5, 6]])
+        B = self.spcreator(A)
+        for k in range(-1, 3):
+            assert_equal(A.trace(offset=k), B.trace(offset=k))
+
+    def test_reshape(self):
+        x = self.spcreator([[1, 0, 7], [0, 0, 0], [0, 3, 0], [0, 0, 5]])
+        for order in ['C', 'F']:
+            for s in [(12, 1), (1, 12)]:
+                assert_array_equal(x.reshape(s, order=order).toarray(),
+                                   x.toarray().reshape(s, order=order))
+
+        # This example is taken from the stackoverflow answer at
+        # https://stackoverflow.com/q/16511879
+        x = self.spcreator([[0, 10, 0, 0], [0, 0, 0, 0], [0, 20, 30, 40]])
+        y = x.reshape((2, 6))  # Default order is 'C'
+        desired = [[0, 10, 0, 0, 0, 0], [0, 0, 0, 20, 30, 40]]
+        assert_array_equal(y.toarray(), desired)
+
+        # Reshape with negative indexes
+        y = x.reshape((2, -1))
+        assert_array_equal(y.toarray(), desired)
+        y = x.reshape((-1, 6))
+        assert_array_equal(y.toarray(), desired)
+        assert_raises(ValueError, x.reshape, (-1, -1))
+
+        # Reshape with star args
+        y = x.reshape(2, 6)
+        assert_array_equal(y.toarray(), desired)
+        assert_raises(TypeError, x.reshape, 2, 6, not_an_arg=1)
+
+        # Reshape with same size is noop unless copy=True
+        y = x.reshape((3, 4))
+        assert_(y is x)
+        y = x.reshape((3, 4), copy=True)
+        assert_(y is not x)
+
+        # Ensure reshape did not alter original size
+        assert_array_equal(x.shape, (3, 4))
+
+        if self.is_array_test:
+            with assert_raises(AttributeError, match="has no setter|n't set attribute"):
+                x.shape = (2, 6)
+        else:  # spmatrix test
+            # Reshape in place
+            x.shape = (2, 6)
+            assert_array_equal(x.toarray(), desired)
+
+        # Reshape to bad ndim
+        assert_raises(ValueError, x.reshape, (x.size,))
+        assert_raises(ValueError, x.reshape, (1, x.size, 1))
+
+    @pytest.mark.slow
+    def test_setdiag_comprehensive(self):
+        def dense_setdiag(a, v, k):
+            v = np.asarray(v)
+            if k >= 0:
+                n = min(a.shape[0], a.shape[1] - k)
+                if v.ndim != 0:
+                    n = min(n, len(v))
+                    v = v[:n]
+                i = np.arange(0, n)
+                j = np.arange(k, k + n)
+                a[i,j] = v
+            elif k < 0:
+                dense_setdiag(a.T, v, -k)
+
+        def check_setdiag(a, b, k):
+            # Check setting diagonal using a scalar, a vector of
+            # correct length, and too short or too long vectors
+            for r in [-1, len(np.diag(a, k)), 2, 30]:
+                if r < 0:
+                    v = np.random.choice(range(1, 20))
+                else:
+                    v = np.random.randint(1, 20, size=r)
+
+                dense_setdiag(a, v, k)
+                with suppress_warnings() as sup:
+                    sup.filter(SparseEfficiencyWarning, "Changing the sparsity structu")
+                    b.setdiag(v, k)
+
+                # check that dense_setdiag worked
+                d = np.diag(a, k)
+                if np.asarray(v).ndim == 0:
+                    assert_array_equal(d, v, err_msg="{msg} {r}")
+                else:
+                    n = min(len(d), len(v))
+                    assert_array_equal(d[:n], v[:n], err_msg="{msg} {r}")
+                # check that sparse setdiag worked
+                assert_array_equal(b.toarray(), a, err_msg="{msg} {r}")
+
+        # comprehensive test
+        np.random.seed(1234)
+        shapes = [(0,5), (5,0), (1,5), (5,1), (5,5)]
+        for dtype in [np.int8, np.float64]:
+            for m,n in shapes:
+                ks = np.arange(-m+1, n-1)
+                for k in ks:
+                    a = np.zeros((m, n), dtype=dtype)
+                    b = self.spcreator((m, n), dtype=dtype)
+
+                    check_setdiag(a, b, k)
+
+                    # check overwriting etc
+                    for k2 in np.random.choice(ks, size=min(len(ks), 5)):
+                        check_setdiag(a, b, k2)
+
+    def test_setdiag(self):
+        # simple test cases
+        m = self.spcreator(np.eye(3))
+        m2 = self.spcreator((4, 4))
+        values = [3, 2, 1]
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            assert_raises(ValueError, m.setdiag, values, k=4)
+            m.setdiag(values)
+            assert_array_equal(m.diagonal(), values)
+            m.setdiag(values, k=1)
+            assert_array_equal(m.toarray(), np.array([[3, 3, 0],
+                                                      [0, 2, 2],
+                                                      [0, 0, 1]]))
+            m.setdiag(values, k=-2)
+            assert_array_equal(m.toarray(), np.array([[3, 3, 0],
+                                                      [0, 2, 2],
+                                                      [3, 0, 1]]))
+            m.setdiag((9,), k=2)
+            assert_array_equal(m.toarray()[0,2], 9)
+            m.setdiag((9,), k=-2)
+            assert_array_equal(m.toarray()[2,0], 9)
+            # test short values on an empty matrix
+            m2.setdiag([1], k=2)
+            assert_array_equal(m2.toarray()[0], [0, 0, 1, 0])
+            # test overwriting that same diagonal
+            m2.setdiag([1, 1], k=2)
+            assert_array_equal(m2.toarray()[:2], [[0, 0, 1, 0],
+                                                  [0, 0, 0, 1]])
+
+    def test_nonzero(self):
+        A = array([[1, 0, 1],[0, 1, 1],[0, 0, 1]])
+        Asp = self.spcreator(A)
+
+        A_nz = {tuple(ij) for ij in transpose(A.nonzero())}
+        Asp_nz = {tuple(ij) for ij in transpose(Asp.nonzero())}
+
+        assert_equal(A_nz, Asp_nz)
+
+    def test_numpy_nonzero(self):
+        # See gh-5987
+        A = array([[1, 0, 1], [0, 1, 1], [0, 0, 1]])
+        Asp = self.spcreator(A)
+
+        A_nz = {tuple(ij) for ij in transpose(np.nonzero(A))}
+        Asp_nz = {tuple(ij) for ij in transpose(np.nonzero(Asp))}
+
+        assert_equal(A_nz, Asp_nz)
+
+    def test_sum(self):
+        np.random.seed(1234)
+        dat_1 = np.array([[0, 1, 2],
+                        [3, -4, 5],
+                        [-6, 7, 9]])
+        dat_2 = np.random.rand(5, 5)
+        dat_3 = np.array([[]])
+        dat_4 = np.zeros((40, 40))
+        dat_5 = sparse.rand(5, 5, density=1e-2).toarray()
+        matrices = [dat_1, dat_2, dat_3, dat_4, dat_5]
+
+        def check(dtype, j):
+            dat = self.asdense(matrices[j], dtype=dtype)
+            datsp = self.spcreator(dat, dtype=dtype)
+            with np.errstate(over='ignore'):
+                assert_array_almost_equal(dat.sum(), datsp.sum())
+                assert_equal(dat.sum().dtype, datsp.sum().dtype)
+                assert_(np.isscalar(datsp.sum(axis=None)))
+                assert_array_almost_equal(dat.sum(axis=None),
+                                          datsp.sum(axis=None))
+                assert_equal(dat.sum(axis=None).dtype,
+                             datsp.sum(axis=None).dtype)
+                assert_array_almost_equal(dat.sum(axis=0), datsp.sum(axis=0))
+                assert_equal(dat.sum(axis=0).dtype, datsp.sum(axis=0).dtype)
+                assert_array_almost_equal(dat.sum(axis=1), datsp.sum(axis=1))
+                assert_equal(dat.sum(axis=1).dtype, datsp.sum(axis=1).dtype)
+                assert_array_almost_equal(dat.sum(axis=-2), datsp.sum(axis=-2))
+                assert_equal(dat.sum(axis=-2).dtype, datsp.sum(axis=-2).dtype)
+                assert_array_almost_equal(dat.sum(axis=-1), datsp.sum(axis=-1))
+                assert_equal(dat.sum(axis=-1).dtype, datsp.sum(axis=-1).dtype)
+
+        for dtype in self.checked_dtypes:
+            for j in range(len(matrices)):
+                check(dtype, j)
+
+    def test_sum_invalid_params(self):
+        out = np.zeros((1, 3))
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        assert_raises(ValueError, datsp.sum, axis=3)
+        assert_raises(TypeError, datsp.sum, axis=(0, 1))
+        assert_raises(TypeError, datsp.sum, axis=1.5)
+        assert_raises(ValueError, datsp.sum, axis=1, out=out)
+
+    def test_sum_dtype(self):
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        def check(dtype):
+            dat_sum = dat.sum(dtype=dtype)
+            datsp_sum = datsp.sum(dtype=dtype)
+
+            assert_array_almost_equal(dat_sum, datsp_sum)
+            assert_equal(dat_sum.dtype, datsp_sum.dtype)
+
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_sum_out(self):
+        keep = not self.is_array_test
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        dat_out = array(0) if self.is_array_test else array([[0]])
+        datsp_out = array(0) if self.is_array_test else matrix([[0]])
+
+        dat.sum(out=dat_out, keepdims=keep)
+        datsp.sum(out=datsp_out)
+        assert_array_almost_equal(dat_out, datsp_out)
+
+        dat_out = np.zeros((3,)) if self.is_array_test else np.zeros((3, 1))
+        datsp_out = np.zeros((3,)) if self.is_array_test else matrix(np.zeros((3, 1)))
+
+        dat.sum(axis=1, out=dat_out, keepdims=keep)
+        datsp.sum(axis=1, out=datsp_out)
+        assert_array_almost_equal(dat_out, datsp_out)
+
+        # check that wrong shape out parameter raises
+        with assert_raises(ValueError, match="output parameter.*wrong.*dimension"):
+            datsp.sum(out=array([0]))
+        with assert_raises(ValueError, match="output parameter.*wrong.*dimension"):
+            datsp.sum(out=array([[0]] if self.is_array_test else 0))
+
+    def test_numpy_sum(self):
+        # See gh-5987
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        dat_sum = np.sum(dat)
+        datsp_sum = np.sum(datsp)
+
+        assert_array_almost_equal(dat_sum, datsp_sum)
+        assert_equal(dat_sum.dtype, datsp_sum.dtype)
+
+    def test_mean(self):
+        keep = not self.is_array_test
+        def check(dtype):
+            dat = array([[0, 1, 2],
+                         [3, 4, 5],
+                         [6, 7, 9]], dtype=dtype)
+            datsp = self.spcreator(dat, dtype=dtype)
+
+            assert_array_almost_equal(dat.mean(), datsp.mean())
+            assert_equal(dat.mean().dtype, datsp.mean().dtype)
+            assert_(np.isscalar(datsp.mean(axis=None)))
+            assert_array_almost_equal(
+                dat.mean(axis=None, keepdims=keep), datsp.mean(axis=None)
+            )
+            assert_equal(dat.mean(axis=None).dtype, datsp.mean(axis=None).dtype)
+            assert_array_almost_equal(
+                dat.mean(axis=0, keepdims=keep), datsp.mean(axis=0)
+            )
+            assert_equal(dat.mean(axis=0).dtype, datsp.mean(axis=0).dtype)
+            assert_array_almost_equal(
+                dat.mean(axis=1, keepdims=keep), datsp.mean(axis=1)
+            )
+            assert_equal(dat.mean(axis=1).dtype, datsp.mean(axis=1).dtype)
+            assert_array_almost_equal(
+                dat.mean(axis=-2, keepdims=keep), datsp.mean(axis=-2)
+            )
+            assert_equal(dat.mean(axis=-2).dtype, datsp.mean(axis=-2).dtype)
+            assert_array_almost_equal(
+                dat.mean(axis=-1, keepdims=keep), datsp.mean(axis=-1)
+            )
+            assert_equal(dat.mean(axis=-1).dtype, datsp.mean(axis=-1).dtype)
+
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_mean_invalid_params(self):
+        out = self.asdense(np.zeros((1, 3)))
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        assert_raises(ValueError, datsp.mean, axis=3)
+        assert_raises(TypeError, datsp.mean, axis=(0, 1))
+        assert_raises(TypeError, datsp.mean, axis=1.5)
+        assert_raises(ValueError, datsp.mean, axis=1, out=out)
+
+    def test_mean_dtype(self):
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        def check(dtype):
+            dat_mean = dat.mean(dtype=dtype)
+            datsp_mean = datsp.mean(dtype=dtype)
+
+            assert_array_almost_equal(dat_mean, datsp_mean)
+            assert_equal(dat_mean.dtype, datsp_mean.dtype)
+
+        for dtype in self.checked_dtypes:
+            check(dtype)
+
+    def test_mean_out(self):
+        keep = not self.is_array_test
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        dat_out = array(0) if self.is_array_test else array([[0]])
+        datsp_out = array(0) if self.is_array_test else matrix([[0]])
+
+        dat.mean(out=dat_out, keepdims=keep)
+        datsp.mean(out=datsp_out)
+        assert_array_almost_equal(dat_out, datsp_out)
+
+        dat_out = np.zeros((3,)) if self.is_array_test else np.zeros((3, 1))
+        datsp_out = np.zeros((3,)) if self.is_array_test else matrix(np.zeros((3, 1)))
+
+        dat.mean(axis=1, out=dat_out, keepdims=keep)
+        datsp.mean(axis=1, out=datsp_out)
+        assert_array_almost_equal(dat_out, datsp_out)
+
+        # check that wrong shape out parameter raises
+        with assert_raises(ValueError, match="output parameter.*wrong.*dimension"):
+            datsp.mean(out=array([0]))
+        with assert_raises(ValueError, match="output parameter.*wrong.*dimension"):
+            datsp.mean(out=array([[0]] if self.is_array_test else 0))
+
+    def test_numpy_mean(self):
+        # See gh-5987
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        dat_mean = np.mean(dat)
+        datsp_mean = np.mean(datsp)
+
+        assert_array_almost_equal(dat_mean, datsp_mean)
+        assert_equal(dat_mean.dtype, datsp_mean.dtype)
+
+    def test_expm(self):
+        M = array([[1, 0, 2], [0, 0, 3], [-4, 5, 6]], float)
+        sM = self.spcreator(M, shape=(3,3), dtype=float)
+        Mexp = scipy.linalg.expm(M)
+
+        N = array([[3., 0., 1.], [0., 2., 0.], [0., 0., 0.]])
+        sN = self.spcreator(N, shape=(3,3), dtype=float)
+        Nexp = scipy.linalg.expm(N)
+
+        with suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "splu converted its input to CSC format",
+            )
+            sup.filter(
+                SparseEfficiencyWarning,
+                "spsolve is more efficient when sparse b is in the CSC matrix format",
+            )
+            sup.filter(
+                SparseEfficiencyWarning,
+                "spsolve requires A be CSC or CSR matrix format",
+            )
+            sMexp = expm(sM).toarray()
+            sNexp = expm(sN).toarray()
+
+        assert_array_almost_equal((sMexp - Mexp), zeros((3, 3)))
+        assert_array_almost_equal((sNexp - Nexp), zeros((3, 3)))
+
+    def test_inv(self):
+        def check(dtype):
+            M = array([[1, 0, 2], [0, 0, 3], [-4, 5, 6]], dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning,
+                           "spsolve requires A be CSC or CSR matrix format",)
+                sup.filter(SparseEfficiencyWarning,
+                           "spsolve is more efficient when sparse b "
+                           "is in the CSC matrix format",)
+                sup.filter(SparseEfficiencyWarning,
+                           "splu converted its input to CSC format",)
+                sM = self.spcreator(M, shape=(3,3), dtype=dtype)
+                sMinv = inv(sM)
+            assert_array_almost_equal(sMinv.dot(sM).toarray(), np.eye(3))
+            assert_raises(TypeError, inv, M)
+        for dtype in [float]:
+            check(dtype)
+
+    @sup_complex
+    def test_from_array(self):
+        A = array([[1,0,0],[2,3,4],[0,5,0],[0,0,0]])
+        assert_array_equal(self.spcreator(A).toarray(), A)
+
+        A = array([[1.0 + 3j, 0, 0],
+                   [0, 2.0 + 5, 0],
+                   [0, 0, 0]])
+        assert_array_equal(self.spcreator(A).toarray(), A)
+        assert_array_equal(self.spcreator(A, dtype='int16').toarray(),A.astype('int16'))
+
+    @sup_complex
+    def test_from_matrix(self):
+        A = self.asdense([[1, 0, 0], [2, 3, 4], [0, 5, 0], [0, 0, 0]])
+        assert_array_equal(self.spcreator(A).todense(), A)
+
+        A = self.asdense([[1.0 + 3j, 0, 0],
+                          [0, 2.0 + 5, 0],
+                          [0, 0, 0]])
+        assert_array_equal(self.spcreator(A).todense(), A)
+        assert_array_equal(
+            self.spcreator(A, dtype='int16').todense(), A.astype('int16')
+        )
+
+    @sup_complex
+    def test_from_list(self):
+        A = [[1,0,0],[2,3,4],[0,5,0],[0,0,0]]
+        assert_array_equal(self.spcreator(A).toarray(), A)
+
+        A = [[1.0 + 3j, 0, 0],
+             [0, 2.0 + 5, 0],
+             [0, 0, 0]]
+        assert_array_equal(self.spcreator(A).toarray(), array(A))
+        assert_array_equal(
+            self.spcreator(A, dtype='int16').toarray(), array(A).astype('int16')
+        )
+
+    @sup_complex
+    def test_from_sparse(self):
+        D = array([[1,0,0],[2,3,4],[0,5,0],[0,0,0]])
+        S = self.csr_container(D)
+        assert_array_equal(self.spcreator(S).toarray(), D)
+        S = self.spcreator(D)
+        assert_array_equal(self.spcreator(S).toarray(), D)
+
+        D = array([[1.0 + 3j, 0, 0],
+                   [0, 2.0 + 5, 0],
+                   [0, 0, 0]])
+        S = self.csr_container(D)
+        assert_array_equal(self.spcreator(S).toarray(), D)
+        assert_array_equal(self.spcreator(S, dtype='int16').toarray(),
+                           D.astype('int16'))
+        S = self.spcreator(D)
+        assert_array_equal(self.spcreator(S).toarray(), D)
+        assert_array_equal(self.spcreator(S, dtype='int16').toarray(),
+                           D.astype('int16'))
+
+    # def test_array(self):
+    #    """test array(A) where A is in sparse format"""
+    #    assert_equal( array(self.datsp), self.dat )
+
+    def test_todense(self):
+        # Check C- or F-contiguous (default).
+        chk = self.datsp.todense()
+        assert isinstance(chk, np.ndarray if self.is_array_test else np.matrix)
+        assert_array_equal(chk, self.dat)
+        assert_(chk.flags.c_contiguous != chk.flags.f_contiguous)
+        # Check C-contiguous (with arg).
+        chk = self.datsp.todense(order='C')
+        assert_array_equal(chk, self.dat)
+        assert_(chk.flags.c_contiguous)
+        assert_(not chk.flags.f_contiguous)
+        # Check F-contiguous (with arg).
+        chk = self.datsp.todense(order='F')
+        assert_array_equal(chk, self.dat)
+        assert_(not chk.flags.c_contiguous)
+        assert_(chk.flags.f_contiguous)
+        # Check with out argument (array).
+        out = np.zeros(self.datsp.shape, dtype=self.datsp.dtype)
+        chk = self.datsp.todense(out=out)
+        assert_array_equal(self.dat, out)
+        assert_array_equal(self.dat, chk)
+        assert np.may_share_memory(chk, out)
+        # Check with out array (matrix).
+        out = self.asdense(np.zeros(self.datsp.shape, dtype=self.datsp.dtype))
+        chk = self.datsp.todense(out=out)
+        assert_array_equal(self.dat, out)
+        assert_array_equal(self.dat, chk)
+        assert np.may_share_memory(chk, out)
+        a = array([[1.,2.,3.]])
+        dense_dot_dense = a @ self.dat
+        check = a @ self.datsp.todense()
+        assert_array_equal(dense_dot_dense, check)
+        b = array([[1.,2.,3.,4.]]).T
+        dense_dot_dense = self.dat @ b
+        check2 = self.datsp.todense() @ b
+        assert_array_equal(dense_dot_dense, check2)
+        # Check bool data works.
+        spbool = self.spcreator(self.dat, dtype=bool)
+        matbool = self.dat.astype(bool)
+        assert_array_equal(spbool.todense(), matbool)
+
+    def test_toarray(self):
+        # Check C- or F-contiguous (default).
+        dat = asarray(self.dat)
+        chk = self.datsp.toarray()
+        assert_array_equal(chk, dat)
+        assert_(chk.flags.c_contiguous != chk.flags.f_contiguous)
+        # Check C-contiguous (with arg).
+        chk = self.datsp.toarray(order='C')
+        assert_array_equal(chk, dat)
+        assert_(chk.flags.c_contiguous)
+        assert_(not chk.flags.f_contiguous)
+        # Check F-contiguous (with arg).
+        chk = self.datsp.toarray(order='F')
+        assert_array_equal(chk, dat)
+        assert_(not chk.flags.c_contiguous)
+        assert_(chk.flags.f_contiguous)
+        # Check with output arg.
+        out = np.zeros(self.datsp.shape, dtype=self.datsp.dtype)
+        self.datsp.toarray(out=out)
+        assert_array_equal(chk, dat)
+        # Check that things are fine when we don't initialize with zeros.
+        out[...] = 1.
+        self.datsp.toarray(out=out)
+        assert_array_equal(chk, dat)
+        a = array([1.,2.,3.])
+        dense_dot_dense = dot(a, dat)
+        check = dot(a, self.datsp.toarray())
+        assert_array_equal(dense_dot_dense, check)
+        b = array([1.,2.,3.,4.])
+        dense_dot_dense = dot(dat, b)
+        check2 = dot(self.datsp.toarray(), b)
+        assert_array_equal(dense_dot_dense, check2)
+        # Check bool data works.
+        spbool = self.spcreator(self.dat, dtype=bool)
+        arrbool = dat.astype(bool)
+        assert_array_equal(spbool.toarray(), arrbool)
+
+    @sup_complex
+    def test_astype(self):
+        D = array([[2.0 + 3j, 0, 0],
+                   [0, 4.0 + 5j, 0],
+                   [0, 0, 0]])
+        S = self.spcreator(D)
+
+        for x in supported_dtypes:
+            # Check correctly casted
+            D_casted = D.astype(x)
+            for copy in (True, False):
+                S_casted = S.astype(x, copy=copy)
+                assert_equal(S_casted.dtype, D_casted.dtype)  # correct type
+                assert_equal(S_casted.toarray(), D_casted)    # correct values
+                assert_equal(S_casted.format, S.format)       # format preserved
+            # Check correctly copied
+            assert_(S_casted.astype(x, copy=False) is S_casted)
+            S_copied = S_casted.astype(x, copy=True)
+            assert_(S_copied is not S_casted)
+
+            def check_equal_but_not_same_array_attribute(attribute):
+                a = getattr(S_casted, attribute)
+                b = getattr(S_copied, attribute)
+                assert_array_equal(a, b)
+                assert_(a is not b)
+                i = (0,) * b.ndim
+                b_i = b[i]
+                b[i] = not b[i]
+                assert_(a[i] != b[i])
+                b[i] = b_i
+
+            if S_casted.format in ('csr', 'csc', 'bsr'):
+                for attribute in ('indices', 'indptr', 'data'):
+                    check_equal_but_not_same_array_attribute(attribute)
+            elif S_casted.format == 'coo':
+                for attribute in ('row', 'col', 'data'):
+                    check_equal_but_not_same_array_attribute(attribute)
+            elif S_casted.format == 'dia':
+                for attribute in ('offsets', 'data'):
+                    check_equal_but_not_same_array_attribute(attribute)
+
+    @sup_complex
+    def test_astype_immutable(self):
+        D = array([[2.0 + 3j, 0, 0],
+                   [0, 4.0 + 5j, 0],
+                   [0, 0, 0]])
+        S = self.spcreator(D)
+        if hasattr(S, 'data'):
+            S.data.flags.writeable = False
+        if S.format in ('csr', 'csc', 'bsr'):
+            S.indptr.flags.writeable = False
+            S.indices.flags.writeable = False
+        for x in supported_dtypes:
+            D_casted = D.astype(x)
+            S_casted = S.astype(x)
+            assert_equal(S_casted.dtype, D_casted.dtype)
+
+    def test_mul_scalar(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_array_equal(dat*2, (datsp*2).toarray())
+            assert_array_equal(dat*17.3, (datsp*17.3).toarray())
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_rmul_scalar(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_array_equal(2*dat, (2*datsp).toarray())
+            assert_array_equal(17.3*dat, (17.3*datsp).toarray())
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    # GitHub issue #15210
+    def test_rmul_scalar_type_error(self):
+        datsp = self.datsp_dtypes[np.float64]
+        with assert_raises(TypeError):
+            None * datsp
+
+    def test_add(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            a = dat.copy()
+            a[0,2] = 2.0
+            b = datsp
+            c = b + a
+            assert_array_equal(c, b.toarray() + a)
+
+            c = b + b.tocsr()
+            assert_array_equal(c.toarray(),
+                               b.toarray() + b.toarray())
+
+            # test broadcasting
+            c = b + a[0]
+            assert_array_equal(c, b.toarray() + a[0])
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_radd(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            a = dat.copy()
+            a[0,2] = 2.0
+            b = datsp
+            c = a + b
+            assert_array_equal(c, a + b.toarray())
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_sub(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_array_equal((datsp - datsp).toarray(), np.zeros((3, 4)))
+            assert_array_equal((datsp - 0).toarray(), dat)
+
+            A = self.spcreator(
+                np.array([[1, 0, 0, 4], [-1, 0, 0, 0], [0, 8, 0, -5]], 'd')
+            )
+            assert_array_equal((datsp - A).toarray(), dat - A.toarray())
+            assert_array_equal((A - datsp).toarray(), A.toarray() - dat)
+
+            # test broadcasting
+            assert_array_equal(datsp - dat[0], dat - dat[0])
+
+        for dtype in self.math_dtypes:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            check(dtype)
+
+    def test_rsub(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            assert_array_equal((dat - datsp),[[0,0,0,0],[0,0,0,0],[0,0,0,0]])
+            assert_array_equal((datsp - dat),[[0,0,0,0],[0,0,0,0],[0,0,0,0]])
+            assert_array_equal((0 - datsp).toarray(), -dat)
+
+            A = self.spcreator([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],dtype='d')
+            assert_array_equal((dat - A), dat - A.toarray())
+            assert_array_equal((A - dat), A.toarray() - dat)
+            assert_array_equal(A.toarray() - datsp, A.toarray() - dat)
+            assert_array_equal(datsp - A.toarray(), dat - A.toarray())
+
+            # test broadcasting
+            assert_array_equal(dat[0] - datsp, dat[0] - dat)
+
+        for dtype in self.math_dtypes:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            check(dtype)
+
+    def test_add0(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            # Adding 0 to a sparse matrix
+            assert_array_equal((datsp + 0).toarray(), dat)
+            # use sum (which takes 0 as a starting value)
+            sumS = sum([k * datsp for k in range(1, 3)])
+            sumD = sum([k * dat for k in range(1, 3)])
+            assert_almost_equal(sumS.toarray(), sumD)
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_elementwise_multiply(self):
+        # real/real
+        A = array([[4,0,9],[2,-3,5]])
+        B = array([[0,7,0],[0,-4,0]])
+        Asp = self.spcreator(A)
+        Bsp = self.spcreator(B)
+        assert_almost_equal(Asp.multiply(Bsp).toarray(), A*B)  # sparse/sparse
+        assert_almost_equal(Asp.multiply(B).toarray(), A*B)  # sparse/dense
+
+        # complex/complex
+        C = array([[1-2j,0+5j,-1+0j],[4-3j,-3+6j,5]])
+        D = array([[5+2j,7-3j,-2+1j],[0-1j,-4+2j,9]])
+        Csp = self.spcreator(C)
+        Dsp = self.spcreator(D)
+        assert_almost_equal(Csp.multiply(Dsp).toarray(), C*D)  # sparse/sparse
+        assert_almost_equal(Csp.multiply(D).toarray(), C*D)  # sparse/dense
+
+        # real/complex
+        assert_almost_equal(Asp.multiply(Dsp).toarray(), A*D)  # sparse/sparse
+        assert_almost_equal(Asp.multiply(D).toarray(), A*D)  # sparse/dense
+
+    def test_elementwise_multiply_broadcast(self):
+        A = array([4])
+        B = array([[-9]])
+        C = array([1,-1,0])
+        D = array([[7,9,-9]])
+        E = array([[3],[2],[1]])
+        F = array([[8,6,3],[-4,3,2],[6,6,6]])
+        G = [1, 2, 3]
+        H = np.ones((3, 4))
+        J = H.T
+        K = array([[0]])
+        L = array([[[1,2],[0,1]]])
+
+        # Some arrays can't be cast as spmatrices (A,C,L) so leave
+        # them out.
+        Bsp = self.spcreator(B)
+        Dsp = self.spcreator(D)
+        Esp = self.spcreator(E)
+        Fsp = self.spcreator(F)
+        Hsp = self.spcreator(H)
+        Hspp = self.spcreator(H[0,None])
+        Jsp = self.spcreator(J)
+        Jspp = self.spcreator(J[:,0,None])
+        Ksp = self.spcreator(K)
+
+        matrices = [A, B, C, D, E, F, G, H, J, K, L]
+        spmatrices = [Bsp, Dsp, Esp, Fsp, Hsp, Hspp, Jsp, Jspp, Ksp]
+
+        # sparse/sparse
+        for i in spmatrices:
+            for j in spmatrices:
+                try:
+                    dense_mult = i.toarray() * j.toarray()
+                except ValueError:
+                    assert_raises(ValueError, i.multiply, j)
+                    continue
+                sp_mult = i.multiply(j)
+                assert_almost_equal(sp_mult.toarray(), dense_mult)
+
+        # sparse/dense
+        for i in spmatrices:
+            for j in matrices:
+                try:
+                    dense_mult = i.toarray() * j
+                except TypeError:
+                    continue
+                except ValueError:
+                    assert_raises(ValueError, i.multiply, j)
+                    continue
+                sp_mult = i.multiply(j)
+                if issparse(sp_mult):
+                    assert_almost_equal(sp_mult.toarray(), dense_mult)
+                else:
+                    assert_almost_equal(sp_mult, dense_mult)
+
+    def test_elementwise_divide(self):
+        expected = [[1,np.nan,np.nan,1],
+                    [1,np.nan,1,np.nan],
+                    [np.nan,1,np.nan,np.nan]]
+        assert_array_equal(toarray(self.datsp / self.datsp), expected)
+
+        denom = self.spcreator([[1,0,0,4],[-1,0,0,0],[0,8,0,-5]],dtype='d')
+        expected = [[1,np.nan,np.nan,0.5],
+                    [-3,np.nan,inf,np.nan],
+                    [np.nan,0.25,np.nan,0]]
+        assert_array_equal(toarray(self.datsp / denom), expected)
+
+        # complex
+        A = array([[1-2j,0+5j,-1+0j],[4-3j,-3+6j,5]])
+        B = array([[5+2j,7-3j,-2+1j],[0-1j,-4+2j,9]])
+        Asp = self.spcreator(A)
+        Bsp = self.spcreator(B)
+        assert_almost_equal(toarray(Asp / Bsp), A/B)
+
+        # integer
+        A = array([[1,2,3],[-3,2,1]])
+        B = array([[0,1,2],[0,-2,3]])
+        Asp = self.spcreator(A)
+        Bsp = self.spcreator(B)
+        with np.errstate(divide='ignore'):
+            assert_array_equal(toarray(Asp / Bsp), A / B)
+
+        # mismatching sparsity patterns
+        A = array([[0,1],[1,0]])
+        B = array([[1,0],[1,0]])
+        Asp = self.spcreator(A)
+        Bsp = self.spcreator(B)
+        with np.errstate(divide='ignore', invalid='ignore'):
+            assert_array_equal(np.array(toarray(Asp / Bsp)), A / B)
+
+    def test_pow(self):
+        A = array([[1, 0, 2, 0], [0, 3, 4, 0], [0, 5, 0, 0], [0, 6, 7, 8]])
+        B = self.spcreator(A)
+
+        if self.is_array_test:  # sparrays use element-wise power
+            # Todo: Add 1+3j to tested exponent list when np1.24 is no longer supported
+            #    Complex exponents of 0 (our implicit fill value) change in numpy-1.25
+            #    from `(nan+nanj)` to `0`. Old value makes array element-wise result
+            #    dense and is hard to check for without any `isnan` method.
+            # So while untested here, element-wise complex exponents work with np>=1.25.
+            # for exponent in [1, 2, 2.2, 3, 1+3j]:
+            for exponent in [1, 2, 2.2, 3]:
+                ret_sp = B**exponent
+                ret_np = A**exponent
+                assert_array_equal(ret_sp.toarray(), ret_np)
+                assert_equal(ret_sp.dtype, ret_np.dtype)
+
+            # invalid exponents
+            assert_raises(NotImplementedError, B.__pow__, 0)
+            assert_raises(ValueError, B.__pow__, -1)
+
+            # nonsquare matrix
+            B = self.spcreator(A[:3,:])
+            assert_equal((B**1).toarray(), B.toarray())
+        else:  # test sparse matrix. spmatrices use matrix multiplicative power
+            for exponent in [0,1,2,3]:
+                ret_sp = B**exponent
+                ret_np = np.linalg.matrix_power(A, exponent)
+                assert_array_equal(ret_sp.toarray(), ret_np)
+                assert_equal(ret_sp.dtype, ret_np.dtype)
+
+            # invalid exponents
+            for exponent in [-1, 2.2, 1 + 3j]:
+                assert_raises(ValueError, B.__pow__, exponent)
+
+            # nonsquare matrix
+            B = self.spcreator(A[:3,:])
+            assert_raises(TypeError, B.__pow__, 1)
+
+    def test_rmatvec(self):
+        M = self.spcreator([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
+        assert_array_almost_equal([1,2,3,4] @ M, dot([1,2,3,4], M.toarray()))
+        row = array([[1,2,3,4]])
+        assert_array_almost_equal(row @ M, row @ M.toarray())
+
+    def test_small_multiplication(self):
+        # test that A*x works for x with shape () (1,) (1,1) and (1,0)
+        A = self.spcreator([[1],[2],[3]])
+
+        assert_(issparse(A * array(1)))
+        assert_equal((A * array(1)).toarray(), [[1], [2], [3]])
+
+        assert_equal(A @ array([1]), array([1, 2, 3]))
+        assert_equal(A @ array([[1]]), array([[1], [2], [3]]))
+        assert_equal(A @ np.ones((1, 1)), array([[1], [2], [3]]))
+        assert_equal(A @ np.ones((1, 0)), np.ones((3, 0)))
+
+    def test_star_vs_at_sign_for_sparray_and_spmatrix(self):
+        # test that * is matmul for spmatrix and mul for sparray
+        A = np.array([[1], [2], [3]])
+        Asp = self.spcreator(A)
+
+        if self.is_array_test:
+            assert_array_almost_equal((Asp * np.ones((3, 1))).toarray(), A)
+            assert_array_almost_equal((Asp * array([[1]])).toarray(), A)
+        else:
+            assert_equal(Asp * array([1]), array([1, 2, 3]))
+            assert_equal(Asp * array([[1]]), array([[1], [2], [3]]))
+            assert_equal(Asp * np.ones((1, 0)), np.ones((3, 0)))
+
+    def test_binop_custom_type(self):
+        # Non-regression test: previously, binary operations would raise
+        # NotImplementedError instead of returning NotImplemented
+        # (https://docs.python.org/library/constants.html#NotImplemented)
+        # so overloading Custom + matrix etc. didn't work.
+        A = self.spcreator([[1], [2], [3]])
+        B = BinopTester()
+        assert_equal(A + B, "matrix on the left")
+        assert_equal(A - B, "matrix on the left")
+        assert_equal(A * B, "matrix on the left")
+        assert_equal(B + A, "matrix on the right")
+        assert_equal(B - A, "matrix on the right")
+        assert_equal(B * A, "matrix on the right")
+
+        assert_equal(A @ B, "matrix on the left")
+        assert_equal(B @ A, "matrix on the right")
+
+    def test_binop_custom_type_with_shape(self):
+        A = self.spcreator([[1], [2], [3]])
+        B = BinopTester_with_shape((3,1))
+        assert_equal(A + B, "matrix on the left")
+        assert_equal(A - B, "matrix on the left")
+        assert_equal(A * B, "matrix on the left")
+        assert_equal(B + A, "matrix on the right")
+        assert_equal(B - A, "matrix on the right")
+        assert_equal(B * A, "matrix on the right")
+
+        assert_equal(A @ B, "matrix on the left")
+        assert_equal(B @ A, "matrix on the right")
+
+    def test_mul_custom_type(self):
+        class Custom:
+            def __init__(self, scalar):
+                self.scalar = scalar
+
+            def __rmul__(self, other):
+                return other * self.scalar
+
+        scalar = 2
+        A = self.spcreator([[1],[2],[3]])
+        c = Custom(scalar)
+        A_scalar = A * scalar
+        A_c = A * c
+        assert_array_equal_dtype(A_scalar.toarray(), A_c.toarray())
+        assert_equal(A_scalar.format, A_c.format)
+
+    def test_comparisons_custom_type(self):
+        A = self.spcreator([[1], [2], [3]])
+        B = ComparisonTester()
+        assert_equal(A == B, "eq")
+        assert_equal(A != B, "ne")
+        assert_equal(A > B, "lt")
+        assert_equal(A >= B, "le")
+        assert_equal(A < B, "gt")
+        assert_equal(A <= B, "ge")
+
+    def test_dot_scalar(self):
+        M = self.spcreator(array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]))
+        scalar = 10
+        actual = M.dot(scalar)
+        expected = M * scalar
+
+        assert_allclose(actual.toarray(), expected.toarray())
+
+    def test_matmul(self):
+        M = self.spcreator(array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]))
+        B = self.spcreator(array([[0,1],[1,0],[0,2]],'d'))
+        col = array([[1,2,3]]).T
+
+        matmul = operator.matmul
+        # check matrix-vector
+        assert_array_almost_equal(matmul(M, col), M.toarray() @ col)
+
+        # check matrix-matrix
+        assert_array_almost_equal(matmul(M, B).toarray(), (M @ B).toarray())
+        assert_array_almost_equal(matmul(M.toarray(), B), (M @ B).toarray())
+        assert_array_almost_equal(matmul(M, B.toarray()), (M @ B).toarray())
+
+        # check error on matrix-scalar
+        assert_raises(ValueError, matmul, M, 1)
+        assert_raises(ValueError, matmul, 1, M)
+
+    def test_matvec(self):
+        M = self.spcreator([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
+        col = array([[1,2,3]]).T
+
+        assert_array_almost_equal(M @ col, M.toarray() @ col)
+
+        # check result dimensions (ticket #514)
+        assert_equal((M @ array([1,2,3])).shape,(4,))
+        assert_equal((M @ array([[1],[2],[3]])).shape,(4,1))
+        assert_equal((M @ matrix([[1],[2],[3]])).shape,(4,1))
+
+        # check result type
+        assert_(isinstance(M @ array([1,2,3]), ndarray))
+        matrix_or_array = ndarray if self.is_array_test else np.matrix
+        assert_(isinstance(M @ matrix([1,2,3]).T, matrix_or_array))
+
+        # ensure exception is raised for improper dimensions
+        bad_vecs = [array([1,2]), array([1,2,3,4]), array([[1],[2]]),
+                    matrix([1,2,3]), matrix([[1],[2]])]
+        for x in bad_vecs:
+            assert_raises(ValueError, M.__matmul__, x)
+
+        # The current relationship between sparse matrix products and array
+        # products is as follows:
+        assert_almost_equal(M@array([1,2,3]), dot(M.toarray(),[1,2,3]))
+        assert_almost_equal(M@[[1],[2],[3]], np.atleast_2d(dot(M.toarray(),[1,2,3])).T)
+        # Note that the result of M * x is dense if x has a singleton dimension.
+
+        # Currently M.matvec(asarray(col)) is rank-1, whereas M.matvec(col)
+        # is rank-2.  Is this desirable?
+
+    def test_matmat_sparse(self):
+        a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
+        a2 = array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])
+        b = matrix([[0,1],[1,0],[0,2]],'d')
+        asp = self.spcreator(a)
+        bsp = self.spcreator(b)
+        assert_array_almost_equal((asp @ bsp).toarray(), a @ b)
+        assert_array_almost_equal(asp @ b, a @ b)
+        assert_array_almost_equal(a @ bsp, a @ b)
+        assert_array_almost_equal(a2 @ bsp, a @ b)
+
+        # Now try performing cross-type multiplication:
+        csp = bsp.tocsc()
+        c = b
+        want = a @ c
+        assert_array_almost_equal((asp @ csp).toarray(), want)
+        assert_array_almost_equal(asp @ c, want)
+
+        assert_array_almost_equal(a @ csp, want)
+        assert_array_almost_equal(a2 @ csp, want)
+        csp = bsp.tocsr()
+        assert_array_almost_equal((asp @ csp).toarray(), want)
+        assert_array_almost_equal(asp @ c, want)
+
+        assert_array_almost_equal(a @ csp, want)
+        assert_array_almost_equal(a2 @ csp, want)
+        csp = bsp.tocoo()
+        assert_array_almost_equal((asp @ csp).toarray(), want)
+        assert_array_almost_equal(asp @ c, want)
+
+        assert_array_almost_equal(a @ csp, want)
+        assert_array_almost_equal(a2 @ csp, want)
+
+        # Test provided by Andy Fraser, 2006-03-26
+        L = 30
+        frac = .3
+        random.seed(0)  # make runs repeatable
+        A = zeros((L,2))
+        for i in range(L):
+            for j in range(2):
+                r = random.random()
+                if r < frac:
+                    A[i,j] = r/frac
+
+        A = self.spcreator(A)
+        B = A @ A.T
+        assert_array_almost_equal(B.toarray(), A.toarray() @ A.T.toarray())
+        assert_array_almost_equal(B.toarray(), A.toarray() @ A.toarray().T)
+
+        # check dimension mismatch 2x2 times 3x2
+        A = self.spcreator([[1,2],[3,4]])
+        B = self.spcreator([[1,2],[3,4],[5,6]])
+        assert_raises(ValueError, A.__matmul__, B)
+        if self.is_array_test:
+            assert_raises(ValueError, A.__mul__, B)
+
+    def test_matmat_dense(self):
+        a = [[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]
+        asp = self.spcreator(a)
+
+        # check both array and matrix types
+        bs = [array([[1,2],[3,4],[5,6]]), matrix([[1,2],[3,4],[5,6]])]
+
+        for b in bs:
+            result = asp @ b
+            assert_(isinstance(result, ndarray if self.is_array_test else type(b)))
+            assert_equal(result.shape, (4,2))
+            assert_equal(result, dot(a,b))
+
+    def test_sparse_format_conversions(self):
+        A = sparse.kron([[1,0,2],[0,3,4],[5,0,0]], [[1,2],[0,3]])
+        D = A.toarray()
+        A = self.spcreator(A)
+
+        for format in ['bsr','coo','csc','csr','dia','dok','lil']:
+            a = A.asformat(format)
+            assert_equal(a.format,format)
+            assert_array_equal(a.toarray(), D)
+
+            b = self.spcreator(D+3j).asformat(format)
+            assert_equal(b.format,format)
+            assert_array_equal(b.toarray(), D+3j)
+
+            c = self.spcreator(D).asformat(format)
+            assert_equal(c.format,format)
+            assert_array_equal(c.toarray(), D)
+
+        for format in ['array', 'dense']:
+            a = A.asformat(format)
+            assert_array_equal(a, D)
+
+            b = self.spcreator(D+3j).asformat(format)
+            assert_array_equal(b, D+3j)
+
+    def test_tobsr(self):
+        x = array([[1,0,2,0],[0,0,0,0],[0,0,4,5]])
+        y = array([[0,1,2],[3,0,5]])
+        A = kron(x,y)
+        Asp = self.spcreator(A)
+        for format in ['bsr']:
+            fn = getattr(Asp, 'to' + format)
+
+            for X in [1, 2, 3, 6]:
+                for Y in [1, 2, 3, 4, 6, 12]:
+                    assert_equal(fn(blocksize=(X, Y)).toarray(), A)
+
+    def test_transpose(self):
+        dat_1 = self.dat
+        dat_2 = np.array([[]])
+        matrices = [dat_1, dat_2]
+
+        def check(dtype, j):
+            dat = array(matrices[j], dtype=dtype)
+            datsp = self.spcreator(dat)
+
+            a = datsp.transpose()
+            b = dat.transpose()
+
+            assert_array_equal(a.toarray(), b)
+            assert_array_equal(a.transpose().toarray(), dat)
+            assert_array_equal(datsp.transpose(axes=(1, 0)).toarray(), b)
+            assert_equal(a.dtype, b.dtype)
+
+        # See gh-5987
+        empty = self.spcreator((3, 4))
+        assert_array_equal(np.transpose(empty).toarray(),
+                           np.transpose(zeros((3, 4))))
+        assert_array_equal(empty.T.toarray(), zeros((4, 3)))
+        assert_raises(ValueError, empty.transpose, axes=0)
+
+        for dtype in self.checked_dtypes:
+            for j in range(len(matrices)):
+                check(dtype, j)
+
+    def test_add_dense(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            # adding a dense matrix to a sparse matrix
+            sum1 = dat + datsp
+            assert_array_equal(sum1, dat + dat)
+            sum2 = datsp + dat
+            assert_array_equal(sum2, dat + dat)
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_sub_dense(self):
+        # subtracting a dense matrix to/from a sparse matrix
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            # Behavior is different for bool.
+            if dat.dtype == bool:
+                sum1 = dat - datsp
+                assert_array_equal(sum1, dat - dat)
+                sum2 = datsp - dat
+                assert_array_equal(sum2, dat - dat)
+            else:
+                # Manually add to avoid upcasting from scalar
+                # multiplication.
+                sum1 = (dat + dat + dat) - datsp
+                assert_array_equal(sum1, dat + dat)
+                sum2 = (datsp + datsp + datsp) - dat
+                assert_array_equal(sum2, dat + dat)
+
+        for dtype in self.math_dtypes:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            check(dtype)
+
+    def test_maximum_minimum(self):
+        A_dense = np.array([[1, 0, 3], [0, 4, 5], [0, 0, 0]])
+        B_dense = np.array([[1, 1, 2], [0, 3, 6], [1, -1, 0]])
+
+        A_dense_cpx = np.array([[1, 0, 3], [0, 4+2j, 5], [0, 1j, -1j]])
+
+        def check(dtype, dtype2, btype):
+            if np.issubdtype(dtype, np.complexfloating):
+                A = self.spcreator(A_dense_cpx.astype(dtype))
+            else:
+                A = self.spcreator(A_dense.astype(dtype))
+            if btype == 'scalar':
+                B = dtype2.type(1)
+            elif btype == 'scalar2':
+                B = dtype2.type(-1)
+            elif btype == 'dense':
+                B = B_dense.astype(dtype2)
+            elif btype == 'sparse':
+                B = self.spcreator(B_dense.astype(dtype2))
+            else:
+                raise ValueError()
+
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning,
+                           "Taking maximum .minimum. with > 0 .< 0. number "
+                           "results to a dense matrix")
+
+                max_s = A.maximum(B)
+                min_s = A.minimum(B)
+
+            max_d = np.maximum(toarray(A), toarray(B))
+            assert_array_equal(toarray(max_s), max_d)
+            assert_equal(max_s.dtype, max_d.dtype)
+
+            min_d = np.minimum(toarray(A), toarray(B))
+            assert_array_equal(toarray(min_s), min_d)
+            assert_equal(min_s.dtype, min_d.dtype)
+
+        for dtype in self.math_dtypes:
+            for dtype2 in [np.int8, np.float64, np.complex128]:
+                for btype in ['scalar', 'scalar2', 'dense', 'sparse']:
+                    check(np.dtype(dtype), np.dtype(dtype2), btype)
+
+    def test_copy(self):
+        # Check whether the copy=True and copy=False keywords work
+        A = self.datsp
+
+        # check that copy preserves format
+        assert_equal(A.copy().format, A.format)
+        assert_equal(A.__class__(A,copy=True).format, A.format)
+        assert_equal(A.__class__(A,copy=False).format, A.format)
+
+        assert_equal(A.copy().toarray(), A.toarray())
+        assert_equal(A.__class__(A, copy=True).toarray(), A.toarray())
+        assert_equal(A.__class__(A, copy=False).toarray(), A.toarray())
+
+        # check that XXX_array.toXXX() works
+        toself = getattr(A,'to' + A.format)
+        assert_(toself() is A)
+        assert_(toself(copy=False) is A)
+        assert_equal(toself(copy=True).format, A.format)
+        assert_equal(toself(copy=True).toarray(), A.toarray())
+
+        # check whether the data is copied?
+        assert_(not sparse_may_share_memory(A.copy(), A))
+
+    # test that __iter__ is compatible with NumPy matrix
+    def test_iterator(self):
+        B = self.asdense(np.arange(50).reshape(5, 10))
+        A = self.spcreator(B)
+
+        for x, y in zip(A, B):
+            assert_equal(x.toarray(), y)
+
+    def test_size_zero_matrix_arithmetic(self):
+        # Test basic matrix arithmetic with shapes like (0,0), (10,0),
+        # (0, 3), etc.
+        mat = array([])
+        a = mat.reshape((0, 0))
+        b = mat.reshape((0, 1))
+        c = mat.reshape((0, 5))
+        d = mat.reshape((1, 0))
+        e = mat.reshape((5, 0))
+        f = np.ones([5, 5])
+
+        asp = self.spcreator(a)
+        bsp = self.spcreator(b)
+        csp = self.spcreator(c)
+        dsp = self.spcreator(d)
+        esp = self.spcreator(e)
+        fsp = self.spcreator(f)
+
+        # matrix product.
+        assert_array_equal(asp.dot(asp).toarray(), np.dot(a, a))
+        assert_array_equal(bsp.dot(dsp).toarray(), np.dot(b, d))
+        assert_array_equal(dsp.dot(bsp).toarray(), np.dot(d, b))
+        assert_array_equal(csp.dot(esp).toarray(), np.dot(c, e))
+        assert_array_equal(csp.dot(fsp).toarray(), np.dot(c, f))
+        assert_array_equal(esp.dot(csp).toarray(), np.dot(e, c))
+        assert_array_equal(dsp.dot(csp).toarray(), np.dot(d, c))
+        assert_array_equal(fsp.dot(esp).toarray(), np.dot(f, e))
+
+        # bad matrix products
+        assert_raises(ValueError, dsp.dot, e)
+        assert_raises(ValueError, asp.dot, d)
+
+        # elemente-wise multiplication
+        assert_array_equal(asp.multiply(asp).toarray(), np.multiply(a, a))
+        assert_array_equal(bsp.multiply(bsp).toarray(), np.multiply(b, b))
+        assert_array_equal(dsp.multiply(dsp).toarray(), np.multiply(d, d))
+
+        assert_array_equal(asp.multiply(a).toarray(), np.multiply(a, a))
+        assert_array_equal(bsp.multiply(b).toarray(), np.multiply(b, b))
+        assert_array_equal(dsp.multiply(d).toarray(), np.multiply(d, d))
+
+        assert_array_equal(asp.multiply(6).toarray(), np.multiply(a, 6))
+        assert_array_equal(bsp.multiply(6).toarray(), np.multiply(b, 6))
+        assert_array_equal(dsp.multiply(6).toarray(), np.multiply(d, 6))
+
+        # bad element-wise multiplication
+        assert_raises(ValueError, asp.multiply, c)
+        assert_raises(ValueError, esp.multiply, c)
+
+        # Addition
+        assert_array_equal(asp.__add__(asp).toarray(), a.__add__(a))
+        assert_array_equal(bsp.__add__(bsp).toarray(), b.__add__(b))
+        assert_array_equal(dsp.__add__(dsp).toarray(), d.__add__(d))
+
+        # bad addition
+        assert_raises(ValueError, asp.__add__, dsp)
+        assert_raises(ValueError, bsp.__add__, asp)
+
+    def test_size_zero_conversions(self):
+        mat = array([])
+        a = mat.reshape((0, 0))
+        b = mat.reshape((0, 5))
+        c = mat.reshape((5, 0))
+
+        for m in [a, b, c]:
+            spm = self.spcreator(m)
+            assert_array_equal(spm.tocoo().toarray(), m)
+            assert_array_equal(spm.tocsr().toarray(), m)
+            assert_array_equal(spm.tocsc().toarray(), m)
+            assert_array_equal(spm.tolil().toarray(), m)
+            assert_array_equal(spm.todok().toarray(), m)
+            assert_array_equal(spm.tobsr().toarray(), m)
+
+    def test_dtype_check(self):
+        a = np.array([[3.5, 0, 1.1], [0, 0, 0]], dtype=np.float16)
+        with assert_raises(ValueError, match="does not support dtype"):
+            self.spcreator(a)
+
+        A32 = self.spcreator(a.astype(np.float32))
+        with assert_raises(ValueError, match="does not support dtype"):
+            self.spcreator(A32, dtype=np.float16)
+
+    def test_pickle(self):
+        import pickle
+        sup = suppress_warnings()
+        sup.filter(SparseEfficiencyWarning)
+
+        @sup
+        def check():
+            datsp = self.datsp.copy()
+            for protocol in range(pickle.HIGHEST_PROTOCOL):
+                sploaded = pickle.loads(pickle.dumps(datsp, protocol=protocol))
+                assert_equal(datsp.shape, sploaded.shape)
+                assert_array_equal(datsp.toarray(), sploaded.toarray())
+                assert_equal(datsp.format, sploaded.format)
+                # Hacky check for class member equality. This assumes that
+                # all instance variables are one of:
+                #  1. Plain numpy ndarrays
+                #  2. Tuples of ndarrays
+                #  3. Types that support equality comparison with ==
+                for key, val in datsp.__dict__.items():
+                    if isinstance(val, np.ndarray):
+                        assert_array_equal(val, sploaded.__dict__[key])
+                    elif (isinstance(val, tuple) and val
+                          and isinstance(val[0], np.ndarray)):
+                        assert_array_equal(val, sploaded.__dict__[key])
+                    else:
+                        assert_(val == sploaded.__dict__[key])
+        check()
+
+    def test_unary_ufunc_overrides(self):
+        def check(name):
+            if name == "sign":
+                pytest.skip("sign conflicts with comparison op "
+                            "support on Numpy")
+            if self.datsp.format in ["dok", "lil"]:
+                pytest.skip("Unary ops not implemented for dok/lil")
+            ufunc = getattr(np, name)
+
+            X = self.spcreator(np.arange(20).reshape(4, 5) / 20.)
+            X0 = ufunc(X.toarray())
+
+            X2 = ufunc(X)
+            assert_array_equal(X2.toarray(), X0)
+
+        for name in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh",
+                     "arcsinh", "arctanh", "rint", "sign", "expm1", "log1p",
+                     "deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt",
+                     "abs"]:
+            check(name)
+
+    def test_resize(self):
+        # resize(shape) resizes the matrix in-place
+        D = np.array([[1, 0, 3, 4],
+                      [2, 0, 0, 0],
+                      [3, 0, 0, 0]])
+        S = self.spcreator(D)
+        assert_(S.resize((3, 2)) is None)
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [3, 0]])
+        S.resize((2, 2))
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0]])
+        S.resize((3, 2))
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [0, 0]])
+        S.resize((3, 3))
+        assert_array_equal(S.toarray(), [[1, 0, 0],
+                                         [2, 0, 0],
+                                         [0, 0, 0]])
+        # test no-op
+        S.resize((3, 3))
+        assert_array_equal(S.toarray(), [[1, 0, 0],
+                                         [2, 0, 0],
+                                         [0, 0, 0]])
+
+        # test *args
+        S.resize(3, 2)
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [0, 0]])
+
+        if self.is_array_test and S.format in ["coo", "csr"]:
+            S.resize(1)
+        else:
+            assert_raises((ValueError, NotImplementedError, IndexError), S.resize, 1)
+
+        for bad_shape in [(-1, 2), (2, -1), (1, 2, 3)]:
+            assert_raises(ValueError, S.resize, bad_shape)
+
+    def test_constructor1_base(self):
+        A = self.datsp
+
+        self_format = A.format
+
+        C = A.__class__(A, copy=False)
+        assert_array_equal_dtype(A.toarray(), C.toarray())
+        if self_format not in NON_ARRAY_BACKED_FORMATS:
+            assert_(sparse_may_share_memory(A, C))
+
+        C = A.__class__(A, dtype=A.dtype, copy=False)
+        assert_array_equal_dtype(A.toarray(), C.toarray())
+        if self_format not in NON_ARRAY_BACKED_FORMATS:
+            assert_(sparse_may_share_memory(A, C))
+
+        C = A.__class__(A, dtype=np.float32, copy=False)
+        assert_array_equal(A.toarray(), C.toarray())
+
+        C = A.__class__(A, copy=True)
+        assert_array_equal_dtype(A.toarray(), C.toarray())
+        assert_(not sparse_may_share_memory(A, C))
+
+        for other_format in ['csr', 'csc', 'coo', 'dia', 'dok', 'lil']:
+            if other_format == self_format:
+                continue
+            B = A.asformat(other_format)
+            C = A.__class__(B, copy=False)
+            assert_array_equal_dtype(A.toarray(), C.toarray())
+
+            C = A.__class__(B, copy=True)
+            assert_array_equal_dtype(A.toarray(), C.toarray())
+            assert_(not sparse_may_share_memory(B, C))
+
+
+class _TestInplaceArithmetic:
+    def test_inplace_dense(self):
+        a = np.ones((3, 4))
+        b = self.spcreator(a)
+
+        x = a.copy()
+        y = a.copy()
+        x += a
+        y += b
+        assert_array_equal(x, y)
+
+        x = a.copy()
+        y = a.copy()
+        x -= a
+        y -= b
+        assert_array_equal(x, y)
+
+        if self.is_array_test:
+            # Elementwise multiply from sparray.__rmul__
+            x = a.copy()
+            y = a.copy()
+            with assert_raises(ValueError, match="inconsistent shapes"):
+                x *= b.T
+            x = x * a
+            y *= b
+            assert_array_equal(x, y.toarray())
+        else:
+            # Matrix multiply from spmatrix.__rmul__
+            x = a.copy()
+            y = a.copy()
+            with assert_raises(ValueError, match="dimension mismatch"):
+                x *= b
+            x = x.dot(a.T)
+            y *= b.T
+            assert_array_equal(x, y)
+
+        # Matrix multiply from __rmatmul__
+        y = a.copy()
+        # skip this test if numpy doesn't support __imatmul__ yet.
+        # move out of the try/except once numpy 1.24 is no longer supported.
+        try:
+            y @= b.T
+        except TypeError:
+            pass
+        else:
+            x = a.copy()
+            y = a.copy()
+            with assert_raises(ValueError, match="dimension mismatch"):
+                x @= b
+            x = x.dot(a.T)
+            y @= b.T
+            assert_array_equal(x, y)
+
+        # Floor division is not supported
+        with assert_raises(TypeError, match="unsupported operand"):
+            x //= b
+
+    def test_imul_scalar(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            # Avoid implicit casting.
+            if np.can_cast(int, dtype, casting='same_kind'):
+                a = datsp.copy()
+                a *= 2
+                b = dat.copy()
+                b *= 2
+                assert_array_equal(b, a.toarray())
+
+            if np.can_cast(float, dtype, casting='same_kind'):
+                a = datsp.copy()
+                a *= 17.3
+                b = dat.copy()
+                b *= 17.3
+                assert_array_equal(b, a.toarray())
+
+        for dtype in self.math_dtypes:
+            check(dtype)
+
+    def test_idiv_scalar(self):
+        def check(dtype):
+            dat = self.dat_dtypes[dtype]
+            datsp = self.datsp_dtypes[dtype]
+
+            if np.can_cast(int, dtype, casting='same_kind'):
+                a = datsp.copy()
+                a /= 2
+                b = dat.copy()
+                b /= 2
+                assert_array_equal(b, a.toarray())
+
+            if np.can_cast(float, dtype, casting='same_kind'):
+                a = datsp.copy()
+                a /= 17.3
+                b = dat.copy()
+                b /= 17.3
+                assert_array_equal(b, a.toarray())
+
+        for dtype in self.math_dtypes:
+            # /= should only be used with float dtypes to avoid implicit
+            # casting.
+            if not np.can_cast(dtype, np.dtype(int)):
+                check(dtype)
+
+    def test_inplace_success(self):
+        # Inplace ops should work even if a specialized version is not
+        # implemented, falling back to x = x  y
+        a = self.spcreator(np.eye(5))
+        b = self.spcreator(np.eye(5))
+        bp = self.spcreator(np.eye(5))
+
+        b += a
+        bp = bp + a
+        assert_allclose(b.toarray(), bp.toarray())
+
+        if self.is_array_test:
+            b *= a
+            bp = bp * a
+            assert_allclose(b.toarray(), bp.toarray())
+
+        b @= a
+        bp = bp @ a
+        assert_allclose(b.toarray(), bp.toarray())
+
+        b -= a
+        bp = bp - a
+        assert_allclose(b.toarray(), bp.toarray())
+
+        with assert_raises(TypeError, match="unsupported operand"):
+            a //= b
+
+
+class _TestGetSet:
+    def test_getelement(self):
+        def check(dtype):
+            D = array([[1,0,0],
+                       [4,3,0],
+                       [0,2,0],
+                       [0,0,0]], dtype=dtype)
+            A = self.spcreator(D)
+
+            M,N = D.shape
+
+            for i in range(-M, M):
+                for j in range(-N, N):
+                    assert_equal(A[i,j], D[i,j])
+
+            assert_equal(type(A[1,1]), dtype)
+
+            for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1), (1, 2, 3)]:
+                assert_raises((IndexError, TypeError), A.__getitem__, ij)
+
+        for dtype in supported_dtypes:
+            check(np.dtype(dtype))
+
+    def test_setelement(self):
+        def check(dtype):
+            A = self.spcreator((3,4), dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[0, 0] = dtype.type(0)  # bug 870
+                A[1, 2] = dtype.type(4.0)
+                A[0, 1] = dtype.type(3)
+                A[2, 0] = dtype.type(2.0)
+                A[0,-1] = dtype.type(8)
+                A[-1,-2] = dtype.type(7)
+                A[0, 1] = dtype.type(5)
+
+            if dtype != np.bool_:
+                assert_array_equal(
+                    A.toarray(),
+                    [
+                        [0, 5, 0, 8],
+                        [0, 0, 4, 0],
+                        [2, 0, 7, 0]
+                    ]
+                )
+
+            for ij in [(0,4),(-1,4),(3,0),(3,4),(3,-1)]:
+                assert_raises(IndexError, A.__setitem__, ij, 123.0)
+
+            for v in [[1,2,3], array([1,2,3])]:
+                assert_raises(ValueError, A.__setitem__, (0,0), v)
+
+            if (not np.issubdtype(dtype, np.complexfloating) and
+                    dtype != np.bool_):
+                for v in [3j]:
+                    assert_raises(TypeError, A.__setitem__, (0,0), v)
+
+        for dtype in supported_dtypes:
+            check(np.dtype(dtype))
+
+    def test_negative_index_assignment(self):
+        # Regression test for GitHub issue 4428.
+
+        def check(dtype):
+            A = self.spcreator((3, 10), dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[0, -4] = 1
+            assert_equal(A[0, -4], 1)
+
+        for dtype in self.math_dtypes:
+            check(np.dtype(dtype))
+
+    def test_scalar_assign_2(self):
+        n, m = (5, 10)
+
+        def _test_set(i, j, nitems):
+            msg = f"{i!r} ; {j!r} ; {nitems!r}"
+            A = self.spcreator((n, m))
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[i, j] = 1
+            assert_almost_equal(A.sum(), nitems, err_msg=msg)
+            assert_almost_equal(A[i, j], 1, err_msg=msg)
+
+        # [i,j]
+        for i, j in [(2, 3), (-1, 8), (-1, -2), (array(-1), -2), (-1, array(-2)),
+                     (array(-1), array(-2))]:
+            _test_set(i, j, 1)
+
+    def test_index_scalar_assign(self):
+        A = self.spcreator((5, 5))
+        B = np.zeros((5, 5))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            for C in [A, B]:
+                C[0,1] = 1
+                C[3,0] = 4
+                C[3,0] = 9
+        assert_array_equal(A.toarray(), B)
+
+
+@pytest.mark.thread_unsafe
+class _TestSolve:
+    def test_solve(self):
+        # Test whether the lu_solve command segfaults, as reported by Nils
+        # Wagner for a 64-bit machine, 02 March 2005 (EJS)
+        n = 20
+        np.random.seed(0)  # make tests repeatable
+        A = zeros((n,n), dtype=complex)
+        x = np.random.rand(n)
+        y = np.random.rand(n-1)+1j*np.random.rand(n-1)
+        r = np.random.rand(n)
+        for i in range(len(x)):
+            A[i,i] = x[i]
+        for i in range(len(y)):
+            A[i,i+1] = y[i]
+            A[i+1,i] = conjugate(y[i])
+        A = self.spcreator(A)
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning,
+                       "splu converted its input to CSC format")
+            x = splu(A).solve(r)
+        assert_almost_equal(A @ x,r)
+
+
+class _TestSlicing:
+    def test_dtype_preservation(self):
+        assert_equal(self.spcreator((1,10), dtype=np.int16)[0,1:5].dtype, np.int16)
+        assert_equal(self.spcreator((1,10), dtype=np.int32)[0,1:5].dtype, np.int32)
+        assert_equal(self.spcreator((1,10), dtype=np.float32)[0,1:5].dtype, np.float32)
+        assert_equal(self.spcreator((1,10), dtype=np.float64)[0,1:5].dtype, np.float64)
+
+    def test_dtype_preservation_empty_slice(self):
+        # This should be parametrized with pytest, but something in the parent
+        # class creation used in this file breaks pytest.mark.parametrize.
+        for dt in [np.int16, np.int32, np.float32, np.float64]:
+            A = self.spcreator((3, 2), dtype=dt)
+            assert_equal(A[:, 0:0:2].dtype, dt)
+            assert_equal(A[0:0:2, :].dtype, dt)
+            assert_equal(A[0, 0:0:2].dtype, dt)
+            assert_equal(A[0:0:2, 0].dtype, dt)
+
+    def test_get_horiz_slice(self):
+        B = self.asdense(arange(50.).reshape(5,10))
+        A = self.spcreator(B)
+        r0, r1, r2 = (0, 1, 2) if self.is_array_test else ([0], [1], [2])
+        assert_array_equal(B[r1, :], A[1, :].toarray())
+        assert_array_equal(B[r1, 2:5], A[1, 2:5].toarray())
+
+        C = self.asdense([[1, 2, 1], [4, 0, 6], [0, 0, 0], [0, 0, 1]])
+        D = self.spcreator(C)
+        assert_array_equal(C[r1, 1:3], D[1, 1:3].toarray())
+
+        # Now test slicing when a row contains only zeros
+        E = self.asdense([[1, 2, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]])
+        F = self.spcreator(E)
+        assert_array_equal(E[r1, 1:3], F[1, 1:3].toarray())
+        assert_array_equal(E[r2, -2:], F[2, -2:].toarray())
+
+        # The following should raise exceptions:
+        assert_raises(IndexError, A.__getitem__, (slice(None), 11))
+        assert_raises(IndexError, A.__getitem__, (6, slice(3, 7)))
+
+    def test_get_vert_slice(self):
+        B = arange(50.).reshape(5, 10)
+        A = self.spcreator(B)
+        c0, c1, c2 = (0, 1, 2) if self.is_array_test else ([0], [1], [2])
+        assert_array_equal(B[2:5, c0], A[2:5, 0].toarray())
+        assert_array_equal(B[:, c1], A[:, 1].toarray())
+
+        C = array([[1, 2, 1], [4, 0, 6], [0, 0, 0], [0, 0, 1]])
+        D = self.spcreator(C)
+        assert_array_equal(C[1:3, c1], D[1:3, 1].toarray())
+        assert_array_equal(C[:, c2], D[:, 2].toarray())
+
+        # Now test slicing when a column contains only zeros
+        E = array([[1, 0, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]])
+        F = self.spcreator(E)
+        assert_array_equal(E[:, c1], F[:, 1].toarray())
+        assert_array_equal(E[-2:, c2], F[-2:, 2].toarray())
+
+        # The following should raise exceptions:
+        assert_raises(IndexError, A.__getitem__, (slice(None), 11))
+        assert_raises(IndexError, A.__getitem__, (6, slice(3, 7)))
+
+    def test_get_slices(self):
+        B = arange(50.).reshape(5, 10)
+        A = self.spcreator(B)
+        assert_array_equal(A[2:5, 0:3].toarray(), B[2:5, 0:3])
+        assert_array_equal(A[1:, :-1].toarray(), B[1:, :-1])
+        assert_array_equal(A[:-1, 1:].toarray(), B[:-1, 1:])
+
+        # Now test slicing when a column contains only zeros
+        E = array([[1, 0, 1], [4, 0, 0], [0, 0, 0], [0, 0, 1]])
+        F = self.spcreator(E)
+        assert_array_equal(E[1:2, 1:2], F[1:2, 1:2].toarray())
+        assert_array_equal(E[:, 1:], F[:, 1:].toarray())
+
+    def test_non_unit_stride_2d_indexing(self):
+        # Regression test -- used to silently ignore the stride.
+        v0 = np.random.rand(50, 50)
+        try:
+            v = self.spcreator(v0)[0:25:2, 2:30:3]
+        except ValueError:
+            # if unsupported
+            raise pytest.skip("feature not implemented")
+
+        assert_array_equal(v.toarray(), v0[0:25:2, 2:30:3])
+
+    def test_slicing_2(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        # [i,j]
+        assert_equal(A[2,3], B[2,3])
+        assert_equal(A[-1,8], B[-1,8])
+        assert_equal(A[-1,-2],B[-1,-2])
+        assert_equal(A[array(-1),-2],B[-1,-2])
+        assert_equal(A[-1,array(-2)],B[-1,-2])
+        assert_equal(A[array(-1),array(-2)],B[-1,-2])
+
+        # [i,1:2]
+        assert_equal(A[2, :].toarray(), B[2, :])
+        assert_equal(A[2, 5:-2].toarray(), B[2, 5:-2])
+        assert_equal(A[array(2), 5:-2].toarray(), B[2, 5:-2])
+
+        # [1:2,j]
+        assert_equal(A[:, 2].toarray(), B[:, 2])
+        assert_equal(A[3:4, 9].toarray(), B[3:4, 9])
+        assert_equal(A[1:4, -5].toarray(), B[1:4, -5])
+        assert_equal(A[2:-1, 3].toarray(), B[2:-1, 3])
+        assert_equal(A[2:-1, array(3)].toarray(), B[2:-1, 3])
+
+        # [1:2,1:2]
+        assert_equal(A[1:2, 1:2].toarray(), B[1:2, 1:2])
+        assert_equal(A[4:, 3:].toarray(), B[4:, 3:])
+        assert_equal(A[:4, :5].toarray(), B[:4, :5])
+        assert_equal(A[2:-1, :5].toarray(), B[2:-1, :5])
+
+        # [i]
+        assert_equal(A[1, :].toarray(), B[1, :])
+        assert_equal(A[-2, :].toarray(), B[-2, :])
+        assert_equal(A[array(-2), :].toarray(), B[-2, :])
+
+        # [1:2]
+        assert_equal(A[1:4].toarray(), B[1:4])
+        assert_equal(A[1:-2].toarray(), B[1:-2])
+
+        # Check bug reported by Robert Cimrman:
+        # http://thread.gmane.org/gmane.comp.python.scientific.devel/7986 (dead link)
+        s = slice(int8(2),int8(4),None)
+        assert_equal(A[s, :].toarray(), B[2:4, :])
+        assert_equal(A[:, s].toarray(), B[:, 2:4])
+
+    @pytest.mark.fail_slow(2)
+    def test_slicing_3(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        s_ = np.s_
+        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
+                  s_[15:20], s_[3:2],
+                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
+                  0, 1, s_[:], s_[1:5], -1, -2, -5,
+                  array(-1), np.int8(-3)]
+
+        def check_1(a):
+            x = A[a]
+            y = B[a]
+            if y.shape == ():
+                assert_equal(x, y, repr(a))
+            else:
+                if x.size == 0 and y.size == 0:
+                    pass
+                else:
+                    assert_array_equal(x.toarray(), y, repr(a))
+
+        for j, a in enumerate(slices):
+            check_1(a)
+
+        def check_2(a, b):
+            # Indexing np.matrix with 0-d arrays seems to be broken,
+            # as they seem not to be treated as scalars.
+            # https://github.com/numpy/numpy/issues/3110
+            if isinstance(a, np.ndarray):
+                ai = int(a)
+            else:
+                ai = a
+            if isinstance(b, np.ndarray):
+                bi = int(b)
+            else:
+                bi = b
+
+            x = A[a, b]
+            y = B[ai, bi]
+
+            if y.shape == ():
+                assert_equal(x, y, repr((a, b)))
+            else:
+                if x.size == 0 and y.size == 0:
+                    pass
+                else:
+                    assert_array_equal(x.toarray(), y, repr((a, b)))
+
+        for i, a in enumerate(slices):
+            for j, b in enumerate(slices):
+                check_2(a, b)
+
+        # Check out of bounds etc. systematically
+        extra_slices = []
+        for a, b, c in itertools.product(*([(None, 0, 1, 2, 5, 15,
+                                             -1, -2, 5, -15)]*3)):
+            if c == 0:
+                continue
+            extra_slices.append(slice(a, b, c))
+
+        for a in extra_slices:
+            check_2(a, a)
+            check_2(a, -2)
+            check_2(-2, a)
+
+    def test_None_slicing(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        assert A[1, 2].ndim == 0
+        assert A[None, 1, 2:4].shape == (1, 2)
+        assert A[None, 1, 2, None].shape == (1, 1)
+
+        # see gh-22458
+        assert A[None, 1].shape == (1, 10)
+        assert A[1, None].shape == (1, 10)
+        assert A[None, 1, :].shape == (1, 10)
+        assert A[1, None, :].shape == (1, 10)
+        assert A[1, :, None].shape == (10, 1)
+
+        assert A[None, 1:3, 2].shape == B[None, 1:3, 2].shape == (1, 2)
+        assert A[1:3, None, 2].shape == B[1:3, None, 2].shape == (2, 1)
+        assert A[1:3, 2, None].shape == B[1:3, 2, None].shape == (2, 1)
+        assert A[None, 1, 2:4].shape == B[None, 1, 2:4].shape == (1, 2)
+        assert A[1, None, 2:4].shape == B[1, None, 2:4].shape == (1, 2)
+        assert A[1, 2:4, None].shape == B[1, 2:4, None].shape == (2, 1)
+
+        # different for spmatrix
+        if self.is_array_test:
+            assert A[1:3, 2].shape == B[1:3, 2].shape == (2,)
+            assert A[1, 2:4].shape == B[1, 2:4].shape == (2,)
+            assert A[None, 1, 2].shape == B[None, 1, 2].shape == (1,)
+            assert A[1, None, 2].shape == B[1, None, 2].shape == (1,)
+            assert A[1, 2, None].shape == B[1, 2, None].shape == (1,)
+        else:
+            assert A[1, 2:4].shape == B[1, 2:4].shape == (1, 2)
+            assert A[1:3, 2].shape == B[1:3, 2].shape == (2, 1)
+            assert A[None, 1, 2].shape == B[None, 1, 2].shape == (1, 1)
+            assert A[1, None, 2].shape == B[1, None, 2].shape == (1, 1)
+            assert A[1, 2, None].shape == B[1, 2, None].shape == (1, 1)
+
+    def test_ellipsis_slicing(self):
+        b = self.asdense(arange(50).reshape(5,10))
+        a = self.spcreator(b)
+
+        assert_array_equal(a[...].toarray(), b[...])
+        assert_array_equal(a[...,].toarray(), b[...,])
+
+        assert_array_equal(a[4, ...].toarray(), b[4, ...])
+        assert_array_equal(a[..., 4].toarray(), b[..., 4])
+        assert_array_equal(a[..., 5].toarray(), b[..., 5])
+        with pytest.raises(IndexError, match='index .5. out of range'):
+            a[5, ...]
+        with pytest.raises(IndexError, match='index .10. out of range'):
+            a[..., 10]
+        with pytest.raises(IndexError, match='index .5. out of range'):
+            a.T[..., 5]
+
+        assert_array_equal(a[1:, ...].toarray(), b[1:, ...])
+        assert_array_equal(a[..., 1:].toarray(), b[..., 1:])
+        assert_array_equal(a[:2, ...].toarray(), b[:2, ...])
+        assert_array_equal(a[..., :2].toarray(), b[..., :2])
+
+        # check slice limit outside range
+        assert_array_equal(a[:5, ...].toarray(), b[:5, ...])
+        assert_array_equal(a[..., :5].toarray(), b[..., :5])
+        assert_array_equal(a[5:, ...].toarray(), b[5:, ...])
+        assert_array_equal(a[..., 5:].toarray(), b[..., 5:])
+        assert_array_equal(a[10:, ...].toarray(), b[10:, ...])
+        assert_array_equal(a[..., 10:].toarray(), b[..., 10:])
+
+        # ellipsis should be ignored
+        assert_array_equal(a[1:, 1, ...].toarray(), b[1:, 1, ...])
+        assert_array_equal(a[1, ..., 1:].toarray(), b[1, ..., 1:])
+        assert_array_equal(a[..., 1, 1:].toarray(), b[1, ..., 1:])
+        assert_array_equal(a[:2, 1, ...].toarray(), b[:2, 1, ...])
+        assert_array_equal(a[1, ..., :2].toarray(), b[1, ..., :2])
+        assert_array_equal(a[..., 1, :2].toarray(), b[1, ..., :2])
+        # These return ints
+        assert_equal(a[1, 1, ...], b[1, 1, ...])
+        assert_equal(a[1, ..., 1], b[1, ..., 1])
+
+    def test_ellipsis_fancy_bool(self):
+        numpy_a = self.asdense(arange(50).reshape(5, 10))
+        a = self.spcreator(numpy_a)
+
+        ix5 = [True, False, True, False, True]
+        ix10 = [False] * 5 + ix5  # same number of True values as ix5
+        ix10_6True = ix5 + ix5  # not same number of True values as ix5
+        full_ix = [ix10] * 5
+
+        assert_array_equal(toarray(a[full_ix, ...]), numpy_a[full_ix, ...])
+        assert_array_equal(toarray(a[..., full_ix]), numpy_a[..., full_ix])
+
+        assert_array_equal(toarray(a[ix5, ...]), numpy_a[ix5, ...])
+        assert_array_equal(toarray(a[..., ix10]), numpy_a[..., ix10])
+
+        assert_array_equal(toarray(a[ix5, ..., ix10]), numpy_a[ix5, ..., ix10])
+        assert_array_equal(toarray(a[..., ix5, ix10]), numpy_a[..., ix5, ix10])
+        assert_array_equal(toarray(a[ix5, ix10, ...]), numpy_a[ix5, ix10, ...])
+
+        with assert_raises(ValueError, match="shape mismatch"):
+            a[ix5, ix10_6True]
+
+    def test_ellipsis_fancy_slicing(self):
+        b = self.asdense(arange(50).reshape(5, 10))
+        a = self.spcreator(b)
+
+        assert_array_equal(a[[4], ...].toarray(), b[[4], ...])
+        assert_array_equal(a[[2, 4], ...].toarray(), b[[2, 4], ...])
+        assert_array_equal(a[..., [4]].toarray(), b[..., [4]])
+        assert_array_equal(a[..., [2, 4]].toarray(), b[..., [2, 4]])
+
+        assert_array_equal(a[[4], 1, ...].toarray(), b[[4], 1, ...])
+        assert_array_equal(a[[2, 4], 1, ...].toarray(), b[[2, 4], 1, ...])
+        assert_array_equal(a[[4], ..., 1].toarray(), b[[4], ..., 1])
+        assert_array_equal(a[..., [4], 1].toarray(), b[..., [4], 1])
+        # fancy index gives dense
+        assert_array_equal(toarray(a[[2, 4], ..., [2, 4]]), b[[2, 4], ..., [2, 4]])
+        assert_array_equal(toarray(a[..., [2, 4], [2, 4]]), b[..., [2, 4], [2, 4]])
+
+    def test_multiple_ellipsis_slicing(self):
+        a = self.spcreator(arange(6).reshape(3, 2))
+
+        with pytest.raises(IndexError,
+                           match='an index can only have a single ellipsis'):
+            a[..., ...]
+        with pytest.raises(IndexError,
+                           match='an index can only have a single ellipsis'):
+            a[..., 1, ...]
+
+
+class _TestSlicingAssign:
+    def test_slice_scalar_assign(self):
+        A = self.spcreator((5, 5))
+        B = np.zeros((5, 5))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            for C in [A, B]:
+                C[0:1,1] = 1
+                C[3:0,0] = 4
+                C[3:4,0] = 9
+                C[0,4:] = 1
+                C[3::-1,4:] = 9
+        assert_array_equal(A.toarray(), B)
+
+    def test_slice_assign_2(self):
+        n, m = (5, 10)
+
+        def _test_set(i, j):
+            msg = f"i={i!r}; j={j!r}"
+            A = self.spcreator((n, m))
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[i, j] = 1
+            B = np.zeros((n, m))
+            B[i, j] = 1
+            assert_array_almost_equal(A.toarray(), B, err_msg=msg)
+        # [i,1:2]
+        for i, j in [(2, slice(3)), (2, slice(None, 10, 4)), (2, slice(5, -2)),
+                     (array(2), slice(5, -2))]:
+            _test_set(i, j)
+
+    def test_self_self_assignment(self):
+        # Tests whether a row of one sparse array can be assigned to another.
+        B = self.spcreator((4,3))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            B[0,0] = 2
+            B[1,2] = 7
+            B[2,1] = 3
+            B[3,0] = 10
+
+            A = B / 10
+            B[0,:] = A[0,:]
+            assert_array_equal(A[0,:].toarray(), B[0,:].toarray())
+
+            A = B / 10
+            B[:,:] = A[:1,:1]
+            assert_array_equal(np.zeros((4,3)) + A[0,0], B.toarray())
+
+            A = B / 10
+            B[:-1,0] = A[None,0,:].T
+            assert_array_equal(A[0,:].toarray().T, B[:-1,0].toarray())
+
+    def test_slice_assignment(self):
+        B = self.spcreator((4,3))
+        expected = array([[10,0,0],
+                          [0,0,6],
+                          [0,14,0],
+                          [0,0,0]])
+        block = [[1,0],[0,4]]
+
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            B[0,0] = 5
+            B[1,2] = 3
+            B[2,1] = 7
+            B[:,:] = B+B
+            assert_array_equal(B.toarray(), expected)
+
+            B[:2,:2] = self.csc_container(array(block))
+            assert_array_equal(B.toarray()[:2, :2], block)
+
+    def test_sparsity_modifying_assignment(self):
+        B = self.spcreator((4,3))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            B[0,0] = 5
+            B[1,2] = 3
+            B[2,1] = 7
+            B[3,0] = 10
+            B[:3] = self.csr_container(np.eye(3))
+
+        expected = array([[1,0,0],[0,1,0],[0,0,1],[10,0,0]])
+        assert_array_equal(B.toarray(), expected)
+
+    def test_set_slice(self):
+        A = self.spcreator((5,10))
+        B = array(zeros((5, 10), float))
+        s_ = np.s_
+        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
+                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
+                  0, 1, s_[:], s_[1:5], -1, -2, -5,
+                  array(-1), np.int8(-3)]
+
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            for j, a in enumerate(slices):
+                A[a] = j
+                B[a] = j
+                assert_array_equal(A.toarray(), B, repr(a))
+
+            for i, a in enumerate(slices):
+                for j, b in enumerate(slices):
+                    A[a,b] = 10*i + 1000*(j+1)
+                    B[a,b] = 10*i + 1000*(j+1)
+                    assert_array_equal(A.toarray(), B, repr((a, b)))
+
+            A[0, 1:10:2] = range(1, 10, 2)
+            B[0, 1:10:2] = range(1, 10, 2)
+            assert_array_equal(A.toarray(), B)
+            A[1:5:2, 0] = np.arange(1, 5, 2)[:, None]
+            B[1:5:2, 0] = np.arange(1, 5, 2)[:]
+            assert_array_equal(A.toarray(), B)
+
+        # The next commands should raise exceptions
+        assert_raises(ValueError, A.__setitem__, (0, 0), list(range(100)))
+        assert_raises(ValueError, A.__setitem__, (0, 0), arange(100))
+        assert_raises(ValueError, A.__setitem__, (0, slice(None)),
+                      list(range(100)))
+        assert_raises(ValueError, A.__setitem__, (slice(None), 1),
+                      list(range(100)))
+        assert_raises(ValueError, A.__setitem__, (slice(None), 1), A.copy())
+        assert_raises(ValueError, A.__setitem__,
+                      ([[1, 2, 3], [0, 3, 4]], [1, 2, 3]), [1, 2, 3, 4])
+        assert_raises(ValueError, A.__setitem__,
+                      ([[1, 2, 3], [0, 3, 4], [4, 1, 3]],
+                       [[1, 2, 4], [0, 1, 3]]), [2, 3, 4])
+        assert_raises(ValueError, A.__setitem__, (slice(4), 0),
+                      [[1, 2], [3, 4]])
+
+    def test_assign_empty(self):
+        A = self.spcreator(np.ones((2, 3)))
+        B = self.spcreator((1, 2))
+        A[1, :2] = B
+        assert_array_equal(A.toarray(), [[1, 1, 1], [0, 0, 1]])
+
+    def test_assign_1d_slice(self):
+        A = self.spcreator(np.ones((3, 3)))
+        x = np.zeros(3)
+        A[:, 0] = x
+        A[1, :] = x
+        assert_array_equal(A.toarray(), [[0, 1, 1], [0, 0, 0], [0, 1, 1]])
+
+
+class _TestFancyIndexing:
+    """Tests fancy indexing features.  The tests for any matrix formats
+    that implement these features should derive from this class.
+    """
+
+    def test_dtype_preservation_empty_index(self):
+        # This should be parametrized with pytest, but something in the parent
+        # class creation used in this file breaks pytest.mark.parametrize.
+        for dt in [np.int16, np.int32, np.float32, np.float64]:
+            A = self.spcreator((3, 2), dtype=dt)
+            assert_equal(A[:, [False, False]].dtype, dt)
+            assert_equal(A[[False, False, False], :].dtype, dt)
+            assert_equal(A[:, []].dtype, dt)
+            assert_equal(A[[], :].dtype, dt)
+
+    def test_bad_index(self):
+        A = self.spcreator(np.zeros([5, 5]))
+        assert_raises((IndexError, ValueError, TypeError), A.__getitem__, "foo")
+        assert_raises((IndexError, ValueError, TypeError), A.__getitem__, (2, "foo"))
+        assert_raises((IndexError, ValueError), A.__getitem__,
+                      ([1, 2, 3], [1, 2, 3, 4]))
+
+    def test_fancy_indexing(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        # [i]
+        assert_equal(A[[3]].toarray(), B[[3]])
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+
+        # [i,[1,2]]
+        assert_equal(A[3, [3]].toarray(), B[3, [3]])
+        assert_equal(A[3, [1, 3]].toarray(), B[3, [1, 3]])
+        assert_equal(A[-1, [2, -5]].toarray(), B[-1, [2, -5]])
+        assert_equal(A[array(-1), [2, -5]].toarray(), B[-1, [2, -5]])
+        assert_equal(A[-1, array([2, -5])].toarray(), B[-1, [2, -5]])
+        assert_equal(A[array(-1), array([2, -5])].toarray(), B[-1, [2, -5]])
+
+        # [1:2,[1,2]]
+        assert_equal(A[:, [2, 8, 3, -1]].toarray(), B[:, [2, 8, 3, -1]])
+        assert_equal(A[3:4, [9]].toarray(), B[3:4, [9]])
+        assert_equal(A[1:4, [-1, -5]].toarray(), B[1:4, [-1, -5]])
+        assert_equal(A[1:4, array([-1, -5])].toarray(), B[1:4, [-1, -5]])
+
+        # [[1,2],j]
+        assert_equal(A[[3], 3].toarray(), B[[3], 3])
+        assert_equal(A[[1, 3], 3].toarray(), B[[1, 3], 3])
+        assert_equal(A[[2, -5], -4].toarray(), B[[2, -5], -4])
+        assert_equal(A[array([2, -5]), -4].toarray(), B[[2, -5], -4])
+        assert_equal(A[[2, -5], array(-4)].toarray(), B[[2, -5], -4])
+        assert_equal(A[array([2, -5]), array(-4)].toarray(), B[[2, -5], -4])
+
+        # [[1,2],1:2]
+        assert_equal(A[[3], :].toarray(), B[[3], :])
+        assert_equal(A[[1, 3], :].toarray(), B[[1, 3], :])
+        assert_equal(A[[2, -5], 8:-1].toarray(), B[[2, -5], 8:-1])
+        assert_equal(A[array([2, -5]), 8:-1].toarray(), B[[2, -5], 8:-1])
+
+        # [[1,2],[1,2]]
+        assert_equal(toarray(A[[3], [4]]), B[[3], [4]])
+        assert_equal(toarray(A[[1, 3], [2, 4]]), B[[1, 3], [2, 4]])
+        assert_equal(toarray(A[[-1, -3], [2, -4]]), B[[-1, -3], [2, -4]])
+        assert_equal(
+            toarray(A[array([-1, -3]), [2, -4]]), B[[-1, -3], [2, -4]]
+        )
+        assert_equal(
+            toarray(A[[-1, -3], array([2, -4])]), B[[-1, -3], [2, -4]]
+        )
+        assert_equal(
+            toarray(A[array([-1, -3]), array([2, -4])]), B[[-1, -3], [2, -4]]
+        )
+
+        # [[[1],[2]],[1,2]]
+        assert_equal(A[[[1], [3]], [2, 4]].toarray(), B[[[1], [3]], [2, 4]])
+        assert_equal(
+            A[[[-1], [-3], [-2]], [2, -4]].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[array([[-1], [-3], [-2]]), [2, -4]].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[[[-1], [-3], [-2]], array([2, -4])].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[array([[-1], [-3], [-2]]), array([2, -4])].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+
+        # [[1,2]]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+        assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
+        assert_equal(A[array([-1, -3])].toarray(), B[[-1, -3]])
+
+        # [[1,2],:][:,[1,2]]
+        assert_equal(A[[3], :][:, [4]].toarray(), B[[3], :][:, [4]])
+        assert_equal(
+            A[[1, 3], :][:, [2, 4]].toarray(), B[[1, 3], :][:, [2, 4]]
+        )
+        assert_equal(
+            A[[-1, -3], :][:, [2, -4]].toarray(), B[[-1, -3], :][:, [2, -4]]
+        )
+        assert_equal(
+            A[array([-1, -3]), :][:, array([2, -4])].toarray(),
+            B[[-1, -3], :][:, [2, -4]]
+        )
+
+        # [1,[[1,2]]][[[1,2]],1]
+        assert_equal(
+            A[1, [[1, 3]]][[[0, 0]], 1].toarray(), B[1, [[1, 3]]][[[0, 0]], 1]
+        )
+        assert_equal(
+            A[1, [[-1, -3]]][[[0, -1]], 1].toarray(), B[1, [[-1, -3]]][[[0, -1]], 1]
+        )
+        # [:1,[[1,2]]][[[1,2]],:1]
+        with pytest.raises(IndexError, match="Only 1D or 2D arrays allowed"):
+            A[:1, [[1, 3]]]
+        with pytest.raises(IndexError, match="Only 1D or 2D arrays allowed"):
+            A[[[0, 0]], :1]
+
+        # [:,[1,2]][[1,2],:]
+        assert_equal(
+            A[:, [1, 3]][[2, 4], :].toarray(), B[:, [1, 3]][[2, 4], :]
+        )
+        assert_equal(
+            A[:, [-1, -3]][[2, -4], :].toarray(), B[:, [-1, -3]][[2, -4], :]
+        )
+        assert_equal(
+            A[:, array([-1, -3])][array([2, -4]), :].toarray(),
+            B[:, [-1, -3]][[2, -4], :]
+        )
+
+        # Check bug reported by Robert Cimrman:
+        # http://thread.gmane.org/gmane.comp.python.scientific.devel/7986 (dead link)
+        s = slice(int8(2),int8(4),None)
+        assert_equal(A[s, :].toarray(), B[2:4, :])
+        assert_equal(A[:, s].toarray(), B[:, 2:4])
+
+        # Regression for gh-4917: index with tuple of 2D arrays
+        i = np.array([[1]], dtype=int)
+        assert_equal(A[i, i].toarray(), B[i, i])
+
+        # Regression for gh-4917: index with tuple of empty nested lists
+        assert_equal(A[[[]], [[]]].toarray(), B[[[]], [[]]])
+
+    def test_fancy_indexing_randomized(self):
+        np.random.seed(1234)  # make runs repeatable
+
+        NUM_SAMPLES = 50
+        M = 6
+        N = 4
+
+        D = self.asdense(np.random.rand(M,N))
+        D = np.multiply(D, D > 0.5)
+
+        I = np.random.randint(-M + 1, M, size=NUM_SAMPLES)
+        J = np.random.randint(-N + 1, N, size=NUM_SAMPLES)
+
+        S = self.spcreator(D)
+
+        SIJ = S[I,J]
+        if issparse(SIJ):
+            SIJ = SIJ.toarray()
+        assert_equal(SIJ, D[I,J])
+
+        I_bad = I + M
+        J_bad = J - N
+
+        assert_raises(IndexError, S.__getitem__, (I_bad,J))
+        assert_raises(IndexError, S.__getitem__, (I,J_bad))
+
+    def test_missized_masking(self):
+        M, N = 5, 10
+
+        B = self.asdense(arange(M * N).reshape(M, N))
+        A = self.spcreator(B)
+
+        # Content of mask shouldn't matter, only its size
+        row_long = np.ones(M + 1, dtype=bool)
+        row_short = np.ones(M - 1, dtype=bool)
+        col_long = np.ones(N + 2, dtype=bool)
+        col_short = np.ones(N - 2, dtype=bool)
+
+        match="bool index .* has shape .* instead of .*"
+        for i, j in itertools.product(
+            (row_long, row_short, slice(None)),
+            (col_long, col_short, slice(None)),
+        ):
+            if isinstance(i, slice) and isinstance(j, slice):
+                continue
+            with pytest.raises(IndexError, match=match):
+                _ = A[i, j]
+
+    def test_fancy_indexing_boolean(self):
+        np.random.seed(1234)  # make runs repeatable
+
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        I = np.array(np.random.randint(0, 2, size=5), dtype=bool)
+        J = np.array(np.random.randint(0, 2, size=10), dtype=bool)
+        X = np.array(np.random.randint(0, 2, size=(5, 10)), dtype=bool)
+
+        assert_equal(toarray(A[I]), B[I])
+        assert_equal(toarray(A[:, J]), B[:, J])
+        assert_equal(toarray(A[X]), B[X])
+        assert_equal(toarray(A[B > 9]), B[B > 9])
+
+        I = np.array([True, False, True, True, False])
+        J = np.array([False, True, True, False, True,
+                      False, False, False, False, False])
+
+        assert_equal(toarray(A[I, J]), B[I, J])
+
+        Z1 = np.zeros((6, 11), dtype=bool)
+        Z2 = np.zeros((6, 11), dtype=bool)
+        Z2[0,-1] = True
+        Z3 = np.zeros((6, 11), dtype=bool)
+        Z3[-1,0] = True
+
+        assert_raises(IndexError, A.__getitem__, Z1)
+        assert_raises(IndexError, A.__getitem__, Z2)
+        assert_raises(IndexError, A.__getitem__, Z3)
+        assert_raises((IndexError, ValueError), A.__getitem__, (X, 1))
+
+    def test_fancy_indexing_sparse_boolean(self):
+        np.random.seed(1234)  # make runs repeatable
+
+        B = self.asdense(arange(50).reshape(5,10))
+        A = self.spcreator(B)
+
+        X = np.array(np.random.randint(0, 2, size=(5, 10)), dtype=bool)
+
+        Xsp = self.csr_container(X)
+
+        assert_equal(toarray(A[Xsp]), B[X])
+        assert_equal(toarray(A[A > 9]), B[B > 9])
+
+        Z = np.array(np.random.randint(0, 2, size=(5, 11)), dtype=bool)
+        Y = np.array(np.random.randint(0, 2, size=(6, 10)), dtype=bool)
+
+        Zsp = self.csr_container(Z)
+        Ysp = self.csr_container(Y)
+
+        assert_raises(IndexError, A.__getitem__, Zsp)
+        assert_raises(IndexError, A.__getitem__, Ysp)
+        assert_raises((IndexError, ValueError), A.__getitem__, (Xsp, 1))
+
+    def test_fancy_indexing_regression_3087(self):
+        mat = self.spcreator(array([[1, 0, 0], [0,1,0], [1,0,0]]))
+        desired_cols = np.ravel(mat.sum(0)) > 0
+        assert_equal(mat[:, desired_cols].toarray(), [[1, 0], [0, 1], [1, 0]])
+
+    def test_fancy_indexing_seq_assign(self):
+        mat = self.spcreator(array([[1, 0], [0, 1]]))
+        assert_raises(ValueError, mat.__setitem__, (0, 0), np.array([1,2]))
+
+    def test_fancy_indexing_2d_assign(self):
+        # regression test for gh-10695
+        mat = self.spcreator(array([[1, 0], [2, 3]]))
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            mat[[0, 1], [1, 1]] = mat[[1, 0], [0, 0]]
+        assert_equal(toarray(mat), array([[1, 2], [2, 1]]))
+
+    def test_fancy_indexing_empty(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        B[1,:] = 0
+        B[:,2] = 0
+        B[3,6] = 0
+        A = self.spcreator(B)
+
+        K = np.array([False, False, False, False, False])
+        assert_equal(toarray(A[K]), B[K])
+        K = np.array([], dtype=int)
+        assert_equal(toarray(A[K]), B[K])
+        assert_equal(toarray(A[K, K]), B[K, K])
+        J = np.array([0, 1, 2, 3, 4], dtype=int)[:,None]
+        assert_equal(toarray(A[K, J]), B[K, J])
+        assert_equal(toarray(A[J, K]), B[J, K])
+
+
+@contextlib.contextmanager
+def check_remains_sorted(X):
+    """Checks that sorted indices property is retained through an operation
+    """
+    if not hasattr(X, 'has_sorted_indices') or not X.has_sorted_indices:
+        yield
+        return
+    yield
+    indices = X.indices.copy()
+    X.has_sorted_indices = False
+    X.sort_indices()
+    assert_array_equal(indices, X.indices,
+                       'Expected sorted indices, found unsorted')
+
+
+class _TestFancyIndexingAssign:
+    def test_bad_index_assign(self):
+        A = self.spcreator(np.zeros([5, 5]))
+        assert_raises((IndexError, ValueError, TypeError), A.__setitem__, "foo", 2)
+        assert_raises((IndexError, ValueError, TypeError), A.__setitem__, (2, "foo"), 5)
+
+    def test_fancy_indexing_set(self):
+        n, m = (5, 10)
+
+        def _test_set_slice(i, j):
+            A = self.spcreator((n, m))
+            B = self.asdense(np.zeros((n, m)))
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                B[i, j] = 1
+                with check_remains_sorted(A):
+                    A[i, j] = 1
+            assert_array_almost_equal(A.toarray(), B)
+        # [1:2,1:2]
+        for i, j in [((2, 3, 4), slice(None, 10, 4)),
+                     (np.arange(3), slice(5, -2)),
+                     (slice(2, 5), slice(5, -2))]:
+            _test_set_slice(i, j)
+        for i, j in [(np.arange(3), np.arange(3)), ((0, 3, 4), (1, 2, 4))]:
+            _test_set_slice(i, j)
+
+    def test_fancy_assignment_dtypes(self):
+        def check(dtype):
+            A = self.spcreator((5, 5), dtype=dtype)
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[[0,1],[0,1]] = dtype.type(1)
+                assert_equal(A.sum(), dtype.type(1)*2)
+                A[0:2,0:2] = dtype.type(1.0)
+                assert_equal(A.sum(), dtype.type(1)*4)
+                A[2,2] = dtype.type(1.0)
+                assert_equal(A.sum(), dtype.type(1)*4 + dtype.type(1))
+
+        for dtype in supported_dtypes:
+            check(np.dtype(dtype))
+
+    def test_sequence_assignment(self):
+        A = self.spcreator((4,3))
+        B = self.spcreator(eye(3,4))
+
+        i0 = [0,1,2]
+        i1 = (0,1,2)
+        i2 = array(i0)
+
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            with check_remains_sorted(A):
+                A[0,i0] = B[i0,0].T
+                A[1,i1] = B[i1,1].T
+                A[2,i2] = B[i2,2].T
+            assert_array_equal(A.toarray(), B.T.toarray())
+
+            # column slice
+            A = self.spcreator((2,3))
+            with check_remains_sorted(A):
+                A[1,1:3] = [10,20]
+            assert_array_equal(A.toarray(), [[0, 0, 0], [0, 10, 20]])
+
+            # row slice
+            A = self.spcreator((3,2))
+            with check_remains_sorted(A):
+                A[1:3,1] = [[10],[20]]
+            assert_array_equal(A.toarray(), [[0, 0], [0, 10], [0, 20]])
+
+            # both slices
+            A = self.spcreator((3,3))
+            B = self.asdense(np.zeros((3,3)))
+            with check_remains_sorted(A):
+                for C in [A, B]:
+                    C[[0,1,2], [0,1,2]] = [4,5,6]
+            assert_array_equal(A.toarray(), B)
+
+            # both slices (2)
+            A = self.spcreator((4, 3))
+            with check_remains_sorted(A):
+                A[(1, 2, 3), (0, 1, 2)] = [1, 2, 3]
+            assert_almost_equal(A.sum(), 6)
+            B = self.asdense(np.zeros((4, 3)))
+            B[(1, 2, 3), (0, 1, 2)] = [1, 2, 3]
+            assert_array_equal(A.toarray(), B)
+
+    def test_fancy_assign_empty(self):
+        B = self.asdense(arange(50).reshape(5,10))
+        B[1,:] = 0
+        B[:,2] = 0
+        B[3,6] = 0
+        A = self.spcreator(B)
+
+        K = np.array([False, False, False, False, False])
+        A[K] = 42
+        assert_equal(toarray(A), B)
+
+        K = np.array([], dtype=int)
+        A[K] = 42
+        assert_equal(toarray(A), B)
+        A[K,K] = 42
+        assert_equal(toarray(A), B)
+
+        J = np.array([0, 1, 2, 3, 4], dtype=int)[:,None]
+        A[K,J] = 42
+        assert_equal(toarray(A), B)
+        A[J,K] = 42
+        assert_equal(toarray(A), B)
+
+
+class _TestFancyMultidim:
+    def test_fancy_indexing_ndarray(self):
+        sets = [
+            (np.array([[1], [2], [3]]), np.array([3, 4, 2])),
+            (np.array([[1], [2], [3]]), np.array([[3, 4, 2]])),
+            (np.array([[1, 2, 3]]), np.array([[3], [4], [2]])),
+            (np.array([1, 2, 3]), np.array([[3], [4], [2]])),
+            (np.array([[1, 2, 3], [3, 4, 2]]),
+             np.array([[5, 6, 3], [2, 3, 1]]))
+            ]
+        # These inputs generate 3-D outputs
+        #    (np.array([[[1], [2], [3]], [[3], [4], [2]]]),
+        #     np.array([[[5], [6], [3]], [[2], [3], [1]]])),
+
+        for I, J in sets:
+            np.random.seed(1234)
+            D = self.asdense(np.random.rand(5, 7))
+            S = self.spcreator(D)
+
+            SIJ = S[I,J]
+            if issparse(SIJ):
+                SIJ = SIJ.toarray()
+            assert_equal(SIJ, D[I,J])
+
+            I_bad = I + 5
+            J_bad = J + 7
+
+            assert_raises(IndexError, S.__getitem__, (I_bad,J))
+            assert_raises(IndexError, S.__getitem__, (I,J_bad))
+
+            # This would generate 3-D arrays -- not supported
+            assert_raises(IndexError, S.__getitem__, ([I, I], slice(None)))
+            assert_raises(IndexError, S.__getitem__, (slice(None), [J, J]))
+
+
+class _TestFancyMultidimAssign:
+    def test_fancy_assign_ndarray(self):
+        np.random.seed(1234)
+
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+        X = np.random.rand(2, 3)
+
+        I = np.array([[1, 2, 3], [3, 4, 2]])
+        J = np.array([[5, 6, 3], [2, 3, 1]])
+
+        with check_remains_sorted(S):
+            S[I,J] = X
+        D[I,J] = X
+        assert_equal(S.toarray(), D)
+
+        I_bad = I + 5
+        J_bad = J + 7
+
+        C = [1, 2, 3]
+
+        with check_remains_sorted(S):
+            S[I,J] = C
+        D[I,J] = C
+        assert_equal(S.toarray(), D)
+
+        with check_remains_sorted(S):
+            S[I,J] = 3
+        D[I,J] = 3
+        assert_equal(S.toarray(), D)
+
+        assert_raises(IndexError, S.__setitem__, (I_bad,J), C)
+        assert_raises(IndexError, S.__setitem__, (I,J_bad), C)
+
+    def test_fancy_indexing_multidim_set(self):
+        n, m = (5, 10)
+
+        def _test_set_slice(i, j):
+            A = self.spcreator((n, m))
+            with check_remains_sorted(A), suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                A[i, j] = 1
+            B = self.asdense(np.zeros((n, m)))
+            B[i, j] = 1
+            assert_array_almost_equal(A.toarray(), B)
+        # [[[1, 2], [1, 2]], [1, 2]]
+        for i, j in [(np.array([[1, 2], [1, 3]]), [1, 3]),
+                        (np.array([0, 4]), [[0, 3], [1, 2]]),
+                        ([[1, 2, 3], [0, 2, 4]], [[0, 4, 3], [4, 1, 2]])]:
+            _test_set_slice(i, j)
+
+    def test_fancy_assign_list(self):
+        np.random.seed(1234)
+
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+        X = np.random.rand(2, 3)
+
+        I = [[1, 2, 3], [3, 4, 2]]
+        J = [[5, 6, 3], [2, 3, 1]]
+
+        S[I,J] = X
+        D[I,J] = X
+        assert_equal(S.toarray(), D)
+
+        I_bad = [[ii + 5 for ii in i] for i in I]
+        J_bad = [[jj + 7 for jj in j] for j in J]
+        C = [1, 2, 3]
+
+        S[I,J] = C
+        D[I,J] = C
+        assert_equal(S.toarray(), D)
+
+        S[I,J] = 3
+        D[I,J] = 3
+        assert_equal(S.toarray(), D)
+
+        assert_raises(IndexError, S.__setitem__, (I_bad,J), C)
+        assert_raises(IndexError, S.__setitem__, (I,J_bad), C)
+
+    def test_fancy_assign_slice(self):
+        np.random.seed(1234)
+
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+
+        I = [1, 2, 3, 3, 4, 2]
+        J = [5, 6, 3, 2, 3, 1]
+
+        I_bad = [ii + 5 for ii in I]
+        J_bad = [jj + 7 for jj in J]
+
+        C1 = [1, 2, 3, 4, 5, 6, 7]
+        C2 = np.arange(5)[:, None]
+        assert_raises(IndexError, S.__setitem__, (I_bad, slice(None)), C1)
+        assert_raises(IndexError, S.__setitem__, (slice(None), J_bad), C2)
+
+
+class _TestArithmetic:
+    """
+    Test real/complex arithmetic
+    """
+    def __arith_init(self):
+        # these can be represented exactly in FP (so arithmetic should be exact)
+        __A = array([[-1.5, 6.5, 0, 2.25, 0, 0],
+                          [3.125, -7.875, 0.625, 0, 0, 0],
+                          [0, 0, -0.125, 1.0, 0, 0],
+                          [0, 0, 8.375, 0, 0, 0]], 'float64')
+        __B = array([[0.375, 0, 0, 0, -5, 2.5],
+                          [14.25, -3.75, 0, 0, -0.125, 0],
+                          [0, 7.25, 0, 0, 0, 0],
+                          [18.5, -0.0625, 0, 0, 0, 0]], 'complex128')
+        __B.imag = array([[1.25, 0, 0, 0, 6, -3.875],
+                               [2.25, 4.125, 0, 0, 0, 2.75],
+                               [0, 4.125, 0, 0, 0, 0],
+                               [-0.0625, 0, 0, 0, 0, 0]], 'float64')
+
+        # fractions are all x/16ths
+        assert_array_equal((__A*16).astype('int32'),16*__A)
+        assert_array_equal((__B.real*16).astype('int32'),16*__B.real)
+        assert_array_equal((__B.imag*16).astype('int32'),16*__B.imag)
+
+        __Asp = self.spcreator(__A)
+        __Bsp = self.spcreator(__B)
+        return __A, __B, __Asp, __Bsp
+
+    @pytest.mark.fail_slow(20)
+    def test_add_sub(self):
+        __A, __B, __Asp, __Bsp = self.__arith_init()
+
+        # basic tests
+        assert_array_equal(
+            (__Asp + __Bsp).toarray(), __A + __B
+        )
+
+        # check conversions
+        for x in supported_dtypes:
+            with np.errstate(invalid="ignore"):
+                A = __A.astype(x)
+            Asp = self.spcreator(A)
+            for y in supported_dtypes:
+                if not np.issubdtype(y, np.complexfloating):
+                    with np.errstate(invalid="ignore"):
+                        B = __B.real.astype(y)
+                else:
+                    B = __B.astype(y)
+                Bsp = self.spcreator(B)
+
+                # addition
+                D1 = A + B
+                S1 = Asp + Bsp
+
+                assert_equal(S1.dtype,D1.dtype)
+                assert_array_equal(S1.toarray(), D1)
+                assert_array_equal(Asp + B,D1)          # check sparse + dense
+                assert_array_equal(A + Bsp,D1)          # check dense + sparse
+
+                # subtraction
+                if np.dtype('bool') in [x, y]:
+                    # boolean array subtraction deprecated in 1.9.0
+                    continue
+
+                D1 = A - B
+                S1 = Asp - Bsp
+
+                assert_equal(S1.dtype,D1.dtype)
+                assert_array_equal(S1.toarray(), D1)
+                assert_array_equal(Asp - B,D1)          # check sparse - dense
+                assert_array_equal(A - Bsp,D1)          # check dense - sparse
+
+    def test_mu(self):
+        __A, __B, __Asp, __Bsp = self.__arith_init()
+
+        # basic tests
+        assert_array_equal((__Asp @ __Bsp.T).toarray(),
+                            __A @ __B.T)
+
+        for x in supported_dtypes:
+            with np.errstate(invalid="ignore"):
+                A = __A.astype(x)
+            Asp = self.spcreator(A)
+            for y in supported_dtypes:
+                if np.issubdtype(y, np.complexfloating):
+                    B = __B.astype(y)
+                else:
+                    with np.errstate(invalid="ignore"):
+                        B = __B.real.astype(y)
+                Bsp = self.spcreator(B)
+
+                D1 = A @ B.T
+                S1 = Asp @ Bsp.T
+
+                assert_allclose(S1.toarray(), D1,
+                                atol=1e-14*abs(D1).max())
+                assert_equal(S1.dtype,D1.dtype)
+
+
+class _TestMinMax:
+    def test_minmax(self):
+        for dtype in [np.float32, np.float64, np.int32, np.int64, np.complex128]:
+            D = np.arange(20, dtype=dtype).reshape(5,4)
+
+            X = self.spcreator(D)
+            assert_equal(X.min(), 0)
+            assert_equal(X.max(), 19)
+            assert_equal(X.min().dtype, dtype)
+            assert_equal(X.max().dtype, dtype)
+
+            D *= -1
+            X = self.spcreator(D)
+            assert_equal(X.min(), -19)
+            assert_equal(X.max(), 0)
+
+            D += 5
+            X = self.spcreator(D)
+            assert_equal(X.min(), -14)
+            assert_equal(X.max(), 5)
+
+        # try a fully dense matrix
+        X = self.spcreator(np.arange(1, 10).reshape(3, 3))
+        assert_equal(X.min(), 1)
+        assert_equal(X.min().dtype, X.dtype)
+
+        X = -X
+        assert_equal(X.max(), -1)
+
+        # and a fully sparse matrix
+        Z = self.spcreator(np.zeros((1, 1)))
+        assert_equal(Z.min(), 0)
+        assert_equal(Z.max(), 0)
+        assert_equal(Z.max().dtype, Z.dtype)
+
+        # another test
+        D = np.arange(20, dtype=float).reshape(5,4)
+        D[0:2, :] = 0
+        X = self.spcreator(D)
+        assert_equal(X.min(), 0)
+        assert_equal(X.max(), 19)
+
+        # zero-size matrices
+        for D in [np.zeros((0, 0)), np.zeros((0, 10)), np.zeros((10, 0))]:
+            X = self.spcreator(D)
+            assert_raises(ValueError, X.min)
+            assert_raises(ValueError, X.max)
+
+    def test_minmax_axis(self):
+        keep = not self.is_array_test
+        D = np.arange(50).reshape(5, 10)
+        # completely empty rows, leaving some completely full:
+        D[1, :] = 0
+        # empty at end for reduceat:
+        D[:, 9] = 0
+        # partial rows/cols:
+        D[3, 3] = 0
+        # entries on either side of 0:
+        D[2, 2] = -1
+        X = self.spcreator(D)
+
+        axes_even = [0, -2]
+        axes_odd = [1, -1]
+        for axis in axes_odd + axes_even:
+            assert_array_equal(
+                X.max(axis=axis).toarray(), D.max(axis=axis, keepdims=keep)
+            )
+            assert_array_equal(
+                X.min(axis=axis).toarray(), D.min(axis=axis, keepdims=keep)
+            )
+
+        for axis in axes_even:
+            assert_equal(
+                X.max(axis=axis, explicit=True).toarray(),
+                self.asdense([40, 41, 42, 43, 44, 45, 46, 47, 48, 0])
+            )
+            if np.any(X.data == 0):
+                # Noncanonical case
+                expected = self.asdense([20, 1, -1, 3, 4, 5, 0, 7, 8, 0])
+            else:
+                expected = self.asdense([20, 1, -1, 3, 4, 5, 6, 7, 8, 0])
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), expected)
+
+        for axis in axes_odd:
+            expected_max = np.array([8, 0, 28, 38, 48])
+            expected_min = np.array([1, 0, -1, 30, 40])
+            if not self.is_array_test:
+                expected_max = expected_max.reshape((5, 1))
+                expected_min = expected_min.reshape((5, 1))
+            assert_equal(X.max(axis=axis, explicit=True).toarray(), expected_max)
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), expected_min)
+
+        # full matrix
+        D = np.arange(1, 51).reshape(10, 5)
+        X = self.spcreator(D)
+        for axis in axes_odd + axes_even:
+            assert_array_equal(
+                X.max(axis=axis).toarray(), D.max(axis=axis, keepdims=keep)
+            )
+            assert_array_equal(
+                X.min(axis=axis).toarray(), D.min(axis=axis, keepdims=keep)
+            )
+
+        for axis in axes_even:
+            expected_max = D[-1, :]
+            expected_min = D[0, :]
+            if not self.is_array_test:
+                expected_max = D[None, -1, :]
+                expected_min = D[None, 0, :]
+            assert_equal(X.max(axis=axis, explicit=True).toarray(), expected_max)
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), expected_min)
+        for axis in axes_odd:
+            expected_max = D[:, -1]
+            expected_min = D[:, 0]
+            if not self.is_array_test:
+                expected_max = D[:, -1, None]
+                expected_min = D[:, 0, None]
+            assert_equal(X.max(axis=axis, explicit=True).toarray(), expected_max)
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), expected_min)
+
+        # empty matrix
+        D = self.asdense(np.zeros((10, 5)))
+        X = self.spcreator(D)
+        for axis in axes_even + axes_odd:
+            assert_equal(X.max(axis=axis, explicit=True).toarray(), D.max(axis=axis))
+            assert_equal(X.min(axis=axis, explicit=True).toarray(), D.min(axis=axis))
+
+        # zero-size matrices
+        D = self.asdense(np.zeros((0, 10)))
+        X = self.spcreator(D)
+        explicit_values = [True, False]
+        even_explicit_pairs = list(itertools.product(axes_even, explicit_values))
+        odd_explicit_pairs = list(itertools.product(axes_odd, explicit_values))
+        for axis, ex in even_explicit_pairs:
+            assert_raises(ValueError, X.min, axis=axis, explicit=ex)
+            assert_raises(ValueError, X.max, axis=axis, explicit=ex)
+        for axis, ex in odd_explicit_pairs:
+            assert_equal(X.max(axis=axis, explicit=ex).toarray(), D.max(axis=axis))
+            assert_equal(X.min(axis=axis, explicit=ex).toarray(), D.min(axis=axis))
+
+        D = self.asdense(np.zeros((10, 0)))
+        X = self.spcreator(D)
+        for axis, ex in odd_explicit_pairs:
+            assert_raises(ValueError, X.min, axis=axis, explicit=ex)
+            assert_raises(ValueError, X.max, axis=axis, explicit=ex)
+        for axis, ex in even_explicit_pairs:
+            assert_equal(X.max(axis=axis, explicit=ex).toarray(), D.max(axis=axis))
+            assert_equal(X.min(axis=axis, explicit=ex).toarray(), D.min(axis=axis))
+
+    def test_nanminmax(self):
+        D = self.asdense(np.arange(50).reshape(5,10), dtype=float)
+        D[1, :] = 0
+        D[:, 9] = 0
+        D[3, 3] = 0
+        D[2, 2] = -1
+        D[4, 2] = np.nan
+        D[1, 4] = np.nan
+        X = self.spcreator(D)
+
+        X_nan_maximum = X.nanmax()
+        assert np.isscalar(X_nan_maximum)
+        assert X_nan_maximum == np.nanmax(D)
+
+        X_nan_minimum = X.nanmin()
+        assert np.isscalar(X_nan_minimum)
+        assert X_nan_minimum == np.nanmin(D)
+
+        axes = [-2, -1, 0, 1]
+        for axis in axes:
+            X_nan_maxima = X.nanmax(axis=axis)
+            assert_allclose(X_nan_maxima.toarray(), np.nanmax(D, axis=axis))
+            assert isinstance(X_nan_maxima, self.coo_container)
+
+            X_nan_minima = X.nanmin(axis=axis)
+            assert_allclose(X_nan_minima.toarray(), np.nanmin(D, axis=axis))
+            assert isinstance(X_nan_minima, self.coo_container)
+
+    def test_minmax_invalid_params(self):
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        for fname in ('min', 'max'):
+            func = getattr(datsp, fname)
+            assert_raises(ValueError, func, axis=3)
+            assert_raises(TypeError, func, axis=(0, 1))
+            assert_raises(TypeError, func, axis=1.5)
+            assert_raises(ValueError, func, axis=1, out=1)
+
+    def test_numpy_minmax(self):
+        # See gh-5987
+        # xref gh-7460 in 'numpy'
+        from scipy.sparse import _data
+
+        dat = array([[0, 1, 2],
+                     [3, -4, 5],
+                     [-6, 7, 9]])
+        datsp = self.spcreator(dat)
+
+        # We are only testing sparse matrices who have
+        # implemented 'min' and 'max' because they are
+        # the ones with the compatibility issues with
+        # the 'numpy' implementation.
+        if isinstance(datsp, _data._minmax_mixin):
+            assert_array_equal(np.min(datsp), np.min(dat))
+            assert_array_equal(np.max(datsp), np.max(dat))
+
+    def test_argmax(self):
+        from scipy.sparse import _data
+        D1 = np.array([
+            [-1, 5, 2, 3],
+            [0, 0, -1, -2],
+            [-1, -2, -3, -4],
+            [1, 2, 3, 4],
+            [1, 2, 0, 0],
+        ])
+        D2 = D1.transpose()
+        # Non-regression test cases for gh-16929.
+        D3 = np.array([[4, 3], [7, 5]])
+        D4 = np.array([[4, 3], [7, 0]])
+        D5 = np.array([[5, 5, 3], [4, 9, 10], [3, 4, 9]])
+
+        for D in [D1, D2, D3, D4, D5]:
+            D = self.asdense(D)
+            mat = self.spcreator(D)
+            if not isinstance(mat, _data._minmax_mixin):
+                continue
+
+            assert_equal(mat.argmax(), np.argmax(D))
+            assert_equal(mat.argmin(), np.argmin(D))
+
+            assert_equal(mat.argmax(axis=0), np.argmax(D, axis=0))
+            assert_equal(mat.argmin(axis=0), np.argmin(D, axis=0))
+
+            assert_equal(mat.argmax(axis=1), np.argmax(D, axis=1))
+            assert_equal(mat.argmin(axis=1), np.argmin(D, axis=1))
+
+        # zero-size matrices
+        D6 = self.spcreator(np.empty((0, 5)))
+        D7 = self.spcreator(np.empty((5, 0)))
+        explicits = [True, False]
+
+        for mat, axis, ex in itertools.product([D6, D7], [None, 0, 1], explicits):
+            if axis is None or mat.shape[axis] == 0:
+                with pytest.raises(ValueError, match="Cannot apply"):
+                    mat.argmax(axis=axis, explicit=ex)
+                with pytest.raises(ValueError, match="Cannot apply"):
+                    mat.argmin(axis=axis, explicit=ex)
+            else:
+                if self.is_array_test:
+                    expected = np.zeros(0)
+                else:
+                    expected = np.zeros((0, 1) if axis == 1 else (1, 0))
+                assert_equal(mat.argmin(axis=axis, explicit=ex), expected)
+                assert_equal(mat.argmax(axis=axis, explicit=ex), expected)
+
+        mat = self.spcreator(D1)
+        assert_equal(mat.argmax(axis=0, explicit=True), self.asdense([3, 0, 3, 3]))
+        assert_equal(mat.argmin(axis=0, explicit=True), self.asdense([0, 2, 2, 2]))
+
+        expected_max = np.array([1, 2, 0, 3, 1])
+        expected_min = np.array([0, 3, 3, 0, 0])
+        if mat.nnz != 16:
+            # Noncanonical case
+            expected_min[-1] = 2
+        if not self.is_array_test:
+            expected_max = expected_max.reshape((5, 1))
+            expected_min = expected_min.reshape((5, 1))
+
+        assert_equal(mat.argmax(axis=1, explicit=True), expected_max)
+        assert_equal(asarray(mat.argmin(axis=1, explicit=True)), expected_min)
+
+        # all zeros
+        D = np.zeros((2, 2))
+        mat = self.spcreator(D)
+        if mat.nnz != 0:
+            # Noncanonical case
+            assert_equal(mat.argmin(axis=None, explicit=True), 0)
+            assert_equal(mat.argmax(axis=None, explicit=True), 0)
+        else:
+            # Canonical case
+            with pytest.raises(ValueError, match="Cannot apply"):
+                mat.argmin(axis=None, explicit=True)
+            with pytest.raises(ValueError, match="Cannot apply"):
+                mat.argmax(axis=None, explicit=True)
+
+
+class _TestGetNnzAxis:
+    def test_getnnz_axis(self):
+        dat = array([[0, 2],
+                     [3, 5],
+                     [-6, 9]])
+        bool_dat = dat.astype(bool)
+        datsp = self.spcreator(dat)
+
+        accepted_return_dtypes = (np.int32, np.int64)
+
+        getnnz = datsp.count_nonzero if self.is_array_test else datsp.getnnz
+        assert_array_equal(bool_dat.sum(axis=None), getnnz(axis=None))
+        assert_array_equal(bool_dat.sum(), getnnz())
+        assert_array_equal(bool_dat.sum(axis=0), getnnz(axis=0))
+        assert_in(getnnz(axis=0).dtype, accepted_return_dtypes)
+        assert_array_equal(bool_dat.sum(axis=1), getnnz(axis=1))
+        assert_in(getnnz(axis=1).dtype, accepted_return_dtypes)
+        assert_array_equal(bool_dat.sum(axis=-2), getnnz(axis=-2))
+        assert_in(getnnz(axis=-2).dtype, accepted_return_dtypes)
+        assert_array_equal(bool_dat.sum(axis=-1), getnnz(axis=-1))
+        assert_in(getnnz(axis=-1).dtype, accepted_return_dtypes)
+
+        assert_raises(ValueError, getnnz, axis=2)
+
+
+#------------------------------------------------------------------------------
+# Tailored base class for generic tests
+#------------------------------------------------------------------------------
+
+def _possibly_unimplemented(cls, require=True):
+    """
+    Construct a class that either runs tests as usual (require=True),
+    or each method skips if it encounters a common error.
+    """
+    if require:
+        return cls
+    else:
+        def wrap(fc):
+            @functools.wraps(fc)
+            def wrapper(*a, **kw):
+                try:
+                    return fc(*a, **kw)
+                except (NotImplementedError, TypeError, ValueError,
+                        IndexError, AttributeError):
+                    raise pytest.skip("feature not implemented")
+
+            return wrapper
+
+        new_dict = dict(cls.__dict__)
+        for name, func in cls.__dict__.items():
+            if name.startswith('test_'):
+                new_dict[name] = wrap(func)
+        return type(cls.__name__ + "NotImplemented",
+                    cls.__bases__,
+                    new_dict)
+
+
+def sparse_test_class(getset=True, slicing=True, slicing_assign=True,
+                      fancy_indexing=True, fancy_assign=True,
+                      fancy_multidim_indexing=True, fancy_multidim_assign=True,
+                      minmax=True, nnz_axis=True):
+    """
+    Construct a base class, optionally converting some of the tests in
+    the suite to check that the feature is not implemented.
+    """
+    bases = (_TestCommon,
+             _possibly_unimplemented(_TestGetSet, getset),
+             _TestSolve,
+             _TestInplaceArithmetic,
+             _TestArithmetic,
+             _possibly_unimplemented(_TestSlicing, slicing),
+             _possibly_unimplemented(_TestSlicingAssign, slicing_assign),
+             _possibly_unimplemented(_TestFancyIndexing, fancy_indexing),
+             _possibly_unimplemented(_TestFancyIndexingAssign,
+                                     fancy_assign),
+             _possibly_unimplemented(_TestFancyMultidim,
+                                     fancy_indexing and fancy_multidim_indexing),
+             _possibly_unimplemented(_TestFancyMultidimAssign,
+                                     fancy_multidim_assign and fancy_assign),
+             _possibly_unimplemented(_TestMinMax, minmax),
+             _possibly_unimplemented(_TestGetNnzAxis, nnz_axis))
+
+    # check that test names do not clash
+    names = {}
+    for cls in bases:
+        for name in cls.__dict__:
+            if not name.startswith('test_'):
+                continue
+            old_cls = names.get(name)
+            if old_cls is not None:
+                raise ValueError(f"Test class {cls.__name__} overloads test "
+                                 f"{name} defined in {old_cls.__name__}")
+            names[name] = cls
+
+    return type("TestBase", bases, {})
+
+
+#------------------------------------------------------------------------------
+# Matrix class based tests
+#------------------------------------------------------------------------------
+
+class TestCSR(sparse_test_class()):
+    @classmethod
+    def spcreator(cls, *args, **kwargs):
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            return csr_array(*args, **kwargs)
+    math_dtypes = [np.bool_, np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        b = array([[0, 4, 0],
+                   [3, 0, 0],
+                   [0, 2, 0]], 'd')
+        bsp = self.csr_container(b)
+        assert_array_almost_equal(bsp.data,[4,3,2])
+        assert_array_equal(bsp.indices,[1,0,1])
+        assert_array_equal(bsp.indptr,[0,1,2,3])
+        assert_equal(bsp.nnz,3)
+        assert_equal(bsp.format,'csr')
+        assert_array_equal(bsp.toarray(), b)
+
+    def test_constructor2(self):
+        b = zeros((6,6),'d')
+        b[3,4] = 5
+        bsp = self.csr_container(b)
+        assert_array_almost_equal(bsp.data,[5])
+        assert_array_equal(bsp.indices,[4])
+        assert_array_equal(bsp.indptr,[0,0,0,0,1,1,1])
+        assert_array_almost_equal(bsp.toarray(), b)
+
+    def test_constructor3(self):
+        b = array([[1, 0],
+                   [0, 2],
+                   [3, 0]], 'd')
+        bsp = self.csr_container(b)
+        assert_array_almost_equal(bsp.data,[1,2,3])
+        assert_array_equal(bsp.indices,[0,1,0])
+        assert_array_equal(bsp.indptr,[0,1,2,3])
+        assert_array_almost_equal(bsp.toarray(), b)
+
+    def test_constructor4(self):
+        # using (data, ij) format
+        row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
+        col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
+        data = array([6., 10., 3., 9., 1., 4.,
+                              11., 2., 8., 5., 7.])
+
+        ij = vstack((row,col))
+        csr = self.csr_container((data,ij),(4,3))
+        assert_array_equal(arange(12).reshape(4, 3), csr.toarray())
+
+        # using Python lists and a specified dtype
+        csr = self.csr_container(([2**63 + 1, 1], ([0, 1], [0, 1])), dtype=np.uint64)
+        dense = array([[2**63 + 1, 0], [0, 1]], dtype=np.uint64)
+        assert_array_equal(dense, csr.toarray())
+
+        # with duplicates (should sum the duplicates)
+        csr = self.csr_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0])))
+        assert csr.nnz == 2
+
+    def test_constructor5(self):
+        # infer dimensions from arrays
+        indptr = array([0,1,3,3])
+        indices = array([0,5,1,2])
+        data = array([1,2,3,4])
+        csr = self.csr_container((data, indices, indptr))
+        assert_array_equal(csr.shape,(3,6))
+
+    def test_constructor6(self):
+        # infer dimensions and dtype from lists
+        indptr = [0, 1, 3, 3]
+        indices = [0, 5, 1, 2]
+        data = [1, 2, 3, 4]
+        csr = self.csr_container((data, indices, indptr))
+        assert_array_equal(csr.shape, (3,6))
+        assert_(np.issubdtype(csr.dtype, np.signedinteger))
+
+    def test_constructor_smallcol(self):
+        # int64 indices not required
+        data = arange(6) + 1
+        col = array([1, 2, 1, 0, 0, 2], dtype=np.int64)
+        ptr = array([0, 2, 4, 6], dtype=np.int64)
+
+        a = self.csr_container((data, col, ptr), shape=(3, 3))
+
+        b = array([[0, 1, 2],
+                   [4, 3, 0],
+                   [5, 0, 6]], 'd')
+
+        # sparray is less aggressive in downcasting indices to int32 than spmatrix
+        expected_dtype = np.dtype(np.int64 if self.is_array_test else np.int32)
+        assert_equal(a.indptr.dtype, expected_dtype)
+        assert_equal(a.indices.dtype, expected_dtype)
+        assert_array_equal(a.toarray(), b)
+
+    def test_constructor_largecol(self):
+        # int64 indices required
+        data = arange(6) + 1
+        large = np.iinfo(np.int32).max + 100
+        col = array([0, 1, 2, large, large+1, large+2], dtype=np.int64)
+        ptr = array([0, 2, 4, 6], dtype=np.int64)
+
+        a = self.csr_container((data, col, ptr))
+
+        assert_equal(a.indptr.dtype, np.dtype(np.int64))
+        assert_equal(a.indices.dtype, np.dtype(np.int64))
+        assert_array_equal(a.shape, (3, max(col)+1))
+
+    def test_sort_indices(self):
+        data = arange(5)
+        indices = array([7, 2, 1, 5, 4])
+        indptr = array([0, 3, 5])
+        asp = self.csr_container((data, indices, indptr), shape=(2,10))
+        bsp = asp.copy()
+        asp.sort_indices()
+        assert_array_equal(asp.indices,[1, 2, 7, 4, 5])
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_eliminate_zeros(self):
+        data = array([1, 0, 0, 0, 2, 0, 3, 0])
+        indices = array([1, 2, 3, 4, 5, 6, 7, 8])
+        indptr = array([0, 3, 8])
+        asp = self.csr_container((data, indices, indptr), shape=(2,10))
+        bsp = asp.copy()
+        asp.eliminate_zeros()
+        assert_array_equal(asp.nnz, 3)
+        assert_array_equal(asp.data,[1, 2, 3])
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_ufuncs(self):
+        X = self.csr_container(np.arange(20).reshape(4, 5) / 20.)
+        for f in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh",
+                  "arcsinh", "arctanh", "rint", "sign", "expm1", "log1p",
+                  "deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt"]:
+            assert_equal(hasattr(self.datsp, f), True)
+            X2 = getattr(X, f)()
+            assert_equal(X.shape, X2.shape)
+            assert_array_equal(X.indices, X2.indices)
+            assert_array_equal(X.indptr, X2.indptr)
+            assert_array_equal(X2.toarray(), getattr(np, f)(X.toarray()))
+
+    def test_unsorted_arithmetic(self):
+        data = arange(5)
+        indices = array([7, 2, 1, 5, 4])
+        indptr = array([0, 3, 5])
+        asp = self.csr_container((data, indices, indptr), shape=(2,10))
+        data = arange(6)
+        indices = array([8, 1, 5, 7, 2, 4])
+        indptr = array([0, 2, 6])
+        bsp = self.csr_container((data, indices, indptr), shape=(2,10))
+        assert_equal((asp + bsp).toarray(), asp.toarray() + bsp.toarray())
+
+    def test_fancy_indexing_broadcast(self):
+        # broadcasting indexing mode is supported
+        I = np.array([[1], [2], [3]])
+        J = np.array([3, 4, 2])
+
+        np.random.seed(1234)
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+
+        SIJ = S[I,J]
+        if issparse(SIJ):
+            SIJ = SIJ.toarray()
+        assert_equal(SIJ, D[I,J])
+
+    def test_has_sorted_indices(self):
+        "Ensure has_sorted_indices memoizes sorted state for sort_indices"
+        sorted_inds = np.array([0, 1])
+        unsorted_inds = np.array([1, 0])
+        data = np.array([1, 1])
+        indptr = np.array([0, 2])
+        M = self.csr_container((data, sorted_inds, indptr)).copy()
+        assert_equal(True, M.has_sorted_indices)
+        assert isinstance(M.has_sorted_indices, bool)
+
+        M = self.csr_container((data, unsorted_inds, indptr)).copy()
+        assert_equal(False, M.has_sorted_indices)
+
+        # set by sorting
+        M.sort_indices()
+        assert_equal(True, M.has_sorted_indices)
+        assert_array_equal(M.indices, sorted_inds)
+
+        M = self.csr_container((data, unsorted_inds, indptr)).copy()
+        # set manually (although underlyingly unsorted)
+        M.has_sorted_indices = True
+        assert_equal(True, M.has_sorted_indices)
+        assert_array_equal(M.indices, unsorted_inds)
+
+        # ensure sort bypassed when has_sorted_indices == True
+        M.sort_indices()
+        assert_array_equal(M.indices, unsorted_inds)
+
+    def test_has_canonical_format(self):
+        "Ensure has_canonical_format memoizes state for sum_duplicates"
+
+        M = self.csr_container((np.array([2]), np.array([0]), np.array([0, 1])))
+        assert_equal(True, M.has_canonical_format)
+
+        indices = np.array([0, 0])  # contains duplicate
+        data = np.array([1, 1])
+        indptr = np.array([0, 2])
+
+        M = self.csr_container((data, indices, indptr)).copy()
+        assert_equal(False, M.has_canonical_format)
+        assert isinstance(M.has_canonical_format, bool)
+
+        # set by deduplicating
+        M.sum_duplicates()
+        assert_equal(True, M.has_canonical_format)
+        assert_equal(1, len(M.indices))
+
+        M = self.csr_container((data, indices, indptr)).copy()
+        # set manually (although underlyingly duplicated)
+        M.has_canonical_format = True
+        assert_equal(True, M.has_canonical_format)
+        assert_equal(2, len(M.indices))  # unaffected content
+
+        # ensure deduplication bypassed when has_canonical_format == True
+        M.sum_duplicates()
+        assert_equal(2, len(M.indices))  # unaffected content
+
+    def test_scalar_idx_dtype(self):
+        # Check that index dtype takes into account all parameters
+        # passed to sparsetools, including the scalar ones
+        indptr = np.zeros(2, dtype=np.int32)
+        indices = np.zeros(0, dtype=np.int32)
+        vals = np.zeros(0)
+        a = self.csr_container((vals, indices, indptr), shape=(1, 2**31-1))
+        b = self.csr_container((vals, indices, indptr), shape=(1, 2**31))
+        ij = np.zeros((2, 0), dtype=np.int32)
+        c = self.csr_container((vals, ij), shape=(1, 2**31-1))
+        d = self.csr_container((vals, ij), shape=(1, 2**31))
+        e = self.csr_container((1, 2**31-1))
+        f = self.csr_container((1, 2**31))
+        assert_equal(a.indptr.dtype, np.int32)
+        assert_equal(b.indptr.dtype, np.int64)
+        assert_equal(c.indptr.dtype, np.int32)
+        assert_equal(d.indptr.dtype, np.int64)
+        assert_equal(e.indptr.dtype, np.int32)
+        assert_equal(f.indptr.dtype, np.int64)
+
+        # These shouldn't fail
+        for x in [a, b, c, d, e, f]:
+            x + x
+
+    def test_setdiag_csr(self):
+        # see gh-21791 setting mixture of existing and not when new_values < 0.001*nnz
+        D = self.dia_container(([np.arange(1002)], [0]), shape=(1002, 1002))
+        A = self.spcreator(D)
+        A.setdiag(5 * np.ones(A.shape[0]))
+        assert A[-1, -1] == 5
+
+    def test_binop_explicit_zeros(self):
+        # Check that binary ops don't introduce spurious explicit zeros.
+        # See gh-9619 for context.
+        a = self.csr_container([[0, 1, 0]])
+        b = self.csr_container([[1, 1, 0]])
+        assert (a + b).nnz == 2
+        assert a.multiply(b).nnz == 1
+
+
+TestCSR.init_class()
+
+
+class TestCSRMatrix(_MatrixMixin, TestCSR):
+    @classmethod
+    def spcreator(cls, *args, **kwargs):
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            return csr_matrix(*args, **kwargs)
+
+
+TestCSRMatrix.init_class()
+
+
+class TestCSC(sparse_test_class()):
+    @classmethod
+    def spcreator(cls, *args, **kwargs):
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            return csc_array(*args, **kwargs)
+    math_dtypes = [np.bool_, np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        b = array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 2, 0, 3]], 'd')
+        bsp = self.csc_container(b)
+        assert_array_almost_equal(bsp.data,[1,2,1,3])
+        assert_array_equal(bsp.indices,[0,2,1,2])
+        assert_array_equal(bsp.indptr,[0,1,2,3,4])
+        assert_equal(bsp.nnz,4)
+        assert_equal(bsp.shape,b.shape)
+        assert_equal(bsp.format,'csc')
+
+    def test_constructor2(self):
+        b = zeros((6,6),'d')
+        b[2,4] = 5
+        bsp = self.csc_container(b)
+        assert_array_almost_equal(bsp.data,[5])
+        assert_array_equal(bsp.indices,[2])
+        assert_array_equal(bsp.indptr,[0,0,0,0,0,1,1])
+
+    def test_constructor3(self):
+        b = array([[1, 0], [0, 0], [0, 2]], 'd')
+        bsp = self.csc_container(b)
+        assert_array_almost_equal(bsp.data,[1,2])
+        assert_array_equal(bsp.indices,[0,2])
+        assert_array_equal(bsp.indptr,[0,1,2])
+
+    def test_constructor4(self):
+        # using (data, ij) format
+        row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
+        col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
+        data = array([6., 10., 3., 9., 1., 4., 11., 2., 8., 5., 7.])
+
+        ij = vstack((row,col))
+        csc = self.csc_container((data,ij),(4,3))
+        assert_array_equal(arange(12).reshape(4, 3), csc.toarray())
+
+        # with duplicates (should sum the duplicates)
+        csc = self.csc_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0])))
+        assert csc.nnz == 2
+
+    def test_constructor5(self):
+        # infer dimensions from arrays
+        indptr = array([0,1,3,3])
+        indices = array([0,5,1,2])
+        data = array([1,2,3,4])
+        csc = self.csc_container((data, indices, indptr))
+        assert_array_equal(csc.shape,(6,3))
+
+    def test_constructor6(self):
+        # infer dimensions and dtype from lists
+        indptr = [0, 1, 3, 3]
+        indices = [0, 5, 1, 2]
+        data = [1, 2, 3, 4]
+        csc = self.csc_container((data, indices, indptr))
+        assert_array_equal(csc.shape,(6,3))
+        assert_(np.issubdtype(csc.dtype, np.signedinteger))
+
+    def test_eliminate_zeros(self):
+        data = array([1, 0, 0, 0, 2, 0, 3, 0])
+        indices = array([1, 2, 3, 4, 5, 6, 7, 8])
+        indptr = array([0, 3, 8])
+        asp = self.csc_container((data, indices, indptr), shape=(10,2))
+        bsp = asp.copy()
+        asp.eliminate_zeros()
+        assert_array_equal(asp.nnz, 3)
+        assert_array_equal(asp.data,[1, 2, 3])
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_sort_indices(self):
+        data = arange(5)
+        row = array([7, 2, 1, 5, 4])
+        ptr = [0, 3, 5]
+        asp = self.csc_container((data, row, ptr), shape=(10,2))
+        bsp = asp.copy()
+        asp.sort_indices()
+        assert_array_equal(asp.indices,[1, 2, 7, 4, 5])
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_ufuncs(self):
+        X = self.csc_container(np.arange(21).reshape(7, 3) / 21.)
+        for f in ["sin", "tan", "arcsin", "arctan", "sinh", "tanh",
+                  "arcsinh", "arctanh", "rint", "sign", "expm1", "log1p",
+                  "deg2rad", "rad2deg", "floor", "ceil", "trunc", "sqrt"]:
+            assert_equal(hasattr(self.datsp, f), True)
+            X2 = getattr(X, f)()
+            assert_equal(X.shape, X2.shape)
+            assert_array_equal(X.indices, X2.indices)
+            assert_array_equal(X.indptr, X2.indptr)
+            assert_array_equal(X2.toarray(), getattr(np, f)(X.toarray()))
+
+    def test_unsorted_arithmetic(self):
+        data = arange(5)
+        indices = array([7, 2, 1, 5, 4])
+        indptr = array([0, 3, 5])
+        asp = self.csc_container((data, indices, indptr), shape=(10,2))
+        data = arange(6)
+        indices = array([8, 1, 5, 7, 2, 4])
+        indptr = array([0, 2, 6])
+        bsp = self.csc_container((data, indices, indptr), shape=(10,2))
+        assert_equal((asp + bsp).toarray(), asp.toarray() + bsp.toarray())
+
+    def test_fancy_indexing_broadcast(self):
+        # broadcasting indexing mode is supported
+        I = np.array([[1], [2], [3]])
+        J = np.array([3, 4, 2])
+
+        np.random.seed(1234)
+        D = self.asdense(np.random.rand(5, 7))
+        S = self.spcreator(D)
+
+        SIJ = S[I,J]
+        if issparse(SIJ):
+            SIJ = SIJ.toarray()
+        assert_equal(SIJ, D[I,J])
+
+    def test_scalar_idx_dtype(self):
+        # Check that index dtype takes into account all parameters
+        # passed to sparsetools, including the scalar ones
+        indptr = np.zeros(2, dtype=np.int32)
+        indices = np.zeros(0, dtype=np.int32)
+        vals = np.zeros(0)
+        a = self.csc_container((vals, indices, indptr), shape=(2**31-1, 1))
+        b = self.csc_container((vals, indices, indptr), shape=(2**31, 1))
+        ij = np.zeros((2, 0), dtype=np.int32)
+        c = self.csc_container((vals, ij), shape=(2**31-1, 1))
+        d = self.csc_container((vals, ij), shape=(2**31, 1))
+        e = self.csr_container((1, 2**31-1))
+        f = self.csr_container((1, 2**31))
+        assert_equal(a.indptr.dtype, np.int32)
+        assert_equal(b.indptr.dtype, np.int64)
+        assert_equal(c.indptr.dtype, np.int32)
+        assert_equal(d.indptr.dtype, np.int64)
+        assert_equal(e.indptr.dtype, np.int32)
+        assert_equal(f.indptr.dtype, np.int64)
+
+        # These shouldn't fail
+        for x in [a, b, c, d, e, f]:
+            x + x
+
+    def test_setdiag_csc(self):
+        # see gh-21791 setting mixture of existing and not when new_values < 0.001*nnz
+        D = self.dia_container(([np.arange(1002)], [0]), shape=(1002, 1002))
+        A = self.spcreator(D)
+        A.setdiag(5 * np.ones(A.shape[0]))
+        assert A[-1, -1] == 5
+
+
+TestCSC.init_class()
+
+
+class TestCSCMatrix(_MatrixMixin, TestCSC):
+    @classmethod
+    def spcreator(cls, *args, **kwargs):
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            return csc_matrix(*args, **kwargs)
+
+
+TestCSCMatrix.init_class()
+
+
+class TestDOK(sparse_test_class(minmax=False, nnz_axis=False)):
+    spcreator = dok_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_mult(self):
+        A = self.dok_container((10, 12))
+        A[0, 3] = 10
+        A[5, 6] = 20
+        D = A @ A.T
+        E = A @ A.T.conjugate()
+        assert_array_equal(D.toarray(), E.toarray())
+
+    def test_add_nonzero(self):
+        A = self.spcreator((3,2))
+        A[0,1] = -10
+        A[2,0] = 20
+        A = A + 10
+        B = array([[10, 0], [10, 10], [30, 10]])
+        assert_array_equal(A.toarray(), B)
+
+        A = A + 1j
+        B = B + 1j
+        assert_array_equal(A.toarray(), B)
+
+    def test_dok_divide_scalar(self):
+        A = self.spcreator((3,2))
+        A[0,1] = -10
+        A[2,0] = 20
+
+        assert_array_equal((A/1j).toarray(), A.toarray()/1j)
+        assert_array_equal((A/9).toarray(), A.toarray()/9)
+
+    def test_convert(self):
+        # Test provided by Andrew Straw.  Fails in SciPy <= r1477.
+        (m, n) = (6, 7)
+        a = self.dok_container((m, n))
+
+        # set a few elements, but none in the last column
+        a[2,1] = 1
+        a[0,2] = 2
+        a[3,1] = 3
+        a[1,5] = 4
+        a[4,3] = 5
+        a[4,2] = 6
+
+        # assert that the last column is all zeros
+        assert_array_equal(a.toarray()[:,n-1], zeros(m,))
+
+        # make sure it still works for CSC format
+        csc = a.tocsc()
+        assert_array_equal(csc.toarray()[:,n-1], zeros(m,))
+
+        # now test CSR
+        (m, n) = (n, m)
+        b = a.transpose()
+        assert_equal(b.shape, (m, n))
+        # assert that the last row is all zeros
+        assert_array_equal(b.toarray()[m-1,:], zeros(n,))
+
+        # make sure it still works for CSR format
+        csr = b.tocsr()
+        assert_array_equal(csr.toarray()[m-1,:], zeros(n,))
+
+    def test_ctor(self):
+        # Empty ctor
+        assert_raises(TypeError, self.dok_container)
+
+        # Dense ctor
+        b = array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 2, 0, 3]], 'd')
+        A = self.dok_container(b)
+        assert_equal(b.dtype, A.dtype)
+        assert_equal(A.toarray(), b)
+
+        # Sparse ctor
+        c = self.csr_container(b)
+        assert_equal(A.toarray(), c.toarray())
+
+        data = [[0, 1, 2], [3, 0, 0]]
+        d = self.dok_container(data, dtype=np.float32)
+        assert_equal(d.dtype, np.float32)
+        da = d.toarray()
+        assert_equal(da.dtype, np.float32)
+        assert_array_equal(da, data)
+
+    def test_ticket1160(self):
+        # Regression test for ticket #1160.
+        a = self.dok_container((3,3))
+        a[0,0] = 0
+        # This assert would fail, because the above assignment would
+        # incorrectly call __set_item__ even though the value was 0.
+        assert_((0,0) not in a.keys(), "Unexpected entry (0,0) in keys")
+
+        # Slice assignments were also affected.
+        b = self.dok_container((3,3))
+        b[:,0] = 0
+        assert_(len(b.keys()) == 0, "Unexpected entries in keys")
+
+
+class TestDOKMatrix(_MatrixMixin, TestDOK):
+    spcreator = dok_matrix
+
+
+TestDOK.init_class()
+TestDOKMatrix.init_class()
+
+
+class TestLIL(sparse_test_class(minmax=False)):
+    spcreator = lil_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_dot(self):
+        A = zeros((10, 10), np.complex128)
+        A[0, 3] = 10
+        A[5, 6] = 20j
+
+        B = self.lil_container((10, 10), dtype=np.complex128)
+        B[0, 3] = 10
+        B[5, 6] = 20j
+
+        # TODO: properly handle this assertion on ppc64le
+        if platform.machine() != 'ppc64le':
+            assert_array_equal(A @ A.T, (B @ B.T).toarray())
+
+        assert_array_equal(A @ A.conjugate().T, (B @ B.conjugate().T).toarray())
+
+    def test_scalar_mul(self):
+        x = self.lil_container((3, 3))
+        x[0, 0] = 2
+
+        x = x*2
+        assert_equal(x[0, 0], 4)
+
+        x = x*0
+        assert_equal(x[0, 0], 0)
+
+    def test_truediv_scalar(self):
+        A = self.spcreator((3, 2))
+        A[0, 1] = -10
+        A[2, 0] = 20
+
+        assert_array_equal((A / 1j).toarray(), A.toarray() / 1j)
+        assert_array_equal((A / 9).toarray(), A.toarray() / 9)
+
+    def test_inplace_ops(self):
+        A = self.lil_container([[0, 2, 3], [4, 0, 6]])
+        B = self.lil_container([[0, 1, 0], [0, 2, 3]])
+
+        data = {'add': (B, A + B),
+                'sub': (B, A - B),
+                'mul': (3, A * 3)}
+
+        for op, (other, expected) in data.items():
+            result = A.copy()
+            getattr(result, f'__i{op}__')(other)
+
+            assert_array_equal(result.toarray(), expected.toarray())
+
+        # Ticket 1604.
+        A = self.lil_container((1, 3), dtype=np.dtype('float64'))
+        B = self.asdense([0.1, 0.1, 0.1])
+        A[0, :] += B
+        assert_array_equal(A[0, :].toarray(), B)
+
+    def test_lil_iteration(self):
+        row_data = [[1, 2, 3], [4, 5, 6]]
+        B = self.lil_container(array(row_data))
+        for r, row in enumerate(B):
+            assert_array_equal(row.toarray(), array(row_data[r], ndmin=row.ndim))
+
+    def test_lil_from_csr(self):
+        # Tests whether a LIL can be constructed from a CSR.
+        B = self.lil_container((10, 10))
+        B[0, 3] = 10
+        B[5, 6] = 20
+        B[8, 3] = 30
+        B[3, 8] = 40
+        B[8, 9] = 50
+        C = B.tocsr()
+        D = self.lil_container(C)
+        assert_array_equal(C.toarray(), D.toarray())
+
+    def test_fancy_indexing_lil(self):
+        M = self.asdense(arange(25).reshape(5, 5))
+        A = self.lil_container(M)
+
+        assert_equal(A[array([1, 2, 3]), 2:3].toarray(),
+                     M[array([1, 2, 3]), 2:3])
+
+    def test_point_wise_multiply(self):
+        l = self.lil_container((4, 3))
+        l[0, 0] = 1
+        l[1, 1] = 2
+        l[2, 2] = 3
+        l[3, 1] = 4
+
+        m = self.lil_container((4, 3))
+        m[0, 0] = 1
+        m[0, 1] = 2
+        m[2, 2] = 3
+        m[3, 1] = 4
+        m[3, 2] = 4
+
+        assert_array_equal(l.multiply(m).toarray(),
+                           m.multiply(l).toarray())
+
+        assert_array_equal(l.multiply(m).toarray(),
+                           [[1, 0, 0],
+                            [0, 0, 0],
+                            [0, 0, 9],
+                            [0, 16, 0]])
+
+    def test_lil_multiply_removal(self):
+        # Ticket #1427.
+        a = self.lil_container(np.ones((3, 3)))
+        a *= 2.
+        a[0, :] = 0
+
+
+class TestLILMatrix(_MatrixMixin, TestLIL):
+    spcreator = lil_matrix
+
+
+TestLIL.init_class()
+TestLILMatrix.init_class()
+
+
+class TestCOO(sparse_test_class(getset=False,
+                                slicing=False, slicing_assign=False,
+                                fancy_indexing=False, fancy_assign=False)):
+    spcreator = coo_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        # unsorted triplet format
+        row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
+        col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
+        data = array([6., 10., 3., 9., 1., 4., 11., 2., 8., 5., 7.])
+
+        coo = self.coo_container((data,(row,col)),(4,3))
+        assert_array_equal(arange(12).reshape(4, 3), coo.toarray())
+
+        # using Python lists and a specified dtype
+        coo = self.coo_container(([2**63 + 1, 1], ([0, 1], [0, 1])), dtype=np.uint64)
+        dense = array([[2**63 + 1, 0], [0, 1]], dtype=np.uint64)
+        assert_array_equal(dense, coo.toarray())
+
+    def test_constructor2(self):
+        # unsorted triplet format with duplicates (which are summed)
+        row = array([0,1,2,2,2,2,0,0,2,2])
+        col = array([0,2,0,2,1,1,1,0,0,2])
+        data = array([2,9,-4,5,7,0,-1,2,1,-5])
+        coo = self.coo_container((data,(row,col)),(3,3))
+
+        mat = array([[4, -1, 0], [0, 0, 9], [-3, 7, 0]])
+
+        assert_array_equal(mat, coo.toarray())
+
+    def test_constructor3(self):
+        # empty matrix
+        coo = self.coo_container((4,3))
+
+        assert_array_equal(coo.shape,(4,3))
+        assert_array_equal(coo.row,[])
+        assert_array_equal(coo.col,[])
+        assert_array_equal(coo.data,[])
+        assert_array_equal(coo.toarray(), zeros((4, 3)))
+
+    def test_constructor4(self):
+        # from dense matrix
+        mat = array([[0,1,0,0],
+                     [7,0,3,0],
+                     [0,4,0,0]])
+        coo = self.coo_container(mat)
+        assert_array_equal(coo.toarray(), mat)
+
+        # upgrade rank 1 arrays to row matrix
+        mat = array([0,1,0,0])
+        coo = self.coo_container(mat)
+        expected = mat if self.is_array_test else mat.reshape(1, -1)
+        assert_array_equal(coo.toarray(), expected)
+
+        # error if second arg interpreted as shape (gh-9919)
+        with pytest.raises(TypeError, match=r'object cannot be interpreted'):
+            self.coo_container([0, 11, 22, 33], ([0, 1, 2, 3], [0, 0, 0, 0]))
+
+        # error if explicit shape arg doesn't match the dense matrix
+        with pytest.raises(ValueError, match=r'inconsistent shapes'):
+            self.coo_container([0, 11, 22, 33], shape=(4, 4))
+
+    def test_constructor_data_ij_dtypeNone(self):
+        data = [1]
+        coo = self.coo_container((data, ([0], [0])), dtype=None)
+        assert coo.dtype == np.array(data).dtype
+
+    @pytest.mark.xfail(run=False, reason='COO does not have a __getitem__')
+    def test_iterator(self):
+        pass
+
+    def test_todia_all_zeros(self):
+        zeros = [[0, 0]]
+        dia = self.coo_container(zeros).todia()
+        assert_array_equal(dia.toarray(), zeros)
+
+    def test_sum_duplicates(self):
+        coo = self.coo_container((4,3))
+        coo.sum_duplicates()
+        coo = self.coo_container(([1,2], ([1,0], [1,0])))
+        coo.sum_duplicates()
+        assert_array_equal(coo.toarray(), [[2,0],[0,1]])
+        coo = self.coo_container(([1,2], ([1,1], [1,1])))
+        coo.sum_duplicates()
+        assert_array_equal(coo.toarray(), [[0,0],[0,3]])
+        assert_array_equal(coo.row, [1])
+        assert_array_equal(coo.col, [1])
+        assert_array_equal(coo.data, [3])
+
+    def test_todok_duplicates(self):
+        coo = self.coo_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0])))
+        dok = coo.todok()
+        assert_array_equal(dok.toarray(), coo.toarray())
+
+    def test_tocompressed_duplicates(self):
+        coo = self.coo_container(([1,1,1,1], ([0,2,2,0], [0,1,1,0])))
+        csr = coo.tocsr()
+        assert_equal(csr.nnz + 2, coo.nnz)
+        csc = coo.tocsc()
+        assert_equal(csc.nnz + 2, coo.nnz)
+
+    def test_eliminate_zeros(self):
+        data = array([1, 0, 0, 0, 2, 0, 3, 0])
+        row = array([0, 0, 0, 1, 1, 1, 1, 1])
+        col = array([1, 2, 3, 4, 5, 6, 7, 8])
+        asp = self.coo_container((data, (row, col)), shape=(2,10))
+        bsp = asp.copy()
+        asp.eliminate_zeros()
+        assert_((asp.data != 0).all())
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    def test_reshape_copy(self):
+        arr = [[0, 10, 0, 0], [0, 0, 0, 0], [0, 20, 30, 40]]
+        new_shape = (2, 6)
+        x = self.coo_container(arr)
+
+        y = x.reshape(new_shape)
+        assert_(y.data is x.data)
+
+        y = x.reshape(new_shape, copy=False)
+        assert_(y.data is x.data)
+
+        y = x.reshape(new_shape, copy=True)
+        assert_(not np.may_share_memory(y.data, x.data))
+
+    def test_large_dimensions_reshape(self):
+        # Test that reshape is immune to integer overflow when number of elements
+        # exceeds 2^31-1
+        mat1 = self.coo_container(([1], ([3000000], [1000])), (3000001, 1001))
+        mat2 = self.coo_container(([1], ([1000], [3000000])), (1001, 3000001))
+
+        # assert_array_equal is slow for big matrices because it expects dense
+        # Using __ne__ and nnz instead
+        assert_((mat1.reshape((1001, 3000001), order='C') != mat2).nnz == 0)
+        assert_((mat2.reshape((3000001, 1001), order='F') != mat1).nnz == 0)
+
+
+class TestCOOMatrix(_MatrixMixin, TestCOO):
+    spcreator = coo_matrix
+
+
+TestCOO.init_class()
+TestCOOMatrix.init_class()
+
+
+class TestDIA(sparse_test_class(getset=False, slicing=False, slicing_assign=False,
+                                fancy_indexing=False, fancy_assign=False,
+                                minmax=False, nnz_axis=False)):
+    spcreator = dia_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        D = array([[1, 0, 3, 0],
+                   [1, 2, 0, 4],
+                   [0, 2, 3, 0],
+                   [0, 0, 3, 4]])
+        data = np.array([[1,2,3,4]]).repeat(3,axis=0)
+        offsets = np.array([0,-1,2])
+        assert_equal(self.dia_container((data, offsets), shape=(4, 4)).toarray(), D)
+
+    @pytest.mark.xfail(run=False, reason='DIA does not have a __getitem__')
+    def test_iterator(self):
+        pass
+
+    @with_64bit_maxval_limit(3)
+    def test_setdiag_dtype(self):
+        m = self.dia_container(np.eye(3))
+        assert_equal(m.offsets.dtype, np.int32)
+        m.setdiag((3,), k=2)
+        assert_equal(m.offsets.dtype, np.int32)
+
+        m = self.dia_container(np.eye(4))
+        assert_equal(m.offsets.dtype, np.int64)
+        m.setdiag((3,), k=3)
+        assert_equal(m.offsets.dtype, np.int64)
+
+    @pytest.mark.skip(reason='DIA stores extra zeros')
+    def test_getnnz_axis(self):
+        pass
+
+    def test_convert_gh14555(self):
+        # regression test for gh-14555
+        m = self.dia_container(([[1, 1, 0]], [-1]), shape=(4, 2))
+        expected = m.toarray()
+        assert_array_equal(m.tocsc().toarray(), expected)
+        assert_array_equal(m.tocsr().toarray(), expected)
+
+    def test_tocoo_gh10050(self):
+        # regression test for gh-10050
+        m = self.dia_container([[1, 2], [3, 4]]).tocoo()
+        flat_inds = np.ravel_multi_index((m.row, m.col), m.shape)
+        inds_are_sorted = np.all(np.diff(flat_inds) > 0)
+        assert m.has_canonical_format == inds_are_sorted
+
+    def test_tocoo_tocsr_tocsc_gh19245(self):
+        # test index_dtype with tocoo, tocsr, tocsc
+        data = np.array([[1, 2, 3, 4]]).repeat(3, axis=0)
+        offsets = np.array([0, -1, 2], dtype=np.int32)
+        dia = sparse.dia_array((data, offsets), shape=(4, 4))
+
+        coo = dia.tocoo()
+        assert coo.col.dtype == np.int32
+        csr = dia.tocsr()
+        assert csr.indices.dtype == np.int32
+        csc = dia.tocsc()
+        assert csc.indices.dtype == np.int32
+
+    def test_mul_scalar(self):
+        # repro for gh-20434
+        m = self.dia_container([[1, 2], [0, 4]])
+        res = m * 3
+        assert isinstance(res, m.__class__)
+        assert_array_equal(res.toarray(), [[3, 6], [0, 12]])
+
+        res2 = m.multiply(3)
+        assert isinstance(res2, m.__class__)
+        assert_array_equal(res2.toarray(), [[3, 6], [0, 12]])
+
+
+class TestDIAMatrix(_MatrixMixin, TestDIA):
+    spcreator = dia_matrix
+
+
+TestDIA.init_class()
+TestDIAMatrix.init_class()
+
+
+class TestBSR(sparse_test_class(getset=False,
+                                slicing=False, slicing_assign=False,
+                                fancy_indexing=False, fancy_assign=False,
+                                nnz_axis=False)):
+    spcreator = bsr_array
+    math_dtypes = [np.int_, np.float64, np.complex128]
+
+    def test_constructor1(self):
+        # check native BSR format constructor
+        indptr = array([0,2,2,4])
+        indices = array([0,2,2,3])
+        data = zeros((4,2,3))
+
+        data[0] = array([[0, 1, 2],
+                         [3, 0, 5]])
+        data[1] = array([[0, 2, 4],
+                         [6, 0, 10]])
+        data[2] = array([[0, 4, 8],
+                         [12, 0, 20]])
+        data[3] = array([[0, 5, 10],
+                         [15, 0, 25]])
+
+        A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]])
+        Asp = self.bsr_container((data,indices,indptr),shape=(6,12))
+        assert_equal(Asp.toarray(), A)
+
+        # infer shape from arrays
+        Asp = self.bsr_container((data,indices,indptr))
+        assert_equal(Asp.toarray(), A)
+
+    def test_constructor2(self):
+        # construct from dense
+
+        # test zero mats
+        for shape in [(1,1), (5,1), (1,10), (10,4), (3,7), (2,1)]:
+            A = zeros(shape)
+            assert_equal(self.bsr_container(A).toarray(), A)
+        A = zeros((4,6))
+        assert_equal(self.bsr_container(A, blocksize=(2, 2)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(2, 3)).toarray(), A)
+
+        A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]])
+        assert_equal(self.bsr_container(A).toarray(), A)
+        assert_equal(self.bsr_container(A, shape=(6, 12)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(1, 1)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(2, 3)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(2, 6)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(2, 12)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(3, 12)).toarray(), A)
+        assert_equal(self.bsr_container(A, blocksize=(6, 12)).toarray(), A)
+
+        A = kron([[1,0,2,0],[0,1,0,0],[0,0,0,0]], [[0,1,2],[3,0,5]])
+        assert_equal(self.bsr_container(A, blocksize=(2, 3)).toarray(), A)
+
+    def test_constructor3(self):
+        # construct from coo-like (data,(row,col)) format
+        arg = ([1,2,3], ([0,1,1], [0,0,1]))
+        A = array([[1,0],[2,3]])
+        assert_equal(self.bsr_container(arg, blocksize=(2, 2)).toarray(), A)
+
+    def test_constructor4(self):
+        # regression test for gh-6292: self.bsr_matrix((data, indices, indptr)) was
+        #  trying to compare an int to a None
+        n = 8
+        data = np.ones((n, n, 1), dtype=np.int8)
+        indptr = np.array([0, n], dtype=np.int32)
+        indices = np.arange(n, dtype=np.int32)
+        self.bsr_container((data, indices, indptr), blocksize=(n, 1), copy=False)
+
+    def test_constructor5(self):
+        # check for validations introduced in gh-13400
+        n = 8
+        data_1dim = np.ones(n)
+        data = np.ones((n, n, n))
+        indptr = np.array([0, n])
+        indices = np.arange(n)
+
+        with assert_raises(ValueError):
+            # data ndim check
+            self.bsr_container((data_1dim, indices, indptr))
+
+        with assert_raises(ValueError):
+            # invalid blocksize
+            self.bsr_container((data, indices, indptr), blocksize=(1, 1, 1))
+
+        with assert_raises(ValueError):
+            # mismatching blocksize
+            self.bsr_container((data, indices, indptr), blocksize=(1, 1))
+
+    def test_default_dtype(self):
+        # As a numpy array, `values` has shape (2, 2, 1).
+        values = [[[1], [1]], [[1], [1]]]
+        indptr = np.array([0, 2], dtype=np.int32)
+        indices = np.array([0, 1], dtype=np.int32)
+        b = self.bsr_container((values, indices, indptr), blocksize=(2, 1))
+        assert b.dtype == np.array(values).dtype
+
+    def test_bsr_tocsr(self):
+        # check native conversion from BSR to CSR
+        indptr = array([0, 2, 2, 4])
+        indices = array([0, 2, 2, 3])
+        data = zeros((4, 2, 3))
+
+        data[0] = array([[0, 1, 2],
+                         [3, 0, 5]])
+        data[1] = array([[0, 2, 4],
+                         [6, 0, 10]])
+        data[2] = array([[0, 4, 8],
+                         [12, 0, 20]])
+        data[3] = array([[0, 5, 10],
+                         [15, 0, 25]])
+
+        A = kron([[1, 0, 2, 0], [0, 0, 0, 0], [0, 0, 4, 5]],
+                 [[0, 1, 2], [3, 0, 5]])
+        Absr = self.bsr_container((data, indices, indptr), shape=(6, 12))
+        Acsr = Absr.tocsr()
+        Acsr_via_coo = Absr.tocoo().tocsr()
+        assert_equal(Acsr.toarray(), A)
+        assert_equal(Acsr.toarray(), Acsr_via_coo.toarray())
+
+    def test_eliminate_zeros(self):
+        data = kron([1, 0, 0, 0, 2, 0, 3, 0], [[1,1],[1,1]]).T
+        data = data.reshape(-1,2,2)
+        indices = array([1, 2, 3, 4, 5, 6, 7, 8])
+        indptr = array([0, 3, 8])
+        asp = self.bsr_container((data, indices, indptr), shape=(4,20))
+        bsp = asp.copy()
+        asp.eliminate_zeros()
+        assert_array_equal(asp.nnz, 3*4)
+        assert_array_equal(asp.toarray(), bsp.toarray())
+
+    # GitHub issue #9687
+    def test_eliminate_zeros_all_zero(self):
+        np.random.seed(0)
+        m = self.bsr_container(np.random.random((12, 12)), blocksize=(2, 3))
+
+        # eliminate some blocks, but not all
+        m.data[m.data <= 0.9] = 0
+        m.eliminate_zeros()
+        assert_equal(m.nnz, 66)
+        assert_array_equal(m.data.shape, (11, 2, 3))
+
+        # eliminate all remaining blocks
+        m.data[m.data <= 1.0] = 0
+        m.eliminate_zeros()
+        assert_equal(m.nnz, 0)
+        assert_array_equal(m.data.shape, (0, 2, 3))
+        assert_array_equal(m.toarray(), np.zeros((12, 12)))
+
+        # test fast path
+        m.eliminate_zeros()
+        assert_equal(m.nnz, 0)
+        assert_array_equal(m.data.shape, (0, 2, 3))
+        assert_array_equal(m.toarray(), np.zeros((12, 12)))
+
+    def test_bsr_matvec(self):
+        A = self.bsr_container(arange(2*3*4*5).reshape(2*4,3*5), blocksize=(4,5))
+        x = arange(A.shape[1]).reshape(-1,1)
+        assert_equal(A @ x, A.toarray() @ x)
+
+    def test_bsr_matvecs(self):
+        A = self.bsr_container(arange(2*3*4*5).reshape(2*4,3*5), blocksize=(4,5))
+        x = arange(A.shape[1]*6).reshape(-1,6)
+        assert_equal(A @ x, A.toarray() @ x)
+
+    @pytest.mark.xfail(run=False, reason='BSR does not have a __getitem__')
+    def test_iterator(self):
+        pass
+
+    @pytest.mark.xfail(run=False, reason='BSR does not have a __setitem__')
+    def test_setdiag(self):
+        pass
+
+    def test_resize_blocked(self):
+        # test resize() with non-(1,1) blocksize
+        D = np.array([[1, 0, 3, 4],
+                      [2, 0, 0, 0],
+                      [3, 0, 0, 0]])
+        S = self.spcreator(D, blocksize=(1, 2))
+        assert_(S.resize((3, 2)) is None)
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [3, 0]])
+        S.resize((2, 2))
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0]])
+        S.resize((3, 2))
+        assert_array_equal(S.toarray(), [[1, 0],
+                                         [2, 0],
+                                         [0, 0]])
+        S.resize((3, 4))
+        assert_array_equal(S.toarray(), [[1, 0, 0, 0],
+                                         [2, 0, 0, 0],
+                                         [0, 0, 0, 0]])
+        assert_raises(ValueError, S.resize, (2, 3))
+
+    @pytest.mark.xfail(run=False, reason='BSR does not have a __setitem__')
+    def test_setdiag_comprehensive(self):
+        pass
+
+    @pytest.mark.skipif(IS_COLAB, reason="exceeds memory limit")
+    def test_scalar_idx_dtype(self):
+        # Check that index dtype takes into account all parameters
+        # passed to sparsetools, including the scalar ones
+        indptr = np.zeros(2, dtype=np.int32)
+        indices = np.zeros(0, dtype=np.int32)
+        vals = np.zeros((0, 1, 1))
+        a = self.bsr_container((vals, indices, indptr), shape=(1, 2**31-1))
+        b = self.bsr_container((vals, indices, indptr), shape=(1, 2**31))
+        c = self.bsr_container((1, 2**31-1))
+        d = self.bsr_container((1, 2**31))
+        assert_equal(a.indptr.dtype, np.int32)
+        assert_equal(b.indptr.dtype, np.int64)
+        assert_equal(c.indptr.dtype, np.int32)
+        assert_equal(d.indptr.dtype, np.int64)
+
+        try:
+            vals2 = np.zeros((0, 1, 2**31-1))
+            vals3 = np.zeros((0, 1, 2**31))
+            e = self.bsr_container((vals2, indices, indptr), shape=(1, 2**31-1))
+            f = self.bsr_container((vals3, indices, indptr), shape=(1, 2**31))
+            assert_equal(e.indptr.dtype, np.int32)
+            assert_equal(f.indptr.dtype, np.int64)
+        except (MemoryError, ValueError):
+            # May fail on 32-bit Python
+            e = 0
+            f = 0
+
+        # These shouldn't fail
+        for x in [a, b, c, d, e, f]:
+            x + x
+
+
+class TestBSRMatrix(_MatrixMixin, TestBSR):
+    spcreator = bsr_matrix
+
+
+TestBSR.init_class()
+TestBSRMatrix.init_class()
+
+
+#------------------------------------------------------------------------------
+# Tests for non-canonical representations (with duplicates, unsorted indices)
+#------------------------------------------------------------------------------
+
+def _same_sum_duplicate(data, *inds, **kwargs):
+    """Duplicates entries to produce the same matrix"""
+    indptr = kwargs.pop('indptr', None)
+    if np.issubdtype(data.dtype, np.bool_) or \
+       np.issubdtype(data.dtype, np.unsignedinteger):
+        if indptr is None:
+            return (data,) + inds
+        else:
+            return (data,) + inds + (indptr,)
+
+    zeros_pos = (data == 0).nonzero()
+
+    # duplicate data
+    data = data.repeat(2, axis=0)
+    data[::2] -= 1
+    data[1::2] = 1
+
+    # don't spoil all explicit zeros
+    if zeros_pos[0].size > 0:
+        pos = tuple(p[0] for p in zeros_pos)
+        pos1 = (2*pos[0],) + pos[1:]
+        pos2 = (2*pos[0]+1,) + pos[1:]
+        data[pos1] = 0
+        data[pos2] = 0
+
+    inds = tuple(indices.repeat(2) for indices in inds)
+
+    if indptr is None:
+        return (data,) + inds
+    else:
+        return (data,) + inds + (indptr * 2,)
+
+
+class _NonCanonicalMixin:
+    def spcreator(self, D, *args, sorted_indices=False, **kwargs):
+        """Replace D with a non-canonical equivalent: containing
+        duplicate elements and explicit zeros"""
+        construct = super().spcreator
+        M = construct(D, *args, **kwargs)
+
+        zero_pos = (M.toarray() == 0).nonzero()
+        has_zeros = (zero_pos[0].size > 0)
+        if has_zeros:
+            k = zero_pos[0].size//2
+            with suppress_warnings() as sup:
+                sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+                M = self._insert_explicit_zero(M, zero_pos[0][k], zero_pos[1][k])
+
+        arg1 = self._arg1_for_noncanonical(M, sorted_indices)
+        if 'shape' not in kwargs:
+            kwargs['shape'] = M.shape
+        NC = construct(arg1, **kwargs)
+
+        # check that result is valid
+        if NC.dtype in [np.float32, np.complex64]:
+            # For single-precision floats, the differences between M and NC
+            # that are introduced by the extra operations involved in the
+            # construction of NC necessitate a more lenient tolerance level
+            # than the default.
+            rtol = 1e-05
+        else:
+            rtol = 1e-07
+        assert_allclose(NC.toarray(), M.toarray(), rtol=rtol)
+
+        # check that at least one explicit zero
+        if has_zeros:
+            assert_((NC.data == 0).any())
+        # TODO check that NC has duplicates (which are not explicit zeros)
+
+        return NC
+
+    @pytest.mark.skip(reason='bool(matrix) counts explicit zeros')
+    def test_bool(self):
+        pass
+
+    @pytest.mark.skip(reason='getnnz-axis counts explicit zeros')
+    def test_getnnz_axis(self):
+        pass
+
+    @pytest.mark.skip(reason='nnz counts explicit zeros')
+    def test_empty(self):
+        pass
+
+
+class _NonCanonicalCompressedMixin(_NonCanonicalMixin):
+    def _arg1_for_noncanonical(self, M, sorted_indices=False):
+        """Return non-canonical constructor arg1 equivalent to M"""
+        data, indices, indptr = _same_sum_duplicate(M.data, M.indices,
+                                                    indptr=M.indptr)
+        if not sorted_indices:
+            for start, stop in zip(indptr, indptr[1:]):
+                indices[start:stop] = indices[start:stop][::-1].copy()
+                data[start:stop] = data[start:stop][::-1].copy()
+        return data, indices, indptr
+
+    def _insert_explicit_zero(self, M, i, j):
+        M[i,j] = 0
+        return M
+
+
+class _NonCanonicalCSMixin(_NonCanonicalCompressedMixin):
+    def test_getelement(self):
+        def check(dtype, sorted_indices):
+            D = array([[1,0,0],
+                       [4,3,0],
+                       [0,2,0],
+                       [0,0,0]], dtype=dtype)
+            A = self.spcreator(D, sorted_indices=sorted_indices)
+
+            M,N = D.shape
+
+            for i in range(-M, M):
+                for j in range(-N, N):
+                    assert_equal(A[i,j], D[i,j])
+
+            for ij in [(0,3),(-1,3),(4,0),(4,3),(4,-1), (1, 2, 3)]:
+                assert_raises((IndexError, TypeError), A.__getitem__, ij)
+
+        for dtype in supported_dtypes:
+            for sorted_indices in [False, True]:
+                check(np.dtype(dtype), sorted_indices)
+
+    def test_setitem_sparse(self):
+        D = np.eye(3)
+        A = self.spcreator(D)
+        B = self.spcreator([[1,2,3]])
+
+        D[1,:] = B.toarray()
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            A[1,:] = B
+        assert_array_equal(A.toarray(), D)
+
+        D[:,2] = B.toarray().ravel()
+        with suppress_warnings() as sup:
+            sup.filter(SparseEfficiencyWarning, "Changing the sparsity structure")
+            A[:,2] = B.T
+        assert_array_equal(A.toarray(), D)
+
+    @pytest.mark.xfail(run=False, reason='inverse broken with non-canonical matrix')
+    def test_inv(self):
+        pass
+
+    @pytest.mark.xfail(run=False, reason='solve broken with non-canonical matrix')
+    def test_solve(self):
+        pass
+
+
+class TestCSRNonCanonical(_NonCanonicalCSMixin, TestCSR):
+    pass
+
+
+class TestCSRNonCanonicalMatrix(TestCSRNonCanonical, TestCSRMatrix):
+    pass
+
+
+class TestCSCNonCanonical(_NonCanonicalCSMixin, TestCSC):
+    pass
+
+
+class TestCSCNonCanonicalMatrix(TestCSCNonCanonical, TestCSCMatrix):
+    pass
+
+
+class TestBSRNonCanonical(_NonCanonicalCompressedMixin, TestBSR):
+    def _insert_explicit_zero(self, M, i, j):
+        x = M.tocsr()
+        x[i,j] = 0
+        return x.tobsr(blocksize=M.blocksize)
+
+    @pytest.mark.xfail(run=False, reason='diagonal broken with non-canonical BSR')
+    def test_diagonal(self):
+        pass
+
+    @pytest.mark.xfail(run=False, reason='expm broken with non-canonical BSR')
+    def test_expm(self):
+        pass
+
+
+class TestBSRNonCanonicalMatrix(TestBSRNonCanonical, TestBSRMatrix):
+    pass
+
+
+class TestCOONonCanonical(_NonCanonicalMixin, TestCOO):
+    def _arg1_for_noncanonical(self, M, sorted_indices=None):
+        """Return non-canonical constructor arg1 equivalent to M"""
+        data, row, col = _same_sum_duplicate(M.data, M.row, M.col)
+        return data, (row, col)
+
+    def _insert_explicit_zero(self, M, i, j):
+        M.data = np.r_[M.data.dtype.type(0), M.data]
+        M.row = np.r_[M.row.dtype.type(i), M.row]
+        M.col = np.r_[M.col.dtype.type(j), M.col]
+        return M
+
+    def test_setdiag_noncanonical(self):
+        m = self.spcreator(np.eye(3))
+        m.sum_duplicates()
+        m.setdiag([3, 2], k=1)
+        m.sum_duplicates()
+        assert_(np.all(np.diff(m.col) >= 0))
+
+
+class TestCOONonCanonicalMatrix(TestCOONonCanonical, TestCOOMatrix):
+    pass
+
+
+#Todo: Revisit 64bit tests: avoid rerun of all tests for each version of get_index_dtype
+def cases_64bit(sp_api):
+    """Yield all tests for all formats that use get_index_dtype
+
+    This is more than testing get_index_dtype. It allows checking whether upcasting
+    or downcasting the index dtypes affects test results. The approach used here
+    does not try to figure out which tests might fail due to 32/64-bit issues.
+    We just run them all.
+    So, each test method in that uses cases_64bit reruns most of the test suite!
+    """
+    if sp_api == "sparray":
+        TEST_CLASSES = [TestBSR, TestCOO, TestCSC, TestCSR, TestDIA,
+                         # lil/dok->other conversion operations use get_index_dtype
+                         # so we include lil & dok test suite even though they do not
+                         # use get_index_dtype within the class. That means many of
+                         # these tests are superfluous, but it's hard to pick which
+                         TestDOK, TestLIL
+                        ]
+    elif sp_api == "spmatrix":
+        TEST_CLASSES = [TestBSRMatrix, TestCOOMatrix, TestCSCMatrix,
+                         TestCSRMatrix, TestDIAMatrix,
+                         # lil/dok->other conversion operations use get_index_dtype
+                         TestDOKMatrix, TestLILMatrix
+                        ]
+    else:
+        raise ValueError(f"parameter {sp_api=} is not one of 'sparray' or 'spmatrix'")
+
+    # The following features are missing, so skip the tests:
+    SKIP_TESTS = {
+        'test_expm': 'expm for 64-bit indices not available',
+        'test_inv': 'linsolve for 64-bit indices not available',
+        'test_solve': 'linsolve for 64-bit indices not available',
+        'test_scalar_idx_dtype': 'test implemented in base class',
+        'test_large_dimensions_reshape': 'test actually requires 64-bit to work',
+        'test_constructor_smallcol': 'test verifies int32 indexes',
+        'test_constructor_largecol': 'test verifies int64 indexes',
+        'test_tocoo_tocsr_tocsc_gh19245': 'test verifies int32 indexes',
+    }
+
+    for cls in TEST_CLASSES:
+        for method_name in sorted(dir(cls)):
+            method = getattr(cls, method_name)
+            if (method_name.startswith('test_') and
+                    not getattr(method, 'slow', False)):
+                marks = []
+
+                msg = SKIP_TESTS.get(method_name)
+                if bool(msg):
+                    marks += [pytest.mark.skip(reason=msg)]
+
+                markers = getattr(method, 'pytestmark', [])
+                for mark in markers:
+                    if mark.name in ('skipif', 'skip', 'xfail', 'xslow'):
+                        marks.append(mark)
+
+                yield pytest.param(cls, method_name, marks=marks)
+
+
+class Test64Bit:
+    # classes that use get_index_dtype
+    MAT_CLASSES = [
+        bsr_matrix, coo_matrix, csc_matrix, csr_matrix, dia_matrix,
+        bsr_array, coo_array, csc_array, csr_array, dia_array,
+    ]
+
+    def _compare_index_dtype(self, m, dtype):
+        dtype = np.dtype(dtype)
+        if m.format in ['csc', 'csr', 'bsr']:
+            return (m.indices.dtype == dtype) and (m.indptr.dtype == dtype)
+        elif m.format == 'coo':
+            return (m.row.dtype == dtype) and (m.col.dtype == dtype)
+        elif m.format == 'dia':
+            return (m.offsets.dtype == dtype)
+        else:
+            raise ValueError(f"matrix {m!r} has no integer indices")
+
+    @pytest.mark.thread_unsafe
+    def test_decorator_maxval_limit(self):
+        # Test that the with_64bit_maxval_limit decorator works
+
+        @with_64bit_maxval_limit(maxval_limit=10)
+        def check(mat_cls):
+            m = mat_cls(np.random.rand(10, 1))
+            assert_(self._compare_index_dtype(m, np.int32))
+            m = mat_cls(np.random.rand(11, 1))
+            assert_(self._compare_index_dtype(m, np.int64))
+
+        for mat_cls in self.MAT_CLASSES:
+            check(mat_cls)
+
+    @pytest.mark.thread_unsafe
+    def test_decorator_maxval_random(self):
+        # Test that the with_64bit_maxval_limit decorator works (2)
+
+        @with_64bit_maxval_limit(random=True)
+        def check(mat_cls):
+            seen_32 = False
+            seen_64 = False
+            for k in range(100):
+                m = mat_cls(np.random.rand(9, 9))
+                seen_32 = seen_32 or self._compare_index_dtype(m, np.int32)
+                seen_64 = seen_64 or self._compare_index_dtype(m, np.int64)
+                if seen_32 and seen_64:
+                    break
+            else:
+                raise AssertionError("both 32 and 64 bit indices not seen")
+
+        for mat_cls in self.MAT_CLASSES:
+            check(mat_cls)
+
+    @pytest.mark.thread_unsafe
+    def test_downcast_intp(self):
+        # Check that bincount and ufunc.reduceat intp downcasts are
+        # dealt with. The point here is to trigger points in the code
+        # that can fail on 32-bit systems when using 64-bit indices,
+        # due to use of functions that only work with intp-size
+        # indices.
+
+        @with_64bit_maxval_limit(fixed_dtype=np.int64, downcast_maxval=1)
+        def check_limited(csc_container, csr_container, coo_container):
+            # These involve indices larger than `downcast_maxval`
+            a = csc_container([[1, 2], [3, 4], [5, 6]])
+            assert_raises(AssertionError, a.count_nonzero, axis=1)
+            assert_raises(AssertionError, a.sum, axis=0)
+
+            a = csr_container([[1, 2, 3], [3, 4, 6]])
+            assert_raises(AssertionError, a.count_nonzero, axis=0)
+            assert_raises(AssertionError, a.sum, axis=1)
+
+            a = coo_container([[1, 2, 3], [3, 4, 5]])
+            assert_raises(AssertionError, a.count_nonzero, axis=0)
+            a.has_canonical_format = False
+            assert_raises(AssertionError, a.sum_duplicates)
+
+        @with_64bit_maxval_limit(fixed_dtype=np.int64)
+        def check_unlimited(csc_container, csr_container, coo_container):
+            # These involve indices smaller than `downcast_maxval`
+            a = csc_container([[1, 2], [3, 4], [5, 6]])
+            a.count_nonzero(axis=1)
+            a.sum(axis=0)
+
+            a = csr_container([[1, 2, 3], [3, 4, 6]])
+            a.count_nonzero(axis=0)
+            a.sum(axis=1)
+
+            a = coo_container([[1, 2, 3], [3, 4, 5]])
+            a.count_nonzero(axis=0)
+            a.has_canonical_format = False
+            a.sum_duplicates()
+
+        check_limited(csc_array, csr_array, coo_array)
+        check_unlimited(csc_array, csr_array, coo_array)
+        check_limited(csc_matrix, csr_matrix, coo_matrix)
+        check_unlimited(csc_matrix, csr_matrix, coo_matrix)
+
+
+# Testing both spmatrices and sparrays for 64bit index dtype handling is
+# expensive and double-checks the same code (e.g. _coobase)
+class RunAll64Bit:
+    def _check_resiliency(self, cls, method_name, **kw):
+        # Resiliency test, to check that sparse matrices deal reasonably
+        # with varying index data types.
+
+        @with_64bit_maxval_limit(**kw)
+        def check(cls, method_name):
+            instance = cls()
+            if hasattr(instance, 'setup_method'):
+                instance.setup_method()
+            try:
+                getattr(instance, method_name)()
+            finally:
+                if hasattr(instance, 'teardown_method'):
+                    instance.teardown_method()
+
+        check(cls, method_name)
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.slow
+class Test64BitArray(RunAll64Bit):
+    # inheritance of pytest test classes does not separate marks for subclasses.
+    # So we define these functions in both Array and Matrix versions.
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray"))
+    def test_resiliency_limit_10(self, cls, method_name):
+        self._check_resiliency(cls, method_name, maxval_limit=10)
+
+    @pytest.mark.fail_slow(2)
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray"))
+    def test_resiliency_random(self, cls, method_name):
+        # bsr_array.eliminate_zeros relies on csr_array constructor
+        # not making copies of index arrays --- this is not
+        # necessarily true when we pick the index data type randomly
+        self._check_resiliency(cls, method_name, random=True)
+
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray"))
+    def test_resiliency_all_32(self, cls, method_name):
+        self._check_resiliency(cls, method_name, fixed_dtype=np.int32)
+
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("sparray"))
+    def test_resiliency_all_64(self, cls, method_name):
+        self._check_resiliency(cls, method_name, fixed_dtype=np.int64)
+
+
+@pytest.mark.thread_unsafe
+class Test64BitMatrix(RunAll64Bit):
+    # assert_32bit=True only for spmatrix cuz sparray does not check index content
+    @pytest.mark.fail_slow(5)
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_no_64(self, cls, method_name):
+        self._check_resiliency(cls, method_name, assert_32bit=True)
+
+    # inheritance of pytest test classes does not separate marks for subclasses.
+    # So we define these functions in both Array and Matrix versions.
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_resiliency_limit_10(self, cls, method_name):
+        self._check_resiliency(cls, method_name, maxval_limit=10)
+
+    @pytest.mark.fail_slow(2)
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_resiliency_random(self, cls, method_name):
+        # bsr_array.eliminate_zeros relies on csr_array constructor
+        # not making copies of index arrays --- this is not
+        # necessarily true when we pick the index data type randomly
+        self._check_resiliency(cls, method_name, random=True)
+
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_resiliency_all_32(self, cls, method_name):
+        self._check_resiliency(cls, method_name, fixed_dtype=np.int32)
+
+    @pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
+    def test_resiliency_all_64(self, cls, method_name):
+        self._check_resiliency(cls, method_name, fixed_dtype=np.int64)
+
+def test_broadcast_to():
+    a = np.array([[1, 0, 2]])
+    b = np.array([[1], [0], [2]])
+    c = np.array([[1, 0, 2], [0, 3, 0]])
+    d = np.array([[7]])
+    e = np.array([[0]])
+    f = np.array([[0,0,0,0]])
+    for container in (csc_matrix, csc_array, csr_matrix, csr_array):
+        res_a = container(a)._broadcast_to((2,3))
+        res_b = container(b)._broadcast_to((3,4))
+        res_c = container(c)._broadcast_to((2,3))
+        res_d = container(d)._broadcast_to((4,4))
+        res_e = container(e)._broadcast_to((5,6))
+        res_f = container(f)._broadcast_to((2,4))
+        assert_array_equal(res_a.toarray(), np.broadcast_to(a, (2,3)))
+        assert_array_equal(res_b.toarray(), np.broadcast_to(b, (3,4)))
+        assert_array_equal(res_c.toarray(), c)
+        assert_array_equal(res_d.toarray(), np.broadcast_to(d, (4,4)))
+        assert_array_equal(res_e.toarray(), np.broadcast_to(e, (5,6)))
+        assert_array_equal(res_f.toarray(), np.broadcast_to(f, (2,4)))
+
+        with pytest.raises(ValueError, match="cannot be broadcast"):
+            container([[1, 2, 0], [3, 0, 1]])._broadcast_to(shape=(2, 1))
+
+        with pytest.raises(ValueError, match="cannot be broadcast"):
+            container([[0, 1, 2]])._broadcast_to(shape=(3, 2))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_common1d.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_common1d.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab091f7c8fccc42c6d9c6c249e59b1d5e9c326b8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_common1d.py
@@ -0,0 +1,447 @@
+"""Test of 1D aspects of sparse array classes"""
+
+import pytest
+
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+
+from scipy.sparse import (
+        bsr_array, csc_array, dia_array, lil_array,
+        coo_array, csr_array, dok_array,
+    )
+from scipy.sparse._sputils import supported_dtypes, matrix
+from scipy._lib._util import ComplexWarning
+
+
+sup_complex = np.testing.suppress_warnings()
+sup_complex.filter(ComplexWarning)
+
+
+spcreators = [coo_array, csr_array, dok_array]
+math_dtypes = [np.int64, np.float64, np.complex128]
+
+
+@pytest.fixture
+def dat1d():
+    return np.array([3, 0, 1, 0], 'd')
+
+
+@pytest.fixture
+def datsp_math_dtypes(dat1d):
+    dat_dtypes = {dtype: dat1d.astype(dtype) for dtype in math_dtypes}
+    return {
+        spcreator: [(dtype, dat, spcreator(dat)) for dtype, dat in dat_dtypes.items()]
+        for spcreator in spcreators
+    }
+
+
+# Test init with 1D dense input
+# sparrays which do not plan to support 1D
+@pytest.mark.parametrize("spcreator", [bsr_array, csc_array, dia_array, lil_array])
+def test_no_1d_support_in_init(spcreator):
+    with pytest.raises(ValueError, match="arrays don't support 1D input"):
+        spcreator([0, 1, 2, 3])
+
+
+# Test init with nD dense input
+# sparrays which do not yet support nD
+@pytest.mark.parametrize(
+    "spcreator", [csr_array, dok_array, bsr_array, csc_array, dia_array, lil_array]
+)
+def test_no_nd_support_in_init(spcreator):
+    with pytest.raises(ValueError, match="arrays don't.*support 3D"):
+        spcreator(np.ones((3, 2, 4)))
+
+
+# Main tests class
+@pytest.mark.parametrize("spcreator", spcreators)
+class TestCommon1D:
+    """test common functionality shared by 1D sparse formats"""
+
+    def test_create_empty(self, spcreator):
+        assert_equal(spcreator((3,)).toarray(), np.zeros(3))
+        assert_equal(spcreator((3,)).nnz, 0)
+        assert_equal(spcreator((3,)).count_nonzero(), 0)
+
+    def test_invalid_shapes(self, spcreator):
+        with pytest.raises(ValueError, match='elements cannot be negative'):
+            spcreator((-3,))
+
+    def test_repr(self, spcreator, dat1d):
+        repr(spcreator(dat1d))
+
+    def test_str(self, spcreator, dat1d):
+        str(spcreator(dat1d))
+
+    def test_neg(self, spcreator):
+        A = np.array([-1, 0, 17, 0, -5, 0, 1, -4, 0, 0, 0, 0], 'd')
+        assert_equal(-A, (-spcreator(A)).toarray())
+
+    def test_1d_supported_init(self, spcreator):
+        A = spcreator([0, 1, 2, 3])
+        assert A.ndim == 1
+
+    def test_reshape_1d_tofrom_row_or_column(self, spcreator):
+        # add a dimension 1d->2d
+        x = spcreator([1, 0, 7, 0, 0, 0, 0, -3, 0, 0, 0, 5])
+        y = x.reshape(1, 12)
+        desired = [[1, 0, 7, 0, 0, 0, 0, -3, 0, 0, 0, 5]]
+        assert_equal(y.toarray(), desired)
+
+        # remove a size-1 dimension 2d->1d
+        x = spcreator(desired)
+        y = x.reshape(12)
+        assert_equal(y.toarray(), desired[0])
+        y2 = x.reshape((12,))
+        assert y.shape == y2.shape
+
+        # make a 2d column into 1d. 2d->1d
+        y = x.T.reshape(12)
+        assert_equal(y.toarray(), desired[0])
+
+    def test_reshape(self, spcreator):
+        x = spcreator([1, 0, 7, 0, 0, 0, 0, -3, 0, 0, 0, 5])
+        y = x.reshape((4, 3))
+        desired = [[1, 0, 7], [0, 0, 0], [0, -3, 0], [0, 0, 5]]
+        assert_equal(y.toarray(), desired)
+
+        y = x.reshape((12,))
+        assert y is x
+
+        y = x.reshape(12)
+        assert_equal(y.toarray(), x.toarray())
+
+    def test_sum(self, spcreator):
+        np.random.seed(1234)
+        dat_1 = np.array([0, 1, 2, 3, -4, 5, -6, 7, 9])
+        dat_2 = np.random.rand(5)
+        dat_3 = np.array([])
+        dat_4 = np.zeros((40,))
+        arrays = [dat_1, dat_2, dat_3, dat_4]
+
+        for dat in arrays:
+            datsp = spcreator(dat)
+            with np.errstate(over='ignore'):
+                assert np.isscalar(datsp.sum())
+                assert_allclose(dat.sum(), datsp.sum())
+                assert_allclose(dat.sum(axis=None), datsp.sum(axis=None))
+                assert_allclose(dat.sum(axis=0), datsp.sum(axis=0))
+                assert_allclose(dat.sum(axis=-1), datsp.sum(axis=-1))
+
+        # test `out` parameter
+        datsp.sum(axis=0, out=np.zeros(()))
+
+    def test_sum_invalid_params(self, spcreator):
+        out = np.zeros((3,))  # wrong size for out
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        with pytest.raises(ValueError, match='axis must be None, -1 or 0'):
+            datsp.sum(axis=1)
+        with pytest.raises(TypeError, match='Tuples are not accepted'):
+            datsp.sum(axis=(0, 1))
+        with pytest.raises(TypeError, match='axis must be an integer'):
+            datsp.sum(axis=1.5)
+        with pytest.raises(ValueError, match='output parameter.*wrong.*dimension'):
+            datsp.sum(axis=0, out=out)
+
+    def test_numpy_sum(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        dat_sum = np.sum(dat)
+        datsp_sum = np.sum(datsp)
+
+        assert_allclose(dat_sum, datsp_sum)
+
+    def test_mean(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        assert_allclose(dat.mean(), datsp.mean())
+        assert np.isscalar(datsp.mean(axis=None))
+        assert_allclose(dat.mean(axis=None), datsp.mean(axis=None))
+        assert_allclose(dat.mean(axis=0), datsp.mean(axis=0))
+        assert_allclose(dat.mean(axis=-1), datsp.mean(axis=-1))
+
+        with pytest.raises(ValueError, match='axis'):
+            datsp.mean(axis=1)
+        with pytest.raises(ValueError, match='axis'):
+            datsp.mean(axis=-2)
+
+    def test_mean_invalid_params(self, spcreator):
+        out = np.asarray(np.zeros((1, 3)))
+        dat = np.array([[0, 1, 2], [3, -4, 5], [-6, 7, 9]])
+
+        datsp = spcreator(dat)
+        with pytest.raises(ValueError, match='axis out of range'):
+            datsp.mean(axis=3)
+        with pytest.raises(TypeError, match='Tuples are not accepted'):
+            datsp.mean(axis=(0, 1))
+        with pytest.raises(TypeError, match='axis must be an integer'):
+            datsp.mean(axis=1.5)
+        with pytest.raises(ValueError, match='output parameter.*wrong.*dimension'):
+            datsp.mean(axis=1, out=out)
+
+    def test_sum_dtype(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        for dtype in supported_dtypes:
+            dat_sum = dat.sum(dtype=dtype)
+            datsp_sum = datsp.sum(dtype=dtype)
+
+            assert_allclose(dat_sum, datsp_sum)
+            assert_equal(dat_sum.dtype, datsp_sum.dtype)
+
+    def test_mean_dtype(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        for dtype in supported_dtypes:
+            dat_mean = dat.mean(dtype=dtype)
+            datsp_mean = datsp.mean(dtype=dtype)
+
+            assert_allclose(dat_mean, datsp_mean)
+            assert_equal(dat_mean.dtype, datsp_mean.dtype)
+
+    def test_mean_out(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        dat_out = np.array(0)
+        datsp_out = np.array(0)
+
+        dat.mean(out=dat_out)
+        datsp.mean(out=datsp_out)
+        assert_allclose(dat_out, datsp_out)
+
+        dat.mean(axis=0, out=dat_out)
+        datsp.mean(axis=0, out=datsp_out)
+        assert_allclose(dat_out, datsp_out)
+
+        with pytest.raises(ValueError, match="output parameter.*dimension"):
+            datsp.mean(out=np.array([0]))
+        with pytest.raises(ValueError, match="output parameter.*dimension"):
+            datsp.mean(out=np.array([[0]]))
+
+    def test_numpy_mean(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+
+        dat_mean = np.mean(dat)
+        datsp_mean = np.mean(datsp)
+
+        assert_allclose(dat_mean, datsp_mean)
+        assert_equal(dat_mean.dtype, datsp_mean.dtype)
+
+    @pytest.mark.thread_unsafe
+    @sup_complex
+    def test_from_array(self, spcreator):
+        A = np.array([2, 3, 4])
+        assert_equal(spcreator(A).toarray(), A)
+
+        A = np.array([1.0 + 3j, 0, -1])
+        assert_equal(spcreator(A).toarray(), A)
+        assert_equal(spcreator(A, dtype='int16').toarray(), A.astype('int16'))
+
+    @pytest.mark.thread_unsafe
+    @sup_complex
+    def test_from_list(self, spcreator):
+        A = [2, 3, 4]
+        assert_equal(spcreator(A).toarray(), A)
+
+        A = [1.0 + 3j, 0, -1]
+        assert_equal(spcreator(A).toarray(), np.array(A))
+        assert_equal(
+            spcreator(A, dtype='int16').toarray(), np.array(A).astype('int16')
+        )
+
+    @pytest.mark.thread_unsafe
+    @sup_complex
+    def test_from_sparse(self, spcreator):
+        D = np.array([1, 0, 0])
+        S = coo_array(D)
+        assert_equal(spcreator(S).toarray(), D)
+        S = spcreator(D)
+        assert_equal(spcreator(S).toarray(), D)
+
+        D = np.array([1.0 + 3j, 0, -1])
+        S = coo_array(D)
+        assert_equal(spcreator(S).toarray(), D)
+        assert_equal(spcreator(S, dtype='int16').toarray(), D.astype('int16'))
+        S = spcreator(D)
+        assert_equal(spcreator(S).toarray(), D)
+        assert_equal(spcreator(S, dtype='int16').toarray(), D.astype('int16'))
+
+    def test_toarray(self, spcreator, dat1d):
+        datsp = spcreator(dat1d)
+        # Check C- or F-contiguous (default).
+        chk = datsp.toarray()
+        assert_equal(chk, dat1d)
+        assert chk.flags.c_contiguous == chk.flags.f_contiguous
+
+        # Check C-contiguous (with arg).
+        chk = datsp.toarray(order='C')
+        assert_equal(chk, dat1d)
+        assert chk.flags.c_contiguous
+        assert chk.flags.f_contiguous
+
+        # Check F-contiguous (with arg).
+        chk = datsp.toarray(order='F')
+        assert_equal(chk, dat1d)
+        assert chk.flags.c_contiguous
+        assert chk.flags.f_contiguous
+
+        # Check with output arg.
+        out = np.zeros(datsp.shape, dtype=datsp.dtype)
+        datsp.toarray(out=out)
+        assert_equal(out, dat1d)
+
+        # Check that things are fine when we don't initialize with zeros.
+        out[...] = 1.0
+        datsp.toarray(out=out)
+        assert_equal(out, dat1d)
+
+        # np.dot does not work with sparse matrices (unless scalars)
+        # so this is testing whether dat1d matches datsp.toarray()
+        a = np.array([1.0, 2.0, 3.0, 4.0])
+        dense_dot_dense = np.dot(a, dat1d)
+        check = np.dot(a, datsp.toarray())
+        assert_equal(dense_dot_dense, check)
+
+        b = np.array([1.0, 2.0, 3.0, 4.0])
+        dense_dot_dense = np.dot(dat1d, b)
+        check = np.dot(datsp.toarray(), b)
+        assert_equal(dense_dot_dense, check)
+
+        # Check bool data works.
+        spbool = spcreator(dat1d, dtype=bool)
+        arrbool = dat1d.astype(bool)
+        assert_equal(spbool.toarray(), arrbool)
+
+    def test_add(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            a = dat.copy()
+            a[0] = 2.0
+            b = datsp
+            c = b + a
+            assert_equal(c, b.toarray() + a)
+
+            # test broadcasting
+            # Note: cant add nonzero scalar to sparray. Can add len 1 array
+            c = b + a[0:1]
+            assert_equal(c, b.toarray() + a[0])
+
+    def test_radd(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            a = dat.copy()
+            a[0] = 2.0
+            b = datsp
+            c = a + b
+            assert_equal(c, a + b.toarray())
+
+    def test_rsub(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            if dtype == np.dtype('bool'):
+                # boolean array subtraction deprecated in 1.9.0
+                continue
+
+            assert_equal((dat - datsp), [0, 0, 0, 0])
+            assert_equal((datsp - dat), [0, 0, 0, 0])
+            assert_equal((0 - datsp).toarray(), -dat)
+
+            A = spcreator([1, -4, 0, 2], dtype='d')
+            assert_equal((dat - A), dat - A.toarray())
+            assert_equal((A - dat), A.toarray() - dat)
+            assert_equal(A.toarray() - datsp, A.toarray() - dat)
+            assert_equal(datsp - A.toarray(), dat - A.toarray())
+
+            # test broadcasting
+            assert_equal(dat[:1] - datsp, dat[:1] - dat)
+
+    def test_matmul_basic(self, spcreator):
+        A = np.array([[2, 0, 3.0], [0, 0, 0], [0, 1, 2]])
+        v = np.array([1, 0, 3])
+        Asp = spcreator(A)
+        vsp = spcreator(v)
+
+        # sparse result when both args are sparse and result not scalar
+        assert_equal((Asp @ vsp).toarray(), A @ v)
+        assert_equal(A @ vsp, A @ v)
+        assert_equal(Asp @ v, A @ v)
+        assert_equal((vsp @ Asp).toarray(), v @ A)
+        assert_equal(vsp @ A, v @ A)
+        assert_equal(v @ Asp, v @ A)
+
+        assert_equal(vsp @ vsp, v @ v)
+        assert_equal(v @ vsp, v @ v)
+        assert_equal(vsp @ v, v @ v)
+        assert_equal((Asp @ Asp).toarray(), A @ A)
+        assert_equal(A @ Asp, A @ A)
+        assert_equal(Asp @ A, A @ A)
+
+    def test_matvec(self, spcreator):
+        A = np.array([2, 0, 3.0])
+        Asp = spcreator(A)
+        col = np.array([[1, 2, 3]]).T
+
+        assert_allclose(Asp @ col, Asp.toarray() @ col)
+
+        assert (A @ np.array([1, 2, 3])).shape == ()
+        assert Asp @ np.array([1, 2, 3]) == 11
+        assert (Asp @ np.array([1, 2, 3])).shape == ()
+        assert (Asp @ np.array([[1], [2], [3]])).shape == (1,)
+        # check result type
+        assert isinstance(Asp @ matrix([[1, 2, 3]]).T, np.ndarray)
+
+        # ensure exception is raised for improper dimensions
+        bad_vecs = [np.array([1, 2]), np.array([1, 2, 3, 4]), np.array([[1], [2]])]
+        for x in bad_vecs:
+            with pytest.raises(ValueError, match='dimension mismatch'):
+                Asp @ x
+
+        # The current relationship between sparse matrix products and array
+        # products is as follows:
+        dot_result = np.dot(Asp.toarray(), [1, 2, 3])
+        assert_allclose(Asp @ np.array([1, 2, 3]), dot_result)
+        assert_allclose(Asp @ [[1], [2], [3]], dot_result.T)
+        # Note that the result of Asp @ x is dense if x has a singleton dimension.
+
+    def test_rmatvec(self, spcreator, dat1d):
+        M = spcreator(dat1d)
+        assert_allclose([1, 2, 3, 4] @ M, np.dot([1, 2, 3, 4], M.toarray()))
+        row = np.array([[1, 2, 3, 4]])
+        assert_allclose(row @ M, row @ M.toarray())
+
+    def test_transpose(self, spcreator, dat1d):
+        for A in [dat1d, np.array([])]:
+            B = spcreator(A)
+            assert_equal(B.toarray(), A)
+            assert_equal(B.transpose().toarray(), A)
+            assert_equal(B.dtype, A.dtype)
+
+    def test_add_dense_to_sparse(self, spcreator, datsp_math_dtypes):
+        for dtype, dat, datsp in datsp_math_dtypes[spcreator]:
+            sum1 = dat + datsp
+            assert_equal(sum1, dat + dat)
+            sum2 = datsp + dat
+            assert_equal(sum2, dat + dat)
+
+    def test_iterator(self, spcreator):
+        # test that __iter__ is compatible with NumPy
+        B = np.arange(5)
+        A = spcreator(B)
+
+        if A.format not in ['coo', 'dia', 'bsr']:
+            for x, y in zip(A, B):
+                assert_equal(x, y)
+
+    def test_resize(self, spcreator):
+        # resize(shape) resizes the matrix in-place
+        D = np.array([1, 0, 3, 4])
+        S = spcreator(D)
+        assert S.resize((3,)) is None
+        assert_equal(S.toarray(), [1, 0, 3])
+        S.resize((5,))
+        assert_equal(S.toarray(), [1, 0, 3, 0, 0])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py
new file mode 100644
index 0000000000000000000000000000000000000000..38b8288c39f4ebacd9cadc58bba7b18416377c73
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_construct.py
@@ -0,0 +1,872 @@
+"""test sparse matrix construction functions"""
+
+import numpy as np
+from numpy import array
+from numpy.testing import (assert_equal, assert_,
+        assert_array_equal, assert_array_almost_equal_nulp)
+import pytest
+from pytest import raises as assert_raises
+from scipy._lib._testutils import check_free_memory
+
+from scipy.sparse import (csr_matrix, coo_matrix,
+                          csr_array, coo_array,
+                          csc_array, bsr_array,
+                          dia_array, dok_array,
+                          lil_array, csc_matrix,
+                          bsr_matrix, dia_matrix,
+                          lil_matrix, sparray, spmatrix,
+                          _construct as construct)
+from scipy.sparse._construct import rand as sprand
+
+sparse_formats = ['csr','csc','coo','bsr','dia','lil','dok']
+
+#TODO check whether format=XXX is respected
+
+
+def _sprandn(m, n, density=0.01, format="coo", dtype=None, rng=None):
+    # Helper function for testing.
+    rng = np.random.default_rng(rng)
+    data_rvs = rng.standard_normal
+    return construct.random(m, n, density, format, dtype, rng, data_rvs)
+
+
+def _sprandn_array(m, n, density=0.01, format="coo", dtype=None, rng=None):
+    # Helper function for testing.
+    rng = np.random.default_rng(rng)
+    data_sampler = rng.standard_normal
+    return construct.random_array((m, n), density=density, format=format, dtype=dtype,
+                                  rng=rng, data_sampler=data_sampler)
+
+
+class TestConstructUtils:
+
+    @pytest.mark.parametrize("cls", [
+        csc_array, csr_array, coo_array, bsr_array,
+        dia_array, dok_array, lil_array
+    ])
+    def test_singleton_array_constructor(self, cls):
+        with pytest.raises(
+            ValueError,
+            match=(
+                'scipy sparse array classes do not support '
+                'instantiation from a scalar'
+            )
+        ):
+            cls(0)
+
+    @pytest.mark.parametrize("cls", [
+        csc_matrix, csr_matrix, coo_matrix,
+        bsr_matrix, dia_matrix, lil_matrix
+    ])
+    def test_singleton_matrix_constructor(self, cls):
+        """
+        This test is for backwards compatibility post scipy 1.13.
+        The behavior observed here is what is to be expected
+        with the older matrix classes. This test comes with the
+        exception of dok_matrix, which was not working pre scipy1.12
+        (unlike the rest of these).
+        """
+        assert cls(0).shape == (1, 1)
+
+    def test_spdiags(self):
+        diags1 = array([[1, 2, 3, 4, 5]])
+        diags2 = array([[1, 2, 3, 4, 5],
+                         [6, 7, 8, 9,10]])
+        diags3 = array([[1, 2, 3, 4, 5],
+                         [6, 7, 8, 9,10],
+                         [11,12,13,14,15]])
+
+        cases = []
+        cases.append((diags1, 0, 1, 1, [[1]]))
+        cases.append((diags1, [0], 1, 1, [[1]]))
+        cases.append((diags1, [0], 2, 1, [[1],[0]]))
+        cases.append((diags1, [0], 1, 2, [[1,0]]))
+        cases.append((diags1, [1], 1, 2, [[0,2]]))
+        cases.append((diags1,[-1], 1, 2, [[0,0]]))
+        cases.append((diags1, [0], 2, 2, [[1,0],[0,2]]))
+        cases.append((diags1,[-1], 2, 2, [[0,0],[1,0]]))
+        cases.append((diags1, [3], 2, 2, [[0,0],[0,0]]))
+        cases.append((diags1, [0], 3, 4, [[1,0,0,0],[0,2,0,0],[0,0,3,0]]))
+        cases.append((diags1, [1], 3, 4, [[0,2,0,0],[0,0,3,0],[0,0,0,4]]))
+        cases.append((diags1, [2], 3, 5, [[0,0,3,0,0],[0,0,0,4,0],[0,0,0,0,5]]))
+
+        cases.append((diags2, [0,2], 3, 3, [[1,0,8],[0,2,0],[0,0,3]]))
+        cases.append((diags2, [-1,0], 3, 4, [[6,0,0,0],[1,7,0,0],[0,2,8,0]]))
+        cases.append((diags2, [2,-3], 6, 6, [[0,0,3,0,0,0],
+                                              [0,0,0,4,0,0],
+                                              [0,0,0,0,5,0],
+                                              [6,0,0,0,0,0],
+                                              [0,7,0,0,0,0],
+                                              [0,0,8,0,0,0]]))
+
+        cases.append((diags3, [-1,0,1], 6, 6, [[6,12, 0, 0, 0, 0],
+                                                [1, 7,13, 0, 0, 0],
+                                                [0, 2, 8,14, 0, 0],
+                                                [0, 0, 3, 9,15, 0],
+                                                [0, 0, 0, 4,10, 0],
+                                                [0, 0, 0, 0, 5, 0]]))
+        cases.append((diags3, [-4,2,-1], 6, 5, [[0, 0, 8, 0, 0],
+                                                 [11, 0, 0, 9, 0],
+                                                 [0,12, 0, 0,10],
+                                                 [0, 0,13, 0, 0],
+                                                 [1, 0, 0,14, 0],
+                                                 [0, 2, 0, 0,15]]))
+        cases.append((diags3, [-1, 1, 2], len(diags3[0]), len(diags3[0]),
+                      [[0, 7, 13, 0, 0],
+                       [1, 0, 8, 14, 0],
+                       [0, 2, 0, 9, 15],
+                       [0, 0, 3, 0, 10],
+                       [0, 0, 0, 4, 0]]))
+
+        for d, o, m, n, result in cases:
+            if len(d[0]) == m and m == n:
+                assert_equal(construct.spdiags(d, o).toarray(), result)
+            assert_equal(construct.spdiags(d, o, m, n).toarray(), result)
+            assert_equal(construct.spdiags(d, o, (m, n)).toarray(), result)
+
+    def test_diags(self):
+        a = array([1, 2, 3, 4, 5])
+        b = array([6, 7, 8, 9, 10])
+        c = array([11, 12, 13, 14, 15])
+
+        cases = []
+        cases.append((a[:1], 0, (1, 1), [[1]]))
+        cases.append(([a[:1]], [0], (1, 1), [[1]]))
+        cases.append(([a[:1]], [0], (2, 1), [[1],[0]]))
+        cases.append(([a[:1]], [0], (1, 2), [[1,0]]))
+        cases.append(([a[:1]], [1], (1, 2), [[0,1]]))
+        cases.append(([a[:2]], [0], (2, 2), [[1,0],[0,2]]))
+        cases.append(([a[:1]],[-1], (2, 2), [[0,0],[1,0]]))
+        cases.append(([a[:3]], [0], (3, 4), [[1,0,0,0],[0,2,0,0],[0,0,3,0]]))
+        cases.append(([a[:3]], [1], (3, 4), [[0,1,0,0],[0,0,2,0],[0,0,0,3]]))
+        cases.append(([a[:1]], [-2], (3, 5), [[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0]]))
+        cases.append(([a[:2]], [-1], (3, 5), [[0,0,0,0,0],[1,0,0,0,0],[0,2,0,0,0]]))
+        cases.append(([a[:3]], [0], (3, 5), [[1,0,0,0,0],[0,2,0,0,0],[0,0,3,0,0]]))
+        cases.append(([a[:3]], [1], (3, 5), [[0,1,0,0,0],[0,0,2,0,0],[0,0,0,3,0]]))
+        cases.append(([a[:3]], [2], (3, 5), [[0,0,1,0,0],[0,0,0,2,0],[0,0,0,0,3]]))
+        cases.append(([a[:2]], [3], (3, 5), [[0,0,0,1,0],[0,0,0,0,2],[0,0,0,0,0]]))
+        cases.append(([a[:1]], [4], (3, 5), [[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0]]))
+        cases.append(([a[:1]], [-4], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[1,0,0]]))
+        cases.append(([a[:2]], [-3], (5, 3), [[0,0,0],[0,0,0],[0,0,0],[1,0,0],[0,2,0]]))
+        cases.append(([a[:3]], [-2], (5, 3), [[0,0,0],[0,0,0],[1,0,0],[0,2,0],[0,0,3]]))
+        cases.append(([a[:3]], [-1], (5, 3), [[0,0,0],[1,0,0],[0,2,0],[0,0,3],[0,0,0]]))
+        cases.append(([a[:3]], [0], (5, 3), [[1,0,0],[0,2,0],[0,0,3],[0,0,0],[0,0,0]]))
+        cases.append(([a[:2]], [1], (5, 3), [[0,1,0],[0,0,2],[0,0,0],[0,0,0],[0,0,0]]))
+        cases.append(([a[:1]], [2], (5, 3), [[0,0,1],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]))
+
+        cases.append(([a[:3],b[:1]], [0,2], (3, 3), [[1,0,6],[0,2,0],[0,0,3]]))
+        cases.append(([a[:2],b[:3]], [-1,0], (3, 4), [[6,0,0,0],[1,7,0,0],[0,2,8,0]]))
+        cases.append(([a[:4],b[:3]], [2,-3], (6, 6), [[0,0,1,0,0,0],
+                                                     [0,0,0,2,0,0],
+                                                     [0,0,0,0,3,0],
+                                                     [6,0,0,0,0,4],
+                                                     [0,7,0,0,0,0],
+                                                     [0,0,8,0,0,0]]))
+
+        cases.append(([a[:4],b,c[:4]], [-1,0,1], (5, 5), [[6,11, 0, 0, 0],
+                                                            [1, 7,12, 0, 0],
+                                                            [0, 2, 8,13, 0],
+                                                            [0, 0, 3, 9,14],
+                                                            [0, 0, 0, 4,10]]))
+        cases.append(([a[:2],b[:3],c], [-4,2,-1], (6, 5), [[0, 0, 6, 0, 0],
+                                                          [11, 0, 0, 7, 0],
+                                                          [0,12, 0, 0, 8],
+                                                          [0, 0,13, 0, 0],
+                                                          [1, 0, 0,14, 0],
+                                                          [0, 2, 0, 0,15]]))
+
+        # too long arrays are OK
+        cases.append(([a], [0], (1, 1), [[1]]))
+        cases.append(([a[:3],b], [0,2], (3, 3), [[1, 0, 6], [0, 2, 0], [0, 0, 3]]))
+        cases.append((
+            np.array([[1, 2, 3], [4, 5, 6]]),
+            [0,-1],
+            (3, 3),
+            [[1, 0, 0], [4, 2, 0], [0, 5, 3]]
+        ))
+
+        # scalar case: broadcasting
+        cases.append(([1,-2,1], [1,0,-1], (3, 3), [[-2, 1, 0],
+                                                    [1, -2, 1],
+                                                    [0, 1, -2]]))
+
+        for d, o, shape, result in cases:
+            err_msg = f"{d!r} {o!r} {shape!r} {result!r}"
+            assert_equal(construct.diags(d, offsets=o, shape=shape).toarray(),
+                         result, err_msg=err_msg)
+
+            if (shape[0] == shape[1]
+                and hasattr(d[0], '__len__')
+                and len(d[0]) <= max(shape)):
+                # should be able to find the shape automatically
+                assert_equal(construct.diags(d, offsets=o).toarray(), result,
+                             err_msg=err_msg)
+
+    def test_diags_default(self):
+        a = array([1, 2, 3, 4, 5])
+        assert_equal(construct.diags(a).toarray(), np.diag(a))
+
+    def test_diags_default_bad(self):
+        a = array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]])
+        assert_raises(ValueError, construct.diags, a)
+
+    def test_diags_bad(self):
+        a = array([1, 2, 3, 4, 5])
+        b = array([6, 7, 8, 9, 10])
+        c = array([11, 12, 13, 14, 15])
+
+        cases = []
+        cases.append(([a[:0]], 0, (1, 1)))
+        cases.append(([a[:4],b,c[:3]], [-1,0,1], (5, 5)))
+        cases.append(([a[:2],c,b[:3]], [-4,2,-1], (6, 5)))
+        cases.append(([a[:2],c,b[:3]], [-4,2,-1], None))
+        cases.append(([], [-4,2,-1], None))
+        cases.append(([1], [-5], (4, 4)))
+        cases.append(([a], 0, None))
+
+        for d, o, shape in cases:
+            assert_raises(ValueError, construct.diags, d, offsets=o, shape=shape)
+
+        assert_raises(TypeError, construct.diags, [[None]], offsets=[0])
+
+    def test_diags_vs_diag(self):
+        # Check that
+        #
+        #    diags([a, b, ...], [i, j, ...]) == diag(a, i) + diag(b, j) + ...
+        #
+
+        rng = np.random.RandomState(1234)
+
+        for n_diags in [1, 2, 3, 4, 5, 10]:
+            n = 1 + n_diags//2 + rng.randint(0, 10)
+
+            offsets = np.arange(-n+1, n-1)
+            rng.shuffle(offsets)
+            offsets = offsets[:n_diags]
+
+            diagonals = [rng.rand(n - abs(q)) for q in offsets]
+
+            mat = construct.diags(diagonals, offsets=offsets)
+            dense_mat = sum([np.diag(x, j) for x, j in zip(diagonals, offsets)])
+
+            assert_array_almost_equal_nulp(mat.toarray(), dense_mat)
+
+            if len(offsets) == 1:
+                mat = construct.diags(diagonals[0], offsets=offsets[0])
+                dense_mat = np.diag(diagonals[0], offsets[0])
+                assert_array_almost_equal_nulp(mat.toarray(), dense_mat)
+
+    def test_diags_dtype(self):
+        x = construct.diags([2.2], offsets=[0], shape=(2, 2), dtype=int)
+        assert_equal(x.dtype, int)
+        assert_equal(x.toarray(), [[2, 0], [0, 2]])
+
+    def test_diags_one_diagonal(self):
+        d = list(range(5))
+        for k in range(-5, 6):
+            assert_equal(construct.diags(d, offsets=k).toarray(),
+                         construct.diags([d], offsets=[k]).toarray())
+
+    def test_diags_empty(self):
+        x = construct.diags([])
+        assert_equal(x.shape, (0, 0))
+
+    @pytest.mark.parametrize("identity", [construct.identity, construct.eye_array])
+    def test_identity(self, identity):
+        assert_equal(identity(1).toarray(), [[1]])
+        assert_equal(identity(2).toarray(), [[1,0],[0,1]])
+
+        I = identity(3, dtype='int8', format='dia')
+        assert_equal(I.dtype, np.dtype('int8'))
+        assert_equal(I.format, 'dia')
+
+        for fmt in sparse_formats:
+            I = identity(3, format=fmt)
+            assert_equal(I.format, fmt)
+            assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]])
+
+    @pytest.mark.parametrize("eye", [construct.eye, construct.eye_array])
+    def test_eye(self, eye):
+        assert_equal(eye(1,1).toarray(), [[1]])
+        assert_equal(eye(2,3).toarray(), [[1,0,0],[0,1,0]])
+        assert_equal(eye(3,2).toarray(), [[1,0],[0,1],[0,0]])
+        assert_equal(eye(3,3).toarray(), [[1,0,0],[0,1,0],[0,0,1]])
+
+        assert_equal(eye(3,3,dtype='int16').dtype, np.dtype('int16'))
+
+        for m in [3, 5]:
+            for n in [3, 5]:
+                for k in range(-5,6):
+                    # scipy.sparse.eye deviates from np.eye here. np.eye will
+                    # create arrays of all 0's when the diagonal offset is
+                    # greater than the size of the array. For sparse arrays
+                    # this makes less sense, especially as it results in dia
+                    # arrays with negative diagonals. Therefore sp.sparse.eye
+                    # validates that diagonal offsets fall within the shape of
+                    # the array. See gh-18555.
+                    if (k > 0 and k > n) or (k < 0 and abs(k) > m):
+                        with pytest.raises(
+                            ValueError, match="Offset.*out of bounds"
+                        ):
+                            eye(m, n, k=k)
+
+                    else:
+                        assert_equal(
+                            eye(m, n, k=k).toarray(),
+                            np.eye(m, n, k=k)
+                        )
+                        if m == n:
+                            assert_equal(
+                                eye(m, k=k).toarray(),
+                                np.eye(m, n, k=k)
+                            )
+
+    @pytest.mark.parametrize("eye", [construct.eye, construct.eye_array])
+    def test_eye_one(self, eye):
+        assert_equal(eye(1).toarray(), [[1]])
+        assert_equal(eye(2).toarray(), [[1,0],[0,1]])
+
+        I = eye(3, dtype='int8', format='dia')
+        assert_equal(I.dtype, np.dtype('int8'))
+        assert_equal(I.format, 'dia')
+
+        for fmt in sparse_formats:
+            I = eye(3, format=fmt)
+            assert_equal(I.format, fmt)
+            assert_equal(I.toarray(), [[1,0,0],[0,1,0],[0,0,1]])
+
+    def test_eye_array_vs_matrix(self):
+        assert isinstance(construct.eye_array(3), sparray)
+        assert not isinstance(construct.eye(3), sparray)
+
+    def test_kron(self):
+        cases = []
+
+        cases.append(array([[0]]))
+        cases.append(array([[-1]]))
+        cases.append(array([[4]]))
+        cases.append(array([[10]]))
+        cases.append(array([[0],[0]]))
+        cases.append(array([[0,0]]))
+        cases.append(array([[1,2],[3,4]]))
+        cases.append(array([[0,2],[5,0]]))
+        cases.append(array([[0,2,-6],[8,0,14]]))
+        cases.append(array([[5,4],[0,0],[6,0]]))
+        cases.append(array([[5,4,4],[1,0,0],[6,0,8]]))
+        cases.append(array([[0,1,0,2,0,5,8]]))
+        cases.append(array([[0.5,0.125,0,3.25],[0,2.5,0,0]]))
+
+        # test all cases with some formats
+        for a in cases:
+            ca = csr_array(a)
+            for b in cases:
+                cb = csr_array(b)
+                expected = np.kron(a, b)
+                for fmt in sparse_formats[1:4]:
+                    result = construct.kron(ca, cb, format=fmt)
+                    assert_equal(result.format, fmt)
+                    assert_array_equal(result.toarray(), expected)
+                    assert isinstance(result, sparray)
+
+        # test one case with all formats
+        a = cases[-1]
+        b = cases[-3]
+        ca = csr_array(a)
+        cb = csr_array(b)
+
+        expected = np.kron(a, b)
+        for fmt in sparse_formats:
+            result = construct.kron(ca, cb, format=fmt)
+            assert_equal(result.format, fmt)
+            assert_array_equal(result.toarray(), expected)
+            assert isinstance(result, sparray)
+
+        # check that spmatrix returned when both inputs are spmatrix
+        result = construct.kron(csr_matrix(a), csr_matrix(b), format=fmt)
+        assert_equal(result.format, fmt)
+        assert_array_equal(result.toarray(), expected)
+        assert isinstance(result, spmatrix)
+
+    def test_kron_ndim_exceptions(self):
+        with pytest.raises(ValueError, match='requires 2D input'):
+            construct.kron([[0], [1]], csr_array([0, 1]))
+        with pytest.raises(ValueError, match='requires 2D input'):
+            construct.kron(csr_array([0, 1]), [[0], [1]])
+        # no exception if sparse arrays are not input (spmatrix inferred)
+        construct.kron([[0], [1]], [0, 1])
+
+    def test_kron_large(self):
+        n = 2**16
+        a = construct.diags_array([1], shape=(1, n), offsets=n-1)
+        b = construct.diags_array([1], shape=(n, 1), offsets=1-n)
+
+        construct.kron(a, a)
+        construct.kron(b, b)
+
+    def test_kronsum(self):
+        cases = []
+
+        cases.append(array([[0]]))
+        cases.append(array([[-1]]))
+        cases.append(array([[4]]))
+        cases.append(array([[10]]))
+        cases.append(array([[1,2],[3,4]]))
+        cases.append(array([[0,2],[5,0]]))
+        cases.append(array([[0,2,-6],[8,0,14],[0,3,0]]))
+        cases.append(array([[1,0,0],[0,5,-1],[4,-2,8]]))
+
+        # test all cases with default format
+        for a in cases:
+            for b in cases:
+                result = construct.kronsum(csr_array(a), csr_array(b)).toarray()
+                expected = (np.kron(np.eye(b.shape[0]), a)
+                            + np.kron(b, np.eye(a.shape[0])))
+                assert_array_equal(result, expected)
+
+        # check that spmatrix returned when both inputs are spmatrix
+        result = construct.kronsum(csr_matrix(a), csr_matrix(b)).toarray()
+        assert_array_equal(result, expected)
+
+    def test_kronsum_ndim_exceptions(self):
+        with pytest.raises(ValueError, match='requires 2D input'):
+            construct.kronsum([[0], [1]], csr_array([0, 1]))
+        with pytest.raises(ValueError, match='requires 2D input'):
+            construct.kronsum(csr_array([0, 1]), [[0], [1]])
+        # no exception if sparse arrays are not input (spmatrix inferred)
+        construct.kronsum([[0, 1], [1, 0]], [2])
+
+    @pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array])
+    def test_vstack(self, coo_cls):
+        A = coo_cls([[1,2],[3,4]])
+        B = coo_cls([[5,6]])
+
+        expected = array([[1, 2],
+                          [3, 4],
+                          [5, 6]])
+        assert_equal(construct.vstack([A, B]).toarray(), expected)
+        assert_equal(construct.vstack([A, B], dtype=np.float32).dtype,
+                     np.float32)
+
+        assert_equal(construct.vstack([A.todok(), B.todok()]).toarray(), expected)
+
+        assert_equal(construct.vstack([A.tocsr(), B.tocsr()]).toarray(),
+                     expected)
+        result = construct.vstack([A.tocsr(), B.tocsr()],
+                                  format="csr", dtype=np.float32)
+        assert_equal(result.dtype, np.float32)
+        assert_equal(result.indices.dtype, np.int32)
+        assert_equal(result.indptr.dtype, np.int32)
+
+        assert_equal(construct.vstack([A.tocsc(), B.tocsc()]).toarray(),
+                     expected)
+        result = construct.vstack([A.tocsc(), B.tocsc()],
+                                  format="csc", dtype=np.float32)
+        assert_equal(result.dtype, np.float32)
+        assert_equal(result.indices.dtype, np.int32)
+        assert_equal(result.indptr.dtype, np.int32)
+
+    def test_vstack_maintain64bit_idx_dtype(self):
+        # see gh-20389 v/hstack returns int32 idx_dtype with input int64 idx_dtype
+        X = csr_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]])
+        X.indptr = X.indptr.astype(np.int64)
+        X.indices = X.indices.astype(np.int64)
+        assert construct.vstack([X, X]).indptr.dtype == np.int64
+        assert construct.hstack([X, X]).indptr.dtype == np.int64
+
+        X = csc_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]])
+        X.indptr = X.indptr.astype(np.int64)
+        X.indices = X.indices.astype(np.int64)
+        assert construct.vstack([X, X]).indptr.dtype == np.int64
+        assert construct.hstack([X, X]).indptr.dtype == np.int64
+
+        X = coo_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]])
+        X.coords = tuple(co.astype(np.int64) for co in X.coords)
+        assert construct.vstack([X, X]).coords[0].dtype == np.int64
+        assert construct.hstack([X, X]).coords[0].dtype == np.int64
+
+    def test_vstack_matrix_or_array(self):
+        A = [[1,2],[3,4]]
+        B = [[5,6]]
+        assert isinstance(construct.vstack([coo_array(A), coo_array(B)]), sparray)
+        assert isinstance(construct.vstack([coo_array(A), coo_matrix(B)]), sparray)
+        assert isinstance(construct.vstack([coo_matrix(A), coo_array(B)]), sparray)
+        assert isinstance(construct.vstack([coo_matrix(A), coo_matrix(B)]), spmatrix)
+
+    def test_vstack_1d_with_2d(self):
+        # fixes gh-21064
+        arr = csr_array([[1, 0, 0], [0, 1, 0]])
+        arr1d = csr_array([1, 0, 0])
+        arr1dcoo = coo_array([1, 0, 0])
+        assert construct.vstack([arr, np.array([0, 0, 0])]).shape == (3, 3)
+        assert construct.hstack([arr1d, np.array([[0]])]).shape == (1, 4)
+        assert construct.hstack([arr1d, arr1d]).shape == (1, 6)
+        assert construct.vstack([arr1d, arr1d]).shape == (2, 3)
+
+        # check csr specialty stacking code like _stack_along_minor_axis
+        assert construct.hstack([arr, arr]).shape == (2, 6)
+        assert construct.hstack([arr1d, arr1d]).shape == (1, 6)
+
+        assert construct.hstack([arr1d, arr1dcoo]).shape == (1, 6)
+        assert construct.vstack([arr, arr1dcoo]).shape == (3, 3)
+        assert construct.vstack([arr1d, arr1dcoo]).shape == (2, 3)
+
+        with pytest.raises(ValueError, match="incompatible row dimensions"):
+            construct.hstack([arr, np.array([0, 0])])
+        with pytest.raises(ValueError, match="incompatible column dimensions"):
+            construct.vstack([arr, np.array([0, 0])])
+
+    @pytest.mark.parametrize("coo_cls", [coo_matrix, coo_array])
+    def test_hstack(self, coo_cls):
+        A = coo_cls([[1,2],[3,4]])
+        B = coo_cls([[5],[6]])
+
+        expected = array([[1, 2, 5],
+                          [3, 4, 6]])
+        assert_equal(construct.hstack([A, B]).toarray(), expected)
+        assert_equal(construct.hstack([A, B], dtype=np.float32).dtype,
+                     np.float32)
+
+        assert_equal(construct.hstack([A.todok(), B.todok()]).toarray(), expected)
+
+        assert_equal(construct.hstack([A.tocsc(), B.tocsc()]).toarray(),
+                     expected)
+        assert_equal(construct.hstack([A.tocsc(), B.tocsc()],
+                                      dtype=np.float32).dtype,
+                     np.float32)
+        assert_equal(construct.hstack([A.tocsr(), B.tocsr()]).toarray(),
+                     expected)
+        assert_equal(construct.hstack([A.tocsr(), B.tocsr()],
+                                      dtype=np.float32).dtype,
+                     np.float32)
+
+    def test_hstack_matrix_or_array(self):
+        A = [[1,2],[3,4]]
+        B = [[5],[6]]
+        assert isinstance(construct.hstack([coo_array(A), coo_array(B)]), sparray)
+        assert isinstance(construct.hstack([coo_array(A), coo_matrix(B)]), sparray)
+        assert isinstance(construct.hstack([coo_matrix(A), coo_array(B)]), sparray)
+        assert isinstance(construct.hstack([coo_matrix(A), coo_matrix(B)]), spmatrix)
+
+    @pytest.mark.parametrize("block_array", (construct.bmat, construct.block_array))
+    def test_block_creation(self, block_array):
+
+        A = coo_array([[1, 2], [3, 4]])
+        B = coo_array([[5],[6]])
+        C = coo_array([[7]])
+        D = coo_array((0, 0))
+
+        expected = array([[1, 2, 5],
+                          [3, 4, 6],
+                          [0, 0, 7]])
+        assert_equal(block_array([[A, B], [None, C]]).toarray(), expected)
+        E = csr_array((1, 2), dtype=np.int32)
+        assert_equal(block_array([[A.tocsr(), B.tocsr()],
+                                  [E, C.tocsr()]]).toarray(),
+                     expected)
+        assert_equal(block_array([[A.tocsc(), B.tocsc()],
+                                  [E.tocsc(), C.tocsc()]]).toarray(),
+                     expected)
+
+        expected = array([[1, 2, 0],
+                          [3, 4, 0],
+                          [0, 0, 7]])
+        assert_equal(block_array([[A, None], [None, C]]).toarray(), expected)
+        assert_equal(block_array([[A.tocsr(), E.T.tocsr()],
+                                  [E, C.tocsr()]]).toarray(),
+                     expected)
+        assert_equal(block_array([[A.tocsc(), E.T.tocsc()],
+                                  [E.tocsc(), C.tocsc()]]).toarray(),
+                     expected)
+
+        Z = csr_array((1, 1), dtype=np.int32)
+        expected = array([[0, 5],
+                          [0, 6],
+                          [7, 0]])
+        assert_equal(block_array([[None, B], [C, None]]).toarray(), expected)
+        assert_equal(block_array([[E.T.tocsr(), B.tocsr()],
+                                  [C.tocsr(), Z]]).toarray(),
+                     expected)
+        assert_equal(block_array([[E.T.tocsc(), B.tocsc()],
+                                  [C.tocsc(), Z.tocsc()]]).toarray(),
+                     expected)
+
+        expected = np.empty((0, 0))
+        assert_equal(block_array([[None, None]]).toarray(), expected)
+        assert_equal(block_array([[None, D], [D, None]]).toarray(),
+                     expected)
+
+        # test bug reported in gh-5976
+        expected = array([[7]])
+        assert_equal(block_array([[None, D], [C, None]]).toarray(),
+                     expected)
+
+        # test failure cases
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A], [B]])
+        excinfo.match(r'Got blocks\[1,0\]\.shape\[1\] == 1, expected 2')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A.tocsr()], [B.tocsr()]])
+        excinfo.match(r'incompatible dimensions for axis 1')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A.tocsc()], [B.tocsc()]])
+        excinfo.match(r'Mismatching dimensions along axis 1: ({1, 2}|{2, 1})')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A, C]])
+        excinfo.match(r'Got blocks\[0,1\]\.shape\[0\] == 1, expected 2')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A.tocsr(), C.tocsr()]])
+        excinfo.match(r'Mismatching dimensions along axis 0: ({1, 2}|{2, 1})')
+
+        with assert_raises(ValueError) as excinfo:
+            block_array([[A.tocsc(), C.tocsc()]])
+        excinfo.match(r'incompatible dimensions for axis 0')
+
+    def test_block_return_type(self):
+        block = construct.block_array
+
+        # csr format ensures we hit _compressed_sparse_stack
+        # shape of F,G ensure we hit _stack_along_minor_axis
+        # list version ensure we hit the path with neither helper function
+        Fl, Gl = [[1, 2],[3, 4]], [[7], [5]]
+        Fm, Gm = csr_matrix(Fl), csr_matrix(Gl)
+        assert isinstance(block([[None, Fl], [Gl, None]], format="csr"), sparray)
+        assert isinstance(block([[None, Fm], [Gm, None]], format="csr"), sparray)
+        assert isinstance(block([[Fm, Gm]], format="csr"), sparray)
+
+    def test_bmat_return_type(self):
+        """This can be removed after sparse matrix is removed"""
+        bmat = construct.bmat
+        # check return type. if any input _is_array output array, else matrix
+        Fl, Gl = [[1, 2],[3, 4]], [[7], [5]]
+        Fm, Gm = csr_matrix(Fl), csr_matrix(Gl)
+        Fa, Ga = csr_array(Fl), csr_array(Gl)
+        assert isinstance(bmat([[Fa, Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Fm, Gm]], format="csr"), spmatrix)
+        assert isinstance(bmat([[None, Fa], [Ga, None]], format="csr"), sparray)
+        assert isinstance(bmat([[None, Fm], [Ga, None]], format="csr"), sparray)
+        assert isinstance(bmat([[None, Fm], [Gm, None]], format="csr"), spmatrix)
+        assert isinstance(bmat([[None, Fl], [Gl, None]], format="csr"), spmatrix)
+
+        # type returned by _compressed_sparse_stack (all csr)
+        assert isinstance(bmat([[Ga, Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Gm, Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Ga, Gm]], format="csr"), sparray)
+        assert isinstance(bmat([[Gm, Gm]], format="csr"), spmatrix)
+        # shape is 2x2 so no _stack_along_minor_axis
+        assert isinstance(bmat([[Fa, Fm]], format="csr"), sparray)
+        assert isinstance(bmat([[Fm, Fm]], format="csr"), spmatrix)
+
+        # type returned by _compressed_sparse_stack (all csc)
+        assert isinstance(bmat([[Gm.tocsc(), Ga.tocsc()]], format="csc"), sparray)
+        assert isinstance(bmat([[Gm.tocsc(), Gm.tocsc()]], format="csc"), spmatrix)
+        # shape is 2x2 so no _stack_along_minor_axis
+        assert isinstance(bmat([[Fa.tocsc(), Fm.tocsc()]], format="csr"), sparray)
+        assert isinstance(bmat([[Fm.tocsc(), Fm.tocsc()]], format="csr"), spmatrix)
+
+        # type returned when mixed input
+        assert isinstance(bmat([[Gl, Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Gm.tocsc(), Ga]], format="csr"), sparray)
+        assert isinstance(bmat([[Gm.tocsc(), Gm]], format="csr"), spmatrix)
+        assert isinstance(bmat([[Gm, Gm]], format="csc"), spmatrix)
+
+    @pytest.mark.slow
+    @pytest.mark.thread_unsafe
+    @pytest.mark.xfail_on_32bit("Can't create large array for test")
+    def test_concatenate_int32_overflow(self):
+        """ test for indptr overflow when concatenating matrices """
+        check_free_memory(30000)
+
+        n = 33000
+        A = csr_array(np.ones((n, n), dtype=bool))
+        B = A.copy()
+        C = construct._compressed_sparse_stack((A, B), axis=0,
+                                               return_spmatrix=False)
+
+        assert_(np.all(np.equal(np.diff(C.indptr), n)))
+        assert_equal(C.indices.dtype, np.int64)
+        assert_equal(C.indptr.dtype, np.int64)
+
+    def test_block_diag_basic(self):
+        """ basic test for block_diag """
+        A = coo_array([[1,2],[3,4]])
+        B = coo_array([[5],[6]])
+        C = coo_array([[7]])
+
+        expected = array([[1, 2, 0, 0],
+                          [3, 4, 0, 0],
+                          [0, 0, 5, 0],
+                          [0, 0, 6, 0],
+                          [0, 0, 0, 7]])
+
+        ABC = construct.block_diag((A, B, C))
+        assert_equal(ABC.toarray(), expected)
+        assert ABC.coords[0].dtype == np.int32
+
+    def test_block_diag_idx_dtype(self):
+        X = coo_array([[1, 0, 0], [0, 1, 0], [0, 1, 0]])
+        X.coords = tuple(co.astype(np.int64) for co in X.coords)
+        assert construct.block_diag([X, X]).coords[0].dtype == np.int64
+
+    def test_block_diag_scalar_1d_args(self):
+        """ block_diag with scalar and 1d arguments """
+        # one 1d matrix and a scalar
+        assert_array_equal(construct.block_diag([[2,3], 4]).toarray(),
+                           [[2, 3, 0], [0, 0, 4]])
+        # 1d sparse arrays
+        A = coo_array([1,0,3])
+        B = coo_array([0,4])
+        assert_array_equal(construct.block_diag([A, B]).toarray(),
+                           [[1, 0, 3, 0, 0], [0, 0, 0, 0, 4]])
+
+    def test_block_diag_1(self):
+        """ block_diag with one matrix """
+        assert_equal(construct.block_diag([[1, 0]]).toarray(),
+                     array([[1, 0]]))
+        assert_equal(construct.block_diag([[[1, 0]]]).toarray(),
+                     array([[1, 0]]))
+        assert_equal(construct.block_diag([[[1], [0]]]).toarray(),
+                     array([[1], [0]]))
+        # just on scalar
+        assert_equal(construct.block_diag([1]).toarray(),
+                     array([[1]]))
+
+    def test_block_diag_sparse_arrays(self):
+        """ block_diag with sparse arrays """
+
+        A = coo_array([[1, 2, 3]], shape=(1, 3))
+        B = coo_array([[4, 5]], shape=(1, 2))
+        assert_equal(construct.block_diag([A, B]).toarray(),
+                     array([[1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]))
+
+        A = coo_array([[1], [2], [3]], shape=(3, 1))
+        B = coo_array([[4], [5]], shape=(2, 1))
+        assert_equal(construct.block_diag([A, B]).toarray(),
+                     array([[1, 0], [2, 0], [3, 0], [0, 4], [0, 5]]))
+
+    def test_block_diag_return_type(self):
+        A, B = coo_array([[1, 2, 3]]), coo_matrix([[2, 3, 4]])
+        assert isinstance(construct.block_diag([A, A]), sparray)
+        assert isinstance(construct.block_diag([A, B]), sparray)
+        assert isinstance(construct.block_diag([B, A]), sparray)
+        assert isinstance(construct.block_diag([B, B]), spmatrix)
+
+    def test_random_sampling(self):
+        # Simple sanity checks for sparse random sampling.
+        for f in sprand, _sprandn:
+            for t in [np.float32, np.float64, np.longdouble,
+                      np.int32, np.int64, np.complex64, np.complex128]:
+                x = f(5, 10, density=0.1, dtype=t)
+                assert_equal(x.dtype, t)
+                assert_equal(x.shape, (5, 10))
+                assert_equal(x.nnz, 5)
+
+            x1 = f(5, 10, density=0.1, rng=4321)
+            assert_equal(x1.dtype, np.float64)
+
+            x2 = f(5, 10, density=0.1, rng=np.random.default_rng(4321))
+
+            assert_array_equal(x1.data, x2.data)
+            assert_array_equal(x1.row, x2.row)
+            assert_array_equal(x1.col, x2.col)
+
+            for density in [0.0, 0.1, 0.5, 1.0]:
+                x = f(5, 10, density=density)
+                assert_equal(x.nnz, int(density * np.prod(x.shape)))
+
+            for fmt in ['coo', 'csc', 'csr', 'lil']:
+                x = f(5, 10, format=fmt)
+                assert_equal(x.format, fmt)
+
+            assert_raises(ValueError, lambda: f(5, 10, 1.1))
+            assert_raises(ValueError, lambda: f(5, 10, -0.1))
+
+    @pytest.mark.parametrize("rng", [None, 4321, np.random.default_rng(4321)])
+    def test_rand(self, rng):
+        # Simple distributional checks for sparse.rand.
+        x = sprand(10, 20, density=0.5, dtype=np.float64, rng=rng)
+        assert_(np.all(np.less_equal(0, x.data)))
+        assert_(np.all(np.less_equal(x.data, 1)))
+
+    @pytest.mark.parametrize("rng", [None, 4321, np.random.default_rng(4321)])
+    def test_randn(self, rng):
+        # Simple distributional checks for sparse.randn.
+        # Statistically, some of these should be negative
+        # and some should be greater than 1.
+        x = _sprandn(10, 20, density=0.5, dtype=np.float64, rng=rng)
+        assert_(np.any(np.less(x.data, 0)))
+        assert_(np.any(np.less(1, x.data)))
+        x = _sprandn_array(10, 20, density=0.5, dtype=np.float64, rng=rng)
+        assert_(np.any(np.less(x.data, 0)))
+        assert_(np.any(np.less(1, x.data)))
+
+    def test_random_accept_str_dtype(self):
+        # anything that np.dtype can convert to a dtype should be accepted
+        # for the dtype
+        construct.random(10, 10, dtype='d')
+        construct.random_array((10, 10), dtype='d')
+        construct.random_array((10, 10, 10), dtype='d')
+        construct.random_array((10, 10, 10, 10, 10), dtype='d')
+
+    def test_random_array_maintains_array_shape(self):
+        # preserve use of old random_state during SPEC 7 transition
+        arr = construct.random_array((0, 4), density=0.3, dtype=int, random_state=0)
+        assert arr.shape == (0, 4)
+
+        arr = construct.random_array((10, 10, 10), density=0.3, dtype=int, rng=0)
+        assert arr.shape == (10, 10, 10)
+
+        arr = construct.random_array((10, 10, 10, 10, 10), density=0.3, dtype=int,
+                                     rng=0)
+        assert arr.shape == (10, 10, 10, 10, 10)
+
+    def test_random_array_idx_dtype(self):
+        A = construct.random_array((10, 10))
+        assert A.coords[0].dtype == np.int32
+
+    def test_random_sparse_matrix_returns_correct_number_of_non_zero_elements(self):
+        # A 10 x 10 matrix, with density of 12.65%, should have 13 nonzero elements.
+        # 10 x 10 x 0.1265 = 12.65, which should be rounded up to 13, not 12.
+        sparse_matrix = construct.random(10, 10, density=0.1265)
+        assert_equal(sparse_matrix.count_nonzero(),13)
+        # check random_array
+        sparse_array = construct.random_array((10, 10), density=0.1265)
+        assert_equal(sparse_array.count_nonzero(),13)
+        assert isinstance(sparse_array, sparray)
+        # check big size
+        shape = (2**33, 2**33)
+        sparse_array = construct.random_array(shape, density=2.7105e-17)
+        assert_equal(sparse_array.count_nonzero(),2000)
+
+        # for n-D
+        # check random_array
+        sparse_array = construct.random_array((10, 10, 10, 10), density=0.12658)
+        assert_equal(sparse_array.count_nonzero(),1266)
+        assert isinstance(sparse_array, sparray)
+        # check big size
+        shape = (2**33, 2**33, 2**33)
+        sparse_array = construct.random_array(shape, density=2.7105e-28)
+        assert_equal(sparse_array.count_nonzero(),172)
+
+
+def test_diags_array():
+    """Tests of diags_array that do not rely on diags wrapper."""
+    diag = np.arange(1, 5)
+
+    assert_array_equal(construct.diags_array(diag).toarray(), np.diag(diag))
+
+    assert_array_equal(
+        construct.diags_array(diag, offsets=2).toarray(), np.diag(diag, k=2)
+    )
+
+    assert_array_equal(
+        construct.diags_array(diag, offsets=2, shape=(4, 4)).toarray(),
+        np.diag(diag, k=2)[:4, :4]
+    )
+
+    # Offset outside bounds when shape specified
+    with pytest.raises(ValueError, match=".*out of bounds"):
+        construct.diags(np.arange(1, 5), 5, shape=(4, 4))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9281748e6fc9ccdcf8aa44d154ada5856bd46a9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_coo.py
@@ -0,0 +1,851 @@
+import numpy as np
+from numpy.testing import assert_equal
+import pytest
+from scipy.linalg import block_diag
+from scipy.sparse import coo_array, random_array
+from .._coo import _block_diag, _extract_block_diag
+
+
+def test_shape_constructor():
+    empty1d = coo_array((3,))
+    assert empty1d.shape == (3,)
+    assert_equal(empty1d.toarray(), np.zeros((3,)))
+
+    empty2d = coo_array((3, 2))
+    assert empty2d.shape == (3, 2)
+    assert_equal(empty2d.toarray(), np.zeros((3, 2)))
+
+    empty_nd = coo_array((2,3,4,6,7))
+    assert empty_nd.shape == (2,3,4,6,7)
+    assert_equal(empty_nd.toarray(), np.zeros((2,3,4,6,7)))
+
+
+def test_dense_constructor():
+    # 1d
+    res1d = coo_array([1, 2, 3])
+    assert res1d.shape == (3,)
+    assert_equal(res1d.toarray(), np.array([1, 2, 3]))
+
+    # 2d
+    res2d = coo_array([[1, 2, 3], [4, 5, 6]])
+    assert res2d.shape == (2, 3)
+    assert_equal(res2d.toarray(), np.array([[1, 2, 3], [4, 5, 6]]))
+
+    # 4d
+    arr4d = np.array([[[[3, 7], [1, 0]], [[6, 5], [9, 2]]],
+                      [[[4, 3], [2, 8]], [[7, 5], [1, 6]]],
+                      [[[0, 9], [4, 3]], [[2, 1], [7, 8]]]])
+    res4d = coo_array(arr4d)
+    assert res4d.shape == (3, 2, 2, 2)
+    assert_equal(res4d.toarray(), arr4d)
+
+    # 9d
+    np.random.seed(12)
+    arr9d = np.random.randn(2,3,4,7,6,5,3,2,4)
+    res9d = coo_array(arr9d)
+    assert res9d.shape == (2,3,4,7,6,5,3,2,4)
+    assert_equal(res9d.toarray(), arr9d)
+
+    # storing nan as element of sparse array
+    nan_3d = coo_array([[[1, np.nan]], [[3, 4]], [[5, 6]]])
+    assert nan_3d.shape == (3, 1, 2)
+    assert_equal(nan_3d.toarray(), np.array([[[1, np.nan]], [[3, 4]], [[5, 6]]]))
+
+
+def test_dense_constructor_with_shape():
+    res1d = coo_array([1, 2, 3], shape=(3,))
+    assert res1d.shape == (3,)
+    assert_equal(res1d.toarray(), np.array([1, 2, 3]))
+
+    res2d = coo_array([[1, 2, 3], [4, 5, 6]], shape=(2, 3))
+    assert res2d.shape == (2, 3)
+    assert_equal(res2d.toarray(), np.array([[1, 2, 3], [4, 5, 6]]))
+
+    res3d = coo_array([[[3]], [[4]]], shape=(2, 1, 1))
+    assert res3d.shape == (2, 1, 1)
+    assert_equal(res3d.toarray(), np.array([[[3]], [[4]]]))
+
+    np.random.seed(12)
+    arr7d = np.random.randn(2,4,1,6,5,3,2)
+    res7d = coo_array((arr7d), shape=(2,4,1,6,5,3,2))
+    assert res7d.shape == (2,4,1,6,5,3,2)
+    assert_equal(res7d.toarray(), arr7d)
+
+
+def test_dense_constructor_with_inconsistent_shape():
+    with pytest.raises(ValueError, match='inconsistent shapes'):
+        coo_array([1, 2, 3], shape=(4,))
+
+    with pytest.raises(ValueError, match='inconsistent shapes'):
+        coo_array([1, 2, 3], shape=(3, 1))
+
+    with pytest.raises(ValueError, match='inconsistent shapes'):
+        coo_array([[1, 2, 3]], shape=(3,))
+
+    with pytest.raises(ValueError, match='inconsistent shapes'):
+        coo_array([[[3]], [[4]]], shape=(1, 1, 1))
+
+    with pytest.raises(ValueError,
+                       match='axis 0 index 2 exceeds matrix dimension 2'):
+        coo_array(([1], ([2],)), shape=(2,))
+
+    with pytest.raises(ValueError,
+                       match='axis 1 index 3 exceeds matrix dimension 3'):
+        coo_array(([1,3], ([0, 1], [0, 3], [1, 1])), shape=(2, 3, 2))
+
+    with pytest.raises(ValueError, match='negative axis 0 index: -1'):
+        coo_array(([1], ([-1],)))
+
+    with pytest.raises(ValueError, match='negative axis 2 index: -1'):
+        coo_array(([1], ([0], [2], [-1])))
+
+
+def test_1d_sparse_constructor():
+    empty1d = coo_array((3,))
+    res = coo_array(empty1d)
+    assert res.shape == (3,)
+    assert_equal(res.toarray(), np.zeros((3,)))
+
+
+def test_1d_tuple_constructor():
+    res = coo_array(([9,8], ([1,2],)))
+    assert res.shape == (3,)
+    assert_equal(res.toarray(), np.array([0, 9, 8]))
+
+
+def test_1d_tuple_constructor_with_shape():
+    res = coo_array(([9,8], ([1,2],)), shape=(4,))
+    assert res.shape == (4,)
+    assert_equal(res.toarray(), np.array([0, 9, 8, 0]))
+
+def test_non_subscriptability():
+    coo_2d = coo_array((2, 2))
+
+    with pytest.raises(TypeError,
+                        match="'coo_array' object does not support item assignment"):
+        coo_2d[0, 0] = 1
+
+    with pytest.raises(TypeError,
+                       match="'coo_array' object is not subscriptable"):
+        coo_2d[0, :]
+
+def test_reshape_overflow():
+    # see gh-22353 : new idx_dtype can need to be int64 instead of int32
+    M, N = (1045507, 523266)
+    coords = (np.array([M - 1], dtype='int32'), np.array([N - 1], dtype='int32'))
+    A = coo_array(([3.3], coords), shape=(M, N))
+
+    # need new idx_dtype to not overflow
+    B = A.reshape((M * N, 1))
+    assert B.coords[0].dtype == np.dtype('int64')
+    assert B.coords[0][0] == (M * N) - 1
+
+    # need idx_dtype to stay int32 if before and after can be int32
+    C = A.reshape(N, M)
+    assert C.coords[0].dtype == np.dtype('int32')
+    assert C.coords[0][0] == N - 1
+
+def test_reshape():
+    arr1d = coo_array([1, 0, 3])
+    assert arr1d.shape == (3,)
+
+    col_vec = arr1d.reshape((3, 1))
+    assert col_vec.shape == (3, 1)
+    assert_equal(col_vec.toarray(), np.array([[1], [0], [3]]))
+
+    row_vec = arr1d.reshape((1, 3))
+    assert row_vec.shape == (1, 3)
+    assert_equal(row_vec.toarray(), np.array([[1, 0, 3]]))
+
+    # attempting invalid reshape
+    with pytest.raises(ValueError, match="cannot reshape array"):
+        arr1d.reshape((3,3))
+
+    # attempting reshape with a size 0 dimension
+    with pytest.raises(ValueError, match="cannot reshape array"):
+        arr1d.reshape((3,0))
+
+    arr2d = coo_array([[1, 2, 0], [0, 0, 3]])
+    assert arr2d.shape == (2, 3)
+
+    flat = arr2d.reshape((6,))
+    assert flat.shape == (6,)
+    assert_equal(flat.toarray(), np.array([1, 2, 0, 0, 0, 3]))
+
+    # 2d to 3d
+    to_3d_arr = arr2d.reshape((2, 3, 1))
+    assert to_3d_arr.shape == (2, 3, 1)
+    assert_equal(to_3d_arr.toarray(), np.array([[[1], [2], [0]], [[0], [0], [3]]]))
+
+    # attempting invalid reshape
+    with pytest.raises(ValueError, match="cannot reshape array"):
+        arr2d.reshape((1,3))
+
+
+def test_nnz():
+    arr1d = coo_array([1, 0, 3])
+    assert arr1d.shape == (3,)
+    assert arr1d.nnz == 2
+
+    arr2d = coo_array([[1, 2, 0], [0, 0, 3]])
+    assert arr2d.shape == (2, 3)
+    assert arr2d.nnz == 3
+
+
+def test_transpose():
+    arr1d = coo_array([1, 0, 3]).T
+    assert arr1d.shape == (3,)
+    assert_equal(arr1d.toarray(), np.array([1, 0, 3]))
+
+    arr2d = coo_array([[1, 2, 0], [0, 0, 3]]).T
+    assert arr2d.shape == (3, 2)
+    assert_equal(arr2d.toarray(), np.array([[1, 0], [2, 0], [0, 3]]))
+
+
+def test_transpose_with_axis():
+    arr1d = coo_array([1, 0, 3]).transpose(axes=(0,))
+    assert arr1d.shape == (3,)
+    assert_equal(arr1d.toarray(), np.array([1, 0, 3]))
+
+    arr2d = coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(0, 1))
+    assert arr2d.shape == (2, 3)
+    assert_equal(arr2d.toarray(), np.array([[1, 2, 0], [0, 0, 3]]))
+
+    with pytest.raises(ValueError, match="axes don't match matrix dimensions"):
+        coo_array([1, 0, 3]).transpose(axes=(0, 1))
+
+    with pytest.raises(ValueError, match="repeated axis in transpose"):
+        coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(1, 1))
+
+
+def test_1d_row_and_col():
+    res = coo_array([1, -2, -3])
+    assert_equal(res.col, np.array([0, 1, 2]))
+    assert_equal(res.row, np.zeros_like(res.col))
+    assert res.row.dtype == res.col.dtype
+    assert res.row.flags.writeable is False
+
+    res.col = [1, 2, 3]
+    assert len(res.coords) == 1
+    assert_equal(res.col, np.array([1, 2, 3]))
+    assert res.row.dtype == res.col.dtype
+
+    with pytest.raises(ValueError, match="cannot set row attribute"):
+        res.row = [1, 2, 3]
+
+
+def test_1d_toformats():
+    res = coo_array([1, -2, -3])
+    for f in [res.tobsr, res.tocsc, res.todia, res.tolil]:
+        with pytest.raises(ValueError, match='Cannot convert'):
+            f()
+    for f in [res.tocoo, res.tocsr, res.todok]:
+        assert_equal(f().toarray(), res.toarray())
+
+
+@pytest.mark.parametrize('arg', [1, 2, 4, 5, 8])
+def test_1d_resize(arg: int):
+    den = np.array([1, -2, -3])
+    res = coo_array(den)
+    den.resize(arg, refcheck=False)
+    res.resize(arg)
+    assert res.shape == den.shape
+    assert_equal(res.toarray(), den)
+
+
+@pytest.mark.parametrize('arg', zip([1, 2, 3, 4], [1, 2, 3, 4]))
+def test_1d_to_2d_resize(arg: tuple[int, int]):
+    den = np.array([1, 0, 3])
+    res = coo_array(den)
+
+    den.resize(arg, refcheck=False)
+    res.resize(arg)
+    assert res.shape == den.shape
+    assert_equal(res.toarray(), den)
+
+
+@pytest.mark.parametrize('arg', [1, 4, 6, 8])
+def test_2d_to_1d_resize(arg: int):
+    den = np.array([[1, 0, 3], [4, 0, 0]])
+    res = coo_array(den)
+    den.resize(arg, refcheck=False)
+    res.resize(arg)
+    assert res.shape == den.shape
+    assert_equal(res.toarray(), den)
+
+
+def test_sum_duplicates():
+    # 1d case
+    arr1d = coo_array(([2, 2, 2], ([1, 0, 1],)))
+    assert arr1d.nnz == 3
+    assert_equal(arr1d.toarray(), np.array([2, 4]))
+    arr1d.sum_duplicates()
+    assert arr1d.nnz == 2
+    assert_equal(arr1d.toarray(), np.array([2, 4]))
+
+    # 4d case
+    arr4d = coo_array(([2, 3, 7], ([1, 0, 1], [0, 2, 0], [1, 2, 1], [1, 0, 1])))
+    assert arr4d.nnz == 3
+    expected = np.array(  # noqa: E501
+        [[[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [3, 0]]],
+         [[[0, 0], [0, 9], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]]
+    )
+    assert_equal(arr4d.toarray(), expected)
+    arr4d.sum_duplicates()
+    assert arr4d.nnz == 2
+    assert_equal(arr4d.toarray(), expected)
+
+    # when there are no duplicates
+    arr_nodups = coo_array(([1, 2, 3, 4], ([0, 1, 2, 3],)))
+    assert arr_nodups.nnz == 4
+    arr_nodups.sum_duplicates()
+    assert arr_nodups.nnz == 4
+
+
+def test_eliminate_zeros():
+    arr1d = coo_array(([0, 0, 1], ([1, 0, 1],)))
+    assert arr1d.nnz == 3
+    assert arr1d.count_nonzero() == 1
+    assert_equal(arr1d.toarray(), np.array([0, 1]))
+    arr1d.eliminate_zeros()
+    assert arr1d.nnz == 1
+    assert arr1d.count_nonzero() == 1
+    assert_equal(arr1d.toarray(), np.array([0, 1]))
+    assert_equal(arr1d.col, np.array([1]))
+    assert_equal(arr1d.row, np.array([0]))
+
+
+def test_1d_add_dense():
+    den_a = np.array([0, -2, -3, 0])
+    den_b = np.array([0, 1, 2, 3])
+    exp = den_a + den_b
+    res = coo_array(den_a) + den_b
+    assert type(res) is type(exp)
+    assert_equal(res, exp)
+
+
+def test_1d_add_sparse():
+    den_a = np.array([0, -2, -3, 0])
+    den_b = np.array([0, 1, 2, 3])
+    dense_sum = den_a + den_b
+    # this routes through CSR format
+    sparse_sum = coo_array(den_a) + coo_array(den_b)
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+def test_1d_matmul_vector():
+    den_a = np.array([0, -2, -3, 0])
+    den_b = np.array([0, 1, 2, 3])
+    exp = den_a @ den_b
+    res = coo_array(den_a) @ den_b
+    assert np.ndim(res) == 0
+    assert_equal(res, exp)
+
+
+def test_1d_matmul_multivector():
+    den = np.array([0, -2, -3, 0])
+    other = np.array([[0, 1, 2, 3], [3, 2, 1, 0]]).T
+    exp = den @ other
+    res = coo_array(den) @ other
+    assert type(res) is type(exp)
+    assert_equal(res, exp)
+
+
+def test_2d_matmul_multivector():
+    # sparse-sparse matmul
+    den = np.array([[0, 1, 2, 3], [3, 2, 1, 0]])
+    arr2d = coo_array(den)
+    exp = den @ den.T
+    res = arr2d @ arr2d.T
+    assert_equal(res.toarray(), exp)
+
+    # sparse-dense matmul for self.ndim = 2
+    den = np.array([[0, 4, 3, 0, 5], [1, 0, 7, 3, 4]])
+    arr2d = coo_array(den)
+    exp = den @ den.T
+    res = arr2d @ den.T
+    assert_equal(res, exp)
+
+    # sparse-dense matmul for self.ndim = 1
+    den_a = np.array([[0, 4, 3, 0, 5], [1, 0, 7, 3, 4]])
+    den_b = np.array([0, 1, 6, 0, 4])
+    arr1d = coo_array(den_b)
+    exp = den_b @ den_a.T
+    res = arr1d @ den_a.T
+    assert_equal(res, exp)
+
+    # sparse-dense matmul for self.ndim = 1 and other.ndim = 2
+    den_a = np.array([1, 0, 2])
+    den_b = np.array([[3], [4], [0]])
+    exp = den_a @ den_b
+    res = coo_array(den_a) @ den_b
+    assert_equal(res, exp)
+    res = coo_array(den_a) @ list(den_b)
+    assert_equal(res, exp)
+
+
+def test_1d_diagonal():
+    den = np.array([0, -2, -3, 0])
+    with pytest.raises(ValueError, match='diagonal requires two dimensions'):
+        coo_array(den).diagonal()
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_todense(shape):
+    np.random.seed(12)
+    arr = np.random.randint(low=0, high=5, size=shape)
+    assert_equal(coo_array(arr).todense(), arr)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_sparse_constructor(shape):
+    empty_arr = coo_array(shape)
+    res = coo_array(empty_arr)
+    assert res.shape == (shape)
+    assert_equal(res.toarray(), np.zeros(shape))
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_tuple_constructor(shape):
+    np.random.seed(12)
+    arr = np.random.randn(*shape)
+    res = coo_array(arr)
+    assert res.shape == shape
+    assert_equal(res.toarray(), arr)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_tuple_constructor_with_shape(shape):
+    np.random.seed(12)
+    arr = np.random.randn(*shape)
+    res = coo_array(arr, shape=shape)
+    assert res.shape == shape
+    assert_equal(res.toarray(), arr)
+
+
+def test_tuple_constructor_for_dim_size_zero():
+    # arrays with a dimension of size 0
+    with pytest.raises(ValueError, match='exceeds matrix dimension'):
+        coo_array(([9, 8], ([1, 2], [1, 0], [2, 1])), shape=(3,4,0))
+
+    empty_arr = coo_array(([], ([], [], [], [])), shape=(4,0,2,3))
+    assert_equal(empty_arr.toarray(), np.empty((4,0,2,3)))
+
+
+@pytest.mark.parametrize(('shape', 'new_shape'), [((4,9,6,5), (3,6,15,4)),
+                                                  ((4,9,6,5), (36,30)),
+                                                  ((4,9,6,5), (1080,)),
+                                                  ((4,9,6,5), (2,3,2,2,3,5,3)),])
+def test_nd_reshape(shape, new_shape):
+    # reshaping a 4d sparse array
+    rng = np.random.default_rng(23409823)
+
+    arr4d = random_array(shape, density=0.6, rng=rng, dtype=int)
+    assert arr4d.shape == shape
+    den4d = arr4d.toarray()
+
+    exp_arr = den4d.reshape(new_shape)
+    res_arr = arr4d.reshape(new_shape)
+    assert res_arr.shape == new_shape
+    assert_equal(res_arr.toarray(), exp_arr)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_nnz(shape):
+    rng = np.random.default_rng(23409823)
+
+    arr = random_array(shape, density=0.6, rng=rng, dtype=int)
+    assert arr.nnz == np.count_nonzero(arr.toarray())
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_transpose(shape):
+    rng = np.random.default_rng(23409823)
+
+    arr = random_array(shape, density=0.6, rng=rng, dtype=int)
+    exp_arr = arr.toarray().T
+    trans_arr = arr.transpose()
+    assert trans_arr.shape == shape[::-1]
+    assert_equal(exp_arr, trans_arr.toarray())
+
+
+@pytest.mark.parametrize(('shape', 'axis_perm'), [((3,), (0,)),
+                                                  ((2,3), (0,1)),
+                                                  ((2,4,3,6,5,3), (1,2,0,5,3,4)),])
+def test_nd_transpose_with_axis(shape, axis_perm):
+    rng = np.random.default_rng(23409823)
+
+    arr = random_array(shape, density=0.6, rng=rng, dtype=int)
+    trans_arr = arr.transpose(axes=axis_perm)
+    assert_equal(trans_arr.toarray(), np.transpose(arr.toarray(), axes=axis_perm))
+
+
+def test_transpose_with_inconsistent_axis():
+    with pytest.raises(ValueError, match="axes don't match matrix dimensions"):
+        coo_array([1, 0, 3]).transpose(axes=(0, 1))
+
+    with pytest.raises(ValueError, match="repeated axis in transpose"):
+        coo_array([[1, 2, 0], [0, 0, 3]]).transpose(axes=(1, 1))
+
+
+def test_nd_eliminate_zeros():
+    # for 3d sparse arrays
+    arr3d = coo_array(([1, 0, 0, 4], ([0, 1, 1, 2], [0, 1, 0, 1], [1, 1, 2, 0])))
+    assert arr3d.nnz == 4
+    assert arr3d.count_nonzero() == 2
+    assert_equal(arr3d.toarray(), np.array([[[0, 1, 0], [0, 0, 0]],
+                                    [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [4, 0, 0]]]))
+    arr3d.eliminate_zeros()
+    assert arr3d.nnz == 2
+    assert arr3d.count_nonzero() == 2
+    assert_equal(arr3d.toarray(), np.array([[[0, 1, 0], [0, 0, 0]],
+                                    [[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [4, 0, 0]]]))
+
+    # for a 5d sparse array when all elements of data array are 0
+    coords = ([0, 1, 1, 2], [0, 1, 0, 1], [1, 1, 2, 0], [0, 0, 2, 3], [1, 0, 0, 2])
+    arr5d = coo_array(([0, 0, 0, 0], coords))
+    assert arr5d.nnz == 4
+    assert arr5d.count_nonzero() == 0
+    arr5d.eliminate_zeros()
+    assert arr5d.nnz == 0
+    assert arr5d.count_nonzero() == 0
+    assert_equal(arr5d.col, np.array([]))
+    assert_equal(arr5d.row, np.array([]))
+    assert_equal(arr5d.coords, ([], [], [], [], []))
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_add_dense(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array(shape, density=0.6, rng=rng, dtype=int)
+    sp_y = random_array(shape, density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+    exp = den_x + den_y
+    res = sp_x + den_y
+    assert type(res) is type(exp)
+    assert_equal(res, exp)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_add_sparse(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array((shape), density=0.6, rng=rng, dtype=int)
+    sp_y = random_array((shape), density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+
+    dense_sum = den_x + den_y
+    sparse_sum = sp_x + sp_y
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+def test_add_sparse_with_inf():
+    # addition of sparse arrays with an inf element
+    den_a = np.array([[[0], [np.inf]], [[-3], [0]]])
+    den_b = np.array([[[0], [1]], [[2], [3]]])
+    dense_sum = den_a + den_b
+    sparse_sum = coo_array(den_a) + coo_array(den_b)
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+@pytest.mark.parametrize(('a_shape', 'b_shape'), [((7,), (12,)),
+                                                  ((6,4), (6,5)),
+                                                  ((5,9,3,2), (9,5,2,3)),])
+def test_nd_add_sparse_with_inconsistent_shapes(a_shape, b_shape):
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array((a_shape), density=0.6, rng=rng, dtype=int)
+    arr_b = random_array((b_shape), density=0.6, rng=rng, dtype=int)
+    with pytest.raises(ValueError,
+                       match="(Incompatible|inconsistent) shapes|cannot be broadcast"):
+        arr_a + arr_b
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_sub_dense(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array(shape, density=0.6, rng=rng, dtype=int)
+    sp_y = random_array(shape, density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+    exp = den_x - den_y
+    res = sp_x - den_y
+    assert type(res) is type(exp)
+    assert_equal(res, exp)
+
+
+@pytest.mark.parametrize('shape', [(0,), (7,), (4,7), (0,0,0), (3,6,2),
+                                   (1,0,3), (7,9,3,2,4,5)])
+def test_nd_sub_sparse(shape):
+    rng = np.random.default_rng(23409823)
+
+    sp_x = random_array(shape, density=0.6, rng=rng, dtype=int)
+    sp_y = random_array(shape, density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+
+    dense_sum = den_x - den_y
+    sparse_sum = sp_x - sp_y
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+def test_nd_sub_sparse_with_nan():
+    # subtraction of sparse arrays with a nan element
+    den_a = np.array([[[0], [np.nan]], [[-3], [0]]])
+    den_b = np.array([[[0], [1]], [[2], [3]]])
+    dense_sum = den_a - den_b
+    sparse_sum = coo_array(den_a) - coo_array(den_b)
+    assert_equal(dense_sum, sparse_sum.toarray())
+
+
+@pytest.mark.parametrize(('a_shape', 'b_shape'), [((7,), (12,)),
+                                                  ((6,4), (6,5)),
+                                                  ((5,9,3,2), (9,5,2,3)),])
+def test_nd_sub_sparse_with_inconsistent_shapes(a_shape, b_shape):
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array((a_shape), density=0.6, rng=rng, dtype=int)
+    arr_b = random_array((b_shape), density=0.6, rng=rng, dtype=int)
+    with pytest.raises(ValueError, match="inconsistent shapes"):
+        arr_a - arr_b
+
+
+mat_vec_shapes = [
+    ((2, 3, 4, 5), (5,)),
+    ((0, 0), (0,)),
+    ((2, 3, 4, 7, 8), (8,)),
+    ((4, 4, 2, 0), (0,)),
+    ((6, 5, 3, 2, 4), (4, 1)),
+    ((2,5), (5,)),
+    ((2, 5), (5, 1)),
+    ((3,), (3, 1)),
+    ((4,), (4,))
+]
+@pytest.mark.parametrize(('mat_shape', 'vec_shape'), mat_vec_shapes)
+def test_nd_matmul_vector(mat_shape, vec_shape):
+    rng = np.random.default_rng(23409823)
+
+    sp_x = random_array(mat_shape, density=0.6, rng=rng, dtype=int)
+    sp_y = random_array(vec_shape, density=0.6, rng=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+    exp = den_x @ den_y
+    res = sp_x @ den_y
+    assert_equal(res,exp)
+    res = sp_x @ list(den_y)
+    assert_equal(res,exp)
+
+
+mat_mat_shapes = [
+    ((2, 3, 4, 5), (2, 3, 5, 7)),
+    ((0, 0), (0,)),
+    ((4, 4, 2, 0), (0,)),
+    ((7, 8, 3), (3,)),
+    ((7, 8, 3), (3, 1)),
+    ((6, 5, 3, 2, 4), (4, 3)),
+    ((1, 3, 2, 4), (6, 5, 1, 4, 3)),
+    ((6, 1, 1, 2, 4), (1, 3, 4, 3)),
+    ((4,), (2, 4, 3)),
+    ((3,), (5, 6, 7, 3, 2)),
+    ((4,), (4, 3)),
+    ((2, 5), (5, 1)),
+]
+@pytest.mark.parametrize(('mat_shape1', 'mat_shape2'), mat_mat_shapes)
+def test_nd_matmul(mat_shape1, mat_shape2):
+    rng = np.random.default_rng(23409823)
+
+    sp_x = random_array(mat_shape1, density=0.6, random_state=rng, dtype=int)
+    sp_y = random_array(mat_shape2, density=0.6, random_state=rng, dtype=int)
+    den_x, den_y = sp_x.toarray(), sp_y.toarray()
+    exp = den_x @ den_y
+    # sparse-sparse
+    res = sp_x @ sp_y
+    assert_equal(res.toarray(), exp)
+    # sparse-dense
+    res = sp_x @ den_y
+    assert_equal(res, exp)
+    res = sp_x @ list(den_y)
+    assert_equal(res, exp)
+
+    # dense-sparse
+    res = den_x @ sp_y
+    assert_equal(res, exp)
+
+
+def test_nd_matmul_sparse_with_inconsistent_arrays():
+    rng = np.random.default_rng(23409823)
+
+    sp_x = random_array((4,5,7,6,3), density=0.6, random_state=rng, dtype=int)
+    sp_y = random_array((1,5,3,2,5), density=0.6, random_state=rng, dtype=int)
+    with pytest.raises(ValueError, match="matmul: dimension mismatch with signature"):
+        sp_x @ sp_y
+    with pytest.raises(ValueError, match="matmul: dimension mismatch with signature"):
+        sp_x @ (sp_y.toarray())
+
+    sp_z = random_array((1,5,3,2), density=0.6, random_state=rng, dtype=int)
+    with pytest.raises(ValueError, match="Batch dimensions are not broadcastable"):
+        sp_x @ sp_z
+    with pytest.raises(ValueError, match="Batch dimensions are not broadcastable"):
+        sp_x @ (sp_z.toarray())
+
+
+def test_dot_1d_1d(): # 1-D inner product
+    a = coo_array([1,2,3])
+    b = coo_array([4,5,6])
+    exp = np.dot(a.toarray(), b.toarray())
+    res = a.dot(b)
+    assert_equal(res, exp)
+    res = a.dot(b.toarray())
+    assert_equal(res, exp)
+
+
+def test_dot_sparse_scalar():
+    a = coo_array([[1, 2], [3, 4], [5, 6]])
+    b = 3
+    res = a.dot(b)
+    exp = np.dot(a.toarray(), b)
+    assert_equal(res.toarray(), exp)
+
+
+def test_dot_with_inconsistent_shapes():
+    arr_a = coo_array([[[1, 2]], [[3, 4]]])
+    arr_b = coo_array([4, 5, 6])
+    with pytest.raises(ValueError, match="not aligned for n-D dot"):
+        arr_a.dot(arr_b)
+
+
+def test_matmul_dot_not_implemented():
+    arr_a = coo_array([[1, 2], [3, 4]])
+    with pytest.raises(TypeError, match="argument not supported type"):
+        arr_a.dot(None)
+    with pytest.raises(TypeError, match="arg not supported type"):
+        arr_a.tensordot(None)
+    with pytest.raises(TypeError, match="unsupported operand type"):
+        arr_a @ None
+    with pytest.raises(TypeError, match="unsupported operand type"):
+        None @ arr_a
+
+
+dot_shapes = [
+    ((3,3), (3,3)), ((4,6), (6,7)), ((1,4), (4,1)), # matrix multiplication 2-D
+    ((3,2,4,7), (7,)), ((5,), (6,3,5,2)), # dot of n-D and 1-D arrays
+    ((3,2,4,7), (7,1)), ((1,5,), (6,3,5,2)),
+    ((4,6), (3,2,6,4)), ((2,8,7), (4,5,7,7,2)), # dot of n-D and m-D arrays
+    ((4,5,7,6), (3,2,6,4)),
+]
+@pytest.mark.parametrize(('a_shape', 'b_shape'), dot_shapes)
+def test_dot_nd(a_shape, b_shape):
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array(a_shape, density=0.6, random_state=rng, dtype=int)
+    arr_b = random_array(b_shape, density=0.6, random_state=rng, dtype=int)
+
+    exp = np.dot(arr_a.toarray(), arr_b.toarray())
+    # sparse-dense
+    res = arr_a.dot(arr_b.toarray())
+    assert_equal(res, exp)
+    res = arr_a.dot(list(arr_b.toarray()))
+    assert_equal(res, exp)
+    # sparse-sparse
+    res = arr_a.dot(arr_b)
+    assert_equal(res.toarray(), exp)
+
+
+tensordot_shapes_and_axes = [
+    ((4,6), (6,7), ([1], [0])),
+    ((3,2,4,7), (7,), ([3], [0])),
+    ((5,), (6,3,5,2), ([0], [2])),
+    ((4,5,7,6), (3,2,6,4), ([0, 3], [3, 2])),
+    ((2,8,7), (4,5,7,8,2), ([0, 1, 2], [4, 3, 2])),
+    ((4,5,3,2,6), (3,2,6,7,8), 3),
+    ((4,5,7), (7,3,7), 1),
+    ((2,3,4), (2,3,4), ([0, 1, 2], [0, 1, 2])),
+]
+@pytest.mark.parametrize(('a_shape', 'b_shape', 'axes'), tensordot_shapes_and_axes)
+def test_tensordot(a_shape, b_shape, axes):
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array(a_shape, density=0.6, random_state=rng, dtype=int)
+    arr_b = random_array(b_shape, density=0.6, random_state=rng, dtype=int)
+
+    exp = np.tensordot(arr_a.toarray(), arr_b.toarray(), axes=axes)
+
+    # sparse-dense
+    res = arr_a.tensordot(arr_b.toarray(), axes=axes)
+    assert_equal(res, exp)
+    res = arr_a.tensordot(list(arr_b.toarray()), axes=axes)
+    assert_equal(res, exp)
+
+    # sparse-sparse
+    res = arr_a.tensordot(arr_b, axes=axes)
+    if type(res) is coo_array:
+        assert_equal(res.toarray(), exp)
+    else:
+        assert_equal(res, exp)
+
+
+def test_tensordot_with_invalid_args():
+    rng = np.random.default_rng(23409823)
+
+    arr_a = random_array((3,4,5), density=0.6, random_state=rng, dtype=int)
+    arr_b = random_array((3,4,6), density=0.6, random_state=rng, dtype=int)
+
+    axes = ([2], [2]) # sizes of 2nd axes of both shapes do not match
+    with pytest.raises(ValueError, match="sizes of the corresponding axes must match"):
+        arr_a.tensordot(arr_b, axes=axes)
+
+    arr_a = random_array((5,4,2,3,7), density=0.6, random_state=rng, dtype=int)
+    arr_b = random_array((4,6,3,2), density=0.6, random_state=rng, dtype=int)
+
+    axes = ([2,0,1], [1,3]) # lists have different lengths
+    with pytest.raises(ValueError, match="axes lists/tuples must be of the"
+                       " same length"):
+        arr_a.tensordot(arr_b, axes=axes)
+
+
+@pytest.mark.parametrize(('actual_shape', 'broadcast_shape'),
+                         [((1,3,5,4), (2,3,5,4)), ((2,1,5,4), (6,2,3,5,4)),
+                          ((1,1,7,8,9), (4,5,6,7,8,9)), ((1,3), (4,5,3)),
+                          ((7,8,1), (7,8,5)), ((3,1), (3,4)), ((1,), (5,)),
+                          ((1,1,1), (4,5,6)), ((1,3,1,5,4), (8,2,3,9,5,4)),])
+def test_broadcast_to(actual_shape, broadcast_shape):
+    rng = np.random.default_rng(23409823)
+
+    arr = random_array(actual_shape, density=0.6, random_state=rng, dtype=int)
+    res = arr._broadcast_to(broadcast_shape)
+    exp = np.broadcast_to(arr.toarray(), broadcast_shape)
+    assert_equal(res.toarray(), exp)
+
+
+@pytest.mark.parametrize(('shape'), [(4,5,6,7,8), (6,4),
+                                     (5,9,3,2), (9,5,2,3,4),])
+def test_block_diag(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array(shape, density=0.6, random_state=rng, dtype=int)
+    den_x = sp_x.toarray()
+
+    # converting n-d numpy array to an array of slices of 2-D matrices,
+    # to pass as argument into scipy.linalg.block_diag
+    num_slices = int(np.prod(den_x.shape[:-2]))
+    reshaped_array = den_x.reshape((num_slices,) + den_x.shape[-2:])
+    matrices = [reshaped_array[i, :, :] for i in range(num_slices)]
+    exp = block_diag(*matrices)
+
+    res = _block_diag(sp_x)
+
+    assert_equal(res.toarray(), exp)
+
+
+@pytest.mark.parametrize(('shape'), [(4,5,6,7,8), (6,4),
+                                     (5,9,3,2), (9,5,2,3,4),])
+def test_extract_block_diag(shape):
+    rng = np.random.default_rng(23409823)
+    sp_x = random_array(shape, density=0.6, random_state=rng, dtype=int)
+    res = _extract_block_diag(_block_diag(sp_x), shape)
+
+    assert_equal(res.toarray(), sp_x.toarray())
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py
new file mode 100644
index 0000000000000000000000000000000000000000..6313751e41899ae7c5daf01fbdbbacdc1f303fa1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csc.py
@@ -0,0 +1,98 @@
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_
+from scipy.sparse import csr_matrix, csc_matrix, lil_matrix
+
+import pytest
+
+
+def test_csc_getrow():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsc = csc_matrix(X)
+
+    for i in range(N):
+        arr_row = X[i:i + 1, :]
+        csc_row = Xcsc.getrow(i)
+
+        assert_array_almost_equal(arr_row, csc_row.toarray())
+        assert_(type(csc_row) is csr_matrix)
+
+
+def test_csc_getcol():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsc = csc_matrix(X)
+
+    for i in range(N):
+        arr_col = X[:, i:i + 1]
+        csc_col = Xcsc.getcol(i)
+
+        assert_array_almost_equal(arr_col, csc_col.toarray())
+        assert_(type(csc_col) is csc_matrix)
+
+@pytest.mark.parametrize("matrix_input, axis, expected_shape",
+    [(csc_matrix([[1, 0],
+                [0, 0],
+                [0, 2]]),
+      0, (0, 2)),
+     (csc_matrix([[1, 0],
+                [0, 0],
+                [0, 2]]),
+      1, (3, 0)),
+     (csc_matrix([[1, 0],
+                [0, 0],
+                [0, 2]]),
+      'both', (0, 0)),
+     (csc_matrix([[0, 1, 0, 0, 0, 0],
+                [0, 0, 0, 0, 0, 0],
+                [0, 0, 2, 3, 0, 1]]),
+      0, (0, 6))])
+def test_csc_empty_slices(matrix_input, axis, expected_shape):
+    # see gh-11127 for related discussion
+    slice_1 = matrix_input.toarray().shape[0] - 1
+    slice_2 = slice_1
+    slice_3 = slice_2 - 1
+
+    if axis == 0:
+        actual_shape_1 = matrix_input[slice_1:slice_2, :].toarray().shape
+        actual_shape_2 = matrix_input[slice_1:slice_3, :].toarray().shape
+    elif axis == 1:
+        actual_shape_1 = matrix_input[:, slice_1:slice_2].toarray().shape
+        actual_shape_2 = matrix_input[:, slice_1:slice_3].toarray().shape
+    elif axis == 'both':
+        actual_shape_1 = matrix_input[slice_1:slice_2, slice_1:slice_2].toarray().shape
+        actual_shape_2 = matrix_input[slice_1:slice_3, slice_1:slice_3].toarray().shape
+
+    assert actual_shape_1 == expected_shape
+    assert actual_shape_1 == actual_shape_2
+
+
+@pytest.mark.parametrize('ax', (-2, -1, 0, 1, None))
+def test_argmax_overflow(ax):
+    # See gh-13646: Windows integer overflow for large sparse matrices.
+    dim = (100000, 100000)
+    A = lil_matrix(dim)
+    A[-2, -2] = 42
+    A[-3, -3] = 0.1234
+    A = csc_matrix(A)
+    idx = A.argmax(axis=ax)
+
+    if ax is None:
+        # idx is a single flattened index
+        # that we need to convert to a 2d index pair;
+        # can't do this with np.unravel_index because
+        # the dimensions are too large
+        ii = idx % dim[0]
+        jj = idx // dim[0]
+    else:
+        # idx is an array of size of A.shape[ax];
+        # check the max index to make sure no overflows
+        # we encountered
+        assert np.count_nonzero(idx) == A.nnz
+        ii, jj = np.max(idx), np.argmax(idx)
+
+    assert A[ii, jj] == A[-2, -2]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b011ad4fdce93c0fac36e58381da0bb554ba3be
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_csr.py
@@ -0,0 +1,214 @@
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_, assert_array_equal
+from scipy.sparse import csr_matrix, csc_matrix, csr_array, csc_array, hstack
+from scipy import sparse
+import pytest
+
+
+def _check_csr_rowslice(i, sl, X, Xcsr):
+    np_slice = X[i, sl]
+    csr_slice = Xcsr[i, sl]
+    assert_array_almost_equal(np_slice, csr_slice.toarray()[0])
+    assert_(type(csr_slice) is csr_matrix)
+
+
+def test_csr_rowslice():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsr = csr_matrix(X)
+
+    slices = [slice(None, None, None),
+              slice(None, None, -1),
+              slice(1, -2, 2),
+              slice(-2, 1, -2)]
+
+    for i in range(N):
+        for sl in slices:
+            _check_csr_rowslice(i, sl, X, Xcsr)
+
+
+def test_csr_getrow():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsr = csr_matrix(X)
+
+    for i in range(N):
+        arr_row = X[i:i + 1, :]
+        csr_row = Xcsr.getrow(i)
+
+        assert_array_almost_equal(arr_row, csr_row.toarray())
+        assert_(type(csr_row) is csr_matrix)
+
+
+def test_csr_getcol():
+    N = 10
+    np.random.seed(0)
+    X = np.random.random((N, N))
+    X[X > 0.7] = 0
+    Xcsr = csr_matrix(X)
+
+    for i in range(N):
+        arr_col = X[:, i:i + 1]
+        csr_col = Xcsr.getcol(i)
+
+        assert_array_almost_equal(arr_col, csr_col.toarray())
+        assert_(type(csr_col) is csr_matrix)
+
+@pytest.mark.parametrize("matrix_input, axis, expected_shape",
+    [(csr_matrix([[1, 0, 0, 0],
+                [0, 0, 0, 0],
+                [0, 2, 3, 0]]),
+      0, (0, 4)),
+     (csr_matrix([[1, 0, 0, 0],
+                [0, 0, 0, 0],
+                [0, 2, 3, 0]]),
+      1, (3, 0)),
+     (csr_matrix([[1, 0, 0, 0],
+                [0, 0, 0, 0],
+                [0, 2, 3, 0]]),
+      'both', (0, 0)),
+     (csr_matrix([[0, 1, 0, 0, 0],
+                [0, 0, 0, 0, 0],
+                [0, 0, 2, 3, 0]]),
+      0, (0, 5))])
+def test_csr_empty_slices(matrix_input, axis, expected_shape):
+    # see gh-11127 for related discussion
+    slice_1 = matrix_input.toarray().shape[0] - 1
+    slice_2 = slice_1
+    slice_3 = slice_2 - 1
+
+    if axis == 0:
+        actual_shape_1 = matrix_input[slice_1:slice_2, :].toarray().shape
+        actual_shape_2 = matrix_input[slice_1:slice_3, :].toarray().shape
+    elif axis == 1:
+        actual_shape_1 = matrix_input[:, slice_1:slice_2].toarray().shape
+        actual_shape_2 = matrix_input[:, slice_1:slice_3].toarray().shape
+    elif axis == 'both':
+        actual_shape_1 = matrix_input[slice_1:slice_2, slice_1:slice_2].toarray().shape
+        actual_shape_2 = matrix_input[slice_1:slice_3, slice_1:slice_3].toarray().shape
+
+    assert actual_shape_1 == expected_shape
+    assert actual_shape_1 == actual_shape_2
+
+
+def test_csr_bool_indexing():
+    data = csr_matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
+    list_indices1 = [False, True, False]
+    array_indices1 = np.array(list_indices1)
+    list_indices2 = [[False, True, False], [False, True, False], [False, True, False]]
+    array_indices2 = np.array(list_indices2)
+    list_indices3 = ([False, True, False], [False, True, False])
+    array_indices3 = (np.array(list_indices3[0]), np.array(list_indices3[1]))
+    slice_list1 = data[list_indices1].toarray()
+    slice_array1 = data[array_indices1].toarray()
+    slice_list2 = data[list_indices2]
+    slice_array2 = data[array_indices2]
+    slice_list3 = data[list_indices3]
+    slice_array3 = data[array_indices3]
+    assert (slice_list1 == slice_array1).all()
+    assert (slice_list2 == slice_array2).all()
+    assert (slice_list3 == slice_array3).all()
+
+
+def test_csr_hstack_int64():
+    """
+    Tests if hstack properly promotes to indices and indptr arrays to np.int64
+    when using np.int32 during concatenation would result in either array
+    overflowing.
+    """
+    max_int32 = np.iinfo(np.int32).max
+
+    # First case: indices would overflow with int32
+    data = [1.0]
+    row = [0]
+
+    max_indices_1 = max_int32 - 1
+    max_indices_2 = 3
+
+    # Individual indices arrays are representable with int32
+    col_1 = [max_indices_1 - 1]
+    col_2 = [max_indices_2 - 1]
+
+    X_1 = csr_matrix((data, (row, col_1)))
+    X_2 = csr_matrix((data, (row, col_2)))
+
+    assert max(max_indices_1 - 1, max_indices_2 - 1) < max_int32
+    assert X_1.indices.dtype == X_1.indptr.dtype == np.int32
+    assert X_2.indices.dtype == X_2.indptr.dtype == np.int32
+
+    # ... but when concatenating their CSR matrices, the resulting indices
+    # array can't be represented with int32 and must be promoted to int64.
+    X_hs = hstack([X_1, X_2], format="csr")
+
+    assert X_hs.indices.max() == max_indices_1 + max_indices_2 - 1
+    assert max_indices_1 + max_indices_2 - 1 > max_int32
+    assert X_hs.indices.dtype == X_hs.indptr.dtype == np.int64
+
+    # Even if the matrices are empty, we must account for their size
+    # contribution so that we may safely set the final elements.
+    X_1_empty = csr_matrix(X_1.shape)
+    X_2_empty = csr_matrix(X_2.shape)
+    X_hs_empty = hstack([X_1_empty, X_2_empty], format="csr")
+
+    assert X_hs_empty.shape == X_hs.shape
+    assert X_hs_empty.indices.dtype == np.int64
+
+    # Should be just small enough to stay in int32 after stack. Note that
+    # we theoretically could support indices.max() == max_int32, but due to an
+    # edge-case in the underlying sparsetools code
+    # (namely the `coo_tocsr` routine),
+    # we require that max(X_hs_32.shape) < max_int32 as well.
+    # Hence we can only support max_int32 - 1.
+    col_3 = [max_int32 - max_indices_1 - 1]
+    X_3 = csr_matrix((data, (row, col_3)))
+    X_hs_32 = hstack([X_1, X_3], format="csr")
+    assert X_hs_32.indices.dtype == np.int32
+    assert X_hs_32.indices.max() == max_int32 - 1
+
+@pytest.mark.parametrize("cls", [csr_matrix, csr_array, csc_matrix, csc_array])
+def test_mixed_index_dtype_int_indexing(cls):
+    # https://github.com/scipy/scipy/issues/20182
+    rng = np.random.default_rng(0)
+    base_mtx = cls(sparse.random(50, 50, random_state=rng, density=0.1))
+    indptr_64bit = base_mtx.copy()
+    indices_64bit = base_mtx.copy()
+    indptr_64bit.indptr = base_mtx.indptr.astype(np.int64)
+    indices_64bit.indices = base_mtx.indices.astype(np.int64)
+
+    for mtx in [base_mtx, indptr_64bit, indices_64bit]:
+        np.testing.assert_array_equal(
+            mtx[[1,2], :].toarray(),
+            base_mtx[[1, 2], :].toarray()
+        )
+        np.testing.assert_array_equal(
+            mtx[:, [1, 2]].toarray(),
+            base_mtx[:, [1, 2]].toarray()
+        )
+
+def test_broadcast_to():
+    a = np.array([1, 0, 2])
+    b = np.array([3])
+    e = np.zeros((0,))
+    res_a = csr_array(a)._broadcast_to((2,3))
+    res_b = csr_array(b)._broadcast_to((4,))
+    res_c = csr_array(b)._broadcast_to((2,4))
+    res_d = csr_array(b)._broadcast_to((1,))
+    res_e = csr_array(e)._broadcast_to((4,0))
+    assert_array_equal(res_a.toarray(), np.broadcast_to(a, (2,3)))
+    assert_array_equal(res_b.toarray(), np.broadcast_to(b, (4,)))
+    assert_array_equal(res_c.toarray(), np.broadcast_to(b, (2,4)))
+    assert_array_equal(res_d.toarray(), np.broadcast_to(b, (1,)))
+    assert_array_equal(res_e.toarray(), np.broadcast_to(e, (4,0)))
+
+    with pytest.raises(ValueError, match="cannot be broadcast"):
+        csr_matrix([[1, 2, 0], [3, 0, 1]])._broadcast_to(shape=(2, 1))
+
+    with pytest.raises(ValueError, match="cannot be broadcast"):
+        csr_matrix([[0, 1, 2]])._broadcast_to(shape=(3, 2))
+
+    with pytest.raises(ValueError, match="cannot be broadcast"):
+        csr_array([0, 1, 2])._broadcast_to(shape=(3, 2))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3deda1668c3f526cfb205131a1348c620f25d20
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_dok.py
@@ -0,0 +1,209 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_equal
+import scipy as sp
+from scipy.sparse import dok_array, dok_matrix
+
+
+pytestmark = pytest.mark.thread_unsafe
+
+
+@pytest.fixture
+def d():
+    return {(0, 1): 1, (0, 2): 2}
+
+@pytest.fixture
+def A():
+    return np.array([[0, 1, 2], [0, 0, 0], [0, 0, 0]])
+
+@pytest.fixture(params=[dok_array, dok_matrix])
+def Asp(request):
+    A = request.param((3, 3))
+    A[(0, 1)] = 1
+    A[(0, 2)] = 2
+    yield A
+
+# Note: __iter__ and comparison dunders act like ndarrays for DOK, not dict.
+# Dunders reversed, or, ror, ior work as dict for dok_matrix, raise for dok_array
+# All other dict methods on DOK format act like dict methods (with extra checks).
+
+# Start of tests
+################
+def test_dict_methods_covered(d, Asp):
+    d_methods = set(dir(d)) - {"__class_getitem__"}
+    asp_methods = set(dir(Asp))
+    assert d_methods < asp_methods
+
+def test_clear(d, Asp):
+    assert d.items() == Asp.items()
+    d.clear()
+    Asp.clear()
+    assert d.items() == Asp.items()
+
+def test_copy(d, Asp):
+    assert d.items() == Asp.items()
+    dd = d.copy()
+    asp = Asp.copy()
+    assert dd.items() == asp.items()
+    assert asp.items() == Asp.items()
+    asp[(0, 1)] = 3
+    assert Asp[(0, 1)] == 1
+
+def test_fromkeys_default():
+    # test with default value
+    edges = [(0, 2), (1, 0), (2, 1)]
+    Xdok = dok_array.fromkeys(edges)
+    X = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]
+    assert_equal(Xdok.toarray(), X)
+
+def test_fromkeys_positional():
+    # test with positional value
+    edges = [(0, 2), (1, 0), (2, 1)]
+    Xdok = dok_array.fromkeys(edges, -1)
+    X = [[0, 0, -1], [-1, 0, 0], [0, -1, 0]]
+    assert_equal(Xdok.toarray(), X)
+
+def test_fromkeys_iterator():
+    it = ((a, a % 2) for a in range(4))
+    Xdok = dok_array.fromkeys(it)
+    X = [[1, 0], [0, 1], [1, 0], [0, 1]]
+    assert_equal(Xdok.toarray(), X)
+
+def test_get(d, Asp):
+    assert Asp.get((0, 1)) == d.get((0, 1))
+    assert Asp.get((0, 0), 99) == d.get((0, 0), 99)
+    with pytest.raises(IndexError, match="out of bounds"):
+        Asp.get((0, 4), 99)
+
+def test_items(d, Asp):
+    assert Asp.items() == d.items()
+
+def test_keys(d, Asp):
+    assert Asp.keys() == d.keys()
+
+def test_pop(d, Asp):
+    assert d.pop((0, 1)) == 1
+    assert Asp.pop((0, 1)) == 1
+    assert d.items() == Asp.items()
+
+    assert Asp.pop((22, 21), None) is None
+    assert Asp.pop((22, 21), "other") == "other"
+    with pytest.raises(KeyError, match="(22, 21)"):
+        Asp.pop((22, 21))
+    with pytest.raises(TypeError, match="got an unexpected keyword argument"):
+        Asp.pop((22, 21), default=5)
+
+def test_popitem(d, Asp):
+    assert d.popitem() == Asp.popitem()
+    assert d.items() == Asp.items()
+
+def test_setdefault(d, Asp):
+    assert Asp.setdefault((0, 1), 4) == 1
+    assert Asp.setdefault((2, 2), 4) == 4
+    d.setdefault((0, 1), 4)
+    d.setdefault((2, 2), 4)
+    assert d.items() == Asp.items()
+
+def test_update(d, Asp):
+    with pytest.raises(NotImplementedError):
+        Asp.update(Asp)
+
+def test_values(d, Asp):
+    # Note: dict.values are strange: d={1: 1}; d.values() == d.values() is False
+    # Using list(d.values()) makes them comparable.
+    assert list(Asp.values()) == list(d.values())
+
+def test_dunder_getitem(d, Asp):
+    assert Asp[(0, 1)] == d[(0, 1)]
+
+def test_dunder_setitem(d, Asp):
+    Asp[(1, 1)] = 5
+    d[(1, 1)] = 5
+    assert d.items() == Asp.items()
+
+def test_dunder_delitem(d, Asp):
+    del Asp[(0, 1)]
+    del d[(0, 1)]
+    assert d.items() == Asp.items()
+
+def test_dunder_contains(d, Asp):
+    assert ((0, 1) in d) == ((0, 1) in Asp)
+    assert ((0, 0) in d) == ((0, 0) in Asp)
+
+def test_dunder_len(d, Asp):
+    assert len(d) == len(Asp)
+
+# Note: dunders reversed, or, ror, ior work as dict for dok_matrix, raise for dok_array
+def test_dunder_reversed(d, Asp):
+    if isinstance(Asp, dok_array):
+        with pytest.raises(TypeError):
+            list(reversed(Asp))
+    else:
+        assert list(reversed(Asp)) == list(reversed(d))
+
+def test_dunder_ior(d, Asp):
+    if isinstance(Asp, dok_array):
+        with pytest.raises(TypeError):
+            Asp |= Asp
+    else:
+        dd = {(0, 0): 5}
+        Asp |= dd
+        assert Asp[(0, 0)] == 5
+        d |= dd
+        assert d.items() == Asp.items()
+        dd |= Asp
+        assert dd.items() == Asp.items()
+
+def test_dunder_or(d, Asp):
+    if isinstance(Asp, dok_array):
+        with pytest.raises(TypeError):
+            Asp | Asp
+    else:
+        assert d | d == Asp | d
+        assert d | d == Asp | Asp
+
+def test_dunder_ror(d, Asp):
+    if isinstance(Asp, dok_array):
+        with pytest.raises(TypeError):
+            Asp | Asp
+        with pytest.raises(TypeError):
+            d | Asp
+    else:
+        assert Asp.__ror__(d) == Asp.__ror__(Asp)
+        assert d.__ror__(d) == Asp.__ror__(d)
+        assert d | Asp
+
+# Note: comparison dunders, e.g. ==, >=, etc follow np.array not dict
+def test_dunder_eq(A, Asp):
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(sp.sparse.SparseEfficiencyWarning)
+        assert (Asp == Asp).toarray().all()
+        assert (A == Asp).all()
+
+def test_dunder_ne(A, Asp):
+    assert not (Asp != Asp).toarray().any()
+    assert not (A != Asp).any()
+
+def test_dunder_lt(A, Asp):
+    assert not (Asp < Asp).toarray().any()
+    assert not (A < Asp).any()
+
+def test_dunder_gt(A, Asp):
+    assert not (Asp > Asp).toarray().any()
+    assert not (A > Asp).any()
+
+def test_dunder_le(A, Asp):
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(sp.sparse.SparseEfficiencyWarning)
+        assert (Asp <= Asp).toarray().all()
+        assert (A <= Asp).all()
+
+def test_dunder_ge(A, Asp):
+    with np.testing.suppress_warnings() as sup:
+        sup.filter(sp.sparse.SparseEfficiencyWarning)
+        assert (Asp >= Asp).toarray().all()
+        assert (A >= Asp).all()
+
+# Note: iter dunder follows np.array not dict
+def test_dunder_iter(A, Asp):
+    assert all((a == asp).all() for a, asp in zip(A, Asp))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7c9f68bb2bde76d74ca767abba3c99b89d6e771
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_extract.py
@@ -0,0 +1,51 @@
+"""test sparse matrix construction functions"""
+
+from numpy.testing import assert_equal
+from scipy.sparse import csr_matrix, csr_array, sparray
+
+import numpy as np
+from scipy.sparse import _extract
+
+
+class TestExtract:
+    def setup_method(self):
+        self.cases = [
+            csr_array([[1,2]]),
+            csr_array([[1,0]]),
+            csr_array([[0,0]]),
+            csr_array([[1],[2]]),
+            csr_array([[1],[0]]),
+            csr_array([[0],[0]]),
+            csr_array([[1,2],[3,4]]),
+            csr_array([[0,1],[0,0]]),
+            csr_array([[0,0],[1,0]]),
+            csr_array([[0,0],[0,0]]),
+            csr_array([[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]]),
+            csr_array([[1,2,0,0,3],[4,5,0,6,7],[0,0,8,9,0]]).T,
+        ]
+
+    def test_find(self):
+        for A in self.cases:
+            I,J,V = _extract.find(A)
+            B = csr_array((V,(I,J)), shape=A.shape)
+            assert_equal(A.toarray(), B.toarray())
+
+    def test_tril(self):
+        for A in self.cases:
+            B = A.toarray()
+            for k in [-3,-2,-1,0,1,2,3]:
+                assert_equal(_extract.tril(A,k=k).toarray(), np.tril(B,k=k))
+
+    def test_triu(self):
+        for A in self.cases:
+            B = A.toarray()
+            for k in [-3,-2,-1,0,1,2,3]:
+                assert_equal(_extract.triu(A,k=k).toarray(), np.triu(B,k=k))
+
+    def test_array_vs_matrix(self):
+        for A in self.cases:
+            assert isinstance(_extract.tril(A), sparray)
+            assert isinstance(_extract.triu(A), sparray)
+            M = csr_matrix(A)
+            assert not isinstance(_extract.tril(M), sparray)
+            assert not isinstance(_extract.triu(M), sparray)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_indexing1d.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_indexing1d.py
new file mode 100644
index 0000000000000000000000000000000000000000..99934c455b796511b9f48243da044a9cee8a4d53
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_indexing1d.py
@@ -0,0 +1,603 @@
+import contextlib
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+
+from scipy.sparse import csr_array, dok_array, SparseEfficiencyWarning
+from .test_arithmetic1d import toarray
+
+
+formats_for_index1d = [csr_array, dok_array]
+
+
+@contextlib.contextmanager
+def check_remains_sorted(X):
+    """Checks that sorted indices property is retained through an operation"""
+    yield
+    if not hasattr(X, 'has_sorted_indices') or not X.has_sorted_indices:
+        return
+    indices = X.indices.copy()
+    X.has_sorted_indices = False
+    X.sort_indices()
+    assert_equal(indices, X.indices, 'Expected sorted indices, found unsorted')
+
+
+@pytest.mark.parametrize("spcreator", formats_for_index1d)
+class TestGetSet1D:
+    def test_None_index(self, spcreator):
+        D = np.array([4, 3, 0])
+        A = spcreator(D)
+
+        N = D.shape[0]
+        for j in range(-N, N):
+            assert_equal(A[j, None].toarray(), D[j, None])
+            assert_equal(A[None, j].toarray(), D[None, j])
+            assert_equal(A[None, None, j].toarray(), D[None, None, j])
+
+    def test_getitem_shape(self, spcreator):
+        A = spcreator(np.arange(3 * 4).reshape(3, 4))
+        assert A[1, 2].ndim == 0
+        assert A[1, 2:3].shape == (1,)
+        assert A[None, 1, 2:3].shape == (1, 1)
+        assert A[None, 1, 2].shape == (1,)
+        assert A[None, 1, 2, None].shape == (1, 1)
+
+        # see gh-22458
+        assert A[None, 1].shape == (1, 4)
+        assert A[1, None].shape == (1, 4)
+        assert A[None, 1, :].shape == (1, 4)
+        assert A[1, None, :].shape == (1, 4)
+        assert A[1, :, None].shape == (4, 1)
+
+        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
+            A[None, 2, 1, None, None]
+        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
+            A[None, 0:2, None, 1]
+        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
+            A[0:1, 1:, None]
+        with pytest.raises(IndexError, match='Only 1D or 2D arrays'):
+            A[1:, 1, None, None]
+
+    def test_getelement(self, spcreator):
+        D = np.array([4, 3, 0])
+        A = spcreator(D)
+
+        N = D.shape[0]
+        for j in range(-N, N):
+            assert_equal(A[j], D[j])
+
+        for ij in [3, -4]:
+            with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'):
+                A.__getitem__(ij)
+
+        # single element tuples unwrapped
+        assert A[(0,)] == 4
+
+        with pytest.raises(IndexError, match='index (.*) out of (range|bounds)'):
+            A.__getitem__((4,))
+
+    def test_setelement(self, spcreator):
+        dtype = np.float64
+        A = spcreator((12,), dtype=dtype)
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            A[0] = dtype(0)
+            A[1] = dtype(3)
+            A[8] = dtype(9.0)
+            A[-2] = dtype(7)
+            A[5] = 9
+
+            A[-9,] = dtype(8)
+            A[1,] = dtype(5)  # overwrite using 1-tuple index
+
+            for ij in [13, -14, (13,), (14,)]:
+                with pytest.raises(IndexError, match='out of (range|bounds)'):
+                    A.__setitem__(ij, 123.0)
+
+
+@pytest.mark.parametrize("spcreator", formats_for_index1d)
+class TestSlicingAndFancy1D:
+    #######################
+    #  Int-like Array Index
+    #######################
+    def test_get_array_index(self, spcreator):
+        D = np.array([4, 3, 0])
+        A = spcreator(D)
+
+        assert_equal(A[()].toarray(), D[()])
+        for ij in [(0, 3), (3,)]:
+            with pytest.raises(IndexError, match='out of (range|bounds)|many indices'):
+                A.__getitem__(ij)
+
+    def test_set_array_index(self, spcreator):
+        dtype = np.float64
+        A = spcreator((12,), dtype=dtype)
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            A[np.array(6)] = dtype(4.0)  # scalar index
+            A[np.array(6)] = dtype(2.0)  # overwrite with scalar index
+            assert_equal(A.toarray(), [0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0])
+
+            for ij in [(13,), (-14,)]:
+                with pytest.raises(IndexError, match='index .* out of (range|bounds)'):
+                    A.__setitem__(ij, 123.0)
+
+            for v in [(), (0, 3), [1, 2, 3], np.array([1, 2, 3])]:
+                msg = 'Trying to assign a sequence to an item'
+                with pytest.raises(ValueError, match=msg):
+                    A.__setitem__(0, v)
+
+    ####################
+    #  1d Slice as index
+    ####################
+    def test_dtype_preservation(self, spcreator):
+        assert_equal(spcreator((10,), dtype=np.int16)[1:5].dtype, np.int16)
+        assert_equal(spcreator((6,), dtype=np.int32)[0:0:2].dtype, np.int32)
+        assert_equal(spcreator((6,), dtype=np.int64)[:].dtype, np.int64)
+
+    def test_get_1d_slice(self, spcreator):
+        B = np.arange(50.)
+        A = spcreator(B)
+        assert_equal(B[:], A[:].toarray())
+        assert_equal(B[2:5], A[2:5].toarray())
+
+        C = np.array([4, 0, 6, 0, 0, 0, 0, 0, 1])
+        D = spcreator(C)
+        assert_equal(C[1:3], D[1:3].toarray())
+
+        # Now test slicing when a row contains only zeros
+        E = np.array([0, 0, 0, 0, 0])
+        F = spcreator(E)
+        assert_equal(E[1:3], F[1:3].toarray())
+        assert_equal(E[-2:], F[-2:].toarray())
+        assert_equal(E[:], F[:].toarray())
+        assert_equal(E[slice(None)], F[slice(None)].toarray())
+
+    def test_slicing_idx_slice(self, spcreator):
+        B = np.arange(50)
+        A = spcreator(B)
+
+        # [i]
+        assert_equal(A[2], B[2])
+        assert_equal(A[-1], B[-1])
+        assert_equal(A[np.array(-2)], B[-2])
+
+        # [1:2]
+        assert_equal(A[:].toarray(), B[:])
+        assert_equal(A[5:-2].toarray(), B[5:-2])
+        assert_equal(A[5:12:3].toarray(), B[5:12:3])
+
+        # int8 slice
+        s = slice(np.int8(2), np.int8(4), None)
+        assert_equal(A[s].toarray(), B[2:4])
+
+        # np.s_
+        s_ = np.s_
+        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
+                  s_[15:20], s_[3:2],
+                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
+                  0, 1, s_[:], s_[1:5], -1, -2, -5,
+                  np.array(-1), np.int8(-3)]
+
+        for j, a in enumerate(slices):
+            x = A[a]
+            y = B[a]
+            if y.shape == ():
+                assert_equal(x, y, repr(a))
+            else:
+                if x.size == 0 and y.size == 0:
+                    pass
+                else:
+                    assert_equal(x.toarray(), y, repr(a))
+
+    def test_ellipsis_1d_slicing(self, spcreator):
+        B = np.arange(50)
+        A = spcreator(B)
+        assert_equal(A[...].toarray(), B[...])
+        assert_equal(A[...,].toarray(), B[...,])
+
+    ##########################
+    #  Assignment with Slicing
+    ##########################
+    def test_slice_scalar_assign(self, spcreator):
+        A = spcreator((5,))
+        B = np.zeros((5,))
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            for C in [A, B]:
+                C[0:1] = 1
+                C[2:0] = 4
+                C[2:3] = 9
+                C[3:] = 1
+                C[3::-1] = 9
+        assert_equal(A.toarray(), B)
+
+    def test_slice_assign_2(self, spcreator):
+        shape = (10,)
+
+        for idx in [slice(3), slice(None, 10, 4), slice(5, -2)]:
+            A = spcreator(shape)
+            with np.testing.suppress_warnings() as sup:
+                sup.filter(
+                    SparseEfficiencyWarning,
+                    "Changing the sparsity structure of .* is expensive",
+                )
+                A[idx] = 1
+            B = np.zeros(shape)
+            B[idx] = 1
+            msg = f"idx={idx!r}"
+            assert_allclose(A.toarray(), B, err_msg=msg)
+
+    def test_self_self_assignment(self, spcreator):
+        # Tests whether a row of one lil_matrix can be assigned to another.
+        B = spcreator((5,))
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            B[0] = 2
+            B[1] = 0
+            B[2] = 3
+            B[3] = 10
+
+            A = B / 10
+            B[:] = A[:]
+            assert_equal(A[:].toarray(), B[:].toarray())
+
+            A = B / 10
+            B[:] = A[:1]
+            assert_equal(np.zeros((5,)) + A[0], B.toarray())
+
+            A = B / 10
+            B[:-1] = A[1:]
+            assert_equal(A[1:].toarray(), B[:-1].toarray())
+
+    def test_slice_assignment(self, spcreator):
+        B = spcreator((4,))
+        expected = np.array([10, 0, 14, 0])
+        block = [2, 1]
+
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            B[0] = 5
+            B[2] = 7
+            B[:] = B + B
+            assert_equal(B.toarray(), expected)
+
+            B[:2] = csr_array(block)
+            assert_equal(B.toarray()[:2], block)
+
+    def test_set_slice(self, spcreator):
+        A = spcreator((5,))
+        B = np.zeros(5, float)
+        s_ = np.s_
+        slices = [s_[:2], s_[1:2], s_[3:], s_[3::2],
+                  s_[8:3:-1], s_[4::-2], s_[:5:-1],
+                  0, 1, s_[:], s_[1:5], -1, -2, -5,
+                  np.array(-1), np.int8(-3)]
+
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            for j, a in enumerate(slices):
+                A[a] = j
+                B[a] = j
+                assert_equal(A.toarray(), B, repr(a))
+
+            A[1:10:2] = range(1, 5, 2)
+            B[1:10:2] = range(1, 5, 2)
+            assert_equal(A.toarray(), B)
+
+        # The next commands should raise exceptions
+        toobig = list(range(100))
+        with pytest.raises(ValueError, match='Trying to assign a sequence to an item'):
+            A.__setitem__(0, toobig)
+        with pytest.raises(ValueError, match='could not be broadcast together'):
+            A.__setitem__(slice(None), toobig)
+
+    def test_assign_empty(self, spcreator):
+        A = spcreator(np.ones(3))
+        B = spcreator((2,))
+        A[:2] = B
+        assert_equal(A.toarray(), [0, 0, 1])
+
+    ####################
+    #  1d Fancy Indexing
+    ####################
+    def test_dtype_preservation_empty_index(self, spcreator):
+        A = spcreator((2,), dtype=np.int16)
+        assert_equal(A[[False, False]].dtype, np.int16)
+        assert_equal(A[[]].dtype, np.int16)
+
+    def test_bad_index(self, spcreator):
+        A = spcreator(np.zeros(5))
+        with pytest.raises(
+            (IndexError, ValueError, TypeError),
+            match='Index dimension must be 1 or 2|only integers',
+        ):
+            A.__getitem__("foo")
+        with pytest.raises(
+            (IndexError, ValueError, TypeError),
+            match='tuple index out of range|only integers',
+        ):
+            A.__getitem__((2, "foo"))
+
+    def test_fancy_indexing_2darray(self, spcreator):
+        B = np.arange(50).reshape((5, 10))
+        A = spcreator(B)
+
+        # [i]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+
+        # [i,[1,2]]
+        assert_equal(A[3, [1, 3]].toarray(), B[3, [1, 3]])
+        assert_equal(A[-1, [2, -5]].toarray(), B[-1, [2, -5]])
+        assert_equal(A[np.array(-1), [2, -5]].toarray(), B[-1, [2, -5]])
+        assert_equal(A[-1, np.array([2, -5])].toarray(), B[-1, [2, -5]])
+        assert_equal(A[np.array(-1), np.array([2, -5])].toarray(), B[-1, [2, -5]])
+
+        # [1:2,[1,2]]
+        assert_equal(A[:, [2, 8, 3, -1]].toarray(), B[:, [2, 8, 3, -1]])
+        assert_equal(A[3:4, [9]].toarray(), B[3:4, [9]])
+        assert_equal(A[1:4, [-1, -5]].toarray(), B[1:4, [-1, -5]])
+        assert_equal(A[1:4, np.array([-1, -5])].toarray(), B[1:4, [-1, -5]])
+
+        # [[1,2],j]
+        assert_equal(A[[1, 3], 3].toarray(), B[[1, 3], 3])
+        assert_equal(A[[2, -5], -4].toarray(), B[[2, -5], -4])
+        assert_equal(A[np.array([2, -5]), -4].toarray(), B[[2, -5], -4])
+        assert_equal(A[[2, -5], np.array(-4)].toarray(), B[[2, -5], -4])
+        assert_equal(A[np.array([2, -5]), np.array(-4)].toarray(), B[[2, -5], -4])
+
+        # [[1,2],1:2]
+        assert_equal(A[[1, 3], :].toarray(), B[[1, 3], :])
+        assert_equal(A[[2, -5], 8:-1].toarray(), B[[2, -5], 8:-1])
+        assert_equal(A[np.array([2, -5]), 8:-1].toarray(), B[[2, -5], 8:-1])
+
+        # [[1,2],[1,2]]
+        assert_equal(toarray(A[[1, 3], [2, 4]]), B[[1, 3], [2, 4]])
+        assert_equal(toarray(A[[-1, -3], [2, -4]]), B[[-1, -3], [2, -4]])
+        assert_equal(
+            toarray(A[np.array([-1, -3]), [2, -4]]), B[[-1, -3], [2, -4]]
+        )
+        assert_equal(
+            toarray(A[[-1, -3], np.array([2, -4])]), B[[-1, -3], [2, -4]]
+        )
+        assert_equal(
+            toarray(A[np.array([-1, -3]), np.array([2, -4])]), B[[-1, -3], [2, -4]]
+        )
+
+        # [[[1],[2]],[1,2]]
+        assert_equal(A[[[1], [3]], [2, 4]].toarray(), B[[[1], [3]], [2, 4]])
+        assert_equal(
+            A[[[-1], [-3], [-2]], [2, -4]].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[np.array([[-1], [-3], [-2]]), [2, -4]].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[[[-1], [-3], [-2]], np.array([2, -4])].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+        assert_equal(
+            A[np.array([[-1], [-3], [-2]]), np.array([2, -4])].toarray(),
+            B[[[-1], [-3], [-2]], [2, -4]]
+        )
+
+        # [[1,2]]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+        assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
+        assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]])
+
+        # [[1,2],:][:,[1,2]]
+        assert_equal(
+            A[[1, 3], :][:, [2, 4]].toarray(), B[[1, 3], :][:, [2, 4]]
+        )
+        assert_equal(
+            A[[-1, -3], :][:, [2, -4]].toarray(), B[[-1, -3], :][:, [2, -4]]
+        )
+        assert_equal(
+            A[np.array([-1, -3]), :][:, np.array([2, -4])].toarray(),
+            B[[-1, -3], :][:, [2, -4]]
+        )
+
+        # [:,[1,2]][[1,2],:]
+        assert_equal(
+            A[:, [1, 3]][[2, 4], :].toarray(), B[:, [1, 3]][[2, 4], :]
+        )
+        assert_equal(
+            A[:, [-1, -3]][[2, -4], :].toarray(), B[:, [-1, -3]][[2, -4], :]
+        )
+        assert_equal(
+            A[:, np.array([-1, -3])][np.array([2, -4]), :].toarray(),
+            B[:, [-1, -3]][[2, -4], :]
+        )
+
+    def test_fancy_indexing(self, spcreator):
+        B = np.arange(50)
+        A = spcreator(B)
+
+        # [i]
+        assert_equal(A[[3]].toarray(), B[[3]])
+
+        # [np.array]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+        assert_equal(A[[2, -5]].toarray(), B[[2, -5]])
+        assert_equal(A[np.array(-1)], B[-1])
+        assert_equal(A[np.array([-1, 2])].toarray(), B[[-1, 2]])
+        assert_equal(A[np.array(5)], B[np.array(5)])
+
+        # [[[1],[2]]]
+        ind = np.array([[1], [3]])
+        assert_equal(A[ind].toarray(), B[ind])
+        ind = np.array([[-1], [-3], [-2]])
+        assert_equal(A[ind].toarray(), B[ind])
+
+        # [[1, 2]]
+        assert_equal(A[[1, 3]].toarray(), B[[1, 3]])
+        assert_equal(A[[-1, -3]].toarray(), B[[-1, -3]])
+        assert_equal(A[np.array([-1, -3])].toarray(), B[[-1, -3]])
+
+        # [[1, 2]][[1, 2]]
+        assert_equal(A[[1, 5, 2, 8]][[1, 3]].toarray(),
+                     B[[1, 5, 2, 8]][[1, 3]])
+        assert_equal(A[[-1, -5, 2, 8]][[1, -4]].toarray(),
+                     B[[-1, -5, 2, 8]][[1, -4]])
+
+    def test_fancy_indexing_boolean(self, spcreator):
+        np.random.seed(1234)  # make runs repeatable
+
+        B = np.arange(50)
+        A = spcreator(B)
+
+        I = np.array(np.random.randint(0, 2, size=50), dtype=bool)
+
+        assert_equal(toarray(A[I]), B[I])
+        assert_equal(toarray(A[B > 9]), B[B > 9])
+
+        Z1 = np.zeros(51, dtype=bool)
+        Z2 = np.zeros(51, dtype=bool)
+        Z2[-1] = True
+        Z3 = np.zeros(51, dtype=bool)
+        Z3[0] = True
+
+        msg = 'bool index .* has shape|boolean index did not match'
+        with pytest.raises(IndexError, match=msg):
+            A.__getitem__(Z1)
+        with pytest.raises(IndexError, match=msg):
+            A.__getitem__(Z2)
+        with pytest.raises(IndexError, match=msg):
+            A.__getitem__(Z3)
+
+    def test_fancy_indexing_sparse_boolean(self, spcreator):
+        np.random.seed(1234)  # make runs repeatable
+
+        B = np.arange(20)
+        A = spcreator(B)
+
+        X = np.array(np.random.randint(0, 2, size=20), dtype=bool)
+        Xsp = csr_array(X)
+
+        assert_equal(toarray(A[Xsp]), B[X])
+        assert_equal(toarray(A[A > 9]), B[B > 9])
+
+        Y = np.array(np.random.randint(0, 2, size=60), dtype=bool)
+
+        Ysp = csr_array(Y)
+
+        with pytest.raises(IndexError, match='bool index .* has shape|only integers'):
+            A.__getitem__(Ysp)
+        with pytest.raises(IndexError, match='tuple index out of range|only integers'):
+            A.__getitem__((Xsp, 1))
+
+    def test_fancy_indexing_seq_assign(self, spcreator):
+        mat = spcreator(np.array([1, 0]))
+        with pytest.raises(ValueError, match='Trying to assign a sequence to an item'):
+            mat.__setitem__(0, np.array([1, 2]))
+
+    def test_fancy_indexing_empty(self, spcreator):
+        B = np.arange(50)
+        B[3:9] = 0
+        B[30] = 0
+        A = spcreator(B)
+
+        K = np.array([False] * 50)
+        assert_equal(toarray(A[K]), B[K])
+        K = np.array([], dtype=int)
+        assert_equal(toarray(A[K]), B[K])
+        J = np.array([0, 1, 2, 3, 4], dtype=int)
+        assert_equal(toarray(A[J]), B[J])
+
+    ############################
+    #  1d Fancy Index Assignment
+    ############################
+    def test_bad_index_assign(self, spcreator):
+        A = spcreator(np.zeros(5))
+        msg = 'Index dimension must be 1 or 2|only integers'
+        with pytest.raises((IndexError, ValueError, TypeError), match=msg):
+            A.__setitem__("foo", 2)
+
+    def test_fancy_indexing_set(self, spcreator):
+        M = (5,)
+
+        # [1:2]
+        for j in [[2, 3, 4], slice(None, 10, 4), np.arange(3),
+                     slice(5, -2), slice(2, 5)]:
+            A = spcreator(M)
+            B = np.zeros(M)
+            with np.testing.suppress_warnings() as sup:
+                sup.filter(
+                    SparseEfficiencyWarning,
+                    "Changing the sparsity structure of .* is expensive",
+                )
+                B[j] = 1
+                with check_remains_sorted(A):
+                    A[j] = 1
+            assert_allclose(A.toarray(), B)
+
+    def test_sequence_assignment(self, spcreator):
+        A = spcreator((4,))
+        B = spcreator((3,))
+
+        i0 = [0, 1, 2]
+        i1 = (0, 1, 2)
+        i2 = np.array(i0)
+
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(
+                SparseEfficiencyWarning,
+                "Changing the sparsity structure of .* is expensive",
+            )
+            with check_remains_sorted(A):
+                A[i0] = B[i0]
+                msg = "too many indices for array|tuple index out of range"
+                with pytest.raises(IndexError, match=msg):
+                    B.__getitem__(i1)
+                A[i2] = B[i2]
+            assert_equal(A[:3].toarray(), B.toarray())
+            assert A.shape == (4,)
+
+            # slice
+            A = spcreator((4,))
+            with check_remains_sorted(A):
+                A[1:3] = [10, 20]
+            assert_equal(A.toarray(), [0, 10, 20, 0])
+
+            # array
+            A = spcreator((4,))
+            B = np.zeros(4)
+            with check_remains_sorted(A):
+                for C in [A, B]:
+                    C[[0, 1, 2]] = [4, 5, 6]
+            assert_equal(A.toarray(), B)
+
+    def test_fancy_assign_empty(self, spcreator):
+        B = np.arange(50)
+        B[2] = 0
+        B[[3, 6]] = 0
+        A = spcreator(B)
+
+        K = np.array([False] * 50)
+        A[K] = 42
+        assert_equal(A.toarray(), B)
+
+        K = np.array([], dtype=int)
+        A[K] = 42
+        assert_equal(A.toarray(), B)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..90b4ea64a8928073eb5dd3f1b2752379f57327d9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_matrix_io.py
@@ -0,0 +1,109 @@
+import os
+import numpy as np
+import tempfile
+
+from pytest import raises as assert_raises
+from numpy.testing import assert_equal, assert_
+
+from scipy.sparse import (sparray, csc_matrix, csr_matrix, bsr_matrix, dia_matrix,
+                          coo_matrix, dok_matrix, csr_array, save_npz, load_npz)
+
+
+DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
+
+
+def _save_and_load(matrix):
+    fd, tmpfile = tempfile.mkstemp(suffix='.npz')
+    os.close(fd)
+    try:
+        save_npz(tmpfile, matrix)
+        loaded_matrix = load_npz(tmpfile)
+    finally:
+        os.remove(tmpfile)
+    return loaded_matrix
+
+def _check_save_and_load(dense_matrix):
+    for matrix_class in [csc_matrix, csr_matrix, bsr_matrix, dia_matrix, coo_matrix]:
+        matrix = matrix_class(dense_matrix)
+        loaded_matrix = _save_and_load(matrix)
+        assert_(type(loaded_matrix) is matrix_class)
+        assert_(loaded_matrix.shape == dense_matrix.shape)
+        assert_(loaded_matrix.dtype == dense_matrix.dtype)
+        assert_equal(loaded_matrix.toarray(), dense_matrix)
+
+def test_save_and_load_random():
+    N = 10
+    np.random.seed(0)
+    dense_matrix = np.random.random((N, N))
+    dense_matrix[dense_matrix > 0.7] = 0
+    _check_save_and_load(dense_matrix)
+
+def test_save_and_load_empty():
+    dense_matrix = np.zeros((4,6))
+    _check_save_and_load(dense_matrix)
+
+def test_save_and_load_one_entry():
+    dense_matrix = np.zeros((4,6))
+    dense_matrix[1,2] = 1
+    _check_save_and_load(dense_matrix)
+
+def test_sparray_vs_spmatrix():
+    #save/load matrix
+    fd, tmpfile = tempfile.mkstemp(suffix='.npz')
+    os.close(fd)
+    try:
+        save_npz(tmpfile, csr_matrix([[1.2, 0, 0.9], [0, 0.3, 0]]))
+        loaded_matrix = load_npz(tmpfile)
+    finally:
+        os.remove(tmpfile)
+
+    #save/load array
+    fd, tmpfile = tempfile.mkstemp(suffix='.npz')
+    os.close(fd)
+    try:
+        save_npz(tmpfile, csr_array([[1.2, 0, 0.9], [0, 0.3, 0]]))
+        loaded_array = load_npz(tmpfile)
+    finally:
+        os.remove(tmpfile)
+
+    assert not isinstance(loaded_matrix, sparray)
+    assert isinstance(loaded_array, sparray)
+    assert_(loaded_matrix.dtype == loaded_array.dtype)
+    assert_equal(loaded_matrix.toarray(), loaded_array.toarray())
+
+def test_malicious_load():
+    class Executor:
+        def __reduce__(self):
+            return (assert_, (False, 'unexpected code execution'))
+
+    fd, tmpfile = tempfile.mkstemp(suffix='.npz')
+    os.close(fd)
+    try:
+        np.savez(tmpfile, format=Executor())
+
+        # Should raise a ValueError, not execute code
+        assert_raises(ValueError, load_npz, tmpfile)
+    finally:
+        os.remove(tmpfile)
+
+
+def test_py23_compatibility():
+    # Try loading files saved on Python 2 and Python 3.  They are not
+    # the same, since files saved with SciPy versions < 1.0.0 may
+    # contain unicode.
+
+    a = load_npz(os.path.join(DATA_DIR, 'csc_py2.npz'))
+    b = load_npz(os.path.join(DATA_DIR, 'csc_py3.npz'))
+    c = csc_matrix([[0]])
+
+    assert_equal(a.toarray(), c.toarray())
+    assert_equal(b.toarray(), c.toarray())
+
+def test_implemented_error():
+    # Attempts to save an unsupported type and checks that an
+    # NotImplementedError is raised.
+
+    x = dok_matrix((2,3))
+    x[0,1] = 1
+
+    assert_raises(NotImplementedError, save_npz, 'x.npz', x)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py
new file mode 100644
index 0000000000000000000000000000000000000000..dca3f44fa485070805995c2f76c0c511123ce355
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_minmax1d.py
@@ -0,0 +1,128 @@
+"""Test of min-max 1D features of sparse array classes"""
+
+import pytest
+
+import numpy as np
+
+from numpy.testing import assert_equal, assert_array_equal
+
+from scipy.sparse import coo_array, csr_array, csc_array, bsr_array
+from scipy.sparse import coo_matrix, csr_matrix, csc_matrix, bsr_matrix
+from scipy.sparse._sputils import isscalarlike
+
+
+def toarray(a):
+    if isinstance(a, np.ndarray) or isscalarlike(a):
+        return a
+    return a.toarray()
+
+
+formats_for_minmax = [bsr_array, coo_array, csc_array, csr_array]
+formats_for_minmax_supporting_1d = [coo_array, csr_array]
+
+
+@pytest.mark.parametrize("spcreator", formats_for_minmax_supporting_1d)
+class Test_MinMaxMixin1D:
+    def test_minmax(self, spcreator):
+        D = np.arange(5)
+        X = spcreator(D)
+
+        assert_equal(X.min(), 0)
+        assert_equal(X.max(), 4)
+        assert_equal((-X).min(), -4)
+        assert_equal((-X).max(), 0)
+
+    def test_minmax_axis(self, spcreator):
+        D = np.arange(50)
+        X = spcreator(D)
+
+        for axis in [0, -1]:
+            assert_array_equal(
+                toarray(X.max(axis=axis)), D.max(axis=axis, keepdims=True)
+            )
+            assert_array_equal(
+                toarray(X.min(axis=axis)), D.min(axis=axis, keepdims=True)
+            )
+        for axis in [-2, 1]:
+            with pytest.raises(ValueError, match="axis out of range"):
+                X.min(axis=axis)
+            with pytest.raises(ValueError, match="axis out of range"):
+                X.max(axis=axis)
+
+    def test_numpy_minmax(self, spcreator):
+        dat = np.array([0, 1, 2])
+        datsp = spcreator(dat)
+        assert_array_equal(np.min(datsp), np.min(dat))
+        assert_array_equal(np.max(datsp), np.max(dat))
+
+
+    def test_argmax(self, spcreator):
+        D1 = np.array([-1, 5, 2, 3])
+        D2 = np.array([0, 0, -1, -2])
+        D3 = np.array([-1, -2, -3, -4])
+        D4 = np.array([1, 2, 3, 4])
+        D5 = np.array([1, 2, 0, 0])
+
+        for D in [D1, D2, D3, D4, D5]:
+            mat = spcreator(D)
+
+            assert_equal(mat.argmax(), np.argmax(D))
+            assert_equal(mat.argmin(), np.argmin(D))
+
+            assert_equal(mat.argmax(axis=0), np.argmax(D, axis=0))
+            assert_equal(mat.argmin(axis=0), np.argmin(D, axis=0))
+
+        D6 = np.empty((0,))
+
+        for axis in [None, 0]:
+            mat = spcreator(D6)
+            with pytest.raises(ValueError, match="to an empty matrix"):
+                mat.argmin(axis=axis)
+            with pytest.raises(ValueError, match="to an empty matrix"):
+                mat.argmax(axis=axis)
+
+
+@pytest.mark.parametrize("spcreator", formats_for_minmax)
+class Test_ShapeMinMax2DWithAxis:
+    def test_minmax(self, spcreator):
+        dat = np.array([[-1, 5, 0, 3], [0, 0, -1, -2], [0, 0, 1, 2]])
+        datsp = spcreator(dat)
+
+        for (spminmax, npminmax) in [
+            (datsp.min, np.min),
+            (datsp.max, np.max),
+            (datsp.nanmin, np.nanmin),
+            (datsp.nanmax, np.nanmax),
+        ]:
+            for ax, result_shape in [(0, (4,)), (1, (3,))]:
+                assert_equal(toarray(spminmax(axis=ax)), npminmax(dat, axis=ax))
+                assert_equal(spminmax(axis=ax).shape, result_shape)
+                assert spminmax(axis=ax).format == "coo"
+
+        for spminmax in [datsp.argmin, datsp.argmax]:
+            for ax in [0, 1]:
+                assert isinstance(spminmax(axis=ax), np.ndarray)
+
+        # verify spmatrix behavior
+        spmat_form = {
+            'coo': coo_matrix,
+            'csr': csr_matrix,
+            'csc': csc_matrix,
+            'bsr': bsr_matrix,
+        }
+        datspm = spmat_form[datsp.format](dat)
+
+        for spm, npm in [
+            (datspm.min, np.min),
+            (datspm.max, np.max),
+            (datspm.nanmin, np.nanmin),
+            (datspm.nanmax, np.nanmax),
+        ]:
+            for ax, result_shape in [(0, (1, 4)), (1, (3, 1))]:
+                assert_equal(toarray(spm(axis=ax)), npm(dat, axis=ax, keepdims=True))
+                assert_equal(spm(axis=ax).shape, result_shape)
+                assert spm(axis=ax).format == "coo"
+
+        for spminmax in [datspm.argmin, datspm.argmax]:
+            for ax in [0, 1]:
+                assert isinstance(spminmax(axis=ax), np.ndarray)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sparsetools.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sparsetools.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a8b94796116a22c210104fc446c5a17045ed21c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sparsetools.py
@@ -0,0 +1,339 @@
+import sys
+import os
+import gc
+import threading
+
+import numpy as np
+from numpy.testing import assert_equal, assert_, assert_allclose
+from scipy.sparse import (_sparsetools, coo_matrix, csr_matrix, csc_matrix,
+                          bsr_matrix, dia_matrix)
+from scipy.sparse._sputils import supported_dtypes
+from scipy._lib._testutils import check_free_memory
+
+import pytest
+from pytest import raises as assert_raises
+
+
+def int_to_int8(n):
+    """
+    Wrap an integer to the interval [-128, 127].
+    """
+    return (n + 128) % 256 - 128
+
+
+def test_exception():
+    assert_raises(MemoryError, _sparsetools.test_throw_error)
+
+
+def test_threads():
+    # Smoke test for parallel threaded execution; doesn't actually
+    # check that code runs in parallel, but just that it produces
+    # expected results.
+    nthreads = 10
+    niter = 100
+
+    n = 20
+    a = csr_matrix(np.ones([n, n]))
+    bres = []
+
+    class Worker(threading.Thread):
+        def run(self):
+            b = a.copy()
+            for j in range(niter):
+                _sparsetools.csr_plus_csr(n, n,
+                                          a.indptr, a.indices, a.data,
+                                          a.indptr, a.indices, a.data,
+                                          b.indptr, b.indices, b.data)
+            bres.append(b)
+
+    threads = [Worker() for _ in range(nthreads)]
+    for thread in threads:
+        thread.start()
+    for thread in threads:
+        thread.join()
+
+    for b in bres:
+        assert_(np.all(b.toarray() == 2))
+
+
+def test_regression_std_vector_dtypes():
+    # Regression test for gh-3780, checking the std::vector typemaps
+    # in sparsetools.cxx are complete.
+    for dtype in supported_dtypes:
+        ad = np.array([[1, 2], [3, 4]]).astype(dtype)
+        a = csr_matrix(ad, dtype=dtype)
+
+        # getcol is one function using std::vector typemaps, and should not fail
+        assert_equal(a.getcol(0).toarray(), ad[:, :1])
+
+
+@pytest.mark.slow
+@pytest.mark.xfail_on_32bit("Can't create large array for test")
+def test_nnz_overflow():
+    # Regression test for gh-7230 / gh-7871, checking that coo_toarray
+    # with nnz > int32max doesn't overflow.
+    nnz = np.iinfo(np.int32).max + 1
+    # Ensure ~20 GB of RAM is free to run this test.
+    check_free_memory((4 + 4 + 1) * nnz / 1e6 + 0.5)
+
+    # Use nnz duplicate entries to keep the dense version small.
+    row = np.zeros(nnz, dtype=np.int32)
+    col = np.zeros(nnz, dtype=np.int32)
+    data = np.zeros(nnz, dtype=np.int8)
+    data[-1] = 4
+    s = coo_matrix((data, (row, col)), shape=(1, 1), copy=False)
+    # Sums nnz duplicates to produce a 1x1 array containing 4.
+    d = s.toarray()
+
+    assert_allclose(d, [[4]])
+
+
+@pytest.mark.skipif(
+    not (sys.platform.startswith('linux') and np.dtype(np.intp).itemsize >= 8),
+    reason="test requires 64-bit Linux"
+)
+class TestInt32Overflow:
+    """
+    Some of the sparsetools routines use dense 2D matrices whose
+    total size is not bounded by the nnz of the sparse matrix. These
+    routines used to suffer from int32 wraparounds; here, we try to
+    check that the wraparounds don't occur any more.
+    """
+    # choose n large enough
+    n = 50000
+
+    def setup_method(self):
+        assert self.n**2 > np.iinfo(np.int32).max
+
+        # check there's enough memory even if everything is run at the
+        # same time
+        try:
+            parallel_count = int(os.environ.get('PYTEST_XDIST_WORKER_COUNT', '1'))
+        except ValueError:
+            parallel_count = np.inf
+
+        check_free_memory(3000 * parallel_count)
+
+    def teardown_method(self):
+        gc.collect()
+
+    def test_coo_todense(self):
+        # Check *_todense routines (cf. gh-2179)
+        #
+        # All of them in the end call coo_matrix.todense
+
+        n = self.n
+
+        i = np.array([0, n-1])
+        j = np.array([0, n-1])
+        data = np.array([1, 2], dtype=np.int8)
+        m = coo_matrix((data, (i, j)))
+
+        r = m.todense()
+        assert_equal(r[0,0], 1)
+        assert_equal(r[-1,-1], 2)
+        del r
+        gc.collect()
+
+    @pytest.mark.slow
+    def test_matvecs(self):
+        # Check *_matvecs routines
+        n = self.n
+
+        i = np.array([0, n-1])
+        j = np.array([0, n-1])
+        data = np.array([1, 2], dtype=np.int8)
+        m = coo_matrix((data, (i, j)))
+
+        b = np.ones((n, n), dtype=np.int8)
+        for sptype in (csr_matrix, csc_matrix, bsr_matrix):
+            m2 = sptype(m)
+            r = m2.dot(b)
+            assert_equal(r[0,0], 1)
+            assert_equal(r[-1,-1], 2)
+            del r
+            gc.collect()
+
+        del b
+        gc.collect()
+
+    @pytest.mark.slow
+    def test_dia_matvec(self):
+        # Check: huge dia_matrix _matvec
+        n = self.n
+        data = np.ones((n, n), dtype=np.int8)
+        offsets = np.arange(n)
+        m = dia_matrix((data, offsets), shape=(n, n))
+        v = np.ones(m.shape[1], dtype=np.int8)
+        r = m.dot(v)
+        assert_equal(r[0], int_to_int8(n))
+        del data, offsets, m, v, r
+        gc.collect()
+
+    _bsr_ops = [pytest.param("matmat", marks=pytest.mark.xslow),
+                pytest.param("matvecs", marks=pytest.mark.xslow),
+                "matvec",
+                "diagonal",
+                "sort_indices",
+                pytest.param("transpose", marks=pytest.mark.xslow)]
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize("op", _bsr_ops)
+    def test_bsr_1_block(self, op):
+        # Check: huge bsr_matrix (1-block)
+        #
+        # The point here is that indices inside a block may overflow.
+
+        def get_matrix():
+            n = self.n
+            data = np.ones((1, n, n), dtype=np.int8)
+            indptr = np.array([0, 1], dtype=np.int32)
+            indices = np.array([0], dtype=np.int32)
+            m = bsr_matrix((data, indices, indptr), blocksize=(n, n), copy=False)
+            del data, indptr, indices
+            return m
+
+        gc.collect()
+        try:
+            getattr(self, "_check_bsr_" + op)(get_matrix)
+        finally:
+            gc.collect()
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize("op", _bsr_ops)
+    def test_bsr_n_block(self, op):
+        # Check: huge bsr_matrix (n-block)
+        #
+        # The point here is that while indices within a block don't
+        # overflow, accumulators across many block may.
+
+        def get_matrix():
+            n = self.n
+            data = np.ones((n, n, 1), dtype=np.int8)
+            indptr = np.array([0, n], dtype=np.int32)
+            indices = np.arange(n, dtype=np.int32)
+            m = bsr_matrix((data, indices, indptr), blocksize=(n, 1), copy=False)
+            del data, indptr, indices
+            return m
+
+        gc.collect()
+        try:
+            getattr(self, "_check_bsr_" + op)(get_matrix)
+        finally:
+            gc.collect()
+
+    def _check_bsr_matvecs(self, m):  # skip name check
+        m = m()
+        n = self.n
+
+        # _matvecs
+        r = m.dot(np.ones((n, 2), dtype=np.int8))
+        assert_equal(r[0, 0], int_to_int8(n))
+
+    def _check_bsr_matvec(self, m):  # skip name check
+        m = m()
+        n = self.n
+
+        # _matvec
+        r = m.dot(np.ones((n,), dtype=np.int8))
+        assert_equal(r[0], int_to_int8(n))
+
+    def _check_bsr_diagonal(self, m):  # skip name check
+        m = m()
+        n = self.n
+
+        # _diagonal
+        r = m.diagonal()
+        assert_equal(r, np.ones(n))
+
+    def _check_bsr_sort_indices(self, m):  # skip name check
+        # _sort_indices
+        m = m()
+        m.sort_indices()
+
+    def _check_bsr_transpose(self, m):  # skip name check
+        # _transpose
+        m = m()
+        m.transpose()
+
+    def _check_bsr_matmat(self, m):  # skip name check
+        m = m()
+        n = self.n
+
+        # _bsr_matmat
+        m2 = bsr_matrix(np.ones((n, 2), dtype=np.int8), blocksize=(m.blocksize[1], 2))
+        m.dot(m2)  # shouldn't SIGSEGV
+        del m2
+
+        # _bsr_matmat
+        m2 = bsr_matrix(np.ones((2, n), dtype=np.int8), blocksize=(2, m.blocksize[0]))
+        m2.dot(m)  # shouldn't SIGSEGV
+
+
+@pytest.mark.skip(reason="64-bit indices in sparse matrices not available")
+def test_csr_matmat_int64_overflow():
+    n = 3037000500
+    assert n**2 > np.iinfo(np.int64).max
+
+    # the test would take crazy amounts of memory
+    check_free_memory(n * (8*2 + 1) * 3 / 1e6)
+
+    # int64 overflow
+    data = np.ones((n,), dtype=np.int8)
+    indptr = np.arange(n+1, dtype=np.int64)
+    indices = np.zeros(n, dtype=np.int64)
+    a = csr_matrix((data, indices, indptr))
+    b = a.T
+
+    assert_raises(RuntimeError, a.dot, b)
+
+
+def test_upcast():
+    a0 = csr_matrix([[np.pi, np.pi*1j], [3, 4]], dtype=complex)
+    b0 = np.array([256+1j, 2**32], dtype=complex)
+
+    for a_dtype in supported_dtypes:
+        for b_dtype in supported_dtypes:
+            msg = f"({a_dtype!r}, {b_dtype!r})"
+
+            if np.issubdtype(a_dtype, np.complexfloating):
+                a = a0.copy().astype(a_dtype)
+            else:
+                a = a0.real.copy().astype(a_dtype)
+
+            if np.issubdtype(b_dtype, np.complexfloating):
+                b = b0.copy().astype(b_dtype)
+            else:
+                with np.errstate(invalid="ignore"):
+                    # Casting a large value (2**32) to int8 causes a warning in
+                    # numpy >1.23
+                    b = b0.real.copy().astype(b_dtype)
+
+            if not (a_dtype == np.bool_ and b_dtype == np.bool_):
+                c = np.zeros((2,), dtype=np.bool_)
+                assert_raises(ValueError, _sparsetools.csr_matvec,
+                              2, 2, a.indptr, a.indices, a.data, b, c)
+
+            if ((np.issubdtype(a_dtype, np.complexfloating) and
+                 not np.issubdtype(b_dtype, np.complexfloating)) or
+                (not np.issubdtype(a_dtype, np.complexfloating) and
+                 np.issubdtype(b_dtype, np.complexfloating))):
+                c = np.zeros((2,), dtype=np.float64)
+                assert_raises(ValueError, _sparsetools.csr_matvec,
+                              2, 2, a.indptr, a.indices, a.data, b, c)
+
+            c = np.zeros((2,), dtype=np.result_type(a_dtype, b_dtype))
+            _sparsetools.csr_matvec(2, 2, a.indptr, a.indices, a.data, b, c)
+            assert_allclose(c, np.dot(a.toarray(), b), err_msg=msg)
+
+
+def test_endianness():
+    d = np.ones((3,4))
+    offsets = [-1,0,1]
+
+    a = dia_matrix((d.astype('f8'), offsets), (4, 4))
+    v = np.arange(4)
+
+    assert_allclose(a.dot(v), [1, 3, 6, 5])
+    assert_allclose(b.dot(v), [1, 3, 6, 5])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_spfuncs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_spfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..75bc2d92c369be5799a904bc0938617f30321f12
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_spfuncs.py
@@ -0,0 +1,97 @@
+from numpy import array, kron, diag
+from numpy.testing import assert_, assert_equal
+
+from scipy.sparse import _spfuncs as spfuncs
+from scipy.sparse import csr_matrix, csc_matrix, bsr_matrix
+from scipy.sparse._sparsetools import (csr_scale_rows, csr_scale_columns,
+                                       bsr_scale_rows, bsr_scale_columns)
+
+
+class TestSparseFunctions:
+    def test_scale_rows_and_cols(self):
+        D = array([[1, 0, 0, 2, 3],
+                   [0, 4, 0, 5, 0],
+                   [0, 0, 6, 7, 0]])
+
+        #TODO expose through function
+        S = csr_matrix(D)
+        v = array([1,2,3])
+        csr_scale_rows(3,5,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), diag(v)@D)
+
+        S = csr_matrix(D)
+        v = array([1,2,3,4,5])
+        csr_scale_columns(3,5,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), D@diag(v))
+
+        # blocks
+        E = kron(D,[[1,2],[3,4]])
+        S = bsr_matrix(E,blocksize=(2,2))
+        v = array([1,2,3,4,5,6])
+        bsr_scale_rows(3,5,2,2,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), diag(v)@E)
+
+        S = bsr_matrix(E,blocksize=(2,2))
+        v = array([1,2,3,4,5,6,7,8,9,10])
+        bsr_scale_columns(3,5,2,2,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), E@diag(v))
+
+        E = kron(D,[[1,2,3],[4,5,6]])
+        S = bsr_matrix(E,blocksize=(2,3))
+        v = array([1,2,3,4,5,6])
+        bsr_scale_rows(3,5,2,3,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), diag(v)@E)
+
+        S = bsr_matrix(E,blocksize=(2,3))
+        v = array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])
+        bsr_scale_columns(3,5,2,3,S.indptr,S.indices,S.data,v)
+        assert_equal(S.toarray(), E@diag(v))
+
+    def test_estimate_blocksize(self):
+        mats = []
+        mats.append([[0,1],[1,0]])
+        mats.append([[1,1,0],[0,0,1],[1,0,1]])
+        mats.append([[0],[0],[1]])
+        mats = [array(x) for x in mats]
+
+        blks = []
+        blks.append([[1]])
+        blks.append([[1,1],[1,1]])
+        blks.append([[1,1],[0,1]])
+        blks.append([[1,1,0],[1,0,1],[1,1,1]])
+        blks = [array(x) for x in blks]
+
+        for A in mats:
+            for B in blks:
+                X = kron(A,B)
+                r,c = spfuncs.estimate_blocksize(X)
+                assert_(r >= B.shape[0])
+                assert_(c >= B.shape[1])
+
+    def test_count_blocks(self):
+        def gold(A,bs):
+            R,C = bs
+            I,J = A.nonzero()
+            return len(set(zip(I//R,J//C)))
+
+        mats = []
+        mats.append([[0]])
+        mats.append([[1]])
+        mats.append([[1,0]])
+        mats.append([[1,1]])
+        mats.append([[0,1],[1,0]])
+        mats.append([[1,1,0],[0,0,1],[1,0,1]])
+        mats.append([[0],[0],[1]])
+
+        for A in mats:
+            for B in mats:
+                X = kron(A,B)
+                Y = csr_matrix(X)
+                for R in range(1,6):
+                    for C in range(1,6):
+                        assert_equal(spfuncs.count_blocks(Y, (R, C)), gold(X, (R, C)))
+
+        X = kron([[1,1,0],[0,0,1],[1,0,1]],[[1,1]])
+        Y = csc_matrix(X)
+        assert_equal(spfuncs.count_blocks(X, (1, 2)), gold(X, (1, 2)))
+        assert_equal(spfuncs.count_blocks(Y, (1, 2)), gold(X, (1, 2)))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sputils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sputils.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb328e3f6512081f76604c4b92fe3d407819e448
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/sparse/tests/test_sputils.py
@@ -0,0 +1,395 @@
+"""unit tests for sparse utility functions"""
+
+import numpy as np
+from numpy.testing import assert_equal
+import pytest
+from pytest import raises as assert_raises
+from scipy.sparse import _sputils as sputils, csr_array, bsr_array, dia_array, coo_array
+from scipy.sparse._sputils import matrix
+
+
+class TestSparseUtils:
+
+    def test_upcast(self):
+        assert_equal(sputils.upcast('intc'), np.intc)
+        assert_equal(sputils.upcast('int32', 'float32'), np.float64)
+        assert_equal(sputils.upcast('bool', complex, float), np.complex128)
+        assert_equal(sputils.upcast('i', 'd'), np.float64)
+
+    def test_getdtype(self):
+        A = np.array([1], dtype='int8')
+
+        assert_equal(sputils.getdtype(None, default=float), float)
+        assert_equal(sputils.getdtype(None, a=A), np.int8)
+
+        with assert_raises(
+            ValueError,
+            match="scipy.sparse does not support dtype object. .*",
+        ):
+            sputils.getdtype("O")
+
+        with assert_raises(
+            ValueError,
+            match="scipy.sparse does not support dtype float16. .*",
+        ):
+            sputils.getdtype(None, default=np.float16)
+
+    def test_isscalarlike(self):
+        assert_equal(sputils.isscalarlike(3.0), True)
+        assert_equal(sputils.isscalarlike(-4), True)
+        assert_equal(sputils.isscalarlike(2.5), True)
+        assert_equal(sputils.isscalarlike(1 + 3j), True)
+        assert_equal(sputils.isscalarlike(np.array(3)), True)
+        assert_equal(sputils.isscalarlike("16"), True)
+
+        assert_equal(sputils.isscalarlike(np.array([3])), False)
+        assert_equal(sputils.isscalarlike([[3]]), False)
+        assert_equal(sputils.isscalarlike((1,)), False)
+        assert_equal(sputils.isscalarlike((1, 2)), False)
+
+    def test_isintlike(self):
+        assert_equal(sputils.isintlike(-4), True)
+        assert_equal(sputils.isintlike(np.array(3)), True)
+        assert_equal(sputils.isintlike(np.array([3])), False)
+        with assert_raises(
+            ValueError,
+            match="Inexact indices into sparse matrices are not allowed"
+        ):
+            sputils.isintlike(3.0)
+
+        assert_equal(sputils.isintlike(2.5), False)
+        assert_equal(sputils.isintlike(1 + 3j), False)
+        assert_equal(sputils.isintlike((1,)), False)
+        assert_equal(sputils.isintlike((1, 2)), False)
+
+    def test_isshape(self):
+        assert_equal(sputils.isshape((1, 2)), True)
+        assert_equal(sputils.isshape((5, 2)), True)
+
+        assert_equal(sputils.isshape((1.5, 2)), False)
+        assert_equal(sputils.isshape((2, 2, 2)), False)
+        assert_equal(sputils.isshape(([2], 2)), False)
+        assert_equal(sputils.isshape((-1, 2), nonneg=False),True)
+        assert_equal(sputils.isshape((2, -1), nonneg=False),True)
+        assert_equal(sputils.isshape((-1, 2), nonneg=True),False)
+        assert_equal(sputils.isshape((2, -1), nonneg=True),False)
+
+        assert_equal(sputils.isshape((1.5, 2), allow_nd=(1, 2)), False)
+        assert_equal(sputils.isshape(([2], 2), allow_nd=(1, 2)), False)
+        assert_equal(sputils.isshape((2, 2, -2), nonneg=True, allow_nd=(1, 2)),
+                     False)
+        assert_equal(sputils.isshape((2,), allow_nd=(1, 2)), True)
+        assert_equal(sputils.isshape((2, 2,), allow_nd=(1, 2)), True)
+        assert_equal(sputils.isshape((2, 2, 2), allow_nd=(1, 2)), False)
+
+    def test_issequence(self):
+        assert_equal(sputils.issequence((1,)), True)
+        assert_equal(sputils.issequence((1, 2, 3)), True)
+        assert_equal(sputils.issequence([1]), True)
+        assert_equal(sputils.issequence([1, 2, 3]), True)
+        assert_equal(sputils.issequence(np.array([1, 2, 3])), True)
+
+        assert_equal(sputils.issequence(np.array([[1], [2], [3]])), False)
+        assert_equal(sputils.issequence(3), False)
+
+    def test_ismatrix(self):
+        assert_equal(sputils.ismatrix(((),)), True)
+        assert_equal(sputils.ismatrix([[1], [2]]), True)
+        assert_equal(sputils.ismatrix(np.arange(3)[None]), True)
+
+        assert_equal(sputils.ismatrix([1, 2]), False)
+        assert_equal(sputils.ismatrix(np.arange(3)), False)
+        assert_equal(sputils.ismatrix([[[1]]]), False)
+        assert_equal(sputils.ismatrix(3), False)
+
+    def test_isdense(self):
+        assert_equal(sputils.isdense(np.array([1])), True)
+        assert_equal(sputils.isdense(matrix([1])), True)
+
+    def test_validateaxis(self):
+        assert_raises(TypeError, sputils.validateaxis, (0, 1))
+        assert_raises(TypeError, sputils.validateaxis, 1.5)
+        assert_raises(ValueError, sputils.validateaxis, 3)
+
+        # These function calls should not raise errors
+        for axis in (-2, -1, 0, 1, None):
+            sputils.validateaxis(axis)
+
+    @pytest.mark.parametrize("container", [csr_array, bsr_array])
+    def test_safely_cast_index_compressed(self, container):
+        # This is slow to test completely as nnz > imax is big
+        # and indptr is big for some shapes
+        # So we don't test large nnz, nor csc_array (same code as csr_array)
+        imax = np.int64(np.iinfo(np.int32).max)
+
+        # Shape 32bit
+        A32 = container((1, imax))
+        # indices big type, small values
+        B32 = A32.copy()
+        B32.indices = B32.indices.astype(np.int64)
+        B32.indptr = B32.indptr.astype(np.int64)
+
+        # Shape 64bit
+        # indices big type, small values
+        A64 = csr_array((1, imax + 1))
+        # indices small type, small values
+        B64 = A64.copy()
+        B64.indices = B64.indices.astype(np.int32)
+        B64.indptr = B64.indptr.astype(np.int32)
+        # indices big type, big values
+        C64 = A64.copy()
+        C64.indices = np.array([imax + 1], dtype=np.int64)
+        C64.indptr = np.array([0, 1], dtype=np.int64)
+        C64.data = np.array([2.2])
+
+        assert (A32.indices.dtype, A32.indptr.dtype) == (np.int32, np.int32)
+        assert (B32.indices.dtype, B32.indptr.dtype) == (np.int64, np.int64)
+        assert (A64.indices.dtype, A64.indptr.dtype) == (np.int64, np.int64)
+        assert (B64.indices.dtype, B64.indptr.dtype) == (np.int32, np.int32)
+        assert (C64.indices.dtype, C64.indptr.dtype) == (np.int64, np.int64)
+
+        for A in [A32, B32, A64, B64]:
+            indices, indptr = sputils.safely_cast_index_arrays(A, np.int32)
+            assert (indices.dtype, indptr.dtype) == (np.int32, np.int32)
+            indices, indptr = sputils.safely_cast_index_arrays(A, np.int64)
+            assert (indices.dtype, indptr.dtype) == (np.int64, np.int64)
+
+            indices, indptr = sputils.safely_cast_index_arrays(A, A.indices.dtype)
+            assert indices is A.indices
+            assert indptr is A.indptr
+
+        with assert_raises(ValueError):
+            sputils.safely_cast_index_arrays(C64, np.int32)
+        indices, indptr = sputils.safely_cast_index_arrays(C64, np.int64)
+        assert indices is C64.indices
+        assert indptr is C64.indptr
+
+    def test_safely_cast_index_coo(self):
+        # This is slow to test completely as nnz > imax is big
+        # So we don't test large nnz
+        imax = np.int64(np.iinfo(np.int32).max)
+
+        # Shape 32bit
+        A32 = coo_array((1, imax))
+        # coords big type, small values
+        B32 = A32.copy()
+        B32.coords = tuple(co.astype(np.int64) for co in B32.coords)
+
+        # Shape 64bit
+        # coords big type, small values
+        A64 = coo_array((1, imax + 1))
+        # coords small type, small values
+        B64 = A64.copy()
+        B64.coords = tuple(co.astype(np.int32) for co in B64.coords)
+        # coords big type, big values
+        C64 = A64.copy()
+        C64.coords = (np.array([imax + 1]), np.array([0]))
+        C64.data = np.array([2.2])
+
+        assert A32.coords[0].dtype == np.int32
+        assert B32.coords[0].dtype == np.int64
+        assert A64.coords[0].dtype == np.int64
+        assert B64.coords[0].dtype == np.int32
+        assert C64.coords[0].dtype == np.int64
+
+        for A in [A32, B32, A64, B64]:
+            coords = sputils.safely_cast_index_arrays(A, np.int32)
+            assert coords[0].dtype == np.int32
+            coords = sputils.safely_cast_index_arrays(A, np.int64)
+            assert coords[0].dtype == np.int64
+
+            coords = sputils.safely_cast_index_arrays(A, A.coords[0].dtype)
+            assert coords[0] is A.coords[0]
+
+        with assert_raises(ValueError):
+            sputils.safely_cast_index_arrays(C64, np.int32)
+        coords = sputils.safely_cast_index_arrays(C64, np.int64)
+        assert coords[0] is C64.coords[0]
+
+    def test_safely_cast_index_dia(self):
+        # This is slow to test completely as nnz > imax is big
+        # So we don't test large nnz
+        imax = np.int64(np.iinfo(np.int32).max)
+
+        # Shape 32bit
+        A32 = dia_array((1, imax))
+        # offsets big type, small values
+        B32 = A32.copy()
+        B32.offsets = B32.offsets.astype(np.int64)
+
+        # Shape 64bit
+        # offsets big type, small values
+        A64 = dia_array((1, imax + 2))
+        # offsets small type, small values
+        B64 = A64.copy()
+        B64.offsets = B64.offsets.astype(np.int32)
+        # offsets big type, big values
+        C64 = A64.copy()
+        C64.offsets = np.array([imax + 1])
+        C64.data = np.array([2.2])
+
+        assert A32.offsets.dtype == np.int32
+        assert B32.offsets.dtype == np.int64
+        assert A64.offsets.dtype == np.int64
+        assert B64.offsets.dtype == np.int32
+        assert C64.offsets.dtype == np.int64
+
+        for A in [A32, B32, A64, B64]:
+            offsets = sputils.safely_cast_index_arrays(A, np.int32)
+            assert offsets.dtype == np.int32
+            offsets = sputils.safely_cast_index_arrays(A, np.int64)
+            assert offsets.dtype == np.int64
+
+            offsets = sputils.safely_cast_index_arrays(A, A.offsets.dtype)
+            assert offsets is A.offsets
+
+        with assert_raises(ValueError):
+            sputils.safely_cast_index_arrays(C64, np.int32)
+        offsets = sputils.safely_cast_index_arrays(C64, np.int64)
+        assert offsets is C64.offsets
+
+    def test_get_index_dtype(self):
+        imax = np.int64(np.iinfo(np.int32).max)
+        too_big = imax + 1
+
+        # Check that uint32's with no values too large doesn't return
+        # int64
+        a1 = np.ones(90, dtype='uint32')
+        a2 = np.ones(90, dtype='uint32')
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)),
+            np.dtype('int32')
+        )
+
+        # Check that if we can not convert but all values are less than or
+        # equal to max that we can just convert to int32
+        a1[-1] = imax
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)),
+            np.dtype('int32')
+        )
+
+        # Check that if it can not convert directly and the contents are
+        # too large that we return int64
+        a1[-1] = too_big
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2), check_contents=True)),
+            np.dtype('int64')
+        )
+
+        # test that if can not convert and didn't specify to check_contents
+        # we return int64
+        a1 = np.ones(89, dtype='uint32')
+        a2 = np.ones(89, dtype='uint32')
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2))),
+            np.dtype('int64')
+        )
+
+        # Check that even if we have arrays that can be converted directly
+        # that if we specify a maxval directly it takes precedence
+        a1 = np.ones(12, dtype='uint32')
+        a2 = np.ones(12, dtype='uint32')
+        assert_equal(
+            np.dtype(sputils.get_index_dtype(
+                (a1, a2), maxval=too_big, check_contents=True
+            )),
+            np.dtype('int64')
+        )
+
+        # Check that an array with a too max size and maxval set
+        # still returns int64
+        a1[-1] = too_big
+        assert_equal(
+            np.dtype(sputils.get_index_dtype((a1, a2), maxval=too_big)),
+            np.dtype('int64')
+        )
+
+    # tests public broadcast_shapes largely from
+    # numpy/numpy/lib/tests/test_stride_tricks.py
+    # first 3 cause np.broadcast to raise index too large, but not sputils
+    @pytest.mark.parametrize("input_shapes,target_shape", [
+        [((6, 5, 1, 4, 1, 1), (1, 2**32), (2**32, 1)), (6, 5, 1, 4, 2**32, 2**32)],
+        [((6, 5, 1, 4, 1, 1), (1, 2**32)), (6, 5, 1, 4, 1, 2**32)],
+        [((1, 2**32), (2**32, 1)), (2**32, 2**32)],
+        [[2, 2, 2], (2,)],
+        [[], ()],
+        [[()], ()],
+        [[(7,)], (7,)],
+        [[(1, 2), (2,)], (1, 2)],
+        [[(2,), (1, 2)], (1, 2)],
+        [[(1, 1)], (1, 1)],
+        [[(1, 1), (3, 4)], (3, 4)],
+        [[(6, 7), (5, 6, 1), (7,), (5, 1, 7)], (5, 6, 7)],
+        [[(5, 6, 1)], (5, 6, 1)],
+        [[(1, 3), (3, 1)], (3, 3)],
+        [[(1, 0), (0, 0)], (0, 0)],
+        [[(0, 1), (0, 0)], (0, 0)],
+        [[(1, 0), (0, 1)], (0, 0)],
+        [[(1, 1), (0, 0)], (0, 0)],
+        [[(1, 1), (1, 0)], (1, 0)],
+        [[(1, 1), (0, 1)], (0, 1)],
+        [[(), (0,)], (0,)],
+        [[(0,), (0, 0)], (0, 0)],
+        [[(0,), (0, 1)], (0, 0)],
+        [[(1,), (0, 0)], (0, 0)],
+        [[(), (0, 0)], (0, 0)],
+        [[(1, 1), (0,)], (1, 0)],
+        [[(1,), (0, 1)], (0, 1)],
+        [[(1,), (1, 0)], (1, 0)],
+        [[(), (1, 0)], (1, 0)],
+        [[(), (0, 1)], (0, 1)],
+        [[(1,), (3,)], (3,)],
+        [[2, (3, 2)], (3, 2)],
+        [[(1, 2)] * 32, (1, 2)],
+        [[(1, 2)] * 100, (1, 2)],
+        [[(2,)] * 32, (2,)],
+    ])
+    def test_broadcast_shapes_successes(self, input_shapes, target_shape):
+        assert_equal(sputils.broadcast_shapes(*input_shapes), target_shape)
+
+    # tests public broadcast_shapes failures
+    @pytest.mark.parametrize("input_shapes", [
+        [(3,), (4,)],
+        [(2, 3), (2,)],
+        [2, (2, 3)],
+        [(3,), (3,), (4,)],
+        [(2, 5), (3, 5)],
+        [(2, 4), (2, 5)],
+        [(1, 3, 4), (2, 3, 3)],
+        [(1, 2), (3, 1), (3, 2), (10, 5)],
+        [(2,)] * 32 + [(3,)] * 32,
+    ])
+    def test_broadcast_shapes_failures(self, input_shapes):
+        with assert_raises(ValueError, match="cannot be broadcast"):
+            sputils.broadcast_shapes(*input_shapes)
+
+    def test_check_shape_overflow(self):
+        new_shape = sputils.check_shape([(10, -1)], (65535, 131070))
+        assert_equal(new_shape, (10, 858967245))
+
+    def test_matrix(self):
+        a = [[1, 2, 3]]
+        b = np.array(a)
+
+        assert isinstance(sputils.matrix(a), np.matrix)
+        assert isinstance(sputils.matrix(b), np.matrix)
+
+        c = sputils.matrix(b)
+        c[:, :] = 123
+        assert_equal(b, a)
+
+        c = sputils.matrix(b, copy=False)
+        c[:, :] = 123
+        assert_equal(b, [[123, 123, 123]])
+
+    def test_asmatrix(self):
+        a = [[1, 2, 3]]
+        b = np.array(a)
+
+        assert isinstance(sputils.asmatrix(a), np.matrix)
+        assert isinstance(sputils.asmatrix(b), np.matrix)
+
+        c = sputils.asmatrix(b)
+        c[:, :] = 123
+        assert_equal(b, [[123, 123, 123]])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__init__.pxd b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..1daa9fb379572aac4bc9b6d74330a18c5c52bf79
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__init__.pxd
@@ -0,0 +1 @@
+from scipy.special cimport cython_special
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8993f522a0fac00e243d361835a42b89a82d11ef
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__init__.py
@@ -0,0 +1,887 @@
+"""
+========================================
+Special functions (:mod:`scipy.special`)
+========================================
+
+.. currentmodule:: scipy.special
+
+Almost all of the functions below accept NumPy arrays as input
+arguments as well as single numbers. This means they follow
+broadcasting and automatic array-looping rules. Technically,
+they are `NumPy universal functions
+`_.
+Functions which do not accept NumPy arrays are marked by a warning
+in the section description.
+
+.. seealso::
+
+   `scipy.special.cython_special` -- Typed Cython versions of special functions
+
+
+Error handling
+==============
+
+Errors are handled by returning NaNs or other appropriate values.
+Some of the special function routines can emit warnings or raise
+exceptions when an error occurs. By default this is disabled, except
+for memory allocation errors, which result in an exception being raised.
+To query and control the current error handling state the following
+functions are provided.
+
+.. autosummary::
+   :toctree: generated/
+
+   geterr                 -- Get the current way of handling special-function errors.
+   seterr                 -- Set how special-function errors are handled.
+   errstate               -- Context manager for special-function error handling.
+   SpecialFunctionWarning -- Warning that can be emitted by special functions.
+   SpecialFunctionError   -- Exception that can be raised by special functions.
+
+Available functions
+===================
+
+Airy functions
+--------------
+
+.. autosummary::
+   :toctree: generated/
+
+   airy     -- Airy functions and their derivatives.
+   airye    -- Exponentially scaled Airy functions and their derivatives.
+   ai_zeros -- Compute `nt` zeros and values of the Airy function Ai and its derivative.
+   bi_zeros -- Compute `nt` zeros and values of the Airy function Bi and its derivative.
+   itairy   -- Integrals of Airy functions
+
+
+Elliptic functions and integrals
+--------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   ellipj    -- Jacobian elliptic functions.
+   ellipk    -- Complete elliptic integral of the first kind.
+   ellipkm1  -- Complete elliptic integral of the first kind around `m` = 1.
+   ellipkinc -- Incomplete elliptic integral of the first kind.
+   ellipe    -- Complete elliptic integral of the second kind.
+   ellipeinc -- Incomplete elliptic integral of the second kind.
+   elliprc   -- Degenerate symmetric integral RC.
+   elliprd   -- Symmetric elliptic integral of the second kind.
+   elliprf   -- Completely-symmetric elliptic integral of the first kind.
+   elliprg   -- Completely-symmetric elliptic integral of the second kind.
+   elliprj   -- Symmetric elliptic integral of the third kind.
+
+Bessel functions
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   jv                -- Bessel function of the first kind of real order and \
+                        complex argument.
+   jve               -- Exponentially scaled Bessel function of order `v`.
+   yn                -- Bessel function of the second kind of integer order and \
+                        real argument.
+   yv                -- Bessel function of the second kind of real order and \
+                        complex argument.
+   yve               -- Exponentially scaled Bessel function of the second kind \
+                        of real order.
+   kn                -- Modified Bessel function of the second kind of integer \
+                        order `n`
+   kv                -- Modified Bessel function of the second kind of real order \
+                        `v`
+   kve               -- Exponentially scaled modified Bessel function of the \
+                        second kind.
+   iv                -- Modified Bessel function of the first kind of real order.
+   ive               -- Exponentially scaled modified Bessel function of the \
+                        first kind.
+   hankel1           -- Hankel function of the first kind.
+   hankel1e          -- Exponentially scaled Hankel function of the first kind.
+   hankel2           -- Hankel function of the second kind.
+   hankel2e          -- Exponentially scaled Hankel function of the second kind.
+   wright_bessel     -- Wright's generalized Bessel function.
+   log_wright_bessel -- Logarithm of Wright's generalized Bessel function.
+
+The following function does not accept NumPy arrays (it is not a
+universal function):
+
+.. autosummary::
+   :toctree: generated/
+
+   lmbda -- Jahnke-Emden Lambda function, Lambdav(x).
+
+Zeros of Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   jnjnp_zeros -- Compute zeros of integer-order Bessel functions Jn and Jn'.
+   jnyn_zeros  -- Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
+   jn_zeros    -- Compute zeros of integer-order Bessel function Jn(x).
+   jnp_zeros   -- Compute zeros of integer-order Bessel function derivative Jn'(x).
+   yn_zeros    -- Compute zeros of integer-order Bessel function Yn(x).
+   ynp_zeros   -- Compute zeros of integer-order Bessel function derivative Yn'(x).
+   y0_zeros    -- Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
+   y1_zeros    -- Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
+   y1p_zeros   -- Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
+
+Faster versions of common Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   j0  -- Bessel function of the first kind of order 0.
+   j1  -- Bessel function of the first kind of order 1.
+   y0  -- Bessel function of the second kind of order 0.
+   y1  -- Bessel function of the second kind of order 1.
+   i0  -- Modified Bessel function of order 0.
+   i0e -- Exponentially scaled modified Bessel function of order 0.
+   i1  -- Modified Bessel function of order 1.
+   i1e -- Exponentially scaled modified Bessel function of order 1.
+   k0  -- Modified Bessel function of the second kind of order 0, :math:`K_0`.
+   k0e -- Exponentially scaled modified Bessel function K of order 0
+   k1  -- Modified Bessel function of the second kind of order 1, :math:`K_1(x)`.
+   k1e -- Exponentially scaled modified Bessel function K of order 1.
+
+Integrals of Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   itj0y0     -- Integrals of Bessel functions of order 0.
+   it2j0y0    -- Integrals related to Bessel functions of order 0.
+   iti0k0     -- Integrals of modified Bessel functions of order 0.
+   it2i0k0    -- Integrals related to modified Bessel functions of order 0.
+   besselpoly -- Weighted integral of a Bessel function.
+
+Derivatives of Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   jvp  -- Compute nth derivative of Bessel function Jv(z) with respect to `z`.
+   yvp  -- Compute nth derivative of Bessel function Yv(z) with respect to `z`.
+   kvp  -- Compute nth derivative of real-order modified Bessel function Kv(z)
+   ivp  -- Compute nth derivative of modified Bessel function Iv(z) with respect to `z`.
+   h1vp -- Compute nth derivative of Hankel function H1v(z) with respect to `z`.
+   h2vp -- Compute nth derivative of Hankel function H2v(z) with respect to `z`.
+
+Spherical Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   spherical_jn -- Spherical Bessel function of the first kind or its derivative.
+   spherical_yn -- Spherical Bessel function of the second kind or its derivative.
+   spherical_in -- Modified spherical Bessel function of the first kind or its derivative.
+   spherical_kn -- Modified spherical Bessel function of the second kind or its derivative.
+
+Riccati-Bessel functions
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   riccati_jn -- Compute Ricatti-Bessel function of the first kind and its derivative.
+   riccati_yn -- Compute Ricatti-Bessel function of the second kind and its derivative.
+
+Struve functions
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   struve       -- Struve function.
+   modstruve    -- Modified Struve function.
+   itstruve0    -- Integral of the Struve function of order 0.
+   it2struve0   -- Integral related to the Struve function of order 0.
+   itmodstruve0 -- Integral of the modified Struve function of order 0.
+
+
+Raw statistical functions
+-------------------------
+
+.. seealso:: :mod:`scipy.stats`: Friendly versions of these functions.
+
+Binomial distribution
+^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   bdtr         -- Binomial distribution cumulative distribution function.
+   bdtrc        -- Binomial distribution survival function.
+   bdtri        -- Inverse function to `bdtr` with respect to `p`.
+   bdtrik       -- Inverse function to `bdtr` with respect to `k`.
+   bdtrin       -- Inverse function to `bdtr` with respect to `n`.
+
+Beta distribution
+^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   btdtria      -- Inverse of `betainc` with respect to `a`.
+   btdtrib      -- Inverse of `betainc` with respect to `b`.
+
+F distribution
+^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   fdtr         -- F cumulative distribution function.
+   fdtrc        -- F survival function.
+   fdtri        -- The `p`-th quantile of the F-distribution.
+   fdtridfd     -- Inverse to `fdtr` vs dfd.
+
+Gamma distribution
+^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   gdtr         -- Gamma distribution cumulative distribution function.
+   gdtrc        -- Gamma distribution survival function.
+   gdtria       -- Inverse of `gdtr` vs a.
+   gdtrib       -- Inverse of `gdtr` vs b.
+   gdtrix       -- Inverse of `gdtr` vs x.
+
+Negative binomial distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   nbdtr        -- Negative binomial cumulative distribution function.
+   nbdtrc       -- Negative binomial survival function.
+   nbdtri       -- Inverse of `nbdtr` vs `p`.
+   nbdtrik      -- Inverse of `nbdtr` vs `k`.
+   nbdtrin      -- Inverse of `nbdtr` vs `n`.
+
+Noncentral F distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   ncfdtr       -- Cumulative distribution function of the non-central F distribution.
+   ncfdtridfd   -- Calculate degrees of freedom (denominator) for the noncentral F-distribution.
+   ncfdtridfn   -- Calculate degrees of freedom (numerator) for the noncentral F-distribution.
+   ncfdtri      -- Inverse cumulative distribution function of the non-central F distribution.
+   ncfdtrinc    -- Calculate non-centrality parameter for non-central F distribution.
+
+Noncentral t distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   nctdtr       -- Cumulative distribution function of the non-central `t` distribution.
+   nctdtridf    -- Calculate degrees of freedom for non-central t distribution.
+   nctdtrit     -- Inverse cumulative distribution function of the non-central t distribution.
+   nctdtrinc    -- Calculate non-centrality parameter for non-central t distribution.
+
+Normal distribution
+^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   nrdtrimn     -- Calculate mean of normal distribution given other params.
+   nrdtrisd     -- Calculate standard deviation of normal distribution given other params.
+   ndtr         -- Normal cumulative distribution function.
+   log_ndtr     -- Logarithm of normal cumulative distribution function.
+   ndtri        -- Inverse of `ndtr` vs x.
+   ndtri_exp    -- Inverse of `log_ndtr` vs x.
+
+Poisson distribution
+^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   pdtr         -- Poisson cumulative distribution function.
+   pdtrc        -- Poisson survival function.
+   pdtri        -- Inverse to `pdtr` vs m.
+   pdtrik       -- Inverse to `pdtr` vs k.
+
+Student t distribution
+^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   stdtr        -- Student t distribution cumulative distribution function.
+   stdtridf     -- Inverse of `stdtr` vs df.
+   stdtrit      -- Inverse of `stdtr` vs `t`.
+
+Chi square distribution
+^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   chdtr        -- Chi square cumulative distribution function.
+   chdtrc       -- Chi square survival function.
+   chdtri       -- Inverse to `chdtrc`.
+   chdtriv      -- Inverse to `chdtr` vs `v`.
+
+Non-central chi square distribution
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   chndtr       -- Non-central chi square cumulative distribution function.
+   chndtridf    -- Inverse to `chndtr` vs `df`.
+   chndtrinc    -- Inverse to `chndtr` vs `nc`.
+   chndtrix     -- Inverse to `chndtr` vs `x`.
+
+Kolmogorov distribution
+^^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   smirnov      -- Kolmogorov-Smirnov complementary cumulative distribution function.
+   smirnovi     -- Inverse to `smirnov`.
+   kolmogorov   -- Complementary cumulative distribution function of Kolmogorov distribution.
+   kolmogi      -- Inverse function to `kolmogorov`.
+
+Box-Cox transformation
+^^^^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   boxcox       -- Compute the Box-Cox transformation.
+   boxcox1p     -- Compute the Box-Cox transformation of 1 + `x`.
+   inv_boxcox   -- Compute the inverse of the Box-Cox transformation.
+   inv_boxcox1p -- Compute the inverse of the Box-Cox transformation.
+
+
+Sigmoidal functions
+^^^^^^^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   logit        -- Logit ufunc for ndarrays.
+   expit        -- Logistic sigmoid function.
+   log_expit    -- Logarithm of the logistic sigmoid function.
+
+Miscellaneous
+^^^^^^^^^^^^^
+
+.. autosummary::
+   :toctree: generated/
+
+   tklmbda      -- Tukey-Lambda cumulative distribution function.
+   owens_t      -- Owen's T Function.
+
+
+Information Theory functions
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   entr         -- Elementwise function for computing entropy.
+   rel_entr     -- Elementwise function for computing relative entropy.
+   kl_div       -- Elementwise function for computing Kullback-Leibler divergence.
+   huber        -- Huber loss function.
+   pseudo_huber -- Pseudo-Huber loss function.
+
+
+Gamma and related functions
+---------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   gamma        -- Gamma function.
+   gammaln      -- Logarithm of the absolute value of the Gamma function for real inputs.
+   loggamma     -- Principal branch of the logarithm of the Gamma function.
+   gammasgn     -- Sign of the gamma function.
+   gammainc     -- Regularized lower incomplete gamma function.
+   gammaincinv  -- Inverse to `gammainc`.
+   gammaincc    -- Regularized upper incomplete gamma function.
+   gammainccinv -- Inverse to `gammaincc`.
+   beta         -- Beta function.
+   betaln       -- Natural logarithm of absolute value of beta function.
+   betainc      -- Incomplete beta integral.
+   betaincc     -- Complemented incomplete beta integral.
+   betaincinv   -- Inverse function to beta integral.
+   betainccinv  -- Inverse of the complemented incomplete beta integral.
+   psi          -- The digamma function.
+   rgamma       -- Gamma function inverted.
+   polygamma    -- Polygamma function n.
+   multigammaln -- Returns the log of multivariate gamma, also sometimes called the generalized gamma.
+   digamma      -- psi(x[, out]).
+   poch         -- Rising factorial (z)_m.
+
+Error function and Fresnel integrals
+------------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   erf           -- Returns the error function of complex argument.
+   erfc          -- Complementary error function, ``1 - erf(x)``.
+   erfcx         -- Scaled complementary error function, ``exp(x**2) * erfc(x)``.
+   erfi          -- Imaginary error function, ``-i erf(i z)``.
+   erfinv        -- Inverse function for erf.
+   erfcinv       -- Inverse function for erfc.
+   wofz          -- Faddeeva function.
+   dawsn         -- Dawson's integral.
+   fresnel       -- Fresnel sin and cos integrals.
+   fresnel_zeros -- Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
+   modfresnelp   -- Modified Fresnel positive integrals.
+   modfresnelm   -- Modified Fresnel negative integrals.
+   voigt_profile -- Voigt profile.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   erf_zeros      -- Compute nt complex zeros of error function erf(z).
+   fresnelc_zeros -- Compute nt complex zeros of cosine Fresnel integral C(z).
+   fresnels_zeros -- Compute nt complex zeros of sine Fresnel integral S(z).
+
+Legendre functions
+------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   legendre_p                 -- Legendre polynomials of the first kind.
+   legendre_p_all             -- All Legendre polynomials of the first kind up to a specified order.
+   assoc_legendre_p           -- Associated Legendre polynomials of the first kind.
+   assoc_legendre_p_all       -- All associated Legendre polynomials of the first kind up to a specified order and degree.
+   sph_legendre_p             -- Spherical Legendre polynomials of the first kind.
+   sph_legendre_p_all         -- All spherical Legendre polynomials of the first kind up to a specified order and degree.
+   sph_harm_y                 -- Spherical harmonics.
+   sph_harm_y_all             -- All spherical harmonics up to a specified order and degree.
+
+The following functions are in the process of being deprecated in favor of the above,
+which provide a more flexible and consistent interface.
+
+.. autosummary::
+   :toctree: generated/
+
+   lpmv                       -- Associated Legendre function of integer order and real degree.
+   sph_harm                   -- Compute spherical harmonics.
+   clpmn                      -- Associated Legendre function of the first kind for complex arguments.
+   lpn                        -- Legendre function of the first kind.
+   lqn                        -- Legendre function of the second kind.
+   lpmn                       -- Sequence of associated Legendre functions of the first kind.
+   lqmn                       -- Sequence of associated Legendre functions of the second kind.
+
+Ellipsoidal harmonics
+---------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   ellip_harm   -- Ellipsoidal harmonic functions E^p_n(l).
+   ellip_harm_2 -- Ellipsoidal harmonic functions F^p_n(l).
+   ellip_normal -- Ellipsoidal harmonic normalization constants gamma^p_n.
+
+Orthogonal polynomials
+----------------------
+
+The following functions evaluate values of orthogonal polynomials:
+
+.. autosummary::
+   :toctree: generated/
+
+   assoc_laguerre   -- Compute the generalized (associated) Laguerre polynomial of degree n and order k.
+   eval_legendre    -- Evaluate Legendre polynomial at a point.
+   eval_chebyt      -- Evaluate Chebyshev polynomial of the first kind at a point.
+   eval_chebyu      -- Evaluate Chebyshev polynomial of the second kind at a point.
+   eval_chebyc      -- Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a point.
+   eval_chebys      -- Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a point.
+   eval_jacobi      -- Evaluate Jacobi polynomial at a point.
+   eval_laguerre    -- Evaluate Laguerre polynomial at a point.
+   eval_genlaguerre -- Evaluate generalized Laguerre polynomial at a point.
+   eval_hermite     -- Evaluate physicist's Hermite polynomial at a point.
+   eval_hermitenorm -- Evaluate probabilist's (normalized) Hermite polynomial at a point.
+   eval_gegenbauer  -- Evaluate Gegenbauer polynomial at a point.
+   eval_sh_legendre -- Evaluate shifted Legendre polynomial at a point.
+   eval_sh_chebyt   -- Evaluate shifted Chebyshev polynomial of the first kind at a point.
+   eval_sh_chebyu   -- Evaluate shifted Chebyshev polynomial of the second kind at a point.
+   eval_sh_jacobi   -- Evaluate shifted Jacobi polynomial at a point.
+
+The following functions compute roots and quadrature weights for
+orthogonal polynomials:
+
+.. autosummary::
+   :toctree: generated/
+
+   roots_legendre    -- Gauss-Legendre quadrature.
+   roots_chebyt      -- Gauss-Chebyshev (first kind) quadrature.
+   roots_chebyu      -- Gauss-Chebyshev (second kind) quadrature.
+   roots_chebyc      -- Gauss-Chebyshev (first kind) quadrature.
+   roots_chebys      -- Gauss-Chebyshev (second kind) quadrature.
+   roots_jacobi      -- Gauss-Jacobi quadrature.
+   roots_laguerre    -- Gauss-Laguerre quadrature.
+   roots_genlaguerre -- Gauss-generalized Laguerre quadrature.
+   roots_hermite     -- Gauss-Hermite (physicist's) quadrature.
+   roots_hermitenorm -- Gauss-Hermite (statistician's) quadrature.
+   roots_gegenbauer  -- Gauss-Gegenbauer quadrature.
+   roots_sh_legendre -- Gauss-Legendre (shifted) quadrature.
+   roots_sh_chebyt   -- Gauss-Chebyshev (first kind, shifted) quadrature.
+   roots_sh_chebyu   -- Gauss-Chebyshev (second kind, shifted) quadrature.
+   roots_sh_jacobi   -- Gauss-Jacobi (shifted) quadrature.
+
+The functions below, in turn, return the polynomial coefficients in
+``orthopoly1d`` objects, which function similarly as `numpy.poly1d`.
+The ``orthopoly1d`` class also has an attribute ``weights``, which returns
+the roots, weights, and total weights for the appropriate form of Gaussian
+quadrature. These are returned in an ``n x 3`` array with roots in the first
+column, weights in the second column, and total weights in the final column.
+Note that ``orthopoly1d`` objects are converted to `~numpy.poly1d` when doing
+arithmetic, and lose information of the original orthogonal polynomial.
+
+.. autosummary::
+   :toctree: generated/
+
+   legendre    -- Legendre polynomial.
+   chebyt      -- Chebyshev polynomial of the first kind.
+   chebyu      -- Chebyshev polynomial of the second kind.
+   chebyc      -- Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
+   chebys      -- Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
+   jacobi      -- Jacobi polynomial.
+   laguerre    -- Laguerre polynomial.
+   genlaguerre -- Generalized (associated) Laguerre polynomial.
+   hermite     -- Physicist's Hermite polynomial.
+   hermitenorm -- Normalized (probabilist's) Hermite polynomial.
+   gegenbauer  -- Gegenbauer (ultraspherical) polynomial.
+   sh_legendre -- Shifted Legendre polynomial.
+   sh_chebyt   -- Shifted Chebyshev polynomial of the first kind.
+   sh_chebyu   -- Shifted Chebyshev polynomial of the second kind.
+   sh_jacobi   -- Shifted Jacobi polynomial.
+
+.. warning::
+
+   Computing values of high-order polynomials (around ``order > 20``) using
+   polynomial coefficients is numerically unstable. To evaluate polynomial
+   values, the ``eval_*`` functions should be used instead.
+
+
+Hypergeometric functions
+------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   hyp2f1 -- Gauss hypergeometric function 2F1(a, b; c; z).
+   hyp1f1 -- Confluent hypergeometric function 1F1(a, b; x).
+   hyperu -- Confluent hypergeometric function U(a, b, x) of the second kind.
+   hyp0f1 -- Confluent hypergeometric limit function 0F1.
+
+
+Parabolic cylinder functions
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   pbdv -- Parabolic cylinder function D.
+   pbvv -- Parabolic cylinder function V.
+   pbwa -- Parabolic cylinder function W.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   pbdv_seq -- Parabolic cylinder functions Dv(x) and derivatives.
+   pbvv_seq -- Parabolic cylinder functions Vv(x) and derivatives.
+   pbdn_seq -- Parabolic cylinder functions Dn(z) and derivatives.
+
+Mathieu and related functions
+-----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   mathieu_a -- Characteristic value of even Mathieu functions.
+   mathieu_b -- Characteristic value of odd Mathieu functions.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   mathieu_even_coef -- Fourier coefficients for even Mathieu and modified Mathieu functions.
+   mathieu_odd_coef  -- Fourier coefficients for even Mathieu and modified Mathieu functions.
+
+The following return both function and first derivative:
+
+.. autosummary::
+   :toctree: generated/
+
+   mathieu_cem     -- Even Mathieu function and its derivative.
+   mathieu_sem     -- Odd Mathieu function and its derivative.
+   mathieu_modcem1 -- Even modified Mathieu function of the first kind and its derivative.
+   mathieu_modcem2 -- Even modified Mathieu function of the second kind and its derivative.
+   mathieu_modsem1 -- Odd modified Mathieu function of the first kind and its derivative.
+   mathieu_modsem2 -- Odd modified Mathieu function of the second kind and its derivative.
+
+Spheroidal wave functions
+-------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   pro_ang1   -- Prolate spheroidal angular function of the first kind and its derivative.
+   pro_rad1   -- Prolate spheroidal radial function of the first kind and its derivative.
+   pro_rad2   -- Prolate spheroidal radial function of the second kind and its derivative.
+   obl_ang1   -- Oblate spheroidal angular function of the first kind and its derivative.
+   obl_rad1   -- Oblate spheroidal radial function of the first kind and its derivative.
+   obl_rad2   -- Oblate spheroidal radial function of the second kind and its derivative.
+   pro_cv     -- Characteristic value of prolate spheroidal function.
+   obl_cv     -- Characteristic value of oblate spheroidal function.
+   pro_cv_seq -- Characteristic values for prolate spheroidal wave functions.
+   obl_cv_seq -- Characteristic values for oblate spheroidal wave functions.
+
+The following functions require pre-computed characteristic value:
+
+.. autosummary::
+   :toctree: generated/
+
+   pro_ang1_cv -- Prolate spheroidal angular function pro_ang1 for precomputed characteristic value.
+   pro_rad1_cv -- Prolate spheroidal radial function pro_rad1 for precomputed characteristic value.
+   pro_rad2_cv -- Prolate spheroidal radial function pro_rad2 for precomputed characteristic value.
+   obl_ang1_cv -- Oblate spheroidal angular function obl_ang1 for precomputed characteristic value.
+   obl_rad1_cv -- Oblate spheroidal radial function obl_rad1 for precomputed characteristic value.
+   obl_rad2_cv -- Oblate spheroidal radial function obl_rad2 for precomputed characteristic value.
+
+Kelvin functions
+----------------
+
+.. autosummary::
+   :toctree: generated/
+
+   kelvin       -- Kelvin functions as complex numbers.
+   kelvin_zeros -- Compute nt zeros of all Kelvin functions.
+   ber          -- Kelvin function ber.
+   bei          -- Kelvin function bei
+   berp         -- Derivative of the Kelvin function `ber`.
+   beip         -- Derivative of the Kelvin function `bei`.
+   ker          -- Kelvin function ker.
+   kei          -- Kelvin function ker.
+   kerp         -- Derivative of the Kelvin function ker.
+   keip         -- Derivative of the Kelvin function kei.
+
+The following functions do not accept NumPy arrays (they are not
+universal functions):
+
+.. autosummary::
+   :toctree: generated/
+
+   ber_zeros  -- Compute nt zeros of the Kelvin function ber(x).
+   bei_zeros  -- Compute nt zeros of the Kelvin function bei(x).
+   berp_zeros -- Compute nt zeros of the Kelvin function ber'(x).
+   beip_zeros -- Compute nt zeros of the Kelvin function bei'(x).
+   ker_zeros  -- Compute nt zeros of the Kelvin function ker(x).
+   kei_zeros  -- Compute nt zeros of the Kelvin function kei(x).
+   kerp_zeros -- Compute nt zeros of the Kelvin function ker'(x).
+   keip_zeros -- Compute nt zeros of the Kelvin function kei'(x).
+
+Combinatorics
+-------------
+
+.. autosummary::
+   :toctree: generated/
+
+   comb -- The number of combinations of N things taken k at a time.
+   perm -- Permutations of N things taken k at a time, i.e., k-permutations of N.
+   stirling2 -- Stirling numbers of the second kind.
+
+Lambert W and related functions
+-------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   lambertw    -- Lambert W function.
+   wrightomega -- Wright Omega function.
+
+Other special functions
+-----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   agm         -- Arithmetic, Geometric Mean.
+   bernoulli   -- Bernoulli numbers B0..Bn (inclusive).
+   binom       -- Binomial coefficient
+   diric       -- Periodic sinc function, also called the Dirichlet function.
+   euler       -- Euler numbers E0..En (inclusive).
+   expn        -- Exponential integral E_n.
+   exp1        -- Exponential integral E_1 of complex argument z.
+   expi        -- Exponential integral Ei.
+   factorial   -- The factorial of a number or array of numbers.
+   factorial2  -- Double factorial.
+   factorialk  -- Multifactorial of n of order k, n(!!...!).
+   shichi      -- Hyperbolic sine and cosine integrals.
+   sici        -- Sine and cosine integrals.
+   softmax     -- Softmax function.
+   log_softmax -- Logarithm of softmax function.
+   spence      -- Spence's function, also known as the dilogarithm.
+   zeta        -- Riemann zeta function.
+   zetac       -- Riemann zeta function minus 1.
+   softplus    -- Softplus function.
+
+Convenience functions
+---------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   cbrt      -- Cube root of `x`.
+   exp10     -- 10**x.
+   exp2      -- 2**x.
+   radian    -- Convert from degrees to radians.
+   cosdg     -- Cosine of the angle `x` given in degrees.
+   sindg     -- Sine of angle given in degrees.
+   tandg     -- Tangent of angle x given in degrees.
+   cotdg     -- Cotangent of the angle `x` given in degrees.
+   log1p     -- Calculates log(1+x) for use when `x` is near zero.
+   expm1     -- ``exp(x) - 1`` for use when `x` is near zero.
+   cosm1     -- ``cos(x) - 1`` for use when `x` is near zero.
+   powm1     -- ``x**y - 1`` for use when `y` is near zero or `x` is near 1.
+   round     -- Round to nearest integer.
+   xlogy     -- Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.
+   xlog1py   -- Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.
+   logsumexp -- Compute the log of the sum of exponentials of input elements.
+   exprel    -- Relative error exponential, (exp(x)-1)/x, for use when `x` is near zero.
+   sinc      -- Return the sinc function.
+
+"""  # noqa: E501
+
+import os
+import warnings
+
+
+def _load_libsf_error_state():
+    """Load libsf_error_state.dll shared library on Windows
+
+    libsf_error_state manages shared state used by
+    ``scipy.special.seterr`` and ``scipy.special.geterr`` so that these
+    can work consistently between special functions provided by different
+    extension modules. This shared library is installed in scipy/special
+    alongside this __init__.py file. Due to lack of rpath support, Windows
+    cannot find shared libraries installed within wheels. To circumvent this,
+    we pre-load ``lib_sf_error_state.dll`` when on Windows.
+
+    The logic for this function was borrowed from the function ``make_init``
+    in `scipy/tools/openblas_support.py`:
+    https://github.com/scipy/scipy/blob/bb92c8014e21052e7dde67a76b28214dd1dcb94a/tools/openblas_support.py#L239-L274
+    """  # noqa: E501
+    if os.name == "nt":
+        try:
+            from ctypes import WinDLL
+            basedir = os.path.dirname(__file__)
+        except:  # noqa: E722
+            pass
+        else:
+            dll_path = os.path.join(basedir, "libsf_error_state.dll")
+            if os.path.exists(dll_path):
+                WinDLL(dll_path)
+
+
+_load_libsf_error_state()
+
+
+from ._sf_error import SpecialFunctionWarning, SpecialFunctionError
+
+from . import _ufuncs
+from ._ufuncs import *
+
+# Replace some function definitions from _ufuncs to add Array API support
+from ._support_alternative_backends import (
+    log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e, gammaln,
+    gammainc, gammaincc, logit, expit, entr, rel_entr, xlogy,
+    chdtr, chdtrc, betainc, betaincc, stdtr)
+
+from . import _basic
+from ._basic import *
+
+from ._logsumexp import logsumexp, softmax, log_softmax
+
+from . import _multiufuncs
+from ._multiufuncs import *
+
+from . import _orthogonal
+from ._orthogonal import *
+
+from ._spfun_stats import multigammaln
+from ._ellip_harm import (
+    ellip_harm,
+    ellip_harm_2,
+    ellip_normal
+)
+from ._lambertw import lambertw
+from ._spherical_bessel import (
+    spherical_jn,
+    spherical_yn,
+    spherical_in,
+    spherical_kn
+)
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import add_newdocs, basic, orthogonal, specfun, sf_error, spfun_stats
+
+# We replace some function definitions from _ufuncs with those from
+# _support_alternative_backends above, but those are all listed in _ufuncs.__all__,
+# so there is no need to consider _support_alternative_backends.__all__ here.
+__all__ = _ufuncs.__all__ + _basic.__all__ + _orthogonal.__all__ + _multiufuncs.__all__
+__all__ += [
+    'SpecialFunctionWarning',
+    'SpecialFunctionError',
+    'logsumexp',
+    'softmax',
+    'log_softmax',
+    'multigammaln',
+    'ellip_harm',
+    'ellip_harm_2',
+    'ellip_normal',
+    'lambertw',
+    'spherical_jn',
+    'spherical_yn',
+    'spherical_in',
+    'spherical_kn',
+]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
+
+
+def _get_include():
+    """This function is for development purposes only.
+
+    This function could disappear or its behavior could change at any time.
+    """
+    import os
+    return os.path.dirname(__file__)
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f9303d479861c934a1eb8065c33c8f891c245bc
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfc697f999413af8cb4ddecf2439e84d43e32e19
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_ellip_harm.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_input_validation.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_input_validation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0dd1aa2e01167cd42ac0f8a31d612a1d6fdf81dd
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_input_validation.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..441720cfe0ef7f42d947b9fb63eb44f258bfd315
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_lambertw.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aefbd6df2e01a0bf2c24b4ded48855e54f87d44f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_logsumexp.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_multiufuncs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_multiufuncs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9d0b74ce4ddf4c14cb96ad83259a8142c9b6354
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_multiufuncs.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a0d3db30689fad6d115c4525977d5986e2486b3
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_orthogonal.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16dfe59f23ccf3abf3042c93d36ebb2608bef3c4
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_sf_error.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..767f5f303dbdb3f89684955d56a007bb80c44d58
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spfun_stats.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb67749338a0426cb756160a5d2884b3144a2f31
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_spherical_bessel.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..936f08772c6e2b19a7d0a930a18533fe3ec1b89a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/_support_alternative_backends.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42d9ca9e971a2c88ca53f9d7609de4984ca70ea8
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/add_newdocs.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a9174e6cf3f00c8c32bc41191ef255c54b8fd94
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/basic.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d44f9756af70eda7e9158dce1a692d24c4dc503
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/orthogonal.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a765ef5cb09468ab919e9548c7165b4ff4958e26
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/sf_error.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ac4a4e6e9045d0007fc1555fc956783095ccdf9
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/specfun.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28a0e7dbfcdc0c62735afdf35f1bd59bd92ca3a1
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/__pycache__/spfun_stats.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..134604c90128a59d48dee66318fa6fd02308f80c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_add_newdocs.py
@@ -0,0 +1,10699 @@
+# Docstrings for generated ufuncs
+#
+# The syntax is designed to look like the function add_newdoc is being
+# called from numpy.lib, but in this file add_newdoc puts the
+# docstrings in a dictionary. This dictionary is used in
+# _generate_pyx.py to generate the docstrings for the ufuncs in
+# scipy.special at the C level when the ufuncs are created at compile
+# time.
+
+docdict: dict[str, str] = {}
+
+
+def get(name):
+    return docdict.get(name)
+
+
+def add_newdoc(name, doc):
+    docdict[name] = doc
+
+
+add_newdoc("_sf_error_test_function",
+    """
+    Private function; do not use.
+    """)
+
+
+add_newdoc("_cosine_cdf",
+    """
+    _cosine_cdf(x)
+
+    Cumulative distribution function (CDF) of the cosine distribution::
+
+                 {             0,              x < -pi
+        cdf(x) = { (pi + x + sin(x))/(2*pi),   -pi <= x <= pi
+                 {             1,              x > pi
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+
+    Returns
+    -------
+    scalar or ndarray
+        The cosine distribution CDF evaluated at `x`.
+
+    """)
+
+add_newdoc("_cosine_invcdf",
+    """
+    _cosine_invcdf(p)
+
+    Inverse of the cumulative distribution function (CDF) of the cosine
+    distribution.
+
+    The CDF of the cosine distribution is::
+
+        cdf(x) = (pi + x + sin(x))/(2*pi)
+
+    This function computes the inverse of cdf(x).
+
+    Parameters
+    ----------
+    p : array_like
+        `p` must contain real numbers in the interval ``0 <= p <= 1``.
+        `nan` is returned for values of `p` outside the interval [0, 1].
+
+    Returns
+    -------
+    scalar or ndarray
+        The inverse of the cosine distribution CDF evaluated at `p`.
+
+    """)
+
+add_newdoc("_ellip_harm",
+    """
+    Internal function, use `ellip_harm` instead.
+    """)
+
+add_newdoc("_ellip_norm",
+    """
+    Internal function, use `ellip_norm` instead.
+    """)
+
+add_newdoc("voigt_profile",
+    r"""
+    voigt_profile(x, sigma, gamma, out=None)
+
+    Voigt profile.
+
+    The Voigt profile is a convolution of a 1-D Normal distribution with
+    standard deviation ``sigma`` and a 1-D Cauchy distribution with half-width at
+    half-maximum ``gamma``.
+
+    If ``sigma = 0``, PDF of Cauchy distribution is returned.
+    Conversely, if ``gamma = 0``, PDF of Normal distribution is returned.
+    If ``sigma = gamma = 0``, the return value is ``Inf`` for ``x = 0``,
+    and ``0`` for all other ``x``.
+
+    Parameters
+    ----------
+    x : array_like
+        Real argument
+    sigma : array_like
+        The standard deviation of the Normal distribution part
+    gamma : array_like
+        The half-width at half-maximum of the Cauchy distribution part
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The Voigt profile at the given arguments
+
+    See Also
+    --------
+    wofz : Faddeeva function
+
+    Notes
+    -----
+    It can be expressed in terms of Faddeeva function
+
+    .. math:: V(x; \sigma, \gamma) = \frac{Re[w(z)]}{\sigma\sqrt{2\pi}},
+    .. math:: z = \frac{x + i\gamma}{\sqrt{2}\sigma}
+
+    where :math:`w(z)` is the Faddeeva function.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Voigt_profile
+
+    Examples
+    --------
+    Calculate the function at point 2 for ``sigma=1`` and ``gamma=1``.
+
+    >>> from scipy.special import voigt_profile
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> voigt_profile(2, 1., 1.)
+    0.09071519942627544
+
+    Calculate the function at several points by providing a NumPy array
+    for `x`.
+
+    >>> values = np.array([-2., 0., 5])
+    >>> voigt_profile(values, 1., 1.)
+    array([0.0907152 , 0.20870928, 0.01388492])
+
+    Plot the function for different parameter sets.
+
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> x = np.linspace(-10, 10, 500)
+    >>> parameters_list = [(1.5, 0., "solid"), (1.3, 0.5, "dashed"),
+    ...                    (0., 1.8, "dotted"), (1., 1., "dashdot")]
+    >>> for params in parameters_list:
+    ...     sigma, gamma, linestyle = params
+    ...     voigt = voigt_profile(x, sigma, gamma)
+    ...     ax.plot(x, voigt, label=rf"$\sigma={sigma},\, \gamma={gamma}$",
+    ...             ls=linestyle)
+    >>> ax.legend()
+    >>> plt.show()
+
+    Verify visually that the Voigt profile indeed arises as the convolution
+    of a normal and a Cauchy distribution.
+
+    >>> from scipy.signal import convolve
+    >>> x, dx = np.linspace(-10, 10, 500, retstep=True)
+    >>> def gaussian(x, sigma):
+    ...     return np.exp(-0.5 * x**2/sigma**2)/(sigma * np.sqrt(2*np.pi))
+    >>> def cauchy(x, gamma):
+    ...     return gamma/(np.pi * (np.square(x)+gamma**2))
+    >>> sigma = 2
+    >>> gamma = 1
+    >>> gauss_profile = gaussian(x, sigma)
+    >>> cauchy_profile = cauchy(x, gamma)
+    >>> convolved = dx * convolve(cauchy_profile, gauss_profile, mode="same")
+    >>> voigt = voigt_profile(x, sigma, gamma)
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> ax.plot(x, gauss_profile, label="Gauss: $G$", c='b')
+    >>> ax.plot(x, cauchy_profile, label="Cauchy: $C$", c='y', ls="dashed")
+    >>> xx = 0.5*(x[1:] + x[:-1])  # midpoints
+    >>> ax.plot(xx, convolved[1:], label="Convolution: $G * C$", ls='dashdot',
+    ...         c='k')
+    >>> ax.plot(x, voigt, label="Voigt", ls='dotted', c='r')
+    >>> ax.legend()
+    >>> plt.show()
+    """)
+
+add_newdoc("wrightomega",
+    r"""
+    wrightomega(z, out=None)
+
+    Wright Omega function.
+
+    Defined as the solution to
+
+    .. math::
+
+        \omega + \log(\omega) = z
+
+    where :math:`\log` is the principal branch of the complex logarithm.
+
+    Parameters
+    ----------
+    z : array_like
+        Points at which to evaluate the Wright Omega function
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    omega : scalar or ndarray
+        Values of the Wright Omega function
+
+    See Also
+    --------
+    lambertw : The Lambert W function
+
+    Notes
+    -----
+    .. versionadded:: 0.19.0
+
+    The function can also be defined as
+
+    .. math::
+
+        \omega(z) = W_{K(z)}(e^z)
+
+    where :math:`K(z) = \lceil (\Im(z) - \pi)/(2\pi) \rceil` is the
+    unwinding number and :math:`W` is the Lambert W function.
+
+    The implementation here is taken from [1]_.
+
+    References
+    ----------
+    .. [1] Lawrence, Corless, and Jeffrey, "Algorithm 917: Complex
+           Double-Precision Evaluation of the Wright :math:`\omega`
+           Function." ACM Transactions on Mathematical Software,
+           2012. :doi:`10.1145/2168773.2168779`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import wrightomega, lambertw
+
+    >>> wrightomega([-2, -1, 0, 1, 2])
+    array([0.12002824, 0.27846454, 0.56714329, 1.        , 1.5571456 ])
+
+    Complex input:
+
+    >>> wrightomega(3 + 5j)
+    (1.5804428632097158+3.8213626783287937j)
+
+    Verify that ``wrightomega(z)`` satisfies ``w + log(w) = z``:
+
+    >>> w = -5 + 4j
+    >>> wrightomega(w + np.log(w))
+    (-5+4j)
+
+    Verify the connection to ``lambertw``:
+
+    >>> z = 0.5 + 3j
+    >>> wrightomega(z)
+    (0.0966015889280649+1.4937828458191993j)
+    >>> lambertw(np.exp(z))
+    (0.09660158892806493+1.4937828458191993j)
+
+    >>> z = 0.5 + 4j
+    >>> wrightomega(z)
+    (-0.3362123489037213+2.282986001579032j)
+    >>> lambertw(np.exp(z), k=1)
+    (-0.33621234890372115+2.282986001579032j)
+    """)
+
+
+add_newdoc("agm",
+    """
+    agm(a, b, out=None)
+
+    Compute the arithmetic-geometric mean of `a` and `b`.
+
+    Start with a_0 = a and b_0 = b and iteratively compute::
+
+        a_{n+1} = (a_n + b_n)/2
+        b_{n+1} = sqrt(a_n*b_n)
+
+    a_n and b_n converge to the same limit as n increases; their common
+    limit is agm(a, b).
+
+    Parameters
+    ----------
+    a, b : array_like
+        Real values only. If the values are both negative, the result
+        is negative. If one value is negative and the other is positive,
+        `nan` is returned.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The arithmetic-geometric mean of `a` and `b`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import agm
+    >>> a, b = 24.0, 6.0
+    >>> agm(a, b)
+    13.458171481725614
+
+    Compare that result to the iteration:
+
+    >>> while a != b:
+    ...     a, b = (a + b)/2, np.sqrt(a*b)
+    ...     print("a = %19.16f  b=%19.16f" % (a, b))
+    ...
+    a = 15.0000000000000000  b=12.0000000000000000
+    a = 13.5000000000000000  b=13.4164078649987388
+    a = 13.4582039324993694  b=13.4581390309909850
+    a = 13.4581714817451772  b=13.4581714817060547
+    a = 13.4581714817256159  b=13.4581714817256159
+
+    When array-like arguments are given, broadcasting applies:
+
+    >>> a = np.array([[1.5], [3], [6]])  # a has shape (3, 1).
+    >>> b = np.array([6, 12, 24, 48])    # b has shape (4,).
+    >>> agm(a, b)
+    array([[  3.36454287,   5.42363427,   9.05798751,  15.53650756],
+           [  4.37037309,   6.72908574,  10.84726853,  18.11597502],
+           [  6.        ,   8.74074619,  13.45817148,  21.69453707]])
+    """)
+
+add_newdoc("airy",
+    r"""
+    airy(z, out=None)
+
+    Airy functions and their derivatives.
+
+    Parameters
+    ----------
+    z : array_like
+        Real or complex argument.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function values
+
+    Returns
+    -------
+    Ai, Aip, Bi, Bip : 4-tuple of scalar or ndarray
+        Airy functions Ai and Bi, and their derivatives Aip and Bip.
+
+    See Also
+    --------
+    airye : exponentially scaled Airy functions.
+
+    Notes
+    -----
+    The Airy functions Ai and Bi are two independent solutions of
+
+    .. math:: y''(x) = x y(x).
+
+    For real `z` in [-10, 10], the computation is carried out by calling
+    the Cephes [1]_ `airy` routine, which uses power series summation
+    for small `z` and rational minimax approximations for large `z`.
+
+    Outside this range, the AMOS [2]_ `zairy` and `zbiry` routines are
+    employed.  They are computed using power series for :math:`|z| < 1` and
+    the following relations to modified Bessel functions for larger `z`
+    (where :math:`t \equiv 2 z^{3/2}/3`):
+
+    .. math::
+
+        Ai(z) = \frac{1}{\pi \sqrt{3}} K_{1/3}(t)
+
+        Ai'(z) = -\frac{z}{\pi \sqrt{3}} K_{2/3}(t)
+
+        Bi(z) = \sqrt{\frac{z}{3}} \left(I_{-1/3}(t) + I_{1/3}(t) \right)
+
+        Bi'(z) = \frac{z}{\sqrt{3}} \left(I_{-2/3}(t) + I_{2/3}(t)\right)
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [2] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Compute the Airy functions on the interval [-15, 5].
+
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> x = np.linspace(-15, 5, 201)
+    >>> ai, aip, bi, bip = special.airy(x)
+
+    Plot Ai(x) and Bi(x).
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.plot(x, ai, 'r', label='Ai(x)')
+    >>> plt.plot(x, bi, 'b--', label='Bi(x)')
+    >>> plt.ylim(-0.5, 1.0)
+    >>> plt.grid()
+    >>> plt.legend(loc='upper left')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("airye",
+    """
+    airye(z, out=None)
+
+    Exponentially scaled Airy functions and their derivatives.
+
+    Scaling::
+
+        eAi  = Ai  * exp(2.0/3.0*z*sqrt(z))
+        eAip = Aip * exp(2.0/3.0*z*sqrt(z))
+        eBi  = Bi  * exp(-abs(2.0/3.0*(z*sqrt(z)).real))
+        eBip = Bip * exp(-abs(2.0/3.0*(z*sqrt(z)).real))
+
+    Parameters
+    ----------
+    z : array_like
+        Real or complex argument.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function values
+
+    Returns
+    -------
+    eAi, eAip, eBi, eBip : 4-tuple of scalar or ndarray
+        Exponentially scaled Airy functions eAi and eBi, and their derivatives
+        eAip and eBip
+
+    See Also
+    --------
+    airy
+
+    Notes
+    -----
+    Wrapper for the AMOS [1]_ routines `zairy` and `zbiry`.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    We can compute exponentially scaled Airy functions and their derivatives:
+
+    >>> import numpy as np
+    >>> from scipy.special import airye
+    >>> import matplotlib.pyplot as plt
+    >>> z = np.linspace(0, 50, 500)
+    >>> eAi, eAip, eBi, eBip = airye(z)
+    >>> f, ax = plt.subplots(2, 1, sharex=True)
+    >>> for ind, data in enumerate([[eAi, eAip, ["eAi", "eAip"]],
+    ...                             [eBi, eBip, ["eBi", "eBip"]]]):
+    ...     ax[ind].plot(z, data[0], "-r", z, data[1], "-b")
+    ...     ax[ind].legend(data[2])
+    ...     ax[ind].grid(True)
+    >>> plt.show()
+
+    We can compute these using usual non-scaled Airy functions by:
+
+    >>> from scipy.special import airy
+    >>> Ai, Aip, Bi, Bip = airy(z)
+    >>> np.allclose(eAi, Ai * np.exp(2.0 / 3.0 * z * np.sqrt(z)))
+    True
+    >>> np.allclose(eAip, Aip * np.exp(2.0 / 3.0 * z * np.sqrt(z)))
+    True
+    >>> np.allclose(eBi, Bi * np.exp(-abs(np.real(2.0 / 3.0 * z * np.sqrt(z)))))
+    True
+    >>> np.allclose(eBip, Bip * np.exp(-abs(np.real(2.0 / 3.0 * z * np.sqrt(z)))))
+    True
+
+    Comparing non-scaled and exponentially scaled ones, the usual non-scaled
+    function quickly underflows for large values, whereas the exponentially
+    scaled function does not.
+
+    >>> airy(200)
+    (0.0, 0.0, nan, nan)
+    >>> airye(200)
+    (0.07501041684381093, -1.0609012305109042, 0.15003188417418148, 2.1215836725571093)
+
+    """)
+
+add_newdoc("bdtr",
+    r"""
+    bdtr(k, n, p, out=None)
+
+    Binomial distribution cumulative distribution function.
+
+    Sum of the terms 0 through `floor(k)` of the Binomial probability density.
+
+    .. math::
+        \mathrm{bdtr}(k, n, p) =
+        \sum_{j=0}^{\lfloor k \rfloor} {{n}\choose{j}} p^j (1-p)^{n-j}
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (double), rounded down to the nearest integer.
+    n : array_like
+        Number of events (int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Probability of `floor(k)` or fewer successes in `n` independent events with
+        success probabilities of `p`.
+
+    Notes
+    -----
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{bdtr}(k, n, p) =
+        I_{1 - p}(n - \lfloor k \rfloor, \lfloor k \rfloor + 1).
+
+    Wrapper for the Cephes [1]_ routine `bdtr`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    """)
+
+add_newdoc("bdtrc",
+    r"""
+    bdtrc(k, n, p, out=None)
+
+    Binomial distribution survival function.
+
+    Sum of the terms `floor(k) + 1` through `n` of the binomial probability
+    density,
+
+    .. math::
+        \mathrm{bdtrc}(k, n, p) =
+        \sum_{j=\lfloor k \rfloor +1}^n {{n}\choose{j}} p^j (1-p)^{n-j}
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (double), rounded down to nearest integer.
+    n : array_like
+        Number of events (int)
+    p : array_like
+        Probability of success in a single event.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Probability of `floor(k) + 1` or more successes in `n` independent
+        events with success probabilities of `p`.
+
+    See Also
+    --------
+    bdtr
+    betainc
+
+    Notes
+    -----
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{bdtrc}(k, n, p) = I_{p}(\lfloor k \rfloor + 1, n - \lfloor k \rfloor).
+
+    Wrapper for the Cephes [1]_ routine `bdtrc`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    """)
+
+add_newdoc("bdtri",
+    r"""
+    bdtri(k, n, y, out=None)
+
+    Inverse function to `bdtr` with respect to `p`.
+
+    Finds the event probability `p` such that the sum of the terms 0 through
+    `k` of the binomial probability density is equal to the given cumulative
+    probability `y`.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (float), rounded down to the nearest integer.
+    n : array_like
+        Number of events (float)
+    y : array_like
+        Cumulative probability (probability of `k` or fewer successes in `n`
+        events).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    p : scalar or ndarray
+        The event probability such that `bdtr(\lfloor k \rfloor, n, p) = y`.
+
+    See Also
+    --------
+    bdtr
+    betaincinv
+
+    Notes
+    -----
+    The computation is carried out using the inverse beta integral function
+    and the relation,::
+
+        1 - p = betaincinv(n - k, k + 1, y).
+
+    Wrapper for the Cephes [1]_ routine `bdtri`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    """)
+
+add_newdoc("bdtrik",
+    """
+    bdtrik(y, n, p, out=None)
+
+    Inverse function to `bdtr` with respect to `k`.
+
+    Finds the number of successes `k` such that the sum of the terms 0 through
+    `k` of the Binomial probability density for `n` events with probability
+    `p` is equal to the given cumulative probability `y`.
+
+    Parameters
+    ----------
+    y : array_like
+        Cumulative probability (probability of `k` or fewer successes in `n`
+        events).
+    n : array_like
+        Number of events (float).
+    p : array_like
+        Success probability (float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    k : scalar or ndarray
+        The number of successes `k` such that `bdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    bdtr
+
+    Notes
+    -----
+    Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the
+    cumulative incomplete beta distribution.
+
+    Computation of `k` involves a search for a value that produces the desired
+    value of `y`. The search relies on the monotonicity of `y` with `k`.
+
+    Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+    .. [2] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+
+    """)
+
+add_newdoc("bdtrin",
+    """
+    bdtrin(k, y, p, out=None)
+
+    Inverse function to `bdtr` with respect to `n`.
+
+    Finds the number of events `n` such that the sum of the terms 0 through
+    `k` of the Binomial probability density for events with probability `p` is
+    equal to the given cumulative probability `y`.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of successes (float).
+    y : array_like
+        Cumulative probability (probability of `k` or fewer successes in `n`
+        events).
+    p : array_like
+        Success probability (float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    n : scalar or ndarray
+        The number of events `n` such that `bdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    bdtr
+
+    Notes
+    -----
+    Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the
+    cumulative incomplete beta distribution.
+
+    Computation of `n` involves a search for a value that produces the desired
+    value of `y`. The search relies on the monotonicity of `y` with `n`.
+
+    Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+    .. [2] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    """)
+
+add_newdoc("btdtria",
+    r"""
+    btdtria(p, b, x, out=None)
+
+    Inverse of `betainc` with respect to `a`.
+
+    This is the inverse of the beta cumulative distribution function, `betainc`,
+    considered as a function of `a`, returning the value of `a` for which
+    `betainc(a, b, x) = p`, or
+
+    .. math::
+        p = \int_0^x \frac{\Gamma(a + b)}{\Gamma(a)\Gamma(b)} t^{a-1} (1-t)^{b-1}\,dt
+
+    Parameters
+    ----------
+    p : array_like
+        Cumulative probability, in [0, 1].
+    b : array_like
+        Shape parameter (`b` > 0).
+    x : array_like
+        The quantile, in [0, 1].
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    a : scalar or ndarray
+        The value of the shape parameter `a` such that `betainc(a, b, x) = p`.
+
+    See Also
+    --------
+    btdtrib : Inverse of the beta cumulative distribution function, with respect to `b`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `a` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `a`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Algorithm 708: Significant Digit Computation of the Incomplete Beta
+           Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.
+
+    """)
+
+add_newdoc("btdtrib",
+    r"""
+    btdtria(a, p, x, out=None)
+
+    Inverse of `betainc` with respect to `b`.
+
+    This is the inverse of the beta cumulative distribution function, `betainc`,
+    considered as a function of `b`, returning the value of `b` for which
+    `betainc(a, b, x) = p`, or
+
+    .. math::
+        p = \int_0^x \frac{\Gamma(a + b)}{\Gamma(a)\Gamma(b)} t^{a-1} (1-t)^{b-1}\,dt
+
+    Parameters
+    ----------
+    a : array_like
+        Shape parameter (`a` > 0).
+    p : array_like
+        Cumulative probability, in [0, 1].
+    x : array_like
+        The quantile, in [0, 1].
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    b : scalar or ndarray
+        The value of the shape parameter `b` such that `betainc(a, b, x) = p`.
+
+    See Also
+    --------
+    btdtria : Inverse of the beta cumulative distribution function, with respect to `a`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `b` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `b`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Algorithm 708: Significant Digit Computation of the Incomplete Beta
+           Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.
+
+
+    """)
+
+add_newdoc(
+    "betainc",
+    r"""
+    betainc(a, b, x, out=None)
+
+    Regularized incomplete beta function.
+
+    Computes the regularized incomplete beta function, defined as [1]_:
+
+    .. math::
+
+        I_x(a, b) = \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} \int_0^x
+        t^{a-1}(1-t)^{b-1}dt,
+
+    for :math:`0 \leq x \leq 1`.
+
+    This function is the cumulative distribution function for the beta
+    distribution; its range is [0, 1].
+
+    Parameters
+    ----------
+    a, b : array_like
+           Positive, real-valued parameters
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the regularized incomplete beta function
+
+    See Also
+    --------
+    beta : beta function
+    betaincinv : inverse of the regularized incomplete beta function
+    betaincc : complement of the regularized incomplete beta function
+    scipy.stats.beta : beta distribution
+
+    Notes
+    -----
+    The term *regularized* in the name of this function refers to the
+    scaling of the function by the gamma function terms shown in the
+    formula.  When not qualified as *regularized*, the name *incomplete
+    beta function* often refers to just the integral expression,
+    without the gamma terms.  One can use the function `beta` from
+    `scipy.special` to get this "nonregularized" incomplete beta
+    function by multiplying the result of ``betainc(a, b, x)`` by
+    ``beta(a, b)``.
+
+    This function wraps the ``ibeta`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+
+    Let :math:`B(a, b)` be the `beta` function.
+
+    >>> import scipy.special as sc
+
+    The coefficient in terms of `gamma` is equal to
+    :math:`1/B(a, b)`. Also, when :math:`x=1`
+    the integral is equal to :math:`B(a, b)`.
+    Therefore, :math:`I_{x=1}(a, b) = 1` for any :math:`a, b`.
+
+    >>> sc.betainc(0.2, 3.5, 1.0)
+    1.0
+
+    It satisfies
+    :math:`I_x(a, b) = x^a F(a, 1-b, a+1, x)/ (aB(a, b))`,
+    where :math:`F` is the hypergeometric function `hyp2f1`:
+
+    >>> a, b, x = 1.4, 3.1, 0.5
+    >>> x**a * sc.hyp2f1(a, 1 - b, a + 1, x)/(a * sc.beta(a, b))
+    0.8148904036225295
+    >>> sc.betainc(a, b, x)
+    0.8148904036225296
+
+    This functions satisfies the relationship
+    :math:`I_x(a, b) = 1 - I_{1-x}(b, a)`:
+
+    >>> sc.betainc(2.2, 3.1, 0.4)
+    0.49339638807619446
+    >>> 1 - sc.betainc(3.1, 2.2, 1 - 0.4)
+    0.49339638807619446
+
+    """)
+
+
+add_newdoc(
+    "betaincc",
+    r"""
+    betaincc(a, b, x, out=None)
+
+    Complement of the regularized incomplete beta function.
+
+    Computes the complement of the regularized incomplete beta function,
+    defined as [1]_:
+
+    .. math::
+
+        \bar{I}_x(a, b) = 1 - I_x(a, b)
+                        = 1 - \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)} \int_0^x
+                                  t^{a-1}(1-t)^{b-1}dt,
+
+    for :math:`0 \leq x \leq 1`.
+
+    Parameters
+    ----------
+    a, b : array_like
+           Positive, real-valued parameters
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the regularized incomplete beta function
+
+    See Also
+    --------
+    betainc : regularized incomplete beta function
+    betaincinv : inverse of the regularized incomplete beta function
+    betainccinv :
+        inverse of the complement of the regularized incomplete beta function
+    beta : beta function
+    scipy.stats.beta : beta distribution
+
+    Notes
+    -----
+    .. versionadded:: 1.11.0
+
+    This function wraps the ``ibetac`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> from scipy.special import betaincc, betainc
+
+    The naive calculation ``1 - betainc(a, b, x)`` loses precision when
+    the values of ``betainc(a, b, x)`` are close to 1:
+
+    >>> 1 - betainc(0.5, 8, [0.9, 0.99, 0.999])
+    array([2.0574632e-09, 0.0000000e+00, 0.0000000e+00])
+
+    By using ``betaincc``, we get the correct values:
+
+    >>> betaincc(0.5, 8, [0.9, 0.99, 0.999])
+    array([2.05746321e-09, 1.97259354e-17, 1.96467954e-25])
+
+    """)
+
+add_newdoc(
+    "betaincinv",
+    r"""
+    betaincinv(a, b, y, out=None)
+
+    Inverse of the regularized incomplete beta function.
+
+    Computes :math:`x` such that:
+
+    .. math::
+
+        y = I_x(a, b) = \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}
+        \int_0^x t^{a-1}(1-t)^{b-1}dt,
+
+    where :math:`I_x` is the normalized incomplete beta function `betainc`
+    and :math:`\Gamma` is the `gamma` function [1]_.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Positive, real-valued parameters
+    y : array_like
+        Real-valued input
+    out : ndarray, optional
+        Optional output array for function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the inverse of the regularized incomplete beta function
+
+    See Also
+    --------
+    betainc : regularized incomplete beta function
+    gamma : gamma function
+
+    Notes
+    -----
+    This function wraps the ``ibeta_inv`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    This function is the inverse of `betainc` for fixed
+    values of :math:`a` and :math:`b`.
+
+    >>> a, b = 1.2, 3.1
+    >>> y = sc.betainc(a, b, 0.2)
+    >>> sc.betaincinv(a, b, y)
+    0.2
+    >>>
+    >>> a, b = 7.5, 0.4
+    >>> x = sc.betaincinv(a, b, 0.5)
+    >>> sc.betainc(a, b, x)
+    0.5
+
+    """)
+
+
+add_newdoc(
+    "betainccinv",
+    r"""
+    betainccinv(a, b, y, out=None)
+
+    Inverse of the complemented regularized incomplete beta function.
+
+    Computes :math:`x` such that:
+
+    .. math::
+
+        y = 1 - I_x(a, b) = 1 - \frac{\Gamma(a+b)}{\Gamma(a)\Gamma(b)}
+        \int_0^x t^{a-1}(1-t)^{b-1}dt,
+
+    where :math:`I_x` is the normalized incomplete beta function `betainc`
+    and :math:`\Gamma` is the `gamma` function [1]_.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Positive, real-valued parameters
+    y : array_like
+        Real-valued input
+    out : ndarray, optional
+        Optional output array for function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the inverse of the regularized incomplete beta function
+
+    See Also
+    --------
+    betainc : regularized incomplete beta function
+    betaincc : complement of the regularized incomplete beta function
+
+    Notes
+    -----
+    .. versionadded:: 1.11.0
+
+    This function wraps the ``ibetac_inv`` routine from the
+    Boost Math C++ library [2]_.
+
+    References
+    ----------
+    .. [1] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/8.17
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> from scipy.special import betainccinv, betaincc
+
+    This function is the inverse of `betaincc` for fixed
+    values of :math:`a` and :math:`b`.
+
+    >>> a, b = 1.2, 3.1
+    >>> y = betaincc(a, b, 0.2)
+    >>> betainccinv(a, b, y)
+    0.2
+
+    >>> a, b = 7, 2.5
+    >>> x = betainccinv(a, b, 0.875)
+    >>> betaincc(a, b, x)
+    0.875
+
+    """)
+
+add_newdoc("boxcox",
+    """
+    boxcox(x, lmbda, out=None)
+
+    Compute the Box-Cox transformation.
+
+    The Box-Cox transformation is::
+
+        y = (x**lmbda - 1) / lmbda  if lmbda != 0
+            log(x)                  if lmbda == 0
+
+    Returns `nan` if ``x < 0``.
+    Returns `-inf` if ``x == 0`` and ``lmbda < 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox
+    >>> boxcox([1, 4, 10], 2.5)
+    array([   0.        ,   12.4       ,  126.09110641])
+    >>> boxcox(2, [0, 1, 2])
+    array([ 0.69314718,  1.        ,  1.5       ])
+    """)
+
+add_newdoc("boxcox1p",
+    """
+    boxcox1p(x, lmbda, out=None)
+
+    Compute the Box-Cox transformation of 1 + `x`.
+
+    The Box-Cox transformation computed by `boxcox1p` is::
+
+        y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0
+            log(1+x)                    if lmbda == 0
+
+    Returns `nan` if ``x < -1``.
+    Returns `-inf` if ``x == -1`` and ``lmbda < 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.14.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox1p
+    >>> boxcox1p(1e-4, [0, 0.5, 1])
+    array([  9.99950003e-05,   9.99975001e-05,   1.00000000e-04])
+    >>> boxcox1p([0.01, 0.1], 0.25)
+    array([ 0.00996272,  0.09645476])
+    """)
+
+add_newdoc("inv_boxcox",
+    """
+    inv_boxcox(y, lmbda, out=None)
+
+    Compute the inverse of the Box-Cox transformation.
+
+    Find ``x`` such that::
+
+        y = (x**lmbda - 1) / lmbda  if lmbda != 0
+            log(x)                  if lmbda == 0
+
+    Parameters
+    ----------
+    y : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.16.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox, inv_boxcox
+    >>> y = boxcox([1, 4, 10], 2.5)
+    >>> inv_boxcox(y, 2.5)
+    array([1., 4., 10.])
+    """)
+
+add_newdoc("inv_boxcox1p",
+    """
+    inv_boxcox1p(y, lmbda, out=None)
+
+    Compute the inverse of the Box-Cox transformation.
+
+    Find ``x`` such that::
+
+        y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0
+            log(1+x)                    if lmbda == 0
+
+    Parameters
+    ----------
+    y : array_like
+        Data to be transformed.
+    lmbda : array_like
+        Power parameter of the Box-Cox transform.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Transformed data.
+
+    Notes
+    -----
+
+    .. versionadded:: 0.16.0
+
+    Examples
+    --------
+    >>> from scipy.special import boxcox1p, inv_boxcox1p
+    >>> y = boxcox1p([1, 4, 10], 2.5)
+    >>> inv_boxcox1p(y, 2.5)
+    array([1., 4., 10.])
+    """)
+
+add_newdoc("chdtr",
+    r"""
+    chdtr(v, x, out=None)
+
+    Chi square cumulative distribution function.
+
+    Returns the area under the left tail (from 0 to `x`) of the Chi
+    square probability density function with `v` degrees of freedom:
+
+    .. math::
+
+        \frac{1}{2^{v/2} \Gamma(v/2)} \int_0^x t^{v/2 - 1} e^{-t/2} dt
+
+    Here :math:`\Gamma` is the Gamma function; see `gamma`. This
+    integral can be expressed in terms of the regularized lower
+    incomplete gamma function `gammainc` as
+    ``gammainc(v / 2, x / 2)``. [1]_
+
+    Parameters
+    ----------
+    v : array_like
+        Degrees of freedom.
+    x : array_like
+        Upper bound of the integral.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the cumulative distribution function.
+
+    See Also
+    --------
+    chdtrc, chdtri, chdtriv, gammainc
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It can be expressed in terms of the regularized lower incomplete
+    gamma function.
+
+    >>> v = 1
+    >>> x = np.arange(4)
+    >>> sc.chdtr(v, x)
+    array([0.        , 0.68268949, 0.84270079, 0.91673548])
+    >>> sc.gammainc(v / 2, x / 2)
+    array([0.        , 0.68268949, 0.84270079, 0.91673548])
+
+    """)
+
+add_newdoc("chdtrc",
+    r"""
+    chdtrc(v, x, out=None)
+
+    Chi square survival function.
+
+    Returns the area under the right hand tail (from `x` to infinity)
+    of the Chi square probability density function with `v` degrees of
+    freedom:
+
+    .. math::
+
+        \frac{1}{2^{v/2} \Gamma(v/2)} \int_x^\infty t^{v/2 - 1} e^{-t/2} dt
+
+    Here :math:`\Gamma` is the Gamma function; see `gamma`. This
+    integral can be expressed in terms of the regularized upper
+    incomplete gamma function `gammaincc` as
+    ``gammaincc(v / 2, x / 2)``. [1]_
+
+    Parameters
+    ----------
+    v : array_like
+        Degrees of freedom.
+    x : array_like
+        Lower bound of the integral.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the survival function.
+
+    See Also
+    --------
+    chdtr, chdtri, chdtriv, gammaincc
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It can be expressed in terms of the regularized upper incomplete
+    gamma function.
+
+    >>> v = 1
+    >>> x = np.arange(4)
+    >>> sc.chdtrc(v, x)
+    array([1.        , 0.31731051, 0.15729921, 0.08326452])
+    >>> sc.gammaincc(v / 2, x / 2)
+    array([1.        , 0.31731051, 0.15729921, 0.08326452])
+
+    """)
+
+add_newdoc("chdtri",
+    """
+    chdtri(v, p, out=None)
+
+    Inverse to `chdtrc` with respect to `x`.
+
+    Returns `x` such that ``chdtrc(v, x) == p``.
+
+    Parameters
+    ----------
+    v : array_like
+        Degrees of freedom.
+    p : array_like
+        Probability.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value so that the probability a Chi square random variable
+        with `v` degrees of freedom is greater than `x` equals `p`.
+
+    See Also
+    --------
+    chdtrc, chdtr, chdtriv
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It inverts `chdtrc`.
+
+    >>> v, p = 1, 0.3
+    >>> sc.chdtrc(v, sc.chdtri(v, p))
+    0.3
+    >>> x = 1
+    >>> sc.chdtri(v, sc.chdtrc(v, x))
+    1.0
+
+    """)
+
+add_newdoc("chdtriv",
+    """
+    chdtriv(p, x, out=None)
+
+    Inverse to `chdtr` with respect to `v`.
+
+    Returns `v` such that ``chdtr(v, x) == p``.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability that the Chi square random variable is less than
+        or equal to `x`.
+    x : array_like
+        Nonnegative input.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Degrees of freedom.
+
+    See Also
+    --------
+    chdtr, chdtrc, chdtri
+
+    References
+    ----------
+    .. [1] Chi-Square distribution,
+        https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It inverts `chdtr`.
+
+    >>> p, x = 0.5, 1
+    >>> sc.chdtr(sc.chdtriv(p, x), x)
+    0.5000000000202172
+    >>> v = 1
+    >>> sc.chdtriv(sc.chdtr(v, x), v)
+    1.0000000000000013
+
+    """)
+
+add_newdoc("chndtr",
+    r"""
+    chndtr(x, df, nc, out=None)
+
+    Non-central chi square cumulative distribution function
+
+    The cumulative distribution function is given by:
+
+    .. math::
+
+        P(\chi^{\prime 2} \vert \nu, \lambda) =\sum_{j=0}^{\infty}
+        e^{-\lambda /2}
+        \frac{(\lambda /2)^j}{j!} P(\chi^{\prime 2} \vert \nu + 2j),
+
+    where :math:`\nu > 0` is the degrees of freedom (``df``) and
+    :math:`\lambda \geq 0` is the non-centrality parameter (``nc``).
+
+    Parameters
+    ----------
+    x : array_like
+        Upper bound of the integral; must satisfy ``x >= 0``
+    df : array_like
+        Degrees of freedom; must satisfy ``df > 0``
+    nc : array_like
+        Non-centrality parameter; must satisfy ``nc >= 0``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value of the non-central chi square cumulative distribution function.
+
+    See Also
+    --------
+    chndtrix, chndtridf, chndtrinc
+
+    """)
+
+add_newdoc("chndtrix",
+    """
+    chndtrix(p, df, nc, out=None)
+
+    Inverse to `chndtr` vs `x`
+
+    Calculated using a search to find a value for `x` that produces the
+    desired value of `p`.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability; must satisfy ``0 <= p < 1``
+    df : array_like
+        Degrees of freedom; must satisfy ``df > 0``
+    nc : array_like
+        Non-centrality parameter; must satisfy ``nc >= 0``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value so that the probability a non-central Chi square random variable
+        with `df` degrees of freedom and non-centrality, `nc`, is greater than
+        `x` equals `p`.
+
+    See Also
+    --------
+    chndtr, chndtridf, chndtrinc
+
+    """)
+
+add_newdoc("chndtridf",
+    """
+    chndtridf(x, p, nc, out=None)
+
+    Inverse to `chndtr` vs `df`
+
+    Calculated using a search to find a value for `df` that produces the
+    desired value of `p`.
+
+    Parameters
+    ----------
+    x : array_like
+        Upper bound of the integral; must satisfy ``x >= 0``
+    p : array_like
+        Probability; must satisfy ``0 <= p < 1``
+    nc : array_like
+        Non-centrality parameter; must satisfy ``nc >= 0``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    df : scalar or ndarray
+        Degrees of freedom
+
+    See Also
+    --------
+    chndtr, chndtrix, chndtrinc
+
+    """)
+
+add_newdoc("chndtrinc",
+    """
+    chndtrinc(x, df, p, out=None)
+
+    Inverse to `chndtr` vs `nc`
+
+    Calculated using a search to find a value for `df` that produces the
+    desired value of `p`.
+
+    Parameters
+    ----------
+    x : array_like
+        Upper bound of the integral; must satisfy ``x >= 0``
+    df : array_like
+        Degrees of freedom; must satisfy ``df > 0``
+    p : array_like
+        Probability; must satisfy ``0 <= p < 1``
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    nc : scalar or ndarray
+        Non-centrality
+
+    See Also
+    --------
+    chndtr, chndtrix, chndtrinc
+
+    """)
+
+add_newdoc("dawsn",
+    """
+    dawsn(x, out=None)
+
+    Dawson's integral.
+
+    Computes::
+
+        exp(-x**2) * integral(exp(t**2), t=0..x).
+
+    Parameters
+    ----------
+    x : array_like
+        Function parameter.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        Value of the integral.
+
+    See Also
+    --------
+    wofz, erf, erfc, erfcx, erfi
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-15, 15, num=1000)
+    >>> plt.plot(x, special.dawsn(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$dawsn(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc(
+    "elliprc",
+    r"""
+    elliprc(x, y, out=None)
+
+    Degenerate symmetric elliptic integral.
+
+    The function RC is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{C}}(x, y) =
+           \frac{1}{2} \int_0^{+\infty} (t + x)^{-1/2} (t + y)^{-1} dt
+           = R_{\mathrm{F}}(x, y, y)
+
+    Parameters
+    ----------
+    x, y : array_like
+        Real or complex input parameters. `x` can be any number in the
+        complex plane cut along the negative real axis. `y` must be non-zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If `y` is real and negative, the Cauchy
+        principal value is returned. If both of `x` and `y` are real, the
+        return value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    RC is a degenerate case of the symmetric integral RF: ``elliprc(x, y) ==
+    elliprf(x, y, y)``. It is an elementary function rather than an elliptic
+    integral.
+
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order. [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E6
+    .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprc
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprc(scale*x, scale*y)
+    (0.5484493976710874-0.4169557678995833j)
+
+    >>> elliprc(x, y)/np.sqrt(scale)
+    (0.5484493976710874-0.41695576789958333j)
+
+    When the two arguments coincide, the integral is particularly
+    simple:
+
+    >>> x = 1.2 + 3.4j
+    >>> elliprc(x, x)
+    (0.4299173120614631-0.3041729818745595j)
+
+    >>> 1/np.sqrt(x)
+    (0.4299173120614631-0.30417298187455954j)
+
+    Another simple case: the first argument vanishes:
+
+    >>> y = 1.2 + 3.4j
+    >>> elliprc(0, y)
+    (0.6753125346116815-0.47779380263880866j)
+
+    >>> np.pi/2/np.sqrt(y)
+    (0.6753125346116815-0.4777938026388088j)
+
+    When `x` and `y` are both positive, we can express
+    :math:`R_C(x,y)` in terms of more elementary functions.  For the
+    case :math:`0 \le x < y`,
+
+    >>> x = 3.2
+    >>> y = 6.
+    >>> elliprc(x, y)
+    0.44942991498453444
+
+    >>> np.arctan(np.sqrt((y-x)/x))/np.sqrt(y-x)
+    0.44942991498453433
+
+    And for the case :math:`0 \le y < x`,
+
+    >>> x = 6.
+    >>> y = 3.2
+    >>> elliprc(x,y)
+    0.4989837501576147
+
+    >>> np.log((np.sqrt(x)+np.sqrt(x-y))/np.sqrt(y))/np.sqrt(x-y)
+    0.49898375015761476
+
+    """)
+
+add_newdoc(
+    "elliprd",
+    r"""
+    elliprd(x, y, z, out=None)
+
+    Symmetric elliptic integral of the second kind.
+
+    The function RD is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{D}}(x, y, z) =
+           \frac{3}{2} \int_0^{+\infty} [(t + x) (t + y)]^{-1/2} (t + z)^{-3/2}
+           dt
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        Real or complex input parameters. `x` or `y` can be any number in the
+        complex plane cut along the negative real axis, but at most one of them
+        can be zero, while `z` must be non-zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, and `z` are real, the
+        return value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric elliptic integral.
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    RD is a degenerate case of the elliptic integral RJ: ``elliprd(x, y, z) ==
+    elliprj(x, y, z, z)``.
+
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order. [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E5
+    .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprd
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprd(scale*x, scale*y, scale*z)
+    (-0.03703043835680379-0.24500934665683802j)
+
+    >>> elliprd(x, y, z)*np.power(scale, -1.5)
+    (-0.0370304383568038-0.24500934665683805j)
+
+    All three arguments coincide:
+
+    >>> x = 1.2 + 3.4j
+    >>> elliprd(x, x, x)
+    (-0.03986825876151896-0.14051741840449586j)
+
+    >>> np.power(x, -1.5)
+    (-0.03986825876151894-0.14051741840449583j)
+
+    The so-called "second lemniscate constant":
+
+    >>> elliprd(0, 2, 1)/3
+    0.5990701173677961
+
+    >>> from scipy.special import gamma
+    >>> gamma(0.75)**2/np.sqrt(2*np.pi)
+    0.5990701173677959
+
+    """)
+
+add_newdoc(
+    "elliprf",
+    r"""
+    elliprf(x, y, z, out=None)
+
+    Completely-symmetric elliptic integral of the first kind.
+
+    The function RF is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{F}}(x, y, z) =
+           \frac{1}{2} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2} dt
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        Real or complex input parameters. `x`, `y`, or `z` can be any number in
+        the complex plane cut along the negative real axis, but at most one of
+        them can be zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, and `z` are real, the return
+        value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric integral.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order (cf.:
+    https://dlmf.nist.gov/19.36.i) and the AGM algorithm for the complete
+    integral. [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E1
+    .. [2] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprf
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprf(scale*x, scale*y, scale*z)
+    (0.5328051227278146-0.4008623567957094j)
+
+    >>> elliprf(x, y, z)/np.sqrt(scale)
+    (0.5328051227278147-0.4008623567957095j)
+
+    All three arguments coincide:
+
+    >>> x = 1.2 + 3.4j
+    >>> elliprf(x, x, x)
+    (0.42991731206146316-0.30417298187455954j)
+
+    >>> 1/np.sqrt(x)
+    (0.4299173120614631-0.30417298187455954j)
+
+    The so-called "first lemniscate constant":
+
+    >>> elliprf(0, 1, 2)
+    1.3110287771460598
+
+    >>> from scipy.special import gamma
+    >>> gamma(0.25)**2/(4*np.sqrt(2*np.pi))
+    1.3110287771460598
+
+    """)
+
+add_newdoc(
+    "elliprg",
+    r"""
+    elliprg(x, y, z, out=None)
+
+    Completely-symmetric elliptic integral of the second kind.
+
+    The function RG is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{G}}(x, y, z) =
+           \frac{1}{4} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2}
+           \left(\frac{x}{t + x} + \frac{y}{t + y} + \frac{z}{t + z}\right) t
+           dt
+
+    Parameters
+    ----------
+    x, y, z : array_like
+        Real or complex input parameters. `x`, `y`, or `z` can be any number in
+        the complex plane cut along the negative real axis.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, and `z` are real, the return
+        value is real. Otherwise, the return value is complex.
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric integral.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprj : Symmetric elliptic integral of the third kind.
+
+    Notes
+    -----
+    The implementation uses the relation [1]_
+
+    .. math::
+
+        2 R_{\mathrm{G}}(x, y, z) =
+           z R_{\mathrm{F}}(x, y, z) -
+           \frac{1}{3} (x - z) (y - z) R_{\mathrm{D}}(x, y, z) +
+           \sqrt{\frac{x y}{z}}
+
+    and the symmetry of `x`, `y`, `z` when at least one non-zero parameter can
+    be chosen as the pivot. When one of the arguments is close to zero, the AGM
+    method is applied instead. Other special cases are computed following Ref.
+    [2]_
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+    .. [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.16.E1
+           https://dlmf.nist.gov/19.20.ii
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprg
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> scale = 0.3 + 0.4j
+    >>> elliprg(scale*x, scale*y, scale*z)
+    (1.195936862005246+0.8470988320464167j)
+
+    >>> elliprg(x, y, z)*np.sqrt(scale)
+    (1.195936862005246+0.8470988320464165j)
+
+    Simplifications:
+
+    >>> elliprg(0, y, y)
+    1.756203682760182
+
+    >>> 0.25*np.pi*np.sqrt(y)
+    1.7562036827601817
+
+    >>> elliprg(0, 0, z)
+    1.224744871391589
+
+    >>> 0.5*np.sqrt(z)
+    1.224744871391589
+
+    The surface area of a triaxial ellipsoid with semiaxes ``a``, ``b``, and
+    ``c`` is given by
+
+    .. math::
+
+        S = 4 \pi a b c R_{\mathrm{G}}(1 / a^2, 1 / b^2, 1 / c^2).
+
+    >>> def ellipsoid_area(a, b, c):
+    ...     r = 4.0 * np.pi * a * b * c
+    ...     return r * elliprg(1.0 / (a * a), 1.0 / (b * b), 1.0 / (c * c))
+    >>> print(ellipsoid_area(1, 3, 5))
+    108.62688289491807
+    """)
+
+add_newdoc(
+    "elliprj",
+    r"""
+    elliprj(x, y, z, p, out=None)
+
+    Symmetric elliptic integral of the third kind.
+
+    The function RJ is defined as [1]_
+
+    .. math::
+
+        R_{\mathrm{J}}(x, y, z, p) =
+           \frac{3}{2} \int_0^{+\infty} [(t + x) (t + y) (t + z)]^{-1/2}
+           (t + p)^{-1} dt
+
+    .. warning::
+        This function should be considered experimental when the inputs are
+        unbalanced.  Check correctness with another independent implementation.
+
+    Parameters
+    ----------
+    x, y, z, p : array_like
+        Real or complex input parameters. `x`, `y`, or `z` are numbers in
+        the complex plane cut along the negative real axis (subject to further
+        constraints, see Notes), and at most one of them can be zero. `p` must
+        be non-zero.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    R : scalar or ndarray
+        Value of the integral. If all of `x`, `y`, `z`, and `p` are real, the
+        return value is real. Otherwise, the return value is complex.
+
+        If `p` is real and negative, while `x`, `y`, and `z` are real,
+        non-negative, and at most one of them is zero, the Cauchy principal
+        value is returned. [1]_ [2]_
+
+    See Also
+    --------
+    elliprc : Degenerate symmetric integral.
+    elliprd : Symmetric elliptic integral of the second kind.
+    elliprf : Completely-symmetric elliptic integral of the first kind.
+    elliprg : Completely-symmetric elliptic integral of the second kind.
+
+    Notes
+    -----
+    The code implements Carlson's algorithm based on the duplication theorems
+    and series expansion up to the 7th order. [3]_ The algorithm is slightly
+    different from its earlier incarnation as it appears in [1]_, in that the
+    call to `elliprc` (or ``atan``/``atanh``, see [4]_) is no longer needed in
+    the inner loop. Asymptotic approximations are used where arguments differ
+    widely in the order of magnitude. [5]_
+
+    The input values are subject to certain sufficient but not necessary
+    constraints when input arguments are complex. Notably, ``x``, ``y``, and
+    ``z`` must have non-negative real parts, unless two of them are
+    non-negative and complex-conjugates to each other while the other is a real
+    non-negative number. [1]_ If the inputs do not satisfy the sufficient
+    condition described in Ref. [1]_ they are rejected outright with the output
+    set to NaN.
+
+    In the case where one of ``x``, ``y``, and ``z`` is equal to ``p``, the
+    function ``elliprd`` should be preferred because of its less restrictive
+    domain.
+
+    .. versionadded:: 1.8.0
+
+    References
+    ----------
+    .. [1] B. C. Carlson, "Numerical computation of real or complex elliptic
+           integrals," Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.
+           https://arxiv.org/abs/math/9409227
+           https://doi.org/10.1007/BF02198293
+    .. [2] B. C. Carlson, ed., Chapter 19 in "Digital Library of Mathematical
+           Functions," NIST, US Dept. of Commerce.
+           https://dlmf.nist.gov/19.20.iii
+    .. [3] B. C. Carlson, J. FitzSimmons, "Reduction Theorems for Elliptic
+           Integrands with the Square Root of Two Quadratic Factors," J.
+           Comput. Appl. Math., vol. 118, nos. 1-2, pp. 71-85, 2000.
+           https://doi.org/10.1016/S0377-0427(00)00282-X
+    .. [4] F. Johansson, "Numerical Evaluation of Elliptic Functions, Elliptic
+           Integrals and Modular Forms," in J. Blumlein, C. Schneider, P.
+           Paule, eds., "Elliptic Integrals, Elliptic Functions and Modular
+           Forms in Quantum Field Theory," pp. 269-293, 2019 (Cham,
+           Switzerland: Springer Nature Switzerland)
+           https://arxiv.org/abs/1806.06725
+           https://doi.org/10.1007/978-3-030-04480-0
+    .. [5] B. C. Carlson, J. L. Gustafson, "Asymptotic Approximations for
+           Symmetric Elliptic Integrals," SIAM J. Math. Anls., vol. 25, no. 2,
+           pp. 288-303, 1994.
+           https://arxiv.org/abs/math/9310223
+           https://doi.org/10.1137/S0036141092228477
+
+    Examples
+    --------
+    Basic homogeneity property:
+
+    >>> import numpy as np
+    >>> from scipy.special import elliprj
+
+    >>> x = 1.2 + 3.4j
+    >>> y = 5.
+    >>> z = 6.
+    >>> p = 7.
+    >>> scale = 0.3 - 0.4j
+    >>> elliprj(scale*x, scale*y, scale*z, scale*p)
+    (0.10834905565679157+0.19694950747103812j)
+
+    >>> elliprj(x, y, z, p)*np.power(scale, -1.5)
+    (0.10834905565679556+0.19694950747103854j)
+
+    Reduction to simpler elliptic integral:
+
+    >>> elliprj(x, y, z, z)
+    (0.08288462362195129-0.028376809745123258j)
+
+    >>> from scipy.special import elliprd
+    >>> elliprd(x, y, z)
+    (0.08288462362195136-0.028376809745123296j)
+
+    All arguments coincide:
+
+    >>> elliprj(x, x, x, x)
+    (-0.03986825876151896-0.14051741840449586j)
+
+    >>> np.power(x, -1.5)
+    (-0.03986825876151894-0.14051741840449583j)
+
+    """)
+
+add_newdoc("entr",
+    r"""
+    entr(x, out=None)
+
+    Elementwise function for computing entropy.
+
+    .. math:: \text{entr}(x) = \begin{cases} - x \log(x) & x > 0  \\ 0 & x = 0
+              \\ -\infty & \text{otherwise} \end{cases}
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    res : scalar or ndarray
+        The value of the elementwise entropy function at the given points `x`.
+
+    See Also
+    --------
+    kl_div, rel_entr, scipy.stats.entropy
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    This function is concave.
+
+    The origin of this function is in convex programming; see [1]_.
+    Given a probability distribution :math:`p_1, \ldots, p_n`,
+    the definition of entropy in the context of *information theory* is
+
+    .. math::
+
+        \sum_{i = 1}^n \mathrm{entr}(p_i).
+
+    To compute the latter quantity, use `scipy.stats.entropy`.
+
+    References
+    ----------
+    .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.
+           Cambridge University Press, 2004.
+           :doi:`https://doi.org/10.1017/CBO9780511804441`
+
+    """)
+
+add_newdoc("erf",
+    """
+    erf(z, out=None)
+
+    Returns the error function of complex argument.
+
+    It is defined as ``2/sqrt(pi)*integral(exp(-t**2), t=0..z)``.
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    res : scalar or ndarray
+        The values of the error function at the given points `x`.
+
+    See Also
+    --------
+    erfc, erfinv, erfcinv, wofz, erfcx, erfi
+
+    Notes
+    -----
+    The cumulative of the unit normal distribution is given by
+    ``Phi(z) = 1/2[1 + erf(z/sqrt(2))]``.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Error_function
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover,
+        1972. http://www.math.sfu.ca/~cbm/aands/page_297.htm
+    .. [3] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erf(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erf(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("erfc",
+    """
+    erfc(x, out=None)
+
+    Complementary error function, ``1 - erf(x)``.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the complementary error function
+
+    See Also
+    --------
+    erf, erfi, erfcx, dawsn, wofz
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erfc(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erfc(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("erfi",
+    """
+    erfi(z, out=None)
+
+    Imaginary error function, ``-i erf(i z)``.
+
+    Parameters
+    ----------
+    z : array_like
+        Real or complex valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the imaginary error function
+
+    See Also
+    --------
+    erf, erfc, erfcx, dawsn, wofz
+
+    Notes
+    -----
+
+    .. versionadded:: 0.12.0
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erfi(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erfi(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("erfcx",
+    """
+    erfcx(x, out=None)
+
+    Scaled complementary error function, ``exp(x**2) * erfc(x)``.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the scaled complementary error function
+
+
+    See Also
+    --------
+    erf, erfc, erfi, dawsn, wofz
+
+    Notes
+    -----
+
+    .. versionadded:: 0.12.0
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-3, 3)
+    >>> plt.plot(x, special.erfcx(x))
+    >>> plt.xlabel('$x$')
+    >>> plt.ylabel('$erfcx(x)$')
+    >>> plt.show()
+
+    """)
+
+add_newdoc(
+    "erfinv",
+    """
+    erfinv(y, out=None)
+
+    Inverse of the error function.
+
+    Computes the inverse of the error function.
+
+    In the complex domain, there is no unique complex number w satisfying
+    erf(w)=z. This indicates a true inverse function would be multivalued.
+    When the domain restricts to the real, -1 < x < 1, there is a unique real
+    number satisfying erf(erfinv(x)) = x.
+
+    Parameters
+    ----------
+    y : ndarray
+        Argument at which to evaluate. Domain: [-1, 1]
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    erfinv : scalar or ndarray
+        The inverse of erf of y, element-wise
+
+    See Also
+    --------
+    erf : Error function of a complex argument
+    erfc : Complementary error function, ``1 - erf(x)``
+    erfcinv : Inverse of the complementary error function
+
+    Notes
+    -----
+    This function wraps the ``erf_inv`` routine from the
+    Boost Math C++ library [1]_.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import erfinv, erf
+
+    >>> erfinv(0.5)
+    0.4769362762044699
+
+    >>> y = np.linspace(-1.0, 1.0, num=9)
+    >>> x = erfinv(y)
+    >>> x
+    array([       -inf, -0.81341985, -0.47693628, -0.22531206,  0.        ,
+            0.22531206,  0.47693628,  0.81341985,         inf])
+
+    Verify that ``erf(erfinv(y))`` is ``y``.
+
+    >>> erf(x)
+    array([-1.  , -0.75, -0.5 , -0.25,  0.  ,  0.25,  0.5 ,  0.75,  1.  ])
+
+    Plot the function:
+
+    >>> y = np.linspace(-1, 1, 200)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(y, erfinv(y))
+    >>> ax.grid(True)
+    >>> ax.set_xlabel('y')
+    >>> ax.set_title('erfinv(y)')
+    >>> plt.show()
+
+    """)
+
+add_newdoc(
+    "erfcinv",
+    """
+    erfcinv(y, out=None)
+
+    Inverse of the complementary error function.
+
+    Computes the inverse of the complementary error function.
+
+    In the complex domain, there is no unique complex number w satisfying
+    erfc(w)=z. This indicates a true inverse function would be multivalued.
+    When the domain restricts to the real, 0 < x < 2, there is a unique real
+    number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)).
+
+    It is related to inverse of the error function by erfcinv(1-x) = erfinv(x)
+
+    Parameters
+    ----------
+    y : ndarray
+        Argument at which to evaluate. Domain: [0, 2]
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    erfcinv : scalar or ndarray
+        The inverse of erfc of y, element-wise
+
+    See Also
+    --------
+    erf : Error function of a complex argument
+    erfc : Complementary error function, ``1 - erf(x)``
+    erfinv : Inverse of the error function
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import erfcinv
+
+    >>> erfcinv(0.5)
+    0.4769362762044699
+
+    >>> y = np.linspace(0.0, 2.0, num=11)
+    >>> erfcinv(y)
+    array([        inf,  0.9061938 ,  0.59511608,  0.37080716,  0.17914345,
+           -0.        , -0.17914345, -0.37080716, -0.59511608, -0.9061938 ,
+                  -inf])
+
+    Plot the function:
+
+    >>> y = np.linspace(0, 2, 200)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(y, erfcinv(y))
+    >>> ax.grid(True)
+    >>> ax.set_xlabel('y')
+    >>> ax.set_title('erfcinv(y)')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("eval_jacobi",
+    r"""
+    eval_jacobi(n, alpha, beta, x, out=None)
+
+    Evaluate Jacobi polynomial at a point.
+
+    The Jacobi polynomials can be defined via the Gauss hypergeometric
+    function :math:`{}_2F_1` as
+
+    .. math::
+
+        P_n^{(\alpha, \beta)}(x) = \frac{(\alpha + 1)_n}{\Gamma(n + 1)}
+          {}_2F_1(-n, 1 + \alpha + \beta + n; \alpha + 1; (1 - z)/2)
+
+    where :math:`(\cdot)_n` is the Pochhammer symbol; see `poch`. When
+    :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.42 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    alpha : array_like
+        Parameter
+    beta : array_like
+        Parameter
+    x : array_like
+        Points at which to evaluate the polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    P : scalar or ndarray
+        Values of the Jacobi polynomial
+
+    See Also
+    --------
+    roots_jacobi : roots and quadrature weights of Jacobi polynomials
+    jacobi : Jacobi polynomial object
+    hyp2f1 : Gauss hypergeometric function
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_sh_jacobi",
+    r"""
+    eval_sh_jacobi(n, p, q, x, out=None)
+
+    Evaluate shifted Jacobi polynomial at a point.
+
+    Defined by
+
+    .. math::
+
+        G_n^{(p, q)}(x)
+          = \binom{2n + p - 1}{n}^{-1} P_n^{(p - q, q - 1)}(2x - 1),
+
+    where :math:`P_n^{(\cdot, \cdot)}` is the n-th Jacobi
+    polynomial. See 22.5.2 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `binom` and `eval_jacobi`.
+    p : float
+        Parameter
+    q : float
+        Parameter
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    G : scalar or ndarray
+        Values of the shifted Jacobi polynomial.
+
+    See Also
+    --------
+    roots_sh_jacobi : roots and quadrature weights of shifted Jacobi
+                      polynomials
+    sh_jacobi : shifted Jacobi polynomial object
+    eval_jacobi : evaluate Jacobi polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_gegenbauer",
+    r"""
+    eval_gegenbauer(n, alpha, x, out=None)
+
+    Evaluate Gegenbauer polynomial at a point.
+
+    The Gegenbauer polynomials can be defined via the Gauss
+    hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        C_n^{(\alpha)} = \frac{(2\alpha)_n}{\Gamma(n + 1)}
+          {}_2F_1(-n, 2\alpha + n; \alpha + 1/2; (1 - z)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.46 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    alpha : array_like
+        Parameter
+    x : array_like
+        Points at which to evaluate the Gegenbauer polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    C : scalar or ndarray
+        Values of the Gegenbauer polynomial
+
+    See Also
+    --------
+    roots_gegenbauer : roots and quadrature weights of Gegenbauer
+                       polynomials
+    gegenbauer : Gegenbauer polynomial object
+    hyp2f1 : Gauss hypergeometric function
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_chebyt",
+    r"""
+    eval_chebyt(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the first kind at a point.
+
+    The Chebyshev polynomials of the first kind can be defined via the
+    Gauss hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        T_n(x) = {}_2F_1(n, -n; 1/2; (1 - x)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.47 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    T : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebyt : roots and quadrature weights of Chebyshev
+                   polynomials of the first kind
+    chebyu : Chebychev polynomial object
+    eval_chebyu : evaluate Chebyshev polynomials of the second kind
+    hyp2f1 : Gauss hypergeometric function
+    numpy.polynomial.chebyshev.Chebyshev : Chebyshev series
+
+    Notes
+    -----
+    This routine is numerically stable for `x` in ``[-1, 1]`` at least
+    up to order ``10000``.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_chebyu",
+    r"""
+    eval_chebyu(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the second kind at a point.
+
+    The Chebyshev polynomials of the second kind can be defined via
+    the Gauss hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        U_n(x) = (n + 1) {}_2F_1(-n, n + 2; 3/2; (1 - x)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.48 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    U : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebyu : roots and quadrature weights of Chebyshev
+                   polynomials of the second kind
+    chebyu : Chebyshev polynomial object
+    eval_chebyt : evaluate Chebyshev polynomials of the first kind
+    hyp2f1 : Gauss hypergeometric function
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_chebys",
+    r"""
+    eval_chebys(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        S_n(x) = U_n(x/2)
+
+    where :math:`U_n` is a Chebyshev polynomial of the second
+    kind. See 22.5.13 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyu`.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    S : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebys : roots and quadrature weights of Chebyshev
+                   polynomials of the second kind on [-2, 2]
+    chebys : Chebyshev polynomial object
+    eval_chebyu : evaluate Chebyshev polynomials of the second kind
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    They are a scaled version of the Chebyshev polynomials of the
+    second kind.
+
+    >>> x = np.linspace(-2, 2, 6)
+    >>> sc.eval_chebys(3, x)
+    array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])
+    >>> sc.eval_chebyu(3, x / 2)
+    array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])
+
+    """)
+
+add_newdoc("eval_chebyc",
+    r"""
+    eval_chebyc(n, x, out=None)
+
+    Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        C_n(x) = 2 T_n(x/2)
+
+    where :math:`T_n` is a Chebyshev polynomial of the first kind. See
+    22.5.11 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyt`.
+    x : array_like
+        Points at which to evaluate the Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    C : scalar or ndarray
+        Values of the Chebyshev polynomial
+
+    See Also
+    --------
+    roots_chebyc : roots and quadrature weights of Chebyshev
+                   polynomials of the first kind on [-2, 2]
+    chebyc : Chebyshev polynomial object
+    numpy.polynomial.chebyshev.Chebyshev : Chebyshev series
+    eval_chebyt : evaluate Chebycshev polynomials of the first kind
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    They are a scaled version of the Chebyshev polynomials of the
+    first kind.
+
+    >>> x = np.linspace(-2, 2, 6)
+    >>> sc.eval_chebyc(3, x)
+    array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])
+    >>> 2 * sc.eval_chebyt(3, x / 2)
+    array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])
+
+    """)
+
+add_newdoc("eval_sh_chebyt",
+    r"""
+    eval_sh_chebyt(n, x, out=None)
+
+    Evaluate shifted Chebyshev polynomial of the first kind at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        T_n^*(x) = T_n(2x - 1)
+
+    where :math:`T_n` is a Chebyshev polynomial of the first kind. See
+    22.5.14 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyt`.
+    x : array_like
+        Points at which to evaluate the shifted Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    T : scalar or ndarray
+        Values of the shifted Chebyshev polynomial
+
+    See Also
+    --------
+    roots_sh_chebyt : roots and quadrature weights of shifted
+                      Chebyshev polynomials of the first kind
+    sh_chebyt : shifted Chebyshev polynomial object
+    eval_chebyt : evaluate Chebyshev polynomials of the first kind
+    numpy.polynomial.chebyshev.Chebyshev : Chebyshev series
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_sh_chebyu",
+    r"""
+    eval_sh_chebyu(n, x, out=None)
+
+    Evaluate shifted Chebyshev polynomial of the second kind at a
+    point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        U_n^*(x) = U_n(2x - 1)
+
+    where :math:`U_n` is a Chebyshev polynomial of the first kind. See
+    22.5.15 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to `eval_chebyu`.
+    x : array_like
+        Points at which to evaluate the shifted Chebyshev polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    U : scalar or ndarray
+        Values of the shifted Chebyshev polynomial
+
+    See Also
+    --------
+    roots_sh_chebyu : roots and quadrature weights of shifted
+                      Chebychev polynomials of the second kind
+    sh_chebyu : shifted Chebyshev polynomial object
+    eval_chebyu : evaluate Chebyshev polynomials of the second kind
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_legendre",
+    r"""
+    eval_legendre(n, x, out=None)
+
+    Evaluate Legendre polynomial at a point.
+
+    The Legendre polynomials can be defined via the Gauss
+    hypergeometric function :math:`{}_2F_1` as
+
+    .. math::
+
+        P_n(x) = {}_2F_1(-n, n + 1; 1; (1 - x)/2).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.49 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the Gauss hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Legendre polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    P : scalar or ndarray
+        Values of the Legendre polynomial
+
+    See Also
+    --------
+    roots_legendre : roots and quadrature weights of Legendre
+                     polynomials
+    legendre : Legendre polynomial object
+    hyp2f1 : Gauss hypergeometric function
+    numpy.polynomial.legendre.Legendre : Legendre series
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import eval_legendre
+
+    Evaluate the zero-order Legendre polynomial at x = 0
+
+    >>> eval_legendre(0, 0)
+    1.0
+
+    Evaluate the first-order Legendre polynomial between -1 and 1
+
+    >>> X = np.linspace(-1, 1, 5)  # Domain of Legendre polynomials
+    >>> eval_legendre(1, X)
+    array([-1. , -0.5,  0. ,  0.5,  1. ])
+
+    Evaluate Legendre polynomials of order 0 through 4 at x = 0
+
+    >>> N = range(0, 5)
+    >>> eval_legendre(N, 0)
+    array([ 1.   ,  0.   , -0.5  ,  0.   ,  0.375])
+
+    Plot Legendre polynomials of order 0 through 4
+
+    >>> X = np.linspace(-1, 1)
+
+    >>> import matplotlib.pyplot as plt
+    >>> for n in range(0, 5):
+    ...     y = eval_legendre(n, X)
+    ...     plt.plot(X, y, label=r'$P_{}(x)$'.format(n))
+
+    >>> plt.title("Legendre Polynomials")
+    >>> plt.xlabel("x")
+    >>> plt.ylabel(r'$P_n(x)$')
+    >>> plt.legend(loc='lower right')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("eval_sh_legendre",
+    r"""
+    eval_sh_legendre(n, x, out=None)
+
+    Evaluate shifted Legendre polynomial at a point.
+
+    These polynomials are defined as
+
+    .. math::
+
+        P_n^*(x) = P_n(2x - 1)
+
+    where :math:`P_n` is a Legendre polynomial. See 2.2.11 in [AS]_
+    for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the value is
+        determined via the relation to `eval_legendre`.
+    x : array_like
+        Points at which to evaluate the shifted Legendre polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    P : scalar or ndarray
+        Values of the shifted Legendre polynomial
+
+    See Also
+    --------
+    roots_sh_legendre : roots and quadrature weights of shifted
+                        Legendre polynomials
+    sh_legendre : shifted Legendre polynomial object
+    eval_legendre : evaluate Legendre polynomials
+    numpy.polynomial.legendre.Legendre : Legendre series
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_genlaguerre",
+    r"""
+    eval_genlaguerre(n, alpha, x, out=None)
+
+    Evaluate generalized Laguerre polynomial at a point.
+
+    The generalized Laguerre polynomials can be defined via the
+    confluent hypergeometric function :math:`{}_1F_1` as
+
+    .. math::
+
+        L_n^{(\alpha)}(x) = \binom{n + \alpha}{n}
+          {}_1F_1(-n, \alpha + 1, x).
+
+    When :math:`n` is an integer the result is a polynomial of degree
+    :math:`n`. See 22.5.54 in [AS]_ for details. The Laguerre
+    polynomials are the special case where :math:`\alpha = 0`.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer, the result is
+        determined via the relation to the confluent hypergeometric
+        function.
+    alpha : array_like
+        Parameter; must have ``alpha > -1``
+    x : array_like
+        Points at which to evaluate the generalized Laguerre
+        polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    L : scalar or ndarray
+        Values of the generalized Laguerre polynomial
+
+    See Also
+    --------
+    roots_genlaguerre : roots and quadrature weights of generalized
+                        Laguerre polynomials
+    genlaguerre : generalized Laguerre polynomial object
+    hyp1f1 : confluent hypergeometric function
+    eval_laguerre : evaluate Laguerre polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_laguerre",
+    r"""
+    eval_laguerre(n, x, out=None)
+
+    Evaluate Laguerre polynomial at a point.
+
+    The Laguerre polynomials can be defined via the confluent
+    hypergeometric function :math:`{}_1F_1` as
+
+    .. math::
+
+        L_n(x) = {}_1F_1(-n, 1, x).
+
+    See 22.5.16 and 22.5.54 in [AS]_ for details. When :math:`n` is an
+    integer the result is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial. If not an integer the result is
+        determined via the relation to the confluent hypergeometric
+        function.
+    x : array_like
+        Points at which to evaluate the Laguerre polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    L : scalar or ndarray
+        Values of the Laguerre polynomial
+
+    See Also
+    --------
+    roots_laguerre : roots and quadrature weights of Laguerre
+                     polynomials
+    laguerre : Laguerre polynomial object
+    numpy.polynomial.laguerre.Laguerre : Laguerre series
+    eval_genlaguerre : evaluate generalized Laguerre polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+     """)
+
+add_newdoc("eval_hermite",
+    r"""
+    eval_hermite(n, x, out=None)
+
+    Evaluate physicist's Hermite polynomial at a point.
+
+    Defined by
+
+    .. math::
+
+        H_n(x) = (-1)^n e^{x^2} \frac{d^n}{dx^n} e^{-x^2};
+
+    :math:`H_n` is a polynomial of degree :math:`n`. See 22.11.7 in
+    [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial
+    x : array_like
+        Points at which to evaluate the Hermite polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    H : scalar or ndarray
+        Values of the Hermite polynomial
+
+    See Also
+    --------
+    roots_hermite : roots and quadrature weights of physicist's
+                    Hermite polynomials
+    hermite : physicist's Hermite polynomial object
+    numpy.polynomial.hermite.Hermite : Physicist's Hermite series
+    eval_hermitenorm : evaluate Probabilist's Hermite polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+add_newdoc("eval_hermitenorm",
+    r"""
+    eval_hermitenorm(n, x, out=None)
+
+    Evaluate probabilist's (normalized) Hermite polynomial at a
+    point.
+
+    Defined by
+
+    .. math::
+
+        He_n(x) = (-1)^n e^{x^2/2} \frac{d^n}{dx^n} e^{-x^2/2};
+
+    :math:`He_n` is a polynomial of degree :math:`n`. See 22.11.8 in
+    [AS]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        Degree of the polynomial
+    x : array_like
+        Points at which to evaluate the Hermite polynomial
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    He : scalar or ndarray
+        Values of the Hermite polynomial
+
+    See Also
+    --------
+    roots_hermitenorm : roots and quadrature weights of probabilist's
+                        Hermite polynomials
+    hermitenorm : probabilist's Hermite polynomial object
+    numpy.polynomial.hermite_e.HermiteE : Probabilist's Hermite series
+    eval_hermite : evaluate physicist's Hermite polynomials
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """)
+
+
+add_newdoc("exp10",
+    """
+    exp10(x, out=None)
+
+    Compute ``10**x`` element-wise.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        ``10**x``, computed element-wise.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import exp10
+
+    >>> exp10(3)
+    1000.0
+    >>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])
+    >>> exp10(x)
+    array([[  0.1       ,   0.31622777,   1.        ],
+           [  3.16227766,  10.        ,  31.6227766 ]])
+
+    """)
+
+add_newdoc("exp2",
+    """
+    exp2(x, out=None)
+
+    Compute ``2**x`` element-wise.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        ``2**x``, computed element-wise.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import exp2
+
+    >>> exp2(3)
+    8.0
+    >>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])
+    >>> exp2(x)
+    array([[ 0.5       ,  0.70710678,  1.        ],
+           [ 1.41421356,  2.        ,  2.82842712]])
+    """)
+
+add_newdoc("expm1",
+    """
+    expm1(x, out=None)
+
+    Compute ``exp(x) - 1``.
+
+    When `x` is near zero, ``exp(x)`` is near 1, so the numerical calculation
+    of ``exp(x) - 1`` can suffer from catastrophic loss of precision.
+    ``expm1(x)`` is implemented to avoid the loss of precision that occurs when
+    `x` is near zero.
+
+    Parameters
+    ----------
+    x : array_like
+        `x` must contain real numbers.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        ``exp(x) - 1`` computed element-wise.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import expm1
+
+    >>> expm1(1.0)
+    1.7182818284590451
+    >>> expm1([-0.2, -0.1, 0, 0.1, 0.2])
+    array([-0.18126925, -0.09516258,  0.        ,  0.10517092,  0.22140276])
+
+    The exact value of ``exp(7.5e-13) - 1`` is::
+
+        7.5000000000028125000000007031250000001318...*10**-13.
+
+    Here is what ``expm1(7.5e-13)`` gives:
+
+    >>> expm1(7.5e-13)
+    7.5000000000028135e-13
+
+    Compare that to ``exp(7.5e-13) - 1``, where the subtraction results in
+    a "catastrophic" loss of precision:
+
+    >>> np.exp(7.5e-13) - 1
+    7.5006667543675576e-13
+
+    """)
+
+add_newdoc("expn",
+    r"""
+    expn(n, x, out=None)
+
+    Generalized exponential integral En.
+
+    For integer :math:`n \geq 0` and real :math:`x \geq 0` the
+    generalized exponential integral is defined as [dlmf]_
+
+    .. math::
+
+        E_n(x) = x^{n - 1} \int_x^\infty \frac{e^{-t}}{t^n} dt.
+
+    Parameters
+    ----------
+    n : array_like
+        Non-negative integers
+    x : array_like
+        Real argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the generalized exponential integral
+
+    See Also
+    --------
+    exp1 : special case of :math:`E_n` for :math:`n = 1`
+    expi : related to :math:`E_n` when :math:`n = 1`
+
+    References
+    ----------
+    .. [dlmf] Digital Library of Mathematical Functions, 8.19.2
+              https://dlmf.nist.gov/8.19#E2
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    Its domain is nonnegative n and x.
+
+    >>> sc.expn(-1, 1.0), sc.expn(1, -1.0)
+    (nan, nan)
+
+    It has a pole at ``x = 0`` for ``n = 1, 2``; for larger ``n`` it
+    is equal to ``1 / (n - 1)``.
+
+    >>> sc.expn([0, 1, 2, 3, 4], 0)
+    array([       inf,        inf, 1.        , 0.5       , 0.33333333])
+
+    For n equal to 0 it reduces to ``exp(-x) / x``.
+
+    >>> x = np.array([1, 2, 3, 4])
+    >>> sc.expn(0, x)
+    array([0.36787944, 0.06766764, 0.01659569, 0.00457891])
+    >>> np.exp(-x) / x
+    array([0.36787944, 0.06766764, 0.01659569, 0.00457891])
+
+    For n equal to 1 it reduces to `exp1`.
+
+    >>> sc.expn(1, x)
+    array([0.21938393, 0.04890051, 0.01304838, 0.00377935])
+    >>> sc.exp1(x)
+    array([0.21938393, 0.04890051, 0.01304838, 0.00377935])
+
+    """)
+
+add_newdoc("fdtr",
+    r"""
+    fdtr(dfn, dfd, x, out=None)
+
+    F cumulative distribution function.
+
+    Returns the value of the cumulative distribution function of the
+    F-distribution, also known as Snedecor's F-distribution or the
+    Fisher-Snedecor distribution.
+
+    The F-distribution with parameters :math:`d_n` and :math:`d_d` is the
+    distribution of the random variable,
+
+    .. math::
+        X = \frac{U_n/d_n}{U_d/d_d},
+
+    where :math:`U_n` and :math:`U_d` are random variables distributed
+    :math:`\chi^2`, with :math:`d_n` and :math:`d_d` degrees of freedom,
+    respectively.
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    dfd : array_like
+        Second parameter (positive float).
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        The CDF of the F-distribution with parameters `dfn` and `dfd` at `x`.
+
+    See Also
+    --------
+    fdtrc : F distribution survival function
+    fdtri : F distribution inverse cumulative distribution
+    scipy.stats.f : F distribution
+
+    Notes
+    -----
+    The regularized incomplete beta function is used, according to the
+    formula,
+
+    .. math::
+        F(d_n, d_d; x) = I_{xd_n/(d_d + xd_n)}(d_n/2, d_d/2).
+
+    Wrapper for the Cephes [1]_ routine `fdtr`. The F distribution is also
+    available as `scipy.stats.f`. Calling `fdtr` directly can improve
+    performance compared to the ``cdf`` method of `scipy.stats.f` (see last
+    example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.
+
+    >>> import numpy as np
+    >>> from scipy.special import fdtr
+    >>> fdtr(1, 2, 1)
+    0.5773502691896258
+
+    Calculate the function at several points by providing a NumPy array for
+    `x`.
+
+    >>> x = np.array([0.5, 2., 3.])
+    >>> fdtr(1, 2, x)
+    array([0.4472136 , 0.70710678, 0.77459667])
+
+    Plot the function for several parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> dfn_parameters = [1, 5, 10, 50]
+    >>> dfd_parameters = [1, 1, 2, 3]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(dfn_parameters, dfd_parameters,
+    ...                            linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     dfn, dfd, style = parameter_set
+    ...     fdtr_vals = fdtr(dfn, dfd, x)
+    ...     ax.plot(x, fdtr_vals, label=rf"$d_n={dfn},\, d_d={dfd}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("F distribution cumulative distribution function")
+    >>> plt.show()
+
+    The F distribution is also available as `scipy.stats.f`. Using `fdtr`
+    directly can be much faster than calling the ``cdf`` method of
+    `scipy.stats.f`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.f(dfn, dfd).cdf(x)=fdtr(dfn, dfd, x)``.
+
+    >>> from scipy.stats import f
+    >>> dfn, dfd = 1, 2
+    >>> x = 1
+    >>> fdtr_res = fdtr(dfn, dfd, x)  # this will often be faster than below
+    >>> f_dist_res = f(dfn, dfd).cdf(x)
+    >>> fdtr_res == f_dist_res  # test that results are equal
+    True
+    """)
+
+add_newdoc("fdtrc",
+    r"""
+    fdtrc(dfn, dfd, x, out=None)
+
+    F survival function.
+
+    Returns the complemented F-distribution function (the integral of the
+    density from `x` to infinity).
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    dfd : array_like
+        Second parameter (positive float).
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    y : scalar or ndarray
+        The complemented F-distribution function with parameters `dfn` and
+        `dfd` at `x`.
+
+    See Also
+    --------
+    fdtr : F distribution cumulative distribution function
+    fdtri : F distribution inverse cumulative distribution function
+    scipy.stats.f : F distribution
+
+    Notes
+    -----
+    The regularized incomplete beta function is used, according to the
+    formula,
+
+    .. math::
+        F(d_n, d_d; x) = I_{d_d/(d_d + xd_n)}(d_d/2, d_n/2).
+
+    Wrapper for the Cephes [1]_ routine `fdtrc`. The F distribution is also
+    available as `scipy.stats.f`. Calling `fdtrc` directly can improve
+    performance compared to the ``sf`` method of `scipy.stats.f` (see last
+    example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.
+
+    >>> import numpy as np
+    >>> from scipy.special import fdtrc
+    >>> fdtrc(1, 2, 1)
+    0.42264973081037427
+
+    Calculate the function at several points by providing a NumPy array for
+    `x`.
+
+    >>> x = np.array([0.5, 2., 3.])
+    >>> fdtrc(1, 2, x)
+    array([0.5527864 , 0.29289322, 0.22540333])
+
+    Plot the function for several parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> dfn_parameters = [1, 5, 10, 50]
+    >>> dfd_parameters = [1, 1, 2, 3]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(dfn_parameters, dfd_parameters,
+    ...                            linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     dfn, dfd, style = parameter_set
+    ...     fdtrc_vals = fdtrc(dfn, dfd, x)
+    ...     ax.plot(x, fdtrc_vals, label=rf"$d_n={dfn},\, d_d={dfd}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("F distribution survival function")
+    >>> plt.show()
+
+    The F distribution is also available as `scipy.stats.f`. Using `fdtrc`
+    directly can be much faster than calling the ``sf`` method of
+    `scipy.stats.f`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.f(dfn, dfd).sf(x)=fdtrc(dfn, dfd, x)``.
+
+    >>> from scipy.stats import f
+    >>> dfn, dfd = 1, 2
+    >>> x = 1
+    >>> fdtrc_res = fdtrc(dfn, dfd, x)  # this will often be faster than below
+    >>> f_dist_res = f(dfn, dfd).sf(x)
+    >>> f_dist_res == fdtrc_res  # test that results are equal
+    True
+    """)
+
+add_newdoc("fdtri",
+    r"""
+    fdtri(dfn, dfd, p, out=None)
+
+    The `p`-th quantile of the F-distribution.
+
+    This function is the inverse of the F-distribution CDF, `fdtr`, returning
+    the `x` such that `fdtr(dfn, dfd, x) = p`.
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    dfd : array_like
+        Second parameter (positive float).
+    p : array_like
+        Cumulative probability, in [0, 1].
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    x : scalar or ndarray
+        The quantile corresponding to `p`.
+
+    See Also
+    --------
+    fdtr : F distribution cumulative distribution function
+    fdtrc : F distribution survival function
+    scipy.stats.f : F distribution
+
+    Notes
+    -----
+    The computation is carried out using the relation to the inverse
+    regularized beta function, :math:`I^{-1}_x(a, b)`.  Let
+    :math:`z = I^{-1}_p(d_d/2, d_n/2).`  Then,
+
+    .. math::
+        x = \frac{d_d (1 - z)}{d_n z}.
+
+    If `p` is such that :math:`x < 0.5`, the following relation is used
+    instead for improved stability: let
+    :math:`z' = I^{-1}_{1 - p}(d_n/2, d_d/2).` Then,
+
+    .. math::
+        x = \frac{d_d z'}{d_n (1 - z')}.
+
+    Wrapper for the Cephes [1]_ routine `fdtri`.
+
+    The F distribution is also available as `scipy.stats.f`. Calling
+    `fdtri` directly can improve performance compared to the ``ppf``
+    method of `scipy.stats.f` (see last example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    `fdtri` represents the inverse of the F distribution CDF which is
+    available as `fdtr`. Here, we calculate the CDF for ``df1=1``, ``df2=2``
+    at ``x=3``. `fdtri` then returns ``3`` given the same values for `df1`,
+    `df2` and the computed CDF value.
+
+    >>> import numpy as np
+    >>> from scipy.special import fdtri, fdtr
+    >>> df1, df2 = 1, 2
+    >>> x = 3
+    >>> cdf_value =  fdtr(df1, df2, x)
+    >>> fdtri(df1, df2, cdf_value)
+    3.000000000000006
+
+    Calculate the function at several points by providing a NumPy array for
+    `x`.
+
+    >>> x = np.array([0.1, 0.4, 0.7])
+    >>> fdtri(1, 2, x)
+    array([0.02020202, 0.38095238, 1.92156863])
+
+    Plot the function for several parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> dfn_parameters = [50, 10, 1, 50]
+    >>> dfd_parameters = [0.5, 1, 1, 5]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(dfn_parameters, dfd_parameters,
+    ...                            linestyles))
+    >>> x = np.linspace(0, 1, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     dfn, dfd, style = parameter_set
+    ...     fdtri_vals = fdtri(dfn, dfd, x)
+    ...     ax.plot(x, fdtri_vals, label=rf"$d_n={dfn},\, d_d={dfd}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> title = "F distribution inverse cumulative distribution function"
+    >>> ax.set_title(title)
+    >>> ax.set_ylim(0, 30)
+    >>> plt.show()
+
+    The F distribution is also available as `scipy.stats.f`. Using `fdtri`
+    directly can be much faster than calling the ``ppf`` method of
+    `scipy.stats.f`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.f(dfn, dfd).ppf(x)=fdtri(dfn, dfd, x)``.
+
+    >>> from scipy.stats import f
+    >>> dfn, dfd = 1, 2
+    >>> x = 0.7
+    >>> fdtri_res = fdtri(dfn, dfd, x)  # this will often be faster than below
+    >>> f_dist_res = f(dfn, dfd).ppf(x)
+    >>> f_dist_res == fdtri_res  # test that results are equal
+    True
+    """)
+
+add_newdoc("fdtridfd",
+    """
+    fdtridfd(dfn, p, x, out=None)
+
+    Inverse to `fdtr` vs dfd
+
+    Finds the F density argument dfd such that ``fdtr(dfn, dfd, x) == p``.
+
+    Parameters
+    ----------
+    dfn : array_like
+        First parameter (positive float).
+    p : array_like
+        Cumulative probability, in [0, 1].
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    dfd : scalar or ndarray
+        `dfd` such that ``fdtr(dfn, dfd, x) == p``.
+
+    See Also
+    --------
+    fdtr : F distribution cumulative distribution function
+    fdtrc : F distribution survival function
+    fdtri : F distribution quantile function
+    scipy.stats.f : F distribution
+
+    Examples
+    --------
+    Compute the F distribution cumulative distribution function for one
+    parameter set.
+
+    >>> from scipy.special import fdtridfd, fdtr
+    >>> dfn, dfd, x = 10, 5, 2
+    >>> cdf_value = fdtr(dfn, dfd, x)
+    >>> cdf_value
+    0.7700248806501017
+
+    Verify that `fdtridfd` recovers the original value for `dfd`:
+
+    >>> fdtridfd(dfn, cdf_value, x)
+    5.0
+    """)
+
+'''
+commented out as fdtridfn seems to have bugs and is not in functions.json
+see: https://github.com/scipy/scipy/pull/15622#discussion_r811440983
+
+add_newdoc(
+    "fdtridfn",
+    """
+    fdtridfn(p, dfd, x, out=None)
+
+    Inverse to `fdtr` vs dfn
+
+    finds the F density argument dfn such that ``fdtr(dfn, dfd, x) == p``.
+
+
+    Parameters
+    ----------
+    p : array_like
+        Cumulative probability, in [0, 1].
+    dfd : array_like
+        Second parameter (positive float).
+    x : array_like
+        Argument (nonnegative float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    dfn : scalar or ndarray
+        `dfn` such that ``fdtr(dfn, dfd, x) == p``.
+
+    See Also
+    --------
+    fdtr, fdtrc, fdtri, fdtridfd
+
+
+    """)
+'''
+
+add_newdoc("gdtr",
+    r"""
+    gdtr(a, b, x, out=None)
+
+    Gamma distribution cumulative distribution function.
+
+    Returns the integral from zero to `x` of the gamma probability density
+    function,
+
+    .. math::
+
+        F = \int_0^x \frac{a^b}{\Gamma(b)} t^{b-1} e^{-at}\,dt,
+
+    where :math:`\Gamma` is the gamma function.
+
+    Parameters
+    ----------
+    a : array_like
+        The rate parameter of the gamma distribution, sometimes denoted
+        :math:`\beta` (float).  It is also the reciprocal of the scale
+        parameter :math:`\theta`.
+    b : array_like
+        The shape parameter of the gamma distribution, sometimes denoted
+        :math:`\alpha` (float).
+    x : array_like
+        The quantile (upper limit of integration; float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The CDF of the gamma distribution with parameters `a` and `b`
+        evaluated at `x`.
+
+    See Also
+    --------
+    gdtrc : 1 - CDF of the gamma distribution.
+    scipy.stats.gamma: Gamma distribution
+
+    Notes
+    -----
+    The evaluation is carried out using the relation to the incomplete gamma
+    integral (regularized gamma function).
+
+    Wrapper for the Cephes [1]_ routine `gdtr`. Calling `gdtr` directly can
+    improve performance compared to the ``cdf`` method of `scipy.stats.gamma`
+    (see last example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``a=1``, ``b=2`` at ``x=5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import gdtr
+    >>> import matplotlib.pyplot as plt
+    >>> gdtr(1., 2., 5.)
+    0.9595723180054873
+
+    Compute the function for ``a=1`` and ``b=2`` at several points by
+    providing a NumPy array for `x`.
+
+    >>> xvalues = np.array([1., 2., 3., 4])
+    >>> gdtr(1., 1., xvalues)
+    array([0.63212056, 0.86466472, 0.95021293, 0.98168436])
+
+    `gdtr` can evaluate different parameter sets by providing arrays with
+    broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the
+    function for three different `a` at four positions `x` and ``b=3``,
+    resulting in a 3x4 array.
+
+    >>> a = np.array([[0.5], [1.5], [2.5]])
+    >>> x = np.array([1., 2., 3., 4])
+    >>> a.shape, x.shape
+    ((3, 1), (4,))
+
+    >>> gdtr(a, 3., x)
+    array([[0.01438768, 0.0803014 , 0.19115317, 0.32332358],
+           [0.19115317, 0.57680992, 0.82642193, 0.9380312 ],
+           [0.45618688, 0.87534798, 0.97974328, 0.9972306 ]])
+
+    Plot the function for four different parameter sets.
+
+    >>> a_parameters = [0.3, 1, 2, 6]
+    >>> b_parameters = [2, 10, 15, 20]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     a, b, style = parameter_set
+    ...     gdtr_vals = gdtr(a, b, x)
+    ...     ax.plot(x, gdtr_vals, label=fr"$a= {a},\, b={b}$", ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("Gamma distribution cumulative distribution function")
+    >>> plt.show()
+
+    The gamma distribution is also available as `scipy.stats.gamma`. Using
+    `gdtr` directly can be much faster than calling the ``cdf`` method of
+    `scipy.stats.gamma`, especially for small arrays or individual values.
+    To get the same results one must use the following parametrization:
+    ``stats.gamma(b, scale=1/a).cdf(x)=gdtr(a, b, x)``.
+
+    >>> from scipy.stats import gamma
+    >>> a = 2.
+    >>> b = 3
+    >>> x = 1.
+    >>> gdtr_result = gdtr(a, b, x)  # this will often be faster than below
+    >>> gamma_dist_result = gamma(b, scale=1/a).cdf(x)
+    >>> gdtr_result == gamma_dist_result  # test that results are equal
+    True
+    """)
+
+add_newdoc("gdtrc",
+    r"""
+    gdtrc(a, b, x, out=None)
+
+    Gamma distribution survival function.
+
+    Integral from `x` to infinity of the gamma probability density function,
+
+    .. math::
+
+        F = \int_x^\infty \frac{a^b}{\Gamma(b)} t^{b-1} e^{-at}\,dt,
+
+    where :math:`\Gamma` is the gamma function.
+
+    Parameters
+    ----------
+    a : array_like
+        The rate parameter of the gamma distribution, sometimes denoted
+        :math:`\beta` (float). It is also the reciprocal of the scale
+        parameter :math:`\theta`.
+    b : array_like
+        The shape parameter of the gamma distribution, sometimes denoted
+        :math:`\alpha` (float).
+    x : array_like
+        The quantile (lower limit of integration; float).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The survival function of the gamma distribution with parameters `a`
+        and `b` evaluated at `x`.
+
+    See Also
+    --------
+    gdtr: Gamma distribution cumulative distribution function
+    scipy.stats.gamma: Gamma distribution
+    gdtrix
+
+    Notes
+    -----
+    The evaluation is carried out using the relation to the incomplete gamma
+    integral (regularized gamma function).
+
+    Wrapper for the Cephes [1]_ routine `gdtrc`. Calling `gdtrc` directly can
+    improve performance compared to the ``sf`` method of `scipy.stats.gamma`
+    (see last example below).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``a=1`` and ``b=2`` at ``x=5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import gdtrc
+    >>> import matplotlib.pyplot as plt
+    >>> gdtrc(1., 2., 5.)
+    0.04042768199451279
+
+    Compute the function for ``a=1``, ``b=2`` at several points by providing
+    a NumPy array for `x`.
+
+    >>> xvalues = np.array([1., 2., 3., 4])
+    >>> gdtrc(1., 1., xvalues)
+    array([0.36787944, 0.13533528, 0.04978707, 0.01831564])
+
+    `gdtrc` can evaluate different parameter sets by providing arrays with
+    broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the
+    function for three different `a` at four positions `x` and ``b=3``,
+    resulting in a 3x4 array.
+
+    >>> a = np.array([[0.5], [1.5], [2.5]])
+    >>> x = np.array([1., 2., 3., 4])
+    >>> a.shape, x.shape
+    ((3, 1), (4,))
+
+    >>> gdtrc(a, 3., x)
+    array([[0.98561232, 0.9196986 , 0.80884683, 0.67667642],
+           [0.80884683, 0.42319008, 0.17357807, 0.0619688 ],
+           [0.54381312, 0.12465202, 0.02025672, 0.0027694 ]])
+
+    Plot the function for four different parameter sets.
+
+    >>> a_parameters = [0.3, 1, 2, 6]
+    >>> b_parameters = [2, 10, 15, 20]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))
+    >>> x = np.linspace(0, 30, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> for parameter_set in parameters_list:
+    ...     a, b, style = parameter_set
+    ...     gdtrc_vals = gdtrc(a, b, x)
+    ...     ax.plot(x, gdtrc_vals, label=fr"$a= {a},\, b={b}$", ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title("Gamma distribution survival function")
+    >>> plt.show()
+
+    The gamma distribution is also available as `scipy.stats.gamma`.
+    Using `gdtrc` directly can be much faster than calling the ``sf`` method
+    of `scipy.stats.gamma`, especially for small arrays or individual
+    values. To get the same results one must use the following parametrization:
+    ``stats.gamma(b, scale=1/a).sf(x)=gdtrc(a, b, x)``.
+
+    >>> from scipy.stats import gamma
+    >>> a = 2
+    >>> b = 3
+    >>> x = 1.
+    >>> gdtrc_result = gdtrc(a, b, x)  # this will often be faster than below
+    >>> gamma_dist_result = gamma(b, scale=1/a).sf(x)
+    >>> gdtrc_result == gamma_dist_result  # test that results are equal
+    True
+    """)
+
+add_newdoc("gdtria",
+    """
+    gdtria(p, b, x, out=None)
+
+    Inverse of `gdtr` vs a.
+
+    Returns the inverse with respect to the parameter `a` of ``p =
+    gdtr(a, b, x)``, the cumulative distribution function of the gamma
+    distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability values.
+    b : array_like
+        `b` parameter values of `gdtr(a, b, x)`. `b` is the "shape" parameter
+        of the gamma distribution.
+    x : array_like
+        Nonnegative real values, from the domain of the gamma distribution.
+    out : ndarray, optional
+        If a fourth argument is given, it must be a numpy.ndarray whose size
+        matches the broadcast result of `a`, `b` and `x`.  `out` is then the
+        array returned by the function.
+
+    Returns
+    -------
+    a : scalar or ndarray
+        Values of the `a` parameter such that ``p = gdtr(a, b, x)`.  ``1/a``
+        is the "scale" parameter of the gamma distribution.
+
+    See Also
+    --------
+    gdtr : CDF of the gamma distribution.
+    gdtrib : Inverse with respect to `b` of `gdtr(a, b, x)`.
+    gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `a` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `a`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Computation of the incomplete gamma function ratios and their
+           inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.
+
+    Examples
+    --------
+    First evaluate `gdtr`.
+
+    >>> from scipy.special import gdtr, gdtria
+    >>> p = gdtr(1.2, 3.4, 5.6)
+    >>> print(p)
+    0.94378087442
+
+    Verify the inverse.
+
+    >>> gdtria(p, 3.4, 5.6)
+    1.2
+    """)
+
+add_newdoc("gdtrib",
+    """
+    gdtrib(a, p, x, out=None)
+
+    Inverse of `gdtr` vs b.
+
+    Returns the inverse with respect to the parameter `b` of ``p =
+    gdtr(a, b, x)``, the cumulative distribution function of the gamma
+    distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        `a` parameter values of ``gdtr(a, b, x)`. ``1/a`` is the "scale"
+        parameter of the gamma distribution.
+    p : array_like
+        Probability values.
+    x : array_like
+        Nonnegative real values, from the domain of the gamma distribution.
+    out : ndarray, optional
+        If a fourth argument is given, it must be a numpy.ndarray whose size
+        matches the broadcast result of `a`, `b` and `x`.  `out` is then the
+        array returned by the function.
+
+    Returns
+    -------
+    b : scalar or ndarray
+        Values of the `b` parameter such that `p = gdtr(a, b, x)`.  `b` is
+        the "shape" parameter of the gamma distribution.
+
+    See Also
+    --------
+    gdtr : CDF of the gamma distribution.
+    gdtria : Inverse with respect to `a` of `gdtr(a, b, x)`.
+    gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.
+
+    Notes
+    -----
+
+    The cumulative distribution function `p` is computed using the Cephes [1]_
+    routines `igam` and `igamc`. Computation of `b` involves a search for a value
+    that produces the desired value of `p` using Chandrupatla's bracketing
+    root finding algorithm [2]_.
+
+    Note that there are some edge cases where `gdtrib` is extended by taking
+    limits where they are uniquely defined. In particular
+    ``x == 0`` with ``p > 0`` and ``p == 0`` with ``x > 0``.
+    For these edge cases, a numerical result will be returned for
+    ``gdtrib(a, p, x)`` even though ``gdtr(a, gdtrib(a, p, x), x)`` is
+    undefined.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [2] Chandrupatla, Tirupathi R.
+           "A new hybrid quadratic/bisection algorithm for finding the zero of a
+           nonlinear function without using derivatives".
+           Advances in Engineering Software, 28(3), 145-149.
+           https://doi.org/10.1016/s0965-9978(96)00051-8
+
+    Examples
+    --------
+    First evaluate `gdtr`.
+
+    >>> from scipy.special import gdtr, gdtrib
+    >>> p = gdtr(1.2, 3.4, 5.6)
+    >>> print(p)
+    0.94378087442
+
+    Verify the inverse.
+
+    >>> gdtrib(1.2, p, 5.6)
+    3.3999999999999995
+    """)
+
+add_newdoc("gdtrix",
+    """
+    gdtrix(a, b, p, out=None)
+
+    Inverse of `gdtr` vs x.
+
+    Returns the inverse with respect to the parameter `x` of ``p =
+    gdtr(a, b, x)``, the cumulative distribution function of the gamma
+    distribution. This is also known as the pth quantile of the
+    distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        `a` parameter values of ``gdtr(a, b, x)``. ``1/a`` is the "scale"
+        parameter of the gamma distribution.
+    b : array_like
+        `b` parameter values of ``gdtr(a, b, x)``. `b` is the "shape" parameter
+        of the gamma distribution.
+    p : array_like
+        Probability values.
+    out : ndarray, optional
+        If a fourth argument is given, it must be a numpy.ndarray whose size
+        matches the broadcast result of `a`, `b` and `x`. `out` is then the
+        array returned by the function.
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Values of the `x` parameter such that `p = gdtr(a, b, x)`.
+
+    See Also
+    --------
+    gdtr : CDF of the gamma distribution.
+    gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``.
+    gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.
+
+    The cumulative distribution function `p` is computed using a routine by
+    DiDinato and Morris [2]_. Computation of `x` involves a search for a value
+    that produces the desired value of `p`. The search relies on the
+    monotonicity of `p` with `x`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] DiDinato, A. R. and Morris, A. H.,
+           Computation of the incomplete gamma function ratios and their
+           inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.
+
+    Examples
+    --------
+    First evaluate `gdtr`.
+
+    >>> from scipy.special import gdtr, gdtrix
+    >>> p = gdtr(1.2, 3.4, 5.6)
+    >>> print(p)
+    0.94378087442
+
+    Verify the inverse.
+
+    >>> gdtrix(1.2, 3.4, p)
+    5.5999999999999996
+    """)
+
+add_newdoc("hankel1",
+    r"""
+    hankel1(v, z, out=None)
+
+    Hankel function of the first kind
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Hankel function of the first kind.
+
+    See Also
+    --------
+    hankel1e : ndarray
+        This function with leading exponential behavior stripped off.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(1)}_v(z) =
+              \frac{2}{\imath\pi} \exp(-\imath \pi v/2) K_v(z \exp(-\imath\pi/2))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(1)}_{-v}(z) = H^{(1)}_v(z) \exp(\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    """)
+
+add_newdoc("hankel1e",
+    r"""
+    hankel1e(v, z, out=None)
+
+    Exponentially scaled Hankel function of the first kind
+
+    Defined as::
+
+        hankel1e(v, z) = hankel1(v, z) * exp(-1j * z)
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the exponentially scaled Hankel function.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(1)}_v(z) =
+              \frac{2}{\imath\pi} \exp(-\imath \pi v/2) K_v(z \exp(-\imath\pi/2))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(1)}_{-v}(z) = H^{(1)}_v(z) \exp(\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    """)
+
+add_newdoc("hankel2",
+    r"""
+    hankel2(v, z, out=None)
+
+    Hankel function of the second kind
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Hankel function of the second kind.
+
+    See Also
+    --------
+    hankel2e : this function with leading exponential behavior stripped off.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(2)}_v(z) =
+              -\frac{2}{\imath\pi} \exp(\imath \pi v/2) K_v(z \exp(\imath\pi/2))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(2)}_{-v}(z) = H^{(2)}_v(z) \exp(-\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    """)
+
+add_newdoc("hankel2e",
+    r"""
+    hankel2e(v, z, out=None)
+
+    Exponentially scaled Hankel function of the second kind
+
+    Defined as::
+
+        hankel2e(v, z) = hankel2(v, z) * exp(1j * z)
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the exponentially scaled Hankel function of the second kind.
+
+    Notes
+    -----
+    A wrapper for the AMOS [1]_ routine `zbesh`, which carries out the
+    computation using the relation,
+
+    .. math:: H^{(2)}_v(z) = -\frac{2}{\imath\pi}
+              \exp(\frac{\imath \pi v}{2}) K_v(z exp(\frac{\imath\pi}{2}))
+
+    where :math:`K_v` is the modified Bessel function of the second kind.
+    For negative orders, the relation
+
+    .. math:: H^{(2)}_{-v}(z) = H^{(2)}_v(z) \exp(-\imath\pi v)
+
+    is used.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    """)
+
+add_newdoc("huber",
+    r"""
+    huber(delta, r, out=None)
+
+    Huber loss function.
+
+    .. math:: \text{huber}(\delta, r) = \begin{cases} \infty & \delta < 0  \\
+              \frac{1}{2}r^2 & 0 \le \delta, | r | \le \delta \\
+              \delta ( |r| - \frac{1}{2}\delta ) & \text{otherwise} \end{cases}
+
+    Parameters
+    ----------
+    delta : ndarray
+        Input array, indicating the quadratic vs. linear loss changepoint.
+    r : ndarray
+        Input array, possibly representing residuals.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The computed Huber loss function values.
+
+    See Also
+    --------
+    pseudo_huber : smooth approximation of this function
+
+    Notes
+    -----
+    `huber` is useful as a loss function in robust statistics or machine
+    learning to reduce the influence of outliers as compared to the common
+    squared error loss, residuals with a magnitude higher than `delta` are
+    not squared [1]_.
+
+    Typically, `r` represents residuals, the difference
+    between a model prediction and data. Then, for :math:`|r|\leq\delta`,
+    `huber` resembles the squared error and for :math:`|r|>\delta` the
+    absolute error. This way, the Huber loss often achieves
+    a fast convergence in model fitting for small residuals like the squared
+    error loss function and still reduces the influence of outliers
+    (:math:`|r|>\delta`) like the absolute error loss. As :math:`\delta` is
+    the cutoff between squared and absolute error regimes, it has
+    to be tuned carefully for each problem. `huber` is also
+    convex, making it suitable for gradient based optimization.
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Peter Huber. "Robust Estimation of a Location Parameter",
+           1964. Annals of Statistics. 53 (1): 73 - 101.
+
+    Examples
+    --------
+    Import all necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.special import huber
+    >>> import matplotlib.pyplot as plt
+
+    Compute the function for ``delta=1`` at ``r=2``
+
+    >>> huber(1., 2.)
+    1.5
+
+    Compute the function for different `delta` by providing a NumPy array or
+    list for `delta`.
+
+    >>> huber([1., 3., 5.], 4.)
+    array([3.5, 7.5, 8. ])
+
+    Compute the function at different points by providing a NumPy array or
+    list for `r`.
+
+    >>> huber(2., np.array([1., 1.5, 3.]))
+    array([0.5  , 1.125, 4.   ])
+
+    The function can be calculated for different `delta` and `r` by
+    providing arrays for both with compatible shapes for broadcasting.
+
+    >>> r = np.array([1., 2.5, 8., 10.])
+    >>> deltas = np.array([[1.], [5.], [9.]])
+    >>> print(r.shape, deltas.shape)
+    (4,) (3, 1)
+
+    >>> huber(deltas, r)
+    array([[ 0.5  ,  2.   ,  7.5  ,  9.5  ],
+           [ 0.5  ,  3.125, 27.5  , 37.5  ],
+           [ 0.5  ,  3.125, 32.   , 49.5  ]])
+
+    Plot the function for different `delta`.
+
+    >>> x = np.linspace(-4, 4, 500)
+    >>> deltas = [1, 2, 3]
+    >>> linestyles = ["dashed", "dotted", "dashdot"]
+    >>> fig, ax = plt.subplots()
+    >>> combined_plot_parameters = list(zip(deltas, linestyles))
+    >>> for delta, style in combined_plot_parameters:
+    ...     ax.plot(x, huber(delta, x), label=fr"$\delta={delta}$", ls=style)
+    >>> ax.legend(loc="upper center")
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title(r"Huber loss function $h_{\delta}(x)$")
+    >>> ax.set_xlim(-4, 4)
+    >>> ax.set_ylim(0, 8)
+    >>> plt.show()
+    """)
+
+add_newdoc("hyp0f1",
+    r"""
+    hyp0f1(v, z, out=None)
+
+    Confluent hypergeometric limit function 0F1.
+
+    Parameters
+    ----------
+    v : array_like
+        Real-valued parameter
+    z : array_like
+        Real- or complex-valued argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The confluent hypergeometric limit function
+
+    Notes
+    -----
+    This function is defined as:
+
+    .. math:: _0F_1(v, z) = \sum_{k=0}^{\infty}\frac{z^k}{(v)_k k!}.
+
+    It's also the limit as :math:`q \to \infty` of :math:`_1F_1(q; v; z/q)`,
+    and satisfies the differential equation :math:`f''(z) + vf'(z) =
+    f(z)`. See [1]_ for more information.
+
+    References
+    ----------
+    .. [1] Wolfram MathWorld, "Confluent Hypergeometric Limit Function",
+           http://mathworld.wolfram.com/ConfluentHypergeometricLimitFunction.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is one when `z` is zero.
+
+    >>> sc.hyp0f1(1, 0)
+    1.0
+
+    It is the limit of the confluent hypergeometric function as `q`
+    goes to infinity.
+
+    >>> q = np.array([1, 10, 100, 1000])
+    >>> v = 1
+    >>> z = 1
+    >>> sc.hyp1f1(q, v, z / q)
+    array([2.71828183, 2.31481985, 2.28303778, 2.27992985])
+    >>> sc.hyp0f1(v, z)
+    2.2795853023360673
+
+    It is related to Bessel functions.
+
+    >>> n = 1
+    >>> x = np.linspace(0, 1, 5)
+    >>> sc.jv(n, x)
+    array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])
+    >>> (0.5 * x)**n / sc.factorial(n) * sc.hyp0f1(n + 1, -0.25 * x**2)
+    array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])
+
+    """)
+
+add_newdoc("hyp1f1",
+    r"""
+    hyp1f1(a, b, x, out=None)
+
+    Confluent hypergeometric function 1F1.
+
+    The confluent hypergeometric function is defined by the series
+
+    .. math::
+
+       {}_1F_1(a; b; x) = \sum_{k = 0}^\infty \frac{(a)_k}{(b)_k k!} x^k.
+
+    See [dlmf]_ for more details. Here :math:`(\cdot)_k` is the
+    Pochhammer symbol; see `poch`.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Real parameters
+    x : array_like
+        Real or complex argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the confluent hypergeometric function
+
+    See Also
+    --------
+    hyperu : another confluent hypergeometric function
+    hyp0f1 : confluent hypergeometric limit function
+    hyp2f1 : Gaussian hypergeometric function
+
+    Notes
+    -----
+    For real values, this function uses the ``hyp1f1`` routine from the C++ Boost
+    library [2]_, for complex values a C translation of the specfun
+    Fortran library [3]_.
+
+    References
+    ----------
+    .. [dlmf] NIST Digital Library of Mathematical Functions
+              https://dlmf.nist.gov/13.2#E2
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+    .. [3] Zhang, Jin, "Computation of Special Functions", John Wiley
+           and Sons, Inc, 1996.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is one when `x` is zero:
+
+    >>> sc.hyp1f1(0.5, 0.5, 0)
+    1.0
+
+    It is singular when `b` is a nonpositive integer.
+
+    >>> sc.hyp1f1(0.5, -1, 0)
+    inf
+
+    It is a polynomial when `a` is a nonpositive integer.
+
+    >>> a, b, x = -1, 0.5, np.array([1.0, 2.0, 3.0, 4.0])
+    >>> sc.hyp1f1(a, b, x)
+    array([-1., -3., -5., -7.])
+    >>> 1 + (a / b) * x
+    array([-1., -3., -5., -7.])
+
+    It reduces to the exponential function when ``a = b``.
+
+    >>> sc.hyp1f1(2, 2, [1, 2, 3, 4])
+    array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])
+    >>> np.exp([1, 2, 3, 4])
+    array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])
+
+    """)
+
+add_newdoc("hyperu",
+    r"""
+    hyperu(a, b, x, out=None)
+
+    Confluent hypergeometric function U
+
+    It is defined as the solution to the equation
+
+    .. math::
+
+       x \frac{d^2w}{dx^2} + (b - x) \frac{dw}{dx} - aw = 0
+
+    which satisfies the property
+
+    .. math::
+
+       U(a, b, x) \sim x^{-a}
+
+    as :math:`x \to \infty`. See [dlmf]_ for more details.
+
+    Parameters
+    ----------
+    a, b : array_like
+        Real-valued parameters
+    x : array_like
+        Real-valued argument
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of `U`
+
+    References
+    ----------
+    .. [dlmf] NIST Digital Library of Mathematics Functions
+              https://dlmf.nist.gov/13.2#E6
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It has a branch cut along the negative `x` axis.
+
+    >>> x = np.linspace(-0.1, -10, 5)
+    >>> sc.hyperu(1, 1, x)
+    array([nan, nan, nan, nan, nan])
+
+    It approaches zero as `x` goes to infinity.
+
+    >>> x = np.array([1, 10, 100])
+    >>> sc.hyperu(1, 1, x)
+    array([0.59634736, 0.09156333, 0.00990194])
+
+    It satisfies Kummer's transformation.
+
+    >>> a, b, x = 2, 1, 1
+    >>> sc.hyperu(a, b, x)
+    0.1926947246463881
+    >>> x**(1 - b) * sc.hyperu(a - b + 1, 2 - b, x)
+    0.1926947246463881
+
+    """)
+
+add_newdoc("_igam_fac",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("iv",
+    r"""
+    iv(v, z, out=None)
+
+    Modified Bessel function of the first kind of real order.
+
+    Parameters
+    ----------
+    v : array_like
+        Order. If `z` is of real type and negative, `v` must be integer
+        valued.
+    z : array_like of float or complex
+        Argument.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the modified Bessel function.
+
+    See Also
+    --------
+    ive : This function with leading exponential behavior stripped off.
+    i0 : Faster version of this function for order 0.
+    i1 : Faster version of this function for order 1.
+
+    Notes
+    -----
+    For real `z` and :math:`v \in [-50, 50]`, the evaluation is carried out
+    using Temme's method [1]_.  For larger orders, uniform asymptotic
+    expansions are applied.
+
+    For complex `z` and positive `v`, the AMOS [2]_ `zbesi` routine is
+    called. It uses a power series for small `z`, the asymptotic expansion
+    for large `abs(z)`, the Miller algorithm normalized by the Wronskian
+    and a Neumann series for intermediate magnitudes, and the uniform
+    asymptotic expansions for :math:`I_v(z)` and :math:`J_v(z)` for large
+    orders. Backward recurrence is used to generate sequences or reduce
+    orders when necessary.
+
+    The calculations above are done in the right half plane and continued
+    into the left half plane by the formula,
+
+    .. math:: I_v(z \exp(\pm\imath\pi)) = \exp(\pm\pi v) I_v(z)
+
+    (valid when the real part of `z` is positive).  For negative `v`, the
+    formula
+
+    .. math:: I_{-v}(z) = I_v(z) + \frac{2}{\pi} \sin(\pi v) K_v(z)
+
+    is used, where :math:`K_v(z)` is the modified Bessel function of the
+    second kind, evaluated using the AMOS routine `zbesk`.
+
+    References
+    ----------
+    .. [1] Temme, Journal of Computational Physics, vol 21, 343 (1976)
+    .. [2] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import iv
+    >>> iv(0, 1.)
+    1.2660658777520084
+
+    Evaluate the function at one point for different orders.
+
+    >>> iv(0, 1.), iv(1, 1.), iv(1.5, 1.)
+    (1.2660658777520084, 0.565159103992485, 0.2935253263474798)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> iv([0, 1, 1.5], 1.)
+    array([1.26606588, 0.5651591 , 0.29352533])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([-2., 0., 3.])
+    >>> iv(0, points)
+    array([2.2795853 , 1.        , 4.88079259])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> iv(orders, points)
+    array([[ 2.2795853 ,  1.        ,  4.88079259],
+           [-1.59063685,  0.        ,  3.95337022]])
+
+    Plot the functions of order 0 to 3 from -5 to 5.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-5., 5., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, iv(i, x), label=f'$I_{i!r}$')
+    >>> ax.legend()
+    >>> plt.show()
+
+    """)
+
+add_newdoc("ive",
+    r"""
+    ive(v, z, out=None)
+
+    Exponentially scaled modified Bessel function of the first kind.
+
+    Defined as::
+
+        ive(v, z) = iv(v, z) * exp(-abs(z.real))
+
+    For imaginary numbers without a real part, returns the unscaled
+    Bessel function of the first kind `iv`.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order.
+    z : array_like of float or complex
+        Argument.
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the exponentially scaled modified Bessel function.
+
+    See Also
+    --------
+    iv: Modified Bessel function of the first kind
+    i0e: Faster implementation of this function for order 0
+    i1e: Faster implementation of this function for order 1
+
+    Notes
+    -----
+    For positive `v`, the AMOS [1]_ `zbesi` routine is called. It uses a
+    power series for small `z`, the asymptotic expansion for large
+    `abs(z)`, the Miller algorithm normalized by the Wronskian and a
+    Neumann series for intermediate magnitudes, and the uniform asymptotic
+    expansions for :math:`I_v(z)` and :math:`J_v(z)` for large orders.
+    Backward recurrence is used to generate sequences or reduce orders when
+    necessary.
+
+    The calculations above are done in the right half plane and continued
+    into the left half plane by the formula,
+
+    .. math:: I_v(z \exp(\pm\imath\pi)) = \exp(\pm\pi v) I_v(z)
+
+    (valid when the real part of `z` is positive).  For negative `v`, the
+    formula
+
+    .. math:: I_{-v}(z) = I_v(z) + \frac{2}{\pi} \sin(\pi v) K_v(z)
+
+    is used, where :math:`K_v(z)` is the modified Bessel function of the
+    second kind, evaluated using the AMOS routine `zbesk`.
+
+    `ive` is useful for large arguments `z`: for these, `iv` easily overflows,
+    while `ive` does not due to the exponential scaling.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    In the following example `iv` returns infinity whereas `ive` still returns
+    a finite number.
+
+    >>> from scipy.special import iv, ive
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> iv(3, 1000.), ive(3, 1000.)
+    (inf, 0.01256056218254712)
+
+    Evaluate the function at one point for different orders by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> ive([0, 1, 1.5], 1.)
+    array([0.46575961, 0.20791042, 0.10798193])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> points = np.array([-2., 0., 3.])
+    >>> ive(0, points)
+    array([0.30850832, 1.        , 0.24300035])
+
+    Evaluate the function at several points for different orders by
+    providing arrays for both `v` for `z`. Both arrays have to be
+    broadcastable to the correct shape. To calculate the orders 0, 1
+    and 2 for a 1D array of points:
+
+    >>> ive([[0], [1], [2]], points)
+    array([[ 0.30850832,  1.        ,  0.24300035],
+           [-0.21526929,  0.        ,  0.19682671],
+           [ 0.09323903,  0.        ,  0.11178255]])
+
+    Plot the functions of order 0 to 3 from -5 to 5.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-5., 5., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, ive(i, x), label=fr'$I_{i!r}(z)\cdot e^{{-|z|}}$')
+    >>> ax.legend()
+    >>> ax.set_xlabel(r"$z$")
+    >>> plt.show()
+    """)
+
+add_newdoc("jn",
+    """
+    jn(n, x, out=None)
+
+    Bessel function of the first kind of integer order and real argument.
+
+    Parameters
+    ----------
+    n : array_like
+        order of the Bessel function
+    x : array_like
+        argument of the Bessel function
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the bessel function
+
+    See Also
+    --------
+    jv
+    spherical_jn : spherical Bessel functions.
+
+    Notes
+    -----
+    `jn` is an alias of `jv`.
+    Not to be confused with the spherical Bessel functions (see
+    `spherical_jn`).
+
+    """)
+
+add_newdoc("jv",
+    r"""
+    jv(v, z, out=None)
+
+    Bessel function of the first kind of real order and complex argument.
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    J : scalar or ndarray
+        Value of the Bessel function, :math:`J_v(z)`.
+
+    See Also
+    --------
+    jve : :math:`J_v` with leading exponential behavior stripped off.
+    spherical_jn : spherical Bessel functions.
+    j0 : faster version of this function for order 0.
+    j1 : faster version of this function for order 1.
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the AMOS
+    [1]_ `zbesj` routine, which exploits the connection to the modified
+    Bessel function :math:`I_v`,
+
+    .. math::
+        J_v(z) = \exp(v\pi\imath/2) I_v(-\imath z)\qquad (\Im z > 0)
+
+        J_v(z) = \exp(-v\pi\imath/2) I_v(\imath z)\qquad (\Im z < 0)
+
+    For negative `v` values the formula,
+
+    .. math:: J_{-v}(z) = J_v(z) \cos(\pi v) - Y_v(z) \sin(\pi v)
+
+    is used, where :math:`Y_v(z)` is the Bessel function of the second
+    kind, computed using the AMOS routine `zbesy`.  Note that the second
+    term is exactly zero for integer `v`; to improve accuracy the second
+    term is explicitly omitted for `v` values such that `v = floor(v)`.
+
+    Not to be confused with the spherical Bessel functions (see `spherical_jn`).
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import jv
+    >>> jv(0, 1.)
+    0.7651976865579666
+
+    Evaluate the function at one point for different orders.
+
+    >>> jv(0, 1.), jv(1, 1.), jv(1.5, 1.)
+    (0.7651976865579666, 0.44005058574493355, 0.24029783912342725)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> jv([0, 1, 1.5], 1.)
+    array([0.76519769, 0.44005059, 0.24029784])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([-2., 0., 3.])
+    >>> jv(0, points)
+    array([ 0.22389078,  1.        , -0.26005195])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> jv(orders, points)
+    array([[ 0.22389078,  1.        , -0.26005195],
+           [-0.57672481,  0.        ,  0.33905896]])
+
+    Plot the functions of order 0 to 3 from -10 to 10.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-10., 10., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, jv(i, x), label=f'$J_{i!r}$')
+    >>> ax.legend()
+    >>> plt.show()
+
+    """)
+
+add_newdoc("jve",
+    r"""
+    jve(v, z, out=None)
+
+    Exponentially scaled Bessel function of the first kind of order `v`.
+
+    Defined as::
+
+        jve(v, z) = jv(v, z) * exp(-abs(z.imag))
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function values
+
+    Returns
+    -------
+    J : scalar or ndarray
+        Value of the exponentially scaled Bessel function.
+
+    See Also
+    --------
+    jv: Unscaled Bessel function of the first kind
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the AMOS
+    [1]_ `zbesj` routine, which exploits the connection to the modified
+    Bessel function :math:`I_v`,
+
+    .. math::
+        J_v(z) = \exp(v\pi\imath/2) I_v(-\imath z)\qquad (\Im z > 0)
+
+        J_v(z) = \exp(-v\pi\imath/2) I_v(\imath z)\qquad (\Im z < 0)
+
+    For negative `v` values the formula,
+
+    .. math:: J_{-v}(z) = J_v(z) \cos(\pi v) - Y_v(z) \sin(\pi v)
+
+    is used, where :math:`Y_v(z)` is the Bessel function of the second
+    kind, computed using the AMOS routine `zbesy`.  Note that the second
+    term is exactly zero for integer `v`; to improve accuracy the second
+    term is explicitly omitted for `v` values such that `v = floor(v)`.
+
+    Exponentially scaled Bessel functions are useful for large arguments `z`:
+    for these, the unscaled Bessel functions can easily under-or overflow.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Compare the output of `jv` and `jve` for large complex arguments for `z`
+    by computing their values for order ``v=1`` at ``z=1000j``. We see that
+    `jv` overflows but `jve` returns a finite number:
+
+    >>> import numpy as np
+    >>> from scipy.special import jv, jve
+    >>> v = 1
+    >>> z = 1000j
+    >>> jv(v, z), jve(v, z)
+    ((inf+infj), (7.721967686709077e-19+0.012610930256928629j))
+
+    For real arguments for `z`, `jve` returns the same as `jv`.
+
+    >>> v, z = 1, 1000
+    >>> jv(v, z), jve(v, z)
+    (0.004728311907089523, 0.004728311907089523)
+
+    The function can be evaluated for several orders at the same time by
+    providing a list or NumPy array for `v`:
+
+    >>> jve([1, 3, 5], 1j)
+    array([1.27304208e-17+2.07910415e-01j, -4.99352086e-19-8.15530777e-03j,
+           6.11480940e-21+9.98657141e-05j])
+
+    In the same way, the function can be evaluated at several points in one
+    call by providing a list or NumPy array for `z`:
+
+    >>> jve(1, np.array([1j, 2j, 3j]))
+    array([1.27308412e-17+0.20791042j, 1.31814423e-17+0.21526929j,
+           1.20521602e-17+0.19682671j])
+
+    It is also possible to evaluate several orders at several points
+    at the same time by providing arrays for `v` and `z` with
+    compatible shapes for broadcasting. Compute `jve` for two different orders
+    `v` and three points `z` resulting in a 2x3 array.
+
+    >>> v = np.array([[1], [3]])
+    >>> z = np.array([1j, 2j, 3j])
+    >>> v.shape, z.shape
+    ((2, 1), (3,))
+
+    >>> jve(v, z)
+    array([[1.27304208e-17+0.20791042j,  1.31810070e-17+0.21526929j,
+            1.20517622e-17+0.19682671j],
+           [-4.99352086e-19-0.00815531j, -1.76289571e-18-0.02879122j,
+            -2.92578784e-18-0.04778332j]])
+    """)
+
+add_newdoc("kelvin",
+    """
+    kelvin(x, out=None)
+
+    Kelvin functions as complex numbers
+
+    Parameters
+    ----------
+    x : array_like
+        Argument
+    out : tuple of ndarray, optional
+        Optional output arrays for the function values
+
+    Returns
+    -------
+    Be, Ke, Bep, Kep : 4-tuple of scalar or ndarray
+        The tuple (Be, Ke, Bep, Kep) contains complex numbers
+        representing the real and imaginary Kelvin functions and their
+        derivatives evaluated at `x`.  For example, kelvin(x)[0].real =
+        ber x and kelvin(x)[0].imag = bei x with similar relationships
+        for ker and kei.
+    """)
+
+add_newdoc("ker",
+    r"""
+    ker(x, out=None)
+
+    Kelvin function ker.
+
+    Defined as
+
+    .. math::
+
+        \mathrm{ker}(x) = \Re[K_0(x e^{\pi i / 4})]
+
+    Where :math:`K_0` is the modified Bessel function of the second
+    kind (see `kv`). See [dlmf]_ for more details.
+
+    Parameters
+    ----------
+    x : array_like
+        Real argument.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Kelvin function.
+
+    See Also
+    --------
+    kei : the corresponding imaginary part
+    kerp : the derivative of ker
+    kv : modified Bessel function of the second kind
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/10.61
+
+    Examples
+    --------
+    It can be expressed using the modified Bessel function of the
+    second kind.
+
+    >>> import numpy as np
+    >>> import scipy.special as sc
+    >>> x = np.array([1.0, 2.0, 3.0, 4.0])
+    >>> sc.kv(0, x * np.exp(np.pi * 1j / 4)).real
+    array([ 0.28670621, -0.04166451, -0.06702923, -0.03617885])
+    >>> sc.ker(x)
+    array([ 0.28670621, -0.04166451, -0.06702923, -0.03617885])
+
+    """)
+
+add_newdoc("kerp",
+    r"""
+    kerp(x, out=None)
+
+    Derivative of the Kelvin function ker.
+
+    Parameters
+    ----------
+    x : array_like
+        Real argument.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of ker.
+
+    See Also
+    --------
+    ker
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/10#PT5
+
+    """)
+
+add_newdoc("kl_div",
+    r"""
+    kl_div(x, y, out=None)
+
+    Elementwise function for computing Kullback-Leibler divergence.
+
+    .. math::
+
+        \mathrm{kl\_div}(x, y) =
+          \begin{cases}
+            x \log(x / y) - x + y & x > 0, y > 0 \\
+            y & x = 0, y \ge 0 \\
+            \infty & \text{otherwise}
+          \end{cases}
+
+    Parameters
+    ----------
+    x, y : array_like
+        Real arguments
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Kullback-Liebler divergence.
+
+    See Also
+    --------
+    entr, rel_entr, scipy.stats.entropy
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    This function is non-negative and is jointly convex in `x` and `y`.
+
+    The origin of this function is in convex programming; see [1]_ for
+    details. This is why the function contains the extra :math:`-x
+    + y` terms over what might be expected from the Kullback-Leibler
+    divergence. For a version of the function without the extra terms,
+    see `rel_entr`.
+
+    References
+    ----------
+    .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.
+           Cambridge University Press, 2004.
+           :doi:`https://doi.org/10.1017/CBO9780511804441`
+
+    """)
+
+add_newdoc("kn",
+    r"""
+    kn(n, x, out=None)
+
+    Modified Bessel function of the second kind of integer order `n`
+
+    Returns the modified Bessel function of the second kind for integer order
+    `n` at real `z`.
+
+    These are also sometimes called functions of the third kind, Basset
+    functions, or Macdonald functions.
+
+    Parameters
+    ----------
+    n : array_like of int
+        Order of Bessel functions (floats will truncate with a warning)
+    x : array_like of float
+        Argument at which to evaluate the Bessel functions
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the Modified Bessel function of the second kind,
+        :math:`K_n(x)`.
+
+    See Also
+    --------
+    kv : Same function, but accepts real order and complex argument
+    kvp : Derivative of this function
+
+    Notes
+    -----
+    Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the
+    algorithm used, see [2]_ and the references therein.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel
+           functions of a complex argument and nonnegative order", ACM
+           TOMS Vol. 12 Issue 3, Sept. 1986, p. 265
+
+    Examples
+    --------
+    Plot the function of several orders for real input:
+
+    >>> import numpy as np
+    >>> from scipy.special import kn
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> for N in range(6):
+    ...     plt.plot(x, kn(N, x), label='$K_{}(x)$'.format(N))
+    >>> plt.ylim(0, 10)
+    >>> plt.legend()
+    >>> plt.title(r'Modified Bessel function of the second kind $K_n(x)$')
+    >>> plt.show()
+
+    Calculate for a single value at multiple orders:
+
+    >>> kn([4, 5, 6], 1)
+    array([   44.23241585,   360.9605896 ,  3653.83831186])
+    """)
+
+add_newdoc("kolmogi",
+    """
+    kolmogi(p, out=None)
+
+    Inverse Survival Function of Kolmogorov distribution
+
+    It is the inverse function to `kolmogorov`.
+    Returns y such that ``kolmogorov(y) == p``.
+
+    Parameters
+    ----------
+    p : float array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of kolmogi(p)
+
+    See Also
+    --------
+    kolmogorov : The Survival Function for the distribution
+    scipy.stats.kstwobign : Provides the functionality as a continuous distribution
+    smirnov, smirnovi : Functions for the one-sided distribution
+
+    Notes
+    -----
+    `kolmogorov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.kstwobign` distribution.
+
+    Examples
+    --------
+    >>> from scipy.special import kolmogi
+    >>> kolmogi([0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0])
+    array([        inf,  1.22384787,  1.01918472,  0.82757356,  0.67644769,
+            0.57117327,  0.        ])
+
+    """)
+
+add_newdoc("kolmogorov",
+    r"""
+    kolmogorov(y, out=None)
+
+    Complementary cumulative distribution (Survival Function) function of
+    Kolmogorov distribution.
+
+    Returns the complementary cumulative distribution function of
+    Kolmogorov's limiting distribution (``D_n*\sqrt(n)`` as n goes to infinity)
+    of a two-sided test for equality between an empirical and a theoretical
+    distribution. It is equal to the (limit as n->infinity of the)
+    probability that ``sqrt(n) * max absolute deviation > y``.
+
+    Parameters
+    ----------
+    y : float array_like
+      Absolute deviation between the Empirical CDF (ECDF) and the target CDF,
+      multiplied by sqrt(n).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of kolmogorov(y)
+
+    See Also
+    --------
+    kolmogi : The Inverse Survival Function for the distribution
+    scipy.stats.kstwobign : Provides the functionality as a continuous distribution
+    smirnov, smirnovi : Functions for the one-sided distribution
+
+    Notes
+    -----
+    `kolmogorov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.kstwobign` distribution.
+
+    Examples
+    --------
+    Show the probability of a gap at least as big as 0, 0.5 and 1.0.
+
+    >>> import numpy as np
+    >>> from scipy.special import kolmogorov
+    >>> from scipy.stats import kstwobign
+    >>> kolmogorov([0, 0.5, 1.0])
+    array([ 1.        ,  0.96394524,  0.26999967])
+
+    Compare a sample of size 1000 drawn from a Laplace(0, 1) distribution against
+    the target distribution, a Normal(0, 1) distribution.
+
+    >>> from scipy.stats import norm, laplace
+    >>> rng = np.random.default_rng()
+    >>> n = 1000
+    >>> lap01 = laplace(0, 1)
+    >>> x = np.sort(lap01.rvs(n, random_state=rng))
+    >>> np.mean(x), np.std(x)
+    (-0.05841730131499543, 1.3968109101997568)
+
+    Construct the Empirical CDF and the K-S statistic Dn.
+
+    >>> target = norm(0,1)  # Normal mean 0, stddev 1
+    >>> cdfs = target.cdf(x)
+    >>> ecdfs = np.arange(n+1, dtype=float)/n
+    >>> gaps = np.column_stack([cdfs - ecdfs[:n], ecdfs[1:] - cdfs])
+    >>> Dn = np.max(gaps)
+    >>> Kn = np.sqrt(n) * Dn
+    >>> print('Dn=%f, sqrt(n)*Dn=%f' % (Dn, Kn))
+    Dn=0.043363, sqrt(n)*Dn=1.371265
+    >>> print(chr(10).join(['For a sample of size n drawn from a N(0, 1) distribution:',
+    ...   ' the approximate Kolmogorov probability that sqrt(n)*Dn>=%f is %f' %
+    ...    (Kn, kolmogorov(Kn)),
+    ...   ' the approximate Kolmogorov probability that sqrt(n)*Dn<=%f is %f' %
+    ...    (Kn, kstwobign.cdf(Kn))]))
+    For a sample of size n drawn from a N(0, 1) distribution:
+     the approximate Kolmogorov probability that sqrt(n)*Dn>=1.371265 is 0.046533
+     the approximate Kolmogorov probability that sqrt(n)*Dn<=1.371265 is 0.953467
+
+    Plot the Empirical CDF against the target N(0, 1) CDF.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.step(np.concatenate([[-3], x]), ecdfs, where='post', label='Empirical CDF')
+    >>> x3 = np.linspace(-3, 3, 100)
+    >>> plt.plot(x3, target.cdf(x3), label='CDF for N(0, 1)')
+    >>> plt.ylim([0, 1]); plt.grid(True); plt.legend();
+    >>> # Add vertical lines marking Dn+ and Dn-
+    >>> iminus, iplus = np.argmax(gaps, axis=0)
+    >>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus],
+    ...            color='r', linestyle='dashed', lw=4)
+    >>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1],
+    ...            color='r', linestyle='dashed', lw=4)
+    >>> plt.show()
+    """)
+
+add_newdoc("_kolmogc",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc("_kolmogci",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc("_kolmogp",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc("kv",
+    r"""
+    kv(v, z, out=None)
+
+    Modified Bessel function of the second kind of real order `v`
+
+    Returns the modified Bessel function of the second kind for real order
+    `v` at complex `z`.
+
+    These are also sometimes called functions of the third kind, Basset
+    functions, or Macdonald functions.  They are defined as those solutions
+    of the modified Bessel equation for which,
+
+    .. math::
+        K_v(x) \sim \sqrt{\pi/(2x)} \exp(-x)
+
+    as :math:`x \to \infty` [3]_.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel functions
+    z : array_like of complex
+        Argument at which to evaluate the Bessel functions
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The results. Note that input must be of complex type to get complex
+        output, e.g. ``kv(3, -2+0j)`` instead of ``kv(3, -2)``.
+
+    See Also
+    --------
+    kve : This function with leading exponential behavior stripped off.
+    kvp : Derivative of this function
+
+    Notes
+    -----
+    Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the
+    algorithm used, see [2]_ and the references therein.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel
+           functions of a complex argument and nonnegative order", ACM
+           TOMS Vol. 12 Issue 3, Sept. 1986, p. 265
+    .. [3] NIST Digital Library of Mathematical Functions,
+           Eq. 10.25.E3. https://dlmf.nist.gov/10.25.E3
+
+    Examples
+    --------
+    Plot the function of several orders for real input:
+
+    >>> import numpy as np
+    >>> from scipy.special import kv
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> for N in np.linspace(0, 6, 5):
+    ...     plt.plot(x, kv(N, x), label='$K_{{{}}}(x)$'.format(N))
+    >>> plt.ylim(0, 10)
+    >>> plt.legend()
+    >>> plt.title(r'Modified Bessel function of the second kind $K_\nu(x)$')
+    >>> plt.show()
+
+    Calculate for a single value at multiple orders:
+
+    >>> kv([4, 4.5, 5], 1+2j)
+    array([ 0.1992+2.3892j,  2.3493+3.6j   ,  7.2827+3.8104j])
+
+    """)
+
+add_newdoc("kve",
+    r"""
+    kve(v, z, out=None)
+
+    Exponentially scaled modified Bessel function of the second kind.
+
+    Returns the exponentially scaled, modified Bessel function of the
+    second kind (sometimes called the third kind) for real order `v` at
+    complex `z`::
+
+        kve(v, z) = kv(v, z) * exp(z)
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel functions
+    z : array_like of complex
+        Argument at which to evaluate the Bessel functions
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The exponentially scaled modified Bessel function of the second kind.
+
+    See Also
+    --------
+    kv : This function without exponential scaling.
+    k0e : Faster version of this function for order 0.
+    k1e : Faster version of this function for order 1.
+
+    Notes
+    -----
+    Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the
+    algorithm used, see [2]_ and the references therein.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+    .. [2] Donald E. Amos, "Algorithm 644: A portable package for Bessel
+           functions of a complex argument and nonnegative order", ACM
+           TOMS Vol. 12 Issue 3, Sept. 1986, p. 265
+
+    Examples
+    --------
+    In the following example `kv` returns 0 whereas `kve` still returns
+    a useful finite number.
+
+    >>> import numpy as np
+    >>> from scipy.special import kv, kve
+    >>> import matplotlib.pyplot as plt
+    >>> kv(3, 1000.), kve(3, 1000.)
+    (0.0, 0.03980696128440973)
+
+    Evaluate the function at one point for different orders by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> kve([0, 1, 1.5], 1.)
+    array([1.14446308, 1.63615349, 2.50662827])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> points = np.array([1., 3., 10.])
+    >>> kve(0, points)
+    array([1.14446308, 0.6977616 , 0.39163193])
+
+    Evaluate the function at several points for different orders by
+    providing arrays for both `v` for `z`. Both arrays have to be
+    broadcastable to the correct shape. To calculate the orders 0, 1
+    and 2 for a 1D array of points:
+
+    >>> kve([[0], [1], [2]], points)
+    array([[1.14446308, 0.6977616 , 0.39163193],
+           [1.63615349, 0.80656348, 0.41076657],
+           [4.41677005, 1.23547058, 0.47378525]])
+
+    Plot the functions of order 0 to 3 from 0 to 5.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0., 5., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, kve(i, x), label=fr'$K_{i!r}(z)\cdot e^z$')
+    >>> ax.legend()
+    >>> ax.set_xlabel(r"$z$")
+    >>> ax.set_ylim(0, 4)
+    >>> ax.set_xlim(0, 5)
+    >>> plt.show()
+    """)
+
+add_newdoc("_lanczos_sum_expg_scaled",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc(
+    "_landau_pdf",
+    """
+    _landau_pdf(x, loc, scale)
+
+    Probability density function of the Landau distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued argument
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_cdf",
+    """
+    _landau_cdf(x, loc, scale)
+
+    Cumulative distribution function of the Landau distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued argument
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_sf",
+    """
+    _landau_sf(x, loc, scale)
+
+    Survival function of the Landau distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued argument
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_ppf",
+    """
+    _landau_ppf(p, loc, scale)
+
+    Percent point function of the Landau distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Real-valued argument between 0 and 1
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_landau_isf",
+    """
+    _landau_isf(p, loc, scale)
+
+    Inverse survival function of the Landau distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Real-valued argument between 0 and 1
+    loc : array_like
+        Real-valued distribution location
+    scale : array_like
+        Positive, real-valued distribution scale
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc("_lgam1p",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("log1p",
+    """
+    log1p(x, out=None)
+
+    Calculates log(1 + x) for use when `x` is near zero.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex valued input.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of ``log(1 + x)``.
+
+    See Also
+    --------
+    expm1, cosm1
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is more accurate than using ``log(1 + x)`` directly for ``x``
+    near 0. Note that in the below example ``1 + 1e-17 == 1`` to
+    double precision.
+
+    >>> sc.log1p(1e-17)
+    1e-17
+    >>> np.log(1 + 1e-17)
+    0.0
+
+    """)
+
+add_newdoc("_log1pmx",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("lpmv",
+    r"""
+    lpmv(m, v, x, out=None)
+
+    Associated Legendre function of integer order and real degree.
+
+    Defined as
+
+    .. math::
+
+        P_v^m = (-1)^m (1 - x^2)^{m/2} \frac{d^m}{dx^m} P_v(x)
+
+    where
+
+    .. math::
+
+        P_v = \sum_{k = 0}^\infty \frac{(-v)_k (v + 1)_k}{(k!)^2}
+                \left(\frac{1 - x}{2}\right)^k
+
+    is the Legendre function of the first kind. Here :math:`(\cdot)_k`
+    is the Pochhammer symbol; see `poch`.
+
+    Parameters
+    ----------
+    m : array_like
+        Order (int or float). If passed a float not equal to an
+        integer the function returns NaN.
+    v : array_like
+        Degree (float).
+    x : array_like
+        Argument (float). Must have ``|x| <= 1``.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    pmv : scalar or ndarray
+        Value of the associated Legendre function.
+
+    See Also
+    --------
+    lpmn : Compute the associated Legendre function for all orders
+           ``0, ..., m`` and degrees ``0, ..., n``.
+    clpmn : Compute the associated Legendre function at complex
+            arguments.
+
+    Notes
+    -----
+    Note that this implementation includes the Condon-Shortley phase.
+
+    References
+    ----------
+    .. [1] Zhang, Jin, "Computation of Special Functions", John Wiley
+           and Sons, Inc, 1996.
+
+    """)
+
+add_newdoc("nbdtr",
+    r"""
+    nbdtr(k, n, p, out=None)
+
+    Negative binomial cumulative distribution function.
+
+    Returns the sum of the terms 0 through `k` of the negative binomial
+    distribution probability mass function,
+
+    .. math::
+
+        F = \sum_{j=0}^k {{n + j - 1}\choose{j}} p^n (1 - p)^j.
+
+    In a sequence of Bernoulli trials with individual success probabilities
+    `p`, this is the probability that `k` or fewer failures precede the nth
+    success.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    n : array_like
+        The target number of successes (positive int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The probability of `k` or fewer failures before `n` successes in a
+        sequence of events with individual success probability `p`.
+
+    See Also
+    --------
+    nbdtrc : Negative binomial survival function
+    nbdtrik : Negative binomial quantile function
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    If floating point values are passed for `k` or `n`, they will be truncated
+    to integers.
+
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{nbdtr}(k, n, p) = I_{p}(n, k + 1).
+
+    Wrapper for the Cephes [1]_ routine `nbdtr`.
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtr` directly can improve performance
+    compared to the ``cdf`` method of `scipy.stats.nbinom` (see last example).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtr
+    >>> nbdtr(10, 5, 0.5)
+    0.940765380859375
+
+    Compute the function for ``n=10`` and ``p=0.5`` at several points by
+    providing a NumPy array or list for `k`.
+
+    >>> nbdtr([5, 10, 15], 10, 0.5)
+    array([0.15087891, 0.58809853, 0.88523853])
+
+    Plot the function for four different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> k = np.arange(130)
+    >>> n_parameters = [20, 20, 20, 80]
+    >>> p_parameters = [0.2, 0.5, 0.8, 0.5]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(p_parameters, n_parameters,
+    ...                            linestyles))
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     p, n, style = parameter_set
+    ...     nbdtr_vals = nbdtr(k, n, p)
+    ...     ax.plot(k, nbdtr_vals, label=rf"$n={n},\, p={p}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$k$")
+    >>> ax.set_title("Negative binomial cumulative distribution function")
+    >>> plt.show()
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtr` directly can be much faster than
+    calling the ``cdf`` method of `scipy.stats.nbinom`, especially for small
+    arrays or individual values. To get the same results one must use the
+    following parametrization: ``nbinom(n, p).cdf(k)=nbdtr(k, n, p)``.
+
+    >>> from scipy.stats import nbinom
+    >>> k, n, p = 5, 3, 0.5
+    >>> nbdtr_res = nbdtr(k, n, p)  # this will often be faster than below
+    >>> stats_res = nbinom(n, p).cdf(k)
+    >>> stats_res, nbdtr_res  # test that results are equal
+    (0.85546875, 0.85546875)
+
+    `nbdtr` can evaluate different parameter sets by providing arrays with
+    shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute
+    the function for three different `k` at four locations `p`, resulting in
+    a 3x4 array.
+
+    >>> k = np.array([[5], [10], [15]])
+    >>> p = np.array([0.3, 0.5, 0.7, 0.9])
+    >>> k.shape, p.shape
+    ((3, 1), (4,))
+
+    >>> nbdtr(k, 5, p)
+    array([[0.15026833, 0.62304687, 0.95265101, 0.9998531 ],
+           [0.48450894, 0.94076538, 0.99932777, 0.99999999],
+           [0.76249222, 0.99409103, 0.99999445, 1.        ]])
+    """)
+
+add_newdoc("nbdtrc",
+    r"""
+    nbdtrc(k, n, p, out=None)
+
+    Negative binomial survival function.
+
+    Returns the sum of the terms `k + 1` to infinity of the negative binomial
+    distribution probability mass function,
+
+    .. math::
+
+        F = \sum_{j=k + 1}^\infty {{n + j - 1}\choose{j}} p^n (1 - p)^j.
+
+    In a sequence of Bernoulli trials with individual success probabilities
+    `p`, this is the probability that more than `k` failures precede the nth
+    success.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    n : array_like
+        The target number of successes (positive int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    F : scalar or ndarray
+        The probability of `k + 1` or more failures before `n` successes in a
+        sequence of events with individual success probability `p`.
+
+    See Also
+    --------
+    nbdtr : Negative binomial cumulative distribution function
+    nbdtrik : Negative binomial percentile function
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    If floating point values are passed for `k` or `n`, they will be truncated
+    to integers.
+
+    The terms are not summed directly; instead the regularized incomplete beta
+    function is employed, according to the formula,
+
+    .. math::
+        \mathrm{nbdtrc}(k, n, p) = I_{1 - p}(k + 1, n).
+
+    Wrapper for the Cephes [1]_ routine `nbdtrc`.
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtrc` directly can improve performance
+    compared to the ``sf`` method of `scipy.stats.nbinom` (see last example).
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtrc
+    >>> nbdtrc(10, 5, 0.5)
+    0.059234619140624986
+
+    Compute the function for ``n=10`` and ``p=0.5`` at several points by
+    providing a NumPy array or list for `k`.
+
+    >>> nbdtrc([5, 10, 15], 10, 0.5)
+    array([0.84912109, 0.41190147, 0.11476147])
+
+    Plot the function for four different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> k = np.arange(130)
+    >>> n_parameters = [20, 20, 20, 80]
+    >>> p_parameters = [0.2, 0.5, 0.8, 0.5]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(p_parameters, n_parameters,
+    ...                            linestyles))
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     p, n, style = parameter_set
+    ...     nbdtrc_vals = nbdtrc(k, n, p)
+    ...     ax.plot(k, nbdtrc_vals, label=rf"$n={n},\, p={p}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_xlabel("$k$")
+    >>> ax.set_title("Negative binomial distribution survival function")
+    >>> plt.show()
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtrc` directly can be much faster than
+    calling the ``sf`` method of `scipy.stats.nbinom`, especially for small
+    arrays or individual values. To get the same results one must use the
+    following parametrization: ``nbinom(n, p).sf(k)=nbdtrc(k, n, p)``.
+
+    >>> from scipy.stats import nbinom
+    >>> k, n, p = 3, 5, 0.5
+    >>> nbdtr_res = nbdtrc(k, n, p)  # this will often be faster than below
+    >>> stats_res = nbinom(n, p).sf(k)
+    >>> stats_res, nbdtr_res  # test that results are equal
+    (0.6367187499999999, 0.6367187499999999)
+
+    `nbdtrc` can evaluate different parameter sets by providing arrays with
+    shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute
+    the function for three different `k` at four locations `p`, resulting in
+    a 3x4 array.
+
+    >>> k = np.array([[5], [10], [15]])
+    >>> p = np.array([0.3, 0.5, 0.7, 0.9])
+    >>> k.shape, p.shape
+    ((3, 1), (4,))
+
+    >>> nbdtrc(k, 5, p)
+    array([[8.49731667e-01, 3.76953125e-01, 4.73489874e-02, 1.46902600e-04],
+           [5.15491059e-01, 5.92346191e-02, 6.72234070e-04, 9.29610100e-09],
+           [2.37507779e-01, 5.90896606e-03, 5.55025308e-06, 3.26346760e-13]])
+    """)
+
+add_newdoc(
+    "nbdtri",
+    r"""
+    nbdtri(k, n, y, out=None)
+
+    Returns the inverse with respect to the parameter `p` of
+    ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution
+    function.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    n : array_like
+        The target number of successes (positive int).
+    y : array_like
+        The probability of `k` or fewer failures before `n` successes (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    p : scalar or ndarray
+        Probability of success in a single event (float) such that
+        `nbdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    nbdtr : Cumulative distribution function of the negative binomial.
+    nbdtrc : Negative binomial survival function.
+    scipy.stats.nbinom : negative binomial distribution.
+    nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.
+    nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    Wrapper for the Cephes [1]_ routine `nbdtri`.
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. Using `nbdtri` directly can improve performance
+    compared to the ``ppf`` method of `scipy.stats.nbinom`.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    `nbdtri` is the inverse of `nbdtr` with respect to `p`.
+    Up to floating point errors the following holds:
+    ``nbdtri(k, n, nbdtr(k, n, p))=p``.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtri, nbdtr
+    >>> k, n, y = 5, 10, 0.2
+    >>> cdf_val = nbdtr(k, n, y)
+    >>> nbdtri(k, n, cdf_val)
+    0.20000000000000004
+
+    Compute the function for ``k=10`` and ``n=5`` at several points by
+    providing a NumPy array or list for `y`.
+
+    >>> y = np.array([0.1, 0.4, 0.8])
+    >>> nbdtri(3, 5, y)
+    array([0.34462319, 0.51653095, 0.69677416])
+
+    Plot the function for three different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> n_parameters = [5, 20, 30, 30]
+    >>> k_parameters = [20, 20, 60, 80]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(n_parameters, k_parameters, linestyles))
+    >>> cdf_vals = np.linspace(0, 1, 1000)
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     n, k, style = parameter_set
+    ...     nbdtri_vals = nbdtri(k, n, cdf_vals)
+    ...     ax.plot(cdf_vals, nbdtri_vals, label=rf"$k={k},\ n={n}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_ylabel("$p$")
+    >>> ax.set_xlabel("$CDF$")
+    >>> title = "nbdtri: inverse of negative binomial CDF with respect to $p$"
+    >>> ax.set_title(title)
+    >>> plt.show()
+
+    `nbdtri` can evaluate different parameter sets by providing arrays with
+    shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute
+    the function for three different `k` at four locations `p`, resulting in
+    a 3x4 array.
+
+    >>> k = np.array([[5], [10], [15]])
+    >>> y = np.array([0.3, 0.5, 0.7, 0.9])
+    >>> k.shape, y.shape
+    ((3, 1), (4,))
+
+    >>> nbdtri(k, 5, y)
+    array([[0.37258157, 0.45169416, 0.53249956, 0.64578407],
+           [0.24588501, 0.30451981, 0.36778453, 0.46397088],
+           [0.18362101, 0.22966758, 0.28054743, 0.36066188]])
+    """)
+
+add_newdoc("nbdtrik",
+    r"""
+    nbdtrik(y, n, p, out=None)
+
+    Negative binomial percentile function.
+
+    Returns the inverse with respect to the parameter `k` of
+    ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution
+    function.
+
+    Parameters
+    ----------
+    y : array_like
+        The probability of `k` or fewer failures before `n` successes (float).
+    n : array_like
+        The target number of successes (positive int).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    k : scalar or ndarray
+        The maximum number of allowed failures such that `nbdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    nbdtr : Cumulative distribution function of the negative binomial.
+    nbdtrc : Survival function of the negative binomial.
+    nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.
+    nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.
+    scipy.stats.nbinom : Negative binomial distribution
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.
+
+    Formula 26.5.26 of [2]_,
+
+    .. math::
+        \sum_{j=k + 1}^\infty {{n + j - 1}
+        \choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),
+
+    is used to reduce calculation of the cumulative distribution function to
+    that of a regularized incomplete beta :math:`I`.
+
+    Computation of `k` involves a search for a value that produces the desired
+    value of `y`.  The search relies on the monotonicity of `y` with `k`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Compute the negative binomial cumulative distribution function for an
+    exemplary parameter set.
+
+    >>> import numpy as np
+    >>> from scipy.special import nbdtr, nbdtrik
+    >>> k, n, p = 5, 2, 0.5
+    >>> cdf_value = nbdtr(k, n, p)
+    >>> cdf_value
+    0.9375
+
+    Verify that `nbdtrik` recovers the original value for `k`.
+
+    >>> nbdtrik(cdf_value, n, p)
+    5.0
+
+    Plot the function for different parameter sets.
+
+    >>> import matplotlib.pyplot as plt
+    >>> p_parameters = [0.2, 0.5, 0.7, 0.5]
+    >>> n_parameters = [30, 30, 30, 80]
+    >>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']
+    >>> parameters_list = list(zip(p_parameters, n_parameters, linestyles))
+    >>> cdf_vals = np.linspace(0, 1, 1000)
+    >>> fig, ax = plt.subplots(figsize=(8, 8))
+    >>> for parameter_set in parameters_list:
+    ...     p, n, style = parameter_set
+    ...     nbdtrik_vals = nbdtrik(cdf_vals, n, p)
+    ...     ax.plot(cdf_vals, nbdtrik_vals, label=rf"$n={n},\ p={p}$",
+    ...             ls=style)
+    >>> ax.legend()
+    >>> ax.set_ylabel("$k$")
+    >>> ax.set_xlabel("$CDF$")
+    >>> ax.set_title("Negative binomial percentile function")
+    >>> plt.show()
+
+    The negative binomial distribution is also available as
+    `scipy.stats.nbinom`. The percentile function  method ``ppf``
+    returns the result of `nbdtrik` rounded up to integers:
+
+    >>> from scipy.stats import nbinom
+    >>> q, n, p = 0.6, 5, 0.5
+    >>> nbinom.ppf(q, n, p), nbdtrik(q, n, p)
+    (5.0, 4.800428460273882)
+
+    """)
+
+add_newdoc("nbdtrin",
+    r"""
+    nbdtrin(k, y, p, out=None)
+
+    Inverse of `nbdtr` vs `n`.
+
+    Returns the inverse with respect to the parameter `n` of
+    ``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution
+    function.
+
+    Parameters
+    ----------
+    k : array_like
+        The maximum number of allowed failures (nonnegative int).
+    y : array_like
+        The probability of `k` or fewer failures before `n` successes (float).
+    p : array_like
+        Probability of success in a single event (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    n : scalar or ndarray
+        The number of successes `n` such that `nbdtr(k, n, p) = y`.
+
+    See Also
+    --------
+    nbdtr : Cumulative distribution function of the negative binomial.
+    nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.
+    nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.
+
+    Notes
+    -----
+    Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.
+
+    Formula 26.5.26 of [2]_,
+
+    .. math::
+        \sum_{j=k + 1}^\infty {{n + j - 1}
+        \choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),
+
+    is used to reduce calculation of the cumulative distribution function to
+    that of a regularized incomplete beta :math:`I`.
+
+    Computation of `n` involves a search for a value that produces the desired
+    value of `y`.  The search relies on the monotonicity of `y` with `n`.
+
+    References
+    ----------
+    .. [1] Barry Brown, James Lovato, and Kathy Russell,
+           CDFLIB: Library of Fortran Routines for Cumulative Distribution
+           Functions, Inverses, and Other Parameters.
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Compute the negative binomial cumulative distribution function for an
+    exemplary parameter set.
+
+    >>> from scipy.special import nbdtr, nbdtrin
+    >>> k, n, p = 5, 2, 0.5
+    >>> cdf_value = nbdtr(k, n, p)
+    >>> cdf_value
+    0.9375
+
+    Verify that `nbdtrin` recovers the original value for `n` up to floating
+    point accuracy.
+
+    >>> nbdtrin(k, cdf_value, p)
+    1.999999999998137
+    """)
+
+add_newdoc("ncfdtr",
+    r"""
+    ncfdtr(dfn, dfd, nc, f, out=None)
+
+    Cumulative distribution function of the non-central F distribution.
+
+    The non-central F describes the distribution of,
+
+    .. math::
+        Z = \frac{X/d_n}{Y/d_d}
+
+    where :math:`X` and :math:`Y` are independently distributed, with
+    :math:`X` distributed non-central :math:`\chi^2` with noncentrality
+    parameter `nc` and :math:`d_n` degrees of freedom, and :math:`Y`
+    distributed :math:`\chi^2` with :math:`d_d` degrees of freedom.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares.  Range (0, inf).
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares.  Range (0, inf).
+    nc : array_like
+        Noncentrality parameter.  Range [0, inf).
+    f : array_like
+        Quantiles, i.e. the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    cdf : scalar or ndarray
+        The calculated CDF.  If all inputs are scalar, the return will be a
+        float.  Otherwise it will be an array.
+
+    See Also
+    --------
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+    scipy.stats.ncf : Non-central F distribution.
+
+    Notes
+    -----
+    This function calculates the CDF of the non-central f distribution using
+    the Boost Math C++ library [1]_.
+
+    The cumulative distribution function is computed using Formula 26.6.20 of
+    [2]_:
+
+    .. math::
+        F(d_n, d_d, n_c, f) = \sum_{j=0}^\infty e^{-n_c/2}
+        \frac{(n_c/2)^j}{j!} I_{x}(\frac{d_n}{2} + j, \frac{d_d}{2}),
+
+    where :math:`I` is the regularized incomplete beta function, and
+    :math:`x = f d_n/(f d_n + d_d)`.
+
+    Note that argument order of `ncfdtr` is different from that of the
+    similar ``cdf`` method of `scipy.stats.ncf`: `f` is the last
+    parameter of `ncfdtr` but the first parameter of ``scipy.stats.ncf.cdf``.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+    .. [2] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Plot the CDF of the non-central F distribution, for nc=0.  Compare with the
+    F-distribution from scipy.stats:
+
+    >>> x = np.linspace(-1, 8, num=500)
+    >>> dfn = 3
+    >>> dfd = 2
+    >>> ncf_stats = stats.f.cdf(x, dfn, dfd)
+    >>> ncf_special = special.ncfdtr(dfn, dfd, 0, x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, ncf_stats, 'b-', lw=3)
+    >>> ax.plot(x, ncf_special, 'r-')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("ncfdtri",
+    """
+    ncfdtri(dfn, dfd, nc, p, out=None)
+
+    Inverse with respect to `f` of the CDF of the non-central F distribution.
+
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares.  Range (0, inf).
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares.  Range (0, inf).
+    nc : array_like
+        Noncentrality parameter.  Range [0, inf).
+    p : array_like
+        Value of the cumulative distribution function.  Must be in the
+        range [0, 1].
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    f : scalar or ndarray
+        Quantiles, i.e., the upper limit of integration.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+    scipy.stats.ncf : Non-central F distribution.
+
+    Notes
+    -----
+    This function calculates the Quantile of the non-central f distribution
+    using the Boost Math C++ library [1]_.
+
+    Note that argument order of `ncfdtri` is different from that of the
+    similar ``ppf`` method of `scipy.stats.ncf`. `p` is the last parameter
+    of `ncfdtri` but the first parameter of ``scipy.stats.ncf.ppf``.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtri
+
+    Compute the CDF for several values of `f`:
+
+    >>> f = [0.5, 1, 1.5]
+    >>> p = ncfdtr(2, 3, 1.5, f)
+    >>> p
+    array([ 0.20782291,  0.36107392,  0.47345752])
+
+    Compute the inverse.  We recover the values of `f`, as expected:
+
+    >>> ncfdtri(2, 3, 1.5, p)
+    array([ 0.5,  1. ,  1.5])
+
+    """)
+
+add_newdoc("ncfdtridfd",
+    """
+    ncfdtridfd(dfn, p, nc, f, out=None)
+
+    Calculate degrees of freedom (denominator) for the noncentral F-distribution.
+
+    This is the inverse with respect to `dfd` of `ncfdtr`.
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares.  Range (0, inf).
+    p : array_like
+        Value of the cumulative distribution function.  Must be in the
+        range [0, 1].
+    nc : array_like
+        Noncentrality parameter.  Should be in range (0, 1e4).
+    f : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    dfd : scalar or ndarray
+        Degrees of freedom of the denominator sum of squares.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+
+    Notes
+    -----
+    The value of the cumulative noncentral F distribution is not necessarily
+    monotone in either degrees of freedom. There thus may be two values that
+    provide a given CDF value. This routine assumes monotonicity and will
+    find an arbitrary one of the two values.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtridfd
+
+    Compute the CDF for several values of `dfd`:
+
+    >>> dfd = [1, 2, 3]
+    >>> p = ncfdtr(2, dfd, 0.25, 15)
+    >>> p
+    array([ 0.8097138 ,  0.93020416,  0.96787852])
+
+    Compute the inverse.  We recover the values of `dfd`, as expected:
+
+    >>> ncfdtridfd(2, p, 0.25, 15)
+    array([ 1.,  2.,  3.])
+
+    """)
+
+add_newdoc("ncfdtridfn",
+    """
+    ncfdtridfn(p, dfd, nc, f, out=None)
+
+    Calculate degrees of freedom (numerator) for the noncentral F-distribution.
+
+    This is the inverse with respect to `dfn` of `ncfdtr`.
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    p : array_like
+        Value of the cumulative distribution function. Must be in the
+        range [0, 1].
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares. Range (0, inf).
+    nc : array_like
+        Noncentrality parameter.  Should be in range (0, 1e4).
+    f : float
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    dfn : scalar or ndarray
+        Degrees of freedom of the numerator sum of squares.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.
+
+    Notes
+    -----
+    The value of the cumulative noncentral F distribution is not necessarily
+    monotone in either degrees of freedom. There thus may be two values that
+    provide a given CDF value. This routine assumes monotonicity and will
+    find an arbitrary one of the two values.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtridfn
+
+    Compute the CDF for several values of `dfn`:
+
+    >>> dfn = [1, 2, 3]
+    >>> p = ncfdtr(dfn, 2, 0.25, 15)
+    >>> p
+    array([ 0.92562363,  0.93020416,  0.93188394])
+
+    Compute the inverse. We recover the values of `dfn`, as expected:
+
+    >>> ncfdtridfn(p, 2, 0.25, 15)
+    array([ 1.,  2.,  3.])
+
+    """)
+
+add_newdoc("ncfdtrinc",
+    """
+    ncfdtrinc(dfn, dfd, p, f, out=None)
+
+    Calculate non-centrality parameter for non-central F distribution.
+
+    This is the inverse with respect to `nc` of `ncfdtr`.
+    See `ncfdtr` for more details.
+
+    Parameters
+    ----------
+    dfn : array_like
+        Degrees of freedom of the numerator sum of squares. Range (0, inf).
+    dfd : array_like
+        Degrees of freedom of the denominator sum of squares. Range (0, inf).
+    p : array_like
+        Value of the cumulative distribution function. Must be in the
+        range [0, 1].
+    f : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    nc : scalar or ndarray
+        Noncentrality parameter.
+
+    See Also
+    --------
+    ncfdtr : CDF of the non-central F distribution.
+    ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.
+    ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.
+    ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.
+
+    Examples
+    --------
+    >>> from scipy.special import ncfdtr, ncfdtrinc
+
+    Compute the CDF for several values of `nc`:
+
+    >>> nc = [0.5, 1.5, 2.0]
+    >>> p = ncfdtr(2, 3, nc, 15)
+    >>> p
+    array([ 0.96309246,  0.94327955,  0.93304098])
+
+    Compute the inverse. We recover the values of `nc`, as expected:
+
+    >>> ncfdtrinc(2, 3, p, 15)
+    array([ 0.5,  1.5,  2. ])
+
+    """)
+
+add_newdoc("nctdtr",
+    """
+    nctdtr(df, nc, t, out=None)
+
+    Cumulative distribution function of the non-central `t` distribution.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution. Should be in range (0, inf).
+    nc : array_like
+        Noncentrality parameter.
+    t : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    cdf : scalar or ndarray
+        The calculated CDF. If all inputs are scalar, the return will be a
+        float. Otherwise, it will be an array.
+
+    See Also
+    --------
+    nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.
+    nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.
+    nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.
+
+    Notes
+    -----
+    This function calculates the CDF of the non-central t distribution using
+    the Boost Math C++ library [1]_.
+
+    Note that the argument order of `nctdtr` is different from that of the
+    similar ``cdf`` method of `scipy.stats.nct`: `t` is the last
+    parameter of `nctdtr` but the first parameter of ``scipy.stats.nct.cdf``.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Plot the CDF of the non-central t distribution, for nc=0. Compare with the
+    t-distribution from scipy.stats:
+
+    >>> x = np.linspace(-5, 5, num=500)
+    >>> df = 3
+    >>> nct_stats = stats.t.cdf(x, df)
+    >>> nct_special = special.nctdtr(df, 0, x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, nct_stats, 'b-', lw=3)
+    >>> ax.plot(x, nct_special, 'r-')
+    >>> plt.show()
+
+    """)
+
+add_newdoc("nctdtridf",
+    """
+    nctdtridf(p, nc, t, out=None)
+
+    Calculate degrees of freedom for non-central t distribution.
+
+    See `nctdtr` for more details.
+
+    Parameters
+    ----------
+    p : array_like
+        CDF values, in range (0, 1].
+    nc : array_like
+        Noncentrality parameter. Should be in range (-1e6, 1e6).
+    t : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    df : scalar or ndarray
+        The degrees of freedom. If all inputs are scalar, the return will be a
+        float. Otherwise, it will be an array.
+
+    See Also
+    --------
+    nctdtr :  CDF of the non-central `t` distribution.
+    nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.
+    nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.
+
+    Examples
+    --------
+    >>> from scipy.special import nctdtr, nctdtridf
+
+    Compute the CDF for several values of `df`:
+
+    >>> df = [1, 2, 3]
+    >>> p = nctdtr(df, 0.25, 1)
+    >>> p
+    array([0.67491974, 0.716464  , 0.73349456])
+
+    Compute the inverse. We recover the values of `df`, as expected:
+
+    >>> nctdtridf(p, 0.25, 1)
+    array([1., 2., 3.])
+
+    """)
+
+add_newdoc("nctdtrinc",
+    """
+    nctdtrinc(df, p, t, out=None)
+
+    Calculate non-centrality parameter for non-central t distribution.
+
+    See `nctdtr` for more details.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution. Should be in range (0, inf).
+    p : array_like
+        CDF values, in range (0, 1].
+    t : array_like
+        Quantiles, i.e., the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    nc : scalar or ndarray
+        Noncentrality parameter
+
+    See Also
+    --------
+    nctdtr :  CDF of the non-central `t` distribution.
+    nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.
+    nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.
+
+    Examples
+    --------
+    >>> from scipy.special import nctdtr, nctdtrinc
+
+    Compute the CDF for several values of `nc`:
+
+    >>> nc = [0.5, 1.5, 2.5]
+    >>> p = nctdtr(3, nc, 1.5)
+    >>> p
+    array([0.77569497, 0.45524533, 0.1668691 ])
+
+    Compute the inverse. We recover the values of `nc`, as expected:
+
+    >>> nctdtrinc(3, p, 1.5)
+    array([0.5, 1.5, 2.5])
+
+    """)
+
+add_newdoc("nctdtrit",
+    """
+    nctdtrit(df, nc, p, out=None)
+
+    Inverse cumulative distribution function of the non-central t distribution.
+
+    See `nctdtr` for more details.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution. Should be in range (0, inf).
+    nc : array_like
+        Noncentrality parameter. Should be in range (-1e6, 1e6).
+    p : array_like
+        CDF values, in range (0, 1].
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    t : scalar or ndarray
+        Quantiles
+
+    See Also
+    --------
+    nctdtr :  CDF of the non-central `t` distribution.
+    nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.
+    nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.
+
+    Examples
+    --------
+    >>> from scipy.special import nctdtr, nctdtrit
+
+    Compute the CDF for several values of `t`:
+
+    >>> t = [0.5, 1, 1.5]
+    >>> p = nctdtr(3, 1, t)
+    >>> p
+    array([0.29811049, 0.46922687, 0.6257559 ])
+
+    Compute the inverse. We recover the values of `t`, as expected:
+
+    >>> nctdtrit(3, 1, p)
+    array([0.5, 1. , 1.5])
+
+    """)
+
+add_newdoc("ndtr",
+    r"""
+    ndtr(x, out=None)
+
+    Cumulative distribution of the standard normal distribution.
+
+    Returns the area under the standard Gaussian probability
+    density function, integrated from minus infinity to `x`
+
+    .. math::
+
+       \frac{1}{\sqrt{2\pi}} \int_{-\infty}^x \exp(-t^2/2) dt
+
+    Parameters
+    ----------
+    x : array_like, real or complex
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the normal CDF evaluated at `x`
+
+    See Also
+    --------
+    log_ndtr : Logarithm of ndtr
+    ndtri : Inverse of ndtr, standard normal percentile function
+    erf : Error function
+    erfc : 1 - erf
+    scipy.stats.norm : Normal distribution
+
+    Examples
+    --------
+    Evaluate `ndtr` at one point.
+
+    >>> import numpy as np
+    >>> from scipy.special import ndtr
+    >>> ndtr(0.5)
+    0.6914624612740131
+
+    Evaluate the function at several points by providing a NumPy array
+    or list for `x`.
+
+    >>> ndtr([0, 0.5, 2])
+    array([0.5       , 0.69146246, 0.97724987])
+
+    Plot the function.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-5, 5, 100)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, ndtr(x))
+    >>> ax.set_title(r"Standard normal cumulative distribution function $\Phi$")
+    >>> plt.show()
+    """)
+
+
+add_newdoc("nrdtrimn",
+    """
+    nrdtrimn(p, std, x, out=None)
+
+    Calculate mean of normal distribution given other params.
+
+    Parameters
+    ----------
+    p : array_like
+        CDF values, in range (0, 1].
+    std : array_like
+        Standard deviation.
+    x : array_like
+        Quantiles, i.e. the upper limit of integration.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    mn : scalar or ndarray
+        The mean of the normal distribution.
+
+    See Also
+    --------
+    scipy.stats.norm : Normal distribution
+    ndtr : Standard normal cumulative probability distribution
+    ndtri : Inverse of standard normal CDF with respect to quantile
+    nrdtrisd : Inverse of normal distribution CDF with respect to
+               standard deviation
+
+    Examples
+    --------
+    `nrdtrimn` can be used to recover the mean of a normal distribution
+    if we know the CDF value `p` for a given quantile `x` and the
+    standard deviation `std`. First, we calculate
+    the normal distribution CDF for an exemplary parameter set.
+
+    >>> from scipy.stats import norm
+    >>> mean = 3.
+    >>> std = 2.
+    >>> x = 6.
+    >>> p = norm.cdf(x, loc=mean, scale=std)
+    >>> p
+    0.9331927987311419
+
+    Verify that `nrdtrimn` returns the original value for `mean`.
+
+    >>> from scipy.special import nrdtrimn
+    >>> nrdtrimn(p, std, x)
+    3.0000000000000004
+
+    """)
+
+add_newdoc("nrdtrisd",
+    """
+    nrdtrisd(mn, p, x, out=None)
+
+    Calculate standard deviation of normal distribution given other params.
+
+    Parameters
+    ----------
+    mn : scalar or ndarray
+        The mean of the normal distribution.
+    p : array_like
+        CDF values, in range (0, 1].
+    x : array_like
+        Quantiles, i.e. the upper limit of integration.
+
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    std : scalar or ndarray
+        Standard deviation.
+
+    See Also
+    --------
+    scipy.stats.norm : Normal distribution
+    ndtr : Standard normal cumulative probability distribution
+    ndtri : Inverse of standard normal CDF with respect to quantile
+    nrdtrimn : Inverse of normal distribution CDF with respect to
+               mean
+
+    Examples
+    --------
+    `nrdtrisd` can be used to recover the standard deviation of a normal
+    distribution if we know the CDF value `p` for a given quantile `x` and
+    the mean `mn`. First, we calculate the normal distribution CDF for an
+    exemplary parameter set.
+
+    >>> from scipy.stats import norm
+    >>> mean = 3.
+    >>> std = 2.
+    >>> x = 6.
+    >>> p = norm.cdf(x, loc=mean, scale=std)
+    >>> p
+    0.9331927987311419
+
+    Verify that `nrdtrisd` returns the original value for `std`.
+
+    >>> from scipy.special import nrdtrisd
+    >>> nrdtrisd(mean, p, x)
+    2.0000000000000004
+
+    """)
+
+add_newdoc("log_ndtr",
+    """
+    log_ndtr(x, out=None)
+
+    Logarithm of Gaussian cumulative distribution function.
+
+    Returns the log of the area under the standard Gaussian probability
+    density function, integrated from minus infinity to `x`::
+
+        log(1/sqrt(2*pi) * integral(exp(-t**2 / 2), t=-inf..x))
+
+    Parameters
+    ----------
+    x : array_like, real or complex
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the log of the normal CDF evaluated at `x`
+
+    See Also
+    --------
+    erf
+    erfc
+    scipy.stats.norm
+    ndtr
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import log_ndtr, ndtr
+
+    The benefit of ``log_ndtr(x)`` over the naive implementation
+    ``np.log(ndtr(x))`` is most evident with moderate to large positive
+    values of ``x``:
+
+    >>> x = np.array([6, 7, 9, 12, 15, 25])
+    >>> log_ndtr(x)
+    array([-9.86587646e-010, -1.27981254e-012, -1.12858841e-019,
+           -1.77648211e-033, -3.67096620e-051, -3.05669671e-138])
+
+    The results of the naive calculation for the moderate ``x`` values
+    have only 5 or 6 correct significant digits. For values of ``x``
+    greater than approximately 8.3, the naive expression returns 0:
+
+    >>> np.log(ndtr(x))
+    array([-9.86587701e-10, -1.27986510e-12,  0.00000000e+00,
+            0.00000000e+00,  0.00000000e+00,  0.00000000e+00])
+    """)
+
+add_newdoc("ndtri",
+    """
+    ndtri(y, out=None)
+
+    Inverse of `ndtr` vs x
+
+    Returns the argument x for which the area under the standard normal
+    probability density function (integrated from minus infinity to `x`)
+    is equal to y.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    x : scalar or ndarray
+        Value of x such that ``ndtr(x) == p``.
+
+    See Also
+    --------
+    ndtr : Standard normal cumulative probability distribution
+    ndtri_exp : Inverse of log_ndtr
+
+    Examples
+    --------
+    `ndtri` is the percentile function of the standard normal distribution.
+    This means it returns the inverse of the cumulative density `ndtr`. First,
+    let us compute a cumulative density value.
+
+    >>> import numpy as np
+    >>> from scipy.special import ndtri, ndtr
+    >>> cdf_val = ndtr(2)
+    >>> cdf_val
+    0.9772498680518208
+
+    Verify that `ndtri` yields the original value for `x` up to floating point
+    errors.
+
+    >>> ndtri(cdf_val)
+    2.0000000000000004
+
+    Plot the function. For that purpose, we provide a NumPy array as argument.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0.01, 1, 200)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, ndtri(x))
+    >>> ax.set_title("Standard normal percentile function")
+    >>> plt.show()
+    """)
+
+add_newdoc("pdtr",
+    r"""
+    pdtr(k, m, out=None)
+
+    Poisson cumulative distribution function.
+
+    Defined as the probability that a Poisson-distributed random
+    variable with event rate :math:`m` is less than or equal to
+    :math:`k`. More concretely, this works out to be [1]_
+
+    .. math::
+
+       \exp(-m) \sum_{j = 0}^{\lfloor{k}\rfloor} \frac{m^j}{j!}.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of occurrences (nonnegative, real)
+    m : array_like
+        Shape parameter (nonnegative, real)
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Poisson cumulative distribution function
+
+    See Also
+    --------
+    pdtrc : Poisson survival function
+    pdtrik : inverse of `pdtr` with respect to `k`
+    pdtri : inverse of `pdtr` with respect to `m`
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Poisson_distribution
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is a cumulative distribution function, so it converges to 1
+    monotonically as `k` goes to infinity.
+
+    >>> sc.pdtr([1, 10, 100, np.inf], 1)
+    array([0.73575888, 0.99999999, 1.        , 1.        ])
+
+    It is discontinuous at integers and constant between integers.
+
+    >>> sc.pdtr([1, 1.5, 1.9, 2], 1)
+    array([0.73575888, 0.73575888, 0.73575888, 0.9196986 ])
+
+    """)
+
+add_newdoc("pdtrc",
+    """
+    pdtrc(k, m, out=None)
+
+    Poisson survival function
+
+    Returns the sum of the terms from k+1 to infinity of the Poisson
+    distribution: sum(exp(-m) * m**j / j!, j=k+1..inf) = gammainc(
+    k+1, m). Arguments must both be non-negative doubles.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of occurrences (nonnegative, real)
+    m : array_like
+        Shape parameter (nonnegative, real)
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the Poisson survival function
+
+    See Also
+    --------
+    pdtr : Poisson cumulative distribution function
+    pdtrik : inverse of `pdtr` with respect to `k`
+    pdtri : inverse of `pdtr` with respect to `m`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    It is a survival function, so it decreases to 0
+    monotonically as `k` goes to infinity.
+
+    >>> k = np.array([1, 10, 100, np.inf])
+    >>> sc.pdtrc(k, 1)
+    array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])
+
+    It can be expressed in terms of the lower incomplete gamma
+    function `gammainc`.
+
+    >>> sc.gammainc(k + 1, 1)
+    array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])
+
+    """)
+
+add_newdoc("pdtri",
+    """
+    pdtri(k, y, out=None)
+
+    Inverse to `pdtr` vs m
+
+    Returns the Poisson variable `m` such that the sum from 0 to `k` of
+    the Poisson density is equal to the given probability `y`:
+    calculated by ``gammaincinv(k + 1, y)``. `k` must be a nonnegative
+    integer and `y` between 0 and 1.
+
+    Parameters
+    ----------
+    k : array_like
+        Number of occurrences (nonnegative, real)
+    y : array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the shape parameter `m` such that ``pdtr(k, m) = p``
+
+    See Also
+    --------
+    pdtr : Poisson cumulative distribution function
+    pdtrc : Poisson survival function
+    pdtrik : inverse of `pdtr` with respect to `k`
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    Compute the CDF for several values of `m`:
+
+    >>> m = [0.5, 1, 1.5]
+    >>> p = sc.pdtr(1, m)
+    >>> p
+    array([0.90979599, 0.73575888, 0.5578254 ])
+
+    Compute the inverse. We recover the values of `m`, as expected:
+
+    >>> sc.pdtri(1, p)
+    array([0.5, 1. , 1.5])
+
+    """)
+
+add_newdoc("pdtrik",
+    """
+    pdtrik(p, m, out=None)
+
+    Inverse to `pdtr` vs `k`.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability
+    m : array_like
+        Shape parameter (nonnegative, real)
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The number of occurrences `k` such that ``pdtr(k, m) = p``
+
+    See Also
+    --------
+    pdtr : Poisson cumulative distribution function
+    pdtrc : Poisson survival function
+    pdtri : inverse of `pdtr` with respect to `m`
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    Compute the CDF for several values of `k`:
+
+    >>> k = [1, 2, 3]
+    >>> p = sc.pdtr(k, 2)
+    >>> p
+    array([0.40600585, 0.67667642, 0.85712346])
+
+    Compute the inverse. We recover the values of `k`, as expected:
+
+    >>> sc.pdtrik(p, 2)
+    array([1., 2., 3.])
+
+    """)
+
+add_newdoc("poch",
+    r"""
+    poch(z, m, out=None)
+
+    Pochhammer symbol.
+
+    The Pochhammer symbol (rising factorial) is defined as
+
+    .. math::
+
+        (z)_m = \frac{\Gamma(z + m)}{\Gamma(z)}
+
+    For positive integer `m` it reads
+
+    .. math::
+
+        (z)_m = z (z + 1) ... (z + m - 1)
+
+    See [dlmf]_ for more details.
+
+    Parameters
+    ----------
+    z, m : array_like
+        Real-valued arguments.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value of the function.
+
+    References
+    ----------
+    .. [dlmf] Nist, Digital Library of Mathematical Functions
+        https://dlmf.nist.gov/5.2#iii
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It is 1 when m is 0.
+
+    >>> sc.poch([1, 2, 3, 4], 0)
+    array([1., 1., 1., 1.])
+
+    For z equal to 1 it reduces to the factorial function.
+
+    >>> sc.poch(1, 5)
+    120.0
+    >>> 1 * 2 * 3 * 4 * 5
+    120
+
+    It can be expressed in terms of the gamma function.
+
+    >>> z, m = 3.7, 2.1
+    >>> sc.poch(z, m)
+    20.529581933776953
+    >>> sc.gamma(z + m) / sc.gamma(z)
+    20.52958193377696
+
+    """)
+
+add_newdoc("powm1", """
+    powm1(x, y, out=None)
+
+    Computes ``x**y - 1``.
+
+    This function is useful when `y` is near 0, or when `x` is near 1.
+
+    The function is implemented for real types only (unlike ``numpy.power``,
+    which accepts complex inputs).
+
+    Parameters
+    ----------
+    x : array_like
+        The base. Must be a real type (i.e. integer or float, not complex).
+    y : array_like
+        The exponent. Must be a real type (i.e. integer or float, not complex).
+
+    Returns
+    -------
+    array_like
+        Result of the calculation
+
+    Notes
+    -----
+    .. versionadded:: 1.10.0
+
+    The underlying code is implemented for single precision and double
+    precision floats only.  Unlike `numpy.power`, integer inputs to
+    `powm1` are converted to floating point, and complex inputs are
+    not accepted.
+
+    Note the following edge cases:
+
+    * ``powm1(x, 0)`` returns 0 for any ``x``, including 0, ``inf``
+      and ``nan``.
+    * ``powm1(1, y)`` returns 0 for any ``y``, including ``nan``
+      and ``inf``.
+
+    This function wraps the ``powm1`` routine from the
+    Boost Math C++ library [1]_.
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import powm1
+
+    >>> x = np.array([1.2, 10.0, 0.9999999975])
+    >>> y = np.array([1e-9, 1e-11, 0.1875])
+    >>> powm1(x, y)
+    array([ 1.82321557e-10,  2.30258509e-11, -4.68749998e-10])
+
+    It can be verified that the relative errors in those results
+    are less than 2.5e-16.
+
+    Compare that to the result of ``x**y - 1``, where the
+    relative errors are all larger than 8e-8:
+
+    >>> x**y - 1
+    array([ 1.82321491e-10,  2.30258035e-11, -4.68750039e-10])
+
+    """)
+
+
+add_newdoc("pseudo_huber",
+    r"""
+    pseudo_huber(delta, r, out=None)
+
+    Pseudo-Huber loss function.
+
+    .. math:: \mathrm{pseudo\_huber}(\delta, r) =
+              \delta^2 \left( \sqrt{ 1 + \left( \frac{r}{\delta} \right)^2 } - 1 \right)
+
+    Parameters
+    ----------
+    delta : array_like
+        Input array, indicating the soft quadratic vs. linear loss changepoint.
+    r : array_like
+        Input array, possibly representing residuals.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    res : scalar or ndarray
+        The computed Pseudo-Huber loss function values.
+
+    See Also
+    --------
+    huber: Similar function which this function approximates
+
+    Notes
+    -----
+    Like `huber`, `pseudo_huber` often serves as a robust loss function
+    in statistics or machine learning to reduce the influence of outliers.
+    Unlike `huber`, `pseudo_huber` is smooth.
+
+    Typically, `r` represents residuals, the difference
+    between a model prediction and data. Then, for :math:`|r|\leq\delta`,
+    `pseudo_huber` resembles the squared error and for :math:`|r|>\delta` the
+    absolute error. This way, the Pseudo-Huber loss often achieves
+    a fast convergence in model fitting for small residuals like the squared
+    error loss function and still reduces the influence of outliers
+    (:math:`|r|>\delta`) like the absolute error loss. As :math:`\delta` is
+    the cutoff between squared and absolute error regimes, it has
+    to be tuned carefully for each problem. `pseudo_huber` is also
+    convex, making it suitable for gradient based optimization. [1]_ [2]_
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Hartley, Zisserman, "Multiple View Geometry in Computer Vision".
+           2003. Cambridge University Press. p. 619
+    .. [2] Charbonnier et al. "Deterministic edge-preserving regularization
+           in computed imaging". 1997. IEEE Trans. Image Processing.
+           6 (2): 298 - 311.
+
+    Examples
+    --------
+    Import all necessary modules.
+
+    >>> import numpy as np
+    >>> from scipy.special import pseudo_huber, huber
+    >>> import matplotlib.pyplot as plt
+
+    Calculate the function for ``delta=1`` at ``r=2``.
+
+    >>> pseudo_huber(1., 2.)
+    1.2360679774997898
+
+    Calculate the function at ``r=2`` for different `delta` by providing
+    a list or NumPy array for `delta`.
+
+    >>> pseudo_huber([1., 2., 4.], 3.)
+    array([2.16227766, 3.21110255, 4.        ])
+
+    Calculate the function for ``delta=1`` at several points by providing
+    a list or NumPy array for `r`.
+
+    >>> pseudo_huber(2., np.array([1., 1.5, 3., 4.]))
+    array([0.47213595, 1.        , 3.21110255, 4.94427191])
+
+    The function can be calculated for different `delta` and `r` by
+    providing arrays for both with compatible shapes for broadcasting.
+
+    >>> r = np.array([1., 2.5, 8., 10.])
+    >>> deltas = np.array([[1.], [5.], [9.]])
+    >>> print(r.shape, deltas.shape)
+    (4,) (3, 1)
+
+    >>> pseudo_huber(deltas, r)
+    array([[ 0.41421356,  1.6925824 ,  7.06225775,  9.04987562],
+           [ 0.49509757,  2.95084972, 22.16990566, 30.90169944],
+           [ 0.49846624,  3.06693762, 27.37435121, 40.08261642]])
+
+    Plot the function for different `delta`.
+
+    >>> x = np.linspace(-4, 4, 500)
+    >>> deltas = [1, 2, 3]
+    >>> linestyles = ["dashed", "dotted", "dashdot"]
+    >>> fig, ax = plt.subplots()
+    >>> combined_plot_parameters = list(zip(deltas, linestyles))
+    >>> for delta, style in combined_plot_parameters:
+    ...     ax.plot(x, pseudo_huber(delta, x), label=rf"$\delta={delta}$",
+    ...             ls=style)
+    >>> ax.legend(loc="upper center")
+    >>> ax.set_xlabel("$x$")
+    >>> ax.set_title(r"Pseudo-Huber loss function $h_{\delta}(x)$")
+    >>> ax.set_xlim(-4, 4)
+    >>> ax.set_ylim(0, 8)
+    >>> plt.show()
+
+    Finally, illustrate the difference between `huber` and `pseudo_huber` by
+    plotting them and their gradients with respect to `r`. The plot shows
+    that `pseudo_huber` is continuously differentiable while `huber` is not
+    at the points :math:`\pm\delta`.
+
+    >>> def huber_grad(delta, x):
+    ...     grad = np.copy(x)
+    ...     linear_area = np.argwhere(np.abs(x) > delta)
+    ...     grad[linear_area]=delta*np.sign(x[linear_area])
+    ...     return grad
+    >>> def pseudo_huber_grad(delta, x):
+    ...     return x* (1+(x/delta)**2)**(-0.5)
+    >>> x=np.linspace(-3, 3, 500)
+    >>> delta = 1.
+    >>> fig, ax = plt.subplots(figsize=(7, 7))
+    >>> ax.plot(x, huber(delta, x), label="Huber", ls="dashed")
+    >>> ax.plot(x, huber_grad(delta, x), label="Huber Gradient", ls="dashdot")
+    >>> ax.plot(x, pseudo_huber(delta, x), label="Pseudo-Huber", ls="dotted")
+    >>> ax.plot(x, pseudo_huber_grad(delta, x), label="Pseudo-Huber Gradient",
+    ...         ls="solid")
+    >>> ax.legend(loc="upper center")
+    >>> plt.show()
+    """)
+
+add_newdoc("rel_entr",
+    r"""
+    rel_entr(x, y, out=None)
+
+    Elementwise function for computing relative entropy.
+
+    .. math::
+
+        \mathrm{rel\_entr}(x, y) =
+            \begin{cases}
+                x \log(x / y) & x > 0, y > 0 \\
+                0 & x = 0, y \ge 0 \\
+                \infty & \text{otherwise}
+            \end{cases}
+
+    Parameters
+    ----------
+    x, y : array_like
+        Input arrays
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Relative entropy of the inputs
+
+    See Also
+    --------
+    entr, kl_div, scipy.stats.entropy
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    This function is jointly convex in x and y.
+
+    The origin of this function is in convex programming; see
+    [1]_. Given two discrete probability distributions :math:`p_1,
+    \ldots, p_n` and :math:`q_1, \ldots, q_n`, the definition of relative
+    entropy in the context of *information theory* is
+
+    .. math::
+
+        \sum_{i = 1}^n \mathrm{rel\_entr}(p_i, q_i).
+
+    To compute the latter quantity, use `scipy.stats.entropy`.
+
+    See [2]_ for details.
+
+    References
+    ----------
+    .. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.
+           Cambridge University Press, 2004.
+           :doi:`https://doi.org/10.1017/CBO9780511804441`
+    .. [2] Kullback-Leibler divergence,
+           https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence
+
+    """)
+
+add_newdoc("round",
+    """
+    round(x, out=None)
+
+    Round to the nearest integer.
+
+    Returns the nearest integer to `x`.  If `x` ends in 0.5 exactly,
+    the nearest even integer is chosen.
+
+    Parameters
+    ----------
+    x : array_like
+        Real valued input.
+    out : ndarray, optional
+        Optional output array for the function results.
+
+    Returns
+    -------
+    scalar or ndarray
+        The nearest integers to the elements of `x`. The result is of
+        floating type, not integer type.
+
+    Examples
+    --------
+    >>> import scipy.special as sc
+
+    It rounds to even.
+
+    >>> sc.round([0.5, 1.5])
+    array([0., 2.])
+
+    """)
+
+add_newdoc("shichi",
+    r"""
+    shichi(x, out=None)
+
+    Hyperbolic sine and cosine integrals.
+
+    The hyperbolic sine integral is
+
+    .. math::
+
+      \int_0^x \frac{\sinh{t}}{t}dt
+
+    and the hyperbolic cosine integral is
+
+    .. math::
+
+      \gamma + \log(x) + \int_0^x \frac{\cosh{t} - 1}{t} dt
+
+    where :math:`\gamma` is Euler's constant and :math:`\log` is the
+    principal branch of the logarithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex points at which to compute the hyperbolic sine
+        and cosine integrals.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function results
+
+    Returns
+    -------
+    si : scalar or ndarray
+        Hyperbolic sine integral at ``x``
+    ci : scalar or ndarray
+        Hyperbolic cosine integral at ``x``
+
+    See Also
+    --------
+    sici : Sine and cosine integrals.
+    exp1 : Exponential integral E1.
+    expi : Exponential integral Ei.
+
+    Notes
+    -----
+    For real arguments with ``x < 0``, ``chi`` is the real part of the
+    hyperbolic cosine integral. For such points ``chi(x)`` and ``chi(x
+    + 0j)`` differ by a factor of ``1j*pi``.
+
+    For real arguments the function is computed by calling Cephes'
+    [2]_ *shichi* routine. For complex arguments the algorithm is based
+    on Mpmath's [3]_ *shi* and *chi* routines.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+           (See Section 5.2.)
+    .. [2] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [3] Fredrik Johansson and others.
+           "mpmath: a Python library for arbitrary-precision floating-point
+           arithmetic" (Version 0.19) http://mpmath.org/
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import shichi, sici
+
+    `shichi` accepts real or complex input:
+
+    >>> shichi(0.5)
+    (0.5069967498196671, -0.05277684495649357)
+    >>> shichi(0.5 + 2.5j)
+    ((0.11772029666668238+1.831091777729851j),
+     (0.29912435887648825+1.7395351121166562j))
+
+    The hyperbolic sine and cosine integrals Shi(z) and Chi(z) are
+    related to the sine and cosine integrals Si(z) and Ci(z) by
+
+    * Shi(z) = -i*Si(i*z)
+    * Chi(z) = Ci(-i*z) + i*pi/2
+
+    >>> z = 0.25 + 5j
+    >>> shi, chi = shichi(z)
+    >>> shi, -1j*sici(1j*z)[0]            # Should be the same.
+    ((-0.04834719325101729+1.5469354086921228j),
+     (-0.04834719325101729+1.5469354086921228j))
+    >>> chi, sici(-1j*z)[1] + 1j*np.pi/2  # Should be the same.
+    ((-0.19568708973868087+1.556276312103824j),
+     (-0.19568708973868087+1.556276312103824j))
+
+    Plot the functions evaluated on the real axis:
+
+    >>> xp = np.geomspace(1e-8, 4.0, 250)
+    >>> x = np.concatenate((-xp[::-1], xp))
+    >>> shi, chi = shichi(x)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, shi, label='Shi(x)')
+    >>> ax.plot(x, chi, '--', label='Chi(x)')
+    >>> ax.set_xlabel('x')
+    >>> ax.set_title('Hyperbolic Sine and Cosine Integrals')
+    >>> ax.legend(shadow=True, framealpha=1, loc='lower right')
+    >>> ax.grid(True)
+    >>> plt.show()
+
+    """)
+
+add_newdoc("sici",
+    r"""
+    sici(x, out=None)
+
+    Sine and cosine integrals.
+
+    The sine integral is
+
+    .. math::
+
+      \int_0^x \frac{\sin{t}}{t}dt
+
+    and the cosine integral is
+
+    .. math::
+
+      \gamma + \log(x) + \int_0^x \frac{\cos{t} - 1}{t}dt
+
+    where :math:`\gamma` is Euler's constant and :math:`\log` is the
+    principal branch of the logarithm [1]_.
+
+    Parameters
+    ----------
+    x : array_like
+        Real or complex points at which to compute the sine and cosine
+        integrals.
+    out : tuple of ndarray, optional
+        Optional output arrays for the function results
+
+    Returns
+    -------
+    si : scalar or ndarray
+        Sine integral at ``x``
+    ci : scalar or ndarray
+        Cosine integral at ``x``
+
+    See Also
+    --------
+    shichi : Hyperbolic sine and cosine integrals.
+    exp1 : Exponential integral E1.
+    expi : Exponential integral Ei.
+
+    Notes
+    -----
+    For real arguments with ``x < 0``, ``ci`` is the real part of the
+    cosine integral. For such points ``ci(x)`` and ``ci(x + 0j)``
+    differ by a factor of ``1j*pi``.
+
+    For real arguments the function is computed by calling Cephes'
+    [2]_ *sici* routine. For complex arguments the algorithm is based
+    on Mpmath's [3]_ *si* and *ci* routines.
+
+    References
+    ----------
+    .. [1] Milton Abramowitz and Irene A. Stegun, eds.
+           Handbook of Mathematical Functions with Formulas,
+           Graphs, and Mathematical Tables. New York: Dover, 1972.
+           (See Section 5.2.)
+    .. [2] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+    .. [3] Fredrik Johansson and others.
+           "mpmath: a Python library for arbitrary-precision floating-point
+           arithmetic" (Version 0.19) http://mpmath.org/
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import sici, exp1
+
+    `sici` accepts real or complex input:
+
+    >>> sici(2.5)
+    (1.7785201734438267, 0.2858711963653835)
+    >>> sici(2.5 + 3j)
+    ((4.505735874563953+0.06863305018999577j),
+    (0.0793644206906966-2.935510262937543j))
+
+    For z in the right half plane, the sine and cosine integrals are
+    related to the exponential integral E1 (implemented in SciPy as
+    `scipy.special.exp1`) by
+
+    * Si(z) = (E1(i*z) - E1(-i*z))/2i + pi/2
+    * Ci(z) = -(E1(i*z) + E1(-i*z))/2
+
+    See [1]_ (equations 5.2.21 and 5.2.23).
+
+    We can verify these relations:
+
+    >>> z = 2 - 3j
+    >>> sici(z)
+    ((4.54751388956229-1.3991965806460565j),
+    (1.408292501520851+2.9836177420296055j))
+
+    >>> (exp1(1j*z) - exp1(-1j*z))/2j + np.pi/2  # Same as sine integral
+    (4.54751388956229-1.3991965806460565j)
+
+    >>> -(exp1(1j*z) + exp1(-1j*z))/2            # Same as cosine integral
+    (1.408292501520851+2.9836177420296055j)
+
+    Plot the functions evaluated on the real axis; the dotted horizontal
+    lines are at pi/2 and -pi/2:
+
+    >>> x = np.linspace(-16, 16, 150)
+    >>> si, ci = sici(x)
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, si, label='Si(x)')
+    >>> ax.plot(x, ci, '--', label='Ci(x)')
+    >>> ax.legend(shadow=True, framealpha=1, loc='upper left')
+    >>> ax.set_xlabel('x')
+    >>> ax.set_title('Sine and Cosine Integrals')
+    >>> ax.axhline(np.pi/2, linestyle=':', alpha=0.5, color='k')
+    >>> ax.axhline(-np.pi/2, linestyle=':', alpha=0.5, color='k')
+    >>> ax.grid(True)
+    >>> plt.show()
+
+    """)
+
+add_newdoc("smirnov",
+    r"""
+    smirnov(n, d, out=None)
+
+    Kolmogorov-Smirnov complementary cumulative distribution function
+
+    Returns the exact Kolmogorov-Smirnov complementary cumulative
+    distribution function,(aka the Survival Function) of Dn+ (or Dn-)
+    for a one-sided test of equality between an empirical and a
+    theoretical distribution. It is equal to the probability that the
+    maximum difference between a theoretical distribution and an empirical
+    one based on `n` samples is greater than d.
+
+    Parameters
+    ----------
+    n : int
+      Number of samples
+    d : float array_like
+      Deviation between the Empirical CDF (ECDF) and the target CDF.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of smirnov(n, d), Prob(Dn+ >= d) (Also Prob(Dn- >= d))
+
+    See Also
+    --------
+    smirnovi : The Inverse Survival Function for the distribution
+    scipy.stats.ksone : Provides the functionality as a continuous distribution
+    kolmogorov, kolmogi : Functions for the two-sided distribution
+
+    Notes
+    -----
+    `smirnov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.ksone` distribution.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import smirnov
+    >>> from scipy.stats import norm
+
+    Show the probability of a gap at least as big as 0, 0.5 and 1.0 for a
+    sample of size 5.
+
+    >>> smirnov(5, [0, 0.5, 1.0])
+    array([ 1.   ,  0.056,  0.   ])
+
+    Compare a sample of size 5 against N(0, 1), the standard normal
+    distribution with mean 0 and standard deviation 1.
+
+    `x` is the sample.
+
+    >>> x = np.array([-1.392, -0.135, 0.114, 0.190, 1.82])
+
+    >>> target = norm(0, 1)
+    >>> cdfs = target.cdf(x)
+    >>> cdfs
+    array([0.0819612 , 0.44630594, 0.5453811 , 0.57534543, 0.9656205 ])
+
+    Construct the empirical CDF and the K-S statistics (Dn+, Dn-, Dn).
+
+    >>> n = len(x)
+    >>> ecdfs = np.arange(n+1, dtype=float)/n
+    >>> cols = np.column_stack([x, ecdfs[1:], cdfs, cdfs - ecdfs[:n],
+    ...                        ecdfs[1:] - cdfs])
+    >>> with np.printoptions(precision=3):
+    ...    print(cols)
+    [[-1.392  0.2    0.082  0.082  0.118]
+     [-0.135  0.4    0.446  0.246 -0.046]
+     [ 0.114  0.6    0.545  0.145  0.055]
+     [ 0.19   0.8    0.575 -0.025  0.225]
+     [ 1.82   1.     0.966  0.166  0.034]]
+    >>> gaps = cols[:, -2:]
+    >>> Dnpm = np.max(gaps, axis=0)
+    >>> print(f'Dn-={Dnpm[0]:f}, Dn+={Dnpm[1]:f}')
+    Dn-=0.246306, Dn+=0.224655
+    >>> probs = smirnov(n, Dnpm)
+    >>> print(f'For a sample of size {n} drawn from N(0, 1):',
+    ...       f' Smirnov n={n}: Prob(Dn- >= {Dnpm[0]:f}) = {probs[0]:.4f}',
+    ...       f' Smirnov n={n}: Prob(Dn+ >= {Dnpm[1]:f}) = {probs[1]:.4f}',
+    ...       sep='\n')
+    For a sample of size 5 drawn from N(0, 1):
+     Smirnov n=5: Prob(Dn- >= 0.246306) = 0.4711
+     Smirnov n=5: Prob(Dn+ >= 0.224655) = 0.5245
+
+    Plot the empirical CDF and the standard normal CDF.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.step(np.concatenate(([-2.5], x, [2.5])),
+    ...          np.concatenate((ecdfs, [1])),
+    ...          where='post', label='Empirical CDF')
+    >>> xx = np.linspace(-2.5, 2.5, 100)
+    >>> plt.plot(xx, target.cdf(xx), '--', label='CDF for N(0, 1)')
+
+    Add vertical lines marking Dn+ and Dn-.
+
+    >>> iminus, iplus = np.argmax(gaps, axis=0)
+    >>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], color='r',
+    ...            alpha=0.5, lw=4)
+    >>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], color='m',
+    ...            alpha=0.5, lw=4)
+
+    >>> plt.grid(True)
+    >>> plt.legend(framealpha=1, shadow=True)
+    >>> plt.show()
+    """)
+
+add_newdoc("smirnovi",
+    """
+    smirnovi(n, p, out=None)
+
+    Inverse to `smirnov`
+
+    Returns `d` such that ``smirnov(n, d) == p``, the critical value
+    corresponding to `p`.
+
+    Parameters
+    ----------
+    n : int
+      Number of samples
+    p : float array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        The value(s) of smirnovi(n, p), the critical values.
+
+    See Also
+    --------
+    smirnov : The Survival Function (SF) for the distribution
+    scipy.stats.ksone : Provides the functionality as a continuous distribution
+    kolmogorov, kolmogi : Functions for the two-sided distribution
+    scipy.stats.kstwobign : Two-sided Kolmogorov-Smirnov distribution, large n
+
+    Notes
+    -----
+    `smirnov` is used by `stats.kstest` in the application of the
+    Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this
+    function is exposed in `scpy.special`, but the recommended way to achieve
+    the most accurate CDF/SF/PDF/PPF/ISF computations is to use the
+    `stats.ksone` distribution.
+
+    Examples
+    --------
+    >>> from scipy.special import smirnovi, smirnov
+
+    >>> n = 24
+    >>> deviations = [0.1, 0.2, 0.3]
+
+    Use `smirnov` to compute the complementary CDF of the Smirnov
+    distribution for the given number of samples and deviations.
+
+    >>> p = smirnov(n, deviations)
+    >>> p
+    array([0.58105083, 0.12826832, 0.01032231])
+
+    The inverse function ``smirnovi(n, p)`` returns ``deviations``.
+
+    >>> smirnovi(n, p)
+    array([0.1, 0.2, 0.3])
+
+    """)
+
+add_newdoc("_smirnovc",
+    """
+    _smirnovc(n, d)
+     Internal function, do not use.
+    """)
+
+add_newdoc("_smirnovci",
+    """
+     Internal function, do not use.
+    """)
+
+add_newdoc("_smirnovp",
+    """
+    _smirnovp(n, p)
+     Internal function, do not use.
+    """)
+
+add_newdoc("spence",
+    r"""
+    spence(z, out=None)
+
+    Spence's function, also known as the dilogarithm.
+
+    It is defined to be
+
+    .. math::
+      \int_1^z \frac{\log(t)}{1 - t}dt
+
+    for complex :math:`z`, where the contour of integration is taken
+    to avoid the branch cut of the logarithm. Spence's function is
+    analytic everywhere except the negative real axis where it has a
+    branch cut.
+
+    Parameters
+    ----------
+    z : array_like
+        Points at which to evaluate Spence's function
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    s : scalar or ndarray
+        Computed values of Spence's function
+
+    Notes
+    -----
+    There is a different convention which defines Spence's function by
+    the integral
+
+    .. math::
+      -\int_0^z \frac{\log(1 - t)}{t}dt;
+
+    this is our ``spence(1 - z)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import spence
+    >>> import matplotlib.pyplot as plt
+
+    The function is defined for complex inputs:
+
+    >>> spence([1-1j, 1.5+2j, 3j, -10-5j])
+    array([-0.20561676+0.91596559j, -0.86766909-1.39560134j,
+           -0.59422064-2.49129918j, -1.14044398+6.80075924j])
+
+    For complex inputs on the branch cut, which is the negative real axis,
+    the function returns the limit for ``z`` with positive imaginary part.
+    For example, in the following, note the sign change of the imaginary
+    part of the output for ``z = -2`` and ``z = -2 - 1e-8j``:
+
+    >>> spence([-2 + 1e-8j, -2, -2 - 1e-8j])
+    array([2.32018041-3.45139229j, 2.32018042-3.4513923j ,
+           2.32018041+3.45139229j])
+
+    The function returns ``nan`` for real inputs on the branch cut:
+
+    >>> spence(-1.5)
+    nan
+
+    Verify some particular values: ``spence(0) = pi**2/6``,
+    ``spence(1) = 0`` and ``spence(2) = -pi**2/12``.
+
+    >>> spence([0, 1, 2])
+    array([ 1.64493407,  0.        , -0.82246703])
+    >>> np.pi**2/6, -np.pi**2/12
+    (1.6449340668482264, -0.8224670334241132)
+
+    Verify the identity::
+
+        spence(z) + spence(1 - z) = pi**2/6 - log(z)*log(1 - z)
+
+    >>> z = 3 + 4j
+    >>> spence(z) + spence(1 - z)
+    (-2.6523186143876067+1.8853470951513935j)
+    >>> np.pi**2/6 - np.log(z)*np.log(1 - z)
+    (-2.652318614387606+1.885347095151394j)
+
+    Plot the function for positive real input.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0, 6, 400)
+    >>> ax.plot(x, spence(x))
+    >>> ax.grid()
+    >>> ax.set_xlabel('x')
+    >>> ax.set_title('spence(x)')
+    >>> plt.show()
+    """)
+
+add_newdoc(
+    "stdtr",
+    r"""
+    stdtr(df, t, out=None)
+
+    Student t distribution cumulative distribution function
+
+    Returns the integral:
+
+    .. math::
+        \frac{\Gamma((df+1)/2)}{\sqrt{\pi df} \Gamma(df/2)}
+        \int_{-\infty}^t (1+x^2/df)^{-(df+1)/2}\, dx
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom
+    t : array_like
+        Upper bound of the integral
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the Student t CDF at t
+
+    See Also
+    --------
+    stdtridf : inverse of stdtr with respect to `df`
+    stdtrit : inverse of stdtr with respect to `t`
+    scipy.stats.t : student t distribution
+
+    Notes
+    -----
+    The student t distribution is also available as `scipy.stats.t`.
+    Calling `stdtr` directly can improve performance compared to the
+    ``cdf`` method of `scipy.stats.t` (see last example below).
+
+    Examples
+    --------
+    Calculate the function for ``df=3`` at ``t=1``.
+
+    >>> import numpy as np
+    >>> from scipy.special import stdtr
+    >>> import matplotlib.pyplot as plt
+    >>> stdtr(3, 1)
+    0.8044988905221148
+
+    Plot the function for three different degrees of freedom.
+
+    >>> x = np.linspace(-10, 10, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> parameters = [(1, "solid"), (3, "dashed"), (10, "dotted")]
+    >>> for (df, linestyle) in parameters:
+    ...     ax.plot(x, stdtr(df, x), ls=linestyle, label=f"$df={df}$")
+    >>> ax.legend()
+    >>> ax.set_title("Student t distribution cumulative distribution function")
+    >>> plt.show()
+
+    The function can be computed for several degrees of freedom at the same
+    time by providing a NumPy array or list for `df`:
+
+    >>> stdtr([1, 2, 3], 1)
+    array([0.75      , 0.78867513, 0.80449889])
+
+    It is possible to calculate the function at several points for several
+    different degrees of freedom simultaneously by providing arrays for `df`
+    and `t` with shapes compatible for broadcasting. Compute `stdtr` at
+    4 points for 3 degrees of freedom resulting in an array of shape 3x4.
+
+    >>> dfs = np.array([[1], [2], [3]])
+    >>> t = np.array([2, 4, 6, 8])
+    >>> dfs.shape, t.shape
+    ((3, 1), (4,))
+
+    >>> stdtr(dfs, t)
+    array([[0.85241638, 0.92202087, 0.94743154, 0.96041658],
+           [0.90824829, 0.97140452, 0.98666426, 0.99236596],
+           [0.93033702, 0.98599577, 0.99536364, 0.99796171]])
+
+    The t distribution is also available as `scipy.stats.t`. Calling `stdtr`
+    directly can be much faster than calling the ``cdf`` method of
+    `scipy.stats.t`. To get the same results, one must use the following
+    parametrization: ``scipy.stats.t(df).cdf(x) = stdtr(df, x)``.
+
+    >>> from scipy.stats import t
+    >>> df, x = 3, 1
+    >>> stdtr_result = stdtr(df, x)  # this can be faster than below
+    >>> stats_result = t(df).cdf(x)
+    >>> stats_result == stdtr_result  # test that results are equal
+    True
+    """)
+
+add_newdoc("stdtridf",
+    """
+    stdtridf(p, t, out=None)
+
+    Inverse of `stdtr` vs df
+
+    Returns the argument df such that stdtr(df, t) is equal to `p`.
+
+    Parameters
+    ----------
+    p : array_like
+        Probability
+    t : array_like
+        Upper bound of the integral
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    df : scalar or ndarray
+        Value of `df` such that ``stdtr(df, t) == p``
+
+    See Also
+    --------
+    stdtr : Student t CDF
+    stdtrit : inverse of stdtr with respect to `t`
+    scipy.stats.t : Student t distribution
+
+    Examples
+    --------
+    Compute the student t cumulative distribution function for one
+    parameter set.
+
+    >>> from scipy.special import stdtr, stdtridf
+    >>> df, x = 5, 2
+    >>> cdf_value = stdtr(df, x)
+    >>> cdf_value
+    0.9490302605850709
+
+    Verify that `stdtridf` recovers the original value for `df` given
+    the CDF value and `x`.
+
+    >>> stdtridf(cdf_value, x)
+    5.0
+    """)
+
+add_newdoc("stdtrit",
+    """
+    stdtrit(df, p, out=None)
+
+    The `p`-th quantile of the student t distribution.
+
+    This function is the inverse of the student t distribution cumulative
+    distribution function (CDF), returning `t` such that `stdtr(df, t) = p`.
+
+    Returns the argument `t` such that stdtr(df, t) is equal to `p`.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom
+    p : array_like
+        Probability
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    t : scalar or ndarray
+        Value of `t` such that ``stdtr(df, t) == p``
+
+    See Also
+    --------
+    stdtr : Student t CDF
+    stdtridf : inverse of stdtr with respect to `df`
+    scipy.stats.t : Student t distribution
+
+    Notes
+    -----
+    The student t distribution is also available as `scipy.stats.t`. Calling
+    `stdtrit` directly can improve performance compared to the ``ppf``
+    method of `scipy.stats.t` (see last example below).
+
+    Examples
+    --------
+    `stdtrit` represents the inverse of the student t distribution CDF which
+    is available as `stdtr`. Here, we calculate the CDF for ``df`` at
+    ``x=1``. `stdtrit` then returns ``1`` up to floating point errors
+    given the same value for `df` and the computed CDF value.
+
+    >>> import numpy as np
+    >>> from scipy.special import stdtr, stdtrit
+    >>> import matplotlib.pyplot as plt
+    >>> df = 3
+    >>> x = 1
+    >>> cdf_value = stdtr(df, x)
+    >>> stdtrit(df, cdf_value)
+    0.9999999994418539
+
+    Plot the function for three different degrees of freedom.
+
+    >>> x = np.linspace(0, 1, 1000)
+    >>> parameters = [(1, "solid"), (2, "dashed"), (5, "dotted")]
+    >>> fig, ax = plt.subplots()
+    >>> for (df, linestyle) in parameters:
+    ...     ax.plot(x, stdtrit(df, x), ls=linestyle, label=f"$df={df}$")
+    >>> ax.legend()
+    >>> ax.set_ylim(-10, 10)
+    >>> ax.set_title("Student t distribution quantile function")
+    >>> plt.show()
+
+    The function can be computed for several degrees of freedom at the same
+    time by providing a NumPy array or list for `df`:
+
+    >>> stdtrit([1, 2, 3], 0.7)
+    array([0.72654253, 0.6172134 , 0.58438973])
+
+    It is possible to calculate the function at several points for several
+    different degrees of freedom simultaneously by providing arrays for `df`
+    and `p` with shapes compatible for broadcasting. Compute `stdtrit` at
+    4 points for 3 degrees of freedom resulting in an array of shape 3x4.
+
+    >>> dfs = np.array([[1], [2], [3]])
+    >>> p = np.array([0.2, 0.4, 0.7, 0.8])
+    >>> dfs.shape, p.shape
+    ((3, 1), (4,))
+
+    >>> stdtrit(dfs, p)
+    array([[-1.37638192, -0.3249197 ,  0.72654253,  1.37638192],
+           [-1.06066017, -0.28867513,  0.6172134 ,  1.06066017],
+           [-0.97847231, -0.27667066,  0.58438973,  0.97847231]])
+
+    The t distribution is also available as `scipy.stats.t`. Calling `stdtrit`
+    directly can be much faster than calling the ``ppf`` method of
+    `scipy.stats.t`. To get the same results, one must use the following
+    parametrization: ``scipy.stats.t(df).ppf(x) = stdtrit(df, x)``.
+
+    >>> from scipy.stats import t
+    >>> df, x = 3, 0.5
+    >>> stdtrit_result = stdtrit(df, x)  # this can be faster than below
+    >>> stats_result = t(df).ppf(x)
+    >>> stats_result == stdtrit_result  # test that results are equal
+    True
+    """)
+
+add_newdoc(
+    "tklmbda",
+    r"""
+    tklmbda(x, lmbda, out=None)
+
+    Cumulative distribution function of the Tukey lambda distribution.
+
+    Parameters
+    ----------
+    x, lmbda : array_like
+        Parameters
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    cdf : scalar or ndarray
+        Value of the Tukey lambda CDF
+
+    See Also
+    --------
+    scipy.stats.tukeylambda : Tukey lambda distribution
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import tklmbda, expit
+
+    Compute the cumulative distribution function (CDF) of the Tukey lambda
+    distribution at several ``x`` values for `lmbda` = -1.5.
+
+    >>> x = np.linspace(-2, 2, 9)
+    >>> x
+    array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])
+    >>> tklmbda(x, -1.5)
+    array([0.34688734, 0.3786554 , 0.41528805, 0.45629737, 0.5       ,
+           0.54370263, 0.58471195, 0.6213446 , 0.65311266])
+
+    When `lmbda` is 0, the function is the logistic sigmoid function,
+    which is implemented in `scipy.special` as `expit`.
+
+    >>> tklmbda(x, 0)
+    array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,
+           0.62245933, 0.73105858, 0.81757448, 0.88079708])
+    >>> expit(x)
+    array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,
+           0.62245933, 0.73105858, 0.81757448, 0.88079708])
+
+    When `lmbda` is 1, the Tukey lambda distribution is uniform on the
+    interval [-1, 1], so the CDF increases linearly.
+
+    >>> t = np.linspace(-1, 1, 9)
+    >>> tklmbda(t, 1)
+    array([0.   , 0.125, 0.25 , 0.375, 0.5  , 0.625, 0.75 , 0.875, 1.   ])
+
+    In the following, we generate plots for several values of `lmbda`.
+
+    The first figure shows graphs for `lmbda` <= 0.
+
+    >>> styles = ['-', '-.', '--', ':']
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-12, 12, 500)
+    >>> for k, lmbda in enumerate([-1.0, -0.5, 0.0]):
+    ...     y = tklmbda(x, lmbda)
+    ...     ax.plot(x, y, styles[k], label=rf'$\lambda$ = {lmbda:-4.1f}')
+
+    >>> ax.set_title(r'tklmbda(x, $\lambda$)')
+    >>> ax.set_label('x')
+    >>> ax.legend(framealpha=1, shadow=True)
+    >>> ax.grid(True)
+
+    The second figure shows graphs for `lmbda` > 0.  The dots in the
+    graphs show the bounds of the support of the distribution.
+
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(-4.2, 4.2, 500)
+    >>> lmbdas = [0.25, 0.5, 1.0, 1.5]
+    >>> for k, lmbda in enumerate(lmbdas):
+    ...     y = tklmbda(x, lmbda)
+    ...     ax.plot(x, y, styles[k], label=fr'$\lambda$ = {lmbda}')
+
+    >>> ax.set_prop_cycle(None)
+    >>> for lmbda in lmbdas:
+    ...     ax.plot([-1/lmbda, 1/lmbda], [0, 1], '.', ms=8)
+
+    >>> ax.set_title(r'tklmbda(x, $\lambda$)')
+    >>> ax.set_xlabel('x')
+    >>> ax.legend(framealpha=1, shadow=True)
+    >>> ax.grid(True)
+
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    The CDF of the Tukey lambda distribution is also implemented as the
+    ``cdf`` method of `scipy.stats.tukeylambda`.  In the following,
+    ``tukeylambda.cdf(x, -0.5)`` and ``tklmbda(x, -0.5)`` compute the
+    same values:
+
+    >>> from scipy.stats import tukeylambda
+    >>> x = np.linspace(-2, 2, 9)
+
+    >>> tukeylambda.cdf(x, -0.5)
+    array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,
+           0.58671839, 0.66458323, 0.72906142, 0.78004843])
+
+    >>> tklmbda(x, -0.5)
+    array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,
+           0.58671839, 0.66458323, 0.72906142, 0.78004843])
+
+    The implementation in ``tukeylambda`` also provides location and scale
+    parameters, and other methods such as ``pdf()`` (the probability
+    density function) and ``ppf()`` (the inverse of the CDF), so for
+    working with the Tukey lambda distribution, ``tukeylambda`` is more
+    generally useful.  The primary advantage of ``tklmbda`` is that it is
+    significantly faster than ``tukeylambda.cdf``.
+    """)
+
+add_newdoc("wofz",
+    """
+    wofz(z, out=None)
+
+    Faddeeva function
+
+    Returns the value of the Faddeeva function for complex argument::
+
+        exp(-z**2) * erfc(-i*z)
+
+    Parameters
+    ----------
+    z : array_like
+        complex argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Value of the Faddeeva function
+
+    See Also
+    --------
+    dawsn, erf, erfc, erfcx, erfi
+
+    References
+    ----------
+    .. [1] Steven G. Johnson, Faddeeva W function implementation.
+       http://ab-initio.mit.edu/Faddeeva
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-3, 3)
+    >>> z = special.wofz(x)
+
+    >>> plt.plot(x, z.real, label='wofz(x).real')
+    >>> plt.plot(x, z.imag, label='wofz(x).imag')
+    >>> plt.xlabel('$x$')
+    >>> plt.legend(framealpha=1, shadow=True)
+    >>> plt.grid(alpha=0.25)
+    >>> plt.show()
+
+    """)
+
+add_newdoc("xlogy",
+    """
+    xlogy(x, y, out=None)
+
+    Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Multiplier
+    y : array_like
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    z : scalar or ndarray
+        Computed x*log(y)
+
+    Notes
+    -----
+    The log function used in the computation is the natural log.
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    We can use this function to calculate the binary logistic loss also
+    known as the binary cross entropy. This loss function is used for
+    binary classification problems and is defined as:
+
+    .. math::
+        L = 1/n * \\sum_{i=0}^n -(y_i*log(y\\_pred_i) + (1-y_i)*log(1-y\\_pred_i))
+
+    We can define the parameters `x` and `y` as y and y_pred respectively.
+    y is the array of the actual labels which over here can be either 0 or 1.
+    y_pred is the array of the predicted probabilities with respect to
+    the positive class (1).
+
+    >>> import numpy as np
+    >>> from scipy.special import xlogy
+    >>> y = np.array([0, 1, 0, 1, 1, 0])
+    >>> y_pred = np.array([0.3, 0.8, 0.4, 0.7, 0.9, 0.2])
+    >>> n = len(y)
+    >>> loss = -(xlogy(y, y_pred) + xlogy(1 - y, 1 - y_pred)).sum()
+    >>> loss /= n
+    >>> loss
+    0.29597052165495025
+
+    A lower loss is usually better as it indicates that the predictions are
+    similar to the actual labels. In this example since our predicted
+    probabilities are close to the actual labels, we get an overall loss
+    that is reasonably low and appropriate.
+
+    """)
+
+add_newdoc("xlog1py",
+    """
+    xlog1py(x, y, out=None)
+
+    Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.
+
+    Parameters
+    ----------
+    x : array_like
+        Multiplier
+    y : array_like
+        Argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    z : scalar or ndarray
+        Computed x*log1p(y)
+
+    Notes
+    -----
+
+    .. versionadded:: 0.13.0
+
+    Examples
+    --------
+    This example shows how the function can be used to calculate the log of
+    the probability mass function for a geometric discrete random variable.
+    The probability mass function of the geometric distribution is defined
+    as follows:
+
+    .. math:: f(k) = (1-p)^{k-1} p
+
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure
+    and :math:`k` is the number of trials to get the first success.
+
+    >>> import numpy as np
+    >>> from scipy.special import xlog1py
+    >>> p = 0.5
+    >>> k = 100
+    >>> _pmf = np.power(1 - p, k - 1) * p
+    >>> _pmf
+    7.888609052210118e-31
+
+    If we take k as a relatively large number the value of the probability
+    mass function can become very low. In such cases taking the log of the
+    pmf would be more suitable as the log function can change the values
+    to a scale that is more appropriate to work with.
+
+    >>> _log_pmf = xlog1py(k - 1, -p) + np.log(p)
+    >>> _log_pmf
+    -69.31471805599453
+
+    We can confirm that we get a value close to the original pmf value by
+    taking the exponential of the log pmf.
+
+    >>> _orig_pmf = np.exp(_log_pmf)
+    >>> np.isclose(_pmf, _orig_pmf)
+    True
+
+    """)
+
+add_newdoc("yn",
+    r"""
+    yn(n, x, out=None)
+
+    Bessel function of the second kind of integer order and real argument.
+
+    Parameters
+    ----------
+    n : array_like
+        Order (integer).
+    x : array_like
+        Argument (float).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    Y : scalar or ndarray
+        Value of the Bessel function, :math:`Y_n(x)`.
+
+    See Also
+    --------
+    yv : For real order and real or complex argument.
+    y0: faster implementation of this function for order 0
+    y1: faster implementation of this function for order 1
+
+    Notes
+    -----
+    Wrapper for the Cephes [1]_ routine `yn`.
+
+    The function is evaluated by forward recurrence on `n`, starting with
+    values computed by the Cephes routines `y0` and `y1`. If ``n = 0`` or 1,
+    the routine for `y0` or `y1` is called directly.
+
+    References
+    ----------
+    .. [1] Cephes Mathematical Functions Library,
+           http://www.netlib.org/cephes/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import yn
+    >>> yn(0, 1.)
+    0.08825696421567697
+
+    Evaluate the function at one point for different orders.
+
+    >>> yn(0, 1.), yn(1, 1.), yn(2, 1.)
+    (0.08825696421567697, -0.7812128213002888, -1.6506826068162546)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> yn([0, 1, 2], 1.)
+    array([ 0.08825696, -0.78121282, -1.65068261])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 3., 8.])
+    >>> yn(0, points)
+    array([-0.44451873,  0.37685001,  0.22352149])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> yn(orders, points)
+    array([[-0.44451873,  0.37685001,  0.22352149],
+           [-1.47147239,  0.32467442, -0.15806046]])
+
+    Plot the functions of order 0 to 3 from 0 to 10.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0., 10., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, yn(i, x), label=f'$Y_{i!r}$')
+    >>> ax.set_ylim(-3, 1)
+    >>> ax.legend()
+    >>> plt.show()
+    """)
+
+add_newdoc("yv",
+    r"""
+    yv(v, z, out=None)
+
+    Bessel function of the second kind of real order and complex argument.
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    Y : scalar or ndarray
+        Value of the Bessel function of the second kind, :math:`Y_v(x)`.
+
+    See Also
+    --------
+    yve : :math:`Y_v` with leading exponential behavior stripped off.
+    y0: faster implementation of this function for order 0
+    y1: faster implementation of this function for order 1
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the
+    AMOS [1]_ `zbesy` routine, which exploits the connection to the Hankel
+    Bessel functions :math:`H_v^{(1)}` and :math:`H_v^{(2)}`,
+
+    .. math:: Y_v(z) = \frac{1}{2\imath} (H_v^{(1)} - H_v^{(2)}).
+
+    For negative `v` values the formula,
+
+    .. math:: Y_{-v}(z) = Y_v(z) \cos(\pi v) + J_v(z) \sin(\pi v)
+
+    is used, where :math:`J_v(z)` is the Bessel function of the first kind,
+    computed using the AMOS routine `zbesj`.  Note that the second term is
+    exactly zero for integer `v`; to improve accuracy the second term is
+    explicitly omitted for `v` values such that `v = floor(v)`.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Evaluate the function of order 0 at one point.
+
+    >>> from scipy.special import yv
+    >>> yv(0, 1.)
+    0.088256964215677
+
+    Evaluate the function at one point for different orders.
+
+    >>> yv(0, 1.), yv(1, 1.), yv(1.5, 1.)
+    (0.088256964215677, -0.7812128213002889, -1.102495575160179)
+
+    The evaluation for different orders can be carried out in one call by
+    providing a list or NumPy array as argument for the `v` parameter:
+
+    >>> yv([0, 1, 1.5], 1.)
+    array([ 0.08825696, -0.78121282, -1.10249558])
+
+    Evaluate the function at several points for order 0 by providing an
+    array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 3., 8.])
+    >>> yv(0, points)
+    array([-0.44451873,  0.37685001,  0.22352149])
+
+    If `z` is an array, the order parameter `v` must be broadcastable to
+    the correct shape if different orders shall be computed in one call.
+    To calculate the orders 0 and 1 for an 1D array:
+
+    >>> orders = np.array([[0], [1]])
+    >>> orders.shape
+    (2, 1)
+
+    >>> yv(orders, points)
+    array([[-0.44451873,  0.37685001,  0.22352149],
+           [-1.47147239,  0.32467442, -0.15806046]])
+
+    Plot the functions of order 0 to 3 from 0 to 10.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> x = np.linspace(0., 10., 1000)
+    >>> for i in range(4):
+    ...     ax.plot(x, yv(i, x), label=f'$Y_{i!r}$')
+    >>> ax.set_ylim(-3, 1)
+    >>> ax.legend()
+    >>> plt.show()
+
+    """)
+
+add_newdoc("yve",
+    r"""
+    yve(v, z, out=None)
+
+    Exponentially scaled Bessel function of the second kind of real order.
+
+    Returns the exponentially scaled Bessel function of the second
+    kind of real order `v` at complex `z`::
+
+        yve(v, z) = yv(v, z) * exp(-abs(z.imag))
+
+    Parameters
+    ----------
+    v : array_like
+        Order (float).
+    z : array_like
+        Argument (float or complex).
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    Y : scalar or ndarray
+        Value of the exponentially scaled Bessel function.
+
+    See Also
+    --------
+    yv: Unscaled Bessel function of the second kind of real order.
+
+    Notes
+    -----
+    For positive `v` values, the computation is carried out using the
+    AMOS [1]_ `zbesy` routine, which exploits the connection to the Hankel
+    Bessel functions :math:`H_v^{(1)}` and :math:`H_v^{(2)}`,
+
+    .. math:: Y_v(z) = \frac{1}{2\imath} (H_v^{(1)} - H_v^{(2)}).
+
+    For negative `v` values the formula,
+
+    .. math:: Y_{-v}(z) = Y_v(z) \cos(\pi v) + J_v(z) \sin(\pi v)
+
+    is used, where :math:`J_v(z)` is the Bessel function of the first kind,
+    computed using the AMOS routine `zbesj`.  Note that the second term is
+    exactly zero for integer `v`; to improve accuracy the second term is
+    explicitly omitted for `v` values such that `v = floor(v)`.
+
+    Exponentially scaled Bessel functions are useful for large `z`:
+    for these, the unscaled Bessel functions can easily under-or overflow.
+
+    References
+    ----------
+    .. [1] Donald E. Amos, "AMOS, A Portable Package for Bessel Functions
+           of a Complex Argument and Nonnegative Order",
+           http://netlib.org/amos/
+
+    Examples
+    --------
+    Compare the output of `yv` and `yve` for large complex arguments for `z`
+    by computing their values for order ``v=1`` at ``z=1000j``. We see that
+    `yv` returns nan but `yve` returns a finite number:
+
+    >>> import numpy as np
+    >>> from scipy.special import yv, yve
+    >>> v = 1
+    >>> z = 1000j
+    >>> yv(v, z), yve(v, z)
+    ((nan+nanj), (-0.012610930256928629+7.721967686709076e-19j))
+
+    For real arguments for `z`, `yve` returns the same as `yv` up to
+    floating point errors.
+
+    >>> v, z = 1, 1000
+    >>> yv(v, z), yve(v, z)
+    (-0.02478433129235178, -0.02478433129235179)
+
+    The function can be evaluated for several orders at the same time by
+    providing a list or NumPy array for `v`:
+
+    >>> yve([1, 2, 3], 1j)
+    array([-0.20791042+0.14096627j,  0.38053618-0.04993878j,
+           0.00815531-1.66311097j])
+
+    In the same way, the function can be evaluated at several points in one
+    call by providing a list or NumPy array for `z`:
+
+    >>> yve(1, np.array([1j, 2j, 3j]))
+    array([-0.20791042+0.14096627j, -0.21526929+0.01205044j,
+           -0.19682671+0.00127278j])
+
+    It is also possible to evaluate several orders at several points
+    at the same time by providing arrays for `v` and `z` with
+    broadcasting compatible shapes. Compute `yve` for two different orders
+    `v` and three points `z` resulting in a 2x3 array.
+
+    >>> v = np.array([[1], [2]])
+    >>> z = np.array([3j, 4j, 5j])
+    >>> v.shape, z.shape
+    ((2, 1), (3,))
+
+    >>> yve(v, z)
+    array([[-1.96826713e-01+1.27277544e-03j, -1.78750840e-01+1.45558819e-04j,
+            -1.63972267e-01+1.73494110e-05j],
+           [1.94960056e-03-1.11782545e-01j,  2.02902325e-04-1.17626501e-01j,
+            2.27727687e-05-1.17951906e-01j]])
+    """)
+
+add_newdoc("_struve_asymp_large_z",
+    """
+    _struve_asymp_large_z(v, z, is_h)
+
+    Internal function for testing `struve` & `modstruve`
+
+    Evaluates using asymptotic expansion
+
+    Returns
+    -------
+    v, err
+    """)
+
+add_newdoc("_struve_power_series",
+    """
+    _struve_power_series(v, z, is_h)
+
+    Internal function for testing `struve` & `modstruve`
+
+    Evaluates using power series
+
+    Returns
+    -------
+    v, err
+    """)
+
+add_newdoc("_struve_bessel_series",
+    """
+    _struve_bessel_series(v, z, is_h)
+
+    Internal function for testing `struve` & `modstruve`
+
+    Evaluates using Bessel function series
+
+    Returns
+    -------
+    v, err
+    """)
+
+add_newdoc("_spherical_jn",
+    """
+    Internal function, use `spherical_jn` instead.
+    """)
+
+add_newdoc("_spherical_jn_d",
+    """
+    Internal function, use `spherical_jn` instead.
+    """)
+
+add_newdoc("_spherical_yn",
+    """
+    Internal function, use `spherical_yn` instead.
+    """)
+
+add_newdoc("_spherical_yn_d",
+    """
+    Internal function, use `spherical_yn` instead.
+    """)
+
+add_newdoc("_spherical_in",
+    """
+    Internal function, use `spherical_in` instead.
+    """)
+
+add_newdoc("_spherical_in_d",
+    """
+    Internal function, use `spherical_in` instead.
+    """)
+
+add_newdoc("_spherical_kn",
+    """
+    Internal function, use `spherical_kn` instead.
+    """)
+
+add_newdoc("_spherical_kn_d",
+    """
+    Internal function, use `spherical_kn` instead.
+    """)
+
+add_newdoc("owens_t",
+    """
+    owens_t(h, a, out=None)
+
+    Owen's T Function.
+
+    The function T(h, a) gives the probability of the event
+    (X > h and 0 < Y < a * X) where X and Y are independent
+    standard normal random variables.
+
+    Parameters
+    ----------
+    h: array_like
+        Input value.
+    a: array_like
+        Input value.
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    t: scalar or ndarray
+        Probability of the event (X > h and 0 < Y < a * X),
+        where X and Y are independent standard normal random variables.
+
+    References
+    ----------
+    .. [1] M. Patefield and D. Tandy, "Fast and accurate calculation of
+           Owen's T Function", Statistical Software vol. 5, pp. 1-25, 2000.
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> a = 3.5
+    >>> h = 0.78
+    >>> special.owens_t(h, a)
+    0.10877216734852274
+    """)
+
+add_newdoc("_factorial",
+    """
+    Internal function, do not use.
+    """)
+
+add_newdoc("ndtri_exp",
+    r"""
+    ndtri_exp(y, out=None)
+
+    Inverse of `log_ndtr` vs x. Allows for greater precision than
+    `ndtri` composed with `numpy.exp` for very small values of y and for
+    y close to 0.
+
+    Parameters
+    ----------
+    y : array_like of float
+        Function argument
+    out : ndarray, optional
+        Optional output array for the function results
+
+    Returns
+    -------
+    scalar or ndarray
+        Inverse of the log CDF of the standard normal distribution, evaluated
+        at y.
+
+    See Also
+    --------
+    log_ndtr : log of the standard normal cumulative distribution function
+    ndtr : standard normal cumulative distribution function
+    ndtri : standard normal percentile function
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import scipy.special as sc
+
+    `ndtri_exp` agrees with the naive implementation when the latter does
+    not suffer from underflow.
+
+    >>> sc.ndtri_exp(-1)
+    -0.33747496376420244
+    >>> sc.ndtri(np.exp(-1))
+    -0.33747496376420244
+
+    For extreme values of y, the naive approach fails
+
+    >>> sc.ndtri(np.exp(-800))
+    -inf
+    >>> sc.ndtri(np.exp(-1e-20))
+    inf
+
+    whereas `ndtri_exp` is still able to compute the result to high precision.
+
+    >>> sc.ndtri_exp(-800)
+    -39.88469483825668
+    >>> sc.ndtri_exp(-1e-20)
+    9.262340089798409
+    """)
+
+
+add_newdoc("_stirling2_inexact",
+    r"""
+    Internal function, do not use.
+    """)
+
+add_newdoc(
+    "_beta_pdf",
+    r"""
+    _beta_pdf(x, a, b)
+
+    Probability density function of beta distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    a, b : array_like
+           Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_beta_ppf",
+    r"""
+    _beta_ppf(x, a, b)
+
+    Percent point function of beta distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued such that :math:`0 \leq x \leq 1`,
+        the upper limit of integration
+    a, b : array_like
+           Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_invgauss_ppf",
+    """
+    _invgauss_ppf(x, mu)
+
+    Percent point function of inverse gaussian distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    mu : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_invgauss_isf",
+    """
+    _invgauss_isf(x, mu, s)
+
+    Inverse survival function of inverse gaussian distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    mu : array_like
+        Positive, real-valued parameters
+    s : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_cauchy_ppf",
+    """
+    _cauchy_ppf(p, loc, scale)
+
+    Percent point function (i.e. quantile) of the Cauchy distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Probabilities
+    loc : array_like
+        Location parameter of the distribution.
+    scale : array_like
+        Scale parameter of the distribution.
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_cauchy_isf",
+    """
+    _cauchy_isf(p, loc, scale)
+
+    Inverse survival function of the Cauchy distribution.
+
+    Parameters
+    ----------
+    p : array_like
+        Probabilities
+    loc : array_like
+        Location parameter of the distribution.
+    scale : array_like
+        Scale parameter of the distribution.
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_pdf",
+    """
+    _ncx2_pdf(x, k, l)
+
+    Probability density function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_cdf",
+    """
+    _ncx2_cdf(x, k, l)
+
+    Cumulative density function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_ppf",
+    """
+    _ncx2_ppf(x, k, l)
+
+    Percent point function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_sf",
+    """
+    _ncx2_sf(x, k, l)
+
+    Survival function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncx2_isf",
+    """
+    _ncx2_isf(x, k, l)
+
+    Inverse survival function of Non-central chi-squared distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    k, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_pdf",
+    """
+    _ncf_pdf(x, v1, v2, l)
+
+    Probability density function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_cdf",
+    """
+    _ncf_cdf(x, v1, v2, l)
+
+    Cumulative density function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_ppf",
+    """
+    _ncf_ppf(x, v1, v2, l)
+
+    Percent point function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_sf",
+    """
+    _ncf_sf(x, v1, v2, l)
+
+    Survival function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_isf",
+    """
+    _ncf_isf(x, v1, v2, l)
+
+    Inverse survival function of noncentral F-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Positive real-valued
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_mean",
+    """
+    _ncf_mean(v1, v2, l)
+
+    Mean of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_variance",
+    """
+    _ncf_variance(v1, v2, l)
+
+    Variance of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_skewness",
+    """
+    _ncf_skewness(v1, v2, l)
+
+    Skewness of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_ncf_kurtosis_excess",
+    """
+    _ncf_kurtosis_excess(v1, v2, l)
+
+    Kurtosis excess of noncentral F-distribution.
+
+    Parameters
+    ----------
+    v1, v2, l : array_like
+        Positive, real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_cdf",
+    """
+    _nct_cdf(x, v, l)
+
+    Cumulative density function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_pdf",
+    """
+    _nct_pdf(x, v, l)
+
+    Probability density function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+
+add_newdoc(
+    "_nct_ppf",
+    """
+    _nct_ppf(x, v, l)
+
+    Percent point function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_sf",
+    """
+    _nct_sf(x, v, l)
+
+    Survival function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_isf",
+    """
+    _nct_isf(x, v, l)
+
+    Inverse survival function of noncentral t-distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_mean",
+    """
+    _nct_mean(v, l)
+
+    Mean of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_variance",
+    """
+    _nct_variance(v, l)
+
+    Variance of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_skewness",
+    """
+    _nct_skewness(v, l)
+
+    Skewness of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nct_kurtosis_excess",
+    """
+    _nct_kurtosis_excess(v, l)
+
+    Kurtosis excess of noncentral t-distribution.
+
+    Parameters
+    ----------
+    v : array_like
+        Positive, real-valued parameters
+    l : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_skewnorm_cdf",
+    """
+    _skewnorm_cdf(x, l, sc, sh)
+
+    Cumulative density function of skewnorm distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    l : array_like
+        Real-valued parameters
+    sc : array_like
+        Positive, Real-valued parameters
+    sh : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_skewnorm_ppf",
+    """
+    _skewnorm_ppf(x, l, sc, sh)
+
+    Percent point function of skewnorm distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    l : array_like
+        Real-valued parameters
+    sc : array_like
+        Positive, Real-valued parameters
+    sh : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_skewnorm_isf",
+    """
+    _skewnorm_isf(x, l, sc, sh)
+
+    Inverse survival function of skewnorm distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    l : array_like
+        Real-valued parameters
+    sc : array_like
+        Positive, Real-valued parameters
+    sh : array_like
+        Real-valued parameters
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_pmf",
+    """
+    _binom_pmf(x, n, p)
+
+    Probability mass function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_cdf",
+    """
+    _binom_cdf(x, n, p)
+
+    Cumulative density function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_ppf",
+    """
+    _binom_ppf(x, n, p)
+
+    Percent point function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_sf",
+    """
+    _binom_sf(x, n, p)
+
+    Survival function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_binom_isf",
+    """
+    _binom_isf(x, n, p)
+
+    Inverse survival function of binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    n : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_pmf",
+    """
+    _nbinom_pmf(x, r, p)
+
+    Probability mass function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_cdf",
+    """
+    _nbinom_cdf(x, r, p)
+
+    Cumulative density function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_ppf",
+    """
+    _nbinom_ppf(x, r, p)
+
+    Percent point function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_sf",
+    """
+    _nbinom_sf(x, r, p)
+
+    Survival function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_isf",
+    """
+    _nbinom_isf(x, r, p)
+
+    Inverse survival function of negative binomial distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_mean",
+    """
+    _nbinom_mean(r, p)
+
+    Mean of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_variance",
+    """
+    _nbinom_variance(r, p)
+
+    Variance of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_skewness",
+    """
+    _nbinom_skewness(r, p)
+
+    Skewness of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_nbinom_kurtosis_excess",
+    """
+    _nbinom_kurtosis_excess(r, p)
+
+    Kurtosis excess of negative binomial distribution.
+
+    Parameters
+    ----------
+    r : array_like
+        Positive, integer-valued parameter
+    p : array_like
+        Positive, real-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_pmf",
+    """
+    _hypergeom_pmf(x, r, N, M)
+
+    Probability mass function of hypergeometric distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_cdf",
+    """
+    _hypergeom_cdf(x, r, N, M)
+
+    Cumulative density function of hypergeometric distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_hypergeom_sf",
+    """
+    _hypergeom_sf(x, r, N, M)
+
+    Survival function of hypergeometric distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Real-valued
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+    """)
+
+add_newdoc(
+    "_hypergeom_mean",
+    """
+    _hypergeom_mean(r, N, M)
+
+    Mean of hypergeometric distribution.
+
+    Parameters
+    ----------
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_variance",
+    """
+    _hypergeom_variance(r, N, M)
+
+    Mean of hypergeometric distribution.
+
+    Parameters
+    ----------
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
+
+add_newdoc(
+    "_hypergeom_skewness",
+    """
+    _hypergeom_skewness(r, N, M)
+
+    Skewness of hypergeometric distribution.
+
+    Parameters
+    ----------
+    r, N, M : array_like
+        Positive, integer-valued parameter
+
+    Returns
+    -------
+    scalar or ndarray
+
+    """)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..76b13b309eed0c036dd226ff96f0e020f296e032
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_basic.py
@@ -0,0 +1,3579 @@
+#
+# Author:  Travis Oliphant, 2002
+#
+
+import numpy as np
+import math
+import warnings
+from collections import defaultdict
+from heapq import heapify, heappop
+from numpy import (pi, asarray, floor, isscalar, sqrt, where,
+                   sin, place, issubdtype, extract, inexact, nan, zeros, sinc)
+
+from . import _ufuncs
+from ._ufuncs import (mathieu_a, mathieu_b, iv, jv, gamma, rgamma,
+                      psi, hankel1, hankel2, yv, kv, poch, binom,
+                      _stirling2_inexact)
+
+from ._gufuncs import _lqn, _lqmn, _rctj, _rcty
+from ._input_validation import _nonneg_int_or_fail
+from . import _specfun
+from ._comb import _comb_int
+from ._multiufuncs import (assoc_legendre_p_all,
+                           legendre_p_all)
+from scipy._lib.deprecation import _deprecated
+
+
+__all__ = [
+    'ai_zeros',
+    'assoc_laguerre',
+    'bei_zeros',
+    'beip_zeros',
+    'ber_zeros',
+    'bernoulli',
+    'berp_zeros',
+    'bi_zeros',
+    'clpmn',
+    'comb',
+    'digamma',
+    'diric',
+    'erf_zeros',
+    'euler',
+    'factorial',
+    'factorial2',
+    'factorialk',
+    'fresnel_zeros',
+    'fresnelc_zeros',
+    'fresnels_zeros',
+    'h1vp',
+    'h2vp',
+    'ivp',
+    'jn_zeros',
+    'jnjnp_zeros',
+    'jnp_zeros',
+    'jnyn_zeros',
+    'jvp',
+    'kei_zeros',
+    'keip_zeros',
+    'kelvin_zeros',
+    'ker_zeros',
+    'kerp_zeros',
+    'kvp',
+    'lmbda',
+    'lpmn',
+    'lpn',
+    'lqmn',
+    'lqn',
+    'mathieu_even_coef',
+    'mathieu_odd_coef',
+    'obl_cv_seq',
+    'pbdn_seq',
+    'pbdv_seq',
+    'pbvv_seq',
+    'perm',
+    'polygamma',
+    'pro_cv_seq',
+    'riccati_jn',
+    'riccati_yn',
+    'sinc',
+    'softplus',
+    'stirling2',
+    'y0_zeros',
+    'y1_zeros',
+    'y1p_zeros',
+    'yn_zeros',
+    'ynp_zeros',
+    'yvp',
+    'zeta'
+]
+
+
+__DEPRECATION_MSG_1_15 = (
+    "`scipy.special.{}` is deprecated as of SciPy 1.15.0 and will be "
+    "removed in SciPy 1.17.0. Please use `scipy.special.{}` instead."
+)
+
+# mapping k to last n such that factorialk(n, k) < np.iinfo(np.int64).max
+_FACTORIALK_LIMITS_64BITS = {1: 20, 2: 33, 3: 44, 4: 54, 5: 65,
+                             6: 74, 7: 84, 8: 93, 9: 101}
+# mapping k to last n such that factorialk(n, k) < np.iinfo(np.int32).max
+_FACTORIALK_LIMITS_32BITS = {1: 12, 2: 19, 3: 25, 4: 31, 5: 37,
+                             6: 43, 7: 47, 8: 51, 9: 56}
+
+
+def diric(x, n):
+    """Periodic sinc function, also called the Dirichlet function.
+
+    The Dirichlet function is defined as::
+
+        diric(x, n) = sin(x * n/2) / (n * sin(x / 2)),
+
+    where `n` is a positive integer.
+
+    Parameters
+    ----------
+    x : array_like
+        Input data
+    n : int
+        Integer defining the periodicity.
+
+    Returns
+    -------
+    diric : ndarray
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-8*np.pi, 8*np.pi, num=201)
+    >>> plt.figure(figsize=(8, 8));
+    >>> for idx, n in enumerate([2, 3, 4, 9]):
+    ...     plt.subplot(2, 2, idx+1)
+    ...     plt.plot(x, special.diric(x, n))
+    ...     plt.title('diric, n={}'.format(n))
+    >>> plt.show()
+
+    The following example demonstrates that `diric` gives the magnitudes
+    (modulo the sign and scaling) of the Fourier coefficients of a
+    rectangular pulse.
+
+    Suppress output of values that are effectively 0:
+
+    >>> np.set_printoptions(suppress=True)
+
+    Create a signal `x` of length `m` with `k` ones:
+
+    >>> m = 8
+    >>> k = 3
+    >>> x = np.zeros(m)
+    >>> x[:k] = 1
+
+    Use the FFT to compute the Fourier transform of `x`, and
+    inspect the magnitudes of the coefficients:
+
+    >>> np.abs(np.fft.fft(x))
+    array([ 3.        ,  2.41421356,  1.        ,  0.41421356,  1.        ,
+            0.41421356,  1.        ,  2.41421356])
+
+    Now find the same values (up to sign) using `diric`. We multiply
+    by `k` to account for the different scaling conventions of
+    `numpy.fft.fft` and `diric`:
+
+    >>> theta = np.linspace(0, 2*np.pi, m, endpoint=False)
+    >>> k * special.diric(theta, k)
+    array([ 3.        ,  2.41421356,  1.        , -0.41421356, -1.        ,
+           -0.41421356,  1.        ,  2.41421356])
+    """
+    x, n = asarray(x), asarray(n)
+    n = asarray(n + (x-x))
+    x = asarray(x + (n-n))
+    if issubdtype(x.dtype, inexact):
+        ytype = x.dtype
+    else:
+        ytype = float
+    y = zeros(x.shape, ytype)
+
+    # empirical minval for 32, 64 or 128 bit float computations
+    # where sin(x/2) < minval, result is fixed at +1 or -1
+    if np.finfo(ytype).eps < 1e-18:
+        minval = 1e-11
+    elif np.finfo(ytype).eps < 1e-15:
+        minval = 1e-7
+    else:
+        minval = 1e-3
+
+    mask1 = (n <= 0) | (n != floor(n))
+    place(y, mask1, nan)
+
+    x = x / 2
+    denom = sin(x)
+    mask2 = (1-mask1) & (abs(denom) < minval)
+    xsub = extract(mask2, x)
+    nsub = extract(mask2, n)
+    zsub = xsub / pi
+    place(y, mask2, pow(-1, np.round(zsub)*(nsub-1)))
+
+    mask = (1-mask1) & (1-mask2)
+    xsub = extract(mask, x)
+    nsub = extract(mask, n)
+    dsub = extract(mask, denom)
+    place(y, mask, sin(nsub*xsub)/(nsub*dsub))
+    return y
+
+
+def jnjnp_zeros(nt):
+    """Compute zeros of integer-order Bessel functions Jn and Jn'.
+
+    Results are arranged in order of the magnitudes of the zeros.
+
+    Parameters
+    ----------
+    nt : int
+        Number (<=1200) of zeros to compute
+
+    Returns
+    -------
+    zo[l-1] : ndarray
+        Value of the lth zero of Jn(x) and Jn'(x). Of length `nt`.
+    n[l-1] : ndarray
+        Order of the Jn(x) or Jn'(x) associated with lth zero. Of length `nt`.
+    m[l-1] : ndarray
+        Serial number of the zeros of Jn(x) or Jn'(x) associated
+        with lth zero. Of length `nt`.
+    t[l-1] : ndarray
+        0 if lth zero in zo is zero of Jn(x), 1 if it is a zero of Jn'(x). Of
+        length `nt`.
+
+    See Also
+    --------
+    jn_zeros, jnp_zeros : to get separated arrays of zeros.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt > 1200):
+        raise ValueError("Number must be integer <= 1200.")
+    nt = int(nt)
+    n, m, t, zo = _specfun.jdzo(nt)
+    return zo[1:nt+1], n[:nt], m[:nt], t[:nt]
+
+
+def jnyn_zeros(n, nt):
+    """Compute nt zeros of Bessel functions Jn(x), Jn'(x), Yn(x), and Yn'(x).
+
+    Returns 4 arrays of length `nt`, corresponding to the first `nt`
+    zeros of Jn(x), Jn'(x), Yn(x), and Yn'(x), respectively. The zeros
+    are returned in ascending order.
+
+    Parameters
+    ----------
+    n : int
+        Order of the Bessel functions
+    nt : int
+        Number (<=1200) of zeros to compute
+
+    Returns
+    -------
+    Jn : ndarray
+        First `nt` zeros of Jn
+    Jnp : ndarray
+        First `nt` zeros of Jn'
+    Yn : ndarray
+        First `nt` zeros of Yn
+    Ynp : ndarray
+        First `nt` zeros of Yn'
+
+    See Also
+    --------
+    jn_zeros, jnp_zeros, yn_zeros, ynp_zeros
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first three roots of :math:`J_1`, :math:`J_1'`,
+    :math:`Y_1` and :math:`Y_1'`.
+
+    >>> from scipy.special import jnyn_zeros
+    >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3)
+    >>> jn_roots, yn_roots
+    (array([ 3.83170597,  7.01558667, 10.17346814]),
+     array([2.19714133, 5.42968104, 8.59600587]))
+
+    Plot :math:`J_1`, :math:`J_1'`, :math:`Y_1`, :math:`Y_1'` and their roots.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import jnyn_zeros, jvp, jn, yvp, yn
+    >>> jn_roots, jnp_roots, yn_roots, ynp_roots = jnyn_zeros(1, 3)
+    >>> fig, ax = plt.subplots()
+    >>> xmax= 11
+    >>> x = np.linspace(0, xmax)
+    >>> x[0] += 1e-15
+    >>> ax.plot(x, jn(1, x), label=r"$J_1$", c='r')
+    >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$", c='b')
+    >>> ax.plot(x, yn(1, x), label=r"$Y_1$", c='y')
+    >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$", c='c')
+    >>> zeros = np.zeros((3, ))
+    >>> ax.scatter(jn_roots, zeros, s=30, c='r', zorder=5,
+    ...            label=r"$J_1$ roots")
+    >>> ax.scatter(jnp_roots, zeros, s=30, c='b', zorder=5,
+    ...            label=r"$J_1'$ roots")
+    >>> ax.scatter(yn_roots, zeros, s=30, c='y', zorder=5,
+    ...            label=r"$Y_1$ roots")
+    >>> ax.scatter(ynp_roots, zeros, s=30, c='c', zorder=5,
+    ...            label=r"$Y_1'$ roots")
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_ylim(-0.6, 0.6)
+    >>> ax.set_xlim(0, xmax)
+    >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75))
+    >>> plt.tight_layout()
+    >>> plt.show()
+    """
+    if not (isscalar(nt) and isscalar(n)):
+        raise ValueError("Arguments must be scalars.")
+    if (floor(n) != n) or (floor(nt) != nt):
+        raise ValueError("Arguments must be integers.")
+    if (nt <= 0):
+        raise ValueError("nt > 0")
+    return _specfun.jyzo(abs(n), nt)
+
+
+def jn_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel functions Jn.
+
+    Compute `nt` zeros of the Bessel functions :math:`J_n(x)` on the
+    interval :math:`(0, \infty)`. The zeros are returned in ascending
+    order. Note that this interval excludes the zero at :math:`x = 0`
+    that exists for :math:`n > 0`.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel function.
+
+    See Also
+    --------
+    jv: Real-order Bessel functions of the first kind
+    jnp_zeros: Zeros of :math:`Jn'`
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four positive roots of :math:`J_3`.
+
+    >>> from scipy.special import jn_zeros
+    >>> jn_zeros(3, 4)
+    array([ 6.3801619 ,  9.76102313, 13.01520072, 16.22346616])
+
+    Plot :math:`J_3` and its first four positive roots. Note
+    that the root located at 0 is not returned by `jn_zeros`.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import jn, jn_zeros
+    >>> j3_roots = jn_zeros(3, 4)
+    >>> xmax = 18
+    >>> xmin = -1
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, jn(3, x), label=r'$J_3$')
+    >>> ax.scatter(j3_roots, np.zeros((4, )), s=30, c='r',
+    ...            label=r"$J_3$_Zeros", zorder=5)
+    >>> ax.scatter(0, 0, s=30, c='k',
+    ...            label=r"Root at 0", zorder=5)
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[0]
+
+
+def jnp_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel function derivatives Jn'.
+
+    Compute `nt` zeros of the functions :math:`J_n'(x)` on the
+    interval :math:`(0, \infty)`. The zeros are returned in ascending
+    order. Note that this interval excludes the zero at :math:`x = 0`
+    that exists for :math:`n > 1`.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel function.
+
+    See Also
+    --------
+    jvp: Derivatives of integer-order Bessel functions of the first kind
+    jv: Float-order Bessel functions of the first kind
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of :math:`J_2'`.
+
+    >>> from scipy.special import jnp_zeros
+    >>> jnp_zeros(2, 4)
+    array([ 3.05423693,  6.70613319,  9.96946782, 13.17037086])
+
+    As `jnp_zeros` yields the roots of :math:`J_n'`, it can be used to
+    compute the locations of the peaks of :math:`J_n`. Plot
+    :math:`J_2`, :math:`J_2'` and the locations of the roots of :math:`J_2'`.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import jn, jnp_zeros, jvp
+    >>> j2_roots = jnp_zeros(2, 4)
+    >>> xmax = 15
+    >>> x = np.linspace(0, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, jn(2, x), label=r'$J_2$')
+    >>> ax.plot(x, jvp(2, x, 1), label=r"$J_2'$")
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.scatter(j2_roots, np.zeros((4, )), s=30, c='r',
+    ...            label=r"Roots of $J_2'$", zorder=5)
+    >>> ax.set_ylim(-0.4, 0.8)
+    >>> ax.set_xlim(0, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[1]
+
+
+def yn_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel function Yn(x).
+
+    Compute `nt` zeros of the functions :math:`Y_n(x)` on the interval
+    :math:`(0, \infty)`. The zeros are returned in ascending order.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel function.
+
+    See Also
+    --------
+    yn: Bessel function of the second kind for integer order
+    yv: Bessel function of the second kind for real order
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of :math:`Y_2`.
+
+    >>> from scipy.special import yn_zeros
+    >>> yn_zeros(2, 4)
+    array([ 3.38424177,  6.79380751, 10.02347798, 13.20998671])
+
+    Plot :math:`Y_2` and its first four roots.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import yn, yn_zeros
+    >>> xmin = 2
+    >>> xmax = 15
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hlines(0, xmin, xmax, color='k')
+    >>> ax.plot(x, yn(2, x), label=r'$Y_2$')
+    >>> ax.scatter(yn_zeros(2, 4), np.zeros((4, )), s=30, c='r',
+    ...            label='Roots', zorder=5)
+    >>> ax.set_ylim(-0.4, 0.4)
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[2]
+
+
+def ynp_zeros(n, nt):
+    r"""Compute zeros of integer-order Bessel function derivatives Yn'(x).
+
+    Compute `nt` zeros of the functions :math:`Y_n'(x)` on the
+    interval :math:`(0, \infty)`. The zeros are returned in ascending
+    order.
+
+    Parameters
+    ----------
+    n : int
+        Order of Bessel function
+    nt : int
+        Number of zeros to return
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Bessel derivative function.
+
+
+    See Also
+    --------
+    yvp
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of the first derivative of the
+    Bessel function of second kind for order 0 :math:`Y_0'`.
+
+    >>> from scipy.special import ynp_zeros
+    >>> ynp_zeros(0, 4)
+    array([ 2.19714133,  5.42968104,  8.59600587, 11.74915483])
+
+    Plot :math:`Y_0`, :math:`Y_0'` and confirm visually that the roots of
+    :math:`Y_0'` are located at local extrema of :math:`Y_0`.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import yn, ynp_zeros, yvp
+    >>> zeros = ynp_zeros(0, 4)
+    >>> xmax = 13
+    >>> x = np.linspace(0, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, yn(0, x), label=r'$Y_0$')
+    >>> ax.plot(x, yvp(0, x, 1), label=r"$Y_0'$")
+    >>> ax.scatter(zeros, np.zeros((4, )), s=30, c='r',
+    ...            label=r"Roots of $Y_0'$", zorder=5)
+    >>> for root in zeros:
+    ...     y0_extremum =  yn(0, root)
+    ...     lower = min(0, y0_extremum)
+    ...     upper = max(0, y0_extremum)
+    ...     ax.vlines(root, lower, upper, color='r')
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_ylim(-0.6, 0.6)
+    >>> ax.set_xlim(0, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    return jnyn_zeros(n, nt)[3]
+
+
+def y0_zeros(nt, complex=False):
+    """Compute nt zeros of Bessel function Y0(z), and derivative at each zero.
+
+    The derivatives are given by Y0'(z0) = -Y1(z0) at each zero z0.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to return
+    complex : bool, default False
+        Set to False to return only the real zeros; set to True to return only
+        the complex zeros with negative real part and positive imaginary part.
+        Note that the complex conjugates of the latter are also zeros of the
+        function, but are not returned by this routine.
+
+    Returns
+    -------
+    z0n : ndarray
+        Location of nth zero of Y0(z)
+    y0pz0n : ndarray
+        Value of derivative Y0'(z0) for nth zero
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first 4 real roots and the derivatives at the roots of
+    :math:`Y_0`:
+
+    >>> import numpy as np
+    >>> from scipy.special import y0_zeros
+    >>> zeros, grads = y0_zeros(4)
+    >>> with np.printoptions(precision=5):
+    ...     print(f"Roots: {zeros}")
+    ...     print(f"Gradients: {grads}")
+    Roots: [ 0.89358+0.j  3.95768+0.j  7.08605+0.j 10.22235+0.j]
+    Gradients: [-0.87942+0.j  0.40254+0.j -0.3001 +0.j  0.2497 +0.j]
+
+    Plot the real part of :math:`Y_0` and the first four computed roots.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import y0
+    >>> xmin = 0
+    >>> xmax = 11
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hlines(0, xmin, xmax, color='k')
+    >>> ax.plot(x, y0(x), label=r'$Y_0$')
+    >>> zeros, grads = y0_zeros(4)
+    >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r',
+    ...            label=r'$Y_0$_zeros', zorder=5)
+    >>> ax.set_ylim(-0.5, 0.6)
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend(ncol=2)
+    >>> plt.show()
+
+    Compute the first 4 complex roots and the derivatives at the roots of
+    :math:`Y_0` by setting ``complex=True``:
+
+    >>> y0_zeros(4, True)
+    (array([ -2.40301663+0.53988231j,  -5.5198767 +0.54718001j,
+             -8.6536724 +0.54841207j, -11.79151203+0.54881912j]),
+     array([ 0.10074769-0.88196771j, -0.02924642+0.5871695j ,
+             0.01490806-0.46945875j, -0.00937368+0.40230454j]))
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("Arguments must be scalar positive integer.")
+    kf = 0
+    kc = not complex
+    return _specfun.cyzo(nt, kf, kc)
+
+
+def y1_zeros(nt, complex=False):
+    """Compute nt zeros of Bessel function Y1(z), and derivative at each zero.
+
+    The derivatives are given by Y1'(z1) = Y0(z1) at each zero z1.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to return
+    complex : bool, default False
+        Set to False to return only the real zeros; set to True to return only
+        the complex zeros with negative real part and positive imaginary part.
+        Note that the complex conjugates of the latter are also zeros of the
+        function, but are not returned by this routine.
+
+    Returns
+    -------
+    z1n : ndarray
+        Location of nth zero of Y1(z)
+    y1pz1n : ndarray
+        Value of derivative Y1'(z1) for nth zero
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first 4 real roots and the derivatives at the roots of
+    :math:`Y_1`:
+
+    >>> import numpy as np
+    >>> from scipy.special import y1_zeros
+    >>> zeros, grads = y1_zeros(4)
+    >>> with np.printoptions(precision=5):
+    ...     print(f"Roots: {zeros}")
+    ...     print(f"Gradients: {grads}")
+    Roots: [ 2.19714+0.j  5.42968+0.j  8.59601+0.j 11.74915+0.j]
+    Gradients: [ 0.52079+0.j -0.34032+0.j  0.27146+0.j -0.23246+0.j]
+
+    Extract the real parts:
+
+    >>> realzeros = zeros.real
+    >>> realzeros
+    array([ 2.19714133,  5.42968104,  8.59600587, 11.74915483])
+
+    Plot :math:`Y_1` and the first four computed roots.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import y1
+    >>> xmin = 0
+    >>> xmax = 13
+    >>> x = np.linspace(xmin, xmax, 500)
+    >>> zeros, grads = y1_zeros(4)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hlines(0, xmin, xmax, color='k')
+    >>> ax.plot(x, y1(x), label=r'$Y_1$')
+    >>> ax.scatter(zeros.real, np.zeros((4, )), s=30, c='r',
+    ...            label=r'$Y_1$_zeros', zorder=5)
+    >>> ax.set_ylim(-0.5, 0.5)
+    >>> ax.set_xlim(xmin, xmax)
+    >>> plt.legend()
+    >>> plt.show()
+
+    Compute the first 4 complex roots and the derivatives at the roots of
+    :math:`Y_1` by setting ``complex=True``:
+
+    >>> y1_zeros(4, True)
+    (array([ -0.50274327+0.78624371j,  -3.83353519+0.56235654j,
+             -7.01590368+0.55339305j, -10.17357383+0.55127339j]),
+     array([-0.45952768+1.31710194j,  0.04830191-0.69251288j,
+            -0.02012695+0.51864253j,  0.011614  -0.43203296j]))
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("Arguments must be scalar positive integer.")
+    kf = 1
+    kc = not complex
+    return _specfun.cyzo(nt, kf, kc)
+
+
+def y1p_zeros(nt, complex=False):
+    """Compute nt zeros of Bessel derivative Y1'(z), and value at each zero.
+
+    The values are given by Y1(z1) at each z1 where Y1'(z1)=0.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to return
+    complex : bool, default False
+        Set to False to return only the real zeros; set to True to return only
+        the complex zeros with negative real part and positive imaginary part.
+        Note that the complex conjugates of the latter are also zeros of the
+        function, but are not returned by this routine.
+
+    Returns
+    -------
+    z1pn : ndarray
+        Location of nth zero of Y1'(z)
+    y1z1pn : ndarray
+        Value of derivative Y1(z1) for nth zero
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    Compute the first four roots of :math:`Y_1'` and the values of
+    :math:`Y_1` at these roots.
+
+    >>> import numpy as np
+    >>> from scipy.special import y1p_zeros
+    >>> y1grad_roots, y1_values = y1p_zeros(4)
+    >>> with np.printoptions(precision=5):
+    ...     print(f"Y1' Roots: {y1grad_roots.real}")
+    ...     print(f"Y1 values: {y1_values.real}")
+    Y1' Roots: [ 3.68302  6.9415  10.1234  13.28576]
+    Y1 values: [ 0.41673 -0.30317  0.25091 -0.21897]
+
+    `y1p_zeros` can be used to calculate the extremal points of :math:`Y_1`
+    directly. Here we plot :math:`Y_1` and the first four extrema.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.special import y1, yvp
+    >>> y1_roots, y1_values_at_roots = y1p_zeros(4)
+    >>> real_roots = y1_roots.real
+    >>> xmax = 15
+    >>> x = np.linspace(0, xmax, 500)
+    >>> x[0] += 1e-15
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y1(x), label=r'$Y_1$')
+    >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$")
+    >>> ax.scatter(real_roots, np.zeros((4, )), s=30, c='r',
+    ...            label=r"Roots of $Y_1'$", zorder=5)
+    >>> ax.scatter(real_roots, y1_values_at_roots.real, s=30, c='k',
+    ...            label=r"Extrema of $Y_1$", zorder=5)
+    >>> ax.hlines(0, 0, xmax, color='k')
+    >>> ax.set_ylim(-0.5, 0.5)
+    >>> ax.set_xlim(0, xmax)
+    >>> ax.legend(ncol=2, bbox_to_anchor=(1., 0.75))
+    >>> plt.tight_layout()
+    >>> plt.show()
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("Arguments must be scalar positive integer.")
+    kf = 2
+    kc = not complex
+    return _specfun.cyzo(nt, kf, kc)
+
+
+def _bessel_diff_formula(v, z, n, L, phase):
+    # from AMS55.
+    # L(v, z) = J(v, z), Y(v, z), H1(v, z), H2(v, z), phase = -1
+    # L(v, z) = I(v, z) or exp(v*pi*i)K(v, z), phase = 1
+    # For K, you can pull out the exp((v-k)*pi*i) into the caller
+    v = asarray(v)
+    p = 1.0
+    s = L(v-n, z)
+    for i in range(1, n+1):
+        p = phase * (p * (n-i+1)) / i   # = choose(k, i)
+        s += p*L(v-n + i*2, z)
+    return s / (2.**n)
+
+
+def jvp(v, z, n=1):
+    """Compute derivatives of Bessel functions of the first kind.
+
+    Compute the nth derivative of the Bessel function `Jv` with
+    respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like or float
+        Order of Bessel function
+    z : complex
+        Argument at which to evaluate the derivative; can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0 returns the Bessel function `jv` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of the Bessel function.
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+
+    Compute the Bessel function of the first kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import jvp
+    >>> jvp(0, 1, 0), jvp(0, 1, 1), jvp(0, 1, 2)
+    (0.7651976865579666, -0.44005058574493355, -0.3251471008130331)
+
+    Compute the first derivative of the Bessel function of the first
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> jvp([0, 1, 2], 1, 1)
+    array([-0.44005059,  0.3251471 ,  0.21024362])
+
+    Compute the first derivative of the Bessel function of the first
+    kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0., 1.5, 3.])
+    >>> jvp(0, points, 1)
+    array([-0.        , -0.55793651, -0.33905896])
+
+    Plot the Bessel function of the first kind of order 1 and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-10, 10, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, jvp(1, x, 0), label=r"$J_1$")
+    >>> ax.plot(x, jvp(1, x, 1), label=r"$J_1'$")
+    >>> ax.plot(x, jvp(1, x, 2), label=r"$J_1''$")
+    >>> ax.plot(x, jvp(1, x, 3), label=r"$J_1'''$")
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return jv(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, jv, -1)
+
+
+def yvp(v, z, n=1):
+    """Compute derivatives of Bessel functions of the second kind.
+
+    Compute the nth derivative of the Bessel function `Yv` with
+    respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel function
+    z : complex
+        Argument at which to evaluate the derivative
+    n : int, default 1
+        Order of derivative. For 0 returns the BEssel function `yv`
+
+    Returns
+    -------
+    scalar or ndarray
+        nth derivative of the Bessel function.
+
+    See Also
+    --------
+    yv : Bessel functions of the second kind
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+    Compute the Bessel function of the second kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import yvp
+    >>> yvp(0, 1, 0), yvp(0, 1, 1), yvp(0, 1, 2)
+    (0.088256964215677, 0.7812128213002889, -0.8694697855159659)
+
+    Compute the first derivative of the Bessel function of the second
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> yvp([0, 1, 2], 1, 1)
+    array([0.78121282, 0.86946979, 2.52015239])
+
+    Compute the first derivative of the Bessel function of the
+    second kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> yvp(0, points, 1)
+    array([ 1.47147239,  0.41230863, -0.32467442])
+
+    Plot the Bessel function of the second kind of order 1 and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> x[0] += 1e-15
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, yvp(1, x, 0), label=r"$Y_1$")
+    >>> ax.plot(x, yvp(1, x, 1), label=r"$Y_1'$")
+    >>> ax.plot(x, yvp(1, x, 2), label=r"$Y_1''$")
+    >>> ax.plot(x, yvp(1, x, 3), label=r"$Y_1'''$")
+    >>> ax.set_ylim(-10, 10)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return yv(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, yv, -1)
+
+
+def kvp(v, z, n=1):
+    """Compute derivatives of real-order modified Bessel function Kv(z)
+
+    Kv(z) is the modified Bessel function of the second kind.
+    Derivative is calculated with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like of float
+        Order of Bessel function
+    z : array_like of complex
+        Argument at which to evaluate the derivative
+    n : int, default 1
+        Order of derivative. For 0 returns the Bessel function `kv` itself.
+
+    Returns
+    -------
+    out : ndarray
+        The results
+
+    See Also
+    --------
+    kv
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.29.5 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 6.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.29.E5
+
+    Examples
+    --------
+    Compute the modified bessel function of the second kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import kvp
+    >>> kvp(0, 1, 0), kvp(0, 1, 1), kvp(0, 1, 2)
+    (0.42102443824070834, -0.6019072301972346, 1.0229316684379428)
+
+    Compute the first derivative of the modified Bessel function of the second
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> kvp([0, 1, 2], 1, 1)
+    array([-0.60190723, -1.02293167, -3.85158503])
+
+    Compute the first derivative of the modified Bessel function of the
+    second kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> kvp(0, points, 1)
+    array([-1.65644112, -0.2773878 , -0.04015643])
+
+    Plot the modified bessel function of the second kind and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, kvp(1, x, 0), label=r"$K_1$")
+    >>> ax.plot(x, kvp(1, x, 1), label=r"$K_1'$")
+    >>> ax.plot(x, kvp(1, x, 2), label=r"$K_1''$")
+    >>> ax.plot(x, kvp(1, x, 3), label=r"$K_1'''$")
+    >>> ax.set_ylim(-2.5, 2.5)
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return kv(v, z)
+    else:
+        return (-1)**n * _bessel_diff_formula(v, z, n, kv, 1)
+
+
+def ivp(v, z, n=1):
+    """Compute derivatives of modified Bessel functions of the first kind.
+
+    Compute the nth derivative of the modified Bessel function `Iv`
+    with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like or float
+        Order of Bessel function
+    z : array_like
+        Argument at which to evaluate the derivative; can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0, returns the Bessel function `iv` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        nth derivative of the modified Bessel function.
+
+    See Also
+    --------
+    iv
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.29.5 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 6.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.29.E5
+
+    Examples
+    --------
+    Compute the modified Bessel function of the first kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import ivp
+    >>> ivp(0, 1, 0), ivp(0, 1, 1), ivp(0, 1, 2)
+    (1.2660658777520084, 0.565159103992485, 0.7009067737595233)
+
+    Compute the first derivative of the modified Bessel function of the first
+    kind for several orders at 1 by providing an array for `v`.
+
+    >>> ivp([0, 1, 2], 1, 1)
+    array([0.5651591 , 0.70090677, 0.29366376])
+
+    Compute the first derivative of the modified Bessel function of the
+    first kind of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0., 1.5, 3.])
+    >>> ivp(0, points, 1)
+    array([0.        , 0.98166643, 3.95337022])
+
+    Plot the modified Bessel function of the first kind of order 1 and its
+    first three derivatives.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(-5, 5, 1000)
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, ivp(1, x, 0), label=r"$I_1$")
+    >>> ax.plot(x, ivp(1, x, 1), label=r"$I_1'$")
+    >>> ax.plot(x, ivp(1, x, 2), label=r"$I_1''$")
+    >>> ax.plot(x, ivp(1, x, 3), label=r"$I_1'''$")
+    >>> plt.legend()
+    >>> plt.show()
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return iv(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, iv, 1)
+
+
+def h1vp(v, z, n=1):
+    """Compute derivatives of Hankel function H1v(z) with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like
+        Order of Hankel function
+    z : array_like
+        Argument at which to evaluate the derivative. Can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0 returns the Hankel function `h1v` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of the Hankel function.
+
+    See Also
+    --------
+    hankel1
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+    Compute the Hankel function of the first kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import h1vp
+    >>> h1vp(0, 1, 0), h1vp(0, 1, 1), h1vp(0, 1, 2)
+    ((0.7651976865579664+0.088256964215677j),
+     (-0.44005058574493355+0.7812128213002889j),
+     (-0.3251471008130329-0.8694697855159659j))
+
+    Compute the first derivative of the Hankel function of the first kind
+    for several orders at 1 by providing an array for `v`.
+
+    >>> h1vp([0, 1, 2], 1, 1)
+    array([-0.44005059+0.78121282j,  0.3251471 +0.86946979j,
+           0.21024362+2.52015239j])
+
+    Compute the first derivative of the Hankel function of the first kind
+    of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> h1vp(0, points, 1)
+    array([-0.24226846+1.47147239j, -0.55793651+0.41230863j,
+           -0.33905896-0.32467442j])
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return hankel1(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, hankel1, -1)
+
+
+def h2vp(v, z, n=1):
+    """Compute derivatives of Hankel function H2v(z) with respect to `z`.
+
+    Parameters
+    ----------
+    v : array_like
+        Order of Hankel function
+    z : array_like
+        Argument at which to evaluate the derivative. Can be real or
+        complex.
+    n : int, default 1
+        Order of derivative. For 0 returns the Hankel function `h2v` itself.
+
+    Returns
+    -------
+    scalar or ndarray
+        Values of the derivative of the Hankel function.
+
+    See Also
+    --------
+    hankel2
+
+    Notes
+    -----
+    The derivative is computed using the relation DLFM 10.6.7 [2]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 5.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.6.E7
+
+    Examples
+    --------
+    Compute the Hankel function of the second kind of order 0 and
+    its first two derivatives at 1.
+
+    >>> from scipy.special import h2vp
+    >>> h2vp(0, 1, 0), h2vp(0, 1, 1), h2vp(0, 1, 2)
+    ((0.7651976865579664-0.088256964215677j),
+     (-0.44005058574493355-0.7812128213002889j),
+     (-0.3251471008130329+0.8694697855159659j))
+
+    Compute the first derivative of the Hankel function of the second kind
+    for several orders at 1 by providing an array for `v`.
+
+    >>> h2vp([0, 1, 2], 1, 1)
+    array([-0.44005059-0.78121282j,  0.3251471 -0.86946979j,
+           0.21024362-2.52015239j])
+
+    Compute the first derivative of the Hankel function of the second kind
+    of order 0 at several points by providing an array for `z`.
+
+    >>> import numpy as np
+    >>> points = np.array([0.5, 1.5, 3.])
+    >>> h2vp(0, points, 1)
+    array([-0.24226846-1.47147239j, -0.55793651-0.41230863j,
+           -0.33905896+0.32467442j])
+    """
+    n = _nonneg_int_or_fail(n, 'n')
+    if n == 0:
+        return hankel2(v, z)
+    else:
+        return _bessel_diff_formula(v, z, n, hankel2, -1)
+
+
+def riccati_jn(n, x):
+    r"""Compute Ricatti-Bessel function of the first kind and its derivative.
+
+    The Ricatti-Bessel function of the first kind is defined as :math:`x
+    j_n(x)`, where :math:`j_n` is the spherical Bessel function of the first
+    kind of order :math:`n`.
+
+    This function computes the value and first derivative of the
+    Ricatti-Bessel function for all orders up to and including `n`.
+
+    Parameters
+    ----------
+    n : int
+        Maximum order of function to compute
+    x : float
+        Argument at which to evaluate
+
+    Returns
+    -------
+    jn : ndarray
+        Value of j0(x), ..., jn(x)
+    jnp : ndarray
+        First derivative j0'(x), ..., jn'(x)
+
+    Notes
+    -----
+    The computation is carried out via backward recurrence, using the
+    relation DLMF 10.51.1 [2]_.
+
+    Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
+    Jin [1]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.51.E1
+
+    """
+    if not (isscalar(n) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+    if (n == 0):
+        n1 = 1
+    else:
+        n1 = n
+
+    jn = np.empty((n1 + 1,), dtype=np.float64)
+    jnp = np.empty_like(jn)
+
+    _rctj(x, out=(jn, jnp))
+    return jn[:(n+1)], jnp[:(n+1)]
+
+
+def riccati_yn(n, x):
+    """Compute Ricatti-Bessel function of the second kind and its derivative.
+
+    The Ricatti-Bessel function of the second kind is defined here as :math:`+x
+    y_n(x)`, where :math:`y_n` is the spherical Bessel function of the second
+    kind of order :math:`n`. *Note that this is in contrast to a common convention
+    that includes a minus sign in the definition.*
+
+    This function computes the value and first derivative of the function for
+    all orders up to and including `n`.
+
+    Parameters
+    ----------
+    n : int
+        Maximum order of function to compute
+    x : float
+        Argument at which to evaluate
+
+    Returns
+    -------
+    yn : ndarray
+        Value of y0(x), ..., yn(x)
+    ynp : ndarray
+        First derivative y0'(x), ..., yn'(x)
+
+    Notes
+    -----
+    The computation is carried out via ascending recurrence, using the
+    relation DLMF 10.51.1 [2]_.
+
+    Wrapper for a Fortran routine created by Shanjie Zhang and Jianming
+    Jin [1]_.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions.
+           https://dlmf.nist.gov/10.51.E1
+
+    """
+    if not (isscalar(n) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+    if (n == 0):
+        n1 = 1
+    else:
+        n1 = n
+
+    yn = np.empty((n1 + 1,), dtype=np.float64)
+    ynp = np.empty_like(yn)
+    _rcty(x, out=(yn, ynp))
+
+    return yn[:(n+1)], ynp[:(n+1)]
+
+
+def erf_zeros(nt):
+    """Compute the first nt zero in the first quadrant, ordered by absolute value.
+
+    Zeros in the other quadrants can be obtained by using the symmetries
+    erf(-z) = erf(z) and erf(conj(z)) = conj(erf(z)).
+
+
+    Parameters
+    ----------
+    nt : int
+        The number of zeros to compute
+
+    Returns
+    -------
+    The locations of the zeros of erf : ndarray (complex)
+        Complex values at which zeros of erf(z)
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> special.erf_zeros(1)
+    array([1.45061616+1.880943j])
+
+    Check that erf is (close to) zero for the value returned by erf_zeros
+
+    >>> special.erf(special.erf_zeros(1))
+    array([4.95159469e-14-1.16407394e-16j])
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.cerzo(nt)
+
+
+def fresnelc_zeros(nt):
+    """Compute nt complex zeros of cosine Fresnel integral C(z).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    fresnelc_zeros: ndarray
+        Zeros of the cosine Fresnel integral
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.fcszo(1, nt)
+
+
+def fresnels_zeros(nt):
+    """Compute nt complex zeros of sine Fresnel integral S(z).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    fresnels_zeros: ndarray
+        Zeros of the sine Fresnel integral
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.fcszo(2, nt)
+
+
+def fresnel_zeros(nt):
+    """Compute nt complex zeros of sine and cosine Fresnel integrals S(z) and C(z).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    zeros_sine: ndarray
+        Zeros of the sine Fresnel integral
+    zeros_cosine : ndarray
+        Zeros of the cosine Fresnel integral
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if (floor(nt) != nt) or (nt <= 0) or not isscalar(nt):
+        raise ValueError("Argument must be positive scalar integer.")
+    return _specfun.fcszo(2, nt), _specfun.fcszo(1, nt)
+
+
+def assoc_laguerre(x, n, k=0.0):
+    """Compute the generalized (associated) Laguerre polynomial of degree n and order k.
+
+    The polynomial :math:`L^{(k)}_n(x)` is orthogonal over ``[0, inf)``,
+    with weighting function ``exp(-x) * x**k`` with ``k > -1``.
+
+    Parameters
+    ----------
+    x : float or ndarray
+        Points where to evaluate the Laguerre polynomial
+    n : int
+        Degree of the Laguerre polynomial
+    k : int
+        Order of the Laguerre polynomial
+
+    Returns
+    -------
+    assoc_laguerre: float or ndarray
+        Associated laguerre polynomial values
+
+    Notes
+    -----
+    `assoc_laguerre` is a simple wrapper around `eval_genlaguerre`, with
+    reversed argument order ``(x, n, k=0.0) --> (n, k, x)``.
+
+    """
+    return _ufuncs.eval_genlaguerre(n, k, x)
+
+
+digamma = psi
+
+
+def polygamma(n, x):
+    r"""Polygamma functions.
+
+    Defined as :math:`\psi^{(n)}(x)` where :math:`\psi` is the
+    `digamma` function. See [dlmf]_ for details.
+
+    Parameters
+    ----------
+    n : array_like
+        The order of the derivative of the digamma function; must be
+        integral
+    x : array_like
+        Real valued input
+
+    Returns
+    -------
+    ndarray
+        Function results
+
+    See Also
+    --------
+    digamma
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/5.15
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> x = [2, 3, 25.5]
+    >>> special.polygamma(1, x)
+    array([ 0.64493407,  0.39493407,  0.03999467])
+    >>> special.polygamma(0, x) == special.psi(x)
+    array([ True,  True,  True], dtype=bool)
+
+    """
+    n, x = asarray(n), asarray(x)
+    fac2 = (-1.0)**(n+1) * gamma(n+1.0) * zeta(n+1, x)
+    return where(n == 0, psi(x), fac2)
+
+
+def mathieu_even_coef(m, q):
+    r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
+
+    The Fourier series of the even solutions of the Mathieu differential
+    equation are of the form
+
+    .. math:: \mathrm{ce}_{2n}(z, q) = \sum_{k=0}^{\infty} A_{(2n)}^{(2k)} \cos 2kz
+
+    .. math:: \mathrm{ce}_{2n+1}(z, q) =
+              \sum_{k=0}^{\infty} A_{(2n+1)}^{(2k+1)} \cos (2k+1)z
+
+    This function returns the coefficients :math:`A_{(2n)}^{(2k)}` for even
+    input m=2n, and the coefficients :math:`A_{(2n+1)}^{(2k+1)}` for odd input
+    m=2n+1.
+
+    Parameters
+    ----------
+    m : int
+        Order of Mathieu functions.  Must be non-negative.
+    q : float (>=0)
+        Parameter of Mathieu functions.  Must be non-negative.
+
+    Returns
+    -------
+    Ak : ndarray
+        Even or odd Fourier coefficients, corresponding to even or odd m.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/28.4#i
+
+    """
+    if not (isscalar(m) and isscalar(q)):
+        raise ValueError("m and q must be scalars.")
+    if (q < 0):
+        raise ValueError("q >=0")
+    if (m != floor(m)) or (m < 0):
+        raise ValueError("m must be an integer >=0.")
+
+    if (q <= 1):
+        qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
+    else:
+        qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
+    km = int(qm + 0.5*m)
+    if km > 251:
+        warnings.warn("Too many predicted coefficients.", RuntimeWarning, stacklevel=2)
+    kd = 1
+    m = int(floor(m))
+    if m % 2:
+        kd = 2
+
+    a = mathieu_a(m, q)
+    fc = _specfun.fcoef(kd, m, q, a)
+    return fc[:km]
+
+
+def mathieu_odd_coef(m, q):
+    r"""Fourier coefficients for even Mathieu and modified Mathieu functions.
+
+    The Fourier series of the odd solutions of the Mathieu differential
+    equation are of the form
+
+    .. math:: \mathrm{se}_{2n+1}(z, q) =
+              \sum_{k=0}^{\infty} B_{(2n+1)}^{(2k+1)} \sin (2k+1)z
+
+    .. math:: \mathrm{se}_{2n+2}(z, q) =
+              \sum_{k=0}^{\infty} B_{(2n+2)}^{(2k+2)} \sin (2k+2)z
+
+    This function returns the coefficients :math:`B_{(2n+2)}^{(2k+2)}` for even
+    input m=2n+2, and the coefficients :math:`B_{(2n+1)}^{(2k+1)}` for odd
+    input m=2n+1.
+
+    Parameters
+    ----------
+    m : int
+        Order of Mathieu functions.  Must be non-negative.
+    q : float (>=0)
+        Parameter of Mathieu functions.  Must be non-negative.
+
+    Returns
+    -------
+    Bk : ndarray
+        Even or odd Fourier coefficients, corresponding to even or odd m.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(m) and isscalar(q)):
+        raise ValueError("m and q must be scalars.")
+    if (q < 0):
+        raise ValueError("q >=0")
+    if (m != floor(m)) or (m <= 0):
+        raise ValueError("m must be an integer > 0")
+
+    if (q <= 1):
+        qm = 7.5 + 56.1*sqrt(q) - 134.7*q + 90.7*sqrt(q)*q
+    else:
+        qm = 17.0 + 3.1*sqrt(q) - .126*q + .0037*sqrt(q)*q
+    km = int(qm + 0.5*m)
+    if km > 251:
+        warnings.warn("Too many predicted coefficients.", RuntimeWarning, stacklevel=2)
+    kd = 4
+    m = int(floor(m))
+    if m % 2:
+        kd = 3
+
+    b = mathieu_b(m, q)
+    fc = _specfun.fcoef(kd, m, q, b)
+    return fc[:km]
+
+
+@_deprecated(__DEPRECATION_MSG_1_15.format("lpmn", "assoc_legendre_p_all"))
+def lpmn(m, n, z):
+    """Sequence of associated Legendre functions of the first kind.
+
+    Computes the associated Legendre function of the first kind of order m and
+    degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
+    Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
+    ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
+
+    This function takes a real argument ``z``. For complex arguments ``z``
+    use clpmn instead.
+
+    .. deprecated:: 1.15.0
+        This function is deprecated and will be removed in SciPy 1.17.0.
+        Please `scipy.special.assoc_legendre_p_all` instead.
+
+    Parameters
+    ----------
+    m : int
+       ``|m| <= n``; the order of the Legendre function.
+    n : int
+       where ``n >= 0``; the degree of the Legendre function.  Often
+       called ``l`` (lower case L) in descriptions of the associated
+       Legendre function
+    z : array_like
+        Input value.
+
+    Returns
+    -------
+    Pmn_z : (m+1, n+1) array
+       Values for all orders 0..m and degrees 0..n
+    Pmn_d_z : (m+1, n+1) array
+       Derivatives for all orders 0..m and degrees 0..n
+
+    See Also
+    --------
+    clpmn: associated Legendre functions of the first kind for complex z
+
+    Notes
+    -----
+    In the interval (-1, 1), Ferrer's function of the first kind is
+    returned. The phase convention used for the intervals (1, inf)
+    and (-inf, -1) is such that the result is always real.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/14.3
+
+    """
+
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+
+    if (abs(m) > n):
+        raise ValueError("m must be <= n.")
+
+    if np.iscomplexobj(z):
+        raise ValueError("Argument must be real. Use clpmn instead.")
+
+    m, n = int(m), int(n)  # Convert to int to maintain backwards compatibility.
+
+    branch_cut = np.where(np.abs(z) <= 1, 2, 3)
+
+    p, pd = assoc_legendre_p_all(n, abs(m), z, branch_cut=branch_cut, diff_n=1)
+    p = np.swapaxes(p, 0, 1)
+    pd = np.swapaxes(pd, 0, 1)
+
+    if (m >= 0):
+        p = p[:(m + 1)]
+        pd = pd[:(m + 1)]
+    else:
+        p = np.insert(p[:(m - 1):-1], 0, p[0], axis=0)
+        pd = np.insert(pd[:(m - 1):-1], 0, pd[0], axis=0)
+
+    return p, pd
+
+
+@_deprecated(__DEPRECATION_MSG_1_15.format("clpmn", "assoc_legendre_p_all"))
+def clpmn(m, n, z, type=3):
+    """Associated Legendre function of the first kind for complex arguments.
+
+    Computes the associated Legendre function of the first kind of order m and
+    degree n, ``Pmn(z)`` = :math:`P_n^m(z)`, and its derivative, ``Pmn'(z)``.
+    Returns two arrays of size ``(m+1, n+1)`` containing ``Pmn(z)`` and
+    ``Pmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
+
+    .. deprecated:: 1.15.0
+        This function is deprecated and will be removed in SciPy 1.17.0.
+        Please use `scipy.special.assoc_legendre_p_all` instead.
+
+    Parameters
+    ----------
+    m : int
+       ``|m| <= n``; the order of the Legendre function.
+    n : int
+       where ``n >= 0``; the degree of the Legendre function.  Often
+       called ``l`` (lower case L) in descriptions of the associated
+       Legendre function
+    z : array_like, float or complex
+        Input value.
+    type : int, optional
+       takes values 2 or 3
+       2: cut on the real axis ``|x| > 1``
+       3: cut on the real axis ``-1 < x < 1`` (default)
+
+    Returns
+    -------
+    Pmn_z : (m+1, n+1) array
+       Values for all orders ``0..m`` and degrees ``0..n``
+    Pmn_d_z : (m+1, n+1) array
+       Derivatives for all orders ``0..m`` and degrees ``0..n``
+
+    See Also
+    --------
+    lpmn: associated Legendre functions of the first kind for real z
+
+    Notes
+    -----
+    By default, i.e. for ``type=3``, phase conventions are chosen according
+    to [1]_ such that the function is analytic. The cut lies on the interval
+    (-1, 1). Approaching the cut from above or below in general yields a phase
+    factor with respect to Ferrer's function of the first kind
+    (cf. `lpmn`).
+
+    For ``type=2`` a cut at ``|x| > 1`` is chosen. Approaching the real values
+    on the interval (-1, 1) in the complex plane yields Ferrer's function
+    of the first kind.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] NIST Digital Library of Mathematical Functions
+           https://dlmf.nist.gov/14.21
+
+    """
+
+    if (abs(m) > n):
+        raise ValueError("m must be <= n.")
+
+    if not (type == 2 or type == 3):
+        raise ValueError("type must be either 2 or 3.")
+
+    m, n = int(m), int(n)  # Convert to int to maintain backwards compatibility.
+
+    if not np.iscomplexobj(z):
+        z = np.asarray(z, dtype=complex)
+
+    out, out_jac = assoc_legendre_p_all(n, abs(m), z, branch_cut=type, diff_n=1)
+    out = np.swapaxes(out, 0, 1)
+    out_jac = np.swapaxes(out_jac, 0, 1)
+
+    if (m >= 0):
+        out = out[:(m + 1)]
+        out_jac = out_jac[:(m + 1)]
+    else:
+        out = np.insert(out[:(m - 1):-1], 0, out[0], axis=0)
+        out_jac = np.insert(out_jac[:(m - 1):-1], 0, out_jac[0], axis=0)
+
+    return out, out_jac
+
+
+def lqmn(m, n, z):
+    """Sequence of associated Legendre functions of the second kind.
+
+    Computes the associated Legendre function of the second kind of order m and
+    degree n, ``Qmn(z)`` = :math:`Q_n^m(z)`, and its derivative, ``Qmn'(z)``.
+    Returns two arrays of size ``(m+1, n+1)`` containing ``Qmn(z)`` and
+    ``Qmn'(z)`` for all orders from ``0..m`` and degrees from ``0..n``.
+
+    Parameters
+    ----------
+    m : int
+       ``|m| <= n``; the order of the Legendre function.
+    n : int
+       where ``n >= 0``; the degree of the Legendre function.  Often
+       called ``l`` (lower case L) in descriptions of the associated
+       Legendre function
+    z : array_like, complex
+        Input value.
+
+    Returns
+    -------
+    Qmn_z : (m+1, n+1) array
+       Values for all orders 0..m and degrees 0..n
+    Qmn_d_z : (m+1, n+1) array
+       Derivatives for all orders 0..m and degrees 0..n
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(m) or (m < 0):
+        raise ValueError("m must be a non-negative integer.")
+    if not isscalar(n) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+
+    m, n = int(m), int(n)  # Convert to int to maintain backwards compatibility.
+    # Ensure neither m nor n == 0
+    mm = max(1, m)
+    nn = max(1, n)
+
+    z = np.asarray(z)
+    if (not np.issubdtype(z.dtype, np.inexact)):
+        z = z.astype(np.float64)
+
+    if np.iscomplexobj(z):
+        q = np.empty((mm + 1, nn + 1) + z.shape, dtype=np.complex128)
+    else:
+        q = np.empty((mm + 1, nn + 1) + z.shape, dtype=np.float64)
+    qd = np.empty_like(q)
+    if (z.ndim == 0):
+        _lqmn(z, out=(q, qd))
+    else:
+        # new axes must be last for the ufunc
+        _lqmn(z,
+              out=(np.moveaxis(q, (0, 1), (-2, -1)),
+                   np.moveaxis(qd, (0, 1), (-2, -1))))
+
+    return q[:(m+1), :(n+1)], qd[:(m+1), :(n+1)]
+
+
+def bernoulli(n):
+    """Bernoulli numbers B0..Bn (inclusive).
+
+    Parameters
+    ----------
+    n : int
+        Indicated the number of terms in the Bernoulli series to generate.
+
+    Returns
+    -------
+    ndarray
+        The Bernoulli numbers ``[B(0), B(1), ..., B(n)]``.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] "Bernoulli number", Wikipedia, https://en.wikipedia.org/wiki/Bernoulli_number
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import bernoulli, zeta
+    >>> bernoulli(4)
+    array([ 1.        , -0.5       ,  0.16666667,  0.        , -0.03333333])
+
+    The Wikipedia article ([2]_) points out the relationship between the
+    Bernoulli numbers and the zeta function, ``B_n^+ = -n * zeta(1 - n)``
+    for ``n > 0``:
+
+    >>> n = np.arange(1, 5)
+    >>> -n * zeta(1 - n)
+    array([ 0.5       ,  0.16666667, -0.        , -0.03333333])
+
+    Note that, in the notation used in the wikipedia article,
+    `bernoulli` computes ``B_n^-`` (i.e. it used the convention that
+    ``B_1`` is -1/2).  The relation given above is for ``B_n^+``, so the
+    sign of 0.5 does not match the output of ``bernoulli(4)``.
+
+    """
+    if not isscalar(n) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+    n = int(n)
+    if (n < 2):
+        n1 = 2
+    else:
+        n1 = n
+    return _specfun.bernob(int(n1))[:(n+1)]
+
+
+def euler(n):
+    """Euler numbers E(0), E(1), ..., E(n).
+
+    The Euler numbers [1]_ are also known as the secant numbers.
+
+    Because ``euler(n)`` returns floating point values, it does not give
+    exact values for large `n`.  The first inexact value is E(22).
+
+    Parameters
+    ----------
+    n : int
+        The highest index of the Euler number to be returned.
+
+    Returns
+    -------
+    ndarray
+        The Euler numbers [E(0), E(1), ..., E(n)].
+        The odd Euler numbers, which are all zero, are included.
+
+    References
+    ----------
+    .. [1] Sequence A122045, The On-Line Encyclopedia of Integer Sequences,
+           https://oeis.org/A122045
+    .. [2] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import euler
+    >>> euler(6)
+    array([  1.,   0.,  -1.,   0.,   5.,   0., -61.])
+
+    >>> euler(13).astype(np.int64)
+    array([      1,       0,      -1,       0,       5,       0,     -61,
+                 0,    1385,       0,  -50521,       0, 2702765,       0])
+
+    >>> euler(22)[-1]  # Exact value of E(22) is -69348874393137901.
+    -69348874393137976.0
+
+    """
+    if not isscalar(n) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+    n = int(n)
+    if (n < 2):
+        n1 = 2
+    else:
+        n1 = n
+    return _specfun.eulerb(n1)[:(n+1)]
+
+
+@_deprecated(__DEPRECATION_MSG_1_15.format("lpn", "legendre_p_all"))
+def lpn(n, z):
+    """Legendre function of the first kind.
+
+    Compute sequence of Legendre functions of the first kind (polynomials),
+    Pn(z) and derivatives for all degrees from 0 to n (inclusive).
+
+    See also special.legendre for polynomial class.
+
+    .. deprecated:: 1.15.0
+        This function is deprecated and will be removed in SciPy 1.17.0.
+        Please use `scipy.special.legendre_p_all` instead.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    """
+
+    return legendre_p_all(n, z, diff_n=1)
+
+
+def lqn(n, z):
+    """Legendre function of the second kind.
+
+    Compute sequence of Legendre functions of the second kind, Qn(z) and
+    derivatives for all degrees from 0 to n (inclusive).
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+    if (n < 1):
+        n1 = 1
+    else:
+        n1 = n
+
+    z = np.asarray(z)
+    if (not np.issubdtype(z.dtype, np.inexact)):
+        z = z.astype(float)
+
+    if np.iscomplexobj(z):
+        qn = np.empty((n1 + 1,) + z.shape, dtype=np.complex128)
+    else:
+        qn = np.empty((n1 + 1,) + z.shape, dtype=np.float64)
+    qd = np.empty_like(qn)
+    if (z.ndim == 0):
+        _lqn(z, out=(qn, qd))
+    else:
+          # new axes must be last for the ufunc
+        _lqn(z,
+             out=(np.moveaxis(qn, 0, -1),
+                  np.moveaxis(qd, 0, -1)))
+
+    return qn[:(n+1)], qd[:(n+1)]
+
+
+def ai_zeros(nt):
+    """
+    Compute `nt` zeros and values of the Airy function Ai and its derivative.
+
+    Computes the first `nt` zeros, `a`, of the Airy function Ai(x);
+    first `nt` zeros, `ap`, of the derivative of the Airy function Ai'(x);
+    the corresponding values Ai(a');
+    and the corresponding values Ai'(a).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    a : ndarray
+        First `nt` zeros of Ai(x)
+    ap : ndarray
+        First `nt` zeros of Ai'(x)
+    ai : ndarray
+        Values of Ai(x) evaluated at first `nt` zeros of Ai'(x)
+    aip : ndarray
+        Values of Ai'(x) evaluated at first `nt` zeros of Ai(x)
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> a, ap, ai, aip = special.ai_zeros(3)
+    >>> a
+    array([-2.33810741, -4.08794944, -5.52055983])
+    >>> ap
+    array([-1.01879297, -3.24819758, -4.82009921])
+    >>> ai
+    array([ 0.53565666, -0.41901548,  0.38040647])
+    >>> aip
+    array([ 0.70121082, -0.80311137,  0.86520403])
+
+    """
+    kf = 1
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be a positive integer scalar.")
+    return _specfun.airyzo(nt, kf)
+
+
+def bi_zeros(nt):
+    """
+    Compute `nt` zeros and values of the Airy function Bi and its derivative.
+
+    Computes the first `nt` zeros, b, of the Airy function Bi(x);
+    first `nt` zeros, b', of the derivative of the Airy function Bi'(x);
+    the corresponding values Bi(b');
+    and the corresponding values Bi'(b).
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute
+
+    Returns
+    -------
+    b : ndarray
+        First `nt` zeros of Bi(x)
+    bp : ndarray
+        First `nt` zeros of Bi'(x)
+    bi : ndarray
+        Values of Bi(x) evaluated at first `nt` zeros of Bi'(x)
+    bip : ndarray
+        Values of Bi'(x) evaluated at first `nt` zeros of Bi(x)
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> b, bp, bi, bip = special.bi_zeros(3)
+    >>> b
+    array([-1.17371322, -3.2710933 , -4.83073784])
+    >>> bp
+    array([-2.29443968, -4.07315509, -5.51239573])
+    >>> bi
+    array([-0.45494438,  0.39652284, -0.36796916])
+    >>> bip
+    array([ 0.60195789, -0.76031014,  0.83699101])
+
+    """
+    kf = 2
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be a positive integer scalar.")
+    return _specfun.airyzo(nt, kf)
+
+
+def lmbda(v, x):
+    r"""Jahnke-Emden Lambda function, Lambdav(x).
+
+    This function is defined as [2]_,
+
+    .. math:: \Lambda_v(x) = \Gamma(v+1) \frac{J_v(x)}{(x/2)^v},
+
+    where :math:`\Gamma` is the gamma function and :math:`J_v` is the
+    Bessel function of the first kind.
+
+    Parameters
+    ----------
+    v : float
+        Order of the Lambda function
+    x : float
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    vl : ndarray
+        Values of Lambda_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+    dl : ndarray
+        Derivatives Lambda_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    .. [2] Jahnke, E. and Emde, F. "Tables of Functions with Formulae and
+           Curves" (4th ed.), Dover, 1945
+    """
+    if not (isscalar(v) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    if (v < 0):
+        raise ValueError("argument must be > 0.")
+    n = int(v)
+    v0 = v - n
+    if (n < 1):
+        n1 = 1
+    else:
+        n1 = n
+    v1 = n1 + v0
+    if (v != floor(v)):
+        vm, vl, dl = _specfun.lamv(v1, x)
+    else:
+        vm, vl, dl = _specfun.lamn(v1, x)
+    return vl[:(n+1)], dl[:(n+1)]
+
+
+def pbdv_seq(v, x):
+    """Parabolic cylinder functions Dv(x) and derivatives.
+
+    Parameters
+    ----------
+    v : float
+        Order of the parabolic cylinder function
+    x : float
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    dv : ndarray
+        Values of D_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+    dp : ndarray
+        Derivatives D_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 13.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(v) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = int(v)
+    v0 = v-n
+    if (n < 1):
+        n1 = 1
+    else:
+        n1 = n
+    v1 = n1 + v0
+    dv, dp, pdf, pdd = _specfun.pbdv(v1, x)
+    return dv[:n1+1], dp[:n1+1]
+
+
+def pbvv_seq(v, x):
+    """Parabolic cylinder functions Vv(x) and derivatives.
+
+    Parameters
+    ----------
+    v : float
+        Order of the parabolic cylinder function
+    x : float
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    dv : ndarray
+        Values of V_vi(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+    dp : ndarray
+        Derivatives V_vi'(x), for vi=v-int(v), vi=1+v-int(v), ..., vi=v.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 13.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(v) and isscalar(x)):
+        raise ValueError("arguments must be scalars.")
+    n = int(v)
+    v0 = v-n
+    if (n <= 1):
+        n1 = 1
+    else:
+        n1 = n
+    v1 = n1 + v0
+    dv, dp, pdf, pdd = _specfun.pbvv(v1, x)
+    return dv[:n1+1], dp[:n1+1]
+
+
+def pbdn_seq(n, z):
+    """Parabolic cylinder functions Dn(z) and derivatives.
+
+    Parameters
+    ----------
+    n : int
+        Order of the parabolic cylinder function
+    z : complex
+        Value at which to evaluate the function and derivatives
+
+    Returns
+    -------
+    dv : ndarray
+        Values of D_i(z), for i=0, ..., i=n.
+    dp : ndarray
+        Derivatives D_i'(z), for i=0, ..., i=n.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996, chapter 13.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(n) and isscalar(z)):
+        raise ValueError("arguments must be scalars.")
+    if (floor(n) != n):
+        raise ValueError("n must be an integer.")
+    if (abs(n) <= 1):
+        n1 = 1
+    else:
+        n1 = n
+    cpb, cpd = _specfun.cpbdn(n1, z)
+    return cpb[:n1+1], cpd[:n1+1]
+
+
+def ber_zeros(nt):
+    """Compute nt zeros of the Kelvin function ber.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    ber
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 1)
+
+
+def bei_zeros(nt):
+    """Compute nt zeros of the Kelvin function bei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    bei
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 2)
+
+
+def ker_zeros(nt):
+    """Compute nt zeros of the Kelvin function ker.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    ker
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 3)
+
+
+def kei_zeros(nt):
+    """Compute nt zeros of the Kelvin function kei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the Kelvin function.
+
+    See Also
+    --------
+    kei
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 4)
+
+
+def berp_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function ber.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    ber, berp
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+
+    Examples
+    --------
+    Compute the first 5 zeros of the derivative of the Kelvin function.
+
+    >>> from scipy.special import berp_zeros
+    >>> berp_zeros(5)
+    array([ 6.03871081, 10.51364251, 14.96844542, 19.41757493, 23.86430432])
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 5)
+
+
+def beip_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function bei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    bei, beip
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 6)
+
+
+def kerp_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function ker.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    ker, kerp
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 7)
+
+
+def keip_zeros(nt):
+    """Compute nt zeros of the derivative of the Kelvin function kei.
+
+    Parameters
+    ----------
+    nt : int
+        Number of zeros to compute. Must be positive.
+
+    Returns
+    -------
+    ndarray
+        First `nt` zeros of the derivative of the Kelvin function.
+
+    See Also
+    --------
+    kei, keip
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return _specfun.klvnzo(nt, 8)
+
+
+def kelvin_zeros(nt):
+    """Compute nt zeros of all Kelvin functions.
+
+    Returned in a length-8 tuple of arrays of length nt.  The tuple contains
+    the arrays of zeros of (ber, bei, ker, kei, ber', bei', ker', kei').
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0):
+        raise ValueError("nt must be positive integer scalar.")
+    return (_specfun.klvnzo(nt, 1),
+            _specfun.klvnzo(nt, 2),
+            _specfun.klvnzo(nt, 3),
+            _specfun.klvnzo(nt, 4),
+            _specfun.klvnzo(nt, 5),
+            _specfun.klvnzo(nt, 6),
+            _specfun.klvnzo(nt, 7),
+            _specfun.klvnzo(nt, 8))
+
+
+def pro_cv_seq(m, n, c):
+    """Characteristic values for prolate spheroidal wave functions.
+
+    Compute a sequence of characteristic values for the prolate
+    spheroidal wave functions for mode m and n'=m..n and spheroidal
+    parameter c.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(m) and isscalar(n) and isscalar(c)):
+        raise ValueError("Arguments must be scalars.")
+    if (n != floor(n)) or (m != floor(m)):
+        raise ValueError("Modes must be integers.")
+    if (n-m > 199):
+        raise ValueError("Difference between n and m is too large.")
+    maxL = n-m+1
+    return _specfun.segv(m, n, c, 1)[1][:maxL]
+
+
+def obl_cv_seq(m, n, c):
+    """Characteristic values for oblate spheroidal wave functions.
+
+    Compute a sequence of characteristic values for the oblate
+    spheroidal wave functions for mode m and n'=m..n and spheroidal
+    parameter c.
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+
+    """
+    if not (isscalar(m) and isscalar(n) and isscalar(c)):
+        raise ValueError("Arguments must be scalars.")
+    if (n != floor(n)) or (m != floor(m)):
+        raise ValueError("Modes must be integers.")
+    if (n-m > 199):
+        raise ValueError("Difference between n and m is too large.")
+    maxL = n-m+1
+    return _specfun.segv(m, n, c, -1)[1][:maxL]
+
+
+def comb(N, k, *, exact=False, repetition=False):
+    """The number of combinations of N things taken k at a time.
+
+    This is often expressed as "N choose k".
+
+    Parameters
+    ----------
+    N : int, ndarray
+        Number of things.
+    k : int, ndarray
+        Number of elements taken.
+    exact : bool, optional
+        For integers, if `exact` is False, then floating point precision is
+        used, otherwise the result is computed exactly.
+
+        .. deprecated:: 1.14.0
+            ``exact=True`` is deprecated for non-integer `N` and `k` and will raise an
+            error in SciPy 1.16.0
+    repetition : bool, optional
+        If `repetition` is True, then the number of combinations with
+        repetition is computed.
+
+    Returns
+    -------
+    val : int, float, ndarray
+        The total number of combinations.
+
+    See Also
+    --------
+    binom : Binomial coefficient considered as a function of two real
+            variables.
+
+    Notes
+    -----
+    - Array arguments accepted only for exact=False case.
+    - If N < 0, or k < 0, then 0 is returned.
+    - If k > N and repetition=False, then 0 is returned.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import comb
+    >>> k = np.array([3, 4])
+    >>> n = np.array([10, 10])
+    >>> comb(n, k, exact=False)
+    array([ 120.,  210.])
+    >>> comb(10, 3, exact=True)
+    120
+    >>> comb(10, 3, exact=True, repetition=True)
+    220
+
+    """
+    if repetition:
+        return comb(N + k - 1, k, exact=exact)
+    if exact:
+        if int(N) == N and int(k) == k:
+            # _comb_int casts inputs to integers, which is safe & intended here
+            return _comb_int(N, k)
+        # otherwise, we disregard `exact=True`; it makes no sense for
+        # non-integral arguments
+        msg = ("`exact=True` is deprecated for non-integer `N` and `k` and will raise "
+               "an error in SciPy 1.16.0")
+        warnings.warn(msg, DeprecationWarning, stacklevel=2)
+        return comb(N, k)
+    else:
+        k, N = asarray(k), asarray(N)
+        cond = (k <= N) & (N >= 0) & (k >= 0)
+        vals = binom(N, k)
+        if isinstance(vals, np.ndarray):
+            vals[~cond] = 0
+        elif not cond:
+            vals = np.float64(0)
+        return vals
+
+
+def perm(N, k, exact=False):
+    """Permutations of N things taken k at a time, i.e., k-permutations of N.
+
+    It's also known as "partial permutations".
+
+    Parameters
+    ----------
+    N : int, ndarray
+        Number of things.
+    k : int, ndarray
+        Number of elements taken.
+    exact : bool, optional
+        If ``True``, calculate the answer exactly using long integer arithmetic (`N`
+        and `k` must be scalar integers). If ``False``, a floating point approximation
+        is calculated (more rapidly) using `poch`. Default is ``False``.
+
+    Returns
+    -------
+    val : int, ndarray
+        The number of k-permutations of N.
+
+    Notes
+    -----
+    - Array arguments accepted only for exact=False case.
+    - If k > N, N < 0, or k < 0, then a 0 is returned.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import perm
+    >>> k = np.array([3, 4])
+    >>> n = np.array([10, 10])
+    >>> perm(n, k)
+    array([  720.,  5040.])
+    >>> perm(10, 3, exact=True)
+    720
+
+    """
+    if exact:
+        N = np.squeeze(N)[()]  # for backward compatibility (accepted size 1 arrays)
+        k = np.squeeze(k)[()]
+        if not (isscalar(N) and isscalar(k)):
+            raise ValueError("`N` and `k` must scalar integers be with `exact=True`.")
+
+        floor_N, floor_k = int(N), int(k)
+        non_integral = not (floor_N == N and floor_k == k)
+        if (k > N) or (N < 0) or (k < 0):
+            if non_integral:
+                msg = ("Non-integer `N` and `k` with `exact=True` is deprecated and "
+                       "will raise an error in SciPy 1.16.0.")
+                warnings.warn(msg, DeprecationWarning, stacklevel=2)
+            return 0
+        if non_integral:
+            raise ValueError("Non-integer `N` and `k` with `exact=True` is not "
+                             "supported.")
+        val = 1
+        for i in range(floor_N - floor_k + 1, floor_N + 1):
+            val *= i
+        return val
+    else:
+        k, N = asarray(k), asarray(N)
+        cond = (k <= N) & (N >= 0) & (k >= 0)
+        vals = poch(N - k + 1, k)
+        if isinstance(vals, np.ndarray):
+            vals[~cond] = 0
+        elif not cond:
+            vals = np.float64(0)
+        return vals
+
+
+# https://stackoverflow.com/a/16327037
+def _range_prod(lo, hi, k=1):
+    """
+    Product of a range of numbers spaced k apart (from hi).
+
+    For k=1, this returns the product of
+    lo * (lo+1) * (lo+2) * ... * (hi-2) * (hi-1) * hi
+    = hi! / (lo-1)!
+
+    For k>1, it correspond to taking only every k'th number when
+    counting down from hi - e.g. 18!!!! = _range_prod(1, 18, 4).
+
+    Breaks into smaller products first for speed:
+    _range_prod(2, 9) = ((2*3)*(4*5))*((6*7)*(8*9))
+    """
+    if lo == 1 and k == 1:
+        return math.factorial(hi)
+
+    if lo + k < hi:
+        mid = (hi + lo) // 2
+        if k > 1:
+            # make sure mid is a multiple of k away from hi
+            mid = mid - ((mid - hi) % k)
+        return _range_prod(lo, mid, k) * _range_prod(mid + k, hi, k)
+    elif lo + k == hi:
+        return lo * hi
+    else:
+        return hi
+
+
+def _factorialx_array_exact(n, k=1):
+    """
+    Exact computation of factorial for an array.
+
+    The factorials are computed in incremental fashion, by taking
+    the sorted unique values of n and multiplying the intervening
+    numbers between the different unique values.
+
+    In other words, the factorial for the largest input is only
+    computed once, with each other result computed in the process.
+
+    k > 1 corresponds to the multifactorial.
+    """
+    un = np.unique(n)
+    # numpy changed nan-sorting behaviour with 1.21, see numpy/numpy#18070;
+    # to unify the behaviour, we remove the nan's here; the respective
+    # values will be set separately at the end
+    un = un[~np.isnan(un)]
+
+    # Convert to object array if np.int64 can't handle size
+    if np.isnan(n).any():
+        dt = float
+    elif k in _FACTORIALK_LIMITS_64BITS.keys():
+        if un[-1] > _FACTORIALK_LIMITS_64BITS[k]:
+            # e.g. k=1: 21! > np.iinfo(np.int64).max
+            dt = object
+        elif un[-1] > _FACTORIALK_LIMITS_32BITS[k]:
+            # e.g. k=3: 26!!! > np.iinfo(np.int32).max
+            dt = np.int64
+        else:
+            dt = np.dtype("long")
+    else:
+        # for k >= 10, we always use object
+        dt = object
+
+    out = np.empty_like(n, dtype=dt)
+
+    # Handle invalid/trivial values
+    un = un[un > 1]
+    out[n < 2] = 1
+    out[n < 0] = 0
+
+    # Calculate products of each range of numbers
+    # we can only multiply incrementally if the values are k apart;
+    # therefore we partition `un` into "lanes", i.e. its residues modulo k
+    for lane in range(0, k):
+        ul = un[(un % k) == lane] if k > 1 else un
+        if ul.size:
+            # after np.unique, un resp. ul are sorted, ul[0] is the smallest;
+            # cast to python ints to avoid overflow with np.int-types
+            val = _range_prod(1, int(ul[0]), k=k)
+            out[n == ul[0]] = val
+            for i in range(len(ul) - 1):
+                # by the filtering above, we have ensured that prev & current
+                # are a multiple of k apart
+                prev = ul[i]
+                current = ul[i + 1]
+                # we already multiplied all factors until prev; continue
+                # building the full factorial from the following (`prev + 1`);
+                # use int() for the same reason as above
+                val *= _range_prod(int(prev + 1), int(current), k=k)
+                out[n == current] = val
+
+    if np.isnan(n).any():
+        out = out.astype(np.float64)
+        out[np.isnan(n)] = np.nan
+    return out
+
+
+def _factorialx_array_approx(n, k, extend):
+    """
+    Calculate approximation to multifactorial for array n and integer k.
+
+    Ensure that values aren't calculated unnecessarily.
+    """
+    if extend == "complex":
+        return _factorialx_approx_core(n, k=k, extend=extend)
+
+    # at this point we are guaranteed that extend='zero' and that k>0 is an integer
+    result = zeros(n.shape)
+    # keep nans as nans
+    place(result, np.isnan(n), np.nan)
+    # only compute where n >= 0 (excludes nans), everything else is 0
+    cond = (n >= 0)
+    n_to_compute = extract(cond, n)
+    place(result, cond, _factorialx_approx_core(n_to_compute, k=k, extend=extend))
+    return result
+
+
+def _gamma1p(vals):
+    """
+    returns gamma(n+1), though with NaN at -1 instead of inf, c.f. #21827
+    """
+    res = gamma(vals + 1)
+    # replace infinities at -1 (from gamma function at 0) with nan
+    # gamma only returns inf for real inputs; can ignore complex case
+    if isinstance(res, np.ndarray):
+        if not _is_subdtype(vals.dtype, "c"):
+            res[vals == -1] = np.nan
+    elif np.isinf(res) and vals == -1:
+        res = np.float64("nan")
+    return res
+
+
+def _factorialx_approx_core(n, k, extend):
+    """
+    Core approximation to multifactorial for array n and integer k.
+    """
+    if k == 1:
+        # shortcut for k=1; same for both extensions, because we assume the
+        # handling of extend == 'zero' happens in _factorialx_array_approx
+        result = _gamma1p(n)
+        if isinstance(n, np.ndarray):
+            # gamma does not maintain 0-dim arrays; fix it
+            result = np.array(result)
+        return result
+
+    if extend == "complex":
+        # see https://numpy.org/doc/stable/reference/generated/numpy.power.html
+        p_dtype = complex if (_is_subdtype(type(k), "c") or k < 0) else None
+        with warnings.catch_warnings():
+            # do not warn about 0 * inf, nan / nan etc.; the results are correct
+            warnings.simplefilter("ignore", RuntimeWarning)
+            # don't use `(n-1)/k` in np.power; underflows if 0 is of a uintX type
+            result = np.power(k, n / k, dtype=p_dtype) * _gamma1p(n / k)
+            result *= rgamma(1 / k + 1) / np.power(k, 1 / k, dtype=p_dtype)
+        if isinstance(n, np.ndarray):
+            # ensure we keep array-ness for 0-dim inputs; already n/k above loses it
+            result = np.array(result)
+        return result
+
+    # at this point we are guaranteed that extend='zero' and that k>0 is an integer
+    n_mod_k = n % k
+    # scalar case separately, unified handling would be inefficient for arrays;
+    # don't use isscalar due to numpy/numpy#23574; 0-dim arrays treated below
+    if not isinstance(n, np.ndarray):
+        return (
+            np.power(k, (n - n_mod_k) / k)
+            * gamma(n / k + 1) / gamma(n_mod_k / k + 1)
+            * max(n_mod_k, 1)
+        )
+
+    # factor that's independent of the residue class (see factorialk docstring)
+    result = np.power(k, n / k) * gamma(n / k + 1)
+    # factor dependent on residue r (for `r=0` it's 1, so we skip `r=0`
+    # below and thus also avoid evaluating `max(r, 1)`)
+    def corr(k, r): return np.power(k, -r / k) / gamma(r / k + 1) * r
+    for r in np.unique(n_mod_k):
+        if r == 0:
+            continue
+        # cast to int because uint types break on `-r`
+        result[n_mod_k == r] *= corr(k, int(r))
+    return result
+
+
+def _is_subdtype(dtype, dtypes):
+    """
+    Shorthand for calculating whether dtype is subtype of some dtypes.
+
+    Also allows specifying a list instead of just a single dtype.
+
+    Additionaly, the most important supertypes from
+        https://numpy.org/doc/stable/reference/arrays.scalars.html
+    can optionally be specified using abbreviations as follows:
+        "i": np.integer
+        "f": np.floating
+        "c": np.complexfloating
+        "n": np.number (contains the other three)
+    """
+    dtypes = dtypes if isinstance(dtypes, list) else [dtypes]
+    # map single character abbreviations, if they are in dtypes
+    mapping = {
+        "i": np.integer,
+        "f": np.floating,
+        "c": np.complexfloating,
+        "n": np.number
+    }
+    dtypes = [mapping.get(x, x) for x in dtypes]
+    return any(np.issubdtype(dtype, dt) for dt in dtypes)
+
+
+def _factorialx_wrapper(fname, n, k, exact, extend):
+    """
+    Shared implementation for factorial, factorial2 & factorialk.
+    """
+    if extend not in ("zero", "complex"):
+        raise ValueError(
+            f"argument `extend` must be either 'zero' or 'complex', received: {extend}"
+        )
+    if exact and extend == "complex":
+        raise ValueError("Incompatible options: `exact=True` and `extend='complex'`")
+
+    msg_unsup = (
+        "Unsupported data type for {vname} in {fname}: {dtype}\n"
+    )
+    if fname == "factorial":
+        msg_unsup += (
+            "Permitted data types are integers and floating point numbers, "
+            "as well as complex numbers if `extend='complex' is passed."
+        )
+    else:
+        msg_unsup += (
+            "Permitted data types are integers, as well as floating point "
+            "numbers and complex numbers if `extend='complex' is passed."
+        )
+    msg_exact_not_possible = (
+        "`exact=True` only supports integers, cannot use data type {dtype}"
+    )
+    msg_needs_complex = (
+        "In order to use non-integer arguments, you must opt into this by passing "
+        "`extend='complex'`. Note that this changes the result for all negative "
+        "arguments (which by default return 0)."
+    )
+
+    if fname == "factorial2":
+        msg_needs_complex += (" Additionally, it will rescale the values of the double"
+                              " factorial at even integers by a factor of sqrt(2/pi).")
+    elif fname == "factorialk":
+        msg_needs_complex += (" Additionally, it will perturb the values of the"
+                              " multifactorial at most positive integers `n`.")
+        # check type of k
+        if not _is_subdtype(type(k), ["i", "f", "c"]):
+            raise ValueError(msg_unsup.format(vname="`k`", fname=fname, dtype=type(k)))
+        elif _is_subdtype(type(k), ["f", "c"]) and extend != "complex":
+            raise ValueError(msg_needs_complex)
+        # check value of k
+        if extend == "zero" and k < 1:
+            msg = f"For `extend='zero'`, k must be a positive integer, received: {k}"
+            raise ValueError(msg)
+        elif k == 0:
+            raise ValueError("Parameter k cannot be zero!")
+
+    # factorial allows floats also for extend="zero"
+    types_requiring_complex = "c" if fname == "factorial" else ["f", "c"]
+
+    # don't use isscalar due to numpy/numpy#23574; 0-dim arrays treated below
+    if np.ndim(n) == 0 and not isinstance(n, np.ndarray):
+        # scalar cases
+        if not _is_subdtype(type(n), ["i", "f", "c", type(None)]):
+            raise ValueError(msg_unsup.format(vname="`n`", fname=fname, dtype=type(n)))
+        elif _is_subdtype(type(n), types_requiring_complex) and extend != "complex":
+            raise ValueError(msg_needs_complex)
+        elif n is None or np.isnan(n):
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            return np.complex128("nan+nanj") if complexify else np.float64("nan")
+        elif extend == "zero" and n < 0:
+            return 0 if exact else np.float64(0)
+        elif n in {0, 1}:
+            return 1 if exact else np.float64(1)
+        elif exact and _is_subdtype(type(n), "i"):
+            # calculate with integers
+            return _range_prod(1, n, k=k)
+        elif exact:
+            # only relevant for factorial
+            raise ValueError(msg_exact_not_possible.format(dtype=type(n)))
+        # approximation
+        return _factorialx_approx_core(n, k=k, extend=extend)
+
+    # arrays & array-likes
+    n = asarray(n)
+
+    if not _is_subdtype(n.dtype, ["i", "f", "c"]):
+        raise ValueError(msg_unsup.format(vname="`n`", fname=fname, dtype=n.dtype))
+    elif _is_subdtype(n.dtype, types_requiring_complex) and extend != "complex":
+        raise ValueError(msg_needs_complex)
+    elif exact and _is_subdtype(n.dtype, ["f"]):
+        # only relevant for factorial
+        raise ValueError(msg_exact_not_possible.format(dtype=n.dtype))
+
+    if n.size == 0:
+        # return empty arrays unchanged
+        return n
+    elif exact:
+        # calculate with integers
+        return _factorialx_array_exact(n, k=k)
+    # approximation
+    return _factorialx_array_approx(n, k=k, extend=extend)
+
+
+def factorial(n, exact=False, extend="zero"):
+    """
+    The factorial of a number or array of numbers.
+
+    The factorial of non-negative integer `n` is the product of all
+    positive integers less than or equal to `n`::
+
+        n! = n * (n - 1) * (n - 2) * ... * 1
+
+    Parameters
+    ----------
+    n : int or float or complex (or array_like thereof)
+        Input values for ``n!``. Complex values require ``extend='complex'``.
+        By default, the return value for ``n < 0`` is 0.
+    exact : bool, optional
+        If ``exact`` is set to True, calculate the answer exactly using
+        integer arithmetic, otherwise approximate using the gamma function
+        (faster, but yields floats instead of integers).
+        Default is False.
+    extend : string, optional
+        One of ``'zero'`` or ``'complex'``; this determines how values ``n<0``
+        are handled - by default they are 0, but it is possible to opt into the
+        complex extension of the factorial (see below).
+
+    Returns
+    -------
+    nf : int or float or complex or ndarray
+        Factorial of ``n``, as integer, float or complex (depending on ``exact``
+        and ``extend``). Array inputs are returned as arrays.
+
+    Notes
+    -----
+    For arrays with ``exact=True``, the factorial is computed only once, for
+    the largest input, with each other result computed in the process.
+    The output dtype is increased to ``int64`` or ``object`` if necessary.
+
+    With ``exact=False`` the factorial is approximated using the gamma
+    function (which is also the definition of the complex extension):
+
+    .. math:: n! = \\Gamma(n+1)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import factorial
+    >>> arr = np.array([3, 4, 5])
+    >>> factorial(arr, exact=False)
+    array([   6.,   24.,  120.])
+    >>> factorial(arr, exact=True)
+    array([  6,  24, 120])
+    >>> factorial(5, exact=True)
+    120
+
+    """
+    return _factorialx_wrapper("factorial", n, k=1, exact=exact, extend=extend)
+
+
+def factorial2(n, exact=False, extend="zero"):
+    """Double factorial.
+
+    This is the factorial with every second value skipped.  E.g., ``7!! = 7 * 5
+    * 3 * 1``.  It can be approximated numerically as::
+
+      n!! = 2 ** (n / 2) * gamma(n / 2 + 1) * sqrt(2 / pi)  n odd
+          = 2 ** (n / 2) * gamma(n / 2 + 1)                 n even
+          = 2 ** (n / 2) * (n / 2)!                         n even
+
+    The formula for odd ``n`` is the basis for the complex extension.
+
+    Parameters
+    ----------
+    n : int or float or complex (or array_like thereof)
+        Input values for ``n!!``. Non-integer values require ``extend='complex'``.
+        By default, the return value for ``n < 0`` is 0.
+    exact : bool, optional
+        If ``exact`` is set to True, calculate the answer exactly using
+        integer arithmetic, otherwise use above approximation (faster,
+        but yields floats instead of integers).
+        Default is False.
+    extend : string, optional
+        One of ``'zero'`` or ``'complex'``; this determines how values ``n<0``
+        are handled - by default they are 0, but it is possible to opt into the
+        complex extension of the double factorial. This also enables passing
+        complex values to ``n``.
+
+        .. warning::
+
+           Using the ``'complex'`` extension also changes the values of the
+           double factorial for even integers, reducing them by a factor of
+           ``sqrt(2/pi) ~= 0.79``, see [1].
+
+    Returns
+    -------
+    nf : int or float or complex or ndarray
+        Double factorial of ``n``, as integer, float or complex (depending on
+        ``exact`` and ``extend``). Array inputs are returned as arrays.
+
+    Examples
+    --------
+    >>> from scipy.special import factorial2
+    >>> factorial2(7, exact=False)
+    array(105.00000000000001)
+    >>> factorial2(7, exact=True)
+    105
+
+    References
+    ----------
+    .. [1] Complex extension to double factorial
+            https://en.wikipedia.org/wiki/Double_factorial#Complex_arguments
+    """
+    return _factorialx_wrapper("factorial2", n, k=2, exact=exact, extend=extend)
+
+
+def factorialk(n, k, exact=False, extend="zero"):
+    """Multifactorial of n of order k, n(!!...!).
+
+    This is the multifactorial of n skipping k values.  For example,
+
+      factorialk(17, 4) = 17!!!! = 17 * 13 * 9 * 5 * 1
+
+    In particular, for any integer ``n``, we have
+
+      factorialk(n, 1) = factorial(n)
+
+      factorialk(n, 2) = factorial2(n)
+
+    Parameters
+    ----------
+    n : int or float or complex (or array_like thereof)
+        Input values for multifactorial. Non-integer values require
+        ``extend='complex'``. By default, the return value for ``n < 0`` is 0.
+    n : int or float or complex (or array_like thereof)
+        Order of multifactorial. Non-integer values require ``extend='complex'``.
+    exact : bool, optional
+        If ``exact`` is set to True, calculate the answer exactly using
+        integer arithmetic, otherwise use an approximation (faster,
+        but yields floats instead of integers)
+        Default is False.
+    extend : string, optional
+        One of ``'zero'`` or ``'complex'``; this determines how values ``n<0`` are
+        handled - by default they are 0, but it is possible to opt into the complex
+        extension of the multifactorial. This enables passing complex values,
+        not only to ``n`` but also to ``k``.
+
+        .. warning::
+
+           Using the ``'complex'`` extension also changes the values of the
+           multifactorial at integers ``n != 1 (mod k)`` by a factor depending
+           on both ``k`` and ``n % k``, see below or [1].
+
+    Returns
+    -------
+    nf : int or float or complex or ndarray
+        Multifactorial (order ``k``) of ``n``, as integer, float or complex (depending
+        on ``exact`` and ``extend``). Array inputs are returned as arrays.
+
+    Examples
+    --------
+    >>> from scipy.special import factorialk
+    >>> factorialk(5, k=1, exact=True)
+    120
+    >>> factorialk(5, k=3, exact=True)
+    10
+    >>> factorialk([5, 7, 9], k=3, exact=True)
+    array([ 10,  28, 162])
+    >>> factorialk([5, 7, 9], k=3, exact=False)
+    array([ 10.,  28., 162.])
+
+    Notes
+    -----
+    While less straight-forward than for the double-factorial, it's possible to
+    calculate a general approximation formula of n!(k) by studying ``n`` for a given
+    remainder ``r < k`` (thus ``n = m * k + r``, resp. ``r = n % k``), which can be
+    put together into something valid for all integer values ``n >= 0`` & ``k > 0``::
+
+      n!(k) = k ** ((n - r)/k) * gamma(n/k + 1) / gamma(r/k + 1) * max(r, 1)
+
+    This is the basis of the approximation when ``exact=False``.
+
+    In principle, any fixed choice of ``r`` (ignoring its relation ``r = n%k``
+    to ``n``) would provide a suitable analytic continuation from integer ``n``
+    to complex ``z`` (not only satisfying the functional equation but also
+    being logarithmically convex, c.f. Bohr-Mollerup theorem) -- in fact, the
+    choice of ``r`` above only changes the function by a constant factor. The
+    final constraint that determines the canonical continuation is ``f(1) = 1``,
+    which forces ``r = 1`` (see also [1]).::
+
+      z!(k) = k ** ((z - 1)/k) * gamma(z/k + 1) / gamma(1/k + 1)
+
+    References
+    ----------
+    .. [1] Complex extension to multifactorial
+            https://en.wikipedia.org/wiki/Double_factorial#Alternative_extension_of_the_multifactorial
+    """
+    return _factorialx_wrapper("factorialk", n, k=k, exact=exact, extend=extend)
+
+
+def stirling2(N, K, *, exact=False):
+    r"""Generate Stirling number(s) of the second kind.
+
+    Stirling numbers of the second kind count the number of ways to
+    partition a set with N elements into K non-empty subsets.
+
+    The values this function returns are calculated using a dynamic
+    program which avoids redundant computation across the subproblems
+    in the solution. For array-like input, this implementation also
+    avoids redundant computation across the different Stirling number
+    calculations.
+
+    The numbers are sometimes denoted
+
+    .. math::
+
+        {N \brace{K}}
+
+    see [1]_ for details. This is often expressed-verbally-as
+    "N subset K".
+
+    Parameters
+    ----------
+    N : int, ndarray
+        Number of things.
+    K : int, ndarray
+        Number of non-empty subsets taken.
+    exact : bool, optional
+        Uses dynamic programming (DP) with floating point
+        numbers for smaller arrays and uses a second order approximation due to
+        Temme for larger entries  of `N` and `K` that allows trading speed for
+        accuracy. See [2]_ for a description. Temme approximation is used for
+        values ``n>50``. The max error from the DP has max relative error
+        ``4.5*10^-16`` for ``n<=50`` and the max error from the Temme approximation
+        has max relative error ``5*10^-5`` for ``51 <= n < 70`` and
+        ``9*10^-6`` for ``70 <= n < 101``. Note that these max relative errors will
+        decrease further as `n` increases.
+
+    Returns
+    -------
+    val : int, float, ndarray
+        The number of partitions.
+
+    See Also
+    --------
+    comb : The number of combinations of N things taken k at a time.
+
+    Notes
+    -----
+    - If N < 0, or K < 0, then 0 is returned.
+    - If K > N, then 0 is returned.
+
+    The output type will always be `int` or ndarray of `object`.
+    The input must contain either numpy or python integers otherwise a
+    TypeError is raised.
+
+    References
+    ----------
+    .. [1] R. L. Graham, D. E. Knuth and O. Patashnik, "Concrete
+        Mathematics: A Foundation for Computer Science," Addison-Wesley
+        Publishing Company, Boston, 1989. Chapter 6, page 258.
+
+    .. [2] Temme, Nico M. "Asymptotic estimates of Stirling numbers."
+        Studies in Applied Mathematics 89.3 (1993): 233-243.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import stirling2
+    >>> k = np.array([3, -1, 3])
+    >>> n = np.array([10, 10, 9])
+    >>> stirling2(n, k)
+    array([9330.0, 0.0, 3025.0])
+
+    """
+    output_is_scalar = np.isscalar(N) and np.isscalar(K)
+    # make a min-heap of unique (n,k) pairs
+    N, K = asarray(N), asarray(K)
+    if not np.issubdtype(N.dtype, np.integer):
+        raise TypeError("Argument `N` must contain only integers")
+    if not np.issubdtype(K.dtype, np.integer):
+        raise TypeError("Argument `K` must contain only integers")
+    if not exact:
+        # NOTE: here we allow np.uint via casting to double types prior to
+        # passing to private ufunc dispatcher. All dispatched functions
+        # take double type for (n,k) arguments and return double.
+        return _stirling2_inexact(N.astype(float), K.astype(float))
+    nk_pairs = list(
+        set([(n.take(0), k.take(0))
+             for n, k in np.nditer([N, K], ['refs_ok'])])
+    )
+    heapify(nk_pairs)
+    # base mapping for small values
+    snsk_vals = defaultdict(int)
+    for pair in [(0, 0), (1, 1), (2, 1), (2, 2)]:
+        snsk_vals[pair] = 1
+    # for each pair in the min-heap, calculate the value, store for later
+    n_old, n_row = 2, [0, 1, 1]
+    while nk_pairs:
+        n, k = heappop(nk_pairs)
+        if n < 2 or k > n or k <= 0:
+            continue
+        elif k == n or k == 1:
+            snsk_vals[(n, k)] = 1
+            continue
+        elif n != n_old:
+            num_iters = n - n_old
+            while num_iters > 0:
+                n_row.append(1)
+                # traverse from back to remove second row
+                for j in range(len(n_row)-2, 1, -1):
+                    n_row[j] = n_row[j]*j + n_row[j-1]
+                num_iters -= 1
+            snsk_vals[(n, k)] = n_row[k]
+        else:
+            snsk_vals[(n, k)] = n_row[k]
+        n_old, n_row = n, n_row
+    out_types = [object, object, object] if exact else [float, float, float]
+    # for each pair in the map, fetch the value, and populate the array
+    it = np.nditer(
+        [N, K, None],
+        ['buffered', 'refs_ok'],
+        [['readonly'], ['readonly'], ['writeonly', 'allocate']],
+        op_dtypes=out_types,
+    )
+    with it:
+        while not it.finished:
+            it[2] = snsk_vals[(int(it[0]), int(it[1]))]
+            it.iternext()
+        output = it.operands[2]
+        # If N and K were both scalars, convert output to scalar.
+        if output_is_scalar:
+            output = output.take(0)
+    return output
+
+
+def zeta(x, q=None, out=None):
+    r"""
+    Riemann or Hurwitz zeta function.
+
+    Parameters
+    ----------
+    x : array_like of float or complex.
+        Input data
+    q : array_like of float, optional
+        Input data, must be real.  Defaults to Riemann zeta. When `q` is
+        ``None``, complex inputs `x` are supported. If `q` is not ``None``,
+        then currently only real inputs `x` with ``x >= 1`` are supported,
+        even when ``q = 1.0`` (corresponding to the Riemann zeta function).
+
+    out : ndarray, optional
+        Output array for the computed values.
+
+    Returns
+    -------
+    out : array_like
+        Values of zeta(x).
+
+    See Also
+    --------
+    zetac
+
+    Notes
+    -----
+    The two-argument version is the Hurwitz zeta function
+
+    .. math::
+
+        \zeta(x, q) = \sum_{k=0}^{\infty} \frac{1}{(k + q)^x};
+
+    see [dlmf]_ for details. The Riemann zeta function corresponds to
+    the case when ``q = 1``.
+
+    For complex inputs with ``q = None``, points with
+    ``abs(z.imag) > 1e9`` and ``0 <= abs(z.real) < 2.5`` are currently not
+    supported due to slow convergence causing excessive runtime.
+
+    References
+    ----------
+    .. [dlmf] NIST, Digital Library of Mathematical Functions,
+        https://dlmf.nist.gov/25.11#i
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import zeta, polygamma, factorial
+
+    Some specific values:
+
+    >>> zeta(2), np.pi**2/6
+    (1.6449340668482266, 1.6449340668482264)
+
+    >>> zeta(4), np.pi**4/90
+    (1.0823232337111381, 1.082323233711138)
+
+    First nontrivial zero:
+
+    >>> zeta(0.5 + 14.134725141734695j)
+    0 + 0j
+
+    Relation to the `polygamma` function:
+
+    >>> m = 3
+    >>> x = 1.25
+    >>> polygamma(m, x)
+    array(2.782144009188397)
+    >>> (-1)**(m+1) * factorial(m) * zeta(m+1, x)
+    2.7821440091883969
+
+    """
+    if q is None:
+        return _ufuncs._riemann_zeta(x, out)
+    else:
+        return _ufuncs._zeta(x, q, out)
+
+
+def softplus(x, **kwargs):
+    r"""
+    Compute the softplus function element-wise.
+
+    The softplus function is defined as: ``softplus(x) = log(1 + exp(x))``.
+    It is a smooth approximation of the rectifier function (ReLU).
+
+    Parameters
+    ----------
+    x : array_like
+        Input value.
+    **kwargs
+        For other keyword-only arguments, see the
+        `ufunc docs `_.
+
+    Returns
+    -------
+    softplus : ndarray
+        Logarithm of ``exp(0) + exp(x)``.
+
+    Examples
+    --------
+    >>> from scipy import special
+
+    >>> special.softplus(0)
+    0.6931471805599453
+
+    >>> special.softplus([-1, 0, 1])
+    array([0.31326169, 0.69314718, 1.31326169])
+    """
+    return np.logaddexp(0, x, **kwargs)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..e0598ff2d395e08055065c94341de42ce84c5651
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_comb.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b1ce34aa58054be13edfd5d87f2059e8a0d9224
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ellip_harm.py
@@ -0,0 +1,214 @@
+import numpy as np
+
+from ._ufuncs import _ellip_harm
+from ._ellip_harm_2 import _ellipsoid, _ellipsoid_norm
+
+
+def ellip_harm(h2, k2, n, p, s, signm=1, signn=1):
+    r"""
+    Ellipsoidal harmonic functions E^p_n(l)
+
+    These are also known as Lame functions of the first kind, and are
+    solutions to the Lame equation:
+
+    .. math:: (s^2 - h^2)(s^2 - k^2)E''(s)
+              + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0
+
+    where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
+    returned) corresponding to the solutions.
+
+    Parameters
+    ----------
+    h2 : float
+        ``h**2``
+    k2 : float
+        ``k**2``; should be larger than ``h**2``
+    n : int
+        Degree
+    s : float
+        Coordinate
+    p : int
+        Order, can range between [1,2n+1]
+    signm : {1, -1}, optional
+        Sign of prefactor of functions. Can be +/-1. See Notes.
+    signn : {1, -1}, optional
+        Sign of prefactor of functions. Can be +/-1. See Notes.
+
+    Returns
+    -------
+    E : float
+        the harmonic :math:`E^p_n(s)`
+
+    See Also
+    --------
+    ellip_harm_2, ellip_normal
+
+    Notes
+    -----
+    The geometric interpretation of the ellipsoidal functions is
+    explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the
+    sign of prefactors for functions according to their type::
+
+        K : +1
+        L : signm
+        M : signn
+        N : signm*signn
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Digital Library of Mathematical Functions 29.12
+       https://dlmf.nist.gov/29.12
+    .. [2] Bardhan and Knepley, "Computational science and
+       re-discovery: open-source implementations of
+       ellipsoidal harmonics for problems in potential theory",
+       Comput. Sci. Disc. 5, 014006 (2012)
+       :doi:`10.1088/1749-4699/5/1/014006`.
+    .. [3] David J.and Dechambre P, "Computation of Ellipsoidal
+       Gravity Field Harmonics for small solar system bodies"
+       pp. 30-36, 2000
+    .. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications"
+       pp. 418, 2012
+
+    Examples
+    --------
+    >>> from scipy.special import ellip_harm
+    >>> w = ellip_harm(5,8,1,1,2.5)
+    >>> w
+    2.5
+
+    Check that the functions indeed are solutions to the Lame equation:
+
+    >>> import numpy as np
+    >>> from scipy.interpolate import UnivariateSpline
+    >>> def eigenvalue(f, df, ddf):
+    ...     r = (((s**2 - h**2) * (s**2 - k**2) * ddf
+    ...           + s * (2*s**2 - h**2 - k**2) * df
+    ...           - n * (n + 1)*s**2*f) / f)
+    ...     return -r.mean(), r.std()
+    >>> s = np.linspace(0.1, 10, 200)
+    >>> k, h, n, p = 8.0, 2.2, 3, 2
+    >>> E = ellip_harm(h**2, k**2, n, p, s)
+    >>> E_spl = UnivariateSpline(s, E)
+    >>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2))
+    >>> a, a_err
+    (583.44366156701483, 6.4580890640310646e-11)
+
+    """  # noqa: E501
+    return _ellip_harm(h2, k2, n, p, s, signm, signn)
+
+
+_ellip_harm_2_vec = np.vectorize(_ellipsoid, otypes='d')
+
+
+def ellip_harm_2(h2, k2, n, p, s):
+    r"""
+    Ellipsoidal harmonic functions F^p_n(l)
+
+    These are also known as Lame functions of the second kind, and are
+    solutions to the Lame equation:
+
+    .. math:: (s^2 - h^2)(s^2 - k^2)F''(s)
+              + s(2s^2 - h^2 - k^2)F'(s) + (a - q s^2)F(s) = 0
+
+    where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not
+    returned) corresponding to the solutions.
+
+    Parameters
+    ----------
+    h2 : float
+        ``h**2``
+    k2 : float
+        ``k**2``; should be larger than ``h**2``
+    n : int
+        Degree.
+    p : int
+        Order, can range between [1,2n+1].
+    s : float
+        Coordinate
+
+    Returns
+    -------
+    F : float
+        The harmonic :math:`F^p_n(s)`
+
+    See Also
+    --------
+    ellip_harm, ellip_normal
+
+    Notes
+    -----
+    Lame functions of the second kind are related to the functions of the first kind:
+
+    .. math::
+
+       F^p_n(s)=(2n + 1)E^p_n(s)\int_{0}^{1/s}
+       \frac{du}{(E^p_n(1/u))^2\sqrt{(1-u^2k^2)(1-u^2h^2)}}
+
+    .. versionadded:: 0.15.0
+
+    Examples
+    --------
+    >>> from scipy.special import ellip_harm_2
+    >>> w = ellip_harm_2(5,8,2,1,10)
+    >>> w
+    0.00108056853382
+
+    """
+    with np.errstate(all='ignore'):
+        return _ellip_harm_2_vec(h2, k2, n, p, s)
+
+
+def _ellip_normal_vec(h2, k2, n, p):
+    return _ellipsoid_norm(h2, k2, n, p)
+
+
+_ellip_normal_vec = np.vectorize(_ellip_normal_vec, otypes='d')
+
+
+def ellip_normal(h2, k2, n, p):
+    r"""
+    Ellipsoidal harmonic normalization constants gamma^p_n
+
+    The normalization constant is defined as
+
+    .. math::
+
+       \gamma^p_n=8\int_{0}^{h}dx\int_{h}^{k}dy
+       \frac{(y^2-x^2)(E^p_n(y)E^p_n(x))^2}{\sqrt((k^2-y^2)(y^2-h^2)(h^2-x^2)(k^2-x^2)}
+
+    Parameters
+    ----------
+    h2 : float
+        ``h**2``
+    k2 : float
+        ``k**2``; should be larger than ``h**2``
+    n : int
+        Degree.
+    p : int
+        Order, can range between [1,2n+1].
+
+    Returns
+    -------
+    gamma : float
+        The normalization constant :math:`\gamma^p_n`
+
+    See Also
+    --------
+    ellip_harm, ellip_harm_2
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    Examples
+    --------
+    >>> from scipy.special import ellip_normal
+    >>> w = ellip_normal(5,8,3,7)
+    >>> w
+    1723.38796997
+
+    """
+    with np.errstate(all='ignore'):
+        return _ellip_normal_vec(h2, k2, n, p)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_input_validation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_input_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5b7fe36df87617bf91655623ee0076c37a4d08a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_input_validation.py
@@ -0,0 +1,17 @@
+import math
+import operator
+
+def _nonneg_int_or_fail(n, var_name, strict=True):
+    try:
+        if strict:
+            # Raises an exception if float
+            n = operator.index(n)
+        elif n == math.floor(n):
+            n = int(n)
+        else:
+            raise ValueError()
+        if n < 0:
+            raise ValueError()
+    except (ValueError, TypeError) as err:
+        raise err.__class__(f"{var_name} must be a non-negative integer") from err
+    return n
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_lambertw.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_lambertw.py
new file mode 100644
index 0000000000000000000000000000000000000000..f758c7c21fdddc0ec1b84727d90c6de7f34a094e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_lambertw.py
@@ -0,0 +1,149 @@
+from ._ufuncs import _lambertw
+
+import numpy as np
+
+
+def lambertw(z, k=0, tol=1e-8):
+    r"""
+    lambertw(z, k=0, tol=1e-8)
+
+    Lambert W function.
+
+    The Lambert W function `W(z)` is defined as the inverse function
+    of ``w * exp(w)``. In other words, the value of ``W(z)`` is
+    such that ``z = W(z) * exp(W(z))`` for any complex number
+    ``z``.
+
+    The Lambert W function is a multivalued function with infinitely
+    many branches. Each branch gives a separate solution of the
+    equation ``z = w exp(w)``. Here, the branches are indexed by the
+    integer `k`.
+
+    Parameters
+    ----------
+    z : array_like
+        Input argument.
+    k : int, optional
+        Branch index.
+    tol : float, optional
+        Evaluation tolerance.
+
+    Returns
+    -------
+    w : array
+        `w` will have the same shape as `z`.
+
+    See Also
+    --------
+    wrightomega : the Wright Omega function
+
+    Notes
+    -----
+    All branches are supported by `lambertw`:
+
+    * ``lambertw(z)`` gives the principal solution (branch 0)
+    * ``lambertw(z, k)`` gives the solution on branch `k`
+
+    The Lambert W function has two partially real branches: the
+    principal branch (`k = 0`) is real for real ``z > -1/e``, and the
+    ``k = -1`` branch is real for ``-1/e < z < 0``. All branches except
+    ``k = 0`` have a logarithmic singularity at ``z = 0``.
+
+    **Possible issues**
+
+    The evaluation can become inaccurate very close to the branch point
+    at ``-1/e``. In some corner cases, `lambertw` might currently
+    fail to converge, or can end up on the wrong branch.
+
+    **Algorithm**
+
+    Halley's iteration is used to invert ``w * exp(w)``, using a first-order
+    asymptotic approximation (O(log(w)) or `O(w)`) as the initial estimate.
+
+    The definition, implementation and choice of branches is based on [2]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Lambert_W_function
+    .. [2] Corless et al, "On the Lambert W function", Adv. Comp. Math. 5
+       (1996) 329-359.
+       https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf
+
+    Examples
+    --------
+    The Lambert W function is the inverse of ``w exp(w)``:
+
+    >>> import numpy as np
+    >>> from scipy.special import lambertw
+    >>> w = lambertw(1)
+    >>> w
+    (0.56714329040978384+0j)
+    >>> w * np.exp(w)
+    (1.0+0j)
+
+    Any branch gives a valid inverse:
+
+    >>> w = lambertw(1, k=3)
+    >>> w
+    (-2.8535817554090377+17.113535539412148j)
+    >>> w*np.exp(w)
+    (1.0000000000000002+1.609823385706477e-15j)
+
+    **Applications to equation-solving**
+
+    The Lambert W function may be used to solve various kinds of
+    equations.  We give two examples here.
+
+    First, the function can be used to solve implicit equations of the
+    form
+
+        :math:`x = a + b e^{c x}`
+
+    for :math:`x`.  We assume :math:`c` is not zero.  After a little
+    algebra, the equation may be written
+
+        :math:`z e^z = -b c e^{a c}`
+
+    where :math:`z = c (a - x)`.  :math:`z` may then be expressed using
+    the Lambert W function
+
+        :math:`z = W(-b c e^{a c})`
+
+    giving
+
+        :math:`x = a - W(-b c e^{a c})/c`
+
+    For example,
+
+    >>> a = 3
+    >>> b = 2
+    >>> c = -0.5
+
+    The solution to :math:`x = a + b e^{c x}` is:
+
+    >>> x = a - lambertw(-b*c*np.exp(a*c))/c
+    >>> x
+    (3.3707498368978794+0j)
+
+    Verify that it solves the equation:
+
+    >>> a + b*np.exp(c*x)
+    (3.37074983689788+0j)
+
+    The Lambert W function may also be used find the value of the infinite
+    power tower :math:`z^{z^{z^{\ldots}}}`:
+
+    >>> def tower(z, n):
+    ...     if n == 0:
+    ...         return z
+    ...     return z ** tower(z, n-1)
+    ...
+    >>> tower(0.5, 100)
+    0.641185744504986
+    >>> -lambertw(-np.log(0.5)) / np.log(0.5)
+    (0.64118574450498589+0j)
+    """
+    # TODO: special expert should inspect this
+    # interception; better place to do it?
+    k = np.asarray(k, dtype=np.dtype("long"))
+    return _lambertw(z, k, tol)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b0da953464e8d92925ebdaba79ce062c38fc7e5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_logsumexp.py
@@ -0,0 +1,417 @@
+import math
+import numpy as np
+from scipy._lib._util import _asarray_validated
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_broadcast_promote,
+    xp_copy,
+    xp_float_to_complex,
+    is_complex,
+)
+from scipy._lib import array_api_extra as xpx
+
+__all__ = ["logsumexp", "softmax", "log_softmax"]
+
+
+def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False):
+    """Compute the log of the sum of exponentials of input elements.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : None or int or tuple of ints, optional
+        Axis or axes over which the sum is taken. By default `axis` is None,
+        and all elements are summed.
+
+        .. versionadded:: 0.11.0
+    b : array-like, optional
+        Scaling factor for exp(`a`) must be of the same shape as `a` or
+        broadcastable to `a`. These values may be negative in order to
+        implement subtraction.
+
+        .. versionadded:: 0.12.0
+    keepdims : bool, optional
+        If this is set to True, the axes which are reduced are left in the
+        result as dimensions with size one. With this option, the result
+        will broadcast correctly against the original array.
+
+        .. versionadded:: 0.15.0
+    return_sign : bool, optional
+        If this is set to True, the result will be a pair containing sign
+        information; if False, results that are negative will be returned
+        as NaN. Default is False (no sign information).
+
+        .. versionadded:: 0.16.0
+
+    Returns
+    -------
+    res : ndarray
+        The result, ``np.log(np.sum(np.exp(a)))`` calculated in a numerically
+        more stable way. If `b` is given then ``np.log(np.sum(b*np.exp(a)))``
+        is returned. If ``return_sign`` is True, ``res`` contains the log of
+        the absolute value of the argument.
+    sgn : ndarray
+        If ``return_sign`` is True, this will be an array of floating-point
+        numbers matching res containing +1, 0, -1 (for real-valued inputs)
+        or a complex phase (for complex inputs). This gives the sign of the
+        argument of the logarithm in ``res``.
+        If ``return_sign`` is False, only one result is returned.
+
+    See Also
+    --------
+    numpy.logaddexp, numpy.logaddexp2
+
+    Notes
+    -----
+    NumPy has a logaddexp function which is very similar to `logsumexp`, but
+    only handles two arguments. `logaddexp.reduce` is similar to this
+    function, but may be less stable.
+
+    The logarithm is a multivalued function: for each :math:`x` there is an
+    infinite number of :math:`z` such that :math:`exp(z) = x`. The convention
+    is to return the :math:`z` whose imaginary part lies in :math:`(-pi, pi]`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import logsumexp
+    >>> a = np.arange(10)
+    >>> logsumexp(a)
+    9.4586297444267107
+    >>> np.log(np.sum(np.exp(a)))
+    9.4586297444267107
+
+    With weights
+
+    >>> a = np.arange(10)
+    >>> b = np.arange(10, 0, -1)
+    >>> logsumexp(a, b=b)
+    9.9170178533034665
+    >>> np.log(np.sum(b*np.exp(a)))
+    9.9170178533034647
+
+    Returning a sign flag
+
+    >>> logsumexp([1,2],b=[1,-1],return_sign=True)
+    (1.5413248546129181, -1.0)
+
+    Notice that `logsumexp` does not directly support masked arrays. To use it
+    on a masked array, convert the mask into zero weights:
+
+    >>> a = np.ma.array([np.log(2), 2, np.log(3)],
+    ...                  mask=[False, True, False])
+    >>> b = (~a.mask).astype(int)
+    >>> logsumexp(a.data, b=b), np.log(5)
+    1.6094379124341005, 1.6094379124341005
+
+    """
+    xp = array_namespace(a, b)
+    a, b = xp_broadcast_promote(a, b, ensure_writeable=True, force_floating=True, xp=xp)
+    a = xpx.atleast_nd(a, ndim=1, xp=xp)
+    b = xpx.atleast_nd(b, ndim=1, xp=xp) if b is not None else b
+    axis = tuple(range(a.ndim)) if axis is None else axis
+
+    if xp_size(a) != 0:
+        with np.errstate(divide='ignore', invalid='ignore'):  # log of zero is OK
+            out, sgn = _logsumexp(a, b, axis=axis, return_sign=return_sign, xp=xp)
+    else:
+        shape = np.asarray(a.shape)  # NumPy is convenient for shape manipulation
+        shape[axis] = 1
+        out = xp.full(tuple(shape), -xp.inf, dtype=a.dtype)
+        sgn = xp.sign(out)
+
+    if xp.isdtype(out.dtype, 'complex floating'):
+        if return_sign:
+            real = xp.real(sgn)
+            imag = xp_float_to_complex(_wrap_radians(xp.imag(sgn), xp))
+            sgn = real + imag*1j
+        else:
+            real = xp.real(out)
+            imag = xp_float_to_complex(_wrap_radians(xp.imag(out), xp))
+            out = real + imag*1j
+
+    # Deal with shape details - reducing dimensions and convert 0-D to scalar for NumPy
+    out = xp.squeeze(out, axis=axis) if not keepdims else out
+    sgn = xp.squeeze(sgn, axis=axis) if (sgn is not None and not keepdims) else sgn
+    out = out[()] if out.ndim == 0 else out
+    sgn = sgn[()] if (sgn is not None and sgn.ndim == 0) else sgn
+
+    return (out, sgn) if return_sign else out
+
+
+def _wrap_radians(x, xp=None):
+    xp = array_namespace(x) if xp is None else xp
+    # Wrap radians to (-pi, pi] interval
+    out = -((-x + math.pi) % (2 * math.pi) - math.pi)
+    # preserve relative precision
+    no_wrap = xp.abs(x) < xp.pi
+    out[no_wrap] = x[no_wrap]
+    return out
+
+
+def _elements_and_indices_with_max_real(a, axis=-1, xp=None):
+    # This is an array-API compatible `max` function that works something
+    # like `np.max` for complex input. The important part is that it finds
+    # the element with maximum real part. When there are multiple complex values
+    # with this real part, it doesn't matter which we choose.
+    # We could use `argmax` on real component, but array API doesn't yet have
+    # `take_along_axis`, and even if it did, we would have problems with axis tuples.
+    # Feel free to rewrite! It's ugly, but it's not the purpose of the PR, and
+    # it gets the job done.
+    xp = array_namespace(a) if xp is None else xp
+
+    if xp.isdtype(a.dtype, "complex floating"):
+        # select all elements with max real part.
+        real_a = xp.real(a)
+        max = xp.max(real_a, axis=axis, keepdims=True)
+        mask = real_a == max
+
+        # Of those, choose one arbitrarily. This is a reasonably
+        # simple, array-API compatible way of doing so that doesn't
+        # have a problem with `axis` being a tuple or None.
+        i = xp.reshape(xp.arange(xp_size(a)), a.shape)
+        i[~mask] = -1
+        max_i = xp.max(i, axis=axis, keepdims=True)
+        mask = i == max_i
+        a = xp_copy(a)
+        a[~mask] = 0
+        max = xp.sum(a, axis=axis, dtype=a.dtype, keepdims=True)
+    else:
+        max = xp.max(a, axis=axis, keepdims=True)
+        mask = a == max
+
+    return xp.asarray(max), xp.asarray(mask)
+
+
+def _sign(x, xp):
+    return x / xp.where(x == 0, xp.asarray(1, dtype=x.dtype), xp.abs(x))
+
+
+def _logsumexp(a, b, axis, return_sign, xp):
+
+    # This has been around for about a decade, so let's consider it a feature:
+    # Even if element of `a` is infinite or NaN, it adds nothing to the sum if
+    # the corresponding weight is zero.
+    if b is not None:
+        a[b == 0] = -xp.inf
+
+    # Find element with maximum real part, since this is what affects the magnitude
+    # of the exponential. Possible enhancement: include log of `b` magnitude in `a`.
+    a_max, i_max = _elements_and_indices_with_max_real(a, axis=axis, xp=xp)
+
+    # for precision, these terms are separated out of the main sum.
+    a[i_max] = -xp.inf
+    i_max_dt = xp.astype(i_max, a.dtype)
+    # This is an inefficient way of getting `m` because it is the sum of a sparse
+    # array; however, this is the simplest way I can think of to get the right shape.
+    m = (xp.sum(i_max_dt, axis=axis, keepdims=True, dtype=a.dtype) if b is None
+         else xp.sum(b * i_max_dt, axis=axis, keepdims=True, dtype=a.dtype))
+
+    # Arithmetic between infinities will introduce NaNs.
+    # `+ a_max` at the end naturally corrects for removing them here.
+    shift = xp.where(xp.isfinite(a_max), a_max, xp.asarray(0, dtype=a_max.dtype))
+
+    # Shift, exponentiate, scale, and sum
+    exp = b * xp.exp(a - shift) if b is not None else xp.exp(a - shift)
+    s = xp.sum(exp, axis=axis, keepdims=True, dtype=exp.dtype)
+    s = xp.where(s == 0, s, s/m)
+
+    # Separate sign/magnitude information
+    # Originally, this was only performed if `return_sign=True`.
+    # However, this is also needed if any elements of `m < 0` or `s < -1`.
+    # An improvement would be to perform the calculations only on these entries.
+
+    # Use the numpy>=2.0 convention for sign.
+    # When all array libraries agree, this can become sng = xp.sign(s).
+    sgn = _sign(s + 1, xp=xp) * _sign(m, xp=xp)
+
+    if xp.isdtype(s.dtype, "real floating"):
+        # The log functions need positive arguments
+        s = xp.where(s < -1, -s - 2, s)
+        m = xp.abs(m)
+    else:
+        # `a_max` can have a sign component for complex input
+        sgn = sgn * xp.exp(xp.imag(a_max) * xp.asarray(1.0j, dtype=a_max.dtype))
+
+    # Take log and undo shift
+    out = xp.log1p(s) + xp.log(m) + a_max
+
+    if return_sign:
+        if is_complex(out, xp):
+            out = xp.real(out)
+    elif xp.isdtype(out.dtype, 'real floating'):
+        out[sgn < 0] = xp.nan
+
+    return out, sgn
+
+
+def softmax(x, axis=None):
+    r"""Compute the softmax function.
+
+    The softmax function transforms each element of a collection by
+    computing the exponential of each element divided by the sum of the
+    exponentials of all the elements. That is, if `x` is a one-dimensional
+    numpy array::
+
+        softmax(x) = np.exp(x)/sum(np.exp(x))
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axis : int or tuple of ints, optional
+        Axis to compute values along. Default is None and softmax will be
+        computed over the entire array `x`.
+
+    Returns
+    -------
+    s : ndarray
+        An array the same shape as `x`. The result will sum to 1 along the
+        specified axis.
+
+    Notes
+    -----
+    The formula for the softmax function :math:`\sigma(x)` for a vector
+    :math:`x = \{x_0, x_1, ..., x_{n-1}\}` is
+
+    .. math:: \sigma(x)_j = \frac{e^{x_j}}{\sum_k e^{x_k}}
+
+    The `softmax` function is the gradient of `logsumexp`.
+
+    The implementation uses shifting to avoid overflow. See [1]_ for more
+    details.
+
+    .. versionadded:: 1.2.0
+
+    References
+    ----------
+    .. [1] P. Blanchard, D.J. Higham, N.J. Higham, "Accurately computing the
+       log-sum-exp and softmax functions", IMA Journal of Numerical Analysis,
+       Vol.41(4), :doi:`10.1093/imanum/draa038`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import softmax
+    >>> np.set_printoptions(precision=5)
+
+    >>> x = np.array([[1, 0.5, 0.2, 3],
+    ...               [1,  -1,   7, 3],
+    ...               [2,  12,  13, 3]])
+    ...
+
+    Compute the softmax transformation over the entire array.
+
+    >>> m = softmax(x)
+    >>> m
+    array([[  4.48309e-06,   2.71913e-06,   2.01438e-06,   3.31258e-05],
+           [  4.48309e-06,   6.06720e-07,   1.80861e-03,   3.31258e-05],
+           [  1.21863e-05,   2.68421e-01,   7.29644e-01,   3.31258e-05]])
+
+    >>> m.sum()
+    1.0
+
+    Compute the softmax transformation along the first axis (i.e., the
+    columns).
+
+    >>> m = softmax(x, axis=0)
+
+    >>> m
+    array([[  2.11942e-01,   1.01300e-05,   2.75394e-06,   3.33333e-01],
+           [  2.11942e-01,   2.26030e-06,   2.47262e-03,   3.33333e-01],
+           [  5.76117e-01,   9.99988e-01,   9.97525e-01,   3.33333e-01]])
+
+    >>> m.sum(axis=0)
+    array([ 1.,  1.,  1.,  1.])
+
+    Compute the softmax transformation along the second axis (i.e., the rows).
+
+    >>> m = softmax(x, axis=1)
+    >>> m
+    array([[  1.05877e-01,   6.42177e-02,   4.75736e-02,   7.82332e-01],
+           [  2.42746e-03,   3.28521e-04,   9.79307e-01,   1.79366e-02],
+           [  1.22094e-05,   2.68929e-01,   7.31025e-01,   3.31885e-05]])
+
+    >>> m.sum(axis=1)
+    array([ 1.,  1.,  1.])
+
+    """
+    x = _asarray_validated(x, check_finite=False)
+    x_max = np.amax(x, axis=axis, keepdims=True)
+    exp_x_shifted = np.exp(x - x_max)
+    return exp_x_shifted / np.sum(exp_x_shifted, axis=axis, keepdims=True)
+
+
+def log_softmax(x, axis=None):
+    r"""Compute the logarithm of the softmax function.
+
+    In principle::
+
+        log_softmax(x) = log(softmax(x))
+
+    but using a more accurate implementation.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    axis : int or tuple of ints, optional
+        Axis to compute values along. Default is None and softmax will be
+        computed over the entire array `x`.
+
+    Returns
+    -------
+    s : ndarray or scalar
+        An array with the same shape as `x`. Exponential of the result will
+        sum to 1 along the specified axis. If `x` is a scalar, a scalar is
+        returned.
+
+    Notes
+    -----
+    `log_softmax` is more accurate than ``np.log(softmax(x))`` with inputs that
+    make `softmax` saturate (see examples below).
+
+    .. versionadded:: 1.5.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import log_softmax
+    >>> from scipy.special import softmax
+    >>> np.set_printoptions(precision=5)
+
+    >>> x = np.array([1000.0, 1.0])
+
+    >>> y = log_softmax(x)
+    >>> y
+    array([   0., -999.])
+
+    >>> with np.errstate(divide='ignore'):
+    ...   y = np.log(softmax(x))
+    ...
+    >>> y
+    array([  0., -inf])
+
+    """
+
+    x = _asarray_validated(x, check_finite=False)
+
+    x_max = np.amax(x, axis=axis, keepdims=True)
+
+    if x_max.ndim > 0:
+        x_max[~np.isfinite(x_max)] = 0
+    elif not np.isfinite(x_max):
+        x_max = 0
+
+    tmp = x - x_max
+    exp_tmp = np.exp(tmp)
+
+    # suppress warnings about log of zero
+    with np.errstate(divide='ignore'):
+        s = np.sum(exp_tmp, axis=axis, keepdims=True)
+        out = np.log(s)
+
+    out = tmp - out
+    return out
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e519093dface79e21f16d7063541ad107f5ca96
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_mptestutils.py
@@ -0,0 +1,453 @@
+import os
+import sys
+import time
+from itertools import zip_longest
+
+import numpy as np
+from numpy.testing import assert_
+import pytest
+
+from scipy.special._testutils import assert_func_equal
+
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+# ------------------------------------------------------------------------------
+# Machinery for systematic tests with mpmath
+# ------------------------------------------------------------------------------
+
+class Arg:
+    """Generate a set of numbers on the real axis, concentrating on
+    'interesting' regions and covering all orders of magnitude.
+
+    """
+
+    def __init__(self, a=-np.inf, b=np.inf, inclusive_a=True, inclusive_b=True):
+        if a > b:
+            raise ValueError("a should be less than or equal to b")
+        if a == -np.inf:
+            a = -0.5*np.finfo(float).max
+        if b == np.inf:
+            b = 0.5*np.finfo(float).max
+        self.a, self.b = a, b
+
+        self.inclusive_a, self.inclusive_b = inclusive_a, inclusive_b
+
+    def _positive_values(self, a, b, n):
+        if a < 0:
+            raise ValueError("a should be positive")
+
+        # Try to put half of the points into a linspace between a and
+        # 10 the other half in a logspace.
+        if n % 2 == 0:
+            nlogpts = n//2
+            nlinpts = nlogpts
+        else:
+            nlogpts = n//2
+            nlinpts = nlogpts + 1
+
+        if a >= 10:
+            # Outside of linspace range; just return a logspace.
+            pts = np.logspace(np.log10(a), np.log10(b), n)
+        elif a > 0 and b < 10:
+            # Outside of logspace range; just return a linspace
+            pts = np.linspace(a, b, n)
+        elif a > 0:
+            # Linspace between a and 10 and a logspace between 10 and
+            # b.
+            linpts = np.linspace(a, 10, nlinpts, endpoint=False)
+            logpts = np.logspace(1, np.log10(b), nlogpts)
+            pts = np.hstack((linpts, logpts))
+        elif a == 0 and b <= 10:
+            # Linspace between 0 and b and a logspace between 0 and
+            # the smallest positive point of the linspace
+            linpts = np.linspace(0, b, nlinpts)
+            if linpts.size > 1:
+                right = np.log10(linpts[1])
+            else:
+                right = -30
+            logpts = np.logspace(-30, right, nlogpts, endpoint=False)
+            pts = np.hstack((logpts, linpts))
+        else:
+            # Linspace between 0 and 10, logspace between 0 and the
+            # smallest positive point of the linspace, and a logspace
+            # between 10 and b.
+            if nlogpts % 2 == 0:
+                nlogpts1 = nlogpts//2
+                nlogpts2 = nlogpts1
+            else:
+                nlogpts1 = nlogpts//2
+                nlogpts2 = nlogpts1 + 1
+            linpts = np.linspace(0, 10, nlinpts, endpoint=False)
+            if linpts.size > 1:
+                right = np.log10(linpts[1])
+            else:
+                right = -30
+            logpts1 = np.logspace(-30, right, nlogpts1, endpoint=False)
+            logpts2 = np.logspace(1, np.log10(b), nlogpts2)
+            pts = np.hstack((logpts1, linpts, logpts2))
+
+        return np.sort(pts)
+
+    def values(self, n):
+        """Return an array containing n numbers."""
+        a, b = self.a, self.b
+        if a == b:
+            return np.zeros(n)
+
+        if not self.inclusive_a:
+            n += 1
+        if not self.inclusive_b:
+            n += 1
+
+        if n % 2 == 0:
+            n1 = n//2
+            n2 = n1
+        else:
+            n1 = n//2
+            n2 = n1 + 1
+
+        if a >= 0:
+            pospts = self._positive_values(a, b, n)
+            negpts = []
+        elif b <= 0:
+            pospts = []
+            negpts = -self._positive_values(-b, -a, n)
+        else:
+            pospts = self._positive_values(0, b, n1)
+            negpts = -self._positive_values(0, -a, n2 + 1)
+            # Don't want to get zero twice
+            negpts = negpts[1:]
+        pts = np.hstack((negpts[::-1], pospts))
+
+        if not self.inclusive_a:
+            pts = pts[1:]
+        if not self.inclusive_b:
+            pts = pts[:-1]
+        return pts
+
+
+class FixedArg:
+    def __init__(self, values):
+        self._values = np.asarray(values)
+
+    def values(self, n):
+        return self._values
+
+
+class ComplexArg:
+    def __init__(self, a=complex(-np.inf, -np.inf), b=complex(np.inf, np.inf)):
+        self.real = Arg(a.real, b.real)
+        self.imag = Arg(a.imag, b.imag)
+
+    def values(self, n):
+        m = int(np.floor(np.sqrt(n)))
+        x = self.real.values(m)
+        y = self.imag.values(m + 1)
+        return (x[:,None] + 1j*y[None,:]).ravel()
+
+
+class IntArg:
+    def __init__(self, a=-1000, b=1000):
+        self.a = a
+        self.b = b
+
+    def values(self, n):
+        v1 = Arg(self.a, self.b).values(max(1 + n//2, n-5)).astype(int)
+        v2 = np.arange(-5, 5)
+        v = np.unique(np.r_[v1, v2])
+        v = v[(v >= self.a) & (v < self.b)]
+        return v
+
+
+def get_args(argspec, n):
+    if isinstance(argspec, np.ndarray):
+        args = argspec.copy()
+    else:
+        nargs = len(argspec)
+        ms = np.asarray(
+            [1.5 if isinstance(spec, ComplexArg) else 1.0 for spec in argspec]
+        )
+        ms = (n**(ms/sum(ms))).astype(int) + 1
+
+        args = [spec.values(m) for spec, m in zip(argspec, ms)]
+        args = np.array(np.broadcast_arrays(*np.ix_(*args))).reshape(nargs, -1).T
+
+    return args
+
+
+class MpmathData:
+    def __init__(self, scipy_func, mpmath_func, arg_spec, name=None,
+                 dps=None, prec=None, n=None, rtol=1e-7, atol=1e-300,
+                 ignore_inf_sign=False, distinguish_nan_and_inf=True,
+                 nan_ok=True, param_filter=None):
+
+        # mpmath tests are really slow (see gh-6989).  Use a small number of
+        # points by default, increase back to 5000 (old default) if XSLOW is
+        # set
+        if n is None:
+            try:
+                is_xslow = int(os.environ.get('SCIPY_XSLOW', '0'))
+            except ValueError:
+                is_xslow = False
+
+            n = 5000 if is_xslow else 500
+
+        self.scipy_func = scipy_func
+        self.mpmath_func = mpmath_func
+        self.arg_spec = arg_spec
+        self.dps = dps
+        self.prec = prec
+        self.n = n
+        self.rtol = rtol
+        self.atol = atol
+        self.ignore_inf_sign = ignore_inf_sign
+        self.nan_ok = nan_ok
+        if isinstance(self.arg_spec, np.ndarray):
+            self.is_complex = np.issubdtype(self.arg_spec.dtype, np.complexfloating)
+        else:
+            self.is_complex = any(
+                [isinstance(arg, ComplexArg) for arg in self.arg_spec]
+            )
+        self.ignore_inf_sign = ignore_inf_sign
+        self.distinguish_nan_and_inf = distinguish_nan_and_inf
+        if not name or name == '':
+            name = getattr(scipy_func, '__name__', None)
+        if not name or name == '':
+            name = getattr(mpmath_func, '__name__', None)
+        self.name = name
+        self.param_filter = param_filter
+
+    def check(self):
+        np.random.seed(1234)
+
+        # Generate values for the arguments
+        argarr = get_args(self.arg_spec, self.n)
+
+        # Check
+        old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
+        try:
+            if self.dps is not None:
+                dps_list = [self.dps]
+            else:
+                dps_list = [20]
+            if self.prec is not None:
+                mpmath.mp.prec = self.prec
+
+            # Proper casting of mpmath input and output types. Using
+            # native mpmath types as inputs gives improved precision
+            # in some cases.
+            if np.issubdtype(argarr.dtype, np.complexfloating):
+                pytype = mpc2complex
+
+                def mptype(x):
+                    return mpmath.mpc(complex(x))
+            else:
+                def mptype(x):
+                    return mpmath.mpf(float(x))
+
+                def pytype(x):
+                    if abs(x.imag) > 1e-16*(1 + abs(x.real)):
+                        return np.nan
+                    else:
+                        return mpf2float(x.real)
+
+            # Try out different dps until one (or none) works
+            for j, dps in enumerate(dps_list):
+                mpmath.mp.dps = dps
+
+                try:
+                    assert_func_equal(
+                        self.scipy_func,
+                        lambda *a: pytype(self.mpmath_func(*map(mptype, a))),
+                        argarr,
+                        vectorized=False,
+                        rtol=self.rtol,
+                        atol=self.atol,
+                        ignore_inf_sign=self.ignore_inf_sign,
+                        distinguish_nan_and_inf=self.distinguish_nan_and_inf,
+                        nan_ok=self.nan_ok,
+                        param_filter=self.param_filter
+                    )
+                    break
+                except AssertionError:
+                    if j >= len(dps_list)-1:
+                        # reraise the Exception
+                        tp, value, tb = sys.exc_info()
+                        if value.__traceback__ is not tb:
+                            raise value.with_traceback(tb)
+                        raise value
+        finally:
+            mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
+
+    def __repr__(self):
+        if self.is_complex:
+            return f""
+        else:
+            return f""
+
+
+def assert_mpmath_equal(*a, **kw):
+    d = MpmathData(*a, **kw)
+    d.check()
+
+
+def nonfunctional_tooslow(func):
+    return pytest.mark.skip(
+        reason="    Test not yet functional (too slow), needs more work."
+    )(func)
+
+
+# ------------------------------------------------------------------------------
+# Tools for dealing with mpmath quirks
+# ------------------------------------------------------------------------------
+
+def mpf2float(x):
+    """
+    Convert an mpf to the nearest floating point number. Just using
+    float directly doesn't work because of results like this:
+
+    with mp.workdps(50):
+        float(mpf("0.99999999999999999")) = 0.9999999999999999
+
+    """
+    return float(mpmath.nstr(x, 17, min_fixed=0, max_fixed=0))
+
+
+def mpc2complex(x):
+    return complex(mpf2float(x.real), mpf2float(x.imag))
+
+
+def trace_args(func):
+    def tofloat(x):
+        if isinstance(x, mpmath.mpc):
+            return complex(x)
+        else:
+            return float(x)
+
+    def wrap(*a, **kw):
+        sys.stderr.write(f"{tuple(map(tofloat, a))!r}: ")
+        sys.stderr.flush()
+        try:
+            r = func(*a, **kw)
+            sys.stderr.write(f"-> {r!r}")
+        finally:
+            sys.stderr.write("\n")
+            sys.stderr.flush()
+        return r
+    return wrap
+
+
+try:
+    import signal
+    POSIX = ('setitimer' in dir(signal))
+except ImportError:
+    POSIX = False
+
+
+class TimeoutError(Exception):
+    pass
+
+
+def time_limited(timeout=0.5, return_val=np.nan, use_sigalrm=True):
+    """
+    Decorator for setting a timeout for pure-Python functions.
+
+    If the function does not return within `timeout` seconds, the
+    value `return_val` is returned instead.
+
+    On POSIX this uses SIGALRM by default. On non-POSIX, settrace is
+    used. Do not use this with threads: the SIGALRM implementation
+    does probably not work well. The settrace implementation only
+    traces the current thread.
+
+    The settrace implementation slows down execution speed. Slowdown
+    by a factor around 10 is probably typical.
+    """
+    if POSIX and use_sigalrm:
+        def sigalrm_handler(signum, frame):
+            raise TimeoutError()
+
+        def deco(func):
+            def wrap(*a, **kw):
+                old_handler = signal.signal(signal.SIGALRM, sigalrm_handler)
+                signal.setitimer(signal.ITIMER_REAL, timeout)
+                try:
+                    return func(*a, **kw)
+                except TimeoutError:
+                    return return_val
+                finally:
+                    signal.setitimer(signal.ITIMER_REAL, 0)
+                    signal.signal(signal.SIGALRM, old_handler)
+            return wrap
+    else:
+        def deco(func):
+            def wrap(*a, **kw):
+                start_time = time.time()
+
+                def trace(frame, event, arg):
+                    if time.time() - start_time > timeout:
+                        raise TimeoutError()
+                    return trace
+                sys.settrace(trace)
+                try:
+                    return func(*a, **kw)
+                except TimeoutError:
+                    sys.settrace(None)
+                    return return_val
+                finally:
+                    sys.settrace(None)
+            return wrap
+    return deco
+
+
+def exception_to_nan(func):
+    """Decorate function to return nan if it raises an exception"""
+    def wrap(*a, **kw):
+        try:
+            return func(*a, **kw)
+        except Exception:
+            return np.nan
+    return wrap
+
+
+def inf_to_nan(func):
+    """Decorate function to return nan if it returns inf"""
+    def wrap(*a, **kw):
+        v = func(*a, **kw)
+        if not np.isfinite(v):
+            return np.nan
+        return v
+    return wrap
+
+
+def mp_assert_allclose(res, std, atol=0, rtol=1e-17):
+    """
+    Compare lists of mpmath.mpf's or mpmath.mpc's directly so that it
+    can be done to higher precision than double.
+    """
+    failures = []
+    for k, (resval, stdval) in enumerate(zip_longest(res, std)):
+        if resval is None or stdval is None:
+            raise ValueError('Lengths of inputs res and std are not equal.')
+        if mpmath.fabs(resval - stdval) > atol + rtol*mpmath.fabs(stdval):
+            failures.append((k, resval, stdval))
+
+    nfail = len(failures)
+    if nfail > 0:
+        ndigits = int(abs(np.log10(rtol)))
+        msg = [""]
+        msg.append(f"Bad results ({nfail} out of {k + 1}) for the following points:")
+        for k, resval, stdval in failures:
+            resrep = mpmath.nstr(resval, ndigits, min_fixed=0, max_fixed=0)
+            stdrep = mpmath.nstr(stdval, ndigits, min_fixed=0, max_fixed=0)
+            if stdval == 0:
+                rdiff = "inf"
+            else:
+                rdiff = mpmath.fabs((resval - stdval)/stdval)
+                rdiff = mpmath.nstr(rdiff, 3)
+            msg.append(f"{k}: {resrep} != {stdrep} (rdiff {rdiff})")
+        assert_(False, "\n".join(msg))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bb1be9461c629a48841f1d01268e8d11eee230f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_multiufuncs.py
@@ -0,0 +1,610 @@
+import collections
+import numbers
+import numpy as np
+
+from ._input_validation import _nonneg_int_or_fail
+
+from ._special_ufuncs import (legendre_p, assoc_legendre_p,
+                              sph_legendre_p, sph_harm_y)
+from ._gufuncs import (legendre_p_all, assoc_legendre_p_all,
+                       sph_legendre_p_all, sph_harm_y_all)
+
+__all__ = [
+    "assoc_legendre_p",
+    "assoc_legendre_p_all",
+    "legendre_p",
+    "legendre_p_all",
+    "sph_harm_y",
+    "sph_harm_y_all",
+    "sph_legendre_p",
+    "sph_legendre_p_all",
+]
+
+
+class MultiUFunc:
+    def __init__(self, ufunc_or_ufuncs, doc=None, *,
+                 force_complex_output=False, **default_kwargs):
+        if not isinstance(ufunc_or_ufuncs, np.ufunc):
+            if isinstance(ufunc_or_ufuncs, collections.abc.Mapping):
+                ufuncs_iter = ufunc_or_ufuncs.values()
+            elif isinstance(ufunc_or_ufuncs, collections.abc.Iterable):
+                ufuncs_iter = ufunc_or_ufuncs
+            else:
+                raise ValueError("ufunc_or_ufuncs should be a ufunc or a"
+                                 " ufunc collection")
+
+            # Perform input validation to ensure all ufuncs in ufuncs are
+            # actually ufuncs and all take the same input types.
+            seen_input_types = set()
+            for ufunc in ufuncs_iter:
+                if not isinstance(ufunc, np.ufunc):
+                    raise ValueError("All ufuncs must have type `numpy.ufunc`."
+                                     f" Received {ufunc_or_ufuncs}")
+                seen_input_types.add(frozenset(x.split("->")[0] for x in ufunc.types))
+            if len(seen_input_types) > 1:
+                raise ValueError("All ufuncs must take the same input types.")
+
+        self._ufunc_or_ufuncs = ufunc_or_ufuncs
+        self.__doc = doc
+        self.__force_complex_output = force_complex_output
+        self._default_kwargs = default_kwargs
+        self._resolve_out_shapes = None
+        self._finalize_out = None
+        self._key = None
+        self._ufunc_default_args = lambda *args, **kwargs: ()
+        self._ufunc_default_kwargs = lambda *args, **kwargs: {}
+
+    @property
+    def __doc__(self):
+        return self.__doc
+
+    def _override_key(self, func):
+        """Set `key` method by decorating a function.
+        """
+        self._key = func
+
+    def _override_ufunc_default_args(self, func):
+        self._ufunc_default_args = func
+
+    def _override_ufunc_default_kwargs(self, func):
+        self._ufunc_default_kwargs = func
+
+    def _override_resolve_out_shapes(self, func):
+        """Set `resolve_out_shapes` method by decorating a function."""
+        if func.__doc__ is None:
+            func.__doc__ = \
+                """Resolve to output shapes based on relevant inputs."""
+        func.__name__ = "resolve_out_shapes"
+        self._resolve_out_shapes = func
+
+    def _override_finalize_out(self, func):
+        self._finalize_out = func
+
+    def _resolve_ufunc(self, **kwargs):
+        """Resolve to a ufunc based on keyword arguments."""
+
+        if isinstance(self._ufunc_or_ufuncs, np.ufunc):
+            return self._ufunc_or_ufuncs
+
+        ufunc_key = self._key(**kwargs)
+        return self._ufunc_or_ufuncs[ufunc_key]
+
+    def __call__(self, *args, **kwargs):
+        kwargs = self._default_kwargs | kwargs
+
+        args += self._ufunc_default_args(**kwargs)
+
+        ufunc = self._resolve_ufunc(**kwargs)
+
+        # array arguments to be passed to the ufunc
+        ufunc_args = [np.asarray(arg) for arg in args[-ufunc.nin:]]
+
+        ufunc_kwargs = self._ufunc_default_kwargs(**kwargs)
+
+        if (self._resolve_out_shapes is not None):
+            ufunc_arg_shapes = tuple(np.shape(ufunc_arg) for ufunc_arg in ufunc_args)
+            ufunc_out_shapes = self._resolve_out_shapes(*args[:-ufunc.nin],
+                                                        *ufunc_arg_shapes, ufunc.nout,
+                                                        **kwargs)
+
+            ufunc_arg_dtypes = tuple(ufunc_arg.dtype if hasattr(ufunc_arg, 'dtype')
+                                     else np.dtype(type(ufunc_arg))
+                                     for ufunc_arg in ufunc_args)
+
+            if hasattr(ufunc, 'resolve_dtypes'):
+                ufunc_dtypes = ufunc_arg_dtypes + ufunc.nout * (None,)
+                ufunc_dtypes = ufunc.resolve_dtypes(ufunc_dtypes)
+                ufunc_out_dtypes = ufunc_dtypes[-ufunc.nout:]
+            else:
+                ufunc_out_dtype = np.result_type(*ufunc_arg_dtypes)
+                if (not np.issubdtype(ufunc_out_dtype, np.inexact)):
+                    ufunc_out_dtype = np.float64
+
+                ufunc_out_dtypes = ufunc.nout * (ufunc_out_dtype,)
+
+            if self.__force_complex_output:
+                ufunc_out_dtypes = tuple(np.result_type(1j, ufunc_out_dtype)
+                                         for ufunc_out_dtype in ufunc_out_dtypes)
+
+            out = tuple(np.empty(ufunc_out_shape, dtype=ufunc_out_dtype)
+                        for ufunc_out_shape, ufunc_out_dtype
+                        in zip(ufunc_out_shapes, ufunc_out_dtypes))
+
+            ufunc_kwargs['out'] = out
+
+        out = ufunc(*ufunc_args, **ufunc_kwargs)
+        if (self._finalize_out is not None):
+            out = self._finalize_out(out)
+
+        return out
+
+
+sph_legendre_p = MultiUFunc(
+    sph_legendre_p,
+    r"""sph_legendre_p(n, m, theta, *, diff_n=0)
+
+    Spherical Legendre polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the spherical Legendre polynomial. Must have ``n >= 0``.
+    m : ArrayLike[int]
+        Order of the spherical Legendre polynomial.
+    theta : ArrayLike[float]
+        Input value.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    p : ndarray or tuple[ndarray]
+        Spherical Legendre polynomial with ``diff_n`` derivatives.
+
+    Notes
+    -----
+    The spherical counterpart of an (unnormalized) associated Legendre polynomial has
+    the additional factor
+
+    .. math::
+
+        \sqrt{\frac{(2 n + 1) (n - m)!}{4 \pi (n + m)!}}
+
+    It is the same as the spherical harmonic :math:`Y_{n}^{m}(\theta, \phi)`
+    with :math:`\phi = 0`.
+    """, diff_n=0
+)
+
+
+@sph_legendre_p._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_legendre_p._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+sph_legendre_p_all = MultiUFunc(
+    sph_legendre_p_all,
+    """sph_legendre_p_all(n, m, theta, *, diff_n=0)
+
+    All spherical Legendre polynomials of the first kind up to the
+    specified degree ``n`` and order ``m``.
+
+    Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)``
+    corresponds to degree ``j`` and order ``i`` for all  ``0 <= j <= n``
+    and ``-m <= i <= m``.
+
+    See Also
+    --------
+    sph_legendre_p
+    """, diff_n=0
+)
+
+
+@sph_legendre_p_all._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_legendre_p_all._override_ufunc_default_kwargs
+def _(diff_n):
+    return {'axes': [()] + [(0, 1, -1)]}
+
+
+@sph_legendre_p_all._override_resolve_out_shapes
+def _(n, m, theta_shape, nout, diff_n):
+    if not isinstance(n, numbers.Integral) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+
+    return ((n + 1, 2 * abs(m) + 1) + theta_shape + (diff_n + 1,),)
+
+
+@sph_legendre_p_all._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+assoc_legendre_p = MultiUFunc(
+    assoc_legendre_p,
+    r"""assoc_legendre_p(n, m, z, *, branch_cut=2, norm=False, diff_n=0)
+
+    Associated Legendre polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the associated Legendre polynomial. Must have ``n >= 0``.
+    m : ArrayLike[int]
+        order of the associated Legendre polynomial.
+    z : ArrayLike[float | complex]
+        Input value.
+    branch_cut : Optional[ArrayLike[int]]
+        Selects branch cut. Must be 2 (default) or 3.
+        2: cut on the real axis ``|z| > 1``
+        3: cut on the real axis ``-1 < z < 1``
+    norm : Optional[bool]
+        If ``True``, compute the normalized associated Legendre polynomial.
+        Default is ``False``.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    p : ndarray or tuple[ndarray]
+        Associated Legendre polynomial with ``diff_n`` derivatives.
+
+    Notes
+    -----
+    The normalized counterpart of an (unnormalized) associated Legendre
+    polynomial has the additional factor
+
+    .. math::
+
+        \sqrt{\frac{(2 n + 1) (n - m)!}{2 (n + m)!}}
+    """, branch_cut=2, norm=False, diff_n=0
+)
+
+
+@assoc_legendre_p._override_key
+def _(branch_cut, norm, diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return norm, diff_n
+
+
+@assoc_legendre_p._override_ufunc_default_args
+def _(branch_cut, norm, diff_n):
+    return branch_cut,
+
+
+@assoc_legendre_p._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+assoc_legendre_p_all = MultiUFunc(
+    assoc_legendre_p_all,
+    """assoc_legendre_p_all(n, m, z, *, branch_cut=2, norm=False, diff_n=0)
+
+    All associated Legendre polynomials of the first kind up to the
+    specified degree ``n`` and order ``m``.
+
+    Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)``
+    corresponds to degree ``j`` and order ``i`` for all  ``0 <= j <= n``
+    and ``-m <= i <= m``.
+
+    See Also
+    --------
+    assoc_legendre_p
+    """, branch_cut=2, norm=False, diff_n=0
+)
+
+
+@assoc_legendre_p_all._override_key
+def _(branch_cut, norm, diff_n):
+    if not ((isinstance(diff_n, numbers.Integral))
+            and diff_n >= 0):
+        raise ValueError(
+            f"diff_n must be a non-negative integer, received: {diff_n}."
+        )
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return norm, diff_n
+
+
+@assoc_legendre_p_all._override_ufunc_default_args
+def _(branch_cut, norm, diff_n):
+    return branch_cut,
+
+
+@assoc_legendre_p_all._override_ufunc_default_kwargs
+def _(branch_cut, norm, diff_n):
+    return {'axes': [(), ()] + [(0, 1, -1)]}
+
+
+@assoc_legendre_p_all._override_resolve_out_shapes
+def _(n, m, z_shape, branch_cut_shape, nout, **kwargs):
+    diff_n = kwargs['diff_n']
+
+    if not isinstance(n, numbers.Integral) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+    if not isinstance(m, numbers.Integral) or (m < 0):
+        raise ValueError("m must be a non-negative integer.")
+
+    return ((n + 1, 2 * abs(m) + 1) +
+        np.broadcast_shapes(z_shape, branch_cut_shape) + (diff_n + 1,),)
+
+
+@assoc_legendre_p_all._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+legendre_p = MultiUFunc(
+    legendre_p,
+    """legendre_p(n, z, *, diff_n=0)
+
+    Legendre polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the Legendre polynomial. Must have ``n >= 0``.
+    z : ArrayLike[float]
+        Input value.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    p : ndarray or tuple[ndarray]
+        Legendre polynomial with ``diff_n`` derivatives.
+
+    See Also
+    --------
+    legendre
+
+    References
+    ----------
+    .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special
+           Functions", John Wiley and Sons, 1996.
+           https://people.sc.fsu.edu/~jburkardt/f77_src/special_functions/special_functions.html
+    """, diff_n=0
+)
+
+
+@legendre_p._override_key
+def _(diff_n):
+    if (not isinstance(diff_n, numbers.Integral)) or (diff_n < 0):
+        raise ValueError(
+            f"diff_n must be a non-negative integer, received: {diff_n}."
+        )
+    if not 0 <= diff_n <= 2:
+        raise NotImplementedError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@legendre_p._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+legendre_p_all = MultiUFunc(
+    legendre_p_all,
+    """legendre_p_all(n, z, *, diff_n=0)
+
+    All Legendre polynomials of the first kind up to the
+    specified degree ``n``.
+
+    Output shape is ``(n + 1, ...)``. The entry at ``j``
+    corresponds to degree ``j`` for all  ``0 <= j <= n``.
+
+    See Also
+    --------
+    legendre_p
+    """, diff_n=0
+)
+
+
+@legendre_p_all._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@legendre_p_all._override_ufunc_default_kwargs
+def _(diff_n):
+    return {'axes': [(), (0, -1)]}
+
+
+@legendre_p_all._override_resolve_out_shapes
+def _(n, z_shape, nout, diff_n):
+    n = _nonneg_int_or_fail(n, 'n', strict=False)
+
+    return nout * ((n + 1,) + z_shape + (diff_n + 1,),)
+
+
+@legendre_p_all._override_finalize_out
+def _(out):
+    return np.moveaxis(out, -1, 0)
+
+
+sph_harm_y = MultiUFunc(
+    sph_harm_y,
+    r"""sph_harm_y(n, m, theta, phi, *, diff_n=0)
+
+    Spherical harmonics. They are defined as
+
+    .. math::
+
+        Y_n^m(\theta,\phi) = \sqrt{\frac{2 n + 1}{4 \pi} \frac{(n - m)!}{(n + m)!}}
+            P_n^m(\cos(\theta)) e^{i m \phi}
+
+    where :math:`P_n^m` are the (unnormalized) associated Legendre polynomials.
+
+    Parameters
+    ----------
+    n : ArrayLike[int]
+        Degree of the harmonic. Must have ``n >= 0``. This is
+        often denoted by ``l`` (lower case L) in descriptions of
+        spherical harmonics.
+    m : ArrayLike[int]
+        Order of the harmonic.
+    theta : ArrayLike[float]
+        Polar (colatitudinal) coordinate; must be in ``[0, pi]``.
+    phi : ArrayLike[float]
+        Azimuthal (longitudinal) coordinate; must be in ``[0, 2*pi]``.
+    diff_n : Optional[int]
+        A non-negative integer. Compute and return all derivatives up
+        to order ``diff_n``. Default is 0.
+
+    Returns
+    -------
+    y : ndarray[complex] or tuple[ndarray[complex]]
+       Spherical harmonics with ``diff_n`` derivatives.
+
+    Notes
+    -----
+    There are different conventions for the meanings of the input
+    arguments ``theta`` and ``phi``. In SciPy ``theta`` is the
+    polar angle and ``phi`` is the azimuthal angle. It is common to
+    see the opposite convention, that is, ``theta`` as the azimuthal angle
+    and ``phi`` as the polar angle.
+
+    Note that SciPy's spherical harmonics include the Condon-Shortley
+    phase [2]_ because it is part of `sph_legendre_p`.
+
+    With SciPy's conventions, the first several spherical harmonics
+    are
+
+    .. math::
+
+        Y_0^0(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{1}{\pi}} \\
+        Y_1^{-1}(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{3}{2\pi}}
+                                    e^{-i\phi} \sin(\theta) \\
+        Y_1^0(\theta, \phi) &= \frac{1}{2} \sqrt{\frac{3}{\pi}}
+                                 \cos(\theta) \\
+        Y_1^1(\theta, \phi) &= -\frac{1}{2} \sqrt{\frac{3}{2\pi}}
+                                 e^{i\phi} \sin(\theta).
+
+    References
+    ----------
+    .. [1] Digital Library of Mathematical Functions, 14.30.
+           https://dlmf.nist.gov/14.30
+    .. [2] https://en.wikipedia.org/wiki/Spherical_harmonics#Condon.E2.80.93Shortley_phase
+    """, force_complex_output=True, diff_n=0
+)
+
+
+@sph_harm_y._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 0, 1, and 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_harm_y._override_finalize_out
+def _(out):
+    if (out.shape[-1] == 1):
+        return out[..., 0, 0]
+
+    if (out.shape[-1] == 2):
+        return out[..., 0, 0], out[..., [1, 0], [0, 1]]
+
+    if (out.shape[-1] == 3):
+        return (out[..., 0, 0], out[..., [1, 0], [0, 1]],
+            out[..., [[2, 1], [1, 0]], [[0, 1], [1, 2]]])
+
+
+sph_harm_y_all = MultiUFunc(
+    sph_harm_y_all,
+    """sph_harm_y_all(n, m, theta, phi, *, diff_n=0)
+
+    All spherical harmonics up to the specified degree ``n`` and order ``m``.
+
+    Output shape is ``(n + 1, 2 * m + 1, ...)``. The entry at ``(j, i)``
+    corresponds to degree ``j`` and order ``i`` for all  ``0 <= j <= n``
+    and ``-m <= i <= m``.
+
+    See Also
+    --------
+    sph_harm_y
+    """, force_complex_output=True, diff_n=0
+)
+
+
+@sph_harm_y_all._override_key
+def _(diff_n):
+    diff_n = _nonneg_int_or_fail(diff_n, "diff_n", strict=False)
+    if not 0 <= diff_n <= 2:
+        raise ValueError(
+            "diff_n is currently only implemented for orders 2,"
+            f" received: {diff_n}."
+        )
+    return diff_n
+
+
+@sph_harm_y_all._override_ufunc_default_kwargs
+def _(diff_n):
+    return {'axes': [(), ()] + [(0, 1, -2, -1)]}
+
+
+@sph_harm_y_all._override_resolve_out_shapes
+def _(n, m, theta_shape, phi_shape, nout, **kwargs):
+    diff_n = kwargs['diff_n']
+
+    if not isinstance(n, numbers.Integral) or (n < 0):
+        raise ValueError("n must be a non-negative integer.")
+
+    return ((n + 1, 2 * abs(m) + 1) + np.broadcast_shapes(theta_shape, phi_shape) +
+        (diff_n + 1, diff_n + 1),)
+
+
+@sph_harm_y_all._override_finalize_out
+def _(out):
+    if (out.shape[-1] == 1):
+        return out[..., 0, 0]
+
+    if (out.shape[-1] == 2):
+        return out[..., 0, 0], out[..., [1, 0], [0, 1]]
+
+    if (out.shape[-1] == 3):
+        return (out[..., 0, 0], out[..., [1, 0], [0, 1]],
+            out[..., [[2, 1], [1, 0]], [[0, 1], [1, 2]]])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..e021f5a899b2b9218d59527fd91fb6cf7a545042
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.py
@@ -0,0 +1,2592 @@
+"""
+A collection of functions to find the weights and abscissas for
+Gaussian Quadrature.
+
+These calculations are done by finding the eigenvalues of a
+tridiagonal matrix whose entries are dependent on the coefficients
+in the recursion formula for the orthogonal polynomials with the
+corresponding weighting function over the interval.
+
+Many recursion relations for orthogonal polynomials are given:
+
+.. math::
+
+    a1n f_{n+1} (x) = (a2n + a3n x ) f_n (x) - a4n f_{n-1} (x)
+
+The recursion relation of interest is
+
+.. math::
+
+    P_{n+1} (x) = (x - A_n) P_n (x) - B_n P_{n-1} (x)
+
+where :math:`P` has a different normalization than :math:`f`.
+
+The coefficients can be found as:
+
+.. math::
+
+    A_n = -a2n / a3n
+    \\qquad
+    B_n = ( a4n / a3n \\sqrt{h_n-1 / h_n})^2
+
+where
+
+.. math::
+
+    h_n = \\int_a^b w(x) f_n(x)^2
+
+assume:
+
+.. math::
+
+    P_0 (x) = 1
+    \\qquad
+    P_{-1} (x) == 0
+
+For the mathematical background, see [golub.welsch-1969-mathcomp]_ and
+[abramowitz.stegun-1965]_.
+
+References
+----------
+.. [golub.welsch-1969-mathcomp]
+   Golub, Gene H, and John H Welsch. 1969. Calculation of Gauss
+   Quadrature Rules. *Mathematics of Computation* 23, 221-230+s1--s10.
+
+.. [abramowitz.stegun-1965]
+   Abramowitz, Milton, and Irene A Stegun. (1965) *Handbook of
+   Mathematical Functions: with Formulas, Graphs, and Mathematical
+   Tables*. Gaithersburg, MD: National Bureau of Standards.
+   http://www.math.sfu.ca/~cbm/aands/
+
+.. [townsend.trogdon.olver-2014]
+   Townsend, A. and Trogdon, T. and Olver, S. (2014)
+   *Fast computation of Gauss quadrature nodes and
+   weights on the whole real line*. :arXiv:`1410.5286`.
+
+.. [townsend.trogdon.olver-2015]
+   Townsend, A. and Trogdon, T. and Olver, S. (2015)
+   *Fast computation of Gauss quadrature nodes and
+   weights on the whole real line*.
+   IMA Journal of Numerical Analysis
+   :doi:`10.1093/imanum/drv002`.
+"""
+#
+# Author:  Travis Oliphant 2000
+# Updated Sep. 2003 (fixed bugs --- tested to be accurate)
+
+# SciPy imports.
+import numpy as np
+from numpy import (exp, inf, pi, sqrt, floor, sin, cos, around,
+                   hstack, arccos, arange)
+from scipy import linalg
+from scipy.special import airy
+
+# Local imports.
+# There is no .pyi file for _specfun
+from . import _specfun  # type: ignore
+from . import _ufuncs
+_gam = _ufuncs.gamma
+
+_polyfuns = ['legendre', 'chebyt', 'chebyu', 'chebyc', 'chebys',
+             'jacobi', 'laguerre', 'genlaguerre', 'hermite',
+             'hermitenorm', 'gegenbauer', 'sh_legendre', 'sh_chebyt',
+             'sh_chebyu', 'sh_jacobi']
+
+# Correspondence between new and old names of root functions
+_rootfuns_map = {'roots_legendre': 'p_roots',
+                 'roots_chebyt': 't_roots',
+                 'roots_chebyu': 'u_roots',
+                 'roots_chebyc': 'c_roots',
+                 'roots_chebys': 's_roots',
+                 'roots_jacobi': 'j_roots',
+                 'roots_laguerre': 'l_roots',
+                 'roots_genlaguerre': 'la_roots',
+                 'roots_hermite': 'h_roots',
+                 'roots_hermitenorm': 'he_roots',
+                 'roots_gegenbauer': 'cg_roots',
+                 'roots_sh_legendre': 'ps_roots',
+                 'roots_sh_chebyt': 'ts_roots',
+                 'roots_sh_chebyu': 'us_roots',
+                 'roots_sh_jacobi': 'js_roots'}
+
+__all__ = _polyfuns + list(_rootfuns_map.keys())
+
+
+class orthopoly1d(np.poly1d):
+
+    def __init__(self, roots, weights=None, hn=1.0, kn=1.0, wfunc=None,
+                 limits=None, monic=False, eval_func=None):
+        equiv_weights = [weights[k] / wfunc(roots[k]) for
+                         k in range(len(roots))]
+        mu = sqrt(hn)
+        if monic:
+            evf = eval_func
+            if evf:
+                knn = kn
+                def eval_func(x):
+                    return evf(x) / knn
+            mu = mu / abs(kn)
+            kn = 1.0
+
+        # compute coefficients from roots, then scale
+        poly = np.poly1d(roots, r=True)
+        np.poly1d.__init__(self, poly.coeffs * float(kn))
+
+        self.weights = np.array(list(zip(roots, weights, equiv_weights)))
+        self.weight_func = wfunc
+        self.limits = limits
+        self.normcoef = mu
+
+        # Note: eval_func will be discarded on arithmetic
+        self._eval_func = eval_func
+
+    def __call__(self, v):
+        if self._eval_func and not isinstance(v, np.poly1d):
+            return self._eval_func(v)
+        else:
+            return np.poly1d.__call__(self, v)
+
+    def _scale(self, p):
+        if p == 1.0:
+            return
+        self._coeffs *= p
+
+        evf = self._eval_func
+        if evf:
+            self._eval_func = lambda x: evf(x) * p
+        self.normcoef *= p
+
+
+def _gen_roots_and_weights(n, mu0, an_func, bn_func, f, df, symmetrize, mu):
+    """[x,w] = gen_roots_and_weights(n,an_func,sqrt_bn_func,mu)
+
+    Returns the roots (x) of an nth order orthogonal polynomial,
+    and weights (w) to use in appropriate Gaussian quadrature with that
+    orthogonal polynomial.
+
+    The polynomials have the recurrence relation
+          P_n+1(x) = (x - A_n) P_n(x) - B_n P_n-1(x)
+
+    an_func(n)          should return A_n
+    sqrt_bn_func(n)     should return sqrt(B_n)
+    mu ( = h_0 )        is the integral of the weight over the orthogonal
+                        interval
+    """
+    k = np.arange(n, dtype='d')
+    c = np.zeros((2, n))
+    c[0,1:] = bn_func(k[1:])
+    c[1,:] = an_func(k)
+    x = linalg.eigvals_banded(c, overwrite_a_band=True)
+
+    # improve roots by one application of Newton's method
+    y = f(n, x)
+    dy = df(n, x)
+    x -= y/dy
+
+    # fm and dy may contain very large/small values, so we
+    # log-normalize them to maintain precision in the product fm*dy
+    fm = f(n-1, x)
+    log_fm = np.log(np.abs(fm))
+    log_dy = np.log(np.abs(dy))
+    fm /= np.exp((log_fm.max() + log_fm.min()) / 2.)
+    dy /= np.exp((log_dy.max() + log_dy.min()) / 2.)
+    w = 1.0 / (fm * dy)
+
+    if symmetrize:
+        w = (w + w[::-1]) / 2
+        x = (x - x[::-1]) / 2
+
+    w *= mu0 / w.sum()
+
+    if mu:
+        return x, w, mu0
+    else:
+        return x, w
+
+# Jacobi Polynomials 1               P^(alpha,beta)_n(x)
+
+
+def roots_jacobi(n, alpha, beta, mu=False):
+    r"""Gauss-Jacobi quadrature.
+
+    Compute the sample points and weights for Gauss-Jacobi
+    quadrature. The sample points are the roots of the nth degree
+    Jacobi polynomial, :math:`P^{\alpha, \beta}_n(x)`. These sample
+    points and weights correctly integrate polynomials of degree
+    :math:`2n - 1` or less over the interval :math:`[-1, 1]` with
+    weight function :math:`w(x) = (1 - x)^{\alpha} (1 +
+    x)^{\beta}`. See 22.2.1 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    alpha : float
+        alpha must be > -1
+    beta : float
+        beta must be > -1
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+    if alpha <= -1 or beta <= -1:
+        raise ValueError("alpha and beta must be greater than -1.")
+
+    if alpha == 0.0 and beta == 0.0:
+        return roots_legendre(m, mu)
+    if alpha == beta:
+        return roots_gegenbauer(m, alpha+0.5, mu)
+
+    if (alpha + beta) <= 1000:
+        mu0 = 2.0**(alpha+beta+1) * _ufuncs.beta(alpha+1, beta+1)
+    else:
+        # Avoid overflows in pow and beta for very large parameters
+        mu0 = np.exp((alpha + beta + 1) * np.log(2.0)
+                     + _ufuncs.betaln(alpha+1, beta+1))
+    a = alpha
+    b = beta
+    if a + b == 0.0:
+        def an_func(k):
+            return np.where(k == 0, (b - a) / (2 + a + b), 0.0)
+    else:
+        def an_func(k):
+            return np.where(
+                k == 0,
+                (b - a) / (2 + a + b),
+                (b * b - a * a) / ((2.0 * k + a + b) * (2.0 * k + a + b + 2))
+            )
+
+    def bn_func(k):
+        return (
+            2.0 / (2.0 * k + a + b)
+            * np.sqrt((k + a) * (k + b) / (2 * k + a + b + 1))
+            * np.where(k == 1, 1.0, np.sqrt(k * (k + a + b) / (2.0 * k + a + b - 1)))
+        )
+
+    def f(n, x):
+        return _ufuncs.eval_jacobi(n, a, b, x)
+    def df(n, x):
+        return 0.5 * (n + a + b + 1) * _ufuncs.eval_jacobi(n - 1, a + 1, b + 1, x)
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu)
+
+
+def jacobi(n, alpha, beta, monic=False):
+    r"""Jacobi polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}P_n^{(\alpha, \beta)}
+          + (\beta - \alpha - (\alpha + \beta + 2)x)
+            \frac{d}{dx}P_n^{(\alpha, \beta)}
+          + n(n + \alpha + \beta + 1)P_n^{(\alpha, \beta)} = 0
+
+    for :math:`\alpha, \beta > -1`; :math:`P_n^{(\alpha, \beta)}` is a
+    polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    alpha : float
+        Parameter, must be greater than -1.
+    beta : float
+        Parameter, must be greater than -1.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    P : orthopoly1d
+        Jacobi polynomial.
+
+    Notes
+    -----
+    For fixed :math:`\alpha, \beta`, the polynomials
+    :math:`P_n^{(\alpha, \beta)}` are orthogonal over :math:`[-1, 1]`
+    with weight function :math:`(1 - x)^\alpha(1 + x)^\beta`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The Jacobi polynomials satisfy the recurrence relation:
+
+    .. math::
+        P_n^{(\alpha, \beta-1)}(x) - P_n^{(\alpha-1, \beta)}(x)
+          = P_{n-1}^{(\alpha, \beta)}(x)
+
+    This can be verified, for example, for :math:`\alpha = \beta = 2`
+    and :math:`n = 1` over the interval :math:`[-1, 1]`:
+
+    >>> import numpy as np
+    >>> from scipy.special import jacobi
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(jacobi(0, 2, 2)(x),
+    ...             jacobi(1, 2, 1)(x) - jacobi(1, 1, 2)(x))
+    True
+
+    Plot of the Jacobi polynomial :math:`P_5^{(\alpha, -0.5)}` for
+    different values of :math:`\alpha`:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 2.0)
+    >>> ax.set_title(r'Jacobi polynomials $P_5^{(\alpha, -0.5)}$')
+    >>> for alpha in np.arange(0, 4, 1):
+    ...     ax.plot(x, jacobi(5, alpha, -0.5)(x), label=rf'$\alpha={alpha}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return (1 - x) ** alpha * (1 + x) ** beta
+    if n == 0:
+        return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic,
+                           eval_func=np.ones_like)
+    x, w, mu = roots_jacobi(n, alpha, beta, mu=True)
+    ab1 = alpha + beta + 1.0
+    hn = 2**ab1 / (2 * n + ab1) * _gam(n + alpha + 1)
+    hn *= _gam(n + beta + 1.0) / _gam(n + 1) / _gam(n + ab1)
+    kn = _gam(2 * n + ab1) / 2.0**n / _gam(n + 1) / _gam(n + ab1)
+    # here kn = coefficient on x^n term
+    p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic,
+                    lambda x: _ufuncs.eval_jacobi(n, alpha, beta, x))
+    return p
+
+# Jacobi Polynomials shifted         G_n(p,q,x)
+
+
+def roots_sh_jacobi(n, p1, q1, mu=False):
+    """Gauss-Jacobi (shifted) quadrature.
+
+    Compute the sample points and weights for Gauss-Jacobi (shifted)
+    quadrature. The sample points are the roots of the nth degree
+    shifted Jacobi polynomial, :math:`G^{p,q}_n(x)`. These sample
+    points and weights correctly integrate polynomials of degree
+    :math:`2n - 1` or less over the interval :math:`[0, 1]` with
+    weight function :math:`w(x) = (1 - x)^{p-q} x^{q-1}`. See 22.2.2
+    in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    p1 : float
+        (p1 - q1) must be > -1
+    q1 : float
+        q1 must be > 0
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    if (p1-q1) <= -1 or q1 <= 0:
+        message = "(p - q) must be greater than -1, and q must be greater than 0."
+        raise ValueError(message)
+    x, w, m = roots_jacobi(n, p1-q1, q1-1, True)
+    x = (x + 1) / 2
+    scale = 2.0**p1
+    w /= scale
+    m /= scale
+    if mu:
+        return x, w, m
+    else:
+        return x, w
+
+
+def sh_jacobi(n, p, q, monic=False):
+    r"""Shifted Jacobi polynomial.
+
+    Defined by
+
+    .. math::
+
+        G_n^{(p, q)}(x)
+          = \binom{2n + p - 1}{n}^{-1}P_n^{(p - q, q - 1)}(2x - 1),
+
+    where :math:`P_n^{(\cdot, \cdot)}` is the nth Jacobi polynomial.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    p : float
+        Parameter, must have :math:`p > q - 1`.
+    q : float
+        Parameter, must be greater than 0.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    G : orthopoly1d
+        Shifted Jacobi polynomial.
+
+    Notes
+    -----
+    For fixed :math:`p, q`, the polynomials :math:`G_n^{(p, q)}` are
+    orthogonal over :math:`[0, 1]` with weight function :math:`(1 -
+    x)^{p - q}x^{q - 1}`.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return (1.0 - x) ** (p - q) * x ** (q - 1.0)
+    if n == 0:
+        return orthopoly1d([], [], 1.0, 1.0, wfunc, (-1, 1), monic,
+                           eval_func=np.ones_like)
+    n1 = n
+    x, w = roots_sh_jacobi(n1, p, q)
+    hn = _gam(n + 1) * _gam(n + q) * _gam(n + p) * _gam(n + p - q + 1)
+    hn /= (2 * n + p) * (_gam(2 * n + p)**2)
+    # kn = 1.0 in standard form so monic is redundant. Kept for compatibility.
+    kn = 1.0
+    pp = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(0, 1), monic=monic,
+                     eval_func=lambda x: _ufuncs.eval_sh_jacobi(n, p, q, x))
+    return pp
+
+# Generalized Laguerre               L^(alpha)_n(x)
+
+
+def roots_genlaguerre(n, alpha, mu=False):
+    r"""Gauss-generalized Laguerre quadrature.
+
+    Compute the sample points and weights for Gauss-generalized
+    Laguerre quadrature. The sample points are the roots of the nth
+    degree generalized Laguerre polynomial, :math:`L^{\alpha}_n(x)`.
+    These sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[0,
+    \infty]` with weight function :math:`w(x) = x^{\alpha}
+    e^{-x}`. See 22.3.9 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    alpha : float
+        alpha must be > -1
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+    if alpha < -1:
+        raise ValueError("alpha must be greater than -1.")
+
+    mu0 = _ufuncs.gamma(alpha + 1)
+
+    if m == 1:
+        x = np.array([alpha+1.0], 'd')
+        w = np.array([mu0], 'd')
+        if mu:
+            return x, w, mu0
+        else:
+            return x, w
+
+    def an_func(k):
+        return 2 * k + alpha + 1
+    def bn_func(k):
+        return -np.sqrt(k * (k + alpha))
+    def f(n, x):
+        return _ufuncs.eval_genlaguerre(n, alpha, x)
+    def df(n, x):
+        return (n * _ufuncs.eval_genlaguerre(n, alpha, x)
+                - (n + alpha) * _ufuncs.eval_genlaguerre(n - 1, alpha, x)) / x
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, False, mu)
+
+
+def genlaguerre(n, alpha, monic=False):
+    r"""Generalized (associated) Laguerre polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        x\frac{d^2}{dx^2}L_n^{(\alpha)}
+          + (\alpha + 1 - x)\frac{d}{dx}L_n^{(\alpha)}
+          + nL_n^{(\alpha)} = 0,
+
+    where :math:`\alpha > -1`; :math:`L_n^{(\alpha)}` is a polynomial
+    of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    alpha : float
+        Parameter, must be greater than -1.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    L : orthopoly1d
+        Generalized Laguerre polynomial.
+
+    See Also
+    --------
+    laguerre : Laguerre polynomial.
+    hyp1f1 : confluent hypergeometric function
+
+    Notes
+    -----
+    For fixed :math:`\alpha`, the polynomials :math:`L_n^{(\alpha)}`
+    are orthogonal over :math:`[0, \infty)` with weight function
+    :math:`e^{-x}x^\alpha`.
+
+    The Laguerre polynomials are the special case where :math:`\alpha
+    = 0`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The generalized Laguerre polynomials are closely related to the confluent
+    hypergeometric function :math:`{}_1F_1`:
+
+        .. math::
+            L_n^{(\alpha)} = \binom{n + \alpha}{n} {}_1F_1(-n, \alpha +1, x)
+
+    This can be verified, for example,  for :math:`n = \alpha = 3` over the
+    interval :math:`[-1, 1]`:
+
+    >>> import numpy as np
+    >>> from scipy.special import binom
+    >>> from scipy.special import genlaguerre
+    >>> from scipy.special import hyp1f1
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(genlaguerre(3, 3)(x), binom(6, 3) * hyp1f1(-3, 4, x))
+    True
+
+    This is the plot of the generalized Laguerre polynomials
+    :math:`L_3^{(\alpha)}` for some values of :math:`\alpha`:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(-4.0, 12.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-5.0, 10.0)
+    >>> ax.set_title(r'Generalized Laguerre polynomials $L_3^{\alpha}$')
+    >>> for alpha in np.arange(0, 5):
+    ...     ax.plot(x, genlaguerre(3, alpha)(x), label=rf'$L_3^{(alpha)}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if alpha <= -1:
+        raise ValueError("alpha must be > -1")
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_genlaguerre(n1, alpha)
+    def wfunc(x):
+        return exp(-x) * x ** alpha
+    if n == 0:
+        x, w = [], []
+    hn = _gam(n + alpha + 1) / _gam(n + 1)
+    kn = (-1)**n / _gam(n + 1)
+    p = orthopoly1d(x, w, hn, kn, wfunc, (0, inf), monic,
+                    lambda x: _ufuncs.eval_genlaguerre(n, alpha, x))
+    return p
+
+# Laguerre                      L_n(x)
+
+
+def roots_laguerre(n, mu=False):
+    r"""Gauss-Laguerre quadrature.
+
+    Compute the sample points and weights for Gauss-Laguerre
+    quadrature. The sample points are the roots of the nth degree
+    Laguerre polynomial, :math:`L_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[0, \infty]` with weight function
+    :math:`w(x) = e^{-x}`. See 22.2.13 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.laguerre.laggauss
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    return roots_genlaguerre(n, 0.0, mu=mu)
+
+
+def laguerre(n, monic=False):
+    r"""Laguerre polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        x\frac{d^2}{dx^2}L_n + (1 - x)\frac{d}{dx}L_n + nL_n = 0;
+
+    :math:`L_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    L : orthopoly1d
+        Laguerre Polynomial.
+
+    See Also
+    --------
+    genlaguerre : Generalized (associated) Laguerre polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`L_n` are orthogonal over :math:`[0,
+    \infty)` with weight function :math:`e^{-x}`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The Laguerre polynomials :math:`L_n` are the special case
+    :math:`\alpha = 0` of the generalized Laguerre polynomials
+    :math:`L_n^{(\alpha)}`.
+    Let's verify it on the interval :math:`[-1, 1]`:
+
+    >>> import numpy as np
+    >>> from scipy.special import genlaguerre
+    >>> from scipy.special import laguerre
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(genlaguerre(3, 0)(x), laguerre(3)(x))
+    True
+
+    The polynomials :math:`L_n` also satisfy the recurrence relation:
+
+    .. math::
+        (n + 1)L_{n+1}(x) = (2n +1 -x)L_n(x) - nL_{n-1}(x)
+
+    This can be easily checked on :math:`[0, 1]` for :math:`n = 3`:
+
+    >>> x = np.arange(0.0, 1.0, 0.01)
+    >>> np.allclose(4 * laguerre(4)(x),
+    ...             (7 - x) * laguerre(3)(x) - 3 * laguerre(2)(x))
+    True
+
+    This is the plot of the first few Laguerre polynomials :math:`L_n`:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(-1.0, 5.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-5.0, 5.0)
+    >>> ax.set_title(r'Laguerre polynomials $L_n$')
+    >>> for n in np.arange(0, 5):
+    ...     ax.plot(x, laguerre(n)(x), label=rf'$L_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_laguerre(n1)
+    if n == 0:
+        x, w = [], []
+    hn = 1.0
+    kn = (-1)**n / _gam(n + 1)
+    p = orthopoly1d(x, w, hn, kn, lambda x: exp(-x), (0, inf), monic,
+                    lambda x: _ufuncs.eval_laguerre(n, x))
+    return p
+
+# Hermite  1                         H_n(x)
+
+
+def roots_hermite(n, mu=False):
+    r"""Gauss-Hermite (physicist's) quadrature.
+
+    Compute the sample points and weights for Gauss-Hermite
+    quadrature. The sample points are the roots of the nth degree
+    Hermite polynomial, :math:`H_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[-\infty, \infty]` with weight
+    function :math:`w(x) = e^{-x^2}`. See 22.2.14 in [AS]_ for
+    details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.hermite.hermgauss
+    roots_hermitenorm
+
+    Notes
+    -----
+    For small n up to 150 a modified version of the Golub-Welsch
+    algorithm is used. Nodes are computed from the eigenvalue
+    problem and improved by one step of a Newton iteration.
+    The weights are computed from the well-known analytical formula.
+
+    For n larger than 150 an optimal asymptotic algorithm is applied
+    which computes nodes and weights in a numerically stable manner.
+    The algorithm has linear runtime making computation for very
+    large n (several thousand or more) feasible.
+
+    References
+    ----------
+    .. [townsend.trogdon.olver-2014]
+        Townsend, A. and Trogdon, T. and Olver, S. (2014)
+        *Fast computation of Gauss quadrature nodes and
+        weights on the whole real line*. :arXiv:`1410.5286`.
+    .. [townsend.trogdon.olver-2015]
+        Townsend, A. and Trogdon, T. and Olver, S. (2015)
+        *Fast computation of Gauss quadrature nodes and
+        weights on the whole real line*.
+        IMA Journal of Numerical Analysis
+        :doi:`10.1093/imanum/drv002`.
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+
+    mu0 = np.sqrt(np.pi)
+    if n <= 150:
+        def an_func(k):
+            return 0.0 * k
+        def bn_func(k):
+            return np.sqrt(k / 2.0)
+        f = _ufuncs.eval_hermite
+        def df(n, x):
+            return 2.0 * n * _ufuncs.eval_hermite(n - 1, x)
+        return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+    else:
+        nodes, weights = _roots_hermite_asy(m)
+        if mu:
+            return nodes, weights, mu0
+        else:
+            return nodes, weights
+
+
+def _compute_tauk(n, k, maxit=5):
+    """Helper function for Tricomi initial guesses
+
+    For details, see formula 3.1 in lemma 3.1 in the
+    original paper.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    k : ndarray of type int
+        Index of roots :math:`\tau_k` to compute
+    maxit : int
+        Number of Newton maxit performed, the default
+        value of 5 is sufficient.
+
+    Returns
+    -------
+    tauk : ndarray
+        Roots of equation 3.1
+
+    See Also
+    --------
+    initial_nodes_a
+    roots_hermite_asy
+    """
+    a = n % 2 - 0.5
+    c = (4.0*floor(n/2.0) - 4.0*k + 3.0)*pi / (4.0*floor(n/2.0) + 2.0*a + 2.0)
+    def f(x):
+        return x - sin(x) - c
+    def df(x):
+        return 1.0 - cos(x)
+    xi = 0.5*pi
+    for i in range(maxit):
+        xi = xi - f(xi)/df(xi)
+    return xi
+
+
+def _initial_nodes_a(n, k):
+    r"""Tricomi initial guesses
+
+    Computes an initial approximation to the square of the `k`-th
+    (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n`
+    of order :math:`n`. The formula is the one from lemma 3.1 in the
+    original paper. The guesses are accurate except in the region
+    near :math:`\sqrt{2n + 1}`.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    k : ndarray of type int
+        Index of roots to compute
+
+    Returns
+    -------
+    xksq : ndarray
+        Square of the approximate roots
+
+    See Also
+    --------
+    initial_nodes
+    roots_hermite_asy
+    """
+    tauk = _compute_tauk(n, k)
+    sigk = cos(0.5*tauk)**2
+    a = n % 2 - 0.5
+    nu = 4.0*floor(n/2.0) + 2.0*a + 2.0
+    # Initial approximation of Hermite roots (square)
+    xksq = nu*sigk - 1.0/(3.0*nu) * (5.0/(4.0*(1.0-sigk)**2) - 1.0/(1.0-sigk) - 0.25)
+    return xksq
+
+
+def _initial_nodes_b(n, k):
+    r"""Gatteschi initial guesses
+
+    Computes an initial approximation to the square of the kth
+    (positive) root :math:`x_k` of the Hermite polynomial :math:`H_n`
+    of order :math:`n`. The formula is the one from lemma 3.2 in the
+    original paper. The guesses are accurate in the region just
+    below :math:`\sqrt{2n + 1}`.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    k : ndarray of type int
+        Index of roots to compute
+
+    Returns
+    -------
+    xksq : ndarray
+        Square of the approximate root
+
+    See Also
+    --------
+    initial_nodes
+    roots_hermite_asy
+    """
+    a = n % 2 - 0.5
+    nu = 4.0*floor(n/2.0) + 2.0*a + 2.0
+    # Airy roots by approximation
+    ak = _specfun.airyzo(k.max(), 1)[0][::-1]
+    # Initial approximation of Hermite roots (square)
+    xksq = (nu
+            + 2.0**(2.0/3.0) * ak * nu**(1.0/3.0)
+            + 1.0/5.0 * 2.0**(4.0/3.0) * ak**2 * nu**(-1.0/3.0)
+            + (9.0/140.0 - 12.0/175.0 * ak**3) * nu**(-1.0)
+            + (16.0/1575.0 * ak + 92.0/7875.0 * ak**4) * 2.0**(2.0/3.0) * nu**(-5.0/3.0)
+            - (15152.0/3031875.0 * ak**5 + 1088.0/121275.0 * ak**2)
+              * 2.0**(1.0/3.0) * nu**(-7.0/3.0))
+    return xksq
+
+
+def _initial_nodes(n):
+    """Initial guesses for the Hermite roots
+
+    Computes an initial approximation to the non-negative
+    roots :math:`x_k` of the Hermite polynomial :math:`H_n`
+    of order :math:`n`. The Tricomi and Gatteschi initial
+    guesses are used in the region where they are accurate.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+
+    Returns
+    -------
+    xk : ndarray
+        Approximate roots
+
+    See Also
+    --------
+    roots_hermite_asy
+    """
+    # Turnover point
+    # linear polynomial fit to error of 10, 25, 40, ..., 1000 point rules
+    fit = 0.49082003*n - 4.37859653
+    turnover = around(fit).astype(int)
+    # Compute all approximations
+    ia = arange(1, int(floor(n*0.5)+1))
+    ib = ia[::-1]
+    xasq = _initial_nodes_a(n, ia[:turnover+1])
+    xbsq = _initial_nodes_b(n, ib[turnover+1:])
+    # Combine
+    iv = sqrt(hstack([xasq, xbsq]))
+    # Central node is always zero
+    if n % 2 == 1:
+        iv = hstack([0.0, iv])
+    return iv
+
+
+def _pbcf(n, theta):
+    r"""Asymptotic series expansion of parabolic cylinder function
+
+    The implementation is based on sections 3.2 and 3.3 from the
+    original paper. Compared to the published version this code
+    adds one more term to the asymptotic series. The detailed
+    formulas can be found at [parabolic-asymptotics]_. The evaluation
+    is done in a transformed variable :math:`\theta := \arccos(t)`
+    where :math:`t := x / \mu` and :math:`\mu := \sqrt{2n + 1}`.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    theta : ndarray
+        Transformed position variable
+
+    Returns
+    -------
+    U : ndarray
+        Value of the parabolic cylinder function :math:`U(a, \theta)`.
+    Ud : ndarray
+        Value of the derivative :math:`U^{\prime}(a, \theta)` of
+        the parabolic cylinder function.
+
+    See Also
+    --------
+    roots_hermite_asy
+
+    References
+    ----------
+    .. [parabolic-asymptotics]
+       https://dlmf.nist.gov/12.10#vii
+    """
+    st = sin(theta)
+    ct = cos(theta)
+    # https://dlmf.nist.gov/12.10#vii
+    mu = 2.0*n + 1.0
+    # https://dlmf.nist.gov/12.10#E23
+    eta = 0.5*theta - 0.5*st*ct
+    # https://dlmf.nist.gov/12.10#E39
+    zeta = -(3.0*eta/2.0) ** (2.0/3.0)
+    # https://dlmf.nist.gov/12.10#E40
+    phi = (-zeta / st**2) ** (0.25)
+    # Coefficients
+    # https://dlmf.nist.gov/12.10#E43
+    a0 = 1.0
+    a1 = 0.10416666666666666667
+    a2 = 0.08355034722222222222
+    a3 = 0.12822657455632716049
+    a4 = 0.29184902646414046425
+    a5 = 0.88162726744375765242
+    b0 = 1.0
+    b1 = -0.14583333333333333333
+    b2 = -0.09874131944444444444
+    b3 = -0.14331205391589506173
+    b4 = -0.31722720267841354810
+    b5 = -0.94242914795712024914
+    # Polynomials
+    # https://dlmf.nist.gov/12.10#E9
+    # https://dlmf.nist.gov/12.10#E10
+    ctp = ct ** arange(16).reshape((-1,1))
+    u0 = 1.0
+    u1 = (1.0*ctp[3,:] - 6.0*ct) / 24.0
+    u2 = (-9.0*ctp[4,:] + 249.0*ctp[2,:] + 145.0) / 1152.0
+    u3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 28287.0*ctp[5,:]
+          - 151995.0*ctp[3,:] - 259290.0*ct) / 414720.0
+    u4 = (72756.0*ctp[10,:] - 321339.0*ctp[8,:] - 154982.0*ctp[6,:]
+          + 50938215.0*ctp[4,:] + 122602962.0*ctp[2,:] + 12773113.0) / 39813120.0
+    u5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 1994971575.0*ctp[11,:]
+          - 3630137104.0*ctp[9,:] + 4433574213.0*ctp[7,:] - 37370295816.0*ctp[5,:]
+          - 119582875013.0*ctp[3,:] - 34009066266.0*ct) / 6688604160.0
+    v0 = 1.0
+    v1 = (1.0*ctp[3,:] + 6.0*ct) / 24.0
+    v2 = (15.0*ctp[4,:] - 327.0*ctp[2,:] - 143.0) / 1152.0
+    v3 = (-4042.0*ctp[9,:] + 18189.0*ctp[7,:] - 36387.0*ctp[5,:] 
+          + 238425.0*ctp[3,:] + 259290.0*ct) / 414720.0
+    v4 = (-121260.0*ctp[10,:] + 551733.0*ctp[8,:] - 151958.0*ctp[6,:]
+          - 57484425.0*ctp[4,:] - 132752238.0*ctp[2,:] - 12118727) / 39813120.0
+    v5 = (82393456.0*ctp[15,:] - 617950920.0*ctp[13,:] + 2025529095.0*ctp[11,:]
+          - 3750839308.0*ctp[9,:] + 3832454253.0*ctp[7,:] + 35213253348.0*ctp[5,:]
+          + 130919230435.0*ctp[3,:] + 34009066266*ct) / 6688604160.0
+    # Airy Evaluation (Bi and Bip unused)
+    Ai, Aip, Bi, Bip = airy(mu**(4.0/6.0) * zeta)
+    # Prefactor for U
+    P = 2.0*sqrt(pi) * mu**(1.0/6.0) * phi
+    # Terms for U
+    # https://dlmf.nist.gov/12.10#E42
+    phip = phi ** arange(6, 31, 6).reshape((-1,1))
+    A0 = b0*u0
+    A1 = (b2*u0 + phip[0,:]*b1*u1 + phip[1,:]*b0*u2) / zeta**3
+    A2 = (b4*u0 + phip[0,:]*b3*u1 + phip[1,:]*b2*u2 + phip[2,:]*b1*u3
+          + phip[3,:]*b0*u4) / zeta**6
+    B0 = -(a1*u0 + phip[0,:]*a0*u1) / zeta**2
+    B1 = -(a3*u0 + phip[0,:]*a2*u1 + phip[1,:]*a1*u2 + phip[2,:]*a0*u3) / zeta**5
+    B2 = -(a5*u0 + phip[0,:]*a4*u1 + phip[1,:]*a3*u2 + phip[2,:]*a2*u3
+           + phip[3,:]*a1*u4 + phip[4,:]*a0*u5) / zeta**8
+    # U
+    # https://dlmf.nist.gov/12.10#E35
+    U = P * (Ai * (A0 + A1/mu**2.0 + A2/mu**4.0) +
+             Aip * (B0 + B1/mu**2.0 + B2/mu**4.0) / mu**(8.0/6.0))
+    # Prefactor for derivative of U
+    Pd = sqrt(2.0*pi) * mu**(2.0/6.0) / phi
+    # Terms for derivative of U
+    # https://dlmf.nist.gov/12.10#E46
+    C0 = -(b1*v0 + phip[0,:]*b0*v1) / zeta
+    C1 = -(b3*v0 + phip[0,:]*b2*v1 + phip[1,:]*b1*v2 + phip[2,:]*b0*v3) / zeta**4
+    C2 = -(b5*v0 + phip[0,:]*b4*v1 + phip[1,:]*b3*v2 + phip[2,:]*b2*v3
+           + phip[3,:]*b1*v4 + phip[4,:]*b0*v5) / zeta**7
+    D0 = a0*v0
+    D1 = (a2*v0 + phip[0,:]*a1*v1 + phip[1,:]*a0*v2) / zeta**3
+    D2 = (a4*v0 + phip[0,:]*a3*v1 + phip[1,:]*a2*v2 + phip[2,:]*a1*v3
+          + phip[3,:]*a0*v4) / zeta**6
+    # Derivative of U
+    # https://dlmf.nist.gov/12.10#E36
+    Ud = Pd * (Ai * (C0 + C1/mu**2.0 + C2/mu**4.0) / mu**(4.0/6.0) +
+               Aip * (D0 + D1/mu**2.0 + D2/mu**4.0))
+    return U, Ud
+
+
+def _newton(n, x_initial, maxit=5):
+    """Newton iteration for polishing the asymptotic approximation
+    to the zeros of the Hermite polynomials.
+
+    Parameters
+    ----------
+    n : int
+        Quadrature order
+    x_initial : ndarray
+        Initial guesses for the roots
+    maxit : int
+        Maximal number of Newton iterations.
+        The default 5 is sufficient, usually
+        only one or two steps are needed.
+
+    Returns
+    -------
+    nodes : ndarray
+        Quadrature nodes
+    weights : ndarray
+        Quadrature weights
+
+    See Also
+    --------
+    roots_hermite_asy
+    """
+    # Variable transformation
+    mu = sqrt(2.0*n + 1.0)
+    t = x_initial / mu
+    theta = arccos(t)
+    # Newton iteration
+    for i in range(maxit):
+        u, ud = _pbcf(n, theta)
+        dtheta = u / (sqrt(2.0) * mu * sin(theta) * ud)
+        theta = theta + dtheta
+        if max(abs(dtheta)) < 1e-14:
+            break
+    # Undo variable transformation
+    x = mu * cos(theta)
+    # Central node is always zero
+    if n % 2 == 1:
+        x[0] = 0.0
+    # Compute weights
+    w = exp(-x**2) / (2.0*ud**2)
+    return x, w
+
+
+def _roots_hermite_asy(n):
+    r"""Gauss-Hermite (physicist's) quadrature for large n.
+
+    Computes the sample points and weights for Gauss-Hermite quadrature.
+    The sample points are the roots of the nth degree Hermite polynomial,
+    :math:`H_n(x)`. These sample points and weights correctly integrate
+    polynomials of degree :math:`2n - 1` or less over the interval
+    :math:`[-\infty, \infty]` with weight function :math:`f(x) = e^{-x^2}`.
+
+    This method relies on asymptotic expansions which work best for n > 150.
+    The algorithm has linear runtime making computation for very large n
+    feasible.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+
+    Returns
+    -------
+    nodes : ndarray
+        Quadrature nodes
+    weights : ndarray
+        Quadrature weights
+
+    See Also
+    --------
+    roots_hermite
+
+    References
+    ----------
+    .. [townsend.trogdon.olver-2014]
+       Townsend, A. and Trogdon, T. and Olver, S. (2014)
+       *Fast computation of Gauss quadrature nodes and
+       weights on the whole real line*. :arXiv:`1410.5286`.
+
+    .. [townsend.trogdon.olver-2015]
+       Townsend, A. and Trogdon, T. and Olver, S. (2015)
+       *Fast computation of Gauss quadrature nodes and
+       weights on the whole real line*.
+       IMA Journal of Numerical Analysis
+       :doi:`10.1093/imanum/drv002`.
+    """
+    iv = _initial_nodes(n)
+    nodes, weights = _newton(n, iv)
+    # Combine with negative parts
+    if n % 2 == 0:
+        nodes = hstack([-nodes[::-1], nodes])
+        weights = hstack([weights[::-1], weights])
+    else:
+        nodes = hstack([-nodes[-1:0:-1], nodes])
+        weights = hstack([weights[-1:0:-1], weights])
+    # Scale weights
+    weights *= sqrt(pi) / sum(weights)
+    return nodes, weights
+
+
+def hermite(n, monic=False):
+    r"""Physicist's Hermite polynomial.
+
+    Defined by
+
+    .. math::
+
+        H_n(x) = (-1)^ne^{x^2}\frac{d^n}{dx^n}e^{-x^2};
+
+    :math:`H_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    H : orthopoly1d
+        Hermite polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`H_n` are orthogonal over :math:`(-\infty,
+    \infty)` with weight function :math:`e^{-x^2}`.
+
+    Examples
+    --------
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+    >>> import numpy as np
+
+    >>> p_monic = special.hermite(3, monic=True)
+    >>> p_monic
+    poly1d([ 1. ,  0. , -1.5,  0. ])
+    >>> p_monic(1)
+    -0.49999999999999983
+    >>> x = np.linspace(-3, 3, 400)
+    >>> y = p_monic(x)
+    >>> plt.plot(x, y)
+    >>> plt.title("Monic Hermite polynomial of degree 3")
+    >>> plt.xlabel("x")
+    >>> plt.ylabel("H_3(x)")
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_hermite(n1)
+    def wfunc(x):
+        return exp(-x * x)
+    if n == 0:
+        x, w = [], []
+    hn = 2**n * _gam(n + 1) * sqrt(pi)
+    kn = 2**n
+    p = orthopoly1d(x, w, hn, kn, wfunc, (-inf, inf), monic,
+                    lambda x: _ufuncs.eval_hermite(n, x))
+    return p
+
+# Hermite  2                         He_n(x)
+
+
+def roots_hermitenorm(n, mu=False):
+    r"""Gauss-Hermite (statistician's) quadrature.
+
+    Compute the sample points and weights for Gauss-Hermite
+    quadrature. The sample points are the roots of the nth degree
+    Hermite polynomial, :math:`He_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[-\infty, \infty]` with weight
+    function :math:`w(x) = e^{-x^2/2}`. See 22.2.15 in [AS]_ for more
+    details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.hermite_e.hermegauss
+
+    Notes
+    -----
+    For small n up to 150 a modified version of the Golub-Welsch
+    algorithm is used. Nodes are computed from the eigenvalue
+    problem and improved by one step of a Newton iteration.
+    The weights are computed from the well-known analytical formula.
+
+    For n larger than 150 an optimal asymptotic algorithm is used
+    which computes nodes and weights in a numerical stable manner.
+    The algorithm has linear runtime making computation for very
+    large n (several thousand or more) feasible.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+
+    mu0 = np.sqrt(2.0*np.pi)
+    if n <= 150:
+        def an_func(k):
+            return 0.0 * k
+        def bn_func(k):
+            return np.sqrt(k)
+        f = _ufuncs.eval_hermitenorm
+        def df(n, x):
+            return n * _ufuncs.eval_hermitenorm(n - 1, x)
+        return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+    else:
+        nodes, weights = _roots_hermite_asy(m)
+        # Transform
+        nodes *= sqrt(2)
+        weights *= sqrt(2)
+        if mu:
+            return nodes, weights, mu0
+        else:
+            return nodes, weights
+
+
+def hermitenorm(n, monic=False):
+    r"""Normalized (probabilist's) Hermite polynomial.
+
+    Defined by
+
+    .. math::
+
+        He_n(x) = (-1)^ne^{x^2/2}\frac{d^n}{dx^n}e^{-x^2/2};
+
+    :math:`He_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    He : orthopoly1d
+        Hermite polynomial.
+
+    Notes
+    -----
+
+    The polynomials :math:`He_n` are orthogonal over :math:`(-\infty,
+    \infty)` with weight function :math:`e^{-x^2/2}`.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_hermitenorm(n1)
+    def wfunc(x):
+        return exp(-x * x / 2.0)
+    if n == 0:
+        x, w = [], []
+    hn = sqrt(2 * pi) * _gam(n + 1)
+    kn = 1.0
+    p = orthopoly1d(x, w, hn, kn, wfunc=wfunc, limits=(-inf, inf), monic=monic,
+                    eval_func=lambda x: _ufuncs.eval_hermitenorm(n, x))
+    return p
+
+# The remainder of the polynomials can be derived from the ones above.
+
+# Ultraspherical (Gegenbauer)        C^(alpha)_n(x)
+
+
+def roots_gegenbauer(n, alpha, mu=False):
+    r"""Gauss-Gegenbauer quadrature.
+
+    Compute the sample points and weights for Gauss-Gegenbauer
+    quadrature. The sample points are the roots of the nth degree
+    Gegenbauer polynomial, :math:`C^{\alpha}_n(x)`. These sample
+    points and weights correctly integrate polynomials of degree
+    :math:`2n - 1` or less over the interval :math:`[-1, 1]` with
+    weight function :math:`w(x) = (1 - x^2)^{\alpha - 1/2}`. See
+    22.2.3 in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    alpha : float
+        alpha must be > -0.5
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+    if alpha < -0.5:
+        raise ValueError("alpha must be greater than -0.5.")
+    elif alpha == 0.0:
+        # C(n,0,x) == 0 uniformly, however, as alpha->0, C(n,alpha,x)->T(n,x)
+        # strictly, we should just error out here, since the roots are not
+        # really defined, but we used to return something useful, so let's
+        # keep doing so.
+        return roots_chebyt(n, mu)
+
+    if alpha <= 170:
+        mu0 = (np.sqrt(np.pi) * _ufuncs.gamma(alpha + 0.5)) \
+              / _ufuncs.gamma(alpha + 1)
+    else:
+        # For large alpha we use a Taylor series expansion around inf,
+        # expressed as a 6th order polynomial of a^-1 and using Horner's
+        # method to minimize computation and maximize precision
+        inv_alpha = 1. / alpha
+        coeffs = np.array([0.000207186, -0.00152206, -0.000640869,
+                           0.00488281, 0.0078125, -0.125, 1.])
+        mu0 = coeffs[0]
+        for term in range(1, len(coeffs)):
+            mu0 = mu0 * inv_alpha + coeffs[term]
+        mu0 = mu0 * np.sqrt(np.pi / alpha)
+    def an_func(k):
+        return 0.0 * k
+    def bn_func(k):
+        return np.sqrt(k * (k + 2 * alpha - 1) / (4 * (k + alpha) * (k + alpha - 1)))
+    def f(n, x):
+        return _ufuncs.eval_gegenbauer(n, alpha, x)
+    def df(n, x):
+        return (
+            -n * x * _ufuncs.eval_gegenbauer(n, alpha, x)
+            + (n + 2 * alpha - 1) * _ufuncs.eval_gegenbauer(n - 1, alpha, x)
+        ) / (1 - x ** 2)
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+
+
+def gegenbauer(n, alpha, monic=False):
+    r"""Gegenbauer (ultraspherical) polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}C_n^{(\alpha)}
+          - (2\alpha + 1)x\frac{d}{dx}C_n^{(\alpha)}
+          + n(n + 2\alpha)C_n^{(\alpha)} = 0
+
+    for :math:`\alpha > -1/2`; :math:`C_n^{(\alpha)}` is a polynomial
+    of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    alpha : float
+        Parameter, must be greater than -0.5.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    C : orthopoly1d
+        Gegenbauer polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`C_n^{(\alpha)}` are orthogonal over
+    :math:`[-1,1]` with weight function :math:`(1 - x^2)^{(\alpha -
+    1/2)}`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import special
+    >>> import matplotlib.pyplot as plt
+
+    We can initialize a variable ``p`` as a Gegenbauer polynomial using the
+    `gegenbauer` function and evaluate at a point ``x = 1``.
+
+    >>> p = special.gegenbauer(3, 0.5, monic=False)
+    >>> p
+    poly1d([ 2.5,  0. , -1.5,  0. ])
+    >>> p(1)
+    1.0
+
+    To evaluate ``p`` at various points ``x`` in the interval ``(-3, 3)``,
+    simply pass an array ``x`` to ``p`` as follows:
+
+    >>> x = np.linspace(-3, 3, 400)
+    >>> y = p(x)
+
+    We can then visualize ``x, y`` using `matplotlib.pyplot`.
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.plot(x, y)
+    >>> ax.set_title("Gegenbauer (ultraspherical) polynomial of degree 3")
+    >>> ax.set_xlabel("x")
+    >>> ax.set_ylabel("G_3(x)")
+    >>> plt.show()
+
+    """
+    if not np.isfinite(alpha) or alpha <= -0.5 :
+        raise ValueError("`alpha` must be a finite number greater than -1/2")
+    base = jacobi(n, alpha - 0.5, alpha - 0.5, monic=monic)
+    if monic or n == 0:
+        return base
+    #  Abrahmowitz and Stegan 22.5.20
+    factor = (_gam(2*alpha + n) * _gam(alpha + 0.5) /
+              _gam(2*alpha) / _gam(alpha + 0.5 + n))
+    base._scale(factor)
+    base.__dict__['_eval_func'] = lambda x: _ufuncs.eval_gegenbauer(float(n),
+                                                                    alpha, x)
+    return base
+
+# Chebyshev of the first kind: T_n(x) =
+#     n! sqrt(pi) / _gam(n+1./2)* P^(-1/2,-1/2)_n(x)
+# Computed anew.
+
+
+def roots_chebyt(n, mu=False):
+    r"""Gauss-Chebyshev (first kind) quadrature.
+
+    Computes the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the first kind, :math:`T_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-1, 1]`
+    with weight function :math:`w(x) = 1/\sqrt{1 - x^2}`. See 22.2.4
+    in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.chebyshev.chebgauss
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError('n must be a positive integer.')
+    x = _ufuncs._sinpi(np.arange(-m + 1, m, 2) / (2*m))
+    w = np.full_like(x, pi/m)
+    if mu:
+        return x, w, pi
+    else:
+        return x, w
+
+
+def chebyt(n, monic=False):
+    r"""Chebyshev polynomial of the first kind.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}T_n - x\frac{d}{dx}T_n + n^2T_n = 0;
+
+    :math:`T_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    T : orthopoly1d
+        Chebyshev polynomial of the first kind.
+
+    See Also
+    --------
+    chebyu : Chebyshev polynomial of the second kind.
+
+    Notes
+    -----
+    The polynomials :math:`T_n` are orthogonal over :math:`[-1, 1]`
+    with weight function :math:`(1 - x^2)^{-1/2}`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Chebyshev polynomials of the first kind of order :math:`n` can
+    be obtained as the determinant of specific :math:`n \times n`
+    matrices. As an example we can check how the points obtained from
+    the determinant of the following :math:`3 \times 3` matrix
+    lay exactly on :math:`T_3`:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.linalg import det
+    >>> from scipy.special import chebyt
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 2.0)
+    >>> ax.set_title(r'Chebyshev polynomial $T_3$')
+    >>> ax.plot(x, chebyt(3)(x), label=rf'$T_3$')
+    >>> for p in np.arange(-1.0, 1.0, 0.1):
+    ...     ax.plot(p,
+    ...             det(np.array([[p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])),
+    ...             'rx')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    They are also related to the Jacobi Polynomials
+    :math:`P_n^{(-0.5, -0.5)}` through the relation:
+
+    .. math::
+        P_n^{(-0.5, -0.5)}(x) = \frac{1}{4^n} \binom{2n}{n} T_n(x)
+
+    Let's verify it for :math:`n = 3`:
+
+    >>> from scipy.special import binom
+    >>> from scipy.special import jacobi
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(jacobi(3, -0.5, -0.5)(x),
+    ...             1/64 * binom(6, 3) * chebyt(3)(x))
+    True
+
+    We can plot the Chebyshev polynomials :math:`T_n` for some values
+    of :math:`n`:
+
+    >>> x = np.arange(-1.5, 1.5, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-4.0, 4.0)
+    >>> ax.set_title(r'Chebyshev polynomials $T_n$')
+    >>> for n in np.arange(2,5):
+    ...     ax.plot(x, chebyt(n)(x), label=rf'$T_n={n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return 1.0 / sqrt(1 - x * x)
+    if n == 0:
+        return orthopoly1d([], [], pi, 1.0, wfunc, (-1, 1), monic,
+                           lambda x: _ufuncs.eval_chebyt(n, x))
+    n1 = n
+    x, w, mu = roots_chebyt(n1, mu=True)
+    hn = pi / 2
+    kn = 2**(n - 1)
+    p = orthopoly1d(x, w, hn, kn, wfunc, (-1, 1), monic,
+                    lambda x: _ufuncs.eval_chebyt(n, x))
+    return p
+
+# Chebyshev of the second kind
+#    U_n(x) = (n+1)! sqrt(pi) / (2*_gam(n+3./2)) * P^(1/2,1/2)_n(x)
+
+
+def roots_chebyu(n, mu=False):
+    r"""Gauss-Chebyshev (second kind) quadrature.
+
+    Computes the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the second kind, :math:`U_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-1, 1]`
+    with weight function :math:`w(x) = \sqrt{1 - x^2}`. See 22.2.5 in
+    [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError('n must be a positive integer.')
+    t = np.arange(m, 0, -1) * pi / (m + 1)
+    x = np.cos(t)
+    w = pi * np.sin(t)**2 / (m + 1)
+    if mu:
+        return x, w, pi / 2
+    else:
+        return x, w
+
+
+def chebyu(n, monic=False):
+    r"""Chebyshev polynomial of the second kind.
+
+    Defined to be the solution of
+
+    .. math::
+        (1 - x^2)\frac{d^2}{dx^2}U_n - 3x\frac{d}{dx}U_n
+          + n(n + 2)U_n = 0;
+
+    :math:`U_n` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    U : orthopoly1d
+        Chebyshev polynomial of the second kind.
+
+    See Also
+    --------
+    chebyt : Chebyshev polynomial of the first kind.
+
+    Notes
+    -----
+    The polynomials :math:`U_n` are orthogonal over :math:`[-1, 1]`
+    with weight function :math:`(1 - x^2)^{1/2}`.
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    Chebyshev polynomials of the second kind of order :math:`n` can
+    be obtained as the determinant of specific :math:`n \times n`
+    matrices. As an example we can check how the points obtained from
+    the determinant of the following :math:`3 \times 3` matrix
+    lay exactly on :math:`U_3`:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.linalg import det
+    >>> from scipy.special import chebyu
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 2.0)
+    >>> ax.set_title(r'Chebyshev polynomial $U_3$')
+    >>> ax.plot(x, chebyu(3)(x), label=rf'$U_3$')
+    >>> for p in np.arange(-1.0, 1.0, 0.1):
+    ...     ax.plot(p,
+    ...             det(np.array([[2*p, 1, 0], [1, 2*p, 1], [0, 1, 2*p]])),
+    ...             'rx')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    They satisfy the recurrence relation:
+
+    .. math::
+        U_{2n-1}(x) = 2 T_n(x)U_{n-1}(x)
+
+    where the :math:`T_n` are the Chebyshev polynomial of the first kind.
+    Let's verify it for :math:`n = 2`:
+
+    >>> from scipy.special import chebyt
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> np.allclose(chebyu(3)(x), 2 * chebyt(2)(x) * chebyu(1)(x))
+    True
+
+    We can plot the Chebyshev polynomials :math:`U_n` for some values
+    of :math:`n`:
+
+    >>> x = np.arange(-1.0, 1.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-1.5, 1.5)
+    >>> ax.set_title(r'Chebyshev polynomials $U_n$')
+    >>> for n in np.arange(1,5):
+    ...     ax.plot(x, chebyu(n)(x), label=rf'$U_n={n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    base = jacobi(n, 0.5, 0.5, monic=monic)
+    if monic:
+        return base
+    factor = sqrt(pi) / 2.0 * _gam(n + 2) / _gam(n + 1.5)
+    base._scale(factor)
+    return base
+
+# Chebyshev of the first kind        C_n(x)
+
+
+def roots_chebyc(n, mu=False):
+    r"""Gauss-Chebyshev (first kind) quadrature.
+
+    Compute the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the first kind, :math:`C_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-2, 2]`
+    with weight function :math:`w(x) = 1 / \sqrt{1 - (x/2)^2}`. See
+    22.2.6 in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w, m = roots_chebyt(n, True)
+    x *= 2
+    w *= 2
+    m *= 2
+    if mu:
+        return x, w, m
+    else:
+        return x, w
+
+
+def chebyc(n, monic=False):
+    r"""Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
+
+    Defined as :math:`C_n(x) = 2T_n(x/2)`, where :math:`T_n` is the
+    nth Chebychev polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    C : orthopoly1d
+        Chebyshev polynomial of the first kind on :math:`[-2, 2]`.
+
+    See Also
+    --------
+    chebyt : Chebyshev polynomial of the first kind.
+
+    Notes
+    -----
+    The polynomials :math:`C_n(x)` are orthogonal over :math:`[-2, 2]`
+    with weight function :math:`1/\sqrt{1 - (x/2)^2}`.
+
+    References
+    ----------
+    .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions"
+           Section 22. National Bureau of Standards, 1972.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_chebyc(n1)
+    if n == 0:
+        x, w = [], []
+    hn = 4 * pi * ((n == 0) + 1)
+    kn = 1.0
+    p = orthopoly1d(x, w, hn, kn,
+                    wfunc=lambda x: 1.0 / sqrt(1 - x * x / 4.0),
+                    limits=(-2, 2), monic=monic)
+    if not monic:
+        p._scale(2.0 / p(2))
+        p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebyc(n, x)
+    return p
+
+# Chebyshev of the second kind       S_n(x)
+
+
+def roots_chebys(n, mu=False):
+    r"""Gauss-Chebyshev (second kind) quadrature.
+
+    Compute the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    Chebyshev polynomial of the second kind, :math:`S_n(x)`. These
+    sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[-2, 2]`
+    with weight function :math:`w(x) = \sqrt{1 - (x/2)^2}`. See 22.2.7
+    in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w, m = roots_chebyu(n, True)
+    x *= 2
+    w *= 2
+    m *= 2
+    if mu:
+        return x, w, m
+    else:
+        return x, w
+
+
+def chebys(n, monic=False):
+    r"""Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
+
+    Defined as :math:`S_n(x) = U_n(x/2)` where :math:`U_n` is the
+    nth Chebychev polynomial of the second kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    S : orthopoly1d
+        Chebyshev polynomial of the second kind on :math:`[-2, 2]`.
+
+    See Also
+    --------
+    chebyu : Chebyshev polynomial of the second kind
+
+    Notes
+    -----
+    The polynomials :math:`S_n(x)` are orthogonal over :math:`[-2, 2]`
+    with weight function :math:`\sqrt{1 - (x/2)}^2`.
+
+    References
+    ----------
+    .. [1] Abramowitz and Stegun, "Handbook of Mathematical Functions"
+           Section 22. National Bureau of Standards, 1972.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_chebys(n1)
+    if n == 0:
+        x, w = [], []
+    hn = pi
+    kn = 1.0
+    p = orthopoly1d(x, w, hn, kn,
+                    wfunc=lambda x: sqrt(1 - x * x / 4.0),
+                    limits=(-2, 2), monic=monic)
+    if not monic:
+        factor = (n + 1.0) / p(2)
+        p._scale(factor)
+        p.__dict__['_eval_func'] = lambda x: _ufuncs.eval_chebys(n, x)
+    return p
+
+# Shifted Chebyshev of the first kind     T^*_n(x)
+
+
+def roots_sh_chebyt(n, mu=False):
+    r"""Gauss-Chebyshev (first kind, shifted) quadrature.
+
+    Compute the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    shifted Chebyshev polynomial of the first kind, :math:`T_n(x)`.
+    These sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[0, 1]`
+    with weight function :math:`w(x) = 1/\sqrt{x - x^2}`. See 22.2.8
+    in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    xw = roots_chebyt(n, mu)
+    return ((xw[0] + 1) / 2,) + xw[1:]
+
+
+def sh_chebyt(n, monic=False):
+    r"""Shifted Chebyshev polynomial of the first kind.
+
+    Defined as :math:`T^*_n(x) = T_n(2x - 1)` for :math:`T_n` the nth
+    Chebyshev polynomial of the first kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    T : orthopoly1d
+        Shifted Chebyshev polynomial of the first kind.
+
+    Notes
+    -----
+    The polynomials :math:`T^*_n` are orthogonal over :math:`[0, 1]`
+    with weight function :math:`(x - x^2)^{-1/2}`.
+
+    """
+    base = sh_jacobi(n, 0.0, 0.5, monic=monic)
+    if monic:
+        return base
+    if n > 0:
+        factor = 4**n / 2.0
+    else:
+        factor = 1.0
+    base._scale(factor)
+    return base
+
+
+# Shifted Chebyshev of the second kind    U^*_n(x)
+def roots_sh_chebyu(n, mu=False):
+    r"""Gauss-Chebyshev (second kind, shifted) quadrature.
+
+    Computes the sample points and weights for Gauss-Chebyshev
+    quadrature. The sample points are the roots of the nth degree
+    shifted Chebyshev polynomial of the second kind, :math:`U_n(x)`.
+    These sample points and weights correctly integrate polynomials of
+    degree :math:`2n - 1` or less over the interval :math:`[0, 1]`
+    with weight function :math:`w(x) = \sqrt{x - x^2}`. See 22.2.9 in
+    [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w, m = roots_chebyu(n, True)
+    x = (x + 1) / 2
+    m_us = _ufuncs.beta(1.5, 1.5)
+    w *= m_us / m
+    if mu:
+        return x, w, m_us
+    else:
+        return x, w
+
+
+def sh_chebyu(n, monic=False):
+    r"""Shifted Chebyshev polynomial of the second kind.
+
+    Defined as :math:`U^*_n(x) = U_n(2x - 1)` for :math:`U_n` the nth
+    Chebyshev polynomial of the second kind.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    U : orthopoly1d
+        Shifted Chebyshev polynomial of the second kind.
+
+    Notes
+    -----
+    The polynomials :math:`U^*_n` are orthogonal over :math:`[0, 1]`
+    with weight function :math:`(x - x^2)^{1/2}`.
+
+    """
+    base = sh_jacobi(n, 2.0, 1.5, monic=monic)
+    if monic:
+        return base
+    factor = 4**n
+    base._scale(factor)
+    return base
+
+# Legendre
+
+
+def roots_legendre(n, mu=False):
+    r"""Gauss-Legendre quadrature.
+
+    Compute the sample points and weights for Gauss-Legendre
+    quadrature [GL]_. The sample points are the roots of the nth degree
+    Legendre polynomial :math:`P_n(x)`. These sample points and
+    weights correctly integrate polynomials of degree :math:`2n - 1`
+    or less over the interval :math:`[-1, 1]` with weight function
+    :math:`w(x) = 1`. See 2.2.10 in [AS]_ for more details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+    numpy.polynomial.legendre.leggauss
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+    .. [GL] Gauss-Legendre quadrature, Wikipedia,
+        https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_quadrature
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import roots_legendre, eval_legendre
+    >>> roots, weights = roots_legendre(9)
+
+    ``roots`` holds the roots, and ``weights`` holds the weights for
+    Gauss-Legendre quadrature.
+
+    >>> roots
+    array([-0.96816024, -0.83603111, -0.61337143, -0.32425342,  0.        ,
+            0.32425342,  0.61337143,  0.83603111,  0.96816024])
+    >>> weights
+    array([0.08127439, 0.18064816, 0.2606107 , 0.31234708, 0.33023936,
+           0.31234708, 0.2606107 , 0.18064816, 0.08127439])
+
+    Verify that we have the roots by evaluating the degree 9 Legendre
+    polynomial at ``roots``.  All the values are approximately zero:
+
+    >>> eval_legendre(9, roots)
+    array([-8.88178420e-16, -2.22044605e-16,  1.11022302e-16,  1.11022302e-16,
+            0.00000000e+00, -5.55111512e-17, -1.94289029e-16,  1.38777878e-16,
+           -8.32667268e-17])
+
+    Here we'll show how the above values can be used to estimate the
+    integral from 1 to 2 of f(t) = t + 1/t with Gauss-Legendre
+    quadrature [GL]_.  First define the function and the integration
+    limits.
+
+    >>> def f(t):
+    ...    return t + 1/t
+    ...
+    >>> a = 1
+    >>> b = 2
+
+    We'll use ``integral(f(t), t=a, t=b)`` to denote the definite integral
+    of f from t=a to t=b.  The sample points in ``roots`` are from the
+    interval [-1, 1], so we'll rewrite the integral with the simple change
+    of variable::
+
+        x = 2/(b - a) * t - (a + b)/(b - a)
+
+    with inverse::
+
+        t = (b - a)/2 * x + (a + b)/2
+
+    Then::
+
+        integral(f(t), a, b) =
+            (b - a)/2 * integral(f((b-a)/2*x + (a+b)/2), x=-1, x=1)
+
+    We can approximate the latter integral with the values returned
+    by `roots_legendre`.
+
+    Map the roots computed above from [-1, 1] to [a, b].
+
+    >>> t = (b - a)/2 * roots + (a + b)/2
+
+    Approximate the integral as the weighted sum of the function values.
+
+    >>> (b - a)/2 * f(t).dot(weights)
+    2.1931471805599276
+
+    Compare that to the exact result, which is 3/2 + log(2):
+
+    >>> 1.5 + np.log(2)
+    2.1931471805599454
+
+    """
+    m = int(n)
+    if n < 1 or n != m:
+        raise ValueError("n must be a positive integer.")
+
+    mu0 = 2.0
+    def an_func(k):
+        return 0.0 * k
+    def bn_func(k):
+        return k * np.sqrt(1.0 / (4 * k * k - 1))
+    f = _ufuncs.eval_legendre
+    def df(n, x):
+        return (-n * x * _ufuncs.eval_legendre(n, x)
+                + n * _ufuncs.eval_legendre(n - 1, x)) / (1 - x ** 2)
+    return _gen_roots_and_weights(m, mu0, an_func, bn_func, f, df, True, mu)
+
+
+def legendre(n, monic=False):
+    r"""Legendre polynomial.
+
+    Defined to be the solution of
+
+    .. math::
+        \frac{d}{dx}\left[(1 - x^2)\frac{d}{dx}P_n(x)\right]
+          + n(n + 1)P_n(x) = 0;
+
+    :math:`P_n(x)` is a polynomial of degree :math:`n`.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    P : orthopoly1d
+        Legendre polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`P_n` are orthogonal over :math:`[-1, 1]`
+    with weight function 1.
+
+    Examples
+    --------
+    Generate the 3rd-order Legendre polynomial 1/2*(5x^3 + 0x^2 - 3x + 0):
+
+    >>> from scipy.special import legendre
+    >>> legendre(3)
+    poly1d([ 2.5,  0. , -1.5,  0. ])
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    if n == 0:
+        n1 = n + 1
+    else:
+        n1 = n
+    x, w = roots_legendre(n1)
+    if n == 0:
+        x, w = [], []
+    hn = 2.0 / (2 * n + 1)
+    kn = _gam(2 * n + 1) / _gam(n + 1)**2 / 2.0**n
+    p = orthopoly1d(x, w, hn, kn, wfunc=lambda x: 1.0, limits=(-1, 1),
+                    monic=monic,
+                    eval_func=lambda x: _ufuncs.eval_legendre(n, x))
+    return p
+
+# Shifted Legendre              P^*_n(x)
+
+
+def roots_sh_legendre(n, mu=False):
+    r"""Gauss-Legendre (shifted) quadrature.
+
+    Compute the sample points and weights for Gauss-Legendre
+    quadrature. The sample points are the roots of the nth degree
+    shifted Legendre polynomial :math:`P^*_n(x)`. These sample points
+    and weights correctly integrate polynomials of degree :math:`2n -
+    1` or less over the interval :math:`[0, 1]` with weight function
+    :math:`w(x) = 1.0`. See 2.2.11 in [AS]_ for details.
+
+    Parameters
+    ----------
+    n : int
+        quadrature order
+    mu : bool, optional
+        If True, return the sum of the weights, optional.
+
+    Returns
+    -------
+    x : ndarray
+        Sample points
+    w : ndarray
+        Weights
+    mu : float
+        Sum of the weights
+
+    See Also
+    --------
+    scipy.integrate.fixed_quad
+
+    References
+    ----------
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    """
+    x, w = roots_legendre(n)
+    x = (x + 1) / 2
+    w /= 2
+    if mu:
+        return x, w, 1.0
+    else:
+        return x, w
+
+
+def sh_legendre(n, monic=False):
+    r"""Shifted Legendre polynomial.
+
+    Defined as :math:`P^*_n(x) = P_n(2x - 1)` for :math:`P_n` the nth
+    Legendre polynomial.
+
+    Parameters
+    ----------
+    n : int
+        Degree of the polynomial.
+    monic : bool, optional
+        If `True`, scale the leading coefficient to be 1. Default is
+        `False`.
+
+    Returns
+    -------
+    P : orthopoly1d
+        Shifted Legendre polynomial.
+
+    Notes
+    -----
+    The polynomials :math:`P^*_n` are orthogonal over :math:`[0, 1]`
+    with weight function 1.
+
+    """
+    if n < 0:
+        raise ValueError("n must be nonnegative.")
+
+    def wfunc(x):
+        return 0.0 * x + 1.0
+    if n == 0:
+        return orthopoly1d([], [], 1.0, 1.0, wfunc, (0, 1), monic,
+                           lambda x: _ufuncs.eval_sh_legendre(n, x))
+    x, w = roots_sh_legendre(n)
+    hn = 1.0 / (2 * n + 1.0)
+    kn = _gam(2 * n + 1) / _gam(n + 1)**2
+    p = orthopoly1d(x, w, hn, kn, wfunc, limits=(0, 1), monic=monic,
+                    eval_func=lambda x: _ufuncs.eval_sh_legendre(n, x))
+    return p
+
+
+# Make the old root function names an alias for the new ones
+_modattrs = globals()
+for newfun, oldfun in _rootfuns_map.items():
+    _modattrs[oldfun] = _modattrs[newfun]
+    __all__.append(oldfun)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..e0ae3ce3be90187cd957fe16cc6d145a7093da5a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_orthogonal.pyi
@@ -0,0 +1,330 @@
+from typing import (
+    Any,
+    Callable,
+    Literal,
+    Optional,
+    overload,
+)
+
+import numpy as np
+
+_IntegerType = int | np.integer
+_FloatingType = float | np.floating
+_PointsAndWeights = tuple[np.ndarray, np.ndarray]
+_PointsAndWeightsAndMu = tuple[np.ndarray, np.ndarray, float]
+
+_ArrayLike0D = bool | int | float | complex | str | bytes | np.generic
+
+__all__ = [
+    'legendre',
+    'chebyt',
+    'chebyu',
+    'chebyc',
+    'chebys',
+    'jacobi',
+    'laguerre',
+    'genlaguerre',
+    'hermite',
+    'hermitenorm',
+    'gegenbauer',
+    'sh_legendre',
+    'sh_chebyt',
+    'sh_chebyu',
+    'sh_jacobi',
+    'roots_legendre',
+    'roots_chebyt',
+    'roots_chebyu',
+    'roots_chebyc',
+    'roots_chebys',
+    'roots_jacobi',
+    'roots_laguerre',
+    'roots_genlaguerre',
+    'roots_hermite',
+    'roots_hermitenorm',
+    'roots_gegenbauer',
+    'roots_sh_legendre',
+    'roots_sh_chebyt',
+    'roots_sh_chebyu',
+    'roots_sh_jacobi',
+]
+
+@overload
+def roots_jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_jacobi(
+        n: _IntegerType,
+        p1: _FloatingType,
+        q1: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_jacobi(
+        n: _IntegerType,
+        p1: _FloatingType,
+        q1: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_jacobi(
+        n: _IntegerType,
+        p1: _FloatingType,
+        q1: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_laguerre(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_laguerre(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_laguerre(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_hermite(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_hermite(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_hermite(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_hermitenorm(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_hermitenorm(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_hermitenorm(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+) -> _PointsAndWeights: ...
+@overload
+def roots_gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebyt(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebyt(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebyt(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebyu(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebyu(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebyu(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebyc(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebyc(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebyc(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_chebys(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_chebys(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_chebys(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_chebyt(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyt(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyt(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_chebyu(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyu(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_chebyu(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_legendre(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_legendre(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_legendre(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+@overload
+def roots_sh_legendre(n: _IntegerType) -> _PointsAndWeights: ...
+@overload
+def roots_sh_legendre(
+        n: _IntegerType,
+        mu: Literal[False],
+) -> _PointsAndWeights: ...
+@overload
+def roots_sh_legendre(
+        n: _IntegerType,
+        mu: Literal[True],
+) -> _PointsAndWeightsAndMu: ...
+
+class orthopoly1d(np.poly1d):
+    def __init__(
+            self,
+            roots: np.typing.ArrayLike,
+            weights: np.typing.ArrayLike | None,
+            hn: float = ...,
+            kn: float = ...,
+            wfunc = Optional[Callable[[float], float]],  # noqa: UP007
+            limits = tuple[float, float] | None,
+            monic: bool = ...,
+            eval_func: np.ufunc = ...,
+    ) -> None: ...
+    @property
+    def limits(self) -> tuple[float, float]: ...
+    def weight_func(self, x: float) -> float: ...
+    @overload
+    def __call__(self, x: _ArrayLike0D) -> Any: ...
+    @overload
+    def __call__(self, x: np.poly1d) -> np.poly1d: ...  # type: ignore[overload-overlap]
+    @overload
+    def __call__(self, x: np.typing.ArrayLike) -> np.ndarray: ...
+
+def legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebyc(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def chebys(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def jacobi(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        beta: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+def laguerre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def genlaguerre(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+def hermite(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def hermitenorm(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def gegenbauer(
+        n: _IntegerType,
+        alpha: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+def sh_legendre(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def sh_chebyt(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def sh_chebyu(n: _IntegerType, monic: bool = ...) -> orthopoly1d: ...
+def sh_jacobi(
+        n: _IntegerType,
+        p: _FloatingType,
+        q: _FloatingType,
+        monic: bool = ...,
+) -> orthopoly1d: ...
+
+# These functions are not public, but still need stubs because they
+# get checked in the tests.
+def _roots_hermite_asy(n: _IntegerType) -> _PointsAndWeights: ...
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py
new file mode 100644
index 0000000000000000000000000000000000000000..662c12bc74b31478c87471fbd1cce8bea285e765
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/cosine_cdf.py
@@ -0,0 +1,17 @@
+import mpmath
+
+
+def f(x):
+    return (mpmath.pi + x + mpmath.sin(x)) / (2*mpmath.pi)
+
+
+# Note: 40 digits might be overkill; a few more digits than the default
+# might be sufficient.
+mpmath.mp.dps = 40
+ts = mpmath.taylor(f, -mpmath.pi, 20)
+p, q = mpmath.pade(ts, 9, 10)
+
+p = [float(c) for c in p]
+q = [float(c) for c in q]
+print('p =', p)
+print('q =', q)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py
new file mode 100644
index 0000000000000000000000000000000000000000..3491b8acd588a2cacfc48f0a3a60c6ae88c3e8c5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/expn_asy.py
@@ -0,0 +1,54 @@
+"""Precompute the polynomials for the asymptotic expansion of the
+generalized exponential integral.
+
+Sources
+-------
+[1] NIST, Digital Library of Mathematical Functions,
+    https://dlmf.nist.gov/8.20#ii
+
+"""
+import os
+
+try:
+    import sympy
+    from sympy import Poly
+    x = sympy.symbols('x')
+except ImportError:
+    pass
+
+
+def generate_A(K):
+    A = [Poly(1, x)]
+    for k in range(K):
+        A.append(Poly(1 - 2*k*x, x)*A[k] + Poly(x*(x + 1))*A[k].diff())
+    return A
+
+
+WARNING = """\
+/* This file was automatically generated by _precompute/expn_asy.py.
+ * Do not edit it manually!
+ */
+"""
+
+
+def main():
+    print(__doc__)
+    fn = os.path.join('..', 'cephes', 'expn.h')
+
+    K = 12
+    A = generate_A(K)
+    with open(fn + '.new', 'w') as f:
+        f.write(WARNING)
+        f.write(f"#define nA {len(A)}\n")
+        for k, Ak in enumerate(A):
+            ', '.join([str(x.evalf(18)) for x in Ak.coeffs()])
+            f.write(f"static const double A{k}[] = {{tmp}};\n")
+        ", ".join([f"A{k}" for k in range(K + 1)])
+        f.write("static const double *A[] = {{tmp}};\n")
+        ", ".join([str(Ak.degree()) for Ak in A])
+        f.write("static const int Adegs[] = {{tmp}};\n")
+    os.rename(fn + '.new', fn)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py
new file mode 100644
index 0000000000000000000000000000000000000000..98035457c78706ae01c02273ae1ab458b4ca140d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_asy.py
@@ -0,0 +1,116 @@
+"""
+Precompute coefficients of Temme's asymptotic expansion for gammainc.
+
+This takes about 8 hours to run on a 2.3 GHz Macbook Pro with 4GB ram.
+
+Sources:
+[1] NIST, "Digital Library of Mathematical Functions",
+    https://dlmf.nist.gov/
+
+"""
+import os
+from scipy.special._precompute.utils import lagrange_inversion
+
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+
+def compute_a(n):
+    """a_k from DLMF 5.11.6"""
+    a = [mp.sqrt(2)/2]
+    for k in range(1, n):
+        ak = a[-1]/k
+        for j in range(1, len(a)):
+            ak -= a[j]*a[-j]/(j + 1)
+        ak /= a[0]*(1 + mp.mpf(1)/(k + 1))
+        a.append(ak)
+    return a
+
+
+def compute_g(n):
+    """g_k from DLMF 5.11.3/5.11.5"""
+    a = compute_a(2*n)
+    g = [mp.sqrt(2)*mp.rf(0.5, k)*a[2*k] for k in range(n)]
+    return g
+
+
+def eta(lam):
+    """Function from DLMF 8.12.1 shifted to be centered at 0."""
+    if lam > 0:
+        return mp.sqrt(2*(lam - mp.log(lam + 1)))
+    elif lam < 0:
+        return -mp.sqrt(2*(lam - mp.log(lam + 1)))
+    else:
+        return 0
+
+
+def compute_alpha(n):
+    """alpha_n from DLMF 8.12.13"""
+    coeffs = mp.taylor(eta, 0, n - 1)
+    return lagrange_inversion(coeffs)
+
+
+def compute_d(K, N):
+    """d_{k, n} from DLMF 8.12.12"""
+    M = N + 2*K
+    d0 = [-mp.mpf(1)/3]
+    alpha = compute_alpha(M + 2)
+    for n in range(1, M):
+        d0.append((n + 2)*alpha[n+2])
+    d = [d0]
+    g = compute_g(K)
+    for k in range(1, K):
+        dk = []
+        for n in range(M - 2*k):
+            dk.append((-1)**k*g[k]*d[0][n] + (n + 2)*d[k-1][n+2])
+        d.append(dk)
+    for k in range(K):
+        d[k] = d[k][:N]
+    return d
+
+
+header = \
+r"""/* This file was automatically generated by _precomp/gammainc.py.
+ * Do not edit it manually!
+ */
+
+#ifndef IGAM_H
+#define IGAM_H
+
+#define K {}
+#define N {}
+
+static const double d[K][N] =
+{{"""
+
+footer = \
+r"""
+#endif
+"""
+
+
+def main():
+    print(__doc__)
+    K = 25
+    N = 25
+    with mp.workdps(50):
+        d = compute_d(K, N)
+    fn = os.path.join(os.path.dirname(__file__), '..', 'cephes', 'igam.h')
+    with open(fn + '.new', 'w') as f:
+        f.write(header.format(K, N))
+        for k, row in enumerate(d):
+            row = [mp.nstr(x, 17, min_fixed=0, max_fixed=0) for x in row]
+            f.write('{')
+            f.write(", ".join(row))
+            if k < K - 1:
+                f.write('},\n')
+            else:
+                f.write('}};\n')
+        f.write(footer)
+    os.rename(fn + '.new', fn)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebbe39f6159fb80c424dbb38eedeba46bd8cccf2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/gammainc_data.py
@@ -0,0 +1,124 @@
+"""Compute gammainc and gammaincc for large arguments and parameters
+and save the values to data files for use in tests. We can't just
+compare to mpmath's gammainc in test_mpmath.TestSystematic because it
+would take too long.
+
+Note that mpmath's gammainc is computed using hypercomb, but since it
+doesn't allow the user to increase the maximum number of terms used in
+the series it doesn't converge for many arguments. To get around this
+we copy the mpmath implementation but use more terms.
+
+This takes about 17 minutes to run on a 2.3 GHz Macbook Pro with 4GB
+ram.
+
+Sources:
+[1] Fredrik Johansson and others. mpmath: a Python library for
+    arbitrary-precision floating-point arithmetic (version 0.19),
+    December 2013. http://mpmath.org/.
+
+"""
+import os
+from time import time
+import numpy as np
+from numpy import pi
+
+from scipy.special._mptestutils import mpf2float
+
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+
+def gammainc(a, x, dps=50, maxterms=10**8):
+    """Compute gammainc exactly like mpmath does but allow for more
+    summands in hypercomb. See
+
+    mpmath/functions/expintegrals.py#L134
+
+    in the mpmath GitHub repository.
+
+    """
+    with mp.workdps(dps):
+        z, a, b = mp.mpf(a), mp.mpf(x), mp.mpf(x)
+        G = [z]
+        negb = mp.fneg(b, exact=True)
+
+        def h(z):
+            T1 = [mp.exp(negb), b, z], [1, z, -1], [], G, [1], [1+z], b
+            return (T1,)
+
+        res = mp.hypercomb(h, [z], maxterms=maxterms)
+        return mpf2float(res)
+
+
+def gammaincc(a, x, dps=50, maxterms=10**8):
+    """Compute gammaincc exactly like mpmath does but allow for more
+    terms in hypercomb. See
+
+    mpmath/functions/expintegrals.py#L187
+
+    in the mpmath GitHub repository.
+
+    """
+    with mp.workdps(dps):
+        z, a = a, x
+
+        if mp.isint(z):
+            try:
+                # mpmath has a fast integer path
+                return mpf2float(mp.gammainc(z, a=a, regularized=True))
+            except mp.libmp.NoConvergence:
+                pass
+        nega = mp.fneg(a, exact=True)
+        G = [z]
+        # Use 2F0 series when possible; fall back to lower gamma representation
+        try:
+            def h(z):
+                r = z-1
+                return [([mp.exp(nega), a], [1, r], [], G, [1, -r], [], 1/nega)]
+            return mpf2float(mp.hypercomb(h, [z], force_series=True))
+        except mp.libmp.NoConvergence:
+            def h(z):
+                T1 = [], [1, z-1], [z], G, [], [], 0
+                T2 = [-mp.exp(nega), a, z], [1, z, -1], [], G, [1], [1+z], a
+                return T1, T2
+            return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms))
+
+
+def main():
+    t0 = time()
+    # It would be nice to have data for larger values, but either this
+    # requires prohibitively large precision (dps > 800) or mpmath has
+    # a bug. For example, gammainc(1e20, 1e20, dps=800) returns a
+    # value around 0.03, while the true value should be close to 0.5
+    # (DLMF 8.12.15).
+    print(__doc__)
+    pwd = os.path.dirname(__file__)
+    r = np.logspace(4, 14, 30)
+    ltheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(0.6)), 30)
+    utheta = np.logspace(np.log10(pi/4), np.log10(np.arctan(1.4)), 30)
+
+    regimes = [(gammainc, ltheta), (gammaincc, utheta)]
+    for func, theta in regimes:
+        rg, thetag = np.meshgrid(r, theta)
+        a, x = rg*np.cos(thetag), rg*np.sin(thetag)
+        a, x = a.flatten(), x.flatten()
+        dataset = []
+        for i, (a0, x0) in enumerate(zip(a, x)):
+            if func == gammaincc:
+                # Exploit the fast integer path in gammaincc whenever
+                # possible so that the computation doesn't take too
+                # long
+                a0, x0 = np.floor(a0), np.floor(x0)
+            dataset.append((a0, x0, func(a0, x0)))
+        dataset = np.array(dataset)
+        filename = os.path.join(pwd, '..', 'tests', 'data', 'local',
+                                f'{func.__name__}.txt')
+        np.savetxt(filename, dataset)
+
+    print(f"{(time() - t0)/60} minutes elapsed")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4adf14f49184bf75048a28a823909d24e778e04
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/hyp2f1_data.py
@@ -0,0 +1,484 @@
+"""This script evaluates scipy's implementation of hyp2f1 against mpmath's.
+
+Author: Albert Steppi
+
+This script is long running and generates a large output file. With default
+arguments, the generated file is roughly 700MB in size and it takes around
+40 minutes using an Intel(R) Core(TM) i5-8250U CPU with n_jobs set to 8
+(full utilization). There are optional arguments which can be used to restrict
+(or enlarge) the computations performed. These are described below.
+The output of this script can be analyzed to identify suitable test cases and
+to find parameter and argument regions where hyp2f1 needs to be improved.
+
+The script has one mandatory positional argument for specifying the path to
+the location where the output file is to be placed, and 4 optional arguments
+--n_jobs, --grid_size, --regions, and --parameter_groups. --n_jobs specifies
+the number of processes to use if running in parallel. The default value is 1.
+The other optional arguments are explained below.
+
+Produces a tab separated values file with 11 columns. The first four columns
+contain the parameters a, b, c and the argument z. The next two contain |z| and
+a region code for which region of the complex plane belongs to. The regions are
+
+    0) z == 1
+    1) |z| < 0.9 and real(z) >= 0
+    2) |z| <= 1 and real(z) < 0
+    3) 0.9 <= |z| <= 1 and |1 - z| < 0.9:
+    4) 0.9 <= |z| <= 1 and |1 - z| >= 0.9 and real(z) >= 0:
+    5) 1 < |z| < 1.1 and |1 - z| >= 0.9 and real(z) >= 0
+    6) |z| > 1 and not in 5)
+
+The --regions optional argument allows the user to specify a list of regions
+to which computation will be restricted.
+
+Parameters a, b, c are taken from a 10 * 10 * 10 grid with values at
+
+    -16, -8, -4, -2, -1, 1, 2, 4, 8, 16
+
+with random perturbations applied.
+
+There are 9 parameter groups handling the following cases.
+
+    1) A, B, C, B - A, C - A, C - B, C - A - B all non-integral.
+    2) B - A integral
+    3) C - A integral
+    4) C - B integral
+    5) C - A - B integral
+    6) A integral
+    7) B integral
+    8) C integral
+    9) Wider range with c - a - b > 0.
+
+The seventh column of the output file is an integer between 1 and 8 specifying
+the parameter group as above.
+
+The --parameter_groups optional argument allows the user to specify a list of
+parameter groups to which computation will be restricted.
+
+The argument z is taken from a grid in the box
+    -box_size <= real(z) <= box_size, -box_size <= imag(z) <= box_size.
+with grid size specified using the optional command line argument --grid_size,
+and box_size specified with the command line argument --box_size.
+The default value of grid_size is 20 and the default value of box_size is 2.0,
+yielding a 20 * 20 grid in the box with corners -2-2j, -2+2j, 2-2j, 2+2j.
+
+The final four columns have the expected value of hyp2f1 for the given
+parameters and argument as calculated with mpmath, the observed value
+calculated with scipy's hyp2f1, the relative error, and the absolute error.
+
+As special cases of hyp2f1 are moved from the original Fortran implementation
+into Cython, this script can be used to ensure that no regressions occur and
+to point out where improvements are needed.
+"""
+
+
+import os
+import csv
+import argparse
+import numpy as np
+from itertools import product
+from multiprocessing import Pool
+
+
+from scipy.special import hyp2f1
+from scipy.special.tests.test_hyp2f1 import mp_hyp2f1
+
+
+def get_region(z):
+    """Assign numbers for regions where hyp2f1 must be handled differently."""
+    if z == 1 + 0j:
+        return 0
+    elif abs(z) < 0.9 and z.real >= 0:
+        return 1
+    elif abs(z) <= 1 and z.real < 0:
+        return 2
+    elif 0.9 <= abs(z) <= 1 and abs(1 - z) < 0.9:
+        return 3
+    elif 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0.9:
+        return 4
+    elif 1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0:
+        return 5
+    else:
+        return 6
+
+
+def get_result(a, b, c, z, group):
+    """Get results for given parameter and value combination."""
+    expected, observed = mp_hyp2f1(a, b, c, z), hyp2f1(a, b, c, z)
+    if (
+            np.isnan(observed) and np.isnan(expected) or
+            expected == observed
+    ):
+        relative_error = 0.0
+        absolute_error = 0.0
+    elif np.isnan(observed):
+        # Set error to infinity if result is nan when not expected to be.
+        # Makes results easier to interpret.
+        relative_error = float("inf")
+        absolute_error = float("inf")
+    else:
+        absolute_error = abs(expected - observed)
+        relative_error = absolute_error / abs(expected)
+
+    return (
+        a,
+        b,
+        c,
+        z,
+        abs(z),
+        get_region(z),
+        group,
+        expected,
+        observed,
+        relative_error,
+        absolute_error,
+    )
+
+
+def get_result_no_mp(a, b, c, z, group):
+    """Get results for given parameter and value combination."""
+    expected, observed = complex('nan'), hyp2f1(a, b, c, z)
+    relative_error, absolute_error = float('nan'), float('nan')
+    return (
+        a,
+        b,
+        c,
+        z,
+        abs(z),
+        get_region(z),
+        group,
+        expected,
+        observed,
+        relative_error,
+        absolute_error,
+    )
+
+
+def get_results(params, Z, n_jobs=1, compute_mp=True):
+    """Batch compute results for multiple parameter and argument values.
+
+    Parameters
+    ----------
+    params : iterable
+        iterable of tuples of floats (a, b, c) specifying parameter values
+        a, b, c for hyp2f1
+    Z : iterable of complex
+        Arguments at which to evaluate hyp2f1
+    n_jobs : Optional[int]
+        Number of jobs for parallel execution.
+
+    Returns
+    -------
+    list
+        List of tuples of results values. See return value in source code
+        of `get_result`.
+    """
+    input_ = (
+        (a, b, c, z, group) for (a, b, c, group), z in product(params, Z)
+    )
+
+    with Pool(n_jobs) as pool:
+        rows = pool.starmap(
+            get_result if compute_mp else get_result_no_mp,
+            input_
+        )
+    return rows
+
+
+def _make_hyp2f1_test_case(a, b, c, z, rtol):
+    """Generate string for single test case as used in test_hyp2f1.py."""
+    expected = mp_hyp2f1(a, b, c, z)
+    return (
+        "    pytest.param(\n"
+        "        Hyp2f1TestCase(\n"
+        f"            a={a},\n"
+        f"            b={b},\n"
+        f"            c={c},\n"
+        f"            z={z},\n"
+        f"            expected={expected},\n"
+        f"            rtol={rtol},\n"
+        "        ),\n"
+        "    ),"
+    )
+
+
+def make_hyp2f1_test_cases(rows):
+    """Generate string for a list of test cases for test_hyp2f1.py.
+
+    Parameters
+    ----------
+    rows : list
+        List of lists of the form [a, b, c, z, rtol] where a, b, c, z are
+        parameters and the argument for hyp2f1 and rtol is an expected
+        relative error for the associated test case.
+
+    Returns
+    -------
+    str
+        String for a list of test cases. The output string can be printed
+        or saved to a file and then copied into an argument for
+        `pytest.mark.parameterize` within `scipy.special.tests.test_hyp2f1.py`.
+    """
+    result = "[\n"
+    result += '\n'.join(
+        _make_hyp2f1_test_case(a, b, c, z, rtol)
+        for a, b, c, z, rtol in rows
+    )
+    result += "\n]"
+    return result
+
+
+def main(
+        outpath,
+        n_jobs=1,
+        box_size=2.0,
+        grid_size=20,
+        regions=None,
+        parameter_groups=None,
+        compute_mp=True,
+):
+    outpath = os.path.realpath(os.path.expanduser(outpath))
+
+    random_state = np.random.RandomState(1234)
+    # Parameters a, b, c selected near these values.
+    root_params = np.array(
+        [-16, -8, -4, -2, -1, 1, 2, 4, 8, 16]
+    )
+    # Perturbations to apply to root values.
+    perturbations = 0.1 * random_state.random_sample(
+        size=(3, len(root_params))
+    )
+
+    params = []
+    # Parameter group 1
+    # -----------------
+    # No integer differences. This has been confirmed for the above seed.
+    A = root_params + perturbations[0, :]
+    B = root_params + perturbations[1, :]
+    C = root_params + perturbations[2, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 1) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 2
+    # -----------------
+    # B - A an integer
+    A = root_params + 0.5
+    B = root_params + 0.5
+    C = root_params + perturbations[1, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 2) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 3
+    # -----------------
+    # C - A an integer
+    A = root_params + 0.5
+    B = root_params + perturbations[1, :]
+    C = root_params + 0.5
+    params.extend(
+        sorted(
+            ((a, b, c, 3) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 4
+    # -----------------
+    # C - B an integer
+    A = root_params + perturbations[0, :]
+    B = root_params + 0.5
+    C = root_params + 0.5
+    params.extend(
+        sorted(
+            ((a, b, c, 4) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 5
+    # -----------------
+    # C - A - B an integer
+    A = root_params + 0.25
+    B = root_params + 0.25
+    C = root_params + 0.5
+    params.extend(
+        sorted(
+            ((a, b, c, 5) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 6
+    # -----------------
+    # A an integer
+    A = root_params
+    B = root_params + perturbations[0, :]
+    C = root_params + perturbations[1, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 6) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 7
+    # -----------------
+    # B an integer
+    A = root_params + perturbations[0, :]
+    B = root_params
+    C = root_params + perturbations[1, :]
+    params.extend(
+        sorted(
+            ((a, b, c, 7) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 8
+    # -----------------
+    # C an integer
+    A = root_params + perturbations[0, :]
+    B = root_params + perturbations[1, :]
+    C = root_params
+    params.extend(
+        sorted(
+            ((a, b, c, 8) for a, b, c in product(A, B, C)),
+            key=lambda x: max(abs(x[0]), abs(x[1])),
+        )
+    )
+
+    # Parameter group 9
+    # -----------------
+    # Wide range of magnitudes, c - a - b > 0.
+    phi = (1 + np.sqrt(5))/2
+    P = phi**np.arange(16)
+    P = np.hstack([-P, P])
+    group_9_params = sorted(
+        (
+            (a, b, c, 9) for a, b, c in product(P, P, P) if c - a - b > 0
+        ),
+        key=lambda x: max(abs(x[0]), abs(x[1])),
+    )
+
+    if parameter_groups is not None:
+        # Group 9 params only used if specified in arguments.
+        params.extend(group_9_params)
+        params = [
+            (a, b, c, group) for a, b, c, group in params
+            if group in parameter_groups
+        ]
+
+    # grid_size * grid_size grid in box with corners
+    # -2 - 2j, -2 + 2j, 2 - 2j, 2 + 2j
+    X, Y = np.meshgrid(
+        np.linspace(-box_size, box_size, grid_size),
+        np.linspace(-box_size, box_size, grid_size)
+    )
+    Z = X + Y * 1j
+    Z = Z.flatten().tolist()
+    # Add z = 1 + 0j (region 0).
+    Z.append(1 + 0j)
+    if regions is not None:
+        Z = [z for z in Z if get_region(z) in regions]
+
+    # Evaluate scipy and mpmath's hyp2f1 for all parameter combinations
+    # above against all arguments in the grid Z
+    rows = get_results(params, Z, n_jobs=n_jobs, compute_mp=compute_mp)
+
+    with open(outpath, "w", newline="") as f:
+        writer = csv.writer(f, delimiter="\t")
+        writer.writerow(
+            [
+                "a",
+                "b",
+                "c",
+                "z",
+                "|z|",
+                "region",
+                "parameter_group",
+                "expected",  # mpmath's hyp2f1
+                "observed",  # scipy's hyp2f1
+                "relative_error",
+                "absolute_error",
+            ]
+        )
+        for row in rows:
+            writer.writerow(row)
+
+
+if __name__ == "__main__":
+    parser = argparse.ArgumentParser(
+        description="Test scipy's hyp2f1 against mpmath's on a grid in the"
+        " complex plane over a grid of parameter values. Saves output to file"
+        " specified in positional argument \"outpath\"."
+        " Caution: With default arguments, the generated output file is"
+        " roughly 700MB in size. Script may take several hours to finish if"
+        " \"--n_jobs\" is set to 1."
+    )
+    parser.add_argument(
+        "outpath", type=str, help="Path to output tsv file."
+    )
+    parser.add_argument(
+        "--n_jobs",
+        type=int,
+        default=1,
+        help="Number of jobs for multiprocessing.",
+    )
+    parser.add_argument(
+        "--box_size",
+        type=float,
+        default=2.0,
+        help="hyp2f1 is evaluated in box of side_length 2*box_size centered"
+        " at the origin."
+    )
+    parser.add_argument(
+        "--grid_size",
+        type=int,
+        default=20,
+        help="hyp2f1 is evaluated on grid_size * grid_size grid in box of side"
+        " length 2*box_size centered at the origin."
+    )
+    parser.add_argument(
+        "--parameter_groups",
+        type=int,
+        nargs='+',
+        default=None,
+        help="Restrict to supplied parameter groups. See the Docstring for"
+        " this module for more info on parameter groups. Calculate for all"
+        " parameter groups by default."
+    )
+    parser.add_argument(
+        "--regions",
+        type=int,
+        nargs='+',
+        default=None,
+        help="Restrict to argument z only within the supplied regions. See"
+        " the Docstring for this module for more info on regions. Calculate"
+        " for all regions by default."
+    )
+    parser.add_argument(
+        "--no_mp",
+        action='store_true',
+        help="If this flag is set, do not compute results with mpmath. Saves"
+        " time if results have already been computed elsewhere. Fills in"
+        " \"expected\" column with None values."
+    )
+    args = parser.parse_args()
+    compute_mp = not args.no_mp
+    print(args.parameter_groups)
+    main(
+        args.outpath,
+        n_jobs=args.n_jobs,
+        box_size=args.box_size,
+        grid_size=args.grid_size,
+        parameter_groups=args.parameter_groups,
+        regions=args.regions,
+        compute_mp=compute_mp,
+    )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fdbf35b2cf85f1f7a6e73579546ed5cfe508fa6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/lambertw.py
@@ -0,0 +1,68 @@
+"""Compute a Pade approximation for the principal branch of the
+Lambert W function around 0 and compare it to various other
+approximations.
+
+"""
+import numpy as np
+
+try:
+    import mpmath
+    import matplotlib.pyplot as plt
+except ImportError:
+    pass
+
+
+def lambertw_pade():
+    derivs = [mpmath.diff(mpmath.lambertw, 0, n=n) for n in range(6)]
+    p, q = mpmath.pade(derivs, 3, 2)
+    return p, q
+
+
+def main():
+    print(__doc__)
+    with mpmath.workdps(50):
+        p, q = lambertw_pade()
+        p, q = p[::-1], q[::-1]
+        print(f"p = {p}")
+        print(f"q = {q}")
+
+    x, y = np.linspace(-1.5, 1.5, 75), np.linspace(-1.5, 1.5, 75)
+    x, y = np.meshgrid(x, y)
+    z = x + 1j*y
+    lambertw_std = []
+    for z0 in z.flatten():
+        lambertw_std.append(complex(mpmath.lambertw(z0)))
+    lambertw_std = np.array(lambertw_std).reshape(x.shape)
+
+    fig, axes = plt.subplots(nrows=3, ncols=1)
+    # Compare Pade approximation to true result
+    p = np.array([float(p0) for p0 in p])
+    q = np.array([float(q0) for q0 in q])
+    pade_approx = np.polyval(p, z)/np.polyval(q, z)
+    pade_err = abs(pade_approx - lambertw_std)
+    axes[0].pcolormesh(x, y, pade_err)
+    # Compare two terms of asymptotic series to true result
+    asy_approx = np.log(z) - np.log(np.log(z))
+    asy_err = abs(asy_approx - lambertw_std)
+    axes[1].pcolormesh(x, y, asy_err)
+    # Compare two terms of the series around the branch point to the
+    # true result
+    p = np.sqrt(2*(np.exp(1)*z + 1))
+    series_approx = -1 + p - p**2/3
+    series_err = abs(series_approx - lambertw_std)
+    im = axes[2].pcolormesh(x, y, series_err)
+
+    fig.colorbar(im, ax=axes.ravel().tolist())
+    plt.show()
+
+    fig, ax = plt.subplots(nrows=1, ncols=1)
+    pade_better = pade_err < asy_err
+    im = ax.pcolormesh(x, y, pade_better)
+    t = np.linspace(-0.3, 0.3)
+    ax.plot(-2.5*abs(t) - 0.2, t, 'r')
+    fig.colorbar(im, ax=ax)
+    plt.show()
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..74051ac7b46c70dc01919a362d05a8bbbe11333a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/loggamma.py
@@ -0,0 +1,43 @@
+"""Precompute series coefficients for log-Gamma."""
+
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+def stirling_series(N):
+    with mpmath.workdps(100):
+        coeffs = [mpmath.bernoulli(2*n)/(2*n*(2*n - 1))
+                  for n in range(1, N + 1)]
+    return coeffs
+
+
+def taylor_series_at_1(N):
+    coeffs = []
+    with mpmath.workdps(100):
+        coeffs.append(-mpmath.euler)
+        for n in range(2, N + 1):
+            coeffs.append((-1)**n*mpmath.zeta(n)/n)
+    return coeffs
+
+
+def main():
+    print(__doc__)
+    print()
+    stirling_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
+                       for x in stirling_series(8)[::-1]]
+    taylor_coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
+                     for x in taylor_series_at_1(23)[::-1]]
+    print("Stirling series coefficients")
+    print("----------------------------")
+    print("\n".join(stirling_coeffs))
+    print()
+    print("Taylor series coefficients")
+    print("--------------------------")
+    print("\n".join(taylor_coeffs))
+    print()
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbf6009368540dbf603b61f5b72510f0acd1a65b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/struve_convergence.py
@@ -0,0 +1,131 @@
+"""
+Convergence regions of the expansions used in ``struve.c``
+
+Note that for v >> z both functions tend rapidly to 0,
+and for v << -z, they tend to infinity.
+
+The floating-point functions over/underflow in the lower left and right
+corners of the figure.
+
+
+Figure legend
+=============
+
+Red region
+    Power series is close (1e-12) to the mpmath result
+
+Blue region
+    Asymptotic series is close to the mpmath result
+
+Green region
+    Bessel series is close to the mpmath result
+
+Dotted colored lines
+    Boundaries of the regions
+
+Solid colored lines
+    Boundaries estimated by the routine itself. These will be used
+    for determining which of the results to use.
+
+Black dashed line
+    The line z = 0.7*|v| + 12
+
+"""
+import numpy as np
+import matplotlib.pyplot as plt
+
+import mpmath
+
+
+def err_metric(a, b, atol=1e-290):
+    m = abs(a - b) / (atol + abs(b))
+    m[np.isinf(b) & (a == b)] = 0
+    return m
+
+
+def do_plot(is_h=True):
+    from scipy.special._ufuncs import (_struve_power_series,
+                                       _struve_asymp_large_z,
+                                       _struve_bessel_series)
+
+    vs = np.linspace(-1000, 1000, 91)
+    zs = np.sort(np.r_[1e-5, 1.0, np.linspace(0, 700, 91)[1:]])
+
+    rp = _struve_power_series(vs[:,None], zs[None,:], is_h)
+    ra = _struve_asymp_large_z(vs[:,None], zs[None,:], is_h)
+    rb = _struve_bessel_series(vs[:,None], zs[None,:], is_h)
+
+    mpmath.mp.dps = 50
+    if is_h:
+        def sh(v, z):
+            return float(mpmath.struveh(mpmath.mpf(v), mpmath.mpf(z)))
+    else:
+        def sh(v, z):
+            return float(mpmath.struvel(mpmath.mpf(v), mpmath.mpf(z)))
+    ex = np.vectorize(sh, otypes='d')(vs[:,None], zs[None,:])
+
+    err_a = err_metric(ra[0], ex) + 1e-300
+    err_p = err_metric(rp[0], ex) + 1e-300
+    err_b = err_metric(rb[0], ex) + 1e-300
+
+    err_est_a = abs(ra[1]/ra[0])
+    err_est_p = abs(rp[1]/rp[0])
+    err_est_b = abs(rb[1]/rb[0])
+
+    z_cutoff = 0.7*abs(vs) + 12
+
+    levels = [-1000, -12]
+
+    plt.cla()
+
+    plt.hold(1)
+    plt.contourf(vs, zs, np.log10(err_p).T,
+                 levels=levels, colors=['r', 'r'], alpha=0.1)
+    plt.contourf(vs, zs, np.log10(err_a).T,
+                 levels=levels, colors=['b', 'b'], alpha=0.1)
+    plt.contourf(vs, zs, np.log10(err_b).T,
+                 levels=levels, colors=['g', 'g'], alpha=0.1)
+
+    plt.contour(vs, zs, np.log10(err_p).T,
+                levels=levels, colors=['r', 'r'], linestyles=[':', ':'])
+    plt.contour(vs, zs, np.log10(err_a).T,
+                levels=levels, colors=['b', 'b'], linestyles=[':', ':'])
+    plt.contour(vs, zs, np.log10(err_b).T,
+                levels=levels, colors=['g', 'g'], linestyles=[':', ':'])
+
+    lp = plt.contour(vs, zs, np.log10(err_est_p).T,
+                     levels=levels, colors=['r', 'r'], linestyles=['-', '-'])
+    la = plt.contour(vs, zs, np.log10(err_est_a).T,
+                     levels=levels, colors=['b', 'b'], linestyles=['-', '-'])
+    lb = plt.contour(vs, zs, np.log10(err_est_b).T,
+                     levels=levels, colors=['g', 'g'], linestyles=['-', '-'])
+
+    plt.clabel(lp, fmt={-1000: 'P', -12: 'P'})
+    plt.clabel(la, fmt={-1000: 'A', -12: 'A'})
+    plt.clabel(lb, fmt={-1000: 'B', -12: 'B'})
+
+    plt.plot(vs, z_cutoff, 'k--')
+
+    plt.xlim(vs.min(), vs.max())
+    plt.ylim(zs.min(), zs.max())
+
+    plt.xlabel('v')
+    plt.ylabel('z')
+
+
+def main():
+    plt.clf()
+    plt.subplot(121)
+    do_plot(True)
+    plt.title('Struve H')
+
+    plt.subplot(122)
+    do_plot(False)
+    plt.title('Struve L')
+
+    plt.savefig('struve_convergence.png')
+    plt.show()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..55cf4083ed5e5a6628fd3316c02ce1a5ce21a92c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/utils.py
@@ -0,0 +1,38 @@
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+try:
+    from sympy.abc import x
+except ImportError:
+    pass
+
+
+def lagrange_inversion(a):
+    """Given a series
+
+    f(x) = a[1]*x + a[2]*x**2 + ... + a[n-1]*x**(n - 1),
+
+    use the Lagrange inversion formula to compute a series
+
+    g(x) = b[1]*x + b[2]*x**2 + ... + b[n-1]*x**(n - 1)
+
+    so that f(g(x)) = g(f(x)) = x mod x**n. We must have a[0] = 0, so
+    necessarily b[0] = 0 too.
+
+    The algorithm is naive and could be improved, but speed isn't an
+    issue here and it's easy to read.
+
+    """
+    n = len(a)
+    f = sum(a[i]*x**i for i in range(n))
+    h = (x/f).series(x, 0, n).removeO()
+    hpower = [h**0]
+    for k in range(n):
+        hpower.append((hpower[-1]*h).expand())
+    b = [mp.mpf(0)]
+    for k in range(1, n):
+        b.append(hpower[k].coeff(x, k - 1)/k)
+    b = [mp.mpf(x) for x in b]
+    return b
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..51d56b1cd5c47c7ef005d21aad9827a1e85ec0d9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel.py
@@ -0,0 +1,342 @@
+"""Precompute coefficients of several series expansions
+of Wright's generalized Bessel function Phi(a, b, x).
+
+See https://dlmf.nist.gov/10.46.E1 with rho=a, beta=b, z=x.
+"""
+from argparse import ArgumentParser, RawTextHelpFormatter
+import numpy as np
+from scipy.integrate import quad
+from scipy.optimize import minimize_scalar, curve_fit
+from time import time
+
+try:
+    import sympy
+    from sympy import EulerGamma, Rational, S, Sum, \
+        factorial, gamma, gammasimp, pi, polygamma, symbols, zeta
+    from sympy.polys.polyfuncs import horner
+except ImportError:
+    pass
+
+
+def series_small_a():
+    """Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.
+    """
+    order = 5
+    a, b, x, k = symbols("a b x k")
+    A = []  # terms with a
+    X = []  # terms with x
+    B = []  # terms with b (polygammas)
+    # Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i])
+    expression = Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity))
+    expression = gamma(b)/sympy.exp(x) * expression
+
+    # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0)
+    for n in range(0, order+1):
+        term = expression.diff(a, n).subs(a, 0).simplify().doit()
+        # set the whole bracket involving polygammas to 1
+        x_part = (term.subs(polygamma(0, b), 1)
+                  .replace(polygamma, lambda *args: 0))
+        # sign convention: x part always positive
+        x_part *= (-1)**n
+
+        A.append(a**n/factorial(n))
+        X.append(horner(x_part))
+        B.append(horner((term/x_part).simplify()))
+
+    s = "Tylor series expansion of Phi(a, b, x) in a=0 up to order 5.\n"
+    s += "Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5)\n"
+    for name, c in zip(['A', 'X', 'B'], [A, X, B]):
+        for i in range(len(c)):
+            s += f"\n{name}[{i}] = " + str(c[i])
+    return s
+
+
+# expansion of digamma
+def dg_series(z, n):
+    """Symbolic expansion of digamma(z) in z=0 to order n.
+
+    See https://dlmf.nist.gov/5.7.E4 and with https://dlmf.nist.gov/5.5.E2
+    """
+    k = symbols("k")
+    return -1/z - EulerGamma + \
+        sympy.summation((-1)**k * zeta(k) * z**(k-1), (k, 2, n+1))
+
+
+def pg_series(k, z, n):
+    """Symbolic expansion of polygamma(k, z) in z=0 to order n."""
+    return sympy.diff(dg_series(z, n+k), z, k)
+
+
+def series_small_a_small_b():
+    """Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5.
+
+    Be aware of cancellation of poles in b=0 of digamma(b)/Gamma(b) and
+    polygamma functions.
+
+    digamma(b)/Gamma(b) = -1 - 2*M_EG*b + O(b^2)
+    digamma(b)^2/Gamma(b) = 1/b + 3*M_EG + b*(-5/12*PI^2+7/2*M_EG^2) + O(b^2)
+    polygamma(1, b)/Gamma(b) = 1/b + M_EG + b*(1/12*PI^2 + 1/2*M_EG^2) + O(b^2)
+    and so on.
+    """
+    order = 5
+    a, b, x, k = symbols("a b x k")
+    M_PI, M_EG, M_Z3 = symbols("M_PI M_EG M_Z3")
+    c_subs = {pi: M_PI, EulerGamma: M_EG, zeta(3): M_Z3}
+    A = []  # terms with a
+    X = []  # terms with x
+    B = []  # terms with b (polygammas expanded)
+    C = []  # terms that generate B
+    # Phi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i])
+    # B[0] = 1
+    # B[k] = sum(C[k] * b**k/k!, k=0..)
+    # Note: C[k] can be obtained from a series expansion of 1/gamma(b).
+    expression = gamma(b)/sympy.exp(x) * \
+        Sum(x**k/factorial(k)/gamma(a*k+b), (k, 0, S.Infinity))
+
+    # nth term of taylor series in a=0: a^n/n! * (d^n Phi(a, b, x)/da^n at a=0)
+    for n in range(0, order+1):
+        term = expression.diff(a, n).subs(a, 0).simplify().doit()
+        # set the whole bracket involving polygammas to 1
+        x_part = (term.subs(polygamma(0, b), 1)
+                  .replace(polygamma, lambda *args: 0))
+        # sign convention: x part always positive
+        x_part *= (-1)**n
+        # expansion of polygamma part with 1/gamma(b)
+        pg_part = term/x_part/gamma(b)
+        if n >= 1:
+            # Note: highest term is digamma^n
+            pg_part = pg_part.replace(polygamma,
+                                      lambda k, x: pg_series(k, x, order+1+n))
+            pg_part = (pg_part.series(b, 0, n=order+1-n)
+                       .removeO()
+                       .subs(polygamma(2, 1), -2*zeta(3))
+                       .simplify()
+                       )
+
+        A.append(a**n/factorial(n))
+        X.append(horner(x_part))
+        B.append(pg_part)
+
+    # Calculate C and put in the k!
+    C = sympy.Poly(B[1].subs(c_subs), b).coeffs()
+    C.reverse()
+    for i in range(len(C)):
+        C[i] = (C[i] * factorial(i)).simplify()
+
+    s = "Tylor series expansion of Phi(a, b, x) in a=0 and b=0 up to order 5."
+    s += "\nPhi(a, b, x) = exp(x) * sum(A[i] * X[i] * B[i], i=0..5)\n"
+    s += "B[0] = 1\n"
+    s += "B[i] = sum(C[k+i-1] * b**k/k!, k=0..)\n"
+    s += "\nM_PI = pi"
+    s += "\nM_EG = EulerGamma"
+    s += "\nM_Z3 = zeta(3)"
+    for name, c in zip(['A', 'X'], [A, X]):
+        for i in range(len(c)):
+            s += f"\n{name}[{i}] = "
+            s += str(c[i])
+    # For C, do also compute the values numerically
+    for i in range(len(C)):
+        s += f"\n# C[{i}] = "
+        s += str(C[i])
+        s += f"\nC[{i}] = "
+        s += str(C[i].subs({M_EG: EulerGamma, M_PI: pi, M_Z3: zeta(3)})
+                 .evalf(17))
+
+    # Does B have the assumed structure?
+    s += "\n\nTest if B[i] does have the assumed structure."
+    s += "\nC[i] are derived from B[1] alone."
+    s += "\nTest B[2] == C[1] + b*C[2] + b^2/2*C[3] + b^3/6*C[4] + .."
+    test = sum([b**k/factorial(k) * C[k+1] for k in range(order-1)])
+    test = (test - B[2].subs(c_subs)).simplify()
+    s += f"\ntest successful = {test==S(0)}"
+    s += "\nTest B[3] == C[2] + b*C[3] + b^2/2*C[4] + .."
+    test = sum([b**k/factorial(k) * C[k+2] for k in range(order-2)])
+    test = (test - B[3].subs(c_subs)).simplify()
+    s += f"\ntest successful = {test==S(0)}"
+    return s
+
+
+def asymptotic_series():
+    """Asymptotic expansion for large x.
+
+    Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k
+    Z = (a*x)^(1/(1+a))
+
+    Wright (1935) lists the coefficients C_0 and C_1 (he calls them a_0 and
+    a_1). With slightly different notation, Paris (2017) lists coefficients
+    c_k up to order k=3.
+    Paris (2017) uses ZP = (1+a)/a * Z  (ZP = Z of Paris) and
+    C_k = C_0 * (-a/(1+a))^k * c_k
+    """
+    order = 8
+
+    class g(sympy.Function):
+        """Helper function g according to Wright (1935)
+
+        g(n, rho, v) = (1 + (rho+2)/3 * v + (rho+2)*(rho+3)/(2*3) * v^2 + ...)
+
+        Note: Wright (1935) uses square root of above definition.
+        """
+        nargs = 3
+
+        @classmethod
+        def eval(cls, n, rho, v):
+            if not n >= 0:
+                raise ValueError("must have n >= 0")
+            elif n == 0:
+                return 1
+            else:
+                return g(n-1, rho, v) \
+                    + gammasimp(gamma(rho+2+n)/gamma(rho+2)) \
+                    / gammasimp(gamma(3+n)/gamma(3))*v**n
+
+    class coef_C(sympy.Function):
+        """Calculate coefficients C_m for integer m.
+
+        C_m is the coefficient of v^(2*m) in the Taylor expansion in v=0 of
+        Gamma(m+1/2)/(2*pi) * (2/(rho+1))^(m+1/2) * (1-v)^(-b)
+            * g(rho, v)^(-m-1/2)
+        """
+        nargs = 3
+
+        @classmethod
+        def eval(cls, m, rho, beta):
+            if not m >= 0:
+                raise ValueError("must have m >= 0")
+
+            v = symbols("v")
+            expression = (1-v)**(-beta) * g(2*m, rho, v)**(-m-Rational(1, 2))
+            res = expression.diff(v, 2*m).subs(v, 0) / factorial(2*m)
+            res = res * (gamma(m + Rational(1, 2)) / (2*pi)
+                         * (2/(rho+1))**(m + Rational(1, 2)))
+            return res
+
+    # in order to have nice ordering/sorting of expressions, we set a = xa.
+    xa, b, xap1 = symbols("xa b xap1")
+    C0 = coef_C(0, xa, b)
+    # a1 = a(1, rho, beta)
+    s = "Asymptotic expansion for large x\n"
+    s += "Phi(a, b, x) = Z**(1/2-b) * exp((1+a)/a * Z) \n"
+    s += "               * sum((-1)**k * C[k]/Z**k, k=0..6)\n\n"
+    s += "Z      = pow(a * x, 1/(1+a))\n"
+    s += "A[k]   = pow(a, k)\n"
+    s += "B[k]   = pow(b, k)\n"
+    s += "Ap1[k] = pow(1+a, k)\n\n"
+    s += "C[0] = 1./sqrt(2. * M_PI * Ap1[1])\n"
+    for i in range(1, order+1):
+        expr = (coef_C(i, xa, b) / (C0/(1+xa)**i)).simplify()
+        factor = [x.denominator() for x in sympy.Poly(expr).coeffs()]
+        factor = sympy.lcm(factor)
+        expr = (expr * factor).simplify().collect(b, sympy.factor)
+        expr = expr.xreplace({xa+1: xap1})
+        s += f"C[{i}] = C[0] / ({factor} * Ap1[{i}])\n"
+        s += f"C[{i}] *= {str(expr)}\n\n"
+    import re
+    re_a = re.compile(r'xa\*\*(\d+)')
+    s = re_a.sub(r'A[\1]', s)
+    re_b = re.compile(r'b\*\*(\d+)')
+    s = re_b.sub(r'B[\1]', s)
+    s = s.replace('xap1', 'Ap1[1]')
+    s = s.replace('xa', 'a')
+    # max integer = 2^31-1 = 2,147,483,647. Solution: Put a point after 10
+    # or more digits.
+    re_digits = re.compile(r'(\d{10,})')
+    s = re_digits.sub(r'\1.', s)
+    return s
+
+
+def optimal_epsilon_integral():
+    """Fit optimal choice of epsilon for integral representation.
+
+    The integrand of
+        int_0^pi P(eps, a, b, x, phi) * dphi
+    can exhibit oscillatory behaviour. It stems from the cosine of P and can be
+    minimized by minimizing the arc length of the argument
+        f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a * phi) + (1 - b) * phi
+    of cos(f(phi)).
+    We minimize the arc length in eps for a grid of values (a, b, x) and fit a
+    parametric function to it.
+    """
+    def fp(eps, a, b, x, phi):
+        """Derivative of f w.r.t. phi."""
+        eps_a = np.power(1. * eps, -a)
+        return eps * np.cos(phi) - a * x * eps_a * np.cos(a * phi) + 1 - b
+
+    def arclength(eps, a, b, x, epsrel=1e-2, limit=100):
+        """Compute Arc length of f.
+
+        Note that the arc length of a function f from t0 to t1 is given by
+            int_t0^t1 sqrt(1 + f'(t)^2) dt
+        """
+        return quad(lambda phi: np.sqrt(1 + fp(eps, a, b, x, phi)**2),
+                    0, np.pi,
+                    epsrel=epsrel, limit=100)[0]
+
+    # grid of minimal arc length values
+    data_a = [1e-3, 0.1, 0.5, 0.9, 1, 2, 4, 5, 6, 8]
+    data_b = [0, 1, 4, 7, 10]
+    data_x = [1, 1.5, 2, 4, 10, 20, 50, 100, 200, 500, 1e3, 5e3, 1e4]
+    data_a, data_b, data_x = np.meshgrid(data_a, data_b, data_x)
+    data_a, data_b, data_x = (data_a.flatten(), data_b.flatten(),
+                              data_x.flatten())
+    best_eps = []
+    for i in range(data_x.size):
+        best_eps.append(
+            minimize_scalar(lambda eps: arclength(eps, data_a[i], data_b[i],
+                                                  data_x[i]),
+                            bounds=(1e-3, 1000),
+                            method='Bounded', options={'xatol': 1e-3}).x
+        )
+    best_eps = np.array(best_eps)
+    # pandas would be nice, but here a dictionary is enough
+    df = {'a': data_a,
+          'b': data_b,
+          'x': data_x,
+          'eps': best_eps,
+          }
+
+    def func(data, A0, A1, A2, A3, A4, A5):
+        """Compute parametric function to fit."""
+        a = data['a']
+        b = data['b']
+        x = data['x']
+        return (A0 * b * np.exp(-0.5 * a)
+                + np.exp(A1 + 1 / (1 + a) * np.log(x) - A2 * np.exp(-A3 * a)
+                         + A4 / (1 + np.exp(A5 * a))))
+
+    func_params = list(curve_fit(func, df, df['eps'], method='trf')[0])
+
+    s = "Fit optimal eps for integrand P via minimal arc length\n"
+    s += "with parametric function:\n"
+    s += "optimal_eps = (A0 * b * exp(-a/2) + exp(A1 + 1 / (1 + a) * log(x)\n"
+    s += "              - A2 * exp(-A3 * a) + A4 / (1 + exp(A5 * a)))\n\n"
+    s += "Fitted parameters A0 to A5 are:\n"
+    s += ', '.join([f'{x:.5g}' for x in func_params])
+    return s
+
+
+def main():
+    t0 = time()
+    parser = ArgumentParser(description=__doc__,
+                            formatter_class=RawTextHelpFormatter)
+    parser.add_argument('action', type=int, choices=[1, 2, 3, 4],
+                        help='chose what expansion to precompute\n'
+                             '1 : Series for small a\n'
+                             '2 : Series for small a and small b\n'
+                             '3 : Asymptotic series for large x\n'
+                             '    This may take some time (>4h).\n'
+                             '4 : Fit optimal eps for integral representation.'
+                        )
+    args = parser.parse_args()
+
+    switch = {1: lambda: print(series_small_a()),
+              2: lambda: print(series_small_a_small_b()),
+              3: lambda: print(asymptotic_series()),
+              4: lambda: print(optimal_epsilon_integral())
+              }
+    switch.get(args.action, lambda: print("Invalid input."))()
+    print(f"\n{(time() - t0)/60:.1f} minutes elapsed.\n")
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..1de9b4fe552ca9178c452194ab84af6ca5daac71
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wright_bessel_data.py
@@ -0,0 +1,152 @@
+"""Compute a grid of values for Wright's generalized Bessel function
+and save the values to data files for use in tests. Using mpmath directly in
+tests would take too long.
+
+This takes about 10 minutes to run on a 2.7 GHz i7 Macbook Pro.
+"""
+from functools import lru_cache
+import os
+from time import time
+
+import numpy as np
+from scipy.special._mptestutils import mpf2float
+
+try:
+    import mpmath as mp
+except ImportError:
+    pass
+
+# exp_inf: smallest value x for which exp(x) == inf
+exp_inf = 709.78271289338403
+
+
+# 64 Byte per value
+@lru_cache(maxsize=100_000)
+def rgamma_cached(x, dps):
+    with mp.workdps(dps):
+        return mp.rgamma(x)
+
+
+def mp_wright_bessel(a, b, x, dps=50, maxterms=2000):
+    """Compute Wright's generalized Bessel function as Series with mpmath.
+    """
+    with mp.workdps(dps):
+        a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x)
+        res = mp.nsum(lambda k: x**k / mp.fac(k)
+                      * rgamma_cached(a * k + b, dps=dps),
+                      [0, mp.inf],
+                      tol=dps, method='s', steps=[maxterms]
+                      )
+        return mpf2float(res)
+
+
+def main():
+    t0 = time()
+    print(__doc__)
+    pwd = os.path.dirname(__file__)
+    eps = np.finfo(float).eps * 100
+
+    a_range = np.array([eps,
+                        1e-4 * (1 - eps), 1e-4, 1e-4 * (1 + eps),
+                        1e-3 * (1 - eps), 1e-3, 1e-3 * (1 + eps),
+                        0.1, 0.5,
+                        1 * (1 - eps), 1, 1 * (1 + eps),
+                        1.5, 2, 4.999, 5, 10])
+    b_range = np.array([0, eps, 1e-10, 1e-5, 0.1, 1, 2, 10, 20, 100])
+    x_range = np.array([0, eps, 1 - eps, 1, 1 + eps,
+                        1.5,
+                        2 - eps, 2, 2 + eps,
+                        9 - eps, 9, 9 + eps,
+                        10 * (1 - eps), 10, 10 * (1 + eps),
+                        100 * (1 - eps), 100, 100 * (1 + eps),
+                        500, exp_inf, 1e3, 1e5, 1e10, 1e20])
+
+    a_range, b_range, x_range = np.meshgrid(a_range, b_range, x_range,
+                                            indexing='ij')
+    a_range = a_range.flatten()
+    b_range = b_range.flatten()
+    x_range = x_range.flatten()
+
+    # filter out some values, especially too large x
+    bool_filter = ~((a_range < 5e-3) & (x_range >= exp_inf))
+    bool_filter = bool_filter & ~((a_range < 0.2) & (x_range > exp_inf))
+    bool_filter = bool_filter & ~((a_range < 0.5) & (x_range > 1e3))
+    bool_filter = bool_filter & ~((a_range < 0.56) & (x_range > 5e3))
+    bool_filter = bool_filter & ~((a_range < 1) & (x_range > 1e4))
+    bool_filter = bool_filter & ~((a_range < 1.4) & (x_range > 1e5))
+    bool_filter = bool_filter & ~((a_range < 1.8) & (x_range > 1e6))
+    bool_filter = bool_filter & ~((a_range < 2.2) & (x_range > 1e7))
+    bool_filter = bool_filter & ~((a_range < 2.5) & (x_range > 1e8))
+    bool_filter = bool_filter & ~((a_range < 2.9) & (x_range > 1e9))
+    bool_filter = bool_filter & ~((a_range < 3.3) & (x_range > 1e10))
+    bool_filter = bool_filter & ~((a_range < 3.7) & (x_range > 1e11))
+    bool_filter = bool_filter & ~((a_range < 4) & (x_range > 1e12))
+    bool_filter = bool_filter & ~((a_range < 4.4) & (x_range > 1e13))
+    bool_filter = bool_filter & ~((a_range < 4.7) & (x_range > 1e14))
+    bool_filter = bool_filter & ~((a_range < 5.1) & (x_range > 1e15))
+    bool_filter = bool_filter & ~((a_range < 5.4) & (x_range > 1e16))
+    bool_filter = bool_filter & ~((a_range < 5.8) & (x_range > 1e17))
+    bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18))
+    bool_filter = bool_filter & ~((a_range < 6.2) & (x_range > 1e18))
+    bool_filter = bool_filter & ~((a_range < 6.5) & (x_range > 1e19))
+    bool_filter = bool_filter & ~((a_range < 6.9) & (x_range > 1e20))
+
+    # filter out known values that do not meet the required numerical accuracy
+    # see test test_wright_data_grid_failures
+    failing = np.array([
+        [0.1, 100, 709.7827128933841],
+        [0.5, 10, 709.7827128933841],
+        [0.5, 10, 1000],
+        [0.5, 100, 1000],
+        [1, 20, 100000],
+        [1, 100, 100000],
+        [1.0000000000000222, 20, 100000],
+        [1.0000000000000222, 100, 100000],
+        [1.5, 0, 500],
+        [1.5, 2.220446049250313e-14, 500],
+        [1.5, 1.e-10, 500],
+        [1.5, 1.e-05, 500],
+        [1.5, 0.1, 500],
+        [1.5, 20, 100000],
+        [1.5, 100, 100000],
+        ]).tolist()
+
+    does_fail = np.full_like(a_range, False, dtype=bool)
+    for i in range(x_range.size):
+        if [a_range[i], b_range[i], x_range[i]] in failing:
+            does_fail[i] = True
+
+    # filter and flatten
+    a_range = a_range[bool_filter]
+    b_range = b_range[bool_filter]
+    x_range = x_range[bool_filter]
+    does_fail = does_fail[bool_filter]
+
+    dataset = []
+    print(f"Computing {x_range.size} single points.")
+    print("Tests will fail for the following data points:")
+    for i in range(x_range.size):
+        a = a_range[i]
+        b = b_range[i]
+        x = x_range[i]
+        # take care of difficult corner cases
+        maxterms = 1000
+        if a < 1e-6 and x >= exp_inf/10:
+            maxterms = 2000
+        f = mp_wright_bessel(a, b, x, maxterms=maxterms)
+        if does_fail[i]:
+            print("failing data point a, b, x, value = "
+                  f"[{a}, {b}, {x}, {f}]")
+        else:
+            dataset.append((a, b, x, f))
+    dataset = np.array(dataset)
+
+    filename = os.path.join(pwd, '..', 'tests', 'data', 'local',
+                            'wright_bessel.txt')
+    np.savetxt(filename, dataset)
+
+    print(f"{(time() - t0)/60:.1f} minutes elapsed")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bcd0345a9c1b90c45b0e9e3340ab4da4ec5c6d7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/wrightomega.py
@@ -0,0 +1,41 @@
+import numpy as np
+
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+def mpmath_wrightomega(x):
+    return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
+
+
+def wrightomega_series_error(x):
+    series = x
+    desired = mpmath_wrightomega(x)
+    return abs(series - desired) / desired
+
+
+def wrightomega_exp_error(x):
+    exponential_approx = mpmath.exp(x)
+    desired = mpmath_wrightomega(x)
+    return abs(exponential_approx - desired) / desired
+
+
+def main():
+    desired_error = 2 * np.finfo(float).eps
+    print('Series Error')
+    for x in [1e5, 1e10, 1e15, 1e20]:
+        with mpmath.workdps(100):
+            error = wrightomega_series_error(x)
+        print(x, error, error < desired_error)
+
+    print('Exp error')
+    for x in [-10, -25, -50, -100, -200, -400, -700, -740]:
+        with mpmath.workdps(100):
+            error = wrightomega_exp_error(x)
+        print(x, error, error < desired_error)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py
new file mode 100644
index 0000000000000000000000000000000000000000..d408b1a2fffb6872287452923fcc9394adc13a7c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_precompute/zetac.py
@@ -0,0 +1,27 @@
+"""Compute the Taylor series for zeta(x) - 1 around x = 0."""
+try:
+    import mpmath
+except ImportError:
+    pass
+
+
+def zetac_series(N):
+    coeffs = []
+    with mpmath.workdps(100):
+        coeffs.append(-1.5)
+        for n in range(1, N):
+            coeff = mpmath.diff(mpmath.zeta, 0, n)/mpmath.factorial(n)
+            coeffs.append(coeff)
+    return coeffs
+
+
+def main():
+    print(__doc__)
+    coeffs = zetac_series(10)
+    coeffs = [mpmath.nstr(x, 20, min_fixed=0, max_fixed=0)
+              for x in coeffs]
+    print("\n".join(coeffs[::-1]))
+
+
+if __name__ == '__main__':
+    main()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_sf_error.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1edc9800759dfda9e49bde1becc775a64bce958
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_sf_error.py
@@ -0,0 +1,15 @@
+"""Warnings and Exceptions that can be raised by special functions."""
+import warnings
+
+
+class SpecialFunctionWarning(Warning):
+    """Warning that can be emitted by special functions."""
+    pass
+
+
+warnings.simplefilter("always", category=SpecialFunctionWarning)
+
+
+class SpecialFunctionError(Exception):
+    """Exception that can be raised by special functions."""
+    pass
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..2525eceb47ec2b20b45ca693e19e741f4a666597
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_spfun_stats.py
@@ -0,0 +1,106 @@
+# Last Change: Sat Mar 21 02:00 PM 2009 J
+
+# Copyright (c) 2001, 2002 Enthought, Inc.
+#
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#   a. Redistributions of source code must retain the above copyright notice,
+#      this list of conditions and the following disclaimer.
+#   b. Redistributions in binary form must reproduce the above copyright
+#      notice, this list of conditions and the following disclaimer in the
+#      documentation and/or other materials provided with the distribution.
+#   c. Neither the name of the Enthought nor the names of its contributors
+#      may be used to endorse or promote products derived from this software
+#      without specific prior written permission.
+#
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+# DAMAGE.
+
+"""Some more special functions which may be useful for multivariate statistical
+analysis."""
+
+import numpy as np
+from scipy.special import gammaln as loggam
+
+
+__all__ = ['multigammaln']
+
+
+def multigammaln(a, d):
+    r"""Returns the log of multivariate gamma, also sometimes called the
+    generalized gamma.
+
+    Parameters
+    ----------
+    a : ndarray
+        The multivariate gamma is computed for each item of `a`.
+    d : int
+        The dimension of the space of integration.
+
+    Returns
+    -------
+    res : ndarray
+        The values of the log multivariate gamma at the given points `a`.
+
+    Notes
+    -----
+    The formal definition of the multivariate gamma of dimension d for a real
+    `a` is
+
+    .. math::
+
+        \Gamma_d(a) = \int_{A>0} e^{-tr(A)} |A|^{a - (d+1)/2} dA
+
+    with the condition :math:`a > (d-1)/2`, and :math:`A > 0` being the set of
+    all the positive definite matrices of dimension `d`.  Note that `a` is a
+    scalar: the integrand only is multivariate, the argument is not (the
+    function is defined over a subset of the real set).
+
+    This can be proven to be equal to the much friendlier equation
+
+    .. math::
+
+        \Gamma_d(a) = \pi^{d(d-1)/4} \prod_{i=1}^{d} \Gamma(a - (i-1)/2).
+
+    References
+    ----------
+    R. J. Muirhead, Aspects of multivariate statistical theory (Wiley Series in
+    probability and mathematical statistics).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.special import multigammaln, gammaln
+    >>> a = 23.5
+    >>> d = 10
+    >>> multigammaln(a, d)
+    454.1488605074416
+
+    Verify that the result agrees with the logarithm of the equation
+    shown above:
+
+    >>> d*(d-1)/4*np.log(np.pi) + gammaln(a - 0.5*np.arange(0, d)).sum()
+    454.1488605074416
+    """
+    a = np.asarray(a)
+    if not np.isscalar(d) or (np.floor(d) != d):
+        raise ValueError("d should be a positive integer (dimension)")
+    if np.any(a <= 0.5 * (d - 1)):
+        raise ValueError(f"condition a ({a:f}) > 0.5 * (d-1) ({0.5 * (d-1):f}) not met")
+
+    res = (d * (d-1) * 0.25) * np.log(np.pi)
+    res += np.sum(loggam([(a - (j - 1.)/2) for j in range(1, d+1)]), axis=0)
+    return res
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3d871fcd07ef092962a4594cf780445daae4458
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_spherical_bessel.py
@@ -0,0 +1,397 @@
+from functools import wraps
+from scipy._lib._util import _lazywhere
+import numpy as np
+from ._ufuncs import (_spherical_jn, _spherical_yn, _spherical_in,
+                      _spherical_kn, _spherical_jn_d, _spherical_yn_d,
+                      _spherical_in_d, _spherical_kn_d)
+
+
+def use_reflection(sign_n_even=None, reflection_fun=None):
+    # - If reflection_fun is not specified, reflects negative `z` and multiplies
+    #   output by appropriate sign (indicated by `sign_n_even`).
+    # - If reflection_fun is specified, calls `reflection_fun` instead of `fun`.
+    # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+    def decorator(fun):
+        def standard_reflection(n, z, derivative):
+            # sign_n_even indicates the sign when the order `n` is even
+            sign = np.where(n % 2 == 0, sign_n_even, -sign_n_even)
+            # By the chain rule, differentiation at `-z` adds a minus sign
+            sign = -sign if derivative else sign
+            # Evaluate at positive z (minus negative z) and adjust the sign
+            return fun(n, -z, derivative) * sign
+
+        @wraps(fun)
+        def wrapper(n, z, derivative=False):
+            z = np.asarray(z)
+
+            if np.issubdtype(z.dtype, np.complexfloating):
+                return fun(n, z, derivative)  # complex dtype just works
+
+            f2 = standard_reflection if reflection_fun is None else reflection_fun
+            return _lazywhere(z.real >= 0, (n, z),
+                              f=lambda n, z: fun(n, z, derivative),
+                              f2=lambda n, z: f2(n, z, derivative))[()]
+        return wrapper
+    return decorator
+
+
+@use_reflection(+1)  # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+def spherical_jn(n, z, derivative=False):
+    r"""Spherical Bessel function of the first kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: j_n(z) = \sqrt{\frac{\pi}{2z}} J_{n + 1/2}(z),
+
+    where :math:`J_n` is the Bessel function of the first kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    jn : ndarray
+
+    Notes
+    -----
+    For real arguments greater than the order, the function is computed
+    using the ascending recurrence [2]_. For small real or complex
+    arguments, the definitional relation to the cylindrical Bessel function
+    of the first kind is used.
+
+    The derivative is computed using the relations [3]_,
+
+    .. math::
+        j_n'(z) = j_{n-1}(z) - \frac{n + 1}{z} j_n(z).
+
+        j_0'(z) = -j_1(z)
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E3
+    .. [2] https://dlmf.nist.gov/10.51.E1
+    .. [3] https://dlmf.nist.gov/10.51.E2
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The spherical Bessel functions of the first kind :math:`j_n` accept
+    both real and complex second argument. They can return a complex type:
+
+    >>> from scipy.special import spherical_jn
+    >>> spherical_jn(0, 3+5j)
+    (-9.878987731663194-8.021894345786002j)
+    >>> type(spherical_jn(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_jn(3, x, True),
+    ...             spherical_jn(2, x) - 4/x * spherical_jn(3, x))
+    True
+
+    The first few :math:`j_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 10.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-0.5, 1.5)
+    >>> ax.set_title(r'Spherical Bessel functions $j_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_jn(n, x), label=rf'$j_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_jn_d(n, z)
+    else:
+        return _spherical_jn(n, z)
+
+
+@use_reflection(-1)  # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+def spherical_yn(n, z, derivative=False):
+    r"""Spherical Bessel function of the second kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: y_n(z) = \sqrt{\frac{\pi}{2z}} Y_{n + 1/2}(z),
+
+    where :math:`Y_n` is the Bessel function of the second kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    yn : ndarray
+
+    Notes
+    -----
+    For real arguments, the function is computed using the ascending
+    recurrence [2]_.  For complex arguments, the definitional relation to
+    the cylindrical Bessel function of the second kind is used.
+
+    The derivative is computed using the relations [3]_,
+
+    .. math::
+        y_n' = y_{n-1} - \frac{n + 1}{z} y_n.
+
+        y_0' = -y_1
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E4
+    .. [2] https://dlmf.nist.gov/10.51.E1
+    .. [3] https://dlmf.nist.gov/10.51.E2
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The spherical Bessel functions of the second kind :math:`y_n` accept
+    both real and complex second argument. They can return a complex type:
+
+    >>> from scipy.special import spherical_yn
+    >>> spherical_yn(0, 3+5j)
+    (8.022343088587197-9.880052589376795j)
+    >>> type(spherical_yn(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_yn(3, x, True),
+    ...             spherical_yn(2, x) - 4/x * spherical_yn(3, x))
+    True
+
+    The first few :math:`y_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 10.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-2.0, 1.0)
+    >>> ax.set_title(r'Spherical Bessel functions $y_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_yn(n, x), label=rf'$y_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_yn_d(n, z)
+    else:
+        return _spherical_yn(n, z)
+
+
+@use_reflection(+1)  # See DLMF 10.47(v) https://dlmf.nist.gov/10.47
+def spherical_in(n, z, derivative=False):
+    r"""Modified spherical Bessel function of the first kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: i_n(z) = \sqrt{\frac{\pi}{2z}} I_{n + 1/2}(z),
+
+    where :math:`I_n` is the modified Bessel function of the first kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    in : ndarray
+
+    Notes
+    -----
+    The function is computed using its definitional relation to the
+    modified cylindrical Bessel function of the first kind.
+
+    The derivative is computed using the relations [2]_,
+
+    .. math::
+        i_n' = i_{n-1} - \frac{n + 1}{z} i_n.
+
+        i_1' = i_0
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E7
+    .. [2] https://dlmf.nist.gov/10.51.E5
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The modified spherical Bessel functions of the first kind :math:`i_n`
+    accept both real and complex second argument.
+    They can return a complex type:
+
+    >>> from scipy.special import spherical_in
+    >>> spherical_in(0, 3+5j)
+    (-1.1689867793369182-1.2697305267234222j)
+    >>> type(spherical_in(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_in(3, x, True),
+    ...             spherical_in(2, x) - 4/x * spherical_in(3, x))
+    True
+
+    The first few :math:`i_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 6.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(-0.5, 5.0)
+    >>> ax.set_title(r'Modified spherical Bessel functions $i_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_in(n, x), label=rf'$i_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_in_d(n, z)
+    else:
+        return _spherical_in(n, z)
+
+
+def spherical_kn_reflection(n, z, derivative=False):
+    # More complex than the other cases, and this will likely be re-implemented
+    # in C++ anyway. Would require multiple function evaluations. Probably about
+    # as fast to just resort to complex math, and much simpler.
+    return spherical_kn(n, z + 0j, derivative=derivative).real
+
+
+@use_reflection(reflection_fun=spherical_kn_reflection)
+def spherical_kn(n, z, derivative=False):
+    r"""Modified spherical Bessel function of the second kind or its derivative.
+
+    Defined as [1]_,
+
+    .. math:: k_n(z) = \sqrt{\frac{\pi}{2z}} K_{n + 1/2}(z),
+
+    where :math:`K_n` is the modified Bessel function of the second kind.
+
+    Parameters
+    ----------
+    n : int, array_like
+        Order of the Bessel function (n >= 0).
+    z : complex or float, array_like
+        Argument of the Bessel function.
+    derivative : bool, optional
+        If True, the value of the derivative (rather than the function
+        itself) is returned.
+
+    Returns
+    -------
+    kn : ndarray
+
+    Notes
+    -----
+    The function is computed using its definitional relation to the
+    modified cylindrical Bessel function of the second kind.
+
+    The derivative is computed using the relations [2]_,
+
+    .. math::
+        k_n' = -k_{n-1} - \frac{n + 1}{z} k_n.
+
+        k_0' = -k_1
+
+
+    .. versionadded:: 0.18.0
+
+    References
+    ----------
+    .. [1] https://dlmf.nist.gov/10.47.E9
+    .. [2] https://dlmf.nist.gov/10.51.E5
+    .. [AS] Milton Abramowitz and Irene A. Stegun, eds.
+        Handbook of Mathematical Functions with Formulas,
+        Graphs, and Mathematical Tables. New York: Dover, 1972.
+
+    Examples
+    --------
+    The modified spherical Bessel functions of the second kind :math:`k_n`
+    accept both real and complex second argument.
+    They can return a complex type:
+
+    >>> from scipy.special import spherical_kn
+    >>> spherical_kn(0, 3+5j)
+    (0.012985785614001561+0.003354691603137546j)
+    >>> type(spherical_kn(0, 3+5j))
+    
+
+    We can verify the relation for the derivative from the Notes
+    for :math:`n=3` in the interval :math:`[1, 2]`:
+
+    >>> import numpy as np
+    >>> x = np.arange(1.0, 2.0, 0.01)
+    >>> np.allclose(spherical_kn(3, x, True),
+    ...             - 4/x * spherical_kn(3, x) - spherical_kn(2, x))
+    True
+
+    The first few :math:`k_n` with real argument:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.arange(0.0, 4.0, 0.01)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_ylim(0.0, 5.0)
+    >>> ax.set_title(r'Modified spherical Bessel functions $k_n$')
+    >>> for n in np.arange(0, 4):
+    ...     ax.plot(x, spherical_kn(n, x), label=rf'$k_{n}$')
+    >>> plt.legend(loc='best')
+    >>> plt.show()
+
+    """
+    n = np.asarray(n, dtype=np.dtype("long"))
+    if derivative:
+        return _spherical_kn_d(n, z)
+    else:
+        return _spherical_kn(n, z)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f5101198cebcbb5138e88a2050a5c4d7a115d60
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_support_alternative_backends.py
@@ -0,0 +1,202 @@
+import os
+import sys
+import functools
+
+import numpy as np
+from scipy._lib._array_api import (
+    array_namespace, scipy_namespace_for, is_numpy
+)
+from . import _ufuncs
+# These don't really need to be imported, but otherwise IDEs might not realize
+# that these are defined in this file / report an error in __init__.py
+from ._ufuncs import (
+    log_ndtr, ndtr, ndtri, erf, erfc, i0, i0e, i1, i1e, gammaln,  # noqa: F401
+    gammainc, gammaincc, logit, expit, entr, rel_entr, xlogy,  # noqa: F401
+    chdtr, chdtrc, betainc, betaincc, stdtr  # noqa: F401
+)
+
+_SCIPY_ARRAY_API = os.environ.get("SCIPY_ARRAY_API", False)
+array_api_compat_prefix = "scipy._lib.array_api_compat"
+
+
+def get_array_special_func(f_name, xp, n_array_args):
+    spx = scipy_namespace_for(xp)
+    f = None
+    if is_numpy(xp):
+        f = getattr(_ufuncs, f_name, None)
+    elif spx is not None:
+        f = getattr(spx.special, f_name, None)
+
+    if f is not None:
+        return f
+
+    # if generic array-API implementation is available, use that;
+    # otherwise, fall back to NumPy/SciPy
+    if f_name in _generic_implementations:
+        _f = _generic_implementations[f_name](xp=xp, spx=spx)
+        if _f is not None:
+            return _f
+
+    _f = getattr(_ufuncs, f_name, None)
+    def __f(*args, _f=_f, _xp=xp, **kwargs):
+        array_args = args[:n_array_args]
+        other_args = args[n_array_args:]
+        array_args = [np.asarray(arg) for arg in array_args]
+        out = _f(*array_args, *other_args, **kwargs)
+        return _xp.asarray(out)
+
+    return __f
+
+
+def _get_shape_dtype(*args, xp):
+    args = xp.broadcast_arrays(*args)
+    shape = args[0].shape
+    dtype = xp.result_type(*args)
+    if xp.isdtype(dtype, 'integral'):
+        dtype = xp.float64
+        args = [xp.asarray(arg, dtype=dtype) for arg in args]
+    return args, shape, dtype
+
+
+def _rel_entr(xp, spx):
+    def __rel_entr(x, y, *, xp=xp):
+        args, shape, dtype = _get_shape_dtype(x, y, xp=xp)
+        x, y = args
+        res = xp.full(x.shape, xp.inf, dtype=dtype)
+        res[(x == 0) & (y >= 0)] = xp.asarray(0, dtype=dtype)
+        i = (x > 0) & (y > 0)
+        res[i] = x[i] * (xp.log(x[i]) - xp.log(y[i]))
+        return res
+    return __rel_entr
+
+
+def _xlogy(xp, spx):
+    def __xlogy(x, y, *, xp=xp):
+        with np.errstate(divide='ignore', invalid='ignore'):
+            temp = x * xp.log(y)
+        return xp.where(x == 0., xp.asarray(0., dtype=temp.dtype), temp)
+    return __xlogy
+
+
+def _chdtr(xp, spx):
+    # The difference between this and just using `gammainc`
+    # defined by `get_array_special_func` is that if `gammainc`
+    # isn't found, we don't want to use the SciPy version; we'll
+    # return None here and use the SciPy version of `chdtr`.
+    gammainc = getattr(spx.special, 'gammainc', None) if spx else None  # noqa: F811
+    if gammainc is None and hasattr(xp, 'special'):
+        gammainc = getattr(xp.special, 'gammainc', None)
+    if gammainc is None:
+        return None
+
+    def __chdtr(v, x):
+        res = gammainc(v / 2, x / 2)  # this is almost all we need
+        # The rest can be removed when google/jax#20507 is resolved
+        mask = (v == 0) & (x > 0)  # JAX returns NaN
+        res = xp.where(mask, 1., res)
+        mask = xp.isinf(v) & xp.isinf(x)  # JAX returns 1.0
+        return xp.where(mask, xp.nan, res)
+    return __chdtr
+
+
+def _chdtrc(xp, spx):
+    # The difference between this and just using `gammaincc`
+    # defined by `get_array_special_func` is that if `gammaincc`
+    # isn't found, we don't want to use the SciPy version; we'll
+    # return None here and use the SciPy version of `chdtrc`.
+    gammaincc = getattr(spx.special, 'gammaincc', None) if spx else None  # noqa: F811
+    if gammaincc is None and hasattr(xp, 'special'):
+        gammaincc = getattr(xp.special, 'gammaincc', None)
+    if gammaincc is None:
+        return None
+
+    def __chdtrc(v, x):
+        res = xp.where(x >= 0, gammaincc(v/2, x/2), 1)
+        i_nan = ((x == 0) & (v == 0)) | xp.isnan(x) | xp.isnan(v) | (v <= 0)
+        res = xp.where(i_nan, xp.nan, res)
+        return res
+    return __chdtrc
+
+
+def _betaincc(xp, spx):
+    betainc = getattr(spx.special, 'betainc', None) if spx else None  # noqa: F811
+    if betainc is None and hasattr(xp, 'special'):
+        betainc = getattr(xp.special, 'betainc', None)
+    if betainc is None:
+        return None
+
+    def __betaincc(a, b, x):
+        # not perfect; might want to just rely on SciPy
+        return betainc(b, a, 1-x)
+    return __betaincc
+
+
+def _stdtr(xp, spx):
+    betainc = getattr(spx.special, 'betainc', None) if spx else None  # noqa: F811
+    if betainc is None and hasattr(xp, 'special'):
+        betainc = getattr(xp.special, 'betainc', None)
+    if betainc is None:
+        return None
+
+    def __stdtr(df, t):
+        x = df / (t ** 2 + df)
+        tail = betainc(df / 2, 0.5, x) / 2
+        return xp.where(t < 0, tail, 1 - tail)
+
+    return __stdtr
+
+
+_generic_implementations = {'rel_entr': _rel_entr,
+                            'xlogy': _xlogy,
+                            'chdtr': _chdtr,
+                            'chdtrc': _chdtrc,
+                            'betaincc': _betaincc,
+                            'stdtr': _stdtr,
+                            }
+
+
+# functools.wraps doesn't work because:
+# 'numpy.ufunc' object has no attribute '__module__'
+def support_alternative_backends(f_name, n_array_args):
+    func = getattr(_ufuncs, f_name)
+
+    @functools.wraps(func)
+    def wrapped(*args, **kwargs):
+        xp = array_namespace(*args[:n_array_args])
+        f = get_array_special_func(f_name, xp, n_array_args)
+        return f(*args, **kwargs)
+
+    return wrapped
+
+
+array_special_func_map = {
+    'log_ndtr': 1,
+    'ndtr': 1,
+    'ndtri': 1,
+    'erf': 1,
+    'erfc': 1,
+    'i0': 1,
+    'i0e': 1,
+    'i1': 1,
+    'i1e': 1,
+    'gammaln': 1,
+    'gammainc': 2,
+    'gammaincc': 2,
+    'logit': 1,
+    'expit': 1,
+    'entr': 1,
+    'rel_entr': 2,
+    'xlogy': 2,
+    'chdtr': 2,
+    'chdtrc': 2,
+    'betainc': 3,
+    'betaincc': 3,
+    'stdtr': 2,
+}
+
+for f_name, n_array_args in array_special_func_map.items():
+    f = (support_alternative_backends(f_name, n_array_args) if _SCIPY_ARRAY_API
+         else getattr(_ufuncs, f_name))
+    sys.modules[__name__].__dict__[f_name] = f
+
+__all__ = list(array_special_func_map)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..1e6c272f16fa2bd3ae75af412bc6ae3270158ce4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_test_internal.pyi
@@ -0,0 +1,9 @@
+import numpy as np
+
+def have_fenv() -> bool: ...
+def random_double(size: int, rng: np.random.RandomState) -> np.float64: ...
+def test_add_round(size: int, mode: str, rng: np.random.RandomState): ...
+
+def _dd_exp(xhi: float, xlo: float) -> tuple[float, float]: ...
+def _dd_log(xhi: float, xlo: float) -> tuple[float, float]: ...
+def _dd_expm1(xhi: float, xlo: float) -> tuple[float, float]: ...
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_testutils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_testutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0c2bd3053d076aacfa8be1d53cd851443fd8821
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_testutils.py
@@ -0,0 +1,321 @@
+import os
+import functools
+import operator
+from scipy._lib import _pep440
+
+import numpy as np
+from numpy.testing import assert_
+import pytest
+
+import scipy.special as sc
+
+__all__ = ['with_special_errors', 'assert_func_equal', 'FuncData']
+
+
+#------------------------------------------------------------------------------
+# Check if a module is present to be used in tests
+#------------------------------------------------------------------------------
+
+class MissingModule:
+    def __init__(self, name):
+        self.name = name
+
+
+def check_version(module, min_ver):
+    if type(module) is MissingModule:
+        return pytest.mark.skip(reason=f"{module.name} is not installed")
+    return pytest.mark.skipif(
+        _pep440.parse(module.__version__) < _pep440.Version(min_ver),
+        reason=f"{module.__name__} version >= {min_ver} required"
+    )
+
+
+#------------------------------------------------------------------------------
+# Enable convergence and loss of precision warnings -- turn off one by one
+#------------------------------------------------------------------------------
+
+def with_special_errors(func):
+    """
+    Enable special function errors (such as underflow, overflow,
+    loss of precision, etc.)
+    """
+    @functools.wraps(func)
+    def wrapper(*a, **kw):
+        with sc.errstate(all='raise'):
+            res = func(*a, **kw)
+        return res
+    return wrapper
+
+
+#------------------------------------------------------------------------------
+# Comparing function values at many data points at once, with helpful
+# error reports
+#------------------------------------------------------------------------------
+
+def assert_func_equal(func, results, points, rtol=None, atol=None,
+                      param_filter=None, knownfailure=None,
+                      vectorized=True, dtype=None, nan_ok=False,
+                      ignore_inf_sign=False, distinguish_nan_and_inf=True):
+    if hasattr(points, 'next'):
+        # it's a generator
+        points = list(points)
+
+    points = np.asarray(points)
+    if points.ndim == 1:
+        points = points[:,None]
+    nparams = points.shape[1]
+
+    if hasattr(results, '__name__'):
+        # function
+        data = points
+        result_columns = None
+        result_func = results
+    else:
+        # dataset
+        data = np.c_[points, results]
+        result_columns = list(range(nparams, data.shape[1]))
+        result_func = None
+
+    fdata = FuncData(func, data, list(range(nparams)),
+                     result_columns=result_columns, result_func=result_func,
+                     rtol=rtol, atol=atol, param_filter=param_filter,
+                     knownfailure=knownfailure, nan_ok=nan_ok, vectorized=vectorized,
+                     ignore_inf_sign=ignore_inf_sign,
+                     distinguish_nan_and_inf=distinguish_nan_and_inf)
+    fdata.check()
+
+
+class FuncData:
+    """
+    Data set for checking a special function.
+
+    Parameters
+    ----------
+    func : function
+        Function to test
+    data : numpy array
+        columnar data to use for testing
+    param_columns : int or tuple of ints
+        Columns indices in which the parameters to `func` lie.
+        Can be imaginary integers to indicate that the parameter
+        should be cast to complex.
+    result_columns : int or tuple of ints, optional
+        Column indices for expected results from `func`.
+    result_func : callable, optional
+        Function to call to obtain results.
+    rtol : float, optional
+        Required relative tolerance. Default is 5*eps.
+    atol : float, optional
+        Required absolute tolerance. Default is 5*tiny.
+    param_filter : function, or tuple of functions/Nones, optional
+        Filter functions to exclude some parameter ranges.
+        If omitted, no filtering is done.
+    knownfailure : str, optional
+        Known failure error message to raise when the test is run.
+        If omitted, no exception is raised.
+    nan_ok : bool, optional
+        If nan is always an accepted result.
+    vectorized : bool, optional
+        Whether all functions passed in are vectorized.
+    ignore_inf_sign : bool, optional
+        Whether to ignore signs of infinities.
+        (Doesn't matter for complex-valued functions.)
+    distinguish_nan_and_inf : bool, optional
+        If True, treat numbers which contain nans or infs as
+        equal. Sets ignore_inf_sign to be True.
+
+    """
+
+    def __init__(self, func, data, param_columns, result_columns=None,
+                 result_func=None, rtol=None, atol=None, param_filter=None,
+                 knownfailure=None, dataname=None, nan_ok=False, vectorized=True,
+                 ignore_inf_sign=False, distinguish_nan_and_inf=True):
+        self.func = func
+        self.data = data
+        self.dataname = dataname
+        if not hasattr(param_columns, '__len__'):
+            param_columns = (param_columns,)
+        self.param_columns = tuple(param_columns)
+        if result_columns is not None:
+            if not hasattr(result_columns, '__len__'):
+                result_columns = (result_columns,)
+            self.result_columns = tuple(result_columns)
+            if result_func is not None:
+                message = "Only result_func or result_columns should be provided"
+                raise ValueError(message)
+        elif result_func is not None:
+            self.result_columns = None
+        else:
+            raise ValueError("Either result_func or result_columns should be provided")
+        self.result_func = result_func
+        self.rtol = rtol
+        self.atol = atol
+        if not hasattr(param_filter, '__len__'):
+            param_filter = (param_filter,)
+        self.param_filter = param_filter
+        self.knownfailure = knownfailure
+        self.nan_ok = nan_ok
+        self.vectorized = vectorized
+        self.ignore_inf_sign = ignore_inf_sign
+        self.distinguish_nan_and_inf = distinguish_nan_and_inf
+        if not self.distinguish_nan_and_inf:
+            self.ignore_inf_sign = True
+
+    def get_tolerances(self, dtype):
+        if not np.issubdtype(dtype, np.inexact):
+            dtype = np.dtype(float)
+        info = np.finfo(dtype)
+        rtol, atol = self.rtol, self.atol
+        if rtol is None:
+            rtol = 5*info.eps
+        if atol is None:
+            atol = 5*info.tiny
+        return rtol, atol
+
+    def check(self, data=None, dtype=None, dtypes=None):
+        """Check the special function against the data."""
+        __tracebackhide__ = operator.methodcaller(
+            'errisinstance', AssertionError
+        )
+
+        if self.knownfailure:
+            pytest.xfail(reason=self.knownfailure)
+
+        if data is None:
+            data = self.data
+
+        if dtype is None:
+            dtype = data.dtype
+        else:
+            data = data.astype(dtype)
+
+        rtol, atol = self.get_tolerances(dtype)
+
+        # Apply given filter functions
+        if self.param_filter:
+            param_mask = np.ones((data.shape[0],), np.bool_)
+            for j, filter in zip(self.param_columns, self.param_filter):
+                if filter:
+                    param_mask &= list(filter(data[:,j]))
+            data = data[param_mask]
+
+        # Pick parameters from the correct columns
+        params = []
+        for idx, j in enumerate(self.param_columns):
+            if np.iscomplexobj(j):
+                j = int(j.imag)
+                params.append(data[:,j].astype(complex))
+            elif dtypes and idx < len(dtypes):
+                params.append(data[:, j].astype(dtypes[idx]))
+            else:
+                params.append(data[:,j])
+
+        # Helper for evaluating results
+        def eval_func_at_params(func, skip_mask=None):
+            if self.vectorized:
+                got = func(*params)
+            else:
+                got = []
+                for j in range(len(params[0])):
+                    if skip_mask is not None and skip_mask[j]:
+                        got.append(np.nan)
+                        continue
+                    got.append(func(*tuple([params[i][j] for i in range(len(params))])))
+                got = np.asarray(got)
+            if not isinstance(got, tuple):
+                got = (got,)
+            return got
+
+        # Evaluate function to be tested
+        got = eval_func_at_params(self.func)
+
+        # Grab the correct results
+        if self.result_columns is not None:
+            # Correct results passed in with the data
+            wanted = tuple([data[:,icol] for icol in self.result_columns])
+        else:
+            # Function producing correct results passed in
+            skip_mask = None
+            if self.nan_ok and len(got) == 1:
+                # Don't spend time evaluating what doesn't need to be evaluated
+                skip_mask = np.isnan(got[0])
+            wanted = eval_func_at_params(self.result_func, skip_mask=skip_mask)
+
+        # Check the validity of each output returned
+        assert_(len(got) == len(wanted))
+
+        for output_num, (x, y) in enumerate(zip(got, wanted)):
+            if np.issubdtype(x.dtype, np.complexfloating) or self.ignore_inf_sign:
+                pinf_x = np.isinf(x)
+                pinf_y = np.isinf(y)
+                minf_x = np.isinf(x)
+                minf_y = np.isinf(y)
+            else:
+                pinf_x = np.isposinf(x)
+                pinf_y = np.isposinf(y)
+                minf_x = np.isneginf(x)
+                minf_y = np.isneginf(y)
+            nan_x = np.isnan(x)
+            nan_y = np.isnan(y)
+
+            with np.errstate(all='ignore'):
+                abs_y = np.absolute(y)
+                abs_y[~np.isfinite(abs_y)] = 0
+                diff = np.absolute(x - y)
+                diff[~np.isfinite(diff)] = 0
+
+                rdiff = diff / np.absolute(y)
+                rdiff[~np.isfinite(rdiff)] = 0
+
+            tol_mask = (diff <= atol + rtol*abs_y)
+            pinf_mask = (pinf_x == pinf_y)
+            minf_mask = (minf_x == minf_y)
+
+            nan_mask = (nan_x == nan_y)
+
+            bad_j = ~(tol_mask & pinf_mask & minf_mask & nan_mask)
+
+            point_count = bad_j.size
+            if self.nan_ok:
+                bad_j &= ~nan_x
+                bad_j &= ~nan_y
+                point_count -= (nan_x | nan_y).sum()
+
+            if not self.distinguish_nan_and_inf and not self.nan_ok:
+                # If nan's are okay we've already covered all these cases
+                inf_x = np.isinf(x)
+                inf_y = np.isinf(y)
+                both_nonfinite = (inf_x & nan_y) | (nan_x & inf_y)
+                bad_j &= ~both_nonfinite
+                point_count -= both_nonfinite.sum()
+
+            if np.any(bad_j):
+                # Some bad results: inform what, where, and how bad
+                msg = [""]
+                msg.append(f"Max |adiff|: {diff[bad_j].max():g}")
+                msg.append(f"Max |rdiff|: {rdiff[bad_j].max():g}")
+                msg.append("Bad results (%d out of %d) for the following points "
+                           "(in output %d):"
+                           % (np.sum(bad_j), point_count, output_num,))
+                for j in np.nonzero(bad_j)[0]:
+                    j = int(j)
+                    def fmt(x):
+                        return '%30s' % np.array2string(x[j], precision=18)
+                    a = "  ".join(map(fmt, params))
+                    b = "  ".join(map(fmt, got))
+                    c = "  ".join(map(fmt, wanted))
+                    d = fmt(rdiff)
+                    msg.append(f"{a} => {b} != {c}  (rdiff {d})")
+                assert_(False, "\n".join(msg))
+
+    def __repr__(self):
+        """Pretty-printing"""
+        if np.any(list(map(np.iscomplexobj, self.param_columns))):
+            is_complex = " (complex)"
+        else:
+            is_complex = ""
+        if self.dataname:
+            return (f"")
+        else:
+            return f""
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0ccf14137096c862a0644cdb229cb98b4556e5d7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyi
@@ -0,0 +1,521 @@
+from typing import Any
+
+import numpy as np
+
+__all__ = [
+    'geterr',
+    'seterr',
+    'errstate',
+    'agm',
+    'airy',
+    'airye',
+    'bdtr',
+    'bdtrc',
+    'bdtri',
+    'bdtrik',
+    'bdtrin',
+    'bei',
+    'beip',
+    'ber',
+    'berp',
+    'besselpoly',
+    'beta',
+    'betainc',
+    'betaincc',
+    'betainccinv',
+    'betaincinv',
+    'betaln',
+    'binom',
+    'boxcox',
+    'boxcox1p',
+    'btdtria',
+    'btdtrib',
+    'cbrt',
+    'chdtr',
+    'chdtrc',
+    'chdtri',
+    'chdtriv',
+    'chndtr',
+    'chndtridf',
+    'chndtrinc',
+    'chndtrix',
+    'cosdg',
+    'cosm1',
+    'cotdg',
+    'dawsn',
+    'ellipe',
+    'ellipeinc',
+    'ellipj',
+    'ellipk',
+    'ellipkinc',
+    'ellipkm1',
+    'elliprc',
+    'elliprd',
+    'elliprf',
+    'elliprg',
+    'elliprj',
+    'entr',
+    'erf',
+    'erfc',
+    'erfcinv',
+    'erfcx',
+    'erfi',
+    'erfinv',
+    'eval_chebyc',
+    'eval_chebys',
+    'eval_chebyt',
+    'eval_chebyu',
+    'eval_gegenbauer',
+    'eval_genlaguerre',
+    'eval_hermite',
+    'eval_hermitenorm',
+    'eval_jacobi',
+    'eval_laguerre',
+    'eval_legendre',
+    'eval_sh_chebyt',
+    'eval_sh_chebyu',
+    'eval_sh_jacobi',
+    'eval_sh_legendre',
+    'exp1',
+    'exp10',
+    'exp2',
+    'expi',
+    'expit',
+    'expm1',
+    'expn',
+    'exprel',
+    'fdtr',
+    'fdtrc',
+    'fdtri',
+    'fdtridfd',
+    'fresnel',
+    'gamma',
+    'gammainc',
+    'gammaincc',
+    'gammainccinv',
+    'gammaincinv',
+    'gammaln',
+    'gammasgn',
+    'gdtr',
+    'gdtrc',
+    'gdtria',
+    'gdtrib',
+    'gdtrix',
+    'hankel1',
+    'hankel1e',
+    'hankel2',
+    'hankel2e',
+    'huber',
+    'hyp0f1',
+    'hyp1f1',
+    'hyp2f1',
+    'hyperu',
+    'i0',
+    'i0e',
+    'i1',
+    'i1e',
+    'inv_boxcox',
+    'inv_boxcox1p',
+    'it2i0k0',
+    'it2j0y0',
+    'it2struve0',
+    'itairy',
+    'iti0k0',
+    'itj0y0',
+    'itmodstruve0',
+    'itstruve0',
+    'iv',
+    'ive',
+    'j0',
+    'j1',
+    'jn',
+    'jv',
+    'jve',
+    'k0',
+    'k0e',
+    'k1',
+    'k1e',
+    'kei',
+    'keip',
+    'kelvin',
+    'ker',
+    'kerp',
+    'kl_div',
+    'kn',
+    'kolmogi',
+    'kolmogorov',
+    'kv',
+    'kve',
+    'log1p',
+    'log_expit',
+    'log_ndtr',
+    'log_wright_bessel',
+    'loggamma',
+    'logit',
+    'lpmv',
+    'mathieu_a',
+    'mathieu_b',
+    'mathieu_cem',
+    'mathieu_modcem1',
+    'mathieu_modcem2',
+    'mathieu_modsem1',
+    'mathieu_modsem2',
+    'mathieu_sem',
+    'modfresnelm',
+    'modfresnelp',
+    'modstruve',
+    'nbdtr',
+    'nbdtrc',
+    'nbdtri',
+    'nbdtrik',
+    'nbdtrin',
+    'ncfdtr',
+    'ncfdtri',
+    'ncfdtridfd',
+    'ncfdtridfn',
+    'ncfdtrinc',
+    'nctdtr',
+    'nctdtridf',
+    'nctdtrinc',
+    'nctdtrit',
+    'ndtr',
+    'ndtri',
+    'ndtri_exp',
+    'nrdtrimn',
+    'nrdtrisd',
+    'obl_ang1',
+    'obl_ang1_cv',
+    'obl_cv',
+    'obl_rad1',
+    'obl_rad1_cv',
+    'obl_rad2',
+    'obl_rad2_cv',
+    'owens_t',
+    'pbdv',
+    'pbvv',
+    'pbwa',
+    'pdtr',
+    'pdtrc',
+    'pdtri',
+    'pdtrik',
+    'poch',
+    'powm1',
+    'pro_ang1',
+    'pro_ang1_cv',
+    'pro_cv',
+    'pro_rad1',
+    'pro_rad1_cv',
+    'pro_rad2',
+    'pro_rad2_cv',
+    'pseudo_huber',
+    'psi',
+    'radian',
+    'rel_entr',
+    'rgamma',
+    'round',
+    'shichi',
+    'sici',
+    'sindg',
+    'smirnov',
+    'smirnovi',
+    'spence',
+    'sph_harm',
+    'stdtr',
+    'stdtridf',
+    'stdtrit',
+    'struve',
+    'tandg',
+    'tklmbda',
+    'voigt_profile',
+    'wofz',
+    'wright_bessel',
+    'wrightomega',
+    'xlog1py',
+    'xlogy',
+    'y0',
+    'y1',
+    'yn',
+    'yv',
+    'yve',
+    'zetac'
+]
+
+def geterr() -> dict[str, str]: ...
+def seterr(**kwargs: str) -> dict[str, str]: ...
+
+class errstate:
+    def __init__(self, **kargs: str) -> None: ...
+    def __enter__(self) -> None: ...
+    def __exit__(
+        self,
+        exc_type: Any,  # Unused
+        exc_value: Any,  # Unused
+        traceback: Any,  # Unused
+    ) -> None: ...
+
+_cosine_cdf: np.ufunc
+_cosine_invcdf: np.ufunc
+_cospi: np.ufunc
+_ellip_harm: np.ufunc
+_factorial: np.ufunc
+_igam_fac: np.ufunc
+_kolmogc: np.ufunc
+_kolmogci: np.ufunc
+_kolmogp: np.ufunc
+_lambertw: np.ufunc
+_lanczos_sum_expg_scaled: np.ufunc
+_lgam1p: np.ufunc
+_log1pmx: np.ufunc
+_riemann_zeta: np.ufunc
+_scaled_exp1: np.ufunc
+_sf_error_test_function: np.ufunc
+_sinpi: np.ufunc
+_smirnovc: np.ufunc
+_smirnovci: np.ufunc
+_smirnovp: np.ufunc
+_spherical_in: np.ufunc
+_spherical_in_d: np.ufunc
+_spherical_jn: np.ufunc
+_spherical_jn_d: np.ufunc
+_spherical_kn: np.ufunc
+_spherical_kn_d: np.ufunc
+_spherical_yn: np.ufunc
+_spherical_yn_d: np.ufunc
+_stirling2_inexact: np.ufunc
+_struve_asymp_large_z: np.ufunc
+_struve_bessel_series: np.ufunc
+_struve_power_series: np.ufunc
+_zeta: np.ufunc
+agm: np.ufunc
+airy: np.ufunc
+airye: np.ufunc
+bdtr: np.ufunc
+bdtrc: np.ufunc
+bdtri: np.ufunc
+bdtrik: np.ufunc
+bdtrin: np.ufunc
+bei: np.ufunc
+beip: np.ufunc
+ber: np.ufunc
+berp: np.ufunc
+besselpoly: np.ufunc
+beta: np.ufunc
+betainc: np.ufunc
+betaincc: np.ufunc
+betainccinv: np.ufunc
+betaincinv: np.ufunc
+betaln: np.ufunc
+binom: np.ufunc
+boxcox1p: np.ufunc
+boxcox: np.ufunc
+btdtria: np.ufunc
+btdtrib: np.ufunc
+cbrt: np.ufunc
+chdtr: np.ufunc
+chdtrc: np.ufunc
+chdtri: np.ufunc
+chdtriv: np.ufunc
+chndtr: np.ufunc
+chndtridf: np.ufunc
+chndtrinc: np.ufunc
+chndtrix: np.ufunc
+cosdg: np.ufunc
+cosm1: np.ufunc
+cotdg: np.ufunc
+dawsn: np.ufunc
+ellipe: np.ufunc
+ellipeinc: np.ufunc
+ellipj: np.ufunc
+ellipk: np.ufunc
+ellipkinc: np.ufunc
+ellipkm1: np.ufunc
+elliprc: np.ufunc
+elliprd: np.ufunc
+elliprf: np.ufunc
+elliprg: np.ufunc
+elliprj: np.ufunc
+entr: np.ufunc
+erf: np.ufunc
+erfc: np.ufunc
+erfcinv: np.ufunc
+erfcx: np.ufunc
+erfi: np.ufunc
+erfinv: np.ufunc
+eval_chebyc: np.ufunc
+eval_chebys: np.ufunc
+eval_chebyt: np.ufunc
+eval_chebyu: np.ufunc
+eval_gegenbauer: np.ufunc
+eval_genlaguerre: np.ufunc
+eval_hermite: np.ufunc
+eval_hermitenorm: np.ufunc
+eval_jacobi: np.ufunc
+eval_laguerre: np.ufunc
+eval_legendre: np.ufunc
+eval_sh_chebyt: np.ufunc
+eval_sh_chebyu: np.ufunc
+eval_sh_jacobi: np.ufunc
+eval_sh_legendre: np.ufunc
+exp10: np.ufunc
+exp1: np.ufunc
+exp2: np.ufunc
+expi: np.ufunc
+expit: np.ufunc
+expm1: np.ufunc
+expn: np.ufunc
+exprel: np.ufunc
+fdtr: np.ufunc
+fdtrc: np.ufunc
+fdtri: np.ufunc
+fdtridfd: np.ufunc
+fresnel: np.ufunc
+gamma: np.ufunc
+gammainc: np.ufunc
+gammaincc: np.ufunc
+gammainccinv: np.ufunc
+gammaincinv: np.ufunc
+gammaln: np.ufunc
+gammasgn: np.ufunc
+gdtr: np.ufunc
+gdtrc: np.ufunc
+gdtria: np.ufunc
+gdtrib: np.ufunc
+gdtrix: np.ufunc
+hankel1: np.ufunc
+hankel1e: np.ufunc
+hankel2: np.ufunc
+hankel2e: np.ufunc
+huber: np.ufunc
+hyp0f1: np.ufunc
+hyp1f1: np.ufunc
+hyp2f1: np.ufunc
+hyperu: np.ufunc
+i0: np.ufunc
+i0e: np.ufunc
+i1: np.ufunc
+i1e: np.ufunc
+inv_boxcox1p: np.ufunc
+inv_boxcox: np.ufunc
+it2i0k0: np.ufunc
+it2j0y0: np.ufunc
+it2struve0: np.ufunc
+itairy: np.ufunc
+iti0k0: np.ufunc
+itj0y0: np.ufunc
+itmodstruve0: np.ufunc
+itstruve0: np.ufunc
+iv: np.ufunc
+ive: np.ufunc
+j0: np.ufunc
+j1: np.ufunc
+jn: np.ufunc
+jv: np.ufunc
+jve: np.ufunc
+k0: np.ufunc
+k0e: np.ufunc
+k1: np.ufunc
+k1e: np.ufunc
+kei: np.ufunc
+keip: np.ufunc
+kelvin: np.ufunc
+ker: np.ufunc
+kerp: np.ufunc
+kl_div: np.ufunc
+kn: np.ufunc
+kolmogi: np.ufunc
+kolmogorov: np.ufunc
+kv: np.ufunc
+kve: np.ufunc
+log1p: np.ufunc
+log_expit: np.ufunc
+log_ndtr: np.ufunc
+log_wright_bessel: np.ufunc
+loggamma: np.ufunc
+logit: np.ufunc
+lpmv: np.ufunc
+mathieu_a: np.ufunc
+mathieu_b: np.ufunc
+mathieu_cem: np.ufunc
+mathieu_modcem1: np.ufunc
+mathieu_modcem2: np.ufunc
+mathieu_modsem1: np.ufunc
+mathieu_modsem2: np.ufunc
+mathieu_sem: np.ufunc
+modfresnelm: np.ufunc
+modfresnelp: np.ufunc
+modstruve: np.ufunc
+nbdtr: np.ufunc
+nbdtrc: np.ufunc
+nbdtri: np.ufunc
+nbdtrik: np.ufunc
+nbdtrin: np.ufunc
+ncfdtr: np.ufunc
+ncfdtri: np.ufunc
+ncfdtridfd: np.ufunc
+ncfdtridfn: np.ufunc
+ncfdtrinc: np.ufunc
+nctdtr: np.ufunc
+nctdtridf: np.ufunc
+nctdtrinc: np.ufunc
+nctdtrit: np.ufunc
+ndtr: np.ufunc
+ndtri: np.ufunc
+ndtri_exp: np.ufunc
+nrdtrimn: np.ufunc
+nrdtrisd: np.ufunc
+obl_ang1: np.ufunc
+obl_ang1_cv: np.ufunc
+obl_cv: np.ufunc
+obl_rad1: np.ufunc
+obl_rad1_cv: np.ufunc
+obl_rad2: np.ufunc
+obl_rad2_cv: np.ufunc
+owens_t: np.ufunc
+pbdv: np.ufunc
+pbvv: np.ufunc
+pbwa: np.ufunc
+pdtr: np.ufunc
+pdtrc: np.ufunc
+pdtri: np.ufunc
+pdtrik: np.ufunc
+poch: np.ufunc
+powm1: np.ufunc
+pro_ang1: np.ufunc
+pro_ang1_cv: np.ufunc
+pro_cv: np.ufunc
+pro_rad1: np.ufunc
+pro_rad1_cv: np.ufunc
+pro_rad2: np.ufunc
+pro_rad2_cv: np.ufunc
+pseudo_huber: np.ufunc
+psi: np.ufunc
+radian: np.ufunc
+rel_entr: np.ufunc
+rgamma: np.ufunc
+round: np.ufunc
+shichi: np.ufunc
+sici: np.ufunc
+sindg: np.ufunc
+smirnov: np.ufunc
+smirnovi: np.ufunc
+spence: np.ufunc
+sph_harm: np.ufunc
+stdtr: np.ufunc
+stdtridf: np.ufunc
+stdtrit: np.ufunc
+struve: np.ufunc
+tandg: np.ufunc
+tklmbda: np.ufunc
+voigt_profile: np.ufunc
+wofz: np.ufunc
+wright_bessel: np.ufunc
+wrightomega: np.ufunc
+xlog1py: np.ufunc
+xlogy: np.ufunc
+y0: np.ufunc
+y1: np.ufunc
+yn: np.ufunc
+yv: np.ufunc
+yve: np.ufunc
+zetac: np.ufunc
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..5f9afc828a16d598b3ba76582111cd964cfe764a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs.pyx
@@ -0,0 +1,14358 @@
+# This file is automatically generated by _generate_pyx.py.
+# Do not edit manually!
+
+from libc.math cimport NAN
+
+include "_ufuncs_extra_code_common.pxi"
+include "_ufuncs_extra_code.pxi"
+__all__ = ['agm', 'bdtr', 'bdtrc', 'bdtri', 'bdtrik', 'bdtrin', 'betainc', 'betaincc', 'betainccinv', 'betaincinv', 'boxcox', 'boxcox1p', 'btdtria', 'btdtrib', 'chdtr', 'chdtrc', 'chdtri', 'chdtriv', 'chndtr', 'chndtridf', 'chndtrinc', 'chndtrix', 'dawsn', 'elliprc', 'elliprd', 'elliprf', 'elliprg', 'elliprj', 'entr', 'erf', 'erfc', 'erfcinv', 'erfcx', 'erfi', 'erfinv', 'eval_chebyc', 'eval_chebys', 'eval_chebyt', 'eval_chebyu', 'eval_gegenbauer', 'eval_genlaguerre', 'eval_hermite', 'eval_hermitenorm', 'eval_jacobi', 'eval_laguerre', 'eval_legendre', 'eval_sh_chebyt', 'eval_sh_chebyu', 'eval_sh_jacobi', 'eval_sh_legendre', 'exp10', 'exp2', 'expm1', 'expn', 'fdtr', 'fdtrc', 'fdtri', 'fdtridfd', 'gdtr', 'gdtrc', 'gdtria', 'gdtrib', 'gdtrix', 'huber', 'hyp0f1', 'hyp1f1', 'hyperu', 'inv_boxcox', 'inv_boxcox1p', 'kl_div', 'kn', 'kolmogi', 'kolmogorov', 'log1p', 'log_ndtr', 'lpmv', 'nbdtr', 'nbdtrc', 'nbdtri', 'nbdtrik', 'nbdtrin', 'ncfdtr', 'ncfdtri', 'ncfdtridfd', 'ncfdtridfn', 'ncfdtrinc', 'nctdtr', 'nctdtridf', 'nctdtrinc', 'nctdtrit', 'ndtr', 'ndtri', 'ndtri_exp', 'nrdtrimn', 'nrdtrisd', 'owens_t', 'pdtr', 'pdtrc', 'pdtri', 'pdtrik', 'poch', 'powm1', 'pseudo_huber', 'rel_entr', 'round', 'shichi', 'sici', 'smirnov', 'smirnovi', 'spence', 'stdtr', 'stdtridf', 'stdtrit', 'tklmbda', 'voigt_profile', 'wofz', 'wrightomega', 'xlog1py', 'xlogy', 'yn', 'geterr', 'seterr', 'errstate', 'jn', 'airy', 'airye', 'bei', 'beip', 'ber', 'berp', 'binom', 'exp1', 'expi', 'expit', 'exprel', 'gamma', 'gammaln', 'hankel1', 'hankel1e', 'hankel2', 'hankel2e', 'hyp2f1', 'it2i0k0', 'it2j0y0', 'it2struve0', 'itairy', 'iti0k0', 'itj0y0', 'itmodstruve0', 'itstruve0', 'iv', 'ive', 'jv', 'jve', 'kei', 'keip', 'kelvin', 'ker', 'kerp', 'kv', 'kve', 'log_expit', 'log_wright_bessel', 'loggamma', 'logit', 'mathieu_a', 'mathieu_b', 'mathieu_cem', 'mathieu_modcem1', 'mathieu_modcem2', 'mathieu_modsem1', 'mathieu_modsem2', 'mathieu_sem', 'modfresnelm', 'modfresnelp', 'obl_ang1', 'obl_ang1_cv', 'obl_cv', 'obl_rad1', 'obl_rad1_cv', 'obl_rad2', 'obl_rad2_cv', 'pbdv', 'pbvv', 'pbwa', 'pro_ang1', 'pro_ang1_cv', 'pro_cv', 'pro_rad1', 'pro_rad1_cv', 'pro_rad2', 'pro_rad2_cv', 'psi', 'rgamma', 'sph_harm', 'wright_bessel', 'yv', 'yve', 'zetac', 'sindg', 'cosdg', 'tandg', 'cotdg', 'i0', 'i0e', 'i1', 'i1e', 'k0', 'k0e', 'k1', 'k1e', 'y0', 'y1', 'j0', 'j1', 'struve', 'modstruve', 'beta', 'betaln', 'besselpoly', 'gammaln', 'gammasgn', 'cbrt', 'radian', 'cosm1', 'gammainc', 'gammaincinv', 'gammaincc', 'gammainccinv', 'fresnel', 'ellipe', 'ellipeinc', 'ellipk', 'ellipkinc', 'ellipkm1', 'ellipj']
+cdef void loop_D_DDDD__As_DDDD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DDDD__As_FFFF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DDD__As_DDD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DDD__As_FFF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DD__As_DD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_DD__As_FF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_D__As_D_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_D__As_F_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dD__As_dD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dD__As_fF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_ddD__As_ddD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_ddD__As_ffF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dddD__As_dddD_D(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_D_dddD__As_fffF_F(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double complex ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_d__As_d_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_d__As_f_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dd__As_dd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dd__As_ff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddd__As_ddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddd__As_fff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dddd__As_dddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dddd__As_ffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddddddd__As_ddddddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *ip4 = args[4]
+    cdef char *ip5 = args[5]
+    cdef char *ip6 = args[6]
+    cdef char *op0 = args[7]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        ip4 += steps[4]
+        ip5 += steps[5]
+        ip6 += steps[6]
+        op0 += steps[7]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddddddd__As_fffffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *ip4 = args[4]
+    cdef char *ip5 = args[5]
+    cdef char *ip6 = args[6]
+    cdef char *op0 = args[7]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        ip4 += steps[4]
+        ip5 += steps[5]
+        ip6 += steps[6]
+        op0 += steps[7]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddiiddd__As_ddllddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *ip4 = args[4]
+    cdef char *ip5 = args[5]
+    cdef char *ip6 = args[6]
+    cdef char *op0 = args[7]
+    cdef double ov0
+    for i in range(n):
+        if (ip2)[0] == (ip2)[0] and (ip3)[0] == (ip3)[0]:
+            ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0], (ip4)[0], (ip5)[0], (ip6)[0])
+        else:
+            sf_error.error(func_name, sf_error.DOMAIN, "invalid input argument")
+            ov0 = NAN
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        ip4 += steps[4]
+        ip5 += steps[5]
+        ip6 += steps[6]
+        op0 += steps[7]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ddp_d_As_ddp_dd(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef char *op1 = args[4]
+    cdef double ov0
+    cdef double ov1
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+        op1 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_dpd__As_dpd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_pd__As_pd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_pdd__As_pdd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_pddd__As_pddd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_d_ppd__As_ppd_d(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef double ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_f__As_f_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_ff__As_ff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *op0 = args[2]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        op0 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_fff__As_fff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *op0 = args[3]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        op0 += steps[3]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_f_ffff__As_ffff_f(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *ip1 = args[1]
+    cdef char *ip2 = args[2]
+    cdef char *ip3 = args[3]
+    cdef char *op0 = args[4]
+    cdef float ov0
+    for i in range(n):
+        ov0 = (func)((ip0)[0], (ip1)[0], (ip2)[0], (ip3)[0])
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        ip1 += steps[1]
+        ip2 += steps[2]
+        ip3 += steps[3]
+        op0 += steps[4]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_D_DD_As_D_DD(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double complex ov0
+    cdef double complex ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_D_DD_As_F_FF(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double complex ov0
+    cdef double complex ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_d_dd_As_d_dd(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double ov0
+    cdef double ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_d_dd_As_f_ff(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef char *op1 = args[2]
+    cdef double ov0
+    cdef double ov1
+    for i in range(n):
+        (func)((ip0)[0], &ov0, &ov1)
+        (op0)[0] = ov0
+        (op1)[0] = ov1
+        ip0 += steps[0]
+        op0 += steps[1]
+        op1 += steps[2]
+    sf_error.check_fpe(func_name)
+
+cdef void loop_i_i__As_l_l(char **args, np.npy_intp *dims, np.npy_intp *steps, void *data) noexcept nogil:
+    cdef np.npy_intp i, n = dims[0]
+    cdef void *func = (data)[0]
+    cdef char *func_name = (data)[1]
+    cdef char *ip0 = args[0]
+    cdef char *op0 = args[1]
+    cdef int ov0
+    for i in range(n):
+        if (ip0)[0] == (ip0)[0]:
+            ov0 = (func)((ip0)[0])
+        else:
+            sf_error.error(func_name, sf_error.DOMAIN, "invalid input argument")
+            ov0 = 0xbad0bad0
+        (op0)[0] = ov0
+        ip0 += steps[0]
+        op0 += steps[1]
+    sf_error.check_fpe(func_name)
+
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cosine_cdf "cosine_cdf"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cosine_invcdf "cosine_invcdf"(double) noexcept nogil
+from ._ellip_harm cimport ellip_harmonic as _func_ellip_harmonic
+ctypedef double _proto_ellip_harmonic_t(double, double, int, int, double, double, double) noexcept nogil
+cdef _proto_ellip_harmonic_t *_proto_ellip_harmonic_t_var = &_func_ellip_harmonic
+from ._legacy cimport ellip_harmonic_unsafe as _func_ellip_harmonic_unsafe
+ctypedef double _proto_ellip_harmonic_unsafe_t(double, double, double, double, double, double, double) noexcept nogil
+cdef _proto_ellip_harmonic_unsafe_t *_proto_ellip_harmonic_unsafe_t_var = &_func_ellip_harmonic_unsafe
+from ._factorial cimport _factorial as _func__factorial
+ctypedef double _proto__factorial_t(double) noexcept nogil
+cdef _proto__factorial_t *_proto__factorial_t_var = &_func__factorial
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_igam_fac "cephes_igam_fac"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogc "xsf_kolmogc"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogci "xsf_kolmogci"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogp "xsf_kolmogp"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_lanczos_sum_expg_scaled "cephes_lanczos_sum_expg_scaled"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_lgam1p "cephes_lgam1p"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_log1pmx "cephes_log1pmx"(double) noexcept nogil
+from .sf_error cimport _sf_error_test_function as _func__sf_error_test_function
+ctypedef int _proto__sf_error_test_function_t(int) noexcept nogil
+cdef _proto__sf_error_test_function_t *_proto__sf_error_test_function_t_var = &_func__sf_error_test_function
+from ._legacy cimport smirnovc_unsafe as _func_smirnovc_unsafe
+ctypedef double _proto_smirnovc_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovc_unsafe_t *_proto_smirnovc_unsafe_t_var = &_func_smirnovc_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovc_wrap "cephes_smirnovc_wrap"(Py_ssize_t, double) noexcept nogil
+from ._legacy cimport smirnovci_unsafe as _func_smirnovci_unsafe
+ctypedef double _proto_smirnovci_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovci_unsafe_t *_proto_smirnovci_unsafe_t_var = &_func_smirnovci_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovci_wrap "cephes_smirnovci_wrap"(Py_ssize_t, double) noexcept nogil
+from ._legacy cimport smirnovp_unsafe as _func_smirnovp_unsafe
+ctypedef double _proto_smirnovp_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovp_unsafe_t *_proto_smirnovp_unsafe_t_var = &_func_smirnovp_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovp_wrap "cephes_smirnovp_wrap"(Py_ssize_t, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes__struve_asymp_large_z "cephes__struve_asymp_large_z"(double, double, Py_ssize_t, double *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes__struve_bessel_series "cephes__struve_bessel_series"(double, double, Py_ssize_t, double *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes__struve_power_series "cephes__struve_power_series"(double, double, Py_ssize_t, double *) noexcept nogil
+from ._agm cimport agm as _func_agm
+ctypedef double _proto_agm_t(double, double) noexcept nogil
+cdef _proto_agm_t *_proto_agm_t_var = &_func_agm
+from ._legacy cimport bdtr_unsafe as _func_bdtr_unsafe
+ctypedef double _proto_bdtr_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_bdtr_unsafe_t *_proto_bdtr_unsafe_t_var = &_func_bdtr_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_bdtr_wrap "cephes_bdtr_wrap"(double, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport bdtrc_unsafe as _func_bdtrc_unsafe
+ctypedef double _proto_bdtrc_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_bdtrc_unsafe_t *_proto_bdtrc_unsafe_t_var = &_func_bdtrc_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_bdtrc_wrap "cephes_bdtrc_wrap"(double, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport bdtri_unsafe as _func_bdtri_unsafe
+ctypedef double _proto_bdtri_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_bdtri_unsafe_t *_proto_bdtri_unsafe_t_var = &_func_bdtri_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_bdtri_wrap "cephes_bdtri_wrap"(double, Py_ssize_t, double) noexcept nogil
+from ._cdflib_wrappers cimport bdtrik as _func_bdtrik
+ctypedef double _proto_bdtrik_t(double, double, double) noexcept nogil
+cdef _proto_bdtrik_t *_proto_bdtrik_t_var = &_func_bdtrik
+from ._cdflib_wrappers cimport bdtrin as _func_bdtrin
+ctypedef double _proto_bdtrin_t(double, double, double) noexcept nogil
+cdef _proto_bdtrin_t *_proto_bdtrin_t_var = &_func_bdtrin
+from ._boxcox cimport boxcox as _func_boxcox
+ctypedef double _proto_boxcox_t(double, double) noexcept nogil
+cdef _proto_boxcox_t *_proto_boxcox_t_var = &_func_boxcox
+from ._boxcox cimport boxcox1p as _func_boxcox1p
+ctypedef double _proto_boxcox1p_t(double, double) noexcept nogil
+cdef _proto_boxcox1p_t *_proto_boxcox1p_t_var = &_func_boxcox1p
+from ._cdflib_wrappers cimport btdtria as _func_btdtria
+ctypedef double _proto_btdtria_t(double, double, double) noexcept nogil
+cdef _proto_btdtria_t *_proto_btdtria_t_var = &_func_btdtria
+from ._cdflib_wrappers cimport btdtrib as _func_btdtrib
+ctypedef double _proto_btdtrib_t(double, double, double) noexcept nogil
+cdef _proto_btdtrib_t *_proto_btdtrib_t_var = &_func_btdtrib
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_chdtr "xsf_chdtr"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_chdtrc "xsf_chdtrc"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_chdtri "xsf_chdtri"(double, double) noexcept nogil
+from ._cdflib_wrappers cimport chdtriv as _func_chdtriv
+ctypedef double _proto_chdtriv_t(double, double) noexcept nogil
+cdef _proto_chdtriv_t *_proto_chdtriv_t_var = &_func_chdtriv
+from ._cdflib_wrappers cimport chndtr as _func_chndtr
+ctypedef double _proto_chndtr_t(double, double, double) noexcept nogil
+cdef _proto_chndtr_t *_proto_chndtr_t_var = &_func_chndtr
+from ._cdflib_wrappers cimport chndtridf as _func_chndtridf
+ctypedef double _proto_chndtridf_t(double, double, double) noexcept nogil
+cdef _proto_chndtridf_t *_proto_chndtridf_t_var = &_func_chndtridf
+from ._cdflib_wrappers cimport chndtrinc as _func_chndtrinc
+ctypedef double _proto_chndtrinc_t(double, double, double) noexcept nogil
+cdef _proto_chndtrinc_t *_proto_chndtrinc_t_var = &_func_chndtrinc
+from ._cdflib_wrappers cimport chndtrix as _func_chndtrix
+ctypedef double _proto_chndtrix_t(double, double, double) noexcept nogil
+cdef _proto_chndtrix_t *_proto_chndtrix_t_var = &_func_chndtrix
+from ._convex_analysis cimport entr as _func_entr
+ctypedef double _proto_entr_t(double) noexcept nogil
+cdef _proto_entr_t *_proto_entr_t_var = &_func_entr
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_erf "cephes_erf"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_erfc "cephes_erfc"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_erfcinv "cephes_erfcinv"(double) noexcept nogil
+from .orthogonal_eval cimport eval_chebyc as _func_eval_chebyc
+ctypedef double complex _proto_eval_chebyc_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebyc_double_complex__t *_proto_eval_chebyc_double_complex__t_var = &_func_eval_chebyc[double_complex]
+from .orthogonal_eval cimport eval_chebyc as _func_eval_chebyc
+ctypedef double _proto_eval_chebyc_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebyc_double__t *_proto_eval_chebyc_double__t_var = &_func_eval_chebyc[double]
+from .orthogonal_eval cimport eval_chebyc_l as _func_eval_chebyc_l
+ctypedef double _proto_eval_chebyc_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebyc_l_t *_proto_eval_chebyc_l_t_var = &_func_eval_chebyc_l
+from .orthogonal_eval cimport eval_chebys as _func_eval_chebys
+ctypedef double complex _proto_eval_chebys_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebys_double_complex__t *_proto_eval_chebys_double_complex__t_var = &_func_eval_chebys[double_complex]
+from .orthogonal_eval cimport eval_chebys as _func_eval_chebys
+ctypedef double _proto_eval_chebys_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebys_double__t *_proto_eval_chebys_double__t_var = &_func_eval_chebys[double]
+from .orthogonal_eval cimport eval_chebys_l as _func_eval_chebys_l
+ctypedef double _proto_eval_chebys_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebys_l_t *_proto_eval_chebys_l_t_var = &_func_eval_chebys_l
+from .orthogonal_eval cimport eval_chebyt as _func_eval_chebyt
+ctypedef double complex _proto_eval_chebyt_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebyt_double_complex__t *_proto_eval_chebyt_double_complex__t_var = &_func_eval_chebyt[double_complex]
+from .orthogonal_eval cimport eval_chebyt as _func_eval_chebyt
+ctypedef double _proto_eval_chebyt_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebyt_double__t *_proto_eval_chebyt_double__t_var = &_func_eval_chebyt[double]
+from .orthogonal_eval cimport eval_chebyt_l as _func_eval_chebyt_l
+ctypedef double _proto_eval_chebyt_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebyt_l_t *_proto_eval_chebyt_l_t_var = &_func_eval_chebyt_l
+from .orthogonal_eval cimport eval_chebyu as _func_eval_chebyu
+ctypedef double complex _proto_eval_chebyu_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_chebyu_double_complex__t *_proto_eval_chebyu_double_complex__t_var = &_func_eval_chebyu[double_complex]
+from .orthogonal_eval cimport eval_chebyu as _func_eval_chebyu
+ctypedef double _proto_eval_chebyu_double__t(double, double) noexcept nogil
+cdef _proto_eval_chebyu_double__t *_proto_eval_chebyu_double__t_var = &_func_eval_chebyu[double]
+from .orthogonal_eval cimport eval_chebyu_l as _func_eval_chebyu_l
+ctypedef double _proto_eval_chebyu_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_chebyu_l_t *_proto_eval_chebyu_l_t_var = &_func_eval_chebyu_l
+from .orthogonal_eval cimport eval_gegenbauer as _func_eval_gegenbauer
+ctypedef double complex _proto_eval_gegenbauer_double_complex__t(double, double, double complex) noexcept nogil
+cdef _proto_eval_gegenbauer_double_complex__t *_proto_eval_gegenbauer_double_complex__t_var = &_func_eval_gegenbauer[double_complex]
+from .orthogonal_eval cimport eval_gegenbauer as _func_eval_gegenbauer
+ctypedef double _proto_eval_gegenbauer_double__t(double, double, double) noexcept nogil
+cdef _proto_eval_gegenbauer_double__t *_proto_eval_gegenbauer_double__t_var = &_func_eval_gegenbauer[double]
+from .orthogonal_eval cimport eval_gegenbauer_l as _func_eval_gegenbauer_l
+ctypedef double _proto_eval_gegenbauer_l_t(Py_ssize_t, double, double) noexcept nogil
+cdef _proto_eval_gegenbauer_l_t *_proto_eval_gegenbauer_l_t_var = &_func_eval_gegenbauer_l
+from .orthogonal_eval cimport eval_genlaguerre as _func_eval_genlaguerre
+ctypedef double complex _proto_eval_genlaguerre_double_complex__t(double, double, double complex) noexcept nogil
+cdef _proto_eval_genlaguerre_double_complex__t *_proto_eval_genlaguerre_double_complex__t_var = &_func_eval_genlaguerre[double_complex]
+from .orthogonal_eval cimport eval_genlaguerre as _func_eval_genlaguerre
+ctypedef double _proto_eval_genlaguerre_double__t(double, double, double) noexcept nogil
+cdef _proto_eval_genlaguerre_double__t *_proto_eval_genlaguerre_double__t_var = &_func_eval_genlaguerre[double]
+from .orthogonal_eval cimport eval_genlaguerre_l as _func_eval_genlaguerre_l
+ctypedef double _proto_eval_genlaguerre_l_t(Py_ssize_t, double, double) noexcept nogil
+cdef _proto_eval_genlaguerre_l_t *_proto_eval_genlaguerre_l_t_var = &_func_eval_genlaguerre_l
+from .orthogonal_eval cimport eval_hermite as _func_eval_hermite
+ctypedef double _proto_eval_hermite_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_hermite_t *_proto_eval_hermite_t_var = &_func_eval_hermite
+from .orthogonal_eval cimport eval_hermitenorm as _func_eval_hermitenorm
+ctypedef double _proto_eval_hermitenorm_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_hermitenorm_t *_proto_eval_hermitenorm_t_var = &_func_eval_hermitenorm
+from .orthogonal_eval cimport eval_jacobi as _func_eval_jacobi
+ctypedef double complex _proto_eval_jacobi_double_complex__t(double, double, double, double complex) noexcept nogil
+cdef _proto_eval_jacobi_double_complex__t *_proto_eval_jacobi_double_complex__t_var = &_func_eval_jacobi[double_complex]
+from .orthogonal_eval cimport eval_jacobi as _func_eval_jacobi
+ctypedef double _proto_eval_jacobi_double__t(double, double, double, double) noexcept nogil
+cdef _proto_eval_jacobi_double__t *_proto_eval_jacobi_double__t_var = &_func_eval_jacobi[double]
+from .orthogonal_eval cimport eval_jacobi_l as _func_eval_jacobi_l
+ctypedef double _proto_eval_jacobi_l_t(Py_ssize_t, double, double, double) noexcept nogil
+cdef _proto_eval_jacobi_l_t *_proto_eval_jacobi_l_t_var = &_func_eval_jacobi_l
+from .orthogonal_eval cimport eval_laguerre as _func_eval_laguerre
+ctypedef double complex _proto_eval_laguerre_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_laguerre_double_complex__t *_proto_eval_laguerre_double_complex__t_var = &_func_eval_laguerre[double_complex]
+from .orthogonal_eval cimport eval_laguerre as _func_eval_laguerre
+ctypedef double _proto_eval_laguerre_double__t(double, double) noexcept nogil
+cdef _proto_eval_laguerre_double__t *_proto_eval_laguerre_double__t_var = &_func_eval_laguerre[double]
+from .orthogonal_eval cimport eval_laguerre_l as _func_eval_laguerre_l
+ctypedef double _proto_eval_laguerre_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_laguerre_l_t *_proto_eval_laguerre_l_t_var = &_func_eval_laguerre_l
+from .orthogonal_eval cimport eval_legendre as _func_eval_legendre
+ctypedef double complex _proto_eval_legendre_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_legendre_double_complex__t *_proto_eval_legendre_double_complex__t_var = &_func_eval_legendre[double_complex]
+from .orthogonal_eval cimport eval_legendre as _func_eval_legendre
+ctypedef double _proto_eval_legendre_double__t(double, double) noexcept nogil
+cdef _proto_eval_legendre_double__t *_proto_eval_legendre_double__t_var = &_func_eval_legendre[double]
+from .orthogonal_eval cimport eval_legendre_l as _func_eval_legendre_l
+ctypedef double _proto_eval_legendre_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_legendre_l_t *_proto_eval_legendre_l_t_var = &_func_eval_legendre_l
+from .orthogonal_eval cimport eval_sh_chebyt as _func_eval_sh_chebyt
+ctypedef double complex _proto_eval_sh_chebyt_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_sh_chebyt_double_complex__t *_proto_eval_sh_chebyt_double_complex__t_var = &_func_eval_sh_chebyt[double_complex]
+from .orthogonal_eval cimport eval_sh_chebyt as _func_eval_sh_chebyt
+ctypedef double _proto_eval_sh_chebyt_double__t(double, double) noexcept nogil
+cdef _proto_eval_sh_chebyt_double__t *_proto_eval_sh_chebyt_double__t_var = &_func_eval_sh_chebyt[double]
+from .orthogonal_eval cimport eval_sh_chebyt_l as _func_eval_sh_chebyt_l
+ctypedef double _proto_eval_sh_chebyt_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_sh_chebyt_l_t *_proto_eval_sh_chebyt_l_t_var = &_func_eval_sh_chebyt_l
+from .orthogonal_eval cimport eval_sh_chebyu as _func_eval_sh_chebyu
+ctypedef double complex _proto_eval_sh_chebyu_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_sh_chebyu_double_complex__t *_proto_eval_sh_chebyu_double_complex__t_var = &_func_eval_sh_chebyu[double_complex]
+from .orthogonal_eval cimport eval_sh_chebyu as _func_eval_sh_chebyu
+ctypedef double _proto_eval_sh_chebyu_double__t(double, double) noexcept nogil
+cdef _proto_eval_sh_chebyu_double__t *_proto_eval_sh_chebyu_double__t_var = &_func_eval_sh_chebyu[double]
+from .orthogonal_eval cimport eval_sh_chebyu_l as _func_eval_sh_chebyu_l
+ctypedef double _proto_eval_sh_chebyu_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_sh_chebyu_l_t *_proto_eval_sh_chebyu_l_t_var = &_func_eval_sh_chebyu_l
+from .orthogonal_eval cimport eval_sh_jacobi as _func_eval_sh_jacobi
+ctypedef double complex _proto_eval_sh_jacobi_double_complex__t(double, double, double, double complex) noexcept nogil
+cdef _proto_eval_sh_jacobi_double_complex__t *_proto_eval_sh_jacobi_double_complex__t_var = &_func_eval_sh_jacobi[double_complex]
+from .orthogonal_eval cimport eval_sh_jacobi as _func_eval_sh_jacobi
+ctypedef double _proto_eval_sh_jacobi_double__t(double, double, double, double) noexcept nogil
+cdef _proto_eval_sh_jacobi_double__t *_proto_eval_sh_jacobi_double__t_var = &_func_eval_sh_jacobi[double]
+from .orthogonal_eval cimport eval_sh_jacobi_l as _func_eval_sh_jacobi_l
+ctypedef double _proto_eval_sh_jacobi_l_t(Py_ssize_t, double, double, double) noexcept nogil
+cdef _proto_eval_sh_jacobi_l_t *_proto_eval_sh_jacobi_l_t_var = &_func_eval_sh_jacobi_l
+from .orthogonal_eval cimport eval_sh_legendre as _func_eval_sh_legendre
+ctypedef double complex _proto_eval_sh_legendre_double_complex__t(double, double complex) noexcept nogil
+cdef _proto_eval_sh_legendre_double_complex__t *_proto_eval_sh_legendre_double_complex__t_var = &_func_eval_sh_legendre[double_complex]
+from .orthogonal_eval cimport eval_sh_legendre as _func_eval_sh_legendre
+ctypedef double _proto_eval_sh_legendre_double__t(double, double) noexcept nogil
+cdef _proto_eval_sh_legendre_double__t *_proto_eval_sh_legendre_double__t_var = &_func_eval_sh_legendre[double]
+from .orthogonal_eval cimport eval_sh_legendre_l as _func_eval_sh_legendre_l
+ctypedef double _proto_eval_sh_legendre_l_t(Py_ssize_t, double) noexcept nogil
+cdef _proto_eval_sh_legendre_l_t *_proto_eval_sh_legendre_l_t_var = &_func_eval_sh_legendre_l
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_exp10 "cephes_exp10"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_exp2 "cephes_exp2"(double) noexcept nogil
+from ._cunity cimport cexpm1 as _func_cexpm1
+ctypedef double complex _proto_cexpm1_t(double complex) noexcept nogil
+cdef _proto_cexpm1_t *_proto_cexpm1_t_var = &_func_cexpm1
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_expm1 "cephes_expm1"(double) noexcept nogil
+from ._legacy cimport expn_unsafe as _func_expn_unsafe
+ctypedef double _proto_expn_unsafe_t(double, double) noexcept nogil
+cdef _proto_expn_unsafe_t *_proto_expn_unsafe_t_var = &_func_expn_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_expn_wrap "cephes_expn_wrap"(Py_ssize_t, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_fdtr "xsf_fdtr"(double, double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_fdtrc "xsf_fdtrc"(double, double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_fdtri "xsf_fdtri"(double, double, double) noexcept nogil
+from ._cdflib_wrappers cimport fdtridfd as _func_fdtridfd
+ctypedef double _proto_fdtridfd_t(double, double, double) noexcept nogil
+cdef _proto_fdtridfd_t *_proto_fdtridfd_t_var = &_func_fdtridfd
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_gdtr "xsf_gdtr"(double, double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_gdtrc "xsf_gdtrc"(double, double, double) noexcept nogil
+from ._cdflib_wrappers cimport gdtria as _func_gdtria
+ctypedef double _proto_gdtria_t(double, double, double) noexcept nogil
+cdef _proto_gdtria_t *_proto_gdtria_t_var = &_func_gdtria
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_gdtrib "xsf_gdtrib"(double, double, double) noexcept nogil
+from ._cdflib_wrappers cimport gdtrix as _func_gdtrix
+ctypedef double _proto_gdtrix_t(double, double, double) noexcept nogil
+cdef _proto_gdtrix_t *_proto_gdtrix_t_var = &_func_gdtrix
+from ._convex_analysis cimport huber as _func_huber
+ctypedef double _proto_huber_t(double, double) noexcept nogil
+cdef _proto_huber_t *_proto_huber_t_var = &_func_huber
+from ._hyp0f1 cimport _hyp0f1_cmplx as _func__hyp0f1_cmplx
+ctypedef double complex _proto__hyp0f1_cmplx_t(double, double complex) noexcept nogil
+cdef _proto__hyp0f1_cmplx_t *_proto__hyp0f1_cmplx_t_var = &_func__hyp0f1_cmplx
+from ._hyp0f1 cimport _hyp0f1_real as _func__hyp0f1_real
+ctypedef double _proto__hyp0f1_real_t(double, double) noexcept nogil
+cdef _proto__hyp0f1_real_t *_proto__hyp0f1_real_t_var = &_func__hyp0f1_real
+cdef extern from r"_ufuncs_defs.h":
+    cdef double complex _func_chyp1f1_wrap "chyp1f1_wrap"(double, double, double complex) noexcept nogil
+from ._hypergeometric cimport hyperu as _func_hyperu
+ctypedef double _proto_hyperu_t(double, double, double) noexcept nogil
+cdef _proto_hyperu_t *_proto_hyperu_t_var = &_func_hyperu
+from ._boxcox cimport inv_boxcox as _func_inv_boxcox
+ctypedef double _proto_inv_boxcox_t(double, double) noexcept nogil
+cdef _proto_inv_boxcox_t *_proto_inv_boxcox_t_var = &_func_inv_boxcox
+from ._boxcox cimport inv_boxcox1p as _func_inv_boxcox1p
+ctypedef double _proto_inv_boxcox1p_t(double, double) noexcept nogil
+cdef _proto_inv_boxcox1p_t *_proto_inv_boxcox1p_t_var = &_func_inv_boxcox1p
+from ._convex_analysis cimport kl_div as _func_kl_div
+ctypedef double _proto_kl_div_t(double, double) noexcept nogil
+cdef _proto_kl_div_t *_proto_kl_div_t_var = &_func_kl_div
+from ._legacy cimport kn_unsafe as _func_kn_unsafe
+ctypedef double _proto_kn_unsafe_t(double, double) noexcept nogil
+cdef _proto_kn_unsafe_t *_proto_kn_unsafe_t_var = &_func_kn_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_special_cyl_bessel_k_int "special_cyl_bessel_k_int"(Py_ssize_t, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogi "xsf_kolmogi"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_kolmogorov "xsf_kolmogorov"(double) noexcept nogil
+from ._cunity cimport clog1p as _func_clog1p
+ctypedef double complex _proto_clog1p_t(double complex) noexcept nogil
+cdef _proto_clog1p_t *_proto_clog1p_t_var = &_func_clog1p
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_log1p "cephes_log1p"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_pmv_wrap "pmv_wrap"(double, double, double) noexcept nogil
+from ._legacy cimport nbdtr_unsafe as _func_nbdtr_unsafe
+ctypedef double _proto_nbdtr_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_nbdtr_unsafe_t *_proto_nbdtr_unsafe_t_var = &_func_nbdtr_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_nbdtr_wrap "cephes_nbdtr_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport nbdtrc_unsafe as _func_nbdtrc_unsafe
+ctypedef double _proto_nbdtrc_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_nbdtrc_unsafe_t *_proto_nbdtrc_unsafe_t_var = &_func_nbdtrc_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_nbdtrc_wrap "cephes_nbdtrc_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil
+from ._legacy cimport nbdtri_unsafe as _func_nbdtri_unsafe
+ctypedef double _proto_nbdtri_unsafe_t(double, double, double) noexcept nogil
+cdef _proto_nbdtri_unsafe_t *_proto_nbdtri_unsafe_t_var = &_func_nbdtri_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_nbdtri_wrap "cephes_nbdtri_wrap"(Py_ssize_t, Py_ssize_t, double) noexcept nogil
+from ._cdflib_wrappers cimport nbdtrik as _func_nbdtrik
+ctypedef double _proto_nbdtrik_t(double, double, double) noexcept nogil
+cdef _proto_nbdtrik_t *_proto_nbdtrik_t_var = &_func_nbdtrik
+from ._cdflib_wrappers cimport nbdtrin as _func_nbdtrin
+ctypedef double _proto_nbdtrin_t(double, double, double) noexcept nogil
+cdef _proto_nbdtrin_t *_proto_nbdtrin_t_var = &_func_nbdtrin
+from ._cdflib_wrappers cimport ncfdtridfd as _func_ncfdtridfd
+ctypedef double _proto_ncfdtridfd_t(double, double, double, double) noexcept nogil
+cdef _proto_ncfdtridfd_t *_proto_ncfdtridfd_t_var = &_func_ncfdtridfd
+from ._cdflib_wrappers cimport ncfdtridfn as _func_ncfdtridfn
+ctypedef double _proto_ncfdtridfn_t(double, double, double, double) noexcept nogil
+cdef _proto_ncfdtridfn_t *_proto_ncfdtridfn_t_var = &_func_ncfdtridfn
+from ._cdflib_wrappers cimport ncfdtrinc as _func_ncfdtrinc
+ctypedef double _proto_ncfdtrinc_t(double, double, double, double) noexcept nogil
+cdef _proto_ncfdtrinc_t *_proto_ncfdtrinc_t_var = &_func_ncfdtrinc
+from ._cdflib_wrappers cimport nctdtridf as _func_nctdtridf
+ctypedef double _proto_nctdtridf_t(double, double, double) noexcept nogil
+cdef _proto_nctdtridf_t *_proto_nctdtridf_t_var = &_func_nctdtridf
+from ._cdflib_wrappers cimport nctdtrinc as _func_nctdtrinc
+ctypedef double _proto_nctdtrinc_t(double, double, double) noexcept nogil
+cdef _proto_nctdtrinc_t *_proto_nctdtrinc_t_var = &_func_nctdtrinc
+from ._cdflib_wrappers cimport nctdtrit as _func_nctdtrit
+ctypedef double _proto_nctdtrit_t(double, double, double) noexcept nogil
+cdef _proto_nctdtrit_t *_proto_nctdtrit_t_var = &_func_nctdtrit
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_ndtr "xsf_ndtr"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_ndtri "xsf_ndtri"(double) noexcept nogil
+from ._ndtri_exp cimport ndtri_exp as _func_ndtri_exp
+ctypedef double _proto_ndtri_exp_t(double) noexcept nogil
+cdef _proto_ndtri_exp_t *_proto_ndtri_exp_t_var = &_func_ndtri_exp
+from ._cdflib_wrappers cimport nrdtrimn as _func_nrdtrimn
+ctypedef double _proto_nrdtrimn_t(double, double, double) noexcept nogil
+cdef _proto_nrdtrimn_t *_proto_nrdtrimn_t_var = &_func_nrdtrimn
+from ._cdflib_wrappers cimport nrdtrisd as _func_nrdtrisd
+ctypedef double _proto_nrdtrisd_t(double, double, double) noexcept nogil
+cdef _proto_nrdtrisd_t *_proto_nrdtrisd_t_var = &_func_nrdtrisd
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_owens_t "xsf_owens_t"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_pdtr "xsf_pdtr"(double, double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_pdtrc "xsf_pdtrc"(double, double) noexcept nogil
+from ._legacy cimport pdtri_unsafe as _func_pdtri_unsafe
+ctypedef double _proto_pdtri_unsafe_t(double, double) noexcept nogil
+cdef _proto_pdtri_unsafe_t *_proto_pdtri_unsafe_t_var = &_func_pdtri_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_pdtri_wrap "cephes_pdtri_wrap"(Py_ssize_t, double) noexcept nogil
+from ._cdflib_wrappers cimport pdtrik as _func_pdtrik
+ctypedef double _proto_pdtrik_t(double, double) noexcept nogil
+cdef _proto_pdtrik_t *_proto_pdtrik_t_var = &_func_pdtrik
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_poch "cephes_poch"(double, double) noexcept nogil
+from ._convex_analysis cimport pseudo_huber as _func_pseudo_huber
+ctypedef double _proto_pseudo_huber_t(double, double) noexcept nogil
+cdef _proto_pseudo_huber_t *_proto_pseudo_huber_t_var = &_func_pseudo_huber
+from ._convex_analysis cimport rel_entr as _func_rel_entr
+ctypedef double _proto_rel_entr_t(double, double) noexcept nogil
+cdef _proto_rel_entr_t *_proto_rel_entr_t_var = &_func_rel_entr
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_round "cephes_round"(double) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_cshichi "xsf_cshichi"(double complex, double complex *, double complex *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_shichi "xsf_shichi"(double, double *, double *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_csici "xsf_csici"(double complex, double complex *, double complex *) noexcept nogil
+cdef extern from r"_ufuncs_defs.h":
+    cdef int _func_xsf_sici "xsf_sici"(double, double *, double *) noexcept nogil
+from ._legacy cimport smirnov_unsafe as _func_smirnov_unsafe
+ctypedef double _proto_smirnov_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnov_unsafe_t *_proto_smirnov_unsafe_t_var = &_func_smirnov_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnov_wrap "cephes_smirnov_wrap"(Py_ssize_t, double) noexcept nogil
+from ._legacy cimport smirnovi_unsafe as _func_smirnovi_unsafe
+ctypedef double _proto_smirnovi_unsafe_t(double, double) noexcept nogil
+cdef _proto_smirnovi_unsafe_t *_proto_smirnovi_unsafe_t_var = &_func_smirnovi_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_smirnovi_wrap "cephes_smirnovi_wrap"(Py_ssize_t, double) noexcept nogil
+from ._spence cimport cspence as _func_cspence
+ctypedef double complex _proto_cspence_t(double complex) noexcept nogil
+cdef _proto_cspence_t *_proto_cspence_t_var = &_func_cspence
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_spence "cephes_spence"(double) noexcept nogil
+from ._cdflib_wrappers cimport stdtr as _func_stdtr
+ctypedef double _proto_stdtr_t(double, double) noexcept nogil
+cdef _proto_stdtr_t *_proto_stdtr_t_var = &_func_stdtr
+from ._cdflib_wrappers cimport stdtridf as _func_stdtridf
+ctypedef double _proto_stdtridf_t(double, double) noexcept nogil
+cdef _proto_stdtridf_t *_proto_stdtridf_t_var = &_func_stdtridf
+from ._cdflib_wrappers cimport stdtrit as _func_stdtrit
+ctypedef double _proto_stdtrit_t(double, double) noexcept nogil
+cdef _proto_stdtrit_t *_proto_stdtrit_t_var = &_func_stdtrit
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_xsf_tukeylambdacdf "xsf_tukeylambdacdf"(double, double) noexcept nogil
+from ._xlogy cimport xlog1py as _func_xlog1py
+ctypedef double _proto_xlog1py_double__t(double, double) noexcept nogil
+cdef _proto_xlog1py_double__t *_proto_xlog1py_double__t_var = &_func_xlog1py[double]
+from ._xlogy cimport xlog1py as _func_xlog1py
+ctypedef double complex _proto_xlog1py_double_complex__t(double complex, double complex) noexcept nogil
+cdef _proto_xlog1py_double_complex__t *_proto_xlog1py_double_complex__t_var = &_func_xlog1py[double_complex]
+from ._xlogy cimport xlogy as _func_xlogy
+ctypedef double _proto_xlogy_double__t(double, double) noexcept nogil
+cdef _proto_xlogy_double__t *_proto_xlogy_double__t_var = &_func_xlogy[double]
+from ._xlogy cimport xlogy as _func_xlogy
+ctypedef double complex _proto_xlogy_double_complex__t(double complex, double complex) noexcept nogil
+cdef _proto_xlogy_double_complex__t *_proto_xlogy_double_complex__t_var = &_func_xlogy[double_complex]
+from ._legacy cimport yn_unsafe as _func_yn_unsafe
+ctypedef double _proto_yn_unsafe_t(double, double) noexcept nogil
+cdef _proto_yn_unsafe_t *_proto_yn_unsafe_t_var = &_func_yn_unsafe
+cdef extern from r"_ufuncs_defs.h":
+    cdef double _func_cephes_yn_wrap "cephes_yn_wrap"(Py_ssize_t, double) noexcept nogil
+cdef np.PyUFuncGenericFunction ufunc__beta_pdf_loops[2]
+cdef void *ufunc__beta_pdf_ptr[4]
+cdef void *ufunc__beta_pdf_data[2]
+cdef char ufunc__beta_pdf_types[8]
+cdef char *ufunc__beta_pdf_doc = (
+    "_beta_pdf(x, a, b)\n"
+    "\n"
+    "Probability density function of beta distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__beta_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__beta_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__beta_pdf_types[0] = NPY_FLOAT
+ufunc__beta_pdf_types[1] = NPY_FLOAT
+ufunc__beta_pdf_types[2] = NPY_FLOAT
+ufunc__beta_pdf_types[3] = NPY_FLOAT
+ufunc__beta_pdf_types[4] = NPY_DOUBLE
+ufunc__beta_pdf_types[5] = NPY_DOUBLE
+ufunc__beta_pdf_types[6] = NPY_DOUBLE
+ufunc__beta_pdf_types[7] = NPY_DOUBLE
+ufunc__beta_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_beta_pdf_float
+ufunc__beta_pdf_ptr[2*0+1] = ("_beta_pdf")
+ufunc__beta_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_beta_pdf_double
+ufunc__beta_pdf_ptr[2*1+1] = ("_beta_pdf")
+ufunc__beta_pdf_data[0] = &ufunc__beta_pdf_ptr[2*0]
+ufunc__beta_pdf_data[1] = &ufunc__beta_pdf_ptr[2*1]
+_beta_pdf = np.PyUFunc_FromFuncAndData(ufunc__beta_pdf_loops, ufunc__beta_pdf_data, ufunc__beta_pdf_types, 2, 3, 1, 0, "_beta_pdf", ufunc__beta_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__beta_ppf_loops[2]
+cdef void *ufunc__beta_ppf_ptr[4]
+cdef void *ufunc__beta_ppf_data[2]
+cdef char ufunc__beta_ppf_types[8]
+cdef char *ufunc__beta_ppf_doc = (
+    "_beta_ppf(x, a, b)\n"
+    "\n"
+    "Percent point function of beta distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__beta_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__beta_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__beta_ppf_types[0] = NPY_FLOAT
+ufunc__beta_ppf_types[1] = NPY_FLOAT
+ufunc__beta_ppf_types[2] = NPY_FLOAT
+ufunc__beta_ppf_types[3] = NPY_FLOAT
+ufunc__beta_ppf_types[4] = NPY_DOUBLE
+ufunc__beta_ppf_types[5] = NPY_DOUBLE
+ufunc__beta_ppf_types[6] = NPY_DOUBLE
+ufunc__beta_ppf_types[7] = NPY_DOUBLE
+ufunc__beta_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_beta_ppf_float
+ufunc__beta_ppf_ptr[2*0+1] = ("_beta_ppf")
+ufunc__beta_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_beta_ppf_double
+ufunc__beta_ppf_ptr[2*1+1] = ("_beta_ppf")
+ufunc__beta_ppf_data[0] = &ufunc__beta_ppf_ptr[2*0]
+ufunc__beta_ppf_data[1] = &ufunc__beta_ppf_ptr[2*1]
+_beta_ppf = np.PyUFunc_FromFuncAndData(ufunc__beta_ppf_loops, ufunc__beta_ppf_data, ufunc__beta_ppf_types, 2, 3, 1, 0, "_beta_ppf", ufunc__beta_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_cdf_loops[2]
+cdef void *ufunc__binom_cdf_ptr[4]
+cdef void *ufunc__binom_cdf_data[2]
+cdef char ufunc__binom_cdf_types[8]
+cdef char *ufunc__binom_cdf_doc = (
+    "_binom_cdf(x, n, p)\n"
+    "\n"
+    "Cumulative density function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_cdf_types[0] = NPY_FLOAT
+ufunc__binom_cdf_types[1] = NPY_FLOAT
+ufunc__binom_cdf_types[2] = NPY_FLOAT
+ufunc__binom_cdf_types[3] = NPY_FLOAT
+ufunc__binom_cdf_types[4] = NPY_DOUBLE
+ufunc__binom_cdf_types[5] = NPY_DOUBLE
+ufunc__binom_cdf_types[6] = NPY_DOUBLE
+ufunc__binom_cdf_types[7] = NPY_DOUBLE
+ufunc__binom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_cdf_float
+ufunc__binom_cdf_ptr[2*0+1] = ("_binom_cdf")
+ufunc__binom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_cdf_double
+ufunc__binom_cdf_ptr[2*1+1] = ("_binom_cdf")
+ufunc__binom_cdf_data[0] = &ufunc__binom_cdf_ptr[2*0]
+ufunc__binom_cdf_data[1] = &ufunc__binom_cdf_ptr[2*1]
+_binom_cdf = np.PyUFunc_FromFuncAndData(ufunc__binom_cdf_loops, ufunc__binom_cdf_data, ufunc__binom_cdf_types, 2, 3, 1, 0, "_binom_cdf", ufunc__binom_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_isf_loops[2]
+cdef void *ufunc__binom_isf_ptr[4]
+cdef void *ufunc__binom_isf_data[2]
+cdef char ufunc__binom_isf_types[8]
+cdef char *ufunc__binom_isf_doc = (
+    "_binom_isf(x, n, p)\n"
+    "\n"
+    "Inverse survival function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_isf_types[0] = NPY_FLOAT
+ufunc__binom_isf_types[1] = NPY_FLOAT
+ufunc__binom_isf_types[2] = NPY_FLOAT
+ufunc__binom_isf_types[3] = NPY_FLOAT
+ufunc__binom_isf_types[4] = NPY_DOUBLE
+ufunc__binom_isf_types[5] = NPY_DOUBLE
+ufunc__binom_isf_types[6] = NPY_DOUBLE
+ufunc__binom_isf_types[7] = NPY_DOUBLE
+ufunc__binom_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_isf_float
+ufunc__binom_isf_ptr[2*0+1] = ("_binom_isf")
+ufunc__binom_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_isf_double
+ufunc__binom_isf_ptr[2*1+1] = ("_binom_isf")
+ufunc__binom_isf_data[0] = &ufunc__binom_isf_ptr[2*0]
+ufunc__binom_isf_data[1] = &ufunc__binom_isf_ptr[2*1]
+_binom_isf = np.PyUFunc_FromFuncAndData(ufunc__binom_isf_loops, ufunc__binom_isf_data, ufunc__binom_isf_types, 2, 3, 1, 0, "_binom_isf", ufunc__binom_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_pmf_loops[2]
+cdef void *ufunc__binom_pmf_ptr[4]
+cdef void *ufunc__binom_pmf_data[2]
+cdef char ufunc__binom_pmf_types[8]
+cdef char *ufunc__binom_pmf_doc = (
+    "_binom_pmf(x, n, p)\n"
+    "\n"
+    "Probability mass function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_pmf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_pmf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_pmf_types[0] = NPY_FLOAT
+ufunc__binom_pmf_types[1] = NPY_FLOAT
+ufunc__binom_pmf_types[2] = NPY_FLOAT
+ufunc__binom_pmf_types[3] = NPY_FLOAT
+ufunc__binom_pmf_types[4] = NPY_DOUBLE
+ufunc__binom_pmf_types[5] = NPY_DOUBLE
+ufunc__binom_pmf_types[6] = NPY_DOUBLE
+ufunc__binom_pmf_types[7] = NPY_DOUBLE
+ufunc__binom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_pmf_float
+ufunc__binom_pmf_ptr[2*0+1] = ("_binom_pmf")
+ufunc__binom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_pmf_double
+ufunc__binom_pmf_ptr[2*1+1] = ("_binom_pmf")
+ufunc__binom_pmf_data[0] = &ufunc__binom_pmf_ptr[2*0]
+ufunc__binom_pmf_data[1] = &ufunc__binom_pmf_ptr[2*1]
+_binom_pmf = np.PyUFunc_FromFuncAndData(ufunc__binom_pmf_loops, ufunc__binom_pmf_data, ufunc__binom_pmf_types, 2, 3, 1, 0, "_binom_pmf", ufunc__binom_pmf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_ppf_loops[2]
+cdef void *ufunc__binom_ppf_ptr[4]
+cdef void *ufunc__binom_ppf_data[2]
+cdef char ufunc__binom_ppf_types[8]
+cdef char *ufunc__binom_ppf_doc = (
+    "_binom_ppf(x, n, p)\n"
+    "\n"
+    "Percent point function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_ppf_types[0] = NPY_FLOAT
+ufunc__binom_ppf_types[1] = NPY_FLOAT
+ufunc__binom_ppf_types[2] = NPY_FLOAT
+ufunc__binom_ppf_types[3] = NPY_FLOAT
+ufunc__binom_ppf_types[4] = NPY_DOUBLE
+ufunc__binom_ppf_types[5] = NPY_DOUBLE
+ufunc__binom_ppf_types[6] = NPY_DOUBLE
+ufunc__binom_ppf_types[7] = NPY_DOUBLE
+ufunc__binom_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_ppf_float
+ufunc__binom_ppf_ptr[2*0+1] = ("_binom_ppf")
+ufunc__binom_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_ppf_double
+ufunc__binom_ppf_ptr[2*1+1] = ("_binom_ppf")
+ufunc__binom_ppf_data[0] = &ufunc__binom_ppf_ptr[2*0]
+ufunc__binom_ppf_data[1] = &ufunc__binom_ppf_ptr[2*1]
+_binom_ppf = np.PyUFunc_FromFuncAndData(ufunc__binom_ppf_loops, ufunc__binom_ppf_data, ufunc__binom_ppf_types, 2, 3, 1, 0, "_binom_ppf", ufunc__binom_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__binom_sf_loops[2]
+cdef void *ufunc__binom_sf_ptr[4]
+cdef void *ufunc__binom_sf_data[2]
+cdef char ufunc__binom_sf_types[8]
+cdef char *ufunc__binom_sf_doc = (
+    "_binom_sf(x, n, p)\n"
+    "\n"
+    "Survival function of binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "n : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__binom_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__binom_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__binom_sf_types[0] = NPY_FLOAT
+ufunc__binom_sf_types[1] = NPY_FLOAT
+ufunc__binom_sf_types[2] = NPY_FLOAT
+ufunc__binom_sf_types[3] = NPY_FLOAT
+ufunc__binom_sf_types[4] = NPY_DOUBLE
+ufunc__binom_sf_types[5] = NPY_DOUBLE
+ufunc__binom_sf_types[6] = NPY_DOUBLE
+ufunc__binom_sf_types[7] = NPY_DOUBLE
+ufunc__binom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_binom_sf_float
+ufunc__binom_sf_ptr[2*0+1] = ("_binom_sf")
+ufunc__binom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_binom_sf_double
+ufunc__binom_sf_ptr[2*1+1] = ("_binom_sf")
+ufunc__binom_sf_data[0] = &ufunc__binom_sf_ptr[2*0]
+ufunc__binom_sf_data[1] = &ufunc__binom_sf_ptr[2*1]
+_binom_sf = np.PyUFunc_FromFuncAndData(ufunc__binom_sf_loops, ufunc__binom_sf_data, ufunc__binom_sf_types, 2, 3, 1, 0, "_binom_sf", ufunc__binom_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cauchy_isf_loops[2]
+cdef void *ufunc__cauchy_isf_ptr[4]
+cdef void *ufunc__cauchy_isf_data[2]
+cdef char ufunc__cauchy_isf_types[8]
+cdef char *ufunc__cauchy_isf_doc = (
+    "_cauchy_isf(p, loc, scale)\n"
+    "\n"
+    "Inverse survival function of the Cauchy distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probabilities\n"
+    "loc : array_like\n"
+    "    Location parameter of the distribution.\n"
+    "scale : array_like\n"
+    "    Scale parameter of the distribution.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__cauchy_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__cauchy_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__cauchy_isf_types[0] = NPY_FLOAT
+ufunc__cauchy_isf_types[1] = NPY_FLOAT
+ufunc__cauchy_isf_types[2] = NPY_FLOAT
+ufunc__cauchy_isf_types[3] = NPY_FLOAT
+ufunc__cauchy_isf_types[4] = NPY_DOUBLE
+ufunc__cauchy_isf_types[5] = NPY_DOUBLE
+ufunc__cauchy_isf_types[6] = NPY_DOUBLE
+ufunc__cauchy_isf_types[7] = NPY_DOUBLE
+ufunc__cauchy_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_cauchy_isf_float
+ufunc__cauchy_isf_ptr[2*0+1] = ("_cauchy_isf")
+ufunc__cauchy_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_cauchy_isf_double
+ufunc__cauchy_isf_ptr[2*1+1] = ("_cauchy_isf")
+ufunc__cauchy_isf_data[0] = &ufunc__cauchy_isf_ptr[2*0]
+ufunc__cauchy_isf_data[1] = &ufunc__cauchy_isf_ptr[2*1]
+_cauchy_isf = np.PyUFunc_FromFuncAndData(ufunc__cauchy_isf_loops, ufunc__cauchy_isf_data, ufunc__cauchy_isf_types, 2, 3, 1, 0, "_cauchy_isf", ufunc__cauchy_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cauchy_ppf_loops[2]
+cdef void *ufunc__cauchy_ppf_ptr[4]
+cdef void *ufunc__cauchy_ppf_data[2]
+cdef char ufunc__cauchy_ppf_types[8]
+cdef char *ufunc__cauchy_ppf_doc = (
+    "_cauchy_ppf(p, loc, scale)\n"
+    "\n"
+    "Percent point function (i.e. quantile) of the Cauchy distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probabilities\n"
+    "loc : array_like\n"
+    "    Location parameter of the distribution.\n"
+    "scale : array_like\n"
+    "    Scale parameter of the distribution.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__cauchy_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__cauchy_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__cauchy_ppf_types[0] = NPY_FLOAT
+ufunc__cauchy_ppf_types[1] = NPY_FLOAT
+ufunc__cauchy_ppf_types[2] = NPY_FLOAT
+ufunc__cauchy_ppf_types[3] = NPY_FLOAT
+ufunc__cauchy_ppf_types[4] = NPY_DOUBLE
+ufunc__cauchy_ppf_types[5] = NPY_DOUBLE
+ufunc__cauchy_ppf_types[6] = NPY_DOUBLE
+ufunc__cauchy_ppf_types[7] = NPY_DOUBLE
+ufunc__cauchy_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_cauchy_ppf_float
+ufunc__cauchy_ppf_ptr[2*0+1] = ("_cauchy_ppf")
+ufunc__cauchy_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_cauchy_ppf_double
+ufunc__cauchy_ppf_ptr[2*1+1] = ("_cauchy_ppf")
+ufunc__cauchy_ppf_data[0] = &ufunc__cauchy_ppf_ptr[2*0]
+ufunc__cauchy_ppf_data[1] = &ufunc__cauchy_ppf_ptr[2*1]
+_cauchy_ppf = np.PyUFunc_FromFuncAndData(ufunc__cauchy_ppf_loops, ufunc__cauchy_ppf_data, ufunc__cauchy_ppf_types, 2, 3, 1, 0, "_cauchy_ppf", ufunc__cauchy_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cosine_cdf_loops[2]
+cdef void *ufunc__cosine_cdf_ptr[4]
+cdef void *ufunc__cosine_cdf_data[2]
+cdef char ufunc__cosine_cdf_types[4]
+cdef char *ufunc__cosine_cdf_doc = (
+    "_cosine_cdf(x)\n"
+    "\n"
+    "Cumulative distribution function (CDF) of the cosine distribution::\n"
+    "\n"
+    "             {             0,              x < -pi\n"
+    "    cdf(x) = { (pi + x + sin(x))/(2*pi),   -pi <= x <= pi\n"
+    "             {             1,              x > pi\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The cosine distribution CDF evaluated at `x`.")
+ufunc__cosine_cdf_loops[0] = loop_d_d__As_f_f
+ufunc__cosine_cdf_loops[1] = loop_d_d__As_d_d
+ufunc__cosine_cdf_types[0] = NPY_FLOAT
+ufunc__cosine_cdf_types[1] = NPY_FLOAT
+ufunc__cosine_cdf_types[2] = NPY_DOUBLE
+ufunc__cosine_cdf_types[3] = NPY_DOUBLE
+ufunc__cosine_cdf_ptr[2*0] = _func_cosine_cdf
+ufunc__cosine_cdf_ptr[2*0+1] = ("_cosine_cdf")
+ufunc__cosine_cdf_ptr[2*1] = _func_cosine_cdf
+ufunc__cosine_cdf_ptr[2*1+1] = ("_cosine_cdf")
+ufunc__cosine_cdf_data[0] = &ufunc__cosine_cdf_ptr[2*0]
+ufunc__cosine_cdf_data[1] = &ufunc__cosine_cdf_ptr[2*1]
+_cosine_cdf = np.PyUFunc_FromFuncAndData(ufunc__cosine_cdf_loops, ufunc__cosine_cdf_data, ufunc__cosine_cdf_types, 2, 1, 1, 0, "_cosine_cdf", ufunc__cosine_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__cosine_invcdf_loops[2]
+cdef void *ufunc__cosine_invcdf_ptr[4]
+cdef void *ufunc__cosine_invcdf_data[2]
+cdef char ufunc__cosine_invcdf_types[4]
+cdef char *ufunc__cosine_invcdf_doc = (
+    "_cosine_invcdf(p)\n"
+    "\n"
+    "Inverse of the cumulative distribution function (CDF) of the cosine\n"
+    "distribution.\n"
+    "\n"
+    "The CDF of the cosine distribution is::\n"
+    "\n"
+    "    cdf(x) = (pi + x + sin(x))/(2*pi)\n"
+    "\n"
+    "This function computes the inverse of cdf(x).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    `p` must contain real numbers in the interval ``0 <= p <= 1``.\n"
+    "    `nan` is returned for values of `p` outside the interval [0, 1].\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The inverse of the cosine distribution CDF evaluated at `p`.")
+ufunc__cosine_invcdf_loops[0] = loop_d_d__As_f_f
+ufunc__cosine_invcdf_loops[1] = loop_d_d__As_d_d
+ufunc__cosine_invcdf_types[0] = NPY_FLOAT
+ufunc__cosine_invcdf_types[1] = NPY_FLOAT
+ufunc__cosine_invcdf_types[2] = NPY_DOUBLE
+ufunc__cosine_invcdf_types[3] = NPY_DOUBLE
+ufunc__cosine_invcdf_ptr[2*0] = _func_cosine_invcdf
+ufunc__cosine_invcdf_ptr[2*0+1] = ("_cosine_invcdf")
+ufunc__cosine_invcdf_ptr[2*1] = _func_cosine_invcdf
+ufunc__cosine_invcdf_ptr[2*1+1] = ("_cosine_invcdf")
+ufunc__cosine_invcdf_data[0] = &ufunc__cosine_invcdf_ptr[2*0]
+ufunc__cosine_invcdf_data[1] = &ufunc__cosine_invcdf_ptr[2*1]
+_cosine_invcdf = np.PyUFunc_FromFuncAndData(ufunc__cosine_invcdf_loops, ufunc__cosine_invcdf_data, ufunc__cosine_invcdf_types, 2, 1, 1, 0, "_cosine_invcdf", ufunc__cosine_invcdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ellip_harm_loops[3]
+cdef void *ufunc__ellip_harm_ptr[6]
+cdef void *ufunc__ellip_harm_data[3]
+cdef char ufunc__ellip_harm_types[24]
+cdef char *ufunc__ellip_harm_doc = (
+    "Internal function, use `ellip_harm` instead.")
+ufunc__ellip_harm_loops[0] = loop_d_ddddddd__As_fffffff_f
+ufunc__ellip_harm_loops[1] = loop_d_ddiiddd__As_ddllddd_d
+ufunc__ellip_harm_loops[2] = loop_d_ddddddd__As_ddddddd_d
+ufunc__ellip_harm_types[0] = NPY_FLOAT
+ufunc__ellip_harm_types[1] = NPY_FLOAT
+ufunc__ellip_harm_types[2] = NPY_FLOAT
+ufunc__ellip_harm_types[3] = NPY_FLOAT
+ufunc__ellip_harm_types[4] = NPY_FLOAT
+ufunc__ellip_harm_types[5] = NPY_FLOAT
+ufunc__ellip_harm_types[6] = NPY_FLOAT
+ufunc__ellip_harm_types[7] = NPY_FLOAT
+ufunc__ellip_harm_types[8] = NPY_DOUBLE
+ufunc__ellip_harm_types[9] = NPY_DOUBLE
+ufunc__ellip_harm_types[10] = NPY_LONG
+ufunc__ellip_harm_types[11] = NPY_LONG
+ufunc__ellip_harm_types[12] = NPY_DOUBLE
+ufunc__ellip_harm_types[13] = NPY_DOUBLE
+ufunc__ellip_harm_types[14] = NPY_DOUBLE
+ufunc__ellip_harm_types[15] = NPY_DOUBLE
+ufunc__ellip_harm_types[16] = NPY_DOUBLE
+ufunc__ellip_harm_types[17] = NPY_DOUBLE
+ufunc__ellip_harm_types[18] = NPY_DOUBLE
+ufunc__ellip_harm_types[19] = NPY_DOUBLE
+ufunc__ellip_harm_types[20] = NPY_DOUBLE
+ufunc__ellip_harm_types[21] = NPY_DOUBLE
+ufunc__ellip_harm_types[22] = NPY_DOUBLE
+ufunc__ellip_harm_types[23] = NPY_DOUBLE
+ufunc__ellip_harm_ptr[2*0] = _func_ellip_harmonic_unsafe
+ufunc__ellip_harm_ptr[2*0+1] = ("_ellip_harm")
+ufunc__ellip_harm_ptr[2*1] = _func_ellip_harmonic
+ufunc__ellip_harm_ptr[2*1+1] = ("_ellip_harm")
+ufunc__ellip_harm_ptr[2*2] = _func_ellip_harmonic_unsafe
+ufunc__ellip_harm_ptr[2*2+1] = ("_ellip_harm")
+ufunc__ellip_harm_data[0] = &ufunc__ellip_harm_ptr[2*0]
+ufunc__ellip_harm_data[1] = &ufunc__ellip_harm_ptr[2*1]
+ufunc__ellip_harm_data[2] = &ufunc__ellip_harm_ptr[2*2]
+_ellip_harm = np.PyUFunc_FromFuncAndData(ufunc__ellip_harm_loops, ufunc__ellip_harm_data, ufunc__ellip_harm_types, 3, 7, 1, 0, "_ellip_harm", ufunc__ellip_harm_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__factorial_loops[2]
+cdef void *ufunc__factorial_ptr[4]
+cdef void *ufunc__factorial_data[2]
+cdef char ufunc__factorial_types[4]
+cdef char *ufunc__factorial_doc = (
+    "Internal function, do not use.")
+ufunc__factorial_loops[0] = loop_d_d__As_f_f
+ufunc__factorial_loops[1] = loop_d_d__As_d_d
+ufunc__factorial_types[0] = NPY_FLOAT
+ufunc__factorial_types[1] = NPY_FLOAT
+ufunc__factorial_types[2] = NPY_DOUBLE
+ufunc__factorial_types[3] = NPY_DOUBLE
+ufunc__factorial_ptr[2*0] = _func__factorial
+ufunc__factorial_ptr[2*0+1] = ("_factorial")
+ufunc__factorial_ptr[2*1] = _func__factorial
+ufunc__factorial_ptr[2*1+1] = ("_factorial")
+ufunc__factorial_data[0] = &ufunc__factorial_ptr[2*0]
+ufunc__factorial_data[1] = &ufunc__factorial_ptr[2*1]
+_factorial = np.PyUFunc_FromFuncAndData(ufunc__factorial_loops, ufunc__factorial_data, ufunc__factorial_types, 2, 1, 1, 0, "_factorial", ufunc__factorial_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_cdf_loops[2]
+cdef void *ufunc__hypergeom_cdf_ptr[4]
+cdef void *ufunc__hypergeom_cdf_data[2]
+cdef char ufunc__hypergeom_cdf_types[10]
+cdef char *ufunc__hypergeom_cdf_doc = (
+    "_hypergeom_cdf(x, r, N, M)\n"
+    "\n"
+    "Cumulative density function of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_cdf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__hypergeom_cdf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__hypergeom_cdf_types[0] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[1] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[2] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[3] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[4] = NPY_FLOAT
+ufunc__hypergeom_cdf_types[5] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[6] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[7] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[8] = NPY_DOUBLE
+ufunc__hypergeom_cdf_types[9] = NPY_DOUBLE
+ufunc__hypergeom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_cdf_float
+ufunc__hypergeom_cdf_ptr[2*0+1] = ("_hypergeom_cdf")
+ufunc__hypergeom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_cdf_double
+ufunc__hypergeom_cdf_ptr[2*1+1] = ("_hypergeom_cdf")
+ufunc__hypergeom_cdf_data[0] = &ufunc__hypergeom_cdf_ptr[2*0]
+ufunc__hypergeom_cdf_data[1] = &ufunc__hypergeom_cdf_ptr[2*1]
+_hypergeom_cdf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_cdf_loops, ufunc__hypergeom_cdf_data, ufunc__hypergeom_cdf_types, 2, 4, 1, 0, "_hypergeom_cdf", ufunc__hypergeom_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_mean_loops[2]
+cdef void *ufunc__hypergeom_mean_ptr[4]
+cdef void *ufunc__hypergeom_mean_data[2]
+cdef char ufunc__hypergeom_mean_types[8]
+cdef char *ufunc__hypergeom_mean_doc = (
+    "_hypergeom_mean(r, N, M)\n"
+    "\n"
+    "Mean of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_mean_loops[0] = loop_f_fff__As_fff_f
+ufunc__hypergeom_mean_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__hypergeom_mean_types[0] = NPY_FLOAT
+ufunc__hypergeom_mean_types[1] = NPY_FLOAT
+ufunc__hypergeom_mean_types[2] = NPY_FLOAT
+ufunc__hypergeom_mean_types[3] = NPY_FLOAT
+ufunc__hypergeom_mean_types[4] = NPY_DOUBLE
+ufunc__hypergeom_mean_types[5] = NPY_DOUBLE
+ufunc__hypergeom_mean_types[6] = NPY_DOUBLE
+ufunc__hypergeom_mean_types[7] = NPY_DOUBLE
+ufunc__hypergeom_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_mean_float
+ufunc__hypergeom_mean_ptr[2*0+1] = ("_hypergeom_mean")
+ufunc__hypergeom_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_mean_double
+ufunc__hypergeom_mean_ptr[2*1+1] = ("_hypergeom_mean")
+ufunc__hypergeom_mean_data[0] = &ufunc__hypergeom_mean_ptr[2*0]
+ufunc__hypergeom_mean_data[1] = &ufunc__hypergeom_mean_ptr[2*1]
+_hypergeom_mean = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_mean_loops, ufunc__hypergeom_mean_data, ufunc__hypergeom_mean_types, 2, 3, 1, 0, "_hypergeom_mean", ufunc__hypergeom_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_pmf_loops[2]
+cdef void *ufunc__hypergeom_pmf_ptr[4]
+cdef void *ufunc__hypergeom_pmf_data[2]
+cdef char ufunc__hypergeom_pmf_types[10]
+cdef char *ufunc__hypergeom_pmf_doc = (
+    "_hypergeom_pmf(x, r, N, M)\n"
+    "\n"
+    "Probability mass function of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_pmf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__hypergeom_pmf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__hypergeom_pmf_types[0] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[1] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[2] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[3] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[4] = NPY_FLOAT
+ufunc__hypergeom_pmf_types[5] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[6] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[7] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[8] = NPY_DOUBLE
+ufunc__hypergeom_pmf_types[9] = NPY_DOUBLE
+ufunc__hypergeom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_pmf_float
+ufunc__hypergeom_pmf_ptr[2*0+1] = ("_hypergeom_pmf")
+ufunc__hypergeom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_pmf_double
+ufunc__hypergeom_pmf_ptr[2*1+1] = ("_hypergeom_pmf")
+ufunc__hypergeom_pmf_data[0] = &ufunc__hypergeom_pmf_ptr[2*0]
+ufunc__hypergeom_pmf_data[1] = &ufunc__hypergeom_pmf_ptr[2*1]
+_hypergeom_pmf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_pmf_loops, ufunc__hypergeom_pmf_data, ufunc__hypergeom_pmf_types, 2, 4, 1, 0, "_hypergeom_pmf", ufunc__hypergeom_pmf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_sf_loops[2]
+cdef void *ufunc__hypergeom_sf_ptr[4]
+cdef void *ufunc__hypergeom_sf_data[2]
+cdef char ufunc__hypergeom_sf_types[10]
+cdef char *ufunc__hypergeom_sf_doc = (
+    "_hypergeom_sf(x, r, N, M)\n"
+    "\n"
+    "Survival function of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_sf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__hypergeom_sf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__hypergeom_sf_types[0] = NPY_FLOAT
+ufunc__hypergeom_sf_types[1] = NPY_FLOAT
+ufunc__hypergeom_sf_types[2] = NPY_FLOAT
+ufunc__hypergeom_sf_types[3] = NPY_FLOAT
+ufunc__hypergeom_sf_types[4] = NPY_FLOAT
+ufunc__hypergeom_sf_types[5] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[6] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[7] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[8] = NPY_DOUBLE
+ufunc__hypergeom_sf_types[9] = NPY_DOUBLE
+ufunc__hypergeom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_sf_float
+ufunc__hypergeom_sf_ptr[2*0+1] = ("_hypergeom_sf")
+ufunc__hypergeom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_sf_double
+ufunc__hypergeom_sf_ptr[2*1+1] = ("_hypergeom_sf")
+ufunc__hypergeom_sf_data[0] = &ufunc__hypergeom_sf_ptr[2*0]
+ufunc__hypergeom_sf_data[1] = &ufunc__hypergeom_sf_ptr[2*1]
+_hypergeom_sf = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_sf_loops, ufunc__hypergeom_sf_data, ufunc__hypergeom_sf_types, 2, 4, 1, 0, "_hypergeom_sf", ufunc__hypergeom_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_skewness_loops[2]
+cdef void *ufunc__hypergeom_skewness_ptr[4]
+cdef void *ufunc__hypergeom_skewness_data[2]
+cdef char ufunc__hypergeom_skewness_types[8]
+cdef char *ufunc__hypergeom_skewness_doc = (
+    "_hypergeom_skewness(r, N, M)\n"
+    "\n"
+    "Skewness of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_skewness_loops[0] = loop_f_fff__As_fff_f
+ufunc__hypergeom_skewness_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__hypergeom_skewness_types[0] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[1] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[2] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[3] = NPY_FLOAT
+ufunc__hypergeom_skewness_types[4] = NPY_DOUBLE
+ufunc__hypergeom_skewness_types[5] = NPY_DOUBLE
+ufunc__hypergeom_skewness_types[6] = NPY_DOUBLE
+ufunc__hypergeom_skewness_types[7] = NPY_DOUBLE
+ufunc__hypergeom_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_skewness_float
+ufunc__hypergeom_skewness_ptr[2*0+1] = ("_hypergeom_skewness")
+ufunc__hypergeom_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_skewness_double
+ufunc__hypergeom_skewness_ptr[2*1+1] = ("_hypergeom_skewness")
+ufunc__hypergeom_skewness_data[0] = &ufunc__hypergeom_skewness_ptr[2*0]
+ufunc__hypergeom_skewness_data[1] = &ufunc__hypergeom_skewness_ptr[2*1]
+_hypergeom_skewness = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_skewness_loops, ufunc__hypergeom_skewness_data, ufunc__hypergeom_skewness_types, 2, 3, 1, 0, "_hypergeom_skewness", ufunc__hypergeom_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__hypergeom_variance_loops[2]
+cdef void *ufunc__hypergeom_variance_ptr[4]
+cdef void *ufunc__hypergeom_variance_data[2]
+cdef char ufunc__hypergeom_variance_types[8]
+cdef char *ufunc__hypergeom_variance_doc = (
+    "_hypergeom_variance(r, N, M)\n"
+    "\n"
+    "Mean of hypergeometric distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r, N, M : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__hypergeom_variance_loops[0] = loop_f_fff__As_fff_f
+ufunc__hypergeom_variance_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__hypergeom_variance_types[0] = NPY_FLOAT
+ufunc__hypergeom_variance_types[1] = NPY_FLOAT
+ufunc__hypergeom_variance_types[2] = NPY_FLOAT
+ufunc__hypergeom_variance_types[3] = NPY_FLOAT
+ufunc__hypergeom_variance_types[4] = NPY_DOUBLE
+ufunc__hypergeom_variance_types[5] = NPY_DOUBLE
+ufunc__hypergeom_variance_types[6] = NPY_DOUBLE
+ufunc__hypergeom_variance_types[7] = NPY_DOUBLE
+ufunc__hypergeom_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_hypergeom_variance_float
+ufunc__hypergeom_variance_ptr[2*0+1] = ("_hypergeom_variance")
+ufunc__hypergeom_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_hypergeom_variance_double
+ufunc__hypergeom_variance_ptr[2*1+1] = ("_hypergeom_variance")
+ufunc__hypergeom_variance_data[0] = &ufunc__hypergeom_variance_ptr[2*0]
+ufunc__hypergeom_variance_data[1] = &ufunc__hypergeom_variance_ptr[2*1]
+_hypergeom_variance = np.PyUFunc_FromFuncAndData(ufunc__hypergeom_variance_loops, ufunc__hypergeom_variance_data, ufunc__hypergeom_variance_types, 2, 3, 1, 0, "_hypergeom_variance", ufunc__hypergeom_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__igam_fac_loops[2]
+cdef void *ufunc__igam_fac_ptr[4]
+cdef void *ufunc__igam_fac_data[2]
+cdef char ufunc__igam_fac_types[6]
+cdef char *ufunc__igam_fac_doc = (
+    "Internal function, do not use.")
+ufunc__igam_fac_loops[0] = loop_d_dd__As_ff_f
+ufunc__igam_fac_loops[1] = loop_d_dd__As_dd_d
+ufunc__igam_fac_types[0] = NPY_FLOAT
+ufunc__igam_fac_types[1] = NPY_FLOAT
+ufunc__igam_fac_types[2] = NPY_FLOAT
+ufunc__igam_fac_types[3] = NPY_DOUBLE
+ufunc__igam_fac_types[4] = NPY_DOUBLE
+ufunc__igam_fac_types[5] = NPY_DOUBLE
+ufunc__igam_fac_ptr[2*0] = _func_cephes_igam_fac
+ufunc__igam_fac_ptr[2*0+1] = ("_igam_fac")
+ufunc__igam_fac_ptr[2*1] = _func_cephes_igam_fac
+ufunc__igam_fac_ptr[2*1+1] = ("_igam_fac")
+ufunc__igam_fac_data[0] = &ufunc__igam_fac_ptr[2*0]
+ufunc__igam_fac_data[1] = &ufunc__igam_fac_ptr[2*1]
+_igam_fac = np.PyUFunc_FromFuncAndData(ufunc__igam_fac_loops, ufunc__igam_fac_data, ufunc__igam_fac_types, 2, 2, 1, 0, "_igam_fac", ufunc__igam_fac_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__invgauss_isf_loops[2]
+cdef void *ufunc__invgauss_isf_ptr[4]
+cdef void *ufunc__invgauss_isf_data[2]
+cdef char ufunc__invgauss_isf_types[8]
+cdef char *ufunc__invgauss_isf_doc = (
+    "_invgauss_isf(x, mu, s)\n"
+    "\n"
+    "Inverse survival function of inverse gaussian distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "mu : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "s : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__invgauss_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__invgauss_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__invgauss_isf_types[0] = NPY_FLOAT
+ufunc__invgauss_isf_types[1] = NPY_FLOAT
+ufunc__invgauss_isf_types[2] = NPY_FLOAT
+ufunc__invgauss_isf_types[3] = NPY_FLOAT
+ufunc__invgauss_isf_types[4] = NPY_DOUBLE
+ufunc__invgauss_isf_types[5] = NPY_DOUBLE
+ufunc__invgauss_isf_types[6] = NPY_DOUBLE
+ufunc__invgauss_isf_types[7] = NPY_DOUBLE
+ufunc__invgauss_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_invgauss_isf_float
+ufunc__invgauss_isf_ptr[2*0+1] = ("_invgauss_isf")
+ufunc__invgauss_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_invgauss_isf_double
+ufunc__invgauss_isf_ptr[2*1+1] = ("_invgauss_isf")
+ufunc__invgauss_isf_data[0] = &ufunc__invgauss_isf_ptr[2*0]
+ufunc__invgauss_isf_data[1] = &ufunc__invgauss_isf_ptr[2*1]
+_invgauss_isf = np.PyUFunc_FromFuncAndData(ufunc__invgauss_isf_loops, ufunc__invgauss_isf_data, ufunc__invgauss_isf_types, 2, 3, 1, 0, "_invgauss_isf", ufunc__invgauss_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__invgauss_ppf_loops[2]
+cdef void *ufunc__invgauss_ppf_ptr[4]
+cdef void *ufunc__invgauss_ppf_data[2]
+cdef char ufunc__invgauss_ppf_types[8]
+cdef char *ufunc__invgauss_ppf_doc = (
+    "_invgauss_ppf(x, mu)\n"
+    "\n"
+    "Percent point function of inverse gaussian distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "mu : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__invgauss_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__invgauss_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__invgauss_ppf_types[0] = NPY_FLOAT
+ufunc__invgauss_ppf_types[1] = NPY_FLOAT
+ufunc__invgauss_ppf_types[2] = NPY_FLOAT
+ufunc__invgauss_ppf_types[3] = NPY_FLOAT
+ufunc__invgauss_ppf_types[4] = NPY_DOUBLE
+ufunc__invgauss_ppf_types[5] = NPY_DOUBLE
+ufunc__invgauss_ppf_types[6] = NPY_DOUBLE
+ufunc__invgauss_ppf_types[7] = NPY_DOUBLE
+ufunc__invgauss_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_invgauss_ppf_float
+ufunc__invgauss_ppf_ptr[2*0+1] = ("_invgauss_ppf")
+ufunc__invgauss_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_invgauss_ppf_double
+ufunc__invgauss_ppf_ptr[2*1+1] = ("_invgauss_ppf")
+ufunc__invgauss_ppf_data[0] = &ufunc__invgauss_ppf_ptr[2*0]
+ufunc__invgauss_ppf_data[1] = &ufunc__invgauss_ppf_ptr[2*1]
+_invgauss_ppf = np.PyUFunc_FromFuncAndData(ufunc__invgauss_ppf_loops, ufunc__invgauss_ppf_data, ufunc__invgauss_ppf_types, 2, 3, 1, 0, "_invgauss_ppf", ufunc__invgauss_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__kolmogc_loops[2]
+cdef void *ufunc__kolmogc_ptr[4]
+cdef void *ufunc__kolmogc_data[2]
+cdef char ufunc__kolmogc_types[4]
+cdef char *ufunc__kolmogc_doc = (
+    "Internal function, do not use.")
+ufunc__kolmogc_loops[0] = loop_d_d__As_f_f
+ufunc__kolmogc_loops[1] = loop_d_d__As_d_d
+ufunc__kolmogc_types[0] = NPY_FLOAT
+ufunc__kolmogc_types[1] = NPY_FLOAT
+ufunc__kolmogc_types[2] = NPY_DOUBLE
+ufunc__kolmogc_types[3] = NPY_DOUBLE
+ufunc__kolmogc_ptr[2*0] = _func_xsf_kolmogc
+ufunc__kolmogc_ptr[2*0+1] = ("_kolmogc")
+ufunc__kolmogc_ptr[2*1] = _func_xsf_kolmogc
+ufunc__kolmogc_ptr[2*1+1] = ("_kolmogc")
+ufunc__kolmogc_data[0] = &ufunc__kolmogc_ptr[2*0]
+ufunc__kolmogc_data[1] = &ufunc__kolmogc_ptr[2*1]
+_kolmogc = np.PyUFunc_FromFuncAndData(ufunc__kolmogc_loops, ufunc__kolmogc_data, ufunc__kolmogc_types, 2, 1, 1, 0, "_kolmogc", ufunc__kolmogc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__kolmogci_loops[2]
+cdef void *ufunc__kolmogci_ptr[4]
+cdef void *ufunc__kolmogci_data[2]
+cdef char ufunc__kolmogci_types[4]
+cdef char *ufunc__kolmogci_doc = (
+    "Internal function, do not use.")
+ufunc__kolmogci_loops[0] = loop_d_d__As_f_f
+ufunc__kolmogci_loops[1] = loop_d_d__As_d_d
+ufunc__kolmogci_types[0] = NPY_FLOAT
+ufunc__kolmogci_types[1] = NPY_FLOAT
+ufunc__kolmogci_types[2] = NPY_DOUBLE
+ufunc__kolmogci_types[3] = NPY_DOUBLE
+ufunc__kolmogci_ptr[2*0] = _func_xsf_kolmogci
+ufunc__kolmogci_ptr[2*0+1] = ("_kolmogci")
+ufunc__kolmogci_ptr[2*1] = _func_xsf_kolmogci
+ufunc__kolmogci_ptr[2*1+1] = ("_kolmogci")
+ufunc__kolmogci_data[0] = &ufunc__kolmogci_ptr[2*0]
+ufunc__kolmogci_data[1] = &ufunc__kolmogci_ptr[2*1]
+_kolmogci = np.PyUFunc_FromFuncAndData(ufunc__kolmogci_loops, ufunc__kolmogci_data, ufunc__kolmogci_types, 2, 1, 1, 0, "_kolmogci", ufunc__kolmogci_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__kolmogp_loops[2]
+cdef void *ufunc__kolmogp_ptr[4]
+cdef void *ufunc__kolmogp_data[2]
+cdef char ufunc__kolmogp_types[4]
+cdef char *ufunc__kolmogp_doc = (
+    "Internal function, do not use.")
+ufunc__kolmogp_loops[0] = loop_d_d__As_f_f
+ufunc__kolmogp_loops[1] = loop_d_d__As_d_d
+ufunc__kolmogp_types[0] = NPY_FLOAT
+ufunc__kolmogp_types[1] = NPY_FLOAT
+ufunc__kolmogp_types[2] = NPY_DOUBLE
+ufunc__kolmogp_types[3] = NPY_DOUBLE
+ufunc__kolmogp_ptr[2*0] = _func_xsf_kolmogp
+ufunc__kolmogp_ptr[2*0+1] = ("_kolmogp")
+ufunc__kolmogp_ptr[2*1] = _func_xsf_kolmogp
+ufunc__kolmogp_ptr[2*1+1] = ("_kolmogp")
+ufunc__kolmogp_data[0] = &ufunc__kolmogp_ptr[2*0]
+ufunc__kolmogp_data[1] = &ufunc__kolmogp_ptr[2*1]
+_kolmogp = np.PyUFunc_FromFuncAndData(ufunc__kolmogp_loops, ufunc__kolmogp_data, ufunc__kolmogp_types, 2, 1, 1, 0, "_kolmogp", ufunc__kolmogp_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__lanczos_sum_expg_scaled_loops[2]
+cdef void *ufunc__lanczos_sum_expg_scaled_ptr[4]
+cdef void *ufunc__lanczos_sum_expg_scaled_data[2]
+cdef char ufunc__lanczos_sum_expg_scaled_types[4]
+cdef char *ufunc__lanczos_sum_expg_scaled_doc = (
+    "Internal function, do not use.")
+ufunc__lanczos_sum_expg_scaled_loops[0] = loop_d_d__As_f_f
+ufunc__lanczos_sum_expg_scaled_loops[1] = loop_d_d__As_d_d
+ufunc__lanczos_sum_expg_scaled_types[0] = NPY_FLOAT
+ufunc__lanczos_sum_expg_scaled_types[1] = NPY_FLOAT
+ufunc__lanczos_sum_expg_scaled_types[2] = NPY_DOUBLE
+ufunc__lanczos_sum_expg_scaled_types[3] = NPY_DOUBLE
+ufunc__lanczos_sum_expg_scaled_ptr[2*0] = _func_cephes_lanczos_sum_expg_scaled
+ufunc__lanczos_sum_expg_scaled_ptr[2*0+1] = ("_lanczos_sum_expg_scaled")
+ufunc__lanczos_sum_expg_scaled_ptr[2*1] = _func_cephes_lanczos_sum_expg_scaled
+ufunc__lanczos_sum_expg_scaled_ptr[2*1+1] = ("_lanczos_sum_expg_scaled")
+ufunc__lanczos_sum_expg_scaled_data[0] = &ufunc__lanczos_sum_expg_scaled_ptr[2*0]
+ufunc__lanczos_sum_expg_scaled_data[1] = &ufunc__lanczos_sum_expg_scaled_ptr[2*1]
+_lanczos_sum_expg_scaled = np.PyUFunc_FromFuncAndData(ufunc__lanczos_sum_expg_scaled_loops, ufunc__lanczos_sum_expg_scaled_data, ufunc__lanczos_sum_expg_scaled_types, 2, 1, 1, 0, "_lanczos_sum_expg_scaled", ufunc__lanczos_sum_expg_scaled_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_cdf_loops[2]
+cdef void *ufunc__landau_cdf_ptr[4]
+cdef void *ufunc__landau_cdf_data[2]
+cdef char ufunc__landau_cdf_types[8]
+cdef char *ufunc__landau_cdf_doc = (
+    "_landau_cdf(x, loc, scale)\n"
+    "\n"
+    "Cumulative distribution function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_cdf_types[0] = NPY_FLOAT
+ufunc__landau_cdf_types[1] = NPY_FLOAT
+ufunc__landau_cdf_types[2] = NPY_FLOAT
+ufunc__landau_cdf_types[3] = NPY_FLOAT
+ufunc__landau_cdf_types[4] = NPY_DOUBLE
+ufunc__landau_cdf_types[5] = NPY_DOUBLE
+ufunc__landau_cdf_types[6] = NPY_DOUBLE
+ufunc__landau_cdf_types[7] = NPY_DOUBLE
+ufunc__landau_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_cdf_float
+ufunc__landau_cdf_ptr[2*0+1] = ("_landau_cdf")
+ufunc__landau_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_cdf_double
+ufunc__landau_cdf_ptr[2*1+1] = ("_landau_cdf")
+ufunc__landau_cdf_data[0] = &ufunc__landau_cdf_ptr[2*0]
+ufunc__landau_cdf_data[1] = &ufunc__landau_cdf_ptr[2*1]
+_landau_cdf = np.PyUFunc_FromFuncAndData(ufunc__landau_cdf_loops, ufunc__landau_cdf_data, ufunc__landau_cdf_types, 2, 3, 1, 0, "_landau_cdf", ufunc__landau_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_isf_loops[2]
+cdef void *ufunc__landau_isf_ptr[4]
+cdef void *ufunc__landau_isf_data[2]
+cdef char ufunc__landau_isf_types[8]
+cdef char *ufunc__landau_isf_doc = (
+    "_landau_isf(p, loc, scale)\n"
+    "\n"
+    "Inverse survival function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Real-valued argument between 0 and 1\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_isf_types[0] = NPY_FLOAT
+ufunc__landau_isf_types[1] = NPY_FLOAT
+ufunc__landau_isf_types[2] = NPY_FLOAT
+ufunc__landau_isf_types[3] = NPY_FLOAT
+ufunc__landau_isf_types[4] = NPY_DOUBLE
+ufunc__landau_isf_types[5] = NPY_DOUBLE
+ufunc__landau_isf_types[6] = NPY_DOUBLE
+ufunc__landau_isf_types[7] = NPY_DOUBLE
+ufunc__landau_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_isf_float
+ufunc__landau_isf_ptr[2*0+1] = ("_landau_isf")
+ufunc__landau_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_isf_double
+ufunc__landau_isf_ptr[2*1+1] = ("_landau_isf")
+ufunc__landau_isf_data[0] = &ufunc__landau_isf_ptr[2*0]
+ufunc__landau_isf_data[1] = &ufunc__landau_isf_ptr[2*1]
+_landau_isf = np.PyUFunc_FromFuncAndData(ufunc__landau_isf_loops, ufunc__landau_isf_data, ufunc__landau_isf_types, 2, 3, 1, 0, "_landau_isf", ufunc__landau_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_pdf_loops[2]
+cdef void *ufunc__landau_pdf_ptr[4]
+cdef void *ufunc__landau_pdf_data[2]
+cdef char ufunc__landau_pdf_types[8]
+cdef char *ufunc__landau_pdf_doc = (
+    "_landau_pdf(x, loc, scale)\n"
+    "\n"
+    "Probability density function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_pdf_types[0] = NPY_FLOAT
+ufunc__landau_pdf_types[1] = NPY_FLOAT
+ufunc__landau_pdf_types[2] = NPY_FLOAT
+ufunc__landau_pdf_types[3] = NPY_FLOAT
+ufunc__landau_pdf_types[4] = NPY_DOUBLE
+ufunc__landau_pdf_types[5] = NPY_DOUBLE
+ufunc__landau_pdf_types[6] = NPY_DOUBLE
+ufunc__landau_pdf_types[7] = NPY_DOUBLE
+ufunc__landau_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_pdf_float
+ufunc__landau_pdf_ptr[2*0+1] = ("_landau_pdf")
+ufunc__landau_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_pdf_double
+ufunc__landau_pdf_ptr[2*1+1] = ("_landau_pdf")
+ufunc__landau_pdf_data[0] = &ufunc__landau_pdf_ptr[2*0]
+ufunc__landau_pdf_data[1] = &ufunc__landau_pdf_ptr[2*1]
+_landau_pdf = np.PyUFunc_FromFuncAndData(ufunc__landau_pdf_loops, ufunc__landau_pdf_data, ufunc__landau_pdf_types, 2, 3, 1, 0, "_landau_pdf", ufunc__landau_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_ppf_loops[2]
+cdef void *ufunc__landau_ppf_ptr[4]
+cdef void *ufunc__landau_ppf_data[2]
+cdef char ufunc__landau_ppf_types[8]
+cdef char *ufunc__landau_ppf_doc = (
+    "_landau_ppf(p, loc, scale)\n"
+    "\n"
+    "Percent point function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Real-valued argument between 0 and 1\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_ppf_types[0] = NPY_FLOAT
+ufunc__landau_ppf_types[1] = NPY_FLOAT
+ufunc__landau_ppf_types[2] = NPY_FLOAT
+ufunc__landau_ppf_types[3] = NPY_FLOAT
+ufunc__landau_ppf_types[4] = NPY_DOUBLE
+ufunc__landau_ppf_types[5] = NPY_DOUBLE
+ufunc__landau_ppf_types[6] = NPY_DOUBLE
+ufunc__landau_ppf_types[7] = NPY_DOUBLE
+ufunc__landau_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_ppf_float
+ufunc__landau_ppf_ptr[2*0+1] = ("_landau_ppf")
+ufunc__landau_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_ppf_double
+ufunc__landau_ppf_ptr[2*1+1] = ("_landau_ppf")
+ufunc__landau_ppf_data[0] = &ufunc__landau_ppf_ptr[2*0]
+ufunc__landau_ppf_data[1] = &ufunc__landau_ppf_ptr[2*1]
+_landau_ppf = np.PyUFunc_FromFuncAndData(ufunc__landau_ppf_loops, ufunc__landau_ppf_data, ufunc__landau_ppf_types, 2, 3, 1, 0, "_landau_ppf", ufunc__landau_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__landau_sf_loops[2]
+cdef void *ufunc__landau_sf_ptr[4]
+cdef void *ufunc__landau_sf_data[2]
+cdef char ufunc__landau_sf_types[8]
+cdef char *ufunc__landau_sf_doc = (
+    "_landau_sf(x, loc, scale)\n"
+    "\n"
+    "Survival function of the Landau distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "loc : array_like\n"
+    "    Real-valued distribution location\n"
+    "scale : array_like\n"
+    "    Positive, real-valued distribution scale\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__landau_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__landau_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__landau_sf_types[0] = NPY_FLOAT
+ufunc__landau_sf_types[1] = NPY_FLOAT
+ufunc__landau_sf_types[2] = NPY_FLOAT
+ufunc__landau_sf_types[3] = NPY_FLOAT
+ufunc__landau_sf_types[4] = NPY_DOUBLE
+ufunc__landau_sf_types[5] = NPY_DOUBLE
+ufunc__landau_sf_types[6] = NPY_DOUBLE
+ufunc__landau_sf_types[7] = NPY_DOUBLE
+ufunc__landau_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_landau_sf_float
+ufunc__landau_sf_ptr[2*0+1] = ("_landau_sf")
+ufunc__landau_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_landau_sf_double
+ufunc__landau_sf_ptr[2*1+1] = ("_landau_sf")
+ufunc__landau_sf_data[0] = &ufunc__landau_sf_ptr[2*0]
+ufunc__landau_sf_data[1] = &ufunc__landau_sf_ptr[2*1]
+_landau_sf = np.PyUFunc_FromFuncAndData(ufunc__landau_sf_loops, ufunc__landau_sf_data, ufunc__landau_sf_types, 2, 3, 1, 0, "_landau_sf", ufunc__landau_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__lgam1p_loops[2]
+cdef void *ufunc__lgam1p_ptr[4]
+cdef void *ufunc__lgam1p_data[2]
+cdef char ufunc__lgam1p_types[4]
+cdef char *ufunc__lgam1p_doc = (
+    "Internal function, do not use.")
+ufunc__lgam1p_loops[0] = loop_d_d__As_f_f
+ufunc__lgam1p_loops[1] = loop_d_d__As_d_d
+ufunc__lgam1p_types[0] = NPY_FLOAT
+ufunc__lgam1p_types[1] = NPY_FLOAT
+ufunc__lgam1p_types[2] = NPY_DOUBLE
+ufunc__lgam1p_types[3] = NPY_DOUBLE
+ufunc__lgam1p_ptr[2*0] = _func_cephes_lgam1p
+ufunc__lgam1p_ptr[2*0+1] = ("_lgam1p")
+ufunc__lgam1p_ptr[2*1] = _func_cephes_lgam1p
+ufunc__lgam1p_ptr[2*1+1] = ("_lgam1p")
+ufunc__lgam1p_data[0] = &ufunc__lgam1p_ptr[2*0]
+ufunc__lgam1p_data[1] = &ufunc__lgam1p_ptr[2*1]
+_lgam1p = np.PyUFunc_FromFuncAndData(ufunc__lgam1p_loops, ufunc__lgam1p_data, ufunc__lgam1p_types, 2, 1, 1, 0, "_lgam1p", ufunc__lgam1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__log1pmx_loops[2]
+cdef void *ufunc__log1pmx_ptr[4]
+cdef void *ufunc__log1pmx_data[2]
+cdef char ufunc__log1pmx_types[4]
+cdef char *ufunc__log1pmx_doc = (
+    "Internal function, do not use.")
+ufunc__log1pmx_loops[0] = loop_d_d__As_f_f
+ufunc__log1pmx_loops[1] = loop_d_d__As_d_d
+ufunc__log1pmx_types[0] = NPY_FLOAT
+ufunc__log1pmx_types[1] = NPY_FLOAT
+ufunc__log1pmx_types[2] = NPY_DOUBLE
+ufunc__log1pmx_types[3] = NPY_DOUBLE
+ufunc__log1pmx_ptr[2*0] = _func_cephes_log1pmx
+ufunc__log1pmx_ptr[2*0+1] = ("_log1pmx")
+ufunc__log1pmx_ptr[2*1] = _func_cephes_log1pmx
+ufunc__log1pmx_ptr[2*1+1] = ("_log1pmx")
+ufunc__log1pmx_data[0] = &ufunc__log1pmx_ptr[2*0]
+ufunc__log1pmx_data[1] = &ufunc__log1pmx_ptr[2*1]
+_log1pmx = np.PyUFunc_FromFuncAndData(ufunc__log1pmx_loops, ufunc__log1pmx_data, ufunc__log1pmx_types, 2, 1, 1, 0, "_log1pmx", ufunc__log1pmx_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_cdf_loops[2]
+cdef void *ufunc__nbinom_cdf_ptr[4]
+cdef void *ufunc__nbinom_cdf_data[2]
+cdef char ufunc__nbinom_cdf_types[8]
+cdef char *ufunc__nbinom_cdf_doc = (
+    "_nbinom_cdf(x, r, p)\n"
+    "\n"
+    "Cumulative density function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_cdf_types[0] = NPY_FLOAT
+ufunc__nbinom_cdf_types[1] = NPY_FLOAT
+ufunc__nbinom_cdf_types[2] = NPY_FLOAT
+ufunc__nbinom_cdf_types[3] = NPY_FLOAT
+ufunc__nbinom_cdf_types[4] = NPY_DOUBLE
+ufunc__nbinom_cdf_types[5] = NPY_DOUBLE
+ufunc__nbinom_cdf_types[6] = NPY_DOUBLE
+ufunc__nbinom_cdf_types[7] = NPY_DOUBLE
+ufunc__nbinom_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_cdf_float
+ufunc__nbinom_cdf_ptr[2*0+1] = ("_nbinom_cdf")
+ufunc__nbinom_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_cdf_double
+ufunc__nbinom_cdf_ptr[2*1+1] = ("_nbinom_cdf")
+ufunc__nbinom_cdf_data[0] = &ufunc__nbinom_cdf_ptr[2*0]
+ufunc__nbinom_cdf_data[1] = &ufunc__nbinom_cdf_ptr[2*1]
+_nbinom_cdf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_cdf_loops, ufunc__nbinom_cdf_data, ufunc__nbinom_cdf_types, 2, 3, 1, 0, "_nbinom_cdf", ufunc__nbinom_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_isf_loops[2]
+cdef void *ufunc__nbinom_isf_ptr[4]
+cdef void *ufunc__nbinom_isf_data[2]
+cdef char ufunc__nbinom_isf_types[8]
+cdef char *ufunc__nbinom_isf_doc = (
+    "_nbinom_isf(x, r, p)\n"
+    "\n"
+    "Inverse survival function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_isf_types[0] = NPY_FLOAT
+ufunc__nbinom_isf_types[1] = NPY_FLOAT
+ufunc__nbinom_isf_types[2] = NPY_FLOAT
+ufunc__nbinom_isf_types[3] = NPY_FLOAT
+ufunc__nbinom_isf_types[4] = NPY_DOUBLE
+ufunc__nbinom_isf_types[5] = NPY_DOUBLE
+ufunc__nbinom_isf_types[6] = NPY_DOUBLE
+ufunc__nbinom_isf_types[7] = NPY_DOUBLE
+ufunc__nbinom_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_isf_float
+ufunc__nbinom_isf_ptr[2*0+1] = ("_nbinom_isf")
+ufunc__nbinom_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_isf_double
+ufunc__nbinom_isf_ptr[2*1+1] = ("_nbinom_isf")
+ufunc__nbinom_isf_data[0] = &ufunc__nbinom_isf_ptr[2*0]
+ufunc__nbinom_isf_data[1] = &ufunc__nbinom_isf_ptr[2*1]
+_nbinom_isf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_isf_loops, ufunc__nbinom_isf_data, ufunc__nbinom_isf_types, 2, 3, 1, 0, "_nbinom_isf", ufunc__nbinom_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_kurtosis_excess_loops[2]
+cdef void *ufunc__nbinom_kurtosis_excess_ptr[4]
+cdef void *ufunc__nbinom_kurtosis_excess_data[2]
+cdef char ufunc__nbinom_kurtosis_excess_types[6]
+cdef char *ufunc__nbinom_kurtosis_excess_doc = (
+    "_nbinom_kurtosis_excess(r, p)\n"
+    "\n"
+    "Kurtosis excess of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_kurtosis_excess_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_kurtosis_excess_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_kurtosis_excess_types[0] = NPY_FLOAT
+ufunc__nbinom_kurtosis_excess_types[1] = NPY_FLOAT
+ufunc__nbinom_kurtosis_excess_types[2] = NPY_FLOAT
+ufunc__nbinom_kurtosis_excess_types[3] = NPY_DOUBLE
+ufunc__nbinom_kurtosis_excess_types[4] = NPY_DOUBLE
+ufunc__nbinom_kurtosis_excess_types[5] = NPY_DOUBLE
+ufunc__nbinom_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_kurtosis_excess_float
+ufunc__nbinom_kurtosis_excess_ptr[2*0+1] = ("_nbinom_kurtosis_excess")
+ufunc__nbinom_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_kurtosis_excess_double
+ufunc__nbinom_kurtosis_excess_ptr[2*1+1] = ("_nbinom_kurtosis_excess")
+ufunc__nbinom_kurtosis_excess_data[0] = &ufunc__nbinom_kurtosis_excess_ptr[2*0]
+ufunc__nbinom_kurtosis_excess_data[1] = &ufunc__nbinom_kurtosis_excess_ptr[2*1]
+_nbinom_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__nbinom_kurtosis_excess_loops, ufunc__nbinom_kurtosis_excess_data, ufunc__nbinom_kurtosis_excess_types, 2, 2, 1, 0, "_nbinom_kurtosis_excess", ufunc__nbinom_kurtosis_excess_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_mean_loops[2]
+cdef void *ufunc__nbinom_mean_ptr[4]
+cdef void *ufunc__nbinom_mean_data[2]
+cdef char ufunc__nbinom_mean_types[6]
+cdef char *ufunc__nbinom_mean_doc = (
+    "_nbinom_mean(r, p)\n"
+    "\n"
+    "Mean of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_mean_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_mean_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_mean_types[0] = NPY_FLOAT
+ufunc__nbinom_mean_types[1] = NPY_FLOAT
+ufunc__nbinom_mean_types[2] = NPY_FLOAT
+ufunc__nbinom_mean_types[3] = NPY_DOUBLE
+ufunc__nbinom_mean_types[4] = NPY_DOUBLE
+ufunc__nbinom_mean_types[5] = NPY_DOUBLE
+ufunc__nbinom_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_mean_float
+ufunc__nbinom_mean_ptr[2*0+1] = ("_nbinom_mean")
+ufunc__nbinom_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_mean_double
+ufunc__nbinom_mean_ptr[2*1+1] = ("_nbinom_mean")
+ufunc__nbinom_mean_data[0] = &ufunc__nbinom_mean_ptr[2*0]
+ufunc__nbinom_mean_data[1] = &ufunc__nbinom_mean_ptr[2*1]
+_nbinom_mean = np.PyUFunc_FromFuncAndData(ufunc__nbinom_mean_loops, ufunc__nbinom_mean_data, ufunc__nbinom_mean_types, 2, 2, 1, 0, "_nbinom_mean", ufunc__nbinom_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_pmf_loops[2]
+cdef void *ufunc__nbinom_pmf_ptr[4]
+cdef void *ufunc__nbinom_pmf_data[2]
+cdef char ufunc__nbinom_pmf_types[8]
+cdef char *ufunc__nbinom_pmf_doc = (
+    "_nbinom_pmf(x, r, p)\n"
+    "\n"
+    "Probability mass function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_pmf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_pmf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_pmf_types[0] = NPY_FLOAT
+ufunc__nbinom_pmf_types[1] = NPY_FLOAT
+ufunc__nbinom_pmf_types[2] = NPY_FLOAT
+ufunc__nbinom_pmf_types[3] = NPY_FLOAT
+ufunc__nbinom_pmf_types[4] = NPY_DOUBLE
+ufunc__nbinom_pmf_types[5] = NPY_DOUBLE
+ufunc__nbinom_pmf_types[6] = NPY_DOUBLE
+ufunc__nbinom_pmf_types[7] = NPY_DOUBLE
+ufunc__nbinom_pmf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_pmf_float
+ufunc__nbinom_pmf_ptr[2*0+1] = ("_nbinom_pmf")
+ufunc__nbinom_pmf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_pmf_double
+ufunc__nbinom_pmf_ptr[2*1+1] = ("_nbinom_pmf")
+ufunc__nbinom_pmf_data[0] = &ufunc__nbinom_pmf_ptr[2*0]
+ufunc__nbinom_pmf_data[1] = &ufunc__nbinom_pmf_ptr[2*1]
+_nbinom_pmf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_pmf_loops, ufunc__nbinom_pmf_data, ufunc__nbinom_pmf_types, 2, 3, 1, 0, "_nbinom_pmf", ufunc__nbinom_pmf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_ppf_loops[2]
+cdef void *ufunc__nbinom_ppf_ptr[4]
+cdef void *ufunc__nbinom_ppf_data[2]
+cdef char ufunc__nbinom_ppf_types[8]
+cdef char *ufunc__nbinom_ppf_doc = (
+    "_nbinom_ppf(x, r, p)\n"
+    "\n"
+    "Percent point function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_ppf_types[0] = NPY_FLOAT
+ufunc__nbinom_ppf_types[1] = NPY_FLOAT
+ufunc__nbinom_ppf_types[2] = NPY_FLOAT
+ufunc__nbinom_ppf_types[3] = NPY_FLOAT
+ufunc__nbinom_ppf_types[4] = NPY_DOUBLE
+ufunc__nbinom_ppf_types[5] = NPY_DOUBLE
+ufunc__nbinom_ppf_types[6] = NPY_DOUBLE
+ufunc__nbinom_ppf_types[7] = NPY_DOUBLE
+ufunc__nbinom_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_ppf_float
+ufunc__nbinom_ppf_ptr[2*0+1] = ("_nbinom_ppf")
+ufunc__nbinom_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_ppf_double
+ufunc__nbinom_ppf_ptr[2*1+1] = ("_nbinom_ppf")
+ufunc__nbinom_ppf_data[0] = &ufunc__nbinom_ppf_ptr[2*0]
+ufunc__nbinom_ppf_data[1] = &ufunc__nbinom_ppf_ptr[2*1]
+_nbinom_ppf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_ppf_loops, ufunc__nbinom_ppf_data, ufunc__nbinom_ppf_types, 2, 3, 1, 0, "_nbinom_ppf", ufunc__nbinom_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_sf_loops[2]
+cdef void *ufunc__nbinom_sf_ptr[4]
+cdef void *ufunc__nbinom_sf_data[2]
+cdef char ufunc__nbinom_sf_types[8]
+cdef char *ufunc__nbinom_sf_doc = (
+    "_nbinom_sf(x, r, p)\n"
+    "\n"
+    "Survival function of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nbinom_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nbinom_sf_types[0] = NPY_FLOAT
+ufunc__nbinom_sf_types[1] = NPY_FLOAT
+ufunc__nbinom_sf_types[2] = NPY_FLOAT
+ufunc__nbinom_sf_types[3] = NPY_FLOAT
+ufunc__nbinom_sf_types[4] = NPY_DOUBLE
+ufunc__nbinom_sf_types[5] = NPY_DOUBLE
+ufunc__nbinom_sf_types[6] = NPY_DOUBLE
+ufunc__nbinom_sf_types[7] = NPY_DOUBLE
+ufunc__nbinom_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_sf_float
+ufunc__nbinom_sf_ptr[2*0+1] = ("_nbinom_sf")
+ufunc__nbinom_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_sf_double
+ufunc__nbinom_sf_ptr[2*1+1] = ("_nbinom_sf")
+ufunc__nbinom_sf_data[0] = &ufunc__nbinom_sf_ptr[2*0]
+ufunc__nbinom_sf_data[1] = &ufunc__nbinom_sf_ptr[2*1]
+_nbinom_sf = np.PyUFunc_FromFuncAndData(ufunc__nbinom_sf_loops, ufunc__nbinom_sf_data, ufunc__nbinom_sf_types, 2, 3, 1, 0, "_nbinom_sf", ufunc__nbinom_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_skewness_loops[2]
+cdef void *ufunc__nbinom_skewness_ptr[4]
+cdef void *ufunc__nbinom_skewness_data[2]
+cdef char ufunc__nbinom_skewness_types[6]
+cdef char *ufunc__nbinom_skewness_doc = (
+    "_nbinom_skewness(r, p)\n"
+    "\n"
+    "Skewness of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_skewness_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_skewness_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_skewness_types[0] = NPY_FLOAT
+ufunc__nbinom_skewness_types[1] = NPY_FLOAT
+ufunc__nbinom_skewness_types[2] = NPY_FLOAT
+ufunc__nbinom_skewness_types[3] = NPY_DOUBLE
+ufunc__nbinom_skewness_types[4] = NPY_DOUBLE
+ufunc__nbinom_skewness_types[5] = NPY_DOUBLE
+ufunc__nbinom_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_skewness_float
+ufunc__nbinom_skewness_ptr[2*0+1] = ("_nbinom_skewness")
+ufunc__nbinom_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_skewness_double
+ufunc__nbinom_skewness_ptr[2*1+1] = ("_nbinom_skewness")
+ufunc__nbinom_skewness_data[0] = &ufunc__nbinom_skewness_ptr[2*0]
+ufunc__nbinom_skewness_data[1] = &ufunc__nbinom_skewness_ptr[2*1]
+_nbinom_skewness = np.PyUFunc_FromFuncAndData(ufunc__nbinom_skewness_loops, ufunc__nbinom_skewness_data, ufunc__nbinom_skewness_types, 2, 2, 1, 0, "_nbinom_skewness", ufunc__nbinom_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nbinom_variance_loops[2]
+cdef void *ufunc__nbinom_variance_ptr[4]
+cdef void *ufunc__nbinom_variance_data[2]
+cdef char ufunc__nbinom_variance_types[6]
+cdef char *ufunc__nbinom_variance_doc = (
+    "_nbinom_variance(r, p)\n"
+    "\n"
+    "Variance of negative binomial distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "r : array_like\n"
+    "    Positive, integer-valued parameter\n"
+    "p : array_like\n"
+    "    Positive, real-valued parameter\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nbinom_variance_loops[0] = loop_f_ff__As_ff_f
+ufunc__nbinom_variance_loops[1] = loop_d_dd__As_dd_d
+ufunc__nbinom_variance_types[0] = NPY_FLOAT
+ufunc__nbinom_variance_types[1] = NPY_FLOAT
+ufunc__nbinom_variance_types[2] = NPY_FLOAT
+ufunc__nbinom_variance_types[3] = NPY_DOUBLE
+ufunc__nbinom_variance_types[4] = NPY_DOUBLE
+ufunc__nbinom_variance_types[5] = NPY_DOUBLE
+ufunc__nbinom_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_nbinom_variance_float
+ufunc__nbinom_variance_ptr[2*0+1] = ("_nbinom_variance")
+ufunc__nbinom_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_nbinom_variance_double
+ufunc__nbinom_variance_ptr[2*1+1] = ("_nbinom_variance")
+ufunc__nbinom_variance_data[0] = &ufunc__nbinom_variance_ptr[2*0]
+ufunc__nbinom_variance_data[1] = &ufunc__nbinom_variance_ptr[2*1]
+_nbinom_variance = np.PyUFunc_FromFuncAndData(ufunc__nbinom_variance_loops, ufunc__nbinom_variance_data, ufunc__nbinom_variance_types, 2, 2, 1, 0, "_nbinom_variance", ufunc__nbinom_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_isf_loops[2]
+cdef void *ufunc__ncf_isf_ptr[4]
+cdef void *ufunc__ncf_isf_data[2]
+cdef char ufunc__ncf_isf_types[10]
+cdef char *ufunc__ncf_isf_doc = (
+    "_ncf_isf(x, v1, v2, l)\n"
+    "\n"
+    "Inverse survival function of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_isf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__ncf_isf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__ncf_isf_types[0] = NPY_FLOAT
+ufunc__ncf_isf_types[1] = NPY_FLOAT
+ufunc__ncf_isf_types[2] = NPY_FLOAT
+ufunc__ncf_isf_types[3] = NPY_FLOAT
+ufunc__ncf_isf_types[4] = NPY_FLOAT
+ufunc__ncf_isf_types[5] = NPY_DOUBLE
+ufunc__ncf_isf_types[6] = NPY_DOUBLE
+ufunc__ncf_isf_types[7] = NPY_DOUBLE
+ufunc__ncf_isf_types[8] = NPY_DOUBLE
+ufunc__ncf_isf_types[9] = NPY_DOUBLE
+ufunc__ncf_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_isf_float
+ufunc__ncf_isf_ptr[2*0+1] = ("_ncf_isf")
+ufunc__ncf_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_isf_double
+ufunc__ncf_isf_ptr[2*1+1] = ("_ncf_isf")
+ufunc__ncf_isf_data[0] = &ufunc__ncf_isf_ptr[2*0]
+ufunc__ncf_isf_data[1] = &ufunc__ncf_isf_ptr[2*1]
+_ncf_isf = np.PyUFunc_FromFuncAndData(ufunc__ncf_isf_loops, ufunc__ncf_isf_data, ufunc__ncf_isf_types, 2, 4, 1, 0, "_ncf_isf", ufunc__ncf_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_kurtosis_excess_loops[2]
+cdef void *ufunc__ncf_kurtosis_excess_ptr[4]
+cdef void *ufunc__ncf_kurtosis_excess_data[2]
+cdef char ufunc__ncf_kurtosis_excess_types[8]
+cdef char *ufunc__ncf_kurtosis_excess_doc = (
+    "_ncf_kurtosis_excess(v1, v2, l)\n"
+    "\n"
+    "Kurtosis excess of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_kurtosis_excess_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_kurtosis_excess_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_kurtosis_excess_types[0] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[1] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[2] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[3] = NPY_FLOAT
+ufunc__ncf_kurtosis_excess_types[4] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_types[5] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_types[6] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_types[7] = NPY_DOUBLE
+ufunc__ncf_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_kurtosis_excess_float
+ufunc__ncf_kurtosis_excess_ptr[2*0+1] = ("_ncf_kurtosis_excess")
+ufunc__ncf_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_kurtosis_excess_double
+ufunc__ncf_kurtosis_excess_ptr[2*1+1] = ("_ncf_kurtosis_excess")
+ufunc__ncf_kurtosis_excess_data[0] = &ufunc__ncf_kurtosis_excess_ptr[2*0]
+ufunc__ncf_kurtosis_excess_data[1] = &ufunc__ncf_kurtosis_excess_ptr[2*1]
+_ncf_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__ncf_kurtosis_excess_loops, ufunc__ncf_kurtosis_excess_data, ufunc__ncf_kurtosis_excess_types, 2, 3, 1, 0, "_ncf_kurtosis_excess", ufunc__ncf_kurtosis_excess_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_mean_loops[2]
+cdef void *ufunc__ncf_mean_ptr[4]
+cdef void *ufunc__ncf_mean_data[2]
+cdef char ufunc__ncf_mean_types[8]
+cdef char *ufunc__ncf_mean_doc = (
+    "_ncf_mean(v1, v2, l)\n"
+    "\n"
+    "Mean of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_mean_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_mean_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_mean_types[0] = NPY_FLOAT
+ufunc__ncf_mean_types[1] = NPY_FLOAT
+ufunc__ncf_mean_types[2] = NPY_FLOAT
+ufunc__ncf_mean_types[3] = NPY_FLOAT
+ufunc__ncf_mean_types[4] = NPY_DOUBLE
+ufunc__ncf_mean_types[5] = NPY_DOUBLE
+ufunc__ncf_mean_types[6] = NPY_DOUBLE
+ufunc__ncf_mean_types[7] = NPY_DOUBLE
+ufunc__ncf_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_mean_float
+ufunc__ncf_mean_ptr[2*0+1] = ("_ncf_mean")
+ufunc__ncf_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_mean_double
+ufunc__ncf_mean_ptr[2*1+1] = ("_ncf_mean")
+ufunc__ncf_mean_data[0] = &ufunc__ncf_mean_ptr[2*0]
+ufunc__ncf_mean_data[1] = &ufunc__ncf_mean_ptr[2*1]
+_ncf_mean = np.PyUFunc_FromFuncAndData(ufunc__ncf_mean_loops, ufunc__ncf_mean_data, ufunc__ncf_mean_types, 2, 3, 1, 0, "_ncf_mean", ufunc__ncf_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_pdf_loops[2]
+cdef void *ufunc__ncf_pdf_ptr[4]
+cdef void *ufunc__ncf_pdf_data[2]
+cdef char ufunc__ncf_pdf_types[10]
+cdef char *ufunc__ncf_pdf_doc = (
+    "_ncf_pdf(x, v1, v2, l)\n"
+    "\n"
+    "Probability density function of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_pdf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__ncf_pdf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__ncf_pdf_types[0] = NPY_FLOAT
+ufunc__ncf_pdf_types[1] = NPY_FLOAT
+ufunc__ncf_pdf_types[2] = NPY_FLOAT
+ufunc__ncf_pdf_types[3] = NPY_FLOAT
+ufunc__ncf_pdf_types[4] = NPY_FLOAT
+ufunc__ncf_pdf_types[5] = NPY_DOUBLE
+ufunc__ncf_pdf_types[6] = NPY_DOUBLE
+ufunc__ncf_pdf_types[7] = NPY_DOUBLE
+ufunc__ncf_pdf_types[8] = NPY_DOUBLE
+ufunc__ncf_pdf_types[9] = NPY_DOUBLE
+ufunc__ncf_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_pdf_float
+ufunc__ncf_pdf_ptr[2*0+1] = ("_ncf_pdf")
+ufunc__ncf_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_pdf_double
+ufunc__ncf_pdf_ptr[2*1+1] = ("_ncf_pdf")
+ufunc__ncf_pdf_data[0] = &ufunc__ncf_pdf_ptr[2*0]
+ufunc__ncf_pdf_data[1] = &ufunc__ncf_pdf_ptr[2*1]
+_ncf_pdf = np.PyUFunc_FromFuncAndData(ufunc__ncf_pdf_loops, ufunc__ncf_pdf_data, ufunc__ncf_pdf_types, 2, 4, 1, 0, "_ncf_pdf", ufunc__ncf_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_sf_loops[2]
+cdef void *ufunc__ncf_sf_ptr[4]
+cdef void *ufunc__ncf_sf_data[2]
+cdef char ufunc__ncf_sf_types[10]
+cdef char *ufunc__ncf_sf_doc = (
+    "_ncf_sf(x, v1, v2, l)\n"
+    "\n"
+    "Survival function of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_sf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__ncf_sf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__ncf_sf_types[0] = NPY_FLOAT
+ufunc__ncf_sf_types[1] = NPY_FLOAT
+ufunc__ncf_sf_types[2] = NPY_FLOAT
+ufunc__ncf_sf_types[3] = NPY_FLOAT
+ufunc__ncf_sf_types[4] = NPY_FLOAT
+ufunc__ncf_sf_types[5] = NPY_DOUBLE
+ufunc__ncf_sf_types[6] = NPY_DOUBLE
+ufunc__ncf_sf_types[7] = NPY_DOUBLE
+ufunc__ncf_sf_types[8] = NPY_DOUBLE
+ufunc__ncf_sf_types[9] = NPY_DOUBLE
+ufunc__ncf_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_sf_float
+ufunc__ncf_sf_ptr[2*0+1] = ("_ncf_sf")
+ufunc__ncf_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_sf_double
+ufunc__ncf_sf_ptr[2*1+1] = ("_ncf_sf")
+ufunc__ncf_sf_data[0] = &ufunc__ncf_sf_ptr[2*0]
+ufunc__ncf_sf_data[1] = &ufunc__ncf_sf_ptr[2*1]
+_ncf_sf = np.PyUFunc_FromFuncAndData(ufunc__ncf_sf_loops, ufunc__ncf_sf_data, ufunc__ncf_sf_types, 2, 4, 1, 0, "_ncf_sf", ufunc__ncf_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_skewness_loops[2]
+cdef void *ufunc__ncf_skewness_ptr[4]
+cdef void *ufunc__ncf_skewness_data[2]
+cdef char ufunc__ncf_skewness_types[8]
+cdef char *ufunc__ncf_skewness_doc = (
+    "_ncf_skewness(v1, v2, l)\n"
+    "\n"
+    "Skewness of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_skewness_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_skewness_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_skewness_types[0] = NPY_FLOAT
+ufunc__ncf_skewness_types[1] = NPY_FLOAT
+ufunc__ncf_skewness_types[2] = NPY_FLOAT
+ufunc__ncf_skewness_types[3] = NPY_FLOAT
+ufunc__ncf_skewness_types[4] = NPY_DOUBLE
+ufunc__ncf_skewness_types[5] = NPY_DOUBLE
+ufunc__ncf_skewness_types[6] = NPY_DOUBLE
+ufunc__ncf_skewness_types[7] = NPY_DOUBLE
+ufunc__ncf_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_skewness_float
+ufunc__ncf_skewness_ptr[2*0+1] = ("_ncf_skewness")
+ufunc__ncf_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_skewness_double
+ufunc__ncf_skewness_ptr[2*1+1] = ("_ncf_skewness")
+ufunc__ncf_skewness_data[0] = &ufunc__ncf_skewness_ptr[2*0]
+ufunc__ncf_skewness_data[1] = &ufunc__ncf_skewness_ptr[2*1]
+_ncf_skewness = np.PyUFunc_FromFuncAndData(ufunc__ncf_skewness_loops, ufunc__ncf_skewness_data, ufunc__ncf_skewness_types, 2, 3, 1, 0, "_ncf_skewness", ufunc__ncf_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncf_variance_loops[2]
+cdef void *ufunc__ncf_variance_ptr[4]
+cdef void *ufunc__ncf_variance_data[2]
+cdef char ufunc__ncf_variance_types[8]
+cdef char *ufunc__ncf_variance_doc = (
+    "_ncf_variance(v1, v2, l)\n"
+    "\n"
+    "Variance of noncentral F-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v1, v2, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncf_variance_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncf_variance_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncf_variance_types[0] = NPY_FLOAT
+ufunc__ncf_variance_types[1] = NPY_FLOAT
+ufunc__ncf_variance_types[2] = NPY_FLOAT
+ufunc__ncf_variance_types[3] = NPY_FLOAT
+ufunc__ncf_variance_types[4] = NPY_DOUBLE
+ufunc__ncf_variance_types[5] = NPY_DOUBLE
+ufunc__ncf_variance_types[6] = NPY_DOUBLE
+ufunc__ncf_variance_types[7] = NPY_DOUBLE
+ufunc__ncf_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_variance_float
+ufunc__ncf_variance_ptr[2*0+1] = ("_ncf_variance")
+ufunc__ncf_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_variance_double
+ufunc__ncf_variance_ptr[2*1+1] = ("_ncf_variance")
+ufunc__ncf_variance_data[0] = &ufunc__ncf_variance_ptr[2*0]
+ufunc__ncf_variance_data[1] = &ufunc__ncf_variance_ptr[2*1]
+_ncf_variance = np.PyUFunc_FromFuncAndData(ufunc__ncf_variance_loops, ufunc__ncf_variance_data, ufunc__ncf_variance_types, 2, 3, 1, 0, "_ncf_variance", ufunc__ncf_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_isf_loops[2]
+cdef void *ufunc__nct_isf_ptr[4]
+cdef void *ufunc__nct_isf_data[2]
+cdef char ufunc__nct_isf_types[8]
+cdef char *ufunc__nct_isf_doc = (
+    "_nct_isf(x, v, l)\n"
+    "\n"
+    "Inverse survival function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_isf_types[0] = NPY_FLOAT
+ufunc__nct_isf_types[1] = NPY_FLOAT
+ufunc__nct_isf_types[2] = NPY_FLOAT
+ufunc__nct_isf_types[3] = NPY_FLOAT
+ufunc__nct_isf_types[4] = NPY_DOUBLE
+ufunc__nct_isf_types[5] = NPY_DOUBLE
+ufunc__nct_isf_types[6] = NPY_DOUBLE
+ufunc__nct_isf_types[7] = NPY_DOUBLE
+ufunc__nct_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_isf_float
+ufunc__nct_isf_ptr[2*0+1] = ("_nct_isf")
+ufunc__nct_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_isf_double
+ufunc__nct_isf_ptr[2*1+1] = ("_nct_isf")
+ufunc__nct_isf_data[0] = &ufunc__nct_isf_ptr[2*0]
+ufunc__nct_isf_data[1] = &ufunc__nct_isf_ptr[2*1]
+_nct_isf = np.PyUFunc_FromFuncAndData(ufunc__nct_isf_loops, ufunc__nct_isf_data, ufunc__nct_isf_types, 2, 3, 1, 0, "_nct_isf", ufunc__nct_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_kurtosis_excess_loops[2]
+cdef void *ufunc__nct_kurtosis_excess_ptr[4]
+cdef void *ufunc__nct_kurtosis_excess_data[2]
+cdef char ufunc__nct_kurtosis_excess_types[6]
+cdef char *ufunc__nct_kurtosis_excess_doc = (
+    "_nct_kurtosis_excess(v, l)\n"
+    "\n"
+    "Kurtosis excess of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_kurtosis_excess_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_kurtosis_excess_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_kurtosis_excess_types[0] = NPY_FLOAT
+ufunc__nct_kurtosis_excess_types[1] = NPY_FLOAT
+ufunc__nct_kurtosis_excess_types[2] = NPY_FLOAT
+ufunc__nct_kurtosis_excess_types[3] = NPY_DOUBLE
+ufunc__nct_kurtosis_excess_types[4] = NPY_DOUBLE
+ufunc__nct_kurtosis_excess_types[5] = NPY_DOUBLE
+ufunc__nct_kurtosis_excess_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_kurtosis_excess_float
+ufunc__nct_kurtosis_excess_ptr[2*0+1] = ("_nct_kurtosis_excess")
+ufunc__nct_kurtosis_excess_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_kurtosis_excess_double
+ufunc__nct_kurtosis_excess_ptr[2*1+1] = ("_nct_kurtosis_excess")
+ufunc__nct_kurtosis_excess_data[0] = &ufunc__nct_kurtosis_excess_ptr[2*0]
+ufunc__nct_kurtosis_excess_data[1] = &ufunc__nct_kurtosis_excess_ptr[2*1]
+_nct_kurtosis_excess = np.PyUFunc_FromFuncAndData(ufunc__nct_kurtosis_excess_loops, ufunc__nct_kurtosis_excess_data, ufunc__nct_kurtosis_excess_types, 2, 2, 1, 0, "_nct_kurtosis_excess", ufunc__nct_kurtosis_excess_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_mean_loops[2]
+cdef void *ufunc__nct_mean_ptr[4]
+cdef void *ufunc__nct_mean_data[2]
+cdef char ufunc__nct_mean_types[6]
+cdef char *ufunc__nct_mean_doc = (
+    "_nct_mean(v, l)\n"
+    "\n"
+    "Mean of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_mean_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_mean_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_mean_types[0] = NPY_FLOAT
+ufunc__nct_mean_types[1] = NPY_FLOAT
+ufunc__nct_mean_types[2] = NPY_FLOAT
+ufunc__nct_mean_types[3] = NPY_DOUBLE
+ufunc__nct_mean_types[4] = NPY_DOUBLE
+ufunc__nct_mean_types[5] = NPY_DOUBLE
+ufunc__nct_mean_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_mean_float
+ufunc__nct_mean_ptr[2*0+1] = ("_nct_mean")
+ufunc__nct_mean_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_mean_double
+ufunc__nct_mean_ptr[2*1+1] = ("_nct_mean")
+ufunc__nct_mean_data[0] = &ufunc__nct_mean_ptr[2*0]
+ufunc__nct_mean_data[1] = &ufunc__nct_mean_ptr[2*1]
+_nct_mean = np.PyUFunc_FromFuncAndData(ufunc__nct_mean_loops, ufunc__nct_mean_data, ufunc__nct_mean_types, 2, 2, 1, 0, "_nct_mean", ufunc__nct_mean_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_pdf_loops[2]
+cdef void *ufunc__nct_pdf_ptr[4]
+cdef void *ufunc__nct_pdf_data[2]
+cdef char ufunc__nct_pdf_types[8]
+cdef char *ufunc__nct_pdf_doc = (
+    "_nct_pdf(x, v, l)\n"
+    "\n"
+    "Probability density function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_pdf_types[0] = NPY_FLOAT
+ufunc__nct_pdf_types[1] = NPY_FLOAT
+ufunc__nct_pdf_types[2] = NPY_FLOAT
+ufunc__nct_pdf_types[3] = NPY_FLOAT
+ufunc__nct_pdf_types[4] = NPY_DOUBLE
+ufunc__nct_pdf_types[5] = NPY_DOUBLE
+ufunc__nct_pdf_types[6] = NPY_DOUBLE
+ufunc__nct_pdf_types[7] = NPY_DOUBLE
+ufunc__nct_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_pdf_float
+ufunc__nct_pdf_ptr[2*0+1] = ("_nct_pdf")
+ufunc__nct_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_pdf_double
+ufunc__nct_pdf_ptr[2*1+1] = ("_nct_pdf")
+ufunc__nct_pdf_data[0] = &ufunc__nct_pdf_ptr[2*0]
+ufunc__nct_pdf_data[1] = &ufunc__nct_pdf_ptr[2*1]
+_nct_pdf = np.PyUFunc_FromFuncAndData(ufunc__nct_pdf_loops, ufunc__nct_pdf_data, ufunc__nct_pdf_types, 2, 3, 1, 0, "_nct_pdf", ufunc__nct_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_ppf_loops[2]
+cdef void *ufunc__nct_ppf_ptr[4]
+cdef void *ufunc__nct_ppf_data[2]
+cdef char ufunc__nct_ppf_types[8]
+cdef char *ufunc__nct_ppf_doc = (
+    "_nct_ppf(x, v, l)\n"
+    "\n"
+    "Percent point function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_ppf_types[0] = NPY_FLOAT
+ufunc__nct_ppf_types[1] = NPY_FLOAT
+ufunc__nct_ppf_types[2] = NPY_FLOAT
+ufunc__nct_ppf_types[3] = NPY_FLOAT
+ufunc__nct_ppf_types[4] = NPY_DOUBLE
+ufunc__nct_ppf_types[5] = NPY_DOUBLE
+ufunc__nct_ppf_types[6] = NPY_DOUBLE
+ufunc__nct_ppf_types[7] = NPY_DOUBLE
+ufunc__nct_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_ppf_float
+ufunc__nct_ppf_ptr[2*0+1] = ("_nct_ppf")
+ufunc__nct_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_ppf_double
+ufunc__nct_ppf_ptr[2*1+1] = ("_nct_ppf")
+ufunc__nct_ppf_data[0] = &ufunc__nct_ppf_ptr[2*0]
+ufunc__nct_ppf_data[1] = &ufunc__nct_ppf_ptr[2*1]
+_nct_ppf = np.PyUFunc_FromFuncAndData(ufunc__nct_ppf_loops, ufunc__nct_ppf_data, ufunc__nct_ppf_types, 2, 3, 1, 0, "_nct_ppf", ufunc__nct_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_sf_loops[2]
+cdef void *ufunc__nct_sf_ptr[4]
+cdef void *ufunc__nct_sf_data[2]
+cdef char ufunc__nct_sf_types[8]
+cdef char *ufunc__nct_sf_doc = (
+    "_nct_sf(x, v, l)\n"
+    "\n"
+    "Survival function of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__nct_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__nct_sf_types[0] = NPY_FLOAT
+ufunc__nct_sf_types[1] = NPY_FLOAT
+ufunc__nct_sf_types[2] = NPY_FLOAT
+ufunc__nct_sf_types[3] = NPY_FLOAT
+ufunc__nct_sf_types[4] = NPY_DOUBLE
+ufunc__nct_sf_types[5] = NPY_DOUBLE
+ufunc__nct_sf_types[6] = NPY_DOUBLE
+ufunc__nct_sf_types[7] = NPY_DOUBLE
+ufunc__nct_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_sf_float
+ufunc__nct_sf_ptr[2*0+1] = ("_nct_sf")
+ufunc__nct_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_sf_double
+ufunc__nct_sf_ptr[2*1+1] = ("_nct_sf")
+ufunc__nct_sf_data[0] = &ufunc__nct_sf_ptr[2*0]
+ufunc__nct_sf_data[1] = &ufunc__nct_sf_ptr[2*1]
+_nct_sf = np.PyUFunc_FromFuncAndData(ufunc__nct_sf_loops, ufunc__nct_sf_data, ufunc__nct_sf_types, 2, 3, 1, 0, "_nct_sf", ufunc__nct_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_skewness_loops[2]
+cdef void *ufunc__nct_skewness_ptr[4]
+cdef void *ufunc__nct_skewness_data[2]
+cdef char ufunc__nct_skewness_types[6]
+cdef char *ufunc__nct_skewness_doc = (
+    "_nct_skewness(v, l)\n"
+    "\n"
+    "Skewness of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_skewness_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_skewness_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_skewness_types[0] = NPY_FLOAT
+ufunc__nct_skewness_types[1] = NPY_FLOAT
+ufunc__nct_skewness_types[2] = NPY_FLOAT
+ufunc__nct_skewness_types[3] = NPY_DOUBLE
+ufunc__nct_skewness_types[4] = NPY_DOUBLE
+ufunc__nct_skewness_types[5] = NPY_DOUBLE
+ufunc__nct_skewness_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_skewness_float
+ufunc__nct_skewness_ptr[2*0+1] = ("_nct_skewness")
+ufunc__nct_skewness_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_skewness_double
+ufunc__nct_skewness_ptr[2*1+1] = ("_nct_skewness")
+ufunc__nct_skewness_data[0] = &ufunc__nct_skewness_ptr[2*0]
+ufunc__nct_skewness_data[1] = &ufunc__nct_skewness_ptr[2*1]
+_nct_skewness = np.PyUFunc_FromFuncAndData(ufunc__nct_skewness_loops, ufunc__nct_skewness_data, ufunc__nct_skewness_types, 2, 2, 1, 0, "_nct_skewness", ufunc__nct_skewness_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__nct_variance_loops[2]
+cdef void *ufunc__nct_variance_ptr[4]
+cdef void *ufunc__nct_variance_data[2]
+cdef char ufunc__nct_variance_types[6]
+cdef char *ufunc__nct_variance_doc = (
+    "_nct_variance(v, l)\n"
+    "\n"
+    "Variance of noncentral t-distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__nct_variance_loops[0] = loop_f_ff__As_ff_f
+ufunc__nct_variance_loops[1] = loop_d_dd__As_dd_d
+ufunc__nct_variance_types[0] = NPY_FLOAT
+ufunc__nct_variance_types[1] = NPY_FLOAT
+ufunc__nct_variance_types[2] = NPY_FLOAT
+ufunc__nct_variance_types[3] = NPY_DOUBLE
+ufunc__nct_variance_types[4] = NPY_DOUBLE
+ufunc__nct_variance_types[5] = NPY_DOUBLE
+ufunc__nct_variance_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_variance_float
+ufunc__nct_variance_ptr[2*0+1] = ("_nct_variance")
+ufunc__nct_variance_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_variance_double
+ufunc__nct_variance_ptr[2*1+1] = ("_nct_variance")
+ufunc__nct_variance_data[0] = &ufunc__nct_variance_ptr[2*0]
+ufunc__nct_variance_data[1] = &ufunc__nct_variance_ptr[2*1]
+_nct_variance = np.PyUFunc_FromFuncAndData(ufunc__nct_variance_loops, ufunc__nct_variance_data, ufunc__nct_variance_types, 2, 2, 1, 0, "_nct_variance", ufunc__nct_variance_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_cdf_loops[2]
+cdef void *ufunc__ncx2_cdf_ptr[4]
+cdef void *ufunc__ncx2_cdf_data[2]
+cdef char ufunc__ncx2_cdf_types[8]
+cdef char *ufunc__ncx2_cdf_doc = (
+    "_ncx2_cdf(x, k, l)\n"
+    "\n"
+    "Cumulative density function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_cdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_cdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_cdf_types[0] = NPY_FLOAT
+ufunc__ncx2_cdf_types[1] = NPY_FLOAT
+ufunc__ncx2_cdf_types[2] = NPY_FLOAT
+ufunc__ncx2_cdf_types[3] = NPY_FLOAT
+ufunc__ncx2_cdf_types[4] = NPY_DOUBLE
+ufunc__ncx2_cdf_types[5] = NPY_DOUBLE
+ufunc__ncx2_cdf_types[6] = NPY_DOUBLE
+ufunc__ncx2_cdf_types[7] = NPY_DOUBLE
+ufunc__ncx2_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_cdf_float
+ufunc__ncx2_cdf_ptr[2*0+1] = ("_ncx2_cdf")
+ufunc__ncx2_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_cdf_double
+ufunc__ncx2_cdf_ptr[2*1+1] = ("_ncx2_cdf")
+ufunc__ncx2_cdf_data[0] = &ufunc__ncx2_cdf_ptr[2*0]
+ufunc__ncx2_cdf_data[1] = &ufunc__ncx2_cdf_ptr[2*1]
+_ncx2_cdf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_cdf_loops, ufunc__ncx2_cdf_data, ufunc__ncx2_cdf_types, 2, 3, 1, 0, "_ncx2_cdf", ufunc__ncx2_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_isf_loops[2]
+cdef void *ufunc__ncx2_isf_ptr[4]
+cdef void *ufunc__ncx2_isf_data[2]
+cdef char ufunc__ncx2_isf_types[8]
+cdef char *ufunc__ncx2_isf_doc = (
+    "_ncx2_isf(x, k, l)\n"
+    "\n"
+    "Inverse survival function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_isf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_isf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_isf_types[0] = NPY_FLOAT
+ufunc__ncx2_isf_types[1] = NPY_FLOAT
+ufunc__ncx2_isf_types[2] = NPY_FLOAT
+ufunc__ncx2_isf_types[3] = NPY_FLOAT
+ufunc__ncx2_isf_types[4] = NPY_DOUBLE
+ufunc__ncx2_isf_types[5] = NPY_DOUBLE
+ufunc__ncx2_isf_types[6] = NPY_DOUBLE
+ufunc__ncx2_isf_types[7] = NPY_DOUBLE
+ufunc__ncx2_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_isf_float
+ufunc__ncx2_isf_ptr[2*0+1] = ("_ncx2_isf")
+ufunc__ncx2_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_isf_double
+ufunc__ncx2_isf_ptr[2*1+1] = ("_ncx2_isf")
+ufunc__ncx2_isf_data[0] = &ufunc__ncx2_isf_ptr[2*0]
+ufunc__ncx2_isf_data[1] = &ufunc__ncx2_isf_ptr[2*1]
+_ncx2_isf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_isf_loops, ufunc__ncx2_isf_data, ufunc__ncx2_isf_types, 2, 3, 1, 0, "_ncx2_isf", ufunc__ncx2_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_pdf_loops[2]
+cdef void *ufunc__ncx2_pdf_ptr[4]
+cdef void *ufunc__ncx2_pdf_data[2]
+cdef char ufunc__ncx2_pdf_types[8]
+cdef char *ufunc__ncx2_pdf_doc = (
+    "_ncx2_pdf(x, k, l)\n"
+    "\n"
+    "Probability density function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_pdf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_pdf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_pdf_types[0] = NPY_FLOAT
+ufunc__ncx2_pdf_types[1] = NPY_FLOAT
+ufunc__ncx2_pdf_types[2] = NPY_FLOAT
+ufunc__ncx2_pdf_types[3] = NPY_FLOAT
+ufunc__ncx2_pdf_types[4] = NPY_DOUBLE
+ufunc__ncx2_pdf_types[5] = NPY_DOUBLE
+ufunc__ncx2_pdf_types[6] = NPY_DOUBLE
+ufunc__ncx2_pdf_types[7] = NPY_DOUBLE
+ufunc__ncx2_pdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_pdf_float
+ufunc__ncx2_pdf_ptr[2*0+1] = ("_ncx2_pdf")
+ufunc__ncx2_pdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_pdf_double
+ufunc__ncx2_pdf_ptr[2*1+1] = ("_ncx2_pdf")
+ufunc__ncx2_pdf_data[0] = &ufunc__ncx2_pdf_ptr[2*0]
+ufunc__ncx2_pdf_data[1] = &ufunc__ncx2_pdf_ptr[2*1]
+_ncx2_pdf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_pdf_loops, ufunc__ncx2_pdf_data, ufunc__ncx2_pdf_types, 2, 3, 1, 0, "_ncx2_pdf", ufunc__ncx2_pdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_ppf_loops[2]
+cdef void *ufunc__ncx2_ppf_ptr[4]
+cdef void *ufunc__ncx2_ppf_data[2]
+cdef char ufunc__ncx2_ppf_types[8]
+cdef char *ufunc__ncx2_ppf_doc = (
+    "_ncx2_ppf(x, k, l)\n"
+    "\n"
+    "Percent point function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_ppf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_ppf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_ppf_types[0] = NPY_FLOAT
+ufunc__ncx2_ppf_types[1] = NPY_FLOAT
+ufunc__ncx2_ppf_types[2] = NPY_FLOAT
+ufunc__ncx2_ppf_types[3] = NPY_FLOAT
+ufunc__ncx2_ppf_types[4] = NPY_DOUBLE
+ufunc__ncx2_ppf_types[5] = NPY_DOUBLE
+ufunc__ncx2_ppf_types[6] = NPY_DOUBLE
+ufunc__ncx2_ppf_types[7] = NPY_DOUBLE
+ufunc__ncx2_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_ppf_float
+ufunc__ncx2_ppf_ptr[2*0+1] = ("_ncx2_ppf")
+ufunc__ncx2_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_ppf_double
+ufunc__ncx2_ppf_ptr[2*1+1] = ("_ncx2_ppf")
+ufunc__ncx2_ppf_data[0] = &ufunc__ncx2_ppf_ptr[2*0]
+ufunc__ncx2_ppf_data[1] = &ufunc__ncx2_ppf_ptr[2*1]
+_ncx2_ppf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_ppf_loops, ufunc__ncx2_ppf_data, ufunc__ncx2_ppf_types, 2, 3, 1, 0, "_ncx2_ppf", ufunc__ncx2_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__ncx2_sf_loops[2]
+cdef void *ufunc__ncx2_sf_ptr[4]
+cdef void *ufunc__ncx2_sf_data[2]
+cdef char ufunc__ncx2_sf_types[8]
+cdef char *ufunc__ncx2_sf_doc = (
+    "_ncx2_sf(x, k, l)\n"
+    "\n"
+    "Survival function of Non-central chi-squared distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Positive real-valued\n"
+    "k, l : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__ncx2_sf_loops[0] = loop_f_fff__As_fff_f
+ufunc__ncx2_sf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc__ncx2_sf_types[0] = NPY_FLOAT
+ufunc__ncx2_sf_types[1] = NPY_FLOAT
+ufunc__ncx2_sf_types[2] = NPY_FLOAT
+ufunc__ncx2_sf_types[3] = NPY_FLOAT
+ufunc__ncx2_sf_types[4] = NPY_DOUBLE
+ufunc__ncx2_sf_types[5] = NPY_DOUBLE
+ufunc__ncx2_sf_types[6] = NPY_DOUBLE
+ufunc__ncx2_sf_types[7] = NPY_DOUBLE
+ufunc__ncx2_sf_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncx2_sf_float
+ufunc__ncx2_sf_ptr[2*0+1] = ("_ncx2_sf")
+ufunc__ncx2_sf_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncx2_sf_double
+ufunc__ncx2_sf_ptr[2*1+1] = ("_ncx2_sf")
+ufunc__ncx2_sf_data[0] = &ufunc__ncx2_sf_ptr[2*0]
+ufunc__ncx2_sf_data[1] = &ufunc__ncx2_sf_ptr[2*1]
+_ncx2_sf = np.PyUFunc_FromFuncAndData(ufunc__ncx2_sf_loops, ufunc__ncx2_sf_data, ufunc__ncx2_sf_types, 2, 3, 1, 0, "_ncx2_sf", ufunc__ncx2_sf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__sf_error_test_function_loops[1]
+cdef void *ufunc__sf_error_test_function_ptr[2]
+cdef void *ufunc__sf_error_test_function_data[1]
+cdef char ufunc__sf_error_test_function_types[2]
+cdef char *ufunc__sf_error_test_function_doc = (
+    "Private function; do not use.")
+ufunc__sf_error_test_function_loops[0] = loop_i_i__As_l_l
+ufunc__sf_error_test_function_types[0] = NPY_LONG
+ufunc__sf_error_test_function_types[1] = NPY_LONG
+ufunc__sf_error_test_function_ptr[2*0] = _func__sf_error_test_function
+ufunc__sf_error_test_function_ptr[2*0+1] = ("_sf_error_test_function")
+ufunc__sf_error_test_function_data[0] = &ufunc__sf_error_test_function_ptr[2*0]
+_sf_error_test_function = np.PyUFunc_FromFuncAndData(ufunc__sf_error_test_function_loops, ufunc__sf_error_test_function_data, ufunc__sf_error_test_function_types, 1, 1, 1, 0, "_sf_error_test_function", ufunc__sf_error_test_function_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__skewnorm_cdf_loops[2]
+cdef void *ufunc__skewnorm_cdf_ptr[4]
+cdef void *ufunc__skewnorm_cdf_data[2]
+cdef char ufunc__skewnorm_cdf_types[10]
+cdef char *ufunc__skewnorm_cdf_doc = (
+    "_skewnorm_cdf(x, l, sc, sh)\n"
+    "\n"
+    "Cumulative density function of skewnorm distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "sc : array_like\n"
+    "    Positive, Real-valued parameters\n"
+    "sh : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__skewnorm_cdf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__skewnorm_cdf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__skewnorm_cdf_types[0] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[1] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[2] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[3] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[4] = NPY_FLOAT
+ufunc__skewnorm_cdf_types[5] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[6] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[7] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[8] = NPY_DOUBLE
+ufunc__skewnorm_cdf_types[9] = NPY_DOUBLE
+ufunc__skewnorm_cdf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_cdf_float
+ufunc__skewnorm_cdf_ptr[2*0+1] = ("_skewnorm_cdf")
+ufunc__skewnorm_cdf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_cdf_double
+ufunc__skewnorm_cdf_ptr[2*1+1] = ("_skewnorm_cdf")
+ufunc__skewnorm_cdf_data[0] = &ufunc__skewnorm_cdf_ptr[2*0]
+ufunc__skewnorm_cdf_data[1] = &ufunc__skewnorm_cdf_ptr[2*1]
+_skewnorm_cdf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_cdf_loops, ufunc__skewnorm_cdf_data, ufunc__skewnorm_cdf_types, 2, 4, 1, 0, "_skewnorm_cdf", ufunc__skewnorm_cdf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__skewnorm_isf_loops[2]
+cdef void *ufunc__skewnorm_isf_ptr[4]
+cdef void *ufunc__skewnorm_isf_data[2]
+cdef char ufunc__skewnorm_isf_types[10]
+cdef char *ufunc__skewnorm_isf_doc = (
+    "_skewnorm_isf(x, l, sc, sh)\n"
+    "\n"
+    "Inverse survival function of skewnorm distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "sc : array_like\n"
+    "    Positive, Real-valued parameters\n"
+    "sh : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__skewnorm_isf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__skewnorm_isf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__skewnorm_isf_types[0] = NPY_FLOAT
+ufunc__skewnorm_isf_types[1] = NPY_FLOAT
+ufunc__skewnorm_isf_types[2] = NPY_FLOAT
+ufunc__skewnorm_isf_types[3] = NPY_FLOAT
+ufunc__skewnorm_isf_types[4] = NPY_FLOAT
+ufunc__skewnorm_isf_types[5] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[6] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[7] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[8] = NPY_DOUBLE
+ufunc__skewnorm_isf_types[9] = NPY_DOUBLE
+ufunc__skewnorm_isf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_isf_float
+ufunc__skewnorm_isf_ptr[2*0+1] = ("_skewnorm_isf")
+ufunc__skewnorm_isf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_isf_double
+ufunc__skewnorm_isf_ptr[2*1+1] = ("_skewnorm_isf")
+ufunc__skewnorm_isf_data[0] = &ufunc__skewnorm_isf_ptr[2*0]
+ufunc__skewnorm_isf_data[1] = &ufunc__skewnorm_isf_ptr[2*1]
+_skewnorm_isf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_isf_loops, ufunc__skewnorm_isf_data, ufunc__skewnorm_isf_types, 2, 4, 1, 0, "_skewnorm_isf", ufunc__skewnorm_isf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__skewnorm_ppf_loops[2]
+cdef void *ufunc__skewnorm_ppf_ptr[4]
+cdef void *ufunc__skewnorm_ppf_data[2]
+cdef char ufunc__skewnorm_ppf_types[10]
+cdef char *ufunc__skewnorm_ppf_doc = (
+    "_skewnorm_ppf(x, l, sc, sh)\n"
+    "\n"
+    "Percent point function of skewnorm distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real-valued\n"
+    "l : array_like\n"
+    "    Real-valued parameters\n"
+    "sc : array_like\n"
+    "    Positive, Real-valued parameters\n"
+    "sh : array_like\n"
+    "    Real-valued parameters\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray")
+ufunc__skewnorm_ppf_loops[0] = loop_f_ffff__As_ffff_f
+ufunc__skewnorm_ppf_loops[1] = loop_d_dddd__As_dddd_d
+ufunc__skewnorm_ppf_types[0] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[1] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[2] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[3] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[4] = NPY_FLOAT
+ufunc__skewnorm_ppf_types[5] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[6] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[7] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[8] = NPY_DOUBLE
+ufunc__skewnorm_ppf_types[9] = NPY_DOUBLE
+ufunc__skewnorm_ppf_ptr[2*0] = scipy.special._ufuncs_cxx._export_skewnorm_ppf_float
+ufunc__skewnorm_ppf_ptr[2*0+1] = ("_skewnorm_ppf")
+ufunc__skewnorm_ppf_ptr[2*1] = scipy.special._ufuncs_cxx._export_skewnorm_ppf_double
+ufunc__skewnorm_ppf_ptr[2*1+1] = ("_skewnorm_ppf")
+ufunc__skewnorm_ppf_data[0] = &ufunc__skewnorm_ppf_ptr[2*0]
+ufunc__skewnorm_ppf_data[1] = &ufunc__skewnorm_ppf_ptr[2*1]
+_skewnorm_ppf = np.PyUFunc_FromFuncAndData(ufunc__skewnorm_ppf_loops, ufunc__skewnorm_ppf_data, ufunc__skewnorm_ppf_types, 2, 4, 1, 0, "_skewnorm_ppf", ufunc__skewnorm_ppf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__smirnovc_loops[3]
+cdef void *ufunc__smirnovc_ptr[6]
+cdef void *ufunc__smirnovc_data[3]
+cdef char ufunc__smirnovc_types[9]
+cdef char *ufunc__smirnovc_doc = (
+    "_smirnovc(n, d)\n"
+    " Internal function, do not use.")
+ufunc__smirnovc_loops[0] = loop_d_pd__As_pd_d
+ufunc__smirnovc_loops[1] = loop_d_dd__As_ff_f
+ufunc__smirnovc_loops[2] = loop_d_dd__As_dd_d
+ufunc__smirnovc_types[0] = NPY_INTP
+ufunc__smirnovc_types[1] = NPY_DOUBLE
+ufunc__smirnovc_types[2] = NPY_DOUBLE
+ufunc__smirnovc_types[3] = NPY_FLOAT
+ufunc__smirnovc_types[4] = NPY_FLOAT
+ufunc__smirnovc_types[5] = NPY_FLOAT
+ufunc__smirnovc_types[6] = NPY_DOUBLE
+ufunc__smirnovc_types[7] = NPY_DOUBLE
+ufunc__smirnovc_types[8] = NPY_DOUBLE
+ufunc__smirnovc_ptr[2*0] = _func_cephes_smirnovc_wrap
+ufunc__smirnovc_ptr[2*0+1] = ("_smirnovc")
+ufunc__smirnovc_ptr[2*1] = _func_smirnovc_unsafe
+ufunc__smirnovc_ptr[2*1+1] = ("_smirnovc")
+ufunc__smirnovc_ptr[2*2] = _func_smirnovc_unsafe
+ufunc__smirnovc_ptr[2*2+1] = ("_smirnovc")
+ufunc__smirnovc_data[0] = &ufunc__smirnovc_ptr[2*0]
+ufunc__smirnovc_data[1] = &ufunc__smirnovc_ptr[2*1]
+ufunc__smirnovc_data[2] = &ufunc__smirnovc_ptr[2*2]
+_smirnovc = np.PyUFunc_FromFuncAndData(ufunc__smirnovc_loops, ufunc__smirnovc_data, ufunc__smirnovc_types, 3, 2, 1, 0, "_smirnovc", ufunc__smirnovc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__smirnovci_loops[3]
+cdef void *ufunc__smirnovci_ptr[6]
+cdef void *ufunc__smirnovci_data[3]
+cdef char ufunc__smirnovci_types[9]
+cdef char *ufunc__smirnovci_doc = (
+    "Internal function, do not use.")
+ufunc__smirnovci_loops[0] = loop_d_pd__As_pd_d
+ufunc__smirnovci_loops[1] = loop_d_dd__As_ff_f
+ufunc__smirnovci_loops[2] = loop_d_dd__As_dd_d
+ufunc__smirnovci_types[0] = NPY_INTP
+ufunc__smirnovci_types[1] = NPY_DOUBLE
+ufunc__smirnovci_types[2] = NPY_DOUBLE
+ufunc__smirnovci_types[3] = NPY_FLOAT
+ufunc__smirnovci_types[4] = NPY_FLOAT
+ufunc__smirnovci_types[5] = NPY_FLOAT
+ufunc__smirnovci_types[6] = NPY_DOUBLE
+ufunc__smirnovci_types[7] = NPY_DOUBLE
+ufunc__smirnovci_types[8] = NPY_DOUBLE
+ufunc__smirnovci_ptr[2*0] = _func_cephes_smirnovci_wrap
+ufunc__smirnovci_ptr[2*0+1] = ("_smirnovci")
+ufunc__smirnovci_ptr[2*1] = _func_smirnovci_unsafe
+ufunc__smirnovci_ptr[2*1+1] = ("_smirnovci")
+ufunc__smirnovci_ptr[2*2] = _func_smirnovci_unsafe
+ufunc__smirnovci_ptr[2*2+1] = ("_smirnovci")
+ufunc__smirnovci_data[0] = &ufunc__smirnovci_ptr[2*0]
+ufunc__smirnovci_data[1] = &ufunc__smirnovci_ptr[2*1]
+ufunc__smirnovci_data[2] = &ufunc__smirnovci_ptr[2*2]
+_smirnovci = np.PyUFunc_FromFuncAndData(ufunc__smirnovci_loops, ufunc__smirnovci_data, ufunc__smirnovci_types, 3, 2, 1, 0, "_smirnovci", ufunc__smirnovci_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__smirnovp_loops[3]
+cdef void *ufunc__smirnovp_ptr[6]
+cdef void *ufunc__smirnovp_data[3]
+cdef char ufunc__smirnovp_types[9]
+cdef char *ufunc__smirnovp_doc = (
+    "_smirnovp(n, p)\n"
+    " Internal function, do not use.")
+ufunc__smirnovp_loops[0] = loop_d_pd__As_pd_d
+ufunc__smirnovp_loops[1] = loop_d_dd__As_ff_f
+ufunc__smirnovp_loops[2] = loop_d_dd__As_dd_d
+ufunc__smirnovp_types[0] = NPY_INTP
+ufunc__smirnovp_types[1] = NPY_DOUBLE
+ufunc__smirnovp_types[2] = NPY_DOUBLE
+ufunc__smirnovp_types[3] = NPY_FLOAT
+ufunc__smirnovp_types[4] = NPY_FLOAT
+ufunc__smirnovp_types[5] = NPY_FLOAT
+ufunc__smirnovp_types[6] = NPY_DOUBLE
+ufunc__smirnovp_types[7] = NPY_DOUBLE
+ufunc__smirnovp_types[8] = NPY_DOUBLE
+ufunc__smirnovp_ptr[2*0] = _func_cephes_smirnovp_wrap
+ufunc__smirnovp_ptr[2*0+1] = ("_smirnovp")
+ufunc__smirnovp_ptr[2*1] = _func_smirnovp_unsafe
+ufunc__smirnovp_ptr[2*1+1] = ("_smirnovp")
+ufunc__smirnovp_ptr[2*2] = _func_smirnovp_unsafe
+ufunc__smirnovp_ptr[2*2+1] = ("_smirnovp")
+ufunc__smirnovp_data[0] = &ufunc__smirnovp_ptr[2*0]
+ufunc__smirnovp_data[1] = &ufunc__smirnovp_ptr[2*1]
+ufunc__smirnovp_data[2] = &ufunc__smirnovp_ptr[2*2]
+_smirnovp = np.PyUFunc_FromFuncAndData(ufunc__smirnovp_loops, ufunc__smirnovp_data, ufunc__smirnovp_types, 3, 2, 1, 0, "_smirnovp", ufunc__smirnovp_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__stirling2_inexact_loops[2]
+cdef void *ufunc__stirling2_inexact_ptr[4]
+cdef void *ufunc__stirling2_inexact_data[2]
+cdef char ufunc__stirling2_inexact_types[6]
+cdef char *ufunc__stirling2_inexact_doc = (
+    "Internal function, do not use.")
+ufunc__stirling2_inexact_loops[0] = loop_d_dd__As_ff_f
+ufunc__stirling2_inexact_loops[1] = loop_d_dd__As_dd_d
+ufunc__stirling2_inexact_types[0] = NPY_FLOAT
+ufunc__stirling2_inexact_types[1] = NPY_FLOAT
+ufunc__stirling2_inexact_types[2] = NPY_FLOAT
+ufunc__stirling2_inexact_types[3] = NPY_DOUBLE
+ufunc__stirling2_inexact_types[4] = NPY_DOUBLE
+ufunc__stirling2_inexact_types[5] = NPY_DOUBLE
+ufunc__stirling2_inexact_ptr[2*0] = scipy.special._ufuncs_cxx._export__stirling2_inexact
+ufunc__stirling2_inexact_ptr[2*0+1] = ("_stirling2_inexact")
+ufunc__stirling2_inexact_ptr[2*1] = scipy.special._ufuncs_cxx._export__stirling2_inexact
+ufunc__stirling2_inexact_ptr[2*1+1] = ("_stirling2_inexact")
+ufunc__stirling2_inexact_data[0] = &ufunc__stirling2_inexact_ptr[2*0]
+ufunc__stirling2_inexact_data[1] = &ufunc__stirling2_inexact_ptr[2*1]
+_stirling2_inexact = np.PyUFunc_FromFuncAndData(ufunc__stirling2_inexact_loops, ufunc__stirling2_inexact_data, ufunc__stirling2_inexact_types, 2, 2, 1, 0, "_stirling2_inexact", ufunc__stirling2_inexact_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__struve_asymp_large_z_loops[1]
+cdef void *ufunc__struve_asymp_large_z_ptr[2]
+cdef void *ufunc__struve_asymp_large_z_data[1]
+cdef char ufunc__struve_asymp_large_z_types[5]
+cdef char *ufunc__struve_asymp_large_z_doc = (
+    "_struve_asymp_large_z(v, z, is_h)\n"
+    "\n"
+    "Internal function for testing `struve` & `modstruve`\n"
+    "\n"
+    "Evaluates using asymptotic expansion\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "v, err")
+ufunc__struve_asymp_large_z_loops[0] = loop_d_ddp_d_As_ddp_dd
+ufunc__struve_asymp_large_z_types[0] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_types[1] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_types[2] = NPY_INTP
+ufunc__struve_asymp_large_z_types[3] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_types[4] = NPY_DOUBLE
+ufunc__struve_asymp_large_z_ptr[2*0] = _func_cephes__struve_asymp_large_z
+ufunc__struve_asymp_large_z_ptr[2*0+1] = ("_struve_asymp_large_z")
+ufunc__struve_asymp_large_z_data[0] = &ufunc__struve_asymp_large_z_ptr[2*0]
+_struve_asymp_large_z = np.PyUFunc_FromFuncAndData(ufunc__struve_asymp_large_z_loops, ufunc__struve_asymp_large_z_data, ufunc__struve_asymp_large_z_types, 1, 3, 2, 0, "_struve_asymp_large_z", ufunc__struve_asymp_large_z_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__struve_bessel_series_loops[1]
+cdef void *ufunc__struve_bessel_series_ptr[2]
+cdef void *ufunc__struve_bessel_series_data[1]
+cdef char ufunc__struve_bessel_series_types[5]
+cdef char *ufunc__struve_bessel_series_doc = (
+    "_struve_bessel_series(v, z, is_h)\n"
+    "\n"
+    "Internal function for testing `struve` & `modstruve`\n"
+    "\n"
+    "Evaluates using Bessel function series\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "v, err")
+ufunc__struve_bessel_series_loops[0] = loop_d_ddp_d_As_ddp_dd
+ufunc__struve_bessel_series_types[0] = NPY_DOUBLE
+ufunc__struve_bessel_series_types[1] = NPY_DOUBLE
+ufunc__struve_bessel_series_types[2] = NPY_INTP
+ufunc__struve_bessel_series_types[3] = NPY_DOUBLE
+ufunc__struve_bessel_series_types[4] = NPY_DOUBLE
+ufunc__struve_bessel_series_ptr[2*0] = _func_cephes__struve_bessel_series
+ufunc__struve_bessel_series_ptr[2*0+1] = ("_struve_bessel_series")
+ufunc__struve_bessel_series_data[0] = &ufunc__struve_bessel_series_ptr[2*0]
+_struve_bessel_series = np.PyUFunc_FromFuncAndData(ufunc__struve_bessel_series_loops, ufunc__struve_bessel_series_data, ufunc__struve_bessel_series_types, 1, 3, 2, 0, "_struve_bessel_series", ufunc__struve_bessel_series_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc__struve_power_series_loops[1]
+cdef void *ufunc__struve_power_series_ptr[2]
+cdef void *ufunc__struve_power_series_data[1]
+cdef char ufunc__struve_power_series_types[5]
+cdef char *ufunc__struve_power_series_doc = (
+    "_struve_power_series(v, z, is_h)\n"
+    "\n"
+    "Internal function for testing `struve` & `modstruve`\n"
+    "\n"
+    "Evaluates using power series\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "v, err")
+ufunc__struve_power_series_loops[0] = loop_d_ddp_d_As_ddp_dd
+ufunc__struve_power_series_types[0] = NPY_DOUBLE
+ufunc__struve_power_series_types[1] = NPY_DOUBLE
+ufunc__struve_power_series_types[2] = NPY_INTP
+ufunc__struve_power_series_types[3] = NPY_DOUBLE
+ufunc__struve_power_series_types[4] = NPY_DOUBLE
+ufunc__struve_power_series_ptr[2*0] = _func_cephes__struve_power_series
+ufunc__struve_power_series_ptr[2*0+1] = ("_struve_power_series")
+ufunc__struve_power_series_data[0] = &ufunc__struve_power_series_ptr[2*0]
+_struve_power_series = np.PyUFunc_FromFuncAndData(ufunc__struve_power_series_loops, ufunc__struve_power_series_data, ufunc__struve_power_series_types, 1, 3, 2, 0, "_struve_power_series", ufunc__struve_power_series_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_agm_loops[2]
+cdef void *ufunc_agm_ptr[4]
+cdef void *ufunc_agm_data[2]
+cdef char ufunc_agm_types[6]
+cdef char *ufunc_agm_doc = (
+    "agm(a, b, out=None)\n"
+    "\n"
+    "Compute the arithmetic-geometric mean of `a` and `b`.\n"
+    "\n"
+    "Start with a_0 = a and b_0 = b and iteratively compute::\n"
+    "\n"
+    "    a_{n+1} = (a_n + b_n)/2\n"
+    "    b_{n+1} = sqrt(a_n*b_n)\n"
+    "\n"
+    "a_n and b_n converge to the same limit as n increases; their common\n"
+    "limit is agm(a, b).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Real values only. If the values are both negative, the result\n"
+    "    is negative. If one value is negative and the other is positive,\n"
+    "    `nan` is returned.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The arithmetic-geometric mean of `a` and `b`.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import agm\n"
+    ">>> a, b = 24.0, 6.0\n"
+    ">>> agm(a, b)\n"
+    "13.458171481725614\n"
+    "\n"
+    "Compare that result to the iteration:\n"
+    "\n"
+    ">>> while a != b:\n"
+    "...     a, b = (a + b)/2, np.sqrt(a*b)\n"
+    "...     print(\"a = %19.16f  b=%19.16f\" % (a, b))\n"
+    "...\n"
+    "a = 15.0000000000000000  b=12.0000000000000000\n"
+    "a = 13.5000000000000000  b=13.4164078649987388\n"
+    "a = 13.4582039324993694  b=13.4581390309909850\n"
+    "a = 13.4581714817451772  b=13.4581714817060547\n"
+    "a = 13.4581714817256159  b=13.4581714817256159\n"
+    "\n"
+    "When array-like arguments are given, broadcasting applies:\n"
+    "\n"
+    ">>> a = np.array([[1.5], [3], [6]])  # a has shape (3, 1).\n"
+    ">>> b = np.array([6, 12, 24, 48])    # b has shape (4,).\n"
+    ">>> agm(a, b)\n"
+    "array([[  3.36454287,   5.42363427,   9.05798751,  15.53650756],\n"
+    "       [  4.37037309,   6.72908574,  10.84726853,  18.11597502],\n"
+    "       [  6.        ,   8.74074619,  13.45817148,  21.69453707]])")
+ufunc_agm_loops[0] = loop_d_dd__As_ff_f
+ufunc_agm_loops[1] = loop_d_dd__As_dd_d
+ufunc_agm_types[0] = NPY_FLOAT
+ufunc_agm_types[1] = NPY_FLOAT
+ufunc_agm_types[2] = NPY_FLOAT
+ufunc_agm_types[3] = NPY_DOUBLE
+ufunc_agm_types[4] = NPY_DOUBLE
+ufunc_agm_types[5] = NPY_DOUBLE
+ufunc_agm_ptr[2*0] = _func_agm
+ufunc_agm_ptr[2*0+1] = ("agm")
+ufunc_agm_ptr[2*1] = _func_agm
+ufunc_agm_ptr[2*1+1] = ("agm")
+ufunc_agm_data[0] = &ufunc_agm_ptr[2*0]
+ufunc_agm_data[1] = &ufunc_agm_ptr[2*1]
+agm = np.PyUFunc_FromFuncAndData(ufunc_agm_loops, ufunc_agm_data, ufunc_agm_types, 2, 2, 1, 0, "agm", ufunc_agm_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtr_loops[3]
+cdef void *ufunc_bdtr_ptr[6]
+cdef void *ufunc_bdtr_data[3]
+cdef char ufunc_bdtr_types[12]
+cdef char *ufunc_bdtr_doc = (
+    "bdtr(k, n, p, out=None)\n"
+    "\n"
+    "Binomial distribution cumulative distribution function.\n"
+    "\n"
+    "Sum of the terms 0 through `floor(k)` of the Binomial probability density.\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtr}(k, n, p) =\n"
+    "    \\sum_{j=0}^{\\lfloor k \\rfloor} {{n}\\choose{j}} p^j (1-p)^{n-j}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (double), rounded down to the nearest integer.\n"
+    "n : array_like\n"
+    "    Number of events (int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Probability of `floor(k)` or fewer successes in `n` independent events with\n"
+    "    success probabilities of `p`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtr}(k, n, p) =\n"
+    "    I_{1 - p}(n - \\lfloor k \\rfloor, \\lfloor k \\rfloor + 1).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `bdtr`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/")
+ufunc_bdtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtr_loops[1] = loop_d_dpd__As_dpd_d
+ufunc_bdtr_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_bdtr_types[0] = NPY_FLOAT
+ufunc_bdtr_types[1] = NPY_FLOAT
+ufunc_bdtr_types[2] = NPY_FLOAT
+ufunc_bdtr_types[3] = NPY_FLOAT
+ufunc_bdtr_types[4] = NPY_DOUBLE
+ufunc_bdtr_types[5] = NPY_INTP
+ufunc_bdtr_types[6] = NPY_DOUBLE
+ufunc_bdtr_types[7] = NPY_DOUBLE
+ufunc_bdtr_types[8] = NPY_DOUBLE
+ufunc_bdtr_types[9] = NPY_DOUBLE
+ufunc_bdtr_types[10] = NPY_DOUBLE
+ufunc_bdtr_types[11] = NPY_DOUBLE
+ufunc_bdtr_ptr[2*0] = _func_bdtr_unsafe
+ufunc_bdtr_ptr[2*0+1] = ("bdtr")
+ufunc_bdtr_ptr[2*1] = _func_cephes_bdtr_wrap
+ufunc_bdtr_ptr[2*1+1] = ("bdtr")
+ufunc_bdtr_ptr[2*2] = _func_bdtr_unsafe
+ufunc_bdtr_ptr[2*2+1] = ("bdtr")
+ufunc_bdtr_data[0] = &ufunc_bdtr_ptr[2*0]
+ufunc_bdtr_data[1] = &ufunc_bdtr_ptr[2*1]
+ufunc_bdtr_data[2] = &ufunc_bdtr_ptr[2*2]
+bdtr = np.PyUFunc_FromFuncAndData(ufunc_bdtr_loops, ufunc_bdtr_data, ufunc_bdtr_types, 3, 3, 1, 0, "bdtr", ufunc_bdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtrc_loops[3]
+cdef void *ufunc_bdtrc_ptr[6]
+cdef void *ufunc_bdtrc_data[3]
+cdef char ufunc_bdtrc_types[12]
+cdef char *ufunc_bdtrc_doc = (
+    "bdtrc(k, n, p, out=None)\n"
+    "\n"
+    "Binomial distribution survival function.\n"
+    "\n"
+    "Sum of the terms `floor(k) + 1` through `n` of the binomial probability\n"
+    "density,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtrc}(k, n, p) =\n"
+    "    \\sum_{j=\\lfloor k \\rfloor +1}^n {{n}\\choose{j}} p^j (1-p)^{n-j}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (double), rounded down to nearest integer.\n"
+    "n : array_like\n"
+    "    Number of events (int)\n"
+    "p : array_like\n"
+    "    Probability of success in a single event.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Probability of `floor(k) + 1` or more successes in `n` independent\n"
+    "    events with success probabilities of `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "betainc\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{bdtrc}(k, n, p) = I_{p}(\\lfloor k \\rfloor + 1, n - \\lfloor k \\rfloor).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `bdtrc`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/")
+ufunc_bdtrc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtrc_loops[1] = loop_d_dpd__As_dpd_d
+ufunc_bdtrc_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_bdtrc_types[0] = NPY_FLOAT
+ufunc_bdtrc_types[1] = NPY_FLOAT
+ufunc_bdtrc_types[2] = NPY_FLOAT
+ufunc_bdtrc_types[3] = NPY_FLOAT
+ufunc_bdtrc_types[4] = NPY_DOUBLE
+ufunc_bdtrc_types[5] = NPY_INTP
+ufunc_bdtrc_types[6] = NPY_DOUBLE
+ufunc_bdtrc_types[7] = NPY_DOUBLE
+ufunc_bdtrc_types[8] = NPY_DOUBLE
+ufunc_bdtrc_types[9] = NPY_DOUBLE
+ufunc_bdtrc_types[10] = NPY_DOUBLE
+ufunc_bdtrc_types[11] = NPY_DOUBLE
+ufunc_bdtrc_ptr[2*0] = _func_bdtrc_unsafe
+ufunc_bdtrc_ptr[2*0+1] = ("bdtrc")
+ufunc_bdtrc_ptr[2*1] = _func_cephes_bdtrc_wrap
+ufunc_bdtrc_ptr[2*1+1] = ("bdtrc")
+ufunc_bdtrc_ptr[2*2] = _func_bdtrc_unsafe
+ufunc_bdtrc_ptr[2*2+1] = ("bdtrc")
+ufunc_bdtrc_data[0] = &ufunc_bdtrc_ptr[2*0]
+ufunc_bdtrc_data[1] = &ufunc_bdtrc_ptr[2*1]
+ufunc_bdtrc_data[2] = &ufunc_bdtrc_ptr[2*2]
+bdtrc = np.PyUFunc_FromFuncAndData(ufunc_bdtrc_loops, ufunc_bdtrc_data, ufunc_bdtrc_types, 3, 3, 1, 0, "bdtrc", ufunc_bdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtri_loops[3]
+cdef void *ufunc_bdtri_ptr[6]
+cdef void *ufunc_bdtri_data[3]
+cdef char ufunc_bdtri_types[12]
+cdef char *ufunc_bdtri_doc = (
+    "bdtri(k, n, y, out=None)\n"
+    "\n"
+    "Inverse function to `bdtr` with respect to `p`.\n"
+    "\n"
+    "Finds the event probability `p` such that the sum of the terms 0 through\n"
+    "`k` of the binomial probability density is equal to the given cumulative\n"
+    "probability `y`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (float), rounded down to the nearest integer.\n"
+    "n : array_like\n"
+    "    Number of events (float)\n"
+    "y : array_like\n"
+    "    Cumulative probability (probability of `k` or fewer successes in `n`\n"
+    "    events).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "p : scalar or ndarray\n"
+    "    The event probability such that `bdtr(\\lfloor k \\rfloor, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "betaincinv\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The computation is carried out using the inverse beta integral function\n"
+    "and the relation,::\n"
+    "\n"
+    "    1 - p = betaincinv(n - k, k + 1, y).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `bdtri`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/")
+ufunc_bdtri_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtri_loops[1] = loop_d_dpd__As_dpd_d
+ufunc_bdtri_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_bdtri_types[0] = NPY_FLOAT
+ufunc_bdtri_types[1] = NPY_FLOAT
+ufunc_bdtri_types[2] = NPY_FLOAT
+ufunc_bdtri_types[3] = NPY_FLOAT
+ufunc_bdtri_types[4] = NPY_DOUBLE
+ufunc_bdtri_types[5] = NPY_INTP
+ufunc_bdtri_types[6] = NPY_DOUBLE
+ufunc_bdtri_types[7] = NPY_DOUBLE
+ufunc_bdtri_types[8] = NPY_DOUBLE
+ufunc_bdtri_types[9] = NPY_DOUBLE
+ufunc_bdtri_types[10] = NPY_DOUBLE
+ufunc_bdtri_types[11] = NPY_DOUBLE
+ufunc_bdtri_ptr[2*0] = _func_bdtri_unsafe
+ufunc_bdtri_ptr[2*0+1] = ("bdtri")
+ufunc_bdtri_ptr[2*1] = _func_cephes_bdtri_wrap
+ufunc_bdtri_ptr[2*1+1] = ("bdtri")
+ufunc_bdtri_ptr[2*2] = _func_bdtri_unsafe
+ufunc_bdtri_ptr[2*2+1] = ("bdtri")
+ufunc_bdtri_data[0] = &ufunc_bdtri_ptr[2*0]
+ufunc_bdtri_data[1] = &ufunc_bdtri_ptr[2*1]
+ufunc_bdtri_data[2] = &ufunc_bdtri_ptr[2*2]
+bdtri = np.PyUFunc_FromFuncAndData(ufunc_bdtri_loops, ufunc_bdtri_data, ufunc_bdtri_types, 3, 3, 1, 0, "bdtri", ufunc_bdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtrik_loops[2]
+cdef void *ufunc_bdtrik_ptr[4]
+cdef void *ufunc_bdtrik_data[2]
+cdef char ufunc_bdtrik_types[8]
+cdef char *ufunc_bdtrik_doc = (
+    "bdtrik(y, n, p, out=None)\n"
+    "\n"
+    "Inverse function to `bdtr` with respect to `k`.\n"
+    "\n"
+    "Finds the number of successes `k` such that the sum of the terms 0 through\n"
+    "`k` of the Binomial probability density for `n` events with probability\n"
+    "`p` is equal to the given cumulative probability `y`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    Cumulative probability (probability of `k` or fewer successes in `n`\n"
+    "    events).\n"
+    "n : array_like\n"
+    "    Number of events (float).\n"
+    "p : array_like\n"
+    "    Success probability (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "k : scalar or ndarray\n"
+    "    The number of successes `k` such that `bdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the\n"
+    "cumulative incomplete beta distribution.\n"
+    "\n"
+    "Computation of `k` involves a search for a value that produces the desired\n"
+    "value of `y`. The search relies on the monotonicity of `y` with `k`.\n"
+    "\n"
+    "Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    ".. [2] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.")
+ufunc_bdtrik_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtrik_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_bdtrik_types[0] = NPY_FLOAT
+ufunc_bdtrik_types[1] = NPY_FLOAT
+ufunc_bdtrik_types[2] = NPY_FLOAT
+ufunc_bdtrik_types[3] = NPY_FLOAT
+ufunc_bdtrik_types[4] = NPY_DOUBLE
+ufunc_bdtrik_types[5] = NPY_DOUBLE
+ufunc_bdtrik_types[6] = NPY_DOUBLE
+ufunc_bdtrik_types[7] = NPY_DOUBLE
+ufunc_bdtrik_ptr[2*0] = _func_bdtrik
+ufunc_bdtrik_ptr[2*0+1] = ("bdtrik")
+ufunc_bdtrik_ptr[2*1] = _func_bdtrik
+ufunc_bdtrik_ptr[2*1+1] = ("bdtrik")
+ufunc_bdtrik_data[0] = &ufunc_bdtrik_ptr[2*0]
+ufunc_bdtrik_data[1] = &ufunc_bdtrik_ptr[2*1]
+bdtrik = np.PyUFunc_FromFuncAndData(ufunc_bdtrik_loops, ufunc_bdtrik_data, ufunc_bdtrik_types, 2, 3, 1, 0, "bdtrik", ufunc_bdtrik_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_bdtrin_loops[2]
+cdef void *ufunc_bdtrin_ptr[4]
+cdef void *ufunc_bdtrin_data[2]
+cdef char ufunc_bdtrin_types[8]
+cdef char *ufunc_bdtrin_doc = (
+    "bdtrin(k, y, p, out=None)\n"
+    "\n"
+    "Inverse function to `bdtr` with respect to `n`.\n"
+    "\n"
+    "Finds the number of events `n` such that the sum of the terms 0 through\n"
+    "`k` of the Binomial probability density for events with probability `p` is\n"
+    "equal to the given cumulative probability `y`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of successes (float).\n"
+    "y : array_like\n"
+    "    Cumulative probability (probability of `k` or fewer successes in `n`\n"
+    "    events).\n"
+    "p : array_like\n"
+    "    Success probability (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "n : scalar or ndarray\n"
+    "    The number of events `n` such that `bdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "bdtr\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Formula 26.5.24 of [1]_ is used to reduce the binomial distribution to the\n"
+    "cumulative incomplete beta distribution.\n"
+    "\n"
+    "Computation of `n` involves a search for a value that produces the desired\n"
+    "value of `y`. The search relies on the monotonicity of `y` with `n`.\n"
+    "\n"
+    "Wrapper for the CDFLIB [2]_ Fortran routine `cdfbin`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    ".. [2] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.")
+ufunc_bdtrin_loops[0] = loop_d_ddd__As_fff_f
+ufunc_bdtrin_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_bdtrin_types[0] = NPY_FLOAT
+ufunc_bdtrin_types[1] = NPY_FLOAT
+ufunc_bdtrin_types[2] = NPY_FLOAT
+ufunc_bdtrin_types[3] = NPY_FLOAT
+ufunc_bdtrin_types[4] = NPY_DOUBLE
+ufunc_bdtrin_types[5] = NPY_DOUBLE
+ufunc_bdtrin_types[6] = NPY_DOUBLE
+ufunc_bdtrin_types[7] = NPY_DOUBLE
+ufunc_bdtrin_ptr[2*0] = _func_bdtrin
+ufunc_bdtrin_ptr[2*0+1] = ("bdtrin")
+ufunc_bdtrin_ptr[2*1] = _func_bdtrin
+ufunc_bdtrin_ptr[2*1+1] = ("bdtrin")
+ufunc_bdtrin_data[0] = &ufunc_bdtrin_ptr[2*0]
+ufunc_bdtrin_data[1] = &ufunc_bdtrin_ptr[2*1]
+bdtrin = np.PyUFunc_FromFuncAndData(ufunc_bdtrin_loops, ufunc_bdtrin_data, ufunc_bdtrin_types, 2, 3, 1, 0, "bdtrin", ufunc_bdtrin_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betainc_loops[2]
+cdef void *ufunc_betainc_ptr[4]
+cdef void *ufunc_betainc_data[2]
+cdef char ufunc_betainc_types[8]
+cdef char *ufunc_betainc_doc = (
+    "betainc(a, b, x, out=None)\n"
+    "\n"
+    "Regularized incomplete beta function.\n"
+    "\n"
+    "Computes the regularized incomplete beta function, defined as [1]_:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    I_x(a, b) = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)} \\int_0^x\n"
+    "    t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "for :math:`0 \\leq x \\leq 1`.\n"
+    "\n"
+    "This function is the cumulative distribution function for the beta\n"
+    "distribution; its range is [0, 1].\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "beta : beta function\n"
+    "betaincinv : inverse of the regularized incomplete beta function\n"
+    "betaincc : complement of the regularized incomplete beta function\n"
+    "scipy.stats.beta : beta distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The term *regularized* in the name of this function refers to the\n"
+    "scaling of the function by the gamma function terms shown in the\n"
+    "formula.  When not qualified as *regularized*, the name *incomplete\n"
+    "beta function* often refers to just the integral expression,\n"
+    "without the gamma terms.  One can use the function `beta` from\n"
+    "`scipy.special` to get this \"nonregularized\" incomplete beta\n"
+    "function by multiplying the result of ``betainc(a, b, x)`` by\n"
+    "``beta(a, b)``.\n"
+    "\n"
+    "This function wraps the ``ibeta`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "\n"
+    "Let :math:`B(a, b)` be the `beta` function.\n"
+    "\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "The coefficient in terms of `gamma` is equal to\n"
+    ":math:`1/B(a, b)`. Also, when :math:`x=1`\n"
+    "the integral is equal to :math:`B(a, b)`.\n"
+    "Therefore, :math:`I_{x=1}(a, b) = 1` for any :math:`a, b`.\n"
+    "\n"
+    ">>> sc.betainc(0.2, 3.5, 1.0)\n"
+    "1.0\n"
+    "\n"
+    "It satisfies\n"
+    ":math:`I_x(a, b) = x^a F(a, 1-b, a+1, x)/ (aB(a, b))`,\n"
+    "where :math:`F` is the hypergeometric function `hyp2f1`:\n"
+    "\n"
+    ">>> a, b, x = 1.4, 3.1, 0.5\n"
+    ">>> x**a * sc.hyp2f1(a, 1 - b, a + 1, x)/(a * sc.beta(a, b))\n"
+    "0.8148904036225295\n"
+    ">>> sc.betainc(a, b, x)\n"
+    "0.8148904036225296\n"
+    "\n"
+    "This functions satisfies the relationship\n"
+    ":math:`I_x(a, b) = 1 - I_{1-x}(b, a)`:\n"
+    "\n"
+    ">>> sc.betainc(2.2, 3.1, 0.4)\n"
+    "0.49339638807619446\n"
+    ">>> 1 - sc.betainc(3.1, 2.2, 1 - 0.4)\n"
+    "0.49339638807619446")
+ufunc_betainc_loops[0] = loop_f_fff__As_fff_f
+ufunc_betainc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betainc_types[0] = NPY_FLOAT
+ufunc_betainc_types[1] = NPY_FLOAT
+ufunc_betainc_types[2] = NPY_FLOAT
+ufunc_betainc_types[3] = NPY_FLOAT
+ufunc_betainc_types[4] = NPY_DOUBLE
+ufunc_betainc_types[5] = NPY_DOUBLE
+ufunc_betainc_types[6] = NPY_DOUBLE
+ufunc_betainc_types[7] = NPY_DOUBLE
+ufunc_betainc_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibeta_float
+ufunc_betainc_ptr[2*0+1] = ("betainc")
+ufunc_betainc_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibeta_double
+ufunc_betainc_ptr[2*1+1] = ("betainc")
+ufunc_betainc_data[0] = &ufunc_betainc_ptr[2*0]
+ufunc_betainc_data[1] = &ufunc_betainc_ptr[2*1]
+betainc = np.PyUFunc_FromFuncAndData(ufunc_betainc_loops, ufunc_betainc_data, ufunc_betainc_types, 2, 3, 1, 0, "betainc", ufunc_betainc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betaincc_loops[2]
+cdef void *ufunc_betaincc_ptr[4]
+cdef void *ufunc_betaincc_data[2]
+cdef char ufunc_betaincc_types[8]
+cdef char *ufunc_betaincc_doc = (
+    "betaincc(a, b, x, out=None)\n"
+    "\n"
+    "Complement of the regularized incomplete beta function.\n"
+    "\n"
+    "Computes the complement of the regularized incomplete beta function,\n"
+    "defined as [1]_:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\bar{I}_x(a, b) = 1 - I_x(a, b)\n"
+    "                    = 1 - \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)} \\int_0^x\n"
+    "                              t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "for :math:`0 \\leq x \\leq 1`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "       Positive, real-valued parameters\n"
+    "x : array_like\n"
+    "    Real-valued such that :math:`0 \\leq x \\leq 1`,\n"
+    "    the upper limit of integration\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "betainc : regularized incomplete beta function\n"
+    "betaincinv : inverse of the regularized incomplete beta function\n"
+    "betainccinv :\n"
+    "    inverse of the complement of the regularized incomplete beta function\n"
+    "beta : beta function\n"
+    "scipy.stats.beta : beta distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 1.11.0\n"
+    "\n"
+    "This function wraps the ``ibetac`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import betaincc, betainc\n"
+    "\n"
+    "The naive calculation ``1 - betainc(a, b, x)`` loses precision when\n"
+    "the values of ``betainc(a, b, x)`` are close to 1:\n"
+    "\n"
+    ">>> 1 - betainc(0.5, 8, [0.9, 0.99, 0.999])\n"
+    "array([2.0574632e-09, 0.0000000e+00, 0.0000000e+00])\n"
+    "\n"
+    "By using ``betaincc``, we get the correct values:\n"
+    "\n"
+    ">>> betaincc(0.5, 8, [0.9, 0.99, 0.999])\n"
+    "array([2.05746321e-09, 1.97259354e-17, 1.96467954e-25])")
+ufunc_betaincc_loops[0] = loop_f_fff__As_fff_f
+ufunc_betaincc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betaincc_types[0] = NPY_FLOAT
+ufunc_betaincc_types[1] = NPY_FLOAT
+ufunc_betaincc_types[2] = NPY_FLOAT
+ufunc_betaincc_types[3] = NPY_FLOAT
+ufunc_betaincc_types[4] = NPY_DOUBLE
+ufunc_betaincc_types[5] = NPY_DOUBLE
+ufunc_betaincc_types[6] = NPY_DOUBLE
+ufunc_betaincc_types[7] = NPY_DOUBLE
+ufunc_betaincc_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibetac_float
+ufunc_betaincc_ptr[2*0+1] = ("betaincc")
+ufunc_betaincc_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibetac_double
+ufunc_betaincc_ptr[2*1+1] = ("betaincc")
+ufunc_betaincc_data[0] = &ufunc_betaincc_ptr[2*0]
+ufunc_betaincc_data[1] = &ufunc_betaincc_ptr[2*1]
+betaincc = np.PyUFunc_FromFuncAndData(ufunc_betaincc_loops, ufunc_betaincc_data, ufunc_betaincc_types, 2, 3, 1, 0, "betaincc", ufunc_betaincc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betainccinv_loops[2]
+cdef void *ufunc_betainccinv_ptr[4]
+cdef void *ufunc_betainccinv_data[2]
+cdef char ufunc_betainccinv_types[8]
+cdef char *ufunc_betainccinv_doc = (
+    "betainccinv(a, b, y, out=None)\n"
+    "\n"
+    "Inverse of the complemented regularized incomplete beta function.\n"
+    "\n"
+    "Computes :math:`x` such that:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    y = 1 - I_x(a, b) = 1 - \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\n"
+    "    \\int_0^x t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "where :math:`I_x` is the normalized incomplete beta function `betainc`\n"
+    "and :math:`\\Gamma` is the `gamma` function [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "y : array_like\n"
+    "    Real-valued input\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the inverse of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "betainc : regularized incomplete beta function\n"
+    "betaincc : complement of the regularized incomplete beta function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 1.11.0\n"
+    "\n"
+    "This function wraps the ``ibetac_inv`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import betainccinv, betaincc\n"
+    "\n"
+    "This function is the inverse of `betaincc` for fixed\n"
+    "values of :math:`a` and :math:`b`.\n"
+    "\n"
+    ">>> a, b = 1.2, 3.1\n"
+    ">>> y = betaincc(a, b, 0.2)\n"
+    ">>> betainccinv(a, b, y)\n"
+    "0.2\n"
+    "\n"
+    ">>> a, b = 7, 2.5\n"
+    ">>> x = betainccinv(a, b, 0.875)\n"
+    ">>> betaincc(a, b, x)\n"
+    "0.875")
+ufunc_betainccinv_loops[0] = loop_f_fff__As_fff_f
+ufunc_betainccinv_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betainccinv_types[0] = NPY_FLOAT
+ufunc_betainccinv_types[1] = NPY_FLOAT
+ufunc_betainccinv_types[2] = NPY_FLOAT
+ufunc_betainccinv_types[3] = NPY_FLOAT
+ufunc_betainccinv_types[4] = NPY_DOUBLE
+ufunc_betainccinv_types[5] = NPY_DOUBLE
+ufunc_betainccinv_types[6] = NPY_DOUBLE
+ufunc_betainccinv_types[7] = NPY_DOUBLE
+ufunc_betainccinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibetac_inv_float
+ufunc_betainccinv_ptr[2*0+1] = ("betainccinv")
+ufunc_betainccinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibetac_inv_double
+ufunc_betainccinv_ptr[2*1+1] = ("betainccinv")
+ufunc_betainccinv_data[0] = &ufunc_betainccinv_ptr[2*0]
+ufunc_betainccinv_data[1] = &ufunc_betainccinv_ptr[2*1]
+betainccinv = np.PyUFunc_FromFuncAndData(ufunc_betainccinv_loops, ufunc_betainccinv_data, ufunc_betainccinv_types, 2, 3, 1, 0, "betainccinv", ufunc_betainccinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_betaincinv_loops[2]
+cdef void *ufunc_betaincinv_ptr[4]
+cdef void *ufunc_betaincinv_data[2]
+cdef char ufunc_betaincinv_types[8]
+cdef char *ufunc_betaincinv_doc = (
+    "betaincinv(a, b, y, out=None)\n"
+    "\n"
+    "Inverse of the regularized incomplete beta function.\n"
+    "\n"
+    "Computes :math:`x` such that:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    y = I_x(a, b) = \\frac{\\Gamma(a+b)}{\\Gamma(a)\\Gamma(b)}\n"
+    "    \\int_0^x t^{a-1}(1-t)^{b-1}dt,\n"
+    "\n"
+    "where :math:`I_x` is the normalized incomplete beta function `betainc`\n"
+    "and :math:`\\Gamma` is the `gamma` function [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Positive, real-valued parameters\n"
+    "y : array_like\n"
+    "    Real-valued input\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the inverse of the regularized incomplete beta function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "betainc : regularized incomplete beta function\n"
+    "gamma : gamma function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function wraps the ``ibeta_inv`` routine from the\n"
+    "Boost Math C++ library [2]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] NIST Digital Library of Mathematical Functions\n"
+    "       https://dlmf.nist.gov/8.17\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "This function is the inverse of `betainc` for fixed\n"
+    "values of :math:`a` and :math:`b`.\n"
+    "\n"
+    ">>> a, b = 1.2, 3.1\n"
+    ">>> y = sc.betainc(a, b, 0.2)\n"
+    ">>> sc.betaincinv(a, b, y)\n"
+    "0.2\n"
+    ">>>\n"
+    ">>> a, b = 7.5, 0.4\n"
+    ">>> x = sc.betaincinv(a, b, 0.5)\n"
+    ">>> sc.betainc(a, b, x)\n"
+    "0.5")
+ufunc_betaincinv_loops[0] = loop_f_fff__As_fff_f
+ufunc_betaincinv_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_betaincinv_types[0] = NPY_FLOAT
+ufunc_betaincinv_types[1] = NPY_FLOAT
+ufunc_betaincinv_types[2] = NPY_FLOAT
+ufunc_betaincinv_types[3] = NPY_FLOAT
+ufunc_betaincinv_types[4] = NPY_DOUBLE
+ufunc_betaincinv_types[5] = NPY_DOUBLE
+ufunc_betaincinv_types[6] = NPY_DOUBLE
+ufunc_betaincinv_types[7] = NPY_DOUBLE
+ufunc_betaincinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_ibeta_inv_float
+ufunc_betaincinv_ptr[2*0+1] = ("betaincinv")
+ufunc_betaincinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_ibeta_inv_double
+ufunc_betaincinv_ptr[2*1+1] = ("betaincinv")
+ufunc_betaincinv_data[0] = &ufunc_betaincinv_ptr[2*0]
+ufunc_betaincinv_data[1] = &ufunc_betaincinv_ptr[2*1]
+betaincinv = np.PyUFunc_FromFuncAndData(ufunc_betaincinv_loops, ufunc_betaincinv_data, ufunc_betaincinv_types, 2, 3, 1, 0, "betaincinv", ufunc_betaincinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_boxcox_loops[2]
+cdef void *ufunc_boxcox_ptr[4]
+cdef void *ufunc_boxcox_data[2]
+cdef char ufunc_boxcox_types[6]
+cdef char *ufunc_boxcox_doc = (
+    "boxcox(x, lmbda, out=None)\n"
+    "\n"
+    "Compute the Box-Cox transformation.\n"
+    "\n"
+    "The Box-Cox transformation is::\n"
+    "\n"
+    "    y = (x**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(x)                  if lmbda == 0\n"
+    "\n"
+    "Returns `nan` if ``x < 0``.\n"
+    "Returns `-inf` if ``x == 0`` and ``lmbda < 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.14.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox\n"
+    ">>> boxcox([1, 4, 10], 2.5)\n"
+    "array([   0.        ,   12.4       ,  126.09110641])\n"
+    ">>> boxcox(2, [0, 1, 2])\n"
+    "array([ 0.69314718,  1.        ,  1.5       ])")
+ufunc_boxcox_loops[0] = loop_d_dd__As_ff_f
+ufunc_boxcox_loops[1] = loop_d_dd__As_dd_d
+ufunc_boxcox_types[0] = NPY_FLOAT
+ufunc_boxcox_types[1] = NPY_FLOAT
+ufunc_boxcox_types[2] = NPY_FLOAT
+ufunc_boxcox_types[3] = NPY_DOUBLE
+ufunc_boxcox_types[4] = NPY_DOUBLE
+ufunc_boxcox_types[5] = NPY_DOUBLE
+ufunc_boxcox_ptr[2*0] = _func_boxcox
+ufunc_boxcox_ptr[2*0+1] = ("boxcox")
+ufunc_boxcox_ptr[2*1] = _func_boxcox
+ufunc_boxcox_ptr[2*1+1] = ("boxcox")
+ufunc_boxcox_data[0] = &ufunc_boxcox_ptr[2*0]
+ufunc_boxcox_data[1] = &ufunc_boxcox_ptr[2*1]
+boxcox = np.PyUFunc_FromFuncAndData(ufunc_boxcox_loops, ufunc_boxcox_data, ufunc_boxcox_types, 2, 2, 1, 0, "boxcox", ufunc_boxcox_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_boxcox1p_loops[2]
+cdef void *ufunc_boxcox1p_ptr[4]
+cdef void *ufunc_boxcox1p_data[2]
+cdef char ufunc_boxcox1p_types[6]
+cdef char *ufunc_boxcox1p_doc = (
+    "boxcox1p(x, lmbda, out=None)\n"
+    "\n"
+    "Compute the Box-Cox transformation of 1 + `x`.\n"
+    "\n"
+    "The Box-Cox transformation computed by `boxcox1p` is::\n"
+    "\n"
+    "    y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(1+x)                    if lmbda == 0\n"
+    "\n"
+    "Returns `nan` if ``x < -1``.\n"
+    "Returns `-inf` if ``x == -1`` and ``lmbda < 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.14.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox1p\n"
+    ">>> boxcox1p(1e-4, [0, 0.5, 1])\n"
+    "array([  9.99950003e-05,   9.99975001e-05,   1.00000000e-04])\n"
+    ">>> boxcox1p([0.01, 0.1], 0.25)\n"
+    "array([ 0.00996272,  0.09645476])")
+ufunc_boxcox1p_loops[0] = loop_d_dd__As_ff_f
+ufunc_boxcox1p_loops[1] = loop_d_dd__As_dd_d
+ufunc_boxcox1p_types[0] = NPY_FLOAT
+ufunc_boxcox1p_types[1] = NPY_FLOAT
+ufunc_boxcox1p_types[2] = NPY_FLOAT
+ufunc_boxcox1p_types[3] = NPY_DOUBLE
+ufunc_boxcox1p_types[4] = NPY_DOUBLE
+ufunc_boxcox1p_types[5] = NPY_DOUBLE
+ufunc_boxcox1p_ptr[2*0] = _func_boxcox1p
+ufunc_boxcox1p_ptr[2*0+1] = ("boxcox1p")
+ufunc_boxcox1p_ptr[2*1] = _func_boxcox1p
+ufunc_boxcox1p_ptr[2*1+1] = ("boxcox1p")
+ufunc_boxcox1p_data[0] = &ufunc_boxcox1p_ptr[2*0]
+ufunc_boxcox1p_data[1] = &ufunc_boxcox1p_ptr[2*1]
+boxcox1p = np.PyUFunc_FromFuncAndData(ufunc_boxcox1p_loops, ufunc_boxcox1p_data, ufunc_boxcox1p_types, 2, 2, 1, 0, "boxcox1p", ufunc_boxcox1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_btdtria_loops[2]
+cdef void *ufunc_btdtria_ptr[4]
+cdef void *ufunc_btdtria_data[2]
+cdef char ufunc_btdtria_types[8]
+cdef char *ufunc_btdtria_doc = (
+    "btdtria(p, b, x, out=None)\n"
+    "\n"
+    "Inverse of `betainc` with respect to `a`.\n"
+    "\n"
+    "This is the inverse of the beta cumulative distribution function, `betainc`,\n"
+    "considered as a function of `a`, returning the value of `a` for which\n"
+    "`betainc(a, b, x) = p`, or\n"
+    "\n"
+    ".. math::\n"
+    "    p = \\int_0^x \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} t^{a-1} (1-t)^{b-1}\\,dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "b : array_like\n"
+    "    Shape parameter (`b` > 0).\n"
+    "x : array_like\n"
+    "    The quantile, in [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "a : scalar or ndarray\n"
+    "    The value of the shape parameter `a` such that `betainc(a, b, x) = p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "btdtrib : Inverse of the beta cumulative distribution function, with respect to `b`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `a` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `a`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Algorithm 708: Significant Digit Computation of the Incomplete Beta\n"
+    "       Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.")
+ufunc_btdtria_loops[0] = loop_d_ddd__As_fff_f
+ufunc_btdtria_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_btdtria_types[0] = NPY_FLOAT
+ufunc_btdtria_types[1] = NPY_FLOAT
+ufunc_btdtria_types[2] = NPY_FLOAT
+ufunc_btdtria_types[3] = NPY_FLOAT
+ufunc_btdtria_types[4] = NPY_DOUBLE
+ufunc_btdtria_types[5] = NPY_DOUBLE
+ufunc_btdtria_types[6] = NPY_DOUBLE
+ufunc_btdtria_types[7] = NPY_DOUBLE
+ufunc_btdtria_ptr[2*0] = _func_btdtria
+ufunc_btdtria_ptr[2*0+1] = ("btdtria")
+ufunc_btdtria_ptr[2*1] = _func_btdtria
+ufunc_btdtria_ptr[2*1+1] = ("btdtria")
+ufunc_btdtria_data[0] = &ufunc_btdtria_ptr[2*0]
+ufunc_btdtria_data[1] = &ufunc_btdtria_ptr[2*1]
+btdtria = np.PyUFunc_FromFuncAndData(ufunc_btdtria_loops, ufunc_btdtria_data, ufunc_btdtria_types, 2, 3, 1, 0, "btdtria", ufunc_btdtria_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_btdtrib_loops[2]
+cdef void *ufunc_btdtrib_ptr[4]
+cdef void *ufunc_btdtrib_data[2]
+cdef char ufunc_btdtrib_types[8]
+cdef char *ufunc_btdtrib_doc = (
+    "btdtria(a, p, x, out=None)\n"
+    "\n"
+    "Inverse of `betainc` with respect to `b`.\n"
+    "\n"
+    "This is the inverse of the beta cumulative distribution function, `betainc`,\n"
+    "considered as a function of `b`, returning the value of `b` for which\n"
+    "`betainc(a, b, x) = p`, or\n"
+    "\n"
+    ".. math::\n"
+    "    p = \\int_0^x \\frac{\\Gamma(a + b)}{\\Gamma(a)\\Gamma(b)} t^{a-1} (1-t)^{b-1}\\,dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    Shape parameter (`a` > 0).\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "x : array_like\n"
+    "    The quantile, in [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "b : scalar or ndarray\n"
+    "    The value of the shape parameter `b` such that `betainc(a, b, x) = p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "btdtria : Inverse of the beta cumulative distribution function, with respect to `a`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfbet`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `b` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `b`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Algorithm 708: Significant Digit Computation of the Incomplete Beta\n"
+    "       Function Ratios. ACM Trans. Math. Softw. 18 (1993), 360-373.")
+ufunc_btdtrib_loops[0] = loop_d_ddd__As_fff_f
+ufunc_btdtrib_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_btdtrib_types[0] = NPY_FLOAT
+ufunc_btdtrib_types[1] = NPY_FLOAT
+ufunc_btdtrib_types[2] = NPY_FLOAT
+ufunc_btdtrib_types[3] = NPY_FLOAT
+ufunc_btdtrib_types[4] = NPY_DOUBLE
+ufunc_btdtrib_types[5] = NPY_DOUBLE
+ufunc_btdtrib_types[6] = NPY_DOUBLE
+ufunc_btdtrib_types[7] = NPY_DOUBLE
+ufunc_btdtrib_ptr[2*0] = _func_btdtrib
+ufunc_btdtrib_ptr[2*0+1] = ("btdtrib")
+ufunc_btdtrib_ptr[2*1] = _func_btdtrib
+ufunc_btdtrib_ptr[2*1+1] = ("btdtrib")
+ufunc_btdtrib_data[0] = &ufunc_btdtrib_ptr[2*0]
+ufunc_btdtrib_data[1] = &ufunc_btdtrib_ptr[2*1]
+btdtrib = np.PyUFunc_FromFuncAndData(ufunc_btdtrib_loops, ufunc_btdtrib_data, ufunc_btdtrib_types, 2, 3, 1, 0, "btdtrib", ufunc_btdtrib_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtr_loops[2]
+cdef void *ufunc_chdtr_ptr[4]
+cdef void *ufunc_chdtr_data[2]
+cdef char ufunc_chdtr_types[6]
+cdef char *ufunc_chdtr_doc = (
+    "chdtr(v, x, out=None)\n"
+    "\n"
+    "Chi square cumulative distribution function.\n"
+    "\n"
+    "Returns the area under the left tail (from 0 to `x`) of the Chi\n"
+    "square probability density function with `v` degrees of freedom:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\frac{1}{2^{v/2} \\Gamma(v/2)} \\int_0^x t^{v/2 - 1} e^{-t/2} dt\n"
+    "\n"
+    "Here :math:`\\Gamma` is the Gamma function; see `gamma`. This\n"
+    "integral can be expressed in terms of the regularized lower\n"
+    "incomplete gamma function `gammainc` as\n"
+    "``gammainc(v / 2, x / 2)``. [1]_\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Degrees of freedom.\n"
+    "x : array_like\n"
+    "    Upper bound of the integral.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the cumulative distribution function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtrc, chdtri, chdtriv, gammainc\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It can be expressed in terms of the regularized lower incomplete\n"
+    "gamma function.\n"
+    "\n"
+    ">>> v = 1\n"
+    ">>> x = np.arange(4)\n"
+    ">>> sc.chdtr(v, x)\n"
+    "array([0.        , 0.68268949, 0.84270079, 0.91673548])\n"
+    ">>> sc.gammainc(v / 2, x / 2)\n"
+    "array([0.        , 0.68268949, 0.84270079, 0.91673548])")
+ufunc_chdtr_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtr_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtr_types[0] = NPY_FLOAT
+ufunc_chdtr_types[1] = NPY_FLOAT
+ufunc_chdtr_types[2] = NPY_FLOAT
+ufunc_chdtr_types[3] = NPY_DOUBLE
+ufunc_chdtr_types[4] = NPY_DOUBLE
+ufunc_chdtr_types[5] = NPY_DOUBLE
+ufunc_chdtr_ptr[2*0] = _func_xsf_chdtr
+ufunc_chdtr_ptr[2*0+1] = ("chdtr")
+ufunc_chdtr_ptr[2*1] = _func_xsf_chdtr
+ufunc_chdtr_ptr[2*1+1] = ("chdtr")
+ufunc_chdtr_data[0] = &ufunc_chdtr_ptr[2*0]
+ufunc_chdtr_data[1] = &ufunc_chdtr_ptr[2*1]
+chdtr = np.PyUFunc_FromFuncAndData(ufunc_chdtr_loops, ufunc_chdtr_data, ufunc_chdtr_types, 2, 2, 1, 0, "chdtr", ufunc_chdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtrc_loops[2]
+cdef void *ufunc_chdtrc_ptr[4]
+cdef void *ufunc_chdtrc_data[2]
+cdef char ufunc_chdtrc_types[6]
+cdef char *ufunc_chdtrc_doc = (
+    "chdtrc(v, x, out=None)\n"
+    "\n"
+    "Chi square survival function.\n"
+    "\n"
+    "Returns the area under the right hand tail (from `x` to infinity)\n"
+    "of the Chi square probability density function with `v` degrees of\n"
+    "freedom:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\frac{1}{2^{v/2} \\Gamma(v/2)} \\int_x^\\infty t^{v/2 - 1} e^{-t/2} dt\n"
+    "\n"
+    "Here :math:`\\Gamma` is the Gamma function; see `gamma`. This\n"
+    "integral can be expressed in terms of the regularized upper\n"
+    "incomplete gamma function `gammaincc` as\n"
+    "``gammaincc(v / 2, x / 2)``. [1]_\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Degrees of freedom.\n"
+    "x : array_like\n"
+    "    Lower bound of the integral.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the survival function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtr, chdtri, chdtriv, gammaincc\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It can be expressed in terms of the regularized upper incomplete\n"
+    "gamma function.\n"
+    "\n"
+    ">>> v = 1\n"
+    ">>> x = np.arange(4)\n"
+    ">>> sc.chdtrc(v, x)\n"
+    "array([1.        , 0.31731051, 0.15729921, 0.08326452])\n"
+    ">>> sc.gammaincc(v / 2, x / 2)\n"
+    "array([1.        , 0.31731051, 0.15729921, 0.08326452])")
+ufunc_chdtrc_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtrc_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtrc_types[0] = NPY_FLOAT
+ufunc_chdtrc_types[1] = NPY_FLOAT
+ufunc_chdtrc_types[2] = NPY_FLOAT
+ufunc_chdtrc_types[3] = NPY_DOUBLE
+ufunc_chdtrc_types[4] = NPY_DOUBLE
+ufunc_chdtrc_types[5] = NPY_DOUBLE
+ufunc_chdtrc_ptr[2*0] = _func_xsf_chdtrc
+ufunc_chdtrc_ptr[2*0+1] = ("chdtrc")
+ufunc_chdtrc_ptr[2*1] = _func_xsf_chdtrc
+ufunc_chdtrc_ptr[2*1+1] = ("chdtrc")
+ufunc_chdtrc_data[0] = &ufunc_chdtrc_ptr[2*0]
+ufunc_chdtrc_data[1] = &ufunc_chdtrc_ptr[2*1]
+chdtrc = np.PyUFunc_FromFuncAndData(ufunc_chdtrc_loops, ufunc_chdtrc_data, ufunc_chdtrc_types, 2, 2, 1, 0, "chdtrc", ufunc_chdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtri_loops[2]
+cdef void *ufunc_chdtri_ptr[4]
+cdef void *ufunc_chdtri_data[2]
+cdef char ufunc_chdtri_types[6]
+cdef char *ufunc_chdtri_doc = (
+    "chdtri(v, p, out=None)\n"
+    "\n"
+    "Inverse to `chdtrc` with respect to `x`.\n"
+    "\n"
+    "Returns `x` such that ``chdtrc(v, x) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Degrees of freedom.\n"
+    "p : array_like\n"
+    "    Probability.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value so that the probability a Chi square random variable\n"
+    "    with `v` degrees of freedom is greater than `x` equals `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtrc, chdtr, chdtriv\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It inverts `chdtrc`.\n"
+    "\n"
+    ">>> v, p = 1, 0.3\n"
+    ">>> sc.chdtrc(v, sc.chdtri(v, p))\n"
+    "0.3\n"
+    ">>> x = 1\n"
+    ">>> sc.chdtri(v, sc.chdtrc(v, x))\n"
+    "1.0")
+ufunc_chdtri_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtri_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtri_types[0] = NPY_FLOAT
+ufunc_chdtri_types[1] = NPY_FLOAT
+ufunc_chdtri_types[2] = NPY_FLOAT
+ufunc_chdtri_types[3] = NPY_DOUBLE
+ufunc_chdtri_types[4] = NPY_DOUBLE
+ufunc_chdtri_types[5] = NPY_DOUBLE
+ufunc_chdtri_ptr[2*0] = _func_xsf_chdtri
+ufunc_chdtri_ptr[2*0+1] = ("chdtri")
+ufunc_chdtri_ptr[2*1] = _func_xsf_chdtri
+ufunc_chdtri_ptr[2*1+1] = ("chdtri")
+ufunc_chdtri_data[0] = &ufunc_chdtri_ptr[2*0]
+ufunc_chdtri_data[1] = &ufunc_chdtri_ptr[2*1]
+chdtri = np.PyUFunc_FromFuncAndData(ufunc_chdtri_loops, ufunc_chdtri_data, ufunc_chdtri_types, 2, 2, 1, 0, "chdtri", ufunc_chdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chdtriv_loops[2]
+cdef void *ufunc_chdtriv_ptr[4]
+cdef void *ufunc_chdtriv_data[2]
+cdef char ufunc_chdtriv_types[6]
+cdef char *ufunc_chdtriv_doc = (
+    "chdtriv(p, x, out=None)\n"
+    "\n"
+    "Inverse to `chdtr` with respect to `v`.\n"
+    "\n"
+    "Returns `v` such that ``chdtr(v, x) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability that the Chi square random variable is less than\n"
+    "    or equal to `x`.\n"
+    "x : array_like\n"
+    "    Nonnegative input.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Degrees of freedom.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chdtr, chdtrc, chdtri\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Chi-Square distribution,\n"
+    "    https://www.itl.nist.gov/div898/handbook/eda/section3/eda3666.htm\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It inverts `chdtr`.\n"
+    "\n"
+    ">>> p, x = 0.5, 1\n"
+    ">>> sc.chdtr(sc.chdtriv(p, x), x)\n"
+    "0.5000000000202172\n"
+    ">>> v = 1\n"
+    ">>> sc.chdtriv(sc.chdtr(v, x), v)\n"
+    "1.0000000000000013")
+ufunc_chdtriv_loops[0] = loop_d_dd__As_ff_f
+ufunc_chdtriv_loops[1] = loop_d_dd__As_dd_d
+ufunc_chdtriv_types[0] = NPY_FLOAT
+ufunc_chdtriv_types[1] = NPY_FLOAT
+ufunc_chdtriv_types[2] = NPY_FLOAT
+ufunc_chdtriv_types[3] = NPY_DOUBLE
+ufunc_chdtriv_types[4] = NPY_DOUBLE
+ufunc_chdtriv_types[5] = NPY_DOUBLE
+ufunc_chdtriv_ptr[2*0] = _func_chdtriv
+ufunc_chdtriv_ptr[2*0+1] = ("chdtriv")
+ufunc_chdtriv_ptr[2*1] = _func_chdtriv
+ufunc_chdtriv_ptr[2*1+1] = ("chdtriv")
+ufunc_chdtriv_data[0] = &ufunc_chdtriv_ptr[2*0]
+ufunc_chdtriv_data[1] = &ufunc_chdtriv_ptr[2*1]
+chdtriv = np.PyUFunc_FromFuncAndData(ufunc_chdtriv_loops, ufunc_chdtriv_data, ufunc_chdtriv_types, 2, 2, 1, 0, "chdtriv", ufunc_chdtriv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtr_loops[2]
+cdef void *ufunc_chndtr_ptr[4]
+cdef void *ufunc_chndtr_data[2]
+cdef char ufunc_chndtr_types[8]
+cdef char *ufunc_chndtr_doc = (
+    "chndtr(x, df, nc, out=None)\n"
+    "\n"
+    "Non-central chi square cumulative distribution function\n"
+    "\n"
+    "The cumulative distribution function is given by:\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P(\\chi^{\\prime 2} \\vert \\nu, \\lambda) =\\sum_{j=0}^{\\infty}\n"
+    "    e^{-\\lambda /2}\n"
+    "    \\frac{(\\lambda /2)^j}{j!} P(\\chi^{\\prime 2} \\vert \\nu + 2j),\n"
+    "\n"
+    "where :math:`\\nu > 0` is the degrees of freedom (``df``) and\n"
+    ":math:`\\lambda \\geq 0` is the non-centrality parameter (``nc``).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Upper bound of the integral; must satisfy ``x >= 0``\n"
+    "df : array_like\n"
+    "    Degrees of freedom; must satisfy ``df > 0``\n"
+    "nc : array_like\n"
+    "    Non-centrality parameter; must satisfy ``nc >= 0``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value of the non-central chi square cumulative distribution function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtrix, chndtridf, chndtrinc")
+ufunc_chndtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtr_types[0] = NPY_FLOAT
+ufunc_chndtr_types[1] = NPY_FLOAT
+ufunc_chndtr_types[2] = NPY_FLOAT
+ufunc_chndtr_types[3] = NPY_FLOAT
+ufunc_chndtr_types[4] = NPY_DOUBLE
+ufunc_chndtr_types[5] = NPY_DOUBLE
+ufunc_chndtr_types[6] = NPY_DOUBLE
+ufunc_chndtr_types[7] = NPY_DOUBLE
+ufunc_chndtr_ptr[2*0] = _func_chndtr
+ufunc_chndtr_ptr[2*0+1] = ("chndtr")
+ufunc_chndtr_ptr[2*1] = _func_chndtr
+ufunc_chndtr_ptr[2*1+1] = ("chndtr")
+ufunc_chndtr_data[0] = &ufunc_chndtr_ptr[2*0]
+ufunc_chndtr_data[1] = &ufunc_chndtr_ptr[2*1]
+chndtr = np.PyUFunc_FromFuncAndData(ufunc_chndtr_loops, ufunc_chndtr_data, ufunc_chndtr_types, 2, 3, 1, 0, "chndtr", ufunc_chndtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtridf_loops[2]
+cdef void *ufunc_chndtridf_ptr[4]
+cdef void *ufunc_chndtridf_data[2]
+cdef char ufunc_chndtridf_types[8]
+cdef char *ufunc_chndtridf_doc = (
+    "chndtridf(x, p, nc, out=None)\n"
+    "\n"
+    "Inverse to `chndtr` vs `df`\n"
+    "\n"
+    "Calculated using a search to find a value for `df` that produces the\n"
+    "desired value of `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Upper bound of the integral; must satisfy ``x >= 0``\n"
+    "p : array_like\n"
+    "    Probability; must satisfy ``0 <= p < 1``\n"
+    "nc : array_like\n"
+    "    Non-centrality parameter; must satisfy ``nc >= 0``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "df : scalar or ndarray\n"
+    "    Degrees of freedom\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtr, chndtrix, chndtrinc")
+ufunc_chndtridf_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtridf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtridf_types[0] = NPY_FLOAT
+ufunc_chndtridf_types[1] = NPY_FLOAT
+ufunc_chndtridf_types[2] = NPY_FLOAT
+ufunc_chndtridf_types[3] = NPY_FLOAT
+ufunc_chndtridf_types[4] = NPY_DOUBLE
+ufunc_chndtridf_types[5] = NPY_DOUBLE
+ufunc_chndtridf_types[6] = NPY_DOUBLE
+ufunc_chndtridf_types[7] = NPY_DOUBLE
+ufunc_chndtridf_ptr[2*0] = _func_chndtridf
+ufunc_chndtridf_ptr[2*0+1] = ("chndtridf")
+ufunc_chndtridf_ptr[2*1] = _func_chndtridf
+ufunc_chndtridf_ptr[2*1+1] = ("chndtridf")
+ufunc_chndtridf_data[0] = &ufunc_chndtridf_ptr[2*0]
+ufunc_chndtridf_data[1] = &ufunc_chndtridf_ptr[2*1]
+chndtridf = np.PyUFunc_FromFuncAndData(ufunc_chndtridf_loops, ufunc_chndtridf_data, ufunc_chndtridf_types, 2, 3, 1, 0, "chndtridf", ufunc_chndtridf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtrinc_loops[2]
+cdef void *ufunc_chndtrinc_ptr[4]
+cdef void *ufunc_chndtrinc_data[2]
+cdef char ufunc_chndtrinc_types[8]
+cdef char *ufunc_chndtrinc_doc = (
+    "chndtrinc(x, df, p, out=None)\n"
+    "\n"
+    "Inverse to `chndtr` vs `nc`\n"
+    "\n"
+    "Calculated using a search to find a value for `df` that produces the\n"
+    "desired value of `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Upper bound of the integral; must satisfy ``x >= 0``\n"
+    "df : array_like\n"
+    "    Degrees of freedom; must satisfy ``df > 0``\n"
+    "p : array_like\n"
+    "    Probability; must satisfy ``0 <= p < 1``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "nc : scalar or ndarray\n"
+    "    Non-centrality\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtr, chndtrix, chndtrinc")
+ufunc_chndtrinc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtrinc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtrinc_types[0] = NPY_FLOAT
+ufunc_chndtrinc_types[1] = NPY_FLOAT
+ufunc_chndtrinc_types[2] = NPY_FLOAT
+ufunc_chndtrinc_types[3] = NPY_FLOAT
+ufunc_chndtrinc_types[4] = NPY_DOUBLE
+ufunc_chndtrinc_types[5] = NPY_DOUBLE
+ufunc_chndtrinc_types[6] = NPY_DOUBLE
+ufunc_chndtrinc_types[7] = NPY_DOUBLE
+ufunc_chndtrinc_ptr[2*0] = _func_chndtrinc
+ufunc_chndtrinc_ptr[2*0+1] = ("chndtrinc")
+ufunc_chndtrinc_ptr[2*1] = _func_chndtrinc
+ufunc_chndtrinc_ptr[2*1+1] = ("chndtrinc")
+ufunc_chndtrinc_data[0] = &ufunc_chndtrinc_ptr[2*0]
+ufunc_chndtrinc_data[1] = &ufunc_chndtrinc_ptr[2*1]
+chndtrinc = np.PyUFunc_FromFuncAndData(ufunc_chndtrinc_loops, ufunc_chndtrinc_data, ufunc_chndtrinc_types, 2, 3, 1, 0, "chndtrinc", ufunc_chndtrinc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_chndtrix_loops[2]
+cdef void *ufunc_chndtrix_ptr[4]
+cdef void *ufunc_chndtrix_data[2]
+cdef char ufunc_chndtrix_types[8]
+cdef char *ufunc_chndtrix_doc = (
+    "chndtrix(p, df, nc, out=None)\n"
+    "\n"
+    "Inverse to `chndtr` vs `x`\n"
+    "\n"
+    "Calculated using a search to find a value for `x` that produces the\n"
+    "desired value of `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability; must satisfy ``0 <= p < 1``\n"
+    "df : array_like\n"
+    "    Degrees of freedom; must satisfy ``df > 0``\n"
+    "nc : array_like\n"
+    "    Non-centrality parameter; must satisfy ``nc >= 0``\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value so that the probability a non-central Chi square random variable\n"
+    "    with `df` degrees of freedom and non-centrality, `nc`, is greater than\n"
+    "    `x` equals `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "chndtr, chndtridf, chndtrinc")
+ufunc_chndtrix_loops[0] = loop_d_ddd__As_fff_f
+ufunc_chndtrix_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_chndtrix_types[0] = NPY_FLOAT
+ufunc_chndtrix_types[1] = NPY_FLOAT
+ufunc_chndtrix_types[2] = NPY_FLOAT
+ufunc_chndtrix_types[3] = NPY_FLOAT
+ufunc_chndtrix_types[4] = NPY_DOUBLE
+ufunc_chndtrix_types[5] = NPY_DOUBLE
+ufunc_chndtrix_types[6] = NPY_DOUBLE
+ufunc_chndtrix_types[7] = NPY_DOUBLE
+ufunc_chndtrix_ptr[2*0] = _func_chndtrix
+ufunc_chndtrix_ptr[2*0+1] = ("chndtrix")
+ufunc_chndtrix_ptr[2*1] = _func_chndtrix
+ufunc_chndtrix_ptr[2*1+1] = ("chndtrix")
+ufunc_chndtrix_data[0] = &ufunc_chndtrix_ptr[2*0]
+ufunc_chndtrix_data[1] = &ufunc_chndtrix_ptr[2*1]
+chndtrix = np.PyUFunc_FromFuncAndData(ufunc_chndtrix_loops, ufunc_chndtrix_data, ufunc_chndtrix_types, 2, 3, 1, 0, "chndtrix", ufunc_chndtrix_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_dawsn_loops[4]
+cdef void *ufunc_dawsn_ptr[8]
+cdef void *ufunc_dawsn_data[4]
+cdef char ufunc_dawsn_types[8]
+cdef char *ufunc_dawsn_doc = (
+    "dawsn(x, out=None)\n"
+    "\n"
+    "Dawson's integral.\n"
+    "\n"
+    "Computes::\n"
+    "\n"
+    "    exp(-x**2) * integral(exp(t**2), t=0..x).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Function parameter.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    Value of the integral.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "wofz, erf, erfc, erfcx, erfi\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-15, 15, num=1000)\n"
+    ">>> plt.plot(x, special.dawsn(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$dawsn(x)$')\n"
+    ">>> plt.show()")
+ufunc_dawsn_loops[0] = loop_d_d__As_f_f
+ufunc_dawsn_loops[1] = loop_d_d__As_d_d
+ufunc_dawsn_loops[2] = loop_D_D__As_F_F
+ufunc_dawsn_loops[3] = loop_D_D__As_D_D
+ufunc_dawsn_types[0] = NPY_FLOAT
+ufunc_dawsn_types[1] = NPY_FLOAT
+ufunc_dawsn_types[2] = NPY_DOUBLE
+ufunc_dawsn_types[3] = NPY_DOUBLE
+ufunc_dawsn_types[4] = NPY_CFLOAT
+ufunc_dawsn_types[5] = NPY_CFLOAT
+ufunc_dawsn_types[6] = NPY_CDOUBLE
+ufunc_dawsn_types[7] = NPY_CDOUBLE
+ufunc_dawsn_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn
+ufunc_dawsn_ptr[2*0+1] = ("dawsn")
+ufunc_dawsn_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn
+ufunc_dawsn_ptr[2*1+1] = ("dawsn")
+ufunc_dawsn_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn_complex
+ufunc_dawsn_ptr[2*2+1] = ("dawsn")
+ufunc_dawsn_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_dawsn_complex
+ufunc_dawsn_ptr[2*3+1] = ("dawsn")
+ufunc_dawsn_data[0] = &ufunc_dawsn_ptr[2*0]
+ufunc_dawsn_data[1] = &ufunc_dawsn_ptr[2*1]
+ufunc_dawsn_data[2] = &ufunc_dawsn_ptr[2*2]
+ufunc_dawsn_data[3] = &ufunc_dawsn_ptr[2*3]
+dawsn = np.PyUFunc_FromFuncAndData(ufunc_dawsn_loops, ufunc_dawsn_data, ufunc_dawsn_types, 4, 1, 1, 0, "dawsn", ufunc_dawsn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprc_loops[4]
+cdef void *ufunc_elliprc_ptr[8]
+cdef void *ufunc_elliprc_data[4]
+cdef char ufunc_elliprc_types[12]
+cdef char *ufunc_elliprc_doc = (
+    "elliprc(x, y, out=None)\n"
+    "\n"
+    "Degenerate symmetric elliptic integral.\n"
+    "\n"
+    "The function RC is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{C}}(x, y) =\n"
+    "       \\frac{1}{2} \\int_0^{+\\infty} (t + x)^{-1/2} (t + y)^{-1} dt\n"
+    "       = R_{\\mathrm{F}}(x, y, y)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y : array_like\n"
+    "    Real or complex input parameters. `x` can be any number in the\n"
+    "    complex plane cut along the negative real axis. `y` must be non-zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If `y` is real and negative, the Cauchy\n"
+    "    principal value is returned. If both of `x` and `y` are real, the\n"
+    "    return value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "RC is a degenerate case of the symmetric integral RF: ``elliprc(x, y) ==\n"
+    "elliprf(x, y, y)``. It is an elementary function rather than an elliptic\n"
+    "integral.\n"
+    "\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order. [2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E6\n"
+    ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprc\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprc(scale*x, scale*y)\n"
+    "(0.5484493976710874-0.4169557678995833j)\n"
+    "\n"
+    ">>> elliprc(x, y)/np.sqrt(scale)\n"
+    "(0.5484493976710874-0.41695576789958333j)\n"
+    "\n"
+    "When the two arguments coincide, the integral is particularly\n"
+    "simple:\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> elliprc(x, x)\n"
+    "(0.4299173120614631-0.3041729818745595j)\n"
+    "\n"
+    ">>> 1/np.sqrt(x)\n"
+    "(0.4299173120614631-0.30417298187455954j)\n"
+    "\n"
+    "Another simple case: the first argument vanishes:\n"
+    "\n"
+    ">>> y = 1.2 + 3.4j\n"
+    ">>> elliprc(0, y)\n"
+    "(0.6753125346116815-0.47779380263880866j)\n"
+    "\n"
+    ">>> np.pi/2/np.sqrt(y)\n"
+    "(0.6753125346116815-0.4777938026388088j)\n"
+    "\n"
+    "When `x` and `y` are both positive, we can express\n"
+    ":math:`R_C(x,y)` in terms of more elementary functions.  For the\n"
+    "case :math:`0 \\le x < y`,\n"
+    "\n"
+    ">>> x = 3.2\n"
+    ">>> y = 6.\n"
+    ">>> elliprc(x, y)\n"
+    "0.44942991498453444\n"
+    "\n"
+    ">>> np.arctan(np.sqrt((y-x)/x))/np.sqrt(y-x)\n"
+    "0.44942991498453433\n"
+    "\n"
+    "And for the case :math:`0 \\le y < x`,\n"
+    "\n"
+    ">>> x = 6.\n"
+    ">>> y = 3.2\n"
+    ">>> elliprc(x,y)\n"
+    "0.4989837501576147\n"
+    "\n"
+    ">>> np.log((np.sqrt(x)+np.sqrt(x-y))/np.sqrt(y))/np.sqrt(x-y)\n"
+    "0.49898375015761476")
+ufunc_elliprc_loops[0] = loop_d_dd__As_ff_f
+ufunc_elliprc_loops[1] = loop_d_dd__As_dd_d
+ufunc_elliprc_loops[2] = loop_D_DD__As_FF_F
+ufunc_elliprc_loops[3] = loop_D_DD__As_DD_D
+ufunc_elliprc_types[0] = NPY_FLOAT
+ufunc_elliprc_types[1] = NPY_FLOAT
+ufunc_elliprc_types[2] = NPY_FLOAT
+ufunc_elliprc_types[3] = NPY_DOUBLE
+ufunc_elliprc_types[4] = NPY_DOUBLE
+ufunc_elliprc_types[5] = NPY_DOUBLE
+ufunc_elliprc_types[6] = NPY_CFLOAT
+ufunc_elliprc_types[7] = NPY_CFLOAT
+ufunc_elliprc_types[8] = NPY_CFLOAT
+ufunc_elliprc_types[9] = NPY_CDOUBLE
+ufunc_elliprc_types[10] = NPY_CDOUBLE
+ufunc_elliprc_types[11] = NPY_CDOUBLE
+ufunc_elliprc_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RC
+ufunc_elliprc_ptr[2*0+1] = ("elliprc")
+ufunc_elliprc_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RC
+ufunc_elliprc_ptr[2*1+1] = ("elliprc")
+ufunc_elliprc_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RC
+ufunc_elliprc_ptr[2*2+1] = ("elliprc")
+ufunc_elliprc_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RC
+ufunc_elliprc_ptr[2*3+1] = ("elliprc")
+ufunc_elliprc_data[0] = &ufunc_elliprc_ptr[2*0]
+ufunc_elliprc_data[1] = &ufunc_elliprc_ptr[2*1]
+ufunc_elliprc_data[2] = &ufunc_elliprc_ptr[2*2]
+ufunc_elliprc_data[3] = &ufunc_elliprc_ptr[2*3]
+elliprc = np.PyUFunc_FromFuncAndData(ufunc_elliprc_loops, ufunc_elliprc_data, ufunc_elliprc_types, 4, 2, 1, 0, "elliprc", ufunc_elliprc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprd_loops[4]
+cdef void *ufunc_elliprd_ptr[8]
+cdef void *ufunc_elliprd_data[4]
+cdef char ufunc_elliprd_types[16]
+cdef char *ufunc_elliprd_doc = (
+    "elliprd(x, y, z, out=None)\n"
+    "\n"
+    "Symmetric elliptic integral of the second kind.\n"
+    "\n"
+    "The function RD is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{D}}(x, y, z) =\n"
+    "       \\frac{3}{2} \\int_0^{+\\infty} [(t + x) (t + y)]^{-1/2} (t + z)^{-3/2}\n"
+    "       dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z : array_like\n"
+    "    Real or complex input parameters. `x` or `y` can be any number in the\n"
+    "    complex plane cut along the negative real axis, but at most one of them\n"
+    "    can be zero, while `z` must be non-zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, and `z` are real, the\n"
+    "    return value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric elliptic integral.\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "RD is a degenerate case of the elliptic integral RJ: ``elliprd(x, y, z) ==\n"
+    "elliprj(x, y, z, z)``.\n"
+    "\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order. [2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E5\n"
+    ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprd\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprd(scale*x, scale*y, scale*z)\n"
+    "(-0.03703043835680379-0.24500934665683802j)\n"
+    "\n"
+    ">>> elliprd(x, y, z)*np.power(scale, -1.5)\n"
+    "(-0.0370304383568038-0.24500934665683805j)\n"
+    "\n"
+    "All three arguments coincide:\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> elliprd(x, x, x)\n"
+    "(-0.03986825876151896-0.14051741840449586j)\n"
+    "\n"
+    ">>> np.power(x, -1.5)\n"
+    "(-0.03986825876151894-0.14051741840449583j)\n"
+    "\n"
+    "The so-called \"second lemniscate constant\":\n"
+    "\n"
+    ">>> elliprd(0, 2, 1)/3\n"
+    "0.5990701173677961\n"
+    "\n"
+    ">>> from scipy.special import gamma\n"
+    ">>> gamma(0.75)**2/np.sqrt(2*np.pi)\n"
+    "0.5990701173677959")
+ufunc_elliprd_loops[0] = loop_d_ddd__As_fff_f
+ufunc_elliprd_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_elliprd_loops[2] = loop_D_DDD__As_FFF_F
+ufunc_elliprd_loops[3] = loop_D_DDD__As_DDD_D
+ufunc_elliprd_types[0] = NPY_FLOAT
+ufunc_elliprd_types[1] = NPY_FLOAT
+ufunc_elliprd_types[2] = NPY_FLOAT
+ufunc_elliprd_types[3] = NPY_FLOAT
+ufunc_elliprd_types[4] = NPY_DOUBLE
+ufunc_elliprd_types[5] = NPY_DOUBLE
+ufunc_elliprd_types[6] = NPY_DOUBLE
+ufunc_elliprd_types[7] = NPY_DOUBLE
+ufunc_elliprd_types[8] = NPY_CFLOAT
+ufunc_elliprd_types[9] = NPY_CFLOAT
+ufunc_elliprd_types[10] = NPY_CFLOAT
+ufunc_elliprd_types[11] = NPY_CFLOAT
+ufunc_elliprd_types[12] = NPY_CDOUBLE
+ufunc_elliprd_types[13] = NPY_CDOUBLE
+ufunc_elliprd_types[14] = NPY_CDOUBLE
+ufunc_elliprd_types[15] = NPY_CDOUBLE
+ufunc_elliprd_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RD
+ufunc_elliprd_ptr[2*0+1] = ("elliprd")
+ufunc_elliprd_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RD
+ufunc_elliprd_ptr[2*1+1] = ("elliprd")
+ufunc_elliprd_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RD
+ufunc_elliprd_ptr[2*2+1] = ("elliprd")
+ufunc_elliprd_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RD
+ufunc_elliprd_ptr[2*3+1] = ("elliprd")
+ufunc_elliprd_data[0] = &ufunc_elliprd_ptr[2*0]
+ufunc_elliprd_data[1] = &ufunc_elliprd_ptr[2*1]
+ufunc_elliprd_data[2] = &ufunc_elliprd_ptr[2*2]
+ufunc_elliprd_data[3] = &ufunc_elliprd_ptr[2*3]
+elliprd = np.PyUFunc_FromFuncAndData(ufunc_elliprd_loops, ufunc_elliprd_data, ufunc_elliprd_types, 4, 3, 1, 0, "elliprd", ufunc_elliprd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprf_loops[4]
+cdef void *ufunc_elliprf_ptr[8]
+cdef void *ufunc_elliprf_data[4]
+cdef char ufunc_elliprf_types[16]
+cdef char *ufunc_elliprf_doc = (
+    "elliprf(x, y, z, out=None)\n"
+    "\n"
+    "Completely-symmetric elliptic integral of the first kind.\n"
+    "\n"
+    "The function RF is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{F}}(x, y, z) =\n"
+    "       \\frac{1}{2} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2} dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z : array_like\n"
+    "    Real or complex input parameters. `x`, `y`, or `z` can be any number in\n"
+    "    the complex plane cut along the negative real axis, but at most one of\n"
+    "    them can be zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, and `z` are real, the return\n"
+    "    value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric integral.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order (cf.:\n"
+    "https://dlmf.nist.gov/19.36.i) and the AGM algorithm for the complete\n"
+    "integral. [2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E1\n"
+    ".. [2] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprf\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprf(scale*x, scale*y, scale*z)\n"
+    "(0.5328051227278146-0.4008623567957094j)\n"
+    "\n"
+    ">>> elliprf(x, y, z)/np.sqrt(scale)\n"
+    "(0.5328051227278147-0.4008623567957095j)\n"
+    "\n"
+    "All three arguments coincide:\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> elliprf(x, x, x)\n"
+    "(0.42991731206146316-0.30417298187455954j)\n"
+    "\n"
+    ">>> 1/np.sqrt(x)\n"
+    "(0.4299173120614631-0.30417298187455954j)\n"
+    "\n"
+    "The so-called \"first lemniscate constant\":\n"
+    "\n"
+    ">>> elliprf(0, 1, 2)\n"
+    "1.3110287771460598\n"
+    "\n"
+    ">>> from scipy.special import gamma\n"
+    ">>> gamma(0.25)**2/(4*np.sqrt(2*np.pi))\n"
+    "1.3110287771460598")
+ufunc_elliprf_loops[0] = loop_d_ddd__As_fff_f
+ufunc_elliprf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_elliprf_loops[2] = loop_D_DDD__As_FFF_F
+ufunc_elliprf_loops[3] = loop_D_DDD__As_DDD_D
+ufunc_elliprf_types[0] = NPY_FLOAT
+ufunc_elliprf_types[1] = NPY_FLOAT
+ufunc_elliprf_types[2] = NPY_FLOAT
+ufunc_elliprf_types[3] = NPY_FLOAT
+ufunc_elliprf_types[4] = NPY_DOUBLE
+ufunc_elliprf_types[5] = NPY_DOUBLE
+ufunc_elliprf_types[6] = NPY_DOUBLE
+ufunc_elliprf_types[7] = NPY_DOUBLE
+ufunc_elliprf_types[8] = NPY_CFLOAT
+ufunc_elliprf_types[9] = NPY_CFLOAT
+ufunc_elliprf_types[10] = NPY_CFLOAT
+ufunc_elliprf_types[11] = NPY_CFLOAT
+ufunc_elliprf_types[12] = NPY_CDOUBLE
+ufunc_elliprf_types[13] = NPY_CDOUBLE
+ufunc_elliprf_types[14] = NPY_CDOUBLE
+ufunc_elliprf_types[15] = NPY_CDOUBLE
+ufunc_elliprf_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RF
+ufunc_elliprf_ptr[2*0+1] = ("elliprf")
+ufunc_elliprf_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RF
+ufunc_elliprf_ptr[2*1+1] = ("elliprf")
+ufunc_elliprf_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RF
+ufunc_elliprf_ptr[2*2+1] = ("elliprf")
+ufunc_elliprf_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RF
+ufunc_elliprf_ptr[2*3+1] = ("elliprf")
+ufunc_elliprf_data[0] = &ufunc_elliprf_ptr[2*0]
+ufunc_elliprf_data[1] = &ufunc_elliprf_ptr[2*1]
+ufunc_elliprf_data[2] = &ufunc_elliprf_ptr[2*2]
+ufunc_elliprf_data[3] = &ufunc_elliprf_ptr[2*3]
+elliprf = np.PyUFunc_FromFuncAndData(ufunc_elliprf_loops, ufunc_elliprf_data, ufunc_elliprf_types, 4, 3, 1, 0, "elliprf", ufunc_elliprf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprg_loops[4]
+cdef void *ufunc_elliprg_ptr[8]
+cdef void *ufunc_elliprg_data[4]
+cdef char ufunc_elliprg_types[16]
+cdef char *ufunc_elliprg_doc = (
+    "elliprg(x, y, z, out=None)\n"
+    "\n"
+    "Completely-symmetric elliptic integral of the second kind.\n"
+    "\n"
+    "The function RG is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{G}}(x, y, z) =\n"
+    "       \\frac{1}{4} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2}\n"
+    "       \\left(\\frac{x}{t + x} + \\frac{y}{t + y} + \\frac{z}{t + z}\\right) t\n"
+    "       dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z : array_like\n"
+    "    Real or complex input parameters. `x`, `y`, or `z` can be any number in\n"
+    "    the complex plane cut along the negative real axis.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, and `z` are real, the return\n"
+    "    value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric integral.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprj : Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The implementation uses the relation [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    2 R_{\\mathrm{G}}(x, y, z) =\n"
+    "       z R_{\\mathrm{F}}(x, y, z) -\n"
+    "       \\frac{1}{3} (x - z) (y - z) R_{\\mathrm{D}}(x, y, z) +\n"
+    "       \\sqrt{\\frac{x y}{z}}\n"
+    "\n"
+    "and the symmetry of `x`, `y`, `z` when at least one non-zero parameter can\n"
+    "be chosen as the pivot. When one of the arguments is close to zero, the AGM\n"
+    "method is applied instead. Other special cases are computed following Ref.\n"
+    "[2]_\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    ".. [2] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.16.E1\n"
+    "       https://dlmf.nist.gov/19.20.ii\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprg\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> scale = 0.3 + 0.4j\n"
+    ">>> elliprg(scale*x, scale*y, scale*z)\n"
+    "(1.195936862005246+0.8470988320464167j)\n"
+    "\n"
+    ">>> elliprg(x, y, z)*np.sqrt(scale)\n"
+    "(1.195936862005246+0.8470988320464165j)\n"
+    "\n"
+    "Simplifications:\n"
+    "\n"
+    ">>> elliprg(0, y, y)\n"
+    "1.756203682760182\n"
+    "\n"
+    ">>> 0.25*np.pi*np.sqrt(y)\n"
+    "1.7562036827601817\n"
+    "\n"
+    ">>> elliprg(0, 0, z)\n"
+    "1.224744871391589\n"
+    "\n"
+    ">>> 0.5*np.sqrt(z)\n"
+    "1.224744871391589\n"
+    "\n"
+    "The surface area of a triaxial ellipsoid with semiaxes ``a``, ``b``, and\n"
+    "``c`` is given by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    S = 4 \\pi a b c R_{\\mathrm{G}}(1 / a^2, 1 / b^2, 1 / c^2).\n"
+    "\n"
+    ">>> def ellipsoid_area(a, b, c):\n"
+    "...     r = 4.0 * np.pi * a * b * c\n"
+    "...     return r * elliprg(1.0 / (a * a), 1.0 / (b * b), 1.0 / (c * c))\n"
+    ">>> print(ellipsoid_area(1, 3, 5))\n"
+    "108.62688289491807")
+ufunc_elliprg_loops[0] = loop_d_ddd__As_fff_f
+ufunc_elliprg_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_elliprg_loops[2] = loop_D_DDD__As_FFF_F
+ufunc_elliprg_loops[3] = loop_D_DDD__As_DDD_D
+ufunc_elliprg_types[0] = NPY_FLOAT
+ufunc_elliprg_types[1] = NPY_FLOAT
+ufunc_elliprg_types[2] = NPY_FLOAT
+ufunc_elliprg_types[3] = NPY_FLOAT
+ufunc_elliprg_types[4] = NPY_DOUBLE
+ufunc_elliprg_types[5] = NPY_DOUBLE
+ufunc_elliprg_types[6] = NPY_DOUBLE
+ufunc_elliprg_types[7] = NPY_DOUBLE
+ufunc_elliprg_types[8] = NPY_CFLOAT
+ufunc_elliprg_types[9] = NPY_CFLOAT
+ufunc_elliprg_types[10] = NPY_CFLOAT
+ufunc_elliprg_types[11] = NPY_CFLOAT
+ufunc_elliprg_types[12] = NPY_CDOUBLE
+ufunc_elliprg_types[13] = NPY_CDOUBLE
+ufunc_elliprg_types[14] = NPY_CDOUBLE
+ufunc_elliprg_types[15] = NPY_CDOUBLE
+ufunc_elliprg_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RG
+ufunc_elliprg_ptr[2*0+1] = ("elliprg")
+ufunc_elliprg_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RG
+ufunc_elliprg_ptr[2*1+1] = ("elliprg")
+ufunc_elliprg_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RG
+ufunc_elliprg_ptr[2*2+1] = ("elliprg")
+ufunc_elliprg_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RG
+ufunc_elliprg_ptr[2*3+1] = ("elliprg")
+ufunc_elliprg_data[0] = &ufunc_elliprg_ptr[2*0]
+ufunc_elliprg_data[1] = &ufunc_elliprg_ptr[2*1]
+ufunc_elliprg_data[2] = &ufunc_elliprg_ptr[2*2]
+ufunc_elliprg_data[3] = &ufunc_elliprg_ptr[2*3]
+elliprg = np.PyUFunc_FromFuncAndData(ufunc_elliprg_loops, ufunc_elliprg_data, ufunc_elliprg_types, 4, 3, 1, 0, "elliprg", ufunc_elliprg_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_elliprj_loops[4]
+cdef void *ufunc_elliprj_ptr[8]
+cdef void *ufunc_elliprj_data[4]
+cdef char ufunc_elliprj_types[20]
+cdef char *ufunc_elliprj_doc = (
+    "elliprj(x, y, z, p, out=None)\n"
+    "\n"
+    "Symmetric elliptic integral of the third kind.\n"
+    "\n"
+    "The function RJ is defined as [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    R_{\\mathrm{J}}(x, y, z, p) =\n"
+    "       \\frac{3}{2} \\int_0^{+\\infty} [(t + x) (t + y) (t + z)]^{-1/2}\n"
+    "       (t + p)^{-1} dt\n"
+    "\n"
+    ".. warning::\n"
+    "    This function should be considered experimental when the inputs are\n"
+    "    unbalanced.  Check correctness with another independent implementation.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y, z, p : array_like\n"
+    "    Real or complex input parameters. `x`, `y`, or `z` are numbers in\n"
+    "    the complex plane cut along the negative real axis (subject to further\n"
+    "    constraints, see Notes), and at most one of them can be zero. `p` must\n"
+    "    be non-zero.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "R : scalar or ndarray\n"
+    "    Value of the integral. If all of `x`, `y`, `z`, and `p` are real, the\n"
+    "    return value is real. Otherwise, the return value is complex.\n"
+    "\n"
+    "    If `p` is real and negative, while `x`, `y`, and `z` are real,\n"
+    "    non-negative, and at most one of them is zero, the Cauchy principal\n"
+    "    value is returned. [1]_ [2]_\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "elliprc : Degenerate symmetric integral.\n"
+    "elliprd : Symmetric elliptic integral of the second kind.\n"
+    "elliprf : Completely-symmetric elliptic integral of the first kind.\n"
+    "elliprg : Completely-symmetric elliptic integral of the second kind.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The code implements Carlson's algorithm based on the duplication theorems\n"
+    "and series expansion up to the 7th order. [3]_ The algorithm is slightly\n"
+    "different from its earlier incarnation as it appears in [1]_, in that the\n"
+    "call to `elliprc` (or ``atan``/``atanh``, see [4]_) is no longer needed in\n"
+    "the inner loop. Asymptotic approximations are used where arguments differ\n"
+    "widely in the order of magnitude. [5]_\n"
+    "\n"
+    "The input values are subject to certain sufficient but not necessary\n"
+    "constraints when input arguments are complex. Notably, ``x``, ``y``, and\n"
+    "``z`` must have non-negative real parts, unless two of them are\n"
+    "non-negative and complex-conjugates to each other while the other is a real\n"
+    "non-negative number. [1]_ If the inputs do not satisfy the sufficient\n"
+    "condition described in Ref. [1]_ they are rejected outright with the output\n"
+    "set to NaN.\n"
+    "\n"
+    "In the case where one of ``x``, ``y``, and ``z`` is equal to ``p``, the\n"
+    "function ``elliprd`` should be preferred because of its less restrictive\n"
+    "domain.\n"
+    "\n"
+    ".. versionadded:: 1.8.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] B. C. Carlson, \"Numerical computation of real or complex elliptic\n"
+    "       integrals,\" Numer. Algorithm, vol. 10, no. 1, pp. 13-26, 1995.\n"
+    "       https://arxiv.org/abs/math/9409227\n"
+    "       https://doi.org/10.1007/BF02198293\n"
+    ".. [2] B. C. Carlson, ed., Chapter 19 in \"Digital Library of Mathematical\n"
+    "       Functions,\" NIST, US Dept. of Commerce.\n"
+    "       https://dlmf.nist.gov/19.20.iii\n"
+    ".. [3] B. C. Carlson, J. FitzSimmons, \"Reduction Theorems for Elliptic\n"
+    "       Integrands with the Square Root of Two Quadratic Factors,\" J.\n"
+    "       Comput. Appl. Math., vol. 118, nos. 1-2, pp. 71-85, 2000.\n"
+    "       https://doi.org/10.1016/S0377-0427(00)00282-X\n"
+    ".. [4] F. Johansson, \"Numerical Evaluation of Elliptic Functions, Elliptic\n"
+    "       Integrals and Modular Forms,\" in J. Blumlein, C. Schneider, P.\n"
+    "       Paule, eds., \"Elliptic Integrals, Elliptic Functions and Modular\n"
+    "       Forms in Quantum Field Theory,\" pp. 269-293, 2019 (Cham,\n"
+    "       Switzerland: Springer Nature Switzerland)\n"
+    "       https://arxiv.org/abs/1806.06725\n"
+    "       https://doi.org/10.1007/978-3-030-04480-0\n"
+    ".. [5] B. C. Carlson, J. L. Gustafson, \"Asymptotic Approximations for\n"
+    "       Symmetric Elliptic Integrals,\" SIAM J. Math. Anls., vol. 25, no. 2,\n"
+    "       pp. 288-303, 1994.\n"
+    "       https://arxiv.org/abs/math/9310223\n"
+    "       https://doi.org/10.1137/S0036141092228477\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Basic homogeneity property:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import elliprj\n"
+    "\n"
+    ">>> x = 1.2 + 3.4j\n"
+    ">>> y = 5.\n"
+    ">>> z = 6.\n"
+    ">>> p = 7.\n"
+    ">>> scale = 0.3 - 0.4j\n"
+    ">>> elliprj(scale*x, scale*y, scale*z, scale*p)\n"
+    "(0.10834905565679157+0.19694950747103812j)\n"
+    "\n"
+    ">>> elliprj(x, y, z, p)*np.power(scale, -1.5)\n"
+    "(0.10834905565679556+0.19694950747103854j)\n"
+    "\n"
+    "Reduction to simpler elliptic integral:\n"
+    "\n"
+    ">>> elliprj(x, y, z, z)\n"
+    "(0.08288462362195129-0.028376809745123258j)\n"
+    "\n"
+    ">>> from scipy.special import elliprd\n"
+    ">>> elliprd(x, y, z)\n"
+    "(0.08288462362195136-0.028376809745123296j)\n"
+    "\n"
+    "All arguments coincide:\n"
+    "\n"
+    ">>> elliprj(x, x, x, x)\n"
+    "(-0.03986825876151896-0.14051741840449586j)\n"
+    "\n"
+    ">>> np.power(x, -1.5)\n"
+    "(-0.03986825876151894-0.14051741840449583j)")
+ufunc_elliprj_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_elliprj_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_elliprj_loops[2] = loop_D_DDDD__As_FFFF_F
+ufunc_elliprj_loops[3] = loop_D_DDDD__As_DDDD_D
+ufunc_elliprj_types[0] = NPY_FLOAT
+ufunc_elliprj_types[1] = NPY_FLOAT
+ufunc_elliprj_types[2] = NPY_FLOAT
+ufunc_elliprj_types[3] = NPY_FLOAT
+ufunc_elliprj_types[4] = NPY_FLOAT
+ufunc_elliprj_types[5] = NPY_DOUBLE
+ufunc_elliprj_types[6] = NPY_DOUBLE
+ufunc_elliprj_types[7] = NPY_DOUBLE
+ufunc_elliprj_types[8] = NPY_DOUBLE
+ufunc_elliprj_types[9] = NPY_DOUBLE
+ufunc_elliprj_types[10] = NPY_CFLOAT
+ufunc_elliprj_types[11] = NPY_CFLOAT
+ufunc_elliprj_types[12] = NPY_CFLOAT
+ufunc_elliprj_types[13] = NPY_CFLOAT
+ufunc_elliprj_types[14] = NPY_CFLOAT
+ufunc_elliprj_types[15] = NPY_CDOUBLE
+ufunc_elliprj_types[16] = NPY_CDOUBLE
+ufunc_elliprj_types[17] = NPY_CDOUBLE
+ufunc_elliprj_types[18] = NPY_CDOUBLE
+ufunc_elliprj_types[19] = NPY_CDOUBLE
+ufunc_elliprj_ptr[2*0] = scipy.special._ufuncs_cxx._export_fellint_RJ
+ufunc_elliprj_ptr[2*0+1] = ("elliprj")
+ufunc_elliprj_ptr[2*1] = scipy.special._ufuncs_cxx._export_fellint_RJ
+ufunc_elliprj_ptr[2*1+1] = ("elliprj")
+ufunc_elliprj_ptr[2*2] = scipy.special._ufuncs_cxx._export_cellint_RJ
+ufunc_elliprj_ptr[2*2+1] = ("elliprj")
+ufunc_elliprj_ptr[2*3] = scipy.special._ufuncs_cxx._export_cellint_RJ
+ufunc_elliprj_ptr[2*3+1] = ("elliprj")
+ufunc_elliprj_data[0] = &ufunc_elliprj_ptr[2*0]
+ufunc_elliprj_data[1] = &ufunc_elliprj_ptr[2*1]
+ufunc_elliprj_data[2] = &ufunc_elliprj_ptr[2*2]
+ufunc_elliprj_data[3] = &ufunc_elliprj_ptr[2*3]
+elliprj = np.PyUFunc_FromFuncAndData(ufunc_elliprj_loops, ufunc_elliprj_data, ufunc_elliprj_types, 4, 4, 1, 0, "elliprj", ufunc_elliprj_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_entr_loops[2]
+cdef void *ufunc_entr_ptr[4]
+cdef void *ufunc_entr_data[2]
+cdef char ufunc_entr_types[4]
+cdef char *ufunc_entr_doc = (
+    "entr(x, out=None)\n"
+    "\n"
+    "Elementwise function for computing entropy.\n"
+    "\n"
+    ".. math:: \\text{entr}(x) = \\begin{cases} - x \\log(x) & x > 0  \\\\ 0 & x = 0\n"
+    "          \\\\ -\\infty & \\text{otherwise} \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : ndarray\n"
+    "    Input array.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "res : scalar or ndarray\n"
+    "    The value of the elementwise entropy function at the given points `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kl_div, rel_entr, scipy.stats.entropy\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "This function is concave.\n"
+    "\n"
+    "The origin of this function is in convex programming; see [1]_.\n"
+    "Given a probability distribution :math:`p_1, \\ldots, p_n`,\n"
+    "the definition of entropy in the context of *information theory* is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\sum_{i = 1}^n \\mathrm{entr}(p_i).\n"
+    "\n"
+    "To compute the latter quantity, use `scipy.stats.entropy`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n"
+    "       Cambridge University Press, 2004.\n"
+    "       :doi:`https://doi.org/10.1017/CBO9780511804441`")
+ufunc_entr_loops[0] = loop_d_d__As_f_f
+ufunc_entr_loops[1] = loop_d_d__As_d_d
+ufunc_entr_types[0] = NPY_FLOAT
+ufunc_entr_types[1] = NPY_FLOAT
+ufunc_entr_types[2] = NPY_DOUBLE
+ufunc_entr_types[3] = NPY_DOUBLE
+ufunc_entr_ptr[2*0] = _func_entr
+ufunc_entr_ptr[2*0+1] = ("entr")
+ufunc_entr_ptr[2*1] = _func_entr
+ufunc_entr_ptr[2*1+1] = ("entr")
+ufunc_entr_data[0] = &ufunc_entr_ptr[2*0]
+ufunc_entr_data[1] = &ufunc_entr_ptr[2*1]
+entr = np.PyUFunc_FromFuncAndData(ufunc_entr_loops, ufunc_entr_data, ufunc_entr_types, 2, 1, 1, 0, "entr", ufunc_entr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erf_loops[4]
+cdef void *ufunc_erf_ptr[8]
+cdef void *ufunc_erf_data[4]
+cdef char ufunc_erf_types[8]
+cdef char *ufunc_erf_doc = (
+    "erf(z, out=None)\n"
+    "\n"
+    "Returns the error function of complex argument.\n"
+    "\n"
+    "It is defined as ``2/sqrt(pi)*integral(exp(-t**2), t=0..z)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : ndarray\n"
+    "    Input array.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "res : scalar or ndarray\n"
+    "    The values of the error function at the given points `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erfc, erfinv, erfcinv, wofz, erfcx, erfi\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The cumulative of the unit normal distribution is given by\n"
+    "``Phi(z) = 1/2[1 + erf(z/sqrt(2))]``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] https://en.wikipedia.org/wiki/Error_function\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover,\n"
+    "    1972. http://www.math.sfu.ca/~cbm/aands/page_297.htm\n"
+    ".. [3] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erf(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erf(x)$')\n"
+    ">>> plt.show()")
+ufunc_erf_loops[0] = loop_d_d__As_f_f
+ufunc_erf_loops[1] = loop_d_d__As_d_d
+ufunc_erf_loops[2] = loop_D_D__As_F_F
+ufunc_erf_loops[3] = loop_D_D__As_D_D
+ufunc_erf_types[0] = NPY_FLOAT
+ufunc_erf_types[1] = NPY_FLOAT
+ufunc_erf_types[2] = NPY_DOUBLE
+ufunc_erf_types[3] = NPY_DOUBLE
+ufunc_erf_types[4] = NPY_CFLOAT
+ufunc_erf_types[5] = NPY_CFLOAT
+ufunc_erf_types[6] = NPY_CDOUBLE
+ufunc_erf_types[7] = NPY_CDOUBLE
+ufunc_erf_ptr[2*0] = _func_cephes_erf
+ufunc_erf_ptr[2*0+1] = ("erf")
+ufunc_erf_ptr[2*1] = _func_cephes_erf
+ufunc_erf_ptr[2*1+1] = ("erf")
+ufunc_erf_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erf
+ufunc_erf_ptr[2*2+1] = ("erf")
+ufunc_erf_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erf
+ufunc_erf_ptr[2*3+1] = ("erf")
+ufunc_erf_data[0] = &ufunc_erf_ptr[2*0]
+ufunc_erf_data[1] = &ufunc_erf_ptr[2*1]
+ufunc_erf_data[2] = &ufunc_erf_ptr[2*2]
+ufunc_erf_data[3] = &ufunc_erf_ptr[2*3]
+erf = np.PyUFunc_FromFuncAndData(ufunc_erf_loops, ufunc_erf_data, ufunc_erf_types, 4, 1, 1, 0, "erf", ufunc_erf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfc_loops[4]
+cdef void *ufunc_erfc_ptr[8]
+cdef void *ufunc_erfc_data[4]
+cdef char ufunc_erfc_types[8]
+cdef char *ufunc_erfc_doc = (
+    "erfc(x, out=None)\n"
+    "\n"
+    "Complementary error function, ``1 - erf(x)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the complementary error function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf, erfi, erfcx, dawsn, wofz\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erfc(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erfc(x)$')\n"
+    ">>> plt.show()")
+ufunc_erfc_loops[0] = loop_d_d__As_f_f
+ufunc_erfc_loops[1] = loop_d_d__As_d_d
+ufunc_erfc_loops[2] = loop_D_D__As_F_F
+ufunc_erfc_loops[3] = loop_D_D__As_D_D
+ufunc_erfc_types[0] = NPY_FLOAT
+ufunc_erfc_types[1] = NPY_FLOAT
+ufunc_erfc_types[2] = NPY_DOUBLE
+ufunc_erfc_types[3] = NPY_DOUBLE
+ufunc_erfc_types[4] = NPY_CFLOAT
+ufunc_erfc_types[5] = NPY_CFLOAT
+ufunc_erfc_types[6] = NPY_CDOUBLE
+ufunc_erfc_types[7] = NPY_CDOUBLE
+ufunc_erfc_ptr[2*0] = _func_cephes_erfc
+ufunc_erfc_ptr[2*0+1] = ("erfc")
+ufunc_erfc_ptr[2*1] = _func_cephes_erfc
+ufunc_erfc_ptr[2*1+1] = ("erfc")
+ufunc_erfc_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfc_complex
+ufunc_erfc_ptr[2*2+1] = ("erfc")
+ufunc_erfc_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfc_complex
+ufunc_erfc_ptr[2*3+1] = ("erfc")
+ufunc_erfc_data[0] = &ufunc_erfc_ptr[2*0]
+ufunc_erfc_data[1] = &ufunc_erfc_ptr[2*1]
+ufunc_erfc_data[2] = &ufunc_erfc_ptr[2*2]
+ufunc_erfc_data[3] = &ufunc_erfc_ptr[2*3]
+erfc = np.PyUFunc_FromFuncAndData(ufunc_erfc_loops, ufunc_erfc_data, ufunc_erfc_types, 4, 1, 1, 0, "erfc", ufunc_erfc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfcinv_loops[2]
+cdef void *ufunc_erfcinv_ptr[4]
+cdef void *ufunc_erfcinv_data[2]
+cdef char ufunc_erfcinv_types[4]
+cdef char *ufunc_erfcinv_doc = (
+    "erfcinv(y, out=None)\n"
+    "\n"
+    "Inverse of the complementary error function.\n"
+    "\n"
+    "Computes the inverse of the complementary error function.\n"
+    "\n"
+    "In the complex domain, there is no unique complex number w satisfying\n"
+    "erfc(w)=z. This indicates a true inverse function would be multivalued.\n"
+    "When the domain restricts to the real, 0 < x < 2, there is a unique real\n"
+    "number satisfying erfc(erfcinv(x)) = erfcinv(erfc(x)).\n"
+    "\n"
+    "It is related to inverse of the error function by erfcinv(1-x) = erfinv(x)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : ndarray\n"
+    "    Argument at which to evaluate. Domain: [0, 2]\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "erfcinv : scalar or ndarray\n"
+    "    The inverse of erfc of y, element-wise\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf : Error function of a complex argument\n"
+    "erfc : Complementary error function, ``1 - erf(x)``\n"
+    "erfinv : Inverse of the error function\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import erfcinv\n"
+    "\n"
+    ">>> erfcinv(0.5)\n"
+    "0.4769362762044699\n"
+    "\n"
+    ">>> y = np.linspace(0.0, 2.0, num=11)\n"
+    ">>> erfcinv(y)\n"
+    "array([        inf,  0.9061938 ,  0.59511608,  0.37080716,  0.17914345,\n"
+    "       -0.        , -0.17914345, -0.37080716, -0.59511608, -0.9061938 ,\n"
+    "              -inf])\n"
+    "\n"
+    "Plot the function:\n"
+    "\n"
+    ">>> y = np.linspace(0, 2, 200)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(y, erfcinv(y))\n"
+    ">>> ax.grid(True)\n"
+    ">>> ax.set_xlabel('y')\n"
+    ">>> ax.set_title('erfcinv(y)')\n"
+    ">>> plt.show()")
+ufunc_erfcinv_loops[0] = loop_d_d__As_f_f
+ufunc_erfcinv_loops[1] = loop_d_d__As_d_d
+ufunc_erfcinv_types[0] = NPY_FLOAT
+ufunc_erfcinv_types[1] = NPY_FLOAT
+ufunc_erfcinv_types[2] = NPY_DOUBLE
+ufunc_erfcinv_types[3] = NPY_DOUBLE
+ufunc_erfcinv_ptr[2*0] = _func_cephes_erfcinv
+ufunc_erfcinv_ptr[2*0+1] = ("erfcinv")
+ufunc_erfcinv_ptr[2*1] = _func_cephes_erfcinv
+ufunc_erfcinv_ptr[2*1+1] = ("erfcinv")
+ufunc_erfcinv_data[0] = &ufunc_erfcinv_ptr[2*0]
+ufunc_erfcinv_data[1] = &ufunc_erfcinv_ptr[2*1]
+erfcinv = np.PyUFunc_FromFuncAndData(ufunc_erfcinv_loops, ufunc_erfcinv_data, ufunc_erfcinv_types, 2, 1, 1, 0, "erfcinv", ufunc_erfcinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfcx_loops[4]
+cdef void *ufunc_erfcx_ptr[8]
+cdef void *ufunc_erfcx_data[4]
+cdef char ufunc_erfcx_types[8]
+cdef char *ufunc_erfcx_doc = (
+    "erfcx(x, out=None)\n"
+    "\n"
+    "Scaled complementary error function, ``exp(x**2) * erfc(x)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the scaled complementary error function\n"
+    "\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf, erfc, erfi, dawsn, wofz\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.12.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erfcx(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erfcx(x)$')\n"
+    ">>> plt.show()")
+ufunc_erfcx_loops[0] = loop_d_d__As_f_f
+ufunc_erfcx_loops[1] = loop_d_d__As_d_d
+ufunc_erfcx_loops[2] = loop_D_D__As_F_F
+ufunc_erfcx_loops[3] = loop_D_D__As_D_D
+ufunc_erfcx_types[0] = NPY_FLOAT
+ufunc_erfcx_types[1] = NPY_FLOAT
+ufunc_erfcx_types[2] = NPY_DOUBLE
+ufunc_erfcx_types[3] = NPY_DOUBLE
+ufunc_erfcx_types[4] = NPY_CFLOAT
+ufunc_erfcx_types[5] = NPY_CFLOAT
+ufunc_erfcx_types[6] = NPY_CDOUBLE
+ufunc_erfcx_types[7] = NPY_CDOUBLE
+ufunc_erfcx_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx
+ufunc_erfcx_ptr[2*0+1] = ("erfcx")
+ufunc_erfcx_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx
+ufunc_erfcx_ptr[2*1+1] = ("erfcx")
+ufunc_erfcx_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx_complex
+ufunc_erfcx_ptr[2*2+1] = ("erfcx")
+ufunc_erfcx_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfcx_complex
+ufunc_erfcx_ptr[2*3+1] = ("erfcx")
+ufunc_erfcx_data[0] = &ufunc_erfcx_ptr[2*0]
+ufunc_erfcx_data[1] = &ufunc_erfcx_ptr[2*1]
+ufunc_erfcx_data[2] = &ufunc_erfcx_ptr[2*2]
+ufunc_erfcx_data[3] = &ufunc_erfcx_ptr[2*3]
+erfcx = np.PyUFunc_FromFuncAndData(ufunc_erfcx_loops, ufunc_erfcx_data, ufunc_erfcx_types, 4, 1, 1, 0, "erfcx", ufunc_erfcx_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfi_loops[4]
+cdef void *ufunc_erfi_ptr[8]
+cdef void *ufunc_erfi_data[4]
+cdef char ufunc_erfi_types[8]
+cdef char *ufunc_erfi_doc = (
+    "erfi(z, out=None)\n"
+    "\n"
+    "Imaginary error function, ``-i erf(i z)``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    Real or complex valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the imaginary error function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf, erfc, erfcx, dawsn, wofz\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.12.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> plt.plot(x, special.erfi(x))\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.ylabel('$erfi(x)$')\n"
+    ">>> plt.show()")
+ufunc_erfi_loops[0] = loop_d_d__As_f_f
+ufunc_erfi_loops[1] = loop_d_d__As_d_d
+ufunc_erfi_loops[2] = loop_D_D__As_F_F
+ufunc_erfi_loops[3] = loop_D_D__As_D_D
+ufunc_erfi_types[0] = NPY_FLOAT
+ufunc_erfi_types[1] = NPY_FLOAT
+ufunc_erfi_types[2] = NPY_DOUBLE
+ufunc_erfi_types[3] = NPY_DOUBLE
+ufunc_erfi_types[4] = NPY_CFLOAT
+ufunc_erfi_types[5] = NPY_CFLOAT
+ufunc_erfi_types[6] = NPY_CDOUBLE
+ufunc_erfi_types[7] = NPY_CDOUBLE
+ufunc_erfi_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_erfi
+ufunc_erfi_ptr[2*0+1] = ("erfi")
+ufunc_erfi_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_erfi
+ufunc_erfi_ptr[2*1+1] = ("erfi")
+ufunc_erfi_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_erfi_complex
+ufunc_erfi_ptr[2*2+1] = ("erfi")
+ufunc_erfi_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_erfi_complex
+ufunc_erfi_ptr[2*3+1] = ("erfi")
+ufunc_erfi_data[0] = &ufunc_erfi_ptr[2*0]
+ufunc_erfi_data[1] = &ufunc_erfi_ptr[2*1]
+ufunc_erfi_data[2] = &ufunc_erfi_ptr[2*2]
+ufunc_erfi_data[3] = &ufunc_erfi_ptr[2*3]
+erfi = np.PyUFunc_FromFuncAndData(ufunc_erfi_loops, ufunc_erfi_data, ufunc_erfi_types, 4, 1, 1, 0, "erfi", ufunc_erfi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_erfinv_loops[2]
+cdef void *ufunc_erfinv_ptr[4]
+cdef void *ufunc_erfinv_data[2]
+cdef char ufunc_erfinv_types[4]
+cdef char *ufunc_erfinv_doc = (
+    "erfinv(y, out=None)\n"
+    "\n"
+    "Inverse of the error function.\n"
+    "\n"
+    "Computes the inverse of the error function.\n"
+    "\n"
+    "In the complex domain, there is no unique complex number w satisfying\n"
+    "erf(w)=z. This indicates a true inverse function would be multivalued.\n"
+    "When the domain restricts to the real, -1 < x < 1, there is a unique real\n"
+    "number satisfying erf(erfinv(x)) = x.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : ndarray\n"
+    "    Argument at which to evaluate. Domain: [-1, 1]\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "erfinv : scalar or ndarray\n"
+    "    The inverse of erf of y, element-wise\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf : Error function of a complex argument\n"
+    "erfc : Complementary error function, ``1 - erf(x)``\n"
+    "erfcinv : Inverse of the complementary error function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function wraps the ``erf_inv`` routine from the\n"
+    "Boost Math C++ library [1]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import erfinv, erf\n"
+    "\n"
+    ">>> erfinv(0.5)\n"
+    "0.4769362762044699\n"
+    "\n"
+    ">>> y = np.linspace(-1.0, 1.0, num=9)\n"
+    ">>> x = erfinv(y)\n"
+    ">>> x\n"
+    "array([       -inf, -0.81341985, -0.47693628, -0.22531206,  0.        ,\n"
+    "        0.22531206,  0.47693628,  0.81341985,         inf])\n"
+    "\n"
+    "Verify that ``erf(erfinv(y))`` is ``y``.\n"
+    "\n"
+    ">>> erf(x)\n"
+    "array([-1.  , -0.75, -0.5 , -0.25,  0.  ,  0.25,  0.5 ,  0.75,  1.  ])\n"
+    "\n"
+    "Plot the function:\n"
+    "\n"
+    ">>> y = np.linspace(-1, 1, 200)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(y, erfinv(y))\n"
+    ">>> ax.grid(True)\n"
+    ">>> ax.set_xlabel('y')\n"
+    ">>> ax.set_title('erfinv(y)')\n"
+    ">>> plt.show()")
+ufunc_erfinv_loops[0] = loop_f_f__As_f_f
+ufunc_erfinv_loops[1] = loop_d_d__As_d_d
+ufunc_erfinv_types[0] = NPY_FLOAT
+ufunc_erfinv_types[1] = NPY_FLOAT
+ufunc_erfinv_types[2] = NPY_DOUBLE
+ufunc_erfinv_types[3] = NPY_DOUBLE
+ufunc_erfinv_ptr[2*0] = scipy.special._ufuncs_cxx._export_erfinv_float
+ufunc_erfinv_ptr[2*0+1] = ("erfinv")
+ufunc_erfinv_ptr[2*1] = scipy.special._ufuncs_cxx._export_erfinv_double
+ufunc_erfinv_ptr[2*1+1] = ("erfinv")
+ufunc_erfinv_data[0] = &ufunc_erfinv_ptr[2*0]
+ufunc_erfinv_data[1] = &ufunc_erfinv_ptr[2*1]
+erfinv = np.PyUFunc_FromFuncAndData(ufunc_erfinv_loops, ufunc_erfinv_data, ufunc_erfinv_types, 2, 1, 1, 0, "erfinv", ufunc_erfinv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebyc_loops[5]
+cdef void *ufunc_eval_chebyc_ptr[10]
+cdef void *ufunc_eval_chebyc_data[5]
+cdef char ufunc_eval_chebyc_types[15]
+cdef char *ufunc_eval_chebyc_doc = (
+    "eval_chebyc(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the first kind on [-2, 2] at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    C_n(x) = 2 T_n(x/2)\n"
+    "\n"
+    "where :math:`T_n` is a Chebyshev polynomial of the first kind. See\n"
+    "22.5.11 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyt`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "C : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebyc : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the first kind on [-2, 2]\n"
+    "chebyc : Chebyshev polynomial object\n"
+    "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n"
+    "eval_chebyt : evaluate Chebycshev polynomials of the first kind\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "They are a scaled version of the Chebyshev polynomials of the\n"
+    "first kind.\n"
+    "\n"
+    ">>> x = np.linspace(-2, 2, 6)\n"
+    ">>> sc.eval_chebyc(3, x)\n"
+    "array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])\n"
+    ">>> 2 * sc.eval_chebyt(3, x / 2)\n"
+    "array([-2.   ,  1.872,  1.136, -1.136, -1.872,  2.   ])")
+ufunc_eval_chebyc_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebyc_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebyc_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebyc_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebyc_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebyc_types[0] = NPY_INTP
+ufunc_eval_chebyc_types[1] = NPY_DOUBLE
+ufunc_eval_chebyc_types[2] = NPY_DOUBLE
+ufunc_eval_chebyc_types[3] = NPY_FLOAT
+ufunc_eval_chebyc_types[4] = NPY_FLOAT
+ufunc_eval_chebyc_types[5] = NPY_FLOAT
+ufunc_eval_chebyc_types[6] = NPY_FLOAT
+ufunc_eval_chebyc_types[7] = NPY_CFLOAT
+ufunc_eval_chebyc_types[8] = NPY_CFLOAT
+ufunc_eval_chebyc_types[9] = NPY_DOUBLE
+ufunc_eval_chebyc_types[10] = NPY_DOUBLE
+ufunc_eval_chebyc_types[11] = NPY_DOUBLE
+ufunc_eval_chebyc_types[12] = NPY_DOUBLE
+ufunc_eval_chebyc_types[13] = NPY_CDOUBLE
+ufunc_eval_chebyc_types[14] = NPY_CDOUBLE
+ufunc_eval_chebyc_ptr[2*0] = _func_eval_chebyc_l
+ufunc_eval_chebyc_ptr[2*0+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*1] = _func_eval_chebyc[double]
+ufunc_eval_chebyc_ptr[2*1+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*2] = _func_eval_chebyc[double_complex]
+ufunc_eval_chebyc_ptr[2*2+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*3] = _func_eval_chebyc[double]
+ufunc_eval_chebyc_ptr[2*3+1] = ("eval_chebyc")
+ufunc_eval_chebyc_ptr[2*4] = _func_eval_chebyc[double_complex]
+ufunc_eval_chebyc_ptr[2*4+1] = ("eval_chebyc")
+ufunc_eval_chebyc_data[0] = &ufunc_eval_chebyc_ptr[2*0]
+ufunc_eval_chebyc_data[1] = &ufunc_eval_chebyc_ptr[2*1]
+ufunc_eval_chebyc_data[2] = &ufunc_eval_chebyc_ptr[2*2]
+ufunc_eval_chebyc_data[3] = &ufunc_eval_chebyc_ptr[2*3]
+ufunc_eval_chebyc_data[4] = &ufunc_eval_chebyc_ptr[2*4]
+eval_chebyc = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyc_loops, ufunc_eval_chebyc_data, ufunc_eval_chebyc_types, 5, 2, 1, 0, "eval_chebyc", ufunc_eval_chebyc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebys_loops[5]
+cdef void *ufunc_eval_chebys_ptr[10]
+cdef void *ufunc_eval_chebys_data[5]
+cdef char ufunc_eval_chebys_types[15]
+cdef char *ufunc_eval_chebys_doc = (
+    "eval_chebys(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the second kind on [-2, 2] at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    S_n(x) = U_n(x/2)\n"
+    "\n"
+    "where :math:`U_n` is a Chebyshev polynomial of the second\n"
+    "kind. See 22.5.13 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyu`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "S : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebys : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the second kind on [-2, 2]\n"
+    "chebys : Chebyshev polynomial object\n"
+    "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "They are a scaled version of the Chebyshev polynomials of the\n"
+    "second kind.\n"
+    "\n"
+    ">>> x = np.linspace(-2, 2, 6)\n"
+    ">>> sc.eval_chebys(3, x)\n"
+    "array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])\n"
+    ">>> sc.eval_chebyu(3, x / 2)\n"
+    "array([-4.   ,  0.672,  0.736, -0.736, -0.672,  4.   ])")
+ufunc_eval_chebys_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebys_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebys_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebys_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebys_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebys_types[0] = NPY_INTP
+ufunc_eval_chebys_types[1] = NPY_DOUBLE
+ufunc_eval_chebys_types[2] = NPY_DOUBLE
+ufunc_eval_chebys_types[3] = NPY_FLOAT
+ufunc_eval_chebys_types[4] = NPY_FLOAT
+ufunc_eval_chebys_types[5] = NPY_FLOAT
+ufunc_eval_chebys_types[6] = NPY_FLOAT
+ufunc_eval_chebys_types[7] = NPY_CFLOAT
+ufunc_eval_chebys_types[8] = NPY_CFLOAT
+ufunc_eval_chebys_types[9] = NPY_DOUBLE
+ufunc_eval_chebys_types[10] = NPY_DOUBLE
+ufunc_eval_chebys_types[11] = NPY_DOUBLE
+ufunc_eval_chebys_types[12] = NPY_DOUBLE
+ufunc_eval_chebys_types[13] = NPY_CDOUBLE
+ufunc_eval_chebys_types[14] = NPY_CDOUBLE
+ufunc_eval_chebys_ptr[2*0] = _func_eval_chebys_l
+ufunc_eval_chebys_ptr[2*0+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*1] = _func_eval_chebys[double]
+ufunc_eval_chebys_ptr[2*1+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*2] = _func_eval_chebys[double_complex]
+ufunc_eval_chebys_ptr[2*2+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*3] = _func_eval_chebys[double]
+ufunc_eval_chebys_ptr[2*3+1] = ("eval_chebys")
+ufunc_eval_chebys_ptr[2*4] = _func_eval_chebys[double_complex]
+ufunc_eval_chebys_ptr[2*4+1] = ("eval_chebys")
+ufunc_eval_chebys_data[0] = &ufunc_eval_chebys_ptr[2*0]
+ufunc_eval_chebys_data[1] = &ufunc_eval_chebys_ptr[2*1]
+ufunc_eval_chebys_data[2] = &ufunc_eval_chebys_ptr[2*2]
+ufunc_eval_chebys_data[3] = &ufunc_eval_chebys_ptr[2*3]
+ufunc_eval_chebys_data[4] = &ufunc_eval_chebys_ptr[2*4]
+eval_chebys = np.PyUFunc_FromFuncAndData(ufunc_eval_chebys_loops, ufunc_eval_chebys_data, ufunc_eval_chebys_types, 5, 2, 1, 0, "eval_chebys", ufunc_eval_chebys_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebyt_loops[5]
+cdef void *ufunc_eval_chebyt_ptr[10]
+cdef void *ufunc_eval_chebyt_data[5]
+cdef char ufunc_eval_chebyt_types[15]
+cdef char *ufunc_eval_chebyt_doc = (
+    "eval_chebyt(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the first kind at a point.\n"
+    "\n"
+    "The Chebyshev polynomials of the first kind can be defined via the\n"
+    "Gauss hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    T_n(x) = {}_2F_1(n, -n; 1/2; (1 - x)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.47 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "T : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebyt : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the first kind\n"
+    "chebyu : Chebychev polynomial object\n"
+    "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This routine is numerically stable for `x` in ``[-1, 1]`` at least\n"
+    "up to order ``10000``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_chebyt_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebyt_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebyt_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebyt_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebyt_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebyt_types[0] = NPY_INTP
+ufunc_eval_chebyt_types[1] = NPY_DOUBLE
+ufunc_eval_chebyt_types[2] = NPY_DOUBLE
+ufunc_eval_chebyt_types[3] = NPY_FLOAT
+ufunc_eval_chebyt_types[4] = NPY_FLOAT
+ufunc_eval_chebyt_types[5] = NPY_FLOAT
+ufunc_eval_chebyt_types[6] = NPY_FLOAT
+ufunc_eval_chebyt_types[7] = NPY_CFLOAT
+ufunc_eval_chebyt_types[8] = NPY_CFLOAT
+ufunc_eval_chebyt_types[9] = NPY_DOUBLE
+ufunc_eval_chebyt_types[10] = NPY_DOUBLE
+ufunc_eval_chebyt_types[11] = NPY_DOUBLE
+ufunc_eval_chebyt_types[12] = NPY_DOUBLE
+ufunc_eval_chebyt_types[13] = NPY_CDOUBLE
+ufunc_eval_chebyt_types[14] = NPY_CDOUBLE
+ufunc_eval_chebyt_ptr[2*0] = _func_eval_chebyt_l
+ufunc_eval_chebyt_ptr[2*0+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*1] = _func_eval_chebyt[double]
+ufunc_eval_chebyt_ptr[2*1+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*2] = _func_eval_chebyt[double_complex]
+ufunc_eval_chebyt_ptr[2*2+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*3] = _func_eval_chebyt[double]
+ufunc_eval_chebyt_ptr[2*3+1] = ("eval_chebyt")
+ufunc_eval_chebyt_ptr[2*4] = _func_eval_chebyt[double_complex]
+ufunc_eval_chebyt_ptr[2*4+1] = ("eval_chebyt")
+ufunc_eval_chebyt_data[0] = &ufunc_eval_chebyt_ptr[2*0]
+ufunc_eval_chebyt_data[1] = &ufunc_eval_chebyt_ptr[2*1]
+ufunc_eval_chebyt_data[2] = &ufunc_eval_chebyt_ptr[2*2]
+ufunc_eval_chebyt_data[3] = &ufunc_eval_chebyt_ptr[2*3]
+ufunc_eval_chebyt_data[4] = &ufunc_eval_chebyt_ptr[2*4]
+eval_chebyt = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyt_loops, ufunc_eval_chebyt_data, ufunc_eval_chebyt_types, 5, 2, 1, 0, "eval_chebyt", ufunc_eval_chebyt_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_chebyu_loops[5]
+cdef void *ufunc_eval_chebyu_ptr[10]
+cdef void *ufunc_eval_chebyu_data[5]
+cdef char ufunc_eval_chebyu_types[15]
+cdef char *ufunc_eval_chebyu_doc = (
+    "eval_chebyu(n, x, out=None)\n"
+    "\n"
+    "Evaluate Chebyshev polynomial of the second kind at a point.\n"
+    "\n"
+    "The Chebyshev polynomials of the second kind can be defined via\n"
+    "the Gauss hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    U_n(x) = (n + 1) {}_2F_1(-n, n + 2; 3/2; (1 - x)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.48 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "U : scalar or ndarray\n"
+    "    Values of the Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_chebyu : roots and quadrature weights of Chebyshev\n"
+    "               polynomials of the second kind\n"
+    "chebyu : Chebyshev polynomial object\n"
+    "eval_chebyt : evaluate Chebyshev polynomials of the first kind\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_chebyu_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_chebyu_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_chebyu_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_chebyu_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_chebyu_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_chebyu_types[0] = NPY_INTP
+ufunc_eval_chebyu_types[1] = NPY_DOUBLE
+ufunc_eval_chebyu_types[2] = NPY_DOUBLE
+ufunc_eval_chebyu_types[3] = NPY_FLOAT
+ufunc_eval_chebyu_types[4] = NPY_FLOAT
+ufunc_eval_chebyu_types[5] = NPY_FLOAT
+ufunc_eval_chebyu_types[6] = NPY_FLOAT
+ufunc_eval_chebyu_types[7] = NPY_CFLOAT
+ufunc_eval_chebyu_types[8] = NPY_CFLOAT
+ufunc_eval_chebyu_types[9] = NPY_DOUBLE
+ufunc_eval_chebyu_types[10] = NPY_DOUBLE
+ufunc_eval_chebyu_types[11] = NPY_DOUBLE
+ufunc_eval_chebyu_types[12] = NPY_DOUBLE
+ufunc_eval_chebyu_types[13] = NPY_CDOUBLE
+ufunc_eval_chebyu_types[14] = NPY_CDOUBLE
+ufunc_eval_chebyu_ptr[2*0] = _func_eval_chebyu_l
+ufunc_eval_chebyu_ptr[2*0+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*1] = _func_eval_chebyu[double]
+ufunc_eval_chebyu_ptr[2*1+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*2] = _func_eval_chebyu[double_complex]
+ufunc_eval_chebyu_ptr[2*2+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*3] = _func_eval_chebyu[double]
+ufunc_eval_chebyu_ptr[2*3+1] = ("eval_chebyu")
+ufunc_eval_chebyu_ptr[2*4] = _func_eval_chebyu[double_complex]
+ufunc_eval_chebyu_ptr[2*4+1] = ("eval_chebyu")
+ufunc_eval_chebyu_data[0] = &ufunc_eval_chebyu_ptr[2*0]
+ufunc_eval_chebyu_data[1] = &ufunc_eval_chebyu_ptr[2*1]
+ufunc_eval_chebyu_data[2] = &ufunc_eval_chebyu_ptr[2*2]
+ufunc_eval_chebyu_data[3] = &ufunc_eval_chebyu_ptr[2*3]
+ufunc_eval_chebyu_data[4] = &ufunc_eval_chebyu_ptr[2*4]
+eval_chebyu = np.PyUFunc_FromFuncAndData(ufunc_eval_chebyu_loops, ufunc_eval_chebyu_data, ufunc_eval_chebyu_types, 5, 2, 1, 0, "eval_chebyu", ufunc_eval_chebyu_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_gegenbauer_loops[5]
+cdef void *ufunc_eval_gegenbauer_ptr[10]
+cdef void *ufunc_eval_gegenbauer_data[5]
+cdef char ufunc_eval_gegenbauer_types[20]
+cdef char *ufunc_eval_gegenbauer_doc = (
+    "eval_gegenbauer(n, alpha, x, out=None)\n"
+    "\n"
+    "Evaluate Gegenbauer polynomial at a point.\n"
+    "\n"
+    "The Gegenbauer polynomials can be defined via the Gauss\n"
+    "hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    C_n^{(\\alpha)} = \\frac{(2\\alpha)_n}{\\Gamma(n + 1)}\n"
+    "      {}_2F_1(-n, 2\\alpha + n; \\alpha + 1/2; (1 - z)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.46 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "alpha : array_like\n"
+    "    Parameter\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Gegenbauer polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "C : scalar or ndarray\n"
+    "    Values of the Gegenbauer polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_gegenbauer : roots and quadrature weights of Gegenbauer\n"
+    "                   polynomials\n"
+    "gegenbauer : Gegenbauer polynomial object\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_gegenbauer_loops[0] = loop_d_pdd__As_pdd_d
+ufunc_eval_gegenbauer_loops[1] = loop_d_ddd__As_fff_f
+ufunc_eval_gegenbauer_loops[2] = loop_D_ddD__As_ffF_F
+ufunc_eval_gegenbauer_loops[3] = loop_d_ddd__As_ddd_d
+ufunc_eval_gegenbauer_loops[4] = loop_D_ddD__As_ddD_D
+ufunc_eval_gegenbauer_types[0] = NPY_INTP
+ufunc_eval_gegenbauer_types[1] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[2] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[3] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[4] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[5] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[6] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[7] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[8] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[9] = NPY_FLOAT
+ufunc_eval_gegenbauer_types[10] = NPY_CFLOAT
+ufunc_eval_gegenbauer_types[11] = NPY_CFLOAT
+ufunc_eval_gegenbauer_types[12] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[13] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[14] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[15] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[16] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[17] = NPY_DOUBLE
+ufunc_eval_gegenbauer_types[18] = NPY_CDOUBLE
+ufunc_eval_gegenbauer_types[19] = NPY_CDOUBLE
+ufunc_eval_gegenbauer_ptr[2*0] = _func_eval_gegenbauer_l
+ufunc_eval_gegenbauer_ptr[2*0+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*1] = _func_eval_gegenbauer[double]
+ufunc_eval_gegenbauer_ptr[2*1+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*2] = _func_eval_gegenbauer[double_complex]
+ufunc_eval_gegenbauer_ptr[2*2+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*3] = _func_eval_gegenbauer[double]
+ufunc_eval_gegenbauer_ptr[2*3+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_ptr[2*4] = _func_eval_gegenbauer[double_complex]
+ufunc_eval_gegenbauer_ptr[2*4+1] = ("eval_gegenbauer")
+ufunc_eval_gegenbauer_data[0] = &ufunc_eval_gegenbauer_ptr[2*0]
+ufunc_eval_gegenbauer_data[1] = &ufunc_eval_gegenbauer_ptr[2*1]
+ufunc_eval_gegenbauer_data[2] = &ufunc_eval_gegenbauer_ptr[2*2]
+ufunc_eval_gegenbauer_data[3] = &ufunc_eval_gegenbauer_ptr[2*3]
+ufunc_eval_gegenbauer_data[4] = &ufunc_eval_gegenbauer_ptr[2*4]
+eval_gegenbauer = np.PyUFunc_FromFuncAndData(ufunc_eval_gegenbauer_loops, ufunc_eval_gegenbauer_data, ufunc_eval_gegenbauer_types, 5, 3, 1, 0, "eval_gegenbauer", ufunc_eval_gegenbauer_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_genlaguerre_loops[5]
+cdef void *ufunc_eval_genlaguerre_ptr[10]
+cdef void *ufunc_eval_genlaguerre_data[5]
+cdef char ufunc_eval_genlaguerre_types[20]
+cdef char *ufunc_eval_genlaguerre_doc = (
+    "eval_genlaguerre(n, alpha, x, out=None)\n"
+    "\n"
+    "Evaluate generalized Laguerre polynomial at a point.\n"
+    "\n"
+    "The generalized Laguerre polynomials can be defined via the\n"
+    "confluent hypergeometric function :math:`{}_1F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    L_n^{(\\alpha)}(x) = \\binom{n + \\alpha}{n}\n"
+    "      {}_1F_1(-n, \\alpha + 1, x).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.54 in [AS]_ for details. The Laguerre\n"
+    "polynomials are the special case where :math:`\\alpha = 0`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the confluent hypergeometric\n"
+    "    function.\n"
+    "alpha : array_like\n"
+    "    Parameter; must have ``alpha > -1``\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the generalized Laguerre\n"
+    "    polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "L : scalar or ndarray\n"
+    "    Values of the generalized Laguerre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_genlaguerre : roots and quadrature weights of generalized\n"
+    "                    Laguerre polynomials\n"
+    "genlaguerre : generalized Laguerre polynomial object\n"
+    "hyp1f1 : confluent hypergeometric function\n"
+    "eval_laguerre : evaluate Laguerre polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_genlaguerre_loops[0] = loop_d_pdd__As_pdd_d
+ufunc_eval_genlaguerre_loops[1] = loop_d_ddd__As_fff_f
+ufunc_eval_genlaguerre_loops[2] = loop_D_ddD__As_ffF_F
+ufunc_eval_genlaguerre_loops[3] = loop_d_ddd__As_ddd_d
+ufunc_eval_genlaguerre_loops[4] = loop_D_ddD__As_ddD_D
+ufunc_eval_genlaguerre_types[0] = NPY_INTP
+ufunc_eval_genlaguerre_types[1] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[2] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[3] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[4] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[5] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[6] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[7] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[8] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[9] = NPY_FLOAT
+ufunc_eval_genlaguerre_types[10] = NPY_CFLOAT
+ufunc_eval_genlaguerre_types[11] = NPY_CFLOAT
+ufunc_eval_genlaguerre_types[12] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[13] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[14] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[15] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[16] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[17] = NPY_DOUBLE
+ufunc_eval_genlaguerre_types[18] = NPY_CDOUBLE
+ufunc_eval_genlaguerre_types[19] = NPY_CDOUBLE
+ufunc_eval_genlaguerre_ptr[2*0] = _func_eval_genlaguerre_l
+ufunc_eval_genlaguerre_ptr[2*0+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*1] = _func_eval_genlaguerre[double]
+ufunc_eval_genlaguerre_ptr[2*1+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*2] = _func_eval_genlaguerre[double_complex]
+ufunc_eval_genlaguerre_ptr[2*2+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*3] = _func_eval_genlaguerre[double]
+ufunc_eval_genlaguerre_ptr[2*3+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_ptr[2*4] = _func_eval_genlaguerre[double_complex]
+ufunc_eval_genlaguerre_ptr[2*4+1] = ("eval_genlaguerre")
+ufunc_eval_genlaguerre_data[0] = &ufunc_eval_genlaguerre_ptr[2*0]
+ufunc_eval_genlaguerre_data[1] = &ufunc_eval_genlaguerre_ptr[2*1]
+ufunc_eval_genlaguerre_data[2] = &ufunc_eval_genlaguerre_ptr[2*2]
+ufunc_eval_genlaguerre_data[3] = &ufunc_eval_genlaguerre_ptr[2*3]
+ufunc_eval_genlaguerre_data[4] = &ufunc_eval_genlaguerre_ptr[2*4]
+eval_genlaguerre = np.PyUFunc_FromFuncAndData(ufunc_eval_genlaguerre_loops, ufunc_eval_genlaguerre_data, ufunc_eval_genlaguerre_types, 5, 3, 1, 0, "eval_genlaguerre", ufunc_eval_genlaguerre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_hermite_loops[1]
+cdef void *ufunc_eval_hermite_ptr[2]
+cdef void *ufunc_eval_hermite_data[1]
+cdef char ufunc_eval_hermite_types[3]
+cdef char *ufunc_eval_hermite_doc = (
+    "eval_hermite(n, x, out=None)\n"
+    "\n"
+    "Evaluate physicist's Hermite polynomial at a point.\n"
+    "\n"
+    "Defined by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    H_n(x) = (-1)^n e^{x^2} \\frac{d^n}{dx^n} e^{-x^2};\n"
+    "\n"
+    ":math:`H_n` is a polynomial of degree :math:`n`. See 22.11.7 in\n"
+    "[AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Hermite polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "H : scalar or ndarray\n"
+    "    Values of the Hermite polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_hermite : roots and quadrature weights of physicist's\n"
+    "                Hermite polynomials\n"
+    "hermite : physicist's Hermite polynomial object\n"
+    "numpy.polynomial.hermite.Hermite : Physicist's Hermite series\n"
+    "eval_hermitenorm : evaluate Probabilist's Hermite polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_hermite_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_hermite_types[0] = NPY_INTP
+ufunc_eval_hermite_types[1] = NPY_DOUBLE
+ufunc_eval_hermite_types[2] = NPY_DOUBLE
+ufunc_eval_hermite_ptr[2*0] = _func_eval_hermite
+ufunc_eval_hermite_ptr[2*0+1] = ("eval_hermite")
+ufunc_eval_hermite_data[0] = &ufunc_eval_hermite_ptr[2*0]
+eval_hermite = np.PyUFunc_FromFuncAndData(ufunc_eval_hermite_loops, ufunc_eval_hermite_data, ufunc_eval_hermite_types, 1, 2, 1, 0, "eval_hermite", ufunc_eval_hermite_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_hermitenorm_loops[1]
+cdef void *ufunc_eval_hermitenorm_ptr[2]
+cdef void *ufunc_eval_hermitenorm_data[1]
+cdef char ufunc_eval_hermitenorm_types[3]
+cdef char *ufunc_eval_hermitenorm_doc = (
+    "eval_hermitenorm(n, x, out=None)\n"
+    "\n"
+    "Evaluate probabilist's (normalized) Hermite polynomial at a\n"
+    "point.\n"
+    "\n"
+    "Defined by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    He_n(x) = (-1)^n e^{x^2/2} \\frac{d^n}{dx^n} e^{-x^2/2};\n"
+    "\n"
+    ":math:`He_n` is a polynomial of degree :math:`n`. See 22.11.8 in\n"
+    "[AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Hermite polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "He : scalar or ndarray\n"
+    "    Values of the Hermite polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_hermitenorm : roots and quadrature weights of probabilist's\n"
+    "                    Hermite polynomials\n"
+    "hermitenorm : probabilist's Hermite polynomial object\n"
+    "numpy.polynomial.hermite_e.HermiteE : Probabilist's Hermite series\n"
+    "eval_hermite : evaluate physicist's Hermite polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_hermitenorm_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_hermitenorm_types[0] = NPY_INTP
+ufunc_eval_hermitenorm_types[1] = NPY_DOUBLE
+ufunc_eval_hermitenorm_types[2] = NPY_DOUBLE
+ufunc_eval_hermitenorm_ptr[2*0] = _func_eval_hermitenorm
+ufunc_eval_hermitenorm_ptr[2*0+1] = ("eval_hermitenorm")
+ufunc_eval_hermitenorm_data[0] = &ufunc_eval_hermitenorm_ptr[2*0]
+eval_hermitenorm = np.PyUFunc_FromFuncAndData(ufunc_eval_hermitenorm_loops, ufunc_eval_hermitenorm_data, ufunc_eval_hermitenorm_types, 1, 2, 1, 0, "eval_hermitenorm", ufunc_eval_hermitenorm_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_jacobi_loops[5]
+cdef void *ufunc_eval_jacobi_ptr[10]
+cdef void *ufunc_eval_jacobi_data[5]
+cdef char ufunc_eval_jacobi_types[25]
+cdef char *ufunc_eval_jacobi_doc = (
+    "eval_jacobi(n, alpha, beta, x, out=None)\n"
+    "\n"
+    "Evaluate Jacobi polynomial at a point.\n"
+    "\n"
+    "The Jacobi polynomials can be defined via the Gauss hypergeometric\n"
+    "function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_n^{(\\alpha, \\beta)}(x) = \\frac{(\\alpha + 1)_n}{\\Gamma(n + 1)}\n"
+    "      {}_2F_1(-n, 1 + \\alpha + \\beta + n; \\alpha + 1; (1 - z)/2)\n"
+    "\n"
+    "where :math:`(\\cdot)_n` is the Pochhammer symbol; see `poch`. When\n"
+    ":math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.42 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "alpha : array_like\n"
+    "    Parameter\n"
+    "beta : array_like\n"
+    "    Parameter\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "P : scalar or ndarray\n"
+    "    Values of the Jacobi polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_jacobi : roots and quadrature weights of Jacobi polynomials\n"
+    "jacobi : Jacobi polynomial object\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_jacobi_loops[0] = loop_d_pddd__As_pddd_d
+ufunc_eval_jacobi_loops[1] = loop_d_dddd__As_ffff_f
+ufunc_eval_jacobi_loops[2] = loop_D_dddD__As_fffF_F
+ufunc_eval_jacobi_loops[3] = loop_d_dddd__As_dddd_d
+ufunc_eval_jacobi_loops[4] = loop_D_dddD__As_dddD_D
+ufunc_eval_jacobi_types[0] = NPY_INTP
+ufunc_eval_jacobi_types[1] = NPY_DOUBLE
+ufunc_eval_jacobi_types[2] = NPY_DOUBLE
+ufunc_eval_jacobi_types[3] = NPY_DOUBLE
+ufunc_eval_jacobi_types[4] = NPY_DOUBLE
+ufunc_eval_jacobi_types[5] = NPY_FLOAT
+ufunc_eval_jacobi_types[6] = NPY_FLOAT
+ufunc_eval_jacobi_types[7] = NPY_FLOAT
+ufunc_eval_jacobi_types[8] = NPY_FLOAT
+ufunc_eval_jacobi_types[9] = NPY_FLOAT
+ufunc_eval_jacobi_types[10] = NPY_FLOAT
+ufunc_eval_jacobi_types[11] = NPY_FLOAT
+ufunc_eval_jacobi_types[12] = NPY_FLOAT
+ufunc_eval_jacobi_types[13] = NPY_CFLOAT
+ufunc_eval_jacobi_types[14] = NPY_CFLOAT
+ufunc_eval_jacobi_types[15] = NPY_DOUBLE
+ufunc_eval_jacobi_types[16] = NPY_DOUBLE
+ufunc_eval_jacobi_types[17] = NPY_DOUBLE
+ufunc_eval_jacobi_types[18] = NPY_DOUBLE
+ufunc_eval_jacobi_types[19] = NPY_DOUBLE
+ufunc_eval_jacobi_types[20] = NPY_DOUBLE
+ufunc_eval_jacobi_types[21] = NPY_DOUBLE
+ufunc_eval_jacobi_types[22] = NPY_DOUBLE
+ufunc_eval_jacobi_types[23] = NPY_CDOUBLE
+ufunc_eval_jacobi_types[24] = NPY_CDOUBLE
+ufunc_eval_jacobi_ptr[2*0] = _func_eval_jacobi_l
+ufunc_eval_jacobi_ptr[2*0+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*1] = _func_eval_jacobi[double]
+ufunc_eval_jacobi_ptr[2*1+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*2] = _func_eval_jacobi[double_complex]
+ufunc_eval_jacobi_ptr[2*2+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*3] = _func_eval_jacobi[double]
+ufunc_eval_jacobi_ptr[2*3+1] = ("eval_jacobi")
+ufunc_eval_jacobi_ptr[2*4] = _func_eval_jacobi[double_complex]
+ufunc_eval_jacobi_ptr[2*4+1] = ("eval_jacobi")
+ufunc_eval_jacobi_data[0] = &ufunc_eval_jacobi_ptr[2*0]
+ufunc_eval_jacobi_data[1] = &ufunc_eval_jacobi_ptr[2*1]
+ufunc_eval_jacobi_data[2] = &ufunc_eval_jacobi_ptr[2*2]
+ufunc_eval_jacobi_data[3] = &ufunc_eval_jacobi_ptr[2*3]
+ufunc_eval_jacobi_data[4] = &ufunc_eval_jacobi_ptr[2*4]
+eval_jacobi = np.PyUFunc_FromFuncAndData(ufunc_eval_jacobi_loops, ufunc_eval_jacobi_data, ufunc_eval_jacobi_types, 5, 4, 1, 0, "eval_jacobi", ufunc_eval_jacobi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_laguerre_loops[5]
+cdef void *ufunc_eval_laguerre_ptr[10]
+cdef void *ufunc_eval_laguerre_data[5]
+cdef char ufunc_eval_laguerre_types[15]
+cdef char *ufunc_eval_laguerre_doc = (
+    "eval_laguerre(n, x, out=None)\n"
+    "\n"
+    "Evaluate Laguerre polynomial at a point.\n"
+    "\n"
+    "The Laguerre polynomials can be defined via the confluent\n"
+    "hypergeometric function :math:`{}_1F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    L_n(x) = {}_1F_1(-n, 1, x).\n"
+    "\n"
+    "See 22.5.16 and 22.5.54 in [AS]_ for details. When :math:`n` is an\n"
+    "integer the result is a polynomial of degree :math:`n`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer the result is\n"
+    "    determined via the relation to the confluent hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Laguerre polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "L : scalar or ndarray\n"
+    "    Values of the Laguerre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_laguerre : roots and quadrature weights of Laguerre\n"
+    "                 polynomials\n"
+    "laguerre : Laguerre polynomial object\n"
+    "numpy.polynomial.laguerre.Laguerre : Laguerre series\n"
+    "eval_genlaguerre : evaluate generalized Laguerre polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_laguerre_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_laguerre_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_laguerre_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_laguerre_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_laguerre_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_laguerre_types[0] = NPY_INTP
+ufunc_eval_laguerre_types[1] = NPY_DOUBLE
+ufunc_eval_laguerre_types[2] = NPY_DOUBLE
+ufunc_eval_laguerre_types[3] = NPY_FLOAT
+ufunc_eval_laguerre_types[4] = NPY_FLOAT
+ufunc_eval_laguerre_types[5] = NPY_FLOAT
+ufunc_eval_laguerre_types[6] = NPY_FLOAT
+ufunc_eval_laguerre_types[7] = NPY_CFLOAT
+ufunc_eval_laguerre_types[8] = NPY_CFLOAT
+ufunc_eval_laguerre_types[9] = NPY_DOUBLE
+ufunc_eval_laguerre_types[10] = NPY_DOUBLE
+ufunc_eval_laguerre_types[11] = NPY_DOUBLE
+ufunc_eval_laguerre_types[12] = NPY_DOUBLE
+ufunc_eval_laguerre_types[13] = NPY_CDOUBLE
+ufunc_eval_laguerre_types[14] = NPY_CDOUBLE
+ufunc_eval_laguerre_ptr[2*0] = _func_eval_laguerre_l
+ufunc_eval_laguerre_ptr[2*0+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*1] = _func_eval_laguerre[double]
+ufunc_eval_laguerre_ptr[2*1+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*2] = _func_eval_laguerre[double_complex]
+ufunc_eval_laguerre_ptr[2*2+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*3] = _func_eval_laguerre[double]
+ufunc_eval_laguerre_ptr[2*3+1] = ("eval_laguerre")
+ufunc_eval_laguerre_ptr[2*4] = _func_eval_laguerre[double_complex]
+ufunc_eval_laguerre_ptr[2*4+1] = ("eval_laguerre")
+ufunc_eval_laguerre_data[0] = &ufunc_eval_laguerre_ptr[2*0]
+ufunc_eval_laguerre_data[1] = &ufunc_eval_laguerre_ptr[2*1]
+ufunc_eval_laguerre_data[2] = &ufunc_eval_laguerre_ptr[2*2]
+ufunc_eval_laguerre_data[3] = &ufunc_eval_laguerre_ptr[2*3]
+ufunc_eval_laguerre_data[4] = &ufunc_eval_laguerre_ptr[2*4]
+eval_laguerre = np.PyUFunc_FromFuncAndData(ufunc_eval_laguerre_loops, ufunc_eval_laguerre_data, ufunc_eval_laguerre_types, 5, 2, 1, 0, "eval_laguerre", ufunc_eval_laguerre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_legendre_loops[5]
+cdef void *ufunc_eval_legendre_ptr[10]
+cdef void *ufunc_eval_legendre_data[5]
+cdef char ufunc_eval_legendre_types[15]
+cdef char *ufunc_eval_legendre_doc = (
+    "eval_legendre(n, x, out=None)\n"
+    "\n"
+    "Evaluate Legendre polynomial at a point.\n"
+    "\n"
+    "The Legendre polynomials can be defined via the Gauss\n"
+    "hypergeometric function :math:`{}_2F_1` as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_n(x) = {}_2F_1(-n, n + 1; 1; (1 - x)/2).\n"
+    "\n"
+    "When :math:`n` is an integer the result is a polynomial of degree\n"
+    ":math:`n`. See 22.5.49 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to the Gauss hypergeometric\n"
+    "    function.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the Legendre polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "P : scalar or ndarray\n"
+    "    Values of the Legendre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_legendre : roots and quadrature weights of Legendre\n"
+    "                 polynomials\n"
+    "legendre : Legendre polynomial object\n"
+    "hyp2f1 : Gauss hypergeometric function\n"
+    "numpy.polynomial.legendre.Legendre : Legendre series\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import eval_legendre\n"
+    "\n"
+    "Evaluate the zero-order Legendre polynomial at x = 0\n"
+    "\n"
+    ">>> eval_legendre(0, 0)\n"
+    "1.0\n"
+    "\n"
+    "Evaluate the first-order Legendre polynomial between -1 and 1\n"
+    "\n"
+    ">>> X = np.linspace(-1, 1, 5)  # Domain of Legendre polynomials\n"
+    ">>> eval_legendre(1, X)\n"
+    "array([-1. , -0.5,  0. ,  0.5,  1. ])\n"
+    "\n"
+    "Evaluate Legendre polynomials of order 0 through 4 at x = 0\n"
+    "\n"
+    ">>> N = range(0, 5)\n"
+    ">>> eval_legendre(N, 0)\n"
+    "array([ 1.   ,  0.   , -0.5  ,  0.   ,  0.375])\n"
+    "\n"
+    "Plot Legendre polynomials of order 0 through 4\n"
+    "\n"
+    ">>> X = np.linspace(-1, 1)\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> for n in range(0, 5):\n"
+    "...     y = eval_legendre(n, X)\n"
+    "...     plt.plot(X, y, label=r'$P_{}(x)$'.format(n))\n"
+    "\n"
+    ">>> plt.title(\"Legendre Polynomials\")\n"
+    ">>> plt.xlabel(\"x\")\n"
+    ">>> plt.ylabel(r'$P_n(x)$')\n"
+    ">>> plt.legend(loc='lower right')\n"
+    ">>> plt.show()")
+ufunc_eval_legendre_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_legendre_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_legendre_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_legendre_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_legendre_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_legendre_types[0] = NPY_INTP
+ufunc_eval_legendre_types[1] = NPY_DOUBLE
+ufunc_eval_legendre_types[2] = NPY_DOUBLE
+ufunc_eval_legendre_types[3] = NPY_FLOAT
+ufunc_eval_legendre_types[4] = NPY_FLOAT
+ufunc_eval_legendre_types[5] = NPY_FLOAT
+ufunc_eval_legendre_types[6] = NPY_FLOAT
+ufunc_eval_legendre_types[7] = NPY_CFLOAT
+ufunc_eval_legendre_types[8] = NPY_CFLOAT
+ufunc_eval_legendre_types[9] = NPY_DOUBLE
+ufunc_eval_legendre_types[10] = NPY_DOUBLE
+ufunc_eval_legendre_types[11] = NPY_DOUBLE
+ufunc_eval_legendre_types[12] = NPY_DOUBLE
+ufunc_eval_legendre_types[13] = NPY_CDOUBLE
+ufunc_eval_legendre_types[14] = NPY_CDOUBLE
+ufunc_eval_legendre_ptr[2*0] = _func_eval_legendre_l
+ufunc_eval_legendre_ptr[2*0+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*1] = _func_eval_legendre[double]
+ufunc_eval_legendre_ptr[2*1+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*2] = _func_eval_legendre[double_complex]
+ufunc_eval_legendre_ptr[2*2+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*3] = _func_eval_legendre[double]
+ufunc_eval_legendre_ptr[2*3+1] = ("eval_legendre")
+ufunc_eval_legendre_ptr[2*4] = _func_eval_legendre[double_complex]
+ufunc_eval_legendre_ptr[2*4+1] = ("eval_legendre")
+ufunc_eval_legendre_data[0] = &ufunc_eval_legendre_ptr[2*0]
+ufunc_eval_legendre_data[1] = &ufunc_eval_legendre_ptr[2*1]
+ufunc_eval_legendre_data[2] = &ufunc_eval_legendre_ptr[2*2]
+ufunc_eval_legendre_data[3] = &ufunc_eval_legendre_ptr[2*3]
+ufunc_eval_legendre_data[4] = &ufunc_eval_legendre_ptr[2*4]
+eval_legendre = np.PyUFunc_FromFuncAndData(ufunc_eval_legendre_loops, ufunc_eval_legendre_data, ufunc_eval_legendre_types, 5, 2, 1, 0, "eval_legendre", ufunc_eval_legendre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_chebyt_loops[5]
+cdef void *ufunc_eval_sh_chebyt_ptr[10]
+cdef void *ufunc_eval_sh_chebyt_data[5]
+cdef char ufunc_eval_sh_chebyt_types[15]
+cdef char *ufunc_eval_sh_chebyt_doc = (
+    "eval_sh_chebyt(n, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Chebyshev polynomial of the first kind at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    T_n^*(x) = T_n(2x - 1)\n"
+    "\n"
+    "where :math:`T_n` is a Chebyshev polynomial of the first kind. See\n"
+    "22.5.14 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyt`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the shifted Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "T : scalar or ndarray\n"
+    "    Values of the shifted Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_chebyt : roots and quadrature weights of shifted\n"
+    "                  Chebyshev polynomials of the first kind\n"
+    "sh_chebyt : shifted Chebyshev polynomial object\n"
+    "eval_chebyt : evaluate Chebyshev polynomials of the first kind\n"
+    "numpy.polynomial.chebyshev.Chebyshev : Chebyshev series\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_chebyt_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_sh_chebyt_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_sh_chebyt_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_sh_chebyt_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_sh_chebyt_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_sh_chebyt_types[0] = NPY_INTP
+ufunc_eval_sh_chebyt_types[1] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[2] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[3] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[4] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[5] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[6] = NPY_FLOAT
+ufunc_eval_sh_chebyt_types[7] = NPY_CFLOAT
+ufunc_eval_sh_chebyt_types[8] = NPY_CFLOAT
+ufunc_eval_sh_chebyt_types[9] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[10] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[11] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[12] = NPY_DOUBLE
+ufunc_eval_sh_chebyt_types[13] = NPY_CDOUBLE
+ufunc_eval_sh_chebyt_types[14] = NPY_CDOUBLE
+ufunc_eval_sh_chebyt_ptr[2*0] = _func_eval_sh_chebyt_l
+ufunc_eval_sh_chebyt_ptr[2*0+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*1] = _func_eval_sh_chebyt[double]
+ufunc_eval_sh_chebyt_ptr[2*1+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*2] = _func_eval_sh_chebyt[double_complex]
+ufunc_eval_sh_chebyt_ptr[2*2+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*3] = _func_eval_sh_chebyt[double]
+ufunc_eval_sh_chebyt_ptr[2*3+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_ptr[2*4] = _func_eval_sh_chebyt[double_complex]
+ufunc_eval_sh_chebyt_ptr[2*4+1] = ("eval_sh_chebyt")
+ufunc_eval_sh_chebyt_data[0] = &ufunc_eval_sh_chebyt_ptr[2*0]
+ufunc_eval_sh_chebyt_data[1] = &ufunc_eval_sh_chebyt_ptr[2*1]
+ufunc_eval_sh_chebyt_data[2] = &ufunc_eval_sh_chebyt_ptr[2*2]
+ufunc_eval_sh_chebyt_data[3] = &ufunc_eval_sh_chebyt_ptr[2*3]
+ufunc_eval_sh_chebyt_data[4] = &ufunc_eval_sh_chebyt_ptr[2*4]
+eval_sh_chebyt = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_chebyt_loops, ufunc_eval_sh_chebyt_data, ufunc_eval_sh_chebyt_types, 5, 2, 1, 0, "eval_sh_chebyt", ufunc_eval_sh_chebyt_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_chebyu_loops[5]
+cdef void *ufunc_eval_sh_chebyu_ptr[10]
+cdef void *ufunc_eval_sh_chebyu_data[5]
+cdef char ufunc_eval_sh_chebyu_types[15]
+cdef char *ufunc_eval_sh_chebyu_doc = (
+    "eval_sh_chebyu(n, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Chebyshev polynomial of the second kind at a\n"
+    "point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    U_n^*(x) = U_n(2x - 1)\n"
+    "\n"
+    "where :math:`U_n` is a Chebyshev polynomial of the first kind. See\n"
+    "22.5.15 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `eval_chebyu`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the shifted Chebyshev polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "U : scalar or ndarray\n"
+    "    Values of the shifted Chebyshev polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_chebyu : roots and quadrature weights of shifted\n"
+    "                  Chebychev polynomials of the second kind\n"
+    "sh_chebyu : shifted Chebyshev polynomial object\n"
+    "eval_chebyu : evaluate Chebyshev polynomials of the second kind\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_chebyu_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_sh_chebyu_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_sh_chebyu_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_sh_chebyu_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_sh_chebyu_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_sh_chebyu_types[0] = NPY_INTP
+ufunc_eval_sh_chebyu_types[1] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[2] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[3] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[4] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[5] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[6] = NPY_FLOAT
+ufunc_eval_sh_chebyu_types[7] = NPY_CFLOAT
+ufunc_eval_sh_chebyu_types[8] = NPY_CFLOAT
+ufunc_eval_sh_chebyu_types[9] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[10] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[11] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[12] = NPY_DOUBLE
+ufunc_eval_sh_chebyu_types[13] = NPY_CDOUBLE
+ufunc_eval_sh_chebyu_types[14] = NPY_CDOUBLE
+ufunc_eval_sh_chebyu_ptr[2*0] = _func_eval_sh_chebyu_l
+ufunc_eval_sh_chebyu_ptr[2*0+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*1] = _func_eval_sh_chebyu[double]
+ufunc_eval_sh_chebyu_ptr[2*1+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*2] = _func_eval_sh_chebyu[double_complex]
+ufunc_eval_sh_chebyu_ptr[2*2+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*3] = _func_eval_sh_chebyu[double]
+ufunc_eval_sh_chebyu_ptr[2*3+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_ptr[2*4] = _func_eval_sh_chebyu[double_complex]
+ufunc_eval_sh_chebyu_ptr[2*4+1] = ("eval_sh_chebyu")
+ufunc_eval_sh_chebyu_data[0] = &ufunc_eval_sh_chebyu_ptr[2*0]
+ufunc_eval_sh_chebyu_data[1] = &ufunc_eval_sh_chebyu_ptr[2*1]
+ufunc_eval_sh_chebyu_data[2] = &ufunc_eval_sh_chebyu_ptr[2*2]
+ufunc_eval_sh_chebyu_data[3] = &ufunc_eval_sh_chebyu_ptr[2*3]
+ufunc_eval_sh_chebyu_data[4] = &ufunc_eval_sh_chebyu_ptr[2*4]
+eval_sh_chebyu = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_chebyu_loops, ufunc_eval_sh_chebyu_data, ufunc_eval_sh_chebyu_types, 5, 2, 1, 0, "eval_sh_chebyu", ufunc_eval_sh_chebyu_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_jacobi_loops[5]
+cdef void *ufunc_eval_sh_jacobi_ptr[10]
+cdef void *ufunc_eval_sh_jacobi_data[5]
+cdef char ufunc_eval_sh_jacobi_types[25]
+cdef char *ufunc_eval_sh_jacobi_doc = (
+    "eval_sh_jacobi(n, p, q, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Jacobi polynomial at a point.\n"
+    "\n"
+    "Defined by\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    G_n^{(p, q)}(x)\n"
+    "      = \\binom{2n + p - 1}{n}^{-1} P_n^{(p - q, q - 1)}(2x - 1),\n"
+    "\n"
+    "where :math:`P_n^{(\\cdot, \\cdot)}` is the n-th Jacobi\n"
+    "polynomial. See 22.5.2 in [AS]_ for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : int\n"
+    "    Degree of the polynomial. If not an integer, the result is\n"
+    "    determined via the relation to `binom` and `eval_jacobi`.\n"
+    "p : float\n"
+    "    Parameter\n"
+    "q : float\n"
+    "    Parameter\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "G : scalar or ndarray\n"
+    "    Values of the shifted Jacobi polynomial.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_jacobi : roots and quadrature weights of shifted Jacobi\n"
+    "                  polynomials\n"
+    "sh_jacobi : shifted Jacobi polynomial object\n"
+    "eval_jacobi : evaluate Jacobi polynomials\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_jacobi_loops[0] = loop_d_pddd__As_pddd_d
+ufunc_eval_sh_jacobi_loops[1] = loop_d_dddd__As_ffff_f
+ufunc_eval_sh_jacobi_loops[2] = loop_D_dddD__As_fffF_F
+ufunc_eval_sh_jacobi_loops[3] = loop_d_dddd__As_dddd_d
+ufunc_eval_sh_jacobi_loops[4] = loop_D_dddD__As_dddD_D
+ufunc_eval_sh_jacobi_types[0] = NPY_INTP
+ufunc_eval_sh_jacobi_types[1] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[2] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[3] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[4] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[5] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[6] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[7] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[8] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[9] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[10] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[11] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[12] = NPY_FLOAT
+ufunc_eval_sh_jacobi_types[13] = NPY_CFLOAT
+ufunc_eval_sh_jacobi_types[14] = NPY_CFLOAT
+ufunc_eval_sh_jacobi_types[15] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[16] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[17] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[18] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[19] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[20] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[21] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[22] = NPY_DOUBLE
+ufunc_eval_sh_jacobi_types[23] = NPY_CDOUBLE
+ufunc_eval_sh_jacobi_types[24] = NPY_CDOUBLE
+ufunc_eval_sh_jacobi_ptr[2*0] = _func_eval_sh_jacobi_l
+ufunc_eval_sh_jacobi_ptr[2*0+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*1] = _func_eval_sh_jacobi[double]
+ufunc_eval_sh_jacobi_ptr[2*1+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*2] = _func_eval_sh_jacobi[double_complex]
+ufunc_eval_sh_jacobi_ptr[2*2+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*3] = _func_eval_sh_jacobi[double]
+ufunc_eval_sh_jacobi_ptr[2*3+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_ptr[2*4] = _func_eval_sh_jacobi[double_complex]
+ufunc_eval_sh_jacobi_ptr[2*4+1] = ("eval_sh_jacobi")
+ufunc_eval_sh_jacobi_data[0] = &ufunc_eval_sh_jacobi_ptr[2*0]
+ufunc_eval_sh_jacobi_data[1] = &ufunc_eval_sh_jacobi_ptr[2*1]
+ufunc_eval_sh_jacobi_data[2] = &ufunc_eval_sh_jacobi_ptr[2*2]
+ufunc_eval_sh_jacobi_data[3] = &ufunc_eval_sh_jacobi_ptr[2*3]
+ufunc_eval_sh_jacobi_data[4] = &ufunc_eval_sh_jacobi_ptr[2*4]
+eval_sh_jacobi = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_jacobi_loops, ufunc_eval_sh_jacobi_data, ufunc_eval_sh_jacobi_types, 5, 4, 1, 0, "eval_sh_jacobi", ufunc_eval_sh_jacobi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_eval_sh_legendre_loops[5]
+cdef void *ufunc_eval_sh_legendre_ptr[10]
+cdef void *ufunc_eval_sh_legendre_data[5]
+cdef char ufunc_eval_sh_legendre_types[15]
+cdef char *ufunc_eval_sh_legendre_doc = (
+    "eval_sh_legendre(n, x, out=None)\n"
+    "\n"
+    "Evaluate shifted Legendre polynomial at a point.\n"
+    "\n"
+    "These polynomials are defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_n^*(x) = P_n(2x - 1)\n"
+    "\n"
+    "where :math:`P_n` is a Legendre polynomial. See 2.2.11 in [AS]_\n"
+    "for details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Degree of the polynomial. If not an integer, the value is\n"
+    "    determined via the relation to `eval_legendre`.\n"
+    "x : array_like\n"
+    "    Points at which to evaluate the shifted Legendre polynomial\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "P : scalar or ndarray\n"
+    "    Values of the shifted Legendre polynomial\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "roots_sh_legendre : roots and quadrature weights of shifted\n"
+    "                    Legendre polynomials\n"
+    "sh_legendre : shifted Legendre polynomial object\n"
+    "eval_legendre : evaluate Legendre polynomials\n"
+    "numpy.polynomial.legendre.Legendre : Legendre series\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [AS] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "    Handbook of Mathematical Functions with Formulas,\n"
+    "    Graphs, and Mathematical Tables. New York: Dover, 1972.")
+ufunc_eval_sh_legendre_loops[0] = loop_d_pd__As_pd_d
+ufunc_eval_sh_legendre_loops[1] = loop_d_dd__As_ff_f
+ufunc_eval_sh_legendre_loops[2] = loop_D_dD__As_fF_F
+ufunc_eval_sh_legendre_loops[3] = loop_d_dd__As_dd_d
+ufunc_eval_sh_legendre_loops[4] = loop_D_dD__As_dD_D
+ufunc_eval_sh_legendre_types[0] = NPY_INTP
+ufunc_eval_sh_legendre_types[1] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[2] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[3] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[4] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[5] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[6] = NPY_FLOAT
+ufunc_eval_sh_legendre_types[7] = NPY_CFLOAT
+ufunc_eval_sh_legendre_types[8] = NPY_CFLOAT
+ufunc_eval_sh_legendre_types[9] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[10] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[11] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[12] = NPY_DOUBLE
+ufunc_eval_sh_legendre_types[13] = NPY_CDOUBLE
+ufunc_eval_sh_legendre_types[14] = NPY_CDOUBLE
+ufunc_eval_sh_legendre_ptr[2*0] = _func_eval_sh_legendre_l
+ufunc_eval_sh_legendre_ptr[2*0+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*1] = _func_eval_sh_legendre[double]
+ufunc_eval_sh_legendre_ptr[2*1+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*2] = _func_eval_sh_legendre[double_complex]
+ufunc_eval_sh_legendre_ptr[2*2+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*3] = _func_eval_sh_legendre[double]
+ufunc_eval_sh_legendre_ptr[2*3+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_ptr[2*4] = _func_eval_sh_legendre[double_complex]
+ufunc_eval_sh_legendre_ptr[2*4+1] = ("eval_sh_legendre")
+ufunc_eval_sh_legendre_data[0] = &ufunc_eval_sh_legendre_ptr[2*0]
+ufunc_eval_sh_legendre_data[1] = &ufunc_eval_sh_legendre_ptr[2*1]
+ufunc_eval_sh_legendre_data[2] = &ufunc_eval_sh_legendre_ptr[2*2]
+ufunc_eval_sh_legendre_data[3] = &ufunc_eval_sh_legendre_ptr[2*3]
+ufunc_eval_sh_legendre_data[4] = &ufunc_eval_sh_legendre_ptr[2*4]
+eval_sh_legendre = np.PyUFunc_FromFuncAndData(ufunc_eval_sh_legendre_loops, ufunc_eval_sh_legendre_data, ufunc_eval_sh_legendre_types, 5, 2, 1, 0, "eval_sh_legendre", ufunc_eval_sh_legendre_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_exp10_loops[2]
+cdef void *ufunc_exp10_ptr[4]
+cdef void *ufunc_exp10_data[2]
+cdef char ufunc_exp10_types[4]
+cdef char *ufunc_exp10_doc = (
+    "exp10(x, out=None)\n"
+    "\n"
+    "Compute ``10**x`` element-wise.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    ``10**x``, computed element-wise.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import exp10\n"
+    "\n"
+    ">>> exp10(3)\n"
+    "1000.0\n"
+    ">>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])\n"
+    ">>> exp10(x)\n"
+    "array([[  0.1       ,   0.31622777,   1.        ],\n"
+    "       [  3.16227766,  10.        ,  31.6227766 ]])")
+ufunc_exp10_loops[0] = loop_d_d__As_f_f
+ufunc_exp10_loops[1] = loop_d_d__As_d_d
+ufunc_exp10_types[0] = NPY_FLOAT
+ufunc_exp10_types[1] = NPY_FLOAT
+ufunc_exp10_types[2] = NPY_DOUBLE
+ufunc_exp10_types[3] = NPY_DOUBLE
+ufunc_exp10_ptr[2*0] = _func_cephes_exp10
+ufunc_exp10_ptr[2*0+1] = ("exp10")
+ufunc_exp10_ptr[2*1] = _func_cephes_exp10
+ufunc_exp10_ptr[2*1+1] = ("exp10")
+ufunc_exp10_data[0] = &ufunc_exp10_ptr[2*0]
+ufunc_exp10_data[1] = &ufunc_exp10_ptr[2*1]
+exp10 = np.PyUFunc_FromFuncAndData(ufunc_exp10_loops, ufunc_exp10_data, ufunc_exp10_types, 2, 1, 1, 0, "exp10", ufunc_exp10_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_exp2_loops[2]
+cdef void *ufunc_exp2_ptr[4]
+cdef void *ufunc_exp2_data[2]
+cdef char ufunc_exp2_types[4]
+cdef char *ufunc_exp2_doc = (
+    "exp2(x, out=None)\n"
+    "\n"
+    "Compute ``2**x`` element-wise.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    ``2**x``, computed element-wise.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import exp2\n"
+    "\n"
+    ">>> exp2(3)\n"
+    "8.0\n"
+    ">>> x = np.array([[-1, -0.5, 0], [0.5, 1, 1.5]])\n"
+    ">>> exp2(x)\n"
+    "array([[ 0.5       ,  0.70710678,  1.        ],\n"
+    "       [ 1.41421356,  2.        ,  2.82842712]])")
+ufunc_exp2_loops[0] = loop_d_d__As_f_f
+ufunc_exp2_loops[1] = loop_d_d__As_d_d
+ufunc_exp2_types[0] = NPY_FLOAT
+ufunc_exp2_types[1] = NPY_FLOAT
+ufunc_exp2_types[2] = NPY_DOUBLE
+ufunc_exp2_types[3] = NPY_DOUBLE
+ufunc_exp2_ptr[2*0] = _func_cephes_exp2
+ufunc_exp2_ptr[2*0+1] = ("exp2")
+ufunc_exp2_ptr[2*1] = _func_cephes_exp2
+ufunc_exp2_ptr[2*1+1] = ("exp2")
+ufunc_exp2_data[0] = &ufunc_exp2_ptr[2*0]
+ufunc_exp2_data[1] = &ufunc_exp2_ptr[2*1]
+exp2 = np.PyUFunc_FromFuncAndData(ufunc_exp2_loops, ufunc_exp2_data, ufunc_exp2_types, 2, 1, 1, 0, "exp2", ufunc_exp2_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_expm1_loops[4]
+cdef void *ufunc_expm1_ptr[8]
+cdef void *ufunc_expm1_data[4]
+cdef char ufunc_expm1_types[8]
+cdef char *ufunc_expm1_doc = (
+    "expm1(x, out=None)\n"
+    "\n"
+    "Compute ``exp(x) - 1``.\n"
+    "\n"
+    "When `x` is near zero, ``exp(x)`` is near 1, so the numerical calculation\n"
+    "of ``exp(x) - 1`` can suffer from catastrophic loss of precision.\n"
+    "``expm1(x)`` is implemented to avoid the loss of precision that occurs when\n"
+    "`x` is near zero.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    `x` must contain real numbers.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    ``exp(x) - 1`` computed element-wise.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import expm1\n"
+    "\n"
+    ">>> expm1(1.0)\n"
+    "1.7182818284590451\n"
+    ">>> expm1([-0.2, -0.1, 0, 0.1, 0.2])\n"
+    "array([-0.18126925, -0.09516258,  0.        ,  0.10517092,  0.22140276])\n"
+    "\n"
+    "The exact value of ``exp(7.5e-13) - 1`` is::\n"
+    "\n"
+    "    7.5000000000028125000000007031250000001318...*10**-13.\n"
+    "\n"
+    "Here is what ``expm1(7.5e-13)`` gives:\n"
+    "\n"
+    ">>> expm1(7.5e-13)\n"
+    "7.5000000000028135e-13\n"
+    "\n"
+    "Compare that to ``exp(7.5e-13) - 1``, where the subtraction results in\n"
+    "a \"catastrophic\" loss of precision:\n"
+    "\n"
+    ">>> np.exp(7.5e-13) - 1\n"
+    "7.5006667543675576e-13")
+ufunc_expm1_loops[0] = loop_d_d__As_f_f
+ufunc_expm1_loops[1] = loop_d_d__As_d_d
+ufunc_expm1_loops[2] = loop_D_D__As_F_F
+ufunc_expm1_loops[3] = loop_D_D__As_D_D
+ufunc_expm1_types[0] = NPY_FLOAT
+ufunc_expm1_types[1] = NPY_FLOAT
+ufunc_expm1_types[2] = NPY_DOUBLE
+ufunc_expm1_types[3] = NPY_DOUBLE
+ufunc_expm1_types[4] = NPY_CFLOAT
+ufunc_expm1_types[5] = NPY_CFLOAT
+ufunc_expm1_types[6] = NPY_CDOUBLE
+ufunc_expm1_types[7] = NPY_CDOUBLE
+ufunc_expm1_ptr[2*0] = _func_cephes_expm1
+ufunc_expm1_ptr[2*0+1] = ("expm1")
+ufunc_expm1_ptr[2*1] = _func_cephes_expm1
+ufunc_expm1_ptr[2*1+1] = ("expm1")
+ufunc_expm1_ptr[2*2] = _func_cexpm1
+ufunc_expm1_ptr[2*2+1] = ("expm1")
+ufunc_expm1_ptr[2*3] = _func_cexpm1
+ufunc_expm1_ptr[2*3+1] = ("expm1")
+ufunc_expm1_data[0] = &ufunc_expm1_ptr[2*0]
+ufunc_expm1_data[1] = &ufunc_expm1_ptr[2*1]
+ufunc_expm1_data[2] = &ufunc_expm1_ptr[2*2]
+ufunc_expm1_data[3] = &ufunc_expm1_ptr[2*3]
+expm1 = np.PyUFunc_FromFuncAndData(ufunc_expm1_loops, ufunc_expm1_data, ufunc_expm1_types, 4, 1, 1, 0, "expm1", ufunc_expm1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_expn_loops[3]
+cdef void *ufunc_expn_ptr[6]
+cdef void *ufunc_expn_data[3]
+cdef char ufunc_expn_types[9]
+cdef char *ufunc_expn_doc = (
+    "expn(n, x, out=None)\n"
+    "\n"
+    "Generalized exponential integral En.\n"
+    "\n"
+    "For integer :math:`n \\geq 0` and real :math:`x \\geq 0` the\n"
+    "generalized exponential integral is defined as [dlmf]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    E_n(x) = x^{n - 1} \\int_x^\\infty \\frac{e^{-t}}{t^n} dt.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Non-negative integers\n"
+    "x : array_like\n"
+    "    Real argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the generalized exponential integral\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "exp1 : special case of :math:`E_n` for :math:`n = 1`\n"
+    "expi : related to :math:`E_n` when :math:`n = 1`\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] Digital Library of Mathematical Functions, 8.19.2\n"
+    "          https://dlmf.nist.gov/8.19#E2\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "Its domain is nonnegative n and x.\n"
+    "\n"
+    ">>> sc.expn(-1, 1.0), sc.expn(1, -1.0)\n"
+    "(nan, nan)\n"
+    "\n"
+    "It has a pole at ``x = 0`` for ``n = 1, 2``; for larger ``n`` it\n"
+    "is equal to ``1 / (n - 1)``.\n"
+    "\n"
+    ">>> sc.expn([0, 1, 2, 3, 4], 0)\n"
+    "array([       inf,        inf, 1.        , 0.5       , 0.33333333])\n"
+    "\n"
+    "For n equal to 0 it reduces to ``exp(-x) / x``.\n"
+    "\n"
+    ">>> x = np.array([1, 2, 3, 4])\n"
+    ">>> sc.expn(0, x)\n"
+    "array([0.36787944, 0.06766764, 0.01659569, 0.00457891])\n"
+    ">>> np.exp(-x) / x\n"
+    "array([0.36787944, 0.06766764, 0.01659569, 0.00457891])\n"
+    "\n"
+    "For n equal to 1 it reduces to `exp1`.\n"
+    "\n"
+    ">>> sc.expn(1, x)\n"
+    "array([0.21938393, 0.04890051, 0.01304838, 0.00377935])\n"
+    ">>> sc.exp1(x)\n"
+    "array([0.21938393, 0.04890051, 0.01304838, 0.00377935])")
+ufunc_expn_loops[0] = loop_d_pd__As_pd_d
+ufunc_expn_loops[1] = loop_d_dd__As_ff_f
+ufunc_expn_loops[2] = loop_d_dd__As_dd_d
+ufunc_expn_types[0] = NPY_INTP
+ufunc_expn_types[1] = NPY_DOUBLE
+ufunc_expn_types[2] = NPY_DOUBLE
+ufunc_expn_types[3] = NPY_FLOAT
+ufunc_expn_types[4] = NPY_FLOAT
+ufunc_expn_types[5] = NPY_FLOAT
+ufunc_expn_types[6] = NPY_DOUBLE
+ufunc_expn_types[7] = NPY_DOUBLE
+ufunc_expn_types[8] = NPY_DOUBLE
+ufunc_expn_ptr[2*0] = _func_cephes_expn_wrap
+ufunc_expn_ptr[2*0+1] = ("expn")
+ufunc_expn_ptr[2*1] = _func_expn_unsafe
+ufunc_expn_ptr[2*1+1] = ("expn")
+ufunc_expn_ptr[2*2] = _func_expn_unsafe
+ufunc_expn_ptr[2*2+1] = ("expn")
+ufunc_expn_data[0] = &ufunc_expn_ptr[2*0]
+ufunc_expn_data[1] = &ufunc_expn_ptr[2*1]
+ufunc_expn_data[2] = &ufunc_expn_ptr[2*2]
+expn = np.PyUFunc_FromFuncAndData(ufunc_expn_loops, ufunc_expn_data, ufunc_expn_types, 3, 2, 1, 0, "expn", ufunc_expn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtr_loops[2]
+cdef void *ufunc_fdtr_ptr[4]
+cdef void *ufunc_fdtr_data[2]
+cdef char ufunc_fdtr_types[8]
+cdef char *ufunc_fdtr_doc = (
+    "fdtr(dfn, dfd, x, out=None)\n"
+    "\n"
+    "F cumulative distribution function.\n"
+    "\n"
+    "Returns the value of the cumulative distribution function of the\n"
+    "F-distribution, also known as Snedecor's F-distribution or the\n"
+    "Fisher-Snedecor distribution.\n"
+    "\n"
+    "The F-distribution with parameters :math:`d_n` and :math:`d_d` is the\n"
+    "distribution of the random variable,\n"
+    "\n"
+    ".. math::\n"
+    "    X = \\frac{U_n/d_n}{U_d/d_d},\n"
+    "\n"
+    "where :math:`U_n` and :math:`U_d` are random variables distributed\n"
+    ":math:`\\chi^2`, with :math:`d_n` and :math:`d_d` degrees of freedom,\n"
+    "respectively.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "dfd : array_like\n"
+    "    Second parameter (positive float).\n"
+    "x : array_like\n"
+    "    Argument (nonnegative float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    The CDF of the F-distribution with parameters `dfn` and `dfd` at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtrc : F distribution survival function\n"
+    "fdtri : F distribution inverse cumulative distribution\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The regularized incomplete beta function is used, according to the\n"
+    "formula,\n"
+    "\n"
+    ".. math::\n"
+    "    F(d_n, d_d; x) = I_{xd_n/(d_d + xd_n)}(d_n/2, d_d/2).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `fdtr`. The F distribution is also\n"
+    "available as `scipy.stats.f`. Calling `fdtr` directly can improve\n"
+    "performance compared to the ``cdf`` method of `scipy.stats.f` (see last\n"
+    "example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import fdtr\n"
+    ">>> fdtr(1, 2, 1)\n"
+    "0.5773502691896258\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array for\n"
+    "`x`.\n"
+    "\n"
+    ">>> x = np.array([0.5, 2., 3.])\n"
+    ">>> fdtr(1, 2, x)\n"
+    "array([0.4472136 , 0.70710678, 0.77459667])\n"
+    "\n"
+    "Plot the function for several parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> dfn_parameters = [1, 5, 10, 50]\n"
+    ">>> dfd_parameters = [1, 1, 2, 3]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     dfn, dfd, style = parameter_set\n"
+    "...     fdtr_vals = fdtr(dfn, dfd, x)\n"
+    "...     ax.plot(x, fdtr_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"F distribution cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Using `fdtr`\n"
+    "directly can be much faster than calling the ``cdf`` method of\n"
+    "`scipy.stats.f`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.f(dfn, dfd).cdf(x)=fdtr(dfn, dfd, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import f\n"
+    ">>> dfn, dfd = 1, 2\n"
+    ">>> x = 1\n"
+    ">>> fdtr_res = fdtr(dfn, dfd, x)  # this will often be faster than below\n"
+    ">>> f_dist_res = f(dfn, dfd).cdf(x)\n"
+    ">>> fdtr_res == f_dist_res  # test that results are equal\n"
+    "True")
+ufunc_fdtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtr_types[0] = NPY_FLOAT
+ufunc_fdtr_types[1] = NPY_FLOAT
+ufunc_fdtr_types[2] = NPY_FLOAT
+ufunc_fdtr_types[3] = NPY_FLOAT
+ufunc_fdtr_types[4] = NPY_DOUBLE
+ufunc_fdtr_types[5] = NPY_DOUBLE
+ufunc_fdtr_types[6] = NPY_DOUBLE
+ufunc_fdtr_types[7] = NPY_DOUBLE
+ufunc_fdtr_ptr[2*0] = _func_xsf_fdtr
+ufunc_fdtr_ptr[2*0+1] = ("fdtr")
+ufunc_fdtr_ptr[2*1] = _func_xsf_fdtr
+ufunc_fdtr_ptr[2*1+1] = ("fdtr")
+ufunc_fdtr_data[0] = &ufunc_fdtr_ptr[2*0]
+ufunc_fdtr_data[1] = &ufunc_fdtr_ptr[2*1]
+fdtr = np.PyUFunc_FromFuncAndData(ufunc_fdtr_loops, ufunc_fdtr_data, ufunc_fdtr_types, 2, 3, 1, 0, "fdtr", ufunc_fdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtrc_loops[2]
+cdef void *ufunc_fdtrc_ptr[4]
+cdef void *ufunc_fdtrc_data[2]
+cdef char ufunc_fdtrc_types[8]
+cdef char *ufunc_fdtrc_doc = (
+    "fdtrc(dfn, dfd, x, out=None)\n"
+    "\n"
+    "F survival function.\n"
+    "\n"
+    "Returns the complemented F-distribution function (the integral of the\n"
+    "density from `x` to infinity).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "dfd : array_like\n"
+    "    Second parameter (positive float).\n"
+    "x : array_like\n"
+    "    Argument (nonnegative float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "y : scalar or ndarray\n"
+    "    The complemented F-distribution function with parameters `dfn` and\n"
+    "    `dfd` at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtr : F distribution cumulative distribution function\n"
+    "fdtri : F distribution inverse cumulative distribution function\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The regularized incomplete beta function is used, according to the\n"
+    "formula,\n"
+    "\n"
+    ".. math::\n"
+    "    F(d_n, d_d; x) = I_{d_d/(d_d + xd_n)}(d_d/2, d_n/2).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `fdtrc`. The F distribution is also\n"
+    "available as `scipy.stats.f`. Calling `fdtrc` directly can improve\n"
+    "performance compared to the ``sf`` method of `scipy.stats.f` (see last\n"
+    "example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function for ``dfn=1`` and ``dfd=2`` at ``x=1``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import fdtrc\n"
+    ">>> fdtrc(1, 2, 1)\n"
+    "0.42264973081037427\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array for\n"
+    "`x`.\n"
+    "\n"
+    ">>> x = np.array([0.5, 2., 3.])\n"
+    ">>> fdtrc(1, 2, x)\n"
+    "array([0.5527864 , 0.29289322, 0.22540333])\n"
+    "\n"
+    "Plot the function for several parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> dfn_parameters = [1, 5, 10, 50]\n"
+    ">>> dfd_parameters = [1, 1, 2, 3]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     dfn, dfd, style = parameter_set\n"
+    "...     fdtrc_vals = fdtrc(dfn, dfd, x)\n"
+    "...     ax.plot(x, fdtrc_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"F distribution survival function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Using `fdtrc`\n"
+    "directly can be much faster than calling the ``sf`` method of\n"
+    "`scipy.stats.f`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.f(dfn, dfd).sf(x)=fdtrc(dfn, dfd, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import f\n"
+    ">>> dfn, dfd = 1, 2\n"
+    ">>> x = 1\n"
+    ">>> fdtrc_res = fdtrc(dfn, dfd, x)  # this will often be faster than below\n"
+    ">>> f_dist_res = f(dfn, dfd).sf(x)\n"
+    ">>> f_dist_res == fdtrc_res  # test that results are equal\n"
+    "True")
+ufunc_fdtrc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtrc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtrc_types[0] = NPY_FLOAT
+ufunc_fdtrc_types[1] = NPY_FLOAT
+ufunc_fdtrc_types[2] = NPY_FLOAT
+ufunc_fdtrc_types[3] = NPY_FLOAT
+ufunc_fdtrc_types[4] = NPY_DOUBLE
+ufunc_fdtrc_types[5] = NPY_DOUBLE
+ufunc_fdtrc_types[6] = NPY_DOUBLE
+ufunc_fdtrc_types[7] = NPY_DOUBLE
+ufunc_fdtrc_ptr[2*0] = _func_xsf_fdtrc
+ufunc_fdtrc_ptr[2*0+1] = ("fdtrc")
+ufunc_fdtrc_ptr[2*1] = _func_xsf_fdtrc
+ufunc_fdtrc_ptr[2*1+1] = ("fdtrc")
+ufunc_fdtrc_data[0] = &ufunc_fdtrc_ptr[2*0]
+ufunc_fdtrc_data[1] = &ufunc_fdtrc_ptr[2*1]
+fdtrc = np.PyUFunc_FromFuncAndData(ufunc_fdtrc_loops, ufunc_fdtrc_data, ufunc_fdtrc_types, 2, 3, 1, 0, "fdtrc", ufunc_fdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtri_loops[2]
+cdef void *ufunc_fdtri_ptr[4]
+cdef void *ufunc_fdtri_data[2]
+cdef char ufunc_fdtri_types[8]
+cdef char *ufunc_fdtri_doc = (
+    "fdtri(dfn, dfd, p, out=None)\n"
+    "\n"
+    "The `p`-th quantile of the F-distribution.\n"
+    "\n"
+    "This function is the inverse of the F-distribution CDF, `fdtr`, returning\n"
+    "the `x` such that `fdtr(dfn, dfd, x) = p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "dfd : array_like\n"
+    "    Second parameter (positive float).\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    The quantile corresponding to `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtr : F distribution cumulative distribution function\n"
+    "fdtrc : F distribution survival function\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The computation is carried out using the relation to the inverse\n"
+    "regularized beta function, :math:`I^{-1}_x(a, b)`.  Let\n"
+    ":math:`z = I^{-1}_p(d_d/2, d_n/2).`  Then,\n"
+    "\n"
+    ".. math::\n"
+    "    x = \\frac{d_d (1 - z)}{d_n z}.\n"
+    "\n"
+    "If `p` is such that :math:`x < 0.5`, the following relation is used\n"
+    "instead for improved stability: let\n"
+    ":math:`z' = I^{-1}_{1 - p}(d_n/2, d_d/2).` Then,\n"
+    "\n"
+    ".. math::\n"
+    "    x = \\frac{d_d z'}{d_n (1 - z')}.\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `fdtri`.\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Calling\n"
+    "`fdtri` directly can improve performance compared to the ``ppf``\n"
+    "method of `scipy.stats.f` (see last example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`fdtri` represents the inverse of the F distribution CDF which is\n"
+    "available as `fdtr`. Here, we calculate the CDF for ``df1=1``, ``df2=2``\n"
+    "at ``x=3``. `fdtri` then returns ``3`` given the same values for `df1`,\n"
+    "`df2` and the computed CDF value.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import fdtri, fdtr\n"
+    ">>> df1, df2 = 1, 2\n"
+    ">>> x = 3\n"
+    ">>> cdf_value =  fdtr(df1, df2, x)\n"
+    ">>> fdtri(df1, df2, cdf_value)\n"
+    "3.000000000000006\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array for\n"
+    "`x`.\n"
+    "\n"
+    ">>> x = np.array([0.1, 0.4, 0.7])\n"
+    ">>> fdtri(1, 2, x)\n"
+    "array([0.02020202, 0.38095238, 1.92156863])\n"
+    "\n"
+    "Plot the function for several parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> dfn_parameters = [50, 10, 1, 50]\n"
+    ">>> dfd_parameters = [0.5, 1, 1, 5]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(dfn_parameters, dfd_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> x = np.linspace(0, 1, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     dfn, dfd, style = parameter_set\n"
+    "...     fdtri_vals = fdtri(dfn, dfd, x)\n"
+    "...     ax.plot(x, fdtri_vals, label=rf\"$d_n={dfn},\\, d_d={dfd}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> title = \"F distribution inverse cumulative distribution function\"\n"
+    ">>> ax.set_title(title)\n"
+    ">>> ax.set_ylim(0, 30)\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The F distribution is also available as `scipy.stats.f`. Using `fdtri`\n"
+    "directly can be much faster than calling the ``ppf`` method of\n"
+    "`scipy.stats.f`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.f(dfn, dfd).ppf(x)=fdtri(dfn, dfd, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import f\n"
+    ">>> dfn, dfd = 1, 2\n"
+    ">>> x = 0.7\n"
+    ">>> fdtri_res = fdtri(dfn, dfd, x)  # this will often be faster than below\n"
+    ">>> f_dist_res = f(dfn, dfd).ppf(x)\n"
+    ">>> f_dist_res == fdtri_res  # test that results are equal\n"
+    "True")
+ufunc_fdtri_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtri_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtri_types[0] = NPY_FLOAT
+ufunc_fdtri_types[1] = NPY_FLOAT
+ufunc_fdtri_types[2] = NPY_FLOAT
+ufunc_fdtri_types[3] = NPY_FLOAT
+ufunc_fdtri_types[4] = NPY_DOUBLE
+ufunc_fdtri_types[5] = NPY_DOUBLE
+ufunc_fdtri_types[6] = NPY_DOUBLE
+ufunc_fdtri_types[7] = NPY_DOUBLE
+ufunc_fdtri_ptr[2*0] = _func_xsf_fdtri
+ufunc_fdtri_ptr[2*0+1] = ("fdtri")
+ufunc_fdtri_ptr[2*1] = _func_xsf_fdtri
+ufunc_fdtri_ptr[2*1+1] = ("fdtri")
+ufunc_fdtri_data[0] = &ufunc_fdtri_ptr[2*0]
+ufunc_fdtri_data[1] = &ufunc_fdtri_ptr[2*1]
+fdtri = np.PyUFunc_FromFuncAndData(ufunc_fdtri_loops, ufunc_fdtri_data, ufunc_fdtri_types, 2, 3, 1, 0, "fdtri", ufunc_fdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_fdtridfd_loops[2]
+cdef void *ufunc_fdtridfd_ptr[4]
+cdef void *ufunc_fdtridfd_data[2]
+cdef char ufunc_fdtridfd_types[8]
+cdef char *ufunc_fdtridfd_doc = (
+    "fdtridfd(dfn, p, x, out=None)\n"
+    "\n"
+    "Inverse to `fdtr` vs dfd\n"
+    "\n"
+    "Finds the F density argument dfd such that ``fdtr(dfn, dfd, x) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    First parameter (positive float).\n"
+    "p : array_like\n"
+    "    Cumulative probability, in [0, 1].\n"
+    "x : array_like\n"
+    "    Argument (nonnegative float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "dfd : scalar or ndarray\n"
+    "    `dfd` such that ``fdtr(dfn, dfd, x) == p``.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "fdtr : F distribution cumulative distribution function\n"
+    "fdtrc : F distribution survival function\n"
+    "fdtri : F distribution quantile function\n"
+    "scipy.stats.f : F distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the F distribution cumulative distribution function for one\n"
+    "parameter set.\n"
+    "\n"
+    ">>> from scipy.special import fdtridfd, fdtr\n"
+    ">>> dfn, dfd, x = 10, 5, 2\n"
+    ">>> cdf_value = fdtr(dfn, dfd, x)\n"
+    ">>> cdf_value\n"
+    "0.7700248806501017\n"
+    "\n"
+    "Verify that `fdtridfd` recovers the original value for `dfd`:\n"
+    "\n"
+    ">>> fdtridfd(dfn, cdf_value, x)\n"
+    "5.0")
+ufunc_fdtridfd_loops[0] = loop_d_ddd__As_fff_f
+ufunc_fdtridfd_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_fdtridfd_types[0] = NPY_FLOAT
+ufunc_fdtridfd_types[1] = NPY_FLOAT
+ufunc_fdtridfd_types[2] = NPY_FLOAT
+ufunc_fdtridfd_types[3] = NPY_FLOAT
+ufunc_fdtridfd_types[4] = NPY_DOUBLE
+ufunc_fdtridfd_types[5] = NPY_DOUBLE
+ufunc_fdtridfd_types[6] = NPY_DOUBLE
+ufunc_fdtridfd_types[7] = NPY_DOUBLE
+ufunc_fdtridfd_ptr[2*0] = _func_fdtridfd
+ufunc_fdtridfd_ptr[2*0+1] = ("fdtridfd")
+ufunc_fdtridfd_ptr[2*1] = _func_fdtridfd
+ufunc_fdtridfd_ptr[2*1+1] = ("fdtridfd")
+ufunc_fdtridfd_data[0] = &ufunc_fdtridfd_ptr[2*0]
+ufunc_fdtridfd_data[1] = &ufunc_fdtridfd_ptr[2*1]
+fdtridfd = np.PyUFunc_FromFuncAndData(ufunc_fdtridfd_loops, ufunc_fdtridfd_data, ufunc_fdtridfd_types, 2, 3, 1, 0, "fdtridfd", ufunc_fdtridfd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtr_loops[2]
+cdef void *ufunc_gdtr_ptr[4]
+cdef void *ufunc_gdtr_data[2]
+cdef char ufunc_gdtr_types[8]
+cdef char *ufunc_gdtr_doc = (
+    "gdtr(a, b, x, out=None)\n"
+    "\n"
+    "Gamma distribution cumulative distribution function.\n"
+    "\n"
+    "Returns the integral from zero to `x` of the gamma probability density\n"
+    "function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\int_0^x \\frac{a^b}{\\Gamma(b)} t^{b-1} e^{-at}\\,dt,\n"
+    "\n"
+    "where :math:`\\Gamma` is the gamma function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    The rate parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\beta` (float).  It is also the reciprocal of the scale\n"
+    "    parameter :math:`\\theta`.\n"
+    "b : array_like\n"
+    "    The shape parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\alpha` (float).\n"
+    "x : array_like\n"
+    "    The quantile (upper limit of integration; float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The CDF of the gamma distribution with parameters `a` and `b`\n"
+    "    evaluated at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtrc : 1 - CDF of the gamma distribution.\n"
+    "scipy.stats.gamma: Gamma distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The evaluation is carried out using the relation to the incomplete gamma\n"
+    "integral (regularized gamma function).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `gdtr`. Calling `gdtr` directly can\n"
+    "improve performance compared to the ``cdf`` method of `scipy.stats.gamma`\n"
+    "(see last example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``a=1``, ``b=2`` at ``x=5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import gdtr\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> gdtr(1., 2., 5.)\n"
+    "0.9595723180054873\n"
+    "\n"
+    "Compute the function for ``a=1`` and ``b=2`` at several points by\n"
+    "providing a NumPy array for `x`.\n"
+    "\n"
+    ">>> xvalues = np.array([1., 2., 3., 4])\n"
+    ">>> gdtr(1., 1., xvalues)\n"
+    "array([0.63212056, 0.86466472, 0.95021293, 0.98168436])\n"
+    "\n"
+    "`gdtr` can evaluate different parameter sets by providing arrays with\n"
+    "broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the\n"
+    "function for three different `a` at four positions `x` and ``b=3``,\n"
+    "resulting in a 3x4 array.\n"
+    "\n"
+    ">>> a = np.array([[0.5], [1.5], [2.5]])\n"
+    ">>> x = np.array([1., 2., 3., 4])\n"
+    ">>> a.shape, x.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> gdtr(a, 3., x)\n"
+    "array([[0.01438768, 0.0803014 , 0.19115317, 0.32332358],\n"
+    "       [0.19115317, 0.57680992, 0.82642193, 0.9380312 ],\n"
+    "       [0.45618688, 0.87534798, 0.97974328, 0.9972306 ]])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> a_parameters = [0.3, 1, 2, 6]\n"
+    ">>> b_parameters = [2, 10, 15, 20]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     a, b, style = parameter_set\n"
+    "...     gdtr_vals = gdtr(a, b, x)\n"
+    "...     ax.plot(x, gdtr_vals, label=fr\"$a= {a},\\, b={b}$\", ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"Gamma distribution cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The gamma distribution is also available as `scipy.stats.gamma`. Using\n"
+    "`gdtr` directly can be much faster than calling the ``cdf`` method of\n"
+    "`scipy.stats.gamma`, especially for small arrays or individual values.\n"
+    "To get the same results one must use the following parametrization:\n"
+    "``stats.gamma(b, scale=1/a).cdf(x)=gdtr(a, b, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import gamma\n"
+    ">>> a = 2.\n"
+    ">>> b = 3\n"
+    ">>> x = 1.\n"
+    ">>> gdtr_result = gdtr(a, b, x)  # this will often be faster than below\n"
+    ">>> gamma_dist_result = gamma(b, scale=1/a).cdf(x)\n"
+    ">>> gdtr_result == gamma_dist_result  # test that results are equal\n"
+    "True")
+ufunc_gdtr_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtr_types[0] = NPY_FLOAT
+ufunc_gdtr_types[1] = NPY_FLOAT
+ufunc_gdtr_types[2] = NPY_FLOAT
+ufunc_gdtr_types[3] = NPY_FLOAT
+ufunc_gdtr_types[4] = NPY_DOUBLE
+ufunc_gdtr_types[5] = NPY_DOUBLE
+ufunc_gdtr_types[6] = NPY_DOUBLE
+ufunc_gdtr_types[7] = NPY_DOUBLE
+ufunc_gdtr_ptr[2*0] = _func_xsf_gdtr
+ufunc_gdtr_ptr[2*0+1] = ("gdtr")
+ufunc_gdtr_ptr[2*1] = _func_xsf_gdtr
+ufunc_gdtr_ptr[2*1+1] = ("gdtr")
+ufunc_gdtr_data[0] = &ufunc_gdtr_ptr[2*0]
+ufunc_gdtr_data[1] = &ufunc_gdtr_ptr[2*1]
+gdtr = np.PyUFunc_FromFuncAndData(ufunc_gdtr_loops, ufunc_gdtr_data, ufunc_gdtr_types, 2, 3, 1, 0, "gdtr", ufunc_gdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtrc_loops[2]
+cdef void *ufunc_gdtrc_ptr[4]
+cdef void *ufunc_gdtrc_data[2]
+cdef char ufunc_gdtrc_types[8]
+cdef char *ufunc_gdtrc_doc = (
+    "gdtrc(a, b, x, out=None)\n"
+    "\n"
+    "Gamma distribution survival function.\n"
+    "\n"
+    "Integral from `x` to infinity of the gamma probability density function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\int_x^\\infty \\frac{a^b}{\\Gamma(b)} t^{b-1} e^{-at}\\,dt,\n"
+    "\n"
+    "where :math:`\\Gamma` is the gamma function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    The rate parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\beta` (float). It is also the reciprocal of the scale\n"
+    "    parameter :math:`\\theta`.\n"
+    "b : array_like\n"
+    "    The shape parameter of the gamma distribution, sometimes denoted\n"
+    "    :math:`\\alpha` (float).\n"
+    "x : array_like\n"
+    "    The quantile (lower limit of integration; float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The survival function of the gamma distribution with parameters `a`\n"
+    "    and `b` evaluated at `x`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr: Gamma distribution cumulative distribution function\n"
+    "scipy.stats.gamma: Gamma distribution\n"
+    "gdtrix\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The evaluation is carried out using the relation to the incomplete gamma\n"
+    "integral (regularized gamma function).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `gdtrc`. Calling `gdtrc` directly can\n"
+    "improve performance compared to the ``sf`` method of `scipy.stats.gamma`\n"
+    "(see last example below).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``a=1`` and ``b=2`` at ``x=5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import gdtrc\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> gdtrc(1., 2., 5.)\n"
+    "0.04042768199451279\n"
+    "\n"
+    "Compute the function for ``a=1``, ``b=2`` at several points by providing\n"
+    "a NumPy array for `x`.\n"
+    "\n"
+    ">>> xvalues = np.array([1., 2., 3., 4])\n"
+    ">>> gdtrc(1., 1., xvalues)\n"
+    "array([0.36787944, 0.13533528, 0.04978707, 0.01831564])\n"
+    "\n"
+    "`gdtrc` can evaluate different parameter sets by providing arrays with\n"
+    "broadcasting compatible shapes for `a`, `b` and `x`. Here we compute the\n"
+    "function for three different `a` at four positions `x` and ``b=3``,\n"
+    "resulting in a 3x4 array.\n"
+    "\n"
+    ">>> a = np.array([[0.5], [1.5], [2.5]])\n"
+    ">>> x = np.array([1., 2., 3., 4])\n"
+    ">>> a.shape, x.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> gdtrc(a, 3., x)\n"
+    "array([[0.98561232, 0.9196986 , 0.80884683, 0.67667642],\n"
+    "       [0.80884683, 0.42319008, 0.17357807, 0.0619688 ],\n"
+    "       [0.54381312, 0.12465202, 0.02025672, 0.0027694 ]])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> a_parameters = [0.3, 1, 2, 6]\n"
+    ">>> b_parameters = [2, 10, 15, 20]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(a_parameters, b_parameters, linestyles))\n"
+    ">>> x = np.linspace(0, 30, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     a, b, style = parameter_set\n"
+    "...     gdtrc_vals = gdtrc(a, b, x)\n"
+    "...     ax.plot(x, gdtrc_vals, label=fr\"$a= {a},\\, b={b}$\", ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(\"Gamma distribution survival function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The gamma distribution is also available as `scipy.stats.gamma`.\n"
+    "Using `gdtrc` directly can be much faster than calling the ``sf`` method\n"
+    "of `scipy.stats.gamma`, especially for small arrays or individual\n"
+    "values. To get the same results one must use the following parametrization:\n"
+    "``stats.gamma(b, scale=1/a).sf(x)=gdtrc(a, b, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import gamma\n"
+    ">>> a = 2\n"
+    ">>> b = 3\n"
+    ">>> x = 1.\n"
+    ">>> gdtrc_result = gdtrc(a, b, x)  # this will often be faster than below\n"
+    ">>> gamma_dist_result = gamma(b, scale=1/a).sf(x)\n"
+    ">>> gdtrc_result == gamma_dist_result  # test that results are equal\n"
+    "True")
+ufunc_gdtrc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtrc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtrc_types[0] = NPY_FLOAT
+ufunc_gdtrc_types[1] = NPY_FLOAT
+ufunc_gdtrc_types[2] = NPY_FLOAT
+ufunc_gdtrc_types[3] = NPY_FLOAT
+ufunc_gdtrc_types[4] = NPY_DOUBLE
+ufunc_gdtrc_types[5] = NPY_DOUBLE
+ufunc_gdtrc_types[6] = NPY_DOUBLE
+ufunc_gdtrc_types[7] = NPY_DOUBLE
+ufunc_gdtrc_ptr[2*0] = _func_xsf_gdtrc
+ufunc_gdtrc_ptr[2*0+1] = ("gdtrc")
+ufunc_gdtrc_ptr[2*1] = _func_xsf_gdtrc
+ufunc_gdtrc_ptr[2*1+1] = ("gdtrc")
+ufunc_gdtrc_data[0] = &ufunc_gdtrc_ptr[2*0]
+ufunc_gdtrc_data[1] = &ufunc_gdtrc_ptr[2*1]
+gdtrc = np.PyUFunc_FromFuncAndData(ufunc_gdtrc_loops, ufunc_gdtrc_data, ufunc_gdtrc_types, 2, 3, 1, 0, "gdtrc", ufunc_gdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtria_loops[2]
+cdef void *ufunc_gdtria_ptr[4]
+cdef void *ufunc_gdtria_data[2]
+cdef char ufunc_gdtria_types[8]
+cdef char *ufunc_gdtria_doc = (
+    "gdtria(p, b, x, out=None)\n"
+    "\n"
+    "Inverse of `gdtr` vs a.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `a` of ``p =\n"
+    "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n"
+    "distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability values.\n"
+    "b : array_like\n"
+    "    `b` parameter values of `gdtr(a, b, x)`. `b` is the \"shape\" parameter\n"
+    "    of the gamma distribution.\n"
+    "x : array_like\n"
+    "    Nonnegative real values, from the domain of the gamma distribution.\n"
+    "out : ndarray, optional\n"
+    "    If a fourth argument is given, it must be a numpy.ndarray whose size\n"
+    "    matches the broadcast result of `a`, `b` and `x`.  `out` is then the\n"
+    "    array returned by the function.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "a : scalar or ndarray\n"
+    "    Values of the `a` parameter such that ``p = gdtr(a, b, x)`.  ``1/a``\n"
+    "    is the \"scale\" parameter of the gamma distribution.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr : CDF of the gamma distribution.\n"
+    "gdtrib : Inverse with respect to `b` of `gdtr(a, b, x)`.\n"
+    "gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `a` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `a`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Computation of the incomplete gamma function ratios and their\n"
+    "       inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "First evaluate `gdtr`.\n"
+    "\n"
+    ">>> from scipy.special import gdtr, gdtria\n"
+    ">>> p = gdtr(1.2, 3.4, 5.6)\n"
+    ">>> print(p)\n"
+    "0.94378087442\n"
+    "\n"
+    "Verify the inverse.\n"
+    "\n"
+    ">>> gdtria(p, 3.4, 5.6)\n"
+    "1.2")
+ufunc_gdtria_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtria_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtria_types[0] = NPY_FLOAT
+ufunc_gdtria_types[1] = NPY_FLOAT
+ufunc_gdtria_types[2] = NPY_FLOAT
+ufunc_gdtria_types[3] = NPY_FLOAT
+ufunc_gdtria_types[4] = NPY_DOUBLE
+ufunc_gdtria_types[5] = NPY_DOUBLE
+ufunc_gdtria_types[6] = NPY_DOUBLE
+ufunc_gdtria_types[7] = NPY_DOUBLE
+ufunc_gdtria_ptr[2*0] = _func_gdtria
+ufunc_gdtria_ptr[2*0+1] = ("gdtria")
+ufunc_gdtria_ptr[2*1] = _func_gdtria
+ufunc_gdtria_ptr[2*1+1] = ("gdtria")
+ufunc_gdtria_data[0] = &ufunc_gdtria_ptr[2*0]
+ufunc_gdtria_data[1] = &ufunc_gdtria_ptr[2*1]
+gdtria = np.PyUFunc_FromFuncAndData(ufunc_gdtria_loops, ufunc_gdtria_data, ufunc_gdtria_types, 2, 3, 1, 0, "gdtria", ufunc_gdtria_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtrib_loops[2]
+cdef void *ufunc_gdtrib_ptr[4]
+cdef void *ufunc_gdtrib_data[2]
+cdef char ufunc_gdtrib_types[8]
+cdef char *ufunc_gdtrib_doc = (
+    "gdtrib(a, p, x, out=None)\n"
+    "\n"
+    "Inverse of `gdtr` vs b.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `b` of ``p =\n"
+    "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n"
+    "distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    `a` parameter values of ``gdtr(a, b, x)`. ``1/a`` is the \"scale\"\n"
+    "    parameter of the gamma distribution.\n"
+    "p : array_like\n"
+    "    Probability values.\n"
+    "x : array_like\n"
+    "    Nonnegative real values, from the domain of the gamma distribution.\n"
+    "out : ndarray, optional\n"
+    "    If a fourth argument is given, it must be a numpy.ndarray whose size\n"
+    "    matches the broadcast result of `a`, `b` and `x`.  `out` is then the\n"
+    "    array returned by the function.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "b : scalar or ndarray\n"
+    "    Values of the `b` parameter such that `p = gdtr(a, b, x)`.  `b` is\n"
+    "    the \"shape\" parameter of the gamma distribution.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr : CDF of the gamma distribution.\n"
+    "gdtria : Inverse with respect to `a` of `gdtr(a, b, x)`.\n"
+    "gdtrix : Inverse with respect to `x` of `gdtr(a, b, x)`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using the Cephes [1]_\n"
+    "routines `igam` and `igamc`. Computation of `b` involves a search for a value\n"
+    "that produces the desired value of `p` using Chandrupatla's bracketing\n"
+    "root finding algorithm [2]_.\n"
+    "\n"
+    "Note that there are some edge cases where `gdtrib` is extended by taking\n"
+    "limits where they are uniquely defined. In particular\n"
+    "``x == 0`` with ``p > 0`` and ``p == 0`` with ``x > 0``.\n"
+    "For these edge cases, a numerical result will be returned for\n"
+    "``gdtrib(a, p, x)`` even though ``gdtr(a, gdtrib(a, p, x), x)`` is\n"
+    "undefined.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    ".. [2] Chandrupatla, Tirupathi R.\n"
+    "       \"A new hybrid quadratic/bisection algorithm for finding the zero of a\n"
+    "       nonlinear function without using derivatives\".\n"
+    "       Advances in Engineering Software, 28(3), 145-149.\n"
+    "       https://doi.org/10.1016/s0965-9978(96)00051-8\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "First evaluate `gdtr`.\n"
+    "\n"
+    ">>> from scipy.special import gdtr, gdtrib\n"
+    ">>> p = gdtr(1.2, 3.4, 5.6)\n"
+    ">>> print(p)\n"
+    "0.94378087442\n"
+    "\n"
+    "Verify the inverse.\n"
+    "\n"
+    ">>> gdtrib(1.2, p, 5.6)\n"
+    "3.3999999999999995")
+ufunc_gdtrib_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtrib_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtrib_types[0] = NPY_FLOAT
+ufunc_gdtrib_types[1] = NPY_FLOAT
+ufunc_gdtrib_types[2] = NPY_FLOAT
+ufunc_gdtrib_types[3] = NPY_FLOAT
+ufunc_gdtrib_types[4] = NPY_DOUBLE
+ufunc_gdtrib_types[5] = NPY_DOUBLE
+ufunc_gdtrib_types[6] = NPY_DOUBLE
+ufunc_gdtrib_types[7] = NPY_DOUBLE
+ufunc_gdtrib_ptr[2*0] = _func_xsf_gdtrib
+ufunc_gdtrib_ptr[2*0+1] = ("gdtrib")
+ufunc_gdtrib_ptr[2*1] = _func_xsf_gdtrib
+ufunc_gdtrib_ptr[2*1+1] = ("gdtrib")
+ufunc_gdtrib_data[0] = &ufunc_gdtrib_ptr[2*0]
+ufunc_gdtrib_data[1] = &ufunc_gdtrib_ptr[2*1]
+gdtrib = np.PyUFunc_FromFuncAndData(ufunc_gdtrib_loops, ufunc_gdtrib_data, ufunc_gdtrib_types, 2, 3, 1, 0, "gdtrib", ufunc_gdtrib_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_gdtrix_loops[2]
+cdef void *ufunc_gdtrix_ptr[4]
+cdef void *ufunc_gdtrix_data[2]
+cdef char ufunc_gdtrix_types[8]
+cdef char *ufunc_gdtrix_doc = (
+    "gdtrix(a, b, p, out=None)\n"
+    "\n"
+    "Inverse of `gdtr` vs x.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `x` of ``p =\n"
+    "gdtr(a, b, x)``, the cumulative distribution function of the gamma\n"
+    "distribution. This is also known as the pth quantile of the\n"
+    "distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a : array_like\n"
+    "    `a` parameter values of ``gdtr(a, b, x)``. ``1/a`` is the \"scale\"\n"
+    "    parameter of the gamma distribution.\n"
+    "b : array_like\n"
+    "    `b` parameter values of ``gdtr(a, b, x)``. `b` is the \"shape\" parameter\n"
+    "    of the gamma distribution.\n"
+    "p : array_like\n"
+    "    Probability values.\n"
+    "out : ndarray, optional\n"
+    "    If a fourth argument is given, it must be a numpy.ndarray whose size\n"
+    "    matches the broadcast result of `a`, `b` and `x`. `out` is then the\n"
+    "    array returned by the function.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Values of the `x` parameter such that `p = gdtr(a, b, x)`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "gdtr : CDF of the gamma distribution.\n"
+    "gdtria : Inverse with respect to `a` of ``gdtr(a, b, x)``.\n"
+    "gdtrib : Inverse with respect to `b` of ``gdtr(a, b, x)``.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfgam`.\n"
+    "\n"
+    "The cumulative distribution function `p` is computed using a routine by\n"
+    "DiDinato and Morris [2]_. Computation of `x` involves a search for a value\n"
+    "that produces the desired value of `p`. The search relies on the\n"
+    "monotonicity of `p` with `x`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] DiDinato, A. R. and Morris, A. H.,\n"
+    "       Computation of the incomplete gamma function ratios and their\n"
+    "       inverse.  ACM Trans. Math. Softw. 12 (1986), 377-393.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "First evaluate `gdtr`.\n"
+    "\n"
+    ">>> from scipy.special import gdtr, gdtrix\n"
+    ">>> p = gdtr(1.2, 3.4, 5.6)\n"
+    ">>> print(p)\n"
+    "0.94378087442\n"
+    "\n"
+    "Verify the inverse.\n"
+    "\n"
+    ">>> gdtrix(1.2, 3.4, p)\n"
+    "5.5999999999999996")
+ufunc_gdtrix_loops[0] = loop_d_ddd__As_fff_f
+ufunc_gdtrix_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_gdtrix_types[0] = NPY_FLOAT
+ufunc_gdtrix_types[1] = NPY_FLOAT
+ufunc_gdtrix_types[2] = NPY_FLOAT
+ufunc_gdtrix_types[3] = NPY_FLOAT
+ufunc_gdtrix_types[4] = NPY_DOUBLE
+ufunc_gdtrix_types[5] = NPY_DOUBLE
+ufunc_gdtrix_types[6] = NPY_DOUBLE
+ufunc_gdtrix_types[7] = NPY_DOUBLE
+ufunc_gdtrix_ptr[2*0] = _func_gdtrix
+ufunc_gdtrix_ptr[2*0+1] = ("gdtrix")
+ufunc_gdtrix_ptr[2*1] = _func_gdtrix
+ufunc_gdtrix_ptr[2*1+1] = ("gdtrix")
+ufunc_gdtrix_data[0] = &ufunc_gdtrix_ptr[2*0]
+ufunc_gdtrix_data[1] = &ufunc_gdtrix_ptr[2*1]
+gdtrix = np.PyUFunc_FromFuncAndData(ufunc_gdtrix_loops, ufunc_gdtrix_data, ufunc_gdtrix_types, 2, 3, 1, 0, "gdtrix", ufunc_gdtrix_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_huber_loops[2]
+cdef void *ufunc_huber_ptr[4]
+cdef void *ufunc_huber_data[2]
+cdef char ufunc_huber_types[6]
+cdef char *ufunc_huber_doc = (
+    "huber(delta, r, out=None)\n"
+    "\n"
+    "Huber loss function.\n"
+    "\n"
+    ".. math:: \\text{huber}(\\delta, r) = \\begin{cases} \\infty & \\delta < 0  \\\\\n"
+    "          \\frac{1}{2}r^2 & 0 \\le \\delta, | r | \\le \\delta \\\\\n"
+    "          \\delta ( |r| - \\frac{1}{2}\\delta ) & \\text{otherwise} \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "delta : ndarray\n"
+    "    Input array, indicating the quadratic vs. linear loss changepoint.\n"
+    "r : ndarray\n"
+    "    Input array, possibly representing residuals.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The computed Huber loss function values.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pseudo_huber : smooth approximation of this function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`huber` is useful as a loss function in robust statistics or machine\n"
+    "learning to reduce the influence of outliers as compared to the common\n"
+    "squared error loss, residuals with a magnitude higher than `delta` are\n"
+    "not squared [1]_.\n"
+    "\n"
+    "Typically, `r` represents residuals, the difference\n"
+    "between a model prediction and data. Then, for :math:`|r|\\leq\\delta`,\n"
+    "`huber` resembles the squared error and for :math:`|r|>\\delta` the\n"
+    "absolute error. This way, the Huber loss often achieves\n"
+    "a fast convergence in model fitting for small residuals like the squared\n"
+    "error loss function and still reduces the influence of outliers\n"
+    "(:math:`|r|>\\delta`) like the absolute error loss. As :math:`\\delta` is\n"
+    "the cutoff between squared and absolute error regimes, it has\n"
+    "to be tuned carefully for each problem. `huber` is also\n"
+    "convex, making it suitable for gradient based optimization.\n"
+    "\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Peter Huber. \"Robust Estimation of a Location Parameter\",\n"
+    "       1964. Annals of Statistics. 53 (1): 73 - 101.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Import all necessary modules.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import huber\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Compute the function for ``delta=1`` at ``r=2``\n"
+    "\n"
+    ">>> huber(1., 2.)\n"
+    "1.5\n"
+    "\n"
+    "Compute the function for different `delta` by providing a NumPy array or\n"
+    "list for `delta`.\n"
+    "\n"
+    ">>> huber([1., 3., 5.], 4.)\n"
+    "array([3.5, 7.5, 8. ])\n"
+    "\n"
+    "Compute the function at different points by providing a NumPy array or\n"
+    "list for `r`.\n"
+    "\n"
+    ">>> huber(2., np.array([1., 1.5, 3.]))\n"
+    "array([0.5  , 1.125, 4.   ])\n"
+    "\n"
+    "The function can be calculated for different `delta` and `r` by\n"
+    "providing arrays for both with compatible shapes for broadcasting.\n"
+    "\n"
+    ">>> r = np.array([1., 2.5, 8., 10.])\n"
+    ">>> deltas = np.array([[1.], [5.], [9.]])\n"
+    ">>> print(r.shape, deltas.shape)\n"
+    "(4,) (3, 1)\n"
+    "\n"
+    ">>> huber(deltas, r)\n"
+    "array([[ 0.5  ,  2.   ,  7.5  ,  9.5  ],\n"
+    "       [ 0.5  ,  3.125, 27.5  , 37.5  ],\n"
+    "       [ 0.5  ,  3.125, 32.   , 49.5  ]])\n"
+    "\n"
+    "Plot the function for different `delta`.\n"
+    "\n"
+    ">>> x = np.linspace(-4, 4, 500)\n"
+    ">>> deltas = [1, 2, 3]\n"
+    ">>> linestyles = [\"dashed\", \"dotted\", \"dashdot\"]\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> combined_plot_parameters = list(zip(deltas, linestyles))\n"
+    ">>> for delta, style in combined_plot_parameters:\n"
+    "...     ax.plot(x, huber(delta, x), label=fr\"$\\delta={delta}$\", ls=style)\n"
+    ">>> ax.legend(loc=\"upper center\")\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(r\"Huber loss function $h_{\\delta}(x)$\")\n"
+    ">>> ax.set_xlim(-4, 4)\n"
+    ">>> ax.set_ylim(0, 8)\n"
+    ">>> plt.show()")
+ufunc_huber_loops[0] = loop_d_dd__As_ff_f
+ufunc_huber_loops[1] = loop_d_dd__As_dd_d
+ufunc_huber_types[0] = NPY_FLOAT
+ufunc_huber_types[1] = NPY_FLOAT
+ufunc_huber_types[2] = NPY_FLOAT
+ufunc_huber_types[3] = NPY_DOUBLE
+ufunc_huber_types[4] = NPY_DOUBLE
+ufunc_huber_types[5] = NPY_DOUBLE
+ufunc_huber_ptr[2*0] = _func_huber
+ufunc_huber_ptr[2*0+1] = ("huber")
+ufunc_huber_ptr[2*1] = _func_huber
+ufunc_huber_ptr[2*1+1] = ("huber")
+ufunc_huber_data[0] = &ufunc_huber_ptr[2*0]
+ufunc_huber_data[1] = &ufunc_huber_ptr[2*1]
+huber = np.PyUFunc_FromFuncAndData(ufunc_huber_loops, ufunc_huber_data, ufunc_huber_types, 2, 2, 1, 0, "huber", ufunc_huber_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_hyp0f1_loops[4]
+cdef void *ufunc_hyp0f1_ptr[8]
+cdef void *ufunc_hyp0f1_data[4]
+cdef char ufunc_hyp0f1_types[12]
+cdef char *ufunc_hyp0f1_doc = (
+    "hyp0f1(v, z, out=None)\n"
+    "\n"
+    "Confluent hypergeometric limit function 0F1.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "v : array_like\n"
+    "    Real-valued parameter\n"
+    "z : array_like\n"
+    "    Real- or complex-valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The confluent hypergeometric limit function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function is defined as:\n"
+    "\n"
+    ".. math:: _0F_1(v, z) = \\sum_{k=0}^{\\infty}\\frac{z^k}{(v)_k k!}.\n"
+    "\n"
+    "It's also the limit as :math:`q \\to \\infty` of :math:`_1F_1(q; v; z/q)`,\n"
+    "and satisfies the differential equation :math:`f''(z) + vf'(z) =\n"
+    "f(z)`. See [1]_ for more information.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Wolfram MathWorld, \"Confluent Hypergeometric Limit Function\",\n"
+    "       http://mathworld.wolfram.com/ConfluentHypergeometricLimitFunction.html\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is one when `z` is zero.\n"
+    "\n"
+    ">>> sc.hyp0f1(1, 0)\n"
+    "1.0\n"
+    "\n"
+    "It is the limit of the confluent hypergeometric function as `q`\n"
+    "goes to infinity.\n"
+    "\n"
+    ">>> q = np.array([1, 10, 100, 1000])\n"
+    ">>> v = 1\n"
+    ">>> z = 1\n"
+    ">>> sc.hyp1f1(q, v, z / q)\n"
+    "array([2.71828183, 2.31481985, 2.28303778, 2.27992985])\n"
+    ">>> sc.hyp0f1(v, z)\n"
+    "2.2795853023360673\n"
+    "\n"
+    "It is related to Bessel functions.\n"
+    "\n"
+    ">>> n = 1\n"
+    ">>> x = np.linspace(0, 1, 5)\n"
+    ">>> sc.jv(n, x)\n"
+    "array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])\n"
+    ">>> (0.5 * x)**n / sc.factorial(n) * sc.hyp0f1(n + 1, -0.25 * x**2)\n"
+    "array([0.        , 0.12402598, 0.24226846, 0.3492436 , 0.44005059])")
+ufunc_hyp0f1_loops[0] = loop_d_dd__As_ff_f
+ufunc_hyp0f1_loops[1] = loop_D_dD__As_fF_F
+ufunc_hyp0f1_loops[2] = loop_d_dd__As_dd_d
+ufunc_hyp0f1_loops[3] = loop_D_dD__As_dD_D
+ufunc_hyp0f1_types[0] = NPY_FLOAT
+ufunc_hyp0f1_types[1] = NPY_FLOAT
+ufunc_hyp0f1_types[2] = NPY_FLOAT
+ufunc_hyp0f1_types[3] = NPY_FLOAT
+ufunc_hyp0f1_types[4] = NPY_CFLOAT
+ufunc_hyp0f1_types[5] = NPY_CFLOAT
+ufunc_hyp0f1_types[6] = NPY_DOUBLE
+ufunc_hyp0f1_types[7] = NPY_DOUBLE
+ufunc_hyp0f1_types[8] = NPY_DOUBLE
+ufunc_hyp0f1_types[9] = NPY_DOUBLE
+ufunc_hyp0f1_types[10] = NPY_CDOUBLE
+ufunc_hyp0f1_types[11] = NPY_CDOUBLE
+ufunc_hyp0f1_ptr[2*0] = _func__hyp0f1_real
+ufunc_hyp0f1_ptr[2*0+1] = ("hyp0f1")
+ufunc_hyp0f1_ptr[2*1] = _func__hyp0f1_cmplx
+ufunc_hyp0f1_ptr[2*1+1] = ("hyp0f1")
+ufunc_hyp0f1_ptr[2*2] = _func__hyp0f1_real
+ufunc_hyp0f1_ptr[2*2+1] = ("hyp0f1")
+ufunc_hyp0f1_ptr[2*3] = _func__hyp0f1_cmplx
+ufunc_hyp0f1_ptr[2*3+1] = ("hyp0f1")
+ufunc_hyp0f1_data[0] = &ufunc_hyp0f1_ptr[2*0]
+ufunc_hyp0f1_data[1] = &ufunc_hyp0f1_ptr[2*1]
+ufunc_hyp0f1_data[2] = &ufunc_hyp0f1_ptr[2*2]
+ufunc_hyp0f1_data[3] = &ufunc_hyp0f1_ptr[2*3]
+hyp0f1 = np.PyUFunc_FromFuncAndData(ufunc_hyp0f1_loops, ufunc_hyp0f1_data, ufunc_hyp0f1_types, 4, 2, 1, 0, "hyp0f1", ufunc_hyp0f1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_hyp1f1_loops[4]
+cdef void *ufunc_hyp1f1_ptr[8]
+cdef void *ufunc_hyp1f1_data[4]
+cdef char ufunc_hyp1f1_types[16]
+cdef char *ufunc_hyp1f1_doc = (
+    "hyp1f1(a, b, x, out=None)\n"
+    "\n"
+    "Confluent hypergeometric function 1F1.\n"
+    "\n"
+    "The confluent hypergeometric function is defined by the series\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   {}_1F_1(a; b; x) = \\sum_{k = 0}^\\infty \\frac{(a)_k}{(b)_k k!} x^k.\n"
+    "\n"
+    "See [dlmf]_ for more details. Here :math:`(\\cdot)_k` is the\n"
+    "Pochhammer symbol; see `poch`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Real parameters\n"
+    "x : array_like\n"
+    "    Real or complex argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the confluent hypergeometric function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "hyperu : another confluent hypergeometric function\n"
+    "hyp0f1 : confluent hypergeometric limit function\n"
+    "hyp2f1 : Gaussian hypergeometric function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "For real values, this function uses the ``hyp1f1`` routine from the C++ Boost\n"
+    "library [2]_, for complex values a C translation of the specfun\n"
+    "Fortran library [3]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] NIST Digital Library of Mathematical Functions\n"
+    "          https://dlmf.nist.gov/13.2#E2\n"
+    ".. [2] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    ".. [3] Zhang, Jin, \"Computation of Special Functions\", John Wiley\n"
+    "       and Sons, Inc, 1996.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is one when `x` is zero:\n"
+    "\n"
+    ">>> sc.hyp1f1(0.5, 0.5, 0)\n"
+    "1.0\n"
+    "\n"
+    "It is singular when `b` is a nonpositive integer.\n"
+    "\n"
+    ">>> sc.hyp1f1(0.5, -1, 0)\n"
+    "inf\n"
+    "\n"
+    "It is a polynomial when `a` is a nonpositive integer.\n"
+    "\n"
+    ">>> a, b, x = -1, 0.5, np.array([1.0, 2.0, 3.0, 4.0])\n"
+    ">>> sc.hyp1f1(a, b, x)\n"
+    "array([-1., -3., -5., -7.])\n"
+    ">>> 1 + (a / b) * x\n"
+    "array([-1., -3., -5., -7.])\n"
+    "\n"
+    "It reduces to the exponential function when ``a = b``.\n"
+    "\n"
+    ">>> sc.hyp1f1(2, 2, [1, 2, 3, 4])\n"
+    "array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])\n"
+    ">>> np.exp([1, 2, 3, 4])\n"
+    "array([ 2.71828183,  7.3890561 , 20.08553692, 54.59815003])")
+ufunc_hyp1f1_loops[0] = loop_d_ddd__As_fff_f
+ufunc_hyp1f1_loops[1] = loop_D_ddD__As_ffF_F
+ufunc_hyp1f1_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_hyp1f1_loops[3] = loop_D_ddD__As_ddD_D
+ufunc_hyp1f1_types[0] = NPY_FLOAT
+ufunc_hyp1f1_types[1] = NPY_FLOAT
+ufunc_hyp1f1_types[2] = NPY_FLOAT
+ufunc_hyp1f1_types[3] = NPY_FLOAT
+ufunc_hyp1f1_types[4] = NPY_FLOAT
+ufunc_hyp1f1_types[5] = NPY_FLOAT
+ufunc_hyp1f1_types[6] = NPY_CFLOAT
+ufunc_hyp1f1_types[7] = NPY_CFLOAT
+ufunc_hyp1f1_types[8] = NPY_DOUBLE
+ufunc_hyp1f1_types[9] = NPY_DOUBLE
+ufunc_hyp1f1_types[10] = NPY_DOUBLE
+ufunc_hyp1f1_types[11] = NPY_DOUBLE
+ufunc_hyp1f1_types[12] = NPY_DOUBLE
+ufunc_hyp1f1_types[13] = NPY_DOUBLE
+ufunc_hyp1f1_types[14] = NPY_CDOUBLE
+ufunc_hyp1f1_types[15] = NPY_CDOUBLE
+ufunc_hyp1f1_ptr[2*0] = scipy.special._ufuncs_cxx._export_hyp1f1_double
+ufunc_hyp1f1_ptr[2*0+1] = ("hyp1f1")
+ufunc_hyp1f1_ptr[2*1] = _func_chyp1f1_wrap
+ufunc_hyp1f1_ptr[2*1+1] = ("hyp1f1")
+ufunc_hyp1f1_ptr[2*2] = scipy.special._ufuncs_cxx._export_hyp1f1_double
+ufunc_hyp1f1_ptr[2*2+1] = ("hyp1f1")
+ufunc_hyp1f1_ptr[2*3] = _func_chyp1f1_wrap
+ufunc_hyp1f1_ptr[2*3+1] = ("hyp1f1")
+ufunc_hyp1f1_data[0] = &ufunc_hyp1f1_ptr[2*0]
+ufunc_hyp1f1_data[1] = &ufunc_hyp1f1_ptr[2*1]
+ufunc_hyp1f1_data[2] = &ufunc_hyp1f1_ptr[2*2]
+ufunc_hyp1f1_data[3] = &ufunc_hyp1f1_ptr[2*3]
+hyp1f1 = np.PyUFunc_FromFuncAndData(ufunc_hyp1f1_loops, ufunc_hyp1f1_data, ufunc_hyp1f1_types, 4, 3, 1, 0, "hyp1f1", ufunc_hyp1f1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_hyperu_loops[2]
+cdef void *ufunc_hyperu_ptr[4]
+cdef void *ufunc_hyperu_data[2]
+cdef char ufunc_hyperu_types[8]
+cdef char *ufunc_hyperu_doc = (
+    "hyperu(a, b, x, out=None)\n"
+    "\n"
+    "Confluent hypergeometric function U\n"
+    "\n"
+    "It is defined as the solution to the equation\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   x \\frac{d^2w}{dx^2} + (b - x) \\frac{dw}{dx} - aw = 0\n"
+    "\n"
+    "which satisfies the property\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   U(a, b, x) \\sim x^{-a}\n"
+    "\n"
+    "as :math:`x \\to \\infty`. See [dlmf]_ for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "a, b : array_like\n"
+    "    Real-valued parameters\n"
+    "x : array_like\n"
+    "    Real-valued argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of `U`\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] NIST Digital Library of Mathematics Functions\n"
+    "          https://dlmf.nist.gov/13.2#E6\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It has a branch cut along the negative `x` axis.\n"
+    "\n"
+    ">>> x = np.linspace(-0.1, -10, 5)\n"
+    ">>> sc.hyperu(1, 1, x)\n"
+    "array([nan, nan, nan, nan, nan])\n"
+    "\n"
+    "It approaches zero as `x` goes to infinity.\n"
+    "\n"
+    ">>> x = np.array([1, 10, 100])\n"
+    ">>> sc.hyperu(1, 1, x)\n"
+    "array([0.59634736, 0.09156333, 0.00990194])\n"
+    "\n"
+    "It satisfies Kummer's transformation.\n"
+    "\n"
+    ">>> a, b, x = 2, 1, 1\n"
+    ">>> sc.hyperu(a, b, x)\n"
+    "0.1926947246463881\n"
+    ">>> x**(1 - b) * sc.hyperu(a - b + 1, 2 - b, x)\n"
+    "0.1926947246463881")
+ufunc_hyperu_loops[0] = loop_d_ddd__As_fff_f
+ufunc_hyperu_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_hyperu_types[0] = NPY_FLOAT
+ufunc_hyperu_types[1] = NPY_FLOAT
+ufunc_hyperu_types[2] = NPY_FLOAT
+ufunc_hyperu_types[3] = NPY_FLOAT
+ufunc_hyperu_types[4] = NPY_DOUBLE
+ufunc_hyperu_types[5] = NPY_DOUBLE
+ufunc_hyperu_types[6] = NPY_DOUBLE
+ufunc_hyperu_types[7] = NPY_DOUBLE
+ufunc_hyperu_ptr[2*0] = _func_hyperu
+ufunc_hyperu_ptr[2*0+1] = ("hyperu")
+ufunc_hyperu_ptr[2*1] = _func_hyperu
+ufunc_hyperu_ptr[2*1+1] = ("hyperu")
+ufunc_hyperu_data[0] = &ufunc_hyperu_ptr[2*0]
+ufunc_hyperu_data[1] = &ufunc_hyperu_ptr[2*1]
+hyperu = np.PyUFunc_FromFuncAndData(ufunc_hyperu_loops, ufunc_hyperu_data, ufunc_hyperu_types, 2, 3, 1, 0, "hyperu", ufunc_hyperu_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_inv_boxcox_loops[2]
+cdef void *ufunc_inv_boxcox_ptr[4]
+cdef void *ufunc_inv_boxcox_data[2]
+cdef char ufunc_inv_boxcox_types[6]
+cdef char *ufunc_inv_boxcox_doc = (
+    "inv_boxcox(y, lmbda, out=None)\n"
+    "\n"
+    "Compute the inverse of the Box-Cox transformation.\n"
+    "\n"
+    "Find ``x`` such that::\n"
+    "\n"
+    "    y = (x**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(x)                  if lmbda == 0\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.16.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox, inv_boxcox\n"
+    ">>> y = boxcox([1, 4, 10], 2.5)\n"
+    ">>> inv_boxcox(y, 2.5)\n"
+    "array([1., 4., 10.])")
+ufunc_inv_boxcox_loops[0] = loop_d_dd__As_ff_f
+ufunc_inv_boxcox_loops[1] = loop_d_dd__As_dd_d
+ufunc_inv_boxcox_types[0] = NPY_FLOAT
+ufunc_inv_boxcox_types[1] = NPY_FLOAT
+ufunc_inv_boxcox_types[2] = NPY_FLOAT
+ufunc_inv_boxcox_types[3] = NPY_DOUBLE
+ufunc_inv_boxcox_types[4] = NPY_DOUBLE
+ufunc_inv_boxcox_types[5] = NPY_DOUBLE
+ufunc_inv_boxcox_ptr[2*0] = _func_inv_boxcox
+ufunc_inv_boxcox_ptr[2*0+1] = ("inv_boxcox")
+ufunc_inv_boxcox_ptr[2*1] = _func_inv_boxcox
+ufunc_inv_boxcox_ptr[2*1+1] = ("inv_boxcox")
+ufunc_inv_boxcox_data[0] = &ufunc_inv_boxcox_ptr[2*0]
+ufunc_inv_boxcox_data[1] = &ufunc_inv_boxcox_ptr[2*1]
+inv_boxcox = np.PyUFunc_FromFuncAndData(ufunc_inv_boxcox_loops, ufunc_inv_boxcox_data, ufunc_inv_boxcox_types, 2, 2, 1, 0, "inv_boxcox", ufunc_inv_boxcox_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_inv_boxcox1p_loops[2]
+cdef void *ufunc_inv_boxcox1p_ptr[4]
+cdef void *ufunc_inv_boxcox1p_data[2]
+cdef char ufunc_inv_boxcox1p_types[6]
+cdef char *ufunc_inv_boxcox1p_doc = (
+    "inv_boxcox1p(y, lmbda, out=None)\n"
+    "\n"
+    "Compute the inverse of the Box-Cox transformation.\n"
+    "\n"
+    "Find ``x`` such that::\n"
+    "\n"
+    "    y = ((1+x)**lmbda - 1) / lmbda  if lmbda != 0\n"
+    "        log(1+x)                    if lmbda == 0\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    Data to be transformed.\n"
+    "lmbda : array_like\n"
+    "    Power parameter of the Box-Cox transform.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Transformed data.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.16.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import boxcox1p, inv_boxcox1p\n"
+    ">>> y = boxcox1p([1, 4, 10], 2.5)\n"
+    ">>> inv_boxcox1p(y, 2.5)\n"
+    "array([1., 4., 10.])")
+ufunc_inv_boxcox1p_loops[0] = loop_d_dd__As_ff_f
+ufunc_inv_boxcox1p_loops[1] = loop_d_dd__As_dd_d
+ufunc_inv_boxcox1p_types[0] = NPY_FLOAT
+ufunc_inv_boxcox1p_types[1] = NPY_FLOAT
+ufunc_inv_boxcox1p_types[2] = NPY_FLOAT
+ufunc_inv_boxcox1p_types[3] = NPY_DOUBLE
+ufunc_inv_boxcox1p_types[4] = NPY_DOUBLE
+ufunc_inv_boxcox1p_types[5] = NPY_DOUBLE
+ufunc_inv_boxcox1p_ptr[2*0] = _func_inv_boxcox1p
+ufunc_inv_boxcox1p_ptr[2*0+1] = ("inv_boxcox1p")
+ufunc_inv_boxcox1p_ptr[2*1] = _func_inv_boxcox1p
+ufunc_inv_boxcox1p_ptr[2*1+1] = ("inv_boxcox1p")
+ufunc_inv_boxcox1p_data[0] = &ufunc_inv_boxcox1p_ptr[2*0]
+ufunc_inv_boxcox1p_data[1] = &ufunc_inv_boxcox1p_ptr[2*1]
+inv_boxcox1p = np.PyUFunc_FromFuncAndData(ufunc_inv_boxcox1p_loops, ufunc_inv_boxcox1p_data, ufunc_inv_boxcox1p_types, 2, 2, 1, 0, "inv_boxcox1p", ufunc_inv_boxcox1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kl_div_loops[2]
+cdef void *ufunc_kl_div_ptr[4]
+cdef void *ufunc_kl_div_data[2]
+cdef char ufunc_kl_div_types[6]
+cdef char *ufunc_kl_div_doc = (
+    "kl_div(x, y, out=None)\n"
+    "\n"
+    "Elementwise function for computing Kullback-Leibler divergence.\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\mathrm{kl\\_div}(x, y) =\n"
+    "      \\begin{cases}\n"
+    "        x \\log(x / y) - x + y & x > 0, y > 0 \\\\\n"
+    "        y & x = 0, y \\ge 0 \\\\\n"
+    "        \\infty & \\text{otherwise}\n"
+    "      \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y : array_like\n"
+    "    Real arguments\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the Kullback-Liebler divergence.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "entr, rel_entr, scipy.stats.entropy\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "This function is non-negative and is jointly convex in `x` and `y`.\n"
+    "\n"
+    "The origin of this function is in convex programming; see [1]_ for\n"
+    "details. This is why the function contains the extra :math:`-x\n"
+    "+ y` terms over what might be expected from the Kullback-Leibler\n"
+    "divergence. For a version of the function without the extra terms,\n"
+    "see `rel_entr`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n"
+    "       Cambridge University Press, 2004.\n"
+    "       :doi:`https://doi.org/10.1017/CBO9780511804441`")
+ufunc_kl_div_loops[0] = loop_d_dd__As_ff_f
+ufunc_kl_div_loops[1] = loop_d_dd__As_dd_d
+ufunc_kl_div_types[0] = NPY_FLOAT
+ufunc_kl_div_types[1] = NPY_FLOAT
+ufunc_kl_div_types[2] = NPY_FLOAT
+ufunc_kl_div_types[3] = NPY_DOUBLE
+ufunc_kl_div_types[4] = NPY_DOUBLE
+ufunc_kl_div_types[5] = NPY_DOUBLE
+ufunc_kl_div_ptr[2*0] = _func_kl_div
+ufunc_kl_div_ptr[2*0+1] = ("kl_div")
+ufunc_kl_div_ptr[2*1] = _func_kl_div
+ufunc_kl_div_ptr[2*1+1] = ("kl_div")
+ufunc_kl_div_data[0] = &ufunc_kl_div_ptr[2*0]
+ufunc_kl_div_data[1] = &ufunc_kl_div_ptr[2*1]
+kl_div = np.PyUFunc_FromFuncAndData(ufunc_kl_div_loops, ufunc_kl_div_data, ufunc_kl_div_types, 2, 2, 1, 0, "kl_div", ufunc_kl_div_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kn_loops[3]
+cdef void *ufunc_kn_ptr[6]
+cdef void *ufunc_kn_data[3]
+cdef char ufunc_kn_types[9]
+cdef char *ufunc_kn_doc = (
+    "kn(n, x, out=None)\n"
+    "\n"
+    "Modified Bessel function of the second kind of integer order `n`\n"
+    "\n"
+    "Returns the modified Bessel function of the second kind for integer order\n"
+    "`n` at real `z`.\n"
+    "\n"
+    "These are also sometimes called functions of the third kind, Basset\n"
+    "functions, or Macdonald functions.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like of int\n"
+    "    Order of Bessel functions (floats will truncate with a warning)\n"
+    "x : array_like of float\n"
+    "    Argument at which to evaluate the Bessel functions\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the Modified Bessel function of the second kind,\n"
+    "    :math:`K_n(x)`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kv : Same function, but accepts real order and complex argument\n"
+    "kvp : Derivative of this function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for AMOS [1]_ routine `zbesk`.  For a discussion of the\n"
+    "algorithm used, see [2]_ and the references therein.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Donald E. Amos, \"AMOS, A Portable Package for Bessel Functions\n"
+    "       of a Complex Argument and Nonnegative Order\",\n"
+    "       http://netlib.org/amos/\n"
+    ".. [2] Donald E. Amos, \"Algorithm 644: A portable package for Bessel\n"
+    "       functions of a complex argument and nonnegative order\", ACM\n"
+    "       TOMS Vol. 12 Issue 3, Sept. 1986, p. 265\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Plot the function of several orders for real input:\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import kn\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(0, 5, 1000)\n"
+    ">>> for N in range(6):\n"
+    "...     plt.plot(x, kn(N, x), label='$K_{}(x)$'.format(N))\n"
+    ">>> plt.ylim(0, 10)\n"
+    ">>> plt.legend()\n"
+    ">>> plt.title(r'Modified Bessel function of the second kind $K_n(x)$')\n"
+    ">>> plt.show()\n"
+    "\n"
+    "Calculate for a single value at multiple orders:\n"
+    "\n"
+    ">>> kn([4, 5, 6], 1)\n"
+    "array([   44.23241585,   360.9605896 ,  3653.83831186])")
+ufunc_kn_loops[0] = loop_d_pd__As_pd_d
+ufunc_kn_loops[1] = loop_d_dd__As_ff_f
+ufunc_kn_loops[2] = loop_d_dd__As_dd_d
+ufunc_kn_types[0] = NPY_INTP
+ufunc_kn_types[1] = NPY_DOUBLE
+ufunc_kn_types[2] = NPY_DOUBLE
+ufunc_kn_types[3] = NPY_FLOAT
+ufunc_kn_types[4] = NPY_FLOAT
+ufunc_kn_types[5] = NPY_FLOAT
+ufunc_kn_types[6] = NPY_DOUBLE
+ufunc_kn_types[7] = NPY_DOUBLE
+ufunc_kn_types[8] = NPY_DOUBLE
+ufunc_kn_ptr[2*0] = _func_special_cyl_bessel_k_int
+ufunc_kn_ptr[2*0+1] = ("kn")
+ufunc_kn_ptr[2*1] = _func_kn_unsafe
+ufunc_kn_ptr[2*1+1] = ("kn")
+ufunc_kn_ptr[2*2] = _func_kn_unsafe
+ufunc_kn_ptr[2*2+1] = ("kn")
+ufunc_kn_data[0] = &ufunc_kn_ptr[2*0]
+ufunc_kn_data[1] = &ufunc_kn_ptr[2*1]
+ufunc_kn_data[2] = &ufunc_kn_ptr[2*2]
+kn = np.PyUFunc_FromFuncAndData(ufunc_kn_loops, ufunc_kn_data, ufunc_kn_types, 3, 2, 1, 0, "kn", ufunc_kn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kolmogi_loops[2]
+cdef void *ufunc_kolmogi_ptr[4]
+cdef void *ufunc_kolmogi_data[2]
+cdef char ufunc_kolmogi_types[4]
+cdef char *ufunc_kolmogi_doc = (
+    "kolmogi(p, out=None)\n"
+    "\n"
+    "Inverse Survival Function of Kolmogorov distribution\n"
+    "\n"
+    "It is the inverse function to `kolmogorov`.\n"
+    "Returns y such that ``kolmogorov(y) == p``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : float array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of kolmogi(p)\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kolmogorov : The Survival Function for the distribution\n"
+    "scipy.stats.kstwobign : Provides the functionality as a continuous distribution\n"
+    "smirnov, smirnovi : Functions for the one-sided distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`kolmogorov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.kstwobign` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import kolmogi\n"
+    ">>> kolmogi([0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0])\n"
+    "array([        inf,  1.22384787,  1.01918472,  0.82757356,  0.67644769,\n"
+    "        0.57117327,  0.        ])")
+ufunc_kolmogi_loops[0] = loop_d_d__As_f_f
+ufunc_kolmogi_loops[1] = loop_d_d__As_d_d
+ufunc_kolmogi_types[0] = NPY_FLOAT
+ufunc_kolmogi_types[1] = NPY_FLOAT
+ufunc_kolmogi_types[2] = NPY_DOUBLE
+ufunc_kolmogi_types[3] = NPY_DOUBLE
+ufunc_kolmogi_ptr[2*0] = _func_xsf_kolmogi
+ufunc_kolmogi_ptr[2*0+1] = ("kolmogi")
+ufunc_kolmogi_ptr[2*1] = _func_xsf_kolmogi
+ufunc_kolmogi_ptr[2*1+1] = ("kolmogi")
+ufunc_kolmogi_data[0] = &ufunc_kolmogi_ptr[2*0]
+ufunc_kolmogi_data[1] = &ufunc_kolmogi_ptr[2*1]
+kolmogi = np.PyUFunc_FromFuncAndData(ufunc_kolmogi_loops, ufunc_kolmogi_data, ufunc_kolmogi_types, 2, 1, 1, 0, "kolmogi", ufunc_kolmogi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_kolmogorov_loops[2]
+cdef void *ufunc_kolmogorov_ptr[4]
+cdef void *ufunc_kolmogorov_data[2]
+cdef char ufunc_kolmogorov_types[4]
+cdef char *ufunc_kolmogorov_doc = (
+    "kolmogorov(y, out=None)\n"
+    "\n"
+    "Complementary cumulative distribution (Survival Function) function of\n"
+    "Kolmogorov distribution.\n"
+    "\n"
+    "Returns the complementary cumulative distribution function of\n"
+    "Kolmogorov's limiting distribution (``D_n*\\sqrt(n)`` as n goes to infinity)\n"
+    "of a two-sided test for equality between an empirical and a theoretical\n"
+    "distribution. It is equal to the (limit as n->infinity of the)\n"
+    "probability that ``sqrt(n) * max absolute deviation > y``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : float array_like\n"
+    "  Absolute deviation between the Empirical CDF (ECDF) and the target CDF,\n"
+    "  multiplied by sqrt(n).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of kolmogorov(y)\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "kolmogi : The Inverse Survival Function for the distribution\n"
+    "scipy.stats.kstwobign : Provides the functionality as a continuous distribution\n"
+    "smirnov, smirnovi : Functions for the one-sided distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`kolmogorov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.kstwobign` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Show the probability of a gap at least as big as 0, 0.5 and 1.0.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import kolmogorov\n"
+    ">>> from scipy.stats import kstwobign\n"
+    ">>> kolmogorov([0, 0.5, 1.0])\n"
+    "array([ 1.        ,  0.96394524,  0.26999967])\n"
+    "\n"
+    "Compare a sample of size 1000 drawn from a Laplace(0, 1) distribution against\n"
+    "the target distribution, a Normal(0, 1) distribution.\n"
+    "\n"
+    ">>> from scipy.stats import norm, laplace\n"
+    ">>> rng = np.random.default_rng()\n"
+    ">>> n = 1000\n"
+    ">>> lap01 = laplace(0, 1)\n"
+    ">>> x = np.sort(lap01.rvs(n, random_state=rng))\n"
+    ">>> np.mean(x), np.std(x)\n"
+    "(-0.05841730131499543, 1.3968109101997568)\n"
+    "\n"
+    "Construct the Empirical CDF and the K-S statistic Dn.\n"
+    "\n"
+    ">>> target = norm(0,1)  # Normal mean 0, stddev 1\n"
+    ">>> cdfs = target.cdf(x)\n"
+    ">>> ecdfs = np.arange(n+1, dtype=float)/n\n"
+    ">>> gaps = np.column_stack([cdfs - ecdfs[:n], ecdfs[1:] - cdfs])\n"
+    ">>> Dn = np.max(gaps)\n"
+    ">>> Kn = np.sqrt(n) * Dn\n"
+    ">>> print('Dn=%f, sqrt(n)*Dn=%f' % (Dn, Kn))\n"
+    "Dn=0.043363, sqrt(n)*Dn=1.371265\n"
+    ">>> print(chr(10).join(['For a sample of size n drawn from a N(0, 1) distribution:',\n"
+    "...   ' the approximate Kolmogorov probability that sqrt(n)*Dn>=%f is %f' %\n"
+    "...    (Kn, kolmogorov(Kn)),\n"
+    "...   ' the approximate Kolmogorov probability that sqrt(n)*Dn<=%f is %f' %\n"
+    "...    (Kn, kstwobign.cdf(Kn))]))\n"
+    "For a sample of size n drawn from a N(0, 1) distribution:\n"
+    " the approximate Kolmogorov probability that sqrt(n)*Dn>=1.371265 is 0.046533\n"
+    " the approximate Kolmogorov probability that sqrt(n)*Dn<=1.371265 is 0.953467\n"
+    "\n"
+    "Plot the Empirical CDF against the target N(0, 1) CDF.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> plt.step(np.concatenate([[-3], x]), ecdfs, where='post', label='Empirical CDF')\n"
+    ">>> x3 = np.linspace(-3, 3, 100)\n"
+    ">>> plt.plot(x3, target.cdf(x3), label='CDF for N(0, 1)')\n"
+    ">>> plt.ylim([0, 1]); plt.grid(True); plt.legend();\n"
+    ">>> # Add vertical lines marking Dn+ and Dn-\n"
+    ">>> iminus, iplus = np.argmax(gaps, axis=0)\n"
+    ">>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus],\n"
+    "...            color='r', linestyle='dashed', lw=4)\n"
+    ">>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1],\n"
+    "...            color='r', linestyle='dashed', lw=4)\n"
+    ">>> plt.show()")
+ufunc_kolmogorov_loops[0] = loop_d_d__As_f_f
+ufunc_kolmogorov_loops[1] = loop_d_d__As_d_d
+ufunc_kolmogorov_types[0] = NPY_FLOAT
+ufunc_kolmogorov_types[1] = NPY_FLOAT
+ufunc_kolmogorov_types[2] = NPY_DOUBLE
+ufunc_kolmogorov_types[3] = NPY_DOUBLE
+ufunc_kolmogorov_ptr[2*0] = _func_xsf_kolmogorov
+ufunc_kolmogorov_ptr[2*0+1] = ("kolmogorov")
+ufunc_kolmogorov_ptr[2*1] = _func_xsf_kolmogorov
+ufunc_kolmogorov_ptr[2*1+1] = ("kolmogorov")
+ufunc_kolmogorov_data[0] = &ufunc_kolmogorov_ptr[2*0]
+ufunc_kolmogorov_data[1] = &ufunc_kolmogorov_ptr[2*1]
+kolmogorov = np.PyUFunc_FromFuncAndData(ufunc_kolmogorov_loops, ufunc_kolmogorov_data, ufunc_kolmogorov_types, 2, 1, 1, 0, "kolmogorov", ufunc_kolmogorov_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_log1p_loops[4]
+cdef void *ufunc_log1p_ptr[8]
+cdef void *ufunc_log1p_data[4]
+cdef char ufunc_log1p_types[8]
+cdef char *ufunc_log1p_doc = (
+    "log1p(x, out=None)\n"
+    "\n"
+    "Calculates log(1 + x) for use when `x` is near zero.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex valued input.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of ``log(1 + x)``.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "expm1, cosm1\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is more accurate than using ``log(1 + x)`` directly for ``x``\n"
+    "near 0. Note that in the below example ``1 + 1e-17 == 1`` to\n"
+    "double precision.\n"
+    "\n"
+    ">>> sc.log1p(1e-17)\n"
+    "1e-17\n"
+    ">>> np.log(1 + 1e-17)\n"
+    "0.0")
+ufunc_log1p_loops[0] = loop_d_d__As_f_f
+ufunc_log1p_loops[1] = loop_d_d__As_d_d
+ufunc_log1p_loops[2] = loop_D_D__As_F_F
+ufunc_log1p_loops[3] = loop_D_D__As_D_D
+ufunc_log1p_types[0] = NPY_FLOAT
+ufunc_log1p_types[1] = NPY_FLOAT
+ufunc_log1p_types[2] = NPY_DOUBLE
+ufunc_log1p_types[3] = NPY_DOUBLE
+ufunc_log1p_types[4] = NPY_CFLOAT
+ufunc_log1p_types[5] = NPY_CFLOAT
+ufunc_log1p_types[6] = NPY_CDOUBLE
+ufunc_log1p_types[7] = NPY_CDOUBLE
+ufunc_log1p_ptr[2*0] = _func_cephes_log1p
+ufunc_log1p_ptr[2*0+1] = ("log1p")
+ufunc_log1p_ptr[2*1] = _func_cephes_log1p
+ufunc_log1p_ptr[2*1+1] = ("log1p")
+ufunc_log1p_ptr[2*2] = _func_clog1p
+ufunc_log1p_ptr[2*2+1] = ("log1p")
+ufunc_log1p_ptr[2*3] = _func_clog1p
+ufunc_log1p_ptr[2*3+1] = ("log1p")
+ufunc_log1p_data[0] = &ufunc_log1p_ptr[2*0]
+ufunc_log1p_data[1] = &ufunc_log1p_ptr[2*1]
+ufunc_log1p_data[2] = &ufunc_log1p_ptr[2*2]
+ufunc_log1p_data[3] = &ufunc_log1p_ptr[2*3]
+log1p = np.PyUFunc_FromFuncAndData(ufunc_log1p_loops, ufunc_log1p_data, ufunc_log1p_types, 4, 1, 1, 0, "log1p", ufunc_log1p_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_log_ndtr_loops[4]
+cdef void *ufunc_log_ndtr_ptr[8]
+cdef void *ufunc_log_ndtr_data[4]
+cdef char ufunc_log_ndtr_types[8]
+cdef char *ufunc_log_ndtr_doc = (
+    "log_ndtr(x, out=None)\n"
+    "\n"
+    "Logarithm of Gaussian cumulative distribution function.\n"
+    "\n"
+    "Returns the log of the area under the standard Gaussian probability\n"
+    "density function, integrated from minus infinity to `x`::\n"
+    "\n"
+    "    log(1/sqrt(2*pi) * integral(exp(-t**2 / 2), t=-inf..x))\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like, real or complex\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value of the log of the normal CDF evaluated at `x`\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "erf\n"
+    "erfc\n"
+    "scipy.stats.norm\n"
+    "ndtr\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import log_ndtr, ndtr\n"
+    "\n"
+    "The benefit of ``log_ndtr(x)`` over the naive implementation\n"
+    "``np.log(ndtr(x))`` is most evident with moderate to large positive\n"
+    "values of ``x``:\n"
+    "\n"
+    ">>> x = np.array([6, 7, 9, 12, 15, 25])\n"
+    ">>> log_ndtr(x)\n"
+    "array([-9.86587646e-010, -1.27981254e-012, -1.12858841e-019,\n"
+    "       -1.77648211e-033, -3.67096620e-051, -3.05669671e-138])\n"
+    "\n"
+    "The results of the naive calculation for the moderate ``x`` values\n"
+    "have only 5 or 6 correct significant digits. For values of ``x``\n"
+    "greater than approximately 8.3, the naive expression returns 0:\n"
+    "\n"
+    ">>> np.log(ndtr(x))\n"
+    "array([-9.86587701e-10, -1.27986510e-12,  0.00000000e+00,\n"
+    "        0.00000000e+00,  0.00000000e+00,  0.00000000e+00])")
+ufunc_log_ndtr_loops[0] = loop_d_d__As_f_f
+ufunc_log_ndtr_loops[1] = loop_d_d__As_d_d
+ufunc_log_ndtr_loops[2] = loop_D_D__As_F_F
+ufunc_log_ndtr_loops[3] = loop_D_D__As_D_D
+ufunc_log_ndtr_types[0] = NPY_FLOAT
+ufunc_log_ndtr_types[1] = NPY_FLOAT
+ufunc_log_ndtr_types[2] = NPY_DOUBLE
+ufunc_log_ndtr_types[3] = NPY_DOUBLE
+ufunc_log_ndtr_types[4] = NPY_CFLOAT
+ufunc_log_ndtr_types[5] = NPY_CFLOAT
+ufunc_log_ndtr_types[6] = NPY_CDOUBLE
+ufunc_log_ndtr_types[7] = NPY_CDOUBLE
+ufunc_log_ndtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr
+ufunc_log_ndtr_ptr[2*0+1] = ("log_ndtr")
+ufunc_log_ndtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr
+ufunc_log_ndtr_ptr[2*1+1] = ("log_ndtr")
+ufunc_log_ndtr_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr_complex
+ufunc_log_ndtr_ptr[2*2+1] = ("log_ndtr")
+ufunc_log_ndtr_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_log_ndtr_complex
+ufunc_log_ndtr_ptr[2*3+1] = ("log_ndtr")
+ufunc_log_ndtr_data[0] = &ufunc_log_ndtr_ptr[2*0]
+ufunc_log_ndtr_data[1] = &ufunc_log_ndtr_ptr[2*1]
+ufunc_log_ndtr_data[2] = &ufunc_log_ndtr_ptr[2*2]
+ufunc_log_ndtr_data[3] = &ufunc_log_ndtr_ptr[2*3]
+log_ndtr = np.PyUFunc_FromFuncAndData(ufunc_log_ndtr_loops, ufunc_log_ndtr_data, ufunc_log_ndtr_types, 4, 1, 1, 0, "log_ndtr", ufunc_log_ndtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_lpmv_loops[2]
+cdef void *ufunc_lpmv_ptr[4]
+cdef void *ufunc_lpmv_data[2]
+cdef char ufunc_lpmv_types[8]
+cdef char *ufunc_lpmv_doc = (
+    "lpmv(m, v, x, out=None)\n"
+    "\n"
+    "Associated Legendre function of integer order and real degree.\n"
+    "\n"
+    "Defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_v^m = (-1)^m (1 - x^2)^{m/2} \\frac{d^m}{dx^m} P_v(x)\n"
+    "\n"
+    "where\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    P_v = \\sum_{k = 0}^\\infty \\frac{(-v)_k (v + 1)_k}{(k!)^2}\n"
+    "            \\left(\\frac{1 - x}{2}\\right)^k\n"
+    "\n"
+    "is the Legendre function of the first kind. Here :math:`(\\cdot)_k`\n"
+    "is the Pochhammer symbol; see `poch`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "m : array_like\n"
+    "    Order (int or float). If passed a float not equal to an\n"
+    "    integer the function returns NaN.\n"
+    "v : array_like\n"
+    "    Degree (float).\n"
+    "x : array_like\n"
+    "    Argument (float). Must have ``|x| <= 1``.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "pmv : scalar or ndarray\n"
+    "    Value of the associated Legendre function.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "lpmn : Compute the associated Legendre function for all orders\n"
+    "       ``0, ..., m`` and degrees ``0, ..., n``.\n"
+    "clpmn : Compute the associated Legendre function at complex\n"
+    "        arguments.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Note that this implementation includes the Condon-Shortley phase.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Zhang, Jin, \"Computation of Special Functions\", John Wiley\n"
+    "       and Sons, Inc, 1996.")
+ufunc_lpmv_loops[0] = loop_d_ddd__As_fff_f
+ufunc_lpmv_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_lpmv_types[0] = NPY_FLOAT
+ufunc_lpmv_types[1] = NPY_FLOAT
+ufunc_lpmv_types[2] = NPY_FLOAT
+ufunc_lpmv_types[3] = NPY_FLOAT
+ufunc_lpmv_types[4] = NPY_DOUBLE
+ufunc_lpmv_types[5] = NPY_DOUBLE
+ufunc_lpmv_types[6] = NPY_DOUBLE
+ufunc_lpmv_types[7] = NPY_DOUBLE
+ufunc_lpmv_ptr[2*0] = _func_pmv_wrap
+ufunc_lpmv_ptr[2*0+1] = ("lpmv")
+ufunc_lpmv_ptr[2*1] = _func_pmv_wrap
+ufunc_lpmv_ptr[2*1+1] = ("lpmv")
+ufunc_lpmv_data[0] = &ufunc_lpmv_ptr[2*0]
+ufunc_lpmv_data[1] = &ufunc_lpmv_ptr[2*1]
+lpmv = np.PyUFunc_FromFuncAndData(ufunc_lpmv_loops, ufunc_lpmv_data, ufunc_lpmv_types, 2, 3, 1, 0, "lpmv", ufunc_lpmv_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtr_loops[3]
+cdef void *ufunc_nbdtr_ptr[6]
+cdef void *ufunc_nbdtr_data[3]
+cdef char ufunc_nbdtr_types[12]
+cdef char *ufunc_nbdtr_doc = (
+    "nbdtr(k, n, p, out=None)\n"
+    "\n"
+    "Negative binomial cumulative distribution function.\n"
+    "\n"
+    "Returns the sum of the terms 0 through `k` of the negative binomial\n"
+    "distribution probability mass function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\sum_{j=0}^k {{n + j - 1}\\choose{j}} p^n (1 - p)^j.\n"
+    "\n"
+    "In a sequence of Bernoulli trials with individual success probabilities\n"
+    "`p`, this is the probability that `k` or fewer failures precede the nth\n"
+    "success.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The probability of `k` or fewer failures before `n` successes in a\n"
+    "    sequence of events with individual success probability `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtrc : Negative binomial survival function\n"
+    "nbdtrik : Negative binomial quantile function\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "If floating point values are passed for `k` or `n`, they will be truncated\n"
+    "to integers.\n"
+    "\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{nbdtr}(k, n, p) = I_{p}(n, k + 1).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `nbdtr`.\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtr` directly can improve performance\n"
+    "compared to the ``cdf`` method of `scipy.stats.nbinom` (see last example).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtr\n"
+    ">>> nbdtr(10, 5, 0.5)\n"
+    "0.940765380859375\n"
+    "\n"
+    "Compute the function for ``n=10`` and ``p=0.5`` at several points by\n"
+    "providing a NumPy array or list for `k`.\n"
+    "\n"
+    ">>> nbdtr([5, 10, 15], 10, 0.5)\n"
+    "array([0.15087891, 0.58809853, 0.88523853])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> k = np.arange(130)\n"
+    ">>> n_parameters = [20, 20, 20, 80]\n"
+    ">>> p_parameters = [0.2, 0.5, 0.8, 0.5]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(p_parameters, n_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     p, n, style = parameter_set\n"
+    "...     nbdtr_vals = nbdtr(k, n, p)\n"
+    "...     ax.plot(k, nbdtr_vals, label=rf\"$n={n},\\, p={p}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$k$\")\n"
+    ">>> ax.set_title(\"Negative binomial cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtr` directly can be much faster than\n"
+    "calling the ``cdf`` method of `scipy.stats.nbinom`, especially for small\n"
+    "arrays or individual values. To get the same results one must use the\n"
+    "following parametrization: ``nbinom(n, p).cdf(k)=nbdtr(k, n, p)``.\n"
+    "\n"
+    ">>> from scipy.stats import nbinom\n"
+    ">>> k, n, p = 5, 3, 0.5\n"
+    ">>> nbdtr_res = nbdtr(k, n, p)  # this will often be faster than below\n"
+    ">>> stats_res = nbinom(n, p).cdf(k)\n"
+    ">>> stats_res, nbdtr_res  # test that results are equal\n"
+    "(0.85546875, 0.85546875)\n"
+    "\n"
+    "`nbdtr` can evaluate different parameter sets by providing arrays with\n"
+    "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n"
+    "the function for three different `k` at four locations `p`, resulting in\n"
+    "a 3x4 array.\n"
+    "\n"
+    ">>> k = np.array([[5], [10], [15]])\n"
+    ">>> p = np.array([0.3, 0.5, 0.7, 0.9])\n"
+    ">>> k.shape, p.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> nbdtr(k, 5, p)\n"
+    "array([[0.15026833, 0.62304687, 0.95265101, 0.9998531 ],\n"
+    "       [0.48450894, 0.94076538, 0.99932777, 0.99999999],\n"
+    "       [0.76249222, 0.99409103, 0.99999445, 1.        ]])")
+ufunc_nbdtr_loops[0] = loop_d_ppd__As_ppd_d
+ufunc_nbdtr_loops[1] = loop_d_ddd__As_fff_f
+ufunc_nbdtr_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_nbdtr_types[0] = NPY_INTP
+ufunc_nbdtr_types[1] = NPY_INTP
+ufunc_nbdtr_types[2] = NPY_DOUBLE
+ufunc_nbdtr_types[3] = NPY_DOUBLE
+ufunc_nbdtr_types[4] = NPY_FLOAT
+ufunc_nbdtr_types[5] = NPY_FLOAT
+ufunc_nbdtr_types[6] = NPY_FLOAT
+ufunc_nbdtr_types[7] = NPY_FLOAT
+ufunc_nbdtr_types[8] = NPY_DOUBLE
+ufunc_nbdtr_types[9] = NPY_DOUBLE
+ufunc_nbdtr_types[10] = NPY_DOUBLE
+ufunc_nbdtr_types[11] = NPY_DOUBLE
+ufunc_nbdtr_ptr[2*0] = _func_cephes_nbdtr_wrap
+ufunc_nbdtr_ptr[2*0+1] = ("nbdtr")
+ufunc_nbdtr_ptr[2*1] = _func_nbdtr_unsafe
+ufunc_nbdtr_ptr[2*1+1] = ("nbdtr")
+ufunc_nbdtr_ptr[2*2] = _func_nbdtr_unsafe
+ufunc_nbdtr_ptr[2*2+1] = ("nbdtr")
+ufunc_nbdtr_data[0] = &ufunc_nbdtr_ptr[2*0]
+ufunc_nbdtr_data[1] = &ufunc_nbdtr_ptr[2*1]
+ufunc_nbdtr_data[2] = &ufunc_nbdtr_ptr[2*2]
+nbdtr = np.PyUFunc_FromFuncAndData(ufunc_nbdtr_loops, ufunc_nbdtr_data, ufunc_nbdtr_types, 3, 3, 1, 0, "nbdtr", ufunc_nbdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtrc_loops[3]
+cdef void *ufunc_nbdtrc_ptr[6]
+cdef void *ufunc_nbdtrc_data[3]
+cdef char ufunc_nbdtrc_types[12]
+cdef char *ufunc_nbdtrc_doc = (
+    "nbdtrc(k, n, p, out=None)\n"
+    "\n"
+    "Negative binomial survival function.\n"
+    "\n"
+    "Returns the sum of the terms `k + 1` to infinity of the negative binomial\n"
+    "distribution probability mass function,\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    F = \\sum_{j=k + 1}^\\infty {{n + j - 1}\\choose{j}} p^n (1 - p)^j.\n"
+    "\n"
+    "In a sequence of Bernoulli trials with individual success probabilities\n"
+    "`p`, this is the probability that more than `k` failures precede the nth\n"
+    "success.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "F : scalar or ndarray\n"
+    "    The probability of `k + 1` or more failures before `n` successes in a\n"
+    "    sequence of events with individual success probability `p`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Negative binomial cumulative distribution function\n"
+    "nbdtrik : Negative binomial percentile function\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "If floating point values are passed for `k` or `n`, they will be truncated\n"
+    "to integers.\n"
+    "\n"
+    "The terms are not summed directly; instead the regularized incomplete beta\n"
+    "function is employed, according to the formula,\n"
+    "\n"
+    ".. math::\n"
+    "    \\mathrm{nbdtrc}(k, n, p) = I_{1 - p}(k + 1, n).\n"
+    "\n"
+    "Wrapper for the Cephes [1]_ routine `nbdtrc`.\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtrc` directly can improve performance\n"
+    "compared to the ``sf`` method of `scipy.stats.nbinom` (see last example).\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the function for ``k=10`` and ``n=5`` at ``p=0.5``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtrc\n"
+    ">>> nbdtrc(10, 5, 0.5)\n"
+    "0.059234619140624986\n"
+    "\n"
+    "Compute the function for ``n=10`` and ``p=0.5`` at several points by\n"
+    "providing a NumPy array or list for `k`.\n"
+    "\n"
+    ">>> nbdtrc([5, 10, 15], 10, 0.5)\n"
+    "array([0.84912109, 0.41190147, 0.11476147])\n"
+    "\n"
+    "Plot the function for four different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> k = np.arange(130)\n"
+    ">>> n_parameters = [20, 20, 20, 80]\n"
+    ">>> p_parameters = [0.2, 0.5, 0.8, 0.5]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(p_parameters, n_parameters,\n"
+    "...                            linestyles))\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     p, n, style = parameter_set\n"
+    "...     nbdtrc_vals = nbdtrc(k, n, p)\n"
+    "...     ax.plot(k, nbdtrc_vals, label=rf\"$n={n},\\, p={p}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_xlabel(\"$k$\")\n"
+    ">>> ax.set_title(\"Negative binomial distribution survival function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtrc` directly can be much faster than\n"
+    "calling the ``sf`` method of `scipy.stats.nbinom`, especially for small\n"
+    "arrays or individual values. To get the same results one must use the\n"
+    "following parametrization: ``nbinom(n, p).sf(k)=nbdtrc(k, n, p)``.\n"
+    "\n"
+    ">>> from scipy.stats import nbinom\n"
+    ">>> k, n, p = 3, 5, 0.5\n"
+    ">>> nbdtr_res = nbdtrc(k, n, p)  # this will often be faster than below\n"
+    ">>> stats_res = nbinom(n, p).sf(k)\n"
+    ">>> stats_res, nbdtr_res  # test that results are equal\n"
+    "(0.6367187499999999, 0.6367187499999999)\n"
+    "\n"
+    "`nbdtrc` can evaluate different parameter sets by providing arrays with\n"
+    "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n"
+    "the function for three different `k` at four locations `p`, resulting in\n"
+    "a 3x4 array.\n"
+    "\n"
+    ">>> k = np.array([[5], [10], [15]])\n"
+    ">>> p = np.array([0.3, 0.5, 0.7, 0.9])\n"
+    ">>> k.shape, p.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> nbdtrc(k, 5, p)\n"
+    "array([[8.49731667e-01, 3.76953125e-01, 4.73489874e-02, 1.46902600e-04],\n"
+    "       [5.15491059e-01, 5.92346191e-02, 6.72234070e-04, 9.29610100e-09],\n"
+    "       [2.37507779e-01, 5.90896606e-03, 5.55025308e-06, 3.26346760e-13]])")
+ufunc_nbdtrc_loops[0] = loop_d_ppd__As_ppd_d
+ufunc_nbdtrc_loops[1] = loop_d_ddd__As_fff_f
+ufunc_nbdtrc_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_nbdtrc_types[0] = NPY_INTP
+ufunc_nbdtrc_types[1] = NPY_INTP
+ufunc_nbdtrc_types[2] = NPY_DOUBLE
+ufunc_nbdtrc_types[3] = NPY_DOUBLE
+ufunc_nbdtrc_types[4] = NPY_FLOAT
+ufunc_nbdtrc_types[5] = NPY_FLOAT
+ufunc_nbdtrc_types[6] = NPY_FLOAT
+ufunc_nbdtrc_types[7] = NPY_FLOAT
+ufunc_nbdtrc_types[8] = NPY_DOUBLE
+ufunc_nbdtrc_types[9] = NPY_DOUBLE
+ufunc_nbdtrc_types[10] = NPY_DOUBLE
+ufunc_nbdtrc_types[11] = NPY_DOUBLE
+ufunc_nbdtrc_ptr[2*0] = _func_cephes_nbdtrc_wrap
+ufunc_nbdtrc_ptr[2*0+1] = ("nbdtrc")
+ufunc_nbdtrc_ptr[2*1] = _func_nbdtrc_unsafe
+ufunc_nbdtrc_ptr[2*1+1] = ("nbdtrc")
+ufunc_nbdtrc_ptr[2*2] = _func_nbdtrc_unsafe
+ufunc_nbdtrc_ptr[2*2+1] = ("nbdtrc")
+ufunc_nbdtrc_data[0] = &ufunc_nbdtrc_ptr[2*0]
+ufunc_nbdtrc_data[1] = &ufunc_nbdtrc_ptr[2*1]
+ufunc_nbdtrc_data[2] = &ufunc_nbdtrc_ptr[2*2]
+nbdtrc = np.PyUFunc_FromFuncAndData(ufunc_nbdtrc_loops, ufunc_nbdtrc_data, ufunc_nbdtrc_types, 3, 3, 1, 0, "nbdtrc", ufunc_nbdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtri_loops[3]
+cdef void *ufunc_nbdtri_ptr[6]
+cdef void *ufunc_nbdtri_data[3]
+cdef char ufunc_nbdtri_types[12]
+cdef char *ufunc_nbdtri_doc = (
+    "nbdtri(k, n, y, out=None)\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `p` of\n"
+    "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n"
+    "function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "y : array_like\n"
+    "    The probability of `k` or fewer failures before `n` successes (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "p : scalar or ndarray\n"
+    "    Probability of success in a single event (float) such that\n"
+    "    `nbdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Cumulative distribution function of the negative binomial.\n"
+    "nbdtrc : Negative binomial survival function.\n"
+    "scipy.stats.nbinom : negative binomial distribution.\n"
+    "nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.\n"
+    "nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the Cephes [1]_ routine `nbdtri`.\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. Using `nbdtri` directly can improve performance\n"
+    "compared to the ``ppf`` method of `scipy.stats.nbinom`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`nbdtri` is the inverse of `nbdtr` with respect to `p`.\n"
+    "Up to floating point errors the following holds:\n"
+    "``nbdtri(k, n, nbdtr(k, n, p))=p``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtri, nbdtr\n"
+    ">>> k, n, y = 5, 10, 0.2\n"
+    ">>> cdf_val = nbdtr(k, n, y)\n"
+    ">>> nbdtri(k, n, cdf_val)\n"
+    "0.20000000000000004\n"
+    "\n"
+    "Compute the function for ``k=10`` and ``n=5`` at several points by\n"
+    "providing a NumPy array or list for `y`.\n"
+    "\n"
+    ">>> y = np.array([0.1, 0.4, 0.8])\n"
+    ">>> nbdtri(3, 5, y)\n"
+    "array([0.34462319, 0.51653095, 0.69677416])\n"
+    "\n"
+    "Plot the function for three different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> n_parameters = [5, 20, 30, 30]\n"
+    ">>> k_parameters = [20, 20, 60, 80]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(n_parameters, k_parameters, linestyles))\n"
+    ">>> cdf_vals = np.linspace(0, 1, 1000)\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     n, k, style = parameter_set\n"
+    "...     nbdtri_vals = nbdtri(k, n, cdf_vals)\n"
+    "...     ax.plot(cdf_vals, nbdtri_vals, label=rf\"$k={k},\\ n={n}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_ylabel(\"$p$\")\n"
+    ">>> ax.set_xlabel(\"$CDF$\")\n"
+    ">>> title = \"nbdtri: inverse of negative binomial CDF with respect to $p$\"\n"
+    ">>> ax.set_title(title)\n"
+    ">>> plt.show()\n"
+    "\n"
+    "`nbdtri` can evaluate different parameter sets by providing arrays with\n"
+    "shapes compatible for broadcasting for `k`, `n` and `p`. Here we compute\n"
+    "the function for three different `k` at four locations `p`, resulting in\n"
+    "a 3x4 array.\n"
+    "\n"
+    ">>> k = np.array([[5], [10], [15]])\n"
+    ">>> y = np.array([0.3, 0.5, 0.7, 0.9])\n"
+    ">>> k.shape, y.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> nbdtri(k, 5, y)\n"
+    "array([[0.37258157, 0.45169416, 0.53249956, 0.64578407],\n"
+    "       [0.24588501, 0.30451981, 0.36778453, 0.46397088],\n"
+    "       [0.18362101, 0.22966758, 0.28054743, 0.36066188]])")
+ufunc_nbdtri_loops[0] = loop_d_ppd__As_ppd_d
+ufunc_nbdtri_loops[1] = loop_d_ddd__As_fff_f
+ufunc_nbdtri_loops[2] = loop_d_ddd__As_ddd_d
+ufunc_nbdtri_types[0] = NPY_INTP
+ufunc_nbdtri_types[1] = NPY_INTP
+ufunc_nbdtri_types[2] = NPY_DOUBLE
+ufunc_nbdtri_types[3] = NPY_DOUBLE
+ufunc_nbdtri_types[4] = NPY_FLOAT
+ufunc_nbdtri_types[5] = NPY_FLOAT
+ufunc_nbdtri_types[6] = NPY_FLOAT
+ufunc_nbdtri_types[7] = NPY_FLOAT
+ufunc_nbdtri_types[8] = NPY_DOUBLE
+ufunc_nbdtri_types[9] = NPY_DOUBLE
+ufunc_nbdtri_types[10] = NPY_DOUBLE
+ufunc_nbdtri_types[11] = NPY_DOUBLE
+ufunc_nbdtri_ptr[2*0] = _func_cephes_nbdtri_wrap
+ufunc_nbdtri_ptr[2*0+1] = ("nbdtri")
+ufunc_nbdtri_ptr[2*1] = _func_nbdtri_unsafe
+ufunc_nbdtri_ptr[2*1+1] = ("nbdtri")
+ufunc_nbdtri_ptr[2*2] = _func_nbdtri_unsafe
+ufunc_nbdtri_ptr[2*2+1] = ("nbdtri")
+ufunc_nbdtri_data[0] = &ufunc_nbdtri_ptr[2*0]
+ufunc_nbdtri_data[1] = &ufunc_nbdtri_ptr[2*1]
+ufunc_nbdtri_data[2] = &ufunc_nbdtri_ptr[2*2]
+nbdtri = np.PyUFunc_FromFuncAndData(ufunc_nbdtri_loops, ufunc_nbdtri_data, ufunc_nbdtri_types, 3, 3, 1, 0, "nbdtri", ufunc_nbdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtrik_loops[2]
+cdef void *ufunc_nbdtrik_ptr[4]
+cdef void *ufunc_nbdtrik_data[2]
+cdef char ufunc_nbdtrik_types[8]
+cdef char *ufunc_nbdtrik_doc = (
+    "nbdtrik(y, n, p, out=None)\n"
+    "\n"
+    "Negative binomial percentile function.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `k` of\n"
+    "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n"
+    "function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like\n"
+    "    The probability of `k` or fewer failures before `n` successes (float).\n"
+    "n : array_like\n"
+    "    The target number of successes (positive int).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "k : scalar or ndarray\n"
+    "    The maximum number of allowed failures such that `nbdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Cumulative distribution function of the negative binomial.\n"
+    "nbdtrc : Survival function of the negative binomial.\n"
+    "nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.\n"
+    "nbdtrin : Inverse with respect to `n` of `nbdtr(k, n, p)`.\n"
+    "scipy.stats.nbinom : Negative binomial distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.\n"
+    "\n"
+    "Formula 26.5.26 of [2]_,\n"
+    "\n"
+    ".. math::\n"
+    "    \\sum_{j=k + 1}^\\infty {{n + j - 1}\n"
+    "    \\choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),\n"
+    "\n"
+    "is used to reduce calculation of the cumulative distribution function to\n"
+    "that of a regularized incomplete beta :math:`I`.\n"
+    "\n"
+    "Computation of `k` involves a search for a value that produces the desired\n"
+    "value of `y`.  The search relies on the monotonicity of `y` with `k`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the negative binomial cumulative distribution function for an\n"
+    "exemplary parameter set.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import nbdtr, nbdtrik\n"
+    ">>> k, n, p = 5, 2, 0.5\n"
+    ">>> cdf_value = nbdtr(k, n, p)\n"
+    ">>> cdf_value\n"
+    "0.9375\n"
+    "\n"
+    "Verify that `nbdtrik` recovers the original value for `k`.\n"
+    "\n"
+    ">>> nbdtrik(cdf_value, n, p)\n"
+    "5.0\n"
+    "\n"
+    "Plot the function for different parameter sets.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> p_parameters = [0.2, 0.5, 0.7, 0.5]\n"
+    ">>> n_parameters = [30, 30, 30, 80]\n"
+    ">>> linestyles = ['solid', 'dashed', 'dotted', 'dashdot']\n"
+    ">>> parameters_list = list(zip(p_parameters, n_parameters, linestyles))\n"
+    ">>> cdf_vals = np.linspace(0, 1, 1000)\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> for parameter_set in parameters_list:\n"
+    "...     p, n, style = parameter_set\n"
+    "...     nbdtrik_vals = nbdtrik(cdf_vals, n, p)\n"
+    "...     ax.plot(cdf_vals, nbdtrik_vals, label=rf\"$n={n},\\ p={p}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_ylabel(\"$k$\")\n"
+    ">>> ax.set_xlabel(\"$CDF$\")\n"
+    ">>> ax.set_title(\"Negative binomial percentile function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The negative binomial distribution is also available as\n"
+    "`scipy.stats.nbinom`. The percentile function  method ``ppf``\n"
+    "returns the result of `nbdtrik` rounded up to integers:\n"
+    "\n"
+    ">>> from scipy.stats import nbinom\n"
+    ">>> q, n, p = 0.6, 5, 0.5\n"
+    ">>> nbinom.ppf(q, n, p), nbdtrik(q, n, p)\n"
+    "(5.0, 4.800428460273882)")
+ufunc_nbdtrik_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nbdtrik_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nbdtrik_types[0] = NPY_FLOAT
+ufunc_nbdtrik_types[1] = NPY_FLOAT
+ufunc_nbdtrik_types[2] = NPY_FLOAT
+ufunc_nbdtrik_types[3] = NPY_FLOAT
+ufunc_nbdtrik_types[4] = NPY_DOUBLE
+ufunc_nbdtrik_types[5] = NPY_DOUBLE
+ufunc_nbdtrik_types[6] = NPY_DOUBLE
+ufunc_nbdtrik_types[7] = NPY_DOUBLE
+ufunc_nbdtrik_ptr[2*0] = _func_nbdtrik
+ufunc_nbdtrik_ptr[2*0+1] = ("nbdtrik")
+ufunc_nbdtrik_ptr[2*1] = _func_nbdtrik
+ufunc_nbdtrik_ptr[2*1+1] = ("nbdtrik")
+ufunc_nbdtrik_data[0] = &ufunc_nbdtrik_ptr[2*0]
+ufunc_nbdtrik_data[1] = &ufunc_nbdtrik_ptr[2*1]
+nbdtrik = np.PyUFunc_FromFuncAndData(ufunc_nbdtrik_loops, ufunc_nbdtrik_data, ufunc_nbdtrik_types, 2, 3, 1, 0, "nbdtrik", ufunc_nbdtrik_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nbdtrin_loops[2]
+cdef void *ufunc_nbdtrin_ptr[4]
+cdef void *ufunc_nbdtrin_data[2]
+cdef char ufunc_nbdtrin_types[8]
+cdef char *ufunc_nbdtrin_doc = (
+    "nbdtrin(k, y, p, out=None)\n"
+    "\n"
+    "Inverse of `nbdtr` vs `n`.\n"
+    "\n"
+    "Returns the inverse with respect to the parameter `n` of\n"
+    "``y = nbdtr(k, n, p)``, the negative binomial cumulative distribution\n"
+    "function.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    The maximum number of allowed failures (nonnegative int).\n"
+    "y : array_like\n"
+    "    The probability of `k` or fewer failures before `n` successes (float).\n"
+    "p : array_like\n"
+    "    Probability of success in a single event (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "n : scalar or ndarray\n"
+    "    The number of successes `n` such that `nbdtr(k, n, p) = y`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nbdtr : Cumulative distribution function of the negative binomial.\n"
+    "nbdtri : Inverse with respect to `p` of `nbdtr(k, n, p)`.\n"
+    "nbdtrik : Inverse with respect to `k` of `nbdtr(k, n, p)`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the CDFLIB [1]_ Fortran routine `cdfnbn`.\n"
+    "\n"
+    "Formula 26.5.26 of [2]_,\n"
+    "\n"
+    ".. math::\n"
+    "    \\sum_{j=k + 1}^\\infty {{n + j - 1}\n"
+    "    \\choose{j}} p^n (1 - p)^j = I_{1 - p}(k + 1, n),\n"
+    "\n"
+    "is used to reduce calculation of the cumulative distribution function to\n"
+    "that of a regularized incomplete beta :math:`I`.\n"
+    "\n"
+    "Computation of `n` involves a search for a value that produces the desired\n"
+    "value of `y`.  The search relies on the monotonicity of `y` with `n`.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Barry Brown, James Lovato, and Kathy Russell,\n"
+    "       CDFLIB: Library of Fortran Routines for Cumulative Distribution\n"
+    "       Functions, Inverses, and Other Parameters.\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the negative binomial cumulative distribution function for an\n"
+    "exemplary parameter set.\n"
+    "\n"
+    ">>> from scipy.special import nbdtr, nbdtrin\n"
+    ">>> k, n, p = 5, 2, 0.5\n"
+    ">>> cdf_value = nbdtr(k, n, p)\n"
+    ">>> cdf_value\n"
+    "0.9375\n"
+    "\n"
+    "Verify that `nbdtrin` recovers the original value for `n` up to floating\n"
+    "point accuracy.\n"
+    "\n"
+    ">>> nbdtrin(k, cdf_value, p)\n"
+    "1.999999999998137")
+ufunc_nbdtrin_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nbdtrin_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nbdtrin_types[0] = NPY_FLOAT
+ufunc_nbdtrin_types[1] = NPY_FLOAT
+ufunc_nbdtrin_types[2] = NPY_FLOAT
+ufunc_nbdtrin_types[3] = NPY_FLOAT
+ufunc_nbdtrin_types[4] = NPY_DOUBLE
+ufunc_nbdtrin_types[5] = NPY_DOUBLE
+ufunc_nbdtrin_types[6] = NPY_DOUBLE
+ufunc_nbdtrin_types[7] = NPY_DOUBLE
+ufunc_nbdtrin_ptr[2*0] = _func_nbdtrin
+ufunc_nbdtrin_ptr[2*0+1] = ("nbdtrin")
+ufunc_nbdtrin_ptr[2*1] = _func_nbdtrin
+ufunc_nbdtrin_ptr[2*1+1] = ("nbdtrin")
+ufunc_nbdtrin_data[0] = &ufunc_nbdtrin_ptr[2*0]
+ufunc_nbdtrin_data[1] = &ufunc_nbdtrin_ptr[2*1]
+nbdtrin = np.PyUFunc_FromFuncAndData(ufunc_nbdtrin_loops, ufunc_nbdtrin_data, ufunc_nbdtrin_types, 2, 3, 1, 0, "nbdtrin", ufunc_nbdtrin_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtr_loops[2]
+cdef void *ufunc_ncfdtr_ptr[4]
+cdef void *ufunc_ncfdtr_data[2]
+cdef char ufunc_ncfdtr_types[10]
+cdef char *ufunc_ncfdtr_doc = (
+    "ncfdtr(dfn, dfd, nc, f, out=None)\n"
+    "\n"
+    "Cumulative distribution function of the non-central F distribution.\n"
+    "\n"
+    "The non-central F describes the distribution of,\n"
+    "\n"
+    ".. math::\n"
+    "    Z = \\frac{X/d_n}{Y/d_d}\n"
+    "\n"
+    "where :math:`X` and :math:`Y` are independently distributed, with\n"
+    ":math:`X` distributed non-central :math:`\\chi^2` with noncentrality\n"
+    "parameter `nc` and :math:`d_n` degrees of freedom, and :math:`Y`\n"
+    "distributed :math:`\\chi^2` with :math:`d_d` degrees of freedom.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares.  Range (0, inf).\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares.  Range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Range [0, inf).\n"
+    "f : array_like\n"
+    "    Quantiles, i.e. the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "cdf : scalar or ndarray\n"
+    "    The calculated CDF.  If all inputs are scalar, the return will be a\n"
+    "    float.  Otherwise it will be an array.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "scipy.stats.ncf : Non-central F distribution.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function calculates the CDF of the non-central f distribution using\n"
+    "the Boost Math C++ library [1]_.\n"
+    "\n"
+    "The cumulative distribution function is computed using Formula 26.6.20 of\n"
+    "[2]_:\n"
+    "\n"
+    ".. math::\n"
+    "    F(d_n, d_d, n_c, f) = \\sum_{j=0}^\\infty e^{-n_c/2}\n"
+    "    \\frac{(n_c/2)^j}{j!} I_{x}(\\frac{d_n}{2} + j, \\frac{d_d}{2}),\n"
+    "\n"
+    "where :math:`I` is the regularized incomplete beta function, and\n"
+    ":math:`x = f d_n/(f d_n + d_d)`.\n"
+    "\n"
+    "Note that argument order of `ncfdtr` is different from that of the\n"
+    "similar ``cdf`` method of `scipy.stats.ncf`: `f` is the last\n"
+    "parameter of `ncfdtr` but the first parameter of ``scipy.stats.ncf.cdf``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    ".. [2] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> from scipy import stats\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Plot the CDF of the non-central F distribution, for nc=0.  Compare with the\n"
+    "F-distribution from scipy.stats:\n"
+    "\n"
+    ">>> x = np.linspace(-1, 8, num=500)\n"
+    ">>> dfn = 3\n"
+    ">>> dfd = 2\n"
+    ">>> ncf_stats = stats.f.cdf(x, dfn, dfd)\n"
+    ">>> ncf_special = special.ncfdtr(dfn, dfd, 0, x)\n"
+    "\n"
+    ">>> fig = plt.figure()\n"
+    ">>> ax = fig.add_subplot(111)\n"
+    ">>> ax.plot(x, ncf_stats, 'b-', lw=3)\n"
+    ">>> ax.plot(x, ncf_special, 'r-')\n"
+    ">>> plt.show()")
+ufunc_ncfdtr_loops[0] = loop_f_ffff__As_ffff_f
+ufunc_ncfdtr_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtr_types[0] = NPY_FLOAT
+ufunc_ncfdtr_types[1] = NPY_FLOAT
+ufunc_ncfdtr_types[2] = NPY_FLOAT
+ufunc_ncfdtr_types[3] = NPY_FLOAT
+ufunc_ncfdtr_types[4] = NPY_FLOAT
+ufunc_ncfdtr_types[5] = NPY_DOUBLE
+ufunc_ncfdtr_types[6] = NPY_DOUBLE
+ufunc_ncfdtr_types[7] = NPY_DOUBLE
+ufunc_ncfdtr_types[8] = NPY_DOUBLE
+ufunc_ncfdtr_types[9] = NPY_DOUBLE
+ufunc_ncfdtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_cdf_float
+ufunc_ncfdtr_ptr[2*0+1] = ("ncfdtr")
+ufunc_ncfdtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_cdf_double
+ufunc_ncfdtr_ptr[2*1+1] = ("ncfdtr")
+ufunc_ncfdtr_data[0] = &ufunc_ncfdtr_ptr[2*0]
+ufunc_ncfdtr_data[1] = &ufunc_ncfdtr_ptr[2*1]
+ncfdtr = np.PyUFunc_FromFuncAndData(ufunc_ncfdtr_loops, ufunc_ncfdtr_data, ufunc_ncfdtr_types, 2, 4, 1, 0, "ncfdtr", ufunc_ncfdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtri_loops[2]
+cdef void *ufunc_ncfdtri_ptr[4]
+cdef void *ufunc_ncfdtri_data[2]
+cdef char ufunc_ncfdtri_types[10]
+cdef char *ufunc_ncfdtri_doc = (
+    "ncfdtri(dfn, dfd, nc, p, out=None)\n"
+    "\n"
+    "Inverse with respect to `f` of the CDF of the non-central F distribution.\n"
+    "\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares.  Range (0, inf).\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares.  Range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Range [0, inf).\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function.  Must be in the\n"
+    "    range [0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "f : scalar or ndarray\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "scipy.stats.ncf : Non-central F distribution.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function calculates the Quantile of the non-central f distribution\n"
+    "using the Boost Math C++ library [1]_.\n"
+    "\n"
+    "Note that argument order of `ncfdtri` is different from that of the\n"
+    "similar ``ppf`` method of `scipy.stats.ncf`. `p` is the last parameter\n"
+    "of `ncfdtri` but the first parameter of ``scipy.stats.ncf.ppf``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtri\n"
+    "\n"
+    "Compute the CDF for several values of `f`:\n"
+    "\n"
+    ">>> f = [0.5, 1, 1.5]\n"
+    ">>> p = ncfdtr(2, 3, 1.5, f)\n"
+    ">>> p\n"
+    "array([ 0.20782291,  0.36107392,  0.47345752])\n"
+    "\n"
+    "Compute the inverse.  We recover the values of `f`, as expected:\n"
+    "\n"
+    ">>> ncfdtri(2, 3, 1.5, p)\n"
+    "array([ 0.5,  1. ,  1.5])")
+ufunc_ncfdtri_loops[0] = loop_f_ffff__As_ffff_f
+ufunc_ncfdtri_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtri_types[0] = NPY_FLOAT
+ufunc_ncfdtri_types[1] = NPY_FLOAT
+ufunc_ncfdtri_types[2] = NPY_FLOAT
+ufunc_ncfdtri_types[3] = NPY_FLOAT
+ufunc_ncfdtri_types[4] = NPY_FLOAT
+ufunc_ncfdtri_types[5] = NPY_DOUBLE
+ufunc_ncfdtri_types[6] = NPY_DOUBLE
+ufunc_ncfdtri_types[7] = NPY_DOUBLE
+ufunc_ncfdtri_types[8] = NPY_DOUBLE
+ufunc_ncfdtri_types[9] = NPY_DOUBLE
+ufunc_ncfdtri_ptr[2*0] = scipy.special._ufuncs_cxx._export_ncf_ppf_float
+ufunc_ncfdtri_ptr[2*0+1] = ("ncfdtri")
+ufunc_ncfdtri_ptr[2*1] = scipy.special._ufuncs_cxx._export_ncf_ppf_double
+ufunc_ncfdtri_ptr[2*1+1] = ("ncfdtri")
+ufunc_ncfdtri_data[0] = &ufunc_ncfdtri_ptr[2*0]
+ufunc_ncfdtri_data[1] = &ufunc_ncfdtri_ptr[2*1]
+ncfdtri = np.PyUFunc_FromFuncAndData(ufunc_ncfdtri_loops, ufunc_ncfdtri_data, ufunc_ncfdtri_types, 2, 4, 1, 0, "ncfdtri", ufunc_ncfdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtridfd_loops[2]
+cdef void *ufunc_ncfdtridfd_ptr[4]
+cdef void *ufunc_ncfdtridfd_data[2]
+cdef char ufunc_ncfdtridfd_types[10]
+cdef char *ufunc_ncfdtridfd_doc = (
+    "ncfdtridfd(dfn, p, nc, f, out=None)\n"
+    "\n"
+    "Calculate degrees of freedom (denominator) for the noncentral F-distribution.\n"
+    "\n"
+    "This is the inverse with respect to `dfd` of `ncfdtr`.\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares.  Range (0, inf).\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function.  Must be in the\n"
+    "    range [0, 1].\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Should be in range (0, 1e4).\n"
+    "f : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "dfd : scalar or ndarray\n"
+    "    Degrees of freedom of the denominator sum of squares.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The value of the cumulative noncentral F distribution is not necessarily\n"
+    "monotone in either degrees of freedom. There thus may be two values that\n"
+    "provide a given CDF value. This routine assumes monotonicity and will\n"
+    "find an arbitrary one of the two values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtridfd\n"
+    "\n"
+    "Compute the CDF for several values of `dfd`:\n"
+    "\n"
+    ">>> dfd = [1, 2, 3]\n"
+    ">>> p = ncfdtr(2, dfd, 0.25, 15)\n"
+    ">>> p\n"
+    "array([ 0.8097138 ,  0.93020416,  0.96787852])\n"
+    "\n"
+    "Compute the inverse.  We recover the values of `dfd`, as expected:\n"
+    "\n"
+    ">>> ncfdtridfd(2, p, 0.25, 15)\n"
+    "array([ 1.,  2.,  3.])")
+ufunc_ncfdtridfd_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_ncfdtridfd_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtridfd_types[0] = NPY_FLOAT
+ufunc_ncfdtridfd_types[1] = NPY_FLOAT
+ufunc_ncfdtridfd_types[2] = NPY_FLOAT
+ufunc_ncfdtridfd_types[3] = NPY_FLOAT
+ufunc_ncfdtridfd_types[4] = NPY_FLOAT
+ufunc_ncfdtridfd_types[5] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[6] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[7] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[8] = NPY_DOUBLE
+ufunc_ncfdtridfd_types[9] = NPY_DOUBLE
+ufunc_ncfdtridfd_ptr[2*0] = _func_ncfdtridfd
+ufunc_ncfdtridfd_ptr[2*0+1] = ("ncfdtridfd")
+ufunc_ncfdtridfd_ptr[2*1] = _func_ncfdtridfd
+ufunc_ncfdtridfd_ptr[2*1+1] = ("ncfdtridfd")
+ufunc_ncfdtridfd_data[0] = &ufunc_ncfdtridfd_ptr[2*0]
+ufunc_ncfdtridfd_data[1] = &ufunc_ncfdtridfd_ptr[2*1]
+ncfdtridfd = np.PyUFunc_FromFuncAndData(ufunc_ncfdtridfd_loops, ufunc_ncfdtridfd_data, ufunc_ncfdtridfd_types, 2, 4, 1, 0, "ncfdtridfd", ufunc_ncfdtridfd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtridfn_loops[2]
+cdef void *ufunc_ncfdtridfn_ptr[4]
+cdef void *ufunc_ncfdtridfn_data[2]
+cdef char ufunc_ncfdtridfn_types[10]
+cdef char *ufunc_ncfdtridfn_doc = (
+    "ncfdtridfn(p, dfd, nc, f, out=None)\n"
+    "\n"
+    "Calculate degrees of freedom (numerator) for the noncentral F-distribution.\n"
+    "\n"
+    "This is the inverse with respect to `dfn` of `ncfdtr`.\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function. Must be in the\n"
+    "    range [0, 1].\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares. Range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.  Should be in range (0, 1e4).\n"
+    "f : float\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "dfn : scalar or ndarray\n"
+    "    Degrees of freedom of the numerator sum of squares.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtrinc : Inverse of `ncfdtr` with respect to `nc`.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The value of the cumulative noncentral F distribution is not necessarily\n"
+    "monotone in either degrees of freedom. There thus may be two values that\n"
+    "provide a given CDF value. This routine assumes monotonicity and will\n"
+    "find an arbitrary one of the two values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtridfn\n"
+    "\n"
+    "Compute the CDF for several values of `dfn`:\n"
+    "\n"
+    ">>> dfn = [1, 2, 3]\n"
+    ">>> p = ncfdtr(dfn, 2, 0.25, 15)\n"
+    ">>> p\n"
+    "array([ 0.92562363,  0.93020416,  0.93188394])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `dfn`, as expected:\n"
+    "\n"
+    ">>> ncfdtridfn(p, 2, 0.25, 15)\n"
+    "array([ 1.,  2.,  3.])")
+ufunc_ncfdtridfn_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_ncfdtridfn_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtridfn_types[0] = NPY_FLOAT
+ufunc_ncfdtridfn_types[1] = NPY_FLOAT
+ufunc_ncfdtridfn_types[2] = NPY_FLOAT
+ufunc_ncfdtridfn_types[3] = NPY_FLOAT
+ufunc_ncfdtridfn_types[4] = NPY_FLOAT
+ufunc_ncfdtridfn_types[5] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[6] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[7] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[8] = NPY_DOUBLE
+ufunc_ncfdtridfn_types[9] = NPY_DOUBLE
+ufunc_ncfdtridfn_ptr[2*0] = _func_ncfdtridfn
+ufunc_ncfdtridfn_ptr[2*0+1] = ("ncfdtridfn")
+ufunc_ncfdtridfn_ptr[2*1] = _func_ncfdtridfn
+ufunc_ncfdtridfn_ptr[2*1+1] = ("ncfdtridfn")
+ufunc_ncfdtridfn_data[0] = &ufunc_ncfdtridfn_ptr[2*0]
+ufunc_ncfdtridfn_data[1] = &ufunc_ncfdtridfn_ptr[2*1]
+ncfdtridfn = np.PyUFunc_FromFuncAndData(ufunc_ncfdtridfn_loops, ufunc_ncfdtridfn_data, ufunc_ncfdtridfn_types, 2, 4, 1, 0, "ncfdtridfn", ufunc_ncfdtridfn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ncfdtrinc_loops[2]
+cdef void *ufunc_ncfdtrinc_ptr[4]
+cdef void *ufunc_ncfdtrinc_data[2]
+cdef char ufunc_ncfdtrinc_types[10]
+cdef char *ufunc_ncfdtrinc_doc = (
+    "ncfdtrinc(dfn, dfd, p, f, out=None)\n"
+    "\n"
+    "Calculate non-centrality parameter for non-central F distribution.\n"
+    "\n"
+    "This is the inverse with respect to `nc` of `ncfdtr`.\n"
+    "See `ncfdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "dfn : array_like\n"
+    "    Degrees of freedom of the numerator sum of squares. Range (0, inf).\n"
+    "dfd : array_like\n"
+    "    Degrees of freedom of the denominator sum of squares. Range (0, inf).\n"
+    "p : array_like\n"
+    "    Value of the cumulative distribution function. Must be in the\n"
+    "    range [0, 1].\n"
+    "f : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "nc : scalar or ndarray\n"
+    "    Noncentrality parameter.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ncfdtr : CDF of the non-central F distribution.\n"
+    "ncfdtri : Quantile function; inverse of `ncfdtr` with respect to `f`.\n"
+    "ncfdtridfd : Inverse of `ncfdtr` with respect to `dfd`.\n"
+    "ncfdtridfn : Inverse of `ncfdtr` with respect to `dfn`.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import ncfdtr, ncfdtrinc\n"
+    "\n"
+    "Compute the CDF for several values of `nc`:\n"
+    "\n"
+    ">>> nc = [0.5, 1.5, 2.0]\n"
+    ">>> p = ncfdtr(2, 3, nc, 15)\n"
+    ">>> p\n"
+    "array([ 0.96309246,  0.94327955,  0.93304098])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `nc`, as expected:\n"
+    "\n"
+    ">>> ncfdtrinc(2, 3, p, 15)\n"
+    "array([ 0.5,  1.5,  2. ])")
+ufunc_ncfdtrinc_loops[0] = loop_d_dddd__As_ffff_f
+ufunc_ncfdtrinc_loops[1] = loop_d_dddd__As_dddd_d
+ufunc_ncfdtrinc_types[0] = NPY_FLOAT
+ufunc_ncfdtrinc_types[1] = NPY_FLOAT
+ufunc_ncfdtrinc_types[2] = NPY_FLOAT
+ufunc_ncfdtrinc_types[3] = NPY_FLOAT
+ufunc_ncfdtrinc_types[4] = NPY_FLOAT
+ufunc_ncfdtrinc_types[5] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[6] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[7] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[8] = NPY_DOUBLE
+ufunc_ncfdtrinc_types[9] = NPY_DOUBLE
+ufunc_ncfdtrinc_ptr[2*0] = _func_ncfdtrinc
+ufunc_ncfdtrinc_ptr[2*0+1] = ("ncfdtrinc")
+ufunc_ncfdtrinc_ptr[2*1] = _func_ncfdtrinc
+ufunc_ncfdtrinc_ptr[2*1+1] = ("ncfdtrinc")
+ufunc_ncfdtrinc_data[0] = &ufunc_ncfdtrinc_ptr[2*0]
+ufunc_ncfdtrinc_data[1] = &ufunc_ncfdtrinc_ptr[2*1]
+ncfdtrinc = np.PyUFunc_FromFuncAndData(ufunc_ncfdtrinc_loops, ufunc_ncfdtrinc_data, ufunc_ncfdtrinc_types, 2, 4, 1, 0, "ncfdtrinc", ufunc_ncfdtrinc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtr_loops[2]
+cdef void *ufunc_nctdtr_ptr[4]
+cdef void *ufunc_nctdtr_data[2]
+cdef char ufunc_nctdtr_types[8]
+cdef char *ufunc_nctdtr_doc = (
+    "nctdtr(df, nc, t, out=None)\n"
+    "\n"
+    "Cumulative distribution function of the non-central `t` distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom of the distribution. Should be in range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter.\n"
+    "t : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "cdf : scalar or ndarray\n"
+    "    The calculated CDF. If all inputs are scalar, the return will be a\n"
+    "    float. Otherwise, it will be an array.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n"
+    "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n"
+    "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "This function calculates the CDF of the non-central t distribution using\n"
+    "the Boost Math C++ library [1]_.\n"
+    "\n"
+    "Note that the argument order of `nctdtr` is different from that of the\n"
+    "similar ``cdf`` method of `scipy.stats.nct`: `t` is the last\n"
+    "parameter of `nctdtr` but the first parameter of ``scipy.stats.nct.cdf``.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> from scipy import stats\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Plot the CDF of the non-central t distribution, for nc=0. Compare with the\n"
+    "t-distribution from scipy.stats:\n"
+    "\n"
+    ">>> x = np.linspace(-5, 5, num=500)\n"
+    ">>> df = 3\n"
+    ">>> nct_stats = stats.t.cdf(x, df)\n"
+    ">>> nct_special = special.nctdtr(df, 0, x)\n"
+    "\n"
+    ">>> fig = plt.figure()\n"
+    ">>> ax = fig.add_subplot(111)\n"
+    ">>> ax.plot(x, nct_stats, 'b-', lw=3)\n"
+    ">>> ax.plot(x, nct_special, 'r-')\n"
+    ">>> plt.show()")
+ufunc_nctdtr_loops[0] = loop_f_fff__As_fff_f
+ufunc_nctdtr_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtr_types[0] = NPY_FLOAT
+ufunc_nctdtr_types[1] = NPY_FLOAT
+ufunc_nctdtr_types[2] = NPY_FLOAT
+ufunc_nctdtr_types[3] = NPY_FLOAT
+ufunc_nctdtr_types[4] = NPY_DOUBLE
+ufunc_nctdtr_types[5] = NPY_DOUBLE
+ufunc_nctdtr_types[6] = NPY_DOUBLE
+ufunc_nctdtr_types[7] = NPY_DOUBLE
+ufunc_nctdtr_ptr[2*0] = scipy.special._ufuncs_cxx._export_nct_cdf_float
+ufunc_nctdtr_ptr[2*0+1] = ("nctdtr")
+ufunc_nctdtr_ptr[2*1] = scipy.special._ufuncs_cxx._export_nct_cdf_double
+ufunc_nctdtr_ptr[2*1+1] = ("nctdtr")
+ufunc_nctdtr_data[0] = &ufunc_nctdtr_ptr[2*0]
+ufunc_nctdtr_data[1] = &ufunc_nctdtr_ptr[2*1]
+nctdtr = np.PyUFunc_FromFuncAndData(ufunc_nctdtr_loops, ufunc_nctdtr_data, ufunc_nctdtr_types, 2, 3, 1, 0, "nctdtr", ufunc_nctdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtridf_loops[2]
+cdef void *ufunc_nctdtridf_ptr[4]
+cdef void *ufunc_nctdtridf_data[2]
+cdef char ufunc_nctdtridf_types[8]
+cdef char *ufunc_nctdtridf_doc = (
+    "nctdtridf(p, nc, t, out=None)\n"
+    "\n"
+    "Calculate degrees of freedom for non-central t distribution.\n"
+    "\n"
+    "See `nctdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter. Should be in range (-1e6, 1e6).\n"
+    "t : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "df : scalar or ndarray\n"
+    "    The degrees of freedom. If all inputs are scalar, the return will be a\n"
+    "    float. Otherwise, it will be an array.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtr :  CDF of the non-central `t` distribution.\n"
+    "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n"
+    "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import nctdtr, nctdtridf\n"
+    "\n"
+    "Compute the CDF for several values of `df`:\n"
+    "\n"
+    ">>> df = [1, 2, 3]\n"
+    ">>> p = nctdtr(df, 0.25, 1)\n"
+    ">>> p\n"
+    "array([0.67491974, 0.716464  , 0.73349456])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `df`, as expected:\n"
+    "\n"
+    ">>> nctdtridf(p, 0.25, 1)\n"
+    "array([1., 2., 3.])")
+ufunc_nctdtridf_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nctdtridf_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtridf_types[0] = NPY_FLOAT
+ufunc_nctdtridf_types[1] = NPY_FLOAT
+ufunc_nctdtridf_types[2] = NPY_FLOAT
+ufunc_nctdtridf_types[3] = NPY_FLOAT
+ufunc_nctdtridf_types[4] = NPY_DOUBLE
+ufunc_nctdtridf_types[5] = NPY_DOUBLE
+ufunc_nctdtridf_types[6] = NPY_DOUBLE
+ufunc_nctdtridf_types[7] = NPY_DOUBLE
+ufunc_nctdtridf_ptr[2*0] = _func_nctdtridf
+ufunc_nctdtridf_ptr[2*0+1] = ("nctdtridf")
+ufunc_nctdtridf_ptr[2*1] = _func_nctdtridf
+ufunc_nctdtridf_ptr[2*1+1] = ("nctdtridf")
+ufunc_nctdtridf_data[0] = &ufunc_nctdtridf_ptr[2*0]
+ufunc_nctdtridf_data[1] = &ufunc_nctdtridf_ptr[2*1]
+nctdtridf = np.PyUFunc_FromFuncAndData(ufunc_nctdtridf_loops, ufunc_nctdtridf_data, ufunc_nctdtridf_types, 2, 3, 1, 0, "nctdtridf", ufunc_nctdtridf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtrinc_loops[2]
+cdef void *ufunc_nctdtrinc_ptr[4]
+cdef void *ufunc_nctdtrinc_data[2]
+cdef char ufunc_nctdtrinc_types[8]
+cdef char *ufunc_nctdtrinc_doc = (
+    "nctdtrinc(df, p, t, out=None)\n"
+    "\n"
+    "Calculate non-centrality parameter for non-central t distribution.\n"
+    "\n"
+    "See `nctdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom of the distribution. Should be in range (0, inf).\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "t : array_like\n"
+    "    Quantiles, i.e., the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "nc : scalar or ndarray\n"
+    "    Noncentrality parameter\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtr :  CDF of the non-central `t` distribution.\n"
+    "nctdtrit : Inverse CDF (iCDF) of the non-central t distribution.\n"
+    "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import nctdtr, nctdtrinc\n"
+    "\n"
+    "Compute the CDF for several values of `nc`:\n"
+    "\n"
+    ">>> nc = [0.5, 1.5, 2.5]\n"
+    ">>> p = nctdtr(3, nc, 1.5)\n"
+    ">>> p\n"
+    "array([0.77569497, 0.45524533, 0.1668691 ])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `nc`, as expected:\n"
+    "\n"
+    ">>> nctdtrinc(3, p, 1.5)\n"
+    "array([0.5, 1.5, 2.5])")
+ufunc_nctdtrinc_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nctdtrinc_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtrinc_types[0] = NPY_FLOAT
+ufunc_nctdtrinc_types[1] = NPY_FLOAT
+ufunc_nctdtrinc_types[2] = NPY_FLOAT
+ufunc_nctdtrinc_types[3] = NPY_FLOAT
+ufunc_nctdtrinc_types[4] = NPY_DOUBLE
+ufunc_nctdtrinc_types[5] = NPY_DOUBLE
+ufunc_nctdtrinc_types[6] = NPY_DOUBLE
+ufunc_nctdtrinc_types[7] = NPY_DOUBLE
+ufunc_nctdtrinc_ptr[2*0] = _func_nctdtrinc
+ufunc_nctdtrinc_ptr[2*0+1] = ("nctdtrinc")
+ufunc_nctdtrinc_ptr[2*1] = _func_nctdtrinc
+ufunc_nctdtrinc_ptr[2*1+1] = ("nctdtrinc")
+ufunc_nctdtrinc_data[0] = &ufunc_nctdtrinc_ptr[2*0]
+ufunc_nctdtrinc_data[1] = &ufunc_nctdtrinc_ptr[2*1]
+nctdtrinc = np.PyUFunc_FromFuncAndData(ufunc_nctdtrinc_loops, ufunc_nctdtrinc_data, ufunc_nctdtrinc_types, 2, 3, 1, 0, "nctdtrinc", ufunc_nctdtrinc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nctdtrit_loops[2]
+cdef void *ufunc_nctdtrit_ptr[4]
+cdef void *ufunc_nctdtrit_data[2]
+cdef char ufunc_nctdtrit_types[8]
+cdef char *ufunc_nctdtrit_doc = (
+    "nctdtrit(df, nc, p, out=None)\n"
+    "\n"
+    "Inverse cumulative distribution function of the non-central t distribution.\n"
+    "\n"
+    "See `nctdtr` for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom of the distribution. Should be in range (0, inf).\n"
+    "nc : array_like\n"
+    "    Noncentrality parameter. Should be in range (-1e6, 1e6).\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "t : scalar or ndarray\n"
+    "    Quantiles\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "nctdtr :  CDF of the non-central `t` distribution.\n"
+    "nctdtridf : Calculate degrees of freedom, given CDF and iCDF values.\n"
+    "nctdtrinc : Calculate non-centrality parameter, given CDF iCDF values.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import nctdtr, nctdtrit\n"
+    "\n"
+    "Compute the CDF for several values of `t`:\n"
+    "\n"
+    ">>> t = [0.5, 1, 1.5]\n"
+    ">>> p = nctdtr(3, 1, t)\n"
+    ">>> p\n"
+    "array([0.29811049, 0.46922687, 0.6257559 ])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `t`, as expected:\n"
+    "\n"
+    ">>> nctdtrit(3, 1, p)\n"
+    "array([0.5, 1. , 1.5])")
+ufunc_nctdtrit_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nctdtrit_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nctdtrit_types[0] = NPY_FLOAT
+ufunc_nctdtrit_types[1] = NPY_FLOAT
+ufunc_nctdtrit_types[2] = NPY_FLOAT
+ufunc_nctdtrit_types[3] = NPY_FLOAT
+ufunc_nctdtrit_types[4] = NPY_DOUBLE
+ufunc_nctdtrit_types[5] = NPY_DOUBLE
+ufunc_nctdtrit_types[6] = NPY_DOUBLE
+ufunc_nctdtrit_types[7] = NPY_DOUBLE
+ufunc_nctdtrit_ptr[2*0] = _func_nctdtrit
+ufunc_nctdtrit_ptr[2*0+1] = ("nctdtrit")
+ufunc_nctdtrit_ptr[2*1] = _func_nctdtrit
+ufunc_nctdtrit_ptr[2*1+1] = ("nctdtrit")
+ufunc_nctdtrit_data[0] = &ufunc_nctdtrit_ptr[2*0]
+ufunc_nctdtrit_data[1] = &ufunc_nctdtrit_ptr[2*1]
+nctdtrit = np.PyUFunc_FromFuncAndData(ufunc_nctdtrit_loops, ufunc_nctdtrit_data, ufunc_nctdtrit_types, 2, 3, 1, 0, "nctdtrit", ufunc_nctdtrit_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ndtr_loops[4]
+cdef void *ufunc_ndtr_ptr[8]
+cdef void *ufunc_ndtr_data[4]
+cdef char ufunc_ndtr_types[8]
+cdef char *ufunc_ndtr_doc = (
+    "ndtr(x, out=None)\n"
+    "\n"
+    "Cumulative distribution of the standard normal distribution.\n"
+    "\n"
+    "Returns the area under the standard Gaussian probability\n"
+    "density function, integrated from minus infinity to `x`\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   \\frac{1}{\\sqrt{2\\pi}} \\int_{-\\infty}^x \\exp(-t^2/2) dt\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like, real or complex\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value of the normal CDF evaluated at `x`\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "log_ndtr : Logarithm of ndtr\n"
+    "ndtri : Inverse of ndtr, standard normal percentile function\n"
+    "erf : Error function\n"
+    "erfc : 1 - erf\n"
+    "scipy.stats.norm : Normal distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Evaluate `ndtr` at one point.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import ndtr\n"
+    ">>> ndtr(0.5)\n"
+    "0.6914624612740131\n"
+    "\n"
+    "Evaluate the function at several points by providing a NumPy array\n"
+    "or list for `x`.\n"
+    "\n"
+    ">>> ndtr([0, 0.5, 2])\n"
+    "array([0.5       , 0.69146246, 0.97724987])\n"
+    "\n"
+    "Plot the function.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(-5, 5, 100)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, ndtr(x))\n"
+    ">>> ax.set_title(r\"Standard normal cumulative distribution function $\\Phi$\")\n"
+    ">>> plt.show()")
+ufunc_ndtr_loops[0] = loop_d_d__As_f_f
+ufunc_ndtr_loops[1] = loop_d_d__As_d_d
+ufunc_ndtr_loops[2] = loop_D_D__As_F_F
+ufunc_ndtr_loops[3] = loop_D_D__As_D_D
+ufunc_ndtr_types[0] = NPY_FLOAT
+ufunc_ndtr_types[1] = NPY_FLOAT
+ufunc_ndtr_types[2] = NPY_DOUBLE
+ufunc_ndtr_types[3] = NPY_DOUBLE
+ufunc_ndtr_types[4] = NPY_CFLOAT
+ufunc_ndtr_types[5] = NPY_CFLOAT
+ufunc_ndtr_types[6] = NPY_CDOUBLE
+ufunc_ndtr_types[7] = NPY_CDOUBLE
+ufunc_ndtr_ptr[2*0] = _func_xsf_ndtr
+ufunc_ndtr_ptr[2*0+1] = ("ndtr")
+ufunc_ndtr_ptr[2*1] = _func_xsf_ndtr
+ufunc_ndtr_ptr[2*1+1] = ("ndtr")
+ufunc_ndtr_ptr[2*2] = scipy.special._ufuncs_cxx._export_faddeeva_ndtr
+ufunc_ndtr_ptr[2*2+1] = ("ndtr")
+ufunc_ndtr_ptr[2*3] = scipy.special._ufuncs_cxx._export_faddeeva_ndtr
+ufunc_ndtr_ptr[2*3+1] = ("ndtr")
+ufunc_ndtr_data[0] = &ufunc_ndtr_ptr[2*0]
+ufunc_ndtr_data[1] = &ufunc_ndtr_ptr[2*1]
+ufunc_ndtr_data[2] = &ufunc_ndtr_ptr[2*2]
+ufunc_ndtr_data[3] = &ufunc_ndtr_ptr[2*3]
+ndtr = np.PyUFunc_FromFuncAndData(ufunc_ndtr_loops, ufunc_ndtr_data, ufunc_ndtr_types, 4, 1, 1, 0, "ndtr", ufunc_ndtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ndtri_loops[2]
+cdef void *ufunc_ndtri_ptr[4]
+cdef void *ufunc_ndtri_data[2]
+cdef char ufunc_ndtri_types[4]
+cdef char *ufunc_ndtri_doc = (
+    "ndtri(y, out=None)\n"
+    "\n"
+    "Inverse of `ndtr` vs x\n"
+    "\n"
+    "Returns the argument x for which the area under the standard normal\n"
+    "probability density function (integrated from minus infinity to `x`)\n"
+    "is equal to y.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "x : scalar or ndarray\n"
+    "    Value of x such that ``ndtr(x) == p``.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "ndtr : Standard normal cumulative probability distribution\n"
+    "ndtri_exp : Inverse of log_ndtr\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`ndtri` is the percentile function of the standard normal distribution.\n"
+    "This means it returns the inverse of the cumulative density `ndtr`. First,\n"
+    "let us compute a cumulative density value.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import ndtri, ndtr\n"
+    ">>> cdf_val = ndtr(2)\n"
+    ">>> cdf_val\n"
+    "0.9772498680518208\n"
+    "\n"
+    "Verify that `ndtri` yields the original value for `x` up to floating point\n"
+    "errors.\n"
+    "\n"
+    ">>> ndtri(cdf_val)\n"
+    "2.0000000000000004\n"
+    "\n"
+    "Plot the function. For that purpose, we provide a NumPy array as argument.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> x = np.linspace(0.01, 1, 200)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, ndtri(x))\n"
+    ">>> ax.set_title(\"Standard normal percentile function\")\n"
+    ">>> plt.show()")
+ufunc_ndtri_loops[0] = loop_d_d__As_f_f
+ufunc_ndtri_loops[1] = loop_d_d__As_d_d
+ufunc_ndtri_types[0] = NPY_FLOAT
+ufunc_ndtri_types[1] = NPY_FLOAT
+ufunc_ndtri_types[2] = NPY_DOUBLE
+ufunc_ndtri_types[3] = NPY_DOUBLE
+ufunc_ndtri_ptr[2*0] = _func_xsf_ndtri
+ufunc_ndtri_ptr[2*0+1] = ("ndtri")
+ufunc_ndtri_ptr[2*1] = _func_xsf_ndtri
+ufunc_ndtri_ptr[2*1+1] = ("ndtri")
+ufunc_ndtri_data[0] = &ufunc_ndtri_ptr[2*0]
+ufunc_ndtri_data[1] = &ufunc_ndtri_ptr[2*1]
+ndtri = np.PyUFunc_FromFuncAndData(ufunc_ndtri_loops, ufunc_ndtri_data, ufunc_ndtri_types, 2, 1, 1, 0, "ndtri", ufunc_ndtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_ndtri_exp_loops[2]
+cdef void *ufunc_ndtri_exp_ptr[4]
+cdef void *ufunc_ndtri_exp_data[2]
+cdef char ufunc_ndtri_exp_types[4]
+cdef char *ufunc_ndtri_exp_doc = (
+    "ndtri_exp(y, out=None)\n"
+    "\n"
+    "Inverse of `log_ndtr` vs x. Allows for greater precision than\n"
+    "`ndtri` composed with `numpy.exp` for very small values of y and for\n"
+    "y close to 0.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "y : array_like of float\n"
+    "    Function argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Inverse of the log CDF of the standard normal distribution, evaluated\n"
+    "    at y.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "log_ndtr : log of the standard normal cumulative distribution function\n"
+    "ndtr : standard normal cumulative distribution function\n"
+    "ndtri : standard normal percentile function\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "`ndtri_exp` agrees with the naive implementation when the latter does\n"
+    "not suffer from underflow.\n"
+    "\n"
+    ">>> sc.ndtri_exp(-1)\n"
+    "-0.33747496376420244\n"
+    ">>> sc.ndtri(np.exp(-1))\n"
+    "-0.33747496376420244\n"
+    "\n"
+    "For extreme values of y, the naive approach fails\n"
+    "\n"
+    ">>> sc.ndtri(np.exp(-800))\n"
+    "-inf\n"
+    ">>> sc.ndtri(np.exp(-1e-20))\n"
+    "inf\n"
+    "\n"
+    "whereas `ndtri_exp` is still able to compute the result to high precision.\n"
+    "\n"
+    ">>> sc.ndtri_exp(-800)\n"
+    "-39.88469483825668\n"
+    ">>> sc.ndtri_exp(-1e-20)\n"
+    "9.262340089798409")
+ufunc_ndtri_exp_loops[0] = loop_d_d__As_f_f
+ufunc_ndtri_exp_loops[1] = loop_d_d__As_d_d
+ufunc_ndtri_exp_types[0] = NPY_FLOAT
+ufunc_ndtri_exp_types[1] = NPY_FLOAT
+ufunc_ndtri_exp_types[2] = NPY_DOUBLE
+ufunc_ndtri_exp_types[3] = NPY_DOUBLE
+ufunc_ndtri_exp_ptr[2*0] = _func_ndtri_exp
+ufunc_ndtri_exp_ptr[2*0+1] = ("ndtri_exp")
+ufunc_ndtri_exp_ptr[2*1] = _func_ndtri_exp
+ufunc_ndtri_exp_ptr[2*1+1] = ("ndtri_exp")
+ufunc_ndtri_exp_data[0] = &ufunc_ndtri_exp_ptr[2*0]
+ufunc_ndtri_exp_data[1] = &ufunc_ndtri_exp_ptr[2*1]
+ndtri_exp = np.PyUFunc_FromFuncAndData(ufunc_ndtri_exp_loops, ufunc_ndtri_exp_data, ufunc_ndtri_exp_types, 2, 1, 1, 0, "ndtri_exp", ufunc_ndtri_exp_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nrdtrimn_loops[2]
+cdef void *ufunc_nrdtrimn_ptr[4]
+cdef void *ufunc_nrdtrimn_data[2]
+cdef char ufunc_nrdtrimn_types[8]
+cdef char *ufunc_nrdtrimn_doc = (
+    "nrdtrimn(p, std, x, out=None)\n"
+    "\n"
+    "Calculate mean of normal distribution given other params.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "std : array_like\n"
+    "    Standard deviation.\n"
+    "x : array_like\n"
+    "    Quantiles, i.e. the upper limit of integration.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "mn : scalar or ndarray\n"
+    "    The mean of the normal distribution.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "scipy.stats.norm : Normal distribution\n"
+    "ndtr : Standard normal cumulative probability distribution\n"
+    "ndtri : Inverse of standard normal CDF with respect to quantile\n"
+    "nrdtrisd : Inverse of normal distribution CDF with respect to\n"
+    "           standard deviation\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`nrdtrimn` can be used to recover the mean of a normal distribution\n"
+    "if we know the CDF value `p` for a given quantile `x` and the\n"
+    "standard deviation `std`. First, we calculate\n"
+    "the normal distribution CDF for an exemplary parameter set.\n"
+    "\n"
+    ">>> from scipy.stats import norm\n"
+    ">>> mean = 3.\n"
+    ">>> std = 2.\n"
+    ">>> x = 6.\n"
+    ">>> p = norm.cdf(x, loc=mean, scale=std)\n"
+    ">>> p\n"
+    "0.9331927987311419\n"
+    "\n"
+    "Verify that `nrdtrimn` returns the original value for `mean`.\n"
+    "\n"
+    ">>> from scipy.special import nrdtrimn\n"
+    ">>> nrdtrimn(p, std, x)\n"
+    "3.0000000000000004")
+ufunc_nrdtrimn_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nrdtrimn_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nrdtrimn_types[0] = NPY_FLOAT
+ufunc_nrdtrimn_types[1] = NPY_FLOAT
+ufunc_nrdtrimn_types[2] = NPY_FLOAT
+ufunc_nrdtrimn_types[3] = NPY_FLOAT
+ufunc_nrdtrimn_types[4] = NPY_DOUBLE
+ufunc_nrdtrimn_types[5] = NPY_DOUBLE
+ufunc_nrdtrimn_types[6] = NPY_DOUBLE
+ufunc_nrdtrimn_types[7] = NPY_DOUBLE
+ufunc_nrdtrimn_ptr[2*0] = _func_nrdtrimn
+ufunc_nrdtrimn_ptr[2*0+1] = ("nrdtrimn")
+ufunc_nrdtrimn_ptr[2*1] = _func_nrdtrimn
+ufunc_nrdtrimn_ptr[2*1+1] = ("nrdtrimn")
+ufunc_nrdtrimn_data[0] = &ufunc_nrdtrimn_ptr[2*0]
+ufunc_nrdtrimn_data[1] = &ufunc_nrdtrimn_ptr[2*1]
+nrdtrimn = np.PyUFunc_FromFuncAndData(ufunc_nrdtrimn_loops, ufunc_nrdtrimn_data, ufunc_nrdtrimn_types, 2, 3, 1, 0, "nrdtrimn", ufunc_nrdtrimn_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_nrdtrisd_loops[2]
+cdef void *ufunc_nrdtrisd_ptr[4]
+cdef void *ufunc_nrdtrisd_data[2]
+cdef char ufunc_nrdtrisd_types[8]
+cdef char *ufunc_nrdtrisd_doc = (
+    "nrdtrisd(mn, p, x, out=None)\n"
+    "\n"
+    "Calculate standard deviation of normal distribution given other params.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "mn : scalar or ndarray\n"
+    "    The mean of the normal distribution.\n"
+    "p : array_like\n"
+    "    CDF values, in range (0, 1].\n"
+    "x : array_like\n"
+    "    Quantiles, i.e. the upper limit of integration.\n"
+    "\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "std : scalar or ndarray\n"
+    "    Standard deviation.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "scipy.stats.norm : Normal distribution\n"
+    "ndtr : Standard normal cumulative probability distribution\n"
+    "ndtri : Inverse of standard normal CDF with respect to quantile\n"
+    "nrdtrimn : Inverse of normal distribution CDF with respect to\n"
+    "           mean\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`nrdtrisd` can be used to recover the standard deviation of a normal\n"
+    "distribution if we know the CDF value `p` for a given quantile `x` and\n"
+    "the mean `mn`. First, we calculate the normal distribution CDF for an\n"
+    "exemplary parameter set.\n"
+    "\n"
+    ">>> from scipy.stats import norm\n"
+    ">>> mean = 3.\n"
+    ">>> std = 2.\n"
+    ">>> x = 6.\n"
+    ">>> p = norm.cdf(x, loc=mean, scale=std)\n"
+    ">>> p\n"
+    "0.9331927987311419\n"
+    "\n"
+    "Verify that `nrdtrisd` returns the original value for `std`.\n"
+    "\n"
+    ">>> from scipy.special import nrdtrisd\n"
+    ">>> nrdtrisd(mean, p, x)\n"
+    "2.0000000000000004")
+ufunc_nrdtrisd_loops[0] = loop_d_ddd__As_fff_f
+ufunc_nrdtrisd_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_nrdtrisd_types[0] = NPY_FLOAT
+ufunc_nrdtrisd_types[1] = NPY_FLOAT
+ufunc_nrdtrisd_types[2] = NPY_FLOAT
+ufunc_nrdtrisd_types[3] = NPY_FLOAT
+ufunc_nrdtrisd_types[4] = NPY_DOUBLE
+ufunc_nrdtrisd_types[5] = NPY_DOUBLE
+ufunc_nrdtrisd_types[6] = NPY_DOUBLE
+ufunc_nrdtrisd_types[7] = NPY_DOUBLE
+ufunc_nrdtrisd_ptr[2*0] = _func_nrdtrisd
+ufunc_nrdtrisd_ptr[2*0+1] = ("nrdtrisd")
+ufunc_nrdtrisd_ptr[2*1] = _func_nrdtrisd
+ufunc_nrdtrisd_ptr[2*1+1] = ("nrdtrisd")
+ufunc_nrdtrisd_data[0] = &ufunc_nrdtrisd_ptr[2*0]
+ufunc_nrdtrisd_data[1] = &ufunc_nrdtrisd_ptr[2*1]
+nrdtrisd = np.PyUFunc_FromFuncAndData(ufunc_nrdtrisd_loops, ufunc_nrdtrisd_data, ufunc_nrdtrisd_types, 2, 3, 1, 0, "nrdtrisd", ufunc_nrdtrisd_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_owens_t_loops[2]
+cdef void *ufunc_owens_t_ptr[4]
+cdef void *ufunc_owens_t_data[2]
+cdef char ufunc_owens_t_types[6]
+cdef char *ufunc_owens_t_doc = (
+    "owens_t(h, a, out=None)\n"
+    "\n"
+    "Owen's T Function.\n"
+    "\n"
+    "The function T(h, a) gives the probability of the event\n"
+    "(X > h and 0 < Y < a * X) where X and Y are independent\n"
+    "standard normal random variables.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "h: array_like\n"
+    "    Input value.\n"
+    "a: array_like\n"
+    "    Input value.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "t: scalar or ndarray\n"
+    "    Probability of the event (X > h and 0 < Y < a * X),\n"
+    "    where X and Y are independent standard normal random variables.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] M. Patefield and D. Tandy, \"Fast and accurate calculation of\n"
+    "       Owen's T Function\", Statistical Software vol. 5, pp. 1-25, 2000.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy import special\n"
+    ">>> a = 3.5\n"
+    ">>> h = 0.78\n"
+    ">>> special.owens_t(h, a)\n"
+    "0.10877216734852274")
+ufunc_owens_t_loops[0] = loop_d_dd__As_ff_f
+ufunc_owens_t_loops[1] = loop_d_dd__As_dd_d
+ufunc_owens_t_types[0] = NPY_FLOAT
+ufunc_owens_t_types[1] = NPY_FLOAT
+ufunc_owens_t_types[2] = NPY_FLOAT
+ufunc_owens_t_types[3] = NPY_DOUBLE
+ufunc_owens_t_types[4] = NPY_DOUBLE
+ufunc_owens_t_types[5] = NPY_DOUBLE
+ufunc_owens_t_ptr[2*0] = _func_xsf_owens_t
+ufunc_owens_t_ptr[2*0+1] = ("owens_t")
+ufunc_owens_t_ptr[2*1] = _func_xsf_owens_t
+ufunc_owens_t_ptr[2*1+1] = ("owens_t")
+ufunc_owens_t_data[0] = &ufunc_owens_t_ptr[2*0]
+ufunc_owens_t_data[1] = &ufunc_owens_t_ptr[2*1]
+owens_t = np.PyUFunc_FromFuncAndData(ufunc_owens_t_loops, ufunc_owens_t_data, ufunc_owens_t_types, 2, 2, 1, 0, "owens_t", ufunc_owens_t_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtr_loops[2]
+cdef void *ufunc_pdtr_ptr[4]
+cdef void *ufunc_pdtr_data[2]
+cdef char ufunc_pdtr_types[6]
+cdef char *ufunc_pdtr_doc = (
+    "pdtr(k, m, out=None)\n"
+    "\n"
+    "Poisson cumulative distribution function.\n"
+    "\n"
+    "Defined as the probability that a Poisson-distributed random\n"
+    "variable with event rate :math:`m` is less than or equal to\n"
+    ":math:`k`. More concretely, this works out to be [1]_\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "   \\exp(-m) \\sum_{j = 0}^{\\lfloor{k}\\rfloor} \\frac{m^j}{j!}.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of occurrences (nonnegative, real)\n"
+    "m : array_like\n"
+    "    Shape parameter (nonnegative, real)\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the Poisson cumulative distribution function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtrc : Poisson survival function\n"
+    "pdtrik : inverse of `pdtr` with respect to `k`\n"
+    "pdtri : inverse of `pdtr` with respect to `m`\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] https://en.wikipedia.org/wiki/Poisson_distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is a cumulative distribution function, so it converges to 1\n"
+    "monotonically as `k` goes to infinity.\n"
+    "\n"
+    ">>> sc.pdtr([1, 10, 100, np.inf], 1)\n"
+    "array([0.73575888, 0.99999999, 1.        , 1.        ])\n"
+    "\n"
+    "It is discontinuous at integers and constant between integers.\n"
+    "\n"
+    ">>> sc.pdtr([1, 1.5, 1.9, 2], 1)\n"
+    "array([0.73575888, 0.73575888, 0.73575888, 0.9196986 ])")
+ufunc_pdtr_loops[0] = loop_d_dd__As_ff_f
+ufunc_pdtr_loops[1] = loop_d_dd__As_dd_d
+ufunc_pdtr_types[0] = NPY_FLOAT
+ufunc_pdtr_types[1] = NPY_FLOAT
+ufunc_pdtr_types[2] = NPY_FLOAT
+ufunc_pdtr_types[3] = NPY_DOUBLE
+ufunc_pdtr_types[4] = NPY_DOUBLE
+ufunc_pdtr_types[5] = NPY_DOUBLE
+ufunc_pdtr_ptr[2*0] = _func_xsf_pdtr
+ufunc_pdtr_ptr[2*0+1] = ("pdtr")
+ufunc_pdtr_ptr[2*1] = _func_xsf_pdtr
+ufunc_pdtr_ptr[2*1+1] = ("pdtr")
+ufunc_pdtr_data[0] = &ufunc_pdtr_ptr[2*0]
+ufunc_pdtr_data[1] = &ufunc_pdtr_ptr[2*1]
+pdtr = np.PyUFunc_FromFuncAndData(ufunc_pdtr_loops, ufunc_pdtr_data, ufunc_pdtr_types, 2, 2, 1, 0, "pdtr", ufunc_pdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtrc_loops[2]
+cdef void *ufunc_pdtrc_ptr[4]
+cdef void *ufunc_pdtrc_data[2]
+cdef char ufunc_pdtrc_types[6]
+cdef char *ufunc_pdtrc_doc = (
+    "pdtrc(k, m, out=None)\n"
+    "\n"
+    "Poisson survival function\n"
+    "\n"
+    "Returns the sum of the terms from k+1 to infinity of the Poisson\n"
+    "distribution: sum(exp(-m) * m**j / j!, j=k+1..inf) = gammainc(\n"
+    "k+1, m). Arguments must both be non-negative doubles.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of occurrences (nonnegative, real)\n"
+    "m : array_like\n"
+    "    Shape parameter (nonnegative, real)\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the Poisson survival function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtr : Poisson cumulative distribution function\n"
+    "pdtrik : inverse of `pdtr` with respect to `k`\n"
+    "pdtri : inverse of `pdtr` with respect to `m`\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is a survival function, so it decreases to 0\n"
+    "monotonically as `k` goes to infinity.\n"
+    "\n"
+    ">>> k = np.array([1, 10, 100, np.inf])\n"
+    ">>> sc.pdtrc(k, 1)\n"
+    "array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])\n"
+    "\n"
+    "It can be expressed in terms of the lower incomplete gamma\n"
+    "function `gammainc`.\n"
+    "\n"
+    ">>> sc.gammainc(k + 1, 1)\n"
+    "array([2.64241118e-001, 1.00477664e-008, 3.94147589e-161, 0.00000000e+000])")
+ufunc_pdtrc_loops[0] = loop_d_dd__As_ff_f
+ufunc_pdtrc_loops[1] = loop_d_dd__As_dd_d
+ufunc_pdtrc_types[0] = NPY_FLOAT
+ufunc_pdtrc_types[1] = NPY_FLOAT
+ufunc_pdtrc_types[2] = NPY_FLOAT
+ufunc_pdtrc_types[3] = NPY_DOUBLE
+ufunc_pdtrc_types[4] = NPY_DOUBLE
+ufunc_pdtrc_types[5] = NPY_DOUBLE
+ufunc_pdtrc_ptr[2*0] = _func_xsf_pdtrc
+ufunc_pdtrc_ptr[2*0+1] = ("pdtrc")
+ufunc_pdtrc_ptr[2*1] = _func_xsf_pdtrc
+ufunc_pdtrc_ptr[2*1+1] = ("pdtrc")
+ufunc_pdtrc_data[0] = &ufunc_pdtrc_ptr[2*0]
+ufunc_pdtrc_data[1] = &ufunc_pdtrc_ptr[2*1]
+pdtrc = np.PyUFunc_FromFuncAndData(ufunc_pdtrc_loops, ufunc_pdtrc_data, ufunc_pdtrc_types, 2, 2, 1, 0, "pdtrc", ufunc_pdtrc_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtri_loops[3]
+cdef void *ufunc_pdtri_ptr[6]
+cdef void *ufunc_pdtri_data[3]
+cdef char ufunc_pdtri_types[9]
+cdef char *ufunc_pdtri_doc = (
+    "pdtri(k, y, out=None)\n"
+    "\n"
+    "Inverse to `pdtr` vs m\n"
+    "\n"
+    "Returns the Poisson variable `m` such that the sum from 0 to `k` of\n"
+    "the Poisson density is equal to the given probability `y`:\n"
+    "calculated by ``gammaincinv(k + 1, y)``. `k` must be a nonnegative\n"
+    "integer and `y` between 0 and 1.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "k : array_like\n"
+    "    Number of occurrences (nonnegative, real)\n"
+    "y : array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Values of the shape parameter `m` such that ``pdtr(k, m) = p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtr : Poisson cumulative distribution function\n"
+    "pdtrc : Poisson survival function\n"
+    "pdtrik : inverse of `pdtr` with respect to `k`\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "Compute the CDF for several values of `m`:\n"
+    "\n"
+    ">>> m = [0.5, 1, 1.5]\n"
+    ">>> p = sc.pdtr(1, m)\n"
+    ">>> p\n"
+    "array([0.90979599, 0.73575888, 0.5578254 ])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `m`, as expected:\n"
+    "\n"
+    ">>> sc.pdtri(1, p)\n"
+    "array([0.5, 1. , 1.5])")
+ufunc_pdtri_loops[0] = loop_d_pd__As_pd_d
+ufunc_pdtri_loops[1] = loop_d_dd__As_ff_f
+ufunc_pdtri_loops[2] = loop_d_dd__As_dd_d
+ufunc_pdtri_types[0] = NPY_INTP
+ufunc_pdtri_types[1] = NPY_DOUBLE
+ufunc_pdtri_types[2] = NPY_DOUBLE
+ufunc_pdtri_types[3] = NPY_FLOAT
+ufunc_pdtri_types[4] = NPY_FLOAT
+ufunc_pdtri_types[5] = NPY_FLOAT
+ufunc_pdtri_types[6] = NPY_DOUBLE
+ufunc_pdtri_types[7] = NPY_DOUBLE
+ufunc_pdtri_types[8] = NPY_DOUBLE
+ufunc_pdtri_ptr[2*0] = _func_cephes_pdtri_wrap
+ufunc_pdtri_ptr[2*0+1] = ("pdtri")
+ufunc_pdtri_ptr[2*1] = _func_pdtri_unsafe
+ufunc_pdtri_ptr[2*1+1] = ("pdtri")
+ufunc_pdtri_ptr[2*2] = _func_pdtri_unsafe
+ufunc_pdtri_ptr[2*2+1] = ("pdtri")
+ufunc_pdtri_data[0] = &ufunc_pdtri_ptr[2*0]
+ufunc_pdtri_data[1] = &ufunc_pdtri_ptr[2*1]
+ufunc_pdtri_data[2] = &ufunc_pdtri_ptr[2*2]
+pdtri = np.PyUFunc_FromFuncAndData(ufunc_pdtri_loops, ufunc_pdtri_data, ufunc_pdtri_types, 3, 2, 1, 0, "pdtri", ufunc_pdtri_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pdtrik_loops[2]
+cdef void *ufunc_pdtrik_ptr[4]
+cdef void *ufunc_pdtrik_data[2]
+cdef char ufunc_pdtrik_types[6]
+cdef char *ufunc_pdtrik_doc = (
+    "pdtrik(p, m, out=None)\n"
+    "\n"
+    "Inverse to `pdtr` vs `k`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "m : array_like\n"
+    "    Shape parameter (nonnegative, real)\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The number of occurrences `k` such that ``pdtr(k, m) = p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "pdtr : Poisson cumulative distribution function\n"
+    "pdtrc : Poisson survival function\n"
+    "pdtri : inverse of `pdtr` with respect to `m`\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "Compute the CDF for several values of `k`:\n"
+    "\n"
+    ">>> k = [1, 2, 3]\n"
+    ">>> p = sc.pdtr(k, 2)\n"
+    ">>> p\n"
+    "array([0.40600585, 0.67667642, 0.85712346])\n"
+    "\n"
+    "Compute the inverse. We recover the values of `k`, as expected:\n"
+    "\n"
+    ">>> sc.pdtrik(p, 2)\n"
+    "array([1., 2., 3.])")
+ufunc_pdtrik_loops[0] = loop_d_dd__As_ff_f
+ufunc_pdtrik_loops[1] = loop_d_dd__As_dd_d
+ufunc_pdtrik_types[0] = NPY_FLOAT
+ufunc_pdtrik_types[1] = NPY_FLOAT
+ufunc_pdtrik_types[2] = NPY_FLOAT
+ufunc_pdtrik_types[3] = NPY_DOUBLE
+ufunc_pdtrik_types[4] = NPY_DOUBLE
+ufunc_pdtrik_types[5] = NPY_DOUBLE
+ufunc_pdtrik_ptr[2*0] = _func_pdtrik
+ufunc_pdtrik_ptr[2*0+1] = ("pdtrik")
+ufunc_pdtrik_ptr[2*1] = _func_pdtrik
+ufunc_pdtrik_ptr[2*1+1] = ("pdtrik")
+ufunc_pdtrik_data[0] = &ufunc_pdtrik_ptr[2*0]
+ufunc_pdtrik_data[1] = &ufunc_pdtrik_ptr[2*1]
+pdtrik = np.PyUFunc_FromFuncAndData(ufunc_pdtrik_loops, ufunc_pdtrik_data, ufunc_pdtrik_types, 2, 2, 1, 0, "pdtrik", ufunc_pdtrik_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_poch_loops[2]
+cdef void *ufunc_poch_ptr[4]
+cdef void *ufunc_poch_data[2]
+cdef char ufunc_poch_types[6]
+cdef char *ufunc_poch_doc = (
+    "poch(z, m, out=None)\n"
+    "\n"
+    "Pochhammer symbol.\n"
+    "\n"
+    "The Pochhammer symbol (rising factorial) is defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    (z)_m = \\frac{\\Gamma(z + m)}{\\Gamma(z)}\n"
+    "\n"
+    "For positive integer `m` it reads\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    (z)_m = z (z + 1) ... (z + m - 1)\n"
+    "\n"
+    "See [dlmf]_ for more details.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z, m : array_like\n"
+    "    Real-valued arguments.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value of the function.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [dlmf] Nist, Digital Library of Mathematical Functions\n"
+    "    https://dlmf.nist.gov/5.2#iii\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It is 1 when m is 0.\n"
+    "\n"
+    ">>> sc.poch([1, 2, 3, 4], 0)\n"
+    "array([1., 1., 1., 1.])\n"
+    "\n"
+    "For z equal to 1 it reduces to the factorial function.\n"
+    "\n"
+    ">>> sc.poch(1, 5)\n"
+    "120.0\n"
+    ">>> 1 * 2 * 3 * 4 * 5\n"
+    "120\n"
+    "\n"
+    "It can be expressed in terms of the gamma function.\n"
+    "\n"
+    ">>> z, m = 3.7, 2.1\n"
+    ">>> sc.poch(z, m)\n"
+    "20.529581933776953\n"
+    ">>> sc.gamma(z + m) / sc.gamma(z)\n"
+    "20.52958193377696")
+ufunc_poch_loops[0] = loop_d_dd__As_ff_f
+ufunc_poch_loops[1] = loop_d_dd__As_dd_d
+ufunc_poch_types[0] = NPY_FLOAT
+ufunc_poch_types[1] = NPY_FLOAT
+ufunc_poch_types[2] = NPY_FLOAT
+ufunc_poch_types[3] = NPY_DOUBLE
+ufunc_poch_types[4] = NPY_DOUBLE
+ufunc_poch_types[5] = NPY_DOUBLE
+ufunc_poch_ptr[2*0] = _func_cephes_poch
+ufunc_poch_ptr[2*0+1] = ("poch")
+ufunc_poch_ptr[2*1] = _func_cephes_poch
+ufunc_poch_ptr[2*1+1] = ("poch")
+ufunc_poch_data[0] = &ufunc_poch_ptr[2*0]
+ufunc_poch_data[1] = &ufunc_poch_ptr[2*1]
+poch = np.PyUFunc_FromFuncAndData(ufunc_poch_loops, ufunc_poch_data, ufunc_poch_types, 2, 2, 1, 0, "poch", ufunc_poch_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_powm1_loops[2]
+cdef void *ufunc_powm1_ptr[4]
+cdef void *ufunc_powm1_data[2]
+cdef char ufunc_powm1_types[6]
+cdef char *ufunc_powm1_doc = (
+    "powm1(x, y, out=None)\n"
+    "\n"
+    "Computes ``x**y - 1``.\n"
+    "\n"
+    "This function is useful when `y` is near 0, or when `x` is near 1.\n"
+    "\n"
+    "The function is implemented for real types only (unlike ``numpy.power``,\n"
+    "which accepts complex inputs).\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    The base. Must be a real type (i.e. integer or float, not complex).\n"
+    "y : array_like\n"
+    "    The exponent. Must be a real type (i.e. integer or float, not complex).\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "array_like\n"
+    "    Result of the calculation\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 1.10.0\n"
+    "\n"
+    "The underlying code is implemented for single precision and double\n"
+    "precision floats only.  Unlike `numpy.power`, integer inputs to\n"
+    "`powm1` are converted to floating point, and complex inputs are\n"
+    "not accepted.\n"
+    "\n"
+    "Note the following edge cases:\n"
+    "\n"
+    "* ``powm1(x, 0)`` returns 0 for any ``x``, including 0, ``inf``\n"
+    "  and ``nan``.\n"
+    "* ``powm1(1, y)`` returns 0 for any ``y``, including ``nan``\n"
+    "  and ``inf``.\n"
+    "\n"
+    "This function wraps the ``powm1`` routine from the\n"
+    "Boost Math C++ library [1]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] The Boost Developers. \"Boost C++ Libraries\". https://www.boost.org/.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import powm1\n"
+    "\n"
+    ">>> x = np.array([1.2, 10.0, 0.9999999975])\n"
+    ">>> y = np.array([1e-9, 1e-11, 0.1875])\n"
+    ">>> powm1(x, y)\n"
+    "array([ 1.82321557e-10,  2.30258509e-11, -4.68749998e-10])\n"
+    "\n"
+    "It can be verified that the relative errors in those results\n"
+    "are less than 2.5e-16.\n"
+    "\n"
+    "Compare that to the result of ``x**y - 1``, where the\n"
+    "relative errors are all larger than 8e-8:\n"
+    "\n"
+    ">>> x**y - 1\n"
+    "array([ 1.82321491e-10,  2.30258035e-11, -4.68750039e-10])")
+ufunc_powm1_loops[0] = loop_f_ff__As_ff_f
+ufunc_powm1_loops[1] = loop_d_dd__As_dd_d
+ufunc_powm1_types[0] = NPY_FLOAT
+ufunc_powm1_types[1] = NPY_FLOAT
+ufunc_powm1_types[2] = NPY_FLOAT
+ufunc_powm1_types[3] = NPY_DOUBLE
+ufunc_powm1_types[4] = NPY_DOUBLE
+ufunc_powm1_types[5] = NPY_DOUBLE
+ufunc_powm1_ptr[2*0] = scipy.special._ufuncs_cxx._export_powm1_float
+ufunc_powm1_ptr[2*0+1] = ("powm1")
+ufunc_powm1_ptr[2*1] = scipy.special._ufuncs_cxx._export_powm1_double
+ufunc_powm1_ptr[2*1+1] = ("powm1")
+ufunc_powm1_data[0] = &ufunc_powm1_ptr[2*0]
+ufunc_powm1_data[1] = &ufunc_powm1_ptr[2*1]
+powm1 = np.PyUFunc_FromFuncAndData(ufunc_powm1_loops, ufunc_powm1_data, ufunc_powm1_types, 2, 2, 1, 0, "powm1", ufunc_powm1_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_pseudo_huber_loops[2]
+cdef void *ufunc_pseudo_huber_ptr[4]
+cdef void *ufunc_pseudo_huber_data[2]
+cdef char ufunc_pseudo_huber_types[6]
+cdef char *ufunc_pseudo_huber_doc = (
+    "pseudo_huber(delta, r, out=None)\n"
+    "\n"
+    "Pseudo-Huber loss function.\n"
+    "\n"
+    ".. math:: \\mathrm{pseudo\\_huber}(\\delta, r) =\n"
+    "          \\delta^2 \\left( \\sqrt{ 1 + \\left( \\frac{r}{\\delta} \\right)^2 } - 1 \\right)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "delta : array_like\n"
+    "    Input array, indicating the soft quadratic vs. linear loss changepoint.\n"
+    "r : array_like\n"
+    "    Input array, possibly representing residuals.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "res : scalar or ndarray\n"
+    "    The computed Pseudo-Huber loss function values.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "huber: Similar function which this function approximates\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Like `huber`, `pseudo_huber` often serves as a robust loss function\n"
+    "in statistics or machine learning to reduce the influence of outliers.\n"
+    "Unlike `huber`, `pseudo_huber` is smooth.\n"
+    "\n"
+    "Typically, `r` represents residuals, the difference\n"
+    "between a model prediction and data. Then, for :math:`|r|\\leq\\delta`,\n"
+    "`pseudo_huber` resembles the squared error and for :math:`|r|>\\delta` the\n"
+    "absolute error. This way, the Pseudo-Huber loss often achieves\n"
+    "a fast convergence in model fitting for small residuals like the squared\n"
+    "error loss function and still reduces the influence of outliers\n"
+    "(:math:`|r|>\\delta`) like the absolute error loss. As :math:`\\delta` is\n"
+    "the cutoff between squared and absolute error regimes, it has\n"
+    "to be tuned carefully for each problem. `pseudo_huber` is also\n"
+    "convex, making it suitable for gradient based optimization. [1]_ [2]_\n"
+    "\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Hartley, Zisserman, \"Multiple View Geometry in Computer Vision\".\n"
+    "       2003. Cambridge University Press. p. 619\n"
+    ".. [2] Charbonnier et al. \"Deterministic edge-preserving regularization\n"
+    "       in computed imaging\". 1997. IEEE Trans. Image Processing.\n"
+    "       6 (2): 298 - 311.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Import all necessary modules.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import pseudo_huber, huber\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "Calculate the function for ``delta=1`` at ``r=2``.\n"
+    "\n"
+    ">>> pseudo_huber(1., 2.)\n"
+    "1.2360679774997898\n"
+    "\n"
+    "Calculate the function at ``r=2`` for different `delta` by providing\n"
+    "a list or NumPy array for `delta`.\n"
+    "\n"
+    ">>> pseudo_huber([1., 2., 4.], 3.)\n"
+    "array([2.16227766, 3.21110255, 4.        ])\n"
+    "\n"
+    "Calculate the function for ``delta=1`` at several points by providing\n"
+    "a list or NumPy array for `r`.\n"
+    "\n"
+    ">>> pseudo_huber(2., np.array([1., 1.5, 3., 4.]))\n"
+    "array([0.47213595, 1.        , 3.21110255, 4.94427191])\n"
+    "\n"
+    "The function can be calculated for different `delta` and `r` by\n"
+    "providing arrays for both with compatible shapes for broadcasting.\n"
+    "\n"
+    ">>> r = np.array([1., 2.5, 8., 10.])\n"
+    ">>> deltas = np.array([[1.], [5.], [9.]])\n"
+    ">>> print(r.shape, deltas.shape)\n"
+    "(4,) (3, 1)\n"
+    "\n"
+    ">>> pseudo_huber(deltas, r)\n"
+    "array([[ 0.41421356,  1.6925824 ,  7.06225775,  9.04987562],\n"
+    "       [ 0.49509757,  2.95084972, 22.16990566, 30.90169944],\n"
+    "       [ 0.49846624,  3.06693762, 27.37435121, 40.08261642]])\n"
+    "\n"
+    "Plot the function for different `delta`.\n"
+    "\n"
+    ">>> x = np.linspace(-4, 4, 500)\n"
+    ">>> deltas = [1, 2, 3]\n"
+    ">>> linestyles = [\"dashed\", \"dotted\", \"dashdot\"]\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> combined_plot_parameters = list(zip(deltas, linestyles))\n"
+    ">>> for delta, style in combined_plot_parameters:\n"
+    "...     ax.plot(x, pseudo_huber(delta, x), label=rf\"$\\delta={delta}$\",\n"
+    "...             ls=style)\n"
+    ">>> ax.legend(loc=\"upper center\")\n"
+    ">>> ax.set_xlabel(\"$x$\")\n"
+    ">>> ax.set_title(r\"Pseudo-Huber loss function $h_{\\delta}(x)$\")\n"
+    ">>> ax.set_xlim(-4, 4)\n"
+    ">>> ax.set_ylim(0, 8)\n"
+    ">>> plt.show()\n"
+    "\n"
+    "Finally, illustrate the difference between `huber` and `pseudo_huber` by\n"
+    "plotting them and their gradients with respect to `r`. The plot shows\n"
+    "that `pseudo_huber` is continuously differentiable while `huber` is not\n"
+    "at the points :math:`\\pm\\delta`.\n"
+    "\n"
+    ">>> def huber_grad(delta, x):\n"
+    "...     grad = np.copy(x)\n"
+    "...     linear_area = np.argwhere(np.abs(x) > delta)\n"
+    "...     grad[linear_area]=delta*np.sign(x[linear_area])\n"
+    "...     return grad\n"
+    ">>> def pseudo_huber_grad(delta, x):\n"
+    "...     return x* (1+(x/delta)**2)**(-0.5)\n"
+    ">>> x=np.linspace(-3, 3, 500)\n"
+    ">>> delta = 1.\n"
+    ">>> fig, ax = plt.subplots(figsize=(7, 7))\n"
+    ">>> ax.plot(x, huber(delta, x), label=\"Huber\", ls=\"dashed\")\n"
+    ">>> ax.plot(x, huber_grad(delta, x), label=\"Huber Gradient\", ls=\"dashdot\")\n"
+    ">>> ax.plot(x, pseudo_huber(delta, x), label=\"Pseudo-Huber\", ls=\"dotted\")\n"
+    ">>> ax.plot(x, pseudo_huber_grad(delta, x), label=\"Pseudo-Huber Gradient\",\n"
+    "...         ls=\"solid\")\n"
+    ">>> ax.legend(loc=\"upper center\")\n"
+    ">>> plt.show()")
+ufunc_pseudo_huber_loops[0] = loop_d_dd__As_ff_f
+ufunc_pseudo_huber_loops[1] = loop_d_dd__As_dd_d
+ufunc_pseudo_huber_types[0] = NPY_FLOAT
+ufunc_pseudo_huber_types[1] = NPY_FLOAT
+ufunc_pseudo_huber_types[2] = NPY_FLOAT
+ufunc_pseudo_huber_types[3] = NPY_DOUBLE
+ufunc_pseudo_huber_types[4] = NPY_DOUBLE
+ufunc_pseudo_huber_types[5] = NPY_DOUBLE
+ufunc_pseudo_huber_ptr[2*0] = _func_pseudo_huber
+ufunc_pseudo_huber_ptr[2*0+1] = ("pseudo_huber")
+ufunc_pseudo_huber_ptr[2*1] = _func_pseudo_huber
+ufunc_pseudo_huber_ptr[2*1+1] = ("pseudo_huber")
+ufunc_pseudo_huber_data[0] = &ufunc_pseudo_huber_ptr[2*0]
+ufunc_pseudo_huber_data[1] = &ufunc_pseudo_huber_ptr[2*1]
+pseudo_huber = np.PyUFunc_FromFuncAndData(ufunc_pseudo_huber_loops, ufunc_pseudo_huber_data, ufunc_pseudo_huber_types, 2, 2, 1, 0, "pseudo_huber", ufunc_pseudo_huber_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_rel_entr_loops[2]
+cdef void *ufunc_rel_entr_ptr[4]
+cdef void *ufunc_rel_entr_data[2]
+cdef char ufunc_rel_entr_types[6]
+cdef char *ufunc_rel_entr_doc = (
+    "rel_entr(x, y, out=None)\n"
+    "\n"
+    "Elementwise function for computing relative entropy.\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\mathrm{rel\\_entr}(x, y) =\n"
+    "        \\begin{cases}\n"
+    "            x \\log(x / y) & x > 0, y > 0 \\\\\n"
+    "            0 & x = 0, y \\ge 0 \\\\\n"
+    "            \\infty & \\text{otherwise}\n"
+    "        \\end{cases}\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, y : array_like\n"
+    "    Input arrays\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Relative entropy of the inputs\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "entr, kl_div, scipy.stats.entropy\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.15.0\n"
+    "\n"
+    "This function is jointly convex in x and y.\n"
+    "\n"
+    "The origin of this function is in convex programming; see\n"
+    "[1]_. Given two discrete probability distributions :math:`p_1,\n"
+    "\\ldots, p_n` and :math:`q_1, \\ldots, q_n`, the definition of relative\n"
+    "entropy in the context of *information theory* is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\sum_{i = 1}^n \\mathrm{rel\\_entr}(p_i, q_i).\n"
+    "\n"
+    "To compute the latter quantity, use `scipy.stats.entropy`.\n"
+    "\n"
+    "See [2]_ for details.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Boyd, Stephen and Lieven Vandenberghe. *Convex optimization*.\n"
+    "       Cambridge University Press, 2004.\n"
+    "       :doi:`https://doi.org/10.1017/CBO9780511804441`\n"
+    ".. [2] Kullback-Leibler divergence,\n"
+    "       https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence")
+ufunc_rel_entr_loops[0] = loop_d_dd__As_ff_f
+ufunc_rel_entr_loops[1] = loop_d_dd__As_dd_d
+ufunc_rel_entr_types[0] = NPY_FLOAT
+ufunc_rel_entr_types[1] = NPY_FLOAT
+ufunc_rel_entr_types[2] = NPY_FLOAT
+ufunc_rel_entr_types[3] = NPY_DOUBLE
+ufunc_rel_entr_types[4] = NPY_DOUBLE
+ufunc_rel_entr_types[5] = NPY_DOUBLE
+ufunc_rel_entr_ptr[2*0] = _func_rel_entr
+ufunc_rel_entr_ptr[2*0+1] = ("rel_entr")
+ufunc_rel_entr_ptr[2*1] = _func_rel_entr
+ufunc_rel_entr_ptr[2*1+1] = ("rel_entr")
+ufunc_rel_entr_data[0] = &ufunc_rel_entr_ptr[2*0]
+ufunc_rel_entr_data[1] = &ufunc_rel_entr_ptr[2*1]
+rel_entr = np.PyUFunc_FromFuncAndData(ufunc_rel_entr_loops, ufunc_rel_entr_data, ufunc_rel_entr_types, 2, 2, 1, 0, "rel_entr", ufunc_rel_entr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_round_loops[2]
+cdef void *ufunc_round_ptr[4]
+cdef void *ufunc_round_data[2]
+cdef char ufunc_round_types[4]
+cdef char *ufunc_round_doc = (
+    "round(x, out=None)\n"
+    "\n"
+    "Round to the nearest integer.\n"
+    "\n"
+    "Returns the nearest integer to `x`.  If `x` ends in 0.5 exactly,\n"
+    "the nearest even integer is chosen.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real valued input.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results.\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The nearest integers to the elements of `x`. The result is of\n"
+    "    floating type, not integer type.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import scipy.special as sc\n"
+    "\n"
+    "It rounds to even.\n"
+    "\n"
+    ">>> sc.round([0.5, 1.5])\n"
+    "array([0., 2.])")
+ufunc_round_loops[0] = loop_d_d__As_f_f
+ufunc_round_loops[1] = loop_d_d__As_d_d
+ufunc_round_types[0] = NPY_FLOAT
+ufunc_round_types[1] = NPY_FLOAT
+ufunc_round_types[2] = NPY_DOUBLE
+ufunc_round_types[3] = NPY_DOUBLE
+ufunc_round_ptr[2*0] = _func_cephes_round
+ufunc_round_ptr[2*0+1] = ("round")
+ufunc_round_ptr[2*1] = _func_cephes_round
+ufunc_round_ptr[2*1+1] = ("round")
+ufunc_round_data[0] = &ufunc_round_ptr[2*0]
+ufunc_round_data[1] = &ufunc_round_ptr[2*1]
+round = np.PyUFunc_FromFuncAndData(ufunc_round_loops, ufunc_round_data, ufunc_round_types, 2, 1, 1, 0, "round", ufunc_round_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_shichi_loops[4]
+cdef void *ufunc_shichi_ptr[8]
+cdef void *ufunc_shichi_data[4]
+cdef char ufunc_shichi_types[12]
+cdef char *ufunc_shichi_doc = (
+    "shichi(x, out=None)\n"
+    "\n"
+    "Hyperbolic sine and cosine integrals.\n"
+    "\n"
+    "The hyperbolic sine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\int_0^x \\frac{\\sinh{t}}{t}dt\n"
+    "\n"
+    "and the hyperbolic cosine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\gamma + \\log(x) + \\int_0^x \\frac{\\cosh{t} - 1}{t} dt\n"
+    "\n"
+    "where :math:`\\gamma` is Euler's constant and :math:`\\log` is the\n"
+    "principal branch of the logarithm [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex points at which to compute the hyperbolic sine\n"
+    "    and cosine integrals.\n"
+    "out : tuple of ndarray, optional\n"
+    "    Optional output arrays for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "si : scalar or ndarray\n"
+    "    Hyperbolic sine integral at ``x``\n"
+    "ci : scalar or ndarray\n"
+    "    Hyperbolic cosine integral at ``x``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "sici : Sine and cosine integrals.\n"
+    "exp1 : Exponential integral E1.\n"
+    "expi : Exponential integral Ei.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "For real arguments with ``x < 0``, ``chi`` is the real part of the\n"
+    "hyperbolic cosine integral. For such points ``chi(x)`` and ``chi(x\n"
+    "+ 0j)`` differ by a factor of ``1j*pi``.\n"
+    "\n"
+    "For real arguments the function is computed by calling Cephes'\n"
+    "[2]_ *shichi* routine. For complex arguments the algorithm is based\n"
+    "on Mpmath's [3]_ *shi* and *chi* routines.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "       (See Section 5.2.)\n"
+    ".. [2] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    ".. [3] Fredrik Johansson and others.\n"
+    "       \"mpmath: a Python library for arbitrary-precision floating-point\n"
+    "       arithmetic\" (Version 0.19) http://mpmath.org/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import shichi, sici\n"
+    "\n"
+    "`shichi` accepts real or complex input:\n"
+    "\n"
+    ">>> shichi(0.5)\n"
+    "(0.5069967498196671, -0.05277684495649357)\n"
+    ">>> shichi(0.5 + 2.5j)\n"
+    "((0.11772029666668238+1.831091777729851j),\n"
+    " (0.29912435887648825+1.7395351121166562j))\n"
+    "\n"
+    "The hyperbolic sine and cosine integrals Shi(z) and Chi(z) are\n"
+    "related to the sine and cosine integrals Si(z) and Ci(z) by\n"
+    "\n"
+    "* Shi(z) = -i*Si(i*z)\n"
+    "* Chi(z) = Ci(-i*z) + i*pi/2\n"
+    "\n"
+    ">>> z = 0.25 + 5j\n"
+    ">>> shi, chi = shichi(z)\n"
+    ">>> shi, -1j*sici(1j*z)[0]            # Should be the same.\n"
+    "((-0.04834719325101729+1.5469354086921228j),\n"
+    " (-0.04834719325101729+1.5469354086921228j))\n"
+    ">>> chi, sici(-1j*z)[1] + 1j*np.pi/2  # Should be the same.\n"
+    "((-0.19568708973868087+1.556276312103824j),\n"
+    " (-0.19568708973868087+1.556276312103824j))\n"
+    "\n"
+    "Plot the functions evaluated on the real axis:\n"
+    "\n"
+    ">>> xp = np.geomspace(1e-8, 4.0, 250)\n"
+    ">>> x = np.concatenate((-xp[::-1], xp))\n"
+    ">>> shi, chi = shichi(x)\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, shi, label='Shi(x)')\n"
+    ">>> ax.plot(x, chi, '--', label='Chi(x)')\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.set_title('Hyperbolic Sine and Cosine Integrals')\n"
+    ">>> ax.legend(shadow=True, framealpha=1, loc='lower right')\n"
+    ">>> ax.grid(True)\n"
+    ">>> plt.show()")
+ufunc_shichi_loops[0] = loop_i_d_dd_As_f_ff
+ufunc_shichi_loops[1] = loop_i_d_dd_As_d_dd
+ufunc_shichi_loops[2] = loop_i_D_DD_As_F_FF
+ufunc_shichi_loops[3] = loop_i_D_DD_As_D_DD
+ufunc_shichi_types[0] = NPY_FLOAT
+ufunc_shichi_types[1] = NPY_FLOAT
+ufunc_shichi_types[2] = NPY_FLOAT
+ufunc_shichi_types[3] = NPY_DOUBLE
+ufunc_shichi_types[4] = NPY_DOUBLE
+ufunc_shichi_types[5] = NPY_DOUBLE
+ufunc_shichi_types[6] = NPY_CFLOAT
+ufunc_shichi_types[7] = NPY_CFLOAT
+ufunc_shichi_types[8] = NPY_CFLOAT
+ufunc_shichi_types[9] = NPY_CDOUBLE
+ufunc_shichi_types[10] = NPY_CDOUBLE
+ufunc_shichi_types[11] = NPY_CDOUBLE
+ufunc_shichi_ptr[2*0] = _func_xsf_shichi
+ufunc_shichi_ptr[2*0+1] = ("shichi")
+ufunc_shichi_ptr[2*1] = _func_xsf_shichi
+ufunc_shichi_ptr[2*1+1] = ("shichi")
+ufunc_shichi_ptr[2*2] = _func_xsf_cshichi
+ufunc_shichi_ptr[2*2+1] = ("shichi")
+ufunc_shichi_ptr[2*3] = _func_xsf_cshichi
+ufunc_shichi_ptr[2*3+1] = ("shichi")
+ufunc_shichi_data[0] = &ufunc_shichi_ptr[2*0]
+ufunc_shichi_data[1] = &ufunc_shichi_ptr[2*1]
+ufunc_shichi_data[2] = &ufunc_shichi_ptr[2*2]
+ufunc_shichi_data[3] = &ufunc_shichi_ptr[2*3]
+shichi = np.PyUFunc_FromFuncAndData(ufunc_shichi_loops, ufunc_shichi_data, ufunc_shichi_types, 4, 1, 2, 0, "shichi", ufunc_shichi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_sici_loops[4]
+cdef void *ufunc_sici_ptr[8]
+cdef void *ufunc_sici_data[4]
+cdef char ufunc_sici_types[12]
+cdef char *ufunc_sici_doc = (
+    "sici(x, out=None)\n"
+    "\n"
+    "Sine and cosine integrals.\n"
+    "\n"
+    "The sine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\int_0^x \\frac{\\sin{t}}{t}dt\n"
+    "\n"
+    "and the cosine integral is\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "  \\gamma + \\log(x) + \\int_0^x \\frac{\\cos{t} - 1}{t}dt\n"
+    "\n"
+    "where :math:`\\gamma` is Euler's constant and :math:`\\log` is the\n"
+    "principal branch of the logarithm [1]_.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real or complex points at which to compute the sine and cosine\n"
+    "    integrals.\n"
+    "out : tuple of ndarray, optional\n"
+    "    Optional output arrays for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "si : scalar or ndarray\n"
+    "    Sine integral at ``x``\n"
+    "ci : scalar or ndarray\n"
+    "    Cosine integral at ``x``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "shichi : Hyperbolic sine and cosine integrals.\n"
+    "exp1 : Exponential integral E1.\n"
+    "expi : Exponential integral Ei.\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "For real arguments with ``x < 0``, ``ci`` is the real part of the\n"
+    "cosine integral. For such points ``ci(x)`` and ``ci(x + 0j)``\n"
+    "differ by a factor of ``1j*pi``.\n"
+    "\n"
+    "For real arguments the function is computed by calling Cephes'\n"
+    "[2]_ *sici* routine. For complex arguments the algorithm is based\n"
+    "on Mpmath's [3]_ *si* and *ci* routines.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Milton Abramowitz and Irene A. Stegun, eds.\n"
+    "       Handbook of Mathematical Functions with Formulas,\n"
+    "       Graphs, and Mathematical Tables. New York: Dover, 1972.\n"
+    "       (See Section 5.2.)\n"
+    ".. [2] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    ".. [3] Fredrik Johansson and others.\n"
+    "       \"mpmath: a Python library for arbitrary-precision floating-point\n"
+    "       arithmetic\" (Version 0.19) http://mpmath.org/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import sici, exp1\n"
+    "\n"
+    "`sici` accepts real or complex input:\n"
+    "\n"
+    ">>> sici(2.5)\n"
+    "(1.7785201734438267, 0.2858711963653835)\n"
+    ">>> sici(2.5 + 3j)\n"
+    "((4.505735874563953+0.06863305018999577j),\n"
+    "(0.0793644206906966-2.935510262937543j))\n"
+    "\n"
+    "For z in the right half plane, the sine and cosine integrals are\n"
+    "related to the exponential integral E1 (implemented in SciPy as\n"
+    "`scipy.special.exp1`) by\n"
+    "\n"
+    "* Si(z) = (E1(i*z) - E1(-i*z))/2i + pi/2\n"
+    "* Ci(z) = -(E1(i*z) + E1(-i*z))/2\n"
+    "\n"
+    "See [1]_ (equations 5.2.21 and 5.2.23).\n"
+    "\n"
+    "We can verify these relations:\n"
+    "\n"
+    ">>> z = 2 - 3j\n"
+    ">>> sici(z)\n"
+    "((4.54751388956229-1.3991965806460565j),\n"
+    "(1.408292501520851+2.9836177420296055j))\n"
+    "\n"
+    ">>> (exp1(1j*z) - exp1(-1j*z))/2j + np.pi/2  # Same as sine integral\n"
+    "(4.54751388956229-1.3991965806460565j)\n"
+    "\n"
+    ">>> -(exp1(1j*z) + exp1(-1j*z))/2            # Same as cosine integral\n"
+    "(1.408292501520851+2.9836177420296055j)\n"
+    "\n"
+    "Plot the functions evaluated on the real axis; the dotted horizontal\n"
+    "lines are at pi/2 and -pi/2:\n"
+    "\n"
+    ">>> x = np.linspace(-16, 16, 150)\n"
+    ">>> si, ci = sici(x)\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> ax.plot(x, si, label='Si(x)')\n"
+    ">>> ax.plot(x, ci, '--', label='Ci(x)')\n"
+    ">>> ax.legend(shadow=True, framealpha=1, loc='upper left')\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.set_title('Sine and Cosine Integrals')\n"
+    ">>> ax.axhline(np.pi/2, linestyle=':', alpha=0.5, color='k')\n"
+    ">>> ax.axhline(-np.pi/2, linestyle=':', alpha=0.5, color='k')\n"
+    ">>> ax.grid(True)\n"
+    ">>> plt.show()")
+ufunc_sici_loops[0] = loop_i_d_dd_As_f_ff
+ufunc_sici_loops[1] = loop_i_d_dd_As_d_dd
+ufunc_sici_loops[2] = loop_i_D_DD_As_F_FF
+ufunc_sici_loops[3] = loop_i_D_DD_As_D_DD
+ufunc_sici_types[0] = NPY_FLOAT
+ufunc_sici_types[1] = NPY_FLOAT
+ufunc_sici_types[2] = NPY_FLOAT
+ufunc_sici_types[3] = NPY_DOUBLE
+ufunc_sici_types[4] = NPY_DOUBLE
+ufunc_sici_types[5] = NPY_DOUBLE
+ufunc_sici_types[6] = NPY_CFLOAT
+ufunc_sici_types[7] = NPY_CFLOAT
+ufunc_sici_types[8] = NPY_CFLOAT
+ufunc_sici_types[9] = NPY_CDOUBLE
+ufunc_sici_types[10] = NPY_CDOUBLE
+ufunc_sici_types[11] = NPY_CDOUBLE
+ufunc_sici_ptr[2*0] = _func_xsf_sici
+ufunc_sici_ptr[2*0+1] = ("sici")
+ufunc_sici_ptr[2*1] = _func_xsf_sici
+ufunc_sici_ptr[2*1+1] = ("sici")
+ufunc_sici_ptr[2*2] = _func_xsf_csici
+ufunc_sici_ptr[2*2+1] = ("sici")
+ufunc_sici_ptr[2*3] = _func_xsf_csici
+ufunc_sici_ptr[2*3+1] = ("sici")
+ufunc_sici_data[0] = &ufunc_sici_ptr[2*0]
+ufunc_sici_data[1] = &ufunc_sici_ptr[2*1]
+ufunc_sici_data[2] = &ufunc_sici_ptr[2*2]
+ufunc_sici_data[3] = &ufunc_sici_ptr[2*3]
+sici = np.PyUFunc_FromFuncAndData(ufunc_sici_loops, ufunc_sici_data, ufunc_sici_types, 4, 1, 2, 0, "sici", ufunc_sici_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_smirnov_loops[3]
+cdef void *ufunc_smirnov_ptr[6]
+cdef void *ufunc_smirnov_data[3]
+cdef char ufunc_smirnov_types[9]
+cdef char *ufunc_smirnov_doc = (
+    "smirnov(n, d, out=None)\n"
+    "\n"
+    "Kolmogorov-Smirnov complementary cumulative distribution function\n"
+    "\n"
+    "Returns the exact Kolmogorov-Smirnov complementary cumulative\n"
+    "distribution function,(aka the Survival Function) of Dn+ (or Dn-)\n"
+    "for a one-sided test of equality between an empirical and a\n"
+    "theoretical distribution. It is equal to the probability that the\n"
+    "maximum difference between a theoretical distribution and an empirical\n"
+    "one based on `n` samples is greater than d.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : int\n"
+    "  Number of samples\n"
+    "d : float array_like\n"
+    "  Deviation between the Empirical CDF (ECDF) and the target CDF.\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of smirnov(n, d), Prob(Dn+ >= d) (Also Prob(Dn- >= d))\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "smirnovi : The Inverse Survival Function for the distribution\n"
+    "scipy.stats.ksone : Provides the functionality as a continuous distribution\n"
+    "kolmogorov, kolmogi : Functions for the two-sided distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`smirnov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.ksone` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import smirnov\n"
+    ">>> from scipy.stats import norm\n"
+    "\n"
+    "Show the probability of a gap at least as big as 0, 0.5 and 1.0 for a\n"
+    "sample of size 5.\n"
+    "\n"
+    ">>> smirnov(5, [0, 0.5, 1.0])\n"
+    "array([ 1.   ,  0.056,  0.   ])\n"
+    "\n"
+    "Compare a sample of size 5 against N(0, 1), the standard normal\n"
+    "distribution with mean 0 and standard deviation 1.\n"
+    "\n"
+    "`x` is the sample.\n"
+    "\n"
+    ">>> x = np.array([-1.392, -0.135, 0.114, 0.190, 1.82])\n"
+    "\n"
+    ">>> target = norm(0, 1)\n"
+    ">>> cdfs = target.cdf(x)\n"
+    ">>> cdfs\n"
+    "array([0.0819612 , 0.44630594, 0.5453811 , 0.57534543, 0.9656205 ])\n"
+    "\n"
+    "Construct the empirical CDF and the K-S statistics (Dn+, Dn-, Dn).\n"
+    "\n"
+    ">>> n = len(x)\n"
+    ">>> ecdfs = np.arange(n+1, dtype=float)/n\n"
+    ">>> cols = np.column_stack([x, ecdfs[1:], cdfs, cdfs - ecdfs[:n],\n"
+    "...                        ecdfs[1:] - cdfs])\n"
+    ">>> with np.printoptions(precision=3):\n"
+    "...    print(cols)\n"
+    "[[-1.392  0.2    0.082  0.082  0.118]\n"
+    " [-0.135  0.4    0.446  0.246 -0.046]\n"
+    " [ 0.114  0.6    0.545  0.145  0.055]\n"
+    " [ 0.19   0.8    0.575 -0.025  0.225]\n"
+    " [ 1.82   1.     0.966  0.166  0.034]]\n"
+    ">>> gaps = cols[:, -2:]\n"
+    ">>> Dnpm = np.max(gaps, axis=0)\n"
+    ">>> print(f'Dn-={Dnpm[0]:f}, Dn+={Dnpm[1]:f}')\n"
+    "Dn-=0.246306, Dn+=0.224655\n"
+    ">>> probs = smirnov(n, Dnpm)\n"
+    ">>> print(f'For a sample of size {n} drawn from N(0, 1):',\n"
+    "...       f' Smirnov n={n}: Prob(Dn- >= {Dnpm[0]:f}) = {probs[0]:.4f}',\n"
+    "...       f' Smirnov n={n}: Prob(Dn+ >= {Dnpm[1]:f}) = {probs[1]:.4f}',\n"
+    "...       sep='\\n')\n"
+    "For a sample of size 5 drawn from N(0, 1):\n"
+    " Smirnov n=5: Prob(Dn- >= 0.246306) = 0.4711\n"
+    " Smirnov n=5: Prob(Dn+ >= 0.224655) = 0.5245\n"
+    "\n"
+    "Plot the empirical CDF and the standard normal CDF.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> plt.step(np.concatenate(([-2.5], x, [2.5])),\n"
+    "...          np.concatenate((ecdfs, [1])),\n"
+    "...          where='post', label='Empirical CDF')\n"
+    ">>> xx = np.linspace(-2.5, 2.5, 100)\n"
+    ">>> plt.plot(xx, target.cdf(xx), '--', label='CDF for N(0, 1)')\n"
+    "\n"
+    "Add vertical lines marking Dn+ and Dn-.\n"
+    "\n"
+    ">>> iminus, iplus = np.argmax(gaps, axis=0)\n"
+    ">>> plt.vlines([x[iminus]], ecdfs[iminus], cdfs[iminus], color='r',\n"
+    "...            alpha=0.5, lw=4)\n"
+    ">>> plt.vlines([x[iplus]], cdfs[iplus], ecdfs[iplus+1], color='m',\n"
+    "...            alpha=0.5, lw=4)\n"
+    "\n"
+    ">>> plt.grid(True)\n"
+    ">>> plt.legend(framealpha=1, shadow=True)\n"
+    ">>> plt.show()")
+ufunc_smirnov_loops[0] = loop_d_pd__As_pd_d
+ufunc_smirnov_loops[1] = loop_d_dd__As_ff_f
+ufunc_smirnov_loops[2] = loop_d_dd__As_dd_d
+ufunc_smirnov_types[0] = NPY_INTP
+ufunc_smirnov_types[1] = NPY_DOUBLE
+ufunc_smirnov_types[2] = NPY_DOUBLE
+ufunc_smirnov_types[3] = NPY_FLOAT
+ufunc_smirnov_types[4] = NPY_FLOAT
+ufunc_smirnov_types[5] = NPY_FLOAT
+ufunc_smirnov_types[6] = NPY_DOUBLE
+ufunc_smirnov_types[7] = NPY_DOUBLE
+ufunc_smirnov_types[8] = NPY_DOUBLE
+ufunc_smirnov_ptr[2*0] = _func_cephes_smirnov_wrap
+ufunc_smirnov_ptr[2*0+1] = ("smirnov")
+ufunc_smirnov_ptr[2*1] = _func_smirnov_unsafe
+ufunc_smirnov_ptr[2*1+1] = ("smirnov")
+ufunc_smirnov_ptr[2*2] = _func_smirnov_unsafe
+ufunc_smirnov_ptr[2*2+1] = ("smirnov")
+ufunc_smirnov_data[0] = &ufunc_smirnov_ptr[2*0]
+ufunc_smirnov_data[1] = &ufunc_smirnov_ptr[2*1]
+ufunc_smirnov_data[2] = &ufunc_smirnov_ptr[2*2]
+smirnov = np.PyUFunc_FromFuncAndData(ufunc_smirnov_loops, ufunc_smirnov_data, ufunc_smirnov_types, 3, 2, 1, 0, "smirnov", ufunc_smirnov_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_smirnovi_loops[3]
+cdef void *ufunc_smirnovi_ptr[6]
+cdef void *ufunc_smirnovi_data[3]
+cdef char ufunc_smirnovi_types[9]
+cdef char *ufunc_smirnovi_doc = (
+    "smirnovi(n, p, out=None)\n"
+    "\n"
+    "Inverse to `smirnov`\n"
+    "\n"
+    "Returns `d` such that ``smirnov(n, d) == p``, the critical value\n"
+    "corresponding to `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : int\n"
+    "  Number of samples\n"
+    "p : float array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The value(s) of smirnovi(n, p), the critical values.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "smirnov : The Survival Function (SF) for the distribution\n"
+    "scipy.stats.ksone : Provides the functionality as a continuous distribution\n"
+    "kolmogorov, kolmogi : Functions for the two-sided distribution\n"
+    "scipy.stats.kstwobign : Two-sided Kolmogorov-Smirnov distribution, large n\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "`smirnov` is used by `stats.kstest` in the application of the\n"
+    "Kolmogorov-Smirnov Goodness of Fit test. For historical reasons this\n"
+    "function is exposed in `scpy.special`, but the recommended way to achieve\n"
+    "the most accurate CDF/SF/PDF/PPF/ISF computations is to use the\n"
+    "`stats.ksone` distribution.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> from scipy.special import smirnovi, smirnov\n"
+    "\n"
+    ">>> n = 24\n"
+    ">>> deviations = [0.1, 0.2, 0.3]\n"
+    "\n"
+    "Use `smirnov` to compute the complementary CDF of the Smirnov\n"
+    "distribution for the given number of samples and deviations.\n"
+    "\n"
+    ">>> p = smirnov(n, deviations)\n"
+    ">>> p\n"
+    "array([0.58105083, 0.12826832, 0.01032231])\n"
+    "\n"
+    "The inverse function ``smirnovi(n, p)`` returns ``deviations``.\n"
+    "\n"
+    ">>> smirnovi(n, p)\n"
+    "array([0.1, 0.2, 0.3])")
+ufunc_smirnovi_loops[0] = loop_d_pd__As_pd_d
+ufunc_smirnovi_loops[1] = loop_d_dd__As_ff_f
+ufunc_smirnovi_loops[2] = loop_d_dd__As_dd_d
+ufunc_smirnovi_types[0] = NPY_INTP
+ufunc_smirnovi_types[1] = NPY_DOUBLE
+ufunc_smirnovi_types[2] = NPY_DOUBLE
+ufunc_smirnovi_types[3] = NPY_FLOAT
+ufunc_smirnovi_types[4] = NPY_FLOAT
+ufunc_smirnovi_types[5] = NPY_FLOAT
+ufunc_smirnovi_types[6] = NPY_DOUBLE
+ufunc_smirnovi_types[7] = NPY_DOUBLE
+ufunc_smirnovi_types[8] = NPY_DOUBLE
+ufunc_smirnovi_ptr[2*0] = _func_cephes_smirnovi_wrap
+ufunc_smirnovi_ptr[2*0+1] = ("smirnovi")
+ufunc_smirnovi_ptr[2*1] = _func_smirnovi_unsafe
+ufunc_smirnovi_ptr[2*1+1] = ("smirnovi")
+ufunc_smirnovi_ptr[2*2] = _func_smirnovi_unsafe
+ufunc_smirnovi_ptr[2*2+1] = ("smirnovi")
+ufunc_smirnovi_data[0] = &ufunc_smirnovi_ptr[2*0]
+ufunc_smirnovi_data[1] = &ufunc_smirnovi_ptr[2*1]
+ufunc_smirnovi_data[2] = &ufunc_smirnovi_ptr[2*2]
+smirnovi = np.PyUFunc_FromFuncAndData(ufunc_smirnovi_loops, ufunc_smirnovi_data, ufunc_smirnovi_types, 3, 2, 1, 0, "smirnovi", ufunc_smirnovi_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_spence_loops[4]
+cdef void *ufunc_spence_ptr[8]
+cdef void *ufunc_spence_data[4]
+cdef char ufunc_spence_types[8]
+cdef char *ufunc_spence_doc = (
+    "spence(z, out=None)\n"
+    "\n"
+    "Spence's function, also known as the dilogarithm.\n"
+    "\n"
+    "It is defined to be\n"
+    "\n"
+    ".. math::\n"
+    "  \\int_1^z \\frac{\\log(t)}{1 - t}dt\n"
+    "\n"
+    "for complex :math:`z`, where the contour of integration is taken\n"
+    "to avoid the branch cut of the logarithm. Spence's function is\n"
+    "analytic everywhere except the negative real axis where it has a\n"
+    "branch cut.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    Points at which to evaluate Spence's function\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "s : scalar or ndarray\n"
+    "    Computed values of Spence's function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "There is a different convention which defines Spence's function by\n"
+    "the integral\n"
+    "\n"
+    ".. math::\n"
+    "  -\\int_0^z \\frac{\\log(1 - t)}{t}dt;\n"
+    "\n"
+    "this is our ``spence(1 - z)``.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import spence\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    "The function is defined for complex inputs:\n"
+    "\n"
+    ">>> spence([1-1j, 1.5+2j, 3j, -10-5j])\n"
+    "array([-0.20561676+0.91596559j, -0.86766909-1.39560134j,\n"
+    "       -0.59422064-2.49129918j, -1.14044398+6.80075924j])\n"
+    "\n"
+    "For complex inputs on the branch cut, which is the negative real axis,\n"
+    "the function returns the limit for ``z`` with positive imaginary part.\n"
+    "For example, in the following, note the sign change of the imaginary\n"
+    "part of the output for ``z = -2`` and ``z = -2 - 1e-8j``:\n"
+    "\n"
+    ">>> spence([-2 + 1e-8j, -2, -2 - 1e-8j])\n"
+    "array([2.32018041-3.45139229j, 2.32018042-3.4513923j ,\n"
+    "       2.32018041+3.45139229j])\n"
+    "\n"
+    "The function returns ``nan`` for real inputs on the branch cut:\n"
+    "\n"
+    ">>> spence(-1.5)\n"
+    "nan\n"
+    "\n"
+    "Verify some particular values: ``spence(0) = pi**2/6``,\n"
+    "``spence(1) = 0`` and ``spence(2) = -pi**2/12``.\n"
+    "\n"
+    ">>> spence([0, 1, 2])\n"
+    "array([ 1.64493407,  0.        , -0.82246703])\n"
+    ">>> np.pi**2/6, -np.pi**2/12\n"
+    "(1.6449340668482264, -0.8224670334241132)\n"
+    "\n"
+    "Verify the identity::\n"
+    "\n"
+    "    spence(z) + spence(1 - z) = pi**2/6 - log(z)*log(1 - z)\n"
+    "\n"
+    ">>> z = 3 + 4j\n"
+    ">>> spence(z) + spence(1 - z)\n"
+    "(-2.6523186143876067+1.8853470951513935j)\n"
+    ">>> np.pi**2/6 - np.log(z)*np.log(1 - z)\n"
+    "(-2.652318614387606+1.885347095151394j)\n"
+    "\n"
+    "Plot the function for positive real input.\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(0, 6, 400)\n"
+    ">>> ax.plot(x, spence(x))\n"
+    ">>> ax.grid()\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.set_title('spence(x)')\n"
+    ">>> plt.show()")
+ufunc_spence_loops[0] = loop_d_d__As_f_f
+ufunc_spence_loops[1] = loop_d_d__As_d_d
+ufunc_spence_loops[2] = loop_D_D__As_F_F
+ufunc_spence_loops[3] = loop_D_D__As_D_D
+ufunc_spence_types[0] = NPY_FLOAT
+ufunc_spence_types[1] = NPY_FLOAT
+ufunc_spence_types[2] = NPY_DOUBLE
+ufunc_spence_types[3] = NPY_DOUBLE
+ufunc_spence_types[4] = NPY_CFLOAT
+ufunc_spence_types[5] = NPY_CFLOAT
+ufunc_spence_types[6] = NPY_CDOUBLE
+ufunc_spence_types[7] = NPY_CDOUBLE
+ufunc_spence_ptr[2*0] = _func_cephes_spence
+ufunc_spence_ptr[2*0+1] = ("spence")
+ufunc_spence_ptr[2*1] = _func_cephes_spence
+ufunc_spence_ptr[2*1+1] = ("spence")
+ufunc_spence_ptr[2*2] = _func_cspence
+ufunc_spence_ptr[2*2+1] = ("spence")
+ufunc_spence_ptr[2*3] = _func_cspence
+ufunc_spence_ptr[2*3+1] = ("spence")
+ufunc_spence_data[0] = &ufunc_spence_ptr[2*0]
+ufunc_spence_data[1] = &ufunc_spence_ptr[2*1]
+ufunc_spence_data[2] = &ufunc_spence_ptr[2*2]
+ufunc_spence_data[3] = &ufunc_spence_ptr[2*3]
+spence = np.PyUFunc_FromFuncAndData(ufunc_spence_loops, ufunc_spence_data, ufunc_spence_types, 4, 1, 1, 0, "spence", ufunc_spence_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_stdtr_loops[2]
+cdef void *ufunc_stdtr_ptr[4]
+cdef void *ufunc_stdtr_data[2]
+cdef char ufunc_stdtr_types[6]
+cdef char *ufunc_stdtr_doc = (
+    "stdtr(df, t, out=None)\n"
+    "\n"
+    "Student t distribution cumulative distribution function\n"
+    "\n"
+    "Returns the integral:\n"
+    "\n"
+    ".. math::\n"
+    "    \\frac{\\Gamma((df+1)/2)}{\\sqrt{\\pi df} \\Gamma(df/2)}\n"
+    "    \\int_{-\\infty}^t (1+x^2/df)^{-(df+1)/2}\\, dx\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom\n"
+    "t : array_like\n"
+    "    Upper bound of the integral\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the Student t CDF at t\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "stdtridf : inverse of stdtr with respect to `df`\n"
+    "stdtrit : inverse of stdtr with respect to `t`\n"
+    "scipy.stats.t : student t distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The student t distribution is also available as `scipy.stats.t`.\n"
+    "Calling `stdtr` directly can improve performance compared to the\n"
+    "``cdf`` method of `scipy.stats.t` (see last example below).\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function for ``df=3`` at ``t=1``.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import stdtr\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> stdtr(3, 1)\n"
+    "0.8044988905221148\n"
+    "\n"
+    "Plot the function for three different degrees of freedom.\n"
+    "\n"
+    ">>> x = np.linspace(-10, 10, 1000)\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> parameters = [(1, \"solid\"), (3, \"dashed\"), (10, \"dotted\")]\n"
+    ">>> for (df, linestyle) in parameters:\n"
+    "...     ax.plot(x, stdtr(df, x), ls=linestyle, label=f\"$df={df}$\")\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_title(\"Student t distribution cumulative distribution function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The function can be computed for several degrees of freedom at the same\n"
+    "time by providing a NumPy array or list for `df`:\n"
+    "\n"
+    ">>> stdtr([1, 2, 3], 1)\n"
+    "array([0.75      , 0.78867513, 0.80449889])\n"
+    "\n"
+    "It is possible to calculate the function at several points for several\n"
+    "different degrees of freedom simultaneously by providing arrays for `df`\n"
+    "and `t` with shapes compatible for broadcasting. Compute `stdtr` at\n"
+    "4 points for 3 degrees of freedom resulting in an array of shape 3x4.\n"
+    "\n"
+    ">>> dfs = np.array([[1], [2], [3]])\n"
+    ">>> t = np.array([2, 4, 6, 8])\n"
+    ">>> dfs.shape, t.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> stdtr(dfs, t)\n"
+    "array([[0.85241638, 0.92202087, 0.94743154, 0.96041658],\n"
+    "       [0.90824829, 0.97140452, 0.98666426, 0.99236596],\n"
+    "       [0.93033702, 0.98599577, 0.99536364, 0.99796171]])\n"
+    "\n"
+    "The t distribution is also available as `scipy.stats.t`. Calling `stdtr`\n"
+    "directly can be much faster than calling the ``cdf`` method of\n"
+    "`scipy.stats.t`. To get the same results, one must use the following\n"
+    "parametrization: ``scipy.stats.t(df).cdf(x) = stdtr(df, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import t\n"
+    ">>> df, x = 3, 1\n"
+    ">>> stdtr_result = stdtr(df, x)  # this can be faster than below\n"
+    ">>> stats_result = t(df).cdf(x)\n"
+    ">>> stats_result == stdtr_result  # test that results are equal\n"
+    "True")
+ufunc_stdtr_loops[0] = loop_d_dd__As_ff_f
+ufunc_stdtr_loops[1] = loop_d_dd__As_dd_d
+ufunc_stdtr_types[0] = NPY_FLOAT
+ufunc_stdtr_types[1] = NPY_FLOAT
+ufunc_stdtr_types[2] = NPY_FLOAT
+ufunc_stdtr_types[3] = NPY_DOUBLE
+ufunc_stdtr_types[4] = NPY_DOUBLE
+ufunc_stdtr_types[5] = NPY_DOUBLE
+ufunc_stdtr_ptr[2*0] = _func_stdtr
+ufunc_stdtr_ptr[2*0+1] = ("stdtr")
+ufunc_stdtr_ptr[2*1] = _func_stdtr
+ufunc_stdtr_ptr[2*1+1] = ("stdtr")
+ufunc_stdtr_data[0] = &ufunc_stdtr_ptr[2*0]
+ufunc_stdtr_data[1] = &ufunc_stdtr_ptr[2*1]
+stdtr = np.PyUFunc_FromFuncAndData(ufunc_stdtr_loops, ufunc_stdtr_data, ufunc_stdtr_types, 2, 2, 1, 0, "stdtr", ufunc_stdtr_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_stdtridf_loops[2]
+cdef void *ufunc_stdtridf_ptr[4]
+cdef void *ufunc_stdtridf_data[2]
+cdef char ufunc_stdtridf_types[6]
+cdef char *ufunc_stdtridf_doc = (
+    "stdtridf(p, t, out=None)\n"
+    "\n"
+    "Inverse of `stdtr` vs df\n"
+    "\n"
+    "Returns the argument df such that stdtr(df, t) is equal to `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "t : array_like\n"
+    "    Upper bound of the integral\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "df : scalar or ndarray\n"
+    "    Value of `df` such that ``stdtr(df, t) == p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "stdtr : Student t CDF\n"
+    "stdtrit : inverse of stdtr with respect to `t`\n"
+    "scipy.stats.t : Student t distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Compute the student t cumulative distribution function for one\n"
+    "parameter set.\n"
+    "\n"
+    ">>> from scipy.special import stdtr, stdtridf\n"
+    ">>> df, x = 5, 2\n"
+    ">>> cdf_value = stdtr(df, x)\n"
+    ">>> cdf_value\n"
+    "0.9490302605850709\n"
+    "\n"
+    "Verify that `stdtridf` recovers the original value for `df` given\n"
+    "the CDF value and `x`.\n"
+    "\n"
+    ">>> stdtridf(cdf_value, x)\n"
+    "5.0")
+ufunc_stdtridf_loops[0] = loop_d_dd__As_ff_f
+ufunc_stdtridf_loops[1] = loop_d_dd__As_dd_d
+ufunc_stdtridf_types[0] = NPY_FLOAT
+ufunc_stdtridf_types[1] = NPY_FLOAT
+ufunc_stdtridf_types[2] = NPY_FLOAT
+ufunc_stdtridf_types[3] = NPY_DOUBLE
+ufunc_stdtridf_types[4] = NPY_DOUBLE
+ufunc_stdtridf_types[5] = NPY_DOUBLE
+ufunc_stdtridf_ptr[2*0] = _func_stdtridf
+ufunc_stdtridf_ptr[2*0+1] = ("stdtridf")
+ufunc_stdtridf_ptr[2*1] = _func_stdtridf
+ufunc_stdtridf_ptr[2*1+1] = ("stdtridf")
+ufunc_stdtridf_data[0] = &ufunc_stdtridf_ptr[2*0]
+ufunc_stdtridf_data[1] = &ufunc_stdtridf_ptr[2*1]
+stdtridf = np.PyUFunc_FromFuncAndData(ufunc_stdtridf_loops, ufunc_stdtridf_data, ufunc_stdtridf_types, 2, 2, 1, 0, "stdtridf", ufunc_stdtridf_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_stdtrit_loops[2]
+cdef void *ufunc_stdtrit_ptr[4]
+cdef void *ufunc_stdtrit_data[2]
+cdef char ufunc_stdtrit_types[6]
+cdef char *ufunc_stdtrit_doc = (
+    "stdtrit(df, p, out=None)\n"
+    "\n"
+    "The `p`-th quantile of the student t distribution.\n"
+    "\n"
+    "This function is the inverse of the student t distribution cumulative\n"
+    "distribution function (CDF), returning `t` such that `stdtr(df, t) = p`.\n"
+    "\n"
+    "Returns the argument `t` such that stdtr(df, t) is equal to `p`.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "df : array_like\n"
+    "    Degrees of freedom\n"
+    "p : array_like\n"
+    "    Probability\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "t : scalar or ndarray\n"
+    "    Value of `t` such that ``stdtr(df, t) == p``\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "stdtr : Student t CDF\n"
+    "stdtridf : inverse of stdtr with respect to `df`\n"
+    "scipy.stats.t : Student t distribution\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The student t distribution is also available as `scipy.stats.t`. Calling\n"
+    "`stdtrit` directly can improve performance compared to the ``ppf``\n"
+    "method of `scipy.stats.t` (see last example below).\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "`stdtrit` represents the inverse of the student t distribution CDF which\n"
+    "is available as `stdtr`. Here, we calculate the CDF for ``df`` at\n"
+    "``x=1``. `stdtrit` then returns ``1`` up to floating point errors\n"
+    "given the same value for `df` and the computed CDF value.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import stdtr, stdtrit\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> df = 3\n"
+    ">>> x = 1\n"
+    ">>> cdf_value = stdtr(df, x)\n"
+    ">>> stdtrit(df, cdf_value)\n"
+    "0.9999999994418539\n"
+    "\n"
+    "Plot the function for three different degrees of freedom.\n"
+    "\n"
+    ">>> x = np.linspace(0, 1, 1000)\n"
+    ">>> parameters = [(1, \"solid\"), (2, \"dashed\"), (5, \"dotted\")]\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> for (df, linestyle) in parameters:\n"
+    "...     ax.plot(x, stdtrit(df, x), ls=linestyle, label=f\"$df={df}$\")\n"
+    ">>> ax.legend()\n"
+    ">>> ax.set_ylim(-10, 10)\n"
+    ">>> ax.set_title(\"Student t distribution quantile function\")\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The function can be computed for several degrees of freedom at the same\n"
+    "time by providing a NumPy array or list for `df`:\n"
+    "\n"
+    ">>> stdtrit([1, 2, 3], 0.7)\n"
+    "array([0.72654253, 0.6172134 , 0.58438973])\n"
+    "\n"
+    "It is possible to calculate the function at several points for several\n"
+    "different degrees of freedom simultaneously by providing arrays for `df`\n"
+    "and `p` with shapes compatible for broadcasting. Compute `stdtrit` at\n"
+    "4 points for 3 degrees of freedom resulting in an array of shape 3x4.\n"
+    "\n"
+    ">>> dfs = np.array([[1], [2], [3]])\n"
+    ">>> p = np.array([0.2, 0.4, 0.7, 0.8])\n"
+    ">>> dfs.shape, p.shape\n"
+    "((3, 1), (4,))\n"
+    "\n"
+    ">>> stdtrit(dfs, p)\n"
+    "array([[-1.37638192, -0.3249197 ,  0.72654253,  1.37638192],\n"
+    "       [-1.06066017, -0.28867513,  0.6172134 ,  1.06066017],\n"
+    "       [-0.97847231, -0.27667066,  0.58438973,  0.97847231]])\n"
+    "\n"
+    "The t distribution is also available as `scipy.stats.t`. Calling `stdtrit`\n"
+    "directly can be much faster than calling the ``ppf`` method of\n"
+    "`scipy.stats.t`. To get the same results, one must use the following\n"
+    "parametrization: ``scipy.stats.t(df).ppf(x) = stdtrit(df, x)``.\n"
+    "\n"
+    ">>> from scipy.stats import t\n"
+    ">>> df, x = 3, 0.5\n"
+    ">>> stdtrit_result = stdtrit(df, x)  # this can be faster than below\n"
+    ">>> stats_result = t(df).ppf(x)\n"
+    ">>> stats_result == stdtrit_result  # test that results are equal\n"
+    "True")
+ufunc_stdtrit_loops[0] = loop_d_dd__As_ff_f
+ufunc_stdtrit_loops[1] = loop_d_dd__As_dd_d
+ufunc_stdtrit_types[0] = NPY_FLOAT
+ufunc_stdtrit_types[1] = NPY_FLOAT
+ufunc_stdtrit_types[2] = NPY_FLOAT
+ufunc_stdtrit_types[3] = NPY_DOUBLE
+ufunc_stdtrit_types[4] = NPY_DOUBLE
+ufunc_stdtrit_types[5] = NPY_DOUBLE
+ufunc_stdtrit_ptr[2*0] = _func_stdtrit
+ufunc_stdtrit_ptr[2*0+1] = ("stdtrit")
+ufunc_stdtrit_ptr[2*1] = _func_stdtrit
+ufunc_stdtrit_ptr[2*1+1] = ("stdtrit")
+ufunc_stdtrit_data[0] = &ufunc_stdtrit_ptr[2*0]
+ufunc_stdtrit_data[1] = &ufunc_stdtrit_ptr[2*1]
+stdtrit = np.PyUFunc_FromFuncAndData(ufunc_stdtrit_loops, ufunc_stdtrit_data, ufunc_stdtrit_types, 2, 2, 1, 0, "stdtrit", ufunc_stdtrit_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_tklmbda_loops[2]
+cdef void *ufunc_tklmbda_ptr[4]
+cdef void *ufunc_tklmbda_data[2]
+cdef char ufunc_tklmbda_types[6]
+cdef char *ufunc_tklmbda_doc = (
+    "tklmbda(x, lmbda, out=None)\n"
+    "\n"
+    "Cumulative distribution function of the Tukey lambda distribution.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x, lmbda : array_like\n"
+    "    Parameters\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "cdf : scalar or ndarray\n"
+    "    Value of the Tukey lambda CDF\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "scipy.stats.tukeylambda : Tukey lambda distribution\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> from scipy.special import tklmbda, expit\n"
+    "\n"
+    "Compute the cumulative distribution function (CDF) of the Tukey lambda\n"
+    "distribution at several ``x`` values for `lmbda` = -1.5.\n"
+    "\n"
+    ">>> x = np.linspace(-2, 2, 9)\n"
+    ">>> x\n"
+    "array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])\n"
+    ">>> tklmbda(x, -1.5)\n"
+    "array([0.34688734, 0.3786554 , 0.41528805, 0.45629737, 0.5       ,\n"
+    "       0.54370263, 0.58471195, 0.6213446 , 0.65311266])\n"
+    "\n"
+    "When `lmbda` is 0, the function is the logistic sigmoid function,\n"
+    "which is implemented in `scipy.special` as `expit`.\n"
+    "\n"
+    ">>> tklmbda(x, 0)\n"
+    "array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,\n"
+    "       0.62245933, 0.73105858, 0.81757448, 0.88079708])\n"
+    ">>> expit(x)\n"
+    "array([0.11920292, 0.18242552, 0.26894142, 0.37754067, 0.5       ,\n"
+    "       0.62245933, 0.73105858, 0.81757448, 0.88079708])\n"
+    "\n"
+    "When `lmbda` is 1, the Tukey lambda distribution is uniform on the\n"
+    "interval [-1, 1], so the CDF increases linearly.\n"
+    "\n"
+    ">>> t = np.linspace(-1, 1, 9)\n"
+    ">>> tklmbda(t, 1)\n"
+    "array([0.   , 0.125, 0.25 , 0.375, 0.5  , 0.625, 0.75 , 0.875, 1.   ])\n"
+    "\n"
+    "In the following, we generate plots for several values of `lmbda`.\n"
+    "\n"
+    "The first figure shows graphs for `lmbda` <= 0.\n"
+    "\n"
+    ">>> styles = ['-', '-.', '--', ':']\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(-12, 12, 500)\n"
+    ">>> for k, lmbda in enumerate([-1.0, -0.5, 0.0]):\n"
+    "...     y = tklmbda(x, lmbda)\n"
+    "...     ax.plot(x, y, styles[k], label=rf'$\\lambda$ = {lmbda:-4.1f}')\n"
+    "\n"
+    ">>> ax.set_title(r'tklmbda(x, $\\lambda$)')\n"
+    ">>> ax.set_label('x')\n"
+    ">>> ax.legend(framealpha=1, shadow=True)\n"
+    ">>> ax.grid(True)\n"
+    "\n"
+    "The second figure shows graphs for `lmbda` > 0.  The dots in the\n"
+    "graphs show the bounds of the support of the distribution.\n"
+    "\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(-4.2, 4.2, 500)\n"
+    ">>> lmbdas = [0.25, 0.5, 1.0, 1.5]\n"
+    ">>> for k, lmbda in enumerate(lmbdas):\n"
+    "...     y = tklmbda(x, lmbda)\n"
+    "...     ax.plot(x, y, styles[k], label=fr'$\\lambda$ = {lmbda}')\n"
+    "\n"
+    ">>> ax.set_prop_cycle(None)\n"
+    ">>> for lmbda in lmbdas:\n"
+    "...     ax.plot([-1/lmbda, 1/lmbda], [0, 1], '.', ms=8)\n"
+    "\n"
+    ">>> ax.set_title(r'tklmbda(x, $\\lambda$)')\n"
+    ">>> ax.set_xlabel('x')\n"
+    ">>> ax.legend(framealpha=1, shadow=True)\n"
+    ">>> ax.grid(True)\n"
+    "\n"
+    ">>> plt.tight_layout()\n"
+    ">>> plt.show()\n"
+    "\n"
+    "The CDF of the Tukey lambda distribution is also implemented as the\n"
+    "``cdf`` method of `scipy.stats.tukeylambda`.  In the following,\n"
+    "``tukeylambda.cdf(x, -0.5)`` and ``tklmbda(x, -0.5)`` compute the\n"
+    "same values:\n"
+    "\n"
+    ">>> from scipy.stats import tukeylambda\n"
+    ">>> x = np.linspace(-2, 2, 9)\n"
+    "\n"
+    ">>> tukeylambda.cdf(x, -0.5)\n"
+    "array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,\n"
+    "       0.58671839, 0.66458323, 0.72906142, 0.78004843])\n"
+    "\n"
+    ">>> tklmbda(x, -0.5)\n"
+    "array([0.21995157, 0.27093858, 0.33541677, 0.41328161, 0.5       ,\n"
+    "       0.58671839, 0.66458323, 0.72906142, 0.78004843])\n"
+    "\n"
+    "The implementation in ``tukeylambda`` also provides location and scale\n"
+    "parameters, and other methods such as ``pdf()`` (the probability\n"
+    "density function) and ``ppf()`` (the inverse of the CDF), so for\n"
+    "working with the Tukey lambda distribution, ``tukeylambda`` is more\n"
+    "generally useful.  The primary advantage of ``tklmbda`` is that it is\n"
+    "significantly faster than ``tukeylambda.cdf``.")
+ufunc_tklmbda_loops[0] = loop_d_dd__As_ff_f
+ufunc_tklmbda_loops[1] = loop_d_dd__As_dd_d
+ufunc_tklmbda_types[0] = NPY_FLOAT
+ufunc_tklmbda_types[1] = NPY_FLOAT
+ufunc_tklmbda_types[2] = NPY_FLOAT
+ufunc_tklmbda_types[3] = NPY_DOUBLE
+ufunc_tklmbda_types[4] = NPY_DOUBLE
+ufunc_tklmbda_types[5] = NPY_DOUBLE
+ufunc_tklmbda_ptr[2*0] = _func_xsf_tukeylambdacdf
+ufunc_tklmbda_ptr[2*0+1] = ("tklmbda")
+ufunc_tklmbda_ptr[2*1] = _func_xsf_tukeylambdacdf
+ufunc_tklmbda_ptr[2*1+1] = ("tklmbda")
+ufunc_tklmbda_data[0] = &ufunc_tklmbda_ptr[2*0]
+ufunc_tklmbda_data[1] = &ufunc_tklmbda_ptr[2*1]
+tklmbda = np.PyUFunc_FromFuncAndData(ufunc_tklmbda_loops, ufunc_tklmbda_data, ufunc_tklmbda_types, 2, 2, 1, 0, "tklmbda", ufunc_tklmbda_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_voigt_profile_loops[2]
+cdef void *ufunc_voigt_profile_ptr[4]
+cdef void *ufunc_voigt_profile_data[2]
+cdef char ufunc_voigt_profile_types[8]
+cdef char *ufunc_voigt_profile_doc = (
+    "voigt_profile(x, sigma, gamma, out=None)\n"
+    "\n"
+    "Voigt profile.\n"
+    "\n"
+    "The Voigt profile is a convolution of a 1-D Normal distribution with\n"
+    "standard deviation ``sigma`` and a 1-D Cauchy distribution with half-width at\n"
+    "half-maximum ``gamma``.\n"
+    "\n"
+    "If ``sigma = 0``, PDF of Cauchy distribution is returned.\n"
+    "Conversely, if ``gamma = 0``, PDF of Normal distribution is returned.\n"
+    "If ``sigma = gamma = 0``, the return value is ``Inf`` for ``x = 0``,\n"
+    "and ``0`` for all other ``x``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Real argument\n"
+    "sigma : array_like\n"
+    "    The standard deviation of the Normal distribution part\n"
+    "gamma : array_like\n"
+    "    The half-width at half-maximum of the Cauchy distribution part\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    The Voigt profile at the given arguments\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "wofz : Faddeeva function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "It can be expressed in terms of Faddeeva function\n"
+    "\n"
+    ".. math:: V(x; \\sigma, \\gamma) = \\frac{Re[w(z)]}{\\sigma\\sqrt{2\\pi}},\n"
+    ".. math:: z = \\frac{x + i\\gamma}{\\sqrt{2}\\sigma}\n"
+    "\n"
+    "where :math:`w(z)` is the Faddeeva function.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] https://en.wikipedia.org/wiki/Voigt_profile\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Calculate the function at point 2 for ``sigma=1`` and ``gamma=1``.\n"
+    "\n"
+    ">>> from scipy.special import voigt_profile\n"
+    ">>> import numpy as np\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> voigt_profile(2, 1., 1.)\n"
+    "0.09071519942627544\n"
+    "\n"
+    "Calculate the function at several points by providing a NumPy array\n"
+    "for `x`.\n"
+    "\n"
+    ">>> values = np.array([-2., 0., 5])\n"
+    ">>> voigt_profile(values, 1., 1.)\n"
+    "array([0.0907152 , 0.20870928, 0.01388492])\n"
+    "\n"
+    "Plot the function for different parameter sets.\n"
+    "\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> x = np.linspace(-10, 10, 500)\n"
+    ">>> parameters_list = [(1.5, 0., \"solid\"), (1.3, 0.5, \"dashed\"),\n"
+    "...                    (0., 1.8, \"dotted\"), (1., 1., \"dashdot\")]\n"
+    ">>> for params in parameters_list:\n"
+    "...     sigma, gamma, linestyle = params\n"
+    "...     voigt = voigt_profile(x, sigma, gamma)\n"
+    "...     ax.plot(x, voigt, label=rf\"$\\sigma={sigma},\\, \\gamma={gamma}$\",\n"
+    "...             ls=linestyle)\n"
+    ">>> ax.legend()\n"
+    ">>> plt.show()\n"
+    "\n"
+    "Verify visually that the Voigt profile indeed arises as the convolution\n"
+    "of a normal and a Cauchy distribution.\n"
+    "\n"
+    ">>> from scipy.signal import convolve\n"
+    ">>> x, dx = np.linspace(-10, 10, 500, retstep=True)\n"
+    ">>> def gaussian(x, sigma):\n"
+    "...     return np.exp(-0.5 * x**2/sigma**2)/(sigma * np.sqrt(2*np.pi))\n"
+    ">>> def cauchy(x, gamma):\n"
+    "...     return gamma/(np.pi * (np.square(x)+gamma**2))\n"
+    ">>> sigma = 2\n"
+    ">>> gamma = 1\n"
+    ">>> gauss_profile = gaussian(x, sigma)\n"
+    ">>> cauchy_profile = cauchy(x, gamma)\n"
+    ">>> convolved = dx * convolve(cauchy_profile, gauss_profile, mode=\"same\")\n"
+    ">>> voigt = voigt_profile(x, sigma, gamma)\n"
+    ">>> fig, ax = plt.subplots(figsize=(8, 8))\n"
+    ">>> ax.plot(x, gauss_profile, label=\"Gauss: $G$\", c='b')\n"
+    ">>> ax.plot(x, cauchy_profile, label=\"Cauchy: $C$\", c='y', ls=\"dashed\")\n"
+    ">>> xx = 0.5*(x[1:] + x[:-1])  # midpoints\n"
+    ">>> ax.plot(xx, convolved[1:], label=\"Convolution: $G * C$\", ls='dashdot',\n"
+    "...         c='k')\n"
+    ">>> ax.plot(x, voigt, label=\"Voigt\", ls='dotted', c='r')\n"
+    ">>> ax.legend()\n"
+    ">>> plt.show()")
+ufunc_voigt_profile_loops[0] = loop_d_ddd__As_fff_f
+ufunc_voigt_profile_loops[1] = loop_d_ddd__As_ddd_d
+ufunc_voigt_profile_types[0] = NPY_FLOAT
+ufunc_voigt_profile_types[1] = NPY_FLOAT
+ufunc_voigt_profile_types[2] = NPY_FLOAT
+ufunc_voigt_profile_types[3] = NPY_FLOAT
+ufunc_voigt_profile_types[4] = NPY_DOUBLE
+ufunc_voigt_profile_types[5] = NPY_DOUBLE
+ufunc_voigt_profile_types[6] = NPY_DOUBLE
+ufunc_voigt_profile_types[7] = NPY_DOUBLE
+ufunc_voigt_profile_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_voigt_profile
+ufunc_voigt_profile_ptr[2*0+1] = ("voigt_profile")
+ufunc_voigt_profile_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_voigt_profile
+ufunc_voigt_profile_ptr[2*1+1] = ("voigt_profile")
+ufunc_voigt_profile_data[0] = &ufunc_voigt_profile_ptr[2*0]
+ufunc_voigt_profile_data[1] = &ufunc_voigt_profile_ptr[2*1]
+voigt_profile = np.PyUFunc_FromFuncAndData(ufunc_voigt_profile_loops, ufunc_voigt_profile_data, ufunc_voigt_profile_types, 2, 3, 1, 0, "voigt_profile", ufunc_voigt_profile_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_wofz_loops[2]
+cdef void *ufunc_wofz_ptr[4]
+cdef void *ufunc_wofz_data[2]
+cdef char ufunc_wofz_types[4]
+cdef char *ufunc_wofz_doc = (
+    "wofz(z, out=None)\n"
+    "\n"
+    "Faddeeva function\n"
+    "\n"
+    "Returns the value of the Faddeeva function for complex argument::\n"
+    "\n"
+    "    exp(-z**2) * erfc(-i*z)\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    complex argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "scalar or ndarray\n"
+    "    Value of the Faddeeva function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "dawsn, erf, erfc, erfcx, erfi\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Steven G. Johnson, Faddeeva W function implementation.\n"
+    "   http://ab-initio.mit.edu/Faddeeva\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy import special\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    "\n"
+    ">>> x = np.linspace(-3, 3)\n"
+    ">>> z = special.wofz(x)\n"
+    "\n"
+    ">>> plt.plot(x, z.real, label='wofz(x).real')\n"
+    ">>> plt.plot(x, z.imag, label='wofz(x).imag')\n"
+    ">>> plt.xlabel('$x$')\n"
+    ">>> plt.legend(framealpha=1, shadow=True)\n"
+    ">>> plt.grid(alpha=0.25)\n"
+    ">>> plt.show()")
+ufunc_wofz_loops[0] = loop_D_D__As_F_F
+ufunc_wofz_loops[1] = loop_D_D__As_D_D
+ufunc_wofz_types[0] = NPY_CFLOAT
+ufunc_wofz_types[1] = NPY_CFLOAT
+ufunc_wofz_types[2] = NPY_CDOUBLE
+ufunc_wofz_types[3] = NPY_CDOUBLE
+ufunc_wofz_ptr[2*0] = scipy.special._ufuncs_cxx._export_faddeeva_w
+ufunc_wofz_ptr[2*0+1] = ("wofz")
+ufunc_wofz_ptr[2*1] = scipy.special._ufuncs_cxx._export_faddeeva_w
+ufunc_wofz_ptr[2*1+1] = ("wofz")
+ufunc_wofz_data[0] = &ufunc_wofz_ptr[2*0]
+ufunc_wofz_data[1] = &ufunc_wofz_ptr[2*1]
+wofz = np.PyUFunc_FromFuncAndData(ufunc_wofz_loops, ufunc_wofz_data, ufunc_wofz_types, 2, 1, 1, 0, "wofz", ufunc_wofz_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_wrightomega_loops[4]
+cdef void *ufunc_wrightomega_ptr[8]
+cdef void *ufunc_wrightomega_data[4]
+cdef char ufunc_wrightomega_types[8]
+cdef char *ufunc_wrightomega_doc = (
+    "wrightomega(z, out=None)\n"
+    "\n"
+    "Wright Omega function.\n"
+    "\n"
+    "Defined as the solution to\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\omega + \\log(\\omega) = z\n"
+    "\n"
+    "where :math:`\\log` is the principal branch of the complex logarithm.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "z : array_like\n"
+    "    Points at which to evaluate the Wright Omega function\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function values\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "omega : scalar or ndarray\n"
+    "    Values of the Wright Omega function\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "lambertw : The Lambert W function\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    ".. versionadded:: 0.19.0\n"
+    "\n"
+    "The function can also be defined as\n"
+    "\n"
+    ".. math::\n"
+    "\n"
+    "    \\omega(z) = W_{K(z)}(e^z)\n"
+    "\n"
+    "where :math:`K(z) = \\lceil (\\Im(z) - \\pi)/(2\\pi) \\rceil` is the\n"
+    "unwinding number and :math:`W` is the Lambert W function.\n"
+    "\n"
+    "The implementation here is taken from [1]_.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Lawrence, Corless, and Jeffrey, \"Algorithm 917: Complex\n"
+    "       Double-Precision Evaluation of the Wright :math:`\\omega`\n"
+    "       Function.\" ACM Transactions on Mathematical Software,\n"
+    "       2012. :doi:`10.1145/2168773.2168779`.\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import wrightomega, lambertw\n"
+    "\n"
+    ">>> wrightomega([-2, -1, 0, 1, 2])\n"
+    "array([0.12002824, 0.27846454, 0.56714329, 1.        , 1.5571456 ])\n"
+    "\n"
+    "Complex input:\n"
+    "\n"
+    ">>> wrightomega(3 + 5j)\n"
+    "(1.5804428632097158+3.8213626783287937j)\n"
+    "\n"
+    "Verify that ``wrightomega(z)`` satisfies ``w + log(w) = z``:\n"
+    "\n"
+    ">>> w = -5 + 4j\n"
+    ">>> wrightomega(w + np.log(w))\n"
+    "(-5+4j)\n"
+    "\n"
+    "Verify the connection to ``lambertw``:\n"
+    "\n"
+    ">>> z = 0.5 + 3j\n"
+    ">>> wrightomega(z)\n"
+    "(0.0966015889280649+1.4937828458191993j)\n"
+    ">>> lambertw(np.exp(z))\n"
+    "(0.09660158892806493+1.4937828458191993j)\n"
+    "\n"
+    ">>> z = 0.5 + 4j\n"
+    ">>> wrightomega(z)\n"
+    "(-0.3362123489037213+2.282986001579032j)\n"
+    ">>> lambertw(np.exp(z), k=1)\n"
+    "(-0.33621234890372115+2.282986001579032j)")
+ufunc_wrightomega_loops[0] = loop_d_d__As_f_f
+ufunc_wrightomega_loops[1] = loop_d_d__As_d_d
+ufunc_wrightomega_loops[2] = loop_D_D__As_F_F
+ufunc_wrightomega_loops[3] = loop_D_D__As_D_D
+ufunc_wrightomega_types[0] = NPY_FLOAT
+ufunc_wrightomega_types[1] = NPY_FLOAT
+ufunc_wrightomega_types[2] = NPY_DOUBLE
+ufunc_wrightomega_types[3] = NPY_DOUBLE
+ufunc_wrightomega_types[4] = NPY_CFLOAT
+ufunc_wrightomega_types[5] = NPY_CFLOAT
+ufunc_wrightomega_types[6] = NPY_CDOUBLE
+ufunc_wrightomega_types[7] = NPY_CDOUBLE
+ufunc_wrightomega_ptr[2*0] = scipy.special._ufuncs_cxx._export_wrightomega_real
+ufunc_wrightomega_ptr[2*0+1] = ("wrightomega")
+ufunc_wrightomega_ptr[2*1] = scipy.special._ufuncs_cxx._export_wrightomega_real
+ufunc_wrightomega_ptr[2*1+1] = ("wrightomega")
+ufunc_wrightomega_ptr[2*2] = scipy.special._ufuncs_cxx._export_wrightomega
+ufunc_wrightomega_ptr[2*2+1] = ("wrightomega")
+ufunc_wrightomega_ptr[2*3] = scipy.special._ufuncs_cxx._export_wrightomega
+ufunc_wrightomega_ptr[2*3+1] = ("wrightomega")
+ufunc_wrightomega_data[0] = &ufunc_wrightomega_ptr[2*0]
+ufunc_wrightomega_data[1] = &ufunc_wrightomega_ptr[2*1]
+ufunc_wrightomega_data[2] = &ufunc_wrightomega_ptr[2*2]
+ufunc_wrightomega_data[3] = &ufunc_wrightomega_ptr[2*3]
+wrightomega = np.PyUFunc_FromFuncAndData(ufunc_wrightomega_loops, ufunc_wrightomega_data, ufunc_wrightomega_types, 4, 1, 1, 0, "wrightomega", ufunc_wrightomega_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_xlog1py_loops[4]
+cdef void *ufunc_xlog1py_ptr[8]
+cdef void *ufunc_xlog1py_data[4]
+cdef char ufunc_xlog1py_types[12]
+cdef char *ufunc_xlog1py_doc = (
+    "xlog1py(x, y, out=None)\n"
+    "\n"
+    "Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Multiplier\n"
+    "y : array_like\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "z : scalar or ndarray\n"
+    "    Computed x*log1p(y)\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "\n"
+    ".. versionadded:: 0.13.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "This example shows how the function can be used to calculate the log of\n"
+    "the probability mass function for a geometric discrete random variable.\n"
+    "The probability mass function of the geometric distribution is defined\n"
+    "as follows:\n"
+    "\n"
+    ".. math:: f(k) = (1-p)^{k-1} p\n"
+    "\n"
+    "where :math:`p` is the probability of a single success\n"
+    "and :math:`1-p` is the probability of a single failure\n"
+    "and :math:`k` is the number of trials to get the first success.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import xlog1py\n"
+    ">>> p = 0.5\n"
+    ">>> k = 100\n"
+    ">>> _pmf = np.power(1 - p, k - 1) * p\n"
+    ">>> _pmf\n"
+    "7.888609052210118e-31\n"
+    "\n"
+    "If we take k as a relatively large number the value of the probability\n"
+    "mass function can become very low. In such cases taking the log of the\n"
+    "pmf would be more suitable as the log function can change the values\n"
+    "to a scale that is more appropriate to work with.\n"
+    "\n"
+    ">>> _log_pmf = xlog1py(k - 1, -p) + np.log(p)\n"
+    ">>> _log_pmf\n"
+    "-69.31471805599453\n"
+    "\n"
+    "We can confirm that we get a value close to the original pmf value by\n"
+    "taking the exponential of the log pmf.\n"
+    "\n"
+    ">>> _orig_pmf = np.exp(_log_pmf)\n"
+    ">>> np.isclose(_pmf, _orig_pmf)\n"
+    "True")
+ufunc_xlog1py_loops[0] = loop_d_dd__As_ff_f
+ufunc_xlog1py_loops[1] = loop_d_dd__As_dd_d
+ufunc_xlog1py_loops[2] = loop_D_DD__As_FF_F
+ufunc_xlog1py_loops[3] = loop_D_DD__As_DD_D
+ufunc_xlog1py_types[0] = NPY_FLOAT
+ufunc_xlog1py_types[1] = NPY_FLOAT
+ufunc_xlog1py_types[2] = NPY_FLOAT
+ufunc_xlog1py_types[3] = NPY_DOUBLE
+ufunc_xlog1py_types[4] = NPY_DOUBLE
+ufunc_xlog1py_types[5] = NPY_DOUBLE
+ufunc_xlog1py_types[6] = NPY_CFLOAT
+ufunc_xlog1py_types[7] = NPY_CFLOAT
+ufunc_xlog1py_types[8] = NPY_CFLOAT
+ufunc_xlog1py_types[9] = NPY_CDOUBLE
+ufunc_xlog1py_types[10] = NPY_CDOUBLE
+ufunc_xlog1py_types[11] = NPY_CDOUBLE
+ufunc_xlog1py_ptr[2*0] = _func_xlog1py[double]
+ufunc_xlog1py_ptr[2*0+1] = ("xlog1py")
+ufunc_xlog1py_ptr[2*1] = _func_xlog1py[double]
+ufunc_xlog1py_ptr[2*1+1] = ("xlog1py")
+ufunc_xlog1py_ptr[2*2] = _func_xlog1py[double_complex]
+ufunc_xlog1py_ptr[2*2+1] = ("xlog1py")
+ufunc_xlog1py_ptr[2*3] = _func_xlog1py[double_complex]
+ufunc_xlog1py_ptr[2*3+1] = ("xlog1py")
+ufunc_xlog1py_data[0] = &ufunc_xlog1py_ptr[2*0]
+ufunc_xlog1py_data[1] = &ufunc_xlog1py_ptr[2*1]
+ufunc_xlog1py_data[2] = &ufunc_xlog1py_ptr[2*2]
+ufunc_xlog1py_data[3] = &ufunc_xlog1py_ptr[2*3]
+xlog1py = np.PyUFunc_FromFuncAndData(ufunc_xlog1py_loops, ufunc_xlog1py_data, ufunc_xlog1py_types, 4, 2, 1, 0, "xlog1py", ufunc_xlog1py_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_xlogy_loops[4]
+cdef void *ufunc_xlogy_ptr[8]
+cdef void *ufunc_xlogy_data[4]
+cdef char ufunc_xlogy_types[12]
+cdef char *ufunc_xlogy_doc = (
+    "xlogy(x, y, out=None)\n"
+    "\n"
+    "Compute ``x*log(y)`` so that the result is 0 if ``x = 0``.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "x : array_like\n"
+    "    Multiplier\n"
+    "y : array_like\n"
+    "    Argument\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "z : scalar or ndarray\n"
+    "    Computed x*log(y)\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "The log function used in the computation is the natural log.\n"
+    "\n"
+    ".. versionadded:: 0.13.0\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "We can use this function to calculate the binary logistic loss also\n"
+    "known as the binary cross entropy. This loss function is used for\n"
+    "binary classification problems and is defined as:\n"
+    "\n"
+    ".. math::\n"
+    "    L = 1/n * \\sum_{i=0}^n -(y_i*log(y\\_pred_i) + (1-y_i)*log(1-y\\_pred_i))\n"
+    "\n"
+    "We can define the parameters `x` and `y` as y and y_pred respectively.\n"
+    "y is the array of the actual labels which over here can be either 0 or 1.\n"
+    "y_pred is the array of the predicted probabilities with respect to\n"
+    "the positive class (1).\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> from scipy.special import xlogy\n"
+    ">>> y = np.array([0, 1, 0, 1, 1, 0])\n"
+    ">>> y_pred = np.array([0.3, 0.8, 0.4, 0.7, 0.9, 0.2])\n"
+    ">>> n = len(y)\n"
+    ">>> loss = -(xlogy(y, y_pred) + xlogy(1 - y, 1 - y_pred)).sum()\n"
+    ">>> loss /= n\n"
+    ">>> loss\n"
+    "0.29597052165495025\n"
+    "\n"
+    "A lower loss is usually better as it indicates that the predictions are\n"
+    "similar to the actual labels. In this example since our predicted\n"
+    "probabilities are close to the actual labels, we get an overall loss\n"
+    "that is reasonably low and appropriate.")
+ufunc_xlogy_loops[0] = loop_d_dd__As_ff_f
+ufunc_xlogy_loops[1] = loop_d_dd__As_dd_d
+ufunc_xlogy_loops[2] = loop_D_DD__As_FF_F
+ufunc_xlogy_loops[3] = loop_D_DD__As_DD_D
+ufunc_xlogy_types[0] = NPY_FLOAT
+ufunc_xlogy_types[1] = NPY_FLOAT
+ufunc_xlogy_types[2] = NPY_FLOAT
+ufunc_xlogy_types[3] = NPY_DOUBLE
+ufunc_xlogy_types[4] = NPY_DOUBLE
+ufunc_xlogy_types[5] = NPY_DOUBLE
+ufunc_xlogy_types[6] = NPY_CFLOAT
+ufunc_xlogy_types[7] = NPY_CFLOAT
+ufunc_xlogy_types[8] = NPY_CFLOAT
+ufunc_xlogy_types[9] = NPY_CDOUBLE
+ufunc_xlogy_types[10] = NPY_CDOUBLE
+ufunc_xlogy_types[11] = NPY_CDOUBLE
+ufunc_xlogy_ptr[2*0] = _func_xlogy[double]
+ufunc_xlogy_ptr[2*0+1] = ("xlogy")
+ufunc_xlogy_ptr[2*1] = _func_xlogy[double]
+ufunc_xlogy_ptr[2*1+1] = ("xlogy")
+ufunc_xlogy_ptr[2*2] = _func_xlogy[double_complex]
+ufunc_xlogy_ptr[2*2+1] = ("xlogy")
+ufunc_xlogy_ptr[2*3] = _func_xlogy[double_complex]
+ufunc_xlogy_ptr[2*3+1] = ("xlogy")
+ufunc_xlogy_data[0] = &ufunc_xlogy_ptr[2*0]
+ufunc_xlogy_data[1] = &ufunc_xlogy_ptr[2*1]
+ufunc_xlogy_data[2] = &ufunc_xlogy_ptr[2*2]
+ufunc_xlogy_data[3] = &ufunc_xlogy_ptr[2*3]
+xlogy = np.PyUFunc_FromFuncAndData(ufunc_xlogy_loops, ufunc_xlogy_data, ufunc_xlogy_types, 4, 2, 1, 0, "xlogy", ufunc_xlogy_doc, 0)
+
+cdef np.PyUFuncGenericFunction ufunc_yn_loops[3]
+cdef void *ufunc_yn_ptr[6]
+cdef void *ufunc_yn_data[3]
+cdef char ufunc_yn_types[9]
+cdef char *ufunc_yn_doc = (
+    "yn(n, x, out=None)\n"
+    "\n"
+    "Bessel function of the second kind of integer order and real argument.\n"
+    "\n"
+    "Parameters\n"
+    "----------\n"
+    "n : array_like\n"
+    "    Order (integer).\n"
+    "x : array_like\n"
+    "    Argument (float).\n"
+    "out : ndarray, optional\n"
+    "    Optional output array for the function results\n"
+    "\n"
+    "Returns\n"
+    "-------\n"
+    "Y : scalar or ndarray\n"
+    "    Value of the Bessel function, :math:`Y_n(x)`.\n"
+    "\n"
+    "See Also\n"
+    "--------\n"
+    "yv : For real order and real or complex argument.\n"
+    "y0: faster implementation of this function for order 0\n"
+    "y1: faster implementation of this function for order 1\n"
+    "\n"
+    "Notes\n"
+    "-----\n"
+    "Wrapper for the Cephes [1]_ routine `yn`.\n"
+    "\n"
+    "The function is evaluated by forward recurrence on `n`, starting with\n"
+    "values computed by the Cephes routines `y0` and `y1`. If ``n = 0`` or 1,\n"
+    "the routine for `y0` or `y1` is called directly.\n"
+    "\n"
+    "References\n"
+    "----------\n"
+    ".. [1] Cephes Mathematical Functions Library,\n"
+    "       http://www.netlib.org/cephes/\n"
+    "\n"
+    "Examples\n"
+    "--------\n"
+    "Evaluate the function of order 0 at one point.\n"
+    "\n"
+    ">>> from scipy.special import yn\n"
+    ">>> yn(0, 1.)\n"
+    "0.08825696421567697\n"
+    "\n"
+    "Evaluate the function at one point for different orders.\n"
+    "\n"
+    ">>> yn(0, 1.), yn(1, 1.), yn(2, 1.)\n"
+    "(0.08825696421567697, -0.7812128213002888, -1.6506826068162546)\n"
+    "\n"
+    "The evaluation for different orders can be carried out in one call by\n"
+    "providing a list or NumPy array as argument for the `v` parameter:\n"
+    "\n"
+    ">>> yn([0, 1, 2], 1.)\n"
+    "array([ 0.08825696, -0.78121282, -1.65068261])\n"
+    "\n"
+    "Evaluate the function at several points for order 0 by providing an\n"
+    "array for `z`.\n"
+    "\n"
+    ">>> import numpy as np\n"
+    ">>> points = np.array([0.5, 3., 8.])\n"
+    ">>> yn(0, points)\n"
+    "array([-0.44451873,  0.37685001,  0.22352149])\n"
+    "\n"
+    "If `z` is an array, the order parameter `v` must be broadcastable to\n"
+    "the correct shape if different orders shall be computed in one call.\n"
+    "To calculate the orders 0 and 1 for an 1D array:\n"
+    "\n"
+    ">>> orders = np.array([[0], [1]])\n"
+    ">>> orders.shape\n"
+    "(2, 1)\n"
+    "\n"
+    ">>> yn(orders, points)\n"
+    "array([[-0.44451873,  0.37685001,  0.22352149],\n"
+    "       [-1.47147239,  0.32467442, -0.15806046]])\n"
+    "\n"
+    "Plot the functions of order 0 to 3 from 0 to 10.\n"
+    "\n"
+    ">>> import matplotlib.pyplot as plt\n"
+    ">>> fig, ax = plt.subplots()\n"
+    ">>> x = np.linspace(0., 10., 1000)\n"
+    ">>> for i in range(4):\n"
+    "...     ax.plot(x, yn(i, x), label=f'$Y_{i!r}$')\n"
+    ">>> ax.set_ylim(-3, 1)\n"
+    ">>> ax.legend()\n"
+    ">>> plt.show()")
+ufunc_yn_loops[0] = loop_d_pd__As_pd_d
+ufunc_yn_loops[1] = loop_d_dd__As_ff_f
+ufunc_yn_loops[2] = loop_d_dd__As_dd_d
+ufunc_yn_types[0] = NPY_INTP
+ufunc_yn_types[1] = NPY_DOUBLE
+ufunc_yn_types[2] = NPY_DOUBLE
+ufunc_yn_types[3] = NPY_FLOAT
+ufunc_yn_types[4] = NPY_FLOAT
+ufunc_yn_types[5] = NPY_FLOAT
+ufunc_yn_types[6] = NPY_DOUBLE
+ufunc_yn_types[7] = NPY_DOUBLE
+ufunc_yn_types[8] = NPY_DOUBLE
+ufunc_yn_ptr[2*0] = _func_cephes_yn_wrap
+ufunc_yn_ptr[2*0+1] = ("yn")
+ufunc_yn_ptr[2*1] = _func_yn_unsafe
+ufunc_yn_ptr[2*1+1] = ("yn")
+ufunc_yn_ptr[2*2] = _func_yn_unsafe
+ufunc_yn_ptr[2*2+1] = ("yn")
+ufunc_yn_data[0] = &ufunc_yn_ptr[2*0]
+ufunc_yn_data[1] = &ufunc_yn_ptr[2*1]
+ufunc_yn_data[2] = &ufunc_yn_ptr[2*2]
+yn = np.PyUFunc_FromFuncAndData(ufunc_yn_loops, ufunc_yn_data, ufunc_yn_types, 3, 2, 1, 0, "yn", ufunc_yn_doc, 0)
+
+from ._special_ufuncs import (_cospi, _lambertw, _scaled_exp1, _sinpi, _spherical_jn, _spherical_jn_d, _spherical_yn, _spherical_yn_d, _spherical_in, _spherical_in_d, _spherical_kn, _spherical_kn_d, airy, airye, bei, beip, ber, berp, binom, exp1, expi, expit, exprel, gamma, gammaln, hankel1, hankel1e, hankel2, hankel2e, hyp2f1, it2i0k0, it2j0y0, it2struve0, itairy, iti0k0, itj0y0, itmodstruve0, itstruve0, iv, _iv_ratio, _iv_ratio_c, ive, jv, jve, kei, keip, kelvin, ker, kerp, kv, kve, log_expit, log_wright_bessel, loggamma, logit, mathieu_a, mathieu_b, mathieu_cem, mathieu_modcem1, mathieu_modcem2, mathieu_modsem1, mathieu_modsem2, mathieu_sem, modfresnelm, modfresnelp, obl_ang1, obl_ang1_cv, obl_cv, obl_rad1, obl_rad1_cv, obl_rad2, obl_rad2_cv, pbdv, pbvv, pbwa, pro_ang1, pro_ang1_cv, pro_cv, pro_rad1, pro_rad1_cv, pro_rad2, pro_rad2_cv, psi, rgamma, sph_harm, wright_bessel, yv, yve, zetac, _zeta, sindg, cosdg, tandg, cotdg, i0, i0e, i1, i1e, k0, k0e, k1, k1e, y0, y1, j0, j1, struve, modstruve, beta, betaln, besselpoly, gammaln, gammasgn, cbrt, radian, cosm1, gammainc, gammaincinv, gammaincc, gammainccinv, fresnel, ellipe, ellipeinc, ellipk, ellipkinc, ellipkm1, ellipj, _riemann_zeta)
+
+#
+# Aliases
+#
+jn = jv
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..a2fffff86812d1a7ca547a71a19078b6d5f59716
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pxd
@@ -0,0 +1,155 @@
+from . cimport sf_error
+cdef void _set_action(sf_error.sf_error_t, sf_error.sf_action_t) noexcept nogil
+cdef void *_export_beta_pdf_float
+cdef void *_export_beta_pdf_double
+cdef void *_export_beta_ppf_float
+cdef void *_export_beta_ppf_double
+cdef void *_export_binom_cdf_float
+cdef void *_export_binom_cdf_double
+cdef void *_export_binom_isf_float
+cdef void *_export_binom_isf_double
+cdef void *_export_binom_pmf_float
+cdef void *_export_binom_pmf_double
+cdef void *_export_binom_ppf_float
+cdef void *_export_binom_ppf_double
+cdef void *_export_binom_sf_float
+cdef void *_export_binom_sf_double
+cdef void *_export_cauchy_isf_float
+cdef void *_export_cauchy_isf_double
+cdef void *_export_cauchy_ppf_float
+cdef void *_export_cauchy_ppf_double
+cdef void *_export_hypergeom_cdf_float
+cdef void *_export_hypergeom_cdf_double
+cdef void *_export_hypergeom_mean_float
+cdef void *_export_hypergeom_mean_double
+cdef void *_export_hypergeom_pmf_float
+cdef void *_export_hypergeom_pmf_double
+cdef void *_export_hypergeom_sf_float
+cdef void *_export_hypergeom_sf_double
+cdef void *_export_hypergeom_skewness_float
+cdef void *_export_hypergeom_skewness_double
+cdef void *_export_hypergeom_variance_float
+cdef void *_export_hypergeom_variance_double
+cdef void *_export_invgauss_isf_float
+cdef void *_export_invgauss_isf_double
+cdef void *_export_invgauss_ppf_float
+cdef void *_export_invgauss_ppf_double
+cdef void *_export_landau_cdf_float
+cdef void *_export_landau_cdf_double
+cdef void *_export_landau_isf_float
+cdef void *_export_landau_isf_double
+cdef void *_export_landau_pdf_float
+cdef void *_export_landau_pdf_double
+cdef void *_export_landau_ppf_float
+cdef void *_export_landau_ppf_double
+cdef void *_export_landau_sf_float
+cdef void *_export_landau_sf_double
+cdef void *_export_nbinom_cdf_float
+cdef void *_export_nbinom_cdf_double
+cdef void *_export_nbinom_isf_float
+cdef void *_export_nbinom_isf_double
+cdef void *_export_nbinom_kurtosis_excess_float
+cdef void *_export_nbinom_kurtosis_excess_double
+cdef void *_export_nbinom_mean_float
+cdef void *_export_nbinom_mean_double
+cdef void *_export_nbinom_pmf_float
+cdef void *_export_nbinom_pmf_double
+cdef void *_export_nbinom_ppf_float
+cdef void *_export_nbinom_ppf_double
+cdef void *_export_nbinom_sf_float
+cdef void *_export_nbinom_sf_double
+cdef void *_export_nbinom_skewness_float
+cdef void *_export_nbinom_skewness_double
+cdef void *_export_nbinom_variance_float
+cdef void *_export_nbinom_variance_double
+cdef void *_export_ncf_isf_float
+cdef void *_export_ncf_isf_double
+cdef void *_export_ncf_kurtosis_excess_float
+cdef void *_export_ncf_kurtosis_excess_double
+cdef void *_export_ncf_mean_float
+cdef void *_export_ncf_mean_double
+cdef void *_export_ncf_pdf_float
+cdef void *_export_ncf_pdf_double
+cdef void *_export_ncf_sf_float
+cdef void *_export_ncf_sf_double
+cdef void *_export_ncf_skewness_float
+cdef void *_export_ncf_skewness_double
+cdef void *_export_ncf_variance_float
+cdef void *_export_ncf_variance_double
+cdef void *_export_nct_isf_float
+cdef void *_export_nct_isf_double
+cdef void *_export_nct_kurtosis_excess_float
+cdef void *_export_nct_kurtosis_excess_double
+cdef void *_export_nct_mean_float
+cdef void *_export_nct_mean_double
+cdef void *_export_nct_pdf_float
+cdef void *_export_nct_pdf_double
+cdef void *_export_nct_ppf_float
+cdef void *_export_nct_ppf_double
+cdef void *_export_nct_sf_float
+cdef void *_export_nct_sf_double
+cdef void *_export_nct_skewness_float
+cdef void *_export_nct_skewness_double
+cdef void *_export_nct_variance_float
+cdef void *_export_nct_variance_double
+cdef void *_export_ncx2_cdf_float
+cdef void *_export_ncx2_cdf_double
+cdef void *_export_ncx2_isf_float
+cdef void *_export_ncx2_isf_double
+cdef void *_export_ncx2_pdf_float
+cdef void *_export_ncx2_pdf_double
+cdef void *_export_ncx2_ppf_float
+cdef void *_export_ncx2_ppf_double
+cdef void *_export_ncx2_sf_float
+cdef void *_export_ncx2_sf_double
+cdef void *_export_skewnorm_cdf_float
+cdef void *_export_skewnorm_cdf_double
+cdef void *_export_skewnorm_isf_float
+cdef void *_export_skewnorm_isf_double
+cdef void *_export_skewnorm_ppf_float
+cdef void *_export_skewnorm_ppf_double
+cdef void *_export__stirling2_inexact
+cdef void *_export_ibeta_float
+cdef void *_export_ibeta_double
+cdef void *_export_ibetac_float
+cdef void *_export_ibetac_double
+cdef void *_export_ibetac_inv_float
+cdef void *_export_ibetac_inv_double
+cdef void *_export_ibeta_inv_float
+cdef void *_export_ibeta_inv_double
+cdef void *_export_faddeeva_dawsn
+cdef void *_export_faddeeva_dawsn_complex
+cdef void *_export_fellint_RC
+cdef void *_export_cellint_RC
+cdef void *_export_fellint_RD
+cdef void *_export_cellint_RD
+cdef void *_export_fellint_RF
+cdef void *_export_cellint_RF
+cdef void *_export_fellint_RG
+cdef void *_export_cellint_RG
+cdef void *_export_fellint_RJ
+cdef void *_export_cellint_RJ
+cdef void *_export_faddeeva_erf
+cdef void *_export_faddeeva_erfc_complex
+cdef void *_export_faddeeva_erfcx
+cdef void *_export_faddeeva_erfcx_complex
+cdef void *_export_faddeeva_erfi
+cdef void *_export_faddeeva_erfi_complex
+cdef void *_export_erfinv_float
+cdef void *_export_erfinv_double
+cdef void *_export_hyp1f1_double
+cdef void *_export_faddeeva_log_ndtr
+cdef void *_export_faddeeva_log_ndtr_complex
+cdef void *_export_ncf_cdf_float
+cdef void *_export_ncf_cdf_double
+cdef void *_export_ncf_ppf_float
+cdef void *_export_ncf_ppf_double
+cdef void *_export_nct_cdf_float
+cdef void *_export_nct_cdf_double
+cdef void *_export_faddeeva_ndtr
+cdef void *_export_powm1_float
+cdef void *_export_powm1_double
+cdef void *_export_faddeeva_voigt_profile
+cdef void *_export_faddeeva_w
+cdef void *_export_wrightomega
+cdef void *_export_wrightomega_real
\ No newline at end of file
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..19cbd36c4707bb593e7e5638b9a158df504d3001
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx.pyx
@@ -0,0 +1,466 @@
+# This file is automatically generated by _generate_pyx.py.
+# Do not edit manually!
+
+from libc.math cimport NAN
+
+include "_ufuncs_extra_code_common.pxi"
+
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_beta_pdf_float "beta_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_beta_pdf_float = _func_beta_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_beta_pdf_double "beta_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_beta_pdf_double = _func_beta_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_beta_ppf_float "beta_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_beta_ppf_float = _func_beta_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_beta_ppf_double "beta_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_beta_ppf_double = _func_beta_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_cdf_float "binom_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_cdf_float = _func_binom_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_cdf_double "binom_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_cdf_double = _func_binom_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_isf_float "binom_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_isf_float = _func_binom_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_isf_double "binom_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_isf_double = _func_binom_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_pmf_float "binom_pmf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_pmf_float = _func_binom_pmf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_pmf_double "binom_pmf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_pmf_double = _func_binom_pmf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_ppf_float "binom_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_ppf_float = _func_binom_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_ppf_double "binom_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_ppf_double = _func_binom_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_binom_sf_float "binom_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_binom_sf_float = _func_binom_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_binom_sf_double "binom_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_binom_sf_double = _func_binom_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_cauchy_isf_float "cauchy_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_cauchy_isf_float = _func_cauchy_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_cauchy_isf_double "cauchy_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_cauchy_isf_double = _func_cauchy_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_cauchy_ppf_float "cauchy_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_cauchy_ppf_float = _func_cauchy_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_cauchy_ppf_double "cauchy_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_cauchy_ppf_double = _func_cauchy_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_cdf_float "hypergeom_cdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_hypergeom_cdf_float = _func_hypergeom_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_cdf_double "hypergeom_cdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_hypergeom_cdf_double = _func_hypergeom_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_mean_float "hypergeom_mean_float"(float, float, float) noexcept nogil
+cdef void *_export_hypergeom_mean_float = _func_hypergeom_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_mean_double "hypergeom_mean_double"(double, double, double) noexcept nogil
+cdef void *_export_hypergeom_mean_double = _func_hypergeom_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_pmf_float "hypergeom_pmf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_hypergeom_pmf_float = _func_hypergeom_pmf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_pmf_double "hypergeom_pmf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_hypergeom_pmf_double = _func_hypergeom_pmf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_sf_float "hypergeom_sf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_hypergeom_sf_float = _func_hypergeom_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_sf_double "hypergeom_sf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_hypergeom_sf_double = _func_hypergeom_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_skewness_float "hypergeom_skewness_float"(float, float, float) noexcept nogil
+cdef void *_export_hypergeom_skewness_float = _func_hypergeom_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_skewness_double "hypergeom_skewness_double"(double, double, double) noexcept nogil
+cdef void *_export_hypergeom_skewness_double = _func_hypergeom_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_hypergeom_variance_float "hypergeom_variance_float"(float, float, float) noexcept nogil
+cdef void *_export_hypergeom_variance_float = _func_hypergeom_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hypergeom_variance_double "hypergeom_variance_double"(double, double, double) noexcept nogil
+cdef void *_export_hypergeom_variance_double = _func_hypergeom_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_invgauss_isf_float "invgauss_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_invgauss_isf_float = _func_invgauss_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_invgauss_isf_double "invgauss_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_invgauss_isf_double = _func_invgauss_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_invgauss_ppf_float "invgauss_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_invgauss_ppf_float = _func_invgauss_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_invgauss_ppf_double "invgauss_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_invgauss_ppf_double = _func_invgauss_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_cdf_float "landau_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_cdf_float = _func_landau_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_cdf_double "landau_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_cdf_double = _func_landau_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_isf_float "landau_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_isf_float = _func_landau_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_isf_double "landau_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_isf_double = _func_landau_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_pdf_float "landau_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_pdf_float = _func_landau_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_pdf_double "landau_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_pdf_double = _func_landau_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_ppf_float "landau_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_ppf_float = _func_landau_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_ppf_double "landau_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_ppf_double = _func_landau_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_landau_sf_float "landau_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_landau_sf_float = _func_landau_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_landau_sf_double "landau_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_landau_sf_double = _func_landau_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_cdf_float "nbinom_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_cdf_float = _func_nbinom_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_cdf_double "nbinom_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_cdf_double = _func_nbinom_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_isf_float "nbinom_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_isf_float = _func_nbinom_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_isf_double "nbinom_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_isf_double = _func_nbinom_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_kurtosis_excess_float "nbinom_kurtosis_excess_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_kurtosis_excess_float = _func_nbinom_kurtosis_excess_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_kurtosis_excess_double "nbinom_kurtosis_excess_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_kurtosis_excess_double = _func_nbinom_kurtosis_excess_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_mean_float "nbinom_mean_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_mean_float = _func_nbinom_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_mean_double "nbinom_mean_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_mean_double = _func_nbinom_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_pmf_float "nbinom_pmf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_pmf_float = _func_nbinom_pmf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_pmf_double "nbinom_pmf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_pmf_double = _func_nbinom_pmf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_ppf_float "nbinom_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_ppf_float = _func_nbinom_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_ppf_double "nbinom_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_ppf_double = _func_nbinom_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_sf_float "nbinom_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_nbinom_sf_float = _func_nbinom_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_sf_double "nbinom_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_nbinom_sf_double = _func_nbinom_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_skewness_float "nbinom_skewness_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_skewness_float = _func_nbinom_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_skewness_double "nbinom_skewness_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_skewness_double = _func_nbinom_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nbinom_variance_float "nbinom_variance_float"(float, float) noexcept nogil
+cdef void *_export_nbinom_variance_float = _func_nbinom_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nbinom_variance_double "nbinom_variance_double"(double, double) noexcept nogil
+cdef void *_export_nbinom_variance_double = _func_nbinom_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_isf_float "ncf_isf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_isf_float = _func_ncf_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_isf_double "ncf_isf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_isf_double = _func_ncf_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_kurtosis_excess_float "ncf_kurtosis_excess_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_kurtosis_excess_float = _func_ncf_kurtosis_excess_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_kurtosis_excess_double "ncf_kurtosis_excess_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_kurtosis_excess_double = _func_ncf_kurtosis_excess_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_mean_float "ncf_mean_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_mean_float = _func_ncf_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_mean_double "ncf_mean_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_mean_double = _func_ncf_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_pdf_float "ncf_pdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_pdf_float = _func_ncf_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_pdf_double "ncf_pdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_pdf_double = _func_ncf_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_sf_float "ncf_sf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_sf_float = _func_ncf_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_sf_double "ncf_sf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_sf_double = _func_ncf_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_skewness_float "ncf_skewness_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_skewness_float = _func_ncf_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_skewness_double "ncf_skewness_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_skewness_double = _func_ncf_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_variance_float "ncf_variance_float"(float, float, float) noexcept nogil
+cdef void *_export_ncf_variance_float = _func_ncf_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_variance_double "ncf_variance_double"(double, double, double) noexcept nogil
+cdef void *_export_ncf_variance_double = _func_ncf_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_isf_float "nct_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_isf_float = _func_nct_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_isf_double "nct_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_isf_double = _func_nct_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_kurtosis_excess_float "nct_kurtosis_excess_float"(float, float) noexcept nogil
+cdef void *_export_nct_kurtosis_excess_float = _func_nct_kurtosis_excess_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_kurtosis_excess_double "nct_kurtosis_excess_double"(double, double) noexcept nogil
+cdef void *_export_nct_kurtosis_excess_double = _func_nct_kurtosis_excess_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_mean_float "nct_mean_float"(float, float) noexcept nogil
+cdef void *_export_nct_mean_float = _func_nct_mean_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_mean_double "nct_mean_double"(double, double) noexcept nogil
+cdef void *_export_nct_mean_double = _func_nct_mean_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_pdf_float "nct_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_pdf_float = _func_nct_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_pdf_double "nct_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_pdf_double = _func_nct_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_ppf_float "nct_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_ppf_float = _func_nct_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_ppf_double "nct_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_ppf_double = _func_nct_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_sf_float "nct_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_sf_float = _func_nct_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_sf_double "nct_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_sf_double = _func_nct_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_skewness_float "nct_skewness_float"(float, float) noexcept nogil
+cdef void *_export_nct_skewness_float = _func_nct_skewness_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_skewness_double "nct_skewness_double"(double, double) noexcept nogil
+cdef void *_export_nct_skewness_double = _func_nct_skewness_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_variance_float "nct_variance_float"(float, float) noexcept nogil
+cdef void *_export_nct_variance_float = _func_nct_variance_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_variance_double "nct_variance_double"(double, double) noexcept nogil
+cdef void *_export_nct_variance_double = _func_nct_variance_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_cdf_float "ncx2_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_cdf_float = _func_ncx2_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_cdf_double "ncx2_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_cdf_double = _func_ncx2_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_isf_float "ncx2_isf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_isf_float = _func_ncx2_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_isf_double "ncx2_isf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_isf_double = _func_ncx2_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_pdf_float "ncx2_pdf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_pdf_float = _func_ncx2_pdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_pdf_double "ncx2_pdf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_pdf_double = _func_ncx2_pdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_ppf_float "ncx2_ppf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_ppf_float = _func_ncx2_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_ppf_double "ncx2_ppf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_ppf_double = _func_ncx2_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncx2_sf_float "ncx2_sf_float"(float, float, float) noexcept nogil
+cdef void *_export_ncx2_sf_float = _func_ncx2_sf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncx2_sf_double "ncx2_sf_double"(double, double, double) noexcept nogil
+cdef void *_export_ncx2_sf_double = _func_ncx2_sf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_skewnorm_cdf_float "skewnorm_cdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_skewnorm_cdf_float = _func_skewnorm_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_skewnorm_cdf_double "skewnorm_cdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_skewnorm_cdf_double = _func_skewnorm_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_skewnorm_isf_float "skewnorm_isf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_skewnorm_isf_float = _func_skewnorm_isf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_skewnorm_isf_double "skewnorm_isf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_skewnorm_isf_double = _func_skewnorm_isf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_skewnorm_ppf_float "skewnorm_ppf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_skewnorm_ppf_float = _func_skewnorm_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_skewnorm_ppf_double "skewnorm_ppf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_skewnorm_ppf_double = _func_skewnorm_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func__stirling2_inexact "_stirling2_inexact"(double, double) noexcept nogil
+cdef void *_export__stirling2_inexact = _func__stirling2_inexact
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibeta_float "ibeta_float"(float, float, float) noexcept nogil
+cdef void *_export_ibeta_float = _func_ibeta_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibeta_double "ibeta_double"(double, double, double) noexcept nogil
+cdef void *_export_ibeta_double = _func_ibeta_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibetac_float "ibetac_float"(float, float, float) noexcept nogil
+cdef void *_export_ibetac_float = _func_ibetac_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibetac_double "ibetac_double"(double, double, double) noexcept nogil
+cdef void *_export_ibetac_double = _func_ibetac_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibetac_inv_float "ibetac_inv_float"(float, float, float) noexcept nogil
+cdef void *_export_ibetac_inv_float = _func_ibetac_inv_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibetac_inv_double "ibetac_inv_double"(double, double, double) noexcept nogil
+cdef void *_export_ibetac_inv_double = _func_ibetac_inv_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ibeta_inv_float "ibeta_inv_float"(float, float, float) noexcept nogil
+cdef void *_export_ibeta_inv_float = _func_ibeta_inv_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ibeta_inv_double "ibeta_inv_double"(double, double, double) noexcept nogil
+cdef void *_export_ibeta_inv_double = _func_ibeta_inv_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_dawsn "faddeeva_dawsn"(double) noexcept nogil
+cdef void *_export_faddeeva_dawsn = _func_faddeeva_dawsn
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_dawsn_complex "faddeeva_dawsn_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_dawsn_complex = _func_faddeeva_dawsn_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RC "fellint_RC"(double, double) noexcept nogil
+cdef void *_export_fellint_RC = _func_fellint_RC
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RC "cellint_RC"(double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RC = _func_cellint_RC
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RD "fellint_RD"(double, double, double) noexcept nogil
+cdef void *_export_fellint_RD = _func_fellint_RD
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RD "cellint_RD"(double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RD = _func_cellint_RD
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RF "fellint_RF"(double, double, double) noexcept nogil
+cdef void *_export_fellint_RF = _func_fellint_RF
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RF "cellint_RF"(double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RF = _func_cellint_RF
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RG "fellint_RG"(double, double, double) noexcept nogil
+cdef void *_export_fellint_RG = _func_fellint_RG
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RG "cellint_RG"(double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RG = _func_cellint_RG
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_fellint_RJ "fellint_RJ"(double, double, double, double) noexcept nogil
+cdef void *_export_fellint_RJ = _func_fellint_RJ
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_cellint_RJ "cellint_RJ"(double complex, double complex, double complex, double complex) noexcept nogil
+cdef void *_export_cellint_RJ = _func_cellint_RJ
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erf "faddeeva_erf"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erf = _func_faddeeva_erf
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erfc_complex "faddeeva_erfc_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erfc_complex = _func_faddeeva_erfc_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_erfcx "faddeeva_erfcx"(double) noexcept nogil
+cdef void *_export_faddeeva_erfcx = _func_faddeeva_erfcx
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erfcx_complex "faddeeva_erfcx_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erfcx_complex = _func_faddeeva_erfcx_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_erfi "faddeeva_erfi"(double) noexcept nogil
+cdef void *_export_faddeeva_erfi = _func_faddeeva_erfi
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_erfi_complex "faddeeva_erfi_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_erfi_complex = _func_faddeeva_erfi_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_erfinv_float "erfinv_float"(float) noexcept nogil
+cdef void *_export_erfinv_float = _func_erfinv_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_erfinv_double "erfinv_double"(double) noexcept nogil
+cdef void *_export_erfinv_double = _func_erfinv_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_hyp1f1_double "hyp1f1_double"(double, double, double) noexcept nogil
+cdef void *_export_hyp1f1_double = _func_hyp1f1_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_log_ndtr "faddeeva_log_ndtr"(double) noexcept nogil
+cdef void *_export_faddeeva_log_ndtr = _func_faddeeva_log_ndtr
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_log_ndtr_complex "faddeeva_log_ndtr_complex"(double complex) noexcept nogil
+cdef void *_export_faddeeva_log_ndtr_complex = _func_faddeeva_log_ndtr_complex
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_cdf_float "ncf_cdf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_cdf_float = _func_ncf_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_cdf_double "ncf_cdf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_cdf_double = _func_ncf_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_ncf_ppf_float "ncf_ppf_float"(float, float, float, float) noexcept nogil
+cdef void *_export_ncf_ppf_float = _func_ncf_ppf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_ncf_ppf_double "ncf_ppf_double"(double, double, double, double) noexcept nogil
+cdef void *_export_ncf_ppf_double = _func_ncf_ppf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_nct_cdf_float "nct_cdf_float"(float, float, float) noexcept nogil
+cdef void *_export_nct_cdf_float = _func_nct_cdf_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_nct_cdf_double "nct_cdf_double"(double, double, double) noexcept nogil
+cdef void *_export_nct_cdf_double = _func_nct_cdf_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_ndtr "faddeeva_ndtr"(double complex) noexcept nogil
+cdef void *_export_faddeeva_ndtr = _func_faddeeva_ndtr
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef float _func_powm1_float "powm1_float"(float, float) noexcept nogil
+cdef void *_export_powm1_float = _func_powm1_float
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_powm1_double "powm1_double"(double, double) noexcept nogil
+cdef void *_export_powm1_double = _func_powm1_double
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_faddeeva_voigt_profile "faddeeva_voigt_profile"(double, double, double) noexcept nogil
+cdef void *_export_faddeeva_voigt_profile = _func_faddeeva_voigt_profile
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_faddeeva_w "faddeeva_w"(double complex) noexcept nogil
+cdef void *_export_faddeeva_w = _func_faddeeva_w
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double complex _func_wrightomega "wrightomega"(double complex) noexcept nogil
+cdef void *_export_wrightomega = _func_wrightomega
+cdef extern from r"_ufuncs_cxx_defs.h":
+    cdef double _func_wrightomega_real "wrightomega_real"(double) noexcept nogil
+cdef void *_export_wrightomega_real = _func_wrightomega_real
\ No newline at end of file
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..4e916ce565742ecd949c2c6f9c1a1891e734a96d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_cxx_defs.h
@@ -0,0 +1,161 @@
+#ifndef UFUNCS_PROTO_H
+#define UFUNCS_PROTO_H 1
+#include "boost_special_functions.h"
+npy_float beta_pdf_float(npy_float, npy_float, npy_float);
+npy_double beta_pdf_double(npy_double, npy_double, npy_double);
+npy_float beta_ppf_float(npy_float, npy_float, npy_float);
+npy_double beta_ppf_double(npy_double, npy_double, npy_double);
+npy_float binom_cdf_float(npy_float, npy_float, npy_float);
+npy_double binom_cdf_double(npy_double, npy_double, npy_double);
+npy_float binom_isf_float(npy_float, npy_float, npy_float);
+npy_double binom_isf_double(npy_double, npy_double, npy_double);
+npy_float binom_pmf_float(npy_float, npy_float, npy_float);
+npy_double binom_pmf_double(npy_double, npy_double, npy_double);
+npy_float binom_ppf_float(npy_float, npy_float, npy_float);
+npy_double binom_ppf_double(npy_double, npy_double, npy_double);
+npy_float binom_sf_float(npy_float, npy_float, npy_float);
+npy_double binom_sf_double(npy_double, npy_double, npy_double);
+npy_float cauchy_isf_float(npy_float, npy_float, npy_float);
+npy_double cauchy_isf_double(npy_double, npy_double, npy_double);
+npy_float cauchy_ppf_float(npy_float, npy_float, npy_float);
+npy_double cauchy_ppf_double(npy_double, npy_double, npy_double);
+npy_float hypergeom_cdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double hypergeom_cdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float hypergeom_mean_float(npy_float, npy_float, npy_float);
+npy_double hypergeom_mean_double(npy_double, npy_double, npy_double);
+npy_float hypergeom_pmf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double hypergeom_pmf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float hypergeom_sf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double hypergeom_sf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float hypergeom_skewness_float(npy_float, npy_float, npy_float);
+npy_double hypergeom_skewness_double(npy_double, npy_double, npy_double);
+npy_float hypergeom_variance_float(npy_float, npy_float, npy_float);
+npy_double hypergeom_variance_double(npy_double, npy_double, npy_double);
+npy_float invgauss_isf_float(npy_float, npy_float, npy_float);
+npy_double invgauss_isf_double(npy_double, npy_double, npy_double);
+npy_float invgauss_ppf_float(npy_float, npy_float, npy_float);
+npy_double invgauss_ppf_double(npy_double, npy_double, npy_double);
+npy_float landau_cdf_float(npy_float, npy_float, npy_float);
+npy_double landau_cdf_double(npy_double, npy_double, npy_double);
+npy_float landau_isf_float(npy_float, npy_float, npy_float);
+npy_double landau_isf_double(npy_double, npy_double, npy_double);
+npy_float landau_pdf_float(npy_float, npy_float, npy_float);
+npy_double landau_pdf_double(npy_double, npy_double, npy_double);
+npy_float landau_ppf_float(npy_float, npy_float, npy_float);
+npy_double landau_ppf_double(npy_double, npy_double, npy_double);
+npy_float landau_sf_float(npy_float, npy_float, npy_float);
+npy_double landau_sf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_cdf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_cdf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_isf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_isf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_kurtosis_excess_float(npy_float, npy_float);
+npy_double nbinom_kurtosis_excess_double(npy_double, npy_double);
+npy_float nbinom_mean_float(npy_float, npy_float);
+npy_double nbinom_mean_double(npy_double, npy_double);
+npy_float nbinom_pmf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_pmf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_ppf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_ppf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_sf_float(npy_float, npy_float, npy_float);
+npy_double nbinom_sf_double(npy_double, npy_double, npy_double);
+npy_float nbinom_skewness_float(npy_float, npy_float);
+npy_double nbinom_skewness_double(npy_double, npy_double);
+npy_float nbinom_variance_float(npy_float, npy_float);
+npy_double nbinom_variance_double(npy_double, npy_double);
+npy_float ncf_isf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_isf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_kurtosis_excess_float(npy_float, npy_float, npy_float);
+npy_double ncf_kurtosis_excess_double(npy_double, npy_double, npy_double);
+npy_float ncf_mean_float(npy_float, npy_float, npy_float);
+npy_double ncf_mean_double(npy_double, npy_double, npy_double);
+npy_float ncf_pdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_pdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_sf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_sf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_skewness_float(npy_float, npy_float, npy_float);
+npy_double ncf_skewness_double(npy_double, npy_double, npy_double);
+npy_float ncf_variance_float(npy_float, npy_float, npy_float);
+npy_double ncf_variance_double(npy_double, npy_double, npy_double);
+npy_float nct_isf_float(npy_float, npy_float, npy_float);
+npy_double nct_isf_double(npy_double, npy_double, npy_double);
+npy_float nct_kurtosis_excess_float(npy_float, npy_float);
+npy_double nct_kurtosis_excess_double(npy_double, npy_double);
+npy_float nct_mean_float(npy_float, npy_float);
+npy_double nct_mean_double(npy_double, npy_double);
+npy_float nct_pdf_float(npy_float, npy_float, npy_float);
+npy_double nct_pdf_double(npy_double, npy_double, npy_double);
+npy_float nct_ppf_float(npy_float, npy_float, npy_float);
+npy_double nct_ppf_double(npy_double, npy_double, npy_double);
+npy_float nct_sf_float(npy_float, npy_float, npy_float);
+npy_double nct_sf_double(npy_double, npy_double, npy_double);
+npy_float nct_skewness_float(npy_float, npy_float);
+npy_double nct_skewness_double(npy_double, npy_double);
+npy_float nct_variance_float(npy_float, npy_float);
+npy_double nct_variance_double(npy_double, npy_double);
+npy_float ncx2_cdf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_cdf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_isf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_isf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_pdf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_pdf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_ppf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_ppf_double(npy_double, npy_double, npy_double);
+npy_float ncx2_sf_float(npy_float, npy_float, npy_float);
+npy_double ncx2_sf_double(npy_double, npy_double, npy_double);
+npy_float skewnorm_cdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double skewnorm_cdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float skewnorm_isf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double skewnorm_isf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float skewnorm_ppf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double skewnorm_ppf_double(npy_double, npy_double, npy_double, npy_double);
+#include "stirling2.h"
+npy_double _stirling2_inexact(npy_double, npy_double);
+npy_float ibeta_float(npy_float, npy_float, npy_float);
+npy_double ibeta_double(npy_double, npy_double, npy_double);
+npy_float ibetac_float(npy_float, npy_float, npy_float);
+npy_double ibetac_double(npy_double, npy_double, npy_double);
+npy_float ibetac_inv_float(npy_float, npy_float, npy_float);
+npy_double ibetac_inv_double(npy_double, npy_double, npy_double);
+npy_float ibeta_inv_float(npy_float, npy_float, npy_float);
+npy_double ibeta_inv_double(npy_double, npy_double, npy_double);
+#include "_faddeeva.h"
+npy_double faddeeva_dawsn(npy_double);
+npy_cdouble faddeeva_dawsn_complex(npy_cdouble);
+#include "ellint_carlson_wrap.hh"
+npy_double fellint_RC(npy_double, npy_double);
+npy_cdouble cellint_RC(npy_cdouble, npy_cdouble);
+npy_double fellint_RD(npy_double, npy_double, npy_double);
+npy_cdouble cellint_RD(npy_cdouble, npy_cdouble, npy_cdouble);
+npy_double fellint_RF(npy_double, npy_double, npy_double);
+npy_cdouble cellint_RF(npy_cdouble, npy_cdouble, npy_cdouble);
+npy_double fellint_RG(npy_double, npy_double, npy_double);
+npy_cdouble cellint_RG(npy_cdouble, npy_cdouble, npy_cdouble);
+npy_double fellint_RJ(npy_double, npy_double, npy_double, npy_double);
+npy_cdouble cellint_RJ(npy_cdouble, npy_cdouble, npy_cdouble, npy_cdouble);
+npy_cdouble faddeeva_erf(npy_cdouble);
+npy_cdouble faddeeva_erfc_complex(npy_cdouble);
+npy_double faddeeva_erfcx(npy_double);
+npy_cdouble faddeeva_erfcx_complex(npy_cdouble);
+npy_double faddeeva_erfi(npy_double);
+npy_cdouble faddeeva_erfi_complex(npy_cdouble);
+npy_float erfinv_float(npy_float);
+npy_double erfinv_double(npy_double);
+npy_double hyp1f1_double(npy_double, npy_double, npy_double);
+npy_double faddeeva_log_ndtr(npy_double);
+npy_cdouble faddeeva_log_ndtr_complex(npy_cdouble);
+npy_float ncf_cdf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_cdf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float ncf_ppf_float(npy_float, npy_float, npy_float, npy_float);
+npy_double ncf_ppf_double(npy_double, npy_double, npy_double, npy_double);
+npy_float nct_cdf_float(npy_float, npy_float, npy_float);
+npy_double nct_cdf_double(npy_double, npy_double, npy_double);
+npy_cdouble faddeeva_ndtr(npy_cdouble);
+npy_float powm1_float(npy_float, npy_float);
+npy_double powm1_double(npy_double, npy_double);
+npy_double faddeeva_voigt_profile(npy_double, npy_double, npy_double);
+npy_cdouble faddeeva_w(npy_cdouble);
+#include "_wright.h"
+npy_cdouble wrightomega(npy_cdouble);
+npy_double wrightomega_real(npy_double);
+#endif
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h
new file mode 100644
index 0000000000000000000000000000000000000000..86d2349d2b7881b71bfdec2a60a78e2bfc18f9fe
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/_ufuncs_defs.h
@@ -0,0 +1,65 @@
+#ifndef UFUNCS_PROTO_H
+#define UFUNCS_PROTO_H 1
+#include "_cosine.h"
+npy_double cosine_cdf(npy_double);
+npy_double cosine_invcdf(npy_double);
+#include "xsf_wrappers.h"
+npy_double cephes_igam_fac(npy_double, npy_double);
+npy_double xsf_kolmogc(npy_double);
+npy_double xsf_kolmogci(npy_double);
+npy_double xsf_kolmogp(npy_double);
+npy_double cephes_lanczos_sum_expg_scaled(npy_double);
+npy_double cephes_lgam1p(npy_double);
+npy_double cephes_log1pmx(npy_double);
+npy_double cephes_smirnovc_wrap(npy_intp, npy_double);
+npy_double cephes_smirnovci_wrap(npy_intp, npy_double);
+npy_double cephes_smirnovp_wrap(npy_intp, npy_double);
+npy_double cephes__struve_asymp_large_z(npy_double, npy_double, npy_intp, npy_double *);
+npy_double cephes__struve_bessel_series(npy_double, npy_double, npy_intp, npy_double *);
+npy_double cephes__struve_power_series(npy_double, npy_double, npy_intp, npy_double *);
+npy_double cephes_bdtr_wrap(npy_double, npy_intp, npy_double);
+npy_double cephes_bdtrc_wrap(npy_double, npy_intp, npy_double);
+npy_double cephes_bdtri_wrap(npy_double, npy_intp, npy_double);
+npy_double xsf_chdtr(npy_double, npy_double);
+npy_double xsf_chdtrc(npy_double, npy_double);
+npy_double xsf_chdtri(npy_double, npy_double);
+npy_double cephes_erf(npy_double);
+npy_double cephes_erfc(npy_double);
+npy_double cephes_erfcinv(npy_double);
+npy_double cephes_exp10(npy_double);
+npy_double cephes_exp2(npy_double);
+npy_double cephes_expm1(npy_double);
+npy_double cephes_expn_wrap(npy_intp, npy_double);
+npy_double xsf_fdtr(npy_double, npy_double, npy_double);
+npy_double xsf_fdtrc(npy_double, npy_double, npy_double);
+npy_double xsf_fdtri(npy_double, npy_double, npy_double);
+npy_double xsf_gdtr(npy_double, npy_double, npy_double);
+npy_double xsf_gdtrc(npy_double, npy_double, npy_double);
+npy_double xsf_gdtrib(npy_double, npy_double, npy_double);
+npy_cdouble chyp1f1_wrap(npy_double, npy_double, npy_cdouble);
+npy_double special_cyl_bessel_k_int(npy_intp, npy_double);
+npy_double xsf_kolmogi(npy_double);
+npy_double xsf_kolmogorov(npy_double);
+npy_double cephes_log1p(npy_double);
+npy_double pmv_wrap(npy_double, npy_double, npy_double);
+npy_double cephes_nbdtr_wrap(npy_intp, npy_intp, npy_double);
+npy_double cephes_nbdtrc_wrap(npy_intp, npy_intp, npy_double);
+npy_double cephes_nbdtri_wrap(npy_intp, npy_intp, npy_double);
+npy_double xsf_ndtr(npy_double);
+npy_double xsf_ndtri(npy_double);
+npy_double xsf_owens_t(npy_double, npy_double);
+npy_double xsf_pdtr(npy_double, npy_double);
+npy_double xsf_pdtrc(npy_double, npy_double);
+npy_double cephes_pdtri_wrap(npy_intp, npy_double);
+npy_double cephes_poch(npy_double, npy_double);
+npy_double cephes_round(npy_double);
+npy_int xsf_cshichi(npy_cdouble, npy_cdouble *, npy_cdouble *);
+npy_int xsf_shichi(npy_double, npy_double *, npy_double *);
+npy_int xsf_csici(npy_cdouble, npy_cdouble *, npy_cdouble *);
+npy_int xsf_sici(npy_double, npy_double *, npy_double *);
+npy_double cephes_smirnov_wrap(npy_intp, npy_double);
+npy_double cephes_smirnovi_wrap(npy_intp, npy_double);
+npy_double cephes_spence(npy_double);
+npy_double xsf_tukeylambdacdf(npy_double, npy_double);
+npy_double cephes_yn_wrap(npy_intp, npy_double);
+#endif
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..5549717d35710d71655e42c836625cde9346bcc3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/add_newdocs.py
@@ -0,0 +1,15 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="add_newdocs",
+                                   private_modules=["_add_newdocs"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..e55695f44d05187d6c83f1ebefd70270af2c2d76
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/basic.py
@@ -0,0 +1,87 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'ai_zeros',
+    'assoc_laguerre',
+    'bei_zeros',
+    'beip_zeros',
+    'ber_zeros',
+    'bernoulli',
+    'berp_zeros',
+    'bi_zeros',
+    'clpmn',
+    'comb',
+    'digamma',
+    'diric',
+    'erf_zeros',
+    'euler',
+    'factorial',
+    'factorial2',
+    'factorialk',
+    'fresnel_zeros',
+    'fresnelc_zeros',
+    'fresnels_zeros',
+    'gamma',
+    'h1vp',
+    'h2vp',
+    'hankel1',
+    'hankel2',
+    'iv',
+    'ivp',
+    'jn_zeros',
+    'jnjnp_zeros',
+    'jnp_zeros',
+    'jnyn_zeros',
+    'jv',
+    'jvp',
+    'kei_zeros',
+    'keip_zeros',
+    'kelvin_zeros',
+    'ker_zeros',
+    'kerp_zeros',
+    'kv',
+    'kvp',
+    'lmbda',
+    'lpmn',
+    'lpn',
+    'lqmn',
+    'lqn',
+    'mathieu_a',
+    'mathieu_b',
+    'mathieu_even_coef',
+    'mathieu_odd_coef',
+    'obl_cv_seq',
+    'pbdn_seq',
+    'pbdv_seq',
+    'pbvv_seq',
+    'perm',
+    'polygamma',
+    'pro_cv_seq',
+    'psi',
+    'riccati_jn',
+    'riccati_yn',
+    'sinc',
+    'y0_zeros',
+    'y1_zeros',
+    'y1p_zeros',
+    'yn_zeros',
+    'ynp_zeros',
+    'yv',
+    'yvp',
+    'zeta'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="basic",
+                                   private_modules=["_basic", "_ufuncs"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..c5d323fbd5f04ec56749505bc24feb080a851506
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pxd
@@ -0,0 +1,259 @@
+
+ctypedef fused number_t:
+    double complex
+    double
+
+cpdef number_t spherical_jn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+cpdef number_t spherical_yn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+cpdef number_t spherical_in(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+cpdef number_t spherical_kn(Py_ssize_t n, number_t z, bint derivative=*) noexcept nogil
+
+ctypedef fused Dd_number_t:
+    double complex
+    double
+
+ctypedef fused df_number_t:
+    double
+    float
+
+ctypedef fused dfg_number_t:
+    double
+    float
+    long double
+
+ctypedef fused dlp_number_t:
+    double
+    long
+    Py_ssize_t
+
+cpdef double voigt_profile(double x0, double x1, double x2) noexcept nogil
+cpdef double agm(double x0, double x1) noexcept nogil
+cdef void airy(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1, Dd_number_t *y2, Dd_number_t *y3) noexcept nogil
+cdef void airye(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1, Dd_number_t *y2, Dd_number_t *y3) noexcept nogil
+cpdef double bdtr(double x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double bdtrc(double x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double bdtri(double x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double bdtrik(double x0, double x1, double x2) noexcept nogil
+cpdef double bdtrin(double x0, double x1, double x2) noexcept nogil
+cpdef double bei(double x0) noexcept nogil
+cpdef double beip(double x0) noexcept nogil
+cpdef double ber(double x0) noexcept nogil
+cpdef double berp(double x0) noexcept nogil
+cpdef double besselpoly(double x0, double x1, double x2) noexcept nogil
+cpdef double beta(double x0, double x1) noexcept nogil
+cpdef df_number_t betainc(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef df_number_t betaincc(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef df_number_t betaincinv(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef df_number_t betainccinv(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef double betaln(double x0, double x1) noexcept nogil
+cpdef double binom(double x0, double x1) noexcept nogil
+cpdef double boxcox(double x0, double x1) noexcept nogil
+cpdef double boxcox1p(double x0, double x1) noexcept nogil
+cpdef double btdtria(double x0, double x1, double x2) noexcept nogil
+cpdef double btdtrib(double x0, double x1, double x2) noexcept nogil
+cpdef double cbrt(double x0) noexcept nogil
+cpdef double chdtr(double x0, double x1) noexcept nogil
+cpdef double chdtrc(double x0, double x1) noexcept nogil
+cpdef double chdtri(double x0, double x1) noexcept nogil
+cpdef double chdtriv(double x0, double x1) noexcept nogil
+cpdef double chndtr(double x0, double x1, double x2) noexcept nogil
+cpdef double chndtridf(double x0, double x1, double x2) noexcept nogil
+cpdef double chndtrinc(double x0, double x1, double x2) noexcept nogil
+cpdef double chndtrix(double x0, double x1, double x2) noexcept nogil
+cpdef double cosdg(double x0) noexcept nogil
+cpdef double cosm1(double x0) noexcept nogil
+cpdef double cotdg(double x0) noexcept nogil
+cpdef Dd_number_t dawsn(Dd_number_t x0) noexcept nogil
+cpdef double ellipe(double x0) noexcept nogil
+cpdef double ellipeinc(double x0, double x1) noexcept nogil
+cdef void ellipj(double x0, double x1, double *y0, double *y1, double *y2, double *y3) noexcept nogil
+cpdef double ellipkinc(double x0, double x1) noexcept nogil
+cpdef double ellipkm1(double x0) noexcept nogil
+cpdef double ellipk(double x0) noexcept nogil
+cpdef Dd_number_t elliprc(Dd_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t elliprd(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t elliprf(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t elliprg(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t elliprj(Dd_number_t x0, Dd_number_t x1, Dd_number_t x2, Dd_number_t x3) noexcept nogil
+cpdef double entr(double x0) noexcept nogil
+cpdef Dd_number_t erf(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t erfc(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t erfcx(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t erfi(Dd_number_t x0) noexcept nogil
+cpdef df_number_t erfinv(df_number_t x0) noexcept nogil
+cpdef double erfcinv(double x0) noexcept nogil
+cpdef Dd_number_t eval_chebyc(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_chebys(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_chebyt(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_chebyu(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_gegenbauer(dlp_number_t x0, double x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t eval_genlaguerre(dlp_number_t x0, double x1, Dd_number_t x2) noexcept nogil
+cpdef double eval_hermite(Py_ssize_t x0, double x1) noexcept nogil
+cpdef double eval_hermitenorm(Py_ssize_t x0, double x1) noexcept nogil
+cpdef Dd_number_t eval_jacobi(dlp_number_t x0, double x1, double x2, Dd_number_t x3) noexcept nogil
+cpdef Dd_number_t eval_laguerre(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_legendre(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_sh_chebyt(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_sh_chebyu(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t eval_sh_jacobi(dlp_number_t x0, double x1, double x2, Dd_number_t x3) noexcept nogil
+cpdef Dd_number_t eval_sh_legendre(dlp_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t exp1(Dd_number_t x0) noexcept nogil
+cpdef double exp10(double x0) noexcept nogil
+cpdef double exp2(double x0) noexcept nogil
+cpdef Dd_number_t expi(Dd_number_t x0) noexcept nogil
+cpdef dfg_number_t expit(dfg_number_t x0) noexcept nogil
+cpdef Dd_number_t expm1(Dd_number_t x0) noexcept nogil
+cpdef double expn(dlp_number_t x0, double x1) noexcept nogil
+cpdef double exprel(double x0) noexcept nogil
+cpdef double fdtr(double x0, double x1, double x2) noexcept nogil
+cpdef double fdtrc(double x0, double x1, double x2) noexcept nogil
+cpdef double fdtri(double x0, double x1, double x2) noexcept nogil
+cpdef double fdtridfd(double x0, double x1, double x2) noexcept nogil
+cdef void fresnel(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil
+cpdef Dd_number_t gamma(Dd_number_t x0) noexcept nogil
+cpdef double gammainc(double x0, double x1) noexcept nogil
+cpdef double gammaincc(double x0, double x1) noexcept nogil
+cpdef double gammainccinv(double x0, double x1) noexcept nogil
+cpdef double gammaincinv(double x0, double x1) noexcept nogil
+cpdef double gammaln(double x0) noexcept nogil
+cpdef double gammasgn(double x0) noexcept nogil
+cpdef double gdtr(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtrc(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtria(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtrib(double x0, double x1, double x2) noexcept nogil
+cpdef double gdtrix(double x0, double x1, double x2) noexcept nogil
+cpdef double complex hankel1(double x0, double complex x1) noexcept nogil
+cpdef double complex hankel1e(double x0, double complex x1) noexcept nogil
+cpdef double complex hankel2(double x0, double complex x1) noexcept nogil
+cpdef double complex hankel2e(double x0, double complex x1) noexcept nogil
+cpdef double huber(double x0, double x1) noexcept nogil
+cpdef Dd_number_t hyp0f1(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t hyp1f1(double x0, double x1, Dd_number_t x2) noexcept nogil
+cpdef Dd_number_t hyp2f1(double x0, double x1, double x2, Dd_number_t x3) noexcept nogil
+cpdef double hyperu(double x0, double x1, double x2) noexcept nogil
+cpdef double i0(double x0) noexcept nogil
+cpdef double i0e(double x0) noexcept nogil
+cpdef double i1(double x0) noexcept nogil
+cpdef double i1e(double x0) noexcept nogil
+cpdef double inv_boxcox(double x0, double x1) noexcept nogil
+cpdef double inv_boxcox1p(double x0, double x1) noexcept nogil
+cdef void it2i0k0(double x0, double *y0, double *y1) noexcept nogil
+cdef void it2j0y0(double x0, double *y0, double *y1) noexcept nogil
+cpdef double it2struve0(double x0) noexcept nogil
+cdef void itairy(double x0, double *y0, double *y1, double *y2, double *y3) noexcept nogil
+cdef void iti0k0(double x0, double *y0, double *y1) noexcept nogil
+cdef void itj0y0(double x0, double *y0, double *y1) noexcept nogil
+cpdef double itmodstruve0(double x0) noexcept nogil
+cpdef double itstruve0(double x0) noexcept nogil
+cpdef Dd_number_t iv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t ive(double x0, Dd_number_t x1) noexcept nogil
+cpdef double j0(double x0) noexcept nogil
+cpdef double j1(double x0) noexcept nogil
+cpdef Dd_number_t jv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t jve(double x0, Dd_number_t x1) noexcept nogil
+cpdef double k0(double x0) noexcept nogil
+cpdef double k0e(double x0) noexcept nogil
+cpdef double k1(double x0) noexcept nogil
+cpdef double k1e(double x0) noexcept nogil
+cpdef double kei(double x0) noexcept nogil
+cpdef double keip(double x0) noexcept nogil
+cdef void kelvin(double x0, double complex *y0, double complex *y1, double complex *y2, double complex *y3) noexcept nogil
+cpdef double ker(double x0) noexcept nogil
+cpdef double kerp(double x0) noexcept nogil
+cpdef double kl_div(double x0, double x1) noexcept nogil
+cpdef double kn(dlp_number_t x0, double x1) noexcept nogil
+cpdef double kolmogi(double x0) noexcept nogil
+cpdef double kolmogorov(double x0) noexcept nogil
+cpdef Dd_number_t kv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t kve(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t log1p(Dd_number_t x0) noexcept nogil
+cpdef dfg_number_t log_expit(dfg_number_t x0) noexcept nogil
+cpdef Dd_number_t log_ndtr(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t loggamma(Dd_number_t x0) noexcept nogil
+cpdef dfg_number_t logit(dfg_number_t x0) noexcept nogil
+cpdef double lpmv(double x0, double x1, double x2) noexcept nogil
+cpdef double mathieu_a(double x0, double x1) noexcept nogil
+cpdef double mathieu_b(double x0, double x1) noexcept nogil
+cdef void mathieu_cem(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modcem1(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modcem2(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modsem1(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_modsem2(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void mathieu_sem(double x0, double x1, double x2, double *y0, double *y1) noexcept nogil
+cdef void modfresnelm(double x0, double complex *y0, double complex *y1) noexcept nogil
+cdef void modfresnelp(double x0, double complex *y0, double complex *y1) noexcept nogil
+cpdef double modstruve(double x0, double x1) noexcept nogil
+cpdef double nbdtr(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double nbdtrc(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double nbdtri(dlp_number_t x0, dlp_number_t x1, double x2) noexcept nogil
+cpdef double nbdtrik(double x0, double x1, double x2) noexcept nogil
+cpdef double nbdtrin(double x0, double x1, double x2) noexcept nogil
+cpdef df_number_t ncfdtr(df_number_t x0, df_number_t x1, df_number_t x2, df_number_t x3) noexcept nogil
+cpdef df_number_t ncfdtri(df_number_t x0, df_number_t x1, df_number_t x2, df_number_t x3) noexcept nogil
+cpdef double ncfdtridfd(double x0, double x1, double x2, double x3) noexcept nogil
+cpdef double ncfdtridfn(double x0, double x1, double x2, double x3) noexcept nogil
+cpdef double ncfdtrinc(double x0, double x1, double x2, double x3) noexcept nogil
+cpdef df_number_t nctdtr(df_number_t x0, df_number_t x1, df_number_t x2) noexcept nogil
+cpdef double nctdtridf(double x0, double x1, double x2) noexcept nogil
+cpdef double nctdtrinc(double x0, double x1, double x2) noexcept nogil
+cpdef double nctdtrit(double x0, double x1, double x2) noexcept nogil
+cpdef Dd_number_t ndtr(Dd_number_t x0) noexcept nogil
+cpdef double ndtri(double x0) noexcept nogil
+cpdef double nrdtrimn(double x0, double x1, double x2) noexcept nogil
+cpdef double nrdtrisd(double x0, double x1, double x2) noexcept nogil
+cdef void obl_ang1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void obl_ang1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double obl_cv(double x0, double x1, double x2) noexcept nogil
+cdef void obl_rad1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void obl_rad1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cdef void obl_rad2(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void obl_rad2_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double owens_t(double x0, double x1) noexcept nogil
+cdef void pbdv(double x0, double x1, double *y0, double *y1) noexcept nogil
+cdef void pbvv(double x0, double x1, double *y0, double *y1) noexcept nogil
+cdef void pbwa(double x0, double x1, double *y0, double *y1) noexcept nogil
+cpdef double pdtr(double x0, double x1) noexcept nogil
+cpdef double pdtrc(double x0, double x1) noexcept nogil
+cpdef double pdtri(dlp_number_t x0, double x1) noexcept nogil
+cpdef double pdtrik(double x0, double x1) noexcept nogil
+cpdef double poch(double x0, double x1) noexcept nogil
+cpdef df_number_t powm1(df_number_t x0, df_number_t x1) noexcept nogil
+cdef void pro_ang1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void pro_ang1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double pro_cv(double x0, double x1, double x2) noexcept nogil
+cdef void pro_rad1(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void pro_rad1_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cdef void pro_rad2(double x0, double x1, double x2, double x3, double *y0, double *y1) noexcept nogil
+cdef void pro_rad2_cv(double x0, double x1, double x2, double x3, double x4, double *y0, double *y1) noexcept nogil
+cpdef double pseudo_huber(double x0, double x1) noexcept nogil
+cpdef Dd_number_t psi(Dd_number_t x0) noexcept nogil
+cpdef double radian(double x0, double x1, double x2) noexcept nogil
+cpdef double rel_entr(double x0, double x1) noexcept nogil
+cpdef Dd_number_t rgamma(Dd_number_t x0) noexcept nogil
+cpdef double round(double x0) noexcept nogil
+cdef void shichi(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil
+cdef void sici(Dd_number_t x0, Dd_number_t *y0, Dd_number_t *y1) noexcept nogil
+cpdef double sindg(double x0) noexcept nogil
+cpdef double smirnov(dlp_number_t x0, double x1) noexcept nogil
+cpdef double smirnovi(dlp_number_t x0, double x1) noexcept nogil
+cpdef Dd_number_t spence(Dd_number_t x0) noexcept nogil
+cpdef double complex sph_harm(dlp_number_t x0, dlp_number_t x1, double x2, double x3) noexcept nogil
+cpdef double stdtr(double x0, double x1) noexcept nogil
+cpdef double stdtridf(double x0, double x1) noexcept nogil
+cpdef double stdtrit(double x0, double x1) noexcept nogil
+cpdef double struve(double x0, double x1) noexcept nogil
+cpdef double tandg(double x0) noexcept nogil
+cpdef double tklmbda(double x0, double x1) noexcept nogil
+cpdef double complex wofz(double complex x0) noexcept nogil
+cpdef Dd_number_t wrightomega(Dd_number_t x0) noexcept nogil
+cpdef Dd_number_t xlog1py(Dd_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t xlogy(Dd_number_t x0, Dd_number_t x1) noexcept nogil
+cpdef double y0(double x0) noexcept nogil
+cpdef double y1(double x0) noexcept nogil
+cpdef double yn(dlp_number_t x0, double x1) noexcept nogil
+cpdef Dd_number_t yv(double x0, Dd_number_t x1) noexcept nogil
+cpdef Dd_number_t yve(double x0, Dd_number_t x1) noexcept nogil
+cpdef double zetac(double x0) noexcept nogil
+cpdef double wright_bessel(double x0, double x1, double x2) noexcept nogil
+cpdef double log_wright_bessel(double x0, double x1, double x2) noexcept nogil
+cpdef double ndtri_exp(double x0) noexcept nogil
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..024e962b10df8892631eaad20223f7fc8378ea83
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/cython_special.pyi
@@ -0,0 +1,3 @@
+from typing import Any
+
+def __getattr__(name) -> Any: ...
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so
new file mode 100644
index 0000000000000000000000000000000000000000..84e37bedbdfcc83bb65efc5d7f1961f2b749ebeb
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/libsf_error_state.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/orthogonal.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..0b13a08a96cb683d72a4a00d6962446e1779c88a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/orthogonal.py
@@ -0,0 +1,45 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+_polyfuns = ['legendre', 'chebyt', 'chebyu', 'chebyc', 'chebys',
+             'jacobi', 'laguerre', 'genlaguerre', 'hermite',
+             'hermitenorm', 'gegenbauer', 'sh_legendre', 'sh_chebyt',
+             'sh_chebyu', 'sh_jacobi']
+
+# Correspondence between new and old names of root functions
+_rootfuns_map = {'roots_legendre': 'p_roots',
+               'roots_chebyt': 't_roots',
+               'roots_chebyu': 'u_roots',
+               'roots_chebyc': 'c_roots',
+               'roots_chebys': 's_roots',
+               'roots_jacobi': 'j_roots',
+               'roots_laguerre': 'l_roots',
+               'roots_genlaguerre': 'la_roots',
+               'roots_hermite': 'h_roots',
+               'roots_hermitenorm': 'he_roots',
+               'roots_gegenbauer': 'cg_roots',
+               'roots_sh_legendre': 'ps_roots',
+               'roots_sh_chebyt': 'ts_roots',
+               'roots_sh_chebyu': 'us_roots',
+               'roots_sh_jacobi': 'js_roots'}
+
+
+__all__ = _polyfuns + list(_rootfuns_map.keys()) + [  # noqa: F822
+    'airy', 'p_roots', 't_roots', 'u_roots', 'c_roots', 's_roots',
+    'j_roots', 'l_roots', 'la_roots', 'h_roots', 'he_roots', 'cg_roots',
+    'ps_roots', 'ts_roots', 'us_roots', 'js_roots'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="orthogonal",
+                                   private_modules=["_orthogonal"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/sf_error.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ff73756acd4219a4ba94eb089bce7d4c32266d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/sf_error.py
@@ -0,0 +1,20 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [  # noqa: F822
+    'SpecialFunctionWarning',
+    'SpecialFunctionError'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="sf_error",
+                                   private_modules=["_sf_error"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/specfun.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/specfun.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fca00415a6406b8cdf41a42b6fbf991cea1f53f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/specfun.py
@@ -0,0 +1,24 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+# ruff: noqa: F822
+__all__ = [
+    'clpmn',
+    'lpmn',
+    'lpn',
+    'lqmn',
+    'pbdv'
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="specfun",
+                                   private_modules=["_basic", "_specfun"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1e58487aaa547483c9f2531ac4efc2ad5e4795c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/spfun_stats.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.special` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = ['multigammaln']  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="special", module="spfun_stats",
+                                   private_modules=["_spfun_stats"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/extending.pyx b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..ca3bf2167f0f7726f8b0acb60ed8b8798a518d79
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/extending.pyx
@@ -0,0 +1,12 @@
+#!/usr/bin/env python3
+#cython: language_level=3
+#cython: boundscheck=False
+#cython: wraparound=False
+
+from scipy.special.cython_special cimport beta, gamma
+
+cpdef double cy_beta(double a, double b):
+    return beta(a, b)
+
+cpdef double complex cy_gamma(double complex z):
+    return gamma(z)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/meson.build b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..2a5e1535a16f840f31ca0207513e7c060767ea12
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/_cython_examples/meson.build
@@ -0,0 +1,25 @@
+project('random-build-examples', 'c', 'cpp', 'cython')
+
+fs = import('fs')
+
+py3 = import('python').find_installation(pure: false)
+
+cy = meson.get_compiler('cython')
+
+if not cy.version().version_compare('>=3.0.8')
+  error('tests requires Cython >= 3.0.8')
+endif
+
+py3.extension_module(
+  'extending',
+  'extending.pyx',
+  install: false,
+)
+
+extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx')
+py3.extension_module(
+  'extending_cpp',
+  extending_cpp,
+  install: false,
+  override_options : ['cython_language=cpp']
+)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/data/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..67bb83f1f1682e5eb83cc66f052ea51e3caf8757
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_basic.py
@@ -0,0 +1,4682 @@
+# this program corresponds to special.py
+
+### Means test is not done yet
+# E   Means test is giving error (E)
+# F   Means test is failing (F)
+# EF  Means test is giving error and Failing
+#!   Means test is segfaulting
+# 8   Means test runs forever
+
+###  test_besselpoly
+###  test_mathieu_a
+###  test_mathieu_even_coef
+###  test_mathieu_odd_coef
+###  test_modfresnelp
+###  test_modfresnelm
+#    test_pbdv_seq
+###  test_pbvv_seq
+###  test_sph_harm
+
+import functools
+import itertools
+import operator
+import platform
+import sys
+
+import numpy as np
+from numpy import (array, isnan, r_, arange, finfo, pi, sin, cos, tan, exp,
+        log, zeros, sqrt, asarray, inf, nan_to_num, real, arctan, double,
+        array_equal)
+
+import pytest
+from pytest import raises as assert_raises
+from numpy.testing import (assert_equal, assert_almost_equal,
+        assert_array_equal, assert_array_almost_equal, assert_approx_equal,
+        assert_, assert_allclose, assert_array_almost_equal_nulp,
+        suppress_warnings)
+
+from scipy import special
+import scipy.special._ufuncs as cephes
+from scipy.special import ellipe, ellipk, ellipkm1
+from scipy.special import elliprc, elliprd, elliprf, elliprg, elliprj
+from scipy.special import softplus
+from scipy.special import mathieu_odd_coef, mathieu_even_coef, stirling2
+from scipy.special import lpn, lpmn, clpmn
+from scipy._lib._util import np_long, np_ulong
+from scipy._lib._array_api import xp_assert_close, xp_assert_equal, SCIPY_ARRAY_API
+
+from scipy.special._basic import (
+    _FACTORIALK_LIMITS_64BITS, _FACTORIALK_LIMITS_32BITS, _is_subdtype
+)
+from scipy.special._testutils import with_special_errors, \
+     assert_func_equal, FuncData
+
+import math
+
+
+native_int = np.int32 if (
+    sys.platform == 'win32'
+    or platform.architecture()[0] == "32bit"
+) else np.int64
+
+
+class TestCephes:
+    def test_airy(self):
+        cephes.airy(0)
+
+    def test_airye(self):
+        cephes.airye(0)
+
+    def test_binom(self):
+        n = np.array([0.264, 4, 5.2, 17])
+        k = np.array([2, 0.4, 7, 3.3])
+        nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])
+                      ).reshape(2, -1).T
+        rknown = np.array([[-0.097152, 0.9263051596159367, 0.01858423645695389,
+            -0.007581020651518199],[6, 2.0214389119675666, 0, 2.9827344527963846],
+            [10.92, 2.22993515861399, -0.00585728, 10.468891352063146],
+            [136, 3.5252179590758828, 19448, 1024.5526916174495]])
+        assert_func_equal(cephes.binom, rknown.ravel(), nk, rtol=1e-13)
+
+        # Test branches in implementation
+        rng = np.random.RandomState(1234)
+        n = np.r_[np.arange(-7, 30), 1000*rng.rand(30) - 500]
+        k = np.arange(0, 102)
+        nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])
+                      ).reshape(2, -1).T
+
+        assert_func_equal(cephes.binom,
+                          cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)),
+                          nk,
+                          atol=1e-10, rtol=1e-10)
+
+    def test_binom_2(self):
+        # Test branches in implementation
+        np.random.seed(1234)
+        n = np.r_[np.logspace(1, 300, 20)]
+        k = np.arange(0, 102)
+        nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])
+                      ).reshape(2, -1).T
+
+        assert_func_equal(cephes.binom,
+                          cephes.binom(nk[:,0], nk[:,1] * (1 + 1e-15)),
+                          nk,
+                          atol=1e-10, rtol=1e-10)
+
+    def test_binom_exact(self):
+        @np.vectorize
+        def binom_int(n, k):
+            n = int(n)
+            k = int(k)
+            num = 1
+            den = 1
+            for i in range(1, k+1):
+                num *= i + n - k
+                den *= i
+            return float(num/den)
+
+        np.random.seed(1234)
+        n = np.arange(1, 15)
+        k = np.arange(0, 15)
+        nk = np.array(np.broadcast_arrays(n[:,None], k[None,:])
+                      ).reshape(2, -1).T
+        nk = nk[nk[:,0] >= nk[:,1]]
+        assert_func_equal(cephes.binom,
+                          binom_int(nk[:,0], nk[:,1]),
+                          nk,
+                          atol=0, rtol=0)
+
+    def test_binom_nooverflow_8346(self):
+        # Test (binom(n, k) doesn't overflow prematurely */
+        dataset = [
+            (1000, 500, 2.70288240945436551e+299),
+            (1002, 501, 1.08007396880791225e+300),
+            (1004, 502, 4.31599279169058121e+300),
+            (1006, 503, 1.72468101616263781e+301),
+            (1008, 504, 6.89188009236419153e+301),
+            (1010, 505, 2.75402257948335448e+302),
+            (1012, 506, 1.10052048531923757e+303),
+            (1014, 507, 4.39774063758732849e+303),
+            (1016, 508, 1.75736486108312519e+304),
+            (1018, 509, 7.02255427788423734e+304),
+            (1020, 510, 2.80626776829962255e+305),
+            (1022, 511, 1.12140876377061240e+306),
+            (1024, 512, 4.48125455209897109e+306),
+            (1026, 513, 1.79075474304149900e+307),
+            (1028, 514, 7.15605105487789676e+307)
+        ]
+        dataset = np.asarray(dataset)
+        FuncData(cephes.binom, dataset, (0, 1), 2, rtol=1e-12).check()
+
+    def test_bdtr(self):
+        assert_equal(cephes.bdtr(1,1,0.5),1.0)
+
+    def test_bdtri(self):
+        assert_equal(cephes.bdtri(1,3,0.5),0.5)
+
+    def test_bdtrc(self):
+        assert_equal(cephes.bdtrc(1,3,0.5),0.5)
+
+    def test_bdtrin(self):
+        assert_equal(cephes.bdtrin(1,0,1),5.0)
+
+    def test_bdtrik(self):
+        cephes.bdtrik(1,3,0.5)
+
+    def test_bei(self):
+        assert_equal(cephes.bei(0),0.0)
+
+    def test_beip(self):
+        assert_equal(cephes.beip(0),0.0)
+
+    def test_ber(self):
+        assert_equal(cephes.ber(0),1.0)
+
+    def test_berp(self):
+        assert_equal(cephes.berp(0),0.0)
+
+    def test_besselpoly(self):
+        assert_equal(cephes.besselpoly(0,0,0),1.0)
+
+    def test_btdtria(self):
+        assert_equal(cephes.btdtria(1,1,1),5.0)
+
+    def test_btdtrib(self):
+        assert_equal(cephes.btdtrib(1,1,1),5.0)
+
+    def test_cbrt(self):
+        assert_approx_equal(cephes.cbrt(1),1.0)
+
+    def test_chdtr(self):
+        assert_equal(cephes.chdtr(1,0),0.0)
+
+    def test_chdtrc(self):
+        assert_equal(cephes.chdtrc(1,0),1.0)
+
+    def test_chdtri(self):
+        assert_equal(cephes.chdtri(1,1),0.0)
+
+    def test_chdtriv(self):
+        assert_equal(cephes.chdtriv(0,0),5.0)
+
+    def test_chndtr(self):
+        assert_equal(cephes.chndtr(0,1,0),0.0)
+
+        # Each row holds (x, nu, lam, expected_value)
+        # These values were computed using Wolfram Alpha with
+        #     CDF[NoncentralChiSquareDistribution[nu, lam], x]
+        values = np.array([
+            [25.00, 20.0, 400, 4.1210655112396197139e-57],
+            [25.00, 8.00, 250, 2.3988026526832425878e-29],
+            [0.001, 8.00, 40., 5.3761806201366039084e-24],
+            [0.010, 8.00, 40., 5.45396231055999457039e-20],
+            [20.00, 2.00, 107, 1.39390743555819597802e-9],
+            [22.50, 2.00, 107, 7.11803307138105870671e-9],
+            [25.00, 2.00, 107, 3.11041244829864897313e-8],
+            [3.000, 2.00, 1.0, 0.62064365321954362734],
+            [350.0, 300., 10., 0.93880128006276407710],
+            [100.0, 13.5, 10., 0.99999999650104210949],
+            [700.0, 20.0, 400, 0.99999999925680650105],
+            [150.0, 13.5, 10., 0.99999999999999983046],
+            [160.0, 13.5, 10., 0.99999999999999999518],  # 1.0
+        ])
+        cdf = cephes.chndtr(values[:, 0], values[:, 1], values[:, 2])
+        assert_allclose(cdf, values[:, 3], rtol=1e-12)
+
+        assert_almost_equal(cephes.chndtr(np.inf, np.inf, 0), 2.0)
+        assert_almost_equal(cephes.chndtr(2, 1, np.inf), 0.0)
+        assert_(np.isnan(cephes.chndtr(np.nan, 1, 2)))
+        assert_(np.isnan(cephes.chndtr(5, np.nan, 2)))
+        assert_(np.isnan(cephes.chndtr(5, 1, np.nan)))
+
+    def test_chndtridf(self):
+        assert_equal(cephes.chndtridf(0,0,1),5.0)
+
+    def test_chndtrinc(self):
+        assert_equal(cephes.chndtrinc(0,1,0),5.0)
+
+    def test_chndtrix(self):
+        assert_equal(cephes.chndtrix(0,1,0),0.0)
+
+    def test_cosdg(self):
+        assert_equal(cephes.cosdg(0),1.0)
+
+    def test_cosm1(self):
+        assert_equal(cephes.cosm1(0),0.0)
+
+    def test_cotdg(self):
+        assert_almost_equal(cephes.cotdg(45),1.0)
+
+    def test_dawsn(self):
+        assert_equal(cephes.dawsn(0),0.0)
+        assert_allclose(cephes.dawsn(1.23), 0.50053727749081767)
+
+    def test_diric(self):
+        # Test behavior near multiples of 2pi.  Regression test for issue
+        # described in gh-4001.
+        n_odd = [1, 5, 25]
+        x = np.array(2*np.pi + 5e-5).astype(np.float32)
+        assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=7)
+        x = np.array(2*np.pi + 1e-9).astype(np.float64)
+        assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15)
+        x = np.array(2*np.pi + 1e-15).astype(np.float64)
+        assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=15)
+        if hasattr(np, 'float128'):
+            # No float128 available in 32-bit numpy
+            x = np.array(2*np.pi + 1e-12).astype(np.float128)
+            assert_almost_equal(special.diric(x, n_odd), 1.0, decimal=19)
+
+        n_even = [2, 4, 24]
+        x = np.array(2*np.pi + 1e-9).astype(np.float64)
+        assert_almost_equal(special.diric(x, n_even), -1.0, decimal=15)
+
+        # Test at some values not near a multiple of pi
+        x = np.arange(0.2*np.pi, 1.0*np.pi, 0.2*np.pi)
+        octave_result = [0.872677996249965, 0.539344662916632,
+                         0.127322003750035, -0.206011329583298]
+        assert_almost_equal(special.diric(x, 3), octave_result, decimal=15)
+
+    def test_diric_broadcasting(self):
+        x = np.arange(5)
+        n = np.array([1, 3, 7])
+        assert_(special.diric(x[:, np.newaxis], n).shape == (x.size, n.size))
+
+    def test_ellipe(self):
+        assert_equal(cephes.ellipe(1),1.0)
+
+    def test_ellipeinc(self):
+        assert_equal(cephes.ellipeinc(0,1),0.0)
+
+    def test_ellipj(self):
+        cephes.ellipj(0,1)
+
+    def test_ellipk(self):
+        assert_allclose(ellipk(0), pi/2)
+
+    def test_ellipkinc(self):
+        assert_equal(cephes.ellipkinc(0,0),0.0)
+
+    def test_erf(self):
+        assert_equal(cephes.erf(0), 0.0)
+
+    def test_erf_symmetry(self):
+        x = 5.905732037710919
+        assert_equal(cephes.erf(x) + cephes.erf(-x), 0.0)
+
+    def test_erfc(self):
+        assert_equal(cephes.erfc(0), 1.0)
+
+    def test_exp10(self):
+        assert_approx_equal(cephes.exp10(2),100.0)
+
+    def test_exp2(self):
+        assert_equal(cephes.exp2(2),4.0)
+
+    def test_expm1(self):
+        assert_equal(cephes.expm1(0),0.0)
+        assert_equal(cephes.expm1(np.inf), np.inf)
+        assert_equal(cephes.expm1(-np.inf), -1)
+        assert_equal(cephes.expm1(np.nan), np.nan)
+
+    def test_expm1_complex(self):
+        expm1 = cephes.expm1
+        assert_equal(expm1(0 + 0j), 0 + 0j)
+        assert_equal(expm1(complex(np.inf, 0)), complex(np.inf, 0))
+        assert_equal(expm1(complex(np.inf, 1)), complex(np.inf, np.inf))
+        assert_equal(expm1(complex(np.inf, 2)), complex(-np.inf, np.inf))
+        assert_equal(expm1(complex(np.inf, 4)), complex(-np.inf, -np.inf))
+        assert_equal(expm1(complex(np.inf, 5)), complex(np.inf, -np.inf))
+        assert_equal(expm1(complex(1, np.inf)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(0, np.inf)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(np.inf, np.inf)), complex(np.inf, np.nan))
+        assert_equal(expm1(complex(-np.inf, np.inf)), complex(-1, 0))
+        assert_equal(expm1(complex(-np.inf, np.nan)), complex(-1, 0))
+        assert_equal(expm1(complex(np.inf, np.nan)), complex(np.inf, np.nan))
+        assert_equal(expm1(complex(0, np.nan)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(1, np.nan)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(np.nan, 1)), complex(np.nan, np.nan))
+        assert_equal(expm1(complex(np.nan, np.nan)), complex(np.nan, np.nan))
+
+    @pytest.mark.xfail(reason='The real part of expm1(z) bad at these points')
+    def test_expm1_complex_hard(self):
+        # The real part of this function is difficult to evaluate when
+        # z.real = -log(cos(z.imag)).
+        y = np.array([0.1, 0.2, 0.3, 5, 11, 20])
+        x = -np.log(np.cos(y))
+        z = x + 1j*y
+
+        # evaluate using mpmath.expm1 with dps=1000
+        expected = np.array([-5.5507901846769623e-17+0.10033467208545054j,
+                              2.4289354732893695e-18+0.20271003550867248j,
+                              4.5235500262585768e-17+0.30933624960962319j,
+                              7.8234305217489006e-17-3.3805150062465863j,
+                             -1.3685191953697676e-16-225.95084645419513j,
+                              8.7175620481291045e-17+2.2371609442247422j])
+        found = cephes.expm1(z)
+        # this passes.
+        assert_array_almost_equal_nulp(found.imag, expected.imag, 3)
+        # this fails.
+        assert_array_almost_equal_nulp(found.real, expected.real, 20)
+
+    def test_fdtr(self):
+        assert_equal(cephes.fdtr(1, 1, 0), 0.0)
+        # Computed using Wolfram Alpha: CDF[FRatioDistribution[1e-6, 5], 10]
+        assert_allclose(cephes.fdtr(1e-6, 5, 10), 0.9999940790193488,
+                        rtol=1e-12)
+
+    def test_fdtrc(self):
+        assert_equal(cephes.fdtrc(1, 1, 0), 1.0)
+        # Computed using Wolfram Alpha:
+        #   1 - CDF[FRatioDistribution[2, 1/10], 1e10]
+        assert_allclose(cephes.fdtrc(2, 0.1, 1e10), 0.27223784621293512,
+                        rtol=1e-12)
+
+    def test_fdtri(self):
+        assert_allclose(cephes.fdtri(1, 1, [0.499, 0.501]),
+                        array([0.9937365, 1.00630298]), rtol=1e-6)
+        # From Wolfram Alpha:
+        #   CDF[FRatioDistribution[1/10, 1], 3] = 0.8756751669632105666874...
+        p = 0.8756751669632105666874
+        assert_allclose(cephes.fdtri(0.1, 1, p), 3, rtol=1e-12)
+
+    @pytest.mark.xfail(reason='Returns nan on i686.')
+    def test_fdtri_mysterious_failure(self):
+        assert_allclose(cephes.fdtri(1, 1, 0.5), 1)
+
+    def test_fdtridfd(self):
+        assert_equal(cephes.fdtridfd(1,0,0),5.0)
+
+    def test_fresnel(self):
+        assert_equal(cephes.fresnel(0),(0.0,0.0))
+
+    def test_gamma(self):
+        assert_equal(cephes.gamma(5),24.0)
+
+    def test_gammainccinv(self):
+        assert_equal(cephes.gammainccinv(5,1),0.0)
+
+    def test_gammaln(self):
+        cephes.gammaln(10)
+
+    def test_gammasgn(self):
+        vals = np.array(
+            [-np.inf, -4, -3.5, -2.3, -0.0, 0.0, 1, 4.2, np.inf], np.float64
+        )
+        reference = np.array(
+            [np.nan, np.nan, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0], np.float64
+        )
+        assert_array_equal(cephes.gammasgn(vals), reference)
+
+    def test_gdtr(self):
+        assert_equal(cephes.gdtr(1,1,0),0.0)
+
+    def test_gdtr_inf(self):
+        assert_equal(cephes.gdtr(1,1,np.inf),1.0)
+
+    def test_gdtrc(self):
+        assert_equal(cephes.gdtrc(1,1,0),1.0)
+
+    def test_gdtria(self):
+        assert_equal(cephes.gdtria(0,1,1),0.0)
+
+    def test_gdtrib(self):
+        cephes.gdtrib(1,0,1)
+        # assert_equal(cephes.gdtrib(1,0,1),5.0)
+
+    def test_gdtrix(self):
+        cephes.gdtrix(1,1,.1)
+
+    def test_hankel1(self):
+        cephes.hankel1(1,1)
+
+    def test_hankel1e(self):
+        cephes.hankel1e(1,1)
+
+    def test_hankel2(self):
+        cephes.hankel2(1,1)
+
+    def test_hankel2e(self):
+        cephes.hankel2e(1,1)
+
+    def test_hyp1f1(self):
+        assert_approx_equal(cephes.hyp1f1(1,1,1), exp(1.0))
+        assert_approx_equal(cephes.hyp1f1(3,4,-6), 0.026056422099537251095)
+        cephes.hyp1f1(1,1,1)
+
+    def test_hyp2f1(self):
+        assert_equal(cephes.hyp2f1(1,1,1,0),1.0)
+
+    def test_i0(self):
+        assert_equal(cephes.i0(0),1.0)
+
+    def test_i0e(self):
+        assert_equal(cephes.i0e(0),1.0)
+
+    def test_i1(self):
+        assert_equal(cephes.i1(0),0.0)
+
+    def test_i1e(self):
+        assert_equal(cephes.i1e(0),0.0)
+
+    def test_it2i0k0(self):
+        cephes.it2i0k0(1)
+
+    def test_it2j0y0(self):
+        cephes.it2j0y0(1)
+
+    def test_it2struve0(self):
+        cephes.it2struve0(1)
+
+    def test_itairy(self):
+        cephes.itairy(1)
+
+    def test_iti0k0(self):
+        assert_equal(cephes.iti0k0(0),(0.0,0.0))
+
+    def test_itj0y0(self):
+        assert_equal(cephes.itj0y0(0),(0.0,0.0))
+
+    def test_itmodstruve0(self):
+        assert_equal(cephes.itmodstruve0(0),0.0)
+
+    def test_itstruve0(self):
+        assert_equal(cephes.itstruve0(0),0.0)
+
+    def test_iv(self):
+        assert_equal(cephes.iv(1,0),0.0)
+
+    def test_ive(self):
+        assert_equal(cephes.ive(1,0),0.0)
+
+    def test_j0(self):
+        assert_equal(cephes.j0(0),1.0)
+
+    def test_j1(self):
+        assert_equal(cephes.j1(0),0.0)
+
+    def test_jn(self):
+        assert_equal(cephes.jn(0,0),1.0)
+
+    def test_jv(self):
+        assert_equal(cephes.jv(0,0),1.0)
+
+    def test_jve(self):
+        assert_equal(cephes.jve(0,0),1.0)
+
+    def test_k0(self):
+        cephes.k0(2)
+
+    def test_k0e(self):
+        cephes.k0e(2)
+
+    def test_k1(self):
+        cephes.k1(2)
+
+    def test_k1e(self):
+        cephes.k1e(2)
+
+    def test_kei(self):
+        cephes.kei(2)
+
+    def test_keip(self):
+        assert_equal(cephes.keip(0),0.0)
+
+    def test_ker(self):
+        cephes.ker(2)
+
+    def test_kerp(self):
+        cephes.kerp(2)
+
+    def test_kelvin(self):
+        cephes.kelvin(2)
+
+    def test_kn(self):
+        cephes.kn(1,1)
+
+    def test_kolmogi(self):
+        assert_equal(cephes.kolmogi(1),0.0)
+        assert_(np.isnan(cephes.kolmogi(np.nan)))
+
+    def test_kolmogorov(self):
+        assert_equal(cephes.kolmogorov(0), 1.0)
+
+    def test_kolmogp(self):
+        assert_equal(cephes._kolmogp(0), -0.0)
+
+    def test_kolmogc(self):
+        assert_equal(cephes._kolmogc(0), 0.0)
+
+    def test_kolmogci(self):
+        assert_equal(cephes._kolmogci(0), 0.0)
+        assert_(np.isnan(cephes._kolmogci(np.nan)))
+
+    def test_kv(self):
+        cephes.kv(1,1)
+
+    def test_kve(self):
+        cephes.kve(1,1)
+
+    def test_log1p(self):
+        log1p = cephes.log1p
+        assert_equal(log1p(0), 0.0)
+        assert_equal(log1p(-1), -np.inf)
+        assert_equal(log1p(-2), np.nan)
+        assert_equal(log1p(np.inf), np.inf)
+
+    def test_log1p_complex(self):
+        log1p = cephes.log1p
+        c = complex
+        assert_equal(log1p(0 + 0j), 0 + 0j)
+        assert_equal(log1p(c(-1, 0)), c(-np.inf, 0))
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+            assert_allclose(log1p(c(1, np.inf)), c(np.inf, np.pi/2))
+            assert_equal(log1p(c(1, np.nan)), c(np.nan, np.nan))
+            assert_allclose(log1p(c(-np.inf, 1)), c(np.inf, np.pi))
+            assert_equal(log1p(c(np.inf, 1)), c(np.inf, 0))
+            assert_allclose(log1p(c(-np.inf, np.inf)), c(np.inf, 3*np.pi/4))
+            assert_allclose(log1p(c(np.inf, np.inf)), c(np.inf, np.pi/4))
+            assert_equal(log1p(c(np.inf, np.nan)), c(np.inf, np.nan))
+            assert_equal(log1p(c(-np.inf, np.nan)), c(np.inf, np.nan))
+            assert_equal(log1p(c(np.nan, np.inf)), c(np.inf, np.nan))
+            assert_equal(log1p(c(np.nan, 1)), c(np.nan, np.nan))
+            assert_equal(log1p(c(np.nan, np.nan)), c(np.nan, np.nan))
+
+    def test_lpmv(self):
+        assert_equal(cephes.lpmv(0,0,1),1.0)
+
+    def test_mathieu_a(self):
+        assert_equal(cephes.mathieu_a(1,0),1.0)
+
+    def test_mathieu_b(self):
+        assert_equal(cephes.mathieu_b(1,0),1.0)
+
+    def test_mathieu_cem(self):
+        assert_equal(cephes.mathieu_cem(1,0,0),(1.0,0.0))
+
+        # Test AMS 20.2.27
+        @np.vectorize
+        def ce_smallq(m, q, z):
+            z *= np.pi/180
+            if m == 0:
+                # + O(q^2)
+                return 2**(-0.5) * (1 - .5*q*cos(2*z))
+            elif m == 1:
+                # + O(q^2)
+                return cos(z) - q/8 * cos(3*z)
+            elif m == 2:
+                # + O(q^2)
+                return cos(2*z) - q*(cos(4*z)/12 - 1/4)
+            else:
+                # + O(q^2)
+                return cos(m*z) - q*(cos((m+2)*z)/(4*(m+1)) - cos((m-2)*z)/(4*(m-1)))
+        m = np.arange(0, 100)
+        q = np.r_[0, np.logspace(-30, -9, 10)]
+        assert_allclose(cephes.mathieu_cem(m[:,None], q[None,:], 0.123)[0],
+                        ce_smallq(m[:,None], q[None,:], 0.123),
+                        rtol=1e-14, atol=0)
+
+    def test_mathieu_sem(self):
+        assert_equal(cephes.mathieu_sem(1,0,0),(0.0,1.0))
+
+        # Test AMS 20.2.27
+        @np.vectorize
+        def se_smallq(m, q, z):
+            z *= np.pi/180
+            if m == 1:
+                # + O(q^2)
+                return sin(z) - q/8 * sin(3*z)
+            elif m == 2:
+                # + O(q^2)
+                return sin(2*z) - q*sin(4*z)/12
+            else:
+                # + O(q^2)
+                return sin(m*z) - q*(sin((m+2)*z)/(4*(m+1)) - sin((m-2)*z)/(4*(m-1)))
+        m = np.arange(1, 100)
+        q = np.r_[0, np.logspace(-30, -9, 10)]
+        assert_allclose(cephes.mathieu_sem(m[:,None], q[None,:], 0.123)[0],
+                        se_smallq(m[:,None], q[None,:], 0.123),
+                        rtol=1e-14, atol=0)
+
+    def test_mathieu_modcem1(self):
+        assert_equal(cephes.mathieu_modcem1(1,0,0),(0.0,0.0))
+
+    def test_mathieu_modcem2(self):
+        cephes.mathieu_modcem2(1,1,1)
+
+        # Test reflection relation AMS 20.6.19
+        m = np.arange(0, 4)[:,None,None]
+        q = np.r_[np.logspace(-2, 2, 10)][None,:,None]
+        z = np.linspace(0, 1, 7)[None,None,:]
+
+        y1 = cephes.mathieu_modcem2(m, q, -z)[0]
+
+        fr = -cephes.mathieu_modcem2(m, q, 0)[0] / cephes.mathieu_modcem1(m, q, 0)[0]
+        y2 = (-cephes.mathieu_modcem2(m, q, z)[0]
+              - 2*fr*cephes.mathieu_modcem1(m, q, z)[0])
+
+        assert_allclose(y1, y2, rtol=1e-10)
+
+    def test_mathieu_modsem1(self):
+        assert_equal(cephes.mathieu_modsem1(1,0,0),(0.0,0.0))
+
+    def test_mathieu_modsem2(self):
+        cephes.mathieu_modsem2(1,1,1)
+
+        # Test reflection relation AMS 20.6.20
+        m = np.arange(1, 4)[:,None,None]
+        q = np.r_[np.logspace(-2, 2, 10)][None,:,None]
+        z = np.linspace(0, 1, 7)[None,None,:]
+
+        y1 = cephes.mathieu_modsem2(m, q, -z)[0]
+        fr = cephes.mathieu_modsem2(m, q, 0)[1] / cephes.mathieu_modsem1(m, q, 0)[1]
+        y2 = (cephes.mathieu_modsem2(m, q, z)[0]
+              - 2*fr*cephes.mathieu_modsem1(m, q, z)[0])
+        assert_allclose(y1, y2, rtol=1e-10)
+
+    def test_mathieu_overflow(self):
+        # Check that these return NaNs instead of causing a SEGV
+        assert_equal(cephes.mathieu_cem(10000, 0, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_sem(10000, 0, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_cem(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_sem(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_modcem1(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_modsem1(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_modcem2(10000, 1.5, 1.3), (np.nan, np.nan))
+        assert_equal(cephes.mathieu_modsem2(10000, 1.5, 1.3), (np.nan, np.nan))
+
+    def test_mathieu_ticket_1847(self):
+        # Regression test --- this call had some out-of-bounds access
+        # and could return nan occasionally
+        for k in range(60):
+            v = cephes.mathieu_modsem2(2, 100, -1)
+            # Values from ACM TOMS 804 (derivate by numerical differentiation)
+            assert_allclose(v[0], 0.1431742913063671074347, rtol=1e-10)
+            assert_allclose(v[1], 0.9017807375832909144719, rtol=1e-4)
+
+    def test_modfresnelm(self):
+        cephes.modfresnelm(0)
+
+    def test_modfresnelp(self):
+        cephes.modfresnelp(0)
+
+    def test_modstruve(self):
+        assert_equal(cephes.modstruve(1,0),0.0)
+
+    def test_nbdtr(self):
+        assert_equal(cephes.nbdtr(1,1,1),1.0)
+
+    def test_nbdtrc(self):
+        assert_equal(cephes.nbdtrc(1,1,1),0.0)
+
+    def test_nbdtri(self):
+        assert_equal(cephes.nbdtri(1,1,1),1.0)
+
+    def test_nbdtrik(self):
+        cephes.nbdtrik(1,.4,.5)
+
+    def test_nbdtrin(self):
+        assert_equal(cephes.nbdtrin(1,0,0),5.0)
+
+    def test_ncfdtr(self):
+        assert_equal(cephes.ncfdtr(1,1,1,0),0.0)
+
+    def test_ncfdtri(self):
+        assert_equal(cephes.ncfdtri(1, 1, 1, 0), 0.0)
+        f = [0.5, 1, 1.5]
+        p = cephes.ncfdtr(2, 3, 1.5, f)
+        assert_allclose(cephes.ncfdtri(2, 3, 1.5, p), f)
+
+    @pytest.mark.xfail(
+        reason=(
+            "ncfdtr uses a Boost math implementation but ncfdtridfd"
+            "inverts the less accurate cdflib implementation of ncfdtr."
+        )
+    )
+    def test_ncfdtridfd(self):
+        dfd = [1, 2, 3]
+        p = cephes.ncfdtr(2, dfd, 0.25, 15)
+        assert_allclose(cephes.ncfdtridfd(2, p, 0.25, 15), dfd)
+
+    @pytest.mark.xfail(
+        reason=(
+            "ncfdtr uses a Boost math implementation but ncfdtridfn"
+            "inverts the less accurate cdflib implementation of ncfdtr."
+        )
+    )
+    def test_ncfdtridfn(self):
+        dfn = [0.1, 1, 2, 3, 1e4]
+        p = cephes.ncfdtr(dfn, 2, 0.25, 15)
+        assert_allclose(cephes.ncfdtridfn(p, 2, 0.25, 15), dfn, rtol=1e-5)
+
+    @pytest.mark.xfail(
+        reason=(
+            "ncfdtr uses a Boost math implementation but ncfdtrinc"
+            "inverts the less accurate cdflib implementation of ncfdtr."
+        )
+    )
+    def test_ncfdtrinc(self):
+        nc = [0.5, 1.5, 2.0]
+        p = cephes.ncfdtr(2, 3, nc, 15)
+        assert_allclose(cephes.ncfdtrinc(2, 3, p, 15), nc)
+
+    def test_nctdtr(self):
+        assert_equal(cephes.nctdtr(1,0,0),0.5)
+        assert_equal(cephes.nctdtr(9, 65536, 45), 0.0)
+
+        assert_approx_equal(cephes.nctdtr(np.inf, 1., 1.), 0.5, 5)
+        assert_(np.isnan(cephes.nctdtr(2., np.inf, 10.)))
+        assert_approx_equal(cephes.nctdtr(2., 1., np.inf), 1.)
+
+        assert_(np.isnan(cephes.nctdtr(np.nan, 1., 1.)))
+        assert_(np.isnan(cephes.nctdtr(2., np.nan, 1.)))
+        assert_(np.isnan(cephes.nctdtr(2., 1., np.nan)))
+
+    def test_nctdtridf(self):
+        cephes.nctdtridf(1,0.5,0)
+
+    def test_nctdtrinc(self):
+        cephes.nctdtrinc(1,0,0)
+
+    def test_nctdtrit(self):
+        cephes.nctdtrit(.1,0.2,.5)
+
+    def test_nrdtrimn(self):
+        assert_approx_equal(cephes.nrdtrimn(0.5,1,1),1.0)
+
+    def test_nrdtrisd(self):
+        assert_allclose(cephes.nrdtrisd(0.5,0.5,0.5), 0.0,
+                         atol=0, rtol=0)
+
+    def test_obl_ang1(self):
+        cephes.obl_ang1(1,1,1,0)
+
+    def test_obl_ang1_cv(self):
+        result = cephes.obl_ang1_cv(1,1,1,1,0)
+        assert_almost_equal(result[0],1.0)
+        assert_almost_equal(result[1],0.0)
+
+    def test_obl_cv(self):
+        assert_equal(cephes.obl_cv(1,1,0),2.0)
+
+    def test_obl_rad1(self):
+        cephes.obl_rad1(1,1,1,0)
+
+    def test_obl_rad1_cv(self):
+        cephes.obl_rad1_cv(1,1,1,1,0)
+
+    def test_obl_rad2(self):
+        cephes.obl_rad2(1,1,1,0)
+
+    def test_obl_rad2_cv(self):
+        cephes.obl_rad2_cv(1,1,1,1,0)
+
+    def test_pbdv(self):
+        assert_equal(cephes.pbdv(1,0),(0.0,1.0))
+
+    def test_pbvv(self):
+        cephes.pbvv(1,0)
+
+    def test_pbwa(self):
+        cephes.pbwa(1,0)
+
+    def test_pdtr(self):
+        val = cephes.pdtr(0, 1)
+        assert_almost_equal(val, np.exp(-1))
+        # Edge case: m = 0.
+        val = cephes.pdtr([0, 1, 2], 0)
+        assert_array_equal(val, [1, 1, 1])
+
+    def test_pdtrc(self):
+        val = cephes.pdtrc(0, 1)
+        assert_almost_equal(val, 1 - np.exp(-1))
+        # Edge case: m = 0.
+        val = cephes.pdtrc([0, 1, 2], 0.0)
+        assert_array_equal(val, [0, 0, 0])
+
+    def test_pdtri(self):
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "floating point number truncated to an integer")
+            cephes.pdtri(0.5,0.5)
+
+    def test_pdtrik(self):
+        k = cephes.pdtrik(0.5, 1)
+        assert_almost_equal(cephes.gammaincc(k + 1, 1), 0.5)
+        # Edge case: m = 0 or very small.
+        k = cephes.pdtrik([[0], [0.25], [0.95]], [0, 1e-20, 1e-6])
+        assert_array_equal(k, np.zeros((3, 3)))
+
+    def test_pro_ang1(self):
+        cephes.pro_ang1(1,1,1,0)
+
+    def test_pro_ang1_cv(self):
+        assert_array_almost_equal(cephes.pro_ang1_cv(1,1,1,1,0),
+                                  array((1.0,0.0)))
+
+    def test_pro_cv(self):
+        assert_equal(cephes.pro_cv(1,1,0),2.0)
+
+    def test_pro_rad1(self):
+        cephes.pro_rad1(1,1,1,0.1)
+
+    def test_pro_rad1_cv(self):
+        cephes.pro_rad1_cv(1,1,1,1,0)
+
+    def test_pro_rad2(self):
+        cephes.pro_rad2(1,1,1,0)
+
+    def test_pro_rad2_cv(self):
+        cephes.pro_rad2_cv(1,1,1,1,0)
+
+    def test_psi(self):
+        cephes.psi(1)
+
+    def test_radian(self):
+        assert_equal(cephes.radian(0,0,0),0)
+
+    def test_rgamma(self):
+        assert_equal(cephes.rgamma(1),1.0)
+
+    def test_round(self):
+        assert_equal(cephes.round(3.4),3.0)
+        assert_equal(cephes.round(-3.4),-3.0)
+        assert_equal(cephes.round(3.6),4.0)
+        assert_equal(cephes.round(-3.6),-4.0)
+        assert_equal(cephes.round(3.5),4.0)
+        assert_equal(cephes.round(-3.5),-4.0)
+
+    def test_shichi(self):
+        cephes.shichi(1)
+
+    def test_sici(self):
+        cephes.sici(1)
+
+        s, c = cephes.sici(np.inf)
+        assert_almost_equal(s, np.pi * 0.5)
+        assert_almost_equal(c, 0)
+
+        s, c = cephes.sici(-np.inf)
+        assert_almost_equal(s, -np.pi * 0.5)
+        assert_(np.isnan(c), "cosine integral(-inf) is not nan")
+
+    def test_sindg(self):
+        assert_equal(cephes.sindg(90),1.0)
+
+    def test_smirnov(self):
+        assert_equal(cephes.smirnov(1,.1),0.9)
+        assert_(np.isnan(cephes.smirnov(1,np.nan)))
+
+    def test_smirnovp(self):
+        assert_equal(cephes._smirnovp(1, .1), -1)
+        assert_equal(cephes._smirnovp(2, 0.75), -2*(0.25)**(2-1))
+        assert_equal(cephes._smirnovp(3, 0.75), -3*(0.25)**(3-1))
+        assert_(np.isnan(cephes._smirnovp(1, np.nan)))
+
+    def test_smirnovc(self):
+        assert_equal(cephes._smirnovc(1,.1),0.1)
+        assert_(np.isnan(cephes._smirnovc(1,np.nan)))
+        x10 = np.linspace(0, 1, 11, endpoint=True)
+        assert_almost_equal(cephes._smirnovc(3, x10), 1-cephes.smirnov(3, x10))
+        x4 = np.linspace(0, 1, 5, endpoint=True)
+        assert_almost_equal(cephes._smirnovc(4, x4), 1-cephes.smirnov(4, x4))
+
+    def test_smirnovi(self):
+        assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.4)),0.4)
+        assert_almost_equal(cephes.smirnov(1,cephes.smirnovi(1,0.6)),0.6)
+        assert_(np.isnan(cephes.smirnovi(1,np.nan)))
+
+    def test_smirnovci(self):
+        assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.4)),0.4)
+        assert_almost_equal(cephes._smirnovc(1,cephes._smirnovci(1,0.6)),0.6)
+        assert_(np.isnan(cephes._smirnovci(1,np.nan)))
+
+    def test_spence(self):
+        assert_equal(cephes.spence(1),0.0)
+
+    def test_stdtr(self):
+        assert_equal(cephes.stdtr(1,0),0.5)
+        assert_almost_equal(cephes.stdtr(1,1), 0.75)
+        assert_almost_equal(cephes.stdtr(1,2), 0.852416382349)
+
+    def test_stdtridf(self):
+        cephes.stdtridf(0.7,1)
+
+    def test_stdtrit(self):
+        cephes.stdtrit(1,0.7)
+
+    def test_struve(self):
+        assert_equal(cephes.struve(0,0),0.0)
+
+    def test_tandg(self):
+        assert_equal(cephes.tandg(45),1.0)
+
+    def test_tklmbda(self):
+        assert_almost_equal(cephes.tklmbda(1,1),1.0)
+
+    def test_y0(self):
+        cephes.y0(1)
+
+    def test_y1(self):
+        cephes.y1(1)
+
+    def test_yn(self):
+        cephes.yn(1,1)
+
+    def test_yv(self):
+        cephes.yv(1,1)
+
+    def test_yve(self):
+        cephes.yve(1,1)
+
+    def test_wofz(self):
+        z = [complex(624.2,-0.26123), complex(-0.4,3.), complex(0.6,2.),
+             complex(-1.,1.), complex(-1.,-9.), complex(-1.,9.),
+             complex(-0.0000000234545,1.1234), complex(-3.,5.1),
+             complex(-53,30.1), complex(0.0,0.12345),
+             complex(11,1), complex(-22,-2), complex(9,-28),
+             complex(21,-33), complex(1e5,1e5), complex(1e14,1e14)
+             ]
+        w = [
+            complex(-3.78270245518980507452677445620103199303131110e-7,
+                    0.000903861276433172057331093754199933411710053155),
+            complex(0.1764906227004816847297495349730234591778719532788,
+                    -0.02146550539468457616788719893991501311573031095617),
+            complex(0.2410250715772692146133539023007113781272362309451,
+                    0.06087579663428089745895459735240964093522265589350),
+            complex(0.30474420525691259245713884106959496013413834051768,
+                    -0.20821893820283162728743734725471561394145872072738),
+            complex(7.317131068972378096865595229600561710140617977e34,
+                    8.321873499714402777186848353320412813066170427e34),
+            complex(0.0615698507236323685519612934241429530190806818395,
+                    -0.00676005783716575013073036218018565206070072304635),
+            complex(0.3960793007699874918961319170187598400134746631,
+                    -5.593152259116644920546186222529802777409274656e-9),
+            complex(0.08217199226739447943295069917990417630675021771804,
+                    -0.04701291087643609891018366143118110965272615832184),
+            complex(0.00457246000350281640952328010227885008541748668738,
+                    -0.00804900791411691821818731763401840373998654987934),
+            complex(0.8746342859608052666092782112565360755791467973338452,
+                    0.),
+            complex(0.00468190164965444174367477874864366058339647648741,
+                    0.0510735563901306197993676329845149741675029197050),
+            complex(-0.0023193175200187620902125853834909543869428763219,
+                    -0.025460054739731556004902057663500272721780776336),
+            complex(9.11463368405637174660562096516414499772662584e304,
+                    3.97101807145263333769664875189354358563218932e305),
+            complex(-4.4927207857715598976165541011143706155432296e281,
+                    -2.8019591213423077494444700357168707775769028e281),
+            complex(2.820947917809305132678577516325951485807107151e-6,
+                    2.820947917668257736791638444590253942253354058e-6),
+            complex(2.82094791773878143474039725787438662716372268e-15,
+                    2.82094791773878143474039725773333923127678361e-15)
+        ]
+        assert_func_equal(cephes.wofz, w, z, rtol=1e-13)
+
+
+class TestAiry:
+    def test_airy(self):
+        # This tests the airy function to ensure 8 place accuracy in computation
+
+        x = special.airy(.99)
+        assert_array_almost_equal(
+            x,
+            array([0.13689066,-0.16050153,1.19815925,0.92046818]),
+            8,
+        )
+        x = special.airy(.41)
+        assert_array_almost_equal(
+            x,
+            array([0.25238916,-.23480512,0.80686202,0.51053919]),
+            8,
+        )
+        x = special.airy(-.36)
+        assert_array_almost_equal(
+            x,
+            array([0.44508477,-0.23186773,0.44939534,0.48105354]),
+            8,
+        )
+
+    def test_airye(self):
+        a = special.airye(0.01)
+        b = special.airy(0.01)
+        b1 = [None]*4
+        for n in range(2):
+            b1[n] = b[n]*exp(2.0/3.0*0.01*sqrt(0.01))
+        for n in range(2,4):
+            b1[n] = b[n]*exp(-abs(real(2.0/3.0*0.01*sqrt(0.01))))
+        assert_array_almost_equal(a,b1,6)
+
+    def test_bi_zeros(self):
+        bi = special.bi_zeros(2)
+        bia = (array([-1.17371322, -3.2710930]),
+               array([-2.29443968, -4.07315509]),
+               array([-0.45494438, 0.39652284]),
+               array([0.60195789, -0.76031014]))
+        assert_array_almost_equal(bi,bia,4)
+
+        bi = special.bi_zeros(5)
+        assert_array_almost_equal(bi[0],array([-1.173713222709127,
+                                               -3.271093302836352,
+                                               -4.830737841662016,
+                                               -6.169852128310251,
+                                               -7.376762079367764]),11)
+
+        assert_array_almost_equal(bi[1],array([-2.294439682614122,
+                                               -4.073155089071828,
+                                               -5.512395729663599,
+                                               -6.781294445990305,
+                                               -7.940178689168587]),10)
+
+        assert_array_almost_equal(bi[2],array([-0.454944383639657,
+                                               0.396522836094465,
+                                               -0.367969161486959,
+                                               0.349499116831805,
+                                               -0.336026240133662]),11)
+
+        assert_array_almost_equal(bi[3],array([0.601957887976239,
+                                               -0.760310141492801,
+                                               0.836991012619261,
+                                               -0.88947990142654,
+                                               0.929983638568022]),10)
+
+    def test_ai_zeros(self):
+        ai = special.ai_zeros(1)
+        assert_array_almost_equal(ai,(array([-2.33810741]),
+                                     array([-1.01879297]),
+                                     array([0.5357]),
+                                     array([0.7012])),4)
+
+    @pytest.mark.fail_slow(5)
+    def test_ai_zeros_big(self):
+        z, zp, ai_zpx, aip_zx = special.ai_zeros(50000)
+        ai_z, aip_z, _, _ = special.airy(z)
+        ai_zp, aip_zp, _, _ = special.airy(zp)
+
+        ai_envelope = 1/abs(z)**(1./4)
+        aip_envelope = abs(zp)**(1./4)
+
+        # Check values
+        assert_allclose(ai_zpx, ai_zp, rtol=1e-10)
+        assert_allclose(aip_zx, aip_z, rtol=1e-10)
+
+        # Check they are zeros
+        assert_allclose(ai_z/ai_envelope, 0, atol=1e-10, rtol=0)
+        assert_allclose(aip_zp/aip_envelope, 0, atol=1e-10, rtol=0)
+
+        # Check first zeros, DLMF 9.9.1
+        assert_allclose(z[:6],
+            [-2.3381074105, -4.0879494441, -5.5205598281,
+             -6.7867080901, -7.9441335871, -9.0226508533], rtol=1e-10)
+        assert_allclose(zp[:6],
+            [-1.0187929716, -3.2481975822, -4.8200992112,
+             -6.1633073556, -7.3721772550, -8.4884867340], rtol=1e-10)
+
+    @pytest.mark.fail_slow(5)
+    def test_bi_zeros_big(self):
+        z, zp, bi_zpx, bip_zx = special.bi_zeros(50000)
+        _, _, bi_z, bip_z = special.airy(z)
+        _, _, bi_zp, bip_zp = special.airy(zp)
+
+        bi_envelope = 1/abs(z)**(1./4)
+        bip_envelope = abs(zp)**(1./4)
+
+        # Check values
+        assert_allclose(bi_zpx, bi_zp, rtol=1e-10)
+        assert_allclose(bip_zx, bip_z, rtol=1e-10)
+
+        # Check they are zeros
+        assert_allclose(bi_z/bi_envelope, 0, atol=1e-10, rtol=0)
+        assert_allclose(bip_zp/bip_envelope, 0, atol=1e-10, rtol=0)
+
+        # Check first zeros, DLMF 9.9.2
+        assert_allclose(z[:6],
+            [-1.1737132227, -3.2710933028, -4.8307378417,
+             -6.1698521283, -7.3767620794, -8.4919488465], rtol=1e-10)
+        assert_allclose(zp[:6],
+            [-2.2944396826, -4.0731550891, -5.5123957297,
+             -6.7812944460, -7.9401786892, -9.0195833588], rtol=1e-10)
+
+
+class TestAssocLaguerre:
+    def test_assoc_laguerre(self):
+        a1 = special.genlaguerre(11,1)
+        a2 = special.assoc_laguerre(.2,11,1)
+        assert_array_almost_equal(a2,a1(.2),8)
+        a2 = special.assoc_laguerre(1,11,1)
+        assert_array_almost_equal(a2,a1(1),8)
+
+
+class TestBesselpoly:
+    def test_besselpoly(self):
+        pass
+
+
+class TestKelvin:
+    def test_bei(self):
+        mbei = special.bei(2)
+        assert_almost_equal(mbei, 0.9722916273066613,5)  # this may not be exact
+
+    def test_beip(self):
+        mbeip = special.beip(2)
+        assert_almost_equal(mbeip,0.91701361338403631,5)  # this may not be exact
+
+    def test_ber(self):
+        mber = special.ber(2)
+        assert_almost_equal(mber,0.75173418271380821,5)  # this may not be exact
+
+    def test_berp(self):
+        mberp = special.berp(2)
+        assert_almost_equal(mberp,-0.49306712470943909,5)  # this may not be exact
+
+    def test_bei_zeros(self):
+        # Abramowitz & Stegun, Table 9.12
+        bi = special.bei_zeros(5)
+        assert_array_almost_equal(bi,array([5.02622,
+                                            9.45541,
+                                            13.89349,
+                                            18.33398,
+                                            22.77544]),4)
+
+    def test_beip_zeros(self):
+        bip = special.beip_zeros(5)
+        assert_array_almost_equal(bip,array([3.772673304934953,
+                                               8.280987849760042,
+                                               12.742147523633703,
+                                               17.193431752512542,
+                                               21.641143941167325]),8)
+
+    def test_ber_zeros(self):
+        ber = special.ber_zeros(5)
+        assert_array_almost_equal(ber,array([2.84892,
+                                             7.23883,
+                                             11.67396,
+                                             16.11356,
+                                             20.55463]),4)
+
+    def test_berp_zeros(self):
+        brp = special.berp_zeros(5)
+        assert_array_almost_equal(brp,array([6.03871,
+                                             10.51364,
+                                             14.96844,
+                                             19.41758,
+                                             23.86430]),4)
+
+    def test_kelvin(self):
+        mkelv = special.kelvin(2)
+        assert_array_almost_equal(mkelv,(special.ber(2) + special.bei(2)*1j,
+                                         special.ker(2) + special.kei(2)*1j,
+                                         special.berp(2) + special.beip(2)*1j,
+                                         special.kerp(2) + special.keip(2)*1j),8)
+
+    def test_kei(self):
+        mkei = special.kei(2)
+        assert_almost_equal(mkei,-0.20240006776470432,5)
+
+    def test_keip(self):
+        mkeip = special.keip(2)
+        assert_almost_equal(mkeip,0.21980790991960536,5)
+
+    def test_ker(self):
+        mker = special.ker(2)
+        assert_almost_equal(mker,-0.041664513991509472,5)
+
+    def test_kerp(self):
+        mkerp = special.kerp(2)
+        assert_almost_equal(mkerp,-0.10660096588105264,5)
+
+    def test_kei_zeros(self):
+        kei = special.kei_zeros(5)
+        assert_array_almost_equal(kei,array([3.91467,
+                                              8.34422,
+                                              12.78256,
+                                              17.22314,
+                                              21.66464]),4)
+
+    def test_keip_zeros(self):
+        keip = special.keip_zeros(5)
+        assert_array_almost_equal(keip,array([4.93181,
+                                                9.40405,
+                                                13.85827,
+                                                18.30717,
+                                                22.75379]),4)
+
+    # numbers come from 9.9 of A&S pg. 381
+    def test_kelvin_zeros(self):
+        tmp = special.kelvin_zeros(5)
+        berz,beiz,kerz,keiz,berpz,beipz,kerpz,keipz = tmp
+        assert_array_almost_equal(berz,array([2.84892,
+                                               7.23883,
+                                               11.67396,
+                                               16.11356,
+                                               20.55463]),4)
+        assert_array_almost_equal(beiz,array([5.02622,
+                                               9.45541,
+                                               13.89349,
+                                               18.33398,
+                                               22.77544]),4)
+        assert_array_almost_equal(kerz,array([1.71854,
+                                               6.12728,
+                                               10.56294,
+                                               15.00269,
+                                               19.44382]),4)
+        assert_array_almost_equal(keiz,array([3.91467,
+                                               8.34422,
+                                               12.78256,
+                                               17.22314,
+                                               21.66464]),4)
+        assert_array_almost_equal(berpz,array([6.03871,
+                                                10.51364,
+                                                14.96844,
+                                                19.41758,
+                                                23.86430]),4)
+        assert_array_almost_equal(beipz,array([3.77267,
+                 # table from 1927 had 3.77320
+                 #  but this is more accurate
+                                                8.28099,
+                                                12.74215,
+                                                17.19343,
+                                                21.64114]),4)
+        assert_array_almost_equal(kerpz,array([2.66584,
+                                                7.17212,
+                                                11.63218,
+                                                16.08312,
+                                                20.53068]),4)
+        assert_array_almost_equal(keipz,array([4.93181,
+                                                9.40405,
+                                                13.85827,
+                                                18.30717,
+                                                22.75379]),4)
+
+    def test_ker_zeros(self):
+        ker = special.ker_zeros(5)
+        assert_array_almost_equal(ker,array([1.71854,
+                                               6.12728,
+                                               10.56294,
+                                               15.00269,
+                                               19.44381]),4)
+
+    def test_kerp_zeros(self):
+        kerp = special.kerp_zeros(5)
+        assert_array_almost_equal(kerp,array([2.66584,
+                                                7.17212,
+                                                11.63218,
+                                                16.08312,
+                                                20.53068]),4)
+
+
+class TestBernoulli:
+    def test_bernoulli(self):
+        brn = special.bernoulli(5)
+        assert_array_almost_equal(brn,array([1.0000,
+                                             -0.5000,
+                                             0.1667,
+                                             0.0000,
+                                             -0.0333,
+                                             0.0000]),4)
+
+
+class TestBeta:
+    """
+    Test beta and betaln.
+    """
+
+    def test_beta(self):
+        assert_equal(special.beta(1, 1), 1.0)
+        assert_allclose(special.beta(-100.3, 1e-200), special.gamma(1e-200))
+        assert_allclose(special.beta(0.0342, 171), 24.070498359873497,
+                        rtol=1e-13, atol=0)
+
+        bet = special.beta(2, 4)
+        betg = (special.gamma(2)*special.gamma(4))/special.gamma(6)
+        assert_allclose(bet, betg, rtol=1e-13)
+
+    def test_beta_inf(self):
+        assert_(np.isinf(special.beta(-1, 2)))
+
+    def test_betaln(self):
+        assert_equal(special.betaln(1, 1), 0.0)
+        assert_allclose(special.betaln(-100.3, 1e-200),
+                        special.gammaln(1e-200))
+        assert_allclose(special.betaln(0.0342, 170), 3.1811881124242447,
+                        rtol=1e-14, atol=0)
+
+        betln = special.betaln(2, 4)
+        bet = log(abs(special.beta(2, 4)))
+        assert_allclose(betln, bet, rtol=1e-13)
+
+
+class TestBetaInc:
+    """
+    Tests for betainc, betaincinv, betaincc, betainccinv.
+    """
+
+    def test_a1_b1(self):
+        # betainc(1, 1, x) is x.
+        x = np.array([0, 0.25, 1])
+        assert_equal(special.betainc(1, 1, x), x)
+        assert_equal(special.betaincinv(1, 1, x), x)
+        assert_equal(special.betaincc(1, 1, x), 1 - x)
+        assert_equal(special.betainccinv(1, 1, x), 1 - x)
+
+    # Nontrivial expected values computed with mpmath:
+    #    from mpmath import mp
+    #    mp.dps = 100
+    #    p = mp.betainc(a, b, 0, x, regularized=True)
+    #
+    # or, e.g.,
+    #
+    #    p = 0.25
+    #    a, b = 0.0342, 171
+    #    x = mp.findroot(
+    #        lambda t: mp.betainc(a, b, 0, t, regularized=True) - p,
+    #        (8e-21, 9e-21),
+    #        solver='anderson',
+    #    )
+    #
+    @pytest.mark.parametrize(
+        'a, b, x, p',
+        [(2, 4, 0.3138101704556974, 0.5),
+         (0.0342, 171.0, 1e-10, 0.552699169018070910641),
+         # gh-3761:
+         (0.0342, 171, 8.42313169354797e-21, 0.25),
+         # gh-4244:
+         (0.0002742794749792665, 289206.03125, 1.639984034231756e-56,
+          0.9688708782196045),
+         # gh-12796:
+         (4, 99997, 0.0001947841578892121, 0.999995)])
+    def test_betainc_betaincinv(self, a, b, x, p):
+        p1 = special.betainc(a, b, x)
+        assert_allclose(p1, p, rtol=1e-15)
+        x1 = special.betaincinv(a, b, p)
+        assert_allclose(x1, x, rtol=5e-13)
+
+    # Expected values computed with mpmath:
+    #     from mpmath import mp
+    #     mp.dps = 100
+    #     p = mp.betainc(a, b, x, 1, regularized=True)
+    @pytest.mark.parametrize('a, b, x, p',
+                             [(2.5, 3.0, 0.25, 0.833251953125),
+                              (7.5, 13.25, 0.375, 0.43298734645560368593),
+                              (0.125, 7.5, 0.425, 0.0006688257851314237),
+                              (0.125, 18.0, 1e-6, 0.72982359145096327654),
+                              (0.125, 18.0, 0.996, 7.2745875538380150586e-46),
+                              (0.125, 24.0, 0.75, 3.70853404816862016966e-17),
+                              (16.0, 0.75, 0.99999999975,
+                               5.4408759277418629909e-07),
+                              # gh-4677 (numbers from stackoverflow question):
+                              (0.4211959643503401, 16939.046996018118,
+                               0.000815296167195521, 1e-7)])
+    def test_betaincc_betainccinv(self, a, b, x, p):
+        p1 = special.betaincc(a, b, x)
+        assert_allclose(p1, p, rtol=5e-15)
+        x1 = special.betainccinv(a, b, p)
+        assert_allclose(x1, x, rtol=8e-15)
+
+    @pytest.mark.parametrize(
+        'a, b, y, ref',
+        [(14.208308325339239, 14.208308325339239, 7.703145458496392e-307,
+          8.566004561846704e-23),
+         (14.0, 14.5, 1e-280, 2.9343915006642424e-21),
+         (3.5, 15.0, 4e-95, 1.3290751429289227e-28),
+         (10.0, 1.25, 2e-234, 3.982659092143654e-24),
+         (4.0, 99997.0, 5e-88, 3.309800566862242e-27)]
+    )
+    def test_betaincinv_tiny_y(self, a, b, y, ref):
+        # Test with extremely small y values.  This test includes
+        # a regression test for an issue in the boost code;
+        # see https://github.com/boostorg/math/issues/961
+        #
+        # The reference values were computed with mpmath. For example,
+        #
+        #   from mpmath import mp
+        #   mp.dps = 1000
+        #   a = 14.208308325339239
+        #   p = 7.703145458496392e-307
+        #   x = mp.findroot(lambda t: mp.betainc(a, a, 0, t,
+        #                                        regularized=True) - p,
+        #                   x0=8.566e-23)
+        #   print(float(x))
+        #
+        x = special.betaincinv(a, b, y)
+        assert_allclose(x, ref, rtol=1e-14)
+
+    @pytest.mark.parametrize('func', [special.betainc, special.betaincinv,
+                                      special.betaincc, special.betainccinv])
+    @pytest.mark.parametrize('args', [(-1.0, 2, 0.5), (0, 2, 0.5),
+                                      (1.5, -2.0, 0.5), (1.5, 0, 0.5),
+                                      (1.5, 2.0, -0.3), (1.5, 2.0, 1.1)])
+    def test_betainc_domain_errors(self, func, args):
+        with special.errstate(domain='raise'):
+            with pytest.raises(special.SpecialFunctionError, match='domain'):
+                special.betainc(*args)
+
+    @pytest.mark.parametrize('dtype', [np.float32, np.float64])
+    def test_gh21426(self, dtype):
+        # Test for gh-21426: betaincinv must not return NaN
+        a = np.array([5.], dtype=dtype)
+        x = np.array([0.5], dtype=dtype)
+        result = special.betaincinv(a, a, x)
+        assert_allclose(result, x, rtol=10 * np.finfo(dtype).eps)
+
+
+class TestCombinatorics:
+    def test_comb(self):
+        assert_allclose(special.comb([10, 10], [3, 4]), [120., 210.])
+        assert_allclose(special.comb(10, 3), 120.)
+        assert_equal(special.comb(10, 3, exact=True), 120)
+        assert_equal(special.comb(10, 3, exact=True, repetition=True), 220)
+
+        assert_allclose([special.comb(20, k, exact=True) for k in range(21)],
+                        special.comb(20, list(range(21))), atol=1e-15)
+
+        ii = np.iinfo(int).max + 1
+        assert_equal(special.comb(ii, ii-1, exact=True), ii)
+
+        expected = 100891344545564193334812497256
+        assert special.comb(100, 50, exact=True) == expected
+
+    def test_comb_with_np_int64(self):
+        n = 70
+        k = 30
+        np_n = np.int64(n)
+        np_k = np.int64(k)
+        res_np = special.comb(np_n, np_k, exact=True)
+        res_py = special.comb(n, k, exact=True)
+        assert res_np == res_py
+
+    def test_comb_zeros(self):
+        assert_equal(special.comb(2, 3, exact=True), 0)
+        assert_equal(special.comb(-1, 3, exact=True), 0)
+        assert_equal(special.comb(2, -1, exact=True), 0)
+        assert_equal(special.comb(2, -1, exact=False), 0)
+        assert_allclose(special.comb([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 120.])
+
+    @pytest.mark.thread_unsafe
+    def test_comb_exact_non_int_dep(self):
+        msg = "`exact=True`"
+        with pytest.deprecated_call(match=msg):
+            special.comb(3.4, 4, exact=True)
+
+    def test_perm(self):
+        assert_allclose(special.perm([10, 10], [3, 4]), [720., 5040.])
+        assert_almost_equal(special.perm(10, 3), 720.)
+        assert_equal(special.perm(10, 3, exact=True), 720)
+
+    def test_perm_zeros(self):
+        assert_equal(special.perm(2, 3, exact=True), 0)
+        assert_equal(special.perm(-1, 3, exact=True), 0)
+        assert_equal(special.perm(2, -1, exact=True), 0)
+        assert_equal(special.perm(2, -1, exact=False), 0)
+        assert_allclose(special.perm([2, -1, 2, 10], [3, 3, -1, 3]), [0., 0., 0., 720.])
+
+    @pytest.mark.thread_unsafe
+    def test_perm_iv(self):
+        # currently `exact=True` only support scalars
+        with pytest.raises(ValueError, match="scalar integers"):
+            special.perm([1, 2], [4, 5], exact=True)
+
+        # Non-integral scalars with N < k, or N,k < 0 used to return 0, this is now
+        # deprecated and will raise an error in SciPy 1.16.0
+        with pytest.deprecated_call(match="Non-integer"):
+            special.perm(4.6, 6, exact=True)
+        with pytest.deprecated_call(match="Non-integer"):
+            special.perm(-4.6, 3, exact=True)
+        with pytest.deprecated_call(match="Non-integer"):
+            special.perm(4, -3.9, exact=True)
+
+        # Non-integral scalars which aren't included in the cases above an raise an
+        # error directly without deprecation as this code never worked
+        with pytest.raises(ValueError, match="Non-integer"):
+            special.perm(6.0, 4.6, exact=True)
+
+
+class TestTrigonometric:
+    def test_cbrt(self):
+        cb = special.cbrt(27)
+        cbrl = 27**(1.0/3.0)
+        assert_approx_equal(cb,cbrl)
+
+    def test_cbrtmore(self):
+        cb1 = special.cbrt(27.9)
+        cbrl1 = 27.9**(1.0/3.0)
+        assert_almost_equal(cb1,cbrl1,8)
+
+    def test_cosdg(self):
+        cdg = special.cosdg(90)
+        cdgrl = cos(pi/2.0)
+        assert_almost_equal(cdg,cdgrl,8)
+
+    def test_cosdgmore(self):
+        cdgm = special.cosdg(30)
+        cdgmrl = cos(pi/6.0)
+        assert_almost_equal(cdgm,cdgmrl,8)
+
+    def test_cosm1(self):
+        cs = (special.cosm1(0),special.cosm1(.3),special.cosm1(pi/10))
+        csrl = (cos(0)-1,cos(.3)-1,cos(pi/10)-1)
+        assert_array_almost_equal(cs,csrl,8)
+
+    def test_cotdg(self):
+        ct = special.cotdg(30)
+        ctrl = tan(pi/6.0)**(-1)
+        assert_almost_equal(ct,ctrl,8)
+
+    def test_cotdgmore(self):
+        ct1 = special.cotdg(45)
+        ctrl1 = tan(pi/4.0)**(-1)
+        assert_almost_equal(ct1,ctrl1,8)
+
+    def test_specialpoints(self):
+        assert_almost_equal(special.cotdg(45), 1.0, 14)
+        assert_almost_equal(special.cotdg(-45), -1.0, 14)
+        assert_almost_equal(special.cotdg(90), 0.0, 14)
+        assert_almost_equal(special.cotdg(-90), 0.0, 14)
+        assert_almost_equal(special.cotdg(135), -1.0, 14)
+        assert_almost_equal(special.cotdg(-135), 1.0, 14)
+        assert_almost_equal(special.cotdg(225), 1.0, 14)
+        assert_almost_equal(special.cotdg(-225), -1.0, 14)
+        assert_almost_equal(special.cotdg(270), 0.0, 14)
+        assert_almost_equal(special.cotdg(-270), 0.0, 14)
+        assert_almost_equal(special.cotdg(315), -1.0, 14)
+        assert_almost_equal(special.cotdg(-315), 1.0, 14)
+        assert_almost_equal(special.cotdg(765), 1.0, 14)
+
+    def test_sinc(self):
+        # the sinc implementation and more extensive sinc tests are in numpy
+        assert_array_equal(special.sinc([0]), 1)
+        assert_equal(special.sinc(0.0), 1.0)
+
+    def test_sindg(self):
+        sn = special.sindg(90)
+        assert_equal(sn,1.0)
+
+    def test_sindgmore(self):
+        snm = special.sindg(30)
+        snmrl = sin(pi/6.0)
+        assert_almost_equal(snm,snmrl,8)
+        snm1 = special.sindg(45)
+        snmrl1 = sin(pi/4.0)
+        assert_almost_equal(snm1,snmrl1,8)
+
+
+class TestTandg:
+
+    def test_tandg(self):
+        tn = special.tandg(30)
+        tnrl = tan(pi/6.0)
+        assert_almost_equal(tn,tnrl,8)
+
+    def test_tandgmore(self):
+        tnm = special.tandg(45)
+        tnmrl = tan(pi/4.0)
+        assert_almost_equal(tnm,tnmrl,8)
+        tnm1 = special.tandg(60)
+        tnmrl1 = tan(pi/3.0)
+        assert_almost_equal(tnm1,tnmrl1,8)
+
+    def test_specialpoints(self):
+        assert_almost_equal(special.tandg(0), 0.0, 14)
+        assert_almost_equal(special.tandg(45), 1.0, 14)
+        assert_almost_equal(special.tandg(-45), -1.0, 14)
+        assert_almost_equal(special.tandg(135), -1.0, 14)
+        assert_almost_equal(special.tandg(-135), 1.0, 14)
+        assert_almost_equal(special.tandg(180), 0.0, 14)
+        assert_almost_equal(special.tandg(-180), 0.0, 14)
+        assert_almost_equal(special.tandg(225), 1.0, 14)
+        assert_almost_equal(special.tandg(-225), -1.0, 14)
+        assert_almost_equal(special.tandg(315), -1.0, 14)
+        assert_almost_equal(special.tandg(-315), 1.0, 14)
+
+
+class TestEllip:
+    def test_ellipj_nan(self):
+        """Regression test for #912."""
+        special.ellipj(0.5, np.nan)
+
+    def test_ellipj(self):
+        el = special.ellipj(0.2,0)
+        rel = [sin(0.2),cos(0.2),1.0,0.20]
+        assert_array_almost_equal(el,rel,13)
+
+    def test_ellipk(self):
+        elk = special.ellipk(.2)
+        assert_almost_equal(elk,1.659623598610528,11)
+
+        assert_equal(special.ellipkm1(0.0), np.inf)
+        assert_equal(special.ellipkm1(1.0), pi/2)
+        assert_equal(special.ellipkm1(np.inf), 0.0)
+        assert_equal(special.ellipkm1(np.nan), np.nan)
+        assert_equal(special.ellipkm1(-1), np.nan)
+        assert_allclose(special.ellipk(-10), 0.7908718902387385)
+
+    def test_ellipkinc(self):
+        elkinc = special.ellipkinc(pi/2,.2)
+        elk = special.ellipk(0.2)
+        assert_almost_equal(elkinc,elk,15)
+        alpha = 20*pi/180
+        phi = 45*pi/180
+        m = sin(alpha)**2
+        elkinc = special.ellipkinc(phi,m)
+        assert_almost_equal(elkinc,0.79398143,8)
+        # From pg. 614 of A & S
+
+        assert_equal(special.ellipkinc(pi/2, 0.0), pi/2)
+        assert_equal(special.ellipkinc(pi/2, 1.0), np.inf)
+        assert_equal(special.ellipkinc(pi/2, -np.inf), 0.0)
+        assert_equal(special.ellipkinc(pi/2, np.nan), np.nan)
+        assert_equal(special.ellipkinc(pi/2, 2), np.nan)
+        assert_equal(special.ellipkinc(0, 0.5), 0.0)
+        assert_equal(special.ellipkinc(np.inf, 0.5), np.inf)
+        assert_equal(special.ellipkinc(-np.inf, 0.5), -np.inf)
+        assert_equal(special.ellipkinc(np.inf, np.inf), np.nan)
+        assert_equal(special.ellipkinc(np.inf, -np.inf), np.nan)
+        assert_equal(special.ellipkinc(-np.inf, -np.inf), np.nan)
+        assert_equal(special.ellipkinc(-np.inf, np.inf), np.nan)
+        assert_equal(special.ellipkinc(np.nan, 0.5), np.nan)
+        assert_equal(special.ellipkinc(np.nan, np.nan), np.nan)
+
+        assert_allclose(special.ellipkinc(0.38974112035318718, 1), 0.4, rtol=1e-14)
+        assert_allclose(special.ellipkinc(1.5707, -10), 0.79084284661724946)
+
+    def test_ellipkinc_2(self):
+        # Regression test for gh-3550
+        # ellipkinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value
+        mbad = 0.68359375000000011
+        phi = 0.9272952180016123
+        m = np.nextafter(mbad, 0)
+        mvals = []
+        for j in range(10):
+            mvals.append(m)
+            m = np.nextafter(m, 1)
+        f = special.ellipkinc(phi, mvals)
+        assert_array_almost_equal_nulp(f, np.full_like(f, 1.0259330100195334), 1)
+        # this bug also appears at phi + n * pi for at least small n
+        f1 = special.ellipkinc(phi + pi, mvals)
+        assert_array_almost_equal_nulp(f1, np.full_like(f1, 5.1296650500976675), 2)
+
+    def test_ellipkinc_singular(self):
+        # ellipkinc(phi, 1) has closed form and is finite only for phi in (-pi/2, pi/2)
+        xlog = np.logspace(-300, -17, 25)
+        xlin = np.linspace(1e-17, 0.1, 25)
+        xlin2 = np.linspace(0.1, pi/2, 25, endpoint=False)
+
+        assert_allclose(special.ellipkinc(xlog, 1), np.arcsinh(np.tan(xlog)),
+                        rtol=1e14)
+        assert_allclose(special.ellipkinc(xlin, 1), np.arcsinh(np.tan(xlin)),
+                        rtol=1e14)
+        assert_allclose(special.ellipkinc(xlin2, 1), np.arcsinh(np.tan(xlin2)),
+                        rtol=1e14)
+        assert_equal(special.ellipkinc(np.pi/2, 1), np.inf)
+        assert_allclose(special.ellipkinc(-xlog, 1), np.arcsinh(np.tan(-xlog)),
+                        rtol=1e14)
+        assert_allclose(special.ellipkinc(-xlin, 1), np.arcsinh(np.tan(-xlin)),
+                        rtol=1e14)
+        assert_allclose(special.ellipkinc(-xlin2, 1), np.arcsinh(np.tan(-xlin2)),
+                        rtol=1e14)
+        assert_equal(special.ellipkinc(-np.pi/2, 1), np.inf)
+
+    def test_ellipe(self):
+        ele = special.ellipe(.2)
+        assert_almost_equal(ele,1.4890350580958529,8)
+
+        assert_equal(special.ellipe(0.0), pi/2)
+        assert_equal(special.ellipe(1.0), 1.0)
+        assert_equal(special.ellipe(-np.inf), np.inf)
+        assert_equal(special.ellipe(np.nan), np.nan)
+        assert_equal(special.ellipe(2), np.nan)
+        assert_allclose(special.ellipe(-10), 3.6391380384177689)
+
+    def test_ellipeinc(self):
+        eleinc = special.ellipeinc(pi/2,.2)
+        ele = special.ellipe(0.2)
+        assert_almost_equal(eleinc,ele,14)
+        # pg 617 of A & S
+        alpha, phi = 52*pi/180,35*pi/180
+        m = sin(alpha)**2
+        eleinc = special.ellipeinc(phi,m)
+        assert_almost_equal(eleinc, 0.58823065, 8)
+
+        assert_equal(special.ellipeinc(pi/2, 0.0), pi/2)
+        assert_equal(special.ellipeinc(pi/2, 1.0), 1.0)
+        assert_equal(special.ellipeinc(pi/2, -np.inf), np.inf)
+        assert_equal(special.ellipeinc(pi/2, np.nan), np.nan)
+        assert_equal(special.ellipeinc(pi/2, 2), np.nan)
+        assert_equal(special.ellipeinc(0, 0.5), 0.0)
+        assert_equal(special.ellipeinc(np.inf, 0.5), np.inf)
+        assert_equal(special.ellipeinc(-np.inf, 0.5), -np.inf)
+        assert_equal(special.ellipeinc(np.inf, -np.inf), np.inf)
+        assert_equal(special.ellipeinc(-np.inf, -np.inf), -np.inf)
+        assert_equal(special.ellipeinc(np.inf, np.inf), np.nan)
+        assert_equal(special.ellipeinc(-np.inf, np.inf), np.nan)
+        assert_equal(special.ellipeinc(np.nan, 0.5), np.nan)
+        assert_equal(special.ellipeinc(np.nan, np.nan), np.nan)
+        assert_allclose(special.ellipeinc(1.5707, -10), 3.6388185585822876)
+
+    def test_ellipeinc_2(self):
+        # Regression test for gh-3550
+        # ellipeinc(phi, mbad) was NaN and mvals[2:6] were twice the correct value
+        mbad = 0.68359375000000011
+        phi = 0.9272952180016123
+        m = np.nextafter(mbad, 0)
+        mvals = []
+        for j in range(10):
+            mvals.append(m)
+            m = np.nextafter(m, 1)
+        f = special.ellipeinc(phi, mvals)
+        assert_array_almost_equal_nulp(f, np.full_like(f, 0.84442884574781019), 2)
+        # this bug also appears at phi + n * pi for at least small n
+        f1 = special.ellipeinc(phi + pi, mvals)
+        assert_array_almost_equal_nulp(f1, np.full_like(f1, 3.3471442287390509), 4)
+
+
+class TestEllipCarlson:
+    """Test for Carlson elliptic integrals ellipr[cdfgj].
+    The special values used in these tests can be found in Sec. 3 of Carlson
+    (1994), https://arxiv.org/abs/math/9409227
+    """
+    def test_elliprc(self):
+        assert_allclose(elliprc(1, 1), 1)
+        assert elliprc(1, inf) == 0.0
+        assert isnan(elliprc(1, 0))
+        assert elliprc(1, complex(1, inf)) == 0.0
+        args = array([[0.0, 0.25],
+                      [2.25, 2.0],
+                      [0.0, 1.0j],
+                      [-1.0j, 1.0j],
+                      [0.25, -2.0],
+                      [1.0j, -1.0]])
+        expected_results = array([np.pi,
+                                  np.log(2.0),
+                                  1.1107207345396 * (1.0-1.0j),
+                                  1.2260849569072-0.34471136988768j,
+                                  np.log(2.0) / 3.0,
+                                  0.77778596920447+0.19832484993429j])
+        for i, arr in enumerate(args):
+            assert_allclose(elliprc(*arr), expected_results[i])
+
+    def test_elliprd(self):
+        assert_allclose(elliprd(1, 1, 1), 1)
+        assert_allclose(elliprd(0, 2, 1) / 3.0, 0.59907011736779610371)
+        assert elliprd(1, 1, inf) == 0.0
+        assert np.isinf(elliprd(1, 1, 0))
+        assert np.isinf(elliprd(1, 1, complex(0, 0)))
+        assert np.isinf(elliprd(0, 1, complex(0, 0)))
+        assert isnan(elliprd(1, 1, -np.finfo(np.float64).tiny / 2.0))
+        assert isnan(elliprd(1, 1, complex(-1, 0)))
+        args = array([[0.0, 2.0, 1.0],
+                      [2.0, 3.0, 4.0],
+                      [1.0j, -1.0j, 2.0],
+                      [0.0, 1.0j, -1.0j],
+                      [0.0, -1.0+1.0j, 1.0j],
+                      [-2.0-1.0j, -1.0j, -1.0+1.0j]])
+        expected_results = array([1.7972103521034,
+                                  0.16510527294261,
+                                  0.65933854154220,
+                                  1.2708196271910+2.7811120159521j,
+                                  -1.8577235439239-0.96193450888839j,
+                                  1.8249027393704-1.2218475784827j])
+        for i, arr in enumerate(args):
+            assert_allclose(elliprd(*arr), expected_results[i])
+
+    def test_elliprf(self):
+        assert_allclose(elliprf(1, 1, 1), 1)
+        assert_allclose(elliprf(0, 1, 2), 1.31102877714605990523)
+        assert elliprf(1, inf, 1) == 0.0
+        assert np.isinf(elliprf(0, 1, 0))
+        assert isnan(elliprf(1, 1, -1))
+        assert elliprf(complex(inf), 0, 1) == 0.0
+        assert isnan(elliprf(1, 1, complex(-inf, 1)))
+        args = array([[1.0, 2.0, 0.0],
+                      [1.0j, -1.0j, 0.0],
+                      [0.5, 1.0, 0.0],
+                      [-1.0+1.0j, 1.0j, 0.0],
+                      [2.0, 3.0, 4.0],
+                      [1.0j, -1.0j, 2.0],
+                      [-1.0+1.0j, 1.0j, 1.0-1.0j]])
+        expected_results = array([1.3110287771461,
+                                  1.8540746773014,
+                                  1.8540746773014,
+                                  0.79612586584234-1.2138566698365j,
+                                  0.58408284167715,
+                                  1.0441445654064,
+                                  0.93912050218619-0.53296252018635j])
+        for i, arr in enumerate(args):
+            assert_allclose(elliprf(*arr), expected_results[i])
+
+    def test_elliprg(self):
+        assert_allclose(elliprg(1, 1, 1), 1)
+        assert_allclose(elliprg(0, 0, 1), 0.5)
+        assert_allclose(elliprg(0, 0, 0), 0)
+        assert np.isinf(elliprg(1, inf, 1))
+        assert np.isinf(elliprg(complex(inf), 1, 1))
+        args = array([[0.0, 16.0, 16.0],
+                      [2.0, 3.0, 4.0],
+                      [0.0, 1.0j, -1.0j],
+                      [-1.0+1.0j, 1.0j, 0.0],
+                      [-1.0j, -1.0+1.0j, 1.0j],
+                      [0.0, 0.0796, 4.0]])
+        expected_results = array([np.pi,
+                                  1.7255030280692,
+                                  0.42360654239699,
+                                  0.44660591677018+0.70768352357515j,
+                                  0.36023392184473+0.40348623401722j,
+                                  1.0284758090288])
+        for i, arr in enumerate(args):
+            assert_allclose(elliprg(*arr), expected_results[i])
+
+    def test_elliprj(self):
+        assert_allclose(elliprj(1, 1, 1, 1), 1)
+        assert elliprj(1, 1, inf, 1) == 0.0
+        assert isnan(elliprj(1, 0, 0, 0))
+        assert isnan(elliprj(-1, 1, 1, 1))
+        assert elliprj(1, 1, 1, inf) == 0.0
+        args = array([[0.0, 1.0, 2.0, 3.0],
+                      [2.0, 3.0, 4.0, 5.0],
+                      [2.0, 3.0, 4.0, -1.0+1.0j],
+                      [1.0j, -1.0j, 0.0, 2.0],
+                      [-1.0+1.0j, -1.0-1.0j, 1.0, 2.0],
+                      [1.0j, -1.0j, 0.0, 1.0-1.0j],
+                      [-1.0+1.0j, -1.0-1.0j, 1.0, -3.0+1.0j],
+                      [2.0, 3.0, 4.0, -0.5],    # Cauchy principal value
+                      [2.0, 3.0, 4.0, -5.0]])   # Cauchy principal value
+        expected_results = array([0.77688623778582,
+                                  0.14297579667157,
+                                  0.13613945827771-0.38207561624427j,
+                                  1.6490011662711,
+                                  0.94148358841220,
+                                  1.8260115229009+1.2290661908643j,
+                                  -0.61127970812028-1.0684038390007j,
+                                  0.24723819703052,    # Cauchy principal value
+                                  -0.12711230042964])  # Caucny principal value
+        for i, arr in enumerate(args):
+            assert_allclose(elliprj(*arr), expected_results[i])
+
+    @pytest.mark.xfail(reason="Insufficient accuracy on 32-bit")
+    def test_elliprj_hard(self):
+        assert_allclose(elliprj(6.483625725195452e-08,
+                                1.1649136528196886e-27,
+                                3.6767340167168e+13,
+                                0.493704617023468),
+                        8.63426920644241857617477551054e-6,
+                        rtol=5e-15, atol=1e-20)
+        assert_allclose(elliprj(14.375105857849121,
+                                9.993988969725365e-11,
+                                1.72844262269944e-26,
+                                5.898871222598245e-06),
+                        829774.1424801627252574054378691828,
+                        rtol=5e-15, atol=1e-20)
+
+
+class TestEllipLegendreCarlsonIdentities:
+    """Test identities expressing the Legendre elliptic integrals in terms
+    of Carlson's symmetric integrals.  These identities can be found
+    in the DLMF https://dlmf.nist.gov/19.25#i .
+    """
+
+    def setup_class(self):
+        self.m_n1_1 = np.arange(-1., 1., 0.01)
+        # For double, this is -(2**1024)
+        self.max_neg = finfo(double).min
+        # Lots of very negative numbers
+        self.very_neg_m = -1. * 2.**arange(-1 +
+                                           np.log2(-self.max_neg), 0.,
+                                           -1.)
+        self.ms_up_to_1 = np.concatenate(([self.max_neg],
+                                          self.very_neg_m,
+                                          self.m_n1_1))
+
+    def test_k(self):
+        """Test identity:
+        K(m) = R_F(0, 1-m, 1)
+        """
+        m = self.ms_up_to_1
+        assert_allclose(ellipk(m), elliprf(0., 1.-m, 1.))
+
+    def test_km1(self):
+        """Test identity:
+        K(m) = R_F(0, 1-m, 1)
+        But with the ellipkm1 function
+        """
+        # For double, this is 2**-1022
+        tiny = finfo(double).tiny
+        # All these small powers of 2, up to 2**-1
+        m1 = tiny * 2.**arange(0., -np.log2(tiny))
+        assert_allclose(ellipkm1(m1), elliprf(0., m1, 1.))
+
+    def test_e(self):
+        """Test identity:
+        E(m) = 2*R_G(0, 1-k^2, 1)
+        """
+        m = self.ms_up_to_1
+        assert_allclose(ellipe(m), 2.*elliprg(0., 1.-m, 1.))
+
+
+class TestErf:
+
+    def test_erf(self):
+        er = special.erf(.25)
+        assert_almost_equal(er,0.2763263902,8)
+
+    def test_erf_zeros(self):
+        erz = special.erf_zeros(5)
+        erzr = array([1.45061616+1.88094300j,
+                     2.24465928+2.61657514j,
+                     2.83974105+3.17562810j,
+                     3.33546074+3.64617438j,
+                     3.76900557+4.06069723j])
+        assert_array_almost_equal(erz,erzr,4)
+
+    def _check_variant_func(self, func, other_func, rtol, atol=0):
+        rng = np.random.RandomState(1234)
+        n = 10000
+        x = rng.pareto(0.02, n) * (2*rng.randint(0, 2, n) - 1)
+        y = rng.pareto(0.02, n) * (2*rng.randint(0, 2, n) - 1)
+        z = x + 1j*y
+
+        with np.errstate(all='ignore'):
+            w = other_func(z)
+            w_real = other_func(x).real
+
+            mask = np.isfinite(w)
+            w = w[mask]
+            z = z[mask]
+
+            mask = np.isfinite(w_real)
+            w_real = w_real[mask]
+            x = x[mask]
+
+            # test both real and complex variants
+            assert_func_equal(func, w, z, rtol=rtol, atol=atol)
+            assert_func_equal(func, w_real, x, rtol=rtol, atol=atol)
+
+    def test_erfc_consistent(self):
+        self._check_variant_func(
+            cephes.erfc,
+            lambda z: 1 - cephes.erf(z),
+            rtol=1e-12,
+            atol=1e-14  # <- the test function loses precision
+            )
+
+    def test_erfcx_consistent(self):
+        self._check_variant_func(
+            cephes.erfcx,
+            lambda z: np.exp(z*z) * cephes.erfc(z),
+            rtol=1e-12
+            )
+
+    def test_erfi_consistent(self):
+        self._check_variant_func(
+            cephes.erfi,
+            lambda z: -1j * cephes.erf(1j*z),
+            rtol=1e-12
+            )
+
+    def test_dawsn_consistent(self):
+        self._check_variant_func(
+            cephes.dawsn,
+            lambda z: sqrt(pi)/2 * np.exp(-z*z) * cephes.erfi(z),
+            rtol=1e-12
+            )
+
+    def test_erf_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, -1, 1]
+        assert_allclose(special.erf(vals), expected, rtol=1e-15)
+
+    def test_erfc_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, 2, 0]
+        assert_allclose(special.erfc(vals), expected, rtol=1e-15)
+
+    def test_erfcx_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, np.inf, 0]
+        assert_allclose(special.erfcx(vals), expected, rtol=1e-15)
+
+    def test_erfi_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, -np.inf, np.inf]
+        assert_allclose(special.erfi(vals), expected, rtol=1e-15)
+
+    def test_dawsn_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan, -0.0, 0.0]
+        assert_allclose(special.dawsn(vals), expected, rtol=1e-15)
+
+    def test_wofz_nan_inf(self):
+        vals = [np.nan, -np.inf, np.inf]
+        expected = [np.nan + np.nan * 1.j, 0.-0.j, 0.+0.j]
+        assert_allclose(special.wofz(vals), expected, rtol=1e-15)
+
+
+class TestEuler:
+    def test_euler(self):
+        eu0 = special.euler(0)
+        eu1 = special.euler(1)
+        eu2 = special.euler(2)   # just checking segfaults
+        assert_allclose(eu0, [1], rtol=1e-15)
+        assert_allclose(eu1, [1, 0], rtol=1e-15)
+        assert_allclose(eu2, [1, 0, -1], rtol=1e-15)
+        eu24 = special.euler(24)
+        mathworld = [1,1,5,61,1385,50521,2702765,199360981,
+                     19391512145,2404879675441,
+                     370371188237525,69348874393137901,
+                     15514534163557086905]
+        correct = zeros((25,),'d')
+        for k in range(0,13):
+            if (k % 2):
+                correct[2*k] = -float(mathworld[k])
+            else:
+                correct[2*k] = float(mathworld[k])
+        with np.errstate(all='ignore'):
+            err = nan_to_num((eu24-correct)/correct)
+            errmax = max(err)
+        assert_almost_equal(errmax, 0.0, 14)
+
+
+class TestExp:
+    def test_exp2(self):
+        ex = special.exp2(2)
+        exrl = 2**2
+        assert_equal(ex,exrl)
+
+    def test_exp2more(self):
+        exm = special.exp2(2.5)
+        exmrl = 2**(2.5)
+        assert_almost_equal(exm,exmrl,8)
+
+    def test_exp10(self):
+        ex = special.exp10(2)
+        exrl = 10**2
+        assert_approx_equal(ex,exrl)
+
+    def test_exp10more(self):
+        exm = special.exp10(2.5)
+        exmrl = 10**(2.5)
+        assert_almost_equal(exm,exmrl,8)
+
+    def test_expm1(self):
+        ex = (special.expm1(2),special.expm1(3),special.expm1(4))
+        exrl = (exp(2)-1,exp(3)-1,exp(4)-1)
+        assert_array_almost_equal(ex,exrl,8)
+
+    def test_expm1more(self):
+        ex1 = (special.expm1(2),special.expm1(2.1),special.expm1(2.2))
+        exrl1 = (exp(2)-1,exp(2.1)-1,exp(2.2)-1)
+        assert_array_almost_equal(ex1,exrl1,8)
+
+
+def assert_really_equal(x, y, rtol=None):
+    """
+    Sharper assertion function that is stricter about matching types, not just values
+
+    This is useful/necessary in some cases:
+      * dtypes for arrays that have the same _values_ (e.g. element 1.0 vs 1)
+      * distinguishing complex from real NaN
+      * result types for scalars
+
+    We still want to be able to allow a relative tolerance for the values though.
+    The main logic comparison logic is handled by the xp_assert_* functions.
+    """
+    def assert_func(x, y):
+        xp_assert_equal(x, y) if rtol is None else xp_assert_close(x, y, rtol=rtol)
+
+    def assert_complex_nan(x):
+        assert np.isnan(x.real) and np.isnan(x.imag)
+
+    assert type(x) is type(y), f"types not equal: {type(x)}, {type(y)}"
+
+    # ensure we also compare the values _within_ an array appropriately,
+    # e.g. assert_equal does not distinguish different complex nans in arrays
+    if isinstance(x, np.ndarray):
+        # assert_equal does not compare (all) types, only values
+        assert x.dtype == y.dtype
+        # for empty arrays resp. to ensure shapes match
+        assert_func(x, y)
+        for elem_x, elem_y in zip(x.ravel(), y.ravel()):
+            assert_really_equal(elem_x, elem_y, rtol=rtol)
+    elif np.isnan(x) and np.isnan(y) and _is_subdtype(type(x), "c"):
+        assert_complex_nan(x) and assert_complex_nan(y)
+    # no need to consider complex infinities due to numpy/numpy#25493
+    else:
+        assert_func(x, y)
+
+
+class TestFactorialFunctions:
+    def factorialk_ref(self, n, k, exact, extend):
+        if exact:
+            return special.factorialk(n, k=k, exact=True)
+        # for details / explanation see factorialk-docstring
+        r = np.mod(n, k) if extend == "zero" else 1
+        vals = np.power(k, (n - r)/k) * special.gamma(n/k + 1) * special.rgamma(r/k + 1)
+        # np.maximum is element-wise, which is what we want
+        return vals * np.maximum(r, 1)
+
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    def test_factorialx_scalar_return_type(self, exact, extend):
+        kw = {"exact": exact, "extend": extend}
+        assert np.isscalar(special.factorial(1, **kw))
+        assert np.isscalar(special.factorial2(1, **kw))
+        assert np.isscalar(special.factorialk(1, k=3, **kw))
+
+    @pytest.mark.parametrize("n", [-1, -2, -3])
+    @pytest.mark.parametrize("exact", [True, False])
+    def test_factorialx_negative_extend_zero(self, exact, n):
+        kw = {"exact": exact}
+        assert_equal(special.factorial(n, **kw), 0)
+        assert_equal(special.factorial2(n, **kw), 0)
+        assert_equal(special.factorialk(n, k=3, **kw), 0)
+
+    @pytest.mark.parametrize("exact", [True, False])
+    def test_factorialx_negative_extend_zero_array(self, exact):
+        kw = {"exact": exact}
+        rtol = 1e-15
+        n = [-5, -4, 0, 1]
+        # Consistent output for n < 0
+        expected = np.array([0, 0, 1, 1], dtype=native_int if exact else np.float64)
+        assert_really_equal(special.factorial(n, **kw), expected, rtol=rtol)
+        assert_really_equal(special.factorial2(n, **kw), expected, rtol=rtol)
+        assert_really_equal(special.factorialk(n, k=3, **kw), expected, rtol=rtol)
+
+    @pytest.mark.parametrize("n", [-1.1, -2.2, -3.3])
+    def test_factorialx_negative_extend_complex(self, n):
+        kw = {"extend": "complex"}
+        exp_1 = {-1.1: -10.686287021193184771,
+                 -2.2:   4.8509571405220931958,
+                 -3.3:  -1.4471073942559181166}
+        exp_2 = {-1.1:  1.0725776858167496309,
+                 -2.2: -3.9777171783768419874,
+                 -3.3: -0.99588841846200555977}
+        exp_k = {-1.1:  0.73565345382163025659,
+                 -2.2:  1.1749163167190809498,
+                 -3.3: -2.4780584257450583713}
+        rtol = 3e-15
+        assert_allclose(special.factorial(n, **kw), exp_1[n], rtol=rtol)
+        assert_allclose(special.factorial2(n, **kw), exp_2[n], rtol=rtol)
+        assert_allclose(special.factorialk(n, k=3, **kw), exp_k[n], rtol=rtol)
+        assert_allclose(special.factorial([n], **kw)[0], exp_1[n], rtol=rtol)
+        assert_allclose(special.factorial2([n], **kw)[0], exp_2[n], rtol=rtol)
+        assert_allclose(special.factorialk([n], k=3, **kw)[0], exp_k[n], rtol=rtol)
+
+    @pytest.mark.parametrize("imag", [0, 0j])
+    @pytest.mark.parametrize("n_outer", [-1, -2, -3])
+    def test_factorialx_negative_extend_complex_poles(self, n_outer, imag):
+        kw = {"extend": "complex"}
+        def _check(n):
+            complexify = _is_subdtype(type(n), "c")
+            # like for gamma, we expect complex nans for complex inputs
+            complex_nan = np.complex128("nan+nanj")
+            exp = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            # poles are at negative integers that are multiples of k
+            assert_really_equal(special.factorial(n, **kw), exp)
+            assert_really_equal(special.factorial2(n * 2, **kw), exp)
+            assert_really_equal(special.factorialk(n * 3, k=3, **kw), exp)
+            # also test complex k for factorialk
+            c = 1.5 - 2j
+            assert_really_equal(special.factorialk(n * c, k=c, **kw), complex_nan)
+            # same for array case
+            assert_really_equal(special.factorial([n], **kw)[0], exp)
+            assert_really_equal(special.factorial2([n * 2], **kw)[0], exp)
+            assert_really_equal(special.factorialk([n * 3], k=3, **kw)[0], exp)
+            assert_really_equal(special.factorialk([n * c], k=c, **kw)[0], complex_nan)
+            # more specific tests in test_factorial{,2,k}_complex_reference
+
+        # imag ensures we test both real and complex representations of the poles
+        _check(n_outer + imag)
+        # check for large multiple of period
+        _check(100_000 * n_outer + imag)
+
+    @pytest.mark.parametrize("boxed", [True, False])
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize(
+        "n",
+        [
+            np.nan, np.float64("nan"), np.nan + np.nan*1j, np.complex128("nan+nanj"),
+            np.inf, np.inf + 0j, -np.inf, -np.inf + 0j, None, np.datetime64("nat")
+        ],
+        ids=[
+            "NaN", "np.float64('nan')", "NaN+i*NaN", "np.complex128('nan+nanj')",
+            "inf", "inf+0i", "-inf", "-inf+0i", "None", "NaT"
+        ]
+    )
+    @pytest.mark.parametrize(
+        "factorialx",
+        [special.factorial, special.factorial2, special.factorialk]
+    )
+    def test_factorialx_inf_nan(self, factorialx, n, extend, boxed):
+        # NaNs not allowed (by dtype) for exact=True
+        kw = {"exact": False, "extend": extend}
+        if factorialx == special.factorialk:
+            kw["k"] = 3
+
+        # None is allowed for scalars, but would cause object type in array case
+        permissible_types = ["i", "f", "c"] if boxed else ["i", "f", "c", type(None)]
+        # factorial allows floats also for extend="zero"
+        types_need_complex_ext = "c" if factorialx == special.factorial else ["f", "c"]
+
+        if not _is_subdtype(type(n), permissible_types):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                factorialx([n] if boxed else n, **kw)
+        elif _is_subdtype(type(n), types_need_complex_ext) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                factorialx([n] if boxed else n, **kw)
+        else:
+            # account for type and whether extend="complex"
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            # note that the type of the naïve `np.nan + np.nan * 1j` is `complex`
+            # instead of `numpy.complex128`, which trips up assert_really_equal
+            expected = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            # the only exception are real infinities
+            if _is_subdtype(type(n), "f") and np.isinf(n):
+                # unchanged for positive infinity; negative one depends on extension
+                neg_inf_result = np.float64(0 if (extend == "zero") else "nan")
+                expected = np.float64("inf") if (n > 0) else neg_inf_result
+
+            result = factorialx([n], **kw)[0] if boxed else factorialx(n, **kw)
+            assert_really_equal(result, expected)
+            # also tested in test_factorial{,2,k}_{array,scalar}_corner_cases
+
+    @pytest.mark.parametrize("extend", [0, 1.1, np.nan, "string"])
+    def test_factorialx_raises_extend(self, extend):
+        with pytest.raises(ValueError, match="argument `extend` must be.*"):
+            special.factorial(1, extend=extend)
+        with pytest.raises(ValueError, match="argument `extend` must be.*"):
+            special.factorial2(1, extend=extend)
+        with pytest.raises(ValueError, match="argument `extend` must be.*"):
+            special.factorialk(1, k=3, exact=True, extend=extend)
+
+    @pytest.mark.parametrize("levels", range(1, 5))
+    @pytest.mark.parametrize("exact", [True, False])
+    def test_factorialx_array_shape(self, levels, exact):
+        def _nest_me(x, k=1):
+            """
+            Double x and nest it k times
+
+            For example:
+            >>> _nest_me([3, 4], 2)
+            [[[3, 4], [3, 4]], [[3, 4], [3, 4]]]
+            """
+            if k == 0:
+                return x
+            else:
+                return _nest_me([x, x], k-1)
+
+        def _check(res, nucleus):
+            exp = np.array(_nest_me(nucleus, k=levels), dtype=object)
+            # test that ndarray shape is maintained
+            # need to cast to float due to numpy/numpy#21220
+            assert_allclose(res.astype(np.float64), exp.astype(np.float64))
+
+        n = np.array(_nest_me([5, 25], k=levels))
+        exp_nucleus = {1: [120, math.factorial(25)],
+                       # correctness of factorial{2,k}() is tested elsewhere
+                       2: [15, special.factorial2(25, exact=True)],
+                       3: [10, special.factorialk(25, 3, exact=True)]}
+
+        _check(special.factorial(n, exact=exact), exp_nucleus[1])
+        _check(special.factorial2(n, exact=exact), exp_nucleus[2])
+        _check(special.factorialk(n, 3, exact=exact), exp_nucleus[3])
+
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("dtype", [
+        None, int, np.int8, np.int16, np.int32, np.int64,
+        np.uint8, np.uint16, np.uint32, np.uint64
+    ])
+    @pytest.mark.parametrize("dim", range(0, 5))
+    def test_factorialx_array_dimension(self, dim, dtype, exact):
+        n = np.array(5, dtype=dtype, ndmin=dim)
+        exp = {1: 120, 2: 15, 3: 10}
+        assert_allclose(special.factorial(n, exact=exact),
+                        np.array(exp[1], ndmin=dim))
+        assert_allclose(special.factorial2(n, exact=exact),
+                        np.array(exp[2], ndmin=dim))
+        assert_allclose(special.factorialk(n, 3, exact=exact),
+                        np.array(exp[3], ndmin=dim))
+
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("level", range(1, 5))
+    def test_factorialx_array_like(self, level, exact):
+        def _nest_me(x, k=1):
+            if k == 0:
+                return x
+            else:
+                return _nest_me([x], k-1)
+
+        n = _nest_me([5], k=level-1)  # nested list
+        exp_nucleus = {1: 120, 2: 15, 3: 10}
+        assert_func = assert_array_equal if exact else assert_allclose
+        assert_func(special.factorial(n, exact=exact),
+                    np.array(exp_nucleus[1], ndmin=level))
+        assert_func(special.factorial2(n, exact=exact),
+                    np.array(exp_nucleus[2], ndmin=level))
+        assert_func(special.factorialk(n, 3, exact=exact),
+                    np.array(exp_nucleus[3], ndmin=level))
+
+    @pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.uint32, np.uint64])
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    def test_factorialx_uint(self, exact, extend, dtype):
+        # ensure that uint types work correctly as inputs
+        kw = {"exact": exact, "extend": extend}
+        assert_func = assert_array_equal if exact else assert_allclose
+        def _check(n):
+            n_ref = n.astype(np.int64) if isinstance(n, np.ndarray) else np.int64(n)
+            assert_func(special.factorial(n, **kw), special.factorial(n_ref, **kw))
+            assert_func(special.factorial2(n, **kw), special.factorial2(n_ref, **kw))
+            assert_func(special.factorialk(n, k=3, **kw),
+                        special.factorialk(n_ref, k=3, **kw))
+        _check(dtype(0))
+        _check(dtype(1))
+        _check(np.array(0, dtype=dtype))
+        _check(np.array([0, 1], dtype=dtype))
+
+    # note that n=170 is the last integer such that factorial(n) fits float64
+    @pytest.mark.parametrize('n', range(30, 180, 10))
+    def test_factorial_accuracy(self, n):
+        # Compare exact=True vs False, i.e. that the accuracy of the
+        # approximation is better than the specified tolerance.
+
+        rtol = 6e-14 if sys.platform == 'win32' else 1e-15
+        # need to cast exact result to float due to numpy/numpy#21220
+        assert_allclose(float(special.factorial(n, exact=True)),
+                        special.factorial(n, exact=False), rtol=rtol)
+        assert_allclose(special.factorial([n], exact=True).astype(float),
+                        special.factorial([n], exact=False), rtol=rtol)
+
+    @pytest.mark.parametrize('n',
+                             list(range(0, 22)) + list(range(30, 180, 10)))
+    def test_factorial_int_reference(self, n):
+        # Compare all with math.factorial
+        correct = math.factorial(n)
+        assert_array_equal(correct, special.factorial(n, exact=True))
+        assert_array_equal(correct, special.factorial([n], exact=True)[0])
+
+        rtol = 8e-14 if sys.platform == 'win32' else 1e-15
+        # need to cast exact result to float due to numpy/numpy#21220
+        correct = float(correct)
+        assert_allclose(correct, special.factorial(n, exact=False), rtol=rtol)
+        assert_allclose(correct, special.factorial([n], exact=False)[0], rtol=rtol)
+
+        # extend="complex" only works for exact=False
+        kw = {"exact": False, "extend": "complex"}
+        assert_allclose(correct, special.factorial(n, **kw), rtol=rtol)
+        assert_allclose(correct, special.factorial([n], **kw)[0], rtol=rtol)
+
+    def test_factorial_float_reference(self):
+        def _check(n, expected):
+            rtol = 8e-14 if sys.platform == 'win32' else 1e-15
+            assert_allclose(special.factorial(n), expected, rtol=rtol)
+            assert_allclose(special.factorial([n])[0], expected, rtol=rtol)
+            # using floats with `exact=True` raises an error for scalars and arrays
+            with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+                special.factorial(n, exact=True)
+            with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+                special.factorial([n], exact=True)
+
+        # Reference values from mpmath for gamma(n+1)
+        _check(0.01, 0.994325851191506032181932988)
+        _check(1.11, 1.051609009483625091514147465)
+        _check(5.55, 314.9503192327208241614959052)
+        _check(11.1, 50983227.84411615655137170553)
+        _check(33.3, 2.493363339642036352229215273e+37)
+        _check(55.5, 9.479934358436729043289162027e+73)
+        _check(77.7, 3.060540559059579022358692625e+114)
+        _check(99.9, 5.885840419492871504575693337e+157)
+        # close to maximum for float64
+        _check(170.6243, 1.79698185749571048960082e+308)
+
+    def test_factorial_complex_reference(self):
+        def _check(n, expected):
+            rtol = 3e-15 if sys.platform == 'win32' else 2e-15
+            kw = {"exact": False, "extend": "complex"}
+            assert_allclose(special.factorial(n, **kw), expected, rtol=rtol)
+            assert_allclose(special.factorial([n], **kw)[0], expected, rtol=rtol)
+
+        # Reference values from mpmath.gamma(n+1)
+        # negative & complex values
+        _check(-0.5, expected=1.7724538509055160276)
+        _check(-0.5 + 0j, expected=1.7724538509055160276 + 0j)
+        _check(2 + 2j, expected=-0.42263728631120216694 + 0.87181425569650686062j)
+        # close to poles
+        _check(-0.9999, expected=9999.422883232725532)
+        _check(-1 + 0.0001j, expected=-0.57721565582674219 - 9999.9999010944009697j)
+
+    @pytest.mark.parametrize("dtype", [np.int64, np.float64,
+                                       np.complex128, object])
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("dim", range(0, 5))
+    # test empty & non-empty arrays, with nans and mixed
+    @pytest.mark.parametrize(
+        "content",
+        [[], [1], [1.1], [np.nan], [np.nan + np.nan * 1j], [np.nan, 1]],
+        ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN+i*NaN]", "[NaN, 1]"],
+    )
+    def test_factorial_array_corner_cases(self, content, dim, exact, extend, dtype):
+        if dtype is object and SCIPY_ARRAY_API:
+            pytest.skip("object arrays unsupported in array API mode")
+        # get dtype without calling array constructor (that might fail or mutate)
+        if dtype is np.int64 and any(np.isnan(x) or (x != int(x)) for x in content):
+            pytest.skip("impossible combination")
+        if dtype == np.float64 and any(_is_subdtype(type(x), "c") for x in content):
+            pytest.skip("impossible combination")
+
+        kw = {"exact": exact, "extend": extend}
+        # np.array(x, ndim=0) will not be 0-dim. unless x is too
+        content = content if (dim > 0 or len(content) != 1) else content[0]
+        n = np.array(content, ndmin=dim, dtype=dtype)
+
+        result = None
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorial(n, **kw)
+        elif not _is_subdtype(n.dtype, ["i", "f", "c"]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorial(n, **kw)
+        elif _is_subdtype(n.dtype, "c") and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorial(n, **kw)
+        elif exact and not _is_subdtype(n.dtype, "i"):
+            with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+                special.factorial(n, **kw)
+        else:
+            result = special.factorial(n, **kw)
+
+        if result is not None:
+            # use scalar case as reference; tested separately in *_scalar_corner_cases
+            ref = [special.factorial(x, **kw) for x in n.ravel()]
+            # unpack length-1 lists so that np.array(x, ndim=0) works correctly
+            ref = ref[0] if len(ref) == 1 else ref
+            # result is empty if and only if n is empty, and has the same dimension
+            # as n; dtype stays the same, except when not empty and not exact:
+            if n.size:
+                cx = (extend == "complex") and _is_subdtype(n.dtype, "c")
+                dtype = np.complex128 if cx else (native_int if exact else np.float64)
+            expected = np.array(ref, ndmin=dim, dtype=dtype)
+            assert_really_equal(result, expected, rtol=1e-15)
+
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, np.nan + np.nan*1j, None],
+                             ids=["1", "1.1", "2+2j", "NaN", "NaN+i*NaN", "None"])
+    def test_factorial_scalar_corner_cases(self, n, exact, extend):
+        kw = {"exact": exact, "extend": extend}
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorial(n, **kw)
+        elif not _is_subdtype(type(n), ["i", "f", "c", type(None)]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorial(n, **kw)
+        elif _is_subdtype(type(n), "c") and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorial(n, **kw)
+        elif n is None or np.isnan(n):
+            # account for dtype and whether extend="complex"
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            expected = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            assert_really_equal(special.factorial(n, **kw), expected)
+        elif exact and _is_subdtype(type(n), "f"):
+            with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+                special.factorial(n, **kw)
+        else:
+            assert_equal(special.factorial(n, **kw), special.gamma(n + 1))
+
+    # use odd increment to make sure both odd & even numbers are tested!
+    @pytest.mark.parametrize('n', range(30, 180, 11))
+    def test_factorial2_accuracy(self, n):
+        # Compare exact=True vs False, i.e. that the accuracy of the
+        # approximation is better than the specified tolerance.
+
+        rtol = 2e-14 if sys.platform == 'win32' else 1e-15
+        # need to cast exact result to float due to numpy/numpy#21220
+        assert_allclose(float(special.factorial2(n, exact=True)),
+                        special.factorial2(n, exact=False), rtol=rtol)
+        assert_allclose(special.factorial2([n], exact=True).astype(float),
+                        special.factorial2([n], exact=False), rtol=rtol)
+
+    @pytest.mark.parametrize('n',
+                             list(range(0, 22)) + list(range(30, 180, 11)))
+    def test_factorial2_int_reference(self, n):
+        # Compare all with correct value
+
+        # Cannot use np.product due to overflow
+        correct = functools.reduce(operator.mul, list(range(n, 0, -2)), 1)
+
+        assert_array_equal(correct, special.factorial2(n, exact=True))
+        assert_array_equal(correct, special.factorial2([n], exact=True)[0])
+
+        rtol = 2e-14 if sys.platform == 'win32' else 1e-15
+        # need to cast exact result to float due to numpy/numpy#21220
+        correct = float(correct)
+        assert_allclose(correct, special.factorial2(n, exact=False), rtol=rtol)
+        assert_allclose(correct, special.factorial2([n], exact=False)[0], rtol=rtol)
+
+        # extend="complex" only works for exact=False
+        kw = {"exact": False, "extend": "complex"}
+        # approximation only matches exactly for `n == 1 (mod k)`, see docstring
+        if n % 2 == 1:
+            assert_allclose(correct, special.factorial2(n, **kw), rtol=rtol)
+            assert_allclose(correct, special.factorial2([n], **kw)[0], rtol=rtol)
+
+    def test_factorial2_complex_reference(self):
+        # this tests for both floats and complex
+        def _check(n, expected):
+            rtol = 5e-15
+            kw = {"exact": False, "extend": "complex"}
+            assert_allclose(special.factorial2(n, **kw), expected, rtol=rtol)
+            assert_allclose(special.factorial2([n], **kw)[0], expected, rtol=rtol)
+
+        # Reference values from mpmath for:
+        # mpmath.power(2, n/2) * mpmath.gamma(n/2 + 1) * mpmath.sqrt(2 / mpmath.pi)
+        _check(3, expected=3)
+        _check(4, expected=special.factorial2(4) * math.sqrt(2 / math.pi))
+        _check(20, expected=special.factorial2(20) * math.sqrt(2 / math.pi))
+        # negative & complex values
+        _check(-0.5, expected=0.82217895866245855122)
+        _check(-0.5 + 0j, expected=0.82217895866245855122 + 0j)
+        _check(3 + 3j, expected=-1.0742236630142471526 + 1.4421398439387262897j)
+        # close to poles
+        _check(-1.9999, expected=7978.8918745523440682)
+        _check(-2 + 0.0001j, expected=0.0462499835314308444 - 7978.84559148876374493j)
+
+    @pytest.mark.parametrize("dtype", [np.int64, np.float64,
+                                       np.complex128, object])
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("dim", range(0, 5))
+    # test empty & non-empty arrays, with nans and mixed
+    @pytest.mark.parametrize(
+        "content",
+        [[], [1], [1.1], [np.nan], [np.nan + np.nan * 1j], [np.nan, 1]],
+        ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN+i*NaN]", "[NaN, 1]"],
+    )
+    def test_factorial2_array_corner_cases(self, content, dim, exact, extend, dtype):
+        # get dtype without calling array constructor (that might fail or mutate)
+        if dtype == np.int64 and any(np.isnan(x) or (x != int(x)) for x in content):
+            pytest.skip("impossible combination")
+        if dtype == np.float64 and any(_is_subdtype(type(x), "c") for x in content):
+            pytest.skip("impossible combination")
+
+        kw = {"exact": exact, "extend": extend}
+        # np.array(x, ndim=0) will not be 0-dim. unless x is too
+        content = content if (dim > 0 or len(content) != 1) else content[0]
+        n = np.array(content, ndmin=dim, dtype=dtype)
+
+        result = None
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorial2(n, **kw)
+        elif not _is_subdtype(n.dtype, ["i", "f", "c"]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorial2(n, **kw)
+        elif _is_subdtype(n.dtype, ["f", "c"]) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorial2(n, **kw)
+        else:
+            result = special.factorial2(n, **kw)
+
+        if result is not None:
+            # use scalar case as reference; tested separately in *_scalar_corner_cases
+            ref = [special.factorial2(x, **kw) for x in n.ravel()]
+            # unpack length-1 lists so that np.array(x, ndim=0) works correctly
+            ref = ref[0] if len(ref) == 1 else ref
+            # result is empty if and only if n is empty, and has the same dimension
+            # as n; dtype stays the same, except when not empty and not exact:
+            if n.size:
+                cx = (extend == "complex") and _is_subdtype(n.dtype, "c")
+                dtype = np.complex128 if cx else (native_int if exact else np.float64)
+            expected = np.array(ref, ndmin=dim, dtype=dtype)
+            assert_really_equal(result, expected, rtol=2e-15)
+
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, np.nan + np.nan*1j, None],
+                             ids=["1", "1.1", "2+2j", "NaN", "NaN+i*NaN", "None"])
+    def test_factorial2_scalar_corner_cases(self, n, exact, extend):
+        kw = {"exact": exact, "extend": extend}
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorial2(n, **kw)
+        elif not _is_subdtype(type(n), ["i", "f", "c", type(None)]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorial2(n, **kw)
+        elif _is_subdtype(type(n), ["f", "c"]) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorial2(n, **kw)
+        elif n is None or np.isnan(n):
+            # account for dtype and whether extend="complex"
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            expected = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            assert_really_equal(special.factorial2(n, **kw), expected)
+        else:
+            expected = self.factorialk_ref(n, k=2, **kw)
+            assert_really_equal(special.factorial2(n, **kw), expected, rtol=1e-15)
+
+    @pytest.mark.parametrize("k", range(1, 5))
+    # note that n=170 is the last integer such that factorial(n) fits float64;
+    # use odd increment to make sure both odd & even numbers are tested
+    @pytest.mark.parametrize('n', range(170, 20, -29))
+    def test_factorialk_accuracy(self, n, k):
+        # Compare exact=True vs False, i.e. that the accuracy of the
+        # approximation is better than the specified tolerance.
+
+        rtol = 6e-14 if sys.platform == 'win32' else 2e-14
+        # need to cast exact result to float due to numpy/numpy#21220
+        assert_allclose(float(special.factorialk(n, k=k, exact=True)),
+                        special.factorialk(n, k=k, exact=False), rtol=rtol)
+        assert_allclose(special.factorialk([n], k=k, exact=True).astype(float),
+                        special.factorialk([n], k=k, exact=False), rtol=rtol)
+
+    @pytest.mark.parametrize('k', list(range(1, 5)) + [10, 20])
+    @pytest.mark.parametrize('n',
+                             list(range(0, 22)) + list(range(22, 100, 11)))
+    def test_factorialk_int_reference(self, n, k):
+        # Compare all with correct value
+
+        # Would be nice to use np.product here, but that's
+        # broken on windows, see numpy/numpy#21219
+        correct = functools.reduce(operator.mul, list(range(n, 0, -k)), 1)
+
+        assert_array_equal(correct, special.factorialk(n, k, exact=True))
+        assert_array_equal(correct, special.factorialk([n], k, exact=True)[0])
+
+        rtol = 3e-14 if sys.platform == 'win32' else 1e-14
+        # need to cast exact result to float due to numpy/numpy#21220
+        correct = float(correct)
+        assert_allclose(correct, special.factorialk(n, k, exact=False), rtol=rtol)
+        assert_allclose(correct, special.factorialk([n], k, exact=False)[0], rtol=rtol)
+
+        # extend="complex" only works for exact=False
+        kw = {"k": k, "exact": False, "extend": "complex"}
+        # approximation only matches exactly for `n == 1 (mod k)`, see docstring
+        if n % k == 1:
+            rtol = 2e-14
+            assert_allclose(correct, special.factorialk(n, **kw), rtol=rtol)
+            assert_allclose(correct, special.factorialk([n], **kw)[0], rtol=rtol)
+
+    def test_factorialk_complex_reference(self):
+        # this tests for both floats and complex
+        def _check(n, k, exp):
+            rtol = 1e-14
+            kw = {"k": k, "exact": False, "extend": "complex"}
+            assert_allclose(special.factorialk(n, **kw), exp, rtol=rtol)
+            assert_allclose(special.factorialk([n], **kw)[0], exp, rtol=rtol)
+
+        # Reference values from mpmath for:
+        # mpmath.power(k, (n-1)/k) * mpmath.gamma(n/k + 1) / mpmath.gamma(1/k + 1)
+        _check(n=4, k=3, exp=special.factorialk(4, k=3, exact=True))
+        _check(n=5, k=3, exp=7.29011132947227083)
+        _check(n=6.5, k=3, exp=19.6805080113566010)
+        # non-integer k
+        _check(n=3, k=2.5, exp=2.58465740293218541)
+        _check(n=11, k=2.5, exp=1963.5)  # ==11*8.5*6*3.5; c.f. n == 1 (mod k)
+        _check(n=-3 + 3j + 1, k=-3 + 3j, exp=-2 + 3j)
+        # complex values
+        _check(n=4 + 4j, k=4, exp=-0.67855904082768043854 + 2.1993925819930311497j)
+        _check(n=4, k=4 - 4j, exp=1.9775338957222718742 + 0.92607172675423901371j)
+        _check(n=4 + 4j, k=4 - 4j, exp=0.1868492880824934475 + 0.87660580316894290247j)
+        # negative values
+        _check(n=-0.5, k=3, exp=0.72981013240713739354)
+        _check(n=-0.5 + 0j, k=3, exp=0.72981013240713739354 + 0j)
+        _check(n=2.9, k=-0.7, exp=0.45396591474966867296 + 0.56925525174685228866j)
+        _check(n=-0.6, k=-0.7, exp=-0.07190820089634757334 - 0.090170031876701730081j)
+        # close to poles
+        _check(n=-2.9999, k=3, exp=7764.7170695908828364)
+        _check(n=-3 + 0.0001j, k=3, exp=0.1349475632879599864 - 7764.5821055158365027j)
+
+    @pytest.mark.parametrize("dtype", [np.int64, np.float64,
+                                       np.complex128, object])
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("dim", range(0, 5))
+    # test empty & non-empty arrays, with nans and mixed
+    @pytest.mark.parametrize(
+        "content",
+        [[], [1], [1.1], [np.nan], [np.nan + np.nan * 1j], [np.nan, 1]],
+        ids=["[]", "[1]", "[1.1]", "[NaN]", "[NaN+i*NaN]", "[NaN, 1]"],
+    )
+    def test_factorialk_array_corner_cases(self, content, dim, exact, extend, dtype):
+        # get dtype without calling array constructor (that might fail or mutate)
+        if dtype == np.int64 and any(np.isnan(x) or (x != int(x)) for x in content):
+            pytest.skip("impossible combination")
+        if dtype == np.float64 and any(_is_subdtype(type(x), "c") for x in content):
+            pytest.skip("impossible combination")
+
+        kw = {"k": 3, "exact": exact, "extend": extend}
+        # np.array(x, ndim=0) will not be 0-dim. unless x is too
+        content = content if (dim > 0 or len(content) != 1) else content[0]
+        n = np.array(content, ndmin=dim, dtype=dtype)
+
+        result = None
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorialk(n, **kw)
+        elif not _is_subdtype(n.dtype, ["i", "f", "c"]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorialk(n, **kw)
+        elif _is_subdtype(n.dtype, ["f", "c"]) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorialk(n, **kw)
+        else:
+            result = special.factorialk(n, **kw)
+
+        if result is not None:
+            # use scalar case as reference; tested separately in *_scalar_corner_cases
+            ref = [special.factorialk(x, **kw) for x in n.ravel()]
+            # unpack length-1 lists so that np.array(x, ndim=0) works correctly
+            ref = ref[0] if len(ref) == 1 else ref
+            # result is empty if and only if n is empty, and has the same dimension
+            # as n; dtype stays the same, except when not empty and not exact:
+            if n.size:
+                cx = (extend == "complex") and _is_subdtype(n.dtype, "c")
+                dtype = np.complex128 if cx else (native_int if exact else np.float64)
+            expected = np.array(ref, ndmin=dim, dtype=dtype)
+            assert_really_equal(result, expected, rtol=2e-15)
+
+    @pytest.mark.parametrize("extend", ["zero", "complex"])
+    @pytest.mark.parametrize("exact", [True, False])
+    @pytest.mark.parametrize("k", range(1, 5))
+    @pytest.mark.parametrize("n", [1, 1.1, 2 + 2j, np.nan, np.nan + np.nan*1j, None],
+                             ids=["1", "1.1", "2+2j", "NaN", "NaN+i*NaN", "None"])
+    def test_factorialk_scalar_corner_cases(self, n, k, exact, extend):
+        kw = {"k": k, "exact": exact, "extend": extend}
+        if extend == "complex" and exact:
+            with pytest.raises(ValueError, match="Incompatible options:.*"):
+                special.factorialk(n, **kw)
+        elif not _is_subdtype(type(n), ["i", "f", "c", type(None)]):
+            with pytest.raises(ValueError, match="Unsupported data type.*"):
+                special.factorialk(n, **kw)
+        elif _is_subdtype(type(n), ["f", "c"]) and extend != "complex":
+            with pytest.raises(ValueError, match="In order to use non-integer.*"):
+                special.factorialk(n, **kw)
+        elif n is None or np.isnan(n):
+            # account for dtype and whether extend="complex"
+            complexify = (extend == "complex") and _is_subdtype(type(n), "c")
+            expected = np.complex128("nan+nanj") if complexify else np.float64("nan")
+            assert_really_equal(special.factorialk(n, **kw), expected)
+        else:
+            expected = self.factorialk_ref(n, **kw)
+            assert_really_equal(special.factorialk(n, **kw), expected, rtol=1e-15)
+
+    @pytest.mark.parametrize("boxed", [True, False])
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    @pytest.mark.parametrize("k", [-1, -1.0, 0, 0.0, 0 + 1j, 1.1, np.nan])
+    def test_factorialk_raises_k_complex(self, k, exact, extend, boxed):
+        n = [1] if boxed else 1
+        kw = {"k": k, "exact": exact, "extend": extend}
+        if extend == "zero":
+            msg = "In order to use non-integer.*"
+            if _is_subdtype(type(k), "i") and (k < 1):
+                msg = "For `extend='zero'`.*"
+            with pytest.raises(ValueError, match=msg):
+                special.factorialk(n, **kw)
+        elif k == 0:
+            with pytest.raises(ValueError, match="Parameter k cannot be zero!"):
+                special.factorialk(n, **kw)
+        else:
+            # no error
+            special.factorialk(n, **kw)
+
+    @pytest.mark.parametrize("boxed", [True, False])
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    # neither integer, float nor complex
+    @pytest.mark.parametrize("k", ["string", np.datetime64("nat")],
+                             ids=["string", "NaT"])
+    def test_factorialk_raises_k_other(self, k, exact, extend, boxed):
+        n = [1] if boxed else 1
+        kw = {"k": k, "exact": exact, "extend": extend}
+        with pytest.raises(ValueError, match="Unsupported data type.*"):
+            special.factorialk(n, **kw)
+
+    @pytest.mark.parametrize("exact,extend",
+                             [(True, "zero"), (False, "zero"), (False, "complex")])
+    @pytest.mark.parametrize("k", range(1, 12))
+    def test_factorialk_dtype(self, k, exact, extend):
+        kw = {"k": k, "exact": exact, "extend": extend}
+        if exact and k in _FACTORIALK_LIMITS_64BITS.keys():
+            n = np.array([_FACTORIALK_LIMITS_32BITS[k]])
+            assert_equal(special.factorialk(n, **kw).dtype, np_long)
+            assert_equal(special.factorialk(n + 1, **kw).dtype, np.int64)
+            # assert maximality of limits for given dtype
+            assert special.factorialk(n + 1, **kw) > np.iinfo(np.int32).max
+
+            n = np.array([_FACTORIALK_LIMITS_64BITS[k]])
+            assert_equal(special.factorialk(n, **kw).dtype, np.int64)
+            assert_equal(special.factorialk(n + 1, **kw).dtype, object)
+            assert special.factorialk(n + 1, **kw) > np.iinfo(np.int64).max
+        else:
+            n = np.array([_FACTORIALK_LIMITS_64BITS.get(k, 1)])
+            # for exact=True and k >= 10, we always return object;
+            # for exact=False it's always float (unless input is complex)
+            dtype = object if exact else np.float64
+            assert_equal(special.factorialk(n, **kw).dtype, dtype)
+
+    def test_factorial_mixed_nan_inputs(self):
+        x = np.array([np.nan, 1, 2, 3, np.nan])
+        expected = np.array([np.nan, 1, 2, 6, np.nan])
+        assert_equal(special.factorial(x, exact=False), expected)
+        with pytest.raises(ValueError, match="`exact=True` only supports.*"):
+            special.factorial(x, exact=True)
+
+
+class TestFresnel:
+    @pytest.mark.parametrize("z, s, c", [
+        # some positive value
+        (.5, 0.064732432859999287, 0.49234422587144644),
+        (.5 + .0j, 0.064732432859999287, 0.49234422587144644),
+        # negative half annulus
+        # https://github.com/scipy/scipy/issues/12309
+        # Reference values can be reproduced with
+        # https://www.wolframalpha.com/input/?i=FresnelS%5B-2.0+%2B+0.1i%5D
+        # https://www.wolframalpha.com/input/?i=FresnelC%5B-2.0+%2B+0.1i%5D
+        (
+            -2.0 + 0.1j,
+            -0.3109538687728942-0.0005870728836383176j,
+            -0.4879956866358554+0.10670801832903172j
+        ),
+        (
+            -0.1 - 1.5j,
+            -0.03918309471866977+0.7197508454568574j,
+            0.09605692502968956-0.43625191013617465j
+        ),
+        # a different algorithm kicks in for "large" values, i.e., |z| >= 4.5,
+        # make sure to test both float and complex values; a different
+        # algorithm is used
+        (6.0, 0.44696076, 0.49953147),
+        (6.0 + 0.0j, 0.44696076, 0.49953147),
+        (6.0j, -0.44696076j, 0.49953147j),
+        (-6.0 + 0.0j, -0.44696076, -0.49953147),
+        (-6.0j, 0.44696076j, -0.49953147j),
+        # inf
+        (np.inf, 0.5, 0.5),
+        (-np.inf, -0.5, -0.5),
+    ])
+    def test_fresnel_values(self, z, s, c):
+        frs = array(special.fresnel(z))
+        assert_array_almost_equal(frs, array([s, c]), 8)
+
+    # values from pg 329  Table 7.11 of A & S
+    #  slightly corrected in 4th decimal place
+    def test_fresnel_zeros(self):
+        szo, czo = special.fresnel_zeros(5)
+        assert_array_almost_equal(szo,
+                                  array([2.0093+0.2885j,
+                                          2.8335+0.2443j,
+                                          3.4675+0.2185j,
+                                          4.0026+0.2009j,
+                                          4.4742+0.1877j]),3)
+        assert_array_almost_equal(czo,
+                                  array([1.7437+0.3057j,
+                                          2.6515+0.2529j,
+                                          3.3204+0.2240j,
+                                          3.8757+0.2047j,
+                                          4.3611+0.1907j]),3)
+        vals1 = special.fresnel(szo)[0]
+        vals2 = special.fresnel(czo)[1]
+        assert_array_almost_equal(vals1,0,14)
+        assert_array_almost_equal(vals2,0,14)
+
+    def test_fresnelc_zeros(self):
+        szo, czo = special.fresnel_zeros(6)
+        frc = special.fresnelc_zeros(6)
+        assert_array_almost_equal(frc,czo,12)
+
+    def test_fresnels_zeros(self):
+        szo, czo = special.fresnel_zeros(5)
+        frs = special.fresnels_zeros(5)
+        assert_array_almost_equal(frs,szo,12)
+
+
+class TestGamma:
+    def test_gamma(self):
+        gam = special.gamma(5)
+        assert_equal(gam,24.0)
+
+    def test_gammaln(self):
+        gamln = special.gammaln(3)
+        lngam = log(special.gamma(3))
+        assert_almost_equal(gamln,lngam,8)
+
+    def test_gammainccinv(self):
+        gccinv = special.gammainccinv(.5,.5)
+        gcinv = special.gammaincinv(.5,.5)
+        assert_almost_equal(gccinv,gcinv,8)
+
+    @with_special_errors
+    def test_gammaincinv(self):
+        y = special.gammaincinv(.4,.4)
+        x = special.gammainc(.4,y)
+        assert_almost_equal(x,0.4,1)
+        y = special.gammainc(10, 0.05)
+        x = special.gammaincinv(10, 2.5715803516000736e-20)
+        assert_almost_equal(0.05, x, decimal=10)
+        assert_almost_equal(y, 2.5715803516000736e-20, decimal=10)
+        x = special.gammaincinv(50, 8.20754777388471303050299243573393e-18)
+        assert_almost_equal(11.0, x, decimal=10)
+
+    @with_special_errors
+    def test_975(self):
+        # Regression test for ticket #975 -- switch point in algorithm
+        # check that things work OK at the point, immediately next floats
+        # around it, and a bit further away
+        pts = [0.25,
+               np.nextafter(0.25, 0), 0.25 - 1e-12,
+               np.nextafter(0.25, 1), 0.25 + 1e-12]
+        for xp in pts:
+            y = special.gammaincinv(.4, xp)
+            x = special.gammainc(0.4, y)
+            assert_allclose(x, xp, rtol=1e-12)
+
+    def test_rgamma(self):
+        rgam = special.rgamma(8)
+        rlgam = 1/special.gamma(8)
+        assert_almost_equal(rgam,rlgam,8)
+
+    def test_infinity(self):
+        assert_equal(special.rgamma(-1), 0)
+
+    @pytest.mark.parametrize(
+        "x,expected",
+        [
+            # infinities
+            ([-np.inf, np.inf], [np.nan, np.inf]),
+            # negative and positive zero
+            ([-0.0, 0.0], [-np.inf, np.inf]),
+            # small poles
+            (range(-32, 0), np.full(32, np.nan)),
+            # medium sized poles
+            (range(-1024, -32, 99), np.full(11, np.nan)),
+            # large pole
+            ([-4.141512231792294e+16], [np.nan]),
+        ]
+    )
+    def test_poles(self, x, expected):
+        assert_array_equal(special.gamma(x), expected)
+
+
+class TestHankel:
+
+    def test_negv1(self):
+        assert_almost_equal(special.hankel1(-3,2), -special.hankel1(3,2), 14)
+
+    def test_hankel1(self):
+        hank1 = special.hankel1(1,.1)
+        hankrl = (special.jv(1,.1) + special.yv(1,.1)*1j)
+        assert_almost_equal(hank1,hankrl,8)
+
+    def test_negv1e(self):
+        assert_almost_equal(special.hankel1e(-3,2), -special.hankel1e(3,2), 14)
+
+    def test_hankel1e(self):
+        hank1e = special.hankel1e(1,.1)
+        hankrle = special.hankel1(1,.1)*exp(-.1j)
+        assert_almost_equal(hank1e,hankrle,8)
+
+    def test_negv2(self):
+        assert_almost_equal(special.hankel2(-3,2), -special.hankel2(3,2), 14)
+
+    def test_hankel2(self):
+        hank2 = special.hankel2(1,.1)
+        hankrl2 = (special.jv(1,.1) - special.yv(1,.1)*1j)
+        assert_almost_equal(hank2,hankrl2,8)
+
+    def test_neg2e(self):
+        assert_almost_equal(special.hankel2e(-3,2), -special.hankel2e(3,2), 14)
+
+    def test_hankl2e(self):
+        hank2e = special.hankel2e(1,.1)
+        hankrl2e = special.hankel2e(1,.1)
+        assert_almost_equal(hank2e,hankrl2e,8)
+
+    def test_hankel2_gh4517(self):
+        # Test edge case reported in https://github.com/scipy/scipy/issues/4517
+        res = special.hankel2(0, 0)
+        assert np.isnan(res.real)
+        assert np.isposinf(res.imag)
+
+
+class TestHyper:
+    def test_h1vp(self):
+        h1 = special.h1vp(1,.1)
+        h1real = (special.jvp(1,.1) + special.yvp(1,.1)*1j)
+        assert_almost_equal(h1,h1real,8)
+
+    def test_h2vp(self):
+        h2 = special.h2vp(1,.1)
+        h2real = (special.jvp(1,.1) - special.yvp(1,.1)*1j)
+        assert_almost_equal(h2,h2real,8)
+
+    def test_hyp0f1(self):
+        # scalar input
+        assert_allclose(special.hyp0f1(2.5, 0.5), 1.21482702689997, rtol=1e-12)
+        assert_allclose(special.hyp0f1(2.5, 0), 1.0, rtol=1e-15)
+
+        # float input, expected values match mpmath
+        x = special.hyp0f1(3.0, [-1.5, -1, 0, 1, 1.5])
+        expected = np.array([0.58493659229143, 0.70566805723127, 1.0,
+                             1.37789689539747, 1.60373685288480])
+        assert_allclose(x, expected, rtol=1e-12)
+
+        # complex input
+        x = special.hyp0f1(3.0, np.array([-1.5, -1, 0, 1, 1.5]) + 0.j)
+        assert_allclose(x, expected.astype(complex), rtol=1e-12)
+
+        # test broadcasting
+        x1 = [0.5, 1.5, 2.5]
+        x2 = [0, 1, 0.5]
+        x = special.hyp0f1(x1, x2)
+        expected = [1.0, 1.8134302039235093, 1.21482702689997]
+        assert_allclose(x, expected, rtol=1e-12)
+        x = special.hyp0f1(np.vstack([x1] * 2), x2)
+        assert_allclose(x, np.vstack([expected] * 2), rtol=1e-12)
+        assert_raises(ValueError, special.hyp0f1,
+                      np.vstack([x1] * 3), [0, 1])
+
+    def test_hyp0f1_gh5764(self):
+        # Just checks the point that failed; there's a more systematic
+        # test in test_mpmath
+        res = special.hyp0f1(0.8, 0.5 + 0.5*1J)
+        # The expected value was generated using mpmath
+        assert_almost_equal(res, 1.6139719776441115 + 1J*0.80893054061790665)
+
+    def test_hyp1f1(self):
+        hyp1 = special.hyp1f1(.1,.1,.3)
+        assert_almost_equal(hyp1, 1.3498588075760032,7)
+
+        # test contributed by Moritz Deger (2008-05-29)
+        # https://github.com/scipy/scipy/issues/1186 (Trac #659)
+
+        # reference data obtained from mathematica [ a, b, x, m(a,b,x)]:
+        # produced with test_hyp1f1.nb
+        ref_data = array([
+            [-8.38132975e+00, -1.28436461e+01, -2.91081397e+01, 1.04178330e+04],
+            [2.91076882e+00, -6.35234333e+00, -1.27083993e+01, 6.68132725e+00],
+            [-1.42938258e+01, 1.80869131e-01, 1.90038728e+01, 1.01385897e+05],
+            [5.84069088e+00, 1.33187908e+01, 2.91290106e+01, 1.59469411e+08],
+            [-2.70433202e+01, -1.16274873e+01, -2.89582384e+01, 1.39900152e+24],
+            [4.26344966e+00, -2.32701773e+01, 1.91635759e+01, 6.13816915e+21],
+            [1.20514340e+01, -3.40260240e+00, 7.26832235e+00, 1.17696112e+13],
+            [2.77372955e+01, -1.99424687e+00, 3.61332246e+00, 3.07419615e+13],
+            [1.50310939e+01, -2.91198675e+01, -1.53581080e+01, -3.79166033e+02],
+            [1.43995827e+01, 9.84311196e+00, 1.93204553e+01, 2.55836264e+10],
+            [-4.08759686e+00, 1.34437025e+01, -1.42072843e+01, 1.70778449e+01],
+            [8.05595738e+00, -1.31019838e+01, 1.52180721e+01, 3.06233294e+21],
+            [1.81815804e+01, -1.42908793e+01, 9.57868793e+00, -2.84771348e+20],
+            [-2.49671396e+01, 1.25082843e+01, -1.71562286e+01, 2.36290426e+07],
+            [2.67277673e+01, 1.70315414e+01, 6.12701450e+00, 7.77917232e+03],
+            [2.49565476e+01, 2.91694684e+01, 6.29622660e+00, 2.35300027e+02],
+            [6.11924542e+00, -1.59943768e+00, 9.57009289e+00, 1.32906326e+11],
+            [-1.47863653e+01, 2.41691301e+01, -1.89981821e+01, 2.73064953e+03],
+            [2.24070483e+01, -2.93647433e+00, 8.19281432e+00, -6.42000372e+17],
+            [8.04042600e-01, 1.82710085e+01, -1.97814534e+01, 5.48372441e-01],
+            [1.39590390e+01, 1.97318686e+01, 2.37606635e+00, 5.51923681e+00],
+            [-4.66640483e+00, -2.00237930e+01, 7.40365095e+00, 4.50310752e+00],
+            [2.76821999e+01, -6.36563968e+00, 1.11533984e+01, -9.28725179e+23],
+            [-2.56764457e+01, 1.24544906e+00, 1.06407572e+01, 1.25922076e+01],
+            [3.20447808e+00, 1.30874383e+01, 2.26098014e+01, 2.03202059e+04],
+            [-1.24809647e+01, 4.15137113e+00, -2.92265700e+01, 2.39621411e+08],
+            [2.14778108e+01, -2.35162960e+00, -1.13758664e+01, 4.46882152e-01],
+            [-9.85469168e+00, -3.28157680e+00, 1.67447548e+01, -1.07342390e+07],
+            [1.08122310e+01, -2.47353236e+01, -1.15622349e+01, -2.91733796e+03],
+            [-2.67933347e+01, -3.39100709e+00, 2.56006986e+01, -5.29275382e+09],
+            [-8.60066776e+00, -8.02200924e+00, 1.07231926e+01, 1.33548320e+06],
+            [-1.01724238e-01, -1.18479709e+01, -2.55407104e+01, 1.55436570e+00],
+            [-3.93356771e+00, 2.11106818e+01, -2.57598485e+01, 2.13467840e+01],
+            [3.74750503e+00, 1.55687633e+01, -2.92841720e+01, 1.43873509e-02],
+            [6.99726781e+00, 2.69855571e+01, -1.63707771e+01, 3.08098673e-02],
+            [-2.31996011e+01, 3.47631054e+00, 9.75119815e-01, 1.79971073e-02],
+            [2.38951044e+01, -2.91460190e+01, -2.50774708e+00, 9.56934814e+00],
+            [1.52730825e+01, 5.77062507e+00, 1.21922003e+01, 1.32345307e+09],
+            [1.74673917e+01, 1.89723426e+01, 4.94903250e+00, 9.90859484e+01],
+            [1.88971241e+01, 2.86255413e+01, 5.52360109e-01, 1.44165360e+00],
+            [1.02002319e+01, -1.66855152e+01, -2.55426235e+01, 6.56481554e+02],
+            [-1.79474153e+01, 1.22210200e+01, -1.84058212e+01, 8.24041812e+05],
+            [-1.36147103e+01, 1.32365492e+00, -7.22375200e+00, 9.92446491e+05],
+            [7.57407832e+00, 2.59738234e+01, -1.34139168e+01, 3.64037761e-02],
+            [2.21110169e+00, 1.28012666e+01, 1.62529102e+01, 1.33433085e+02],
+            [-2.64297569e+01, -1.63176658e+01, -1.11642006e+01, -2.44797251e+13],
+            [-2.46622944e+01, -3.02147372e+00, 8.29159315e+00, -3.21799070e+05],
+            [-1.37215095e+01, -1.96680183e+01, 2.91940118e+01, 3.21457520e+12],
+            [-5.45566105e+00, 2.81292086e+01, 1.72548215e-01, 9.66973000e-01],
+            [-1.55751298e+00, -8.65703373e+00, 2.68622026e+01, -3.17190834e+16],
+            [2.45393609e+01, -2.70571903e+01, 1.96815505e+01, 1.80708004e+37],
+            [5.77482829e+00, 1.53203143e+01, 2.50534322e+01, 1.14304242e+06],
+            [-1.02626819e+01, 2.36887658e+01, -2.32152102e+01, 7.28965646e+02],
+            [-1.30833446e+00, -1.28310210e+01, 1.87275544e+01, -9.33487904e+12],
+            [5.83024676e+00, -1.49279672e+01, 2.44957538e+01, -7.61083070e+27],
+            [-2.03130747e+01, 2.59641715e+01, -2.06174328e+01, 4.54744859e+04],
+            [1.97684551e+01, -2.21410519e+01, -2.26728740e+01, 3.53113026e+06],
+            [2.73673444e+01, 2.64491725e+01, 1.57599882e+01, 1.07385118e+07],
+            [5.73287971e+00, 1.21111904e+01, 1.33080171e+01, 2.63220467e+03],
+            [-2.82751072e+01, 2.08605881e+01, 9.09838900e+00, -6.60957033e-07],
+            [1.87270691e+01, -1.74437016e+01, 1.52413599e+01, 6.59572851e+27],
+            [6.60681457e+00, -2.69449855e+00, 9.78972047e+00, -2.38587870e+12],
+            [1.20895561e+01, -2.51355765e+01, 2.30096101e+01, 7.58739886e+32],
+            [-2.44682278e+01, 2.10673441e+01, -1.36705538e+01, 4.54213550e+04],
+            [-4.50665152e+00, 3.72292059e+00, -4.83403707e+00, 2.68938214e+01],
+            [-7.46540049e+00, -1.08422222e+01, -1.72203805e+01, -2.09402162e+02],
+            [-2.00307551e+01, -7.50604431e+00, -2.78640020e+01, 4.15985444e+19],
+            [1.99890876e+01, 2.20677419e+01, -2.51301778e+01, 1.23840297e-09],
+            [2.03183823e+01, -7.66942559e+00, 2.10340070e+01, 1.46285095e+31],
+            [-2.90315825e+00, -2.55785967e+01, -9.58779316e+00, 2.65714264e-01],
+            [2.73960829e+01, -1.80097203e+01, -2.03070131e+00, 2.52908999e+02],
+            [-2.11708058e+01, -2.70304032e+01, 2.48257944e+01, 3.09027527e+08],
+            [2.21959758e+01, 4.00258675e+00, -1.62853977e+01, -9.16280090e-09],
+            [1.61661840e+01, -2.26845150e+01, 2.17226940e+01, -8.24774394e+33],
+            [-3.35030306e+00, 1.32670581e+00, 9.39711214e+00, -1.47303163e+01],
+            [7.23720726e+00, -2.29763909e+01, 2.34709682e+01, -9.20711735e+29],
+            [2.71013568e+01, 1.61951087e+01, -7.11388906e-01, 2.98750911e-01],
+            [8.40057933e+00, -7.49665220e+00, 2.95587388e+01, 6.59465635e+29],
+            [-1.51603423e+01, 1.94032322e+01, -7.60044357e+00, 1.05186941e+02],
+            [-8.83788031e+00, -2.72018313e+01, 1.88269907e+00, 1.81687019e+00],
+            [-1.87283712e+01, 5.87479570e+00, -1.91210203e+01, 2.52235612e+08],
+            [-5.61338513e-01, 2.69490237e+01, 1.16660111e-01, 9.97567783e-01],
+            [-5.44354025e+00, -1.26721408e+01, -4.66831036e+00, 1.06660735e-01],
+            [-2.18846497e+00, 2.33299566e+01, 9.62564397e+00, 3.03842061e-01],
+            [6.65661299e+00, -2.39048713e+01, 1.04191807e+01, 4.73700451e+13],
+            [-2.57298921e+01, -2.60811296e+01, 2.74398110e+01, -5.32566307e+11],
+            [-1.11431826e+01, -1.59420160e+01, -1.84880553e+01, -1.01514747e+02],
+            [6.50301931e+00, 2.59859051e+01, -2.33270137e+01, 1.22760500e-02],
+            [-1.94987891e+01, -2.62123262e+01, 3.90323225e+00, 1.71658894e+01],
+            [7.26164601e+00, -1.41469402e+01, 2.81499763e+01, -2.50068329e+31],
+            [-1.52424040e+01, 2.99719005e+01, -2.85753678e+01, 1.31906693e+04],
+            [5.24149291e+00, -1.72807223e+01, 2.22129493e+01, 2.50748475e+25],
+            [3.63207230e-01, -9.54120862e-02, -2.83874044e+01, 9.43854939e-01],
+            [-2.11326457e+00, -1.25707023e+01, 1.17172130e+00, 1.20812698e+00],
+            [2.48513582e+00, 1.03652647e+01, -1.84625148e+01, 6.47910997e-02],
+            [2.65395942e+01, 2.74794672e+01, 1.29413428e+01, 2.89306132e+05],
+            [-9.49445460e+00, 1.59930921e+01, -1.49596331e+01, 3.27574841e+02],
+            [-5.89173945e+00, 9.96742426e+00, 2.60318889e+01, -3.15842908e-01],
+            [-1.15387239e+01, -2.21433107e+01, -2.17686413e+01, 1.56724718e-01],
+            [-5.30592244e+00, -2.42752190e+01, 1.29734035e+00, 1.31985534e+00]
+        ])
+
+        for a,b,c,expected in ref_data:
+            result = special.hyp1f1(a,b,c)
+            assert_(abs(expected - result)/expected < 1e-4)
+
+    def test_hyp1f1_gh2957(self):
+        hyp1 = special.hyp1f1(0.5, 1.5, -709.7827128933)
+        hyp2 = special.hyp1f1(0.5, 1.5, -709.7827128934)
+        assert_almost_equal(hyp1, hyp2, 12)
+
+    def test_hyp1f1_gh2282(self):
+        hyp = special.hyp1f1(0.5, 1.5, -1000)
+        assert_almost_equal(hyp, 0.028024956081989643, 12)
+
+    def test_hyp2f1(self):
+        # a collection of special cases taken from AMS 55
+        values = [
+            [0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))],
+            [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)],
+            [1, 1, 2, 0.2, -1/0.2*log(1-0.2)],
+            [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))],
+            [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)],
+            [3, 4, 8, 1,
+             special.gamma(8) * special.gamma(8-4-3)
+             / special.gamma(8-3) / special.gamma(8-4)],
+            [3, 2, 3-2+1, -1,
+             1./2**3*sqrt(pi) * special.gamma(1+3-2)
+             / special.gamma(1+0.5*3-2) / special.gamma(0.5+0.5*3)],
+            [5, 2, 5-2+1, -1,
+             1./2**5*sqrt(pi) * special.gamma(1+5-2)
+             / special.gamma(1+0.5*5-2) / special.gamma(0.5+0.5*5)],
+            [4, 0.5+4, 1.5-2*4, -1./3,
+             (8./9)**(-2*4)*special.gamma(4./3) * special.gamma(1.5-2*4)
+             / special.gamma(3./2) / special.gamma(4./3-2*4)],
+            # and some others
+            # ticket #424
+            [1.5, -0.5, 1.0, -10.0, 4.1300097765277476484],
+            # negative integer a or b, with c-a-b integer and x > 0.9
+            [-2,3,1,0.95,0.715],
+            [2,-3,1,0.95,-0.007],
+            [-6,3,1,0.95,0.0000810625],
+            [2,-5,1,0.95,-0.000029375],
+            # huge negative integers
+            (10, -900, 10.5, 0.99, 1.91853705796607664803709475658e-24),
+            (10, -900, -10.5, 0.99, 3.54279200040355710199058559155e-18),
+        ]
+        for i, (a, b, c, x, v) in enumerate(values):
+            cv = special.hyp2f1(a, b, c, x)
+            assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)
+
+    def test_hyperu(self):
+        val1 = special.hyperu(1,0.1,100)
+        assert_almost_equal(val1,0.0098153,7)
+        a,b = [0.3,0.6,1.2,-2.7],[1.5,3.2,-0.4,-3.2]
+        a,b = asarray(a), asarray(b)
+        z = 0.5
+        hypu = special.hyperu(a,b,z)
+        hprl = (pi/sin(pi*b))*(special.hyp1f1(a,b,z) /
+                               (special.gamma(1+a-b)*special.gamma(b)) -
+                               z**(1-b)*special.hyp1f1(1+a-b,2-b,z)
+                               / (special.gamma(a)*special.gamma(2-b)))
+        assert_array_almost_equal(hypu,hprl,12)
+
+    def test_hyperu_gh2287(self):
+        assert_almost_equal(special.hyperu(1, 1.5, 20.2),
+                            0.048360918656699191, 12)
+
+
+class TestBessel:
+    def test_itj0y0(self):
+        it0 = array(special.itj0y0(.2))
+        assert_array_almost_equal(
+            it0,
+            array([0.19933433254006822, -0.34570883800412566]),
+            8,
+        )
+
+    def test_it2j0y0(self):
+        it2 = array(special.it2j0y0(.2))
+        assert_array_almost_equal(
+            it2,
+            array([0.0049937546274601858, -0.43423067011231614]),
+            8,
+        )
+
+    def test_negv_iv(self):
+        assert_equal(special.iv(3,2), special.iv(-3,2))
+
+    def test_j0(self):
+        oz = special.j0(.1)
+        ozr = special.jn(0,.1)
+        assert_almost_equal(oz,ozr,8)
+
+    def test_j1(self):
+        o1 = special.j1(.1)
+        o1r = special.jn(1,.1)
+        assert_almost_equal(o1,o1r,8)
+
+    def test_jn(self):
+        jnnr = special.jn(1,.2)
+        assert_almost_equal(jnnr,0.099500832639235995,8)
+
+    def test_negv_jv(self):
+        assert_almost_equal(special.jv(-3,2), -special.jv(3,2), 14)
+
+    def test_jv(self):
+        values = [[0, 0.1, 0.99750156206604002],
+                  [2./3, 1e-8, 0.3239028506761532e-5],
+                  [2./3, 1e-10, 0.1503423854873779e-6],
+                  [3.1, 1e-10, 0.1711956265409013e-32],
+                  [2./3, 4.0, -0.2325440850267039],
+                  ]
+        for i, (v, x, y) in enumerate(values):
+            yc = special.jv(v, x)
+            assert_almost_equal(yc, y, 8, err_msg='test #%d' % i)
+
+    def test_negv_jve(self):
+        assert_almost_equal(special.jve(-3,2), -special.jve(3,2), 14)
+
+    def test_jve(self):
+        jvexp = special.jve(1,.2)
+        assert_almost_equal(jvexp,0.099500832639235995,8)
+        jvexp1 = special.jve(1,.2+1j)
+        z = .2+1j
+        jvexpr = special.jv(1,z)*exp(-abs(z.imag))
+        assert_almost_equal(jvexp1,jvexpr,8)
+
+    def test_jn_zeros(self):
+        jn0 = special.jn_zeros(0,5)
+        jn1 = special.jn_zeros(1,5)
+        assert_array_almost_equal(jn0,array([2.4048255577,
+                                              5.5200781103,
+                                              8.6537279129,
+                                              11.7915344391,
+                                              14.9309177086]),4)
+        assert_array_almost_equal(jn1,array([3.83171,
+                                              7.01559,
+                                              10.17347,
+                                              13.32369,
+                                              16.47063]),4)
+
+        jn102 = special.jn_zeros(102,5)
+        assert_allclose(jn102, array([110.89174935992040343,
+                                       117.83464175788308398,
+                                       123.70194191713507279,
+                                       129.02417238949092824,
+                                       134.00114761868422559]), rtol=1e-13)
+
+        jn301 = special.jn_zeros(301,5)
+        assert_allclose(jn301, array([313.59097866698830153,
+                                       323.21549776096288280,
+                                       331.22338738656748796,
+                                       338.39676338872084500,
+                                       345.03284233056064157]), rtol=1e-13)
+
+    def test_jn_zeros_slow(self):
+        jn0 = special.jn_zeros(0, 300)
+        assert_allclose(jn0[260-1], 816.02884495068867280, rtol=1e-13)
+        assert_allclose(jn0[280-1], 878.86068707124422606, rtol=1e-13)
+        assert_allclose(jn0[300-1], 941.69253065317954064, rtol=1e-13)
+
+        jn10 = special.jn_zeros(10, 300)
+        assert_allclose(jn10[260-1], 831.67668514305631151, rtol=1e-13)
+        assert_allclose(jn10[280-1], 894.51275095371316931, rtol=1e-13)
+        assert_allclose(jn10[300-1], 957.34826370866539775, rtol=1e-13)
+
+        jn3010 = special.jn_zeros(3010,5)
+        assert_allclose(jn3010, array([3036.86590780927,
+                                        3057.06598526482,
+                                        3073.66360690272,
+                                        3088.37736494778,
+                                        3101.86438139042]), rtol=1e-8)
+
+    def test_jnjnp_zeros(self):
+        jn = special.jn
+
+        def jnp(n, x):
+            return (jn(n-1,x) - jn(n+1,x))/2
+        for nt in range(1, 30):
+            z, n, m, t = special.jnjnp_zeros(nt)
+            for zz, nn, tt in zip(z, n, t):
+                if tt == 0:
+                    assert_allclose(jn(nn, zz), 0, atol=1e-6)
+                elif tt == 1:
+                    assert_allclose(jnp(nn, zz), 0, atol=1e-6)
+                else:
+                    raise AssertionError("Invalid t return for nt=%d" % nt)
+
+    def test_jnp_zeros(self):
+        jnp = special.jnp_zeros(1,5)
+        assert_array_almost_equal(jnp, array([1.84118,
+                                                5.33144,
+                                                8.53632,
+                                                11.70600,
+                                                14.86359]),4)
+        jnp = special.jnp_zeros(443,5)
+        assert_allclose(special.jvp(443, jnp), 0, atol=1e-15)
+
+    def test_jnyn_zeros(self):
+        jnz = special.jnyn_zeros(1,5)
+        assert_array_almost_equal(jnz,(array([3.83171,
+                                                7.01559,
+                                                10.17347,
+                                                13.32369,
+                                                16.47063]),
+                                       array([1.84118,
+                                                5.33144,
+                                                8.53632,
+                                                11.70600,
+                                                14.86359]),
+                                       array([2.19714,
+                                                5.42968,
+                                                8.59601,
+                                                11.74915,
+                                                14.89744]),
+                                       array([3.68302,
+                                                6.94150,
+                                                10.12340,
+                                                13.28576,
+                                                16.44006])),5)
+
+    def test_jvp(self):
+        jvprim = special.jvp(2,2)
+        jv0 = (special.jv(1,2)-special.jv(3,2))/2
+        assert_almost_equal(jvprim,jv0,10)
+
+    def test_k0(self):
+        ozk = special.k0(.1)
+        ozkr = special.kv(0,.1)
+        assert_almost_equal(ozk,ozkr,8)
+
+    def test_k0e(self):
+        ozke = special.k0e(.1)
+        ozker = special.kve(0,.1)
+        assert_almost_equal(ozke,ozker,8)
+
+    def test_k1(self):
+        o1k = special.k1(.1)
+        o1kr = special.kv(1,.1)
+        assert_almost_equal(o1k,o1kr,8)
+
+    def test_k1e(self):
+        o1ke = special.k1e(.1)
+        o1ker = special.kve(1,.1)
+        assert_almost_equal(o1ke,o1ker,8)
+
+    def test_jacobi(self):
+        a = 5*np.random.random() - 1
+        b = 5*np.random.random() - 1
+        P0 = special.jacobi(0,a,b)
+        P1 = special.jacobi(1,a,b)
+        P2 = special.jacobi(2,a,b)
+        P3 = special.jacobi(3,a,b)
+
+        assert_array_almost_equal(P0.c,[1],13)
+        assert_array_almost_equal(P1.c,array([a+b+2,a-b])/2.0,13)
+        cp = [(a+b+3)*(a+b+4), 4*(a+b+3)*(a+2), 4*(a+1)*(a+2)]
+        p2c = [cp[0],cp[1]-2*cp[0],cp[2]-cp[1]+cp[0]]
+        assert_array_almost_equal(P2.c,array(p2c)/8.0,13)
+        cp = [(a+b+4)*(a+b+5)*(a+b+6),6*(a+b+4)*(a+b+5)*(a+3),
+              12*(a+b+4)*(a+2)*(a+3),8*(a+1)*(a+2)*(a+3)]
+        p3c = [cp[0],cp[1]-3*cp[0],cp[2]-2*cp[1]+3*cp[0],cp[3]-cp[2]+cp[1]-cp[0]]
+        assert_array_almost_equal(P3.c,array(p3c)/48.0,13)
+
+    def test_kn(self):
+        kn1 = special.kn(0,.2)
+        assert_almost_equal(kn1,1.7527038555281462,8)
+
+    def test_negv_kv(self):
+        assert_equal(special.kv(3.0, 2.2), special.kv(-3.0, 2.2))
+
+    def test_kv0(self):
+        kv0 = special.kv(0,.2)
+        assert_almost_equal(kv0, 1.7527038555281462, 10)
+
+    def test_kv1(self):
+        kv1 = special.kv(1,0.2)
+        assert_almost_equal(kv1, 4.775972543220472, 10)
+
+    def test_kv2(self):
+        kv2 = special.kv(2,0.2)
+        assert_almost_equal(kv2, 49.51242928773287, 10)
+
+    def test_kn_largeorder(self):
+        assert_allclose(special.kn(32, 1), 1.7516596664574289e+43)
+
+    def test_kv_largearg(self):
+        assert_equal(special.kv(0, 1e19), 0)
+
+    def test_negv_kve(self):
+        assert_equal(special.kve(3.0, 2.2), special.kve(-3.0, 2.2))
+
+    def test_kve(self):
+        kve1 = special.kve(0,.2)
+        kv1 = special.kv(0,.2)*exp(.2)
+        assert_almost_equal(kve1,kv1,8)
+        z = .2+1j
+        kve2 = special.kve(0,z)
+        kv2 = special.kv(0,z)*exp(z)
+        assert_almost_equal(kve2,kv2,8)
+
+    def test_kvp_v0n1(self):
+        z = 2.2
+        assert_almost_equal(-special.kv(1,z), special.kvp(0,z, n=1), 10)
+
+    def test_kvp_n1(self):
+        v = 3.
+        z = 2.2
+        xc = -special.kv(v+1,z) + v/z*special.kv(v,z)
+        x = special.kvp(v,z, n=1)
+        assert_almost_equal(xc, x, 10)   # this function (kvp) is broken
+
+    def test_kvp_n2(self):
+        v = 3.
+        z = 2.2
+        xc = (z**2+v**2-v)/z**2 * special.kv(v,z) + special.kv(v+1,z)/z
+        x = special.kvp(v, z, n=2)
+        assert_almost_equal(xc, x, 10)
+
+    def test_y0(self):
+        oz = special.y0(.1)
+        ozr = special.yn(0,.1)
+        assert_almost_equal(oz,ozr,8)
+
+    def test_y1(self):
+        o1 = special.y1(.1)
+        o1r = special.yn(1,.1)
+        assert_almost_equal(o1,o1r,8)
+
+    def test_y0_zeros(self):
+        yo,ypo = special.y0_zeros(2)
+        zo,zpo = special.y0_zeros(2,complex=1)
+        all = r_[yo,zo]
+        allval = r_[ypo,zpo]
+        assert_array_almost_equal(abs(special.yv(0.0,all)),0.0,11)
+        assert_array_almost_equal(abs(special.yv(1,all)-allval),0.0,11)
+
+    def test_y1_zeros(self):
+        y1 = special.y1_zeros(1)
+        assert_array_almost_equal(y1,(array([2.19714]),array([0.52079])),5)
+
+    def test_y1p_zeros(self):
+        y1p = special.y1p_zeros(1,complex=1)
+        assert_array_almost_equal(
+            y1p,
+            (array([0.5768+0.904j]), array([-0.7635+0.5892j])),
+            3,
+        )
+
+    def test_yn_zeros(self):
+        an = special.yn_zeros(4,2)
+        assert_array_almost_equal(an,array([5.64515, 9.36162]),5)
+        an = special.yn_zeros(443,5)
+        assert_allclose(an, [450.13573091578090314,
+                             463.05692376675001542,
+                             472.80651546418663566,
+                             481.27353184725625838,
+                             488.98055964441374646],
+                        rtol=1e-15,)
+
+    def test_ynp_zeros(self):
+        ao = special.ynp_zeros(0,2)
+        assert_array_almost_equal(ao,array([2.19714133, 5.42968104]),6)
+        ao = special.ynp_zeros(43,5)
+        assert_allclose(special.yvp(43, ao), 0, atol=1e-15)
+        ao = special.ynp_zeros(443,5)
+        assert_allclose(special.yvp(443, ao), 0, atol=1e-9)
+
+    def test_ynp_zeros_large_order(self):
+        ao = special.ynp_zeros(443,5)
+        assert_allclose(special.yvp(443, ao), 0, atol=1e-14)
+
+    def test_yn(self):
+        yn2n = special.yn(1,.2)
+        assert_almost_equal(yn2n,-3.3238249881118471,8)
+
+    def test_yn_gh_20405(self):
+        # Enforce correct asymptotic behavior for large n.
+        observed = cephes.yn(500, 1)
+        assert observed == -np.inf
+
+    def test_negv_yv(self):
+        assert_almost_equal(special.yv(-3,2), -special.yv(3,2), 14)
+
+    def test_yv(self):
+        yv2 = special.yv(1,.2)
+        assert_almost_equal(yv2,-3.3238249881118471,8)
+
+    def test_negv_yve(self):
+        assert_almost_equal(special.yve(-3,2), -special.yve(3,2), 14)
+
+    def test_yve(self):
+        yve2 = special.yve(1,.2)
+        assert_almost_equal(yve2,-3.3238249881118471,8)
+        yve2r = special.yv(1,.2+1j)*exp(-1)
+        yve22 = special.yve(1,.2+1j)
+        assert_almost_equal(yve22,yve2r,8)
+
+    def test_yvp(self):
+        yvpr = (special.yv(1,.2) - special.yv(3,.2))/2.0
+        yvp1 = special.yvp(2,.2)
+        assert_array_almost_equal(yvp1,yvpr,10)
+
+    def _cephes_vs_amos_points(self):
+        """Yield points at which to compare Cephes implementation to AMOS"""
+        # check several points, including large-amplitude ones
+        v = [-120, -100.3, -20., -10., -1., -.5, 0., 1., 12.49, 120., 301]
+        z = [-1300, -11, -10, -1, 1., 10., 200.5, 401., 600.5, 700.6, 1300,
+             10003]
+        yield from itertools.product(v, z)
+
+        # check half-integers; these are problematic points at least
+        # for cephes/iv
+        yield from itertools.product(0.5 + arange(-60, 60), [3.5])
+
+    def check_cephes_vs_amos(self, f1, f2, rtol=1e-11, atol=0, skip=None):
+        for v, z in self._cephes_vs_amos_points():
+            if skip is not None and skip(v, z):
+                continue
+            c1, c2, c3 = f1(v, z), f1(v,z+0j), f2(int(v), z)
+            if np.isinf(c1):
+                assert_(np.abs(c2) >= 1e300, (v, z))
+            elif np.isnan(c1):
+                assert_(c2.imag != 0, (v, z))
+            else:
+                assert_allclose(c1, c2, err_msg=(v, z), rtol=rtol, atol=atol)
+                if v == int(v):
+                    assert_allclose(c3, c2, err_msg=(v, z),
+                                     rtol=rtol, atol=atol)
+
+    @pytest.mark.xfail(platform.machine() == 'ppc64le',
+                       reason="fails on ppc64le")
+    def test_jv_cephes_vs_amos(self):
+        self.check_cephes_vs_amos(special.jv, special.jn, rtol=1e-10, atol=1e-305)
+
+    @pytest.mark.xfail(platform.machine() == 'ppc64le',
+                       reason="fails on ppc64le")
+    def test_yv_cephes_vs_amos(self):
+        self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305)
+
+    def test_yv_cephes_vs_amos_only_small_orders(self):
+        def skipper(v, z):
+            return abs(v) > 50
+        self.check_cephes_vs_amos(special.yv, special.yn, rtol=1e-11, atol=1e-305,
+                                  skip=skipper)
+
+    def test_iv_cephes_vs_amos(self):
+        with np.errstate(all='ignore'):
+            self.check_cephes_vs_amos(special.iv, special.iv, rtol=5e-9, atol=1e-305)
+
+    @pytest.mark.slow
+    def test_iv_cephes_vs_amos_mass_test(self):
+        N = 1000000
+        np.random.seed(1)
+        v = np.random.pareto(0.5, N) * (-1)**np.random.randint(2, size=N)
+        x = np.random.pareto(0.2, N) * (-1)**np.random.randint(2, size=N)
+
+        imsk = (np.random.randint(8, size=N) == 0)
+        v[imsk] = v[imsk].astype(np.int64)
+
+        with np.errstate(all='ignore'):
+            c1 = special.iv(v, x)
+            c2 = special.iv(v, x+0j)
+
+            # deal with differences in the inf and zero cutoffs
+            c1[abs(c1) > 1e300] = np.inf
+            c2[abs(c2) > 1e300] = np.inf
+            c1[abs(c1) < 1e-300] = 0
+            c2[abs(c2) < 1e-300] = 0
+
+            dc = abs(c1/c2 - 1)
+            dc[np.isnan(dc)] = 0
+
+        k = np.argmax(dc)
+
+        # Most error apparently comes from AMOS and not our implementation;
+        # there are some problems near integer orders there
+        assert_(
+            dc[k] < 2e-7,
+            (v[k], x[k], special.iv(v[k], x[k]), special.iv(v[k], x[k]+0j))
+        )
+
+    def test_kv_cephes_vs_amos(self):
+        self.check_cephes_vs_amos(special.kv, special.kn, rtol=1e-9, atol=1e-305)
+        self.check_cephes_vs_amos(special.kv, special.kv, rtol=1e-9, atol=1e-305)
+
+    def test_ticket_623(self):
+        assert_allclose(special.jv(3, 4), 0.43017147387562193)
+        assert_allclose(special.jv(301, 1300), 0.0183487151115275)
+        assert_allclose(special.jv(301, 1296.0682), -0.0224174325312048)
+
+    def test_ticket_853(self):
+        """Negative-order Bessels"""
+        # cephes
+        assert_allclose(special.jv(-1, 1), -0.4400505857449335)
+        assert_allclose(special.jv(-2, 1), 0.1149034849319005)
+        assert_allclose(special.yv(-1, 1), 0.7812128213002887)
+        assert_allclose(special.yv(-2, 1), -1.650682606816255)
+        assert_allclose(special.iv(-1, 1), 0.5651591039924851)
+        assert_allclose(special.iv(-2, 1), 0.1357476697670383)
+        assert_allclose(special.kv(-1, 1), 0.6019072301972347)
+        assert_allclose(special.kv(-2, 1), 1.624838898635178)
+        assert_allclose(special.jv(-0.5, 1), 0.43109886801837607952)
+        assert_allclose(special.yv(-0.5, 1), 0.6713967071418031)
+        assert_allclose(special.iv(-0.5, 1), 1.231200214592967)
+        assert_allclose(special.kv(-0.5, 1), 0.4610685044478945)
+        # amos
+        assert_allclose(special.jv(-1, 1+0j), -0.4400505857449335)
+        assert_allclose(special.jv(-2, 1+0j), 0.1149034849319005)
+        assert_allclose(special.yv(-1, 1+0j), 0.7812128213002887)
+        assert_allclose(special.yv(-2, 1+0j), -1.650682606816255)
+
+        assert_allclose(special.iv(-1, 1+0j), 0.5651591039924851)
+        assert_allclose(special.iv(-2, 1+0j), 0.1357476697670383)
+        assert_allclose(special.kv(-1, 1+0j), 0.6019072301972347)
+        assert_allclose(special.kv(-2, 1+0j), 1.624838898635178)
+
+        assert_allclose(special.jv(-0.5, 1+0j), 0.43109886801837607952)
+        assert_allclose(special.jv(-0.5, 1+1j), 0.2628946385649065-0.827050182040562j)
+        assert_allclose(special.yv(-0.5, 1+0j), 0.6713967071418031)
+        assert_allclose(special.yv(-0.5, 1+1j), 0.967901282890131+0.0602046062142816j)
+
+        assert_allclose(special.iv(-0.5, 1+0j), 1.231200214592967)
+        assert_allclose(special.iv(-0.5, 1+1j), 0.77070737376928+0.39891821043561j)
+        assert_allclose(special.kv(-0.5, 1+0j), 0.4610685044478945)
+        assert_allclose(special.kv(-0.5, 1+1j), 0.06868578341999-0.38157825981268j)
+
+        assert_allclose(special.jve(-0.5,1+0.3j), special.jv(-0.5, 1+0.3j)*exp(-0.3))
+        assert_allclose(special.yve(-0.5,1+0.3j), special.yv(-0.5, 1+0.3j)*exp(-0.3))
+        assert_allclose(special.ive(-0.5,0.3+1j), special.iv(-0.5, 0.3+1j)*exp(-0.3))
+        assert_allclose(special.kve(-0.5,0.3+1j), special.kv(-0.5, 0.3+1j)*exp(0.3+1j))
+
+        assert_allclose(
+            special.hankel1(-0.5, 1+1j),
+            special.jv(-0.5, 1+1j) + 1j*special.yv(-0.5,1+1j)
+        )
+        assert_allclose(
+            special.hankel2(-0.5, 1+1j),
+            special.jv(-0.5, 1+1j) - 1j*special.yv(-0.5,1+1j)
+        )
+
+    def test_ticket_854(self):
+        """Real-valued Bessel domains"""
+        assert_(isnan(special.jv(0.5, -1)))
+        assert_(isnan(special.iv(0.5, -1)))
+        assert_(isnan(special.yv(0.5, -1)))
+        assert_(isnan(special.yv(1, -1)))
+        assert_(isnan(special.kv(0.5, -1)))
+        assert_(isnan(special.kv(1, -1)))
+        assert_(isnan(special.jve(0.5, -1)))
+        assert_(isnan(special.ive(0.5, -1)))
+        assert_(isnan(special.yve(0.5, -1)))
+        assert_(isnan(special.yve(1, -1)))
+        assert_(isnan(special.kve(0.5, -1)))
+        assert_(isnan(special.kve(1, -1)))
+        assert_(isnan(special.airye(-1)[0:2]).all(), special.airye(-1))
+        assert_(not isnan(special.airye(-1)[2:4]).any(), special.airye(-1))
+
+    def test_gh_7909(self):
+        assert_(special.kv(1.5, 0) == np.inf)
+        assert_(special.kve(1.5, 0) == np.inf)
+
+    def test_ticket_503(self):
+        """Real-valued Bessel I overflow"""
+        assert_allclose(special.iv(1, 700), 1.528500390233901e302)
+        assert_allclose(special.iv(1000, 1120), 1.301564549405821e301)
+
+    def test_iv_hyperg_poles(self):
+        assert_allclose(special.iv(-0.5, 1), 1.231200214592967)
+
+    def iv_series(self, v, z, n=200):
+        k = arange(0, n).astype(double)
+        r = (v+2*k)*log(.5*z) - special.gammaln(k+1) - special.gammaln(v+k+1)
+        r[isnan(r)] = inf
+        r = exp(r)
+        err = abs(r).max() * finfo(double).eps * n + abs(r[-1])*10
+        return r.sum(), err
+
+    def test_i0_series(self):
+        for z in [1., 10., 200.5]:
+            value, err = self.iv_series(0, z)
+            assert_allclose(special.i0(z), value, atol=err, err_msg=z)
+
+    def test_i1_series(self):
+        for z in [1., 10., 200.5]:
+            value, err = self.iv_series(1, z)
+            assert_allclose(special.i1(z), value, atol=err, err_msg=z)
+
+    def test_iv_series(self):
+        for v in [-20., -10., -1., 0., 1., 12.49, 120.]:
+            for z in [1., 10., 200.5, -1+2j]:
+                value, err = self.iv_series(v, z)
+                assert_allclose(special.iv(v, z), value, atol=err, err_msg=(v, z))
+
+    def test_i0(self):
+        values = [[0.0, 1.0],
+                  [1e-10, 1.0],
+                  [0.1, 0.9071009258],
+                  [0.5, 0.6450352706],
+                  [1.0, 0.4657596077],
+                  [2.5, 0.2700464416],
+                  [5.0, 0.1835408126],
+                  [20.0, 0.0897803119],
+                  ]
+        for i, (x, v) in enumerate(values):
+            cv = special.i0(x) * exp(-x)
+            assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)
+
+    def test_i0e(self):
+        oize = special.i0e(.1)
+        oizer = special.ive(0,.1)
+        assert_almost_equal(oize,oizer,8)
+
+    def test_i1(self):
+        values = [[0.0, 0.0],
+                  [1e-10, 0.4999999999500000e-10],
+                  [0.1, 0.0452984468],
+                  [0.5, 0.1564208032],
+                  [1.0, 0.2079104154],
+                  [5.0, 0.1639722669],
+                  [20.0, 0.0875062222],
+                  ]
+        for i, (x, v) in enumerate(values):
+            cv = special.i1(x) * exp(-x)
+            assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)
+
+    def test_i1e(self):
+        oi1e = special.i1e(.1)
+        oi1er = special.ive(1,.1)
+        assert_almost_equal(oi1e,oi1er,8)
+
+    def test_iti0k0(self):
+        iti0 = array(special.iti0k0(5))
+        assert_array_almost_equal(
+            iti0,
+            array([31.848667776169801, 1.5673873907283657]),
+            5,
+        )
+
+    def test_it2i0k0(self):
+        it2k = special.it2i0k0(.1)
+        assert_array_almost_equal(
+            it2k,
+            array([0.0012503906973464409, 3.3309450354686687]),
+            6,
+        )
+
+    def test_iv(self):
+        iv1 = special.iv(0,.1)*exp(-.1)
+        assert_almost_equal(iv1,0.90710092578230106,10)
+
+    def test_negv_ive(self):
+        assert_equal(special.ive(3,2), special.ive(-3,2))
+
+    def test_ive(self):
+        ive1 = special.ive(0,.1)
+        iv1 = special.iv(0,.1)*exp(-.1)
+        assert_almost_equal(ive1,iv1,10)
+
+    def test_ivp0(self):
+        assert_almost_equal(special.iv(1,2), special.ivp(0,2), 10)
+
+    def test_ivp(self):
+        y = (special.iv(0,2) + special.iv(2,2))/2
+        x = special.ivp(1,2)
+        assert_almost_equal(x,y,10)
+
+
+class TestLaguerre:
+    def test_laguerre(self):
+        lag0 = special.laguerre(0)
+        lag1 = special.laguerre(1)
+        lag2 = special.laguerre(2)
+        lag3 = special.laguerre(3)
+        lag4 = special.laguerre(4)
+        lag5 = special.laguerre(5)
+        assert_array_almost_equal(lag0.c,[1],13)
+        assert_array_almost_equal(lag1.c,[-1,1],13)
+        assert_array_almost_equal(lag2.c,array([1,-4,2])/2.0,13)
+        assert_array_almost_equal(lag3.c,array([-1,9,-18,6])/6.0,13)
+        assert_array_almost_equal(lag4.c,array([1,-16,72,-96,24])/24.0,13)
+        assert_array_almost_equal(lag5.c,array([-1,25,-200,600,-600,120])/120.0,13)
+
+    def test_genlaguerre(self):
+        k = 5*np.random.random() - 0.9
+        lag0 = special.genlaguerre(0,k)
+        lag1 = special.genlaguerre(1,k)
+        lag2 = special.genlaguerre(2,k)
+        lag3 = special.genlaguerre(3,k)
+        assert_equal(lag0.c, [1])
+        assert_equal(lag1.c, [-1, k + 1])
+        assert_almost_equal(
+            lag2.c,
+            array([1,-2*(k+2),(k+1.)*(k+2.)])/2.0
+        )
+        assert_almost_equal(
+            lag3.c,
+            array([-1,3*(k+3),-3*(k+2)*(k+3),(k+1)*(k+2)*(k+3)])/6.0
+        )
+
+
+class TestLambda:
+    def test_lmbda(self):
+        lam = special.lmbda(1,.1)
+        lamr = (
+            array([special.jn(0,.1), 2*special.jn(1,.1)/.1]),
+            array([special.jvp(0,.1), -2*special.jv(1,.1)/.01 + 2*special.jvp(1,.1)/.1])
+        )
+        assert_array_almost_equal(lam,lamr,8)
+
+
+class TestLog1p:
+    def test_log1p(self):
+        l1p = (special.log1p(10), special.log1p(11), special.log1p(12))
+        l1prl = (log(11), log(12), log(13))
+        assert_array_almost_equal(l1p,l1prl,8)
+
+    def test_log1pmore(self):
+        l1pm = (special.log1p(1), special.log1p(1.1), special.log1p(1.2))
+        l1pmrl = (log(2),log(2.1),log(2.2))
+        assert_array_almost_equal(l1pm,l1pmrl,8)
+
+
+class TestMathieu:
+
+    def test_mathieu_a(self):
+        pass
+
+    def test_mathieu_even_coef(self):
+        special.mathieu_even_coef(2,5)
+        # Q not defined broken and cannot figure out proper reporting order
+
+    def test_mathieu_odd_coef(self):
+        # same problem as above
+        pass
+
+
+class TestFresnelIntegral:
+
+    def test_modfresnelp(self):
+        pass
+
+    def test_modfresnelm(self):
+        pass
+
+
+class TestOblCvSeq:
+    def test_obl_cv_seq(self):
+        obl = special.obl_cv_seq(0,3,1)
+        assert_array_almost_equal(obl,array([-0.348602,
+                                              1.393206,
+                                              5.486800,
+                                              11.492120]),5)
+
+
+class TestParabolicCylinder:
+    def test_pbdn_seq(self):
+        pb = special.pbdn_seq(1,.1)
+        assert_array_almost_equal(pb,(array([0.9975,
+                                              0.0998]),
+                                      array([-0.0499,
+                                             0.9925])),4)
+
+    def test_pbdv(self):
+        special.pbdv(1,.2)
+        1/2*(.2)*special.pbdv(1,.2)[0] - special.pbdv(0,.2)[0]
+
+    def test_pbdv_seq(self):
+        pbn = special.pbdn_seq(1,.1)
+        pbv = special.pbdv_seq(1,.1)
+        assert_array_almost_equal(pbv,(real(pbn[0]),real(pbn[1])),4)
+
+    def test_pbdv_points(self):
+        # simple case
+        eta = np.linspace(-10, 10, 5)
+        z = 2**(eta/2)*np.sqrt(np.pi)*special.rgamma(.5-.5*eta)
+        assert_allclose(special.pbdv(eta, 0.)[0], z, rtol=1e-14, atol=1e-14)
+
+        # some points
+        assert_allclose(special.pbdv(10.34, 20.44)[0], 1.3731383034455e-32, rtol=1e-12)
+        assert_allclose(special.pbdv(-9.53, 3.44)[0], 3.166735001119246e-8, rtol=1e-12)
+
+    def test_pbdv_gradient(self):
+        x = np.linspace(-4, 4, 8)[:,None]
+        eta = np.linspace(-10, 10, 5)[None,:]
+
+        p = special.pbdv(eta, x)
+        eps = 1e-7 + 1e-7*abs(x)
+        dp = (special.pbdv(eta, x + eps)[0] - special.pbdv(eta, x - eps)[0]) / eps / 2.
+        assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6)
+
+    def test_pbvv_gradient(self):
+        x = np.linspace(-4, 4, 8)[:,None]
+        eta = np.linspace(-10, 10, 5)[None,:]
+
+        p = special.pbvv(eta, x)
+        eps = 1e-7 + 1e-7*abs(x)
+        dp = (special.pbvv(eta, x + eps)[0] - special.pbvv(eta, x - eps)[0]) / eps / 2.
+        assert_allclose(p[1], dp, rtol=1e-6, atol=1e-6)
+
+    def test_pbvv_seq(self):
+        res1, res2 = special.pbvv_seq(2, 3)
+        assert_allclose(res1, np.array([2.976319645712036,
+                                        1.358840996329579,
+                                        0.5501016716383508]))
+        assert_allclose(res2, np.array([3.105638472238475,
+                                        0.9380581512176672,
+                                        0.533688488872053]))
+
+
+class TestPolygamma:
+    # from Table 6.2 (pg. 271) of A&S
+    def test_polygamma(self):
+        poly2 = special.polygamma(2,1)
+        poly3 = special.polygamma(3,1)
+        assert_almost_equal(poly2,-2.4041138063,10)
+        assert_almost_equal(poly3,6.4939394023,10)
+
+        # Test polygamma(0, x) == psi(x)
+        x = [2, 3, 1.1e14]
+        assert_almost_equal(special.polygamma(0, x), special.psi(x))
+
+        # Test broadcasting
+        n = [0, 1, 2]
+        x = [0.5, 1.5, 2.5]
+        expected = [-1.9635100260214238, 0.93480220054467933,
+                    -0.23620405164172739]
+        assert_almost_equal(special.polygamma(n, x), expected)
+        expected = np.vstack([expected]*2)
+        assert_almost_equal(special.polygamma(n, np.vstack([x]*2)),
+                            expected)
+        assert_almost_equal(special.polygamma(np.vstack([n]*2), x),
+                            expected)
+
+
+class TestProCvSeq:
+    def test_pro_cv_seq(self):
+        prol = special.pro_cv_seq(0,3,1)
+        assert_array_almost_equal(prol,array([0.319000,
+                                               2.593084,
+                                               6.533471,
+                                               12.514462]),5)
+
+
+class TestPsi:
+    def test_psi(self):
+        ps = special.psi(1)
+        assert_almost_equal(ps,-0.57721566490153287,8)
+
+
+class TestRadian:
+    def test_radian(self):
+        rad = special.radian(90,0,0)
+        assert_almost_equal(rad,pi/2.0,5)
+
+    def test_radianmore(self):
+        rad1 = special.radian(90,1,60)
+        assert_almost_equal(rad1,pi/2+0.0005816135199345904,5)
+
+
+class TestRiccati:
+    def test_riccati_jn(self):
+        N, x = 2, 0.2
+        S = np.empty((N, N))
+        for n in range(N):
+            j = special.spherical_jn(n, x)
+            jp = special.spherical_jn(n, x, derivative=True)
+            S[0,n] = x*j
+            S[1,n] = x*jp + j
+        assert_array_almost_equal(S, special.riccati_jn(n, x), 8)
+
+    def test_riccati_yn(self):
+        N, x = 2, 0.2
+        C = np.empty((N, N))
+        for n in range(N):
+            y = special.spherical_yn(n, x)
+            yp = special.spherical_yn(n, x, derivative=True)
+            C[0,n] = x*y
+            C[1,n] = x*yp + y
+        assert_array_almost_equal(C, special.riccati_yn(n, x), 8)
+
+
+class TestSoftplus:
+    def test_softplus(self):
+        # Test cases for the softplus function. Selected based on Eq.(10) of:
+        # Mächler, M. (2012). log1mexp-note.pdf. Rmpfr: R MPFR - Multiple Precision
+        # Floating-Point Reliable. Retrieved from:
+        # https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf
+        # Reference values computed with `mpmath`
+        import numpy as np
+        rng = np.random.default_rng(3298432985245)
+        n = 3
+        a1 = rng.uniform(-100, -37, size=n)
+        a2 = rng.uniform(-37, 18, size=n)
+        a3 = rng.uniform(18, 33.3, size=n)
+        a4 = rng.uniform(33.33, 100, size=n)
+        a = np.stack([a1, a2, a3, a4])
+
+        # from mpmath import mp
+        # mp.dps = 100
+        # @np.vectorize
+        # def softplus(x):
+        #     return float(mp.log(mp.one + mp.exp(x)))
+        # softplus(a).tolist()
+        ref = [[1.692721323272333e-42, 7.42673911145206e-41, 8.504608846033205e-35],
+               [1.8425343736349797, 9.488245799395577e-15, 7.225195764021444e-08],
+               [31.253760266045106, 27.758244090327832, 29.995959179643634],
+               [73.26040086468937, 76.24944728617226, 37.83955519155184]]
+
+        res = softplus(a)
+        assert_allclose(res, ref, rtol=2e-15)
+
+    def test_softplus_with_kwargs(self):
+        x = np.arange(5) - 2
+        out = np.ones(5)
+        ref = out.copy()
+        where = x > 0
+
+        softplus(x, out=out, where=where)
+        ref[where] = softplus(x[where])
+        assert_allclose(out, ref)
+
+
+class TestRound:
+    def test_round(self):
+        rnd = list(map(int, (special.round(10.1),
+                             special.round(10.4),
+                             special.round(10.5),
+                             special.round(10.6))))
+
+        # Note: According to the documentation, scipy.special.round is
+        # supposed to round to the nearest even number if the fractional
+        # part is exactly 0.5. On some platforms, this does not appear
+        # to work and thus this test may fail. However, this unit test is
+        # correctly written.
+        rndrl = (10,10,10,11)
+        assert_array_equal(rnd,rndrl)
+
+# sph_harm is deprecated and is implemented as a shim around sph_harm_y.
+# The following two tests are maintained to verify the correctness of the shim.
+
+def test_sph_harm():
+    # Tests derived from tables in
+    # https://en.wikipedia.org/wiki/Table_of_spherical_harmonics
+    sh = special.sph_harm
+    pi = np.pi
+    exp = np.exp
+    sqrt = np.sqrt
+    sin = np.sin
+    cos = np.cos
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        assert_array_almost_equal(sh(0,0,0,0),
+               0.5/sqrt(pi))
+        assert_array_almost_equal(sh(-2,2,0.,pi/4),
+               0.25*sqrt(15./(2.*pi)) *
+               (sin(pi/4))**2.)
+        assert_array_almost_equal(sh(-2,2,0.,pi/2),
+               0.25*sqrt(15./(2.*pi)))
+        assert_array_almost_equal(sh(2,2,pi,pi/2),
+               0.25*sqrt(15/(2.*pi)) *
+               exp(0+2.*pi*1j)*sin(pi/2.)**2.)
+        assert_array_almost_equal(sh(2,4,pi/4.,pi/3.),
+               (3./8.)*sqrt(5./(2.*pi)) *
+               exp(0+2.*pi/4.*1j) *
+               sin(pi/3.)**2. *
+               (7.*cos(pi/3.)**2.-1))
+        assert_array_almost_equal(sh(4,4,pi/8.,pi/6.),
+               (3./16.)*sqrt(35./(2.*pi)) *
+               exp(0+4.*pi/8.*1j)*sin(pi/6.)**4.)
+
+
+def test_sph_harm_ufunc_loop_selection():
+    # see https://github.com/scipy/scipy/issues/4895
+    dt = np.dtype(np.complex128)
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        assert_equal(special.sph_harm(0, 0, 0, 0).dtype, dt)
+        assert_equal(special.sph_harm([0], 0, 0, 0).dtype, dt)
+        assert_equal(special.sph_harm(0, [0], 0, 0).dtype, dt)
+        assert_equal(special.sph_harm(0, 0, [0], 0).dtype, dt)
+        assert_equal(special.sph_harm(0, 0, 0, [0]).dtype, dt)
+        assert_equal(special.sph_harm([0], [0], [0], [0]).dtype, dt)
+
+
+class TestStruve:
+    def _series(self, v, z, n=100):
+        """Compute Struve function & error estimate from its power series."""
+        k = arange(0, n)
+        r = (-1)**k * (.5*z)**(2*k+v+1)/special.gamma(k+1.5)/special.gamma(k+v+1.5)
+        err = abs(r).max() * finfo(double).eps * n
+        return r.sum(), err
+
+    def test_vs_series(self):
+        """Check Struve function versus its power series"""
+        for v in [-20, -10, -7.99, -3.4, -1, 0, 1, 3.4, 12.49, 16]:
+            for z in [1, 10, 19, 21, 30]:
+                value, err = self._series(v, z)
+                assert_allclose(special.struve(v, z), value, rtol=0, atol=err), (v, z)
+
+    def test_some_values(self):
+        assert_allclose(special.struve(-7.99, 21), 0.0467547614113, rtol=1e-7)
+        assert_allclose(special.struve(-8.01, 21), 0.0398716951023, rtol=1e-8)
+        assert_allclose(special.struve(-3.0, 200), 0.0142134427432, rtol=1e-12)
+        assert_allclose(special.struve(-8.0, -41), 0.0192469727846, rtol=1e-11)
+        assert_equal(special.struve(-12, -41), -special.struve(-12, 41))
+        assert_equal(special.struve(+12, -41), -special.struve(+12, 41))
+        assert_equal(special.struve(-11, -41), +special.struve(-11, 41))
+        assert_equal(special.struve(+11, -41), +special.struve(+11, 41))
+
+        assert_(isnan(special.struve(-7.1, -1)))
+        assert_(isnan(special.struve(-10.1, -1)))
+
+    def test_regression_679(self):
+        """Regression test for #679"""
+        assert_allclose(special.struve(-1.0, 20 - 1e-8),
+                        special.struve(-1.0, 20 + 1e-8))
+        assert_allclose(special.struve(-2.0, 20 - 1e-8),
+                        special.struve(-2.0, 20 + 1e-8))
+        assert_allclose(special.struve(-4.3, 20 - 1e-8),
+                        special.struve(-4.3, 20 + 1e-8))
+
+
+def test_chi2_smalldf():
+    assert_almost_equal(special.chdtr(0.6,3), 0.957890536704110)
+
+
+def test_ch2_inf():
+    assert_equal(special.chdtr(0.7,np.inf), 1.0)
+
+
+def test_chi2c_smalldf():
+    assert_almost_equal(special.chdtrc(0.6,3), 1-0.957890536704110)
+
+
+def test_chi2_inv_smalldf():
+    assert_almost_equal(special.chdtri(0.6,1-0.957890536704110), 3)
+
+
+def test_agm_simple():
+    rtol = 1e-13
+
+    # Gauss's constant
+    assert_allclose(1/special.agm(1, np.sqrt(2)), 0.834626841674073186,
+                    rtol=rtol)
+
+    # These values were computed using Wolfram Alpha, with the
+    # function ArithmeticGeometricMean[a, b].
+    agm13 = 1.863616783244897
+    agm15 = 2.604008190530940
+    agm35 = 3.936235503649555
+    assert_allclose(special.agm([[1], [3]], [1, 3, 5]),
+                    [[1, agm13, agm15],
+                     [agm13, 3, agm35]], rtol=rtol)
+
+    # Computed by the iteration formula using mpmath,
+    # with mpmath.mp.prec = 1000:
+    agm12 = 1.4567910310469068
+    assert_allclose(special.agm(1, 2), agm12, rtol=rtol)
+    assert_allclose(special.agm(2, 1), agm12, rtol=rtol)
+    assert_allclose(special.agm(-1, -2), -agm12, rtol=rtol)
+    assert_allclose(special.agm(24, 6), 13.458171481725614, rtol=rtol)
+    assert_allclose(special.agm(13, 123456789.5), 11111458.498599306,
+                    rtol=rtol)
+    assert_allclose(special.agm(1e30, 1), 2.229223055945383e+28, rtol=rtol)
+    assert_allclose(special.agm(1e-22, 1), 0.030182566420169886, rtol=rtol)
+    assert_allclose(special.agm(1e150, 1e180), 2.229223055945383e+178,
+                    rtol=rtol)
+    assert_allclose(special.agm(1e180, 1e-150), 2.0634722510162677e+177,
+                    rtol=rtol)
+    assert_allclose(special.agm(1e-150, 1e-170), 3.3112619670463756e-152,
+                    rtol=rtol)
+    fi = np.finfo(1.0)
+    assert_allclose(special.agm(fi.tiny, fi.max), 1.9892072050015473e+305,
+                    rtol=rtol)
+    assert_allclose(special.agm(0.75*fi.max, fi.max), 1.564904312298045e+308,
+                    rtol=rtol)
+    assert_allclose(special.agm(fi.tiny, 3*fi.tiny), 4.1466849866735005e-308,
+                    rtol=rtol)
+
+    # zero, nan and inf cases.
+    assert_equal(special.agm(0, 0), 0)
+    assert_equal(special.agm(99, 0), 0)
+
+    assert_equal(special.agm(-1, 10), np.nan)
+    assert_equal(special.agm(0, np.inf), np.nan)
+    assert_equal(special.agm(np.inf, 0), np.nan)
+    assert_equal(special.agm(0, -np.inf), np.nan)
+    assert_equal(special.agm(-np.inf, 0), np.nan)
+    assert_equal(special.agm(np.inf, -np.inf), np.nan)
+    assert_equal(special.agm(-np.inf, np.inf), np.nan)
+    assert_equal(special.agm(1, np.nan), np.nan)
+    assert_equal(special.agm(np.nan, -1), np.nan)
+
+    assert_equal(special.agm(1, np.inf), np.inf)
+    assert_equal(special.agm(np.inf, 1), np.inf)
+    assert_equal(special.agm(-1, -np.inf), -np.inf)
+    assert_equal(special.agm(-np.inf, -1), -np.inf)
+
+
+def test_legacy():
+    # Legacy behavior: truncating arguments to integers
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning, "floating point number truncated to an integer")
+        assert_equal(special.expn(1, 0.3), special.expn(1.8, 0.3))
+        assert_equal(special.nbdtrc(1, 2, 0.3), special.nbdtrc(1.8, 2.8, 0.3))
+        assert_equal(special.nbdtr(1, 2, 0.3), special.nbdtr(1.8, 2.8, 0.3))
+        assert_equal(special.nbdtri(1, 2, 0.3), special.nbdtri(1.8, 2.8, 0.3))
+        assert_equal(special.pdtri(1, 0.3), special.pdtri(1.8, 0.3))
+        assert_equal(special.kn(1, 0.3), special.kn(1.8, 0.3))
+        assert_equal(special.yn(1, 0.3), special.yn(1.8, 0.3))
+        assert_equal(special.smirnov(1, 0.3), special.smirnov(1.8, 0.3))
+        assert_equal(special.smirnovi(1, 0.3), special.smirnovi(1.8, 0.3))
+
+
+# This lock can be removed once errstate is made thread-safe (see gh-21956)
+@pytest.fixture
+def errstate_lock():
+    import threading
+    return threading.Lock()
+
+
+@with_special_errors
+def test_error_raising(errstate_lock):
+    with errstate_lock:
+        with special.errstate(all='raise'):
+            assert_raises(special.SpecialFunctionError, special.iv, 1, 1e99j)
+
+
+def test_xlogy():
+    def xfunc(x, y):
+        with np.errstate(invalid='ignore'):
+            if x == 0 and not np.isnan(y):
+                return x
+            else:
+                return x*np.log(y)
+
+    z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0)], dtype=float)
+    z2 = np.r_[z1, [(0, 1j), (1, 1j)]]
+
+    w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1])
+    assert_func_equal(special.xlogy, w1, z1, rtol=1e-13, atol=1e-13)
+    w2 = np.vectorize(xfunc)(z2[:,0], z2[:,1])
+    assert_func_equal(special.xlogy, w2, z2, rtol=1e-13, atol=1e-13)
+
+
+def test_xlog1py():
+    def xfunc(x, y):
+        with np.errstate(invalid='ignore'):
+            if x == 0 and not np.isnan(y):
+                return x
+            else:
+                return x * np.log1p(y)
+
+    z1 = np.asarray([(0,0), (0, np.nan), (0, np.inf), (1.0, 2.0),
+                     (1, 1e-30)], dtype=float)
+    w1 = np.vectorize(xfunc)(z1[:,0], z1[:,1])
+    assert_func_equal(special.xlog1py, w1, z1, rtol=1e-13, atol=1e-13)
+
+
+def test_entr():
+    def xfunc(x):
+        if x < 0:
+            return -np.inf
+        else:
+            return -special.xlogy(x, x)
+    values = (0, 0.5, 1.0, np.inf)
+    signs = [-1, 1]
+    arr = []
+    for sgn, v in itertools.product(signs, values):
+        arr.append(sgn * v)
+    z = np.array(arr, dtype=float)
+    w = np.vectorize(xfunc, otypes=[np.float64])(z)
+    assert_func_equal(special.entr, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_kl_div():
+    def xfunc(x, y):
+        if x < 0 or y < 0 or (y == 0 and x != 0):
+            # extension of natural domain to preserve convexity
+            return np.inf
+        elif np.isposinf(x) or np.isposinf(y):
+            # limits within the natural domain
+            return np.inf
+        elif x == 0:
+            return y
+        else:
+            return special.xlogy(x, x/y) - x + y
+    values = (0, 0.5, 1.0)
+    signs = [-1, 1]
+    arr = []
+    for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values):
+        arr.append((sgna*va, sgnb*vb))
+    z = np.array(arr, dtype=float)
+    w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])
+    assert_func_equal(special.kl_div, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_rel_entr():
+    def xfunc(x, y):
+        if x > 0 and y > 0:
+            return special.xlogy(x, x/y)
+        elif x == 0 and y >= 0:
+            return 0
+        else:
+            return np.inf
+    values = (0, 0.5, 1.0)
+    signs = [-1, 1]
+    arr = []
+    for sgna, va, sgnb, vb in itertools.product(signs, values, signs, values):
+        arr.append((sgna*va, sgnb*vb))
+    z = np.array(arr, dtype=float)
+    w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])
+    assert_func_equal(special.rel_entr, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_rel_entr_gh_20710_near_zero():
+    # Check accuracy of inputs which are very close
+    inputs = np.array([
+        # x, y
+        (0.9456657713430001, 0.9456657713430094),
+        (0.48066098564791515, 0.48066098564794774),
+        (0.786048657854401, 0.7860486578542367),
+    ])
+    # Known values produced using `x * mpmath.log(x / y)` with dps=30
+    expected = [
+        -9.325873406851269e-15,
+        -3.258504577274724e-14,
+        1.6431300764454033e-13,
+    ]
+    x = inputs[:, 0]
+    y = inputs[:, 1]
+    assert_allclose(special.rel_entr(x, y), expected, rtol=1e-13, atol=0)
+
+
+def test_rel_entr_gh_20710_overflow():
+    special.seterr(all='ignore')
+    inputs = np.array([
+        # x, y
+        # Overflow
+        (4, 2.22e-308),
+        # Underflow
+        (1e-200, 1e+200),
+        # Subnormal
+        (2.22e-308, 1e15),
+    ])
+    # Known values produced using `x * mpmath.log(x / y)` with dps=30
+    expected = [
+        2839.139983229607,
+        -9.210340371976183e-198,
+        -1.6493212008074475e-305,
+    ]
+    x = inputs[:, 0]
+    y = inputs[:, 1]
+    assert_allclose(special.rel_entr(x, y), expected, rtol=1e-13, atol=0)
+
+
+def test_huber():
+    assert_equal(special.huber(-1, 1.5), np.inf)
+    assert_allclose(special.huber(2, 1.5), 0.5 * np.square(1.5))
+    assert_allclose(special.huber(2, 2.5), 2 * (2.5 - 0.5 * 2))
+
+    def xfunc(delta, r):
+        if delta < 0:
+            return np.inf
+        elif np.abs(r) < delta:
+            return 0.5 * np.square(r)
+        else:
+            return delta * (np.abs(r) - 0.5 * delta)
+
+    z = np.random.randn(10, 2)
+    w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])
+    assert_func_equal(special.huber, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_pseudo_huber():
+    def xfunc(delta, r):
+        if delta < 0:
+            return np.inf
+        elif (not delta) or (not r):
+            return 0
+        else:
+            return delta**2 * (np.sqrt(1 + (r/delta)**2) - 1)
+
+    z = np.array(np.random.randn(10, 2).tolist() + [[0, 0.5], [0.5, 0]])
+    w = np.vectorize(xfunc, otypes=[np.float64])(z[:,0], z[:,1])
+    assert_func_equal(special.pseudo_huber, w, z, rtol=1e-13, atol=1e-13)
+
+
+def test_pseudo_huber_small_r():
+    delta = 1.0
+    r = 1e-18
+    y = special.pseudo_huber(delta, r)
+    # expected computed with mpmath:
+    #     import mpmath
+    #     mpmath.mp.dps = 200
+    #     r = mpmath.mpf(1e-18)
+    #     expected = float(mpmath.sqrt(1 + r**2) - 1)
+    expected = 5.0000000000000005e-37
+    assert_allclose(y, expected, rtol=1e-13)
+
+
+@pytest.mark.thread_unsafe
+def test_runtime_warning():
+    with pytest.warns(RuntimeWarning,
+                      match=r'Too many predicted coefficients'):
+        mathieu_odd_coef(1000, 1000)
+    with pytest.warns(RuntimeWarning,
+                      match=r'Too many predicted coefficients'):
+        mathieu_even_coef(1000, 1000)
+
+
+class TestStirling2:
+    table = [
+        [1],
+        [0, 1],
+        [0, 1, 1],
+        [0, 1, 3, 1],
+        [0, 1, 7, 6, 1],
+        [0, 1, 15, 25, 10, 1],
+        [0, 1, 31, 90, 65, 15, 1],
+        [0, 1, 63, 301, 350, 140, 21, 1],
+        [0, 1, 127, 966, 1701, 1050, 266, 28, 1],
+        [0, 1, 255, 3025, 7770, 6951, 2646, 462, 36, 1],
+        [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1],
+    ]
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-12})
+    ])
+    def test_table_cases(self, is_exact, comp, kwargs):
+        for n in range(1, len(self.table)):
+            k_values = list(range(n+1))
+            row = self.table[n]
+            comp(row, stirling2([n], k_values, exact=is_exact), **kwargs)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-12})
+    ])
+    def test_valid_single_integer(self, is_exact, comp, kwargs):
+        comp(stirling2(0, 0, exact=is_exact), self.table[0][0], **kwargs)
+        comp(stirling2(4, 2, exact=is_exact), self.table[4][2], **kwargs)
+        # a single 2-tuple of integers as arguments must return an int and not
+        # an array whereas arrays of single values should return array
+        comp(stirling2(5, 3, exact=is_exact), 25, **kwargs)
+        comp(stirling2([5], [3], exact=is_exact), [25], **kwargs)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-12})
+    ])
+    def test_negative_integer(self, is_exact, comp, kwargs):
+        # negative integers for n or k arguments return 0
+        comp(stirling2(-1, -1, exact=is_exact), 0, **kwargs)
+        comp(stirling2(-1, 2, exact=is_exact), 0, **kwargs)
+        comp(stirling2(2, -1, exact=is_exact), 0, **kwargs)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-12})
+    ])
+    def test_array_inputs(self, is_exact, comp, kwargs):
+        ans = [self.table[10][3], self.table[10][4]]
+        comp(stirling2(asarray([10, 10]),
+                               asarray([3, 4]),
+                               exact=is_exact),
+                     ans)
+        comp(stirling2([10, 10],
+                               asarray([3, 4]),
+                               exact=is_exact),
+                     ans)
+        comp(stirling2(asarray([10, 10]),
+                               [3, 4],
+                               exact=is_exact),
+                     ans)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-13})
+    ])
+    def test_mixed_values(self, is_exact, comp, kwargs):
+        # negative values-of either n or k-should return 0 for the entry
+        ans = [0, 1, 3, 25, 1050, 5880, 9330]
+        n = [-1, 0, 3, 5, 8, 10, 10]
+        k = [-2, 0, 2, 3, 5, 7, 3]
+        comp(stirling2(n, k, exact=is_exact), ans, **kwargs)
+
+    def test_correct_parity(self):
+        """Test parity follows well known identity.
+
+        en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind#Parity
+        """
+        n, K = 100, np.arange(101)
+        assert_equal(
+            stirling2(n, K, exact=True) % 2,
+            [math.comb(n - (k // 2) - 1, n - k) % 2 for k in K],
+        )
+
+    def test_big_numbers(self):
+        # via mpmath (bigger than 32bit)
+        ans = asarray([48063331393110, 48004081105038305])
+        n = [25, 30]
+        k = [17, 4]
+        assert array_equal(stirling2(n, k, exact=True), ans)
+        # bigger than 64 bit
+        ans = asarray([2801934359500572414253157841233849412,
+                       14245032222277144547280648984426251])
+        n = [42, 43]
+        k = [17, 23]
+        assert array_equal(stirling2(n, k, exact=True), ans)
+
+    @pytest.mark.parametrize("N", [4.5, 3., 4+1j, "12", np.nan])
+    @pytest.mark.parametrize("K", [3.5, 3, "2", None])
+    @pytest.mark.parametrize("is_exact", [True, False])
+    def test_unsupported_input_types(self, N, K, is_exact):
+        # object, float, string, complex are not supported and raise TypeError
+        with pytest.raises(TypeError):
+            stirling2(N, K, exact=is_exact)
+
+    @pytest.mark.parametrize("is_exact", [True, False])
+    def test_numpy_array_int_object_dtype(self, is_exact):
+        # python integers with arbitrary precision are *not* allowed as
+        # object type in numpy arrays are inconsistent from api perspective
+        ans = asarray(self.table[4][1:])
+        n = asarray([4, 4, 4, 4], dtype=object)
+        k = asarray([1, 2, 3, 4], dtype=object)
+        with pytest.raises(TypeError):
+            array_equal(stirling2(n, k, exact=is_exact), ans)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-13})
+    ])
+    def test_numpy_array_unsigned_int_dtype(self, is_exact, comp, kwargs):
+        # numpy unsigned integers are allowed as dtype in numpy arrays
+        ans = asarray(self.table[4][1:])
+        n = asarray([4, 4, 4, 4], dtype=np_ulong)
+        k = asarray([1, 2, 3, 4], dtype=np_ulong)
+        comp(stirling2(n, k, exact=False), ans, **kwargs)
+
+    @pytest.mark.parametrize("is_exact, comp, kwargs", [
+        (True, assert_equal, {}),
+        (False, assert_allclose, {'rtol': 1e-13})
+    ])
+    def test_broadcasting_arrays_correctly(self, is_exact, comp, kwargs):
+        # broadcasting is handled by stirling2
+        # test leading 1s are replicated
+        ans = asarray([[1, 15, 25, 10], [1, 7, 6, 1]])  # shape (2,4)
+        n = asarray([[5, 5, 5, 5], [4, 4, 4, 4]])  # shape (2,4)
+        k = asarray([1, 2, 3, 4])  # shape (4,)
+        comp(stirling2(n, k, exact=is_exact), ans, **kwargs)
+        # test that dims both mismatch broadcast correctly (5,1) & (6,)
+        n = asarray([[4], [4], [4], [4], [4]])
+        k = asarray([0, 1, 2, 3, 4, 5])
+        ans = asarray([[0, 1, 7, 6, 1, 0] for _ in range(5)])
+        comp(stirling2(n, k, exact=False), ans, **kwargs)
+
+    def test_temme_rel_max_error(self):
+        # python integers with arbitrary precision are *not* allowed as
+        # object type in numpy arrays are inconsistent from api perspective
+        x = list(range(51, 101, 5))
+        for n in x:
+            k_entries = list(range(1, n+1))
+            denom = stirling2([n], k_entries, exact=True)
+            num = denom - stirling2([n], k_entries, exact=False)
+            assert np.max(np.abs(num / denom)) < 2e-5
+
+
+class TestLegendreDeprecation:
+
+    def test_warn_lpn(self):
+        msg = "`scipy.special.lpn` is deprecated..."
+        with pytest.deprecated_call(match=msg):
+            _ = lpn(1, 0)
+
+    @pytest.mark.parametrize("xlpmn", [lpmn, clpmn])
+    def test_warn_xlpmn(self, xlpmn):
+        message = f"`scipy.special.{xlpmn.__name__}` is deprecated..."
+        with pytest.deprecated_call(match=message):
+            _ = xlpmn(1, 1, 0)
+
+    def test_warn_sph_harm(self):
+        msg = "`scipy.special.sph_harm` is deprecated..."
+        with pytest.deprecated_call(match=msg):
+            _ = special.sph_harm(1, 1, 0, 0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py
new file mode 100644
index 0000000000000000000000000000000000000000..57694becc49b2028f17eac819b80a225ac010795
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_bdtr.py
@@ -0,0 +1,112 @@
+import numpy as np
+import scipy.special as sc
+import pytest
+from numpy.testing import assert_allclose, assert_array_equal, suppress_warnings
+
+
+class TestBdtr:
+    def test(self):
+        val = sc.bdtr(0, 1, 0.5)
+        assert_allclose(val, 0.5)
+
+    def test_sum_is_one(self):
+        val = sc.bdtr([0, 1, 2], 2, 0.5)
+        assert_array_equal(val, [0.25, 0.75, 1.0])
+
+    def test_rounding(self):
+        double_val = sc.bdtr([0.1, 1.1, 2.1], 2, 0.5)
+        int_val = sc.bdtr([0, 1, 2], 2, 0.5)
+        assert_array_equal(double_val, int_val)
+
+    @pytest.mark.parametrize('k, n, p', [
+        (np.inf, 2, 0.5),
+        (1.0, np.inf, 0.5),
+        (1.0, 2, np.inf)
+    ])
+    def test_inf(self, k, n, p):
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning)
+            val = sc.bdtr(k, n, p)
+        assert np.isnan(val)
+
+    def test_domain(self):
+        val = sc.bdtr(-1.1, 1, 0.5)
+        assert np.isnan(val)
+
+
+class TestBdtrc:
+    def test_value(self):
+        val = sc.bdtrc(0, 1, 0.5)
+        assert_allclose(val, 0.5)
+
+    def test_sum_is_one(self):
+        val = sc.bdtrc([0, 1, 2], 2, 0.5)
+        assert_array_equal(val, [0.75, 0.25, 0.0])
+
+    def test_rounding(self):
+        double_val = sc.bdtrc([0.1, 1.1, 2.1], 2, 0.5)
+        int_val = sc.bdtrc([0, 1, 2], 2, 0.5)
+        assert_array_equal(double_val, int_val)
+
+    @pytest.mark.parametrize('k, n, p', [
+        (np.inf, 2, 0.5),
+        (1.0, np.inf, 0.5),
+        (1.0, 2, np.inf)
+    ])
+    def test_inf(self, k, n, p):
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning)
+            val = sc.bdtrc(k, n, p)
+        assert np.isnan(val)
+
+    def test_domain(self):
+        val = sc.bdtrc(-1.1, 1, 0.5)
+        val2 = sc.bdtrc(2.1, 1, 0.5)
+        assert np.isnan(val2)
+        assert_allclose(val, 1.0)
+
+    def test_bdtr_bdtrc_sum_to_one(self):
+        bdtr_vals = sc.bdtr([0, 1, 2], 2, 0.5)
+        bdtrc_vals = sc.bdtrc([0, 1, 2], 2, 0.5)
+        vals = bdtr_vals + bdtrc_vals
+        assert_allclose(vals, [1.0, 1.0, 1.0])
+
+
+class TestBdtri:
+    def test_value(self):
+        val = sc.bdtri(0, 1, 0.5)
+        assert_allclose(val, 0.5)
+
+    def test_sum_is_one(self):
+        val = sc.bdtri([0, 1], 2, 0.5)
+        actual = np.asarray([1 - 1/np.sqrt(2), 1/np.sqrt(2)])
+        assert_allclose(val, actual)
+
+    def test_rounding(self):
+        double_val = sc.bdtri([0.1, 1.1], 2, 0.5)
+        int_val = sc.bdtri([0, 1], 2, 0.5)
+        assert_allclose(double_val, int_val)
+
+    @pytest.mark.parametrize('k, n, p', [
+        (np.inf, 2, 0.5),
+        (1.0, np.inf, 0.5),
+        (1.0, 2, np.inf)
+    ])
+    def test_inf(self, k, n, p):
+        with suppress_warnings() as sup:
+            sup.filter(DeprecationWarning)
+            val = sc.bdtri(k, n, p)
+        assert np.isnan(val)
+
+    @pytest.mark.parametrize('k, n, p', [
+        (-1.1, 1, 0.5),
+        (2.1, 1, 0.5)
+    ])
+    def test_domain(self, k, n, p):
+        val = sc.bdtri(k, n, p)
+        assert np.isnan(val)
+
+    def test_bdtr_bdtri_roundtrip(self):
+        bdtr_vals = sc.bdtr([0, 1, 2], 2, 0.5)
+        roundtrip_vals = sc.bdtri([0, 1, 2], 2, bdtr_vals)
+        assert_allclose(roundtrip_vals, [0.5, 0.5, np.nan])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..132fb9ab11ec19d8efa00c5bb96f851795017d31
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boost_ufuncs.py
@@ -0,0 +1,61 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.special._ufuncs as scu
+from scipy.integrate import tanhsinh
+
+
+type_char_to_type_tol = {'f': (np.float32, 32*np.finfo(np.float32).eps),
+                         'd': (np.float64, 32*np.finfo(np.float64).eps)}
+
+
+# Each item in this list is
+#   (func, args, expected_value)
+# All the values can be represented exactly, even with np.float32.
+#
+# This is not an exhaustive test data set of all the functions!
+# It is a spot check of several functions, primarily for
+# checking that the different data types are handled correctly.
+test_data = [
+    (scu._beta_pdf, (0.5, 2, 3), 1.5),
+    (scu._beta_pdf, (0, 1, 5), 5.0),
+    (scu._beta_pdf, (1, 5, 1), 5.0),
+    (scu._beta_ppf, (0.5, 5., 5.), 0.5),  # gh-21303
+    (scu._binom_cdf, (1, 3, 0.5), 0.5),
+    (scu._binom_pmf, (1, 4, 0.5), 0.25),
+    (scu._hypergeom_cdf, (2, 3, 5, 6), 0.5),
+    (scu._nbinom_cdf, (1, 4, 0.25), 0.015625),
+    (scu._ncf_mean, (10, 12, 2.5), 1.5),
+]
+
+
+@pytest.mark.parametrize('func, args, expected', test_data)
+def test_stats_boost_ufunc(func, args, expected):
+    type_sigs = func.types
+    type_chars = [sig.split('->')[-1] for sig in type_sigs]
+    for type_char in type_chars:
+        typ, rtol = type_char_to_type_tol[type_char]
+        args = [typ(arg) for arg in args]
+        # Harmless overflow warnings are a "feature" of some wrappers on some
+        # platforms. This test is about dtype and accuracy, so let's avoid false
+        # test failures cause by these warnings. See gh-17432.
+        with np.errstate(over='ignore'):
+            value = func(*args)
+        assert isinstance(value, typ)
+        assert_allclose(value, expected, rtol=rtol)
+
+
+def test_landau():
+    # Test that Landau distribution ufuncs are wrapped as expected;
+    # accuracy is tested by Boost.
+    x = np.linspace(-3, 10, 10)
+    args = (0, 1)
+    res = tanhsinh(lambda x: scu._landau_pdf(x, *args), -np.inf, x)
+    cdf = scu._landau_cdf(x, *args)
+    assert_allclose(res.integral, cdf)
+    sf = scu._landau_sf(x, *args)
+    assert_allclose(sf, 1-cdf)
+    ppf = scu._landau_ppf(cdf, *args)
+    assert_allclose(ppf, x)
+    isf = scu._landau_isf(sf, *args)
+    assert_allclose(isf, x, rtol=1e-6)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py
new file mode 100644
index 0000000000000000000000000000000000000000..25d76d0560a6a9fe416f750213662b5f7fb22f25
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_boxcox.py
@@ -0,0 +1,125 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_almost_equal, assert_allclose
+from scipy.special import boxcox, boxcox1p, inv_boxcox, inv_boxcox1p
+import pytest
+
+
+# There are more tests of boxcox and boxcox1p in test_mpmath.py.
+
+def test_boxcox_basic():
+    x = np.array([0.5, 1, 2, 4])
+
+    # lambda = 0  =>  y = log(x)
+    y = boxcox(x, 0)
+    assert_almost_equal(y, np.log(x))
+
+    # lambda = 1  =>  y = x - 1
+    y = boxcox(x, 1)
+    assert_almost_equal(y, x - 1)
+
+    # lambda = 2  =>  y = 0.5*(x**2 - 1)
+    y = boxcox(x, 2)
+    assert_almost_equal(y, 0.5*(x**2 - 1))
+
+    # x = 0 and lambda > 0  =>  y = -1 / lambda
+    lam = np.array([0.5, 1, 2])
+    y = boxcox(0, lam)
+    assert_almost_equal(y, -1.0 / lam)
+
+def test_boxcox_underflow():
+    x = 1 + 1e-15
+    lmbda = 1e-306
+    y = boxcox(x, lmbda)
+    assert_allclose(y, np.log(x), rtol=1e-14)
+
+
+def test_boxcox_nonfinite():
+    # x < 0  =>  y = nan
+    x = np.array([-1, -1, -0.5])
+    y = boxcox(x, [0.5, 2.0, -1.5])
+    assert_equal(y, np.array([np.nan, np.nan, np.nan]))
+
+    # x = 0 and lambda <= 0  =>  y = -inf
+    x = 0
+    y = boxcox(x, [-2.5, 0])
+    assert_equal(y, np.array([-np.inf, -np.inf]))
+
+
+def test_boxcox1p_basic():
+    x = np.array([-0.25, -1e-20, 0, 1e-20, 0.25, 1, 3])
+
+    # lambda = 0  =>  y = log(1+x)
+    y = boxcox1p(x, 0)
+    assert_almost_equal(y, np.log1p(x))
+
+    # lambda = 1  =>  y = x
+    y = boxcox1p(x, 1)
+    assert_almost_equal(y, x)
+
+    # lambda = 2  =>  y = 0.5*((1+x)**2 - 1) = 0.5*x*(2 + x)
+    y = boxcox1p(x, 2)
+    assert_almost_equal(y, 0.5*x*(2 + x))
+
+    # x = -1 and lambda > 0  =>  y = -1 / lambda
+    lam = np.array([0.5, 1, 2])
+    y = boxcox1p(-1, lam)
+    assert_almost_equal(y, -1.0 / lam)
+
+
+def test_boxcox1p_underflow():
+    x = np.array([1e-15, 1e-306])
+    lmbda = np.array([1e-306, 1e-18])
+    y = boxcox1p(x, lmbda)
+    assert_allclose(y, np.log1p(x), rtol=1e-14)
+
+
+def test_boxcox1p_nonfinite():
+    # x < -1  =>  y = nan
+    x = np.array([-2, -2, -1.5])
+    y = boxcox1p(x, [0.5, 2.0, -1.5])
+    assert_equal(y, np.array([np.nan, np.nan, np.nan]))
+
+    # x = -1 and lambda <= 0  =>  y = -inf
+    x = -1
+    y = boxcox1p(x, [-2.5, 0])
+    assert_equal(y, np.array([-np.inf, -np.inf]))
+
+
+def test_inv_boxcox():
+    x = np.array([0., 1., 2.])
+    lam = np.array([0., 1., 2.])
+    y = boxcox(x, lam)
+    x2 = inv_boxcox(y, lam)
+    assert_almost_equal(x, x2)
+
+    x = np.array([0., 1., 2.])
+    lam = np.array([0., 1., 2.])
+    y = boxcox1p(x, lam)
+    x2 = inv_boxcox1p(y, lam)
+    assert_almost_equal(x, x2)
+
+
+def test_inv_boxcox1p_underflow():
+    x = 1e-15
+    lam = 1e-306
+    y = inv_boxcox1p(x, lam)
+    assert_allclose(y, x, rtol=1e-14)
+
+
+@pytest.mark.parametrize(
+    "x, lmb",
+    [[100, 155],
+     [0.01, -155]]
+)
+def test_boxcox_premature_overflow(x, lmb):
+    # test boxcox & inv_boxcox
+    y = boxcox(x, lmb)
+    assert np.isfinite(y)
+    x_inv = inv_boxcox(y, lmb)
+    assert_allclose(x, x_inv)
+
+    # test boxcox1p & inv_boxcox1p
+    y1p = boxcox1p(x-1, lmb)
+    assert np.isfinite(y1p)
+    x1p_inv = inv_boxcox1p(y1p, lmb)
+    assert_allclose(x-1, x1p_inv)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8352182bdf657029ab9857411e1b41141fdc0a5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdflib.py
@@ -0,0 +1,688 @@
+"""
+Test cdflib functions versus mpmath, if available.
+
+The following functions still need tests:
+
+- ncfdtri
+- ncfdtridfn
+- ncfdtridfd
+- ncfdtrinc
+- nbdtrik
+- nbdtrin
+- pdtrik
+- nctdtrit
+- nctdtridf
+- nctdtrinc
+
+"""
+import itertools
+
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+import pytest
+
+import scipy.special as sp
+from scipy.special._testutils import (
+    MissingModule, check_version, FuncData)
+from scipy.special._mptestutils import (
+    Arg, IntArg, get_args, mpf2float, assert_mpmath_equal)
+
+try:
+    import mpmath
+except ImportError:
+    mpmath = MissingModule('mpmath')
+
+
+class ProbArg:
+    """Generate a set of probabilities on [0, 1]."""
+
+    def __init__(self):
+        # Include the endpoints for compatibility with Arg et. al.
+        self.a = 0
+        self.b = 1
+
+    def values(self, n):
+        """Return an array containing approximately n numbers."""
+        m = max(1, n//3)
+        v1 = np.logspace(-30, np.log10(0.3), m)
+        v2 = np.linspace(0.3, 0.7, m + 1, endpoint=False)[1:]
+        v3 = 1 - np.logspace(np.log10(0.3), -15, m)
+        v = np.r_[v1, v2, v3]
+        return np.unique(v)
+
+
+class EndpointFilter:
+    def __init__(self, a, b, rtol, atol):
+        self.a = a
+        self.b = b
+        self.rtol = rtol
+        self.atol = atol
+
+    def __call__(self, x):
+        mask1 = np.abs(x - self.a) < self.rtol*np.abs(self.a) + self.atol
+        mask2 = np.abs(x - self.b) < self.rtol*np.abs(self.b) + self.atol
+        return np.where(mask1 | mask2, False, True)
+
+
+class _CDFData:
+    def __init__(self, spfunc, mpfunc, index, argspec, spfunc_first=True,
+                 dps=20, n=5000, rtol=None, atol=None,
+                 endpt_rtol=None, endpt_atol=None):
+        self.spfunc = spfunc
+        self.mpfunc = mpfunc
+        self.index = index
+        self.argspec = argspec
+        self.spfunc_first = spfunc_first
+        self.dps = dps
+        self.n = n
+        self.rtol = rtol
+        self.atol = atol
+
+        if not isinstance(argspec, list):
+            self.endpt_rtol = None
+            self.endpt_atol = None
+        elif endpt_rtol is not None or endpt_atol is not None:
+            if isinstance(endpt_rtol, list):
+                self.endpt_rtol = endpt_rtol
+            else:
+                self.endpt_rtol = [endpt_rtol]*len(self.argspec)
+            if isinstance(endpt_atol, list):
+                self.endpt_atol = endpt_atol
+            else:
+                self.endpt_atol = [endpt_atol]*len(self.argspec)
+        else:
+            self.endpt_rtol = None
+            self.endpt_atol = None
+
+    def idmap(self, *args):
+        if self.spfunc_first:
+            res = self.spfunc(*args)
+            if np.isnan(res):
+                return np.nan
+            args = list(args)
+            args[self.index] = res
+            with mpmath.workdps(self.dps):
+                res = self.mpfunc(*tuple(args))
+                # Imaginary parts are spurious
+                res = mpf2float(res.real)
+        else:
+            with mpmath.workdps(self.dps):
+                res = self.mpfunc(*args)
+                res = mpf2float(res.real)
+            args = list(args)
+            args[self.index] = res
+            res = self.spfunc(*tuple(args))
+        return res
+
+    def get_param_filter(self):
+        if self.endpt_rtol is None and self.endpt_atol is None:
+            return None
+
+        filters = []
+        for rtol, atol, spec in zip(self.endpt_rtol, self.endpt_atol, self.argspec):
+            if rtol is None and atol is None:
+                filters.append(None)
+                continue
+            elif rtol is None:
+                rtol = 0.0
+            elif atol is None:
+                atol = 0.0
+
+            filters.append(EndpointFilter(spec.a, spec.b, rtol, atol))
+        return filters
+
+    def check(self):
+        # Generate values for the arguments
+        args = get_args(self.argspec, self.n)
+        param_filter = self.get_param_filter()
+        param_columns = tuple(range(args.shape[1]))
+        result_columns = args.shape[1]
+        args = np.hstack((args, args[:, self.index].reshape(args.shape[0], 1)))
+        FuncData(self.idmap, args,
+                 param_columns=param_columns, result_columns=result_columns,
+                 rtol=self.rtol, atol=self.atol, vectorized=False,
+                 param_filter=param_filter).check()
+
+
+def _assert_inverts(*a, **kw):
+    d = _CDFData(*a, **kw)
+    d.check()
+
+
+def _binomial_cdf(k, n, p):
+    k, n, p = mpmath.mpf(k), mpmath.mpf(n), mpmath.mpf(p)
+    if k <= 0:
+        return mpmath.mpf(0)
+    elif k >= n:
+        return mpmath.mpf(1)
+
+    onemp = mpmath.fsub(1, p, exact=True)
+    return mpmath.betainc(n - k, k + 1, x2=onemp, regularized=True)
+
+
+def _f_cdf(dfn, dfd, x):
+    if x < 0:
+        return mpmath.mpf(0)
+    dfn, dfd, x = mpmath.mpf(dfn), mpmath.mpf(dfd), mpmath.mpf(x)
+    ub = dfn*x/(dfn*x + dfd)
+    res = mpmath.betainc(dfn/2, dfd/2, x2=ub, regularized=True)
+    return res
+
+
+def _student_t_cdf(df, t, dps=None):
+    if dps is None:
+        dps = mpmath.mp.dps
+    with mpmath.workdps(dps):
+        df, t = mpmath.mpf(df), mpmath.mpf(t)
+        fac = mpmath.hyp2f1(0.5, 0.5*(df + 1), 1.5, -t**2/df)
+        fac *= t*mpmath.gamma(0.5*(df + 1))
+        fac /= mpmath.sqrt(mpmath.pi*df)*mpmath.gamma(0.5*df)
+        return 0.5 + fac
+
+
+def _noncentral_chi_pdf(t, df, nc):
+    res = mpmath.besseli(df/2 - 1, mpmath.sqrt(nc*t))
+    res *= mpmath.exp(-(t + nc)/2)*(t/nc)**(df/4 - 1/2)/2
+    return res
+
+
+def _noncentral_chi_cdf(x, df, nc, dps=None):
+    if dps is None:
+        dps = mpmath.mp.dps
+    x, df, nc = mpmath.mpf(x), mpmath.mpf(df), mpmath.mpf(nc)
+    with mpmath.workdps(dps):
+        res = mpmath.quad(lambda t: _noncentral_chi_pdf(t, df, nc), [0, x])
+        return res
+
+
+def _tukey_lmbda_quantile(p, lmbda):
+    # For lmbda != 0
+    return (p**lmbda - (1 - p)**lmbda)/lmbda
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+class TestCDFlib:
+
+    @pytest.mark.xfail(run=False)
+    def test_bdtrik(self):
+        _assert_inverts(
+            sp.bdtrik,
+            _binomial_cdf,
+            0, [ProbArg(), IntArg(1, 1000), ProbArg()],
+            rtol=1e-4)
+
+    def test_bdtrin(self):
+        _assert_inverts(
+            sp.bdtrin,
+            _binomial_cdf,
+            1, [IntArg(1, 1000), ProbArg(), ProbArg()],
+            rtol=1e-4, endpt_atol=[None, None, 1e-6])
+
+    def test_btdtria(self):
+        _assert_inverts(
+            sp.btdtria,
+            lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True),
+            0, [ProbArg(), Arg(0, 1e2, inclusive_a=False),
+                Arg(0, 1, inclusive_a=False, inclusive_b=False)],
+            rtol=1e-6)
+
+    def test_btdtrib(self):
+        # Use small values of a or mpmath doesn't converge
+        _assert_inverts(
+            sp.btdtrib,
+            lambda a, b, x: mpmath.betainc(a, b, x2=x, regularized=True),
+            1,
+            [Arg(0, 1e2, inclusive_a=False), ProbArg(),
+             Arg(0, 1, inclusive_a=False, inclusive_b=False)],
+            rtol=1e-7,
+            endpt_atol=[None, 1e-18, 1e-15])
+
+    @pytest.mark.xfail(run=False)
+    def test_fdtridfd(self):
+        _assert_inverts(
+            sp.fdtridfd,
+            _f_cdf,
+            1,
+            [IntArg(1, 100), ProbArg(), Arg(0, 100, inclusive_a=False)],
+            rtol=1e-7)
+
+    def test_gdtria(self):
+        _assert_inverts(
+            sp.gdtria,
+            lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True),
+            0,
+            [ProbArg(), Arg(0, 1e3, inclusive_a=False),
+             Arg(0, 1e4, inclusive_a=False)],
+            rtol=1e-7,
+            endpt_atol=[None, 1e-7, 1e-10])
+
+    def test_gdtrib(self):
+        # Use small values of a and x or mpmath doesn't converge
+        _assert_inverts(
+            sp.gdtrib,
+            lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True),
+            1,
+            [Arg(0, 1e2, inclusive_a=False), ProbArg(),
+             Arg(0, 1e3, inclusive_a=False)],
+            rtol=1e-5)
+
+    def test_gdtrix(self):
+        _assert_inverts(
+            sp.gdtrix,
+            lambda a, b, x: mpmath.gammainc(b, b=a*x, regularized=True),
+            2,
+            [Arg(0, 1e3, inclusive_a=False), Arg(0, 1e3, inclusive_a=False),
+             ProbArg()],
+            rtol=1e-7,
+            endpt_atol=[None, 1e-7, 1e-10])
+
+    # Overall nrdtrimn and nrdtrisd are not performing well with infeasible/edge
+    # combinations of sigma and x, hence restricted the domains to still use the
+    # testing machinery, also see gh-20069
+
+    # nrdtrimn signature: p, sd, x
+    # nrdtrisd signature: mn, p, x
+    def test_nrdtrimn(self):
+        _assert_inverts(
+            sp.nrdtrimn,
+            lambda x, y, z: mpmath.ncdf(z, x, y),
+            0,
+            [ProbArg(),  # CDF value p
+             Arg(0.1, np.inf, inclusive_a=False, inclusive_b=False),  # sigma
+             Arg(-1e10, 1e10)],  # x
+            rtol=1e-5)
+
+    def test_nrdtrisd(self):
+        _assert_inverts(
+            sp.nrdtrisd,
+            lambda x, y, z: mpmath.ncdf(z, x, y),
+            1,
+            [Arg(-np.inf, 10, inclusive_a=False, inclusive_b=False),  # mn
+             ProbArg(),  # CDF value p
+             Arg(10, 1e100)],  # x
+            rtol=1e-5)
+
+    def test_stdtr(self):
+        # Ideally the left endpoint for Arg() should be 0.
+        assert_mpmath_equal(
+            sp.stdtr,
+            _student_t_cdf,
+            [IntArg(1, 100), Arg(1e-10, np.inf)], rtol=1e-7)
+
+    @pytest.mark.xfail(run=False)
+    def test_stdtridf(self):
+        _assert_inverts(
+            sp.stdtridf,
+            _student_t_cdf,
+            0, [ProbArg(), Arg()], rtol=1e-7)
+
+    def test_stdtrit(self):
+        _assert_inverts(
+            sp.stdtrit,
+            _student_t_cdf,
+            1, [IntArg(1, 100), ProbArg()], rtol=1e-7,
+            endpt_atol=[None, 1e-10])
+
+    def test_chdtriv(self):
+        _assert_inverts(
+            sp.chdtriv,
+            lambda v, x: mpmath.gammainc(v/2, b=x/2, regularized=True),
+            0, [ProbArg(), IntArg(1, 100)], rtol=1e-4)
+
+    @pytest.mark.xfail(run=False)
+    def test_chndtridf(self):
+        # Use a larger atol since mpmath is doing numerical integration
+        _assert_inverts(
+            sp.chndtridf,
+            _noncentral_chi_cdf,
+            1, [Arg(0, 100, inclusive_a=False), ProbArg(),
+                Arg(0, 100, inclusive_a=False)],
+            n=1000, rtol=1e-4, atol=1e-15)
+
+    @pytest.mark.xfail(run=False)
+    def test_chndtrinc(self):
+        # Use a larger atol since mpmath is doing numerical integration
+        _assert_inverts(
+            sp.chndtrinc,
+            _noncentral_chi_cdf,
+            2, [Arg(0, 100, inclusive_a=False), IntArg(1, 100), ProbArg()],
+            n=1000, rtol=1e-4, atol=1e-15)
+
+    def test_chndtrix(self):
+        # Use a larger atol since mpmath is doing numerical integration
+        _assert_inverts(
+            sp.chndtrix,
+            _noncentral_chi_cdf,
+            0, [ProbArg(), IntArg(1, 100), Arg(0, 100, inclusive_a=False)],
+            n=1000, rtol=1e-4, atol=1e-15,
+            endpt_atol=[1e-6, None, None])
+
+    def test_tklmbda_zero_shape(self):
+        # When lmbda = 0 the CDF has a simple closed form
+        one = mpmath.mpf(1)
+        assert_mpmath_equal(
+            lambda x: sp.tklmbda(x, 0),
+            lambda x: one/(mpmath.exp(-x) + one),
+            [Arg()], rtol=1e-7)
+
+    def test_tklmbda_neg_shape(self):
+        _assert_inverts(
+            sp.tklmbda,
+            _tukey_lmbda_quantile,
+            0, [ProbArg(), Arg(-25, 0, inclusive_b=False)],
+            spfunc_first=False, rtol=1e-5,
+            endpt_atol=[1e-9, 1e-5])
+
+    @pytest.mark.xfail(run=False)
+    def test_tklmbda_pos_shape(self):
+        _assert_inverts(
+            sp.tklmbda,
+            _tukey_lmbda_quantile,
+            0, [ProbArg(), Arg(0, 100, inclusive_a=False)],
+            spfunc_first=False, rtol=1e-5)
+
+    # The values of lmdba are chosen so that 1/lmbda is exact.
+    @pytest.mark.parametrize('lmbda', [0.5, 1.0, 8.0])
+    def test_tklmbda_lmbda1(self, lmbda):
+        bound = 1/lmbda
+        assert_equal(sp.tklmbda([-bound, bound], lmbda), [0.0, 1.0])
+
+
+funcs = [
+    ("btdtria", 3),
+    ("btdtrib", 3),
+    ("bdtrik", 3),
+    ("bdtrin", 3),
+    ("chdtriv", 2),
+    ("chndtr", 3),
+    ("chndtrix", 3),
+    ("chndtridf", 3),
+    ("chndtrinc", 3),
+    ("fdtridfd", 3),
+    ("ncfdtr", 4),
+    ("ncfdtri", 4),
+    ("ncfdtridfn", 4),
+    ("ncfdtridfd", 4),
+    ("ncfdtrinc", 4),
+    ("gdtrix", 3),
+    ("gdtrib", 3),
+    ("gdtria", 3),
+    ("nbdtrik", 3),
+    ("nbdtrin", 3),
+    ("nrdtrimn", 3),
+    ("nrdtrisd", 3),
+    ("pdtrik", 2),
+    ("stdtr", 2),
+    ("stdtrit", 2),
+    ("stdtridf", 2),
+    ("nctdtr", 3),
+    ("nctdtrit", 3),
+    ("nctdtridf", 3),
+    ("nctdtrinc", 3),
+    ("tklmbda", 2),
+]
+
+
+@pytest.mark.parametrize('func,numargs', funcs, ids=[x[0] for x in funcs])
+def test_nonfinite(func, numargs):
+
+    rng = np.random.default_rng(1701299355559735)
+    func = getattr(sp, func)
+    args_choices = [(float(x), np.nan, np.inf, -np.inf) for x in rng.random(numargs)]
+
+    for args in itertools.product(*args_choices):
+        res = func(*args)
+
+        if any(np.isnan(x) for x in args):
+            # Nan inputs should result to nan output
+            assert_equal(res, np.nan)
+        else:
+            # All other inputs should return something (but not
+            # raise exceptions or cause hangs)
+            pass
+
+
+def test_chndtrix_gh2158():
+    # test that gh-2158 is resolved; previously this blew up
+    res = sp.chndtrix(0.999999, 2, np.arange(20.)+1e-6)
+
+    # Generated in R
+    # options(digits=16)
+    # ncp <- seq(0, 19) + 1e-6
+    # print(qchisq(0.999999, df = 2, ncp = ncp))
+    res_exp = [27.63103493142305, 35.25728589950540, 39.97396073236288,
+               43.88033702110538, 47.35206403482798, 50.54112500166103,
+               53.52720257322766, 56.35830042867810, 59.06600769498512,
+               61.67243118946381, 64.19376191277179, 66.64228141346548,
+               69.02756927200180, 71.35726934749408, 73.63759723904816,
+               75.87368842650227, 78.06984431185720, 80.22971052389806,
+               82.35640899964173, 84.45263768373256]
+    assert_allclose(res, res_exp)
+
+
+def test_nctdtrinc_gh19896():
+    # test that gh-19896 is resolved.
+    # Compared to SciPy 1.11 results from Fortran code.
+    dfarr = [0.001, 0.98, 9.8, 98, 980, 10000, 98, 9.8, 0.98, 0.001]
+    parr = [0.001, 0.1, 0.3, 0.8, 0.999, 0.001, 0.1, 0.3, 0.8, 0.999]
+    tarr = [0.0015, 0.15, 1.5, 15, 300, 0.0015, 0.15, 1.5, 15, 300]
+    desired = [3.090232306168629, 1.406141304556198, 2.014225177124157,
+               13.727067118283456, 278.9765683871208, 3.090232306168629,
+               1.4312427877936222, 2.014225177124157, 3.712743137978295,
+               -3.086951096691082]
+    actual = sp.nctdtrinc(dfarr, parr, tarr)
+    assert_allclose(actual, desired, rtol=5e-12, atol=0.0)
+
+
+def test_stdtr_stdtrit_neg_inf():
+    # -inf was treated as +inf and values from the normal were returned
+    assert np.all(np.isnan(sp.stdtr(-np.inf, [-np.inf, -1.0, 0.0, 1.0, np.inf])))
+    assert np.all(np.isnan(sp.stdtrit(-np.inf, [0.0, 0.25, 0.5, 0.75, 1.0])))
+
+
+def test_bdtrik_nbdtrik_inf():
+    y = np.array(
+        [np.nan,-np.inf,-10.0, -1.0, 0.0, .00001, .5, 0.9999, 1.0, 10.0, np.inf])
+    y = y[:,None]
+    p = np.atleast_2d(
+        [np.nan, -np.inf, -10.0, -1.0, 0.0, .00001, .5, 1.0, np.inf])
+    assert np.all(np.isnan(sp.bdtrik(y, np.inf, p)))
+    assert np.all(np.isnan(sp.nbdtrik(y, np.inf, p)))
+
+
+@pytest.mark.parametrize(
+    "dfn,dfd,nc,f,expected",
+    [[100.0, 0.1, 0.1, 100.0, 0.29787396410092676],
+     [100.0, 100.0, 0.01, 0.1, 4.4344737598690424e-26],
+     [100.0, 0.01, 0.1, 0.01, 0.002848616633080384],
+     [10.0, 0.01, 1.0, 0.1, 0.012339557729057956],
+     [100.0, 100.0, 0.01, 0.01, 1.8926477420964936e-72],
+     [1.0, 100.0, 100.0, 0.1, 1.7925940526821304e-22],
+     [1.0, 0.01, 100.0, 10.0, 0.012334711965024968],
+     [1.0, 0.01, 10.0, 0.01, 0.00021944525290299],
+     [10.0, 1.0, 0.1, 100.0, 0.9219345555070705],
+     [0.1, 0.1, 1.0, 1.0, 0.3136335813423239],
+     [100.0, 100.0, 0.1, 10.0, 1.0],
+     [1.0, 0.1, 100.0, 10.0, 0.02926064279680897]]
+)
+def test_ncfdtr(dfn, dfd, nc, f, expected):
+    # Reference values computed with mpmath with the following script
+    #
+    # import numpy as np
+    #
+    # from mpmath import mp
+    # from scipy.special import ncfdtr
+    #
+    # mp.dps = 100
+    #
+    # def mp_ncfdtr(dfn, dfd, nc, f):
+    #     # Uses formula 26.2.20 from Abramowitz and Stegun.
+    #     dfn, dfd, nc, f = map(mp.mpf, (dfn, dfd, nc, f))
+    #     def term(j):
+    #         result = mp.exp(-nc/2)*(nc/2)**j / mp.factorial(j)
+    #         result *= mp.betainc(
+    #             dfn/2 + j, dfd/2, 0, f*dfn/(f*dfn + dfd), regularized=True
+    #         )
+    #         return result
+    #     result = mp.nsum(term, [0, mp.inf])
+    #     return float(result)
+    #
+    # dfn = np.logspace(-2, 2, 5)
+    # dfd = np.logspace(-2, 2, 5)
+    # nc = np.logspace(-2, 2, 5)
+    # f = np.logspace(-2, 2, 5)
+    #
+    # dfn, dfd, nc, f = np.meshgrid(dfn, dfd, nc, f)
+    # dfn, dfd, nc, f = map(np.ravel, (dfn, dfd, nc, f))
+    #
+    # cases = []
+    # re = []
+    # for x0, x1, x2, x3 in zip(*(dfn, dfd, nc, f)):
+    #     observed = ncfdtr(x0, x1, x2, x3)
+    #     expected = mp_ncfdtr(x0, x1, x2, x3)
+    #     cases.append((x0, x1, x2, x3, expected))
+    #     re.append((abs(expected - observed)/abs(expected)))
+    #
+    # assert np.max(re) < 1e-13
+    #
+    # rng = np.random.default_rng(1234)
+    # sample_idx = rng.choice(len(re), replace=False, size=12)
+    # cases = np.array(cases)[sample_idx].tolist()
+    assert_allclose(sp.ncfdtr(dfn, dfd, nc, f), expected, rtol=1e-13, atol=0)
+
+
+class TestNctdtr:
+
+    # Reference values computed with mpmath with the following script
+    # Formula from:
+    # Lenth, Russell V (1989). "Algorithm AS 243: Cumulative Distribution Function
+    # of the Non-central t Distribution". Journal of the Royal Statistical Society,
+    # Series C. 38 (1): 185-189
+    #
+    # Warning: may take a long time to run
+    #
+    # from mpmath import mp
+    # mp.dps = 400
+
+    # def nct_cdf(df, nc, x):
+    #     df, nc, x = map(mp.mpf, (df, nc, x))
+        
+    #     def f(df, nc, x):
+    #         phi = mp.ncdf(-nc)
+    #         y = x * x / (x * x + df)
+    #         constant = mp.exp(-nc * nc / 2.)
+    #         def term(j):
+    #             intermediate = constant * (nc *nc / 2.)**j
+    #             p = intermediate/mp.factorial(j)
+    #             q = nc / (mp.sqrt(2.) * mp.gamma(j + 1.5)) * intermediate
+    #             first_beta_term = mp.betainc(j + 0.5, df/2., x2=y,
+    #                                          regularized=True)
+    #             second_beta_term = mp.betainc(j + mp.one, df/2., x2=y,
+    #                                           regularized=True)
+    #             return p * first_beta_term + q * second_beta_term
+
+    #         sum_term = mp.nsum(term, [0, mp.inf])
+    #         f = phi + 0.5 * sum_term
+    #         return f
+
+    #     if x >= 0:
+    #         result = f(df, nc, x)
+    #     else:
+    #         result = mp.one - f(df, -nc, x)
+    #     return float(result)
+
+    @pytest.mark.parametrize("df, nc, x, expected", [
+        (0.98, -3.8, 0.0015, 0.9999279987514815),
+        (0.98, -3.8, 0.15, 0.9999528361700505),
+        (0.98, -3.8, 1.5, 0.9999908823016942),
+        (0.98, -3.8, 15, 0.9999990264591945),
+        (0.98, 0.38, 0.0015, 0.35241533122693),
+        (0.98, 0.38, 0.15, 0.39749697267146983),
+        (0.98, 0.38, 1.5, 0.716862963488558),
+        (0.98, 0.38, 15, 0.9656246449257494),
+        (0.98, 3.8, 0.0015, 7.26973354942293e-05),
+        (0.98, 3.8, 0.15, 0.00012416481147589105),
+        (0.98, 3.8, 1.5, 0.035388035775454095),
+        (0.98, 3.8, 15, 0.7954826975430583),
+        (0.98, 38, 0.0015, 3.02106943e-316),
+        (0.98, 38, 0.15, 6.069970616996603e-309),
+        (0.98, 38, 1.5, 2.591995360483094e-97),
+        (0.98, 38, 15, 0.011927265886910935),
+        (9.8, -3.8, 0.0015, 0.9999280776192786),
+        (9.8, -3.8, 0.15, 0.9999599410685442),
+        (9.8, -3.8, 1.5, 0.9999997432394788),
+        (9.8, -3.8, 15, 0.9999999999999984),
+        (9.8, 0.38, 0.0015, 0.3525155979107491),
+        (9.8, 0.38, 0.15, 0.40763120140379194),
+        (9.8, 0.38, 1.5, 0.8476794017024651),
+        (9.8, 0.38, 15, 0.9999999297116268),
+        (9.8, 3.8, 0.0015, 7.277620328149153e-05),
+        (9.8, 3.8, 0.15, 0.00013024802220900652),
+        (9.8, 3.8, 1.5, 0.013477432800072933),
+        (9.8, 3.8, 15, 0.999850151230648),
+        (9.8, 38, 0.0015, 3.05066095e-316),
+        (9.8, 38, 0.15, 1.79065514676e-313),
+        (9.8, 38, 1.5, 2.0935940165900746e-249),
+        (9.8, 38, 15, 2.252076291604796e-09),
+        (98, -3.8, 0.0015, 0.9999280875149109),
+        (98, -3.8, 0.15, 0.9999608250170452),
+        (98, -3.8, 1.5, 0.9999999304757682),
+        (98, -3.8, 15, 1.0),
+        (98, 0.38, 0.0015, 0.35252817848596313),
+        (98, 0.38, 0.15, 0.40890253001794846),
+        (98, 0.38, 1.5, 0.8664672830006552),
+        (98, 0.38, 15, 1.0),
+        (98, 3.8, 0.0015, 7.278609891281275e-05),
+        (98, 3.8, 0.15, 0.0001310318674827004),
+        (98, 3.8, 1.5, 0.010990879189991727),
+        (98, 3.8, 15, 0.9999999999999989),
+        (98, 38, 0.0015, 3.05437385e-316),
+        (98, 38, 0.15, 9.1668336166e-314),
+        (98, 38, 1.5, 1.8085884236563926e-288),
+        (98, 38, 15, 2.7740532792035907e-50),
+        (980, -3.8, 0.0015, 0.9999280885188965),
+        (980, -3.8, 0.15, 0.9999609144559273),
+        (980, -3.8, 1.5, 0.9999999410050979),
+        (980, -3.8, 15, 1.0),
+        (980, 0.38, 0.0015, 0.3525294548792812),
+        (980, 0.38, 0.15, 0.4090315324657382),
+        (980, 0.38, 1.5, 0.8684247068517293),
+        (980, 0.38, 15, 1.0),
+        (980, 3.8, 0.0015, 7.278710289828983e-05),
+        (980, 3.8, 0.15, 0.00013111131667906573),
+        (980, 3.8, 1.5, 0.010750678886113882),
+        (980, 3.8, 15, 1.0),
+        (980, 38, 0.0015, 3.0547506e-316),
+        (980, 38, 0.15, 8.6191646313e-314),
+        pytest.param(980, 38, 1.5, 1.1824454111413493e-291,
+                     marks=pytest.mark.xfail(
+                        reason="Bug in underlying Boost math implementation")),
+        (980, 38, 15, 5.407535300713606e-105)
+    ])
+    def test_gh19896(self, df, nc, x, expected):
+        # test that gh-19896 is resolved.
+        # Originally this was a regression test that used the old Fortran results
+        # as a reference. The Fortran results were not accurate, so the reference
+        # values were recomputed with mpmath.
+        result = sp.nctdtr(df, nc, x)
+        assert_allclose(result, expected, rtol=1e-13, atol=1e-303)
+
+    def test_nctdtr_gh8344(self):
+        # test that gh-8344 is resolved.
+        df, nc, x = 3000, 3, 0.1
+        expected = 0.0018657780826323328
+        assert_allclose(sp.nctdtr(df, nc, x), expected, rtol=1e-14)
+
+    @pytest.mark.parametrize(
+        "df, nc, x, expected, rtol",
+        [[3., 5., -2., 1.5645373999149622e-09, 5e-9],
+         [1000., 10., 1., 1.1493552133826623e-19, 1e-13],
+         [1e-5, -6., 2., 0.9999999990135003, 1e-13],
+         [10., 20., 0.15, 6.426530505957303e-88, 1e-13],
+         [1., 1., np.inf, 1.0, 0.0],
+         [1., 1., -np.inf, 0.0, 0.0]
+        ]
+    )
+    def test_accuracy(self, df, nc, x, expected, rtol):
+        assert_allclose(sp.nctdtr(df, nc, x), expected, rtol=rtol)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b1ad41243f0865c205963d938ab61a346ee8e88
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cdft_asymptotic.py
@@ -0,0 +1,49 @@
+# gh-14777 regression tests
+# Test stdtr and stdtrit with infinite df and large values of df
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+from scipy.special import stdtr, stdtrit, ndtr, ndtri
+
+
+def test_stdtr_vs_R_large_df():
+    df = [1e10, 1e12, 1e120, np.inf]
+    t = 1.
+    res = stdtr(df, t)
+    # R Code:
+    #   options(digits=20)
+    #   pt(1., c(1e10, 1e12, 1e120, Inf))
+    res_R = [0.84134474605644460343,
+             0.84134474606842180044,
+             0.84134474606854281475,
+             0.84134474606854292578]
+    assert_allclose(res, res_R, rtol=2e-15)
+    # last value should also agree with ndtr
+    assert_equal(res[3], ndtr(1.))
+
+
+def test_stdtrit_vs_R_large_df():
+    df = [1e10, 1e12, 1e120, np.inf]
+    p = 0.1
+    res = stdtrit(df, p)
+    # R Code:
+    #   options(digits=20)
+    #   qt(0.1, c(1e10, 1e12, 1e120, Inf))
+    res_R = [-1.2815515656292593150,
+             -1.2815515655454472466,
+             -1.2815515655446008125,
+             -1.2815515655446008125]
+    assert_allclose(res, res_R, rtol=1e-14, atol=1e-15)
+    # last value should also agree with ndtri
+    assert_equal(res[3], ndtri(0.1))
+
+
+def test_stdtr_stdtri_invalid():
+    # a mix of large and inf df with t/p equal to nan
+    df = [1e10, 1e12, 1e120, np.inf]
+    x = np.nan
+    res1 = stdtr(df, x)
+    res2 = stdtrit(df, x)
+    res_ex = 4*[np.nan]
+    assert_equal(res1, res_ex)
+    assert_equal(res2, res_ex)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cephes_intp_cast.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cephes_intp_cast.py
new file mode 100644
index 0000000000000000000000000000000000000000..05f3d1ae5c101ff50c75d1065e5e234063d192e4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cephes_intp_cast.py
@@ -0,0 +1,29 @@
+import pytest
+import numpy as np
+from scipy.special._ufuncs import (
+    _smirnovc, _smirnovci, _smirnovp,
+    _struve_asymp_large_z, _struve_bessel_series, _struve_power_series,
+    bdtr, bdtrc, bdtri, expn, kn, nbdtr, nbdtrc, nbdtri, pdtri,
+    smirnov, smirnovi, yn
+)
+
+
+#
+# For each ufunc here, verify that the default integer type, np.intp,
+# can be safely cast to the integer type found in the input type signatures.
+# For this particular set of functions, the code expects to find just one
+# integer type among the input signatures.
+#
+@pytest.mark.parametrize(
+    'ufunc',
+    [_smirnovc, _smirnovci, _smirnovp,
+     _struve_asymp_large_z, _struve_bessel_series, _struve_power_series,
+     bdtr, bdtrc, bdtri, expn, kn, nbdtr, nbdtrc, nbdtri, pdtri,
+     smirnov, smirnovi, yn],
+)
+def test_intp_safe_cast(ufunc):
+    int_chars = {'i', 'l', 'q'}
+    int_input = [set(sig.split('->')[0]) & int_chars for sig in ufunc.types]
+    int_char = ''.join(s.pop() if s else '' for s in int_input)
+    assert len(int_char) == 1, "More integer types in the signatures than expected"
+    assert np.can_cast(np.intp, np.dtype(int_char))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py
new file mode 100644
index 0000000000000000000000000000000000000000..27e3ca2699d0d1d0b58665f125d99c166095696d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cosine_distr.py
@@ -0,0 +1,83 @@
+import numpy as np
+from numpy.testing import assert_allclose
+import pytest
+from scipy.special._ufuncs import _cosine_cdf, _cosine_invcdf
+
+
+# These values are (x, p) where p is the expected exact value of
+# _cosine_cdf(x).  These values will be tested for exact agreement.
+_coscdf_exact = [
+    (-4.0, 0.0),
+    (0, 0.5),
+    (np.pi, 1.0),
+    (4.0, 1.0),
+]
+
+@pytest.mark.parametrize("x, expected", _coscdf_exact)
+def test_cosine_cdf_exact(x, expected):
+    assert _cosine_cdf(x) == expected
+
+
+# These values are (x, p), where p is the expected value of
+# _cosine_cdf(x). The expected values were computed with mpmath using
+# 50 digits of precision.  These values will be tested for agreement
+# with the computed values using a very small relative tolerance.
+# The value at -np.pi is not 0, because -np.pi does not equal -π.
+_coscdf_close = [
+    (3.1409, 0.999999999991185),
+    (2.25, 0.9819328173287907),
+    # -1.6 is the threshold below which the Pade approximant is used.
+    (-1.599, 0.08641959838382553),
+    (-1.601, 0.086110582992713),
+    (-2.0, 0.0369709335961611),
+    (-3.0, 7.522387241801384e-05),
+    (-3.1415, 2.109869685443648e-14),
+    (-3.14159, 4.956444476505336e-19),
+    (-np.pi, 4.871934450264861e-50),
+]
+
+@pytest.mark.parametrize("x, expected", _coscdf_close)
+def test_cosine_cdf(x, expected):
+    assert_allclose(_cosine_cdf(x), expected, rtol=5e-15)
+
+
+# These values are (p, x) where x is the expected exact value of
+# _cosine_invcdf(p).  These values will be tested for exact agreement.
+_cosinvcdf_exact = [
+    (0.0, -np.pi),
+    (0.5, 0.0),
+    (1.0, np.pi),
+]
+
+@pytest.mark.parametrize("p, expected", _cosinvcdf_exact)
+def test_cosine_invcdf_exact(p, expected):
+    assert _cosine_invcdf(p) == expected
+
+
+def test_cosine_invcdf_invalid_p():
+    # Check that p values outside of [0, 1] return nan.
+    assert np.isnan(_cosine_invcdf([-0.1, 1.1])).all()
+
+
+# These values are (p, x), where x is the expected value of _cosine_invcdf(p).
+# The expected values were computed with mpmath using 50 digits of precision.
+_cosinvcdf_close = [
+    (1e-50, -np.pi),
+    (1e-14, -3.1415204137058454),
+    (1e-08, -3.1343686589124524),
+    (0.0018001, -2.732563923138336),
+    (0.010, -2.41276589008678),
+    (0.060, -1.7881244975330157),
+    (0.125, -1.3752523669869274),
+    (0.250, -0.831711193579736),
+    (0.400, -0.3167954512395289),
+    (0.419, -0.25586025626919906),
+    (0.421, -0.24947570750445663),
+    (0.750, 0.831711193579736),
+    (0.940, 1.7881244975330153),
+    (0.9999999996, 3.1391220839917167),
+]
+
+@pytest.mark.parametrize("p, expected", _cosinvcdf_close)
+def test_cosine_invcdf(p, expected):
+    assert_allclose(_cosine_invcdf(p), expected, rtol=1e-14)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dc9ed50cec9503edb77064cfa209c9d81573214
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_cython_special.py
@@ -0,0 +1,363 @@
+from collections.abc import Callable
+
+import pytest
+from itertools import product
+from numpy.testing import assert_allclose, suppress_warnings
+from scipy import special
+from scipy.special import cython_special
+
+
+bint_points = [True, False]
+int_points = [-10, -1, 1, 10]
+real_points = [-10.0, -1.0, 1.0, 10.0]
+complex_points = [complex(*tup) for tup in product(real_points, repeat=2)]
+
+
+CYTHON_SIGNATURE_MAP = {
+    'b': 'bint',
+    'f': 'float',
+    'd': 'double',
+    'g': 'long double',
+    'F': 'float complex',
+    'D': 'double complex',
+    'G': 'long double complex',
+    'i': 'int',
+    'l': 'long'
+}
+
+
+TEST_POINTS = {
+    'b': bint_points,
+    'f': real_points,
+    'd': real_points,
+    'g': real_points,
+    'F': complex_points,
+    'D': complex_points,
+    'G': complex_points,
+    'i': int_points,
+    'l': int_points,
+}
+
+
+PARAMS: list[tuple[Callable, Callable, tuple[str, ...], str | None]] = [
+    (special.agm, cython_special.agm, ('dd',), None),
+    (special.airy, cython_special._airy_pywrap, ('d', 'D'), None),
+    (special.airye, cython_special._airye_pywrap, ('d', 'D'), None),
+    (special.bdtr, cython_special.bdtr, ('dld', 'ddd'), None),
+    (special.bdtrc, cython_special.bdtrc, ('dld', 'ddd'), None),
+    (special.bdtri, cython_special.bdtri, ('dld', 'ddd'), None),
+    (special.bdtrik, cython_special.bdtrik, ('ddd',), None),
+    (special.bdtrin, cython_special.bdtrin, ('ddd',), None),
+    (special.bei, cython_special.bei, ('d',), None),
+    (special.beip, cython_special.beip, ('d',), None),
+    (special.ber, cython_special.ber, ('d',), None),
+    (special.berp, cython_special.berp, ('d',), None),
+    (special.besselpoly, cython_special.besselpoly, ('ddd',), None),
+    (special.beta, cython_special.beta, ('dd',), None),
+    (special.betainc, cython_special.betainc, ('ddd',), None),
+    (special.betaincc, cython_special.betaincc, ('ddd',), None),
+    (special.betaincinv, cython_special.betaincinv, ('ddd',), None),
+    (special.betainccinv, cython_special.betainccinv, ('ddd',), None),
+    (special.betaln, cython_special.betaln, ('dd',), None),
+    (special.binom, cython_special.binom, ('dd',), None),
+    (special.boxcox, cython_special.boxcox, ('dd',), None),
+    (special.boxcox1p, cython_special.boxcox1p, ('dd',), None),
+    (special.btdtria, cython_special.btdtria, ('ddd',), None),
+    (special.btdtrib, cython_special.btdtrib, ('ddd',), None),
+    (special.cbrt, cython_special.cbrt, ('d',), None),
+    (special.chdtr, cython_special.chdtr, ('dd',), None),
+    (special.chdtrc, cython_special.chdtrc, ('dd',), None),
+    (special.chdtri, cython_special.chdtri, ('dd',), None),
+    (special.chdtriv, cython_special.chdtriv, ('dd',), None),
+    (special.chndtr, cython_special.chndtr, ('ddd',), None),
+    (special.chndtridf, cython_special.chndtridf, ('ddd',), None),
+    (special.chndtrinc, cython_special.chndtrinc, ('ddd',), None),
+    (special.chndtrix, cython_special.chndtrix, ('ddd',), None),
+    (special.cosdg, cython_special.cosdg, ('d',), None),
+    (special.cosm1, cython_special.cosm1, ('d',), None),
+    (special.cotdg, cython_special.cotdg, ('d',), None),
+    (special.dawsn, cython_special.dawsn, ('d', 'D'), None),
+    (special.ellipe, cython_special.ellipe, ('d',), None),
+    (special.ellipeinc, cython_special.ellipeinc, ('dd',), None),
+    (special.ellipj, cython_special._ellipj_pywrap, ('dd',), None),
+    (special.ellipkinc, cython_special.ellipkinc, ('dd',), None),
+    (special.ellipkm1, cython_special.ellipkm1, ('d',), None),
+    (special.ellipk, cython_special.ellipk, ('d',), None),
+    (special.elliprc, cython_special.elliprc, ('dd', 'DD'), None),
+    (special.elliprd, cython_special.elliprd, ('ddd', 'DDD'), None),
+    (special.elliprf, cython_special.elliprf, ('ddd', 'DDD'), None),
+    (special.elliprg, cython_special.elliprg, ('ddd', 'DDD'), None),
+    (special.elliprj, cython_special.elliprj, ('dddd', 'DDDD'), None),
+    (special.entr, cython_special.entr, ('d',), None),
+    (special.erf, cython_special.erf, ('d', 'D'), None),
+    (special.erfc, cython_special.erfc, ('d', 'D'), None),
+    (special.erfcx, cython_special.erfcx, ('d', 'D'), None),
+    (special.erfi, cython_special.erfi, ('d', 'D'), None),
+    (special.erfinv, cython_special.erfinv, ('d',), None),
+    (special.erfcinv, cython_special.erfcinv, ('d',), None),
+    (special.eval_chebyc, cython_special.eval_chebyc, ('dd', 'dD', 'ld'), None),
+    (special.eval_chebys, cython_special.eval_chebys, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_chebyt, cython_special.eval_chebyt, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_chebyu, cython_special.eval_chebyu, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_gegenbauer, cython_special.eval_gegenbauer, ('ddd', 'ddD', 'ldd'),
+     'd and l differ for negative int'),
+    (special.eval_genlaguerre, cython_special.eval_genlaguerre, ('ddd', 'ddD', 'ldd'),
+     'd and l differ for negative int'),
+    (special.eval_hermite, cython_special.eval_hermite, ('ld',), None),
+    (special.eval_hermitenorm, cython_special.eval_hermitenorm, ('ld',), None),
+    (special.eval_jacobi, cython_special.eval_jacobi, ('dddd', 'dddD', 'lddd'),
+     'd and l differ for negative int'),
+    (special.eval_laguerre, cython_special.eval_laguerre, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_legendre, cython_special.eval_legendre, ('dd', 'dD', 'ld'), None),
+    (special.eval_sh_chebyt, cython_special.eval_sh_chebyt, ('dd', 'dD', 'ld'), None),
+    (special.eval_sh_chebyu, cython_special.eval_sh_chebyu, ('dd', 'dD', 'ld'),
+     'd and l differ for negative int'),
+    (special.eval_sh_jacobi, cython_special.eval_sh_jacobi, ('dddd', 'dddD', 'lddd'),
+     'd and l differ for negative int'),
+    (special.eval_sh_legendre, cython_special.eval_sh_legendre, ('dd', 'dD', 'ld'),
+     None),
+    (special.exp1, cython_special.exp1, ('d', 'D'), None),
+    (special.exp10, cython_special.exp10, ('d',), None),
+    (special.exp2, cython_special.exp2, ('d',), None),
+    (special.expi, cython_special.expi, ('d', 'D'), None),
+    (special.expit, cython_special.expit, ('f', 'd', 'g'), None),
+    (special.expm1, cython_special.expm1, ('d', 'D'), None),
+    (special.expn, cython_special.expn, ('ld', 'dd'), None),
+    (special.exprel, cython_special.exprel, ('d',), None),
+    (special.fdtr, cython_special.fdtr, ('ddd',), None),
+    (special.fdtrc, cython_special.fdtrc, ('ddd',), None),
+    (special.fdtri, cython_special.fdtri, ('ddd',), None),
+    (special.fdtridfd, cython_special.fdtridfd, ('ddd',), None),
+    (special.fresnel, cython_special._fresnel_pywrap, ('d', 'D'), None),
+    (special.gamma, cython_special.gamma, ('d', 'D'), None),
+    (special.gammainc, cython_special.gammainc, ('dd',), None),
+    (special.gammaincc, cython_special.gammaincc, ('dd',), None),
+    (special.gammainccinv, cython_special.gammainccinv, ('dd',), None),
+    (special.gammaincinv, cython_special.gammaincinv, ('dd',), None),
+    (special.gammaln, cython_special.gammaln, ('d',), None),
+    (special.gammasgn, cython_special.gammasgn, ('d',), None),
+    (special.gdtr, cython_special.gdtr, ('ddd',), None),
+    (special.gdtrc, cython_special.gdtrc, ('ddd',), None),
+    (special.gdtria, cython_special.gdtria, ('ddd',), None),
+    (special.gdtrib, cython_special.gdtrib, ('ddd',), None),
+    (special.gdtrix, cython_special.gdtrix, ('ddd',), None),
+    (special.hankel1, cython_special.hankel1, ('dD',), None),
+    (special.hankel1e, cython_special.hankel1e, ('dD',), None),
+    (special.hankel2, cython_special.hankel2, ('dD',), None),
+    (special.hankel2e, cython_special.hankel2e, ('dD',), None),
+    (special.huber, cython_special.huber, ('dd',), None),
+    (special.hyp0f1, cython_special.hyp0f1, ('dd', 'dD'), None),
+    (special.hyp1f1, cython_special.hyp1f1, ('ddd', 'ddD'), None),
+    (special.hyp2f1, cython_special.hyp2f1, ('dddd', 'dddD'), None),
+    (special.hyperu, cython_special.hyperu, ('ddd',), None),
+    (special.i0, cython_special.i0, ('d',), None),
+    (special.i0e, cython_special.i0e, ('d',), None),
+    (special.i1, cython_special.i1, ('d',), None),
+    (special.i1e, cython_special.i1e, ('d',), None),
+    (special.inv_boxcox, cython_special.inv_boxcox, ('dd',), None),
+    (special.inv_boxcox1p, cython_special.inv_boxcox1p, ('dd',), None),
+    (special.it2i0k0, cython_special._it2i0k0_pywrap, ('d',), None),
+    (special.it2j0y0, cython_special._it2j0y0_pywrap, ('d',), None),
+    (special.it2struve0, cython_special.it2struve0, ('d',), None),
+    (special.itairy, cython_special._itairy_pywrap, ('d',), None),
+    (special.iti0k0, cython_special._iti0k0_pywrap, ('d',), None),
+    (special.itj0y0, cython_special._itj0y0_pywrap, ('d',), None),
+    (special.itmodstruve0, cython_special.itmodstruve0, ('d',), None),
+    (special.itstruve0, cython_special.itstruve0, ('d',), None),
+    (special.iv, cython_special.iv, ('dd', 'dD'), None),
+    (special.ive, cython_special.ive, ('dd', 'dD'), None),
+    (special.j0, cython_special.j0, ('d',), None),
+    (special.j1, cython_special.j1, ('d',), None),
+    (special.jv, cython_special.jv, ('dd', 'dD'), None),
+    (special.jve, cython_special.jve, ('dd', 'dD'), None),
+    (special.k0, cython_special.k0, ('d',), None),
+    (special.k0e, cython_special.k0e, ('d',), None),
+    (special.k1, cython_special.k1, ('d',), None),
+    (special.k1e, cython_special.k1e, ('d',), None),
+    (special.kei, cython_special.kei, ('d',), None),
+    (special.keip, cython_special.keip, ('d',), None),
+    (special.kelvin, cython_special._kelvin_pywrap, ('d',), None),
+    (special.ker, cython_special.ker, ('d',), None),
+    (special.kerp, cython_special.kerp, ('d',), None),
+    (special.kl_div, cython_special.kl_div, ('dd',), None),
+    (special.kn, cython_special.kn, ('ld', 'dd'), None),
+    (special.kolmogi, cython_special.kolmogi, ('d',), None),
+    (special.kolmogorov, cython_special.kolmogorov, ('d',), None),
+    (special.kv, cython_special.kv, ('dd', 'dD'), None),
+    (special.kve, cython_special.kve, ('dd', 'dD'), None),
+    (special.log1p, cython_special.log1p, ('d', 'D'), None),
+    (special.log_expit, cython_special.log_expit, ('f', 'd', 'g'), None),
+    (special.log_ndtr, cython_special.log_ndtr, ('d', 'D'), None),
+    (special.log_wright_bessel, cython_special.log_wright_bessel, ('ddd',), None),
+    (special.ndtri_exp, cython_special.ndtri_exp, ('d',), None),
+    (special.loggamma, cython_special.loggamma, ('D',), None),
+    (special.logit, cython_special.logit, ('f', 'd', 'g'), None),
+    (special.lpmv, cython_special.lpmv, ('ddd',), None),
+    (special.mathieu_a, cython_special.mathieu_a, ('dd',), None),
+    (special.mathieu_b, cython_special.mathieu_b, ('dd',), None),
+    (special.mathieu_cem, cython_special._mathieu_cem_pywrap, ('ddd',), None),
+    (special.mathieu_modcem1, cython_special._mathieu_modcem1_pywrap, ('ddd',), None),
+    (special.mathieu_modcem2, cython_special._mathieu_modcem2_pywrap, ('ddd',), None),
+    (special.mathieu_modsem1, cython_special._mathieu_modsem1_pywrap, ('ddd',), None),
+    (special.mathieu_modsem2, cython_special._mathieu_modsem2_pywrap, ('ddd',), None),
+    (special.mathieu_sem, cython_special._mathieu_sem_pywrap, ('ddd',), None),
+    (special.modfresnelm, cython_special._modfresnelm_pywrap, ('d',), None),
+    (special.modfresnelp, cython_special._modfresnelp_pywrap, ('d',), None),
+    (special.modstruve, cython_special.modstruve, ('dd',), None),
+    (special.nbdtr, cython_special.nbdtr, ('lld', 'ddd'), None),
+    (special.nbdtrc, cython_special.nbdtrc, ('lld', 'ddd'), None),
+    (special.nbdtri, cython_special.nbdtri, ('lld', 'ddd'), None),
+    (special.nbdtrik, cython_special.nbdtrik, ('ddd',), None),
+    (special.nbdtrin, cython_special.nbdtrin, ('ddd',), None),
+    (special.ncfdtr, cython_special.ncfdtr, ('dddd',), None),
+    (special.ncfdtri, cython_special.ncfdtri, ('dddd',), None),
+    (special.ncfdtridfd, cython_special.ncfdtridfd, ('dddd',), None),
+    (special.ncfdtridfn, cython_special.ncfdtridfn, ('dddd',), None),
+    (special.ncfdtrinc, cython_special.ncfdtrinc, ('dddd',), None),
+    (special.nctdtr, cython_special.nctdtr, ('ddd',), None),
+    (special.nctdtridf, cython_special.nctdtridf, ('ddd',), None),
+    (special.nctdtrinc, cython_special.nctdtrinc, ('ddd',), None),
+    (special.nctdtrit, cython_special.nctdtrit, ('ddd',), None),
+    (special.ndtr, cython_special.ndtr, ('d', 'D'), None),
+    (special.ndtri, cython_special.ndtri, ('d',), None),
+    (special.nrdtrimn, cython_special.nrdtrimn, ('ddd',), None),
+    (special.nrdtrisd, cython_special.nrdtrisd, ('ddd',), None),
+    (special.obl_ang1, cython_special._obl_ang1_pywrap, ('dddd',), None),
+    (special.obl_ang1_cv, cython_special._obl_ang1_cv_pywrap, ('ddddd',), None),
+    (special.obl_cv, cython_special.obl_cv, ('ddd',), None),
+    (special.obl_rad1, cython_special._obl_rad1_pywrap, ('dddd',), "see gh-6211"),
+    (special.obl_rad1_cv, cython_special._obl_rad1_cv_pywrap, ('ddddd',),
+     "see gh-6211"),
+    (special.obl_rad2, cython_special._obl_rad2_pywrap, ('dddd',), "see gh-6211"),
+    (special.obl_rad2_cv, cython_special._obl_rad2_cv_pywrap, ('ddddd',),
+     "see gh-6211"),
+    (special.pbdv, cython_special._pbdv_pywrap, ('dd',), None),
+    (special.pbvv, cython_special._pbvv_pywrap, ('dd',), None),
+    (special.pbwa, cython_special._pbwa_pywrap, ('dd',), None),
+    (special.pdtr, cython_special.pdtr, ('dd', 'dd'), None),
+    (special.pdtrc, cython_special.pdtrc, ('dd', 'dd'), None),
+    (special.pdtri, cython_special.pdtri, ('ld', 'dd'), None),
+    (special.pdtrik, cython_special.pdtrik, ('dd',), None),
+    (special.poch, cython_special.poch, ('dd',), None),
+    (special.powm1, cython_special.powm1, ('dd',), None),
+    (special.pro_ang1, cython_special._pro_ang1_pywrap, ('dddd',), None),
+    (special.pro_ang1_cv, cython_special._pro_ang1_cv_pywrap, ('ddddd',), None),
+    (special.pro_cv, cython_special.pro_cv, ('ddd',), None),
+    (special.pro_rad1, cython_special._pro_rad1_pywrap, ('dddd',), "see gh-6211"),
+    (special.pro_rad1_cv, cython_special._pro_rad1_cv_pywrap, ('ddddd',),
+     "see gh-6211"),
+    (special.pro_rad2, cython_special._pro_rad2_pywrap, ('dddd',), "see gh-6211"),
+    (special.pro_rad2_cv, cython_special._pro_rad2_cv_pywrap, ('ddddd',),
+     "see gh-6211"),
+    (special.pseudo_huber, cython_special.pseudo_huber, ('dd',), None),
+    (special.psi, cython_special.psi, ('d', 'D'), None),
+    (special.radian, cython_special.radian, ('ddd',), None),
+    (special.rel_entr, cython_special.rel_entr, ('dd',), None),
+    (special.rgamma, cython_special.rgamma, ('d', 'D'), None),
+    (special.round, cython_special.round, ('d',), None),
+    (special.spherical_jn, cython_special.spherical_jn, ('ld', 'ldb', 'lD', 'lDb'),
+     "Python version supports negative reals; Cython version doesn't - see gh-21629"),
+    (special.spherical_yn, cython_special.spherical_yn, ('ld', 'ldb', 'lD', 'lDb'),
+     "Python version supports negative reals; Cython version doesn't - see gh-21629"),
+    (special.spherical_in, cython_special.spherical_in, ('ld', 'ldb', 'lD', 'lDb'),
+     "Python version supports negative reals; Cython version doesn't - see gh-21629"),
+    (special.spherical_kn, cython_special.spherical_kn, ('ld', 'ldb', 'lD', 'lDb'),
+     "Python version supports negative reals; Cython version doesn't - see gh-21629"),
+    (special.shichi, cython_special._shichi_pywrap, ('d', 'D'), None),
+    (special.sici, cython_special._sici_pywrap, ('d', 'D'), None),
+    (special.sindg, cython_special.sindg, ('d',), None),
+    (special.smirnov, cython_special.smirnov, ('ld', 'dd'), None),
+    (special.smirnovi, cython_special.smirnovi, ('ld', 'dd'), None),
+    (special.spence, cython_special.spence, ('d', 'D'), None),
+    (special.sph_harm, cython_special.sph_harm, ('lldd', 'dddd'), None),
+    (special.stdtr, cython_special.stdtr, ('dd',), None),
+    (special.stdtridf, cython_special.stdtridf, ('dd',), None),
+    (special.stdtrit, cython_special.stdtrit, ('dd',), None),
+    (special.struve, cython_special.struve, ('dd',), None),
+    (special.tandg, cython_special.tandg, ('d',), None),
+    (special.tklmbda, cython_special.tklmbda, ('dd',), None),
+    (special.voigt_profile, cython_special.voigt_profile, ('ddd',), None),
+    (special.wofz, cython_special.wofz, ('D',), None),
+    (special.wright_bessel, cython_special.wright_bessel, ('ddd',), None),
+    (special.wrightomega, cython_special.wrightomega, ('D',), None),
+    (special.xlog1py, cython_special.xlog1py, ('dd', 'DD'), None),
+    (special.xlogy, cython_special.xlogy, ('dd', 'DD'), None),
+    (special.y0, cython_special.y0, ('d',), None),
+    (special.y1, cython_special.y1, ('d',), None),
+    (special.yn, cython_special.yn, ('ld', 'dd'), None),
+    (special.yv, cython_special.yv, ('dd', 'dD'), None),
+    (special.yve, cython_special.yve, ('dd', 'dD'), None),
+    (special.zetac, cython_special.zetac, ('d',), None),
+    (special.owens_t, cython_special.owens_t, ('dd',), None)
+]
+
+
+IDS = [x[0].__name__ for x in PARAMS]
+
+
+def _generate_test_points(typecodes):
+    axes = tuple(TEST_POINTS[x] for x in typecodes)
+    pts = list(product(*axes))
+    return pts
+
+
+def test_cython_api_completeness():
+    # Check that everything is tested
+    for name in dir(cython_special):
+        func = getattr(cython_special, name)
+        if callable(func) and not name.startswith('_'):
+            for _, cyfun, _, _ in PARAMS:
+                if cyfun is func:
+                    break
+            else:
+                raise RuntimeError(f"{name} missing from tests!")
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.fail_slow(20)
+@pytest.mark.parametrize("param", PARAMS, ids=IDS)
+def test_cython_api(param):
+    pyfunc, cyfunc, specializations, knownfailure = param
+    if knownfailure:
+        pytest.xfail(reason=knownfailure)
+
+    # Check which parameters are expected to be fused types
+    max_params = max(len(spec) for spec in specializations)
+    values = [set() for _ in range(max_params)]
+    for typecodes in specializations:
+        for j, v in enumerate(typecodes):
+            values[j].add(v)
+    seen = set()
+    is_fused_code = [False] * len(values)
+    for j, v in enumerate(values):
+        vv = tuple(sorted(v))
+        if vv in seen:
+            continue
+        is_fused_code[j] = (len(v) > 1)
+        seen.add(vv)
+
+    # Check results
+    for typecodes in specializations:
+        # Pick the correct specialized function
+        signature = [CYTHON_SIGNATURE_MAP[code]
+                     for j, code in enumerate(typecodes)
+                     if is_fused_code[j]]
+
+        if signature:
+            cy_spec_func = cyfunc[tuple(signature)]
+        else:
+            signature = None
+            cy_spec_func = cyfunc
+
+        # Test it
+        pts = _generate_test_points(typecodes)
+        for pt in pts:
+            with suppress_warnings() as sup:
+                sup.filter(DeprecationWarning)
+                pyval = pyfunc(*pt)
+                cyval = cy_spec_func(*pt)
+            assert_allclose(cyval, pyval, err_msg=f"{pt} {typecodes} {signature}")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fc89a328cf20da0fd243ab7603cf316ecf2acb4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_data.py
@@ -0,0 +1,719 @@
+import importlib.resources
+
+import numpy as np
+from numpy.testing import suppress_warnings
+import pytest
+
+from scipy.special import (
+    lpn, lpmn, lpmv, lqn, lqmn, sph_harm, eval_legendre, eval_hermite,
+    eval_laguerre, eval_genlaguerre, binom, cbrt, expm1, log1p, zeta,
+    jn, jv, jvp, yn, yv, yvp, iv, ivp, kn, kv, kvp,
+    gamma, gammaln, gammainc, gammaincc, gammaincinv, gammainccinv, digamma,
+    beta, betainc, betaincinv, poch,
+    ellipe, ellipeinc, ellipk, ellipkm1, ellipkinc,
+    elliprc, elliprd, elliprf, elliprg, elliprj,
+    erf, erfc, erfinv, erfcinv, exp1, expi, expn,
+    bdtrik, btdtria, btdtrib, chndtr, gdtr, gdtrc, gdtrix, gdtrib,
+    nbdtrik, pdtrik, owens_t,
+    mathieu_a, mathieu_b, mathieu_cem, mathieu_sem, mathieu_modcem1,
+    mathieu_modsem1, mathieu_modcem2, mathieu_modsem2,
+    ellip_harm, ellip_harm_2, spherical_jn, spherical_yn, wright_bessel
+)
+from scipy.integrate import IntegrationWarning
+
+from scipy.special._testutils import FuncData
+
+
+# The npz files are generated, and hence may live in the build dir. We can only
+# access them through `importlib.resources`, not an explicit path from `__file__`
+_datadir = importlib.resources.files('scipy.special.tests.data')
+
+_boost_npz = _datadir.joinpath('boost.npz')
+with importlib.resources.as_file(_boost_npz) as f:
+    DATASETS_BOOST = np.load(f)
+
+_gsl_npz = _datadir.joinpath('gsl.npz')
+with importlib.resources.as_file(_gsl_npz) as f:
+    DATASETS_GSL = np.load(f)
+
+_local_npz = _datadir.joinpath('local.npz')
+with importlib.resources.as_file(_local_npz) as f:
+    DATASETS_LOCAL = np.load(f)
+
+
+def data(func, dataname, *a, **kw):
+    kw.setdefault('dataname', dataname)
+    return FuncData(func, DATASETS_BOOST[dataname], *a, **kw)
+
+
+def data_gsl(func, dataname, *a, **kw):
+    kw.setdefault('dataname', dataname)
+    return FuncData(func, DATASETS_GSL[dataname], *a, **kw)
+
+
+def data_local(func, dataname, *a, **kw):
+    kw.setdefault('dataname', dataname)
+    return FuncData(func, DATASETS_LOCAL[dataname], *a, **kw)
+
+
+# The functions lpn, lpmn, clpmn, and sph_harm appearing below are
+# deprecated in favor of legendre_p_all, assoc_legendre_p_all,
+# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn),
+# and sph_harm_y respectively. The deprecated functions listed above are
+# implemented as shims around their respective replacements. The replacements
+# are tested separately, but tests for the deprecated functions remain to
+# verify the correctness of the shims.
+
+
+def ellipk_(k):
+    return ellipk(k*k)
+
+
+def ellipkinc_(f, k):
+    return ellipkinc(f, k*k)
+
+
+def ellipe_(k):
+    return ellipe(k*k)
+
+
+def ellipeinc_(f, k):
+    return ellipeinc(f, k*k)
+
+
+def zeta_(x):
+    return zeta(x, 1.)
+
+
+def assoc_legendre_p_boost_(nu, mu, x):
+    # the boost test data is for integer orders only
+    return lpmv(mu, nu.astype(int), x)
+
+def legendre_p_via_assoc_(nu, x):
+    return lpmv(0, nu, x)
+
+def lpn_(n, x):
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        return lpn(n.astype('l'), x)[0][-1]
+
+def lqn_(n, x):
+    return lqn(n.astype('l'), x)[0][-1]
+
+def legendre_p_via_lpmn(n, x):
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        return lpmn(0, n, x)[0][0,-1]
+
+def legendre_q_via_lqmn(n, x):
+    return lqmn(0, n, x)[0][0,-1]
+
+def mathieu_ce_rad(m, q, x):
+    return mathieu_cem(m, q, x*180/np.pi)[0]
+
+
+def mathieu_se_rad(m, q, x):
+    return mathieu_sem(m, q, x*180/np.pi)[0]
+
+
+def mathieu_mc1_scaled(m, q, x):
+    # GSL follows a different normalization.
+    # We follow Abramowitz & Stegun, they apparently something else.
+    return mathieu_modcem1(m, q, x)[0] * np.sqrt(np.pi/2)
+
+
+def mathieu_ms1_scaled(m, q, x):
+    return mathieu_modsem1(m, q, x)[0] * np.sqrt(np.pi/2)
+
+
+def mathieu_mc2_scaled(m, q, x):
+    return mathieu_modcem2(m, q, x)[0] * np.sqrt(np.pi/2)
+
+
+def mathieu_ms2_scaled(m, q, x):
+    return mathieu_modsem2(m, q, x)[0] * np.sqrt(np.pi/2)
+
+def eval_legendre_ld(n, x):
+    return eval_legendre(n.astype('l'), x)
+
+def eval_legendre_dd(n, x):
+    return eval_legendre(n.astype('d'), x)
+
+def eval_hermite_ld(n, x):
+    return eval_hermite(n.astype('l'), x)
+
+def eval_laguerre_ld(n, x):
+    return eval_laguerre(n.astype('l'), x)
+
+def eval_laguerre_dd(n, x):
+    return eval_laguerre(n.astype('d'), x)
+
+def eval_genlaguerre_ldd(n, a, x):
+    return eval_genlaguerre(n.astype('l'), a, x)
+
+def eval_genlaguerre_ddd(n, a, x):
+    return eval_genlaguerre(n.astype('d'), a, x)
+
+def bdtrik_comp(y, n, p):
+    return bdtrik(1-y, n, p)
+
+def btdtria_comp(p, b, x):
+    return btdtria(1-p, b, x)
+
+def btdtrib_comp(a, p, x):
+    return btdtrib(a, 1-p, x)
+
+def gdtr_(p, x):
+    return gdtr(1.0, p, x)
+
+def gdtrc_(p, x):
+    return gdtrc(1.0, p, x)
+
+def gdtrix_(b, p):
+    return gdtrix(1.0, b, p)
+
+def gdtrix_comp(b, p):
+    return gdtrix(1.0, b, 1-p)
+
+def gdtrib_(p, x):
+    return gdtrib(1.0, p, x)
+
+def gdtrib_comp(p, x):
+    return gdtrib(1.0, 1-p, x)
+
+def nbdtrik_comp(y, n, p):
+    return nbdtrik(1-y, n, p)
+
+def pdtrik_comp(p, m):
+    return pdtrik(1-p, m)
+
+def poch_(z, m):
+    return 1.0 / poch(z, m)
+
+def poch_minus(z, m):
+    return 1.0 / poch(z, -m)
+
+def spherical_jn_(n, x):
+    return spherical_jn(n.astype('l'), x)
+
+def spherical_yn_(n, x):
+    return spherical_yn(n.astype('l'), x)
+
+def sph_harm_(m, n, theta, phi):
+    with suppress_warnings() as sup:
+        sup.filter(category=DeprecationWarning)
+        y = sph_harm(m, n, theta, phi)
+    return (y.real, y.imag)
+
+def cexpm1(x, y):
+    z = expm1(x + 1j*y)
+    return z.real, z.imag
+
+def clog1p(x, y):
+    z = log1p(x + 1j*y)
+    return z.real, z.imag
+
+
+BOOST_TESTS = [
+        data(assoc_legendre_p_boost_, 'assoc_legendre_p_ipp-assoc_legendre_p',
+             (0,1,2), 3, rtol=1e-11),
+
+        data(legendre_p_via_assoc_, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=1e-11),
+        data(legendre_p_via_assoc_, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=9.6e-14),
+        data(legendre_p_via_lpmn, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=5e-14, vectorized=False),
+        data(legendre_p_via_lpmn, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=3e-13, vectorized=False),
+        data(lpn_, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=5e-14, vectorized=False),
+        data(lpn_, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=3e-13, vectorized=False),
+        data(eval_legendre_ld, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=6e-14),
+        data(eval_legendre_ld, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=2e-13),
+        data(eval_legendre_dd, 'legendre_p_ipp-legendre_p',
+             (0,1), 2, rtol=2e-14),
+        data(eval_legendre_dd, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 2, rtol=2e-13),
+
+        data(lqn_, 'legendre_p_ipp-legendre_p',
+             (0,1), 3, rtol=2e-14, vectorized=False),
+        data(lqn_, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 3, rtol=2e-12, vectorized=False),
+        data(legendre_q_via_lqmn, 'legendre_p_ipp-legendre_p',
+             (0,1), 3, rtol=2e-14, vectorized=False),
+        data(legendre_q_via_lqmn, 'legendre_p_large_ipp-legendre_p_large',
+             (0,1), 3, rtol=2e-12, vectorized=False),
+
+        data(beta, 'beta_exp_data_ipp-beta_exp_data',
+             (0,1), 2, rtol=1e-13),
+        data(beta, 'beta_exp_data_ipp-beta_exp_data',
+             (0,1), 2, rtol=1e-13),
+        data(beta, 'beta_med_data_ipp-beta_med_data',
+             (0,1), 2, rtol=5e-13),
+
+        data(betainc, 'ibeta_small_data_ipp-ibeta_small_data',
+             (0,1,2), 5, rtol=6e-15),
+        data(betainc, 'ibeta_data_ipp-ibeta_data',
+             (0,1,2), 5, rtol=5e-13),
+        data(betainc, 'ibeta_int_data_ipp-ibeta_int_data',
+             (0,1,2), 5, rtol=2e-14),
+        data(betainc, 'ibeta_large_data_ipp-ibeta_large_data',
+             (0,1,2), 5, rtol=4e-10),
+
+        data(betaincinv, 'ibeta_inv_data_ipp-ibeta_inv_data',
+             (0,1,2), 3, rtol=1e-5),
+
+        data(btdtria, 'ibeta_inva_data_ipp-ibeta_inva_data',
+             (2,0,1), 3, rtol=5e-9),
+        data(btdtria_comp, 'ibeta_inva_data_ipp-ibeta_inva_data',
+             (2,0,1), 4, rtol=5e-9),
+
+        data(btdtrib, 'ibeta_inva_data_ipp-ibeta_inva_data',
+             (0,2,1), 5, rtol=5e-9),
+        data(btdtrib_comp, 'ibeta_inva_data_ipp-ibeta_inva_data',
+             (0,2,1), 6, rtol=5e-9),
+
+        data(binom, 'binomial_data_ipp-binomial_data',
+             (0,1), 2, rtol=1e-13),
+        data(binom, 'binomial_large_data_ipp-binomial_large_data',
+             (0,1), 2, rtol=5e-13),
+
+        data(bdtrik, 'binomial_quantile_ipp-binomial_quantile_data',
+             (2,0,1), 3, rtol=5e-9),
+        data(bdtrik_comp, 'binomial_quantile_ipp-binomial_quantile_data',
+             (2,0,1), 4, rtol=5e-9),
+
+        data(nbdtrik, 'negative_binomial_quantile_ipp-negative_binomial_quantile_data',
+             (2,0,1), 3, rtol=4e-9),
+        data(nbdtrik_comp,
+             'negative_binomial_quantile_ipp-negative_binomial_quantile_data',
+             (2,0,1), 4, rtol=4e-9),
+
+        data(pdtrik, 'poisson_quantile_ipp-poisson_quantile_data',
+             (1,0), 2, rtol=3e-9),
+        data(pdtrik_comp, 'poisson_quantile_ipp-poisson_quantile_data',
+             (1,0), 3, rtol=4e-9),
+
+        data(cbrt, 'cbrt_data_ipp-cbrt_data', 1, 0),
+
+        data(digamma, 'digamma_data_ipp-digamma_data', 0, 1),
+        data(digamma, 'digamma_data_ipp-digamma_data', 0j, 1),
+        data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0, 1, rtol=2e-13),
+        data(digamma, 'digamma_neg_data_ipp-digamma_neg_data', 0j, 1, rtol=1e-13),
+        data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0, 1, rtol=1e-15),
+        data(digamma, 'digamma_root_data_ipp-digamma_root_data', 0j, 1, rtol=1e-15),
+        data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0, 1, rtol=1e-15),
+        data(digamma, 'digamma_small_data_ipp-digamma_small_data', 0j, 1, rtol=1e-14),
+
+        data(ellipk_, 'ellint_k_data_ipp-ellint_k_data', 0, 1),
+        data(ellipkinc_, 'ellint_f_data_ipp-ellint_f_data', (0,1), 2, rtol=1e-14),
+        data(ellipe_, 'ellint_e_data_ipp-ellint_e_data', 0, 1),
+        data(ellipeinc_, 'ellint_e2_data_ipp-ellint_e2_data', (0,1), 2, rtol=1e-14),
+
+        data(erf, 'erf_data_ipp-erf_data', 0, 1),
+        data(erf, 'erf_data_ipp-erf_data', 0j, 1, rtol=1e-13),
+        data(erfc, 'erf_data_ipp-erf_data', 0, 2, rtol=6e-15),
+        data(erf, 'erf_large_data_ipp-erf_large_data', 0, 1),
+        data(erf, 'erf_large_data_ipp-erf_large_data', 0j, 1),
+        data(erfc, 'erf_large_data_ipp-erf_large_data', 0, 2, rtol=4e-14),
+        data(erf, 'erf_small_data_ipp-erf_small_data', 0, 1),
+        data(erf, 'erf_small_data_ipp-erf_small_data', 0j, 1, rtol=1e-13),
+        data(erfc, 'erf_small_data_ipp-erf_small_data', 0, 2),
+
+        data(erfinv, 'erf_inv_data_ipp-erf_inv_data', 0, 1),
+        data(erfcinv, 'erfc_inv_data_ipp-erfc_inv_data', 0, 1),
+        data(erfcinv, 'erfc_inv_big_data_ipp-erfc_inv_big_data', 0, 1,
+             param_filter=(lambda s: s > 0)),
+
+        data(exp1, 'expint_1_data_ipp-expint_1_data', 1, 2, rtol=1e-13),
+        data(exp1, 'expint_1_data_ipp-expint_1_data', 1j, 2, rtol=5e-9),
+        data(expi, 'expinti_data_ipp-expinti_data', 0, 1, rtol=1e-13),
+        data(expi, 'expinti_data_double_ipp-expinti_data_double', 0, 1, rtol=1e-13),
+        data(expi, 'expinti_data_long_ipp-expinti_data_long', 0, 1),
+
+        data(expn, 'expint_small_data_ipp-expint_small_data', (0,1), 2),
+        data(expn, 'expint_data_ipp-expint_data', (0,1), 2, rtol=1e-14),
+
+        data(gamma, 'test_gamma_data_ipp-near_0', 0, 1),
+        data(gamma, 'test_gamma_data_ipp-near_1', 0, 1),
+        data(gamma, 'test_gamma_data_ipp-near_2', 0, 1),
+        data(gamma, 'test_gamma_data_ipp-near_m10', 0, 1),
+        data(gamma, 'test_gamma_data_ipp-near_m55', 0, 1, rtol=7e-12),
+        data(gamma, 'test_gamma_data_ipp-factorials', 0, 1, rtol=4e-14),
+        data(gamma, 'test_gamma_data_ipp-near_0', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-near_1', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-near_2', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-near_m10', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-near_m55', 0j, 1, rtol=2e-9),
+        data(gamma, 'test_gamma_data_ipp-factorials', 0j, 1, rtol=2e-13),
+        data(gammaln, 'test_gamma_data_ipp-near_0', 0, 2, rtol=5e-11),
+        data(gammaln, 'test_gamma_data_ipp-near_1', 0, 2, rtol=5e-11),
+        data(gammaln, 'test_gamma_data_ipp-near_2', 0, 2, rtol=2e-10),
+        data(gammaln, 'test_gamma_data_ipp-near_m10', 0, 2, rtol=5e-11),
+        data(gammaln, 'test_gamma_data_ipp-near_m55', 0, 2, rtol=5e-11),
+        data(gammaln, 'test_gamma_data_ipp-factorials', 0, 2),
+
+        data(gammainc, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=5e-15),
+        data(gammainc, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13),
+        data(gammainc, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13),
+        data(gammainc, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=1e-12),
+
+        data(gdtr_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 5, rtol=1e-13),
+        data(gdtr_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 5, rtol=2e-13),
+        data(gdtr_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 5, rtol=2e-13),
+        data(gdtr_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 5, rtol=2e-9),
+
+        data(gammaincc, 'igamma_small_data_ipp-igamma_small_data',
+             (0,1), 3, rtol=1e-13),
+        data(gammaincc, 'igamma_med_data_ipp-igamma_med_data',
+             (0,1), 3, rtol=2e-13),
+        data(gammaincc, 'igamma_int_data_ipp-igamma_int_data',
+             (0,1), 3, rtol=4e-14),
+        data(gammaincc, 'igamma_big_data_ipp-igamma_big_data',
+             (0,1), 3, rtol=1e-11),
+
+        data(gdtrc_, 'igamma_small_data_ipp-igamma_small_data', (0,1), 3, rtol=1e-13),
+        data(gdtrc_, 'igamma_med_data_ipp-igamma_med_data', (0,1), 3, rtol=2e-13),
+        data(gdtrc_, 'igamma_int_data_ipp-igamma_int_data', (0,1), 3, rtol=4e-14),
+        data(gdtrc_, 'igamma_big_data_ipp-igamma_big_data', (0,1), 3, rtol=1e-11),
+
+        data(gdtrib_, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 2, rtol=5e-9),
+        data(gdtrib_comp, 'igamma_inva_data_ipp-igamma_inva_data', (1,0), 3, rtol=5e-9),
+
+        data(poch_, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data',
+             (0,1), 2, rtol=2e-13),
+        data(poch_, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int',
+             (0,1), 2,),
+        data(poch_, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2',
+             (0,1), 2,),
+        data(poch_minus, 'tgamma_delta_ratio_data_ipp-tgamma_delta_ratio_data',
+             (0,1), 3, rtol=2e-13),
+        data(poch_minus, 'tgamma_delta_ratio_int_ipp-tgamma_delta_ratio_int',
+             (0,1), 3),
+        data(poch_minus, 'tgamma_delta_ratio_int2_ipp-tgamma_delta_ratio_int2',
+             (0,1), 3),
+
+        data(eval_hermite_ld, 'hermite_ipp-hermite',
+             (0,1), 2, rtol=2e-14),
+
+        data(eval_laguerre_ld, 'laguerre2_ipp-laguerre2',
+             (0,1), 2, rtol=7e-12),
+        data(eval_laguerre_dd, 'laguerre2_ipp-laguerre2',
+             (0,1), 2, knownfailure='hyp2f1 insufficiently accurate.'),
+        data(eval_genlaguerre_ldd, 'laguerre3_ipp-laguerre3',
+             (0,1,2), 3, rtol=2e-13),
+        data(eval_genlaguerre_ddd, 'laguerre3_ipp-laguerre3',
+             (0,1,2), 3, knownfailure='hyp2f1 insufficiently accurate.'),
+
+        data(log1p, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 1),
+        data(expm1, 'log1p_expm1_data_ipp-log1p_expm1_data', 0, 2),
+
+        data(iv, 'bessel_i_data_ipp-bessel_i_data',
+             (0,1), 2, rtol=1e-12),
+        data(iv, 'bessel_i_data_ipp-bessel_i_data',
+             (0,1j), 2, rtol=2e-10, atol=1e-306),
+        data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data',
+             (0,1), 2, rtol=1e-9),
+        data(iv, 'bessel_i_int_data_ipp-bessel_i_int_data',
+             (0,1j), 2, rtol=2e-10),
+
+        data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data',
+             (0,1), 2, rtol=1.2e-13),
+        data(ivp, 'bessel_i_prime_int_data_ipp-bessel_i_prime_int_data',
+             (0,1j), 2, rtol=1.2e-13, atol=1e-300),
+
+        data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
+        data(jn, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
+        data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1), 2, rtol=6e-11),
+        data(jn, 'bessel_j_large_data_ipp-bessel_j_large_data', (0,1j), 2, rtol=6e-11),
+
+        data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1), 2, rtol=1e-12),
+        data(jv, 'bessel_j_int_data_ipp-bessel_j_int_data', (0,1j), 2, rtol=1e-12),
+        data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1), 2, rtol=1e-12),
+        data(jv, 'bessel_j_data_ipp-bessel_j_data', (0,1j), 2, rtol=1e-12),
+
+        data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data',
+             (0,1), 2, rtol=1e-13),
+        data(jvp, 'bessel_j_prime_int_data_ipp-bessel_j_prime_int_data',
+             (0,1j), 2, rtol=1e-13),
+        data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data',
+             (0,1), 2, rtol=1e-11),
+        data(jvp, 'bessel_j_prime_large_data_ipp-bessel_j_prime_large_data',
+             (0,1j), 2, rtol=2e-11),
+
+        data(kn, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12),
+
+        data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1), 2, rtol=1e-12),
+        data(kv, 'bessel_k_int_data_ipp-bessel_k_int_data', (0,1j), 2, rtol=1e-12),
+        data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1), 2, rtol=1e-12),
+        data(kv, 'bessel_k_data_ipp-bessel_k_data', (0,1j), 2, rtol=1e-12),
+
+        data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data',
+             (0,1), 2, rtol=3e-14),
+        data(kvp, 'bessel_k_prime_int_data_ipp-bessel_k_prime_int_data',
+             (0,1j), 2, rtol=3e-14),
+        data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1), 2, rtol=7e-14),
+        data(kvp, 'bessel_k_prime_data_ipp-bessel_k_prime_data', (0,1j), 2, rtol=7e-14),
+
+        data(yn, 'bessel_y01_data_ipp-bessel_y01_data', (0,1), 2, rtol=1e-12),
+        data(yn, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
+
+        data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1), 2, rtol=1e-12),
+        data(yv, 'bessel_yn_data_ipp-bessel_yn_data', (0,1j), 2, rtol=1e-12),
+        data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1), 2, rtol=1e-10),
+        data(yv, 'bessel_yv_data_ipp-bessel_yv_data', (0,1j), 2, rtol=1e-10),
+
+        data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data',
+             (0, 1), 2, rtol=4e-9),
+        data(yvp, 'bessel_yv_prime_data_ipp-bessel_yv_prime_data',
+             (0, 1j), 2, rtol=4e-9),
+
+        data(zeta_, 'zeta_data_ipp-zeta_data', 0, 1,
+             param_filter=(lambda s: s > 1)),
+        data(zeta_, 'zeta_neg_data_ipp-zeta_neg_data', 0, 1,
+             param_filter=(lambda s: s > 1)),
+        data(zeta_, 'zeta_1_up_data_ipp-zeta_1_up_data', 0, 1,
+             param_filter=(lambda s: s > 1)),
+        data(zeta_, 'zeta_1_below_data_ipp-zeta_1_below_data', 0, 1,
+             param_filter=(lambda s: s > 1)),
+
+        data(gammaincinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data',
+             (0,1), 2, rtol=1e-11),
+        data(gammaincinv, 'gamma_inv_data_ipp-gamma_inv_data',
+             (0,1), 2, rtol=1e-14),
+        data(gammaincinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data',
+             (0,1), 2, rtol=1e-11),
+
+        data(gammainccinv, 'gamma_inv_small_data_ipp-gamma_inv_small_data',
+             (0,1), 3, rtol=1e-12),
+        data(gammainccinv, 'gamma_inv_data_ipp-gamma_inv_data',
+             (0,1), 3, rtol=1e-14),
+        data(gammainccinv, 'gamma_inv_big_data_ipp-gamma_inv_big_data',
+             (0,1), 3, rtol=1e-14),
+
+        data(gdtrix_, 'gamma_inv_small_data_ipp-gamma_inv_small_data',
+             (0,1), 2, rtol=3e-13, knownfailure='gdtrix unflow some points'),
+        data(gdtrix_, 'gamma_inv_data_ipp-gamma_inv_data',
+             (0,1), 2, rtol=3e-15),
+        data(gdtrix_, 'gamma_inv_big_data_ipp-gamma_inv_big_data',
+             (0,1), 2),
+        data(gdtrix_comp, 'gamma_inv_small_data_ipp-gamma_inv_small_data',
+             (0,1), 2, knownfailure='gdtrix bad some points'),
+        data(gdtrix_comp, 'gamma_inv_data_ipp-gamma_inv_data',
+             (0,1), 3, rtol=6e-15),
+        data(gdtrix_comp, 'gamma_inv_big_data_ipp-gamma_inv_big_data',
+             (0,1), 3),
+
+        data(chndtr, 'nccs_ipp-nccs',
+             (2,0,1), 3, rtol=3e-5),
+        data(chndtr, 'nccs_big_ipp-nccs_big',
+             (2,0,1), 3, rtol=5e-4, knownfailure='chndtr inaccurate some points'),
+
+        data(sph_harm_, 'spherical_harmonic_ipp-spherical_harmonic',
+             (1,0,3,2), (4,5), rtol=5e-11,
+             param_filter=(lambda p: np.ones(p.shape, '?'),
+                           lambda p: np.ones(p.shape, '?'),
+                           lambda p: np.logical_and(p < 2*np.pi, p >= 0),
+                           lambda p: np.logical_and(p < np.pi, p >= 0))),
+
+        data(spherical_jn_, 'sph_bessel_data_ipp-sph_bessel_data',
+             (0,1), 2, rtol=1e-13),
+        data(spherical_yn_, 'sph_neumann_data_ipp-sph_neumann_data',
+             (0,1), 2, rtol=8e-15),
+
+        data(owens_t, 'owens_t_ipp-owens_t',
+             (0, 1), 2, rtol=5e-14),
+        data(owens_t, 'owens_t_large_data_ipp-owens_t_large_data',
+             (0, 1), 2, rtol=8e-12),
+
+        # -- test data exists in boost but is not used in scipy --
+
+        # ibeta_derivative_data_ipp/ibeta_derivative_data.txt
+        # ibeta_derivative_int_data_ipp/ibeta_derivative_int_data.txt
+        # ibeta_derivative_large_data_ipp/ibeta_derivative_large_data.txt
+        # ibeta_derivative_small_data_ipp/ibeta_derivative_small_data.txt
+
+        # bessel_y01_prime_data_ipp/bessel_y01_prime_data.txt
+        # bessel_yn_prime_data_ipp/bessel_yn_prime_data.txt
+        # sph_bessel_prime_data_ipp/sph_bessel_prime_data.txt
+        # sph_neumann_prime_data_ipp/sph_neumann_prime_data.txt
+
+        # ellint_d2_data_ipp/ellint_d2_data.txt
+        # ellint_d_data_ipp/ellint_d_data.txt
+        # ellint_pi2_data_ipp/ellint_pi2_data.txt
+        # ellint_pi3_data_ipp/ellint_pi3_data.txt
+        # ellint_pi3_large_data_ipp/ellint_pi3_large_data.txt
+        data(elliprc, 'ellint_rc_data_ipp-ellint_rc_data', (0, 1), 2,
+             rtol=5e-16),
+        data(elliprd, 'ellint_rd_data_ipp-ellint_rd_data', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprd, 'ellint_rd_0xy_ipp-ellint_rd_0xy', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprd, 'ellint_rd_0yy_ipp-ellint_rd_0yy', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprd, 'ellint_rd_xxx_ipp-ellint_rd_xxx', (0, 1, 2), 3,
+             rtol=5e-16),
+        # Some of the following rtol for elliprd may be larger than 5e-16 to
+        # work around some hard cases in the Boost test where we get slightly
+        # larger error than the ideal bound when the x (==y) input is close to
+        # zero.
+        # Also the accuracy on 32-bit builds with g++ may suffer from excess
+        # loss of precision; see GCC bugzilla 323
+        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=323
+        data(elliprd, 'ellint_rd_xxz_ipp-ellint_rd_xxz', (0, 1, 2), 3,
+             rtol=6.5e-16),
+        data(elliprd, 'ellint_rd_xyy_ipp-ellint_rd_xyy', (0, 1, 2), 3,
+             rtol=6e-16),
+        data(elliprf, 'ellint_rf_data_ipp-ellint_rf_data', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprf, 'ellint_rf_xxx_ipp-ellint_rf_xxx', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprf, 'ellint_rf_xyy_ipp-ellint_rf_xyy', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprf, 'ellint_rf_xy0_ipp-ellint_rf_xy0', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprf, 'ellint_rf_0yy_ipp-ellint_rf_0yy', (0, 1, 2), 3,
+             rtol=5e-16),
+        # The accuracy of R_G is primarily limited by R_D that is used
+        # internally. It is generally worse than R_D. Notice that we increased
+        # the rtol for R_G here. The cases with duplicate arguments are
+        # slightly less likely to be unbalanced (at least two arguments are
+        # already balanced) so the error bound is slightly better. Again,
+        # precision with g++ 32-bit is even worse.
+        data(elliprg, 'ellint_rg_ipp-ellint_rg', (0, 1, 2), 3,
+             rtol=8.0e-16),
+        data(elliprg, 'ellint_rg_xxx_ipp-ellint_rg_xxx', (0, 1, 2), 3,
+             rtol=6e-16),
+        data(elliprg, 'ellint_rg_xyy_ipp-ellint_rg_xyy', (0, 1, 2), 3,
+             rtol=7.5e-16),
+        data(elliprg, 'ellint_rg_xy0_ipp-ellint_rg_xy0', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprg, 'ellint_rg_00x_ipp-ellint_rg_00x', (0, 1, 2), 3,
+             rtol=5e-16),
+        data(elliprj, 'ellint_rj_data_ipp-ellint_rj_data', (0, 1, 2, 3), 4,
+             rtol=5e-16, atol=1e-25,
+             param_filter=(lambda s: s <= 5e-26,)),
+        # ellint_rc_data_ipp/ellint_rc_data.txt
+        # ellint_rd_0xy_ipp/ellint_rd_0xy.txt
+        # ellint_rd_0yy_ipp/ellint_rd_0yy.txt
+        # ellint_rd_data_ipp/ellint_rd_data.txt
+        # ellint_rd_xxx_ipp/ellint_rd_xxx.txt
+        # ellint_rd_xxz_ipp/ellint_rd_xxz.txt
+        # ellint_rd_xyy_ipp/ellint_rd_xyy.txt
+        # ellint_rf_0yy_ipp/ellint_rf_0yy.txt
+        # ellint_rf_data_ipp/ellint_rf_data.txt
+        # ellint_rf_xxx_ipp/ellint_rf_xxx.txt
+        # ellint_rf_xy0_ipp/ellint_rf_xy0.txt
+        # ellint_rf_xyy_ipp/ellint_rf_xyy.txt
+        # ellint_rg_00x_ipp/ellint_rg_00x.txt
+        # ellint_rg_ipp/ellint_rg.txt
+        # ellint_rg_xxx_ipp/ellint_rg_xxx.txt
+        # ellint_rg_xy0_ipp/ellint_rg_xy0.txt
+        # ellint_rg_xyy_ipp/ellint_rg_xyy.txt
+        # ellint_rj_data_ipp/ellint_rj_data.txt
+        # ellint_rj_e2_ipp/ellint_rj_e2.txt
+        # ellint_rj_e3_ipp/ellint_rj_e3.txt
+        # ellint_rj_e4_ipp/ellint_rj_e4.txt
+        # ellint_rj_zp_ipp/ellint_rj_zp.txt
+
+        # jacobi_elliptic_ipp/jacobi_elliptic.txt
+        # jacobi_elliptic_small_ipp/jacobi_elliptic_small.txt
+        # jacobi_large_phi_ipp/jacobi_large_phi.txt
+        # jacobi_near_1_ipp/jacobi_near_1.txt
+        # jacobi_zeta_big_phi_ipp/jacobi_zeta_big_phi.txt
+        # jacobi_zeta_data_ipp/jacobi_zeta_data.txt
+
+        # heuman_lambda_data_ipp/heuman_lambda_data.txt
+
+        # hypergeometric_0F2_ipp/hypergeometric_0F2.txt
+        # hypergeometric_1F1_big_ipp/hypergeometric_1F1_big.txt
+        # hypergeometric_1F1_ipp/hypergeometric_1F1.txt
+        # hypergeometric_1F1_small_random_ipp/hypergeometric_1F1_small_random.txt
+        # hypergeometric_1F2_ipp/hypergeometric_1F2.txt
+        # hypergeometric_1f1_large_regularized_ipp/hypergeometric_1f1_large_regularized.txt  # noqa: E501
+        # hypergeometric_1f1_log_large_unsolved_ipp/hypergeometric_1f1_log_large_unsolved.txt  # noqa: E501
+        # hypergeometric_2F0_half_ipp/hypergeometric_2F0_half.txt
+        # hypergeometric_2F0_integer_a2_ipp/hypergeometric_2F0_integer_a2.txt
+        # hypergeometric_2F0_ipp/hypergeometric_2F0.txt
+        # hypergeometric_2F0_large_z_ipp/hypergeometric_2F0_large_z.txt
+        # hypergeometric_2F1_ipp/hypergeometric_2F1.txt
+        # hypergeometric_2F2_ipp/hypergeometric_2F2.txt
+
+        # ncbeta_big_ipp/ncbeta_big.txt
+        # nct_small_delta_ipp/nct_small_delta.txt
+        # nct_asym_ipp/nct_asym.txt
+        # ncbeta_ipp/ncbeta.txt
+
+        # powm1_data_ipp/powm1_big_data.txt
+        # powm1_sqrtp1m1_test_hpp/sqrtp1m1_data.txt
+
+        # sinc_data_ipp/sinc_data.txt
+
+        # test_gamma_data_ipp/gammap1m1_data.txt
+        # tgamma_ratio_data_ipp/tgamma_ratio_data.txt
+
+        # trig_data_ipp/trig_data.txt
+        # trig_data2_ipp/trig_data2.txt
+]
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.parametrize('test', BOOST_TESTS, ids=repr)
+def test_boost(test):
+     _test_factory(test)
+
+
+GSL_TESTS = [
+        data_gsl(mathieu_a, 'mathieu_ab', (0, 1), 2, rtol=1e-13, atol=1e-13),
+        data_gsl(mathieu_b, 'mathieu_ab', (0, 1), 3, rtol=1e-13, atol=1e-13),
+
+        # Also the GSL output has limited accuracy...
+        data_gsl(mathieu_ce_rad, 'mathieu_ce_se', (0, 1, 2), 3, rtol=1e-7, atol=1e-13),
+        data_gsl(mathieu_se_rad, 'mathieu_ce_se', (0, 1, 2), 4, rtol=1e-7, atol=1e-13),
+
+        data_gsl(mathieu_mc1_scaled, 'mathieu_mc_ms',
+                 (0, 1, 2), 3, rtol=1e-7, atol=1e-13),
+        data_gsl(mathieu_ms1_scaled, 'mathieu_mc_ms',
+                 (0, 1, 2), 4, rtol=1e-7, atol=1e-13),
+
+        data_gsl(mathieu_mc2_scaled, 'mathieu_mc_ms',
+                 (0, 1, 2), 5, rtol=1e-7, atol=1e-13),
+        data_gsl(mathieu_ms2_scaled, 'mathieu_mc_ms',
+                 (0, 1, 2), 6, rtol=1e-7, atol=1e-13),
+]
+
+
+@pytest.mark.parametrize('test', GSL_TESTS, ids=repr)
+def test_gsl(test):
+    _test_factory(test)
+
+
+LOCAL_TESTS = [
+    data_local(ellipkinc, 'ellipkinc_neg_m', (0, 1), 2),
+    data_local(ellipkm1, 'ellipkm1', 0, 1),
+    data_local(ellipeinc, 'ellipeinc_neg_m', (0, 1), 2),
+    data_local(clog1p, 'log1p_expm1_complex', (0,1), (2,3), rtol=1e-14),
+    data_local(cexpm1, 'log1p_expm1_complex', (0,1), (4,5), rtol=1e-14),
+    data_local(gammainc, 'gammainc', (0, 1), 2, rtol=1e-12),
+    data_local(gammaincc, 'gammaincc', (0, 1), 2, rtol=1e-11),
+    data_local(ellip_harm_2, 'ellip',(0, 1, 2, 3, 4), 6, rtol=1e-10, atol=1e-13),
+    data_local(ellip_harm, 'ellip',(0, 1, 2, 3, 4), 5, rtol=1e-10, atol=1e-13),
+    data_local(wright_bessel, 'wright_bessel', (0, 1, 2), 3, rtol=1e-11),
+]
+
+
+@pytest.mark.parametrize('test', LOCAL_TESTS, ids=repr)
+def test_local(test):
+    _test_factory(test)
+
+
+def _test_factory(test, dtype=np.float64):
+    """Boost test"""
+    with suppress_warnings() as sup:
+        sup.filter(IntegrationWarning, "The occurrence of roundoff error is detected")
+        with np.errstate(all='ignore'):
+            test.check(dtype=dtype)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py
new file mode 100644
index 0000000000000000000000000000000000000000..6da2c8ddddd7341cbb777216e9f2f3cce536a51e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_dd.py
@@ -0,0 +1,42 @@
+# Tests for a few of the "double-double" C++ functions defined in
+# special/cephes/dd_real.h. Prior to gh-20390 which translated these
+# functions from C to C++, there were test cases for _dd_expm1. It
+# was determined that this function is not used anywhere internally
+# in SciPy, so this function was not translated.
+
+
+import pytest
+from numpy.testing import assert_allclose
+from scipy.special._test_internal import _dd_exp, _dd_log
+
+
+# Each tuple in test_data contains:
+#   (dd_func, xhi, xlo, expected_yhi, expected_ylo)
+# The expected values were computed with mpmath, e.g.
+#
+#   import mpmath
+#   mpmath.mp.dps = 100
+#   xhi = 10.0
+#   xlo = 0.0
+#   x = mpmath.mpf(xhi) + mpmath.mpf(xlo)
+#   y = mpmath.log(x)
+#   expected_yhi = float(y)
+#   expected_ylo = float(y - expected_yhi)
+#
+test_data = [
+    (_dd_exp, -0.3333333333333333, -1.850371707708594e-17,
+     0.7165313105737893, -2.0286948382455594e-17),
+    (_dd_exp, 0.0, 0.0, 1.0, 0.0),
+    (_dd_exp, 10.0, 0.0, 22026.465794806718, -1.3780134700517372e-12),
+    (_dd_log, 0.03125, 0.0, -3.4657359027997265, -4.930038229799327e-18),
+    (_dd_log, 10.0, 0.0, 2.302585092994046, -2.1707562233822494e-16),
+]
+
+
+@pytest.mark.parametrize('dd_func, xhi, xlo, expected_yhi, expected_ylo',
+                         test_data)
+def test_dd(dd_func, xhi, xlo, expected_yhi, expected_ylo):
+    yhi, ylo = dd_func(xhi, xlo)
+    assert yhi == expected_yhi, (f"high double ({yhi}) does not equal the "
+                                 f"expected value {expected_yhi}")
+    assert_allclose(ylo, expected_ylo, rtol=5e-15)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7f27dc7b71c1ae928b4bdd8bd987df9ca420bab
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_digamma.py
@@ -0,0 +1,45 @@
+import numpy as np
+from numpy import pi, log, sqrt
+from numpy.testing import assert_, assert_equal
+
+from scipy.special._testutils import FuncData
+import scipy.special as sc
+
+# Euler-Mascheroni constant
+euler = 0.57721566490153286
+
+
+def test_consistency():
+    # Make sure the implementation of digamma for real arguments
+    # agrees with the implementation of digamma for complex arguments.
+
+    # It's all poles after -1e16
+    x = np.r_[-np.logspace(15, -30, 200), np.logspace(-30, 300, 200)]
+    dataset = np.vstack((x + 0j, sc.digamma(x))).T
+    FuncData(sc.digamma, dataset, 0, 1, rtol=5e-14, nan_ok=True).check()
+
+
+def test_special_values():
+    # Test special values from Gauss's digamma theorem. See
+    #
+    # https://en.wikipedia.org/wiki/Digamma_function
+
+    dataset = [
+        (1, -euler),
+        (0.5, -2*log(2) - euler),
+        (1/3, -pi/(2*sqrt(3)) - 3*log(3)/2 - euler),
+        (1/4, -pi/2 - 3*log(2) - euler),
+        (1/6, -pi*sqrt(3)/2 - 2*log(2) - 3*log(3)/2 - euler),
+        (1/8,
+         -pi/2 - 4*log(2) - (pi + log(2 + sqrt(2)) - log(2 - sqrt(2)))/sqrt(2) - euler)
+    ]
+
+    dataset = np.asarray(dataset)
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check()
+
+
+def test_nonfinite():
+    pts = [0.0, -0.0, np.inf]
+    std = [-np.inf, np.inf, np.inf]
+    assert_equal(sc.digamma(pts), std)
+    assert_(all(np.isnan(sc.digamma([-np.inf, -1]))))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cfb6530e2fd80d2c261af960f42c974e1e1b26e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ellip_harm.py
@@ -0,0 +1,278 @@
+#
+# Tests for the Ellipsoidal Harmonic Function,
+# Distributed under the same license as SciPy itself.
+#
+
+import numpy as np
+from numpy.testing import (assert_equal, assert_almost_equal, assert_allclose,
+                           assert_, suppress_warnings)
+from scipy.special._testutils import assert_func_equal
+from scipy.special import ellip_harm, ellip_harm_2, ellip_normal
+from scipy.integrate import IntegrationWarning
+from numpy import sqrt, pi
+
+
+def test_ellip_potential():
+    def change_coefficient(lambda1, mu, nu, h2, k2):
+        x = sqrt(lambda1**2*mu**2*nu**2/(h2*k2))
+        y = sqrt((lambda1**2 - h2)*(mu**2 - h2)*(h2 - nu**2)/(h2*(k2 - h2)))
+        z = sqrt((lambda1**2 - k2)*(k2 - mu**2)*(k2 - nu**2)/(k2*(k2 - h2)))
+        return x, y, z
+
+    def solid_int_ellip(lambda1, mu, nu, n, p, h2, k2):
+        return (ellip_harm(h2, k2, n, p, lambda1)*ellip_harm(h2, k2, n, p, mu)
+               * ellip_harm(h2, k2, n, p, nu))
+
+    def solid_int_ellip2(lambda1, mu, nu, n, p, h2, k2):
+        return (ellip_harm_2(h2, k2, n, p, lambda1)
+                * ellip_harm(h2, k2, n, p, mu)*ellip_harm(h2, k2, n, p, nu))
+
+    def summation(lambda1, mu1, nu1, lambda2, mu2, nu2, h2, k2):
+        tol = 1e-8
+        sum1 = 0
+        for n in range(20):
+            xsum = 0
+            for p in range(1, 2*n+2):
+                xsum += (4*pi*(solid_int_ellip(lambda2, mu2, nu2, n, p, h2, k2)
+                    * solid_int_ellip2(lambda1, mu1, nu1, n, p, h2, k2)) /
+                    (ellip_normal(h2, k2, n, p)*(2*n + 1)))
+            if abs(xsum) < 0.1*tol*abs(sum1):
+                break
+            sum1 += xsum
+        return sum1, xsum
+
+    def potential(lambda1, mu1, nu1, lambda2, mu2, nu2, h2, k2):
+        x1, y1, z1 = change_coefficient(lambda1, mu1, nu1, h2, k2)
+        x2, y2, z2 = change_coefficient(lambda2, mu2, nu2, h2, k2)
+        res = sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)
+        return 1/res
+
+    pts = [
+        (120, sqrt(19), 2, 41, sqrt(17), 2, 15, 25),
+        (120, sqrt(16), 3.2, 21, sqrt(11), 2.9, 11, 20),
+       ]
+
+    with suppress_warnings() as sup:
+        sup.filter(IntegrationWarning, "The occurrence of roundoff error")
+        sup.filter(IntegrationWarning, "The maximum number of subdivisions")
+
+        for p in pts:
+            err_msg = repr(p)
+            exact = potential(*p)
+            result, last_term = summation(*p)
+            assert_allclose(exact, result, atol=0, rtol=1e-8, err_msg=err_msg)
+            assert_(abs(result - exact) < 10*abs(last_term), err_msg)
+
+
+def test_ellip_norm():
+
+    def G01(h2, k2):
+        return 4*pi
+
+    def G11(h2, k2):
+        return 4*pi*h2*k2/3
+
+    def G12(h2, k2):
+        return 4*pi*h2*(k2 - h2)/3
+
+    def G13(h2, k2):
+        return 4*pi*k2*(k2 - h2)/3
+
+    def G22(h2, k2):
+        res = (2*(h2**4 + k2**4) - 4*h2*k2*(h2**2 + k2**2) + 6*h2**2*k2**2 +
+        sqrt(h2**2 + k2**2 - h2*k2)*(-2*(h2**3 + k2**3) + 3*h2*k2*(h2 + k2)))
+        return 16*pi/405*res
+
+    def G21(h2, k2):
+        res = (2*(h2**4 + k2**4) - 4*h2*k2*(h2**2 + k2**2) + 6*h2**2*k2**2
+        + sqrt(h2**2 + k2**2 - h2*k2)*(2*(h2**3 + k2**3) - 3*h2*k2*(h2 + k2)))
+        return 16*pi/405*res
+
+    def G23(h2, k2):
+        return 4*pi*h2**2*k2*(k2 - h2)/15
+
+    def G24(h2, k2):
+        return 4*pi*h2*k2**2*(k2 - h2)/15
+
+    def G25(h2, k2):
+        return 4*pi*h2*k2*(k2 - h2)**2/15
+
+    def G32(h2, k2):
+        res = (16*(h2**4 + k2**4) - 36*h2*k2*(h2**2 + k2**2) + 46*h2**2*k2**2
+        + sqrt(4*(h2**2 + k2**2) - 7*h2*k2)*(-8*(h2**3 + k2**3) +
+        11*h2*k2*(h2 + k2)))
+        return 16*pi/13125*k2*h2*res
+
+    def G31(h2, k2):
+        res = (16*(h2**4 + k2**4) - 36*h2*k2*(h2**2 + k2**2) + 46*h2**2*k2**2
+        + sqrt(4*(h2**2 + k2**2) - 7*h2*k2)*(8*(h2**3 + k2**3) -
+        11*h2*k2*(h2 + k2)))
+        return 16*pi/13125*h2*k2*res
+
+    def G34(h2, k2):
+        res = (6*h2**4 + 16*k2**4 - 12*h2**3*k2 - 28*h2*k2**3 + 34*h2**2*k2**2
+        + sqrt(h2**2 + 4*k2**2 - h2*k2)*(-6*h2**3 - 8*k2**3 + 9*h2**2*k2 +
+                                            13*h2*k2**2))
+        return 16*pi/13125*h2*(k2 - h2)*res
+
+    def G33(h2, k2):
+        res = (6*h2**4 + 16*k2**4 - 12*h2**3*k2 - 28*h2*k2**3 + 34*h2**2*k2**2
+        + sqrt(h2**2 + 4*k2**2 - h2*k2)*(6*h2**3 + 8*k2**3 - 9*h2**2*k2 -
+        13*h2*k2**2))
+        return 16*pi/13125*h2*(k2 - h2)*res
+
+    def G36(h2, k2):
+        res = (16*h2**4 + 6*k2**4 - 28*h2**3*k2 - 12*h2*k2**3 + 34*h2**2*k2**2
+        + sqrt(4*h2**2 + k2**2 - h2*k2)*(-8*h2**3 - 6*k2**3 + 13*h2**2*k2 +
+        9*h2*k2**2))
+        return 16*pi/13125*k2*(k2 - h2)*res
+
+    def G35(h2, k2):
+        res = (16*h2**4 + 6*k2**4 - 28*h2**3*k2 - 12*h2*k2**3 + 34*h2**2*k2**2
+        + sqrt(4*h2**2 + k2**2 - h2*k2)*(8*h2**3 + 6*k2**3 - 13*h2**2*k2 -
+        9*h2*k2**2))
+        return 16*pi/13125*k2*(k2 - h2)*res
+
+    def G37(h2, k2):
+        return 4*pi*h2**2*k2**2*(k2 - h2)**2/105
+
+    known_funcs = {(0, 1): G01, (1, 1): G11, (1, 2): G12, (1, 3): G13,
+                   (2, 1): G21, (2, 2): G22, (2, 3): G23, (2, 4): G24,
+                   (2, 5): G25, (3, 1): G31, (3, 2): G32, (3, 3): G33,
+                   (3, 4): G34, (3, 5): G35, (3, 6): G36, (3, 7): G37}
+
+    def _ellip_norm(n, p, h2, k2):
+        func = known_funcs[n, p]
+        return func(h2, k2)
+    _ellip_norm = np.vectorize(_ellip_norm)
+
+    def ellip_normal_known(h2, k2, n, p):
+        return _ellip_norm(n, p, h2, k2)
+
+    # generate both large and small h2 < k2 pairs
+    np.random.seed(1234)
+    h2 = np.random.pareto(0.5, size=1)
+    k2 = h2 * (1 + np.random.pareto(0.5, size=h2.size))
+
+    points = []
+    for n in range(4):
+        for p in range(1, 2*n+2):
+            points.append((h2, k2, np.full(h2.size, n), np.full(h2.size, p)))
+    points = np.array(points)
+    with suppress_warnings() as sup:
+        sup.filter(IntegrationWarning, "The occurrence of roundoff error")
+        assert_func_equal(ellip_normal, ellip_normal_known, points, rtol=1e-12)
+
+
+def test_ellip_harm_2():
+
+    def I1(h2, k2, s):
+        res = (ellip_harm_2(h2, k2, 1, 1, s)/(3 * ellip_harm(h2, k2, 1, 1, s))
+        + ellip_harm_2(h2, k2, 1, 2, s)/(3 * ellip_harm(h2, k2, 1, 2, s)) +
+        ellip_harm_2(h2, k2, 1, 3, s)/(3 * ellip_harm(h2, k2, 1, 3, s)))
+        return res
+
+    with suppress_warnings() as sup:
+        sup.filter(IntegrationWarning, "The occurrence of roundoff error")
+        assert_almost_equal(I1(5, 8, 10), 1/(10*sqrt((100-5)*(100-8))))
+
+        # Values produced by code from arXiv:1204.0267
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 1, 10), 0.00108056853382)
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 2, 10), 0.00105820513809)
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 3, 10), 0.00106058384743)
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 4, 10), 0.00106774492306)
+        assert_almost_equal(ellip_harm_2(5, 8, 2, 5, 10), 0.00107976356454)
+
+
+def test_ellip_harm():
+
+    def E01(h2, k2, s):
+        return 1
+
+    def E11(h2, k2, s):
+        return s
+
+    def E12(h2, k2, s):
+        return sqrt(abs(s*s - h2))
+
+    def E13(h2, k2, s):
+        return sqrt(abs(s*s - k2))
+
+    def E21(h2, k2, s):
+        return s*s - 1/3*((h2 + k2) + sqrt(abs((h2 + k2)*(h2 + k2)-3*h2*k2)))
+
+    def E22(h2, k2, s):
+        return s*s - 1/3*((h2 + k2) - sqrt(abs((h2 + k2)*(h2 + k2)-3*h2*k2)))
+
+    def E23(h2, k2, s):
+        return s * sqrt(abs(s*s - h2))
+
+    def E24(h2, k2, s):
+        return s * sqrt(abs(s*s - k2))
+
+    def E25(h2, k2, s):
+        return sqrt(abs((s*s - h2)*(s*s - k2)))
+
+    def E31(h2, k2, s):
+        return s*s*s - (s/5)*(2*(h2 + k2) + sqrt(4*(h2 + k2)*(h2 + k2) -
+        15*h2*k2))
+
+    def E32(h2, k2, s):
+        return s*s*s - (s/5)*(2*(h2 + k2) - sqrt(4*(h2 + k2)*(h2 + k2) -
+        15*h2*k2))
+
+    def E33(h2, k2, s):
+        return sqrt(abs(s*s - h2))*(s*s - 1/5*((h2 + 2*k2) + sqrt(abs((h2 +
+        2*k2)*(h2 + 2*k2) - 5*h2*k2))))
+
+    def E34(h2, k2, s):
+        return sqrt(abs(s*s - h2))*(s*s - 1/5*((h2 + 2*k2) - sqrt(abs((h2 +
+        2*k2)*(h2 + 2*k2) - 5*h2*k2))))
+
+    def E35(h2, k2, s):
+        return sqrt(abs(s*s - k2))*(s*s - 1/5*((2*h2 + k2) + sqrt(abs((2*h2
+        + k2)*(2*h2 + k2) - 5*h2*k2))))
+
+    def E36(h2, k2, s):
+        return sqrt(abs(s*s - k2))*(s*s - 1/5*((2*h2 + k2) - sqrt(abs((2*h2
+        + k2)*(2*h2 + k2) - 5*h2*k2))))
+
+    def E37(h2, k2, s):
+        return s * sqrt(abs((s*s - h2)*(s*s - k2)))
+
+    assert_equal(ellip_harm(5, 8, 1, 2, 2.5, 1, 1),
+    ellip_harm(5, 8, 1, 2, 2.5))
+
+    known_funcs = {(0, 1): E01, (1, 1): E11, (1, 2): E12, (1, 3): E13,
+                   (2, 1): E21, (2, 2): E22, (2, 3): E23, (2, 4): E24,
+                   (2, 5): E25, (3, 1): E31, (3, 2): E32, (3, 3): E33,
+                   (3, 4): E34, (3, 5): E35, (3, 6): E36, (3, 7): E37}
+
+    point_ref = []
+
+    def ellip_harm_known(h2, k2, n, p, s):
+        for i in range(h2.size):
+            func = known_funcs[(int(n[i]), int(p[i]))]
+            point_ref.append(func(h2[i], k2[i], s[i]))
+        return point_ref
+
+    rng = np.random.RandomState(1234)
+    h2 = rng.pareto(0.5, size=30)
+    k2 = h2*(1 + rng.pareto(0.5, size=h2.size))
+    s = rng.pareto(0.5, size=h2.size)
+    points = []
+    for i in range(h2.size):
+        for n in range(4):
+            for p in range(1, 2*n+2):
+                points.append((h2[i], k2[i], n, p, s[i]))
+    points = np.array(points)
+    assert_func_equal(ellip_harm, ellip_harm_known, points, rtol=1e-12)
+
+
+def test_ellip_harm_invalid_p():
+    # Regression test. This should return nan.
+    n = 4
+    # Make p > 2*n + 1.
+    p = 2*n + 2
+    result = ellip_harm(0.5, 2.0, n, p, 0.2)
+    assert np.isnan(result)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py
new file mode 100644
index 0000000000000000000000000000000000000000..98739b93fc6ad75a41a7b80107ee696453b12a09
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_erfinv.py
@@ -0,0 +1,89 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+import pytest
+
+import scipy.special as sc
+
+
+class TestInverseErrorFunction:
+    def test_compliment(self):
+        # Test erfcinv(1 - x) == erfinv(x)
+        x = np.linspace(-1, 1, 101)
+        assert_allclose(sc.erfcinv(1 - x), sc.erfinv(x), rtol=0, atol=1e-15)
+
+    def test_literal_values(self):
+        # The expected values were calculated with mpmath:
+        #
+        #   import mpmath
+        #   mpmath.mp.dps = 200
+        #   for y in [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]:
+        #       x = mpmath.erfinv(y)
+        #       print(x)
+        #
+        y = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
+        actual = sc.erfinv(y)
+        expected = [
+            0.0,
+            0.08885599049425769,
+            0.1791434546212917,
+            0.2724627147267543,
+            0.37080715859355795,
+            0.4769362762044699,
+            0.5951160814499948,
+            0.7328690779592167,
+            0.9061938024368233,
+            1.1630871536766743,
+        ]
+        assert_allclose(actual, expected, rtol=0, atol=1e-15)
+
+    @pytest.mark.parametrize(
+        'f, x, y',
+        [
+            (sc.erfinv, -1, -np.inf),
+            (sc.erfinv, 0, 0),
+            (sc.erfinv, 1, np.inf),
+            (sc.erfinv, -100, np.nan),
+            (sc.erfinv, 100, np.nan),
+            (sc.erfcinv, 0, np.inf),
+            (sc.erfcinv, 1, -0.0),
+            (sc.erfcinv, 2, -np.inf),
+            (sc.erfcinv, -100, np.nan),
+            (sc.erfcinv, 100, np.nan),
+        ],
+        ids=[
+            'erfinv at lower bound',
+            'erfinv at midpoint',
+            'erfinv at upper bound',
+            'erfinv below lower bound',
+            'erfinv above upper bound',
+            'erfcinv at lower bound',
+            'erfcinv at midpoint',
+            'erfcinv at upper bound',
+            'erfcinv below lower bound',
+            'erfcinv above upper bound',
+        ]
+    )
+    def test_domain_bounds(self, f, x, y):
+        assert_equal(f(x), y)
+
+    def test_erfinv_asympt(self):
+        # regression test for gh-12758: erfinv(x) loses precision at small x
+        # expected values precomputed with mpmath:
+        # >>> mpmath.mp.dps = 100
+        # >>> expected = [float(mpmath.erfinv(t)) for t in x]
+        x = np.array([1e-20, 1e-15, 1e-14, 1e-10, 1e-8, 0.9e-7, 1.1e-7, 1e-6])
+        expected = np.array([8.86226925452758e-21,
+                             8.862269254527581e-16,
+                             8.86226925452758e-15,
+                             8.862269254527581e-11,
+                             8.86226925452758e-09,
+                             7.97604232907484e-08,
+                             9.74849617998037e-08,
+                             8.8622692545299e-07])
+        assert_allclose(sc.erfinv(x), expected,
+                        rtol=1e-15)
+
+        # also test the roundtrip consistency
+        assert_allclose(sc.erf(sc.erfinv(x)),
+                        x,
+                        rtol=5e-15)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py
new file mode 100644
index 0000000000000000000000000000000000000000..8332a83267e2f75dded04e80443c150c832676c8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_exponential_integrals.py
@@ -0,0 +1,118 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.special as sc
+
+
+class TestExp1:
+
+    def test_branch_cut(self):
+        assert np.isnan(sc.exp1(-1))
+        assert sc.exp1(complex(-1, 0)).imag == (
+            -sc.exp1(complex(-1, -0.0)).imag
+        )
+
+        assert_allclose(
+            sc.exp1(complex(-1, 0)),
+            sc.exp1(-1 + 1e-20j),
+            atol=0,
+            rtol=1e-15
+        )
+        assert_allclose(
+            sc.exp1(complex(-1, -0.0)),
+            sc.exp1(-1 - 1e-20j),
+            atol=0,
+            rtol=1e-15
+        )
+
+    def test_834(self):
+        # Regression test for #834
+        a = sc.exp1(-complex(19.9999990))
+        b = sc.exp1(-complex(19.9999991))
+        assert_allclose(a.imag, b.imag, atol=0, rtol=1e-15)
+
+
+class TestScaledExp1:
+
+    @pytest.mark.parametrize('x, expected', [(0, 0), (np.inf, 1)])
+    def test_limits(self, x, expected):
+        y = sc._ufuncs._scaled_exp1(x)
+        assert y == expected
+
+    # The expected values were computed with mpmath, e.g.:
+    #
+    #   from mpmath import mp
+    #   mp.dps = 80
+    #   x = 1e-25
+    #   print(float(x*mp.exp(x)*np.expint(1, x)))
+    #
+    # prints 5.698741165994961e-24
+    #
+    # The method used to compute _scaled_exp1 changes at x=1
+    # and x=1250, so values at those inputs, and values just
+    # above and below them, are included in the test data.
+    @pytest.mark.parametrize('x, expected',
+                             [(1e-25, 5.698741165994961e-24),
+                              (0.1, 0.20146425447084518),
+                              (0.9995, 0.5962509885831002),
+                              (1.0, 0.5963473623231941),
+                              (1.0005, 0.5964436833238044),
+                              (2.5, 0.7588145912149602),
+                              (10.0, 0.9156333393978808),
+                              (100.0, 0.9901942286733019),
+                              (500.0, 0.9980079523802055),
+                              (1000.0, 0.9990019940238807),
+                              (1249.5, 0.9992009578306811),
+                              (1250.0, 0.9992012769377913),
+                              (1250.25, 0.9992014363957858),
+                              (2000.0, 0.9995004992514963),
+                              (1e4, 0.9999000199940024),
+                              (1e10, 0.9999999999),
+                              (1e15, 0.999999999999999),
+                              ])
+    def test_scaled_exp1(self, x, expected):
+        y = sc._ufuncs._scaled_exp1(x)
+        assert_allclose(y, expected, rtol=2e-15)
+
+
+class TestExpi:
+
+    @pytest.mark.parametrize('result', [
+        sc.expi(complex(-1, 0)),
+        sc.expi(complex(-1, -0.0)),
+        sc.expi(-1)
+    ])
+    def test_branch_cut(self, result):
+        desired = -0.21938393439552027368  # Computed using Mpmath
+        assert_allclose(result, desired, atol=0, rtol=1e-14)
+
+    def test_near_branch_cut(self):
+        lim_from_above = sc.expi(-1 + 1e-20j)
+        lim_from_below = sc.expi(-1 - 1e-20j)
+        assert_allclose(
+            lim_from_above.real,
+            lim_from_below.real,
+            atol=0,
+            rtol=1e-15
+        )
+        assert_allclose(
+            lim_from_above.imag,
+            -lim_from_below.imag,
+            atol=0,
+            rtol=1e-15
+        )
+
+    def test_continuity_on_positive_real_axis(self):
+        assert_allclose(
+            sc.expi(complex(1, 0)),
+            sc.expi(complex(1, -0.0)),
+            atol=0,
+            rtol=1e-15
+        )
+
+
+class TestExpn:
+
+    def test_out_of_domain(self):
+        assert all(np.isnan([sc.expn(-1, 1.0), sc.expn(1, -1.0)]))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ecaf51545e006e37a451a08f356ce0392a3159c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_extending.py
@@ -0,0 +1,28 @@
+import os
+import platform
+import sysconfig
+
+import pytest
+
+from scipy._lib._testutils import IS_EDITABLE,_test_cython_extension, cython
+from scipy.special import beta, gamma
+
+
+@pytest.mark.fail_slow(40)
+# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247
+@pytest.mark.skipif(IS_EDITABLE,
+                    reason='Editable install cannot find .pxd headers.')
+@pytest.mark.skipif((platform.system() == 'Windows' and
+                     sysconfig.get_config_var('Py_GIL_DISABLED')),
+                    reason='gh-22039')
+@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"],
+                    reason="Can't start subprocess")
+@pytest.mark.skipif(cython is None, reason="requires cython")
+def test_cython(tmp_path):
+    srcdir = os.path.dirname(os.path.dirname(__file__))
+    extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir)
+    # actually test the cython c-extensions
+    assert extensions.cy_beta(0.5, 0.1) == beta(0.5, 0.1)
+    assert extensions.cy_gamma(0.5 + 1.0j) == gamma(0.5 + 1.0j)
+    assert extensions_cpp.cy_beta(0.5, 0.1) == beta(0.5, 0.1)
+    assert extensions_cpp.cy_gamma(0.5 + 1.0j) == gamma(0.5 + 1.0j)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py
new file mode 100644
index 0000000000000000000000000000000000000000..8868f66c47ce0d4bbb21c78435a6c89d44065252
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_faddeeva.py
@@ -0,0 +1,85 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.special as sc
+from scipy.special._testutils import FuncData
+
+
+class TestVoigtProfile:
+
+    @pytest.mark.parametrize('x, sigma, gamma', [
+        (np.nan, 1, 1),
+        (0, np.nan, 1),
+        (0, 1, np.nan),
+        (1, np.nan, 0),
+        (np.nan, 1, 0),
+        (1, 0, np.nan),
+        (np.nan, 0, 1),
+        (np.nan, 0, 0)
+    ])
+    def test_nan(self, x, sigma, gamma):
+        assert np.isnan(sc.voigt_profile(x, sigma, gamma))
+
+    @pytest.mark.parametrize('x, desired', [
+        (-np.inf, 0),
+        (np.inf, 0)
+    ])
+    def test_inf(self, x, desired):
+        assert sc.voigt_profile(x, 1, 1) == desired
+
+    def test_against_mathematica(self):
+        # Results obtained from Mathematica by computing
+        #
+        # PDF[VoigtDistribution[gamma, sigma], x]
+        #
+        points = np.array([
+            [-7.89, 45.06, 6.66, 0.0077921073660388806401],
+            [-0.05, 7.98, 24.13, 0.012068223646769913478],
+            [-13.98, 16.83, 42.37, 0.0062442236362132357833],
+            [-12.66, 0.21, 6.32, 0.010052516161087379402],
+            [11.34, 4.25, 21.96, 0.0113698923627278917805],
+            [-11.56, 20.40, 30.53, 0.0076332760432097464987],
+            [-9.17, 25.61, 8.32, 0.011646345779083005429],
+            [16.59, 18.05, 2.50, 0.013637768837526809181],
+            [9.11, 2.12, 39.33, 0.0076644040807277677585],
+            [-43.33, 0.30, 45.68, 0.0036680463875330150996]
+        ])
+        FuncData(
+            sc.voigt_profile,
+            points,
+            (0, 1, 2),
+            3,
+            atol=0,
+            rtol=1e-15
+        ).check()
+
+    def test_symmetry(self):
+        x = np.linspace(0, 10, 20)
+        assert_allclose(
+            sc.voigt_profile(x, 1, 1),
+            sc.voigt_profile(-x, 1, 1),
+            rtol=1e-15,
+            atol=0
+        )
+
+    @pytest.mark.parametrize('x, sigma, gamma, desired', [
+        (0, 0, 0, np.inf),
+        (1, 0, 0, 0)
+    ])
+    def test_corner_cases(self, x, sigma, gamma, desired):
+        assert sc.voigt_profile(x, sigma, gamma) == desired
+
+    @pytest.mark.parametrize('sigma1, gamma1, sigma2, gamma2', [
+        (0, 1, 1e-16, 1),
+        (1, 0, 1, 1e-16),
+        (0, 0, 1e-16, 1e-16)
+    ])
+    def test_continuity(self, sigma1, gamma1, sigma2, gamma2):
+        x = np.linspace(1, 10, 20)
+        assert_allclose(
+            sc.voigt_profile(x, sigma1, gamma1),
+            sc.voigt_profile(x, sigma2, gamma2),
+            rtol=1e-16,
+            atol=1e-16
+        )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e3fbd17dddeed73d311566a930f52899e3b9db6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gamma.py
@@ -0,0 +1,12 @@
+import numpy as np
+import scipy.special as sc
+
+
+class TestRgamma:
+
+    def test_gh_11315(self):
+        assert sc.rgamma(-35) == 0
+
+    def test_rgamma_zeros(self):
+        x = np.array([0, -10, -100, -1000, -10000])
+        assert np.all(sc.rgamma(x) == 0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py
new file mode 100644
index 0000000000000000000000000000000000000000..aae34e5c23f2d293f362abd825f1dad454371ae0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_gammainc.py
@@ -0,0 +1,136 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_equal
+
+import scipy.special as sc
+from scipy.special._testutils import FuncData
+
+
+INVALID_POINTS = [
+    (1, -1),
+    (0, 0),
+    (-1, 1),
+    (np.nan, 1),
+    (1, np.nan)
+]
+
+
+class TestGammainc:
+
+    @pytest.mark.parametrize('a, x', INVALID_POINTS)
+    def test_domain(self, a, x):
+        assert np.isnan(sc.gammainc(a, x))
+
+    def test_a_eq_0_x_gt_0(self):
+        assert sc.gammainc(0, 1) == 1
+
+    @pytest.mark.parametrize('a, x, desired', [
+        (np.inf, 1, 0),
+        (np.inf, 0, 0),
+        (np.inf, np.inf, np.nan),
+        (1, np.inf, 1)
+    ])
+    def test_infinite_arguments(self, a, x, desired):
+        result = sc.gammainc(a, x)
+        if np.isnan(desired):
+            assert np.isnan(result)
+        else:
+            assert result == desired
+
+    def test_infinite_limits(self):
+        # Test that large arguments converge to the hard-coded limits
+        # at infinity.
+        assert_allclose(
+            sc.gammainc(1000, 100),
+            sc.gammainc(np.inf, 100),
+            atol=1e-200,  # Use `atol` since the function converges to 0.
+            rtol=0
+        )
+        assert sc.gammainc(100, 1000) == sc.gammainc(100, np.inf)
+
+    def test_x_zero(self):
+        a = np.arange(1, 10)
+        assert_array_equal(sc.gammainc(a, 0), 0)
+
+    def test_limit_check(self):
+        result = sc.gammainc(1e-10, 1)
+        limit = sc.gammainc(0, 1)
+        assert np.isclose(result, limit)
+
+    def gammainc_line(self, x):
+        # The line a = x where a simpler asymptotic expansion (analog
+        # of DLMF 8.12.15) is available.
+        c = np.array([-1/3, -1/540, 25/6048, 101/155520,
+                      -3184811/3695155200, -2745493/8151736420])
+        res = 0
+        xfac = 1
+        for ck in c:
+            res -= ck*xfac
+            xfac /= x
+        res /= np.sqrt(2*np.pi*x)
+        res += 0.5
+        return res
+
+    def test_line(self):
+        x = np.logspace(np.log10(25), 300, 500)
+        a = x
+        dataset = np.vstack((a, x, self.gammainc_line(x))).T
+        FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-11).check()
+
+    def test_roundtrip(self):
+        a = np.logspace(-5, 10, 100)
+        x = np.logspace(-5, 10, 100)
+
+        y = sc.gammaincinv(a, sc.gammainc(a, x))
+        assert_allclose(x, y, rtol=1e-10)
+
+
+class TestGammaincc:
+
+    @pytest.mark.parametrize('a, x', INVALID_POINTS)
+    def test_domain(self, a, x):
+        assert np.isnan(sc.gammaincc(a, x))
+
+    def test_a_eq_0_x_gt_0(self):
+        assert sc.gammaincc(0, 1) == 0
+
+    @pytest.mark.parametrize('a, x, desired', [
+        (np.inf, 1, 1),
+        (np.inf, 0, 1),
+        (np.inf, np.inf, np.nan),
+        (1, np.inf, 0)
+    ])
+    def test_infinite_arguments(self, a, x, desired):
+        result = sc.gammaincc(a, x)
+        if np.isnan(desired):
+            assert np.isnan(result)
+        else:
+            assert result == desired
+
+    def test_infinite_limits(self):
+        # Test that large arguments converge to the hard-coded limits
+        # at infinity.
+        assert sc.gammaincc(1000, 100) == sc.gammaincc(np.inf, 100)
+        assert_allclose(
+            sc.gammaincc(100, 1000),
+            sc.gammaincc(100, np.inf),
+            atol=1e-200,  # Use `atol` since the function converges to 0.
+            rtol=0
+        )
+
+    def test_limit_check(self):
+        result = sc.gammaincc(1e-10,1)
+        limit = sc.gammaincc(0,1)
+        assert np.isclose(result, limit)
+
+    def test_x_zero(self):
+        a = np.arange(1, 10)
+        assert_array_equal(sc.gammaincc(a, 0), 1)
+
+    def test_roundtrip(self):
+        a = np.logspace(-5, 10, 100)
+        x = np.logspace(-5, 10, 100)
+
+        y = sc.gammainccinv(a, sc.gammaincc(a, x))
+        assert_allclose(x, y, rtol=1e-14)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py
new file mode 100644
index 0000000000000000000000000000000000000000..2102152213997886d0127080a2767e8fcc9af63a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hyp2f1.py
@@ -0,0 +1,2566 @@
+"""Tests for hyp2f1 for complex values.
+
+Author: Albert Steppi, with credit to Adam Kullberg (FormerPhycisist) for
+the implementation of mp_hyp2f1 below, which modifies mpmath's hyp2f1 to
+return the same branch as scipy's on the standard branch cut.
+"""
+
+import sys
+import pytest
+import numpy as np
+from typing import NamedTuple
+from numpy.testing import assert_allclose
+
+from scipy.special import hyp2f1
+from scipy.special._testutils import check_version, MissingModule
+
+
+try:
+    import mpmath
+except ImportError:
+    mpmath = MissingModule("mpmath")
+
+
+def mp_hyp2f1(a, b, c, z):
+    """Return mpmath hyp2f1 calculated on same branch as scipy hyp2f1.
+
+    For most values of a,b,c mpmath returns the x - 0j branch of hyp2f1 on the
+    branch cut x=(1,inf) whereas scipy's hyp2f1 calculates the x + 0j branch.
+    Thus, to generate the right comparison values on the branch cut, we
+    evaluate mpmath.hyp2f1 at x + 1e-15*j.
+
+    The exception to this occurs when c-a=-m in which case both mpmath and
+    scipy calculate the x + 0j branch on the branch cut. When this happens
+    mpmath.hyp2f1 will be evaluated at the original z point.
+    """
+    on_branch_cut = z.real > 1.0 and abs(z.imag) < 1.0e-15
+    cond1 = abs(c - a - round(c - a)) < 1.0e-15 and round(c - a) <= 0
+    cond2 = abs(c - b - round(c - b)) < 1.0e-15 and round(c - b) <= 0
+    # Make sure imaginary part is *exactly* zero
+    if on_branch_cut:
+        z = z.real + 0.0j
+    if on_branch_cut and not (cond1 or cond2):
+        z_mpmath = z.real + 1.0e-15j
+    else:
+        z_mpmath = z
+    return complex(mpmath.hyp2f1(a, b, c, z_mpmath))
+
+
+class Hyp2f1TestCase(NamedTuple):
+    a: float
+    b: float
+    c: float
+    z: complex
+    expected: complex
+    rtol: float
+
+
+class TestHyp2f1:
+    """Tests for hyp2f1 for complex values.
+
+    Expected values for test cases were computed using mpmath. See
+    `scipy.special._precompute.hyp2f1_data`. The verbose style of specifying
+    test cases is used for readability and to make it easier to mark individual
+    cases as expected to fail. Expected failures are used to highlight cases
+    where improvements are needed. See
+    `scipy.special._precompute.hyp2f1_data.make_hyp2f1_test_cases` for a
+    function to generate the boilerplate for the test cases.
+
+    Assertions have been added to each test to ensure that the test cases match
+    the situations that are intended. A final test `test_test_hyp2f1` checks
+    that the expected values in the test cases actually match what is computed
+    by mpmath. This test is marked slow even though it isn't particularly slow
+    so that it won't run by default on continuous integration builds.
+    """
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=np.inf + 0j,
+                    rtol=0
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=-10,
+                    z=0 + 0j,
+                    expected=1 + 0j,
+                    rtol=0
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=1 + 0j,
+                    rtol=0
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0,
+                    c=0,
+                    z=0.2 + 0.2j,
+                    expected=1 + 0j,
+                    rtol=0,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=0,
+                    z=0.2 + 0.2j,
+                    expected=np.inf + 0j,
+                    rtol=0,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=0,
+                    z=0 + 0j,
+                    expected=np.nan + 0j,
+                    rtol=0,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=-5,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=(1.0495404166666666+0.05708208333333334j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=-10,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=(1.092966013125+0.13455014673750001j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-10,
+                    b=-20,
+                    c=-10,
+                    z=0.2 + 0.2j,
+                    expected=(-0.07712512000000005+0.12752814080000005j),
+                    rtol=1e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1,
+                    b=3.2,
+                    c=-1,
+                    z=0.2 + 0.2j,
+                    expected=(1.6400000000000001+0.6400000000000001j),
+                    rtol=1e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-2,
+                    b=1.2,
+                    c=-4,
+                    z=1 + 0j,
+                    expected=1.8200000000000001 + 0j,
+                    rtol=1e-15,
+                ),
+            ),
+        ]
+    )
+    def test_c_non_positive_int(self, hyp2f1_test_case):
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=1.5,
+                    z=1 + 0j,
+                    expected=1.1496439092239847 + 0j,
+                    rtol=1e-15
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=12.3,
+                    b=8.0,
+                    c=20.31,
+                    z=1 + 0j,
+                    expected=69280986.75273195 + 0j,
+                    rtol=1e-15
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=290.2,
+                    b=321.5,
+                    c=700.1,
+                    z=1 + 0j,
+                    expected=1.3396562400934e117 + 0j,
+                    rtol=1e-12,
+                ),
+            ),
+            # Note that here even mpmath produces different results for
+            # results that should be equivalent.
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=9.2,
+                    b=621.5,
+                    c=700.1,
+                    z=(1+0j),
+                    expected=(952726652.4158565+0j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=621.5,
+                    b=9.2,
+                    c=700.1,
+                    z=(1+0j),
+                    expected=(952726652.4160284+0j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-101.2,
+                    b=-400.4,
+                    c=-172.1,
+                    z=(1+0j),
+                    expected=(2.2253618341394838e+37+0j),
+                    rtol=1e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-400.4,
+                    b=-101.2,
+                    c=-172.1,
+                    z=(1+0j),
+                    expected=(2.2253618341394838e+37+0j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=172.5,
+                    b=-201.3,
+                    c=151.2,
+                    z=(1+0j),
+                    expected=(7.072266653650905e-135+0j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-201.3,
+                    b=172.5,
+                    c=151.2,
+                    z=(1+0j),
+                    expected=(7.072266653650905e-135+0j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-102.1,
+                    b=-20.3,
+                    c=1.3,
+                    z=1 + 0j,
+                    expected=2.7899070752746906e22 + 0j,
+                    rtol=3e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-202.6,
+                    b=60.3,
+                    c=1.5,
+                    z=1 + 0j,
+                    expected=-1.3113641413099326e-56 + 0j,
+                    rtol=1e-12,
+                ),
+            ),
+        ],
+    )
+    def test_unital_argument(self, hyp2f1_test_case):
+        """Tests for case z = 1, c - a - b > 0.
+
+        Expected answers computed using mpmath.
+        """
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert z == 1 and c - a - b > 0  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=0.5,
+                    b=0.2,
+                    c=1.3,
+                    z=-1 + 0j,
+                    expected=0.9428846409614143 + 0j,
+                    rtol=1e-15),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=12.3,
+                    b=8.0,
+                    c=5.300000000000001,
+                    z=-1 + 0j,
+                    expected=-4.845809986595704e-06 + 0j,
+                    rtol=1e-15
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=221.5,
+                    b=90.2,
+                    c=132.3,
+                    z=-1 + 0j,
+                    expected=2.0490488728377282e-42 + 0j,
+                    rtol=1e-7,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-102.1,
+                    b=-20.3,
+                    c=-80.8,
+                    z=-1 + 0j,
+                    expected=45143784.46783885 + 0j,
+                    rtol=1e-7,
+                ),
+                marks=pytest.mark.xfail(
+                    condition=sys.maxsize < 2**32,
+                    reason="Fails on 32 bit.",
+                )
+            ),
+        ],
+    )
+    def test_special_case_z_near_minus_1(self, hyp2f1_test_case):
+        """Tests for case z ~ -1, c ~ 1 + a - b
+
+        Expected answers computed using mpmath.
+        """
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert abs(1 + a - b - c) < 1e-15 and abs(z + 1) < 1e-15
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-4,
+                    b=2.02764642551431,
+                    c=1.0561196186065624,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.0031961077109535375-0.0011313924606557173j),
+                    rtol=1e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-8,
+                    b=-7.937789122896016,
+                    c=-15.964218273004214,
+                    z=(2-0.10526315789473695j),
+                    expected=(0.005543763196412503-0.0025948879065698306j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-8,
+                    b=8.095813935368371,
+                    c=4.0013768449590685,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(-0.0003054674127221263-9.261359291755414e-05j),
+                    rtol=1e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-4,
+                    b=-3.956227226099288,
+                    c=-3.9316537064827854,
+                    z=(1.1578947368421053-0.3157894736842106j),
+                    expected=(-0.0020809502580892937-0.0041877333232365095j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=-4,
+                    c=2.050308316530781,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.0011282435590058734+0.0002027062303465851j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-8,
+                    c=-15.964218273004214,
+                    z=(1.3684210526315788+0.10526315789473673j),
+                    expected=(-9.134907719238265e-05-0.00040219233987390723j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-4,
+                    c=4.0013768449590685,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(-0.000519013062087489-0.0005855883076830948j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-10000,
+                    b=2.2,
+                    c=93459345.3,
+                    z=(2+2j),
+                    expected=(0.9995292071559088-0.00047047067522659253j),
+                    rtol=1e-12,
+                ),
+            ),
+        ]
+    )
+    def test_a_b_negative_int(self, hyp2f1_test_case):
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert a == int(a) and a < 0 or b == int(b) and b < 0  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=-0.9629749245209605,
+                    c=-15.5,
+                    z=(1.1578947368421053-1.1578947368421053j),
+                    expected=(0.9778506962676361+0.044083801141231616j),
+                    rtol=3e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-3.9316537064827854,
+                    c=1.5,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(4.0793167523167675-10.11694246310966j),
+                    rtol=6e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-0.9629749245209605,
+                    c=2.5,
+                    z=(1.1578947368421053-0.10526315789473695j),
+                    expected=(-2.9692999501916915+0.6394599899845594j),
+                    rtol=1e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=-0.9629749245209605,
+                    c=-15.5,
+                    z=(1.5789473684210522-1.1578947368421053j),
+                    expected=(0.9493076367106102-0.04316852977183447j),
+                    rtol=1e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-0.5,
+                    c=-15.5,
+                    z=(0.5263157894736841+0.10526315789473673j),
+                    expected=(0.9844377175631795-0.003120587561483841j),
+                    rtol=1e-10,
+                ),
+            ),
+        ],
+    )
+    def test_a_b_neg_int_after_euler_hypergeometric_transformation(
+        self, hyp2f1_test_case
+    ):
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert (  # Tests the test
+            (abs(c - a - int(c - a)) < 1e-15 and c - a < 0) or
+            (abs(c - b - int(c - b)) < 1e-15 and c - b < 0)
+        )
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-0.9629749245209605,
+                    c=-15.963511401609862,
+                    z=(0.10526315789473673-0.3157894736842106j),
+                    expected=(0.9941449585778349+0.01756335047931358j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-0.9629749245209605,
+                    c=-15.963511401609862,
+                    z=(0.5263157894736841+0.5263157894736841j),
+                    expected=(1.0388722293372104-0.09549450380041416j),
+                    rtol=5e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=1.0561196186065624,
+                    c=-7.93846038215665,
+                    z=(0.10526315789473673+0.7368421052631575j),
+                    expected=(2.1948378809826434+24.934157235172222j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=16.088264119063613,
+                    c=8.031683612216888,
+                    z=(0.3157894736842106-0.736842105263158j),
+                    expected=(-0.4075277891264672-0.06819344579666956j),
+                    rtol=2e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=2.050308316530781,
+                    c=8.031683612216888,
+                    z=(0.7368421052631575-0.10526315789473695j),
+                    expected=(2.833535530740603-0.6925373701408158j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=2.050308316530781,
+                    c=4.078873014294075,
+                    z=(0.10526315789473673-0.3157894736842106j),
+                    expected=(1.005347176329683-0.3580736009337313j),
+                    rtol=5e-16,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-0.9629749245209605,
+                    c=-15.963511401609862,
+                    z=(0.3157894736842106-0.5263157894736843j),
+                    expected=(0.9824353641135369+0.029271018868990268j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-0.9629749245209605,
+                    c=-159.63511401609862,
+                    z=(0.3157894736842106-0.5263157894736843j),
+                    expected=(0.9982436200365834+0.002927268199671111j),
+                    rtol=1e-7,
+                ),
+                marks=pytest.mark.xfail(reason="Poor convergence.")
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=16.088264119063613,
+                    c=8.031683612216888,
+                    z=(0.5263157894736841-0.5263157894736843j),
+                    expected=(-0.6906825165778091+0.8176575137504892j),
+                    rtol=5e-13,
+                ),
+            ),
+        ]
+    )
+    def test_region1(self, hyp2f1_test_case):
+        """|z| < 0.9 and real(z) >= 0."""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert abs(z) < 0.9 and z.real >= 0  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=1.0561196186065624,
+                    c=4.078873014294075,
+                    z=(-0.3157894736842106+0.7368421052631575j),
+                    expected=(0.7751915029081136+0.24068493258607315j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=16.088264119063613,
+                    c=2.0397202577726152,
+                    z=(-0.9473684210526316-0.3157894736842106j),
+                    expected=(6.564549348474962e-07+1.6761570598334562e-06j),
+                    rtol=5e-09,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=2.050308316530781,
+                    c=16.056809865262608,
+                    z=(-0.10526315789473695-0.10526315789473695j),
+                    expected=(0.9862043298997204-0.013293151372712681j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=8.077282662161238,
+                    c=16.056809865262608,
+                    z=(-0.3157894736842106-0.736842105263158j),
+                    expected=(0.16163826638754716-0.41378530376373734j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=2.050308316530781,
+                    c=-0.906685989801748,
+                    z=(-0.5263157894736843+0.3157894736842106j),
+                    expected=(-6.256871535165936+0.13824973858225484j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=8.077282662161238,
+                    c=-3.9924618758357022,
+                    z=(-0.9473684210526316-0.3157894736842106j),
+                    expected=(75.54672526086316+50.56157041797548j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=8.077282662161238,
+                    c=-1.9631175993998025,
+                    z=(-0.5263157894736843+0.5263157894736841j),
+                    expected=(282.0602536306534-82.31597306936214j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-3.9316537064827854,
+                    c=8.031683612216888,
+                    z=(-0.5263157894736843-0.10526315789473695j),
+                    expected=(5.179603735575851+1.4445374002099813j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-7.949900487447654,
+                    c=1.0651378143226575,
+                    z=(-0.3157894736842106-0.9473684210526316j),
+                    expected=(2317.623517606141-269.51476321010324j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=-1.92872979730171,
+                    c=2.0397202577726152,
+                    z=(-0.736842105263158-0.3157894736842106j),
+                    expected=(29.179154096175836+22.126690357535043j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-3.9316537064827854,
+                    c=-15.963511401609862,
+                    z=(-0.736842105263158-0.10526315789473695j),
+                    expected=(0.20820247892032057-0.04763956711248794j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-15.964218273004214,
+                    c=-1.9631175993998025,
+                    z=(-0.3157894736842106-0.5263157894736843j),
+                    expected=(-157471.63920142158+991294.0587828817j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-7.949900487447654,
+                    c=-7.93846038215665,
+                    z=(-0.10526315789473695-0.10526315789473695j),
+                    expected=(0.30765349653210194-0.2979706363594157j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=1.0561196186065624,
+                    c=8.031683612216888,
+                    z=(-0.9473684210526316-0.10526315789473695j),
+                    expected=(1.6787607400597109+0.10056620134616838j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=16.088264119063613,
+                    c=4.078873014294075,
+                    z=(-0.5263157894736843-0.736842105263158j),
+                    expected=(7062.07842506049-12768.77955655703j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=16.088264119063613,
+                    c=2.0397202577726152,
+                    z=(-0.3157894736842106+0.7368421052631575j),
+                    expected=(54749.216391029935-23078.144720887536j),
+                    rtol=2e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=1.0561196186065624,
+                    c=-0.906685989801748,
+                    z=(-0.10526315789473695-0.10526315789473695j),
+                    expected=(1.21521766411428-4.449385173946672j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=4.0013768449590685,
+                    c=-1.9631175993998025,
+                    z=(-0.736842105263158+0.5263157894736841j),
+                    expected=(19234693144.196907+1617913967.7294445j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=1.0561196186065624,
+                    c=-15.963511401609862,
+                    z=(-0.5263157894736843+0.3157894736842106j),
+                    expected=(0.9345201094534371+0.03745712558992195j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-0.9629749245209605,
+                    c=2.0397202577726152,
+                    z=(-0.10526315789473695+0.10526315789473673j),
+                    expected=(0.605732446296829+0.398171533680972j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=-15.964218273004214,
+                    c=2.0397202577726152,
+                    z=(-0.10526315789473695-0.5263157894736843j),
+                    expected=(-9.753761888305416-4.590126012666959j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-1.92872979730171,
+                    c=2.0397202577726152,
+                    z=(-0.10526315789473695+0.3157894736842106j),
+                    expected=(0.45587226291120714+1.0694545265819797j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-7.949900487447654,
+                    c=-0.906685989801748,
+                    z=(-0.736842105263158+0.3157894736842106j),
+                    expected=(12.334808243233418-76.26089051819054j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-7.949900487447654,
+                    c=-15.963511401609862,
+                    z=(-0.5263157894736843+0.10526315789473673j),
+                    expected=(1.2396019687632678-0.047507973161146286j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=-0.9629749245209605,
+                    c=-0.906685989801748,
+                    z=(-0.3157894736842106-0.5263157894736843j),
+                    expected=(97.7889554372208-18.999754543400016j),
+                    rtol=5e-13,
+                ),
+            ),
+        ]
+    )
+    def test_region2(self, hyp2f1_test_case):
+        """|z| < 1 and real(z) < 0."""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert abs(z) < 1 and z.real < 0  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=-3.75,
+                    c=-3.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(-1279.4894322256655-2302.914821389276j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=8.25,
+                    c=-1.5,
+                    z=(0.9473684210526314+0.3157894736842106j),
+                    expected=(-8889.452798586273-11961.162305065242j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.25,
+                    b=2.25,
+                    c=-1.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(-236.58971357952055-238.5228224781136j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.75,
+                    b=-7.75,
+                    c=-15.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(0.8116076584352279-0.29360565398246036j),
+                    rtol=5e-16,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.25,
+                    b=4.25,
+                    c=-0.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(-28.119407485189985+98.89858821348005j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.75,
+                    b=2.25,
+                    c=1.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(0.5311049067450484-0.9434347326448517j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=-15.75,
+                    c=-7.5,
+                    z=(0.9473684210526314+0.10526315789473673j),
+                    expected=(1262084.378141873+1775569.6338380123j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=-7.75,
+                    c=-15.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(-0.009810480794804165+0.3648997569257999j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=2.25,
+                    c=-3.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(585660.8815535795-33646.68398590896j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-3.9316537064827854,
+                    c=-15.963511401609862,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(181899621848365.2-173207123998705.7j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=8.25,
+                    c=-0.5,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.04271686244952705-0.14087902824639406j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-1.92872979730171,
+                    c=-0.906685989801748,
+                    z=(0.9473684210526314-0.3157894736842106j),
+                    expected=(-449.5119088817207+320.1423128036188j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=1.0561196186065624,
+                    c=8.031683612216888,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.6361479738012501+0.028575620091205088j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.25,
+                    b=16.25,
+                    c=16.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(-0.9038811840552261-1.5356250756164884j),
+                    rtol=1e-8,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=-1.75,
+                    c=-1.5,
+                    z=(0.9473684210526314+0.3157894736842106j),
+                    expected=(653.0109150415394-4554.162605155542j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=-3.75,
+                    c=4.5,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(118.7009859241035-34.18713648654642j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.25,
+                    b=-15.75,
+                    c=-3.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(-540204.4774526551+4970059.109251281j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=-15.75,
+                    c=-0.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(2253490.972258385+3318620.683390017j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=-7.75,
+                    c=-7.5,
+                    z=(0.9473684210526314+0.3157894736842106j),
+                    expected=(-46159826.46716958-17880663.82218242j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-7.949900487447654,
+                    c=-7.93846038215665,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.07116833581404514+0.11823358038036977j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=4.0013768449590685,
+                    c=-7.93846038215665,
+                    z=(0.7368421052631575+0.5263157894736841j),
+                    expected=(4.7724909620664006e+17-6.039064078946702e+16j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.25,
+                    b=-7.75,
+                    c=1.5,
+                    z=(0.9473684210526314-0.10526315789473695j),
+                    expected=(0.0188022179759303+0.002921737281641378j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=1.0561196186065624,
+                    c=-7.93846038215665,
+                    z=(0.7368421052631575-0.5263157894736843j),
+                    expected=(-9203.462928334846+12390.110518017136j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.75,
+                    b=-15.75,
+                    c=8.5,
+                    z=(0.7368421052631575+0.5263157894736841j),
+                    expected=(6.468457061368628+24.190040684917374j),
+                    rtol=5e-16,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=16.088264119063613,
+                    c=2.0397202577726152,
+                    z=(0.7368421052631575+0.5263157894736841j),
+                    expected=(2408.3451340186543-4275.257316636014j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.75,
+                    b=-7.75,
+                    c=8.5,
+                    z=(0.7368421052631575-0.5263157894736843j),
+                    expected=(4.1379984626381345-5.183654781039423j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=-7.75,
+                    c=-0.5,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(-81177.775295738+56079.73286548954j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=2.050308316530781,
+                    c=-0.906685989801748,
+                    z=(0.9473684210526314+0.3157894736842106j),
+                    expected=(1192868.5068926765+3624210.8182139914j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-1.92872979730171,
+                    c=8.031683612216888,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(1.8286341846195202+1.9295255682312178j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=1.0561196186065624,
+                    c=16.056809865262608,
+                    z=(0.7368421052631575-0.5263157894736843j),
+                    expected=(1.0514645669696452-0.0430834059440128j),
+                    rtol=5e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=-15.964218273004214,
+                    c=2.0397202577726152,
+                    z=(0.5263157894736841+0.7368421052631575j),
+                    expected=(541983.236432269+288200.2043029435j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.25,
+                    b=8.25,
+                    c=1.5,
+                    z=(0.5263157894736841-0.736842105263158j),
+                    expected=(-10.931988086039945+1.9136272843579096j),
+                    rtol=1e-15,
+                ),
+            ),
+        ]
+    )
+    def test_region3(self, hyp2f1_test_case):
+        """0.9 <= |z| <= 1 and |1 - z| < 0.9."""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert 0.9 <= abs(z) <= 1 and abs(1 - z) < 0.9  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=4.25,
+                    c=2.5,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(38.41207903409937-30.510151276075792j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.0,
+                    b=16.087593263474208,
+                    c=16.088264119063613,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(-0.6667857912761286-1.0206224321443573j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.0,
+                    b=1.0272592605282642,
+                    c=-7.949900487447654,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(1679024.1647997478-2748129.775857212j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=16.0,
+                    c=-7.949900487447654,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(424747226301.16986-1245539049327.2856j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=-15.964218273004214,
+                    c=4.0,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(-0.0057826199201757595+0.026359861999025885j),
+                    rtol=5e-06,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=-0.9629749245209605,
+                    c=2.0397202577726152,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(0.4671901063492606+0.7769632229834897j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.0,
+                    b=-3.956227226099288,
+                    c=-7.949900487447654,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(0.9422283708145973+1.3476905754773343j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0,
+                    b=-15.980848054962111,
+                    c=-15.964218273004214,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(0.4168719497319604-0.9770953555235625j),
+                    rtol=5e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=16.088264119063613,
+                    c=2.5,
+                    z=(0.5689655172413794+0.7965517241379312j),
+                    expected=(1.279096377550619-2.173827694297929j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=4.0013768449590685,
+                    c=2.0397202577726152,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(-2.071520656161738-0.7846098268395909j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=8.0,
+                    c=-0.9629749245209605,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(-7.740015495862889+3.386766435696699j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=16.088264119063613,
+                    c=-7.93846038215665,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(-6318.553685853241-7133.416085202879j),
+                    rtol=5e-9,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=-3.9316537064827854,
+                    c=16.056809865262608,
+                    z=(0.5689655172413794+0.7965517241379312j),
+                    expected=(-0.8854577905547399+8.135089099967278j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=-0.9629749245209605,
+                    c=4.078873014294075,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(1.224291301521487+0.36014711766402485j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=-0.75,
+                    c=-1.5,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(-1.5765685855028473-3.9399766961046323j),
+                    rtol=1e-3,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=-1.92872979730171,
+                    c=-7.93846038215665,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(56.794588688231194+4.556286783533971j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=4.5,
+                    c=2.050308316530781,
+                    z=(0.5689655172413794+0.7965517241379312j),
+                    expected=(-4.251456563455306+6.737837111569671j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=8.5,
+                    c=-1.92872979730171,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(2177143.9156599627-3313617.2748088865j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.5,
+                    b=-1.5,
+                    c=4.0013768449590685,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(0.45563554481603946+0.6212000158060831j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-7.5,
+                    c=-15.964218273004214,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(61.03201617828073-37.185626416756214j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=16.5,
+                    c=4.0013768449590685,
+                    z=(0.4931034482758623+0.7965517241379312j),
+                    expected=(-33143.425963520735+20790.608514722644j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=4.5,
+                    c=-0.9629749245209605,
+                    z=(0.5689655172413794+0.7965517241379312j),
+                    expected=(30.778600270824423-26.65160354466787j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=-3.5,
+                    c=16.088264119063613,
+                    z=(0.5689655172413794-0.7965517241379311j),
+                    expected=(1.0629792615560487-0.08308454486044772j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.5,
+                    b=-7.5,
+                    c=-0.9629749245209605,
+                    z=(0.4931034482758623-0.7965517241379311j),
+                    expected=(17431.571802591767+3553.7129767034507j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.25,
+                    b=8.25,
+                    c=16.5,
+                    z=(0.11379310344827598+0.9482758620689657j),
+                    expected=(0.4468600750211926+0.7313214934036885j),
+                    rtol=1e-3,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=16.25,
+                    c=4.5,
+                    z=(0.3413793103448277+0.8724137931034486j),
+                    expected=(-3.905704438293991+3.693347860329299j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.25,
+                    b=4.25,
+                    c=-0.5,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(-40.31777941834244-89.89852492432011j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=8.0,
+                    c=-15.964218273004214,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(52584.347773055284-109197.86244309516j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-15.964218273004214,
+                    c=16.056809865262608,
+                    z=(0.03793103448275881+0.9482758620689657j),
+                    expected=(-1.187733570412592-1.5147865053584582j),
+                    rtol=5e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-3.9316537064827854,
+                    c=1.0651378143226575,
+                    z=(0.26551724137931054+0.9482758620689657j),
+                    expected=(13.077494677898947+35.071599628224966j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-3.5,
+                    c=-3.5,
+                    z=(0.26551724137931054+0.8724137931034486j),
+                    expected=(-0.5359656237994614-0.2344483936591811j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.25,
+                    b=-3.75,
+                    c=-1.5,
+                    z=(0.26551724137931054+0.9482758620689657j),
+                    expected=(1204.8114871663133+64.41022826840198j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=16.0,
+                    c=4.0013768449590685,
+                    z=(0.03793103448275881-0.9482758620689655j),
+                    expected=(-9.85268872413994+7.011107558429154j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=16.0,
+                    c=4.0013768449590685,
+                    z=(0.3413793103448277-0.8724137931034484j),
+                    expected=(528.5522951158454-1412.21630264791j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=1.0561196186065624,
+                    c=-7.5,
+                    z=(0.4172413793103451+0.8724137931034486j),
+                    expected=(133306.45260685298+256510.7045225382j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=8.077282662161238,
+                    c=-15.963511401609862,
+                    z=(0.3413793103448277-0.8724137931034484j),
+                    expected=(-0.998555715276967+2.774198742229889j),
+                    rtol=5e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.75,
+                    b=-0.75,
+                    c=1.5,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(2.072445019723025-2.9793504811373515j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=-1.92872979730171,
+                    c=1.5,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(-41.87581944176649-32.52980303527139j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.75,
+                    b=-15.75,
+                    c=-0.5,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(-3729.6214864209774-30627.510509112635j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-15.964218273004214,
+                    c=-0.906685989801748,
+                    z=(0.03793103448275881+0.9482758620689657j),
+                    expected=(-131615.07820609974+145596.13384245415j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=16.5,
+                    c=16.088264119063613,
+                    z=(0.26551724137931054+0.8724137931034486j),
+                    expected=(0.18981844071070744+0.7855036242583742j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.5,
+                    b=8.5,
+                    c=-3.9316537064827854,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(110224529.2376068+128287212.04290268j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.5,
+                    b=-7.5,
+                    c=4.0013768449590685,
+                    z=(0.3413793103448277-0.8724137931034484j),
+                    expected=(0.2722302180888523-0.21790187837266162j),
+                    rtol=1e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-7.5,
+                    c=-15.964218273004214,
+                    z=(0.11379310344827598-0.9482758620689655j),
+                    expected=(-2.8252338010989035+2.430661949756161j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.5,
+                    b=16.5,
+                    c=4.0013768449590685,
+                    z=(0.03793103448275881+0.9482758620689657j),
+                    expected=(-20.604894257647945+74.5109432558078j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=8.5,
+                    c=-0.9629749245209605,
+                    z=(0.3413793103448277+0.8724137931034486j),
+                    expected=(-2764422.521269463-3965966.9965808876j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.5,
+                    b=-0.5,
+                    c=1.0561196186065624,
+                    z=(0.26551724137931054+0.9482758620689657j),
+                    expected=(1.2262338560994905+0.6545051266925549j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.5,
+                    b=-15.5,
+                    c=-7.949900487447654,
+                    z=(0.4172413793103451-0.8724137931034484j),
+                    expected=(-2258.1590330318213+8860.193389158803j),
+                    rtol=1.4e-10,
+                ),
+            ),
+        ]
+    )
+    def test_region4(self, hyp2f1_test_case):
+        """0.9 <= |z| <= 1 and |1 - z| >= 1.
+
+        This region is unhandled by of the standard transformations and
+        needs special care.
+        """
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert 0.9 <= abs(z) <= 1 and abs(1 - z) >= 0.9  # Tests the test
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=16.088264119063613,
+                    c=8.5,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(0.018601324701770394-0.07618420586062377j),
+                    rtol=5e-08,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.25,
+                    b=4.25,
+                    c=4.5,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(-1.391549471425551-0.118036604903893j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=2.050308316530781,
+                    c=-1.9631175993998025,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(-2309.178768155151-1932.7247727595172j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=1.0,
+                    c=-15.964218273004214,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(85592537010.05054-8061416766688.324j),
+                    rtol=2e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-0.5,
+                    c=1.5,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(1.2334498208515172-2.1639498536219732j),
+                    rtol=5e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=-15.964218273004214,
+                    c=4.0,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(102266.35398605966-44976.97828737755j),
+                    rtol=1e-3,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.0,
+                    b=-3.956227226099288,
+                    c=-15.964218273004214,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(-2.9590030930007236-4.190770764773225j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-15.5,
+                    c=-7.5,
+                    z=(0.5689655172413794-0.8724137931034484j),
+                    expected=(-112554838.92074208+174941462.9202412j),
+                    rtol=5e-05,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=2.050308316530781,
+                    c=1.0,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(3.7519882374080145+7.360753798667486j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=2.050308316530781,
+                    c=4.0,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(0.000181132943964693+0.07742903103815582j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=4.0013768449590685,
+                    c=-1.9631175993998025,
+                    z=(0.5689655172413794+0.8724137931034486j),
+                    expected=(386338.760913596-386166.51762171905j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.980848054962111,
+                    b=8.0,
+                    c=-1.92872979730171,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(1348667126.3444858-2375132427.158893j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.5,
+                    b=-0.9629749245209605,
+                    c=4.5,
+                    z=(0.5689655172413794+0.8724137931034486j),
+                    expected=(1.428353429538678+0.6472718120804372j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-0.9629749245209605,
+                    c=2.0397202577726152,
+                    z=(0.5689655172413794-0.8724137931034484j),
+                    expected=(3.1439267526119643-3.145305240375117j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=-15.964218273004214,
+                    c=-7.93846038215665,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(75.27467675681773+144.0946946292215j),
+                    rtol=1e-07,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.75,
+                    b=-7.75,
+                    c=-7.5,
+                    z=(0.5689655172413794+0.8724137931034486j),
+                    expected=(-0.3699450626264222+0.8732812475910993j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=16.5,
+                    c=1.0561196186065624,
+                    z=(0.5689655172413794-0.8724137931034484j),
+                    expected=(5.5361025821300665-2.4709693474656285j),
+                    rtol=5e-09,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=8.5,
+                    c=-3.9316537064827854,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(-782805.6699207705-537192.581278909j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.5,
+                    b=-15.5,
+                    c=1.0561196186065624,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(12.345113400639693-14.993248992902007j),
+                    rtol=0.0005,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=-0.5,
+                    c=-15.964218273004214,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(23.698109392667842+97.15002033534108j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=16.5,
+                    c=4.0013768449590685,
+                    z=(0.6448275862068968-0.8724137931034484j),
+                    expected=(1115.2978631811834+915.9212658718577j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=16.5,
+                    c=-0.9629749245209605,
+                    z=(0.6448275862068968+0.8724137931034486j),
+                    expected=(642077722221.6489+535274495398.21027j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=-3.5,
+                    c=4.0013768449590685,
+                    z=(0.5689655172413794+0.8724137931034486j),
+                    expected=(-5.689219222945697+16.877463062787143j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=-1.5,
+                    c=-0.9629749245209605,
+                    z=(0.5689655172413794-0.8724137931034484j),
+                    expected=(-44.32070290703576+1026.9127058617403j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=2.25,
+                    c=4.5,
+                    z=(0.11379310344827598-1.024137931034483j),
+                    expected=(-0.021965227124574663+0.009908300237809064j),
+                    rtol=1e-3,
+                ),
+                marks=pytest.mark.xfail(
+                    reason="Unhandled parameters."
+                )
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.02764642551431,
+                    b=1.5,
+                    c=16.5,
+                    z=(0.26551724137931054+1.024137931034483j),
+                    expected=(1.0046072901244183+0.19945500134119992j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=1.0,
+                    c=-3.9316537064827854,
+                    z=(0.3413793103448277+0.9482758620689657j),
+                    expected=(21022.30133421465+49175.98317370489j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=16.088264119063613,
+                    c=-1.9631175993998025,
+                    z=(0.4172413793103451-0.9482758620689655j),
+                    expected=(-7024239.358547302+2481375.02681063j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=-15.75,
+                    c=1.5,
+                    z=(0.18965517241379315+1.024137931034483j),
+                    expected=(92371704.94848-403546832.548352j),
+                    rtol=5e-06,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.5,
+                    b=-7.949900487447654,
+                    c=8.5,
+                    z=(0.26551724137931054-1.024137931034483j),
+                    expected=(1.9335109845308265+5.986542524829654j),
+                    rtol=5e-10,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-1.92872979730171,
+                    c=-7.93846038215665,
+                    z=(0.4931034482758623+0.8724137931034486j),
+                    expected=(-122.52639696039328-59.72428067512221j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.25,
+                    b=-1.75,
+                    c=-1.5,
+                    z=(0.4931034482758623+0.9482758620689657j),
+                    expected=(-90.40642053579428+50.50649180047921j),
+                    rtol=5e-08,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.5,
+                    b=8.077282662161238,
+                    c=16.5,
+                    z=(0.4931034482758623+0.9482758620689657j),
+                    expected=(-0.2155745818150323-0.564628986876639j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=1.0561196186065624,
+                    c=8.031683612216888,
+                    z=(0.4172413793103451-0.9482758620689655j),
+                    expected=(0.9503140488280465+0.11574960074292677j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.75,
+                    b=2.25,
+                    c=-15.5,
+                    z=(0.4172413793103451+0.9482758620689657j),
+                    expected=(0.9285862488442175+0.8203699266719692j),
+                    rtol=5e-13,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.75,
+                    b=4.25,
+                    c=-15.5,
+                    z=(0.3413793103448277-0.9482758620689655j),
+                    expected=(-1.0509834850116921-1.1145522325486075j),
+                    rtol=1.1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-0.9629749245209605,
+                    c=2.0397202577726152,
+                    z=(0.4931034482758623-0.9482758620689655j),
+                    expected=(2.88119116536769-3.4249933450696806j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=-15.964218273004214,
+                    c=16.5,
+                    z=(0.18965517241379315+1.024137931034483j),
+                    expected=(199.65868451496038+347.79384207302877j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.75,
+                    b=-15.75,
+                    c=-3.5,
+                    z=(0.4931034482758623-0.8724137931034484j),
+                    expected=(-208138312553.07013+58631611809.026955j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-15.5,
+                    c=-7.5,
+                    z=(0.3413793103448277+0.9482758620689657j),
+                    expected=(-23032.90519856288-18256.94050457296j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=1.5,
+                    c=1.0561196186065624,
+                    z=(0.4931034482758623-0.8724137931034484j),
+                    expected=(1.507342459587056+1.2332023580148403j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=2.5,
+                    b=4.5,
+                    c=-3.9316537064827854,
+                    z=(0.4172413793103451+0.9482758620689657j),
+                    expected=(7044.766127108853-40210.365567285575j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.5,
+                    b=-1.5,
+                    c=1.0561196186065624,
+                    z=(0.03793103448275881+1.024137931034483j),
+                    expected=(0.2725347741628333-2.247314875514784j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.5,
+                    b=-1.5,
+                    c=-7.949900487447654,
+                    z=(0.26551724137931054+1.024137931034483j),
+                    expected=(-11.250200011017546+12.597393659160472j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=8.5,
+                    c=16.088264119063613,
+                    z=(0.26551724137931054+1.024137931034483j),
+                    expected=(-0.18515160890991517+0.7959014164484782j),
+                    rtol=2e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.5,
+                    b=16.5,
+                    c=-3.9316537064827854,
+                    z=(0.3413793103448277-1.024137931034483j),
+                    expected=(998246378.8556538+1112032928.103645j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.5,
+                    b=-3.5,
+                    c=2.050308316530781,
+                    z=(0.03793103448275881+1.024137931034483j),
+                    expected=(0.5527670397711952+2.697662715303637j),
+                    rtol=1.2e-15,       # rtol bumped from 1e-15 in gh18414
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-15.5,
+                    b=-1.5,
+                    c=-0.9629749245209605,
+                    z=(0.4931034482758623-0.8724137931034484j),
+                    expected=(55.396931662136886+968.467463806326j),
+                    rtol=5e-14,
+                ),
+            ),
+        ]
+    )
+    def test_region5(self, hyp2f1_test_case):
+        """1 < |z| < 1.1 and |1 - z| >= 0.9 and real(z) >= 0"""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert 1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=4.0013768449590685,
+                    c=4.078873014294075,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(-0.0018093573941378783+0.003481887377423739j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=2.050308316530781,
+                    c=1.0651378143226575,
+                    z=(-0.736842105263158-0.736842105263158j),
+                    expected=(-0.00023401243818780545-1.7983496305603562e-05j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=8.077282662161238,
+                    c=4.078873014294075,
+                    z=(-0.5263157894736843-0.9473684210526316j),
+                    expected=(0.22359773002226846-0.24092487123993353j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=2.050308316530781,
+                    c=-15.963511401609862,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(1.191573745740011+0.14347394589721466j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=4.0013768449590685,
+                    c=-15.963511401609862,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(31.822620756901784-66.09094396747611j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=8.077282662161238,
+                    c=-7.93846038215665,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(207.16750179245952+34.80478274924269j),
+                    rtol=5e-12,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=8.095813935368371,
+                    b=-7.949900487447654,
+                    c=8.031683612216888,
+                    z=(-0.736842105263158+0.7368421052631575j),
+                    expected=(-159.62429364277145+9.154224290644898j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-1.92872979730171,
+                    c=16.056809865262608,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(1.121122351247184-0.07170260470126685j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=16.087593263474208,
+                    b=-0.9629749245209605,
+                    c=16.056809865262608,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(1.9040596681316053-0.4951799449960107j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-1.92872979730171,
+                    c=-0.906685989801748,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(-14.496623497780739-21.897524523299875j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=4.080187217753502,
+                    b=-3.9316537064827854,
+                    c=-3.9924618758357022,
+                    z=(-0.5263157894736843-0.9473684210526316j),
+                    expected=(36.33473466026878+253.88728442029577j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.0272592605282642,
+                    b=-15.964218273004214,
+                    c=-0.906685989801748,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(1505052.5653144997-50820766.81043443j),
+                    rtol=1e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=4.0013768449590685,
+                    c=1.0651378143226575,
+                    z=(-0.5263157894736843+0.9473684210526314j),
+                    expected=(-127.79407519260877-28.69899444941112j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=8.077282662161238,
+                    c=16.056809865262608,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(2.0623331933754976+0.741234463565458j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=8.077282662161238,
+                    c=2.0397202577726152,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(30.729193458862525-292.5700835046965j),
+                    rtol=1e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=1.0561196186065624,
+                    c=-1.9631175993998025,
+                    z=(-0.5263157894736843-0.9473684210526316j),
+                    expected=(1.1285917906203495-0.735264575450189j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=1.0561196186065624,
+                    c=-3.9924618758357022,
+                    z=(-0.736842105263158+0.7368421052631575j),
+                    expected=(0.6356474446678052-0.02429663008952248j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-1.9214641416286231,
+                    b=16.088264119063613,
+                    c=-7.93846038215665,
+                    z=(-0.736842105263158+0.7368421052631575j),
+                    expected=(0.4718880510273174+0.655083067736377j),
+                    rtol=1e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-7.937789122896016,
+                    b=-3.9316537064827854,
+                    c=16.056809865262608,
+                    z=(-0.9473684210526316+0.5263157894736841j),
+                    expected=(-0.14681550942352714+0.16092206364265146j),
+                    rtol=5e-11,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-15.964218273004214,
+                    c=1.0651378143226575,
+                    z=(-0.5263157894736843+0.9473684210526314j),
+                    expected=(-6.436835190526225+22.883156700606182j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-0.9220024191881196,
+                    b=-7.949900487447654,
+                    c=4.078873014294075,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(-0.7505682955068583-1.1026583264249945j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-3.9316537064827854,
+                    c=-7.93846038215665,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(3.6247814989198166+2.596041360148318j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-15.964218273004214,
+                    c=-1.9631175993998025,
+                    z=(-0.5263157894736843-0.9473684210526316j),
+                    expected=(-59537.65287927933-669074.4342539902j),
+                    rtol=5e-15,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=-3.956227226099288,
+                    b=-15.964218273004214,
+                    c=-1.9631175993998025,
+                    z=(-0.9473684210526316-0.5263157894736843j),
+                    expected=(-433084.9970266166+431088.393918521j),
+                    rtol=5e-14,
+                ),
+            ),
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1,
+                    b=1,
+                    c=4,
+                    z=(3 + 4j),
+                    expected=(0.49234384000963544+0.6051340616612397j),
+                    rtol=5e-14,
+                ),
+            ),
+        ]
+    )
+    def test_region6(self, hyp2f1_test_case):
+        """|z| > 1 but not in region 5."""
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert (
+            abs(z) > 1 and
+            not (1 < abs(z) < 1.1 and abs(1 - z) >= 0.9 and z.real >= 0)
+        )
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+
+    @pytest.mark.parametrize(
+        "hyp2f1_test_case",
+        [
+            # Broke when fixing gamma pole behavior in gh-21827
+            pytest.param(
+                Hyp2f1TestCase(
+                    a=1.3,
+                    b=-0.2,
+                    c=0.3,
+                    z=-2.1,
+                    expected=1.8202169687521206,
+                    rtol=5e-15,
+                ),
+            ),
+        ]
+    )
+    def test_miscellaneous(self, hyp2f1_test_case ):
+        a, b, c, z, expected, rtol = hyp2f1_test_case
+        assert_allclose(hyp2f1(a, b, c, z), expected, rtol=rtol)
+
+    @pytest.mark.slow
+    @check_version(mpmath, "1.0.0")
+    def test_test_hyp2f1(self):
+        """Test that expected values match what is computed by mpmath.
+
+        This gathers the parameters for the test cases out of the pytest marks.
+        The parameters are a, b, c, z, expected, rtol, where expected should
+        be the value of hyp2f1(a, b, c, z) computed with mpmath. The test
+        recomputes hyp2f1(a, b, c, z) using mpmath and verifies that expected
+        actually is the correct value. This allows the data for the tests to
+        live within the test code instead of an external datafile, while
+        avoiding having to compute the results with mpmath during the test,
+        except for when slow tests are being run.
+        """
+        test_methods = [
+            test_method for test_method in dir(self)
+            if test_method.startswith('test') and
+            # Filter properties and attributes (futureproofing).
+            callable(getattr(self, test_method)) and
+            # Filter out this test
+            test_method != 'test_test_hyp2f1'
+        ]
+        for test_method in test_methods:
+            params = self._get_test_parameters(getattr(self, test_method))
+            for a, b, c, z, expected, _ in params:
+                assert_allclose(mp_hyp2f1(a, b, c, z), expected, rtol=2.25e-16)
+
+    def _get_test_parameters(self, test_method):
+        """Get pytest.mark parameters for a test in this class."""
+        return [
+            case.values[0] for mark in test_method.pytestmark
+            if mark.name == 'parametrize'
+            for case in mark.args[1]
+        ]
+
+class TestHyp2f1ExtremeInputs:
+
+    @pytest.mark.parametrize("a", [1.0, 2.0, 3.0, -np.inf, np.inf])
+    @pytest.mark.parametrize("b", [3.0, 4.0, 5.0, -np.inf, np.inf])
+    @pytest.mark.parametrize("c", [3.0, 5.0, 6.0, 7.0])
+    @pytest.mark.parametrize("z", [4.0 + 1.0j])
+    def test_inf_a_b(self, a, b, c, z):
+        if np.any(np.isinf(np.asarray([a, b]))):
+            assert(np.isnan(hyp2f1(a, b, c, z)))
+
+    def test_large_a_b(self):
+        assert(np.isnan(hyp2f1(10**7, 1.0, 3.0, 4.0 + 1.0j)))
+        assert(np.isnan(hyp2f1(-10**7, 1.0, 3.0, 4.0 + 1.0j)))
+
+        assert(np.isnan(hyp2f1(1.0, 10**7, 3.0, 4.0 + 1.0j)))
+        assert(np.isnan(hyp2f1(1.0, -10**7, 3.0, 4.0 + 1.0j)))
+
+        # Already correct in main but testing for surety
+        assert(np.isnan(hyp2f1(np.inf, 1.0, 3.0, 4.0)))
+        assert(np.isnan(hyp2f1(1.0, np.inf, 3.0, 4.0)))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ad092491905ae66c39cd881836054aef3dc6f6e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_hypergeometric.py
@@ -0,0 +1,234 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+import scipy.special as sc
+
+
+class TestHyperu:
+
+    def test_negative_x(self):
+        a, b, x = np.meshgrid(
+            [-1, -0.5, 0, 0.5, 1],
+            [-1, -0.5, 0, 0.5, 1],
+            np.linspace(-100, -1, 10),
+        )
+        assert np.all(np.isnan(sc.hyperu(a, b, x)))
+
+    def test_special_cases(self):
+        assert sc.hyperu(0, 1, 1) == 1.0
+
+    @pytest.mark.parametrize('a', [0.5, 1, np.nan])
+    @pytest.mark.parametrize('b', [1, 2, np.nan])
+    @pytest.mark.parametrize('x', [0.25, 3, np.nan])
+    def test_nan_inputs(self, a, b, x):
+        assert np.isnan(sc.hyperu(a, b, x)) == np.any(np.isnan([a, b, x]))
+
+    @pytest.mark.parametrize(
+        'a,b,x,expected',
+        [(0.21581740448533887, 1.0, 1e-05, 3.6030558839391325),
+         (0.21581740448533887, 1.0, 0.00021544346900318823, 2.8783254988948976),
+         (0.21581740448533887, 1.0, 0.004641588833612777, 2.154928216691109),
+         (0.21581740448533887, 1.0, 0.1, 1.446546638718792),
+         (0.0030949064301273865, 1.0, 1e-05, 1.0356696454116199),
+         (0.0030949064301273865, 1.0, 0.00021544346900318823, 1.0261510362481985),
+         (0.0030949064301273865, 1.0, 0.004641588833612777, 1.0166326903402296),
+         (0.0030949064301273865, 1.0, 0.1, 1.0071174207698674),
+         (0.1509924314279033, 1.0, 1e-05, 2.806173846998948),
+         (0.1509924314279033, 1.0, 0.00021544346900318823, 2.3092158526816124),
+         (0.1509924314279033, 1.0, 0.004641588833612777, 1.812905980588048),
+         (0.1509924314279033, 1.0, 0.1, 1.3239738117634872),
+         (-0.010678995342969011, 1.0, 1e-05, 0.8775194903781114),
+         (-0.010678995342969011, 1.0, 0.00021544346900318823, 0.9101008998540128),
+         (-0.010678995342969011, 1.0, 0.004641588833612777, 0.9426854294058609),
+         (-0.010678995342969011, 1.0, 0.1, 0.9753065150174902),
+         (-0.06556622211831487, 1.0, 1e-05, 0.26435429752668904),
+         (-0.06556622211831487, 1.0, 0.00021544346900318823, 0.4574756033875781),
+         (-0.06556622211831487, 1.0, 0.004641588833612777, 0.6507121093358457),
+         (-0.06556622211831487, 1.0, 0.1, 0.8453129788602187),
+         (-0.21628242470175185, 1.0, 1e-05, -1.2318314201114489),
+         (-0.21628242470175185, 1.0, 0.00021544346900318823, -0.6704694233529538),
+         (-0.21628242470175185, 1.0, 0.004641588833612777, -0.10795098653682857),
+         (-0.21628242470175185, 1.0, 0.1, 0.4687227684115524)]
+    )
+    def test_gh_15650_mp(self, a, b, x, expected):
+        # See https://github.com/scipy/scipy/issues/15650
+        # b == 1, |a| < 0.25, 0 < x < 1
+        #
+        # This purpose of this test is to check the accuracy of results
+        # in the region that was impacted by gh-15650.
+        #
+        # Reference values computed with mpmath using the script:
+        #
+        # import itertools as it
+        # import numpy as np
+        #
+        # from mpmath import mp
+        #
+        # rng = np.random.default_rng(1234)
+        #
+        # cases = []
+        # for a, x in it.product(
+        #         np.random.uniform(-0.25, 0.25, size=6),
+        #         np.logspace(-5, -1, 4),
+        # ):
+        #     with mp.workdps(100):
+        #         cases.append((float(a), 1.0, float(x), float(mp.hyperu(a, 1.0, x))))
+        assert_allclose(sc.hyperu(a, b, x), expected, rtol=1e-13)
+
+    def test_gh_15650_sanity(self):
+        # The purpose of this test is to sanity check hyperu in the region that
+        # was impacted by gh-15650 by making sure there are no excessively large
+        # results, as were reported there.
+        a = np.linspace(-0.5, 0.5, 500)
+        x = np.linspace(1e-6, 1e-1, 500)
+        a, x = np.meshgrid(a, x)
+        results = sc.hyperu(a, 1.0, x)
+        assert np.all(np.abs(results) < 1e3)
+
+
+class TestHyp1f1:
+
+    @pytest.mark.parametrize('a, b, x', [
+        (np.nan, 1, 1),
+        (1, np.nan, 1),
+        (1, 1, np.nan)
+    ])
+    def test_nan_inputs(self, a, b, x):
+        assert np.isnan(sc.hyp1f1(a, b, x))
+
+    def test_poles(self):
+        assert_equal(sc.hyp1f1(1, [0, -1, -2, -3, -4], 0.5), np.inf)
+
+    @pytest.mark.parametrize('a, b, x, result', [
+        (-1, 1, 0.5, 0.5),
+        (1, 1, 0.5, 1.6487212707001281468),
+        (2, 1, 0.5, 2.4730819060501922203),
+        (1, 2, 0.5, 1.2974425414002562937),
+        (-10, 1, 0.5, -0.38937441413785204475)
+    ])
+    def test_special_cases(self, a, b, x, result):
+        # Hit all the special case branches at the beginning of the
+        # function. Desired answers computed using Mpmath.
+        assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=1e-15)
+
+    @pytest.mark.parametrize('a, b, x, result', [
+        (1, 1, 0.44, 1.5527072185113360455),
+        (-1, 1, 0.44, 0.55999999999999999778),
+        (100, 100, 0.89, 2.4351296512898745592),
+        (-100, 100, 0.89, 0.40739062490768104667),
+        (1.5, 100, 59.99, 3.8073513625965598107),
+        (-1.5, 100, 59.99, 0.25099240047125826943)
+    ])
+    def test_geometric_convergence(self, a, b, x, result):
+        # Test the region where we are relying on the ratio of
+        #
+        # (|a| + 1) * |x| / |b|
+        #
+        # being small. Desired answers computed using Mpmath
+        assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=1e-15)
+
+    @pytest.mark.parametrize('a, b, x, result', [
+        (-1, 1, 1.5, -0.5),
+        (-10, 1, 1.5, 0.41801777430943080357),
+        (-25, 1, 1.5, 0.25114491646037839809),
+        (-50, 1, 1.5, -0.25683643975194756115),
+        (-80, 1, 1.5, -0.24554329325751503601),
+        (-150, 1, 1.5, -0.173364795515420454496),
+    ])
+    def test_a_negative_integer(self, a, b, x, result):
+        # Desired answers computed using Mpmath.
+        assert_allclose(sc.hyp1f1(a, b, x), result, atol=0, rtol=2e-14)
+
+    @pytest.mark.parametrize('a, b, x, expected', [
+        (0.01, 150, -4, 0.99973683897677527773),        # gh-3492
+        (1, 5, 0.01, 1.0020033381011970966),            # gh-3593
+        (50, 100, 0.01, 1.0050126452421463411),         # gh-3593
+        (1, 0.3, -1e3, -7.011932249442947651455e-04),   # gh-14149
+        (1, 0.3, -1e4, -7.001190321418937164734e-05),   # gh-14149
+        (9, 8.5, -350, -5.224090831922378361082e-20),   # gh-17120
+        (9, 8.5, -355, -4.595407159813368193322e-20),   # gh-17120
+        (75, -123.5, 15, 3.425753920814889017493e+06),
+    ])
+    def test_assorted_cases(self, a, b, x, expected):
+        # Expected values were computed with mpmath.hyp1f1(a, b, x).
+        assert_allclose(sc.hyp1f1(a, b, x), expected, atol=0, rtol=1e-14)
+
+    def test_a_neg_int_and_b_equal_x(self):
+        # This is a case where the Boost wrapper will call hypergeometric_pFq
+        # instead of hypergeometric_1F1.  When we use a version of Boost in
+        # which https://github.com/boostorg/math/issues/833 is fixed, this
+        # test case can probably be moved into test_assorted_cases.
+        # The expected value was computed with mpmath.hyp1f1(a, b, x).
+        a = -10.0
+        b = 2.5
+        x = 2.5
+        expected = 0.0365323664364104338721
+        computed = sc.hyp1f1(a, b, x)
+        assert_allclose(computed, expected, atol=0, rtol=1e-13)
+
+    @pytest.mark.parametrize('a, b, x, desired', [
+        (-1, -2, 2, 2),
+        (-1, -4, 10, 3.5),
+        (-2, -2, 1, 2.5)
+    ])
+    def test_gh_11099(self, a, b, x, desired):
+        # All desired results computed using Mpmath
+        assert sc.hyp1f1(a, b, x) == desired
+
+    @pytest.mark.parametrize('a', [-3, -2])
+    def test_x_zero_a_and_b_neg_ints_and_a_ge_b(self, a):
+        assert sc.hyp1f1(a, -3, 0) == 1
+
+    # In the following tests with complex z, the reference values
+    # were computed with mpmath.hyp1f1(a, b, z), and verified with
+    # Wolfram Alpha Hypergeometric1F1(a, b, z), except for the
+    # case a=0.1, b=1, z=7-24j, where Wolfram Alpha reported
+    # "Standard computation time exceeded".  That reference value
+    # was confirmed in an online Matlab session, with the commands
+    #
+    #  > format long
+    #  > hypergeom(0.1, 1, 7-24i)
+    #  ans =
+    #   -3.712349651834209 + 4.554636556672912i
+    #
+    @pytest.mark.parametrize(
+        'a, b, z, ref',
+        [(-0.25, 0.5, 1+2j, 1.1814553180903435-1.2792130661292984j),
+         (0.25, 0.5, 1+2j, 0.24636797405707597+1.293434354945675j),
+         (25, 1.5, -2j, -516.1771262822523+407.04142751922024j),
+         (12, -1.5, -10+20j, -5098507.422706547-1341962.8043508842j),
+         pytest.param(
+             10, 250, 10-15j, 1.1985998416598884-0.8613474402403436j,
+             marks=pytest.mark.xfail,
+         ),
+         pytest.param(
+             0.1, 1, 7-24j, -3.712349651834209+4.554636556672913j,
+             marks=pytest.mark.xfail,
+         )
+         ],
+    )
+    def test_complex_z(self, a, b, z, ref):
+        h = sc.hyp1f1(a, b, z)
+        assert_allclose(h, ref, rtol=4e-15)
+
+    # The "legacy edge cases" mentioned in the comments in the following
+    # tests refers to the behavior of hyp1f1(a, b, x) when b is a nonpositive
+    # integer.  In some subcases, the behavior of SciPy does not match that
+    # of Boost (1.81+), mpmath and Mathematica (via Wolfram Alpha online).
+    # If the handling of these edges cases is changed to agree with those
+    # libraries, these test will have to be updated.
+
+    @pytest.mark.parametrize('b', [0, -1, -5])
+    def test_legacy_case1(self, b):
+        # Test results of hyp1f1(0, n, x) for n <= 0.
+        # This is a legacy edge case.
+        # Boost (versions greater than 1.80), Mathematica (via Wolfram Alpha
+        # online) and mpmath all return 1 in this case, but SciPy's hyp1f1
+        # returns inf.
+        assert_equal(sc.hyp1f1(0, b, [-1.5, 0, 1.5]), [np.inf, np.inf, np.inf])
+
+    def test_legacy_case2(self):
+        # This is a legacy edge case.
+        # In software such as boost (1.81+), mpmath and Mathematica,
+        # the value is 1.
+        assert sc.hyp1f1(-4, -3, 0) == np.inf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_iv_ratio.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_iv_ratio.py
new file mode 100644
index 0000000000000000000000000000000000000000..dafc35982c4d4869ead2136e74466f1c44c64556
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_iv_ratio.py
@@ -0,0 +1,249 @@
+# This file contains unit tests for iv_ratio() and related functions.
+
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+from scipy.special._ufuncs import (  # type: ignore[attr-defined]
+    _iv_ratio as iv_ratio,
+    _iv_ratio_c as iv_ratio_c,
+)
+
+
+class TestIvRatio:
+
+    @pytest.mark.parametrize('v,x,r', [
+        (0.5, 0.16666666666666666, 0.16514041292462933),
+        (0.5, 0.3333333333333333, 0.32151273753163434),
+        (0.5, 0.5, 0.46211715726000974),
+        (0.5, 0.6666666666666666, 0.5827829453479101),
+        (0.5, 0.8333333333333335, 0.6822617902381698),
+        (1, 0.3380952380952381, 0.1666773049170313),
+        (1, 0.7083333333333333, 0.33366443586989925),
+        (1, 1.1666666666666667, 0.5023355231537423),
+        (1, 1.8666666666666665, 0.674616572252164),
+        (1, 3.560606060606061, 0.844207659503163),
+        (2.34, 0.7975238095238094, 0.16704903081553285),
+        (2.34, 1.7133333333333334, 0.3360215931268845),
+        (2.34, 2.953333333333333, 0.50681909317803),
+        (2.34, 5.0826666666666656, 0.6755252698800679),
+        (2.34, 10.869696969696973, 0.8379351104498762),
+        (56.789, 19.46575238095238, 0.1667020505391409),
+        (56.789, 42.55008333333333, 0.33353809996933026),
+        (56.789, 75.552, 0.5003932381177826),
+        (56.789, 135.76026666666667, 0.6670528221946127),
+        (56.789, 307.8642424242425, 0.8334999441460798),
+    ])
+    def test_against_reference_values(self, v, x, r):
+        """The reference values are computed using mpmath as follows.
+
+        from mpmath import mp
+        mp.dps = 100
+
+        def iv_ratio_mp(v, x):
+            return mp.besseli(v, x) / mp.besseli(v - 1, x)
+
+        def _sample(n, *, v):
+            '''Return n positive real numbers x such that iv_ratio(v, x) are
+            roughly evenly spaced over (0, 1).  The formula is taken from [1].
+
+            [1] Banerjee A., Dhillon, I. S., Ghosh, J., Sra, S. (2005).
+                "Clustering on the Unit Hypersphere using von Mises-Fisher
+                Distributions."  Journal of Machine Learning Research,
+                6(46):1345-1382.
+            '''
+            r = np.arange(1, n+1) / (n+1)
+            return r * (2*v-r*r) / (1-r*r)
+
+        for v in (0.5, 1, 2.34, 56.789):
+            xs = _sample(5, v=v)
+            for x in xs:
+                print(f"({v}, {x}, {float(iv_ratio_mp(v,x))}),")
+        """
+        assert_allclose(iv_ratio(v, x), r, rtol=4e-16, atol=0)
+
+    @pytest.mark.parametrize('v,x,r', [
+        (1, np.inf, 1),
+        (np.inf, 1, 0),
+    ])
+    def test_inf(self, v, x, r):
+        """If exactly one of v or x is inf and the other is within domain,
+        should return 0 or 1 accordingly."""
+        assert_equal(iv_ratio(v, x), r)
+
+    @pytest.mark.parametrize('v', [0.49, -np.inf, np.nan, np.inf])
+    @pytest.mark.parametrize('x', [-np.finfo(float).smallest_normal,
+                                   -np.finfo(float).smallest_subnormal,
+                                   -np.inf, np.nan, np.inf])
+    def test_nan(self, v, x):
+        """If at least one argument is out of domain, or if v = x = inf,
+        the function should return nan."""
+        assert_equal(iv_ratio(v, x), np.nan)
+
+    @pytest.mark.parametrize('v', [0.5, 1, np.finfo(float).max, np.inf])
+    def test_zero_x(self, v):
+        """If x is +/-0.0, return x to ensure iv_ratio is an odd function."""
+        assert_equal(iv_ratio(v, 0.0), 0.0)
+        assert_equal(iv_ratio(v, -0.0), -0.0)
+
+    @pytest.mark.parametrize('v,x', [
+        (1, np.finfo(float).smallest_normal),
+        (1, np.finfo(float).smallest_subnormal),
+        (1, np.finfo(float).smallest_subnormal*2),
+        (1e20, 123),
+        (np.finfo(float).max, 1),
+        (np.finfo(float).max, np.sqrt(np.finfo(float).max)),
+    ])
+    def test_tiny_x(self, v, x):
+        """If x is much less than v, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= -----------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-1+sqrt(x**2+(v+1)**2)
+
+        collapses to R ~= x/2v.  Test against this asymptotic expression.
+        """
+        assert_equal(iv_ratio(v, x), (0.5*x)/v)
+
+    @pytest.mark.parametrize('v,x', [
+        (1, 1e16),
+        (1e20, 1e40),
+        (np.sqrt(np.finfo(float).max), np.finfo(float).max),
+    ])
+    def test_huge_x(self, v, x):
+        """If x is much greater than v, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= ---------------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-0.5+sqrt(x**2+(v-0.5)**2)
+
+        collapses to R ~= 1.  Test against this asymptotic expression.
+        """
+        assert_equal(iv_ratio(v, x), 1.0)
+
+    @pytest.mark.parametrize('v,x', [
+        (np.finfo(float).max, np.finfo(float).max),
+        (np.finfo(float).max / 3, np.finfo(float).max),
+        (np.finfo(float).max, np.finfo(float).max / 3),
+    ])
+    def test_huge_v_x(self, v, x):
+        """If both x and v are very large, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= -----------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-1+sqrt(x**2+(v+1)**2)
+
+        collapses to R ~= x/(v+sqrt(x**2+v**2).  Test against this asymptotic
+        expression, and in particular that no numerical overflow occurs during
+        intermediate calculations.
+        """
+        t = x / v
+        expected = t / (1 + np.hypot(1, t))
+        assert_allclose(iv_ratio(v, x), expected, rtol=4e-16, atol=0)
+
+
+class TestIvRatioC:
+
+    @pytest.mark.parametrize('v,x,r', [
+        (0.5, 0.16666666666666666, 0.8348595870753707),
+        (0.5, 0.3333333333333333, 0.6784872624683657),
+        (0.5, 0.5, 0.5378828427399902),
+        (0.5, 0.6666666666666666, 0.4172170546520899),
+        (0.5, 0.8333333333333335, 0.3177382097618302),
+        (1, 0.3380952380952381, 0.8333226950829686),
+        (1, 0.7083333333333333, 0.6663355641301008),
+        (1, 1.1666666666666667, 0.4976644768462577),
+        (1, 1.8666666666666665, 0.325383427747836),
+        (1, 3.560606060606061, 0.155792340496837),
+        (2.34, 0.7975238095238094, 0.8329509691844672),
+        (2.34, 1.7133333333333334, 0.6639784068731155),
+        (2.34, 2.953333333333333, 0.49318090682197),
+        (2.34, 5.0826666666666656, 0.3244747301199321),
+        (2.34, 10.869696969696973, 0.16206488955012377),
+        (56.789, 19.46575238095238, 0.8332979494608591),
+        (56.789, 42.55008333333333, 0.6664619000306697),
+        (56.789, 75.552, 0.4996067618822174),
+        (56.789, 135.76026666666667, 0.3329471778053873),
+        (56.789, 307.8642424242425, 0.16650005585392025),
+    ])
+    def test_against_reference_values(self, v, x, r):
+        """The reference values are one minus those of TestIvRatio."""
+        assert_allclose(iv_ratio_c(v, x), r, rtol=1e-15, atol=0)
+
+    @pytest.mark.parametrize('v,x,r', [
+        (1, np.inf, 0),
+        (np.inf, 1, 1),
+    ])
+    def test_inf(self, v, x, r):
+        """If exactly one of v or x is inf and the other is within domain,
+        should return 0 or 1 accordingly."""
+        assert_equal(iv_ratio_c(v, x), r)
+
+    @pytest.mark.parametrize('v', [0.49, -np.inf, np.nan, np.inf])
+    @pytest.mark.parametrize('x', [-np.finfo(float).smallest_normal,
+                                   -np.finfo(float).smallest_subnormal,
+                                   -np.inf, np.nan, np.inf])
+    def test_nan(self, v, x):
+        """If at least one argument is out of domain, or if v = x = inf,
+        the function should return nan."""
+        assert_equal(iv_ratio_c(v, x), np.nan)
+
+    @pytest.mark.parametrize('v', [0.5, 1, np.finfo(float).max, np.inf])
+    def test_zero_x(self, v):
+        """If x is +/-0.0, return 1."""
+        assert_equal(iv_ratio_c(v, 0.0), 1.0)
+        assert_equal(iv_ratio_c(v, -0.0), 1.0)
+
+    @pytest.mark.parametrize('v,x', [
+        (1, np.finfo(float).smallest_normal),
+        (1, np.finfo(float).smallest_subnormal),
+        (1, np.finfo(float).smallest_subnormal*2),
+        (1e20, 123),
+        (np.finfo(float).max, 1),
+        (np.finfo(float).max, np.sqrt(np.finfo(float).max)),
+    ])
+    def test_tiny_x(self, v, x):
+        """If x is much less than v, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= -----------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-1+sqrt(x**2+(v+1)**2)
+
+        collapses to 1-R ~= 1-x/2v.  Test against this asymptotic expression.
+        """
+        assert_equal(iv_ratio_c(v, x), 1.0-(0.5*x)/v)
+
+    @pytest.mark.parametrize('v,x', [
+        (1, 1e16),
+        (1e20, 1e40),
+        (np.sqrt(np.finfo(float).max), np.finfo(float).max),
+    ])
+    def test_huge_x(self, v, x):
+        """If x is much greater than v, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= ---------------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-0.5+sqrt(x**2+(v-0.5)**2)
+
+        collapses to 1-R ~= (v-0.5)/x.  Test against this asymptotic expression.
+        """
+        assert_allclose(iv_ratio_c(v, x), (v-0.5)/x, rtol=1e-15, atol=0)
+
+    @pytest.mark.parametrize('v,x', [
+        (np.finfo(float).max, np.finfo(float).max),
+        (np.finfo(float).max / 3, np.finfo(float).max),
+        (np.finfo(float).max, np.finfo(float).max / 3),
+    ])
+    def test_huge_v_x(self, v, x):
+        """If both x and v are very large, the bounds
+
+                    x                                 x
+        --------------------------- <= R <= -----------------------
+        v-0.5+sqrt(x**2+(v+0.5)**2)         v-1+sqrt(x**2+(v+1)**2)
+
+        collapses to 1 - R ~= 1 - x/(v+sqrt(x**2+v**2).  Test against this
+        asymptotic expression, and in particular that no numerical overflow
+        occurs during intermediate calculations.
+        """
+        t = x / v
+        expected = 1 - t / (1 + np.hypot(1, t))
+        assert_allclose(iv_ratio_c(v, x), expected, rtol=4e-16, atol=0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py
new file mode 100644
index 0000000000000000000000000000000000000000..ade38115706808809890e1eba3b938562b0af6e6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_kolmogorov.py
@@ -0,0 +1,491 @@
+import itertools
+
+import numpy as np
+from numpy.testing import assert_
+from scipy.special._testutils import FuncData
+
+from scipy.special import kolmogorov, kolmogi, smirnov, smirnovi
+from scipy.special._ufuncs import (_kolmogc, _kolmogci, _kolmogp,
+                                   _smirnovc, _smirnovci, _smirnovp)
+
+_rtol = 1e-10
+
+class TestSmirnov:
+    def test_nan(self):
+        assert_(np.isnan(smirnov(1, np.nan)))
+
+    def test_basic(self):
+        dataset = [(1, 0.1, 0.9),
+                   (1, 0.875, 0.125),
+                   (2, 0.875, 0.125 * 0.125),
+                   (3, 0.875, 0.125 * 0.125 * 0.125)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_0(self):
+        dataset = [(n, 0, 1) for n in itertools.chain(range(2, 20), range(1010, 1020))]
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_1(self):
+        dataset = [(n, 1, 0) for n in itertools.chain(range(2, 20), range(1010, 1020))]
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_0point5(self):
+        dataset = [(1, 0.5, 0.5),
+                   (2, 0.5, 0.25),
+                   (3, 0.5, 0.166666666667),
+                   (4, 0.5, 0.09375),
+                   (5, 0.5, 0.056),
+                   (6, 0.5, 0.0327932098765),
+                   (7, 0.5, 0.0191958707681),
+                   (8, 0.5, 0.0112953186035),
+                   (9, 0.5, 0.00661933257355),
+                   (10, 0.5, 0.003888705)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_1(self):
+        x = np.linspace(0, 1, 101, endpoint=True)
+        dataset = np.column_stack([[1]*len(x), x, 1-x])
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_2(self):
+        x = np.linspace(0.5, 1, 101, endpoint=True)
+        p = np.power(1-x, 2)
+        n = np.array([2] * len(x))
+        dataset = np.column_stack([n, x, p])
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_3(self):
+        x = np.linspace(0.7, 1, 31, endpoint=True)
+        p = np.power(1-x, 3)
+        n = np.array([3] * len(x))
+        dataset = np.column_stack([n, x, p])
+        FuncData(
+            smirnov, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, -1] = 1 - dataset[:, -1]
+        FuncData(
+            _smirnovc, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_large(self):
+        # test for large values of n
+        # Probabilities should go down as n goes up
+        x = 0.4
+        pvals = np.array([smirnov(n, x) for n in range(400, 1100, 20)])
+        dfs = np.diff(pvals)
+        assert_(np.all(dfs <= 0), msg=f'Not all diffs negative {dfs}')
+
+
+class TestSmirnovi:
+    def test_nan(self):
+        assert_(np.isnan(smirnovi(1, np.nan)))
+
+    def test_basic(self):
+        dataset = [(1, 0.4, 0.6),
+                   (1, 0.6, 0.4),
+                   (1, 0.99, 0.01),
+                   (1, 0.01, 0.99),
+                   (2, 0.125 * 0.125, 0.875),
+                   (3, 0.125 * 0.125 * 0.125, 0.875),
+                   (10, 1.0 / 16 ** 10, 1 - 1.0 / 16)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_0(self):
+        dataset = [(n, 0, 1) for n in itertools.chain(range(2, 20), range(1010, 1020))]
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_1(self):
+        dataset = [(n, 1, 0) for n in itertools.chain(range(2, 20), range(1010, 1020))]
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_1(self):
+        pp = np.linspace(0, 1, 101, endpoint=True)
+        # dataset = np.array([(1, p, 1-p) for p in pp])
+        dataset = np.column_stack([[1]*len(pp), pp, 1-pp])
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_2(self):
+        x = np.linspace(0.5, 1, 101, endpoint=True)
+        p = np.power(1-x, 2)
+        n = np.array([2] * len(x))
+        dataset = np.column_stack([n, p, x])
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_n_equals_3(self):
+        x = np.linspace(0.7, 1, 31, endpoint=True)
+        p = np.power(1-x, 3)
+        n = np.array([3] * len(x))
+        dataset = np.column_stack([n, p, x])
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_round_trip(self):
+        def _sm_smi(n, p):
+            return smirnov(n, smirnovi(n, p))
+
+        def _smc_smci(n, p):
+            return _smirnovc(n, _smirnovci(n, p))
+
+        dataset = [(1, 0.4, 0.4),
+                   (1, 0.6, 0.6),
+                   (2, 0.875, 0.875),
+                   (3, 0.875, 0.875),
+                   (3, 0.125, 0.125),
+                   (10, 0.999, 0.999),
+                   (10, 0.0001, 0.0001)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            _sm_smi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        FuncData(
+            _smc_smci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_x_equals_0point5(self):
+        dataset = [(1, 0.5, 0.5),
+                   (2, 0.5, 0.366025403784),
+                   (2, 0.25, 0.5),
+                   (3, 0.5, 0.297156508177),
+                   (4, 0.5, 0.255520481121),
+                   (5, 0.5, 0.234559536069),
+                   (6, 0.5, 0.21715965898),
+                   (7, 0.5, 0.202722580034),
+                   (8, 0.5, 0.190621765256),
+                   (9, 0.5, 0.180363501362),
+                   (10, 0.5, 0.17157867006)]
+
+        dataset = np.asarray(dataset)
+        FuncData(
+            smirnovi, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+        dataset[:, 1] = 1 - dataset[:, 1]
+        FuncData(
+            _smirnovci, dataset, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+
+class TestSmirnovp:
+    def test_nan(self):
+        assert_(np.isnan(_smirnovp(1, np.nan)))
+
+    def test_basic(self):
+        # Check derivative at endpoints
+        n1_10 = np.arange(1, 10)
+        dataset0 = np.column_stack([n1_10,
+                                    np.full_like(n1_10, 0),
+                                    np.full_like(n1_10, -1)])
+        FuncData(
+            _smirnovp, dataset0, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+        n2_10 = np.arange(2, 10)
+        dataset1 = np.column_stack([n2_10,
+                                    np.full_like(n2_10, 1.0),
+                                    np.full_like(n2_10, 0)])
+        FuncData(
+            _smirnovp, dataset1, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_oneminusoneovern(self):
+        # Check derivative at x=1-1/n
+        n = np.arange(1, 20)
+        x = 1.0/n
+        xm1 = 1-1.0/n
+        pp1 = -n * x**(n-1)
+        pp1 -= (1-np.sign(n-2)**2) * 0.5  # n=2, x=0.5, 1-1/n = 0.5, need to adjust
+        dataset1 = np.column_stack([n, xm1, pp1])
+        FuncData(
+            _smirnovp, dataset1, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_oneovertwon(self):
+        # Check derivative at x=1/2n  (Discontinuous at x=1/n, so check at x=1/2n)
+        n = np.arange(1, 20)
+        x = 1.0/2/n
+        pp = -(n*x+1) * (1+x)**(n-2)
+        dataset0 = np.column_stack([n, x, pp])
+        FuncData(
+            _smirnovp, dataset0, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_oneovern(self):
+        # Check derivative at x=1/n
+        # (Discontinuous at x=1/n, hard to tell if x==1/n, only use n=power of 2)
+        n = 2**np.arange(1, 10)
+        x = 1.0/n
+        pp = -(n*x+1) * (1+x)**(n-2) + 0.5
+        dataset0 = np.column_stack([n, x, pp])
+        FuncData(
+            _smirnovp, dataset0, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+    def test_oneovernclose(self):
+        # Check derivative at x=1/n
+        # (Discontinuous at x=1/n, test on either side: x=1/n +/- 2epsilon)
+        n = np.arange(3, 20)
+
+        x = 1.0/n - 2*np.finfo(float).eps
+        pp = -(n*x+1) * (1+x)**(n-2)
+        dataset0 = np.column_stack([n, x, pp])
+        FuncData(
+            _smirnovp, dataset0, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+        x = 1.0/n + 2*np.finfo(float).eps
+        pp = -(n*x+1) * (1+x)**(n-2) + 1
+        dataset1 = np.column_stack([n, x, pp])
+        FuncData(
+            _smirnovp, dataset1, (0, 1), 2, rtol=_rtol
+        ).check(dtypes=[int, float, float])
+
+
+class TestKolmogorov:
+    def test_nan(self):
+        assert_(np.isnan(kolmogorov(np.nan)))
+
+    def test_basic(self):
+        dataset = [(0, 1.0),
+                   (0.5, 0.96394524366487511),
+                   (0.8275735551899077, 0.5000000000000000),
+                   (1, 0.26999967167735456),
+                   (2, 0.00067092525577969533)]
+
+        dataset = np.asarray(dataset)
+        FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_linspace(self):
+        x = np.linspace(0, 2.0, 21)
+        dataset = [1.0000000000000000, 1.0000000000000000, 0.9999999999994950,
+                   0.9999906941986655, 0.9971923267772983, 0.9639452436648751,
+                   0.8642827790506042, 0.7112351950296890, 0.5441424115741981,
+                   0.3927307079406543, 0.2699996716773546, 0.1777181926064012,
+                   0.1122496666707249, 0.0680922218447664, 0.0396818795381144,
+                   0.0222179626165251, 0.0119520432391966, 0.0061774306344441,
+                   0.0030676213475797, 0.0014636048371873, 0.0006709252557797]
+
+        dataset_c = [0.0000000000000000, 6.609305242245699e-53, 5.050407338670114e-13,
+                     9.305801334566668e-06, 0.0028076732227017, 0.0360547563351249,
+                     0.1357172209493958, 0.2887648049703110, 0.4558575884258019,
+                     0.6072692920593457, 0.7300003283226455, 0.8222818073935988,
+                     0.8877503333292751, 0.9319077781552336, 0.9603181204618857,
+                     0.9777820373834749, 0.9880479567608034, 0.9938225693655559,
+                     0.9969323786524203, 0.9985363951628127, 0.9993290747442203]
+
+        dataset = np.column_stack([x, dataset])
+        FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check()
+        dataset_c = np.column_stack([x, dataset_c])
+        FuncData(_kolmogc, dataset_c, (0,), 1, rtol=_rtol).check()
+
+    def test_linspacei(self):
+        p = np.linspace(0, 1.0, 21, endpoint=True)
+        dataset = [np.inf, 1.3580986393225507, 1.2238478702170823,
+                   1.1379465424937751, 1.0727491749396481, 1.0191847202536859,
+                   0.9730633753323726, 0.9320695842357622, 0.8947644549851197,
+                   0.8601710725555463, 0.8275735551899077, 0.7964065373291559,
+                   0.7661855555617682, 0.7364542888171910, 0.7067326523068980,
+                   0.6764476915028201, 0.6448126061663567, 0.6105590999244391,
+                   0.5711732651063401, 0.5196103791686224, 0.0000000000000000]
+
+        dataset_c = [0.0000000000000000, 0.5196103791686225, 0.5711732651063401,
+                     0.6105590999244391, 0.6448126061663567, 0.6764476915028201,
+                     0.7067326523068980, 0.7364542888171910, 0.7661855555617682,
+                     0.7964065373291559, 0.8275735551899077, 0.8601710725555463,
+                     0.8947644549851196, 0.9320695842357622, 0.9730633753323727,
+                     1.0191847202536859, 1.0727491749396481, 1.1379465424937754,
+                     1.2238478702170825, 1.3580986393225509, np.inf]
+
+        dataset = np.column_stack([p[1:], dataset[1:]])
+        FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check()
+        dataset_c = np.column_stack([p[:-1], dataset_c[:-1]])
+        FuncData(_kolmogci, dataset_c, (0,), 1, rtol=_rtol).check()
+
+    def test_smallx(self):
+        epsilon = 0.1 ** np.arange(1, 14)
+        x = np.array([0.571173265106, 0.441027698518, 0.374219690278, 0.331392659217,
+                      0.300820537459, 0.277539353999, 0.259023494805, 0.243829561254,
+                      0.231063086389, 0.220135543236, 0.210641372041, 0.202290283658,
+                      0.19487060742])
+
+        dataset = np.column_stack([x, 1-epsilon])
+        FuncData(kolmogorov, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_round_trip(self):
+        def _ki_k(_x):
+            return kolmogi(kolmogorov(_x))
+
+        def _kci_kc(_x):
+            return _kolmogci(_kolmogc(_x))
+
+        x = np.linspace(0.0, 2.0, 21, endpoint=True)
+        # Exclude 0.1, 0.2.  0.2 almost makes succeeds, but 0.1 has no chance.
+        x02 = x[(x == 0) | (x > 0.21)]
+        dataset02 = np.column_stack([x02, x02])
+        FuncData(_ki_k, dataset02, (0,), 1, rtol=_rtol).check()
+
+        dataset = np.column_stack([x, x])
+        FuncData(_kci_kc, dataset, (0,), 1, rtol=_rtol).check()
+
+
+class TestKolmogi:
+    def test_nan(self):
+        assert_(np.isnan(kolmogi(np.nan)))
+
+    def test_basic(self):
+        dataset = [(1.0, 0),
+                   (0.96394524366487511, 0.5),
+                   (0.9, 0.571173265106),
+                   (0.5000000000000000, 0.8275735551899077),
+                   (0.26999967167735456, 1),
+                   (0.00067092525577969533, 2)]
+
+        dataset = np.asarray(dataset)
+        FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_smallpcdf(self):
+        epsilon = 0.5 ** np.arange(1, 55, 3)
+        # kolmogi(1-p) == _kolmogci(p) if  1-(1-p) == p, but not necessarily otherwise
+        # Use epsilon s.t. 1-(1-epsilon)) == epsilon,
+        # so can use same x-array for both results
+
+        x = np.array([0.8275735551899077, 0.5345255069097583, 0.4320114038786941,
+                      0.3736868442620478, 0.3345161714909591, 0.3057833329315859,
+                      0.2835052890528936, 0.2655578150208676, 0.2506869966107999,
+                      0.2380971058736669, 0.2272549289962079, 0.2177876361600040,
+                      0.2094254686862041, 0.2019676748836232, 0.1952612948137504,
+                      0.1891874239646641, 0.1836520225050326, 0.1785795904846466])
+
+        dataset = np.column_stack([1-epsilon, x])
+        FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check()
+
+        dataset = np.column_stack([epsilon, x])
+        FuncData(_kolmogci, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_smallpsf(self):
+        epsilon = 0.5 ** np.arange(1, 55, 3)
+        # kolmogi(p) == _kolmogci(1-p) if  1-(1-p) == p, but not necessarily otherwise
+        # Use epsilon s.t. 1-(1-epsilon)) == epsilon,
+        # so can use same x-array for both results
+
+        x = np.array([0.8275735551899077, 1.3163786275161036, 1.6651092133663343,
+                      1.9525136345289607, 2.2027324540033235, 2.4272929437460848,
+                      2.6327688477341593, 2.8233300509220260, 3.0018183401530627,
+                      3.1702735084088891, 3.3302184446307912, 3.4828258153113318,
+                      3.6290214150152051, 3.7695513262825959, 3.9050272690877326,
+                      4.0359582187082550, 4.1627730557884890, 4.2858371743264527])
+
+        dataset = np.column_stack([epsilon, x])
+        FuncData(kolmogi, dataset, (0,), 1, rtol=_rtol).check()
+
+        dataset = np.column_stack([1-epsilon, x])
+        FuncData(_kolmogci, dataset, (0,), 1, rtol=_rtol).check()
+
+    def test_round_trip(self):
+        def _k_ki(_p):
+            return kolmogorov(kolmogi(_p))
+
+        p = np.linspace(0.1, 1.0, 10, endpoint=True)
+        dataset = np.column_stack([p, p])
+        FuncData(_k_ki, dataset, (0,), 1, rtol=_rtol).check()
+
+
+class TestKolmogp:
+    def test_nan(self):
+        assert_(np.isnan(_kolmogp(np.nan)))
+
+    def test_basic(self):
+        dataset = [(0.000000, -0.0),
+                   (0.200000, -1.532420541338916e-10),
+                   (0.400000, -0.1012254419260496),
+                   (0.600000, -1.324123244249925),
+                   (0.800000, -1.627024345636592),
+                   (1.000000, -1.071948558356941),
+                   (1.200000, -0.538512430720529),
+                   (1.400000, -0.2222133182429472),
+                   (1.600000, -0.07649302775520538),
+                   (1.800000, -0.02208687346347873),
+                   (2.000000, -0.005367402045629683)]
+
+        dataset = np.asarray(dataset)
+        FuncData(_kolmogp, dataset, (0,), 1, rtol=_rtol).check()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7fde685406661b821bb1dc490ca0da173eb4bd0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_lambertw.py
@@ -0,0 +1,109 @@
+#
+# Tests for the lambertw function,
+# Adapted from the MPMath tests [1] by Yosef Meller, mellerf@netvision.net.il
+# Distributed under the same license as SciPy itself.
+#
+# [1] mpmath source code, Subversion revision 992
+#     http://code.google.com/p/mpmath/source/browse/trunk/mpmath/tests/test_functions2.py?spec=svn994&r=992
+
+import pytest
+import numpy as np
+from numpy.testing import assert_, assert_equal, assert_array_almost_equal
+from scipy.special import lambertw
+from numpy import nan, inf, pi, e, isnan, log, r_, array, complex128
+
+from scipy.special._testutils import FuncData
+
+
+def test_values():
+    assert_(isnan(lambertw(nan)))
+    assert_equal(lambertw(inf,1).real, inf)
+    assert_equal(lambertw(inf,1).imag, 2*pi)
+    assert_equal(lambertw(-inf,1).real, inf)
+    assert_equal(lambertw(-inf,1).imag, 3*pi)
+
+    assert_equal(lambertw(1.), lambertw(1., 0))
+
+    data = [
+        (0,0, 0),
+        (0+0j,0, 0),
+        (inf,0, inf),
+        (0,-1, -inf),
+        (0,1, -inf),
+        (0,3, -inf),
+        (e,0, 1),
+        (1,0, 0.567143290409783873),
+        (-pi/2,0, 1j*pi/2),
+        (-log(2)/2,0, -log(2)),
+        (0.25,0, 0.203888354702240164),
+        (-0.25,0, -0.357402956181388903),
+        (-1./10000,0, -0.000100010001500266719),
+        (-0.25,-1, -2.15329236411034965),
+        (0.25,-1, -3.00899800997004620-4.07652978899159763j),
+        (-0.25,-1, -2.15329236411034965),
+        (0.25,1, -3.00899800997004620+4.07652978899159763j),
+        (-0.25,1, -3.48973228422959210+7.41405453009603664j),
+        (-4,0, 0.67881197132094523+1.91195078174339937j),
+        (-4,1, -0.66743107129800988+7.76827456802783084j),
+        (-4,-1, 0.67881197132094523-1.91195078174339937j),
+        (1000,0, 5.24960285240159623),
+        (1000,1, 4.91492239981054535+5.44652615979447070j),
+        (1000,-1, 4.91492239981054535-5.44652615979447070j),
+        (1000,5, 3.5010625305312892+29.9614548941181328j),
+        (3+4j,0, 1.281561806123775878+0.533095222020971071j),
+        (-0.4+0.4j,0, -0.10396515323290657+0.61899273315171632j),
+        (3+4j,1, -0.11691092896595324+5.61888039871282334j),
+        (3+4j,-1, 0.25856740686699742-3.85211668616143559j),
+        (-0.5,-1, -0.794023632344689368-0.770111750510379110j),
+        (-1./10000,1, -11.82350837248724344+6.80546081842002101j),
+        (-1./10000,-1, -11.6671145325663544),
+        (-1./10000,-2, -11.82350837248724344-6.80546081842002101j),
+        (-1./100000,4, -14.9186890769540539+26.1856750178782046j),
+        (-1./100000,5, -15.0931437726379218666+32.5525721210262290086j),
+        ((2+1j)/10,0, 0.173704503762911669+0.071781336752835511j),
+        ((2+1j)/10,1, -3.21746028349820063+4.56175438896292539j),
+        ((2+1j)/10,-1, -3.03781405002993088-3.53946629633505737j),
+        ((2+1j)/10,4, -4.6878509692773249+23.8313630697683291j),
+        (-(2+1j)/10,0, -0.226933772515757933-0.164986470020154580j),
+        (-(2+1j)/10,1, -2.43569517046110001+0.76974067544756289j),
+        (-(2+1j)/10,-1, -3.54858738151989450-6.91627921869943589j),
+        (-(2+1j)/10,4, -4.5500846928118151+20.6672982215434637j),
+        (pi,0, 1.073658194796149172092178407024821347547745350410314531),
+
+        # Former bug in generated branch,
+        (-0.5+0.002j,0, -0.78917138132659918344 + 0.76743539379990327749j),
+        (-0.5-0.002j,0, -0.78917138132659918344 - 0.76743539379990327749j),
+        (-0.448+0.4j,0, -0.11855133765652382241 + 0.66570534313583423116j),
+        (-0.448-0.4j,0, -0.11855133765652382241 - 0.66570534313583423116j),
+    ]
+    data = array(data, dtype=complex128)
+
+    def w(x, y):
+        return lambertw(x, y.real.astype(int))
+    with np.errstate(all='ignore'):
+        FuncData(w, data, (0,1), 2, rtol=1e-10, atol=1e-13).check()
+
+
+def test_ufunc():
+    assert_array_almost_equal(
+        lambertw(r_[0., e, 1.]), r_[0., 1., 0.567143290409783873])
+
+
+def test_lambertw_ufunc_loop_selection():
+    # see https://github.com/scipy/scipy/issues/4895
+    dt = np.dtype(np.complex128)
+    assert_equal(lambertw(0, 0, 0).dtype, dt)
+    assert_equal(lambertw([0], 0, 0).dtype, dt)
+    assert_equal(lambertw(0, [0], 0).dtype, dt)
+    assert_equal(lambertw(0, 0, [0]).dtype, dt)
+    assert_equal(lambertw([0], [0], [0]).dtype, dt)
+
+
+@pytest.mark.parametrize('z', [1e-316, -2e-320j, -5e-318+1e-320j])
+def test_lambertw_subnormal_k0(z):
+    # Verify that subnormal inputs are handled correctly on
+    # the branch k=0 (regression test for gh-16291).
+    w = lambertw(z)
+    # For values this small, we can be sure that numerically,
+    # lambertw(z) is z.
+    assert w == z
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py
new file mode 100644
index 0000000000000000000000000000000000000000..430a4175426e30bde02be7972b3144eed4923b27
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_legendre.py
@@ -0,0 +1,1518 @@
+import math
+
+import numpy as np
+
+import pytest
+from numpy.testing import (assert_equal, assert_almost_equal, assert_array_almost_equal,
+    assert_allclose, suppress_warnings)
+
+from scipy import special
+from scipy.special import (legendre_p, legendre_p_all, assoc_legendre_p,
+    assoc_legendre_p_all, sph_legendre_p, sph_legendre_p_all)
+
+# The functions lpn, lpmn, clpmn, appearing below are
+# deprecated in favor of legendre_p_all, assoc_legendre_p_all, and
+# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn)
+# respectively. The deprecated functions listed above are implemented as
+# shims around their respective replacements. The replacements are tested
+# separately, but tests for the deprecated functions remain to verify the
+# correctness of the shims.
+
+# Base polynomials come from Abrahmowitz and Stegan
+class TestLegendre:
+    def test_legendre(self):
+        leg0 = special.legendre(0)
+        leg1 = special.legendre(1)
+        leg2 = special.legendre(2)
+        leg3 = special.legendre(3)
+        leg4 = special.legendre(4)
+        leg5 = special.legendre(5)
+        assert_equal(leg0.c, [1])
+        assert_equal(leg1.c, [1,0])
+        assert_almost_equal(leg2.c, np.array([3,0,-1])/2.0, decimal=13)
+        assert_almost_equal(leg3.c, np.array([5,0,-3,0])/2.0)
+        assert_almost_equal(leg4.c, np.array([35,0,-30,0,3])/8.0)
+        assert_almost_equal(leg5.c, np.array([63,0,-70,0,15,0])/8.0)
+
+    @pytest.mark.parametrize('n', [1, 2, 3, 4, 5])
+    @pytest.mark.parametrize('zr', [0.5241717, 12.80232, -9.699001,
+                                    0.5122437, 0.1714377])
+    @pytest.mark.parametrize('zi', [9.766818, 0.2999083, 8.24726, -22.84843,
+                                    -0.8792666])
+    def test_lpn_against_clpmn(self, n, zr, zi):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            reslpn = special.lpn(n, zr + zi*1j)
+            resclpmn = special.clpmn(0, n, zr+zi*1j)
+
+        assert_allclose(reslpn[0], resclpmn[0][0])
+        assert_allclose(reslpn[1], resclpmn[1][0])
+
+class TestLegendreP:
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_ode(self, shape):
+        rng = np.random.default_rng(1234)
+
+        n = rng.integers(0, 100, shape)
+        x = rng.uniform(-1, 1, shape)
+
+        p, p_jac, p_hess = legendre_p(n, x, diff_n=2)
+
+        assert p.shape == shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        err = (1 - x * x) * p_hess - 2 * x * p_jac + n * (n + 1) * p
+        np.testing.assert_allclose(err, 0, atol=1e-10)
+
+    @pytest.mark.parametrize("n_max", [1, 2, 4, 8, 16, 32])
+    @pytest.mark.parametrize("x_shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_all_ode(self, n_max, x_shape):
+        rng = np.random.default_rng(1234)
+
+        x = rng.uniform(-1, 1, x_shape)
+        p, p_jac, p_hess = legendre_p_all(n_max, x, diff_n=2)
+
+        n = np.arange(n_max + 1)
+        n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 1)))
+
+        assert p.shape == (len(n),) + x.shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        err = (1 - x * x) * p_hess - 2 * x * p_jac + n * (n + 1) * p
+        np.testing.assert_allclose(err, 0, atol=1e-10)
+
+    def test_legacy(self):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            p, pd = special.lpn(2, 0.5)
+
+        assert_array_almost_equal(p, [1.00000, 0.50000, -0.12500], 4)
+        assert_array_almost_equal(pd, [0.00000, 1.00000, 1.50000], 4)
+
+class TestAssocLegendreP:
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
+    @pytest.mark.parametrize("m_max", [5, 4])
+    @pytest.mark.parametrize("n_max", [7, 10])
+    def test_lpmn(self, shape, n_max, m_max):
+        rng = np.random.default_rng(1234)
+
+        x = rng.uniform(-0.99, 0.99, shape)
+        p_all, p_all_jac, p_all_hess = \
+            assoc_legendre_p_all(n_max, m_max, x, diff_n=2)
+
+        n = np.arange(n_max + 1)
+        n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2)))
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2)))
+
+        x = np.expand_dims(x, axis = (0, 1))
+        p, p_jac, p_hess = assoc_legendre_p(n, m, x, diff_n=2)
+
+        np.testing.assert_allclose(p, p_all)
+        np.testing.assert_allclose(p_jac, p_all_jac)
+        np.testing.assert_allclose(p_hess, p_all_hess)
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
+    @pytest.mark.parametrize("norm", [True, False])
+    def test_ode(self, shape, norm):
+        rng = np.random.default_rng(1234)
+
+        n = rng.integers(0, 10, shape)
+        m = rng.integers(-10, 10, shape)
+        x = rng.uniform(-1, 1, shape)
+
+        p, p_jac, p_hess = assoc_legendre_p(n, m, x, norm=norm, diff_n=2)
+
+        assert p.shape == shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        np.testing.assert_allclose((1 - x * x) * p_hess,
+            2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p,
+            rtol=1e-05, atol=1e-08)
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_all(self, shape):
+        rng = np.random.default_rng(1234)
+
+        n_max = 20
+        m_max = 20
+
+        x = rng.uniform(-0.99, 0.99, shape)
+
+        p, p_jac, p_hess = assoc_legendre_p_all(n_max, m_max, x, diff_n=2)
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        n = np.arange(n_max + 1)
+
+        n = np.expand_dims(n, axis = tuple(range(1, x.ndim + 2)))
+        m = np.expand_dims(m, axis = (0,) + tuple(range(2, x.ndim + 2)))
+        np.testing.assert_allclose((1 - x * x) * p_hess,
+            2 * x * p_jac - (n * (n + 1) - m * m / (1 - x * x)) * p,
+            rtol=1e-05, atol=1e-08)
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    @pytest.mark.parametrize("norm", [True, False])
+    def test_specific(self, shape, norm):
+        rng = np.random.default_rng(1234)
+
+        x = rng.uniform(-0.99, 0.99, shape)
+
+        p, p_jac = assoc_legendre_p_all(4, 4, x, norm=norm, diff_n=1)
+
+        np.testing.assert_allclose(p[0, 0],
+            assoc_legendre_p_0_0(x, norm=norm))
+        np.testing.assert_allclose(p[0, 1], 0)
+        np.testing.assert_allclose(p[0, 2], 0)
+        np.testing.assert_allclose(p[0, 3], 0)
+        np.testing.assert_allclose(p[0, 4], 0)
+        np.testing.assert_allclose(p[0, -3], 0)
+        np.testing.assert_allclose(p[0, -2], 0)
+        np.testing.assert_allclose(p[0, -1], 0)
+
+        np.testing.assert_allclose(p[1, 0],
+            assoc_legendre_p_1_0(x, norm=norm))
+        np.testing.assert_allclose(p[1, 1],
+            assoc_legendre_p_1_1(x, norm=norm))
+        np.testing.assert_allclose(p[1, 2], 0)
+        np.testing.assert_allclose(p[1, 3], 0)
+        np.testing.assert_allclose(p[1, 4], 0)
+        np.testing.assert_allclose(p[1, -4], 0)
+        np.testing.assert_allclose(p[1, -3], 0)
+        np.testing.assert_allclose(p[1, -2], 0)
+        np.testing.assert_allclose(p[1, -1],
+            assoc_legendre_p_1_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p[2, 0],
+            assoc_legendre_p_2_0(x, norm=norm))
+        np.testing.assert_allclose(p[2, 1],
+            assoc_legendre_p_2_1(x, norm=norm))
+        np.testing.assert_allclose(p[2, 2],
+            assoc_legendre_p_2_2(x, norm=norm))
+        np.testing.assert_allclose(p[2, 3], 0)
+        np.testing.assert_allclose(p[2, 4], 0)
+        np.testing.assert_allclose(p[2, -4], 0)
+        np.testing.assert_allclose(p[2, -3], 0)
+        np.testing.assert_allclose(p[2, -2],
+            assoc_legendre_p_2_m2(x, norm=norm))
+        np.testing.assert_allclose(p[2, -1],
+            assoc_legendre_p_2_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p[3, 0],
+            assoc_legendre_p_3_0(x, norm=norm))
+        np.testing.assert_allclose(p[3, 1],
+            assoc_legendre_p_3_1(x, norm=norm))
+        np.testing.assert_allclose(p[3, 2],
+            assoc_legendre_p_3_2(x, norm=norm))
+        np.testing.assert_allclose(p[3, 3],
+            assoc_legendre_p_3_3(x, norm=norm))
+        np.testing.assert_allclose(p[3, 4], 0)
+        np.testing.assert_allclose(p[3, -4], 0)
+        np.testing.assert_allclose(p[3, -3],
+            assoc_legendre_p_3_m3(x, norm=norm))
+        np.testing.assert_allclose(p[3, -2],
+            assoc_legendre_p_3_m2(x, norm=norm))
+        np.testing.assert_allclose(p[3, -1],
+            assoc_legendre_p_3_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p[4, 0],
+            assoc_legendre_p_4_0(x, norm=norm))
+        np.testing.assert_allclose(p[4, 1],
+            assoc_legendre_p_4_1(x, norm=norm))
+        np.testing.assert_allclose(p[4, 2],
+            assoc_legendre_p_4_2(x, norm=norm))
+        np.testing.assert_allclose(p[4, 3],
+            assoc_legendre_p_4_3(x, norm=norm))
+        np.testing.assert_allclose(p[4, 4],
+            assoc_legendre_p_4_4(x, norm=norm))
+        np.testing.assert_allclose(p[4, -4],
+            assoc_legendre_p_4_m4(x, norm=norm))
+        np.testing.assert_allclose(p[4, -3],
+            assoc_legendre_p_4_m3(x, norm=norm))
+        np.testing.assert_allclose(p[4, -2],
+            assoc_legendre_p_4_m2(x, norm=norm))
+        np.testing.assert_allclose(p[4, -1],
+            assoc_legendre_p_4_m1(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[0, 0],
+            assoc_legendre_p_0_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[0, 1], 0)
+        np.testing.assert_allclose(p_jac[0, 2], 0)
+        np.testing.assert_allclose(p_jac[0, 3], 0)
+        np.testing.assert_allclose(p_jac[0, 4], 0)
+        np.testing.assert_allclose(p_jac[0, -4], 0)
+        np.testing.assert_allclose(p_jac[0, -3], 0)
+        np.testing.assert_allclose(p_jac[0, -2], 0)
+        np.testing.assert_allclose(p_jac[0, -1], 0)
+
+        np.testing.assert_allclose(p_jac[1, 0],
+            assoc_legendre_p_1_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 1],
+            assoc_legendre_p_1_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 2], 0)
+        np.testing.assert_allclose(p_jac[1, 3], 0)
+        np.testing.assert_allclose(p_jac[1, 4], 0)
+        np.testing.assert_allclose(p_jac[1, -4], 0)
+        np.testing.assert_allclose(p_jac[1, -3], 0)
+        np.testing.assert_allclose(p_jac[1, -2], 0)
+        np.testing.assert_allclose(p_jac[1, -1],
+            assoc_legendre_p_1_m1_jac(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[2, 0],
+            assoc_legendre_p_2_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 1],
+            assoc_legendre_p_2_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 2],
+            assoc_legendre_p_2_2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 3], 0)
+        np.testing.assert_allclose(p_jac[2, 4], 0)
+        np.testing.assert_allclose(p_jac[2, -4], 0)
+        np.testing.assert_allclose(p_jac[2, -3], 0)
+        np.testing.assert_allclose(p_jac[2, -2],
+            assoc_legendre_p_2_m2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[2, -1],
+            assoc_legendre_p_2_m1_jac(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[3, 0],
+            assoc_legendre_p_3_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 1],
+            assoc_legendre_p_3_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 2],
+            assoc_legendre_p_3_2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 3],
+            assoc_legendre_p_3_3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 4], 0)
+        np.testing.assert_allclose(p_jac[3, -4], 0)
+        np.testing.assert_allclose(p_jac[3, -3],
+            assoc_legendre_p_3_m3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -2],
+            assoc_legendre_p_3_m2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -1],
+            assoc_legendre_p_3_m1_jac(x, norm=norm))
+
+        np.testing.assert_allclose(p_jac[4, 0],
+            assoc_legendre_p_4_0_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 1],
+            assoc_legendre_p_4_1_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 2],
+            assoc_legendre_p_4_2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 3],
+            assoc_legendre_p_4_3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 4],
+            assoc_legendre_p_4_4_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -4],
+            assoc_legendre_p_4_m4_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -3],
+            assoc_legendre_p_4_m3_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -2],
+            assoc_legendre_p_4_m2_jac(x, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -1],
+            assoc_legendre_p_4_m1_jac(x, norm=norm))
+
+    @pytest.mark.parametrize("m_max", [7])
+    @pytest.mark.parametrize("n_max", [10])
+    @pytest.mark.parametrize("x", [1, -1])
+    def test_all_limits(self, m_max, n_max, x):
+        p, p_jac = assoc_legendre_p_all(n_max, m_max, x, diff_n=1)
+
+        n = np.arange(n_max + 1)
+
+        np.testing.assert_allclose(p_jac[:, 0],
+            pow(x, n + 1) * n * (n + 1) / 2)
+        np.testing.assert_allclose(p_jac[:, 1],
+            np.where(n >= 1, pow(x, n) * np.inf, 0))
+        np.testing.assert_allclose(p_jac[:, 2],
+            np.where(n >= 2, -pow(x, n + 1) * (n + 2) * (n + 1) * n * (n - 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[:, -2],
+            np.where(n >= 2, -pow(x, n + 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[:, -1],
+            np.where(n >= 1, -pow(x, n) * np.inf, 0))
+
+        for m in range(3, m_max + 1):
+            np.testing.assert_allclose(p_jac[:, m], 0)
+            np.testing.assert_allclose(p_jac[:, -m], 0)
+
+    @pytest.mark.parametrize("m_max", [3, 5, 10])
+    @pytest.mark.parametrize("n_max", [10])
+    def test_legacy(self, m_max, n_max):
+        x = 0.5
+        p, p_jac = assoc_legendre_p_all(n_max, m_max, x, diff_n=1)
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+
+            p_legacy, p_jac_legacy = special.lpmn(m_max, n_max, x)
+            for m in range(m_max + 1):
+                np.testing.assert_allclose(p_legacy[m], p[:, m])
+
+            p_legacy, p_jac_legacy = special.lpmn(-m_max, n_max, x)
+            for m in range(m_max + 1):
+                np.testing.assert_allclose(p_legacy[m], p[:, -m])
+
+class TestMultiAssocLegendreP:
+    @pytest.mark.parametrize("shape", [(1000,), (4, 9), (3, 5, 7)])
+    @pytest.mark.parametrize("branch_cut", [2, 3])
+    @pytest.mark.parametrize("z_min, z_max", [(-10 - 10j, 10 + 10j),
+        (-1, 1), (-10j, 10j)])
+    @pytest.mark.parametrize("norm", [True, False])
+    def test_specific(self, shape, branch_cut, z_min, z_max, norm):
+        rng = np.random.default_rng(1234)
+
+        z = rng.uniform(z_min.real, z_max.real, shape) + \
+            1j * rng.uniform(z_min.imag, z_max.imag, shape)
+
+        p, p_jac = assoc_legendre_p_all(4, 4,
+            z, branch_cut=branch_cut, norm=norm, diff_n=1)
+
+        np.testing.assert_allclose(p[0, 0],
+            assoc_legendre_p_0_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[0, 1], 0)
+        np.testing.assert_allclose(p[0, 2], 0)
+        np.testing.assert_allclose(p[0, 3], 0)
+        np.testing.assert_allclose(p[0, 4], 0)
+        np.testing.assert_allclose(p[0, -4], 0)
+        np.testing.assert_allclose(p[0, -3], 0)
+        np.testing.assert_allclose(p[0, -2], 0)
+        np.testing.assert_allclose(p[0, -1], 0)
+
+        np.testing.assert_allclose(p[1, 0],
+            assoc_legendre_p_1_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[1, 1],
+            assoc_legendre_p_1_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[1, 2], 0)
+        np.testing.assert_allclose(p[1, 3], 0)
+        np.testing.assert_allclose(p[1, 4], 0)
+        np.testing.assert_allclose(p[1, -4], 0)
+        np.testing.assert_allclose(p[1, -3], 0)
+        np.testing.assert_allclose(p[1, -2], 0)
+        np.testing.assert_allclose(p[1, -1],
+            assoc_legendre_p_1_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p[2, 0],
+            assoc_legendre_p_2_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, 1],
+            assoc_legendre_p_2_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, 2],
+            assoc_legendre_p_2_2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, 3], 0)
+        np.testing.assert_allclose(p[2, 4], 0)
+        np.testing.assert_allclose(p[2, -4], 0)
+        np.testing.assert_allclose(p[2, -3], 0)
+        np.testing.assert_allclose(p[2, -2],
+            assoc_legendre_p_2_m2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[2, -1],
+            assoc_legendre_p_2_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p[3, 0],
+            assoc_legendre_p_3_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 1],
+            assoc_legendre_p_3_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 2],
+            assoc_legendre_p_3_2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 3],
+            assoc_legendre_p_3_3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, 4], 0)
+        np.testing.assert_allclose(p[3, -4], 0)
+        np.testing.assert_allclose(p[3, -3],
+            assoc_legendre_p_3_m3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, -2],
+            assoc_legendre_p_3_m2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[3, -1],
+            assoc_legendre_p_3_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p[4, 0],
+            assoc_legendre_p_4_0(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 1],
+            assoc_legendre_p_4_1(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 2],
+            assoc_legendre_p_4_2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 3],
+            assoc_legendre_p_4_3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, 4],
+            assoc_legendre_p_4_4(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -4],
+            assoc_legendre_p_4_m4(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -3],
+            assoc_legendre_p_4_m3(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -2],
+            assoc_legendre_p_4_m2(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p[4, -1],
+            assoc_legendre_p_4_m1(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[0, 0],
+            assoc_legendre_p_0_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[0, 1], 0)
+        np.testing.assert_allclose(p_jac[0, 2], 0)
+        np.testing.assert_allclose(p_jac[0, 3], 0)
+        np.testing.assert_allclose(p_jac[0, 4], 0)
+        np.testing.assert_allclose(p_jac[0, -4], 0)
+        np.testing.assert_allclose(p_jac[0, -3], 0)
+        np.testing.assert_allclose(p_jac[0, -2], 0)
+        np.testing.assert_allclose(p_jac[0, -1], 0)
+
+        np.testing.assert_allclose(p_jac[1, 0],
+            assoc_legendre_p_1_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 1],
+            assoc_legendre_p_1_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[1, 2], 0)
+        np.testing.assert_allclose(p_jac[1, 3], 0)
+        np.testing.assert_allclose(p_jac[1, 4], 0)
+        np.testing.assert_allclose(p_jac[1, -4], 0)
+        np.testing.assert_allclose(p_jac[1, -3], 0)
+        np.testing.assert_allclose(p_jac[1, -2], 0)
+        np.testing.assert_allclose(p_jac[1, -1],
+            assoc_legendre_p_1_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[2, 0],
+            assoc_legendre_p_2_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 1],
+            assoc_legendre_p_2_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 2],
+            assoc_legendre_p_2_2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, 3], 0)
+        np.testing.assert_allclose(p_jac[2, 4], 0)
+        np.testing.assert_allclose(p_jac[2, -4], 0)
+        np.testing.assert_allclose(p_jac[2, -3], 0)
+        np.testing.assert_allclose(p_jac[2, -2],
+            assoc_legendre_p_2_m2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[2, -1],
+            assoc_legendre_p_2_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[3, 0],
+            assoc_legendre_p_3_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 1],
+            assoc_legendre_p_3_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 2],
+            assoc_legendre_p_3_2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 3],
+            assoc_legendre_p_3_3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, 4], 0)
+        np.testing.assert_allclose(p_jac[3, -4], 0)
+        np.testing.assert_allclose(p_jac[3, -3],
+            assoc_legendre_p_3_m3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -2],
+            assoc_legendre_p_3_m2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[3, -1],
+            assoc_legendre_p_3_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+        np.testing.assert_allclose(p_jac[4, 0],
+            assoc_legendre_p_4_0_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 1],
+            assoc_legendre_p_4_1_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 2],
+            assoc_legendre_p_4_2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 3],
+            assoc_legendre_p_4_3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, 4],
+            assoc_legendre_p_4_4_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -4],
+            assoc_legendre_p_4_m4_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -3],
+            assoc_legendre_p_4_m3_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -2],
+            assoc_legendre_p_4_m2_jac(z, branch_cut=branch_cut, norm=norm))
+        np.testing.assert_allclose(p_jac[4, -1],
+            assoc_legendre_p_4_m1_jac(z, branch_cut=branch_cut, norm=norm))
+
+class TestSphLegendreP:
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)])
+    def test_specific(self, shape):
+        rng = np.random.default_rng(1234)
+
+        theta = rng.uniform(-np.pi, np.pi, shape)
+
+        p, p_jac = sph_legendre_p_all(4, 4, theta, diff_n=1)
+
+        np.testing.assert_allclose(p[0, 0],
+            sph_legendre_p_0_0(theta))
+        np.testing.assert_allclose(p[0, 1], 0)
+        np.testing.assert_allclose(p[0, 2], 0)
+        np.testing.assert_allclose(p[0, 3], 0)
+        np.testing.assert_allclose(p[0, 4], 0)
+        np.testing.assert_allclose(p[0, -3], 0)
+        np.testing.assert_allclose(p[0, -2], 0)
+        np.testing.assert_allclose(p[0, -1], 0)
+
+        np.testing.assert_allclose(p[1, 0],
+            sph_legendre_p_1_0(theta))
+        np.testing.assert_allclose(p[1, 1],
+            sph_legendre_p_1_1(theta))
+        np.testing.assert_allclose(p[1, 2], 0)
+        np.testing.assert_allclose(p[1, 3], 0)
+        np.testing.assert_allclose(p[1, 4], 0)
+        np.testing.assert_allclose(p[1, -4], 0)
+        np.testing.assert_allclose(p[1, -3], 0)
+        np.testing.assert_allclose(p[1, -2], 0)
+        np.testing.assert_allclose(p[1, -1],
+            sph_legendre_p_1_m1(theta))
+
+        np.testing.assert_allclose(p[2, 0],
+            sph_legendre_p_2_0(theta))
+        np.testing.assert_allclose(p[2, 1],
+            sph_legendre_p_2_1(theta))
+        np.testing.assert_allclose(p[2, 2],
+            sph_legendre_p_2_2(theta))
+        np.testing.assert_allclose(p[2, 3], 0)
+        np.testing.assert_allclose(p[2, 4], 0)
+        np.testing.assert_allclose(p[2, -4], 0)
+        np.testing.assert_allclose(p[2, -3], 0)
+        np.testing.assert_allclose(p[2, -2],
+            sph_legendre_p_2_m2(theta))
+        np.testing.assert_allclose(p[2, -1],
+            sph_legendre_p_2_m1(theta))
+
+        np.testing.assert_allclose(p[3, 0],
+            sph_legendre_p_3_0(theta))
+        np.testing.assert_allclose(p[3, 1],
+            sph_legendre_p_3_1(theta))
+        np.testing.assert_allclose(p[3, 2],
+            sph_legendre_p_3_2(theta))
+        np.testing.assert_allclose(p[3, 3],
+            sph_legendre_p_3_3(theta))
+        np.testing.assert_allclose(p[3, 4], 0)
+        np.testing.assert_allclose(p[3, -4], 0)
+        np.testing.assert_allclose(p[3, -3],
+            sph_legendre_p_3_m3(theta))
+        np.testing.assert_allclose(p[3, -2],
+            sph_legendre_p_3_m2(theta))
+        np.testing.assert_allclose(p[3, -1],
+            sph_legendre_p_3_m1(theta))
+
+        np.testing.assert_allclose(p[4, 0],
+            sph_legendre_p_4_0(theta))
+        np.testing.assert_allclose(p[4, 1],
+            sph_legendre_p_4_1(theta))
+        np.testing.assert_allclose(p[4, 2],
+            sph_legendre_p_4_2(theta))
+        np.testing.assert_allclose(p[4, 3],
+            sph_legendre_p_4_3(theta))
+        np.testing.assert_allclose(p[4, 4],
+            sph_legendre_p_4_4(theta))
+        np.testing.assert_allclose(p[4, -4],
+            sph_legendre_p_4_m4(theta))
+        np.testing.assert_allclose(p[4, -3],
+            sph_legendre_p_4_m3(theta))
+        np.testing.assert_allclose(p[4, -2],
+            sph_legendre_p_4_m2(theta))
+        np.testing.assert_allclose(p[4, -1],
+            sph_legendre_p_4_m1(theta))
+
+        np.testing.assert_allclose(p_jac[0, 0],
+            sph_legendre_p_0_0_jac(theta))
+        np.testing.assert_allclose(p_jac[0, 1], 0)
+        np.testing.assert_allclose(p_jac[0, 2], 0)
+        np.testing.assert_allclose(p_jac[0, 3], 0)
+        np.testing.assert_allclose(p_jac[0, 4], 0)
+        np.testing.assert_allclose(p_jac[0, -3], 0)
+        np.testing.assert_allclose(p_jac[0, -2], 0)
+        np.testing.assert_allclose(p_jac[0, -1], 0)
+
+        np.testing.assert_allclose(p_jac[1, 0],
+            sph_legendre_p_1_0_jac(theta))
+        np.testing.assert_allclose(p_jac[1, 1],
+            sph_legendre_p_1_1_jac(theta))
+        np.testing.assert_allclose(p_jac[1, 2], 0)
+        np.testing.assert_allclose(p_jac[1, 3], 0)
+        np.testing.assert_allclose(p_jac[1, 4], 0)
+        np.testing.assert_allclose(p_jac[1, -4], 0)
+        np.testing.assert_allclose(p_jac[1, -3], 0)
+        np.testing.assert_allclose(p_jac[1, -2], 0)
+        np.testing.assert_allclose(p_jac[1, -1],
+            sph_legendre_p_1_m1_jac(theta))
+
+        np.testing.assert_allclose(p_jac[2, 0],
+            sph_legendre_p_2_0_jac(theta))
+        np.testing.assert_allclose(p_jac[2, 1],
+            sph_legendre_p_2_1_jac(theta))
+        np.testing.assert_allclose(p_jac[2, 2],
+            sph_legendre_p_2_2_jac(theta))
+        np.testing.assert_allclose(p_jac[2, 3], 0)
+        np.testing.assert_allclose(p_jac[2, 4], 0)
+        np.testing.assert_allclose(p_jac[2, -4], 0)
+        np.testing.assert_allclose(p_jac[2, -3], 0)
+        np.testing.assert_allclose(p_jac[2, -2],
+            sph_legendre_p_2_m2_jac(theta))
+        np.testing.assert_allclose(p_jac[2, -1],
+            sph_legendre_p_2_m1_jac(theta))
+
+        np.testing.assert_allclose(p_jac[3, 0],
+            sph_legendre_p_3_0_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 1],
+            sph_legendre_p_3_1_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 2],
+            sph_legendre_p_3_2_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 3],
+            sph_legendre_p_3_3_jac(theta))
+        np.testing.assert_allclose(p_jac[3, 4], 0)
+        np.testing.assert_allclose(p_jac[3, -4], 0)
+        np.testing.assert_allclose(p_jac[3, -3],
+            sph_legendre_p_3_m3_jac(theta))
+        np.testing.assert_allclose(p_jac[3, -2],
+            sph_legendre_p_3_m2_jac(theta))
+        np.testing.assert_allclose(p_jac[3, -1],
+            sph_legendre_p_3_m1_jac(theta))
+
+        np.testing.assert_allclose(p_jac[4, 0],
+            sph_legendre_p_4_0_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 1],
+            sph_legendre_p_4_1_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 2],
+            sph_legendre_p_4_2_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 3],
+            sph_legendre_p_4_3_jac(theta))
+        np.testing.assert_allclose(p_jac[4, 4],
+            sph_legendre_p_4_4_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -4],
+            sph_legendre_p_4_m4_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -3],
+            sph_legendre_p_4_m3_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -2],
+            sph_legendre_p_4_m2_jac(theta))
+        np.testing.assert_allclose(p_jac[4, -1],
+            sph_legendre_p_4_m1_jac(theta))
+
+    @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7, 10)])
+    def test_ode(self, shape):
+        rng = np.random.default_rng(1234)
+
+        n = rng.integers(0, 10, shape)
+        m = rng.integers(-10, 10, shape)
+        theta = rng.uniform(-np.pi, np.pi, shape)
+
+        p, p_jac, p_hess = sph_legendre_p(n, m, theta, diff_n=2)
+
+        assert p.shape == shape
+        assert p_jac.shape == p.shape
+        assert p_hess.shape == p_jac.shape
+
+        np.testing.assert_allclose(np.sin(theta) * p_hess, -np.cos(theta) * p_jac
+            - (n * (n + 1) * np.sin(theta) - m * m / np.sin(theta)) * p,
+            rtol=1e-05, atol=1e-08)
+
+class TestLegendreFunctions:
+    def test_clpmn(self):
+        z = 0.5+0.3j
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            clp = special.clpmn(2, 2, z, 3)
+
+        assert_array_almost_equal(clp,
+                   (np.array([[1.0000, z, 0.5*(3*z*z-1)],
+                           [0.0000, np.sqrt(z*z-1), 3*z*np.sqrt(z*z-1)],
+                           [0.0000, 0.0000, 3*(z*z-1)]]),
+                    np.array([[0.0000, 1.0000, 3*z],
+                           [0.0000, z/np.sqrt(z*z-1), 3*(2*z*z-1)/np.sqrt(z*z-1)],
+                           [0.0000, 0.0000, 6*z]])),
+                    7)
+
+    def test_clpmn_close_to_real_2(self):
+        eps = 1e-10
+        m = 1
+        n = 3
+        x = 0.5
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            clp_plus = special.clpmn(m, n, x+1j*eps, 2)[0][m, n]
+            clp_minus = special.clpmn(m, n, x-1j*eps, 2)[0][m, n]
+
+        assert_array_almost_equal(np.array([clp_plus, clp_minus]),
+                                  np.array([special.lpmv(m, n, x),
+                                         special.lpmv(m, n, x)]),
+                                  7)
+
+    def test_clpmn_close_to_real_3(self):
+        eps = 1e-10
+        m = 1
+        n = 3
+        x = 0.5
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            clp_plus = special.clpmn(m, n, x+1j*eps, 3)[0][m, n]
+            clp_minus = special.clpmn(m, n, x-1j*eps, 3)[0][m, n]
+
+        assert_array_almost_equal(np.array([clp_plus, clp_minus]),
+                                  np.array([special.lpmv(m, n, x)*np.exp(-0.5j*m*np.pi),
+                                         special.lpmv(m, n, x)*np.exp(0.5j*m*np.pi)]),
+                                  7)
+
+    def test_clpmn_across_unit_circle(self):
+        eps = 1e-7
+        m = 1
+        n = 1
+        x = 1j
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            for type in [2, 3]:
+                assert_almost_equal(special.clpmn(m, n, x+1j*eps, type)[0][m, n],
+                                special.clpmn(m, n, x-1j*eps, type)[0][m, n], 6)
+
+    def test_inf(self):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            for z in (1, -1):
+                for n in range(4):
+                    for m in range(1, n):
+                        lp = special.clpmn(m, n, z)
+                        assert np.isinf(lp[1][1,1:]).all()
+                        lp = special.lpmn(m, n, z)
+                        assert np.isinf(lp[1][1,1:]).all()
+
+    def test_deriv_clpmn(self):
+        # data inside and outside of the unit circle
+        zvals = [0.5+0.5j, -0.5+0.5j, -0.5-0.5j, 0.5-0.5j,
+                 1+1j, -1+1j, -1-1j, 1-1j]
+        m = 2
+        n = 3
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            for type in [2, 3]:
+                for z in zvals:
+                    for h in [1e-3, 1e-3j]:
+                        approx_derivative = (special.clpmn(m, n, z+0.5*h, type)[0]
+                                            - special.clpmn(m, n, z-0.5*h, type)[0])/h
+                        assert_allclose(special.clpmn(m, n, z, type)[1],
+                                        approx_derivative,
+                                        rtol=1e-4)
+
+    """
+    @pytest.mark.parametrize("m_max", [3])
+    @pytest.mark.parametrize("n_max", [5])
+    @pytest.mark.parametrize("z", [-1])
+    def test_clpmn_all_limits(self, m_max, n_max, z):
+        rng = np.random.default_rng(1234)
+
+        type = 2
+
+        p, p_jac = special.clpmn_all(m_max, n_max, type, z, diff_n=1)
+
+        n = np.arange(n_max + 1)
+
+        np.testing.assert_allclose(p_jac[0], pow(z, n + 1) * n * (n + 1) / 2)
+        np.testing.assert_allclose(p_jac[1], np.where(n >= 1, pow(z, n) * np.inf, 0))
+        np.testing.assert_allclose(p_jac[2], np.where(n >= 2,
+            -pow(z, n + 1) * (n + 2) * (n + 1) * n * (n - 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[-2], np.where(n >= 2, -pow(z, n + 1) / 4, 0))
+        np.testing.assert_allclose(p_jac[-1], np.where(n >= 1, -pow(z, n) * np.inf, 0))
+
+        for m in range(3, m_max + 1):
+            np.testing.assert_allclose(p_jac[m], 0)
+            np.testing.assert_allclose(p_jac[-m], 0)
+    """
+
+    def test_lpmv(self):
+        lp = special.lpmv(0,2,.5)
+        assert_almost_equal(lp,-0.125,7)
+        lp = special.lpmv(0,40,.001)
+        assert_almost_equal(lp,0.1252678976534484,7)
+
+        # XXX: this is outside the domain of the current implementation,
+        #      so ensure it returns a NaN rather than a wrong answer.
+        with np.errstate(all='ignore'):
+            lp = special.lpmv(-1,-1,.001)
+        assert lp != 0 or np.isnan(lp)
+
+    def test_lqmn(self):
+        lqmnf = special.lqmn(0,2,.5)
+        lqf = special.lqn(2,.5)
+        assert_array_almost_equal(lqmnf[0][0],lqf[0],4)
+        assert_array_almost_equal(lqmnf[1][0],lqf[1],4)
+
+    def test_lqmn_gt1(self):
+        """algorithm for real arguments changes at 1.0001
+           test against analytical result for m=2, n=1
+        """
+        x0 = 1.0001
+        delta = 0.00002
+        for x in (x0-delta, x0+delta):
+            lq = special.lqmn(2, 1, x)[0][-1, -1]
+            expected = 2/(x*x-1)
+            assert_almost_equal(lq, expected)
+
+    def test_lqmn_shape(self):
+        a, b = special.lqmn(4, 4, 1.1)
+        assert_equal(a.shape, (5, 5))
+        assert_equal(b.shape, (5, 5))
+
+        a, b = special.lqmn(4, 0, 1.1)
+        assert_equal(a.shape, (5, 1))
+        assert_equal(b.shape, (5, 1))
+
+    def test_lqn(self):
+        lqf = special.lqn(2,.5)
+        assert_array_almost_equal(lqf,(np.array([0.5493, -0.7253, -0.8187]),
+                                       np.array([1.3333, 1.216, -0.8427])),4)
+
+    @pytest.mark.parametrize("function", [special.lpn, special.lqn])
+    @pytest.mark.parametrize("n", [1, 2, 4, 8, 16, 32])
+    @pytest.mark.parametrize("z_complex", [False, True])
+    @pytest.mark.parametrize("z_inexact", [False, True])
+    @pytest.mark.parametrize(
+        "input_shape",
+        [
+            (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1), (2, 2, 2)
+        ]
+    )
+    def test_array_inputs_lxn(self, function, n, z_complex, z_inexact, input_shape):
+        """Tests for correct output shapes."""
+        rng = np.random.default_rng(1234)
+        if z_inexact:
+            z = rng.integers(-3, 3, size=input_shape)
+        else:
+            z = rng.uniform(-1, 1, size=input_shape)
+
+        if z_complex:
+            z = 1j * z + 0.5j * z
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            P_z, P_d_z = function(n, z)
+        assert P_z.shape == (n + 1, ) + input_shape
+        assert P_d_z.shape == (n + 1, ) + input_shape
+
+    @pytest.mark.parametrize("function", [special.lqmn])
+    @pytest.mark.parametrize(
+        "m,n",
+        [(0, 1), (1, 2), (1, 4), (3, 8), (11, 16), (19, 32)]
+    )
+    @pytest.mark.parametrize("z_inexact", [False, True])
+    @pytest.mark.parametrize(
+        "input_shape", [
+            (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1)
+        ]
+    )
+    def test_array_inputs_lxmn(self, function, m, n, z_inexact, input_shape):
+        """Tests for correct output shapes and dtypes."""
+        rng = np.random.default_rng(1234)
+        if z_inexact:
+            z = rng.integers(-3, 3, size=input_shape)
+        else:
+            z = rng.uniform(-1, 1, size=input_shape)
+
+        P_z, P_d_z = function(m, n, z)
+        assert P_z.shape == (m + 1, n + 1) + input_shape
+        assert P_d_z.shape == (m + 1, n + 1) + input_shape
+
+    @pytest.mark.parametrize("function", [special.clpmn, special.lqmn])
+    @pytest.mark.parametrize(
+        "m,n",
+        [(0, 1), (1, 2), (1, 4), (3, 8), (11, 16), (19, 32)]
+    )
+    @pytest.mark.parametrize(
+        "input_shape", [
+            (), (1, ), (2, ), (2, 1), (1, 2), (2, 2), (2, 2, 1)
+        ]
+    )
+    def test_array_inputs_clxmn(self, function, m, n, input_shape):
+        """Tests for correct output shapes and dtypes."""
+        rng = np.random.default_rng(1234)
+        z = rng.uniform(-1, 1, size=input_shape)
+        z = 1j * z + 0.5j * z
+
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            P_z, P_d_z = function(m, n, z)
+
+        assert P_z.shape == (m + 1, n + 1) + input_shape
+        assert P_d_z.shape == (m + 1, n + 1) + input_shape
+
+def assoc_legendre_factor(n, m, norm):
+    if norm:
+        return (math.sqrt((2 * n + 1) *
+            math.factorial(n - m) / (2 * math.factorial(n + m))))
+
+    return 1
+
+def assoc_legendre_p_0_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(0, 0, norm)
+
+    return np.full_like(z, fac)
+
+def assoc_legendre_p_1_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(1, 0, norm)
+
+    return fac * z
+
+def assoc_legendre_p_1_1(z, *, branch_cut=2, norm=False):
+    branch_sign = np.where(branch_cut == 3, np.where(np.signbit(np.real(z)), 1, -1), -1)
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(1, 1, norm)
+
+    w = np.sqrt(np.where(branch_cut == 3, z * z - 1, 1 - z * z))
+
+    return branch_cut_sign * branch_sign * fac * w
+
+def assoc_legendre_p_1_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(1, -1, norm)
+
+    return (-branch_cut_sign * fac *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_2_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 0, norm)
+
+    return fac * (3 * z * z - 1) / 2
+
+def assoc_legendre_p_2_1(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 1, norm)
+
+    return (3 * fac * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_2_2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, 2, norm)
+
+    return 3 * branch_cut_sign * fac * (1 - z * z)
+
+def assoc_legendre_p_2_m2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -2, norm)
+
+    return branch_cut_sign * fac * (1 - z * z) / 8
+
+def assoc_legendre_p_2_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -1, norm)
+
+    return (-branch_cut_sign * fac * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_3_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 0, norm)
+
+    return fac * (5 * z * z - 3) * z / 2
+
+def assoc_legendre_p_3_1(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 1, norm)
+
+    return (3 * fac * (5 * z * z - 1) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_3_2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 2, norm)
+
+    return 15 * branch_cut_sign * fac * (1 - z * z) * z
+
+def assoc_legendre_p_3_3(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 3, norm)
+
+    return (15 * branch_cut_sign * fac * (1 - z * z) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_3_m3(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, -3, norm)
+
+    return (fac * (z * z - 1) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 48)
+
+def assoc_legendre_p_3_m2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -2, norm)
+
+    return branch_cut_sign * fac * (1 - z * z) * z / 8
+
+def assoc_legendre_p_3_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -1, norm)
+
+    return (branch_cut_sign * fac * (1 - 5 * z * z) *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 8)
+
+def assoc_legendre_p_4_0(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 0, norm)
+
+    return fac * ((35 * z * z - 30) * z * z + 3) / 8
+
+def assoc_legendre_p_4_1(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 1, norm)
+
+    return (5 * fac * (7 * z * z - 3) * z *
+       assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_4_2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 2, norm)
+
+    return 15 * branch_cut_sign * fac * ((8 - 7 * z * z) * z * z - 1) / 2
+
+def assoc_legendre_p_4_3(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 3, norm)
+
+    return (105 * branch_cut_sign * fac * (1 - z * z) * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_4_4(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 4, norm)
+
+    return 105 * fac * np.square(z * z - 1)
+
+def assoc_legendre_p_4_m4(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -4, norm)
+
+    return fac * np.square(z * z - 1) / 384
+
+def assoc_legendre_p_4_m3(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -3, norm)
+
+    return (fac * (z * z - 1) * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 48)
+
+def assoc_legendre_p_4_m2(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -2, norm)
+
+    return branch_cut_sign * fac * ((8 - 7 * z * z) * z * z - 1) / 48
+
+def assoc_legendre_p_4_m1(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -1, norm)
+
+    return (branch_cut_sign * fac * (3 - 7 * z * z) * z *
+        assoc_legendre_p_1_1(z, branch_cut=branch_cut) / 8)
+
+def assoc_legendre_p_1_1_jac_div_z(z, branch_cut=2):
+    branch_sign = np.where(branch_cut == 3, np.where(np.signbit(np.real(z)), 1, -1), -1)
+
+    out11_div_z = (-branch_sign /
+        np.sqrt(np.where(branch_cut == 3, z * z - 1, 1 - z * z)))
+
+    return out11_div_z
+
+def assoc_legendre_p_0_0_jac(z, *, branch_cut=2, norm=False):
+    return np.zeros_like(z)
+
+def assoc_legendre_p_1_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(1, 0, norm)
+
+    return np.full_like(z, fac)
+
+def assoc_legendre_p_1_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(1, 1, norm)
+
+    return (fac * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_1_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(1, -1, norm)
+
+    return (-branch_cut_sign * fac * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_2_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 0, norm)
+
+    return 3 * fac * z
+
+def assoc_legendre_p_2_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(2, 1, norm)
+
+    return (3 * fac * (2 * z * z - 1) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_2_2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, 2, norm)
+
+    return -6 * branch_cut_sign * fac * z
+
+def assoc_legendre_p_2_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -1, norm)
+
+    return (branch_cut_sign * fac * (1 - 2 * z * z) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_2_m2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(2, -2, norm)
+
+    return -branch_cut_sign * fac * z / 4
+
+def assoc_legendre_p_3_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 0, norm)
+
+    return 3 * fac * (5 * z * z - 1) / 2
+
+def assoc_legendre_p_3_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, 1, norm)
+
+    return (3 * fac * (15 * z * z - 11) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_3_2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 2, norm)
+
+    return 15 * branch_cut_sign * fac * (1 - 3 * z * z)
+
+def assoc_legendre_p_3_3_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, 3, norm)
+
+    return (45 * branch_cut_sign * fac * (1 - z * z) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_3_m3_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(3, -3, norm)
+
+    return (fac * (z * z - 1) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 16)
+
+def assoc_legendre_p_3_m2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -2, norm)
+
+    return branch_cut_sign * fac * (1 - 3 * z * z) / 8
+
+def assoc_legendre_p_3_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(3, -1, norm)
+
+    return (branch_cut_sign * fac * (11 - 15 * z * z) * z *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 8)
+
+def assoc_legendre_p_4_0_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 0, norm)
+
+    return 5 * fac * (7 * z * z - 3) * z / 2
+
+def assoc_legendre_p_4_1_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 1, norm)
+
+    return (5 * fac * ((28 * z * z - 27) * z * z + 3) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 2)
+
+def assoc_legendre_p_4_2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 2, norm)
+
+    return 30 * branch_cut_sign * fac * (4 - 7 * z * z) * z
+
+def assoc_legendre_p_4_3_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, 3, norm)
+
+    return (105 * branch_cut_sign * fac * ((5 - 4 * z * z) * z * z - 1) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut))
+
+def assoc_legendre_p_4_4_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, 4, norm)
+
+    return 420 * fac * (z * z - 1) * z
+
+def assoc_legendre_p_4_m4_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -4, norm)
+
+    return fac * (z * z - 1) * z / 96
+
+def assoc_legendre_p_4_m3_jac(z, *, branch_cut=2, norm=False):
+    fac = assoc_legendre_factor(4, -3, norm)
+
+    return (fac * ((4 * z * z - 5) * z * z + 1) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 48)
+
+def assoc_legendre_p_4_m2_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -2, norm)
+
+    return branch_cut_sign * fac * (4 - 7 * z * z) * z / 12
+
+def assoc_legendre_p_4_m1_jac(z, *, branch_cut=2, norm=False):
+    branch_cut_sign = np.where(branch_cut == 3, -1, 1)
+    fac = assoc_legendre_factor(4, -1, norm)
+
+    return (branch_cut_sign * fac * ((27 - 28 * z * z) * z * z - 3) *
+        assoc_legendre_p_1_1_jac_div_z(z, branch_cut=branch_cut) / 8)
+
+def sph_legendre_factor(n, m):
+    return assoc_legendre_factor(n, m, norm=True) / np.sqrt(2 * np.pi)
+
+def sph_legendre_p_0_0(theta):
+    fac = sph_legendre_factor(0, 0)
+
+    return np.full_like(theta, fac)
+
+def sph_legendre_p_1_0(theta):
+    fac = sph_legendre_factor(1, 0)
+
+    return fac * np.cos(theta)
+
+def sph_legendre_p_1_1(theta):
+    fac = sph_legendre_factor(1, 1)
+
+    return -fac * np.abs(np.sin(theta))
+
+def sph_legendre_p_1_m1(theta):
+    fac = sph_legendre_factor(1, -1)
+
+    return fac * np.abs(np.sin(theta)) / 2
+
+def sph_legendre_p_2_0(theta):
+    fac = sph_legendre_factor(2, 0)
+
+    return fac * (3 * np.square(np.cos(theta)) - 1) / 2
+
+def sph_legendre_p_2_1(theta):
+    fac = sph_legendre_factor(2, 1)
+
+    return -3 * fac * np.abs(np.sin(theta)) * np.cos(theta)
+
+def sph_legendre_p_2_2(theta):
+    fac = sph_legendre_factor(2, 2)
+
+    return 3 * fac * (1 - np.square(np.cos(theta)))
+
+def sph_legendre_p_2_m2(theta):
+    fac = sph_legendre_factor(2, -2)
+
+    return fac * (1 - np.square(np.cos(theta))) / 8
+
+def sph_legendre_p_2_m1(theta):
+    fac = sph_legendre_factor(2, -1)
+
+    return fac * np.cos(theta) * np.abs(np.sin(theta)) / 2
+
+def sph_legendre_p_3_0(theta):
+    fac = sph_legendre_factor(3, 0)
+
+    return (fac * (5 * np.square(np.cos(theta)) - 3) *
+        np.cos(theta) / 2)
+
+def sph_legendre_p_3_1(theta):
+    fac = sph_legendre_factor(3, 1)
+
+    return (-3 * fac * (5 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) / 2)
+
+def sph_legendre_p_3_2(theta):
+    fac = sph_legendre_factor(3, 2)
+
+    return (-15 * fac * (np.square(np.cos(theta)) - 1) *
+        np.cos(theta))
+
+def sph_legendre_p_3_3(theta):
+    fac = sph_legendre_factor(3, 3)
+
+    return -15 * fac * np.power(np.abs(np.sin(theta)), 3)
+
+def sph_legendre_p_3_m3(theta):
+    fac = sph_legendre_factor(3, -3)
+
+    return fac * np.power(np.abs(np.sin(theta)), 3) / 48
+
+def sph_legendre_p_3_m2(theta):
+    fac = sph_legendre_factor(3, -2)
+
+    return (-fac * (np.square(np.cos(theta)) - 1) *
+        np.cos(theta) / 8)
+
+def sph_legendre_p_3_m1(theta):
+    fac = sph_legendre_factor(3, -1)
+
+    return (fac * (5 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) / 8)
+
+def sph_legendre_p_4_0(theta):
+    fac = sph_legendre_factor(4, 0)
+
+    return (fac * (35 * np.square(np.square(np.cos(theta))) -
+        30 * np.square(np.cos(theta)) + 3) / 8)
+
+def sph_legendre_p_4_1(theta):
+    fac = sph_legendre_factor(4, 1)
+
+    return (-5 * fac * (7 * np.square(np.cos(theta)) - 3) *
+        np.cos(theta) * np.abs(np.sin(theta)) / 2)
+
+def sph_legendre_p_4_2(theta):
+    fac = sph_legendre_factor(4, 2)
+
+    return (-15 * fac * (7 * np.square(np.cos(theta)) - 1) *
+        (np.square(np.cos(theta)) - 1) / 2)
+
+def sph_legendre_p_4_3(theta):
+    fac = sph_legendre_factor(4, 3)
+
+    return -105 * fac * np.power(np.abs(np.sin(theta)), 3) * np.cos(theta)
+
+def sph_legendre_p_4_4(theta):
+    fac = sph_legendre_factor(4, 4)
+
+    return 105 * fac * np.square(np.square(np.cos(theta)) - 1)
+
+def sph_legendre_p_4_m4(theta):
+    fac = sph_legendre_factor(4, -4)
+
+    return fac * np.square(np.square(np.cos(theta)) - 1) / 384
+
+def sph_legendre_p_4_m3(theta):
+    fac = sph_legendre_factor(4, -3)
+
+    return (fac * np.power(np.abs(np.sin(theta)), 3) *
+        np.cos(theta) / 48)
+
+def sph_legendre_p_4_m2(theta):
+    fac = sph_legendre_factor(4, -2)
+
+    return (-fac * (7 * np.square(np.cos(theta)) - 1) *
+        (np.square(np.cos(theta)) - 1) / 48)
+
+def sph_legendre_p_4_m1(theta):
+    fac = sph_legendre_factor(4, -1)
+
+    return (fac * (7 * np.square(np.cos(theta)) - 3) *
+        np.cos(theta) * np.abs(np.sin(theta)) / 8)
+
+def sph_legendre_p_0_0_jac(theta):
+    return np.zeros_like(theta)
+
+def sph_legendre_p_1_0_jac(theta):
+    fac = sph_legendre_factor(1, 0)
+
+    return -fac * np.sin(theta)
+
+def sph_legendre_p_1_1_jac(theta):
+    fac = sph_legendre_factor(1, 1)
+
+    return -fac * np.cos(theta) * (2 * np.heaviside(np.sin(theta), 1) - 1)
+
+def sph_legendre_p_1_m1_jac(theta):
+    fac = sph_legendre_factor(1, -1)
+
+    return fac * np.cos(theta) * (2 * np.heaviside(np.sin(theta), 1) - 1) / 2
+
+def sph_legendre_p_2_0_jac(theta):
+    fac = sph_legendre_factor(2, 0)
+
+    return -3 * fac * np.cos(theta) * np.sin(theta)
+
+def sph_legendre_p_2_1_jac(theta):
+    fac = sph_legendre_factor(2, 1)
+
+    return (3 * fac * (-np.square(np.cos(theta)) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) +
+        np.abs(np.sin(theta)) * np.sin(theta)))
+
+def sph_legendre_p_2_2_jac(theta):
+    fac = sph_legendre_factor(2, 2)
+
+    return 6 * fac * np.sin(theta) * np.cos(theta)
+
+def sph_legendre_p_2_m2_jac(theta):
+    fac = sph_legendre_factor(2, -2)
+
+    return fac * np.sin(theta) * np.cos(theta) / 4
+
+def sph_legendre_p_2_m1_jac(theta):
+    fac = sph_legendre_factor(2, -1)
+
+    return (-fac * (-np.square(np.cos(theta)) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) +
+        np.abs(np.sin(theta)) * np.sin(theta)) / 2)
+
+def sph_legendre_p_3_0_jac(theta):
+    fac = sph_legendre_factor(3, 0)
+
+    return 3 * fac * (1 - 5 * np.square(np.cos(theta))) * np.sin(theta) / 2
+
+def sph_legendre_p_3_1_jac(theta):
+    fac = sph_legendre_factor(3, 1)
+
+    return (3 * fac * (11 - 15 * np.square(np.cos(theta))) * np.cos(theta) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 2)
+
+def sph_legendre_p_3_2_jac(theta):
+    fac = sph_legendre_factor(3, 2)
+
+    return 15 * fac * (3 * np.square(np.cos(theta)) - 1) * np.sin(theta)
+
+def sph_legendre_p_3_3_jac(theta):
+    fac = sph_legendre_factor(3, 3)
+
+    return -45 * fac * np.abs(np.sin(theta)) * np.sin(theta) * np.cos(theta)
+
+def sph_legendre_p_3_m3_jac(theta):
+    fac = sph_legendre_factor(3, -3)
+
+    return fac * np.abs(np.sin(theta)) * np.sin(theta) * np.cos(theta) / 16
+
+def sph_legendre_p_3_m2_jac(theta):
+    fac = sph_legendre_factor(3, -2)
+
+    return fac * (3 * np.square(np.cos(theta)) - 1) * np.sin(theta) / 8
+
+def sph_legendre_p_3_m1_jac(theta):
+    fac = sph_legendre_factor(3, -1)
+
+    return (-fac * (11 - 15 * np.square(np.cos(theta))) *
+        np.cos(theta) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 8)
+
+def sph_legendre_p_4_0_jac(theta):
+    fac = sph_legendre_factor(4, 0)
+
+    return (-5 * fac * (7 * np.square(np.cos(theta)) - 3) *
+        np.sin(theta) * np.cos(theta) / 2)
+
+def sph_legendre_p_4_1_jac(theta):
+    fac = sph_legendre_factor(4, 1)
+
+    return (5 * fac * (-3 + 27 * np.square(np.cos(theta)) -
+        28 * np.square(np.square(np.cos(theta)))) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 2)
+
+def sph_legendre_p_4_2_jac(theta):
+    fac = sph_legendre_factor(4, 2)
+
+    return (30 * fac * (7 * np.square(np.cos(theta)) - 4) *
+        np.sin(theta) * np.cos(theta))
+
+def sph_legendre_p_4_3_jac(theta):
+    fac = sph_legendre_factor(4, 3)
+
+    return (-105 * fac * (4 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) * np.sin(theta))
+
+def sph_legendre_p_4_4_jac(theta):
+    fac = sph_legendre_factor(4, 4)
+
+    return (-420 * fac * (np.square(np.cos(theta)) - 1) *
+        np.sin(theta) * np.cos(theta))
+
+def sph_legendre_p_4_m4_jac(theta):
+    fac = sph_legendre_factor(4, -4)
+
+    return (-fac * (np.square(np.cos(theta)) - 1) *
+        np.sin(theta) * np.cos(theta) / 96)
+
+def sph_legendre_p_4_m3_jac(theta):
+    fac = sph_legendre_factor(4, -3)
+
+    return (fac * (4 * np.square(np.cos(theta)) - 1) *
+        np.abs(np.sin(theta)) * np.sin(theta) / 48)
+
+def sph_legendre_p_4_m2_jac(theta):
+    fac = sph_legendre_factor(4, -2)
+
+    return (fac * (7 * np.square(np.cos(theta)) - 4) * np.sin(theta) *
+        np.cos(theta) / 12)
+
+def sph_legendre_p_4_m1_jac(theta):
+    fac = sph_legendre_factor(4, -1)
+
+    return (-fac * (-3 + 27 * np.square(np.cos(theta)) -
+        28 * np.square(np.square(np.cos(theta)))) *
+        (2 * np.heaviside(np.sin(theta), 1) - 1) / 8)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b3a5071fc671d8d4a7ef6c7655ca4212ced4f45
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_log_softmax.py
@@ -0,0 +1,109 @@
+import numpy as np
+from numpy.testing import assert_allclose
+
+import pytest
+
+import scipy.special as sc
+
+
+@pytest.mark.parametrize('x, expected', [
+    (np.array([1000, 1]), np.array([0, -999])),
+
+    # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+    # converted to float.
+    (np.arange(4), np.array([-3.4401896985611953,
+                             -2.4401896985611953,
+                             -1.4401896985611953,
+                             -0.44018969856119533]))
+])
+def test_log_softmax(x, expected):
+    assert_allclose(sc.log_softmax(x), expected, rtol=1e-13)
+
+
+@pytest.fixture
+def log_softmax_x():
+    x = np.arange(4)
+    return x
+
+
+@pytest.fixture
+def log_softmax_expected():
+    # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+    # converted to float.
+    expected = np.array([-3.4401896985611953,
+                         -2.4401896985611953,
+                         -1.4401896985611953,
+                         -0.44018969856119533])
+    return expected
+
+
+def test_log_softmax_translation(log_softmax_x, log_softmax_expected):
+    # Translation property.  If all the values are changed by the same amount,
+    # the softmax result does not change.
+    x = log_softmax_x + 100
+    expected = log_softmax_expected
+    assert_allclose(sc.log_softmax(x), expected, rtol=1e-13)
+
+
+def test_log_softmax_noneaxis(log_softmax_x, log_softmax_expected):
+    # When axis=None, softmax operates on the entire array, and preserves
+    # the shape.
+    x = log_softmax_x.reshape(2, 2)
+    expected = log_softmax_expected.reshape(2, 2)
+    assert_allclose(sc.log_softmax(x), expected, rtol=1e-13)
+
+
+@pytest.mark.parametrize('axis_2d, expected_2d', [
+    (0, np.log(0.5) * np.ones((2, 2))),
+    (1, np.array([[0, -999], [0, -999]]))
+])
+def test_axes(axis_2d, expected_2d):
+    assert_allclose(
+        sc.log_softmax([[1000, 1], [1000, 1]], axis=axis_2d),
+        expected_2d,
+        rtol=1e-13,
+    )
+
+
+@pytest.fixture
+def log_softmax_2d_x():
+    x = np.arange(8).reshape(2, 4)
+    return x
+
+
+@pytest.fixture
+def log_softmax_2d_expected():
+    # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+    # converted to float.
+    expected = np.array([[-3.4401896985611953,
+                         -2.4401896985611953,
+                         -1.4401896985611953,
+                         -0.44018969856119533],
+                        [-3.4401896985611953,
+                         -2.4401896985611953,
+                         -1.4401896985611953,
+                         -0.44018969856119533]])
+    return expected
+
+
+def test_log_softmax_2d_axis1(log_softmax_2d_x, log_softmax_2d_expected):
+    x = log_softmax_2d_x
+    expected = log_softmax_2d_expected
+    assert_allclose(sc.log_softmax(x, axis=1), expected, rtol=1e-13)
+
+
+def test_log_softmax_2d_axis0(log_softmax_2d_x, log_softmax_2d_expected):
+    x = log_softmax_2d_x.T
+    expected = log_softmax_2d_expected.T
+    assert_allclose(sc.log_softmax(x, axis=0), expected, rtol=1e-13)
+
+
+def test_log_softmax_3d(log_softmax_2d_x, log_softmax_2d_expected):
+    # 3-d input, with a tuple for the axis.
+    x_3d = log_softmax_2d_x.reshape(2, 2, 2)
+    expected_3d = log_softmax_2d_expected.reshape(2, 2, 2)
+    assert_allclose(sc.log_softmax(x_3d, axis=(1, 2)), expected_3d, rtol=1e-13)
+
+
+def test_log_softmax_scalar():
+    assert_allclose(sc.log_softmax(1.0), 0.0, rtol=1e-13)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fcb5a20037de46df939895d38fbe5fe6b85c9aa
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_loggamma.py
@@ -0,0 +1,70 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_
+
+from scipy.special._testutils import FuncData
+from scipy.special import gamma, gammaln, loggamma
+
+
+def test_identities1():
+    # test the identity exp(loggamma(z)) = gamma(z)
+    x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5])
+    y = x.copy()
+    x, y = np.meshgrid(x, y)
+    z = (x + 1J*y).flatten()
+    dataset = np.vstack((z, gamma(z))).T
+
+    def f(z):
+        return np.exp(loggamma(z))
+
+    FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+
+
+def test_identities2():
+    # test the identity loggamma(z + 1) = log(z) + loggamma(z)
+    x = np.array([-99.5, -9.5, -0.5, 0.5, 9.5, 99.5])
+    y = x.copy()
+    x, y = np.meshgrid(x, y)
+    z = (x + 1J*y).flatten()
+    dataset = np.vstack((z, np.log(z) + loggamma(z))).T
+
+    def f(z):
+        return loggamma(z + 1)
+
+    FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+
+
+def test_complex_dispatch_realpart():
+    # Test that the real parts of loggamma and gammaln agree on the
+    # real axis.
+    x = np.r_[-np.logspace(10, -10), np.logspace(-10, 10)] + 0.5
+
+    dataset = np.vstack((x, gammaln(x))).T
+
+    def f(z):
+        z = np.array(z, dtype='complex128')
+        return loggamma(z).real
+
+    FuncData(f, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+
+
+def test_real_dispatch():
+    x = np.logspace(-10, 10) + 0.5
+    dataset = np.vstack((x, gammaln(x))).T
+
+    FuncData(loggamma, dataset, 0, 1, rtol=1e-14, atol=1e-14).check()
+    assert_(loggamma(0) == np.inf)
+    assert_(np.isnan(loggamma(-1)))
+
+
+def test_gh_6536():
+    z = loggamma(complex(-3.4, +0.0))
+    zbar = loggamma(complex(-3.4, -0.0))
+    assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0)
+
+
+def test_branch_cut():
+    # Make sure negative zero is treated correctly
+    x = -np.logspace(300, -30, 100)
+    z = np.asarray([complex(x0, 0.0) for x0 in x])
+    zbar = np.asarray([complex(x0, -0.0) for x0 in x])
+    assert_allclose(z, zbar.conjugate(), rtol=1e-15, atol=0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py
new file mode 100644
index 0000000000000000000000000000000000000000..050e8db5cb408c5c576c6cd292175d2df7c8f756
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logit.py
@@ -0,0 +1,162 @@
+import numpy as np
+from numpy.testing import (assert_equal, assert_almost_equal,
+                           assert_allclose)
+from scipy.special import logit, expit, log_expit
+
+
+class TestLogit:
+
+    def check_logit_out(self, a, expected):
+        actual = logit(a)
+        assert_equal(actual.dtype, a.dtype)
+        rtol = 16*np.finfo(a.dtype).eps
+        assert_allclose(actual, expected, rtol=rtol)
+
+    def test_float32(self):
+        a = np.concatenate((np.linspace(0, 1, 10, dtype=np.float32),
+                            [np.float32(0.0001), np.float32(0.49999),
+                             np.float32(0.50001)]))
+        # Expected values computed with mpmath from float32 inputs, e.g.
+        #   from mpmath import mp
+        #   mp.dps = 200
+        #   a = np.float32(1/9)
+        #   print(np.float32(mp.log(a) - mp.log1p(-a)))
+        # prints `-2.0794415`.
+        expected = np.array([-np.inf, -2.0794415, -1.2527629, -6.9314712e-01,
+                             -2.2314353e-01,  2.2314365e-01,  6.9314724e-01,
+                             1.2527630, 2.0794415, np.inf,
+                             -9.2102404, -4.0054321e-05, 4.0054321e-05],
+                            dtype=np.float32)
+        self.check_logit_out(a, expected)
+
+    def test_float64(self):
+        a = np.concatenate((np.linspace(0, 1, 10, dtype=np.float64),
+                            [1e-8, 0.4999999999999, 0.50000000001]))
+        # Expected values computed with mpmath.
+        expected = np.array([-np.inf,
+                             -2.079441541679836,
+                             -1.252762968495368,
+                             -0.6931471805599454,
+                             -0.22314355131420985,
+                             0.22314355131420985,
+                             0.6931471805599452,
+                             1.2527629684953674,
+                             2.0794415416798353,
+                             np.inf,
+                             -18.420680733952366,
+                             -3.999023334699814e-13,
+                             4.000000330961484e-11])
+        self.check_logit_out(a, expected)
+
+    def test_nan(self):
+        expected = np.array([np.nan]*4)
+        with np.errstate(invalid='ignore'):
+            actual = logit(np.array([-3., -2., 2., 3.]))
+
+        assert_equal(expected, actual)
+
+
+class TestExpit:
+    def check_expit_out(self, dtype, expected):
+        a = np.linspace(-4, 4, 10)
+        a = np.array(a, dtype=dtype)
+        actual = expit(a)
+        assert_almost_equal(actual, expected)
+        assert_equal(actual.dtype, np.dtype(dtype))
+
+    def test_float32(self):
+        expected = np.array([0.01798621, 0.04265125,
+                            0.09777259, 0.20860852,
+                            0.39068246, 0.60931754,
+                            0.79139149, 0.9022274,
+                            0.95734876, 0.98201376], dtype=np.float32)
+        self.check_expit_out('f4', expected)
+
+    def test_float64(self):
+        expected = np.array([0.01798621, 0.04265125,
+                            0.0977726, 0.20860853,
+                            0.39068246, 0.60931754,
+                            0.79139147, 0.9022274,
+                            0.95734875, 0.98201379])
+        self.check_expit_out('f8', expected)
+
+    def test_large(self):
+        for dtype in (np.float32, np.float64, np.longdouble):
+            for n in (88, 89, 709, 710, 11356, 11357):
+                n = np.array(n, dtype=dtype)
+                assert_allclose(expit(n), 1.0, atol=1e-20)
+                assert_allclose(expit(-n), 0.0, atol=1e-20)
+                assert_equal(expit(n).dtype, dtype)
+                assert_equal(expit(-n).dtype, dtype)
+
+
+class TestLogExpit:
+
+    def test_large_negative(self):
+        x = np.array([-10000.0, -750.0, -500.0, -35.0])
+        y = log_expit(x)
+        assert_equal(y, x)
+
+    def test_large_positive(self):
+        x = np.array([750.0, 1000.0, 10000.0])
+        y = log_expit(x)
+        # y will contain -0.0, and -0.0 is used in the expected value,
+        # but assert_equal does not check the sign of zeros, and I don't
+        # think the sign is an essential part of the test (i.e. it would
+        # probably be OK if log_expit(1000) returned 0.0 instead of -0.0).
+        assert_equal(y, np.array([-0.0, -0.0, -0.0]))
+
+    def test_basic_float64(self):
+        x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9,
+                      0, 1e-9, 0.1, 1, 10, 100, 500, 710, 725, 735])
+        y = log_expit(x)
+        #
+        # Expected values were computed with mpmath:
+        #
+        #   import mpmath
+        #
+        #   mpmath.mp.dps = 100
+        #
+        #   def mp_log_expit(x):
+        #       return -mpmath.log1p(mpmath.exp(-x))
+        #
+        #   expected = [float(mp_log_expit(t)) for t in x]
+        #
+        expected = [-32.000000000000014, -20.000000002061153,
+                    -10.000045398899218, -3.048587351573742,
+                    -1.3132616875182228, -0.7443966600735709,
+                    -0.6931471810599453, -0.6931471805599453,
+                    -0.6931471800599454, -0.6443966600735709,
+                    -0.3132616875182228, -4.539889921686465e-05,
+                    -3.720075976020836e-44, -7.124576406741286e-218,
+                    -4.47628622567513e-309, -1.36930634e-315,
+                    -6.217e-320]
+
+        # When tested locally, only one value in y was not exactly equal to
+        # expected.  That was for x=1, and the y value differed from the
+        # expected by 1 ULP.  For this test, however, I'll use rtol=1e-15.
+        assert_allclose(y, expected, rtol=1e-15)
+
+    def test_basic_float32(self):
+        x = np.array([-32, -20, -10, -3, -1, -0.1, -1e-9,
+                      0, 1e-9, 0.1, 1, 10, 100], dtype=np.float32)
+        y = log_expit(x)
+        #
+        # Expected values were computed with mpmath:
+        #
+        #   import mpmath
+        #
+        #   mpmath.mp.dps = 100
+        #
+        #   def mp_log_expit(x):
+        #       return -mpmath.log1p(mpmath.exp(-x))
+        #
+        #   expected = [np.float32(mp_log_expit(t)) for t in x]
+        #
+        expected = np.array([-32.0, -20.0, -10.000046, -3.0485873,
+                             -1.3132616, -0.7443967, -0.6931472,
+                             -0.6931472, -0.6931472, -0.64439666,
+                             -0.3132617, -4.5398898e-05, -3.8e-44],
+                            dtype=np.float32)
+
+        assert_allclose(y, expected, rtol=5e-7)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py
new file mode 100644
index 0000000000000000000000000000000000000000..420c0d89f438701b57c4786ce7fa62279c668e5e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_logsumexp.py
@@ -0,0 +1,327 @@
+import math
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import array_namespace, is_array_api_strict
+from scipy._lib._array_api_no_0d import (xp_assert_equal, xp_assert_close,
+                                         xp_assert_less)
+
+from scipy.special import logsumexp, softmax
+from scipy.special._logsumexp import _wrap_radians
+
+
+dtypes = ['float32', 'float64', 'int32', 'int64', 'complex64', 'complex128']
+integral_dtypes = ['int32', 'int64']
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends('jax.numpy',
+                              reason="JAX arrays do not support item assignment")
+def test_wrap_radians(xp):
+    x = xp.asarray([-math.pi-1, -math.pi, -1, -1e-300,
+                    0, 1e-300, 1, math.pi, math.pi+1])
+    ref = xp.asarray([math.pi-1, math.pi, -1, -1e-300,
+                    0, 1e-300, 1, math.pi, -math.pi+1])
+    res = _wrap_radians(x, xp)
+    xp_assert_close(res, ref, atol=0)
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@pytest.mark.skip_xp_backends('jax.numpy',
+                              reason="JAX arrays do not support item assignment")
+class TestLogSumExp:
+    def test_logsumexp(self, xp):
+        # Test with zero-size array
+        a = xp.asarray([])
+        desired = xp.asarray(-xp.inf)
+        xp_assert_equal(logsumexp(a), desired)
+
+        # Test whether logsumexp() function correctly handles large inputs.
+        a = xp.arange(200., dtype=xp.float64)
+        desired = xp.log(xp.sum(xp.exp(a)))
+        xp_assert_close(logsumexp(a), desired)
+
+        # Now test with large numbers
+        b = xp.asarray([1000., 1000.])
+        desired = xp.asarray(1000.0 + math.log(2.0))
+        xp_assert_close(logsumexp(b), desired)
+
+        n = 1000
+        b = xp.full((n,), 10000)
+        desired = xp.asarray(10000.0 + math.log(n))
+        xp_assert_close(logsumexp(b), desired)
+
+        x = xp.asarray([1e-40] * 1000000)
+        logx = xp.log(x)
+        X = xp.stack([x, x])
+        logX = xp.stack([logx, logx])
+        xp_assert_close(xp.exp(logsumexp(logX)), xp.sum(X))
+        xp_assert_close(xp.exp(logsumexp(logX, axis=0)), xp.sum(X, axis=0))
+        xp_assert_close(xp.exp(logsumexp(logX, axis=1)), xp.sum(X, axis=1))
+
+        # Handling special values properly
+        inf = xp.asarray([xp.inf])
+        nan = xp.asarray([xp.nan])
+        xp_assert_equal(logsumexp(inf), inf[0])
+        xp_assert_equal(logsumexp(-inf), -inf[0])
+        xp_assert_equal(logsumexp(nan), nan[0])
+        xp_assert_equal(logsumexp(xp.asarray([-xp.inf, -xp.inf])), -inf[0])
+
+        # Handling an array with different magnitudes on the axes
+        a = xp.asarray([[1e10, 1e-10],
+                        [-1e10, -np.inf]])
+        ref = xp.asarray([1e10, -1e10])
+        xp_assert_close(logsumexp(a, axis=-1), ref)
+
+        # Test keeping dimensions
+        xp_test = array_namespace(a) # `torch` needs `expand_dims`
+        ref = xp_test.expand_dims(ref, axis=-1)
+        xp_assert_close(logsumexp(a, axis=-1, keepdims=True), ref)
+
+        # Test multiple axes
+        xp_assert_close(logsumexp(a, axis=(-1, -2)), xp.asarray(1e10))
+
+    def test_logsumexp_b(self, xp):
+        a = xp.arange(200., dtype=xp.float64)
+        b = xp.arange(200., 0., -1.)
+        desired = xp.log(xp.sum(b*xp.exp(a)))
+        xp_assert_close(logsumexp(a, b=b), desired)
+
+        a = xp.asarray([1000, 1000])
+        b = xp.asarray([1.2, 1.2])
+        desired = xp.asarray(1000 + math.log(2 * 1.2))
+        xp_assert_close(logsumexp(a, b=b), desired)
+
+        x = xp.asarray([1e-40] * 100000)
+        b = xp.linspace(1, 1000, 100000)
+        logx = xp.log(x)
+        X = xp.stack((x, x))
+        logX = xp.stack((logx, logx))
+        B = xp.stack((b, b))
+        xp_assert_close(xp.exp(logsumexp(logX, b=B)), xp.sum(B * X))
+        xp_assert_close(xp.exp(logsumexp(logX, b=B, axis=0)), xp.sum(B * X, axis=0))
+        xp_assert_close(xp.exp(logsumexp(logX, b=B, axis=1)), xp.sum(B * X, axis=1))
+
+    def test_logsumexp_sign(self, xp):
+        a = xp.asarray([1, 1, 1])
+        b = xp.asarray([1, -1, -1])
+
+        r, s = logsumexp(a, b=b, return_sign=True)
+        xp_assert_close(r, xp.asarray(1.))
+        xp_assert_equal(s, xp.asarray(-1.))
+
+    def test_logsumexp_sign_zero(self, xp):
+        a = xp.asarray([1, 1])
+        b = xp.asarray([1, -1])
+
+        r, s = logsumexp(a, b=b, return_sign=True)
+        assert not xp.isfinite(r)
+        assert not xp.isnan(r)
+        assert r < 0
+        assert s == 0
+
+    def test_logsumexp_sign_shape(self, xp):
+        a = xp.ones((1, 2, 3, 4))
+        b = xp.ones_like(a)
+
+        r, s = logsumexp(a, axis=2, b=b, return_sign=True)
+        assert r.shape == s.shape == (1, 2, 4)
+
+        r, s = logsumexp(a, axis=(1, 3), b=b, return_sign=True)
+        assert r.shape == s.shape == (1,3)
+
+    def test_logsumexp_complex_sign(self, xp):
+        a = xp.asarray([1 + 1j, 2 - 1j, -2 + 3j])
+
+        r, s = logsumexp(a, return_sign=True)
+
+        expected_sumexp = xp.sum(xp.exp(a))
+        # This is the numpy>=2.0 convention for np.sign
+        expected_sign = expected_sumexp / xp.abs(expected_sumexp)
+
+        xp_assert_close(s, expected_sign)
+        xp_assert_close(s * xp.exp(r), expected_sumexp)
+
+    def test_logsumexp_shape(self, xp):
+        a = xp.ones((1, 2, 3, 4))
+        b = xp.ones_like(a)
+
+        r = logsumexp(a, axis=2, b=b)
+        assert r.shape == (1, 2, 4)
+
+        r = logsumexp(a, axis=(1, 3), b=b)
+        assert r.shape == (1, 3)
+
+    def test_logsumexp_b_zero(self, xp):
+        a = xp.asarray([1, 10000])
+        b = xp.asarray([1, 0])
+
+        xp_assert_close(logsumexp(a, b=b), xp.asarray(1.))
+
+    def test_logsumexp_b_shape(self, xp):
+        a = xp.zeros((4, 1, 2, 1))
+        b = xp.ones((3, 1, 5))
+
+        logsumexp(a, b=b)
+
+    @pytest.mark.parametrize('arg', (1, [1, 2, 3]))
+    @pytest.mark.skip_xp_backends(np_only=True)
+    def test_xp_invalid_input(self, arg, xp):
+        assert logsumexp(arg) == logsumexp(np.asarray(np.atleast_1d(arg)))
+
+    @pytest.mark.skip_xp_backends(np_only=True,
+                                  reason="Lists correspond with NumPy backend")
+    def test_list(self, xp):
+        a = [1000, 1000]
+        desired = xp.asarray(1000.0 + math.log(2.0), dtype=np.float64)
+        xp_assert_close(logsumexp(a), desired)
+
+    @pytest.mark.parametrize('dtype', dtypes)
+    def test_dtypes_a(self, dtype, xp):
+        dtype = getattr(xp, dtype)
+        a = xp.asarray([1000., 1000.], dtype=dtype)
+        xp_test = array_namespace(a)  # torch needs compatible `isdtype`
+        desired_dtype = (xp.asarray(1.).dtype if xp_test.isdtype(dtype, 'integral')
+                         else dtype)  # true for all libraries tested
+        desired = xp.asarray(1000.0 + math.log(2.0), dtype=desired_dtype)
+        xp_assert_close(logsumexp(a), desired)
+
+    @pytest.mark.parametrize('dtype_a', dtypes)
+    @pytest.mark.parametrize('dtype_b', dtypes)
+    def test_dtypes_ab(self, dtype_a, dtype_b, xp):
+        xp_dtype_a = getattr(xp, dtype_a)
+        xp_dtype_b = getattr(xp, dtype_b)
+        a = xp.asarray([2, 1], dtype=xp_dtype_a)
+        b = xp.asarray([1, -1], dtype=xp_dtype_b)
+        xp_test = array_namespace(a, b)  # torch needs compatible result_type
+        if is_array_api_strict(xp):
+            xp_float_dtypes = [dtype for dtype in [xp_dtype_a, xp_dtype_b]
+                               if not xp_test.isdtype(dtype, 'integral')]
+            if len(xp_float_dtypes) < 2:  # at least one is integral
+                xp_float_dtypes.append(xp.asarray(1.).dtype)
+            desired_dtype = xp_test.result_type(*xp_float_dtypes)
+        else:
+            # True for all libraries tested
+            desired_dtype = xp_test.result_type(xp_dtype_a, xp_dtype_b, xp.float32)
+        desired = xp.asarray(math.log(math.exp(2) - math.exp(1)), dtype=desired_dtype)
+        xp_assert_close(logsumexp(a, b=b), desired)
+
+    def test_gh18295(self, xp):
+        # gh-18295 noted loss of precision when real part of one element is much
+        # larger than the rest. Check that this is resolved.
+        a = xp.asarray([0.0, -40.0])
+        res = logsumexp(a)
+        ref = xp.logaddexp(a[0], a[1])
+        xp_assert_close(res, ref)
+
+    @pytest.mark.parametrize('dtype', ['complex64', 'complex128'])
+    def test_gh21610(self, xp, dtype):
+        # gh-21610 noted that `logsumexp` could return imaginary components
+        # outside the range (-pi, pi]. Check that this is resolved.
+        # While working on this, I noticed that all other tests passed even
+        # when the imaginary component of the result was zero. This suggested
+        # the need of a stronger test with imaginary dtype.
+        rng = np.random.default_rng(324984329582349862)
+        dtype = getattr(xp, dtype)
+        shape = (10, 100)
+        x = rng.uniform(1, 40, shape) + 1.j * rng.uniform(1, 40, shape)
+        x = xp.asarray(x, dtype=dtype)
+
+        res = logsumexp(x, axis=1)
+        ref = xp.log(xp.sum(xp.exp(x), axis=1))
+        max = xp.full_like(xp.imag(res), xp.asarray(xp.pi))
+        xp_assert_less(xp.abs(xp.imag(res)), max)
+        xp_assert_close(res, ref)
+
+        out, sgn = logsumexp(x, return_sign=True, axis=1)
+        ref = xp.sum(xp.exp(x), axis=1)
+        xp_assert_less(xp.abs(xp.imag(sgn)), max)
+        xp_assert_close(out, xp.real(xp.log(ref)))
+        xp_assert_close(sgn, ref/xp.abs(ref))
+
+    def test_gh21709_small_imaginary(self, xp):
+        # Test that `logsumexp` does not lose relative precision of
+        # small imaginary components
+        x = xp.asarray([0, 0.+2.2204460492503132e-17j])
+        res = logsumexp(x)
+        # from mpmath import mp
+        # mp.dps = 100
+        # x, y = mp.mpc(0), mp.mpc('0', '2.2204460492503132e-17')
+        # ref = complex(mp.log(mp.exp(x) + mp.exp(y)))
+        ref = xp.asarray(0.6931471805599453+1.1102230246251566e-17j)
+        xp_assert_close(xp.real(res), xp.real(ref))
+        xp_assert_close(xp.imag(res), xp.imag(ref), atol=0, rtol=1e-15)
+
+    def test_gh22903(self, xp):
+        # gh-22903 reported that `logsumexp` produced NaN where the weight associated
+        # with the max magnitude element was negative and `return_sign=False`, even if
+        # the net result should be the log of a positive number.
+
+        # result is log of positive number
+        a = xp.asarray([3.06409428, 0.37251854, 3.87471931])
+        b = xp.asarray([1.88190708, 2.84174795, -0.85016884])
+        xp_assert_close(logsumexp(a, b=b), logsumexp(a, b=b, return_sign=True)[0])
+
+        # result is log of negative number
+        b = xp.asarray([1.88190708, 2.84174795, -3.85016884])
+        xp_assert_close(logsumexp(a, b=b), xp.asarray(xp.nan))
+
+
+class TestSoftmax:
+    def test_softmax_fixtures(self):
+        assert_allclose(softmax([1000, 0, 0, 0]), np.array([1, 0, 0, 0]),
+                        rtol=1e-13)
+        assert_allclose(softmax([1, 1]), np.array([.5, .5]), rtol=1e-13)
+        assert_allclose(softmax([0, 1]), np.array([1, np.e])/(1 + np.e),
+                        rtol=1e-13)
+
+        # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+        # converted to float.
+        x = np.arange(4)
+        expected = np.array([0.03205860328008499,
+                            0.08714431874203256,
+                            0.23688281808991013,
+                            0.6439142598879722])
+
+        assert_allclose(softmax(x), expected, rtol=1e-13)
+
+        # Translation property.  If all the values are changed by the same amount,
+        # the softmax result does not change.
+        assert_allclose(softmax(x + 100), expected, rtol=1e-13)
+
+        # When axis=None, softmax operates on the entire array, and preserves
+        # the shape.
+        assert_allclose(softmax(x.reshape(2, 2)), expected.reshape(2, 2),
+                        rtol=1e-13)
+
+
+    def test_softmax_multi_axes(self):
+        assert_allclose(softmax([[1000, 0], [1000, 0]], axis=0),
+                        np.array([[.5, .5], [.5, .5]]), rtol=1e-13)
+        assert_allclose(softmax([[1000, 0], [1000, 0]], axis=1),
+                        np.array([[1, 0], [1, 0]]), rtol=1e-13)
+
+        # Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
+        # converted to float.
+        x = np.array([[-25, 0, 25, 50],
+                    [1, 325, 749, 750]])
+        expected = np.array([[2.678636961770877e-33,
+                            1.9287498479371314e-22,
+                            1.3887943864771144e-11,
+                            0.999999999986112],
+                            [0.0,
+                            1.9444526359919372e-185,
+                            0.2689414213699951,
+                            0.7310585786300048]])
+        assert_allclose(softmax(x, axis=1), expected, rtol=1e-13)
+        assert_allclose(softmax(x.T, axis=0), expected.T, rtol=1e-13)
+
+        # 3-d input, with a tuple for the axis.
+        x3d = x.reshape(2, 2, 2)
+        assert_allclose(softmax(x3d, axis=(1, 2)), expected.reshape(2, 2, 2),
+                        rtol=1e-13)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py
new file mode 100644
index 0000000000000000000000000000000000000000..43e84e444f2eda03aef77ea923ca2d498aef4126
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_mpmath.py
@@ -0,0 +1,2292 @@
+"""
+Test SciPy functions versus mpmath, if available.
+
+"""
+import numpy as np
+from numpy.testing import assert_, assert_allclose, suppress_warnings
+from numpy import pi
+import pytest
+import itertools
+
+from scipy._lib import _pep440
+
+import scipy.special as sc
+from scipy.special._testutils import (
+    MissingModule, check_version, FuncData,
+    assert_func_equal)
+from scipy.special._mptestutils import (
+    Arg, FixedArg, ComplexArg, IntArg, assert_mpmath_equal,
+    nonfunctional_tooslow, trace_args, time_limited, exception_to_nan,
+    inf_to_nan)
+from scipy.special._ufuncs import (
+    _sinpi, _cospi, _lgam1p, _lanczos_sum_expg_scaled, _log1pmx,
+    _igam_fac)
+
+try:
+    import mpmath
+except ImportError:
+    mpmath = MissingModule('mpmath')
+
+
+# ------------------------------------------------------------------------------
+# expi
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.10')
+def test_expi_complex():
+    dataset = []
+    for r in np.logspace(-99, 2, 10):
+        for p in np.linspace(0, 2*np.pi, 30):
+            z = r*np.exp(1j*p)
+            dataset.append((z, complex(mpmath.ei(z))))
+    dataset = np.array(dataset, dtype=np.cdouble)
+
+    FuncData(sc.expi, dataset, 0, 1).check()
+
+
+# ------------------------------------------------------------------------------
+# expn
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+def test_expn_large_n():
+    # Test the transition to the asymptotic regime of n.
+    dataset = []
+    for n in [50, 51]:
+        for x in np.logspace(0, 4, 200):
+            with mpmath.workdps(100):
+                dataset.append((n, x, float(mpmath.expint(n, x))))
+    dataset = np.asarray(dataset)
+
+    FuncData(sc.expn, dataset, (0, 1), 2, rtol=1e-13).check()
+
+# ------------------------------------------------------------------------------
+# hyp0f1
+# ------------------------------------------------------------------------------
+
+
+@check_version(mpmath, '0.19')
+def test_hyp0f1_gh5764():
+    # Do a small and somewhat systematic test that runs quickly
+    dataset = []
+    axis = [-99.5, -9.5, -0.5, 0.5, 9.5, 99.5]
+    for v in axis:
+        for x in axis:
+            for y in axis:
+                z = x + 1j*y
+                # mpmath computes the answer correctly at dps ~ 17 but
+                # fails for 20 < dps < 120 (uses a different method);
+                # set the dps high enough that this isn't an issue
+                with mpmath.workdps(120):
+                    res = complex(mpmath.hyp0f1(v, z))
+                dataset.append((v, z, res))
+    dataset = np.array(dataset)
+
+    FuncData(lambda v, z: sc.hyp0f1(v.real, z), dataset, (0, 1), 2,
+             rtol=1e-13).check()
+
+
+@check_version(mpmath, '0.19')
+def test_hyp0f1_gh_1609():
+    # this is a regression test for gh-1609
+    vv = np.linspace(150, 180, 21)
+    af = sc.hyp0f1(vv, 0.5)
+    mf = np.array([mpmath.hyp0f1(v, 0.5) for v in vv])
+    assert_allclose(af, mf.astype(float), rtol=1e-12)
+
+
+# ------------------------------------------------------------------------------
+# hyperu
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '1.1.0')
+def test_hyperu_around_0():
+    dataset = []
+    # DLMF 13.2.14-15 test points.
+    for n in np.arange(-5, 5):
+        for b in np.linspace(-5, 5, 20):
+            a = -n
+            dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
+            a = -n + b - 1
+            dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
+    # DLMF 13.2.16-22 test points.
+    for a in [-10.5, -1.5, -0.5, 0, 0.5, 1, 10]:
+        for b in [-1.0, -0.5, 0, 0.5, 1, 1.5, 2, 2.5]:
+            dataset.append((a, b, 0, float(mpmath.hyperu(a, b, 0))))
+    dataset = np.array(dataset)
+
+    FuncData(sc.hyperu, dataset, (0, 1, 2), 3, rtol=1e-15, atol=5e-13).check()
+
+
+# ------------------------------------------------------------------------------
+# hyp2f1
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '1.0.0')
+def test_hyp2f1_strange_points():
+    pts = [
+        (2, -1, -1, 0.7),  # expected: 2.4
+        (2, -2, -2, 0.7),  # expected: 3.87
+    ]
+    pts += list(itertools.product([2, 1, -0.7, -1000], repeat=4))
+    pts = [
+        (a, b, c, x) for a, b, c, x in pts
+        if b == c and round(b) == b and b < 0 and b != -1000
+    ]
+    kw = dict(eliminate=True)
+    dataset = [p + (float(mpmath.hyp2f1(*p, **kw)),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
+
+
+@check_version(mpmath, '0.13')
+def test_hyp2f1_real_some_points():
+    pts = [
+        (1, 2, 3, 0),
+        (1./3, 2./3, 5./6, 27./32),
+        (1./4, 1./2, 3./4, 80./81),
+        (2,-2, -3, 3),
+        (2, -3, -2, 3),
+        (2, -1.5, -1.5, 3),
+        (1, 2, 3, 0),
+        (0.7235, -1, -5, 0.3),
+        (0.25, 1./3, 2, 0.999),
+        (0.25, 1./3, 2, -1),
+        (2, 3, 5, 0.99),
+        (3./2, -0.5, 3, 0.99),
+        (2, 2.5, -3.25, 0.999),
+        (-8, 18.016500331508873, 10.805295997850628, 0.90875647507000001),
+        (-10, 900, -10.5, 0.99),
+        (-10, 900, 10.5, 0.99),
+        (-1, 2, 1, 1.0),
+        (-1, 2, 1, -1.0),
+        (-3, 13, 5, 1.0),
+        (-3, 13, 5, -1.0),
+        (0.5, 1 - 270.5, 1.5, 0.999**2),  # from issue 1561
+    ]
+    dataset = [p + (float(mpmath.hyp2f1(*p)),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    with np.errstate(invalid='ignore'):
+        FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
+
+
+@check_version(mpmath, '0.14')
+def test_hyp2f1_some_points_2():
+    # Taken from mpmath unit tests -- this point failed for mpmath 0.13 but
+    # was fixed in their SVN since then
+    pts = [
+        (112, (51,10), (-9,10), -0.99999),
+        (10,-900,10.5,0.99),
+        (10,-900,-10.5,0.99),
+    ]
+
+    def fev(x):
+        if isinstance(x, tuple):
+            return float(x[0]) / x[1]
+        else:
+            return x
+
+    dataset = [tuple(map(fev, p)) + (float(mpmath.hyp2f1(*p)),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-10).check()
+
+
+@check_version(mpmath, '0.13')
+def test_hyp2f1_real_some():
+    dataset = []
+    for a in [-10, -5, -1.8, 1.8, 5, 10]:
+        for b in [-2.5, -1, 1, 7.4]:
+            for c in [-9, -1.8, 5, 20.4]:
+                for z in [-10, -1.01, -0.99, 0, 0.6, 0.95, 1.5, 10]:
+                    try:
+                        v = float(mpmath.hyp2f1(a, b, c, z))
+                    except Exception:
+                        continue
+                    dataset.append((a, b, c, z, v))
+    dataset = np.array(dataset, dtype=np.float64)
+
+    with np.errstate(invalid='ignore'):
+        FuncData(sc.hyp2f1, dataset, (0,1,2,3), 4, rtol=1e-9,
+                 ignore_inf_sign=True).check()
+
+
+@check_version(mpmath, '0.12')
+@pytest.mark.slow
+def test_hyp2f1_real_random():
+    npoints = 500
+    dataset = np.zeros((npoints, 5), np.float64)
+
+    np.random.seed(1234)
+    dataset[:, 0] = np.random.pareto(1.5, npoints)
+    dataset[:, 1] = np.random.pareto(1.5, npoints)
+    dataset[:, 2] = np.random.pareto(1.5, npoints)
+    dataset[:, 3] = 2*np.random.rand(npoints) - 1
+
+    dataset[:, 0] *= (-1)**np.random.randint(2, npoints)
+    dataset[:, 1] *= (-1)**np.random.randint(2, npoints)
+    dataset[:, 2] *= (-1)**np.random.randint(2, npoints)
+
+    for ds in dataset:
+        if mpmath.__version__ < '0.14':
+            # mpmath < 0.14 fails for c too much smaller than a, b
+            if abs(ds[:2]).max() > abs(ds[2]):
+                ds[2] = abs(ds[:2]).max()
+        ds[4] = float(mpmath.hyp2f1(*tuple(ds[:4])))
+
+    FuncData(sc.hyp2f1, dataset, (0, 1, 2, 3), 4, rtol=1e-9).check()
+
+
+# ------------------------------------------------------------------------------
+# erf (complex)
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.14')
+def test_erf_complex():
+    # need to increase mpmath precision for this test
+    old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
+    try:
+        mpmath.mp.dps = 70
+        x1, y1 = np.meshgrid(np.linspace(-10, 1, 31), np.linspace(-10, 1, 11))
+        x2, y2 = np.meshgrid(np.logspace(-80, .8, 31), np.logspace(-80, .8, 11))
+        points = np.r_[x1.ravel(),x2.ravel()] + 1j*np.r_[y1.ravel(), y2.ravel()]
+
+        assert_func_equal(sc.erf, lambda x: complex(mpmath.erf(x)), points,
+                          vectorized=False, rtol=1e-13)
+        assert_func_equal(sc.erfc, lambda x: complex(mpmath.erfc(x)), points,
+                          vectorized=False, rtol=1e-13)
+    finally:
+        mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
+
+
+# ------------------------------------------------------------------------------
+# lpmv
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.15')
+def test_lpmv():
+    pts = []
+    for x in [-0.99, -0.557, 1e-6, 0.132, 1]:
+        pts.extend([
+            (1, 1, x),
+            (1, -1, x),
+            (-1, 1, x),
+            (-1, -2, x),
+            (1, 1.7, x),
+            (1, -1.7, x),
+            (-1, 1.7, x),
+            (-1, -2.7, x),
+            (1, 10, x),
+            (1, 11, x),
+            (3, 8, x),
+            (5, 11, x),
+            (-3, 8, x),
+            (-5, 11, x),
+            (3, -8, x),
+            (5, -11, x),
+            (-3, -8, x),
+            (-5, -11, x),
+            (3, 8.3, x),
+            (5, 11.3, x),
+            (-3, 8.3, x),
+            (-5, 11.3, x),
+            (3, -8.3, x),
+            (5, -11.3, x),
+            (-3, -8.3, x),
+            (-5, -11.3, x),
+        ])
+
+    def mplegenp(nu, mu, x):
+        if mu == int(mu) and x == 1:
+            # mpmath 0.17 gets this wrong
+            if mu == 0:
+                return 1
+            else:
+                return 0
+        return mpmath.legenp(nu, mu, x)
+
+    dataset = [p + (mplegenp(p[1], p[0], p[2]),) for p in pts]
+    dataset = np.array(dataset, dtype=np.float64)
+
+    def evf(mu, nu, x):
+        return sc.lpmv(mu.astype(int), nu, x)
+
+    with np.errstate(invalid='ignore'):
+        FuncData(evf, dataset, (0,1,2), 3, rtol=1e-10, atol=1e-14).check()
+
+
+# ------------------------------------------------------------------------------
+# beta
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.15')
+def test_beta():
+    np.random.seed(1234)
+
+    b = np.r_[np.logspace(-200, 200, 4),
+              np.logspace(-10, 10, 4),
+              np.logspace(-1, 1, 4),
+              np.arange(-10, 11, 1),
+              np.arange(-10, 11, 1) + 0.5,
+              -1, -2.3, -3, -100.3, -10003.4]
+    a = b
+
+    ab = np.array(np.broadcast_arrays(a[:,None], b[None,:])).reshape(2, -1).T
+
+    old_dps, old_prec = mpmath.mp.dps, mpmath.mp.prec
+    try:
+        mpmath.mp.dps = 400
+
+        assert_func_equal(sc.beta,
+                          lambda a, b: float(mpmath.beta(a, b)),
+                          ab,
+                          vectorized=False,
+                          rtol=1e-10,
+                          ignore_inf_sign=True)
+
+        assert_func_equal(
+            sc.betaln,
+            lambda a, b: float(mpmath.log(abs(mpmath.beta(a, b)))),
+            ab,
+            vectorized=False,
+            rtol=1e-10)
+    finally:
+        mpmath.mp.dps, mpmath.mp.prec = old_dps, old_prec
+
+
+# ------------------------------------------------------------------------------
+# loggamma
+# ------------------------------------------------------------------------------
+
+LOGGAMMA_TAYLOR_RADIUS = 0.2
+
+
+@check_version(mpmath, '0.19')
+def test_loggamma_taylor_transition():
+    # Make sure there isn't a big jump in accuracy when we move from
+    # using the Taylor series to using the recurrence relation.
+
+    r = LOGGAMMA_TAYLOR_RADIUS + np.array([-0.1, -0.01, 0, 0.01, 0.1])
+    theta = np.linspace(0, 2*np.pi, 20)
+    r, theta = np.meshgrid(r, theta)
+    dz = r*np.exp(1j*theta)
+    z = np.r_[1 + dz, 2 + dz].flatten()
+
+    dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z]
+    dataset = np.array(dataset)
+
+    FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check()
+
+
+@check_version(mpmath, '0.19')
+def test_loggamma_taylor():
+    # Test around the zeros at z = 1, 2.
+
+    r = np.logspace(-16, np.log10(LOGGAMMA_TAYLOR_RADIUS), 10)
+    theta = np.linspace(0, 2*np.pi, 20)
+    r, theta = np.meshgrid(r, theta)
+    dz = r*np.exp(1j*theta)
+    z = np.r_[1 + dz, 2 + dz].flatten()
+
+    dataset = [(z0, complex(mpmath.loggamma(z0))) for z0 in z]
+    dataset = np.array(dataset)
+
+    FuncData(sc.loggamma, dataset, 0, 1, rtol=5e-14).check()
+
+
+# ------------------------------------------------------------------------------
+# rgamma
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_rgamma_zeros():
+    # Test around the zeros at z = 0, -1, -2, ...,  -169. (After -169 we
+    # get values that are out of floating point range even when we're
+    # within 0.1 of the zero.)
+
+    # Can't use too many points here or the test takes forever.
+    dx = np.r_[-np.logspace(-1, -13, 3), 0, np.logspace(-13, -1, 3)]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    zeros = np.arange(0, -170, -1).reshape(1, 1, -1)
+    z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
+    with mpmath.workdps(100):
+        dataset = [(z0, complex(mpmath.rgamma(z0))) for z0 in z]
+
+    dataset = np.array(dataset)
+    FuncData(sc.rgamma, dataset, 0, 1, rtol=1e-12).check()
+
+
+# ------------------------------------------------------------------------------
+# digamma
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_digamma_roots():
+    # Test the special-cased roots for digamma.
+    root = mpmath.findroot(mpmath.digamma, 1.5)
+    roots = [float(root)]
+    root = mpmath.findroot(mpmath.digamma, -0.5)
+    roots.append(float(root))
+    roots = np.array(roots)
+
+    # If we test beyond a radius of 0.24 mpmath will take forever.
+    dx = np.r_[-0.24, -np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10), 0.24]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    z = (roots + np.dstack((dz,)*roots.size)).flatten()
+    with mpmath.workdps(30):
+        dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z]
+
+    dataset = np.array(dataset)
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-14).check()
+
+
+@check_version(mpmath, '0.19')
+def test_digamma_negreal():
+    # Test digamma around the negative real axis. Don't do this in
+    # TestSystematic because the points need some jiggering so that
+    # mpmath doesn't take forever.
+
+    digamma = exception_to_nan(mpmath.digamma)
+
+    x = -np.logspace(300, -30, 100)
+    y = np.r_[-np.logspace(0, -3, 5), 0, np.logspace(-3, 0, 5)]
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    with mpmath.workdps(40):
+        dataset = [(z0, complex(digamma(z0))) for z0 in z]
+    dataset = np.asarray(dataset)
+
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check()
+
+
+@check_version(mpmath, '0.19')
+def test_digamma_boundary():
+    # Check that there isn't a jump in accuracy when we switch from
+    # using the asymptotic series to the reflection formula.
+
+    x = -np.logspace(300, -30, 100)
+    y = np.array([-6.1, -5.9, 5.9, 6.1])
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    with mpmath.workdps(30):
+        dataset = [(z0, complex(mpmath.digamma(z0))) for z0 in z]
+    dataset = np.asarray(dataset)
+
+    FuncData(sc.digamma, dataset, 0, 1, rtol=1e-13).check()
+
+
+# ------------------------------------------------------------------------------
+# gammainc
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_gammainc_boundary():
+    # Test the transition to the asymptotic series.
+    small = 20
+    a = np.linspace(0.5*small, 2*small, 50)
+    x = a.copy()
+    a, x = np.meshgrid(a, x)
+    a, x = a.flatten(), x.flatten()
+    with mpmath.workdps(100):
+        dataset = [(a0, x0, float(mpmath.gammainc(a0, b=x0, regularized=True)))
+                   for a0, x0 in zip(a, x)]
+    dataset = np.array(dataset)
+
+    FuncData(sc.gammainc, dataset, (0, 1), 2, rtol=1e-12).check()
+
+
+# ------------------------------------------------------------------------------
+# spence
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+@pytest.mark.slow
+def test_spence_circle():
+    # The trickiest region for spence is around the circle |z - 1| = 1,
+    # so test that region carefully.
+
+    def spence(z):
+        return complex(mpmath.polylog(2, 1 - z))
+
+    r = np.linspace(0.5, 1.5)
+    theta = np.linspace(0, 2*pi)
+    z = (1 + np.outer(r, np.exp(1j*theta))).flatten()
+    dataset = np.asarray([(z0, spence(z0)) for z0 in z])
+
+    FuncData(sc.spence, dataset, 0, 1, rtol=1e-14).check()
+
+
+# ------------------------------------------------------------------------------
+# sinpi and cospi
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+def test_sinpi_zeros():
+    eps = np.finfo(float).eps
+    dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    zeros = np.arange(-100, 100, 1).reshape(1, 1, -1)
+    z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
+    dataset = np.asarray([(z0, complex(mpmath.sinpi(z0)))
+                          for z0 in z])
+    FuncData(_sinpi, dataset, 0, 1, rtol=2*eps).check()
+
+
+@check_version(mpmath, '0.19')
+def test_cospi_zeros():
+    eps = np.finfo(float).eps
+    dx = np.r_[-np.logspace(0, -13, 3), 0, np.logspace(-13, 0, 3)]
+    dy = dx.copy()
+    dx, dy = np.meshgrid(dx, dy)
+    dz = dx + 1j*dy
+    zeros = (np.arange(-100, 100, 1) + 0.5).reshape(1, 1, -1)
+    z = (zeros + np.dstack((dz,)*zeros.size)).flatten()
+    dataset = np.asarray([(z0, complex(mpmath.cospi(z0)))
+                          for z0 in z])
+
+    FuncData(_cospi, dataset, 0, 1, rtol=2*eps).check()
+
+
+# ------------------------------------------------------------------------------
+# ellipj
+# ------------------------------------------------------------------------------
+
+@check_version(mpmath, '0.19')
+def test_dn_quarter_period():
+    def dn(u, m):
+        return sc.ellipj(u, m)[2]
+
+    def mpmath_dn(u, m):
+        return float(mpmath.ellipfun("dn", u=u, m=m))
+
+    m = np.linspace(0, 1, 20)
+    du = np.r_[-np.logspace(-1, -15, 10), 0, np.logspace(-15, -1, 10)]
+    dataset = []
+    for m0 in m:
+        u0 = float(mpmath.ellipk(m0))
+        for du0 in du:
+            p = u0 + du0
+            dataset.append((p, m0, mpmath_dn(p, m0)))
+    dataset = np.asarray(dataset)
+
+    FuncData(dn, dataset, (0, 1), 2, rtol=1e-10).check()
+
+
+# ------------------------------------------------------------------------------
+# Wright Omega
+# ------------------------------------------------------------------------------
+
+def _mpmath_wrightomega(z, dps):
+    with mpmath.workdps(dps):
+        z = mpmath.mpc(z)
+        unwind = mpmath.ceil((z.imag - mpmath.pi)/(2*mpmath.pi))
+        res = mpmath.lambertw(mpmath.exp(z), unwind)
+    return res
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_wrightomega_branch():
+    x = -np.logspace(10, 0, 25)
+    picut_above = [np.nextafter(np.pi, np.inf)]
+    picut_below = [np.nextafter(np.pi, -np.inf)]
+    npicut_above = [np.nextafter(-np.pi, np.inf)]
+    npicut_below = [np.nextafter(-np.pi, -np.inf)]
+    for i in range(50):
+        picut_above.append(np.nextafter(picut_above[-1], np.inf))
+        picut_below.append(np.nextafter(picut_below[-1], -np.inf))
+        npicut_above.append(np.nextafter(npicut_above[-1], np.inf))
+        npicut_below.append(np.nextafter(npicut_below[-1], -np.inf))
+    y = np.hstack((picut_above, picut_below, npicut_above, npicut_below))
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
+                          for z0 in z])
+
+    FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-8).check()
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_wrightomega_region1():
+    # This region gets less coverage in the TestSystematic test
+    x = np.linspace(-2, 1)
+    y = np.linspace(1, 2*np.pi)
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
+                          for z0 in z])
+
+    FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check()
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_wrightomega_region2():
+    # This region gets less coverage in the TestSystematic test
+    x = np.linspace(-2, 1)
+    y = np.linspace(-2*np.pi, -1)
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(_mpmath_wrightomega(z0, 25)))
+                          for z0 in z])
+
+    FuncData(sc.wrightomega, dataset, 0, 1, rtol=1e-15).check()
+
+
+# ------------------------------------------------------------------------------
+# lambertw
+# ------------------------------------------------------------------------------
+
+@pytest.mark.slow
+@check_version(mpmath, '0.19')
+def test_lambertw_smallz():
+    x, y = np.linspace(-1, 1, 25), np.linspace(-1, 1, 25)
+    x, y = np.meshgrid(x, y)
+    z = (x + 1j*y).flatten()
+
+    dataset = np.asarray([(z0, complex(mpmath.lambertw(z0)))
+                          for z0 in z])
+
+    FuncData(sc.lambertw, dataset, 0, 1, rtol=1e-13).check()
+
+
+# ------------------------------------------------------------------------------
+# Systematic tests
+# ------------------------------------------------------------------------------
+
+# The functions lpn, lpmn, clpmn, and sph_harm appearing below are
+# deprecated in favor of legendre_p_all, assoc_legendre_p_all,
+# assoc_legendre_p_all (assoc_legendre_p_all covers lpmn and clpmn),
+# and sph_harm_y respectively. The deprecated functions listed above are
+# implemented as shims around their respective replacements. The replacements
+# are tested separately, but tests for the deprecated functions remain to
+# verify the correctness of the shims.
+
+HYPERKW = dict(maxprec=200, maxterms=200)
+
+
+@pytest.mark.slow
+@check_version(mpmath, '0.17')
+class TestSystematic:
+
+    def test_airyai(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[0],
+                            mpmath.airyai,
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[0],
+                            mpmath.airyai,
+                            [Arg(-1e3, 1e3)])
+
+    def test_airyai_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[0],
+                            mpmath.airyai,
+                            [ComplexArg()])
+
+    def test_airyai_prime(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
+                            mpmath.airyai(z, derivative=1),
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
+                            mpmath.airyai(z, derivative=1),
+                            [Arg(-1e3, 1e3)])
+
+    def test_airyai_prime_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[1], lambda z:
+                            mpmath.airyai(z, derivative=1),
+                            [ComplexArg()])
+
+    def test_airybi(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
+                            mpmath.airybi(z),
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
+                            mpmath.airybi(z),
+                            [Arg(-1e3, 1e3)])
+
+    def test_airybi_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[2], lambda z:
+                            mpmath.airybi(z),
+                            [ComplexArg()])
+
+    def test_airybi_prime(self):
+        # oscillating function, limit range
+        assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
+                            mpmath.airybi(z, derivative=1),
+                            [Arg(-1e8, 1e8)],
+                            rtol=1e-5)
+        assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
+                            mpmath.airybi(z, derivative=1),
+                            [Arg(-1e3, 1e3)])
+
+    def test_airybi_prime_complex(self):
+        assert_mpmath_equal(lambda z: sc.airy(z)[3], lambda z:
+                            mpmath.airybi(z, derivative=1),
+                            [ComplexArg()])
+
+    def test_bei(self):
+        assert_mpmath_equal(sc.bei,
+                            exception_to_nan(lambda z: mpmath.bei(0, z, **HYPERKW)),
+                            [Arg(-1e3, 1e3)])
+
+    def test_ber(self):
+        assert_mpmath_equal(sc.ber,
+                            exception_to_nan(lambda z: mpmath.ber(0, z, **HYPERKW)),
+                            [Arg(-1e3, 1e3)])
+
+    def test_bernoulli(self):
+        assert_mpmath_equal(lambda n: sc.bernoulli(int(n))[int(n)],
+                            lambda n: float(mpmath.bernoulli(int(n))),
+                            [IntArg(0, 13000)],
+                            rtol=1e-9, n=13000)
+
+    def test_besseli(self):
+        assert_mpmath_equal(
+            sc.iv,
+            exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), Arg()],
+            atol=1e-270,
+        )
+
+    def test_besseli_complex(self):
+        assert_mpmath_equal(
+            lambda v, z: sc.iv(v.real, z),
+            exception_to_nan(lambda v, z: mpmath.besseli(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), ComplexArg()],
+        )
+
+    def test_besselj(self):
+        assert_mpmath_equal(
+            sc.jv,
+            exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), Arg(-1e3, 1e3)],
+            ignore_inf_sign=True,
+        )
+
+        # loss of precision at large arguments due to oscillation
+        assert_mpmath_equal(
+            sc.jv,
+            exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), Arg(-1e8, 1e8)],
+            ignore_inf_sign=True,
+            rtol=1e-5,
+        )
+
+    def test_besselj_complex(self):
+        assert_mpmath_equal(
+            lambda v, z: sc.jv(v.real, z),
+            exception_to_nan(lambda v, z: mpmath.besselj(v, z, **HYPERKW)),
+            [Arg(), ComplexArg()]
+        )
+
+    def test_besselk(self):
+        assert_mpmath_equal(
+            sc.kv,
+            mpmath.besselk,
+            [Arg(-200, 200), Arg(0, np.inf)],
+            nan_ok=False,
+            rtol=1e-12,
+        )
+
+    def test_besselk_int(self):
+        assert_mpmath_equal(
+            sc.kn,
+            mpmath.besselk,
+            [IntArg(-200, 200), Arg(0, np.inf)],
+            nan_ok=False,
+            rtol=1e-12,
+        )
+
+    def test_besselk_complex(self):
+        assert_mpmath_equal(
+            lambda v, z: sc.kv(v.real, z),
+            exception_to_nan(lambda v, z: mpmath.besselk(v, z, **HYPERKW)),
+            [Arg(-1e100, 1e100), ComplexArg()],
+        )
+
+    def test_bessely(self):
+        def mpbessely(v, x):
+            r = float(mpmath.bessely(v, x, **HYPERKW))
+            if abs(r) > 1e305:
+                # overflowing to inf a bit earlier is OK
+                r = np.inf * np.sign(r)
+            if abs(r) == 0 and x == 0:
+                # invalid result from mpmath, point x=0 is a divergence
+                return np.nan
+            return r
+        assert_mpmath_equal(
+            sc.yv,
+            exception_to_nan(mpbessely),
+            [Arg(-1e100, 1e100), Arg(-1e8, 1e8)],
+            n=5000,
+        )
+
+    def test_bessely_complex(self):
+        def mpbessely(v, x):
+            r = complex(mpmath.bessely(v, x, **HYPERKW))
+            if abs(r) > 1e305:
+                # overflowing to inf a bit earlier is OK
+                with np.errstate(invalid='ignore'):
+                    r = np.inf * np.sign(r)
+            return r
+        assert_mpmath_equal(
+            lambda v, z: sc.yv(v.real, z),
+            exception_to_nan(mpbessely),
+            [Arg(), ComplexArg()],
+            n=15000,
+        )
+
+    def test_bessely_int(self):
+        def mpbessely(v, x):
+            r = float(mpmath.bessely(v, x))
+            if abs(r) == 0 and x == 0:
+                # invalid result from mpmath, point x=0 is a divergence
+                return np.nan
+            return r
+        assert_mpmath_equal(
+            lambda v, z: sc.yn(int(v), z),
+            exception_to_nan(mpbessely),
+            [IntArg(-1000, 1000), Arg(-1e8, 1e8)],
+        )
+
+    def test_beta(self):
+        bad_points = []
+
+        def beta(a, b, nonzero=False):
+            if a < -1e12 or b < -1e12:
+                # Function is defined here only at integers, but due
+                # to loss of precision this is numerically
+                # ill-defined. Don't compare values here.
+                return np.nan
+            if (a < 0 or b < 0) and (abs(float(a + b)) % 1) == 0:
+                # close to a zero of the function: mpmath and scipy
+                # will not round here the same, so the test needs to be
+                # run with an absolute tolerance
+                if nonzero:
+                    bad_points.append((float(a), float(b)))
+                    return np.nan
+            return mpmath.beta(a, b)
+
+        assert_mpmath_equal(
+            sc.beta,
+            lambda a, b: beta(a, b, nonzero=True),
+            [Arg(), Arg()],
+            dps=400,
+            ignore_inf_sign=True,
+        )
+
+        assert_mpmath_equal(
+            sc.beta,
+            beta,
+            np.array(bad_points),
+            dps=400,
+            ignore_inf_sign=True,
+            atol=1e-11,
+        )
+
+    def test_betainc(self):
+        assert_mpmath_equal(
+            sc.betainc,
+            time_limited()(
+                exception_to_nan(
+                    lambda a, b, x: mpmath.betainc(a, b, 0, x, regularized=True)
+                )
+            ),
+            [Arg(), Arg(), Arg()],
+        )
+
+    def test_betaincc(self):
+        assert_mpmath_equal(
+            sc.betaincc,
+            time_limited()(
+                exception_to_nan(
+                    lambda a, b, x: mpmath.betainc(a, b, x, 1, regularized=True)
+                )
+            ),
+            [Arg(), Arg(), Arg()],
+            dps=400,
+        )
+
+    def test_binom(self):
+        bad_points = []
+
+        def binomial(n, k, nonzero=False):
+            if abs(k) > 1e8*(abs(n) + 1):
+                # The binomial is rapidly oscillating in this region,
+                # and the function is numerically ill-defined. Don't
+                # compare values here.
+                return np.nan
+            if n < k and abs(float(n-k) - np.round(float(n-k))) < 1e-15:
+                # close to a zero of the function: mpmath and scipy
+                # will not round here the same, so the test needs to be
+                # run with an absolute tolerance
+                if nonzero:
+                    bad_points.append((float(n), float(k)))
+                    return np.nan
+            return mpmath.binomial(n, k)
+
+        assert_mpmath_equal(
+            sc.binom,
+            lambda n, k: binomial(n, k, nonzero=True),
+            [Arg(), Arg()],
+            dps=400,
+        )
+
+        assert_mpmath_equal(
+            sc.binom,
+            binomial,
+            np.array(bad_points),
+            dps=400,
+            atol=1e-14,
+        )
+
+    def test_chebyt_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_chebyt(int(n), x),
+            exception_to_nan(lambda n, x: mpmath.chebyt(n, x, **HYPERKW)),
+            [IntArg(), Arg()],
+            dps=50,
+        )
+
+    @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate")
+    def test_chebyt(self):
+        assert_mpmath_equal(
+            sc.eval_chebyt,
+            lambda n, x: time_limited()(
+                exception_to_nan(mpmath.chebyt)
+            )(n, x, **HYPERKW),
+            [Arg(-101, 101), Arg()],
+            n=10000,
+        )
+
+    def test_chebyu_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_chebyu(int(n), x),
+            exception_to_nan(lambda n, x: mpmath.chebyu(n, x, **HYPERKW)),
+            [IntArg(), Arg()],
+            dps=50,
+        )
+
+    @pytest.mark.xfail(run=False, reason="some cases in hyp2f1 not fully accurate")
+    def test_chebyu(self):
+        assert_mpmath_equal(
+            sc.eval_chebyu,
+            lambda n, x: time_limited()(
+                exception_to_nan(mpmath.chebyu)
+            )(n, x, **HYPERKW),
+            [Arg(-101, 101), Arg()],
+        )
+
+    def test_chi(self):
+        def chi(x):
+            return sc.shichi(x)[1]
+        assert_mpmath_equal(chi, mpmath.chi, [Arg()])
+        # check asymptotic series cross-over
+        assert_mpmath_equal(chi, mpmath.chi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])])
+
+    def test_chi_complex(self):
+        def chi(z):
+            return sc.shichi(z)[1]
+        # chi oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            chi,
+            mpmath.chi,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-12,
+        )
+
+    def test_ci(self):
+        def ci(x):
+            return sc.sici(x)[1]
+        # oscillating function: limit range
+        assert_mpmath_equal(ci, mpmath.ci, [Arg(-1e8, 1e8)])
+
+    def test_ci_complex(self):
+        def ci(z):
+            return sc.sici(z)[1]
+        # ci oscillates as Re[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            ci,
+            mpmath.ci,
+            [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))],
+            rtol=1e-8,
+        )
+
+    def test_cospi(self):
+        eps = np.finfo(float).eps
+        assert_mpmath_equal(_cospi, mpmath.cospi, [Arg()], nan_ok=False, rtol=2*eps)
+
+    def test_cospi_complex(self):
+        assert_mpmath_equal(
+            _cospi,
+            mpmath.cospi,
+            [ComplexArg()],
+            nan_ok=False,
+            rtol=1e-13,
+        )
+
+    def test_digamma(self):
+        assert_mpmath_equal(
+            sc.digamma,
+            exception_to_nan(mpmath.digamma),
+            [Arg()],
+            rtol=1e-12,
+            dps=50,
+        )
+
+    def test_digamma_complex(self):
+        # Test on a cut plane because mpmath will hang. See
+        # test_digamma_negreal for tests on the negative real axis.
+        def param_filter(z):
+            return np.where((z.real < 0) & (np.abs(z.imag) < 1.12), False, True)
+
+        assert_mpmath_equal(
+            sc.digamma,
+            exception_to_nan(mpmath.digamma),
+            [ComplexArg()],
+            rtol=1e-13,
+            dps=40,
+            param_filter=param_filter
+        )
+
+    def test_e1(self):
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            [Arg()],
+            rtol=1e-14,
+        )
+
+    def test_e1_complex(self):
+        # E_1 oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-11,
+        )
+
+        # Check cross-over region
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            (np.linspace(-50, 50, 171)[:, None]
+             + np.r_[0, np.logspace(-3, 2, 61), -np.logspace(-3, 2, 11)]*1j).ravel(),
+            rtol=1e-11,
+        )
+        assert_mpmath_equal(
+            sc.exp1,
+            mpmath.e1,
+            (np.linspace(-50, -35, 10000) + 0j),
+            rtol=1e-11,
+        )
+
+    def test_exprel(self):
+        assert_mpmath_equal(
+            sc.exprel,
+            lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'),
+            [Arg(a=-np.log(np.finfo(np.float64).max),
+                 b=np.log(np.finfo(np.float64).max))],
+        )
+        assert_mpmath_equal(
+            sc.exprel,
+            lambda x: mpmath.expm1(x)/x if x != 0 else mpmath.mpf('1.0'),
+            np.array([1e-12, 1e-24, 0, 1e12, 1e24, np.inf]),
+            rtol=1e-11,
+        )
+        assert_(np.isinf(sc.exprel(np.inf)))
+        assert_(sc.exprel(-np.inf) == 0)
+
+    def test_expm1_complex(self):
+        # Oscillates as a function of Im[z], so limit range to avoid loss of precision
+        assert_mpmath_equal(
+            sc.expm1,
+            mpmath.expm1,
+            [ComplexArg(complex(-np.inf, -1e7), complex(np.inf, 1e7))],
+        )
+
+    def test_log1p_complex(self):
+        assert_mpmath_equal(
+            sc.log1p,
+            lambda x: mpmath.log(x+1),
+            [ComplexArg()],
+            dps=60,
+        )
+
+    def test_log1pmx(self):
+        assert_mpmath_equal(
+            _log1pmx,
+            lambda x: mpmath.log(x + 1) - x,
+            [Arg()],
+            dps=60,
+            rtol=1e-14,
+        )
+
+    def test_ei(self):
+        assert_mpmath_equal(sc.expi, mpmath.ei, [Arg()], rtol=1e-11)
+
+    def test_ei_complex(self):
+        # Ei oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            sc.expi,
+            mpmath.ei,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-9,
+        )
+
+    def test_ellipe(self):
+        assert_mpmath_equal(sc.ellipe, mpmath.ellipe, [Arg(b=1.0)])
+
+    def test_ellipeinc(self):
+        assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(-1e3, 1e3), Arg(b=1.0)])
+
+    def test_ellipeinc_largephi(self):
+        assert_mpmath_equal(sc.ellipeinc, mpmath.ellipe, [Arg(), Arg()])
+
+    def test_ellipf(self):
+        assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(-1e3, 1e3), Arg()])
+
+    def test_ellipf_largephi(self):
+        assert_mpmath_equal(sc.ellipkinc, mpmath.ellipf, [Arg(), Arg()])
+
+    def test_ellipk(self):
+        assert_mpmath_equal(sc.ellipk, mpmath.ellipk, [Arg(b=1.0)])
+        assert_mpmath_equal(
+            sc.ellipkm1,
+            lambda m: mpmath.ellipk(1 - m),
+            [Arg(a=0.0)],
+            dps=400,
+        )
+
+    def test_ellipkinc(self):
+        def ellipkinc(phi, m):
+            return mpmath.ellippi(0, phi, m)
+        assert_mpmath_equal(
+            sc.ellipkinc,
+            ellipkinc,
+            [Arg(-1e3, 1e3), Arg(b=1.0)],
+            ignore_inf_sign=True,
+        )
+
+    def test_ellipkinc_largephi(self):
+        def ellipkinc(phi, m):
+            return mpmath.ellippi(0, phi, m)
+        assert_mpmath_equal(
+            sc.ellipkinc,
+            ellipkinc,
+            [Arg(), Arg(b=1.0)],
+            ignore_inf_sign=True,
+        )
+
+    def test_ellipfun_sn(self):
+        def sn(u, m):
+            # mpmath doesn't get the zero at u = 0--fix that
+            if u == 0:
+                return 0
+            else:
+                return mpmath.ellipfun("sn", u=u, m=m)
+
+        # Oscillating function --- limit range of first argument; the
+        # loss of precision there is an expected numerical feature
+        # rather than an actual bug
+        assert_mpmath_equal(
+            lambda u, m: sc.ellipj(u, m)[0],
+            sn,
+            [Arg(-1e6, 1e6), Arg(a=0, b=1)],
+            rtol=1e-8,
+        )
+
+    def test_ellipfun_cn(self):
+        # see comment in ellipfun_sn
+        assert_mpmath_equal(
+            lambda u, m: sc.ellipj(u, m)[1],
+            lambda u, m: mpmath.ellipfun("cn", u=u, m=m),
+            [Arg(-1e6, 1e6), Arg(a=0, b=1)],
+            rtol=1e-8,
+        )
+
+    def test_ellipfun_dn(self):
+        # see comment in ellipfun_sn
+        assert_mpmath_equal(
+            lambda u, m: sc.ellipj(u, m)[2],
+            lambda u, m: mpmath.ellipfun("dn", u=u, m=m),
+            [Arg(-1e6, 1e6), Arg(a=0, b=1)],
+            rtol=1e-8,
+        )
+
+    def test_erf(self):
+        assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [Arg()])
+
+    def test_erf_complex(self):
+        assert_mpmath_equal(sc.erf, lambda z: mpmath.erf(z), [ComplexArg()], n=200)
+
+    def test_erfc(self):
+        assert_mpmath_equal(
+            sc.erfc,
+            exception_to_nan(lambda z: mpmath.erfc(z)),
+            [Arg()],
+            rtol=1e-13,
+        )
+
+    def test_erfc_complex(self):
+        assert_mpmath_equal(
+            sc.erfc,
+            exception_to_nan(lambda z: mpmath.erfc(z)),
+            [ComplexArg()],
+            n=200,
+        )
+
+    def test_erfi(self):
+        assert_mpmath_equal(sc.erfi, mpmath.erfi, [Arg()], n=200)
+
+    def test_erfi_complex(self):
+        assert_mpmath_equal(sc.erfi, mpmath.erfi, [ComplexArg()], n=200)
+
+    def test_ndtr(self):
+        assert_mpmath_equal(
+            sc.ndtr,
+            exception_to_nan(lambda z: mpmath.ncdf(z)),
+            [Arg()],
+            n=200,
+        )
+
+    def test_ndtr_complex(self):
+        assert_mpmath_equal(
+            sc.ndtr,
+            lambda z: mpmath.erfc(-z/np.sqrt(2.))/2.,
+            [ComplexArg(a=complex(-10000, -10000), b=complex(10000, 10000))],
+            n=400,
+        )
+
+    def test_log_ndtr(self):
+        assert_mpmath_equal(
+            sc.log_ndtr,
+            exception_to_nan(lambda z: mpmath.log(mpmath.ncdf(z))),
+            [Arg()], n=600, dps=300, rtol=1e-13,
+        )
+
+    def test_log_ndtr_complex(self):
+        assert_mpmath_equal(
+            sc.log_ndtr,
+            exception_to_nan(lambda z: mpmath.log(mpmath.erfc(-z/np.sqrt(2.))/2.)),
+            [ComplexArg(a=complex(-10000, -100), b=complex(10000, 100))],
+            n=200, dps=300,
+        )
+
+    def test_eulernum(self):
+        assert_mpmath_equal(
+            lambda n: sc.euler(n)[-1],
+            mpmath.eulernum,
+            [IntArg(1, 10000)],
+            n=10000,
+        )
+
+    def test_expint(self):
+        assert_mpmath_equal(
+            sc.expn,
+            mpmath.expint,
+            [IntArg(0, 200), Arg(0, np.inf)],
+            rtol=1e-13,
+            dps=160,
+        )
+
+    def test_fresnels(self):
+        def fresnels(x):
+            return sc.fresnel(x)[0]
+        assert_mpmath_equal(fresnels, mpmath.fresnels, [Arg()])
+
+    def test_fresnelc(self):
+        def fresnelc(x):
+            return sc.fresnel(x)[1]
+        assert_mpmath_equal(fresnelc, mpmath.fresnelc, [Arg()])
+
+    def test_gamma(self):
+        assert_mpmath_equal(sc.gamma, exception_to_nan(mpmath.gamma), [Arg()])
+
+    def test_gamma_complex(self):
+        assert_mpmath_equal(
+            sc.gamma,
+            exception_to_nan(mpmath.gamma),
+            [ComplexArg()],
+            rtol=5e-13,
+        )
+
+    def test_gammainc(self):
+        # Larger arguments are tested in test_data.py:test_local
+        assert_mpmath_equal(
+            sc.gammainc,
+            lambda z, b: mpmath.gammainc(z, b=b, regularized=True),
+            [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)],
+            nan_ok=False,
+            rtol=1e-11,
+        )
+
+    def test_gammaincc(self):
+        # Larger arguments are tested in test_data.py:test_local
+        assert_mpmath_equal(
+            sc.gammaincc,
+            lambda z, a: mpmath.gammainc(z, a=a, regularized=True),
+            [Arg(0, 1e4, inclusive_a=False), Arg(0, 1e4)],
+            nan_ok=False,
+            rtol=1e-11,
+        )
+
+    def test_gammaln(self):
+        # The real part of loggamma is log(|gamma(z)|).
+        def f(z):
+            return mpmath.loggamma(z).real
+
+        assert_mpmath_equal(sc.gammaln, exception_to_nan(f), [Arg()])
+
+    @pytest.mark.xfail(run=False)
+    def test_gegenbauer(self):
+        assert_mpmath_equal(
+            sc.eval_gegenbauer,
+            exception_to_nan(mpmath.gegenbauer),
+            [Arg(-1e3, 1e3), Arg(), Arg()],
+        )
+
+    def test_gegenbauer_int(self):
+        # Redefine functions to deal with numerical + mpmath issues
+        def gegenbauer(n, a, x):
+            # Avoid overflow at large `a` (mpmath would need an even larger
+            # dps to handle this correctly, so just skip this region)
+            if abs(a) > 1e100:
+                return np.nan
+
+            # Deal with n=0, n=1 correctly; mpmath 0.17 doesn't do these
+            # always correctly
+            if n == 0:
+                r = 1.0
+            elif n == 1:
+                r = 2*a*x
+            else:
+                r = mpmath.gegenbauer(n, a, x)
+
+            # Mpmath 0.17 gives wrong results (spurious zero) in some cases, so
+            # compute the value by perturbing the result
+            if float(r) == 0 and a < -1 and float(a) == int(float(a)):
+                r = mpmath.gegenbauer(n, a + mpmath.mpf('1e-50'), x)
+                if abs(r) < mpmath.mpf('1e-50'):
+                    r = mpmath.mpf('0.0')
+
+            # Differing overflow thresholds in scipy vs. mpmath
+            if abs(r) > 1e270:
+                return np.inf
+            return r
+
+        def sc_gegenbauer(n, a, x):
+            r = sc.eval_gegenbauer(int(n), a, x)
+            # Differing overflow thresholds in scipy vs. mpmath
+            if abs(r) > 1e270:
+                return np.inf
+            return r
+        assert_mpmath_equal(
+            sc_gegenbauer,
+            exception_to_nan(gegenbauer),
+            [IntArg(0, 100), Arg(-1e9, 1e9), Arg()],
+            n=40000, dps=100, ignore_inf_sign=True, rtol=1e-6,
+        )
+
+        # Check the small-x expansion
+        assert_mpmath_equal(
+            sc_gegenbauer,
+            exception_to_nan(gegenbauer),
+            [IntArg(0, 100), Arg(), FixedArg(np.logspace(-30, -4, 30))],
+            dps=100, ignore_inf_sign=True,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_gegenbauer_complex(self):
+        assert_mpmath_equal(
+            lambda n, a, x: sc.eval_gegenbauer(int(n), a.real, x),
+            exception_to_nan(mpmath.gegenbauer),
+            [IntArg(0, 100), Arg(), ComplexArg()],
+        )
+
+    @nonfunctional_tooslow
+    def test_gegenbauer_complex_general(self):
+        assert_mpmath_equal(
+            lambda n, a, x: sc.eval_gegenbauer(n.real, a.real, x),
+            exception_to_nan(mpmath.gegenbauer),
+            [Arg(-1e3, 1e3), Arg(), ComplexArg()],
+        )
+
+    def test_hankel1(self):
+        assert_mpmath_equal(
+            sc.hankel1,
+            exception_to_nan(lambda v, x: mpmath.hankel1(v, x, **HYPERKW)),
+            [Arg(-1e20, 1e20), Arg()],
+        )
+
+    def test_hankel2(self):
+        assert_mpmath_equal(
+            sc.hankel2,
+            exception_to_nan(lambda v, x: mpmath.hankel2(v, x, **HYPERKW)),
+            [Arg(-1e20, 1e20), Arg()],
+        )
+
+    @pytest.mark.xfail(run=False, reason="issues at intermediately large orders")
+    def test_hermite(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_hermite(int(n), x),
+            exception_to_nan(mpmath.hermite),
+            [IntArg(0, 10000), Arg()],
+        )
+
+    # hurwitz: same as zeta
+
+    def test_hyp0f1(self):
+        # mpmath reports no convergence unless maxterms is large enough
+        KW = dict(maxprec=400, maxterms=1500)
+        # n=500 (non-xslow default) fails for one bad point
+        assert_mpmath_equal(
+            sc.hyp0f1,
+            lambda a, x: mpmath.hyp0f1(a, x, **KW),
+            [Arg(-1e7, 1e7), Arg(0, 1e5)],
+            n=5000,
+        )
+        # NB: The range of the second parameter ("z") is limited from below
+        # because of an overflow in the intermediate calculations. The way
+        # for fix it is to implement an asymptotic expansion for Bessel J
+        # (similar to what is implemented for Bessel I here).
+
+    def test_hyp0f1_complex(self):
+        assert_mpmath_equal(
+            lambda a, z: sc.hyp0f1(a.real, z),
+            exception_to_nan(lambda a, x: mpmath.hyp0f1(a, x, **HYPERKW)),
+            [Arg(-10, 10), ComplexArg(complex(-120, -120), complex(120, 120))],
+        )
+        # NB: The range of the first parameter ("v") are limited by an overflow
+        # in the intermediate calculations. Can be fixed by implementing an
+        # asymptotic expansion for Bessel functions for large order.
+
+    def test_hyp1f1(self):
+        def mpmath_hyp1f1(a, b, x):
+            try:
+                return mpmath.hyp1f1(a, b, x)
+            except ZeroDivisionError:
+                return np.inf
+
+        assert_mpmath_equal(
+            sc.hyp1f1,
+            mpmath_hyp1f1,
+            [Arg(-50, 50), Arg(1, 50, inclusive_a=False), Arg(-50, 50)],
+            n=500,
+            nan_ok=False,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_hyp1f1_complex(self):
+        assert_mpmath_equal(
+            inf_to_nan(lambda a, b, x: sc.hyp1f1(a.real, b.real, x)),
+            exception_to_nan(lambda a, b, x: mpmath.hyp1f1(a, b, x, **HYPERKW)),
+            [Arg(-1e3, 1e3), Arg(-1e3, 1e3), ComplexArg()],
+            n=2000,
+        )
+
+    @nonfunctional_tooslow
+    def test_hyp2f1_complex(self):
+        # SciPy's hyp2f1 seems to have performance and accuracy problems
+        assert_mpmath_equal(
+            lambda a, b, c, x: sc.hyp2f1(a.real, b.real, c.real, x),
+            exception_to_nan(lambda a, b, c, x: mpmath.hyp2f1(a, b, c, x, **HYPERKW)),
+            [Arg(-1e2, 1e2), Arg(-1e2, 1e2), Arg(-1e2, 1e2), ComplexArg()],
+            n=10,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_hyperu(self):
+        assert_mpmath_equal(
+            sc.hyperu,
+            exception_to_nan(lambda a, b, x: mpmath.hyperu(a, b, x, **HYPERKW)),
+            [Arg(), Arg(), Arg()],
+        )
+
+    @pytest.mark.xfail_on_32bit("mpmath issue gh-342: "
+                                "unsupported operand mpz, long for pow")
+    def test_igam_fac(self):
+        def mp_igam_fac(a, x):
+            return mpmath.power(x, a)*mpmath.exp(-x)/mpmath.gamma(a)
+
+        assert_mpmath_equal(
+            _igam_fac,
+            mp_igam_fac,
+            [Arg(0, 1e14, inclusive_a=False), Arg(0, 1e14)],
+            rtol=1e-10,
+            dps=29,
+        )
+
+    def test_j0(self):
+        # The Bessel function at large arguments is j0(x) ~ cos(x + phi)/sqrt(x)
+        # and at large arguments the phase of the cosine loses precision.
+        #
+        # This is numerically expected behavior, so we compare only up to
+        # 1e8 = 1e15 * 1e-7
+        assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e3, 1e3)])
+        assert_mpmath_equal(sc.j0, mpmath.j0, [Arg(-1e8, 1e8)], rtol=1e-5)
+
+    def test_j1(self):
+        # See comment in test_j0
+        assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e3, 1e3)])
+        assert_mpmath_equal(sc.j1, mpmath.j1, [Arg(-1e8, 1e8)], rtol=1e-5)
+
+    @pytest.mark.xfail(run=False)
+    def test_jacobi(self):
+        assert_mpmath_equal(
+            sc.eval_jacobi,
+            exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)),
+            [Arg(), Arg(), Arg(), Arg()],
+        )
+        assert_mpmath_equal(
+            lambda n, b, c, x: sc.eval_jacobi(int(n), b, c, x),
+            exception_to_nan(lambda a, b, c, x: mpmath.jacobi(a, b, c, x, **HYPERKW)),
+            [IntArg(), Arg(), Arg(), Arg()],
+        )
+
+    def test_jacobi_int(self):
+        # Redefine functions to deal with numerical + mpmath issues
+        def jacobi(n, a, b, x):
+            # Mpmath does not handle n=0 case always correctly
+            if n == 0:
+                return 1.0
+            return mpmath.jacobi(n, a, b, x)
+        assert_mpmath_equal(
+            lambda n, a, b, x: sc.eval_jacobi(int(n), a, b, x),
+            lambda n, a, b, x: exception_to_nan(jacobi)(n, a, b, x, **HYPERKW),
+            [IntArg(), Arg(), Arg(), Arg()],
+            n=20000,
+            dps=50,
+        )
+
+    def test_kei(self):
+        def kei(x):
+            if x == 0:
+                # work around mpmath issue at x=0
+                return -pi/4
+            return exception_to_nan(mpmath.kei)(0, x, **HYPERKW)
+        assert_mpmath_equal(sc.kei, kei, [Arg(-1e30, 1e30)], n=1000)
+
+    def test_ker(self):
+        assert_mpmath_equal(
+            sc.ker,
+            exception_to_nan(lambda x: mpmath.ker(0, x, **HYPERKW)),
+            [Arg(-1e30, 1e30)],
+            n=1000,
+        )
+
+    @nonfunctional_tooslow
+    def test_laguerre(self):
+        assert_mpmath_equal(
+            trace_args(sc.eval_laguerre),
+            lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW),
+            [Arg(), Arg()],
+        )
+
+    def test_laguerre_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_laguerre(int(n), x),
+            lambda n, x: exception_to_nan(mpmath.laguerre)(n, x, **HYPERKW),
+            [IntArg(), Arg()],
+            n=20000,
+        )
+
+    @pytest.mark.xfail_on_32bit("see gh-3551 for bad points")
+    def test_lambertw_real(self):
+        assert_mpmath_equal(
+            lambda x, k: sc.lambertw(x, int(k.real)),
+            lambda x, k: mpmath.lambertw(x, int(k.real)),
+            [ComplexArg(-np.inf, np.inf), IntArg(0, 10)],
+            rtol=1e-13, nan_ok=False,
+        )
+
+    def test_lanczos_sum_expg_scaled(self):
+        maxgamma = 171.624376956302725
+        e = np.exp(1)
+        g = 6.024680040776729583740234375
+
+        def gamma(x):
+            with np.errstate(over='ignore'):
+                fac = ((x + g - 0.5)/e)**(x - 0.5)
+                if fac != np.inf:
+                    res = fac*_lanczos_sum_expg_scaled(x)
+                else:
+                    fac = ((x + g - 0.5)/e)**(0.5*(x - 0.5))
+                    res = fac*_lanczos_sum_expg_scaled(x)
+                    res *= fac
+            return res
+
+        assert_mpmath_equal(
+            gamma,
+            mpmath.gamma,
+            [Arg(0, maxgamma, inclusive_a=False)],
+            rtol=1e-13,
+        )
+
+    @nonfunctional_tooslow
+    def test_legendre(self):
+        assert_mpmath_equal(sc.eval_legendre, mpmath.legendre, [Arg(), Arg()])
+
+    def test_legendre_int(self):
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_legendre(int(n), x),
+            lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW),
+            [IntArg(), Arg()],
+            n=20000,
+        )
+
+        # Check the small-x expansion
+        assert_mpmath_equal(
+            lambda n, x: sc.eval_legendre(int(n), x),
+            lambda n, x: exception_to_nan(mpmath.legendre)(n, x, **HYPERKW),
+            [IntArg(), FixedArg(np.logspace(-30, -4, 20))],
+        )
+
+    def test_legenp(self):
+        def lpnm(n, m, z):
+            try:
+                with suppress_warnings() as sup:
+                    sup.filter(category=DeprecationWarning)
+                    v = sc.lpmn(m, n, z)[0][-1,-1]
+            except ValueError:
+                return np.nan
+            if abs(v) > 1e306:
+                # harmonize overflow to inf
+                v = np.inf * np.sign(v.real)
+            return v
+
+        def lpnm_2(n, m, z):
+            v = sc.lpmv(m, n, z)
+            if abs(v) > 1e306:
+                # harmonize overflow to inf
+                v = np.inf * np.sign(v.real)
+            return v
+
+        def legenp(n, m, z):
+            if (z == 1 or z == -1) and int(n) == n:
+                # Special case (mpmath may give inf, we take the limit by
+                # continuity)
+                if m == 0:
+                    if n < 0:
+                        n = -n - 1
+                    return mpmath.power(mpmath.sign(z), n)
+                else:
+                    return 0
+
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+
+            typ = 2 if abs(z) <= 1 else 3
+            v = exception_to_nan(mpmath.legenp)(n, m, z, type=typ)
+
+            if abs(v) > 1e306:
+                # harmonize overflow to inf
+                v = mpmath.inf * mpmath.sign(v.real)
+
+            return v
+
+        assert_mpmath_equal(lpnm, legenp, [IntArg(-100, 100), IntArg(-100, 100), Arg()])
+
+        assert_mpmath_equal(
+            lpnm_2,
+            legenp,
+            [IntArg(-100, 100), Arg(-100, 100), Arg(-1, 1)],
+            atol=1e-10,
+        )
+
+    def test_legenp_complex_2(self):
+        def clpnm(n, m, z):
+            try:
+                with suppress_warnings() as sup:
+                    sup.filter(category=DeprecationWarning)
+                    return sc.clpmn(m.real, n.real, z, type=2)[0][-1,-1]
+            except ValueError:
+                return np.nan
+
+        def legenp(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=2)
+
+        # mpmath is quite slow here
+        x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3])
+        y = np.array([-1e3, -0.5, 0.5, 1.3])
+        z = (x[:,None] + 1j*y[None,:]).ravel()
+
+        assert_mpmath_equal(
+            clpnm,
+            legenp,
+            [FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg(z)],
+            rtol=1e-6,
+            n=500,
+        )
+
+    def test_legenp_complex_3(self):
+        def clpnm(n, m, z):
+            try:
+                with suppress_warnings() as sup:
+                    sup.filter(category=DeprecationWarning)
+                    return sc.clpmn(m.real, n.real, z, type=3)[0][-1,-1]
+            except ValueError:
+                return np.nan
+
+        def legenp(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenp)(int(n.real), int(m.real), z, type=3)
+
+        # mpmath is quite slow here
+        x = np.array([-2, -0.99, -0.5, 0, 1e-5, 0.5, 0.99, 20, 2e3])
+        y = np.array([-1e3, -0.5, 0.5, 1.3])
+        z = (x[:,None] + 1j*y[None,:]).ravel()
+
+        assert_mpmath_equal(
+            clpnm,
+            legenp,
+            [FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg([-2, -1, 0, 1, 2, 10]),
+             FixedArg(z)],
+            rtol=1e-6,
+            n=500,
+        )
+
+    @pytest.mark.xfail(run=False, reason="apparently picks wrong function at |z| > 1")
+    def test_legenq(self):
+        def lqnm(n, m, z):
+            return sc.lqmn(m, n, z)[0][-1,-1]
+
+        def legenq(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenq)(n, m, z, type=2)
+
+        assert_mpmath_equal(
+            lqnm,
+            legenq,
+            [IntArg(0, 100), IntArg(0, 100), Arg()],
+        )
+
+    @nonfunctional_tooslow
+    def test_legenq_complex(self):
+        def lqnm(n, m, z):
+            return sc.lqmn(int(m.real), int(n.real), z)[0][-1,-1]
+
+        def legenq(n, m, z):
+            if abs(z) < 1e-15:
+                # mpmath has bad performance here
+                return np.nan
+            return exception_to_nan(mpmath.legenq)(int(n.real), int(m.real), z, type=2)
+
+        assert_mpmath_equal(
+            lqnm,
+            legenq,
+            [IntArg(0, 100), IntArg(0, 100), ComplexArg()],
+            n=100,
+        )
+
+    def test_lgam1p(self):
+        def param_filter(x):
+            # Filter the poles
+            return np.where((np.floor(x) == x) & (x <= 0), False, True)
+
+        def mp_lgam1p(z):
+            # The real part of loggamma is log(|gamma(z)|)
+            return mpmath.loggamma(1 + z).real
+
+        assert_mpmath_equal(
+            _lgam1p,
+            mp_lgam1p,
+            [Arg()],
+            rtol=1e-13,
+            dps=100,
+            param_filter=param_filter,
+        )
+
+    def test_loggamma(self):
+        def mpmath_loggamma(z):
+            try:
+                res = mpmath.loggamma(z)
+            except ValueError:
+                res = complex(np.nan, np.nan)
+            return res
+
+        assert_mpmath_equal(
+            sc.loggamma,
+            mpmath_loggamma,
+            [ComplexArg()],
+            nan_ok=False,
+            distinguish_nan_and_inf=False,
+            rtol=5e-14,
+        )
+
+    @pytest.mark.xfail(run=False)
+    def test_pcfd(self):
+        def pcfd(v, x):
+            return sc.pbdv(v, x)[0]
+        assert_mpmath_equal(
+            pcfd,
+            exception_to_nan(lambda v, x: mpmath.pcfd(v, x, **HYPERKW)),
+            [Arg(), Arg()],
+        )
+
+    @pytest.mark.xfail(run=False, reason="it's not the same as the mpmath function --- "
+                                         "maybe different definition?")
+    def test_pcfv(self):
+        def pcfv(v, x):
+            return sc.pbvv(v, x)[0]
+        assert_mpmath_equal(
+            pcfv,
+            lambda v, x: time_limited()(exception_to_nan(mpmath.pcfv))(v, x, **HYPERKW),
+            [Arg(), Arg()],
+            n=1000,
+        )
+
+    def test_pcfw(self):
+        def pcfw(a, x):
+            return sc.pbwa(a, x)[0]
+
+        def dpcfw(a, x):
+            return sc.pbwa(a, x)[1]
+
+        def mpmath_dpcfw(a, x):
+            return mpmath.diff(mpmath.pcfw, (a, x), (0, 1))
+
+        # The Zhang and Jin implementation only uses Taylor series and
+        # is thus accurate in only a very small range.
+        assert_mpmath_equal(
+            pcfw,
+            mpmath.pcfw,
+            [Arg(-5, 5), Arg(-5, 5)],
+            rtol=2e-8,
+            n=100,
+        )
+
+        assert_mpmath_equal(
+            dpcfw,
+            mpmath_dpcfw,
+            [Arg(-5, 5), Arg(-5, 5)],
+            rtol=2e-9,
+            n=100,
+        )
+
+    @pytest.mark.xfail(run=False,
+                       reason="issues at large arguments (atol OK, rtol not) "
+                              "and = _pep440.Version("1.0.0"):
+            # no workarounds needed
+            mppoch = mpmath.rf
+        else:
+            def mppoch(a, m):
+                # deal with cases where the result in double precision
+                # hits exactly a non-positive integer, but the
+                # corresponding extended-precision mpf floats don't
+                if float(a + m) == int(a + m) and float(a + m) <= 0:
+                    a = mpmath.mpf(a)
+                    m = int(a + m) - a
+                return mpmath.rf(a, m)
+
+        assert_mpmath_equal(sc.poch, mppoch, [Arg(), Arg()], dps=400)
+
+    def test_sinpi(self):
+        eps = np.finfo(float).eps
+        assert_mpmath_equal(
+            _sinpi,
+            mpmath.sinpi,
+            [Arg()],
+            nan_ok=False,
+            rtol=2*eps,
+        )
+
+    def test_sinpi_complex(self):
+        assert_mpmath_equal(
+            _sinpi,
+            mpmath.sinpi,
+            [ComplexArg()],
+            nan_ok=False,
+            rtol=2e-14,
+        )
+
+    def test_shi(self):
+        def shi(x):
+            return sc.shichi(x)[0]
+        assert_mpmath_equal(shi, mpmath.shi, [Arg()])
+        # check asymptotic series cross-over
+        assert_mpmath_equal(shi, mpmath.shi, [FixedArg([88 - 1e-9, 88, 88 + 1e-9])])
+
+    def test_shi_complex(self):
+        def shi(z):
+            return sc.shichi(z)[0]
+        # shi oscillates as Im[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            shi,
+            mpmath.shi,
+            [ComplexArg(complex(-np.inf, -1e8), complex(np.inf, 1e8))],
+            rtol=1e-12,
+        )
+
+    def test_si(self):
+        def si(x):
+            return sc.sici(x)[0]
+        assert_mpmath_equal(si, mpmath.si, [Arg()])
+
+    def test_si_complex(self):
+        def si(z):
+            return sc.sici(z)[0]
+        # si oscillates as Re[z] -> +- inf, so limit range
+        assert_mpmath_equal(
+            si,
+            mpmath.si,
+            [ComplexArg(complex(-1e8, -np.inf), complex(1e8, np.inf))],
+            rtol=1e-12,
+        )
+
+    def test_spence(self):
+        # mpmath uses a different convention for the dilogarithm
+        def dilog(x):
+            return mpmath.polylog(2, 1 - x)
+        # Spence has a branch cut on the negative real axis
+        assert_mpmath_equal(
+            sc.spence,
+            exception_to_nan(dilog),
+            [Arg(0, np.inf)],
+            rtol=1e-14,
+        )
+
+    def test_spence_complex(self):
+        def dilog(z):
+            return mpmath.polylog(2, 1 - z)
+        assert_mpmath_equal(
+            sc.spence,
+            exception_to_nan(dilog),
+            [ComplexArg()],
+            rtol=1e-14,
+        )
+
+    def test_spherharm(self):
+        def spherharm(l, m, theta, phi):
+            if m > l:
+                return np.nan
+            with suppress_warnings() as sup:
+                sup.filter(category=DeprecationWarning)
+                return sc.sph_harm(m, l, phi, theta)
+        assert_mpmath_equal(
+            spherharm,
+            mpmath.spherharm,
+            [IntArg(0, 100), IntArg(0, 100), Arg(a=0, b=pi), Arg(a=0, b=2*pi)],
+            atol=1e-8,
+            n=6000,
+            dps=150,
+        )
+
+    def test_struveh(self):
+        assert_mpmath_equal(
+            sc.struve,
+            exception_to_nan(mpmath.struveh),
+            [Arg(-1e4, 1e4), Arg(0, 1e4)],
+            rtol=5e-10,
+        )
+
+    def test_struvel(self):
+        def mp_struvel(v, z):
+            if v < 0 and z < -v and abs(v) > 1000:
+                # larger DPS needed for correct results
+                old_dps = mpmath.mp.dps
+                try:
+                    mpmath.mp.dps = 500
+                    return mpmath.struvel(v, z)
+                finally:
+                    mpmath.mp.dps = old_dps
+            return mpmath.struvel(v, z)
+
+        assert_mpmath_equal(
+            sc.modstruve,
+            exception_to_nan(mp_struvel),
+            [Arg(-1e4, 1e4), Arg(0, 1e4)],
+            rtol=5e-10,
+            ignore_inf_sign=True,
+        )
+
+    def test_wrightomega_real(self):
+        def mpmath_wrightomega_real(x):
+            return mpmath.lambertw(mpmath.exp(x), mpmath.mpf('-0.5'))
+
+        # For x < -1000 the Wright Omega function is just 0 to double
+        # precision, and for x > 1e21 it is just x to double
+        # precision.
+        assert_mpmath_equal(
+            sc.wrightomega,
+            mpmath_wrightomega_real,
+            [Arg(-1000, 1e21)],
+            rtol=5e-15,
+            atol=0,
+            nan_ok=False,
+        )
+
+    def test_wrightomega(self):
+        assert_mpmath_equal(
+            sc.wrightomega,
+            lambda z: _mpmath_wrightomega(z, 25),
+            [ComplexArg()],
+            rtol=1e-14,
+            nan_ok=False,
+        )
+
+    def test_hurwitz_zeta(self):
+        assert_mpmath_equal(
+            sc.zeta,
+            exception_to_nan(mpmath.zeta),
+            [Arg(a=1, b=1e10, inclusive_a=False), Arg(a=0, inclusive_a=False)],
+        )
+
+    def test_riemann_zeta(self):
+        assert_mpmath_equal(
+            sc.zeta,
+            lambda x: mpmath.zeta(x) if x != 1 else mpmath.inf,
+            [Arg(-100, 100)],
+            nan_ok=False,
+            rtol=5e-13,
+        )
+
+    def test_zetac(self):
+        assert_mpmath_equal(
+            sc.zetac,
+            lambda x: mpmath.zeta(x) - 1 if x != 1 else mpmath.inf,
+            [Arg(-100, 100)],
+            nan_ok=False,
+            dps=45,
+            rtol=5e-13,
+        )
+
+    def test_boxcox(self):
+
+        def mp_boxcox(x, lmbda):
+            x = mpmath.mp.mpf(x)
+            lmbda = mpmath.mp.mpf(lmbda)
+            if lmbda == 0:
+                return mpmath.mp.log(x)
+            else:
+                return mpmath.mp.powm1(x, lmbda) / lmbda
+
+        assert_mpmath_equal(
+            sc.boxcox,
+            exception_to_nan(mp_boxcox),
+            [Arg(a=0, inclusive_a=False), Arg()],
+            n=200,
+            dps=60,
+            rtol=1e-13,
+        )
+
+    def test_boxcox1p(self):
+
+        def mp_boxcox1p(x, lmbda):
+            x = mpmath.mp.mpf(x)
+            lmbda = mpmath.mp.mpf(lmbda)
+            one = mpmath.mp.mpf(1)
+            if lmbda == 0:
+                return mpmath.mp.log(one + x)
+            else:
+                return mpmath.mp.powm1(one + x, lmbda) / lmbda
+
+        assert_mpmath_equal(
+            sc.boxcox1p,
+            exception_to_nan(mp_boxcox1p),
+            [Arg(a=-1, inclusive_a=False), Arg()],
+            n=200,
+            dps=60,
+            rtol=1e-13,
+        )
+
+    def test_spherical_jn(self):
+        def mp_spherical_jn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_jn(int(n), z),
+            exception_to_nan(mp_spherical_jn),
+            [IntArg(0, 200), Arg(-1e8, 1e8)],
+            dps=300,
+            # underflow of `spherical_jn` is a bit premature; see gh-21629
+            param_filter=(None, lambda z: np.abs(z) > 1e-20),
+        )
+
+    def test_spherical_jn_complex(self):
+        def mp_spherical_jn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselj(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_jn(int(n.real), z),
+            exception_to_nan(mp_spherical_jn),
+            [IntArg(0, 200), ComplexArg()]
+        )
+
+    def test_spherical_yn(self):
+        def mp_spherical_yn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_yn(int(n), z),
+            exception_to_nan(mp_spherical_yn),
+            [IntArg(0, 200), Arg(-1e10, 1e10)],
+            dps=100,
+        )
+
+    def test_spherical_yn_complex(self):
+        def mp_spherical_yn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.bessely(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_yn(int(n.real), z),
+            exception_to_nan(mp_spherical_yn),
+            [IntArg(0, 200), ComplexArg()],
+        )
+
+    def test_spherical_in(self):
+        def mp_spherical_in(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_in(int(n), z),
+            exception_to_nan(mp_spherical_in),
+            [IntArg(0, 200), Arg()],
+            dps=200,
+            atol=10**(-278),
+        )
+
+    def test_spherical_in_complex(self):
+        def mp_spherical_in(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besseli(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_in(int(n.real), z),
+            exception_to_nan(mp_spherical_in),
+            [IntArg(0, 200), ComplexArg()],
+        )
+
+    def test_spherical_kn(self):
+        def mp_spherical_kn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if mpmath.mpmathify(z).imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_kn(int(n), z),
+            exception_to_nan(mp_spherical_kn),
+            [IntArg(0, 150), Arg()],
+            dps=100,
+        )
+
+    @pytest.mark.xfail(run=False,
+                       reason="Accuracy issues near z = -1 inherited from kv.")
+    def test_spherical_kn_complex(self):
+        def mp_spherical_kn(n, z):
+            arg = mpmath.mpmathify(z)
+            out = (mpmath.besselk(n + mpmath.mpf(1)/2, arg) /
+                   mpmath.sqrt(2*arg/mpmath.pi))
+            if arg.imag == 0:
+                return out.real
+            else:
+                return out
+
+        assert_mpmath_equal(
+            lambda n, z: sc.spherical_kn(int(n.real), z),
+            exception_to_nan(mp_spherical_kn),
+            [IntArg(0, 200), ComplexArg()],
+            dps=200,
+        )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b3e574da056bc9ba7d472567caf992d6638c20a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_nan_inputs.py
@@ -0,0 +1,65 @@
+"""Test how the ufuncs in special handle nan inputs.
+
+"""
+from typing import Callable
+
+import numpy as np
+from numpy.testing import assert_array_equal, assert_, suppress_warnings
+import pytest
+import scipy.special as sc
+
+
+KNOWNFAILURES: dict[str, Callable] = {}
+
+POSTPROCESSING: dict[str, Callable] = {}
+
+
+def _get_ufuncs():
+    ufuncs = []
+    ufunc_names = []
+    for name in sorted(sc.__dict__):
+        obj = sc.__dict__[name]
+        if not isinstance(obj, np.ufunc):
+            continue
+        msg = KNOWNFAILURES.get(obj)
+        if msg is None:
+            ufuncs.append(obj)
+            ufunc_names.append(name)
+        else:
+            fail = pytest.mark.xfail(run=False, reason=msg)
+            ufuncs.append(pytest.param(obj, marks=fail))
+            ufunc_names.append(name)
+    return ufuncs, ufunc_names
+
+
+UFUNCS, UFUNC_NAMES = _get_ufuncs()
+
+
+@pytest.mark.thread_unsafe
+@pytest.mark.parametrize("func", UFUNCS, ids=UFUNC_NAMES)
+def test_nan_inputs(func):
+    args = (np.nan,)*func.nin
+    with suppress_warnings() as sup:
+        # Ignore warnings about unsafe casts from legacy wrappers
+        sup.filter(RuntimeWarning,
+                   "floating point number truncated to an integer")
+        try:
+            with suppress_warnings() as sup:
+                sup.filter(DeprecationWarning)
+                res = func(*args)
+        except TypeError:
+            # One of the arguments doesn't take real inputs
+            return
+    if func in POSTPROCESSING:
+        res = POSTPROCESSING[func](*res)
+
+    msg = f"got {res} instead of nan"
+    assert_array_equal(np.isnan(res), True, err_msg=msg)
+
+
+def test_legacy_cast():
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning,
+                   "floating point number truncated to an integer")
+        res = sc.bdtrc(np.nan, 1, 0.5)
+        assert_(np.isnan(res))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba9b689b34384585cc65204000febcb99c910d55
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtr.py
@@ -0,0 +1,77 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+import scipy.special as sc
+
+
+def test_ndtr():
+    assert_equal(sc.ndtr(0), 0.5)
+    assert_allclose(sc.ndtr(1), 0.8413447460685429)
+
+
+class TestNdtri:
+
+    def test_zero(self):
+        assert sc.ndtri(0.5) == 0.0
+
+    def test_asymptotes(self):
+        assert_equal(sc.ndtri([0.0, 1.0]), [-np.inf, np.inf])
+
+    def test_outside_of_domain(self):
+        assert all(np.isnan(sc.ndtri([-1.5, 1.5])))
+
+
+class TestLogNdtr:
+
+    # The expected values in these tests were computed with mpmath:
+    #
+    #   def log_ndtr_mp(x):
+    #       return mpmath.log(mpmath.ncdf(x))
+    #
+
+    def test_log_ndtr_moderate_le8(self):
+        x = np.array([-0.75, -0.25, 0, 0.5, 1.5, 2.5, 3, 4, 5, 7, 8])
+        expected = np.array([-1.4844482299196562,
+                             -0.9130617648111351,
+                             -0.6931471805599453,
+                             -0.3689464152886564,
+                             -0.06914345561223398,
+                             -0.006229025485860002,
+                             -0.0013508099647481938,
+                             -3.167174337748927e-05,
+                             -2.866516129637636e-07,
+                             -1.279812543886654e-12,
+                             -6.220960574271786e-16])
+        y = sc.log_ndtr(x)
+        assert_allclose(y, expected, rtol=1e-14)
+
+    def test_log_ndtr_values_8_16(self):
+        x = np.array([8.001, 8.06, 8.15, 8.5, 10, 12, 14, 16])
+        expected = [-6.170639424817055e-16,
+                    -3.814722443652823e-16,
+                    -1.819621363526629e-16,
+                    -9.479534822203318e-18,
+                    -7.619853024160525e-24,
+                    -1.776482112077679e-33,
+                    -7.7935368191928e-45,
+                    -6.388754400538087e-58]
+        y = sc.log_ndtr(x)
+        assert_allclose(y, expected, rtol=5e-14)
+
+    def test_log_ndtr_values_16_31(self):
+        x = np.array([16.15, 20.3, 21.4, 26.2, 30.9])
+        expected = [-5.678084565148492e-59,
+                    -6.429244467698346e-92,
+                    -6.680402412553295e-102,
+                    -1.328698078458869e-151,
+                    -5.972288641838264e-210]
+        y = sc.log_ndtr(x)
+        assert_allclose(y, expected, rtol=2e-13)
+
+    def test_log_ndtr_values_gt31(self):
+        x = np.array([31.6, 32.8, 34.9, 37.1])
+        expected = [-1.846036234858162e-219,
+                    -2.9440539964066835e-236,
+                    -3.71721649450857e-267,
+                    -1.4047119663106221e-301]
+        y = sc.log_ndtr(x)
+        assert_allclose(y, expected, rtol=3e-13)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py
new file mode 100644
index 0000000000000000000000000000000000000000..82a9fbd3bcda117770e00018facda3f56630a6bc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ndtri_exp.py
@@ -0,0 +1,94 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+from scipy.special import log_ndtr, ndtri_exp
+from scipy.special._testutils import assert_func_equal
+
+
+def log_ndtr_ndtri_exp(y):
+    return log_ndtr(ndtri_exp(y))
+
+
+@pytest.fixture(scope="class")
+def uniform_random_points():
+    random_state = np.random.RandomState(1234)
+    points = random_state.random_sample(1000)
+    return points
+
+
+class TestNdtriExp:
+    """Tests that ndtri_exp is sufficiently close to an inverse of log_ndtr.
+
+    We have separate tests for the five intervals (-inf, -10),
+    [-10, -2), [-2, -0.14542), [-0.14542, -1e-6), and [-1e-6, 0).
+    ndtri_exp(y) is computed in three different ways depending on if y
+    is in (-inf, -2), [-2, log(1 - exp(-2))], or [log(1 - exp(-2), 0).
+    Each of these intervals is given its own test with two additional tests
+    for handling very small values and values very close to zero.
+    """
+
+    @pytest.mark.parametrize(
+        "test_input", [-1e1, -1e2, -1e10, -1e20, -np.finfo(float).max]
+    )
+    def test_very_small_arg(self, test_input, uniform_random_points):
+        scale = test_input
+        points = scale * (0.5 * uniform_random_points + 0.5)
+        assert_func_equal(
+            log_ndtr_ndtri_exp,
+            lambda y: y, points,
+            rtol=1e-14,
+            nan_ok=True
+        )
+
+    @pytest.mark.parametrize(
+        "interval,expected_rtol",
+        [
+            ((-10, -2), 1e-14),
+            ((-2, -0.14542), 1e-12),
+            ((-0.14542, -1e-6), 1e-10),
+            ((-1e-6, 0), 1e-6),
+        ],
+    )
+    def test_in_interval(self, interval, expected_rtol, uniform_random_points):
+        left, right = interval
+        points = (right - left) * uniform_random_points + left
+        assert_func_equal(
+            log_ndtr_ndtri_exp,
+            lambda y: y, points,
+            rtol=expected_rtol,
+            nan_ok=True
+        )
+
+    def test_extreme(self):
+        # bigneg is not quite the largest negative double precision value.
+        # Here's why:
+        # The round-trip calculation
+        #    y = ndtri_exp(bigneg)
+        #    bigneg2 = log_ndtr(y)
+        # where bigneg is a very large negative value, would--with infinite
+        # precision--result in bigneg2 == bigneg.  When bigneg is large enough,
+        # y is effectively equal to -sqrt(2)*sqrt(-bigneg), and log_ndtr(y) is
+        # effectively -(y/sqrt(2))**2.  If we use bigneg = np.finfo(float).min,
+        # then by construction, the theoretical value is the most negative
+        # finite value that can be represented with 64 bit float point.  This
+        # means tiny changes in how the computation proceeds can result in the
+        # return value being -inf.  (E.g. changing the constant representation
+        # of 1/sqrt(2) from 0.7071067811865475--which is the value returned by
+        # 1/np.sqrt(2)--to 0.7071067811865476--which is the most accurate 64
+        # bit floating point representation of 1/sqrt(2)--results in the
+        # round-trip that starts with np.finfo(float).min returning -inf.  So
+        # we'll move the bigneg value a few ULPs towards 0 to avoid this
+        # sensitivity.
+        # Use the reduce method to apply nextafter four times.
+        bigneg = np.nextafter.reduce([np.finfo(float).min, 0, 0, 0, 0])
+        # tinyneg is approx. -2.225e-308.
+        tinyneg = -np.finfo(float).tiny
+        x = np.array([tinyneg, bigneg])
+        result = log_ndtr_ndtri_exp(x)
+        assert_allclose(result, x, rtol=1e-12)
+
+    def test_asymptotes(self):
+        assert_equal(ndtri_exp([-np.inf, 0.0]), [-np.inf, np.inf])
+
+    def test_outside_domain(self):
+        assert np.isnan(ndtri_exp(1.0))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py
new file mode 100644
index 0000000000000000000000000000000000000000..47831c18ab6fa48925cae576f6c664767df99d05
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal.py
@@ -0,0 +1,822 @@
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from numpy import array, sqrt
+from numpy.testing import (assert_array_almost_equal, assert_equal,
+                           assert_almost_equal, assert_allclose)
+
+from scipy import integrate
+import scipy.special as sc
+from scipy.special import gamma
+import scipy.special._orthogonal as orth
+
+
+class TestCheby:
+    def test_chebyc(self):
+        C0 = orth.chebyc(0)
+        C1 = orth.chebyc(1)
+        with np.errstate(all='ignore'):
+            C2 = orth.chebyc(2)
+            C3 = orth.chebyc(3)
+            C4 = orth.chebyc(4)
+            C5 = orth.chebyc(5)
+
+        assert_array_almost_equal(C0.c,[2],13)
+        assert_array_almost_equal(C1.c,[1,0],13)
+        assert_array_almost_equal(C2.c,[1,0,-2],13)
+        assert_array_almost_equal(C3.c,[1,0,-3,0],13)
+        assert_array_almost_equal(C4.c,[1,0,-4,0,2],13)
+        assert_array_almost_equal(C5.c,[1,0,-5,0,5,0],13)
+
+    def test_chebys(self):
+        S0 = orth.chebys(0)
+        S1 = orth.chebys(1)
+        S2 = orth.chebys(2)
+        S3 = orth.chebys(3)
+        S4 = orth.chebys(4)
+        S5 = orth.chebys(5)
+        assert_array_almost_equal(S0.c,[1],13)
+        assert_array_almost_equal(S1.c,[1,0],13)
+        assert_array_almost_equal(S2.c,[1,0,-1],13)
+        assert_array_almost_equal(S3.c,[1,0,-2,0],13)
+        assert_array_almost_equal(S4.c,[1,0,-3,0,1],13)
+        assert_array_almost_equal(S5.c,[1,0,-4,0,3,0],13)
+
+    def test_chebyt(self):
+        T0 = orth.chebyt(0)
+        T1 = orth.chebyt(1)
+        T2 = orth.chebyt(2)
+        T3 = orth.chebyt(3)
+        T4 = orth.chebyt(4)
+        T5 = orth.chebyt(5)
+        assert_array_almost_equal(T0.c,[1],13)
+        assert_array_almost_equal(T1.c,[1,0],13)
+        assert_array_almost_equal(T2.c,[2,0,-1],13)
+        assert_array_almost_equal(T3.c,[4,0,-3,0],13)
+        assert_array_almost_equal(T4.c,[8,0,-8,0,1],13)
+        assert_array_almost_equal(T5.c,[16,0,-20,0,5,0],13)
+
+    def test_chebyu(self):
+        U0 = orth.chebyu(0)
+        U1 = orth.chebyu(1)
+        U2 = orth.chebyu(2)
+        U3 = orth.chebyu(3)
+        U4 = orth.chebyu(4)
+        U5 = orth.chebyu(5)
+        assert_array_almost_equal(U0.c,[1],13)
+        assert_array_almost_equal(U1.c,[2,0],13)
+        assert_array_almost_equal(U2.c,[4,0,-1],13)
+        assert_array_almost_equal(U3.c,[8,0,-4,0],13)
+        assert_array_almost_equal(U4.c,[16,0,-12,0,1],13)
+        assert_array_almost_equal(U5.c,[32,0,-32,0,6,0],13)
+
+
+class TestGegenbauer:
+
+    def test_gegenbauer(self):
+        a = 5*np.random.random() - 0.5
+        if np.any(a == 0):
+            a = -0.2
+        Ca0 = orth.gegenbauer(0,a)
+        Ca1 = orth.gegenbauer(1,a)
+        Ca2 = orth.gegenbauer(2,a)
+        Ca3 = orth.gegenbauer(3,a)
+        Ca4 = orth.gegenbauer(4,a)
+        Ca5 = orth.gegenbauer(5,a)
+
+        assert_array_almost_equal(Ca0.c,array([1]),13)
+        assert_array_almost_equal(Ca1.c,array([2*a,0]),13)
+        assert_array_almost_equal(Ca2.c,array([2*a*(a+1),0,-a]),13)
+        assert_array_almost_equal(Ca3.c,array([4*sc.poch(a,3),0,-6*a*(a+1),
+                                               0])/3.0,11)
+        assert_array_almost_equal(Ca4.c,array([4*sc.poch(a,4),0,-12*sc.poch(a,3),
+                                               0,3*a*(a+1)])/6.0,11)
+        assert_array_almost_equal(Ca5.c,array([4*sc.poch(a,5),0,-20*sc.poch(a,4),
+                                               0,15*sc.poch(a,3),0])/15.0,11)
+
+    @pytest.mark.parametrize('a', [0, 1])
+    def test_n_zero_gh8888(self, a):
+        # gh-8888 reported that gegenbauer(0, 0) returns NaN polynomial
+        Cn0 = orth.gegenbauer(0, a)
+        assert_equal(Cn0.c, np.asarray([1.]))
+
+    def test_valid_alpha(self):
+        # Check input validation of `alpha`
+        message = '`alpha` must be a finite number greater...'
+        with pytest.raises(ValueError, match=message):
+            orth.gegenbauer(0, np.nan)
+        with pytest.raises(ValueError, match=message):
+            orth.gegenbauer(1, -0.5)
+        with pytest.raises(ValueError, match=message):
+            orth.gegenbauer(2, -np.inf)
+
+
+class TestHermite:
+    def test_hermite(self):
+        H0 = orth.hermite(0)
+        H1 = orth.hermite(1)
+        H2 = orth.hermite(2)
+        H3 = orth.hermite(3)
+        H4 = orth.hermite(4)
+        H5 = orth.hermite(5)
+        assert_array_almost_equal(H0.c,[1],13)
+        assert_array_almost_equal(H1.c,[2,0],13)
+        assert_array_almost_equal(H2.c,[4,0,-2],13)
+        assert_array_almost_equal(H3.c,[8,0,-12,0],13)
+        assert_array_almost_equal(H4.c,[16,0,-48,0,12],12)
+        assert_array_almost_equal(H5.c,[32,0,-160,0,120,0],12)
+
+    def test_hermitenorm(self):
+        # He_n(x) = 2**(-n/2) H_n(x/sqrt(2))
+        psub = np.poly1d([1.0/sqrt(2),0])
+        H0 = orth.hermitenorm(0)
+        H1 = orth.hermitenorm(1)
+        H2 = orth.hermitenorm(2)
+        H3 = orth.hermitenorm(3)
+        H4 = orth.hermitenorm(4)
+        H5 = orth.hermitenorm(5)
+        he0 = orth.hermite(0)(psub)
+        he1 = orth.hermite(1)(psub) / sqrt(2)
+        he2 = orth.hermite(2)(psub) / 2.0
+        he3 = orth.hermite(3)(psub) / (2*sqrt(2))
+        he4 = orth.hermite(4)(psub) / 4.0
+        he5 = orth.hermite(5)(psub) / (4.0*sqrt(2))
+
+        assert_array_almost_equal(H0.c,he0.c,13)
+        assert_array_almost_equal(H1.c,he1.c,13)
+        assert_array_almost_equal(H2.c,he2.c,13)
+        assert_array_almost_equal(H3.c,he3.c,13)
+        assert_array_almost_equal(H4.c,he4.c,13)
+        assert_array_almost_equal(H5.c,he5.c,13)
+
+
+class TestShLegendre:
+    def test_sh_legendre(self):
+        # P*_n(x) = P_n(2x-1)
+        psub = np.poly1d([2,-1])
+        Ps0 = orth.sh_legendre(0)
+        Ps1 = orth.sh_legendre(1)
+        Ps2 = orth.sh_legendre(2)
+        Ps3 = orth.sh_legendre(3)
+        Ps4 = orth.sh_legendre(4)
+        Ps5 = orth.sh_legendre(5)
+        pse0 = orth.legendre(0)(psub)
+        pse1 = orth.legendre(1)(psub)
+        pse2 = orth.legendre(2)(psub)
+        pse3 = orth.legendre(3)(psub)
+        pse4 = orth.legendre(4)(psub)
+        pse5 = orth.legendre(5)(psub)
+        assert_array_almost_equal(Ps0.c,pse0.c,13)
+        assert_array_almost_equal(Ps1.c,pse1.c,13)
+        assert_array_almost_equal(Ps2.c,pse2.c,13)
+        assert_array_almost_equal(Ps3.c,pse3.c,13)
+        assert_array_almost_equal(Ps4.c,pse4.c,12)
+        assert_array_almost_equal(Ps5.c,pse5.c,12)
+
+
+class TestShChebyt:
+    def test_sh_chebyt(self):
+        # T*_n(x) = T_n(2x-1)
+        psub = np.poly1d([2,-1])
+        Ts0 = orth.sh_chebyt(0)
+        Ts1 = orth.sh_chebyt(1)
+        Ts2 = orth.sh_chebyt(2)
+        Ts3 = orth.sh_chebyt(3)
+        Ts4 = orth.sh_chebyt(4)
+        Ts5 = orth.sh_chebyt(5)
+        tse0 = orth.chebyt(0)(psub)
+        tse1 = orth.chebyt(1)(psub)
+        tse2 = orth.chebyt(2)(psub)
+        tse3 = orth.chebyt(3)(psub)
+        tse4 = orth.chebyt(4)(psub)
+        tse5 = orth.chebyt(5)(psub)
+        assert_array_almost_equal(Ts0.c,tse0.c,13)
+        assert_array_almost_equal(Ts1.c,tse1.c,13)
+        assert_array_almost_equal(Ts2.c,tse2.c,13)
+        assert_array_almost_equal(Ts3.c,tse3.c,13)
+        assert_array_almost_equal(Ts4.c,tse4.c,12)
+        assert_array_almost_equal(Ts5.c,tse5.c,12)
+
+
+class TestShChebyu:
+    def test_sh_chebyu(self):
+        # U*_n(x) = U_n(2x-1)
+        psub = np.poly1d([2,-1])
+        Us0 = orth.sh_chebyu(0)
+        Us1 = orth.sh_chebyu(1)
+        Us2 = orth.sh_chebyu(2)
+        Us3 = orth.sh_chebyu(3)
+        Us4 = orth.sh_chebyu(4)
+        Us5 = orth.sh_chebyu(5)
+        use0 = orth.chebyu(0)(psub)
+        use1 = orth.chebyu(1)(psub)
+        use2 = orth.chebyu(2)(psub)
+        use3 = orth.chebyu(3)(psub)
+        use4 = orth.chebyu(4)(psub)
+        use5 = orth.chebyu(5)(psub)
+        assert_array_almost_equal(Us0.c,use0.c,13)
+        assert_array_almost_equal(Us1.c,use1.c,13)
+        assert_array_almost_equal(Us2.c,use2.c,13)
+        assert_array_almost_equal(Us3.c,use3.c,13)
+        assert_array_almost_equal(Us4.c,use4.c,12)
+        assert_array_almost_equal(Us5.c,use5.c,11)
+
+
+class TestShJacobi:
+    def test_sh_jacobi(self):
+        # G^(p,q)_n(x) = n! gamma(n+p)/gamma(2*n+p) * P^(p-q,q-1)_n(2*x-1)
+        def conv(n, p):
+            return gamma(n + 1) * gamma(n + p) / gamma(2 * n + p)
+        psub = np.poly1d([2,-1])
+        q = 4 * np.random.random()
+        p = q-1 + 2*np.random.random()
+        # print("shifted jacobi p,q = ", p, q)
+        G0 = orth.sh_jacobi(0,p,q)
+        G1 = orth.sh_jacobi(1,p,q)
+        G2 = orth.sh_jacobi(2,p,q)
+        G3 = orth.sh_jacobi(3,p,q)
+        G4 = orth.sh_jacobi(4,p,q)
+        G5 = orth.sh_jacobi(5,p,q)
+        ge0 = orth.jacobi(0,p-q,q-1)(psub) * conv(0,p)
+        ge1 = orth.jacobi(1,p-q,q-1)(psub) * conv(1,p)
+        ge2 = orth.jacobi(2,p-q,q-1)(psub) * conv(2,p)
+        ge3 = orth.jacobi(3,p-q,q-1)(psub) * conv(3,p)
+        ge4 = orth.jacobi(4,p-q,q-1)(psub) * conv(4,p)
+        ge5 = orth.jacobi(5,p-q,q-1)(psub) * conv(5,p)
+
+        assert_array_almost_equal(G0.c,ge0.c,13)
+        assert_array_almost_equal(G1.c,ge1.c,13)
+        assert_array_almost_equal(G2.c,ge2.c,13)
+        assert_array_almost_equal(G3.c,ge3.c,13)
+        assert_array_almost_equal(G4.c,ge4.c,13)
+        assert_array_almost_equal(G5.c,ge5.c,13)
+
+
+class TestCall:
+    def test_call(self):
+        poly = []
+        for n in range(5):
+            poly.extend([x.strip() for x in
+                ("""
+                orth.jacobi(%(n)d,0.3,0.9)
+                orth.sh_jacobi(%(n)d,0.3,0.9)
+                orth.genlaguerre(%(n)d,0.3)
+                orth.laguerre(%(n)d)
+                orth.hermite(%(n)d)
+                orth.hermitenorm(%(n)d)
+                orth.gegenbauer(%(n)d,0.3)
+                orth.chebyt(%(n)d)
+                orth.chebyu(%(n)d)
+                orth.chebyc(%(n)d)
+                orth.chebys(%(n)d)
+                orth.sh_chebyt(%(n)d)
+                orth.sh_chebyu(%(n)d)
+                orth.legendre(%(n)d)
+                orth.sh_legendre(%(n)d)
+                """ % dict(n=n)).split()
+            ])
+        with np.errstate(all='ignore'):
+            for pstr in poly:
+                p = eval(pstr)
+                assert_almost_equal(p(0.315), np.poly1d(p.coef)(0.315),
+                                    err_msg=pstr)
+
+
+class TestGenlaguerre:
+    def test_regression(self):
+        assert_equal(orth.genlaguerre(1, 1, monic=False)(0), 2.)
+        assert_equal(orth.genlaguerre(1, 1, monic=True)(0), -2.)
+        assert_equal(orth.genlaguerre(1, 1, monic=False), np.poly1d([-1, 2]))
+        assert_equal(orth.genlaguerre(1, 1, monic=True), np.poly1d([1, -2]))
+
+
+def verify_gauss_quad(root_func, eval_func, weight_func, a, b, N,
+                      rtol=1e-15, atol=5e-14):
+    # this test is copied from numpy's TestGauss in test_hermite.py
+    x, w, mu = root_func(N, True)
+
+    n = np.arange(N, dtype=np.dtype("long"))
+    v = eval_func(n[:,np.newaxis], x)
+    vv = np.dot(v*w, v.T)
+    vd = 1 / np.sqrt(vv.diagonal())
+    vv = vd[:, np.newaxis] * vv * vd
+    assert_allclose(vv, np.eye(N), rtol, atol)
+
+    # check that the integral of 1 is correct
+    assert_allclose(w.sum(), mu, rtol, atol)
+
+    # compare the results of integrating a function with quad.
+    def f(x):
+        return x ** 3 - 3 * x ** 2 + x - 2
+    resI = integrate.quad(lambda x: f(x)*weight_func(x), a, b)
+    resG = np.vdot(f(x), w)
+    rtol = 1e-6 if 1e-6 < resI[1] else resI[1] * 10
+    assert_allclose(resI[0], resG, rtol=rtol)
+
+def test_roots_jacobi():
+    def rf(a, b):
+        return lambda n, mu: sc.roots_jacobi(n, a, b, mu)
+    def ef(a, b):
+        return lambda n, x: sc.eval_jacobi(n, a, b, x)
+    def wf(a, b):
+        return lambda x: (1 - x) ** a * (1 + x) ** b
+
+    vgq = verify_gauss_quad
+    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1., 5)
+    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1.,
+        25, atol=1e-12)
+    vgq(rf(-0.5, -0.75), ef(-0.5, -0.75), wf(-0.5, -0.75), -1., 1.,
+        100, atol=1e-11)
+
+    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 5)
+    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 25, atol=1.5e-13)
+    vgq(rf(0.5, -0.5), ef(0.5, -0.5), wf(0.5, -0.5), -1., 1., 100, atol=2e-12)
+
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 5, atol=2e-13)
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 25, atol=2e-13)
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), -1., 1., 100, atol=1e-12)
+
+    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 5)
+    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 25, atol=1e-13)
+    vgq(rf(0.9, 2), ef(0.9, 2), wf(0.9, 2), -1., 1., 100, atol=3e-13)
+
+    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 5)
+    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1., 25,
+        atol=1.1e-14)
+    vgq(rf(18.24, 27.3), ef(18.24, 27.3), wf(18.24, 27.3), -1., 1.,
+        100, atol=1e-13)
+
+    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 5, atol=1e-13)
+    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1., 25, atol=2e-13)
+    vgq(rf(47.1, -0.2), ef(47.1, -0.2), wf(47.1, -0.2), -1., 1.,
+        100, atol=1e-11)
+
+    vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 5, atol=2e-13)
+    vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 25, atol=1e-12)
+    vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 100, atol=1e-11)
+    vgq(rf(1., 658.), ef(1., 658.), wf(1., 658.), -1., 1., 250, atol=1e-11)
+
+    vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 5,
+        atol=1e-12)
+    vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 25,
+        atol=1e-11)
+    vgq(rf(511., 511.), ef(511., 511.), wf(511., 511.), -1., 1., 100,
+        atol=1e-10)
+
+    vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 5,
+        atol=1e-12)
+    vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 25,
+        atol=1e-11)
+    vgq(rf(511., 512.), ef(511., 512.), wf(511., 512.), -1., 1., 100,
+        atol=1e-10)
+
+    vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 5,
+        atol=1e-12)
+    vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 25,
+        atol=1e-11)
+    vgq(rf(1000., 500.), ef(1000., 500.), wf(1000., 500.), -1., 1., 100,
+        atol=1e-10)
+
+    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 5)
+    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 25,
+        atol=1e-13)
+    vgq(rf(2.25, 68.9), ef(2.25, 68.9), wf(2.25, 68.9), -1., 1., 100,
+        atol=1e-13)
+
+    # when alpha == beta == 0, P_n^{a,b}(x) == P_n(x)
+    xj, wj = sc.roots_jacobi(6, 0.0, 0.0)
+    xl, wl = sc.roots_legendre(6)
+    assert_allclose(xj, xl, 1e-14, 1e-14)
+    assert_allclose(wj, wl, 1e-14, 1e-14)
+
+    # when alpha == beta != 0, P_n^{a,b}(x) == C_n^{alpha+0.5}(x)
+    xj, wj = sc.roots_jacobi(6, 4.0, 4.0)
+    xc, wc = sc.roots_gegenbauer(6, 4.5)
+    assert_allclose(xj, xc, 1e-14, 1e-14)
+    assert_allclose(wj, wc, 1e-14, 1e-14)
+
+    x, w = sc.roots_jacobi(5, 2, 3, False)
+    y, v, m = sc.roots_jacobi(5, 2, 3, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(wf(2,3), -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_jacobi, 0, 1, 1)
+    assert_raises(ValueError, sc.roots_jacobi, 3.3, 1, 1)
+    assert_raises(ValueError, sc.roots_jacobi, 3, -2, 1)
+    assert_raises(ValueError, sc.roots_jacobi, 3, 1, -2)
+    assert_raises(ValueError, sc.roots_jacobi, 3, -2, -2)
+
+def test_roots_sh_jacobi():
+    def rf(a, b):
+        return lambda n, mu: sc.roots_sh_jacobi(n, a, b, mu)
+    def ef(a, b):
+        return lambda n, x: sc.eval_sh_jacobi(n, a, b, x)
+    def wf(a, b):
+        return lambda x: (1.0 - x) ** (a - b) * x ** (b - 1.0)
+
+    vgq = verify_gauss_quad
+    vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1., 5)
+    vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1.,
+        25, atol=1e-12)
+    vgq(rf(-0.5, 0.25), ef(-0.5, 0.25), wf(-0.5, 0.25), 0., 1.,
+        100, atol=1e-11)
+
+    vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 5)
+    vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 25, atol=1e-13)
+    vgq(rf(0.5, 0.5), ef(0.5, 0.5), wf(0.5, 0.5), 0., 1., 100, atol=1e-12)
+
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 5)
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 25, atol=1.5e-13)
+    vgq(rf(1, 0.5), ef(1, 0.5), wf(1, 0.5), 0., 1., 100, atol=2e-12)
+
+    vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 5)
+    vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 25, atol=1e-13)
+    vgq(rf(2, 0.9), ef(2, 0.9), wf(2, 0.9), 0., 1., 100, atol=1e-12)
+
+    vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 5)
+    vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1., 25)
+    vgq(rf(27.3, 18.24), ef(27.3, 18.24), wf(27.3, 18.24), 0., 1.,
+        100, atol=1e-13)
+
+    vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 5, atol=1e-12)
+    vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 25, atol=1e-11)
+    vgq(rf(47.1, 0.2), ef(47.1, 0.2), wf(47.1, 0.2), 0., 1., 100, atol=1e-10)
+
+    vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 5, atol=3.5e-14)
+    vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1., 25, atol=2e-13)
+    vgq(rf(68.9, 2.25), ef(68.9, 2.25), wf(68.9, 2.25), 0., 1.,
+        100, atol=1e-12)
+
+    x, w = sc.roots_sh_jacobi(5, 3, 2, False)
+    y, v, m = sc.roots_sh_jacobi(5, 3, 2, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(wf(3,2), 0, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_sh_jacobi, 0, 1, 1)
+    assert_raises(ValueError, sc.roots_sh_jacobi, 3.3, 1, 1)
+    assert_raises(ValueError, sc.roots_sh_jacobi, 3, 1, 2)    # p - q <= -1
+    assert_raises(ValueError, sc.roots_sh_jacobi, 3, 2, -1)   # q <= 0
+    assert_raises(ValueError, sc.roots_sh_jacobi, 3, -2, -1)  # both
+
+def test_roots_hermite():
+    rootf = sc.roots_hermite
+    evalf = sc.eval_hermite
+    weightf = orth.hermite(5).weight_func
+
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5)
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13)
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12)
+
+    # Golub-Welsch branch
+    x, w = sc.roots_hermite(5, False)
+    y, v, m = sc.roots_hermite(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -np.inf, np.inf)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    # Asymptotic branch (switch over at n >= 150)
+    x, w = sc.roots_hermite(200, False)
+    y, v, m = sc.roots_hermite(200, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+    assert_allclose(sum(v), m, 1e-14, 1e-14)
+
+    assert_raises(ValueError, sc.roots_hermite, 0)
+    assert_raises(ValueError, sc.roots_hermite, 3.3)
+
+def test_roots_hermite_asy():
+    # Recursion for Hermite functions
+    def hermite_recursion(n, nodes):
+        H = np.zeros((n, nodes.size))
+        H[0,:] = np.pi**(-0.25) * np.exp(-0.5*nodes**2)
+        if n > 1:
+            H[1,:] = sqrt(2.0) * nodes * H[0,:]
+            for k in range(2, n):
+                H[k,:] = sqrt(2.0/k) * nodes * H[k-1,:] - sqrt((k-1.0)/k) * H[k-2,:]
+        return H
+
+    # This tests only the nodes
+    def test(N, rtol=1e-15, atol=1e-14):
+        x, w = orth._roots_hermite_asy(N)
+        H = hermite_recursion(N+1, x)
+        assert_allclose(H[-1,:], np.zeros(N), rtol, atol)
+        assert_allclose(sum(w), sqrt(np.pi), rtol, atol)
+
+    test(150, atol=1e-12)
+    test(151, atol=1e-12)
+    test(300, atol=1e-12)
+    test(301, atol=1e-12)
+    test(500, atol=1e-12)
+    test(501, atol=1e-12)
+    test(999, atol=1e-12)
+    test(1000, atol=1e-12)
+    test(2000, atol=1e-12)
+    test(5000, atol=1e-12)
+
+def test_roots_hermitenorm():
+    rootf = sc.roots_hermitenorm
+    evalf = sc.eval_hermitenorm
+    weightf = orth.hermitenorm(5).weight_func
+
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 5)
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 25, atol=1e-13)
+    verify_gauss_quad(rootf, evalf, weightf, -np.inf, np.inf, 100, atol=1e-12)
+
+    x, w = sc.roots_hermitenorm(5, False)
+    y, v, m = sc.roots_hermitenorm(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -np.inf, np.inf)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_hermitenorm, 0)
+    assert_raises(ValueError, sc.roots_hermitenorm, 3.3)
+
+def test_roots_gegenbauer():
+    def rootf(a):
+        return lambda n, mu: sc.roots_gegenbauer(n, a, mu)
+    def evalf(a):
+        return lambda n, x: sc.eval_gegenbauer(n, a, x)
+    def weightf(a):
+        return lambda x: (1 - x ** 2) ** (a - 0.5)
+
+    vgq = verify_gauss_quad
+    vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 5)
+    vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 25, atol=1e-12)
+    vgq(rootf(-0.25), evalf(-0.25), weightf(-0.25), -1., 1., 100, atol=1e-11)
+
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 5)
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 25, atol=1e-13)
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), -1., 1., 100, atol=1e-12)
+
+    vgq(rootf(1), evalf(1), weightf(1), -1., 1., 5)
+    vgq(rootf(1), evalf(1), weightf(1), -1., 1., 25, atol=1e-13)
+    vgq(rootf(1), evalf(1), weightf(1), -1., 1., 100, atol=1e-12)
+
+    vgq(rootf(10), evalf(10), weightf(10), -1., 1., 5)
+    vgq(rootf(10), evalf(10), weightf(10), -1., 1., 25, atol=1e-13)
+    vgq(rootf(10), evalf(10), weightf(10), -1., 1., 100, atol=1e-12)
+
+    vgq(rootf(50), evalf(50), weightf(50), -1., 1., 5, atol=1e-13)
+    vgq(rootf(50), evalf(50), weightf(50), -1., 1., 25, atol=1e-12)
+    vgq(rootf(50), evalf(50), weightf(50), -1., 1., 100, atol=1e-11)
+
+    # Alpha=170 is where the approximation used in roots_gegenbauer changes
+    vgq(rootf(170), evalf(170), weightf(170), -1., 1., 5, atol=1e-13)
+    vgq(rootf(170), evalf(170), weightf(170), -1., 1., 25, atol=1e-12)
+    vgq(rootf(170), evalf(170), weightf(170), -1., 1., 100, atol=1e-11)
+    vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 5, atol=1.25e-13)
+    vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 25, atol=1e-12)
+    vgq(rootf(170.5), evalf(170.5), weightf(170.5), -1., 1., 100, atol=1e-11)
+
+    # Test for failures, e.g. overflows, resulting from large alphas
+    vgq(rootf(238), evalf(238), weightf(238), -1., 1., 5, atol=1e-13)
+    vgq(rootf(238), evalf(238), weightf(238), -1., 1., 25, atol=1e-12)
+    vgq(rootf(238), evalf(238), weightf(238), -1., 1., 100, atol=1e-11)
+    vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 5, atol=1e-12)
+    vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 25, atol=1e-11)
+    vgq(rootf(512.5), evalf(512.5), weightf(512.5), -1., 1., 100, atol=1e-10)
+
+    # this is a special case that the old code supported.
+    # when alpha = 0, the gegenbauer polynomial is uniformly 0. but it goes
+    # to a scaled down copy of T_n(x) there.
+    vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 5)
+    vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 25)
+    vgq(rootf(0), sc.eval_chebyt, weightf(0), -1., 1., 100, atol=1e-12)
+
+    x, w = sc.roots_gegenbauer(5, 2, False)
+    y, v, m = sc.roots_gegenbauer(5, 2, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf(2), -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_gegenbauer, 0, 2)
+    assert_raises(ValueError, sc.roots_gegenbauer, 3.3, 2)
+    assert_raises(ValueError, sc.roots_gegenbauer, 3, -.75)
+
+def test_roots_chebyt():
+    weightf = orth.chebyt(5).weight_func
+    verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 5)
+    verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 25)
+    verify_gauss_quad(sc.roots_chebyt, sc.eval_chebyt, weightf, -1., 1., 100,
+                      atol=1e-12)
+
+    x, w = sc.roots_chebyt(5, False)
+    y, v, m = sc.roots_chebyt(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_chebyt, 0)
+    assert_raises(ValueError, sc.roots_chebyt, 3.3)
+
+def test_chebyt_symmetry():
+    x, w = sc.roots_chebyt(21)
+    pos, neg = x[:10], x[11:]
+    assert_equal(neg, -pos[::-1])
+    assert_equal(x[10], 0)
+
+def test_roots_chebyu():
+    weightf = orth.chebyu(5).weight_func
+    verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 5)
+    verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 25)
+    verify_gauss_quad(sc.roots_chebyu, sc.eval_chebyu, weightf, -1., 1., 100)
+
+    x, w = sc.roots_chebyu(5, False)
+    y, v, m = sc.roots_chebyu(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_chebyu, 0)
+    assert_raises(ValueError, sc.roots_chebyu, 3.3)
+
+def test_roots_chebyc():
+    weightf = orth.chebyc(5).weight_func
+    verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 5)
+    verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 25)
+    verify_gauss_quad(sc.roots_chebyc, sc.eval_chebyc, weightf, -2., 2., 100,
+                      atol=1e-12)
+
+    x, w = sc.roots_chebyc(5, False)
+    y, v, m = sc.roots_chebyc(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -2, 2)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_chebyc, 0)
+    assert_raises(ValueError, sc.roots_chebyc, 3.3)
+
+def test_roots_chebys():
+    weightf = orth.chebys(5).weight_func
+    verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 5)
+    verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 25)
+    verify_gauss_quad(sc.roots_chebys, sc.eval_chebys, weightf, -2., 2., 100)
+
+    x, w = sc.roots_chebys(5, False)
+    y, v, m = sc.roots_chebys(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -2, 2)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_chebys, 0)
+    assert_raises(ValueError, sc.roots_chebys, 3.3)
+
+def test_roots_sh_chebyt():
+    weightf = orth.sh_chebyt(5).weight_func
+    verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 5)
+    verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1., 25)
+    verify_gauss_quad(sc.roots_sh_chebyt, sc.eval_sh_chebyt, weightf, 0., 1.,
+                      100, atol=1e-13)
+
+    x, w = sc.roots_sh_chebyt(5, False)
+    y, v, m = sc.roots_sh_chebyt(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, 0, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_sh_chebyt, 0)
+    assert_raises(ValueError, sc.roots_sh_chebyt, 3.3)
+
+def test_roots_sh_chebyu():
+    weightf = orth.sh_chebyu(5).weight_func
+    verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 5)
+    verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1., 25)
+    verify_gauss_quad(sc.roots_sh_chebyu, sc.eval_sh_chebyu, weightf, 0., 1.,
+                      100, atol=1e-13)
+
+    x, w = sc.roots_sh_chebyu(5, False)
+    y, v, m = sc.roots_sh_chebyu(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, 0, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_sh_chebyu, 0)
+    assert_raises(ValueError, sc.roots_sh_chebyu, 3.3)
+
+def test_roots_legendre():
+    weightf = orth.legendre(5).weight_func
+    verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1., 5)
+    verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1.,
+                      25, atol=1e-13)
+    verify_gauss_quad(sc.roots_legendre, sc.eval_legendre, weightf, -1., 1.,
+                      100, atol=1e-12)
+
+    x, w = sc.roots_legendre(5, False)
+    y, v, m = sc.roots_legendre(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, -1, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_legendre, 0)
+    assert_raises(ValueError, sc.roots_legendre, 3.3)
+
+def test_roots_sh_legendre():
+    weightf = orth.sh_legendre(5).weight_func
+    verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1., 5)
+    verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1.,
+                      25, atol=1e-13)
+    verify_gauss_quad(sc.roots_sh_legendre, sc.eval_sh_legendre, weightf, 0., 1.,
+                      100, atol=1e-12)
+
+    x, w = sc.roots_sh_legendre(5, False)
+    y, v, m = sc.roots_sh_legendre(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, 0, 1)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_sh_legendre, 0)
+    assert_raises(ValueError, sc.roots_sh_legendre, 3.3)
+
+def test_roots_laguerre():
+    weightf = orth.laguerre(5).weight_func
+    verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf, 5)
+    verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf,
+                      25, atol=1e-13)
+    verify_gauss_quad(sc.roots_laguerre, sc.eval_laguerre, weightf, 0., np.inf,
+                      100, atol=1e-12)
+
+    x, w = sc.roots_laguerre(5, False)
+    y, v, m = sc.roots_laguerre(5, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf, 0, np.inf)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_laguerre, 0)
+    assert_raises(ValueError, sc.roots_laguerre, 3.3)
+
+def test_roots_genlaguerre():
+    def rootf(a):
+        return lambda n, mu: sc.roots_genlaguerre(n, a, mu)
+    def evalf(a):
+        return lambda n, x: sc.eval_genlaguerre(n, a, x)
+    def weightf(a):
+        return lambda x: x ** a * np.exp(-x)
+
+    vgq = verify_gauss_quad
+    vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 5)
+    vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(-0.5), evalf(-0.5), weightf(-0.5), 0., np.inf, 100, atol=1e-12)
+
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 5)
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(0.1), evalf(0.1), weightf(0.1), 0., np.inf, 100, atol=1.6e-13)
+
+    vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 5)
+    vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(1), evalf(1), weightf(1), 0., np.inf, 100, atol=1.03e-13)
+
+    vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 5)
+    vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(10), evalf(10), weightf(10), 0., np.inf, 100, atol=1e-12)
+
+    vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 5)
+    vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 25, atol=1e-13)
+    vgq(rootf(50), evalf(50), weightf(50), 0., np.inf, 100, rtol=1e-14, atol=2e-13)
+
+    x, w = sc.roots_genlaguerre(5, 2, False)
+    y, v, m = sc.roots_genlaguerre(5, 2, True)
+    assert_allclose(x, y, 1e-14, 1e-14)
+    assert_allclose(w, v, 1e-14, 1e-14)
+
+    muI, muI_err = integrate.quad(weightf(2.), 0., np.inf)
+    assert_allclose(m, muI, rtol=muI_err)
+
+    assert_raises(ValueError, sc.roots_genlaguerre, 0, 2)
+    assert_raises(ValueError, sc.roots_genlaguerre, 3.3, 2)
+    assert_raises(ValueError, sc.roots_genlaguerre, 3, -1.1)
+
+
+def test_gh_6721():
+    # Regression test for gh_6721. This should not raise.
+    sc.chebyt(65)(0.2)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a4f379effdc9c3aa18bd2948fbd9f716b1f8d57
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_orthogonal_eval.py
@@ -0,0 +1,275 @@
+import numpy as np
+from numpy.testing import assert_, assert_allclose
+import pytest
+
+from scipy.special import _ufuncs
+import scipy.special._orthogonal as orth
+from scipy.special._testutils import FuncData
+
+
+def test_eval_chebyt():
+    n = np.arange(0, 10000, 7, dtype=np.dtype("long"))
+    x = 2*np.random.rand() - 1
+    v1 = np.cos(n*np.arccos(x))
+    v2 = _ufuncs.eval_chebyt(n, x)
+    assert_(np.allclose(v1, v2, rtol=1e-15))
+
+
+def test_eval_chebyt_gh20129():
+    # https://github.com/scipy/scipy/issues/20129
+    assert _ufuncs.eval_chebyt(7, 2 + 0j) == 5042.0
+
+
+def test_eval_genlaguerre_restriction():
+    # check it returns nan for alpha <= -1
+    assert_(np.isnan(_ufuncs.eval_genlaguerre(0, -1, 0)))
+    assert_(np.isnan(_ufuncs.eval_genlaguerre(0.1, -1, 0)))
+
+
+def test_warnings():
+    # ticket 1334
+    with np.errstate(all='raise'):
+        # these should raise no fp warnings
+        _ufuncs.eval_legendre(1, 0)
+        _ufuncs.eval_laguerre(1, 1)
+        _ufuncs.eval_gegenbauer(1, 1, 0)
+
+
+class TestPolys:
+    """
+    Check that the eval_* functions agree with the constructed polynomials
+
+    """
+
+    def check_poly(self, func, cls, param_ranges=(), x_range=(), nn=10,
+                   nparam=10, nx=10, rtol=1e-8):
+        rng = np.random.RandomState(1234)
+
+        dataset = []
+        for n in np.arange(nn):
+            params = [a + (b-a)*rng.rand(nparam) for a,b in param_ranges]
+            params = np.asarray(params).T
+            if not param_ranges:
+                params = [0]
+            for p in params:
+                if param_ranges:
+                    p = (n,) + tuple(p)
+                else:
+                    p = (n,)
+                x = x_range[0] + (x_range[1] - x_range[0])*rng.rand(nx)
+                x[0] = x_range[0]  # always include domain start point
+                x[1] = x_range[1]  # always include domain end point
+                poly = np.poly1d(cls(*p).coef)
+                z = np.c_[np.tile(p, (nx,1)), x, poly(x)]
+                dataset.append(z)
+
+        dataset = np.concatenate(dataset, axis=0)
+
+        def polyfunc(*p):
+            p = (p[0].astype(np.dtype("long")),) + p[1:]
+            return func(*p)
+
+        with np.errstate(all='raise'):
+            ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1,
+                          rtol=rtol)
+            ds.check()
+
+    def test_jacobi(self):
+        self.check_poly(_ufuncs.eval_jacobi, orth.jacobi,
+                        param_ranges=[(-0.99, 10), (-0.99, 10)],
+                        x_range=[-1, 1], rtol=1e-5)
+
+    def test_sh_jacobi(self):
+        self.check_poly(_ufuncs.eval_sh_jacobi, orth.sh_jacobi,
+                        param_ranges=[(1, 10), (0, 1)], x_range=[0, 1],
+                        rtol=1e-5)
+
+    def test_gegenbauer(self):
+        self.check_poly(_ufuncs.eval_gegenbauer, orth.gegenbauer,
+                        param_ranges=[(-0.499, 10)], x_range=[-1, 1],
+                        rtol=1e-7)
+
+    def test_chebyt(self):
+        self.check_poly(_ufuncs.eval_chebyt, orth.chebyt,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_chebyu(self):
+        self.check_poly(_ufuncs.eval_chebyu, orth.chebyu,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_chebys(self):
+        self.check_poly(_ufuncs.eval_chebys, orth.chebys,
+                        param_ranges=[], x_range=[-2, 2])
+
+    def test_chebyc(self):
+        self.check_poly(_ufuncs.eval_chebyc, orth.chebyc,
+                        param_ranges=[], x_range=[-2, 2])
+
+    def test_sh_chebyt(self):
+        with np.errstate(all='ignore'):
+            self.check_poly(_ufuncs.eval_sh_chebyt, orth.sh_chebyt,
+                            param_ranges=[], x_range=[0, 1])
+
+    def test_sh_chebyu(self):
+        self.check_poly(_ufuncs.eval_sh_chebyu, orth.sh_chebyu,
+                        param_ranges=[], x_range=[0, 1])
+
+    def test_legendre(self):
+        self.check_poly(_ufuncs.eval_legendre, orth.legendre,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_sh_legendre(self):
+        with np.errstate(all='ignore'):
+            self.check_poly(_ufuncs.eval_sh_legendre, orth.sh_legendre,
+                            param_ranges=[], x_range=[0, 1])
+
+    def test_genlaguerre(self):
+        self.check_poly(_ufuncs.eval_genlaguerre, orth.genlaguerre,
+                        param_ranges=[(-0.99, 10)], x_range=[0, 100])
+
+    def test_laguerre(self):
+        self.check_poly(_ufuncs.eval_laguerre, orth.laguerre,
+                        param_ranges=[], x_range=[0, 100])
+
+    def test_hermite(self):
+        self.check_poly(_ufuncs.eval_hermite, orth.hermite,
+                        param_ranges=[], x_range=[-100, 100])
+
+    def test_hermitenorm(self):
+        self.check_poly(_ufuncs.eval_hermitenorm, orth.hermitenorm,
+                        param_ranges=[], x_range=[-100, 100])
+
+
+class TestRecurrence:
+    """
+    Check that the eval_* functions sig='ld->d' and 'dd->d' agree.
+
+    """
+
+    def check_poly(self, func, param_ranges=(), x_range=(), nn=10,
+                   nparam=10, nx=10, rtol=1e-8):
+        np.random.seed(1234)
+
+        dataset = []
+        for n in np.arange(nn):
+            params = [a + (b-a)*np.random.rand(nparam) for a,b in param_ranges]
+            params = np.asarray(params).T
+            if not param_ranges:
+                params = [0]
+            for p in params:
+                if param_ranges:
+                    p = (n,) + tuple(p)
+                else:
+                    p = (n,)
+                x = x_range[0] + (x_range[1] - x_range[0])*np.random.rand(nx)
+                x[0] = x_range[0]  # always include domain start point
+                x[1] = x_range[1]  # always include domain end point
+                kw = dict(sig=(len(p)+1)*'d'+'->d')
+                z = np.c_[np.tile(p, (nx,1)), x, func(*(p + (x,)), **kw)]
+                dataset.append(z)
+
+        dataset = np.concatenate(dataset, axis=0)
+
+        def polyfunc(*p):
+            p0 = p[0].astype(np.intp)
+            p = (p0,) + p[1:]
+            p0_type_char = p0.dtype.char
+            kw = dict(sig=p0_type_char + (len(p)-1)*'d' + '->d')
+            return func(*p, **kw)
+
+        with np.errstate(all='raise'):
+            ds = FuncData(polyfunc, dataset, list(range(len(param_ranges)+2)), -1,
+                          rtol=rtol)
+            ds.check()
+
+    def test_jacobi(self):
+        self.check_poly(_ufuncs.eval_jacobi,
+                        param_ranges=[(-0.99, 10), (-0.99, 10)],
+                        x_range=[-1, 1])
+
+    def test_sh_jacobi(self):
+        self.check_poly(_ufuncs.eval_sh_jacobi,
+                        param_ranges=[(1, 10), (0, 1)], x_range=[0, 1])
+
+    def test_gegenbauer(self):
+        self.check_poly(_ufuncs.eval_gegenbauer,
+                        param_ranges=[(-0.499, 10)], x_range=[-1, 1])
+
+    def test_chebyt(self):
+        self.check_poly(_ufuncs.eval_chebyt,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_chebyu(self):
+        self.check_poly(_ufuncs.eval_chebyu,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_chebys(self):
+        self.check_poly(_ufuncs.eval_chebys,
+                        param_ranges=[], x_range=[-2, 2])
+
+    def test_chebyc(self):
+        self.check_poly(_ufuncs.eval_chebyc,
+                        param_ranges=[], x_range=[-2, 2])
+
+    def test_sh_chebyt(self):
+        self.check_poly(_ufuncs.eval_sh_chebyt,
+                        param_ranges=[], x_range=[0, 1])
+
+    def test_sh_chebyu(self):
+        self.check_poly(_ufuncs.eval_sh_chebyu,
+                        param_ranges=[], x_range=[0, 1])
+
+    def test_legendre(self):
+        self.check_poly(_ufuncs.eval_legendre,
+                        param_ranges=[], x_range=[-1, 1])
+
+    def test_sh_legendre(self):
+        self.check_poly(_ufuncs.eval_sh_legendre,
+                        param_ranges=[], x_range=[0, 1])
+
+    def test_genlaguerre(self):
+        self.check_poly(_ufuncs.eval_genlaguerre,
+                        param_ranges=[(-0.99, 10)], x_range=[0, 100])
+
+    def test_laguerre(self):
+        self.check_poly(_ufuncs.eval_laguerre,
+                        param_ranges=[], x_range=[0, 100])
+
+    def test_hermite(self):
+        v = _ufuncs.eval_hermite(70, 1.0)
+        a = -1.457076485701412e60
+        assert_allclose(v, a)
+
+
+def test_hermite_domain():
+    # Regression test for gh-11091.
+    assert np.isnan(_ufuncs.eval_hermite(-1, 1.0))
+    assert np.isnan(_ufuncs.eval_hermitenorm(-1, 1.0))
+
+
+@pytest.mark.parametrize("n", [0, 1, 2])
+@pytest.mark.parametrize("x", [0, 1, np.nan])
+def test_hermite_nan(n, x):
+    # Regression test for gh-11369.
+    assert np.isnan(_ufuncs.eval_hermite(n, x)) == np.any(np.isnan([n, x]))
+    assert np.isnan(_ufuncs.eval_hermitenorm(n, x)) == np.any(np.isnan([n, x]))
+
+
+@pytest.mark.parametrize('n', [0, 1, 2, 3.2])
+@pytest.mark.parametrize('alpha', [1, np.nan])
+@pytest.mark.parametrize('x', [2, np.nan])
+def test_genlaguerre_nan(n, alpha, x):
+    # Regression test for gh-11361.
+    nan_laguerre = np.isnan(_ufuncs.eval_genlaguerre(n, alpha, x))
+    nan_arg = np.any(np.isnan([n, alpha, x]))
+    assert nan_laguerre == nan_arg
+
+
+@pytest.mark.parametrize('n', [0, 1, 2, 3.2])
+@pytest.mark.parametrize('alpha', [0.0, 1, np.nan])
+@pytest.mark.parametrize('x', [1e-6, 2, np.nan])
+def test_gegenbauer_nan(n, alpha, x):
+    # Regression test for gh-11370.
+    nan_gegenbauer = np.isnan(_ufuncs.eval_gegenbauer(n, alpha, x))
+    nan_arg = np.any(np.isnan([n, alpha, x]))
+    assert nan_gegenbauer == nan_arg
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d15aead25302023c5f07d8392c0931995764ced
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_owens_t.py
@@ -0,0 +1,53 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+
+import scipy.special as sc
+
+
+def test_symmetries():
+    np.random.seed(1234)
+    a, h = np.random.rand(100), np.random.rand(100)
+    assert_equal(sc.owens_t(h, a), sc.owens_t(-h, a))
+    assert_equal(sc.owens_t(h, a), -sc.owens_t(h, -a))
+
+
+def test_special_cases():
+    assert_equal(sc.owens_t(5, 0), 0)
+    assert_allclose(sc.owens_t(0, 5), 0.5*np.arctan(5)/np.pi,
+                    rtol=5e-14)
+    # Target value is 0.5*Phi(5)*(1 - Phi(5)) for Phi the CDF of the
+    # standard normal distribution
+    assert_allclose(sc.owens_t(5, 1), 1.4332574485503512543e-07,
+                    rtol=5e-14)
+
+
+def test_nans():
+    assert_equal(sc.owens_t(20, np.nan), np.nan)
+    assert_equal(sc.owens_t(np.nan, 20), np.nan)
+    assert_equal(sc.owens_t(np.nan, np.nan), np.nan)
+
+
+def test_infs():
+    h, a = 0, np.inf
+    # T(0, a) = 1/2π * arctan(a)
+    res = 1/(2*np.pi) * np.arctan(a)
+    assert_allclose(sc.owens_t(h, a), res, rtol=5e-14)
+    assert_allclose(sc.owens_t(h, -a), -res, rtol=5e-14)
+
+    h = 1
+    # Refer Owens T function definition in Wikipedia
+    # https://en.wikipedia.org/wiki/Owen%27s_T_function
+    # Value approximated through Numerical Integration
+    # using scipy.integrate.quad
+    # quad(lambda x: 1/(2*pi)*(exp(-0.5*(1*1)*(1+x*x))/(1+x*x)), 0, inf)
+    res = 0.07932762696572854
+    assert_allclose(sc.owens_t(h, np.inf), res, rtol=5e-14)
+    assert_allclose(sc.owens_t(h, -np.inf), -res, rtol=5e-14)
+
+    assert_equal(sc.owens_t(np.inf, 1), 0)
+    assert_equal(sc.owens_t(-np.inf, 1), 0)
+
+    assert_equal(sc.owens_t(np.inf, np.inf), 0)
+    assert_equal(sc.owens_t(-np.inf, np.inf), 0)
+    assert_equal(sc.owens_t(np.inf, -np.inf), -0.0)
+    assert_equal(sc.owens_t(-np.inf, -np.inf), -0.0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8c42aa688081fb58f79ad2c8ea932d03b33523b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pcf.py
@@ -0,0 +1,24 @@
+"""Tests for parabolic cylinder functions.
+
+"""
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+import scipy.special as sc
+
+
+def test_pbwa_segfault():
+    # Regression test for https://github.com/scipy/scipy/issues/6208.
+    #
+    # Data generated by mpmath.
+    #
+    w = 1.02276567211316867161
+    wp = -0.48887053372346189882
+    assert_allclose(sc.pbwa(0, 0), (w, wp), rtol=1e-13, atol=0)
+
+
+def test_pbwa_nan():
+    # Check that NaN's are returned outside of the range in which the
+    # implementation is accurate.
+    pts = [(-6, -6), (-6, 6), (6, -6), (6, 6)]
+    for p in pts:
+        assert_equal(sc.pbwa(*p), (np.nan, np.nan))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py
new file mode 100644
index 0000000000000000000000000000000000000000..122e6009bd71e77ae39f55da5cf056500ff526a9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_pdtr.py
@@ -0,0 +1,48 @@
+import numpy as np
+import scipy.special as sc
+from numpy.testing import assert_almost_equal, assert_array_equal
+
+
+class TestPdtr:
+    def test(self):
+        val = sc.pdtr(0, 1)
+        assert_almost_equal(val, np.exp(-1))
+
+    def test_m_zero(self):
+        val = sc.pdtr([0, 1, 2], 0)
+        assert_array_equal(val, [1, 1, 1])
+
+    def test_rounding(self):
+        double_val = sc.pdtr([0.1, 1.1, 2.1], 1.0)
+        int_val = sc.pdtr([0, 1, 2], 1.0)
+        assert_array_equal(double_val, int_val)
+
+    def test_inf(self):
+        val = sc.pdtr(np.inf, 1.0)
+        assert_almost_equal(val, 1.0)
+
+    def test_domain(self):
+        val = sc.pdtr(-1.1, 1.0)
+        assert np.isnan(val)
+
+class TestPdtrc:
+    def test_value(self):
+        val = sc.pdtrc(0, 1)
+        assert_almost_equal(val, 1 - np.exp(-1))
+
+    def test_m_zero(self):
+        val = sc.pdtrc([0, 1, 2], 0.0)
+        assert_array_equal(val, [0, 0, 0])
+
+    def test_rounding(self):
+        double_val = sc.pdtrc([0.1, 1.1, 2.1], 1.0)
+        int_val = sc.pdtrc([0, 1, 2], 1.0)
+        assert_array_equal(double_val, int_val)
+
+    def test_inf(self):
+        val = sc.pdtrc(np.inf, 1.0)
+        assert_almost_equal(val, 0.0)
+
+    def test_domain(self):
+        val = sc.pdtrc(-1.1, 1.0)
+        assert np.isnan(val)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d809963f64ddaedf6b59de80dcd5f7ca8fa18a9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_powm1.py
@@ -0,0 +1,65 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+from scipy.special import powm1
+
+
+# Expected values were computed with mpmath, e.g.
+#
+#   >>> import mpmath
+#   >>> mpmath.np.dps = 200
+#   >>> print(float(mpmath.powm1(2.0, 1e-7))
+#   6.931472045825965e-08
+#
+powm1_test_cases = [
+    (1.25, 0.75, 0.18217701125396976, 1e-15),
+    (2.0, 1e-7, 6.931472045825965e-08, 1e-15),
+    (25.0, 5e-11, 1.6094379125636148e-10, 1e-15),
+    (0.99996, 0.75, -3.0000150002530058e-05, 1e-15),
+    (0.9999999999990905, 20, -1.81898940353014e-11, 1e-15),
+    (-1.25, 751.0, -6.017550852453444e+72, 2e-15)
+]
+
+
+@pytest.mark.parametrize('x, y, expected, rtol', powm1_test_cases)
+def test_powm1(x, y, expected, rtol):
+    p = powm1(x, y)
+    assert_allclose(p, expected, rtol=rtol)
+
+
+@pytest.mark.parametrize('x, y, expected',
+                         [(0.0, 0.0, 0.0),
+                          (0.0, -1.5, np.inf),
+                          (0.0, 1.75, -1.0),
+                          (-1.5, 2.0, 1.25),
+                          (-1.5, 3.0, -4.375),
+                          (np.nan, 0.0, 0.0),
+                          (1.0, np.nan, 0.0),
+                          (1.0, np.inf, 0.0),
+                          (1.0, -np.inf, 0.0),
+                          (np.inf, 7.5, np.inf),
+                          (np.inf, -7.5, -1.0),
+                          (3.25, np.inf, np.inf),
+                          (np.inf, np.inf, np.inf),
+                          (np.inf, -np.inf, -1.0),
+                          (np.inf, 0.0, 0.0),
+                          (-np.inf, 0.0, 0.0),
+                          (-np.inf, 2.0, np.inf),
+                          (-np.inf, 3.0, -np.inf),
+                          (-1.0, float(2**53 - 1), -2.0)])
+def test_powm1_exact_cases(x, y, expected):
+    # Test cases where we have an exact expected value.
+    p = powm1(x, y)
+    assert p == expected
+
+
+@pytest.mark.parametrize('x, y',
+                         [(-1.25, 751.03),
+                          (-1.25, np.inf),
+                          (np.nan, np.nan),
+                          (-np.inf, -np.inf),
+                          (-np.inf, 2.5)])
+def test_powm1_return_nan(x, y):
+    # Test cases where the expected return value is nan.
+    p = powm1(x, y)
+    assert np.isnan(p)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b6c6cba21d5c1d5fdfab879153ba8f125e98d5f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_expn_asy.py
@@ -0,0 +1,24 @@
+from numpy.testing import assert_equal
+
+from scipy.special._testutils import check_version, MissingModule
+from scipy.special._precompute.expn_asy import generate_A
+
+try:
+    import sympy
+    from sympy import Poly
+except ImportError:
+    sympy = MissingModule("sympy")
+
+
+@check_version(sympy, "1.0")
+def test_generate_A():
+    # Data from DLMF 8.20.5
+    x = sympy.symbols('x')
+    Astd = [Poly(1, x),
+            Poly(1, x),
+            Poly(1 - 2*x),
+            Poly(1 - 8*x + 6*x**2)]
+    Ares = generate_A(len(Astd))
+
+    for p, q in zip(Astd, Ares):
+        assert_equal(p, q)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0c46b456d0a1b545b29e0b8b81b39dafb6b0610
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_gammainc.py
@@ -0,0 +1,108 @@
+import pytest
+
+from scipy.special._testutils import MissingModule, check_version
+from scipy.special._mptestutils import (
+    Arg, IntArg, mp_assert_allclose, assert_mpmath_equal)
+from scipy.special._precompute.gammainc_asy import (
+    compute_g, compute_alpha, compute_d)
+from scipy.special._precompute.gammainc_data import gammainc, gammaincc
+
+try:
+    import sympy
+except ImportError:
+    sympy = MissingModule('sympy')
+
+try:
+    import mpmath as mp
+except ImportError:
+    mp = MissingModule('mpmath')
+
+
+@check_version(mp, '0.19')
+def test_g():
+    # Test data for the g_k. See DLMF 5.11.4.
+    with mp.workdps(30):
+        g = [mp.mpf(1), mp.mpf(1)/12, mp.mpf(1)/288,
+             -mp.mpf(139)/51840, -mp.mpf(571)/2488320,
+             mp.mpf(163879)/209018880, mp.mpf(5246819)/75246796800]
+        mp_assert_allclose(compute_g(7), g)
+
+
+@pytest.mark.slow
+@check_version(mp, '0.19')
+@check_version(sympy, '0.7')
+@pytest.mark.xfail_on_32bit("rtol only 2e-11, see gh-6938")
+def test_alpha():
+    # Test data for the alpha_k. See DLMF 8.12.14.
+    with mp.workdps(30):
+        alpha = [mp.mpf(0), mp.mpf(1), mp.mpf(1)/3, mp.mpf(1)/36,
+                 -mp.mpf(1)/270, mp.mpf(1)/4320, mp.mpf(1)/17010,
+                 -mp.mpf(139)/5443200, mp.mpf(1)/204120]
+        mp_assert_allclose(compute_alpha(9), alpha)
+
+
+@pytest.mark.xslow
+@check_version(mp, '0.19')
+@check_version(sympy, '0.7')
+def test_d():
+    # Compare the d_{k, n} to the results in appendix F of [1].
+    #
+    # Sources
+    # -------
+    # [1] DiDonato and Morris, Computation of the Incomplete Gamma
+    #     Function Ratios and their Inverse, ACM Transactions on
+    #     Mathematical Software, 1986.
+
+    with mp.workdps(50):
+        dataset = [(0, 0, -mp.mpf('0.333333333333333333333333333333')),
+                   (0, 12, mp.mpf('0.102618097842403080425739573227e-7')),
+                   (1, 0, -mp.mpf('0.185185185185185185185185185185e-2')),
+                   (1, 12, mp.mpf('0.119516285997781473243076536700e-7')),
+                   (2, 0, mp.mpf('0.413359788359788359788359788360e-2')),
+                   (2, 12, -mp.mpf('0.140925299108675210532930244154e-7')),
+                   (3, 0, mp.mpf('0.649434156378600823045267489712e-3')),
+                   (3, 12, -mp.mpf('0.191111684859736540606728140873e-7')),
+                   (4, 0, -mp.mpf('0.861888290916711698604702719929e-3')),
+                   (4, 12, mp.mpf('0.288658297427087836297341274604e-7')),
+                   (5, 0, -mp.mpf('0.336798553366358150308767592718e-3')),
+                   (5, 12, mp.mpf('0.482409670378941807563762631739e-7')),
+                   (6, 0, mp.mpf('0.531307936463992223165748542978e-3')),
+                   (6, 12, -mp.mpf('0.882860074633048352505085243179e-7')),
+                   (7, 0, mp.mpf('0.344367606892377671254279625109e-3')),
+                   (7, 12, -mp.mpf('0.175629733590604619378669693914e-6')),
+                   (8, 0, -mp.mpf('0.652623918595309418922034919727e-3')),
+                   (8, 12, mp.mpf('0.377358774161109793380344937299e-6')),
+                   (9, 0, -mp.mpf('0.596761290192746250124390067179e-3')),
+                   (9, 12, mp.mpf('0.870823417786464116761231237189e-6'))]
+        d = compute_d(10, 13)
+        res = [d[k][n] for k, n, std in dataset]
+        std = [x[2] for x in dataset]
+        mp_assert_allclose(res, std)
+
+
+@check_version(mp, '0.19')
+def test_gammainc():
+    # Quick check that the gammainc in
+    # special._precompute.gammainc_data agrees with mpmath's
+    # gammainc.
+    assert_mpmath_equal(gammainc,
+                        lambda a, x: mp.gammainc(a, b=x, regularized=True),
+                        [Arg(0, 100, inclusive_a=False), Arg(0, 100)],
+                        nan_ok=False, rtol=1e-17, n=50, dps=50)
+
+
+@pytest.mark.xslow
+@check_version(mp, '0.19')
+def test_gammaincc():
+    # Check that the gammaincc in special._precompute.gammainc_data
+    # agrees with mpmath's gammainc.
+    assert_mpmath_equal(lambda a, x: gammaincc(a, x, dps=1000),
+                        lambda a, x: mp.gammainc(a, a=x, regularized=True),
+                        [Arg(20, 100), Arg(20, 100)],
+                        nan_ok=False, rtol=1e-17, n=50, dps=1000)
+
+    # Test the fast integer path
+    assert_mpmath_equal(gammaincc,
+                        lambda a, x: mp.gammainc(a, a=x, regularized=True),
+                        [IntArg(1, 100), Arg(0, 100)],
+                        nan_ok=False, rtol=1e-17, n=50, dps=50)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..89616b92329691ca76039fe11a7e08f7f3db1150
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_precompute_utils.py
@@ -0,0 +1,36 @@
+import pytest
+
+from scipy.special._testutils import MissingModule, check_version
+from scipy.special._mptestutils import mp_assert_allclose
+from scipy.special._precompute.utils import lagrange_inversion
+
+try:
+    import sympy
+except ImportError:
+    sympy = MissingModule('sympy')
+
+try:
+    import mpmath as mp
+except ImportError:
+    mp = MissingModule('mpmath')
+
+
+@pytest.mark.slow
+@check_version(sympy, '0.7')
+@check_version(mp, '0.19')
+class TestInversion:
+    @pytest.mark.xfail_on_32bit("rtol only 2e-9, see gh-6938")
+    def test_log(self):
+        with mp.workdps(30):
+            logcoeffs = mp.taylor(lambda x: mp.log(1 + x), 0, 10)
+            expcoeffs = mp.taylor(lambda x: mp.exp(x) - 1, 0, 10)
+            invlogcoeffs = lagrange_inversion(logcoeffs)
+            mp_assert_allclose(invlogcoeffs, expcoeffs)
+
+    @pytest.mark.xfail_on_32bit("rtol only 1e-15, see gh-6938")
+    def test_sin(self):
+        with mp.workdps(30):
+            sincoeffs = mp.taylor(mp.sin, 0, 10)
+            asincoeffs = mp.taylor(mp.asin, 0, 10)
+            invsincoeffs = lagrange_inversion(sincoeffs)
+            mp_assert_allclose(invsincoeffs, asincoeffs, atol=1e-30)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba28b7c1cff95327df0ed69086dd92b93399c3c4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_round.py
@@ -0,0 +1,18 @@
+import numpy as np
+import pytest
+
+from scipy.special import _test_internal
+
+
+@pytest.mark.fail_slow(20)
+@pytest.mark.skipif(not _test_internal.have_fenv(), reason="no fenv()")
+def test_add_round_up():
+    rng = np.random.RandomState(1234)
+    _test_internal.test_add_round(10**5, 'up', rng)
+
+
+@pytest.mark.fail_slow(20)
+@pytest.mark.skipif(not _test_internal.have_fenv(), reason="no fenv()")
+def test_add_round_down():
+    rng = np.random.RandomState(1234)
+    _test_internal.test_add_round(10**5, 'down', rng)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dfe8287ee4f53a51a5654edc975c5c521a7d747
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sf_error.py
@@ -0,0 +1,145 @@
+import sys
+import warnings
+
+import numpy as np
+from numpy.testing import assert_, assert_equal, IS_PYPY
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.special as sc
+from scipy.special._ufuncs import _sf_error_test_function
+
+_sf_error_code_map = {
+    # skip 'ok'
+    'singular': 1,
+    'underflow': 2,
+    'overflow': 3,
+    'slow': 4,
+    'loss': 5,
+    'no_result': 6,
+    'domain': 7,
+    'arg': 8,
+    'other': 9,
+    'memory': 10,
+}
+
+_sf_error_actions = [
+    'ignore',
+    'warn',
+    'raise'
+]
+
+
+def _check_action(fun, args, action):
+    # TODO: special expert should correct
+    # the coercion at the true location?
+    args = np.asarray(args, dtype=np.dtype("long"))
+    if action == 'warn':
+        with pytest.warns(sc.SpecialFunctionWarning):
+            fun(*args)
+    elif action == 'raise':
+        with assert_raises(sc.SpecialFunctionError):
+            fun(*args)
+    else:
+        # action == 'ignore', make sure there are no warnings/exceptions
+        with warnings.catch_warnings():
+            warnings.simplefilter("error")
+            fun(*args)
+
+
+def test_geterr():
+    err = sc.geterr()
+    for key, value in err.items():
+        assert_(key in _sf_error_code_map)
+        assert_(value in _sf_error_actions)
+
+
+@pytest.mark.thread_unsafe
+def test_seterr():
+    entry_err = sc.geterr()
+    try:
+        for category, error_code in _sf_error_code_map.items():
+            for action in _sf_error_actions:
+                geterr_olderr = sc.geterr()
+                seterr_olderr = sc.seterr(**{category: action})
+                assert_(geterr_olderr == seterr_olderr)
+                newerr = sc.geterr()
+                assert_(newerr[category] == action)
+                geterr_olderr.pop(category)
+                newerr.pop(category)
+                assert_(geterr_olderr == newerr)
+                _check_action(_sf_error_test_function, (error_code,), action)
+    finally:
+        sc.seterr(**entry_err)
+
+
+@pytest.mark.skipif(IS_PYPY, reason="Test not meaningful on PyPy")
+def test_sf_error_special_refcount():
+    # Regression test for gh-16233.
+    # Check that the reference count of scipy.special is not increased
+    # when a SpecialFunctionError is raised.
+    refcount_before = sys.getrefcount(sc)
+    with sc.errstate(all='raise'):
+        with pytest.raises(sc.SpecialFunctionError, match='domain error'):
+            sc.ndtri(2.0)
+    refcount_after = sys.getrefcount(sc)
+    assert refcount_after == refcount_before
+
+
+def test_errstate_pyx_basic():
+    olderr = sc.geterr()
+    with sc.errstate(singular='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.loggamma(0)
+    assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_c_basic():
+    olderr = sc.geterr()
+    with sc.errstate(domain='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.spence(-1)
+    assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_cpp_basic():
+    olderr = sc.geterr()
+    with sc.errstate(underflow='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.wrightomega(-1000)
+    assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_cpp_scipy_special():
+    olderr = sc.geterr()
+    with sc.errstate(singular='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.lambertw(0, 1)
+    assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_cpp_alt_ufunc_machinery():
+    olderr = sc.geterr()
+    with sc.errstate(singular='raise'):
+        with assert_raises(sc.SpecialFunctionError):
+            sc.gammaln(0)
+    assert_equal(olderr, sc.geterr())
+
+
+@pytest.mark.thread_unsafe
+def test_errstate():
+    for category, error_code in _sf_error_code_map.items():
+        for action in _sf_error_actions:
+            olderr = sc.geterr()
+            with sc.errstate(**{category: action}):
+                _check_action(_sf_error_test_function, (error_code,), action)
+            assert_equal(olderr, sc.geterr())
+
+
+def test_errstate_all_but_one():
+    olderr = sc.geterr()
+    with sc.errstate(all='raise', singular='ignore'):
+        sc.gammaln(0)
+        with assert_raises(sc.SpecialFunctionError):
+            sc.spence(-1.0)
+    assert_equal(olderr, sc.geterr())
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py
new file mode 100644
index 0000000000000000000000000000000000000000..d33c1795641ba74f777fcfdcffe80d86463477e3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sici.py
@@ -0,0 +1,36 @@
+import numpy as np
+
+import scipy.special as sc
+from scipy.special._testutils import FuncData
+
+
+def test_sici_consistency():
+    # Make sure the implementation of sici for real arguments agrees
+    # with the implementation of sici for complex arguments.
+
+    # On the negative real axis Cephes drops the imaginary part in ci
+    def sici(x):
+        si, ci = sc.sici(x + 0j)
+        return si.real, ci.real
+    
+    x = np.r_[-np.logspace(8, -30, 200), 0, np.logspace(-30, 8, 200)]
+    si, ci = sc.sici(x)
+    dataset = np.column_stack((x, si, ci))
+    FuncData(sici, dataset, 0, (1, 2), rtol=1e-12).check()
+
+
+def test_shichi_consistency():
+    # Make sure the implementation of shichi for real arguments agrees
+    # with the implementation of shichi for complex arguments.
+
+    # On the negative real axis Cephes drops the imaginary part in chi
+    def shichi(x):
+        shi, chi = sc.shichi(x + 0j)
+        return shi.real, chi.real
+
+    # Overflow happens quickly, so limit range
+    x = np.r_[-np.logspace(np.log10(700), -30, 200), 0,
+              np.logspace(-30, np.log10(700), 200)]
+    shi, chi = sc.shichi(x)
+    dataset = np.column_stack((x, shi, chi))
+    FuncData(shichi, dataset, 0, (1, 2), rtol=1e-14).check()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py
new file mode 100644
index 0000000000000000000000000000000000000000..f36fd2915be8c8d14138493c34dfd5733a2a1e6d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_specfun.py
@@ -0,0 +1,48 @@
+"""
+Various made-up tests to hit different branches of the code in specfun.c
+"""
+
+import numpy as np
+from numpy.testing import assert_allclose
+from scipy import special
+
+
+def test_cva2_cv0_branches():
+    res, resp = special.mathieu_cem([40, 129], [13, 14], [30, 45])
+    assert_allclose(res, np.array([-0.3741211, 0.74441928]))
+    assert_allclose(resp, np.array([-37.02872758, -86.13549877]))
+
+    res, resp = special.mathieu_sem([40, 129], [13, 14], [30, 45])
+    assert_allclose(res, np.array([0.92955551, 0.66771207]))
+    assert_allclose(resp, np.array([-14.91073448, 96.02954185]))
+
+
+def test_chgm_branches():
+    res = special.eval_genlaguerre(-3.2, 3, 2.5)
+    assert_allclose(res, -0.7077721935779854)
+
+
+def test_hygfz_branches():
+    """(z == 1.0) && (c-a-b > 0.0)"""
+    res = special.hyp2f1(1.5, 2.5, 4.5, 1.+0.j)
+    assert_allclose(res, 10.30835089459151+0j)
+    """(cabs(z+1) < eps) && (fabs(c-a+b - 1.0) < eps)"""
+    res = special.hyp2f1(5+5e-16, 2, 2, -1.0 + 5e-16j)
+    assert_allclose(res, 0.031249999999999986+3.9062499999999994e-17j)
+
+
+def test_pro_rad1():
+    # https://github.com/scipy/scipy/issues/21058
+    # Reference values taken from WolframAlpha
+    # SpheroidalS1(1, 1, 30, 1.1)
+    # SpheroidalS1Prime(1, 1, 30, 1.1)
+    res = special.pro_rad1(1, 1, 30, 1.1)
+    assert_allclose(res, (0.009657872296166435, 3.253369651472877), rtol=2e-5)
+
+def test_pro_rad2():
+    # https://github.com/scipy/scipy/issues/21461
+    # Reference values taken from WolframAlpha
+    # SpheroidalS2(0, 0, 3, 1.02)
+    # SpheroidalS2Prime(0, 0, 3, 1.02)
+    res = special.pro_rad2(0, 0, 3, 1.02)
+    assert_allclose(res, (-0.35089596858528077, 13.652764213480872), rtol=10e-10)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbb26ac281dff81ea71b30318731065fe5a78f94
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spence.py
@@ -0,0 +1,32 @@
+import numpy as np
+from numpy import sqrt, log, pi
+from scipy.special._testutils import FuncData
+from scipy.special import spence
+
+
+def test_consistency():
+    # Make sure the implementation of spence for real arguments
+    # agrees with the implementation of spence for imaginary arguments.
+
+    x = np.logspace(-30, 300, 200)
+    dataset = np.vstack((x + 0j, spence(x))).T
+    FuncData(spence, dataset, 0, 1, rtol=1e-14).check()
+
+
+def test_special_points():
+    # Check against known values of Spence's function.
+
+    phi = (1 + sqrt(5))/2
+    dataset = [(1, 0),
+               (2, -pi**2/12),
+               (0.5, pi**2/12 - log(2)**2/2),
+               (0, pi**2/6),
+               (-1, pi**2/4 - 1j*pi*log(2)),
+               ((-1 + sqrt(5))/2, pi**2/15 - log(phi)**2),
+               ((3 - sqrt(5))/2, pi**2/10 - log(phi)**2),
+               (phi, -pi**2/15 + log(phi)**2/2),
+               # Corrected from Zagier, "The Dilogarithm Function"
+               ((3 + sqrt(5))/2, -pi**2/10 - log(phi)**2)]
+
+    dataset = np.asarray(dataset)
+    FuncData(spence, dataset, 0, 1, rtol=1e-14).check()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4a047c78fb8542bd0abbb75a4815d777e1414b0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spfun_stats.py
@@ -0,0 +1,61 @@
+import numpy as np
+from numpy.testing import (assert_array_equal,
+        assert_array_almost_equal_nulp, assert_almost_equal)
+from pytest import raises as assert_raises
+
+from scipy.special import gammaln, multigammaln
+
+
+class TestMultiGammaLn:
+
+    def test1(self):
+        # A test of the identity
+        #     Gamma_1(a) = Gamma(a)
+        np.random.seed(1234)
+        a = np.abs(np.random.randn())
+        assert_array_equal(multigammaln(a, 1), gammaln(a))
+
+    def test2(self):
+        # A test of the identity
+        #     Gamma_2(a) = sqrt(pi) * Gamma(a) * Gamma(a - 0.5)
+        a = np.array([2.5, 10.0])
+        result = multigammaln(a, 2)
+        expected = np.log(np.sqrt(np.pi)) + gammaln(a) + gammaln(a - 0.5)
+        assert_almost_equal(result, expected)
+
+    def test_bararg(self):
+        assert_raises(ValueError, multigammaln, 0.5, 1.2)
+
+
+def _check_multigammaln_array_result(a, d):
+    # Test that the shape of the array returned by multigammaln
+    # matches the input shape, and that all the values match
+    # the value computed when multigammaln is called with a scalar.
+    result = multigammaln(a, d)
+    assert_array_equal(a.shape, result.shape)
+    a1 = a.ravel()
+    result1 = result.ravel()
+    for i in range(a.size):
+        assert_array_almost_equal_nulp(result1[i], multigammaln(a1[i], d))
+
+
+def test_multigammaln_array_arg():
+    # Check that the array returned by multigammaln has the correct
+    # shape and contains the correct values.  The cases have arrays
+    # with several different shapes.
+    # The cases include a regression test for ticket #1849
+    # (a = np.array([2.0]), an array with a single element).
+    np.random.seed(1234)
+
+    cases = [
+        # a, d
+        (np.abs(np.random.randn(3, 2)) + 5, 5),
+        (np.abs(np.random.randn(1, 2)) + 5, 5),
+        (np.arange(10.0, 18.0).reshape(2, 2, 2), 3),
+        (np.array([2.0]), 3),
+        (np.float64(2.0), 3),
+    ]
+
+    for a, d in cases:
+        _check_multigammaln_array_result(a, d)
+
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py
new file mode 100644
index 0000000000000000000000000000000000000000..310bda00b4d8b715cddcd94f5aa7142a0bdae6fa
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_sph_harm.py
@@ -0,0 +1,86 @@
+import numpy as np
+import pytest
+
+from numpy.testing import assert_allclose, suppress_warnings
+import scipy.special as sc
+
+class TestSphHarm:
+    @pytest.mark.slow
+    def test_p(self):
+        m_max = 20
+        n_max = 10
+
+        theta = np.linspace(0, np.pi)
+        phi = np.linspace(0, 2*np.pi)
+        theta, phi = np.meshgrid(theta, phi)
+
+        y, y_jac, y_hess = sc.sph_harm_y_all(n_max, m_max, theta, phi, diff_n=2)
+        p, p_jac, p_hess = sc.sph_legendre_p_all(n_max, m_max, theta, diff_n=2)
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        m = np.expand_dims(m, axis=(0,)+tuple(range(2,theta.ndim+2)))
+
+        assert_allclose(y, p * np.exp(1j * m * phi))
+
+        assert_allclose(y_jac[..., 0], p_jac * np.exp(1j * m * phi))
+        assert_allclose(y_jac[..., 1], 1j * m * p * np.exp(1j * m * phi))
+
+        assert_allclose(y_hess[..., 0, 0], p_hess * np.exp(1j * m * phi))
+        assert_allclose(y_hess[..., 0, 1], 1j * m * p_jac * np.exp(1j * m * phi))
+        assert_allclose(y_hess[..., 1, 0], y_hess[..., 0, 1])
+        assert_allclose(y_hess[..., 1, 1], -m * m * p * np.exp(1j * m * phi))
+
+    @pytest.mark.parametrize("n_max", [7, 10, 50])
+    @pytest.mark.parametrize("m_max", [1, 4, 5, 9, 14])
+    def test_all(self, n_max, m_max):
+        theta = np.linspace(0, np.pi)
+        phi = np.linspace(0, 2 * np.pi)
+
+        n = np.arange(n_max + 1)
+        n = np.expand_dims(n, axis=tuple(range(1,theta.ndim+2)))
+
+        m = np.concatenate([np.arange(m_max + 1), np.arange(-m_max, 0)])
+        m = np.expand_dims(m, axis=(0,)+tuple(range(2,theta.ndim+2)))
+
+        y_actual = sc.sph_harm_y_all(n_max, m_max, theta, phi)
+        y_desired = sc.sph_harm_y(n, m, theta, phi)
+
+        np.testing.assert_allclose(y_actual, y_desired, rtol=1e-05)
+
+def test_first_harmonics():
+    # Test against explicit representations of the first four
+    # spherical harmonics which use `theta` as the azimuthal angle,
+    # `phi` as the polar angle, and include the Condon-Shortley
+    # phase.
+
+    # sph_harm is deprecated and is implemented as a shim around sph_harm_y.
+    # This test is maintained to verify the correctness of the shim.
+
+    # Notation is Ymn
+    def Y00(theta, phi):
+        return 0.5*np.sqrt(1/np.pi)
+
+    def Yn11(theta, phi):
+        return 0.5*np.sqrt(3/(2*np.pi))*np.exp(-1j*theta)*np.sin(phi)
+
+    def Y01(theta, phi):
+        return 0.5*np.sqrt(3/np.pi)*np.cos(phi)
+
+    def Y11(theta, phi):
+        return -0.5*np.sqrt(3/(2*np.pi))*np.exp(1j*theta)*np.sin(phi)
+
+    harms = [Y00, Yn11, Y01, Y11]
+    m = [0, -1, 0, 1]
+    n = [0, 1, 1, 1]
+
+    theta = np.linspace(0, 2*np.pi)
+    phi = np.linspace(0, np.pi)
+    theta, phi = np.meshgrid(theta, phi)
+
+    for harm, m, n in zip(harms, m, n):
+        with suppress_warnings() as sup:
+            sup.filter(category=DeprecationWarning)
+            assert_allclose(sc.sph_harm(m, n, theta, phi),
+                            harm(theta, phi),
+                            rtol=1e-15, atol=1e-15,
+                            err_msg=f"Y^{m}_{n} incorrect")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a0173152c25eca57670b7ee6eadb57cd965266c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_spherical_bessel.py
@@ -0,0 +1,400 @@
+#
+# Tests of spherical Bessel functions.
+#
+import numpy as np
+from numpy.testing import (assert_almost_equal, assert_allclose,
+                           assert_array_almost_equal, suppress_warnings)
+import pytest
+from numpy import sin, cos, sinh, cosh, exp, inf, nan, r_, pi
+
+from scipy.special import spherical_jn, spherical_yn, spherical_in, spherical_kn
+from scipy.integrate import quad
+
+
+class TestSphericalJn:
+    def test_spherical_jn_exact(self):
+        # https://dlmf.nist.gov/10.49.E3
+        # Note: exact expression is numerically stable only for small
+        # n or z >> n.
+        x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5])
+        assert_allclose(spherical_jn(2, x),
+                        (-1/x + 3/x**3)*sin(x) - 3/x**2*cos(x))
+
+    def test_spherical_jn_recurrence_complex(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 1.1 + 1.5j
+        assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1, x),
+                        (2*n + 1)/x*spherical_jn(n, x))
+
+    def test_spherical_jn_recurrence_real(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 0.12
+        assert_allclose(spherical_jn(n - 1, x) + spherical_jn(n + 1,x),
+                        (2*n + 1)/x*spherical_jn(n, x))
+
+    def test_spherical_jn_inf_real(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 6
+        x = np.array([-inf, inf])
+        assert_allclose(spherical_jn(n, x), np.array([0, 0]))
+
+    def test_spherical_jn_inf_complex(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 7
+        x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)])
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+            assert_allclose(spherical_jn(n, x), np.array([0, 0, inf*(1+1j)]))
+
+    def test_spherical_jn_large_arg_1(self):
+        # https://github.com/scipy/scipy/issues/2165
+        # Reference value computed using mpmath, via
+        # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z))
+        assert_allclose(spherical_jn(2, 3350.507), -0.00029846226538040747)
+
+    def test_spherical_jn_large_arg_2(self):
+        # https://github.com/scipy/scipy/issues/1641
+        # Reference value computed using mpmath, via
+        # besselj(n + mpf(1)/2, z)*sqrt(pi/(2*z))
+        assert_allclose(spherical_jn(2, 10000), 3.0590002633029811e-05)
+
+    def test_spherical_jn_at_zero(self):
+        # https://dlmf.nist.gov/10.52.E1
+        # But note that n = 0 is a special case: j0 = sin(x)/x -> 1
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0
+        assert_allclose(spherical_jn(n, x), np.array([1, 0, 0, 0, 0, 0]))
+
+
+class TestSphericalYn:
+    def test_spherical_yn_exact(self):
+        # https://dlmf.nist.gov/10.49.E5
+        # Note: exact expression is numerically stable only for small
+        # n or z >> n.
+        x = np.array([0.12, 1.23, 12.34, 123.45, 1234.5])
+        assert_allclose(spherical_yn(2, x),
+                        (1/x - 3/x**3)*cos(x) - 3/x**2*sin(x))
+
+    def test_spherical_yn_recurrence_real(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 0.12
+        assert_allclose(spherical_yn(n - 1, x) + spherical_yn(n + 1,x),
+                        (2*n + 1)/x*spherical_yn(n, x))
+
+    def test_spherical_yn_recurrence_complex(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 1.1 + 1.5j
+        assert_allclose(spherical_yn(n - 1, x) + spherical_yn(n + 1, x),
+                        (2*n + 1)/x*spherical_yn(n, x))
+
+    def test_spherical_yn_inf_real(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 6
+        x = np.array([-inf, inf])
+        assert_allclose(spherical_yn(n, x), np.array([0, 0]))
+
+    def test_spherical_yn_inf_complex(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 7
+        x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)])
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+            assert_allclose(spherical_yn(n, x), np.array([0, 0, inf*(1+1j)]))
+
+    def test_spherical_yn_at_zero(self):
+        # https://dlmf.nist.gov/10.52.E2
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0
+        assert_allclose(spherical_yn(n, x), np.full(n.shape, -inf))
+
+    def test_spherical_yn_at_zero_complex(self):
+        # Consistently with numpy:
+        # >>> -np.cos(0)/0
+        # -inf
+        # >>> -np.cos(0+0j)/(0+0j)
+        # (-inf + nan*j)
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0 + 0j
+        assert_allclose(spherical_yn(n, x), np.full(n.shape, nan))
+
+
+class TestSphericalJnYnCrossProduct:
+    def test_spherical_jn_yn_cross_product_1(self):
+        # https://dlmf.nist.gov/10.50.E3
+        n = np.array([1, 5, 8])
+        x = np.array([0.1, 1, 10])
+        left = (spherical_jn(n + 1, x) * spherical_yn(n, x) -
+                spherical_jn(n, x) * spherical_yn(n + 1, x))
+        right = 1/x**2
+        assert_allclose(left, right)
+
+    def test_spherical_jn_yn_cross_product_2(self):
+        # https://dlmf.nist.gov/10.50.E3
+        n = np.array([1, 5, 8])
+        x = np.array([0.1, 1, 10])
+        left = (spherical_jn(n + 2, x) * spherical_yn(n, x) -
+                spherical_jn(n, x) * spherical_yn(n + 2, x))
+        right = (2*n + 3)/x**3
+        assert_allclose(left, right)
+
+
+class TestSphericalIn:
+    def test_spherical_in_exact(self):
+        # https://dlmf.nist.gov/10.49.E9
+        x = np.array([0.12, 1.23, 12.34, 123.45])
+        assert_allclose(spherical_in(2, x),
+                        (1/x + 3/x**3)*sinh(x) - 3/x**2*cosh(x))
+
+    def test_spherical_in_recurrence_real(self):
+        # https://dlmf.nist.gov/10.51.E4
+        n = np.array([1, 2, 3, 7, 12])
+        x = 0.12
+        assert_allclose(spherical_in(n - 1, x) - spherical_in(n + 1,x),
+                        (2*n + 1)/x*spherical_in(n, x))
+
+    def test_spherical_in_recurrence_complex(self):
+        # https://dlmf.nist.gov/10.51.E1
+        n = np.array([1, 2, 3, 7, 12])
+        x = 1.1 + 1.5j
+        assert_allclose(spherical_in(n - 1, x) - spherical_in(n + 1,x),
+                        (2*n + 1)/x*spherical_in(n, x))
+
+    def test_spherical_in_inf_real(self):
+        # https://dlmf.nist.gov/10.52.E3
+        n = 5
+        x = np.array([-inf, inf])
+        assert_allclose(spherical_in(n, x), np.array([-inf, inf]))
+
+    def test_spherical_in_inf_complex(self):
+        # https://dlmf.nist.gov/10.52.E5
+        # Ideally, i1n(n, 1j*inf) = 0 and i1n(n, (1+1j)*inf) = (1+1j)*inf, but
+        # this appears impossible to achieve because C99 regards any complex
+        # value with at least one infinite  part as a complex infinity, so
+        # 1j*inf cannot be distinguished from (1+1j)*inf.  Therefore, nan is
+        # the correct return value.
+        n = 7
+        x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)])
+        assert_allclose(spherical_in(n, x), np.array([-inf, inf, nan]))
+
+    def test_spherical_in_at_zero(self):
+        # https://dlmf.nist.gov/10.52.E1
+        # But note that n = 0 is a special case: i0 = sinh(x)/x -> 1
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0
+        assert_allclose(spherical_in(n, x), np.array([1, 0, 0, 0, 0, 0]))
+
+
+class TestSphericalKn:
+    def test_spherical_kn_exact(self):
+        # https://dlmf.nist.gov/10.49.E13
+        x = np.array([0.12, 1.23, 12.34, 123.45])
+        assert_allclose(spherical_kn(2, x),
+                        pi/2*exp(-x)*(1/x + 3/x**2 + 3/x**3))
+
+    def test_spherical_kn_recurrence_real(self):
+        # https://dlmf.nist.gov/10.51.E4
+        n = np.array([1, 2, 3, 7, 12])
+        x = 0.12
+        assert_allclose(
+            (-1)**(n - 1)*spherical_kn(n - 1, x) - (-1)**(n + 1)*spherical_kn(n + 1,x),
+            (-1)**n*(2*n + 1)/x*spherical_kn(n, x)
+        )
+
+    def test_spherical_kn_recurrence_complex(self):
+        # https://dlmf.nist.gov/10.51.E4
+        n = np.array([1, 2, 3, 7, 12])
+        x = 1.1 + 1.5j
+        assert_allclose(
+            (-1)**(n - 1)*spherical_kn(n - 1, x) - (-1)**(n + 1)*spherical_kn(n + 1,x),
+            (-1)**n*(2*n + 1)/x*spherical_kn(n, x)
+        )
+
+    def test_spherical_kn_inf_real(self):
+        # https://dlmf.nist.gov/10.52.E6
+        n = 5
+        x = np.array([-inf, inf])
+        assert_allclose(spherical_kn(n, x), np.array([-inf, 0]))
+
+    def test_spherical_kn_inf_complex(self):
+        # https://dlmf.nist.gov/10.52.E6
+        # The behavior at complex infinity depends on the sign of the real
+        # part: if Re(z) >= 0, then the limit is 0; if Re(z) < 0, then it's
+        # z*inf.  This distinction cannot be captured, so we return nan.
+        n = 7
+        x = np.array([-inf + 0j, inf + 0j, inf*(1+1j)])
+        assert_allclose(spherical_kn(n, x), np.array([-inf, 0, nan]))
+
+    def test_spherical_kn_at_zero(self):
+        # https://dlmf.nist.gov/10.52.E2
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0
+        assert_allclose(spherical_kn(n, x), np.full(n.shape, inf))
+
+    def test_spherical_kn_at_zero_complex(self):
+        # https://dlmf.nist.gov/10.52.E2
+        n = np.array([0, 1, 2, 5, 10, 100])
+        x = 0 + 0j
+        assert_allclose(spherical_kn(n, x), np.full(n.shape, nan))
+
+
+class SphericalDerivativesTestCase:
+    def fundamental_theorem(self, n, a, b):
+        integral, tolerance = quad(lambda z: self.df(n, z), a, b)
+        assert_allclose(integral,
+                        self.f(n, b) - self.f(n, a),
+                        atol=tolerance)
+
+    @pytest.mark.slow
+    def test_fundamental_theorem_0(self):
+        self.fundamental_theorem(0, 3.0, 15.0)
+
+    @pytest.mark.slow
+    def test_fundamental_theorem_7(self):
+        self.fundamental_theorem(7, 0.5, 1.2)
+
+
+class TestSphericalJnDerivatives(SphericalDerivativesTestCase):
+    def f(self, n, z):
+        return spherical_jn(n, z)
+
+    def df(self, n, z):
+        return spherical_jn(n, z, derivative=True)
+
+    def test_spherical_jn_d_zero(self):
+        n = np.array([0, 1, 2, 3, 7, 15])
+        assert_allclose(spherical_jn(n, 0, derivative=True),
+                        np.array([0, 1/3, 0, 0, 0, 0]))
+
+
+class TestSphericalYnDerivatives(SphericalDerivativesTestCase):
+    def f(self, n, z):
+        return spherical_yn(n, z)
+
+    def df(self, n, z):
+        return spherical_yn(n, z, derivative=True)
+
+
+class TestSphericalInDerivatives(SphericalDerivativesTestCase):
+    def f(self, n, z):
+        return spherical_in(n, z)
+
+    def df(self, n, z):
+        return spherical_in(n, z, derivative=True)
+
+    def test_spherical_in_d_zero(self):
+        n = np.array([0, 1, 2, 3, 7, 15])
+        spherical_in(n, 0, derivative=False)
+        assert_allclose(spherical_in(n, 0, derivative=True),
+                        np.array([0, 1/3, 0, 0, 0, 0]))
+
+
+class TestSphericalKnDerivatives(SphericalDerivativesTestCase):
+    def f(self, n, z):
+        return spherical_kn(n, z)
+
+    def df(self, n, z):
+        return spherical_kn(n, z, derivative=True)
+
+
+class TestSphericalOld:
+    # These are tests from the TestSpherical class of test_basic.py,
+    # rewritten to use spherical_* instead of sph_* but otherwise unchanged.
+
+    def test_sph_in(self):
+        # This test reproduces test_basic.TestSpherical.test_sph_in.
+        i1n = np.empty((2,2))
+        x = 0.2
+
+        i1n[0][0] = spherical_in(0, x)
+        i1n[0][1] = spherical_in(1, x)
+        i1n[1][0] = spherical_in(0, x, derivative=True)
+        i1n[1][1] = spherical_in(1, x, derivative=True)
+
+        inp0 = (i1n[0][1])
+        inp1 = (i1n[0][0] - 2.0/0.2 * i1n[0][1])
+        assert_array_almost_equal(i1n[0],np.array([1.0066800127054699381,
+                                                0.066933714568029540839]),12)
+        assert_array_almost_equal(i1n[1],[inp0,inp1],12)
+
+    def test_sph_in_kn_order0(self):
+        x = 1.
+        sph_i0 = np.empty((2,))
+        sph_i0[0] = spherical_in(0, x)
+        sph_i0[1] = spherical_in(0, x, derivative=True)
+        sph_i0_expected = np.array([np.sinh(x)/x,
+                                    np.cosh(x)/x-np.sinh(x)/x**2])
+        assert_array_almost_equal(r_[sph_i0], sph_i0_expected)
+
+        sph_k0 = np.empty((2,))
+        sph_k0[0] = spherical_kn(0, x)
+        sph_k0[1] = spherical_kn(0, x, derivative=True)
+        sph_k0_expected = np.array([0.5*pi*exp(-x)/x,
+                                    -0.5*pi*exp(-x)*(1/x+1/x**2)])
+        assert_array_almost_equal(r_[sph_k0], sph_k0_expected)
+
+    def test_sph_jn(self):
+        s1 = np.empty((2,3))
+        x = 0.2
+
+        s1[0][0] = spherical_jn(0, x)
+        s1[0][1] = spherical_jn(1, x)
+        s1[0][2] = spherical_jn(2, x)
+        s1[1][0] = spherical_jn(0, x, derivative=True)
+        s1[1][1] = spherical_jn(1, x, derivative=True)
+        s1[1][2] = spherical_jn(2, x, derivative=True)
+
+        s10 = -s1[0][1]
+        s11 = s1[0][0]-2.0/0.2*s1[0][1]
+        s12 = s1[0][1]-3.0/0.2*s1[0][2]
+        assert_array_almost_equal(s1[0],[0.99334665397530607731,
+                                      0.066400380670322230863,
+                                      0.0026590560795273856680],12)
+        assert_array_almost_equal(s1[1],[s10,s11,s12],12)
+
+    def test_sph_kn(self):
+        kn = np.empty((2,3))
+        x = 0.2
+
+        kn[0][0] = spherical_kn(0, x)
+        kn[0][1] = spherical_kn(1, x)
+        kn[0][2] = spherical_kn(2, x)
+        kn[1][0] = spherical_kn(0, x, derivative=True)
+        kn[1][1] = spherical_kn(1, x, derivative=True)
+        kn[1][2] = spherical_kn(2, x, derivative=True)
+
+        kn0 = -kn[0][1]
+        kn1 = -kn[0][0]-2.0/0.2*kn[0][1]
+        kn2 = -kn[0][1]-3.0/0.2*kn[0][2]
+        assert_array_almost_equal(kn[0],[6.4302962978445670140,
+                                         38.581777787067402086,
+                                         585.15696310385559829],12)
+        assert_array_almost_equal(kn[1],[kn0,kn1,kn2],9)
+
+    def test_sph_yn(self):
+        sy1 = spherical_yn(2, 0.2)
+        sy2 = spherical_yn(0, 0.2)
+        assert_almost_equal(sy1,-377.52483,5)  # previous values in the system
+        assert_almost_equal(sy2,-4.9003329,5)
+        sphpy = (spherical_yn(0, 0.2) - 2*spherical_yn(2, 0.2))/3
+        sy3 = spherical_yn(1, 0.2, derivative=True)
+        # compare correct derivative val. (correct =-system val).
+        assert_almost_equal(sy3,sphpy,4)
+
+
+@pytest.mark.parametrize('derivative', [False, True])
+@pytest.mark.parametrize('fun', [spherical_jn, spherical_in,
+                                 spherical_yn, spherical_kn])
+def test_negative_real_gh14582(derivative, fun):
+    # gh-14582 reported that the spherical Bessel functions did not work
+    # with negative real argument `z`. Check that this is resolved.
+    rng = np.random.default_rng(3598435982345987234)
+    size = 25
+    n = rng.integers(0, 10, size=size)
+    z = rng.standard_normal(size=size)
+    res = fun(n, z, derivative=derivative)
+    ref = fun(n, z+0j, derivative=derivative)
+    np.testing.assert_allclose(res, ref.real)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..48cfe5bfb64c15486f4b0b2d911846b96e29f3df
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_support_alternative_backends.py
@@ -0,0 +1,113 @@
+import pytest
+
+from scipy.special._support_alternative_backends import (get_array_special_func,
+                                                         array_special_func_map)
+from scipy.conftest import array_api_compatible
+from scipy import special
+from scipy._lib._array_api_no_0d import xp_assert_close
+from scipy._lib._array_api import is_jax, is_torch, SCIPY_DEVICE
+from scipy._lib.array_api_compat import numpy as np
+
+try:
+    import array_api_strict
+    HAVE_ARRAY_API_STRICT = True
+except ImportError:
+    HAVE_ARRAY_API_STRICT = False
+
+
+@pytest.mark.skipif(not HAVE_ARRAY_API_STRICT,
+                    reason="`array_api_strict` not installed")
+def test_dispatch_to_unrecognize_library():
+    xp = array_api_strict
+    f = get_array_special_func('ndtr', xp=xp, n_array_args=1)
+    x = [1, 2, 3]
+    res = f(xp.asarray(x))
+    ref = xp.asarray(special.ndtr(np.asarray(x)))
+    xp_assert_close(res, ref, xp=xp)
+
+
+@pytest.mark.parametrize('dtype', ['float32', 'float64', 'int64'])
+@pytest.mark.skipif(not HAVE_ARRAY_API_STRICT,
+                    reason="`array_api_strict` not installed")
+def test_rel_entr_generic(dtype):
+    xp = array_api_strict
+    f = get_array_special_func('rel_entr', xp=xp, n_array_args=2)
+    dtype_np = getattr(np, dtype)
+    dtype_xp = getattr(xp, dtype)
+    x, y = [-1, 0, 0, 1], [1, 0, 2, 3]
+
+    x_xp, y_xp = xp.asarray(x, dtype=dtype_xp), xp.asarray(y, dtype=dtype_xp)
+    res = f(x_xp, y_xp)
+
+    x_np, y_np = np.asarray(x, dtype=dtype_np), np.asarray(y, dtype=dtype_np)
+    ref = special.rel_entr(x_np[-1], y_np[-1])
+    ref = np.asarray([np.inf, 0, 0, ref], dtype=ref.dtype)
+
+    xp_assert_close(res, xp.asarray(ref), xp=xp)
+
+
+@pytest.mark.fail_slow(5)
+@array_api_compatible
+# @pytest.mark.skip_xp_backends('numpy', reason='skip while debugging')
+# @pytest.mark.usefixtures("skip_xp_backends")
+# `reversed` is for developer convenience: test new function first = less waiting
+@pytest.mark.parametrize('f_name_n_args', reversed(array_special_func_map.items()))
+@pytest.mark.parametrize('dtype', ['float32', 'float64'])
+@pytest.mark.parametrize('shapes', [[(0,)]*4, [tuple()]*4, [(10,)]*4,
+                                    [(10,), (11, 1), (12, 1, 1), (13, 1, 1, 1)]])
+def test_support_alternative_backends(xp, f_name_n_args, dtype, shapes):
+    f_name, n_args = f_name_n_args
+
+    if (SCIPY_DEVICE != 'cpu'
+        and is_torch(xp)
+        and f_name in {'stdtr', 'betaincc', 'betainc'}
+    ):
+        pytest.skip(f"`{f_name}` does not have an array-agnostic implementation "
+                    f"and cannot delegate to PyTorch.")
+
+    shapes = shapes[:n_args]
+    f = getattr(special, f_name)
+
+    dtype_np = getattr(np, dtype)
+    dtype_xp = getattr(xp, dtype)
+
+    # # To test the robustness of the alternative backend's implementation,
+    # # use Hypothesis to generate arguments
+    # from hypothesis import given, strategies, reproduce_failure, assume
+    # import hypothesis.extra.numpy as npst
+    # @given(data=strategies.data())
+    # mbs = npst.mutually_broadcastable_shapes(num_shapes=n_args)
+    # shapes, final_shape = data.draw(mbs)
+    # elements = dict(allow_subnormal=False)  # consider min_value, max_value
+    # args_np = [np.asarray(data.draw(npst.arrays(dtype_np, shape, elements=elements)),
+    #                       dtype=dtype_np)
+    #            for shape in shapes]
+
+    # For CI, be a little more forgiving; just generate normally distributed arguments
+    rng = np.random.default_rng(984254252920492019)
+    args_np = [rng.standard_normal(size=shape, dtype=dtype_np) for shape in shapes]
+
+    if (is_jax(xp) and f_name == 'gammaincc'  # google/jax#20699
+            or f_name == 'chdtrc'):  # gh-20972
+        args_np[0] = np.abs(args_np[0])
+        args_np[1] = np.abs(args_np[1])
+
+    args_xp = [xp.asarray(arg[()], dtype=dtype_xp) for arg in args_np]
+
+    res = f(*args_xp)
+    ref = xp.asarray(f(*args_np), dtype=dtype_xp)
+
+    eps = np.finfo(dtype_np).eps
+    xp_assert_close(res, ref, atol=10*eps)
+
+
+@array_api_compatible
+def test_chdtr_gh21311(xp):
+    # the edge case behavior of generic chdtr was not right; see gh-21311
+    # be sure to test at least these cases
+    # should add `np.nan` into the mix when gh-21317 is resolved
+    x = np.asarray([-np.inf, -1., 0., 1., np.inf])
+    v = x.reshape(-1, 1)
+    ref = special.chdtr(v, x)
+    res = special.chdtr(xp.asarray(v), xp.asarray(x))
+    xp_assert_close(res, xp.asarray(ref))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py
new file mode 100644
index 0000000000000000000000000000000000000000..578dfbd5e95e6c44b1828716a74c93d645efcb1e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_trig.py
@@ -0,0 +1,72 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose, suppress_warnings
+
+from scipy.special._ufuncs import _sinpi as sinpi
+from scipy.special._ufuncs import _cospi as cospi
+
+
+def test_integer_real_part():
+    x = np.arange(-100, 101)
+    y = np.hstack((-np.linspace(310, -30, 10), np.linspace(-30, 310, 10)))
+    x, y = np.meshgrid(x, y)
+    z = x + 1j*y
+    # In the following we should be *exactly* right
+    res = sinpi(z)
+    assert_equal(res.real, 0.0)
+    res = cospi(z)
+    assert_equal(res.imag, 0.0)
+
+
+def test_half_integer_real_part():
+    x = np.arange(-100, 101) + 0.5
+    y = np.hstack((-np.linspace(310, -30, 10), np.linspace(-30, 310, 10)))
+    x, y = np.meshgrid(x, y)
+    z = x + 1j*y
+    # In the following we should be *exactly* right
+    res = sinpi(z)
+    assert_equal(res.imag, 0.0)
+    res = cospi(z)
+    assert_equal(res.real, 0.0)
+
+
+@pytest.mark.skip("Temporary skip while gh-19526 is being resolved")
+def test_intermediate_overlow():
+    # Make sure we avoid overflow in situations where cosh/sinh would
+    # overflow but the product with sin/cos would not
+    sinpi_pts = [complex(1 + 1e-14, 227),
+                 complex(1e-35, 250),
+                 complex(1e-301, 445)]
+    # Data generated with mpmath
+    sinpi_std = [complex(-8.113438309924894e+295, -np.inf),
+                 complex(1.9507801934611995e+306, np.inf),
+                 complex(2.205958493464539e+306, np.inf)]
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+        for p, std in zip(sinpi_pts, sinpi_std):
+            res = sinpi(p)
+            assert_allclose(res.real, std.real)
+            assert_allclose(res.imag, std.imag)
+
+    # Test for cosine, less interesting because cos(0) = 1.
+    p = complex(0.5 + 1e-14, 227)
+    std = complex(-8.113438309924894e+295, -np.inf)
+    with suppress_warnings() as sup:
+        sup.filter(RuntimeWarning, "invalid value encountered in multiply")
+        res = cospi(p)
+        assert_allclose(res.real, std.real)
+        assert_allclose(res.imag, std.imag)
+
+
+def test_zero_sign():
+    y = sinpi(-0.0)
+    assert y == 0.0
+    assert np.signbit(y)
+
+    y = sinpi(0.0)
+    assert y == 0.0
+    assert not np.signbit(y)
+
+    y = cospi(0.5)
+    assert y == 0.0
+    assert not np.signbit(y)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ufunc_signatures.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ufunc_signatures.py
new file mode 100644
index 0000000000000000000000000000000000000000..6bc3ffae15ab4620c4e752df166721825cb7449c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_ufunc_signatures.py
@@ -0,0 +1,46 @@
+"""Test that all ufuncs have float32-preserving signatures.
+
+This was once guaranteed through the code generation script for
+generating ufuncs, `scipy/special/_generate_pyx.py`. Starting with
+gh-20260, SciPy developers have begun moving to generate ufuncs
+through direct use of the NumPy C API (through C++). Existence of
+float32 preserving signatures must now be tested since it is no
+longer guaranteed.
+"""
+
+import numpy as np
+import pytest
+import scipy.special._ufuncs
+import scipy.special._gufuncs
+
+_ufuncs = []
+for funcname in dir(scipy.special._ufuncs):
+    _ufuncs.append(getattr(scipy.special._ufuncs, funcname))
+for funcname in dir(scipy.special._gufuncs):
+    _ufuncs.append(getattr(scipy.special._gufuncs, funcname))
+
+# Not all module members are actually ufuncs
+_ufuncs = [func for func in _ufuncs if isinstance(func, np.ufunc)]
+
+@pytest.mark.parametrize("ufunc", _ufuncs)
+def test_ufunc_signatures(ufunc):
+
+    # From _generate_pyx.py
+    # "Don't add float32 versions of ufuncs with integer arguments, as this
+    # can lead to incorrect dtype selection if the integer arguments are
+    # arrays, but float arguments are scalars.
+    # For instance sph_harm(0,[0],0,0).dtype == complex64
+    # This may be a NumPy bug, but we need to work around it.
+    # cf. gh-4895, https://github.com/numpy/numpy/issues/5895"
+    types = set(sig for sig in ufunc.types
+                if not ("l" in sig or "i" in sig or "q" in sig or "p" in sig))
+
+    # Generate the full expanded set of signatures which should exist. There
+    # should be matching float and double versions of any existing signature.
+    expanded_types = set()
+    for sig in types:
+        expanded_types.update(
+            [sig.replace("d", "f").replace("D", "F"),
+             sig.replace("f", "d").replace("F", "D")]
+        )
+    assert types == expanded_types
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef30163f55c90850fe32ca600eb47547e4fa5e03
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wright_bessel.py
@@ -0,0 +1,205 @@
+# Reference MPMATH implementation:
+#
+# import mpmath
+# from mpmath import nsum
+#
+# def Wright_Series_MPMATH(a, b, z, dps=50, method='r+s+e', steps=[1000]):
+#    """Compute Wright' generalized Bessel function as Series.
+#
+#    This uses mpmath for arbitrary precision.
+#    """
+#    with mpmath.workdps(dps):
+#        res = nsum(lambda k: z**k/mpmath.fac(k) * mpmath.rgamma(a*k+b),
+#                          [0, mpmath.inf],
+#                          tol=dps, method=method, steps=steps
+#                          )
+#
+#    return res
+
+from itertools import product
+
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+
+import scipy.special as sc
+from scipy.special import log_wright_bessel, loggamma, rgamma, wright_bessel
+
+
+@pytest.mark.parametrize('a', [0, 1e-6, 0.1, 0.5, 1, 10])
+@pytest.mark.parametrize('b', [0, 1e-6, 0.1, 0.5, 1, 10])
+def test_wright_bessel_zero(a, b):
+    """Test at x = 0."""
+    assert_equal(wright_bessel(a, b, 0.), rgamma(b))
+    assert_allclose(log_wright_bessel(a, b, 0.), -loggamma(b))
+
+
+@pytest.mark.parametrize('b', [0, 1e-6, 0.1, 0.5, 1, 10])
+@pytest.mark.parametrize('x', [0, 1e-6, 0.1, 0.5, 1])
+def test_wright_bessel_iv(b, x):
+    """Test relation of wright_bessel and modified bessel function iv.
+
+    iv(z) = (1/2*z)**v * Phi(1, v+1; 1/4*z**2).
+    See https://dlmf.nist.gov/10.46.E2
+    """
+    if x != 0:
+        v = b - 1
+        wb = wright_bessel(1, v + 1, x**2 / 4.)
+        # Note: iv(v, x) has precision of less than 1e-12 for some cases
+        # e.g v=1-1e-6 and x=1e-06)
+        assert_allclose(np.power(x / 2., v) * wb,
+                        sc.iv(v, x),
+                        rtol=1e-11, atol=1e-11)
+
+
+@pytest.mark.parametrize('a', [0, 1e-6, 0.1, 0.5, 1, 10])
+@pytest.mark.parametrize('b', [1, 1 + 1e-3, 2, 5, 10])
+@pytest.mark.parametrize('x', [0, 1e-6, 0.1, 0.5, 1, 5, 10, 100])
+def test_wright_functional(a, b, x):
+    """Test functional relation of wright_bessel.
+
+    Phi(a, b-1, z) = a*z*Phi(a, b+a, z) + (b-1)*Phi(a, b, z)
+
+    Note that d/dx Phi(a, b, x) = Phi(a, b-1, x)
+    See Eq. (22) of
+    B. Stankovic, On the Function of E. M. Wright,
+    Publ. de l' Institut Mathematique, Beograd,
+    Nouvelle S`er. 10 (1970), 113-124.
+    """
+    assert_allclose(wright_bessel(a, b - 1, x),
+                    a * x * wright_bessel(a, b + a, x)
+                    + (b - 1) * wright_bessel(a, b, x),
+                    rtol=1e-8, atol=1e-8)
+
+
+# grid of rows [a, b, x, value, accuracy] that do not reach 1e-11 accuracy
+# see output of:
+# cd scipy/scipy/_precompute
+# python wright_bessel_data.py
+grid_a_b_x_value_acc = np.array([
+    [0.1, 100.0, 709.7827128933841, 8.026353022981087e+34, 2e-8],
+    [0.5, 10.0, 709.7827128933841, 2.680788404494657e+48, 9e-8],
+    [0.5, 10.0, 1000.0, 2.005901980702872e+64, 1e-8],
+    [0.5, 100.0, 1000.0, 3.4112367580445246e-117, 6e-8],
+    [1.0, 20.0, 100000.0, 1.7717158630699857e+225, 3e-11],
+    [1.0, 100.0, 100000.0, 1.0269334596230763e+22, np.nan],
+    [1.0000000000000222, 20.0, 100000.0, 1.7717158630001672e+225, 3e-11],
+    [1.0000000000000222, 100.0, 100000.0, 1.0269334595866202e+22, np.nan],
+    [1.5, 0.0, 500.0, 15648961196.432373, 3e-11],
+    [1.5, 2.220446049250313e-14, 500.0, 15648961196.431465, 3e-11],
+    [1.5, 1e-10, 500.0, 15648961192.344728, 3e-11],
+    [1.5, 1e-05, 500.0, 15648552437.334162, 3e-11],
+    [1.5, 0.1, 500.0, 12049870581.10317, 2e-11],
+    [1.5, 20.0, 100000.0, 7.81930438331405e+43, 3e-9],
+    [1.5, 100.0, 100000.0, 9.653370857459075e-130, np.nan],
+    ])
+
+
+@pytest.mark.xfail
+@pytest.mark.parametrize(
+    'a, b, x, phi',
+    grid_a_b_x_value_acc[:, :4].tolist())
+def test_wright_data_grid_failures(a, b, x, phi):
+    """Test cases of test_data that do not reach relative accuracy of 1e-11"""
+    assert_allclose(wright_bessel(a, b, x), phi, rtol=1e-11)
+
+
+@pytest.mark.parametrize(
+    'a, b, x, phi, accuracy',
+    grid_a_b_x_value_acc.tolist())
+def test_wright_data_grid_less_accurate(a, b, x, phi, accuracy):
+    """Test cases of test_data that do not reach relative accuracy of 1e-11
+
+    Here we test for reduced accuracy or even nan.
+    """
+    if np.isnan(accuracy):
+        assert np.isnan(wright_bessel(a, b, x))
+    else:
+        assert_allclose(wright_bessel(a, b, x), phi, rtol=accuracy)
+
+
+@pytest.mark.parametrize(
+    'a, b, x',
+    list(
+        product([0, 0.1, 0.5, 1.5, 5, 10], [1, 2], [1e-3, 1, 1.5, 5, 10])
+    )
+)
+def test_log_wright_bessel_same_as_wright_bessel(a, b, x):
+    """Test that log_wright_bessel equals log of wright_bessel."""
+    assert_allclose(
+        log_wright_bessel(a, b, x),
+        np.log(wright_bessel(a, b, x)),
+        rtol=1e-8,
+    )
+
+
+# Computed with, see also mp_wright_bessel from wright_bessel_data.py:
+#
+# from functools import lru_cache
+# import mpmath as mp
+#
+# @lru_cache(maxsize=1_000_000)
+# def rgamma_cached(x, dps):
+#     with mp.workdps(dps):
+#         return mp.rgamma(x)
+#
+# def mp_log_wright_bessel(a, b, x, dps=100, maxterms=10_000, method="d"):
+#     """Compute log of Wright's generalized Bessel function as Series with mpmath."""
+#     with mp.workdps(dps):
+#         a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x)
+#         res = mp.nsum(lambda k: x**k / mp.fac(k)
+#                       * rgamma_cached(a * k + b, dps=dps),
+#                       [0, mp.inf],
+#                       tol=dps, method=method, steps=[maxterms]
+#                       )
+#         return mp.log(res)
+#
+# Sometimes, one needs to set maxterms as high as 1_00_000 to get accurate results for
+# phi.
+# At the end of the day, we can only hope that results are correct for very large x,
+# e.g. by the asymptotic series, as there is no way to produce those in "exact"
+# arithmetic.
+# Note: accuracy = np.nan means log_wright_bessel returns nan.
+@pytest.mark.parametrize(
+    'a, b, x, phi, accuracy',
+    [
+        (0, 0, 0, -np.inf, 1e-11),
+        (0, 0, 1, -np.inf, 1e-11),
+        (0, 1, 1.23, 1.23, 1e-11),
+        (0, 1, 1e50, 1e50, 1e-11),
+        (1e-5, 0, 700, 695.0421608273609, 1e-11),
+        (1e-5, 0, 1e3, 995.40052566540066, 1e-11),
+        (1e-5, 100, 1e3, 640.8197935670078, 1e-11),
+        (1e-3, 0, 1e4, 9987.2229532297262, 1e-11),
+        (1e-3, 0, 1e5, 99641.920687169507, 1e-11),
+        (1e-3, 0, 1e6, 994118.55560054416, 1e-11),  # maxterms=1_000_000
+        (1e-3, 10, 1e5, 99595.47710802537, 1e-11),
+        (1e-3, 50, 1e5, 99401.240922855647, 1e-3),
+        (1e-3, 100, 1e5, 99143.465191656527, np.nan),
+        (0.5, 0, 1e5, 4074.1112442197941, 1e-11),
+        (0.5, 0, 1e7, 87724.552120038896, 1e-11),
+        (0.5, 100, 1e5, 3350.3928746306163, np.nan),
+        (0.5, 100, 1e7, 86696.109975301719, 1e-11),
+        (1, 0, 1e5, 634.06765787997266, 1e-11),
+        (1, 0, 1e8, 20003.339639312035, 1e-11),
+        (1.5, 0, 1e5, 197.01777556071194, 1e-11),
+        (1.5, 0, 1e8, 3108.987414395706, 1e-11),
+        (1.5, 100, 1e8, 2354.8915946283275, np.nan),
+        (5, 0, 1e5, 9.8980480013203547, 1e-11),
+        (5, 0, 1e8, 33.642337258687465, 1e-11),
+        (5, 0, 1e12, 157.53704288117429, 1e-11),
+        (5, 100, 1e5, -359.13419630792148, 1e-11),
+        (5, 100, 1e12, -337.07722086995229, 1e-4),
+        (5, 100, 1e20, 2588.2471229986845, 2e-6),
+        (100, 0, 1e5, -347.62127990460517, 1e-11),
+        (100, 0, 1e20, -313.08250350969449, 1e-11),
+        (100, 100, 1e5, -359.1342053695754, 1e-11),
+        (100, 100, 1e20, -359.1342053695754, 1e-11),
+    ]
+)
+def test_log_wright_bessel(a, b, x, phi, accuracy):
+    """Test for log_wright_bessel, in particular for large x."""
+    if np.isnan(accuracy):
+        assert np.isnan(log_wright_bessel(a, b, x))
+    else:
+        assert_allclose(log_wright_bessel(a, b, x), phi, rtol=accuracy)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1a93ca007e42fea3a0dec634c51b37f03effa9e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_wrightomega.py
@@ -0,0 +1,117 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_, assert_equal, assert_allclose
+
+import scipy.special as sc
+from scipy.special._testutils import assert_func_equal
+
+
+def test_wrightomega_nan():
+    pts = [complex(np.nan, 0),
+           complex(0, np.nan),
+           complex(np.nan, np.nan),
+           complex(np.nan, 1),
+           complex(1, np.nan)]
+    for p in pts:
+        res = sc.wrightomega(p)
+        assert_(np.isnan(res.real))
+        assert_(np.isnan(res.imag))
+
+
+def test_wrightomega_inf_branch():
+    pts = [complex(-np.inf, np.pi/4),
+           complex(-np.inf, -np.pi/4),
+           complex(-np.inf, 3*np.pi/4),
+           complex(-np.inf, -3*np.pi/4)]
+    expected_results = [complex(0.0, 0.0),
+                        complex(0.0, -0.0),
+                        complex(-0.0, 0.0),
+                        complex(-0.0, -0.0)]
+    for p, expected in zip(pts, expected_results):
+        res = sc.wrightomega(p)
+        # We can't use assert_equal(res, expected) because in older versions of
+        # numpy, assert_equal doesn't check the sign of the real and imaginary
+        # parts when comparing complex zeros. It does check the sign when the
+        # arguments are *real* scalars.
+        assert_equal(res.real, expected.real)
+        assert_equal(res.imag, expected.imag)
+
+
+def test_wrightomega_inf():
+    pts = [complex(np.inf, 10),
+           complex(-np.inf, 10),
+           complex(10, np.inf),
+           complex(10, -np.inf)]
+    for p in pts:
+        assert_equal(sc.wrightomega(p), p)
+
+
+def test_wrightomega_singular():
+    pts = [complex(-1.0, np.pi),
+           complex(-1.0, -np.pi)]
+    for p in pts:
+        res = sc.wrightomega(p)
+        assert_equal(res, -1.0)
+        assert_(np.signbit(res.imag) == np.bool_(False))
+
+
+@pytest.mark.parametrize('x, desired', [
+    (-np.inf, 0),
+    (np.inf, np.inf),
+])
+def test_wrightomega_real_infinities(x, desired):
+    assert sc.wrightomega(x) == desired
+
+
+def test_wrightomega_real_nan():
+    assert np.isnan(sc.wrightomega(np.nan))
+
+
+def test_wrightomega_real_series_crossover():
+    desired_error = 2 * np.finfo(float).eps
+    crossover = 1e20
+    x_before_crossover = np.nextafter(crossover, -np.inf)
+    x_after_crossover = np.nextafter(crossover, np.inf)
+    # Computed using Mpmath
+    desired_before_crossover = 99999999999999983569.948
+    desired_after_crossover = 100000000000000016337.948
+    assert_allclose(
+        sc.wrightomega(x_before_crossover),
+        desired_before_crossover,
+        atol=0,
+        rtol=desired_error,
+    )
+    assert_allclose(
+        sc.wrightomega(x_after_crossover),
+        desired_after_crossover,
+        atol=0,
+        rtol=desired_error,
+    )
+
+
+def test_wrightomega_exp_approximation_crossover():
+    desired_error = 2 * np.finfo(float).eps
+    crossover = -50
+    x_before_crossover = np.nextafter(crossover, np.inf)
+    x_after_crossover = np.nextafter(crossover, -np.inf)
+    # Computed using Mpmath
+    desired_before_crossover = 1.9287498479639314876e-22
+    desired_after_crossover = 1.9287498479639040784e-22
+    assert_allclose(
+        sc.wrightomega(x_before_crossover),
+        desired_before_crossover,
+        atol=0,
+        rtol=desired_error,
+    )
+    assert_allclose(
+        sc.wrightomega(x_after_crossover),
+        desired_after_crossover,
+        atol=0,
+        rtol=desired_error,
+    )
+
+
+def test_wrightomega_real_versus_complex():
+    x = np.linspace(-500, 500, 1001)
+    results = sc.wrightomega(x + 0j).real
+    assert_func_equal(sc.wrightomega, results, x, atol=0, rtol=1e-14)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc39c2eeaf43196d4bf25964a0c2aefec2c8c0b4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_xsf_cuda.py
@@ -0,0 +1,114 @@
+import os
+import pytest
+import scipy.special as sc
+import shutil
+import tempfile
+
+from uuid import uuid4
+
+from scipy.special._testutils import check_version
+from scipy.special._testutils import MissingModule
+
+try:
+    import cupy  # type: ignore
+except (ImportError, AttributeError):
+    cupy = MissingModule('cupy')
+
+
+def get_test_cases():
+    cases_source = [
+        (sc.beta, "cephes/beta.h", "out0 = xsf::cephes::beta(in0, in1)"),
+        (sc.binom, "binom.h", "out0 = xsf::binom(in0, in1)"),
+        (sc.digamma, "digamma.h", "xsf::digamma(in0)"),
+        (sc.expn, "cephes/expn.h", "out0 = xsf::cephes::expn(in0, in1)"),
+        (sc.hyp2f1, "hyp2f1.h", "out0 = xsf::hyp2f1(in0, in1, in2, in3)"),
+        (sc._ufuncs._lambertw, "lambertw.h", "out0 = xsf::lambertw(in0, in1, in2)"),
+        (sc.ellipkinc, "cephes/ellik.h", "out0 = xsf::cephes::ellik(in0, in1)"),
+        (sc.ellipeinc, "cephes/ellie.h", "out0 = xsf::cephes::ellie(in0, in1)"),
+        (sc.gdtrib, "cdflib.h", "out0 = xsf::gdtrib(in0, in1, in2)"),
+        (sc.sici, "sici.h", "xsf::sici(in0, &out0, &out1)"),
+        (sc.shichi, "sici.h", "xsf::shichi(in0, &out0, &out1)"),
+    ]
+
+    cases = []
+    for ufunc, header, routine in cases_source:
+        preamble = f"#include "
+        for signature in ufunc.types:
+            cases.append((signature, preamble, routine))
+    return cases
+
+
+dtype_map = {
+    "f": "float32",
+    "d": "float64",
+    "F": "complex64",
+    "D": "complex128",
+    "i": "int32",
+    "l": "int64",
+}
+
+
+def get_params(signature):
+    in_, out = signature.split("->")
+    in_params = []
+    out_params = []
+    for i, typecode in enumerate(in_):
+        in_params.append(f"{dtype_map[typecode]} in{i}")
+    for i, typecode in enumerate(out):
+        out_params.append(f"{dtype_map[typecode]} out{i}")
+    in_params = ", ".join(in_params)
+    out_params = ", ".join(out_params)
+    return in_params, out_params
+
+
+def get_sample_input(signature, xp):
+    dtype_map = {
+        "f": xp.float32,
+        "d": xp.float64,
+        "F": xp.complex64,
+        "D": xp.complex128,
+        "i": xp.int32,
+        "l": xp.int64,
+    }
+
+    in_, _ = signature.split("->")
+    args = []
+    for typecode in in_:
+        args.append(xp.zeros(2, dtype=dtype_map[typecode]))
+    return args
+
+
+@pytest.fixture(scope="module", autouse=True)
+def manage_cupy_cache():
+    # Temporarily change cupy kernel cache location so kernel cache will not be polluted
+    # by these tests. Remove temporary cache in teardown.
+    temp_cache_dir = tempfile.mkdtemp()
+    original_cache_dir = os.environ.get('CUPY_CACHE_DIR', None)
+    os.environ['CUPY_CACHE_DIR'] = temp_cache_dir
+
+    yield
+
+    if original_cache_dir is not None:
+        os.environ['CUPY_CACHE_DIR'] = original_cache_dir
+    else:
+        del os.environ['CUPY_CACHE_DIR']
+    shutil.rmtree(temp_cache_dir)
+
+
+@check_version(cupy, "13.0.0")
+@pytest.mark.parametrize("signature,preamble,routine", get_test_cases())
+@pytest.mark.xslow
+def test_compiles_in_cupy(signature, preamble, routine, manage_cupy_cache):
+    name = f"x{uuid4().hex}"
+    in_params, out_params = get_params(signature)
+
+    func = cupy.ElementwiseKernel(
+        in_params,
+        out_params,
+        routine,
+        name,
+        preamble=preamble,
+        options=(f"--include-path={sc._get_include()}", "-std=c++17")
+    )
+
+    _ = func(*get_sample_input(signature, cupy))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py
new file mode 100644
index 0000000000000000000000000000000000000000..988f9a716196fb8f65a92a0a2e894038c2474cfa
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/tests/test_zeta.py
@@ -0,0 +1,301 @@
+import scipy
+import scipy.special as sc
+import sys
+import numpy as np
+import pytest
+
+from numpy.testing import assert_equal, assert_allclose
+
+
+def test_zeta():
+    assert_allclose(sc.zeta(2,2), np.pi**2/6 - 1, rtol=1e-12)
+
+
+def test_zetac():
+    # Expected values in the following were computed using Wolfram
+    # Alpha's `Zeta[x] - 1`
+    x = [-2.1, 0.8, 0.9999, 9, 50, 75]
+    desired = [
+        -0.9972705002153750,
+        -5.437538415895550,
+        -10000.42279161673,
+        0.002008392826082214,
+        8.881784210930816e-16,
+        2.646977960169853e-23,
+    ]
+    assert_allclose(sc.zetac(x), desired, rtol=1e-12)
+
+
+def test_zetac_special_cases():
+    assert sc.zetac(np.inf) == 0
+    assert np.isnan(sc.zetac(-np.inf))
+    assert sc.zetac(0) == -1.5
+    assert sc.zetac(1.0) == np.inf
+
+    assert_equal(sc.zetac([-2, -50, -100]), -1)
+
+
+def test_riemann_zeta_special_cases():
+    assert np.isnan(sc.zeta(np.nan))
+    assert sc.zeta(np.inf) == 1
+    assert sc.zeta(0) == -0.5
+
+    # Riemann zeta is zero add negative even integers.
+    assert_equal(sc.zeta([-2, -4, -6, -8, -10]), 0)
+
+    assert_allclose(sc.zeta(2), np.pi**2/6, rtol=1e-12)
+    assert_allclose(sc.zeta(4), np.pi**4/90, rtol=1e-12)
+
+
+def test_riemann_zeta_avoid_overflow():
+    s = -260.00000000001
+    desired = -5.6966307844402683127e+297  # Computed with Mpmath
+    assert_allclose(sc.zeta(s), desired, atol=0, rtol=5e-14)
+
+
+@pytest.mark.parametrize(
+    "z, desired, rtol",
+    [
+        ## Test cases taken from mpmath with the script:
+
+        # import numpy as np
+        # import scipy.stats as stats
+
+        # from mpmath import mp
+
+        # # seed = np.random.SeedSequence().entropy
+        # seed = 154689806791763421822480125722191067828
+        # rng = np.random.default_rng(seed)
+        # default_rtol = 1e-13
+
+        # # A small point in each quadrant outside of the critical strip
+        # cases = []
+        # for x_sign, y_sign in [1, 1], [1, -1], [-1, 1], [-1, -1]:
+        #     x = x_sign * rng.uniform(2, 8)
+        #     y = y_sign * rng.uniform(2, 8)
+        #     z = x + y*1j
+        #     reference = complex(mp.zeta(z))
+        #     cases.append((z, reference, default_rtol))
+
+        # # Moderately large imaginary part in each quadrant outside of critical strip
+        # for x_sign, y_sign in [1, 1], [1, -1], [-1, 1], [-1, -1]:
+        #     x = x_sign * rng.uniform(2, 8)
+        #     y = y_sign * rng.uniform(50, 80)
+        #     z = x + y*1j
+        #     reference = complex(mp.zeta(z))
+        #     cases.append((z, reference, default_rtol))
+
+        # # points in critical strip
+        # x = rng.uniform(0.0, 1.0, size=5)
+        # y = np.exp(rng.uniform(0, 5, size=5))
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, default_rtol))
+        # z = x - y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, default_rtol))
+
+        # # Near small trivial zeros
+        # x = np.array([-2, -4, -6, -8])
+        # y = np.array([1e-15, -1e-15])
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, 1e-7))
+
+        # # Some other points near real axis
+        # x = np.array([-0.5, 0, 0.2, 0.75])
+        # y = np.array([1e-15, -1e-15])
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, 1e-7))
+
+        # # Moderately large real part
+        # x = np.array([49.33915930750887, 50.55805244181687])
+        # y = rng.uniform(20, 100, size=3)
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, default_rtol))
+
+        # # Very large imaginary part
+        # x = np.array([0.5, 34.812847097948854, 50.55805244181687])
+        # y = np.array([1e6, -1e6])
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     rtol = 1e-7 if t.real == 0.5 else default_rtol
+        #     cases.append((complex(t), reference, rtol))
+        #
+        # # Naive implementation of reflection formula suffers internal overflow
+        # x = -rng.uniform(200, 300, 3)
+        # y = np.array([rng.uniform(10, 30), -rng.uniform(10, 30)])
+        # x, y = np.meshgrid(x, y)
+        # x, y = x.ravel(), y.ravel()
+        # z = x + y*1j
+        # for t in z:
+        #     reference = complex(mp.zeta(t))
+        #     cases.append((complex(t), reference, default_rtol))
+        #
+        # A small point in each quadrant outside of the critical strip
+        ((3.12838509346655+7.111085974836645j),
+         (1.0192654793474945+0.08795174413289127j),
+         1e-13),
+        ((7.06791362314716-7.219497492626728j),
+         (1.0020740683598117-0.006752725913243711j),
+         1e-13),
+        ((-6.806227077655519+2.724411451005281j),
+         (0.06312488213559667-0.061641496333765956j),
+         1e-13),
+        ((-3.0170751511621026-6.3686522550665945j),
+         (-0.10330747857150148-1.214541994832571j),
+         1e-13),
+        # Moderately large imaginary part in each quadrant outside of critical strip
+        ((6.133994402212294+60.03091448000761j),
+         (0.9885701843417336+0.009636925981078128j),
+         1e-13),
+        ((6.17268142822657-64.74883149743795j),
+         (1.0080474225840865+0.012032804974965354j),
+         1e-13),
+        ((-3.462191939791879+76.16258975567534j),
+         (18672.072070850158+2908.5104826247184j),
+         1e-13),
+        ((-6.955735216531752-74.75791554155748j),
+         (-77672258.72276545+71625206.0401107j),
+         1e-13),
+        # Points in critical strip
+        ((0.4088038289823922+1.4596830498094384j),
+         (0.3032837969400845-0.47272237994110344j),
+         1e-13),
+        ((0.9673493951209633+4.918968547259143j),
+         (0.7488756907431944+0.17281553371482428j),
+         1e-13),
+        ((0.8692482679977754+66.6142398421354j),
+         (0.5831942469552066-0.26848904799062334j),
+         1e-13),
+        ((0.42771847720003764+21.783747851715468j),
+         (0.4767032638444329+0.6898148744603123j),
+         1e-13),
+        ((0.20479494678428956+33.17656449538932j),
+         (-0.6983038977487848+0.18060923618150224j),
+         1e-13),
+        ((0.4088038289823922-1.4596830498094384j),
+         (0.3032837969400845+0.47272237994110344j),
+         1e-13),
+        ((0.9673493951209633-4.918968547259143j),
+         (0.7488756907431944-0.17281553371482428j),
+         1e-13),
+        ((0.8692482679977754-66.6142398421354j),
+         (0.5831942469552066+0.26848904799062334j),
+         1e-13),
+        ((0.42771847720003764-21.783747851715468j),
+         (0.4767032638444329-0.6898148744603123j),
+         1e-13),
+        ((0.20479494678428956-33.17656449538932j),
+         (-0.6983038977487848-0.18060923618150224j),
+         1e-13),
+        # Near small trivial zeros
+        ((-2+1e-15j), (3.288175809370978e-32-3.0448457058393275e-17j), 1e-07),
+        ((-4+1e-15j), (-2.868707923051182e-33+7.983811450268625e-18j), 1e-07),
+        ((-6+1e-15j), (-1.7064292323640116e-34-5.8997591435159376e-18j), 1e-07),
+        ((-8+1e-15j), (2.5060859548261706e-33+8.316161985602247e-18j), 1e-07),
+        ((-2-1e-15j), (3.288175809371319e-32+3.0448457058393275e-17j), 1e-07),
+        ((-4-1e-15j), (-2.8687079230520114e-33-7.983811450268625e-18j), 1e-07),
+        ((-6-1e-15j), (-1.70642923235801e-34+5.8997591435159376e-18j), 1e-07),
+        ((-8-1e-15j), (2.5060859548253293e-33-8.316161985602247e-18j), 1e-07),
+        # Some other points near real axis
+        ((-0.5+1e-15j), (-0.20788622497735457-3.608543395999408e-16j), 1e-07),
+        (1e-15j, (-0.5-9.189384239689193e-16j), 1e-07),
+        ((0.2+1e-15j), (-0.7339209248963406-1.4828001150329085e-15j), 1e-07),
+        ((0.75+1e-15j), (-3.4412853869452227-1.5924832114302393e-14j), 1e-13),
+        ((-0.5-1e-15j), (-0.20788622497735457+3.608543395999408e-16j), 1e-07),
+        (-1e-15j, (-0.5+9.189387416062746e-16j), 1e-07),
+        ((0.2-1e-15j), (-0.7339209248963406+1.4828004007675122e-15j), 1e-07),
+        ((0.75-1e-15j), (-3.4412853869452227+1.5924831974403957e-14j), 1e-13),
+        # Moderately large real part
+        ((49.33915930750887+53.213478698903955j),
+         (1.0000000000000009+1.0212452494616078e-15j),
+         1e-13),
+        ((50.55805244181687+53.213478698903955j),
+         (1.0000000000000004+4.387394180390787e-16j),
+         1e-13),
+        ((49.33915930750887+40.6366015728302j),
+         (0.9999999999999986-1.502268709924849e-16j),
+         1e-13),
+        ((50.55805244181687+40.6366015728302j),
+         (0.9999999999999994-6.453929613571651e-17j),
+         1e-13),
+        ((49.33915930750887+85.83555435273925j),
+         (0.9999999999999987-2.7014400611995846e-16j),
+         1e-13),
+        ((50.55805244181687+85.83555435273925j),
+         (0.9999999999999994-1.160571605555322e-16j),
+         1e-13),
+        # Very large imaginary part
+        ((0.5+1e6j), (0.0760890697382271+2.805102101019299j), 1e-07),
+        ((34.812847097948854+1e6j),
+         (1.0000000000102545+3.150848654056419e-11j),
+         1e-13),
+        ((50.55805244181687+1e6j),
+         (1.0000000000000002+5.736517078070873e-16j),
+         1e-13),
+        ((0.5-1e6j), (0.0760890697382271-2.805102101019299j), 1e-07),
+        ((34.812847097948854-1e6j),
+         (1.0000000000102545-3.150848654056419e-11j),
+         1e-13),
+        ((50.55805244181687-1e6j),
+         (1.0000000000000002-5.736517078070873e-16j),
+         1e-13),
+        ((-294.86605461349745+13.992648136816397j), (-np.inf+np.inf*1j), 1e-13),
+        ((-294.86605461349745-16.147667799398363j), (np.inf-np.inf*1j), 1e-13),
+    ]
+)
+def test_riemann_zeta_complex(z, desired, rtol):
+    assert_allclose(sc.zeta(z), desired, rtol=rtol)
+
+
+# Some of the test cases below fail for intel compilers
+cpp_compiler = scipy.__config__.CONFIG["Compilers"]["c++"]["name"]
+gcc_linux = cpp_compiler == "gcc" and sys.platform == "linux"
+clang_macOS = cpp_compiler == "clang" and sys.platform == "darwin"
+
+
+@pytest.mark.skipif(
+    not (gcc_linux or clang_macOS),
+    reason="Underflow may not be avoided on other platforms",
+)
+@pytest.mark.parametrize(
+    "z, desired, rtol",
+    [
+        # Test cases generated as part of same script for
+        # test_riemann_zeta_complex. These cases are split off because
+        # they fail on some platforms.
+        #
+        # Naive implementation of reflection formula suffers internal overflow
+        ((-217.40285743524163+13.992648136816397j),
+         (-6.012818500554211e+249-1.926943776932387e+250j),
+         5e-13,),
+        ((-237.71710702931668+13.992648136816397j),
+         (-8.823803086106129e+281-5.009074181335139e+281j),
+         1e-13,),
+        ((-217.40285743524163-16.147667799398363j),
+         (-5.111612904844256e+251-4.907132127666742e+250j),
+         5e-13,),
+        ((-237.71710702931668-16.147667799398363j),
+         (-1.3256112779883167e+283-2.253002003455494e+283j),
+         5e-13,),
+    ],
+)
+def test_riemann_zeta_complex_avoid_underflow(z, desired, rtol):
+    assert_allclose(sc.zeta(z), desired, rtol=rtol)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h
new file mode 100644
index 0000000000000000000000000000000000000000..6a9b9ead9d7d458b47c5a51fd3104c9f72ff20a5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/binom.h
@@ -0,0 +1,89 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ *
+ * Original authors: Pauli Virtanen, Eric Moore
+ */
+
+// Binomial coefficient
+
+#pragma once
+
+#include "config.h"
+
+#include "cephes/beta.h"
+#include "cephes/gamma.h"
+
+namespace xsf {
+
+XSF_HOST_DEVICE inline double binom(double n, double k) {
+    double kx, nx, num, den, dk, sgn;
+
+    if (n < 0) {
+        nx = std::floor(n);
+        if (n == nx) {
+            // Undefined
+            return std::numeric_limits::quiet_NaN();
+        }
+    }
+
+    kx = std::floor(k);
+    if (k == kx && (std::abs(n) > 1E-8 || n == 0)) {
+        /* Integer case: use multiplication formula for less rounding
+         * error for cases where the result is an integer.
+         *
+         * This cannot be used for small nonzero n due to loss of
+         * precision. */
+        nx = std::floor(n);
+        if (nx == n && kx > nx / 2 && nx > 0) {
+            // Reduce kx by symmetry
+            kx = nx - kx;
+        }
+
+        if (kx >= 0 && kx < 20) {
+            num = 1.0;
+            den = 1.0;
+            for (int i = 1; i < 1 + static_cast(kx); i++) {
+                num *= i + n - kx;
+                den *= i;
+                if (std::abs(num) > 1E50) {
+                    num /= den;
+                    den = 1.0;
+                }
+            }
+            return num / den;
+        }
+    }
+
+    // general case
+    if (n >= 1E10 * k and k > 0) {
+        // avoid under/overflows intermediate results
+        return std::exp(-cephes::lbeta(1 + n - k, 1 + k) - std::log(n + 1));
+    }
+    if (k > 1E8 * std::abs(n)) {
+        // avoid loss of precision
+        num = cephes::Gamma(1 + n) / std::abs(k) + cephes::Gamma(1 + n) * n / (2 * k * k); // + ...
+        num /= M_PI * std::pow(std::abs(k), n);
+        if (k > 0) {
+            kx = std::floor(k);
+            if (static_cast(kx) == kx) {
+                dk = k - kx;
+                sgn = (static_cast(kx) % 2 == 0) ? 1 : -1;
+            } else {
+                dk = k;
+                sgn = 1;
+            }
+            return num * std::sin((dk - n) * M_PI) * sgn;
+        }
+        kx = std::floor(k);
+        if (static_cast(kx) == kx) {
+            return 0;
+        }
+        return num * std::sin(k * M_PI);
+    }
+    return 1 / (n + 1) / cephes::beta(1 + n - k, 1 + k);
+}
+
+XSF_HOST_DEVICE inline float binom(float n, float k) {
+    return binom(static_cast(n), static_cast(k));
+}
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h
new file mode 100644
index 0000000000000000000000000000000000000000..1ce5550efb6d2b13a45e22c0cbea7952bbd7938c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cdflib.h
@@ -0,0 +1,100 @@
+
+#pragma once
+
+#include "cephes/igam.h"
+#include "config.h"
+#include "error.h"
+#include "tools.h"
+
+namespace xsf {
+
+XSF_HOST_DEVICE inline double gdtrib(double a, double p, double x) {
+    if (std::isnan(p) || std::isnan(a) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (!((0 <= p) && (p <= 1))) {
+        set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter p is out of range");
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (!(a > 0) || std::isinf(a)) {
+        set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter a is out of range");
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (!(x >= 0) || std::isinf(x)) {
+        set_error("gdtrib", SF_ERROR_DOMAIN, "Input parameter x is out of range");
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0.0) {
+        if (p == 0.0) {
+            set_error("gdtrib", SF_ERROR_DOMAIN, "Indeterminate result for (x, p) == (0, 0).");
+            return std::numeric_limits::quiet_NaN();
+        }
+        /* gdtrib(a, p, x) tends to 0 as x -> 0 when p > 0 */
+        return 0.0;
+    }
+    if (p == 0.0) {
+        /* gdtrib(a, p, x) tends to infinity as p -> 0 from the right when x > 0. */
+        set_error("gdtrib", SF_ERROR_SINGULAR, NULL);
+        return std::numeric_limits::infinity();
+    }
+    if (p == 1.0) {
+        /* gdtrib(a, p, x) tends to 0 as p -> 1.0 from the left when x > 0. */
+        return 0.0;
+    }
+    double q = 1.0 - p;
+    auto func = [a, p, q, x](double b) {
+	if (p <= q) {
+	    return cephes::igam(b, a * x) - p;
+	}
+	return q - cephes::igamc(b, a * x);
+    };
+    double lower_bound = std::numeric_limits::min();
+    double upper_bound = std::numeric_limits::max();
+    /* To explain the magic constants used below:
+     * 1.0 is the initial guess for the root. -0.875 is the initial step size
+     * for the leading bracket endpoint if the bracket search will proceed to the
+     * left, likewise 7.0 is the initial step size when the bracket search will
+     * proceed to the right. 0.125 is the scale factor for a left moving bracket
+     * search and 8.0 the scale factor for a right moving bracket search. These
+     * constants are chosen so that:
+     *
+     * 1. The scale factor and bracket endpoints remain powers of 2, allowing for
+     *    exact arithmetic, preventing roundoff error from causing numerical catastrophe
+     *    which could lead to unexpected results.
+     * 2. The bracket sizes remain constant in a relative sense. Each candidate bracket
+     *    will contain roughly the same number of floating point values. This means that
+     *    the number of necessary function evaluations in the worst case scenario for
+     *    Chandrupatla's algorithm will remain constant.
+     *
+     * false specifies that the function is not decreasing. 342 is equal to
+     * max(ceil(log_8(DBL_MAX)), ceil(log_(1/8)(DBL_MIN))). An upper bound for the
+     * number of iterations needed in this bracket search to check all normalized
+     * floating point values.
+     */
+    auto [xl, xr, f_xl, f_xr, bracket_status] = detail::bracket_root_for_cdf_inversion(
+        func, 1.0, lower_bound, upper_bound, -0.875, 7.0, 0.125, 8, false, 342
+    );
+    if (bracket_status == 1) {
+        set_error("gdtrib", SF_ERROR_UNDERFLOW, NULL);
+        return 0.0;
+    }
+    if (bracket_status == 2) {
+        set_error("gdtrib", SF_ERROR_OVERFLOW, NULL);
+        return std::numeric_limits::infinity();
+    }
+    if (bracket_status >= 3) {
+        set_error("gdtrib", SF_ERROR_OTHER, "Computational Error");
+        return std::numeric_limits::quiet_NaN();
+    }
+    auto [result, root_status] = detail::find_root_chandrupatla(
+        func, xl, xr, f_xl, f_xr, std::numeric_limits::epsilon(), 1e-100, 100
+    );
+    if (root_status) {
+        /* The root finding return should only fail if there's a bug in our code. */
+        set_error("gdtrib", SF_ERROR_OTHER, "Computational Error, (%.17g, %.17g, %.17g)", a, p, x);
+        return std::numeric_limits::quiet_NaN();
+    }
+    return result;
+}
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h
new file mode 100644
index 0000000000000000000000000000000000000000..8db31fa9b3830b1e561a27a349154fc96ab071d3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/airy.h
@@ -0,0 +1,307 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     airy.c
+ *
+ *     Airy function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, ai, aip, bi, bip;
+ * int airy();
+ *
+ * airy( x, _&ai, _&aip, _&bi, _&bip );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Solution of the differential equation
+ *
+ *     y"(x) = xy.
+ *
+ * The function returns the two independent solutions Ai, Bi
+ * and their first derivatives Ai'(x), Bi'(x).
+ *
+ * Evaluation is by power series summation for small x,
+ * by rational minimax approximations for large x.
+ *
+ *
+ *
+ * ACCURACY:
+ * Error criterion is absolute when function <= 1, relative
+ * when function > 1, except * denotes relative error criterion.
+ * For large negative x, the absolute error increases as x^1.5.
+ * For large positive x, the relative error increases as x^1.5.
+ *
+ * Arithmetic  domain   function  # trials      peak         rms
+ * IEEE        -10, 0     Ai        10000       1.6e-15     2.7e-16
+ * IEEE          0, 10    Ai        10000       2.3e-14*    1.8e-15*
+ * IEEE        -10, 0     Ai'       10000       4.6e-15     7.6e-16
+ * IEEE          0, 10    Ai'       10000       1.8e-14*    1.5e-15*
+ * IEEE        -10, 10    Bi        30000       4.2e-15     5.3e-16
+ * IEEE        -10, 10    Bi'       30000       4.9e-15     7.3e-16
+ *
+ */
+/*							airy.c */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double airy_c1 = 0.35502805388781723926;
+        constexpr double airy_c2 = 0.258819403792806798405;
+        constexpr double MAXAIRY = 103.892;
+
+        constexpr double airy_AN[8] = {
+            3.46538101525629032477E-1, 1.20075952739645805542E1, 7.62796053615234516538E1, 1.68089224934630576269E2,
+            1.59756391350164413639E2,  7.05360906840444183113E1, 1.40264691163389668864E1, 9.99999999999999995305E-1,
+        };
+
+        constexpr double airy_AD[8] = {
+            5.67594532638770212846E-1, 1.47562562584847203173E1, 8.45138970141474626562E1, 1.77318088145400459522E2,
+            1.64234692871529701831E2,  7.14778400825575695274E1, 1.40959135607834029598E1, 1.00000000000000000470E0,
+        };
+
+        constexpr double airy_APN[8] = {
+            6.13759184814035759225E-1, 1.47454670787755323881E1, 8.20584123476060982430E1, 1.71184781360976385540E2,
+            1.59317847137141783523E2,  6.99778599330103016170E1, 1.39470856980481566958E1, 1.00000000000000000550E0,
+        };
+
+        constexpr double airy_APD[8] = {
+            3.34203677749736953049E-1, 1.11810297306158156705E1, 7.11727352147859965283E1, 1.58778084372838313640E2,
+            1.53206427475809220834E2,  6.86752304592780337944E1, 1.38498634758259442477E1, 9.99999999999999994502E-1,
+        };
+
+        constexpr double airy_BN16[5] = {
+            -2.53240795869364152689E-1, 5.75285167332467384228E-1,  -3.29907036873225371650E-1,
+            6.44404068948199951727E-2,  -3.82519546641336734394E-3,
+        };
+
+        constexpr double airy_BD16[5] = {
+            /* 1.00000000000000000000E0, */
+            -7.15685095054035237902E0, 1.06039580715664694291E1,   -5.23246636471251500874E0,
+            9.57395864378383833152E-1, -5.50828147163549611107E-2,
+        };
+
+        constexpr double airy_BPPN[5] = {
+            4.65461162774651610328E-1,  -1.08992173800493920734E0, 6.38800117371827987759E-1,
+            -1.26844349553102907034E-1, 7.62487844342109852105E-3,
+        };
+
+        constexpr double airy_BPPD[5] = {
+            /* 1.00000000000000000000E0, */
+            -8.70622787633159124240E0, 1.38993162704553213172E1,   -7.14116144616431159572E0,
+            1.34008595960680518666E0,  -7.84273211323341930448E-2,
+        };
+
+        constexpr double airy_AFN[9] = {
+            -1.31696323418331795333E-1, -6.26456544431912369773E-1, -6.93158036036933542233E-1,
+            -2.79779981545119124951E-1, -4.91900132609500318020E-2, -4.06265923594885404393E-3,
+            -1.59276496239262096340E-4, -2.77649108155232920844E-6, -1.67787698489114633780E-8,
+        };
+
+        constexpr double airy_AFD[9] = {
+            /* 1.00000000000000000000E0, */
+            1.33560420706553243746E1,  3.26825032795224613948E1,  2.67367040941499554804E1,
+            9.18707402907259625840E0,  1.47529146771666414581E0,  1.15687173795188044134E-1,
+            4.40291641615211203805E-3, 7.54720348287414296618E-5, 4.51850092970580378464E-7,
+        };
+
+        constexpr double airy_AGN[11] = {
+            1.97339932091685679179E-2, 3.91103029615688277255E-1, 1.06579897599595591108E0,   9.39169229816650230044E-1,
+            3.51465656105547619242E-1, 6.33888919628925490927E-2, 5.85804113048388458567E-3,  2.82851600836737019778E-4,
+            6.98793669997260967291E-6, 8.11789239554389293311E-8, 3.41551784765923618484E-10,
+        };
+
+        constexpr double airy_AGD[10] = {
+            /*  1.00000000000000000000E0, */
+            9.30892908077441974853E0,  1.98352928718312140417E1,  1.55646628932864612953E1,  5.47686069422975497931E0,
+            9.54293611618961883998E-1, 8.64580826352392193095E-2, 4.12656523824222607191E-3, 1.01259085116509135510E-4,
+            1.17166733214413521882E-6, 4.91834570062930015649E-9,
+        };
+
+        constexpr double airy_APFN[9] = {
+            1.85365624022535566142E-1, 8.86712188052584095637E-1, 9.87391981747398547272E-1,
+            4.01241082318003734092E-1, 7.10304926289631174579E-2, 5.90618657995661810071E-3,
+            2.33051409401776799569E-4, 4.08718778289035454598E-6, 2.48379932900442457853E-8,
+        };
+
+        constexpr double airy_APFD[9] = {
+            /*  1.00000000000000000000E0, */
+            1.47345854687502542552E1,  3.75423933435489594466E1,  3.14657751203046424330E1,
+            1.09969125207298778536E1,  1.78885054766999417817E0,  1.41733275753662636873E-1,
+            5.44066067017226003627E-3, 9.39421290654511171663E-5, 5.65978713036027009243E-7,
+        };
+
+        constexpr double airy_APGN[11] = {
+            -3.55615429033082288335E-2, -6.37311518129435504426E-1,  -1.70856738884312371053E0,
+            -1.50221872117316635393E0,  -5.63606665822102676611E-1,  -1.02101031120216891789E-1,
+            -9.48396695961445269093E-3, -4.60325307486780994357E-4,  -1.14300836484517375919E-5,
+            -1.33415518685547420648E-7, -5.63803833958893494476E-10,
+        };
+
+        constexpr double airy_APGD[11] = {
+            /*  1.00000000000000000000E0, */
+            9.85865801696130355144E0,  2.16401867356585941885E1,  1.73130776389749389525E1,  6.17872175280828766327E0,
+            1.08848694396321495475E0,  9.95005543440888479402E-2, 4.78468199683886610842E-3, 1.18159633322838625562E-4,
+            1.37480673554219441465E-6, 5.79912514929147598821E-9,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline int airy(double x, double *ai, double *aip, double *bi, double *bip) {
+        double z, zz, t, f, g, uf, ug, k, zeta, theta;
+        int domflg;
+
+        domflg = 0;
+        if (x > detail::MAXAIRY) {
+            *ai = 0;
+            *aip = 0;
+            *bi = std::numeric_limits::infinity();
+            *bip = std::numeric_limits::infinity();
+            return (-1);
+        }
+
+        if (x < -2.09) {
+            domflg = 15;
+            t = std::sqrt(-x);
+            zeta = -2.0 * x * t / 3.0;
+            t = std::sqrt(t);
+            k = detail::SQRT1OPI / t;
+            z = 1.0 / zeta;
+            zz = z * z;
+            uf = 1.0 + zz * polevl(zz, detail::airy_AFN, 8) / p1evl(zz, detail::airy_AFD, 9);
+            ug = z * polevl(zz, detail::airy_AGN, 10) / p1evl(zz, detail::airy_AGD, 10);
+            theta = zeta + 0.25 * M_PI;
+            f = std::sin(theta);
+            g = std::cos(theta);
+            *ai = k * (f * uf - g * ug);
+            *bi = k * (g * uf + f * ug);
+            uf = 1.0 + zz * polevl(zz, detail::airy_APFN, 8) / p1evl(zz, detail::airy_APFD, 9);
+            ug = z * polevl(zz, detail::airy_APGN, 10) / p1evl(zz, detail::airy_APGD, 10);
+            k = detail::SQRT1OPI * t;
+            *aip = -k * (g * uf + f * ug);
+            *bip = k * (f * uf - g * ug);
+            return (0);
+        }
+
+        if (x >= 2.09) { /* cbrt(9) */
+            domflg = 5;
+            t = std::sqrt(x);
+            zeta = 2.0 * x * t / 3.0;
+            g = std::exp(zeta);
+            t = std::sqrt(t);
+            k = 2.0 * t * g;
+            z = 1.0 / zeta;
+            f = polevl(z, detail::airy_AN, 7) / polevl(z, detail::airy_AD, 7);
+            *ai = detail::SQRT1OPI * f / k;
+            k = -0.5 * detail::SQRT1OPI * t / g;
+            f = polevl(z, detail::airy_APN, 7) / polevl(z, detail::airy_APD, 7);
+            *aip = f * k;
+
+            if (x > 8.3203353) { /* zeta > 16 */
+                f = z * polevl(z, detail::airy_BN16, 4) / p1evl(z, detail::airy_BD16, 5);
+                k = detail::SQRT1OPI * g;
+                *bi = k * (1.0 + f) / t;
+                f = z * polevl(z, detail::airy_BPPN, 4) / p1evl(z, detail::airy_BPPD, 5);
+                *bip = k * t * (1.0 + f);
+                return (0);
+            }
+        }
+
+        f = 1.0;
+        g = x;
+        t = 1.0;
+        uf = 1.0;
+        ug = x;
+        k = 1.0;
+        z = x * x * x;
+        while (t > detail::MACHEP) {
+            uf *= z;
+            k += 1.0;
+            uf /= k;
+            ug *= z;
+            k += 1.0;
+            ug /= k;
+            uf /= k;
+            f += uf;
+            k += 1.0;
+            ug /= k;
+            g += ug;
+            t = std::abs(uf / f);
+        }
+        uf = detail::airy_c1 * f;
+        ug = detail::airy_c2 * g;
+        if ((domflg & 1) == 0) {
+            *ai = uf - ug;
+        }
+        if ((domflg & 2) == 0) {
+            *bi = detail::SQRT3 * (uf + ug);
+        }
+
+        /* the deriviative of ai */
+        k = 4.0;
+        uf = x * x / 2.0;
+        ug = z / 3.0;
+        f = uf;
+        g = 1.0 + ug;
+        uf /= 3.0;
+        t = 1.0;
+
+        while (t > detail::MACHEP) {
+            uf *= z;
+            ug /= k;
+            k += 1.0;
+            ug *= z;
+            uf /= k;
+            f += uf;
+            k += 1.0;
+            ug /= k;
+            uf /= k;
+            g += ug;
+            k += 1.0;
+            t = std::abs(ug / g);
+        }
+
+        uf = detail::airy_c1 * f;
+        ug = detail::airy_c2 * g;
+        if ((domflg & 4) == 0) {
+            *aip = uf - ug;
+        }
+        if ((domflg & 8) == 0) {
+            *bip = detail::SQRT3 * (uf + ug);
+        };
+        return (0);
+    }
+
+    inline int airy(float xf, float *aif, float *aipf, float *bif, float *bipf) {
+        double ai;
+        double aip;
+        double bi;
+        double bip;
+        int res = cephes::airy(xf, &ai, &aip, &bi, &bip);
+
+        *aif = ai;
+        *aipf = aip;
+        *bif = bi;
+        *bipf = bip;
+        return res;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h
new file mode 100644
index 0000000000000000000000000000000000000000..d113b8b7d0f4ae4e7ad9da2faf66d3ab7406d736
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/besselpoly.h
@@ -0,0 +1,51 @@
+/* Translated into C++ by SciPy developers in 2024.
+ *
+ * This was not part of the original cephes library.
+ */
+#pragma once
+
+#include "../config.h"
+#include "gamma.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+
+        constexpr double besselpoly_EPS = 1.0e-17;
+    }
+
+    XSF_HOST_DEVICE inline double besselpoly(double a, double lambda, double nu) {
+
+        int m, factor = 0;
+        double Sm, relerr, Sol;
+        double sum = 0.0;
+
+        /* Special handling for a = 0.0 */
+        if (a == 0.0) {
+            if (nu == 0.0) {
+                return 1.0 / (lambda + 1);
+            } else {
+                return 0.0;
+            }
+        }
+        /* Special handling for negative and integer nu */
+        if ((nu < 0) && (std::floor(nu) == nu)) {
+            nu = -nu;
+            factor = static_cast(nu) % 2;
+        }
+        Sm = std::exp(nu * std::log(a)) / (Gamma(nu + 1) * (lambda + nu + 1));
+        m = 0;
+        do {
+            sum += Sm;
+            Sol = Sm;
+            Sm *= -a * a * (lambda + nu + 1 + 2 * m) / ((nu + m + 1) * (m + 1) * (lambda + nu + 1 + 2 * m + 2));
+            m++;
+            relerr = std::abs((Sm - Sol) / Sm);
+        } while (relerr > detail::besselpoly_EPS && m < 1000);
+        if (!factor)
+            return sum;
+        else
+            return -sum;
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h
new file mode 100644
index 0000000000000000000000000000000000000000..437262793e8f94b229671978b23a638820ff1290
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/beta.h
@@ -0,0 +1,257 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     beta.c
+ *
+ *     Beta function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, b, y, beta();
+ *
+ * y = beta( a, b );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ *                   -     -
+ *                  | (a) | (b)
+ * beta( a, b )  =  -----------.
+ *                     -
+ *                    | (a+b)
+ *
+ * For large arguments the logarithm of the function is
+ * evaluated using lgam(), then exponentiated.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0,30       30000       8.1e-14     1.1e-14
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition          value returned
+ * beta overflow    log(beta) > MAXLOG       0.0
+ *                  a or b <0 integer        0.0
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "const.h"
+#include "gamma.h"
+#include "rgamma.h"
+
+namespace xsf {
+namespace cephes {
+
+    XSF_HOST_DEVICE double beta(double, double);
+    XSF_HOST_DEVICE double lbeta(double, double);
+
+    namespace detail {
+        constexpr double beta_ASYMP_FACTOR = 1e6;
+
+        /*
+         * Asymptotic expansion for  ln(|B(a, b)|) for a > ASYMP_FACTOR*max(|b|, 1).
+         */
+        XSF_HOST_DEVICE inline double lbeta_asymp(double a, double b, int *sgn) {
+            double r = lgam_sgn(b, sgn);
+            r -= b * std::log(a);
+
+            r += b * (1 - b) / (2 * a);
+            r += b * (1 - b) * (1 - 2 * b) / (12 * a * a);
+            r += -b * b * (1 - b) * (1 - b) / (12 * a * a * a);
+
+            return r;
+        }
+
+        /*
+         * Special case for a negative integer argument
+         */
+
+        XSF_HOST_DEVICE inline double beta_negint(int a, double b) {
+            int sgn;
+            if (b == static_cast(b) && 1 - a - b > 0) {
+                sgn = (static_cast(b) % 2 == 0) ? 1 : -1;
+                return sgn * xsf::cephes::beta(1 - a - b, b);
+            } else {
+                set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
+                return std::numeric_limits::infinity();
+            }
+        }
+
+        XSF_HOST_DEVICE inline double lbeta_negint(int a, double b) {
+            double r;
+            if (b == static_cast(b) && 1 - a - b > 0) {
+                r = xsf::cephes::lbeta(1 - a - b, b);
+                return r;
+            } else {
+                set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
+                return std::numeric_limits::infinity();
+            }
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double beta(double a, double b) {
+        double y;
+        int sign = 1;
+
+        if (a <= 0.0) {
+            if (a == std::floor(a)) {
+                if (a == static_cast(a)) {
+                    return detail::beta_negint(static_cast(a), b);
+                } else {
+                    goto overflow;
+                }
+            }
+        }
+
+        if (b <= 0.0) {
+            if (b == std::floor(b)) {
+                if (b == static_cast(b)) {
+                    return detail::beta_negint(static_cast(b), a);
+                } else {
+                    goto overflow;
+                }
+            }
+        }
+
+        if (std::abs(a) < std::abs(b)) {
+            y = a;
+            a = b;
+            b = y;
+        }
+
+        if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) {
+            /* Avoid loss of precision in lgam(a + b) - lgam(a) */
+            y = detail::lbeta_asymp(a, b, &sign);
+            return sign * std::exp(y);
+        }
+
+        y = a + b;
+        if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) {
+            int sgngam;
+            y = detail::lgam_sgn(y, &sgngam);
+            sign *= sgngam; /* keep track of the sign */
+            y = detail::lgam_sgn(b, &sgngam) - y;
+            sign *= sgngam;
+            y = detail::lgam_sgn(a, &sgngam) + y;
+            sign *= sgngam;
+            if (y > detail::MAXLOG) {
+                goto overflow;
+            }
+            return (sign * std::exp(y));
+        }
+
+        y = rgamma(y);
+        a = Gamma(a);
+        b = Gamma(b);
+        if (std::isinf(y)) {
+            goto overflow;
+	}
+
+        if (std::abs(std::abs(a*y) - 1.0) > std::abs(std::abs(b*y) - 1.0)) {
+            y = b * y;
+            y *= a;
+        } else {
+            y = a * y;
+            y *= b;
+        }
+
+        return (y);
+
+    overflow:
+        set_error("beta", SF_ERROR_OVERFLOW, NULL);
+        return (sign * std::numeric_limits::infinity());
+    }
+
+    /* Natural log of |beta|. */
+
+    XSF_HOST_DEVICE inline double lbeta(double a, double b) {
+        double y;
+        int sign;
+
+        sign = 1;
+
+        if (a <= 0.0) {
+            if (a == std::floor(a)) {
+                if (a == static_cast(a)) {
+                    return detail::lbeta_negint(static_cast(a), b);
+                } else {
+                    goto over;
+                }
+            }
+        }
+
+        if (b <= 0.0) {
+            if (b == std::floor(b)) {
+                if (b == static_cast(b)) {
+                    return detail::lbeta_negint(static_cast(b), a);
+                } else {
+                    goto over;
+                }
+            }
+        }
+
+        if (std::abs(a) < std::abs(b)) {
+            y = a;
+            a = b;
+            b = y;
+        }
+
+        if (std::abs(a) > detail::beta_ASYMP_FACTOR * std::abs(b) && a > detail::beta_ASYMP_FACTOR) {
+            /* Avoid loss of precision in lgam(a + b) - lgam(a) */
+            y = detail::lbeta_asymp(a, b, &sign);
+            return y;
+        }
+
+        y = a + b;
+        if (std::abs(y) > detail::MAXGAM || std::abs(a) > detail::MAXGAM || std::abs(b) > detail::MAXGAM) {
+            int sgngam;
+            y = detail::lgam_sgn(y, &sgngam);
+            sign *= sgngam; /* keep track of the sign */
+            y = detail::lgam_sgn(b, &sgngam) - y;
+            sign *= sgngam;
+            y = detail::lgam_sgn(a, &sgngam) + y;
+            sign *= sgngam;
+            return (y);
+        }
+
+        y = rgamma(y);
+        a = Gamma(a);
+        b = Gamma(b);
+        if (std::isinf(y)) {
+        over:
+            set_error("lbeta", SF_ERROR_OVERFLOW, NULL);
+            return (sign * std::numeric_limits::infinity());
+        }
+
+        if (std::abs(std::abs(a*y) - 1.0) > std::abs(std::abs(b*y) - 1.0)) {
+            y = b * y;
+            y *= a;
+        } else {
+            y = a * y;
+            y *= b;
+        }
+
+        if (y < 0) {
+            y = -y;
+        }
+
+        return (std::log(y));
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h
new file mode 100644
index 0000000000000000000000000000000000000000..3e9fbd4eab45b24f1caa8b509c9d1d3c536867fe
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/cbrt.h
@@ -0,0 +1,131 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     cbrt.c
+ *
+ *     Cube root
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, cbrt();
+ *
+ * y = cbrt( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the cube root of the argument, which may be negative.
+ *
+ * Range reduction involves determining the power of 2 of
+ * the argument.  A polynomial of degree 2 applied to the
+ * mantissa, and multiplication by the cube root of 1, 2, or 4
+ * approximates the root to within about 0.1%.  Then Newton's
+ * iteration is used three times to converge to an accurate
+ * result.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0,1e308     30000      1.5e-16     5.0e-17
+ *
+ */
+/*							cbrt.c  */
+
+/*
+ * Cephes Math Library Release 2.2:  January, 1991
+ * Copyright 1984, 1991 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double CBRT2 = 1.2599210498948731647672;
+        constexpr double CBRT4 = 1.5874010519681994747517;
+        constexpr double CBRT2I = 0.79370052598409973737585;
+        constexpr double CBRT4I = 0.62996052494743658238361;
+
+        XSF_HOST_DEVICE inline double cbrt(double x) {
+            int e, rem, sign;
+            double z;
+
+            if (!std::isfinite(x)) {
+                return x;
+            }
+            if (x == 0) {
+                return (x);
+            }
+            if (x > 0) {
+                sign = 1;
+            } else {
+                sign = -1;
+                x = -x;
+            }
+
+            z = x;
+            /* extract power of 2, leaving
+             * mantissa between 0.5 and 1
+             */
+            x = std::frexp(x, &e);
+
+            /* Approximate cube root of number between .5 and 1,
+             * peak relative error = 9.2e-6
+             */
+            x = (((-1.3466110473359520655053e-1 * x + 5.4664601366395524503440e-1) * x - 9.5438224771509446525043e-1) *
+                     x +
+                 1.1399983354717293273738e0) *
+                    x +
+                4.0238979564544752126924e-1;
+
+            /* exponent divided by 3 */
+            if (e >= 0) {
+                rem = e;
+                e /= 3;
+                rem -= 3 * e;
+                if (rem == 1) {
+                    x *= CBRT2;
+                } else if (rem == 2) {
+                    x *= CBRT4;
+                }
+            }
+            /* argument less than 1 */
+            else {
+                e = -e;
+                rem = e;
+                e /= 3;
+                rem -= 3 * e;
+                if (rem == 1) {
+                    x *= CBRT2I;
+                } else if (rem == 2) {
+                    x *= CBRT4I;
+                }
+                e = -e;
+            }
+
+            /* multiply by power of 2 */
+            x = std::ldexp(x, e);
+
+            /* Newton iteration */
+            x -= (x - (z / (x * x))) * 0.33333333333333333333;
+            x -= (x - (z / (x * x))) * 0.33333333333333333333;
+
+            if (sign < 0)
+                x = -x;
+            return (x);
+        }
+    } // namespace detail
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h
new file mode 100644
index 0000000000000000000000000000000000000000..caaa74fc7b81015784608cc38aed5987ca145526
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chbevl.h
@@ -0,0 +1,85 @@
+/*                                                     chbevl.c
+ *
+ *     Evaluate Chebyshev series
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * int N;
+ * double x, y, coef[N], chebevl();
+ *
+ * y = chbevl( x, coef, N );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates the series
+ *
+ *        N-1
+ *         - '
+ *  y  =   >   coef[i] T (x/2)
+ *         -            i
+ *        i=0
+ *
+ * of Chebyshev polynomials Ti at argument x/2.
+ *
+ * Coefficients are stored in reverse order, i.e. the zero
+ * order term is last in the array.  Note N is the number of
+ * coefficients, not the order.
+ *
+ * If coefficients are for the interval a to b, x must
+ * have been transformed to x -> 2(2x - b - a)/(b-a) before
+ * entering the routine.  This maps x from (a, b) to (-1, 1),
+ * over which the Chebyshev polynomials are defined.
+ *
+ * If the coefficients are for the inverted interval, in
+ * which (a, b) is mapped to (1/b, 1/a), the transformation
+ * required is x -> 2(2ab/x - b - a)/(b-a).  If b is infinity,
+ * this becomes x -> 4a/x - 1.
+ *
+ *
+ *
+ * SPEED:
+ *
+ * Taking advantage of the recurrence properties of the
+ * Chebyshev polynomials, the routine requires one more
+ * addition per loop than evaluating a nested polynomial of
+ * the same degree.
+ *
+ */
+/*							chbevl.c	*/
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+
+    XSF_HOST_DEVICE double chbevl(double x, const double array[], int n) {
+        double b0, b1, b2;
+        const double *p;
+        int i;
+
+        p = array;
+        b0 = *p++;
+        b1 = 0.0;
+        i = n - 1;
+
+        do {
+            b2 = b1;
+            b1 = b0;
+            b0 = x * b1 - b2 + *p++;
+        } while (--i);
+
+        return (0.5 * (b0 - b2));
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h
new file mode 100644
index 0000000000000000000000000000000000000000..0a97def6d00baa18eaffaca73c92d7b6dd2b5e32
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/chdtr.h
@@ -0,0 +1,193 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     chdtr.c
+ *
+ *     Chi-square distribution
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double df, x, y, chdtr();
+ *
+ * y = chdtr( df, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the area under the left hand tail (from 0 to x)
+ * of the Chi square probability density function with
+ * v degrees of freedom.
+ *
+ *
+ *                                  inf.
+ *                                    -
+ *                        1          | |  v/2-1  -t/2
+ *  P( x | v )   =   -----------     |   t      e     dt
+ *                    v/2  -       | |
+ *                   2    | (v/2)   -
+ *                                   x
+ *
+ * where x is the Chi-square variable.
+ *
+ * The incomplete Gamma integral is used, according to the
+ * formula
+ *
+ *     y = chdtr( v, x ) = igam( v/2.0, x/2.0 ).
+ *
+ *
+ * The arguments must both be positive.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * See igam().
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * chdtr domain   x < 0 or v < 1        0.0
+ */
+/*							chdtrc()
+ *
+ *	Complemented Chi-square distribution
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double v, x, y, chdtrc();
+ *
+ * y = chdtrc( v, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the area under the right hand tail (from x to
+ * infinity) of the Chi square probability density function
+ * with v degrees of freedom:
+ *
+ *
+ *                                  inf.
+ *                                    -
+ *                        1          | |  v/2-1  -t/2
+ *  P( x | v )   =   -----------     |   t      e     dt
+ *                    v/2  -       | |
+ *                   2    | (v/2)   -
+ *                                   x
+ *
+ * where x is the Chi-square variable.
+ *
+ * The incomplete Gamma integral is used, according to the
+ * formula
+ *
+ *	y = chdtr( v, x ) = igamc( v/2.0, x/2.0 ).
+ *
+ *
+ * The arguments must both be positive.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * See igamc().
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * chdtrc domain  x < 0 or v < 1        0.0
+ */
+/*							chdtri()
+ *
+ *	Inverse of complemented Chi-square distribution
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double df, x, y, chdtri();
+ *
+ * x = chdtri( df, y );
+ *
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Finds the Chi-square argument x such that the integral
+ * from x to infinity of the Chi-square density is equal
+ * to the given cumulative probability y.
+ *
+ * This is accomplished using the inverse Gamma integral
+ * function and the relation
+ *
+ *    x/2 = igamci( df/2, y );
+ *
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * See igami.c.
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * chdtri domain   y < 0 or y > 1        0.0
+ *                     v < 1
+ *
+ */
+
+/*                                                             chdtr() */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "igam.h"
+#include "igami.h"
+
+namespace xsf {
+namespace cephes {
+
+    XSF_HOST_DEVICE inline double chdtrc(double df, double x) {
+
+        if (x < 0.0)
+            return 1.0; /* modified by T. Oliphant */
+        return (igamc(df / 2.0, x / 2.0));
+    }
+
+    XSF_HOST_DEVICE inline double chdtr(double df, double x) {
+
+        if ((x < 0.0)) { /* || (df < 1.0) ) */
+            set_error("chdtr", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+        return (igam(df / 2.0, x / 2.0));
+    }
+
+    XSF_HOST_DEVICE double chdtri(double df, double y) {
+        double x;
+
+        if ((y < 0.0) || (y > 1.0)) { /* || (df < 1.0) ) */
+            set_error("chdtri", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+
+        x = igamci(0.5 * df, y);
+        return (2.0 * x);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h
new file mode 100644
index 0000000000000000000000000000000000000000..d7b162c5efc8e11f407c6108d55c117820e9e76d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/const.h
@@ -0,0 +1,87 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ *
+ * Since we support only IEEE-754 floating point numbers, conditional logic
+ * supporting other arithmetic types has been removed.
+ */
+
+/*
+ *
+ *
+ *                                                   const.c
+ *
+ *     Globally declared constants
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * extern double nameofconstant;
+ *
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * This file contains a number of mathematical constants and
+ * also some needed size parameters of the computer arithmetic.
+ * The values are supplied as arrays of hexadecimal integers
+ * for IEEE arithmetic, and in a normal decimal scientific notation for
+ * other machines.  The particular notation used is determined
+ * by a symbol (IBMPC, or UNK) defined in the include file
+ * mconf.h.
+ *
+ * The default size parameters are as follows.
+ *
+ * For UNK mode:
+ * MACHEP =  1.38777878078144567553E-17       2**-56
+ * MAXLOG =  8.8029691931113054295988E1       log(2**127)
+ * MINLOG = -8.872283911167299960540E1        log(2**-128)
+ *
+ * For IEEE arithmetic (IBMPC):
+ * MACHEP =  1.11022302462515654042E-16       2**-53
+ * MAXLOG =  7.09782712893383996843E2         log(2**1024)
+ * MINLOG = -7.08396418532264106224E2         log(2**-1022)
+ *
+ * The global symbols for mathematical constants are
+ * SQ2OPI =  7.9788456080286535587989E-1      sqrt( 2/pi )
+ * LOGSQ2 =  3.46573590279972654709E-1        log(2)/2
+ * THPIO4 =  2.35619449019234492885           3*pi/4
+ *
+ * These lists are subject to change.
+ */
+/*                                                     const.c */
+
+/*
+ * Cephes Math Library Release 2.3:  March, 1995
+ * Copyright 1984, 1995 by Stephen L. Moshier
+ */
+#pragma once
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+        constexpr std::uint64_t MAXITER = 500;
+        constexpr double MACHEP = 1.11022302462515654042E-16;    // 2**-53
+        constexpr double MAXLOG = 7.09782712893383996732E2;      // log(DBL_MAX)
+        constexpr double MINLOG = -7.451332191019412076235E2;    // log 2**-1022
+        constexpr double SQRT1OPI = 5.64189583547756286948E-1;   // sqrt( 1/pi)
+        constexpr double SQRT2OPI = 7.9788456080286535587989E-1; // sqrt( 2/pi )
+        constexpr double SQRT2PI = 0.79788456080286535587989;    // sqrt(2pi)
+        constexpr double LOGSQ2 = 3.46573590279972654709E-1;     // log(2)/2
+        constexpr double THPIO4 = 2.35619449019234492885;        // 3*pi/4
+        constexpr double SQRT3 = 1.732050807568877293527;        // sqrt(3)
+        constexpr double PI180 = 1.74532925199432957692E-2;      // pi/180
+        constexpr double SQRTPI = 2.50662827463100050242E0;      // sqrt(pi)
+        constexpr double LOGPI = 1.14472988584940017414;         // log(pi)
+        constexpr double MAXGAM = 171.624376956302725;
+        constexpr double LOGSQRT2PI = 0.9189385332046727; // log(sqrt(pi))
+
+        // Following two added by SciPy developers.
+        // Euler's constant
+        constexpr double SCIPY_EULER = 0.577215664901532860606512090082402431;
+        // e as long double
+        constexpr long double SCIPY_El = 2.718281828459045235360287471352662498L;
+    } // namespace detail
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h
new file mode 100644
index 0000000000000000000000000000000000000000..a455599b4a95b3c69d23df188669e84deac4e31c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellie.h
@@ -0,0 +1,293 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellie.c
+ *
+ *     Incomplete elliptic integral of the second kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double phi, m, y, ellie();
+ *
+ * y = ellie( phi, m );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *                 phi
+ *                  -
+ *                 | |
+ *                 |                   2
+ * E(phi_\m)  =    |    sqrt( 1 - m sin t ) dt
+ *                 |
+ *               | |
+ *                -
+ *                 0
+ *
+ * of amplitude phi and modulus m, using the arithmetic -
+ * geometric mean algorithm.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at random arguments with phi in [-10, 10] and m in
+ * [0, 1].
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -10,10      150000       3.3e-15     1.4e-16
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987, 1993 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+/* Copyright 2014, Eric W. Moore */
+
+/*     Incomplete elliptic integral of second kind     */
+#pragma once
+
+#include "../config.h"
+#include "const.h"
+#include "ellpe.h"
+#include "ellpk.h"
+#include "unity.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+
+        /* To calculate legendre's incomplete elliptical integral of the second kind for
+         * negative m, we use a power series in phi for small m*phi*phi, an asymptotic
+         * series in m for large m*phi*phi* and the relation to Carlson's symmetric
+         * integrals, R_F(x,y,z) and R_D(x,y,z).
+         *
+         * E(phi, m) = sin(phi) * R_F(cos(phi)^2, 1 - m * sin(phi)^2, 1.0)
+         *             - m * sin(phi)^3 * R_D(cos(phi)^2, 1 - m * sin(phi)^2, 1.0) / 3
+         *
+         *           = R_F(c-1, c-m, c) - m * R_D(c-1, c-m, c) / 3
+         *
+         * where c = csc(phi)^2. We use the second form of this for (approximately)
+         * phi > 1/(sqrt(DBL_MAX) ~ 1e-154, where csc(phi)^2 overflows. Elsewhere we
+         * use the first form, accounting for the smallness of phi.
+         *
+         * The algorithm used is described in Carlson, B. C. Numerical computation of
+         * real or complex elliptic integrals. (1994) https://arxiv.org/abs/math/9409227
+         * Most variable names reflect Carlson's usage.
+         *
+         * In this routine, we assume m < 0 and  0 > phi > pi/2.
+         */
+        XSF_HOST_DEVICE inline double ellie_neg_m(double phi, double m) {
+            double x, y, z, x1, y1, z1, ret, Q;
+            double A0f, Af, Xf, Yf, Zf, E2f, E3f, scalef;
+            double A0d, Ad, seriesn, seriesd, Xd, Yd, Zd, E2d, E3d, E4d, E5d, scaled;
+            int n = 0;
+            double mpp = (m * phi) * phi;
+
+            if (-mpp < 1e-6 && phi < -m) {
+                return phi + (mpp * phi * phi / 30.0 - mpp * mpp / 40.0 - mpp / 6.0) * phi;
+            }
+
+            if (-mpp > 1e6) {
+                double sm = std::sqrt(-m);
+                double sp = std::sin(phi);
+                double cp = std::cos(phi);
+
+                double a = -cosm1(phi);
+                double b1 = std::log(4 * sp * sm / (1 + cp));
+                double b = -(0.5 + b1) / 2.0 / m;
+                double c = (0.75 + cp / sp / sp - b1) / 16.0 / m / m;
+                return (a + b + c) * sm;
+            }
+
+            if (phi > 1e-153 && m > -1e200) {
+                double s = std::sin(phi);
+                double csc2 = 1.0 / s / s;
+                scalef = 1.0;
+                scaled = m / 3.0;
+                x = 1.0 / std::tan(phi) / std::tan(phi);
+                y = csc2 - m;
+                z = csc2;
+            } else {
+                scalef = phi;
+                scaled = mpp * phi / 3.0;
+                x = 1.0;
+                y = 1 - mpp;
+                z = 1.0;
+            }
+
+            if (x == y && x == z) {
+                return (scalef + scaled / x) / std::sqrt(x);
+            }
+
+            A0f = (x + y + z) / 3.0;
+            Af = A0f;
+            A0d = (x + y + 3.0 * z) / 5.0;
+            Ad = A0d;
+            x1 = x;
+            y1 = y;
+            z1 = z;
+            seriesd = 0.0;
+            seriesn = 1.0;
+            /* Carlson gives 1/pow(3*r, 1.0/6.0) for this constant. if r == eps,
+             * it is ~338.38. */
+
+            /* N.B. This will evaluate its arguments multiple times. */
+            Q = 400.0 * std::fmax(std::abs(A0f - x), std::fmax(std::abs(A0f - y), std::abs(A0f - z)));
+
+            while (Q > std::abs(Af) && Q > std::abs(Ad) && n <= 100) {
+                double sx = std::sqrt(x1);
+                double sy = std::sqrt(y1);
+                double sz = std::sqrt(z1);
+                double lam = sx * sy + sx * sz + sy * sz;
+                seriesd += seriesn / (sz * (z1 + lam));
+                x1 = (x1 + lam) / 4.0;
+                y1 = (y1 + lam) / 4.0;
+                z1 = (z1 + lam) / 4.0;
+                Af = (x1 + y1 + z1) / 3.0;
+                Ad = (Ad + lam) / 4.0;
+                n += 1;
+                Q /= 4.0;
+                seriesn /= 4.0;
+            }
+
+            Xf = (A0f - x) / Af / (1 << 2 * n);
+            Yf = (A0f - y) / Af / (1 << 2 * n);
+            Zf = -(Xf + Yf);
+
+            E2f = Xf * Yf - Zf * Zf;
+            E3f = Xf * Yf * Zf;
+
+            ret = scalef * (1.0 - E2f / 10.0 + E3f / 14.0 + E2f * E2f / 24.0 - 3.0 * E2f * E3f / 44.0) / sqrt(Af);
+
+            Xd = (A0d - x) / Ad / (1 << 2 * n);
+            Yd = (A0d - y) / Ad / (1 << 2 * n);
+            Zd = -(Xd + Yd) / 3.0;
+
+            E2d = Xd * Yd - 6.0 * Zd * Zd;
+            E3d = (3 * Xd * Yd - 8.0 * Zd * Zd) * Zd;
+            E4d = 3.0 * (Xd * Yd - Zd * Zd) * Zd * Zd;
+            E5d = Xd * Yd * Zd * Zd * Zd;
+
+            ret -= scaled *
+                   (1.0 - 3.0 * E2d / 14.0 + E3d / 6.0 + 9.0 * E2d * E2d / 88.0 - 3.0 * E4d / 22.0 -
+                    9.0 * E2d * E3d / 52.0 + 3.0 * E5d / 26.0) /
+                   (1 << 2 * n) / Ad / sqrt(Ad);
+            ret -= 3.0 * scaled * seriesd;
+            return ret;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellie(double phi, double m) {
+        double a, b, c, e, temp;
+        double lphi, t, E, denom, npio2;
+        int d, mod, sign;
+
+        if (std::isnan(phi) || std::isnan(m))
+            return std::numeric_limits::quiet_NaN();
+        if (m > 1.0)
+            return std::numeric_limits::quiet_NaN();
+        ;
+        if (std::isinf(phi))
+            return phi;
+        if (std::isinf(m))
+            return -m;
+        if (m == 0.0)
+            return (phi);
+        lphi = phi;
+        npio2 = std::floor(lphi / M_PI_2);
+        if (std::fmod(std::abs(npio2), 2.0) == 1.0)
+            npio2 += 1;
+        lphi = lphi - npio2 * M_PI_2;
+        if (lphi < 0.0) {
+            lphi = -lphi;
+            sign = -1;
+        } else {
+            sign = 1;
+        }
+        a = 1.0 - m;
+        E = ellpe(m);
+        if (a == 0.0) {
+            temp = std::sin(lphi);
+            goto done;
+        }
+        if (a > 1.0) {
+            temp = detail::ellie_neg_m(lphi, m);
+            goto done;
+        }
+
+        if (lphi < 0.135) {
+            double m11 = (((((-7.0 / 2816.0) * m + (5.0 / 1056.0)) * m - (7.0 / 2640.0)) * m + (17.0 / 41580.0)) * m -
+                          (1.0 / 155925.0)) *
+                         m;
+            double m9 = ((((-5.0 / 1152.0) * m + (1.0 / 144.0)) * m - (1.0 / 360.0)) * m + (1.0 / 5670.0)) * m;
+            double m7 = ((-m / 112.0 + (1.0 / 84.0)) * m - (1.0 / 315.0)) * m;
+            double m5 = (-m / 40.0 + (1.0 / 30)) * m;
+            double m3 = -m / 6.0;
+            double p2 = lphi * lphi;
+
+            temp = ((((m11 * p2 + m9) * p2 + m7) * p2 + m5) * p2 + m3) * p2 * lphi + lphi;
+            goto done;
+        }
+        t = std::tan(lphi);
+        b = std::sqrt(a);
+        /* Thanks to Brian Fitzgerald 
+         * for pointing out an instability near odd multiples of pi/2.  */
+        if (std::abs(t) > 10.0) {
+            /* Transform the amplitude */
+            e = 1.0 / (b * t);
+            /* ... but avoid multiple recursions.  */
+            if (std::abs(e) < 10.0) {
+                e = std::atan(e);
+                temp = E + m * std::sin(lphi) * std::sin(e) - ellie(e, m);
+                goto done;
+            }
+        }
+        c = std::sqrt(m);
+        a = 1.0;
+        d = 1;
+        e = 0.0;
+        mod = 0;
+
+        while (std::abs(c / a) > detail::MACHEP) {
+            temp = b / a;
+            lphi = lphi + atan(t * temp) + mod * M_PI;
+            denom = 1 - temp * t * t;
+            if (std::abs(denom) > 10 * detail::MACHEP) {
+                t = t * (1.0 + temp) / denom;
+                mod = (lphi + M_PI_2) / M_PI;
+            } else {
+                t = std::tan(lphi);
+                mod = static_cast(std::floor((lphi - std::atan(t)) / M_PI));
+            }
+            c = (a - b) / 2.0;
+            temp = std::sqrt(a * b);
+            a = (a + b) / 2.0;
+            b = temp;
+            d += d;
+            e += c * std::sin(lphi);
+        }
+
+        temp = E / ellpk(1.0 - m);
+        temp *= (std::atan(t) + mod * M_PI) / (d * a);
+        temp += e;
+
+    done:
+
+        if (sign < 0)
+            temp = -temp;
+        temp += npio2 * E;
+        return (temp);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h
new file mode 100644
index 0000000000000000000000000000000000000000..c05b3ec76c2e9a3acbc947842e0a849f5ba837e0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellik.h
@@ -0,0 +1,251 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellik.c
+ *
+ *     Incomplete elliptic integral of the first kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double phi, m, y, ellik();
+ *
+ * y = ellik( phi, m );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *
+ *                phi
+ *                 -
+ *                | |
+ *                |           dt
+ * F(phi | m) =   |    ------------------
+ *                |                   2
+ *              | |    sqrt( 1 - m sin t )
+ *               -
+ *                0
+ *
+ * of amplitude phi and modulus m, using the arithmetic -
+ * geometric mean algorithm.
+ *
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at random points with m in [0, 1] and phi as indicated.
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -10,10       200000      7.4e-16     1.0e-16
+ *
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+/* Copyright 2014, Eric W. Moore */
+
+/*     Incomplete elliptic integral of first kind      */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "ellpk.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* To calculate legendre's incomplete elliptical integral of the first kind for
+         * negative m, we use a power series in phi for small m*phi*phi, an asymptotic
+         * series in m for large m*phi*phi* and the relation to Carlson's symmetric
+         * integral of the first kind.
+         *
+         * F(phi, m) = sin(phi) * R_F(cos(phi)^2, 1 - m * sin(phi)^2, 1.0)
+         *           = R_F(c-1, c-m, c)
+         *
+         * where c = csc(phi)^2. We use the second form of this for (approximately)
+         * phi > 1/(sqrt(DBL_MAX) ~ 1e-154, where csc(phi)^2 overflows. Elsewhere we
+         * use the first form, accounting for the smallness of phi.
+         *
+         * The algorithm used is described in Carlson, B. C. Numerical computation of
+         * real or complex elliptic integrals. (1994) https://arxiv.org/abs/math/9409227
+         * Most variable names reflect Carlson's usage.
+         *
+         * In this routine, we assume m < 0 and  0 > phi > pi/2.
+         */
+        XSF_HOST_DEVICE inline double ellik_neg_m(double phi, double m) {
+            double x, y, z, x1, y1, z1, A0, A, Q, X, Y, Z, E2, E3, scale;
+            int n = 0;
+            double mpp = (m * phi) * phi;
+
+            if (-mpp < 1e-6 && phi < -m) {
+                return phi + (-mpp * phi * phi / 30.0 + 3.0 * mpp * mpp / 40.0 + mpp / 6.0) * phi;
+            }
+
+            if (-mpp > 4e7) {
+                double sm = std::sqrt(-m);
+                double sp = std::sin(phi);
+                double cp = std::cos(phi);
+
+                double a = std::log(4 * sp * sm / (1 + cp));
+                double b = -(1 + cp / sp / sp - a) / 4 / m;
+                return (a + b) / sm;
+            }
+
+            if (phi > 1e-153 && m > -1e305) {
+                double s = std::sin(phi);
+                double csc2 = 1.0 / (s * s);
+                scale = 1.0;
+                x = 1.0 / (std::tan(phi) * std::tan(phi));
+                y = csc2 - m;
+                z = csc2;
+            } else {
+                scale = phi;
+                x = 1.0;
+                y = 1 - m * scale * scale;
+                z = 1.0;
+            }
+
+            if (x == y && x == z) {
+                return scale / std::sqrt(x);
+            }
+
+            A0 = (x + y + z) / 3.0;
+            A = A0;
+            x1 = x;
+            y1 = y;
+            z1 = z;
+            /* Carlson gives 1/pow(3*r, 1.0/6.0) for this constant. if r == eps,
+             * it is ~338.38. */
+            Q = 400.0 * std::fmax(std::abs(A0 - x), std::fmax(std::abs(A0 - y), std::abs(A0 - z)));
+
+            while (Q > std::abs(A) && n <= 100) {
+                double sx = std::sqrt(x1);
+                double sy = std::sqrt(y1);
+                double sz = std::sqrt(z1);
+                double lam = sx * sy + sx * sz + sy * sz;
+                x1 = (x1 + lam) / 4.0;
+                y1 = (y1 + lam) / 4.0;
+                z1 = (z1 + lam) / 4.0;
+                A = (x1 + y1 + z1) / 3.0;
+                n += 1;
+                Q /= 4;
+            }
+            X = (A0 - x) / A / (1 << 2 * n);
+            Y = (A0 - y) / A / (1 << 2 * n);
+            Z = -(X + Y);
+
+            E2 = X * Y - Z * Z;
+            E3 = X * Y * Z;
+
+            return scale * (1.0 - E2 / 10.0 + E3 / 14.0 + E2 * E2 / 24.0 - 3.0 * E2 * E3 / 44.0) / sqrt(A);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellik(double phi, double m) {
+        double a, b, c, e, temp, t, K, denom, npio2;
+        int d, mod, sign;
+
+        if (std::isnan(phi) || std::isnan(m))
+            return std::numeric_limits::quiet_NaN();
+        if (m > 1.0)
+            return std::numeric_limits::quiet_NaN();
+        if (std::isinf(phi) || std::isinf(m)) {
+            if (std::isinf(m) && std::isfinite(phi))
+                return 0.0;
+            else if (std::isinf(phi) && std::isfinite(m))
+                return phi;
+            else
+                return std::numeric_limits::quiet_NaN();
+        }
+        if (m == 0.0)
+            return (phi);
+        a = 1.0 - m;
+        if (a == 0.0) {
+            if (std::abs(phi) >= (double) M_PI_2) {
+                set_error("ellik", SF_ERROR_SINGULAR, NULL);
+                return (std::numeric_limits::infinity());
+            }
+            /* DLMF 19.6.8, and 4.23.42 */
+            return std::asinh(std::tan(phi));
+        }
+        npio2 = floor(phi / M_PI_2);
+        if (std::fmod(std::abs(npio2), 2.0) == 1.0)
+            npio2 += 1;
+        if (npio2 != 0.0) {
+            K = ellpk(a);
+            phi = phi - npio2 * M_PI_2;
+        } else
+            K = 0.0;
+        if (phi < 0.0) {
+            phi = -phi;
+            sign = -1;
+        } else
+            sign = 0;
+        if (a > 1.0) {
+            temp = detail::ellik_neg_m(phi, m);
+            goto done;
+        }
+        b = std::sqrt(a);
+        t = std::tan(phi);
+        if (std::abs(t) > 10.0) {
+            /* Transform the amplitude */
+            e = 1.0 / (b * t);
+            /* ... but avoid multiple recursions.  */
+            if (std::abs(e) < 10.0) {
+                e = std::atan(e);
+                if (npio2 == 0)
+                    K = ellpk(a);
+                temp = K - ellik(e, m);
+                goto done;
+            }
+        }
+        a = 1.0;
+        c = std::sqrt(m);
+        d = 1;
+        mod = 0;
+
+        while (std::abs(c / a) > detail::MACHEP) {
+            temp = b / a;
+            phi = phi + atan(t * temp) + mod * M_PI;
+            denom = 1.0 - temp * t * t;
+            if (std::abs(denom) > 10 * detail::MACHEP) {
+                t = t * (1.0 + temp) / denom;
+                mod = (phi + M_PI_2) / M_PI;
+            } else {
+                t = std::tan(phi);
+                mod = static_cast(std::floor((phi - std::atan(t)) / M_PI));
+            }
+            c = (a - b) / 2.0;
+            temp = std::sqrt(a * b);
+            a = (a + b) / 2.0;
+            b = temp;
+            d += d;
+        }
+
+        temp = (std::atan(t) + mod * M_PI) / (d * a);
+
+    done:
+        if (sign < 0)
+            temp = -temp;
+        temp += npio2 * K;
+        return (temp);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h
new file mode 100644
index 0000000000000000000000000000000000000000..bc7c51f11acb13179aaffb301d052308722f8cfa
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpe.h
@@ -0,0 +1,107 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellpe.c
+ *
+ *     Complete elliptic integral of the second kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double m, y, ellpe();
+ *
+ * y = ellpe( m );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *            pi/2
+ *             -
+ *            | |                 2
+ * E(m)  =    |    sqrt( 1 - m sin t ) dt
+ *          | |
+ *           -
+ *            0
+ *
+ * Where m = 1 - m1, using the approximation
+ *
+ *      P(x)  -  x log x Q(x).
+ *
+ * Though there are no singularities, the argument m1 is used
+ * internally rather than m for compatibility with ellpk().
+ *
+ * E(1) = 1; E(0) = pi/2.
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0, 1       10000       2.1e-16     7.3e-17
+ *
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * ellpe domain      x<0, x>1            0.0
+ *
+ */
+
+/*                                                     ellpe.c         */
+
+/* Elliptic integral of second kind */
+
+/*
+ * Cephes Math Library, Release 2.1:  February, 1989
+ * Copyright 1984, 1987, 1989 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ *
+ * Feb, 2002:  altered by Travis Oliphant
+ * so that it is called with argument m
+ * (which gets immediately converted to m1 = 1-m)
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double ellpe_P[] = {1.53552577301013293365E-4, 2.50888492163602060990E-3, 8.68786816565889628429E-3,
+                                      1.07350949056076193403E-2, 7.77395492516787092951E-3, 7.58395289413514708519E-3,
+                                      1.15688436810574127319E-2, 2.18317996015557253103E-2, 5.68051945617860553470E-2,
+                                      4.43147180560990850618E-1, 1.00000000000000000299E0};
+
+        constexpr double ellpe_Q[] = {3.27954898576485872656E-5, 1.00962792679356715133E-3, 6.50609489976927491433E-3,
+                                      1.68862163993311317300E-2, 2.61769742454493659583E-2, 3.34833904888224918614E-2,
+                                      4.27180926518931511717E-2, 5.85936634471101055642E-2, 9.37499997197644278445E-2,
+                                      2.49999999999888314361E-1};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellpe(double x) {
+        x = 1.0 - x;
+        if (x <= 0.0) {
+            if (x == 0.0)
+                return (1.0);
+            set_error("ellpe", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+        if (x > 1.0) {
+            return ellpe(1.0 - 1 / x) * std::sqrt(x);
+        }
+        return (polevl(x, detail::ellpe_P, 10) - std::log(x) * (x * polevl(x, detail::ellpe_Q, 9)));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h
new file mode 100644
index 0000000000000000000000000000000000000000..39ebf7e80b193d385acb45feead4b91632830642
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ellpk.h
@@ -0,0 +1,117 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ellpk.c
+ *
+ *     Complete elliptic integral of the first kind
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double m1, y, ellpk();
+ *
+ * y = ellpk( m1 );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integral
+ *
+ *
+ *
+ *            pi/2
+ *             -
+ *            | |
+ *            |           dt
+ * K(m)  =    |    ------------------
+ *            |                   2
+ *          | |    sqrt( 1 - m sin t )
+ *           -
+ *            0
+ *
+ * where m = 1 - m1, using the approximation
+ *
+ *     P(x)  -  log x Q(x).
+ *
+ * The argument m1 is used internally rather than m so that the logarithmic
+ * singularity at m = 1 will be shifted to the origin; this
+ * preserves maximum accuracy.
+ *
+ * K(0) = pi/2.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE       0,1        30000       2.5e-16     6.8e-17
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * ellpk domain       x<0, x>1           0.0
+ *
+ */
+
+/*                                                     ellpk.c */
+
+/*
+ * Cephes Math Library, Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double ellpk_P[] = {1.37982864606273237150E-4, 2.28025724005875567385E-3, 7.97404013220415179367E-3,
+                                      9.85821379021226008714E-3, 6.87489687449949877925E-3, 6.18901033637687613229E-3,
+                                      8.79078273952743772254E-3, 1.49380448916805252718E-2, 3.08851465246711995998E-2,
+                                      9.65735902811690126535E-2, 1.38629436111989062502E0};
+
+        constexpr double ellpk_Q[] = {2.94078955048598507511E-5, 9.14184723865917226571E-4, 5.94058303753167793257E-3,
+                                      1.54850516649762399335E-2, 2.39089602715924892727E-2, 3.01204715227604046988E-2,
+                                      3.73774314173823228969E-2, 4.88280347570998239232E-2, 7.03124996963957469739E-2,
+                                      1.24999999999870820058E-1, 4.99999999999999999821E-1};
+
+        constexpr double ellpk_C1 = 1.3862943611198906188E0; /* log(4) */
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double ellpk(double x) {
+
+        if (x < 0.0) {
+            set_error("ellpk", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+
+        if (x > 1.0) {
+            if (std::isinf(x)) {
+                return 0.0;
+            }
+            return ellpk(1 / x) / std::sqrt(x);
+        }
+
+        if (x > detail::MACHEP) {
+            return (polevl(x, detail::ellpk_P, 10) - std::log(x) * polevl(x, detail::ellpk_Q, 10));
+        } else {
+            if (x == 0.0) {
+                set_error("ellpk", SF_ERROR_SINGULAR, NULL);
+                return (std::numeric_limits::infinity());
+            } else {
+                return (detail::ellpk_C1 - 0.5 * std::log(x));
+            }
+        }
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h
new file mode 100644
index 0000000000000000000000000000000000000000..8b0b07eab7a94fb1519566da4ef9036fb67edec6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/expn.h
@@ -0,0 +1,260 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     expn.c
+ *
+ *             Exponential integral En
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * int n;
+ * double x, y, expn();
+ *
+ * y = expn( n, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates the exponential integral
+ *
+ *                 inf.
+ *                   -
+ *                  | |   -xt
+ *                  |    e
+ *      E (x)  =    |    ----  dt.
+ *       n          |      n
+ *                | |     t
+ *                 -
+ *                  1
+ *
+ *
+ * Both n and x must be nonnegative.
+ *
+ * The routine employs either a power series, a continued
+ * fraction, or an asymptotic formula depending on the
+ * relative values of n and x.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       10000       1.7e-15     3.6e-16
+ *
+ */
+
+/*                                                     expn.c  */
+
+/* Cephes Math Library Release 1.1:  March, 1985
+ * Copyright 1985 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */
+
+/* Sources
+ * [1] NIST, "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ */
+
+/* Scipy changes:
+ * - 09-10-2016: improved asymptotic expansion for large n
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "rgamma.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int expn_nA = 13;
+        constexpr double expn_A0[] = {1.00000000000000000};
+        constexpr double expn_A1[] = {1.00000000000000000};
+        constexpr double expn_A2[] = {-2.00000000000000000, 1.00000000000000000};
+        constexpr double expn_A3[] = {6.00000000000000000, -8.00000000000000000, 1.00000000000000000};
+        constexpr double expn_A4[] = {-24.0000000000000000, 58.0000000000000000, -22.0000000000000000,
+                                      1.00000000000000000};
+        constexpr double expn_A5[] = {120.000000000000000, -444.000000000000000, 328.000000000000000,
+                                      -52.0000000000000000, 1.00000000000000000};
+        constexpr double expn_A6[] = {-720.000000000000000, 3708.00000000000000,  -4400.00000000000000,
+                                      1452.00000000000000,  -114.000000000000000, 1.00000000000000000};
+        constexpr double expn_A7[] = {5040.00000000000000,  -33984.0000000000000, 58140.0000000000000,
+                                      -32120.0000000000000, 5610.00000000000000,  -240.000000000000000,
+                                      1.00000000000000000};
+        constexpr double expn_A8[] = {-40320.0000000000000, 341136.000000000000,  -785304.000000000000,
+                                      644020.000000000000,  -195800.000000000000, 19950.0000000000000,
+                                      -494.000000000000000, 1.00000000000000000};
+        constexpr double expn_A9[] = {362880.000000000000,  -3733920.00000000000, 11026296.0000000000,
+                                      -12440064.0000000000, 5765500.00000000000,  -1062500.00000000000,
+                                      67260.0000000000000,  -1004.00000000000000, 1.00000000000000000};
+        constexpr double expn_A10[] = {-3628800.00000000000, 44339040.0000000000,  -162186912.000000000,
+                                       238904904.000000000,  -155357384.000000000, 44765000.0000000000,
+                                       -5326160.00000000000, 218848.000000000000,  -2026.00000000000000,
+                                       1.00000000000000000};
+        constexpr double expn_A11[] = {39916800.0000000000,  -568356480.000000000, 2507481216.00000000,
+                                       -4642163952.00000000, 4002695088.00000000,  -1648384304.00000000,
+                                       314369720.000000000,  -25243904.0000000000, 695038.000000000000,
+                                       -4072.00000000000000, 1.00000000000000000};
+        constexpr double expn_A12[] = {-479001600.000000000, 7827719040.00000000,  -40788301824.0000000,
+                                       92199790224.0000000,  -101180433024.000000, 56041398784.0000000,
+                                       -15548960784.0000000, 2051482776.00000000,  -114876376.000000000,
+                                       2170626.00000000000,  -8166.00000000000000, 1.00000000000000000};
+        constexpr const double *expn_A[] = {expn_A0, expn_A1, expn_A2, expn_A3,  expn_A4,  expn_A5, expn_A6,
+                                            expn_A7, expn_A8, expn_A9, expn_A10, expn_A11, expn_A12};
+        constexpr int expn_Adegs[] = {0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
+
+        /* Asymptotic expansion for large n, DLMF 8.20(ii) */
+        XSF_HOST_DEVICE double expn_large_n(int n, double x) {
+            int k;
+            double p = n;
+            double lambda = x / p;
+            double multiplier = 1 / p / (lambda + 1) / (lambda + 1);
+            double fac = 1;
+            double res = 1; /* A[0] = 1 */
+            double expfac, term;
+
+            expfac = std::exp(-lambda * p) / (lambda + 1) / p;
+            if (expfac == 0) {
+                set_error("expn", SF_ERROR_UNDERFLOW, NULL);
+                return 0;
+            }
+
+            /* Do the k = 1 term outside the loop since A[1] = 1 */
+            fac *= multiplier;
+            res += fac;
+
+            for (k = 2; k < expn_nA; k++) {
+                fac *= multiplier;
+                term = fac * polevl(lambda, expn_A[k], expn_Adegs[k]);
+                res += term;
+                if (std::abs(term) < MACHEP * std::abs(res)) {
+                    break;
+                }
+            }
+
+            return expfac * res;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE double expn(int n, double x) {
+        double ans, r, t, yk, xk;
+        double pk, pkm1, pkm2, qk, qkm1, qkm2;
+        double psi, z;
+        int i, k;
+        constexpr double big = 1.44115188075855872E+17;
+
+        if (std::isnan(x)) {
+            return std::numeric_limits::quiet_NaN();
+        } else if (n < 0 || x < 0) {
+            set_error("expn", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x > detail::MAXLOG) {
+            return (0.0);
+        }
+
+        if (x == 0.0) {
+            if (n < 2) {
+                set_error("expn", SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::infinity();
+            } else {
+                return (1.0 / (n - 1.0));
+            }
+        }
+
+        if (n == 0) {
+            return (std::exp(-x) / x);
+        }
+
+        /* Asymptotic expansion for large n, DLMF 8.20(ii) */
+        if (n > 50) {
+            ans = detail::expn_large_n(n, x);
+            return ans;
+        }
+
+        /* Continued fraction, DLMF 8.19.17 */
+        if (x > 1.0) {
+            k = 1;
+            pkm2 = 1.0;
+            qkm2 = x;
+            pkm1 = 1.0;
+            qkm1 = x + n;
+            ans = pkm1 / qkm1;
+
+            do {
+                k += 1;
+                if (k & 1) {
+                    yk = 1.0;
+                    xk = n + (k - 1) / 2;
+                } else {
+                    yk = x;
+                    xk = k / 2;
+                }
+                pk = pkm1 * yk + pkm2 * xk;
+                qk = qkm1 * yk + qkm2 * xk;
+                if (qk != 0) {
+                    r = pk / qk;
+                    t = std::abs((ans - r) / r);
+                    ans = r;
+                } else {
+                    t = 1.0;
+                }
+                pkm2 = pkm1;
+                pkm1 = pk;
+                qkm2 = qkm1;
+                qkm1 = qk;
+                if (std::abs(pk) > big) {
+                    pkm2 /= big;
+                    pkm1 /= big;
+                    qkm2 /= big;
+                    qkm1 /= big;
+                }
+            } while (t > detail::MACHEP);
+
+            ans *= std::exp(-x);
+            return ans;
+        }
+
+        /* Power series expansion, DLMF 8.19.8 */
+        psi = -detail::SCIPY_EULER - std::log(x);
+        for (i = 1; i < n; i++) {
+            psi = psi + 1.0 / i;
+        }
+
+        z = -x;
+        xk = 0.0;
+        yk = 1.0;
+        pk = 1.0 - n;
+        if (n == 1) {
+            ans = 0.0;
+        } else {
+            ans = 1.0 / pk;
+        }
+        do {
+            xk += 1.0;
+            yk *= z / xk;
+            pk += 1.0;
+            if (pk != 0.0) {
+                ans += yk / pk;
+            }
+            if (ans != 0.0)
+                t = std::abs(yk / ans);
+            else
+                t = 1.0;
+        } while (t > detail::MACHEP);
+        k = xk;
+        t = n;
+        r = n - 1;
+        ans = (std::pow(z, r) * psi * rgamma(t)) - ans;
+        return ans;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..1ede1571a67ec9ce54bb6aa1afa1f17f5708f0c0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/gamma.h
@@ -0,0 +1,398 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*
+ *     Gamma function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, Gamma();
+ *
+ * y = Gamma( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Gamma function of the argument.  The result is
+ * correctly signed.
+ *
+ * Arguments |x| <= 34 are reduced by recurrence and the function
+ * approximated by a rational function of degree 6/7 in the
+ * interval (2,3).  Large arguments are handled by Stirling's
+ * formula. Large negative arguments are made positive using
+ * a reflection formula.
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE    -170,-33      20000       2.3e-15     3.3e-16
+ *    IEEE     -33,  33     20000       9.4e-16     2.2e-16
+ *    IEEE      33, 171.6   20000       2.3e-15     3.2e-16
+ *
+ * Error for arguments outside the test range will be larger
+ * owing to error amplification by the exponential function.
+ *
+ */
+
+/*                                                     lgam()
+ *
+ *     Natural logarithm of Gamma function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, lgam();
+ *
+ * y = lgam( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the base e (2.718...) logarithm of the absolute
+ * value of the Gamma function of the argument.
+ *
+ * For arguments greater than 13, the logarithm of the Gamma
+ * function is approximated by the logarithmic version of
+ * Stirling's formula using a polynomial approximation of
+ * degree 4. Arguments between -33 and +33 are reduced by
+ * recurrence to the interval [2,3] of a rational approximation.
+ * The cosecant reflection formula is employed for arguments
+ * less than -33.
+ *
+ * Arguments greater than MAXLGM return INFINITY and an error
+ * message.  MAXLGM = 2.556348e305 for IEEE arithmetic.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *
+ * arithmetic      domain        # trials     peak         rms
+ *    IEEE    0, 3                 28000     5.4e-16     1.1e-16
+ *    IEEE    2.718, 2.556e305     40000     3.5e-16     8.3e-17
+ * The error criterion was relative when the function magnitude
+ * was greater than one but absolute when it was less than one.
+ *
+ * The following test used the relative error criterion, though
+ * at certain points the relative error could be much higher than
+ * indicated.
+ *    IEEE    -200, -4             10000     4.8e-16     1.3e-16
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.2:  July, 1992
+ * Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "polevl.h"
+#include "trig.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+        constexpr double gamma_P[] = {1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2,
+                                      4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1,
+                                      9.99999999999999996796E-1};
+
+        constexpr double gamma_Q[] = {-2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3,
+                                      1.18139785222060435552E-2,  3.58236398605498653373E-2, -2.34591795718243348568E-1,
+                                      7.14304917030273074085E-2,  1.00000000000000000320E0};
+
+        /* Stirling's formula for the Gamma function */
+        constexpr double gamma_STIR[5] = {
+            7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3,
+            3.47222221605458667310E-3, 8.33333333333482257126E-2,
+        };
+
+        constexpr double MAXSTIR = 143.01608;
+
+        /* Gamma function computed by Stirling's formula.
+         * The polynomial STIR is valid for 33 <= x <= 172.
+         */
+        XSF_HOST_DEVICE inline double stirf(double x) {
+            double y, w, v;
+
+            if (x >= MAXGAM) {
+                return (std::numeric_limits::infinity());
+            }
+            w = 1.0 / x;
+            w = 1.0 + w * xsf::cephes::polevl(w, gamma_STIR, 4);
+            y = std::exp(x);
+            if (x > MAXSTIR) { /* Avoid overflow in pow() */
+                v = std::pow(x, 0.5 * x - 0.25);
+                y = v * (v / y);
+            } else {
+                y = std::pow(x, x - 0.5) / y;
+            }
+            y = SQRTPI * y * w;
+            return (y);
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double Gamma(double x) {
+        double p, q, z;
+        int i;
+        int sgngam = 1;
+
+        if (!std::isfinite(x)) {
+	    if (x > 0) {
+		// gamma(+inf) = +inf
+		return x;
+	    }
+	    // gamma(NaN) and gamma(-inf) both should equal NaN.
+            return std::numeric_limits::quiet_NaN();
+        }
+
+	if (x == 0) {
+	    /* For pole at zero, value depends on sign of zero.
+	     * +inf when approaching from right, -inf when approaching
+	     * from left. */
+	    return std::copysign(std::numeric_limits::infinity(), x);
+	}
+
+        q = std::abs(x);
+
+        if (q > 33.0) {
+            if (x < 0.0) {
+                p = std::floor(q);
+                if (p == q) {
+		    // x is a negative integer. This is a pole.
+                    set_error("Gamma", SF_ERROR_SINGULAR, NULL);
+                    return (std::numeric_limits::quiet_NaN());
+                }
+                i = p;
+                if ((i & 1) == 0) {
+                    sgngam = -1;
+                }
+                z = q - p;
+                if (z > 0.5) {
+                    p += 1.0;
+                    z = q - p;
+                }
+                z = q * sinpi(z);
+                if (z == 0.0) {
+                    return (sgngam * std::numeric_limits::infinity());
+                }
+                z = std::abs(z);
+                z = M_PI / (z * detail::stirf(q));
+            } else {
+                z = detail::stirf(x);
+            }
+            return (sgngam * z);
+        }
+
+        z = 1.0;
+        while (x >= 3.0) {
+            x -= 1.0;
+            z *= x;
+        }
+
+        while (x < 0.0) {
+            if (x > -1.E-9) {
+                goto small;
+            }
+            z /= x;
+            x += 1.0;
+        }
+
+        while (x < 2.0) {
+            if (x < 1.e-9) {
+                goto small;
+            }
+            z /= x;
+            x += 1.0;
+        }
+
+        if (x == 2.0) {
+            return (z);
+        }
+
+        x -= 2.0;
+        p = polevl(x, detail::gamma_P, 6);
+        q = polevl(x, detail::gamma_Q, 7);
+        return (z * p / q);
+
+    small:
+        if (x == 0.0) {
+	    /* For this to have happened, x must have started as a negative integer. */
+	    set_error("Gamma", SF_ERROR_SINGULAR, NULL);
+	    return (std::numeric_limits::quiet_NaN());
+        } else
+            return (z / ((1.0 + 0.5772156649015329 * x) * x));
+    }
+
+    namespace detail {
+        /* A[]: Stirling's formula expansion of log Gamma
+         * B[], C[]: log Gamma function between 2 and 3
+         */
+        constexpr double gamma_A[] = {8.11614167470508450300E-4, -5.95061904284301438324E-4, 7.93650340457716943945E-4,
+                                      -2.77777777730099687205E-3, 8.33333333333331927722E-2};
+
+        constexpr double gamma_B[] = {-1.37825152569120859100E3, -3.88016315134637840924E4, -3.31612992738871184744E5,
+                                      -1.16237097492762307383E6, -1.72173700820839662146E6, -8.53555664245765465627E5};
+
+        constexpr double gamma_C[] = {
+            /* 1.00000000000000000000E0, */
+            -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5,
+            -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6};
+
+        /* log( sqrt( 2*pi ) ) */
+        constexpr double LS2PI = 0.91893853320467274178;
+
+        constexpr double MAXLGM = 2.556348e305;
+
+        /* Disable optimizations for this function on 32 bit systems when compiling with GCC.
+         * We've found that enabling optimizations can result in degraded precision
+         * for this asymptotic approximation in that case. */
+#if defined(__GNUC__) && defined(__i386__)
+#pragma GCC push_options
+#pragma GCC optimize("00")
+#endif
+        XSF_HOST_DEVICE inline double lgam_large_x(double x) {
+            double q = (x - 0.5) * std::log(x) - x + LS2PI;
+            if (x > 1.0e8) {
+                return (q);
+            }
+            double p = 1.0 / (x * x);
+            p = ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + 0.0833333333333333333333) / x;
+            return q + p;
+        }
+#if defined(__GNUC__) && defined(__i386__)
+#pragma GCC pop_options
+#endif
+
+        XSF_HOST_DEVICE inline double lgam_sgn(double x, int *sign) {
+            double p, q, u, w, z;
+            int i;
+
+            *sign = 1;
+
+            if (!std::isfinite(x)) {
+                return x;
+            }
+
+            if (x < -34.0) {
+                q = -x;
+                w = lgam_sgn(q, sign);
+                p = std::floor(q);
+                if (p == q) {
+                lgsing:
+                    set_error("lgam", SF_ERROR_SINGULAR, NULL);
+                    return (std::numeric_limits::infinity());
+                }
+                i = p;
+                if ((i & 1) == 0) {
+                    *sign = -1;
+                } else {
+                    *sign = 1;
+                }
+                z = q - p;
+                if (z > 0.5) {
+                    p += 1.0;
+                    z = p - q;
+                }
+                z = q * sinpi(z);
+                if (z == 0.0) {
+                    goto lgsing;
+                }
+                /*     z = log(M_PI) - log( z ) - w; */
+                z = LOGPI - std::log(z) - w;
+                return (z);
+            }
+
+            if (x < 13.0) {
+                z = 1.0;
+                p = 0.0;
+                u = x;
+                while (u >= 3.0) {
+                    p -= 1.0;
+                    u = x + p;
+                    z *= u;
+                }
+                while (u < 2.0) {
+                    if (u == 0.0) {
+                        goto lgsing;
+                    }
+                    z /= u;
+                    p += 1.0;
+                    u = x + p;
+                }
+                if (z < 0.0) {
+                    *sign = -1;
+                    z = -z;
+                } else {
+                    *sign = 1;
+                }
+                if (u == 2.0) {
+                    return (std::log(z));
+                }
+                p -= 2.0;
+                x = x + p;
+                p = x * polevl(x, gamma_B, 5) / p1evl(x, gamma_C, 6);
+                return (std::log(z) + p);
+            }
+
+            if (x > MAXLGM) {
+                return (*sign * std::numeric_limits::infinity());
+            }
+
+            if (x >= 1000.0) {
+                return lgam_large_x(x);
+            }
+
+            q = (x - 0.5) * std::log(x) - x + LS2PI;
+            p = 1.0 / (x * x);
+            return q + polevl(p, gamma_A, 4) / x;
+        }
+    } // namespace detail
+
+    /* Logarithm of Gamma function */
+    XSF_HOST_DEVICE inline double lgam(double x) {
+        int sign;
+        return detail::lgam_sgn(x, &sign);
+    }
+
+    /* Sign of the Gamma function */
+    XSF_HOST_DEVICE inline double gammasgn(double x) {
+        double fx;
+
+        if (std::isnan(x)) {
+            return x;
+        }
+        if (x > 0) {
+            return 1.0;
+	}
+	if (x == 0) {
+	    return std::copysign(1.0, x);
+	}
+	if (std::isinf(x)) {
+	    // x > 0 case handled, so x must be negative infinity.
+	    return std::numeric_limits::quiet_NaN();
+	}
+	fx = std::floor(x);
+	if (x - fx == 0.0) {
+	    return std::numeric_limits::quiet_NaN();
+	}
+	// sign of gamma for x in (-n, -n+1) for positive integer n is (-1)^n.
+	if (static_cast(fx) % 2) {
+	    return -1.0;
+	}
+	return 1.0;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h
new file mode 100644
index 0000000000000000000000000000000000000000..f9ec54bb20326552f5748ad9360dfecfbe18d660
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyp2f1.h
@@ -0,0 +1,596 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                      hyp2f1.c
+ *
+ *      Gauss hypergeometric function   F
+ *                                     2 1
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, b, c, x, y, hyp2f1();
+ *
+ * y = hyp2f1( a, b, c, x );
+ *
+ *
+ * DESCRIPTION:
+ *
+ *
+ *  hyp2f1( a, b, c, x )  =   F ( a, b; c; x )
+ *                           2 1
+ *
+ *           inf.
+ *            -   a(a+1)...(a+k) b(b+1)...(b+k)   k+1
+ *   =  1 +   >   -----------------------------  x   .
+ *            -         c(c+1)...(c+k) (k+1)!
+ *          k = 0
+ *
+ *  Cases addressed are
+ *      Tests and escapes for negative integer a, b, or c
+ *      Linear transformation if c - a or c - b negative integer
+ *      Special case c = a or c = b
+ *      Linear transformation for  x near +1
+ *      Transformation for x < -0.5
+ *      Psi function expansion if x > 0.5 and c - a - b integer
+ *      Conditionally, a recurrence on c to make c-a-b > 0
+ *
+ *      x < -1  AMS 15.3.7 transformation applied (Travis Oliphant)
+ *         valid for b,a,c,(b-a) != integer and (c-a),(c-b) != negative integer
+ *
+ * x >= 1 is rejected (unless special cases are present)
+ *
+ * The parameters a, b, c are considered to be integer
+ * valued if they are within 1.0e-14 of the nearest integer
+ * (1.0e-13 for IEEE arithmetic).
+ *
+ * ACCURACY:
+ *
+ *
+ *               Relative error (-1 < x < 1):
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      -1,7        230000      1.2e-11     5.2e-14
+ *
+ * Several special cases also tested with a, b, c in
+ * the range -7 to 7.
+ *
+ * ERROR MESSAGES:
+ *
+ * A "partial loss of precision" message is printed if
+ * the internally estimated relative error exceeds 1^-12.
+ * A "singularity" message is printed on overflow or
+ * in cases not addressed (such as x < -1).
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "rgamma.h"
+#include "psi.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        constexpr double hyp2f1_EPS = 1.0e-13;
+
+        constexpr double hyp2f1_ETHRESH = 1.0e-12;
+        constexpr std::uint64_t hyp2f1_MAXITER = 10000;
+
+        /* hys2f1 and hyp2f1ra depend on each other, so we need this prototype */
+        XSF_HOST_DEVICE double hyp2f1ra(double a, double b, double c, double x, double *loss);
+
+        /* Defining power series expansion of Gauss hypergeometric function */
+        /* The `loss` parameter estimates loss of significance */
+        XSF_HOST_DEVICE double hys2f1(double a, double b, double c, double x, double *loss) {
+            double f, g, h, k, m, s, u, umax;
+            std::uint64_t i;
+            int ib, intflag = 0;
+
+            if (std::abs(b) > std::abs(a)) {
+                /* Ensure that |a| > |b| ... */
+                f = b;
+                b = a;
+                a = f;
+            }
+
+            ib = std::round(b);
+
+            if (std::abs(b - ib) < hyp2f1_EPS && ib <= 0 && std::abs(b) < std::abs(a)) {
+                /* .. except when `b` is a smaller negative integer */
+                f = b;
+                b = a;
+                a = f;
+                intflag = 1;
+            }
+
+            if ((std::abs(a) > std::abs(c) + 1 || intflag) && std::abs(c - a) > 2 && std::abs(a) > 2) {
+                /* |a| >> |c| implies that large cancellation error is to be expected.
+                 *
+                 * We try to reduce it with the recurrence relations
+                 */
+                return hyp2f1ra(a, b, c, x, loss);
+            }
+
+            i = 0;
+            umax = 0.0;
+            f = a;
+            g = b;
+            h = c;
+            s = 1.0;
+            u = 1.0;
+            k = 0.0;
+            do {
+                if (std::abs(h) < hyp2f1_EPS) {
+                    *loss = 1.0;
+                    return std::numeric_limits::infinity();
+                }
+                m = k + 1.0;
+                u = u * ((f + k) * (g + k) * x / ((h + k) * m));
+                s += u;
+                k = std::abs(u); /* remember largest term summed */
+                if (k > umax)
+                    umax = k;
+                k = m;
+                if (++i > hyp2f1_MAXITER) { /* should never happen */
+                    *loss = 1.0;
+                    return (s);
+                }
+            } while (s == 0 || std::abs(u / s) > MACHEP);
+
+            /* return estimated relative error */
+            *loss = (MACHEP * umax) / fabs(s) + (MACHEP * i);
+
+            return (s);
+        }
+
+        /* Apply transformations for |x| near 1 then call the power series */
+        XSF_HOST_DEVICE double hyt2f1(double a, double b, double c, double x, double *loss) {
+            double p, q, r, s, t, y, w, d, err, err1;
+            double ax, id, d1, d2, e, y1;
+            int i, aid, sign;
+
+            int ia, ib, neg_int_a = 0, neg_int_b = 0;
+
+            ia = std::round(a);
+            ib = std::round(b);
+
+            if (a <= 0 && std::abs(a - ia) < hyp2f1_EPS) { /* a is a negative integer */
+                neg_int_a = 1;
+            }
+
+            if (b <= 0 && std::abs(b - ib) < hyp2f1_EPS) { /* b is a negative integer */
+                neg_int_b = 1;
+            }
+
+            err = 0.0;
+            s = 1.0 - x;
+            if (x < -0.5 && !(neg_int_a || neg_int_b)) {
+                if (b > a)
+                    y = std::pow(s, -a) * hys2f1(a, c - b, c, -x / s, &err);
+
+                else
+                    y = std::pow(s, -b) * hys2f1(c - a, b, c, -x / s, &err);
+
+                goto done;
+            }
+
+            d = c - a - b;
+            id = std::round(d); /* nearest integer to d */
+
+            if (x > 0.9 && !(neg_int_a || neg_int_b)) {
+                if (std::abs(d - id) > MACHEP) {
+                    int sgngam;
+
+                    /* test for integer c-a-b */
+                    /* Try the power series first */
+                    y = hys2f1(a, b, c, x, &err);
+                    if (err < hyp2f1_ETHRESH) {
+                        goto done;
+                    }
+                    /* If power series fails, then apply AMS55 #15.3.6 */
+                    q = hys2f1(a, b, 1.0 - d, s, &err);
+                    sign = 1;
+                    w = lgam_sgn(d, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(c - a, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(c - b, &sgngam);
+                    sign *= sgngam;
+                    q *= sign * std::exp(w);
+                    r = std::pow(s, d) * hys2f1(c - a, c - b, d + 1.0, s, &err1);
+                    sign = 1;
+                    w = lgam_sgn(-d, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(a, &sgngam);
+                    sign *= sgngam;
+                    w -= lgam_sgn(b, &sgngam);
+                    sign *= sgngam;
+                    r *= sign * std::exp(w);
+                    y = q + r;
+
+                    q = std::abs(q); /* estimate cancellation error */
+                    r = std::abs(r);
+                    if (q > r) {
+                        r = q;
+                    }
+                    err += err1 + (MACHEP * r) / y;
+
+                    y *= xsf::cephes::Gamma(c);
+                    goto done;
+                } else {
+                    /* Psi function expansion, AMS55 #15.3.10, #15.3.11, #15.3.12
+                     *
+                     * Although AMS55 does not explicitly state it, this expansion fails
+                     * for negative integer a or b, since the psi and Gamma functions
+                     * involved have poles.
+                     */
+
+                    if (id >= 0.0) {
+                        e = d;
+                        d1 = d;
+                        d2 = 0.0;
+                        aid = id;
+                    } else {
+                        e = -d;
+                        d1 = 0.0;
+                        d2 = d;
+                        aid = -id;
+                    }
+
+                    ax = std::log(s);
+
+                    /* sum for t = 0 */
+                    y = xsf::cephes::psi(1.0) + xsf::cephes::psi(1.0 + e) - xsf::cephes::psi(a + d1) -
+                        xsf::cephes::psi(b + d1) - ax;
+                    y *= xsf::cephes::rgamma(e + 1.0);
+
+                    p = (a + d1) * (b + d1) * s * xsf::cephes::rgamma(e + 2.0); /* Poch for t=1 */
+                    t = 1.0;
+                    do {
+                        r = xsf::cephes::psi(1.0 + t) + xsf::cephes::psi(1.0 + t + e) -
+                            xsf::cephes::psi(a + t + d1) - xsf::cephes::psi(b + t + d1) - ax;
+                        q = p * r;
+                        y += q;
+                        p *= s * (a + t + d1) / (t + 1.0);
+                        p *= (b + t + d1) / (t + 1.0 + e);
+                        t += 1.0;
+                        if (t > hyp2f1_MAXITER) { /* should never happen */
+                            set_error("hyp2f1", SF_ERROR_SLOW, NULL);
+                            *loss = 1.0;
+                            return std::numeric_limits::quiet_NaN();
+                        }
+                    } while (y == 0 || std::abs(q / y) > hyp2f1_EPS);
+
+                    if (id == 0.0) {
+                        y *= xsf::cephes::Gamma(c) / (xsf::cephes::Gamma(a) * xsf::cephes::Gamma(b));
+                        goto psidon;
+                    }
+
+                    y1 = 1.0;
+
+                    if (aid == 1)
+                        goto nosum;
+
+                    t = 0.0;
+                    p = 1.0;
+                    for (i = 1; i < aid; i++) {
+                        r = 1.0 - e + t;
+                        p *= s * (a + t + d2) * (b + t + d2) / r;
+                        t += 1.0;
+                        p /= t;
+                        y1 += p;
+                    }
+                nosum:
+                    p = xsf::cephes::Gamma(c);
+                    y1 *= xsf::cephes::Gamma(e) * p *
+                          (xsf::cephes::rgamma(a + d1) * xsf::cephes::rgamma(b + d1));
+
+                    y *= p * (xsf::cephes::rgamma(a + d2) * xsf::cephes::rgamma(b + d2));
+                    if ((aid & 1) != 0)
+                        y = -y;
+
+                    q = std::pow(s, id); /* s to the id power */
+                    if (id > 0.0)
+                        y *= q;
+                    else
+                        y1 *= q;
+
+                    y += y1;
+                psidon:
+                    goto done;
+                }
+            }
+
+            /* Use defining power series if no special cases */
+            y = hys2f1(a, b, c, x, &err);
+
+        done:
+            *loss = err;
+            return (y);
+        }
+
+        /*
+          15.4.2 Abramowitz & Stegun.
+        */
+        XSF_HOST_DEVICE double hyp2f1_neg_c_equal_bc(double a, double b, double x) {
+            double k;
+            double collector = 1;
+            double sum = 1;
+            double collector_max = 1;
+
+            if (!(std::abs(b) < 1e5)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            for (k = 1; k <= -b; k++) {
+                collector *= (a + k - 1) * x / k;
+                collector_max = std::fmax(std::abs(collector), collector_max);
+                sum += collector;
+            }
+
+            if (1e-16 * (1 + collector_max / std::abs(sum)) > 1e-7) {
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            return sum;
+        }
+
+        /*
+         * Evaluate hypergeometric function by two-term recurrence in `a`.
+         *
+         * This avoids some of the loss of precision in the strongly alternating
+         * hypergeometric series, and can be used to reduce the `a` and `b` parameters
+         * to smaller values.
+         *
+         * AMS55 #15.2.10
+         */
+        XSF_HOST_DEVICE double hyp2f1ra(double a, double b, double c, double x, double *loss) {
+            double f2, f1, f0;
+            int n;
+            double t, err, da;
+
+            /* Don't cross c or zero */
+            if ((c < 0 && a <= c) || (c >= 0 && a >= c)) {
+                da = std::round(a - c);
+            } else {
+                da = std::round(a);
+            }
+            t = a - da;
+
+            *loss = 0;
+
+            XSF_ASSERT(da != 0);
+
+            if (std::abs(da) > hyp2f1_MAXITER) {
+                /* Too expensive to compute this value, so give up */
+                set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL);
+                *loss = 1.0;
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            if (da < 0) {
+                /* Recurse down */
+                f2 = 0;
+                f1 = hys2f1(t, b, c, x, &err);
+                *loss += err;
+                f0 = hys2f1(t - 1, b, c, x, &err);
+                *loss += err;
+                t -= 1;
+                for (n = 1; n < -da; ++n) {
+                    f2 = f1;
+                    f1 = f0;
+                    f0 = -(2 * t - c - t * x + b * x) / (c - t) * f1 - t * (x - 1) / (c - t) * f2;
+                    t -= 1;
+                }
+            } else {
+                /* Recurse up */
+                f2 = 0;
+                f1 = hys2f1(t, b, c, x, &err);
+                *loss += err;
+                f0 = hys2f1(t + 1, b, c, x, &err);
+                *loss += err;
+                t += 1;
+                for (n = 1; n < da; ++n) {
+                    f2 = f1;
+                    f1 = f0;
+                    f0 = -((2 * t - c - t * x + b * x) * f1 + (c - t) * f2) / (t * (x - 1));
+                    t += 1;
+                }
+            }
+
+            return f0;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE double hyp2f1(double a, double b, double c, double x) {
+        double d, d1, d2, e;
+        double p, q, r, s, y, ax;
+        double ia, ib, ic, id, err;
+        double t1;
+        int i, aid;
+        int neg_int_a = 0, neg_int_b = 0;
+        int neg_int_ca_or_cb = 0;
+
+        err = 0.0;
+        ax = std::abs(x);
+        s = 1.0 - x;
+        ia = std::round(a); /* nearest integer to a */
+        ib = std::round(b);
+
+        if (x == 0.0) {
+            return 1.0;
+        }
+
+        d = c - a - b;
+        id = std::round(d);
+
+        if ((a == 0 || b == 0) && c != 0) {
+            return 1.0;
+        }
+
+        if (a <= 0 && std::abs(a - ia) < detail::hyp2f1_EPS) { /* a is a negative integer */
+            neg_int_a = 1;
+        }
+
+        if (b <= 0 && std::abs(b - ib) < detail::hyp2f1_EPS) { /* b is a negative integer */
+            neg_int_b = 1;
+        }
+
+        if (d <= -1 && !(std::abs(d - id) > detail::hyp2f1_EPS && s < 0) && !(neg_int_a || neg_int_b)) {
+            return std::pow(s, d) * hyp2f1(c - a, c - b, c, x);
+        }
+        if (d <= 0 && x == 1 && !(neg_int_a || neg_int_b))
+            goto hypdiv;
+
+        if (ax < 1.0 || x == -1.0) {
+            /* 2F1(a,b;b;x) = (1-x)**(-a) */
+            if (std::abs(b - c) < detail::hyp2f1_EPS) { /* b = c */
+                if (neg_int_b) {
+                    y = detail::hyp2f1_neg_c_equal_bc(a, b, x);
+                } else {
+                    y = std::pow(s, -a); /* s to the -a power */
+                }
+                goto hypdon;
+            }
+            if (std::abs(a - c) < detail::hyp2f1_EPS) { /* a = c */
+                y = std::pow(s, -b);                    /* s to the -b power */
+                goto hypdon;
+            }
+        }
+
+        if (c <= 0.0) {
+            ic = std::round(c);                          /* nearest integer to c */
+            if (std::abs(c - ic) < detail::hyp2f1_EPS) { /* c is a negative integer */
+                /* check if termination before explosion */
+                if (neg_int_a && (ia > ic))
+                    goto hypok;
+                if (neg_int_b && (ib > ic))
+                    goto hypok;
+                goto hypdiv;
+            }
+        }
+
+        if (neg_int_a || neg_int_b) /* function is a polynomial */
+            goto hypok;
+
+        t1 = std::abs(b - a);
+        if (x < -2.0 && std::abs(t1 - round(t1)) > detail::hyp2f1_EPS) {
+            /* This transform has a pole for b-a integer, and
+             * may produce large cancellation errors for |1/x| close 1
+             */
+            p = hyp2f1(a, 1 - c + a, 1 - b + a, 1.0 / x);
+            q = hyp2f1(b, 1 - c + b, 1 - a + b, 1.0 / x);
+            p *= std::pow(-x, -a);
+            q *= std::pow(-x, -b);
+            t1 = Gamma(c);
+            s = t1 * Gamma(b - a) * (rgamma(b) * rgamma(c - a));
+            y = t1 * Gamma(a - b) * (rgamma(a) * rgamma(c - b));
+            return s * p + y * q;
+        } else if (x < -1.0) {
+            if (std::abs(a) < std::abs(b)) {
+                return std::pow(s, -a) * hyp2f1(a, c - b, c, x / (x - 1));
+            } else {
+                return std::pow(s, -b) * hyp2f1(b, c - a, c, x / (x - 1));
+            }
+        }
+
+        if (ax > 1.0) /* series diverges  */
+            goto hypdiv;
+
+        p = c - a;
+        ia = std::round(p);                                         /* nearest integer to c-a */
+        if ((ia <= 0.0) && (std::abs(p - ia) < detail::hyp2f1_EPS)) /* negative int c - a */
+            neg_int_ca_or_cb = 1;
+
+        r = c - b;
+        ib = std::round(r);                                         /* nearest integer to c-b */
+        if ((ib <= 0.0) && (std::abs(r - ib) < detail::hyp2f1_EPS)) /* negative int c - b */
+            neg_int_ca_or_cb = 1;
+
+        id = std::round(d); /* nearest integer to d */
+        q = std::abs(d - id);
+
+        /* Thanks to Christian Burger 
+         * for reporting a bug here.  */
+        if (std::abs(ax - 1.0) < detail::hyp2f1_EPS) { /* |x| == 1.0   */
+            if (x > 0.0) {
+                if (neg_int_ca_or_cb) {
+                    if (d >= 0.0)
+                        goto hypf;
+                    else
+                        goto hypdiv;
+                }
+                if (d <= 0.0)
+                    goto hypdiv;
+                y = Gamma(c) * Gamma(d) * (rgamma(p) * rgamma(r));
+                goto hypdon;
+            }
+            if (d <= -1.0)
+                goto hypdiv;
+        }
+
+        /* Conditionally make d > 0 by recurrence on c
+         * AMS55 #15.2.27
+         */
+        if (d < 0.0) {
+            /* Try the power series first */
+            y = detail::hyt2f1(a, b, c, x, &err);
+            if (err < detail::hyp2f1_ETHRESH)
+                goto hypdon;
+            /* Apply the recurrence if power series fails */
+            err = 0.0;
+            aid = 2 - id;
+            e = c + aid;
+            d2 = hyp2f1(a, b, e, x);
+            d1 = hyp2f1(a, b, e + 1.0, x);
+            q = a + b + 1.0;
+            for (i = 0; i < aid; i++) {
+                r = e - 1.0;
+                y = (e * (r - (2.0 * e - q) * x) * d2 + (e - a) * (e - b) * x * d1) / (e * r * s);
+                e = r;
+                d1 = d2;
+                d2 = y;
+            }
+            goto hypdon;
+        }
+
+        if (neg_int_ca_or_cb) {
+            goto hypf; /* negative integer c-a or c-b */
+        }
+
+    hypok:
+        y = detail::hyt2f1(a, b, c, x, &err);
+
+    hypdon:
+        if (err > detail::hyp2f1_ETHRESH) {
+            set_error("hyp2f1", SF_ERROR_LOSS, NULL);
+            /*      printf( "Estimated err = %.2e\n", err ); */
+        }
+        return (y);
+
+        /* The transformation for c-a or c-b negative integer
+         * AMS55 #15.3.3
+         */
+    hypf:
+        y = std::pow(s, d) * detail::hys2f1(c - a, c - b, c, x, &err);
+        goto hypdon;
+
+        /* The alarm exit */
+    hypdiv:
+        set_error("hyp2f1", SF_ERROR_OVERFLOW, NULL);
+        return std::numeric_limits::infinity();
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h
new file mode 100644
index 0000000000000000000000000000000000000000..18ebcff69ba4f9d9a7d5660aa8c63f858c56c7b3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/hyperg.h
@@ -0,0 +1,361 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     hyperg.c
+ *
+ *     Confluent hypergeometric function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, b, x, y, hyperg();
+ *
+ * y = hyperg( a, b, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Computes the confluent hypergeometric function
+ *
+ *                          1           2
+ *                       a x    a(a+1) x
+ *   F ( a,b;x )  =  1 + ---- + --------- + ...
+ *  1 1                  b 1!   b(b+1) 2!
+ *
+ * Many higher transcendental functions are special cases of
+ * this power series.
+ *
+ * As is evident from the formula, b must not be a negative
+ * integer or zero unless a is an integer with 0 >= a > b.
+ *
+ * The routine attempts both a direct summation of the series
+ * and an asymptotic expansion.  In each case error due to
+ * roundoff, cancellation, and nonconvergence is estimated.
+ * The result with smaller estimated error is returned.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at random points (a, b, x), all three variables
+ * ranging from 0 to 30.
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       1.8e-14     1.1e-15
+ *
+ * Larger errors can be observed when b is near a negative
+ * integer or zero.  Certain combinations of arguments yield
+ * serious cancellation error in the power series summation
+ * and also are not in the region of near convergence of the
+ * asymptotic series.  An error message is printed if the
+ * self-estimated relative error is greater than 1.0e-12.
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "rgamma.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* the `type` parameter determines what converging factor to use */
+        XSF_HOST_DEVICE inline double hyp2f0(double a, double b, double x, int type, double *err) {
+            double a0, alast, t, tlast, maxt;
+            double n, an, bn, u, sum, temp;
+
+            an = a;
+            bn = b;
+            a0 = 1.0e0;
+            alast = 1.0e0;
+            sum = 0.0;
+            n = 1.0e0;
+            t = 1.0e0;
+            tlast = 1.0e9;
+            maxt = 0.0;
+
+            do {
+                if (an == 0)
+                    goto pdone;
+                if (bn == 0)
+                    goto pdone;
+
+                u = an * (bn * x / n);
+
+                /* check for blowup */
+                temp = std::abs(u);
+                if ((temp > 1.0) && (maxt > (std::numeric_limits::max() / temp)))
+                    goto error;
+
+                a0 *= u;
+                t = std::abs(a0);
+
+                /* terminating condition for asymptotic series:
+                 * the series is divergent (if a or b is not a negative integer),
+                 * but its leading part can be used as an asymptotic expansion
+                 */
+                if (t > tlast)
+                    goto ndone;
+
+                tlast = t;
+                sum += alast; /* the sum is one term behind */
+                alast = a0;
+
+                if (n > 200)
+                    goto ndone;
+
+                an += 1.0e0;
+                bn += 1.0e0;
+                n += 1.0e0;
+                if (t > maxt)
+                    maxt = t;
+            } while (t > MACHEP);
+
+        pdone: /* series converged! */
+
+            /* estimate error due to roundoff and cancellation */
+            *err = std::abs(MACHEP * (n + maxt));
+
+            alast = a0;
+            goto done;
+
+        ndone: /* series did not converge */
+
+            /* The following "Converging factors" are supposed to improve accuracy,
+             * but do not actually seem to accomplish very much. */
+
+            n -= 1.0;
+            x = 1.0 / x;
+
+            switch (type) { /* "type" given as subroutine argument */
+            case 1:
+                alast *= (0.5 + (0.125 + 0.25 * b - 0.5 * a + 0.25 * x - 0.25 * n) / x);
+                break;
+
+            case 2:
+                alast *= 2.0 / 3.0 - b + 2.0 * a + x - n;
+                break;
+
+            default:;
+            }
+
+            /* estimate error due to roundoff, cancellation, and nonconvergence */
+            *err = MACHEP * (n + maxt) + std::abs(a0);
+
+        done:
+            sum += alast;
+            return (sum);
+
+            /* series blew up: */
+        error:
+            *err = std::numeric_limits::infinity();
+            set_error("hyperg", SF_ERROR_NO_RESULT, NULL);
+            return (sum);
+        }
+
+        /* asymptotic formula for hypergeometric function:
+         *
+         *        (    -a
+         *  --    ( |z|
+         * |  (b) ( -------- 2f0( a, 1+a-b, -1/x )
+         *        (  --
+         *        ( |  (b-a)
+         *
+         *
+         *                                x    a-b                     )
+         *                               e  |x|                        )
+         *                             + -------- 2f0( b-a, 1-a, 1/x ) )
+         *                                --                           )
+         *                               |  (a)                        )
+         */
+
+        XSF_HOST_DEVICE inline double hy1f1a(double a, double b, double x, double *err) {
+            double h1, h2, t, u, temp, acanc, asum, err1, err2;
+
+            if (x == 0) {
+                acanc = 1.0;
+                asum = std::numeric_limits::infinity();
+                goto adone;
+            }
+            temp = std::log(std::abs(x));
+            t = x + temp * (a - b);
+            u = -temp * a;
+
+            if (b > 0) {
+                temp = xsf::cephes::lgam(b);
+                t += temp;
+                u += temp;
+            }
+
+            h1 = hyp2f0(a, a - b + 1, -1.0 / x, 1, &err1);
+
+            temp = std::exp(u) * xsf::cephes::rgamma(b - a);
+            h1 *= temp;
+            err1 *= temp;
+
+            h2 = hyp2f0(b - a, 1.0 - a, 1.0 / x, 2, &err2);
+
+            if (a < 0)
+                temp = std::exp(t) * xsf::cephes::rgamma(a);
+            else
+                temp = std::exp(t - xsf::cephes::lgam(a));
+
+            h2 *= temp;
+            err2 *= temp;
+
+            if (x < 0.0)
+                asum = h1;
+            else
+                asum = h2;
+
+            acanc = std::abs(err1) + std::abs(err2);
+
+            if (b < 0) {
+                temp = xsf::cephes::Gamma(b);
+                asum *= temp;
+                acanc *= std::abs(temp);
+            }
+
+            if (asum != 0.0)
+                acanc /= std::abs(asum);
+
+            if (acanc != acanc)
+                /* nan */
+                acanc = 1.0;
+
+            if (std::isinf(asum))
+                /* infinity */
+                acanc = 0;
+
+            acanc *= 30.0; /* fudge factor, since error of asymptotic formula
+                            * often seems this much larger than advertised */
+        adone:
+            *err = acanc;
+            return (asum);
+        }
+
+        /* Power series summation for confluent hypergeometric function */
+        XSF_HOST_DEVICE inline double hy1f1p(double a, double b, double x, double *err) {
+            double n, a0, sum, t, u, temp, maxn;
+            double an, bn, maxt;
+            double y, c, sumc;
+
+            /* set up for power series summation */
+            an = a;
+            bn = b;
+            a0 = 1.0;
+            sum = 1.0;
+            c = 0.0;
+            n = 1.0;
+            t = 1.0;
+            maxt = 0.0;
+            *err = 1.0;
+
+            maxn = 200.0 + 2 * fabs(a) + 2 * fabs(b);
+
+            while (t > MACHEP) {
+                if (bn == 0) { /* check bn first since if both   */
+                    sf_error("hyperg", SF_ERROR_SINGULAR, NULL);
+                    return (std::numeric_limits::infinity()); /* an and bn are zero it is     */
+                }
+                if (an == 0) /* a singularity            */
+                    return (sum);
+                if (n > maxn) {
+                    /* too many terms; take the last one as error estimate */
+                    c = std::abs(c) + std::abs(t) * 50.0;
+                    goto pdone;
+                }
+                u = x * (an / (bn * n));
+
+                /* check for blowup */
+                temp = std::abs(u);
+                if ((temp > 1.0) && (maxt > (std::numeric_limits::max() / temp))) {
+                    *err = 1.0; /* blowup: estimate 100% error */
+                    return sum;
+                }
+
+                a0 *= u;
+
+                y = a0 - c;
+                sumc = sum + y;
+                c = (sumc - sum) - y;
+                sum = sumc;
+
+                t = std::abs(a0);
+
+                an += 1.0;
+                bn += 1.0;
+                n += 1.0;
+            }
+
+        pdone:
+
+            /* estimate error due to roundoff and cancellation */
+            if (sum != 0.0) {
+                *err = std::abs(c / sum);
+            } else {
+                *err = std::abs(c);
+            }
+
+            if (*err != *err) {
+                /* nan */
+                *err = 1.0;
+            }
+
+            return (sum);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double hyperg(double a, double b, double x) {
+        double asum, psum, acanc, pcanc, temp;
+
+        /* See if a Kummer transformation will help */
+        temp = b - a;
+        if (std::abs(temp) < 0.001 * std::abs(a))
+            return (exp(x) * hyperg(temp, b, -x));
+
+        /* Try power & asymptotic series, starting from the one that is likely OK */
+        if (std::abs(x) < 10 + std::abs(a) + std::abs(b)) {
+            psum = detail::hy1f1p(a, b, x, &pcanc);
+            if (pcanc < 1.0e-15)
+                goto done;
+            asum = detail::hy1f1a(a, b, x, &acanc);
+        } else {
+            psum = detail::hy1f1a(a, b, x, &pcanc);
+            if (pcanc < 1.0e-15)
+                goto done;
+            asum = detail::hy1f1p(a, b, x, &acanc);
+        }
+
+        /* Pick the result with less estimated error */
+
+        if (acanc < pcanc) {
+            pcanc = acanc;
+            psum = asum;
+        }
+
+    done:
+        if (pcanc > 1.0e-12)
+            set_error("hyperg", SF_ERROR_LOSS, NULL);
+
+        return (psum);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h
new file mode 100644
index 0000000000000000000000000000000000000000..f61e7b12fd22d92e741f53e2acee8a7f65278658
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i0.h
@@ -0,0 +1,149 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     i0.c
+ *
+ *     Modified Bessel function of order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i0();
+ *
+ * y = i0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of order zero of the
+ * argument.
+ *
+ * The function is defined as i0(x) = j0( ix ).
+ *
+ * The range is partitioned into the two intervals [0,8] and
+ * (8, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       5.8e-16     1.4e-16
+ *
+ */
+/*							i0e.c
+ *
+ *	Modified Bessel function of order zero,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i0e();
+ *
+ * y = i0e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of order zero of the argument.
+ *
+ * The function is defined as i0e(x) = exp(-|x|) j0( ix ).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       5.4e-16     1.2e-16
+ * See i0().
+ *
+ */
+
+/*                                                     i0.c            */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "chbevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* Chebyshev coefficients for exp(-x) I0(x)
+         * in the interval [0,8].
+         *
+         * lim(x->0){ exp(-x) I0(x) } = 1.
+         */
+        constexpr double i0_A[] = {
+            -4.41534164647933937950E-18, 3.33079451882223809783E-17,  -2.43127984654795469359E-16,
+            1.71539128555513303061E-15,  -1.16853328779934516808E-14, 7.67618549860493561688E-14,
+            -4.85644678311192946090E-13, 2.95505266312963983461E-12,  -1.72682629144155570723E-11,
+            9.67580903537323691224E-11,  -5.18979560163526290666E-10, 2.65982372468238665035E-9,
+            -1.30002500998624804212E-8,  6.04699502254191894932E-8,   -2.67079385394061173391E-7,
+            1.11738753912010371815E-6,   -4.41673835845875056359E-6,  1.64484480707288970893E-5,
+            -5.75419501008210370398E-5,  1.88502885095841655729E-4,   -5.76375574538582365885E-4,
+            1.63947561694133579842E-3,   -4.32430999505057594430E-3,  1.05464603945949983183E-2,
+            -2.37374148058994688156E-2,  4.93052842396707084878E-2,   -9.49010970480476444210E-2,
+            1.71620901522208775349E-1,   -3.04682672343198398683E-1,  6.76795274409476084995E-1};
+
+        /* Chebyshev coefficients for exp(-x) sqrt(x) I0(x)
+         * in the inverted interval [8,infinity].
+         *
+         * lim(x->inf){ exp(-x) sqrt(x) I0(x) } = 1/sqrt(2pi).
+         */
+        constexpr double i0_B[] = {
+            -7.23318048787475395456E-18, -4.83050448594418207126E-18, 4.46562142029675999901E-17,
+            3.46122286769746109310E-17,  -2.82762398051658348494E-16, -3.42548561967721913462E-16,
+            1.77256013305652638360E-15,  3.81168066935262242075E-15,  -9.55484669882830764870E-15,
+            -4.15056934728722208663E-14, 1.54008621752140982691E-14,  3.85277838274214270114E-13,
+            7.18012445138366623367E-13,  -1.79417853150680611778E-12, -1.32158118404477131188E-11,
+            -3.14991652796324136454E-11, 1.18891471078464383424E-11,  4.94060238822496958910E-10,
+            3.39623202570838634515E-9,   2.26666899049817806459E-8,   2.04891858946906374183E-7,
+            2.89137052083475648297E-6,   6.88975834691682398426E-5,   3.36911647825569408990E-3,
+            8.04490411014108831608E-1};
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double i0(double x) {
+        double y;
+
+        if (x < 0)
+            x = -x;
+        if (x <= 8.0) {
+            y = (x / 2.0) - 2.0;
+            return (std::exp(x) * chbevl(y, detail::i0_A, 30));
+        }
+
+        return (std::exp(x) * chbevl(32.0 / x - 2.0, detail::i0_B, 25) / sqrt(x));
+    }
+
+    XSF_HOST_DEVICE inline double i0e(double x) {
+        double y;
+
+        if (x < 0)
+            x = -x;
+        if (x <= 8.0) {
+            y = (x / 2.0) - 2.0;
+            return (chbevl(y, detail::i0_A, 30));
+        }
+
+        return (chbevl(32.0 / x - 2.0, detail::i0_B, 25) / std::sqrt(x));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h
new file mode 100644
index 0000000000000000000000000000000000000000..49e2690391cf5af19ca36c72cbd38034920c1fd2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/i1.h
@@ -0,0 +1,158 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     i1.c
+ *
+ *     Modified Bessel function of order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i1();
+ *
+ * y = i1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of order one of the
+ * argument.
+ *
+ * The function is defined as i1(x) = -i j1( ix ).
+ *
+ * The range is partitioned into the two intervals [0,8] and
+ * (8, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.9e-15     2.1e-16
+ *
+ *
+ */
+/*							i1e.c
+ *
+ *	Modified Bessel function of order one,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, i1e();
+ *
+ * y = i1e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of order one of the argument.
+ *
+ * The function is defined as i1(x) = -i exp(-|x|) j1( ix ).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       2.0e-15     2.0e-16
+ * See i1().
+ *
+ */
+
+/*                                                     i1.c 2          */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1985, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "chbevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* Chebyshev coefficients for exp(-x) I1(x) / x
+         * in the interval [0,8].
+         *
+         * lim(x->0){ exp(-x) I1(x) / x } = 1/2.
+         */
+
+        constexpr double i1_A[] = {
+            2.77791411276104639959E-18,  -2.11142121435816608115E-17, 1.55363195773620046921E-16,
+            -1.10559694773538630805E-15, 7.60068429473540693410E-15,  -5.04218550472791168711E-14,
+            3.22379336594557470981E-13,  -1.98397439776494371520E-12, 1.17361862988909016308E-11,
+            -6.66348972350202774223E-11, 3.62559028155211703701E-10,  -1.88724975172282928790E-9,
+            9.38153738649577178388E-9,   -4.44505912879632808065E-8,  2.00329475355213526229E-7,
+            -8.56872026469545474066E-7,  3.47025130813767847674E-6,   -1.32731636560394358279E-5,
+            4.78156510755005422638E-5,   -1.61760815825896745588E-4,  5.12285956168575772895E-4,
+            -1.51357245063125314899E-3,  4.15642294431288815669E-3,   -1.05640848946261981558E-2,
+            2.47264490306265168283E-2,   -5.29459812080949914269E-2,  1.02643658689847095384E-1,
+            -1.76416518357834055153E-1,  2.52587186443633654823E-1};
+
+        /* Chebyshev coefficients for exp(-x) sqrt(x) I1(x)
+         * in the inverted interval [8,infinity].
+         *
+         * lim(x->inf){ exp(-x) sqrt(x) I1(x) } = 1/sqrt(2pi).
+         */
+        constexpr double i1_B[] = {
+            7.51729631084210481353E-18,  4.41434832307170791151E-18,  -4.65030536848935832153E-17,
+            -3.20952592199342395980E-17, 2.96262899764595013876E-16,  3.30820231092092828324E-16,
+            -1.88035477551078244854E-15, -3.81440307243700780478E-15, 1.04202769841288027642E-14,
+            4.27244001671195135429E-14,  -2.10154184277266431302E-14, -4.08355111109219731823E-13,
+            -7.19855177624590851209E-13, 2.03562854414708950722E-12,  1.41258074366137813316E-11,
+            3.25260358301548823856E-11,  -1.89749581235054123450E-11, -5.58974346219658380687E-10,
+            -3.83538038596423702205E-9,  -2.63146884688951950684E-8,  -2.51223623787020892529E-7,
+            -3.88256480887769039346E-6,  -1.10588938762623716291E-4,  -9.76109749136146840777E-3,
+            7.78576235018280120474E-1};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double i1(double x) {
+        double y, z;
+
+        z = std::abs(x);
+        if (z <= 8.0) {
+            y = (z / 2.0) - 2.0;
+            z = chbevl(y, detail::i1_A, 29) * z * std::exp(z);
+        } else {
+            z = std::exp(z) * chbevl(32.0 / z - 2.0, detail::i1_B, 25) / std::sqrt(z);
+        }
+        if (x < 0.0)
+            z = -z;
+        return (z);
+    }
+
+    /*                                                     i1e()   */
+
+    XSF_HOST_DEVICE inline double i1e(double x) {
+        double y, z;
+
+        z = std::abs(x);
+        if (z <= 8.0) {
+            y = (z / 2.0) - 2.0;
+            z = chbevl(y, detail::i1_A, 29) * z;
+        } else {
+            z = chbevl(32.0 / z - 2.0, detail::i1_B, 25) / std::sqrt(z);
+        }
+        if (x < 0.0)
+            z = -z;
+        return (z);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h
new file mode 100644
index 0000000000000000000000000000000000000000..dbe4f6519b13111d520306c5eec75bf811b02d0d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam.h
@@ -0,0 +1,421 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     igam.c
+ *
+ *     Incomplete Gamma integral
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, x, y, igam();
+ *
+ * y = igam( a, x );
+ *
+ * DESCRIPTION:
+ *
+ * The function is defined by
+ *
+ *                           x
+ *                            -
+ *                   1       | |  -t  a-1
+ *  igam(a,x)  =   -----     |   e   t   dt.
+ *                  -      | |
+ *                 | (a)    -
+ *                           0
+ *
+ *
+ * In this implementation both arguments must be positive.
+ * The integral is evaluated by either a power series or
+ * continued fraction expansion, depending on the relative
+ * values of a and x.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30       200000       3.6e-14     2.9e-15
+ *    IEEE      0,100      300000       9.9e-14     1.5e-14
+ */
+/*							igamc()
+ *
+ *	Complemented incomplete Gamma integral
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double a, x, y, igamc();
+ *
+ * y = igamc( a, x );
+ *
+ * DESCRIPTION:
+ *
+ * The function is defined by
+ *
+ *
+ *  igamc(a,x)   =   1 - igam(a,x)
+ *
+ *                            inf.
+ *                              -
+ *                     1       | |  -t  a-1
+ *               =   -----     |   e   t   dt.
+ *                    -      | |
+ *                   | (a)    -
+ *                             x
+ *
+ *
+ * In this implementation both arguments must be positive.
+ * The integral is evaluated by either a power series or
+ * continued fraction expansion, depending on the relative
+ * values of a and x.
+ *
+ * ACCURACY:
+ *
+ * Tested at random a, x.
+ *                a         x                      Relative error:
+ * arithmetic   domain   domain     # trials      peak         rms
+ *    IEEE     0.5,100   0,100      200000       1.9e-14     1.7e-15
+ *    IEEE     0.01,0.5  0,100      200000       1.4e-13     1.6e-15
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+
+/* Sources
+ * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ * [2] Maddock et. al., "Incomplete Gamma Functions",
+ *     https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/sf_gamma/igamma.html
+ */
+
+/* Scipy changes:
+ * - 05-01-2016: added asymptotic expansion for igam to improve the
+ *   a ~ x regime.
+ * - 06-19-2016: additional series expansion added for igamc to
+ *   improve accuracy at small arguments.
+ * - 06-24-2016: better choice of domain for the asymptotic series;
+ *   improvements in accuracy for the asymptotic series when a and x
+ *   are very close.
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "igam_asymp_coeff.h"
+#include "lanczos.h"
+#include "ndtr.h"
+#include "unity.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int igam_MAXITER = 2000;
+        constexpr int IGAM = 1;
+        constexpr int IGAMC = 0;
+        constexpr double igam_SMALL = 20;
+        constexpr double igam_LARGE = 200;
+        constexpr double igam_SMALLRATIO = 0.3;
+        constexpr double igam_LARGERATIO = 4.5;
+
+        constexpr double igam_big = 4.503599627370496e15;
+        constexpr double igam_biginv = 2.22044604925031308085e-16;
+
+        /* Compute
+         *
+         * x^a * exp(-x) / gamma(a)
+         *
+         * corrected from (15) and (16) in [2] by replacing exp(x - a) with
+         * exp(a - x).
+         */
+        XSF_HOST_DEVICE inline double igam_fac(double a, double x) {
+            double ax, fac, res, num;
+
+            if (std::abs(a - x) > 0.4 * std::abs(a)) {
+                ax = a * std::log(x) - x - xsf::cephes::lgam(a);
+                if (ax < -MAXLOG) {
+                    set_error("igam", SF_ERROR_UNDERFLOW, NULL);
+                    return 0.0;
+                }
+                return std::exp(ax);
+            }
+
+            fac = a + xsf::cephes::lanczos_g - 0.5;
+            res = std::sqrt(fac / std::exp(1)) / xsf::cephes::lanczos_sum_expg_scaled(a);
+
+            if ((a < 200) && (x < 200)) {
+                res *= std::exp(a - x) * std::pow(x / fac, a);
+            } else {
+                num = x - a - xsf::cephes::lanczos_g + 0.5;
+                res *= std::exp(a * xsf::cephes::log1pmx(num / fac) + x * (0.5 - xsf::cephes::lanczos_g) / fac);
+            }
+
+            return res;
+        }
+
+        /* Compute igamc using DLMF 8.9.2. */
+        XSF_HOST_DEVICE inline double igamc_continued_fraction(double a, double x) {
+            int i;
+            double ans, ax, c, yc, r, t, y, z;
+            double pk, pkm1, pkm2, qk, qkm1, qkm2;
+
+            ax = igam_fac(a, x);
+            if (ax == 0.0) {
+                return 0.0;
+            }
+
+            /* continued fraction */
+            y = 1.0 - a;
+            z = x + y + 1.0;
+            c = 0.0;
+            pkm2 = 1.0;
+            qkm2 = x;
+            pkm1 = x + 1.0;
+            qkm1 = z * x;
+            ans = pkm1 / qkm1;
+
+            for (i = 0; i < igam_MAXITER; i++) {
+                c += 1.0;
+                y += 1.0;
+                z += 2.0;
+                yc = y * c;
+                pk = pkm1 * z - pkm2 * yc;
+                qk = qkm1 * z - qkm2 * yc;
+                if (qk != 0) {
+                    r = pk / qk;
+                    t = std::abs((ans - r) / r);
+                    ans = r;
+                } else
+                    t = 1.0;
+                pkm2 = pkm1;
+                pkm1 = pk;
+                qkm2 = qkm1;
+                qkm1 = qk;
+                if (std::abs(pk) > igam_big) {
+                    pkm2 *= igam_biginv;
+                    pkm1 *= igam_biginv;
+                    qkm2 *= igam_biginv;
+                    qkm1 *= igam_biginv;
+                }
+                if (t <= MACHEP) {
+                    break;
+                }
+            }
+
+            return (ans * ax);
+        }
+
+        /* Compute igam using DLMF 8.11.4. */
+        XSF_HOST_DEVICE inline double igam_series(double a, double x) {
+            int i;
+            double ans, ax, c, r;
+
+            ax = igam_fac(a, x);
+            if (ax == 0.0) {
+                return 0.0;
+            }
+
+            /* power series */
+            r = a;
+            c = 1.0;
+            ans = 1.0;
+
+            for (i = 0; i < igam_MAXITER; i++) {
+                r += 1.0;
+                c *= x / r;
+                ans += c;
+                if (c <= MACHEP * ans) {
+                    break;
+                }
+            }
+
+            return (ans * ax / a);
+        }
+
+        /* Compute igamc using DLMF 8.7.3. This is related to the series in
+         * igam_series but extra care is taken to avoid cancellation.
+         */
+        XSF_HOST_DEVICE inline double igamc_series(double a, double x) {
+            int n;
+            double fac = 1;
+            double sum = 0;
+            double term, logx;
+
+            for (n = 1; n < igam_MAXITER; n++) {
+                fac *= -x / n;
+                term = fac / (a + n);
+                sum += term;
+                if (std::abs(term) <= MACHEP * std::abs(sum)) {
+                    break;
+                }
+            }
+
+            logx = std::log(x);
+            term = -xsf::cephes::expm1(a * logx - xsf::cephes::lgam1p(a));
+            return term - std::exp(a * logx - xsf::cephes::lgam(a)) * sum;
+        }
+
+        /* Compute igam/igamc using DLMF 8.12.3/8.12.4. */
+        XSF_HOST_DEVICE inline double asymptotic_series(double a, double x, int func) {
+            int k, n, sgn;
+            int maxpow = 0;
+            double lambda = x / a;
+            double sigma = (x - a) / a;
+            double eta, res, ck, ckterm, term, absterm;
+            double absoldterm = std::numeric_limits::infinity();
+            double etapow[detail::igam_asymp_coeff_N] = {1};
+            double sum = 0;
+            double afac = 1;
+
+            if (func == detail::IGAM) {
+                sgn = -1;
+            } else {
+                sgn = 1;
+            }
+
+            if (lambda > 1) {
+                eta = std::sqrt(-2 * xsf::cephes::log1pmx(sigma));
+            } else if (lambda < 1) {
+                eta = -std::sqrt(-2 * xsf::cephes::log1pmx(sigma));
+            } else {
+                eta = 0;
+            }
+            res = 0.5 * xsf::cephes::erfc(sgn * eta * std::sqrt(a / 2));
+
+            for (k = 0; k < igam_asymp_coeff_K; k++) {
+                ck = igam_asymp_coeff_d[k][0];
+                for (n = 1; n < igam_asymp_coeff_N; n++) {
+                    if (n > maxpow) {
+                        etapow[n] = eta * etapow[n - 1];
+                        maxpow += 1;
+                    }
+                    ckterm = igam_asymp_coeff_d[k][n] * etapow[n];
+                    ck += ckterm;
+                    if (std::abs(ckterm) < MACHEP * std::abs(ck)) {
+                        break;
+                    }
+                }
+                term = ck * afac;
+                absterm = std::abs(term);
+                if (absterm > absoldterm) {
+                    break;
+                }
+                sum += term;
+                if (absterm < MACHEP * std::abs(sum)) {
+                    break;
+                }
+                absoldterm = absterm;
+                afac /= a;
+            }
+            res += sgn * std::exp(-0.5 * a * eta * eta) * sum / std::sqrt(2 * M_PI * a);
+
+            return res;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double igamc(double a, double x);
+
+    XSF_HOST_DEVICE inline double igam(double a, double x) {
+        double absxma_a;
+
+        if (x < 0 || a < 0) {
+            set_error("gammainc", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        } else if (a == 0) {
+            if (x > 0) {
+                return 1;
+            } else {
+                return std::numeric_limits::quiet_NaN();
+            }
+        } else if (x == 0) {
+            /* Zero integration limit */
+            return 0;
+        } else if (std::isinf(a)) {
+            if (std::isinf(x)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+            return 0;
+        } else if (std::isinf(x)) {
+            return 1;
+        }
+
+        /* Asymptotic regime where a ~ x; see [2]. */
+        absxma_a = std::abs(x - a) / a;
+        if ((a > detail::igam_SMALL) && (a < detail::igam_LARGE) && (absxma_a < detail::igam_SMALLRATIO)) {
+            return detail::asymptotic_series(a, x, detail::IGAM);
+        } else if ((a > detail::igam_LARGE) && (absxma_a < detail::igam_LARGERATIO / std::sqrt(a))) {
+            return detail::asymptotic_series(a, x, detail::IGAM);
+        }
+
+        if ((x > 1.0) && (x > a)) {
+            return (1.0 - igamc(a, x));
+        }
+
+        return detail::igam_series(a, x);
+    }
+
+    XSF_HOST_DEVICE double igamc(double a, double x) {
+        double absxma_a;
+
+        if (x < 0 || a < 0) {
+            set_error("gammaincc", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        } else if (a == 0) {
+            if (x > 0) {
+                return 0;
+            } else {
+                return std::numeric_limits::quiet_NaN();
+            }
+        } else if (x == 0) {
+            return 1;
+        } else if (std::isinf(a)) {
+            if (std::isinf(x)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+            return 1;
+        } else if (std::isinf(x)) {
+            return 0;
+        }
+
+        /* Asymptotic regime where a ~ x; see [2]. */
+        absxma_a = std::abs(x - a) / a;
+        if ((a > detail::igam_SMALL) && (a < detail::igam_LARGE) && (absxma_a < detail::igam_SMALLRATIO)) {
+            return detail::asymptotic_series(a, x, detail::IGAMC);
+        } else if ((a > detail::igam_LARGE) && (absxma_a < detail::igam_LARGERATIO / std::sqrt(a))) {
+            return detail::asymptotic_series(a, x, detail::IGAMC);
+        }
+
+        /* Everywhere else; see [2]. */
+        if (x > 1.1) {
+            if (x < a) {
+                return 1.0 - detail::igam_series(a, x);
+            } else {
+                return detail::igamc_continued_fraction(a, x);
+            }
+        } else if (x <= 0.5) {
+            if (-0.4 / std::log(x) < a) {
+                return 1.0 - detail::igam_series(a, x);
+            } else {
+                return detail::igamc_series(a, x);
+            }
+        } else {
+            if (x * 1.1 < a) {
+                return 1.0 - detail::igam_series(a, x);
+            } else {
+                return detail::igamc_series(a, x);
+            }
+        }
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h
new file mode 100644
index 0000000000000000000000000000000000000000..98404c65ebca79239022c0bae10cfe5e43c361c0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igam_asymp_coeff.h
@@ -0,0 +1,195 @@
+/* Translated into C++ by SciPy developers in 2024.  */
+
+/* This file was automatically generated by _precomp/gammainc.py.
+ * Do not edit it manually!
+ */
+#pragma once
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int igam_asymp_coeff_K = 25;
+        constexpr int igam_asymp_coeff_N = 25;
+
+        static const double igam_asymp_coeff_d[igam_asymp_coeff_K][igam_asymp_coeff_N] = {
+            {-3.3333333333333333e-1,  8.3333333333333333e-2,   -1.4814814814814815e-2,  1.1574074074074074e-3,
+             3.527336860670194e-4,    -1.7875514403292181e-4,  3.9192631785224378e-5,   -2.1854485106799922e-6,
+             -1.85406221071516e-6,    8.296711340953086e-7,    -1.7665952736826079e-7,  6.7078535434014986e-9,
+             1.0261809784240308e-8,   -4.3820360184533532e-9,  9.1476995822367902e-10,  -2.551419399494625e-11,
+             -5.8307721325504251e-11, 2.4361948020667416e-11,  -5.0276692801141756e-12, 1.1004392031956135e-13,
+             3.3717632624009854e-13,  -1.3923887224181621e-13, 2.8534893807047443e-14,  -5.1391118342425726e-16,
+             -1.9752288294349443e-15},
+            {-1.8518518518518519e-3,  -3.4722222222222222e-3,  2.6455026455026455e-3,   -9.9022633744855967e-4,
+             2.0576131687242798e-4,   -4.0187757201646091e-7,  -1.8098550334489978e-5,  7.6491609160811101e-6,
+             -1.6120900894563446e-6,  4.6471278028074343e-9,   1.378633446915721e-7,    -5.752545603517705e-8,
+             1.1951628599778147e-8,   -1.7543241719747648e-11, -1.0091543710600413e-9,  4.1627929918425826e-10,
+             -8.5639070264929806e-11, 6.0672151016047586e-14,  7.1624989648114854e-12,  -2.9331866437714371e-12,
+             5.9966963656836887e-13,  -2.1671786527323314e-16, -4.9783399723692616e-14, 2.0291628823713425e-14,
+             -4.13125571381061e-15},
+            {4.1335978835978836e-3,   -2.6813271604938272e-3,  7.7160493827160494e-4,  2.0093878600823045e-6,
+             -1.0736653226365161e-4,  5.2923448829120125e-5,   -1.2760635188618728e-5, 3.4235787340961381e-8,
+             1.3721957309062933e-6,   -6.298992138380055e-7,   1.4280614206064242e-7,  -2.0477098421990866e-10,
+             -1.4092529910867521e-8,  6.228974084922022e-9,    -1.3670488396617113e-9, 9.4283561590146782e-13,
+             1.2872252400089318e-10,  -5.5645956134363321e-11, 1.1975935546366981e-11, -4.1689782251838635e-15,
+             -1.0940640427884594e-12, 4.6622399463901357e-13,  -9.905105763906906e-14, 1.8931876768373515e-17,
+             8.8592218725911273e-15},
+            {6.4943415637860082e-4,   2.2947209362139918e-4,   -4.6918949439525571e-4,  2.6772063206283885e-4,
+             -7.5618016718839764e-5,  -2.3965051138672967e-7,  1.1082654115347302e-5,   -5.6749528269915966e-6,
+             1.4230900732435884e-6,   -2.7861080291528142e-11, -1.6958404091930277e-7,  8.0994649053880824e-8,
+             -1.9111168485973654e-8,  2.3928620439808118e-12,  2.0620131815488798e-9,   -9.4604966618551322e-10,
+             2.1541049775774908e-10,  -1.388823336813903e-14,  -2.1894761681963939e-11, 9.7909989511716851e-12,
+             -2.1782191880180962e-12, 6.2088195734079014e-17,  2.126978363279737e-13,   -9.3446887915174333e-14,
+             2.0453671226782849e-14},
+            {-8.618882909167117e-4,   7.8403922172006663e-4,   -2.9907248030319018e-4, -1.4638452578843418e-6,
+             6.6414982154651222e-5,   -3.9683650471794347e-5,  1.1375726970678419e-5,  2.5074972262375328e-10,
+             -1.6954149536558306e-6,  8.9075075322053097e-7,   -2.2929348340008049e-7, 2.956794137544049e-11,
+             2.8865829742708784e-8,   -1.4189739437803219e-8,  3.4463580499464897e-9,  -2.3024517174528067e-13,
+             -3.9409233028046405e-10, 1.8602338968504502e-10,  -4.356323005056618e-11, 1.2786001016296231e-15,
+             4.6792750266579195e-12,  -2.1492464706134829e-12, 4.9088156148096522e-13, -6.3385914848915603e-18,
+             -5.0453320690800944e-14},
+            {-3.3679855336635815e-4,  -6.9728137583658578e-5,  2.7727532449593921e-4,  -1.9932570516188848e-4,
+             6.7977804779372078e-5,   1.419062920643967e-7,    -1.3594048189768693e-5, 8.0184702563342015e-6,
+             -2.2914811765080952e-6,  -3.252473551298454e-10,  3.4652846491085265e-7,  -1.8447187191171343e-7,
+             4.8240967037894181e-8,   -1.7989466721743515e-14, -6.3061945000135234e-9, 3.1624176287745679e-9,
+             -7.8409242536974293e-10, 5.1926791652540407e-15,  9.3589442423067836e-11, -4.5134262161632782e-11,
+             1.0799129993116827e-11,  -3.661886712685252e-17,  -1.210902069055155e-12, 5.6807435849905643e-13,
+             -1.3249659916340829e-13},
+            {5.3130793646399222e-4,   -5.9216643735369388e-4,  2.7087820967180448e-4,   7.9023532326603279e-7,
+             -8.1539693675619688e-5,  5.6116827531062497e-5,   -1.8329116582843376e-5,  -3.0796134506033048e-9,
+             3.4651553688036091e-6,   -2.0291327396058604e-6,  5.7887928631490037e-7,   2.338630673826657e-13,
+             -8.8286007463304835e-8,  4.7435958880408128e-8,   -1.2545415020710382e-8,  8.6496488580102925e-14,
+             1.6846058979264063e-9,   -8.5754928235775947e-10, 2.1598224929232125e-10,  -7.6132305204761539e-16,
+             -2.6639822008536144e-11, 1.3065700536611057e-11,  -3.1799163902367977e-12, 4.7109761213674315e-18,
+             3.6902800842763467e-13},
+            {3.4436760689237767e-4,   5.1717909082605922e-5,   -3.3493161081142236e-4,  2.812695154763237e-4,
+             -1.0976582244684731e-4,  -1.2741009095484485e-7,  2.7744451511563644e-5,   -1.8263488805711333e-5,
+             5.7876949497350524e-6,   4.9387589339362704e-10,  -1.0595367014026043e-6,  6.1667143761104075e-7,
+             -1.7562973359060462e-7,  -1.2974473287015439e-12, 2.695423606288966e-8,    -1.4578352908731271e-8,
+             3.887645959386175e-9,    -3.8810022510194121e-17, -5.3279941738772867e-10, 2.7437977643314845e-10,
+             -6.9957960920705679e-11, 2.5899863874868481e-17,  8.8566890996696381e-12,  -4.403168815871311e-12,
+             1.0865561947091654e-12},
+            {-6.5262391859530942e-4, 8.3949872067208728e-4,   -4.3829709854172101e-4, -6.969091458420552e-7,
+             1.6644846642067548e-4,  -1.2783517679769219e-4,  4.6299532636913043e-5,  4.5579098679227077e-9,
+             -1.0595271125805195e-5, 6.7833429048651666e-6,   -2.1075476666258804e-6, -1.7213731432817145e-11,
+             3.7735877416110979e-7,  -2.1867506700122867e-7,  6.2202288040189269e-8,  6.5977038267330006e-16,
+             -9.5903864974256858e-9, 5.2132144922808078e-9,   -1.3991589583935709e-9, 5.382058999060575e-16,
+             1.9484714275467745e-10, -1.0127287556389682e-10, 2.6077347197254926e-11, -5.0904186999932993e-18,
+             -3.3721464474854592e-12},
+            {-5.9676129019274625e-4, -7.2048954160200106e-5,  6.7823088376673284e-4,   -6.4014752602627585e-4,
+             2.7750107634328704e-4,  1.8197008380465151e-7,   -8.4795071170685032e-5,  6.105192082501531e-5,
+             -2.1073920183404862e-5, -8.8585890141255994e-10, 4.5284535953805377e-6,   -2.8427815022504408e-6,
+             8.7082341778646412e-7,  3.6886101871706965e-12,  -1.5344695190702061e-7,  8.862466778790695e-8,
+             -2.5184812301826817e-8, -1.0225912098215092e-14, 3.8969470758154777e-9,   -2.1267304792235635e-9,
+             5.7370135528051385e-10, -1.887749850169741e-19,  -8.0931538694657866e-11, 4.2382723283449199e-11,
+             -1.1002224534207726e-11},
+            {1.3324454494800656e-3,  -1.9144384985654775e-3, 1.1089369134596637e-3,   9.932404122642299e-7,
+             -5.0874501293093199e-4, 4.2735056665392884e-4,  -1.6858853767910799e-4,  -8.1301893922784998e-9,
+             4.5284402370562147e-5,  -3.127053674781734e-5,  1.044986828530338e-5,    4.8435226265680926e-11,
+             -2.1482565873456258e-6, 1.329369701097492e-6,   -4.0295693092101029e-7,  -1.7567877666323291e-13,
+             7.0145043163668257e-8,  -4.040787734999483e-8,  1.1474026743371963e-8,   3.9642746853563325e-18,
+             -1.7804938269892714e-9, 9.7480262548731646e-10, -2.6405338676507616e-10, 5.794875163403742e-18,
+             3.7647749553543836e-11},
+            {1.579727660730835e-3,   1.6251626278391582e-4,   -2.0633421035543276e-3, 2.1389686185689098e-3,
+             -1.0108559391263003e-3, -3.9912705529919201e-7,  3.6235025084764691e-4,  -2.8143901463712154e-4,
+             1.0449513336495887e-4,  2.1211418491830297e-9,   -2.5779417251947842e-5, 1.7281818956040463e-5,
+             -5.6413773872904282e-6, -1.1024320105776174e-11, 1.1223224418895175e-6,  -6.8693396379526735e-7,
+             2.0653236975414887e-7,  4.6714772409838506e-14,  -3.5609886164949055e-8, 2.0470855345905963e-8,
+             -5.8091738633283358e-9, -1.332821287582869e-16,  9.0354604391335133e-10, -4.9598782517330834e-10,
+             1.3481607129399749e-10},
+            {-4.0725121195140166e-3, 6.4033628338080698e-3,  -4.0410161081676618e-3, -2.183732802866233e-6,
+             2.1740441801254639e-3,  -1.9700440518418892e-3, 8.3595469747962458e-4,  1.9445447567109655e-8,
+             -2.5779387120421696e-4, 1.9009987368139304e-4,  -6.7696499937438965e-5, -1.4440629666426572e-10,
+             1.5712512518742269e-5,  -1.0304008744776893e-5, 3.304517767401387e-6,   7.9829760242325709e-13,
+             -6.4097794149313004e-7, 3.8894624761300056e-7,  -1.1618347644948869e-7, -2.816808630596451e-15,
+             1.9878012911297093e-8,  -1.1407719956357511e-8, 3.2355857064185555e-9,  4.1759468293455945e-20,
+             -5.0423112718105824e-10},
+            {-5.9475779383993003e-3, -5.4016476789260452e-4,  8.7910413550767898e-3,  -9.8576315587856125e-3,
+             5.0134695031021538e-3,  1.2807521786221875e-6,   -2.0626019342754683e-3, 1.7109128573523058e-3,
+             -6.7695312714133799e-4, -6.9011545676562133e-9,  1.8855128143995902e-4,  -1.3395215663491969e-4,
+             4.6263183033528039e-5,  4.0034230613321351e-11,  -1.0255652921494033e-5, 6.612086372797651e-6,
+             -2.0913022027253008e-6, -2.0951775649603837e-13, 3.9756029041993247e-7,  -2.3956211978815887e-7,
+             7.1182883382145864e-8,  8.925574873053455e-16,   -1.2101547235064676e-8, 6.9350618248334386e-9,
+             -1.9661464453856102e-9},
+            {1.7402027787522711e-2,  -2.9527880945699121e-2, 2.0045875571402799e-2,  7.0289515966903407e-6,
+             -1.2375421071343148e-2, 1.1976293444235254e-2,  -5.4156038466518525e-3, -6.3290893396418616e-8,
+             1.8855118129005065e-3,  -1.473473274825001e-3,  5.5515810097708387e-4,  5.2406834412550662e-10,
+             -1.4357913535784836e-4, 9.9181293224943297e-5,  -3.3460834749478311e-5, -3.5755837291098993e-12,
+             7.1560851960630076e-6,  -4.5516802628155526e-6, 1.4236576649271475e-6,  1.8803149082089664e-14,
+             -2.6623403898929211e-7, 1.5950642189595716e-7,  -4.7187514673841102e-8, -6.5107872958755177e-17,
+             7.9795091026746235e-9},
+            {3.0249124160905891e-2,  2.4817436002649977e-3,  -4.9939134373457022e-2, 5.9915643009307869e-2,
+             -3.2483207601623391e-2, -5.7212968652103441e-6, 1.5085251778569354e-2,  -1.3261324005088445e-2,
+             5.5515262632426148e-3,  3.0263182257030016e-8,  -1.7229548406756723e-3, 1.2893570099929637e-3,
+             -4.6845138348319876e-4, -1.830259937893045e-10, 1.1449739014822654e-4,  -7.7378565221244477e-5,
+             2.5625836246985201e-5,  1.0766165333192814e-12, -5.3246809282422621e-6, 3.349634863064464e-6,
+             -1.0381253128684018e-6, -5.608909920621128e-15, 1.9150821930676591e-7,  -1.1418365800203486e-7,
+             3.3654425209171788e-8},
+            {-9.9051020880159045e-2, 1.7954011706123486e-1,  -1.2989606383463778e-1, -3.1478872752284357e-5,
+             9.0510635276848131e-2,  -9.2828824411184397e-2, 4.4412112839877808e-2,  2.7779236316835888e-7,
+             -1.7229543805449697e-2, 1.4182925050891573e-2,  -5.6214161633747336e-3, -2.39598509186381e-9,
+             1.6029634366079908e-3,  -1.1606784674435773e-3, 4.1001337768153873e-4,  1.8365800754090661e-11,
+             -9.5844256563655903e-5, 6.3643062337764708e-5,  -2.076250624489065e-5,  -1.1806020912804483e-13,
+             4.2131808239120649e-6,  -2.6262241337012467e-6, 8.0770620494930662e-7,  6.0125912123632725e-16,
+             -1.4729737374018841e-7},
+            {-1.9994542198219728e-1, -1.5056113040026424e-2,  3.6470239469348489e-1,  -4.6435192311733545e-1,
+             2.6640934719197893e-1,  3.4038266027147191e-5,   -1.3784338709329624e-1, 1.276467178337056e-1,
+             -5.6213828755200985e-2, -1.753150885483011e-7,   1.9235592956768113e-2,  -1.5088821281095315e-2,
+             5.7401854451350123e-3,  1.0622382710310225e-9,   -1.5335082692563998e-3, 1.0819320643228214e-3,
+             -3.7372510193945659e-4, -6.6170909729031985e-12, 8.4263617380909628e-5,  -5.5150706827483479e-5,
+             1.7769536448348069e-5,  3.8827923210205533e-14,  -3.53513697488768e-6,   2.1865832130045269e-6,
+             -6.6812849447625594e-7},
+            {7.2438608504029431e-1,  -1.3918010932653375,    1.0654143352413968,     1.876173868950258e-4,
+             -8.2705501176152696e-1, 8.9352433347828414e-1,  -4.4971003995291339e-1, -1.6107401567546652e-6,
+             1.9235590165271091e-1,  -1.6597702160042609e-1, 6.8882222681814333e-2,  1.3910091724608687e-8,
+             -2.146911561508663e-2,  1.6228980898865892e-2,  -5.9796016172584256e-3, -1.1287469112826745e-10,
+             1.5167451119784857e-3,  -1.0478634293553899e-3, 3.5539072889126421e-4,  8.1704322111801517e-13,
+             -7.7773013442452395e-5, 5.0291413897007722e-5,  -1.6035083867000518e-5, 1.2469354315487605e-14,
+             3.1369106244517615e-6},
+            {1.6668949727276811,     1.165462765994632e-1,   -3.3288393225018906,    4.4692325482864037,
+             -2.6977693045875807,    -2.600667859891061e-4,  1.5389017615694539,     -1.4937962361134612,
+             6.8881964633233148e-1,  1.3077482004552385e-6,  -2.5762963325596288e-1, 2.1097676102125449e-1,
+             -8.3714408359219882e-2, -7.7920428881354753e-9, 2.4267923064833599e-2,  -1.7813678334552311e-2,
+             6.3970330388900056e-3,  4.9430807090480523e-11, -1.5554602758465635e-3, 1.0561196919903214e-3,
+             -3.5277184460472902e-4, 9.3002334645022459e-14, 7.5285855026557172e-5,  -4.8186515569156351e-5,
+             1.5227271505597605e-5},
+            {-6.6188298861372935,    1.3397985455142589e+1,  -1.0789350606845146e+1, -1.4352254537875018e-3,
+             9.2333694596189809,     -1.0456552819547769e+1, 5.5105526029033471,     1.2024439690716742e-5,
+             -2.5762961164755816,    2.3207442745387179,     -1.0045728797216284,    -1.0207833290021914e-7,
+             3.3975092171169466e-1,  -2.6720517450757468e-1, 1.0235252851562706e-1,  8.4329730484871625e-10,
+             -2.7998284958442595e-2, 2.0066274144976813e-2,  -7.0554368915086242e-3, 1.9402238183698188e-12,
+             1.6562888105449611e-3,  -1.1082898580743683e-3, 3.654545161310169e-4,   -5.1290032026971794e-11,
+             -7.6340103696869031e-5},
+            {-1.7112706061976095e+1, -1.1208044642899116,     3.7131966511885444e+1,  -5.2298271025348962e+1,
+             3.3058589696624618e+1,  2.4791298976200222e-3,   -2.061089403411526e+1,  2.088672775145582e+1,
+             -1.0045703956517752e+1, -1.2238783449063012e-5,  4.0770134274221141,     -3.473667358470195,
+             1.4329352617312006,     7.1359914411879712e-8,   -4.4797257159115612e-1, 3.4112666080644461e-1,
+             -1.2699786326594923e-1, -2.8953677269081528e-10, 3.3125776278259863e-2,  -2.3274087021036101e-2,
+             8.0399993503648882e-3,  -1.177805216235265e-9,   -1.8321624891071668e-3, 1.2108282933588665e-3,
+             -3.9479941246822517e-4},
+            {7.389033153567425e+1,   -1.5680141270402273e+2, 1.322177542759164e+2,   1.3692876877324546e-2,
+             -1.2366496885920151e+2, 1.4620689391062729e+2,  -8.0365587724865346e+1, -1.1259851148881298e-4,
+             4.0770132196179938e+1,  -3.8210340013273034e+1, 1.719522294277362e+1,   9.3519707955168356e-7,
+             -6.2716159907747034,    5.1168999071852637,     -2.0319658112299095,    -4.9507215582761543e-9,
+             5.9626397294332597e-1,  -4.4220765337238094e-1, 1.6079998700166273e-1,  -2.4733786203223402e-8,
+             -4.0307574759979762e-2, 2.7849050747097869e-2,  -9.4751858992054221e-3, 6.419922235909132e-6,
+             2.1250180774699461e-3},
+            {2.1216837098382522e+2,  1.3107863022633868e+1,  -4.9698285932871748e+2, 7.3121595266969204e+2,
+             -4.8213821720890847e+2, -2.8817248692894889e-2, 3.2616720302947102e+2,  -3.4389340280087117e+2,
+             1.7195193870816232e+2,  1.4038077378096158e-4,  -7.52594195897599e+1,   6.651969984520934e+1,
+             -2.8447519748152462e+1, -7.613702615875391e-7,  9.5402237105304373,     -7.5175301113311376,
+             2.8943997568871961,     -4.6612194999538201e-7, -8.0615149598794088e-1, 5.8483006570631029e-1,
+             -2.0845408972964956e-1, 1.4765818959305817e-4,  5.1000433863753019e-2,  -3.3066252141883665e-2,
+             1.5109265210467774e-2},
+            {-9.8959643098322368e+2, 2.1925555360905233e+3,  -1.9283586782723356e+3, -1.5925738122215253e-1,
+             1.9569985945919857e+3,  -2.4072514765081556e+3, 1.3756149959336496e+3,  1.2920735237496668e-3,
+             -7.525941715948055e+2,  7.3171668742208716e+2,  -3.4137023466220065e+2, -9.9857390260608043e-6,
+             1.3356313181291573e+2,  -1.1276295161252794e+2, 4.6310396098204458e+1,  -7.9237387133614756e-6,
+             -1.4510726927018646e+1, 1.1111771248100563e+1,  -4.1690817945270892,    3.1008219800117808e-3,
+             1.1220095449981468,     -7.6052379926149916e-1, 3.6262236505085254e-1,  2.216867741940747e-1,
+             4.8683443692930507e-1}};
+
+    } // namespace detail
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h
new file mode 100644
index 0000000000000000000000000000000000000000..ff82c35f682b04a250f6a86721312f860b3fe7cb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/igami.h
@@ -0,0 +1,313 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*
+ * (C) Copyright John Maddock 2006.
+ * Use, modification and distribution are subject to the
+ * Boost Software License, Version 1.0. (See accompanying file
+ *  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "igam.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        XSF_HOST_DEVICE double find_inverse_s(double p, double q) {
+            /*
+             * Computation of the Incomplete Gamma Function Ratios and their Inverse
+             * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.
+             * ACM Transactions on Mathematical Software, Vol. 12, No. 4,
+             * December 1986, Pages 377-393.
+             *
+             * See equation 32.
+             */
+            double s, t;
+            constexpr double a[4] = {0.213623493715853, 4.28342155967104, 11.6616720288968, 3.31125922108741};
+            constexpr double b[5] = {0.3611708101884203e-1, 1.27364489782223, 6.40691597760039, 6.61053765625462, 1};
+
+            if (p < 0.5) {
+                t = std::sqrt(-2 * std::log(p));
+            } else {
+                t = std::sqrt(-2 * std::log(q));
+            }
+            s = t - polevl(t, a, 3) / polevl(t, b, 4);
+            if (p < 0.5)
+                s = -s;
+            return s;
+        }
+
+        XSF_HOST_DEVICE inline double didonato_SN(double a, double x, unsigned N, double tolerance) {
+            /*
+             * Computation of the Incomplete Gamma Function Ratios and their Inverse
+             * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.
+             * ACM Transactions on Mathematical Software, Vol. 12, No. 4,
+             * December 1986, Pages 377-393.
+             *
+             * See equation 34.
+             */
+            double sum = 1.0;
+
+            if (N >= 1) {
+                unsigned i;
+                double partial = x / (a + 1);
+
+                sum += partial;
+                for (i = 2; i <= N; ++i) {
+                    partial *= x / (a + i);
+                    sum += partial;
+                    if (partial < tolerance) {
+                        break;
+                    }
+                }
+            }
+            return sum;
+        }
+
+        XSF_HOST_DEVICE inline double find_inverse_gamma(double a, double p, double q) {
+            /*
+             * In order to understand what's going on here, you will
+             * need to refer to:
+             *
+             * Computation of the Incomplete Gamma Function Ratios and their Inverse
+             * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR.
+             * ACM Transactions on Mathematical Software, Vol. 12, No. 4,
+             * December 1986, Pages 377-393.
+             */
+            double result;
+
+            if (a == 1) {
+                if (q > 0.9) {
+                    result = -std::log1p(-p);
+                } else {
+                    result = -std::log(q);
+                }
+            } else if (a < 1) {
+                double g = xsf::cephes::Gamma(a);
+                double b = q * g;
+
+                if ((b > 0.6) || ((b >= 0.45) && (a >= 0.3))) {
+                    /* DiDonato & Morris Eq 21:
+                     *
+                     * There is a slight variation from DiDonato and Morris here:
+                     * the first form given here is unstable when p is close to 1,
+                     * making it impossible to compute the inverse of Q(a,x) for small
+                     * q. Fortunately the second form works perfectly well in this case.
+                     */
+                    double u;
+                    if ((b * q > 1e-8) && (q > 1e-5)) {
+                        u = std::pow(p * g * a, 1 / a);
+                    } else {
+                        u = std::exp((-q / a) - SCIPY_EULER);
+                    }
+                    result = u / (1 - (u / (a + 1)));
+                } else if ((a < 0.3) && (b >= 0.35)) {
+                    /* DiDonato & Morris Eq 22: */
+                    double t = std::exp(-SCIPY_EULER - b);
+                    double u = t * std::exp(t);
+                    result = t * std::exp(u);
+                } else if ((b > 0.15) || (a >= 0.3)) {
+                    /* DiDonato & Morris Eq 23: */
+                    double y = -std::log(b);
+                    double u = y - (1 - a) * std::log(y);
+                    result = y - (1 - a) * std::log(u) - std::log(1 + (1 - a) / (1 + u));
+                } else if (b > 0.1) {
+                    /* DiDonato & Morris Eq 24: */
+                    double y = -std::log(b);
+                    double u = y - (1 - a) * std::log(y);
+                    result = y - (1 - a) * std::log(u) -
+                             std::log((u * u + 2 * (3 - a) * u + (2 - a) * (3 - a)) / (u * u + (5 - a) * u + 2));
+                } else {
+                    /* DiDonato & Morris Eq 25: */
+                    double y = -std::log(b);
+                    double c1 = (a - 1) * std::log(y);
+                    double c1_2 = c1 * c1;
+                    double c1_3 = c1_2 * c1;
+                    double c1_4 = c1_2 * c1_2;
+                    double a_2 = a * a;
+                    double a_3 = a_2 * a;
+
+                    double c2 = (a - 1) * (1 + c1);
+                    double c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2);
+                    double c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 +
+                                           (11 * a_2 - 46 * a + 47) / 6);
+                    double c5 = (a - 1) * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + (-3 * a_2 + 13 * a - 13) * c1_2 +
+                                           (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 +
+                                           (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12);
+
+                    double y_2 = y * y;
+                    double y_3 = y_2 * y;
+                    double y_4 = y_2 * y_2;
+                    result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4);
+                }
+            } else {
+                /* DiDonato and Morris Eq 31: */
+                double s = find_inverse_s(p, q);
+
+                double s_2 = s * s;
+                double s_3 = s_2 * s;
+                double s_4 = s_2 * s_2;
+                double s_5 = s_4 * s;
+                double ra = std::sqrt(a);
+
+                double w = a + s * ra + (s_2 - 1) / 3;
+                w += (s_3 - 7 * s) / (36 * ra);
+                w -= (3 * s_4 + 7 * s_2 - 16) / (810 * a);
+                w += (9 * s_5 + 256 * s_3 - 433 * s) / (38880 * a * ra);
+
+                if ((a >= 500) && (std::abs(1 - w / a) < 1e-6)) {
+                    result = w;
+                } else if (p > 0.5) {
+                    if (w < 3 * a) {
+                        result = w;
+                    } else {
+                        double D = std::fmax(2, a * (a - 1));
+                        double lg = xsf::cephes::lgam(a);
+                        double lb = std::log(q) + lg;
+                        if (lb < -D * 2.3) {
+                            /* DiDonato and Morris Eq 25: */
+                            double y = -lb;
+                            double c1 = (a - 1) * std::log(y);
+                            double c1_2 = c1 * c1;
+                            double c1_3 = c1_2 * c1;
+                            double c1_4 = c1_2 * c1_2;
+                            double a_2 = a * a;
+                            double a_3 = a_2 * a;
+
+                            double c2 = (a - 1) * (1 + c1);
+                            double c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2);
+                            double c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 +
+                                                   (11 * a_2 - 46 * a + 47) / 6);
+                            double c5 =
+                                (a - 1) * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + (-3 * a_2 + 13 * a - 13) * c1_2 +
+                                           (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 +
+                                           (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12);
+
+                            double y_2 = y * y;
+                            double y_3 = y_2 * y;
+                            double y_4 = y_2 * y_2;
+                            result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4);
+                        } else {
+                            /* DiDonato and Morris Eq 33: */
+                            double u = -lb + (a - 1) * std::log(w) - std::log(1 + (1 - a) / (1 + w));
+                            result = -lb + (a - 1) * std::log(u) - std::log(1 + (1 - a) / (1 + u));
+                        }
+                    }
+                } else {
+                    double z = w;
+                    double ap1 = a + 1;
+                    double ap2 = a + 2;
+                    if (w < 0.15 * ap1) {
+                        /* DiDonato and Morris Eq 35: */
+                        double v = std::log(p) + xsf::cephes::lgam(ap1);
+                        z = std::exp((v + w) / a);
+                        s = std::log1p(z / ap1 * (1 + z / ap2));
+                        z = std::exp((v + z - s) / a);
+                        s = std::log1p(z / ap1 * (1 + z / ap2));
+                        z = std::exp((v + z - s) / a);
+                        s = std::log1p(z / ap1 * (1 + z / ap2 * (1 + z / (a + 3))));
+                        z = std::exp((v + z - s) / a);
+                    }
+
+                    if ((z <= 0.01 * ap1) || (z > 0.7 * ap1)) {
+                        result = z;
+                    } else {
+                        /* DiDonato and Morris Eq 36: */
+                        double ls = std::log(didonato_SN(a, z, 100, 1e-4));
+                        double v = std::log(p) + xsf::cephes::lgam(ap1);
+                        z = std::exp((v + z - ls) / a);
+                        result = z * (1 - (a * std::log(z) - z - v + ls) / (a - z));
+                    }
+                }
+            }
+            return result;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double igamci(double a, double q);
+
+    XSF_HOST_DEVICE inline double igami(double a, double p) {
+        int i;
+        double x, fac, f_fp, fpp_fp;
+
+        if (std::isnan(a) || std::isnan(p)) {
+            return std::numeric_limits::quiet_NaN();
+            ;
+        } else if ((a < 0) || (p < 0) || (p > 1)) {
+            set_error("gammaincinv", SF_ERROR_DOMAIN, NULL);
+        } else if (p == 0.0) {
+            return 0.0;
+        } else if (p == 1.0) {
+            return std::numeric_limits::infinity();
+        } else if (p > 0.9) {
+            return igamci(a, 1 - p);
+        }
+
+        x = detail::find_inverse_gamma(a, p, 1 - p);
+        /* Halley's method */
+        for (i = 0; i < 3; i++) {
+            fac = detail::igam_fac(a, x);
+            if (fac == 0.0) {
+                return x;
+            }
+            f_fp = (igam(a, x) - p) * x / fac;
+            /* The ratio of the first and second derivatives simplifies */
+            fpp_fp = -1.0 + (a - 1) / x;
+            if (std::isinf(fpp_fp)) {
+                /* Resort to Newton's method in the case of overflow */
+                x = x - f_fp;
+            } else {
+                x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp);
+            }
+        }
+
+        return x;
+    }
+
+    XSF_HOST_DEVICE inline double igamci(double a, double q) {
+        int i;
+        double x, fac, f_fp, fpp_fp;
+
+        if (std::isnan(a) || std::isnan(q)) {
+            return std::numeric_limits::quiet_NaN();
+        } else if ((a < 0.0) || (q < 0.0) || (q > 1.0)) {
+            set_error("gammainccinv", SF_ERROR_DOMAIN, NULL);
+        } else if (q == 0.0) {
+            return std::numeric_limits::infinity();
+        } else if (q == 1.0) {
+            return 0.0;
+        } else if (q > 0.9) {
+            return igami(a, 1 - q);
+        }
+
+        x = detail::find_inverse_gamma(a, 1 - q, q);
+        for (i = 0; i < 3; i++) {
+            fac = detail::igam_fac(a, x);
+            if (fac == 0.0) {
+                return x;
+            }
+            f_fp = (igamc(a, x) - q) * x / (-fac);
+            fpp_fp = -1.0 + (a - 1) / x;
+            if (std::isinf(fpp_fp)) {
+                x = x - f_fp;
+            } else {
+                x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp);
+            }
+        }
+
+        return x;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h
new file mode 100644
index 0000000000000000000000000000000000000000..29236ef966e05f615920b381489e627950e78740
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j0.h
@@ -0,0 +1,225 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     j0.c
+ *
+ *     Bessel function of order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, j0();
+ *
+ * y = j0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of order zero of the argument.
+ *
+ * The domain is divided into the intervals [0, 5] and
+ * (5, infinity). In the first interval the following rational
+ * approximation is used:
+ *
+ *
+ *        2         2
+ * (w - r  ) (w - r  ) P (w) / Q (w)
+ *       1         2    3       8
+ *
+ *            2
+ * where w = x  and the two r's are zeros of the function.
+ *
+ * In the second interval, the Hankel asymptotic expansion
+ * is employed with two rational functions of degree 6/6
+ * and 7/7.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Absolute error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       60000       4.2e-16     1.1e-16
+ *
+ */
+/*							y0.c
+ *
+ *	Bessel function of the second kind, order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, y0();
+ *
+ * y = y0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of the second kind, of order
+ * zero, of the argument.
+ *
+ * The domain is divided into the intervals [0, 5] and
+ * (5, infinity). In the first interval a rational approximation
+ * R(x) is employed to compute
+ *   y0(x)  = R(x)  +   2 * log(x) * j0(x) / M_PI.
+ * Thus a call to j0() is required.
+ *
+ * In the second interval, the Hankel asymptotic expansion
+ * is employed with two rational functions of degree 6/6
+ * and 7/7.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *  Absolute error, when y0(x) < 1; else relative error:
+ *
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.3e-15     1.6e-16
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
+ */
+
+/* Note: all coefficients satisfy the relative error criterion
+ * except YP, YQ which are designed for absolute error. */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double j0_PP[7] = {
+            7.96936729297347051624E-4, 8.28352392107440799803E-2, 1.23953371646414299388E0,  5.44725003058768775090E0,
+            8.74716500199817011941E0,  5.30324038235394892183E0,  9.99999999999999997821E-1,
+        };
+
+        constexpr double j0_PQ[7] = {
+            9.24408810558863637013E-4, 8.56288474354474431428E-2, 1.25352743901058953537E0, 5.47097740330417105182E0,
+            8.76190883237069594232E0,  5.30605288235394617618E0,  1.00000000000000000218E0,
+        };
+
+        constexpr double j0_QP[8] = {
+            -1.13663838898469149931E-2, -1.28252718670509318512E0, -1.95539544257735972385E1, -9.32060152123768231369E1,
+            -1.77681167980488050595E2,  -1.47077505154951170175E2, -5.14105326766599330220E1, -6.05014350600728481186E0,
+        };
+
+        constexpr double j0_QQ[7] = {
+            /*  1.00000000000000000000E0, */
+            6.43178256118178023184E1, 8.56430025976980587198E2, 3.88240183605401609683E3, 7.24046774195652478189E3,
+            5.93072701187316984827E3, 2.06209331660327847417E3, 2.42005740240291393179E2,
+        };
+
+        constexpr double j0_YP[8] = {
+            1.55924367855235737965E4,   -1.46639295903971606143E7,  5.43526477051876500413E9,
+            -9.82136065717911466409E11, 8.75906394395366999549E13,  -3.46628303384729719441E15,
+            4.42733268572569800351E16,  -1.84950800436986690637E16,
+        };
+
+        constexpr double j0_YQ[7] = {
+            /* 1.00000000000000000000E0, */
+            1.04128353664259848412E3,  6.26107330137134956842E5,  2.68919633393814121987E8,  8.64002487103935000337E10,
+            2.02979612750105546709E13, 3.17157752842975028269E15, 2.50596256172653059228E17,
+        };
+
+        /*  5.783185962946784521175995758455807035071 */
+        constexpr double j0_DR1 = 5.78318596294678452118E0;
+
+        /* 30.47126234366208639907816317502275584842 */
+        constexpr double j0_DR2 = 3.04712623436620863991E1;
+
+        constexpr double j0_RP[4] = {
+            -4.79443220978201773821E9,
+            1.95617491946556577543E12,
+            -2.49248344360967716204E14,
+            9.70862251047306323952E15,
+        };
+
+        constexpr double j0_RQ[8] = {
+            /* 1.00000000000000000000E0, */
+            4.99563147152651017219E2,  1.73785401676374683123E5,  4.84409658339962045305E7,  1.11855537045356834862E10,
+            2.11277520115489217587E12, 3.10518229857422583814E14, 3.18121955943204943306E16, 1.71086294081043136091E18,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double j0(double x) {
+        double w, z, p, q, xn;
+
+        if (x < 0) {
+            x = -x;
+        }
+
+        if (x <= 5.0) {
+            z = x * x;
+            if (x < 1.0e-5) {
+                return (1.0 - z / 4.0);
+            }
+
+            p = (z - detail::j0_DR1) * (z - detail::j0_DR2);
+            p = p * polevl(z, detail::j0_RP, 3) / p1evl(z, detail::j0_RQ, 8);
+            return (p);
+        }
+
+        w = 5.0 / x;
+        q = 25.0 / (x * x);
+        p = polevl(q, detail::j0_PP, 6) / polevl(q, detail::j0_PQ, 6);
+        q = polevl(q, detail::j0_QP, 7) / p1evl(q, detail::j0_QQ, 7);
+        xn = x - M_PI_4;
+        p = p * std::cos(xn) - w * q * std::sin(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+
+    /*                                                     y0() 2  */
+    /* Bessel function of second kind, order zero  */
+
+    /* Rational approximation coefficients YP[], YQ[] are used here.
+     * The function computed is  y0(x)  -  2 * log(x) * j0(x) / M_PI,
+     * whose value at x = 0 is  2 * ( log(0.5) + EUL ) / M_PI
+     * = 0.073804295108687225.
+     */
+
+    XSF_HOST_DEVICE inline double y0(double x) {
+        double w, z, p, q, xn;
+
+        if (x <= 5.0) {
+            if (x == 0.0) {
+                set_error("y0", SF_ERROR_SINGULAR, NULL);
+                return -std::numeric_limits::infinity();
+            } else if (x < 0.0) {
+                set_error("y0", SF_ERROR_DOMAIN, NULL);
+                return std::numeric_limits::quiet_NaN();
+            }
+            z = x * x;
+            w = polevl(z, detail::j0_YP, 7) / p1evl(z, detail::j0_YQ, 7);
+            w += M_2_PI * std::log(x) * j0(x);
+            return (w);
+        }
+
+        w = 5.0 / x;
+        z = 25.0 / (x * x);
+        p = polevl(z, detail::j0_PP, 6) / polevl(z, detail::j0_PQ, 6);
+        q = polevl(z, detail::j0_QP, 7) / p1evl(z, detail::j0_QQ, 7);
+        xn = x - M_PI_4;
+        p = p * std::sin(xn) + w * q * std::cos(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h
new file mode 100644
index 0000000000000000000000000000000000000000..46532249550d214723291f7ca9874bb4a31380ac
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/j1.h
@@ -0,0 +1,198 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     j1.c
+ *
+ *     Bessel function of order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, j1();
+ *
+ * y = j1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of order one of the argument.
+ *
+ * The domain is divided into the intervals [0, 8] and
+ * (8, infinity). In the first interval a 24 term Chebyshev
+ * expansion is used. In the second, the asymptotic
+ * trigonometric representation is employed using two
+ * rational functions of degree 5/5.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Absolute error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE      0, 30       30000       2.6e-16     1.1e-16
+ *
+ *
+ */
+/*							y1.c
+ *
+ *	Bessel function of second kind of order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, y1();
+ *
+ * y = y1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of the second kind of order one
+ * of the argument.
+ *
+ * The domain is divided into the intervals [0, 8] and
+ * (8, infinity). In the first interval a 25 term Chebyshev
+ * expansion is used, and a call to j1() is required.
+ * In the second, the asymptotic trigonometric representation
+ * is employed using two rational functions of degree 5/5.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Absolute error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE      0, 30       30000       1.0e-15     1.3e-16
+ *
+ * (error criterion relative when |y1| > 1).
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
+ */
+
+/*
+ * #define PIO4 .78539816339744830962
+ * #define THPIO4 2.35619449019234492885
+ * #define SQ2OPI .79788456080286535588
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        constexpr double j1_RP[4] = {
+            -8.99971225705559398224E8,
+            4.52228297998194034323E11,
+            -7.27494245221818276015E13,
+            3.68295732863852883286E15,
+        };
+
+        constexpr double j1_RQ[8] = {
+            /* 1.00000000000000000000E0, */
+            6.20836478118054335476E2,  2.56987256757748830383E5,  8.35146791431949253037E7,  2.21511595479792499675E10,
+            4.74914122079991414898E12, 7.84369607876235854894E14, 8.95222336184627338078E16, 5.32278620332680085395E18,
+        };
+
+        constexpr double j1_PP[7] = {
+            7.62125616208173112003E-4, 7.31397056940917570436E-2, 1.12719608129684925192E0, 5.11207951146807644818E0,
+            8.42404590141772420927E0,  5.21451598682361504063E0,  1.00000000000000000254E0,
+        };
+
+        constexpr double j1_PQ[7] = {
+            5.71323128072548699714E-4, 6.88455908754495404082E-2, 1.10514232634061696926E0,  5.07386386128601488557E0,
+            8.39985554327604159757E0,  5.20982848682361821619E0,  9.99999999999999997461E-1,
+        };
+
+        constexpr double j1_QP[8] = {
+            5.10862594750176621635E-2, 4.98213872951233449420E0, 7.58238284132545283818E1, 3.66779609360150777800E2,
+            7.10856304998926107277E2,  5.97489612400613639965E2, 2.11688757100572135698E2, 2.52070205858023719784E1,
+        };
+
+        constexpr double j1_QQ[7] = {
+            /* 1.00000000000000000000E0, */
+            7.42373277035675149943E1, 1.05644886038262816351E3, 4.98641058337653607651E3, 9.56231892404756170795E3,
+            7.99704160447350683650E3, 2.82619278517639096600E3, 3.36093607810698293419E2,
+        };
+
+        constexpr double j1_YP[6] = {
+            1.26320474790178026440E9,   -6.47355876379160291031E11, 1.14509511541823727583E14,
+            -8.12770255501325109621E15, 2.02439475713594898196E17,  -7.78877196265950026825E17,
+        };
+
+        constexpr double j1_YQ[8] = {
+            /* 1.00000000000000000000E0, */
+            5.94301592346128195359E2,  2.35564092943068577943E5,  7.34811944459721705660E7,  1.87601316108706159478E10,
+            3.88231277496238566008E12, 6.20557727146953693363E14, 6.87141087355300489866E16, 3.97270608116560655612E18,
+        };
+
+        constexpr double j1_Z1 = 1.46819706421238932572E1;
+        constexpr double j1_Z2 = 4.92184563216946036703E1;
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double j1(double x) {
+        double w, z, p, q, xn;
+
+        w = x;
+        if (x < 0) {
+            return -j1(-x);
+        }
+
+        if (w <= 5.0) {
+            z = x * x;
+            w = polevl(z, detail::j1_RP, 3) / p1evl(z, detail::j1_RQ, 8);
+            w = w * x * (z - detail::j1_Z1) * (z - detail::j1_Z2);
+            return (w);
+        }
+
+        w = 5.0 / x;
+        z = w * w;
+        p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6);
+        q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7);
+        xn = x - detail::THPIO4;
+        p = p * std::cos(xn) - w * q * std::sin(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+
+    XSF_HOST_DEVICE inline double y1(double x) {
+        double w, z, p, q, xn;
+
+        if (x <= 5.0) {
+            if (x == 0.0) {
+                set_error("y1", SF_ERROR_SINGULAR, NULL);
+                return -std::numeric_limits::infinity();
+            } else if (x <= 0.0) {
+                set_error("y1", SF_ERROR_DOMAIN, NULL);
+                return std::numeric_limits::quiet_NaN();
+            }
+            z = x * x;
+            w = x * (polevl(z, detail::j1_YP, 5) / p1evl(z, detail::j1_YQ, 8));
+            w += M_2_PI * (j1(x) * std::log(x) - 1.0 / x);
+            return (w);
+        }
+
+        w = 5.0 / x;
+        z = w * w;
+        p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6);
+        q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7);
+        xn = x - detail::THPIO4;
+        p = p * std::sin(xn) + w * q * std::cos(xn);
+        return (p * detail::SQRT2OPI / std::sqrt(x));
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h
new file mode 100644
index 0000000000000000000000000000000000000000..db5272f27fb4e6619dafaa02f9fc2cd2b2f57f9e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/jv.h
@@ -0,0 +1,715 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     jv.c
+ *
+ *     Bessel function of noninteger order
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double v, x, y, jv();
+ *
+ * y = jv( v, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns Bessel function of order v of the argument,
+ * where v is real.  Negative x is allowed if v is an integer.
+ *
+ * Several expansions are included: the ascending power
+ * series, the Hankel expansion, and two transitional
+ * expansions for large v.  If v is not too large, it
+ * is reduced by recurrence to a region of best accuracy.
+ * The transitional expansions give 12D accuracy for v > 500.
+ *
+ *
+ *
+ * ACCURACY:
+ * Results for integer v are indicated by *, where x and v
+ * both vary from -125 to +125.  Otherwise,
+ * x ranges from 0 to 125, v ranges as indicated by "domain."
+ * Error criterion is absolute, except relative when |jv()| > 1.
+ *
+ * arithmetic  v domain  x domain    # trials      peak       rms
+ *    IEEE      0,125     0,125      100000      4.6e-15    2.2e-16
+ *    IEEE   -125,0       0,125       40000      5.4e-11    3.7e-13
+ *    IEEE      0,500     0,500       20000      4.4e-15    4.0e-16
+ * Integer v:
+ *    IEEE   -125,125   -125,125      50000      3.5e-15*   1.9e-16*
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "airy.h"
+#include "cbrt.h"
+#include "rgamma.h"
+#include "j0.h"
+#include "j1.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double jv_BIG = 1.44115188075855872E+17;
+
+        /* Reduce the order by backward recurrence.
+         * AMS55 #9.1.27 and 9.1.73.
+         */
+
+        XSF_HOST_DEVICE inline double jv_recur(double *n, double x, double *newn, int cancel) {
+            double pkm2, pkm1, pk, qkm2, qkm1;
+
+            /* double pkp1; */
+            double k, ans, qk, xk, yk, r, t, kf;
+            constexpr double big = jv_BIG;
+            int nflag, ctr;
+            int miniter, maxiter;
+
+            /* Continued fraction for Jn(x)/Jn-1(x)
+             * AMS 9.1.73
+             *
+             *    x       -x^2      -x^2
+             * ------  ---------  ---------   ...
+             * 2 n +   2(n+1) +   2(n+2) +
+             *
+             * Compute it with the simplest possible algorithm.
+             *
+             * This continued fraction starts to converge when (|n| + m) > |x|.
+             * Hence, at least |x|-|n| iterations are necessary before convergence is
+             * achieved. There is a hard limit set below, m <= 30000, which is chosen
+             * so that no branch in `jv` requires more iterations to converge.
+             * The exact maximum number is (500/3.6)^2 - 500 ~ 19000
+             */
+
+            maxiter = 22000;
+            miniter = std::abs(x) - std::abs(*n);
+            if (miniter < 1) {
+                miniter = 1;
+            }
+
+            if (*n < 0.0) {
+                nflag = 1;
+            } else {
+                nflag = 0;
+            }
+
+        fstart:
+            pkm2 = 0.0;
+            qkm2 = 1.0;
+            pkm1 = x;
+            qkm1 = *n + *n;
+            xk = -x * x;
+            yk = qkm1;
+            ans = 0.0; /* ans=0.0 ensures that t=1.0 in the first iteration */
+            ctr = 0;
+            do {
+                yk += 2.0;
+                pk = pkm1 * yk + pkm2 * xk;
+                qk = qkm1 * yk + qkm2 * xk;
+                pkm2 = pkm1;
+                pkm1 = pk;
+                qkm2 = qkm1;
+                qkm1 = qk;
+
+                /* check convergence */
+                if (qk != 0 && ctr > miniter)
+                    r = pk / qk;
+                else
+                    r = 0.0;
+
+                if (r != 0) {
+                    t = std::abs((ans - r) / r);
+                    ans = r;
+                } else {
+                    t = 1.0;
+                }
+
+                if (++ctr > maxiter) {
+                    set_error("jv", SF_ERROR_UNDERFLOW, NULL);
+                    goto done;
+                }
+                if (t < MACHEP) {
+                    goto done;
+                }
+
+                /* renormalize coefficients */
+                if (std::abs(pk) > big) {
+                    pkm2 /= big;
+                    pkm1 /= big;
+                    qkm2 /= big;
+                    qkm1 /= big;
+                }
+            } while (t > MACHEP);
+
+        done:
+            if (ans == 0)
+                ans = 1.0;
+
+            /* Change n to n-1 if n < 0 and the continued fraction is small */
+            if (nflag > 0) {
+                if (std::abs(ans) < 0.125) {
+                    nflag = -1;
+                    *n = *n - 1.0;
+                    goto fstart;
+                }
+            }
+
+            kf = *newn;
+
+            /* backward recurrence
+             *              2k
+             *  J   (x)  =  --- J (x)  -  J   (x)
+             *   k-1         x   k         k+1
+             */
+
+            pk = 1.0;
+            pkm1 = 1.0 / ans;
+            k = *n - 1.0;
+            r = 2 * k;
+            do {
+                pkm2 = (pkm1 * r - pk * x) / x;
+                /*      pkp1 = pk; */
+                pk = pkm1;
+                pkm1 = pkm2;
+                r -= 2.0;
+                /*
+                 * t = fabs(pkp1) + fabs(pk);
+                 * if( (k > (kf + 2.5)) && (fabs(pkm1) < 0.25*t) )
+                 * {
+                 * k -= 1.0;
+                 * t = x*x;
+                 * pkm2 = ( (r*(r+2.0)-t)*pk - r*x*pkp1 )/t;
+                 * pkp1 = pk;
+                 * pk = pkm1;
+                 * pkm1 = pkm2;
+                 * r -= 2.0;
+                 * }
+                 */
+                k -= 1.0;
+            } while (k > (kf + 0.5));
+
+            /* Take the larger of the last two iterates
+             * on the theory that it may have less cancellation error.
+             */
+
+            if (cancel) {
+                if ((kf >= 0.0) && (std::abs(pk) > std::abs(pkm1))) {
+                    k += 1.0;
+                    pkm2 = pk;
+                }
+            }
+            *newn = k;
+            return (pkm2);
+        }
+
+        /* Ascending power series for Jv(x).
+         * AMS55 #9.1.10.
+         */
+
+        XSF_HOST_DEVICE inline double jv_jvs(double n, double x) {
+            double t, u, y, z, k;
+            int ex, sgngam;
+
+            z = -x * x / 4.0;
+            u = 1.0;
+            y = u;
+            k = 1.0;
+            t = 1.0;
+
+            while (t > MACHEP) {
+                u *= z / (k * (n + k));
+                y += u;
+                k += 1.0;
+                if (y != 0)
+                    t = std::abs(u / y);
+            }
+            t = std::frexp(0.5 * x, &ex);
+            ex = ex * n;
+            if ((ex > -1023) && (ex < 1023) && (n > 0.0) && (n < (MAXGAM - 1.0))) {
+                t = std::pow(0.5 * x, n) * xsf::cephes::rgamma(n + 1.0);
+                y *= t;
+            } else {
+                t = n * std::log(0.5 * x) - lgam_sgn(n + 1.0, &sgngam);
+                if (y < 0) {
+                    sgngam = -sgngam;
+                    y = -y;
+                }
+                t += std::log(y);
+                if (t < -MAXLOG) {
+                    return (0.0);
+                }
+                if (t > MAXLOG) {
+                    set_error("Jv", SF_ERROR_OVERFLOW, NULL);
+                    return (std::numeric_limits::infinity());
+                }
+                y = sgngam * std::exp(t);
+            }
+            return (y);
+        }
+
+        /* Hankel's asymptotic expansion
+         * for large x.
+         * AMS55 #9.2.5.
+         */
+
+        XSF_HOST_DEVICE inline double jv_hankel(double n, double x) {
+            double t, u, z, k, sign, conv;
+            double p, q, j, m, pp, qq;
+            int flag;
+
+            m = 4.0 * n * n;
+            j = 1.0;
+            z = 8.0 * x;
+            k = 1.0;
+            p = 1.0;
+            u = (m - 1.0) / z;
+            q = u;
+            sign = 1.0;
+            conv = 1.0;
+            flag = 0;
+            t = 1.0;
+            pp = 1.0e38;
+            qq = 1.0e38;
+
+            while (t > MACHEP) {
+                k += 2.0;
+                j += 1.0;
+                sign = -sign;
+                u *= (m - k * k) / (j * z);
+                p += sign * u;
+                k += 2.0;
+                j += 1.0;
+                u *= (m - k * k) / (j * z);
+                q += sign * u;
+                t = std::abs(u / p);
+                if (t < conv) {
+                    conv = t;
+                    qq = q;
+                    pp = p;
+                    flag = 1;
+                }
+                /* stop if the terms start getting larger */
+                if ((flag != 0) && (t > conv)) {
+                    goto hank1;
+                }
+            }
+
+        hank1:
+            u = x - (0.5 * n + 0.25) * M_PI;
+            t = std::sqrt(2.0 / (M_PI * x)) * (pp * std::cos(u) - qq * std::sin(u));
+            return (t);
+        }
+
+        /* Asymptotic expansion for transition region,
+         * n large and x close to n.
+         * AMS55 #9.3.23.
+         */
+
+        constexpr double jv_PF2[] = {-9.0000000000000000000e-2, 8.5714285714285714286e-2};
+
+        constexpr double jv_PF3[] = {1.3671428571428571429e-1, -5.4920634920634920635e-2, -4.4444444444444444444e-3};
+
+        constexpr double jv_PF4[] = {1.3500000000000000000e-3, -1.6036054421768707483e-1, 4.2590187590187590188e-2,
+                                     2.7330447330447330447e-3};
+
+        constexpr double jv_PG1[] = {-2.4285714285714285714e-1, 1.4285714285714285714e-2};
+
+        constexpr double jv_PG2[] = {-9.0000000000000000000e-3, 1.9396825396825396825e-1, -1.1746031746031746032e-2};
+
+        constexpr double jv_PG3[] = {1.9607142857142857143e-2, -1.5983694083694083694e-1, 6.3838383838383838384e-3};
+
+        XSF_HOST_DEVICE inline double jv_jnt(double n, double x) {
+            double z, zz, z3;
+            double cbn, n23, cbtwo;
+            double ai, aip, bi, bip; /* Airy functions */
+            double nk, fk, gk, pp, qq;
+            double F[5], G[4];
+            int k;
+
+            cbn = cbrt(n);
+            z = (x - n) / cbn;
+            cbtwo = cbrt(2.0);
+
+            /* Airy function */
+            zz = -cbtwo * z;
+            xsf::cephes::airy(zz, &ai, &aip, &bi, &bip);
+
+            /* polynomials in expansion */
+            zz = z * z;
+            z3 = zz * z;
+            F[0] = 1.0;
+            F[1] = -z / 5.0;
+            F[2] = xsf::cephes::polevl(z3, jv_PF2, 1) * zz;
+            F[3] = xsf::cephes::polevl(z3, jv_PF3, 2);
+            F[4] = xsf::cephes::polevl(z3, jv_PF4, 3) * z;
+            G[0] = 0.3 * zz;
+            G[1] = xsf::cephes::polevl(z3, jv_PG1, 1);
+            G[2] = xsf::cephes::polevl(z3, jv_PG2, 2) * z;
+            G[3] = xsf::cephes::polevl(z3, jv_PG3, 2) * zz;
+
+            pp = 0.0;
+            qq = 0.0;
+            nk = 1.0;
+            n23 = cbrt(n * n);
+
+            for (k = 0; k <= 4; k++) {
+                fk = F[k] * nk;
+                pp += fk;
+                if (k != 4) {
+                    gk = G[k] * nk;
+                    qq += gk;
+                }
+                nk /= n23;
+            }
+
+            fk = cbtwo * ai * pp / cbn + cbrt(4.0) * aip * qq / n;
+            return (fk);
+        }
+
+        /* Asymptotic expansion for large n.
+         * AMS55 #9.3.35.
+         */
+
+        constexpr double jv_lambda[] = {1.0,
+                                        1.041666666666666666666667E-1,
+                                        8.355034722222222222222222E-2,
+                                        1.282265745563271604938272E-1,
+                                        2.918490264641404642489712E-1,
+                                        8.816272674437576524187671E-1,
+                                        3.321408281862767544702647E+0,
+                                        1.499576298686255465867237E+1,
+                                        7.892301301158651813848139E+1,
+                                        4.744515388682643231611949E+2,
+                                        3.207490090890661934704328E+3};
+
+        constexpr double jv_mu[] = {1.0,
+                                    -1.458333333333333333333333E-1,
+                                    -9.874131944444444444444444E-2,
+                                    -1.433120539158950617283951E-1,
+                                    -3.172272026784135480967078E-1,
+                                    -9.424291479571202491373028E-1,
+                                    -3.511203040826354261542798E+0,
+                                    -1.572726362036804512982712E+1,
+                                    -8.228143909718594444224656E+1,
+                                    -4.923553705236705240352022E+2,
+                                    -3.316218568547972508762102E+3};
+
+        constexpr double jv_P1[] = {-2.083333333333333333333333E-1, 1.250000000000000000000000E-1};
+
+        constexpr double jv_P2[] = {3.342013888888888888888889E-1, -4.010416666666666666666667E-1,
+                                    7.031250000000000000000000E-2};
+
+        constexpr double jv_P3[] = {-1.025812596450617283950617E+0, 1.846462673611111111111111E+0,
+                                    -8.912109375000000000000000E-1, 7.324218750000000000000000E-2};
+
+        constexpr double jv_P4[] = {4.669584423426247427983539E+0, -1.120700261622299382716049E+1,
+                                    8.789123535156250000000000E+0, -2.364086914062500000000000E+0,
+                                    1.121520996093750000000000E-1};
+
+        constexpr double jv_P5[] = {-2.8212072558200244877E1, 8.4636217674600734632E1,  -9.1818241543240017361E1,
+                                    4.2534998745388454861E1,  -7.3687943594796316964E0, 2.27108001708984375E-1};
+
+        constexpr double jv_P6[] = {2.1257013003921712286E2,  -7.6525246814118164230E2, 1.0599904525279998779E3,
+                                    -6.9957962737613254123E2, 2.1819051174421159048E2,  -2.6491430486951555525E1,
+                                    5.7250142097473144531E-1};
+
+        constexpr double jv_P7[] = {-1.9194576623184069963E3, 8.0617221817373093845E3,  -1.3586550006434137439E4,
+                                    1.1655393336864533248E4,  -5.3056469786134031084E3, 1.2009029132163524628E3,
+                                    -1.0809091978839465550E2, 1.7277275025844573975E0};
+
+        XSF_HOST_DEVICE inline double jv_jnx(double n, double x) {
+            double zeta, sqz, zz, zp, np;
+            double cbn, n23, t, z, sz;
+            double pp, qq, z32i, zzi;
+            double ak, bk, akl, bkl;
+            int sign, doa, dob, nflg, k, s, tk, tkp1, m;
+            double u[8];
+            double ai, aip, bi, bip;
+
+            /* Test for x very close to n. Use expansion for transition region if so. */
+            cbn = cbrt(n);
+            z = (x - n) / cbn;
+            if (std::abs(z) <= 0.7) {
+                return (jv_jnt(n, x));
+            }
+
+            z = x / n;
+            zz = 1.0 - z * z;
+            if (zz == 0.0) {
+                return (0.0);
+            }
+
+            if (zz > 0.0) {
+                sz = std::sqrt(zz);
+                t = 1.5 * (std::log((1.0 + sz) / z) - sz); /* zeta ** 3/2          */
+                zeta = cbrt(t * t);
+                nflg = 1;
+            } else {
+                sz = std::sqrt(-zz);
+                t = 1.5 * (sz - std::acos(1.0 / z));
+                zeta = -cbrt(t * t);
+                nflg = -1;
+            }
+            z32i = std::abs(1.0 / t);
+            sqz = cbrt(t);
+
+            /* Airy function */
+            n23 = cbrt(n * n);
+            t = n23 * zeta;
+
+            xsf::cephes::airy(t, &ai, &aip, &bi, &bip);
+
+            /* polynomials in expansion */
+            u[0] = 1.0;
+            zzi = 1.0 / zz;
+            u[1] = xsf::cephes::polevl(zzi, jv_P1, 1) / sz;
+            u[2] = xsf::cephes::polevl(zzi, jv_P2, 2) / zz;
+            u[3] = xsf::cephes::polevl(zzi, jv_P3, 3) / (sz * zz);
+            pp = zz * zz;
+            u[4] = xsf::cephes::polevl(zzi, jv_P4, 4) / pp;
+            u[5] = xsf::cephes::polevl(zzi, jv_P5, 5) / (pp * sz);
+            pp *= zz;
+            u[6] = xsf::cephes::polevl(zzi, jv_P6, 6) / pp;
+            u[7] = xsf::cephes::polevl(zzi, jv_P7, 7) / (pp * sz);
+
+            pp = 0.0;
+            qq = 0.0;
+            np = 1.0;
+            /* flags to stop when terms get larger */
+            doa = 1;
+            dob = 1;
+            akl = std::numeric_limits::infinity();
+            bkl = std::numeric_limits::infinity();
+
+            for (k = 0; k <= 3; k++) {
+                tk = 2 * k;
+                tkp1 = tk + 1;
+                zp = 1.0;
+                ak = 0.0;
+                bk = 0.0;
+                for (s = 0; s <= tk; s++) {
+                    if (doa) {
+                        if ((s & 3) > 1)
+                            sign = nflg;
+                        else
+                            sign = 1;
+                        ak += sign * jv_mu[s] * zp * u[tk - s];
+                    }
+
+                    if (dob) {
+                        m = tkp1 - s;
+                        if (((m + 1) & 3) > 1)
+                            sign = nflg;
+                        else
+                            sign = 1;
+                        bk += sign * jv_lambda[s] * zp * u[m];
+                    }
+                    zp *= z32i;
+                }
+
+                if (doa) {
+                    ak *= np;
+                    t = std::abs(ak);
+                    if (t < akl) {
+                        akl = t;
+                        pp += ak;
+                    } else
+                        doa = 0;
+                }
+
+                if (dob) {
+                    bk += jv_lambda[tkp1] * zp * u[0];
+                    bk *= -np / sqz;
+                    t = std::abs(bk);
+                    if (t < bkl) {
+                        bkl = t;
+                        qq += bk;
+                    } else
+                        dob = 0;
+                }
+                if (np < MACHEP)
+                    break;
+                np /= n * n;
+            }
+
+            /* normalizing factor ( 4*zeta/(1 - z**2) )**1/4    */
+            t = 4.0 * zeta / zz;
+            t = sqrt(sqrt(t));
+
+            t *= ai * pp / cbrt(n) + aip * qq / (n23 * n);
+            return (t);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double jv(double n, double x) {
+        double k, q, t, y, an;
+        int i, sign, nint;
+
+        nint = 0; /* Flag for integer n */
+        sign = 1; /* Flag for sign inversion */
+        an = std::abs(n);
+        y = std::floor(an);
+        if (y == an) {
+            nint = 1;
+            i = an - 16384.0 * std::floor(an / 16384.0);
+            if (n < 0.0) {
+                if (i & 1)
+                    sign = -sign;
+                n = an;
+            }
+            if (x < 0.0) {
+                if (i & 1)
+                    sign = -sign;
+                x = -x;
+            }
+            if (n == 0.0)
+                return (j0(x));
+            if (n == 1.0)
+                return (sign * j1(x));
+        }
+
+        if ((x < 0.0) && (y != an)) {
+            set_error("Jv", SF_ERROR_DOMAIN, NULL);
+            y = std::numeric_limits::quiet_NaN();
+            goto done;
+        }
+
+        if (x == 0 && n < 0 && !nint) {
+            set_error("Jv", SF_ERROR_OVERFLOW, NULL);
+            return std::numeric_limits::infinity() * rgamma(n + 1);
+        }
+
+        y = std::abs(x);
+
+        if (y * y < std::abs(n + 1) * detail::MACHEP) {
+            return std::pow(0.5 * x, n) * rgamma(n + 1);
+        }
+
+        k = 3.6 * std::sqrt(y);
+        t = 3.6 * std::sqrt(an);
+        if ((y < t) && (an > 21.0)) {
+            return (sign * detail::jv_jvs(n, x));
+        }
+        if ((an < k) && (y > 21.0))
+            return (sign * detail::jv_hankel(n, x));
+
+        if (an < 500.0) {
+            /* Note: if x is too large, the continued fraction will fail; but then the
+             * Hankel expansion can be used. */
+            if (nint != 0) {
+                k = 0.0;
+                q = detail::jv_recur(&n, x, &k, 1);
+                if (k == 0.0) {
+                    y = j0(x) / q;
+                    goto done;
+                }
+                if (k == 1.0) {
+                    y = j1(x) / q;
+                    goto done;
+                }
+            }
+
+            if (an > 2.0 * y)
+                goto rlarger;
+
+            if ((n >= 0.0) && (n < 20.0) && (y > 6.0) && (y < 20.0)) {
+                /* Recur backwards from a larger value of n */
+            rlarger:
+                k = n;
+
+                y = y + an + 1.0;
+                if (y < 30.0)
+                    y = 30.0;
+                y = n + std::floor(y - n);
+                q = detail::jv_recur(&y, x, &k, 0);
+                y = detail::jv_jvs(y, x) * q;
+                goto done;
+            }
+
+            if (k <= 30.0) {
+                k = 2.0;
+            } else if (k < 90.0) {
+                k = (3 * k) / 4;
+            }
+            if (an > (k + 3.0)) {
+                if (n < 0.0) {
+                    k = -k;
+                }
+                q = n - std::floor(n);
+                k = std::floor(k) + q;
+                if (n > 0.0) {
+                    q = detail::jv_recur(&n, x, &k, 1);
+                } else {
+                    t = k;
+                    k = n;
+                    q = detail::jv_recur(&t, x, &k, 1);
+                    k = t;
+                }
+                if (q == 0.0) {
+                    y = 0.0;
+                    goto done;
+                }
+            } else {
+                k = n;
+                q = 1.0;
+            }
+
+            /* boundary between convergence of
+             * power series and Hankel expansion
+             */
+            y = std::abs(k);
+            if (y < 26.0)
+                t = (0.0083 * y + 0.09) * y + 12.9;
+            else
+                t = 0.9 * y;
+
+            if (x > t)
+                y = detail::jv_hankel(k, x);
+            else
+                y = detail::jv_jvs(k, x);
+            if (n > 0.0)
+                y /= q;
+            else
+                y *= q;
+        }
+
+        else {
+            /* For large n, use the uniform expansion or the transitional expansion.
+             * But if x is of the order of n**2, these may blow up, whereas the
+             * Hankel expansion will then work.
+             */
+            if (n < 0.0) {
+                set_error("jv", SF_ERROR_LOSS, NULL);
+                y = std::numeric_limits::quiet_NaN();
+                goto done;
+            }
+            t = x / n;
+            t /= n;
+            if (t > 0.3)
+                y = detail::jv_hankel(n, x);
+            else
+                y = detail::jv_jnx(n, x);
+        }
+
+    done:
+        return (sign * y);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h
new file mode 100644
index 0000000000000000000000000000000000000000..f617b93c73009072498fe4f6f20671a9f83d84e1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k0.h
@@ -0,0 +1,164 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     k0.c
+ *
+ *     Modified Bessel function, third kind, order zero
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k0();
+ *
+ * y = k0( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of the third kind
+ * of order zero of the argument.
+ *
+ * The range is partitioned into the two intervals [0,8] and
+ * (8, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ * Tested at 2000 random points between 0 and 8.  Peak absolute
+ * error (relative when K0 > 1) was 1.46e-14; rms, 4.26e-15.
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.2e-15     1.6e-16
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ *  K0 domain          x <= 0          INFINITY
+ *
+ */
+/*							k0e()
+ *
+ *	Modified Bessel function, third kind, order zero,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k0e();
+ *
+ * y = k0e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of the third kind of order zero of the argument.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.4e-15     1.4e-16
+ * See k0().
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "chbevl.h"
+#include "i0.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        /* Chebyshev coefficients for K0(x) + log(x/2) I0(x)
+         * in the interval [0,2].  The odd order coefficients are all
+         * zero; only the even order coefficients are listed.
+         *
+         * lim(x->0){ K0(x) + log(x/2) I0(x) } = -EUL.
+         */
+
+        constexpr double k0_A[] = {1.37446543561352307156E-16, 4.25981614279661018399E-14, 1.03496952576338420167E-11,
+                                   1.90451637722020886025E-9,  2.53479107902614945675E-7,  2.28621210311945178607E-5,
+                                   1.26461541144692592338E-3,  3.59799365153615016266E-2,  3.44289899924628486886E-1,
+                                   -5.35327393233902768720E-1};
+
+        /* Chebyshev coefficients for exp(x) sqrt(x) K0(x)
+         * in the inverted interval [2,infinity].
+         *
+         * lim(x->inf){ exp(x) sqrt(x) K0(x) } = sqrt(pi/2).
+         */
+        constexpr double k0_B[] = {
+            5.30043377268626276149E-18,  -1.64758043015242134646E-17, 5.21039150503902756861E-17,
+            -1.67823109680541210385E-16, 5.51205597852431940784E-16,  -1.84859337734377901440E-15,
+            6.34007647740507060557E-15,  -2.22751332699166985548E-14, 8.03289077536357521100E-14,
+            -2.98009692317273043925E-13, 1.14034058820847496303E-12,  -4.51459788337394416547E-12,
+            1.85594911495471785253E-11,  -7.95748924447710747776E-11, 3.57739728140030116597E-10,
+            -1.69753450938905987466E-9,  8.57403401741422608519E-9,   -4.66048989768794782956E-8,
+            2.76681363944501510342E-7,   -1.83175552271911948767E-6,  1.39498137188764993662E-5,
+            -1.28495495816278026384E-4,  1.56988388573005337491E-3,   -3.14481013119645005427E-2,
+            2.44030308206595545468E0};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double k0(double x) {
+        double y, z;
+
+        if (x == 0.0) {
+            set_error("k0", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k0", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = chbevl(y, detail::k0_A, 10) - std::log(0.5 * x) * i0(x);
+            return (y);
+        }
+        z = 8.0 / x - 2.0;
+        y = std::exp(-x) * chbevl(z, detail::k0_B, 25) / std::sqrt(x);
+        return (y);
+    }
+
+    XSF_HOST_DEVICE double inline k0e(double x) {
+        double y;
+
+        if (x == 0.0) {
+            set_error("k0e", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k0e", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = chbevl(y, detail::k0_A, 10) - std::log(0.5 * x) * i0(x);
+            return (y * exp(x));
+        }
+
+        y = chbevl(8.0 / x - 2.0, detail::k0_B, 25) / std::sqrt(x);
+        return (y);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h
new file mode 100644
index 0000000000000000000000000000000000000000..96594fd9c345e6fd2ecf02a269601cd2d9592525
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/k1.h
@@ -0,0 +1,163 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     k1.c
+ *
+ *     Modified Bessel function, third kind, order one
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k1();
+ *
+ * y = k1( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Computes the modified Bessel function of the third kind
+ * of order one of the argument.
+ *
+ * The range is partitioned into the two intervals [0,2] and
+ * (2, infinity).  Chebyshev polynomial expansions are employed
+ * in each interval.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       1.2e-15     1.6e-16
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition      value returned
+ * k1 domain          x <= 0          INFINITY
+ *
+ */
+/*							k1e.c
+ *
+ *	Modified Bessel function, third kind, order one,
+ *	exponentially scaled
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, k1e();
+ *
+ * y = k1e( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns exponentially scaled modified Bessel function
+ * of the third kind of order one of the argument:
+ *
+ *      k1e(x) = exp(x) * k1(x).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0, 30       30000       7.8e-16     1.2e-16
+ * See k1().
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 2000 by Stephen L. Moshier
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "chbevl.h"
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        /* Chebyshev coefficients for x(K1(x) - log(x/2) I1(x))
+         * in the interval [0,2].
+         *
+         * lim(x->0){ x(K1(x) - log(x/2) I1(x)) } = 1.
+         */
+
+        constexpr double k1_A[] = {
+            -7.02386347938628759343E-18, -2.42744985051936593393E-15, -6.66690169419932900609E-13,
+            -1.41148839263352776110E-10, -2.21338763073472585583E-8,  -2.43340614156596823496E-6,
+            -1.73028895751305206302E-4,  -6.97572385963986435018E-3,  -1.22611180822657148235E-1,
+            -3.53155960776544875667E-1,  1.52530022733894777053E0};
+
+        /* Chebyshev coefficients for exp(x) sqrt(x) K1(x)
+         * in the interval [2,infinity].
+         *
+         * lim(x->inf){ exp(x) sqrt(x) K1(x) } = sqrt(pi/2).
+         */
+        constexpr double k1_B[] = {
+            -5.75674448366501715755E-18, 1.79405087314755922667E-17,  -5.68946255844285935196E-17,
+            1.83809354436663880070E-16,  -6.05704724837331885336E-16, 2.03870316562433424052E-15,
+            -7.01983709041831346144E-15, 2.47715442448130437068E-14,  -8.97670518232499435011E-14,
+            3.34841966607842919884E-13,  -1.28917396095102890680E-12, 5.13963967348173025100E-12,
+            -2.12996783842756842877E-11, 9.21831518760500529508E-11,  -4.19035475934189648750E-10,
+            2.01504975519703286596E-9,   -1.03457624656780970260E-8,  5.74108412545004946722E-8,
+            -3.50196060308781257119E-7,  2.40648494783721712015E-6,   -1.93619797416608296024E-5,
+            1.95215518471351631108E-4,   -2.85781685962277938680E-3,  1.03923736576817238437E-1,
+            2.72062619048444266945E0};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double k1(double x) {
+        double y, z;
+
+        if (x == 0.0) {
+            set_error("k1", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k1", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+        z = 0.5 * x;
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = std::log(z) * i1(x) + chbevl(y, detail::k1_A, 11) / x;
+            return (y);
+        }
+
+        return (std::exp(-x) * chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x));
+    }
+
+    XSF_HOST_DEVICE double k1e(double x) {
+        double y;
+
+        if (x == 0.0) {
+            set_error("k1e", SF_ERROR_SINGULAR, NULL);
+            return std::numeric_limits::infinity();
+        } else if (x < 0.0) {
+            set_error("k1e", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x <= 2.0) {
+            y = x * x - 2.0;
+            y = std::log(0.5 * x) * i1(x) + chbevl(y, detail::k1_A, 11) / x;
+            return (y * exp(x));
+        }
+
+        return (chbevl(8.0 / x - 2.0, detail::k1_B, 25) / std::sqrt(x));
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h
new file mode 100644
index 0000000000000000000000000000000000000000..31bc9fd7f735002f3381749f8d14c02545155c69
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/kn.h
@@ -0,0 +1,243 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     kn.c
+ *
+ *     Modified Bessel function, third kind, integer order
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, kn();
+ * int n;
+ *
+ * y = kn( n, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of the third kind
+ * of order n of the argument.
+ *
+ * The range is partitioned into the two intervals [0,9.55] and
+ * (9.55, infinity).  An ascending power series is used in the
+ * low range, and an asymptotic expansion in the high range.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        90000       1.8e-8      3.0e-10
+ *
+ *  Error is high only near the crossover point x = 9.55
+ * between the two expansions used.
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
+ */
+
+/*
+ * Algorithm for Kn.
+ *                        n-1
+ *                    -n   -  (n-k-1)!    2   k
+ * K (x)  =  0.5 (x/2)     >  -------- (-x /4)
+ *  n                      -     k!
+ *                        k=0
+ *
+ *                     inf.                                   2   k
+ *        n         n   -                                   (x /4)
+ *  + (-1)  0.5(x/2)    >  {p(k+1) + p(n+k+1) - 2log(x/2)} ---------
+ *                      -                                  k! (n+k)!
+ *                     k=0
+ *
+ * where  p(m) is the psi function: p(1) = -EUL and
+ *
+ *                       m-1
+ *                        -
+ *       p(m)  =  -EUL +  >  1/k
+ *                        -
+ *                       k=1
+ *
+ * For large x,
+ *                                          2        2     2
+ *                                       u-1     (u-1 )(u-3 )
+ * K (z)  =  sqrt(pi/2z) exp(-z) { 1 + ------- + ------------ + ...}
+ *  v                                        1            2
+ *                                     1! (8z)     2! (8z)
+ * asymptotically, where
+ *
+ *            2
+ *     u = 4 v .
+ *
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr int kn_MAXFAC = 31;
+
+    }
+
+    XSF_HOST_DEVICE inline double kn(int nn, double x) {
+        double k, kf, nk1f, nkf, zn, t, s, z0, z;
+        double ans, fn, pn, pk, zmn, tlg, tox;
+        int i, n;
+
+        if (nn < 0)
+            n = -nn;
+        else
+            n = nn;
+
+        if (n > detail::kn_MAXFAC) {
+        overf:
+            set_error("kn", SF_ERROR_OVERFLOW, NULL);
+            return (std::numeric_limits::infinity());
+        }
+
+        if (x <= 0.0) {
+            if (x < 0.0) {
+                set_error("kn", SF_ERROR_DOMAIN, NULL);
+                return std::numeric_limits::quiet_NaN();
+            } else {
+                set_error("kn", SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::infinity();
+            }
+        }
+
+        if (x > 9.55)
+            goto asymp;
+
+        ans = 0.0;
+        z0 = 0.25 * x * x;
+        fn = 1.0;
+        pn = 0.0;
+        zmn = 1.0;
+        tox = 2.0 / x;
+
+        if (n > 0) {
+            /* compute factorial of n and psi(n) */
+            pn = -detail::SCIPY_EULER;
+            k = 1.0;
+            for (i = 1; i < n; i++) {
+                pn += 1.0 / k;
+                k += 1.0;
+                fn *= k;
+            }
+
+            zmn = tox;
+
+            if (n == 1) {
+                ans = 1.0 / x;
+            } else {
+                nk1f = fn / n;
+                kf = 1.0;
+                s = nk1f;
+                z = -z0;
+                zn = 1.0;
+                for (i = 1; i < n; i++) {
+                    nk1f = nk1f / (n - i);
+                    kf = kf * i;
+                    zn *= z;
+                    t = nk1f * zn / kf;
+                    s += t;
+                    if ((std::numeric_limits::max() - std::abs(t)) < std::abs(s)) {
+                        goto overf;
+                    }
+                    if ((tox > 1.0) && ((std::numeric_limits::max() / tox) < zmn)) {
+                        goto overf;
+                    }
+                    zmn *= tox;
+                }
+                s *= 0.5;
+                t = std::abs(s);
+                if ((zmn > 1.0) && ((std::numeric_limits::max() / zmn) < t)) {
+                    goto overf;
+                }
+                if ((t > 1.0) && ((std::numeric_limits::max() / t) < zmn)) {
+                    goto overf;
+                }
+                ans = s * zmn;
+            }
+        }
+
+        tlg = 2.0 * log(0.5 * x);
+        pk = -detail::SCIPY_EULER;
+        if (n == 0) {
+            pn = pk;
+            t = 1.0;
+        } else {
+            pn = pn + 1.0 / n;
+            t = 1.0 / fn;
+        }
+        s = (pk + pn - tlg) * t;
+        k = 1.0;
+        do {
+            t *= z0 / (k * (k + n));
+            pk += 1.0 / k;
+            pn += 1.0 / (k + n);
+            s += (pk + pn - tlg) * t;
+            k += 1.0;
+        } while (fabs(t / s) > detail::MACHEP);
+
+        s = 0.5 * s / zmn;
+        if (n & 1) {
+            s = -s;
+        }
+        ans += s;
+
+        return (ans);
+
+        /* Asymptotic expansion for Kn(x) */
+        /* Converges to 1.4e-17 for x > 18.4 */
+
+    asymp:
+
+        if (x > detail::MAXLOG) {
+            set_error("kn", SF_ERROR_UNDERFLOW, NULL);
+            return (0.0);
+        }
+        k = n;
+        pn = 4.0 * k * k;
+        pk = 1.0;
+        z0 = 8.0 * x;
+        fn = 1.0;
+        t = 1.0;
+        s = t;
+        nkf = std::numeric_limits::infinity();
+        i = 0;
+        do {
+            z = pn - pk * pk;
+            t = t * z / (fn * z0);
+            nk1f = std::abs(t);
+            if ((i >= n) && (nk1f > nkf)) {
+                goto adone;
+            }
+            nkf = nk1f;
+            s += t;
+            fn += 1.0;
+            pk += 2.0;
+            i += 1;
+        } while (std::abs(t / s) > detail::MACHEP);
+
+    adone:
+        ans = std::exp(-x) * std::sqrt(M_PI / (2.0 * x)) * s;
+        return (ans);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h
new file mode 100644
index 0000000000000000000000000000000000000000..a8cbbe1d693f99e96d74cd40a1a15e32b8035871
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/lanczos.h
@@ -0,0 +1,112 @@
+/*  (C) Copyright John Maddock 2006.
+ *  Use, modification and distribution are subject to the
+ *  Boost Software License, Version 1.0. (See accompanying file
+ *  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
+ */
+
+/* Both lanczos.h and lanczos.c were formed from Boost's lanczos.hpp
+ *
+ * Scipy changes:
+ * - 06-22-2016: Removed all code not related to double precision and
+ *   ported to c for use in Cephes. Note that the order of the
+ *   coefficients is reversed to match the behavior of polevl.
+ */
+
+/*
+ * Optimal values for G for each N are taken from
+ * https://web.viu.ca/pughg/phdThesis/phdThesis.pdf,
+ * as are the theoretical error bounds.
+ *
+ * Constants calculated using the method described by Godfrey
+ * https://my.fit.edu/~gabdo/gamma.txt and elaborated by Toth at
+ * https://www.rskey.org/gamma.htm using NTL::RR at 1000 bit precision.
+ */
+
+/*
+ * Lanczos Coefficients for N=13 G=6.024680040776729583740234375
+ * Max experimental error (with arbitrary precision arithmetic) 1.196214e-17
+ * Generated with compiler: Microsoft Visual C++ version 8.0 on Win32 at Mar 23 2006
+ *
+ * Use for double precision.
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double lanczos_num[] = {
+            2.506628274631000270164908177133837338626, 210.8242777515793458725097339207133627117,
+            8071.672002365816210638002902272250613822, 186056.2653952234950402949897160456992822,
+            2876370.628935372441225409051620849613599, 31426415.58540019438061423162831820536287,
+            248874557.8620541565114603864132294232163, 1439720407.311721673663223072794912393972,
+            6039542586.35202800506429164430729792107,  17921034426.03720969991975575445893111267,
+            35711959237.35566804944018545154716670596, 42919803642.64909876895789904700198885093,
+            23531376880.41075968857200767445163675473};
+
+        constexpr double lanczos_denom[] = {1,        66,        1925,      32670,     357423,   2637558, 13339535,
+                                            45995730, 105258076, 150917976, 120543840, 39916800, 0};
+
+        constexpr double lanczos_sum_expg_scaled_num[] = {
+            0.006061842346248906525783753964555936883222, 0.5098416655656676188125178644804694509993,
+            19.51992788247617482847860966235652136208,    449.9445569063168119446858607650988409623,
+            6955.999602515376140356310115515198987526,    75999.29304014542649875303443598909137092,
+            601859.6171681098786670226533699352302507,    3481712.15498064590882071018964774556468,
+            14605578.08768506808414169982791359218571,    43338889.32467613834773723740590533316085,
+            86363131.28813859145546927288977868422342,    103794043.1163445451906271053616070238554,
+            56906521.91347156388090791033559122686859};
+
+        constexpr double lanczos_sum_expg_scaled_denom[] = {
+            1, 66, 1925, 32670, 357423, 2637558, 13339535, 45995730, 105258076, 150917976, 120543840, 39916800, 0};
+
+        constexpr double lanczos_sum_near_1_d[] = {
+            0.3394643171893132535170101292240837927725e-9,  -0.2499505151487868335680273909354071938387e-8,
+            0.8690926181038057039526127422002498960172e-8,  -0.1933117898880828348692541394841204288047e-7,
+            0.3075580174791348492737947340039992829546e-7,  -0.2752907702903126466004207345038327818713e-7,
+            -0.1515973019871092388943437623825208095123e-5, 0.004785200610085071473880915854204301886437,
+            -0.1993758927614728757314233026257810172008,    1.483082862367253753040442933770164111678,
+            -3.327150580651624233553677113928873034916,     2.208709979316623790862569924861841433016};
+
+        constexpr double lanczos_sum_near_2_d[] = {
+            0.1009141566987569892221439918230042368112e-8,  -0.7430396708998719707642735577238449585822e-8,
+            0.2583592566524439230844378948704262291927e-7,  -0.5746670642147041587497159649318454348117e-7,
+            0.9142922068165324132060550591210267992072e-7,  -0.8183698410724358930823737982119474130069e-7,
+            -0.4506604409707170077136555010018549819192e-5, 0.01422519127192419234315002746252160965831,
+            -0.5926941084905061794445733628891024027949,    4.408830289125943377923077727900630927902,
+            -9.8907772644920670589288081640128194231,       6.565936202082889535528455955485877361223};
+
+        XSF_HOST_DEVICE double lanczos_sum(double x) { return ratevl(x, lanczos_num, 12, lanczos_denom, 12); }
+
+        XSF_HOST_DEVICE double lanczos_sum_near_1(double dx) {
+            double result = 0;
+            unsigned k;
+
+            for (k = 1; k <= 12; ++k) {
+                result += (-lanczos_sum_near_1_d[k - 1] * dx) / (k * dx + k * k);
+            }
+            return result;
+        }
+
+        XSF_HOST_DEVICE double lanczos_sum_near_2(double dx) {
+            double result = 0;
+            double x = dx + 2;
+            unsigned k;
+
+            for (k = 1; k <= 12; ++k) {
+                result += (-lanczos_sum_near_2_d[k - 1] * dx) / (x + k * x + k * k - 1);
+            }
+            return result;
+        }
+    } // namespace detail
+
+    constexpr double lanczos_g = 6.024680040776729583740234375;
+    XSF_HOST_DEVICE double lanczos_sum_expg_scaled(double x) {
+        return ratevl(x, detail::lanczos_sum_expg_scaled_num, 12, detail::lanczos_sum_expg_scaled_denom, 12);
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h
new file mode 100644
index 0000000000000000000000000000000000000000..a3611d26ba44a78ab69736f9c69fe5dd4d2bc538
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/ndtr.h
@@ -0,0 +1,275 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     ndtr.c
+ *
+ *     Normal distribution function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, ndtr();
+ *
+ * y = ndtr( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the area under the Gaussian probability density
+ * function, integrated from minus infinity to x:
+ *
+ *                            x
+ *                             -
+ *                   1        | |          2
+ *    ndtr(x)  = ---------    |    exp( - t /2 ) dt
+ *               sqrt(2pi)  | |
+ *                           -
+ *                          -inf.
+ *
+ *             =  ( 1 + erf(z) ) / 2
+ *             =  erfc(z) / 2
+ *
+ * where z = x/sqrt(2). Computation is via the functions
+ * erf and erfc.
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -13,0        30000       3.4e-14     6.7e-15
+ *
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition         value returned
+ * erfc underflow    x > 37.519379347       0.0
+ *
+ */
+/*							erf.c
+ *
+ *	Error function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, erf();
+ *
+ * y = erf( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * The integral is
+ *
+ *                           x
+ *                            -
+ *                 2         | |          2
+ *   erf(x)  =  --------     |    exp( - t  ) dt.
+ *              sqrt(pi)   | |
+ *                          -
+ *                           0
+ *
+ * For 0 <= |x| < 1, erf(x) = x * P4(x**2)/Q5(x**2); otherwise
+ * erf(x) = 1 - erfc(x).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,1         30000       3.7e-16     1.0e-16
+ *
+ */
+/*							erfc.c
+ *
+ *	Complementary error function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, erfc();
+ *
+ * y = erfc( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ *
+ *  1 - erf(x) =
+ *
+ *                           inf.
+ *                             -
+ *                  2         | |          2
+ *   erfc(x)  =  --------     |    exp( - t  ) dt
+ *               sqrt(pi)   | |
+ *                           -
+ *                            x
+ *
+ *
+ * For small x, erfc(x) = 1 - erf(x); otherwise rational
+ * approximations are computed.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,26.6417   30000       5.7e-14     1.5e-14
+ */
+
+/*
+ * Cephes Math Library Release 2.2:  June, 1992
+ * Copyright 1984, 1987, 1988, 1992 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double ndtr_P[] = {2.46196981473530512524E-10, 5.64189564831068821977E-1, 7.46321056442269912687E0,
+                                     4.86371970985681366614E1,   1.96520832956077098242E2,  5.26445194995477358631E2,
+                                     9.34528527171957607540E2,   1.02755188689515710272E3,  5.57535335369399327526E2};
+
+        constexpr double ndtr_Q[] = {
+            /* 1.00000000000000000000E0, */
+            1.32281951154744992508E1, 8.67072140885989742329E1, 3.54937778887819891062E2, 9.75708501743205489753E2,
+            1.82390916687909736289E3, 2.24633760818710981792E3, 1.65666309194161350182E3, 5.57535340817727675546E2};
+
+        constexpr double ndtr_R[] = {5.64189583547755073984E-1, 1.27536670759978104416E0, 5.01905042251180477414E0,
+                                     6.16021097993053585195E0,  7.40974269950448939160E0, 2.97886665372100240670E0};
+
+        constexpr double ndtr_S[] = {
+            /* 1.00000000000000000000E0, */
+            2.26052863220117276590E0, 9.39603524938001434673E0, 1.20489539808096656605E1,
+            1.70814450747565897222E1, 9.60896809063285878198E0, 3.36907645100081516050E0};
+
+        constexpr double ndtr_T[] = {9.60497373987051638749E0, 9.00260197203842689217E1, 2.23200534594684319226E3,
+                                     7.00332514112805075473E3, 5.55923013010394962768E4};
+
+        constexpr double ndtr_U[] = {
+            /* 1.00000000000000000000E0, */
+            3.35617141647503099647E1, 5.21357949780152679795E2, 4.59432382970980127987E3, 2.26290000613890934246E4,
+            4.92673942608635921086E4};
+
+        constexpr double ndtri_UTHRESH = 37.519379347;
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double erf(double x);
+
+    XSF_HOST_DEVICE inline double erfc(double a) {
+        double p, q, x, y, z;
+
+        if (std::isnan(a)) {
+            set_error("erfc", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (a < 0.0) {
+            x = -a;
+        } else {
+            x = a;
+        }
+
+        if (x < 1.0) {
+            return 1.0 - erf(a);
+        }
+
+        z = -a * a;
+
+        if (z < -detail::MAXLOG) {
+            goto under;
+        }
+
+        z = std::exp(z);
+
+        if (x < 8.0) {
+            p = polevl(x, detail::ndtr_P, 8);
+            q = p1evl(x, detail::ndtr_Q, 8);
+        } else {
+            p = polevl(x, detail::ndtr_R, 5);
+            q = p1evl(x, detail::ndtr_S, 6);
+        }
+        y = (z * p) / q;
+
+        if (a < 0) {
+            y = 2.0 - y;
+        }
+
+        if (y != 0.0) {
+            return y;
+        }
+
+    under:
+        set_error("erfc", SF_ERROR_UNDERFLOW, NULL);
+        if (a < 0) {
+            return 2.0;
+        } else {
+            return 0.0;
+        }
+    }
+
+    XSF_HOST_DEVICE inline double erf(double x) {
+        double y, z;
+
+        if (std::isnan(x)) {
+            set_error("erf", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        if (x < 0.0) {
+            return -erf(-x);
+        }
+
+        if (std::abs(x) > 1.0) {
+            return (1.0 - erfc(x));
+        }
+        z = x * x;
+
+        y = x * polevl(z, detail::ndtr_T, 4) / p1evl(z, detail::ndtr_U, 5);
+        return y;
+    }
+
+    XSF_HOST_DEVICE inline double ndtr(double a) {
+        double x, y, z;
+
+        if (std::isnan(a)) {
+            set_error("ndtr", SF_ERROR_DOMAIN, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        x = a * M_SQRT1_2;
+        z = std::abs(x);
+
+        if (z < 1.0) {
+            y = 0.5 + 0.5 * erf(x);
+        } else {
+            y = 0.5 * erfc(z);
+            if (x > 0) {
+                y = 1.0 - y;
+            }
+        }
+
+        return y;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h
new file mode 100644
index 0000000000000000000000000000000000000000..add3a995f38870cad5155b5fda1730e4fcbf1ee3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/poch.h
@@ -0,0 +1,85 @@
+/*
+ * Pochhammer symbol (a)_m = gamma(a + m) / gamma(a)
+ */
+
+#pragma once
+
+#include "../config.h"
+#include "gamma.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        XSF_HOST_DEVICE inline double is_nonpos_int(double x) {
+            return x <= 0 && x == std::ceil(x) && std::abs(x) < 1e13;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double poch(double a, double m) {
+        double r = 1.0;
+
+        /*
+         * 1. Reduce magnitude of `m` to |m| < 1 by using recurrence relations.
+         *
+         * This may end up in over/underflow, but then the function itself either
+         * diverges or goes to zero. In case the remainder goes to the opposite
+         * direction, we end up returning 0*INF = NAN, which is OK.
+         */
+
+        /* Recurse down */
+        while (m >= 1.0) {
+            if (a + m == 1) {
+                break;
+            }
+            m -= 1.0;
+            r *= (a + m);
+            if (!std::isfinite(r) || r == 0) {
+                break;
+            }
+        }
+
+        /* Recurse up */
+        while (m <= -1.0) {
+            if (a + m == 0) {
+                break;
+            }
+            r /= (a + m);
+            m += 1.0;
+            if (!std::isfinite(r) || r == 0) {
+                break;
+            }
+        }
+
+        /*
+         * 2. Evaluate function with reduced `m`
+         *
+         * Now either `m` is not big, or the `r` product has over/underflown.
+         * If so, the function itself does similarly.
+         */
+
+        if (m == 0) {
+            /* Easy case */
+            return r;
+        } else if (a > 1e4 && std::abs(m) <= 1) {
+            /* Avoid loss of precision */
+            return r * std::pow(a, m) *
+                   (1 + m * (m - 1) / (2 * a) + m * (m - 1) * (m - 2) * (3 * m - 1) / (24 * a * a) +
+                    m * m * (m - 1) * (m - 1) * (m - 2) * (m - 3) / (48 * a * a * a));
+        }
+
+        /* Check for infinity */
+        if (detail::is_nonpos_int(a + m) && !detail::is_nonpos_int(a) && a + m != m) {
+            return std::numeric_limits::infinity();
+        }
+
+        /* Check for zero */
+        if (!detail::is_nonpos_int(a + m) && detail::is_nonpos_int(a)) {
+            return 0;
+        }
+
+        return r * std::exp(lgam(a + m) - lgam(a)) * gammasgn(a + m) * gammasgn(a);
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h
new file mode 100644
index 0000000000000000000000000000000000000000..912a506cfb6c0d5fe75ead2d14576ddd57698788
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/polevl.h
@@ -0,0 +1,167 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     polevl.c
+ *                                                     p1evl.c
+ *
+ *     Evaluate polynomial
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * int N;
+ * double x, y, coef[N+1], polevl[];
+ *
+ * y = polevl( x, coef, N );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates polynomial of degree N:
+ *
+ *                     2          N
+ * y  =  C  + C x + C x  +...+ C x
+ *        0    1     2          N
+ *
+ * Coefficients are stored in reverse order:
+ *
+ * coef[0] = C  , ..., coef[N] = C  .
+ *            N                   0
+ *
+ * The function p1evl() assumes that c_N = 1.0 so that coefficent
+ * is omitted from the array.  Its calling arguments are
+ * otherwise the same as polevl().
+ *
+ *
+ * SPEED:
+ *
+ * In the interest of speed, there are no checks for out
+ * of bounds arithmetic.  This routine is used by most of
+ * the functions in the library.  Depending on available
+ * equipment features, the user may wish to rewrite the
+ * program in microcode or assembly language.
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.1:  December, 1988
+ * Copyright 1984, 1987, 1988 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+
+/* Sources:
+ * [1] Holin et. al., "Polynomial and Rational Function Evaluation",
+ *     https://www.boost.org/doc/libs/1_61_0/libs/math/doc/html/math_toolkit/roots/rational.html
+ */
+
+/* Scipy changes:
+ * - 06-23-2016: add code for evaluating rational functions
+ */
+
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+    XSF_HOST_DEVICE inline double polevl(double x, const double coef[], int N) {
+        double ans;
+        int i;
+        const double *p;
+
+        p = coef;
+        ans = *p++;
+        i = N;
+
+        do {
+            ans = ans * x + *p++;
+        } while (--i);
+
+        return (ans);
+    }
+
+    /*                                                     p1evl() */
+    /*                                          N
+     * Evaluate polynomial when coefficient of x  is 1.0.
+     * That is, C_{N} is assumed to be 1, and that coefficient
+     * is not included in the input array coef.
+     * coef must have length N and contain the polynomial coefficients
+     * stored as
+     *     coef[0] = C_{N-1}
+     *     coef[1] = C_{N-2}
+     *          ...
+     *     coef[N-2] = C_1
+     *     coef[N-1] = C_0
+     * Otherwise same as polevl.
+     */
+
+    XSF_HOST_DEVICE inline double p1evl(double x, const double coef[], int N) {
+        double ans;
+        const double *p;
+        int i;
+
+        p = coef;
+        ans = x + *p++;
+        i = N - 1;
+
+        do
+            ans = ans * x + *p++;
+        while (--i);
+
+        return (ans);
+    }
+
+    /* Evaluate a rational function. See [1]. */
+
+    /* The function ratevl is only used once in cephes/lanczos.h. */
+    XSF_HOST_DEVICE inline double ratevl(double x, const double num[], int M, const double denom[], int N) {
+        int i, dir;
+        double y, num_ans, denom_ans;
+        double absx = std::abs(x);
+        const double *p;
+
+        if (absx > 1) {
+            /* Evaluate as a polynomial in 1/x. */
+            dir = -1;
+            p = num + M;
+            y = 1 / x;
+        } else {
+            dir = 1;
+            p = num;
+            y = x;
+        }
+
+        /* Evaluate the numerator */
+        num_ans = *p;
+        p += dir;
+        for (i = 1; i <= M; i++) {
+            num_ans = num_ans * y + *p;
+            p += dir;
+        }
+
+        /* Evaluate the denominator */
+        if (absx > 1) {
+            p = denom + N;
+        } else {
+            p = denom;
+        }
+
+        denom_ans = *p;
+        p += dir;
+        for (i = 1; i <= N; i++) {
+            denom_ans = denom_ans * y + *p;
+            p += dir;
+        }
+
+        if (absx > 1) {
+            i = M - N;
+            return std::pow(x, i) * num_ans / denom_ans;
+        } else {
+            return num_ans / denom_ans;
+        }
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h
new file mode 100644
index 0000000000000000000000000000000000000000..c028e9ea14e0066c3b8c13d2c26c2773e61f767a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/psi.h
@@ -0,0 +1,194 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     psi.c
+ *
+ *     Psi (digamma) function
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, psi();
+ *
+ * y = psi( x );
+ *
+ *
+ * DESCRIPTION:
+ *
+ *              d      -
+ *   psi(x)  =  -- ln | (x)
+ *              dx
+ *
+ * is the logarithmic derivative of the gamma function.
+ * For integer x,
+ *                   n-1
+ *                    -
+ * psi(n) = -EUL  +   >  1/k.
+ *                    -
+ *                   k=1
+ *
+ * This formula is used for 0 < n <= 10.  If x is negative, it
+ * is transformed to a positive argument by the reflection
+ * formula  psi(1-x) = psi(x) + pi cot(pi x).
+ * For general positive x, the argument is made greater than 10
+ * using the recurrence  psi(x+1) = psi(x) + 1/x.
+ * Then the following asymptotic expansion is applied:
+ *
+ *                           inf.   B
+ *                            -      2k
+ * psi(x) = log(x) - 1/2x -   >   -------
+ *                            -        2k
+ *                           k=1   2k x
+ *
+ * where the B2k are Bernoulli numbers.
+ *
+ * ACCURACY:
+ *    Relative error (except absolute when |psi| < 1):
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE      0,30        30000       1.3e-15     1.4e-16
+ *    IEEE      -30,0       40000       1.5e-15     2.2e-16
+ *
+ * ERROR MESSAGES:
+ *     message         condition      value returned
+ * psi singularity    x integer <=0      INFINITY
+ */
+
+/*
+ * Cephes Math Library Release 2.8:  June, 2000
+ * Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier
+ */
+
+/*
+ * Code for the rational approximation on [1, 2] is:
+ *
+ * (C) Copyright John Maddock 2006.
+ * Use, modification and distribution are subject to the
+ * Boost Software License, Version 1.0. (See accompanying file
+ * LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+    namespace detail {
+        constexpr double psi_A[] = {8.33333333333333333333E-2,  -2.10927960927960927961E-2, 7.57575757575757575758E-3,
+                                    -4.16666666666666666667E-3, 3.96825396825396825397E-3,  -8.33333333333333333333E-3,
+                                    8.33333333333333333333E-2};
+
+        constexpr float psi_Y = 0.99558162689208984f;
+
+        constexpr double psi_root1 = 1569415565.0 / 1073741824.0;
+        constexpr double psi_root2 = (381566830.0 / 1073741824.0) / 1073741824.0;
+        constexpr double psi_root3 = 0.9016312093258695918615325266959189453125e-19;
+
+        constexpr double psi_P[] = {-0.0020713321167745952, -0.045251321448739056, -0.28919126444774784,
+                                    -0.65031853770896507,   -0.32555031186804491,  0.25479851061131551};
+        constexpr double psi_Q[] = {-0.55789841321675513e-6,
+                                    0.0021284987017821144,
+                                    0.054151797245674225,
+                                    0.43593529692665969,
+                                    1.4606242909763515,
+                                    2.0767117023730469,
+                                    1.0};
+
+        XSF_HOST_DEVICE double digamma_imp_1_2(double x) {
+            /*
+             * Rational approximation on [1, 2] taken from Boost.
+             *
+             * Now for the approximation, we use the form:
+             *
+             * digamma(x) = (x - root) * (Y + R(x-1))
+             *
+             * Where root is the location of the positive root of digamma,
+             * Y is a constant, and R is optimised for low absolute error
+             * compared to Y.
+             *
+             * Maximum Deviation Found:               1.466e-18
+             * At double precision, max error found:  2.452e-17
+             */
+            double r, g;
+
+            g = x - psi_root1;
+            g -= psi_root2;
+            g -= psi_root3;
+            r = xsf::cephes::polevl(x - 1.0, psi_P, 5) / xsf::cephes::polevl(x - 1.0, psi_Q, 6);
+
+            return g * psi_Y + g * r;
+        }
+
+        XSF_HOST_DEVICE double psi_asy(double x) {
+            double y, z;
+
+            if (x < 1.0e17) {
+                z = 1.0 / (x * x);
+                y = z * xsf::cephes::polevl(z, psi_A, 6);
+            } else {
+                y = 0.0;
+            }
+
+            return std::log(x) - (0.5 / x) - y;
+        }
+    } // namespace detail
+
+    XSF_HOST_DEVICE double psi(double x) {
+        double y = 0.0;
+        double q, r;
+        int i, n;
+
+        if (std::isnan(x)) {
+            return x;
+        } else if (x == std::numeric_limits::infinity()) {
+            return x;
+        } else if (x == -std::numeric_limits::infinity()) {
+            return std::numeric_limits::quiet_NaN();
+        } else if (x == 0) {
+            set_error("psi", SF_ERROR_SINGULAR, NULL);
+            return std::copysign(std::numeric_limits::infinity(), -x);
+        } else if (x < 0.0) {
+            /* argument reduction before evaluating tan(pi * x) */
+            r = std::modf(x, &q);
+            if (r == 0.0) {
+                set_error("psi", SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::quiet_NaN();
+            }
+            y = -M_PI / std::tan(M_PI * r);
+            x = 1.0 - x;
+        }
+
+        /* check for positive integer up to 10 */
+        if ((x <= 10.0) && (x == std::floor(x))) {
+            n = static_cast(x);
+            for (i = 1; i < n; i++) {
+                y += 1.0 / i;
+            }
+            y -= detail::SCIPY_EULER;
+            return y;
+        }
+
+        /* use the recurrence relation to move x into [1, 2] */
+        if (x < 1.0) {
+            y -= 1.0 / x;
+            x += 1.0;
+        } else if (x < 10.0) {
+            while (x > 2.0) {
+                x -= 1.0;
+                y += 1.0 / x;
+            }
+        }
+        if ((1.0 <= x) && (x <= 2.0)) {
+            y += detail::digamma_imp_1_2(x);
+            return y;
+        }
+
+        /* x is large, use the asymptotic series */
+        y += detail::psi_asy(x);
+        return y;
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..97f29b33ab50abb01f4ee4b71d0f2fbc6ffd1858
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/rgamma.h
@@ -0,0 +1,111 @@
+/*                                             rgamma.c
+ *
+ *     Reciprocal Gamma function
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, rgamma();
+ *
+ * y = rgamma( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns one divided by the Gamma function of the argument.
+ *
+ * The function is approximated by a Chebyshev expansion in
+ * the interval [0,1].  Range reduction is by recurrence
+ * for arguments between -34.034 and +34.84425627277176174.
+ * 0 is returned for positive arguments outside this
+ * range.  For arguments less than -34.034 the cosecant
+ * reflection formula is applied; lograrithms are employed
+ * to avoid unnecessary overflow.
+ *
+ * The reciprocal Gamma function has no singularities,
+ * but overflow and underflow may occur for large arguments.
+ * These conditions return either INFINITY or 0 with
+ * appropriate sign.
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     -30,+30      30000       1.1e-15     2.0e-16
+ * For arguments less than -34.034 the peak error is on the
+ * order of 5e-15 (DEC), excepting overflow or underflow.
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "chbevl.h"
+#include "const.h"
+#include "gamma.h"
+#include "trig.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* Chebyshev coefficients for reciprocal Gamma function
+         * in interval 0 to 1.  Function is 1/(x Gamma(x)) - 1
+         */
+
+        constexpr double rgamma_R[] = {
+            3.13173458231230000000E-17, -6.70718606477908000000E-16, 2.20039078172259550000E-15,
+            2.47691630348254132600E-13, -6.60074100411295197440E-12, 5.13850186324226978840E-11,
+            1.08965386454418662084E-9,  -3.33964630686836942556E-8,  2.68975996440595483619E-7,
+            2.96001177518801696639E-6,  -8.04814124978471142852E-5,  4.16609138709688864714E-4,
+            5.06579864028608725080E-3,  -6.41925436109158228810E-2,  -4.98558728684003594785E-3,
+            1.27546015610523951063E-1};
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE double rgamma(double x) {
+        double w, y, z;
+
+	if (x == 0) {
+	    // This case is separate from below to get correct sign for zero.
+	    return x;
+	}
+
+	if (x < 0 && x == std::floor(x)) {
+	    // Gamma poles.
+	    return 0.0;
+	}
+
+	if (std::abs(x) > 4.0) {
+	    return 1.0 / Gamma(x);
+	}
+
+        z = 1.0;
+        w = x;
+
+        while (w > 1.0) { /* Downward recurrence */
+            w -= 1.0;
+            z *= w;
+        }
+        while (w < 0.0) { /* Upward recurrence */
+            z /= w;
+            w += 1.0;
+        }
+        if (w == 0.0) /* Nonpositive integer */
+            return (0.0);
+        if (w == 1.0) /* Other integer */
+            return (1.0 / z);
+
+        y = w * (1.0 + chbevl(4.0 * w - 2.0, detail::rgamma_R, 16)) / z;
+        return (y);
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h
new file mode 100644
index 0000000000000000000000000000000000000000..fe0c631e34582d32132afdf41e2e6904fda90c82
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/scipy_iv.h
@@ -0,0 +1,811 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     iv.c
+ *
+ *     Modified Bessel function of noninteger order
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double v, x, y, iv();
+ *
+ * y = iv( v, x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns modified Bessel function of order v of the
+ * argument.  If x is negative, v must be integer valued.
+ *
+ */
+/*                                                     iv.c    */
+/*     Modified Bessel function of noninteger order            */
+/* If x < 0, then v must be an integer. */
+
+/*
+ * Parts of the code are copyright:
+ *
+ *     Cephes Math Library Release 2.8:  June, 2000
+ *     Copyright 1984, 1987, 1988, 2000 by Stephen L. Moshier
+ *
+ * And other parts:
+ *
+ *     Copyright (c) 2006 Xiaogang Zhang
+ *     Use, modification and distribution are subject to the
+ *     Boost Software License, Version 1.0.
+ *
+ *     Boost Software License - Version 1.0 - August 17th, 2003
+ *
+ *     Permission is hereby granted, free of charge, to any person or
+ *     organization obtaining a copy of the software and accompanying
+ *     documentation covered by this license (the "Software") to use, reproduce,
+ *     display, distribute, execute, and transmit the Software, and to prepare
+ *     derivative works of the Software, and to permit third-parties to whom the
+ *     Software is furnished to do so, all subject to the following:
+ *
+ *     The copyright notices in the Software and this entire statement,
+ *     including the above license grant, this restriction and the following
+ *     disclaimer, must be included in all copies of the Software, in whole or
+ *     in part, and all derivative works of the Software, unless such copies or
+ *     derivative works are solely in the form of machine-executable object code
+ *     generated by a source language processor.
+ *
+ *     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ *     OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *     MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
+ *     NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
+ *     DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY,
+ *     WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ *     CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ *     SOFTWARE.
+ *
+ * And the rest are:
+ *
+ *     Copyright (C) 2009 Pauli Virtanen
+ *     Distributed under the same license as Scipy.
+ *
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "trig.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /*
+         * Compute Iv from (AMS5 9.7.1), asymptotic expansion for large |z|
+         * Iv ~ exp(x)/sqrt(2 pi x) ( 1 + (4*v*v-1)/8x + (4*v*v-1)(4*v*v-9)/8x/2! + ...)
+         */
+        XSF_HOST_DEVICE inline double iv_asymptotic(double v, double x) {
+            double mu;
+            double sum, term, prefactor, factor;
+            int k;
+
+            prefactor = std::exp(x) / std::sqrt(2 * M_PI * x);
+
+            if (prefactor == std::numeric_limits::infinity()) {
+                return prefactor;
+            }
+
+            mu = 4 * v * v;
+            sum = 1.0;
+            term = 1.0;
+            k = 1;
+
+            do {
+                factor = (mu - (2 * k - 1) * (2 * k - 1)) / (8 * x) / k;
+                if (k > 100) {
+                    /* didn't converge */
+                    set_error("iv(iv_asymptotic)", SF_ERROR_NO_RESULT, NULL);
+                    break;
+                }
+                term *= -factor;
+                sum += term;
+                ++k;
+            } while (std::abs(term) > MACHEP * std::abs(sum));
+            return sum * prefactor;
+        }
+
+        /*
+         * Uniform asymptotic expansion factors, (AMS5 9.3.9; AMS5 9.3.10)
+         *
+         * Computed with:
+         * --------------------
+         import numpy as np
+         t = np.poly1d([1,0])
+         def up1(p):
+         return .5*t*t*(1-t*t)*p.deriv() + 1/8. * ((1-5*t*t)*p).integ()
+         us = [np.poly1d([1])]
+         for k in range(10):
+         us.append(up1(us[-1]))
+         n = us[-1].order
+         for p in us:
+         print "{" + ", ".join(["0"]*(n-p.order) + map(repr, p)) + "},"
+         print "N_UFACTORS", len(us)
+         print "N_UFACTOR_TERMS", us[-1].order + 1
+         * --------------------
+         */
+        constexpr int iv_N_UFACTORS = 11;
+        constexpr int iv_N_UFACTOR_TERMS = 31;
+
+        constexpr double iv_asymptotic_ufactors[iv_N_UFACTORS][iv_N_UFACTOR_TERMS] = {
+            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
+            {0,   0,     0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+             0,   0,     0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.20833333333333334,
+             0.0, 0.125, 0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0.3342013888888889,
+             0.0,
+             -0.40104166666666669,
+             0.0,
+             0.0703125,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   -1.0258125964506173,
+             0.0, 1.8464626736111112,
+             0.0, -0.89121093750000002,
+             0.0, 0.0732421875,
+             0.0, 0.0,
+             0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             4.6695844234262474,
+             0.0,
+             -11.207002616222995,
+             0.0,
+             8.78912353515625,
+             0.0,
+             -2.3640869140624998,
+             0.0,
+             0.112152099609375,
+             0.0,
+             0.0,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   -28.212072558200244,
+             0.0, 84.636217674600744,
+             0.0, -91.818241543240035,
+             0.0, 42.534998745388457,
+             0.0, -7.3687943594796312,
+             0.0, 0.22710800170898438,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             212.5701300392171,
+             0.0,
+             -765.25246814118157,
+             0.0,
+             1059.9904525279999,
+             0.0,
+             -699.57962737613275,
+             0.0,
+             218.19051174421159,
+             0.0,
+             -26.491430486951554,
+             0.0,
+             0.57250142097473145,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   0,
+             0,   0,
+             0,   0,
+             0,   -1919.4576623184068,
+             0.0, 8061.7221817373083,
+             0.0, -13586.550006434136,
+             0.0, 11655.393336864536,
+             0.0, -5305.6469786134048,
+             0.0, 1200.9029132163525,
+             0.0, -108.09091978839464,
+             0.0, 1.7277275025844574,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0},
+            {0,
+             0,
+             0,
+             0,
+             0,
+             0,
+             20204.291330966149,
+             0.0,
+             -96980.598388637503,
+             0.0,
+             192547.0012325315,
+             0.0,
+             -203400.17728041555,
+             0.0,
+             122200.46498301747,
+             0.0,
+             -41192.654968897557,
+             0.0,
+             7109.5143024893641,
+             0.0,
+             -493.915304773088,
+             0.0,
+             6.074042001273483,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0},
+            {0,   0,
+             0,   -242919.18790055133,
+             0.0, 1311763.6146629769,
+             0.0, -2998015.9185381061,
+             0.0, 3763271.2976564039,
+             0.0, -2813563.2265865342,
+             0.0, 1268365.2733216248,
+             0.0, -331645.17248456361,
+             0.0, 45218.768981362737,
+             0.0, -2499.8304818112092,
+             0.0, 24.380529699556064,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0, 0.0,
+             0.0},
+            {3284469.8530720375,
+             0.0,
+             -19706819.11843222,
+             0.0,
+             50952602.492664628,
+             0.0,
+             -74105148.211532637,
+             0.0,
+             66344512.274729028,
+             0.0,
+             -37567176.660763353,
+             0.0,
+             13288767.166421819,
+             0.0,
+             -2785618.1280864552,
+             0.0,
+             308186.40461266245,
+             0.0,
+             -13886.089753717039,
+             0.0,
+             110.01714026924674,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0,
+             0.0}};
+
+        /*
+         * Compute Iv, Kv from (AMS5 9.7.7 + 9.7.8), asymptotic expansion for large v
+         */
+        XSF_HOST_DEVICE inline void ikv_asymptotic_uniform(double v, double x, double *i_value, double *k_value) {
+            double i_prefactor, k_prefactor;
+            double t, t2, eta, z;
+            double i_sum, k_sum, term, divisor;
+            int k, n;
+            int sign = 1;
+
+            if (v < 0) {
+                /* Negative v; compute I_{-v} and K_{-v} and use (AMS 9.6.2) */
+                sign = -1;
+                v = -v;
+            }
+
+            z = x / v;
+            t = 1 / std::sqrt(1 + z * z);
+            t2 = t * t;
+            eta = std::sqrt(1 + z * z) + std::log(z / (1 + 1 / t));
+
+            i_prefactor = std::sqrt(t / (2 * M_PI * v)) * std::exp(v * eta);
+            i_sum = 1.0;
+
+            k_prefactor = std::sqrt(M_PI * t / (2 * v)) * std::exp(-v * eta);
+            k_sum = 1.0;
+
+            divisor = v;
+            for (n = 1; n < iv_N_UFACTORS; ++n) {
+                /*
+                 * Evaluate u_k(t) with Horner's scheme;
+                 * (using the knowledge about which coefficients are zero)
+                 */
+                term = 0;
+                for (k = iv_N_UFACTOR_TERMS - 1 - 3 * n; k < iv_N_UFACTOR_TERMS - n; k += 2) {
+                    term *= t2;
+                    term += iv_asymptotic_ufactors[n][k];
+                }
+                for (k = 1; k < n; k += 2) {
+                    term *= t2;
+                }
+                if (n % 2 == 1) {
+                    term *= t;
+                }
+
+                /* Sum terms */
+                term /= divisor;
+                i_sum += term;
+                k_sum += (n % 2 == 0) ? term : -term;
+
+                /* Check convergence */
+                if (std::abs(term) < MACHEP) {
+                    break;
+                }
+
+                divisor *= v;
+            }
+
+            if (std::abs(term) > 1e-3 * std::abs(i_sum)) {
+                /* Didn't converge */
+                set_error("ikv_asymptotic_uniform", SF_ERROR_NO_RESULT, NULL);
+            }
+            if (std::abs(term) > MACHEP * std::abs(i_sum)) {
+                /* Some precision lost */
+                set_error("ikv_asymptotic_uniform", SF_ERROR_LOSS, NULL);
+            }
+
+            if (k_value != NULL) {
+                /* symmetric in v */
+                *k_value = k_prefactor * k_sum;
+            }
+
+            if (i_value != NULL) {
+                if (sign == 1) {
+                    *i_value = i_prefactor * i_sum;
+                } else {
+                    /* (AMS 9.6.2) */
+                    *i_value = (i_prefactor * i_sum + (2 / M_PI) * xsf::cephes::sinpi(v) * k_prefactor * k_sum);
+                }
+            }
+        }
+
+        /*
+         * The following code originates from the Boost C++ library,
+         * from file `boost/math/special_functions/detail/bessel_ik.hpp`,
+         * converted from C++ to C.
+         */
+
+        /*
+         * Modified Bessel functions of the first and second kind of fractional order
+         *
+         * Calculate K(v, x) and K(v+1, x) by method analogous to
+         * Temme, Journal of Computational Physics, vol 21, 343 (1976)
+         */
+        XSF_HOST_DEVICE inline int temme_ik_series(double v, double x, double *K, double *K1) {
+            double f, h, p, q, coef, sum, sum1, tolerance;
+            double a, b, c, d, sigma, gamma1, gamma2;
+            std::uint64_t k;
+            double gp;
+            double gm;
+
+            /*
+             * |x| <= 2, Temme series converge rapidly
+             * |x| > 2, the larger the |x|, the slower the convergence
+             */
+            XSF_ASSERT(std::abs(x) <= 2);
+            XSF_ASSERT(std::abs(v) <= 0.5f);
+
+            gp = xsf::cephes::Gamma(v + 1) - 1;
+            gm = xsf::cephes::Gamma(-v + 1) - 1;
+
+            a = std::log(x / 2);
+            b = std::exp(v * a);
+            sigma = -a * v;
+            c = std::abs(v) < MACHEP ? 1 : xsf::cephes::sinpi(v) / (v * M_PI);
+            d = std::abs(sigma) < MACHEP ? 1 : std::sinh(sigma) / sigma;
+            gamma1 = std::abs(v) < MACHEP ? -SCIPY_EULER : (0.5 / v) * (gp - gm) * c;
+            gamma2 = (2 + gp + gm) * c / 2;
+
+            /* initial values */
+            p = (gp + 1) / (2 * b);
+            q = (1 + gm) * b / 2;
+            f = (std::cosh(sigma) * gamma1 + d * (-a) * gamma2) / c;
+            h = p;
+            coef = 1;
+            sum = coef * f;
+            sum1 = coef * h;
+
+            /* series summation */
+            tolerance = MACHEP;
+            for (k = 1; k < MAXITER; k++) {
+                f = (k * f + p + q) / (k * k - v * v);
+                p /= k - v;
+                q /= k + v;
+                h = p - k * f;
+                coef *= x * x / (4 * k);
+                sum += coef * f;
+                sum1 += coef * h;
+                if (std::abs(coef * f) < std::abs(sum) * tolerance) {
+                    break;
+                }
+            }
+            if (k == MAXITER) {
+                set_error("ikv_temme(temme_ik_series)", SF_ERROR_NO_RESULT, NULL);
+            }
+
+            *K = sum;
+            *K1 = 2 * sum1 / x;
+
+            return 0;
+        }
+
+        /* Evaluate continued fraction fv = I_(v+1) / I_v, derived from
+         * Abramowitz and Stegun, Handbook of Mathematical Functions, 1972, 9.1.73 */
+        XSF_HOST_DEVICE inline int CF1_ik(double v, double x, double *fv) {
+            double C, D, f, a, b, delta, tiny, tolerance;
+            std::uint64_t k;
+
+            /*
+             * |x| <= |v|, CF1_ik converges rapidly
+             * |x| > |v|, CF1_ik needs O(|x|) iterations to converge
+             */
+
+            /*
+             * modified Lentz's method, see
+             * Lentz, Applied Optics, vol 15, 668 (1976)
+             */
+            tolerance = 2 * MACHEP;
+            tiny = 1 / std::sqrt(std::numeric_limits::max());
+            C = f = tiny; /* b0 = 0, replace with tiny */
+            D = 0;
+            for (k = 1; k < MAXITER; k++) {
+                a = 1;
+                b = 2 * (v + k) / x;
+                C = b + a / C;
+                D = b + a * D;
+                if (C == 0) {
+                    C = tiny;
+                }
+                if (D == 0) {
+                    D = tiny;
+                }
+                D = 1 / D;
+                delta = C * D;
+                f *= delta;
+                if (std::abs(delta - 1) <= tolerance) {
+                    break;
+                }
+            }
+            if (k == MAXITER) {
+                set_error("ikv_temme(CF1_ik)", SF_ERROR_NO_RESULT, NULL);
+            }
+
+            *fv = f;
+
+            return 0;
+        }
+
+        /*
+         * Calculate K(v, x) and K(v+1, x) by evaluating continued fraction
+         * z1 / z0 = U(v+1.5, 2v+1, 2x) / U(v+0.5, 2v+1, 2x), see
+         * Thompson and Barnett, Computer Physics Communications, vol 47, 245 (1987)
+         */
+        XSF_HOST_DEVICE inline int CF2_ik(double v, double x, double *Kv, double *Kv1) {
+
+            double S, C, Q, D, f, a, b, q, delta, tolerance, current, prev;
+            std::uint64_t k;
+
+            /*
+             * |x| >= |v|, CF2_ik converges rapidly
+             * |x| -> 0, CF2_ik fails to converge
+             */
+
+            XSF_ASSERT(std::abs(x) > 1);
+
+            /*
+             * Steed's algorithm, see Thompson and Barnett,
+             * Journal of Computational Physics, vol 64, 490 (1986)
+             */
+            tolerance = MACHEP;
+            a = v * v - 0.25;
+            b = 2 * (x + 1);                /* b1 */
+            D = 1 / b;                      /* D1 = 1 / b1 */
+            f = delta = D;                  /* f1 = delta1 = D1, coincidence */
+            prev = 0;                       /* q0 */
+            current = 1;                    /* q1 */
+            Q = C = -a;                     /* Q1 = C1 because q1 = 1 */
+            S = 1 + Q * delta;              /* S1 */
+            for (k = 2; k < MAXITER; k++) { /* starting from 2 */
+                /* continued fraction f = z1 / z0 */
+                a -= 2 * (k - 1);
+                b += 2;
+                D = 1 / (b + a * D);
+                delta *= b * D - 1;
+                f += delta;
+
+                /* series summation S = 1 + \sum_{n=1}^{\infty} C_n * z_n / z_0 */
+                q = (prev - (b - 2) * current) / a;
+                prev = current;
+                current = q; /* forward recurrence for q */
+                C *= -a / k;
+                Q += C * q;
+                S += Q * delta;
+
+                /* S converges slower than f */
+                if (std::abs(Q * delta) < std::abs(S) * tolerance) {
+                    break;
+                }
+            }
+            if (k == MAXITER) {
+                set_error("ikv_temme(CF2_ik)", SF_ERROR_NO_RESULT, NULL);
+            }
+
+            *Kv = std::sqrt(M_PI / (2 * x)) * std::exp(-x) / S;
+            *Kv1 = *Kv * (0.5 + v + x + (v * v - 0.25) * f) / x;
+
+            return 0;
+        }
+
+        /* Flags for what to compute */
+        enum { ikv_temme_need_i = 0x1, ikv_temme_need_k = 0x2 };
+
+        /*
+         * Compute I(v, x) and K(v, x) simultaneously by Temme's method, see
+         * Temme, Journal of Computational Physics, vol 19, 324 (1975)
+         */
+        XSF_HOST_DEVICE inline void ikv_temme(double v, double x, double *Iv_p, double *Kv_p) {
+            /* Kv1 = K_(v+1), fv = I_(v+1) / I_v */
+            /* Ku1 = K_(u+1), fu = I_(u+1) / I_u */
+            double u, Iv, Kv, Kv1, Ku, Ku1, fv;
+            double W, current, prev, next;
+            int reflect = 0;
+            unsigned n, k;
+            int kind;
+
+            kind = 0;
+            if (Iv_p != NULL) {
+                kind |= ikv_temme_need_i;
+            }
+            if (Kv_p != NULL) {
+                kind |= ikv_temme_need_k;
+            }
+
+            if (v < 0) {
+                reflect = 1;
+                v = -v; /* v is non-negative from here */
+                kind |= ikv_temme_need_k;
+            }
+            n = std::round(v);
+            u = v - n; /* -1/2 <= u < 1/2 */
+
+            if (x < 0) {
+                if (Iv_p != NULL)
+                    *Iv_p = std::numeric_limits::quiet_NaN();
+                if (Kv_p != NULL)
+                    *Kv_p = std::numeric_limits::quiet_NaN();
+                set_error("ikv_temme", SF_ERROR_DOMAIN, NULL);
+                return;
+            }
+            if (x == 0) {
+                Iv = (v == 0) ? 1 : 0;
+                if (kind & ikv_temme_need_k) {
+                    set_error("ikv_temme", SF_ERROR_OVERFLOW, NULL);
+                    Kv = std::numeric_limits::infinity();
+                } else {
+                    Kv = std::numeric_limits::quiet_NaN(); /* any value will do */
+                }
+
+                if (reflect && (kind & ikv_temme_need_i)) {
+                    double z = (u + n % 2);
+
+                    Iv = xsf::cephes::sinpi(z) == 0 ? Iv : std::numeric_limits::infinity();
+                    if (std::isinf(Iv)) {
+                        set_error("ikv_temme", SF_ERROR_OVERFLOW, NULL);
+                    }
+                }
+
+                if (Iv_p != NULL) {
+                    *Iv_p = Iv;
+                }
+                if (Kv_p != NULL) {
+                    *Kv_p = Kv;
+                }
+                return;
+            }
+            /* x is positive until reflection */
+            W = 1 / x;                            /* Wronskian */
+            if (x <= 2) {                         /* x in (0, 2] */
+                temme_ik_series(u, x, &Ku, &Ku1); /* Temme series */
+            } else {                              /* x in (2, \infty) */
+                CF2_ik(u, x, &Ku, &Ku1);          /* continued fraction CF2_ik */
+            }
+            prev = Ku;
+            current = Ku1;
+            for (k = 1; k <= n; k++) { /* forward recurrence for K */
+                next = 2 * (u + k) * current / x + prev;
+                prev = current;
+                current = next;
+            }
+            Kv = prev;
+            Kv1 = current;
+            if (kind & ikv_temme_need_i) {
+                double lim = (4 * v * v + 10) / (8 * x);
+
+                lim *= lim;
+                lim *= lim;
+                lim /= 24;
+                if ((lim < MACHEP * 10) && (x > 100)) {
+                    /*
+                     * x is huge compared to v, CF1 may be very slow
+                     * to converge so use asymptotic expansion for large
+                     * x case instead.  Note that the asymptotic expansion
+                     * isn't very accurate - so it's deliberately very hard
+                     * to get here - probably we're going to overflow:
+                     */
+                    Iv = iv_asymptotic(v, x);
+                } else {
+                    CF1_ik(v, x, &fv);        /* continued fraction CF1_ik */
+                    Iv = W / (Kv * fv + Kv1); /* Wronskian relation */
+                }
+            } else {
+                Iv = std::numeric_limits::quiet_NaN(); /* any value will do */
+            }
+
+            if (reflect) {
+                double z = (u + n % 2);
+
+                if (Iv_p != NULL) {
+                    *Iv_p = Iv + (2 / M_PI) * xsf::cephes::sinpi(z) * Kv; /* reflection formula */
+                }
+                if (Kv_p != NULL) {
+                    *Kv_p = Kv;
+                }
+            } else {
+                if (Iv_p != NULL) {
+                    *Iv_p = Iv;
+                }
+                if (Kv_p != NULL) {
+                    *Kv_p = Kv;
+                }
+            }
+            return;
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double iv(double v, double x) {
+        int sign;
+        double t, ax, res;
+
+        if (std::isnan(v) || std::isnan(x)) {
+            return std::numeric_limits::quiet_NaN();
+        }
+
+        /* If v is a negative integer, invoke symmetry */
+        t = std::floor(v);
+        if (v < 0.0) {
+            if (t == v) {
+                v = -v; /* symmetry */
+                t = -t;
+            }
+        }
+        /* If x is negative, require v to be an integer */
+        sign = 1;
+        if (x < 0.0) {
+            if (t != v) {
+                set_error("iv", SF_ERROR_DOMAIN, NULL);
+                return (std::numeric_limits::quiet_NaN());
+            }
+            if (v != 2.0 * std::floor(v / 2.0)) {
+                sign = -1;
+            }
+        }
+
+        /* Avoid logarithm singularity */
+        if (x == 0.0) {
+            if (v == 0.0) {
+                return 1.0;
+            }
+            if (v < 0.0) {
+                set_error("iv", SF_ERROR_OVERFLOW, NULL);
+                return std::numeric_limits::infinity();
+            } else
+                return 0.0;
+        }
+
+        ax = std::abs(x);
+        if (std::abs(v) > 50) {
+            /*
+             * Uniform asymptotic expansion for large orders.
+             *
+             * This appears to overflow slightly later than the Boost
+             * implementation of Temme's method.
+             */
+            detail::ikv_asymptotic_uniform(v, ax, &res, NULL);
+        } else {
+            /* Otherwise: Temme's method */
+            detail::ikv_temme(v, ax, &res, NULL);
+        }
+        res *= sign;
+        return res;
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h
new file mode 100644
index 0000000000000000000000000000000000000000..fcdd2d7986466e33bff8bf15235c2d2814206d61
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/shichi.h
@@ -0,0 +1,248 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     shichi.c
+ *
+ *     Hyperbolic sine and cosine integrals
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, Chi, Shi, shichi();
+ *
+ * shichi( x, &Chi, &Shi );
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Approximates the integrals
+ *
+ *                            x
+ *                            -
+ *                           | |   cosh t - 1
+ *   Chi(x) = eul + ln x +   |    -----------  dt,
+ *                         | |          t
+ *                          -
+ *                          0
+ *
+ *               x
+ *               -
+ *              | |  sinh t
+ *   Shi(x) =   |    ------  dt
+ *            | |       t
+ *             -
+ *             0
+ *
+ * where eul = 0.57721566490153286061 is Euler's constant.
+ * The integrals are evaluated by power series for x < 8
+ * and by Chebyshev expansions for x between 8 and 88.
+ * For large x, both functions approach exp(x)/2x.
+ * Arguments greater than 88 in magnitude return INFINITY.
+ *
+ *
+ * ACCURACY:
+ *
+ * Test interval 0 to 88.
+ *                      Relative error:
+ * arithmetic   function  # trials      peak         rms
+ *    IEEE         Shi      30000       6.9e-16     1.6e-16
+ *        Absolute error, except relative when |Chi| > 1:
+ *    IEEE         Chi      30000       8.4e-16     1.4e-16
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "chbevl.h"
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* x exp(-x) shi(x), inverted interval 8 to 18 */
+        constexpr double shichi_S1[] = {
+            1.83889230173399459482E-17,  -9.55485532279655569575E-17, 2.04326105980879882648E-16,
+            1.09896949074905343022E-15,  -1.31313534344092599234E-14, 5.93976226264314278932E-14,
+            -3.47197010497749154755E-14, -1.40059764613117131000E-12, 9.49044626224223543299E-12,
+            -1.61596181145435454033E-11, -1.77899784436430310321E-10, 1.35455469767246947469E-9,
+            -1.03257121792819495123E-9,  -3.56699611114982536845E-8,  1.44818877384267342057E-7,
+            7.82018215184051295296E-7,   -5.39919118403805073710E-6,  -3.12458202168959833422E-5,
+            8.90136741950727517826E-5,   2.02558474743846862168E-3,   2.96064440855633256972E-2,
+            1.11847751047257036625E0};
+
+        /* x exp(-x) shi(x), inverted interval 18 to 88 */
+        constexpr double shichi_S2[] = {
+            -1.05311574154850938805E-17, 2.62446095596355225821E-17,  8.82090135625368160657E-17,
+            -3.38459811878103047136E-16, -8.30608026366935789136E-16, 3.93397875437050071776E-15,
+            1.01765565969729044505E-14,  -4.21128170307640802703E-14, -1.60818204519802480035E-13,
+            3.34714954175994481761E-13,  2.72600352129153073807E-12,  1.66894954752839083608E-12,
+            -3.49278141024730899554E-11, -1.58580661666482709598E-10, -1.79289437183355633342E-10,
+            1.76281629144264523277E-9,   1.69050228879421288846E-8,   1.25391771228487041649E-7,
+            1.16229947068677338732E-6,   1.61038260117376323993E-5,   3.49810375601053973070E-4,
+            1.28478065259647610779E-2,   1.03665722588798326712E0};
+
+        /* x exp(-x) chin(x), inverted interval 8 to 18 */
+        constexpr double shichi_C1[] = {
+            -8.12435385225864036372E-18, 2.17586413290339214377E-17, 5.22624394924072204667E-17,
+            -9.48812110591690559363E-16, 5.35546311647465209166E-15, -1.21009970113732918701E-14,
+            -6.00865178553447437951E-14, 7.16339649156028587775E-13, -2.93496072607599856104E-12,
+            -1.40359438136491256904E-12, 8.76302288609054966081E-11, -4.40092476213282340617E-10,
+            -1.87992075640569295479E-10, 1.31458150989474594064E-8,  -4.75513930924765465590E-8,
+            -2.21775018801848880741E-7,  1.94635531373272490962E-6,  4.33505889257316408893E-6,
+            -6.13387001076494349496E-5,  -3.13085477492997465138E-4, 4.97164789823116062801E-4,
+            2.64347496031374526641E-2,   1.11446150876699213025E0};
+
+        /* x exp(-x) chin(x), inverted interval 18 to 88 */
+        constexpr double shichi_C2[] = {
+            8.06913408255155572081E-18,  -2.08074168180148170312E-17, -5.98111329658272336816E-17,
+            2.68533951085945765591E-16,  4.52313941698904694774E-16,  -3.10734917335299464535E-15,
+            -4.42823207332531972288E-15, 3.49639695410806959872E-14,  6.63406731718911586609E-14,
+            -3.71902448093119218395E-13, -1.27135418132338309016E-12, 2.74851141935315395333E-12,
+            2.33781843985453438400E-11,  2.71436006377612442764E-11,  -2.56600180000355990529E-10,
+            -1.61021375163803438552E-9,  -4.72543064876271773512E-9,  -3.00095178028681682282E-9,
+            7.79387474390914922337E-8,   1.06942765566401507066E-6,   1.59503164802313196374E-5,
+            3.49592575153777996871E-4,   1.28475387530065247392E-2,   1.03665693917934275131E0};
+
+        /*
+         * Evaluate 3F0(a1, a2, a3; z)
+         *
+         * The series is only asymptotic, so this requires z large enough.
+         */
+        XSF_HOST_DEVICE inline double hyp3f0(double a1, double a2, double a3, double z) {
+            int n, maxiter;
+            double err, sum, term, m;
+
+            m = std::pow(z, -1.0 / 3);
+            if (m < 50) {
+                maxiter = m;
+            } else {
+                maxiter = 50;
+            }
+
+            term = 1.0;
+            sum = term;
+            for (n = 0; n < maxiter; ++n) {
+                term *= (a1 + n) * (a2 + n) * (a3 + n) * z / (n + 1);
+                sum += term;
+                if (std::abs(term) < 1e-13 * std::abs(sum) || term == 0) {
+                    break;
+                }
+            }
+
+            err = std::abs(term);
+
+            if (err > 1e-13 * std::abs(sum)) {
+                return std::numeric_limits::quiet_NaN();
+            }
+
+            return sum;
+        }
+
+    } // namespace detail
+
+    /* Sine and cosine integrals */
+    XSF_HOST_DEVICE inline int shichi(double x, double *si, double *ci) {
+        double k, z, c, s, a, b;
+        short sign;
+
+        if (x < 0.0) {
+            sign = -1;
+            x = -x;
+        } else {
+            sign = 0;
+        }
+
+        if (x == 0.0) {
+            *si = 0.0;
+            *ci = -std::numeric_limits::infinity();
+            return (0);
+        }
+
+        if (x >= 8.0) {
+            goto chb;
+        }
+
+        if (x >= 88.0) {
+            goto asymp;
+        }
+
+        z = x * x;
+
+        /*     Direct power series expansion   */
+        a = 1.0;
+        s = 1.0;
+        c = 0.0;
+        k = 2.0;
+
+        do {
+            a *= z / k;
+            c += a / k;
+            k += 1.0;
+            a /= k;
+            s += a / k;
+            k += 1.0;
+        } while (std::abs(a / s) > detail::MACHEP);
+
+        s *= x;
+        goto done;
+
+    chb:
+        /* Chebyshev series expansions */
+        if (x < 18.0) {
+            a = (576.0 / x - 52.0) / 10.0;
+            k = std::exp(x) / x;
+            s = k * chbevl(a, detail::shichi_S1, 22);
+            c = k * chbevl(a, detail::shichi_C1, 23);
+            goto done;
+        }
+
+        if (x <= 88.0) {
+            a = (6336.0 / x - 212.0) / 70.0;
+            k = std::exp(x) / x;
+            s = k * chbevl(a, detail::shichi_S2, 23);
+            c = k * chbevl(a, detail::shichi_C2, 24);
+            goto done;
+        }
+
+    asymp:
+        if (x > 1000) {
+            *si = std::numeric_limits::infinity();
+            *ci = std::numeric_limits::infinity();
+        } else {
+            /* Asymptotic expansions
+             * http://functions.wolfram.com/GammaBetaErf/CoshIntegral/06/02/
+             * http://functions.wolfram.com/GammaBetaErf/SinhIntegral/06/02/0001/
+             */
+            a = detail::hyp3f0(0.5, 1, 1, 4.0 / (x * x));
+            b = detail::hyp3f0(1, 1, 1.5, 4.0 / (x * x));
+            *si = std::cosh(x) / x * a + std::sinh(x) / (x * x) * b;
+            *ci = std::sinh(x) / x * a + std::cosh(x) / (x * x) * b;
+        }
+        if (sign) {
+            *si = -*si;
+        }
+        return 0;
+
+    done:
+        if (sign) {
+            s = -s;
+        }
+
+        *si = s;
+
+        *ci = detail::SCIPY_EULER + std::log(x) + c;
+        return (0);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h
new file mode 100644
index 0000000000000000000000000000000000000000..c22612ccc9abfd0594467ad40ad466b4559db2bc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sici.h
@@ -0,0 +1,224 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     sici.c
+ *
+ *     Sine and cosine integrals
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, Ci, Si, sici();
+ *
+ * sici( x, &Si, &Ci );
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Evaluates the integrals
+ *
+ *                          x
+ *                          -
+ *                         |  cos t - 1
+ *   Ci(x) = eul + ln x +  |  --------- dt,
+ *                         |      t
+ *                        -
+ *                         0
+ *             x
+ *             -
+ *            |  sin t
+ *   Si(x) =  |  ----- dt
+ *            |    t
+ *           -
+ *            0
+ *
+ * where eul = 0.57721566490153286061 is Euler's constant.
+ * The integrals are approximated by rational functions.
+ * For x > 8 auxiliary functions f(x) and g(x) are employed
+ * such that
+ *
+ * Ci(x) = f(x) sin(x) - g(x) cos(x)
+ * Si(x) = pi/2 - f(x) cos(x) - g(x) sin(x)
+ *
+ *
+ * ACCURACY:
+ *    Test interval = [0,50].
+ * Absolute error, except relative when > 1:
+ * arithmetic   function   # trials      peak         rms
+ *    IEEE        Si        30000       4.4e-16     7.3e-17
+ *    IEEE        Ci        30000       6.9e-16     5.1e-17
+ */
+
+/*
+ * Cephes Math Library Release 2.1:  January, 1989
+ * Copyright 1984, 1987, 1989 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double sici_SN[] = {
+            -8.39167827910303881427E-11, 4.62591714427012837309E-8,  -9.75759303843632795789E-6,
+            9.76945438170435310816E-4,   -4.13470316229406538752E-2, 1.00000000000000000302E0,
+        };
+
+        constexpr double sici_SD[] = {
+            2.03269266195951942049E-12, 1.27997891179943299903E-9, 4.41827842801218905784E-7,
+            9.96412122043875552487E-5,  1.42085239326149893930E-2, 9.99999999999999996984E-1,
+        };
+
+        constexpr double sici_CN[] = {
+            2.02524002389102268789E-11, -1.35249504915790756375E-8, 3.59325051419993077021E-6,
+            -4.74007206873407909465E-4, 2.89159652607555242092E-2,  -1.00000000000000000080E0,
+        };
+
+        constexpr double sici_CD[] = {
+            4.07746040061880559506E-12, 3.06780997581887812692E-9, 1.23210355685883423679E-6,
+            3.17442024775032769882E-4,  5.10028056236446052392E-2, 4.00000000000000000080E0,
+        };
+
+        constexpr double sici_FN4[] = {
+            4.23612862892216586994E0,  5.45937717161812843388E0,  1.62083287701538329132E0,  1.67006611831323023771E-1,
+            6.81020132472518137426E-3, 1.08936580650328664411E-4, 5.48900223421373614008E-7,
+        };
+
+        constexpr double sici_FD4[] = {
+            /*  1.00000000000000000000E0, */
+            8.16496634205391016773E0,  7.30828822505564552187E0,  1.86792257950184183883E0,  1.78792052963149907262E-1,
+            7.01710668322789753610E-3, 1.10034357153915731354E-4, 5.48900252756255700982E-7,
+        };
+
+        constexpr double sici_FN8[] = {
+            4.55880873470465315206E-1, 7.13715274100146711374E-1,  1.60300158222319456320E-1,
+            1.16064229408124407915E-2, 3.49556442447859055605E-4,  4.86215430826454749482E-6,
+            3.20092790091004902806E-8, 9.41779576128512936592E-11, 9.70507110881952024631E-14,
+        };
+
+        constexpr double sici_FD8[] = {
+            /*  1.00000000000000000000E0, */
+            9.17463611873684053703E-1,  1.78685545332074536321E-1,  1.22253594771971293032E-2,
+            3.58696481881851580297E-4,  4.92435064317881464393E-6,  3.21956939101046018377E-8,
+            9.43720590350276732376E-11, 9.70507110881952025725E-14,
+        };
+
+        constexpr double sici_GN4[] = {
+            8.71001698973114191777E-2, 6.11379109952219284151E-1, 3.97180296392337498885E-1, 7.48527737628469092119E-2,
+            5.38868681462177273157E-3, 1.61999794598934024525E-4, 1.97963874140963632189E-6, 7.82579040744090311069E-9,
+        };
+
+        constexpr double sici_GD4[] = {
+            /*  1.00000000000000000000E0, */
+            1.64402202413355338886E0,  6.66296701268987968381E-1, 9.88771761277688796203E-2, 6.22396345441768420760E-3,
+            1.73221081474177119497E-4, 2.02659182086343991969E-6, 7.82579218933534490868E-9,
+        };
+
+        constexpr double sici_GN8[] = {
+            6.97359953443276214934E-1, 3.30410979305632063225E-1,  3.84878767649974295920E-2,
+            1.71718239052347903558E-3, 3.48941165502279436777E-5,  3.47131167084116673800E-7,
+            1.70404452782044526189E-9, 3.85945925430276600453E-12, 3.14040098946363334640E-15,
+        };
+
+        constexpr double sici_GD8[] = {
+            /*  1.00000000000000000000E0, */
+            1.68548898811011640017E0,  4.87852258695304967486E-1,  4.67913194259625806320E-2,
+            1.90284426674399523638E-3, 3.68475504442561108162E-5,  3.57043223443740838771E-7,
+            1.72693748966316146736E-9, 3.87830166023954706752E-12, 3.14040098946363335242E-15,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline int sici(double x, double *si, double *ci) {
+        double z, c, s, f, g;
+        short sign;
+
+        if (x < 0.0) {
+            sign = -1;
+            x = -x;
+        } else {
+            sign = 0;
+        }
+
+        if (x == 0.0) {
+            *si = 0.0;
+            *ci = -std::numeric_limits::infinity();
+            return (0);
+        }
+
+        if (x > 1.0e9) {
+            if (std::isinf(x)) {
+                if (sign == -1) {
+                    *si = -M_PI_2;
+                    *ci = std::numeric_limits::quiet_NaN();
+                } else {
+                    *si = M_PI_2;
+                    *ci = 0;
+                }
+                return 0;
+            }
+            *si = M_PI_2 - std::cos(x) / x;
+            *ci = std::sin(x) / x;
+        }
+
+        if (x > 4.0) {
+            goto asympt;
+        }
+
+        z = x * x;
+        s = x * polevl(z, detail::sici_SN, 5) / polevl(z, detail::sici_SD, 5);
+        c = z * polevl(z, detail::sici_CN, 5) / polevl(z, detail::sici_CD, 5);
+
+        if (sign) {
+            s = -s;
+        }
+        *si = s;
+        *ci = detail::SCIPY_EULER + std::log(x) + c; /* real part if x < 0 */
+        return (0);
+
+        /* The auxiliary functions are:
+         *
+         *
+         * *si = *si - M_PI_2;
+         * c = cos(x);
+         * s = sin(x);
+         *
+         * t = *ci * s - *si * c;
+         * a = *ci * c + *si * s;
+         *
+         * *si = t;
+         * *ci = -a;
+         */
+
+    asympt:
+
+        s = std::sin(x);
+        c = std::cos(x);
+        z = 1.0 / (x * x);
+        if (x < 8.0) {
+            f = polevl(z, detail::sici_FN4, 6) / (x * p1evl(z, detail::sici_FD4, 7));
+            g = z * polevl(z, detail::sici_GN4, 7) / p1evl(z, detail::sici_GD4, 7);
+        } else {
+            f = polevl(z, detail::sici_FN8, 8) / (x * p1evl(z, detail::sici_FD8, 8));
+            g = z * polevl(z, detail::sici_GN8, 8) / p1evl(z, detail::sici_GD8, 9);
+        }
+        *si = M_PI_2 - f * c - g * s;
+        if (sign) {
+            *si = -(*si);
+        }
+        *ci = f * s - g * c;
+
+        return (0);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h
new file mode 100644
index 0000000000000000000000000000000000000000..63adb1698f4c6e51d971484c92b3cf2c98dcba6f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/sindg.h
@@ -0,0 +1,221 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     sindg.c
+ *
+ *     Circular sine of angle in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, sindg();
+ *
+ * y = sindg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Range reduction is into intervals of 45 degrees.
+ *
+ * Two polynomial approximating functions are employed.
+ * Between 0 and pi/4 the sine is approximated by
+ *      x  +  x**3 P(x**2).
+ * Between pi/4 and pi/2 the cosine is represented as
+ *      1  -  x**2 P(x**2).
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE      +-1000       30000      2.3e-16      5.6e-17
+ *
+ * ERROR MESSAGES:
+ *
+ *   message           condition        value returned
+ * sindg total loss   x > 1.0e14 (IEEE)     0.0
+ *
+ */
+/*							cosdg.c
+ *
+ *	Circular cosine of angle in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, cosdg();
+ *
+ * y = cosdg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Range reduction is into intervals of 45 degrees.
+ *
+ * Two polynomial approximating functions are employed.
+ * Between 0 and pi/4 the cosine is approximated by
+ *      1  -  x**2 P(x**2).
+ * Between pi/4 and pi/2 the sine is represented as
+ *      x  +  x**3 P(x**2).
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain      # trials      peak         rms
+ *    IEEE     +-1000        30000       2.1e-16     5.7e-17
+ *  See also sin().
+ *
+ */
+
+/* Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1985, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+#include "const.h"
+#include "polevl.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        constexpr double sincof[] = {1.58962301572218447952E-10, -2.50507477628503540135E-8,
+                                     2.75573136213856773549E-6,  -1.98412698295895384658E-4,
+                                     8.33333333332211858862E-3,  -1.66666666666666307295E-1};
+
+        constexpr double coscof[] = {1.13678171382044553091E-11, -2.08758833757683644217E-9, 2.75573155429816611547E-7,
+                                     -2.48015872936186303776E-5, 1.38888888888806666760E-3,  -4.16666666666666348141E-2,
+                                     4.99999999999999999798E-1};
+
+        constexpr double sindg_lossth = 1.0e14;
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double sindg(double x) {
+        double y, z, zz;
+        int j, sign;
+
+        /* make argument positive but save the sign */
+        sign = 1;
+        if (x < 0) {
+            x = -x;
+            sign = -1;
+        }
+
+        if (x > detail::sindg_lossth) {
+            set_error("sindg", SF_ERROR_NO_RESULT, NULL);
+            return (0.0);
+        }
+
+        y = std::floor(x / 45.0); /* integer part of x/M_PI_4 */
+
+        /* strip high bits of integer part to prevent integer overflow */
+        z = std::ldexp(y, -4);
+        z = std::floor(z);        /* integer part of y/8 */
+        z = y - std::ldexp(z, 4); /* y - 16 * (y/16) */
+
+        j = z; /* convert to integer for tests on the phase angle */
+        /* map zeros to origin */
+        if (j & 1) {
+            j += 1;
+            y += 1.0;
+        }
+        j = j & 07; /* octant modulo 360 degrees */
+        /* reflect in x axis */
+        if (j > 3) {
+            sign = -sign;
+            j -= 4;
+        }
+
+        z = x - y * 45.0;   /* x mod 45 degrees */
+        z *= detail::PI180; /* multiply by pi/180 to convert to radians */
+        zz = z * z;
+
+        if ((j == 1) || (j == 2)) {
+            y = 1.0 - zz * polevl(zz, detail::coscof, 6);
+        } else {
+            y = z + z * (zz * polevl(zz, detail::sincof, 5));
+        }
+
+        if (sign < 0)
+            y = -y;
+
+        return (y);
+    }
+
+    XSF_HOST_DEVICE inline double cosdg(double x) {
+        double y, z, zz;
+        int j, sign;
+
+        /* make argument positive */
+        sign = 1;
+        if (x < 0)
+            x = -x;
+
+        if (x > detail::sindg_lossth) {
+            set_error("cosdg", SF_ERROR_NO_RESULT, NULL);
+            return (0.0);
+        }
+
+        y = std::floor(x / 45.0);
+        z = std::ldexp(y, -4);
+        z = std::floor(z);        /* integer part of y/8 */
+        z = y - std::ldexp(z, 4); /* y - 16 * (y/16) */
+
+        /* integer and fractional part modulo one octant */
+        j = z;
+        if (j & 1) { /* map zeros to origin */
+            j += 1;
+            y += 1.0;
+        }
+        j = j & 07;
+        if (j > 3) {
+            j -= 4;
+            sign = -sign;
+        }
+
+        if (j > 1)
+            sign = -sign;
+
+        z = x - y * 45.0;   /* x mod 45 degrees */
+        z *= detail::PI180; /* multiply by pi/180 to convert to radians */
+
+        zz = z * z;
+
+        if ((j == 1) || (j == 2)) {
+            y = z + z * (zz * polevl(zz, detail::sincof, 5));
+        } else {
+            y = 1.0 - zz * polevl(zz, detail::coscof, 6);
+        }
+
+        if (sign < 0)
+            y = -y;
+
+        return (y);
+    }
+
+    /* Degrees, minutes, seconds to radians: */
+
+    /* 1 arc second, in radians = 4.848136811095359935899141023579479759563533023727e-6 */
+
+    namespace detail {
+        constexpr double sindg_P64800 = 4.848136811095359935899141023579479759563533023727e-6;
+    }
+
+    XSF_HOST_DEVICE inline double radian(double d, double m, double s) {
+        return (((d * 60.0 + m) * 60.0 + s) * detail::sindg_P64800);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h
new file mode 100644
index 0000000000000000000000000000000000000000..071b1a81d8bd5467fabf99fa54881f5862c0218b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/tandg.h
@@ -0,0 +1,139 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     tandg.c
+ *
+ *     Circular tangent of argument in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, tandg();
+ *
+ * y = tandg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the circular tangent of the argument x in degrees.
+ *
+ * Range reduction is modulo pi/4.  A rational function
+ *       x + x**3 P(x**2)/Q(x**2)
+ * is employed in the basic interval [0, pi/4].
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *                      Relative error:
+ * arithmetic   domain     # trials      peak         rms
+ *    IEEE     0,10         30000      3.2e-16      8.4e-17
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition          value returned
+ * tandg total loss   x > 1.0e14 (IEEE)     0.0
+ * tandg singularity  x = 180 k  +  90     INFINITY
+ */
+/*							cotdg.c
+ *
+ *	Circular cotangent of argument in degrees
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, y, cotdg();
+ *
+ * y = cotdg( x );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ * Returns the circular cotangent of the argument x in degrees.
+ *
+ * Range reduction is modulo pi/4.  A rational function
+ *       x + x**3 P(x**2)/Q(x**2)
+ * is employed in the basic interval [0, pi/4].
+ *
+ *
+ * ERROR MESSAGES:
+ *
+ *   message         condition          value returned
+ * cotdg total loss   x > 1.0e14 (IEEE)     0.0
+ * cotdg singularity  x = 180 k            INFINITY
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        constexpr double tandg_lossth = 1.0e14;
+
+        XSF_HOST_DEVICE inline double tancot(double xx, int cotflg) {
+            double x;
+            int sign;
+
+            /* make argument positive but save the sign */
+            if (xx < 0) {
+                x = -xx;
+                sign = -1;
+            } else {
+                x = xx;
+                sign = 1;
+            }
+
+            if (x > detail::tandg_lossth) {
+                set_error("tandg", SF_ERROR_NO_RESULT, NULL);
+                return 0.0;
+            }
+
+            /* modulo 180 */
+            x = x - 180.0 * std::floor(x / 180.0);
+            if (cotflg) {
+                if (x <= 90.0) {
+                    x = 90.0 - x;
+                } else {
+                    x = x - 90.0;
+                    sign *= -1;
+                }
+            } else {
+                if (x > 90.0) {
+                    x = 180.0 - x;
+                    sign *= -1;
+                }
+            }
+            if (x == 0.0) {
+                return 0.0;
+            } else if (x == 45.0) {
+                return sign * 1.0;
+            } else if (x == 90.0) {
+                set_error((cotflg ? "cotdg" : "tandg"), SF_ERROR_SINGULAR, NULL);
+                return std::numeric_limits::infinity();
+            }
+            /* x is now transformed into [0, 90) */
+            return sign * std::tan(x * detail::PI180);
+        }
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double tandg(double x) { return (detail::tancot(x, 0)); }
+
+    XSF_HOST_DEVICE inline double cotdg(double x) { return (detail::tancot(x, 1)); }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h
new file mode 100644
index 0000000000000000000000000000000000000000..47dcdbe6ab3c72e91dcd13f7f432572260ca3c62
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/trig.h
@@ -0,0 +1,58 @@
+/* Translated into C++ by SciPy developers in 2024.
+ *
+ * Original author: Josh Wilson, 2020.
+ */
+
+/*
+ * Implement sin(pi * x) and cos(pi * x) for real x. Since the periods
+ * of these functions are integral (and thus representable in double
+ * precision), it's possible to compute them with greater accuracy
+ * than sin(x) and cos(x).
+ */
+#pragma once
+
+#include "../config.h"
+
+namespace xsf {
+namespace cephes {
+
+    /* Compute sin(pi * x). */
+    template 
+    XSF_HOST_DEVICE T sinpi(T x) {
+        T s = 1.0;
+
+        if (x < 0.0) {
+            x = -x;
+            s = -1.0;
+        }
+
+        T r = std::fmod(x, 2.0);
+        if (r < 0.5) {
+            return s * std::sin(M_PI * r);
+        } else if (r > 1.5) {
+            return s * std::sin(M_PI * (r - 2.0));
+        } else {
+            return -s * std::sin(M_PI * (r - 1.0));
+        }
+    }
+
+    /* Compute cos(pi * x) */
+    template 
+    XSF_HOST_DEVICE T cospi(T x) {
+        if (x < 0.0) {
+            x = -x;
+        }
+
+        T r = std::fmod(x, 2.0);
+        if (r == 0.5) {
+            // We don't want to return -0.0
+            return 0.0;
+        }
+        if (r < 1.0) {
+            return -std::sin(M_PI * (r - 0.5));
+        } else {
+            return std::sin(M_PI * (r - 1.5));
+        }
+    }
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h
new file mode 100644
index 0000000000000000000000000000000000000000..eb045edda2122e206fc866b180c1fbd71670a553
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/unity.h
@@ -0,0 +1,186 @@
+/* Translated into C++ by SciPy developers in 2024. */
+
+/*                                                     unity.c
+ *
+ * Relative error approximations for function arguments near
+ * unity.
+ *
+ *    log1p(x) = log(1+x)
+ *    expm1(x) = exp(x) - 1
+ *    cosm1(x) = cos(x) - 1
+ *    lgam1p(x) = lgam(1+x)
+ *
+ */
+
+/* Scipy changes:
+ * - 06-10-2016: added lgam1p
+ */
+#pragma once
+
+#include "../config.h"
+
+#include "const.h"
+#include "gamma.h"
+#include "polevl.h"
+#include "zeta.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+
+        /* log1p(x) = log(1 + x)  */
+
+        /* Coefficients for log(1+x) = x - x**2/2 + x**3 P(x)/Q(x)
+         * 1/sqrt(2) <= x < sqrt(2)
+         * Theoretical peak relative error = 2.32e-20
+         */
+
+        constexpr double unity_LP[] = {
+            4.5270000862445199635215E-5, 4.9854102823193375972212E-1, 6.5787325942061044846969E0,
+            2.9911919328553073277375E1,  6.0949667980987787057556E1,  5.7112963590585538103336E1,
+            2.0039553499201281259648E1,
+        };
+
+        constexpr double unity_LQ[] = {
+            /* 1.0000000000000000000000E0, */
+            1.5062909083469192043167E1, 8.3047565967967209469434E1, 2.2176239823732856465394E2,
+            3.0909872225312059774938E2, 2.1642788614495947685003E2, 6.0118660497603843919306E1,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double log1p(double x) {
+        double z;
+
+        z = 1.0 + x;
+        if ((z < M_SQRT1_2) || (z > M_SQRT2))
+            return (std::log(z));
+        z = x * x;
+        z = -0.5 * z + x * (z * polevl(x, detail::unity_LP, 6) / p1evl(x, detail::unity_LQ, 6));
+        return (x + z);
+    }
+
+    /* log(1 + x) - x */
+    XSF_HOST_DEVICE inline double log1pmx(double x) {
+        if (std::abs(x) < 0.5) {
+            uint64_t n;
+            double xfac = x;
+            double term;
+            double res = 0;
+
+            for (n = 2; n < detail::MAXITER; n++) {
+                xfac *= -x;
+                term = xfac / n;
+                res += term;
+                if (std::abs(term) < detail::MACHEP * std::abs(res)) {
+                    break;
+                }
+            }
+            return res;
+        } else {
+            return log1p(x) - x;
+        }
+    }
+
+    /* expm1(x) = exp(x) - 1  */
+
+    /*  e^x =  1 + 2x P(x^2)/( Q(x^2) - P(x^2) )
+     * -0.5 <= x <= 0.5
+     */
+
+    namespace detail {
+
+        constexpr double unity_EP[3] = {
+            1.2617719307481059087798E-4,
+            3.0299440770744196129956E-2,
+            9.9999999999999999991025E-1,
+        };
+
+        constexpr double unity_EQ[4] = {
+            3.0019850513866445504159E-6,
+            2.5244834034968410419224E-3,
+            2.2726554820815502876593E-1,
+            2.0000000000000000000897E0,
+        };
+
+    } // namespace detail
+
+    XSF_HOST_DEVICE inline double expm1(double x) {
+        double r, xx;
+
+        if (!std::isfinite(x)) {
+            if (std::isnan(x)) {
+                return x;
+            } else if (x > 0) {
+                return x;
+            } else {
+                return -1.0;
+            }
+        }
+        if ((x < -0.5) || (x > 0.5))
+            return (std::exp(x) - 1.0);
+        xx = x * x;
+        r = x * polevl(xx, detail::unity_EP, 2);
+        r = r / (polevl(xx, detail::unity_EQ, 3) - r);
+        return (r + r);
+    }
+
+    /* cosm1(x) = cos(x) - 1  */
+
+    namespace detail {
+        constexpr double unity_coscof[7] = {
+            4.7377507964246204691685E-14, -1.1470284843425359765671E-11, 2.0876754287081521758361E-9,
+            -2.7557319214999787979814E-7, 2.4801587301570552304991E-5,   -1.3888888888888872993737E-3,
+            4.1666666666666666609054E-2,
+        };
+
+    }
+
+    XSF_HOST_DEVICE inline double cosm1(double x) {
+        double xx;
+
+        if ((x < -M_PI_4) || (x > M_PI_4))
+            return (std::cos(x) - 1.0);
+        xx = x * x;
+        xx = -0.5 * xx + xx * xx * polevl(xx, detail::unity_coscof, 6);
+        return xx;
+    }
+
+    namespace detail {
+        /* Compute lgam(x + 1) around x = 0 using its Taylor series. */
+        XSF_HOST_DEVICE inline double lgam1p_taylor(double x) {
+            int n;
+            double xfac, coeff, res;
+
+            if (x == 0) {
+                return 0;
+            }
+            res = -SCIPY_EULER * x;
+            xfac = -x;
+            for (n = 2; n < 42; n++) {
+                xfac *= -x;
+                coeff = xsf::cephes::zeta(n, 1) * xfac / n;
+                res += coeff;
+                if (std::abs(coeff) < detail::MACHEP * std::abs(res)) {
+                    break;
+                }
+            }
+
+            return res;
+        }
+    } // namespace detail
+
+    /* Compute lgam(x + 1). */
+    XSF_HOST_DEVICE inline double lgam1p(double x) {
+        if (std::abs(x) <= 0.5) {
+            return detail::lgam1p_taylor(x);
+        } else if (std::abs(x - 1) < 0.5) {
+            return std::log(x) + detail::lgam1p_taylor(x - 1);
+        } else {
+            return lgam(x + 1);
+        }
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h
new file mode 100644
index 0000000000000000000000000000000000000000..6f9d68e0bdced0edf70c17cdacf9a676341a908a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/cephes/zeta.h
@@ -0,0 +1,172 @@
+/* Translated into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/*                                                     zeta.c
+ *
+ *     Riemann zeta function of two arguments
+ *
+ *
+ *
+ * SYNOPSIS:
+ *
+ * double x, q, y, zeta();
+ *
+ * y = zeta( x, q );
+ *
+ *
+ *
+ * DESCRIPTION:
+ *
+ *
+ *
+ *                 inf.
+ *                  -        -x
+ *   zeta(x,q)  =   >   (k+q)
+ *                  -
+ *                 k=0
+ *
+ * where x > 1 and q is not a negative integer or zero.
+ * The Euler-Maclaurin summation formula is used to obtain
+ * the expansion
+ *
+ *                n
+ *                -       -x
+ * zeta(x,q)  =   >  (k+q)
+ *                -
+ *               k=1
+ *
+ *           1-x                 inf.  B   x(x+1)...(x+2j)
+ *      (n+q)           1         -     2j
+ *  +  ---------  -  -------  +   >    --------------------
+ *        x-1              x      -                   x+2j+1
+ *                   2(n+q)      j=1       (2j)! (n+q)
+ *
+ * where the B2j are Bernoulli numbers.  Note that (see zetac.c)
+ * zeta(x,1) = zetac(x) + 1.
+ *
+ *
+ *
+ * ACCURACY:
+ *
+ *
+ *
+ * REFERENCE:
+ *
+ * Gradshteyn, I. S., and I. M. Ryzhik, Tables of Integrals,
+ * Series, and Products, p. 1073; Academic Press, 1980.
+ *
+ */
+
+/*
+ * Cephes Math Library Release 2.0:  April, 1987
+ * Copyright 1984, 1987 by Stephen L. Moshier
+ * Direct inquiries to 30 Frost Street, Cambridge, MA 02140
+ */
+#pragma once
+
+#include "../config.h"
+#include "../error.h"
+#include "const.h"
+
+namespace xsf {
+namespace cephes {
+
+    namespace detail {
+        /* Expansion coefficients
+         * for Euler-Maclaurin summation formula
+         * (2k)! / B2k
+         * where B2k are Bernoulli numbers
+         */
+        constexpr double zeta_A[] = {
+            12.0,
+            -720.0,
+            30240.0,
+            -1209600.0,
+            47900160.0,
+            -1.8924375803183791606e9, /*1.307674368e12/691 */
+            7.47242496e10,
+            -2.950130727918164224e12,  /*1.067062284288e16/3617 */
+            1.1646782814350067249e14,  /*5.109094217170944e18/43867 */
+            -4.5979787224074726105e15, /*8.028576626982912e20/174611 */
+            1.8152105401943546773e17,  /*1.5511210043330985984e23/854513 */
+            -7.1661652561756670113e18  /*1.6938241367317436694528e27/236364091 */
+        };
+
+        /* 30 Nov 86 -- error in third coefficient fixed */
+    } // namespace detail
+
+    XSF_HOST_DEVICE double inline zeta(double x, double q) {
+        int i;
+        double a, b, k, s, t, w;
+
+        if (x == 1.0)
+            goto retinf;
+
+        if (x < 1.0) {
+        domerr:
+            set_error("zeta", SF_ERROR_DOMAIN, NULL);
+            return (std::numeric_limits::quiet_NaN());
+        }
+
+        if (q <= 0.0) {
+            if (q == floor(q)) {
+                set_error("zeta", SF_ERROR_SINGULAR, NULL);
+            retinf:
+                return (std::numeric_limits::infinity());
+            }
+            if (x != std::floor(x))
+                goto domerr; /* because q^-x not defined */
+        }
+
+        /* Asymptotic expansion
+         * https://dlmf.nist.gov/25.11#E43
+         */
+        if (q > 1e8) {
+            return (1 / (x - 1) + 1 / (2 * q)) * std::pow(q, 1 - x);
+        }
+
+        /* Euler-Maclaurin summation formula */
+
+        /* Permit negative q but continue sum until n+q > +9 .
+         * This case should be handled by a reflection formula.
+         * If q<0 and x is an integer, there is a relation to
+         * the polyGamma function.
+         */
+        s = std::pow(q, -x);
+        a = q;
+        i = 0;
+        b = 0.0;
+        while ((i < 9) || (a <= 9.0)) {
+            i += 1;
+            a += 1.0;
+            b = std::pow(a, -x);
+            s += b;
+            if (std::abs(b / s) < detail::MACHEP)
+                goto done;
+        }
+
+        w = a;
+        s += b * w / (x - 1.0);
+        s -= 0.5 * b;
+        a = 1.0;
+        k = 0.0;
+        for (i = 0; i < 12; i++) {
+            a *= x + k;
+            b /= w;
+            t = a * b / detail::zeta_A[i];
+            s = s + t;
+            t = std::abs(t / s);
+            if (t < detail::MACHEP)
+                goto done;
+            k += 1.0;
+            a *= x + k;
+            b /= w;
+            k += 1.0;
+        }
+    done:
+        return (s);
+    }
+
+} // namespace cephes
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/config.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/config.h
new file mode 100644
index 0000000000000000000000000000000000000000..5cb40ed1e1e095a8c99414f891a697c263845784
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/config.h
@@ -0,0 +1,304 @@
+#pragma once
+
+// Define math constants if they are not available
+#ifndef M_E
+#define M_E 2.71828182845904523536
+#endif
+
+#ifndef M_LOG2E
+#define M_LOG2E 1.44269504088896340736
+#endif
+
+#ifndef M_LOG10E
+#define M_LOG10E 0.434294481903251827651
+#endif
+
+#ifndef M_LN2
+#define M_LN2 0.693147180559945309417
+#endif
+
+#ifndef M_LN10
+#define M_LN10 2.30258509299404568402
+#endif
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+#ifndef M_PI_2
+#define M_PI_2 1.57079632679489661923
+#endif
+
+#ifndef M_PI_4
+#define M_PI_4 0.785398163397448309616
+#endif
+
+#ifndef M_1_PI
+#define M_1_PI 0.318309886183790671538
+#endif
+
+#ifndef M_2_PI
+#define M_2_PI 0.636619772367581343076
+#endif
+
+#ifndef M_2_SQRTPI
+#define M_2_SQRTPI 1.12837916709551257390
+#endif
+
+#ifndef M_SQRT2
+#define M_SQRT2 1.41421356237309504880
+#endif
+
+#ifndef M_SQRT1_2
+#define M_SQRT1_2 0.707106781186547524401
+#endif
+
+#ifdef __CUDACC__
+#define XSF_HOST_DEVICE __host__ __device__
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+// Fallback to global namespace for functions unsupported on NVRTC Jit
+#ifdef _LIBCUDACXX_COMPILER_NVRTC
+#include 
+#endif
+
+namespace std {
+
+XSF_HOST_DEVICE inline double abs(double num) { return cuda::std::abs(num); }
+
+XSF_HOST_DEVICE inline double exp(double num) { return cuda::std::exp(num); }
+
+XSF_HOST_DEVICE inline double log(double num) { return cuda::std::log(num); }
+
+XSF_HOST_DEVICE inline double sqrt(double num) { return cuda::std::sqrt(num); }
+
+XSF_HOST_DEVICE inline bool isinf(double num) { return cuda::std::isinf(num); }
+
+XSF_HOST_DEVICE inline bool isnan(double num) { return cuda::std::isnan(num); }
+
+XSF_HOST_DEVICE inline bool isfinite(double num) { return cuda::std::isfinite(num); }
+
+XSF_HOST_DEVICE inline double pow(double x, double y) { return cuda::std::pow(x, y); }
+
+XSF_HOST_DEVICE inline double sin(double x) { return cuda::std::sin(x); }
+
+XSF_HOST_DEVICE inline double cos(double x) { return cuda::std::cos(x); }
+
+XSF_HOST_DEVICE inline double tan(double x) { return cuda::std::tan(x); }
+
+XSF_HOST_DEVICE inline double atan(double x) { return cuda::std::atan(x); }
+
+XSF_HOST_DEVICE inline double acos(double x) { return cuda::std::acos(x); }
+
+XSF_HOST_DEVICE inline double sinh(double x) { return cuda::std::sinh(x); }
+
+XSF_HOST_DEVICE inline double cosh(double x) { return cuda::std::cosh(x); }
+
+XSF_HOST_DEVICE inline double asinh(double x) { return cuda::std::asinh(x); }
+
+XSF_HOST_DEVICE inline bool signbit(double x) { return cuda::std::signbit(x); }
+
+// Fallback to global namespace for functions unsupported on NVRTC
+#ifndef _LIBCUDACXX_COMPILER_NVRTC
+XSF_HOST_DEVICE inline double ceil(double x) { return cuda::std::ceil(x); }
+XSF_HOST_DEVICE inline double floor(double x) { return cuda::std::floor(x); }
+XSF_HOST_DEVICE inline double round(double x) { return cuda::std::round(x); }
+XSF_HOST_DEVICE inline double trunc(double x) { return cuda::std::trunc(x); }
+XSF_HOST_DEVICE inline double fma(double x, double y, double z) { return cuda::std::fma(x, y, z); }
+XSF_HOST_DEVICE inline double copysign(double x, double y) { return cuda::std::copysign(x, y); }
+XSF_HOST_DEVICE inline double modf(double value, double *iptr) { return cuda::std::modf(value, iptr); }
+XSF_HOST_DEVICE inline double fmax(double x, double y) { return cuda::std::fmax(x, y); }
+XSF_HOST_DEVICE inline double fmin(double x, double y) { return cuda::std::fmin(x, y); }
+XSF_HOST_DEVICE inline double log10(double num) { return cuda::std::log10(num); }
+XSF_HOST_DEVICE inline double log1p(double num) { return cuda::std::log1p(num); }
+XSF_HOST_DEVICE inline double frexp(double num, int *exp) { return cuda::std::frexp(num, exp); }
+XSF_HOST_DEVICE inline double ldexp(double num, int exp) { return cuda::std::ldexp(num, exp); }
+XSF_HOST_DEVICE inline double fmod(double x, double y) { return cuda::std::fmod(x, y); }
+XSF_HOST_DEVICE inline double nextafter(double from, double to) { return cuda::std::nextafter(from, to); }
+#else
+XSF_HOST_DEVICE inline double ceil(double x) { return ::ceil(x); }
+XSF_HOST_DEVICE inline double floor(double x) { return ::floor(x); }
+XSF_HOST_DEVICE inline double round(double x) { return ::round(x); }
+XSF_HOST_DEVICE inline double trunc(double x) { return ::trunc(x); }
+XSF_HOST_DEVICE inline double fma(double x, double y, double z) { return ::fma(x, y, z); }
+XSF_HOST_DEVICE inline double copysign(double x, double y) { return ::copysign(x, y); }
+XSF_HOST_DEVICE inline double modf(double value, double *iptr) { return ::modf(value, iptr); }
+XSF_HOST_DEVICE inline double fmax(double x, double y) { return ::fmax(x, y); }
+XSF_HOST_DEVICE inline double fmin(double x, double y) { return ::fmin(x, y); }
+XSF_HOST_DEVICE inline double log10(double num) { return ::log10(num); }
+XSF_HOST_DEVICE inline double log1p(double num) { return ::log1p(num); }
+XSF_HOST_DEVICE inline double frexp(double num, int *exp) { return ::frexp(num, exp); }
+XSF_HOST_DEVICE inline double ldexp(double num, int exp) { return ::ldexp(num, exp); }
+XSF_HOST_DEVICE inline double fmod(double x, double y) { return ::fmod(x, y); }
+XSF_HOST_DEVICE inline double nextafter(double from, double to) { return ::nextafter(from, to); }
+#endif
+
+template 
+XSF_HOST_DEVICE void swap(T &a, T &b) {
+    cuda::std::swap(a, b);
+}
+
+// Reimplement std::clamp until it's available in CuPy
+template 
+XSF_HOST_DEVICE constexpr T clamp(T &v, T &lo, T &hi) {
+    return v < lo ? lo : (v > hi ? lo : v);
+}
+
+template 
+using numeric_limits = cuda::std::numeric_limits;
+
+// Must use thrust for complex types in order to support CuPy
+template 
+using complex = thrust::complex;
+
+template 
+XSF_HOST_DEVICE T abs(const complex &z) {
+    return thrust::abs(z);
+}
+
+template 
+XSF_HOST_DEVICE complex exp(const complex &z) {
+    return thrust::exp(z);
+}
+
+template 
+XSF_HOST_DEVICE complex log(const complex &z) {
+    return thrust::log(z);
+}
+
+template 
+XSF_HOST_DEVICE T norm(const complex &z) {
+    return thrust::norm(z);
+}
+
+template 
+XSF_HOST_DEVICE complex sqrt(const complex &z) {
+    return thrust::sqrt(z);
+}
+
+template 
+XSF_HOST_DEVICE complex conj(const complex &z) {
+    return thrust::conj(z);
+}
+
+template 
+XSF_HOST_DEVICE complex pow(const complex &x, const complex &y) {
+    return thrust::pow(x, y);
+}
+
+template 
+XSF_HOST_DEVICE complex pow(const complex &x, const T &y) {
+    return thrust::pow(x, y);
+}
+
+// Other types and utilities
+template 
+using is_floating_point = cuda::std::is_floating_point;
+
+template 
+using enable_if = cuda::std::enable_if;
+
+template 
+using decay = cuda::std::decay;
+
+template 
+using invoke_result = cuda::std::invoke_result;
+
+template 
+using pair = cuda::std::pair;
+
+template 
+using tuple = cuda::std::tuple;
+
+using cuda::std::ptrdiff_t;
+using cuda::std::size_t;
+using cuda::std::uint64_t;
+
+#define XSF_ASSERT(a)
+
+} // namespace std
+
+#else
+#define XSF_HOST_DEVICE
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#ifdef DEBUG
+#define XSF_ASSERT(a) assert(a)
+#else
+#define XSF_ASSERT(a)
+#endif
+
+namespace xsf {
+
+// basic
+using std::abs;
+
+// exponential
+using std::exp;
+
+// power
+using std::sqrt;
+
+// trigonometric
+using std::cos;
+using std::sin;
+
+// floating-point manipulation
+using std::copysign;
+
+// classification and comparison
+using std::isfinite;
+using std::isinf;
+using std::isnan;
+using std::signbit;
+
+// complex
+using std::imag;
+using std::real;
+
+template 
+struct remove_complex {
+    using type = T;
+};
+
+template 
+struct remove_complex> {
+    using type = T;
+};
+
+template 
+using remove_complex_t = typename remove_complex::type;
+
+template 
+struct complex_type {
+    using type = std::complex;
+};
+
+template 
+using complex_type_t = typename complex_type::type;
+
+template 
+using complex = complex_type_t;
+
+} // namespace xsf
+
+#endif
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..db51362ce03907ee7c86c0995836e6d5d18160c6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/digamma.h
@@ -0,0 +1,205 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ * Original header comment appears below.
+ */
+
+/* An implementation of the digamma function for complex arguments.
+ *
+ * Author: Josh Wilson
+ *
+ * Distributed under the same license as Scipy.
+ *
+ * Sources:
+ * [1] "The Digital Library of Mathematical Functions", dlmf.nist.gov
+ *
+ * [2] mpmath (version 0.19), http://mpmath.org
+ */
+
+#pragma once
+
+#include "cephes/psi.h"
+#include "cephes/zeta.h"
+#include "config.h"
+#include "error.h"
+#include "trig.h"
+
+namespace xsf {
+namespace detail {
+    // All of the following were computed with mpmath
+    // Location of the positive root
+    constexpr double digamma_posroot = 1.4616321449683623;
+    // Value of the positive root
+    constexpr double digamma_posrootval = -9.2412655217294275e-17;
+    // Location of the negative root
+    constexpr double digamma_negroot = -0.504083008264455409;
+    // Value of the negative root
+    constexpr double digamma_negrootval = 7.2897639029768949e-17;
+
+    template 
+    XSF_HOST_DEVICE T digamma_zeta_series(T z, double root, double rootval) {
+        T res = rootval;
+        T coeff = -1.0;
+
+        z = z - root;
+        T term;
+        for (int n = 1; n < 100; n++) {
+            coeff *= -z;
+            term = coeff * cephes::zeta(n + 1, root);
+            res += term;
+            if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) {
+                break;
+            }
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline std::complex
+    digamma_forward_recurrence(std::complex z, std::complex psiz, int n) {
+        /* Compute digamma(z + n) using digamma(z) using the recurrence
+         * relation
+         *
+         * digamma(z + 1) = digamma(z) + 1/z.
+         *
+         * See https://dlmf.nist.gov/5.5#E2 */
+        std::complex res = psiz;
+
+        for (int k = 0; k < n; k++) {
+            res += 1.0 / (z + static_cast(k));
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline std::complex
+    digamma_backward_recurrence(std::complex z, std::complex psiz, int n) {
+        /* Compute digamma(z - n) using digamma(z) and a recurrence relation. */
+        std::complex res = psiz;
+
+        for (int k = 1; k < n + 1; k++) {
+            res -= 1.0 / (z - static_cast(k));
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline std::complex digamma_asymptotic_series(std::complex z) {
+        /* Evaluate digamma using an asymptotic series. See
+         *
+         * https://dlmf.nist.gov/5.11#E2 */
+        double bernoulli2k[] = {0.166666666666666667,   -0.0333333333333333333, 0.0238095238095238095,
+                                -0.0333333333333333333, 0.0757575757575757576,  -0.253113553113553114,
+                                1.16666666666666667,    -7.09215686274509804,   54.9711779448621554,
+                                -529.124242424242424,   6192.12318840579710,    -86580.2531135531136,
+                                1425517.16666666667,    -27298231.0678160920,   601580873.900642368,
+                                -15116315767.0921569};
+        std::complex rzz = 1.0 / z / z;
+        std::complex zfac = 1.0;
+        std::complex term;
+        std::complex res;
+
+        if (!(std::isfinite(z.real()) && std::isfinite(z.imag()))) {
+            /* Check for infinity (or nan) and return early.
+             * Result of division by complex infinity is implementation dependent.
+             * and has been observed to vary between C++ stdlib and CUDA stdlib.
+             */
+            return std::log(z);
+        }
+
+        res = std::log(z) - 0.5 / z;
+
+        for (int k = 1; k < 17; k++) {
+            zfac *= rzz;
+            term = -bernoulli2k[k - 1] * zfac / (2 * static_cast(k));
+            res += term;
+            if (std::abs(term) < std::numeric_limits::epsilon() * std::abs(res)) {
+                break;
+            }
+        }
+        return res;
+    }
+
+} // namespace detail
+
+XSF_HOST_DEVICE inline double digamma(double z) {
+    /* Wrap Cephes' psi to take advantage of the series expansion around
+     * the smallest negative zero.
+     */
+    if (std::abs(z - detail::digamma_negroot) < 0.3) {
+        return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval);
+    }
+    return cephes::psi(z);
+}
+
+XSF_HOST_DEVICE inline float digamma(float z) { return static_cast(digamma(static_cast(z))); }
+
+XSF_HOST_DEVICE inline std::complex digamma(std::complex z) {
+    /*
+     * Compute the digamma function for complex arguments. The strategy
+     * is:
+     *
+     * - Around the two zeros closest to the origin (posroot and negroot)
+     * use a Taylor series with precomputed zero order coefficient.
+     * - If close to the origin, use a recurrence relation to step away
+     * from the origin.
+     * - If close to the negative real axis, use the reflection formula
+     * to move to the right halfplane.
+     * - If |z| is large (> 16), use the asymptotic series.
+     * - If |z| is small, use a recurrence relation to make |z| large
+     * enough to use the asymptotic series.
+     */
+    double absz = std::abs(z);
+    std::complex res = 0;
+    /* Use the asymptotic series for z away from the negative real axis
+     * with abs(z) > smallabsz. */
+    int smallabsz = 16;
+    /* Use the reflection principle for z with z.real < 0 that are within
+     * smallimag of the negative real axis.
+     * int smallimag = 6  # unused below except in a comment */
+
+    if (z.real() <= 0.0 && std::ceil(z.real()) == z) {
+        // Poles
+        set_error("digamma", SF_ERROR_SINGULAR, NULL);
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+    if (std::abs(z - detail::digamma_negroot) < 0.3) {
+        // First negative root.
+        return detail::digamma_zeta_series(z, detail::digamma_negroot, detail::digamma_negrootval);
+    }
+
+    if (z.real() < 0 and std::abs(z.imag()) < smallabsz) {
+        /* Reflection formula for digamma. See
+         *
+         *https://dlmf.nist.gov/5.5#E4
+         */
+        res = -M_PI * cospi(z) / sinpi(z);
+        z = 1.0 - z;
+        absz = std::abs(z);
+    }
+
+    if (absz < 0.5) {
+        /* Use one step of the recurrence relation to step away from
+         * the pole. */
+        res = -1.0 / z;
+        z += 1.0;
+        absz = std::abs(z);
+    }
+
+    if (std::abs(z - detail::digamma_posroot) < 0.5) {
+        res += detail::digamma_zeta_series(z, detail::digamma_posroot, detail::digamma_posrootval);
+    } else if (absz > smallabsz) {
+        res += detail::digamma_asymptotic_series(z);
+    } else if (z.real() >= 0.0) {
+        double n = std::trunc(smallabsz - absz) + 1;
+        std::complex init = detail::digamma_asymptotic_series(z + n);
+        res += detail::digamma_backward_recurrence(z + n, init, n);
+    } else {
+        // z.real() < 0, absz < smallabsz, and z.imag() > smallimag
+        double n = std::trunc(smallabsz - absz) - 1;
+        std::complex init = detail::digamma_asymptotic_series(z - n);
+        res += detail::digamma_forward_recurrence(z - n, init, n);
+    }
+    return res;
+}
+
+XSF_HOST_DEVICE inline std::complex digamma(std::complex z) {
+    return static_cast>(digamma(static_cast>(z)));
+}
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/error.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/error.h
new file mode 100644
index 0000000000000000000000000000000000000000..7221b5e6c4051b82f80dfb360f9fab896be6a6bd
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/error.h
@@ -0,0 +1,57 @@
+#pragma once
+
+typedef enum {
+    SF_ERROR_OK = 0,    /* no error */
+    SF_ERROR_SINGULAR,  /* singularity encountered */
+    SF_ERROR_UNDERFLOW, /* floating point underflow */
+    SF_ERROR_OVERFLOW,  /* floating point overflow */
+    SF_ERROR_SLOW,      /* too many iterations required */
+    SF_ERROR_LOSS,      /* loss of precision */
+    SF_ERROR_NO_RESULT, /* no result obtained */
+    SF_ERROR_DOMAIN,    /* out of domain */
+    SF_ERROR_ARG,       /* invalid input parameter */
+    SF_ERROR_OTHER,     /* unclassified error */
+    SF_ERROR_MEMORY,    /* memory allocation failed */
+    SF_ERROR__LAST
+} sf_error_t;
+
+#ifdef __cplusplus
+
+#include "config.h"
+
+namespace xsf {
+
+#ifndef SP_SPECFUN_ERROR
+XSF_HOST_DEVICE inline void set_error(const char *func_name, sf_error_t code, const char *fmt, ...) {
+    // nothing
+}
+#else
+void set_error(const char *func_name, sf_error_t code, const char *fmt, ...);
+#endif
+
+template 
+XSF_HOST_DEVICE void set_error_and_nan(const char *name, sf_error_t code, T &value) {
+    if (code != SF_ERROR_OK) {
+        set_error(name, code, nullptr);
+
+        if (code == SF_ERROR_DOMAIN || code == SF_ERROR_OVERFLOW || code == SF_ERROR_NO_RESULT) {
+            value = std::numeric_limits::quiet_NaN();
+        }
+    }
+}
+
+template 
+XSF_HOST_DEVICE void set_error_and_nan(const char *name, sf_error_t code, std::complex &value) {
+    if (code != SF_ERROR_OK) {
+        set_error(name, code, nullptr);
+
+        if (code == SF_ERROR_DOMAIN || code == SF_ERROR_OVERFLOW || code == SF_ERROR_NO_RESULT) {
+            value.real(std::numeric_limits::quiet_NaN());
+            value.imag(std::numeric_limits::quiet_NaN());
+        }
+    }
+}
+
+} // namespace xsf
+
+#endif
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h
new file mode 100644
index 0000000000000000000000000000000000000000..b126fb608fae47620431e05cea21ac66e6847e59
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/evalpoly.h
@@ -0,0 +1,47 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ *
+ * Original author: Josh Wilson, 2016.
+ */
+
+/* Evaluate polynomials.
+ *
+ * All of the coefficients are stored in reverse order, i.e. if the
+ * polynomial is
+ *
+ *     u_n x^n + u_{n - 1} x^{n - 1} + ... + u_0,
+ *
+ * then coeffs[0] = u_n, coeffs[1] = u_{n - 1}, ..., coeffs[n] = u_0.
+ *
+ * References
+ * ----------
+ * [1] Knuth, "The Art of Computer Programming, Volume II"
+ */
+
+#pragma once
+
+#include "config.h"
+
+namespace xsf {
+
+XSF_HOST_DEVICE inline std::complex cevalpoly(const double *coeffs, int degree, std::complex z) {
+    /* Evaluate a polynomial with real coefficients at a complex point.
+     *
+     * Uses equation (3) in section 4.6.4 of [1]. Note that it is more
+     * efficient than Horner's method.
+     */
+    double a = coeffs[0];
+    double b = coeffs[1];
+    double r = 2 * z.real();
+    double s = std::norm(z);
+    double tmp;
+
+    for (int j = 2; j < degree + 1; j++) {
+        tmp = b;
+        b = std::fma(-s, a, coeffs[j]);
+        a = std::fma(r, a, tmp);
+    }
+
+    return z * a + b;
+}
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h
new file mode 100644
index 0000000000000000000000000000000000000000..600448aeb7f7a525aef76d4c59c31fa2489bcb1d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/expint.h
@@ -0,0 +1,266 @@
+/* The functions exp1, expi below are based on translations of the Fortran code
+ * by Shanjie Zhang and Jianming Jin from the book
+ *
+ *  Shanjie Zhang, Jianming Jin,
+ *  Computation of Special Functions,
+ *  Wiley, 1996,
+ *  ISBN: 0-471-11963-6,
+ *  LC: QA351.C45.
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+
+#include "cephes/const.h"
+
+
+namespace xsf {
+
+
+XSF_HOST_DEVICE inline double exp1(double x) {
+    // ============================================
+    // Purpose: Compute exponential integral E1(x)
+    // Input :  x  --- Argument of E1(x)
+    // Output:  E1 --- E1(x)  ( x > 0 )
+    // ============================================
+    int k, m;
+    double e1, r, t, t0;
+    constexpr double ga = cephes::detail::SCIPY_EULER;
+
+    if (x == 0.0) {
+	return std::numeric_limits::infinity();
+    }
+    if (x <= 1.0) {
+        e1 = 1.0;
+        r = 1.0;
+        for (k = 1; k < 26; k++) {
+            r = -r*k*x/std::pow(k+1.0, 2);
+            e1 += r;
+            if (std::abs(r) <= std::abs(e1)*1e-15) { break; }
+        }
+        return -ga - std::log(x) + x*e1;
+    }
+    m = 20 + (int)(80.0/x);
+    t0 = 0.0;
+    for (k = m; k > 0; k--) {
+	t0 = k / (1.0 + k / (x+t0));
+    }
+    t = 1.0 / (x + t0);
+    return std::exp(-x)*t;
+}
+
+XSF_HOST_DEVICE inline float exp1(float x) { return exp1(static_cast(x)); }
+
+XSF_HOST_DEVICE inline std::complex exp1(std::complex z) {
+    // ====================================================
+    // Purpose: Compute complex exponential integral E1(z)
+    // Input :  z   --- Argument of E1(z)
+    // Output:  CE1 --- E1(z)
+    // ====================================================
+    constexpr double el = cephes::detail::SCIPY_EULER;
+    int k;
+    std::complex ce1, cr, zc, zd, zdc;
+    double x = z.real();
+    double a0 = std::abs(z);
+    // Continued fraction converges slowly near negative real axis,
+    // so use power series in a wedge around it until radius 40.0
+    double xt = -2.0*std::abs(z.imag());
+
+    if (a0 == 0.0) { return std::numeric_limits::infinity(); }
+    if ((a0 < 5.0) || ((x < xt) && (a0 < 40.0))) {
+        // Power series
+        ce1 = 1.0;
+        cr = 1.0;
+        for (k = 1; k < 501; k++) {
+            cr = -cr*z*static_cast(k / std::pow(k + 1, 2));
+            ce1 += cr;
+            if (std::abs(cr) < std::abs(ce1)*1e-15) { break; }
+        }
+        if ((x <= 0.0) && (z.imag() == 0.0)) {
+            //Careful on the branch cut -- use the sign of the imaginary part
+            // to get the right sign on the factor if pi.
+            ce1 = -el - std::log(-z) + z*ce1 - std::copysign(M_PI, z.imag())*std::complex(0.0, 1.0);
+        } else {
+            ce1 = -el - std::log(z) + z*ce1;
+        }
+    } else {
+        // Continued fraction https://dlmf.nist.gov/6.9
+        //                  1     1     1     2     2     3     3
+        // E1 = exp(-z) * ----- ----- ----- ----- ----- ----- ----- ...
+        //                Z +   1 +   Z +   1 +   Z +   1 +   Z +
+        zc = 0.0;
+        zd = static_cast(1) / z;
+        zdc = zd;
+        zc += zdc;
+        for (k = 1; k < 501; k++) {
+            zd = static_cast(1) / (zd*static_cast(k) + static_cast(1));
+            zdc *= (zd - static_cast(1));
+            zc += zdc;
+
+            zd = static_cast(1) / (zd*static_cast(k) + z);
+            zdc *= (z*zd - static_cast(1));
+            zc += zdc;
+            if ((std::abs(zdc) <= std::abs(zc)*1e-15) && (k > 20)) { break; }
+        }
+        ce1 = std::exp(-z)*zc;
+        if ((x <= 0.0) && (z.imag() == 0.0)) {
+            ce1 -= M_PI*std::complex(0.0, 1.0);
+        }
+    }
+    return ce1;
+}
+
+XSF_HOST_DEVICE inline std::complex exp1(std::complex z) {
+    return static_cast>(exp1(static_cast>(z)));
+}
+
+XSF_HOST_DEVICE inline double expi(double x) {
+    // ============================================
+    // Purpose: Compute exponential integral Ei(x)
+    // Input :  x  --- Argument of Ei(x)
+    // Output:  EI --- Ei(x)
+    // ============================================
+
+    constexpr double ga = cephes::detail::SCIPY_EULER;
+    double ei, r;
+
+    if (x == 0.0) {
+        ei = -std::numeric_limits::infinity();
+    } else if (x < 0) {
+        ei = -exp1(-x);
+    } else if (std::abs(x) <= 40.0) {
+        // Power series around x=0
+        ei = 1.0;
+        r = 1.0;
+
+        for (int k = 1; k <= 100; k++) {
+            r = r * k * x / ((k + 1.0) * (k + 1.0));
+            ei += r;
+            if (std::abs(r / ei) <= 1.0e-15) { break; }
+        }
+        ei = ga + std::log(x) + x * ei;
+    } else {
+        // Asymptotic expansion (the series is not convergent)
+        ei = 1.0;
+        r = 1.0;
+        for (int k = 1; k <= 20; k++) {
+            r = r * k / x;
+            ei += r;
+        }
+        ei = std::exp(x) / x * ei;
+    }
+    return ei;
+}
+
+XSF_HOST_DEVICE inline float expi(float x) { return expi(static_cast(x)); }
+    
+std::complex expi(std::complex z) {
+    // ============================================
+    // Purpose: Compute exponential integral Ei(x)
+    // Input :  x  --- Complex argument of Ei(x)
+    // Output:  EI --- Ei(x)
+    // ============================================
+
+    std::complex cei;
+    cei = - exp1(-z);
+    if (z.imag() > 0.0) {
+        cei += std::complex(0.0, M_PI);
+    } else if (z.imag() < 0.0 ) {
+        cei -= std::complex(0.0, M_PI);
+    } else {
+        if (z.real() > 0.0) {
+            cei += std::complex(0.0, copysign(M_PI, z.imag()));
+        }
+    }
+    return cei;
+}
+
+
+XSF_HOST_DEVICE inline std::complex expi(std::complex z) {
+    return static_cast>(expi(static_cast>(z)));
+}
+
+namespace detail {
+
+    //
+    // Compute a factor of the exponential integral E1.
+    // This is used in scaled_exp1(x) for moderate values of x.
+    //
+    // The function uses the continued fraction expansion given in equation 5.1.22
+    // of Abramowitz & Stegun, "Handbook of Mathematical Functions".
+    // For n=1, this is
+    //
+    //    E1(x) = exp(-x)*C(x)
+    //
+    // where C(x), expressed in the notation used in A&S, is the continued fraction
+    //
+    //            1    1    1    2    2    3    3
+    //    C(x) = ---  ---  ---  ---  ---  ---  ---  ...
+    //           x +  1 +  x +  1 +  x +  1 +  x +
+    //
+    // Here, we pull a factor of 1/z out of C(x), so
+    //
+    //    E1(x) = (exp(-x)/x)*F(x)
+    //
+    // and a bit of algebra gives the continued fraction expansion of F(x) to be
+    //
+    //            1    1    1    2    2    3    3
+    //    F(x) = ---  ---  ---  ---  ---  ---  ---  ...
+    //           1 +  x +  1 +  x +  1 +  x +  1 +
+    //
+    XSF_HOST_DEVICE inline double expint1_factor_cont_frac(double x) {
+        // The number of terms to use in the truncated continued fraction
+        // depends on x.  Larger values of x require fewer terms.
+        int m = 20 + (int) (80.0 / x);
+        double t0 = 0.0;
+        for (int k = m; k > 0; --k) {
+            t0 = k / (x + k / (1 + t0));
+        }
+        return 1 / (1 + t0);
+    }
+
+} // namespace detail
+
+//
+// Scaled version  of the exponential integral E_1(x).
+//
+// Factor E_1(x) as
+//
+//    E_1(x) = exp(-x)/x * F(x)
+//
+// This function computes F(x).
+//
+// F(x) has the properties:
+//  * F(0) = 0
+//  * F is increasing on [0, inf)
+//  * lim_{x->inf} F(x) = 1.
+//
+XSF_HOST_DEVICE inline double scaled_exp1(double x) {
+    if (x < 0) {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    if (x == 0) {
+        return 0.0;
+    }
+
+    if (x <= 1) {
+        // For small x, the naive implementation is sufficiently accurate.
+        return x * std::exp(x) * exp1(x);
+    }
+
+    if (x <= 1250) {
+        // For moderate x, use the continued fraction expansion.
+        return detail::expint1_factor_cont_frac(x);
+    }
+
+    // For large x, use the asymptotic expansion.  This is equation 5.1.51
+    // from Abramowitz & Stegun, "Handbook of Mathematical Functions".
+    return 1 + (-1 + (2 + (-6 + (24 - 120 / x) / x) / x) / x) / x;
+}
+
+XSF_HOST_DEVICE inline float scaled_exp1(float x) { return scaled_exp1(static_cast(x)); }
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h
new file mode 100644
index 0000000000000000000000000000000000000000..9d4eff7532202380bcd5dbd2978d46d5f613d5eb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/hyp2f1.h
@@ -0,0 +1,694 @@
+/* Implementation of Gauss's hypergeometric function for complex values.
+ *
+ * This implementation is based on the Fortran implementation by Shanjie Zhang and
+ * Jianming Jin included in specfun.f [1]_.  Computation of Gauss's hypergeometric
+ * function involves handling a patchwork of special cases. By default the Zhang and
+ * Jin implementation has been followed as closely as possible except for situations where
+ * an improvement was obvious. We've attempted to document the reasons behind decisions
+ * made by Zhang and Jin and to document the reasons for deviating from their implementation
+ * when this has been done. References to the NIST Digital Library of Mathematical
+ * Functions [2]_ have been added where they are appropriate. The review paper by
+ * Pearson et al [3]_ is an excellent resource for best practices for numerical
+ * computation of hypergeometric functions. We have followed this review paper
+ * when making improvements to and correcting defects in Zhang and Jin's
+ * implementation. When Pearson et al propose several competing alternatives for a
+ * given case, we've used our best judgment to decide on the method to use.
+ *
+ * Author: Albert Steppi
+ *
+ * Distributed under the same license as Scipy.
+ *
+ * References
+ * ----------
+ * .. [1] S. Zhang and J.M. Jin, "Computation of Special Functions", Wiley 1996
+ * .. [2] NIST Digital Library of Mathematical Functions. http://dlmf.nist.gov/,
+ *        Release 1.1.1 of 2021-03-15. F. W. J. Olver, A. B. Olde Daalhuis,
+ *        D. W. Lozier, B. I. Schneider, R. F. Boisvert, C. W. Clark, B. R. Miller,
+ *        B. V. Saunders, H. S. Cohl, and M. A. McClain, eds.
+ * .. [3] Pearson, J.W., Olver, S. & Porter, M.A.
+ *        "Numerical methods for the computation of the confluent and Gauss
+ *        hypergeometric functions."
+ *        Numer Algor 74, 821-866 (2017). https://doi.org/10.1007/s11075-016-0173-0
+ * .. [4] Raimundas Vidunas, "Degenerate Gauss Hypergeometric Functions",
+ *        Kyushu Journal of Mathematics, 2007, Volume 61, Issue 1, Pages 109-135,
+ * .. [5] López, J.L., Temme, N.M. New series expansions of the Gauss hypergeometric
+ *        function. Adv Comput Math 39, 349-365 (2013).
+ *        https://doi.org/10.1007/s10444-012-9283-y
+ * """
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+#include "tools.h"
+
+#include "binom.h"
+#include "cephes/gamma.h"
+#include "cephes/lanczos.h"
+#include "cephes/poch.h"
+#include "cephes/hyp2f1.h"
+#include "digamma.h"
+
+namespace xsf {
+namespace detail {
+    constexpr double hyp2f1_EPS = 1e-15;
+    /* The original implementation in SciPy from Zhang and Jin used 1500 for the
+     * maximum number of series iterations in some cases and 500 in others.
+     * Through the empirical results on the test cases in
+     * scipy/special/_precompute/hyp2f1_data.py, it was determined that these values
+     * can lead to early termination of series which would have eventually converged
+     * at a reasonable level of accuracy. We've bumped the iteration limit to 3000,
+     * and may adjust it again based on further analysis. */
+    constexpr std::uint64_t hyp2f1_MAXITER = 3000;
+
+    XSF_HOST_DEVICE inline double four_gammas_lanczos(double u, double v, double w, double x) {
+        /* Compute ratio of gamma functions using lanczos approximation.
+         *
+         * Computes gamma(u)*gamma(v)/(gamma(w)*gamma(x))
+         *
+         * It is assumed that x = u + v - w, but it is left to the user to
+         * ensure this.
+         *
+         * The lanczos approximation takes the form
+         *
+         * gamma(x) = factor(x) * lanczos_sum_expg_scaled(x)
+         *
+         * where factor(x) = ((x + lanczos_g - 0.5)/e)**(x - 0.5).
+         *
+         * The formula above is only valid for x >= 0.5, but can be extended to
+         * x < 0.5 with the reflection principle.
+         *
+         * Using the lanczos approximation when computing this ratio of gamma functions
+         * allows factors to be combined analytically to avoid underflow and overflow
+         * and produce a more accurate result. The condition x = u + v - w makes it
+         * possible to cancel the factors in the expression
+         *
+         * factor(u) * factor(v) / (factor(w) * factor(x))
+         *
+         * by taking one factor and absorbing it into the others. Currently, this
+         * implementation takes the factor corresponding to the argument with largest
+         * absolute value and absorbs it into the others.
+         *
+         * Since this is only called internally by four_gammas. It is assumed that
+         * |u| >= |v| and |w| >= |x|.
+         */
+
+        /* The below implementation may incorrectly return finite results
+         * at poles of the gamma function. Handle these cases explicitly. */
+        if ((u == std::trunc(u) && u <= 0) || (v == std::trunc(v) && v <= 0)) {
+            /* Return nan if numerator has pole. Diverges to +- infinity
+             * depending on direction so value is undefined. */
+            return std::numeric_limits::quiet_NaN();
+        }
+        if ((w == std::trunc(w) && w <= 0) || (x == std::trunc(x) && x <= 0)) {
+            // Return 0 if denominator has pole but not numerator.
+            return 0.0;
+        }
+
+        double result = 1.0;
+        double ugh, vgh, wgh, xgh, u_prime, v_prime, w_prime, x_prime;
+
+        if (u >= 0.5) {
+            result *= cephes::lanczos_sum_expg_scaled(u);
+            ugh = u + cephes::lanczos_g - 0.5;
+            u_prime = u;
+        } else {
+            result /= cephes::lanczos_sum_expg_scaled(1 - u) * std::sin(M_PI * u) * M_1_PI;
+            ugh = 0.5 - u + cephes::lanczos_g;
+            u_prime = 1 - u;
+        }
+
+        if (v >= 0.5) {
+            result *= cephes::lanczos_sum_expg_scaled(v);
+            vgh = v + cephes::lanczos_g - 0.5;
+            v_prime = v;
+        } else {
+            result /= cephes::lanczos_sum_expg_scaled(1 - v) * std::sin(M_PI * v) * M_1_PI;
+            vgh = 0.5 - v + cephes::lanczos_g;
+            v_prime = 1 - v;
+        }
+
+        if (w >= 0.5) {
+            result /= cephes::lanczos_sum_expg_scaled(w);
+            wgh = w + cephes::lanczos_g - 0.5;
+            w_prime = w;
+        } else {
+            result *= cephes::lanczos_sum_expg_scaled(1 - w) * std::sin(M_PI * w) * M_1_PI;
+            wgh = 0.5 - w + cephes::lanczos_g;
+            w_prime = 1 - w;
+        }
+
+        if (x >= 0.5) {
+            result /= cephes::lanczos_sum_expg_scaled(x);
+            xgh = x + cephes::lanczos_g - 0.5;
+            x_prime = x;
+        } else {
+            result *= cephes::lanczos_sum_expg_scaled(1 - x) * std::sin(M_PI * x) * M_1_PI;
+            xgh = 0.5 - x + cephes::lanczos_g;
+            x_prime = 1 - x;
+        }
+
+        if (std::abs(u) >= std::abs(w)) {
+            // u has greatest absolute value. Absorb ugh into the others.
+            if (std::abs((v_prime - u_prime) * (v - 0.5)) < 100 * ugh and v > 100) {
+                /* Special case where base is close to 1. Condition taken from
+                 * Boost's beta function implementation. */
+                result *= std::exp((v - 0.5) * std::log1p((v_prime - u_prime) / ugh));
+            } else {
+                result *= std::pow(vgh / ugh, v - 0.5);
+            }
+
+            if (std::abs((u_prime - w_prime) * (w - 0.5)) < 100 * wgh and u > 100) {
+                result *= std::exp((w - 0.5) * std::log1p((u_prime - w_prime) / wgh));
+            } else {
+                result *= std::pow(ugh / wgh, w - 0.5);
+            }
+
+            if (std::abs((u_prime - x_prime) * (x - 0.5)) < 100 * xgh and u > 100) {
+                result *= std::exp((x - 0.5) * std::log1p((u_prime - x_prime) / xgh));
+            } else {
+                result *= std::pow(ugh / xgh, x - 0.5);
+            }
+        } else {
+            // w has greatest absolute value. Absorb wgh into the others.
+            if (std::abs((u_prime - w_prime) * (u - 0.5)) < 100 * wgh and u > 100) {
+                result *= std::exp((u - 0.5) * std::log1p((u_prime - w_prime) / wgh));
+            } else {
+                result *= pow(ugh / wgh, u - 0.5);
+            }
+            if (std::abs((v_prime - w_prime) * (v - 0.5)) < 100 * wgh and v > 100) {
+                result *= std::exp((v - 0.5) * std::log1p((v_prime - w_prime) / wgh));
+            } else {
+                result *= std::pow(vgh / wgh, v - 0.5);
+            }
+            if (std::abs((w_prime - x_prime) * (x - 0.5)) < 100 * xgh and x > 100) {
+                result *= std::exp((x - 0.5) * std::log1p((w_prime - x_prime) / xgh));
+            } else {
+                result *= std::pow(wgh / xgh, x - 0.5);
+            }
+        }
+        // This exhausts all cases because we assume |u| >= |v| and |w| >= |x|.
+
+        return result;
+    }
+
+    XSF_HOST_DEVICE inline double four_gammas(double u, double v, double w, double x) {
+        double result;
+
+        // Without loss of generality, ensure |u| >= |v| and |w| >= |x|.
+        if (std::abs(v) > std::abs(u)) {
+            std::swap(u, v);
+        }
+        if (std::abs(x) > std::abs(w)) {
+            std::swap(x, w);
+        }
+        /* Direct ratio tends to be more accurate for arguments in this range. Range
+         * chosen empirically based on the relevant benchmarks in
+         * scipy/special/_precompute/hyp2f1_data.py */
+        if (std::abs(u) <= 100 && std::abs(v) <= 100 && std::abs(w) <= 100 && std::abs(x) <= 100) {
+            result = cephes::Gamma(u) * cephes::Gamma(v) * (cephes::rgamma(w) * cephes::rgamma(x));
+            if (std::isfinite(result) && result != 0.0) {
+                return result;
+            }
+        }
+        result = four_gammas_lanczos(u, v, w, x);
+        if (std::isfinite(result) && result != 0.0) {
+            return result;
+        }
+        // If overflow or underflow, try again with logs.
+        result = std::exp(cephes::lgam(v) - cephes::lgam(x) + cephes::lgam(u) - cephes::lgam(w));
+        result *= cephes::gammasgn(u) * cephes::gammasgn(w) * cephes::gammasgn(v) * cephes::gammasgn(x);
+        return result;
+    }
+
+    class HypergeometricSeriesGenerator {
+        /* Maclaurin series for hyp2f1.
+         *
+         * Series is convergent for |z| < 1 but is only practical for numerical
+         * computation when |z| < 0.9.
+         */
+      public:
+        XSF_HOST_DEVICE HypergeometricSeriesGenerator(double a, double b, double c, std::complex z)
+            : a_(a), b_(b), c_(c), z_(z), term_(1.0), k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex output = term_;
+            term_ = term_ * (a_ + k_) * (b_ + k_) / ((k_ + 1) * (c_ + k_)) * z_;
+            ++k_;
+            return output;
+        }
+
+      private:
+        double a_, b_, c_;
+        std::complex z_, term_;
+        std::uint64_t k_;
+    };
+
+    class Hyp2f1Transform1Generator {
+        /* 1 -z transformation of standard series.*/
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform1Generator(double a, double b, double c, std::complex z)
+            : factor1_(four_gammas(c, c - a - b, c - a, c - b)),
+              factor2_(four_gammas(c, a + b - c, a, b) * std::pow(1.0 - z, c - a - b)),
+              generator1_(HypergeometricSeriesGenerator(a, b, a + b - c + 1, 1.0 - z)),
+              generator2_(HypergeometricSeriesGenerator(c - a, c - b, c - a - b + 1, 1.0 - z)) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            return factor1_ * generator1_() + factor2_ * generator2_();
+        }
+
+      private:
+        std::complex factor1_, factor2_;
+        HypergeometricSeriesGenerator generator1_, generator2_;
+    };
+
+    class Hyp2f1Transform1LimitSeriesGenerator {
+        /* 1 - z transform in limit as c - a - b approaches an integer m. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform1LimitSeriesGenerator(double a, double b, double m, std::complex z)
+            : d1_(xsf::digamma(a)), d2_(xsf::digamma(b)), d3_(xsf::digamma(1 + m)),
+              d4_(xsf::digamma(1.0)), a_(a), b_(b), m_(m), z_(z), log_1_z_(std::log(1.0 - z)),
+              factor_(cephes::rgamma(m + 1)), k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex term_ = (d1_ + d2_ - d3_ - d4_ + log_1_z_) * factor_;
+            // Use digamma(x + 1) = digamma(x) + 1/x
+            d1_ += 1 / (a_ + k_);       // d1 = digamma(a + k)
+            d2_ += 1 / (b_ + k_);       // d2 = digamma(b + k)
+            d3_ += 1 / (1.0 + m_ + k_); // d3 = digamma(1 + m + k)
+            d4_ += 1 / (1.0 + k_);      // d4 = digamma(1 + k)
+            factor_ *= (a_ + k_) * (b_ + k_) / ((k_ + 1.0) * (m_ + k_ + 1)) * (1.0 - z_);
+            ++k_;
+            return term_;
+        }
+
+      private:
+        double d1_, d2_, d3_, d4_, a_, b_, m_;
+        std::complex z_, log_1_z_, factor_;
+        int k_;
+    };
+
+    class Hyp2f1Transform2Generator {
+        /* 1/z transformation of standard series.*/
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2Generator(double a, double b, double c, std::complex z)
+            : factor1_(four_gammas(c, b - a, b, c - a) * std::pow(-z, -a)),
+              factor2_(four_gammas(c, a - b, a, c - b) * std::pow(-z, -b)),
+              generator1_(HypergeometricSeriesGenerator(a, a - c + 1, a - b + 1, 1.0 / z)),
+              generator2_(HypergeometricSeriesGenerator(b, b - c + 1, b - a + 1, 1.0 / z)) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            return factor1_ * generator1_() + factor2_ * generator2_();
+        }
+
+      private:
+        std::complex factor1_, factor2_;
+        HypergeometricSeriesGenerator generator1_, generator2_;
+    };
+
+    class Hyp2f1Transform2LimitSeriesGenerator {
+        /* 1/z transform in limit as a - b approaches a non-negative integer m. (Can swap a and b to
+         * handle the m a negative integer case. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2LimitSeriesGenerator(double a, double b, double c, double m,
+                                                                 std::complex z)
+            : d1_(xsf::digamma(1.0)), d2_(xsf::digamma(1 + m)), d3_(xsf::digamma(a)),
+              d4_(xsf::digamma(c - a)), a_(a), b_(b), c_(c), m_(m), z_(z), log_neg_z_(std::log(-z)),
+              factor_(xsf::cephes::poch(b, m) * xsf::cephes::poch(1 - c + b, m) *
+                      xsf::cephes::rgamma(m + 1)),
+              k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex term = (d1_ + d2_ - d3_ - d4_ + log_neg_z_) * factor_;
+            // Use digamma(x + 1) = digamma(x) + 1/x
+            d1_ += 1 / (1.0 + k_);         // d1 = digamma(1 + k)
+            d2_ += 1 / (1.0 + m_ + k_);    // d2 = digamma(1 + m + k)
+            d3_ += 1 / (a_ + k_);          // d3 = digamma(a + k)
+            d4_ -= 1 / (c_ - a_ - k_ - 1); // d4 = digamma(c - a - k)
+            factor_ *= (b_ + m_ + k_) * (1 - c_ + b_ + m_ + k_) / ((k_ + 1) * (m_ + k_ + 1)) / z_;
+            ++k_;
+            return term;
+        }
+
+      private:
+        double d1_, d2_, d3_, d4_, a_, b_, c_, m_;
+        std::complex z_, log_neg_z_, factor_;
+        std::uint64_t k_;
+    };
+
+    class Hyp2f1Transform2LimitSeriesCminusAIntGenerator {
+        /* 1/z transform in limit as a - b approaches a non-negative integer m, and c - a approaches
+         * a positive integer n. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2LimitSeriesCminusAIntGenerator(double a, double b, double c, double m,
+                                                                           double n, std::complex z)
+            : d1_(xsf::digamma(1.0)), d2_(xsf::digamma(1 + m)), d3_(xsf::digamma(a)),
+              d4_(xsf::digamma(n)), a_(a), b_(b), c_(c), m_(m), n_(n), z_(z), log_neg_z_(std::log(-z)),
+              factor_(xsf::cephes::poch(b, m) * xsf::cephes::poch(1 - c + b, m) *
+                      xsf::cephes::rgamma(m + 1)),
+              k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex term;
+            if (k_ < n_) {
+                term = (d1_ + d2_ - d3_ - d4_ + log_neg_z_) * factor_;
+                // Use digamma(x + 1) = digamma(x) + 1/x
+                d1_ += 1 / (1.0 + k_);    // d1 = digamma(1 + k)
+                d2_ += 1 / (1 + m_ + k_); // d2 = digamma(1 + m + k)
+                d3_ += 1 / (a_ + k_);     // d3 = digamma(a + k)
+                d4_ -= 1 / (n_ - k_ - 1); // d4 = digamma(c - a - k)
+                factor_ *= (b_ + m_ + k_) * (1 - c_ + b_ + m_ + k_) / ((k_ + 1) * (m_ + k_ + 1)) / z_;
+                ++k_;
+                return term;
+            }
+            if (k_ == n_) {
+                /* When c - a approaches a positive integer and k_ >= c - a = n then
+                 * poch(1 - c + b + m + k) = poch(1 - c + a + k) = approaches zero and
+                 * digamma(c - a - k) approaches a pole. However we can use the limit
+                 * digamma(-n + epsilon) / gamma(-n + epsilon) -> (-1)**(n + 1) * (n+1)! as epsilon -> 0
+                 * to continue the series.
+                 *
+                 * poch(1 - c + b, m + k) = gamma(1 - c + b + m + k)/gamma(1 - c + b)
+                 *
+                 * If a - b is an integer and c - a is an integer, then a and b must both be integers, so assume
+                 * a and b are integers and take the limit as c approaches an integer.
+                 *
+                 * gamma(1 - c + epsilon + a + k)/gamma(1 - c - epsilon + b) =
+                 * (gamma(c + epsilon - b) / gamma(c + epsilon - a - k)) *
+                 * (sin(pi * (c + epsilon - b)) / sin(pi * (c + epsilon - a - k))) (reflection principle)
+                 *
+                 * In the limit as epsilon goes to zero, the ratio of sines will approach
+                 * (-1)**(a - b + k) = (-1)**(m + k)
+                 *
+                 * We may then replace
+                 *
+                 * poch(1 - c - epsilon + b, m + k)*digamma(c + epsilon - a - k)
+                 *
+                 * with
+                 *
+                 * (-1)**(a - b + k)*gamma(c + epsilon - b) * digamma(c + epsilon - a - k) / gamma(c + epsilon - a - k)
+                 *
+                 * and taking the limit epsilon -> 0 gives
+                 *
+                 * (-1)**(a - b + k) * gamma(c - b) * (-1)**(k + a - c + 1)(k + a - c)!
+                 * = (-1)**(c - b - 1)*Gamma(k + a - c + 1)
+                 */
+                factor_ = std::pow(-1, m_ + n_) * xsf::binom(c_ - 1, b_ - 1) *
+                          xsf::cephes::poch(c_ - a_ + 1, m_ - 1) / std::pow(z_, static_cast(k_));
+            }
+            term = factor_;
+            factor_ *= (b_ + m_ + k_) * (k_ + a_ - c_ + 1) / ((k_ + 1) * (m_ + k_ + 1)) / z_;
+            ++k_;
+            return term;
+        }
+
+      private:
+        double d1_, d2_, d3_, d4_, a_, b_, c_, m_, n_;
+        std::complex z_, log_neg_z_, factor_;
+        std::uint64_t k_;
+    };
+
+    class Hyp2f1Transform2LimitFinitePartGenerator {
+        /* Initial finite sum in limit as a - b approaches a non-negative integer m. The limiting series
+         * for the 1 - z transform also has an initial finite sum, but it is a standard hypergeometric
+         * series. */
+      public:
+        XSF_HOST_DEVICE Hyp2f1Transform2LimitFinitePartGenerator(double b, double c, double m,
+                                                                     std::complex z)
+            : b_(b), c_(c), m_(m), z_(z), term_(cephes::Gamma(m) * cephes::rgamma(c - b)), k_(0) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            std::complex output = term_;
+            term_ = term_ * (b_ + k_) * (c_ - b_ - k_ - 1) / ((k_ + 1) * (m_ - k_ - 1)) / z_;
+            ++k_;
+            return output;
+        }
+
+      private:
+        double b_, c_, m_;
+        std::complex z_, term_;
+        std::uint64_t k_;
+    };
+
+    class LopezTemmeSeriesGenerator {
+        /* Lopez-Temme Series for Gaussian hypergeometric function [4].
+         *
+         * Converges for all z with real(z) < 1, including in the regions surrounding
+         * the points exp(+- i*pi/3) that are not covered by any of the standard
+         * transformations.
+         */
+      public:
+        XSF_HOST_DEVICE LopezTemmeSeriesGenerator(double a, double b, double c, std::complex z)
+            : n_(0), a_(a), b_(b), c_(c), phi_previous_(1.0), phi_(1 - 2 * b / c), z_(z), Z_(a * z / (z - 2.0)) {}
+
+        XSF_HOST_DEVICE std::complex operator()() {
+            if (n_ == 0) {
+                ++n_;
+                return 1.0;
+            }
+            if (n_ > 1) { // Update phi and Z for n>=2
+                double new_phi = ((n_ - 1) * phi_previous_ - (2.0 * b_ - c_) * phi_) / (c_ + (n_ - 1));
+                phi_previous_ = phi_;
+                phi_ = new_phi;
+                Z_ = Z_ * z_ / (z_ - 2.0) * ((a_ + (n_ - 1)) / n_);
+            }
+            ++n_;
+            return Z_ * phi_;
+        }
+
+      private:
+        std::uint64_t n_;
+        double a_, b_, c_, phi_previous_, phi_;
+        std::complex z_, Z_;
+    };
+
+    XSF_HOST_DEVICE std::complex hyp2f1_transform1_limiting_case(double a, double b, double c, double m,
+                                                                             std::complex z) {
+        /* 1 - z transform in limiting case where c - a - b approaches an integer m. */
+        std::complex result = 0.0;
+        if (m >= 0) {
+            if (m != 0) {
+                auto series_generator = HypergeometricSeriesGenerator(a, b, 1 - m, 1.0 - z);
+                result += four_gammas(m, c, a + m, b + m) * series_eval_fixed_length(series_generator,
+                                                                                     std::complex{0.0, 0.0},
+                                                                                     static_cast(m));
+            }
+            std::complex prefactor = std::pow(-1.0, m + 1) * xsf::cephes::Gamma(c) /
+                                             (xsf::cephes::Gamma(a) * xsf::cephes::Gamma(b)) *
+                                             std::pow(1.0 - z, m);
+            auto series_generator = Hyp2f1Transform1LimitSeriesGenerator(a + m, b + m, m, z);
+            result += prefactor * series_eval(series_generator, std::complex{0.0, 0.0}, hyp2f1_EPS,
+                                              hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        } else {
+            result = four_gammas(-m, c, a, b) * std::pow(1.0 - z, m);
+            auto series_generator1 = HypergeometricSeriesGenerator(a + m, b + m, 1 + m, 1.0 - z);
+            result *= series_eval_fixed_length(series_generator1, std::complex{0.0, 0.0},
+                                               static_cast(-m));
+            double prefactor = std::pow(-1.0, m + 1) * xsf::cephes::Gamma(c) *
+                               (xsf::cephes::rgamma(a + m) * xsf::cephes::rgamma(b + m));
+            auto series_generator2 = Hyp2f1Transform1LimitSeriesGenerator(a, b, -m, z);
+            result += prefactor * series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS,
+                                              hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        }
+    }
+
+    XSF_HOST_DEVICE std::complex hyp2f1_transform2_limiting_case(double a, double b, double c, double m,
+                                                                             std::complex z) {
+        /* 1 / z transform in limiting case where a - b approaches a non-negative integer m. Negative integer case
+         * can be handled by swapping a and b. */
+        auto series_generator1 = Hyp2f1Transform2LimitFinitePartGenerator(b, c, m, z);
+        std::complex result = cephes::Gamma(c) * cephes::rgamma(a) * std::pow(-z, -b);
+        result *=
+            series_eval_fixed_length(series_generator1, std::complex{0.0, 0.0}, static_cast(m));
+        std::complex prefactor = cephes::Gamma(c) * (cephes::rgamma(a) * cephes::rgamma(c - b) * std::pow(-z, -a));
+        double n = c - a;
+        if (abs(n - std::round(n)) < hyp2f1_EPS) {
+            auto series_generator2 = Hyp2f1Transform2LimitSeriesCminusAIntGenerator(a, b, c, m, n, z);
+            result += prefactor * series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS,
+                                              hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        }
+        auto series_generator2 = Hyp2f1Transform2LimitSeriesGenerator(a, b, c, m, z);
+        result += prefactor *
+                  series_eval(series_generator2, std::complex{0.0, 0.0}, hyp2f1_EPS, hyp2f1_MAXITER, "hyp2f1");
+        return result;
+    }
+
+} // namespace detail
+
+XSF_HOST_DEVICE inline std::complex hyp2f1(double a, double b, double c, std::complex z) {
+    /* Special Cases
+     * -----------------------------------------------------------------------
+     * Takes constant value 1 when a = 0 or b = 0, even if c is a non-positive
+     * integer. This follows mpmath. */
+    if (a == 0 || b == 0) {
+        return 1.0;
+    }
+    double z_abs = std::abs(z);
+    // Equals 1 when z i 0, unless c is 0.
+    if (z_abs == 0) {
+        if (c != 0) {
+            return 1.0;
+        } else {
+            // Returning real part NAN and imaginary part 0 follows mpmath.
+            return std::complex{std::numeric_limits::quiet_NaN(), 0};
+        }
+    }
+    bool a_neg_int = a == std::trunc(a) && a < 0;
+    bool b_neg_int = b == std::trunc(b) && b < 0;
+    bool c_non_pos_int = c == std::trunc(c) and c <= 0;
+    /* Diverges when c is a non-positive integer unless a is an integer with
+     * c <= a <= 0 or b is an integer with c <= b <= 0, (or z equals 0 with
+     * c != 0) Cases z = 0, a = 0, or b = 0 have already been handled. We follow
+     * mpmath in handling the degenerate cases where any of a, b, c are
+     * non-positive integers. See [3] for a treatment of degenerate cases. */
+    if (c_non_pos_int && !((a_neg_int && c <= a && a < 0) || (b_neg_int && c <= b && b < 0))) {
+        return std::complex{std::numeric_limits::infinity(), 0};
+    }
+    /* Reduces to a polynomial when a or b is a negative integer.
+     * If a and b are both negative integers, we take care to terminate
+     * the series at a or b of smaller magnitude. This is to ensure proper
+     * handling of situations like a < c < b <= 0, a, b, c all non-positive
+     * integers, where terminating at a would lead to a term of the form 0 / 0. */
+    double max_degree;
+    if (a_neg_int || b_neg_int) {
+        if (a_neg_int && b_neg_int) {
+            max_degree = a > b ? std::abs(a) : std::abs(b);
+        } else if (a_neg_int) {
+            max_degree = std::abs(a);
+        } else {
+            max_degree = std::abs(b);
+        }
+        if (max_degree <= (double) UINT64_MAX) {
+            auto series_generator = detail::HypergeometricSeriesGenerator(a, b, c, z);
+            return detail::series_eval_fixed_length(series_generator, std::complex{0.0, 0.0}, max_degree + 1);
+        } else {
+            set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL);
+            return std::complex{std::numeric_limits::quiet_NaN(),
+                                        std::numeric_limits::quiet_NaN()};
+        }
+    }
+    // Kummer's Theorem for z = -1; c = 1 + a - b (DLMF 15.4.26)
+    if (std::abs(z + 1.0) < detail::hyp2f1_EPS && std::abs(1 + a - b - c) < detail::hyp2f1_EPS && !c_non_pos_int) {
+        return detail::four_gammas(a - b + 1, 0.5 * a + 1, a + 1, 0.5 * a - b + 1);
+    }
+    std::complex result;
+    bool c_minus_a_neg_int = c - a == std::trunc(c - a) && c - a < 0;
+    bool c_minus_b_neg_int = c - b == std::trunc(c - b) && c - b < 0;
+    /* If one of c - a or c - b is a negative integer, reduces to evaluating
+     * a polynomial through an Euler hypergeometric transformation.
+     * (DLMF 15.8.1) */
+    if (c_minus_a_neg_int || c_minus_b_neg_int) {
+        max_degree = c_minus_b_neg_int ? std::abs(c - b) : std::abs(c - a);
+        if (max_degree <= (double) UINT64_MAX) {
+            result = std::pow(1.0 - z, c - a - b);
+            auto series_generator = detail::HypergeometricSeriesGenerator(c - a, c - b, c, z);
+            result *=
+                detail::series_eval_fixed_length(series_generator, std::complex{0.0, 0.0}, max_degree + 2);
+            return result;
+        } else {
+            set_error("hyp2f1", SF_ERROR_NO_RESULT, NULL);
+            return std::complex{std::numeric_limits::quiet_NaN(),
+                                        std::numeric_limits::quiet_NaN()};
+        }
+    }
+    /* Diverges as real(z) -> 1 when c <= a + b.
+     * Todo: Actually check for overflow instead of using a fixed tolerance for
+     * all parameter combinations like in the Fortran original. */
+    if (std::abs(1 - z.real()) < detail::hyp2f1_EPS && z.imag() == 0 && c - a - b <= 0 && !c_non_pos_int) {
+        return std::complex{std::numeric_limits::infinity(), 0};
+    }
+    // Gauss's Summation Theorem for z = 1; c - a - b > 0 (DLMF 15.4.20).
+    if (z == 1.0 && c - a - b > 0 && !c_non_pos_int) {
+        return detail::four_gammas(c, c - a - b, c - a, c - b);
+    }
+    /* |z| < 0, z.real() >= 0. Use the Maclaurin Series.
+     * -----------------------------------------------------------------------
+     * Apply Euler Hypergeometric Transformation (DLMF 15.8.1) to reduce
+     * size of a and b if possible. We follow Zhang and Jin's
+     * implementation [1] although there is very likely a better heuristic
+     * to determine when this transformation should be applied. As it
+     * stands, this hurts precision in some cases. */
+    if (z_abs < 0.9 && z.real() >= 0) {
+        if (c - a < a && c - b < b) {
+            result = std::pow(1.0 - z, c - a - b);
+            auto series_generator = detail::HypergeometricSeriesGenerator(c - a, c - b, c, z);
+            result *= detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                          detail::hyp2f1_MAXITER, "hyp2f1");
+            return result;
+        }
+        auto series_generator = detail::HypergeometricSeriesGenerator(a, b, c, z);
+        return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                   detail::hyp2f1_MAXITER, "hyp2f1");
+    }
+    /* Points near exp(iπ/3), exp(-iπ/3) not handled by any of the standard
+     * transformations. Use series of López and Temme [5]. These regions
+     * were not correctly handled by Zhang and Jin's implementation.
+     * -------------------------------------------------------------------------*/
+    if (0.9 <= z_abs && z_abs < 1.1 && std::abs(1.0 - z) >= 0.9 && z.real() >= 0) {
+        /* This condition for applying Euler Transformation (DLMF 15.8.1)
+         * was determined empirically to work better for this case than that
+         * used in Zhang and Jin's implementation for |z| < 0.9,
+         *  real(z) >= 0. */
+        if ((c - a <= a && c - b < b) || (c - a < a && c - b <= b)) {
+            auto series_generator = detail::LopezTemmeSeriesGenerator(c - a, c - b, c, z);
+            result = std::pow(1.0 - 0.5 * z, a - c); // Lopez-Temme prefactor
+            result *= detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                          detail::hyp2f1_MAXITER, "hyp2f1");
+            return std::pow(1.0 - z, c - a - b) * result; // Euler transform prefactor.
+        }
+        auto series_generator = detail::LopezTemmeSeriesGenerator(a, b, c, z);
+        result = detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                     detail::hyp2f1_MAXITER, "hyp2f1");
+        return std::pow(1.0 - 0.5 * z, -a) * result; // Lopez-Temme prefactor.
+    }
+    /* z/(z - 1) transformation (DLMF 15.8.1). Avoids cancellation issues that
+     * occur with Maclaurin series for real(z) < 0.
+     * -------------------------------------------------------------------------*/
+    if (z_abs < 1.1 && z.real() < 0) {
+        if (0 < b && b < a && a < c) {
+            std::swap(a, b);
+        }
+        auto series_generator = detail::HypergeometricSeriesGenerator(a, c - b, c, z / (z - 1.0));
+        return std::pow(1.0 - z, -a) * detail::series_eval(series_generator, std::complex{0.0, 0.0},
+                                                           detail::hyp2f1_EPS, detail::hyp2f1_MAXITER, "hyp2f1");
+    }
+    /* 1 - z transformation (DLMF 15.8.4). */
+    if (0.9 <= z_abs && z_abs < 1.1) {
+        if (std::abs(c - a - b - std::round(c - a - b)) < detail::hyp2f1_EPS) {
+            // Removable singularity when c - a - b is an integer. Need to use limiting formula.
+            double m = std::round(c - a - b);
+            return detail::hyp2f1_transform1_limiting_case(a, b, c, m, z);
+        }
+        auto series_generator = detail::Hyp2f1Transform1Generator(a, b, c, z);
+        return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                                   detail::hyp2f1_MAXITER, "hyp2f1");
+    }
+    /* 1/z transformation (DLMF 15.8.2). */
+    if (std::abs(a - b - std::round(a - b)) < detail::hyp2f1_EPS) {
+        if (b > a) {
+            std::swap(a, b);
+        }
+        double m = std::round(a - b);
+        return detail::hyp2f1_transform2_limiting_case(a, b, c, m, z);
+    }
+    auto series_generator = detail::Hyp2f1Transform2Generator(a, b, c, z);
+    return detail::series_eval(series_generator, std::complex{0.0, 0.0}, detail::hyp2f1_EPS,
+                               detail::hyp2f1_MAXITER, "hyp2f1");
+}
+
+XSF_HOST_DEVICE inline std::complex hyp2f1(float a, float b, float c, std::complex x) {
+    return static_cast>(hyp2f1(static_cast(a), static_cast(b),
+                                                   static_cast(c), static_cast>(x)));
+}
+
+XSF_HOST_DEVICE inline double hyp2f1(double a, double b, double c, double x) { return cephes::hyp2f1(a, b, c, x); }
+
+XSF_HOST_DEVICE inline float hyp2f1(float a, float b, float c, float x) {
+    return hyp2f1(static_cast(a), static_cast(b), static_cast(c), static_cast(x));
+}
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h
new file mode 100644
index 0000000000000000000000000000000000000000..e5dc871bd003937a483a39001d796b1bacc26d01
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/iv_ratio.h
@@ -0,0 +1,173 @@
+// Numerically stable computation of iv(v+1, x) / iv(v, x)
+
+#pragma once
+
+#include "config.h"
+#include "tools.h"
+#include "error.h"
+#include "cephes/dd_real.h"
+
+namespace xsf {
+
+/* Generates the "tail" of Perron's continued fraction for iv(v,x)/iv(v-1,x).
+ *
+ * The Perron continued fraction is studied in [1].  It is given by
+ *
+ *         iv(v, x)      x    -(2v+1)x   -(2v+3)x   -(2v+5)x
+ *   R := --------- = ------ ---------- ---------- ---------- ...
+ *        iv(v-1,x)   x+2v + 2(v+x)+1 + 2(v+x)+2 + 2(v+x)+3 +
+ *
+ * Given a suitable constant c, the continued fraction may be rearranged
+ * into the following form to avoid premature floating point overflow:
+ *
+ *        xc                -(2vc+c)(xc) -(2vc+3c)(xc) -(2vc+5c)(xc)
+ *   R = -----,  fc = 2vc + ------------ ------------- ------------- ...
+ *       xc+fc              2(vc+xc)+c + 2(vc+xc)+2c + 2(vc+xc)+3c +
+ *
+ * This class generates the fractions of fc after 2vc.
+ *
+ * [1] Gautschi, W. and Slavik, J. (1978). "On the computation of modified
+ *     Bessel function ratios." Mathematics of Computation, 32(143):865-875.
+ */
+template 
+struct IvRatioCFTailGenerator {
+
+    XSF_HOST_DEVICE IvRatioCFTailGenerator(T vc, T xc, T c) noexcept {
+        a0_ = -(2*vc-c)*xc;
+        as_ = -2*c*xc;
+        b0_ = 2*(vc+xc);
+        bs_ = c;
+        k_ = 0;
+    }
+
+    XSF_HOST_DEVICE std::pair operator()() noexcept {
+        using std::fma;
+        ++k_;
+        return {fma(static_cast(k_), as_, a0_),
+                fma(static_cast(k_), bs_, b0_)};
+    }
+
+private:
+    T a0_, as_;  // a[k] == a0 + as*k, k >= 1
+    T b0_, bs_;  // b[k] == b0 + bs*k, k >= 1
+    std::uint64_t k_; // current index
+};
+
+// Computes f(v, x) using Perron's continued fraction.
+//
+// T specifies the working type.  This allows the function to perform
+// calculations in a higher precision, such as double-double, even if
+// the return type is hardcoded to be double.
+template 
+XSF_HOST_DEVICE inline std::pair
+_iv_ratio_cf(double v, double x, bool complement) {
+
+    int e;
+    std::frexp(std::fmax(v, x), &e);
+    T c = T(std::ldexp(1, 2-e)); // rescaling multiplier
+    T vc = v * c;
+    T xc = x * c;
+
+    IvRatioCFTailGenerator cf(vc, xc, c);
+    auto [fc, terms] = detail::series_eval_kahan(
+        detail::continued_fraction_series(cf),
+        T(std::numeric_limits::epsilon()),
+        1000,
+        2*vc);
+
+    T ret = (complement ? fc : xc) / (xc + fc);
+    return {static_cast(ret), terms};
+}
+
+XSF_HOST_DEVICE inline double iv_ratio(double v, double x) {
+
+    if (std::isnan(v) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (v < 0.5 || x < 0) {
+        set_error("iv_ratio", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (std::isinf(v) && std::isinf(x)) {
+        // There is not a unique limit as both v and x tends to infinity.
+        set_error("iv_ratio", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0.0) {
+        return x; // keep sign of x because iv_ratio is an odd function
+    }
+    if (std::isinf(v)) {
+        return 0.0;
+    }
+    if (std::isinf(x)) {
+        return 1.0;
+    }
+
+    auto [ret, terms] = _iv_ratio_cf(v, x, false);
+    if (terms == 0) { // failed to converge; should not happen
+        set_error("iv_ratio", SF_ERROR_NO_RESULT, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    return ret;
+}
+
+XSF_HOST_DEVICE inline float iv_ratio(float v, float x) {
+    return iv_ratio(static_cast(v), static_cast(x));
+}
+
+XSF_HOST_DEVICE inline double iv_ratio_c(double v, double x) {
+
+    if (std::isnan(v) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (v < 0.5 || x < 0) {
+        set_error("iv_ratio_c", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (std::isinf(v) && std::isinf(x)) {
+        // There is not a unique limit as both v and x tends to infinity.
+        set_error("iv_ratio_c", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0.0) {
+        return 1.0;
+    }
+    if (std::isinf(v)) {
+        return 1.0;
+    }
+    if (std::isinf(x)) {
+        return 0.0;
+    }
+
+    if (v >= 1) {
+        // Numerical experiments show that evaluating the Perron c.f.
+        // in double precision is sufficiently accurate if v >= 1.
+        auto [ret, terms] = _iv_ratio_cf(v, x, true);
+        if (terms == 0) { // failed to converge; should not happen
+            set_error("iv_ratio_c", SF_ERROR_NO_RESULT, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+        return ret;
+    } else if (v > 0.5) {
+        // double-double arithmetic is needed for 0.5 < v < 1 to
+        // achieve relative error on the scale of machine precision.
+        using cephes::detail::double_double;
+        auto [ret, terms] = _iv_ratio_cf(v, x, true);
+        if (terms == 0) { // failed to converge; should not happen
+            set_error("iv_ratio_c", SF_ERROR_NO_RESULT, NULL);
+            return std::numeric_limits::quiet_NaN();
+        }
+        return ret;
+    } else {
+        // The previous branch (v > 0.5) also works for v == 0.5, but
+        // the closed-form formula "1 - tanh(x)" is more efficient.
+        double t = std::exp(-2*x);
+        return (2 * t) / (1 + t);
+    }
+}
+
+XSF_HOST_DEVICE inline float iv_ratio_c(float v, float x) {
+    return iv_ratio_c(static_cast(v), static_cast(x));
+}
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h
new file mode 100644
index 0000000000000000000000000000000000000000..9eb1882eaec464b5e5dcf47f2168f9125996a816
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/lambertw.h
@@ -0,0 +1,150 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ * Original header with Copyright information appears below.
+ */
+
+/* Implementation of the Lambert W function [1]. Based on MPMath
+ *  Implementation [2], and documentation [3].
+ *
+ * Copyright: Yosef Meller, 2009
+ * Author email: mellerf@netvision.net.il
+ *
+ * Distributed under the same license as SciPy
+ *
+ *
+ * References:
+ * [1] On the Lambert W function, Adv. Comp. Math. 5 (1996) 329-359,
+ *     available online: https://web.archive.org/web/20230123211413/https://cs.uwaterloo.ca/research/tr/1993/03/W.pdf
+ * [2] mpmath source code,
+ https://github.com/mpmath/mpmath/blob/c5939823669e1bcce151d89261b802fe0d8978b4/mpmath/functions/functions.py#L435-L461
+ * [3]
+ https://web.archive.org/web/20230504171447/https://mpmath.org/doc/current/functions/powers.html#lambert-w-function
+ *
+
+ * TODO: use a series expansion when extremely close to the branch point
+ * at `-1/e` and make sure that the proper branch is chosen there.
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+#include "evalpoly.h"
+
+namespace xsf {
+constexpr double EXPN1 = 0.36787944117144232159553; // exp(-1)
+constexpr double OMEGA = 0.56714329040978387299997; // W(1, 0)
+
+namespace detail {
+    XSF_HOST_DEVICE inline std::complex lambertw_branchpt(std::complex z) {
+        // Series for W(z, 0) around the branch point; see 4.22 in [1].
+        double coeffs[] = {-1.0 / 3.0, 1.0, -1.0};
+        std::complex p = std::sqrt(2.0 * (M_E * z + 1.0));
+
+        return cevalpoly(coeffs, 2, p);
+    }
+
+    XSF_HOST_DEVICE inline std::complex lambertw_pade0(std::complex z) {
+        // (3, 2) Pade approximation for W(z, 0) around 0.
+        double num[] = {12.85106382978723404255, 12.34042553191489361902, 1.0};
+        double denom[] = {32.53191489361702127660, 14.34042553191489361702, 1.0};
+
+        /* This only gets evaluated close to 0, so we don't need a more
+         * careful algorithm that avoids overflow in the numerator for
+         * large z. */
+        return z * cevalpoly(num, 2, z) / cevalpoly(denom, 2, z);
+    }
+
+    XSF_HOST_DEVICE inline std::complex lambertw_asy(std::complex z, long k) {
+        /* Compute the W function using the first two terms of the
+         * asymptotic series. See 4.20 in [1].
+         */
+        std::complex w = std::log(z) + 2.0 * M_PI * k * std::complex(0, 1);
+        return w - std::log(w);
+    }
+
+} // namespace detail
+
+XSF_HOST_DEVICE inline std::complex lambertw(std::complex z, long k, double tol) {
+    double absz;
+    std::complex w;
+    std::complex ew, wew, wewz, wn;
+
+    if (std::isnan(z.real()) || std::isnan(z.imag())) {
+        return z;
+    }
+    if (z.real() == std::numeric_limits::infinity()) {
+        return z + 2.0 * M_PI * k * std::complex(0, 1);
+    }
+    if (z.real() == -std::numeric_limits::infinity()) {
+        return -z + (2.0 * M_PI * k + M_PI) * std::complex(0, 1);
+    }
+    if (z == 0.0) {
+        if (k == 0) {
+            return z;
+        }
+        set_error("lambertw", SF_ERROR_SINGULAR, NULL);
+        return -std::numeric_limits::infinity();
+    }
+    if (z == 1.0 && k == 0) {
+        // Split out this case because the asymptotic series blows up
+        return OMEGA;
+    }
+
+    absz = std::abs(z);
+    // Get an initial guess for Halley's method
+    if (k == 0) {
+        if (std::abs(z + EXPN1) < 0.3) {
+            w = detail::lambertw_branchpt(z);
+        } else if (-1.0 < z.real() && z.real() < 1.5 && std::abs(z.imag()) < 1.0 &&
+                   -2.5 * std::abs(z.imag()) - 0.2 < z.real()) {
+            /* Empirically determined decision boundary where the Pade
+             * approximation is more accurate. */
+            w = detail::lambertw_pade0(z);
+        } else {
+            w = detail::lambertw_asy(z, k);
+        }
+    } else if (k == -1) {
+        if (absz <= EXPN1 && z.imag() == 0.0 && z.real() < 0.0) {
+            w = std::log(-z.real());
+        } else {
+            w = detail::lambertw_asy(z, k);
+        }
+    } else {
+        w = detail::lambertw_asy(z, k);
+    }
+
+    // Halley's method; see 5.9 in [1]
+    if (w.real() >= 0) {
+        // Rearrange the formula to avoid overflow in exp
+        for (int i = 0; i < 100; i++) {
+            ew = std::exp(-w);
+            wewz = w - z * ew;
+            wn = w - wewz / (w + 1.0 - (w + 2.0) * wewz / (2.0 * w + 2.0));
+            if (std::abs(wn - w) <= tol * std::abs(wn)) {
+                return wn;
+            }
+            w = wn;
+        }
+    } else {
+        for (int i = 0; i < 100; i++) {
+            ew = std::exp(w);
+            wew = w * ew;
+            wewz = wew - z;
+            wn = w - wewz / (wew + ew - (w + 2.0) * wewz / (2.0 * w + 2.0));
+            if (std::abs(wn - w) <= tol * std::abs(wn)) {
+                return wn;
+            }
+            w = wn;
+        }
+    }
+
+    set_error("lambertw", SF_ERROR_SLOW, "iteration failed to converge: %g + %gj", z.real(), z.imag());
+    return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+}
+
+XSF_HOST_DEVICE inline std::complex lambertw(std::complex z, long k, float tol) {
+    return static_cast>(
+        lambertw(static_cast>(z), k, static_cast(tol)));
+}
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h
new file mode 100644
index 0000000000000000000000000000000000000000..eaae479b2054177153b8671e7fe3174f1b09f20a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/loggamma.h
@@ -0,0 +1,163 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ * Original header comment appears below.
+ */
+
+/* An implementation of the principal branch of the logarithm of
+ * Gamma. Also contains implementations of Gamma and 1/Gamma which are
+ * easily computed from log-Gamma.
+ *
+ * Author: Josh Wilson
+ *
+ * Distributed under the same license as Scipy.
+ *
+ * References
+ * ----------
+ * [1] Hare, "Computing the Principal Branch of log-Gamma",
+ *     Journal of Algorithms, 1997.
+ *
+ * [2] Julia,
+ *     https://github.com/JuliaLang/julia/blob/master/base/special/gamma.jl
+ */
+
+#pragma once
+
+#include "cephes/gamma.h"
+#include "cephes/rgamma.h"
+#include "config.h"
+#include "error.h"
+#include "evalpoly.h"
+#include "trig.h"
+#include "zlog1.h"
+
+namespace xsf {
+
+namespace detail {
+    constexpr double loggamma_SMALLX = 7;
+    constexpr double loggamma_SMALLY = 7;
+    constexpr double loggamma_HLOG2PI = 0.918938533204672742;      // log(2*pi)/2
+    constexpr double loggamma_LOGPI = 1.1447298858494001741434262; // log(pi)
+    constexpr double loggamma_TAYLOR_RADIUS = 0.2;
+
+    XSF_HOST_DEVICE std::complex loggamma_stirling(std::complex z) {
+        /* Stirling series for log-Gamma
+         *
+         * The coefficients are B[2*n]/(2*n*(2*n - 1)) where B[2*n] is the
+         * (2*n)th Bernoulli number. See (1.1) in [1].
+         */
+        double coeffs[] = {-2.955065359477124183E-2,  6.4102564102564102564E-3, -1.9175269175269175269E-3,
+                           8.4175084175084175084E-4,  -5.952380952380952381E-4, 7.9365079365079365079E-4,
+                           -2.7777777777777777778E-3, 8.3333333333333333333E-2};
+        std::complex rz = 1.0 / z;
+        std::complex rzz = rz / z;
+
+        return (z - 0.5) * std::log(z) - z + loggamma_HLOG2PI + rz * cevalpoly(coeffs, 7, rzz);
+    }
+
+    XSF_HOST_DEVICE std::complex loggamma_recurrence(std::complex z) {
+        /* Backward recurrence relation.
+         *
+         * See Proposition 2.2 in [1] and the Julia implementation [2].
+         *
+         */
+        int signflips = 0;
+        int sb = 0;
+        std::complex shiftprod = z;
+
+        z += 1.0;
+        int nsb;
+        while (z.real() <= loggamma_SMALLX) {
+            shiftprod *= z;
+            nsb = std::signbit(shiftprod.imag());
+            signflips += nsb != 0 && sb == 0 ? 1 : 0;
+            sb = nsb;
+            z += 1.0;
+        }
+        return loggamma_stirling(z) - std::log(shiftprod) - signflips * 2 * M_PI * std::complex(0, 1);
+    }
+
+    XSF_HOST_DEVICE std::complex loggamma_taylor(std::complex z) {
+        /* Taylor series for log-Gamma around z = 1.
+         *
+         * It is
+         *
+         * loggamma(z + 1) = -gamma*z + zeta(2)*z**2/2 - zeta(3)*z**3/3 ...
+         *
+         * where gamma is the Euler-Mascheroni constant.
+         */
+
+        double coeffs[] = {
+            -4.3478266053040259361E-2, 4.5454556293204669442E-2, -4.7619070330142227991E-2, 5.000004769810169364E-2,
+            -5.2631679379616660734E-2, 5.5555767627403611102E-2, -5.8823978658684582339E-2, 6.2500955141213040742E-2,
+            -6.6668705882420468033E-2, 7.1432946295361336059E-2, -7.6932516411352191473E-2, 8.3353840546109004025E-2,
+            -9.0954017145829042233E-2, 1.0009945751278180853E-1, -1.1133426586956469049E-1, 1.2550966952474304242E-1,
+            -1.4404989676884611812E-1, 1.6955717699740818995E-1, -2.0738555102867398527E-1, 2.7058080842778454788E-1,
+            -4.0068563438653142847E-1, 8.2246703342411321824E-1, -5.7721566490153286061E-1};
+
+        z -= 1.0;
+        return z * cevalpoly(coeffs, 22, z);
+    }
+} // namespace detail
+
+XSF_HOST_DEVICE inline double loggamma(double x) {
+    if (x < 0.0) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    return cephes::lgam(x);
+}
+
+XSF_HOST_DEVICE inline float loggamma(float x) { return loggamma(static_cast(x)); }
+
+XSF_HOST_DEVICE inline std::complex loggamma(std::complex z) {
+    // Compute the principal branch of log-Gamma
+
+    if (std::isnan(z.real()) || std::isnan(z.imag())) {
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+    if (z.real() <= 0 and z == std::floor(z.real())) {
+        set_error("loggamma", SF_ERROR_SINGULAR, NULL);
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+    if (z.real() > detail::loggamma_SMALLX || std::abs(z.imag()) > detail::loggamma_SMALLY) {
+        return detail::loggamma_stirling(z);
+    }
+    if (std::abs(z - 1.0) < detail::loggamma_TAYLOR_RADIUS) {
+        return detail::loggamma_taylor(z);
+    }
+    if (std::abs(z - 2.0) < detail::loggamma_TAYLOR_RADIUS) {
+        // Recurrence relation and the Taylor series around 1.
+        return detail::zlog1(z - 1.0) + detail::loggamma_taylor(z - 1.0);
+    }
+    if (z.real() < 0.1) {
+        // Reflection formula; see Proposition 3.1 in [1]
+        double tmp = std::copysign(2 * M_PI, z.imag()) * std::floor(0.5 * z.real() + 0.25);
+        return std::complex(detail::loggamma_LOGPI, tmp) - std::log(sinpi(z)) - loggamma(1.0 - z);
+    }
+    if (std::signbit(z.imag()) == 0) {
+        // z.imag() >= 0 but is not -0.0
+        return detail::loggamma_recurrence(z);
+    }
+    return std::conj(detail::loggamma_recurrence(std::conj(z)));
+}
+
+XSF_HOST_DEVICE inline std::complex loggamma(std::complex z) {
+    return static_cast>(loggamma(static_cast>(z)));
+}
+
+XSF_HOST_DEVICE inline double rgamma(double z) { return cephes::rgamma(z); }
+
+XSF_HOST_DEVICE inline float rgamma(float z) { return rgamma(static_cast(z)); }
+
+XSF_HOST_DEVICE inline std::complex rgamma(std::complex z) {
+    // Compute 1/Gamma(z) using loggamma.
+    if (z.real() <= 0 && z == std::floor(z.real())) {
+        // Zeros at 0, -1, -2, ...
+        return 0.0;
+    }
+    return std::exp(-loggamma(z));
+}
+
+XSF_HOST_DEVICE inline std::complex rgamma(std::complex z) {
+    return static_cast>(rgamma(static_cast>(z)));
+}
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h
new file mode 100644
index 0000000000000000000000000000000000000000..4d26b64e02aa3f65a97d99160047efd76e7f121d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/sici.h
@@ -0,0 +1,200 @@
+/* Translated from Cython into C++ by SciPy developers in 2024.
+ * Original header with Copyright information appears below.
+ */
+
+/* Implementation of sin/cos/sinh/cosh integrals for complex arguments
+ *
+ * Sources
+ * [1] Fredrik Johansson and others. mpmath: a Python library for
+ *     arbitrary-precision floating-point arithmetic (version 0.19),
+ *     December 2013. http://mpmath.org/.
+ * [2] NIST, "Digital Library of Mathematical Functions",
+ *     https://dlmf.nist.gov/
+ */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+
+#include "expint.h"
+#include "cephes/const.h"
+#include "cephes/sici.h"
+#include "cephes/shichi.h"
+
+namespace xsf {
+namespace detail {
+    
+    XSF_HOST_DEVICE inline void sici_power_series(int sgn, std::complex z,
+						       std::complex *s, std::complex *c) {
+	/* DLMF 6.6.5 and 6.6.6. If sgn = -1 computes si/ci, and if sgn = 1
+	 * computes shi/chi.
+	 */        
+	std::complex fac = z;
+	*s = fac;
+	*c = 0;
+	std::complex term1, term2;
+	for (int n = 1; n < 100; n++) {
+	    fac *= static_cast(sgn)*z/(2.0*n);
+	    term2 = fac/(2.0*n);
+	    *c += term2;
+	    fac *= z/(2.0*n + 1.0);
+	    term1 = fac/(2.0*n + 1.0);
+	    *s += term1;
+	    constexpr double tol = std::numeric_limits::epsilon();
+	    if (std::abs(term1) < tol*std::abs(*s) && std::abs(term2) < tol*std::abs(*c)) {
+		break;
+	    }
+	}
+    }
+
+}
+
+    
+XSF_HOST_DEVICE inline int sici(std::complex z,
+				    std::complex *si, std::complex *ci) {
+    /* Compute sin/cos integrals at complex arguments. The algorithm
+     * largely follows that of [1].
+     */
+
+    constexpr double EULER = xsf::cephes::detail::SCIPY_EULER;
+
+    if (z == std::numeric_limits::infinity()) {
+        *si = M_PI_2;
+        *ci = 0;
+        return 0;
+    }
+    if (z == -std::numeric_limits::infinity()) {
+	*si = -M_PI_2;
+        *ci = {0.0, M_PI};
+        return 0;
+    }
+
+    if (std::abs(z) < 0.8) {
+        // Use the series to avoid cancellation in si
+	detail::sici_power_series(-1, z, si, ci);
+
+        if (z == 0.0) {
+            set_error("sici", SF_ERROR_DOMAIN, NULL);
+            *ci = {-std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN()};
+        } else {
+            *ci += EULER + std::log(z);
+	}
+        return 0;
+    }
+    
+    // DLMF 6.5.5/6.5.6 plus DLMF 6.4.4/6.4.6/6.4.7
+    std::complex jz = std::complex(0.0, 1.0) * z;
+    std::complex term1 = expi(jz);
+    std::complex term2 = expi(-jz);
+    *si = std::complex(0.0, -0.5)*(term1 - term2);
+    *ci = 0.5*(term1 + term2);
+    if (z.real() == 0) {
+        if (z.imag() > 0) {
+            *ci += std::complex(0.0, M_PI_2);
+	} else if (z.imag() < 0) {
+            *ci -= std::complex(0.0, M_PI_2);
+	}
+    } else if (z.real() > 0) {
+        *si -= M_PI_2;
+    } else {
+        *si += M_PI_2;
+        if (z.imag() >= 0) {
+            *ci += std::complex(0.0, M_PI);
+        } else {
+            *ci -= std::complex(0.0, M_PI);
+	}
+    }
+    return 0;
+}
+
+XSF_HOST_DEVICE inline int sici(std::complex z,
+				    std::complex *si_f, std::complex *ci_f) {
+    std::complex si;
+    std::complex ci;
+    int res = sici(z, &si, &ci);
+    *si_f = si;
+    *ci_f = ci;
+    return res;
+}
+
+XSF_HOST_DEVICE inline int shichi(std::complex z,
+				       std::complex *shi, std::complex *chi) {
+    /* Compute sinh/cosh integrals at complex arguments. The algorithm
+     * largely follows that of [1].
+     */
+    constexpr double EULER = xsf::cephes::detail::SCIPY_EULER;
+    if (z == std::numeric_limits::infinity()) {
+        *shi = std::numeric_limits::infinity();
+        *chi = std::numeric_limits::infinity();
+        return 0;
+    }
+    if (z == -std::numeric_limits::infinity()) {
+        *shi = -std::numeric_limits::infinity();
+        *chi = std::numeric_limits::infinity();
+        return 0;
+    }
+    if (std::abs(z) < 0.8) {
+        // Use the series to avoid cancellation in shi
+	detail::sici_power_series(1, z, shi, chi);
+        if (z == 0.0) {
+            set_error("shichi", SF_ERROR_DOMAIN, NULL);
+            *chi = {-std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN()};
+        } else {
+            *chi += EULER + std::log(z);
+	}
+	return 0;
+    }
+
+    std::complex term1 = expi(z);
+    std::complex term2 = expi(-z);
+    *shi = 0.5*(term1 - term2);
+    *chi = 0.5*(term1 + term2);
+    if (z.imag() > 0) {
+        *shi -= std::complex(0.0, 0.5*M_PI);
+        *chi += std::complex(0.0, 0.5*M_PI);
+    } else if (z.imag() < 0) {
+        *shi += std::complex(0.0, 0.5*M_PI);
+        *chi -= std::complex(0.0, 0.5*M_PI);
+    } else if (z.real() < 0) {
+        *chi += std::complex(0.0, M_PI);
+    }
+    return 0;
+}
+
+XSF_HOST_DEVICE inline int shichi(std::complex z,
+				    std::complex *shi_f, std::complex *chi_f) {
+    std::complex shi;
+    std::complex chi;
+    int res = shichi(z, &shi, &chi);
+    *shi_f = shi;
+    *chi_f = chi;
+    return res;
+}
+
+XSF_HOST_DEVICE inline int sici(double x, double *si, double *ci) {
+    return cephes::sici(x, si, ci);
+}
+
+XSF_HOST_DEVICE inline int shichi(double x, double *shi, double *chi) {
+    return cephes::shichi(x, shi, chi);
+}
+
+XSF_HOST_DEVICE inline int sici(float x, float *si_f, float *ci_f) {
+    double si;
+    double ci;
+    int res = cephes::sici(x, &si, &ci);
+    *si_f = si;
+    *ci_f = ci;
+    return res;
+}
+
+XSF_HOST_DEVICE inline int shichi(float x, float *shi_f, float *chi_f) {
+    double shi;
+    double chi;
+    int res = cephes::shichi(x, &shi, &chi);
+    *shi_f = shi;
+    *chi_f = chi;
+    return res;
+}
+}
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h
new file mode 100644
index 0000000000000000000000000000000000000000..e349f6a5fb4f45b4718cb746dd7b0b2c1fd23ddd
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/tools.h
@@ -0,0 +1,427 @@
+/* Building blocks for implementing special functions */
+
+#pragma once
+
+#include "config.h"
+#include "error.h"
+
+namespace xsf {
+namespace detail {
+
+    /* Result type of a "generator", a callable object that produces a value
+     * each time it is called.
+     */
+    template 
+    using generator_result_t = typename std::decay::type>::type;
+
+    /* Used to deduce the type of the numerator/denominator of a fraction. */
+    template 
+    struct pair_traits;
+
+    template 
+    struct pair_traits> {
+        using value_type = T;
+    };
+
+    template 
+    using pair_value_t = typename pair_traits::value_type;
+
+    /* Used to extract the "value type" of a complex type. */
+    template 
+    struct real_type {
+        using type = T;
+    };
+
+    template 
+    struct real_type> {
+        using type = T;
+    };
+
+    template 
+    using real_type_t = typename real_type::type;
+
+    // Return NaN, handling both real and complex types.
+    template 
+    XSF_HOST_DEVICE inline typename std::enable_if::value, T>::type maybe_complex_NaN() {
+        return std::numeric_limits::quiet_NaN();
+    }
+
+    template 
+    XSF_HOST_DEVICE inline typename std::enable_if::value, T>::type maybe_complex_NaN() {
+        using V = typename T::value_type;
+        return {std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN()};
+    }
+
+    // Series evaluators.
+    template >
+    XSF_HOST_DEVICE T
+    series_eval(Generator &g, T init_val, real_type_t tol, std::uint64_t max_terms, const char *func_name) {
+        /* Sum an infinite series to a given precision.
+         *
+         * g : a generator of terms for the series.
+         *
+         * init_val : A starting value that terms are added to. This argument determines the
+         *     type of the result.
+         *
+         * tol : relative tolerance for stopping criterion.
+         *
+         * max_terms : The maximum number of terms to add before giving up and declaring
+         *     non-convergence.
+         *
+         * func_name : The name of the function within SciPy where this call to series_eval
+         *     will ultimately be used. This is needed to pass to set_error in case
+         *     of non-convergence.
+         */
+        T result = init_val;
+        T term;
+        for (std::uint64_t i = 0; i < max_terms; ++i) {
+            term = g();
+            result += term;
+            if (std::abs(term) < std::abs(result) * tol) {
+                return result;
+            }
+        }
+        // Exceeded max terms without converging. Return NaN.
+        set_error(func_name, SF_ERROR_NO_RESULT, NULL);
+        return maybe_complex_NaN();
+    }
+
+    template >
+    XSF_HOST_DEVICE T series_eval_fixed_length(Generator &g, T init_val, std::uint64_t num_terms) {
+        /* Sum a fixed number of terms from a series.
+         *
+         * g : a generator of terms for the series.
+         *
+         * init_val : A starting value that terms are added to. This argument determines the
+         *     type of the result.
+         *
+         * max_terms : The number of terms from the series to sum.
+         *
+         */
+        T result = init_val;
+        for (std::uint64_t i = 0; i < num_terms; ++i) {
+            result += g();
+        }
+        return result;
+    }
+
+    /* Performs one step of Kahan summation. */
+    template 
+    XSF_HOST_DEVICE void kahan_step(T &sum, T &comp, T x) {
+        T y = x - comp;
+        T t = sum + y;
+        comp = (t - sum) - y;
+        sum = t;
+    }
+
+    /* Evaluates an infinite series using Kahan summation.
+     *
+     * Denote the series by
+     *
+     *   S = a[0] + a[1] + a[2] + ...
+     *
+     * And for n = 0, 1, 2, ..., denote its n-th partial sum by
+     *
+     *   S[n] = a[0] + a[1] + ... + a[n]
+     *
+     * This function computes S[0], S[1], ... until a[n] is sufficiently
+     * small or if the maximum number of terms have been evaluated.
+     *
+     * Parameters
+     * ----------
+     *   g
+     *       Reference to generator that yields the sequence of values a[1],
+     *       a[2], a[3], ...
+     *
+     *   tol
+     *       Relative tolerance for convergence.  Specifically, stop iteration
+     *       as soon as `abs(a[n]) <= tol * abs(S[n])` for some n >= 1.
+     *
+     *   max_terms
+     *       Maximum number of terms after a[0] to evaluate.  It should be set
+     *       large enough such that the convergence criterion is guaranteed
+     *       to have been satisfied within that many terms if there is no
+     *       rounding error.
+     *
+     *   init_val
+     *       a[0].  Default is zero.  The type of this parameter (T) is used
+     *       for intermediary computations as well as the result.
+     *
+     * Return Value
+     * ------------
+     * If the convergence criterion is satisfied by some `n <= max_terms`,
+     * returns `(S[n], n)`.  Otherwise, returns `(S[max_terms], 0)`.
+     */
+    template >
+    XSF_HOST_DEVICE std::pair
+    series_eval_kahan(Generator &&g, real_type_t tol, std::uint64_t max_terms, T init_val = T(0)) {
+
+        using std::abs;
+        T sum = init_val;
+        T comp = T(0);
+        for (std::uint64_t i = 0; i < max_terms; ++i) {
+            T term = g();
+            kahan_step(sum, comp, term);
+            if (abs(term) <= tol * abs(sum)) {
+                return {sum, i + 1};
+            }
+        }
+        return {sum, 0};
+    }
+
+    /* Generator that yields the difference of successive convergents of a
+     * continued fraction.
+     *
+     * Let f[n] denote the n-th convergent of a continued fraction:
+     *
+     *                 a[1]   a[2]       a[n]
+     *   f[n] = b[0] + ------ ------ ... ----
+     *                 b[1] + b[2] +     b[n]
+     *
+     * with f[0] = b[0].  This generator yields the sequence of values
+     * f[1]-f[0], f[2]-f[1], f[3]-f[2], ...
+     *
+     * Constructor Arguments
+     * ---------------------
+     *   cf
+     *       Reference to generator that yields the terms of the continued
+     *       fraction as (numerator, denominator) pairs, starting from
+     *       (a[1], b[1]).
+     *
+     *       `cf` must outlive the ContinuedFractionSeriesGenerator object.
+     *
+     *       The constructed object always eagerly retrieves the next term
+     *       of the continued fraction.  Specifically, (a[1], b[1]) is
+     *       retrieved upon construction, and (a[n], b[n]) is retrieved after
+     *       (n-1) calls of `()`.
+     *
+     * Type Arguments
+     * --------------
+     *   T
+     *       Type in which computations are performed and results are turned.
+     *
+     * Remarks
+     * -------
+     * The series is computed using the recurrence relation described in [1].
+     * Let v[n], n >= 1 denote the terms of the series.  Then
+     *
+     *   v[1] = a[1] / b[1]
+     *   v[n] = v[n-1] * r[n-1], n >= 2
+     *
+     * where
+     *
+     *                              -(a[n] + a[n] * r[n-1])
+     *   r[1] = 0,  r[n] = ------------------------------------------, n >= 2
+     *                      (a[n] + a[n] * r[n-1]) + (b[n] * b[n-1])
+     *
+     * No error checking is performed.  The caller must ensure that all terms
+     * are finite and that intermediary computations do not trigger floating
+     * point exceptions such as overflow.
+     *
+     * The numerical stability of this method depends on the characteristics
+     * of the continued fraction being evaluated.
+     *
+     * Reference
+     * ---------
+     * [1] Gautschi, W. (1967). “Computational Aspects of Three-Term
+     *     Recurrence Relations.” SIAM Review, 9(1):24-82.
+     */
+    template >>
+    class ContinuedFractionSeriesGenerator {
+
+      public:
+        XSF_HOST_DEVICE explicit ContinuedFractionSeriesGenerator(Generator &cf) : cf_(cf) { init(); }
+
+        XSF_HOST_DEVICE T operator()() {
+            T v = v_;
+            advance();
+            return v;
+        }
+
+      private:
+        XSF_HOST_DEVICE void init() {
+            auto [num, denom] = cf_();
+            T a = num;
+            T b = denom;
+            r_ = T(0);
+            v_ = a / b;
+            b_ = b;
+        }
+
+        XSF_HOST_DEVICE void advance() {
+            auto [num, denom] = cf_();
+            T a = num;
+            T b = denom;
+            T p = a + a * r_;
+            T q = p + b * b_;
+            r_ = -p / q;
+            v_ = v_ * r_;
+            b_ = b;
+        }
+
+        Generator &cf_; // reference to continued fraction generator
+        T v_;           // v[n] == f[n] - f[n-1], n >= 1
+        T r_;           // r[1] = 0, r[n] = v[n]/v[n-1], n >= 2
+        T b_;           // last denominator, i.e. b[n-1]
+    };
+
+    /* Converts a continued fraction into a series whose terms are the
+     * difference of its successive convergents.
+     *
+     * See ContinuedFractionSeriesGenerator for details.
+     */
+    template >>
+    XSF_HOST_DEVICE ContinuedFractionSeriesGenerator continued_fraction_series(Generator &cf) {
+        return ContinuedFractionSeriesGenerator(cf);
+    }
+
+    /* Find initial bracket for a bracketing scalar root finder. A valid bracket is a pair of points a < b for
+     * which the signs of f(a) and f(b) differ. If f(x0) = 0, where x0 is the initial guess, this bracket finder
+     * will return the bracket (x0, x0). It is expected that the rootfinder will check if the bracket
+     * endpoints are roots.
+     *
+     * This is a private function intended specifically for the situation where
+     * the goal is to invert a CDF function F for a parametrized family of distributions with respect to one
+     * parameter, when the other parameters are known, and where F is monotonic with respect to the unknown parameter.
+     */
+    template 
+    XSF_HOST_DEVICE inline std::tuple bracket_root_for_cdf_inversion(
+        Function func, double x0, double xmin, double xmax, double step0_left,
+        double step0_right, double factor_left, double factor_right, bool increasing, std::uint64_t maxiter
+    ) {
+        double y0 = func(x0);
+
+        if (y0 == 0) {
+            // Initial guess is correct.
+            return {x0, x0, y0, y0, 0};
+        }
+
+        double y0_sgn = std::signbit(y0);
+
+        bool search_left;
+        /* The frontier is the new leading endpoint of the expanding bracket. The
+         * interior endpoint trails behind the frontier. In each step, the old frontier
+         * endpoint becomes the new interior endpoint. */
+        double interior, frontier, y_interior, y_frontier, y_interior_sgn, y_frontier_sgn, boundary, factor;
+        if ((increasing && y0 < 0) || (!increasing && y0 > 0)) {
+            /* If func is increasing  and func(x_right) < 0 or if func is decreasing and
+             *  f(y_right) > 0, we should expand the bracket to the right. */
+            interior = x0, y_interior = y0;
+            frontier = x0 + step0_right;
+            y_interior_sgn = y0_sgn;
+            search_left = false;
+            boundary = xmax;
+            factor = factor_right;
+        } else {
+            /* Otherwise we move and expand the bracket to the left. */
+            interior = x0, y_interior = y0;
+            frontier = x0 + step0_left;
+            y_interior_sgn = y0_sgn;
+            search_left = true;
+            boundary = xmin;
+            factor = factor_left;
+        }
+
+        bool reached_boundary = false;
+        for (std::uint64_t i = 0; i < maxiter; i++) {
+            y_frontier = func(frontier);
+            y_frontier_sgn = std::signbit(y_frontier);
+            if (y_frontier_sgn != y_interior_sgn || (y_frontier == 0.0)) {
+                /* Stopping condition, func evaluated at endpoints of bracket has opposing signs,
+                 * meeting requirement for bracketing root finder. (Or endpoint has reached a
+                 * zero.) */
+                if (search_left) {
+                    /* Ensure we return an interval (a, b) with a < b. */
+                    std::swap(interior, frontier);
+                    std::swap(y_interior, y_frontier);
+                }
+		return {interior, frontier, y_interior, y_frontier, 0};
+            }
+            if (reached_boundary) {
+                /* We've reached a boundary point without finding a root . */
+                return {
+                    std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(),
+                    std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(),
+                    search_left ? 1 : 2
+                };
+            }
+            double step = (frontier - interior) * factor;
+            interior = frontier;
+            y_interior = y_frontier;
+            y_interior_sgn = y_frontier_sgn;
+            frontier += step;
+            if ((search_left && frontier <= boundary) || (!search_left && frontier >= boundary)) {
+                /* If the frontier has reached the boundary, set a flag so the algorithm will know
+                 * not to search beyond this point. */
+                frontier = boundary;
+                reached_boundary = true;
+            }
+        }
+        /* Failed to converge within maxiter iterations. If maxiter is sufficiently high and
+         * factor_left and factor_right are set appropriately, this should only happen due to
+         * a bug in this function. Limiting the number of iterations is a defensive programming measure. */
+	return {
+            std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(),
+            std::numeric_limits::quiet_NaN(), std::numeric_limits::quiet_NaN(), 3
+        };
+    }
+
+    /* Find root of a scalar function using Chandrupatla's algorithm */
+    template 
+    XSF_HOST_DEVICE inline std::pair find_root_chandrupatla(
+        Function func, double x1, double x2, double f1, double f2, double rtol,
+        double atol, std::uint64_t maxiter
+    ) {
+        if (f1 == 0) {
+            return {x1, 0};
+        }
+        if (f2 == 0) {
+            return {x2, 0};
+        }
+        double t = 0.5, x3, f3;
+        for (uint64_t i = 0; i < maxiter; i++) {
+            double x = x1 + t * (x2 - x1);
+            double f = func(x);
+            if (std::signbit(f) == std::signbit(f1)) {
+                x3 = x1;
+                x1 = x;
+                f3 = f1;
+                f1 = f;
+            } else {
+                x3 = x2;
+                x2 = x1;
+                x1 = x;
+                f3 = f2;
+                f2 = f1;
+                f1 = f;
+            }
+            double xm, fm;
+            if (std::abs(f2) < std::abs(f1)) {
+                xm = x2;
+                fm = f2;
+            } else {
+                xm = x1;
+                fm = f1;
+            }
+            double tol = 2.0 * rtol * std::abs(xm) + 0.5 * atol;
+            double tl = tol / std::abs(x2 - x1);
+            if (tl > 0.5 || fm == 0) {
+                return {xm, 0};
+            }
+            double xi = (x1 - x2) / (x3 - x2);
+            double phi = (f1 - f2) / (f3 - f2);
+            double fl = 1.0 - std::sqrt(1.0 - xi);
+            double fh = std::sqrt(xi);
+
+            if ((fl < phi) && (phi < fh)) {
+                t = (f1 / (f2 - f1)) * (f3 / (f2 - f3)) + (f1 / (f3 - f1)) * (f2 / (f3 - f2)) * ((x3 - x1) / (x2 - x1));
+            } else {
+                t = 0.5;
+            }
+            t = std::fmin(std::fmax(t, tl), 1.0 - tl);
+        }
+        return {std::numeric_limits::quiet_NaN(), 1};
+    }
+
+} // namespace detail
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h
new file mode 100644
index 0000000000000000000000000000000000000000..a0221e00bbe358519c1586eb539310a5be6cddd1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/trig.h
@@ -0,0 +1,164 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ *
+ * Original author: Josh Wilson, 2016.
+ */
+
+/* Implement sin(pi*z) and cos(pi*z) for complex z. Since the periods
+ * of these functions are integral (and thus better representable in
+ * floating point), it's possible to compute them with greater accuracy
+ * than sin(z), cos(z).
+ */
+
+#pragma once
+
+#include "cephes/sindg.h"
+#include "cephes/tandg.h"
+#include "cephes/trig.h"
+#include "cephes/unity.h"
+#include "config.h"
+#include "evalpoly.h"
+
+namespace xsf {
+
+template 
+XSF_HOST_DEVICE T sinpi(T x) {
+    return cephes::sinpi(x);
+}
+
+template 
+XSF_HOST_DEVICE std::complex sinpi(std::complex z) {
+    T x = z.real();
+    T piy = M_PI * z.imag();
+    T abspiy = std::abs(piy);
+    T sinpix = cephes::sinpi(x);
+    T cospix = cephes::cospi(x);
+
+    if (abspiy < 700) {
+        return {sinpix * std::cosh(piy), cospix * std::sinh(piy)};
+    }
+
+    /* Have to be careful--sinh/cosh could overflow while cos/sin are small.
+     * At this large of values
+     *
+     * cosh(y) ~ exp(y)/2
+     * sinh(y) ~ sgn(y)*exp(y)/2
+     *
+     * so we can compute exp(y/2), scale by the right factor of sin/cos
+     * and then multiply by exp(y/2) to avoid overflow. */
+    T exphpiy = std::exp(abspiy / 2);
+    T coshfac;
+    T sinhfac;
+    if (exphpiy == std::numeric_limits::infinity()) {
+        if (sinpix == 0.0) {
+            // Preserve the sign of zero.
+            coshfac = std::copysign(0.0, sinpix);
+        } else {
+            coshfac = std::copysign(std::numeric_limits::infinity(), sinpix);
+        }
+        if (cospix == 0.0) {
+            // Preserve the sign of zero.
+            sinhfac = std::copysign(0.0, cospix);
+        } else {
+            sinhfac = std::copysign(std::numeric_limits::infinity(), cospix);
+        }
+        return {coshfac, sinhfac};
+    }
+
+    coshfac = 0.5 * sinpix * exphpiy;
+    sinhfac = 0.5 * cospix * exphpiy;
+    return {coshfac * exphpiy, sinhfac * exphpiy};
+}
+
+template 
+XSF_HOST_DEVICE T cospi(T x) {
+    return cephes::cospi(x);
+}
+
+template 
+XSF_HOST_DEVICE std::complex cospi(std::complex z) {
+    T x = z.real();
+    T piy = M_PI * z.imag();
+    T abspiy = std::abs(piy);
+    T sinpix = cephes::sinpi(x);
+    T cospix = cephes::cospi(x);
+
+    if (abspiy < 700) {
+        return {cospix * std::cosh(piy), -sinpix * std::sinh(piy)};
+    }
+
+    // See csinpi(z) for an idea of what's going on here.
+    T exphpiy = std::exp(abspiy / 2);
+    T coshfac;
+    T sinhfac;
+    if (exphpiy == std::numeric_limits::infinity()) {
+        if (sinpix == 0.0) {
+            // Preserve the sign of zero.
+            coshfac = std::copysign(0.0, cospix);
+        } else {
+            coshfac = std::copysign(std::numeric_limits::infinity(), cospix);
+        }
+        if (cospix == 0.0) {
+            // Preserve the sign of zero.
+            sinhfac = std::copysign(0.0, sinpix);
+        } else {
+            sinhfac = std::copysign(std::numeric_limits::infinity(), sinpix);
+        }
+        return {coshfac, sinhfac};
+    }
+
+    coshfac = 0.5 * cospix * exphpiy;
+    sinhfac = 0.5 * sinpix * exphpiy;
+    return {coshfac * exphpiy, sinhfac * exphpiy};
+}
+
+template 
+XSF_HOST_DEVICE T sindg(T x) {
+    return cephes::sindg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float sindg(float x) {
+    return sindg(static_cast(x));
+}
+
+template 
+XSF_HOST_DEVICE T cosdg(T x) {
+    return cephes::cosdg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float cosdg(float x) {
+    return cosdg(static_cast(x));
+}
+
+template 
+XSF_HOST_DEVICE T tandg(T x) {
+    return cephes::tandg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float tandg(float x) {
+    return tandg(static_cast(x));
+}
+
+template 
+XSF_HOST_DEVICE T cotdg(T x) {
+    return cephes::cotdg(x);
+}
+
+template <>
+XSF_HOST_DEVICE inline float cotdg(float x) {
+    return cotdg(static_cast(x));
+}
+
+inline double radian(double d, double m, double s) { return cephes::radian(d, m, s); }
+
+inline float radian(float d, float m, float s) {
+    return radian(static_cast(d), static_cast(m), static_cast(s));
+}
+
+inline double cosm1(double x) { return cephes::cosm1(x); }
+
+inline float cosm1(float x) { return cosm1(static_cast(x)); }
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h
new file mode 100644
index 0000000000000000000000000000000000000000..77cf165a0fc303a2ee425dff7083889908dcf887
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/wright_bessel.h
@@ -0,0 +1,843 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ * Original header with Copyright information appears below.
+ */
+
+/* Implementation of Wright's generalized Bessel function Phi, see
+ * https://dlmf.nist.gov/10.46.E1
+ *
+ * Copyright: Christian Lorentzen
+ *
+ * Distributed under the same license as SciPy
+ *
+ *
+ * Implementation Overview:
+ *
+ * First, different functions are implemented valid for certain domains of the
+ * three arguments.
+ * Finally they are put together in wright_bessel. See the docstring of
+ * that function for more details.
+ */
+
+#pragma once
+
+#include "cephes/lanczos.h"
+#include "cephes/polevl.h"
+#include "cephes/rgamma.h"
+#include "config.h"
+#include "digamma.h"
+#include "error.h"
+
+namespace xsf {
+
+namespace detail {
+    // rgamma_zero: smallest value x for which rgamma(x) == 0 as x gets large
+    constexpr double rgamma_zero = 178.47241115886637;
+
+    XSF_HOST_DEVICE inline double exp_rgamma(double x, double y) {
+        /* Compute exp(x) / gamma(y) = exp(x) * rgamma(y).
+         *
+         * This helper function avoids overflow by using the lanczos
+         * approximation of the gamma function.
+         */
+        return std::exp(x + (1 - std::log(y + cephes::lanczos_g - 0.5)) * (y - 0.5)) /
+               cephes::lanczos_sum_expg_scaled(y);
+    }
+
+    XSF_HOST_DEVICE inline double wb_series(double a, double b, double x, unsigned int nstart, unsigned int nstop) {
+        /* 1. Taylor series expansion in x=0 for x <= 1.
+         *
+         * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b)
+         *
+         * Note that every term, and therefore also Phi(a, b, x) is
+         * monotone decreasing with increasing a or b.
+         */
+        double xk_k = std::pow(x, nstart) * cephes::rgamma(nstart + 1); // x^k/k!
+        double res = xk_k * cephes::rgamma(nstart * a + b);
+        // term k=nstart+1, +2, +3, ...
+        if (nstop > nstart) {
+            // series expansion until term k such that a*k+b <= rgamma_zero
+            unsigned int k_max = std::floor((rgamma_zero - b) / a);
+            if (nstop > k_max) {
+                nstop = k_max;
+            }
+            for (unsigned int k = nstart + 1; k < nstop; k++) {
+                xk_k *= x / k;
+                res += xk_k * cephes::rgamma(a * k + b);
+            }
+        }
+        return res;
+    }
+
+    template
+    XSF_HOST_DEVICE inline double wb_large_a(double a, double b, double x, int n) {
+        /* 2. Taylor series expansion in x=0, for large a.
+         *
+         * Phi(a, b, x) = sum_k x^k / k! / Gamma(a*k + b)
+         *
+         * Use Stirling's formula to find k=k_max, the maximum term.
+         * Then use n terms of Taylor series around k_max.
+         */
+        int k_max = static_cast(std::pow(std::pow(a, -a) * x, 1.0 / (1 + a)));
+
+        int nstart = k_max - n / 2;
+        if (nstart < 0) {
+            nstart = 0;
+        }
+
+        double res = 0;
+        double lnx = std::log(x);
+        // For numerical stability, we factor out the maximum term exp(..) with k=k_max
+        // but only if it is larger than 0.
+        double max_exponent = std::fmax(0, k_max * lnx - cephes::lgam(k_max + 1) - cephes::lgam(a * k_max + b));
+        for (int k = nstart; k < nstart + n; k++) {
+            res += std::exp(k * lnx - cephes::lgam(k + 1) - cephes::lgam(a * k + b) - max_exponent);
+        }
+
+        if (!log_wb) {
+            res *= std::exp(max_exponent);
+        } else {
+            // logarithm of Wright's function
+            res = max_exponent + std::log(res);
+        }
+        return res;
+    }
+
+    template
+    XSF_HOST_DEVICE inline double wb_small_a(double a, double b, double x, int order) {
+        /* 3. Taylor series in a=0 up to order 5, for tiny a and not too large x
+         *
+         * Phi(a, b, x) = exp(x)/Gamma(b)
+                          * (1 - a*x * Psi(b) + a^2/2*x*(1+x) * (Psi(b)^2 - Psi'(b)
+                             + ... )
+                          + O(a^6))
+         *
+         * where Psi is the digamma function.
+         *
+         * Parameter order takes effect only when b > 1e-3 and 2 <= order <= 5,
+         * otherwise it defaults to 2, or if b <= 1e-3, to 5. The lower order is,
+         * the fewer polygamma functions have to be computed.
+         *
+         * Call: python _precompute/wright_bessel.py 1
+         *
+         * For small b, i.e. b <= 1e-3, cancellation of poles of digamma(b)/Gamma(b)
+         * and polygamma needs to be carried out => series expansion in a=0 to order 5
+         * and in b=0 to order 4.
+         * Call: python _precompute/wright_bessel.py 2
+         */
+        double A[6]; // coefficients of a^k  (1, -x * Psi(b), ...)
+        double B[6]; // powers of b^k/k! or terms in polygamma functions
+        constexpr double C[5] = {  // coefficients of a^k1 * b^k2
+            1.0000000000000000,   // C[0]
+            1.1544313298030657,   // C[1]
+            -3.9352684291215233,  // C[2]
+            -1.0080632408182857,  // C[3]
+            19.984633365874979,   // C[4]
+        };
+        double X[6] = {  // polynomials in x;
+            1,  // X[0]
+            x,  // X[1]
+            x * (x + 1),  // X[2]
+            x * (x * (x + 3) + 1),  // X[3]
+            x * (x * (x * (x + 6) + 7) + 1),  // X[4]
+            x * (x * (x * (x * (x + 10) + 25) + 15) + 1),  // X[5]
+        };
+        double res;
+
+        if (b <= 1E-3) {
+            /* Series expansion of both a and b up to order 5:
+             * M_PI = pi
+             * M_EG = Euler Gamma aka Euler Mascheroni constant
+             * M_Z3 = zeta(3)
+             * C[0] = 1
+             * C[1] = 2*M_EG
+             * C[2] = 3*M_EG^2 - M_PI^2/2
+             * C[3] = 4*M_EG^3 - 2*M_EG*M_PI^2 + 8*M_Z3
+             * C[4] = 5*M_EG^4 - 5*M_EG^2*M_PI^2 + 40*M_EG*M_Z3 + M_PI^4/12
+             */
+            B[0] = 1.;
+            for (int k = 1; k < 5; k++) {
+                B[k] = b / k * B[k - 1];
+            }
+            // Note that polevl assumes inverse ordering => A[5] = 0th term
+            A[5] = cephes::rgamma(b);
+            A[4] = X[1]        * (C[0] + C[1] * b + C[2] * B[2] + C[3] * B[3] + C[4] * B[4]);
+            A[3] = X[2] / 2.   * (C[1] + C[2] * b + C[3] * B[2] + C[4] * B[3]);
+            A[2] = X[3] / 6.   * (C[2] + C[3] * b + C[4] * B[2]);
+            A[1] = X[4] / 24.  * (C[3] + C[4] * b);
+            A[0] = X[5] / 120. * C[4];
+            // res = exp(x) * (A[5] + A[4] * a + A[3] * a^2 + A[2] * a^3 + ...)
+            if (!log_wb) {
+                res = exp(x) * cephes::polevl(a, A, 5);
+            } else {
+                // logarithm of Wright's function
+                res = x + std::log(cephes::polevl(a, A, 5));
+            }
+        } else {
+            /* Phi(a, b, x) = exp(x)/gamma(b) * sum(A[i] * X[i] * B[i], i=0..5)
+             * A[n] = a^n/n!
+             * But here, we repurpose A[n] = X[n] * B[n] / n!
+             * Note that polevl assumes inverse ordering => A[order] = 0th term */
+            double dg = digamma(b);
+            // pg1 = polygamma(1, b)
+            double pg1 = cephes::zeta(2, b);
+            if (order <= 2) {
+                res = 1 + a * x * (-dg + 0.5 * a * (1 + x) * (dg * dg - pg1));
+            } else {
+                if (order > 5) {
+                    order = 5;
+                }
+                // pg2 = polygamma(2, b)
+                double pg2 = -2 * cephes::zeta(3, b);
+                B[0] = 1;
+                B[1] = -dg;
+                B[2] = dg * dg - pg1;
+                B[3] = (-dg * dg + 3 * pg1) * dg - pg2;
+                A[order] = 1;
+                A[order - 1] = X[1] * B[1];
+                A[order - 2] = X[2] * B[2] / 2.;
+                A[order - 3] = X[3] * B[3] / 6.;
+                if (order >= 4) {
+                    // double pg3 = polygamma(3, b)
+                    double pg3 = 6 * cephes::zeta(4, b);
+                    B[4] = ((dg * dg - 6 * pg1) * dg + 4 * pg2) * dg + 3 * pg1 * pg1 - pg3;
+                    A[order - 4] = X[4] * B[4] / 24.;
+                    if (order >= 5) {
+                        // pg4 = polygamma(4, b)
+                        double pg4 = -24 * cephes::zeta(5, b);
+                        B[5] =
+                            ((((-dg * dg + 10 * pg1) * dg - 10 * pg2) * dg - 15 * pg1 * pg1 + 5 * pg3) * dg +
+                             10 * pg1 * pg2 - pg4);
+                        A[order - 5] = X[5] * B[5] / 120.;
+                    }
+                }
+                res = cephes::polevl(a, A, order);
+            }
+            // res *= exp(x) * rgamma(b)
+            if (!log_wb) {
+                res *= exp_rgamma(x, b);
+            } else {
+                // logarithm of Wright's function
+                res = x - cephes::lgam(b) + std::log(res);
+            }
+        }
+        return res;
+    }
+
+    template
+    XSF_HOST_DEVICE inline double wb_asymptotic(double a, double b, double x) {
+        /* 4. Asymptotic expansion for large x up to order 8
+         *
+         * Phi(a, b, x) ~ Z^(1/2-b) * exp((1+a)/a * Z) * sum_k (-1)^k * C_k / Z^k
+         *
+         * with Z = (a*x)^(1/(1+a)).
+         * Call: python _precompute/wright_bessel.py 3
+         */
+        double A[15];  // powers of a
+        double B[17];  // powers of b
+        double Ap1[9]; // powers of (1+a)
+        double C[9];   // coefficients of asymptotic series a_k
+
+        A[0] = 1.;
+        B[0] = 1.;
+        Ap1[0] = 1.;
+        for (int k = 1; k < 15; k++) {
+            A[k] = A[k - 1] * a;
+        }
+        for (int k = 1; k < 17; k++) {
+            B[k] = B[k - 1] * b;
+        }
+        for (int k = 1; k < 9; k++) {
+            Ap1[k] = Ap1[k - 1] * (1 + a);
+        }
+
+        C[0] = 1. / std::sqrt(2. * M_PI * Ap1[1]);
+
+        C[1] = C[0] / (24 * Ap1[1]);
+        C[1] *= (2 * a + 1) * (2 + a) - 12 * b * (1 + a - b);
+
+        C[2] = C[0] / (1152 * Ap1[2]);
+        C[2] *=
+            (144 * B[4] - 96 * B[3] * (5 * a + 1) + 24 * B[2] * (20 * A[2] + 5 * a - 4) -
+             24 * b * Ap1[1] * (6 * A[2] - 7 * a - 2) + (a + 2) * (2 * a + 1) * (2 * A[2] - 19 * a + 2));
+
+        C[3] = C[0] / (414720 * Ap1[3]);
+        C[3] *=
+            (8640 * B[6] - 8640 * B[5] * (7 * a - 1) + 10800 * B[4] * (14 * A[2] - 7 * a - 2) -
+             1440 * B[3] * (112 * A[3] - 147 * A[2] - 63 * a + 8) +
+             180 * B[2] * (364 * A[4] - 1288 * A[3] - 567 * A[2] + 392 * a + 76) -
+             180 * b * Ap1[1] * (20 * A[4] - 516 * A[3] + 417 * A[2] + 172 * a - 12) -
+             (a + 2) * (2 * a + 1) * (556 * A[4] + 1628 * A[3] - 9093 * A[2] + 1628 * a + 556));
+
+        C[4] = C[0] / (39813120 * Ap1[4]);
+        C[4] *=
+            (103680 * B[8] - 414720 * B[7] * (3 * a - 1) + 725760 * B[6] * a * (8 * a - 7) -
+             48384 * B[5] * (274 * A[3] - 489 * A[2] + 39 * a + 26) +
+             30240 * B[4] * (500 * A[4] - 1740 * A[3] + 495 * A[2] + 340 * a - 12) -
+             2880 * B[3] * (2588 * A[5] - 19780 * A[4] + 14453 * A[3] + 9697 * A[2] - 1892 * a - 404) +
+             48 * B[2] *
+                 (11488 * A[6] - 547836 * A[5] + 1007484 * A[4] + 593353 * A[3] - 411276 * A[2] - 114396 * a + 4288) +
+             48 * b * Ap1[1] *
+                 (7784 * A[6] + 48180 * A[5] - 491202 * A[4] + 336347 * A[3] + 163734 * A[2] - 28908 * a - 5560) -
+             (a + 2) * (2 * a + 1) *
+                 (4568 * A[6] - 226668 * A[5] - 465702 * A[4] + 2013479 * A[3] - 465702 * A[2] - 226668 * a + 4568));
+
+        C[5] = C[0] / (6688604160. * Ap1[5]);
+        C[5] *=
+            (1741824 * B[10] - 2903040 * B[9] * (11 * a - 5) + 2177280 * B[8] * (110 * A[2] - 121 * a + 14) -
+             580608 * B[7] * (1628 * A[3] - 3333 * A[2] + 1023 * a + 52) +
+             169344 * B[6] * (12364 * A[4] - 43648 * A[3] + 26763 * A[2] + 1232 * a - 788) -
+             24192 * B[5] * (104852 * A[5] - 646624 * A[4] + 721391 * A[3] - 16841 * A[2] - 74096 * a + 148) +
+             2016 * B[4] *
+                 (710248 * A[6] - 8878716 * A[5] + 17928834 * A[4] - 3333407 * A[3] - 4339566 * A[2] + 287364 * a +
+                  89128) -
+             1344 * B[3] *
+                 (87824 * A[7] - 7150220 * A[6] + 29202756 * A[5] - 15113527 * A[4] - 14223011 * A[3] + 3462492 * A[2] +
+                  1137092 * a - 18896) -
+             84 * B[2] *
+                 (1690480 * A[8] + 14139136 * A[7] - 232575464 * A[6] + 296712592 * A[5] + 215856619 * A[4] -
+                  152181392 * A[3] - 47718440 * A[2] + 5813632 * a + 943216) +
+             84 * b * Ap1[1] *
+                 (82224 * A[8] - 5628896 * A[7] - 26466520 * A[6] + 168779208 * A[5] - 104808005 * A[4] -
+                  56259736 * A[3] + 15879912 * A[2] + 4020640 * a - 63952) +
+             (a + 2) * (2 * a + 1) *
+                 (2622064 * A[8] + 12598624 * A[7] - 167685080 * A[6] - 302008904 * A[5] + 1115235367. * A[4] -
+                  302008904 * A[3] - 167685080 * A[2] + 12598624 * a + 2622064));
+
+        C[6] = C[0] / (4815794995200. * Ap1[6]);
+        C[6] *=
+            (104509440 * B[12] - 209018880 * B[11] * (13 * a - 7) + 574801920 * B[10] * (52 * A[2] - 65 * a + 12) -
+             63866880 * B[9] * (2834 * A[3] - 6279 * A[2] + 2769 * a - 134) +
+             23950080 * B[8] * (27404 * A[4] - 98228 * A[3] + 78663 * A[2] - 10868 * a - 1012) -
+             13685760 * B[7] * (105612 * A[5] - 599196 * A[4] + 791843 * A[3] - 224913 * A[2] - 27612 * a + 4540) +
+             2661120 * B[6] *
+                 (693680 * A[6] - 6473532 * A[5] + 13736424 * A[4] - 7047469 * A[3] - 723840 * A[2] + 471588 * a + 7376
+                 ) -
+             2661120 * B[5] *
+                 (432536 * A[7] - 7850804 * A[6] + 27531114 * A[5] - 24234457 * A[4] - 703001 * A[3] + 3633474 * A[2] -
+                  36244 * a - 45128) +
+             166320 * B[4] *
+                 (548912 * A[8] - 75660832 * A[7] + 502902712 * A[6] - 764807992 * A[5] + 91248287 * A[4] +
+                  217811464 * A[3] - 20365384 * A[2] - 9776416 * a + 37936) +
+             10080 * B[3] *
+                 (18759728 * A[9] + 165932208 * A[8] - 4710418440. * A[7] + 13686052536. * A[6] - 5456818809. * A[5] -
+                  6834514245. * A[4] + 1919299512. * A[3] + 752176152 * A[2] - 45661200 * a - 8616848) -
+             360 * B[2] *
+                 (32743360 * A[10] - 3381871792. * A[9] - 21488827776. * A[8] + 200389923864. * A[7] -
+                  198708005340. * A[6] - 171633799779. * A[5] + 123124874028. * A[4] + 40072774872. * A[3] -
+                  9137993280. * A[2] - 1895843248. * a + 18929728) -
+             360 * b * Ap1[1] *
+                 (57685408 * A[10] + 406929456 * A[9] - 6125375760. * A[8] - 27094918920. * A[7] +
+                  128752249410. * A[6] - 74866710561. * A[5] - 42917416470. * A[4] + 16256951352. * A[3] +
+                  4375268400. * A[2] - 316500688 * a - 47197152) +
+             (a + 2) * (2 * a + 1) *
+                 (167898208 * A[10] - 22774946512. * A[9] - 88280004528. * A[8] + 611863976472. * A[7] +
+                  1041430242126. * A[6] - 3446851131657. * A[5] + 1041430242126. * A[4] + 611863976472. * A[3] -
+                  88280004528. * A[2] - 22774946512. * a + 167898208));
+
+        C[7] = C[0] / (115579079884800. * Ap1[7]);
+        C[7] *=
+            (179159040 * B[14] - 1254113280. * B[13] * (5 * a - 3) + 1358622720. * B[12] * (70 * A[2] - 95 * a + 22) -
+             905748480 * B[11] * (904 * A[3] - 2109 * A[2] + 1119 * a - 112) +
+             1245404160. * B[10] * (3532 * A[4] - 12824 * A[3] + 11829 * A[2] - 2824 * a + 44) -
+             59304960 * B[9] * (256820 * A[5] - 1397680 * A[4] + 2025545 * A[3] - 869495 * A[2] + 52000 * a + 8788) +
+             14826240 * B[8] *
+                 (2274536 * A[6] - 18601572 * A[5] + 40698318 * A[4] - 28230079 * A[3] + 3916398 * A[2] + 832668 * a -
+                  65176) -
+             59304960 * B[7] *
+                 (760224 * A[7] - 9849164 * A[6] + 32495784 * A[5] - 34813869 * A[4] + 9175207 * A[3] + 1898688 * A[2] -
+                  469788 * a - 13184) +
+             25945920 * B[6] *
+                 (1167504 * A[8] - 28779840 * A[7] + 149752856 * A[6] - 246026112 * A[5] + 111944073 * A[4] +
+                  18341600 * A[3] - 12131496 * A[2] - 274368 * a + 102800) -
+             157248 * B[5] *
+                 (12341872 * A[9] - 3122991216. * A[8] + 29900054232. * A[7] - 78024816720. * A[6] +
+                  58914656739. * A[5] + 4637150811. * A[4] - 11523402480. * A[3] + 236218968 * A[2] + 337923216 * a +
+                  1592048) -
+             28080 * B[4] *
+                 (265154912 * A[10] + 2276098704. * A[9] - 105569461008. * A[8] + 496560666360. * A[7] -
+                  627891462858. * A[6] + 41935358025. * A[5] + 203913875814. * A[4] - 23984801544. * A[3] -
+                  13869306000. * A[2] + 372786832 * a + 103532640) +
+             1440 * B[3] *
+                 (310292864 * A[11] - 55169117872. * A[10] - 358957020112. * A[9] + 5714152556088. * A[8] -
+                  13241597459352. * A[7] + 4220720097141. * A[6] + 6845418090249. * A[5] - 2129559215808. * A[4] -
+                  909225098472. * A[3] + 107518582576. * A[2] + 25619444368. * a - 113832704) +
+             12 * B[2] *
+                 (135319651136. * A[12] + 1119107842176. * A[11] - 22193518174320. * A[10] - 133421793595520. * A[9] +
+                  860103051087996. * A[8] - 703353374803080. * A[7] - 704240127687381. * A[6] +
+                  513111704637960. * A[5] + 166909061348316. * A[4] - 57671564069120. * A[3] - 12453426246000. * A[2] +
+                  695901207936. * a + 93786157376.) -
+             12 * b * Ap1[1] *
+                 (4365353408. * A[12] - 720248637504. * A[11] - 4222331152560. * A[10] + 29413934270560. * A[9] +
+                  132123980710980. * A[8] - 511247376962820. * A[7] + 283403639131779. * A[6] +
+                  170415792320940. * A[5] - 79274388426588. * A[4] - 21009953050400. * A[3] + 3284035340880. * A[2] +
+                  589294339776. * a - 3693760576.) -
+             (a + 2) * (2 * a + 1) *
+                 (34221025984. * A[12] + 226022948160. * A[11] - 5067505612464. * A[10] - 18868361443936. * A[9] +
+                  86215425028308. * A[8] + 143500920544692. * A[7] - 437682618704613. * A[6] + 143500920544692. * A[5] +
+                  86215425028308. * A[4] - 18868361443936. * A[3] - 5067505612464. * A[2] + 226022948160. * a +
+                  34221025984.));
+
+        C[8] = C[0] / (22191183337881600. * Ap1[8]);
+        C[8] *=
+            (2149908480. * B[16] - 5733089280. * B[15] * (17 * a - 11) +
+             7166361600. * B[14] * (272 * A[2] - 391 * a + 104) -
+             3344302080. * B[13] * (6766 * A[3] - 16371 * A[2] + 9741 * a - 1306) +
+             1811496960. * B[12] * (93092 * A[4] - 341564 * A[3] + 344199 * A[2] - 104924 * a + 6308) -
+             517570560 * B[11] *
+                 (1626220 * A[5] - 8641508 * A[4] + 13274773 * A[3] - 6952303 * A[2] + 1007420 * a + 5564) +
+             284663808 * B[10] *
+                 (9979136 * A[6] - 75766892 * A[5] + 169256148 * A[4] - 136824959 * A[3] + 35714348 * A[2] -
+                  463692 * a - 293664) -
+             1423319040. * B[9] *
+                 (4466648 * A[7] - 49231116 * A[6] + 157507414 * A[5] - 187114257 * A[4] + 78372295 * A[3] -
+                  4470082 * A[2] - 1913996 * a + 82424) +
+             266872320 * B[8] *
+                 (33133136 * A[8] - 564264544 * A[7] + 2618606424. * A[6] - 4491310104. * A[5] + 2853943765. * A[4] -
+                  374694552 * A[3] - 135365288 * A[2] + 17623968 * a + 696912) -
+             2156544 * B[7] *
+                 (2914256144. * A[9] - 93491712432. * A[8] + 664876176984. * A[7] - 1661362937880. * A[6] +
+                  1563719627313. * A[5] - 382840842843. * A[4] - 115399415640. * A[3] + 34565562936. * A[2] +
+                  1609337232. * a - 217321904) +
+             179712 * B[6] *
+                 (1266018560. * A[10] - 789261834512. * A[9] + 10186841596896. * A[8] - 38877799073352. * A[7] +
+                  54334425968952. * A[6] - 22529574889533. * A[5] - 5132942328000. * A[4] + 3438377465592. * A[3] +
+                  84287641248. * A[2] - 72493479440. * a - 807415936) +
+             13824 * B[5] *
+                 (156356794976. * A[11] + 1180898077328. * A[10] - 90615270907936. * A[9] + 609258947056248. * A[8] -
+                  1312655191366722. * A[7] + 885900509321745. * A[6] + 112162151855265. * A[5] -
+                  212803071513258. * A[4] + 6805217831352. * A[3] + 10051742651296. * A[2] - 55035924848. * a -
+                  52946379296.) -
+             576 * B[4] *
+                 (143943926464. * A[12] - 60115486481856. * A[11] - 376366989757200. * A[10] +
+                  9534223075576160. * A[9] - 35603777465262396. * A[8] + 39375990156664980. * A[7] -
+                  868175004137259. * A[6] - 14279180718355020. * A[5] + 1985747535239364. * A[4] +
+                  1264001337603680. * A[3] - 75972792514320. * A[2] - 23855850572736. * a - 4996648256.) -
+             384 * B[3] *
+                 (2038525473856. * A[13] + 16057322146112. * A[12] - 502133360559024. * A[11] -
+                  2985686417468080. * A[10] + 32418922182093292. * A[9] - 63665380623022452. * A[8] +
+                  16481208821092575. * A[7] + 34161547357596099. * A[6] - 11490298497454932. * A[5] -
+                  5117272758337156. * A[4] + 933703210750480. * A[3] + 234855186762000. * A[2] - 7860524600000. * a -
+                  1226607567040.) +
+             96 * B[2] *
+                 (324439754752. * A[14] - 77231415197120. * A[13] - 539102931841856. * A[12] +
+                  4618258299956336. * A[11] + 28588485529469792. * A[10] - 141383982651179428. * A[9] +
+                  98783147840417772. * A[8] + 112831723492305801. * A[7] - 83329761150975036. * A[6] -
+                  26553582937192900. * A[5] + 12469117738765952. * A[4] + 2587165396642160. * A[3] -
+                  340406368038080. * A[2] - 53659641606080. * a + 219671272960.) +
+             96 * b * Ap1[1] *
+                 (1026630779520. * A[14] + 8781958472768. * A[13] - 210659786204384. * A[12] -
+                  1222283505284208. * A[11] + 5064251967491416. * A[10] + 24013052207628140. * A[9] -
+                  79710880160087370. * A[8] + 42596558293213227. * A[7] + 26570293386695790. * A[6] -
+                  14407831324576884. * A[5] - 3617322833922440. * A[4] + 950664948554384. * A[3] +
+                  172358006894496. * A[2] - 7430887938496. * a - 889746675584.) -
+             (a + 2) * (2 * a + 1) *
+                 (573840801152. * A[14] - 156998277198784. * A[13] - 898376974770592. * A[12] +
+                  8622589006459984. * A[11] + 32874204024803560. * A[10] - 111492707520083828. * A[9] -
+                  184768503480287646. * A[8] + 528612016938984183. * A[7] - 184768503480287646. * A[6] -
+                  111492707520083828. * A[5] + 32874204024803560. * A[4] + 8622589006459984. * A[3] -
+                  898376974770592. * A[2] - 156998277198784. * a + 573840801152.));
+
+        double Z = std::pow(a * x, 1 / Ap1[1]);
+        double Zp = 1.;
+        double res = C[0];
+        for (int k = 1; k < 9; k++) {
+            Zp /= Z;
+            res += (k % 2 == 0 ? 1 : -1) * C[k] * Zp;
+        }
+        if (!log_wb) {
+            res *= std::pow(Z, 0.5 - b) * std::exp(Ap1[1] / a * Z);
+        } else {
+            // logarithm of Wright's function
+            res = std::log(Z) * (0.5 - b) + Ap1[1] / a * Z + std::log(res);
+        }
+        return res;
+    }
+
+    XSF_HOST_DEVICE inline double wb_Kmod(double exp_term, double eps, double a, double b, double x, double r) {
+        /* Compute integrand Kmod(eps, a, b, x, r) for Gauss-Laguerre quadrature.
+         *
+         * K(a, b, x, r+eps) = exp(-r-eps) * Kmod(eps, a, b, x, r)
+         * 
+         * Kmod(eps, a, b, x, r) = exp(x * (r+eps)^(-a) * cos(pi*a)) * (r+eps)^(-b)
+         *                       * sin(x * (r+eps)^(-a) * sin(pi*a) + pi * b)
+         * 
+         * Note that we additionally factor out exp(exp_term) which helps with large
+         * terms in the exponent of exp(...)
+         */
+        double x_r_a = x * std::pow(r + eps, -a);
+        return std::exp(x_r_a * cephes::cospi(a) + exp_term) * std::pow(r + eps, -b) *
+               std::sin(x_r_a * cephes::sinpi(a) + M_PI * b);
+    }
+
+    XSF_HOST_DEVICE inline double wb_P(double exp_term, double eps, double a, double b, double x, double phi) {
+        /* Compute integrand P for Gauss-Legendre quadrature.
+         *
+         * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi))
+         *                      * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi)
+         *                            + (1-b)*phi)
+         * 
+         * Note that we additionally factor out exp(exp_term) which helps with large
+         * terms in the exponent of exp(...)
+         */
+        double x_eps_a = x * std::pow(eps, -a);
+        return std::exp(eps * std::cos(phi) + x_eps_a * std::cos(a * phi) + exp_term) *
+               std::cos(eps * std::sin(phi) - x_eps_a * std::sin(a * phi) + (1 - b) * phi);
+    }
+
+    /* roots of laguerre polynomial of order 50
+     * scipy.special.roots_laguerre(50)[0] or
+     * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[0] */
+    constexpr double wb_x_laguerre[] = {
+        0.02863051833937908, 0.1508829356769337, 0.3709487815348964, 0.6890906998810479, 1.105625023539913,
+        1.620961751102501,   2.23561037591518,   2.950183366641835,  3.765399774405782,  4.682089387559285,
+        5.70119757478489,    6.823790909794551,  8.051063669390792,  9.384345308258407,  10.82510903154915,
+        12.37498160875746,   14.03575459982991,  15.80939719784467,  17.69807093335025,  19.70414653546156,
+        21.83022330657825,   24.0791514444115,   26.45405784125298,  28.95837601193738,  31.59588095662286,
+        34.37072996309045,   37.28751061055049,  40.35129757358607,  43.56772026999502,  46.94304399160304,
+        50.48426796312992,   54.19924488016862,  58.09682801724853,  62.18705417568891,  66.48137387844482,
+        70.99294482661949,   75.73701154772731,  80.73140480247769,  85.99721113646323,  91.55969041253388,
+        97.44956561485056,   103.7048912366923,  110.3738588076403,  117.5191982031112,  125.2254701334734,
+        133.6120279227287,   142.8583254892541,  153.2603719726036,  165.3856433166825,  180.6983437092145
+    };
+    /* weights for laguerre polynomial of order 50
+     * sympy.integrals.quadrature.import gauss_laguerre(50, 16)[1] */
+    constexpr double wb_w_laguerre[] = {
+        0.07140472613518988,   0.1471486069645884,    0.1856716275748313,    0.1843853825273539,
+        0.1542011686063556,    0.1116853699022688,    0.07105288549019586,   0.04002027691150833,
+        0.02005062308007171,   0.008960851203646281,  0.00357811241531566,   0.00127761715678905,
+        0.0004080302449837189, 0.0001165288322309724, 2.974170493694165e-5,  6.777842526542028e-6,
+        1.37747950317136e-6,   2.492886181720092e-7,  4.010354350427827e-8,  5.723331748141425e-9,
+        7.229434249182665e-10, 8.061710142281779e-11, 7.913393099943723e-12, 6.81573661767678e-13,
+        5.13242671658949e-14,  3.365624762437814e-15, 1.913476326965035e-16, 9.385589781827253e-18,
+        3.950069964503411e-19, 1.417749517827512e-20, 4.309970276292175e-22, 1.101257519845548e-23,
+        2.344617755608987e-25, 4.11854415463823e-27,  5.902246763596448e-29, 6.812008916553065e-31,
+        6.237449498812102e-33, 4.452440579683377e-35, 2.426862352250487e-37, 9.852971481049686e-40,
+        2.891078872318428e-42, 5.906162708112361e-45, 8.01287459750397e-48,  6.789575424396417e-51,
+        3.308173010849252e-54, 8.250964876440456e-58, 8.848728128298018e-62, 3.064894889844417e-66,
+        1.988708229330752e-71, 6.049567152238783e-78
+    };
+    /* roots of legendre polynomial of order 50
+     * sympy.integrals.quadrature.import gauss_legendre(50, 16)[0] */
+    constexpr double wb_x_legendre[] = {
+        -0.998866404420071,  -0.9940319694320907, -0.9853540840480059, -0.9728643851066921,  -0.9566109552428079,
+        -0.9366566189448779, -0.9130785566557919, -0.885967979523613,  -0.8554297694299461,  -0.8215820708593359,
+        -0.7845558329003993, -0.7444943022260685, -0.7015524687068223, -0.6558964656854394,  -0.6077029271849502,
+        -0.5571583045146501, -0.5044581449074642, -0.4498063349740388, -0.3934143118975651,  -0.3355002454194374,
+        -0.276288193779532,  -0.2160072368760418, -0.1548905899981459, -0.09317470156008614, -0.03109833832718888,
+        0.03109833832718888, 0.09317470156008614, 0.1548905899981459,  0.2160072368760418,   0.276288193779532,
+        0.3355002454194374,  0.3934143118975651,  0.4498063349740388,  0.5044581449074642,   0.5571583045146501,
+        0.6077029271849502,  0.6558964656854394,  0.7015524687068223,  0.7444943022260685,   0.7845558329003993,
+        0.8215820708593359,  0.8554297694299461,  0.885967979523613,   0.9130785566557919,   0.9366566189448779,
+        0.9566109552428079,  0.9728643851066921,  0.9853540840480059,  0.9940319694320907,   0.998866404420071
+    };
+    /* weights for legendre polynomial of order 50
+     * sympy.integrals.quadrature.import gauss_legendre(50, 16)[1] */
+    constexpr double wb_w_legendre[] = {
+        0.002908622553155141, 0.006759799195745401, 0.01059054838365097, 0.01438082276148557,  0.01811556071348939,
+        0.02178024317012479,  0.02536067357001239,  0.0288429935805352,  0.03221372822357802,  0.03545983561514615,
+        0.03856875661258768,  0.0415284630901477,   0.04432750433880328, 0.04695505130394843,  0.04940093844946632,
+        0.05165570306958114,  0.05371062188899625,  0.05555774480621252, 0.05718992564772838,  0.05860084981322245,
+        0.05978505870426546,  0.06073797084177022,  0.06145589959031666, 0.06193606742068324,  0.06217661665534726,
+        0.06217661665534726,  0.06193606742068324,  0.06145589959031666, 0.06073797084177022,  0.05978505870426546,
+        0.05860084981322245,  0.05718992564772838,  0.05555774480621252, 0.05371062188899625,  0.05165570306958114,
+        0.04940093844946632,  0.04695505130394843,  0.04432750433880328, 0.0415284630901477,   0.03856875661258768,
+        0.03545983561514615,  0.03221372822357802,  0.0288429935805352,  0.02536067357001239,  0.02178024317012479,
+        0.01811556071348939,  0.01438082276148557,  0.01059054838365097, 0.006759799195745401, 0.002908622553155141
+    };
+    /* Fitted parameters for optimal choice of eps
+     * Call: python _precompute/wright_bessel.py 4 */
+    constexpr double wb_A[] = {0.41037, 0.30833, 6.9952, 18.382, -2.8566, 2.1122};
+
+    template
+    XSF_HOST_DEVICE inline double wright_bessel_integral(double a, double b, double x) {
+        /* 5. Integral representation
+         *
+         * K(a, b, x, r) = exp(-r + x * r^(-a) * cos(pi*a)) * r^(-b)
+         *               * sin(x * r^(-a) * sin(pi*a) + pi * b)
+         * P(eps, a, b, x, phi) = exp(eps * cos(phi) + x * eps^(-a) * cos(a*phi))
+         *                      * cos(eps * sin(phi) - x * eps^(-a) * sin(a*phi)
+         *                        + (1-b)*phi)
+         *
+         * Phi(a, b, x) = 1/pi * int_eps^inf K(a, b, x, r) * dr
+         *              + eps^(1-b)/pi * int_0^pi P(eps, a, b, x, phi) * dphi
+         *
+         * for any eps > 0.
+         *
+         * Note that P has a misprint in Luchko (2008) Eq. 9, the cos(phi(beta-1)) at
+         * the end of the first line should be removed and the −sin(phi(beta−1)) at
+         * the end of the second line should read +(1-b)*phi.
+         * This integral representation introduced the free parameter eps (from the
+         * radius of complex contour integration). We try to choose eps such that
+         * the integrand behaves smoothly. Note that this is quite diffrent from how
+         * Luchko (2008) deals with eps: he is either looking for the limit eps -> 0
+         * or he sets (silently) eps=1. But having the freedom to set eps is much more
+         * powerful for numerical evaluation.
+         *
+         * As K has a leading exp(-r), we factor this out and apply Gauss-Laguerre
+         * quadrature rule:
+         *
+         * int_0^inf K(a, b, x, r+eps) dr = exp(-eps) int_0^inf exp(-r) Kmod(.., r) dr
+         *
+         * Note the shift r -> r+eps to have integation from 0 to infinity.
+         * The integral over P is done via a Gauss-Legendre quadrature rule.
+         *
+         * Note: Hardest argument range is large z, large b and small eps.
+         */
+
+        /* We use the free choice of eps to make the integral better behaved.
+         * 1. Concern is oscillatory behaviour of P. Therefore, we'd like to
+         *    make the change in the argument of cosine small, i.e. make arc length
+         *    int_0^phi sqrt(1 + f'(phi)^2) dphi small, with
+         *    f(phi) = eps * sin(phi) - x * eps^(-a) * sin(a*phi) + (1-b)*phi
+         *    Proxy, make |f'(phi)| small.
+         * 2. Concern is int_0 K ~ int_0 (r+eps)^(-b) .. dr
+         *    This is difficult as r -> 0  for large b. It behaves better for larger
+         *    values of eps.
+         */
+
+        // Minimize oscillatory behavoir of P
+        double eps =
+            (wb_A[0] * b * std::exp(-0.5 * a) +
+             std::exp(
+                 wb_A[1] + 1 / (1 + a) * std::log(x) - wb_A[2] * std::exp(-wb_A[3] * a) +
+                 wb_A[4] / (1 + std::exp(wb_A[5] * a))
+             ));
+
+        if (a >= 4 && x >= 100) {
+            eps += 1; // This part is hard to fit
+        }
+
+        // Large b
+        if (b >= 8) {
+            /* Make P small compared to K by setting eps large enough.
+             * int K ~ exp(-eps) and int P ~ eps^(1-b) */
+            eps = std::fmax(eps, std::pow(b, -b / (1. - b)) + 0.1 * b);
+        }
+
+        // safeguard, higher better for larger a, lower better for tiny a.
+        eps = std::fmin(eps, 150.);
+        eps = std::fmax(eps, 3.); // 3 seems to be a pretty good choice in general.
+
+        // We factor out exp(-exp_term) from wb_Kmod and wb_P to avoid overflow of
+        // exp(..).
+        double exp_term = 0;
+        // From the exponent of K:
+        double r = wb_x_laguerre[50-1];  // largest value of x used in wb_Kmod
+        double x_r_a = x * std::pow(r + eps, -a);
+        exp_term = std::fmax(exp_term, x_r_a * cephes::cospi(a));
+        // From the exponent of P:
+        double x_eps_a = x * std::pow(eps, -a);
+        // phi = 0  =>  cos(phi) = cos(a * phi) = 1
+        exp_term = std::fmax(exp_term, eps + x_eps_a);
+        // phi = pi  => cos(phi) = -1
+        exp_term = std::fmax(exp_term, -eps + x_eps_a * cephes::cospi(a));
+
+        double res1 = 0;
+        double res2 = 0;
+
+        double y;
+        for (int k = 0; k < 50; k++) {
+            res1 += wb_w_laguerre[k] * wb_Kmod(-exp_term, eps, a, b, x, wb_x_laguerre[k]);
+            // y = (b-a)*(x+1)/2.0 + a  for integration from a=0 to b=pi
+            y = M_PI * (wb_x_legendre[k] + 1) / 2.0;
+            res2 += wb_w_legendre[k] * wb_P(-exp_term, eps, a, b, x, y);
+        }
+        res1 *= std::exp(-eps);
+        // (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1)
+        res2 *= M_PI / 2.0;
+        res2 *= std::pow(eps, 1 - b);
+
+        if (!log_wb) {
+            // Remember the factored out exp_term from wb_Kmod and wb_P
+            return std::exp(exp_term) / M_PI * (res1 + res2);
+        } else {
+            // logarithm of Wright's function
+            return exp_term + std::log((res1 + res2) / M_PI);
+        }
+    }
+} // namespace detail
+
+template
+XSF_HOST_DEVICE inline double wright_bessel_t(double a, double b, double x) {
+    /* Compute Wright's generalized Bessel function for scalar arguments.
+     *
+     * According to [1], it is an entire function defined as
+     *
+     * .. math:: \Phi(a, b; x) = \sum_{k=0}^\infty \frac{x^k}{k! \Gamma(a k + b)}
+     *
+     * So far, only non-negative values of rho=a, beta=b and z=x are implemented.
+     * There are 5 different approaches depending on the ranges of the arguments:
+     *
+     * 1. Taylor series expansion in x=0 [1], for x <= 1.
+     *    Involves gamma funtions in each term.
+     * 2. Taylor series expansion in x=0 [2], for large a.
+     * 3. Taylor series in a=0, for tiny a and not too large x.
+     * 4. Asymptotic expansion for large x [3, 4].
+     *    Suitable for large x while still small a and b.
+     * 5. Integral representation [5], in principle for all arguments.
+     *
+     * References
+     * ----------
+     * [1] https://dlmf.nist.gov/10.46.E1
+     * [2] P. K. Dunn, G. K. Smyth (2005), Series evaluation of Tweedie exponential
+     *     dispersion model densities. Statistics and Computing 15 (2005): 267-280.
+     * [3] E. M. Wright (1935), The asymptotic expansion of the generalized Bessel
+     *     function. Proc. London Math. Soc. (2) 38, pp. 257-270.
+     *     https://doi.org/10.1112/plms/s2-38.1.257
+     * [4] R. B. Paris (2017), The asymptotics of the generalised Bessel function,
+     *     Mathematica Aeterna, Vol. 7, 2017, no. 4, 381 - 406,
+     *     https://arxiv.org/abs/1711.03006
+     * [5] Y. F. Luchko (2008), Algorithms for Evaluation of the Wright Function for
+     *     the Real Arguments' Values, Fractional Calculus and Applied Analysis 11(1)
+     *     http://sci-gems.math.bas.bg/jspui/bitstream/10525/1298/1/fcaa-vol11-num1-2008-57p-75p.pdf
+     */
+    if (std::isnan(a) || std::isnan(b) || std::isnan(x)) {
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (a < 0 || b < 0 || x < 0) {
+        set_error("wright_bessel", SF_ERROR_DOMAIN, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (std::isinf(x)) {
+        if (std::isinf(a) || std::isinf(b)) {
+            return std::numeric_limits::quiet_NaN();
+        }
+        return std::numeric_limits::infinity();
+    }
+    if (std::isinf(a) || std::isinf(b)) {
+        return std::numeric_limits::quiet_NaN(); // or 0
+    }
+    if (a >= detail::rgamma_zero || b >= detail::rgamma_zero) {
+        set_error("wright_bessel", SF_ERROR_OVERFLOW, NULL);
+        return std::numeric_limits::quiet_NaN();
+    }
+    if (x == 0) {
+        // return rgamma(b)
+        if (!log_wb) {
+            return cephes::rgamma(b);
+        } else {
+            // logarithm of Wright's function
+            return -cephes::lgam(b);
+        }
+    }
+    if (a == 0) {
+        // return exp(x) * rgamma(b)
+        if (!log_wb) {
+            return detail::exp_rgamma(x, b);
+        } else {
+            // logarithm of Wright's function
+            return x - cephes::lgam(b);
+        }
+    }
+
+    constexpr double exp_inf = 709.78271289338403;
+    int order;
+    if ((a <= 1e-3 && b <= 50 && x <= 9) || (a <= 1e-4 && b <= 70 && x <= 100) ||
+        (a <= 1e-5 && b <= 170 && (x < exp_inf || (log_wb && x <= 1e3)))) {
+        /* Taylor Series expansion in a=0 to order=order => precision <= 1e-11
+         * If beta is also small => precision <= 1e-11.
+         * max order = 5 */
+        if (a <= 1e-5) {
+            if (x <= 1) {
+                order = 2;
+            } else if (x <= 10) {
+                order = 3;
+            } else if (x <= 100) {
+                order = 4;
+            } else { // x < exp_inf
+                order = 5;
+            }
+        } else if (a <= 1e-4) {
+            if (x <= 1e-2) {
+                order = 2;
+            } else if (x <= 1) {
+                order = 3;
+            } else if (x <= 10) {
+                order = 4;
+            } else { // x <= 100
+                order = 5;
+            }
+        } else { // a <= 1e-3
+            if (x <= 1e-5) {
+                order = 2;
+            } else if (x <= 1e-1) {
+                order = 3;
+            } else if (x <= 1) {
+                order = 4;
+            } else { // x <= 9
+                order = 5;
+            }
+        }
+
+        return detail::wb_small_a(a, b, x, order);
+    }
+
+    if (x <= 1) {
+        // 18 term Taylor Series => error mostly smaller 5e-14
+        double res = detail::wb_series(a, b, x, 0, 18);
+        if (log_wb) res = std::log(res);
+        return res;
+    }
+    if (x <= 2) {
+        // 20 term Taylor Series => error mostly smaller 1e-12 to 1e-13
+        double res = detail::wb_series(a, b, x, 0, 20);
+        if (log_wb) res = std::log(res);
+        return res;
+    }
+    if (a >= 5) {
+        /* Taylor series around the approximate maximum term.
+         * Set number of terms=order. */
+        if (a >= 10) {
+            if (x <= 1e11) {
+                order = 6;
+            } else {
+                order = static_cast(std::fmin(std::log10(x) - 5 + b / 10, 30));
+            }
+        } else {
+            if (x <= 1e4) {
+                order = 6;
+            } else if (x <= 1e8) {
+                order = static_cast(2 * std::log10(x));
+            } else if (x <= 1e10) {
+                order = static_cast(4 * std::log10(x) - 16);
+            } else {
+                order = static_cast(std::fmin(6 * std::log10(x) - 36, 100));
+            }
+        }
+        return detail::wb_large_a(a, b, x, order);
+    }
+    if (std::pow(a * x, 1 / (1. + a)) >= 14 + b * b / (2 * (1 + a))) {
+        /* Asymptotic expansion in Z = (a*x)^(1/(1+a)) up to 8th term 1/Z^8.
+         * For 1/Z^k, the highest term in b is b^(2*k) * a0 / (2^k k! (1+a)^k).
+         * As a0 is a common factor to all orders, this explains a bit the
+         * domain of good convergence set above.
+         * => precision ~ 1e-11 but can go down to ~1e-8 or 1e-7
+         * Note: We ensured a <= 5 as this is a bad approximation for large a. */
+        return detail::wb_asymptotic(a, b, x);
+    }
+    if (0.5 <= a && a <= 1.8 && 100 <= b && 1e5 <= x) {
+        // This is a very hard domain. This condition is placed after wb_asymptotic.
+        // TODO: Explore ways to cover this domain.
+        return std::numeric_limits::quiet_NaN();
+    }
+    return detail::wright_bessel_integral(a, b, x);
+}
+
+
+XSF_HOST_DEVICE inline double wright_bessel(double a, double b, double x) {
+    return wright_bessel_t(a, b, x);
+}
+
+XSF_HOST_DEVICE inline float wright_bessel(float a, float b, float x) {
+    return wright_bessel(static_cast(a), static_cast(b), static_cast(x));
+}
+
+XSF_HOST_DEVICE inline double log_wright_bessel(double a, double b, double x) {
+    return wright_bessel_t(a, b, x);
+}
+
+XSF_HOST_DEVICE inline float log_wright_bessel(float a, float b, float x) {
+    return log_wright_bessel(static_cast(a), static_cast(b), static_cast(x));
+}
+
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h
new file mode 100644
index 0000000000000000000000000000000000000000..64e83ca390a094b85380ff69c24ba2cdead33d7f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/special/xsf/zlog1.h
@@ -0,0 +1,35 @@
+/* Translated from Cython into C++ by SciPy developers in 2023.
+ *
+ * Original author: Josh Wilson, 2016.
+ */
+
+#pragma once
+
+#include "config.h"
+
+namespace xsf {
+namespace detail {
+
+    XSF_HOST_DEVICE inline std::complex zlog1(std::complex z) {
+        /* Compute log, paying special attention to accuracy around 1. We
+         * implement this ourselves because some systems (most notably the
+         * Travis CI machines) are weak in this regime. */
+        std::complex coeff = -1.0;
+        std::complex res = 0.0;
+
+        if (std::abs(z - 1.0) > 0.1) {
+            return std::log(z);
+        }
+
+        z -= 1.0;
+        for (int n = 1; n < 17; n++) {
+            coeff *= -z;
+            res += coeff / static_cast(n);
+            if (std::abs(res / coeff) < std::numeric_limits::epsilon()) {
+                break;
+            }
+        }
+        return res;
+    }
+} // namespace detail
+} // namespace xsf
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6a73e7b7814175c9e19977fc2ebff2367fc1dca
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__init__.py
@@ -0,0 +1,667 @@
+"""
+.. _statsrefmanual:
+
+==========================================
+Statistical functions (:mod:`scipy.stats`)
+==========================================
+
+.. currentmodule:: scipy.stats
+
+This module contains a large number of probability distributions,
+summary and frequency statistics, correlation functions and statistical
+tests, masked statistics, kernel density estimation, quasi-Monte Carlo
+functionality, and more.
+
+Statistics is a very large area, and there are topics that are out of scope
+for SciPy and are covered by other packages. Some of the most important ones
+are:
+
+- `statsmodels `__:
+  regression, linear models, time series analysis, extensions to topics
+  also covered by ``scipy.stats``.
+- `Pandas `__: tabular data, time series
+  functionality, interfaces to other statistical languages.
+- `PyMC `__: Bayesian statistical
+  modeling, probabilistic machine learning.
+- `scikit-learn `__: classification, regression,
+  model selection.
+- `Seaborn `__: statistical data visualization.
+- `rpy2 `__: Python to R bridge.
+
+
+Probability distributions
+=========================
+
+Each univariate distribution is an instance of a subclass of `rv_continuous`
+(`rv_discrete` for discrete distributions):
+
+.. autosummary::
+   :toctree: generated/
+
+   rv_continuous
+   rv_discrete
+   rv_histogram
+
+Continuous distributions
+------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   alpha             -- Alpha
+   anglit            -- Anglit
+   arcsine           -- Arcsine
+   argus             -- Argus
+   beta              -- Beta
+   betaprime         -- Beta Prime
+   bradford          -- Bradford
+   burr              -- Burr (Type III)
+   burr12            -- Burr (Type XII)
+   cauchy            -- Cauchy
+   chi               -- Chi
+   chi2              -- Chi-squared
+   cosine            -- Cosine
+   crystalball       -- Crystalball
+   dgamma            -- Double Gamma
+   dpareto_lognorm   -- Double Pareto Lognormal
+   dweibull          -- Double Weibull
+   erlang            -- Erlang
+   expon             -- Exponential
+   exponnorm         -- Exponentially Modified Normal
+   exponweib         -- Exponentiated Weibull
+   exponpow          -- Exponential Power
+   f                 -- F (Snecdor F)
+   fatiguelife       -- Fatigue Life (Birnbaum-Saunders)
+   fisk              -- Fisk
+   foldcauchy        -- Folded Cauchy
+   foldnorm          -- Folded Normal
+   genlogistic       -- Generalized Logistic
+   gennorm           -- Generalized normal
+   genpareto         -- Generalized Pareto
+   genexpon          -- Generalized Exponential
+   genextreme        -- Generalized Extreme Value
+   gausshyper        -- Gauss Hypergeometric
+   gamma             -- Gamma
+   gengamma          -- Generalized gamma
+   genhalflogistic   -- Generalized Half Logistic
+   genhyperbolic     -- Generalized Hyperbolic
+   geninvgauss       -- Generalized Inverse Gaussian
+   gibrat            -- Gibrat
+   gompertz          -- Gompertz (Truncated Gumbel)
+   gumbel_r          -- Right Sided Gumbel, Log-Weibull, Fisher-Tippett, Extreme Value Type I
+   gumbel_l          -- Left Sided Gumbel, etc.
+   halfcauchy        -- Half Cauchy
+   halflogistic      -- Half Logistic
+   halfnorm          -- Half Normal
+   halfgennorm       -- Generalized Half Normal
+   hypsecant         -- Hyperbolic Secant
+   invgamma          -- Inverse Gamma
+   invgauss          -- Inverse Gaussian
+   invweibull        -- Inverse Weibull
+   irwinhall         -- Irwin-Hall
+   jf_skew_t         -- Jones and Faddy Skew-T
+   johnsonsb         -- Johnson SB
+   johnsonsu         -- Johnson SU
+   kappa4            -- Kappa 4 parameter
+   kappa3            -- Kappa 3 parameter
+   ksone             -- Distribution of Kolmogorov-Smirnov one-sided test statistic
+   kstwo             -- Distribution of Kolmogorov-Smirnov two-sided test statistic
+   kstwobign         -- Limiting Distribution of scaled Kolmogorov-Smirnov two-sided test statistic.
+   landau            -- Landau
+   laplace           -- Laplace
+   laplace_asymmetric    -- Asymmetric Laplace
+   levy              -- Levy
+   levy_l
+   levy_stable
+   logistic          -- Logistic
+   loggamma          -- Log-Gamma
+   loglaplace        -- Log-Laplace (Log Double Exponential)
+   lognorm           -- Log-Normal
+   loguniform        -- Log-Uniform
+   lomax             -- Lomax (Pareto of the second kind)
+   maxwell           -- Maxwell
+   mielke            -- Mielke's Beta-Kappa
+   moyal             -- Moyal
+   nakagami          -- Nakagami
+   ncx2              -- Non-central chi-squared
+   ncf               -- Non-central F
+   nct               -- Non-central Student's T
+   norm              -- Normal (Gaussian)
+   norminvgauss      -- Normal Inverse Gaussian
+   pareto            -- Pareto
+   pearson3          -- Pearson type III
+   powerlaw          -- Power-function
+   powerlognorm      -- Power log normal
+   powernorm         -- Power normal
+   rdist             -- R-distribution
+   rayleigh          -- Rayleigh
+   rel_breitwigner   -- Relativistic Breit-Wigner
+   rice              -- Rice
+   recipinvgauss     -- Reciprocal Inverse Gaussian
+   semicircular      -- Semicircular
+   skewcauchy        -- Skew Cauchy
+   skewnorm          -- Skew normal
+   studentized_range    -- Studentized Range
+   t                 -- Student's T
+   trapezoid         -- Trapezoidal
+   triang            -- Triangular
+   truncexpon        -- Truncated Exponential
+   truncnorm         -- Truncated Normal
+   truncpareto       -- Truncated Pareto
+   truncweibull_min  -- Truncated minimum Weibull distribution
+   tukeylambda       -- Tukey-Lambda
+   uniform           -- Uniform
+   vonmises          -- Von-Mises (Circular)
+   vonmises_line     -- Von-Mises (Line)
+   wald              -- Wald
+   weibull_min       -- Minimum Weibull (see Frechet)
+   weibull_max       -- Maximum Weibull (see Frechet)
+   wrapcauchy        -- Wrapped Cauchy
+
+The ``fit`` method of the univariate continuous distributions uses
+maximum likelihood estimation to fit the distribution to a data set.
+The ``fit`` method can accept regular data or *censored data*.
+Censored data is represented with instances of the `CensoredData`
+class.
+
+.. autosummary::
+   :toctree: generated/
+
+   CensoredData
+
+
+Multivariate distributions
+--------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   multivariate_normal    -- Multivariate normal distribution
+   matrix_normal          -- Matrix normal distribution
+   dirichlet              -- Dirichlet
+   dirichlet_multinomial  -- Dirichlet multinomial distribution
+   wishart                -- Wishart
+   invwishart             -- Inverse Wishart
+   multinomial            -- Multinomial distribution
+   special_ortho_group    -- SO(N) group
+   ortho_group            -- O(N) group
+   unitary_group          -- U(N) group
+   random_correlation     -- random correlation matrices
+   multivariate_t         -- Multivariate t-distribution
+   multivariate_hypergeom -- Multivariate hypergeometric distribution
+   normal_inverse_gamma   -- Normal-inverse-gamma distribution
+   random_table           -- Distribution of random tables with given marginals
+   uniform_direction      -- Uniform distribution on S(N-1)
+   vonmises_fisher        -- Von Mises-Fisher distribution
+
+`scipy.stats.multivariate_normal` methods accept instances
+of the following class to represent the covariance.
+
+.. autosummary::
+   :toctree: generated/
+
+   Covariance             -- Representation of a covariance matrix
+
+
+Discrete distributions
+----------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   bernoulli                -- Bernoulli
+   betabinom                -- Beta-Binomial
+   betanbinom               -- Beta-Negative Binomial
+   binom                    -- Binomial
+   boltzmann                -- Boltzmann (Truncated Discrete Exponential)
+   dlaplace                 -- Discrete Laplacian
+   geom                     -- Geometric
+   hypergeom                -- Hypergeometric
+   logser                   -- Logarithmic (Log-Series, Series)
+   nbinom                   -- Negative Binomial
+   nchypergeom_fisher       -- Fisher's Noncentral Hypergeometric
+   nchypergeom_wallenius    -- Wallenius's Noncentral Hypergeometric
+   nhypergeom               -- Negative Hypergeometric
+   planck                   -- Planck (Discrete Exponential)
+   poisson                  -- Poisson
+   poisson_binom            -- Poisson Binomial
+   randint                  -- Discrete Uniform
+   skellam                  -- Skellam
+   yulesimon                -- Yule-Simon
+   zipf                     -- Zipf (Zeta)
+   zipfian                  -- Zipfian
+
+
+An overview of statistical functions is given below.  Many of these functions
+have a similar version in `scipy.stats.mstats` which work for masked arrays.
+
+Summary statistics
+==================
+
+.. autosummary::
+   :toctree: generated/
+
+   describe          -- Descriptive statistics
+   gmean             -- Geometric mean
+   hmean             -- Harmonic mean
+   pmean             -- Power mean
+   kurtosis          -- Fisher or Pearson kurtosis
+   mode              -- Modal value
+   moment            -- Central moment
+   lmoment
+   expectile         -- Expectile
+   skew              -- Skewness
+   kstat             --
+   kstatvar          --
+   tmean             -- Truncated arithmetic mean
+   tvar              -- Truncated variance
+   tmin              --
+   tmax              --
+   tstd              --
+   tsem              --
+   variation         -- Coefficient of variation
+   find_repeats
+   rankdata
+   tiecorrect
+   trim_mean
+   gstd              -- Geometric Standard Deviation
+   iqr
+   sem
+   bayes_mvs
+   mvsdist
+   entropy
+   differential_entropy
+   median_abs_deviation
+
+Frequency statistics
+====================
+
+.. autosummary::
+   :toctree: generated/
+
+   cumfreq
+   percentileofscore
+   scoreatpercentile
+   relfreq
+
+.. autosummary::
+   :toctree: generated/
+
+   binned_statistic     -- Compute a binned statistic for a set of data.
+   binned_statistic_2d  -- Compute a 2-D binned statistic for a set of data.
+   binned_statistic_dd  -- Compute a d-D binned statistic for a set of data.
+
+.. _hypotests:
+
+Hypothesis Tests and related functions
+======================================
+SciPy has many functions for performing hypothesis tests that return a
+test statistic and a p-value, and several of them return confidence intervals
+and/or other related information.
+
+The headings below are based on common uses of the functions within, but due to
+the wide variety of statistical procedures, any attempt at coarse-grained
+categorization will be imperfect. Also, note that tests within the same heading
+are not interchangeable in general (e.g. many have different distributional
+assumptions).
+
+One Sample Tests / Paired Sample Tests
+--------------------------------------
+One sample tests are typically used to assess whether a single sample was
+drawn from a specified distribution or a distribution with specified properties
+(e.g. zero mean).
+
+.. autosummary::
+   :toctree: generated/
+
+   ttest_1samp
+   binomtest
+   quantile_test
+   skewtest
+   kurtosistest
+   normaltest
+   jarque_bera
+   shapiro
+   anderson
+   cramervonmises
+   ks_1samp
+   goodness_of_fit
+   chisquare
+   power_divergence
+
+Paired sample tests are often used to assess whether two samples were drawn
+from the same distribution; they differ from the independent sample tests below
+in that each observation in one sample is treated as paired with a
+closely-related observation in the other sample (e.g. when environmental
+factors are controlled between observations within a pair but not among pairs).
+They can also be interpreted or used as one-sample tests (e.g. tests on the
+mean or median of *differences* between paired observations).
+
+.. autosummary::
+   :toctree: generated/
+
+   ttest_rel
+   wilcoxon
+
+Association/Correlation Tests
+-----------------------------
+
+These tests are often used to assess whether there is a relationship (e.g.
+linear) between paired observations in multiple samples or among the
+coordinates of multivariate observations.
+
+.. autosummary::
+   :toctree: generated/
+
+   linregress
+   pearsonr
+   spearmanr
+   pointbiserialr
+   kendalltau
+   chatterjeexi
+   weightedtau
+   somersd
+   siegelslopes
+   theilslopes
+   page_trend_test
+   multiscale_graphcorr
+
+These association tests and are to work with samples in the form of contingency
+tables. Supporting functions are available in `scipy.stats.contingency`.
+
+.. autosummary::
+   :toctree: generated/
+
+   chi2_contingency
+   fisher_exact
+   barnard_exact
+   boschloo_exact
+
+Independent Sample Tests
+------------------------
+Independent sample tests are typically used to assess whether multiple samples
+were independently drawn from the same distribution or different distributions
+with a shared property (e.g. equal means).
+
+Some tests are specifically for comparing two samples.
+
+.. autosummary::
+   :toctree: generated/
+
+   ttest_ind_from_stats
+   poisson_means_test
+   ttest_ind
+   mannwhitneyu
+   bws_test
+   ranksums
+   brunnermunzel
+   mood
+   ansari
+   cramervonmises_2samp
+   epps_singleton_2samp
+   ks_2samp
+   kstest
+
+Others are generalized to multiple samples.
+
+.. autosummary::
+   :toctree: generated/
+
+   f_oneway
+   tukey_hsd
+   dunnett
+   kruskal
+   alexandergovern
+   fligner
+   levene
+   bartlett
+   median_test
+   friedmanchisquare
+   anderson_ksamp
+
+Resampling and Monte Carlo Methods
+----------------------------------
+The following functions can reproduce the p-value and confidence interval
+results of most of the functions above, and often produce accurate results in a
+wider variety of conditions. They can also be used to perform hypothesis tests
+and generate confidence intervals for custom statistics. This flexibility comes
+at the cost of greater computational requirements and stochastic results.
+
+.. autosummary::
+   :toctree: generated/
+
+   monte_carlo_test
+   permutation_test
+   bootstrap
+   power
+
+Instances of the following object can be passed into some hypothesis test
+functions to perform a resampling or Monte Carlo version of the hypothesis
+test.
+
+.. autosummary::
+   :toctree: generated/
+
+   MonteCarloMethod
+   PermutationMethod
+   BootstrapMethod
+
+Multiple Hypothesis Testing and Meta-Analysis
+---------------------------------------------
+These functions are for assessing the results of individual tests as a whole.
+Functions for performing specific multiple hypothesis tests (e.g. post hoc
+tests) are listed above.
+
+.. autosummary::
+   :toctree: generated/
+
+   combine_pvalues
+   false_discovery_control
+
+
+The following functions are related to the tests above but do not belong in the
+above categories.
+
+Random Variables
+================
+
+.. autosummary::
+   :toctree: generated/
+
+   make_distribution
+   Normal
+   Uniform
+   Mixture
+   order_statistic
+   truncate
+   abs
+   exp
+   log
+
+Quasi-Monte Carlo
+=================
+
+.. toctree::
+   :maxdepth: 4
+
+   stats.qmc
+
+Contingency Tables
+==================
+
+.. toctree::
+   :maxdepth: 4
+
+   stats.contingency
+
+Masked statistics functions
+===========================
+
+.. toctree::
+
+   stats.mstats
+
+
+Other statistical functionality
+===============================
+
+Transformations
+---------------
+
+.. autosummary::
+   :toctree: generated/
+
+   boxcox
+   boxcox_normmax
+   boxcox_llf
+   yeojohnson
+   yeojohnson_normmax
+   yeojohnson_llf
+   obrientransform
+   sigmaclip
+   trimboth
+   trim1
+   zmap
+   zscore
+   gzscore
+
+Statistical distances
+---------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   wasserstein_distance
+   wasserstein_distance_nd
+   energy_distance
+
+Sampling
+--------
+
+.. toctree::
+   :maxdepth: 4
+
+   stats.sampling
+
+Fitting / Survival Analysis
+---------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   fit
+   ecdf
+   logrank
+
+Directional statistical functions
+---------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   directional_stats
+   circmean
+   circvar
+   circstd
+
+Sensitivity Analysis
+--------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   sobol_indices
+
+Plot-tests
+----------
+
+.. autosummary::
+   :toctree: generated/
+
+   ppcc_max
+   ppcc_plot
+   probplot
+   boxcox_normplot
+   yeojohnson_normplot
+
+Univariate and multivariate kernel density estimation
+-----------------------------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   gaussian_kde
+
+Warnings / Errors used in :mod:`scipy.stats`
+--------------------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   DegenerateDataWarning
+   ConstantInputWarning
+   NearConstantInputWarning
+   FitError
+
+Result classes used in :mod:`scipy.stats`
+-----------------------------------------
+
+.. warning::
+
+    These classes are private, but they are included here because instances
+    of them are returned by other statistical functions. User import and
+    instantiation is not supported.
+
+.. toctree::
+   :maxdepth: 2
+
+   stats._result_classes
+
+"""  # noqa: E501
+
+from ._warnings_errors import (ConstantInputWarning, NearConstantInputWarning,
+                               DegenerateDataWarning, FitError)
+from ._stats_py import *
+from ._variation import variation
+from .distributions import *
+from ._morestats import *
+from ._multicomp import *
+from ._binomtest import binomtest
+from ._binned_statistic import *
+from ._kde import gaussian_kde
+from . import mstats
+from . import qmc
+from ._multivariate import *
+from . import contingency
+from .contingency import chi2_contingency
+from ._censored_data import CensoredData
+from ._resampling import (bootstrap, monte_carlo_test, permutation_test, power,
+                          MonteCarloMethod, PermutationMethod, BootstrapMethod)
+from ._entropy import *
+from ._hypotests import *
+from ._page_trend_test import page_trend_test
+from ._mannwhitneyu import mannwhitneyu
+from ._bws_test import bws_test
+from ._fit import fit, goodness_of_fit
+from ._covariance import Covariance
+from ._sensitivity_analysis import *
+from ._survival import *
+from ._distribution_infrastructure import (
+    make_distribution, Mixture, order_statistic, truncate, exp, log, abs
+)
+from ._new_distributions import Normal, Uniform
+from ._mgc import multiscale_graphcorr
+from ._correlation import chatterjeexi
+
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+    biasedurn, kde, morestats, mstats_basic, mstats_extras, mvn, stats
+)
+
+
+__all__ = [s for s in dir() if not s.startswith("_")]  # Remove dunders.
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91c22e8bd6fbc9819de3973a29581633adcfb60b
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_axis_nan_policy.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_axis_nan_policy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29a053df2cfa84e621e41ce8cbaa922335fd438d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_axis_nan_policy.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binned_statistic.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binned_statistic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da8133ea7a6441e1d810cb9ff5b76e9f1a03ba43
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binned_statistic.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binomtest.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binomtest.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36c38adaef350e49a819789b05b9c4b42f7d9efd
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_binomtest.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_bws_test.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_bws_test.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d495a59a59643731519df616ccdd581637f7b44c
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_bws_test.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_censored_data.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_censored_data.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57ffba9b26e33a3f1a4a409c53cc22455e6e700b
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_censored_data.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_common.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_common.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7ca29be121f3fd346bc0ce1a856c12aeac9fb23
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_common.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_constants.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_constants.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd4491a1b0cb2de1dfcc593c358ba9381bc744ef
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_constants.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_correlation.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_correlation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6a500ee4395f9dc3d8816c68375e6bbca750509a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_correlation.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_covariance.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_covariance.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c705ec77c1a1e2dc1a60a7d77f09cec14f5d5216
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_covariance.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_crosstab.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_crosstab.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a9a1dd89f2426e39b205423a408a951f966a47a
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_crosstab.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_discrete_distns.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_discrete_distns.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a67afa0d8c8b62338c2d29e57fb39e271114d5cd
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_discrete_distns.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_distr_params.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_distr_params.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a5ccf472f3e609bc794da56be2763f0113dba999
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_distr_params.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_entropy.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_entropy.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ada2f463a8a542f734e312f9e6d675be4344b3f4
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_entropy.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_fit.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_fit.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fd558fa5ea555810ba68c9e77d0e629e6f57045
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_fit.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_hypotests.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_hypotests.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..664cc5e625a351628819d41a13b71e1a6944f80e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_hypotests.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_kde.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_kde.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ad5453d907aeeb2674ff215ecb9b84613c50dad
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_kde.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_ksstats.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_ksstats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6e9290917f2d5e3132eb04ee57d8bab774093f48
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_ksstats.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mannwhitneyu.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mannwhitneyu.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74f8b57cc7acd995ea07e5416c04afafa1f72fed
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mannwhitneyu.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mgc.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mgc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..809c26bf8eca749bb7ba2122567e58acdc0bc6fa
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mgc.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mstats_extras.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mstats_extras.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..220d9058e1944442c528cde38cd980dd1ab23d11
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_mstats_extras.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_multicomp.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_multicomp.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f58e672f69b0d1aa5b4ec0e89b7d0d2e1a2d258c
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_multicomp.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_new_distributions.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_new_distributions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d612e1153e484f49a5d294f535782fb763f2286
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_new_distributions.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_odds_ratio.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_odds_ratio.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ffd7e4ebaa553d5363544f8ca099ed77d3777fb
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_odds_ratio.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_page_trend_test.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_page_trend_test.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7396a979b19379b7fb4dbae9638e65e42a37d0bb
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_page_trend_test.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_probability_distribution.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_probability_distribution.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c7cd0fe66ca95f9471915ced370bcbdf7747b55
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_probability_distribution.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmc.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a56d632c399a86dc1f018a1968ddf7a83875b4d6
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmc.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmvnt.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmvnt.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..924772b1b0d633e13e19607a655d3422e944f8b7
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmvnt.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_relative_risk.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_relative_risk.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2790df00a75e906d16a1b659456bb48782e49928
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_relative_risk.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_resampling.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_resampling.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa37ebef16c0f54b5d2f4abaf70a7a8bc94e94bc
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_resampling.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_sensitivity_analysis.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_sensitivity_analysis.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..661c08201ab57ebe97a0135d15093764ec148256
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_sensitivity_analysis.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_stats_mstats_common.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_stats_mstats_common.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..308903fea571c0f28ed6c3dbe910f257aa7ce303
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_stats_mstats_common.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_survival.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_survival.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29e46f33c48a7682d0bb322c3d5a9a03fb3b739f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_survival.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_tukeylambda_stats.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_tukeylambda_stats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6dff73d9410240f57df67449b28237a7165f9418
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_tukeylambda_stats.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_variation.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_variation.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a52a88265e998b7de0c1e27178d9301f8cd36439
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_variation.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_warnings_errors.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_warnings_errors.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..55ef900800edc762d5d4e4daed47fb8c29c2132e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_warnings_errors.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_wilcoxon.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_wilcoxon.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a06b716ac7984624c02731eed4851438d84c9905
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/_wilcoxon.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/biasedurn.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/biasedurn.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ab414ce88e6d63e1899ce596bc5301f9347430d
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/biasedurn.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/contingency.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/contingency.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9d899e66a7476c53a7dcba49d9db6ecdbb59b6e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/contingency.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/distributions.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/distributions.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0514ab2a8a029b3ba5a4327ab139eb53c2ea6370
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/distributions.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/kde.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/kde.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..303ea4ac6437a8362a37aea1a6d3dc22143c0042
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/kde.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/morestats.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/morestats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b417a26233dda8056bb98ce171a1f9af5c2a52f6
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/morestats.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5edd32e540be7ac79424c7c4826299f942e777f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_basic.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_basic.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a8d786282c7f6046718065afda3dee76e18abbd
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_basic.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_extras.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_extras.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74fa6113de5057c135f542caea3844296d293e40
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_extras.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mvn.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mvn.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e027ccd659e7a2934c465a03ccfb725de94bb23f
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/mvn.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/qmc.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/qmc.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1f1a0bab2dd98a1ea2862435492fc09db0afcb7
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/qmc.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/stats.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/stats.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c9ecc333c0cf42d17633dd5307732ce1d5fce86
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/__pycache__/stats.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_axis_nan_policy.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_axis_nan_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..26a4492056f83647059fbf72b0bf6538474b7451
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_axis_nan_policy.py
@@ -0,0 +1,699 @@
+# Many scipy.stats functions support `axis` and `nan_policy` parameters.
+# When the two are combined, it can be tricky to get all the behavior just
+# right. This file contains utility functions useful for scipy.stats functions
+# that support `axis` and `nan_policy`, including a decorator that
+# automatically adds `axis` and `nan_policy` arguments to a function.
+
+import warnings
+import numpy as np
+from functools import wraps
+from scipy._lib._docscrape import FunctionDoc, Parameter
+from scipy._lib._util import _contains_nan, AxisError, _get_nan
+from scipy._lib._array_api import array_namespace, is_numpy
+
+import inspect
+
+too_small_1d_not_omit = (
+    "One or more sample arguments is too small; all "
+    "returned values will be NaN. "
+    "See documentation for sample size requirements.")
+
+too_small_1d_omit = (
+    "After omitting NaNs, one or more sample arguments "
+    "is too small; all returned values will be NaN. "
+    "See documentation for sample size requirements.")
+
+too_small_nd_not_omit = (
+    "All axis-slices of one or more sample arguments are "
+    "too small; all elements of returned arrays will be NaN. "
+    "See documentation for sample size requirements.")
+
+too_small_nd_omit = (
+    "After omitting NaNs, one or more axis-slices of one "
+    "or more sample arguments is too small; corresponding "
+    "elements of returned arrays will be NaN. "
+    "See documentation for sample size requirements.")
+
+class SmallSampleWarning(RuntimeWarning):
+    pass
+
+
+def _broadcast_arrays(arrays, axis=None, xp=None):
+    """
+    Broadcast shapes of arrays, ignoring incompatibility of specified axes
+    """
+    if not arrays:
+        return arrays
+    xp = array_namespace(*arrays) if xp is None else xp
+    arrays = [xp.asarray(arr) for arr in arrays]
+    shapes = [arr.shape for arr in arrays]
+    new_shapes = _broadcast_shapes(shapes, axis)
+    if axis is None:
+        new_shapes = [new_shapes]*len(arrays)
+    return [xp.broadcast_to(array, new_shape)
+            for array, new_shape in zip(arrays, new_shapes)]
+
+
+def _broadcast_shapes(shapes, axis=None):
+    """
+    Broadcast shapes, ignoring incompatibility of specified axes
+    """
+    if not shapes:
+        return shapes
+
+    # input validation
+    if axis is not None:
+        axis = np.atleast_1d(axis)
+        message = '`axis` must be an integer, a tuple of integers, or `None`.'
+        try:
+            with np.errstate(invalid='ignore'):
+                axis_int = axis.astype(int)
+        except ValueError as e:
+            raise AxisError(message) from e
+        if not np.array_equal(axis_int, axis):
+            raise AxisError(message)
+        axis = axis_int
+
+    # First, ensure all shapes have same number of dimensions by prepending 1s.
+    n_dims = max([len(shape) for shape in shapes])
+    new_shapes = np.ones((len(shapes), n_dims), dtype=int)
+    for row, shape in zip(new_shapes, shapes):
+        row[len(row)-len(shape):] = shape  # can't use negative indices (-0:)
+
+    # Remove the shape elements of the axes to be ignored, but remember them.
+    if axis is not None:
+        axis[axis < 0] = n_dims + axis[axis < 0]
+        axis = np.sort(axis)
+        if axis[-1] >= n_dims or axis[0] < 0:
+            message = (f"`axis` is out of bounds "
+                       f"for array of dimension {n_dims}")
+            raise AxisError(message)
+
+        if len(np.unique(axis)) != len(axis):
+            raise AxisError("`axis` must contain only distinct elements")
+
+        removed_shapes = new_shapes[:, axis]
+        new_shapes = np.delete(new_shapes, axis, axis=1)
+
+    # If arrays are broadcastable, shape elements that are 1 may be replaced
+    # with a corresponding non-1 shape element. Assuming arrays are
+    # broadcastable, that final shape element can be found with:
+    new_shape = np.max(new_shapes, axis=0)
+    # except in case of an empty array:
+    new_shape *= new_shapes.all(axis=0)
+
+    # Among all arrays, there can only be one unique non-1 shape element.
+    # Therefore, if any non-1 shape element does not match what we found
+    # above, the arrays must not be broadcastable after all.
+    if np.any(~((new_shapes == 1) | (new_shapes == new_shape))):
+        raise ValueError("Array shapes are incompatible for broadcasting.")
+
+    if axis is not None:
+        # Add back the shape elements that were ignored
+        new_axis = axis - np.arange(len(axis))
+        new_shapes = [tuple(np.insert(new_shape, new_axis, removed_shape))
+                      for removed_shape in removed_shapes]
+        return new_shapes
+    else:
+        return tuple(new_shape)
+
+
+def _broadcast_array_shapes_remove_axis(arrays, axis=None):
+    """
+    Broadcast shapes of arrays, dropping specified axes
+
+    Given a sequence of arrays `arrays` and an integer or tuple `axis`, find
+    the shape of the broadcast result after consuming/dropping `axis`.
+    In other words, return output shape of a typical hypothesis test on
+    `arrays` vectorized along `axis`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats._axis_nan_policy import _broadcast_array_shapes_remove_axis
+    >>> a = np.zeros((5, 2, 1))
+    >>> b = np.zeros((9, 3))
+    >>> _broadcast_array_shapes_remove_axis((a, b), 1)
+    (5, 3)
+    """
+    # Note that here, `axis=None` means do not consume/drop any axes - _not_
+    # ravel arrays before broadcasting.
+    shapes = [arr.shape for arr in arrays]
+    return _broadcast_shapes_remove_axis(shapes, axis)
+
+
+def _broadcast_shapes_remove_axis(shapes, axis=None):
+    """
+    Broadcast shapes, dropping specified axes
+
+    Same as _broadcast_array_shapes_remove_axis, but given a sequence
+    of array shapes `shapes` instead of the arrays themselves.
+    """
+    shapes = _broadcast_shapes(shapes, axis)
+    shape = shapes[0]
+    if axis is not None:
+        shape = np.delete(shape, axis)
+    return tuple(shape)
+
+
+def _broadcast_concatenate(arrays, axis, paired=False):
+    """Concatenate arrays along an axis with broadcasting."""
+    arrays = _broadcast_arrays(arrays, axis if not paired else None)
+    res = np.concatenate(arrays, axis=axis)
+    return res
+
+
+# TODO: add support for `axis` tuples
+def _remove_nans(samples, paired):
+    "Remove nans from paired or unpaired 1D samples"
+    # potential optimization: don't copy arrays that don't contain nans
+    if not paired:
+        return [sample[~np.isnan(sample)] for sample in samples]
+
+    # for paired samples, we need to remove the whole pair when any part
+    # has a nan
+    nans = np.isnan(samples[0])
+    for sample in samples[1:]:
+        nans = nans | np.isnan(sample)
+    not_nans = ~nans
+    return [sample[not_nans] for sample in samples]
+
+
+def _remove_sentinel(samples, paired, sentinel):
+    "Remove sentinel values from paired or unpaired 1D samples"
+    # could consolidate with `_remove_nans`, but it's not quite as simple as
+    # passing `sentinel=np.nan` because `(np.nan == np.nan) is False`
+
+    # potential optimization: don't copy arrays that don't contain sentinel
+    if not paired:
+        return [sample[sample != sentinel] for sample in samples]
+
+    # for paired samples, we need to remove the whole pair when any part
+    # has a nan
+    sentinels = (samples[0] == sentinel)
+    for sample in samples[1:]:
+        sentinels = sentinels | (sample == sentinel)
+    not_sentinels = ~sentinels
+    return [sample[not_sentinels] for sample in samples]
+
+
+def _masked_arrays_2_sentinel_arrays(samples):
+    # masked arrays in `samples` are converted to regular arrays, and values
+    # corresponding with masked elements are replaced with a sentinel value
+
+    # return without modifying arrays if none have a mask
+    has_mask = False
+    for sample in samples:
+        mask = getattr(sample, 'mask', False)
+        has_mask = has_mask or np.any(mask)
+    if not has_mask:
+        return samples, None  # None means there is no sentinel value
+
+    # Choose a sentinel value. We can't use `np.nan`, because sentinel (masked)
+    # values are always omitted, but there are different nan policies.
+    dtype = np.result_type(*samples)
+    dtype = dtype if np.issubdtype(dtype, np.number) else np.float64
+    for i in range(len(samples)):
+        # Things get more complicated if the arrays are of different types.
+        # We could have different sentinel values for each array, but
+        # the purpose of this code is convenience, not efficiency.
+        samples[i] = samples[i].astype(dtype, copy=False)
+
+    inexact = np.issubdtype(dtype, np.inexact)
+    info = np.finfo if inexact else np.iinfo
+    max_possible, min_possible = info(dtype).max, info(dtype).min
+    nextafter = np.nextafter if inexact else (lambda x, _: x - 1)
+
+    sentinel = max_possible
+    # For simplicity, min_possible/np.infs are not candidate sentinel values
+    while sentinel > min_possible:
+        for sample in samples:
+            if np.any(sample == sentinel):  # choose a new sentinel value
+                sentinel = nextafter(sentinel, -np.inf)
+                break
+        else:  # when sentinel value is OK, break the while loop
+            break
+    else:
+        message = ("This function replaces masked elements with sentinel "
+                   "values, but the data contains all distinct values of this "
+                   "data type. Consider promoting the dtype to `np.float64`.")
+        raise ValueError(message)
+
+    # replace masked elements with sentinel value
+    out_samples = []
+    for sample in samples:
+        mask = getattr(sample, 'mask', None)
+        if mask is not None:  # turn all masked arrays into sentinel arrays
+            mask = np.broadcast_to(mask, sample.shape)
+            sample = sample.data.copy() if np.any(mask) else sample.data
+            sample = np.asarray(sample)  # `sample.data` could be a memoryview?
+            sample[mask] = sentinel
+        out_samples.append(sample)
+
+    return out_samples, sentinel
+
+
+def _check_empty_inputs(samples, axis):
+    """
+    Check for empty sample; return appropriate output for a vectorized hypotest
+    """
+    # if none of the samples are empty, we need to perform the test
+    if not any(sample.size == 0 for sample in samples):
+        return None
+    # otherwise, the statistic and p-value will be either empty arrays or
+    # arrays with NaNs. Produce the appropriate array and return it.
+    output_shape = _broadcast_array_shapes_remove_axis(samples, axis)
+    output = np.ones(output_shape) * _get_nan(*samples)
+    return output
+
+
+def _add_reduced_axes(res, reduced_axes, keepdims):
+    """
+    Add reduced axes back to all the arrays in the result object
+    if keepdims = True.
+    """
+    return ([np.expand_dims(output, reduced_axes) 
+             if not isinstance(output, int) else output for output in res]
+            if keepdims else res)
+
+
+# Standard docstring / signature entries for `axis`, `nan_policy`, `keepdims`
+_name = 'axis'
+_desc = (
+    """If an int, the axis of the input along which to compute the statistic.
+The statistic of each axis-slice (e.g. row) of the input will appear in a
+corresponding element of the output.
+If ``None``, the input will be raveled before computing the statistic."""
+    .split('\n'))
+
+
+def _get_axis_params(default_axis=0, _name=_name, _desc=_desc):  # bind NOW
+    _type = f"int or None, default: {default_axis}"
+    _axis_parameter_doc = Parameter(_name, _type, _desc)
+    _axis_parameter = inspect.Parameter(_name,
+                                        inspect.Parameter.KEYWORD_ONLY,
+                                        default=default_axis)
+    return _axis_parameter_doc, _axis_parameter
+
+
+_name = 'nan_policy'
+_type = "{'propagate', 'omit', 'raise'}"
+_desc = (
+    """Defines how to handle input NaNs.
+
+- ``propagate``: if a NaN is present in the axis slice (e.g. row) along
+  which the  statistic is computed, the corresponding entry of the output
+  will be NaN.
+- ``omit``: NaNs will be omitted when performing the calculation.
+  If insufficient data remains in the axis slice along which the
+  statistic is computed, the corresponding entry of the output will be
+  NaN.
+- ``raise``: if a NaN is present, a ``ValueError`` will be raised."""
+    .split('\n'))
+_nan_policy_parameter_doc = Parameter(_name, _type, _desc)
+_nan_policy_parameter = inspect.Parameter(_name,
+                                          inspect.Parameter.KEYWORD_ONLY,
+                                          default='propagate')
+
+_name = 'keepdims'
+_type = "bool, default: False"
+_desc = (
+    """If this is set to True, the axes which are reduced are left
+in the result as dimensions with size one. With this option,
+the result will broadcast correctly against the input array."""
+    .split('\n'))
+_keepdims_parameter_doc = Parameter(_name, _type, _desc)
+_keepdims_parameter = inspect.Parameter(_name,
+                                        inspect.Parameter.KEYWORD_ONLY,
+                                        default=False)
+
+_standard_note_addition = (
+    """\nBeginning in SciPy 1.9, ``np.matrix`` inputs (not recommended for new
+code) are converted to ``np.ndarray`` before the calculation is performed. In
+this case, the output will be a scalar or ``np.ndarray`` of appropriate shape
+rather than a 2D ``np.matrix``. Similarly, while masked elements of masked
+arrays are ignored, the output will be a scalar or ``np.ndarray`` rather than a
+masked array with ``mask=False``.""").split('\n')
+
+
+def _axis_nan_policy_factory(tuple_to_result, default_axis=0,
+                             n_samples=1, paired=False,
+                             result_to_tuple=None, too_small=0,
+                             n_outputs=2, kwd_samples=(), override=None):
+    """Factory for a wrapper that adds axis/nan_policy params to a function.
+
+    Parameters
+    ----------
+    tuple_to_result : callable
+        Callable that returns an object of the type returned by the function
+        being wrapped (e.g. the namedtuple or dataclass returned by a
+        statistical test) provided the separate components (e.g. statistic,
+        pvalue).
+    default_axis : int, default: 0
+        The default value of the axis argument. Standard is 0 except when
+        backwards compatibility demands otherwise (e.g. `None`).
+    n_samples : int or callable, default: 1
+        The number of data samples accepted by the function
+        (e.g. `mannwhitneyu`), a callable that accepts a dictionary of
+        parameters passed into the function and returns the number of data
+        samples (e.g. `wilcoxon`), or `None` to indicate an arbitrary number
+        of samples (e.g. `kruskal`).
+    paired : {False, True}
+        Whether the function being wrapped treats the samples as paired (i.e.
+        corresponding elements of each sample should be considered as different
+        components of the same sample.)
+    result_to_tuple : callable, optional
+        Function that unpacks the results of the function being wrapped into
+        a tuple. This is essentially the inverse of `tuple_to_result`. Default
+        is `None`, which is appropriate for statistical tests that return a
+        statistic, pvalue tuple (rather than, e.g., a non-iterable datalass).
+    too_small : int or callable, default: 0
+        The largest unnacceptably small sample for the function being wrapped.
+        For example, some functions require samples of size two or more or they
+        raise an error. This argument prevents the error from being raised when
+        input is not 1D and instead places a NaN in the corresponding element
+        of the result. If callable, it must accept a list of samples, axis,
+        and a dictionary of keyword arguments passed to the wrapper function as
+        arguments and return a bool indicating weather the samples passed are
+        too small.
+    n_outputs : int or callable, default: 2
+        The number of outputs produced by the function given 1d sample(s). For
+        example, hypothesis tests that return a namedtuple or result object
+        with attributes ``statistic`` and ``pvalue`` use the default
+        ``n_outputs=2``; summary statistics with scalar output use
+        ``n_outputs=1``. Alternatively, may be a callable that accepts a
+        dictionary of arguments passed into the wrapped function and returns
+        the number of outputs corresponding with those arguments.
+    kwd_samples : sequence, default: ()
+        The names of keyword parameters that should be treated as samples. For
+        example, `gmean` accepts as its first argument a sample `a` but
+        also `weights` as a fourth, optional keyword argument. In this case, we
+        use `n_samples=1` and kwd_samples=['weights'].
+    override : dict, default: {'vectorization': False, 'nan_propagation': True}
+        Pass a dictionary with ``'vectorization': True`` to ensure that the
+        decorator overrides the function's behavior for multimensional input.
+        Use ``'nan_propagation': False`` to ensure that the decorator does not
+        override the function's behavior for ``nan_policy='propagate'``.
+    """
+    # Specify which existing behaviors the decorator must override
+    temp = override or {}
+    override = {'vectorization': False,
+                'nan_propagation': True}
+    override.update(temp)
+
+    if result_to_tuple is None:
+        def result_to_tuple(res):
+            return res
+
+    # The only `result_to_tuple` that needs the second argument (number of
+    # outputs) is the one for `moment`, and this was realized very late.
+    # Rather than changing all `result_to_tuple` definitions, we wrap them
+    # here to accept a second argument if they don't already.
+    if len(inspect.signature(result_to_tuple).parameters) == 1:
+        def result_to_tuple(res, _, f=result_to_tuple):
+            return f(res)
+
+    if not callable(too_small):
+        def is_too_small(samples, *ts_args, axis=-1, **ts_kwargs):
+            for sample in samples:
+                if sample.shape[axis] <= too_small:
+                    return True
+            return False
+    else:
+        is_too_small = too_small
+
+    def axis_nan_policy_decorator(hypotest_fun_in):
+        @wraps(hypotest_fun_in)
+        def axis_nan_policy_wrapper(*args, _no_deco=False, **kwds):
+
+            if _no_deco:  # for testing, decorator does nothing
+                return hypotest_fun_in(*args, **kwds)
+
+            # For now, skip the decorator entirely if using array API. In the future,
+            # we'll probably want to use it for `keepdims`, `axis` tuples, etc.
+            if len(args) == 0:  # extract sample from `kwds` if there are no `args`
+                used_kwd_samples = list(set(kwds).intersection(set(kwd_samples)))
+                temp = used_kwd_samples[:1]
+            else:
+                temp = args[0]
+
+            if not is_numpy(array_namespace(temp)):
+                msg = ("Use of `nan_policy` and `keepdims` "
+                       "is incompatible with non-NumPy arrays.")
+                if 'nan_policy' in kwds or 'keepdims' in kwds:
+                    raise NotImplementedError(msg)
+                return hypotest_fun_in(*args, **kwds)
+
+            # We need to be flexible about whether position or keyword
+            # arguments are used, but we need to make sure users don't pass
+            # both for the same parameter. To complicate matters, some
+            # functions accept samples with *args, and some functions already
+            # accept `axis` and `nan_policy` as positional arguments.
+            # The strategy is to make sure that there is no duplication
+            # between `args` and `kwds`, combine the two into `kwds`, then
+            # the samples, `nan_policy`, and `axis` from `kwds`, as they are
+            # dealt with separately.
+
+            # Check for intersection between positional and keyword args
+            params = list(inspect.signature(hypotest_fun_in).parameters)
+            if n_samples is None:
+                # Give unique names to each positional sample argument
+                # Note that *args can't be provided as a keyword argument
+                params = [f"arg{i}" for i in range(len(args))] + params[1:]
+
+            # raise if there are too many positional args
+            maxarg = (np.inf if inspect.getfullargspec(hypotest_fun_in).varargs
+                      else len(inspect.getfullargspec(hypotest_fun_in).args))
+            if len(args) > maxarg:  # let the function raise the right error
+                hypotest_fun_in(*args, **kwds)
+
+            # raise if multiple values passed for same parameter
+            d_args = dict(zip(params, args))
+            intersection = set(d_args) & set(kwds)
+            if intersection:  # let the function raise the right error
+                hypotest_fun_in(*args, **kwds)
+
+            # Consolidate other positional and keyword args into `kwds`
+            kwds.update(d_args)
+
+            # rename avoids UnboundLocalError
+            if callable(n_samples):
+                # Future refactoring idea: no need for callable n_samples.
+                # Just replace `n_samples` and `kwd_samples` with a single
+                # list of the names of all samples, and treat all of them
+                # as `kwd_samples` are treated below.
+                n_samp = n_samples(kwds)
+            else:
+                n_samp = n_samples or len(args)
+
+            # get the number of outputs
+            n_out = n_outputs  # rename to avoid UnboundLocalError
+            if callable(n_out):
+                n_out = n_out(kwds)
+
+            # If necessary, rearrange function signature: accept other samples
+            # as positional args right after the first n_samp args
+            kwd_samp = [name for name in kwd_samples
+                        if kwds.get(name, None) is not None]
+            n_kwd_samp = len(kwd_samp)
+            if not kwd_samp:
+                hypotest_fun_out = hypotest_fun_in
+            else:
+                def hypotest_fun_out(*samples, **kwds):
+                    new_kwds = dict(zip(kwd_samp, samples[n_samp:]))
+                    kwds.update(new_kwds)
+                    return hypotest_fun_in(*samples[:n_samp], **kwds)
+
+            # Extract the things we need here
+            try:  # if something is missing
+                samples = [np.atleast_1d(kwds.pop(param))
+                           for param in (params[:n_samp] + kwd_samp)]
+            except KeyError:  # let the function raise the right error
+                # might need to revisit this if required arg is not a "sample"
+                hypotest_fun_in(*args, **kwds)
+            vectorized = True if 'axis' in params else False
+            vectorized = vectorized and not override['vectorization']
+            axis = kwds.pop('axis', default_axis)
+            nan_policy = kwds.pop('nan_policy', 'propagate')
+            keepdims = kwds.pop("keepdims", False)
+            del args  # avoid the possibility of passing both `args` and `kwds`
+
+            # convert masked arrays to regular arrays with sentinel values
+            samples, sentinel = _masked_arrays_2_sentinel_arrays(samples)
+
+            # standardize to always work along last axis
+            reduced_axes = axis
+            if axis is None:
+                if samples:
+                    # when axis=None, take the maximum of all dimensions since
+                    # all the dimensions are reduced.
+                    n_dims = np.max([sample.ndim for sample in samples])
+                    reduced_axes = tuple(range(n_dims))
+                samples = [np.asarray(sample.ravel()) for sample in samples]
+            else:
+                # don't ignore any axes when broadcasting if paired
+                samples = _broadcast_arrays(samples, axis=axis if not paired else None)
+                axis = np.atleast_1d(axis)
+                n_axes = len(axis)
+                # move all axes in `axis` to the end to be raveled
+                samples = [np.moveaxis(sample, axis, range(-len(axis), 0))
+                           for sample in samples]
+                shapes = [sample.shape for sample in samples]
+                # New shape is unchanged for all axes _not_ in `axis`
+                # At the end, we append the product of the shapes of the axes
+                # in `axis`. Appending -1 doesn't work for zero-size arrays!
+                new_shapes = [shape[:-n_axes] + (np.prod(shape[-n_axes:]),)
+                              for shape in shapes]
+                samples = [sample.reshape(new_shape)
+                           for sample, new_shape in zip(samples, new_shapes)]
+            axis = -1  # work over the last axis
+            NaN = _get_nan(*samples) if samples else np.nan
+
+            # if axis is not needed, just handle nan_policy and return
+            ndims = np.array([sample.ndim for sample in samples])
+            if np.all(ndims <= 1):
+                # Addresses nan_policy == "raise"
+                if nan_policy != 'propagate' or override['nan_propagation']:
+                    contains_nan = [_contains_nan(sample, nan_policy)[0]
+                                    for sample in samples]
+                else:
+                    # Behave as though there are no NaNs (even if there are)
+                    contains_nan = [False]*len(samples)
+
+                # Addresses nan_policy == "propagate"
+                if any(contains_nan) and (nan_policy == 'propagate'
+                                          and override['nan_propagation']):
+                    res = np.full(n_out, NaN)
+                    res = _add_reduced_axes(res, reduced_axes, keepdims)
+                    return tuple_to_result(*res)
+
+                # Addresses nan_policy == "omit"
+                too_small_msg = too_small_1d_not_omit
+                if any(contains_nan) and nan_policy == 'omit':
+                    # consider passing in contains_nan
+                    samples = _remove_nans(samples, paired)
+                    too_small_msg = too_small_1d_omit
+
+                if sentinel:
+                    samples = _remove_sentinel(samples, paired, sentinel)
+
+                if is_too_small(samples, kwds):
+                    warnings.warn(too_small_msg, SmallSampleWarning, stacklevel=2)
+                    res = np.full(n_out, NaN)
+                    res = _add_reduced_axes(res, reduced_axes, keepdims)
+                    return tuple_to_result(*res)
+
+                res = hypotest_fun_out(*samples, **kwds)
+                res = result_to_tuple(res, n_out)
+                res = _add_reduced_axes(res, reduced_axes, keepdims)
+                return tuple_to_result(*res)
+
+            # check for empty input
+            empty_output = _check_empty_inputs(samples, axis)
+            # only return empty output if zero sized input is too small.
+            if (
+                empty_output is not None
+                and (is_too_small(samples, kwds) or empty_output.size == 0)
+            ):
+                if is_too_small(samples, kwds) and empty_output.size != 0:
+                    warnings.warn(too_small_nd_not_omit, SmallSampleWarning,
+                                  stacklevel=2)
+                res = [empty_output.copy() for i in range(n_out)]
+                res = _add_reduced_axes(res, reduced_axes, keepdims)
+                return tuple_to_result(*res)
+
+            # otherwise, concatenate all samples along axis, remembering where
+            # each separate sample begins
+            lengths = np.array([sample.shape[axis] for sample in samples])
+            split_indices = np.cumsum(lengths)
+            x = _broadcast_concatenate(samples, axis, paired=paired)
+
+            # Addresses nan_policy == "raise"
+            if nan_policy != 'propagate' or override['nan_propagation']:
+                contains_nan, _ = _contains_nan(x, nan_policy)
+            else:
+                contains_nan = False  # behave like there are no NaNs
+
+            if vectorized and not contains_nan and not sentinel:
+                res = hypotest_fun_out(*samples, axis=axis, **kwds)
+                res = result_to_tuple(res, n_out)
+                res = _add_reduced_axes(res, reduced_axes, keepdims)
+                return tuple_to_result(*res)
+
+            # Addresses nan_policy == "omit"
+            if contains_nan and nan_policy == 'omit':
+                def hypotest_fun(x):
+                    samples = np.split(x, split_indices)[:n_samp+n_kwd_samp]
+                    samples = _remove_nans(samples, paired)
+                    if sentinel:
+                        samples = _remove_sentinel(samples, paired, sentinel)
+                    if is_too_small(samples, kwds):
+                        warnings.warn(too_small_nd_omit, SmallSampleWarning,
+                                      stacklevel=4)
+                        return np.full(n_out, NaN)
+                    return result_to_tuple(hypotest_fun_out(*samples, **kwds), n_out)
+
+            # Addresses nan_policy == "propagate"
+            elif (contains_nan and nan_policy == 'propagate'
+                  and override['nan_propagation']):
+                def hypotest_fun(x):
+                    if np.isnan(x).any():
+                        return np.full(n_out, NaN)
+
+                    samples = np.split(x, split_indices)[:n_samp+n_kwd_samp]
+                    if sentinel:
+                        samples = _remove_sentinel(samples, paired, sentinel)
+                    if is_too_small(samples, kwds):
+                        return np.full(n_out, NaN)
+                    return result_to_tuple(hypotest_fun_out(*samples, **kwds), n_out)
+
+            else:
+                def hypotest_fun(x):
+                    samples = np.split(x, split_indices)[:n_samp+n_kwd_samp]
+                    if sentinel:
+                        samples = _remove_sentinel(samples, paired, sentinel)
+                    if is_too_small(samples, kwds):
+                        return np.full(n_out, NaN)
+                    return result_to_tuple(hypotest_fun_out(*samples, **kwds), n_out)
+
+            x = np.moveaxis(x, axis, 0)
+            res = np.apply_along_axis(hypotest_fun, axis=0, arr=x)
+            res = _add_reduced_axes(res, reduced_axes, keepdims)
+            return tuple_to_result(*res)
+
+        _axis_parameter_doc, _axis_parameter = _get_axis_params(default_axis)
+        doc = FunctionDoc(axis_nan_policy_wrapper)
+        parameter_names = [param.name for param in doc['Parameters']]
+        if 'axis' in parameter_names:
+            doc['Parameters'][parameter_names.index('axis')] = (
+                _axis_parameter_doc)
+        else:
+            doc['Parameters'].append(_axis_parameter_doc)
+        if 'nan_policy' in parameter_names:
+            doc['Parameters'][parameter_names.index('nan_policy')] = (
+                _nan_policy_parameter_doc)
+        else:
+            doc['Parameters'].append(_nan_policy_parameter_doc)
+        if 'keepdims' in parameter_names:
+            doc['Parameters'][parameter_names.index('keepdims')] = (
+                _keepdims_parameter_doc)
+        else:
+            doc['Parameters'].append(_keepdims_parameter_doc)
+        doc['Notes'] += _standard_note_addition
+        doc = str(doc).split("\n", 1)[1]  # remove signature
+        axis_nan_policy_wrapper.__doc__ = str(doc)
+
+        sig = inspect.signature(axis_nan_policy_wrapper)
+        parameters = sig.parameters
+        parameter_list = list(parameters.values())
+        if 'axis' not in parameters:
+            parameter_list.append(_axis_parameter)
+        if 'nan_policy' not in parameters:
+            parameter_list.append(_nan_policy_parameter)
+        if 'keepdims' not in parameters:
+            parameter_list.append(_keepdims_parameter)
+        sig = sig.replace(parameters=parameter_list)
+        axis_nan_policy_wrapper.__signature__ = sig
+
+        return axis_nan_policy_wrapper
+    return axis_nan_policy_decorator
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_biasedurn.pxd b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_biasedurn.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..92785f08dbec30a4db286fcb85b42d7221e2228e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_biasedurn.pxd
@@ -0,0 +1,27 @@
+# Declare the class with cdef
+cdef extern from "biasedurn/stocc.h" nogil:
+    cdef cppclass CFishersNCHypergeometric:
+        CFishersNCHypergeometric(int, int, int, double, double) except +
+        int mode()
+        double mean()
+        double variance()
+        double probability(int x)
+        double moments(double * mean, double * var)
+
+    cdef cppclass CWalleniusNCHypergeometric:
+        CWalleniusNCHypergeometric() except +
+        CWalleniusNCHypergeometric(int, int, int, double, double) except +
+        int mode()
+        double mean()
+        double variance()
+        double probability(int x)
+        double moments(double * mean, double * var)
+
+    cdef cppclass StochasticLib3:
+        StochasticLib3(int seed) except +
+        double Random() except +
+        void SetAccuracy(double accur)
+        int FishersNCHyp (int n, int m, int N, double odds) except +
+        int WalleniusNCHyp (int n, int m, int N, double odds) except +
+        double(*next_double)()
+        double(*next_normal)(const double m, const double s)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_binned_statistic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_binned_statistic.py
new file mode 100644
index 0000000000000000000000000000000000000000..c87492ce9e77dc2f11b3138f9294e421621a8292
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_binned_statistic.py
@@ -0,0 +1,795 @@
+import builtins
+from warnings import catch_warnings, simplefilter
+import numpy as np
+from operator import index
+from collections import namedtuple
+
+__all__ = ['binned_statistic',
+           'binned_statistic_2d',
+           'binned_statistic_dd']
+
+
+BinnedStatisticResult = namedtuple('BinnedStatisticResult',
+                                   ('statistic', 'bin_edges', 'binnumber'))
+
+
+def binned_statistic(x, values, statistic='mean',
+                     bins=10, range=None):
+    """
+    Compute a binned statistic for one or more sets of data.
+
+    This is a generalization of a histogram function.  A histogram divides
+    the space into bins, and returns the count of the number of points in
+    each bin.  This function allows the computation of the sum, mean, median,
+    or other statistic of the values (or set of values) within each bin.
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        A sequence of values to be binned.
+    values : (N,) array_like or list of (N,) array_like
+        The data on which the statistic will be computed.  This must be
+        the same shape as `x`, or a set of sequences - each the same shape as
+        `x`.  If `values` is a set of sequences, the statistic will be computed
+        on each independently.
+    statistic : string or callable, optional
+        The statistic to compute (default is 'mean').
+        The following statistics are available:
+
+          * 'mean' : compute the mean of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'std' : compute the standard deviation within each bin. This
+            is implicitly calculated with ddof=0.
+          * 'median' : compute the median of values for points within each
+            bin. Empty bins will be represented by NaN.
+          * 'count' : compute the count of points within each bin.  This is
+            identical to an unweighted histogram.  `values` array is not
+            referenced.
+          * 'sum' : compute the sum of values for points within each bin.
+            This is identical to a weighted histogram.
+          * 'min' : compute the minimum of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'max' : compute the maximum of values for point within each bin.
+            Empty bins will be represented by NaN.
+          * function : a user-defined function which takes a 1D array of
+            values, and outputs a single numerical statistic. This function
+            will be called on the values in each bin.  Empty bins will be
+            represented by function([]), or NaN if this returns an error.
+
+    bins : int or sequence of scalars, optional
+        If `bins` is an int, it defines the number of equal-width bins in the
+        given range (10 by default).  If `bins` is a sequence, it defines the
+        bin edges, including the rightmost edge, allowing for non-uniform bin
+        widths.  Values in `x` that are smaller than lowest bin edge are
+        assigned to bin number 0, values beyond the highest bin are assigned to
+        ``bins[-1]``.  If the bin edges are specified, the number of bins will
+        be, (nx = len(bins)-1).
+    range : (float, float) or [(float, float)], optional
+        The lower and upper range of the bins.  If not provided, range
+        is simply ``(x.min(), x.max())``.  Values outside the range are
+        ignored.
+
+    Returns
+    -------
+    statistic : array
+        The values of the selected statistic in each bin.
+    bin_edges : array of dtype float
+        Return the bin edges ``(length(statistic)+1)``.
+    binnumber: 1-D ndarray of ints
+        Indices of the bins (corresponding to `bin_edges`) in which each value
+        of `x` belongs.  Same length as `values`.  A binnumber of `i` means the
+        corresponding value is between (bin_edges[i-1], bin_edges[i]).
+
+    See Also
+    --------
+    numpy.digitize, numpy.histogram, binned_statistic_2d, binned_statistic_dd
+
+    Notes
+    -----
+    All but the last (righthand-most) bin is half-open.  In other words, if
+    `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1,
+    but excluding 2) and the second ``[2, 3)``.  The last bin, however, is
+    ``[3, 4]``, which *includes* 4.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    First some basic examples:
+
+    Create two evenly spaced bins in the range of the given sample, and sum the
+    corresponding values in each of those bins:
+
+    >>> values = [1.0, 1.0, 2.0, 1.5, 3.0]
+    >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2)
+    BinnedStatisticResult(statistic=array([4. , 4.5]),
+            bin_edges=array([1., 4., 7.]), binnumber=array([1, 1, 1, 2, 2]))
+
+    Multiple arrays of values can also be passed.  The statistic is calculated
+    on each set independently:
+
+    >>> values = [[1.0, 1.0, 2.0, 1.5, 3.0], [2.0, 2.0, 4.0, 3.0, 6.0]]
+    >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2)
+    BinnedStatisticResult(statistic=array([[4. , 4.5],
+           [8. , 9. ]]), bin_edges=array([1., 4., 7.]),
+           binnumber=array([1, 1, 1, 2, 2]))
+
+    >>> stats.binned_statistic([1, 2, 1, 2, 4], np.arange(5), statistic='mean',
+    ...                        bins=3)
+    BinnedStatisticResult(statistic=array([1., 2., 4.]),
+            bin_edges=array([1., 2., 3., 4.]),
+            binnumber=array([1, 2, 1, 2, 3]))
+
+    As a second example, we now generate some random data of sailing boat speed
+    as a function of wind speed, and then determine how fast our boat is for
+    certain wind speeds:
+
+    >>> rng = np.random.default_rng()
+    >>> windspeed = 8 * rng.random(500)
+    >>> boatspeed = .3 * windspeed**.5 + .2 * rng.random(500)
+    >>> bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,
+    ...                 boatspeed, statistic='median', bins=[1,2,3,4,5,6,7])
+    >>> plt.figure()
+    >>> plt.plot(windspeed, boatspeed, 'b.', label='raw data')
+    >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,
+    ...            label='binned statistic of data')
+    >>> plt.legend()
+
+    Now we can use ``binnumber`` to select all datapoints with a windspeed
+    below 1:
+
+    >>> low_boatspeed = boatspeed[binnumber == 0]
+
+    As a final example, we will use ``bin_edges`` and ``binnumber`` to make a
+    plot of a distribution that shows the mean and distribution around that
+    mean per bin, on top of a regular histogram and the probability
+    distribution function:
+
+    >>> x = np.linspace(0, 5, num=500)
+    >>> x_pdf = stats.maxwell.pdf(x)
+    >>> samples = stats.maxwell.rvs(size=10000)
+
+    >>> bin_means, bin_edges, binnumber = stats.binned_statistic(x, x_pdf,
+    ...         statistic='mean', bins=25)
+    >>> bin_width = (bin_edges[1] - bin_edges[0])
+    >>> bin_centers = bin_edges[1:] - bin_width/2
+
+    >>> plt.figure()
+    >>> plt.hist(samples, bins=50, density=True, histtype='stepfilled',
+    ...          alpha=0.2, label='histogram of data')
+    >>> plt.plot(x, x_pdf, 'r-', label='analytical pdf')
+    >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=2,
+    ...            label='binned statistic of data')
+    >>> plt.plot((binnumber - 0.5) * bin_width, x_pdf, 'g.', alpha=0.5)
+    >>> plt.legend(fontsize=10)
+    >>> plt.show()
+
+    """
+    try:
+        N = len(bins)
+    except TypeError:
+        N = 1
+
+    if N != 1:
+        bins = [np.asarray(bins, float)]
+
+    if range is not None:
+        if len(range) == 2:
+            range = [range]
+
+    medians, edges, binnumbers = binned_statistic_dd(
+        [x], values, statistic, bins, range)
+
+    return BinnedStatisticResult(medians, edges[0], binnumbers)
+
+
+BinnedStatistic2dResult = namedtuple('BinnedStatistic2dResult',
+                                     ('statistic', 'x_edge', 'y_edge',
+                                      'binnumber'))
+
+
+def binned_statistic_2d(x, y, values, statistic='mean',
+                        bins=10, range=None, expand_binnumbers=False):
+    """
+    Compute a bidimensional binned statistic for one or more sets of data.
+
+    This is a generalization of a histogram2d function.  A histogram divides
+    the space into bins, and returns the count of the number of points in
+    each bin.  This function allows the computation of the sum, mean, median,
+    or other statistic of the values (or set of values) within each bin.
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        A sequence of values to be binned along the first dimension.
+    y : (N,) array_like
+        A sequence of values to be binned along the second dimension.
+    values : (N,) array_like or list of (N,) array_like
+        The data on which the statistic will be computed.  This must be
+        the same shape as `x`, or a list of sequences - each with the same
+        shape as `x`.  If `values` is such a list, the statistic will be
+        computed on each independently.
+    statistic : string or callable, optional
+        The statistic to compute (default is 'mean').
+        The following statistics are available:
+
+          * 'mean' : compute the mean of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'std' : compute the standard deviation within each bin. This
+            is implicitly calculated with ddof=0.
+          * 'median' : compute the median of values for points within each
+            bin. Empty bins will be represented by NaN.
+          * 'count' : compute the count of points within each bin.  This is
+            identical to an unweighted histogram.  `values` array is not
+            referenced.
+          * 'sum' : compute the sum of values for points within each bin.
+            This is identical to a weighted histogram.
+          * 'min' : compute the minimum of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'max' : compute the maximum of values for point within each bin.
+            Empty bins will be represented by NaN.
+          * function : a user-defined function which takes a 1D array of
+            values, and outputs a single numerical statistic. This function
+            will be called on the values in each bin.  Empty bins will be
+            represented by function([]), or NaN if this returns an error.
+
+    bins : int or [int, int] or array_like or [array, array], optional
+        The bin specification:
+
+          * the number of bins for the two dimensions (nx = ny = bins),
+          * the number of bins in each dimension (nx, ny = bins),
+          * the bin edges for the two dimensions (x_edge = y_edge = bins),
+          * the bin edges in each dimension (x_edge, y_edge = bins).
+
+        If the bin edges are specified, the number of bins will be,
+        (nx = len(x_edge)-1, ny = len(y_edge)-1).
+
+    range : (2,2) array_like, optional
+        The leftmost and rightmost edges of the bins along each dimension
+        (if not specified explicitly in the `bins` parameters):
+        [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be
+        considered outliers and not tallied in the histogram.
+    expand_binnumbers : bool, optional
+        'False' (default): the returned `binnumber` is a shape (N,) array of
+        linearized bin indices.
+        'True': the returned `binnumber` is 'unraveled' into a shape (2,N)
+        ndarray, where each row gives the bin numbers in the corresponding
+        dimension.
+        See the `binnumber` returned value, and the `Examples` section.
+
+        .. versionadded:: 0.17.0
+
+    Returns
+    -------
+    statistic : (nx, ny) ndarray
+        The values of the selected statistic in each two-dimensional bin.
+    x_edge : (nx + 1) ndarray
+        The bin edges along the first dimension.
+    y_edge : (ny + 1) ndarray
+        The bin edges along the second dimension.
+    binnumber : (N,) array of ints or (2,N) ndarray of ints
+        This assigns to each element of `sample` an integer that represents the
+        bin in which this observation falls.  The representation depends on the
+        `expand_binnumbers` argument.  See `Notes` for details.
+
+
+    See Also
+    --------
+    numpy.digitize, numpy.histogram2d, binned_statistic, binned_statistic_dd
+
+    Notes
+    -----
+    Binedges:
+    All but the last (righthand-most) bin is half-open.  In other words, if
+    `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1,
+    but excluding 2) and the second ``[2, 3)``.  The last bin, however, is
+    ``[3, 4]``, which *includes* 4.
+
+    `binnumber`:
+    This returned argument assigns to each element of `sample` an integer that
+    represents the bin in which it belongs.  The representation depends on the
+    `expand_binnumbers` argument. If 'False' (default): The returned
+    `binnumber` is a shape (N,) array of linearized indices mapping each
+    element of `sample` to its corresponding bin (using row-major ordering).
+    Note that the returned linearized bin indices are used for an array with
+    extra bins on the outer binedges to capture values outside of the defined
+    bin bounds.
+    If 'True': The returned `binnumber` is a shape (2,N) ndarray where
+    each row indicates bin placements for each dimension respectively.  In each
+    dimension, a binnumber of `i` means the corresponding value is between
+    (D_edge[i-1], D_edge[i]), where 'D' is either 'x' or 'y'.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> from scipy import stats
+
+    Calculate the counts with explicit bin-edges:
+
+    >>> x = [0.1, 0.1, 0.1, 0.6]
+    >>> y = [2.1, 2.6, 2.1, 2.1]
+    >>> binx = [0.0, 0.5, 1.0]
+    >>> biny = [2.0, 2.5, 3.0]
+    >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx, biny])
+    >>> ret.statistic
+    array([[2., 1.],
+           [1., 0.]])
+
+    The bin in which each sample is placed is given by the `binnumber`
+    returned parameter.  By default, these are the linearized bin indices:
+
+    >>> ret.binnumber
+    array([5, 6, 5, 9])
+
+    The bin indices can also be expanded into separate entries for each
+    dimension using the `expand_binnumbers` parameter:
+
+    >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx, biny],
+    ...                                 expand_binnumbers=True)
+    >>> ret.binnumber
+    array([[1, 1, 1, 2],
+           [1, 2, 1, 1]])
+
+    Which shows that the first three elements belong in the xbin 1, and the
+    fourth into xbin 2; and so on for y.
+
+    """
+
+    # This code is based on np.histogram2d
+    try:
+        N = len(bins)
+    except TypeError:
+        N = 1
+
+    if N != 1 and N != 2:
+        xedges = yedges = np.asarray(bins, float)
+        bins = [xedges, yedges]
+
+    medians, edges, binnumbers = binned_statistic_dd(
+        [x, y], values, statistic, bins, range,
+        expand_binnumbers=expand_binnumbers)
+
+    return BinnedStatistic2dResult(medians, edges[0], edges[1], binnumbers)
+
+
+BinnedStatisticddResult = namedtuple('BinnedStatisticddResult',
+                                     ('statistic', 'bin_edges',
+                                      'binnumber'))
+
+
+def _bincount(x, weights):
+    if np.iscomplexobj(weights):
+        a = np.bincount(x, np.real(weights))
+        b = np.bincount(x, np.imag(weights))
+        z = a + b*1j
+
+    else:
+        z = np.bincount(x, weights)
+    return z
+
+
+def binned_statistic_dd(sample, values, statistic='mean',
+                        bins=10, range=None, expand_binnumbers=False,
+                        binned_statistic_result=None):
+    """
+    Compute a multidimensional binned statistic for a set of data.
+
+    This is a generalization of a histogramdd function.  A histogram divides
+    the space into bins, and returns the count of the number of points in
+    each bin.  This function allows the computation of the sum, mean, median,
+    or other statistic of the values within each bin.
+
+    Parameters
+    ----------
+    sample : array_like
+        Data to histogram passed as a sequence of N arrays of length D, or
+        as an (N,D) array.
+    values : (N,) array_like or list of (N,) array_like
+        The data on which the statistic will be computed.  This must be
+        the same shape as `sample`, or a list of sequences - each with the
+        same shape as `sample`.  If `values` is such a list, the statistic
+        will be computed on each independently.
+    statistic : string or callable, optional
+        The statistic to compute (default is 'mean').
+        The following statistics are available:
+
+          * 'mean' : compute the mean of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'median' : compute the median of values for points within each
+            bin. Empty bins will be represented by NaN.
+          * 'count' : compute the count of points within each bin.  This is
+            identical to an unweighted histogram.  `values` array is not
+            referenced.
+          * 'sum' : compute the sum of values for points within each bin.
+            This is identical to a weighted histogram.
+          * 'std' : compute the standard deviation within each bin. This
+            is implicitly calculated with ddof=0. If the number of values
+            within a given bin is 0 or 1, the computed standard deviation value
+            will be 0 for the bin.
+          * 'min' : compute the minimum of values for points within each bin.
+            Empty bins will be represented by NaN.
+          * 'max' : compute the maximum of values for point within each bin.
+            Empty bins will be represented by NaN.
+          * function : a user-defined function which takes a 1D array of
+            values, and outputs a single numerical statistic. This function
+            will be called on the values in each bin.  Empty bins will be
+            represented by function([]), or NaN if this returns an error.
+
+    bins : sequence or positive int, optional
+        The bin specification must be in one of the following forms:
+
+          * A sequence of arrays describing the bin edges along each dimension.
+          * The number of bins for each dimension (nx, ny, ... = bins).
+          * The number of bins for all dimensions (nx = ny = ... = bins).
+    range : sequence, optional
+        A sequence of lower and upper bin edges to be used if the edges are
+        not given explicitly in `bins`. Defaults to the minimum and maximum
+        values along each dimension.
+    expand_binnumbers : bool, optional
+        'False' (default): the returned `binnumber` is a shape (N,) array of
+        linearized bin indices.
+        'True': the returned `binnumber` is 'unraveled' into a shape (D,N)
+        ndarray, where each row gives the bin numbers in the corresponding
+        dimension.
+        See the `binnumber` returned value, and the `Examples` section of
+        `binned_statistic_2d`.
+    binned_statistic_result : binnedStatisticddResult
+        Result of a previous call to the function in order to reuse bin edges
+        and bin numbers with new values and/or a different statistic.
+        To reuse bin numbers, `expand_binnumbers` must have been set to False
+        (the default)
+
+        .. versionadded:: 0.17.0
+
+    Returns
+    -------
+    statistic : ndarray, shape(nx1, nx2, nx3,...)
+        The values of the selected statistic in each two-dimensional bin.
+    bin_edges : list of ndarrays
+        A list of D arrays describing the (nxi + 1) bin edges for each
+        dimension.
+    binnumber : (N,) array of ints or (D,N) ndarray of ints
+        This assigns to each element of `sample` an integer that represents the
+        bin in which this observation falls.  The representation depends on the
+        `expand_binnumbers` argument.  See `Notes` for details.
+
+
+    See Also
+    --------
+    numpy.digitize, numpy.histogramdd, binned_statistic, binned_statistic_2d
+
+    Notes
+    -----
+    Binedges:
+    All but the last (righthand-most) bin is half-open in each dimension.  In
+    other words, if `bins` is ``[1, 2, 3, 4]``, then the first bin is
+    ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``.  The
+    last bin, however, is ``[3, 4]``, which *includes* 4.
+
+    `binnumber`:
+    This returned argument assigns to each element of `sample` an integer that
+    represents the bin in which it belongs.  The representation depends on the
+    `expand_binnumbers` argument. If 'False' (default): The returned
+    `binnumber` is a shape (N,) array of linearized indices mapping each
+    element of `sample` to its corresponding bin (using row-major ordering).
+    If 'True': The returned `binnumber` is a shape (D,N) ndarray where
+    each row indicates bin placements for each dimension respectively.  In each
+    dimension, a binnumber of `i` means the corresponding value is between
+    (bin_edges[D][i-1], bin_edges[D][i]), for each dimension 'D'.
+
+    .. versionadded:: 0.11.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.mplot3d import Axes3D
+
+    Take an array of 600 (x, y) coordinates as an example.
+    `binned_statistic_dd` can handle arrays of higher dimension `D`. But a plot
+    of dimension `D+1` is required.
+
+    >>> mu = np.array([0., 1.])
+    >>> sigma = np.array([[1., -0.5],[-0.5, 1.5]])
+    >>> multinormal = stats.multivariate_normal(mu, sigma)
+    >>> data = multinormal.rvs(size=600, random_state=235412)
+    >>> data.shape
+    (600, 2)
+
+    Create bins and count how many arrays fall in each bin:
+
+    >>> N = 60
+    >>> x = np.linspace(-3, 3, N)
+    >>> y = np.linspace(-3, 4, N)
+    >>> ret = stats.binned_statistic_dd(data, np.arange(600), bins=[x, y],
+    ...                                 statistic='count')
+    >>> bincounts = ret.statistic
+
+    Set the volume and the location of bars:
+
+    >>> dx = x[1] - x[0]
+    >>> dy = y[1] - y[0]
+    >>> x, y = np.meshgrid(x[:-1]+dx/2, y[:-1]+dy/2)
+    >>> z = 0
+
+    >>> bincounts = bincounts.ravel()
+    >>> x = x.ravel()
+    >>> y = y.ravel()
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111, projection='3d')
+    >>> with np.errstate(divide='ignore'):   # silence random axes3d warning
+    ...     ax.bar3d(x, y, z, dx, dy, bincounts)
+
+    Reuse bin numbers and bin edges with new values:
+
+    >>> ret2 = stats.binned_statistic_dd(data, -np.arange(600),
+    ...                                  binned_statistic_result=ret,
+    ...                                  statistic='mean')
+    """
+    known_stats = ['mean', 'median', 'count', 'sum', 'std', 'min', 'max']
+    if not callable(statistic) and statistic not in known_stats:
+        raise ValueError(f'invalid statistic {statistic!r}')
+
+    try:
+        bins = index(bins)
+    except TypeError:
+        # bins is not an integer
+        pass
+    # If bins was an integer-like object, now it is an actual Python int.
+
+    # NOTE: for _bin_edges(), see e.g. gh-11365
+    if isinstance(bins, int) and not np.isfinite(sample).all():
+        raise ValueError(f'{sample!r} contains non-finite values.')
+
+    # `Ndim` is the number of dimensions (e.g. `2` for `binned_statistic_2d`)
+    # `Dlen` is the length of elements along each dimension.
+    # This code is based on np.histogramdd
+    try:
+        # `sample` is an ND-array.
+        Dlen, Ndim = sample.shape
+    except (AttributeError, ValueError):
+        # `sample` is a sequence of 1D arrays.
+        sample = np.atleast_2d(sample).T
+        Dlen, Ndim = sample.shape
+
+    # Store initial shape of `values` to preserve it in the output
+    values = np.asarray(values)
+    input_shape = list(values.shape)
+    # Make sure that `values` is 2D to iterate over rows
+    values = np.atleast_2d(values)
+    Vdim, Vlen = values.shape
+
+    # Make sure `values` match `sample`
+    if statistic != 'count' and Vlen != Dlen:
+        raise AttributeError('The number of `values` elements must match the '
+                             'length of each `sample` dimension.')
+
+    try:
+        M = len(bins)
+        if M != Ndim:
+            raise AttributeError('The dimension of bins must be equal '
+                                 'to the dimension of the sample x.')
+    except TypeError:
+        bins = Ndim * [bins]
+
+    if binned_statistic_result is None:
+        nbin, edges, dedges = _bin_edges(sample, bins, range)
+        binnumbers = _bin_numbers(sample, nbin, edges, dedges)
+    else:
+        edges = binned_statistic_result.bin_edges
+        nbin = np.array([len(edges[i]) + 1 for i in builtins.range(Ndim)])
+        # +1 for outlier bins
+        dedges = [np.diff(edges[i]) for i in builtins.range(Ndim)]
+        binnumbers = binned_statistic_result.binnumber
+
+    # Avoid overflow with double precision. Complex `values` -> `complex128`.
+    result_type = np.result_type(values, np.float64)
+    result = np.empty([Vdim, nbin.prod()], dtype=result_type)
+
+    if statistic in {'mean', np.mean}:
+        result.fill(np.nan)
+        flatcount = _bincount(binnumbers, None)
+        a = flatcount.nonzero()
+        for vv in builtins.range(Vdim):
+            flatsum = _bincount(binnumbers, values[vv])
+            result[vv, a] = flatsum[a] / flatcount[a]
+    elif statistic in {'std', np.std}:
+        result.fill(np.nan)
+        flatcount = _bincount(binnumbers, None)
+        a = flatcount.nonzero()
+        for vv in builtins.range(Vdim):
+            flatsum = _bincount(binnumbers, values[vv])
+            delta = values[vv] - flatsum[binnumbers] / flatcount[binnumbers]
+            std = np.sqrt(
+                _bincount(binnumbers, delta*np.conj(delta))[a] / flatcount[a]
+            )
+            result[vv, a] = std
+        result = np.real(result)
+    elif statistic == 'count':
+        result = np.empty([Vdim, nbin.prod()], dtype=np.float64)
+        result.fill(0)
+        flatcount = _bincount(binnumbers, None)
+        a = np.arange(len(flatcount))
+        result[:, a] = flatcount[np.newaxis, :]
+    elif statistic in {'sum', np.sum}:
+        result.fill(0)
+        for vv in builtins.range(Vdim):
+            flatsum = _bincount(binnumbers, values[vv])
+            a = np.arange(len(flatsum))
+            result[vv, a] = flatsum
+    elif statistic in {'median', np.median}:
+        result.fill(np.nan)
+        for vv in builtins.range(Vdim):
+            i = np.lexsort((values[vv], binnumbers))
+            _, j, counts = np.unique(binnumbers[i],
+                                     return_index=True, return_counts=True)
+            mid = j + (counts - 1) / 2
+            mid_a = values[vv, i][np.floor(mid).astype(int)]
+            mid_b = values[vv, i][np.ceil(mid).astype(int)]
+            medians = (mid_a + mid_b) / 2
+            result[vv, binnumbers[i][j]] = medians
+    elif statistic in {'min', np.min}:
+        result.fill(np.nan)
+        for vv in builtins.range(Vdim):
+            i = np.argsort(values[vv])[::-1]  # Reversed so the min is last
+            result[vv, binnumbers[i]] = values[vv, i]
+    elif statistic in {'max', np.max}:
+        result.fill(np.nan)
+        for vv in builtins.range(Vdim):
+            i = np.argsort(values[vv])
+            result[vv, binnumbers[i]] = values[vv, i]
+    elif callable(statistic):
+        with np.errstate(invalid='ignore'), catch_warnings():
+            simplefilter("ignore", RuntimeWarning)
+            try:
+                null = statistic([])
+            except Exception:
+                null = np.nan
+        if np.iscomplexobj(null):
+            result = result.astype(np.complex128)
+        result.fill(null)
+        try:
+            _calc_binned_statistic(
+                Vdim, binnumbers, result, values, statistic
+            )
+        except ValueError:
+            result = result.astype(np.complex128)
+            _calc_binned_statistic(
+                Vdim, binnumbers, result, values, statistic
+            )
+
+    # Shape into a proper matrix
+    result = result.reshape(np.append(Vdim, nbin))
+
+    # Remove outliers (indices 0 and -1 for each bin-dimension).
+    core = tuple([slice(None)] + Ndim * [slice(1, -1)])
+    result = result[core]
+
+    # Unravel binnumbers into an ndarray, each row the bins for each dimension
+    if expand_binnumbers and Ndim > 1:
+        binnumbers = np.asarray(np.unravel_index(binnumbers, nbin))
+
+    if np.any(result.shape[1:] != nbin - 2):
+        raise RuntimeError('Internal Shape Error')
+
+    # Reshape to have output (`result`) match input (`values`) shape
+    result = result.reshape(input_shape[:-1] + list(nbin-2))
+
+    return BinnedStatisticddResult(result, edges, binnumbers)
+
+
+def _calc_binned_statistic(Vdim, bin_numbers, result, values, stat_func):
+    unique_bin_numbers = np.unique(bin_numbers)
+    for vv in builtins.range(Vdim):
+        bin_map = _create_binned_data(bin_numbers, unique_bin_numbers,
+                                      values, vv)
+        for i in unique_bin_numbers:
+            stat = stat_func(np.array(bin_map[i]))
+            if np.iscomplexobj(stat) and not np.iscomplexobj(result):
+                raise ValueError("The statistic function returns complex ")
+            result[vv, i] = stat
+
+
+def _create_binned_data(bin_numbers, unique_bin_numbers, values, vv):
+    """ Create hashmap of bin ids to values in bins
+    key: bin number
+    value: list of binned data
+    """
+    bin_map = dict()
+    for i in unique_bin_numbers:
+        bin_map[i] = []
+    for i in builtins.range(len(bin_numbers)):
+        bin_map[bin_numbers[i]].append(values[vv, i])
+    return bin_map
+
+
+def _bin_edges(sample, bins=None, range=None):
+    """ Create edge arrays
+    """
+    Dlen, Ndim = sample.shape
+
+    nbin = np.empty(Ndim, int)    # Number of bins in each dimension
+    edges = Ndim * [None]         # Bin edges for each dim (will be 2D array)
+    dedges = Ndim * [None]        # Spacing between edges (will be 2D array)
+
+    # Select range for each dimension
+    # Used only if number of bins is given.
+    if range is None:
+        smin = np.atleast_1d(np.array(sample.min(axis=0), float))
+        smax = np.atleast_1d(np.array(sample.max(axis=0), float))
+    else:
+        if len(range) != Ndim:
+            raise ValueError(
+                f"range given for {len(range)} dimensions; {Ndim} required")
+        smin = np.empty(Ndim)
+        smax = np.empty(Ndim)
+        for i in builtins.range(Ndim):
+            if range[i][1] < range[i][0]:
+                raise ValueError(
+                    f"In {f'dimension {i + 1} of ' if Ndim > 1 else ''}range,"
+                    " start must be <= stop")
+            smin[i], smax[i] = range[i]
+
+    # Make sure the bins have a finite width.
+    for i in builtins.range(len(smin)):
+        if smin[i] == smax[i]:
+            smin[i] = smin[i] - .5
+            smax[i] = smax[i] + .5
+
+    # Preserve sample floating point precision in bin edges
+    edges_dtype = (sample.dtype if np.issubdtype(sample.dtype, np.floating)
+                   else float)
+
+    # Create edge arrays
+    for i in builtins.range(Ndim):
+        if np.isscalar(bins[i]):
+            nbin[i] = bins[i] + 2  # +2 for outlier bins
+            edges[i] = np.linspace(smin[i], smax[i], nbin[i] - 1,
+                                   dtype=edges_dtype)
+        else:
+            edges[i] = np.asarray(bins[i], edges_dtype)
+            nbin[i] = len(edges[i]) + 1  # +1 for outlier bins
+        dedges[i] = np.diff(edges[i])
+
+    nbin = np.asarray(nbin)
+
+    return nbin, edges, dedges
+
+
+def _bin_numbers(sample, nbin, edges, dedges):
+    """Compute the bin number each sample falls into, in each dimension
+    """
+    Dlen, Ndim = sample.shape
+
+    sampBin = [
+        np.digitize(sample[:, i], edges[i])
+        for i in range(Ndim)
+    ]
+
+    # Using `digitize`, values that fall on an edge are put in the right bin.
+    # For the rightmost bin, we want values equal to the right
+    # edge to be counted in the last bin, and not as an outlier.
+    for i in range(Ndim):
+        # Find the rounding precision
+        dedges_min = dedges[i].min()
+        if dedges_min == 0:
+            raise ValueError('The smallest edge difference is numerically 0.')
+        decimal = int(-np.log10(dedges_min)) + 6
+        # Find which points are on the rightmost edge.
+        on_edge = np.where((sample[:, i] >= edges[i][-1]) &
+                           (np.around(sample[:, i], decimal) ==
+                            np.around(edges[i][-1], decimal)))[0]
+        # Shift these points one bin to the left.
+        sampBin[i][on_edge] -= 1
+
+    # Compute the sample indices in the flattened statistic matrix.
+    binnumbers = np.ravel_multi_index(sampBin, nbin)
+
+    return binnumbers
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_binomtest.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_binomtest.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdf21117383374e730ab052fcbb0b5b7fca029c1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_binomtest.py
@@ -0,0 +1,375 @@
+from math import sqrt
+import numpy as np
+from scipy._lib._util import _validate_int
+from scipy.optimize import brentq
+from scipy.special import ndtri
+from ._discrete_distns import binom
+from ._common import ConfidenceInterval
+
+
+class BinomTestResult:
+    """
+    Result of `scipy.stats.binomtest`.
+
+    Attributes
+    ----------
+    k : int
+        The number of successes (copied from `binomtest` input).
+    n : int
+        The number of trials (copied from `binomtest` input).
+    alternative : str
+        Indicates the alternative hypothesis specified in the input
+        to `binomtest`.  It will be one of ``'two-sided'``, ``'greater'``,
+        or ``'less'``.
+    statistic: float
+        The estimate of the proportion of successes.
+    pvalue : float
+        The p-value of the hypothesis test.
+
+    """
+    def __init__(self, k, n, alternative, statistic, pvalue):
+        self.k = k
+        self.n = n
+        self.alternative = alternative
+        self.statistic = statistic
+        self.pvalue = pvalue
+
+        # add alias for backward compatibility
+        self.proportion_estimate = statistic
+
+    def __repr__(self):
+        s = ("BinomTestResult("
+             f"k={self.k}, "
+             f"n={self.n}, "
+             f"alternative={self.alternative!r}, "
+             f"statistic={self.statistic}, "
+             f"pvalue={self.pvalue})")
+        return s
+
+    def proportion_ci(self, confidence_level=0.95, method='exact'):
+        """
+        Compute the confidence interval for ``statistic``.
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            Confidence level for the computed confidence interval
+            of the estimated proportion. Default is 0.95.
+        method : {'exact', 'wilson', 'wilsoncc'}, optional
+            Selects the method used to compute the confidence interval
+            for the estimate of the proportion:
+
+            'exact' :
+                Use the Clopper-Pearson exact method [1]_.
+            'wilson' :
+                Wilson's method, without continuity correction ([2]_, [3]_).
+            'wilsoncc' :
+                Wilson's method, with continuity correction ([2]_, [3]_).
+
+            Default is ``'exact'``.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` object
+            The object has attributes ``low`` and ``high`` that hold the
+            lower and upper bounds of the confidence interval.
+
+        References
+        ----------
+        .. [1] C. J. Clopper and E. S. Pearson, The use of confidence or
+               fiducial limits illustrated in the case of the binomial,
+               Biometrika, Vol. 26, No. 4, pp 404-413 (Dec. 1934).
+        .. [2] E. B. Wilson, Probable inference, the law of succession, and
+               statistical inference, J. Amer. Stat. Assoc., 22, pp 209-212
+               (1927).
+        .. [3] Robert G. Newcombe, Two-sided confidence intervals for the
+               single proportion: comparison of seven methods, Statistics
+               in Medicine, 17, pp 857-872 (1998).
+
+        Examples
+        --------
+        >>> from scipy.stats import binomtest
+        >>> result = binomtest(k=7, n=50, p=0.1)
+        >>> result.statistic
+        0.14
+        >>> result.proportion_ci()
+        ConfidenceInterval(low=0.05819170033997342, high=0.26739600249700846)
+        """
+        if method not in ('exact', 'wilson', 'wilsoncc'):
+            raise ValueError(f"method ('{method}') must be one of 'exact', "
+                             "'wilson' or 'wilsoncc'.")
+        if not (0 <= confidence_level <= 1):
+            raise ValueError(f'confidence_level ({confidence_level}) must be in '
+                             'the interval [0, 1].')
+        if method == 'exact':
+            low, high = _binom_exact_conf_int(self.k, self.n,
+                                              confidence_level,
+                                              self.alternative)
+        else:
+            # method is 'wilson' or 'wilsoncc'
+            low, high = _binom_wilson_conf_int(self.k, self.n,
+                                               confidence_level,
+                                               self.alternative,
+                                               correction=method == 'wilsoncc')
+        return ConfidenceInterval(low=low, high=high)
+
+
+def _findp(func):
+    try:
+        p = brentq(func, 0, 1)
+    except RuntimeError:
+        raise RuntimeError('numerical solver failed to converge when '
+                           'computing the confidence limits') from None
+    except ValueError as exc:
+        raise ValueError('brentq raised a ValueError; report this to the '
+                         'SciPy developers') from exc
+    return p
+
+
+def _binom_exact_conf_int(k, n, confidence_level, alternative):
+    """
+    Compute the estimate and confidence interval for the binomial test.
+
+    Returns proportion, prop_low, prop_high
+    """
+    if alternative == 'two-sided':
+        alpha = (1 - confidence_level) / 2
+        if k == 0:
+            plow = 0.0
+        else:
+            plow = _findp(lambda p: binom.sf(k-1, n, p) - alpha)
+        if k == n:
+            phigh = 1.0
+        else:
+            phigh = _findp(lambda p: binom.cdf(k, n, p) - alpha)
+    elif alternative == 'less':
+        alpha = 1 - confidence_level
+        plow = 0.0
+        if k == n:
+            phigh = 1.0
+        else:
+            phigh = _findp(lambda p: binom.cdf(k, n, p) - alpha)
+    elif alternative == 'greater':
+        alpha = 1 - confidence_level
+        if k == 0:
+            plow = 0.0
+        else:
+            plow = _findp(lambda p: binom.sf(k-1, n, p) - alpha)
+        phigh = 1.0
+    return plow, phigh
+
+
+def _binom_wilson_conf_int(k, n, confidence_level, alternative, correction):
+    # This function assumes that the arguments have already been validated.
+    # In particular, `alternative` must be one of 'two-sided', 'less' or
+    # 'greater'.
+    p = k / n
+    if alternative == 'two-sided':
+        z = ndtri(0.5 + 0.5*confidence_level)
+    else:
+        z = ndtri(confidence_level)
+
+    # For reference, the formulas implemented here are from
+    # Newcombe (1998) (ref. [3] in the proportion_ci docstring).
+    denom = 2*(n + z**2)
+    center = (2*n*p + z**2)/denom
+    q = 1 - p
+    if correction:
+        if alternative == 'less' or k == 0:
+            lo = 0.0
+        else:
+            dlo = (1 + z*sqrt(z**2 - 2 - 1/n + 4*p*(n*q + 1))) / denom
+            lo = center - dlo
+        if alternative == 'greater' or k == n:
+            hi = 1.0
+        else:
+            dhi = (1 + z*sqrt(z**2 + 2 - 1/n + 4*p*(n*q - 1))) / denom
+            hi = center + dhi
+    else:
+        delta = z/denom * sqrt(4*n*p*q + z**2)
+        if alternative == 'less' or k == 0:
+            lo = 0.0
+        else:
+            lo = center - delta
+        if alternative == 'greater' or k == n:
+            hi = 1.0
+        else:
+            hi = center + delta
+
+    return lo, hi
+
+
+def binomtest(k, n, p=0.5, alternative='two-sided'):
+    """
+    Perform a test that the probability of success is p.
+
+    The binomial test [1]_ is a test of the null hypothesis that the
+    probability of success in a Bernoulli experiment is `p`.
+
+    Details of the test can be found in many texts on statistics, such
+    as section 24.5 of [2]_.
+
+    Parameters
+    ----------
+    k : int
+        The number of successes.
+    n : int
+        The number of trials.
+    p : float, optional
+        The hypothesized probability of success, i.e. the expected
+        proportion of successes.  The value must be in the interval
+        ``0 <= p <= 1``. The default value is ``p = 0.5``.
+    alternative : {'two-sided', 'greater', 'less'}, optional
+        Indicates the alternative hypothesis. The default value is
+        'two-sided'.
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.BinomTestResult` instance
+        The return value is an object with the following attributes:
+
+        k : int
+            The number of successes (copied from `binomtest` input).
+        n : int
+            The number of trials (copied from `binomtest` input).
+        alternative : str
+            Indicates the alternative hypothesis specified in the input
+            to `binomtest`.  It will be one of ``'two-sided'``, ``'greater'``,
+            or ``'less'``.
+        statistic : float
+            The estimate of the proportion of successes.
+        pvalue : float
+            The p-value of the hypothesis test.
+
+        The object has the following methods:
+
+        proportion_ci(confidence_level=0.95, method='exact') :
+            Compute the confidence interval for ``statistic``.
+
+    Notes
+    -----
+    .. versionadded:: 1.7.0
+
+    References
+    ----------
+    .. [1] Binomial test, https://en.wikipedia.org/wiki/Binomial_test
+    .. [2] Jerrold H. Zar, Biostatistical Analysis (fifth edition),
+           Prentice Hall, Upper Saddle River, New Jersey USA (2010)
+
+    Examples
+    --------
+    >>> from scipy.stats import binomtest
+
+    A car manufacturer claims that no more than 10% of their cars are unsafe.
+    15 cars are inspected for safety, 3 were found to be unsafe. Test the
+    manufacturer's claim:
+
+    >>> result = binomtest(3, n=15, p=0.1, alternative='greater')
+    >>> result.pvalue
+    0.18406106910639114
+
+    The null hypothesis cannot be rejected at the 5% level of significance
+    because the returned p-value is greater than the critical value of 5%.
+
+    The test statistic is equal to the estimated proportion, which is simply
+    ``3/15``:
+
+    >>> result.statistic
+    0.2
+
+    We can use the `proportion_ci()` method of the result to compute the
+    confidence interval of the estimate:
+
+    >>> result.proportion_ci(confidence_level=0.95)
+    ConfidenceInterval(low=0.05684686759024681, high=1.0)
+
+    """
+    k = _validate_int(k, 'k', minimum=0)
+    n = _validate_int(n, 'n', minimum=1)
+    if k > n:
+        raise ValueError(f'k ({k}) must not be greater than n ({n}).')
+
+    if not (0 <= p <= 1):
+        raise ValueError(f"p ({p}) must be in range [0,1]")
+
+    if alternative not in ('two-sided', 'less', 'greater'):
+        raise ValueError(f"alternative ('{alternative}') not recognized; \n"
+                         "must be 'two-sided', 'less' or 'greater'")
+    if alternative == 'less':
+        pval = binom.cdf(k, n, p)
+    elif alternative == 'greater':
+        pval = binom.sf(k-1, n, p)
+    else:
+        # alternative is 'two-sided'
+        d = binom.pmf(k, n, p)
+        rerr = 1 + 1e-7
+        if k == p * n:
+            # special case as shortcut, would also be handled by `else` below
+            pval = 1.
+        elif k < p * n:
+            ix = _binary_search_for_binom_tst(lambda x1: -binom.pmf(x1, n, p),
+                                              -d*rerr, np.ceil(p * n), n)
+            # y is the number of terms between mode and n that are <= d*rerr.
+            # ix gave us the first term where a(ix) <= d*rerr < a(ix-1)
+            # if the first equality doesn't hold, y=n-ix. Otherwise, we
+            # need to include ix as well as the equality holds. Note that
+            # the equality will hold in very very rare situations due to rerr.
+            y = n - ix + int(d*rerr == binom.pmf(ix, n, p))
+            pval = binom.cdf(k, n, p) + binom.sf(n - y, n, p)
+        else:
+            ix = _binary_search_for_binom_tst(lambda x1: binom.pmf(x1, n, p),
+                                              d*rerr, 0, np.floor(p * n))
+            # y is the number of terms between 0 and mode that are <= d*rerr.
+            # we need to add a 1 to account for the 0 index.
+            # For comparing this with old behavior, see
+            # tst_binary_srch_for_binom_tst method in test_morestats.
+            y = ix + 1
+            pval = binom.cdf(y-1, n, p) + binom.sf(k-1, n, p)
+
+        pval = min(1.0, pval)
+
+    result = BinomTestResult(k=k, n=n, alternative=alternative,
+                             statistic=k/n, pvalue=pval)
+    return result
+
+
+def _binary_search_for_binom_tst(a, d, lo, hi):
+    """
+    Conducts an implicit binary search on a function specified by `a`.
+
+    Meant to be used on the binomial PMF for the case of two-sided tests
+    to obtain the value on the other side of the mode where the tail
+    probability should be computed. The values on either side of
+    the mode are always in order, meaning binary search is applicable.
+
+    Parameters
+    ----------
+    a : callable
+      The function over which to perform binary search. Its values
+      for inputs lo and hi should be in ascending order.
+    d : float
+      The value to search.
+    lo : int
+      The lower end of range to search.
+    hi : int
+      The higher end of the range to search.
+
+    Returns
+    -------
+    int
+      The index, i between lo and hi
+      such that a(i)<=d d:
+            hi = mid-1
+        else:
+            return mid
+    if a(lo) <= d:
+        return lo
+    else:
+        return lo-1
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_bws_test.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_bws_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..6496ecfba798dc7ad719f784a57896e296590675
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_bws_test.py
@@ -0,0 +1,177 @@
+import numpy as np
+from functools import partial
+from scipy import stats
+
+
+def _bws_input_validation(x, y, alternative, method):
+    ''' Input validation and standardization for bws test'''
+    x, y = np.atleast_1d(x, y)
+    if x.ndim > 1 or y.ndim > 1:
+        raise ValueError('`x` and `y` must be exactly one-dimensional.')
+    if np.isnan(x).any() or np.isnan(y).any():
+        raise ValueError('`x` and `y` must not contain NaNs.')
+    if np.size(x) == 0 or np.size(y) == 0:
+        raise ValueError('`x` and `y` must be of nonzero size.')
+
+    z = stats.rankdata(np.concatenate((x, y)))
+    x, y = z[:len(x)], z[len(x):]
+
+    alternatives = {'two-sided', 'less', 'greater'}
+    alternative = alternative.lower()
+    if alternative not in alternatives:
+        raise ValueError(f'`alternative` must be one of {alternatives}.')
+
+    method = stats.PermutationMethod() if method is None else method
+    if not isinstance(method, stats.PermutationMethod):
+        raise ValueError('`method` must be an instance of '
+                         '`scipy.stats.PermutationMethod`')
+
+    return x, y, alternative, method
+
+
+def _bws_statistic(x, y, alternative, axis):
+    '''Compute the BWS test statistic for two independent samples'''
+    # Public function currently does not accept `axis`, but `permutation_test`
+    # uses `axis` to make vectorized call.
+
+    Ri, Hj = np.sort(x, axis=axis), np.sort(y, axis=axis)
+    n, m = Ri.shape[axis], Hj.shape[axis]
+    i, j = np.arange(1, n+1), np.arange(1, m+1)
+
+    Bx_num = Ri - (m + n)/n * i
+    By_num = Hj - (m + n)/m * j
+
+    if alternative == 'two-sided':
+        Bx_num *= Bx_num
+        By_num *= By_num
+    else:
+        Bx_num *= np.abs(Bx_num)
+        By_num *= np.abs(By_num)
+
+    Bx_den = i/(n+1) * (1 - i/(n+1)) * m*(m+n)/n
+    By_den = j/(m+1) * (1 - j/(m+1)) * n*(m+n)/m
+
+    Bx = 1/n * np.sum(Bx_num/Bx_den, axis=axis)
+    By = 1/m * np.sum(By_num/By_den, axis=axis)
+
+    B = (Bx + By) / 2 if alternative == 'two-sided' else (Bx - By) / 2
+
+    return B
+
+
+def bws_test(x, y, *, alternative="two-sided", method=None):
+    r'''Perform the Baumgartner-Weiss-Schindler test on two independent samples.
+
+    The Baumgartner-Weiss-Schindler (BWS) test is a nonparametric test of 
+    the null hypothesis that the distribution underlying sample `x` 
+    is the same as the distribution underlying sample `y`. Unlike 
+    the Kolmogorov-Smirnov, Wilcoxon, and Cramer-Von Mises tests, 
+    the BWS test weights the integral by the variance of the difference
+    in cumulative distribution functions (CDFs), emphasizing the tails of the
+    distributions, which increases the power of the test in many applications.
+
+    Parameters
+    ----------
+    x, y : array-like
+        1-d arrays of samples.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        Let *F(u)* and *G(u)* be the cumulative distribution functions of the
+        distributions underlying `x` and `y`, respectively. Then the following
+        alternative hypotheses are available:
+
+        * 'two-sided': the distributions are not equal, i.e. *F(u) ≠ G(u)* for
+          at least one *u*.
+        * 'less': the distribution underlying `x` is stochastically less than
+          the distribution underlying `y`, i.e. *F(u) >= G(u)* for all *u*.
+        * 'greater': the distribution underlying `x` is stochastically greater
+          than the distribution underlying `y`, i.e. *F(u) <= G(u)* for all
+          *u*.
+
+        Under a more restrictive set of assumptions, the alternative hypotheses
+        can be expressed in terms of the locations of the distributions;
+        see [2] section 5.1.
+    method : PermutationMethod, optional
+        Configures the method used to compute the p-value. The default is
+        the default `PermutationMethod` object.
+
+    Returns
+    -------
+    res : PermutationTestResult
+    An object with attributes:
+
+    statistic : float
+        The observed test statistic of the data.
+    pvalue : float
+        The p-value for the given alternative.
+    null_distribution : ndarray
+        The values of the test statistic generated under the null hypothesis.
+
+    See also
+    --------
+    scipy.stats.wilcoxon, scipy.stats.mannwhitneyu, scipy.stats.ttest_ind
+
+    Notes
+    -----
+    When ``alternative=='two-sided'``, the statistic is defined by the
+    equations given in [1]_ Section 2. This statistic is not appropriate for
+    one-sided alternatives; in that case, the statistic is the *negative* of
+    that given by the equations in [1]_ Section 2. Consequently, when the
+    distribution of the first sample is stochastically greater than that of the
+    second sample, the statistic will tend to be positive.
+
+    References
+    ----------
+    .. [1] Neuhäuser, M. (2005). Exact Tests Based on the
+           Baumgartner-Weiss-Schindler Statistic: A Survey. Statistical Papers,
+           46(1), 1-29.
+    .. [2] Fay, M. P., & Proschan, M. A. (2010). Wilcoxon-Mann-Whitney or t-test?
+           On assumptions for hypothesis tests and multiple interpretations of 
+           decision rules. Statistics surveys, 4, 1.
+
+    Examples
+    --------
+    We follow the example of table 3 in [1]_: Fourteen children were divided
+    randomly into two groups. Their ranks at performing a specific tests are
+    as follows.
+
+    >>> import numpy as np
+    >>> x = [1, 2, 3, 4, 6, 7, 8]
+    >>> y = [5, 9, 10, 11, 12, 13, 14]
+
+    We use the BWS test to assess whether there is a statistically significant
+    difference between the two groups.
+    The null hypothesis is that there is no difference in the distributions of
+    performance between the two groups. We decide that a significance level of
+    1% is required to reject the null hypothesis in favor of the alternative
+    that the distributions are different.
+    Since the number of samples is very small, we can compare the observed test
+    statistic against the *exact* distribution of the test statistic under the
+    null hypothesis.
+
+    >>> from scipy.stats import bws_test
+    >>> res = bws_test(x, y)
+    >>> print(res.statistic)
+    5.132167152575315
+
+    This agrees with :math:`B = 5.132` reported in [1]_. The *p*-value produced
+    by `bws_test` also agrees with :math:`p = 0.0029` reported in [1]_.
+
+    >>> print(res.pvalue)
+    0.002913752913752914
+
+    Because the p-value is below our threshold of 1%, we take this as evidence
+    against the null hypothesis in favor of the alternative that there is a
+    difference in performance between the two groups.
+    '''
+
+    x, y, alternative, method = _bws_input_validation(x, y, alternative,
+                                                      method)
+    bws_statistic = partial(_bws_statistic, alternative=alternative)
+
+    permutation_alternative = 'less' if alternative == 'less' else 'greater'
+    res = stats.permutation_test((x, y), bws_statistic,
+                                 alternative=permutation_alternative,
+                                 **method._asdict())
+
+    return res
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_censored_data.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_censored_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6fee500f1d97db0bae9ebff26824d4d894c7f39
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_censored_data.py
@@ -0,0 +1,459 @@
+import numpy as np
+
+
+def _validate_1d(a, name, allow_inf=False):
+    if np.ndim(a) != 1:
+        raise ValueError(f'`{name}` must be a one-dimensional sequence.')
+    if np.isnan(a).any():
+        raise ValueError(f'`{name}` must not contain nan.')
+    if not allow_inf and np.isinf(a).any():
+        raise ValueError(f'`{name}` must contain only finite values.')
+
+
+def _validate_interval(interval):
+    interval = np.asarray(interval)
+    if interval.shape == (0,):
+        # The input was a sequence with length 0.
+        interval = interval.reshape((0, 2))
+    if interval.ndim != 2 or interval.shape[-1] != 2:
+        raise ValueError('`interval` must be a two-dimensional array with '
+                         'shape (m, 2), where m is the number of '
+                         'interval-censored values, but got shape '
+                         f'{interval.shape}')
+
+    if np.isnan(interval).any():
+        raise ValueError('`interval` must not contain nan.')
+    if np.isinf(interval).all(axis=1).any():
+        raise ValueError('In each row in `interval`, both values must not'
+                         ' be infinite.')
+    if (interval[:, 0] > interval[:, 1]).any():
+        raise ValueError('In each row of `interval`, the left value must not'
+                         ' exceed the right value.')
+
+    uncensored_mask = interval[:, 0] == interval[:, 1]
+    left_mask = np.isinf(interval[:, 0])
+    right_mask = np.isinf(interval[:, 1])
+    interval_mask = np.isfinite(interval).all(axis=1) & ~uncensored_mask
+
+    uncensored2 = interval[uncensored_mask, 0]
+    left2 = interval[left_mask, 1]
+    right2 = interval[right_mask, 0]
+    interval2 = interval[interval_mask]
+
+    return uncensored2, left2, right2, interval2
+
+
+def _validate_x_censored(x, censored):
+    x = np.asarray(x)
+    if x.ndim != 1:
+        raise ValueError('`x` must be one-dimensional.')
+    censored = np.asarray(censored)
+    if censored.ndim != 1:
+        raise ValueError('`censored` must be one-dimensional.')
+    if (~np.isfinite(x)).any():
+        raise ValueError('`x` must not contain nan or inf.')
+    if censored.size != x.size:
+        raise ValueError('`x` and `censored` must have the same length.')
+    return x, censored.astype(bool)
+
+
+class CensoredData:
+    """
+    Instances of this class represent censored data.
+
+    Instances may be passed to the ``fit`` method of continuous
+    univariate SciPy distributions for maximum likelihood estimation.
+    The *only* method of the univariate continuous distributions that
+    understands `CensoredData` is the ``fit`` method.  An instance of
+    `CensoredData` can not be passed to methods such as ``pdf`` and
+    ``cdf``.
+
+    An observation is said to be *censored* when the precise value is unknown,
+    but it has a known upper and/or lower bound.  The conventional terminology
+    is:
+
+    * left-censored: an observation is below a certain value but it is
+      unknown by how much.
+    * right-censored: an observation is above a certain value but it is
+      unknown by how much.
+    * interval-censored: an observation lies somewhere on an interval between
+      two values.
+
+    Left-, right-, and interval-censored data can be represented by
+    `CensoredData`.
+
+    For convenience, the class methods ``left_censored`` and
+    ``right_censored`` are provided to create a `CensoredData`
+    instance from a single one-dimensional array of measurements
+    and a corresponding boolean array to indicate which measurements
+    are censored.  The class method ``interval_censored`` accepts two
+    one-dimensional arrays that hold the lower and upper bounds of the
+    intervals.
+
+    Parameters
+    ----------
+    uncensored : array_like, 1D
+        Uncensored observations.
+    left : array_like, 1D
+        Left-censored observations.
+    right : array_like, 1D
+        Right-censored observations.
+    interval : array_like, 2D, with shape (m, 2)
+        Interval-censored observations.  Each row ``interval[k, :]``
+        represents the interval for the kth interval-censored observation.
+
+    Notes
+    -----
+    In the input array `interval`, the lower bound of the interval may
+    be ``-inf``, and the upper bound may be ``inf``, but at least one must be
+    finite. When the lower bound is ``-inf``, the row represents a left-
+    censored observation, and when the upper bound is ``inf``, the row
+    represents a right-censored observation.  If the length of an interval
+    is 0 (i.e. ``interval[k, 0] == interval[k, 1]``, the observation is
+    treated as uncensored.  So one can represent all the types of censored
+    and uncensored data in ``interval``, but it is generally more convenient
+    to use `uncensored`, `left` and `right` for uncensored, left-censored and
+    right-censored observations, respectively.
+
+    Examples
+    --------
+    In the most general case, a censored data set may contain values that
+    are left-censored, right-censored, interval-censored, and uncensored.
+    For example, here we create a data set with five observations.  Two
+    are uncensored (values 1 and 1.5), one is a left-censored observation
+    of 0, one is a right-censored observation of 10 and one is
+    interval-censored in the interval [2, 3].
+
+    >>> import numpy as np
+    >>> from scipy.stats import CensoredData
+    >>> data = CensoredData(uncensored=[1, 1.5], left=[0], right=[10],
+    ...                     interval=[[2, 3]])
+    >>> print(data)
+    CensoredData(5 values: 2 not censored, 1 left-censored,
+    1 right-censored, 1 interval-censored)
+
+    Equivalently,
+
+    >>> data = CensoredData(interval=[[1, 1],
+    ...                               [1.5, 1.5],
+    ...                               [-np.inf, 0],
+    ...                               [10, np.inf],
+    ...                               [2, 3]])
+    >>> print(data)
+    CensoredData(5 values: 2 not censored, 1 left-censored,
+    1 right-censored, 1 interval-censored)
+
+    A common case is to have a mix of uncensored observations and censored
+    observations that are all right-censored (or all left-censored). For
+    example, consider an experiment in which six devices are started at
+    various times and left running until they fail.  Assume that time is
+    measured in hours, and the experiment is stopped after 30 hours, even
+    if all the devices have not failed by that time.  We might end up with
+    data such as this::
+
+        Device  Start-time  Fail-time  Time-to-failure
+           1         0         13           13
+           2         2         24           22
+           3         5         22           17
+           4         8         23           15
+           5        10        ***          >20
+           6        12        ***          >18
+
+    Two of the devices had not failed when the experiment was stopped;
+    the observations of the time-to-failure for these two devices are
+    right-censored.  We can represent this data with
+
+    >>> data = CensoredData(uncensored=[13, 22, 17, 15], right=[20, 18])
+    >>> print(data)
+    CensoredData(6 values: 4 not censored, 2 right-censored)
+
+    Alternatively, we can use the method `CensoredData.right_censored` to
+    create a representation of this data.  The time-to-failure observations
+    are put the list ``ttf``.  The ``censored`` list indicates which values
+    in ``ttf`` are censored.
+
+    >>> ttf = [13, 22, 17, 15, 20, 18]
+    >>> censored = [False, False, False, False, True, True]
+
+    Pass these lists to `CensoredData.right_censored` to create an
+    instance of `CensoredData`.
+
+    >>> data = CensoredData.right_censored(ttf, censored)
+    >>> print(data)
+    CensoredData(6 values: 4 not censored, 2 right-censored)
+
+    If the input data is interval censored and already stored in two
+    arrays, one holding the low end of the intervals and another
+    holding the high ends, the class method ``interval_censored`` can
+    be used to create the `CensoredData` instance.
+
+    This example creates an instance with four interval-censored values.
+    The intervals are [10, 11], [0.5, 1], [2, 3], and [12.5, 13.5].
+
+    >>> a = [10, 0.5, 2, 12.5]  # Low ends of the intervals
+    >>> b = [11, 1.0, 3, 13.5]  # High ends of the intervals
+    >>> data = CensoredData.interval_censored(low=a, high=b)
+    >>> print(data)
+    CensoredData(4 values: 0 not censored, 4 interval-censored)
+
+    Finally, we create and censor some data from the `weibull_min`
+    distribution, and then fit `weibull_min` to that data. We'll assume
+    that the location parameter is known to be 0.
+
+    >>> from scipy.stats import weibull_min
+    >>> rng = np.random.default_rng()
+
+    Create the random data set.
+
+    >>> x = weibull_min.rvs(2.5, loc=0, scale=30, size=250, random_state=rng)
+    >>> x[x > 40] = 40  # Right-censor values greater or equal to 40.
+
+    Create the `CensoredData` instance with the `right_censored` method.
+    The censored values are those where the value is 40.
+
+    >>> data = CensoredData.right_censored(x, x == 40)
+    >>> print(data)
+    CensoredData(250 values: 215 not censored, 35 right-censored)
+
+    35 values have been right-censored.
+
+    Fit `weibull_min` to the censored data.  We expect to shape and scale
+    to be approximately 2.5 and 30, respectively.
+
+    >>> weibull_min.fit(data, floc=0)
+    (2.3575922823897315, 0, 30.40650074451254)
+
+    """
+
+    def __init__(self, uncensored=None, *, left=None, right=None,
+                 interval=None):
+        if uncensored is None:
+            uncensored = []
+        if left is None:
+            left = []
+        if right is None:
+            right = []
+        if interval is None:
+            interval = np.empty((0, 2))
+
+        _validate_1d(uncensored, 'uncensored')
+        _validate_1d(left, 'left')
+        _validate_1d(right, 'right')
+        uncensored2, left2, right2, interval2 = _validate_interval(interval)
+
+        self._uncensored = np.concatenate((uncensored, uncensored2))
+        self._left = np.concatenate((left, left2))
+        self._right = np.concatenate((right, right2))
+        # Note that by construction, the private attribute _interval
+        # will be a 2D array that contains only finite values representing
+        # intervals with nonzero but finite length.
+        self._interval = interval2
+
+    def __repr__(self):
+        uncensored_str = " ".join(np.array_repr(self._uncensored).split())
+        left_str = " ".join(np.array_repr(self._left).split())
+        right_str = " ".join(np.array_repr(self._right).split())
+        interval_str = " ".join(np.array_repr(self._interval).split())
+        return (f"CensoredData(uncensored={uncensored_str}, left={left_str}, "
+                f"right={right_str}, interval={interval_str})")
+
+    def __str__(self):
+        num_nc = len(self._uncensored)
+        num_lc = len(self._left)
+        num_rc = len(self._right)
+        num_ic = len(self._interval)
+        n = num_nc + num_lc + num_rc + num_ic
+        parts = [f'{num_nc} not censored']
+        if num_lc > 0:
+            parts.append(f'{num_lc} left-censored')
+        if num_rc > 0:
+            parts.append(f'{num_rc} right-censored')
+        if num_ic > 0:
+            parts.append(f'{num_ic} interval-censored')
+        return f'CensoredData({n} values: ' + ', '.join(parts) + ')'
+
+    # This is not a complete implementation of the arithmetic operators.
+    # All we need is subtracting a scalar and dividing by a scalar.
+
+    def __sub__(self, other):
+        return CensoredData(uncensored=self._uncensored - other,
+                            left=self._left - other,
+                            right=self._right - other,
+                            interval=self._interval - other)
+
+    def __truediv__(self, other):
+        return CensoredData(uncensored=self._uncensored / other,
+                            left=self._left / other,
+                            right=self._right / other,
+                            interval=self._interval / other)
+
+    def __len__(self):
+        """
+        The number of values (censored and not censored).
+        """
+        return (len(self._uncensored) + len(self._left) + len(self._right)
+                + len(self._interval))
+
+    def num_censored(self):
+        """
+        Number of censored values.
+        """
+        return len(self._left) + len(self._right) + len(self._interval)
+
+    @classmethod
+    def right_censored(cls, x, censored):
+        """
+        Create a `CensoredData` instance of right-censored data.
+
+        Parameters
+        ----------
+        x : array_like
+            `x` is the array of observed data or measurements.
+            `x` must be a one-dimensional sequence of finite numbers.
+        censored : array_like of bool
+            `censored` must be a one-dimensional sequence of boolean
+            values.  If ``censored[k]`` is True, the corresponding value
+            in `x` is right-censored.  That is, the value ``x[k]``
+            is the lower bound of the true (but unknown) value.
+
+        Returns
+        -------
+        data : `CensoredData`
+            An instance of `CensoredData` that represents the
+            collection of uncensored and right-censored values.
+
+        Examples
+        --------
+        >>> from scipy.stats import CensoredData
+
+        Two uncensored values (4 and 10) and two right-censored values
+        (24 and 25).
+
+        >>> data = CensoredData.right_censored([4, 10, 24, 25],
+        ...                                    [False, False, True, True])
+        >>> data
+        CensoredData(uncensored=array([ 4., 10.]),
+        left=array([], dtype=float64), right=array([24., 25.]),
+        interval=array([], shape=(0, 2), dtype=float64))
+        >>> print(data)
+        CensoredData(4 values: 2 not censored, 2 right-censored)
+        """
+        x, censored = _validate_x_censored(x, censored)
+        return cls(uncensored=x[~censored], right=x[censored])
+
+    @classmethod
+    def left_censored(cls, x, censored):
+        """
+        Create a `CensoredData` instance of left-censored data.
+
+        Parameters
+        ----------
+        x : array_like
+            `x` is the array of observed data or measurements.
+            `x` must be a one-dimensional sequence of finite numbers.
+        censored : array_like of bool
+            `censored` must be a one-dimensional sequence of boolean
+            values.  If ``censored[k]`` is True, the corresponding value
+            in `x` is left-censored.  That is, the value ``x[k]``
+            is the upper bound of the true (but unknown) value.
+
+        Returns
+        -------
+        data : `CensoredData`
+            An instance of `CensoredData` that represents the
+            collection of uncensored and left-censored values.
+
+        Examples
+        --------
+        >>> from scipy.stats import CensoredData
+
+        Two uncensored values (0.12 and 0.033) and two left-censored values
+        (both 1e-3).
+
+        >>> data = CensoredData.left_censored([0.12, 0.033, 1e-3, 1e-3],
+        ...                                   [False, False, True, True])
+        >>> data
+        CensoredData(uncensored=array([0.12 , 0.033]),
+        left=array([0.001, 0.001]), right=array([], dtype=float64),
+        interval=array([], shape=(0, 2), dtype=float64))
+        >>> print(data)
+        CensoredData(4 values: 2 not censored, 2 left-censored)
+        """
+        x, censored = _validate_x_censored(x, censored)
+        return cls(uncensored=x[~censored], left=x[censored])
+
+    @classmethod
+    def interval_censored(cls, low, high):
+        """
+        Create a `CensoredData` instance of interval-censored data.
+
+        This method is useful when all the data is interval-censored, and
+        the low and high ends of the intervals are already stored in
+        separate one-dimensional arrays.
+
+        Parameters
+        ----------
+        low : array_like
+            The one-dimensional array containing the low ends of the
+            intervals.
+        high : array_like
+            The one-dimensional array containing the high ends of the
+            intervals.
+
+        Returns
+        -------
+        data : `CensoredData`
+            An instance of `CensoredData` that represents the
+            collection of censored values.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.stats import CensoredData
+
+        ``a`` and ``b`` are the low and high ends of a collection of
+        interval-censored values.
+
+        >>> a = [0.5, 2.0, 3.0, 5.5]
+        >>> b = [1.0, 2.5, 3.5, 7.0]
+        >>> data = CensoredData.interval_censored(low=a, high=b)
+        >>> print(data)
+        CensoredData(4 values: 0 not censored, 4 interval-censored)
+        """
+        _validate_1d(low, 'low', allow_inf=True)
+        _validate_1d(high, 'high', allow_inf=True)
+        if len(low) != len(high):
+            raise ValueError('`low` and `high` must have the same length.')
+        interval = np.column_stack((low, high))
+        uncensored, left, right, interval = _validate_interval(interval)
+        return cls(uncensored=uncensored, left=left, right=right,
+                   interval=interval)
+
+    def _uncensor(self):
+        """
+        This function is used when a non-censored version of the data
+        is needed to create a rough estimate of the parameters of a
+        distribution via the method of moments or some similar method.
+        The data is "uncensored" by taking the given endpoints as the
+        data for the left- or right-censored data, and the mean for the
+        interval-censored data.
+        """
+        data = np.concatenate((self._uncensored, self._left, self._right,
+                               self._interval.mean(axis=1)))
+        return data
+
+    def _supported(self, a, b):
+        """
+        Return a subset of self containing the values that are in
+        (or overlap with) the interval (a, b).
+        """
+        uncensored = self._uncensored
+        uncensored = uncensored[(a < uncensored) & (uncensored < b)]
+        left = self._left
+        left = left[a < left]
+        right = self._right
+        right = right[right < b]
+        interval = self._interval
+        interval = interval[(a < interval[:, 1]) & (interval[:, 0] < b)]
+        return CensoredData(uncensored, left=left, right=right,
+                            interval=interval)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_common.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..4011d425cc4afea3c7ee8937526b13f1f92b0850
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_common.py
@@ -0,0 +1,5 @@
+from collections import namedtuple
+
+
+ConfidenceInterval = namedtuple("ConfidenceInterval", ["low", "high"])
+ConfidenceInterval. __doc__ = "Class for confidence intervals."
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_constants.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..b539ce8146ebdbc8e08c66143461b04d742804f2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_constants.py
@@ -0,0 +1,42 @@
+"""
+Statistics-related constants.
+
+"""
+import numpy as np
+
+
+# The smallest representable positive number such that 1.0 + _EPS != 1.0.
+_EPS = np.finfo(float).eps
+
+# The largest [in magnitude] usable floating value.
+_XMAX = np.finfo(float).max
+
+# The log of the largest usable floating value; useful for knowing
+# when exp(something) will overflow
+_LOGXMAX = np.log(_XMAX)
+
+# The smallest [in magnitude] usable (i.e. not subnormal) double precision
+# floating value.
+_XMIN = np.finfo(float).tiny
+
+# The log of the smallest [in magnitude] usable (i.e not subnormal)
+# double precision floating value.
+_LOGXMIN = np.log(_XMIN)
+
+# -special.psi(1)
+_EULER = 0.577215664901532860606512090082402431042
+
+# special.zeta(3, 1)  Apery's constant
+_ZETA3 = 1.202056903159594285399738161511449990765
+
+# sqrt(pi)
+_SQRT_PI = 1.772453850905516027298167483341145182798
+
+# sqrt(2/pi)
+_SQRT_2_OVER_PI = 0.7978845608028654
+
+# log(pi)
+_LOG_PI = 1.1447298858494002
+
+# log(sqrt(2/pi))
+_LOG_SQRT_2_OVER_PI = -0.22579135264472744
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_continuous_distns.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_continuous_distns.py
new file mode 100644
index 0000000000000000000000000000000000000000..d391a946205c975101a9e329fb35052f64be7287
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_continuous_distns.py
@@ -0,0 +1,12516 @@
+#
+# Author:  Travis Oliphant  2002-2011 with contributions from
+#          SciPy Developers 2004-2011
+#
+import warnings
+from collections.abc import Iterable
+from functools import wraps, cached_property
+import ctypes
+
+import numpy as np
+from numpy.polynomial import Polynomial
+from scipy.interpolate import BSpline
+from scipy._lib.doccer import (extend_notes_in_docstring,
+                               replace_notes_in_docstring,
+                               inherit_docstring_from)
+from scipy._lib._ccallback import LowLevelCallable
+from scipy import optimize
+from scipy import integrate
+import scipy.special as sc
+
+import scipy.special._ufuncs as scu
+from scipy._lib._util import _lazyselect, _lazywhere
+
+from . import _stats
+from ._tukeylambda_stats import (tukeylambda_variance as _tlvar,
+                                 tukeylambda_kurtosis as _tlkurt)
+from ._distn_infrastructure import (_vectorize_rvs_over_shapes,
+    get_distribution_names, _kurtosis, _isintegral,
+    rv_continuous, _skew, _get_fixed_fit_value, _check_shape, _ShapeInfo)
+from scipy.stats._distribution_infrastructure import _log1mexp
+from ._ksstats import kolmogn, kolmognp, kolmogni
+from ._constants import (_XMIN, _LOGXMIN, _EULER, _ZETA3, _SQRT_PI,
+                         _SQRT_2_OVER_PI, _LOG_PI, _LOG_SQRT_2_OVER_PI)
+from ._censored_data import CensoredData
+from scipy.optimize import root_scalar
+from scipy.stats._warnings_errors import FitError
+import scipy.stats as stats
+
+def _remove_optimizer_parameters(kwds):
+    """
+    Remove the optimizer-related keyword arguments 'loc', 'scale' and
+    'optimizer' from `kwds`.  Then check that `kwds` is empty, and
+    raise `TypeError("Unknown arguments: %s." % kwds)` if it is not.
+
+    This function is used in the fit method of distributions that override
+    the default method and do not use the default optimization code.
+
+    `kwds` is modified in-place.
+    """
+    kwds.pop('loc', None)
+    kwds.pop('scale', None)
+    kwds.pop('optimizer', None)
+    kwds.pop('method', None)
+    if kwds:
+        raise TypeError(f"Unknown arguments: {kwds}.")
+
+
+def _call_super_mom(fun):
+    # If fit method is overridden only for MLE and doesn't specify what to do
+    # if method == 'mm' or with censored data, this decorator calls the generic
+    # implementation.
+    @wraps(fun)
+    def wrapper(self, data, *args, **kwds):
+        method = kwds.get('method', 'mle').lower()
+        censored = isinstance(data, CensoredData)
+        if method == 'mm' or (censored and data.num_censored() > 0):
+            return super(type(self), self).fit(data, *args, **kwds)
+        else:
+            if censored:
+                # data is an instance of CensoredData, but actually holds
+                # no censored values, so replace it with the array of
+                # uncensored values.
+                data = data._uncensored
+            return fun(self, data, *args, **kwds)
+
+    return wrapper
+
+
+def _get_left_bracket(fun, rbrack, lbrack=None):
+    # find left bracket for `root_scalar`. A guess for lbrack may be provided.
+    lbrack = lbrack or rbrack - 1
+    diff = rbrack - lbrack
+
+    # if there is no sign change in `fun` between the brackets, expand
+    # rbrack - lbrack until a sign change occurs
+    def interval_contains_root(lbrack, rbrack):
+        # return true if the signs disagree.
+        return np.sign(fun(lbrack)) != np.sign(fun(rbrack))
+
+    while not interval_contains_root(lbrack, rbrack):
+        diff *= 2
+        lbrack = rbrack - diff
+
+        msg = ("The solver could not find a bracket containing a "
+               "root to an MLE first order condition.")
+        if np.isinf(lbrack):
+            raise FitSolverError(msg)
+
+    return lbrack
+
+
+class ksone_gen(rv_continuous):
+    r"""Kolmogorov-Smirnov one-sided test statistic distribution.
+
+    This is the distribution of the one-sided Kolmogorov-Smirnov (KS)
+    statistics :math:`D_n^+` and :math:`D_n^-`
+    for a finite sample size ``n >= 1`` (the shape parameter).
+
+    %(before_notes)s
+
+    See Also
+    --------
+    kstwobign, kstwo, kstest
+
+    Notes
+    -----
+    :math:`D_n^+` and :math:`D_n^-` are given by
+
+    .. math::
+
+        D_n^+ &= \text{sup}_x (F_n(x) - F(x)),\\
+        D_n^- &= \text{sup}_x (F(x) - F_n(x)),\\
+
+    where :math:`F` is a continuous CDF and :math:`F_n` is an empirical CDF.
+    `ksone` describes the distribution under the null hypothesis of the KS test
+    that the empirical CDF corresponds to :math:`n` i.i.d. random variates
+    with CDF :math:`F`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Birnbaum, Z. W. and Tingey, F.H. "One-sided confidence contours
+       for probability distribution functions", The Annals of Mathematical
+       Statistics, 22(4), pp 592-596 (1951).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import ksone
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Display the probability density function (``pdf``):
+
+    >>> n = 1e+03
+    >>> x = np.linspace(ksone.ppf(0.01, n),
+    ...                 ksone.ppf(0.99, n), 100)
+    >>> ax.plot(x, ksone.pdf(x, n),
+    ...         'r-', lw=5, alpha=0.6, label='ksone pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = ksone(n)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = ksone.ppf([0.001, 0.5, 0.999], n)
+    >>> np.allclose([0.001, 0.5, 0.999], ksone.cdf(vals, n))
+    True
+
+    """
+    def _argcheck(self, n):
+        return (n >= 1) & (n == np.round(n))
+
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (1, np.inf), (True, False))]
+
+    def _pdf(self, x, n):
+        return -scu._smirnovp(n, x)
+
+    def _cdf(self, x, n):
+        return scu._smirnovc(n, x)
+
+    def _sf(self, x, n):
+        return sc.smirnov(n, x)
+
+    def _ppf(self, q, n):
+        return scu._smirnovci(n, q)
+
+    def _isf(self, q, n):
+        return sc.smirnovi(n, q)
+
+
+ksone = ksone_gen(a=0.0, b=1.0, name='ksone')
+
+
+class kstwo_gen(rv_continuous):
+    r"""Kolmogorov-Smirnov two-sided test statistic distribution.
+
+    This is the distribution of the two-sided Kolmogorov-Smirnov (KS)
+    statistic :math:`D_n` for a finite sample size ``n >= 1``
+    (the shape parameter).
+
+    %(before_notes)s
+
+    See Also
+    --------
+    kstwobign, ksone, kstest
+
+    Notes
+    -----
+    :math:`D_n` is given by
+
+    .. math::
+
+        D_n = \text{sup}_x |F_n(x) - F(x)|
+
+    where :math:`F` is a (continuous) CDF and :math:`F_n` is an empirical CDF.
+    `kstwo` describes the distribution under the null hypothesis of the KS test
+    that the empirical CDF corresponds to :math:`n` i.i.d. random variates
+    with CDF :math:`F`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Simard, R., L'Ecuyer, P. "Computing the Two-Sided
+       Kolmogorov-Smirnov Distribution",  Journal of Statistical Software,
+       Vol 39, 11, 1-18 (2011).
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import kstwo
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Display the probability density function (``pdf``):
+
+    >>> n = 10
+    >>> x = np.linspace(kstwo.ppf(0.01, n),
+    ...                 kstwo.ppf(0.99, n), 100)
+    >>> ax.plot(x, kstwo.pdf(x, n),
+    ...         'r-', lw=5, alpha=0.6, label='kstwo pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = kstwo(n)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = kstwo.ppf([0.001, 0.5, 0.999], n)
+    >>> np.allclose([0.001, 0.5, 0.999], kstwo.cdf(vals, n))
+    True
+
+    """
+    def _argcheck(self, n):
+        return (n >= 1) & (n == np.round(n))
+
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (1, np.inf), (True, False))]
+
+    def _get_support(self, n):
+        return (0.5/(n if not isinstance(n, Iterable) else np.asanyarray(n)),
+                1.0)
+
+    def _pdf(self, x, n):
+        return kolmognp(n, x)
+
+    def _cdf(self, x, n):
+        return kolmogn(n, x)
+
+    def _sf(self, x, n):
+        return kolmogn(n, x, cdf=False)
+
+    def _ppf(self, q, n):
+        return kolmogni(n, q, cdf=True)
+
+    def _isf(self, q, n):
+        return kolmogni(n, q, cdf=False)
+
+
+# Use the pdf, (not the ppf) to compute moments
+kstwo = kstwo_gen(momtype=0, a=0.0, b=1.0, name='kstwo')
+
+
+class kstwobign_gen(rv_continuous):
+    r"""Limiting distribution of scaled Kolmogorov-Smirnov two-sided test statistic.
+
+    This is the asymptotic distribution of the two-sided Kolmogorov-Smirnov
+    statistic :math:`\sqrt{n} D_n` that measures the maximum absolute
+    distance of the theoretical (continuous) CDF from the empirical CDF.
+    (see `kstest`).
+
+    %(before_notes)s
+
+    See Also
+    --------
+    ksone, kstwo, kstest
+
+    Notes
+    -----
+    :math:`\sqrt{n} D_n` is given by
+
+    .. math::
+
+        D_n = \text{sup}_x |F_n(x) - F(x)|
+
+    where :math:`F` is a continuous CDF and :math:`F_n` is an empirical CDF.
+    `kstwobign`  describes the asymptotic distribution (i.e. the limit of
+    :math:`\sqrt{n} D_n`) under the null hypothesis of the KS test that the
+    empirical CDF corresponds to i.i.d. random variates with CDF :math:`F`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Feller, W. "On the Kolmogorov-Smirnov Limit Theorems for Empirical
+       Distributions",  Ann. Math. Statist. Vol 19, 177-189 (1948).
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        return -scu._kolmogp(x)
+
+    def _cdf(self, x):
+        return scu._kolmogc(x)
+
+    def _sf(self, x):
+        return sc.kolmogorov(x)
+
+    def _ppf(self, q):
+        return scu._kolmogci(q)
+
+    def _isf(self, q):
+        return sc.kolmogi(q)
+
+
+kstwobign = kstwobign_gen(a=0.0, name='kstwobign')
+
+
+## Normal distribution
+
+# loc = mu, scale = std
+# Keep these implementations out of the class definition so they can be reused
+# by other distributions.
+_norm_pdf_C = np.sqrt(2*np.pi)
+_norm_pdf_logC = np.log(_norm_pdf_C)
+
+
+def _norm_pdf(x):
+    return np.exp(-x**2/2.0) / _norm_pdf_C
+
+
+def _norm_logpdf(x):
+    return -x**2 / 2.0 - _norm_pdf_logC
+
+
+def _norm_cdf(x):
+    return sc.ndtr(x)
+
+
+def _norm_logcdf(x):
+    return sc.log_ndtr(x)
+
+
+def _norm_ppf(q):
+    return sc.ndtri(q)
+
+
+def _norm_sf(x):
+    return _norm_cdf(-x)
+
+
+def _norm_logsf(x):
+    return _norm_logcdf(-x)
+
+
+def _norm_isf(q):
+    return -_norm_ppf(q)
+
+
+class norm_gen(rv_continuous):
+    r"""A normal continuous random variable.
+
+    The location (``loc``) keyword specifies the mean.
+    The scale (``scale``) keyword specifies the standard deviation.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `norm` is:
+
+    .. math::
+
+        f(x) = \frac{\exp(-x^2/2)}{\sqrt{2\pi}}
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.standard_normal(size)
+
+    def _pdf(self, x):
+        # norm.pdf(x) = exp(-x**2/2)/sqrt(2*pi)
+        return _norm_pdf(x)
+
+    def _logpdf(self, x):
+        return _norm_logpdf(x)
+
+    def _cdf(self, x):
+        return _norm_cdf(x)
+
+    def _logcdf(self, x):
+        return _norm_logcdf(x)
+
+    def _sf(self, x):
+        return _norm_sf(x)
+
+    def _logsf(self, x):
+        return _norm_logsf(x)
+
+    def _ppf(self, q):
+        return _norm_ppf(q)
+
+    def _isf(self, q):
+        return _norm_isf(q)
+
+    def _stats(self):
+        return 0.0, 1.0, 0.0, 0.0
+
+    def _entropy(self):
+        return 0.5*(np.log(2*np.pi)+1)
+
+    @_call_super_mom
+    @replace_notes_in_docstring(rv_continuous, notes="""\
+        For the normal distribution, method of moments and maximum likelihood
+        estimation give identical fits, and explicit formulas for the estimates
+        are available.
+        This function uses these explicit formulas for the maximum likelihood
+        estimation of the normal distribution parameters, so the
+        `optimizer` and `method` arguments are ignored.\n\n""")
+    def fit(self, data, **kwds):
+        floc = kwds.pop('floc', None)
+        fscale = kwds.pop('fscale', None)
+
+        _remove_optimizer_parameters(kwds)
+
+        if floc is not None and fscale is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            # Without this check, this function would just return the
+            # parameters that were given.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        data = np.asarray(data)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        if floc is None:
+            loc = data.mean()
+        else:
+            loc = floc
+
+        if fscale is None:
+            scale = np.sqrt(((data - loc)**2).mean())
+        else:
+            scale = fscale
+
+        return loc, scale
+
+    def _munp(self, n):
+        """
+        @returns Moments of standard normal distribution for integer n >= 0
+
+        See eq. 16 of https://arxiv.org/abs/1209.4340v2
+        """
+        if n == 0:
+            return 1.
+        if n % 2 == 0:
+            return sc.factorial2(int(n) - 1)
+        else:
+            return 0.
+
+
+norm = norm_gen(name='norm')
+
+
+class alpha_gen(rv_continuous):
+    r"""An alpha continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `alpha` ([1]_, [2]_) is:
+
+    .. math::
+
+        f(x, a) = \frac{1}{x^2 \Phi(a) \sqrt{2\pi}} *
+                  \exp(-\frac{1}{2} (a-1/x)^2)
+
+    where :math:`\Phi` is the normal CDF, :math:`x > 0`, and :math:`a > 0`.
+
+    `alpha` takes ``a`` as a shape parameter.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Johnson, Kotz, and Balakrishnan, "Continuous Univariate
+           Distributions, Volume 1", Second Edition, John Wiley and Sons,
+           p. 173 (1994).
+    .. [2] Anthony A. Salvia, "Reliability applications of the Alpha
+           Distribution", IEEE Transactions on Reliability, Vol. R-34,
+           No. 3, pp. 251-252 (1985).
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        # alpha.pdf(x, a) = 1/(x**2*Phi(a)*sqrt(2*pi)) * exp(-1/2 * (a-1/x)**2)
+        return 1.0/(x**2)/_norm_cdf(a)*_norm_pdf(a-1.0/x)
+
+    def _logpdf(self, x, a):
+        return -2*np.log(x) + _norm_logpdf(a-1.0/x) - np.log(_norm_cdf(a))
+
+    def _cdf(self, x, a):
+        return _norm_cdf(a-1.0/x) / _norm_cdf(a)
+
+    def _ppf(self, q, a):
+        return 1.0/np.asarray(a - _norm_ppf(q*_norm_cdf(a)))
+
+    def _stats(self, a):
+        return [np.inf]*2 + [np.nan]*2
+
+
+alpha = alpha_gen(a=0.0, name='alpha')
+
+
+class anglit_gen(rv_continuous):
+    r"""An anglit continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `anglit` is:
+
+    .. math::
+
+        f(x) = \sin(2x + \pi/2) = \cos(2x)
+
+    for :math:`-\pi/4 \le x \le \pi/4`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # anglit.pdf(x) = sin(2*x + \pi/2) = cos(2*x)
+        return np.cos(2*x)
+
+    def _cdf(self, x):
+        return np.sin(x+np.pi/4)**2.0
+
+    def _sf(self, x):
+        return np.cos(x + np.pi / 4) ** 2.0
+
+    def _ppf(self, q):
+        return np.arcsin(np.sqrt(q))-np.pi/4
+
+    def _stats(self):
+        return 0.0, np.pi*np.pi/16-0.5, 0.0, -2*(np.pi**4 - 96)/(np.pi*np.pi-8)**2
+
+    def _entropy(self):
+        return 1-np.log(2)
+
+
+anglit = anglit_gen(a=-np.pi/4, b=np.pi/4, name='anglit')
+
+
+class arcsine_gen(rv_continuous):
+    r"""An arcsine continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `arcsine` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\pi \sqrt{x (1-x)}}
+
+    for :math:`0 < x < 1`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # arcsine.pdf(x) = 1/(pi*sqrt(x*(1-x)))
+        with np.errstate(divide='ignore'):
+            return 1.0/np.pi/np.sqrt(x*(1-x))
+
+    def _cdf(self, x):
+        return 2.0/np.pi*np.arcsin(np.sqrt(x))
+
+    def _ppf(self, q):
+        return np.sin(np.pi/2.0*q)**2.0
+
+    def _stats(self):
+        mu = 0.5
+        mu2 = 1.0/8
+        g1 = 0
+        g2 = -3.0/2.0
+        return mu, mu2, g1, g2
+
+    def _entropy(self):
+        return -0.24156447527049044468
+
+
+arcsine = arcsine_gen(a=0.0, b=1.0, name='arcsine')
+
+
+class FitDataError(ValueError):
+    """Raised when input data is inconsistent with fixed parameters."""
+    # This exception is raised by, for example, beta_gen.fit when both floc
+    # and fscale are fixed and there are values in the data not in the open
+    # interval (floc, floc+fscale).
+    def __init__(self, distr, lower, upper):
+        self.args = (
+            "Invalid values in `data`.  Maximum likelihood "
+            f"estimation with {distr!r} requires that {lower!r} < "
+            f"(x - loc)/scale  < {upper!r} for each x in `data`.",
+        )
+
+
+class FitSolverError(FitError):
+    """
+    Raised when a solver fails to converge while fitting a distribution.
+    """
+    # This exception is raised by, for example, beta_gen.fit when
+    # optimize.fsolve returns with ier != 1.
+    def __init__(self, mesg):
+        emsg = "Solver for the MLE equations failed to converge: "
+        emsg += mesg.replace('\n', '')
+        self.args = (emsg,)
+
+
+def _beta_mle_a(a, b, n, s1):
+    # The zeros of this function give the MLE for `a`, with
+    # `b`, `n` and `s1` given.  `s1` is the sum of the logs of
+    # the data. `n` is the number of data points.
+    psiab = sc.psi(a + b)
+    func = s1 - n * (-psiab + sc.psi(a))
+    return func
+
+
+def _beta_mle_ab(theta, n, s1, s2):
+    # Zeros of this function are critical points of
+    # the maximum likelihood function.  Solving this system
+    # for theta (which contains a and b) gives the MLE for a and b
+    # given `n`, `s1` and `s2`.  `s1` is the sum of the logs of the data,
+    # and `s2` is the sum of the logs of 1 - data.  `n` is the number
+    # of data points.
+    a, b = theta
+    psiab = sc.psi(a + b)
+    func = [s1 - n * (-psiab + sc.psi(a)),
+            s2 - n * (-psiab + sc.psi(b))]
+    return func
+
+
+class beta_gen(rv_continuous):
+    r"""A beta continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `beta` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{\Gamma(a+b) x^{a-1} (1-x)^{b-1}}
+                          {\Gamma(a) \Gamma(b)}
+
+    for :math:`0 <= x <= 1`, :math:`a > 0`, :math:`b > 0`, where
+    :math:`\Gamma` is the gamma function (`scipy.special.gamma`).
+
+    `beta` takes :math:`a` and :math:`b` as shape parameters.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf``
+    methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _rvs(self, a, b, size=None, random_state=None):
+        return random_state.beta(a, b, size)
+
+    def _pdf(self, x, a, b):
+        #                     gamma(a+b) * x**(a-1) * (1-x)**(b-1)
+        # beta.pdf(x, a, b) = ------------------------------------
+        #                              gamma(a)*gamma(b)
+        with np.errstate(over='ignore'):
+            return scu._beta_pdf(x, a, b)
+
+    def _logpdf(self, x, a, b):
+        lPx = sc.xlog1py(b - 1.0, -x) + sc.xlogy(a - 1.0, x)
+        lPx -= sc.betaln(a, b)
+        return lPx
+
+    def _cdf(self, x, a, b):
+        return sc.betainc(a, b, x)
+
+    def _sf(self, x, a, b):
+        return sc.betaincc(a, b, x)
+
+    def _isf(self, x, a, b):
+        return sc.betainccinv(a, b, x)
+
+    def _ppf(self, q, a, b):
+        return scu._beta_ppf(q, a, b)
+
+    def _stats(self, a, b):
+        a_plus_b = a + b
+        _beta_mean = a/a_plus_b
+        _beta_variance = a*b / (a_plus_b**2 * (a_plus_b + 1))
+        _beta_skewness = ((2 * (b - a) * np.sqrt(a_plus_b + 1)) /
+                          ((a_plus_b + 2) * np.sqrt(a * b)))
+        _beta_kurtosis_excess_n = 6 * ((a - b)**2 * (a_plus_b + 1) -
+                                       a * b * (a_plus_b + 2))
+        _beta_kurtosis_excess_d = a * b * (a_plus_b + 2) * (a_plus_b + 3)
+        _beta_kurtosis_excess = _beta_kurtosis_excess_n / _beta_kurtosis_excess_d
+        return (
+            _beta_mean,
+            _beta_variance,
+            _beta_skewness,
+            _beta_kurtosis_excess)
+
+    def _fitstart(self, data):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+
+        g1 = _skew(data)
+        g2 = _kurtosis(data)
+
+        def func(x):
+            a, b = x
+            sk = 2*(b-a)*np.sqrt(a + b + 1) / (a + b + 2) / np.sqrt(a*b)
+            ku = a**3 - a**2*(2*b-1) + b**2*(b+1) - 2*a*b*(b+2)
+            ku /= a*b*(a+b+2)*(a+b+3)
+            ku *= 6
+            return [sk-g1, ku-g2]
+        a, b = optimize.fsolve(func, (1.0, 1.0))
+        return super()._fitstart(data, args=(a, b))
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        In the special case where `method="MLE"` and
+        both `floc` and `fscale` are given, a
+        `ValueError` is raised if any value `x` in `data` does not satisfy
+        `floc < x < floc + fscale`.\n\n""")
+    def fit(self, data, *args, **kwds):
+        # Override rv_continuous.fit, so we can more efficiently handle the
+        # case where floc and fscale are given.
+
+        floc = kwds.get('floc', None)
+        fscale = kwds.get('fscale', None)
+
+        if floc is None or fscale is None:
+            # do general fit
+            return super().fit(data, *args, **kwds)
+
+        # We already got these from kwds, so just pop them.
+        kwds.pop('floc', None)
+        kwds.pop('fscale', None)
+
+        f0 = _get_fixed_fit_value(kwds, ['f0', 'fa', 'fix_a'])
+        f1 = _get_fixed_fit_value(kwds, ['f1', 'fb', 'fix_b'])
+
+        _remove_optimizer_parameters(kwds)
+
+        if f0 is not None and f1 is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        # Special case: loc and scale are constrained, so we are fitting
+        # just the shape parameters.  This can be done much more efficiently
+        # than the method used in `rv_continuous.fit`.  (See the subsection
+        # "Two unknown parameters" in the section "Maximum likelihood" of
+        # the Wikipedia article on the Beta distribution for the formulas.)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        # Normalize the data to the interval [0, 1].
+        data = (np.ravel(data) - floc) / fscale
+        if np.any(data <= 0) or np.any(data >= 1):
+            raise FitDataError("beta", lower=floc, upper=floc + fscale)
+
+        xbar = data.mean()
+
+        if f0 is not None or f1 is not None:
+            # One of the shape parameters is fixed.
+
+            if f0 is not None:
+                # The shape parameter a is fixed, so swap the parameters
+                # and flip the data.  We always solve for `a`.  The result
+                # will be swapped back before returning.
+                b = f0
+                data = 1 - data
+                xbar = 1 - xbar
+            else:
+                b = f1
+
+            # Initial guess for a.  Use the formula for the mean of the beta
+            # distribution, E[x] = a / (a + b), to generate a reasonable
+            # starting point based on the mean of the data and the given
+            # value of b.
+            a = b * xbar / (1 - xbar)
+
+            # Compute the MLE for `a` by solving _beta_mle_a.
+            theta, info, ier, mesg = optimize.fsolve(
+                _beta_mle_a, a,
+                args=(b, len(data), np.log(data).sum()),
+                full_output=True
+            )
+            if ier != 1:
+                raise FitSolverError(mesg=mesg)
+            a = theta[0]
+
+            if f0 is not None:
+                # The shape parameter a was fixed, so swap back the
+                # parameters.
+                a, b = b, a
+
+        else:
+            # Neither of the shape parameters is fixed.
+
+            # s1 and s2 are used in the extra arguments passed to _beta_mle_ab
+            # by optimize.fsolve.
+            s1 = np.log(data).sum()
+            s2 = sc.log1p(-data).sum()
+
+            # Use the "method of moments" to estimate the initial
+            # guess for a and b.
+            fac = xbar * (1 - xbar) / data.var(ddof=0) - 1
+            a = xbar * fac
+            b = (1 - xbar) * fac
+
+            # Compute the MLE for a and b by solving _beta_mle_ab.
+            theta, info, ier, mesg = optimize.fsolve(
+                _beta_mle_ab, [a, b],
+                args=(len(data), s1, s2),
+                full_output=True
+            )
+            if ier != 1:
+                raise FitSolverError(mesg=mesg)
+            a, b = theta
+
+        return a, b, floc, fscale
+
+    def _entropy(self, a, b):
+        def regular(a, b):
+            return (sc.betaln(a, b) - (a - 1) * sc.psi(a) -
+                    (b - 1) * sc.psi(b) + (a + b - 2) * sc.psi(a + b))
+
+        def asymptotic_ab_large(a, b):
+            sum_ab = a + b
+            log_term = 0.5 * (
+                np.log(2*np.pi) + np.log(a) + np.log(b) - 3*np.log(sum_ab) + 1
+            )
+            t1 = 110/sum_ab + 20*sum_ab**-2.0 + sum_ab**-3.0 - 2*sum_ab**-4.0
+            t2 = -50/a - 10*a**-2.0 - a**-3.0 + a**-4.0
+            t3 = -50/b - 10*b**-2.0 - b**-3.0 + b**-4.0
+            return log_term + (t1 + t2 + t3) / 120
+
+        def asymptotic_b_large(a, b):
+            sum_ab = a + b
+            t1 = sc.gammaln(a) - (a - 1) * sc.psi(a)
+            t2 = (
+                - 1/(2*b) + 1/(12*b) - b**-2.0/12 - b**-3.0/120 + b**-4.0/120
+                + b**-5.0/252 - b**-6.0/252 + 1/sum_ab - 1/(12*sum_ab)
+                + sum_ab**-2.0/6 + sum_ab**-3.0/120 - sum_ab**-4.0/60
+                - sum_ab**-5.0/252 + sum_ab**-6.0/126
+            )
+            log_term = sum_ab*np.log1p(a/b) + np.log(b) - 2*np.log(sum_ab)
+            return t1 + t2 + log_term
+
+        def threshold_large(v):
+            if v == 1.0:
+                return 1000
+
+            j = np.log10(v)
+            digits = int(j)
+            d = int(v / 10 ** digits) + 2
+            return d*10**(7 + j)
+
+        if a >= 4.96e6 and b >= 4.96e6:
+            return asymptotic_ab_large(a, b)
+        elif a <= 4.9e6 and b - a >= 1e6 and b >= threshold_large(a):
+            return asymptotic_b_large(a, b)
+        elif b <= 4.9e6 and a - b >= 1e6 and a >= threshold_large(b):
+            return asymptotic_b_large(b, a)
+        else:
+            return regular(a, b)
+
+
+beta = beta_gen(a=0.0, b=1.0, name='beta')
+
+
+class betaprime_gen(rv_continuous):
+    r"""A beta prime continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `betaprime` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{x^{a-1} (1+x)^{-a-b}}{\beta(a, b)}
+
+    for :math:`x >= 0`, :math:`a > 0`, :math:`b > 0`, where
+    :math:`\beta(a, b)` is the beta function (see `scipy.special.beta`).
+
+    `betaprime` takes ``a`` and ``b`` as shape parameters.
+
+    The distribution is related to the `beta` distribution as follows:
+    If :math:`X` follows a beta distribution with parameters :math:`a, b`,
+    then :math:`Y = X/(1-X)` has a beta prime distribution with
+    parameters :math:`a, b` ([1]_).
+
+    The beta prime distribution is a reparametrized version of the
+    F distribution.  The beta prime distribution with shape parameters
+    ``a`` and ``b`` and ``scale = s`` is equivalent to the F distribution
+    with parameters ``d1 = 2*a``, ``d2 = 2*b`` and ``scale = (a/b)*s``.
+    For example,
+
+    >>> from scipy.stats import betaprime, f
+    >>> x = [1, 2, 5, 10]
+    >>> a = 12
+    >>> b = 5
+    >>> betaprime.pdf(x, a, b, scale=2)
+    array([0.00541179, 0.08331299, 0.14669185, 0.03150079])
+    >>> f.pdf(x, 2*a, 2*b, scale=(a/b)*2)
+    array([0.00541179, 0.08331299, 0.14669185, 0.03150079])
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Beta prime distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Beta_prime_distribution
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _rvs(self, a, b, size=None, random_state=None):
+        u1 = gamma.rvs(a, size=size, random_state=random_state)
+        u2 = gamma.rvs(b, size=size, random_state=random_state)
+        return u1 / u2
+
+    def _pdf(self, x, a, b):
+        # betaprime.pdf(x, a, b) = x**(a-1) * (1+x)**(-a-b) / beta(a, b)
+        return np.exp(self._logpdf(x, a, b))
+
+    def _logpdf(self, x, a, b):
+        return sc.xlogy(a - 1.0, x) - sc.xlog1py(a + b, x) - sc.betaln(a, b)
+
+    def _cdf(self, x, a, b):
+        # note: f2 is the direct way to compute the cdf if the relationship
+        # to the beta distribution is used.
+        # however, for very large x, x/(1+x) == 1. since the distribution
+        # has very fat tails if b is small, this can cause inaccurate results
+        # use the following relationship of the incomplete beta function:
+        # betainc(x, a, b) = 1 - betainc(1-x, b, a)
+        # see gh-17631
+        return _lazywhere(
+            x > 1, [x, a, b],
+            lambda x_, a_, b_: beta._sf(1/(1+x_), b_, a_),
+            f2=lambda x_, a_, b_: beta._cdf(x_/(1+x_), a_, b_))
+
+    def _sf(self, x, a, b):
+        return _lazywhere(
+            x > 1, [x, a, b],
+            lambda x_, a_, b_: beta._cdf(1/(1+x_), b_, a_),
+            f2=lambda x_, a_, b_: beta._sf(x_/(1+x_), a_, b_)
+        )
+
+    def _ppf(self, p, a, b):
+        p, a, b = np.broadcast_arrays(p, a, b)
+        # By default, compute the ppf by solving the following:
+        # p = beta._cdf(x/(1+x), a, b). This implies x = r/(1-r) with
+        # r = beta._ppf(p, a, b). This can cause numerical issues if r is
+        # very close to 1. In that case, invert the alternative expression of
+        # the cdf: p = beta._sf(1/(1+x), b, a).
+        r = stats.beta._ppf(p, a, b)
+        with np.errstate(divide='ignore'):
+            out = r / (1 - r)
+        rnear1 = r > 0.9999
+        if np.isscalar(r):
+            if rnear1:
+                out = 1/stats.beta._isf(p, b, a) - 1
+        else:
+            out[rnear1] = 1/stats.beta._isf(p[rnear1], b[rnear1], a[rnear1]) - 1
+        return out
+
+    def _munp(self, n, a, b):
+        return _lazywhere(
+            b > n, (a, b),
+            lambda a, b: np.prod([(a+i-1)/(b-i) for i in range(1, int(n)+1)], axis=0),
+            fillvalue=np.inf)
+
+
+betaprime = betaprime_gen(a=0.0, name='betaprime')
+
+
+class bradford_gen(rv_continuous):
+    r"""A Bradford continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `bradford` is:
+
+    .. math::
+
+        f(x, c) = \frac{c}{\log(1+c) (1+cx)}
+
+    for :math:`0 <= x <= 1` and :math:`c > 0`.
+
+    `bradford` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # bradford.pdf(x, c) = c / (k * (1+c*x))
+        return c / (c*x + 1.0) / sc.log1p(c)
+
+    def _cdf(self, x, c):
+        return sc.log1p(c*x) / sc.log1p(c)
+
+    def _ppf(self, q, c):
+        return sc.expm1(q * sc.log1p(c)) / c
+
+    def _stats(self, c, moments='mv'):
+        k = np.log(1.0+c)
+        mu = (c-k)/(c*k)
+        mu2 = ((c+2.0)*k-2.0*c)/(2*c*k*k)
+        g1 = None
+        g2 = None
+        if 's' in moments:
+            g1 = np.sqrt(2)*(12*c*c-9*c*k*(c+2)+2*k*k*(c*(c+3)+3))
+            g1 /= np.sqrt(c*(c*(k-2)+2*k))*(3*c*(k-2)+6*k)
+        if 'k' in moments:
+            g2 = (c**3*(k-3)*(k*(3*k-16)+24)+12*k*c*c*(k-4)*(k-3) +
+                  6*c*k*k*(3*k-14) + 12*k**3)
+            g2 /= 3*c*(c*(k-2)+2*k)**2
+        return mu, mu2, g1, g2
+
+    def _entropy(self, c):
+        k = np.log(1+c)
+        return k/2.0 - np.log(c/k)
+
+
+bradford = bradford_gen(a=0.0, b=1.0, name='bradford')
+
+
+class burr_gen(rv_continuous):
+    r"""A Burr (Type III) continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    fisk : a special case of either `burr` or `burr12` with ``d=1``
+    burr12 : Burr Type XII distribution
+    mielke : Mielke Beta-Kappa / Dagum distribution
+
+    Notes
+    -----
+    The probability density function for `burr` is:
+
+    .. math::
+
+        f(x; c, d) = c d \frac{x^{-c - 1}}
+                              {{(1 + x^{-c})}^{d + 1}}
+
+    for :math:`x >= 0` and :math:`c, d > 0`.
+
+    `burr` takes ``c`` and ``d`` as shape parameters for :math:`c` and
+    :math:`d`.
+
+    This is the PDF corresponding to the third CDF given in Burr's list;
+    specifically, it is equation (11) in Burr's paper [1]_. The distribution
+    is also commonly referred to as the Dagum distribution [2]_. If the
+    parameter :math:`c < 1` then the mean of the distribution does not
+    exist and if :math:`c < 2` the variance does not exist [2]_.
+    The PDF is finite at the left endpoint :math:`x = 0` if :math:`c * d >= 1`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Burr, I. W. "Cumulative frequency functions", Annals of
+       Mathematical Statistics, 13(2), pp 215-232 (1942).
+    .. [2] https://en.wikipedia.org/wiki/Dagum_distribution
+    .. [3] Kleiber, Christian. "A guide to the Dagum distributions."
+       Modeling Income Distributions and Lorenz Curves  pp 97-117 (2008).
+
+    %(example)s
+
+    """
+    # Do not set _support_mask to rv_continuous._open_support_mask
+    # Whether the left-hand endpoint is suitable for pdf evaluation is dependent
+    # on the values of c and d: if c*d >= 1, the pdf is finite, otherwise infinite.
+
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        id = _ShapeInfo("d", False, (0, np.inf), (False, False))
+        return [ic, id]
+
+    def _pdf(self, x, c, d):
+        # burr.pdf(x, c, d) = c * d * x**(-c-1) * (1+x**(-c))**(-d-1)
+        output = _lazywhere(
+            x == 0, [x, c, d],
+            lambda x_, c_, d_: c_ * d_ * (x_**(c_*d_-1)) / (1 + x_**c_),
+            f2=lambda x_, c_, d_: (c_ * d_ * (x_ ** (-c_ - 1.0)) /
+                                   ((1 + x_ ** (-c_)) ** (d_ + 1.0))))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def _logpdf(self, x, c, d):
+        output = _lazywhere(
+            x == 0, [x, c, d],
+            lambda x_, c_, d_: (np.log(c_) + np.log(d_) + sc.xlogy(c_*d_ - 1, x_)
+                                - (d_+1) * sc.log1p(x_**(c_))),
+            f2=lambda x_, c_, d_: (np.log(c_) + np.log(d_)
+                                   + sc.xlogy(-c_ - 1, x_)
+                                   - sc.xlog1py(d_+1, x_**(-c_))))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def _cdf(self, x, c, d):
+        return (1 + x**(-c))**(-d)
+
+    def _logcdf(self, x, c, d):
+        return sc.log1p(x**(-c)) * (-d)
+
+    def _sf(self, x, c, d):
+        return np.exp(self._logsf(x, c, d))
+
+    def _logsf(self, x, c, d):
+        return np.log1p(- (1 + x**(-c))**(-d))
+
+    def _ppf(self, q, c, d):
+        return (q**(-1.0/d) - 1)**(-1.0/c)
+
+    def _isf(self, q, c, d):
+        _q = sc.xlog1py(-1.0 / d, -q)
+        return sc.expm1(_q) ** (-1.0 / c)
+
+    def _stats(self, c, d):
+        nc = np.arange(1, 5).reshape(4,1) / c
+        # ek is the kth raw moment, e1 is the mean e2-e1**2 variance etc.
+        e1, e2, e3, e4 = sc.beta(d + nc, 1. - nc) * d
+        mu = np.where(c > 1.0, e1, np.nan)
+        mu2_if_c = e2 - mu**2
+        mu2 = np.where(c > 2.0, mu2_if_c, np.nan)
+        g1 = _lazywhere(
+            c > 3.0,
+            (c, e1, e2, e3, mu2_if_c),
+            lambda c, e1, e2, e3, mu2_if_c: ((e3 - 3*e2*e1 + 2*e1**3)
+                                             / np.sqrt((mu2_if_c)**3)),
+            fillvalue=np.nan)
+        g2 = _lazywhere(
+            c > 4.0,
+            (c, e1, e2, e3, e4, mu2_if_c),
+            lambda c, e1, e2, e3, e4, mu2_if_c: (
+                ((e4 - 4*e3*e1 + 6*e2*e1**2 - 3*e1**4) / mu2_if_c**2) - 3),
+            fillvalue=np.nan)
+        if np.ndim(c) == 0:
+            return mu.item(), mu2.item(), g1.item(), g2.item()
+        return mu, mu2, g1, g2
+
+    def _munp(self, n, c, d):
+        def __munp(n, c, d):
+            nc = 1. * n / c
+            return d * sc.beta(1.0 - nc, d + nc)
+        n, c, d = np.asarray(n), np.asarray(c), np.asarray(d)
+        return _lazywhere((c > n) & (n == n) & (d == d), (c, d, n),
+                          lambda c, d, n: __munp(n, c, d),
+                          np.nan)
+
+
+burr = burr_gen(a=0.0, name='burr')
+
+
+class burr12_gen(rv_continuous):
+    r"""A Burr (Type XII) continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    fisk : a special case of either `burr` or `burr12` with ``d=1``
+    burr : Burr Type III distribution
+
+    Notes
+    -----
+    The probability density function for `burr12` is:
+
+    .. math::
+
+        f(x; c, d) = c d \frac{x^{c-1}}
+                              {(1 + x^c)^{d + 1}}
+
+    for :math:`x >= 0` and :math:`c, d > 0`.
+
+    `burr12` takes ``c`` and ``d`` as shape parameters for :math:`c`
+    and :math:`d`.
+
+    This is the PDF corresponding to the twelfth CDF given in Burr's list;
+    specifically, it is equation (20) in Burr's paper [1]_.
+
+    %(after_notes)s
+
+    The Burr type 12 distribution is also sometimes referred to as
+    the Singh-Maddala distribution from NIST [2]_.
+
+    References
+    ----------
+    .. [1] Burr, I. W. "Cumulative frequency functions", Annals of
+       Mathematical Statistics, 13(2), pp 215-232 (1942).
+
+    .. [2] https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/b12pdf.htm
+
+    .. [3] "Burr distribution",
+       https://en.wikipedia.org/wiki/Burr_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        id = _ShapeInfo("d", False, (0, np.inf), (False, False))
+        return [ic, id]
+
+    def _pdf(self, x, c, d):
+        # burr12.pdf(x, c, d) = c * d * x**(c-1) * (1+x**(c))**(-d-1)
+        return np.exp(self._logpdf(x, c, d))
+
+    def _logpdf(self, x, c, d):
+        return np.log(c) + np.log(d) + sc.xlogy(c - 1, x) + sc.xlog1py(-d-1, x**c)
+
+    def _cdf(self, x, c, d):
+        return -sc.expm1(self._logsf(x, c, d))
+
+    def _logcdf(self, x, c, d):
+        return sc.log1p(-(1 + x**c)**(-d))
+
+    def _sf(self, x, c, d):
+        return np.exp(self._logsf(x, c, d))
+
+    def _logsf(self, x, c, d):
+        return sc.xlog1py(-d, x**c)
+
+    def _ppf(self, q, c, d):
+        # The following is an implementation of
+        #   ((1 - q)**(-1.0/d) - 1)**(1.0/c)
+        # that does a better job handling small values of q.
+        return sc.expm1(-1/d * sc.log1p(-q))**(1/c)
+
+    def _isf(self, p, c, d):
+        return sc.expm1(-1/d * np.log(p))**(1/c)
+
+    def _munp(self, n, c, d):
+        def moment_if_exists(n, c, d):
+            nc = 1. * n / c
+            return d * sc.beta(1.0 + nc, d - nc)
+
+        return _lazywhere(c * d > n, (n, c, d), moment_if_exists,
+                          fillvalue=np.nan)
+
+
+burr12 = burr12_gen(a=0.0, name='burr12')
+
+
+class fisk_gen(burr_gen):
+    r"""A Fisk continuous random variable.
+
+    The Fisk distribution is also known as the log-logistic distribution.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    burr
+
+    Notes
+    -----
+    The probability density function for `fisk` is:
+
+    .. math::
+
+        f(x, c) = \frac{c x^{c-1}}
+                       {(1 + x^c)^2}
+
+    for :math:`x >= 0` and :math:`c > 0`.
+
+    Please note that the above expression can be transformed into the following
+    one, which is also commonly used:
+
+    .. math::
+
+        f(x, c) = \frac{c x^{-c-1}}
+                       {(1 + x^{-c})^2}
+
+    `fisk` takes ``c`` as a shape parameter for :math:`c`.
+
+    `fisk` is a special case of `burr` or `burr12` with ``d=1``.
+
+    Suppose ``X`` is a logistic random variable with location ``l``
+    and scale ``s``. Then ``Y = exp(X)`` is a Fisk (log-logistic)
+    random variable with ``scale = exp(l)`` and shape ``c = 1/s``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # fisk.pdf(x, c) = c * x**(-c-1) * (1 + x**(-c))**(-2)
+        return burr._pdf(x, c, 1.0)
+
+    def _cdf(self, x, c):
+        return burr._cdf(x, c, 1.0)
+
+    def _sf(self, x, c):
+        return burr._sf(x, c, 1.0)
+
+    def _logpdf(self, x, c):
+        # fisk.pdf(x, c) = c * x**(-c-1) * (1 + x**(-c))**(-2)
+        return burr._logpdf(x, c, 1.0)
+
+    def _logcdf(self, x, c):
+        return burr._logcdf(x, c, 1.0)
+
+    def _logsf(self, x, c):
+        return burr._logsf(x, c, 1.0)
+
+    def _ppf(self, x, c):
+        return burr._ppf(x, c, 1.0)
+
+    def _isf(self, q, c):
+        return burr._isf(q, c, 1.0)
+
+    def _munp(self, n, c):
+        return burr._munp(n, c, 1.0)
+
+    def _stats(self, c):
+        return burr._stats(c, 1.0)
+
+    def _entropy(self, c):
+        return 2 - np.log(c)
+
+
+fisk = fisk_gen(a=0.0, name='fisk')
+
+
+class cauchy_gen(rv_continuous):
+    r"""A Cauchy continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `cauchy` is
+
+    .. math::
+
+        f(x) = \frac{1}{\pi (1 + x^2)}
+
+    for a real number :math:`x`.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``ppf` and ``isf`` methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # cauchy.pdf(x) = 1 / (pi * (1 + x**2))
+        with np.errstate(over='ignore'):
+            return 1.0/np.pi/(1.0+x*x)
+
+    def _logpdf(self, x):
+        # The formulas
+        #     log(1/(pi*(1 + x**2))) = -log(pi) - log(1 + x**2)
+        #                            = -log(pi) - log(x**2*(1 + 1/x**2))
+        #                            = -log(pi) - (2log(|x|) + log1p(1/x**2))
+        # are used here.
+        absx = np.abs(x)
+        # In the following _lazywhere, `f` provides better precision than `f2`
+        # for small and moderate x, while `f2` avoids the overflow that can
+        # occur with absx**2.
+        y = _lazywhere(absx < 1, (absx,),
+                       f=lambda absx: -_LOG_PI - np.log1p(absx**2),
+                       f2=lambda absx: (-_LOG_PI -
+                                        (2*np.log(absx) + np.log1p((1/absx)**2))))
+        return y
+
+    def _cdf(self, x):
+        return np.arctan2(1, -x)/np.pi
+
+    def _ppf(self, q):
+        return scu._cauchy_ppf(q, 0, 1)
+
+    def _sf(self, x):
+        return np.arctan2(1, x)/np.pi
+
+    def _isf(self, q):
+        return scu._cauchy_isf(q, 0, 1)
+
+    def _stats(self):
+        return np.nan, np.nan, np.nan, np.nan
+
+    def _entropy(self):
+        return np.log(4*np.pi)
+
+    def _fitstart(self, data, args=None):
+        # Initialize ML guesses using quartiles instead of moments.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        p25, p50, p75 = np.percentile(data, [25, 50, 75])
+        return p50, (p75 - p25)/2
+
+
+cauchy = cauchy_gen(name='cauchy')
+
+
+class chi_gen(rv_continuous):
+    r"""A chi continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `chi` is:
+
+    .. math::
+
+        f(x, k) = \frac{1}{2^{k/2-1} \Gamma \left( k/2 \right)}
+                   x^{k-1} \exp \left( -x^2/2 \right)
+
+    for :math:`x >= 0` and :math:`k > 0` (degrees of freedom, denoted ``df``
+    in the implementation). :math:`\Gamma` is the gamma function
+    (`scipy.special.gamma`).
+
+    Special cases of `chi` are:
+
+        - ``chi(1, loc, scale)`` is equivalent to `halfnorm`
+        - ``chi(2, 0, scale)`` is equivalent to `rayleigh`
+        - ``chi(3, 0, scale)`` is equivalent to `maxwell`
+
+    `chi` takes ``df`` as a shape parameter.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("df", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, df, size=None, random_state=None):
+        return np.sqrt(chi2.rvs(df, size=size, random_state=random_state))
+
+    def _pdf(self, x, df):
+        #                   x**(df-1) * exp(-x**2/2)
+        # chi.pdf(x, df) =  -------------------------
+        #                   2**(df/2-1) * gamma(df/2)
+        return np.exp(self._logpdf(x, df))
+
+    def _logpdf(self, x, df):
+        l = np.log(2) - .5*np.log(2)*df - sc.gammaln(.5*df)
+        return l + sc.xlogy(df - 1., x) - .5*x**2
+
+    def _cdf(self, x, df):
+        return sc.gammainc(.5*df, .5*x**2)
+
+    def _sf(self, x, df):
+        return sc.gammaincc(.5*df, .5*x**2)
+
+    def _ppf(self, q, df):
+        return np.sqrt(2*sc.gammaincinv(.5*df, q))
+
+    def _isf(self, q, df):
+        return np.sqrt(2*sc.gammainccinv(.5*df, q))
+
+    def _stats(self, df):
+        # poch(df/2, 1/2) = gamma(df/2 + 1/2) / gamma(df/2)
+        mu = np.sqrt(2) * sc.poch(0.5 * df, 0.5)
+        mu2 = df - mu*mu
+        g1 = (2*mu**3.0 + mu*(1-2*df))/np.asarray(np.power(mu2, 1.5))
+        g2 = 2*df*(1.0-df)-6*mu**4 + 4*mu**2 * (2*df-1)
+        g2 /= np.asarray(mu2**2.0)
+        return mu, mu2, g1, g2
+
+    def _entropy(self, df):
+
+        def regular_formula(df):
+            return (sc.gammaln(.5 * df)
+                    + 0.5 * (df - np.log(2) - (df - 1) * sc.digamma(0.5 * df)))
+
+        def asymptotic_formula(df):
+            return (0.5 + np.log(np.pi)/2 - (df**-1)/6 - (df**-2)/6
+                    - 4/45*(df**-3) + (df**-4)/15)
+
+        return _lazywhere(df < 3e2, (df, ), regular_formula,
+                          f2=asymptotic_formula)
+
+
+chi = chi_gen(a=0.0, name='chi')
+
+
+class chi2_gen(rv_continuous):
+    r"""A chi-squared continuous random variable.
+
+    For the noncentral chi-square distribution, see `ncx2`.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    ncx2
+
+    Notes
+    -----
+    The probability density function for `chi2` is:
+
+    .. math::
+
+        f(x, k) = \frac{1}{2^{k/2} \Gamma \left( k/2 \right)}
+                   x^{k/2-1} \exp \left( -x/2 \right)
+
+    for :math:`x > 0`  and :math:`k > 0` (degrees of freedom, denoted ``df``
+    in the implementation).
+
+    `chi2` takes ``df`` as a shape parameter.
+
+    The chi-squared distribution is a special case of the gamma
+    distribution, with gamma parameters ``a = df/2``, ``loc = 0`` and
+    ``scale = 2``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("df", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, df, size=None, random_state=None):
+        return random_state.chisquare(df, size)
+
+    def _pdf(self, x, df):
+        # chi2.pdf(x, df) = 1 / (2*gamma(df/2)) * (x/2)**(df/2-1) * exp(-x/2)
+        return np.exp(self._logpdf(x, df))
+
+    def _logpdf(self, x, df):
+        return sc.xlogy(df/2.-1, x) - x/2. - sc.gammaln(df/2.) - (np.log(2)*df)/2.
+
+    def _cdf(self, x, df):
+        return sc.chdtr(df, x)
+
+    def _sf(self, x, df):
+        return sc.chdtrc(df, x)
+
+    def _isf(self, p, df):
+        return sc.chdtri(df, p)
+
+    def _ppf(self, p, df):
+        return 2*sc.gammaincinv(df/2, p)
+
+    def _stats(self, df):
+        mu = df
+        mu2 = 2*df
+        g1 = 2*np.sqrt(2.0/df)
+        g2 = 12.0/df
+        return mu, mu2, g1, g2
+
+    def _entropy(self, df):
+        half_df = 0.5 * df
+
+        def regular_formula(half_df):
+            return (half_df + np.log(2) + sc.gammaln(half_df) +
+                    (1 - half_df) * sc.psi(half_df))
+
+        def asymptotic_formula(half_df):
+            # plug in the above formula the following asymptotic
+            # expansions:
+            # ln(gamma(a)) ~ (a - 0.5) * ln(a) - a + 0.5 * ln(2 * pi) +
+            #                 1/(12 * a) - 1/(360 * a**3)
+            # psi(a) ~ ln(a) - 1/(2 * a) - 1/(3 * a**2) + 1/120 * a**4)
+            c = np.log(2) + 0.5*(1 + np.log(2*np.pi))
+            h = 0.5/half_df
+            return (h*(-2/3 + h*(-1/3 + h*(-4/45 + h/7.5))) +
+                    0.5*np.log(half_df) + c)
+
+        return _lazywhere(half_df < 125, (half_df, ),
+                          regular_formula,
+                          f2=asymptotic_formula)
+
+
+chi2 = chi2_gen(a=0.0, name='chi2')
+
+
+class cosine_gen(rv_continuous):
+    r"""A cosine continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The cosine distribution is an approximation to the normal distribution.
+    The probability density function for `cosine` is:
+
+    .. math::
+
+        f(x) = \frac{1}{2\pi} (1+\cos(x))
+
+    for :math:`-\pi \le x \le \pi`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # cosine.pdf(x) = 1/(2*pi) * (1+cos(x))
+        return 1.0/2/np.pi*(1+np.cos(x))
+
+    def _logpdf(self, x):
+        c = np.cos(x)
+        return _lazywhere(c != -1, (c,),
+                          lambda c: np.log1p(c) - np.log(2*np.pi),
+                          fillvalue=-np.inf)
+
+    def _cdf(self, x):
+        return scu._cosine_cdf(x)
+
+    def _sf(self, x):
+        return scu._cosine_cdf(-x)
+
+    def _ppf(self, p):
+        return scu._cosine_invcdf(p)
+
+    def _isf(self, p):
+        return -scu._cosine_invcdf(p)
+
+    def _stats(self):
+        v = (np.pi * np.pi / 3.0) - 2.0
+        k = -6.0 * (np.pi**4 - 90) / (5.0 * (np.pi * np.pi - 6)**2)
+        return 0.0, v, 0.0, k
+
+    def _entropy(self):
+        return np.log(4*np.pi)-1.0
+
+
+cosine = cosine_gen(a=-np.pi, b=np.pi, name='cosine')
+
+
+class dgamma_gen(rv_continuous):
+    r"""A double gamma continuous random variable.
+
+    The double gamma distribution is also known as the reflected gamma
+    distribution [1]_.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `dgamma` is:
+
+    .. math::
+
+        f(x, a) = \frac{1}{2\Gamma(a)} |x|^{a-1} \exp(-|x|)
+
+    for a real number :math:`x` and :math:`a > 0`. :math:`\Gamma` is the
+    gamma function (`scipy.special.gamma`).
+
+    `dgamma` takes ``a`` as a shape parameter for :math:`a`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Johnson, Kotz, and Balakrishnan, "Continuous Univariate
+           Distributions, Volume 1", Second Edition, John Wiley and Sons
+           (1994).
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, a, size=None, random_state=None):
+        u = random_state.uniform(size=size)
+        gm = gamma.rvs(a, size=size, random_state=random_state)
+        return gm * np.where(u >= 0.5, 1, -1)
+
+    def _pdf(self, x, a):
+        # dgamma.pdf(x, a) = 1 / (2*gamma(a)) * abs(x)**(a-1) * exp(-abs(x))
+        ax = abs(x)
+        return 1.0/(2*sc.gamma(a))*ax**(a-1.0) * np.exp(-ax)
+
+    def _logpdf(self, x, a):
+        ax = abs(x)
+        return sc.xlogy(a - 1.0, ax) - ax - np.log(2) - sc.gammaln(a)
+
+    def _cdf(self, x, a):
+        return np.where(x > 0,
+                        0.5 + 0.5*sc.gammainc(a, x),
+                        0.5*sc.gammaincc(a, -x))
+
+    def _sf(self, x, a):
+        return np.where(x > 0,
+                        0.5*sc.gammaincc(a, x),
+                        0.5 + 0.5*sc.gammainc(a, -x))
+
+    def _entropy(self, a):
+        return stats.gamma._entropy(a) - np.log(0.5)
+
+    def _ppf(self, q, a):
+        return np.where(q > 0.5,
+                        sc.gammaincinv(a, 2*q - 1),
+                        -sc.gammainccinv(a, 2*q))
+
+    def _isf(self, q, a):
+        return np.where(q > 0.5,
+                        -sc.gammaincinv(a, 2*q - 1),
+                        sc.gammainccinv(a, 2*q))
+
+    def _stats(self, a):
+        mu2 = a*(a+1.0)
+        return 0.0, mu2, 0.0, (a+2.0)*(a+3.0)/mu2-3.0
+
+
+dgamma = dgamma_gen(name='dgamma')
+
+
+class dpareto_lognorm_gen(rv_continuous):
+    r"""A double Pareto lognormal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `dpareto_lognorm` is:
+
+    .. math::
+
+        f(x, \mu, \sigma, \alpha, \beta) =
+        \frac{\alpha \beta}{(\alpha + \beta) x}
+        \phi\left( \frac{\log x - \mu}{\sigma} \right)
+        \left( R(y_1) + R(y_2) \right)
+
+    where :math:`R(t) = \frac{1 - \Phi(t)}{\phi(t)}`,
+    :math:`\phi` and :math:`\Phi` are the normal PDF and CDF, respectively,
+    :math:`y_1 = \alpha \sigma - \frac{\log x - \mu}{\sigma}`,
+    and :math:`y_2 = \beta \sigma + \frac{\log x - \mu}{\sigma}`
+    for real numbers :math:`x` and :math:`\mu`, :math:`\sigma > 0`,
+    :math:`\alpha > 0`, and :math:`\beta > 0` [1]_.
+
+    `dpareto_lognorm` takes
+    ``u`` as a shape parameter for :math:`\mu`,
+    ``s`` as a shape parameter for :math:`\sigma`,
+    ``a`` as a shape parameter for :math:`\alpha`, and
+    ``b`` as a shape parameter for :math:`\beta`.
+
+    A random variable :math:`X` distributed according to the PDF above
+    can be represented as :math:`X = U \frac{V_1}{V_2}` where :math:`U`,
+    :math:`V_1`, and :math:`V_2` are independent, :math:`U` is lognormally
+    distributed such that :math:`\log U \sim N(\mu, \sigma^2)`, and
+    :math:`V_1` and :math:`V_2` follow Pareto distributions with parameters
+    :math:`\alpha` and :math:`\beta`, respectively [2]_.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Hajargasht, Gholamreza, and William E. Griffiths. "Pareto-lognormal
+           distributions: Inequality, poverty, and estimation from grouped income
+           data." Economic Modelling 33 (2013): 593-604.
+    .. [2] Reed, William J., and Murray Jorgensen. "The double Pareto-lognormal
+           distribution - a new parametric model for size distributions."
+           Communications in Statistics - Theory and Methods 33.8 (2004): 1733-1753.
+
+    %(example)s
+
+    """
+    _logphi = norm._logpdf
+    _logPhi = norm._logcdf
+    _logPhic = norm._logsf
+    _phi = norm._pdf
+    _Phi = norm._cdf
+    _Phic = norm._sf
+
+    def _R(self, z):
+        return self._Phic(z) / self._phi(z)
+
+    def _logR(self, z):
+        return self._logPhic(z) - self._logphi(z)
+
+    def _shape_info(self):
+        return [_ShapeInfo("u", False, (-np.inf, np.inf), (False, False)),
+                _ShapeInfo("s", False, (0, np.inf), (False, False)),
+                _ShapeInfo("a", False, (0, np.inf), (False, False)),
+                _ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _argcheck(self, u, s, a, b):
+        return (s > 0) & (a > 0) & (b > 0)
+
+    def _rvs(self, u, s, a, b, size=None, random_state=None):
+        # From [1] after Equation (12): "To generate pseudo-random
+        # deviates from the dPlN distribution, one can exponentiate
+        # pseudo-random deviates from NL generated using (6)."
+        Z = random_state.normal(u, s, size=size)
+        E1 = random_state.standard_exponential(size=size)
+        E2 = random_state.standard_exponential(size=size)
+        return np.exp(Z + E1 / a - E2 / b)
+
+    def _logpdf(self, x, u, s, a, b):
+        with np.errstate(invalid='ignore', divide='ignore'):
+            log_y, m = np.log(x), u  # compare against [1] Eq. 1
+            z = (log_y - m) / s
+            x1 = a * s - z
+            x2 = b * s + z
+            out = np.asarray(np.log(a) + np.log(b) - np.log(a + b) - log_y)
+            out += self._logphi(z)
+            out += np.logaddexp(self._logR(x1), self._logR(x2))
+        out[(x == 0) | np.isinf(x)] = -np.inf
+        return out[()]
+
+    def _logcdf(self, x, u, s, a, b):
+        with np.errstate(invalid='ignore', divide='ignore'):
+            log_y, m = np.log(x), u  # compare against [1] Eq. 2
+            z = (log_y - m) / s
+            x1 = a * s - z
+            x2 = b * s + z
+            t1 = self._logPhi(z)
+            t2 = self._logphi(z)
+            t3 = (np.log(b) + self._logR(x1))
+            t4 = (np.log(a) + self._logR(x2))
+            t1, t2, t3, t4, one = np.broadcast_arrays(t1, t2, t3, t4, 1)
+            # t3 can be smaller than t4, so we have to consider log of negative number
+            # This would be much simpler, but `return_sign` is available, so use it?
+            # t5 =  sc.logsumexp([t3, t4 + np.pi*1j])
+            t5, sign =  sc.logsumexp([t3, t4], b=[one, -one], axis=0, return_sign=True)
+            temp = [t1, t2 + t5 - np.log(a + b)]
+            out = np.asarray(sc.logsumexp(temp, b=[one, -one*sign], axis=0))
+        out[x == 0] = -np.inf
+        return out[()]
+
+    def _logsf(self, x, u, s, a, b):
+        return _log1mexp(self._logcdf(x, u, s, a, b))
+
+    # Infrastructure doesn't seem to do this, so...
+
+    def _pdf(self, x, u, s, a, b):
+        return np.exp(self._logpdf(x, u, s, a, b))
+
+    def _cdf(self, x, u, s, a, b):
+        return np.exp(self._logcdf(x, u, s, a, b))
+
+    def _sf(self, x, u, s, a, b):
+        return np.exp(self._logsf(x, u, s, a, b))
+
+    def _munp(self, n, u, s, a, b):
+        m, k = u, float(n)  # compare against [1] Eq. 6
+        out = (a * b) / ((a - k) * (b + k)) * np.exp(k * m + k ** 2 * s ** 2 / 2)
+        out = np.asarray(out)
+        out[a <= k] = np.nan
+        return out
+
+
+dpareto_lognorm = dpareto_lognorm_gen(a=0, name='dpareto_lognorm')
+
+
+class dweibull_gen(rv_continuous):
+    r"""A double Weibull continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `dweibull` is given by
+
+    .. math::
+
+        f(x, c) = c / 2 |x|^{c-1} \exp(-|x|^c)
+
+    for a real number :math:`x` and :math:`c > 0`.
+
+    `dweibull` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        u = random_state.uniform(size=size)
+        w = weibull_min.rvs(c, size=size, random_state=random_state)
+        return w * (np.where(u >= 0.5, 1, -1))
+
+    def _pdf(self, x, c):
+        # dweibull.pdf(x, c) = c / 2 * abs(x)**(c-1) * exp(-abs(x)**c)
+        ax = abs(x)
+        Px = c / 2.0 * ax**(c-1.0) * np.exp(-ax**c)
+        return Px
+
+    def _logpdf(self, x, c):
+        ax = abs(x)
+        return np.log(c) - np.log(2.0) + sc.xlogy(c - 1.0, ax) - ax**c
+
+    def _cdf(self, x, c):
+        Cx1 = 0.5 * np.exp(-abs(x)**c)
+        return np.where(x > 0, 1 - Cx1, Cx1)
+
+    def _ppf(self, q, c):
+        fac = 2. * np.where(q <= 0.5, q, 1. - q)
+        fac = np.power(-np.log(fac), 1.0 / c)
+        return np.where(q > 0.5, fac, -fac)
+
+    def _sf(self, x, c):
+        half_weibull_min_sf = 0.5 * stats.weibull_min._sf(np.abs(x), c)
+        return np.where(x > 0, half_weibull_min_sf, 1 - half_weibull_min_sf)
+
+    def _isf(self, q, c):
+        double_q = 2. * np.where(q <= 0.5, q, 1. - q)
+        weibull_min_isf = stats.weibull_min._isf(double_q, c)
+        return np.where(q > 0.5, -weibull_min_isf, weibull_min_isf)
+
+    def _munp(self, n, c):
+        return (1 - (n % 2)) * sc.gamma(1.0 + 1.0 * n / c)
+
+    # since we know that all odd moments are zeros, return them at once.
+    # returning Nones from _stats makes the public stats call _munp
+    # so overall we're saving one or two gamma function evaluations here.
+    def _stats(self, c):
+        return 0, None, 0, None
+
+    def _entropy(self, c):
+        h = stats.weibull_min._entropy(c) - np.log(0.5)
+        return h
+
+
+dweibull = dweibull_gen(name='dweibull')
+
+
+class expon_gen(rv_continuous):
+    r"""An exponential continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `expon` is:
+
+    .. math::
+
+        f(x) = \exp(-x)
+
+    for :math:`x \ge 0`.
+
+    %(after_notes)s
+
+    A common parameterization for `expon` is in terms of the rate parameter
+    ``lambda``, such that ``pdf = lambda * exp(-lambda * x)``. This
+    parameterization corresponds to using ``scale = 1 / lambda``.
+
+    The exponential distribution is a special case of the gamma
+    distributions, with gamma shape parameter ``a = 1``.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.standard_exponential(size)
+
+    def _pdf(self, x):
+        # expon.pdf(x) = exp(-x)
+        return np.exp(-x)
+
+    def _logpdf(self, x):
+        return -x
+
+    def _cdf(self, x):
+        return -sc.expm1(-x)
+
+    def _ppf(self, q):
+        return -sc.log1p(-q)
+
+    def _sf(self, x):
+        return np.exp(-x)
+
+    def _logsf(self, x):
+        return -x
+
+    def _isf(self, q):
+        return -np.log(q)
+
+    def _stats(self):
+        return 1.0, 1.0, 2.0, 6.0
+
+    def _entropy(self):
+        return 1.0
+
+    @_call_super_mom
+    @replace_notes_in_docstring(rv_continuous, notes="""\
+        When `method='MLE'`,
+        this function uses explicit formulas for the maximum likelihood
+        estimation of the exponential distribution parameters, so the
+        `optimizer`, `loc` and `scale` keyword arguments are
+        ignored.\n\n""")
+    def fit(self, data, *args, **kwds):
+        if len(args) > 0:
+            raise TypeError("Too many arguments.")
+
+        floc = kwds.pop('floc', None)
+        fscale = kwds.pop('fscale', None)
+
+        _remove_optimizer_parameters(kwds)
+
+        if floc is not None and fscale is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        data = np.asarray(data)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        data_min = data.min()
+
+        if floc is None:
+            # ML estimate of the location is the minimum of the data.
+            loc = data_min
+        else:
+            loc = floc
+            if data_min < loc:
+                # There are values that are less than the specified loc.
+                raise FitDataError("expon", lower=floc, upper=np.inf)
+
+        if fscale is None:
+            # ML estimate of the scale is the shifted mean.
+            scale = data.mean() - loc
+        else:
+            scale = fscale
+
+        # We expect the return values to be floating point, so ensure it
+        # by explicitly converting to float.
+        return float(loc), float(scale)
+
+
+expon = expon_gen(a=0.0, name='expon')
+
+
+class exponnorm_gen(rv_continuous):
+    r"""An exponentially modified Normal continuous random variable.
+
+    Also known as the exponentially modified Gaussian distribution [1]_.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `exponnorm` is:
+
+    .. math::
+
+        f(x, K) = \frac{1}{2K} \exp\left(\frac{1}{2 K^2} - x / K \right)
+                  \text{erfc}\left(-\frac{x - 1/K}{\sqrt{2}}\right)
+
+    where :math:`x` is a real number and :math:`K > 0`.
+
+    It can be thought of as the sum of a standard normal random variable
+    and an independent exponentially distributed random variable with rate
+    ``1/K``.
+
+    %(after_notes)s
+
+    An alternative parameterization of this distribution (for example, in
+    the Wikipedia article [1]_) involves three parameters, :math:`\mu`,
+    :math:`\lambda` and :math:`\sigma`.
+
+    In the present parameterization this corresponds to having ``loc`` and
+    ``scale`` equal to :math:`\mu` and :math:`\sigma`, respectively, and
+    shape parameter :math:`K = 1/(\sigma\lambda)`.
+
+    .. versionadded:: 0.16.0
+
+    References
+    ----------
+    .. [1] Exponentially modified Gaussian distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("K", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, K, size=None, random_state=None):
+        expval = random_state.standard_exponential(size) * K
+        gval = random_state.standard_normal(size)
+        return expval + gval
+
+    def _pdf(self, x, K):
+        return np.exp(self._logpdf(x, K))
+
+    def _logpdf(self, x, K):
+        invK = 1.0 / K
+        exparg = invK * (0.5 * invK - x)
+        return exparg + _norm_logcdf(x - invK) - np.log(K)
+
+    def _cdf(self, x, K):
+        invK = 1.0 / K
+        expval = invK * (0.5 * invK - x)
+        logprod = expval + _norm_logcdf(x - invK)
+        return _norm_cdf(x) - np.exp(logprod)
+
+    def _sf(self, x, K):
+        invK = 1.0 / K
+        expval = invK * (0.5 * invK - x)
+        logprod = expval + _norm_logcdf(x - invK)
+        return _norm_cdf(-x) + np.exp(logprod)
+
+    def _stats(self, K):
+        K2 = K * K
+        opK2 = 1.0 + K2
+        skw = 2 * K**3 * opK2**(-1.5)
+        krt = 6.0 * K2 * K2 * opK2**(-2)
+        return K, opK2, skw, krt
+
+
+exponnorm = exponnorm_gen(name='exponnorm')
+
+
+def _pow1pm1(x, y):
+    """
+    Compute (1 + x)**y - 1.
+
+    Uses expm1 and xlog1py to avoid loss of precision when
+    (1 + x)**y is close to 1.
+
+    Note that the inverse of this function with respect to x is
+    ``_pow1pm1(x, 1/y)``.  That is, if
+
+        t = _pow1pm1(x, y)
+
+    then
+
+        x = _pow1pm1(t, 1/y)
+    """
+    return np.expm1(sc.xlog1py(y, x))
+
+
+class exponweib_gen(rv_continuous):
+    r"""An exponentiated Weibull continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    weibull_min, numpy.random.Generator.weibull
+
+    Notes
+    -----
+    The probability density function for `exponweib` is:
+
+    .. math::
+
+        f(x, a, c) = a c [1-\exp(-x^c)]^{a-1} \exp(-x^c) x^{c-1}
+
+    and its cumulative distribution function is:
+
+    .. math::
+
+        F(x, a, c) = [1-\exp(-x^c)]^a
+
+    for :math:`x > 0`, :math:`a > 0`, :math:`c > 0`.
+
+    `exponweib` takes :math:`a` and :math:`c` as shape parameters:
+
+    * :math:`a` is the exponentiation parameter,
+      with the special case :math:`a=1` corresponding to the
+      (non-exponentiated) Weibull distribution `weibull_min`.
+    * :math:`c` is the shape parameter of the non-exponentiated Weibull law.
+
+    %(after_notes)s
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/Exponentiated_Weibull_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        return [ia, ic]
+
+    def _pdf(self, x, a, c):
+        # exponweib.pdf(x, a, c) =
+        #     a * c * (1-exp(-x**c))**(a-1) * exp(-x**c)*x**(c-1)
+        return np.exp(self._logpdf(x, a, c))
+
+    def _logpdf(self, x, a, c):
+        negxc = -x**c
+        exm1c = -sc.expm1(negxc)
+        logp = (np.log(a) + np.log(c) + sc.xlogy(a - 1.0, exm1c) +
+                negxc + sc.xlogy(c - 1.0, x))
+        return logp
+
+    def _cdf(self, x, a, c):
+        exm1c = -sc.expm1(-x**c)
+        return exm1c**a
+
+    def _ppf(self, q, a, c):
+        return (-sc.log1p(-q**(1.0/a)))**np.asarray(1.0/c)
+
+    def _sf(self, x, a, c):
+        return -_pow1pm1(-np.exp(-x**c), a)
+
+    def _isf(self, p, a, c):
+        return (-np.log(-_pow1pm1(-p, 1/a)))**(1/c)
+
+
+exponweib = exponweib_gen(a=0.0, name='exponweib')
+
+
+class exponpow_gen(rv_continuous):
+    r"""An exponential power continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `exponpow` is:
+
+    .. math::
+
+        f(x, b) = b x^{b-1} \exp(1 + x^b - \exp(x^b))
+
+    for :math:`x \ge 0`, :math:`b > 0`.  Note that this is a different
+    distribution from the exponential power distribution that is also known
+    under the names "generalized normal" or "generalized Gaussian".
+
+    `exponpow` takes ``b`` as a shape parameter for :math:`b`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Exponentialpower.pdf
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, b):
+        # exponpow.pdf(x, b) = b * x**(b-1) * exp(1 + x**b - exp(x**b))
+        return np.exp(self._logpdf(x, b))
+
+    def _logpdf(self, x, b):
+        xb = x**b
+        f = 1 + np.log(b) + sc.xlogy(b - 1.0, x) + xb - np.exp(xb)
+        return f
+
+    def _cdf(self, x, b):
+        return -sc.expm1(-sc.expm1(x**b))
+
+    def _sf(self, x, b):
+        return np.exp(-sc.expm1(x**b))
+
+    def _isf(self, x, b):
+        return (sc.log1p(-np.log(x)))**(1./b)
+
+    def _ppf(self, q, b):
+        return pow(sc.log1p(-sc.log1p(-q)), 1.0/b)
+
+
+exponpow = exponpow_gen(a=0.0, name='exponpow')
+
+
+class fatiguelife_gen(rv_continuous):
+    r"""A fatigue-life (Birnbaum-Saunders) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `fatiguelife` is:
+
+    .. math::
+
+        f(x, c) = \frac{x+1}{2c\sqrt{2\pi x^3}} \exp(-\frac{(x-1)^2}{2x c^2})
+
+    for :math:`x >= 0` and :math:`c > 0`.
+
+    `fatiguelife` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Birnbaum-Saunders distribution",
+           https://en.wikipedia.org/wiki/Birnbaum-Saunders_distribution
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        z = random_state.standard_normal(size)
+        x = 0.5*c*z
+        x2 = x*x
+        t = 1.0 + 2*x2 + 2*x*np.sqrt(1 + x2)
+        return t
+
+    def _pdf(self, x, c):
+        # fatiguelife.pdf(x, c) =
+        #     (x+1) / (2*c*sqrt(2*pi*x**3)) * exp(-(x-1)**2/(2*x*c**2))
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        return (np.log(x+1) - (x-1)**2 / (2.0*x*c**2) - np.log(2*c) -
+                0.5*(np.log(2*np.pi) + 3*np.log(x)))
+
+    def _cdf(self, x, c):
+        return _norm_cdf(1.0 / c * (np.sqrt(x) - 1.0/np.sqrt(x)))
+
+    def _ppf(self, q, c):
+        tmp = c * _norm_ppf(q)
+        return 0.25 * (tmp + np.sqrt(tmp**2 + 4))**2
+
+    def _sf(self, x, c):
+        return _norm_sf(1.0 / c * (np.sqrt(x) - 1.0/np.sqrt(x)))
+
+    def _isf(self, q, c):
+        tmp = -c * _norm_ppf(q)
+        return 0.25 * (tmp + np.sqrt(tmp**2 + 4))**2
+
+    def _stats(self, c):
+        # NB: the formula for kurtosis in wikipedia seems to have an error:
+        # it's 40, not 41. At least it disagrees with the one from Wolfram
+        # Alpha.  And the latter one, below, passes the tests, while the wiki
+        # one doesn't So far I didn't have the guts to actually check the
+        # coefficients from the expressions for the raw moments.
+        c2 = c*c
+        mu = c2 / 2.0 + 1.0
+        den = 5.0 * c2 + 4.0
+        mu2 = c2*den / 4.0
+        g1 = 4 * c * (11*c2 + 6.0) / np.power(den, 1.5)
+        g2 = 6 * c2 * (93*c2 + 40.0) / den**2.0
+        return mu, mu2, g1, g2
+
+
+fatiguelife = fatiguelife_gen(a=0.0, name='fatiguelife')
+
+
+class foldcauchy_gen(rv_continuous):
+    r"""A folded Cauchy continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `foldcauchy` is:
+
+    .. math::
+
+        f(x, c) = \frac{1}{\pi (1+(x-c)^2)} + \frac{1}{\pi (1+(x+c)^2)}
+
+    for :math:`x \ge 0` and :math:`c \ge 0`.
+
+    `foldcauchy` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return c >= 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (True, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        return abs(cauchy.rvs(loc=c, size=size,
+                              random_state=random_state))
+
+    def _pdf(self, x, c):
+        # foldcauchy.pdf(x, c) = 1/(pi*(1+(x-c)**2)) + 1/(pi*(1+(x+c)**2))
+        return 1.0/np.pi*(1.0/(1+(x-c)**2) + 1.0/(1+(x+c)**2))
+
+    def _cdf(self, x, c):
+        return 1.0/np.pi*(np.arctan(x-c) + np.arctan(x+c))
+
+    def _sf(self, x, c):
+        # 1 - CDF(x, c) = 1 - (atan(x - c) + atan(x + c))/pi
+        #               = ((pi/2 - atan(x - c)) + (pi/2 - atan(x + c)))/pi
+        #               = (acot(x - c) + acot(x + c))/pi
+        #               = (atan2(1, x - c) + atan2(1, x + c))/pi
+        return (np.arctan2(1, x - c) + np.arctan2(1, x + c))/np.pi
+
+    def _stats(self, c):
+        return np.inf, np.inf, np.nan, np.nan
+
+
+foldcauchy = foldcauchy_gen(a=0.0, name='foldcauchy')
+
+
+class f_gen(rv_continuous):
+    r"""An F continuous random variable.
+
+    For the noncentral F distribution, see `ncf`.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    ncf
+
+    Notes
+    -----
+    The F distribution with :math:`df_1 > 0` and :math:`df_2 > 0` degrees of freedom is
+    the distribution of the ratio of two independent chi-squared distributions with
+    :math:`df_1` and :math:`df_2` degrees of freedom, after rescaling by
+    :math:`df_2 / df_1`.
+
+    The probability density function for `f` is:
+
+    .. math::
+
+        f(x, df_1, df_2) = \frac{df_2^{df_2/2} df_1^{df_1/2} x^{df_1 / 2-1}}
+                                {(df_2+df_1 x)^{(df_1+df_2)/2}
+                                 B(df_1/2, df_2/2)}
+
+    for :math:`x > 0`.
+
+    `f` accepts shape parameters ``dfn`` and ``dfd`` for :math:`df_1`, the degrees of
+    freedom of the chi-squared distribution in the numerator, and :math:`df_2`, the
+    degrees of freedom of the chi-squared distribution in the denominator, respectively.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        idfn = _ShapeInfo("dfn", False, (0, np.inf), (False, False))
+        idfd = _ShapeInfo("dfd", False, (0, np.inf), (False, False))
+        return [idfn, idfd]
+
+    def _rvs(self, dfn, dfd, size=None, random_state=None):
+        return random_state.f(dfn, dfd, size)
+
+    def _pdf(self, x, dfn, dfd):
+        #                      df2**(df2/2) * df1**(df1/2) * x**(df1/2-1)
+        # F.pdf(x, df1, df2) = --------------------------------------------
+        #                      (df2+df1*x)**((df1+df2)/2) * B(df1/2, df2/2)
+        return np.exp(self._logpdf(x, dfn, dfd))
+
+    def _logpdf(self, x, dfn, dfd):
+        n = 1.0 * dfn
+        m = 1.0 * dfd
+        lPx = (m/2 * np.log(m) + n/2 * np.log(n) + sc.xlogy(n/2 - 1, x)
+               - (((n+m)/2) * np.log(m + n*x) + sc.betaln(n/2, m/2)))
+        return lPx
+
+    def _cdf(self, x, dfn, dfd):
+        return sc.fdtr(dfn, dfd, x)
+
+    def _sf(self, x, dfn, dfd):
+        return sc.fdtrc(dfn, dfd, x)
+
+    def _ppf(self, q, dfn, dfd):
+        return sc.fdtri(dfn, dfd, q)
+
+    def _stats(self, dfn, dfd):
+        v1, v2 = 1. * dfn, 1. * dfd
+        v2_2, v2_4, v2_6, v2_8 = v2 - 2., v2 - 4., v2 - 6., v2 - 8.
+
+        mu = _lazywhere(
+            v2 > 2, (v2, v2_2),
+            lambda v2, v2_2: v2 / v2_2,
+            np.inf)
+
+        mu2 = _lazywhere(
+            v2 > 4, (v1, v2, v2_2, v2_4),
+            lambda v1, v2, v2_2, v2_4:
+            2 * v2 * v2 * (v1 + v2_2) / (v1 * v2_2**2 * v2_4),
+            np.inf)
+
+        g1 = _lazywhere(
+            v2 > 6, (v1, v2_2, v2_4, v2_6),
+            lambda v1, v2_2, v2_4, v2_6:
+            (2 * v1 + v2_2) / v2_6 * np.sqrt(v2_4 / (v1 * (v1 + v2_2))),
+            np.nan)
+        g1 *= np.sqrt(8.)
+
+        g2 = _lazywhere(
+            v2 > 8, (g1, v2_6, v2_8),
+            lambda g1, v2_6, v2_8: (8 + g1 * g1 * v2_6) / v2_8,
+            np.nan)
+        g2 *= 3. / 2.
+
+        return mu, mu2, g1, g2
+
+    def _entropy(self, dfn, dfd):
+        # the formula found in literature is incorrect. This one yields the
+        # same result as numerical integration using the generic entropy
+        # definition. This is also tested in tests/test_conntinous_basic
+        half_dfn = 0.5 * dfn
+        half_dfd = 0.5 * dfd
+        half_sum = 0.5 * (dfn + dfd)
+
+        return (np.log(dfd) - np.log(dfn) + sc.betaln(half_dfn, half_dfd) +
+                (1 - half_dfn) * sc.psi(half_dfn) - (1 + half_dfd) *
+                sc.psi(half_dfd) + half_sum * sc.psi(half_sum))
+
+
+f = f_gen(a=0.0, name='f')
+
+
+## Folded Normal
+##   abs(Z) where (Z is normal with mu=L and std=S so that c=abs(L)/S)
+##
+##  note: regress docs have scale parameter correct, but first parameter
+##    he gives is a shape parameter A = c * scale
+
+##  Half-normal is folded normal with shape-parameter c=0.
+
+class foldnorm_gen(rv_continuous):
+    r"""A folded normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `foldnorm` is:
+
+    .. math::
+
+        f(x, c) = \sqrt{2/\pi} cosh(c x) \exp(-\frac{x^2+c^2}{2})
+
+    for :math:`x \ge 0` and :math:`c \ge 0`.
+
+    `foldnorm` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return c >= 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (True, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        return abs(random_state.standard_normal(size) + c)
+
+    def _pdf(self, x, c):
+        # foldnormal.pdf(x, c) = sqrt(2/pi) * cosh(c*x) * exp(-(x**2+c**2)/2)
+        return _norm_pdf(x + c) + _norm_pdf(x-c)
+
+    def _cdf(self, x, c):
+        sqrt_two = np.sqrt(2)
+        return 0.5 * (sc.erf((x - c)/sqrt_two) + sc.erf((x + c)/sqrt_two))
+
+    def _sf(self, x, c):
+        return _norm_sf(x - c) + _norm_sf(x + c)
+
+    def _stats(self, c):
+        # Regina C. Elandt, Technometrics 3, 551 (1961)
+        # https://www.jstor.org/stable/1266561
+        #
+        c2 = c*c
+        expfac = np.exp(-0.5*c2) / np.sqrt(2.*np.pi)
+
+        mu = 2.*expfac + c * sc.erf(c/np.sqrt(2))
+        mu2 = c2 + 1 - mu*mu
+
+        g1 = 2. * (mu*mu*mu - c2*mu - expfac)
+        g1 /= np.power(mu2, 1.5)
+
+        g2 = c2 * (c2 + 6.) + 3 + 8.*expfac*mu
+        g2 += (2. * (c2 - 3.) - 3. * mu**2) * mu**2
+        g2 = g2 / mu2**2.0 - 3.
+
+        return mu, mu2, g1, g2
+
+
+foldnorm = foldnorm_gen(a=0.0, name='foldnorm')
+
+
+class weibull_min_gen(rv_continuous):
+    r"""Weibull minimum continuous random variable.
+
+    The Weibull Minimum Extreme Value distribution, from extreme value theory
+    (Fisher-Gnedenko theorem), is also often simply called the Weibull
+    distribution. It arises as the limiting distribution of the rescaled
+    minimum of iid random variables.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    weibull_max, numpy.random.Generator.weibull, exponweib
+
+    Notes
+    -----
+    The probability density function for `weibull_min` is:
+
+    .. math::
+
+        f(x, c) = c x^{c-1} \exp(-x^c)
+
+    for :math:`x > 0`, :math:`c > 0`.
+
+    `weibull_min` takes ``c`` as a shape parameter for :math:`c`.
+    (named :math:`k` in Wikipedia article and :math:`a` in
+    ``numpy.random.weibull``).  Special shape values are :math:`c=1` and
+    :math:`c=2` where Weibull distribution reduces to the `expon` and
+    `rayleigh` distributions respectively.
+
+    Suppose ``X`` is an exponentially distributed random variable with
+    scale ``s``. Then ``Y = X**k`` is `weibull_min` distributed with shape
+    ``c = 1/k`` and scale ``s**k``.
+
+    %(after_notes)s
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/Weibull_distribution
+
+    https://en.wikipedia.org/wiki/Fisher-Tippett-Gnedenko_theorem
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # weibull_min.pdf(x, c) = c * x**(c-1) * exp(-x**c)
+        return c*pow(x, c-1)*np.exp(-pow(x, c))
+
+    def _logpdf(self, x, c):
+        return np.log(c) + sc.xlogy(c - 1, x) - pow(x, c)
+
+    def _cdf(self, x, c):
+        return -sc.expm1(-pow(x, c))
+
+    def _ppf(self, q, c):
+        return pow(-sc.log1p(-q), 1.0/c)
+
+    def _sf(self, x, c):
+        return np.exp(self._logsf(x, c))
+
+    def _logsf(self, x, c):
+        return -pow(x, c)
+
+    def _isf(self, q, c):
+        return (-np.log(q))**(1/c)
+
+    def _munp(self, n, c):
+        return sc.gamma(1.0+n*1.0/c)
+
+    def _entropy(self, c):
+        return -_EULER / c - np.log(c) + _EULER + 1
+
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        If ``method='mm'``, parameters fixed by the user are respected, and the
+        remaining parameters are used to match distribution and sample moments
+        where possible. For example, if the user fixes the location with
+        ``floc``, the parameters will only match the distribution skewness and
+        variance to the sample skewness and variance; no attempt will be made
+        to match the means or minimize a norm of the errors.
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+
+        if isinstance(data, CensoredData):
+            if data.num_censored() == 0:
+                data = data._uncensor()
+            else:
+                return super().fit(data, *args, **kwds)
+
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        # this extracts fixed shape, location, and scale however they
+        # are specified, and also leaves them in `kwds`
+        data, fc, floc, fscale = _check_fit_input_parameters(self, data,
+                                                             args, kwds)
+        method = kwds.get("method", "mle").lower()
+
+        # See https://en.wikipedia.org/wiki/Weibull_distribution#Moments for
+        # moment formulas.
+        def skew(c):
+            gamma1 = sc.gamma(1+1/c)
+            gamma2 = sc.gamma(1+2/c)
+            gamma3 = sc.gamma(1+3/c)
+            num = 2 * gamma1**3 - 3*gamma1*gamma2 + gamma3
+            den = (gamma2 - gamma1**2)**(3/2)
+            return num/den
+
+        # For c in [1e2, 3e4], population skewness appears to approach
+        # asymptote near -1.139, but past c > 3e4, skewness begins to vary
+        # wildly, and MoM won't provide a good guess. Get out early.
+        s = stats.skew(data)
+        max_c = 1e4
+        s_min = skew(max_c)
+        if s < s_min and method != "mm" and fc is None and not args:
+            return super().fit(data, *args, **kwds)
+
+        # If method is method of moments, we don't need the user's guesses.
+        # Otherwise, extract the guesses from args and kwds.
+        if method == "mm":
+            c, loc, scale = None, None, None
+        else:
+            c = args[0] if len(args) else None
+            loc = kwds.pop('loc', None)
+            scale = kwds.pop('scale', None)
+
+        if fc is None and c is None:  # not fixed and no guess: use MoM
+            # Solve for c that matches sample distribution skewness to sample
+            # skewness.
+            # we start having numerical issues with `weibull_min` with
+            # parameters outside this range - and not just in this method.
+            # We could probably improve the situation by doing everything
+            # in the log space, but that is for another time.
+            c = root_scalar(lambda c: skew(c) - s, bracket=[0.02, max_c],
+                            method='bisect').root
+        elif fc is not None:  # fixed: use it
+            c = fc
+
+        if fscale is None and scale is None:
+            v = np.var(data)
+            scale = np.sqrt(v / (sc.gamma(1+2/c) - sc.gamma(1+1/c)**2))
+        elif fscale is not None:
+            scale = fscale
+
+        if floc is None and loc is None:
+            m = np.mean(data)
+            loc = m - scale*sc.gamma(1 + 1/c)
+        elif floc is not None:
+            loc = floc
+
+        if method == 'mm':
+            return c, loc, scale
+        else:
+            # At this point, parameter "guesses" may equal the fixed parameters
+            # in kwds. No harm in passing them as guesses, too.
+            return super().fit(data, c, loc=loc, scale=scale, **kwds)
+
+
+weibull_min = weibull_min_gen(a=0.0, name='weibull_min')
+
+
+class truncweibull_min_gen(rv_continuous):
+    r"""A doubly truncated Weibull minimum continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    weibull_min, truncexpon
+
+    Notes
+    -----
+    The probability density function for `truncweibull_min` is:
+
+    .. math::
+
+        f(x, a, b, c) = \frac{c x^{c-1} \exp(-x^c)}{\exp(-a^c) - \exp(-b^c)}
+
+    for :math:`a < x <= b`, :math:`0 \le a < b` and :math:`c > 0`.
+
+    `truncweibull_min` takes :math:`a`, :math:`b`, and :math:`c` as shape
+    parameters.
+
+    Notice that the truncation values, :math:`a` and :math:`b`, are defined in
+    standardized form:
+
+    .. math::
+
+        a = (u_l - loc)/scale
+        b = (u_r - loc)/scale
+
+    where :math:`u_l` and :math:`u_r` are the specific left and right
+    truncation values, respectively. In other words, the support of the
+    distribution becomes :math:`(a*scale + loc) < x <= (b*scale + loc)` when
+    :math:`loc` and/or :math:`scale` are provided.
+
+    %(after_notes)s
+
+    References
+    ----------
+
+    .. [1] Rinne, H. "The Weibull Distribution: A Handbook". CRC Press (2009).
+
+    %(example)s
+
+    """
+    def _argcheck(self, c, a, b):
+        return (a >= 0.) & (b > a) & (c > 0.)
+
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        ia = _ShapeInfo("a", False, (0, np.inf), (True, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ic, ia, ib]
+
+    def _fitstart(self, data):
+        # Arbitrary, but default a=b=c=1 is not valid
+        return super()._fitstart(data, args=(1, 0, 1))
+
+    def _get_support(self, c, a, b):
+        return a, b
+
+    def _pdf(self, x, c, a, b):
+        denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return (c * pow(x, c-1) * np.exp(-pow(x, c))) / denum
+
+    def _logpdf(self, x, c, a, b):
+        logdenum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return np.log(c) + sc.xlogy(c - 1, x) - pow(x, c) - logdenum
+
+    def _cdf(self, x, c, a, b):
+        num = (np.exp(-pow(a, c)) - np.exp(-pow(x, c)))
+        denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return num / denum
+
+    def _logcdf(self, x, c, a, b):
+        lognum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(x, c)))
+        logdenum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return lognum - logdenum
+
+    def _sf(self, x, c, a, b):
+        num = (np.exp(-pow(x, c)) - np.exp(-pow(b, c)))
+        denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return num / denum
+
+    def _logsf(self, x, c, a, b):
+        lognum = np.log(np.exp(-pow(x, c)) - np.exp(-pow(b, c)))
+        logdenum = np.log(np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return lognum - logdenum
+
+    def _isf(self, q, c, a, b):
+        return pow(
+            -np.log((1 - q) * np.exp(-pow(b, c)) + q * np.exp(-pow(a, c))), 1/c
+            )
+
+    def _ppf(self, q, c, a, b):
+        return pow(
+            -np.log((1 - q) * np.exp(-pow(a, c)) + q * np.exp(-pow(b, c))), 1/c
+            )
+
+    def _munp(self, n, c, a, b):
+        gamma_fun = sc.gamma(n/c + 1.) * (
+            sc.gammainc(n/c + 1., pow(b, c)) - sc.gammainc(n/c + 1., pow(a, c))
+            )
+        denum = (np.exp(-pow(a, c)) - np.exp(-pow(b, c)))
+        return gamma_fun / denum
+
+
+truncweibull_min = truncweibull_min_gen(name='truncweibull_min')
+truncweibull_min._support = ('a', 'b')
+
+
+class weibull_max_gen(rv_continuous):
+    r"""Weibull maximum continuous random variable.
+
+    The Weibull Maximum Extreme Value distribution, from extreme value theory
+    (Fisher-Gnedenko theorem), is the limiting distribution of rescaled
+    maximum of iid random variables. This is the distribution of -X
+    if X is from the `weibull_min` function.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    weibull_min
+
+    Notes
+    -----
+    The probability density function for `weibull_max` is:
+
+    .. math::
+
+        f(x, c) = c (-x)^{c-1} \exp(-(-x)^c)
+
+    for :math:`x < 0`, :math:`c > 0`.
+
+    `weibull_max` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/Weibull_distribution
+
+    https://en.wikipedia.org/wiki/Fisher-Tippett-Gnedenko_theorem
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # weibull_max.pdf(x, c) = c * (-x)**(c-1) * exp(-(-x)**c)
+        return c*pow(-x, c-1)*np.exp(-pow(-x, c))
+
+    def _logpdf(self, x, c):
+        return np.log(c) + sc.xlogy(c-1, -x) - pow(-x, c)
+
+    def _cdf(self, x, c):
+        return np.exp(-pow(-x, c))
+
+    def _logcdf(self, x, c):
+        return -pow(-x, c)
+
+    def _sf(self, x, c):
+        return -sc.expm1(-pow(-x, c))
+
+    def _ppf(self, q, c):
+        return -pow(-np.log(q), 1.0/c)
+
+    def _munp(self, n, c):
+        val = sc.gamma(1.0+n*1.0/c)
+        if int(n) % 2:
+            sgn = -1
+        else:
+            sgn = 1
+        return sgn * val
+
+    def _entropy(self, c):
+        return -_EULER / c - np.log(c) + _EULER + 1
+
+
+weibull_max = weibull_max_gen(b=0.0, name='weibull_max')
+
+
+class genlogistic_gen(rv_continuous):
+    r"""A generalized logistic continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `genlogistic` is:
+
+    .. math::
+
+        f(x, c) = c \frac{\exp(-x)}
+                         {(1 + \exp(-x))^{c+1}}
+
+    for real :math:`x` and :math:`c > 0`. In literature, different
+    generalizations of the logistic distribution can be found. This is the type 1
+    generalized logistic distribution according to [1]_. It is also referred to
+    as the skew-logistic distribution [2]_.
+
+    `genlogistic` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Johnson et al. "Continuous Univariate Distributions", Volume 2,
+           Wiley. 1995.
+    .. [2] "Generalized Logistic Distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Generalized_logistic_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # genlogistic.pdf(x, c) = c * exp(-x) / (1 + exp(-x))**(c+1)
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        # Two mathematically equivalent expressions for log(pdf(x, c)):
+        #     log(pdf(x, c)) = log(c) - x - (c + 1)*log(1 + exp(-x))
+        #                    = log(c) + c*x - (c + 1)*log(1 + exp(x))
+        mult = -(c - 1) * (x < 0) - 1
+        absx = np.abs(x)
+        return np.log(c) + mult*absx - (c+1) * sc.log1p(np.exp(-absx))
+
+    def _cdf(self, x, c):
+        Cx = (1+np.exp(-x))**(-c)
+        return Cx
+
+    def _logcdf(self, x, c):
+        return -c * np.log1p(np.exp(-x))
+
+    def _ppf(self, q, c):
+        return -np.log(sc.powm1(q, -1.0/c))
+
+    def _sf(self, x, c):
+        return -sc.expm1(self._logcdf(x, c))
+
+    def _isf(self, q, c):
+        return self._ppf(1 - q, c)
+
+    def _stats(self, c):
+        mu = _EULER + sc.psi(c)
+        mu2 = np.pi*np.pi/6.0 + sc.zeta(2, c)
+        g1 = -2*sc.zeta(3, c) + 2*_ZETA3
+        g1 /= np.power(mu2, 1.5)
+        g2 = np.pi**4/15.0 + 6*sc.zeta(4, c)
+        g2 /= mu2**2.0
+        return mu, mu2, g1, g2
+
+    def _entropy(self, c):
+        return _lazywhere(c < 8e6, (c, ),
+                          lambda c: -np.log(c) + sc.psi(c + 1) + _EULER + 1,
+                          # asymptotic expansion: psi(c) ~ log(c) - 1/(2 * c)
+                          # a = -log(c) + psi(c + 1)
+                          #   = -log(c) + psi(c) + 1/c
+                          #   ~ -log(c) + log(c) - 1/(2 * c) + 1/c
+                          #   = 1/(2 * c)
+                          f2=lambda c: 1/(2 * c) + _EULER + 1)
+
+
+genlogistic = genlogistic_gen(name='genlogistic')
+
+
+class genpareto_gen(rv_continuous):
+    r"""A generalized Pareto continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `genpareto` is:
+
+    .. math::
+
+        f(x, c) = (1 + c x)^{-1 - 1/c}
+
+    defined for :math:`x \ge 0` if :math:`c \ge 0`, and for
+    :math:`0 \le x \le -1/c` if :math:`c < 0`.
+
+    `genpareto` takes ``c`` as a shape parameter for :math:`c`.
+
+    For :math:`c=0`, `genpareto` reduces to the exponential
+    distribution, `expon`:
+
+    .. math::
+
+        f(x, 0) = \exp(-x)
+
+    For :math:`c=-1`, `genpareto` is uniform on ``[0, 1]``:
+
+    .. math::
+
+        f(x, -1) = 1
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return np.isfinite(c)
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (-np.inf, np.inf), (False, False))]
+
+    def _get_support(self, c):
+        c = np.asarray(c)
+        b = _lazywhere(c < 0, (c,),
+                       lambda c: -1. / c,
+                       np.inf)
+        a = np.where(c >= 0, self.a, self.a)
+        return a, b
+
+    def _pdf(self, x, c):
+        # genpareto.pdf(x, c) = (1 + c * x)**(-1 - 1/c)
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: -sc.xlog1py(c + 1., c*x) / c,
+                          -x)
+
+    def _cdf(self, x, c):
+        return -sc.inv_boxcox1p(-x, -c)
+
+    def _sf(self, x, c):
+        return sc.inv_boxcox(-x, -c)
+
+    def _logsf(self, x, c):
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: -sc.log1p(c*x) / c,
+                          -x)
+
+    def _ppf(self, q, c):
+        return -sc.boxcox1p(-q, -c)
+
+    def _isf(self, q, c):
+        return -sc.boxcox(q, -c)
+
+    def _stats(self, c, moments='mv'):
+        if 'm' not in moments:
+            m = None
+        else:
+            m = _lazywhere(c < 1, (c,),
+                           lambda xi: 1/(1 - xi),
+                           np.inf)
+        if 'v' not in moments:
+            v = None
+        else:
+            v = _lazywhere(c < 1/2, (c,),
+                           lambda xi: 1 / (1 - xi)**2 / (1 - 2*xi),
+                           np.nan)
+        if 's' not in moments:
+            s = None
+        else:
+            s = _lazywhere(c < 1/3, (c,),
+                           lambda xi: (2 * (1 + xi) * np.sqrt(1 - 2*xi) /
+                                       (1 - 3*xi)),
+                           np.nan)
+        if 'k' not in moments:
+            k = None
+        else:
+            k = _lazywhere(c < 1/4, (c,),
+                           lambda xi: (3 * (1 - 2*xi) * (2*xi**2 + xi + 3) /
+                                       (1 - 3*xi) / (1 - 4*xi) - 3),
+                           np.nan)
+        return m, v, s, k
+
+    def _munp(self, n, c):
+        def __munp(n, c):
+            val = 0.0
+            k = np.arange(0, n + 1)
+            for ki, cnk in zip(k, sc.comb(n, k)):
+                val = val + cnk * (-1) ** ki / (1.0 - c * ki)
+            return np.where(c * n < 1, val * (-1.0 / c) ** n, np.inf)
+        return _lazywhere(c != 0, (c,),
+                          lambda c: __munp(n, c),
+                          sc.gamma(n + 1))
+
+    def _entropy(self, c):
+        return 1. + c
+
+
+genpareto = genpareto_gen(a=0.0, name='genpareto')
+
+
+class genexpon_gen(rv_continuous):
+    r"""A generalized exponential continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `genexpon` is:
+
+    .. math::
+
+        f(x, a, b, c) = (a + b (1 - \exp(-c x)))
+                        \exp(-a x - b x + \frac{b}{c}  (1-\exp(-c x)))
+
+    for :math:`x \ge 0`, :math:`a, b, c > 0`.
+
+    `genexpon` takes :math:`a`, :math:`b` and :math:`c` as shape parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    H.K. Ryu, "An Extension of Marshall and Olkin's Bivariate Exponential
+    Distribution", Journal of the American Statistical Association, 1993.
+
+    N. Balakrishnan, Asit P. Basu (editors), *The Exponential Distribution:
+    Theory, Methods and Applications*, Gordon and Breach, 1995.
+    ISBN 10: 2884491929
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        return [ia, ib, ic]
+
+    def _pdf(self, x, a, b, c):
+        # genexpon.pdf(x, a, b, c) = (a + b * (1 - exp(-c*x))) * \
+        #                            exp(-a*x - b*x + b/c * (1-exp(-c*x)))
+        return (a + b*(-sc.expm1(-c*x)))*np.exp((-a-b)*x +
+                                                b*(-sc.expm1(-c*x))/c)
+
+    def _logpdf(self, x, a, b, c):
+        return np.log(a+b*(-sc.expm1(-c*x))) + (-a-b)*x+b*(-sc.expm1(-c*x))/c
+
+    def _cdf(self, x, a, b, c):
+        return -sc.expm1((-a-b)*x + b*(-sc.expm1(-c*x))/c)
+
+    def _ppf(self, p, a, b, c):
+        s = a + b
+        t = (b - c*np.log1p(-p))/s
+        return (t + sc.lambertw(-b/s * np.exp(-t)).real)/c
+
+    def _sf(self, x, a, b, c):
+        return np.exp((-a-b)*x + b*(-sc.expm1(-c*x))/c)
+
+    def _isf(self, p, a, b, c):
+        s = a + b
+        t = (b - c*np.log(p))/s
+        return (t + sc.lambertw(-b/s * np.exp(-t)).real)/c
+
+
+genexpon = genexpon_gen(a=0.0, name='genexpon')
+
+
+class genextreme_gen(rv_continuous):
+    r"""A generalized extreme value continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gumbel_r
+
+    Notes
+    -----
+    For :math:`c=0`, `genextreme` is equal to `gumbel_r` with
+    probability density function
+
+    .. math::
+
+        f(x) = \exp(-\exp(-x)) \exp(-x),
+
+    where :math:`-\infty < x < \infty`.
+
+    For :math:`c \ne 0`, the probability density function for `genextreme` is:
+
+    .. math::
+
+        f(x, c) = \exp(-(1-c x)^{1/c}) (1-c x)^{1/c-1},
+
+    where :math:`-\infty < x \le 1/c` if :math:`c > 0` and
+    :math:`1/c \le x < \infty` if :math:`c < 0`.
+
+    Note that several sources and software packages use the opposite
+    convention for the sign of the shape parameter :math:`c`.
+
+    `genextreme` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return np.isfinite(c)
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (-np.inf, np.inf), (False, False))]
+
+    def _get_support(self, c):
+        _b = np.where(c > 0, 1.0 / np.maximum(c, _XMIN), np.inf)
+        _a = np.where(c < 0, 1.0 / np.minimum(c, -_XMIN), -np.inf)
+        return _a, _b
+
+    def _loglogcdf(self, x, c):
+        # Returns log(-log(cdf(x, c)))
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: sc.log1p(-c*x)/c, -x)
+
+    def _pdf(self, x, c):
+        # genextreme.pdf(x, c) =
+        #     exp(-exp(-x))*exp(-x),                    for c==0
+        #     exp(-(1-c*x)**(1/c))*(1-c*x)**(1/c-1),    for x \le 1/c, c > 0
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        cx = _lazywhere((x == x) & (c != 0), (x, c), lambda x, c: c*x, 0.0)
+        logex2 = sc.log1p(-cx)
+        logpex2 = self._loglogcdf(x, c)
+        pex2 = np.exp(logpex2)
+        # Handle special cases
+        np.putmask(logpex2, (c == 0) & (x == -np.inf), 0.0)
+        logpdf = _lazywhere(~((cx == 1) | (cx == -np.inf)),
+                            (pex2, logpex2, logex2),
+                            lambda pex2, lpex2, lex2: -pex2 + lpex2 - lex2,
+                            fillvalue=-np.inf)
+        np.putmask(logpdf, (c == 1) & (x == 1), 0.0)
+        return logpdf
+
+    def _logcdf(self, x, c):
+        return -np.exp(self._loglogcdf(x, c))
+
+    def _cdf(self, x, c):
+        return np.exp(self._logcdf(x, c))
+
+    def _sf(self, x, c):
+        return -sc.expm1(self._logcdf(x, c))
+
+    def _ppf(self, q, c):
+        x = -np.log(-np.log(q))
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: -sc.expm1(-c * x) / c, x)
+
+    def _isf(self, q, c):
+        x = -np.log(-sc.log1p(-q))
+        return _lazywhere((x == x) & (c != 0), (x, c),
+                          lambda x, c: -sc.expm1(-c * x) / c, x)
+
+    def _stats(self, c):
+        def g(n):
+            return sc.gamma(n * c + 1)
+        g1 = g(1)
+        g2 = g(2)
+        g3 = g(3)
+        g4 = g(4)
+        g2mg12 = np.where(abs(c) < 1e-7, (c*np.pi)**2.0/6.0, g2-g1**2.0)
+        def gam2k_f(c):
+            return sc.expm1(sc.gammaln(2.0*c+1.0)-2*sc.gammaln(c + 1.0))/c**2.0
+        gam2k = _lazywhere(abs(c) >= 1e-7, (c,), f=gam2k_f, fillvalue=np.pi**2.0/6.0)
+        eps = 1e-14
+        def gamk_f(c):
+            return sc.expm1(sc.gammaln(c + 1))/c
+        gamk = _lazywhere(abs(c) >= eps, (c,), f=gamk_f, fillvalue=-_EULER)
+
+        # mean
+        m = np.where(c < -1.0, np.nan, -gamk)
+        
+        # variance
+        v = np.where(c < -0.5, np.nan, g1**2.0*gam2k)
+
+        # skewness
+        def sk1_eval(c, *args):
+            def sk1_eval_f(c, g1, g2, g3, g2mg12):
+                return np.sign(c)*(-g3 + (g2 + 2*g2mg12)*g1)/g2mg12**1.5
+            return _lazywhere(c >= -1./3, (c,)+args, f=sk1_eval_f, fillvalue=np.nan)
+
+        sk_fill = 12*np.sqrt(6)*_ZETA3/np.pi**3
+        args = (g1, g2, g3, g2mg12)
+        sk = _lazywhere(abs(c) > eps**0.29, (c,)+args, f=sk1_eval, fillvalue=sk_fill)
+
+        # kurtosis
+        def ku1_eval(c, *args):
+            def ku1_eval_f(g1, g2, g3, g4, g2mg12):
+                return (g4 + (-4*g3 + 3*(g2 + g2mg12)*g1)*g1)/g2mg12**2 - 3
+            return _lazywhere(c >= -1./4, args, ku1_eval_f, fillvalue=np.nan)
+
+        args = (g1, g2, g3, g4, g2mg12)
+        ku = _lazywhere(abs(c) > eps**0.23, (c,)+args, f=ku1_eval, fillvalue=12.0/5.0)
+
+        return m, v, sk, ku
+
+    def _fitstart(self, data):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        # This is better than the default shape of (1,).
+        g = _skew(data)
+        if g < 0:
+            a = 0.5
+        else:
+            a = -0.5
+        return super()._fitstart(data, args=(a,))
+
+    def _munp(self, n, c):
+        k = np.arange(0, n+1)
+        vals = 1.0/c**n * np.sum(
+            sc.comb(n, k) * (-1)**k * sc.gamma(c*k + 1),
+            axis=0)
+        return np.where(c*n > -1, vals, np.inf)
+
+    def _entropy(self, c):
+        return _EULER*(1 - c) + 1
+
+
+genextreme = genextreme_gen(name='genextreme')
+
+
+def _digammainv(y):
+    """Inverse of the digamma function (real positive arguments only).
+
+    This function is used in the `fit` method of `gamma_gen`.
+    The function uses either optimize.fsolve or optimize.newton
+    to solve `sc.digamma(x) - y = 0`.  There is probably room for
+    improvement, but currently it works over a wide range of y:
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> y = 64*rng.standard_normal(1000000)
+    >>> y.min(), y.max()
+    (-311.43592651416662, 351.77388222276869)
+    >>> x = [_digammainv(t) for t in y]
+    >>> np.abs(sc.digamma(x) - y).max()
+    1.1368683772161603e-13
+
+    """
+    _em = 0.5772156649015328606065120
+
+    def func(x):
+        return sc.digamma(x) - y
+
+    if y > -0.125:
+        x0 = np.exp(y) + 0.5
+        if y < 10:
+            # Some experimentation shows that newton reliably converges
+            # must faster than fsolve in this y range.  For larger y,
+            # newton sometimes fails to converge.
+            value = optimize.newton(func, x0, tol=1e-10)
+            return value
+    elif y > -3:
+        x0 = np.exp(y/2.332) + 0.08661
+    else:
+        x0 = 1.0 / (-y - _em)
+
+    value, info, ier, mesg = optimize.fsolve(func, x0, xtol=1e-11,
+                                             full_output=True)
+    if ier != 1:
+        raise RuntimeError(f"_digammainv: fsolve failed, y = {y!r}")
+
+    return value[0]
+
+
+## Gamma (Use MATLAB and MATHEMATICA (b=theta=scale, a=alpha=shape) definition)
+
+## gamma(a, loc, scale)  with a an integer is the Erlang distribution
+## gamma(1, loc, scale)  is the Exponential distribution
+## gamma(df/2, 0, 2) is the chi2 distribution with df degrees of freedom.
+
+class gamma_gen(rv_continuous):
+    r"""A gamma continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    erlang, expon
+
+    Notes
+    -----
+    The probability density function for `gamma` is:
+
+    .. math::
+
+        f(x, a) = \frac{x^{a-1} e^{-x}}{\Gamma(a)}
+
+    for :math:`x \ge 0`, :math:`a > 0`. Here :math:`\Gamma(a)` refers to the
+    gamma function.
+
+    `gamma` takes ``a`` as a shape parameter for :math:`a`.
+
+    When :math:`a` is an integer, `gamma` reduces to the Erlang
+    distribution, and when :math:`a=1` to the exponential distribution.
+
+    Gamma distributions are sometimes parameterized with two variables,
+    with a probability density function of:
+
+    .. math::
+
+        f(x, \alpha, \beta) =
+        \frac{\beta^\alpha x^{\alpha - 1} e^{-\beta x }}{\Gamma(\alpha)}
+
+    Note that this parameterization is equivalent to the above, with
+    ``scale = 1 / beta``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, a, size=None, random_state=None):
+        return random_state.standard_gamma(a, size)
+
+    def _pdf(self, x, a):
+        # gamma.pdf(x, a) = x**(a-1) * exp(-x) / gamma(a)
+        return np.exp(self._logpdf(x, a))
+
+    def _logpdf(self, x, a):
+        return sc.xlogy(a-1.0, x) - x - sc.gammaln(a)
+
+    def _cdf(self, x, a):
+        return sc.gammainc(a, x)
+
+    def _sf(self, x, a):
+        return sc.gammaincc(a, x)
+
+    def _ppf(self, q, a):
+        return sc.gammaincinv(a, q)
+
+    def _isf(self, q, a):
+        return sc.gammainccinv(a, q)
+
+    def _stats(self, a):
+        return a, a, 2.0/np.sqrt(a), 6.0/a
+
+    def _munp(self, n, a):
+        return sc.poch(a, n)
+
+    def _entropy(self, a):
+
+        def regular_formula(a):
+            return sc.psi(a) * (1-a) + a + sc.gammaln(a)
+
+        def asymptotic_formula(a):
+            # plug in above formula the expansions:
+            # psi(a) ~ ln(a) - 1/2a - 1/12a^2 + 1/120a^4
+            # gammaln(a) ~ a * ln(a) - a - 1/2 * ln(a) + 1/2 ln(2 * pi) +
+            #              1/12a - 1/360a^3
+            return (0.5 * (1. + np.log(2*np.pi) + np.log(a)) - 1/(3 * a)
+                    - (a**-2.)/12 - (a**-3.)/90 + (a**-4.)/120)
+
+        return _lazywhere(a < 250, (a, ), regular_formula,
+                          f2=asymptotic_formula)
+
+    def _fitstart(self, data):
+        # The skewness of the gamma distribution is `2 / np.sqrt(a)`.
+        # We invert that to estimate the shape `a` using the skewness
+        # of the data.  The formula is regularized with 1e-8 in the
+        # denominator to allow for degenerate data where the skewness
+        # is close to 0.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        sk = _skew(data)
+        a = 4 / (1e-8 + sk**2)
+        return super()._fitstart(data, args=(a,))
+
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        When the location is fixed by using the argument `floc`
+        and `method='MLE'`, this
+        function uses explicit formulas or solves a simpler numerical
+        problem than the full ML optimization problem.  So in that case,
+        the `optimizer`, `loc` and `scale` arguments are ignored.
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+        floc = kwds.get('floc', None)
+        method = kwds.get('method', 'mle')
+
+        if (isinstance(data, CensoredData) or
+                floc is None and method.lower() != 'mm'):
+            # loc is not fixed or we're not doing standard MLE.
+            # Use the default fit method.
+            return super().fit(data, *args, **kwds)
+
+        # We already have this value, so just pop it from kwds.
+        kwds.pop('floc', None)
+
+        f0 = _get_fixed_fit_value(kwds, ['f0', 'fa', 'fix_a'])
+        fscale = kwds.pop('fscale', None)
+
+        _remove_optimizer_parameters(kwds)
+
+        if f0 is not None and floc is not None and fscale is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            # Without this check, this function would just return the
+            # parameters that were given.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        # Fixed location is handled by shifting the data.
+        data = np.asarray(data)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        # Use explicit formulas for mm (gh-19884)
+        if method.lower() == 'mm':
+            m1 = np.mean(data)
+            m2 = np.var(data)
+            m3 = np.mean((data - m1) ** 3)
+            a, loc, scale = f0, floc, fscale
+            # Three unknowns
+            if a is None and loc is None and scale is None:
+                scale = m3 / (2 * m2)
+            # Two unknowns
+            if loc is None and scale is None:
+                scale = np.sqrt(m2 / a)
+            if a is None and scale is None:
+                scale = m2 / (m1 - loc)
+            if a is None and loc is None:
+                a = m2 / (scale ** 2)
+            # One unknown
+            if a is None:
+                a = (m1 - loc) / scale
+            if loc is None:
+                loc = m1 - a * scale
+            if scale is None:
+                scale = (m1 - loc) / a
+            return a, loc, scale
+
+        # Special case: loc is fixed.
+
+        # NB: data == loc is ok if a >= 1; the below check is more strict.
+        if np.any(data <= floc):
+            raise FitDataError("gamma", lower=floc, upper=np.inf)
+
+        if floc != 0:
+            # Don't do the subtraction in-place, because `data` might be a
+            # view of the input array.
+            data = data - floc
+        xbar = data.mean()
+
+        # Three cases to handle:
+        # * shape and scale both free
+        # * shape fixed, scale free
+        # * shape free, scale fixed
+
+        if fscale is None:
+            # scale is free
+            if f0 is not None:
+                # shape is fixed
+                a = f0
+            else:
+                # shape and scale are both free.
+                # The MLE for the shape parameter `a` is the solution to:
+                # np.log(a) - sc.digamma(a) - np.log(xbar) +
+                #                             np.log(data).mean() = 0
+                s = np.log(xbar) - np.log(data).mean()
+                aest = (3-s + np.sqrt((s-3)**2 + 24*s)) / (12*s)
+                xa = aest*(1-0.4)
+                xb = aest*(1+0.4)
+                a = optimize.brentq(lambda a: np.log(a) - sc.digamma(a) - s,
+                                    xa, xb, disp=0)
+
+            # The MLE for the scale parameter is just the data mean
+            # divided by the shape parameter.
+            scale = xbar / a
+        else:
+            # scale is fixed, shape is free
+            # The MLE for the shape parameter `a` is the solution to:
+            # sc.digamma(a) - np.log(data).mean() + np.log(fscale) = 0
+            c = np.log(data).mean() - np.log(fscale)
+            a = _digammainv(c)
+            scale = fscale
+
+        return a, floc, scale
+
+
+gamma = gamma_gen(a=0.0, name='gamma')
+
+
+class erlang_gen(gamma_gen):
+    """An Erlang continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gamma
+
+    Notes
+    -----
+    The Erlang distribution is a special case of the Gamma distribution, with
+    the shape parameter `a` an integer.  Note that this restriction is not
+    enforced by `erlang`. It will, however, generate a warning the first time
+    a non-integer value is used for the shape parameter.
+
+    Refer to `gamma` for examples.
+
+    """
+
+    def _argcheck(self, a):
+        allint = np.all(np.floor(a) == a)
+        if not allint:
+            # An Erlang distribution shouldn't really have a non-integer
+            # shape parameter, so warn the user.
+            message = ('The shape parameter of the erlang distribution '
+                       f'has been given a non-integer value {a!r}.')
+            warnings.warn(message, RuntimeWarning, stacklevel=3)
+        return a > 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", True, (1, np.inf), (True, False))]
+
+    def _fitstart(self, data):
+        # Override gamma_gen_fitstart so that an integer initial value is
+        # used.  (Also regularize the division, to avoid issues when
+        # _skew(data) is 0 or close to 0.)
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        a = int(4.0 / (1e-8 + _skew(data)**2))
+        return super(gamma_gen, self)._fitstart(data, args=(a,))
+
+    # Trivial override of the fit method, so we can monkey-patch its
+    # docstring.
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        The Erlang distribution is generally defined to have integer values
+        for the shape parameter.  This is not enforced by the `erlang` class.
+        When fitting the distribution, it will generally return a non-integer
+        value for the shape parameter.  By using the keyword argument
+        `f0=`, the fit method can be constrained to fit the data to
+        a specific integer shape parameter.""")
+    def fit(self, data, *args, **kwds):
+        return super().fit(data, *args, **kwds)
+
+
+erlang = erlang_gen(a=0.0, name='erlang')
+
+
+class gengamma_gen(rv_continuous):
+    r"""A generalized gamma continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gamma, invgamma, weibull_min
+
+    Notes
+    -----
+    The probability density function for `gengamma` is ([1]_):
+
+    .. math::
+
+        f(x, a, c) = \frac{|c| x^{c a-1} \exp(-x^c)}{\Gamma(a)}
+
+    for :math:`x \ge 0`, :math:`a > 0`, and :math:`c \ne 0`.
+    :math:`\Gamma` is the gamma function (`scipy.special.gamma`).
+
+    `gengamma` takes :math:`a` and :math:`c` as shape parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] E.W. Stacy, "A Generalization of the Gamma Distribution",
+       Annals of Mathematical Statistics, Vol 33(3), pp. 1187--1192.
+
+    %(example)s
+
+    """
+    def _argcheck(self, a, c):
+        return (a > 0) & (c != 0)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (-np.inf, np.inf), (False, False))
+        return [ia, ic]
+
+    def _pdf(self, x, a, c):
+        return np.exp(self._logpdf(x, a, c))
+
+    def _logpdf(self, x, a, c):
+        return _lazywhere((x != 0) | (c > 0), (x, c),
+                          lambda x, c: (np.log(abs(c)) + sc.xlogy(c*a - 1, x)
+                                        - x**c - sc.gammaln(a)),
+                          fillvalue=-np.inf)
+
+    def _cdf(self, x, a, c):
+        xc = x**c
+        val1 = sc.gammainc(a, xc)
+        val2 = sc.gammaincc(a, xc)
+        return np.where(c > 0, val1, val2)
+
+    def _rvs(self, a, c, size=None, random_state=None):
+        r = random_state.standard_gamma(a, size=size)
+        return r**(1./c)
+
+    def _sf(self, x, a, c):
+        xc = x**c
+        val1 = sc.gammainc(a, xc)
+        val2 = sc.gammaincc(a, xc)
+        return np.where(c > 0, val2, val1)
+
+    def _ppf(self, q, a, c):
+        val1 = sc.gammaincinv(a, q)
+        val2 = sc.gammainccinv(a, q)
+        return np.where(c > 0, val1, val2)**(1.0/c)
+
+    def _isf(self, q, a, c):
+        val1 = sc.gammaincinv(a, q)
+        val2 = sc.gammainccinv(a, q)
+        return np.where(c > 0, val2, val1)**(1.0/c)
+
+    def _munp(self, n, a, c):
+        # Pochhammer symbol: sc.pocha,n) = gamma(a+n)/gamma(a)
+        return sc.poch(a, n*1.0/c)
+
+    def _entropy(self, a, c):
+        def regular(a, c):
+            val = sc.psi(a)
+            A = a * (1 - val) + val / c
+            B = sc.gammaln(a) - np.log(abs(c))
+            h = A + B
+            return h
+
+        def asymptotic(a, c):
+            # using asymptotic expansions for gammaln and psi (see gh-18093)
+            return (norm._entropy() - np.log(a)/2
+                    - np.log(np.abs(c)) + (a**-1.)/6 - (a**-3.)/90
+                    + (np.log(a) - (a**-1.)/2 - (a**-2.)/12 + (a**-4.)/120)/c)
+
+        h = _lazywhere(a >= 2e2, (a, c), f=asymptotic, f2=regular)
+        return h
+
+
+gengamma = gengamma_gen(a=0.0, name='gengamma')
+
+
+class genhalflogistic_gen(rv_continuous):
+    r"""A generalized half-logistic continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `genhalflogistic` is:
+
+    .. math::
+
+        f(x, c) = \frac{2 (1 - c x)^{1/(c-1)}}{[1 + (1 - c x)^{1/c}]^2}
+
+    for :math:`0 \le x \le 1/c`, and :math:`c > 0`.
+
+    `genhalflogistic` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _get_support(self, c):
+        return self.a, 1.0/c
+
+    def _pdf(self, x, c):
+        # genhalflogistic.pdf(x, c) =
+        #    2 * (1-c*x)**(1/c-1) / (1+(1-c*x)**(1/c))**2
+        limit = 1.0/c
+        tmp = np.asarray(1-c*x)
+        tmp0 = tmp**(limit-1)
+        tmp2 = tmp0*tmp
+        return 2*tmp0 / (1+tmp2)**2
+
+    def _cdf(self, x, c):
+        limit = 1.0/c
+        tmp = np.asarray(1-c*x)
+        tmp2 = tmp**(limit)
+        return (1.0-tmp2) / (1+tmp2)
+
+    def _ppf(self, q, c):
+        return 1.0/c*(1-((1.0-q)/(1.0+q))**c)
+
+    def _entropy(self, c):
+        return 2 - (2*c+1)*np.log(2)
+
+
+genhalflogistic = genhalflogistic_gen(a=0.0, name='genhalflogistic')
+
+
+class genhyperbolic_gen(rv_continuous):
+    r"""A generalized hyperbolic continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    t, norminvgauss, geninvgauss, laplace, cauchy
+
+    Notes
+    -----
+    The probability density function for `genhyperbolic` is:
+
+    .. math::
+
+        f(x, p, a, b) =
+            \frac{(a^2 - b^2)^{p/2}}
+            {\sqrt{2\pi}a^{p-1/2}
+            K_p\Big(\sqrt{a^2 - b^2}\Big)}
+            e^{bx} \times \frac{K_{p - 1/2}
+            (a \sqrt{1 + x^2})}
+            {(\sqrt{1 + x^2})^{1/2 - p}}
+
+    for :math:`x, p \in ( - \infty; \infty)`,
+    :math:`|b| < a` if :math:`p \ge 0`,
+    :math:`|b| \le a` if :math:`p < 0`.
+    :math:`K_{p}(.)` denotes the modified Bessel function of the second
+    kind and order :math:`p` (`scipy.special.kv`)
+
+    `genhyperbolic` takes ``p`` as a tail parameter,
+    ``a`` as a shape parameter,
+    ``b`` as a skewness parameter.
+
+    %(after_notes)s
+
+    The original parameterization of the Generalized Hyperbolic Distribution
+    is found in [1]_ as follows
+
+    .. math::
+
+        f(x, \lambda, \alpha, \beta, \delta, \mu) =
+           \frac{(\gamma/\delta)^\lambda}{\sqrt{2\pi}K_\lambda(\delta \gamma)}
+           e^{\beta (x - \mu)} \times \frac{K_{\lambda - 1/2}
+           (\alpha \sqrt{\delta^2 + (x - \mu)^2})}
+           {(\sqrt{\delta^2 + (x - \mu)^2} / \alpha)^{1/2 - \lambda}}
+
+    for :math:`x \in ( - \infty; \infty)`,
+    :math:`\gamma := \sqrt{\alpha^2 - \beta^2}`,
+    :math:`\lambda, \mu \in ( - \infty; \infty)`,
+    :math:`\delta \ge 0, |\beta| < \alpha` if :math:`\lambda \ge 0`,
+    :math:`\delta > 0, |\beta| \le \alpha` if :math:`\lambda < 0`.
+
+    The location-scale-based parameterization implemented in
+    SciPy is based on [2]_, where :math:`a = \alpha\delta`,
+    :math:`b = \beta\delta`, :math:`p = \lambda`,
+    :math:`scale=\delta` and :math:`loc=\mu`
+
+    Moments are implemented based on [3]_ and [4]_.
+
+    For the distributions that are a special case such as Student's t,
+    it is not recommended to rely on the implementation of genhyperbolic.
+    To avoid potential numerical problems and for performance reasons,
+    the methods of the specific distributions should be used.
+
+    References
+    ----------
+    .. [1] O. Barndorff-Nielsen, "Hyperbolic Distributions and Distributions
+       on Hyperbolae", Scandinavian Journal of Statistics, Vol. 5(3),
+       pp. 151-157, 1978. https://www.jstor.org/stable/4615705
+
+    .. [2] Eberlein E., Prause K. (2002) The Generalized Hyperbolic Model:
+        Financial Derivatives and Risk Measures. In: Geman H., Madan D.,
+        Pliska S.R., Vorst T. (eds) Mathematical Finance - Bachelier
+        Congress 2000. Springer Finance. Springer, Berlin, Heidelberg.
+        :doi:`10.1007/978-3-662-12429-1_12`
+
+    .. [3] Scott, David J, Würtz, Diethelm, Dong, Christine and Tran,
+       Thanh Tam, (2009), Moments of the generalized hyperbolic
+       distribution, MPRA Paper, University Library of Munich, Germany,
+       https://EconPapers.repec.org/RePEc:pra:mprapa:19081.
+
+    .. [4] E. Eberlein and E. A. von Hammerstein. Generalized hyperbolic
+       and inverse Gaussian distributions: Limiting cases and approximation
+       of processes. FDM Preprint 80, April 2003. University of Freiburg.
+       https://freidok.uni-freiburg.de/fedora/objects/freidok:7974/datastreams/FILE1/content
+
+    %(example)s
+
+    """
+
+    def _argcheck(self, p, a, b):
+        return (np.logical_and(np.abs(b) < a, p >= 0)
+                | np.logical_and(np.abs(b) <= a, p < 0))
+
+    def _shape_info(self):
+        ip = _ShapeInfo("p", False, (-np.inf, np.inf), (False, False))
+        ia = _ShapeInfo("a", False, (0, np.inf), (True, False))
+        ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, False))
+        return [ip, ia, ib]
+
+    def _fitstart(self, data):
+        # Arbitrary, but the default p = a = b = 1 is not valid; the
+        # distribution requires |b| < a if p >= 0.
+        return super()._fitstart(data, args=(1, 1, 0.5))
+
+    def _logpdf(self, x, p, a, b):
+        # kve instead of kv works better for large values of p
+        # and smaller values of sqrt(a^2  - b^2)
+        @np.vectorize
+        def _logpdf_single(x, p, a, b):
+            return _stats.genhyperbolic_logpdf(x, p, a, b)
+
+        return _logpdf_single(x, p, a, b)
+
+    def _pdf(self, x, p, a, b):
+        # kve instead of kv works better for large values of p
+        # and smaller values of sqrt(a^2  - b^2)
+        @np.vectorize
+        def _pdf_single(x, p, a, b):
+            return _stats.genhyperbolic_pdf(x, p, a, b)
+
+        return _pdf_single(x, p, a, b)
+
+    # np.vectorize isn't currently designed to be used as a decorator,
+    # so use a lambda instead.  This allows us to decorate the function
+    # with `np.vectorize` and still provide the `otypes` parameter.
+    @lambda func: np.vectorize(func, otypes=[np.float64])
+    @staticmethod
+    def _integrate_pdf(x0, x1, p, a, b):
+        """
+        Integrate the pdf of the genhyberbolic distribution from x0 to x1.
+        This is a private function used by _cdf() and _sf() only; either x0
+        will be -inf or x1 will be inf.
+        """
+        user_data = np.array([p, a, b], float).ctypes.data_as(ctypes.c_void_p)
+        llc = LowLevelCallable.from_cython(_stats, '_genhyperbolic_pdf',
+                                           user_data)
+        d = np.sqrt((a + b)*(a - b))
+        mean = b/d * sc.kv(p + 1, d) / sc.kv(p, d)
+        epsrel = 1e-10
+        epsabs = 0
+        if x0 < mean < x1:
+            # If the interval includes the mean, integrate over the two
+            # intervals [x0, mean] and [mean, x1] and add. If we try to do
+            # the integral in one call of quad and the non-infinite endpoint
+            # is far in the tail, quad might return an incorrect result
+            # because it does not "see" the peak of the PDF.
+            intgrl = (integrate.quad(llc, x0, mean,
+                                     epsrel=epsrel, epsabs=epsabs)[0]
+                      + integrate.quad(llc, mean, x1,
+                                       epsrel=epsrel, epsabs=epsabs)[0])
+        else:
+            intgrl = integrate.quad(llc, x0, x1,
+                                    epsrel=epsrel, epsabs=epsabs)[0]
+        if np.isnan(intgrl):
+            msg = ("Infinite values encountered in scipy.special.kve. "
+                   "Values replaced by NaN to avoid incorrect results.")
+            warnings.warn(msg, RuntimeWarning, stacklevel=3)
+        return max(0.0, min(1.0, intgrl))
+
+    def _cdf(self, x, p, a, b):
+        return self._integrate_pdf(-np.inf, x, p, a, b)
+
+    def _sf(self, x, p, a, b):
+        return self._integrate_pdf(x, np.inf, p, a, b)
+
+    def _rvs(self, p, a, b, size=None, random_state=None):
+        # note: X = b * V + sqrt(V) * X  has a
+        # generalized hyperbolic distribution
+        # if X is standard normal and V is
+        # geninvgauss(p = p, b = t2, loc = loc, scale = t3)
+        t1 = np.float_power(a, 2) - np.float_power(b, 2)
+        # b in the GIG
+        t2 = np.float_power(t1, 0.5)
+        # scale in the GIG
+        t3 = np.float_power(t1, - 0.5)
+        gig = geninvgauss.rvs(
+            p=p,
+            b=t2,
+            scale=t3,
+            size=size,
+            random_state=random_state
+            )
+        normst = norm.rvs(size=size, random_state=random_state)
+
+        return b * gig + np.sqrt(gig) * normst
+
+    def _stats(self, p, a, b):
+        # https://mpra.ub.uni-muenchen.de/19081/1/MPRA_paper_19081.pdf
+        # https://freidok.uni-freiburg.de/fedora/objects/freidok:7974/datastreams/FILE1/content
+        # standardized moments
+        p, a, b = np.broadcast_arrays(p, a, b)
+        t1 = np.float_power(a, 2) - np.float_power(b, 2)
+        t1 = np.float_power(t1, 0.5)
+        t2 = np.float_power(1, 2) * np.float_power(t1, - 1)
+        integers = np.linspace(0, 4, 5)
+        # make integers perpendicular to existing dimensions
+        integers = integers.reshape(integers.shape + (1,) * p.ndim)
+        b0, b1, b2, b3, b4 = sc.kv(p + integers, t1)
+        r1, r2, r3, r4 = (b / b0 for b in (b1, b2, b3, b4))
+
+        m = b * t2 * r1
+        v = (
+            t2 * r1 + np.float_power(b, 2) * np.float_power(t2, 2) *
+            (r2 - np.float_power(r1, 2))
+        )
+        m3e = (
+            np.float_power(b, 3) * np.float_power(t2, 3) *
+            (r3 - 3 * b2 * b1 * np.float_power(b0, -2) +
+             2 * np.float_power(r1, 3)) +
+            3 * b * np.float_power(t2, 2) *
+            (r2 - np.float_power(r1, 2))
+        )
+        s = m3e * np.float_power(v, - 3 / 2)
+        m4e = (
+            np.float_power(b, 4) * np.float_power(t2, 4) *
+            (r4 - 4 * b3 * b1 * np.float_power(b0, - 2) +
+             6 * b2 * np.float_power(b1, 2) * np.float_power(b0, - 3) -
+             3 * np.float_power(r1, 4)) +
+            np.float_power(b, 2) * np.float_power(t2, 3) *
+            (6 * r3 - 12 * b2 * b1 * np.float_power(b0, - 2) +
+             6 * np.float_power(r1, 3)) +
+            3 * np.float_power(t2, 2) * r2
+        )
+        k = m4e * np.float_power(v, -2) - 3
+
+        return m, v, s, k
+
+
+genhyperbolic = genhyperbolic_gen(name='genhyperbolic')
+
+
+class gompertz_gen(rv_continuous):
+    r"""A Gompertz (or truncated Gumbel) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `gompertz` is:
+
+    .. math::
+
+        f(x, c) = c \exp(x) \exp(-c (e^x-1))
+
+    for :math:`x \ge 0`, :math:`c > 0`.
+
+    `gompertz` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # gompertz.pdf(x, c) = c * exp(x) * exp(-c*(exp(x)-1))
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        return np.log(c) + x - c * sc.expm1(x)
+
+    def _cdf(self, x, c):
+        return -sc.expm1(-c * sc.expm1(x))
+
+    def _ppf(self, q, c):
+        return sc.log1p(-1.0 / c * sc.log1p(-q))
+
+    def _sf(self, x, c):
+        return np.exp(-c * sc.expm1(x))
+
+    def _isf(self, p, c):
+        return sc.log1p(-np.log(p)/c)
+
+    def _entropy(self, c):
+        return 1.0 - np.log(c) - sc._ufuncs._scaled_exp1(c)/c
+
+
+gompertz = gompertz_gen(a=0.0, name='gompertz')
+
+
+def _average_with_log_weights(x, logweights):
+    x = np.asarray(x)
+    logweights = np.asarray(logweights)
+    maxlogw = logweights.max()
+    weights = np.exp(logweights - maxlogw)
+    return np.average(x, weights=weights)
+
+
+class gumbel_r_gen(rv_continuous):
+    r"""A right-skewed Gumbel continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gumbel_l, gompertz, genextreme
+
+    Notes
+    -----
+    The probability density function for `gumbel_r` is:
+
+    .. math::
+
+        f(x) = \exp(-(x + e^{-x}))
+
+    for real :math:`x`.
+
+    The Gumbel distribution is sometimes referred to as a type I Fisher-Tippett
+    distribution.  It is also related to the extreme value distribution,
+    log-Weibull and Gompertz distributions.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # gumbel_r.pdf(x) = exp(-(x + exp(-x)))
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        return -x - np.exp(-x)
+
+    def _cdf(self, x):
+        return np.exp(-np.exp(-x))
+
+    def _logcdf(self, x):
+        return -np.exp(-x)
+
+    def _ppf(self, q):
+        return -np.log(-np.log(q))
+
+    def _sf(self, x):
+        return -sc.expm1(-np.exp(-x))
+
+    def _isf(self, p):
+        return -np.log(-np.log1p(-p))
+
+    def _stats(self):
+        return _EULER, np.pi*np.pi/6.0, 12*np.sqrt(6)/np.pi**3 * _ZETA3, 12.0/5
+
+    def _entropy(self):
+        # https://en.wikipedia.org/wiki/Gumbel_distribution
+        return _EULER + 1.
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        # By the method of maximum likelihood, the estimators of the
+        # location and scale are the roots of the equations defined in
+        # `func` and the value of the expression for `loc` that follows.
+        # The first `func` is a first order derivative of the log-likelihood
+        # equation and the second is from Source: Statistical Distributions,
+        # 3rd Edition. Evans, Hastings, and Peacock (2000), Page 101.
+
+        def get_loc_from_scale(scale):
+            return -scale * (sc.logsumexp(-data / scale) - np.log(len(data)))
+
+        if fscale is not None:
+            # if the scale is fixed, the location can be analytically
+            # determined.
+            scale = fscale
+            loc = get_loc_from_scale(scale)
+        else:
+            # A different function is solved depending on whether the location
+            # is fixed.
+            if floc is not None:
+                loc = floc
+
+                # equation to use if the location is fixed.
+                # note that one cannot use the equation in Evans, Hastings,
+                # and Peacock (2000) (since it assumes that the derivative
+                # w.r.t. the log-likelihood is zero). however, it is easy to
+                # derive the MLE condition directly if loc is fixed
+                def func(scale):
+                    term1 = (loc - data) * np.exp((loc - data) / scale) + data
+                    term2 = len(data) * (loc + scale)
+                    return term1.sum() - term2
+            else:
+
+                # equation to use if both location and scale are free
+                def func(scale):
+                    sdata = -data / scale
+                    wavg = _average_with_log_weights(data, logweights=sdata)
+                    return data.mean() - wavg - scale
+
+            # set brackets for `root_scalar` to use when optimizing over the
+            # scale such that a root is likely between them. Use user supplied
+            # guess or default 1.
+            brack_start = kwds.get('scale', 1)
+            lbrack, rbrack = brack_start / 2, brack_start * 2
+
+            # if a root is not between the brackets, iteratively expand them
+            # until they include a sign change, checking after each bracket is
+            # modified.
+            def interval_contains_root(lbrack, rbrack):
+                # return true if the signs disagree.
+                return (np.sign(func(lbrack)) !=
+                        np.sign(func(rbrack)))
+            while (not interval_contains_root(lbrack, rbrack)
+                   and (lbrack > 0 or rbrack < np.inf)):
+                lbrack /= 2
+                rbrack *= 2
+
+            res = optimize.root_scalar(func, bracket=(lbrack, rbrack),
+                                       rtol=1e-14, xtol=1e-14)
+            scale = res.root
+            loc = floc if floc is not None else get_loc_from_scale(scale)
+        return loc, scale
+
+
+gumbel_r = gumbel_r_gen(name='gumbel_r')
+
+
+class gumbel_l_gen(rv_continuous):
+    r"""A left-skewed Gumbel continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gumbel_r, gompertz, genextreme
+
+    Notes
+    -----
+    The probability density function for `gumbel_l` is:
+
+    .. math::
+
+        f(x) = \exp(x - e^x)
+
+    for real :math:`x`.
+
+    The Gumbel distribution is sometimes referred to as a type I Fisher-Tippett
+    distribution.  It is also related to the extreme value distribution,
+    log-Weibull and Gompertz distributions.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # gumbel_l.pdf(x) = exp(x - exp(x))
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        return x - np.exp(x)
+
+    def _cdf(self, x):
+        return -sc.expm1(-np.exp(x))
+
+    def _ppf(self, q):
+        return np.log(-sc.log1p(-q))
+
+    def _logsf(self, x):
+        return -np.exp(x)
+
+    def _sf(self, x):
+        return np.exp(-np.exp(x))
+
+    def _isf(self, x):
+        return np.log(-np.log(x))
+
+    def _stats(self):
+        return -_EULER, np.pi*np.pi/6.0, \
+               -12*np.sqrt(6)/np.pi**3 * _ZETA3, 12.0/5
+
+    def _entropy(self):
+        return _EULER + 1.
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        # The fit method of `gumbel_r` can be used for this distribution with
+        # small modifications. The process to do this is
+        # 1. pass the sign negated data into `gumbel_r.fit`
+        #    - if the location is fixed, it should also be negated.
+        # 2. negate the sign of the resulting location, leaving the scale
+        #    unmodified.
+        # `gumbel_r.fit` holds necessary input checks.
+
+        if kwds.get('floc') is not None:
+            kwds['floc'] = -kwds['floc']
+        loc_r, scale_r, = gumbel_r.fit(-np.asarray(data), *args, **kwds)
+        return -loc_r, scale_r
+
+
+gumbel_l = gumbel_l_gen(name='gumbel_l')
+
+
+class halfcauchy_gen(rv_continuous):
+    r"""A Half-Cauchy continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `halfcauchy` is:
+
+    .. math::
+
+        f(x) = \frac{2}{\pi (1 + x^2)}
+
+    for :math:`x \ge 0`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # halfcauchy.pdf(x) = 2 / (pi * (1 + x**2))
+        return 2.0/np.pi/(1.0+x*x)
+
+    def _logpdf(self, x):
+        return np.log(2.0/np.pi) - sc.log1p(x*x)
+
+    def _cdf(self, x):
+        return 2.0/np.pi*np.arctan(x)
+
+    def _ppf(self, q):
+        return np.tan(np.pi/2*q)
+
+    def _sf(self, x):
+        return 2.0/np.pi * np.arctan2(1, x)
+
+    def _isf(self, p):
+        return 1.0/np.tan(np.pi*p/2)
+
+    def _stats(self):
+        return np.inf, np.inf, np.nan, np.nan
+
+    def _entropy(self):
+        return np.log(2*np.pi)
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        # location is independent from the scale
+        data_min = np.min(data)
+        if floc is not None:
+            if data_min < floc:
+                # There are values that are less than the specified loc.
+                raise FitDataError("halfcauchy", lower=floc, upper=np.inf)
+            loc = floc
+        else:
+            # if not provided, location MLE is the minimal data point
+            loc = data_min
+
+        # find scale
+        def find_scale(loc, data):
+            shifted_data = data - loc
+            n = data.size
+            shifted_data_squared = np.square(shifted_data)
+
+            def fun_to_solve(scale):
+                denominator = scale**2 + shifted_data_squared
+                return 2 * np.sum(shifted_data_squared/denominator) - n
+
+            small = np.finfo(1.0).tiny**0.5  # avoid underflow
+            res = root_scalar(fun_to_solve, bracket=(small, np.max(shifted_data)))
+            return res.root
+
+        if fscale is not None:
+            scale = fscale
+        else:
+            scale = find_scale(loc, data)
+
+        return loc, scale
+
+
+halfcauchy = halfcauchy_gen(a=0.0, name='halfcauchy')
+
+
+class halflogistic_gen(rv_continuous):
+    r"""A half-logistic continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `halflogistic` is:
+
+    .. math::
+
+        f(x) = \frac{ 2 e^{-x} }{ (1+e^{-x})^2 }
+             = \frac{1}{2} \text{sech}(x/2)^2
+
+    for :math:`x \ge 0`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Asgharzadeh et al (2011). "Comparisons of Methods of Estimation for the
+           Half-Logistic Distribution". Selcuk J. Appl. Math. 93-108.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # halflogistic.pdf(x) = 2 * exp(-x) / (1+exp(-x))**2
+        #                     = 1/2 * sech(x/2)**2
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        return np.log(2) - x - 2. * sc.log1p(np.exp(-x))
+
+    def _cdf(self, x):
+        return np.tanh(x/2.0)
+
+    def _ppf(self, q):
+        return 2*np.arctanh(q)
+
+    def _sf(self, x):
+        return 2 * sc.expit(-x)
+
+    def _isf(self, q):
+        return _lazywhere(q < 0.5, (q, ),
+                          lambda q: -sc.logit(0.5 * q),
+                          f2=lambda q: 2*np.arctanh(1 - q))
+
+    def _munp(self, n):
+        if n == 0:
+            return 1  # otherwise returns NaN
+        if n == 1:
+            return 2*np.log(2)
+        if n == 2:
+            return np.pi*np.pi/3.0
+        if n == 3:
+            return 9*_ZETA3
+        if n == 4:
+            return 7*np.pi**4 / 15.0
+        return 2*(1-pow(2.0, 1-n))*sc.gamma(n+1)*sc.zeta(n, 1)
+
+    def _entropy(self):
+        return 2-np.log(2)
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        def find_scale(data, loc):
+            # scale is solution to a fix point problem ([1] 2.6)
+            # use approximate MLE as starting point ([1] 3.1)
+            n_observations = data.shape[0]
+            sorted_data = np.sort(data, axis=0)
+            p = np.arange(1, n_observations + 1)/(n_observations + 1)
+            q = 1 - p
+            pp1 = 1 + p
+            alpha = p - 0.5 * q * pp1 * np.log(pp1 / q)
+            beta = 0.5 * q * pp1
+            sorted_data = sorted_data - loc
+            B = 2 * np.sum(alpha[1:] * sorted_data[1:])
+            C = 2 * np.sum(beta[1:] * sorted_data[1:]**2)
+            # starting guess
+            scale = ((B + np.sqrt(B**2 + 8 * n_observations * C))
+                    /(4 * n_observations))
+
+            # relative tolerance of fix point iterator
+            rtol = 1e-8
+            relative_residual = 1
+            shifted_mean = sorted_data.mean()  # y_mean - y_min
+
+            # find fix point by repeated application of eq. (2.6)
+            # simplify as
+            # exp(-x) / (1 + exp(-x)) = 1 / (1 + exp(x))
+            #                         = expit(-x))
+            while relative_residual > rtol:
+                sum_term = sorted_data * sc.expit(-sorted_data/scale)
+                scale_new = shifted_mean - 2/n_observations * sum_term.sum()
+                relative_residual = abs((scale - scale_new)/scale)
+                scale = scale_new
+            return scale
+
+        # location is independent from the scale
+        data_min = np.min(data)
+        if floc is not None:
+            if data_min < floc:
+                # There are values that are less than the specified loc.
+                raise FitDataError("halflogistic", lower=floc, upper=np.inf)
+            loc = floc
+        else:
+            # if not provided, location MLE is the minimal data point
+            loc = data_min
+
+        # scale depends on location
+        scale = fscale if fscale is not None else find_scale(data, loc)
+
+        return loc, scale
+
+
+halflogistic = halflogistic_gen(a=0.0, name='halflogistic')
+
+
+class halfnorm_gen(rv_continuous):
+    r"""A half-normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `halfnorm` is:
+
+    .. math::
+
+        f(x) = \sqrt{2/\pi} \exp(-x^2 / 2)
+
+    for :math:`x >= 0`.
+
+    `halfnorm` is a special case of `chi` with ``df=1``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return abs(random_state.standard_normal(size=size))
+
+    def _pdf(self, x):
+        # halfnorm.pdf(x) = sqrt(2/pi) * exp(-x**2/2)
+        return np.sqrt(2.0/np.pi)*np.exp(-x*x/2.0)
+
+    def _logpdf(self, x):
+        return 0.5 * np.log(2.0/np.pi) - x*x/2.0
+
+    def _cdf(self, x):
+        return sc.erf(x / np.sqrt(2))
+
+    def _ppf(self, q):
+        return _norm_ppf((1+q)/2.0)
+
+    def _sf(self, x):
+        return 2 * _norm_sf(x)
+
+    def _isf(self, p):
+        return _norm_isf(p/2)
+
+    def _stats(self):
+        return (np.sqrt(2.0/np.pi),
+                1-2.0/np.pi,
+                np.sqrt(2)*(4-np.pi)/(np.pi-2)**1.5,
+                8*(np.pi-3)/(np.pi-2)**2)
+
+    def _entropy(self):
+        return 0.5*np.log(np.pi/2.0)+0.5
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        data_min = np.min(data)
+
+        if floc is not None:
+            if data_min < floc:
+                # There are values that are less than the specified loc.
+                raise FitDataError("halfnorm", lower=floc, upper=np.inf)
+            loc = floc
+        else:
+            loc = data_min
+
+        if fscale is not None:
+            scale = fscale
+        else:
+            scale = stats.moment(data, order=2, center=loc)**0.5
+
+        return loc, scale
+
+
+halfnorm = halfnorm_gen(a=0.0, name='halfnorm')
+
+
+class hypsecant_gen(rv_continuous):
+    r"""A hyperbolic secant continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `hypsecant` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\pi} \text{sech}(x)
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # hypsecant.pdf(x) = 1/pi * sech(x)
+        return 1.0/(np.pi*np.cosh(x))
+
+    def _cdf(self, x):
+        return 2.0/np.pi*np.arctan(np.exp(x))
+
+    def _ppf(self, q):
+        return np.log(np.tan(np.pi*q/2.0))
+
+    def _sf(self, x):
+        return 2.0/np.pi*np.arctan(np.exp(-x))
+
+    def _isf(self, q):
+        return -np.log(np.tan(np.pi*q/2.0))
+
+    def _stats(self):
+        return 0, np.pi*np.pi/4, 0, 2
+
+    def _entropy(self):
+        return np.log(2*np.pi)
+
+
+hypsecant = hypsecant_gen(name='hypsecant')
+
+
+class gausshyper_gen(rv_continuous):
+    r"""A Gauss hypergeometric continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `gausshyper` is:
+
+    .. math::
+
+        f(x, a, b, c, z) = C x^{a-1} (1-x)^{b-1} (1+zx)^{-c}
+
+    for :math:`0 \le x \le 1`, :math:`a,b > 0`, :math:`c` a real number,
+    :math:`z > -1`, and :math:`C = \frac{1}{B(a, b) F[2, 1](c, a; a+b; -z)}`.
+    :math:`F[2, 1]` is the Gauss hypergeometric function
+    `scipy.special.hyp2f1`.
+
+    `gausshyper` takes :math:`a`, :math:`b`, :math:`c` and :math:`z` as shape
+    parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Armero, C., and M. J. Bayarri. "Prior Assessments for Prediction in
+           Queues." *Journal of the Royal Statistical Society*. Series D (The
+           Statistician) 43, no. 1 (1994): 139-53. doi:10.2307/2348939
+
+    %(example)s
+
+    """
+
+    def _argcheck(self, a, b, c, z):
+        # z > -1 per gh-10134
+        return (a > 0) & (b > 0) & (c == c) & (z > -1)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (-np.inf, np.inf), (False, False))
+        iz = _ShapeInfo("z", False, (-1, np.inf), (False, False))
+        return [ia, ib, ic, iz]
+
+    def _pdf(self, x, a, b, c, z):
+        normalization_constant = sc.beta(a, b) * sc.hyp2f1(c, a, a + b, -z)
+        return (1./normalization_constant * x**(a - 1.) * (1. - x)**(b - 1.0)
+                / (1.0 + z*x)**c)
+
+    def _munp(self, n, a, b, c, z):
+        fac = sc.beta(n+a, b) / sc.beta(a, b)
+        num = sc.hyp2f1(c, a+n, a+b+n, -z)
+        den = sc.hyp2f1(c, a, a+b, -z)
+        return fac*num / den
+
+
+gausshyper = gausshyper_gen(a=0.0, b=1.0, name='gausshyper')
+
+
+class invgamma_gen(rv_continuous):
+    r"""An inverted gamma continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `invgamma` is:
+
+    .. math::
+
+        f(x, a) = \frac{x^{-a-1}}{\Gamma(a)} \exp(-\frac{1}{x})
+
+    for :math:`x >= 0`, :math:`a > 0`. :math:`\Gamma` is the gamma function
+    (`scipy.special.gamma`).
+
+    `invgamma` takes ``a`` as a shape parameter for :math:`a`.
+
+    `invgamma` is a special case of `gengamma` with ``c=-1``, and it is a
+    different parameterization of the scaled inverse chi-squared distribution.
+    Specifically, if the scaled inverse chi-squared distribution is
+    parameterized with degrees of freedom :math:`\nu` and scaling parameter
+    :math:`\tau^2`, then it can be modeled using `invgamma` with
+    ``a=`` :math:`\nu/2` and ``scale=`` :math:`\nu \tau^2/2`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        # invgamma.pdf(x, a) = x**(-a-1) / gamma(a) * exp(-1/x)
+        return np.exp(self._logpdf(x, a))
+
+    def _logpdf(self, x, a):
+        return -(a+1) * np.log(x) - sc.gammaln(a) - 1.0/x
+
+    def _cdf(self, x, a):
+        return sc.gammaincc(a, 1.0 / x)
+
+    def _ppf(self, q, a):
+        return 1.0 / sc.gammainccinv(a, q)
+
+    def _sf(self, x, a):
+        return sc.gammainc(a, 1.0 / x)
+
+    def _isf(self, q, a):
+        return 1.0 / sc.gammaincinv(a, q)
+
+    def _stats(self, a, moments='mvsk'):
+        m1 = _lazywhere(a > 1, (a,), lambda x: 1. / (x - 1.), np.inf)
+        m2 = _lazywhere(a > 2, (a,), lambda x: 1. / (x - 1.)**2 / (x - 2.),
+                        np.inf)
+
+        g1, g2 = None, None
+        if 's' in moments:
+            g1 = _lazywhere(
+                a > 3, (a,),
+                lambda x: 4. * np.sqrt(x - 2.) / (x - 3.), np.nan)
+        if 'k' in moments:
+            g2 = _lazywhere(
+                a > 4, (a,),
+                lambda x: 6. * (5. * x - 11.) / (x - 3.) / (x - 4.), np.nan)
+        return m1, m2, g1, g2
+
+    def _entropy(self, a):
+        def regular(a):
+            h = a - (a + 1.0) * sc.psi(a) + sc.gammaln(a)
+            return h
+
+        def asymptotic(a):
+            # gammaln(a) ~ a * ln(a) - a - 0.5 * ln(a) + 0.5 * ln(2 * pi)
+            # psi(a) ~ ln(a) - 1 / (2 * a)
+            h = ((1 - 3*np.log(a) + np.log(2) + np.log(np.pi))/2
+                 + 2/3*a**-1. + a**-2./12 - a**-3./90 - a**-4./120)
+            return h
+
+        h = _lazywhere(a >= 2e2, (a,), f=asymptotic, f2=regular)
+        return h
+
+
+invgamma = invgamma_gen(a=0.0, name='invgamma')
+
+
+class invgauss_gen(rv_continuous):
+    r"""An inverse Gaussian continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `invgauss` is:
+
+    .. math::
+
+        f(x; \mu) = \frac{1}{\sqrt{2 \pi x^3}}
+                    \exp\left(-\frac{(x-\mu)^2}{2 \mu^2 x}\right)
+
+    for :math:`x \ge 0` and :math:`\mu > 0`.
+
+    `invgauss` takes ``mu`` as a shape parameter for :math:`\mu`.
+
+    %(after_notes)s
+
+    A common shape-scale parameterization of the inverse Gaussian distribution
+    has density
+
+    .. math::
+
+        f(x; \nu, \lambda) = \sqrt{\frac{\lambda}{2 \pi x^3}}
+                    \exp\left( -\frac{\lambda(x-\nu)^2}{2 \nu^2 x}\right)
+
+    Using ``nu`` for :math:`\nu` and ``lam`` for :math:`\lambda`, this
+    parameterization is equivalent to the one above with ``mu = nu/lam``,
+    ``loc = 0``, and ``scale = lam``.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``ppf`` and ``isf`` methods. [1]_
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("mu", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, mu, size=None, random_state=None):
+        return random_state.wald(mu, 1.0, size=size)
+
+    def _pdf(self, x, mu):
+        # invgauss.pdf(x, mu) =
+        #                  1 / sqrt(2*pi*x**3) * exp(-(x-mu)**2/(2*x*mu**2))
+        return 1.0/np.sqrt(2*np.pi*x**3.0)*np.exp(-1.0/(2*x)*((x-mu)/mu)**2)
+
+    def _logpdf(self, x, mu):
+        return -0.5*np.log(2*np.pi) - 1.5*np.log(x) - ((x-mu)/mu)**2/(2*x)
+
+    # approach adapted from equations in
+    # https://journal.r-project.org/archive/2016-1/giner-smyth.pdf,
+    # not R code. see gh-13616
+
+    def _logcdf(self, x, mu):
+        fac = 1 / np.sqrt(x)
+        a = _norm_logcdf(fac * ((x / mu) - 1))
+        b = 2 / mu + _norm_logcdf(-fac * ((x / mu) + 1))
+        return a + np.log1p(np.exp(b - a))
+
+    def _logsf(self, x, mu):
+        fac = 1 / np.sqrt(x)
+        a = _norm_logsf(fac * ((x / mu) - 1))
+        b = 2 / mu + _norm_logcdf(-fac * (x + mu) / mu)
+        return a + np.log1p(-np.exp(b - a))
+
+    def _sf(self, x, mu):
+        return np.exp(self._logsf(x, mu))
+
+    def _cdf(self, x, mu):
+        return np.exp(self._logcdf(x, mu))
+
+    def _ppf(self, x, mu):
+        with np.errstate(divide='ignore', over='ignore', invalid='ignore'):
+            x, mu = np.broadcast_arrays(x, mu)
+            ppf = np.asarray(scu._invgauss_ppf(x, mu, 1))
+            i_wt = x > 0.5  # "wrong tail" - sometimes too inaccurate
+            ppf[i_wt] = scu._invgauss_isf(1-x[i_wt], mu[i_wt], 1)
+            i_nan = np.isnan(ppf)
+            ppf[i_nan] = super()._ppf(x[i_nan], mu[i_nan])
+        return ppf
+
+    def _isf(self, x, mu):
+        with np.errstate(divide='ignore', over='ignore', invalid='ignore'):
+            x, mu = np.broadcast_arrays(x, mu)
+            isf = scu._invgauss_isf(x, mu, 1)
+            i_wt = x > 0.5  # "wrong tail" - sometimes too inaccurate
+            isf[i_wt] = scu._invgauss_ppf(1-x[i_wt], mu[i_wt], 1)
+            i_nan = np.isnan(isf)
+            isf[i_nan] = super()._isf(x[i_nan], mu[i_nan])
+        return isf
+
+    def _stats(self, mu):
+        return mu, mu**3.0, 3*np.sqrt(mu), 15*mu
+
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        method = kwds.get('method', 'mle')
+
+        if (isinstance(data, CensoredData) or isinstance(self, wald_gen)
+                or method.lower() == 'mm'):
+            return super().fit(data, *args, **kwds)
+
+        data, fshape_s, floc, fscale = _check_fit_input_parameters(self, data,
+                                                                   args, kwds)
+        '''
+        Source: Statistical Distributions, 3rd Edition. Evans, Hastings,
+        and Peacock (2000), Page 121. Their shape parameter is equivalent to
+        SciPy's with the conversion `fshape_s = fshape / scale`.
+
+        MLE formulas are not used in 3 conditions:
+        - `loc` is not fixed
+        - `mu` is fixed
+        These cases fall back on the superclass fit method.
+        - `loc` is fixed but translation results in negative data raises
+          a `FitDataError`.
+        '''
+        if floc is None or fshape_s is not None:
+            return super().fit(data, *args, **kwds)
+        elif np.any(data - floc < 0):
+            raise FitDataError("invgauss", lower=0, upper=np.inf)
+        else:
+            data = data - floc
+            fshape_n = np.mean(data)
+            if fscale is None:
+                fscale = len(data) / (np.sum(data ** -1 - fshape_n ** -1))
+            fshape_s = fshape_n / fscale
+        return fshape_s, floc, fscale
+
+    def _entropy(self, mu):
+        """
+        Ref.: https://moser-isi.ethz.ch/docs/papers/smos-2012-10.pdf (eq. 9)
+        """
+        # a = log(2*pi*e*mu**3)
+        #   = 1 + log(2*pi) + 3 * log(mu)
+        a = 1. + np.log(2 * np.pi) + 3 * np.log(mu)
+        # b = exp(2/mu) * exp1(2/mu)
+        #   = _scaled_exp1(2/mu) / (2/mu)
+        r = 2/mu
+        b = sc._ufuncs._scaled_exp1(r)/r
+        return 0.5 * a - 1.5 * b
+
+
+invgauss = invgauss_gen(a=0.0, name='invgauss')
+
+
+class geninvgauss_gen(rv_continuous):
+    r"""A Generalized Inverse Gaussian continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `geninvgauss` is:
+
+    .. math::
+
+        f(x, p, b) = x^{p-1} \exp(-b (x + 1/x) / 2) / (2 K_p(b))
+
+    where ``x > 0``, `p` is a real number and ``b > 0``\([1]_).
+    :math:`K_p` is the modified Bessel function of second kind of order `p`
+    (`scipy.special.kv`).
+
+    %(after_notes)s
+
+    The inverse Gaussian distribution `stats.invgauss(mu)` is a special case of
+    `geninvgauss` with ``p = -1/2``, ``b = 1 / mu`` and ``scale = mu``.
+
+    Generating random variates is challenging for this distribution. The
+    implementation is based on [2]_.
+
+    References
+    ----------
+    .. [1] O. Barndorff-Nielsen, P. Blaesild, C. Halgreen, "First hitting time
+       models for the generalized inverse gaussian distribution",
+       Stochastic Processes and their Applications 7, pp. 49--54, 1978.
+
+    .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian
+       random variates", Statistics and Computing, 24(4), p. 547--557, 2014.
+
+    %(example)s
+
+    """
+    def _argcheck(self, p, b):
+        return (p == p) & (b > 0)
+
+    def _shape_info(self):
+        ip = _ShapeInfo("p", False, (-np.inf, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ip, ib]
+
+    def _logpdf(self, x, p, b):
+        # kve instead of kv works better for large values of b
+        # warn if kve produces infinite values and replace by nan
+        # otherwise c = -inf and the results are often incorrect
+        def logpdf_single(x, p, b):
+            return _stats.geninvgauss_logpdf(x, p, b)
+
+        logpdf_single = np.vectorize(logpdf_single, otypes=[np.float64])
+
+        z = logpdf_single(x, p, b)
+        if np.isnan(z).any():
+            msg = ("Infinite values encountered in scipy.special.kve(p, b). "
+                   "Values replaced by NaN to avoid incorrect results.")
+            warnings.warn(msg, RuntimeWarning, stacklevel=3)
+        return z
+
+    def _pdf(self, x, p, b):
+        # relying on logpdf avoids overflow of x**(p-1) for large x and p
+        return np.exp(self._logpdf(x, p, b))
+
+    def _cdf(self, x, p, b):
+        _a, _b = self._get_support(p, b)
+
+        def _cdf_single(x, p, b):
+            user_data = np.array([p, b], float).ctypes.data_as(ctypes.c_void_p)
+            llc = LowLevelCallable.from_cython(_stats, '_geninvgauss_pdf',
+                                               user_data)
+
+            return integrate.quad(llc, _a, x)[0]
+
+        _cdf_single = np.vectorize(_cdf_single, otypes=[np.float64])
+
+        return _cdf_single(x, p, b)
+
+    def _logquasipdf(self, x, p, b):
+        # log of the quasi-density (w/o normalizing constant) used in _rvs
+        return _lazywhere(x > 0, (x, p, b),
+                          lambda x, p, b: (p - 1)*np.log(x) - b*(x + 1/x)/2,
+                          -np.inf)
+
+    def _rvs(self, p, b, size=None, random_state=None):
+        # if p and b are scalar, use _rvs_scalar, otherwise need to create
+        # output by iterating over parameters
+        if np.isscalar(p) and np.isscalar(b):
+            out = self._rvs_scalar(p, b, size, random_state)
+        elif p.size == 1 and b.size == 1:
+            out = self._rvs_scalar(p.item(), b.item(), size, random_state)
+        else:
+            # When this method is called, size will be a (possibly empty)
+            # tuple of integers.  It will not be None; if `size=None` is passed
+            # to `rvs()`, size will be the empty tuple ().
+
+            p, b = np.broadcast_arrays(p, b)
+            # p and b now have the same shape.
+
+            # `shp` is the shape of the blocks of random variates that are
+            # generated for each combination of parameters associated with
+            # broadcasting p and b.
+            # bc is a tuple the same length as size.  The values
+            # in bc are bools.  If bc[j] is True, it means that
+            # entire axis is filled in for a given combination of the
+            # broadcast arguments.
+            shp, bc = _check_shape(p.shape, size)
+
+            # `numsamples` is the total number of variates to be generated
+            # for each combination of the input arguments.
+            numsamples = int(np.prod(shp))
+
+            # `out` is the array to be returned.  It is filled in the
+            # loop below.
+            out = np.empty(size)
+
+            it = np.nditer([p, b],
+                           flags=['multi_index'],
+                           op_flags=[['readonly'], ['readonly']])
+            while not it.finished:
+                # Convert the iterator's multi_index into an index into the
+                # `out` array where the call to _rvs_scalar() will be stored.
+                # Where bc is True, we use a full slice; otherwise we use the
+                # index value from it.multi_index.  len(it.multi_index) might
+                # be less than len(bc), and in that case we want to align these
+                # two sequences to the right, so the loop variable j runs from
+                # -len(size) to 0.  This doesn't cause an IndexError, as
+                # bc[j] will be True in those cases where it.multi_index[j]
+                # would cause an IndexError.
+                idx = tuple((it.multi_index[j] if not bc[j] else slice(None))
+                            for j in range(-len(size), 0))
+                out[idx] = self._rvs_scalar(it[0], it[1], numsamples,
+                                            random_state).reshape(shp)
+                it.iternext()
+
+        if size == ():
+            out = out.item()
+        return out
+
+    def _rvs_scalar(self, p, b, numsamples, random_state):
+        # following [2], the quasi-pdf is used instead of the pdf for the
+        # generation of rvs
+        invert_res = False
+        if not numsamples:
+            numsamples = 1
+        if p < 0:
+            # note: if X is geninvgauss(p, b), then 1/X is geninvgauss(-p, b)
+            p = -p
+            invert_res = True
+        m = self._mode(p, b)
+
+        # determine method to be used following [2]
+        ratio_unif = True
+        if p >= 1 or b > 1:
+            # ratio of uniforms with mode shift below
+            mode_shift = True
+        elif b >= min(0.5, 2 * np.sqrt(1 - p) / 3):
+            # ratio of uniforms without mode shift below
+            mode_shift = False
+        else:
+            # new algorithm in [2]
+            ratio_unif = False
+
+        # prepare sampling of rvs
+        size1d = tuple(np.atleast_1d(numsamples))
+        N = np.prod(size1d)  # number of rvs needed, reshape upon return
+        x = np.zeros(N)
+        simulated = 0
+
+        if ratio_unif:
+            # use ratio of uniforms method
+            if mode_shift:
+                a2 = -2 * (p + 1) / b - m
+                a1 = 2 * m * (p - 1) / b - 1
+                # find roots of x**3 + a2*x**2 + a1*x + m (Cardano's formula)
+                p1 = a1 - a2**2 / 3
+                q1 = 2 * a2**3 / 27 - a2 * a1 / 3 + m
+                phi = np.arccos(-q1 * np.sqrt(-27 / p1**3) / 2)
+                s1 = -np.sqrt(-4 * p1 / 3)
+                root1 = s1 * np.cos(phi / 3 + np.pi / 3) - a2 / 3
+                root2 = -s1 * np.cos(phi / 3) - a2 / 3
+                # root3 = s1 * np.cos(phi / 3 - np.pi / 3) - a2 / 3
+
+                # if g is the quasipdf, rescale: g(x) / g(m) which we can write
+                # as exp(log(g(x)) - log(g(m))). This is important
+                # since for large values of p and b, g cannot be evaluated.
+                # denote the rescaled quasipdf by h
+                lm = self._logquasipdf(m, p, b)
+                d1 = self._logquasipdf(root1, p, b) - lm
+                d2 = self._logquasipdf(root2, p, b) - lm
+                # compute the bounding rectangle w.r.t. h. Note that
+                # np.exp(0.5*d1) = np.sqrt(g(root1)/g(m)) = np.sqrt(h(root1))
+                vmin = (root1 - m) * np.exp(0.5 * d1)
+                vmax = (root2 - m) * np.exp(0.5 * d2)
+                umax = 1  # umax = sqrt(h(m)) = 1
+
+                def logqpdf(x):
+                    return self._logquasipdf(x, p, b) - lm
+
+                c = m
+            else:
+                # ratio of uniforms without mode shift
+                # compute np.sqrt(quasipdf(m))
+                umax = np.exp(0.5*self._logquasipdf(m, p, b))
+                xplus = ((1 + p) + np.sqrt((1 + p)**2 + b**2))/b
+                vmin = 0
+                # compute xplus * np.sqrt(quasipdf(xplus))
+                vmax = xplus * np.exp(0.5 * self._logquasipdf(xplus, p, b))
+                c = 0
+
+                def logqpdf(x):
+                    return self._logquasipdf(x, p, b)
+
+            if vmin >= vmax:
+                raise ValueError("vmin must be smaller than vmax.")
+            if umax <= 0:
+                raise ValueError("umax must be positive.")
+
+            i = 1
+            while simulated < N:
+                k = N - simulated
+                # simulate uniform rvs on [0, umax] and [vmin, vmax]
+                u = umax * random_state.uniform(size=k)
+                v = random_state.uniform(size=k)
+                v = vmin + (vmax - vmin) * v
+                rvs = v / u + c
+                # rewrite acceptance condition u**2 <= pdf(rvs) by taking logs
+                accept = (2*np.log(u) <= logqpdf(rvs))
+                num_accept = np.sum(accept)
+                if num_accept > 0:
+                    x[simulated:(simulated + num_accept)] = rvs[accept]
+                    simulated += num_accept
+
+                if (simulated == 0) and (i*N >= 50000):
+                    msg = ("Not a single random variate could be generated "
+                           f"in {i*N} attempts. Sampling does not appear to "
+                           "work for the provided parameters.")
+                    raise RuntimeError(msg)
+                i += 1
+        else:
+            # use new algorithm in [2]
+            x0 = b / (1 - p)
+            xs = np.max((x0, 2 / b))
+            k1 = np.exp(self._logquasipdf(m, p, b))
+            A1 = k1 * x0
+            if x0 < 2 / b:
+                k2 = np.exp(-b)
+                if p > 0:
+                    A2 = k2 * ((2 / b)**p - x0**p) / p
+                else:
+                    A2 = k2 * np.log(2 / b**2)
+            else:
+                k2, A2 = 0, 0
+            k3 = xs**(p - 1)
+            A3 = 2 * k3 * np.exp(-xs * b / 2) / b
+            A = A1 + A2 + A3
+
+            # [2]: rejection constant is < 2.73; so expected runtime is finite
+            while simulated < N:
+                k = N - simulated
+                h, rvs = np.zeros(k), np.zeros(k)
+                # simulate uniform rvs on [x1, x2] and [0, y2]
+                u = random_state.uniform(size=k)
+                v = A * random_state.uniform(size=k)
+                cond1 = v <= A1
+                cond2 = np.logical_not(cond1) & (v <= A1 + A2)
+                cond3 = np.logical_not(cond1 | cond2)
+                # subdomain (0, x0)
+                rvs[cond1] = x0 * v[cond1] / A1
+                h[cond1] = k1
+                # subdomain (x0, 2 / b)
+                if p > 0:
+                    rvs[cond2] = (x0**p + (v[cond2] - A1) * p / k2)**(1 / p)
+                else:
+                    rvs[cond2] = b * np.exp((v[cond2] - A1) * np.exp(b))
+                h[cond2] = k2 * rvs[cond2]**(p - 1)
+                # subdomain (xs, infinity)
+                z = np.exp(-xs * b / 2) - b * (v[cond3] - A1 - A2) / (2 * k3)
+                rvs[cond3] = -2 / b * np.log(z)
+                h[cond3] = k3 * np.exp(-rvs[cond3] * b / 2)
+                # apply rejection method
+                accept = (np.log(u * h) <= self._logquasipdf(rvs, p, b))
+                num_accept = sum(accept)
+                if num_accept > 0:
+                    x[simulated:(simulated + num_accept)] = rvs[accept]
+                    simulated += num_accept
+
+        rvs = np.reshape(x, size1d)
+        if invert_res:
+            rvs = 1 / rvs
+        return rvs
+
+    def _mode(self, p, b):
+        # distinguish cases to avoid catastrophic cancellation (see [2])
+        if p < 1:
+            return b / (np.sqrt((p - 1)**2 + b**2) + 1 - p)
+        else:
+            return (np.sqrt((1 - p)**2 + b**2) - (1 - p)) / b
+
+    def _munp(self, n, p, b):
+        num = sc.kve(p + n, b)
+        denom = sc.kve(p, b)
+        inf_vals = np.isinf(num) | np.isinf(denom)
+        if inf_vals.any():
+            msg = ("Infinite values encountered in the moment calculation "
+                   "involving scipy.special.kve. Values replaced by NaN to "
+                   "avoid incorrect results.")
+            warnings.warn(msg, RuntimeWarning, stacklevel=3)
+            m = np.full_like(num, np.nan, dtype=np.float64)
+            m[~inf_vals] = num[~inf_vals] / denom[~inf_vals]
+        else:
+            m = num / denom
+        return m
+
+
+geninvgauss = geninvgauss_gen(a=0.0, name="geninvgauss")
+
+
+class norminvgauss_gen(rv_continuous):
+    r"""A Normal Inverse Gaussian continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `norminvgauss` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{a \, K_1(a \sqrt{1 + x^2})}{\pi \sqrt{1 + x^2}} \,
+                     \exp(\sqrt{a^2 - b^2} + b x)
+
+    where :math:`x` is a real number, the parameter :math:`a` is the tail
+    heaviness and :math:`b` is the asymmetry parameter satisfying
+    :math:`a > 0` and :math:`|b| <= a`.
+    :math:`K_1` is the modified Bessel function of second kind
+    (`scipy.special.k1`).
+
+    %(after_notes)s
+
+    A normal inverse Gaussian random variable `Y` with parameters `a` and `b`
+    can be expressed as a normal mean-variance mixture:
+    ``Y = b * V + sqrt(V) * X`` where `X` is ``norm(0,1)`` and `V` is
+    ``invgauss(mu=1/sqrt(a**2 - b**2))``. This representation is used
+    to generate random variates.
+
+    Another common parametrization of the distribution (see Equation 2.1 in
+    [2]_) is given by the following expression of the pdf:
+
+    .. math::
+
+        g(x, \alpha, \beta, \delta, \mu) =
+        \frac{\alpha\delta K_1\left(\alpha\sqrt{\delta^2 + (x - \mu)^2}\right)}
+        {\pi \sqrt{\delta^2 + (x - \mu)^2}} \,
+        e^{\delta \sqrt{\alpha^2 - \beta^2} + \beta (x - \mu)}
+
+    In SciPy, this corresponds to
+    `a = alpha * delta, b = beta * delta, loc = mu, scale=delta`.
+
+    References
+    ----------
+    .. [1] O. Barndorff-Nielsen, "Hyperbolic Distributions and Distributions on
+           Hyperbolae", Scandinavian Journal of Statistics, Vol. 5(3),
+           pp. 151-157, 1978.
+
+    .. [2] O. Barndorff-Nielsen, "Normal Inverse Gaussian Distributions and
+           Stochastic Volatility Modelling", Scandinavian Journal of
+           Statistics, Vol. 24, pp. 1-13, 1997.
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _argcheck(self, a, b):
+        return (a > 0) & (np.absolute(b) < a)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, False))
+        return [ia, ib]
+
+    def _fitstart(self, data):
+        # Arbitrary, but the default a = b = 1 is not valid; the distribution
+        # requires |b| < a.
+        return super()._fitstart(data, args=(1, 0.5))
+
+    def _pdf(self, x, a, b):
+        gamma = np.sqrt(a**2 - b**2)
+        fac1 = a / np.pi
+        sq = np.hypot(1, x)  # reduce overflows
+        return fac1 * sc.k1e(a * sq) * np.exp(b*x - a*sq + gamma) / sq
+
+    def _sf(self, x, a, b):
+        if np.isscalar(x):
+            # If x is a scalar, then so are a and b.
+            return integrate.quad(self._pdf, x, np.inf, args=(a, b))[0]
+        else:
+            a = np.atleast_1d(a)
+            b = np.atleast_1d(b)
+            result = []
+            for (x0, a0, b0) in zip(x, a, b):
+                result.append(integrate.quad(self._pdf, x0, np.inf,
+                                             args=(a0, b0))[0])
+            return np.array(result)
+
+    def _isf(self, q, a, b):
+        def _isf_scalar(q, a, b):
+
+            def eq(x, a, b, q):
+                # Solve eq(x, a, b, q) = 0 to obtain isf(x, a, b) = q.
+                return self._sf(x, a, b) - q
+
+            # Find a bracketing interval for the root.
+            # Start at the mean, and grow the length of the interval
+            # by 2 each iteration until there is a sign change in eq.
+            xm = self.mean(a, b)
+            em = eq(xm, a, b, q)
+            if em == 0:
+                # Unlikely, but might as well check.
+                return xm
+            if em > 0:
+                delta = 1
+                left = xm
+                right = xm + delta
+                while eq(right, a, b, q) > 0:
+                    delta = 2*delta
+                    right = xm + delta
+            else:
+                # em < 0
+                delta = 1
+                right = xm
+                left = xm - delta
+                while eq(left, a, b, q) < 0:
+                    delta = 2*delta
+                    left = xm - delta
+            result = optimize.brentq(eq, left, right, args=(a, b, q),
+                                     xtol=self.xtol)
+            return result
+
+        if np.isscalar(q):
+            return _isf_scalar(q, a, b)
+        else:
+            result = []
+            for (q0, a0, b0) in zip(q, a, b):
+                result.append(_isf_scalar(q0, a0, b0))
+            return np.array(result)
+
+    def _rvs(self, a, b, size=None, random_state=None):
+        # note: X = b * V + sqrt(V) * X is norminvgaus(a,b) if X is standard
+        # normal and V is invgauss(mu=1/sqrt(a**2 - b**2))
+        gamma = np.sqrt(a**2 - b**2)
+        ig = invgauss.rvs(mu=1/gamma, size=size, random_state=random_state)
+        return b * ig + np.sqrt(ig) * norm.rvs(size=size,
+                                               random_state=random_state)
+
+    def _stats(self, a, b):
+        gamma = np.sqrt(a**2 - b**2)
+        mean = b / gamma
+        variance = a**2 / gamma**3
+        skewness = 3.0 * b / (a * np.sqrt(gamma))
+        kurtosis = 3.0 * (1 + 4 * b**2 / a**2) / gamma
+        return mean, variance, skewness, kurtosis
+
+
+norminvgauss = norminvgauss_gen(name="norminvgauss")
+
+
+class invweibull_gen(rv_continuous):
+    """An inverted Weibull continuous random variable.
+
+    This distribution is also known as the Fréchet distribution or the
+    type II extreme value distribution.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `invweibull` is:
+
+    .. math::
+
+        f(x, c) = c x^{-c-1} \\exp(-x^{-c})
+
+    for :math:`x > 0`, :math:`c > 0`.
+
+    `invweibull` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    F.R.S. de Gusmao, E.M.M Ortega and G.M. Cordeiro, "The generalized inverse
+    Weibull distribution", Stat. Papers, vol. 52, pp. 591-619, 2011.
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # invweibull.pdf(x, c) = c * x**(-c-1) * exp(-x**(-c))
+        xc1 = np.power(x, -c - 1.0)
+        xc2 = np.power(x, -c)
+        xc2 = np.exp(-xc2)
+        return c * xc1 * xc2
+
+    def _cdf(self, x, c):
+        xc1 = np.power(x, -c)
+        return np.exp(-xc1)
+
+    def _sf(self, x, c):
+        return -np.expm1(-x**-c)
+
+    def _ppf(self, q, c):
+        return np.power(-np.log(q), -1.0/c)
+
+    def _isf(self, p, c):
+        return (-np.log1p(-p))**(-1/c)
+
+    def _munp(self, n, c):
+        return sc.gamma(1 - n / c)
+
+    def _entropy(self, c):
+        return 1+_EULER + _EULER / c - np.log(c)
+
+    def _fitstart(self, data, args=None):
+        # invweibull requires c > 1 for the first moment to exist, so use 2.0
+        args = (2.0,) if args is None else args
+        return super()._fitstart(data, args=args)
+
+
+invweibull = invweibull_gen(a=0, name='invweibull')
+
+
+class jf_skew_t_gen(rv_continuous):
+    r"""Jones and Faddy skew-t distribution.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `jf_skew_t` is:
+
+    .. math::
+
+        f(x; a, b) = C_{a,b}^{-1}
+                    \left(1+\frac{x}{\left(a+b+x^2\right)^{1/2}}\right)^{a+1/2}
+                    \left(1-\frac{x}{\left(a+b+x^2\right)^{1/2}}\right)^{b+1/2}
+
+    for real numbers :math:`a>0` and :math:`b>0`, where
+    :math:`C_{a,b} = 2^{a+b-1}B(a,b)(a+b)^{1/2}`, and :math:`B` denotes the
+    beta function (`scipy.special.beta`).
+
+    When :math:`ab`, the distribution is positively skewed. If :math:`a=b`, then
+    we recover the `t` distribution with :math:`2a` degrees of freedom.
+
+    `jf_skew_t` takes :math:`a` and :math:`b` as shape parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] M.C. Jones and M.J. Faddy. "A skew extension of the t distribution,
+           with applications" *Journal of the Royal Statistical Society*.
+           Series B (Statistical Methodology) 65, no. 1 (2003): 159-174.
+           :doi:`10.1111/1467-9868.00378`
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _pdf(self, x, a, b):
+        c = 2 ** (a + b - 1) * sc.beta(a, b) * np.sqrt(a + b)
+        d1 = (1 + x / np.sqrt(a + b + x ** 2)) ** (a + 0.5)
+        d2 = (1 - x / np.sqrt(a + b + x ** 2)) ** (b + 0.5)
+        return d1 * d2 / c
+
+    def _rvs(self, a, b, size=None, random_state=None):
+        d1 = random_state.beta(a, b, size)
+        d2 = (2 * d1 - 1) * np.sqrt(a + b)
+        d3 = 2 * np.sqrt(d1 * (1 - d1))
+        return d2 / d3
+
+    def _cdf(self, x, a, b):
+        y = (1 + x / np.sqrt(a + b + x ** 2)) * 0.5
+        return sc.betainc(a, b, y)
+
+    def _sf(self, x, a, b):
+        y = (1 + x / np.sqrt(a + b + x ** 2)) * 0.5
+        return sc.betaincc(a, b, y)
+
+    def _ppf(self, q, a, b):
+        d1 = beta.ppf(q, a, b)
+        d2 = (2 * d1 - 1) * np.sqrt(a + b)
+        d3 = 2 * np.sqrt(d1 * (1 - d1))
+        return d2 / d3
+
+    def _munp(self, n, a, b):
+        """Returns the n-th moment(s) where all the following hold:
+
+        - n >= 0
+        - a > n / 2
+        - b > n / 2
+
+        The result is np.nan in all other cases.
+        """
+        def nth_moment(n_k, a_k, b_k):
+            """Computes E[T^(n_k)] where T is skew-t distributed with
+            parameters a_k and b_k.
+            """
+            num = (a_k + b_k) ** (0.5 * n_k)
+            denom = 2 ** n_k * sc.beta(a_k, b_k)
+
+            indices = np.arange(n_k + 1)
+            sgn = np.where(indices % 2 > 0, -1, 1)
+            d = sc.beta(a_k + 0.5 * n_k - indices, b_k - 0.5 * n_k + indices)
+            sum_terms = sc.comb(n_k, indices) * sgn * d
+
+            return num / denom * sum_terms.sum()
+
+        nth_moment_valid = (a > 0.5 * n) & (b > 0.5 * n) & (n >= 0)
+        return _lazywhere(
+            nth_moment_valid,
+            (n, a, b),
+            np.vectorize(nth_moment, otypes=[np.float64]),
+            np.nan,
+        )
+
+
+jf_skew_t = jf_skew_t_gen(name='jf_skew_t')
+
+
+class johnsonsb_gen(rv_continuous):
+    r"""A Johnson SB continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    johnsonsu
+
+    Notes
+    -----
+    The probability density function for `johnsonsb` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{b}{x(1-x)}  \phi(a + b \log \frac{x}{1-x} )
+
+    where :math:`x`, :math:`a`, and :math:`b` are real scalars; :math:`b > 0`
+    and :math:`x \in [0,1]`.  :math:`\phi` is the pdf of the normal
+    distribution.
+
+    `johnsonsb` takes :math:`a` and :math:`b` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _argcheck(self, a, b):
+        return (b > 0) & (a == a)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (-np.inf, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _pdf(self, x, a, b):
+        # johnsonsb.pdf(x, a, b) = b / (x*(1-x)) * phi(a + b * log(x/(1-x)))
+        trm = _norm_pdf(a + b*sc.logit(x))
+        return b*1.0/(x*(1-x))*trm
+
+    def _cdf(self, x, a, b):
+        return _norm_cdf(a + b*sc.logit(x))
+
+    def _ppf(self, q, a, b):
+        return sc.expit(1.0 / b * (_norm_ppf(q) - a))
+
+    def _sf(self, x, a, b):
+        return _norm_sf(a + b*sc.logit(x))
+
+    def _isf(self, q, a, b):
+        return sc.expit(1.0 / b * (_norm_isf(q) - a))
+
+
+johnsonsb = johnsonsb_gen(a=0.0, b=1.0, name='johnsonsb')
+
+
+class johnsonsu_gen(rv_continuous):
+    r"""A Johnson SU continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    johnsonsb
+
+    Notes
+    -----
+    The probability density function for `johnsonsu` is:
+
+    .. math::
+
+        f(x, a, b) = \frac{b}{\sqrt{x^2 + 1}}
+                     \phi(a + b \log(x + \sqrt{x^2 + 1}))
+
+    where :math:`x`, :math:`a`, and :math:`b` are real scalars; :math:`b > 0`.
+    :math:`\phi` is the pdf of the normal distribution.
+
+    `johnsonsu` takes :math:`a` and :math:`b` as shape parameters.
+
+    The first four central moments are calculated according to the formulas
+    in [1]_.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Taylor Enterprises. "Johnson Family of Distributions".
+       https://variation.com/wp-content/distribution_analyzer_help/hs126.htm
+
+    %(example)s
+
+    """
+    def _argcheck(self, a, b):
+        return (b > 0) & (a == a)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (-np.inf, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _pdf(self, x, a, b):
+        # johnsonsu.pdf(x, a, b) = b / sqrt(x**2 + 1) *
+        #                          phi(a + b * log(x + sqrt(x**2 + 1)))
+        x2 = x*x
+        trm = _norm_pdf(a + b * np.arcsinh(x))
+        return b*1.0/np.sqrt(x2+1.0)*trm
+
+    def _cdf(self, x, a, b):
+        return _norm_cdf(a + b * np.arcsinh(x))
+
+    def _ppf(self, q, a, b):
+        return np.sinh((_norm_ppf(q) - a) / b)
+
+    def _sf(self, x, a, b):
+        return _norm_sf(a + b * np.arcsinh(x))
+
+    def _isf(self, x, a, b):
+        return np.sinh((_norm_isf(x) - a) / b)
+
+    def _stats(self, a, b, moments='mv'):
+        # Naive implementation of first and second moment to address gh-18071.
+        # https://variation.com/wp-content/distribution_analyzer_help/hs126.htm
+        # Numerical improvements left to future enhancements.
+        mu, mu2, g1, g2 = None, None, None, None
+
+        bn2 = b**-2.
+        expbn2 = np.exp(bn2)
+        a_b = a / b
+
+        if 'm' in moments:
+            mu = -expbn2**0.5 * np.sinh(a_b)
+        if 'v' in moments:
+            mu2 = 0.5*sc.expm1(bn2)*(expbn2*np.cosh(2*a_b) + 1)
+        if 's' in moments:
+            t1 = expbn2**.5 * sc.expm1(bn2)**0.5
+            t2 = 3*np.sinh(a_b)
+            t3 = expbn2 * (expbn2 + 2) * np.sinh(3*a_b)
+            denom = np.sqrt(2) * (1 + expbn2 * np.cosh(2*a_b))**(3/2)
+            g1 = -t1 * (t2 + t3) / denom
+        if 'k' in moments:
+            t1 = 3 + 6*expbn2
+            t2 = 4*expbn2**2 * (expbn2 + 2) * np.cosh(2*a_b)
+            t3 = expbn2**2 * np.cosh(4*a_b)
+            t4 = -3 + 3*expbn2**2 + 2*expbn2**3 + expbn2**4
+            denom = 2*(1 + expbn2*np.cosh(2*a_b))**2
+            g2 = (t1 + t2 + t3*t4) / denom - 3
+        return mu, mu2, g1, g2
+
+
+johnsonsu = johnsonsu_gen(name='johnsonsu')
+
+
+class landau_gen(rv_continuous):
+    r"""A Landau continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `landau` ([1]_, [2]_) is:
+
+    .. math::
+
+        f(x) = \frac{1}{\pi}\int_0^\infty \exp(-t \log t - xt)\sin(\pi t) dt
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    Often (e.g. [2]_), the Landau distribution is parameterized in terms of a
+    location parameter :math:`\mu` and scale parameter :math:`c`, the latter of
+    which *also* introduces a location shift. If ``mu`` and ``c`` are used to
+    represent these parameters, this corresponds with SciPy's parameterization
+    with ``loc = mu + 2*c / np.pi * np.log(c)`` and ``scale = c``.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf``
+    methods. [1]_
+
+    References
+    ----------
+    .. [1] Landau, L. (1944). "On the energy loss of fast particles by
+           ionization". J. Phys. (USSR). 8: 201.
+    .. [2] "Landau Distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Landau_distribution
+    .. [3] Chambers, J. M., Mallows, C. L., & Stuck, B. (1976).
+           "A method for simulating stable random variables."
+           Journal of the American Statistical Association, 71(354), 340-344.
+    .. [4] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+    .. [5] Yoshimura, T. "Numerical Evaluation and High Precision Approximation
+           Formula for Landau Distribution".
+           :doi:`10.36227/techrxiv.171822215.53612870/v2`
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _entropy(self):
+        # Computed with mpmath - see gh-19145
+        return 2.37263644000448182
+
+    def _pdf(self, x):
+        return scu._landau_pdf(x, 0, 1)
+
+    def _cdf(self, x):
+        return scu._landau_cdf(x, 0, 1)
+
+    def _sf(self, x):
+        return scu._landau_sf(x, 0, 1)
+
+    def _ppf(self, p):
+        return scu._landau_ppf(p, 0, 1)
+
+    def _isf(self, p):
+        return scu._landau_isf(p, 0, 1)
+
+    def _stats(self):
+        return np.nan, np.nan, np.nan, np.nan
+
+    def _munp(self, n):
+        return np.nan if n > 0 else 1
+
+    def _fitstart(self, data, args=None):
+        # Initialize ML guesses using quartiles instead of moments.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        p25, p50, p75 = np.percentile(data, [25, 50, 75])
+        return p50, (p75 - p25)/2
+
+    def _rvs(self, size=None, random_state=None):
+        # Method from https://www.jstor.org/stable/2285309 Eq. 2.4
+        pi_2 = np.pi / 2
+        U = random_state.uniform(-np.pi / 2, np.pi / 2, size=size)
+        W = random_state.standard_exponential(size=size)
+        S = 2 / np.pi * ((pi_2 + U) * np.tan(U)
+                         - np.log((pi_2 * W * np.cos(U)) / (pi_2 + U)))
+        return S
+
+
+landau = landau_gen(name='landau')
+
+
+class laplace_gen(rv_continuous):
+    r"""A Laplace continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `laplace` is
+
+    .. math::
+
+        f(x) = \frac{1}{2} \exp(-|x|)
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.laplace(0, 1, size=size)
+
+    def _pdf(self, x):
+        # laplace.pdf(x) = 1/2 * exp(-abs(x))
+        return 0.5*np.exp(-abs(x))
+
+    def _cdf(self, x):
+        with np.errstate(over='ignore'):
+            return np.where(x > 0, 1.0 - 0.5*np.exp(-x), 0.5*np.exp(x))
+
+    def _sf(self, x):
+        # By symmetry...
+        return self._cdf(-x)
+
+    def _ppf(self, q):
+        return np.where(q > 0.5, -np.log(2*(1-q)), np.log(2*q))
+
+    def _isf(self, q):
+        # By symmetry...
+        return -self._ppf(q)
+
+    def _stats(self):
+        return 0, 2, 0, 3
+
+    def _entropy(self):
+        return np.log(2)+1
+
+    @_call_super_mom
+    @replace_notes_in_docstring(rv_continuous, notes="""\
+        This function uses explicit formulas for the maximum likelihood
+        estimation of the Laplace distribution parameters, so the keyword
+        arguments `loc`, `scale`, and `optimizer` are ignored.\n\n""")
+    def fit(self, data, *args, **kwds):
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        # Source: Statistical Distributions, 3rd Edition. Evans, Hastings,
+        # and Peacock (2000), Page 124
+
+        if floc is None:
+            floc = np.median(data)
+
+        if fscale is None:
+            fscale = (np.sum(np.abs(data - floc))) / len(data)
+
+        return floc, fscale
+
+
+laplace = laplace_gen(name='laplace')
+
+
+class laplace_asymmetric_gen(rv_continuous):
+    r"""An asymmetric Laplace continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    laplace : Laplace distribution
+
+    Notes
+    -----
+    The probability density function for `laplace_asymmetric` is
+
+    .. math::
+
+       f(x, \kappa) &= \frac{1}{\kappa+\kappa^{-1}}\exp(-x\kappa),\quad x\ge0\\
+                    &= \frac{1}{\kappa+\kappa^{-1}}\exp(x/\kappa),\quad x<0\\
+
+    for :math:`-\infty < x < \infty`, :math:`\kappa > 0`.
+
+    `laplace_asymmetric` takes ``kappa`` as a shape parameter for
+    :math:`\kappa`. For :math:`\kappa = 1`, it is identical to a
+    Laplace distribution.
+
+    %(after_notes)s
+
+    Note that the scale parameter of some references is the reciprocal of
+    SciPy's ``scale``. For example, :math:`\lambda = 1/2` in the
+    parameterization of [1]_ is equivalent to ``scale = 2`` with
+    `laplace_asymmetric`.
+
+    References
+    ----------
+    .. [1] "Asymmetric Laplace distribution", Wikipedia
+            https://en.wikipedia.org/wiki/Asymmetric_Laplace_distribution
+
+    .. [2] Kozubowski TJ and Podgórski K. A Multivariate and
+           Asymmetric Generalization of Laplace Distribution,
+           Computational Statistics 15, 531--540 (2000).
+           :doi:`10.1007/PL00022717`
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("kappa", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, kappa):
+        return np.exp(self._logpdf(x, kappa))
+
+    def _logpdf(self, x, kappa):
+        kapinv = 1/kappa
+        lPx = x * np.where(x >= 0, -kappa, kapinv)
+        lPx -= np.log(kappa+kapinv)
+        return lPx
+
+    def _cdf(self, x, kappa):
+        kapinv = 1/kappa
+        kappkapinv = kappa+kapinv
+        return np.where(x >= 0,
+                        1 - np.exp(-x*kappa)*(kapinv/kappkapinv),
+                        np.exp(x*kapinv)*(kappa/kappkapinv))
+
+    def _sf(self, x, kappa):
+        kapinv = 1/kappa
+        kappkapinv = kappa+kapinv
+        return np.where(x >= 0,
+                        np.exp(-x*kappa)*(kapinv/kappkapinv),
+                        1 - np.exp(x*kapinv)*(kappa/kappkapinv))
+
+    def _ppf(self, q, kappa):
+        kapinv = 1/kappa
+        kappkapinv = kappa+kapinv
+        return np.where(q >= kappa/kappkapinv,
+                        -np.log((1 - q)*kappkapinv*kappa)*kapinv,
+                        np.log(q*kappkapinv/kappa)*kappa)
+
+    def _isf(self, q, kappa):
+        kapinv = 1/kappa
+        kappkapinv = kappa+kapinv
+        return np.where(q <= kapinv/kappkapinv,
+                        -np.log(q*kappkapinv*kappa)*kapinv,
+                        np.log((1 - q)*kappkapinv/kappa)*kappa)
+
+    def _stats(self, kappa):
+        kapinv = 1/kappa
+        mn = kapinv - kappa
+        var = kapinv*kapinv + kappa*kappa
+        g1 = 2.0*(1-np.power(kappa, 6))/np.power(1+np.power(kappa, 4), 1.5)
+        g2 = 6.0*(1+np.power(kappa, 8))/np.power(1+np.power(kappa, 4), 2)
+        return mn, var, g1, g2
+
+    def _entropy(self, kappa):
+        return 1 + np.log(kappa+1/kappa)
+
+
+laplace_asymmetric = laplace_asymmetric_gen(name='laplace_asymmetric')
+
+
+def _check_fit_input_parameters(dist, data, args, kwds):
+    if not isinstance(data, CensoredData):
+        data = np.asarray(data)
+
+    floc = kwds.get('floc', None)
+    fscale = kwds.get('fscale', None)
+
+    num_shapes = len(dist.shapes.split(",")) if dist.shapes else 0
+    fshape_keys = []
+    fshapes = []
+
+    # user has many options for fixing the shape, so here we standardize it
+    # into 'f' + the number of the shape.
+    # Adapted from `_reduce_func` in `_distn_infrastructure.py`:
+    if dist.shapes:
+        shapes = dist.shapes.replace(',', ' ').split()
+        for j, s in enumerate(shapes):
+            key = 'f' + str(j)
+            names = [key, 'f' + s, 'fix_' + s]
+            val = _get_fixed_fit_value(kwds, names)
+            fshape_keys.append(key)
+            fshapes.append(val)
+            if val is not None:
+                kwds[key] = val
+
+    # determine if there are any unknown arguments in kwds
+    known_keys = {'loc', 'scale', 'optimizer', 'method',
+                  'floc', 'fscale', *fshape_keys}
+    unknown_keys = set(kwds).difference(known_keys)
+    if unknown_keys:
+        raise TypeError(f"Unknown keyword arguments: {unknown_keys}.")
+
+    if len(args) > num_shapes:
+        raise TypeError("Too many positional arguments.")
+
+    if None not in {floc, fscale, *fshapes}:
+        # This check is for consistency with `rv_continuous.fit`.
+        # Without this check, this function would just return the
+        # parameters that were given.
+        raise RuntimeError("All parameters fixed. There is nothing to "
+                           "optimize.")
+
+    uncensored = data._uncensor() if isinstance(data, CensoredData) else data
+    if not np.isfinite(uncensored).all():
+        raise ValueError("The data contains non-finite values.")
+
+    return (data, *fshapes, floc, fscale)
+
+
+class levy_gen(rv_continuous):
+    r"""A Levy continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    levy_stable, levy_l
+
+    Notes
+    -----
+    The probability density function for `levy` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\sqrt{2\pi x^3}} \exp\left(-\frac{1}{2x}\right)
+
+    for :math:`x > 0`.
+
+    This is the same as the Levy-stable distribution with :math:`a=1/2` and
+    :math:`b=1`.
+
+    %(after_notes)s
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import levy
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Calculate the first four moments:
+
+    >>> mean, var, skew, kurt = levy.stats(moments='mvsk')
+
+    Display the probability density function (``pdf``):
+
+    >>> # `levy` is very heavy-tailed.
+    >>> # To show a nice plot, let's cut off the upper 40 percent.
+    >>> a, b = levy.ppf(0), levy.ppf(0.6)
+    >>> x = np.linspace(a, b, 100)
+    >>> ax.plot(x, levy.pdf(x),
+    ...        'r-', lw=5, alpha=0.6, label='levy pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = levy()
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = levy.ppf([0.001, 0.5, 0.999])
+    >>> np.allclose([0.001, 0.5, 0.999], levy.cdf(vals))
+    True
+
+    Generate random numbers:
+
+    >>> r = levy.rvs(size=1000)
+
+    And compare the histogram:
+
+    >>> # manual binning to ignore the tail
+    >>> bins = np.concatenate((np.linspace(a, b, 20), [np.max(r)]))
+    >>> ax.hist(r, bins=bins, density=True, histtype='stepfilled', alpha=0.2)
+    >>> ax.set_xlim([x[0], x[-1]])
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # levy.pdf(x) = 1 / (x * sqrt(2*pi*x)) * exp(-1/(2*x))
+        return 1 / np.sqrt(2*np.pi*x) / x * np.exp(-1/(2*x))
+
+    def _cdf(self, x):
+        # Equivalent to 2*norm.sf(np.sqrt(1/x))
+        return sc.erfc(np.sqrt(0.5 / x))
+
+    def _sf(self, x):
+        return sc.erf(np.sqrt(0.5 / x))
+
+    def _ppf(self, q):
+        # Equivalent to 1.0/(norm.isf(q/2)**2) or 0.5/(erfcinv(q)**2)
+        val = _norm_isf(q/2)
+        return 1.0 / (val * val)
+
+    def _isf(self, p):
+        return 1/(2*sc.erfinv(p)**2)
+
+    def _stats(self):
+        return np.inf, np.inf, np.nan, np.nan
+
+
+levy = levy_gen(a=0.0, name="levy")
+
+
+class levy_l_gen(rv_continuous):
+    r"""A left-skewed Levy continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    levy, levy_stable
+
+    Notes
+    -----
+    The probability density function for `levy_l` is:
+
+    .. math::
+        f(x) = \frac{1}{|x| \sqrt{2\pi |x|}} \exp{ \left(-\frac{1}{2|x|} \right)}
+
+    for :math:`x < 0`.
+
+    This is the same as the Levy-stable distribution with :math:`a=1/2` and
+    :math:`b=-1`.
+
+    %(after_notes)s
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import levy_l
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Calculate the first four moments:
+
+    >>> mean, var, skew, kurt = levy_l.stats(moments='mvsk')
+
+    Display the probability density function (``pdf``):
+
+    >>> # `levy_l` is very heavy-tailed.
+    >>> # To show a nice plot, let's cut off the lower 40 percent.
+    >>> a, b = levy_l.ppf(0.4), levy_l.ppf(1)
+    >>> x = np.linspace(a, b, 100)
+    >>> ax.plot(x, levy_l.pdf(x),
+    ...        'r-', lw=5, alpha=0.6, label='levy_l pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = levy_l()
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = levy_l.ppf([0.001, 0.5, 0.999])
+    >>> np.allclose([0.001, 0.5, 0.999], levy_l.cdf(vals))
+    True
+
+    Generate random numbers:
+
+    >>> r = levy_l.rvs(size=1000)
+
+    And compare the histogram:
+
+    >>> # manual binning to ignore the tail
+    >>> bins = np.concatenate(([np.min(r)], np.linspace(a, b, 20)))
+    >>> ax.hist(r, bins=bins, density=True, histtype='stepfilled', alpha=0.2)
+    >>> ax.set_xlim([x[0], x[-1]])
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        # levy_l.pdf(x) = 1 / (abs(x) * sqrt(2*pi*abs(x))) * exp(-1/(2*abs(x)))
+        ax = abs(x)
+        return 1/np.sqrt(2*np.pi*ax)/ax*np.exp(-1/(2*ax))
+
+    def _cdf(self, x):
+        ax = abs(x)
+        return 2 * _norm_cdf(1 / np.sqrt(ax)) - 1
+
+    def _sf(self, x):
+        ax = abs(x)
+        return 2 * _norm_sf(1 / np.sqrt(ax))
+
+    def _ppf(self, q):
+        val = _norm_ppf((q + 1.0) / 2)
+        return -1.0 / (val * val)
+
+    def _isf(self, p):
+        return -1/_norm_isf(p/2)**2
+
+    def _stats(self):
+        return np.inf, np.inf, np.nan, np.nan
+
+
+levy_l = levy_l_gen(b=0.0, name="levy_l")
+
+
+class logistic_gen(rv_continuous):
+    r"""A logistic (or Sech-squared) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `logistic` is:
+
+    .. math::
+
+        f(x) = \frac{\exp(-x)}
+                    {(1+\exp(-x))^2}
+
+    `logistic` is a special case of `genlogistic` with ``c=1``.
+
+    Remark that the survival function (``logistic.sf``) is equal to the
+    Fermi-Dirac distribution describing fermionic statistics.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.logistic(size=size)
+
+    def _pdf(self, x):
+        # logistic.pdf(x) = exp(-x) / (1+exp(-x))**2
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        y = -np.abs(x)
+        return y - 2. * sc.log1p(np.exp(y))
+
+    def _cdf(self, x):
+        return sc.expit(x)
+
+    def _logcdf(self, x):
+        return sc.log_expit(x)
+
+    def _ppf(self, q):
+        return sc.logit(q)
+
+    def _sf(self, x):
+        return sc.expit(-x)
+
+    def _logsf(self, x):
+        return sc.log_expit(-x)
+
+    def _isf(self, q):
+        return -sc.logit(q)
+
+    def _stats(self):
+        return 0, np.pi*np.pi/3.0, 0, 6.0/5.0
+
+    def _entropy(self):
+        # https://en.wikipedia.org/wiki/Logistic_distribution
+        return 2.0
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+        n = len(data)
+
+        # rv_continuous provided guesses
+        loc, scale = self._fitstart(data)
+        # these are trumped by user-provided guesses
+        loc, scale = kwds.get('loc', loc), kwds.get('scale', scale)
+
+        # the maximum likelihood estimators `a` and `b` of the location and
+        # scale parameters are roots of the two equations described in `func`.
+        # Source: Statistical Distributions, 3rd Edition. Evans, Hastings, and
+        # Peacock (2000), Page 130
+
+        def dl_dloc(loc, scale=fscale):
+            c = (data - loc) / scale
+            return np.sum(sc.expit(c)) - n/2
+
+        def dl_dscale(scale, loc=floc):
+            c = (data - loc) / scale
+            return np.sum(c*np.tanh(c/2)) - n
+
+        def func(params):
+            loc, scale = params
+            return dl_dloc(loc, scale), dl_dscale(scale, loc)
+
+        if fscale is not None and floc is None:
+            res = optimize.root(dl_dloc, (loc,))
+            loc = res.x[0]
+            scale = fscale
+        elif floc is not None and fscale is None:
+            res = optimize.root(dl_dscale, (scale,))
+            scale = res.x[0]
+            loc = floc
+        else:
+            res = optimize.root(func, (loc, scale))
+            loc, scale = res.x
+
+        # Note: gh-18176 reported data for which the reported MLE had
+        # `scale < 0`. To fix the bug, we return abs(scale). This is OK because
+        # `dl_dscale` and `dl_dloc` are even and odd functions of `scale`,
+        # respectively, so if `-scale` is a solution, so is `scale`.
+        scale = abs(scale)
+        return ((loc, scale) if res.success
+                else super().fit(data, *args, **kwds))
+
+
+logistic = logistic_gen(name='logistic')
+
+
+class loggamma_gen(rv_continuous):
+    r"""A log gamma continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `loggamma` is:
+
+    .. math::
+
+        f(x, c) = \frac{\exp(c x - \exp(x))}
+                       {\Gamma(c)}
+
+    for all :math:`x, c > 0`. Here, :math:`\Gamma` is the
+    gamma function (`scipy.special.gamma`).
+
+    `loggamma` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, c, size=None, random_state=None):
+        # Use the property of the gamma distribution Gamma(c)
+        #    Gamma(c) ~ Gamma(c + 1)*U**(1/c),
+        # where U is uniform on [0, 1]. (See, e.g.,
+        # G. Marsaglia and W.W. Tsang, "A simple method for generating gamma
+        # variables", https://doi.org/10.1145/358407.358414)
+        # So
+        #    log(Gamma(c)) ~ log(Gamma(c + 1)) + log(U)/c
+        # Generating a sample with this formulation is a bit slower
+        # than the more obvious log(Gamma(c)), but it avoids loss
+        # of precision when c << 1.
+        return (np.log(random_state.gamma(c + 1, size=size))
+                + np.log(random_state.uniform(size=size))/c)
+
+    def _pdf(self, x, c):
+        # loggamma.pdf(x, c) = exp(c*x-exp(x)) / gamma(c)
+        return np.exp(c*x-np.exp(x)-sc.gammaln(c))
+
+    def _logpdf(self, x, c):
+        return c*x - np.exp(x) - sc.gammaln(c)
+
+    def _cdf(self, x, c):
+        # This function is gammainc(c, exp(x)), where gammainc(c, z) is
+        # the regularized incomplete gamma function.
+        # The first term in a series expansion of gamminc(c, z) is
+        # z**c/Gamma(c+1); see 6.5.29 of Abramowitz & Stegun (and refer
+        # back to 6.5.1, 6.5.2 and 6.5.4 for the relevant notation).
+        # This can also be found in the wikipedia article
+        # https://en.wikipedia.org/wiki/Incomplete_gamma_function.
+        # Here we use that formula when x is sufficiently negative that
+        # exp(x) will result in subnormal numbers and lose precision.
+        # We evaluate the log of the expression first to allow the possible
+        # cancellation of the terms in the division, and then exponentiate.
+        # That is,
+        #     exp(x)**c/Gamma(c+1) = exp(log(exp(x)**c/Gamma(c+1)))
+        #                          = exp(c*x - gammaln(c+1))
+        return _lazywhere(x < _LOGXMIN, (x, c),
+                          lambda x, c: np.exp(c*x - sc.gammaln(c+1)),
+                          f2=lambda x, c: sc.gammainc(c, np.exp(x)))
+
+    def _ppf(self, q, c):
+        # The expression used when g < _XMIN inverts the one term expansion
+        # given in the comments of _cdf().
+        g = sc.gammaincinv(c, q)
+        return _lazywhere(g < _XMIN, (g, q, c),
+                          lambda g, q, c: (np.log(q) + sc.gammaln(c+1))/c,
+                          f2=lambda g, q, c: np.log(g))
+
+    def _sf(self, x, c):
+        # See the comments for _cdf() for how x < _LOGXMIN is handled.
+        return _lazywhere(x < _LOGXMIN, (x, c),
+                          lambda x, c: -np.expm1(c*x - sc.gammaln(c+1)),
+                          f2=lambda x, c: sc.gammaincc(c, np.exp(x)))
+
+    def _isf(self, q, c):
+        # The expression used when g < _XMIN inverts the complement of
+        # the one term expansion given in the comments of _cdf().
+        g = sc.gammainccinv(c, q)
+        return _lazywhere(g < _XMIN, (g, q, c),
+                          lambda g, q, c: (np.log1p(-q) + sc.gammaln(c+1))/c,
+                          f2=lambda g, q, c: np.log(g))
+
+    def _stats(self, c):
+        # See, for example, "A Statistical Study of Log-Gamma Distribution", by
+        # Ping Shing Chan (thesis, McMaster University, 1993).
+        mean = sc.digamma(c)
+        var = sc.polygamma(1, c)
+        skewness = sc.polygamma(2, c) / np.power(var, 1.5)
+        excess_kurtosis = sc.polygamma(3, c) / (var*var)
+        return mean, var, skewness, excess_kurtosis
+
+    def _entropy(self, c):
+        def regular(c):
+            h = sc.gammaln(c) - c * sc.digamma(c) + c
+            return h
+
+        def asymptotic(c):
+            # using asymptotic expansions for gammaln and psi (see gh-18093)
+            term = -0.5*np.log(c) + c**-1./6 - c**-3./90 + c**-5./210
+            h = norm._entropy() + term
+            return h
+
+        h = _lazywhere(c >= 45, (c, ), f=asymptotic, f2=regular)
+        return h
+
+
+loggamma = loggamma_gen(name='loggamma')
+
+
+class loglaplace_gen(rv_continuous):
+    r"""A log-Laplace continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `loglaplace` is:
+
+    .. math::
+
+        f(x, c) = \begin{cases}\frac{c}{2} x^{ c-1}  &\text{for } 0 < x < 1\\
+                               \frac{c}{2} x^{-c-1}  &\text{for } x \ge 1
+                  \end{cases}
+
+    for :math:`c > 0`.
+
+    `loglaplace` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    Suppose a random variable ``X`` follows the Laplace distribution with
+    location ``a`` and scale ``b``.  Then ``Y = exp(X)`` follows the
+    log-Laplace distribution with ``c = 1 / b`` and ``scale = exp(a)``.
+
+    References
+    ----------
+    T.J. Kozubowski and K. Podgorski, "A log-Laplace growth rate model",
+    The Mathematical Scientist, vol. 28, pp. 49-60, 2003.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # loglaplace.pdf(x, c) = c / 2 * x**(c-1),   for 0 < x < 1
+        #                      = c / 2 * x**(-c-1),  for x >= 1
+        cd2 = c/2.0
+        c = np.where(x < 1, c, -c)
+        return cd2*x**(c-1)
+
+    def _cdf(self, x, c):
+        return np.where(x < 1, 0.5*x**c, 1-0.5*x**(-c))
+
+    def _sf(self, x, c):
+        return np.where(x < 1, 1 - 0.5*x**c, 0.5*x**(-c))
+
+    def _ppf(self, q, c):
+        return np.where(q < 0.5, (2.0*q)**(1.0/c), (2*(1.0-q))**(-1.0/c))
+
+    def _isf(self, q, c):
+        return np.where(q > 0.5, (2.0*(1.0 - q))**(1.0/c), (2*q)**(-1.0/c))
+
+    def _munp(self, n, c):
+        with np.errstate(divide='ignore'):
+            c2, n2 = c**2, n**2
+            return np.where(n2 < c2, c2 / (c2 - n2), np.inf)
+
+    def _entropy(self, c):
+        return np.log(2.0/c) + 1.0
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        data, fc, floc, fscale = _check_fit_input_parameters(self, data,
+                                                             args, kwds)
+
+        # Specialize MLE only when location is known.
+        if floc is None:
+            return super(type(self), self).fit(data, *args, **kwds)
+
+        # Raise an error if any observation has zero likelihood.
+        if np.any(data <= floc):
+            raise FitDataError("loglaplace", lower=floc, upper=np.inf)
+
+        # Remove location from data.
+        if floc != 0:
+            data = data - floc
+
+        # When location is zero, the log-Laplace distribution is related to
+        # the Laplace distribution in that if X ~ Laplace(loc=a, scale=b),
+        # then Y = exp(X) ~ LogLaplace(c=1/b, loc=0, scale=exp(a)).  It can
+        # be shown that the MLE for Y is the same as the MLE for X = ln(Y).
+        # Therefore, we reuse the formulas from laplace.fit() and transform
+        # the result back into log-laplace's parameter space.
+        a, b = laplace.fit(np.log(data),
+                           floc=np.log(fscale) if fscale is not None else None,
+                           fscale=1/fc if fc is not None else None,
+                           method='mle')
+        loc = floc
+        scale = np.exp(a) if fscale is None else fscale
+        c = 1 / b if fc is None else fc
+        return c, loc, scale
+
+loglaplace = loglaplace_gen(a=0.0, name='loglaplace')
+
+
+def _lognorm_logpdf(x, s):
+    return _lazywhere(x != 0, (x, s),
+                      lambda x, s: (-np.log(x)**2 / (2 * s**2)
+                                    - np.log(s * x * np.sqrt(2 * np.pi))),
+                      -np.inf)
+
+
+class lognorm_gen(rv_continuous):
+    r"""A lognormal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `lognorm` is:
+
+    .. math::
+
+        f(x, s) = \frac{1}{s x \sqrt{2\pi}}
+                  \exp\left(-\frac{\log^2(x)}{2s^2}\right)
+
+    for :math:`x > 0`, :math:`s > 0`.
+
+    `lognorm` takes ``s`` as a shape parameter for :math:`s`.
+
+    %(after_notes)s
+
+    Suppose a normally distributed random variable ``X`` has  mean ``mu`` and
+    standard deviation ``sigma``. Then ``Y = exp(X)`` is lognormally
+    distributed with ``s = sigma`` and ``scale = exp(mu)``.
+
+    %(example)s
+
+    The logarithm of a log-normally distributed random variable is
+    normally distributed:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> mu, sigma = 2, 0.5
+    >>> X = stats.norm(loc=mu, scale=sigma)
+    >>> Y = stats.lognorm(s=sigma, scale=np.exp(mu))
+    >>> x = np.linspace(*X.interval(0.999))
+    >>> y = Y.rvs(size=10000)
+    >>> ax.plot(x, X.pdf(x), label='X (pdf)')
+    >>> ax.hist(np.log(y), density=True, bins=x, label='log(Y) (histogram)')
+    >>> ax.legend()
+    >>> plt.show()
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return [_ShapeInfo("s", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, s, size=None, random_state=None):
+        return np.exp(s * random_state.standard_normal(size))
+
+    def _pdf(self, x, s):
+        # lognorm.pdf(x, s) = 1 / (s*x*sqrt(2*pi)) * exp(-1/2*(log(x)/s)**2)
+        return np.exp(self._logpdf(x, s))
+
+    def _logpdf(self, x, s):
+        return _lognorm_logpdf(x, s)
+
+    def _cdf(self, x, s):
+        return _norm_cdf(np.log(x) / s)
+
+    def _logcdf(self, x, s):
+        return _norm_logcdf(np.log(x) / s)
+
+    def _ppf(self, q, s):
+        return np.exp(s * _norm_ppf(q))
+
+    def _sf(self, x, s):
+        return _norm_sf(np.log(x) / s)
+
+    def _logsf(self, x, s):
+        return _norm_logsf(np.log(x) / s)
+
+    def _isf(self, q, s):
+        return np.exp(s * _norm_isf(q))
+
+    def _stats(self, s):
+        p = np.exp(s*s)
+        mu = np.sqrt(p)
+        mu2 = p*(p-1)
+        g1 = np.sqrt(p-1)*(2+p)
+        g2 = np.polyval([1, 2, 3, 0, -6.0], p)
+        return mu, mu2, g1, g2
+
+    def _entropy(self, s):
+        return 0.5 * (1 + np.log(2*np.pi) + 2 * np.log(s))
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        When `method='MLE'` and
+        the location parameter is fixed by using the `floc` argument,
+        this function uses explicit formulas for the maximum likelihood
+        estimation of the log-normal shape and scale parameters, so the
+        `optimizer`, `loc` and `scale` keyword arguments are ignored.
+        If the location is free, a likelihood maximum is found by
+        setting its partial derivative wrt to location to 0, and
+        solving by substituting the analytical expressions of shape
+        and scale (or provided parameters).
+        See, e.g., equation 3.1 in
+        A. Clifford Cohen & Betty Jones Whitten (1980)
+        Estimation in the Three-Parameter Lognormal Distribution,
+        Journal of the American Statistical Association, 75:370, 399-404
+        https://doi.org/10.2307/2287466
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        parameters = _check_fit_input_parameters(self, data, args, kwds)
+        data, fshape, floc, fscale = parameters
+        data_min = np.min(data)
+
+        def get_shape_scale(loc):
+            # Calculate maximum likelihood scale and shape with analytical
+            # formulas unless provided by the user
+            if fshape is None or fscale is None:
+                lndata = np.log(data - loc)
+            scale = fscale or np.exp(lndata.mean())
+            shape = fshape or np.sqrt(np.mean((lndata - np.log(scale))**2))
+            return shape, scale
+
+        def dL_dLoc(loc):
+            # Derivative of (positive) LL w.r.t. loc
+            shape, scale = get_shape_scale(loc)
+            shifted = data - loc
+            return np.sum((1 + np.log(shifted/scale)/shape**2)/shifted)
+
+        def ll(loc):
+            # (Positive) log-likelihood
+            shape, scale = get_shape_scale(loc)
+            return -self.nnlf((shape, loc, scale), data)
+
+        if floc is None:
+            # The location must be less than the minimum of the data.
+            # Back off a bit to avoid numerical issues.
+            spacing = np.spacing(data_min)
+            rbrack = data_min - spacing
+
+            # Find the right end of the bracket by successive doubling of the
+            # distance to data_min. We're interested in a maximum LL, so the
+            # slope dL_dLoc_rbrack should be negative at the right end.
+            # optimization for later: share shape, scale
+            dL_dLoc_rbrack = dL_dLoc(rbrack)
+            ll_rbrack = ll(rbrack)
+            delta = 2 * spacing  # 2 * (data_min - rbrack)
+            while dL_dLoc_rbrack >= -1e-6:
+                rbrack = data_min - delta
+                dL_dLoc_rbrack = dL_dLoc(rbrack)
+                delta *= 2
+
+            if not np.isfinite(rbrack) or not np.isfinite(dL_dLoc_rbrack):
+                # If we never find a negative slope, either we missed it or the
+                # slope is always positive. It's usually the latter,
+                # which means
+                # loc = data_min - spacing
+                # But sometimes when shape and/or scale are fixed there are
+                # other issues, so be cautious.
+                return super().fit(data, *args, **kwds)
+
+            # Now find the left end of the bracket. Guess is `rbrack-1`
+            # unless that is too small of a difference to resolve. Double
+            # the size of the interval until the left end is found.
+            lbrack = np.minimum(np.nextafter(rbrack, -np.inf), rbrack-1)
+            dL_dLoc_lbrack = dL_dLoc(lbrack)
+            delta = 2 * (rbrack - lbrack)
+            while (np.isfinite(lbrack) and np.isfinite(dL_dLoc_lbrack)
+                   and np.sign(dL_dLoc_lbrack) == np.sign(dL_dLoc_rbrack)):
+                lbrack = rbrack - delta
+                dL_dLoc_lbrack = dL_dLoc(lbrack)
+                delta *= 2
+
+            # I don't recall observing this, but just in case...
+            if not np.isfinite(lbrack) or not np.isfinite(dL_dLoc_lbrack):
+                return super().fit(data, *args, **kwds)
+
+            # If we have a valid bracket, find the root
+            res = root_scalar(dL_dLoc, bracket=(lbrack, rbrack))
+            if not res.converged:
+                return super().fit(data, *args, **kwds)
+
+            # If the slope was positive near the minimum of the data,
+            # the maximum LL could be there instead of at the root. Compare
+            # the LL of the two points to decide.
+            ll_root = ll(res.root)
+            loc = res.root if ll_root > ll_rbrack else data_min-spacing
+
+        else:
+            if floc >= data_min:
+                raise FitDataError("lognorm", lower=0., upper=np.inf)
+            loc = floc
+
+        shape, scale = get_shape_scale(loc)
+        if not (self._argcheck(shape) and scale > 0):
+            return super().fit(data, *args, **kwds)
+        return shape, loc, scale
+
+
+lognorm = lognorm_gen(a=0.0, name='lognorm')
+
+
+class gibrat_gen(rv_continuous):
+    r"""A Gibrat continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `gibrat` is:
+
+    .. math::
+
+        f(x) = \frac{1}{x \sqrt{2\pi}} \exp(-\frac{1}{2} (\log(x))^2)
+
+    for :math:`x >= 0`.
+
+    `gibrat` is a special case of `lognorm` with ``s=1``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return np.exp(random_state.standard_normal(size))
+
+    def _pdf(self, x):
+        # gibrat.pdf(x) = 1/(x*sqrt(2*pi)) * exp(-1/2*(log(x))**2)
+        return np.exp(self._logpdf(x))
+
+    def _logpdf(self, x):
+        return _lognorm_logpdf(x, 1.0)
+
+    def _cdf(self, x):
+        return _norm_cdf(np.log(x))
+
+    def _ppf(self, q):
+        return np.exp(_norm_ppf(q))
+
+    def _sf(self, x):
+        return _norm_sf(np.log(x))
+
+    def _isf(self, p):
+        return np.exp(_norm_isf(p))
+
+    def _stats(self):
+        p = np.e
+        mu = np.sqrt(p)
+        mu2 = p * (p - 1)
+        g1 = np.sqrt(p - 1) * (2 + p)
+        g2 = np.polyval([1, 2, 3, 0, -6.0], p)
+        return mu, mu2, g1, g2
+
+    def _entropy(self):
+        return 0.5 * np.log(2 * np.pi) + 0.5
+
+
+gibrat = gibrat_gen(a=0.0, name='gibrat')
+
+
+class maxwell_gen(rv_continuous):
+    r"""A Maxwell continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    A special case of a `chi` distribution,  with ``df=3``, ``loc=0.0``,
+    and given ``scale = a``, where ``a`` is the parameter used in the
+    Mathworld description [1]_.
+
+    The probability density function for `maxwell` is:
+
+    .. math::
+
+        f(x) = \sqrt{2/\pi}x^2 \exp(-x^2/2)
+
+    for :math:`x >= 0`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/MaxwellDistribution.html
+
+    %(example)s
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return chi.rvs(3.0, size=size, random_state=random_state)
+
+    def _pdf(self, x):
+        # maxwell.pdf(x) = sqrt(2/pi)x**2 * exp(-x**2/2)
+        return _SQRT_2_OVER_PI*x*x*np.exp(-x*x/2.0)
+
+    def _logpdf(self, x):
+        # Allow x=0 without 'divide by zero' warnings
+        with np.errstate(divide='ignore'):
+            return _LOG_SQRT_2_OVER_PI + 2*np.log(x) - 0.5*x*x
+
+    def _cdf(self, x):
+        return sc.gammainc(1.5, x*x/2.0)
+
+    def _ppf(self, q):
+        return np.sqrt(2*sc.gammaincinv(1.5, q))
+
+    def _sf(self, x):
+        return sc.gammaincc(1.5, x*x/2.0)
+
+    def _isf(self, q):
+        return np.sqrt(2*sc.gammainccinv(1.5, q))
+
+    def _stats(self):
+        val = 3*np.pi-8
+        return (2*np.sqrt(2.0/np.pi),
+                3-8/np.pi,
+                np.sqrt(2)*(32-10*np.pi)/val**1.5,
+                (-12*np.pi*np.pi + 160*np.pi - 384) / val**2.0)
+
+    def _entropy(self):
+        return _EULER + 0.5*np.log(2*np.pi)-0.5
+
+
+maxwell = maxwell_gen(a=0.0, name='maxwell')
+
+
+class mielke_gen(rv_continuous):
+    r"""A Mielke Beta-Kappa / Dagum continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `mielke` is:
+
+    .. math::
+
+        f(x, k, s) = \frac{k x^{k-1}}{(1+x^s)^{1+k/s}}
+
+    for :math:`x > 0` and :math:`k, s > 0`. The distribution is sometimes
+    called Dagum distribution ([2]_). It was already defined in [3]_, called
+    a Burr Type III distribution (`burr` with parameters ``c=s`` and
+    ``d=k/s``).
+
+    `mielke` takes ``k`` and ``s`` as shape parameters.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Mielke, P.W., 1973 "Another Family of Distributions for Describing
+           and Analyzing Precipitation Data." J. Appl. Meteor., 12, 275-280
+    .. [2] Dagum, C., 1977 "A new model for personal income distribution."
+           Economie Appliquee, 33, 327-367.
+    .. [3] Burr, I. W. "Cumulative frequency functions", Annals of
+           Mathematical Statistics, 13(2), pp 215-232 (1942).
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        ik = _ShapeInfo("k", False, (0, np.inf), (False, False))
+        i_s = _ShapeInfo("s", False, (0, np.inf), (False, False))
+        return [ik, i_s]
+
+    def _pdf(self, x, k, s):
+        return k*x**(k-1.0) / (1.0+x**s)**(1.0+k*1.0/s)
+
+    def _logpdf(self, x, k, s):
+        # Allow x=0 without 'divide by zero' warnings.
+        with np.errstate(divide='ignore'):
+            return np.log(k) + np.log(x)*(k - 1) - np.log1p(x**s)*(1 + k/s)
+
+    def _cdf(self, x, k, s):
+        return x**k / (1.0+x**s)**(k*1.0/s)
+
+    def _ppf(self, q, k, s):
+        qsk = pow(q, s*1.0/k)
+        return pow(qsk/(1.0-qsk), 1.0/s)
+
+    def _munp(self, n, k, s):
+        def nth_moment(n, k, s):
+            # n-th moment is defined for -k < n < s
+            return sc.gamma((k+n)/s)*sc.gamma(1-n/s)/sc.gamma(k/s)
+
+        return _lazywhere(n < s, (n, k, s), nth_moment, np.inf)
+
+
+mielke = mielke_gen(a=0.0, name='mielke')
+
+
+class kappa4_gen(rv_continuous):
+    r"""Kappa 4 parameter distribution.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for kappa4 is:
+
+    .. math::
+
+        f(x, h, k) = (1 - k x)^{1/k - 1} (1 - h (1 - k x)^{1/k})^{1/h-1}
+
+    if :math:`h` and :math:`k` are not equal to 0.
+
+    If :math:`h` or :math:`k` are zero then the pdf can be simplified:
+
+    h = 0 and k != 0::
+
+        kappa4.pdf(x, h, k) = (1.0 - k*x)**(1.0/k - 1.0)*
+                              exp(-(1.0 - k*x)**(1.0/k))
+
+    h != 0 and k = 0::
+
+        kappa4.pdf(x, h, k) = exp(-x)*(1.0 - h*exp(-x))**(1.0/h - 1.0)
+
+    h = 0 and k = 0::
+
+        kappa4.pdf(x, h, k) = exp(-x)*exp(-exp(-x))
+
+    kappa4 takes :math:`h` and :math:`k` as shape parameters.
+
+    The kappa4 distribution returns other distributions when certain
+    :math:`h` and :math:`k` values are used.
+
+    +------+-------------+----------------+------------------+
+    | h    | k=0.0       | k=1.0          | -inf<=k<=inf     |
+    +======+=============+================+==================+
+    | -1.0 | Logistic    |                | Generalized      |
+    |      |             |                | Logistic(1)      |
+    |      |             |                |                  |
+    |      | logistic(x) |                |                  |
+    +------+-------------+----------------+------------------+
+    |  0.0 | Gumbel      | Reverse        | Generalized      |
+    |      |             | Exponential(2) | Extreme Value    |
+    |      |             |                |                  |
+    |      | gumbel_r(x) |                | genextreme(x, k) |
+    +------+-------------+----------------+------------------+
+    |  1.0 | Exponential | Uniform        | Generalized      |
+    |      |             |                | Pareto           |
+    |      |             |                |                  |
+    |      | expon(x)    | uniform(x)     | genpareto(x, -k) |
+    +------+-------------+----------------+------------------+
+
+    (1) There are at least five generalized logistic distributions.
+        Four are described here:
+        https://en.wikipedia.org/wiki/Generalized_logistic_distribution
+        The "fifth" one is the one kappa4 should match which currently
+        isn't implemented in scipy:
+        https://en.wikipedia.org/wiki/Talk:Generalized_logistic_distribution
+        https://www.mathwave.com/help/easyfit/html/analyses/distributions/gen_logistic.html
+    (2) This distribution is currently not in scipy.
+
+    References
+    ----------
+    J.C. Finney, "Optimization of a Skewed Logistic Distribution With Respect
+    to the Kolmogorov-Smirnov Test", A Dissertation Submitted to the Graduate
+    Faculty of the Louisiana State University and Agricultural and Mechanical
+    College, (August, 2004),
+    https://digitalcommons.lsu.edu/gradschool_dissertations/3672
+
+    J.R.M. Hosking, "The four-parameter kappa distribution". IBM J. Res.
+    Develop. 38 (3), 25 1-258 (1994).
+
+    B. Kumphon, A. Kaew-Man, P. Seenoi, "A Rainfall Distribution for the Lampao
+    Site in the Chi River Basin, Thailand", Journal of Water Resource and
+    Protection, vol. 4, 866-869, (2012).
+    :doi:`10.4236/jwarp.2012.410101`
+
+    C. Winchester, "On Estimation of the Four-Parameter Kappa Distribution", A
+    Thesis Submitted to Dalhousie University, Halifax, Nova Scotia, (March
+    2000).
+    http://www.nlc-bnc.ca/obj/s4/f2/dsk2/ftp01/MQ57336.pdf
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, h, k):
+        shape = np.broadcast_arrays(h, k)[0].shape
+        return np.full(shape, fill_value=True)
+
+    def _shape_info(self):
+        ih = _ShapeInfo("h", False, (-np.inf, np.inf), (False, False))
+        ik = _ShapeInfo("k", False, (-np.inf, np.inf), (False, False))
+        return [ih, ik]
+
+    def _get_support(self, h, k):
+        condlist = [np.logical_and(h > 0, k > 0),
+                    np.logical_and(h > 0, k == 0),
+                    np.logical_and(h > 0, k < 0),
+                    np.logical_and(h <= 0, k > 0),
+                    np.logical_and(h <= 0, k == 0),
+                    np.logical_and(h <= 0, k < 0)]
+
+        def f0(h, k):
+            return (1.0 - np.float_power(h, -k))/k
+
+        def f1(h, k):
+            return np.log(h)
+
+        def f3(h, k):
+            a = np.empty(np.shape(h))
+            a[:] = -np.inf
+            return a
+
+        def f5(h, k):
+            return 1.0/k
+
+        _a = _lazyselect(condlist,
+                         [f0, f1, f0, f3, f3, f5],
+                         [h, k],
+                         default=np.nan)
+
+        def f0(h, k):
+            return 1.0/k
+
+        def f1(h, k):
+            a = np.empty(np.shape(h))
+            a[:] = np.inf
+            return a
+
+        _b = _lazyselect(condlist,
+                         [f0, f1, f1, f0, f1, f1],
+                         [h, k],
+                         default=np.nan)
+        return _a, _b
+
+    def _pdf(self, x, h, k):
+        # kappa4.pdf(x, h, k) = (1.0 - k*x)**(1.0/k - 1.0)*
+        #                       (1.0 - h*(1.0 - k*x)**(1.0/k))**(1.0/h-1)
+        return np.exp(self._logpdf(x, h, k))
+
+    def _logpdf(self, x, h, k):
+        condlist = [np.logical_and(h != 0, k != 0),
+                    np.logical_and(h == 0, k != 0),
+                    np.logical_and(h != 0, k == 0),
+                    np.logical_and(h == 0, k == 0)]
+
+        def f0(x, h, k):
+            '''pdf = (1.0 - k*x)**(1.0/k - 1.0)*(
+                      1.0 - h*(1.0 - k*x)**(1.0/k))**(1.0/h-1.0)
+               logpdf = ...
+            '''
+            return (sc.xlog1py(1.0/k - 1.0, -k*x) +
+                    sc.xlog1py(1.0/h - 1.0, -h*(1.0 - k*x)**(1.0/k)))
+
+        def f1(x, h, k):
+            '''pdf = (1.0 - k*x)**(1.0/k - 1.0)*np.exp(-(
+                      1.0 - k*x)**(1.0/k))
+               logpdf = ...
+            '''
+            return sc.xlog1py(1.0/k - 1.0, -k*x) - (1.0 - k*x)**(1.0/k)
+
+        def f2(x, h, k):
+            '''pdf = np.exp(-x)*(1.0 - h*np.exp(-x))**(1.0/h - 1.0)
+               logpdf = ...
+            '''
+            return -x + sc.xlog1py(1.0/h - 1.0, -h*np.exp(-x))
+
+        def f3(x, h, k):
+            '''pdf = np.exp(-x-np.exp(-x))
+               logpdf = ...
+            '''
+            return -x - np.exp(-x)
+
+        return _lazyselect(condlist,
+                           [f0, f1, f2, f3],
+                           [x, h, k],
+                           default=np.nan)
+
+    def _cdf(self, x, h, k):
+        return np.exp(self._logcdf(x, h, k))
+
+    def _logcdf(self, x, h, k):
+        condlist = [np.logical_and(h != 0, k != 0),
+                    np.logical_and(h == 0, k != 0),
+                    np.logical_and(h != 0, k == 0),
+                    np.logical_and(h == 0, k == 0)]
+
+        def f0(x, h, k):
+            '''cdf = (1.0 - h*(1.0 - k*x)**(1.0/k))**(1.0/h)
+               logcdf = ...
+            '''
+            return (1.0/h)*sc.log1p(-h*(1.0 - k*x)**(1.0/k))
+
+        def f1(x, h, k):
+            '''cdf = np.exp(-(1.0 - k*x)**(1.0/k))
+               logcdf = ...
+            '''
+            return -(1.0 - k*x)**(1.0/k)
+
+        def f2(x, h, k):
+            '''cdf = (1.0 - h*np.exp(-x))**(1.0/h)
+               logcdf = ...
+            '''
+            return (1.0/h)*sc.log1p(-h*np.exp(-x))
+
+        def f3(x, h, k):
+            '''cdf = np.exp(-np.exp(-x))
+               logcdf = ...
+            '''
+            return -np.exp(-x)
+
+        return _lazyselect(condlist,
+                           [f0, f1, f2, f3],
+                           [x, h, k],
+                           default=np.nan)
+
+    def _ppf(self, q, h, k):
+        condlist = [np.logical_and(h != 0, k != 0),
+                    np.logical_and(h == 0, k != 0),
+                    np.logical_and(h != 0, k == 0),
+                    np.logical_and(h == 0, k == 0)]
+
+        def f0(q, h, k):
+            return 1.0/k*(1.0 - ((1.0 - (q**h))/h)**k)
+
+        def f1(q, h, k):
+            return 1.0/k*(1.0 - (-np.log(q))**k)
+
+        def f2(q, h, k):
+            '''ppf = -np.log((1.0 - (q**h))/h)
+            '''
+            return -sc.log1p(-(q**h)) + np.log(h)
+
+        def f3(q, h, k):
+            return -np.log(-np.log(q))
+
+        return _lazyselect(condlist,
+                           [f0, f1, f2, f3],
+                           [q, h, k],
+                           default=np.nan)
+
+    def _get_stats_info(self, h, k):
+        condlist = [
+            np.logical_and(h < 0, k >= 0),
+            k < 0,
+        ]
+
+        def f0(h, k):
+            return (-1.0/h*k).astype(int)
+
+        def f1(h, k):
+            return (-1.0/k).astype(int)
+
+        return _lazyselect(condlist, [f0, f1], [h, k], default=5)
+
+    def _stats(self, h, k):
+        maxr = self._get_stats_info(h, k)
+        outputs = [None if np.any(r < maxr) else np.nan for r in range(1, 5)]
+        return outputs[:]
+
+    def _mom1_sc(self, m, *args):
+        maxr = self._get_stats_info(args[0], args[1])
+        if m >= maxr:
+            return np.nan
+        return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0]
+
+
+kappa4 = kappa4_gen(name='kappa4')
+
+
+class kappa3_gen(rv_continuous):
+    r"""Kappa 3 parameter distribution.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `kappa3` is:
+
+    .. math::
+
+        f(x, a) = a (a + x^a)^{-(a + 1)/a}
+
+    for :math:`x > 0` and :math:`a > 0`.
+
+    `kappa3` takes ``a`` as a shape parameter for :math:`a`.
+
+    References
+    ----------
+    P.W. Mielke and E.S. Johnson, "Three-Parameter Kappa Distribution Maximum
+    Likelihood and Likelihood Ratio Tests", Methods in Weather Research,
+    701-707, (September, 1973),
+    :doi:`10.1175/1520-0493(1973)101<0701:TKDMLE>2.3.CO;2`
+
+    B. Kumphon, "Maximum Entropy and Maximum Likelihood Estimation for the
+    Three-Parameter Kappa Distribution", Open Journal of Statistics, vol 2,
+    415-419 (2012), :doi:`10.4236/ojs.2012.24050`
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        # kappa3.pdf(x, a) = a*(a + x**a)**(-(a + 1)/a),     for x > 0
+        return a*(a + x**a)**(-1.0/a-1)
+
+    def _cdf(self, x, a):
+        return x*(a + x**a)**(-1.0/a)
+
+    def _sf(self, x, a):
+        x, a = np.broadcast_arrays(x, a)  # some code paths pass scalars
+        sf = super()._sf(x, a)
+
+        # When the SF is small, another formulation is typically more accurate.
+        # However, it blows up for large `a`, so use it only if it also returns
+        # a small value of the SF.
+        cutoff = 0.01
+        i = sf < cutoff
+        sf2 = -sc.expm1(sc.xlog1py(-1.0 / a[i], a[i] * x[i]**-a[i]))
+        i2 = sf2 > cutoff
+        sf2[i2] = sf[i][i2]  # replace bad values with original values
+
+        sf[i] = sf2
+        return sf
+
+    def _ppf(self, q, a):
+        return (a/(q**-a - 1.0))**(1.0/a)
+
+    def _isf(self, q, a):
+        lg = sc.xlog1py(-a, -q)
+        denom = sc.expm1(lg)
+        return (a / denom)**(1.0 / a)
+
+    def _stats(self, a):
+        outputs = [None if np.any(i < a) else np.nan for i in range(1, 5)]
+        return outputs[:]
+
+    def _mom1_sc(self, m, *args):
+        if np.any(m >= args[0]):
+            return np.nan
+        return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0]
+
+
+kappa3 = kappa3_gen(a=0.0, name='kappa3')
+
+
+class moyal_gen(rv_continuous):
+    r"""A Moyal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `moyal` is:
+
+    .. math::
+
+        f(x) = \exp(-(x + \exp(-x))/2) / \sqrt{2\pi}
+
+    for a real number :math:`x`.
+
+    %(after_notes)s
+
+    This distribution has utility in high-energy physics and radiation
+    detection. It describes the energy loss of a charged relativistic
+    particle due to ionization of the medium [1]_. It also provides an
+    approximation for the Landau distribution. For an in depth description
+    see [2]_. For additional description, see [3]_.
+
+    References
+    ----------
+    .. [1] J.E. Moyal, "XXX. Theory of ionization fluctuations",
+           The London, Edinburgh, and Dublin Philosophical Magazine
+           and Journal of Science, vol 46, 263-280, (1955).
+           :doi:`10.1080/14786440308521076` (gated)
+    .. [2] G. Cordeiro et al., "The beta Moyal: a useful skew distribution",
+           International Journal of Research and Reviews in Applied Sciences,
+           vol 10, 171-192, (2012).
+           http://www.arpapress.com/Volumes/Vol10Issue2/IJRRAS_10_2_02.pdf
+    .. [3] C. Walck, "Handbook on Statistical Distributions for
+           Experimentalists; International Report SUF-PFY/96-01", Chapter 26,
+           University of Stockholm: Stockholm, Sweden, (2007).
+           http://www.stat.rice.edu/~dobelman/textfiles/DistributionsHandbook.pdf
+
+    .. versionadded:: 1.1.0
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        u1 = gamma.rvs(a=0.5, scale=2, size=size,
+                       random_state=random_state)
+        return -np.log(u1)
+
+    def _pdf(self, x):
+        return np.exp(-0.5 * (x + np.exp(-x))) / np.sqrt(2*np.pi)
+
+    def _cdf(self, x):
+        return sc.erfc(np.exp(-0.5 * x) / np.sqrt(2))
+
+    def _sf(self, x):
+        return sc.erf(np.exp(-0.5 * x) / np.sqrt(2))
+
+    def _ppf(self, x):
+        return -np.log(2 * sc.erfcinv(x)**2)
+
+    def _stats(self):
+        mu = np.log(2) + np.euler_gamma
+        mu2 = np.pi**2 / 2
+        g1 = 28 * np.sqrt(2) * sc.zeta(3) / np.pi**3
+        g2 = 4.
+        return mu, mu2, g1, g2
+
+    def _munp(self, n):
+        if n == 1.0:
+            return np.log(2) + np.euler_gamma
+        elif n == 2.0:
+            return np.pi**2 / 2 + (np.log(2) + np.euler_gamma)**2
+        elif n == 3.0:
+            tmp1 = 1.5 * np.pi**2 * (np.log(2)+np.euler_gamma)
+            tmp2 = (np.log(2)+np.euler_gamma)**3
+            tmp3 = 14 * sc.zeta(3)
+            return tmp1 + tmp2 + tmp3
+        elif n == 4.0:
+            tmp1 = 4 * 14 * sc.zeta(3) * (np.log(2) + np.euler_gamma)
+            tmp2 = 3 * np.pi**2 * (np.log(2) + np.euler_gamma)**2
+            tmp3 = (np.log(2) + np.euler_gamma)**4
+            tmp4 = 7 * np.pi**4 / 4
+            return tmp1 + tmp2 + tmp3 + tmp4
+        else:
+            # return generic for higher moments
+            # return rv_continuous._mom1_sc(self, n, b)
+            return self._mom1_sc(n)
+
+
+moyal = moyal_gen(name="moyal")
+
+
+class nakagami_gen(rv_continuous):
+    r"""A Nakagami continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `nakagami` is:
+
+    .. math::
+
+        f(x, \nu) = \frac{2 \nu^\nu}{\Gamma(\nu)} x^{2\nu-1} \exp(-\nu x^2)
+
+    for :math:`x >= 0`, :math:`\nu > 0`. The distribution was introduced in
+    [2]_, see also [1]_ for further information.
+
+    `nakagami` takes ``nu`` as a shape parameter for :math:`\nu`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Nakagami distribution", Wikipedia
+           https://en.wikipedia.org/wiki/Nakagami_distribution
+    .. [2] M. Nakagami, "The m-distribution - A general formula of intensity
+           distribution of rapid fading", Statistical methods in radio wave
+           propagation, Pergamon Press, 1960, 3-36.
+           :doi:`10.1016/B978-0-08-009306-2.50005-4`
+
+    %(example)s
+
+    """
+    def _argcheck(self, nu):
+        return nu > 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("nu", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, nu):
+        return np.exp(self._logpdf(x, nu))
+
+    def _logpdf(self, x, nu):
+        # nakagami.pdf(x, nu) = 2 * nu**nu / gamma(nu) *
+        #                       x**(2*nu-1) * exp(-nu*x**2)
+        return (np.log(2) + sc.xlogy(nu, nu) - sc.gammaln(nu) +
+                sc.xlogy(2*nu - 1, x) - nu*x**2)
+
+    def _cdf(self, x, nu):
+        return sc.gammainc(nu, nu*x*x)
+
+    def _ppf(self, q, nu):
+        return np.sqrt(1.0/nu*sc.gammaincinv(nu, q))
+
+    def _sf(self, x, nu):
+        return sc.gammaincc(nu, nu*x*x)
+
+    def _isf(self, p, nu):
+        return np.sqrt(1/nu * sc.gammainccinv(nu, p))
+
+    def _stats(self, nu):
+        mu = sc.poch(nu, 0.5)/np.sqrt(nu)
+        mu2 = 1.0-mu*mu
+        g1 = mu * (1 - 4*nu*mu2) / 2.0 / nu / np.power(mu2, 1.5)
+        g2 = -6*mu**4*nu + (8*nu-2)*mu**2-2*nu + 1
+        g2 /= nu*mu2**2.0
+        return mu, mu2, g1, g2
+
+    def _entropy(self, nu):
+        shape = np.shape(nu)
+        # because somehow this isn't taken care of by the infrastructure...
+        nu = np.atleast_1d(nu)
+        A = sc.gammaln(nu)
+        B = nu - (nu - 0.5) * sc.digamma(nu)
+        C = -0.5 * np.log(nu) - np.log(2)
+        h = A + B + C
+        # This is the asymptotic sum of A and B (see gh-17868)
+        norm_entropy = stats.norm._entropy()
+        # Above, this is lost to rounding error for large nu, so use the
+        # asymptotic sum when the approximation becomes accurate
+        i = nu > 5e4  # roundoff error ~ approximation error
+        # -1 / (12 * nu) is the O(1/nu) term; see gh-17929
+        h[i] = C[i] + norm_entropy - 1/(12*nu[i])
+        return h.reshape(shape)[()]
+
+    def _rvs(self, nu, size=None, random_state=None):
+        # this relationship can be found in [1] or by a direct calculation
+        return np.sqrt(random_state.standard_gamma(nu, size=size) / nu)
+
+    def _fitstart(self, data, args=None):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        if args is None:
+            args = (1.0,) * self.numargs
+        # Analytical justified estimates
+        # see: https://docs.scipy.org/doc/scipy/reference/tutorial/stats/continuous_nakagami.html
+        loc = np.min(data)
+        scale = np.sqrt(np.sum((data - loc)**2) / len(data))
+        return args + (loc, scale)
+
+
+nakagami = nakagami_gen(a=0.0, name="nakagami")
+
+
+# The function name ncx2 is an abbreviation for noncentral chi squared.
+def _ncx2_log_pdf(x, df, nc):
+    # We use (xs**2 + ns**2)/2 = (xs - ns)**2/2  + xs*ns, and include the
+    # factor of exp(-xs*ns) into the ive function to improve numerical
+    # stability at large values of xs. See also `rice.pdf`.
+    df2 = df/2.0 - 1.0
+    xs, ns = np.sqrt(x), np.sqrt(nc)
+    res = sc.xlogy(df2/2.0, x/nc) - 0.5*(xs - ns)**2
+    corr = sc.ive(df2, xs*ns) / 2.0
+    # Return res + np.log(corr) avoiding np.log(0)
+    return _lazywhere(
+        corr > 0,
+        (res, corr),
+        f=lambda r, c: r + np.log(c),
+        fillvalue=-np.inf)
+
+
+class ncx2_gen(rv_continuous):
+    r"""A non-central chi-squared continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `ncx2` is:
+
+    .. math::
+
+        f(x, k, \lambda) = \frac{1}{2} \exp(-(\lambda+x)/2)
+            (x/\lambda)^{(k-2)/4}  I_{(k-2)/2}(\sqrt{\lambda x})
+
+    for :math:`x >= 0`, :math:`k > 0` and :math:`\lambda \ge 0`.
+    :math:`k` specifies the degrees of freedom (denoted ``df`` in the
+    implementation) and :math:`\lambda` is the non-centrality parameter
+    (denoted ``nc`` in the implementation). :math:`I_\nu` denotes the
+    modified Bessel function of first order of degree :math:`\nu`
+    (`scipy.special.iv`).
+
+    `ncx2` takes ``df`` and ``nc`` as shape parameters.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf``
+    methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _argcheck(self, df, nc):
+        return (df > 0) & np.isfinite(df) & (nc >= 0)
+
+    def _shape_info(self):
+        idf = _ShapeInfo("df", False, (0, np.inf), (False, False))
+        inc = _ShapeInfo("nc", False, (0, np.inf), (True, False))
+        return [idf, inc]
+
+    def _rvs(self, df, nc, size=None, random_state=None):
+        return random_state.noncentral_chisquare(df, nc, size)
+
+    def _logpdf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        return _lazywhere(cond, (x, df, nc), f=_ncx2_log_pdf,
+                          f2=lambda x, df, _: chi2._logpdf(x, df))
+
+    def _pdf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (x, df, nc), f=scu._ncx2_pdf,
+                              f2=lambda x, df, _: chi2._pdf(x, df))
+
+    def _cdf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (x, df, nc), f=scu._ncx2_cdf,
+                              f2=lambda x, df, _: chi2._cdf(x, df))
+
+    def _ppf(self, q, df, nc):
+        cond = np.ones_like(q, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (q, df, nc), f=scu._ncx2_ppf,
+                              f2=lambda x, df, _: chi2._ppf(x, df))
+
+    def _sf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (x, df, nc), f=scu._ncx2_sf,
+                              f2=lambda x, df, _: chi2._sf(x, df))
+
+    def _isf(self, x, df, nc):
+        cond = np.ones_like(x, dtype=bool) & (nc != 0)
+        with np.errstate(over='ignore'):  # see gh-17432
+            return _lazywhere(cond, (x, df, nc), f=scu._ncx2_isf,
+                              f2=lambda x, df, _: chi2._isf(x, df))
+
+    def _stats(self, df, nc):
+        _ncx2_mean = df + nc
+        def k_plus_cl(k, l, c):
+            return k + c*l
+        _ncx2_variance =  2.0 * k_plus_cl(df, nc, 2.0)
+        _ncx2_skewness = (np.sqrt(8.0) * k_plus_cl(df, nc, 3) /
+                          np.sqrt(k_plus_cl(df, nc, 2.0)**3))
+        _ncx2_kurtosis_excess = (12.0 * k_plus_cl(df, nc, 4.0) /
+                                 k_plus_cl(df, nc, 2.0)**2)
+        return (
+            _ncx2_mean,
+            _ncx2_variance,
+            _ncx2_skewness,
+            _ncx2_kurtosis_excess,
+        )
+
+
+ncx2 = ncx2_gen(a=0.0, name='ncx2')
+
+
+class ncf_gen(rv_continuous):
+    r"""A non-central F distribution continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    scipy.stats.f : Fisher distribution
+
+    Notes
+    -----
+    The probability density function for `ncf` is:
+
+    .. math::
+
+        f(x, n_1, n_2, \lambda) =
+            \exp\left(\frac{\lambda}{2} +
+                      \lambda n_1 \frac{x}{2(n_1 x + n_2)}
+                \right)
+            n_1^{n_1/2} n_2^{n_2/2} x^{n_1/2 - 1} \\
+            (n_2 + n_1 x)^{-(n_1 + n_2)/2}
+            \gamma(n_1/2) \gamma(1 + n_2/2) \\
+            \frac{L^{\frac{n_1}{2}-1}_{n_2/2}
+                \left(-\lambda n_1 \frac{x}{2(n_1 x + n_2)}\right)}
+            {B(n_1/2, n_2/2)
+                \gamma\left(\frac{n_1 + n_2}{2}\right)}
+
+    for :math:`n_1, n_2 > 0`, :math:`\lambda \ge 0`.  Here :math:`n_1` is the
+    degrees of freedom in the numerator, :math:`n_2` the degrees of freedom in
+    the denominator, :math:`\lambda` the non-centrality parameter,
+    :math:`\gamma` is the logarithm of the Gamma function, :math:`L_n^k` is a
+    generalized Laguerre polynomial and :math:`B` is the beta function.
+
+    `ncf` takes ``dfn``, ``dfd`` and ``nc`` as shape parameters. If ``nc=0``,
+    the distribution becomes equivalent to the Fisher distribution.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``stats``, ``sf`` and
+    ``isf`` methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _argcheck(self, dfn, dfd, nc):
+        return (dfn > 0) & (dfd > 0) & (nc >= 0)
+
+    def _shape_info(self):
+        idf1 = _ShapeInfo("dfn", False, (0, np.inf), (False, False))
+        idf2 = _ShapeInfo("dfd", False, (0, np.inf), (False, False))
+        inc = _ShapeInfo("nc", False, (0, np.inf), (True, False))
+        return [idf1, idf2, inc]
+
+    def _rvs(self, dfn, dfd, nc, size=None, random_state=None):
+        return random_state.noncentral_f(dfn, dfd, nc, size)
+
+    def _pdf(self, x, dfn, dfd, nc):
+        return scu._ncf_pdf(x, dfn, dfd, nc)
+
+    def _cdf(self, x, dfn, dfd, nc):
+        return sc.ncfdtr(dfn, dfd, nc, x)
+
+    def _ppf(self, q, dfn, dfd, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return sc.ncfdtri(dfn, dfd, nc, q)
+
+    def _sf(self, x, dfn, dfd, nc):
+        return scu._ncf_sf(x, dfn, dfd, nc)
+
+    def _isf(self, x, dfn, dfd, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._ncf_isf(x, dfn, dfd, nc)
+
+    # # Produces bogus values as written - maybe it's close, though?
+    # def _munp(self, n, dfn, dfd, nc):
+    #     val = (dfn * 1.0/dfd)**n
+    #     term = sc.gammaln(n+0.5*dfn) + sc.gammaln(0.5*dfd-n) - sc.gammaln(dfd*0.5)
+    #     val *= np.exp(-nc / 2.0+term)
+    #     val *= sc.hyp1f1(n+0.5*dfn, 0.5*dfn, 0.5*nc)
+    #     return val
+
+    def _stats(self, dfn, dfd, nc, moments='mv'):
+        mu = scu._ncf_mean(dfn, dfd, nc)
+        mu2 = scu._ncf_variance(dfn, dfd, nc)
+        g1 = scu._ncf_skewness(dfn, dfd, nc) if 's' in moments else None
+        g2 = scu._ncf_kurtosis_excess(  # isn't really excess kurtosis!
+            dfn, dfd, nc) - 3 if 'k' in moments else None
+        # Mathematica: Kurtosis[NoncentralFRatioDistribution[27, 27, 0.415784417992261]]
+        return mu, mu2, g1, g2
+
+
+ncf = ncf_gen(a=0.0, name='ncf')
+
+
+class t_gen(rv_continuous):
+    r"""A Student's t continuous random variable.
+
+    For the noncentral t distribution, see `nct`.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    nct
+
+    Notes
+    -----
+    The probability density function for `t` is:
+
+    .. math::
+
+        f(x, \nu) = \frac{\Gamma((\nu+1)/2)}
+                        {\sqrt{\pi \nu} \Gamma(\nu/2)}
+                    (1+x^2/\nu)^{-(\nu+1)/2}
+
+    where :math:`x` is a real number and the degrees of freedom parameter
+    :math:`\nu` (denoted ``df`` in the implementation) satisfies
+    :math:`\nu > 0`. :math:`\Gamma` is the gamma function
+    (`scipy.special.gamma`).
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("df", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, df, size=None, random_state=None):
+        return random_state.standard_t(df, size=size)
+
+    def _pdf(self, x, df):
+        return _lazywhere(
+            df == np.inf, (x, df),
+            f=lambda x, df: norm._pdf(x),
+            f2=lambda x, df: (
+                np.exp(self._logpdf(x, df))
+            )
+        )
+
+    def _logpdf(self, x, df):
+
+        def t_logpdf(x, df):
+            return (np.log(sc.poch(0.5 * df, 0.5))
+                    - 0.5 * (np.log(df) + np.log(np.pi))
+                    - (df + 1)/2*np.log1p(x * x/df))
+
+        def norm_logpdf(x, df):
+            return norm._logpdf(x)
+
+        return _lazywhere(df == np.inf, (x, df, ), f=norm_logpdf, f2=t_logpdf)
+
+    def _cdf(self, x, df):
+        return sc.stdtr(df, x)
+
+    def _sf(self, x, df):
+        return sc.stdtr(df, -x)
+
+    def _ppf(self, q, df):
+        return sc.stdtrit(df, q)
+
+    def _isf(self, q, df):
+        return -sc.stdtrit(df, q)
+
+    def _stats(self, df):
+        # infinite df -> normal distribution (0.0, 1.0, 0.0, 0.0)
+        infinite_df = np.isposinf(df)
+
+        mu = np.where(df > 1, 0.0, np.inf)
+
+        condlist = ((df > 1) & (df <= 2),
+                    (df > 2) & np.isfinite(df),
+                    infinite_df)
+        choicelist = (lambda df: np.broadcast_to(np.inf, df.shape),
+                      lambda df: df / (df-2.0),
+                      lambda df: np.broadcast_to(1, df.shape))
+        mu2 = _lazyselect(condlist, choicelist, (df,), np.nan)
+
+        g1 = np.where(df > 3, 0.0, np.nan)
+
+        condlist = ((df > 2) & (df <= 4),
+                    (df > 4) & np.isfinite(df),
+                    infinite_df)
+        choicelist = (lambda df: np.broadcast_to(np.inf, df.shape),
+                      lambda df: 6.0 / (df-4.0),
+                      lambda df: np.broadcast_to(0, df.shape))
+        g2 = _lazyselect(condlist, choicelist, (df,), np.nan)
+
+        return mu, mu2, g1, g2
+
+    def _entropy(self, df):
+        if df == np.inf:
+            return norm._entropy()
+
+        def regular(df):
+            half = df/2
+            half1 = (df + 1)/2
+            return (half1*(sc.digamma(half1) - sc.digamma(half))
+                    + np.log(np.sqrt(df)*sc.beta(half, 0.5)))
+
+        def asymptotic(df):
+            # Formula from Wolfram Alpha:
+            # "asymptotic expansion (d+1)/2 * (digamma((d+1)/2) - digamma(d/2))
+            #  + log(sqrt(d) * beta(d/2, 1/2))"
+            h = (norm._entropy() + 1/df + (df**-2.)/4 - (df**-3.)/6
+                 - (df**-4.)/8 + 3/10*(df**-5.) + (df**-6.)/4)
+            return h
+
+        h = _lazywhere(df >= 100, (df, ), f=asymptotic, f2=regular)
+        return h
+
+
+t = t_gen(name='t')
+
+
+class nct_gen(rv_continuous):
+    r"""A non-central Student's t continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    If :math:`Y` is a standard normal random variable and :math:`V` is
+    an independent chi-square random variable (`chi2`) with :math:`k` degrees
+    of freedom, then
+
+    .. math::
+
+        X = \frac{Y + c}{\sqrt{V/k}}
+
+    has a non-central Student's t distribution on the real line.
+    The degrees of freedom parameter :math:`k` (denoted ``df`` in the
+    implementation) satisfies :math:`k > 0` and the noncentrality parameter
+    :math:`c` (denoted ``nc`` in the implementation) is a real number.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pdf``, ``cdf``, ``ppf``, ``sf`` and ``isf``
+    methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _argcheck(self, df, nc):
+        return (df > 0) & (nc == nc)
+
+    def _shape_info(self):
+        idf = _ShapeInfo("df", False, (0, np.inf), (False, False))
+        inc = _ShapeInfo("nc", False, (-np.inf, np.inf), (False, False))
+        return [idf, inc]
+
+    def _rvs(self, df, nc, size=None, random_state=None):
+        n = norm.rvs(loc=nc, size=size, random_state=random_state)
+        c2 = chi2.rvs(df, size=size, random_state=random_state)
+        return n * np.sqrt(df) / np.sqrt(c2)
+
+    def _pdf(self, x, df, nc):
+        return scu._nct_pdf(x, df, nc)
+
+    def _cdf(self, x, df, nc):
+        return sc.nctdtr(df, nc, x)
+
+    def _ppf(self, q, df, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._nct_ppf(q, df, nc)
+
+    def _sf(self, x, df, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return np.clip(scu._nct_sf(x, df, nc), 0, 1)
+
+    def _isf(self, x, df, nc):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._nct_isf(x, df, nc)
+
+    def _stats(self, df, nc, moments='mv'):
+        mu = scu._nct_mean(df, nc)
+        mu2 = scu._nct_variance(df, nc)
+        g1 = scu._nct_skewness(df, nc) if 's' in moments else None
+        g2 = scu._nct_kurtosis_excess(df, nc) if 'k' in moments else None
+        return mu, mu2, g1, g2
+
+
+nct = nct_gen(name="nct")
+
+
+class pareto_gen(rv_continuous):
+    r"""A Pareto continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `pareto` is:
+
+    .. math::
+
+        f(x, b) = \frac{b}{x^{b+1}}
+
+    for :math:`x \ge 1`, :math:`b > 0`.
+
+    `pareto` takes ``b`` as a shape parameter for :math:`b`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, b):
+        # pareto.pdf(x, b) = b / x**(b+1)
+        return b * x**(-b-1)
+
+    def _cdf(self, x, b):
+        return 1 - x**(-b)
+
+    def _ppf(self, q, b):
+        return pow(1-q, -1.0/b)
+
+    def _sf(self, x, b):
+        return x**(-b)
+
+    def _isf(self, q, b):
+        return np.power(q, -1.0 / b)
+
+    def _stats(self, b, moments='mv'):
+        mu, mu2, g1, g2 = None, None, None, None
+        if 'm' in moments:
+            mask = b > 1
+            bt = np.extract(mask, b)
+            mu = np.full(np.shape(b), fill_value=np.inf)
+            np.place(mu, mask, bt / (bt-1.0))
+        if 'v' in moments:
+            mask = b > 2
+            bt = np.extract(mask, b)
+            mu2 = np.full(np.shape(b), fill_value=np.inf)
+            np.place(mu2, mask, bt / (bt-2.0) / (bt-1.0)**2)
+        if 's' in moments:
+            mask = b > 3
+            bt = np.extract(mask, b)
+            g1 = np.full(np.shape(b), fill_value=np.nan)
+            vals = 2 * (bt + 1.0) * np.sqrt(bt - 2.0) / ((bt - 3.0) * np.sqrt(bt))
+            np.place(g1, mask, vals)
+        if 'k' in moments:
+            mask = b > 4
+            bt = np.extract(mask, b)
+            g2 = np.full(np.shape(b), fill_value=np.nan)
+            vals = (6.0*np.polyval([1.0, 1.0, -6, -2], bt) /
+                    np.polyval([1.0, -7.0, 12.0, 0.0], bt))
+            np.place(g2, mask, vals)
+        return mu, mu2, g1, g2
+
+    def _entropy(self, b):
+        return 1 + 1.0/b - np.log(b)
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        parameters = _check_fit_input_parameters(self, data, args, kwds)
+        data, fshape, floc, fscale = parameters
+
+        # ensure that any fixed parameters don't violate constraints of the
+        # distribution before continuing.
+        if floc is not None and np.min(data) - floc < (fscale or 0):
+            raise FitDataError("pareto", lower=1, upper=np.inf)
+
+        ndata = data.shape[0]
+
+        def get_shape(scale, location):
+            # The first-order necessary condition on `shape` can be solved in
+            # closed form
+            return ndata / np.sum(np.log((data - location) / scale))
+
+        if floc is fscale is None:
+            # The support of the distribution is `(x - loc)/scale > 0`.
+            # The method of Lagrange multipliers turns this constraint
+            # into an equation that can be solved numerically.
+            # See gh-12545 for details.
+
+            def dL_dScale(shape, scale):
+                # The partial derivative of the log-likelihood function w.r.t.
+                # the scale.
+                return ndata * shape / scale
+
+            def dL_dLocation(shape, location):
+                # The partial derivative of the log-likelihood function w.r.t.
+                # the location.
+                return (shape + 1) * np.sum(1 / (data - location))
+
+            def fun_to_solve(scale):
+                # optimize the scale by setting the partial derivatives
+                # w.r.t. to location and scale equal and solving.
+                location = np.min(data) - scale
+                shape = fshape or get_shape(scale, location)
+                return dL_dLocation(shape, location) - dL_dScale(shape, scale)
+
+            def interval_contains_root(lbrack, rbrack):
+                # return true if the signs disagree.
+                return (np.sign(fun_to_solve(lbrack)) !=
+                        np.sign(fun_to_solve(rbrack)))
+
+            # set brackets for `root_scalar` to use when optimizing over the
+            # scale such that a root is likely between them. Use user supplied
+            # guess or default 1.
+            brack_start = float(kwds.get('scale', 1))
+            lbrack, rbrack = brack_start / 2, brack_start * 2
+            # if a root is not between the brackets, iteratively expand them
+            # until they include a sign change, checking after each bracket is
+            # modified.
+            while (not interval_contains_root(lbrack, rbrack)
+                   and (lbrack > 0 or rbrack < np.inf)):
+                lbrack /= 2
+                rbrack *= 2
+            res = root_scalar(fun_to_solve, bracket=[lbrack, rbrack])
+            if res.converged:
+                scale = res.root
+                loc = np.min(data) - scale
+                shape = fshape or get_shape(scale, loc)
+
+                # The Pareto distribution requires that its parameters satisfy
+                # the condition `fscale + floc <= min(data)`. However, to
+                # avoid numerical issues, we require that `fscale + floc`
+                # is strictly less than `min(data)`. If this condition
+                # is not satisfied, reduce the scale with `np.nextafter` to
+                # ensure that data does not fall outside of the support.
+                if not (scale + loc) < np.min(data):
+                    scale = np.min(data) - loc
+                    scale = np.nextafter(scale, 0)
+                return shape, loc, scale
+            else:
+                return super().fit(data, **kwds)
+        elif floc is None:
+            loc = np.min(data) - fscale
+        else:
+            loc = floc
+        # Source: Evans, Hastings, and Peacock (2000), Statistical
+        # Distributions, 3rd. Ed., John Wiley and Sons. Page 149.
+        scale = fscale or np.min(data) - loc
+        shape = fshape or get_shape(scale, loc)
+        return shape, loc, scale
+
+
+pareto = pareto_gen(a=1.0, name="pareto")
+
+
+class lomax_gen(rv_continuous):
+    r"""A Lomax (Pareto of the second kind) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `lomax` is:
+
+    .. math::
+
+        f(x, c) = \frac{c}{(1+x)^{c+1}}
+
+    for :math:`x \ge 0`, :math:`c > 0`.
+
+    `lomax` takes ``c`` as a shape parameter for :math:`c`.
+
+    `lomax` is a special case of `pareto` with ``loc=-1.0``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # lomax.pdf(x, c) = c / (1+x)**(c+1)
+        return c*1.0/(1.0+x)**(c+1.0)
+
+    def _logpdf(self, x, c):
+        return np.log(c) - (c+1)*sc.log1p(x)
+
+    def _cdf(self, x, c):
+        return -sc.expm1(-c*sc.log1p(x))
+
+    def _sf(self, x, c):
+        return np.exp(-c*sc.log1p(x))
+
+    def _logsf(self, x, c):
+        return -c*sc.log1p(x)
+
+    def _ppf(self, q, c):
+        return sc.expm1(-sc.log1p(-q)/c)
+
+    def _isf(self, q, c):
+        return q**(-1.0 / c) - 1
+
+    def _stats(self, c):
+        mu, mu2, g1, g2 = pareto.stats(c, loc=-1.0, moments='mvsk')
+        return mu, mu2, g1, g2
+
+    def _entropy(self, c):
+        return 1+1.0/c-np.log(c)
+
+
+lomax = lomax_gen(a=0.0, name="lomax")
+
+
+class pearson3_gen(rv_continuous):
+    r"""A pearson type III continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `pearson3` is:
+
+    .. math::
+
+        f(x, \kappa) = \frac{|\beta|}{\Gamma(\alpha)}
+                       (\beta (x - \zeta))^{\alpha - 1}
+                       \exp(-\beta (x - \zeta))
+
+    where:
+
+    .. math::
+
+            \beta = \frac{2}{\kappa}
+
+            \alpha = \beta^2 = \frac{4}{\kappa^2}
+
+            \zeta = -\frac{\alpha}{\beta} = -\beta
+
+    :math:`\Gamma` is the gamma function (`scipy.special.gamma`).
+    Pass the skew :math:`\kappa` into `pearson3` as the shape parameter
+    ``skew``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    References
+    ----------
+    R.W. Vogel and D.E. McMartin, "Probability Plot Goodness-of-Fit and
+    Skewness Estimation Procedures for the Pearson Type 3 Distribution", Water
+    Resources Research, Vol.27, 3149-3158 (1991).
+
+    L.R. Salvosa, "Tables of Pearson's Type III Function", Ann. Math. Statist.,
+    Vol.1, 191-198 (1930).
+
+    "Using Modern Computing Tools to Fit the Pearson Type III Distribution to
+    Aviation Loads Data", Office of Aviation Research (2003).
+
+    """
+    def _preprocess(self, x, skew):
+        # The real 'loc' and 'scale' are handled in the calling pdf(...). The
+        # local variables 'loc' and 'scale' within pearson3._pdf are set to
+        # the defaults just to keep them as part of the equations for
+        # documentation.
+        loc = 0.0
+        scale = 1.0
+
+        # If skew is small, return _norm_pdf. The divide between pearson3
+        # and norm was found by brute force and is approximately a skew of
+        # 0.000016.  No one, I hope, would actually use a skew value even
+        # close to this small.
+        norm2pearson_transition = 0.000016
+
+        ans, x, skew = np.broadcast_arrays(1.0, x, skew)
+        ans = ans.copy()
+
+        # mask is True where skew is small enough to use the normal approx.
+        mask = np.absolute(skew) < norm2pearson_transition
+        invmask = ~mask
+
+        beta = 2.0 / (skew[invmask] * scale)
+        alpha = (scale * beta)**2
+        zeta = loc - alpha / beta
+
+        transx = beta * (x[invmask] - zeta)
+        return ans, x, transx, mask, invmask, beta, alpha, zeta
+
+    def _argcheck(self, skew):
+        # The _argcheck function in rv_continuous only allows positive
+        # arguments.  The skew argument for pearson3 can be zero (which I want
+        # to handle inside pearson3._pdf) or negative.  So just return True
+        # for all skew args.
+        return np.isfinite(skew)
+
+    def _shape_info(self):
+        return [_ShapeInfo("skew", False, (-np.inf, np.inf), (False, False))]
+
+    def _stats(self, skew):
+        m = 0.0
+        v = 1.0
+        s = skew
+        k = 1.5*skew**2
+        return m, v, s, k
+
+    def _pdf(self, x, skew):
+        # pearson3.pdf(x, skew) = abs(beta) / gamma(alpha) *
+        #     (beta * (x - zeta))**(alpha - 1) * exp(-beta*(x - zeta))
+        # Do the calculation in _logpdf since helps to limit
+        # overflow/underflow problems
+        ans = np.exp(self._logpdf(x, skew))
+        if ans.ndim == 0:
+            if np.isnan(ans):
+                return 0.0
+            return ans
+        ans[np.isnan(ans)] = 0.0
+        return ans
+
+    def _logpdf(self, x, skew):
+        #   PEARSON3 logpdf                           GAMMA logpdf
+        #   np.log(abs(beta))
+        # + (alpha - 1)*np.log(beta*(x - zeta))          + (a - 1)*np.log(x)
+        # - beta*(x - zeta)                           - x
+        # - sc.gammalnalpha)                              - sc.gammalna)
+        ans, x, transx, mask, invmask, beta, alpha, _ = (
+            self._preprocess(x, skew))
+
+        ans[mask] = np.log(_norm_pdf(x[mask]))
+        # use logpdf instead of _logpdf to fix issue mentioned in gh-12640
+        # (_logpdf does not return correct result for alpha = 1)
+        ans[invmask] = np.log(abs(beta)) + gamma.logpdf(transx, alpha)
+        return ans
+
+    def _cdf(self, x, skew):
+        ans, x, transx, mask, invmask, _, alpha, _ = (
+            self._preprocess(x, skew))
+
+        ans[mask] = _norm_cdf(x[mask])
+
+        skew = np.broadcast_to(skew, invmask.shape)
+        invmask1a = np.logical_and(invmask, skew > 0)
+        invmask1b = skew[invmask] > 0
+        # use cdf instead of _cdf to fix issue mentioned in gh-12640
+        # (_cdf produces NaNs for inputs outside support)
+        ans[invmask1a] = gamma.cdf(transx[invmask1b], alpha[invmask1b])
+
+        # The gamma._cdf approach wasn't working with negative skew.
+        # Note that multiplying the skew by -1 reflects about x=0.
+        # So instead of evaluating the CDF with negative skew at x,
+        # evaluate the SF with positive skew at -x.
+        invmask2a = np.logical_and(invmask, skew < 0)
+        invmask2b = skew[invmask] < 0
+        # gamma._sf produces NaNs when transx < 0, so use gamma.sf
+        ans[invmask2a] = gamma.sf(transx[invmask2b], alpha[invmask2b])
+
+        return ans
+
+    def _sf(self, x, skew):
+        ans, x, transx, mask, invmask, _, alpha, _ = (
+            self._preprocess(x, skew))
+
+        ans[mask] = _norm_sf(x[mask])
+
+        skew = np.broadcast_to(skew, invmask.shape)
+        invmask1a = np.logical_and(invmask, skew > 0)
+        invmask1b = skew[invmask] > 0
+        ans[invmask1a] = gamma.sf(transx[invmask1b], alpha[invmask1b])
+
+        invmask2a = np.logical_and(invmask, skew < 0)
+        invmask2b = skew[invmask] < 0
+        ans[invmask2a] = gamma.cdf(transx[invmask2b], alpha[invmask2b])
+
+        return ans
+
+    def _rvs(self, skew, size=None, random_state=None):
+        skew = np.broadcast_to(skew, size)
+        ans, _, _, mask, invmask, beta, alpha, zeta = (
+            self._preprocess([0], skew))
+
+        nsmall = mask.sum()
+        nbig = mask.size - nsmall
+        ans[mask] = random_state.standard_normal(nsmall)
+        ans[invmask] = random_state.standard_gamma(alpha, nbig)/beta + zeta
+
+        if size == ():
+            ans = ans[0]
+        return ans
+
+    def _ppf(self, q, skew):
+        ans, q, _, mask, invmask, beta, alpha, zeta = (
+            self._preprocess(q, skew))
+        ans[mask] = _norm_ppf(q[mask])
+        q = q[invmask]
+        q[beta < 0] = 1 - q[beta < 0]  # for negative skew; see gh-17050
+        ans[invmask] = sc.gammaincinv(alpha, q)/beta + zeta
+        return ans
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        Note that method of moments (`method='MM'`) is not
+        available for this distribution.\n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.get("method", None) == 'MM':
+            raise NotImplementedError("Fit `method='MM'` is not available for "
+                                      "the Pearson3 distribution. Please try "
+                                      "the default `method='MLE'`.")
+        else:
+            return super(type(self), self).fit(data, *args, **kwds)
+
+
+pearson3 = pearson3_gen(name="pearson3")
+
+
+class powerlaw_gen(rv_continuous):
+    r"""A power-function continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    pareto
+
+    Notes
+    -----
+    The probability density function for `powerlaw` is:
+
+    .. math::
+
+        f(x, a) = a x^{a-1}
+
+    for :math:`0 \le x \le 1`, :math:`a > 0`.
+
+    `powerlaw` takes ``a`` as a shape parameter for :math:`a`.
+
+    %(after_notes)s
+
+    For example, the support of `powerlaw` can be adjusted from the default
+    interval ``[0, 1]`` to the interval ``[c, c+d]`` by setting ``loc=c`` and
+    ``scale=d``. For a power-law distribution with infinite support, see
+    `pareto`.
+
+    `powerlaw` is a special case of `beta` with ``b=1``.
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        # powerlaw.pdf(x, a) = a * x**(a-1)
+        return a*x**(a-1.0)
+
+    def _logpdf(self, x, a):
+        return np.log(a) + sc.xlogy(a - 1, x)
+
+    def _cdf(self, x, a):
+        return x**(a*1.0)
+
+    def _logcdf(self, x, a):
+        return a*np.log(x)
+
+    def _ppf(self, q, a):
+        return pow(q, 1.0/a)
+
+    def _sf(self, p, a):
+        return -sc.powm1(p, a)
+
+    def _munp(self, n, a):
+        # The following expression is correct for all real n (provided a > 0).
+        return a / (a + n)
+
+    def _stats(self, a):
+        return (a / (a + 1.0),
+                a / (a + 2.0) / (a + 1.0) ** 2,
+                -2.0 * ((a - 1.0) / (a + 3.0)) * np.sqrt((a + 2.0) / a),
+                6 * np.polyval([1, -1, -6, 2], a) / (a * (a + 3.0) * (a + 4)))
+
+    def _entropy(self, a):
+        return 1 - 1.0/a - np.log(a)
+
+    def _support_mask(self, x, a):
+        return (super()._support_mask(x, a)
+                & ((x != 0) | (a >= 1)))
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        Notes specifically for ``powerlaw.fit``: If the location is a free
+        parameter and the value returned for the shape parameter is less than
+        one, the true maximum likelihood approaches infinity. This causes
+        numerical difficulties, and the resulting estimates are approximate.
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+        # Summary of the strategy:
+        #
+        # 1) If the scale and location are fixed, return the shape according
+        #    to a formula.
+        #
+        # 2) If the scale is fixed, there are two possibilities for the other
+        #    parameters - one corresponding with shape less than one, and
+        #    another with shape greater than one. Calculate both, and return
+        #    whichever has the better log-likelihood.
+        #
+        # At this point, the scale is known to be free.
+        #
+        # 3) If the location is fixed, return the scale and shape according to
+        #    formulas (or, if the shape is fixed, the fixed shape).
+        #
+        # At this point, the location and scale are both free. There are
+        # separate equations depending on whether the shape is less than one or
+        # greater than one.
+        #
+        # 4a) If the shape is less than one, there are formulas for shape,
+        #     location, and scale.
+        # 4b) If the shape is greater than one, there are formulas for shape
+        #     and scale, but there is a condition for location to be solved
+        #     numerically.
+        #
+        # If the shape is fixed and less than one, we use 4a.
+        # If the shape is fixed and greater than one, we use 4b.
+        # If the shape is also free, we calculate fits using both 4a and 4b
+        # and choose the one that results a better log-likelihood.
+        #
+        # In many cases, the use of `np.nextafter` is used to avoid numerical
+        # issues.
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        if len(np.unique(data)) == 1:
+            return super().fit(data, *args, **kwds)
+
+        data, fshape, floc, fscale = _check_fit_input_parameters(self, data,
+                                                                 args, kwds)
+        penalized_nllf_args = [data, (self._fitstart(data),)]
+        penalized_nllf = self._reduce_func(penalized_nllf_args, {})[1]
+
+        # ensure that any fixed parameters don't violate constraints of the
+        # distribution before continuing. The support of the distribution
+        # is `0 < (x - loc)/scale < 1`.
+        if floc is not None:
+            if not data.min() > floc:
+                raise FitDataError('powerlaw', 0, 1)
+            if fscale is not None and not data.max() <= floc + fscale:
+                raise FitDataError('powerlaw', 0, 1)
+
+        if fscale is not None:
+            if fscale <= 0:
+                raise ValueError("Negative or zero `fscale` is outside the "
+                                 "range allowed by the distribution.")
+            if fscale <= np.ptp(data):
+                msg = "`fscale` must be greater than the range of data."
+                raise ValueError(msg)
+
+        def get_shape(data, loc, scale):
+            # The first-order necessary condition on `shape` can be solved in
+            # closed form. It can be used no matter the assumption of the
+            # value of the shape.
+            N = len(data)
+            return - N / (np.sum(np.log(data - loc)) - N*np.log(scale))
+
+        def get_scale(data, loc):
+            # analytical solution for `scale` based on the location.
+            # It can be used no matter the assumption of the value of the
+            # shape.
+            return data.max() - loc
+
+        # 1) The location and scale are both fixed. Analytically determine the
+        # shape.
+        if fscale is not None and floc is not None:
+            return get_shape(data, floc, fscale), floc, fscale
+
+        # 2) The scale is fixed. There are two possibilities for the other
+        # parameters. Choose the option with better log-likelihood.
+        if fscale is not None:
+            # using `data.min()` as the optimal location
+            loc_lt1 = np.nextafter(data.min(), -np.inf)
+            shape_lt1 = fshape or get_shape(data, loc_lt1, fscale)
+            ll_lt1 = penalized_nllf((shape_lt1, loc_lt1, fscale), data)
+
+            # using `data.max() - scale` as the optimal location
+            loc_gt1 = np.nextafter(data.max() - fscale, np.inf)
+            shape_gt1 = fshape or get_shape(data, loc_gt1, fscale)
+            ll_gt1 = penalized_nllf((shape_gt1, loc_gt1, fscale), data)
+
+            if ll_lt1 < ll_gt1:
+                return shape_lt1, loc_lt1, fscale
+            else:
+                return shape_gt1, loc_gt1, fscale
+
+        # 3) The location is fixed. Return the analytical scale and the
+        # analytical (or fixed) shape.
+        if floc is not None:
+            scale = get_scale(data, floc)
+            shape = fshape or get_shape(data, floc, scale)
+            return shape, floc, scale
+
+        # 4) Location and scale are both free
+        # 4a) Use formulas that assume `shape <= 1`.
+
+        def fit_loc_scale_w_shape_lt_1():
+            loc = np.nextafter(data.min(), -np.inf)
+            if np.abs(loc) < np.finfo(loc.dtype).tiny:
+                loc = np.sign(loc) * np.finfo(loc.dtype).tiny
+            scale = np.nextafter(get_scale(data, loc), np.inf)
+            shape = fshape or get_shape(data, loc, scale)
+            return shape, loc, scale
+
+        # 4b) Fit under the assumption that `shape > 1`. The support
+        # of the distribution is `(x - loc)/scale <= 1`. The method of Lagrange
+        # multipliers turns this constraint into the condition that
+        # dL_dScale - dL_dLocation must be zero, which is solved numerically.
+        # (Alternatively, substitute the constraint into the objective
+        # function before deriving the likelihood equation for location.)
+
+        def dL_dScale(data, shape, scale):
+            # The partial derivative of the log-likelihood function w.r.t.
+            # the scale.
+            return -data.shape[0] * shape / scale
+
+        def dL_dLocation(data, shape, loc):
+            # The partial derivative of the log-likelihood function w.r.t.
+            # the location.
+            return (shape - 1) * np.sum(1 / (loc - data))  # -1/(data-loc)
+
+        def dL_dLocation_star(loc):
+            # The derivative of the log-likelihood function w.r.t.
+            # the location, given optimal shape and scale
+            scale = np.nextafter(get_scale(data, loc), -np.inf)
+            shape = fshape or get_shape(data, loc, scale)
+            return dL_dLocation(data, shape, loc)
+
+        def fun_to_solve(loc):
+            # optimize the location by setting the partial derivatives
+            # w.r.t. to location and scale equal and solving.
+            scale = np.nextafter(get_scale(data, loc), -np.inf)
+            shape = fshape or get_shape(data, loc, scale)
+            return (dL_dScale(data, shape, scale)
+                    - dL_dLocation(data, shape, loc))
+
+        def fit_loc_scale_w_shape_gt_1():
+            # set brackets for `root_scalar` to use when optimizing over the
+            # location such that a root is likely between them.
+            rbrack = np.nextafter(data.min(), -np.inf)
+
+            # if the sign of `dL_dLocation_star` is positive at rbrack,
+            # we're not going to find the root we're looking for
+            delta = (data.min() - rbrack)
+            while dL_dLocation_star(rbrack) > 0:
+                rbrack = data.min() - delta
+                delta *= 2
+
+            def interval_contains_root(lbrack, rbrack):
+                # Check if the interval (lbrack, rbrack) contains the root.
+                return (np.sign(fun_to_solve(lbrack))
+                        != np.sign(fun_to_solve(rbrack)))
+
+            lbrack = rbrack - 1
+
+            # if the sign doesn't change between the brackets, move the left
+            # bracket until it does. (The right bracket remains fixed at the
+            # maximum permissible value.)
+            i = 1.0
+            while (not interval_contains_root(lbrack, rbrack)
+                   and lbrack != -np.inf):
+                lbrack = (data.min() - i)
+                i *= 2
+
+            root = optimize.root_scalar(fun_to_solve, bracket=(lbrack, rbrack))
+
+            loc = np.nextafter(root.root, -np.inf)
+            scale = np.nextafter(get_scale(data, loc), np.inf)
+            shape = fshape or get_shape(data, loc, scale)
+            return shape, loc, scale
+
+        # Shape is fixed - choose 4a or 4b accordingly.
+        if fshape is not None and fshape <= 1:
+            return fit_loc_scale_w_shape_lt_1()
+        elif fshape is not None and fshape > 1:
+            return fit_loc_scale_w_shape_gt_1()
+
+        # Shape is free
+        fit_shape_lt1 = fit_loc_scale_w_shape_lt_1()
+        ll_lt1 = self.nnlf(fit_shape_lt1, data)
+
+        fit_shape_gt1 = fit_loc_scale_w_shape_gt_1()
+        ll_gt1 = self.nnlf(fit_shape_gt1, data)
+
+        if ll_lt1 <= ll_gt1 and fit_shape_lt1[0] <= 1:
+            return fit_shape_lt1
+        elif ll_lt1 > ll_gt1 and fit_shape_gt1[0] > 1:
+            return fit_shape_gt1
+        else:
+            return super().fit(data, *args, **kwds)
+
+
+powerlaw = powerlaw_gen(a=0.0, b=1.0, name="powerlaw")
+
+
+class powerlognorm_gen(rv_continuous):
+    r"""A power log-normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `powerlognorm` is:
+
+    .. math::
+
+        f(x, c, s) = \frac{c}{x s} \phi(\log(x)/s)
+                     (\Phi(-\log(x)/s))^{c-1}
+
+    where :math:`\phi` is the normal pdf, and :math:`\Phi` is the normal cdf,
+    and :math:`x > 0`, :math:`s, c > 0`.
+
+    `powerlognorm` takes :math:`c` and :math:`s` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
+        i_s = _ShapeInfo("s", False, (0, np.inf), (False, False))
+        return [ic, i_s]
+
+    def _pdf(self, x, c, s):
+        return np.exp(self._logpdf(x, c, s))
+
+    def _logpdf(self, x, c, s):
+        return (np.log(c) - np.log(x) - np.log(s) +
+                _norm_logpdf(np.log(x) / s) +
+                _norm_logcdf(-np.log(x) / s) * (c - 1.))
+
+    def _cdf(self, x, c, s):
+        return -sc.expm1(self._logsf(x, c, s))
+
+    def _ppf(self, q, c, s):
+        return self._isf(1 - q, c, s)
+
+    def _sf(self, x, c, s):
+        return np.exp(self._logsf(x, c, s))
+
+    def _logsf(self, x, c, s):
+        return _norm_logcdf(-np.log(x) / s) * c
+
+    def _isf(self, q, c, s):
+        return np.exp(-_norm_ppf(q**(1/c)) * s)
+
+
+powerlognorm = powerlognorm_gen(a=0.0, name="powerlognorm")
+
+
+class powernorm_gen(rv_continuous):
+    r"""A power normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `powernorm` is:
+
+    .. math::
+
+        f(x, c) = c \phi(x) (\Phi(-x))^{c-1}
+
+    where :math:`\phi` is the normal pdf, :math:`\Phi` is the normal cdf,
+    :math:`x` is any real, and :math:`c > 0` [1]_.
+
+    `powernorm` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] NIST Engineering Statistics Handbook, Section 1.3.6.6.13,
+           https://www.itl.nist.gov/div898/handbook//eda/section3/eda366d.htm
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, c):
+        # powernorm.pdf(x, c) = c * phi(x) * (Phi(-x))**(c-1)
+        return c*_norm_pdf(x) * (_norm_cdf(-x)**(c-1.0))
+
+    def _logpdf(self, x, c):
+        return np.log(c) + _norm_logpdf(x) + (c-1)*_norm_logcdf(-x)
+
+    def _cdf(self, x, c):
+        return -sc.expm1(self._logsf(x, c))
+
+    def _ppf(self, q, c):
+        return -_norm_ppf(pow(1.0 - q, 1.0 / c))
+
+    def _sf(self, x, c):
+        return np.exp(self._logsf(x, c))
+
+    def _logsf(self, x, c):
+        return c * _norm_logcdf(-x)
+
+    def _isf(self, q, c):
+        return -_norm_ppf(np.exp(np.log(q) / c))
+
+
+powernorm = powernorm_gen(name='powernorm')
+
+
+class rdist_gen(rv_continuous):
+    r"""An R-distributed (symmetric beta) continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `rdist` is:
+
+    .. math::
+
+        f(x, c) = \frac{(1-x^2)^{c/2-1}}{B(1/2, c/2)}
+
+    for :math:`-1 \le x \le 1`, :math:`c > 0`. `rdist` is also called the
+    symmetric beta distribution: if B has a `beta` distribution with
+    parameters (c/2, c/2), then X = 2*B - 1 follows a R-distribution with
+    parameter c.
+
+    `rdist` takes ``c`` as a shape parameter for :math:`c`.
+
+    This distribution includes the following distribution kernels as
+    special cases::
+
+        c = 2:  uniform
+        c = 3:  `semicircular`
+        c = 4:  Epanechnikov (parabolic)
+        c = 6:  quartic (biweight)
+        c = 8:  triweight
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, np.inf), (False, False))]
+
+    # use relation to the beta distribution for pdf, cdf, etc
+    def _pdf(self, x, c):
+        return np.exp(self._logpdf(x, c))
+
+    def _logpdf(self, x, c):
+        return -np.log(2) + beta._logpdf((x + 1)/2, c/2, c/2)
+
+    def _cdf(self, x, c):
+        return beta._cdf((x + 1)/2, c/2, c/2)
+
+    def _sf(self, x, c):
+        return beta._sf((x + 1)/2, c/2, c/2)
+
+    def _ppf(self, q, c):
+        return 2*beta._ppf(q, c/2, c/2) - 1
+
+    def _rvs(self, c, size=None, random_state=None):
+        return 2 * random_state.beta(c/2, c/2, size) - 1
+
+    def _munp(self, n, c):
+        numerator = (1 - (n % 2)) * sc.beta((n + 1.0) / 2, c / 2.0)
+        return numerator / sc.beta(1. / 2, c / 2.)
+
+
+rdist = rdist_gen(a=-1.0, b=1.0, name="rdist")
+
+
+class rayleigh_gen(rv_continuous):
+    r"""A Rayleigh continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `rayleigh` is:
+
+    .. math::
+
+        f(x) = x \exp(-x^2/2)
+
+    for :math:`x \ge 0`.
+
+    `rayleigh` is a special case of `chi` with ``df=2``.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return chi.rvs(2, size=size, random_state=random_state)
+
+    def _pdf(self, r):
+        # rayleigh.pdf(r) = r * exp(-r**2/2)
+        return np.exp(self._logpdf(r))
+
+    def _logpdf(self, r):
+        return np.log(r) - 0.5 * r * r
+
+    def _cdf(self, r):
+        return -sc.expm1(-0.5 * r**2)
+
+    def _ppf(self, q):
+        return np.sqrt(-2 * sc.log1p(-q))
+
+    def _sf(self, r):
+        return np.exp(self._logsf(r))
+
+    def _logsf(self, r):
+        return -0.5 * r * r
+
+    def _isf(self, q):
+        return np.sqrt(-2 * np.log(q))
+
+    def _stats(self):
+        val = 4 - np.pi
+        return (np.sqrt(np.pi/2),
+                val/2,
+                2*(np.pi-3)*np.sqrt(np.pi)/val**1.5,
+                6*np.pi/val-16/val**2)
+
+    def _entropy(self):
+        return _EULER/2.0 + 1 - 0.5*np.log(2)
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        Notes specifically for ``rayleigh.fit``: If the location is fixed with
+        the `floc` parameter, this method uses an analytical formula to find
+        the scale.  Otherwise, this function uses a numerical root finder on
+        the first order conditions of the log-likelihood function to find the
+        MLE.  Only the (optional) `loc` parameter is used as the initial guess
+        for the root finder; the `scale` parameter and any other parameters
+        for the optimizer are ignored.\n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+        data, floc, fscale = _check_fit_input_parameters(self, data,
+                                                         args, kwds)
+
+        def scale_mle(loc):
+            # Source: Statistical Distributions, 3rd Edition. Evans, Hastings,
+            # and Peacock (2000), Page 175
+            return (np.sum((data - loc) ** 2) / (2 * len(data))) ** .5
+
+        def loc_mle(loc):
+            # This implicit equation for `loc` is used when
+            # both `loc` and `scale` are free.
+            xm = data - loc
+            s1 = xm.sum()
+            s2 = (xm**2).sum()
+            s3 = (1/xm).sum()
+            return s1 - s2/(2*len(data))*s3
+
+        def loc_mle_scale_fixed(loc, scale=fscale):
+            # This implicit equation for `loc` is used when
+            # `scale` is fixed but `loc` is not.
+            xm = data - loc
+            return xm.sum() - scale**2 * (1/xm).sum()
+
+        if floc is not None:
+            # `loc` is fixed, analytically determine `scale`.
+            if np.any(data - floc <= 0):
+                raise FitDataError("rayleigh", lower=1, upper=np.inf)
+            else:
+                return floc, scale_mle(floc)
+
+        # Account for user provided guess of `loc`.
+        loc0 = kwds.get('loc')
+        if loc0 is None:
+            # Use _fitstart to estimate loc; ignore the returned scale.
+            loc0 = self._fitstart(data)[0]
+
+        fun = loc_mle if fscale is None else loc_mle_scale_fixed
+        rbrack = np.nextafter(np.min(data), -np.inf)
+        lbrack = _get_left_bracket(fun, rbrack)
+        res = optimize.root_scalar(fun, bracket=(lbrack, rbrack))
+        if not res.converged:
+            raise FitSolverError(res.flag)
+        loc = res.root
+        scale = fscale or scale_mle(loc)
+        return loc, scale
+
+
+rayleigh = rayleigh_gen(a=0.0, name="rayleigh")
+
+
+class reciprocal_gen(rv_continuous):
+    r"""A loguniform or reciprocal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for this class is:
+
+    .. math::
+
+        f(x, a, b) = \frac{1}{x \log(b/a)}
+
+    for :math:`a \le x \le b`, :math:`b > a > 0`. This class takes
+    :math:`a` and :math:`b` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    This doesn't show the equal probability of ``0.01``, ``0.1`` and
+    ``1``. This is best when the x-axis is log-scaled:
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.hist(np.log10(r))
+    >>> ax.set_ylabel("Frequency")
+    >>> ax.set_xlabel("Value of random variable")
+    >>> ax.xaxis.set_major_locator(plt.FixedLocator([-2, -1, 0]))
+    >>> ticks = ["$10^{{ {} }}$".format(i) for i in [-2, -1, 0]]
+    >>> ax.set_xticklabels(ticks)  # doctest: +SKIP
+    >>> plt.show()
+
+    This random variable will be log-uniform regardless of the base chosen for
+    ``a`` and ``b``. Let's specify with base ``2`` instead:
+
+    >>> rvs = %(name)s(2**-2, 2**0).rvs(size=1000)
+
+    Values of ``1/4``, ``1/2`` and ``1`` are equally likely with this random
+    variable.  Here's the histogram:
+
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.hist(np.log2(rvs))
+    >>> ax.set_ylabel("Frequency")
+    >>> ax.set_xlabel("Value of random variable")
+    >>> ax.xaxis.set_major_locator(plt.FixedLocator([-2, -1, 0]))
+    >>> ticks = ["$2^{{ {} }}$".format(i) for i in [-2, -1, 0]]
+    >>> ax.set_xticklabels(ticks)  # doctest: +SKIP
+    >>> plt.show()
+
+    """
+    def _argcheck(self, a, b):
+        return (a > 0) & (b > a)
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
+        ib = _ShapeInfo("b", False, (0, np.inf), (False, False))
+        return [ia, ib]
+
+    def _fitstart(self, data):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        # Reasonable, since support is [a, b]
+        return super()._fitstart(data, args=(np.min(data), np.max(data)))
+
+    def _get_support(self, a, b):
+        return a, b
+
+    def _pdf(self, x, a, b):
+        # reciprocal.pdf(x, a, b) = 1 / (x*(log(b) - log(a)))
+        return np.exp(self._logpdf(x, a, b))
+
+    def _logpdf(self, x, a, b):
+        return -np.log(x) - np.log(np.log(b) - np.log(a))
+
+    def _cdf(self, x, a, b):
+        return (np.log(x)-np.log(a)) / (np.log(b) - np.log(a))
+
+    def _ppf(self, q, a, b):
+        return np.exp(np.log(a) + q*(np.log(b) - np.log(a)))
+
+    def _munp(self, n, a, b):
+        if n == 0:
+            return 1.0
+        t1 = 1 / (np.log(b) - np.log(a)) / n
+        t2 = np.real(np.exp(_log_diff(n * np.log(b), n*np.log(a))))
+        return t1 * t2
+
+    def _entropy(self, a, b):
+        return 0.5*(np.log(a) + np.log(b)) + np.log(np.log(b) - np.log(a))
+
+    fit_note = """\
+        `loguniform`/`reciprocal` is over-parameterized. `fit` automatically
+         fixes `scale` to 1 unless `fscale` is provided by the user.\n\n"""
+
+    @extend_notes_in_docstring(rv_continuous, notes=fit_note)
+    def fit(self, data, *args, **kwds):
+        fscale = kwds.pop('fscale', 1)
+        return super().fit(data, *args, fscale=fscale, **kwds)
+
+    # Details related to the decision of not defining
+    # the survival function for this distribution can be
+    # found in the PR: https://github.com/scipy/scipy/pull/18614
+
+
+loguniform = reciprocal_gen(name="loguniform")
+reciprocal = reciprocal_gen(name="reciprocal")
+loguniform._support = ('a', 'b')
+reciprocal._support = ('a', 'b')
+
+
+class rice_gen(rv_continuous):
+    r"""A Rice continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `rice` is:
+
+    .. math::
+
+        f(x, b) = x \exp(- \frac{x^2 + b^2}{2}) I_0(x b)
+
+    for :math:`x >= 0`, :math:`b > 0`. :math:`I_0` is the modified Bessel
+    function of order zero (`scipy.special.i0`).
+
+    `rice` takes ``b`` as a shape parameter for :math:`b`.
+
+    %(after_notes)s
+
+    The Rice distribution describes the length, :math:`r`, of a 2-D vector with
+    components :math:`(U+u, V+v)`, where :math:`U, V` are constant, :math:`u,
+    v` are independent Gaussian random variables with standard deviation
+    :math:`s`.  Let :math:`R = \sqrt{U^2 + V^2}`. Then the pdf of :math:`r` is
+    ``rice.pdf(x, R/s, scale=s)``.
+
+    %(example)s
+
+    """
+    def _argcheck(self, b):
+        return b >= 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("b", False, (0, np.inf), (True, False))]
+
+    def _rvs(self, b, size=None, random_state=None):
+        # https://en.wikipedia.org/wiki/Rice_distribution
+        t = b/np.sqrt(2) + random_state.standard_normal(size=(2,) + size)
+        return np.sqrt((t*t).sum(axis=0))
+
+    def _cdf(self, x, b):
+        return sc.chndtr(np.square(x), 2, np.square(b))
+
+    def _ppf(self, q, b):
+        return np.sqrt(sc.chndtrix(q, 2, np.square(b)))
+
+    def _pdf(self, x, b):
+        # rice.pdf(x, b) = x * exp(-(x**2+b**2)/2) * I[0](x*b)
+        #
+        # We use (x**2 + b**2)/2 = ((x-b)**2)/2 + xb.
+        # The factor of np.exp(-xb) is then included in the i0e function
+        # in place of the modified Bessel function, i0, improving
+        # numerical stability for large values of xb.
+        return x * np.exp(-(x-b)*(x-b)/2.0) * sc.i0e(x*b)
+
+    def _munp(self, n, b):
+        nd2 = n/2.0
+        n1 = 1 + nd2
+        b2 = b*b/2.0
+        return (2.0**(nd2) * np.exp(-b2) * sc.gamma(n1) *
+                sc.hyp1f1(n1, 1, b2))
+
+
+rice = rice_gen(a=0.0, name="rice")
+
+class irwinhall_gen(rv_continuous):
+    r"""An Irwin-Hall (Uniform Sum) continuous random variable.
+
+    An `Irwin-Hall `_
+    continuous random variable is the sum of :math:`n` independent
+    standard uniform random variables [1]_ [2]_.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    Applications include `Rao's Spacing Test
+    `_,
+    a more powerful alternative to the Rayleigh test
+    when the data are not unimodal, and radar [3]_.
+
+    Conveniently, the pdf and cdf are the :math:`n`-fold convolution of
+    the ones for the standard uniform distribution, which is also the
+    definition of the cardinal B-splines of degree :math:`n-1`
+    having knots evenly spaced from :math:`1` to :math:`n` [4]_ [5]_.
+
+    The Bates distribution, which represents the *mean* of statistically
+    independent, uniformly distributed random variables, is simply the
+    Irwin-Hall distribution scaled by :math:`1/n`. For example, the frozen
+    distribution ``bates = irwinhall(10, scale=1/10)`` represents the
+    distribution of the mean of 10 uniformly distributed random variables.
+    
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] P. Hall, "The distribution of means for samples of size N drawn
+            from a population in which the variate takes values between 0 and 1,
+            all such values being equally probable",
+            Biometrika, Volume 19, Issue 3-4, December 1927, Pages 240-244,
+            :doi:`10.1093/biomet/19.3-4.240`.
+    .. [2] J. O. Irwin, "On the frequency distribution of the means of samples
+            from a population having any law of frequency with finite moments,
+            with special reference to Pearson's Type II,
+            Biometrika, Volume 19, Issue 3-4, December 1927, Pages 225-239,
+            :doi:`0.1093/biomet/19.3-4.225`.
+    .. [3] K. Buchanan, T. Adeyemi, C. Flores-Molina, S. Wheeland and D. Overturf, 
+            "Sidelobe behavior and bandwidth characteristics
+            of distributed antenna arrays,"
+            2018 United States National Committee of
+            URSI National Radio Science Meeting (USNC-URSI NRSM),
+            Boulder, CO, USA, 2018, pp. 1-2.
+            https://www.usnc-ursi-archive.org/nrsm/2018/papers/B15-9.pdf.
+    .. [4] Amos Ron, "Lecture 1: Cardinal B-splines and convolution operators", p. 1
+            https://pages.cs.wisc.edu/~deboor/887/lec1new.pdf.
+    .. [5] Trefethen, N. (2012, July). B-splines and convolution. Chebfun. 
+            Retrieved April 30, 2024, from http://www.chebfun.org/examples/approx/BSplineConv.html.
+
+    %(example)s
+    """  # noqa: E501
+
+    @replace_notes_in_docstring(rv_continuous, notes="""\
+        Raises a ``NotImplementedError`` for the Irwin-Hall distribution because
+        the generic `fit` implementation is unreliable and no custom implementation
+        is available. Consider using `scipy.stats.fit`.\n\n""")
+    def fit(self, data, *args, **kwds):
+        fit_notes = ("The generic `fit` implementation is unreliable for this "
+                     "distribution, and no custom implementation is available. "
+                     "Consider using `scipy.stats.fit`.")
+        raise NotImplementedError(fit_notes)
+
+    def _argcheck(self, n):
+        return (n > 0) & _isintegral(n) & np.isrealobj(n)
+
+    def _get_support(self, n):
+        return 0, n
+
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (1, np.inf), (True, False))]
+
+    def _munp(self, order, n):
+        # see https://link.springer.com/content/pdf/10.1007/s10959-020-01050-9.pdf
+        # page 640, with m=n, j=n+order
+        def vmunp(order, n):
+            n = np.asarray(n, dtype=np.int64)
+            return (sc.stirling2(n+order, n, exact=True)
+                    / sc.comb(n+order, n, exact=True))
+
+        # exact rationals, but we convert to float anyway
+        return np.vectorize(vmunp, otypes=[np.float64])(order, n)
+
+    @staticmethod
+    def _cardbspl(n):
+        t = np.arange(n+1)
+        return BSpline.basis_element(t)
+
+    def _pdf(self, x, n):
+        def vpdf(x, n):
+            return self._cardbspl(n)(x)
+        return np.vectorize(vpdf, otypes=[np.float64])(x, n)
+
+    def _cdf(self, x, n):
+        def vcdf(x, n):
+            return self._cardbspl(n).antiderivative()(x)
+        return np.vectorize(vcdf, otypes=[np.float64])(x, n)
+
+    def _sf(self, x, n):
+        def vsf(x, n):
+            return self._cardbspl(n).antiderivative()(n-x)
+        return np.vectorize(vsf, otypes=[np.float64])(x, n)
+
+    def _rvs(self, n, size=None, random_state=None, *args):
+        @_vectorize_rvs_over_shapes
+        def _rvs1(n, size=None, random_state=None):
+            n = np.floor(n).astype(int)
+            usize = (n,) if size is None else (n, *size)
+            return random_state.uniform(size=usize).sum(axis=0)
+        return _rvs1(n, size=size, random_state=random_state)
+
+    def _stats(self, n):
+        # mgf = ((exp(t) - 1)/t)**n
+        # m'th derivative follows from the generalized Leibniz rule
+        # Moments follow directly from the definition as the sum of n iid unif(0,1)
+        # and the summation rules for moments of a sum of iid random variables
+        # E(IH((n))) = n*E(U(0,1)) = n/2
+        # Var(IH((n))) = n*Var(U(0,1)) = n/12
+        # Skew(IH((n))) = Skew(U(0,1))/sqrt(n) = 0
+        # Kurt(IH((n))) = Kurt(U(0,1))/n = -6/(5*n) -- Fisher's excess kurtosis
+        # See e.g. https://en.wikipedia.org/wiki/Irwin%E2%80%93Hall_distribution
+
+        return n/2, n/12, 0, -6/(5*n)
+
+
+irwinhall = irwinhall_gen(name="irwinhall")
+irwinhall._support = (0.0, 'n')
+
+
+class recipinvgauss_gen(rv_continuous):
+    r"""A reciprocal inverse Gaussian continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `recipinvgauss` is:
+
+    .. math::
+
+        f(x, \mu) = \frac{1}{\sqrt{2\pi x}}
+                    \exp\left(\frac{-(1-\mu x)^2}{2\mu^2x}\right)
+
+    for :math:`x \ge 0`.
+
+    `recipinvgauss` takes ``mu`` as a shape parameter for :math:`\mu`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("mu", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, mu):
+        # recipinvgauss.pdf(x, mu) =
+        #                     1/sqrt(2*pi*x) * exp(-(1-mu*x)**2/(2*x*mu**2))
+        return np.exp(self._logpdf(x, mu))
+
+    def _logpdf(self, x, mu):
+        return _lazywhere(x > 0, (x, mu),
+                          lambda x, mu: (-(1 - mu*x)**2.0 / (2*x*mu**2.0)
+                                         - 0.5*np.log(2*np.pi*x)),
+                          fillvalue=-np.inf)
+
+    def _cdf(self, x, mu):
+        trm1 = 1.0/mu - x
+        trm2 = 1.0/mu + x
+        isqx = 1.0/np.sqrt(x)
+        return _norm_cdf(-isqx*trm1) - np.exp(2.0/mu)*_norm_cdf(-isqx*trm2)
+
+    def _sf(self, x, mu):
+        trm1 = 1.0/mu - x
+        trm2 = 1.0/mu + x
+        isqx = 1.0/np.sqrt(x)
+        return _norm_cdf(isqx*trm1) + np.exp(2.0/mu)*_norm_cdf(-isqx*trm2)
+
+    def _rvs(self, mu, size=None, random_state=None):
+        return 1.0/random_state.wald(mu, 1.0, size=size)
+
+
+recipinvgauss = recipinvgauss_gen(a=0.0, name='recipinvgauss')
+
+
+class semicircular_gen(rv_continuous):
+    r"""A semicircular continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    rdist
+
+    Notes
+    -----
+    The probability density function for `semicircular` is:
+
+    .. math::
+
+        f(x) = \frac{2}{\pi} \sqrt{1-x^2}
+
+    for :math:`-1 \le x \le 1`.
+
+    The distribution is a special case of `rdist` with ``c = 3``.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Wigner semicircle distribution",
+           https://en.wikipedia.org/wiki/Wigner_semicircle_distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _pdf(self, x):
+        return 2.0/np.pi*np.sqrt(1-x*x)
+
+    def _logpdf(self, x):
+        return np.log(2/np.pi) + 0.5*sc.log1p(-x*x)
+
+    def _cdf(self, x):
+        return 0.5+1.0/np.pi*(x*np.sqrt(1-x*x) + np.arcsin(x))
+
+    def _ppf(self, q):
+        return rdist._ppf(q, 3)
+
+    def _rvs(self, size=None, random_state=None):
+        # generate values uniformly distributed on the area under the pdf
+        # (semi-circle) by randomly generating the radius and angle
+        r = np.sqrt(random_state.uniform(size=size))
+        a = np.cos(np.pi * random_state.uniform(size=size))
+        return r * a
+
+    def _stats(self):
+        return 0, 0.25, 0, -1.0
+
+    def _entropy(self):
+        return 0.64472988584940017414
+
+
+semicircular = semicircular_gen(a=-1.0, b=1.0, name="semicircular")
+
+
+class skewcauchy_gen(rv_continuous):
+    r"""A skewed Cauchy random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    cauchy : Cauchy distribution
+
+    Notes
+    -----
+
+    The probability density function for `skewcauchy` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\pi \left(\frac{x^2}{\left(a\, \text{sign}(x) + 1
+                                                   \right)^2} + 1 \right)}
+
+    for a real number :math:`x` and skewness parameter :math:`-1 < a < 1`.
+
+    When :math:`a=0`, the distribution reduces to the usual Cauchy
+    distribution.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Skewed generalized *t* distribution", Wikipedia
+       https://en.wikipedia.org/wiki/Skewed_generalized_t_distribution#Skewed_Cauchy_distribution
+
+    %(example)s
+
+    """
+    def _argcheck(self, a):
+        return np.abs(a) < 1
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (-1.0, 1.0), (False, False))]
+
+    def _pdf(self, x, a):
+        return 1 / (np.pi * (x**2 / (a * np.sign(x) + 1)**2 + 1))
+
+    def _cdf(self, x, a):
+        return np.where(x <= 0,
+                        (1 - a) / 2 + (1 - a) / np.pi * np.arctan(x / (1 - a)),
+                        (1 - a) / 2 + (1 + a) / np.pi * np.arctan(x / (1 + a)))
+
+    def _ppf(self, x, a):
+        i = x < self._cdf(0, a)
+        return np.where(i,
+                        np.tan(np.pi / (1 - a) * (x - (1 - a) / 2)) * (1 - a),
+                        np.tan(np.pi / (1 + a) * (x - (1 - a) / 2)) * (1 + a))
+
+    def _stats(self, a, moments='mvsk'):
+        return np.nan, np.nan, np.nan, np.nan
+
+    def _fitstart(self, data):
+        # Use 0 as the initial guess of the skewness shape parameter.
+        # For the location and scale, estimate using the median and
+        # quartiles.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        p25, p50, p75 = np.percentile(data, [25, 50, 75])
+        return 0.0, p50, (p75 - p25)/2
+
+
+skewcauchy = skewcauchy_gen(name='skewcauchy')
+
+
+class skewnorm_gen(rv_continuous):
+    r"""A skew-normal random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The pdf is::
+
+        skewnorm.pdf(x, a) = 2 * norm.pdf(x) * norm.cdf(a*x)
+
+    `skewnorm` takes a real number :math:`a` as a skewness parameter
+    When ``a = 0`` the distribution is identical to a normal distribution
+    (`norm`). `rvs` implements the method of [1]_.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of ``cdf``, ``ppf`` and ``isf`` methods. [2]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] A. Azzalini and A. Capitanio (1999). Statistical applications of
+        the multivariate skew-normal distribution. J. Roy. Statist. Soc.,
+        B 61, 579-602. :arxiv:`0911.2093`
+    .. [2] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    """
+    def _argcheck(self, a):
+        return np.isfinite(a)
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (-np.inf, np.inf), (False, False))]
+
+    def _pdf(self, x, a):
+        return _lazywhere(
+            a == 0, (x, a), lambda x, a: _norm_pdf(x),
+            f2=lambda x, a: 2.*_norm_pdf(x)*_norm_cdf(a*x)
+        )
+
+    def _logpdf(self, x, a):
+        return _lazywhere(
+            a == 0, (x, a), lambda x, a: _norm_logpdf(x),
+            f2=lambda x, a: np.log(2)+_norm_logpdf(x)+_norm_logcdf(a*x),
+        )
+
+    def _cdf(self, x, a):
+        a = np.atleast_1d(a)
+        cdf = scu._skewnorm_cdf(x, 0.0, 1.0, a)
+        # for some reason, a isn't broadcasted if some of x are invalid
+        a = np.broadcast_to(a, cdf.shape)
+        # Boost is not accurate in left tail when a > 0
+        i_small_cdf = (cdf < 1e-6) & (a > 0)
+        cdf[i_small_cdf] = super()._cdf(x[i_small_cdf], a[i_small_cdf])
+        return np.clip(cdf, 0, 1)
+
+    def _ppf(self, x, a):
+        return scu._skewnorm_ppf(x, 0.0, 1.0, a)
+
+    def _sf(self, x, a):
+        # Boost's SF is implemented this way. Use whatever customizations
+        # we made in the _cdf.
+        return self._cdf(-x, -a)
+
+    def _isf(self, x, a):
+        return scu._skewnorm_isf(x, 0.0, 1.0, a)
+
+    def _rvs(self, a, size=None, random_state=None):
+        u0 = random_state.normal(size=size)
+        v = random_state.normal(size=size)
+        d = a/np.sqrt(1 + a**2)
+        u1 = d*u0 + v*np.sqrt(1 - d**2)
+        return np.where(u0 >= 0, u1, -u1)
+
+    def _stats(self, a, moments='mvsk'):
+        output = [None, None, None, None]
+        const = np.sqrt(2/np.pi) * a/np.sqrt(1 + a**2)
+
+        if 'm' in moments:
+            output[0] = const
+        if 'v' in moments:
+            output[1] = 1 - const**2
+        if 's' in moments:
+            output[2] = ((4 - np.pi)/2) * (const/np.sqrt(1 - const**2))**3
+        if 'k' in moments:
+            output[3] = (2*(np.pi - 3)) * (const**4/(1 - const**2)**2)
+
+        return output
+
+    # For odd order, the each noncentral moment of the skew-normal distribution
+    # with location 0 and scale 1 can be expressed as a polynomial in delta,
+    # where delta = a/sqrt(1 + a**2) and `a` is the skew-normal shape
+    # parameter.  The dictionary _skewnorm_odd_moments defines those
+    # polynomials for orders up to 19.  The dict is implemented as a cached
+    # property to reduce the impact of the creation of the dict on import time.
+    @cached_property
+    def _skewnorm_odd_moments(self):
+        skewnorm_odd_moments = {
+            1: Polynomial([1]),
+            3: Polynomial([3, -1]),
+            5: Polynomial([15, -10, 3]),
+            7: Polynomial([105, -105, 63, -15]),
+            9: Polynomial([945, -1260, 1134, -540, 105]),
+            11: Polynomial([10395, -17325, 20790, -14850, 5775, -945]),
+            13: Polynomial([135135, -270270, 405405, -386100, 225225, -73710,
+                            10395]),
+            15: Polynomial([2027025, -4729725, 8513505, -10135125, 7882875,
+                            -3869775, 1091475, -135135]),
+            17: Polynomial([34459425, -91891800, 192972780, -275675400,
+                            268017750, -175429800, 74220300, -18378360,
+                            2027025]),
+            19: Polynomial([654729075, -1964187225, 4714049340, -7856748900,
+                            9166207050, -7499623950, 4230557100, -1571349780,
+                            346621275, -34459425]),
+        }
+        return skewnorm_odd_moments
+
+    def _munp(self, order, a):
+        if order % 2:
+            if order > 19:
+                raise NotImplementedError("skewnorm noncentral moments not "
+                                          "implemented for odd orders greater "
+                                          "than 19.")
+            # Use the precomputed polynomials that were derived from the
+            # moment generating function.
+            delta = a/np.sqrt(1 + a**2)
+            return (delta * self._skewnorm_odd_moments[order](delta**2)
+                    * _SQRT_2_OVER_PI)
+        else:
+            # For even order, the moment is just (order-1)!!, where !! is the
+            # notation for the double factorial; for an odd integer m, m!! is
+            # m*(m-2)*...*3*1.
+            # We could use special.factorial2, but we know the argument is odd,
+            # so avoid the overhead of that function and compute the result
+            # directly here.
+            return sc.gamma((order + 1)/2) * 2**(order/2) / _SQRT_PI
+
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        If ``method='mm'``, parameters fixed by the user are respected, and the
+        remaining parameters are used to match distribution and sample moments
+        where possible. For example, if the user fixes the location with
+        ``floc``, the parameters will only match the distribution skewness and
+        variance to the sample skewness and variance; no attempt will be made
+        to match the means or minimize a norm of the errors.
+        Note that the maximum possible skewness magnitude of a
+        `scipy.stats.skewnorm` distribution is approximately 0.9952717; if the
+        magnitude of the data's sample skewness exceeds this, the returned
+        shape parameter ``a`` will be infinite.
+        \n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.pop("superfit", False):
+            return super().fit(data, *args, **kwds)
+        if isinstance(data, CensoredData):
+            if data.num_censored() == 0:
+                data = data._uncensor()
+            else:
+                return super().fit(data, *args, **kwds)
+
+        # this extracts fixed shape, location, and scale however they
+        # are specified, and also leaves them in `kwds`
+        data, fa, floc, fscale = _check_fit_input_parameters(self, data,
+                                                             args, kwds)
+        method = kwds.get("method", "mle").lower()
+
+        # See https://en.wikipedia.org/wiki/Skew_normal_distribution for
+        # moment formulas.
+        def skew_d(d):  # skewness in terms of delta
+            return (4-np.pi)/2 * ((d * np.sqrt(2 / np.pi))**3
+                                  / (1 - 2*d**2 / np.pi)**(3/2))
+
+        def d_skew(skew):  # delta in terms of skewness
+            s_23 = np.abs(skew)**(2/3)
+            return np.sign(skew) * np.sqrt(
+                np.pi/2 * s_23 / (s_23 + ((4 - np.pi)/2)**(2/3))
+            )
+
+        # If method is method of moments, we don't need the user's guesses.
+        # Otherwise, extract the guesses from args and kwds.
+        if method == "mm":
+            a, loc, scale = None, None, None
+        else:
+            a = args[0] if len(args) else None
+            loc = kwds.pop('loc', None)
+            scale = kwds.pop('scale', None)
+
+        if fa is None and a is None:  # not fixed and no guess: use MoM
+            # Solve for a that matches sample distribution skewness to sample
+            # skewness.
+            s = stats.skew(data)
+            if method == 'mle':
+                # For MLE initial conditions, clip skewness to a large but
+                # reasonable value in case the data skewness is out-of-range.
+                s = np.clip(s, -0.99, 0.99)
+            else:
+                s_max = skew_d(1)
+                s = np.clip(s, -s_max, s_max)
+            d = d_skew(s)
+            with np.errstate(divide='ignore'):
+                a = np.sqrt(np.divide(d**2, (1-d**2)))*np.sign(s)
+        else:
+            a = fa if fa is not None else a
+            d = a / np.sqrt(1 + a**2)
+
+        if fscale is None and scale is None:
+            v = np.var(data)
+            scale = np.sqrt(v / (1 - 2*d**2/np.pi))
+        elif fscale is not None:
+            scale = fscale
+
+        if floc is None and loc is None:
+            m = np.mean(data)
+            loc = m - scale*d*np.sqrt(2/np.pi)
+        elif floc is not None:
+            loc = floc
+
+        if method == 'mm':
+            return a, loc, scale
+        else:
+            # At this point, parameter "guesses" may equal the fixed parameters
+            # in kwds. No harm in passing them as guesses, too.
+            return super().fit(data, a, loc=loc, scale=scale, **kwds)
+
+
+skewnorm = skewnorm_gen(name='skewnorm')
+
+
+class trapezoid_gen(rv_continuous):
+    r"""A trapezoidal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The trapezoidal distribution can be represented with an up-sloping line
+    from ``loc`` to ``(loc + c*scale)``, then constant to ``(loc + d*scale)``
+    and then downsloping from ``(loc + d*scale)`` to ``(loc+scale)``.  This
+    defines the trapezoid base from ``loc`` to ``(loc+scale)`` and the flat
+    top from ``c`` to ``d`` proportional to the position along the base
+    with ``0 <= c <= d <= 1``.  When ``c=d``, this is equivalent to `triang`
+    with the same values for `loc`, `scale` and `c`.
+    The method of [1]_ is used for computing moments.
+
+    `trapezoid` takes :math:`c` and :math:`d` as shape parameters.
+
+    %(after_notes)s
+
+    The standard form is in the range [0, 1] with c the mode.
+    The location parameter shifts the start to `loc`.
+    The scale parameter changes the width from 1 to `scale`.
+
+    %(example)s
+
+    References
+    ----------
+    .. [1] Kacker, R.N. and Lawrence, J.F. (2007). Trapezoidal and triangular
+       distributions for Type B evaluation of standard uncertainty.
+       Metrologia 44, 117-127. :doi:`10.1088/0026-1394/44/2/003`
+
+
+    """
+    def _argcheck(self, c, d):
+        return (c >= 0) & (c <= 1) & (d >= 0) & (d <= 1) & (d >= c)
+
+    def _shape_info(self):
+        ic = _ShapeInfo("c", False, (0, 1.0), (True, True))
+        id = _ShapeInfo("d", False, (0, 1.0), (True, True))
+        return [ic, id]
+
+    def _pdf(self, x, c, d):
+        u = 2 / (d-c+1)
+
+        return _lazyselect([x < c,
+                            (c <= x) & (x <= d),
+                            x > d],
+                           [lambda x, c, d, u: u * x / c,
+                            lambda x, c, d, u: u,
+                            lambda x, c, d, u: u * (1-x) / (1-d)],
+                           (x, c, d, u))
+
+    def _cdf(self, x, c, d):
+        return _lazyselect([x < c,
+                            (c <= x) & (x <= d),
+                            x > d],
+                           [lambda x, c, d: x**2 / c / (d-c+1),
+                            lambda x, c, d: (c + 2 * (x-c)) / (d-c+1),
+                            lambda x, c, d: 1-((1-x) ** 2
+                                               / (d-c+1) / (1-d))],
+                           (x, c, d))
+
+    def _ppf(self, q, c, d):
+        qc, qd = self._cdf(c, c, d), self._cdf(d, c, d)
+        condlist = [q < qc, q <= qd, q > qd]
+        choicelist = [np.sqrt(q * c * (1 + d - c)),
+                      0.5 * q * (1 + d - c) + 0.5 * c,
+                      1 - np.sqrt((1 - q) * (d - c + 1) * (1 - d))]
+        return np.select(condlist, choicelist)
+
+    def _munp(self, n, c, d):
+        # Using the parameterization from Kacker, 2007, with
+        # a=bottom left, c=top left, d=top right, b=bottom right, then
+        #     E[X^n] = h/(n+1)/(n+2) [(b^{n+2}-d^{n+2})/(b-d)
+        #                             - ((c^{n+2} - a^{n+2})/(c-a)]
+        # with h = 2/((b-a) - (d-c)). The corresponding parameterization
+        # in scipy, has a'=loc, c'=loc+c*scale, d'=loc+d*scale, b'=loc+scale,
+        # which for standard form reduces to a'=0, b'=1, c'=c, d'=d.
+        # Substituting into E[X^n] gives the bd' term as (1 - d^{n+2})/(1 - d)
+        # and the ac' term as c^{n-1} for the standard form. The bd' term has
+        # numerical difficulties near d=1, so replace (1 - d^{n+2})/(1-d)
+        # with expm1((n+2)*log(d))/(d-1).
+        # Testing with n=18 for c=(1e-30,1-eps) shows that this is stable.
+        # We still require an explicit test for d=1 to prevent divide by zero,
+        # and now a test for d=0 to prevent log(0).
+        ab_term = c**(n+1)
+        dc_term = _lazyselect(
+            [d == 0.0, (0.0 < d) & (d < 1.0), d == 1.0],
+            [lambda d: 1.0,
+             lambda d: np.expm1((n+2) * np.log(d)) / (d-1.0),
+             lambda d: n+2],
+            [d])
+        val = 2.0 / (1.0+d-c) * (dc_term - ab_term) / ((n+1) * (n+2))
+        return val
+
+    def _entropy(self, c, d):
+        # Using the parameterization from Wikipedia (van Dorp, 2003)
+        # with a=bottom left, c=top left, d=top right, b=bottom right
+        # gives a'=loc, b'=loc+c*scale, c'=loc+d*scale, d'=loc+scale,
+        # which for loc=0, scale=1 is a'=0, b'=c, c'=d, d'=1.
+        # Substituting into the entropy formula from Wikipedia gives
+        # the following result.
+        return 0.5 * (1.0-d+c) / (1.0+d-c) + np.log(0.5 * (1.0+d-c))
+
+
+# deprecation of trapz, see #20486
+deprmsg = ("`trapz` is deprecated in favour of `trapezoid` "
+           "and will be removed in SciPy 1.16.0.")
+
+
+class trapz_gen(trapezoid_gen):
+    # override __call__ protocol from rv_generic to also
+    # deprecate instantiation of frozen distributions
+    """
+
+    .. deprecated:: 1.14.0
+        `trapz` is deprecated and will be removed in SciPy 1.16.
+        Plese use `trapezoid` instead!
+    """
+    def __call__(self, *args, **kwds):
+        warnings.warn(deprmsg, DeprecationWarning, stacklevel=2)
+        return self.freeze(*args, **kwds)
+
+
+trapezoid = trapezoid_gen(a=0.0, b=1.0, name="trapezoid")
+trapz = trapz_gen(a=0.0, b=1.0, name="trapz")
+
+# since the deprecated class gets intantiated upon import (and we only want to
+# warn upon use), add the deprecation to each class method
+_method_names = [
+    "cdf", "entropy", "expect", "fit", "interval", "isf", "logcdf", "logpdf",
+    "logsf", "mean", "median", "moment", "pdf", "ppf", "rvs", "sf", "stats",
+    "std", "var"
+]
+
+
+class _DeprecationWrapper:
+    def __init__(self, method):
+        self.msg = (f"`trapz.{method}` is deprecated in favour of trapezoid.{method}. "
+                     "Please replace all uses of the distribution class "
+                     "`trapz` with `trapezoid`. `trapz` will be removed in SciPy 1.16.")
+        self.method = getattr(trapezoid, method)
+
+    def __call__(self, *args, **kwargs):
+        warnings.warn(self.msg, DeprecationWarning, stacklevel=2)
+        return self.method(*args, **kwargs)
+
+
+for m in _method_names:
+    setattr(trapz, m, _DeprecationWrapper(m))
+
+
+class triang_gen(rv_continuous):
+    r"""A triangular continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The triangular distribution can be represented with an up-sloping line from
+    ``loc`` to ``(loc + c*scale)`` and then downsloping for ``(loc + c*scale)``
+    to ``(loc + scale)``.
+
+    `triang` takes ``c`` as a shape parameter for :math:`0 \le c \le 1`.
+
+    %(after_notes)s
+
+    The standard form is in the range [0, 1] with c the mode.
+    The location parameter shifts the start to `loc`.
+    The scale parameter changes the width from 1 to `scale`.
+
+    %(example)s
+
+    """
+    def _rvs(self, c, size=None, random_state=None):
+        return random_state.triangular(0, c, 1, size)
+
+    def _argcheck(self, c):
+        return (c >= 0) & (c <= 1)
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, 1.0), (True, True))]
+
+    def _pdf(self, x, c):
+        # 0: edge case where c=0
+        # 1: generalised case for x < c, don't use x <= c, as it doesn't cope
+        #    with c = 0.
+        # 2: generalised case for x >= c, but doesn't cope with c = 1
+        # 3: edge case where c=1
+        r = _lazyselect([c == 0,
+                         x < c,
+                         (x >= c) & (c != 1),
+                         c == 1],
+                        [lambda x, c: 2 - 2 * x,
+                         lambda x, c: 2 * x / c,
+                         lambda x, c: 2 * (1 - x) / (1 - c),
+                         lambda x, c: 2 * x],
+                        (x, c))
+        return r
+
+    def _cdf(self, x, c):
+        r = _lazyselect([c == 0,
+                         x < c,
+                         (x >= c) & (c != 1),
+                         c == 1],
+                        [lambda x, c: 2*x - x*x,
+                         lambda x, c: x * x / c,
+                         lambda x, c: (x*x - 2*x + c) / (c-1),
+                         lambda x, c: x * x],
+                        (x, c))
+        return r
+
+    def _ppf(self, q, c):
+        return np.where(q < c, np.sqrt(c * q), 1-np.sqrt((1-c) * (1-q)))
+
+    def _stats(self, c):
+        return ((c+1.0)/3.0,
+                (1.0-c+c*c)/18,
+                np.sqrt(2)*(2*c-1)*(c+1)*(c-2) / (5*np.power((1.0-c+c*c), 1.5)),
+                -3.0/5.0)
+
+    def _entropy(self, c):
+        return 0.5-np.log(2)
+
+
+triang = triang_gen(a=0.0, b=1.0, name="triang")
+
+
+class truncexpon_gen(rv_continuous):
+    r"""A truncated exponential continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `truncexpon` is:
+
+    .. math::
+
+        f(x, b) = \frac{\exp(-x)}{1 - \exp(-b)}
+
+    for :math:`0 <= x <= b`.
+
+    `truncexpon` takes ``b`` as a shape parameter for :math:`b`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _get_support(self, b):
+        return self.a, b
+
+    def _pdf(self, x, b):
+        # truncexpon.pdf(x, b) = exp(-x) / (1-exp(-b))
+        return np.exp(-x)/(-sc.expm1(-b))
+
+    def _logpdf(self, x, b):
+        return -x - np.log(-sc.expm1(-b))
+
+    def _cdf(self, x, b):
+        return sc.expm1(-x)/sc.expm1(-b)
+
+    def _ppf(self, q, b):
+        return -sc.log1p(q*sc.expm1(-b))
+
+    def _sf(self, x, b):
+        return (np.exp(-b) - np.exp(-x))/sc.expm1(-b)
+
+    def _isf(self, q, b):
+        return -np.log(np.exp(-b) - q * sc.expm1(-b))
+
+    def _munp(self, n, b):
+        # wrong answer with formula, same as in continuous.pdf
+        # return sc.gamman+1)-sc.gammainc1+n, b)
+        if n == 1:
+            return (1-(b+1)*np.exp(-b))/(-sc.expm1(-b))
+        elif n == 2:
+            return 2*(1-0.5*(b*b+2*b+2)*np.exp(-b))/(-sc.expm1(-b))
+        else:
+            # return generic for higher moments
+            return super()._munp(n, b)
+
+    def _entropy(self, b):
+        eB = np.exp(b)
+        return np.log(eB-1)+(1+eB*(b-1.0))/(1.0-eB)
+
+
+truncexpon = truncexpon_gen(a=0.0, name='truncexpon')
+truncexpon._support = (0.0, 'b')
+
+
+# logsumexp trick for log(p + q) with only log(p) and log(q)
+def _log_sum(log_p, log_q):
+    return sc.logsumexp([log_p, log_q], axis=0)
+
+
+# same as above, but using -exp(x) = exp(x + πi)
+def _log_diff(log_p, log_q):
+    return sc.logsumexp([log_p, log_q+np.pi*1j], axis=0)
+
+
+def _log_gauss_mass(a, b):
+    """Log of Gaussian probability mass within an interval"""
+    a, b = np.broadcast_arrays(a, b)
+
+    # Calculations in right tail are inaccurate, so we'll exploit the
+    # symmetry and work only in the left tail
+    case_left = b <= 0
+    case_right = a > 0
+    case_central = ~(case_left | case_right)
+
+    def mass_case_left(a, b):
+        return _log_diff(_norm_logcdf(b), _norm_logcdf(a))
+
+    def mass_case_right(a, b):
+        return mass_case_left(-b, -a)
+
+    def mass_case_central(a, b):
+        # Previously, this was implemented as:
+        # left_mass = mass_case_left(a, 0)
+        # right_mass = mass_case_right(0, b)
+        # return _log_sum(left_mass, right_mass)
+        # Catastrophic cancellation occurs as np.exp(log_mass) approaches 1.
+        # Correct for this with an alternative formulation.
+        # We're not concerned with underflow here: if only one term
+        # underflows, it was insignificant; if both terms underflow,
+        # the result can't accurately be represented in logspace anyway
+        # because sc.log1p(x) ~ x for small x.
+        return sc.log1p(-_norm_cdf(a) - _norm_cdf(-b))
+
+    # _lazyselect not working; don't care to debug it
+    out = np.full_like(a, fill_value=np.nan, dtype=np.complex128)
+    if a[case_left].size:
+        out[case_left] = mass_case_left(a[case_left], b[case_left])
+    if a[case_right].size:
+        out[case_right] = mass_case_right(a[case_right], b[case_right])
+    if a[case_central].size:
+        out[case_central] = mass_case_central(a[case_central], b[case_central])
+    return np.real(out)  # discard ~0j
+
+
+class truncnorm_gen(rv_continuous):
+    r"""A truncated normal continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    This distribution is the normal distribution centered on ``loc`` (default
+    0), with standard deviation ``scale`` (default 1), and truncated at ``a``
+    and ``b`` *standard deviations* from ``loc``. For arbitrary ``loc`` and
+    ``scale``, ``a`` and ``b`` are *not* the abscissae at which the shifted
+    and scaled distribution is truncated.
+
+    .. note::
+        If ``a_trunc`` and ``b_trunc`` are the abscissae at which we wish
+        to truncate the distribution (as opposed to the number of standard
+        deviations from ``loc``), then we can calculate the distribution
+        parameters ``a`` and ``b`` as follows::
+
+            a, b = (a_trunc - loc) / scale, (b_trunc - loc) / scale
+
+        This is a common point of confusion. For additional clarification,
+        please see the example below.
+
+    %(example)s
+
+    In the examples above, ``loc=0`` and ``scale=1``, so the plot is truncated
+    at ``a`` on the left and ``b`` on the right. However, suppose we were to
+    produce the same histogram with ``loc = 1`` and ``scale=0.5``.
+
+    >>> loc, scale = 1, 0.5
+    >>> rv = truncnorm(a, b, loc=loc, scale=scale)
+    >>> x = np.linspace(truncnorm.ppf(0.01, a, b),
+    ...                 truncnorm.ppf(0.99, a, b), 100)
+    >>> r = rv.rvs(size=1000)
+
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+    >>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2)
+    >>> ax.set_xlim(a, b)
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    Note that the distribution is no longer appears to be truncated at
+    abscissae ``a`` and ``b``. That is because the *standard* normal
+    distribution is first truncated at ``a`` and ``b``, *then* the resulting
+    distribution is scaled by ``scale`` and shifted by ``loc``. If we instead
+    want the shifted and scaled distribution to be truncated at ``a`` and
+    ``b``, we need to transform these values before passing them as the
+    distribution parameters.
+
+    >>> a_transformed, b_transformed = (a - loc) / scale, (b - loc) / scale
+    >>> rv = truncnorm(a_transformed, b_transformed, loc=loc, scale=scale)
+    >>> x = np.linspace(truncnorm.ppf(0.01, a, b),
+    ...                 truncnorm.ppf(0.99, a, b), 100)
+    >>> r = rv.rvs(size=10000)
+
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+    >>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2)
+    >>> ax.set_xlim(a-0.1, b+0.1)
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+    """
+
+    def _argcheck(self, a, b):
+        return a < b
+
+    def _shape_info(self):
+        ia = _ShapeInfo("a", False, (-np.inf, np.inf), (True, False))
+        ib = _ShapeInfo("b", False, (-np.inf, np.inf), (False, True))
+        return [ia, ib]
+
+    def _fitstart(self, data):
+        # Reasonable, since support is [a, b]
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        return super()._fitstart(data, args=(np.min(data), np.max(data)))
+
+    def _get_support(self, a, b):
+        return a, b
+
+    def _pdf(self, x, a, b):
+        return np.exp(self._logpdf(x, a, b))
+
+    def _logpdf(self, x, a, b):
+        return _norm_logpdf(x) - _log_gauss_mass(a, b)
+
+    def _cdf(self, x, a, b):
+        return np.exp(self._logcdf(x, a, b))
+
+    def _logcdf(self, x, a, b):
+        x, a, b = np.broadcast_arrays(x, a, b)
+        logcdf = np.asarray(_log_gauss_mass(a, x) - _log_gauss_mass(a, b))
+        i = logcdf > -0.1  # avoid catastrophic cancellation
+        if np.any(i):
+            logcdf[i] = np.log1p(-np.exp(self._logsf(x[i], a[i], b[i])))
+        return logcdf
+
+    def _sf(self, x, a, b):
+        return np.exp(self._logsf(x, a, b))
+
+    def _logsf(self, x, a, b):
+        x, a, b = np.broadcast_arrays(x, a, b)
+        logsf = np.asarray(_log_gauss_mass(x, b) - _log_gauss_mass(a, b))
+        i = logsf > -0.1  # avoid catastrophic cancellation
+        if np.any(i):
+            logsf[i] = np.log1p(-np.exp(self._logcdf(x[i], a[i], b[i])))
+        return logsf
+
+    def _entropy(self, a, b):
+        A = _norm_cdf(a)
+        B = _norm_cdf(b)
+        Z = B - A
+        C = np.log(np.sqrt(2 * np.pi * np.e) * Z)
+        D = (a * _norm_pdf(a) - b * _norm_pdf(b)) / (2 * Z)
+        h = C + D
+        return h
+
+    def _ppf(self, q, a, b):
+        q, a, b = np.broadcast_arrays(q, a, b)
+
+        case_left = a < 0
+        case_right = ~case_left
+
+        def ppf_left(q, a, b):
+            log_Phi_x = _log_sum(_norm_logcdf(a),
+                                 np.log(q) + _log_gauss_mass(a, b))
+            return sc.ndtri_exp(log_Phi_x)
+
+        def ppf_right(q, a, b):
+            log_Phi_x = _log_sum(_norm_logcdf(-b),
+                                 np.log1p(-q) + _log_gauss_mass(a, b))
+            return -sc.ndtri_exp(log_Phi_x)
+
+        out = np.empty_like(q)
+
+        q_left = q[case_left]
+        q_right = q[case_right]
+
+        if q_left.size:
+            out[case_left] = ppf_left(q_left, a[case_left], b[case_left])
+        if q_right.size:
+            out[case_right] = ppf_right(q_right, a[case_right], b[case_right])
+
+        return out
+
+    def _isf(self, q, a, b):
+        # Mostly copy-paste of _ppf, but I think this is simpler than combining
+        q, a, b = np.broadcast_arrays(q, a, b)
+
+        case_left = b < 0
+        case_right = ~case_left
+
+        def isf_left(q, a, b):
+            log_Phi_x = _log_diff(_norm_logcdf(b),
+                                  np.log(q) + _log_gauss_mass(a, b))
+            return sc.ndtri_exp(np.real(log_Phi_x))
+
+        def isf_right(q, a, b):
+            log_Phi_x = _log_diff(_norm_logcdf(-a),
+                                  np.log1p(-q) + _log_gauss_mass(a, b))
+            return -sc.ndtri_exp(np.real(log_Phi_x))
+
+        out = np.empty_like(q)
+
+        q_left = q[case_left]
+        q_right = q[case_right]
+
+        if q_left.size:
+            out[case_left] = isf_left(q_left, a[case_left], b[case_left])
+        if q_right.size:
+            out[case_right] = isf_right(q_right, a[case_right], b[case_right])
+
+        return out
+
+    def _munp(self, n, a, b):
+        def n_th_moment(n, a, b):
+            """
+            Returns n-th moment. Defined only if n >= 0.
+            Function cannot broadcast due to the loop over n
+            """
+            pA, pB = self._pdf(np.asarray([a, b]), a, b)
+            probs = [pA, -pB]
+            moments = [0, 1]
+            for k in range(1, n+1):
+                # a or b might be infinite, and the corresponding pdf value
+                # is 0 in that case, but nan is returned for the
+                # multiplication.  However, as b->infinity,  pdf(b)*b**k -> 0.
+                # So it is safe to use _lazywhere to avoid the nan.
+                vals = _lazywhere(probs, [probs, [a, b]],
+                                  lambda x, y: x * y**(k-1), fillvalue=0)
+                mk = np.sum(vals) + (k-1) * moments[-2]
+                moments.append(mk)
+            return moments[-1]
+
+        return _lazywhere((n >= 0) & (a == a) & (b == b), (n, a, b),
+                          np.vectorize(n_th_moment, otypes=[np.float64]),
+                          np.nan)
+
+    def _stats(self, a, b, moments='mv'):
+        pA, pB = self.pdf(np.array([a, b]), a, b)
+
+        def _truncnorm_stats_scalar(a, b, pA, pB, moments):
+            m1 = pA - pB
+            mu = m1
+            # use _lazywhere to avoid nan (See detailed comment in _munp)
+            probs = [pA, -pB]
+            vals = _lazywhere(probs, [probs, [a, b]], lambda x, y: x*y,
+                              fillvalue=0)
+            m2 = 1 + np.sum(vals)
+            vals = _lazywhere(probs, [probs, [a-mu, b-mu]], lambda x, y: x*y,
+                              fillvalue=0)
+            # mu2 = m2 - mu**2, but not as numerically stable as:
+            # mu2 = (a-mu)*pA - (b-mu)*pB + 1
+            mu2 = 1 + np.sum(vals)
+            vals = _lazywhere(probs, [probs, [a, b]], lambda x, y: x*y**2,
+                              fillvalue=0)
+            m3 = 2*m1 + np.sum(vals)
+            vals = _lazywhere(probs, [probs, [a, b]], lambda x, y: x*y**3,
+                              fillvalue=0)
+            m4 = 3*m2 + np.sum(vals)
+
+            mu3 = m3 + m1 * (-3*m2 + 2*m1**2)
+            g1 = mu3 / np.power(mu2, 1.5)
+            mu4 = m4 + m1*(-4*m3 + 3*m1*(2*m2 - m1**2))
+            g2 = mu4 / mu2**2 - 3
+            return mu, mu2, g1, g2
+
+        _truncnorm_stats = np.vectorize(_truncnorm_stats_scalar,
+                                        excluded=('moments',))
+        return _truncnorm_stats(a, b, pA, pB, moments)
+
+
+truncnorm = truncnorm_gen(name='truncnorm', momtype=1)
+truncnorm._support = ('a', 'b')
+
+
+class truncpareto_gen(rv_continuous):
+    r"""An upper truncated Pareto continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    pareto : Pareto distribution
+
+    Notes
+    -----
+    The probability density function for `truncpareto` is:
+
+    .. math::
+
+        f(x, b, c) = \frac{b}{1 - c^{-b}} \frac{1}{x^{b+1}}
+
+    for :math:`b > 0`, :math:`c > 1` and :math:`1 \le x \le c`.
+
+    `truncpareto` takes `b` and `c` as shape parameters for :math:`b` and
+    :math:`c`.
+
+    Notice that the upper truncation value :math:`c` is defined in
+    standardized form so that random values of an unscaled, unshifted variable
+    are within the range ``[1, c]``.
+    If ``u_r`` is the upper bound to a scaled and/or shifted variable,
+    then ``c = (u_r - loc) / scale``. In other words, the support of the
+    distribution becomes ``(scale + loc) <= x <= (c*scale + loc)`` when
+    `scale` and/or `loc` are provided.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Burroughs, S. M., and Tebbens S. F.
+        "Upper-truncated power laws in natural systems."
+        Pure and Applied Geophysics 158.4 (2001): 741-757.
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        ib = _ShapeInfo("b", False, (0.0, np.inf), (False, False))
+        ic = _ShapeInfo("c", False, (1.0, np.inf), (False, False))
+        return [ib, ic]
+
+    def _argcheck(self, b, c):
+        return (b > 0.) & (c > 1.)
+
+    def _get_support(self, b, c):
+        return self.a, c
+
+    def _pdf(self, x, b, c):
+        return b * x**-(b+1) / (1 - 1/c**b)
+
+    def _logpdf(self, x, b, c):
+        return np.log(b) - np.log(-np.expm1(-b*np.log(c))) - (b+1)*np.log(x)
+
+    def _cdf(self, x, b, c):
+        return (1 - x**-b) / (1 - 1/c**b)
+
+    def _logcdf(self, x, b, c):
+        return np.log1p(-x**-b) - np.log1p(-1/c**b)
+
+    def _ppf(self, q, b, c):
+        return pow(1 - (1 - 1/c**b)*q, -1/b)
+
+    def _sf(self, x, b, c):
+        return (x**-b - 1/c**b) / (1 - 1/c**b)
+
+    def _logsf(self, x, b, c):
+        return np.log(x**-b - 1/c**b) - np.log1p(-1/c**b)
+
+    def _isf(self, q, b, c):
+        return pow(1/c**b + (1 - 1/c**b)*q, -1/b)
+
+    def _entropy(self, b, c):
+        return -(np.log(b/(1 - 1/c**b))
+                 + (b+1)*(np.log(c)/(c**b - 1) - 1/b))
+
+    def _munp(self, n, b, c):
+        if (n == b).all():
+            return b*np.log(c) / (1 - 1/c**b)
+        else:
+            return b / (b-n) * (c**b - c**n) / (c**b - 1)
+
+    def _fitstart(self, data):
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        b, loc, scale = pareto.fit(data)
+        c = (max(data) - loc)/scale
+        return b, c, loc, scale
+
+    @_call_super_mom
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        if kwds.pop("superfit", False):
+            return super().fit(data, *args, **kwds)
+
+        def log_mean(x):
+            return np.mean(np.log(x))
+
+        def harm_mean(x):
+            return 1/np.mean(1/x)
+
+        def get_b(c, loc, scale):
+            u = (data-loc)/scale
+            harm_m = harm_mean(u)
+            log_m = log_mean(u)
+            quot = (harm_m-1)/log_m
+            return (1 - (quot-1) / (quot - (1 - 1/c)*harm_m/np.log(c)))/log_m
+
+        def get_c(loc, scale):
+            return (mx - loc)/scale
+
+        def get_loc(fc, fscale):
+            if fscale:  # (fscale and fc) or (fscale and not fc)
+                loc = mn - fscale
+                return loc
+            if fc:
+                loc = (fc*mn - mx)/(fc - 1)
+                return loc
+
+        def get_scale(loc):
+            return mn - loc
+
+        # Functions used for optimisation; partial derivatives of
+        # the Lagrangian, set to equal 0.
+
+        def dL_dLoc(loc, b_=None):
+            # Partial derivative wrt location.
+            # Optimised upon when no parameters, or only b, are fixed.
+            scale = get_scale(loc)
+            c = get_c(loc, scale)
+            b = get_b(c, loc, scale) if b_ is None else b_
+            harm_m = harm_mean((data - loc)/scale)
+            return 1 - (1 + (c - 1)/(c**(b+1) - c)) * (1 - 1/(b+1)) * harm_m
+
+        def dL_dB(b, logc, logm):
+            # Partial derivative wrt b.
+            # Optimised upon whenever at least one parameter but b is fixed,
+            # and b is free.
+            return b - np.log1p(b*logc / (1 - b*logm)) / logc
+
+        def fallback(data, *args, **kwargs):
+            # Should any issue arise, default to the general fit method.
+            return super(truncpareto_gen, self).fit(data, *args, **kwargs)
+
+        parameters = _check_fit_input_parameters(self, data, args, kwds)
+        data, fb, fc, floc, fscale = parameters
+        mn, mx = data.min(), data.max()
+        mn_inf = np.nextafter(mn, -np.inf)
+
+        if (fb is not None
+                and fc is not None
+                and floc is not None
+                and fscale is not None):
+            raise ValueError("All parameters fixed."
+                             "There is nothing to optimize.")
+        elif fc is None and floc is None and fscale is None:
+            if fb is None:
+                def cond_b(loc):
+                    # b is positive only if this function is positive
+                    scale = get_scale(loc)
+                    c = get_c(loc, scale)
+                    harm_m = harm_mean((data - loc)/scale)
+                    return (1 + 1/(c-1)) * np.log(c) / harm_m - 1
+
+                # This gives an upper bound on loc allowing for a positive b.
+                # Iteratively look for a bracket for root_scalar.
+                mn_inf = np.nextafter(mn, -np.inf)
+                rbrack = mn_inf
+                i = 0
+                lbrack = rbrack - 1
+                while ((lbrack > -np.inf)
+                       and (cond_b(lbrack)*cond_b(rbrack) >= 0)):
+                    i += 1
+                    lbrack = rbrack - np.power(2., i)
+                if not lbrack > -np.inf:
+                    return fallback(data, *args, **kwds)
+                res = root_scalar(cond_b, bracket=(lbrack, rbrack))
+                if not res.converged:
+                    return fallback(data, *args, **kwds)
+
+                # Determine the MLE for loc.
+                # Iteratively look for a bracket for root_scalar.
+                rbrack = res.root - 1e-3  # grad_loc is numerically ill-behaved
+                lbrack = rbrack - 1
+                i = 0
+                while ((lbrack > -np.inf)
+                       and (dL_dLoc(lbrack)*dL_dLoc(rbrack) >= 0)):
+                    i += 1
+                    lbrack = rbrack - np.power(2., i)
+                if not lbrack > -np.inf:
+                    return fallback(data, *args, **kwds)
+                res = root_scalar(dL_dLoc, bracket=(lbrack, rbrack))
+                if not res.converged:
+                    return fallback(data, *args, **kwds)
+                loc = res.root
+                scale = get_scale(loc)
+                c = get_c(loc, scale)
+                b = get_b(c, loc, scale)
+
+                std_data = (data - loc)/scale
+                # The expression of b relies on b being bounded above.
+                up_bound_b = min(1/log_mean(std_data),
+                                 1/(harm_mean(std_data)-1))
+                if not (b < up_bound_b):
+                    return fallback(data, *args, **kwds)
+            else:
+                # We know b is positive (or a FitError will be triggered)
+                # so we let loc get close to min(data).
+                rbrack = mn_inf
+                lbrack = mn_inf - 1
+                i = 0
+                # Iteratively look for a bracket for root_scalar.
+                while (lbrack > -np.inf
+                       and (dL_dLoc(lbrack, fb)
+                            * dL_dLoc(rbrack, fb) >= 0)):
+                    i += 1
+                    lbrack = rbrack - 2**i
+                if not lbrack > -np.inf:
+                    return fallback(data, *args, **kwds)
+                res = root_scalar(dL_dLoc, (fb,),
+                                  bracket=(lbrack, rbrack))
+                if not res.converged:
+                    return fallback(data, *args, **kwds)
+                loc = res.root
+                scale = get_scale(loc)
+                c = get_c(loc, scale)
+                b = fb
+        else:
+            # At least one of the parameters determining the support is fixed;
+            # the others then have analytical expressions from the constraints.
+            # The completely determined case (fixed c, loc and scale)
+            # has to be checked for not overflowing the support.
+            # If not fixed, b has to be determined numerically.
+            loc = floc if floc is not None else get_loc(fc, fscale)
+            scale = fscale or get_scale(loc)
+            c = fc or get_c(loc, scale)
+
+            # Unscaled, translated values should be positive when the location
+            # is fixed. If it is not the case, we end up with negative `scale`
+            # and `c`, which would trigger a FitError before exiting the
+            # method.
+            if floc is not None and data.min() - floc < 0:
+                raise FitDataError("truncpareto", lower=1, upper=c)
+
+            # Standardised values should be within the distribution support
+            # when all parameters controlling it are fixed. If it not the case,
+            # `fc` is overridden by `c` determined from `floc` and `fscale` when
+            # raising the exception.
+            if fc and (floc is not None) and fscale:
+                if data.max() > fc*fscale + floc:
+                    raise FitDataError("truncpareto", lower=1,
+                                       upper=get_c(loc, scale))
+
+            # The other constraints should be automatically satisfied
+            # from the analytical expressions of the parameters.
+            # If fc or fscale are respectively less than one or less than 0,
+            # a FitError is triggered before exiting the method.
+
+            if fb is None:
+                std_data = (data - loc)/scale
+                logm = log_mean(std_data)
+                logc = np.log(c)
+                # Condition for a positive root to exist.
+                if not (2*logm < logc):
+                    return fallback(data, *args, **kwds)
+
+                lbrack = 1/logm + 1/(logm - logc)
+                rbrack = np.nextafter(1/logm, 0)
+                try:
+                    res = root_scalar(dL_dB, (logc, logm),
+                                      bracket=(lbrack, rbrack))
+                    # we should then never get there
+                    if not res.converged:
+                        return fallback(data, *args, **kwds)
+                    b = res.root
+                except ValueError:
+                    b = rbrack
+            else:
+                b = fb
+
+        # The distribution requires that `scale+loc <= data <= c*scale+loc`.
+        # To avoid numerical issues, some tuning may be necessary.
+        # We adjust `scale` to satisfy the lower bound, and we adjust
+        # `c` to satisfy the upper bound.
+        if not (scale+loc) < mn:
+            if fscale:
+                loc = np.nextafter(loc, -np.inf)
+            else:
+                scale = get_scale(loc)
+                scale = np.nextafter(scale, 0)
+        if not (c*scale+loc) > mx:
+            c = get_c(loc, scale)
+            c = np.nextafter(c, np.inf)
+
+        if not (np.all(self._argcheck(b, c)) and (scale > 0)):
+            return fallback(data, *args, **kwds)
+
+        params_override = b, c, loc, scale
+        if floc is None and fscale is None:
+            # Based on testing in gh-16782, the following methods are only
+            # reliable if either `floc` or `fscale` are provided. They are
+            # fast, though, so might as well see if they are better than the
+            # generic method.
+            params_super = fallback(data, *args, **kwds)
+            nllf_override = self.nnlf(params_override, data)
+            nllf_super = self.nnlf(params_super, data)
+            if nllf_super < nllf_override:
+                return params_super
+
+        return params_override
+
+
+truncpareto = truncpareto_gen(a=1.0, name='truncpareto')
+truncpareto._support = (1.0, 'c')
+
+
+class tukeylambda_gen(rv_continuous):
+    r"""A Tukey-Lamdba continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    A flexible distribution, able to represent and interpolate between the
+    following distributions:
+
+    - Cauchy                (:math:`lambda = -1`)
+    - logistic              (:math:`lambda = 0`)
+    - approx Normal         (:math:`lambda = 0.14`)
+    - uniform from -1 to 1  (:math:`lambda = 1`)
+
+    `tukeylambda` takes a real number :math:`lambda` (denoted ``lam``
+    in the implementation) as a shape parameter.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _argcheck(self, lam):
+        return np.isfinite(lam)
+
+    def _shape_info(self):
+        return [_ShapeInfo("lam", False, (-np.inf, np.inf), (False, False))]
+
+    def _get_support(self, lam):
+        b = _lazywhere(lam > 0, (lam,),
+                       f=lambda lam: 1/lam,
+                       fillvalue=np.inf)
+        return -b, b
+
+    def _pdf(self, x, lam):
+        Fx = np.asarray(sc.tklmbda(x, lam))
+        Px = Fx**(lam-1.0) + (np.asarray(1-Fx))**(lam-1.0)
+        with np.errstate(divide='ignore'):
+            Px = 1.0/np.asarray(Px)
+            return np.where((lam <= 0) | (abs(x) < 1.0/np.asarray(lam)), Px, 0.0)
+
+    def _cdf(self, x, lam):
+        return sc.tklmbda(x, lam)
+
+    def _ppf(self, q, lam):
+        return sc.boxcox(q, lam) - sc.boxcox1p(-q, lam)
+
+    def _stats(self, lam):
+        return 0, _tlvar(lam), 0, _tlkurt(lam)
+
+    def _entropy(self, lam):
+        def integ(p):
+            return np.log(pow(p, lam-1)+pow(1-p, lam-1))
+        return integrate.quad(integ, 0, 1)[0]
+
+
+tukeylambda = tukeylambda_gen(name='tukeylambda')
+
+
+class FitUniformFixedScaleDataError(FitDataError):
+    def __init__(self, ptp, fscale):
+        self.args = (
+            "Invalid values in `data`.  Maximum likelihood estimation with "
+            "the uniform distribution and fixed scale requires that "
+            f"np.ptp(data) <= fscale, but np.ptp(data) = {ptp} and "
+            f"fscale = {fscale}."
+        )
+
+
+class uniform_gen(rv_continuous):
+    r"""A uniform continuous random variable.
+
+    In the standard form, the distribution is uniform on ``[0, 1]``. Using
+    the parameters ``loc`` and ``scale``, one obtains the uniform distribution
+    on ``[loc, loc + scale]``.
+
+    %(before_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.uniform(0.0, 1.0, size)
+
+    def _pdf(self, x):
+        return 1.0*(x == x)
+
+    def _cdf(self, x):
+        return x
+
+    def _ppf(self, q):
+        return q
+
+    def _stats(self):
+        return 0.5, 1.0/12, 0, -1.2
+
+    def _entropy(self):
+        return 0.0
+
+    @_call_super_mom
+    def fit(self, data, *args, **kwds):
+        """
+        Maximum likelihood estimate for the location and scale parameters.
+
+        `uniform.fit` uses only the following parameters.  Because exact
+        formulas are used, the parameters related to optimization that are
+        available in the `fit` method of other distributions are ignored
+        here.  The only positional argument accepted is `data`.
+
+        Parameters
+        ----------
+        data : array_like
+            Data to use in calculating the maximum likelihood estimate.
+        floc : float, optional
+            Hold the location parameter fixed to the specified value.
+        fscale : float, optional
+            Hold the scale parameter fixed to the specified value.
+
+        Returns
+        -------
+        loc, scale : float
+            Maximum likelihood estimates for the location and scale.
+
+        Notes
+        -----
+        An error is raised if `floc` is given and any values in `data` are
+        less than `floc`, or if `fscale` is given and `fscale` is less
+        than ``data.max() - data.min()``.  An error is also raised if both
+        `floc` and `fscale` are given.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.stats import uniform
+
+        We'll fit the uniform distribution to `x`:
+
+        >>> x = np.array([2, 2.5, 3.1, 9.5, 13.0])
+
+        For a uniform distribution MLE, the location is the minimum of the
+        data, and the scale is the maximum minus the minimum.
+
+        >>> loc, scale = uniform.fit(x)
+        >>> loc
+        2.0
+        >>> scale
+        11.0
+
+        If we know the data comes from a uniform distribution where the support
+        starts at 0, we can use ``floc=0``:
+
+        >>> loc, scale = uniform.fit(x, floc=0)
+        >>> loc
+        0.0
+        >>> scale
+        13.0
+
+        Alternatively, if we know the length of the support is 12, we can use
+        ``fscale=12``:
+
+        >>> loc, scale = uniform.fit(x, fscale=12)
+        >>> loc
+        1.5
+        >>> scale
+        12.0
+
+        In that last example, the support interval is [1.5, 13.5].  This
+        solution is not unique.  For example, the distribution with ``loc=2``
+        and ``scale=12`` has the same likelihood as the one above.  When
+        `fscale` is given and it is larger than ``data.max() - data.min()``,
+        the parameters returned by the `fit` method center the support over
+        the interval ``[data.min(), data.max()]``.
+
+        """
+        if len(args) > 0:
+            raise TypeError("Too many arguments.")
+
+        floc = kwds.pop('floc', None)
+        fscale = kwds.pop('fscale', None)
+
+        _remove_optimizer_parameters(kwds)
+
+        if floc is not None and fscale is not None:
+            # This check is for consistency with `rv_continuous.fit`.
+            raise ValueError("All parameters fixed. There is nothing to "
+                             "optimize.")
+
+        data = np.asarray(data)
+
+        if not np.isfinite(data).all():
+            raise ValueError("The data contains non-finite values.")
+
+        # MLE for the uniform distribution
+        # --------------------------------
+        # The PDF is
+        #
+        #     f(x, loc, scale) = {1/scale  for loc <= x <= loc + scale
+        #                        {0        otherwise}
+        #
+        # The likelihood function is
+        #     L(x, loc, scale) = (1/scale)**n
+        # where n is len(x), assuming loc <= x <= loc + scale for all x.
+        # The log-likelihood is
+        #     l(x, loc, scale) = -n*log(scale)
+        # The log-likelihood is maximized by making scale as small as possible,
+        # while keeping loc <= x <= loc + scale.   So if neither loc nor scale
+        # are fixed, the log-likelihood is maximized by choosing
+        #     loc = x.min()
+        #     scale = np.ptp(x)
+        # If loc is fixed, it must be less than or equal to x.min(), and then
+        # the scale is
+        #     scale = x.max() - loc
+        # If scale is fixed, it must not be less than np.ptp(x).  If scale is
+        # greater than np.ptp(x), the solution is not unique.  Note that the
+        # likelihood does not depend on loc, except for the requirement that
+        # loc <= x <= loc + scale.  All choices of loc for which
+        #     x.max() - scale <= loc <= x.min()
+        # have the same log-likelihood.  In this case, we choose loc such that
+        # the support is centered over the interval [data.min(), data.max()]:
+        #     loc = x.min() = 0.5*(scale - np.ptp(x))
+
+        if fscale is None:
+            # scale is not fixed.
+            if floc is None:
+                # loc is not fixed, scale is not fixed.
+                loc = data.min()
+                scale = np.ptp(data)
+            else:
+                # loc is fixed, scale is not fixed.
+                loc = floc
+                scale = data.max() - loc
+                if data.min() < loc:
+                    raise FitDataError("uniform", lower=loc, upper=loc + scale)
+        else:
+            # loc is not fixed, scale is fixed.
+            ptp = np.ptp(data)
+            if ptp > fscale:
+                raise FitUniformFixedScaleDataError(ptp=ptp, fscale=fscale)
+            # If ptp < fscale, the ML estimate is not unique; see the comments
+            # above.  We choose the distribution for which the support is
+            # centered over the interval [data.min(), data.max()].
+            loc = data.min() - 0.5*(fscale - ptp)
+            scale = fscale
+
+        # We expect the return values to be floating point, so ensure it
+        # by explicitly converting to float.
+        return float(loc), float(scale)
+
+
+uniform = uniform_gen(a=0.0, b=1.0, name='uniform')
+
+
+class vonmises_gen(rv_continuous):
+    r"""A Von Mises continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    scipy.stats.vonmises_fisher : Von-Mises Fisher distribution on a
+                                  hypersphere
+
+    Notes
+    -----
+    The probability density function for `vonmises` and `vonmises_line` is:
+
+    .. math::
+
+        f(x, \kappa) = \frac{ \exp(\kappa \cos(x)) }{ 2 \pi I_0(\kappa) }
+
+    for :math:`-\pi \le x \le \pi`, :math:`\kappa \ge 0`. :math:`I_0` is the
+    modified Bessel function of order zero (`scipy.special.i0`).
+
+    `vonmises` is a circular distribution which does not restrict the
+    distribution to a fixed interval. Currently, there is no circular
+    distribution framework in SciPy. The ``cdf`` is implemented such that
+    ``cdf(x + 2*np.pi) == cdf(x) + 1``.
+
+    `vonmises_line` is the same distribution, defined on :math:`[-\pi, \pi]`
+    on the real line. This is a regular (i.e. non-circular) distribution.
+
+    Note about distribution parameters: `vonmises` and `vonmises_line` take
+    ``kappa`` as a shape parameter (concentration) and ``loc`` as the location
+    (circular mean). A ``scale`` parameter is accepted but does not have any
+    effect.
+
+    Examples
+    --------
+    Import the necessary modules.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import vonmises
+
+    Define distribution parameters.
+
+    >>> loc = 0.5 * np.pi  # circular mean
+    >>> kappa = 1  # concentration
+
+    Compute the probability density at ``x=0`` via the ``pdf`` method.
+
+    >>> vonmises.pdf(0, loc=loc, kappa=kappa)
+    0.12570826359722018
+
+    Verify that the percentile function ``ppf`` inverts the cumulative
+    distribution function ``cdf`` up to floating point accuracy.
+
+    >>> x = 1
+    >>> cdf_value = vonmises.cdf(x, loc=loc, kappa=kappa)
+    >>> ppf_value = vonmises.ppf(cdf_value, loc=loc, kappa=kappa)
+    >>> x, cdf_value, ppf_value
+    (1, 0.31489339900904967, 1.0000000000000004)
+
+    Draw 1000 random variates by calling the ``rvs`` method.
+
+    >>> sample_size = 1000
+    >>> sample = vonmises(loc=loc, kappa=kappa).rvs(sample_size)
+
+    Plot the von Mises density on a Cartesian and polar grid to emphasize
+    that it is a circular distribution.
+
+    >>> fig = plt.figure(figsize=(12, 6))
+    >>> left = plt.subplot(121)
+    >>> right = plt.subplot(122, projection='polar')
+    >>> x = np.linspace(-np.pi, np.pi, 500)
+    >>> vonmises_pdf = vonmises.pdf(x, loc=loc, kappa=kappa)
+    >>> ticks = [0, 0.15, 0.3]
+
+    The left image contains the Cartesian plot.
+
+    >>> left.plot(x, vonmises_pdf)
+    >>> left.set_yticks(ticks)
+    >>> number_of_bins = int(np.sqrt(sample_size))
+    >>> left.hist(sample, density=True, bins=number_of_bins)
+    >>> left.set_title("Cartesian plot")
+    >>> left.set_xlim(-np.pi, np.pi)
+    >>> left.grid(True)
+
+    The right image contains the polar plot.
+
+    >>> right.plot(x, vonmises_pdf, label="PDF")
+    >>> right.set_yticks(ticks)
+    >>> right.hist(sample, density=True, bins=number_of_bins,
+    ...            label="Histogram")
+    >>> right.set_title("Polar plot")
+    >>> right.legend(bbox_to_anchor=(0.15, 1.06))
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("kappa", False, (0, np.inf), (True, False))]
+
+    def _argcheck(self, kappa):
+        return kappa >= 0
+
+    def _rvs(self, kappa, size=None, random_state=None):
+        return random_state.vonmises(0.0, kappa, size=size)
+
+    @inherit_docstring_from(rv_continuous)
+    def rvs(self, *args, **kwds):
+        rvs = super().rvs(*args, **kwds)
+        return np.mod(rvs + np.pi, 2*np.pi) - np.pi
+
+    def _pdf(self, x, kappa):
+        # vonmises.pdf(x, kappa) = exp(kappa * cos(x)) / (2*pi*I[0](kappa))
+        #                        = exp(kappa * (cos(x) - 1)) /
+        #                          (2*pi*exp(-kappa)*I[0](kappa))
+        #                        = exp(kappa * cosm1(x)) / (2*pi*i0e(kappa))
+        return np.exp(kappa*sc.cosm1(x)) / (2*np.pi*sc.i0e(kappa))
+
+    def _logpdf(self, x, kappa):
+        # vonmises.pdf(x, kappa) = exp(kappa * cosm1(x)) / (2*pi*i0e(kappa))
+        return kappa * sc.cosm1(x) - np.log(2*np.pi) - np.log(sc.i0e(kappa))
+
+    def _cdf(self, x, kappa):
+        return _stats.von_mises_cdf(kappa, x)
+
+    def _stats_skip(self, kappa):
+        return 0, None, 0, None
+
+    def _entropy(self, kappa):
+        # vonmises.entropy(kappa) = -kappa * I[1](kappa) / I[0](kappa) +
+        #                           log(2 * np.pi * I[0](kappa))
+        #                         = -kappa * I[1](kappa) * exp(-kappa) /
+        #                           (I[0](kappa) * exp(-kappa)) +
+        #                           log(2 * np.pi *
+        #                           I[0](kappa) * exp(-kappa) / exp(-kappa))
+        #                         = -kappa * sc.i1e(kappa) / sc.i0e(kappa) +
+        #                           log(2 * np.pi * i0e(kappa)) + kappa
+        return (-kappa * sc.i1e(kappa) / sc.i0e(kappa) +
+                np.log(2 * np.pi * sc.i0e(kappa)) + kappa)
+
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        The default limits of integration are endpoints of the interval
+        of width ``2*pi`` centered at `loc` (e.g. ``[-pi, pi]`` when
+        ``loc=0``).\n\n""")
+    def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None,
+               conditional=False, **kwds):
+        _a, _b = -np.pi, np.pi
+
+        if lb is None:
+            lb = loc + _a
+        if ub is None:
+            ub = loc + _b
+
+        return super().expect(func, args, loc,
+                              scale, lb, ub, conditional, **kwds)
+
+    @_call_super_mom
+    @extend_notes_in_docstring(rv_continuous, notes="""\
+        Fit data is assumed to represent angles and will be wrapped onto the
+        unit circle. `f0` and `fscale` are ignored; the returned shape is
+        always the maximum likelihood estimate and the scale is always
+        1. Initial guesses are ignored.\n\n""")
+    def fit(self, data, *args, **kwds):
+        if kwds.pop('superfit', False):
+            return super().fit(data, *args, **kwds)
+
+        data, fshape, floc, fscale = _check_fit_input_parameters(self, data,
+                                                                 args, kwds)
+        if self.a == -np.pi:
+            # vonmises line case, here the default fit method will be used
+            return super().fit(data, *args, **kwds)
+
+        # wrap data to interval [0, 2*pi]
+        data = np.mod(data, 2 * np.pi)
+
+        def find_mu(data):
+            return stats.circmean(data)
+
+        def find_kappa(data, loc):
+            # Usually, sources list the following as the equation to solve for
+            # the MLE of the shape parameter:
+            # r = I[1](kappa)/I[0](kappa), where r = mean resultant length
+            # This is valid when the location is the MLE of location.
+            # More generally, when the location may be fixed at an arbitrary
+            # value, r should be defined as follows:
+            r = np.sum(np.cos(loc - data))/len(data)
+            # See gh-18128 for more information.
+
+            # The function r[0](kappa) := I[1](kappa)/I[0](kappa) is monotonic
+            # increasing from r[0](0) = 0 to r[0](+inf) = 1.  The partial
+            # derivative of the log likelihood function with respect to kappa
+            # is monotonic decreasing in kappa.
+            if r == 1:
+                # All observations are (almost) equal to the mean.  Return
+                # some large kappa such that r[0](kappa) = 1.0 numerically.
+                return 1e16
+            elif r > 0:
+                def solve_for_kappa(kappa):
+                    return sc.i1e(kappa)/sc.i0e(kappa) - r
+
+                # The bounds of the root of r[0](kappa) = r are derived from
+                # selected bounds of r[0](x) given in [1, Eq. 11 & 16].  See
+                # gh-20102 for details.
+                #
+                # [1] Amos, D. E. (1973).  Computation of Modified Bessel
+                #     Functions and Their Ratios.  Mathematics of Computation,
+                #     28(125): 239-251.
+                lower_bound = r/(1-r)/(1+r)
+                upper_bound = 2*lower_bound
+
+                # The bounds are violated numerically for certain values of r,
+                # where solve_for_kappa evaluated at the bounds have the same
+                # sign.  This indicates numerical imprecision of i1e()/i0e().
+                # Return the violated bound in this case as it's more accurate.
+                if solve_for_kappa(lower_bound) >= 0:
+                    return lower_bound
+                elif solve_for_kappa(upper_bound) <= 0:
+                    return upper_bound
+                else:
+                    root_res = root_scalar(solve_for_kappa, method="brentq",
+                                           bracket=(lower_bound, upper_bound))
+                    return root_res.root
+            else:
+                # if the provided floc is very far from the circular mean,
+                # the mean resultant length r can become negative.
+                # In that case, the equation
+                # I[1](kappa)/I[0](kappa) = r does not have a solution.
+                # The maximum likelihood kappa is then 0 which practically
+                # results in the uniform distribution on the circle. As
+                # vonmises is defined for kappa > 0, return instead the
+                # smallest floating point value.
+                # See gh-18190 for more information
+                return np.finfo(float).tiny
+
+        # location likelihood equation has a solution independent of kappa
+        loc = floc if floc is not None else find_mu(data)
+        # shape likelihood equation depends on location
+        shape = fshape if fshape is not None else find_kappa(data, loc)
+
+        loc = np.mod(loc + np.pi, 2 * np.pi) - np.pi  # ensure in [-pi, pi]
+        return shape, loc, 1  # scale is not handled
+
+
+vonmises = vonmises_gen(name='vonmises')
+vonmises_line = vonmises_gen(a=-np.pi, b=np.pi, name='vonmises_line')
+
+
+class wald_gen(invgauss_gen):
+    r"""A Wald continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `wald` is:
+
+    .. math::
+
+        f(x) = \frac{1}{\sqrt{2\pi x^3}} \exp(- \frac{ (x-1)^2 }{ 2x })
+
+    for :math:`x >= 0`.
+
+    `wald` is a special case of `invgauss` with ``mu=1``.
+
+    %(after_notes)s
+
+    %(example)s
+    """
+    _support_mask = rv_continuous._open_support_mask
+
+    def _shape_info(self):
+        return []
+
+    def _rvs(self, size=None, random_state=None):
+        return random_state.wald(1.0, 1.0, size=size)
+
+    def _pdf(self, x):
+        # wald.pdf(x) = 1/sqrt(2*pi*x**3) * exp(-(x-1)**2/(2*x))
+        return invgauss._pdf(x, 1.0)
+
+    def _cdf(self, x):
+        return invgauss._cdf(x, 1.0)
+
+    def _sf(self, x):
+        return invgauss._sf(x, 1.0)
+
+    def _ppf(self, x):
+        return invgauss._ppf(x, 1.0)
+
+    def _isf(self, x):
+        return invgauss._isf(x, 1.0)
+
+    def _logpdf(self, x):
+        return invgauss._logpdf(x, 1.0)
+
+    def _logcdf(self, x):
+        return invgauss._logcdf(x, 1.0)
+
+    def _logsf(self, x):
+        return invgauss._logsf(x, 1.0)
+
+    def _stats(self):
+        return 1.0, 1.0, 3.0, 15.0
+
+    def _entropy(self):
+        return invgauss._entropy(1.0)
+
+
+wald = wald_gen(a=0.0, name="wald")
+
+
+class wrapcauchy_gen(rv_continuous):
+    r"""A wrapped Cauchy continuous random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `wrapcauchy` is:
+
+    .. math::
+
+        f(x, c) = \frac{1-c^2}{2\pi (1+c^2 - 2c \cos(x))}
+
+    for :math:`0 \le x \le 2\pi`, :math:`0 < c < 1`.
+
+    `wrapcauchy` takes ``c`` as a shape parameter for :math:`c`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _argcheck(self, c):
+        return (c > 0) & (c < 1)
+
+    def _shape_info(self):
+        return [_ShapeInfo("c", False, (0, 1), (False, False))]
+
+    def _pdf(self, x, c):
+        # wrapcauchy.pdf(x, c) = (1-c**2) / (2*pi*(1+c**2-2*c*cos(x)))
+        return (1.0-c*c)/(2*np.pi*(1+c*c-2*c*np.cos(x)))
+
+    def _cdf(self, x, c):
+
+        def f1(x, cr):
+            # CDF for 0 <= x < pi
+            return 1/np.pi * np.arctan(cr*np.tan(x/2))
+
+        def f2(x, cr):
+            # CDF for pi <= x <= 2*pi
+            return 1 - 1/np.pi * np.arctan(cr*np.tan((2*np.pi - x)/2))
+
+        cr = (1 + c)/(1 - c)
+        return _lazywhere(x < np.pi, (x, cr), f=f1, f2=f2)
+
+    def _ppf(self, q, c):
+        val = (1.0-c)/(1.0+c)
+        rcq = 2*np.arctan(val*np.tan(np.pi*q))
+        rcmq = 2*np.pi-2*np.arctan(val*np.tan(np.pi*(1-q)))
+        return np.where(q < 1.0/2, rcq, rcmq)
+
+    def _entropy(self, c):
+        return np.log(2*np.pi*(1-c*c))
+
+    def _fitstart(self, data):
+        # Use 0.5 as the initial guess of the shape parameter.
+        # For the location and scale, use the minimum and
+        # peak-to-peak/(2*pi), respectively.
+        if isinstance(data, CensoredData):
+            data = data._uncensor()
+        return 0.5, np.min(data), np.ptp(data)/(2*np.pi)
+
+
+wrapcauchy = wrapcauchy_gen(a=0.0, b=2*np.pi, name='wrapcauchy')
+
+
+class gennorm_gen(rv_continuous):
+    r"""A generalized normal continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    laplace : Laplace distribution
+    norm : normal distribution
+
+    Notes
+    -----
+    The probability density function for `gennorm` is [1]_:
+
+    .. math::
+
+        f(x, \beta) = \frac{\beta}{2 \Gamma(1/\beta)} \exp(-|x|^\beta),
+
+    where :math:`x` is a real number, :math:`\beta > 0` and
+    :math:`\Gamma` is the gamma function (`scipy.special.gamma`).
+
+    `gennorm` takes ``beta`` as a shape parameter for :math:`\beta`.
+    For :math:`\beta = 1`, it is identical to a Laplace distribution.
+    For :math:`\beta = 2`, it is identical to a normal distribution
+    (with ``scale=1/sqrt(2)``).
+
+    References
+    ----------
+
+    .. [1] "Generalized normal distribution, Version 1",
+           https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1
+
+    .. [2] Nardon, Martina, and Paolo Pianca. "Simulation techniques for
+           generalized Gaussian densities." Journal of Statistical
+           Computation and Simulation 79.11 (2009): 1317-1329
+
+    .. [3] Wicklin, Rick. "Simulate data from a generalized Gaussian
+           distribution" in The DO Loop blog, September 21, 2016,
+           https://blogs.sas.com/content/iml/2016/09/21/simulate-generalized-gaussian-sas.html
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("beta", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, beta):
+        return np.exp(self._logpdf(x, beta))
+
+    def _logpdf(self, x, beta):
+        return np.log(0.5*beta) - sc.gammaln(1.0/beta) - abs(x)**beta
+
+    def _cdf(self, x, beta):
+        c = 0.5 * np.sign(x)
+        # evaluating (.5 + c) first prevents numerical cancellation
+        return (0.5 + c) - c * sc.gammaincc(1.0/beta, abs(x)**beta)
+
+    def _ppf(self, x, beta):
+        c = np.sign(x - 0.5)
+        # evaluating (1. + c) first prevents numerical cancellation
+        return c * sc.gammainccinv(1.0/beta, (1.0 + c) - 2.0*c*x)**(1.0/beta)
+
+    def _sf(self, x, beta):
+        return self._cdf(-x, beta)
+
+    def _isf(self, x, beta):
+        return -self._ppf(x, beta)
+
+    def _stats(self, beta):
+        c1, c3, c5 = sc.gammaln([1.0/beta, 3.0/beta, 5.0/beta])
+        return 0., np.exp(c3 - c1), 0., np.exp(c5 + c1 - 2.0*c3) - 3.
+
+    def _entropy(self, beta):
+        return 1. / beta - np.log(.5 * beta) + sc.gammaln(1. / beta)
+
+    def _rvs(self, beta, size=None, random_state=None):
+        # see [2]_ for the algorithm
+        # see [3]_ for reference implementation in SAS
+        z = random_state.gamma(1/beta, size=size)
+        y = z ** (1/beta)
+        # convert y to array to ensure masking support
+        y = np.asarray(y)
+        mask = random_state.random(size=y.shape) < 0.5
+        y[mask] = -y[mask]
+        return y
+
+
+gennorm = gennorm_gen(name='gennorm')
+
+
+class halfgennorm_gen(rv_continuous):
+    r"""The upper half of a generalized normal continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    gennorm : generalized normal distribution
+    expon : exponential distribution
+    halfnorm : half normal distribution
+
+    Notes
+    -----
+    The probability density function for `halfgennorm` is:
+
+    .. math::
+
+        f(x, \beta) = \frac{\beta}{\Gamma(1/\beta)} \exp(-|x|^\beta)
+
+    for :math:`x, \beta > 0`. :math:`\Gamma` is the gamma function
+    (`scipy.special.gamma`).
+
+    `halfgennorm` takes ``beta`` as a shape parameter for :math:`\beta`.
+    For :math:`\beta = 1`, it is identical to an exponential distribution.
+    For :math:`\beta = 2`, it is identical to a half normal distribution
+    (with ``scale=1/sqrt(2)``).
+
+    References
+    ----------
+
+    .. [1] "Generalized normal distribution, Version 1",
+           https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("beta", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, beta):
+        #                                 beta
+        # halfgennorm.pdf(x, beta) =  -------------  exp(-|x|**beta)
+        #                             gamma(1/beta)
+        return np.exp(self._logpdf(x, beta))
+
+    def _logpdf(self, x, beta):
+        return np.log(beta) - sc.gammaln(1.0/beta) - x**beta
+
+    def _cdf(self, x, beta):
+        return sc.gammainc(1.0/beta, x**beta)
+
+    def _ppf(self, x, beta):
+        return sc.gammaincinv(1.0/beta, x)**(1.0/beta)
+
+    def _sf(self, x, beta):
+        return sc.gammaincc(1.0/beta, x**beta)
+
+    def _isf(self, x, beta):
+        return sc.gammainccinv(1.0/beta, x)**(1.0/beta)
+
+    def _entropy(self, beta):
+        return 1.0/beta - np.log(beta) + sc.gammaln(1.0/beta)
+
+
+halfgennorm = halfgennorm_gen(a=0, name='halfgennorm')
+
+
+class crystalball_gen(rv_continuous):
+    r"""
+    Crystalball distribution
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `crystalball` is:
+
+    .. math::
+
+        f(x, \beta, m) =  \begin{cases}
+                            N \exp(-x^2 / 2),  &\text{for } x > -\beta\\
+                            N A (B - x)^{-m}  &\text{for } x \le -\beta
+                          \end{cases}
+
+    where :math:`A = (m / |\beta|)^m  \exp(-\beta^2 / 2)`,
+    :math:`B = m/|\beta| - |\beta|` and :math:`N` is a normalisation constant.
+
+    `crystalball` takes :math:`\beta > 0` and :math:`m > 1` as shape
+    parameters.  :math:`\beta` defines the point where the pdf changes
+    from a power-law to a Gaussian distribution.  :math:`m` is the power
+    of the power-law tail.
+
+    %(after_notes)s
+
+    .. versionadded:: 0.19.0
+
+    References
+    ----------
+    .. [1] "Crystal Ball Function",
+           https://en.wikipedia.org/wiki/Crystal_Ball_function
+
+    %(example)s
+    """
+    def _argcheck(self, beta, m):
+        """
+        Shape parameter bounds are m > 1 and beta > 0.
+        """
+        return (m > 1) & (beta > 0)
+
+    def _shape_info(self):
+        ibeta = _ShapeInfo("beta", False, (0, np.inf), (False, False))
+        im = _ShapeInfo("m", False, (1, np.inf), (False, False))
+        return [ibeta, im]
+
+    def _fitstart(self, data):
+        # Arbitrary, but the default m=1 is not valid
+        return super()._fitstart(data, args=(1, 1.5))
+
+    def _pdf(self, x, beta, m):
+        """
+        Return PDF of the crystalball function.
+
+                                            --
+                                           | exp(-x**2 / 2),  for x > -beta
+        crystalball.pdf(x, beta, m) =  N * |
+                                           | A * (B - x)**(-m), for x <= -beta
+                                            --
+        """
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+
+        def rhs(x, beta, m):
+            return np.exp(-x**2 / 2)
+
+        def lhs(x, beta, m):
+            return ((m/beta)**m * np.exp(-beta**2 / 2.0) *
+                    (m/beta - beta - x)**(-m))
+
+        return N * _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs)
+
+    def _logpdf(self, x, beta, m):
+        """
+        Return the log of the PDF of the crystalball function.
+        """
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+
+        def rhs(x, beta, m):
+            return -x**2/2
+
+        def lhs(x, beta, m):
+            return m*np.log(m/beta) - beta**2/2 - m*np.log(m/beta - beta - x)
+
+        return np.log(N) + _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs)
+
+    def _cdf(self, x, beta, m):
+        """
+        Return CDF of the crystalball function
+        """
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+
+        def rhs(x, beta, m):
+            return ((m/beta) * np.exp(-beta**2 / 2.0) / (m-1) +
+                    _norm_pdf_C * (_norm_cdf(x) - _norm_cdf(-beta)))
+
+        def lhs(x, beta, m):
+            return ((m/beta)**m * np.exp(-beta**2 / 2.0) *
+                    (m/beta - beta - x)**(-m+1) / (m-1))
+
+        return N * _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs)
+
+    def _sf(self, x, beta, m):
+        """
+        Survival function of the crystalball distribution.
+        """
+
+        def rhs(x, beta, m):
+            # M is the same as 1/N used elsewhere.
+            M = m/beta/(m - 1)*np.exp(-beta**2/2) + _norm_pdf_C*_norm_cdf(beta)
+            return _norm_pdf_C*_norm_sf(x)/M
+
+        def lhs(x, beta, m):
+            # Default behavior is OK in the left tail of the SF.
+            return 1 - self._cdf(x, beta, m)
+
+        return _lazywhere(x > -beta, (x, beta, m), f=rhs, f2=lhs)
+
+    def _ppf(self, p, beta, m):
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+        pbeta = N * (m/beta) * np.exp(-beta**2/2) / (m - 1)
+
+        def ppf_less(p, beta, m):
+            eb2 = np.exp(-beta**2/2)
+            C = (m/beta) * eb2 / (m-1)
+            N = 1/(C + _norm_pdf_C * _norm_cdf(beta))
+            return (m/beta - beta -
+                    ((m - 1)*(m/beta)**(-m)/eb2*p/N)**(1/(1-m)))
+
+        def ppf_greater(p, beta, m):
+            eb2 = np.exp(-beta**2/2)
+            C = (m/beta) * eb2 / (m-1)
+            N = 1/(C + _norm_pdf_C * _norm_cdf(beta))
+            return _norm_ppf(_norm_cdf(-beta) + (1/_norm_pdf_C)*(p/N - C))
+
+        return _lazywhere(p < pbeta, (p, beta, m), f=ppf_less, f2=ppf_greater)
+
+    def _munp(self, n, beta, m):
+        """
+        Returns the n-th non-central moment of the crystalball function.
+        """
+        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) +
+                   _norm_pdf_C * _norm_cdf(beta))
+
+        def n_th_moment(n, beta, m):
+            """
+            Returns n-th moment. Defined only if n+1 < m
+            Function cannot broadcast due to the loop over n
+            """
+            A = (m/beta)**m * np.exp(-beta**2 / 2.0)
+            B = m/beta - beta
+            rhs = (2**((n-1)/2.0) * sc.gamma((n+1)/2) *
+                   (1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2)))
+            lhs = np.zeros(rhs.shape)
+            for k in range(int(n) + 1):
+                lhs += (sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) *
+                        (m/beta)**(-m + k + 1))
+            return A * lhs + rhs
+
+        return N * _lazywhere(n + 1 < m, (n, beta, m),
+                              np.vectorize(n_th_moment, otypes=[np.float64]),
+                              np.inf)
+
+
+crystalball = crystalball_gen(name='crystalball', longname="A Crystalball Function")
+
+
+def _argus_phi(chi):
+    """
+    Utility function for the argus distribution used in the pdf, sf and
+    moment calculation.
+    Note that for all x > 0:
+    gammainc(1.5, x**2/2) = 2 * (_norm_cdf(x) - x * _norm_pdf(x) - 0.5).
+    This can be verified directly by noting that the cdf of Gamma(1.5) can
+    be written as erf(sqrt(x)) - 2*sqrt(x)*exp(-x)/sqrt(Pi).
+    We use gammainc instead of the usual definition because it is more precise
+    for small chi.
+    """
+    return sc.gammainc(1.5, chi**2/2) / 2
+
+
+class argus_gen(rv_continuous):
+    r"""
+    Argus distribution
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability density function for `argus` is:
+
+    .. math::
+
+        f(x, \chi) = \frac{\chi^3}{\sqrt{2\pi} \Psi(\chi)} x \sqrt{1-x^2}
+                     \exp(-\chi^2 (1 - x^2)/2)
+
+    for :math:`0 < x < 1` and :math:`\chi > 0`, where
+
+    .. math::
+
+        \Psi(\chi) = \Phi(\chi) - \chi \phi(\chi) - 1/2
+
+    with :math:`\Phi` and :math:`\phi` being the CDF and PDF of a standard
+    normal distribution, respectively.
+
+    `argus` takes :math:`\chi` as shape a parameter. Details about sampling
+    from the ARGUS distribution can be found in [2]_.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "ARGUS distribution",
+           https://en.wikipedia.org/wiki/ARGUS_distribution
+    .. [2] Christoph Baumgarten "Random variate generation by fast numerical
+           inversion in the varying parameter case." Research in Statistics,
+           vol. 1, 2023, doi:10.1080/27684520.2023.2279060.
+
+    .. versionadded:: 0.19.0
+
+    %(example)s
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("chi", False, (0, np.inf), (False, False))]
+
+    def _logpdf(self, x, chi):
+        # for x = 0 or 1, logpdf returns -np.inf
+        with np.errstate(divide='ignore'):
+            y = 1.0 - x*x
+            A = 3*np.log(chi) - _norm_pdf_logC - np.log(_argus_phi(chi))
+            return A + np.log(x) + 0.5*np.log1p(-x*x) - chi**2 * y / 2
+
+    def _pdf(self, x, chi):
+        return np.exp(self._logpdf(x, chi))
+
+    def _cdf(self, x, chi):
+        return 1.0 - self._sf(x, chi)
+
+    def _sf(self, x, chi):
+        return _argus_phi(chi * np.sqrt((1 - x)*(1 + x))) / _argus_phi(chi)
+
+    def _rvs(self, chi, size=None, random_state=None):
+        chi = np.asarray(chi)
+        if chi.size == 1:
+            out = self._rvs_scalar(chi, numsamples=size,
+                                   random_state=random_state)
+        else:
+            shp, bc = _check_shape(chi.shape, size)
+            numsamples = int(np.prod(shp))
+            out = np.empty(size)
+            it = np.nditer([chi],
+                           flags=['multi_index'],
+                           op_flags=[['readonly']])
+            while not it.finished:
+                idx = tuple((it.multi_index[j] if not bc[j] else slice(None))
+                            for j in range(-len(size), 0))
+                r = self._rvs_scalar(it[0], numsamples=numsamples,
+                                     random_state=random_state)
+                out[idx] = r.reshape(shp)
+                it.iternext()
+
+        if size == ():
+            out = out[()]
+        return out
+
+    def _rvs_scalar(self, chi, numsamples=None, random_state=None):
+        # if chi <= 1.8:
+        # use rejection method, see Devroye:
+        # Non-Uniform Random Variate Generation, 1986, section II.3.2.
+        # write: PDF f(x) = c * g(x) * h(x), where
+        # h is [0,1]-valued and g is a density
+        # we use two ways to write f
+        #
+        # Case 1:
+        # write g(x) = 3*x*sqrt(1-x**2), h(x) = exp(-chi**2 (1-x**2) / 2)
+        # If X has a distribution with density g its ppf G_inv is given by:
+        # G_inv(u) = np.sqrt(1 - u**(2/3))
+        #
+        # Case 2:
+        # g(x) = chi**2 * x * exp(-chi**2 * (1-x**2)/2) / (1 - exp(-chi**2 /2))
+        # h(x) = sqrt(1 - x**2), 0 <= x <= 1
+        # one can show that
+        # G_inv(u) = np.sqrt(2*np.log(u*(np.exp(chi**2/2)-1)+1))/chi
+        #          = np.sqrt(1 + 2*np.log(np.exp(-chi**2/2)*(1-u)+u)/chi**2)
+        # the latter expression is used for precision with small chi
+        #
+        # In both cases, the inverse cdf of g can be written analytically, and
+        # we can apply the rejection method:
+        #
+        # REPEAT
+        #    Generate U uniformly distributed on [0, 1]
+        #    Generate X with density g (e.g. via inverse transform sampling:
+        #    X = G_inv(V) with V uniformly distributed on [0, 1])
+        # UNTIL X <= h(X)
+        # RETURN X
+        #
+        # We use case 1 for chi <= 0.5 as it maintains precision for small chi
+        # and case 2 for 0.5 < chi <= 1.8 due to its speed for moderate chi.
+        #
+        # if chi > 1.8:
+        # use relation to the Gamma distribution: if X is ARGUS with parameter
+        # chi), then Y = chi**2 * (1 - X**2) / 2 has density proportional to
+        # sqrt(u) * exp(-u) on [0, chi**2 / 2], i.e. a Gamma(3/2) distribution
+        # conditioned on [0, chi**2 / 2]). Therefore, to sample X from the
+        # ARGUS distribution, we sample Y from the gamma distribution, keeping
+        # only samples on [0, chi**2 / 2], and apply the inverse
+        # transformation X = (1 - 2*Y/chi**2)**(1/2). Since we only
+        # look at chi > 1.8, gamma(1.5).cdf(chi**2/2) is large enough such
+        # Y falls in the interval [0, chi**2 / 2] with a high probability:
+        # stats.gamma(1.5).cdf(1.8**2/2) = 0.644...
+        #
+        # The points to switch between the different methods are determined
+        # by a comparison of the runtime of the different methods. However,
+        # the runtime is platform-dependent. The implemented values should
+        # ensure a good overall performance and are supported by an analysis
+        # of the rejection constants of different methods.
+
+        size1d = tuple(np.atleast_1d(numsamples))
+        N = int(np.prod(size1d))
+        x = np.zeros(N)
+        simulated = 0
+        chi2 = chi * chi
+        if chi <= 0.5:
+            d = -chi2 / 2
+            while simulated < N:
+                k = N - simulated
+                u = random_state.uniform(size=k)
+                v = random_state.uniform(size=k)
+                z = v**(2/3)
+                # acceptance condition: u <= h(G_inv(v)). This simplifies to
+                accept = (np.log(u) <= d * z)
+                num_accept = np.sum(accept)
+                if num_accept > 0:
+                    # we still need to transform z=v**(2/3) to X = G_inv(v)
+                    rvs = np.sqrt(1 - z[accept])
+                    x[simulated:(simulated + num_accept)] = rvs
+                    simulated += num_accept
+        elif chi <= 1.8:
+            echi = np.exp(-chi2 / 2)
+            while simulated < N:
+                k = N - simulated
+                u = random_state.uniform(size=k)
+                v = random_state.uniform(size=k)
+                z = 2 * np.log(echi * (1 - v) + v) / chi2
+                # as in case one, simplify u <= h(G_inv(v)) and then transform
+                # z to the target distribution X = G_inv(v)
+                accept = (u**2 + z <= 0)
+                num_accept = np.sum(accept)
+                if num_accept > 0:
+                    rvs = np.sqrt(1 + z[accept])
+                    x[simulated:(simulated + num_accept)] = rvs
+                    simulated += num_accept
+        else:
+            # conditional Gamma for chi > 1.8
+            while simulated < N:
+                k = N - simulated
+                g = random_state.standard_gamma(1.5, size=k)
+                accept = (g <= chi2 / 2)
+                num_accept = np.sum(accept)
+                if num_accept > 0:
+                    x[simulated:(simulated + num_accept)] = g[accept]
+                    simulated += num_accept
+            x = np.sqrt(1 - 2 * x / chi2)
+
+        return np.reshape(x, size1d)
+
+    def _stats(self, chi):
+        # need to ensure that dtype is float
+        # otherwise the mask below does not work for integers
+        chi = np.asarray(chi, dtype=float)
+        phi = _argus_phi(chi)
+        m = np.sqrt(np.pi/8) * chi * sc.ive(1, chi**2/4) / phi
+        # compute second moment, use Taylor expansion for small chi (<= 0.1)
+        mu2 = np.empty_like(chi)
+        mask = chi > 0.1
+        c = chi[mask]
+        mu2[mask] = 1 - 3 / c**2 + c * _norm_pdf(c) / phi[mask]
+        c = chi[~mask]
+        coef = [-358/65690625, 0, -94/1010625, 0, 2/2625, 0, 6/175, 0, 0.4]
+        mu2[~mask] = np.polyval(coef, c)
+        return m, mu2 - m**2, None, None
+
+
+argus = argus_gen(name='argus', longname="An Argus Function", a=0.0, b=1.0)
+
+
+class rv_histogram(rv_continuous):
+    """
+    Generates a distribution given by a histogram.
+    This is useful to generate a template distribution from a binned
+    datasample.
+
+    As a subclass of the `rv_continuous` class, `rv_histogram` inherits from it
+    a collection of generic methods (see `rv_continuous` for the full list),
+    and implements them based on the properties of the provided binned
+    datasample.
+
+    Parameters
+    ----------
+    histogram : tuple of array_like
+        Tuple containing two array_like objects.
+        The first containing the content of n bins,
+        the second containing the (n+1) bin boundaries.
+        In particular, the return value of `numpy.histogram` is accepted.
+
+    density : bool, optional
+        If False, assumes the histogram is proportional to counts per bin;
+        otherwise, assumes it is proportional to a density.
+        For constant bin widths, these are equivalent, but the distinction
+        is important when bin widths vary (see Notes).
+        If None (default), sets ``density=True`` for backwards compatibility,
+        but warns if the bin widths are variable. Set `density` explicitly
+        to silence the warning.
+
+        .. versionadded:: 1.10.0
+
+    Notes
+    -----
+    When a histogram has unequal bin widths, there is a distinction between
+    histograms that are proportional to counts per bin and histograms that are
+    proportional to probability density over a bin. If `numpy.histogram` is
+    called with its default ``density=False``, the resulting histogram is the
+    number of counts per bin, so ``density=False`` should be passed to
+    `rv_histogram`. If `numpy.histogram` is called with ``density=True``, the
+    resulting histogram is in terms of probability density, so ``density=True``
+    should be passed to `rv_histogram`. To avoid warnings, always pass
+    ``density`` explicitly when the input histogram has unequal bin widths.
+
+    There are no additional shape parameters except for the loc and scale.
+    The pdf is defined as a stepwise function from the provided histogram.
+    The cdf is a linear interpolation of the pdf.
+
+    .. versionadded:: 0.19.0
+
+    Examples
+    --------
+
+    Create a scipy.stats distribution from a numpy histogram
+
+    >>> import scipy.stats
+    >>> import numpy as np
+    >>> data = scipy.stats.norm.rvs(size=100000, loc=0, scale=1.5,
+    ...                             random_state=123)
+    >>> hist = np.histogram(data, bins=100)
+    >>> hist_dist = scipy.stats.rv_histogram(hist, density=False)
+
+    Behaves like an ordinary scipy rv_continuous distribution
+
+    >>> hist_dist.pdf(1.0)
+    0.20538577847618705
+    >>> hist_dist.cdf(2.0)
+    0.90818568543056499
+
+    PDF is zero above (below) the highest (lowest) bin of the histogram,
+    defined by the max (min) of the original dataset
+
+    >>> hist_dist.pdf(np.max(data))
+    0.0
+    >>> hist_dist.cdf(np.max(data))
+    1.0
+    >>> hist_dist.pdf(np.min(data))
+    7.7591907244498314e-05
+    >>> hist_dist.cdf(np.min(data))
+    0.0
+
+    PDF and CDF follow the histogram
+
+    >>> import matplotlib.pyplot as plt
+    >>> X = np.linspace(-5.0, 5.0, 100)
+    >>> fig, ax = plt.subplots()
+    >>> ax.set_title("PDF from Template")
+    >>> ax.hist(data, density=True, bins=100)
+    >>> ax.plot(X, hist_dist.pdf(X), label='PDF')
+    >>> ax.plot(X, hist_dist.cdf(X), label='CDF')
+    >>> ax.legend()
+    >>> fig.show()
+
+    """
+    _support_mask = rv_continuous._support_mask
+
+    def __init__(self, histogram, *args, density=None, **kwargs):
+        """
+        Create a new distribution using the given histogram
+
+        Parameters
+        ----------
+        histogram : tuple of array_like
+            Tuple containing two array_like objects.
+            The first containing the content of n bins,
+            the second containing the (n+1) bin boundaries.
+            In particular, the return value of np.histogram is accepted.
+        density : bool, optional
+            If False, assumes the histogram is proportional to counts per bin;
+            otherwise, assumes it is proportional to a density.
+            For constant bin widths, these are equivalent.
+            If None (default), sets ``density=True`` for backward
+            compatibility, but warns if the bin widths are variable. Set
+            `density` explicitly to silence the warning.
+        """
+        self._histogram = histogram
+        self._density = density
+        if len(histogram) != 2:
+            raise ValueError("Expected length 2 for parameter histogram")
+        self._hpdf = np.asarray(histogram[0])
+        self._hbins = np.asarray(histogram[1])
+        if len(self._hpdf) + 1 != len(self._hbins):
+            raise ValueError("Number of elements in histogram content "
+                             "and histogram boundaries do not match, "
+                             "expected n and n+1.")
+        self._hbin_widths = self._hbins[1:] - self._hbins[:-1]
+        bins_vary = not np.allclose(self._hbin_widths, self._hbin_widths[0])
+        if density is None and bins_vary:
+            message = ("Bin widths are not constant. Assuming `density=True`."
+                       "Specify `density` explicitly to silence this warning.")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+            density = True
+        elif not density:
+            self._hpdf = self._hpdf / self._hbin_widths
+
+        self._hpdf = self._hpdf / float(np.sum(self._hpdf * self._hbin_widths))
+        self._hcdf = np.cumsum(self._hpdf * self._hbin_widths)
+        self._hpdf = np.hstack([0.0, self._hpdf, 0.0])
+        self._hcdf = np.hstack([0.0, self._hcdf])
+        # Set support
+        kwargs['a'] = self.a = self._hbins[0]
+        kwargs['b'] = self.b = self._hbins[-1]
+        super().__init__(*args, **kwargs)
+
+    def _pdf(self, x):
+        """
+        PDF of the histogram
+        """
+        return self._hpdf[np.searchsorted(self._hbins, x, side='right')]
+
+    def _cdf(self, x):
+        """
+        CDF calculated from the histogram
+        """
+        return np.interp(x, self._hbins, self._hcdf)
+
+    def _ppf(self, x):
+        """
+        Percentile function calculated from the histogram
+        """
+        return np.interp(x, self._hcdf, self._hbins)
+
+    def _munp(self, n):
+        """Compute the n-th non-central moment."""
+        integrals = (self._hbins[1:]**(n+1) - self._hbins[:-1]**(n+1)) / (n+1)
+        return np.sum(self._hpdf[1:-1] * integrals)
+
+    def _entropy(self):
+        """Compute entropy of distribution"""
+        res = _lazywhere(self._hpdf[1:-1] > 0.0,
+                         (self._hpdf[1:-1],),
+                         np.log,
+                         0.0)
+        return -np.sum(self._hpdf[1:-1] * res * self._hbin_widths)
+
+    def _updated_ctor_param(self):
+        """
+        Set the histogram as additional constructor argument
+        """
+        dct = super()._updated_ctor_param()
+        dct['histogram'] = self._histogram
+        dct['density'] = self._density
+        return dct
+
+
+class studentized_range_gen(rv_continuous):
+    r"""A studentized range continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    t: Student's t distribution
+
+    Notes
+    -----
+    The probability density function for `studentized_range` is:
+
+    .. math::
+
+         f(x; k, \nu) = \frac{k(k-1)\nu^{\nu/2}}{\Gamma(\nu/2)
+                        2^{\nu/2-1}} \int_{0}^{\infty} \int_{-\infty}^{\infty}
+                        s^{\nu} e^{-\nu s^2/2} \phi(z) \phi(sx + z)
+                        [\Phi(sx + z) - \Phi(z)]^{k-2} \,dz \,ds
+
+    for :math:`x ≥ 0`, :math:`k > 1`, and :math:`\nu > 0`.
+
+    `studentized_range` takes ``k`` for :math:`k` and ``df`` for :math:`\nu`
+    as shape parameters.
+
+    When :math:`\nu` exceeds 100,000, an asymptotic approximation (infinite
+    degrees of freedom) is used to compute the cumulative distribution
+    function [4]_ and probability distribution function.
+
+    %(after_notes)s
+
+    References
+    ----------
+
+    .. [1] "Studentized range distribution",
+           https://en.wikipedia.org/wiki/Studentized_range_distribution
+    .. [2] Batista, Ben Dêivide, et al. "Externally Studentized Normal Midrange
+           Distribution." Ciência e Agrotecnologia, vol. 41, no. 4, 2017, pp.
+           378-389., doi:10.1590/1413-70542017414047716.
+    .. [3] Harter, H. Leon. "Tables of Range and Studentized Range." The Annals
+           of Mathematical Statistics, vol. 31, no. 4, 1960, pp. 1122-1147.
+           JSTOR, www.jstor.org/stable/2237810. Accessed 18 Feb. 2021.
+    .. [4] Lund, R. E., and J. R. Lund. "Algorithm AS 190: Probabilities and
+           Upper Quantiles for the Studentized Range." Journal of the Royal
+           Statistical Society. Series C (Applied Statistics), vol. 32, no. 2,
+           1983, pp. 204-210. JSTOR, www.jstor.org/stable/2347300. Accessed 18
+           Feb. 2021.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import studentized_range
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Display the probability density function (``pdf``):
+
+    >>> k, df = 3, 10
+    >>> x = np.linspace(studentized_range.ppf(0.01, k, df),
+    ...                 studentized_range.ppf(0.99, k, df), 100)
+    >>> ax.plot(x, studentized_range.pdf(x, k, df),
+    ...         'r-', lw=5, alpha=0.6, label='studentized_range pdf')
+
+    Alternatively, the distribution object can be called (as a function)
+    to fix the shape, location and scale parameters. This returns a "frozen"
+    RV object holding the given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pdf``:
+
+    >>> rv = studentized_range(k, df)
+    >>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+
+    Check accuracy of ``cdf`` and ``ppf``:
+
+    >>> vals = studentized_range.ppf([0.001, 0.5, 0.999], k, df)
+    >>> np.allclose([0.001, 0.5, 0.999], studentized_range.cdf(vals, k, df))
+    True
+
+    Rather than using (``studentized_range.rvs``) to generate random variates,
+    which is very slow for this distribution, we can approximate the inverse
+    CDF using an interpolator, and then perform inverse transform sampling
+    with this approximate inverse CDF.
+
+    This distribution has an infinite but thin right tail, so we focus our
+    attention on the leftmost 99.9 percent.
+
+    >>> a, b = studentized_range.ppf([0, .999], k, df)
+    >>> a, b
+    0, 7.41058083802274
+
+    >>> from scipy.interpolate import interp1d
+    >>> rng = np.random.default_rng()
+    >>> xs = np.linspace(a, b, 50)
+    >>> cdf = studentized_range.cdf(xs, k, df)
+    # Create an interpolant of the inverse CDF
+    >>> ppf = interp1d(cdf, xs, fill_value='extrapolate')
+    # Perform inverse transform sampling using the interpolant
+    >>> r = ppf(rng.uniform(size=1000))
+
+    And compare the histogram:
+
+    >>> ax.hist(r, density=True, histtype='stepfilled', alpha=0.2)
+    >>> ax.legend(loc='best', frameon=False)
+    >>> plt.show()
+
+    """
+
+    def _argcheck(self, k, df):
+        return (k > 1) & (df > 0)
+
+    def _shape_info(self):
+        ik = _ShapeInfo("k", False, (1, np.inf), (False, False))
+        idf = _ShapeInfo("df", False, (0, np.inf), (False, False))
+        return [ik, idf]
+
+    def _fitstart(self, data):
+        # Default is k=1, but that is not a valid value of the parameter.
+        return super()._fitstart(data, args=(2, 1))
+
+    def _munp(self, K, k, df):
+        cython_symbol = '_studentized_range_moment'
+        _a, _b = self._get_support()
+        # all three of these are used to create a numpy array so they must
+        # be the same shape.
+
+        def _single_moment(K, k, df):
+            log_const = _stats._studentized_range_pdf_logconst(k, df)
+            arg = [K, k, df, log_const]
+            usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+
+            llc = LowLevelCallable.from_cython(_stats, cython_symbol, usr_data)
+
+            ranges = [(-np.inf, np.inf), (0, np.inf), (_a, _b)]
+            opts = dict(epsabs=1e-11, epsrel=1e-12)
+
+            return integrate.nquad(llc, ranges=ranges, opts=opts)[0]
+
+        ufunc = np.frompyfunc(_single_moment, 3, 1)
+        return np.asarray(ufunc(K, k, df), dtype=np.float64)[()]
+
+    def _pdf(self, x, k, df):
+
+        def _single_pdf(q, k, df):
+            # The infinite form of the PDF is derived from the infinite
+            # CDF.
+            if df < 100000:
+                cython_symbol = '_studentized_range_pdf'
+                log_const = _stats._studentized_range_pdf_logconst(k, df)
+                arg = [q, k, df, log_const]
+                usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+                ranges = [(-np.inf, np.inf), (0, np.inf)]
+
+            else:
+                cython_symbol = '_studentized_range_pdf_asymptotic'
+                arg = [q, k]
+                usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+                ranges = [(-np.inf, np.inf)]
+
+            llc = LowLevelCallable.from_cython(_stats, cython_symbol, usr_data)
+            opts = dict(epsabs=1e-11, epsrel=1e-12)
+            return integrate.nquad(llc, ranges=ranges, opts=opts)[0]
+
+        ufunc = np.frompyfunc(_single_pdf, 3, 1)
+        return np.asarray(ufunc(x, k, df), dtype=np.float64)[()]
+
+    def _cdf(self, x, k, df):
+
+        def _single_cdf(q, k, df):
+            # "When the degrees of freedom V are infinite the probability
+            # integral takes [on a] simpler form," and a single asymptotic
+            # integral is evaluated rather than the standard double integral.
+            # (Lund, Lund, page 205)
+            if df < 100000:
+                cython_symbol = '_studentized_range_cdf'
+                log_const = _stats._studentized_range_cdf_logconst(k, df)
+                arg = [q, k, df, log_const]
+                usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+                ranges = [(-np.inf, np.inf), (0, np.inf)]
+
+            else:
+                cython_symbol = '_studentized_range_cdf_asymptotic'
+                arg = [q, k]
+                usr_data = np.array(arg, float).ctypes.data_as(ctypes.c_void_p)
+                ranges = [(-np.inf, np.inf)]
+
+            llc = LowLevelCallable.from_cython(_stats, cython_symbol, usr_data)
+            opts = dict(epsabs=1e-11, epsrel=1e-12)
+            return integrate.nquad(llc, ranges=ranges, opts=opts)[0]
+
+        ufunc = np.frompyfunc(_single_cdf, 3, 1)
+
+        # clip p-values to ensure they are in [0, 1].
+        return np.clip(np.asarray(ufunc(x, k, df), dtype=np.float64)[()], 0, 1)
+
+
+studentized_range = studentized_range_gen(name='studentized_range', a=0,
+                                          b=np.inf)
+
+
+class rel_breitwigner_gen(rv_continuous):
+    r"""A relativistic Breit-Wigner random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    cauchy: Cauchy distribution, also known as the Breit-Wigner distribution.
+
+    Notes
+    -----
+
+    The probability density function for `rel_breitwigner` is
+
+    .. math::
+
+        f(x, \rho) = \frac{k}{(x^2 - \rho^2)^2 + \rho^2}
+
+    where
+
+    .. math::
+        k = \frac{2\sqrt{2}\rho^2\sqrt{\rho^2 + 1}}
+            {\pi\sqrt{\rho^2 + \rho\sqrt{\rho^2 + 1}}}
+
+    The relativistic Breit-Wigner distribution is used in high energy physics
+    to model resonances [1]_. It gives the uncertainty in the invariant mass,
+    :math:`M` [2]_, of a resonance with characteristic mass :math:`M_0` and
+    decay-width :math:`\Gamma`, where :math:`M`, :math:`M_0` and :math:`\Gamma`
+    are expressed in natural units. In SciPy's parametrization, the shape
+    parameter :math:`\rho` is equal to :math:`M_0/\Gamma` and takes values in
+    :math:`(0, \infty)`.
+
+    Equivalently, the relativistic Breit-Wigner distribution is said to give
+    the uncertainty in the center-of-mass energy :math:`E_{\text{cm}}`. In
+    natural units, the speed of light :math:`c` is equal to 1 and the invariant
+    mass :math:`M` is equal to the rest energy :math:`Mc^2`. In the
+    center-of-mass frame, the rest energy is equal to the total energy [3]_.
+
+    %(after_notes)s
+
+    :math:`\rho = M/\Gamma` and :math:`\Gamma` is the scale parameter. For
+    example, if one seeks to model the :math:`Z^0` boson with :math:`M_0
+    \approx 91.1876 \text{ GeV}` and :math:`\Gamma \approx 2.4952\text{ GeV}`
+    [4]_ one can set ``rho=91.1876/2.4952`` and ``scale=2.4952``.
+
+    To ensure a physically meaningful result when using the `fit` method, one
+    should set ``floc=0`` to fix the location parameter to 0.
+
+    References
+    ----------
+    .. [1] Relativistic Breit-Wigner distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Relativistic_Breit-Wigner_distribution
+    .. [2] Invariant mass, Wikipedia,
+           https://en.wikipedia.org/wiki/Invariant_mass
+    .. [3] Center-of-momentum frame, Wikipedia,
+           https://en.wikipedia.org/wiki/Center-of-momentum_frame
+    .. [4] M. Tanabashi et al. (Particle Data Group) Phys. Rev. D 98, 030001 -
+           Published 17 August 2018
+
+    %(example)s
+
+    """
+    def _argcheck(self, rho):
+        return rho > 0
+
+    def _shape_info(self):
+        return [_ShapeInfo("rho", False, (0, np.inf), (False, False))]
+
+    def _pdf(self, x, rho):
+        # C = k / rho**2
+        C = np.sqrt(
+            2 * (1 + 1/rho**2) / (1 + np.sqrt(1 + 1/rho**2))
+        ) * 2 / np.pi
+        with np.errstate(over='ignore'):
+            return C / (((x - rho)*(x + rho)/rho)**2 + 1)
+
+    def _cdf(self, x, rho):
+        # C = k / (2 * rho**2) / np.sqrt(1 + 1/rho**2)
+        C = np.sqrt(2/(1 + np.sqrt(1 + 1/rho**2)))/np.pi
+        result = (
+            np.sqrt(-1 + 1j/rho)
+            * np.arctan(x/np.sqrt(-rho*(rho + 1j)))
+        )
+        result = C * 2 * np.imag(result)
+        # Sometimes above formula produces values greater than 1.
+        return np.clip(result, None, 1)
+
+    def _munp(self, n, rho):
+        if n == 0:
+            return 1.
+        if n == 1:
+            # C = k / (2 * rho)
+            C = np.sqrt(
+                2 * (1 + 1/rho**2) / (1 + np.sqrt(1 + 1/rho**2))
+            ) / np.pi * rho
+            return C * (np.pi/2 + np.arctan(rho))
+        if n == 2:
+            # C = pi * k / (4 * rho)
+            C = np.sqrt(
+                (1 + 1/rho**2) / (2 * (1 + np.sqrt(1 + 1/rho**2)))
+            ) * rho
+            result = (1 - rho * 1j) / np.sqrt(-1 - 1j/rho)
+            return 2 * C * np.real(result)
+        else:
+            return np.inf
+
+    def _stats(self, rho):
+        # Returning None from stats makes public stats use _munp.
+        # nan values will be omitted from public stats. Skew and
+        # kurtosis are actually infinite.
+        return None, None, np.nan, np.nan
+
+    @inherit_docstring_from(rv_continuous)
+    def fit(self, data, *args, **kwds):
+        # Override rv_continuous.fit to better handle case where floc is set.
+        data, _, floc, fscale = _check_fit_input_parameters(
+            self, data, args, kwds
+        )
+
+        censored = isinstance(data, CensoredData)
+        if censored:
+            if data.num_censored() == 0:
+                # There are no censored values in data, so replace the
+                # CensoredData instance with a regular array.
+                data = data._uncensored
+                censored = False
+
+        if floc is None or censored:
+            return super().fit(data, *args, **kwds)
+
+        if fscale is None:
+            # The interquartile range approximates the scale parameter gamma.
+            # The median approximates rho * gamma.
+            p25, p50, p75 = np.quantile(data - floc, [0.25, 0.5, 0.75])
+            scale_0 = p75 - p25
+            rho_0 = p50 / scale_0
+            if not args:
+                args = [rho_0]
+            if "scale" not in kwds:
+                kwds["scale"] = scale_0
+        else:
+            M_0 = np.median(data - floc)
+            rho_0 = M_0 / fscale
+            if not args:
+                args = [rho_0]
+        return super().fit(data, *args, **kwds)
+
+
+rel_breitwigner = rel_breitwigner_gen(a=0.0, name="rel_breitwigner")
+
+
+# Collect names of classes and objects in this module.
+pairs = list(globals().copy().items())
+_distn_names, _distn_gen_names = get_distribution_names(pairs, rv_continuous)
+
+__all__ = _distn_names + _distn_gen_names + ['rv_histogram']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_correlation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_correlation.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e47cd6180448c43e5f323ac003e80f1792c061b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_correlation.py
@@ -0,0 +1,210 @@
+import numpy as np
+from scipy import stats
+from scipy.stats._stats_py import _SimpleNormal, SignificanceResult, _get_pvalue
+from scipy.stats._axis_nan_policy import _axis_nan_policy_factory
+
+
+__all__ = ['chatterjeexi']
+
+
+# TODO:
+# - Adjust to respect dtype
+
+
+def _xi_statistic(x, y, y_continuous):
+    # Compute xi correlation statistic
+
+    # `axis=-1` is guaranteed by _axis_nan_policy decorator
+    n = x.shape[-1]
+
+    # "Rearrange the data as (X(1), Y(1)), . . . ,(X(n), Y(n))
+    # such that X(1) ≤ ··· ≤ X(n)"
+    j = np.argsort(x, axis=-1)
+    j, y = np.broadcast_arrays(j, y)
+    y = np.take_along_axis(y, j, axis=-1)
+
+    # "Let ri be the rank of Y(i), that is, the number of j such that Y(j) ≤ Y(i)"
+    r = stats.rankdata(y, method='max', axis=-1)
+    # " additionally define li to be the number of j such that Y(j) ≥ Y(i)"
+    # Could probably compute this from r, but that can be an enhancement
+    l = stats.rankdata(-y, method='max', axis=-1)
+
+    num = np.sum(np.abs(np.diff(r, axis=-1)), axis=-1)
+    if y_continuous:  # [1] Eq. 1.1
+        statistic = 1 - 3 * num / (n ** 2 - 1)
+    else:  # [1] Eq. 1.2
+        den = 2 * np.sum((n - l) * l, axis=-1)
+        statistic = 1 - n * num / den
+
+    return statistic, r, l
+
+
+def _xi_std(r, l, y_continuous):
+    # Compute asymptotic standard deviation of xi under null hypothesis of independence
+
+    # `axis=-1` is guaranteed by _axis_nan_policy decorator
+    n = np.float64(r.shape[-1])
+
+    # "Suppose that X and Y are independent and Y is continuous. Then
+    # √n·ξn(X, Y) → N(0, 2/5) in distribution as n → ∞"
+    if y_continuous:  # [1] Theorem 2.1
+        return np.sqrt(2 / 5) / np.sqrt(n)
+
+    # "Suppose that X and Y are independent. Then √n·ξn(X, Y)
+    # converges to N(0, τ²) in distribution as n → ∞
+    # [1] Eq. 2.2 and surrounding math
+    i = np.arange(1, n + 1)
+    u = np.sort(r, axis=-1)
+    v = np.cumsum(u, axis=-1)
+    an = 1 / n**4 * np.sum((2*n - 2*i + 1) * u**2, axis=-1)
+    bn = 1 / n**5 * np.sum((v + (n - i)*u)**2, axis=-1)
+    cn = 1 / n**3 * np.sum((2*n - 2*i + 1) * u, axis=-1)
+    dn = 1 / n**3 * np.sum((l * (n - l)), axis=-1)
+    tau2 = (an - 2*bn + cn**2) / dn**2
+
+    return np.sqrt(tau2) / np.sqrt(n)
+
+
+def _chatterjeexi_iv(y_continuous, method):
+    # Input validation for `chatterjeexi`
+    # x, y, `axis` input validation taken care of by decorator
+
+    if y_continuous not in {True, False}:
+        raise ValueError('`y_continuous` must be boolean.')
+
+    if not isinstance(method, stats.PermutationMethod):
+        method = method.lower()
+        message = "`method` must be 'asymptotic' or a `PermutationMethod` instance."
+        if method != 'asymptotic':
+            raise ValueError(message)
+
+    return y_continuous, method
+
+
+def _unpack(res):
+    return res.statistic, res.pvalue
+
+
+@_axis_nan_policy_factory(SignificanceResult, paired=True, n_samples=2,
+                          result_to_tuple=_unpack, n_outputs=2, too_small=1)
+def chatterjeexi(x, y, *, axis=0, y_continuous=False, method='asymptotic'):
+    r"""Compute the xi correlation and perform a test of independence
+
+    The xi correlation coefficient is a measure of association between two
+    variables; the value tends to be close to zero when the variables are
+    independent and close to 1 when there is a strong association. Unlike
+    other correlation coefficients, the xi correlation is effective even
+    when the association is not monotonic.
+
+    Parameters
+    ----------
+    x, y : array-like
+        The samples: corresponding observations of the independent and
+        dependent variable. The (N-d) arrays must be broadcastable.
+    axis : int, default: 0
+        Axis along which to perform the test.
+    method : 'asymptotic' or `PermutationMethod` instance, optional
+        Selects the method used to calculate the *p*-value.
+        Default is 'asymptotic'. The following options are available.
+
+        * ``'asymptotic'``: compares the standardized test statistic
+          against the normal distribution.
+        * `PermutationMethod` instance. In this case, the p-value
+          is computed using `permutation_test` with the provided
+          configuration options and other appropriate settings.
+
+    y_continuous : bool, default: False
+        Whether `y` is assumed to be drawn from a continuous distribution.
+        If `y` is drawn from a continuous distribution, results are valid
+        whether this is assumed or not, but enabling this assumption will
+        result in faster computation and typically produce similar results.
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+            The xi correlation statistic.
+        pvalue : float
+            The associated *p*-value: the probability of a statistic at least as
+            high as the observed value under the null hypothesis of independence.
+
+    See Also
+    --------
+    scipy.stats.pearsonr, scipy.stats.spearmanr, scipy.stats.kendalltau
+
+    Notes
+    -----
+    There is currently no special handling of ties in `x`; they are broken arbitrarily
+    by the implementation.
+
+    [1]_ notes that the statistic is not symmetric in `x` and `y` *by design*:
+    "...we may want to understand if :math:`Y` is a function :math:`X`, and not just
+    if one of the variables is a function of the other." See [1]_ Remark 1.
+
+    References
+    ----------
+    .. [1] Chatterjee, Sourav. "A new coefficient of correlation." Journal of
+           the American Statistical Association 116.536 (2021): 2009-2022.
+           :doi:`10.1080/01621459.2020.1758115`.
+
+    Examples
+    --------
+    Generate perfectly correlated data, and observe that the xi correlation is
+    nearly 1.0.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(348932549825235)
+    >>> x = rng.uniform(0, 10, size=100)
+    >>> y = np.sin(x)
+    >>> res = stats.chatterjeexi(x, y)
+    >>> res.statistic
+    np.float64(0.9012901290129013)
+
+    The probability of observing such a high value of the statistic under the
+    null hypothesis of independence is very low.
+
+    >>> res.pvalue
+    np.float64(2.2206974648177804e-46)
+
+    As noise is introduced, the correlation coefficient decreases.
+
+    >>> noise = rng.normal(scale=[[0.1], [0.5], [1]], size=(3, 100))
+    >>> res = stats.chatterjeexi(x, y + noise, axis=-1)
+    >>> res.statistic
+    array([0.79507951, 0.41824182, 0.16651665])
+
+    Because the distribution of `y` is continuous, it is valid to pass
+    ``y_continuous=True``. The statistic is identical, and the p-value
+    (not shown) is only slightly different.
+
+    >>> stats.chatterjeexi(x, y + noise, y_continuous=True, axis=-1).statistic
+    array([0.79507951, 0.41824182, 0.16651665])
+
+    """
+    # x, y, `axis` input validation taken care of by decorator
+    # In fact, `axis` is guaranteed to be -1
+    y_continuous, method = _chatterjeexi_iv(y_continuous, method)
+
+    # A highly negative statistic is possible, e.g.
+    # x = np.arange(100.), y = (x % 2 == 0)
+    # Unclear whether we should expose `alternative`, though.
+    alternative = 'greater'
+
+    if method == 'asymptotic':
+        xi, r, l = _xi_statistic(x, y, y_continuous)
+        std = _xi_std(r, l, y_continuous)
+        norm = _SimpleNormal()
+        pvalue = _get_pvalue(xi / std, norm, alternative=alternative)
+    elif isinstance(method, stats.PermutationMethod):
+        res = stats.permutation_test(
+            # Could be faster if we just permuted the ranks; for now, keep it simple.
+            data=(y,), statistic=lambda y, axis: _xi_statistic(x, y, y_continuous)[0],
+            alternative=alternative, permutation_type='pairings', **method._asdict(),
+            axis=-1)  # `axis=-1` is guaranteed by _axis_nan_policy decorator
+
+        xi, pvalue = res.statistic, res.pvalue
+
+    return SignificanceResult(xi, pvalue)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_covariance.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_covariance.py
new file mode 100644
index 0000000000000000000000000000000000000000..2dde85d0bac9c5f38e9a97ca71194132f3a865af
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_covariance.py
@@ -0,0 +1,633 @@
+from functools import cached_property
+
+import numpy as np
+from scipy import linalg
+from scipy.stats import _multivariate
+
+
+__all__ = ["Covariance"]
+
+
+class Covariance:
+    """
+    Representation of a covariance matrix
+
+    Calculations involving covariance matrices (e.g. data whitening,
+    multivariate normal function evaluation) are often performed more
+    efficiently using a decomposition of the covariance matrix instead of the
+    covariance matrix itself. This class allows the user to construct an
+    object representing a covariance matrix using any of several
+    decompositions and perform calculations using a common interface.
+
+    .. note::
+
+        The `Covariance` class cannot be instantiated directly. Instead, use
+        one of the factory methods (e.g. `Covariance.from_diagonal`).
+
+    Examples
+    --------
+    The `Covariance` class is used by calling one of its
+    factory methods to create a `Covariance` object, then pass that
+    representation of the `Covariance` matrix as a shape parameter of a
+    multivariate distribution.
+
+    For instance, the multivariate normal distribution can accept an array
+    representing a covariance matrix:
+
+    >>> from scipy import stats
+    >>> import numpy as np
+    >>> d = [1, 2, 3]
+    >>> A = np.diag(d)  # a diagonal covariance matrix
+    >>> x = [4, -2, 5]  # a point of interest
+    >>> dist = stats.multivariate_normal(mean=[0, 0, 0], cov=A)
+    >>> dist.pdf(x)
+    4.9595685102808205e-08
+
+    but the calculations are performed in a very generic way that does not
+    take advantage of any special properties of the covariance matrix. Because
+    our covariance matrix is diagonal, we can use ``Covariance.from_diagonal``
+    to create an object representing the covariance matrix, and
+    `multivariate_normal` can use this to compute the probability density
+    function more efficiently.
+
+    >>> cov = stats.Covariance.from_diagonal(d)
+    >>> dist = stats.multivariate_normal(mean=[0, 0, 0], cov=cov)
+    >>> dist.pdf(x)
+    4.9595685102808205e-08
+
+    """
+    def __init__(self):
+        message = ("The `Covariance` class cannot be instantiated directly. "
+                   "Please use one of the factory methods "
+                   "(e.g. `Covariance.from_diagonal`).")
+        raise NotImplementedError(message)
+
+    @staticmethod
+    def from_diagonal(diagonal):
+        r"""
+        Return a representation of a covariance matrix from its diagonal.
+
+        Parameters
+        ----------
+        diagonal : array_like
+            The diagonal elements of a diagonal matrix.
+
+        Notes
+        -----
+        Let the diagonal elements of a diagonal covariance matrix :math:`D` be
+        stored in the vector :math:`d`.
+
+        When all elements of :math:`d` are strictly positive, whitening of a
+        data point :math:`x` is performed by computing
+        :math:`x \cdot d^{-1/2}`, where the inverse square root can be taken
+        element-wise.
+        :math:`\log\det{D}` is calculated as :math:`-2 \sum(\log{d})`,
+        where the :math:`\log` operation is performed element-wise.
+
+        This `Covariance` class supports singular covariance matrices. When
+        computing ``_log_pdet``, non-positive elements of :math:`d` are
+        ignored. Whitening is not well defined when the point to be whitened
+        does not lie in the span of the columns of the covariance matrix. The
+        convention taken here is to treat the inverse square root of
+        non-positive elements of :math:`d` as zeros.
+
+        Examples
+        --------
+        Prepare a symmetric positive definite covariance matrix ``A`` and a
+        data point ``x``.
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 5
+        >>> A = np.diag(rng.random(n))
+        >>> x = rng.random(size=n)
+
+        Extract the diagonal from ``A`` and create the `Covariance` object.
+
+        >>> d = np.diag(A)
+        >>> cov = stats.Covariance.from_diagonal(d)
+
+        Compare the functionality of the `Covariance` object against a
+        reference implementations.
+
+        >>> res = cov.whiten(x)
+        >>> ref = np.diag(d**-0.5) @ x
+        >>> np.allclose(res, ref)
+        True
+        >>> res = cov.log_pdet
+        >>> ref = np.linalg.slogdet(A)[-1]
+        >>> np.allclose(res, ref)
+        True
+
+        """
+        return CovViaDiagonal(diagonal)
+
+    @staticmethod
+    def from_precision(precision, covariance=None):
+        r"""
+        Return a representation of a covariance from its precision matrix.
+
+        Parameters
+        ----------
+        precision : array_like
+            The precision matrix; that is, the inverse of a square, symmetric,
+            positive definite covariance matrix.
+        covariance : array_like, optional
+            The square, symmetric, positive definite covariance matrix. If not
+            provided, this may need to be calculated (e.g. to evaluate the
+            cumulative distribution function of
+            `scipy.stats.multivariate_normal`) by inverting `precision`.
+
+        Notes
+        -----
+        Let the covariance matrix be :math:`A`, its precision matrix be
+        :math:`P = A^{-1}`, and :math:`L` be the lower Cholesky factor such
+        that :math:`L L^T = P`.
+        Whitening of a data point :math:`x` is performed by computing
+        :math:`x^T L`. :math:`\log\det{A}` is calculated as
+        :math:`-2tr(\log{L})`, where the :math:`\log` operation is performed
+        element-wise.
+
+        This `Covariance` class does not support singular covariance matrices
+        because the precision matrix does not exist for a singular covariance
+        matrix.
+
+        Examples
+        --------
+        Prepare a symmetric positive definite precision matrix ``P`` and a
+        data point ``x``. (If the precision matrix is not already available,
+        consider the other factory methods of the `Covariance` class.)
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 5
+        >>> P = rng.random(size=(n, n))
+        >>> P = P @ P.T  # a precision matrix must be positive definite
+        >>> x = rng.random(size=n)
+
+        Create the `Covariance` object.
+
+        >>> cov = stats.Covariance.from_precision(P)
+
+        Compare the functionality of the `Covariance` object against
+        reference implementations.
+
+        >>> res = cov.whiten(x)
+        >>> ref = x @ np.linalg.cholesky(P)
+        >>> np.allclose(res, ref)
+        True
+        >>> res = cov.log_pdet
+        >>> ref = -np.linalg.slogdet(P)[-1]
+        >>> np.allclose(res, ref)
+        True
+
+        """
+        return CovViaPrecision(precision, covariance)
+
+    @staticmethod
+    def from_cholesky(cholesky):
+        r"""
+        Representation of a covariance provided via the (lower) Cholesky factor
+
+        Parameters
+        ----------
+        cholesky : array_like
+            The lower triangular Cholesky factor of the covariance matrix.
+
+        Notes
+        -----
+        Let the covariance matrix be :math:`A` and :math:`L` be the lower
+        Cholesky factor such that :math:`L L^T = A`.
+        Whitening of a data point :math:`x` is performed by computing
+        :math:`L^{-1} x`. :math:`\log\det{A}` is calculated as
+        :math:`2tr(\log{L})`, where the :math:`\log` operation is performed
+        element-wise.
+
+        This `Covariance` class does not support singular covariance matrices
+        because the Cholesky decomposition does not exist for a singular
+        covariance matrix.
+
+        Examples
+        --------
+        Prepare a symmetric positive definite covariance matrix ``A`` and a
+        data point ``x``.
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 5
+        >>> A = rng.random(size=(n, n))
+        >>> A = A @ A.T  # make the covariance symmetric positive definite
+        >>> x = rng.random(size=n)
+
+        Perform the Cholesky decomposition of ``A`` and create the
+        `Covariance` object.
+
+        >>> L = np.linalg.cholesky(A)
+        >>> cov = stats.Covariance.from_cholesky(L)
+
+        Compare the functionality of the `Covariance` object against
+        reference implementation.
+
+        >>> from scipy.linalg import solve_triangular
+        >>> res = cov.whiten(x)
+        >>> ref = solve_triangular(L, x, lower=True)
+        >>> np.allclose(res, ref)
+        True
+        >>> res = cov.log_pdet
+        >>> ref = np.linalg.slogdet(A)[-1]
+        >>> np.allclose(res, ref)
+        True
+
+        """
+        return CovViaCholesky(cholesky)
+
+    @staticmethod
+    def from_eigendecomposition(eigendecomposition):
+        r"""
+        Representation of a covariance provided via eigendecomposition
+
+        Parameters
+        ----------
+        eigendecomposition : sequence
+            A sequence (nominally a tuple) containing the eigenvalue and
+            eigenvector arrays as computed by `scipy.linalg.eigh` or
+            `numpy.linalg.eigh`.
+
+        Notes
+        -----
+        Let the covariance matrix be :math:`A`, let :math:`V` be matrix of
+        eigenvectors, and let :math:`W` be the diagonal matrix of eigenvalues
+        such that `V W V^T = A`.
+
+        When all of the eigenvalues are strictly positive, whitening of a
+        data point :math:`x` is performed by computing
+        :math:`x^T (V W^{-1/2})`, where the inverse square root can be taken
+        element-wise.
+        :math:`\log\det{A}` is calculated as  :math:`tr(\log{W})`,
+        where the :math:`\log` operation is performed element-wise.
+
+        This `Covariance` class supports singular covariance matrices. When
+        computing ``_log_pdet``, non-positive eigenvalues are ignored.
+        Whitening is not well defined when the point to be whitened
+        does not lie in the span of the columns of the covariance matrix. The
+        convention taken here is to treat the inverse square root of
+        non-positive eigenvalues as zeros.
+
+        Examples
+        --------
+        Prepare a symmetric positive definite covariance matrix ``A`` and a
+        data point ``x``.
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 5
+        >>> A = rng.random(size=(n, n))
+        >>> A = A @ A.T  # make the covariance symmetric positive definite
+        >>> x = rng.random(size=n)
+
+        Perform the eigendecomposition of ``A`` and create the `Covariance`
+        object.
+
+        >>> w, v = np.linalg.eigh(A)
+        >>> cov = stats.Covariance.from_eigendecomposition((w, v))
+
+        Compare the functionality of the `Covariance` object against
+        reference implementations.
+
+        >>> res = cov.whiten(x)
+        >>> ref = x @ (v @ np.diag(w**-0.5))
+        >>> np.allclose(res, ref)
+        True
+        >>> res = cov.log_pdet
+        >>> ref = np.linalg.slogdet(A)[-1]
+        >>> np.allclose(res, ref)
+        True
+
+        """
+        return CovViaEigendecomposition(eigendecomposition)
+
+    def whiten(self, x):
+        """
+        Perform a whitening transformation on data.
+
+        "Whitening" ("white" as in "white noise", in which each frequency has
+        equal magnitude) transforms a set of random variables into a new set of
+        random variables with unit-diagonal covariance. When a whitening
+        transform is applied to a sample of points distributed according to
+        a multivariate normal distribution with zero mean, the covariance of
+        the transformed sample is approximately the identity matrix.
+
+        Parameters
+        ----------
+        x : array_like
+            An array of points. The last dimension must correspond with the
+            dimensionality of the space, i.e., the number of columns in the
+            covariance matrix.
+
+        Returns
+        -------
+        x_ : array_like
+            The transformed array of points.
+
+        References
+        ----------
+        .. [1] "Whitening Transformation". Wikipedia.
+               https://en.wikipedia.org/wiki/Whitening_transformation
+        .. [2] Novak, Lukas, and Miroslav Vorechovsky. "Generalization of
+               coloring linear transformation". Transactions of VSB 18.2
+               (2018): 31-35. :doi:`10.31490/tces-2018-0013`
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng()
+        >>> n = 3
+        >>> A = rng.random(size=(n, n))
+        >>> cov_array = A @ A.T  # make matrix symmetric positive definite
+        >>> precision = np.linalg.inv(cov_array)
+        >>> cov_object = stats.Covariance.from_precision(precision)
+        >>> x = rng.multivariate_normal(np.zeros(n), cov_array, size=(10000))
+        >>> x_ = cov_object.whiten(x)
+        >>> np.cov(x_, rowvar=False)  # near-identity covariance
+        array([[0.97862122, 0.00893147, 0.02430451],
+               [0.00893147, 0.96719062, 0.02201312],
+               [0.02430451, 0.02201312, 0.99206881]])
+
+        """
+        return self._whiten(np.asarray(x))
+
+    def colorize(self, x):
+        """
+        Perform a colorizing transformation on data.
+
+        "Colorizing" ("color" as in "colored noise", in which different
+        frequencies may have different magnitudes) transforms a set of
+        uncorrelated random variables into a new set of random variables with
+        the desired covariance. When a coloring transform is applied to a
+        sample of points distributed according to a multivariate normal
+        distribution with identity covariance and zero mean, the covariance of
+        the transformed sample is approximately the covariance matrix used
+        in the coloring transform.
+
+        Parameters
+        ----------
+        x : array_like
+            An array of points. The last dimension must correspond with the
+            dimensionality of the space, i.e., the number of columns in the
+            covariance matrix.
+
+        Returns
+        -------
+        x_ : array_like
+            The transformed array of points.
+
+        References
+        ----------
+        .. [1] "Whitening Transformation". Wikipedia.
+               https://en.wikipedia.org/wiki/Whitening_transformation
+        .. [2] Novak, Lukas, and Miroslav Vorechovsky. "Generalization of
+               coloring linear transformation". Transactions of VSB 18.2
+               (2018): 31-35. :doi:`10.31490/tces-2018-0013`
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> rng = np.random.default_rng(1638083107694713882823079058616272161)
+        >>> n = 3
+        >>> A = rng.random(size=(n, n))
+        >>> cov_array = A @ A.T  # make matrix symmetric positive definite
+        >>> cholesky = np.linalg.cholesky(cov_array)
+        >>> cov_object = stats.Covariance.from_cholesky(cholesky)
+        >>> x = rng.multivariate_normal(np.zeros(n), np.eye(n), size=(10000))
+        >>> x_ = cov_object.colorize(x)
+        >>> cov_data = np.cov(x_, rowvar=False)
+        >>> np.allclose(cov_data, cov_array, rtol=3e-2)
+        True
+        """
+        return self._colorize(np.asarray(x))
+
+    @property
+    def log_pdet(self):
+        """
+        Log of the pseudo-determinant of the covariance matrix
+        """
+        return np.array(self._log_pdet, dtype=float)[()]
+
+    @property
+    def rank(self):
+        """
+        Rank of the covariance matrix
+        """
+        return np.array(self._rank, dtype=int)[()]
+
+    @property
+    def covariance(self):
+        """
+        Explicit representation of the covariance matrix
+        """
+        return self._covariance
+
+    @property
+    def shape(self):
+        """
+        Shape of the covariance array
+        """
+        return self._shape
+
+    def _validate_matrix(self, A, name):
+        A = np.atleast_2d(A)
+        m, n = A.shape[-2:]
+        if m != n or A.ndim != 2 or not (np.issubdtype(A.dtype, np.integer) or
+                                         np.issubdtype(A.dtype, np.floating)):
+            message = (f"The input `{name}` must be a square, "
+                       "two-dimensional array of real numbers.")
+            raise ValueError(message)
+        return A
+
+    def _validate_vector(self, A, name):
+        A = np.atleast_1d(A)
+        if A.ndim != 1 or not (np.issubdtype(A.dtype, np.integer) or
+                               np.issubdtype(A.dtype, np.floating)):
+            message = (f"The input `{name}` must be a one-dimensional array "
+                       "of real numbers.")
+            raise ValueError(message)
+        return A
+
+
+class CovViaPrecision(Covariance):
+
+    def __init__(self, precision, covariance=None):
+        precision = self._validate_matrix(precision, 'precision')
+        if covariance is not None:
+            covariance = self._validate_matrix(covariance, 'covariance')
+            message = "`precision.shape` must equal `covariance.shape`."
+            if precision.shape != covariance.shape:
+                raise ValueError(message)
+
+        self._chol_P = np.linalg.cholesky(precision)
+        self._log_pdet = -2*np.log(np.diag(self._chol_P)).sum(axis=-1)
+        self._rank = precision.shape[-1]  # must be full rank if invertible
+        self._precision = precision
+        self._cov_matrix = covariance
+        self._shape = precision.shape
+        self._allow_singular = False
+
+    def _whiten(self, x):
+        return x @ self._chol_P
+
+    @cached_property
+    def _covariance(self):
+        n = self._shape[-1]
+        return (linalg.cho_solve((self._chol_P, True), np.eye(n))
+                if self._cov_matrix is None else self._cov_matrix)
+
+    def _colorize(self, x):
+        return linalg.solve_triangular(self._chol_P.T, x.T, lower=False).T
+
+
+def _dot_diag(x, d):
+    # If d were a full diagonal matrix, x @ d would always do what we want.
+    # Special treatment is needed for n-dimensional `d` in which each row
+    # includes only the diagonal elements of a covariance matrix.
+    return x * d if x.ndim < 2 else x * np.expand_dims(d, -2)
+
+
+class CovViaDiagonal(Covariance):
+
+    def __init__(self, diagonal):
+        diagonal = self._validate_vector(diagonal, 'diagonal')
+
+        i_zero = diagonal <= 0
+        positive_diagonal = np.array(diagonal, dtype=np.float64)
+
+        positive_diagonal[i_zero] = 1  # ones don't affect determinant
+        self._log_pdet = np.sum(np.log(positive_diagonal), axis=-1)
+
+        psuedo_reciprocals = 1 / np.sqrt(positive_diagonal)
+        psuedo_reciprocals[i_zero] = 0
+
+        self._sqrt_diagonal = np.sqrt(diagonal)
+        self._LP = psuedo_reciprocals
+        self._rank = positive_diagonal.shape[-1] - i_zero.sum(axis=-1)
+        self._covariance = np.apply_along_axis(np.diag, -1, diagonal)
+        self._i_zero = i_zero
+        self._shape = self._covariance.shape
+        self._allow_singular = True
+
+    def _whiten(self, x):
+        return _dot_diag(x, self._LP)
+
+    def _colorize(self, x):
+        return _dot_diag(x, self._sqrt_diagonal)
+
+    def _support_mask(self, x):
+        """
+        Check whether x lies in the support of the distribution.
+        """
+        return ~np.any(_dot_diag(x, self._i_zero), axis=-1)
+
+
+class CovViaCholesky(Covariance):
+
+    def __init__(self, cholesky):
+        L = self._validate_matrix(cholesky, 'cholesky')
+
+        self._factor = L
+        self._log_pdet = 2*np.log(np.diag(self._factor)).sum(axis=-1)
+        self._rank = L.shape[-1]  # must be full rank for cholesky
+        self._shape = L.shape
+        self._allow_singular = False
+
+    @cached_property
+    def _covariance(self):
+        return self._factor @ self._factor.T
+
+    def _whiten(self, x):
+        res = linalg.solve_triangular(self._factor, x.T, lower=True).T
+        return res
+
+    def _colorize(self, x):
+        return x @ self._factor.T
+
+
+class CovViaEigendecomposition(Covariance):
+
+    def __init__(self, eigendecomposition):
+        eigenvalues, eigenvectors = eigendecomposition
+        eigenvalues = self._validate_vector(eigenvalues, 'eigenvalues')
+        eigenvectors = self._validate_matrix(eigenvectors, 'eigenvectors')
+        message = ("The shapes of `eigenvalues` and `eigenvectors` "
+                   "must be compatible.")
+        try:
+            eigenvalues = np.expand_dims(eigenvalues, -2)
+            eigenvectors, eigenvalues = np.broadcast_arrays(eigenvectors,
+                                                            eigenvalues)
+            eigenvalues = eigenvalues[..., 0, :]
+        except ValueError:
+            raise ValueError(message)
+
+        i_zero = eigenvalues <= 0
+        positive_eigenvalues = np.array(eigenvalues, dtype=np.float64)
+
+        positive_eigenvalues[i_zero] = 1  # ones don't affect determinant
+        self._log_pdet = np.sum(np.log(positive_eigenvalues), axis=-1)
+
+        psuedo_reciprocals = 1 / np.sqrt(positive_eigenvalues)
+        psuedo_reciprocals[i_zero] = 0
+
+        self._LP = eigenvectors * psuedo_reciprocals
+        self._LA = eigenvectors * np.sqrt(eigenvalues)
+        self._rank = positive_eigenvalues.shape[-1] - i_zero.sum(axis=-1)
+        self._w = eigenvalues
+        self._v = eigenvectors
+        self._shape = eigenvectors.shape
+        self._null_basis = eigenvectors * i_zero
+        # This is only used for `_support_mask`, not to decide whether
+        # the covariance is singular or not.
+        self._eps = _multivariate._eigvalsh_to_eps(eigenvalues) * 10**3
+        self._allow_singular = True
+
+    def _whiten(self, x):
+        return x @ self._LP
+
+    def _colorize(self, x):
+        return x @ self._LA.T
+
+    @cached_property
+    def _covariance(self):
+        return (self._v * self._w) @ self._v.T
+
+    def _support_mask(self, x):
+        """
+        Check whether x lies in the support of the distribution.
+        """
+        residual = np.linalg.norm(x @ self._null_basis, axis=-1)
+        in_support = residual < self._eps
+        return in_support
+
+
+class CovViaPSD(Covariance):
+    """
+    Representation of a covariance provided via an instance of _PSD
+    """
+
+    def __init__(self, psd):
+        self._LP = psd.U
+        self._log_pdet = psd.log_pdet
+        self._rank = psd.rank
+        self._covariance = psd._M
+        self._shape = psd._M.shape
+        self._psd = psd
+        self._allow_singular = False  # by default
+
+    def _whiten(self, x):
+        return x @ self._LP
+
+    def _support_mask(self, x):
+        return self._psd._support_mask(x)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_crosstab.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_crosstab.py
new file mode 100644
index 0000000000000000000000000000000000000000..e938eacad04467068985aacc7134248ab6ec44a6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_crosstab.py
@@ -0,0 +1,204 @@
+import numpy as np
+from scipy.sparse import coo_matrix
+from scipy._lib._bunch import _make_tuple_bunch
+
+
+CrosstabResult = _make_tuple_bunch(
+    "CrosstabResult", ["elements", "count"]
+)
+
+
+def crosstab(*args, levels=None, sparse=False):
+    """
+    Return table of counts for each possible unique combination in ``*args``.
+
+    When ``len(args) > 1``, the array computed by this function is
+    often referred to as a *contingency table* [1]_.
+
+    The arguments must be sequences with the same length.  The second return
+    value, `count`, is an integer array with ``len(args)`` dimensions.  If
+    `levels` is None, the shape of `count` is ``(n0, n1, ...)``, where ``nk``
+    is the number of unique elements in ``args[k]``.
+
+    Parameters
+    ----------
+    *args : sequences
+        A sequence of sequences whose unique aligned elements are to be
+        counted.  The sequences in args must all be the same length.
+    levels : sequence, optional
+        If `levels` is given, it must be a sequence that is the same length as
+        `args`.  Each element in `levels` is either a sequence or None.  If it
+        is a sequence, it gives the values in the corresponding sequence in
+        `args` that are to be counted.  If any value in the sequences in `args`
+        does not occur in the corresponding sequence in `levels`, that value
+        is ignored and not counted in the returned array `count`.  The default
+        value of `levels` for ``args[i]`` is ``np.unique(args[i])``
+    sparse : bool, optional
+        If True, return a sparse matrix.  The matrix will be an instance of
+        the `scipy.sparse.coo_matrix` class.  Because SciPy's sparse matrices
+        must be 2-d, only two input sequences are allowed when `sparse` is
+        True.  Default is False.
+
+    Returns
+    -------
+    res : CrosstabResult
+        An object containing the following attributes:
+
+        elements : tuple of numpy.ndarrays.
+            Tuple of length ``len(args)`` containing the arrays of elements
+            that are counted in `count`.  These can be interpreted as the
+            labels of the corresponding dimensions of `count`. If `levels` was
+            given, then if ``levels[i]`` is not None, ``elements[i]`` will
+            hold the values given in ``levels[i]``.
+        count : numpy.ndarray or scipy.sparse.coo_matrix
+            Counts of the unique elements in ``zip(*args)``, stored in an
+            array. Also known as a *contingency table* when ``len(args) > 1``.
+
+    See Also
+    --------
+    numpy.unique
+
+    Notes
+    -----
+    .. versionadded:: 1.7.0
+
+    References
+    ----------
+    .. [1] "Contingency table", http://en.wikipedia.org/wiki/Contingency_table
+
+    Examples
+    --------
+    >>> from scipy.stats.contingency import crosstab
+
+    Given the lists `a` and `x`, create a contingency table that counts the
+    frequencies of the corresponding pairs.
+
+    >>> a = ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B']
+    >>> x = ['X', 'X', 'X', 'Y', 'Z', 'Z', 'Y', 'Y', 'Z', 'Z']
+    >>> res = crosstab(a, x)
+    >>> avals, xvals = res.elements
+    >>> avals
+    array(['A', 'B'], dtype='>> xvals
+    array(['X', 'Y', 'Z'], dtype='>> res.count
+    array([[2, 3, 0],
+           [1, 0, 4]])
+
+    So ``('A', 'X')`` occurs twice, ``('A', 'Y')`` occurs three times, etc.
+
+    Higher dimensional contingency tables can be created.
+
+    >>> p = [0, 0, 0, 0, 1, 1, 1, 0, 0, 1]
+    >>> res = crosstab(a, x, p)
+    >>> res.count
+    array([[[2, 0],
+            [2, 1],
+            [0, 0]],
+           [[1, 0],
+            [0, 0],
+            [1, 3]]])
+    >>> res.count.shape
+    (2, 3, 2)
+
+    The values to be counted can be set by using the `levels` argument.
+    It allows the elements of interest in each input sequence to be
+    given explicitly instead finding the unique elements of the sequence.
+
+    For example, suppose one of the arguments is an array containing the
+    answers to a survey question, with integer values 1 to 4.  Even if the
+    value 1 does not occur in the data, we want an entry for it in the table.
+
+    >>> q1 = [2, 3, 3, 2, 4, 4, 2, 3, 4, 4, 4, 3, 3, 3, 4]  # 1 does not occur.
+    >>> q2 = [4, 4, 2, 2, 2, 4, 1, 1, 2, 2, 4, 2, 2, 2, 4]  # 3 does not occur.
+    >>> options = [1, 2, 3, 4]
+    >>> res = crosstab(q1, q2, levels=(options, options))
+    >>> res.count
+    array([[0, 0, 0, 0],
+           [1, 1, 0, 1],
+           [1, 4, 0, 1],
+           [0, 3, 0, 3]])
+
+    If `levels` is given, but an element of `levels` is None, the unique values
+    of the corresponding argument are used. For example,
+
+    >>> res = crosstab(q1, q2, levels=(None, options))
+    >>> res.elements
+    [array([2, 3, 4]), [1, 2, 3, 4]]
+    >>> res.count
+    array([[1, 1, 0, 1],
+           [1, 4, 0, 1],
+           [0, 3, 0, 3]])
+
+    If we want to ignore the pairs where 4 occurs in ``q2``, we can
+    give just the values [1, 2] to `levels`, and the 4 will be ignored:
+
+    >>> res = crosstab(q1, q2, levels=(None, [1, 2]))
+    >>> res.elements
+    [array([2, 3, 4]), [1, 2]]
+    >>> res.count
+    array([[1, 1],
+           [1, 4],
+           [0, 3]])
+
+    Finally, let's repeat the first example, but return a sparse matrix:
+
+    >>> res = crosstab(a, x, sparse=True)
+    >>> res.count
+    
+    >>> res.count.toarray()
+    array([[2, 3, 0],
+           [1, 0, 4]])
+
+    """
+    nargs = len(args)
+    if nargs == 0:
+        raise TypeError("At least one input sequence is required.")
+
+    len0 = len(args[0])
+    if not all(len(a) == len0 for a in args[1:]):
+        raise ValueError("All input sequences must have the same length.")
+
+    if sparse and nargs != 2:
+        raise ValueError("When `sparse` is True, only two input sequences "
+                         "are allowed.")
+
+    if levels is None:
+        # Call np.unique with return_inverse=True on each argument.
+        actual_levels, indices = zip(*[np.unique(a, return_inverse=True)
+                                       for a in args])
+    else:
+        # `levels` is not None...
+        if len(levels) != nargs:
+            raise ValueError('len(levels) must equal the number of input '
+                             'sequences')
+
+        args = [np.asarray(arg) for arg in args]
+        mask = np.zeros((nargs, len0), dtype=np.bool_)
+        inv = np.zeros((nargs, len0), dtype=np.intp)
+        actual_levels = []
+        for k, (levels_list, arg) in enumerate(zip(levels, args)):
+            if levels_list is None:
+                levels_list, inv[k, :] = np.unique(arg, return_inverse=True)
+                mask[k, :] = True
+            else:
+                q = arg == np.asarray(levels_list).reshape(-1, 1)
+                mask[k, :] = np.any(q, axis=0)
+                qnz = q.T.nonzero()
+                inv[k, qnz[0]] = qnz[1]
+            actual_levels.append(levels_list)
+
+        mask_all = mask.all(axis=0)
+        indices = tuple(inv[:, mask_all])
+
+    if sparse:
+        count = coo_matrix((np.ones(len(indices[0]), dtype=int),
+                            (indices[0], indices[1])))
+        count.sum_duplicates()
+    else:
+        shape = [len(u) for u in actual_levels]
+        count = np.zeros(shape, dtype=int)
+        np.add.at(count, indices, 1)
+
+    return CrosstabResult(actual_levels, count)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_discrete_distns.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_discrete_distns.py
new file mode 100644
index 0000000000000000000000000000000000000000..138c56d76a09591533268db35a9bd613f2a034f8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_discrete_distns.py
@@ -0,0 +1,2091 @@
+#
+# Author:  Travis Oliphant  2002-2011 with contributions from
+#          SciPy Developers 2004-2011
+#
+from functools import partial
+
+from scipy import special
+from scipy.special import entr, logsumexp, betaln, gammaln as gamln, zeta
+from scipy._lib._util import _lazywhere, rng_integers
+from scipy.interpolate import interp1d
+
+from numpy import floor, ceil, log, exp, sqrt, log1p, expm1, tanh, cosh, sinh
+
+import numpy as np
+
+from ._distn_infrastructure import (rv_discrete, get_distribution_names,
+                                    _vectorize_rvs_over_shapes,
+                                    _ShapeInfo, _isintegral,
+                                    rv_discrete_frozen)
+from ._biasedurn import (_PyFishersNCHypergeometric,
+                         _PyWalleniusNCHypergeometric,
+                         _PyStochasticLib3)
+from ._stats_pythran import _poisson_binom
+
+import scipy.special._ufuncs as scu
+
+
+
+class binom_gen(rv_discrete):
+    r"""A binomial discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `binom` is:
+
+    .. math::
+
+       f(k) = \binom{n}{k} p^k (1-p)^{n-k}
+
+    for :math:`k \in \{0, 1, \dots, n\}`, :math:`0 \leq p \leq 1`
+
+    `binom` takes :math:`n` and :math:`p` as shape parameters,
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pmf``, ``cdf``, ``sf``, ``ppf`` and ``isf``
+    methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    See Also
+    --------
+    hypergeom, nbinom, nhypergeom
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, n, p, size=None, random_state=None):
+        return random_state.binomial(n, p, size)
+
+    def _argcheck(self, n, p):
+        return (n >= 0) & _isintegral(n) & (p >= 0) & (p <= 1)
+
+    def _get_support(self, n, p):
+        return self.a, n
+
+    def _logpmf(self, x, n, p):
+        k = floor(x)
+        combiln = (gamln(n+1) - (gamln(k+1) + gamln(n-k+1)))
+        return combiln + special.xlogy(k, p) + special.xlog1py(n-k, -p)
+
+    def _pmf(self, x, n, p):
+        # binom.pmf(k) = choose(n, k) * p**k * (1-p)**(n-k)
+        return scu._binom_pmf(x, n, p)
+
+    def _cdf(self, x, n, p):
+        k = floor(x)
+        return scu._binom_cdf(k, n, p)
+
+    def _sf(self, x, n, p):
+        k = floor(x)
+        return scu._binom_sf(k, n, p)
+
+    def _isf(self, x, n, p):
+        return scu._binom_isf(x, n, p)
+
+    def _ppf(self, q, n, p):
+        return scu._binom_ppf(q, n, p)
+
+    def _stats(self, n, p, moments='mv'):
+        mu = n * p
+        var = mu - n * np.square(p)
+        g1, g2 = None, None
+        if 's' in moments:
+            pq = p - np.square(p)
+            npq_sqrt = np.sqrt(n * pq)
+            t1 = np.reciprocal(npq_sqrt)
+            t2 = (2.0 * p) / npq_sqrt
+            g1 = t1 - t2
+        if 'k' in moments:
+            pq = p - np.square(p)
+            npq = n * pq
+            t1 = np.reciprocal(npq)
+            t2 = 6.0/n
+            g2 = t1 - t2
+        return mu, var, g1, g2
+
+    def _entropy(self, n, p):
+        k = np.r_[0:n + 1]
+        vals = self._pmf(k, n, p)
+        return np.sum(entr(vals), axis=0)
+
+
+binom = binom_gen(name='binom')
+
+
+class bernoulli_gen(binom_gen):
+    r"""A Bernoulli discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `bernoulli` is:
+
+    .. math::
+
+       f(k) = \begin{cases}1-p  &\text{if } k = 0\\
+                           p    &\text{if } k = 1\end{cases}
+
+    for :math:`k` in :math:`\{0, 1\}`, :math:`0 \leq p \leq 1`
+
+    `bernoulli` takes :math:`p` as shape parameter,
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, p, size=None, random_state=None):
+        return binom_gen._rvs(self, 1, p, size=size, random_state=random_state)
+
+    def _argcheck(self, p):
+        return (p >= 0) & (p <= 1)
+
+    def _get_support(self, p):
+        # Overrides binom_gen._get_support!x
+        return self.a, self.b
+
+    def _logpmf(self, x, p):
+        return binom._logpmf(x, 1, p)
+
+    def _pmf(self, x, p):
+        # bernoulli.pmf(k) = 1-p  if k = 0
+        #                  = p    if k = 1
+        return binom._pmf(x, 1, p)
+
+    def _cdf(self, x, p):
+        return binom._cdf(x, 1, p)
+
+    def _sf(self, x, p):
+        return binom._sf(x, 1, p)
+
+    def _isf(self, x, p):
+        return binom._isf(x, 1, p)
+
+    def _ppf(self, q, p):
+        return binom._ppf(q, 1, p)
+
+    def _stats(self, p):
+        return binom._stats(1, p)
+
+    def _entropy(self, p):
+        return entr(p) + entr(1-p)
+
+
+bernoulli = bernoulli_gen(b=1, name='bernoulli')
+
+
+class betabinom_gen(rv_discrete):
+    r"""A beta-binomial discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The beta-binomial distribution is a binomial distribution with a
+    probability of success `p` that follows a beta distribution.
+
+    The probability mass function for `betabinom` is:
+
+    .. math::
+
+       f(k) = \binom{n}{k} \frac{B(k + a, n - k + b)}{B(a, b)}
+
+    for :math:`k \in \{0, 1, \dots, n\}`, :math:`n \geq 0`, :math:`a > 0`,
+    :math:`b > 0`, where :math:`B(a, b)` is the beta function.
+
+    `betabinom` takes :math:`n`, :math:`a`, and :math:`b` as shape parameters.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Beta-binomial_distribution
+
+    %(after_notes)s
+
+    .. versionadded:: 1.4.0
+
+    See Also
+    --------
+    beta, binom
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("a", False, (0, np.inf), (False, False)),
+                _ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, n, a, b, size=None, random_state=None):
+        p = random_state.beta(a, b, size)
+        return random_state.binomial(n, p, size)
+
+    def _get_support(self, n, a, b):
+        return 0, n
+
+    def _argcheck(self, n, a, b):
+        return (n >= 0) & _isintegral(n) & (a > 0) & (b > 0)
+
+    def _logpmf(self, x, n, a, b):
+        k = floor(x)
+        combiln = -log(n + 1) - betaln(n - k + 1, k + 1)
+        return combiln + betaln(k + a, n - k + b) - betaln(a, b)
+
+    def _pmf(self, x, n, a, b):
+        return exp(self._logpmf(x, n, a, b))
+
+    def _stats(self, n, a, b, moments='mv'):
+        e_p = a / (a + b)
+        e_q = 1 - e_p
+        mu = n * e_p
+        var = n * (a + b + n) * e_p * e_q / (a + b + 1)
+        g1, g2 = None, None
+        if 's' in moments:
+            g1 = 1.0 / sqrt(var)
+            g1 *= (a + b + 2 * n) * (b - a)
+            g1 /= (a + b + 2) * (a + b)
+        if 'k' in moments:
+            g2 = (a + b).astype(e_p.dtype)
+            g2 *= (a + b - 1 + 6 * n)
+            g2 += 3 * a * b * (n - 2)
+            g2 += 6 * n ** 2
+            g2 -= 3 * e_p * b * n * (6 - n)
+            g2 -= 18 * e_p * e_q * n ** 2
+            g2 *= (a + b) ** 2 * (1 + a + b)
+            g2 /= (n * a * b * (a + b + 2) * (a + b + 3) * (a + b + n))
+            g2 -= 3
+        return mu, var, g1, g2
+
+
+betabinom = betabinom_gen(name='betabinom')
+
+
+class nbinom_gen(rv_discrete):
+    r"""A negative binomial discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    Negative binomial distribution describes a sequence of i.i.d. Bernoulli
+    trials, repeated until a predefined, non-random number of successes occurs.
+
+    The probability mass function of the number of failures for `nbinom` is:
+
+    .. math::
+
+       f(k) = \binom{k+n-1}{n-1} p^n (1-p)^k
+
+    for :math:`k \ge 0`, :math:`0 < p \leq 1`
+
+    `nbinom` takes :math:`n` and :math:`p` as shape parameters where :math:`n`
+    is the number of successes, :math:`p` is the probability of a single
+    success, and :math:`1-p` is the probability of a single failure.
+
+    Another common parameterization of the negative binomial distribution is
+    in terms of the mean number of failures :math:`\mu` to achieve :math:`n`
+    successes. The mean :math:`\mu` is related to the probability of success
+    as
+
+    .. math::
+
+       p = \frac{n}{n + \mu}
+
+    The number of successes :math:`n` may also be specified in terms of a
+    "dispersion", "heterogeneity", or "aggregation" parameter :math:`\alpha`,
+    which relates the mean :math:`\mu` to the variance :math:`\sigma^2`,
+    e.g. :math:`\sigma^2 = \mu + \alpha \mu^2`. Regardless of the convention
+    used for :math:`\alpha`,
+
+    .. math::
+
+       p &= \frac{\mu}{\sigma^2} \\
+       n &= \frac{\mu^2}{\sigma^2 - \mu}
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pmf``, ``cdf``, ``sf``, ``ppf``, ``isf``
+    and ``stats`` methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    %(example)s
+
+    See Also
+    --------
+    hypergeom, binom, nhypergeom
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, n, p, size=None, random_state=None):
+        return random_state.negative_binomial(n, p, size)
+
+    def _argcheck(self, n, p):
+        return (n > 0) & (p > 0) & (p <= 1)
+
+    def _pmf(self, x, n, p):
+        # nbinom.pmf(k) = choose(k+n-1, n-1) * p**n * (1-p)**k
+        return scu._nbinom_pmf(x, n, p)
+
+    def _logpmf(self, x, n, p):
+        coeff = gamln(n+x) - gamln(x+1) - gamln(n)
+        return coeff + n*log(p) + special.xlog1py(x, -p)
+
+    def _cdf(self, x, n, p):
+        k = floor(x)
+        return scu._nbinom_cdf(k, n, p)
+
+    def _logcdf(self, x, n, p):
+        k = floor(x)
+        k, n, p = np.broadcast_arrays(k, n, p)
+        cdf = self._cdf(k, n, p)
+        cond = cdf > 0.5
+        def f1(k, n, p):
+            return np.log1p(-special.betainc(k + 1, n, 1 - p))
+
+        # do calc in place
+        logcdf = cdf
+        with np.errstate(divide='ignore'):
+            logcdf[cond] = f1(k[cond], n[cond], p[cond])
+            logcdf[~cond] = np.log(cdf[~cond])
+        return logcdf
+
+    def _sf(self, x, n, p):
+        k = floor(x)
+        return scu._nbinom_sf(k, n, p)
+
+    def _isf(self, x, n, p):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._nbinom_isf(x, n, p)
+
+    def _ppf(self, q, n, p):
+        with np.errstate(over='ignore'):  # see gh-17432
+            return scu._nbinom_ppf(q, n, p)
+
+    def _stats(self, n, p):
+        return (
+            scu._nbinom_mean(n, p),
+            scu._nbinom_variance(n, p),
+            scu._nbinom_skewness(n, p),
+            scu._nbinom_kurtosis_excess(n, p),
+        )
+
+
+nbinom = nbinom_gen(name='nbinom')
+
+
+class betanbinom_gen(rv_discrete):
+    r"""A beta-negative-binomial discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The beta-negative-binomial distribution is a negative binomial
+    distribution with a probability of success `p` that follows a
+    beta distribution.
+
+    The probability mass function for `betanbinom` is:
+
+    .. math::
+
+       f(k) = \binom{n + k - 1}{k} \frac{B(a + n, b + k)}{B(a, b)}
+
+    for :math:`k \ge 0`, :math:`n \geq 0`, :math:`a > 0`,
+    :math:`b > 0`, where :math:`B(a, b)` is the beta function.
+
+    `betanbinom` takes :math:`n`, :math:`a`, and :math:`b` as shape parameters.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Beta_negative_binomial_distribution
+
+    %(after_notes)s
+
+    .. versionadded:: 1.12.0
+
+    See Also
+    --------
+    betabinom : Beta binomial distribution
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("a", False, (0, np.inf), (False, False)),
+                _ShapeInfo("b", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, n, a, b, size=None, random_state=None):
+        p = random_state.beta(a, b, size)
+        return random_state.negative_binomial(n, p, size)
+
+    def _argcheck(self, n, a, b):
+        return (n >= 0) & _isintegral(n) & (a > 0) & (b > 0)
+
+    def _logpmf(self, x, n, a, b):
+        k = floor(x)
+        combiln = -np.log(n + k) - betaln(n, k + 1)
+        return combiln + betaln(a + n, b + k) - betaln(a, b)
+
+    def _pmf(self, x, n, a, b):
+        return exp(self._logpmf(x, n, a, b))
+
+    def _stats(self, n, a, b, moments='mv'):
+        # reference: Wolfram Alpha input
+        # BetaNegativeBinomialDistribution[a, b, n]
+        def mean(n, a, b):
+            return n * b / (a - 1.)
+        mu = _lazywhere(a > 1, (n, a, b), f=mean, fillvalue=np.inf)
+        def var(n, a, b):
+            return (n * b * (n + a - 1.) * (a + b - 1.)
+                    / ((a - 2.) * (a - 1.)**2.))
+        var = _lazywhere(a > 2, (n, a, b), f=var, fillvalue=np.inf)
+        g1, g2 = None, None
+        def skew(n, a, b):
+            return ((2 * n + a - 1.) * (2 * b + a - 1.)
+                    / (a - 3.) / sqrt(n * b * (n + a - 1.) * (b + a - 1.)
+                    / (a - 2.)))
+        if 's' in moments:
+            g1 = _lazywhere(a > 3, (n, a, b), f=skew, fillvalue=np.inf)
+        def kurtosis(n, a, b):
+            term = (a - 2.)
+            term_2 = ((a - 1.)**2. * (a**2. + a * (6 * b - 1.)
+                      + 6. * (b - 1.) * b)
+                      + 3. * n**2. * ((a + 5.) * b**2. + (a + 5.)
+                      * (a - 1.) * b + 2. * (a - 1.)**2)
+                      + 3 * (a - 1.) * n
+                      * ((a + 5.) * b**2. + (a + 5.) * (a - 1.) * b
+                      + 2. * (a - 1.)**2.))
+            denominator = ((a - 4.) * (a - 3.) * b * n
+                           * (a + b - 1.) * (a + n - 1.))
+            # Wolfram Alpha uses Pearson kurtosis, so we subtract 3 to get
+            # scipy's Fisher kurtosis
+            return term * term_2 / denominator - 3.
+        if 'k' in moments:
+            g2 = _lazywhere(a > 4, (n, a, b), f=kurtosis, fillvalue=np.inf)
+        return mu, var, g1, g2
+
+
+betanbinom = betanbinom_gen(name='betanbinom')
+
+
+class geom_gen(rv_discrete):
+    r"""A geometric discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `geom` is:
+
+    .. math::
+
+        f(k) = (1-p)^{k-1} p
+
+    for :math:`k \ge 1`, :math:`0 < p \leq 1`
+
+    `geom` takes :math:`p` as shape parameter,
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure.
+
+    Note that when drawing random samples, the probability of observations that exceed
+    ``np.iinfo(np.int64).max`` increases rapidly as $p$ decreases below $10^{-17}$. For
+    $p < 10^{-20}$, almost all observations would exceed the maximum ``int64``; however,
+    the output dtype is always ``int64``, so these values are clipped to the maximum.
+
+    %(after_notes)s
+
+    See Also
+    --------
+    planck
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, p, size=None, random_state=None):
+        res = random_state.geometric(p, size=size)
+        # RandomState.geometric can wrap around to negative values; make behavior
+        # consistent with Generator.geometric by replacing with maximum integer.
+        max_int = np.iinfo(res.dtype).max
+        return np.where(res < 0, max_int, res)
+
+    def _argcheck(self, p):
+        return (p <= 1) & (p > 0)
+
+    def _pmf(self, k, p):
+        return np.power(1-p, k-1) * p
+
+    def _logpmf(self, k, p):
+        return special.xlog1py(k - 1, -p) + log(p)
+
+    def _cdf(self, x, p):
+        k = floor(x)
+        return -expm1(log1p(-p)*k)
+
+    def _sf(self, x, p):
+        return np.exp(self._logsf(x, p))
+
+    def _logsf(self, x, p):
+        k = floor(x)
+        return k*log1p(-p)
+
+    def _ppf(self, q, p):
+        vals = ceil(log1p(-q) / log1p(-p))
+        temp = self._cdf(vals-1, p)
+        return np.where((temp >= q) & (vals > 0), vals-1, vals)
+
+    def _stats(self, p):
+        mu = 1.0/p
+        qr = 1.0-p
+        var = qr / p / p
+        g1 = (2.0-p) / sqrt(qr)
+        g2 = np.polyval([1, -6, 6], p)/(1.0-p)
+        return mu, var, g1, g2
+
+    def _entropy(self, p):
+        return -np.log(p) - np.log1p(-p) * (1.0-p) / p
+
+
+geom = geom_gen(a=1, name='geom', longname="A geometric")
+
+
+class hypergeom_gen(rv_discrete):
+    r"""A hypergeometric discrete random variable.
+
+    The hypergeometric distribution models drawing objects from a bin.
+    `M` is the total number of objects, `n` is total number of Type I objects.
+    The random variate represents the number of Type I objects in `N` drawn
+    without replacement from the total population.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The symbols used to denote the shape parameters (`M`, `n`, and `N`) are not
+    universally accepted.  See the Examples for a clarification of the
+    definitions used here.
+
+    The probability mass function is defined as,
+
+    .. math:: p(k, M, n, N) = \frac{\binom{n}{k} \binom{M - n}{N - k}}
+                                   {\binom{M}{N}}
+
+    for :math:`k \in [\max(0, N - M + n), \min(n, N)]`, where the binomial
+    coefficients are defined as,
+
+    .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
+
+    This distribution uses routines from the Boost Math C++ library for
+    the computation of the ``pmf``, ``cdf``, ``sf`` and ``stats`` methods. [1]_
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import hypergeom
+    >>> import matplotlib.pyplot as plt
+
+    Suppose we have a collection of 20 animals, of which 7 are dogs.  Then if
+    we want to know the probability of finding a given number of dogs if we
+    choose at random 12 of the 20 animals, we can initialize a frozen
+    distribution and plot the probability mass function:
+
+    >>> [M, n, N] = [20, 7, 12]
+    >>> rv = hypergeom(M, n, N)
+    >>> x = np.arange(0, n+1)
+    >>> pmf_dogs = rv.pmf(x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, pmf_dogs, 'bo')
+    >>> ax.vlines(x, 0, pmf_dogs, lw=2)
+    >>> ax.set_xlabel('# of dogs in our group of chosen animals')
+    >>> ax.set_ylabel('hypergeom PMF')
+    >>> plt.show()
+
+    Instead of using a frozen distribution we can also use `hypergeom`
+    methods directly.  To for example obtain the cumulative distribution
+    function, use:
+
+    >>> prb = hypergeom.cdf(x, M, n, N)
+
+    And to generate random numbers:
+
+    >>> R = hypergeom.rvs(M, n, N, size=10)
+
+    See Also
+    --------
+    nhypergeom, binom, nbinom
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
+                _ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("N", True, (0, np.inf), (True, False))]
+
+    def _rvs(self, M, n, N, size=None, random_state=None):
+        return random_state.hypergeometric(n, M-n, N, size=size)
+
+    def _get_support(self, M, n, N):
+        return np.maximum(N-(M-n), 0), np.minimum(n, N)
+
+    def _argcheck(self, M, n, N):
+        cond = (M > 0) & (n >= 0) & (N >= 0)
+        cond &= (n <= M) & (N <= M)
+        cond &= _isintegral(M) & _isintegral(n) & _isintegral(N)
+        return cond
+
+    def _logpmf(self, k, M, n, N):
+        tot, good = M, n
+        bad = tot - good
+        result = (betaln(good+1, 1) + betaln(bad+1, 1) + betaln(tot-N+1, N+1) -
+                  betaln(k+1, good-k+1) - betaln(N-k+1, bad-N+k+1) -
+                  betaln(tot+1, 1))
+        return result
+
+    def _pmf(self, k, M, n, N):
+        return scu._hypergeom_pmf(k, n, N, M)
+
+    def _cdf(self, k, M, n, N):
+        return scu._hypergeom_cdf(k, n, N, M)
+
+    def _stats(self, M, n, N):
+        M, n, N = 1. * M, 1. * n, 1. * N
+        m = M - n
+
+        # Boost kurtosis_excess doesn't return the same as the value
+        # computed here.
+        g2 = M * (M + 1) - 6. * N * (M - N) - 6. * n * m
+        g2 *= (M - 1) * M * M
+        g2 += 6. * n * N * (M - N) * m * (5. * M - 6)
+        g2 /= n * N * (M - N) * m * (M - 2.) * (M - 3.)
+        return (
+            scu._hypergeom_mean(n, N, M),
+            scu._hypergeom_variance(n, N, M),
+            scu._hypergeom_skewness(n, N, M),
+            g2,
+        )
+
+    def _entropy(self, M, n, N):
+        k = np.r_[N - (M - n):min(n, N) + 1]
+        vals = self.pmf(k, M, n, N)
+        return np.sum(entr(vals), axis=0)
+
+    def _sf(self, k, M, n, N):
+        return scu._hypergeom_sf(k, n, N, M)
+
+    def _logsf(self, k, M, n, N):
+        res = []
+        for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)):
+            if (quant + 0.5) * (tot + 0.5) < (good - 0.5) * (draw - 0.5):
+                # Less terms to sum if we calculate log(1-cdf)
+                res.append(log1p(-exp(self.logcdf(quant, tot, good, draw))))
+            else:
+                # Integration over probability mass function using logsumexp
+                k2 = np.arange(quant + 1, draw + 1)
+                res.append(logsumexp(self._logpmf(k2, tot, good, draw)))
+        return np.asarray(res)
+
+    def _logcdf(self, k, M, n, N):
+        res = []
+        for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)):
+            if (quant + 0.5) * (tot + 0.5) > (good - 0.5) * (draw - 0.5):
+                # Less terms to sum if we calculate log(1-sf)
+                res.append(log1p(-exp(self.logsf(quant, tot, good, draw))))
+            else:
+                # Integration over probability mass function using logsumexp
+                k2 = np.arange(0, quant + 1)
+                res.append(logsumexp(self._logpmf(k2, tot, good, draw)))
+        return np.asarray(res)
+
+
+hypergeom = hypergeom_gen(name='hypergeom')
+
+
+class nhypergeom_gen(rv_discrete):
+    r"""A negative hypergeometric discrete random variable.
+
+    Consider a box containing :math:`M` balls:, :math:`n` red and
+    :math:`M-n` blue. We randomly sample balls from the box, one
+    at a time and *without* replacement, until we have picked :math:`r`
+    blue balls. `nhypergeom` is the distribution of the number of
+    red balls :math:`k` we have picked.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The symbols used to denote the shape parameters (`M`, `n`, and `r`) are not
+    universally accepted. See the Examples for a clarification of the
+    definitions used here.
+
+    The probability mass function is defined as,
+
+    .. math:: f(k; M, n, r) = \frac{{{k+r-1}\choose{k}}{{M-r-k}\choose{n-k}}}
+                                   {{M \choose n}}
+
+    for :math:`k \in [0, n]`, :math:`n \in [0, M]`, :math:`r \in [0, M-n]`,
+    and the binomial coefficient is:
+
+    .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
+
+    It is equivalent to observing :math:`k` successes in :math:`k+r-1`
+    samples with :math:`k+r`'th sample being a failure. The former
+    can be modelled as a hypergeometric distribution. The probability
+    of the latter is simply the number of failures remaining
+    :math:`M-n-(r-1)` divided by the size of the remaining population
+    :math:`M-(k+r-1)`. This relationship can be shown as:
+
+    .. math:: NHG(k;M,n,r) = HG(k;M,n,k+r-1)\frac{(M-n-(r-1))}{(M-(k+r-1))}
+
+    where :math:`NHG` is probability mass function (PMF) of the
+    negative hypergeometric distribution and :math:`HG` is the
+    PMF of the hypergeometric distribution.
+
+    %(after_notes)s
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import nhypergeom
+    >>> import matplotlib.pyplot as plt
+
+    Suppose we have a collection of 20 animals, of which 7 are dogs.
+    Then if we want to know the probability of finding a given number
+    of dogs (successes) in a sample with exactly 12 animals that
+    aren't dogs (failures), we can initialize a frozen distribution
+    and plot the probability mass function:
+
+    >>> M, n, r = [20, 7, 12]
+    >>> rv = nhypergeom(M, n, r)
+    >>> x = np.arange(0, n+2)
+    >>> pmf_dogs = rv.pmf(x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, pmf_dogs, 'bo')
+    >>> ax.vlines(x, 0, pmf_dogs, lw=2)
+    >>> ax.set_xlabel('# of dogs in our group with given 12 failures')
+    >>> ax.set_ylabel('nhypergeom PMF')
+    >>> plt.show()
+
+    Instead of using a frozen distribution we can also use `nhypergeom`
+    methods directly.  To for example obtain the probability mass
+    function, use:
+
+    >>> prb = nhypergeom.pmf(x, M, n, r)
+
+    And to generate random numbers:
+
+    >>> R = nhypergeom.rvs(M, n, r, size=10)
+
+    To verify the relationship between `hypergeom` and `nhypergeom`, use:
+
+    >>> from scipy.stats import hypergeom, nhypergeom
+    >>> M, n, r = 45, 13, 8
+    >>> k = 6
+    >>> nhypergeom.pmf(k, M, n, r)
+    0.06180776620271643
+    >>> hypergeom.pmf(k, M, n, k+r-1) * (M - n - (r-1)) / (M - (k+r-1))
+    0.06180776620271644
+
+    See Also
+    --------
+    hypergeom, binom, nbinom
+
+    References
+    ----------
+    .. [1] Negative Hypergeometric Distribution on Wikipedia
+           https://en.wikipedia.org/wiki/Negative_hypergeometric_distribution
+
+    .. [2] Negative Hypergeometric Distribution from
+           http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Negativehypergeometric.pdf
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
+                _ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("r", True, (0, np.inf), (True, False))]
+
+    def _get_support(self, M, n, r):
+        return 0, n
+
+    def _argcheck(self, M, n, r):
+        cond = (n >= 0) & (n <= M) & (r >= 0) & (r <= M-n)
+        cond &= _isintegral(M) & _isintegral(n) & _isintegral(r)
+        return cond
+
+    def _rvs(self, M, n, r, size=None, random_state=None):
+
+        @_vectorize_rvs_over_shapes
+        def _rvs1(M, n, r, size, random_state):
+            # invert cdf by calculating all values in support, scalar M, n, r
+            a, b = self.support(M, n, r)
+            ks = np.arange(a, b+1)
+            cdf = self.cdf(ks, M, n, r)
+            ppf = interp1d(cdf, ks, kind='next', fill_value='extrapolate')
+            rvs = ppf(random_state.uniform(size=size)).astype(int)
+            if size is None:
+                return rvs.item()
+            return rvs
+
+        return _rvs1(M, n, r, size=size, random_state=random_state)
+
+    def _logpmf(self, k, M, n, r):
+        cond = ((r == 0) & (k == 0))
+        result = _lazywhere(~cond, (k, M, n, r),
+                            lambda k, M, n, r:
+                                (-betaln(k+1, r) + betaln(k+r, 1) -
+                                 betaln(n-k+1, M-r-n+1) + betaln(M-r-k+1, 1) +
+                                 betaln(n+1, M-n+1) - betaln(M+1, 1)),
+                            fillvalue=0.0)
+        return result
+
+    def _pmf(self, k, M, n, r):
+        # same as the following but numerically more precise
+        # return comb(k+r-1, k) * comb(M-r-k, n-k) / comb(M, n)
+        return exp(self._logpmf(k, M, n, r))
+
+    def _stats(self, M, n, r):
+        # Promote the datatype to at least float
+        # mu = rn / (M-n+1)
+        M, n, r = 1.*M, 1.*n, 1.*r
+        mu = r*n / (M-n+1)
+
+        var = r*(M+1)*n / ((M-n+1)*(M-n+2)) * (1 - r / (M-n+1))
+
+        # The skew and kurtosis are mathematically
+        # intractable so return `None`. See [2]_.
+        g1, g2 = None, None
+        return mu, var, g1, g2
+
+
+nhypergeom = nhypergeom_gen(name='nhypergeom')
+
+
+# FIXME: Fails _cdfvec
+class logser_gen(rv_discrete):
+    r"""A Logarithmic (Log-Series, Series) discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `logser` is:
+
+    .. math::
+
+        f(k) = - \frac{p^k}{k \log(1-p)}
+
+    for :math:`k \ge 1`, :math:`0 < p < 1`
+
+    `logser` takes :math:`p` as shape parameter,
+    where :math:`p` is the probability of a single success
+    and :math:`1-p` is the probability of a single failure.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("p", False, (0, 1), (True, True))]
+
+    def _rvs(self, p, size=None, random_state=None):
+        # looks wrong for p>0.5, too few k=1
+        # trying to use generic is worse, no k=1 at all
+        return random_state.logseries(p, size=size)
+
+    def _argcheck(self, p):
+        return (p > 0) & (p < 1)
+
+    def _pmf(self, k, p):
+        # logser.pmf(k) = - p**k / (k*log(1-p))
+        return -np.power(p, k) * 1.0 / k / special.log1p(-p)
+
+    def _stats(self, p):
+        r = special.log1p(-p)
+        mu = p / (p - 1.0) / r
+        mu2p = -p / r / (p - 1.0)**2
+        var = mu2p - mu*mu
+        mu3p = -p / r * (1.0+p) / (1.0 - p)**3
+        mu3 = mu3p - 3*mu*mu2p + 2*mu**3
+        g1 = mu3 / np.power(var, 1.5)
+
+        mu4p = -p / r * (
+            1.0 / (p-1)**2 - 6*p / (p - 1)**3 + 6*p*p / (p-1)**4)
+        mu4 = mu4p - 4*mu3p*mu + 6*mu2p*mu*mu - 3*mu**4
+        g2 = mu4 / var**2 - 3.0
+        return mu, var, g1, g2
+
+
+logser = logser_gen(a=1, name='logser', longname='A logarithmic')
+
+
+class poisson_gen(rv_discrete):
+    r"""A Poisson discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `poisson` is:
+
+    .. math::
+
+        f(k) = \exp(-\mu) \frac{\mu^k}{k!}
+
+    for :math:`k \ge 0`.
+
+    `poisson` takes :math:`\mu \geq 0` as shape parameter.
+    When :math:`\mu = 0`, the ``pmf`` method
+    returns ``1.0`` at quantile :math:`k = 0`.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("mu", False, (0, np.inf), (True, False))]
+
+    # Override rv_discrete._argcheck to allow mu=0.
+    def _argcheck(self, mu):
+        return mu >= 0
+
+    def _rvs(self, mu, size=None, random_state=None):
+        return random_state.poisson(mu, size)
+
+    def _logpmf(self, k, mu):
+        Pk = special.xlogy(k, mu) - gamln(k + 1) - mu
+        return Pk
+
+    def _pmf(self, k, mu):
+        # poisson.pmf(k) = exp(-mu) * mu**k / k!
+        return exp(self._logpmf(k, mu))
+
+    def _cdf(self, x, mu):
+        k = floor(x)
+        return special.pdtr(k, mu)
+
+    def _sf(self, x, mu):
+        k = floor(x)
+        return special.pdtrc(k, mu)
+
+    def _ppf(self, q, mu):
+        vals = ceil(special.pdtrik(q, mu))
+        vals1 = np.maximum(vals - 1, 0)
+        temp = special.pdtr(vals1, mu)
+        return np.where(temp >= q, vals1, vals)
+
+    def _stats(self, mu):
+        var = mu
+        tmp = np.asarray(mu)
+        mu_nonzero = tmp > 0
+        g1 = _lazywhere(mu_nonzero, (tmp,), lambda x: sqrt(1.0/x), np.inf)
+        g2 = _lazywhere(mu_nonzero, (tmp,), lambda x: 1.0/x, np.inf)
+        return mu, var, g1, g2
+
+
+poisson = poisson_gen(name="poisson", longname='A Poisson')
+
+
+class planck_gen(rv_discrete):
+    r"""A Planck discrete exponential random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `planck` is:
+
+    .. math::
+
+        f(k) = (1-\exp(-\lambda)) \exp(-\lambda k)
+
+    for :math:`k \ge 0` and :math:`\lambda > 0`.
+
+    `planck` takes :math:`\lambda` as shape parameter. The Planck distribution
+    can be written as a geometric distribution (`geom`) with
+    :math:`p = 1 - \exp(-\lambda)` shifted by ``loc = -1``.
+
+    %(after_notes)s
+
+    See Also
+    --------
+    geom
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("lambda", False, (0, np.inf), (False, False))]
+
+    def _argcheck(self, lambda_):
+        return lambda_ > 0
+
+    def _pmf(self, k, lambda_):
+        return -expm1(-lambda_)*exp(-lambda_*k)
+
+    def _cdf(self, x, lambda_):
+        k = floor(x)
+        return -expm1(-lambda_*(k+1))
+
+    def _sf(self, x, lambda_):
+        return exp(self._logsf(x, lambda_))
+
+    def _logsf(self, x, lambda_):
+        k = floor(x)
+        return -lambda_*(k+1)
+
+    def _ppf(self, q, lambda_):
+        vals = ceil(-1.0/lambda_ * log1p(-q)-1)
+        vals1 = (vals-1).clip(*(self._get_support(lambda_)))
+        temp = self._cdf(vals1, lambda_)
+        return np.where(temp >= q, vals1, vals)
+
+    def _rvs(self, lambda_, size=None, random_state=None):
+        # use relation to geometric distribution for sampling
+        p = -expm1(-lambda_)
+        return random_state.geometric(p, size=size) - 1.0
+
+    def _stats(self, lambda_):
+        mu = 1/expm1(lambda_)
+        var = exp(-lambda_)/(expm1(-lambda_))**2
+        g1 = 2*cosh(lambda_/2.0)
+        g2 = 4+2*cosh(lambda_)
+        return mu, var, g1, g2
+
+    def _entropy(self, lambda_):
+        C = -expm1(-lambda_)
+        return lambda_*exp(-lambda_)/C - log(C)
+
+
+planck = planck_gen(a=0, name='planck', longname='A discrete exponential ')
+
+
+class boltzmann_gen(rv_discrete):
+    r"""A Boltzmann (Truncated Discrete Exponential) random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `boltzmann` is:
+
+    .. math::
+
+        f(k) = (1-\exp(-\lambda)) \exp(-\lambda k) / (1-\exp(-\lambda N))
+
+    for :math:`k = 0,..., N-1`.
+
+    `boltzmann` takes :math:`\lambda > 0` and :math:`N > 0` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("lambda_", False, (0, np.inf), (False, False)),
+                _ShapeInfo("N", True, (0, np.inf), (False, False))]
+
+    def _argcheck(self, lambda_, N):
+        return (lambda_ > 0) & (N > 0) & _isintegral(N)
+
+    def _get_support(self, lambda_, N):
+        return self.a, N - 1
+
+    def _pmf(self, k, lambda_, N):
+        # boltzmann.pmf(k) =
+        #               (1-exp(-lambda_)*exp(-lambda_*k)/(1-exp(-lambda_*N))
+        fact = (1-exp(-lambda_))/(1-exp(-lambda_*N))
+        return fact*exp(-lambda_*k)
+
+    def _cdf(self, x, lambda_, N):
+        k = floor(x)
+        return (1-exp(-lambda_*(k+1)))/(1-exp(-lambda_*N))
+
+    def _ppf(self, q, lambda_, N):
+        qnew = q*(1-exp(-lambda_*N))
+        vals = ceil(-1.0/lambda_ * log(1-qnew)-1)
+        vals1 = (vals-1).clip(0.0, np.inf)
+        temp = self._cdf(vals1, lambda_, N)
+        return np.where(temp >= q, vals1, vals)
+
+    def _stats(self, lambda_, N):
+        z = exp(-lambda_)
+        zN = exp(-lambda_*N)
+        mu = z/(1.0-z)-N*zN/(1-zN)
+        var = z/(1.0-z)**2 - N*N*zN/(1-zN)**2
+        trm = (1-zN)/(1-z)
+        trm2 = (z*trm**2 - N*N*zN)
+        g1 = z*(1+z)*trm**3 - N**3*zN*(1+zN)
+        g1 = g1 / trm2**(1.5)
+        g2 = z*(1+4*z+z*z)*trm**4 - N**4 * zN*(1+4*zN+zN*zN)
+        g2 = g2 / trm2 / trm2
+        return mu, var, g1, g2
+
+
+boltzmann = boltzmann_gen(name='boltzmann', a=0,
+                          longname='A truncated discrete exponential ')
+
+
+class randint_gen(rv_discrete):
+    r"""A uniform discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `randint` is:
+
+    .. math::
+
+        f(k) = \frac{1}{\texttt{high} - \texttt{low}}
+
+    for :math:`k \in \{\texttt{low}, \dots, \texttt{high} - 1\}`.
+
+    `randint` takes :math:`\texttt{low}` and :math:`\texttt{high}` as shape
+    parameters.
+
+    %(after_notes)s
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import randint
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+
+    Calculate the first four moments:
+
+    >>> low, high = 7, 31
+    >>> mean, var, skew, kurt = randint.stats(low, high, moments='mvsk')
+
+    Display the probability mass function (``pmf``):
+
+    >>> x = np.arange(low - 5, high + 5)
+    >>> ax.plot(x, randint.pmf(x, low, high), 'bo', ms=8, label='randint pmf')
+    >>> ax.vlines(x, 0, randint.pmf(x, low, high), colors='b', lw=5, alpha=0.5)
+
+    Alternatively, the distribution object can be called (as a function) to
+    fix the shape and location. This returns a "frozen" RV object holding the
+    given parameters fixed.
+
+    Freeze the distribution and display the frozen ``pmf``:
+
+    >>> rv = randint(low, high)
+    >>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-',
+    ...           lw=1, label='frozen pmf')
+    >>> ax.legend(loc='lower center')
+    >>> plt.show()
+
+    Check the relationship between the cumulative distribution function
+    (``cdf``) and its inverse, the percent point function (``ppf``):
+
+    >>> q = np.arange(low, high)
+    >>> p = randint.cdf(q, low, high)
+    >>> np.allclose(q, randint.ppf(p, low, high))
+    True
+
+    Generate random numbers:
+
+    >>> r = randint.rvs(low, high, size=1000)
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("low", True, (-np.inf, np.inf), (False, False)),
+                _ShapeInfo("high", True, (-np.inf, np.inf), (False, False))]
+
+    def _argcheck(self, low, high):
+        return (high > low) & _isintegral(low) & _isintegral(high)
+
+    def _get_support(self, low, high):
+        return low, high-1
+
+    def _pmf(self, k, low, high):
+        # randint.pmf(k) = 1./(high - low)
+        p = np.ones_like(k) / (np.asarray(high, dtype=np.int64) - low)
+        return np.where((k >= low) & (k < high), p, 0.)
+
+    def _cdf(self, x, low, high):
+        k = floor(x)
+        return (k - low + 1.) / (high - low)
+
+    def _ppf(self, q, low, high):
+        vals = ceil(q * (high - low) + low) - 1
+        vals1 = (vals - 1).clip(low, high)
+        temp = self._cdf(vals1, low, high)
+        return np.where(temp >= q, vals1, vals)
+
+    def _stats(self, low, high):
+        m2, m1 = np.asarray(high), np.asarray(low)
+        mu = (m2 + m1 - 1.0) / 2
+        d = m2 - m1
+        var = (d*d - 1) / 12.0
+        g1 = 0.0
+        g2 = -6.0/5.0 * (d*d + 1.0) / (d*d - 1.0)
+        return mu, var, g1, g2
+
+    def _rvs(self, low, high, size=None, random_state=None):
+        """An array of *size* random integers >= ``low`` and < ``high``."""
+        if np.asarray(low).size == 1 and np.asarray(high).size == 1:
+            # no need to vectorize in that case
+            return rng_integers(random_state, low, high, size=size)
+
+        if size is not None:
+            # NumPy's RandomState.randint() doesn't broadcast its arguments.
+            # Use `broadcast_to()` to extend the shapes of low and high
+            # up to size.  Then we can use the numpy.vectorize'd
+            # randint without needing to pass it a `size` argument.
+            low = np.broadcast_to(low, size)
+            high = np.broadcast_to(high, size)
+        randint = np.vectorize(partial(rng_integers, random_state),
+                               otypes=[np.dtype(int)])
+        return randint(low, high)
+
+    def _entropy(self, low, high):
+        return log(high - low)
+
+
+randint = randint_gen(name='randint', longname='A discrete uniform '
+                      '(random integer)')
+
+
+# FIXME: problems sampling.
+class zipf_gen(rv_discrete):
+    r"""A Zipf (Zeta) discrete random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    zipfian
+
+    Notes
+    -----
+    The probability mass function for `zipf` is:
+
+    .. math::
+
+        f(k, a) = \frac{1}{\zeta(a) k^a}
+
+    for :math:`k \ge 1`, :math:`a > 1`.
+
+    `zipf` takes :math:`a > 1` as shape parameter. :math:`\zeta` is the
+    Riemann zeta function (`scipy.special.zeta`)
+
+    The Zipf distribution is also known as the zeta distribution, which is
+    a special case of the Zipfian distribution (`zipfian`).
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Zeta Distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Zeta_distribution
+
+    %(example)s
+
+    Confirm that `zipf` is the large `n` limit of `zipfian`.
+
+    >>> import numpy as np
+    >>> from scipy.stats import zipf, zipfian
+    >>> k = np.arange(11)
+    >>> np.allclose(zipf.pmf(k, a), zipfian.pmf(k, a, n=10000000))
+    True
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (1, np.inf), (False, False))]
+
+    def _rvs(self, a, size=None, random_state=None):
+        return random_state.zipf(a, size=size)
+
+    def _argcheck(self, a):
+        return a > 1
+
+    def _pmf(self, k, a):
+        k = k.astype(np.float64)
+        # zipf.pmf(k, a) = 1/(zeta(a) * k**a)
+        Pk = 1.0 / special.zeta(a, 1) * k**-a
+        return Pk
+
+    def _munp(self, n, a):
+        return _lazywhere(
+            a > n + 1, (a, n),
+            lambda a, n: special.zeta(a - n, 1) / special.zeta(a, 1),
+            np.inf)
+
+
+zipf = zipf_gen(a=1, name='zipf', longname='A Zipf')
+
+
+def _gen_harmonic_gt1(n, a):
+    """Generalized harmonic number, a > 1"""
+    # See https://en.wikipedia.org/wiki/Harmonic_number; search for "hurwitz"
+    return zeta(a, 1) - zeta(a, n+1)
+
+
+def _gen_harmonic_leq1(n, a):
+    """Generalized harmonic number, a <= 1"""
+    if not np.size(n):
+        return n
+    n_max = np.max(n)  # loop starts at maximum of all n
+    out = np.zeros_like(a, dtype=float)
+    # add terms of harmonic series; starting from smallest to avoid roundoff
+    for i in np.arange(n_max, 0, -1, dtype=float):
+        mask = i <= n  # don't add terms after nth
+        out[mask] += 1/i**a[mask]
+    return out
+
+
+def _gen_harmonic(n, a):
+    """Generalized harmonic number"""
+    n, a = np.broadcast_arrays(n, a)
+    return _lazywhere(a > 1, (n, a),
+                      f=_gen_harmonic_gt1, f2=_gen_harmonic_leq1)
+
+
+class zipfian_gen(rv_discrete):
+    r"""A Zipfian discrete random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    zipf
+
+    Notes
+    -----
+    The probability mass function for `zipfian` is:
+
+    .. math::
+
+        f(k, a, n) = \frac{1}{H_{n,a} k^a}
+
+    for :math:`k \in \{1, 2, \dots, n-1, n\}`, :math:`a \ge 0`,
+    :math:`n \in \{1, 2, 3, \dots\}`.
+
+    `zipfian` takes :math:`a` and :math:`n` as shape parameters.
+    :math:`H_{n,a}` is the :math:`n`:sup:`th` generalized harmonic
+    number of order :math:`a`.
+
+    The Zipfian distribution reduces to the Zipf (zeta) distribution as
+    :math:`n \rightarrow \infty`.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Zipf's Law", Wikipedia, https://en.wikipedia.org/wiki/Zipf's_law
+    .. [2] Larry Leemis, "Zipf Distribution", Univariate Distribution
+           Relationships. http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf
+
+    %(example)s
+
+    Confirm that `zipfian` reduces to `zipf` for large `n`, ``a > 1``.
+
+    >>> import numpy as np
+    >>> from scipy.stats import zipf, zipfian
+    >>> k = np.arange(11)
+    >>> np.allclose(zipfian.pmf(k, a=3.5, n=10000000), zipf.pmf(k, a=3.5))
+    True
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (True, False)),
+                _ShapeInfo("n", True, (0, np.inf), (False, False))]
+
+    def _argcheck(self, a, n):
+        # we need np.asarray here because moment (maybe others) don't convert
+        return (a >= 0) & (n > 0) & (n == np.asarray(n, dtype=int))
+
+    def _get_support(self, a, n):
+        return 1, n
+
+    def _pmf(self, k, a, n):
+        k = k.astype(np.float64)
+        return 1.0 / _gen_harmonic(n, a) * k**-a
+
+    def _cdf(self, k, a, n):
+        return _gen_harmonic(k, a) / _gen_harmonic(n, a)
+
+    def _sf(self, k, a, n):
+        k = k + 1  # # to match SciPy convention
+        # see http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf
+        return ((k**a*(_gen_harmonic(n, a) - _gen_harmonic(k, a)) + 1)
+                / (k**a*_gen_harmonic(n, a)))
+
+    def _stats(self, a, n):
+        # see # see http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf
+        Hna = _gen_harmonic(n, a)
+        Hna1 = _gen_harmonic(n, a-1)
+        Hna2 = _gen_harmonic(n, a-2)
+        Hna3 = _gen_harmonic(n, a-3)
+        Hna4 = _gen_harmonic(n, a-4)
+        mu1 = Hna1/Hna
+        mu2n = (Hna2*Hna - Hna1**2)
+        mu2d = Hna**2
+        mu2 = mu2n / mu2d
+        g1 = (Hna3/Hna - 3*Hna1*Hna2/Hna**2 + 2*Hna1**3/Hna**3)/mu2**(3/2)
+        g2 = (Hna**3*Hna4 - 4*Hna**2*Hna1*Hna3 + 6*Hna*Hna1**2*Hna2
+              - 3*Hna1**4) / mu2n**2
+        g2 -= 3
+        return mu1, mu2, g1, g2
+
+
+zipfian = zipfian_gen(a=1, name='zipfian', longname='A Zipfian')
+
+
+class dlaplace_gen(rv_discrete):
+    r"""A  Laplacian discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    The probability mass function for `dlaplace` is:
+
+    .. math::
+
+        f(k) = \tanh(a/2) \exp(-a |k|)
+
+    for integers :math:`k` and :math:`a > 0`.
+
+    `dlaplace` takes :math:`a` as shape parameter.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+
+    def _shape_info(self):
+        return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
+
+    def _pmf(self, k, a):
+        # dlaplace.pmf(k) = tanh(a/2) * exp(-a*abs(k))
+        return tanh(a/2.0) * exp(-a * abs(k))
+
+    def _cdf(self, x, a):
+        k = floor(x)
+
+        def f(k, a):
+            return 1.0 - exp(-a * k) / (exp(a) + 1)
+
+        def f2(k, a):
+            return exp(a * (k + 1)) / (exp(a) + 1)
+
+        return _lazywhere(k >= 0, (k, a), f=f, f2=f2)
+
+    def _ppf(self, q, a):
+        const = 1 + exp(a)
+        vals = ceil(np.where(q < 1.0 / (1 + exp(-a)),
+                             log(q*const) / a - 1,
+                             -log((1-q) * const) / a))
+        vals1 = vals - 1
+        return np.where(self._cdf(vals1, a) >= q, vals1, vals)
+
+    def _stats(self, a):
+        ea = exp(a)
+        mu2 = 2.*ea/(ea-1.)**2
+        mu4 = 2.*ea*(ea**2+10.*ea+1.) / (ea-1.)**4
+        return 0., mu2, 0., mu4/mu2**2 - 3.
+
+    def _entropy(self, a):
+        return a / sinh(a) - log(tanh(a/2.0))
+
+    def _rvs(self, a, size=None, random_state=None):
+        # The discrete Laplace is equivalent to the two-sided geometric
+        # distribution with PMF:
+        #   f(k) = (1 - alpha)/(1 + alpha) * alpha^abs(k)
+        #   Reference:
+        #     https://www.sciencedirect.com/science/
+        #     article/abs/pii/S0378375804003519
+        # Furthermore, the two-sided geometric distribution is
+        # equivalent to the difference between two iid geometric
+        # distributions.
+        #   Reference (page 179):
+        #     https://pdfs.semanticscholar.org/61b3/
+        #     b99f466815808fd0d03f5d2791eea8b541a1.pdf
+        # Thus, we can leverage the following:
+        #   1) alpha = e^-a
+        #   2) probability_of_success = 1 - alpha (Bernoulli trial)
+        probOfSuccess = -np.expm1(-np.asarray(a))
+        x = random_state.geometric(probOfSuccess, size=size)
+        y = random_state.geometric(probOfSuccess, size=size)
+        return x - y
+
+
+dlaplace = dlaplace_gen(a=-np.inf,
+                        name='dlaplace', longname='A discrete Laplacian')
+
+
+class poisson_binom_gen(rv_discrete):
+    r"""A Poisson Binomial discrete random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    binom
+
+    Notes
+    -----
+    The probability mass function for `poisson_binom` is:
+
+    .. math::
+
+     f(k; p_1, p_2, ..., p_n) = \sum_{A \in F_k} \prod_{i \in A} p_i \prod_{j \in A^C} 1 - p_j
+
+    where :math:`k \in \{0, 1, \dots, n-1, n\}`, :math:`F_k` is the set of all
+    subsets of :math:`k` integers that can be selected :math:`\{0, 1, \dots, n-1, n\}`,
+    and :math:`A^C` is the complement of a set :math:`A`.
+
+    `poisson_binom` accepts a single array argument ``p`` for shape parameters
+    :math:`0 ≤ p_i ≤ 1`, where the last axis corresponds with the index :math:`i` and
+    any others are for batch dimensions. Broadcasting behaves according to the usual
+    rules except that the last axis of ``p`` is ignored. Instances of this class do
+    not support serialization/unserialization.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] "Poisson binomial distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Poisson_binomial_distribution
+    .. [2] Biscarri, William, Sihai Dave Zhao, and Robert J. Brunner. "A simple and
+           fast method for computing the Poisson binomial distribution function".
+           Computational Statistics & Data Analysis 122 (2018) 92-100.
+           :doi:`10.1016/j.csda.2018.01.007`
+
+    %(example)s
+
+    """  # noqa: E501
+    def _shape_info(self):
+        # message = 'Fitting is not implemented for this distribution."
+        # raise NotImplementedError(message)
+        return []
+
+    def _argcheck(self, *args):
+        p = np.stack(args, axis=0)
+        conds = (0 <= p) & (p <= 1)
+        return np.all(conds, axis=0)
+
+    def _rvs(self, *args, size=None, random_state=None):
+        # convenient to work along the last axis here to avoid interference with `size`
+        p = np.stack(args, axis=-1)
+        # Size passed by the user is the *shape of the returned array*, so it won't
+        # contain the length of the last axis of p.
+        size = (p.shape if size is None else
+                (size, 1) if np.isscalar(size) else tuple(size) + (1,))
+        size = np.broadcast_shapes(p.shape, size)
+        return bernoulli._rvs(p, size=size, random_state=random_state).sum(axis=-1)
+
+    def _get_support(self, *args):
+        return 0, len(args)
+
+    def _pmf(self, k, *args):
+        k = np.atleast_1d(k).astype(np.int64)
+        k, *args = np.broadcast_arrays(k, *args)
+        args = np.asarray(args, dtype=np.float64)
+        return _poisson_binom(k, args, 'pmf')
+
+    def _cdf(self, k, *args):
+        k = np.atleast_1d(k).astype(np.int64)
+        k, *args = np.broadcast_arrays(k, *args)
+        args = np.asarray(args, dtype=np.float64)
+        return _poisson_binom(k, args, 'cdf')
+
+    def _stats(self, *args, **kwds):
+        p = np.stack(args, axis=0)
+        mean = np.sum(p, axis=0)
+        var = np.sum(p * (1-p), axis=0)
+        return (mean, var, None, None)
+
+    def __call__(self, *args, **kwds):
+        return poisson_binomial_frozen(self, *args, **kwds)
+
+
+poisson_binom = poisson_binom_gen(name='poisson_binom', longname='A Poisson binomial',
+                                  shapes='p')
+
+# The _parse_args methods don't work with vector-valued shape parameters, so we rewrite
+# them. Note that `p` is accepted as an array with the index `i` of `p_i` corresponding
+# with the last axis; we return it as a tuple (p_1, p_2, ..., p_n) so that it looks
+# like `n` scalar (or arrays of scalar-valued) shape parameters to the infrastructure.
+
+def _parse_args_rvs(self, p, loc=0, size=None):
+    return tuple(np.moveaxis(p, -1, 0)), loc, 1.0, size
+
+def _parse_args_stats(self, p, loc=0, moments='mv'):
+    return tuple(np.moveaxis(p, -1, 0)), loc, 1.0, moments
+
+def _parse_args(self, p, loc=0):
+    return tuple(np.moveaxis(p, -1, 0)), loc, 1.0
+
+# The infrastructure manually binds these methods to the instance, so
+# we can only override them by manually binding them, too.
+_pb_obj, _pb_cls = poisson_binom, poisson_binom_gen  # shorter names (for PEP8)
+poisson_binom._parse_args_rvs = _parse_args_rvs.__get__(_pb_obj, _pb_cls)
+poisson_binom._parse_args_stats = _parse_args_stats.__get__(_pb_obj, _pb_cls)
+poisson_binom._parse_args = _parse_args.__get__(_pb_obj, _pb_cls)
+
+class poisson_binomial_frozen(rv_discrete_frozen):
+    # copied from rv_frozen; we just need to bind the `_parse_args` methods
+    def __init__(self, dist, *args, **kwds):                        # verbatim
+        self.args = args                                            # verbatim
+        self.kwds = kwds                                            # verbatim
+
+        # create a new instance                                     # verbatim
+        self.dist = dist.__class__(**dist._updated_ctor_param())    # verbatim
+
+        # Here is the only modification
+        self.dist._parse_args_rvs = _parse_args_rvs.__get__(_pb_obj, _pb_cls)
+        self.dist._parse_args_stats = _parse_args_stats.__get__(_pb_obj, _pb_cls)
+        self.dist._parse_args = _parse_args.__get__(_pb_obj, _pb_cls)
+
+        shapes, _, _ = self.dist._parse_args(*args, **kwds)         # verbatim
+        self.a, self.b = self.dist._get_support(*shapes)            # verbatim
+
+    def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds):
+        a, loc, scale = self.dist._parse_args(*self.args, **self.kwds)
+        # Here's the modification: we pass all args (including `loc`) into the `args`
+        # parameter of `expect` so the shape only goes through `_parse_args` once.
+        return self.dist.expect(func, self.args, loc, lb, ub, conditional, **kwds)
+
+
+class skellam_gen(rv_discrete):
+    r"""A  Skellam discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+    Probability distribution of the difference of two correlated or
+    uncorrelated Poisson random variables.
+
+    Let :math:`k_1` and :math:`k_2` be two Poisson-distributed r.v. with
+    expected values :math:`\lambda_1` and :math:`\lambda_2`. Then,
+    :math:`k_1 - k_2` follows a Skellam distribution with parameters
+    :math:`\mu_1 = \lambda_1 - \rho \sqrt{\lambda_1 \lambda_2}` and
+    :math:`\mu_2 = \lambda_2 - \rho \sqrt{\lambda_1 \lambda_2}`, where
+    :math:`\rho` is the correlation coefficient between :math:`k_1` and
+    :math:`k_2`. If the two Poisson-distributed r.v. are independent then
+    :math:`\rho = 0`.
+
+    Parameters :math:`\mu_1` and :math:`\mu_2` must be strictly positive.
+
+    For details see: https://en.wikipedia.org/wiki/Skellam_distribution
+
+    `skellam` takes :math:`\mu_1` and :math:`\mu_2` as shape parameters.
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("mu1", False, (0, np.inf), (False, False)),
+                _ShapeInfo("mu2", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, mu1, mu2, size=None, random_state=None):
+        n = size
+        return (random_state.poisson(mu1, n) -
+                random_state.poisson(mu2, n))
+
+    def _pmf(self, x, mu1, mu2):
+        with np.errstate(over='ignore'):  # see gh-17432
+            px = np.where(x < 0,
+                          scu._ncx2_pdf(2*mu2, 2*(1-x), 2*mu1)*2,
+                          scu._ncx2_pdf(2*mu1, 2*(1+x), 2*mu2)*2)
+            # ncx2.pdf() returns nan's for extremely low probabilities
+        return px
+
+    def _cdf(self, x, mu1, mu2):
+        x = floor(x)
+        with np.errstate(over='ignore'):  # see gh-17432
+            px = np.where(x < 0,
+                          scu._ncx2_cdf(2*mu2, -2*x, 2*mu1),
+                          1 - scu._ncx2_cdf(2*mu1, 2*(x+1), 2*mu2))
+        return px
+
+    def _stats(self, mu1, mu2):
+        mean = mu1 - mu2
+        var = mu1 + mu2
+        g1 = mean / sqrt((var)**3)
+        g2 = 1 / var
+        return mean, var, g1, g2
+
+
+skellam = skellam_gen(a=-np.inf, name="skellam", longname='A Skellam')
+
+
+class yulesimon_gen(rv_discrete):
+    r"""A Yule-Simon discrete random variable.
+
+    %(before_notes)s
+
+    Notes
+    -----
+
+    The probability mass function for the `yulesimon` is:
+
+    .. math::
+
+        f(k) =  \alpha B(k, \alpha+1)
+
+    for :math:`k=1,2,3,...`, where :math:`\alpha>0`.
+    Here :math:`B` refers to the `scipy.special.beta` function.
+
+    The sampling of random variates is based on pg 553, Section 6.3 of [1]_.
+    Our notation maps to the referenced logic via :math:`\alpha=a-1`.
+
+    For details see the wikipedia entry [2]_.
+
+    References
+    ----------
+    .. [1] Devroye, Luc. "Non-uniform Random Variate Generation",
+         (1986) Springer, New York.
+
+    .. [2] https://en.wikipedia.org/wiki/Yule-Simon_distribution
+
+    %(after_notes)s
+
+    %(example)s
+
+    """
+    def _shape_info(self):
+        return [_ShapeInfo("alpha", False, (0, np.inf), (False, False))]
+
+    def _rvs(self, alpha, size=None, random_state=None):
+        E1 = random_state.standard_exponential(size)
+        E2 = random_state.standard_exponential(size)
+        ans = ceil(-E1 / log1p(-exp(-E2 / alpha)))
+        return ans
+
+    def _pmf(self, x, alpha):
+        return alpha * special.beta(x, alpha + 1)
+
+    def _argcheck(self, alpha):
+        return (alpha > 0)
+
+    def _logpmf(self, x, alpha):
+        return log(alpha) + special.betaln(x, alpha + 1)
+
+    def _cdf(self, x, alpha):
+        return 1 - x * special.beta(x, alpha + 1)
+
+    def _sf(self, x, alpha):
+        return x * special.beta(x, alpha + 1)
+
+    def _logsf(self, x, alpha):
+        return log(x) + special.betaln(x, alpha + 1)
+
+    def _stats(self, alpha):
+        mu = np.where(alpha <= 1, np.inf, alpha / (alpha - 1))
+        mu2 = np.where(alpha > 2,
+                       alpha**2 / ((alpha - 2.0) * (alpha - 1)**2),
+                       np.inf)
+        mu2 = np.where(alpha <= 1, np.nan, mu2)
+        g1 = np.where(alpha > 3,
+                      sqrt(alpha - 2) * (alpha + 1)**2 / (alpha * (alpha - 3)),
+                      np.inf)
+        g1 = np.where(alpha <= 2, np.nan, g1)
+        g2 = np.where(alpha > 4,
+                      alpha + 3 + ((11 * alpha**3 - 49 * alpha - 22) /
+                                   (alpha * (alpha - 4) * (alpha - 3))),
+                      np.inf)
+        g2 = np.where(alpha <= 2, np.nan, g2)
+        return mu, mu2, g1, g2
+
+
+yulesimon = yulesimon_gen(name='yulesimon', a=1)
+
+
+class _nchypergeom_gen(rv_discrete):
+    r"""A noncentral hypergeometric discrete random variable.
+
+    For subclassing by nchypergeom_fisher_gen and nchypergeom_wallenius_gen.
+
+    """
+
+    rvs_name = None
+    dist = None
+
+    def _shape_info(self):
+        return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
+                _ShapeInfo("n", True, (0, np.inf), (True, False)),
+                _ShapeInfo("N", True, (0, np.inf), (True, False)),
+                _ShapeInfo("odds", False, (0, np.inf), (False, False))]
+
+    def _get_support(self, M, n, N, odds):
+        N, m1, n = M, n, N  # follow Wikipedia notation
+        m2 = N - m1
+        x_min = np.maximum(0, n - m2)
+        x_max = np.minimum(n, m1)
+        return x_min, x_max
+
+    def _argcheck(self, M, n, N, odds):
+        M, n = np.asarray(M), np.asarray(n),
+        N, odds = np.asarray(N), np.asarray(odds)
+        cond1 = (M.astype(int) == M) & (M >= 0)
+        cond2 = (n.astype(int) == n) & (n >= 0)
+        cond3 = (N.astype(int) == N) & (N >= 0)
+        cond4 = odds > 0
+        cond5 = N <= M
+        cond6 = n <= M
+        return cond1 & cond2 & cond3 & cond4 & cond5 & cond6
+
+    def _rvs(self, M, n, N, odds, size=None, random_state=None):
+
+        @_vectorize_rvs_over_shapes
+        def _rvs1(M, n, N, odds, size, random_state):
+            length = np.prod(size)
+            urn = _PyStochasticLib3()
+            rv_gen = getattr(urn, self.rvs_name)
+            rvs = rv_gen(N, n, M, odds, length, random_state)
+            rvs = rvs.reshape(size)
+            return rvs
+
+        return _rvs1(M, n, N, odds, size=size, random_state=random_state)
+
+    def _pmf(self, x, M, n, N, odds):
+
+        x, M, n, N, odds = np.broadcast_arrays(x, M, n, N, odds)
+        if x.size == 0:  # np.vectorize doesn't work with zero size input
+            return np.empty_like(x)
+
+        @np.vectorize
+        def _pmf1(x, M, n, N, odds):
+            urn = self.dist(N, n, M, odds, 1e-12)
+            return urn.probability(x)
+
+        return _pmf1(x, M, n, N, odds)
+
+    def _stats(self, M, n, N, odds, moments):
+
+        @np.vectorize
+        def _moments1(M, n, N, odds):
+            urn = self.dist(N, n, M, odds, 1e-12)
+            return urn.moments()
+
+        m, v = (_moments1(M, n, N, odds) if ("m" in moments or "v" in moments)
+                else (None, None))
+        s, k = None, None
+        return m, v, s, k
+
+
+class nchypergeom_fisher_gen(_nchypergeom_gen):
+    r"""A Fisher's noncentral hypergeometric discrete random variable.
+
+    Fisher's noncentral hypergeometric distribution models drawing objects of
+    two types from a bin. `M` is the total number of objects, `n` is the
+    number of Type I objects, and `odds` is the odds ratio: the odds of
+    selecting a Type I object rather than a Type II object when there is only
+    one object of each type.
+    The random variate represents the number of Type I objects drawn if we
+    take a handful of objects from the bin at once and find out afterwards
+    that we took `N` objects.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    nchypergeom_wallenius, hypergeom, nhypergeom
+
+    Notes
+    -----
+    Let mathematical symbols :math:`N`, :math:`n`, and :math:`M` correspond
+    with parameters `N`, `n`, and `M` (respectively) as defined above.
+
+    The probability mass function is defined as
+
+    .. math::
+
+        p(x; M, n, N, \omega) =
+        \frac{\binom{n}{x}\binom{M - n}{N-x}\omega^x}{P_0},
+
+    for
+    :math:`x \in [x_l, x_u]`,
+    :math:`M \in {\mathbb N}`,
+    :math:`n \in [0, M]`,
+    :math:`N \in [0, M]`,
+    :math:`\omega > 0`,
+    where
+    :math:`x_l = \max(0, N - (M - n))`,
+    :math:`x_u = \min(N, n)`,
+
+    .. math::
+
+        P_0 = \sum_{y=x_l}^{x_u} \binom{n}{y}\binom{M - n}{N-y}\omega^y,
+
+    and the binomial coefficients are defined as
+
+    .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
+
+    `nchypergeom_fisher` uses the BiasedUrn package by Agner Fog with
+    permission for it to be distributed under SciPy's license.
+
+    The symbols used to denote the shape parameters (`N`, `n`, and `M`) are not
+    universally accepted; they are chosen for consistency with `hypergeom`.
+
+    Note that Fisher's noncentral hypergeometric distribution is distinct
+    from Wallenius' noncentral hypergeometric distribution, which models
+    drawing a pre-determined `N` objects from a bin one by one.
+    When the odds ratio is unity, however, both distributions reduce to the
+    ordinary hypergeometric distribution.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Agner Fog, "Biased Urn Theory".
+           https://cran.r-project.org/web/packages/BiasedUrn/vignettes/UrnTheory.pdf
+
+    .. [2] "Fisher's noncentral hypergeometric distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Fisher's_noncentral_hypergeometric_distribution
+
+    %(example)s
+
+    """
+
+    rvs_name = "rvs_fisher"
+    dist = _PyFishersNCHypergeometric
+
+
+nchypergeom_fisher = nchypergeom_fisher_gen(
+    name='nchypergeom_fisher',
+    longname="A Fisher's noncentral hypergeometric")
+
+
+class nchypergeom_wallenius_gen(_nchypergeom_gen):
+    r"""A Wallenius' noncentral hypergeometric discrete random variable.
+
+    Wallenius' noncentral hypergeometric distribution models drawing objects of
+    two types from a bin. `M` is the total number of objects, `n` is the
+    number of Type I objects, and `odds` is the odds ratio: the odds of
+    selecting a Type I object rather than a Type II object when there is only
+    one object of each type.
+    The random variate represents the number of Type I objects drawn if we
+    draw a pre-determined `N` objects from a bin one by one.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    nchypergeom_fisher, hypergeom, nhypergeom
+
+    Notes
+    -----
+    Let mathematical symbols :math:`N`, :math:`n`, and :math:`M` correspond
+    with parameters `N`, `n`, and `M` (respectively) as defined above.
+
+    The probability mass function is defined as
+
+    .. math::
+
+        p(x; N, n, M) = \binom{n}{x} \binom{M - n}{N-x}
+        \int_0^1 \left(1-t^{\omega/D}\right)^x\left(1-t^{1/D}\right)^{N-x} dt
+
+    for
+    :math:`x \in [x_l, x_u]`,
+    :math:`M \in {\mathbb N}`,
+    :math:`n \in [0, M]`,
+    :math:`N \in [0, M]`,
+    :math:`\omega > 0`,
+    where
+    :math:`x_l = \max(0, N - (M - n))`,
+    :math:`x_u = \min(N, n)`,
+
+    .. math::
+
+        D = \omega(n - x) + ((M - n)-(N-x)),
+
+    and the binomial coefficients are defined as
+
+    .. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
+
+    `nchypergeom_wallenius` uses the BiasedUrn package by Agner Fog with
+    permission for it to be distributed under SciPy's license.
+
+    The symbols used to denote the shape parameters (`N`, `n`, and `M`) are not
+    universally accepted; they are chosen for consistency with `hypergeom`.
+
+    Note that Wallenius' noncentral hypergeometric distribution is distinct
+    from Fisher's noncentral hypergeometric distribution, which models
+    take a handful of objects from the bin at once, finding out afterwards
+    that `N` objects were taken.
+    When the odds ratio is unity, however, both distributions reduce to the
+    ordinary hypergeometric distribution.
+
+    %(after_notes)s
+
+    References
+    ----------
+    .. [1] Agner Fog, "Biased Urn Theory".
+           https://cran.r-project.org/web/packages/BiasedUrn/vignettes/UrnTheory.pdf
+
+    .. [2] "Wallenius' noncentral hypergeometric distribution", Wikipedia,
+           https://en.wikipedia.org/wiki/Wallenius'_noncentral_hypergeometric_distribution
+
+    %(example)s
+
+    """
+
+    rvs_name = "rvs_wallenius"
+    dist = _PyWalleniusNCHypergeometric
+
+
+nchypergeom_wallenius = nchypergeom_wallenius_gen(
+    name='nchypergeom_wallenius',
+    longname="A Wallenius' noncentral hypergeometric")
+
+
+# Collect names of classes and objects in this module.
+pairs = list(globals().copy().items())
+_distn_names, _distn_gen_names = get_distribution_names(pairs, rv_discrete)
+
+__all__ = _distn_names + _distn_gen_names
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_distn_infrastructure.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_distn_infrastructure.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e2d8134f8679332a58e1c522332b96e50256116
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_distn_infrastructure.py
@@ -0,0 +1,4174 @@
+#
+# Author:  Travis Oliphant  2002-2011 with contributions from
+#          SciPy Developers 2004-2011
+#
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+
+import sys
+import keyword
+import re
+import types
+import warnings
+from itertools import zip_longest
+
+from scipy._lib import doccer
+from ._distr_params import distcont, distdiscrete
+from scipy._lib._util import check_random_state, _lazywhere
+
+from scipy.special import comb, entr
+
+
+# for root finding for continuous distribution ppf, and maximum likelihood
+# estimation
+from scipy import optimize
+
+# for functions of continuous distributions (e.g. moments, entropy, cdf)
+from scipy import integrate
+
+# to approximate the pdf of a continuous distribution given its cdf
+from scipy._lib._finite_differences import _derivative
+
+# for scipy.stats.entropy. Attempts to import just that function or file
+# have cause import problems
+from scipy import stats
+
+from numpy import (arange, putmask, ones, shape, ndarray, zeros, floor,
+                   logical_and, log, sqrt, place, argmax, vectorize, asarray,
+                   nan, inf, isinf, empty)
+
+import numpy as np
+from ._constants import _XMAX, _LOGXMAX
+from ._censored_data import CensoredData
+from scipy.stats._warnings_errors import FitError
+
+# These are the docstring parts used for substitution in specific
+# distribution docstrings
+
+docheaders = {'methods': """\nMethods\n-------\n""",
+              'notes': """\nNotes\n-----\n""",
+              'examples': """\nExamples\n--------\n"""}
+
+_doc_rvs = """\
+rvs(%(shapes)s, loc=0, scale=1, size=1, random_state=None)
+    Random variates.
+"""
+_doc_pdf = """\
+pdf(x, %(shapes)s, loc=0, scale=1)
+    Probability density function.
+"""
+_doc_logpdf = """\
+logpdf(x, %(shapes)s, loc=0, scale=1)
+    Log of the probability density function.
+"""
+_doc_pmf = """\
+pmf(k, %(shapes)s, loc=0, scale=1)
+    Probability mass function.
+"""
+_doc_logpmf = """\
+logpmf(k, %(shapes)s, loc=0, scale=1)
+    Log of the probability mass function.
+"""
+_doc_cdf = """\
+cdf(x, %(shapes)s, loc=0, scale=1)
+    Cumulative distribution function.
+"""
+_doc_logcdf = """\
+logcdf(x, %(shapes)s, loc=0, scale=1)
+    Log of the cumulative distribution function.
+"""
+_doc_sf = """\
+sf(x, %(shapes)s, loc=0, scale=1)
+    Survival function  (also defined as ``1 - cdf``, but `sf` is sometimes more accurate).
+"""  # noqa: E501
+_doc_logsf = """\
+logsf(x, %(shapes)s, loc=0, scale=1)
+    Log of the survival function.
+"""
+_doc_ppf = """\
+ppf(q, %(shapes)s, loc=0, scale=1)
+    Percent point function (inverse of ``cdf`` --- percentiles).
+"""
+_doc_isf = """\
+isf(q, %(shapes)s, loc=0, scale=1)
+    Inverse survival function (inverse of ``sf``).
+"""
+_doc_moment = """\
+moment(order, %(shapes)s, loc=0, scale=1)
+    Non-central moment of the specified order.
+"""
+_doc_stats = """\
+stats(%(shapes)s, loc=0, scale=1, moments='mv')
+    Mean('m'), variance('v'), skew('s'), and/or kurtosis('k').
+"""
+_doc_entropy = """\
+entropy(%(shapes)s, loc=0, scale=1)
+    (Differential) entropy of the RV.
+"""
+_doc_fit = """\
+fit(data)
+    Parameter estimates for generic data.
+    See `scipy.stats.rv_continuous.fit `__ for detailed documentation of the
+    keyword arguments.
+"""  # noqa: E501
+_doc_expect = """\
+expect(func, args=(%(shapes_)s), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)
+    Expected value of a function (of one argument) with respect to the distribution.
+"""  # noqa: E501
+_doc_expect_discrete = """\
+expect(func, args=(%(shapes_)s), loc=0, lb=None, ub=None, conditional=False)
+    Expected value of a function (of one argument) with respect to the distribution.
+"""
+_doc_median = """\
+median(%(shapes)s, loc=0, scale=1)
+    Median of the distribution.
+"""
+_doc_mean = """\
+mean(%(shapes)s, loc=0, scale=1)
+    Mean of the distribution.
+"""
+_doc_var = """\
+var(%(shapes)s, loc=0, scale=1)
+    Variance of the distribution.
+"""
+_doc_std = """\
+std(%(shapes)s, loc=0, scale=1)
+    Standard deviation of the distribution.
+"""
+_doc_interval = """\
+interval(confidence, %(shapes)s, loc=0, scale=1)
+    Confidence interval with equal areas around the median.
+"""
+_doc_allmethods = ''.join([docheaders['methods'], _doc_rvs, _doc_pdf,
+                           _doc_logpdf, _doc_cdf, _doc_logcdf, _doc_sf,
+                           _doc_logsf, _doc_ppf, _doc_isf, _doc_moment,
+                           _doc_stats, _doc_entropy, _doc_fit,
+                           _doc_expect, _doc_median,
+                           _doc_mean, _doc_var, _doc_std, _doc_interval])
+
+_doc_default_longsummary = """\
+As an instance of the `rv_continuous` class, `%(name)s` object inherits from it
+a collection of generic methods (see below for the full list),
+and completes them with details specific for this particular distribution.
+"""
+
+_doc_default_frozen_note = """
+Alternatively, the object may be called (as a function) to fix the shape,
+location, and scale parameters returning a "frozen" continuous RV object:
+
+rv = %(name)s(%(shapes)s, loc=0, scale=1)
+    - Frozen RV object with the same methods but holding the given shape,
+      location, and scale fixed.
+"""
+_doc_default_example = """\
+Examples
+--------
+>>> import numpy as np
+>>> from scipy.stats import %(name)s
+>>> import matplotlib.pyplot as plt
+>>> fig, ax = plt.subplots(1, 1)
+
+Calculate the first four moments:
+
+%(set_vals_stmt)s
+>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')
+
+Display the probability density function (``pdf``):
+
+>>> x = np.linspace(%(name)s.ppf(0.01, %(shapes)s),
+...                 %(name)s.ppf(0.99, %(shapes)s), 100)
+>>> ax.plot(x, %(name)s.pdf(x, %(shapes)s),
+...        'r-', lw=5, alpha=0.6, label='%(name)s pdf')
+
+Alternatively, the distribution object can be called (as a function)
+to fix the shape, location and scale parameters. This returns a "frozen"
+RV object holding the given parameters fixed.
+
+Freeze the distribution and display the frozen ``pdf``:
+
+>>> rv = %(name)s(%(shapes)s)
+>>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')
+
+Check accuracy of ``cdf`` and ``ppf``:
+
+>>> vals = %(name)s.ppf([0.001, 0.5, 0.999], %(shapes)s)
+>>> np.allclose([0.001, 0.5, 0.999], %(name)s.cdf(vals, %(shapes)s))
+True
+
+Generate random numbers:
+
+>>> r = %(name)s.rvs(%(shapes)s, size=1000)
+
+And compare the histogram:
+
+>>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2)
+>>> ax.set_xlim([x[0], x[-1]])
+>>> ax.legend(loc='best', frameon=False)
+>>> plt.show()
+
+"""
+
+_doc_default_locscale = """\
+The probability density above is defined in the "standardized" form. To shift
+and/or scale the distribution use the ``loc`` and ``scale`` parameters.
+Specifically, ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically
+equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with
+``y = (x - loc) / scale``. Note that shifting the location of a distribution
+does not make it a "noncentral" distribution; noncentral generalizations of
+some distributions are available in separate classes.
+"""
+
+_doc_default = ''.join([_doc_default_longsummary,
+                        _doc_allmethods,
+                        '\n',
+                        _doc_default_example])
+
+_doc_default_before_notes = ''.join([_doc_default_longsummary,
+                                     _doc_allmethods])
+
+docdict = {
+    'rvs': _doc_rvs,
+    'pdf': _doc_pdf,
+    'logpdf': _doc_logpdf,
+    'cdf': _doc_cdf,
+    'logcdf': _doc_logcdf,
+    'sf': _doc_sf,
+    'logsf': _doc_logsf,
+    'ppf': _doc_ppf,
+    'isf': _doc_isf,
+    'stats': _doc_stats,
+    'entropy': _doc_entropy,
+    'fit': _doc_fit,
+    'moment': _doc_moment,
+    'expect': _doc_expect,
+    'interval': _doc_interval,
+    'mean': _doc_mean,
+    'std': _doc_std,
+    'var': _doc_var,
+    'median': _doc_median,
+    'allmethods': _doc_allmethods,
+    'longsummary': _doc_default_longsummary,
+    'frozennote': _doc_default_frozen_note,
+    'example': _doc_default_example,
+    'default': _doc_default,
+    'before_notes': _doc_default_before_notes,
+    'after_notes': _doc_default_locscale
+}
+
+# Reuse common content between continuous and discrete docs, change some
+# minor bits.
+docdict_discrete = docdict.copy()
+
+docdict_discrete['pmf'] = _doc_pmf
+docdict_discrete['logpmf'] = _doc_logpmf
+docdict_discrete['expect'] = _doc_expect_discrete
+_doc_disc_methods = ['rvs', 'pmf', 'logpmf', 'cdf', 'logcdf', 'sf', 'logsf',
+                     'ppf', 'isf', 'stats', 'entropy', 'expect', 'median',
+                     'mean', 'var', 'std', 'interval']
+for obj in _doc_disc_methods:
+    docdict_discrete[obj] = docdict_discrete[obj].replace(', scale=1', '')
+
+_doc_disc_methods_err_varname = ['cdf', 'logcdf', 'sf', 'logsf']
+for obj in _doc_disc_methods_err_varname:
+    docdict_discrete[obj] = docdict_discrete[obj].replace('(x, ', '(k, ')
+
+docdict_discrete.pop('pdf')
+docdict_discrete.pop('logpdf')
+
+_doc_allmethods = ''.join([docdict_discrete[obj] for obj in _doc_disc_methods])
+docdict_discrete['allmethods'] = docheaders['methods'] + _doc_allmethods
+
+docdict_discrete['longsummary'] = _doc_default_longsummary.replace(
+    'rv_continuous', 'rv_discrete')
+
+_doc_default_frozen_note = """
+Alternatively, the object may be called (as a function) to fix the shape and
+location parameters returning a "frozen" discrete RV object:
+
+rv = %(name)s(%(shapes)s, loc=0)
+    - Frozen RV object with the same methods but holding the given shape and
+      location fixed.
+"""
+docdict_discrete['frozennote'] = _doc_default_frozen_note
+
+_doc_default_discrete_example = """\
+Examples
+--------
+>>> import numpy as np
+>>> from scipy.stats import %(name)s
+>>> import matplotlib.pyplot as plt
+>>> fig, ax = plt.subplots(1, 1)
+
+Calculate the first four moments:
+
+%(set_vals_stmt)s
+>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')
+
+Display the probability mass function (``pmf``):
+
+>>> x = np.arange(%(name)s.ppf(0.01, %(shapes)s),
+...               %(name)s.ppf(0.99, %(shapes)s))
+>>> ax.plot(x, %(name)s.pmf(x, %(shapes)s), 'bo', ms=8, label='%(name)s pmf')
+>>> ax.vlines(x, 0, %(name)s.pmf(x, %(shapes)s), colors='b', lw=5, alpha=0.5)
+
+Alternatively, the distribution object can be called (as a function)
+to fix the shape and location. This returns a "frozen" RV object holding
+the given parameters fixed.
+
+Freeze the distribution and display the frozen ``pmf``:
+
+>>> rv = %(name)s(%(shapes)s)
+>>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1,
+...         label='frozen pmf')
+>>> ax.legend(loc='best', frameon=False)
+>>> plt.show()
+
+Check accuracy of ``cdf`` and ``ppf``:
+
+>>> prob = %(name)s.cdf(x, %(shapes)s)
+>>> np.allclose(x, %(name)s.ppf(prob, %(shapes)s))
+True
+
+Generate random numbers:
+
+>>> r = %(name)s.rvs(%(shapes)s, size=1000)
+"""
+
+
+_doc_default_discrete_locscale = """\
+The probability mass function above is defined in the "standardized" form.
+To shift distribution use the ``loc`` parameter.
+Specifically, ``%(name)s.pmf(k, %(shapes)s, loc)`` is identically
+equivalent to ``%(name)s.pmf(k - loc, %(shapes)s)``.
+"""
+
+docdict_discrete['example'] = _doc_default_discrete_example
+docdict_discrete['after_notes'] = _doc_default_discrete_locscale
+
+_doc_default_before_notes = ''.join([docdict_discrete['longsummary'],
+                                     docdict_discrete['allmethods']])
+docdict_discrete['before_notes'] = _doc_default_before_notes
+
+_doc_default_disc = ''.join([docdict_discrete['longsummary'],
+                             docdict_discrete['allmethods'],
+                             docdict_discrete['frozennote'],
+                             docdict_discrete['example']])
+docdict_discrete['default'] = _doc_default_disc
+
+# clean up all the separate docstring elements, we do not need them anymore
+for obj in [s for s in dir() if s.startswith('_doc_')]:
+    exec('del ' + obj)
+del obj
+
+
+def _moment(data, n, mu=None):
+    if mu is None:
+        mu = data.mean()
+    return ((data - mu)**n).mean()
+
+
+def _moment_from_stats(n, mu, mu2, g1, g2, moment_func, args):
+    if (n == 0):
+        return 1.0
+    elif (n == 1):
+        if mu is None:
+            val = moment_func(1, *args)
+        else:
+            val = mu
+    elif (n == 2):
+        if mu2 is None or mu is None:
+            val = moment_func(2, *args)
+        else:
+            val = mu2 + mu*mu
+    elif (n == 3):
+        if g1 is None or mu2 is None or mu is None:
+            val = moment_func(3, *args)
+        else:
+            mu3 = g1 * np.power(mu2, 1.5)  # 3rd central moment
+            val = mu3+3*mu*mu2+mu*mu*mu  # 3rd non-central moment
+    elif (n == 4):
+        if g1 is None or g2 is None or mu2 is None or mu is None:
+            val = moment_func(4, *args)
+        else:
+            mu4 = (g2+3.0)*(mu2**2.0)  # 4th central moment
+            mu3 = g1*np.power(mu2, 1.5)  # 3rd central moment
+            val = mu4+4*mu*mu3+6*mu*mu*mu2+mu*mu*mu*mu
+    else:
+        val = moment_func(n, *args)
+
+    return val
+
+
+def _skew(data):
+    """
+    skew is third central moment / variance**(1.5)
+    """
+    data = np.ravel(data)
+    mu = data.mean()
+    m2 = ((data - mu)**2).mean()
+    m3 = ((data - mu)**3).mean()
+    return m3 / np.power(m2, 1.5)
+
+
+def _kurtosis(data):
+    """Fisher's excess kurtosis is fourth central moment / variance**2 - 3."""
+    data = np.ravel(data)
+    mu = data.mean()
+    m2 = ((data - mu)**2).mean()
+    m4 = ((data - mu)**4).mean()
+    return m4 / m2**2 - 3
+
+def _vectorize_rvs_over_shapes(_rvs1):
+    """Decorator that vectorizes _rvs method to work on ndarray shapes"""
+    # _rvs1 must be a _function_ that accepts _scalar_ args as positional
+    # arguments, `size` and `random_state` as keyword arguments.
+    # _rvs1 must return a random variate array with shape `size`. If `size` is
+    # None, _rvs1 must return a scalar.
+    # When applied to _rvs1, this decorator broadcasts ndarray args
+    # and loops over them, calling _rvs1 for each set of scalar args.
+    # For usage example, see _nchypergeom_gen
+    def _rvs(*args, size, random_state):
+        _rvs1_size, _rvs1_indices = _check_shape(args[0].shape, size)
+
+        size = np.array(size)
+        _rvs1_size = np.array(_rvs1_size)
+        _rvs1_indices = np.array(_rvs1_indices)
+
+        if np.all(_rvs1_indices):  # all args are scalars
+            return _rvs1(*args, size, random_state)
+
+        out = np.empty(size)
+
+        # out.shape can mix dimensions associated with arg_shape and _rvs1_size
+        # Sort them to arg_shape + _rvs1_size for easy indexing of dimensions
+        # corresponding with the different sets of scalar args
+        j0 = np.arange(out.ndim)
+        j1 = np.hstack((j0[~_rvs1_indices], j0[_rvs1_indices]))
+        out = np.moveaxis(out, j1, j0)
+
+        for i in np.ndindex(*size[~_rvs1_indices]):
+            # arg can be squeezed because singleton dimensions will be
+            # associated with _rvs1_size, not arg_shape per _check_shape
+            out[i] = _rvs1(*[np.squeeze(arg)[i] for arg in args],
+                           _rvs1_size, random_state)
+
+        return np.moveaxis(out, j0, j1)  # move axes back before returning
+    return _rvs
+
+
+def _fit_determine_optimizer(optimizer):
+    if not callable(optimizer) and isinstance(optimizer, str):
+        if not optimizer.startswith('fmin_'):
+            optimizer = "fmin_"+optimizer
+        if optimizer == 'fmin_':
+            optimizer = 'fmin'
+        try:
+            optimizer = getattr(optimize, optimizer)
+        except AttributeError as e:
+            raise ValueError(f"{optimizer} is not a valid optimizer") from e
+    return optimizer
+
+def _isintegral(x):
+    return x == np.round(x)
+
+def _sum_finite(x):
+    """
+    For a 1D array x, return a tuple containing the sum of the
+    finite values of x and the number of nonfinite values.
+
+    This is a utility function used when evaluating the negative
+    loglikelihood for a distribution and an array of samples.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats._distn_infrastructure import _sum_finite
+    >>> tot, nbad = _sum_finite(np.array([-2, -np.inf, 5, 1]))
+    >>> tot
+    4.0
+    >>> nbad
+    1
+    """
+    finite_x = np.isfinite(x)
+    bad_count = finite_x.size - np.count_nonzero(finite_x)
+    return np.sum(x[finite_x]), bad_count
+
+
+# Frozen RV class
+class rv_frozen:
+
+    def __init__(self, dist, *args, **kwds):
+        self.args = args
+        self.kwds = kwds
+
+        # create a new instance
+        self.dist = dist.__class__(**dist._updated_ctor_param())
+
+        shapes, _, _ = self.dist._parse_args(*args, **kwds)
+        self.a, self.b = self.dist._get_support(*shapes)
+
+    @property
+    def random_state(self):
+        return self.dist._random_state
+
+    @random_state.setter
+    def random_state(self, seed):
+        self.dist._random_state = check_random_state(seed)
+
+    def cdf(self, x):
+        return self.dist.cdf(x, *self.args, **self.kwds)
+
+    def logcdf(self, x):
+        return self.dist.logcdf(x, *self.args, **self.kwds)
+
+    def ppf(self, q):
+        return self.dist.ppf(q, *self.args, **self.kwds)
+
+    def isf(self, q):
+        return self.dist.isf(q, *self.args, **self.kwds)
+
+    def rvs(self, size=None, random_state=None):
+        kwds = self.kwds.copy()
+        kwds.update({'size': size, 'random_state': random_state})
+        return self.dist.rvs(*self.args, **kwds)
+
+    def sf(self, x):
+        return self.dist.sf(x, *self.args, **self.kwds)
+
+    def logsf(self, x):
+        return self.dist.logsf(x, *self.args, **self.kwds)
+
+    def stats(self, moments='mv'):
+        kwds = self.kwds.copy()
+        kwds.update({'moments': moments})
+        return self.dist.stats(*self.args, **kwds)
+
+    def median(self):
+        return self.dist.median(*self.args, **self.kwds)
+
+    def mean(self):
+        return self.dist.mean(*self.args, **self.kwds)
+
+    def var(self):
+        return self.dist.var(*self.args, **self.kwds)
+
+    def std(self):
+        return self.dist.std(*self.args, **self.kwds)
+
+    def moment(self, order=None):
+        return self.dist.moment(order, *self.args, **self.kwds)
+
+    def entropy(self):
+        return self.dist.entropy(*self.args, **self.kwds)
+
+    def interval(self, confidence=None):
+        return self.dist.interval(confidence, *self.args, **self.kwds)
+
+    def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds):
+        # expect method only accepts shape parameters as positional args
+        # hence convert self.args, self.kwds, also loc/scale
+        # See the .expect method docstrings for the meaning of
+        # other parameters.
+        a, loc, scale = self.dist._parse_args(*self.args, **self.kwds)
+        if isinstance(self.dist, rv_discrete):
+            return self.dist.expect(func, a, loc, lb, ub, conditional, **kwds)
+        else:
+            return self.dist.expect(func, a, loc, scale, lb, ub,
+                                    conditional, **kwds)
+
+    def support(self):
+        return self.dist.support(*self.args, **self.kwds)
+
+
+class rv_discrete_frozen(rv_frozen):
+
+    def pmf(self, k):
+        return self.dist.pmf(k, *self.args, **self.kwds)
+
+    def logpmf(self, k):  # No error
+        return self.dist.logpmf(k, *self.args, **self.kwds)
+
+
+class rv_continuous_frozen(rv_frozen):
+
+    def pdf(self, x):
+        return self.dist.pdf(x, *self.args, **self.kwds)
+
+    def logpdf(self, x):
+        return self.dist.logpdf(x, *self.args, **self.kwds)
+
+
+def argsreduce(cond, *args):
+    """Clean arguments to:
+
+    1. Ensure all arguments are iterable (arrays of dimension at least one
+    2. If cond != True and size > 1, ravel(args[i]) where ravel(condition) is
+       True, in 1D.
+
+    Return list of processed arguments.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats._distn_infrastructure import argsreduce
+    >>> rng = np.random.default_rng()
+    >>> A = rng.random((4, 5))
+    >>> B = 2
+    >>> C = rng.random((1, 5))
+    >>> cond = np.ones(A.shape)
+    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
+    >>> A1.shape
+    (4, 5)
+    >>> B1.shape
+    (1,)
+    >>> C1.shape
+    (1, 5)
+    >>> cond[2,:] = 0
+    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
+    >>> A1.shape
+    (15,)
+    >>> B1.shape
+    (1,)
+    >>> C1.shape
+    (15,)
+
+    """
+    # some distributions assume arguments are iterable.
+    newargs = np.atleast_1d(*args)
+
+    # np.atleast_1d returns an array if only one argument, or a list of arrays
+    # if more than one argument.
+    if not isinstance(newargs, (list | tuple)):
+        newargs = (newargs,)
+
+    if np.all(cond):
+        # broadcast arrays with cond
+        *newargs, cond = np.broadcast_arrays(*newargs, cond)
+        return [arg.ravel() for arg in newargs]
+
+    s = cond.shape
+    # np.extract returns flattened arrays, which are not broadcastable together
+    # unless they are either the same size or size == 1.
+    return [(arg if np.size(arg) == 1
+            else np.extract(cond, np.broadcast_to(arg, s)))
+            for arg in newargs]
+
+
+parse_arg_template = """
+def _parse_args(self, %(shape_arg_str)s %(locscale_in)s):
+    return (%(shape_arg_str)s), %(locscale_out)s
+
+def _parse_args_rvs(self, %(shape_arg_str)s %(locscale_in)s, size=None):
+    return self._argcheck_rvs(%(shape_arg_str)s %(locscale_out)s, size=size)
+
+def _parse_args_stats(self, %(shape_arg_str)s %(locscale_in)s, moments='mv'):
+    return (%(shape_arg_str)s), %(locscale_out)s, moments
+"""
+
+
+class rv_generic:
+    """Class which encapsulates common functionality between rv_discrete
+    and rv_continuous.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__()
+
+        # figure out if _stats signature has 'moments' keyword
+        sig = _getfullargspec(self._stats)
+        self._stats_has_moments = ((sig.varkw is not None) or
+                                   ('moments' in sig.args) or
+                                   ('moments' in sig.kwonlyargs))
+        self._random_state = check_random_state(seed)
+
+    @property
+    def random_state(self):
+        """Get or set the generator object for generating random variates.
+
+        If `random_state` is None (or `np.random`), the
+        `numpy.random.RandomState` singleton is used.
+        If `random_state` is an int, a new ``RandomState`` instance is used,
+        seeded with `random_state`.
+        If `random_state` is already a ``Generator`` or ``RandomState``
+        instance, that instance is used.
+
+        """
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, seed):
+        self._random_state = check_random_state(seed)
+
+    def __setstate__(self, state):
+        try:
+            self.__dict__.update(state)
+            # attaches the dynamically created methods on each instance.
+            # if a subclass overrides rv_generic.__setstate__, or implements
+            # it's own _attach_methods, then it must make sure that
+            # _attach_argparser_methods is called.
+            self._attach_methods()
+        except ValueError:
+            # reconstitute an old pickle scipy<1.6, that contains
+            # (_ctor_param, random_state) as state
+            self._ctor_param = state[0]
+            self._random_state = state[1]
+            self.__init__()
+
+    def _attach_methods(self):
+        """Attaches dynamically created methods to the rv_* instance.
+
+        This method must be overridden by subclasses, and must itself call
+         _attach_argparser_methods. This method is called in __init__ in
+         subclasses, and in __setstate__
+        """
+        raise NotImplementedError
+
+    def _attach_argparser_methods(self):
+        """
+        Generates the argument-parsing functions dynamically and attaches
+        them to the instance.
+
+        Should be called from `_attach_methods`, typically in __init__ and
+        during unpickling (__setstate__)
+        """
+        ns = {}
+        exec(self._parse_arg_template, ns)
+        # NB: attach to the instance, not class
+        for name in ['_parse_args', '_parse_args_stats', '_parse_args_rvs']:
+            setattr(self, name, types.MethodType(ns[name], self))
+
+    def _construct_argparser(
+            self, meths_to_inspect, locscale_in, locscale_out):
+        """Construct the parser string for the shape arguments.
+
+        This method should be called in __init__ of a class for each
+        distribution. It creates the `_parse_arg_template` attribute that is
+        then used by `_attach_argparser_methods` to dynamically create and
+        attach the `_parse_args`, `_parse_args_stats`, `_parse_args_rvs`
+        methods to the instance.
+
+        If self.shapes is a non-empty string, interprets it as a
+        comma-separated list of shape parameters.
+
+        Otherwise inspects the call signatures of `meths_to_inspect`
+        and constructs the argument-parsing functions from these.
+        In this case also sets `shapes` and `numargs`.
+        """
+
+        if self.shapes:
+            # sanitize the user-supplied shapes
+            if not isinstance(self.shapes, str):
+                raise TypeError('shapes must be a string.')
+
+            shapes = self.shapes.replace(',', ' ').split()
+
+            for field in shapes:
+                if keyword.iskeyword(field):
+                    raise SyntaxError('keywords cannot be used as shapes.')
+                if not re.match('^[_a-zA-Z][_a-zA-Z0-9]*$', field):
+                    raise SyntaxError(
+                        'shapes must be valid python identifiers')
+        else:
+            # find out the call signatures (_pdf, _cdf etc), deduce shape
+            # arguments. Generic methods only have 'self, x', any further args
+            # are shapes.
+            shapes_list = []
+            for meth in meths_to_inspect:
+                shapes_args = _getfullargspec(meth)  # NB does not contain self
+                args = shapes_args.args[1:]       # peel off 'x', too
+
+                if args:
+                    shapes_list.append(args)
+
+                    # *args or **kwargs are not allowed w/automatic shapes
+                    if shapes_args.varargs is not None:
+                        raise TypeError(
+                            '*args are not allowed w/out explicit shapes')
+                    if shapes_args.varkw is not None:
+                        raise TypeError(
+                            '**kwds are not allowed w/out explicit shapes')
+                    if shapes_args.kwonlyargs:
+                        raise TypeError(
+                            'kwonly args are not allowed w/out explicit shapes')
+                    if shapes_args.defaults is not None:
+                        raise TypeError('defaults are not allowed for shapes')
+
+            if shapes_list:
+                shapes = shapes_list[0]
+
+                # make sure the signatures are consistent
+                for item in shapes_list:
+                    if item != shapes:
+                        raise TypeError('Shape arguments are inconsistent.')
+            else:
+                shapes = []
+
+        # have the arguments, construct the method from template
+        shapes_str = ', '.join(shapes) + ', ' if shapes else ''  # NB: not None
+        dct = dict(shape_arg_str=shapes_str,
+                   locscale_in=locscale_in,
+                   locscale_out=locscale_out,
+                   )
+
+        # this string is used by _attach_argparser_methods
+        self._parse_arg_template = parse_arg_template % dct
+
+        self.shapes = ', '.join(shapes) if shapes else None
+        if not hasattr(self, 'numargs'):
+            # allows more general subclassing with *args
+            self.numargs = len(shapes)
+
+    def _construct_doc(self, docdict, shapes_vals=None):
+        """Construct the instance docstring with string substitutions."""
+        tempdict = docdict.copy()
+        tempdict['name'] = self.name or 'distname'
+        tempdict['shapes'] = self.shapes or ''
+
+        if shapes_vals is None:
+            shapes_vals = ()
+        try:
+            vals = ', '.join(f'{val:.3g}' for val in shapes_vals)
+        except TypeError:
+            vals = ', '.join(f'{val}' for val in shapes_vals)
+        tempdict['vals'] = vals
+
+        tempdict['shapes_'] = self.shapes or ''
+        if self.shapes and self.numargs == 1:
+            tempdict['shapes_'] += ','
+
+        if self.shapes:
+            tempdict['set_vals_stmt'] = f'>>> {self.shapes} = {vals}'
+        else:
+            tempdict['set_vals_stmt'] = ''
+
+        if self.shapes is None:
+            # remove shapes from call parameters if there are none
+            for item in ['default', 'before_notes']:
+                tempdict[item] = tempdict[item].replace(
+                    "\n%(shapes)s : array_like\n    shape parameters", "")
+        for i in range(2):
+            if self.shapes is None:
+                # necessary because we use %(shapes)s in two forms (w w/o ", ")
+                self.__doc__ = self.__doc__.replace("%(shapes)s, ", "")
+            try:
+                self.__doc__ = doccer.docformat(self.__doc__, tempdict)
+            except TypeError as e:
+                raise Exception("Unable to construct docstring for "
+                                f"distribution \"{self.name}\": {repr(e)}") from e
+
+        # correct for empty shapes
+        self.__doc__ = self.__doc__.replace('(, ', '(').replace(', )', ')')
+
+    def _construct_default_doc(self, longname=None,
+                               docdict=None, discrete='continuous'):
+        """Construct instance docstring from the default template."""
+        if longname is None:
+            longname = 'A'
+        self.__doc__ = ''.join([f'{longname} {discrete} random variable.',
+                                '\n\n%(before_notes)s\n', docheaders['notes'],
+                                '\n%(example)s'])
+        self._construct_doc(docdict)
+
+    def freeze(self, *args, **kwds):
+        """Freeze the distribution for the given arguments.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution.  Should include all
+            the non-optional arguments, may include ``loc`` and ``scale``.
+
+        Returns
+        -------
+        rv_frozen : rv_frozen instance
+            The frozen distribution.
+
+        """
+        if isinstance(self, rv_continuous):
+            return rv_continuous_frozen(self, *args, **kwds)
+        else:
+            return rv_discrete_frozen(self, *args, **kwds)
+
+    def __call__(self, *args, **kwds):
+        return self.freeze(*args, **kwds)
+    __call__.__doc__ = freeze.__doc__
+
+    # The actual calculation functions (no basic checking need be done)
+    # If these are defined, the others won't be looked at.
+    # Otherwise, the other set can be defined.
+    def _stats(self, *args, **kwds):
+        return None, None, None, None
+
+    # Noncentral moments (also known as the moment about the origin).
+    # Expressed in LaTeX, munp would be $\mu'_{n}$, i.e. "mu-sub-n-prime".
+    # The primed mu is a widely used notation for the noncentral moment.
+    def _munp(self, n, *args):
+        # Silence floating point warnings from integration.
+        with np.errstate(all='ignore'):
+            vals = self.generic_moment(n, *args)
+        return vals
+
+    def _argcheck_rvs(self, *args, **kwargs):
+        # Handle broadcasting and size validation of the rvs method.
+        # Subclasses should not have to override this method.
+        # The rule is that if `size` is not None, then `size` gives the
+        # shape of the result (integer values of `size` are treated as
+        # tuples with length 1; i.e. `size=3` is the same as `size=(3,)`.)
+        #
+        # `args` is expected to contain the shape parameters (if any), the
+        # location and the scale in a flat tuple (e.g. if there are two
+        # shape parameters `a` and `b`, `args` will be `(a, b, loc, scale)`).
+        # The only keyword argument expected is 'size'.
+        size = kwargs.get('size', None)
+        all_bcast = np.broadcast_arrays(*args)
+
+        def squeeze_left(a):
+            while a.ndim > 0 and a.shape[0] == 1:
+                a = a[0]
+            return a
+
+        # Eliminate trivial leading dimensions.  In the convention
+        # used by numpy's random variate generators, trivial leading
+        # dimensions are effectively ignored.  In other words, when `size`
+        # is given, trivial leading dimensions of the broadcast parameters
+        # in excess of the number of dimensions  in size are ignored, e.g.
+        #   >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]], size=3)
+        #   array([ 1.00104267,  3.00422496,  4.99799278])
+        # If `size` is not given, the exact broadcast shape is preserved:
+        #   >>> np.random.normal([[1, 3, 5]], [[[[0.01]]]])
+        #   array([[[[ 1.00862899,  3.00061431,  4.99867122]]]])
+        #
+        all_bcast = [squeeze_left(a) for a in all_bcast]
+        bcast_shape = all_bcast[0].shape
+        bcast_ndim = all_bcast[0].ndim
+
+        if size is None:
+            size_ = bcast_shape
+        else:
+            size_ = tuple(np.atleast_1d(size))
+
+        # Check compatibility of size_ with the broadcast shape of all
+        # the parameters.  This check is intended to be consistent with
+        # how the numpy random variate generators (e.g. np.random.normal,
+        # np.random.beta) handle their arguments.   The rule is that, if size
+        # is given, it determines the shape of the output.  Broadcasting
+        # can't change the output size.
+
+        # This is the standard broadcasting convention of extending the
+        # shape with fewer dimensions with enough dimensions of length 1
+        # so that the two shapes have the same number of dimensions.
+        ndiff = bcast_ndim - len(size_)
+        if ndiff < 0:
+            bcast_shape = (1,)*(-ndiff) + bcast_shape
+        elif ndiff > 0:
+            size_ = (1,)*ndiff + size_
+
+        # This compatibility test is not standard.  In "regular" broadcasting,
+        # two shapes are compatible if for each dimension, the lengths are the
+        # same or one of the lengths is 1.  Here, the length of a dimension in
+        # size_ must not be less than the corresponding length in bcast_shape.
+        ok = all([bcdim == 1 or bcdim == szdim
+                  for (bcdim, szdim) in zip(bcast_shape, size_)])
+        if not ok:
+            raise ValueError("size does not match the broadcast shape of "
+                             f"the parameters. {size}, {size_}, {bcast_shape}")
+
+        param_bcast = all_bcast[:-2]
+        loc_bcast = all_bcast[-2]
+        scale_bcast = all_bcast[-1]
+
+        return param_bcast, loc_bcast, scale_bcast, size_
+
+    # These are the methods you must define (standard form functions)
+    # NB: generic _pdf, _logpdf, _cdf are different for
+    # rv_continuous and rv_discrete hence are defined in there
+    def _argcheck(self, *args):
+        """Default check for correct values on args and keywords.
+
+        Returns condition array of 1's where arguments are correct and
+         0's where they are not.
+
+        """
+        cond = 1
+        for arg in args:
+            cond = logical_and(cond, (asarray(arg) > 0))
+        return cond
+
+    def _get_support(self, *args, **kwargs):
+        """Return the support of the (unscaled, unshifted) distribution.
+
+        *Must* be overridden by distributions which have support dependent
+        upon the shape parameters of the distribution.  Any such override
+        *must not* set or change any of the class members, as these members
+        are shared amongst all instances of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, ... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+
+        Returns
+        -------
+        a, b : numeric (float, or int or +/-np.inf)
+            end-points of the distribution's support for the specified
+            shape parameters.
+        """
+        return self.a, self.b
+
+    def _support_mask(self, x, *args):
+        a, b = self._get_support(*args)
+        with np.errstate(invalid='ignore'):
+            return (a <= x) & (x <= b)
+
+    def _open_support_mask(self, x, *args):
+        a, b = self._get_support(*args)
+        with np.errstate(invalid='ignore'):
+            return (a < x) & (x < b)
+
+    def _rvs(self, *args, size=None, random_state=None):
+        # This method must handle size being a tuple, and it must
+        # properly broadcast *args and size.  size might be
+        # an empty tuple, which means a scalar random variate is to be
+        # generated.
+
+        # Use basic inverse cdf algorithm for RV generation as default.
+        U = random_state.uniform(size=size)
+        Y = self._ppf(U, *args)
+        return Y
+
+    def _logcdf(self, x, *args):
+        with np.errstate(divide='ignore'):
+            return log(self._cdf(x, *args))
+
+    def _sf(self, x, *args):
+        return 1.0-self._cdf(x, *args)
+
+    def _logsf(self, x, *args):
+        with np.errstate(divide='ignore'):
+            return log(self._sf(x, *args))
+
+    def _ppf(self, q, *args):
+        return self._ppfvec(q, *args)
+
+    def _isf(self, q, *args):
+        return self._ppf(1.0-q, *args)  # use correct _ppf for subclasses
+
+    # These are actually called, and should not be overwritten if you
+    # want to keep error checking.
+    def rvs(self, *args, **kwds):
+        """Random variates of given type.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+        scale : array_like, optional
+            Scale parameter (default=1).
+        size : int or tuple of ints, optional
+            Defining number of random variates (default is 1).
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            If `random_state` is None (or `np.random`), the
+            `numpy.random.RandomState` singleton is used.
+            If `random_state` is an int, a new ``RandomState`` instance is
+            used, seeded with `random_state`.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance, that instance is used.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of given `size`.
+
+        """
+        discrete = kwds.pop('discrete', None)
+        rndm = kwds.pop('random_state', None)
+        args, loc, scale, size = self._parse_args_rvs(*args, **kwds)
+        cond = logical_and(self._argcheck(*args), (scale >= 0))
+        if not np.all(cond):
+            message = ("Domain error in arguments. The `scale` parameter must "
+                       "be positive for all distributions, and many "
+                       "distributions have restrictions on shape parameters. "
+                       f"Please see the `scipy.stats.{self.name}` "
+                       "documentation for details.")
+            raise ValueError(message)
+
+        if np.all(scale == 0):
+            return loc*ones(size, 'd')
+
+        # extra gymnastics needed for a custom random_state
+        if rndm is not None:
+            random_state_saved = self._random_state
+            random_state = check_random_state(rndm)
+        else:
+            random_state = self._random_state
+
+        vals = self._rvs(*args, size=size, random_state=random_state)
+
+        vals = vals * scale + loc
+
+        # do not forget to restore the _random_state
+        if rndm is not None:
+            self._random_state = random_state_saved
+
+        # Cast to int if discrete
+        if discrete and not isinstance(self, rv_sample):
+            if size == ():
+                vals = int(vals)
+            else:
+                vals = vals.astype(np.int64)
+
+        return vals
+
+    def stats(self, *args, **kwds):
+        """Some statistics of the given RV.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional (continuous RVs only)
+            scale parameter (default=1)
+        moments : str, optional
+            composed of letters ['mvsk'] defining which moments to compute:
+            'm' = mean,
+            'v' = variance,
+            's' = (Fisher's) skew,
+            'k' = (Fisher's) kurtosis.
+            (default is 'mv')
+
+        Returns
+        -------
+        stats : sequence
+            of requested moments.
+
+        """
+        args, loc, scale, moments = self._parse_args_stats(*args, **kwds)
+        # scale = 1 by construction for discrete RVs
+        loc, scale = map(asarray, (loc, scale))
+        args = tuple(map(asarray, args))
+        cond = self._argcheck(*args) & (scale > 0) & (loc == loc)
+        output = []
+        default = np.full(shape(cond), fill_value=self.badvalue)
+
+        # Use only entries that are valid in calculation
+        if np.any(cond):
+            goodargs = argsreduce(cond, *(args+(scale, loc)))
+            scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]
+
+            if self._stats_has_moments:
+                mu, mu2, g1, g2 = self._stats(*goodargs,
+                                              **{'moments': moments})
+            else:
+                mu, mu2, g1, g2 = self._stats(*goodargs)
+
+            if 'm' in moments:
+                if mu is None:
+                    mu = self._munp(1, *goodargs)
+                out0 = default.copy()
+                place(out0, cond, mu * scale + loc)
+                output.append(out0)
+
+            if 'v' in moments:
+                if mu2 is None:
+                    mu2p = self._munp(2, *goodargs)
+                    if mu is None:
+                        mu = self._munp(1, *goodargs)
+                    # if mean is inf then var is also inf
+                    with np.errstate(invalid='ignore'):
+                        mu2 = np.where(~np.isinf(mu), mu2p - mu**2, np.inf)
+                out0 = default.copy()
+                place(out0, cond, mu2 * scale * scale)
+                output.append(out0)
+
+            if 's' in moments:
+                if g1 is None:
+                    mu3p = self._munp(3, *goodargs)
+                    if mu is None:
+                        mu = self._munp(1, *goodargs)
+                    if mu2 is None:
+                        mu2p = self._munp(2, *goodargs)
+                        with np.errstate(invalid='ignore'):
+                            mu2 = mu2p - mu * mu
+                    with np.errstate(invalid='ignore'):
+                        mu3 = (-mu*mu - 3*mu2)*mu + mu3p
+                        g1 = mu3 / np.power(mu2, 1.5)
+                out0 = default.copy()
+                place(out0, cond, g1)
+                output.append(out0)
+
+            if 'k' in moments:
+                if g2 is None:
+                    mu4p = self._munp(4, *goodargs)
+                    if mu is None:
+                        mu = self._munp(1, *goodargs)
+                    if mu2 is None:
+                        mu2p = self._munp(2, *goodargs)
+                        with np.errstate(invalid='ignore'):
+                            mu2 = mu2p - mu * mu
+                    if g1 is None:
+                        mu3 = None
+                    else:
+                        # (mu2**1.5) breaks down for nan and inf
+                        mu3 = g1 * np.power(mu2, 1.5)
+                    if mu3 is None:
+                        mu3p = self._munp(3, *goodargs)
+                        with np.errstate(invalid='ignore'):
+                            mu3 = (-mu * mu - 3 * mu2) * mu + mu3p
+                    with np.errstate(invalid='ignore'):
+                        mu4 = ((-mu**2 - 6*mu2) * mu - 4*mu3)*mu + mu4p
+                        g2 = mu4 / mu2**2.0 - 3.0
+                out0 = default.copy()
+                place(out0, cond, g2)
+                output.append(out0)
+        else:  # no valid args
+            output = [default.copy() for _ in moments]
+
+        output = [out[()] for out in output]
+        if len(output) == 1:
+            return output[0]
+        else:
+            return tuple(output)
+
+    def entropy(self, *args, **kwds):
+        """Differential entropy of the RV.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+        scale : array_like, optional  (continuous distributions only).
+            Scale parameter (default=1).
+
+        Notes
+        -----
+        Entropy is defined base `e`:
+
+        >>> import numpy as np
+        >>> from scipy.stats._distn_infrastructure import rv_discrete
+        >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
+        >>> np.allclose(drv.entropy(), np.log(2.0))
+        True
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        # NB: for discrete distributions scale=1 by construction in _parse_args
+        loc, scale = map(asarray, (loc, scale))
+        args = tuple(map(asarray, args))
+        cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
+        output = zeros(shape(cond0), 'd')
+        place(output, (1-cond0), self.badvalue)
+        goodargs = argsreduce(cond0, scale, *args)
+        goodscale = goodargs[0]
+        goodargs = goodargs[1:]
+        place(output, cond0, self.vecentropy(*goodargs) + log(goodscale))
+        return output[()]
+
+    def moment(self, order, *args, **kwds):
+        """non-central moment of distribution of specified order.
+
+        Parameters
+        ----------
+        order : int, order >= 1
+            Order of moment.
+        arg1, arg2, arg3,... : float
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        """
+        n = order
+        shapes, loc, scale = self._parse_args(*args, **kwds)
+        args = np.broadcast_arrays(*(*shapes, loc, scale))
+        *shapes, loc, scale = args
+
+        i0 = np.logical_and(self._argcheck(*shapes), scale > 0)
+        i1 = np.logical_and(i0, loc == 0)
+        i2 = np.logical_and(i0, loc != 0)
+
+        args = argsreduce(i0, *shapes, loc, scale)
+        *shapes, loc, scale = args
+
+        if (floor(n) != n):
+            raise ValueError("Moment must be an integer.")
+        if (n < 0):
+            raise ValueError("Moment must be positive.")
+        mu, mu2, g1, g2 = None, None, None, None
+        if (n > 0) and (n < 5):
+            if self._stats_has_moments:
+                mdict = {'moments': {1: 'm', 2: 'v', 3: 'vs', 4: 'mvsk'}[n]}
+            else:
+                mdict = {}
+            mu, mu2, g1, g2 = self._stats(*shapes, **mdict)
+        val = np.empty(loc.shape)  # val needs to be indexed by loc
+        val[...] = _moment_from_stats(n, mu, mu2, g1, g2, self._munp, shapes)
+
+        # Convert to transformed  X = L + S*Y
+        # E[X^n] = E[(L+S*Y)^n] = L^n sum(comb(n, k)*(S/L)^k E[Y^k], k=0...n)
+        result = zeros(i0.shape)
+        place(result, ~i0, self.badvalue)
+
+        if i1.any():
+            res1 = scale[loc == 0]**n * val[loc == 0]
+            place(result, i1, res1)
+
+        if i2.any():
+            mom = [mu, mu2, g1, g2]
+            arrs = [i for i in mom if i is not None]
+            idx = [i for i in range(4) if mom[i] is not None]
+            if any(idx):
+                arrs = argsreduce(loc != 0, *arrs)
+                j = 0
+                for i in idx:
+                    mom[i] = arrs[j]
+                    j += 1
+            mu, mu2, g1, g2 = mom
+            args = argsreduce(loc != 0, *shapes, loc, scale, val)
+            *shapes, loc, scale, val = args
+
+            res2 = zeros(loc.shape, dtype='d')
+            fac = scale / loc
+            for k in range(n):
+                valk = _moment_from_stats(k, mu, mu2, g1, g2, self._munp,
+                                          shapes)
+                res2 += comb(n, k, exact=True)*fac**k * valk
+            res2 += fac**n * val
+            res2 *= loc**n
+            place(result, i2, res2)
+
+        return result[()]
+
+    def median(self, *args, **kwds):
+        """Median of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            Location parameter, Default is 0.
+        scale : array_like, optional
+            Scale parameter, Default is 1.
+
+        Returns
+        -------
+        median : float
+            The median of the distribution.
+
+        See Also
+        --------
+        rv_discrete.ppf
+            Inverse of the CDF
+
+        """
+        return self.ppf(0.5, *args, **kwds)
+
+    def mean(self, *args, **kwds):
+        """Mean of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        mean : float
+            the mean of the distribution
+
+        """
+        kwds['moments'] = 'm'
+        res = self.stats(*args, **kwds)
+        if isinstance(res, ndarray) and res.ndim == 0:
+            return res[()]
+        return res
+
+    def var(self, *args, **kwds):
+        """Variance of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        var : float
+            the variance of the distribution
+
+        """
+        kwds['moments'] = 'v'
+        res = self.stats(*args, **kwds)
+        if isinstance(res, ndarray) and res.ndim == 0:
+            return res[()]
+        return res
+
+    def std(self, *args, **kwds):
+        """Standard deviation of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        std : float
+            standard deviation of the distribution
+
+        """
+        kwds['moments'] = 'v'
+        res = sqrt(self.stats(*args, **kwds))
+        return res
+
+    def interval(self, confidence, *args, **kwds):
+        """Confidence interval with equal areas around the median.
+
+        Parameters
+        ----------
+        confidence : array_like of float
+            Probability that an rv will be drawn from the returned range.
+            Each value should be in the range [0, 1].
+        arg1, arg2, ... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            location parameter, Default is 0.
+        scale : array_like, optional
+            scale parameter, Default is 1.
+
+        Returns
+        -------
+        a, b : ndarray of float
+            end-points of range that contain ``100 * alpha %`` of the rv's
+            possible values.
+
+        Notes
+        -----
+        This is implemented as ``ppf([p_tail, 1-p_tail])``, where
+        ``ppf`` is the inverse cumulative distribution function and
+        ``p_tail = (1-confidence)/2``. Suppose ``[c, d]`` is the support of a
+        discrete distribution; then ``ppf([0, 1]) == (c-1, d)``. Therefore,
+        when ``confidence=1`` and the distribution is discrete, the left end
+        of the interval will be beyond the support of the distribution.
+        For discrete distributions, the interval will limit the probability
+        in each tail to be less than or equal to ``p_tail`` (usually
+        strictly less).
+
+        """
+        alpha = confidence
+
+        alpha = asarray(alpha)
+        if np.any((alpha > 1) | (alpha < 0)):
+            raise ValueError("alpha must be between 0 and 1 inclusive")
+        q1 = (1.0-alpha)/2
+        q2 = (1.0+alpha)/2
+        a = self.ppf(q1, *args, **kwds)
+        b = self.ppf(q2, *args, **kwds)
+        return a, b
+
+    def support(self, *args, **kwargs):
+        """Support of the distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, ... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            location parameter, Default is 0.
+        scale : array_like, optional
+            scale parameter, Default is 1.
+
+        Returns
+        -------
+        a, b : array_like
+            end-points of the distribution's support.
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwargs)
+        arrs = np.broadcast_arrays(*args, loc, scale)
+        args, loc, scale = arrs[:-2], arrs[-2], arrs[-1]
+        cond = self._argcheck(*args) & (scale > 0)
+        _a, _b = self._get_support(*args)
+        if cond.all():
+            return _a * scale + loc, _b * scale + loc
+        elif cond.ndim == 0:
+            return self.badvalue, self.badvalue
+        # promote bounds to at least float to fill in the badvalue
+        _a, _b = np.asarray(_a).astype('d'), np.asarray(_b).astype('d')
+        out_a, out_b = _a * scale + loc, _b * scale + loc
+        place(out_a, 1-cond, self.badvalue)
+        place(out_b, 1-cond, self.badvalue)
+        return out_a, out_b
+
+    def nnlf(self, theta, x):
+        """Negative loglikelihood function.
+        Notes
+        -----
+        This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the
+        parameters (including loc and scale).
+        """
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+        x = (asarray(x)-loc) / scale
+        n_log_scale = len(x) * log(scale)
+        if np.any(~self._support_mask(x, *args)):
+            return inf
+        return self._nnlf(x, *args) + n_log_scale
+
+    def _nnlf(self, x, *args):
+        return -np.sum(self._logpxf(x, *args), axis=0)
+
+    def _nlff_and_penalty(self, x, args, log_fitfun):
+        # negative log fit function
+        cond0 = ~self._support_mask(x, *args)
+        n_bad = np.count_nonzero(cond0, axis=0)
+        if n_bad > 0:
+            x = argsreduce(~cond0, x)[0]
+        logff = log_fitfun(x, *args)
+        finite_logff = np.isfinite(logff)
+        n_bad += np.sum(~finite_logff, axis=0)
+        if n_bad > 0:
+            penalty = n_bad * log(_XMAX) * 100
+            return -np.sum(logff[finite_logff], axis=0) + penalty
+        return -np.sum(logff, axis=0)
+
+    def _penalized_nnlf(self, theta, x):
+        """Penalized negative loglikelihood function.
+        i.e., - sum (log pdf(x, theta), axis=0) + penalty
+        where theta are the parameters (including loc and scale)
+        """
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+        x = asarray((x-loc) / scale)
+        n_log_scale = len(x) * log(scale)
+        return self._nlff_and_penalty(x, args, self._logpxf) + n_log_scale
+
+    def _penalized_nlpsf(self, theta, x):
+        """Penalized negative log product spacing function.
+        i.e., - sum (log (diff (cdf (x, theta))), axis=0) + penalty
+        where theta are the parameters (including loc and scale)
+        Follows reference [1] of scipy.stats.fit
+        """
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+        x = (np.sort(x) - loc)/scale
+
+        def log_psf(x, *args):
+            x, lj = np.unique(x, return_counts=True)  # fast for sorted x
+            cdf_data = self._cdf(x, *args) if x.size else []
+            if not (x.size and 1 - cdf_data[-1] <= 0):
+                cdf = np.concatenate(([0], cdf_data, [1]))
+                lj = np.concatenate((lj, [1]))
+            else:
+                cdf = np.concatenate(([0], cdf_data))
+            # here we could use logcdf w/ logsumexp trick to take differences,
+            # but in the context of the method, it seems unlikely to matter
+            return lj * np.log(np.diff(cdf) / lj)
+
+        return self._nlff_and_penalty(x, args, log_psf)
+
+
+class _ShapeInfo:
+    def __init__(self, name, integrality=False, domain=(-np.inf, np.inf),
+                 inclusive=(True, True)):
+        self.name = name
+        self.integrality = integrality
+        self.endpoints = domain
+        self.inclusive = inclusive
+
+        domain = list(domain)
+        if np.isfinite(domain[0]) and not inclusive[0]:
+            domain[0] = np.nextafter(domain[0], np.inf)
+        if np.isfinite(domain[1]) and not inclusive[1]:
+            domain[1] = np.nextafter(domain[1], -np.inf)
+        self.domain = domain
+
+
+def _get_fixed_fit_value(kwds, names):
+    """
+    Given names such as ``['f0', 'fa', 'fix_a']``, check that there is
+    at most one non-None value in `kwds` associated with those names.
+    Return that value, or None if none of the names occur in `kwds`.
+    As a side effect, all occurrences of those names in `kwds` are
+    removed.
+    """
+    vals = [(name, kwds.pop(name)) for name in names if name in kwds]
+    if len(vals) > 1:
+        repeated = [name for name, val in vals]
+        raise ValueError("fit method got multiple keyword arguments to "
+                         "specify the same fixed parameter: " +
+                         ', '.join(repeated))
+    return vals[0][1] if vals else None
+
+
+#  continuous random variables: implement maybe later
+#
+#  hf  --- Hazard Function (PDF / SF)
+#  chf  --- Cumulative hazard function (-log(SF))
+#  psf --- Probability sparsity function (reciprocal of the pdf) in
+#                units of percent-point-function (as a function of q).
+#                Also, the derivative of the percent-point function.
+
+
+class rv_continuous(rv_generic):
+    """A generic continuous random variable class meant for subclassing.
+
+    `rv_continuous` is a base class to construct specific distribution classes
+    and instances for continuous random variables. It cannot be used
+    directly as a distribution.
+
+    Parameters
+    ----------
+    momtype : int, optional
+        The type of generic moment calculation to use: 0 for pdf, 1 (default)
+        for ppf.
+    a : float, optional
+        Lower bound of the support of the distribution, default is minus
+        infinity.
+    b : float, optional
+        Upper bound of the support of the distribution, default is plus
+        infinity.
+    xtol : float, optional
+        The tolerance for fixed point calculation for generic ppf.
+    badvalue : float, optional
+        The value in a result arrays that indicates a value that for which
+        some argument restriction is violated, default is np.nan.
+    name : str, optional
+        The name of the instance. This string is used to construct the default
+        example for distributions.
+    longname : str, optional
+        This string is used as part of the first line of the docstring returned
+        when a subclass has no docstring of its own. Note: `longname` exists
+        for backwards compatibility, do not use for new subclasses.
+    shapes : str, optional
+        The shape of the distribution. For example ``"m, n"`` for a
+        distribution that takes two integers as the two shape arguments for all
+        its methods. If not provided, shape parameters will be inferred from
+        the signature of the private methods, ``_pdf`` and ``_cdf`` of the
+        instance.
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    Methods
+    -------
+    rvs
+    pdf
+    logpdf
+    cdf
+    logcdf
+    sf
+    logsf
+    ppf
+    isf
+    moment
+    stats
+    entropy
+    expect
+    median
+    mean
+    std
+    var
+    interval
+    __call__
+    fit
+    fit_loc_scale
+    nnlf
+    support
+
+    Notes
+    -----
+    Public methods of an instance of a distribution class (e.g., ``pdf``,
+    ``cdf``) check their arguments and pass valid arguments to private,
+    computational methods (``_pdf``, ``_cdf``). For ``pdf(x)``, ``x`` is valid
+    if it is within the support of the distribution.
+    Whether a shape parameter is valid is decided by an ``_argcheck`` method
+    (which defaults to checking that its arguments are strictly positive.)
+
+    **Subclassing**
+
+    New random variables can be defined by subclassing the `rv_continuous` class
+    and re-defining at least the ``_pdf`` or the ``_cdf`` method (normalized
+    to location 0 and scale 1).
+
+    If positive argument checking is not correct for your RV
+    then you will also need to re-define the ``_argcheck`` method.
+
+    For most of the scipy.stats distributions, the support interval doesn't
+    depend on the shape parameters. ``x`` being in the support interval is
+    equivalent to ``self.a <= x <= self.b``.  If either of the endpoints of
+    the support do depend on the shape parameters, then
+    i) the distribution must implement the ``_get_support`` method; and
+    ii) those dependent endpoints must be omitted from the distribution's
+    call to the ``rv_continuous`` initializer.
+
+    Correct, but potentially slow defaults exist for the remaining
+    methods but for speed and/or accuracy you can over-ride::
+
+      _logpdf, _cdf, _logcdf, _ppf, _rvs, _isf, _sf, _logsf
+
+    The default method ``_rvs`` relies on the inverse of the cdf, ``_ppf``,
+    applied to a uniform random variate. In order to generate random variates
+    efficiently, either the default ``_ppf`` needs to be overwritten (e.g.
+    if the inverse cdf can expressed in an explicit form) or a sampling
+    method needs to be implemented in a custom ``_rvs`` method.
+
+    If possible, you should override ``_isf``, ``_sf`` or ``_logsf``.
+    The main reason would be to improve numerical accuracy: for example,
+    the survival function ``_sf`` is computed as ``1 - _cdf`` which can
+    result in loss of precision if ``_cdf(x)`` is close to one.
+
+    **Methods that can be overwritten by subclasses**
+    ::
+
+      _rvs
+      _pdf
+      _cdf
+      _sf
+      _ppf
+      _isf
+      _stats
+      _munp
+      _entropy
+      _argcheck
+      _get_support
+
+    There are additional (internal and private) generic methods that can
+    be useful for cross-checking and for debugging, but might work in all
+    cases when directly called.
+
+    A note on ``shapes``: subclasses need not specify them explicitly. In this
+    case, `shapes` will be automatically deduced from the signatures of the
+    overridden methods (`pdf`, `cdf` etc).
+    If, for some reason, you prefer to avoid relying on introspection, you can
+    specify ``shapes`` explicitly as an argument to the instance constructor.
+
+
+    **Frozen Distributions**
+
+    Normally, you must provide shape parameters (and, optionally, location and
+    scale parameters to each call of a method of a distribution.
+
+    Alternatively, the object may be called (as a function) to fix the shape,
+    location, and scale parameters returning a "frozen" continuous RV object:
+
+    rv = generic(, loc=0, scale=1)
+        `rv_frozen` object with the same methods but holding the given shape,
+        location, and scale fixed
+
+    **Statistics**
+
+    Statistics are computed using numerical integration by default.
+    For speed you can redefine this using ``_stats``:
+
+     - take shape parameters and return mu, mu2, g1, g2
+     - If you can't compute one of these, return it as None
+     - Can also be defined with a keyword argument ``moments``, which is a
+       string composed of "m", "v", "s", and/or "k".
+       Only the components appearing in string should be computed and
+       returned in the order "m", "v", "s", or "k"  with missing values
+       returned as None.
+
+    Alternatively, you can override ``_munp``, which takes ``n`` and shape
+    parameters and returns the n-th non-central moment of the distribution.
+
+    **Deepcopying / Pickling**
+
+    If a distribution or frozen distribution is deepcopied (pickled/unpickled,
+    etc.), any underlying random number generator is deepcopied with it. An
+    implication is that if a distribution relies on the singleton RandomState
+    before copying, it will rely on a copy of that random state after copying,
+    and ``np.random.seed`` will no longer control the state.
+
+    Examples
+    --------
+    To create a new Gaussian distribution, we would do the following:
+
+    >>> from scipy.stats import rv_continuous
+    >>> class gaussian_gen(rv_continuous):
+    ...     "Gaussian distribution"
+    ...     def _pdf(self, x):
+    ...         return np.exp(-x**2 / 2.) / np.sqrt(2.0 * np.pi)
+    >>> gaussian = gaussian_gen(name='gaussian')
+
+    ``scipy.stats`` distributions are *instances*, so here we subclass
+    `rv_continuous` and create an instance. With this, we now have
+    a fully functional distribution with all relevant methods automagically
+    generated by the framework.
+
+    Note that above we defined a standard normal distribution, with zero mean
+    and unit variance. Shifting and scaling of the distribution can be done
+    by using ``loc`` and ``scale`` parameters: ``gaussian.pdf(x, loc, scale)``
+    essentially computes ``y = (x - loc) / scale`` and
+    ``gaussian._pdf(y) / scale``.
+
+    """
+
+    def __init__(self, momtype=1, a=None, b=None, xtol=1e-14,
+                 badvalue=None, name=None, longname=None,
+                 shapes=None, seed=None):
+
+        super().__init__(seed)
+
+        # save the ctor parameters, cf generic freeze
+        self._ctor_param = dict(
+            momtype=momtype, a=a, b=b, xtol=xtol,
+            badvalue=badvalue, name=name, longname=longname,
+            shapes=shapes, seed=seed)
+
+        if badvalue is None:
+            badvalue = nan
+        if name is None:
+            name = 'Distribution'
+        self.badvalue = badvalue
+        self.name = name
+        self.a = a
+        self.b = b
+        if a is None:
+            self.a = -inf
+        if b is None:
+            self.b = inf
+        self.xtol = xtol
+        self.moment_type = momtype
+        self.shapes = shapes
+
+        self._construct_argparser(meths_to_inspect=[self._pdf, self._cdf],
+                                  locscale_in='loc=0, scale=1',
+                                  locscale_out='loc, scale')
+        self._attach_methods()
+
+        if longname is None:
+            if name[0] in ['aeiouAEIOU']:
+                hstr = "An "
+            else:
+                hstr = "A "
+            longname = hstr + name
+
+        if sys.flags.optimize < 2:
+            # Skip adding docstrings if interpreter is run with -OO
+            if self.__doc__ is None:
+                self._construct_default_doc(longname=longname,
+                                            docdict=docdict,
+                                            discrete='continuous')
+            else:
+                dct = dict(distcont)
+                self._construct_doc(docdict, dct.get(self.name))
+
+    def __getstate__(self):
+        dct = self.__dict__.copy()
+
+        # these methods will be remade in __setstate__
+        # _random_state attribute is taken care of by rv_generic
+        attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs",
+                 "_cdfvec", "_ppfvec", "vecentropy", "generic_moment"]
+        [dct.pop(attr, None) for attr in attrs]
+        return dct
+
+    def _attach_methods(self):
+        """
+        Attaches dynamically created methods to the rv_continuous instance.
+        """
+        # _attach_methods is responsible for calling _attach_argparser_methods
+        self._attach_argparser_methods()
+
+        # nin correction
+        self._ppfvec = vectorize(self._ppf_single, otypes='d')
+        self._ppfvec.nin = self.numargs + 1
+        self.vecentropy = vectorize(self._entropy, otypes='d')
+        self._cdfvec = vectorize(self._cdf_single, otypes='d')
+        self._cdfvec.nin = self.numargs + 1
+
+        if self.moment_type == 0:
+            self.generic_moment = vectorize(self._mom0_sc, otypes='d')
+        else:
+            self.generic_moment = vectorize(self._mom1_sc, otypes='d')
+        # Because of the *args argument of _mom0_sc, vectorize cannot count the
+        # number of arguments correctly.
+        self.generic_moment.nin = self.numargs + 1
+
+    def _updated_ctor_param(self):
+        """Return the current version of _ctor_param, possibly updated by user.
+
+        Used by freezing.
+        Keep this in sync with the signature of __init__.
+        """
+        dct = self._ctor_param.copy()
+        dct['a'] = self.a
+        dct['b'] = self.b
+        dct['xtol'] = self.xtol
+        dct['badvalue'] = self.badvalue
+        dct['name'] = self.name
+        dct['shapes'] = self.shapes
+        return dct
+
+    def _ppf_to_solve(self, x, q, *args):
+        return self.cdf(*(x, )+args)-q
+
+    def _ppf_single(self, q, *args):
+        factor = 10.
+        left, right = self._get_support(*args)
+
+        if np.isinf(left):
+            left = min(-factor, right)
+            while self._ppf_to_solve(left, q, *args) > 0.:
+                left, right = left * factor, left
+            # left is now such that cdf(left) <= q
+            # if right has changed, then cdf(right) > q
+
+        if np.isinf(right):
+            right = max(factor, left)
+            while self._ppf_to_solve(right, q, *args) < 0.:
+                left, right = right, right * factor
+            # right is now such that cdf(right) >= q
+
+        return optimize.brentq(self._ppf_to_solve,
+                               left, right, args=(q,)+args, xtol=self.xtol)
+
+    # moment from definition
+    def _mom_integ0(self, x, m, *args):
+        return x**m * self.pdf(x, *args)
+
+    def _mom0_sc(self, m, *args):
+        _a, _b = self._get_support(*args)
+        return integrate.quad(self._mom_integ0, _a, _b,
+                              args=(m,)+args)[0]
+
+    # moment calculated using ppf
+    def _mom_integ1(self, q, m, *args):
+        return (self.ppf(q, *args))**m
+
+    def _mom1_sc(self, m, *args):
+        return integrate.quad(self._mom_integ1, 0, 1, args=(m,)+args)[0]
+
+    def _pdf(self, x, *args):
+        return _derivative(self._cdf, x, dx=1e-5, args=args, order=5)
+
+    # Could also define any of these
+    def _logpdf(self, x, *args):
+        p = self._pdf(x, *args)
+        with np.errstate(divide='ignore'):
+            return log(p)
+
+    def _logpxf(self, x, *args):
+        # continuous distributions have PDF, discrete have PMF, but sometimes
+        # the distinction doesn't matter. This lets us use `_logpxf` for both
+        # discrete and continuous distributions.
+        return self._logpdf(x, *args)
+
+    def _cdf_single(self, x, *args):
+        _a, _b = self._get_support(*args)
+        return integrate.quad(self._pdf, _a, x, args=args)[0]
+
+    def _cdf(self, x, *args):
+        return self._cdfvec(x, *args)
+
+    def _logcdf(self, x, *args):
+        median = self._ppf(0.5, *args)
+        with np.errstate(divide='ignore'):
+            return _lazywhere(x < median, (x,) + args,
+                              f=lambda x, *args: np.log(self._cdf(x, *args)),
+                              f2=lambda x, *args: np.log1p(-self._sf(x, *args)))
+
+    def _logsf(self, x, *args):
+        median = self._ppf(0.5, *args)
+        with np.errstate(divide='ignore'):
+            return _lazywhere(x > median, (x,) + args,
+                              f=lambda x, *args: np.log(self._sf(x, *args)),
+                              f2=lambda x, *args: np.log1p(-self._cdf(x, *args)))
+
+    # generic _argcheck, _sf, _ppf, _isf, _rvs are defined
+    # in rv_generic
+
+    def pdf(self, x, *args, **kwds):
+        """Probability density function at x of the given RV.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        pdf : ndarray
+            Probability density function evaluated at x
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._support_mask(x, *args) & (scale > 0)
+        cond = cond0 & cond1
+        output = zeros(shape(cond), dtyp)
+        putmask(output, (1-cond0)+np.isnan(x), self.badvalue)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((x,)+args+(scale,)))
+            scale, goodargs = goodargs[-1], goodargs[:-1]
+            place(output, cond, self._pdf(*goodargs) / scale)
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logpdf(self, x, *args, **kwds):
+        """Log of the probability density function at x of the given RV.
+
+        This uses a more numerically accurate calculation if available.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        logpdf : array_like
+            Log of the probability density function evaluated at x
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._support_mask(x, *args) & (scale > 0)
+        cond = cond0 & cond1
+        output = empty(shape(cond), dtyp)
+        output.fill(-inf)
+        putmask(output, (1-cond0)+np.isnan(x), self.badvalue)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((x,)+args+(scale,)))
+            scale, goodargs = goodargs[-1], goodargs[:-1]
+            place(output, cond, self._logpdf(*goodargs) - log(scale))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def cdf(self, x, *args, **kwds):
+        """
+        Cumulative distribution function of the given RV.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        cdf : ndarray
+            Cumulative distribution function evaluated at `x`
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._open_support_mask(x, *args) & (scale > 0)
+        cond2 = (x >= np.asarray(_b)) & cond0
+        cond = cond0 & cond1
+        output = zeros(shape(cond), dtyp)
+        place(output, (1-cond0)+np.isnan(x), self.badvalue)
+        place(output, cond2, 1.0)
+        if np.any(cond):  # call only if at least 1 entry
+            goodargs = argsreduce(cond, *((x,)+args))
+            place(output, cond, self._cdf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logcdf(self, x, *args, **kwds):
+        """Log of the cumulative distribution function at x of the given RV.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        logcdf : array_like
+            Log of the cumulative distribution function evaluated at x
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._open_support_mask(x, *args) & (scale > 0)
+        cond2 = (x >= _b) & cond0
+        cond = cond0 & cond1
+        output = empty(shape(cond), dtyp)
+        output.fill(-inf)
+        place(output, (1-cond0)*(cond1 == cond1)+np.isnan(x), self.badvalue)
+        place(output, cond2, 0.0)
+        if np.any(cond):  # call only if at least 1 entry
+            goodargs = argsreduce(cond, *((x,)+args))
+            place(output, cond, self._logcdf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def sf(self, x, *args, **kwds):
+        """Survival function (1 - `cdf`) at x of the given RV.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        sf : array_like
+            Survival function evaluated at x
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._open_support_mask(x, *args) & (scale > 0)
+        cond2 = cond0 & (x <= _a)
+        cond = cond0 & cond1
+        output = zeros(shape(cond), dtyp)
+        place(output, (1-cond0)+np.isnan(x), self.badvalue)
+        place(output, cond2, 1.0)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((x,)+args))
+            place(output, cond, self._sf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logsf(self, x, *args, **kwds):
+        """Log of the survival function of the given RV.
+
+        Returns the log of the "survival function," defined as (1 - `cdf`),
+        evaluated at `x`.
+
+        Parameters
+        ----------
+        x : array_like
+            quantiles
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        logsf : ndarray
+            Log of the survival function evaluated at `x`.
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        x, loc, scale = map(asarray, (x, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        dtyp = np.promote_types(x.dtype, np.float64)
+        x = np.asarray((x - loc)/scale, dtype=dtyp)
+        cond0 = self._argcheck(*args) & (scale > 0)
+        cond1 = self._open_support_mask(x, *args) & (scale > 0)
+        cond2 = cond0 & (x <= _a)
+        cond = cond0 & cond1
+        output = empty(shape(cond), dtyp)
+        output.fill(-inf)
+        place(output, (1-cond0)+np.isnan(x), self.badvalue)
+        place(output, cond2, 0.0)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((x,)+args))
+            place(output, cond, self._logsf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def ppf(self, q, *args, **kwds):
+        """Percent point function (inverse of `cdf`) at q of the given RV.
+
+        Parameters
+        ----------
+        q : array_like
+            lower tail probability
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        x : array_like
+            quantile corresponding to the lower tail probability q.
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        q, loc, scale = map(asarray, (q, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
+        cond1 = (0 < q) & (q < 1)
+        cond2 = cond0 & (q == 0)
+        cond3 = cond0 & (q == 1)
+        cond = cond0 & cond1
+        output = np.full(shape(cond), fill_value=self.badvalue)
+
+        lower_bound = _a * scale + loc
+        upper_bound = _b * scale + loc
+        place(output, cond2, argsreduce(cond2, lower_bound)[0])
+        place(output, cond3, argsreduce(cond3, upper_bound)[0])
+
+        if np.any(cond):  # call only if at least 1 entry
+            goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))
+            scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]
+            place(output, cond, self._ppf(*goodargs) * scale + loc)
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def isf(self, q, *args, **kwds):
+        """Inverse survival function (inverse of `sf`) at q of the given RV.
+
+        Parameters
+        ----------
+        q : array_like
+            upper tail probability
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            location parameter (default=0)
+        scale : array_like, optional
+            scale parameter (default=1)
+
+        Returns
+        -------
+        x : ndarray or scalar
+            Quantile corresponding to the upper tail probability q.
+
+        """
+        args, loc, scale = self._parse_args(*args, **kwds)
+        q, loc, scale = map(asarray, (q, loc, scale))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        cond0 = self._argcheck(*args) & (scale > 0) & (loc == loc)
+        cond1 = (0 < q) & (q < 1)
+        cond2 = cond0 & (q == 1)
+        cond3 = cond0 & (q == 0)
+        cond = cond0 & cond1
+        output = np.full(shape(cond), fill_value=self.badvalue)
+
+        lower_bound = _a * scale + loc
+        upper_bound = _b * scale + loc
+        place(output, cond2, argsreduce(cond2, lower_bound)[0])
+        place(output, cond3, argsreduce(cond3, upper_bound)[0])
+
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((q,)+args+(scale, loc)))
+            scale, loc, goodargs = goodargs[-2], goodargs[-1], goodargs[:-2]
+            place(output, cond, self._isf(*goodargs) * scale + loc)
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def _unpack_loc_scale(self, theta):
+        try:
+            loc = theta[-2]
+            scale = theta[-1]
+            args = tuple(theta[:-2])
+        except IndexError as e:
+            raise ValueError("Not enough input arguments.") from e
+        return loc, scale, args
+
+    def _nnlf_and_penalty(self, x, args):
+        """
+        Compute the penalized negative log-likelihood for the
+        "standardized" data (i.e. already shifted by loc and
+        scaled by scale) for the shape parameters in `args`.
+
+        `x` can be a 1D numpy array or a CensoredData instance.
+        """
+        if isinstance(x, CensoredData):
+            # Filter out the data that is not in the support.
+            xs = x._supported(*self._get_support(*args))
+            n_bad = len(x) - len(xs)
+            i1, i2 = xs._interval.T
+            terms = [
+                # logpdf of the noncensored data.
+                self._logpdf(xs._uncensored, *args),
+                # logcdf of the left-censored data.
+                self._logcdf(xs._left, *args),
+                # logsf of the right-censored data.
+                self._logsf(xs._right, *args),
+                # log of probability of the interval-censored data.
+                np.log(self._delta_cdf(i1, i2, *args)),
+            ]
+        else:
+            cond0 = ~self._support_mask(x, *args)
+            n_bad = np.count_nonzero(cond0)
+            if n_bad > 0:
+                x = argsreduce(~cond0, x)[0]
+            terms = [self._logpdf(x, *args)]
+
+        totals, bad_counts = zip(*[_sum_finite(term) for term in terms])
+        total = sum(totals)
+        n_bad += sum(bad_counts)
+
+        return -total + n_bad * _LOGXMAX * 100
+
+    def _penalized_nnlf(self, theta, x):
+        """Penalized negative loglikelihood function.
+
+        i.e., - sum (log pdf(x, theta), axis=0) + penalty
+        where theta are the parameters (including loc and scale)
+        """
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+        if isinstance(x, CensoredData):
+            x = (x - loc) / scale
+            n_log_scale = (len(x) - x.num_censored()) * log(scale)
+        else:
+            x = (x - loc) / scale
+            n_log_scale = len(x) * log(scale)
+
+        return self._nnlf_and_penalty(x, args) + n_log_scale
+
+    def _fitstart(self, data, args=None):
+        """Starting point for fit (shape arguments + loc + scale)."""
+        if args is None:
+            args = (1.0,)*self.numargs
+        loc, scale = self._fit_loc_scale_support(data, *args)
+        return args + (loc, scale)
+
+    def _reduce_func(self, args, kwds, data=None):
+        """
+        Return the (possibly reduced) function to optimize in order to find MLE
+        estimates for the .fit method.
+        """
+        # Convert fixed shape parameters to the standard numeric form: e.g. for
+        # stats.beta, shapes='a, b'. To fix `a`, the caller can give a value
+        # for `f0`, `fa` or 'fix_a'.  The following converts the latter two
+        # into the first (numeric) form.
+        shapes = []
+        if self.shapes:
+            shapes = self.shapes.replace(',', ' ').split()
+            for j, s in enumerate(shapes):
+                key = 'f' + str(j)
+                names = [key, 'f' + s, 'fix_' + s]
+                val = _get_fixed_fit_value(kwds, names)
+                if val is not None:
+                    kwds[key] = val
+
+        args = list(args)
+        Nargs = len(args)
+        fixedn = []
+        names = ['f%d' % n for n in range(Nargs - 2)] + ['floc', 'fscale']
+        x0 = []
+        for n, key in enumerate(names):
+            if key in kwds:
+                fixedn.append(n)
+                args[n] = kwds.pop(key)
+            else:
+                x0.append(args[n])
+
+        methods = {"mle", "mm"}
+        method = kwds.pop('method', "mle").lower()
+        if method == "mm":
+            n_params = len(shapes) + 2 - len(fixedn)
+            exponents = (np.arange(1, n_params+1))[:, np.newaxis]
+            data_moments = np.sum(data[None, :]**exponents/len(data), axis=1)
+
+            def objective(theta, x):
+                return self._moment_error(theta, x, data_moments)
+
+        elif method == "mle":
+            objective = self._penalized_nnlf
+        else:
+            raise ValueError(f"Method '{method}' not available; "
+                             f"must be one of {methods}")
+
+        if len(fixedn) == 0:
+            func = objective
+            restore = None
+        else:
+            if len(fixedn) == Nargs:
+                raise ValueError(
+                    "All parameters fixed. There is nothing to optimize.")
+
+            def restore(args, theta):
+                # Replace with theta for all numbers not in fixedn
+                # This allows the non-fixed values to vary, but
+                #  we still call self.nnlf with all parameters.
+                i = 0
+                for n in range(Nargs):
+                    if n not in fixedn:
+                        args[n] = theta[i]
+                        i += 1
+                return args
+
+            def func(theta, x):
+                newtheta = restore(args[:], theta)
+                return objective(newtheta, x)
+
+        return x0, func, restore, args
+
+    def _moment_error(self, theta, x, data_moments):
+        loc, scale, args = self._unpack_loc_scale(theta)
+        if not self._argcheck(*args) or scale <= 0:
+            return inf
+
+        dist_moments = np.array([self.moment(i+1, *args, loc=loc, scale=scale)
+                                 for i in range(len(data_moments))])
+        if np.any(np.isnan(dist_moments)):
+            raise ValueError("Method of moments encountered a non-finite "
+                             "distribution moment and cannot continue. "
+                             "Consider trying method='MLE'.")
+
+        return (((data_moments - dist_moments) /
+                 np.maximum(np.abs(data_moments), 1e-8))**2).sum()
+
+    def fit(self, data, *args, **kwds):
+        r"""
+        Return estimates of shape (if applicable), location, and scale
+        parameters from data. The default estimation method is Maximum
+        Likelihood Estimation (MLE), but Method of Moments (MM)
+        is also available.
+
+        Starting estimates for the fit are given by input arguments;
+        for any arguments not provided with starting estimates,
+        ``self._fitstart(data)`` is called to generate such.
+
+        One can hold some parameters fixed to specific values by passing in
+        keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)
+        and ``floc`` and ``fscale`` (for location and scale parameters,
+        respectively).
+
+        Parameters
+        ----------
+        data : array_like or `CensoredData` instance
+            Data to use in estimating the distribution parameters.
+        arg1, arg2, arg3,... : floats, optional
+            Starting value(s) for any shape-characterizing arguments (those not
+            provided will be determined by a call to ``_fitstart(data)``).
+            No default value.
+        **kwds : floats, optional
+            - `loc`: initial guess of the distribution's location parameter.
+            - `scale`: initial guess of the distribution's scale parameter.
+
+            Special keyword arguments are recognized as holding certain
+            parameters fixed:
+
+            - f0...fn : hold respective shape parameters fixed.
+              Alternatively, shape parameters to fix can be specified by name.
+              For example, if ``self.shapes == "a, b"``, ``fa`` and ``fix_a``
+              are equivalent to ``f0``, and ``fb`` and ``fix_b`` are
+              equivalent to ``f1``.
+
+            - floc : hold location parameter fixed to specified value.
+
+            - fscale : hold scale parameter fixed to specified value.
+
+            - optimizer : The optimizer to use.  The optimizer must take
+              ``func`` and starting position as the first two arguments,
+              plus ``args`` (for extra arguments to pass to the
+              function to be optimized) and ``disp``.
+              The ``fit`` method calls the optimizer with ``disp=0`` to suppress output.
+              The optimizer must return the estimated parameters.
+
+            - method : The method to use. The default is "MLE" (Maximum
+              Likelihood Estimate); "MM" (Method of Moments)
+              is also available.
+
+        Raises
+        ------
+        TypeError, ValueError
+            If an input is invalid
+        `~scipy.stats.FitError`
+            If fitting fails or the fit produced would be invalid
+
+        Returns
+        -------
+        parameter_tuple : tuple of floats
+            Estimates for any shape parameters (if applicable), followed by
+            those for location and scale. For most random variables, shape
+            statistics will be returned, but there are exceptions (e.g.
+            ``norm``).
+
+        Notes
+        -----
+        With ``method="MLE"`` (default), the fit is computed by minimizing
+        the negative log-likelihood function. A large, finite penalty
+        (rather than infinite negative log-likelihood) is applied for
+        observations beyond the support of the distribution.
+
+        With ``method="MM"``, the fit is computed by minimizing the L2 norm
+        of the relative errors between the first *k* raw (about zero) data
+        moments and the corresponding distribution moments, where *k* is the
+        number of non-fixed parameters.
+        More precisely, the objective function is::
+
+            (((data_moments - dist_moments)
+              / np.maximum(np.abs(data_moments), 1e-8))**2).sum()
+
+        where the constant ``1e-8`` avoids division by zero in case of
+        vanishing data moments. Typically, this error norm can be reduced to
+        zero.
+        Note that the standard method of moments can produce parameters for
+        which some data are outside the support of the fitted distribution;
+        this implementation does nothing to prevent this.
+
+        For either method,
+        the returned answer is not guaranteed to be globally optimal; it
+        may only be locally optimal, or the optimization may fail altogether.
+        If the data contain any of ``np.nan``, ``np.inf``, or ``-np.inf``,
+        the `fit` method will raise a ``RuntimeError``.
+
+        When passing a ``CensoredData`` instance to ``data``, the log-likelihood
+        function is defined as:
+
+        .. math::
+
+            l(\pmb{\theta}; k) & = \sum
+                                    \log(f(k_u; \pmb{\theta}))
+                                + \sum
+                                    \log(F(k_l; \pmb{\theta})) \\
+                                & + \sum
+                                    \log(1 - F(k_r; \pmb{\theta})) \\
+                                & + \sum
+                                    \log(F(k_{\text{high}, i}; \pmb{\theta})
+                                    - F(k_{\text{low}, i}; \pmb{\theta}))
+
+        where :math:`f` and :math:`F` are the pdf and cdf, respectively, of the
+        function being fitted, :math:`\pmb{\theta}` is the parameter vector,
+        :math:`u` are the indices of uncensored observations,
+        :math:`l` are the indices of left-censored observations,
+        :math:`r` are the indices of right-censored observations,
+        subscripts "low"/"high" denote endpoints of interval-censored observations, and
+        :math:`i` are the indices of interval-censored observations.
+
+        Examples
+        --------
+
+        Generate some data to fit: draw random variates from the `beta`
+        distribution
+
+        >>> import numpy as np
+        >>> from scipy.stats import beta
+        >>> a, b = 1., 2.
+        >>> rng = np.random.default_rng(172786373191770012695001057628748821561)
+        >>> x = beta.rvs(a, b, size=1000, random_state=rng)
+
+        Now we can fit all four parameters (``a``, ``b``, ``loc`` and
+        ``scale``):
+
+        >>> a1, b1, loc1, scale1 = beta.fit(x)
+        >>> a1, b1, loc1, scale1
+        (1.0198945204435628, 1.9484708982737828, 4.372241314917588e-05, 0.9979078845964814)
+
+        The fit can be done also using a custom optimizer:
+
+        >>> from scipy.optimize import minimize
+        >>> def custom_optimizer(func, x0, args=(), disp=0):
+        ...     res = minimize(func, x0, args, method="slsqp", options={"disp": disp})
+        ...     if res.success:
+        ...         return res.x
+        ...     raise RuntimeError('optimization routine failed')
+        >>> a1, b1, loc1, scale1 = beta.fit(x, method="MLE", optimizer=custom_optimizer)
+        >>> a1, b1, loc1, scale1
+        (1.0198821087258905, 1.948484145914738, 4.3705304486881485e-05, 0.9979104663953395)
+
+        We can also use some prior knowledge about the dataset: let's keep
+        ``loc`` and ``scale`` fixed:
+
+        >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1)
+        >>> loc1, scale1
+        (0, 1)
+
+        We can also keep shape parameters fixed by using ``f``-keywords. To
+        keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or,
+        equivalently, ``fa=1``:
+
+        >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1)
+        >>> a1
+        1
+
+        Not all distributions return estimates for the shape parameters.
+        ``norm`` for example just returns estimates for location and scale:
+
+        >>> from scipy.stats import norm
+        >>> x = norm.rvs(a, b, size=1000, random_state=123)
+        >>> loc1, scale1 = norm.fit(x)
+        >>> loc1, scale1
+        (0.92087172783841631, 2.0015750750324668)
+        """ # noqa: E501
+        method = kwds.get('method', "mle").lower()
+
+        censored = isinstance(data, CensoredData)
+        if censored:
+            if method != 'mle':
+                raise ValueError('For censored data, the method must'
+                                 ' be "MLE".')
+            if data.num_censored() == 0:
+                # There are no censored values in data, so replace the
+                # CensoredData instance with a regular array.
+                data = data._uncensored
+                censored = False
+
+        Narg = len(args)
+        if Narg > self.numargs:
+            raise TypeError("Too many input arguments.")
+
+        # Check the finiteness of data only if data is not an instance of
+        # CensoredData.  The arrays in a CensoredData instance have already
+        # been validated.
+        if not censored:
+            # Note: `ravel()` is called for backwards compatibility.
+            data = np.asarray(data).ravel()
+            if not np.isfinite(data).all():
+                raise ValueError("The data contains non-finite values.")
+
+        start = [None]*2
+        if (Narg < self.numargs) or not ('loc' in kwds and
+                                         'scale' in kwds):
+            # get distribution specific starting locations
+            start = self._fitstart(data)
+            args += start[Narg:-2]
+        loc = kwds.pop('loc', start[-2])
+        scale = kwds.pop('scale', start[-1])
+        args += (loc, scale)
+        x0, func, restore, args = self._reduce_func(args, kwds, data=data)
+        optimizer = kwds.pop('optimizer', optimize.fmin)
+        # convert string to function in scipy.optimize
+        optimizer = _fit_determine_optimizer(optimizer)
+        # by now kwds must be empty, since everybody took what they needed
+        if kwds:
+            raise TypeError(f"Unknown arguments: {kwds}.")
+
+        # In some cases, method of moments can be done with fsolve/root
+        # instead of an optimizer, but sometimes no solution exists,
+        # especially when the user fixes parameters. Minimizing the sum
+        # of squares of the error generalizes to these cases.
+        vals = optimizer(func, x0, args=(data,), disp=0)
+        obj = func(vals, data)
+
+        if restore is not None:
+            vals = restore(args, vals)
+        vals = tuple(vals)
+
+        loc, scale, shapes = self._unpack_loc_scale(vals)
+        if not (np.all(self._argcheck(*shapes)) and scale > 0):
+            raise FitError("Optimization converged to parameters that are "
+                           "outside the range allowed by the distribution.")
+
+        if method == 'mm':
+            if not np.isfinite(obj):
+                raise FitError("Optimization failed: either a data moment "
+                               "or fitted distribution moment is "
+                               "non-finite.")
+
+        return vals
+
+    def _fit_loc_scale_support(self, data, *args):
+        """Estimate loc and scale parameters from data accounting for support.
+
+        Parameters
+        ----------
+        data : array_like
+            Data to fit.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+
+        Returns
+        -------
+        Lhat : float
+            Estimated location parameter for the data.
+        Shat : float
+            Estimated scale parameter for the data.
+
+        """
+        if isinstance(data, CensoredData):
+            # For this estimate, "uncensor" the data by taking the
+            # given endpoints as the data for the left- or right-censored
+            # data, and the mean for the interval-censored data.
+            data = data._uncensor()
+        else:
+            data = np.asarray(data)
+
+        # Estimate location and scale according to the method of moments.
+        loc_hat, scale_hat = self.fit_loc_scale(data, *args)
+
+        # Compute the support according to the shape parameters.
+        self._argcheck(*args)
+        _a, _b = self._get_support(*args)
+        a, b = _a, _b
+        support_width = b - a
+
+        # If the support is empty then return the moment-based estimates.
+        if support_width <= 0:
+            return loc_hat, scale_hat
+
+        # Compute the proposed support according to the loc and scale
+        # estimates.
+        a_hat = loc_hat + a * scale_hat
+        b_hat = loc_hat + b * scale_hat
+
+        # Use the moment-based estimates if they are compatible with the data.
+        data_a = np.min(data)
+        data_b = np.max(data)
+        if a_hat < data_a and data_b < b_hat:
+            return loc_hat, scale_hat
+
+        # Otherwise find other estimates that are compatible with the data.
+        data_width = data_b - data_a
+        rel_margin = 0.1
+        margin = data_width * rel_margin
+
+        # For a finite interval, both the location and scale
+        # should have interesting values.
+        if support_width < np.inf:
+            loc_hat = (data_a - a) - margin
+            scale_hat = (data_width + 2 * margin) / support_width
+            return loc_hat, scale_hat
+
+        # For a one-sided interval, use only an interesting location parameter.
+        if a > -np.inf:
+            return (data_a - a) - margin, 1
+        elif b < np.inf:
+            return (data_b - b) + margin, 1
+        else:
+            raise RuntimeError
+
+    def fit_loc_scale(self, data, *args):
+        """
+        Estimate loc and scale parameters from data using 1st and 2nd moments.
+
+        Parameters
+        ----------
+        data : array_like
+            Data to fit.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+
+        Returns
+        -------
+        Lhat : float
+            Estimated location parameter for the data.
+        Shat : float
+            Estimated scale parameter for the data.
+
+        """
+        mu, mu2 = self.stats(*args, **{'moments': 'mv'})
+        tmp = asarray(data)
+        muhat = tmp.mean()
+        mu2hat = tmp.var()
+        Shat = sqrt(mu2hat / mu2)
+        with np.errstate(invalid='ignore'):
+            Lhat = muhat - Shat*mu
+        if not np.isfinite(Lhat):
+            Lhat = 0
+        if not (np.isfinite(Shat) and (0 < Shat)):
+            Shat = 1
+        return Lhat, Shat
+
+    def _entropy(self, *args):
+        def integ(x):
+            val = self._pdf(x, *args)
+            return entr(val)
+
+        # upper limit is often inf, so suppress warnings when integrating
+        _a, _b = self._get_support(*args)
+        with np.errstate(over='ignore'):
+            h = integrate.quad(integ, _a, _b)[0]
+
+        if not np.isnan(h):
+            return h
+        else:
+            # try with different limits if integration problems
+            low, upp = self.ppf([1e-10, 1. - 1e-10], *args)
+            if np.isinf(_b):
+                upper = upp
+            else:
+                upper = _b
+            if np.isinf(_a):
+                lower = low
+            else:
+                lower = _a
+            return integrate.quad(integ, lower, upper)[0]
+
+    def expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None,
+               conditional=False, **kwds):
+        """Calculate expected value of a function with respect to the
+        distribution by numerical integration.
+
+        The expected value of a function ``f(x)`` with respect to a
+        distribution ``dist`` is defined as::
+
+                    ub
+            E[f(x)] = Integral(f(x) * dist.pdf(x)),
+                    lb
+
+        where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)``
+        distribution. If the bounds ``lb`` and ``ub`` correspond to the
+        support of the distribution, e.g. ``[-inf, inf]`` in the default
+        case, then the integral is the unrestricted expectation of ``f(x)``.
+        Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0``
+        outside a finite interval in which case the expectation is
+        calculated within the finite range ``[lb, ub]``.
+
+        Parameters
+        ----------
+        func : callable, optional
+            Function for which integral is calculated. Takes only one argument.
+            The default is the identity mapping f(x) = x.
+        args : tuple, optional
+            Shape parameters of the distribution.
+        loc : float, optional
+            Location parameter (default=0).
+        scale : float, optional
+            Scale parameter (default=1).
+        lb, ub : scalar, optional
+            Lower and upper bound for integration. Default is set to the
+            support of the distribution.
+        conditional : bool, optional
+            If True, the integral is corrected by the conditional probability
+            of the integration interval.  The return value is the expectation
+            of the function, conditional on being in the given interval.
+            Default is False.
+
+        Additional keyword arguments are passed to the integration routine.
+
+        Returns
+        -------
+        expect : float
+            The calculated expected value.
+
+        Notes
+        -----
+        The integration behavior of this function is inherited from
+        `scipy.integrate.quad`. Neither this function nor
+        `scipy.integrate.quad` can verify whether the integral exists or is
+        finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and
+        ``cauchy(0).expect()`` returns ``0.0``.
+
+        Likewise, the accuracy of results is not verified by the function.
+        `scipy.integrate.quad` is typically reliable for integrals that are
+        numerically favorable, but it is not guaranteed to converge
+        to a correct value for all possible intervals and integrands. This
+        function is provided for convenience; for critical applications,
+        check results against other integration methods.
+
+        The function is not vectorized.
+
+        Examples
+        --------
+
+        To understand the effect of the bounds of integration consider
+
+        >>> from scipy.stats import expon
+        >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0)
+        0.6321205588285578
+
+        This is close to
+
+        >>> expon(1).cdf(2.0) - expon(1).cdf(0.0)
+        0.6321205588285577
+
+        If ``conditional=True``
+
+        >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True)
+        1.0000000000000002
+
+        The slight deviation from 1 is due to numerical integration.
+
+        The integrand can be treated as a complex-valued function
+        by passing ``complex_func=True`` to `scipy.integrate.quad` .
+
+        >>> import numpy as np
+        >>> from scipy.stats import vonmises
+        >>> res = vonmises(loc=2, kappa=1).expect(lambda x: np.exp(1j*x),
+        ...                                       complex_func=True)
+        >>> res
+        (-0.18576377217422957+0.40590124735052263j)
+
+        >>> np.angle(res)  # location of the (circular) distribution
+        2.0
+
+        """
+        lockwds = {'loc': loc,
+                   'scale': scale}
+        self._argcheck(*args)
+        _a, _b = self._get_support(*args)
+        if func is None:
+            def fun(x, *args):
+                return x * self.pdf(x, *args, **lockwds)
+        else:
+            def fun(x, *args):
+                return func(x) * self.pdf(x, *args, **lockwds)
+        if lb is None:
+            lb = loc + _a * scale
+        if ub is None:
+            ub = loc + _b * scale
+
+        cdf_bounds = self.cdf([lb, ub], *args, **lockwds)
+        invfac = cdf_bounds[1] - cdf_bounds[0]
+
+        kwds['args'] = args
+
+        # split interval to help integrator w/ infinite support; see gh-8928
+        alpha = 0.05  # split body from tails at probability mass `alpha`
+        inner_bounds = np.array([alpha, 1-alpha])
+        cdf_inner_bounds = cdf_bounds[0] + invfac * inner_bounds
+        c, d = loc + self._ppf(cdf_inner_bounds, *args) * scale
+
+        # Do not silence warnings from integration.
+        lbc = integrate.quad(fun, lb, c, **kwds)[0]
+        cd = integrate.quad(fun, c, d, **kwds)[0]
+        dub = integrate.quad(fun, d, ub, **kwds)[0]
+        vals = (lbc + cd + dub)
+
+        if conditional:
+            vals /= invfac
+        return np.array(vals)[()]  # make it a numpy scalar like other methods
+
+    def _param_info(self):
+        shape_info = self._shape_info()
+        loc_info = _ShapeInfo("loc", False, (-np.inf, np.inf), (False, False))
+        scale_info = _ShapeInfo("scale", False, (0, np.inf), (False, False))
+        param_info = shape_info + [loc_info, scale_info]
+        return param_info
+
+    # For now, _delta_cdf is a private method.
+    def _delta_cdf(self, x1, x2, *args, loc=0, scale=1):
+        """
+        Compute CDF(x2) - CDF(x1).
+
+        Where x1 is greater than the median, compute SF(x1) - SF(x2),
+        otherwise compute CDF(x2) - CDF(x1).
+
+        This function is only useful if `dist.sf(x, ...)` has an implementation
+        that is numerically more accurate than `1 - dist.cdf(x, ...)`.
+        """
+        cdf1 = self.cdf(x1, *args, loc=loc, scale=scale)
+        # Possible optimizations (needs investigation-these might not be
+        # better):
+        # * Use _lazywhere instead of np.where
+        # * Instead of cdf1 > 0.5, compare x1 to the median.
+        result = np.where(cdf1 > 0.5,
+                          (self.sf(x1, *args, loc=loc, scale=scale)
+                           - self.sf(x2, *args, loc=loc, scale=scale)),
+                          self.cdf(x2, *args, loc=loc, scale=scale) - cdf1)
+        if result.ndim == 0:
+            result = result[()]
+        return result
+
+
+# Helpers for the discrete distributions
+def _drv2_moment(self, n, *args):
+    """Non-central moment of discrete distribution."""
+    def fun(x):
+        return np.power(x, n) * self._pmf(x, *args)
+
+    _a, _b = self._get_support(*args)
+    return _expect(fun, _a, _b, self._ppf(0.5, *args), self.inc)
+
+
+def _drv2_ppfsingle(self, q, *args):  # Use basic bisection algorithm
+    _a, _b = self._get_support(*args)
+    b = _b
+    a = _a
+
+    step = 10
+    if isinf(b):            # Be sure ending point is > q
+        b = float(max(100*q, 10))
+        while 1:
+            if b >= _b:
+                qb = 1.0
+                break
+            qb = self._cdf(b, *args)
+            if (qb < q):
+                b += step
+                step *= 2
+            else:
+                break
+    else:
+        qb = 1.0
+
+    step = 10
+    if isinf(a):    # be sure starting point < q
+        a = float(min(-100*q, -10))
+        while 1:
+            if a <= _a:
+                qb = 0.0
+                break
+            qa = self._cdf(a, *args)
+            if (qa > q):
+                a -= step
+                step *= 2
+            else:
+                break
+    else:
+        qa = self._cdf(a, *args)
+
+    if np.isinf(a) or np.isinf(b):
+        message = "Arguments that bracket the requested quantile could not be found."
+        raise RuntimeError(message)
+
+    # maximum number of bisections within the normal float64s
+    # maxiter = int(np.log2(finfo.max) - np.log2(finfo.smallest_normal))
+    maxiter = 2046
+    for i in range(maxiter):
+        if (qa == q):
+            return a
+        if (qb == q):
+            return b
+        if b <= a+1:
+            if qa > q:
+                return a
+            else:
+                return b
+        c = int((a+b)/2.0)
+        qc = self._cdf(c, *args)
+        if (qc < q):
+            if a != c:
+                a = c
+            else:
+                raise RuntimeError('updating stopped, endless loop')
+            qa = qc
+        elif (qc > q):
+            if b != c:
+                b = c
+            else:
+                raise RuntimeError('updating stopped, endless loop')
+            qb = qc
+        else:
+            return c
+
+
+# Must over-ride one of _pmf or _cdf or pass in
+#  x_k, p(x_k) lists in initialization
+
+
+class rv_discrete(rv_generic):
+    """A generic discrete random variable class meant for subclassing.
+
+    `rv_discrete` is a base class to construct specific distribution classes
+    and instances for discrete random variables. It can also be used
+    to construct an arbitrary distribution defined by a list of support
+    points and corresponding probabilities.
+
+    Parameters
+    ----------
+    a : float, optional
+        Lower bound of the support of the distribution, default: 0
+    b : float, optional
+        Upper bound of the support of the distribution, default: plus infinity
+    moment_tol : float, optional
+        The tolerance for the generic calculation of moments.
+    values : tuple of two array_like, optional
+        ``(xk, pk)`` where ``xk`` are integers and ``pk`` are the non-zero
+        probabilities between 0 and 1 with ``sum(pk) = 1``. ``xk``
+        and ``pk`` must have the same shape, and ``xk`` must be unique.
+    inc : integer, optional
+        Increment for the support of the distribution.
+        Default is 1. (other values have not been tested)
+    badvalue : float, optional
+        The value in a result arrays that indicates a value that for which
+        some argument restriction is violated, default is np.nan.
+    name : str, optional
+        The name of the instance. This string is used to construct the default
+        example for distributions.
+    longname : str, optional
+        This string is used as part of the first line of the docstring returned
+        when a subclass has no docstring of its own. Note: `longname` exists
+        for backwards compatibility, do not use for new subclasses.
+    shapes : str, optional
+        The shape of the distribution. For example "m, n" for a distribution
+        that takes two integers as the two shape arguments for all its methods
+        If not provided, shape parameters will be inferred from
+        the signatures of the private methods, ``_pmf`` and ``_cdf`` of
+        the instance.
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    Methods
+    -------
+    rvs
+    pmf
+    logpmf
+    cdf
+    logcdf
+    sf
+    logsf
+    ppf
+    isf
+    moment
+    stats
+    entropy
+    expect
+    median
+    mean
+    std
+    var
+    interval
+    __call__
+    support
+
+    Notes
+    -----
+    This class is similar to `rv_continuous`. Whether a shape parameter is
+    valid is decided by an ``_argcheck`` method (which defaults to checking
+    that its arguments are strictly positive.)
+    The main differences are as follows.
+
+    - The support of the distribution is a set of integers.
+    - Instead of the probability density function, ``pdf`` (and the
+      corresponding private ``_pdf``), this class defines the
+      *probability mass function*, `pmf` (and the corresponding
+      private ``_pmf``.)
+    - There is no ``scale`` parameter.
+    - The default implementations of methods (e.g. ``_cdf``) are not designed
+      for distributions with support that is unbounded below (i.e.
+      ``a=-np.inf``), so they must be overridden.
+
+    To create a new discrete distribution, we would do the following:
+
+    >>> from scipy.stats import rv_discrete
+    >>> class poisson_gen(rv_discrete):
+    ...     "Poisson distribution"
+    ...     def _pmf(self, k, mu):
+    ...         return exp(-mu) * mu**k / factorial(k)
+
+    and create an instance::
+
+    >>> poisson = poisson_gen(name="poisson")
+
+    Note that above we defined the Poisson distribution in the standard form.
+    Shifting the distribution can be done by providing the ``loc`` parameter
+    to the methods of the instance. For example, ``poisson.pmf(x, mu, loc)``
+    delegates the work to ``poisson._pmf(x-loc, mu)``.
+
+    **Discrete distributions from a list of probabilities**
+
+    Alternatively, you can construct an arbitrary discrete rv defined
+    on a finite set of values ``xk`` with ``Prob{X=xk} = pk`` by using the
+    ``values`` keyword argument to the `rv_discrete` constructor.
+
+    **Deepcopying / Pickling**
+
+    If a distribution or frozen distribution is deepcopied (pickled/unpickled,
+    etc.), any underlying random number generator is deepcopied with it. An
+    implication is that if a distribution relies on the singleton RandomState
+    before copying, it will rely on a copy of that random state after copying,
+    and ``np.random.seed`` will no longer control the state.
+
+    Examples
+    --------
+    Custom made discrete distribution:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> xk = np.arange(7)
+    >>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)
+    >>> custm = stats.rv_discrete(name='custm', values=(xk, pk))
+    >>>
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.plot(xk, custm.pmf(xk), 'ro', ms=12, mec='r')
+    >>> ax.vlines(xk, 0, custm.pmf(xk), colors='r', lw=4)
+    >>> plt.show()
+
+    Random number generation:
+
+    >>> R = custm.rvs(size=100)
+
+    """
+    def __new__(cls, a=0, b=inf, name=None, badvalue=None,
+                moment_tol=1e-8, values=None, inc=1, longname=None,
+                shapes=None, seed=None):
+
+        if values is not None:
+            # dispatch to a subclass
+            return super().__new__(rv_sample)
+        else:
+            # business as usual
+            return super().__new__(cls)
+
+    def __init__(self, a=0, b=inf, name=None, badvalue=None,
+                 moment_tol=1e-8, values=None, inc=1, longname=None,
+                 shapes=None, seed=None):
+
+        super().__init__(seed)
+
+        # cf generic freeze
+        self._ctor_param = dict(
+            a=a, b=b, name=name, badvalue=badvalue,
+            moment_tol=moment_tol, values=values, inc=inc,
+            longname=longname, shapes=shapes, seed=seed)
+
+        if badvalue is None:
+            badvalue = nan
+        self.badvalue = badvalue
+        self.a = a
+        self.b = b
+        self.moment_tol = moment_tol
+        self.inc = inc
+        self.shapes = shapes
+
+        if values is not None:
+            raise ValueError("rv_discrete.__init__(..., values != None, ...)")
+
+        self._construct_argparser(meths_to_inspect=[self._pmf, self._cdf],
+                                  locscale_in='loc=0',
+                                  # scale=1 for discrete RVs
+                                  locscale_out='loc, 1')
+        self._attach_methods()
+        self._construct_docstrings(name, longname)
+
+    def __getstate__(self):
+        dct = self.__dict__.copy()
+        # these methods will be remade in __setstate__
+        attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs",
+                 "_cdfvec", "_ppfvec", "generic_moment"]
+        [dct.pop(attr, None) for attr in attrs]
+        return dct
+
+    def _attach_methods(self):
+        """Attaches dynamically created methods to the rv_discrete instance."""
+        self._cdfvec = vectorize(self._cdf_single, otypes='d')
+        self.vecentropy = vectorize(self._entropy)
+
+        # _attach_methods is responsible for calling _attach_argparser_methods
+        self._attach_argparser_methods()
+
+        # nin correction needs to be after we know numargs
+        # correct nin for generic moment vectorization
+        _vec_generic_moment = vectorize(_drv2_moment, otypes='d')
+        _vec_generic_moment.nin = self.numargs + 2
+        self.generic_moment = types.MethodType(_vec_generic_moment, self)
+
+        # correct nin for ppf vectorization
+        _vppf = vectorize(_drv2_ppfsingle, otypes='d')
+        _vppf.nin = self.numargs + 2
+        self._ppfvec = types.MethodType(_vppf, self)
+
+        # now that self.numargs is defined, we can adjust nin
+        self._cdfvec.nin = self.numargs + 1
+
+    def _construct_docstrings(self, name, longname):
+        if name is None:
+            name = 'Distribution'
+        self.name = name
+
+        # generate docstring for subclass instances
+        if longname is None:
+            if name[0] in ['aeiouAEIOU']:
+                hstr = "An "
+            else:
+                hstr = "A "
+            longname = hstr + name
+
+        if sys.flags.optimize < 2:
+            # Skip adding docstrings if interpreter is run with -OO
+            if self.__doc__ is None:
+                self._construct_default_doc(longname=longname,
+                                            docdict=docdict_discrete,
+                                            discrete='discrete')
+            else:
+                dct = dict(distdiscrete)
+                self._construct_doc(docdict_discrete, dct.get(self.name))
+
+            # discrete RV do not have the scale parameter, remove it
+            self.__doc__ = self.__doc__.replace(
+                '\n    scale : array_like, '
+                'optional\n        scale parameter (default=1)', '')
+
+    def _updated_ctor_param(self):
+        """Return the current version of _ctor_param, possibly updated by user.
+
+        Used by freezing.
+        Keep this in sync with the signature of __init__.
+        """
+        dct = self._ctor_param.copy()
+        dct['a'] = self.a
+        dct['b'] = self.b
+        dct['badvalue'] = self.badvalue
+        dct['moment_tol'] = self.moment_tol
+        dct['inc'] = self.inc
+        dct['name'] = self.name
+        dct['shapes'] = self.shapes
+        return dct
+
+    def _nonzero(self, k, *args):
+        return floor(k) == k
+
+    def _pmf(self, k, *args):
+        return self._cdf(k, *args) - self._cdf(k-1, *args)
+
+    def _logpmf(self, k, *args):
+        with np.errstate(divide='ignore'):
+            return log(self._pmf(k, *args))
+
+    def _logpxf(self, k, *args):
+        # continuous distributions have PDF, discrete have PMF, but sometimes
+        # the distinction doesn't matter. This lets us use `_logpxf` for both
+        # discrete and continuous distributions.
+        return self._logpmf(k, *args)
+
+    def _unpack_loc_scale(self, theta):
+        try:
+            loc = theta[-1]
+            scale = 1
+            args = tuple(theta[:-1])
+        except IndexError as e:
+            raise ValueError("Not enough input arguments.") from e
+        return loc, scale, args
+
+    def _cdf_single(self, k, *args):
+        _a, _b = self._get_support(*args)
+        m = arange(int(_a), k+1)
+        return np.sum(self._pmf(m, *args), axis=0)
+
+    def _cdf(self, x, *args):
+        k = floor(x).astype(np.float64)
+        return self._cdfvec(k, *args)
+
+    # generic _logcdf, _sf, _logsf, _ppf, _isf, _rvs defined in rv_generic
+
+    def rvs(self, *args, **kwargs):
+        """Random variates of given type.
+
+        Parameters
+        ----------
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+        size : int or tuple of ints, optional
+            Defining number of random variates (Default is 1). Note that `size`
+            has to be given as keyword, not as positional argument.
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            If `random_state` is None (or `np.random`), the
+            `numpy.random.RandomState` singleton is used.
+            If `random_state` is an int, a new ``RandomState`` instance is
+            used, seeded with `random_state`.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance, that instance is used.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of given `size`.
+
+        """
+        kwargs['discrete'] = True
+        return super().rvs(*args, **kwargs)
+
+    def pmf(self, k, *args, **kwds):
+        """Probability mass function at k of the given RV.
+
+        Parameters
+        ----------
+        k : array_like
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information)
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        pmf : array_like
+            Probability mass function evaluated at k
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k <= _b)
+        if not isinstance(self, rv_sample):
+            cond1 = cond1 & self._nonzero(k, *args)
+        cond = cond0 & cond1
+        output = zeros(shape(cond), 'd')
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, np.clip(self._pmf(*goodargs), 0, 1))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logpmf(self, k, *args, **kwds):
+        """Log of the probability mass function at k of the given RV.
+
+        Parameters
+        ----------
+        k : array_like
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter. Default is 0.
+
+        Returns
+        -------
+        logpmf : array_like
+            Log of the probability mass function evaluated at k.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k <= _b)
+        if not isinstance(self, rv_sample):
+            cond1 = cond1 & self._nonzero(k, *args)
+        cond = cond0 & cond1
+        output = empty(shape(cond), 'd')
+        output.fill(-inf)
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, self._logpmf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def cdf(self, k, *args, **kwds):
+        """Cumulative distribution function of the given RV.
+
+        Parameters
+        ----------
+        k : array_like, int
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        cdf : ndarray
+            Cumulative distribution function evaluated at `k`.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k < _b)
+        cond2 = (k >= _b)
+        cond3 = np.isneginf(k)
+        cond = cond0 & cond1 & np.isfinite(k)
+
+        output = zeros(shape(cond), 'd')
+        place(output, cond2*(cond0 == cond0), 1.0)
+        place(output, cond3*(cond0 == cond0), 0.0)
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, np.clip(self._cdf(*goodargs), 0, 1))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logcdf(self, k, *args, **kwds):
+        """Log of the cumulative distribution function at k of the given RV.
+
+        Parameters
+        ----------
+        k : array_like, int
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        logcdf : array_like
+            Log of the cumulative distribution function evaluated at k.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k < _b)
+        cond2 = (k >= _b)
+        cond = cond0 & cond1
+        output = empty(shape(cond), 'd')
+        output.fill(-inf)
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        place(output, cond2*(cond0 == cond0), 0.0)
+
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, self._logcdf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def sf(self, k, *args, **kwds):
+        """Survival function (1 - `cdf`) at k of the given RV.
+
+        Parameters
+        ----------
+        k : array_like
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        sf : array_like
+            Survival function evaluated at k.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k < _b)
+        cond2 = ((k < _a) | np.isneginf(k)) & cond0
+        cond = cond0 & cond1 & np.isfinite(k)
+        output = zeros(shape(cond), 'd')
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        place(output, cond2, 1.0)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, np.clip(self._sf(*goodargs), 0, 1))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def logsf(self, k, *args, **kwds):
+        """Log of the survival function of the given RV.
+
+        Returns the log of the "survival function," defined as 1 - `cdf`,
+        evaluated at `k`.
+
+        Parameters
+        ----------
+        k : array_like
+            Quantiles.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        logsf : ndarray
+            Log of the survival function evaluated at `k`.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        k, loc = map(asarray, (k, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        k = asarray(k-loc)
+        cond0 = self._argcheck(*args)
+        cond1 = (k >= _a) & (k < _b)
+        cond2 = (k < _a) & cond0
+        cond = cond0 & cond1
+        output = empty(shape(cond), 'd')
+        output.fill(-inf)
+        place(output, (1-cond0) + np.isnan(k), self.badvalue)
+        place(output, cond2, 0.0)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((k,)+args))
+            place(output, cond, self._logsf(*goodargs))
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def ppf(self, q, *args, **kwds):
+        """Percent point function (inverse of `cdf`) at q of the given RV.
+
+        Parameters
+        ----------
+        q : array_like
+            Lower tail probability.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        k : array_like
+            Quantile corresponding to the lower tail probability, q.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        q, loc = map(asarray, (q, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        cond0 = self._argcheck(*args) & (loc == loc)
+        cond1 = (q > 0) & (q < 1)
+        cond2 = (q == 1) & cond0
+        cond = cond0 & cond1
+        output = np.full(shape(cond), fill_value=self.badvalue, dtype='d')
+        # output type 'd' to handle nin and inf
+        place(output, (q == 0)*(cond == cond), _a-1 + loc)
+        place(output, cond2, _b + loc)
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((q,)+args+(loc,)))
+            loc, goodargs = goodargs[-1], goodargs[:-1]
+            place(output, cond, self._ppf(*goodargs) + loc)
+
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def isf(self, q, *args, **kwds):
+        """Inverse survival function (inverse of `sf`) at q of the given RV.
+
+        Parameters
+        ----------
+        q : array_like
+            Upper tail probability.
+        arg1, arg2, arg3,... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+        loc : array_like, optional
+            Location parameter (default=0).
+
+        Returns
+        -------
+        k : ndarray or scalar
+            Quantile corresponding to the upper tail probability, q.
+
+        """
+        args, loc, _ = self._parse_args(*args, **kwds)
+        q, loc = map(asarray, (q, loc))
+        args = tuple(map(asarray, args))
+        _a, _b = self._get_support(*args)
+        cond0 = self._argcheck(*args) & (loc == loc)
+        cond1 = (q > 0) & (q < 1)
+        cond2 = (q == 1) & cond0
+        cond3 = (q == 0) & cond0
+        cond = cond0 & cond1
+
+        # same problem as with ppf; copied from ppf and changed
+        output = np.full(shape(cond), fill_value=self.badvalue, dtype='d')
+        # output type 'd' to handle nin and inf
+        lower_bound = _a - 1 + loc
+        upper_bound = _b + loc
+        place(output, cond2*(cond == cond), lower_bound)
+        place(output, cond3*(cond == cond), upper_bound)
+
+        # call place only if at least 1 valid argument
+        if np.any(cond):
+            goodargs = argsreduce(cond, *((q,)+args+(loc,)))
+            loc, goodargs = goodargs[-1], goodargs[:-1]
+            # PB same as ticket 766
+            place(output, cond, self._isf(*goodargs) + loc)
+
+        if output.ndim == 0:
+            return output[()]
+        return output
+
+    def _entropy(self, *args):
+        if hasattr(self, 'pk'):
+            return stats.entropy(self.pk)
+        else:
+            _a, _b = self._get_support(*args)
+            return _expect(lambda x: entr(self._pmf(x, *args)),
+                           _a, _b, self._ppf(0.5, *args), self.inc)
+
+    def expect(self, func=None, args=(), loc=0, lb=None, ub=None,
+               conditional=False, maxcount=1000, tolerance=1e-10, chunksize=32):
+        """
+        Calculate expected value of a function with respect to the distribution
+        for discrete distribution by numerical summation.
+
+        Parameters
+        ----------
+        func : callable, optional
+            Function for which the expectation value is calculated.
+            Takes only one argument.
+            The default is the identity mapping f(k) = k.
+        args : tuple, optional
+            Shape parameters of the distribution.
+        loc : float, optional
+            Location parameter.
+            Default is 0.
+        lb, ub : int, optional
+            Lower and upper bound for the summation, default is set to the
+            support of the distribution, inclusive (``lb <= k <= ub``).
+        conditional : bool, optional
+            If true then the expectation is corrected by the conditional
+            probability of the summation interval. The return value is the
+            expectation of the function, `func`, conditional on being in
+            the given interval (k such that ``lb <= k <= ub``).
+            Default is False.
+        maxcount : int, optional
+            Maximal number of terms to evaluate (to avoid an endless loop for
+            an infinite sum). Default is 1000.
+        tolerance : float, optional
+            Absolute tolerance for the summation. Default is 1e-10.
+        chunksize : int, optional
+            Iterate over the support of a distributions in chunks of this size.
+            Default is 32.
+
+        Returns
+        -------
+        expect : float
+            Expected value.
+
+        Notes
+        -----
+        For heavy-tailed distributions, the expected value may or
+        may not exist,
+        depending on the function, `func`. If it does exist, but the
+        sum converges
+        slowly, the accuracy of the result may be rather low. For instance, for
+        ``zipf(4)``, accuracy for mean, variance in example is only 1e-5.
+        increasing `maxcount` and/or `chunksize` may improve the result,
+        but may also make zipf very slow.
+
+        The function is not vectorized.
+
+        """
+        # Although `args` is just the shape parameters, `poisson_binom` needs this
+        # to split the vector-valued shape into a tuple of separate shapes
+        args, _, _ = self._parse_args(*args)
+
+        if func is None:
+            def fun(x):
+                # loc and args from outer scope
+                return (x+loc)*self._pmf(x, *args)
+        else:
+            def fun(x):
+                # loc and args from outer scope
+                return func(x+loc)*self._pmf(x, *args)
+        # used pmf because _pmf does not check support in randint and there
+        # might be problems(?) with correct self.a, self.b at this stage maybe
+        # not anymore, seems to work now with _pmf
+
+        _a, _b = self._get_support(*args)
+        if lb is None:
+            lb = _a
+        else:
+            lb = lb - loc   # convert bound for standardized distribution
+        if ub is None:
+            ub = _b
+        else:
+            ub = ub - loc   # convert bound for standardized distribution
+        if conditional:
+            invfac = self.sf(lb-1, *args) - self.sf(ub, *args)
+        else:
+            invfac = 1.0
+
+        if isinstance(self, rv_sample):
+            res = self._expect(fun, lb, ub)
+            return res / invfac
+
+        # iterate over the support, starting from the median
+        x0 = self._ppf(0.5, *args)
+        res = _expect(fun, lb, ub, x0, self.inc, maxcount, tolerance, chunksize)
+        return res / invfac
+
+    def _param_info(self):
+        shape_info = self._shape_info()
+        loc_info = _ShapeInfo("loc", True, (-np.inf, np.inf), (False, False))
+        param_info = shape_info + [loc_info]
+        return param_info
+
+
+def _expect(fun, lb, ub, x0, inc, maxcount=1000, tolerance=1e-10,
+            chunksize=32):
+    """Helper for computing the expectation value of `fun`."""
+    # short-circuit if the support size is small enough
+    if (ub - lb) <= chunksize:
+        supp = np.arange(lb, ub+1, inc)
+        vals = fun(supp)
+        return np.sum(vals)
+
+    # otherwise, iterate starting from x0
+    if x0 < lb:
+        x0 = lb
+    if x0 > ub:
+        x0 = ub
+
+    count, tot = 0, 0.
+    # iterate over [x0, ub] inclusive
+    for x in _iter_chunked(x0, ub+1, chunksize=chunksize, inc=inc):
+        count += x.size
+        delta = np.sum(fun(x))
+        tot += delta
+        if abs(delta) < tolerance * x.size:
+            break
+        if count > maxcount:
+            warnings.warn('expect(): sum did not converge',
+                          RuntimeWarning, stacklevel=3)
+            return tot
+
+    # iterate over [lb, x0)
+    for x in _iter_chunked(x0-1, lb-1, chunksize=chunksize, inc=-inc):
+        count += x.size
+        delta = np.sum(fun(x))
+        tot += delta
+        if abs(delta) < tolerance * x.size:
+            break
+        if count > maxcount:
+            warnings.warn('expect(): sum did not converge',
+                          RuntimeWarning, stacklevel=3)
+            break
+
+    return tot
+
+
+def _iter_chunked(x0, x1, chunksize=4, inc=1):
+    """Iterate from x0 to x1 in chunks of chunksize and steps inc.
+
+    x0 must be finite, x1 need not be. In the latter case, the iterator is
+    infinite.
+    Handles both x0 < x1 and x0 > x1. In the latter case, iterates downwards
+    (make sure to set inc < 0.)
+
+    >>> from scipy.stats._distn_infrastructure import _iter_chunked
+    >>> [x for x in _iter_chunked(2, 5, inc=2)]
+    [array([2, 4])]
+    >>> [x for x in _iter_chunked(2, 11, inc=2)]
+    [array([2, 4, 6, 8]), array([10])]
+    >>> [x for x in _iter_chunked(2, -5, inc=-2)]
+    [array([ 2,  0, -2, -4])]
+    >>> [x for x in _iter_chunked(2, -9, inc=-2)]
+    [array([ 2,  0, -2, -4]), array([-6, -8])]
+
+    """
+    if inc == 0:
+        raise ValueError('Cannot increment by zero.')
+    if chunksize <= 0:
+        raise ValueError(f'Chunk size must be positive; got {chunksize}.')
+
+    s = 1 if inc > 0 else -1
+    stepsize = abs(chunksize * inc)
+
+    x = np.copy(x0)
+    while (x - x1) * inc < 0:
+        delta = min(stepsize, abs(x - x1))
+        step = delta * s
+        supp = np.arange(x, x + step, inc)
+        x += step
+        yield supp
+
+
+class rv_sample(rv_discrete):
+    """A 'sample' discrete distribution defined by the support and values.
+
+    The ctor ignores most of the arguments, only needs the `values` argument.
+    """
+
+    def __init__(self, a=0, b=inf, name=None, badvalue=None,
+                 moment_tol=1e-8, values=None, inc=1, longname=None,
+                 shapes=None, seed=None):
+
+        super(rv_discrete, self).__init__(seed)
+
+        if values is None:
+            raise ValueError("rv_sample.__init__(..., values=None,...)")
+
+        # cf generic freeze
+        self._ctor_param = dict(
+            a=a, b=b, name=name, badvalue=badvalue,
+            moment_tol=moment_tol, values=values, inc=inc,
+            longname=longname, shapes=shapes, seed=seed)
+
+        if badvalue is None:
+            badvalue = nan
+        self.badvalue = badvalue
+        self.moment_tol = moment_tol
+        self.inc = inc
+        self.shapes = shapes
+        self.vecentropy = self._entropy
+
+        xk, pk = values
+
+        if np.shape(xk) != np.shape(pk):
+            raise ValueError("xk and pk must have the same shape.")
+        if np.less(pk, 0.0).any():
+            raise ValueError("All elements of pk must be non-negative.")
+        if not np.allclose(np.sum(pk), 1):
+            raise ValueError("The sum of provided pk is not 1.")
+        if not len(set(np.ravel(xk))) == np.size(xk):
+            raise ValueError("xk may not contain duplicate values.")
+
+        indx = np.argsort(np.ravel(xk))
+        self.xk = np.take(np.ravel(xk), indx, 0)
+        self.pk = np.take(np.ravel(pk), indx, 0)
+        self.a = self.xk[0]
+        self.b = self.xk[-1]
+
+        self.qvals = np.cumsum(self.pk, axis=0)
+
+        self.shapes = ' '   # bypass inspection
+
+        self._construct_argparser(meths_to_inspect=[self._pmf],
+                                  locscale_in='loc=0',
+                                  # scale=1 for discrete RVs
+                                  locscale_out='loc, 1')
+
+        self._attach_methods()
+
+        self._construct_docstrings(name, longname)
+
+    def __getstate__(self):
+        dct = self.__dict__.copy()
+
+        # these methods will be remade in rv_generic.__setstate__,
+        # which calls rv_generic._attach_methods
+        attrs = ["_parse_args", "_parse_args_stats", "_parse_args_rvs"]
+        [dct.pop(attr, None) for attr in attrs]
+
+        return dct
+
+    def _attach_methods(self):
+        """Attaches dynamically created argparser methods."""
+        self._attach_argparser_methods()
+
+    def _get_support(self, *args):
+        """Return the support of the (unscaled, unshifted) distribution.
+
+        Parameters
+        ----------
+        arg1, arg2, ... : array_like
+            The shape parameter(s) for the distribution (see docstring of the
+            instance object for more information).
+
+        Returns
+        -------
+        a, b : numeric (float, or int or +/-np.inf)
+            end-points of the distribution's support.
+        """
+        return self.a, self.b
+
+    def _pmf(self, x):
+        return np.select([x == k for k in self.xk],
+                         [np.broadcast_arrays(p, x)[0] for p in self.pk], 0)
+
+    def _cdf(self, x):
+        xx, xxk = np.broadcast_arrays(x[:, None], self.xk)
+        indx = np.argmax(xxk > xx, axis=-1) - 1
+        return self.qvals[indx]
+
+    def _ppf(self, q):
+        qq, sqq = np.broadcast_arrays(q[..., None], self.qvals)
+        indx = argmax(sqq >= qq, axis=-1)
+        return self.xk[indx]
+
+    def _rvs(self, size=None, random_state=None):
+        # Need to define it explicitly, otherwise .rvs() with size=None
+        # fails due to explicit broadcasting in _ppf
+        U = random_state.uniform(size=size)
+        if size is None:
+            U = np.array(U, ndmin=1)
+            Y = self._ppf(U)[0]
+        else:
+            Y = self._ppf(U)
+        return Y
+
+    def _entropy(self):
+        return stats.entropy(self.pk)
+
+    def generic_moment(self, n):
+        n = asarray(n)
+        return np.sum(self.xk**n[np.newaxis, ...] * self.pk, axis=0)
+
+    def _expect(self, fun, lb, ub, *args, **kwds):
+        # ignore all args, just do a brute force summation
+        supp = self.xk[(lb <= self.xk) & (self.xk <= ub)]
+        vals = fun(supp)
+        return np.sum(vals)
+
+
+def _check_shape(argshape, size):
+    """
+    This is a utility function used by `_rvs()` in the class geninvgauss_gen.
+    It compares the tuple argshape to the tuple size.
+
+    Parameters
+    ----------
+    argshape : tuple of integers
+        Shape of the arguments.
+    size : tuple of integers or integer
+        Size argument of rvs().
+
+    Returns
+    -------
+    The function returns two tuples, scalar_shape and bc.
+
+    scalar_shape : tuple
+        Shape to which the 1-d array of random variates returned by
+        _rvs_scalar() is converted when it is copied into the
+        output array of _rvs().
+
+    bc : tuple of booleans
+        bc is an tuple the same length as size. bc[j] is True if the data
+        associated with that index is generated in one call of _rvs_scalar().
+
+    """
+    scalar_shape = []
+    bc = []
+    for argdim, sizedim in zip_longest(argshape[::-1], size[::-1],
+                                       fillvalue=1):
+        if sizedim > argdim or (argdim == sizedim == 1):
+            scalar_shape.append(sizedim)
+            bc.append(True)
+        else:
+            bc.append(False)
+    return tuple(scalar_shape[::-1]), tuple(bc[::-1])
+
+
+def get_distribution_names(namespace_pairs, rv_base_class):
+    """Collect names of statistical distributions and their generators.
+
+    Parameters
+    ----------
+    namespace_pairs : sequence
+        A snapshot of (name, value) pairs in the namespace of a module.
+    rv_base_class : class
+        The base class of random variable generator classes in a module.
+
+    Returns
+    -------
+    distn_names : list of strings
+        Names of the statistical distributions.
+    distn_gen_names : list of strings
+        Names of the generators of the statistical distributions.
+        Note that these are not simply the names of the statistical
+        distributions, with a _gen suffix added.
+
+    """
+    distn_names = []
+    distn_gen_names = []
+    for name, value in namespace_pairs:
+        if name.startswith('_'):
+            continue
+        if name.endswith('_gen') and issubclass(value, rv_base_class):
+            distn_gen_names.append(name)
+        if isinstance(value, rv_base_class):
+            distn_names.append(name)
+    return distn_names, distn_gen_names
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_distr_params.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_distr_params.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bc2a09c78a524a5914cebee7429bf4e0db769f0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_distr_params.py
@@ -0,0 +1,299 @@
+"""
+Sane parameters for stats.distributions.
+"""
+import numpy as np
+
+distcont = [
+    ['alpha', (3.5704770516650459,)],
+    ['anglit', ()],
+    ['arcsine', ()],
+    ['argus', (1.0,)],
+    ['beta', (2.3098496451481823, 0.62687954300963677)],
+    ['betaprime', (5, 6)],
+    ['bradford', (0.29891359763170633,)],
+    ['burr', (10.5, 4.3)],
+    ['burr12', (10, 4)],
+    ['cauchy', ()],
+    ['chi', (78,)],
+    ['chi2', (55,)],
+    ['cosine', ()],
+    ['crystalball', (2.0, 3.0)],
+    ['dgamma', (1.1023326088288166,)],
+    ['dpareto_lognorm', (3, 1.2, 1.5, 2)],
+    ['dweibull', (2.0685080649914673,)],
+    ['erlang', (10,)],
+    ['expon', ()],
+    ['exponnorm', (1.5,)],
+    ['exponpow', (2.697119160358469,)],
+    ['exponweib', (2.8923945291034436, 1.9505288745913174)],
+    ['f', (29, 18)],
+    ['fatiguelife', (29,)],   # correction numargs = 1
+    ['fisk', (3.0857548622253179,)],
+    ['foldcauchy', (4.7164673455831894,)],
+    ['foldnorm', (1.9521253373555869,)],
+    ['gamma', (1.9932305483800778,)],
+    ['gausshyper', (13.763771604130699, 3.1189636648681431,
+                    2.5145980350183019, 5.1811649903971615)],  # veryslow
+    ['genexpon', (9.1325976465418908, 16.231956600590632, 3.2819552690843983)],
+    ['genextreme', (-0.1,)],
+    ['gengamma', (4.4162385429431925, 3.1193091679242761)],
+    ['gengamma', (4.4162385429431925, -3.1193091679242761)],
+    ['genhalflogistic', (0.77274727809929322,)],
+    ['genhyperbolic', (0.5, 1.5, -0.5,)],
+    ['geninvgauss', (2.3, 1.5)],
+    ['genlogistic', (0.41192440799679475,)],
+    ['gennorm', (1.2988442399460265,)],
+    ['halfgennorm', (0.6748054997000371,)],
+    ['genpareto', (0.1,)],   # use case with finite moments
+    ['gibrat', ()],
+    ['gompertz', (0.94743713075105251,)],
+    ['gumbel_l', ()],
+    ['gumbel_r', ()],
+    ['halfcauchy', ()],
+    ['halflogistic', ()],
+    ['halfnorm', ()],
+    ['hypsecant', ()],
+    ['invgamma', (4.0668996136993067,)],
+    ['invgauss', (0.14546264555347513,)],
+    ['invweibull', (10.58,)],
+    ['irwinhall', (10,)],
+    ['jf_skew_t', (8, 4)],
+    ['johnsonsb', (4.3172675099141058, 3.1837781130785063)],
+    ['johnsonsu', (2.554395574161155, 2.2482281679651965)],
+    ['kappa4', (0.0, 0.0)],
+    ['kappa4', (-0.1, 0.1)],
+    ['kappa4', (0.0, 0.1)],
+    ['kappa4', (0.1, 0.0)],
+    ['kappa3', (1.0,)],
+    ['ksone', (1000,)],  # replace 22 by 100 to avoid failing range, ticket 956
+    ['kstwo', (10,)],
+    ['kstwobign', ()],
+    ['landau', ()],
+    ['laplace', ()],
+    ['laplace_asymmetric', (2,)],
+    ['levy', ()],
+    ['levy_l', ()],
+    ['levy_stable', (1.8, -0.5)],
+    ['loggamma', (0.41411931826052117,)],
+    ['logistic', ()],
+    ['loglaplace', (3.2505926592051435,)],
+    ['lognorm', (0.95368226960575331,)],
+    ['loguniform', (0.01, 1.25)],
+    ['lomax', (1.8771398388773268,)],
+    ['maxwell', ()],
+    ['mielke', (10.4, 4.6)],
+    ['moyal', ()],
+    ['nakagami', (4.9673794866666237,)],
+    ['ncf', (27, 27, 0.41578441799226107)],
+    ['nct', (14, 0.24045031331198066)],
+    ['ncx2', (21, 1.0560465975116415)],
+    ['norm', ()],
+    ['norminvgauss', (1.25, 0.5)],
+    ['pareto', (2.621716532144454,)],
+    ['pearson3', (0.1,)],
+    ['pearson3', (-2,)],
+    ['powerlaw', (1.6591133289905851,)],
+    ['powerlaw', (0.6591133289905851,)],
+    ['powerlognorm', (2.1413923530064087, 0.44639540782048337)],
+    ['powernorm', (4.4453652254590779,)],
+    ['rayleigh', ()],
+    ['rdist', (1.6,)],
+    ['recipinvgauss', (0.63004267809369119,)],
+    ['reciprocal', (0.01, 1.25)],
+    ['rel_breitwigner', (36.545206797050334, )],
+    ['rice', (0.7749725210111873,)],
+    ['semicircular', ()],
+    ['skewcauchy', (0.5,)],
+    ['skewnorm', (4.0,)],
+    ['studentized_range', (3.0, 10.0)],
+    ['t', (2.7433514990818093,)],
+    ['trapezoid', (0.2, 0.8)],
+    ['triang', (0.15785029824528218,)],
+    ['truncexpon', (4.6907725456810478,)],
+    ['truncnorm', (-1.0978730080013919, 2.7306754109031979)],
+    ['truncnorm', (0.1, 2.)],
+    ['truncpareto', (1.8, 5.3)],
+    ['truncpareto', (2, 5)],
+    ['truncweibull_min', (2.5, 0.25, 1.75)],
+    ['tukeylambda', (3.1321477856738267,)],
+    ['uniform', ()],
+    ['vonmises', (3.9939042581071398,)],
+    ['vonmises_line', (3.9939042581071398,)],
+    ['wald', ()],
+    ['weibull_max', (2.8687961709100187,)],
+    ['weibull_min', (1.7866166930421596,)],
+    ['wrapcauchy', (0.031071279018614728,)]
+]
+
+
+distdiscrete = [
+    ['bernoulli',(0.3,)],
+    ['betabinom', (5, 2.3, 0.63)],
+    ['betanbinom', (5, 9.3, 1)],
+    ['binom', (5, 0.4)],
+    ['boltzmann',(1.4, 19)],
+    ['dlaplace', (0.8,)],  # 0.5
+    ['geom', (0.5,)],
+    ['hypergeom',(30, 12, 6)],
+    ['hypergeom',(21,3,12)],  # numpy.random (3,18,12) numpy ticket:921
+    ['hypergeom',(21,18,11)],  # numpy.random (18,3,11) numpy ticket:921
+    ['nchypergeom_fisher', (140, 80, 60, 0.5)],
+    ['nchypergeom_wallenius', (140, 80, 60, 0.5)],
+    ['logser', (0.6,)],  # re-enabled, numpy ticket:921
+    ['nbinom', (0.4, 0.4)],  # from tickets: 583
+    ['nbinom', (5, 0.5)],
+    ['planck', (0.51,)],   # 4.1
+    ['poisson', (0.6,)],
+    ['poisson_binom', ([0.1, 0.6, 0.7, 0.8],)],
+    ['randint', (7, 31)],
+    ['skellam', (15, 8)],
+    ['zipf', (6.6,)],
+    ['zipfian', (0.75, 15)],
+    ['zipfian', (1.25, 10)],
+    ['yulesimon', (11.0,)],
+    ['nhypergeom', (20, 7, 1)]
+]
+
+
+invdistdiscrete = [
+    # In each of the following, at least one shape parameter is invalid
+    ['hypergeom', (3, 3, 4)],
+    ['nhypergeom', (5, 2, 8)],
+    ['nchypergeom_fisher', (3, 3, 4, 1)],
+    ['nchypergeom_wallenius', (3, 3, 4, 1)],
+    ['bernoulli', (1.5, )],
+    ['binom', (10, 1.5)],
+    ['betabinom', (10, -0.4, -0.5)],
+    ['betanbinom', (10, -0.4, -0.5)],
+    ['boltzmann', (-1, 4)],
+    ['dlaplace', (-0.5, )],
+    ['geom', (1.5, )],
+    ['logser', (1.5, )],
+    ['nbinom', (10, 1.5)],
+    ['planck', (-0.5, )],
+    ['poisson', (-0.5, )],
+    ['poisson_binom', ([-1, 2, 0.5],)],
+    ['randint', (5, 2)],
+    ['skellam', (-5, -2)],
+    ['zipf', (-2, )],
+    ['yulesimon', (-2, )],
+    ['zipfian', (-0.75, 15)]
+]
+
+
+invdistcont = [
+    # In each of the following, at least one shape parameter is invalid
+    ['alpha', (-1, )],
+    ['anglit', ()],
+    ['arcsine', ()],
+    ['argus', (-1, )],
+    ['beta', (-2, 2)],
+    ['betaprime', (-2, 2)],
+    ['bradford', (-1, )],
+    ['burr', (-1, 1)],
+    ['burr12', (-1, 1)],
+    ['cauchy', ()],
+    ['chi', (-1, )],
+    ['chi2', (-1, )],
+    ['cosine', ()],
+    ['crystalball', (-1, 2)],
+    ['dgamma', (-1, )],
+    ['dpareto_lognorm', (3, -1.2, 1.5, 2)],
+    ['dweibull', (-1, )],
+    ['erlang', (-1, )],
+    ['expon', ()],
+    ['exponnorm', (-1, )],
+    ['exponweib', (1, -1)],
+    ['exponpow', (-1, )],
+    ['f', (10, -10)],
+    ['fatiguelife', (-1, )],
+    ['fisk', (-1, )],
+    ['foldcauchy', (-1, )],
+    ['foldnorm', (-1, )],
+    ['genlogistic', (-1, )],
+    ['gennorm', (-1, )],
+    ['genpareto', (np.inf, )],
+    ['genexpon', (1, 2, -3)],
+    ['genextreme', (np.inf, )],
+    ['genhyperbolic', (0.5, -0.5, -1.5,)],
+    ['gausshyper', (1, 2, 3, -4)],
+    ['gamma', (-1, )],
+    ['gengamma', (-1, 0)],
+    ['genhalflogistic', (-1, )],
+    ['geninvgauss', (1, 0)],
+    ['gibrat', ()],
+    ['gompertz', (-1, )],
+    ['gumbel_r', ()],
+    ['gumbel_l', ()],
+    ['halfcauchy', ()],
+    ['halflogistic', ()],
+    ['halfnorm', ()],
+    ['halfgennorm', (-1, )],
+    ['hypsecant', ()],
+    ['invgamma', (-1, )],
+    ['invgauss', (-1, )],
+    ['invweibull', (-1, )],
+    ['irwinhall', (-1,)],
+    ['irwinhall', (0,)],
+    ['irwinhall', (2.5,)],
+    ['jf_skew_t', (-1, 0)],
+    ['johnsonsb', (1, -2)],
+    ['johnsonsu', (1, -2)],
+    ['kappa4', (np.nan, 0)],
+    ['kappa3', (-1, )],
+    ['ksone', (-1, )],
+    ['kstwo', (-1, )],
+    ['kstwobign', ()],
+    ['landau', ()],
+    ['laplace', ()],
+    ['laplace_asymmetric', (-1, )],
+    ['levy', ()],
+    ['levy_l', ()],
+    ['levy_stable', (-1, 1)],
+    ['logistic', ()],
+    ['loggamma', (-1, )],
+    ['loglaplace', (-1, )],
+    ['lognorm', (-1, )],
+    ['loguniform', (10, 5)],
+    ['lomax', (-1, )],
+    ['maxwell', ()],
+    ['mielke', (1, -2)],
+    ['moyal', ()],
+    ['nakagami', (-1, )],
+    ['ncx2', (-1, 2)],
+    ['ncf', (10, 20, -1)],
+    ['nct', (-1, 2)],
+    ['norm', ()],
+    ['norminvgauss', (5, -10)],
+    ['pareto', (-1, )],
+    ['pearson3', (np.nan, )],
+    ['powerlaw', (-1, )],
+    ['powerlognorm', (1, -2)],
+    ['powernorm', (-1, )],
+    ['rdist', (-1, )],
+    ['rayleigh', ()],
+    ['rice', (-1, )],
+    ['recipinvgauss', (-1, )],
+    ['semicircular', ()],
+    ['skewnorm', (np.inf, )],
+    ['studentized_range', (-1, 1)],
+    ['rel_breitwigner', (-2, )],
+    ['t', (-1, )],
+    ['trapezoid', (0, 2)],
+    ['triang', (2, )],
+    ['truncexpon', (-1, )],
+    ['truncnorm', (10, 5)],
+    ['truncpareto', (-1, 5)],
+    ['truncpareto', (1.8, .5)],
+    ['truncweibull_min', (-2.5, 0.25, 1.75)],
+    ['tukeylambda', (np.nan, )],
+    ['uniform', ()],
+    ['vonmises', (-1, )],
+    ['vonmises_line', (-1, )],
+    ['wald', ()],
+    ['weibull_min', (-1, )],
+    ['weibull_max', (-1, )],
+    ['wrapcauchy', (2, )],
+    ['reciprocal', (15, 10)],
+    ['skewcauchy', (2, )]
+]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_distribution_infrastructure.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_distribution_infrastructure.py
new file mode 100644
index 0000000000000000000000000000000000000000..53691f96ebb275c284f54dc374b03fba44c6b7f1
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_distribution_infrastructure.py
@@ -0,0 +1,5068 @@
+import functools
+from abc import ABC, abstractmethod
+from functools import cached_property
+import math
+
+import numpy as np
+from numpy import inf
+
+from scipy._lib._util import _lazywhere, _rng_spawn
+from scipy._lib._docscrape import ClassDoc, NumpyDocString
+from scipy import special, stats
+from scipy.integrate import tanhsinh as _tanhsinh
+from scipy.optimize._bracket import _bracket_root, _bracket_minimum
+from scipy.optimize._chandrupatla import _chandrupatla, _chandrupatla_minimize
+from scipy.stats._probability_distribution import _ProbabilityDistribution
+from scipy.stats import qmc
+
+# in case we need to distinguish between None and not specified
+# Typically this is used to determine whether the tolerance has been set by the
+# user and make a decision about which method to use to evaluate a distribution
+# function. Sometimes, the logic does not consider the value of the tolerance,
+# only whether this has been defined or not. This is not intended to be the
+# best possible logic; the intent is to establish the structure, which can
+# be refined in follow-up work.
+# See https://github.com/scipy/scipy/pull/21050#discussion_r1714195433.
+_null = object()
+def _isnull(x):
+    return type(x) is object or x is None
+
+__all__ = ['make_distribution', 'Mixture', 'order_statistic',
+           'truncate', 'abs', 'exp', 'log']
+
+# Could add other policies for broadcasting and edge/out-of-bounds case handling
+# For instance, when edge case handling is known not to be needed, it's much
+# faster to turn it off, but it might still be nice to have array conversion
+# and shaping done so the user doesn't need to be so careful.
+_SKIP_ALL = "skip_all"
+# Other cache policies would be useful, too.
+_NO_CACHE = "no_cache"
+
+# TODO:
+#  Test sample dtypes
+#  Add dtype kwarg (especially for distributions with no parameters)
+#  When drawing endpoint/out-of-bounds values of a parameter, draw them from
+#   the endpoints/out-of-bounds region of the full `domain`, not `typical`.
+#  Distributions without shape parameters probably need to accept a `dtype` parameter;
+#    right now they default to float64. If we have them default to float16, they will
+#    need to determine result_type when input is not float16 (overhead).
+#  Test _solve_bounded bracket logic, and decide what to do about warnings
+#  Get test coverage to 100%
+#  Raise when distribution method returns wrong shape/dtype?
+#  Consider ensuring everything is at least 1D for calculations? Would avoid needing
+#    to sprinkle `np.asarray` throughout due to indescriminate conversion of 0D arrays
+#    to scalars
+#  Break up `test_basic`: test each method separately
+#  Fix `sample` for QMCEngine (implementation does not match documentation)
+#  When a parameter is invalid, set only the offending parameter to NaN (if possible)?
+#  `_tanhsinh` special case when there are no abscissae between the limits
+#    example: cdf of uniform betweeen 1.0 and np.nextafter(1.0, np.inf)
+#  check behavior of moment methods when moments are undefined/infinite -
+#    basically OK but needs tests
+#  investigate use of median
+#  implement symmetric distribution
+#  implement composite distribution
+#  implement wrapped distribution
+#  profile/optimize
+#  general cleanup (choose keyword-only parameters)
+#  compare old/new distribution timing
+#  make video
+#  add array API support
+#  why does dist.ilogcdf(-100) not converge to bound? Check solver response to inf
+#  _chandrupatla_minimize should not report xm = fm = NaN when it fails
+#  integrate `logmoment` into `moment`? (Not hard, but enough time and code
+#   complexity to wait for reviewer feedback before adding.)
+#  Eliminate bracket_root error "`min <= a < b <= max` must be True"
+#  Test repr?
+#  use `median` information to improve integration? In some cases this will
+#   speed things up. If it's not needed, it may be about twice as slow. I think
+#   it should depend on the accuracy setting.
+#  in tests, check reference value against that produced using np.vectorize?
+#  add `axis` to `ks_1samp`
+#  User tips for faster execution:
+#  - pass NumPy arrays
+#  - pass inputs of floating point type (not integers)
+#  - prefer NumPy scalars or 0d arrays over other size 1 arrays
+#  - pass no invalid parameters and disable invalid parameter checks with iv_profile
+#  - provide a Generator if you're going to do sampling
+#  add options for drawing parameters: log-spacing
+#  accuracy benchmark suite
+#  Should caches be attributes so we can more easily ensure that they are not
+#   modified when caching is turned off?
+#  Make ShiftedScaledDistribution more efficient - only process underlying
+#   distribution parameters as necessary.
+#  Reconsider `all_inclusive`
+#  Should process_parameters update kwargs rather than returning? Should we
+#   update parameters rather than setting to what process_parameters returns?
+
+# Questions:
+# 1.  I override `__getattr__` so that distribution parameters can be read as
+#     attributes. We don't want uses to try to change them.
+#     - To prevent replacements (dist.a = b), I could override `__setattr__`.
+#     - To prevent in-place modifications, `__getattr__` could return a copy,
+#       or it could set the WRITEABLE flag of the array to false.
+#     Which should I do?
+# 2.  `cache_policy` is supported in several methods where I imagine it being
+#     useful, but it needs to be tested. Before doing that:
+#     - What should the default value be?
+#     - What should the other values be?
+#     Or should we just eliminate this policy?
+# 3.  `validation_policy` is supported in a few places, but it should be checked for
+#     consistency. I have the same questions as for `cache_policy`.
+# 4.  `tol` is currently notional. I think there needs to be way to set
+#     separate `atol` and `rtol`. Some ways I imagine it being used:
+#     - Values can be passed to iterative functions (quadrature, root-finder).
+#     - To control which "method" of a distribution function is used. For
+#       example, if `atol` is set to `1e-12`, it may be acceptable to compute
+#       the complementary CDF as 1 - CDF even when CDF is nearly 1; otherwise,
+#       a (potentially more time-consuming) method would need to be used.
+#     I'm looking for unified suggestions for the interface, not ad hoc ideas
+#     for using tolerances. Suppose the user wants to have more control over
+#     the tolerances used for each method - how do they specify it? It would
+#     probably be easiest for the user if they could pass tolerances into each
+#     method, but it's easiest for us if they can only set it as a property of
+#     the class. Perhaps a dictionary of tolerance settings?
+# 5.  I also envision that accuracy estimates should be reported to the user
+#     somehow. I think my preference would be to return a subclass of an array
+#     with an `error` attribute - yes, really. But this is unlikely to be
+#     popular, so what are other ideas? Again, we need a unified vision here,
+#     not just pointing out difficulties (not all errors are known or easy
+#     to estimate, what to do when errors could compound, etc.).
+# 6.  The term "method" is used to refer to public instance functions,
+#     private instance functions, the "method" string argument, and the means
+#     of calculating the desired quantity (represented by the string argument).
+#     For the sake of disambiguation, shall I rename the "method" string to
+#     "strategy" and refer to the means of calculating the quantity as the
+#     "strategy"?
+
+# Originally, I planned to filter out invalid distribution parameters;
+# distribution implementation functions would always work with "compressed",
+# 1D arrays containing only valid distribution parameters. There are two
+# problems with this:
+# - This essentially requires copying all arrays, even if there is only a
+#   single invalid parameter combination. This is expensive. Then, to output
+#   the original size data to the user, we need to "decompress" the arrays
+#   and fill in the NaNs, so more copying. Unless we branch the code when
+#   there are no invalid data, these copies happen even in the normal case,
+#   where there are no invalid parameter combinations. We should not incur
+#   all this overhead in the normal case.
+# - For methods that accept arguments other than distribution parameters, the
+#   user will pass in arrays that are broadcastable with the original arrays,
+#   not the compressed arrays. This means that this same sort of invalid
+#   value detection needs to be repeated every time one of these methods is
+#   called.
+# The much simpler solution is to keep the data uncompressed but to replace
+# the invalid parameters and arguments with NaNs (and only if some are
+# invalid). With this approach, the copying happens only if/when it is
+# needed. Most functions involved in stats distribution calculations don't
+# mind NaNs; they just return NaN. The behavior "If x_i is NaN, the result
+# is NaN" is explicit in the array API. So this should be fine.
+#
+# Currently, I am still leaving the parameters and function arguments
+# in their broadcasted shapes rather than, say, raveling. The intent
+# is to avoid back and forth reshaping. If authors of distributions have
+# trouble dealing with N-D arrays, we can reconsider this.
+#
+# Another important decision is that the *private* methods must accept
+# the distribution parameters as inputs rather than relying on these
+# cached properties directly (although the public methods typically pass
+# the cached values to the private methods). This is because the elementwise
+# algorithms for quadrature, differentiation, root-finding, and minimization
+# prefer that the input functions are strictly elementwise in the sense
+# that the value output for a given input element does not depend on the
+# shape of the input or that element's location within the input array.
+# When the computation has converged for an element, it is removed from
+# the computation entirely. As a result, the shape of the arrays passed to
+# the function will almost never be broadcastable with the shape of the
+# cached parameter arrays.
+#
+# I've sprinkled in some optimizations for scalars and same-shape/type arrays
+# throughout. The biggest time sinks before were:
+# - broadcast_arrays
+# - result_dtype
+# - is_subdtype
+# It is much faster to check whether these are necessary than to do them.
+
+
+class _Domain(ABC):
+    r""" Representation of the applicable domain of a parameter or variable.
+
+    A `_Domain` object is responsible for storing information about the
+    domain of a parameter or variable, determining whether a value is within
+    the domain (`contains`), and providing a text/mathematical representation
+    of itself (`__str__`). Because the domain of a parameter/variable can have
+    a complicated relationship with other parameters and variables of a
+    distribution, `_Domain` itself does not try to represent all possibilities;
+    in fact, it has no implementation and is meant for subclassing.
+
+    Attributes
+    ----------
+    symbols : dict
+        A map from special numerical values to symbols for use in `__str__`
+
+    Methods
+    -------
+    contains(x)
+        Determine whether the argument is contained within the domain (True)
+        or not (False). Used for input validation.
+    get_numerical_endpoints()
+        Gets the numerical values of the domain endpoints, which may have been
+        defined symbolically.
+    __str__()
+        Returns a text representation of the domain (e.g. ``[0, b)``).
+        Used for generating documentation.
+
+    """
+    symbols = {np.inf: r"\infty", -np.inf: r"-\infty", np.pi: r"\pi", -np.pi: r"-\pi"}
+
+    @abstractmethod
+    def contains(self, x):
+        raise NotImplementedError()
+
+    @abstractmethod
+    def draw(self, n):
+        raise NotImplementedError()
+
+    @abstractmethod
+    def get_numerical_endpoints(self, x):
+        raise NotImplementedError()
+
+    @abstractmethod
+    def __str__(self):
+        raise NotImplementedError()
+
+
+class _SimpleDomain(_Domain):
+    r""" Representation of a simply-connected domain defined by two endpoints.
+
+    Each endpoint may be a finite scalar, positive or negative infinity, or
+    be given by a single parameter. The domain may include the endpoints or
+    not.
+
+    This class still does not provide an implementation of the __str__ method,
+    so it is meant for subclassing (e.g. a subclass for domains on the real
+    line).
+
+    Attributes
+    ----------
+    symbols : dict
+        Inherited. A map from special values to symbols for use in `__str__`.
+    endpoints : 2-tuple of float(s) and/or str(s)
+        A tuple with two values. Each may be either a float (the numerical
+        value of the endpoints of the domain) or a string (the name of the
+        parameters that will define the endpoint).
+    inclusive : 2-tuple of bools
+        A tuple with two boolean values; each indicates whether the
+        corresponding endpoint is included within the domain or not.
+
+    Methods
+    -------
+    define_parameters(*parameters)
+        Records any parameters used to define the endpoints of the domain
+    get_numerical_endpoints(parameter_values)
+        Gets the numerical values of the domain endpoints, which may have been
+        defined symbolically.
+    contains(item, parameter_values)
+        Determines whether the argument is contained within the domain
+
+    """
+    def __init__(self, endpoints=(-inf, inf), inclusive=(False, False)):
+        self.symbols = super().symbols.copy()
+        a, b = endpoints
+        self.endpoints = np.asarray(a)[()], np.asarray(b)[()]
+        self.inclusive = inclusive
+
+    def define_parameters(self, *parameters):
+        r""" Records any parameters used to define the endpoints of the domain.
+
+        Adds the keyword name of each parameter and its text representation
+        to the  `symbols` attribute as key:value pairs.
+        For instance, a parameter may be passed into to a distribution's
+        initializer using the keyword `log_a`, and the corresponding
+        string representation may be '\log(a)'. To form the text
+        representation of the domain for use in documentation, the
+        _Domain object needs to map from the keyword name used in the code
+        to the string representation.
+
+        Returns None, but updates the `symbols` attribute.
+
+        Parameters
+        ----------
+        *parameters : _Parameter objects
+            Parameters that may define the endpoints of the domain.
+
+        """
+        new_symbols = {param.name: param.symbol for param in parameters}
+        self.symbols.update(new_symbols)
+
+    def get_numerical_endpoints(self, parameter_values):
+        r""" Get the numerical values of the domain endpoints.
+
+        Domain endpoints may be defined symbolically. This returns numerical
+        values of the endpoints given numerical values for any variables.
+
+        Parameters
+        ----------
+        parameter_values : dict
+            A dictionary that maps between string variable names and numerical
+            values of parameters, which may define the endpoints.
+
+        Returns
+        -------
+        a, b : ndarray
+            Numerical values of the endpoints
+
+        """
+        # TODO: ensure outputs are floats
+        a, b = self.endpoints
+        # If `a` (`b`) is a string - the name of the parameter that defines
+        # the endpoint of the domain - then corresponding numerical values
+        # will be found in the `parameter_values` dictionary. Otherwise, it is
+        # itself the array of numerical values of the endpoint.
+        try:
+            a = np.asarray(parameter_values.get(a, a))
+            b = np.asarray(parameter_values.get(b, b))
+        except TypeError as e:
+            message = ("The endpoints of the distribution are defined by "
+                       "parameters, but their values were not provided. When "
+                       f"using a private method of {self.__class__}, pass "
+                       "all required distribution parameters as keyword "
+                       "arguments.")
+            raise TypeError(message) from e
+
+        return a, b
+
+    def contains(self, item, parameter_values=None):
+        r"""Determine whether the argument is contained within the domain.
+
+        Parameters
+        ----------
+        item : ndarray
+            The argument
+        parameter_values : dict
+            A dictionary that maps between string variable names and numerical
+            values of parameters, which may define the endpoints.
+
+        Returns
+        -------
+        out : bool
+            True if `item` is within the domain; False otherwise.
+
+        """
+        parameter_values = parameter_values or {}
+        # if self.all_inclusive:
+        #     # Returning a 0d value here makes things much faster.
+        #     # I'm not sure if it's safe, though. If it causes a bug someday,
+        #     # I guess it wasn't.
+        #     # Even if there is no bug because of the shape, it is incorrect for
+        #     # `contains` to return True when there are invalid (e.g. NaN)
+        #     # parameters.
+        #     return np.asarray(True)
+
+        a, b = self.get_numerical_endpoints(parameter_values)
+        left_inclusive, right_inclusive = self.inclusive
+
+        in_left = item >= a if left_inclusive else item > a
+        in_right = item <= b if right_inclusive else item < b
+        return in_left & in_right
+
+
+class _RealDomain(_SimpleDomain):
+    r""" Represents a simply-connected subset of the real line; i.e., an interval
+
+    Completes the implementation of the `_SimpleDomain` class for simple
+    domains on the real line.
+
+    Methods
+    -------
+    define_parameters(*parameters)
+        (Inherited) Records any parameters used to define the endpoints of the
+        domain.
+    get_numerical_endpoints(parameter_values)
+        (Inherited) Gets the numerical values of the domain endpoints, which
+        may have been defined symbolically.
+    contains(item, parameter_values)
+        (Inherited) Determines whether the argument is contained within the
+        domain
+    __str__()
+        Returns a string representation of the domain, e.g. "[a, b)".
+    draw(size, rng, proportions, parameter_values)
+        Draws random values based on the domain. Proportions of values within
+        the domain, on the endpoints of the domain, outside the domain,
+        and having value NaN are specified by `proportions`.
+
+    """
+
+    def __str__(self):
+        a, b = self.endpoints
+        left_inclusive, right_inclusive = self.inclusive
+
+        left = "[" if left_inclusive else "("
+        a = self.symbols.get(a, f"{a}")
+        right = "]" if right_inclusive else ")"
+        b = self.symbols.get(b, f"{b}")
+
+        return f"{left}{a}, {b}{right}"
+
+    def draw(self, n, type_, min, max, squeezed_base_shape, rng=None):
+        r""" Draw random values from the domain.
+
+        Parameters
+        ----------
+        n : int
+            The number of values to be drawn from the domain.
+        type_ : str
+            A string indicating whether the values are
+
+            - strictly within the domain ('in'),
+            - at one of the two endpoints ('on'),
+            - strictly outside the domain ('out'), or
+            - NaN ('nan').
+        min, max : ndarray
+            The endpoints of the domain.
+        squeezed_based_shape : tuple of ints
+            See _RealParameter.draw.
+        rng : np.Generator
+            The Generator used for drawing random values.
+
+        """
+        rng = np.random.default_rng(rng)
+
+        # get copies of min and max with no nans so that uniform doesn't fail
+        min_nn, max_nn = min.copy(), max.copy()
+        i = np.isnan(min_nn) | np.isnan(max_nn)
+        min_nn[i] = 0
+        max_nn[i] = 1
+
+        shape = (n,) + squeezed_base_shape
+
+        if type_ == 'in':
+            z = rng.uniform(min_nn, max_nn, size=shape)
+
+        elif type_ == 'on':
+            z_on_shape = shape
+            z = np.ones(z_on_shape)
+            i = rng.random(size=n) < 0.5
+            z[i] = min
+            z[~i] = max
+
+        elif type_ == 'out':
+            # make this work for infinite bounds
+            z = min_nn - rng.uniform(size=shape)
+            zr = max_nn + rng.uniform(size=shape)
+            i = rng.random(size=n) < 0.5
+            z[i] = zr[i]
+
+        elif type_ == 'nan':
+            z = np.full(shape, np.nan)
+
+        return z
+
+
+class _IntegerDomain(_SimpleDomain):
+    r""" Representation of a domain of consecutive integers.
+
+    Completes the implementation of the `_SimpleDomain` class for domains
+    composed of consecutive integer values.
+
+    To be completed when needed.
+    """
+    def __init__(self):
+        raise NotImplementedError
+
+
+class _Parameter(ABC):
+    r""" Representation of a distribution parameter or variable.
+
+    A `_Parameter` object is responsible for storing information about a
+    parameter or variable, providing input validation/standardization of
+    values passed for that parameter, providing a text/mathematical
+    representation of the parameter for the documentation (`__str__`), and
+    drawing random values of itself for testing and benchmarking. It does
+    not provide a complete implementation of this functionality and is meant
+    for subclassing.
+
+    Attributes
+    ----------
+    name : str
+        The keyword used to pass numerical values of the parameter into the
+        initializer of the distribution
+    symbol : str
+        The text representation of the variable in the documentation. May
+        include LaTeX.
+    domain : _Domain
+        The domain of the parameter for which the distribution is valid.
+    typical : 2-tuple of floats or strings (consider making a _Domain)
+        Defines the endpoints of a typical range of values of the parameter.
+        Used for sampling.
+
+    Methods
+    -------
+    __str__():
+        Returns a string description of the variable for use in documentation,
+        including the keyword used to represent it in code, the symbol used to
+        represent it mathemtatically, and a description of the valid domain.
+    draw(size, *, rng, domain, proportions)
+        Draws random values of the parameter. Proportions of values within
+        the valid domain, on the endpoints of the domain, outside the domain,
+        and having value NaN are specified by `proportions`.
+    validate(x):
+        Validates and standardizes the argument for use as numerical values
+        of the parameter.
+
+   """
+    def __init__(self, name, *, domain, symbol=None, typical=None):
+        self.name = name
+        self.symbol = symbol or name
+        self.domain = domain
+        if typical is not None and not isinstance(typical, _Domain):
+            typical = _RealDomain(typical)
+        self.typical = typical or domain
+
+    def __str__(self):
+        r""" String representation of the parameter for use in documentation."""
+        return f"`{self.name}` for :math:`{self.symbol} \\in {str(self.domain)}`"
+
+    def draw(self, size=None, *, rng=None, region='domain', proportions=None,
+             parameter_values=None):
+        r""" Draw random values of the parameter for use in testing.
+
+        Parameters
+        ----------
+        size : tuple of ints
+            The shape of the array of valid values to be drawn.
+        rng : np.Generator
+            The Generator used for drawing random values.
+        region : str
+            The region of the `_Parameter` from which to draw. Default is
+            "domain" (the *full* domain); alternative is "typical". An
+            enhancement would give a way to interpolate between the two.
+        proportions : tuple of numbers
+            A tuple of four non-negative numbers that indicate the expected
+            relative proportion of elements that:
+
+            - are strictly within the domain,
+            - are at one of the two endpoints,
+            - are strictly outside the domain, and
+            - are NaN,
+
+            respectively. Default is (1, 0, 0, 0). The number of elements in
+            each category is drawn from the multinomial distribution with
+            `np.prod(size)` as the number of trials and `proportions` as the
+            event probabilities. The values in `proportions` are automatically
+            normalized to sum to 1.
+        parameter_values : dict
+            Map between the names of parameters (that define the endpoints of
+            `typical`) and numerical values (arrays).
+
+        """
+        parameter_values = parameter_values or {}
+        domain = self.domain
+        proportions = (1, 0, 0, 0) if proportions is None else proportions
+
+        pvals = proportions / np.sum(proportions)
+
+        a, b = domain.get_numerical_endpoints(parameter_values)
+        a, b = np.broadcast_arrays(a, b)
+
+        base_shape = a.shape
+        extended_shape = np.broadcast_shapes(size, base_shape)
+        n_extended = np.prod(extended_shape)
+        n_base = np.prod(base_shape)
+        n = int(n_extended / n_base) if n_extended else 0
+
+        rng = np.random.default_rng(rng)
+        n_in, n_on, n_out, n_nan = rng.multinomial(n, pvals)
+
+        # `min` and `max` can have singleton dimensions that correspond with
+        # non-singleton dimensions in `size`. We need to be careful to avoid
+        # shuffling results (e.g. a value that was generated for the domain
+        # [min[i], max[i]] ends up at index j). To avoid this:
+        # - Squeeze the singleton dimensions out of `min`/`max`. Squeezing is
+        #   often not the right thing to do, but here is equivalent to moving
+        #   all the dimensions that are singleton in `min`/`max` (which may be
+        #   non-singleton in the result) to the left. This is what we want.
+        # - Now all the non-singleton dimensions of the result are on the left.
+        #   Ravel them to a single dimension of length `n`, which is now along
+        #   the 0th axis.
+        # - Reshape the 0th axis back to the required dimensions, and move
+        #   these axes back to their original places.
+        base_shape_padded = ((1,)*(len(extended_shape) - len(base_shape))
+                             + base_shape)
+        base_singletons = np.where(np.asarray(base_shape_padded)==1)[0]
+        new_base_singletons = tuple(range(len(base_singletons)))
+        # Base singleton dimensions are going to get expanded to these lengths
+        shape_expansion = np.asarray(extended_shape)[base_singletons]
+
+        # assert(np.prod(shape_expansion) == n)  # check understanding
+        # min = np.reshape(min, base_shape_padded)
+        # max = np.reshape(max, base_shape_padded)
+        # min = np.moveaxis(min, base_singletons, new_base_singletons)
+        # max = np.moveaxis(max, base_singletons, new_base_singletons)
+        # squeezed_base_shape = max.shape[len(base_singletons):]
+        # assert np.all(min.reshape(squeezed_base_shape) == min.squeeze())
+        # assert np.all(max.reshape(squeezed_base_shape) == max.squeeze())
+
+        # min = np.maximum(a, _fiinfo(a).min/10) if np.any(np.isinf(a)) else a
+        # max = np.minimum(b, _fiinfo(b).max/10) if np.any(np.isinf(b)) else b
+        min = np.asarray(a.squeeze())
+        max = np.asarray(b.squeeze())
+        squeezed_base_shape = max.shape
+
+        if region == 'typical':
+            typical = self.typical
+            a, b = typical.get_numerical_endpoints(parameter_values)
+            a, b = np.broadcast_arrays(a, b)
+            min_here = np.asarray(a.squeeze())
+            max_here = np.asarray(b.squeeze())
+            z_in = typical.draw(n_in, 'in', min_here, max_here, squeezed_base_shape,
+                                rng=rng)
+        else:
+            z_in = domain.draw(n_in, 'in', min, max, squeezed_base_shape, rng=rng)
+        z_on = domain.draw(n_on, 'on', min, max, squeezed_base_shape, rng=rng)
+        z_out = domain.draw(n_out, 'out', min, max, squeezed_base_shape, rng=rng)
+        z_nan= domain.draw(n_nan, 'nan', min, max, squeezed_base_shape, rng=rng)
+
+        z = np.concatenate((z_in, z_on, z_out, z_nan), axis=0)
+        z = rng.permuted(z, axis=0)
+
+        z = np.reshape(z, tuple(shape_expansion) + squeezed_base_shape)
+        z = np.moveaxis(z, new_base_singletons, base_singletons)
+        return z
+
+    @abstractmethod
+    def validate(self, arr):
+        raise NotImplementedError()
+
+
+class _RealParameter(_Parameter):
+    r""" Represents a real-valued parameter.
+
+    Implements the remaining methods of _Parameter for real parameters.
+    All attributes are inherited.
+
+    """
+    def validate(self, arr, parameter_values):
+        r""" Input validation/standardization of numerical values of a parameter.
+
+        Checks whether elements of the argument `arr` are reals, ensuring that
+        the dtype reflects this. Also produces a logical array that indicates
+        which elements meet the requirements.
+
+        Parameters
+        ----------
+        arr : ndarray
+            The argument array to be validated and standardized.
+        parameter_values : dict
+            Map of parameter names to parameter value arrays.
+
+        Returns
+        -------
+        arr : ndarray
+            The argument array that has been validated and standardized
+            (converted to an appropriate dtype, if necessary).
+        dtype : NumPy dtype
+            The appropriate floating point dtype of the parameter.
+        valid : boolean ndarray
+            Logical array indicating which elements are valid (True) and
+            which are not (False). The arrays of all distribution parameters
+            will be broadcasted, and elements for which any parameter value
+            does not meet the requirements will be replaced with NaN.
+
+        """
+        arr = np.asarray(arr)
+
+        valid_dtype = None
+        # minor optimization - fast track the most common types to avoid
+        # overhead of np.issubdtype. Checking for `in {...}` doesn't work : /
+        if arr.dtype == np.float64 or arr.dtype == np.float32:
+            pass
+        elif arr.dtype == np.int32 or arr.dtype == np.int64:
+            arr = np.asarray(arr, dtype=np.float64)
+        elif np.issubdtype(arr.dtype, np.floating):
+            pass
+        elif np.issubdtype(arr.dtype, np.integer):
+            arr = np.asarray(arr, dtype=np.float64)
+        else:
+            message = f"Parameter `{self.name}` must be of real dtype."
+            raise TypeError(message)
+
+        valid = self.domain.contains(arr, parameter_values)
+        valid = valid & valid_dtype if valid_dtype is not None else valid
+
+        return arr[()], arr.dtype, valid
+
+
+class _Parameterization:
+    r""" Represents a parameterization of a distribution.
+
+    Distributions can have multiple parameterizations. A `_Parameterization`
+    object is responsible for recording the parameters used by the
+    parameterization, checking whether keyword arguments passed to the
+    distribution match the parameterization, and performing input validation
+    of the numerical values of these parameters.
+
+    Attributes
+    ----------
+    parameters : dict
+        String names (of keyword arguments) and the corresponding _Parameters.
+
+    Methods
+    -------
+    __len__()
+        Returns the number of parameters in the parameterization.
+    __str__()
+        Returns a string representation of the parameterization.
+    copy
+        Returns a copy of the parameterization. This is needed for transformed
+        distributions that add parameters to the parameterization.
+    matches(parameters)
+        Checks whether the keyword arguments match the parameterization.
+    validation(parameter_values)
+        Input validation / standardization of parameterization. Validates the
+        numerical values of all parameters.
+    draw(sizes, rng, proportions)
+        Draw random values of all parameters of the parameterization for use
+        in testing.
+    """
+    def __init__(self, *parameters):
+        self.parameters = {param.name: param for param in parameters}
+
+    def __len__(self):
+        return len(self.parameters)
+
+    def copy(self):
+        return _Parameterization(*self.parameters.values())
+
+    def matches(self, parameters):
+        r""" Checks whether the keyword arguments match the parameterization.
+
+        Parameters
+        ----------
+        parameters : set
+            Set of names of parameters passed into the distribution as keyword
+            arguments.
+
+        Returns
+        -------
+        out : bool
+            True if the keyword arguments names match the names of the
+            parameters of this parameterization.
+        """
+        return parameters == set(self.parameters.keys())
+
+    def validation(self, parameter_values):
+        r""" Input validation / standardization of parameterization.
+
+        Parameters
+        ----------
+        parameter_values : dict
+            The keyword arguments passed as parameter values to the
+            distribution.
+
+        Returns
+        -------
+        all_valid : ndarray
+            Logical array indicating the elements of the broadcasted arrays
+            for which all parameter values are valid.
+        dtype : dtype
+            The common dtype of the parameter arrays. This will determine
+            the dtype of the output of distribution methods.
+        """
+        all_valid = True
+        dtypes = set()  # avoid np.result_type if there's only one type
+        for name, arr in parameter_values.items():
+            parameter = self.parameters[name]
+            arr, dtype, valid = parameter.validate(arr, parameter_values)
+            dtypes.add(dtype)
+            all_valid = all_valid & valid
+            parameter_values[name] = arr
+        dtype = arr.dtype if len(dtypes)==1 else np.result_type(*list(dtypes))
+
+        return all_valid, dtype
+
+    def __str__(self):
+        r"""Returns a string representation of the parameterization."""
+        messages = [str(param) for name, param in self.parameters.items()]
+        return ", ".join(messages)
+
+    def draw(self, sizes=None, rng=None, proportions=None, region='domain'):
+        r"""Draw random values of all parameters for use in testing.
+
+        Parameters
+        ----------
+        sizes : iterable of shape tuples
+            The size of the array to be generated for each parameter in the
+            parameterization. Note that the order of sizes is arbitary; the
+            size of the array generated for a specific parameter is not
+            controlled individually as written.
+        rng : NumPy Generator
+            The generator used to draw random values.
+        proportions : tuple
+            A tuple of four non-negative numbers that indicate the expected
+            relative proportion of elements that are within the parameter's
+            domain, are on the boundary of the parameter's domain, are outside
+            the parameter's domain, and have value NaN. For more information,
+            see the `draw` method of the _Parameter subclasses.
+        domain : str
+            The domain of the `_Parameter` from which to draw. Default is
+            "domain" (the *full* domain); alternative is "typical".
+
+        Returns
+        -------
+        parameter_values : dict (string: array)
+            A dictionary of parameter name/value pairs.
+        """
+        # ENH: be smart about the order. The domains of some parameters
+        # depend on others. If the relationshp is simple (e.g. a < b < c),
+        # we can draw values in order a, b, c.
+        parameter_values = {}
+
+        if not len(sizes) or not np.iterable(sizes[0]):
+            sizes = [sizes]*len(self.parameters)
+
+        for size, param in zip(sizes, self.parameters.values()):
+            parameter_values[param.name] = param.draw(
+                size, rng=rng, proportions=proportions,
+                parameter_values=parameter_values,
+                region=region
+            )
+
+        return parameter_values
+
+
+def _set_invalid_nan(f):
+    # Wrapper for input / output validation and standardization of distribution
+    # functions that accept either the quantile or percentile as an argument:
+    # logpdf, pdf
+    # logcdf, cdf
+    # logccdf, ccdf
+    # ilogcdf, icdf
+    # ilogccdf, iccdf
+    # Arguments that are outside the required range are replaced by NaN before
+    # passing them into the underlying function. The corresponding outputs
+    # are replaced by the appropriate value before being returned to the user.
+    # For example, when the argument of `cdf` exceeds the right end of the
+    # distribution's support, the wrapper replaces the argument with NaN,
+    # ignores the output of the underlying function, and returns 1.0. It also
+    # ensures that output is of the appropriate shape and dtype.
+
+    endpoints = {'icdf': (0, 1), 'iccdf': (0, 1),
+                 'ilogcdf': (-np.inf, 0), 'ilogccdf': (-np.inf, 0)}
+    replacements = {'logpdf': (-inf, -inf), 'pdf': (0, 0),
+                    '_logcdf1': (-inf, 0), '_logccdf1': (0, -inf),
+                    '_cdf1': (0, 1), '_ccdf1': (1, 0)}
+    replace_strict = {'pdf', 'logpdf'}
+    replace_exact = {'icdf', 'iccdf', 'ilogcdf', 'ilogccdf'}
+    clip = {'_cdf1', '_ccdf1'}
+    clip_log = {'_logcdf1', '_logccdf1'}
+
+    @functools.wraps(f)
+    def filtered(self, x, *args, **kwargs):
+        if self.validation_policy == _SKIP_ALL:
+            return f(self, x, *args, **kwargs)
+
+        method_name = f.__name__
+        x = np.asarray(x)
+        dtype = self._dtype
+        shape = self._shape
+
+        # Ensure that argument is at least as precise as distribution
+        # parameters, which are already at least floats. This will avoid issues
+        # with raising integers to negative integer powers and failure to replace
+        # invalid integers with NaNs.
+        if x.dtype != dtype:
+            dtype = np.result_type(x.dtype, dtype)
+            x = np.asarray(x, dtype=dtype)
+
+        # Broadcasting is slow. Do it only if necessary.
+        if not x.shape == shape:
+            try:
+                shape = np.broadcast_shapes(x.shape, shape)
+                x = np.broadcast_to(x, shape)
+                # Should we broadcast the distribution parameters to this shape, too?
+            except ValueError as e:
+                message = (
+                    f"The argument provided to `{self.__class__.__name__}"
+                    f".{method_name}` cannot be be broadcast to the same "
+                    "shape as the distribution parameters.")
+                raise ValueError(message) from e
+
+        low, high = endpoints.get(method_name, self.support())
+
+        # Check for arguments outside of domain. They'll be replaced with NaNs,
+        # and the result will be set to the appropriate value.
+        left_inc, right_inc = self._variable.domain.inclusive
+        mask_low = (x < low if (method_name in replace_strict and left_inc)
+                    else x <= low)
+        mask_high = (x > high if (method_name in replace_strict and right_inc)
+                     else x >= high)
+        mask_invalid = (mask_low | mask_high)
+        any_invalid = (mask_invalid if mask_invalid.shape == ()
+                       else np.any(mask_invalid))
+
+        # Check for arguments at domain endpoints, whether they
+        # are part of the domain or not.
+        any_endpoint = False
+        if method_name in replace_exact:
+            mask_low_endpoint = (x == low)
+            mask_high_endpoint = (x == high)
+            mask_endpoint = (mask_low_endpoint | mask_high_endpoint)
+            any_endpoint = (mask_endpoint if mask_endpoint.shape == ()
+                            else np.any(mask_endpoint))
+
+        # Set out-of-domain arguments to NaN. The result will be set to the
+        # appropriate value later.
+        if any_invalid:
+            x = np.array(x, dtype=dtype, copy=True)
+            x[mask_invalid] = np.nan
+
+        res = np.asarray(f(self, x, *args, **kwargs))
+
+        # Ensure that the result is the correct dtype and shape,
+        # copying (only once) if necessary.
+        res_needs_copy = False
+        if res.dtype != dtype:
+            dtype = np.result_type(dtype, self._dtype)
+            res_needs_copy = True
+
+        if res.shape != shape:  # faster to check first
+            res = np.broadcast_to(res, self._shape)
+            res_needs_copy = res_needs_copy or any_invalid or any_endpoint
+
+        if res_needs_copy:
+            res = np.array(res, dtype=dtype, copy=True)
+
+        #  For arguments outside the function domain, replace results
+        if any_invalid:
+            replace_low, replace_high = (
+                replacements.get(method_name, (np.nan, np.nan)))
+            res[mask_low] = replace_low
+            res[mask_high] = replace_high
+
+        # For arguments at the endpoints of the domain, replace results
+        if any_endpoint:
+            a, b = self.support()
+            if a.shape != shape:
+                a = np.array(np.broadcast_to(a, shape), copy=True)
+                b = np.array(np.broadcast_to(b, shape), copy=True)
+
+            replace_low_endpoint = (
+                b[mask_low_endpoint] if method_name.endswith('ccdf')
+                else a[mask_low_endpoint])
+            replace_high_endpoint = (
+                a[mask_high_endpoint] if method_name.endswith('ccdf')
+                else b[mask_high_endpoint])
+
+            res[mask_low_endpoint] = replace_low_endpoint
+            res[mask_high_endpoint] = replace_high_endpoint
+
+        # Clip probabilities to [0, 1]
+        if method_name in clip:
+            res = np.clip(res, 0., 1.)
+        elif method_name in clip_log:
+            res = res.real  # exp(res) > 0
+            res = np.clip(res, None, 0.)  # exp(res) < 1
+
+        return res[()]
+
+    return filtered
+
+
+def _set_invalid_nan_property(f):
+    # Wrapper for input / output validation and standardization of distribution
+    # functions that represent properties of the distribution itself:
+    # logentropy, entropy
+    # median, mode
+    # moment
+    # It ensures that the output is of the correct shape and dtype and that
+    # there are NaNs wherever the distribution parameters were invalid.
+
+    @functools.wraps(f)
+    def filtered(self, *args, **kwargs):
+        if self.validation_policy == _SKIP_ALL:
+            return f(self, *args, **kwargs)
+
+        res = f(self, *args, **kwargs)
+        if res is None:
+            # message could be more appropriate
+            raise NotImplementedError(self._not_implemented)
+
+        res = np.asarray(res)
+        needs_copy = False
+        dtype = res.dtype
+
+        if dtype != self._dtype:  # this won't work for logmoments (complex)
+            dtype = np.result_type(dtype, self._dtype)
+            needs_copy = True
+
+        if res.shape != self._shape:  # faster to check first
+            res = np.broadcast_to(res, self._shape)
+            needs_copy = needs_copy or self._any_invalid
+
+        if needs_copy:
+            res = res.astype(dtype=dtype, copy=True)
+
+        if self._any_invalid:
+            # may be redundant when quadrature is used, but not necessarily
+            # when formulas are used.
+            res[self._invalid] = np.nan
+
+        return res[()]
+
+    return filtered
+
+
+def _dispatch(f):
+    # For each public method (instance function) of a distribution (e.g. ccdf),
+    # there may be several ways ("method"s) that it can be computed (e.g. a
+    # formula, as the complement of the CDF, or via numerical integration).
+    # Each "method" is implemented by a different private method (instance
+    # function).
+    # This wrapper calls the appropriate private method based on the public
+    # method and any specified `method` keyword option.
+    # - If `method` is specified as a string (by the user), the appropriate
+    #   private method is called.
+    # - If `method` is None:
+    #   - The appropriate private method for the public method is looked up
+    #     in a cache.
+    #   - If the cache does not have an entry for the public method, the
+    #     appropriate "dispatch " function is called to determine which method
+    #     is most appropriate given the available private methods and
+    #     settings (e.g. tolerance).
+
+    @functools.wraps(f)
+    def wrapped(self, *args, method=None, **kwargs):
+        func_name = f.__name__
+        method = method or self._method_cache.get(func_name, None)
+        if callable(method):
+            pass
+        elif method is not None:
+            method = 'logexp' if method == 'log/exp' else method
+            method_name = func_name.replace('dispatch', method)
+            method = getattr(self, method_name)
+        else:
+            method = f(self, *args, method=method, **kwargs)
+            if func_name != '_sample_dispatch' and self.cache_policy != _NO_CACHE:
+                self._method_cache[func_name] = method
+
+        try:
+            return method(*args, **kwargs)
+        except KeyError as e:
+            raise NotImplementedError(self._not_implemented) from e
+
+    return wrapped
+
+
+def _cdf2_input_validation(f):
+    # Wrapper that does the job of `_set_invalid_nan` when `cdf` or `logcdf`
+    # is called with two quantile arguments.
+    # Let's keep it simple; no special cases for speed right now.
+    # The strategy is a bit different than for 1-arg `cdf` (and other methods
+    # covered by `_set_invalid_nan`). For 1-arg `cdf`, elements of `x` that
+    # are outside (or at the edge of) the support get replaced by `nan`,
+    # and then the results get replaced by the appropriate value (0 or 1).
+    # We *could* do something similar, dispatching to `_cdf1` in these
+    # cases. That would be a bit more robust, but it would also be quite
+    # a bit more complex, since we'd have to do different things when
+    # `x` and `y` are both out of bounds, when just `x` is out of bounds,
+    # when just `y` is out of bounds, and when both are out of bounds.
+    # I'm not going to do that right now. Instead, simply replace values
+    # outside the support by those at the edge of the support. Here, we also
+    # omit some of the optimizations that make `_set_invalid_nan` faster for
+    # simple arguments (e.g. float64 scalars).
+
+    @functools.wraps(f)
+    def wrapped(self, x, y, *args, **kwargs):
+        func_name = f.__name__
+
+        low, high = self.support()
+        x, y, low, high = np.broadcast_arrays(x, y, low, high)
+        dtype = np.result_type(x.dtype, y.dtype, self._dtype)
+        # yes, copy to avoid modifying input arrays
+        x, y = x.astype(dtype, copy=True), y.astype(dtype, copy=True)
+
+        # Swap arguments to ensure that x < y, and replace
+        # out-of domain arguments with domain endpoints. We'll
+        # transform the result later.
+        i_swap = y < x
+        x[i_swap], y[i_swap] = y[i_swap], x[i_swap]
+        i = x < low
+        x[i] = low[i]
+        i = y < low
+        y[i] = low[i]
+        i = x > high
+        x[i] = high[i]
+        i = y > high
+        y[i] = high[i]
+
+        res = f(self, x, y, *args, **kwargs)
+
+        # Clipping probability to [0, 1]
+        if func_name in {'_cdf2', '_ccdf2'}:
+            res = np.clip(res, 0., 1.)
+        else:
+            res = np.clip(res, None, 0.)  # exp(res) < 1
+
+        # Transform the result to account for swapped argument order
+        res = np.asarray(res)
+        if func_name == '_cdf2':
+            res[i_swap] *= -1.
+        elif func_name == '_ccdf2':
+            res[i_swap] *= -1
+            res[i_swap] += 2.
+        elif func_name == '_logcdf2':
+            res = np.asarray(res + 0j) if np.any(i_swap) else res
+            res[i_swap] = res[i_swap] + np.pi*1j
+        else:
+            # res[i_swap] is always positive and less than 1, so it's
+            # safe to ensure that the result is real
+            res[i_swap] = _logexpxmexpy(np.log(2), res[i_swap]).real
+        return res[()]
+
+    return wrapped
+
+
+def _fiinfo(x):
+    if np.issubdtype(x.dtype, np.inexact):
+        return np.finfo(x.dtype)
+    else:
+        return np.iinfo(x)
+
+
+def _kwargs2args(f, args=None, kwargs=None):
+    # Wraps a function that accepts a primary argument `x`, secondary
+    # arguments `args`, and secondary keyward arguments `kwargs` such that the
+    # wrapper accepts only `x` and `args`. The keyword arguments are extracted
+    # from `args` passed into the wrapper, and these are passed to the
+    # underlying function as `kwargs`.
+    # This is a temporary workaround until the scalar algorithms `_tanhsinh`,
+    # `_chandrupatla`, etc., support `kwargs` or can operate with compressing
+    # arguments to the callable.
+    args = args or []
+    kwargs = kwargs or {}
+    names = list(kwargs.keys())
+    n_args = len(args)
+
+    def wrapped(x, *args):
+        return f(x, *args[:n_args], **dict(zip(names, args[n_args:])))
+
+    args = list(args) + list(kwargs.values())
+
+    return wrapped, args
+
+
+def _log1mexp(x):
+    r"""Compute the log of the complement of the exponential.
+
+    This function is equivalent to::
+
+        log1mexp(x) = np.log(1-np.exp(x))
+
+    but avoids loss of precision when ``np.exp(x)`` is nearly 0 or 1.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+
+    Returns
+    -------
+    y : ndarray
+        An array of the same shape as `x`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats._distribution_infrastructure import _log1mexp
+    >>> x = 1e-300  # log of a number very close to 1
+    >>> _log1mexp(x)  # log of the complement of a number very close to 1
+    -690.7755278982137
+    >>> # np.log1p(-np.exp(x))  # -inf; emits warning
+
+    """
+    def f1(x):
+        # good for exp(x) close to 0
+        return np.log1p(-np.exp(x))
+
+    def f2(x):
+        # good for exp(x) close to 1
+        with np.errstate(divide='ignore'):
+            return np.real(np.log(-special.expm1(x + 0j)))
+
+    return _lazywhere(x < -1, (x,), f=f1, f2=f2)[()]
+
+
+def _logexpxmexpy(x, y):
+    """ Compute the log of the difference of the exponentials of two arguments.
+
+    Avoids over/underflow, but does not prevent loss of precision otherwise.
+    """
+    # TODO: properly avoid NaN when y is negative infinity
+    # TODO: silence warning with taking log of complex nan
+    # TODO: deal with x == y better
+    i = np.isneginf(np.real(y))
+    if np.any(i):
+        y = np.asarray(y.copy())
+        y[i] = np.finfo(y.dtype).min
+    x, y = np.broadcast_arrays(x, y)
+    res = np.asarray(special.logsumexp([x, y+np.pi*1j], axis=0))
+    i = (x == y)
+    res[i] = -np.inf
+    return res
+
+
+def _guess_bracket(xmin, xmax):
+    a = np.full_like(xmin, -1.0)
+    b = np.ones_like(xmax)
+
+    i = np.isfinite(xmin) & np.isfinite(xmax)
+    a[i] = xmin[i]
+    b[i] = xmax[i]
+
+    i = np.isfinite(xmin) & ~np.isfinite(xmax)
+    a[i] = xmin[i]
+    b[i] = xmin[i] + 1
+
+    i = np.isfinite(xmax) & ~np.isfinite(xmin)
+    a[i] = xmax[i] - 1
+    b[i] = xmax[i]
+
+    return a, b
+
+
+def _log_real_standardize(x):
+    """Standardizes the (complex) logarithm of a real number.
+
+    The logarithm of a real number may be represented by a complex number with
+    imaginary part that is a multiple of pi*1j. Even multiples correspond with
+    a positive real and odd multiples correspond with a negative real.
+
+    Given a logarithm of a real number `x`, this function returns an equivalent
+    representation in a standard form: the log of a positive real has imaginary
+    part `0` and the log of a negative real has imaginary part `pi`.
+
+    """
+    shape = x.shape
+    x = np.atleast_1d(x)
+    real = np.real(x).astype(x.dtype)
+    complex = np.imag(x)
+    y = real
+    negative = np.exp(complex*1j) < 0.5
+    y[negative] = y[negative] + np.pi * 1j
+    return y.reshape(shape)[()]
+
+
+def _combine_docs(dist_family, *, include_examples=True):
+    fields = set(NumpyDocString.sections)
+    fields.remove('index')
+    if not include_examples:
+        fields.remove('Examples')
+
+    doc = ClassDoc(dist_family)
+    superdoc = ClassDoc(ContinuousDistribution)
+    for field in fields:
+        if field in {"Methods", "Attributes"}:
+            doc[field] = superdoc[field]
+        elif field in {"Summary"}:
+            pass
+        elif field == "Extended Summary":
+            doc[field].append(_generate_domain_support(dist_family))
+        elif field == 'Examples':
+            doc[field] = [_generate_example(dist_family)]
+        else:
+            doc[field] += superdoc[field]
+    return str(doc)
+
+
+def _generate_domain_support(dist_family):
+    n_parameterizations = len(dist_family._parameterizations)
+
+    domain = f"\nfor :math:`x` in {dist_family._variable.domain}.\n"
+
+    if n_parameterizations == 0:
+        support = """
+        This class accepts no distribution parameters.
+        """
+    elif n_parameterizations == 1:
+        support = f"""
+        This class accepts one parameterization:
+        {str(dist_family._parameterizations[0])}.
+        """
+    else:
+        number = {2: 'two', 3: 'three', 4: 'four', 5: 'five'}[
+            n_parameterizations]
+        parameterizations = [f"- {str(p)}" for p in
+                             dist_family._parameterizations]
+        parameterizations = "\n".join(parameterizations)
+        support = f"""
+        This class accepts {number} parameterizations:
+
+        {parameterizations}
+        """
+    support = "\n".join([line.lstrip() for line in support.split("\n")][1:])
+    return domain + support
+
+
+def _generate_example(dist_family):
+    n_parameters = dist_family._num_parameters(0)
+    shapes = [()] * n_parameters
+    rng = np.random.default_rng(615681484984984)
+    i = 0
+    dist = dist_family._draw(shapes, rng=rng, i_parameterization=i)
+
+    rng = np.random.default_rng(2354873452)
+    name = dist_family.__name__
+    if n_parameters:
+        parameter_names = list(dist._parameterizations[i].parameters)
+        parameter_values = [round(getattr(dist, name), 2) for name in
+                            parameter_names]
+        name_values = [f"{name}={value}" for name, value in
+                       zip(parameter_names, parameter_values)]
+        instantiation = f"{name}({', '.join(name_values)})"
+        attributes = ", ".join([f"X.{param}" for param in dist._parameters])
+        X = dist_family(**dict(zip(parameter_names, parameter_values)))
+    else:
+        instantiation = f"{name}()"
+        X = dist
+
+    p = 0.32
+    x = round(X.icdf(p), 2)
+    y = round(X.icdf(2 * p), 2)
+
+    example = f"""
+    To use the distribution class, it must be instantiated using keyword
+    parameters corresponding with one of the accepted parameterizations.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> from scipy.stats import {name}
+    >>> X = {instantiation}
+
+    For convenience, the ``plot`` method can be used to visualize the density
+    and other functions of the distribution.
+
+    >>> X.plot()
+    >>> plt.show()
+
+    The support of the underlying distribution is available using the ``support``
+    method.
+
+    >>> X.support()
+    {X.support()}
+    """
+
+    if n_parameters:
+        example += f"""
+        The numerical values of parameters associated with all parameterizations
+        are available as attributes.
+
+        >>> {attributes}
+        {tuple(X._parameters.values())}
+        """
+
+    example += f"""
+    To evaluate the probability density function of the underlying distribution
+    at argument ``x={x}``:
+
+    >>> x = {x}
+    >>> X.pdf(x)
+    {X.pdf(x)}
+
+    The cumulative distribution function, its complement, and the logarithm
+    of these functions are evaluated similarly.
+
+    >>> np.allclose(np.exp(X.logccdf(x)), 1 - X.cdf(x))
+    True
+
+    The inverse of these functions with respect to the argument ``x`` is also
+    available.
+
+    >>> logp = np.log(1 - X.ccdf(x))
+    >>> np.allclose(X.ilogcdf(logp), x)
+    True
+
+    Note that distribution functions and their logarithms also have two-argument
+    versions for working with the probability mass between two arguments. The
+    result tends to be more accurate than the naive implementation because it avoids
+    subtractive cancellation.
+
+    >>> y = {y}
+    >>> np.allclose(X.ccdf(x, y), 1 - (X.cdf(y) - X.cdf(x)))
+    True
+
+    There are methods for computing measures of central tendency,
+    dispersion, higher moments, and entropy.
+
+    >>> X.mean(), X.median(), X.mode()
+    {X.mean(), X.median(), X.mode()}
+    >>> X.variance(), X.standard_deviation()
+    {X.variance(), X.standard_deviation()}
+    >>> X.skewness(), X.kurtosis()
+    {X.skewness(), X.kurtosis()}
+    >>> np.allclose(X.moment(order=6, kind='standardized'),
+    ...             X.moment(order=6, kind='central') / X.variance()**3)
+    True
+    >>> np.allclose(np.exp(X.logentropy()), X.entropy())
+    True
+
+    Pseudo-random samples can be drawn from
+    the underlying distribution using ``sample``.
+
+    >>> X.sample(shape=(4,))
+    {repr(X.sample(shape=(4,)))}  # may vary
+    """
+    # remove the indentation due to use of block quote within function;
+    # eliminate blank first line
+    example = "\n".join([line.lstrip() for line in example.split("\n")][1:])
+    return example
+
+
+class ContinuousDistribution(_ProbabilityDistribution):
+    r""" Class that represents a continuous statistical distribution.
+
+    Parameters
+    ----------
+    tol : positive float, optional
+        The desired relative tolerance of calculations. Left unspecified,
+        calculations may be faster; when provided, calculations may be
+        more likely to meet the desired accuracy.
+    validation_policy : {None, "skip_all"}
+        Specifies the level of input validation to perform. Left unspecified,
+        input validation is performed to ensure appropriate behavior in edge
+        case (e.g. parameters out of domain, argument outside of distribution
+        support, etc.) and improve consistency of output dtype, shape, etc.
+        Pass ``'skip_all'`` to avoid the computational overhead of these
+        checks when rough edges are acceptable.
+    cache_policy : {None, "no_cache"}
+        Specifies the extent to which intermediate results are cached. Left
+        unspecified, intermediate results of some calculations (e.g. distribution
+        support, moments, etc.) are cached to improve performance of future
+        calculations. Pass ``'no_cache'`` to reduce memory reserved by the class
+        instance.
+
+    Attributes
+    ----------
+    All parameters are available as attributes.
+
+    Methods
+    -------
+    support
+
+    plot
+
+    sample
+
+    moment
+
+    mean
+    median
+    mode
+
+    variance
+    standard_deviation
+
+    skewness
+    kurtosis
+
+    pdf
+    logpdf
+
+    cdf
+    icdf
+    ccdf
+    iccdf
+
+    logcdf
+    ilogcdf
+    logccdf
+    ilogccdf
+
+    entropy
+    logentropy
+
+    See Also
+    --------
+    :ref:`rv_infrastructure` : Tutorial
+
+    Notes
+    -----
+    The following abbreviations are used throughout the documentation.
+
+    - PDF: probability density function
+    - CDF: cumulative distribution function
+    - CCDF: complementary CDF
+    - entropy: differential entropy
+    - log-*F*: logarithm of *F* (e.g. log-CDF)
+    - inverse *F*: inverse function of *F* (e.g. inverse CDF)
+
+    The API documentation is written to describe the API, not to serve as
+    a statistical reference. Effort is made to be correct at the level
+    required to use the functionality, not to be mathematically rigorous.
+    For example, continuity and differentiability may be implicitly assumed.
+    For precise mathematical definitions, consult your preferred mathematical
+    text.
+
+    """
+    __array_priority__ = 1
+    _parameterizations = []  # type: ignore[var-annotated]
+
+    ### Initialization
+
+    def __init__(self, *, tol=_null, validation_policy=None, cache_policy=None,
+                 **parameters):
+        self.tol = tol
+        self.validation_policy = validation_policy
+        self.cache_policy = cache_policy
+        self._not_implemented = (
+            f"`{self.__class__.__name__}` does not provide an accurate "
+            "implementation of the required method. Consider leaving "
+            "`method` and `tol` unspecified to use another implementation."
+        )
+        self._original_parameters = {}
+        # We may want to override the `__init__` method with parameters so
+        # IDEs can suggest parameter names. If there are multiple parameterizations,
+        # we'll need the default values of parameters to be None; this will
+        # filter out the parameters that were not actually specified by the user.
+        parameters = {key: val for key, val in
+                      sorted(parameters.items()) if val is not None}
+        self._update_parameters(**parameters)
+
+    def _update_parameters(self, *, validation_policy=None, **params):
+        r""" Update the numerical values of distribution parameters.
+
+        Parameters
+        ----------
+        **params : array_like
+            Desired numerical values of the distribution parameters. Any or all
+            of the parameters initially used to instantiate the distribution
+            may be modified. Parameters used in alternative parameterizations
+            are not accepted.
+
+        validation_policy : str
+            To be documented. See Question 3 at the top.
+        """
+
+        parameters = original_parameters = self._original_parameters.copy()
+        parameters.update(**params)
+        parameterization = None
+        self._invalid = np.asarray(False)
+        self._any_invalid = False
+        self._shape = tuple()
+        self._ndim = 0
+        self._size = 1
+        self._dtype = np.float64
+
+        if (validation_policy or self.validation_policy) == _SKIP_ALL:
+            parameters = self._process_parameters(**parameters)
+        elif not len(self._parameterizations):
+            if parameters:
+                message = (f"The `{self.__class__.__name__}` distribution "
+                           "family does not accept parameters, but parameters "
+                           f"`{set(parameters)}` were provided.")
+                raise ValueError(message)
+        else:
+            # This is default behavior, which re-runs all parameter validations
+            # even when only a single parameter is modified. For many
+            # distributions, the domain of a parameter doesn't depend on other
+            # parameters, so parameters could safely be modified without
+            # re-validating all other parameters. To handle these cases more
+            # efficiently, we could allow the developer  to override this
+            # behavior.
+
+            # Currently the user can only update the original parameterization.
+            # Even though that parameterization is already known,
+            # `_identify_parameterization` is called to produce a nice error
+            # message if the user passes other values. To be a little more
+            # efficient, we could detect whether the values passed are
+            # consistent with the original parameterization rather than finding
+            # it from scratch. However, we might want other parameterizations
+            # to be accepted, which would require other changes, so I didn't
+            # optimize this.
+
+            parameterization = self._identify_parameterization(parameters)
+            parameters, shape, size, ndim = self._broadcast(parameters)
+            parameters, invalid, any_invalid, dtype = (
+                self._validate(parameterization, parameters))
+            parameters = self._process_parameters(**parameters)
+
+            self._invalid = invalid
+            self._any_invalid = any_invalid
+            self._shape = shape
+            self._size = size
+            self._ndim = ndim
+            self._dtype = dtype
+
+        self.reset_cache()
+        self._parameters = parameters
+        self._parameterization = parameterization
+        self._original_parameters = original_parameters
+        for name in self._parameters.keys():
+            # Make parameters properties of the class; return values from the instance
+            if hasattr(self.__class__, name):
+                continue
+            setattr(self.__class__, name, property(lambda self_, name_=name:
+                                                   self_._parameters[name_].copy()[()]))
+
+    def reset_cache(self):
+        r""" Clear all cached values.
+
+        To improve the speed of some calculations, the distribution's support
+        and moments are cached.
+
+        This function is called automatically whenever the distribution
+        parameters are updated.
+
+        """
+        # We could offer finer control over what is cleared.
+        # For simplicity, these will still exist even if cache_policy is
+        # NO_CACHE; they just won't be populated. This allows caching to be
+        # turned on and off easily.
+        self._moment_raw_cache = {}
+        self._moment_central_cache = {}
+        self._moment_standardized_cache = {}
+        self._support_cache = None
+        self._method_cache = {}
+        self._constant_cache = None
+
+    def _identify_parameterization(self, parameters):
+        # Determine whether a `parameters` dictionary matches is consistent
+        # with one of the parameterizations of the distribution. If so,
+        # return that parameterization object; if not, raise an error.
+        #
+        # I've come back to this a few times wanting to avoid this explicit
+        # loop. I've considered several possibilities, but they've all been a
+        # little unusual. For example, we could override `_eq_` so we can
+        # use _parameterizations.index() to retrieve the parameterization,
+        # or the user could put the parameterizations in a dictionary so we
+        # could look them up with a key (e.g. frozenset of parameter names).
+        # I haven't been sure enough of these approaches to implement them.
+        parameter_names_set = set(parameters)
+
+        for parameterization in self._parameterizations:
+            if parameterization.matches(parameter_names_set):
+                break
+        else:
+            if not parameter_names_set:
+                message = (f"The `{self.__class__.__name__}` distribution "
+                           "family requires parameters, but none were "
+                           "provided.")
+            else:
+                parameter_names = self._get_parameter_str(parameters)
+                message = (f"The provided parameters `{parameter_names}` "
+                           "do not match a supported parameterization of the "
+                           f"`{self.__class__.__name__}` distribution family.")
+            raise ValueError(message)
+
+        return parameterization
+
+    def _broadcast(self, parameters):
+        # Broadcast the distribution parameters to the same shape. If the
+        # arrays are not broadcastable, raise a meaningful error.
+        #
+        # We always make sure that the parameters *are* the same shape
+        # and not just broadcastable. Users can access parameters as
+        # attributes, and I think they should see the arrays as the same shape.
+        # More importantly, arrays should be the same shape before logical
+        # indexing operations, which are needed in infrastructure code when
+        # there are invalid parameters, and may be needed in
+        # distribution-specific code. We don't want developers to need to
+        # broadcast in implementation functions.
+
+        # It's much faster to check whether broadcasting is necessary than to
+        # broadcast when it's not necessary.
+        parameter_vals = [np.asarray(parameter)
+                          for parameter in parameters.values()]
+        parameter_shapes = set(parameter.shape for parameter in parameter_vals)
+        if len(parameter_shapes) == 1:
+            return (parameters, parameter_vals[0].shape,
+                    parameter_vals[0].size, parameter_vals[0].ndim)
+
+        try:
+            parameter_vals = np.broadcast_arrays(*parameter_vals)
+        except ValueError as e:
+            parameter_names = self._get_parameter_str(parameters)
+            message = (f"The parameters `{parameter_names}` provided to the "
+                       f"`{self.__class__.__name__}` distribution family "
+                       "cannot be broadcast to the same shape.")
+            raise ValueError(message) from e
+        return (dict(zip(parameters.keys(), parameter_vals)),
+                parameter_vals[0].shape,
+                parameter_vals[0].size,
+                parameter_vals[0].ndim)
+
+    def _validate(self, parameterization, parameters):
+        # Broadcasts distribution parameter arrays and converts them to a
+        # consistent dtype. Replaces invalid parameters with `np.nan`.
+        # Returns the validated parameters, a boolean mask indicated *which*
+        # elements are invalid, a boolean scalar indicating whether *any*
+        # are invalid (to skip special treatments if none are invalid), and
+        # the common dtype.
+        valid, dtype = parameterization.validation(parameters)
+        invalid = ~valid
+        any_invalid = invalid if invalid.shape == () else np.any(invalid)
+        # If necessary, make the arrays contiguous and replace invalid with NaN
+        if any_invalid:
+            for parameter_name in parameters:
+                parameters[parameter_name] = np.copy(
+                    parameters[parameter_name])
+                parameters[parameter_name][invalid] = np.nan
+
+        return parameters, invalid, any_invalid, dtype
+
+    def _process_parameters(self, **params):
+        r""" Process and cache distribution parameters for reuse.
+
+        This is intended to be overridden by subclasses. It allows distribution
+        authors to pre-process parameters for re-use. For instance, when a user
+        parameterizes a LogUniform distribution with `a` and `b`, it makes
+        sense to calculate `log(a)` and `log(b)` because these values will be
+        used in almost all distribution methods. The dictionary returned by
+        this method is passed to all private methods that calculate functions
+        of the distribution.
+        """
+        return params
+
+    def _get_parameter_str(self, parameters):
+        # Get a string representation of the parameters like "{a, b, c}".
+        return f"{{{', '.join(parameters.keys())}}}"
+
+    def _copy_parameterization(self):
+        self._parameterizations = self._parameterizations.copy()
+        for i in range(len(self._parameterizations)):
+            self._parameterizations[i] = self._parameterizations[i].copy()
+
+    ### Attributes
+
+    # `tol` attribute is just notional right now. See Question 4 above.
+    @property
+    def tol(self):
+        r"""positive float:
+        The desired relative tolerance of calculations. Left unspecified,
+        calculations may be faster; when provided, calculations may be
+        more likely to meet the desired accuracy.
+        """
+        return self._tol
+
+    @tol.setter
+    def tol(self, tol):
+        if _isnull(tol):
+            self._tol = tol
+            return
+
+        tol = np.asarray(tol)
+        if (tol.shape != () or not tol > 0 or  # catches NaNs
+                not np.issubdtype(tol.dtype, np.floating)):
+            message = (f"Attribute `tol` of `{self.__class__.__name__}` must "
+                       "be a positive float, if specified.")
+            raise ValueError(message)
+        self._tol = tol[()]
+
+    @property
+    def cache_policy(self):
+        r"""{None, "no_cache"}:
+        Specifies the extent to which intermediate results are cached. Left
+        unspecified, intermediate results of some calculations (e.g. distribution
+        support, moments, etc.) are cached to improve performance of future
+        calculations. Pass ``'no_cache'`` to reduce memory reserved by the class
+        instance.
+        """
+        return self._cache_policy
+
+    @cache_policy.setter
+    def cache_policy(self, cache_policy):
+        cache_policy = str(cache_policy).lower() if cache_policy is not None else None
+        cache_policies = {None, 'no_cache'}
+        if cache_policy not in cache_policies:
+            message = (f"Attribute `cache_policy` of `{self.__class__.__name__}` "
+                       f"must be one of {cache_policies}, if specified.")
+            raise ValueError(message)
+        self._cache_policy = cache_policy
+
+    @property
+    def validation_policy(self):
+        r"""{None, "skip_all"}:
+        Specifies the level of input validation to perform. Left unspecified,
+        input validation is performed to ensure appropriate behavior in edge
+        case (e.g. parameters out of domain, argument outside of distribution
+        support, etc.) and improve consistency of output dtype, shape, etc.
+        Use ``'skip_all'`` to avoid the computational overhead of these
+        checks when rough edges are acceptable.
+        """
+        return self._validation_policy
+
+    @validation_policy.setter
+    def validation_policy(self, validation_policy):
+        validation_policy = (str(validation_policy).lower()
+                             if validation_policy is not None else None)
+        iv_policies = {None, 'skip_all'}
+        if validation_policy not in iv_policies:
+            message = (f"Attribute `validation_policy` of `{self.__class__.__name__}` "
+                       f"must be one of {iv_policies}, if specified.")
+            raise ValueError(message)
+        self._validation_policy = validation_policy
+
+    ### Other magic methods
+
+    def __repr__(self):
+        r""" Returns a string representation of the distribution.
+
+        Includes the name of the distribution family, the names of the
+        parameters and the `repr` of each of their values.
+
+
+        """
+        class_name = self.__class__.__name__
+        parameters = list(self._original_parameters.items())
+        info = []
+        with np.printoptions(threshold=10):
+            str_parameters = [f"{symbol}={repr(value)}" for symbol, value in parameters]
+        str_parameters = f"{', '.join(str_parameters)}"
+        info.append(str_parameters)
+        return f"{class_name}({', '.join(info)})"
+
+    def __str__(self):
+        class_name = self.__class__.__name__
+        parameters = list(self._original_parameters.items())
+        info = []
+        with np.printoptions(threshold=10):
+            str_parameters = [f"{symbol}={str(value)}" for symbol, value in parameters]
+        str_parameters = f"{', '.join(str_parameters)}"
+        info.append(str_parameters)
+        return f"{class_name}({', '.join(info)})"
+
+    def __add__(self, loc):
+        return ShiftedScaledDistribution(self, loc=loc)
+
+    def __sub__(self, loc):
+        return ShiftedScaledDistribution(self, loc=-loc)
+
+    def __mul__(self, scale):
+        return ShiftedScaledDistribution(self, scale=scale)
+
+    def __truediv__(self, scale):
+        return ShiftedScaledDistribution(self, scale=1/scale)
+
+    def __pow__(self, other):
+        if not np.isscalar(other) or other <= 0 or other != int(other):
+            message = ("Raising a random variable to the power of an argument is only "
+                       "implemented when the argument is a positive integer.")
+            raise NotImplementedError(message)
+
+        # Fill in repr_pattern with the repr of self before taking abs.
+        # Avoids having unnecessary abs in the repr.
+        with np.printoptions(threshold=10):
+            repr_pattern = f"({repr(self)})**{repr(other)}"
+            str_pattern = f"({str(self)})**{str(other)}"
+        X = abs(self) if other % 2 == 0 else self
+
+        funcs = dict(g=lambda u: u**other, repr_pattern=repr_pattern,
+                     str_pattern=str_pattern,
+                     h=lambda u: np.sign(u) * np.abs(u)**(1 / other),
+                     dh=lambda u: 1/other * np.abs(u)**(1/other - 1))
+
+        return MonotonicTransformedDistribution(X, **funcs, increasing=True)
+
+    def __radd__(self, other):
+        return self.__add__(other)
+
+    def __rsub__(self, other):
+        return self.__neg__().__add__(other)
+
+    def __rmul__(self, other):
+        return self.__mul__(other)
+
+    def __rtruediv__(self, other):
+        a, b = self.support()
+        with np.printoptions(threshold=10):
+            funcs = dict(g=lambda u: 1 / u,
+                         repr_pattern=f"{repr(other)}/({repr(self)})",
+                         str_pattern=f"{str(other)}/({str(self)})",
+                         h=lambda u: 1 / u, dh=lambda u: 1 / u ** 2)
+        if np.all(a >= 0) or np.all(b <= 0):
+            out = MonotonicTransformedDistribution(self, **funcs, increasing=False)
+        else:
+            message = ("Division by a random variable is only implemented "
+                       "when the support is either non-negative or non-positive.")
+            raise NotImplementedError(message)
+        if np.all(other == 1):
+            return out
+        else:
+            return out * other
+
+    def __rpow__(self, other):
+        with np.printoptions(threshold=10):
+            funcs = dict(g=lambda u: other**u,
+                         h=lambda u: np.log(u) / np.log(other),
+                         dh=lambda u: 1 / np.abs(u * np.log(other)),
+                         repr_pattern=f"{repr(other)}**({repr(self)})",
+                         str_pattern=f"{str(other)}**({str(self)})",)
+
+        if not np.isscalar(other) or other <= 0 or other == 1:
+            message = ("Raising an argument to the power of a random variable is only "
+                       "implemented when the argument is a positive scalar other than "
+                       "1.")
+            raise NotImplementedError(message)
+
+        if other > 1:
+            return MonotonicTransformedDistribution(self, **funcs, increasing=True)
+        else:
+            return MonotonicTransformedDistribution(self, **funcs, increasing=False)
+
+    def __neg__(self):
+        return self * -1
+
+    def __abs__(self):
+        return FoldedDistribution(self)
+
+    ### Utilities
+
+    ## Input validation
+
+    def _validate_order_kind(self, order, kind, kinds):
+        # Yet another integer validating function. Unlike others in SciPy, it
+        # Is quite flexible about what is allowed as an integer, and it
+        # raises a distribution-specific error message to facilitate
+        # identification of the source of the error.
+        if self.validation_policy == _SKIP_ALL:
+            return order
+
+        order = np.asarray(order, dtype=self._dtype)[()]
+        message = (f"Argument `order` of `{self.__class__.__name__}.moment` "
+                   "must be a finite, positive integer.")
+        try:
+            order_int = round(order.item())
+            # If this fails for any reason (e.g. it's an array, it's infinite)
+            # it's not a valid `order`.
+        except Exception as e:
+            raise ValueError(message) from e
+
+        if order_int <0 or order_int != order:
+            raise ValueError(message)
+
+        message = (f"Argument `kind` of `{self.__class__.__name__}.moment` "
+                   f"must be one of {set(kinds)}.")
+        if kind.lower() not in kinds:
+            raise ValueError(message)
+
+        return order
+
+    def _preserve_type(self, x):
+        x = np.asarray(x)
+        if x.dtype != self._dtype:
+            x = x.astype(self._dtype)
+        return x[()]
+
+    ## Testing
+
+    @classmethod
+    def _draw(cls, sizes=None, rng=None, i_parameterization=None,
+              proportions=None):
+        r""" Draw a specific (fully-defined) distribution from the family.
+
+        See _Parameterization.draw for documentation details.
+        """
+        rng = np.random.default_rng(rng)
+        if len(cls._parameterizations) == 0:
+            return cls()
+        if i_parameterization is None:
+            n = cls._num_parameterizations()
+            i_parameterization = rng.integers(0, max(0, n - 1), endpoint=True)
+
+        parameterization = cls._parameterizations[i_parameterization]
+        parameters = parameterization.draw(sizes, rng, proportions=proportions,
+                                           region='typical')
+        return cls(**parameters)
+
+    @classmethod
+    def _num_parameterizations(cls):
+        # Returns the number of parameterizations accepted by the family.
+        return len(cls._parameterizations)
+
+    @classmethod
+    def _num_parameters(cls, i_parameterization=0):
+        # Returns the number of parameters used in the specified
+        # parameterization.
+        return (0 if not cls._num_parameterizations()
+                else len(cls._parameterizations[i_parameterization]))
+
+    ## Algorithms
+
+    def _quadrature(self, integrand, limits=None, args=None,
+                    params=None, log=False):
+        # Performs numerical integration of an integrand between limits.
+        # Much of this should be added to `_tanhsinh`.
+        a, b = self._support(**params) if limits is None else limits
+        a, b = np.broadcast_arrays(a, b)
+        if not a.size:
+            # maybe need to figure out result type from a, b
+            return np.empty(a.shape, dtype=self._dtype)
+        args = [] if args is None else args
+        params = {} if params is None else params
+        f, args = _kwargs2args(integrand, args=args, kwargs=params)
+        args = np.broadcast_arrays(*args)
+        # If we know the median or mean, consider breaking up the interval
+        rtol = None if _isnull(self.tol) else self.tol
+        res = _tanhsinh(f, a, b, args=args, log=log, rtol=rtol)
+        # For now, we ignore the status, but I want to return the error
+        # estimate - see question 5 at the top.
+        return res.integral
+
+    def _solve_bounded(self, f, p, *, bounds=None, params=None):
+        # Finds the argument of a function that produces the desired output.
+        # Much of this should be added to _bracket_root / _chandrupatla.
+        xmin, xmax = self._support(**params) if bounds is None else bounds
+        params = {} if params is None else params
+
+        p, xmin, xmax = np.broadcast_arrays(p, xmin, xmax)
+        if not p.size:
+            # might need to figure out result type based on p
+            return np.empty(p.shape, dtype=self._dtype)
+
+        def f2(x, _p, **kwargs):  # named `_p` to avoid conflict with shape `p`
+            return f(x, **kwargs) - _p
+
+        f3, args = _kwargs2args(f2, args=[p], kwargs=params)
+        # If we know the median or mean, should use it
+
+        # Any operations between 0d array and a scalar produces a scalar, so...
+        shape = xmin.shape
+        xmin, xmax = np.atleast_1d(xmin, xmax)
+
+        xl0, xr0 = _guess_bracket(xmin, xmax)
+        xmin = xmin.reshape(shape)
+        xmax = xmax.reshape(shape)
+        xl0 = xl0.reshape(shape)
+        xr0 = xr0.reshape(shape)
+
+        res = _bracket_root(f3, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, args=args)
+        # For now, we ignore the status, but I want to use the bracket width
+        # as an error estimate - see question 5 at the top.
+        xrtol = None if _isnull(self.tol) else self.tol
+        return _chandrupatla(f3, a=res.xl, b=res.xr, args=args, xrtol=xrtol).x
+
+    ## Other
+
+    def _overrides(self, method_name):
+        # Determines whether a class overrides a specified method.
+        # Returns True if the method implementation exists and is the same as
+        # that of the `ContinuousDistribution` class; otherwise returns False.
+
+        # Sometimes we use `_overrides` to check whether a certain method is overridden
+        # and if so, call it. This begs the questions of why we don't do the more
+        # obvious thing: restructure so that if the private method is overridden,
+        # Python will call it instead of the inherited version automatically. The short
+        # answer is that there are multiple ways a use might wish to evaluate a method,
+        # and simply overriding the method with a formula is not always the best option.
+        # For more complete discussion of the considerations, see:
+        # https://github.com/scipy/scipy/pull/21050#discussion_r1707798901
+        method = getattr(self.__class__, method_name, None)
+        super_method = getattr(ContinuousDistribution, method_name, None)
+        return method is not super_method
+
+    ### Distribution properties
+    # The following "distribution properties" are exposed via a public method
+    # that accepts only options (not distribution parameters or quantile/
+    # percentile argument).
+    # support
+    # logentropy, entropy,
+    # median, mode, mean,
+    # variance, standard_deviation
+    # skewness, kurtosis
+    # Common options are:
+    # method - a string that indicates which method should be used to compute
+    #          the quantity (e.g. a formula or numerical integration).
+    # Input/output validation is provided by the `_set_invalid_nan_property`
+    # decorator. These are the methods meant to be called by users.
+    #
+    # Each public method calls a private "dispatch" method that
+    # determines which "method" (strategy for calculating the desired quantity)
+    # to use by default and, via the `@_dispatch` decorator, calls the
+    # method and computes the result.
+    # Dispatch methods always accept:
+    # method - as passed from the public method
+    # params - a dictionary of distribution shape parameters passed by
+    #          the public method.
+    # Dispatch methods accept `params` rather than relying on the state of the
+    # object because iterative algorithms like `_tanhsinh` and `_chandrupatla`
+    # need their callable to follow a strict elementwise protocol: each element
+    # of the output is determined solely by the values of the inputs at the
+    # corresponding location. The public methods do not satisfy this protocol
+    # because they do not accept the parameters as arguments, producing an
+    # output that generally has a different shape than that of the input. Also,
+    # by calling "dispatch" methods rather than the public methods, the
+    # iterative algorithms avoid the overhead of input validation.
+    #
+    # Each dispatch method can designate the responsibility of computing
+    # the required value to any of several "implementation" methods. These
+    # methods accept only `**params`, the parameter dictionary passed from
+    # the public method via the dispatch method. We separate the implementation
+    # methods from the dispatch methods for the sake of simplicity (via
+    # compartmentalization) and to allow subclasses to override certain
+    # implementation methods (typically only the "formula" methods). The names
+    # of implementation methods are combinations of the public method name and
+    # the name of the "method" (strategy for calculating the desired quantity)
+    # string. (In fact, the name of the implementation method is calculated
+    # from these two strings in the `_dispatch` decorator.) Common method
+    # strings are:
+    # formula - distribution-specific analytical expressions to be implemented
+    #           by subclasses.
+    # log/exp - Compute the log of a number and then exponentiate it or vice
+    #           versa.
+    # quadrature - Compute the value via numerical integration.
+    #
+    # The default method (strategy) is determined based on what implementation
+    # methods are available and the error tolerance of the user. Typically,
+    # a formula is always used if available. We fall back to "log/exp" if a
+    # formula for the logarithm or exponential of the quantity is available,
+    # and we use quadrature otherwise.
+
+    def support(self):
+        # If this were a `cached_property`, we couldn't update the value
+        # when the distribution parameters change.
+        # Caching is important, though, because calls to _support take a few
+        # microseconds even when `a` and `b` are already the same shape.
+        if self._support_cache is not None:
+            return self._support_cache
+
+        a, b = self._support(**self._parameters)
+        if a.shape != self._shape:
+            a = np.broadcast_to(a, self._shape)
+        if b.shape != self._shape:
+            b = np.broadcast_to(b, self._shape)
+
+        if self._any_invalid:
+            a, b = np.asarray(a).copy(), np.asarray(b).copy()
+            a[self._invalid], b[self._invalid] = np.nan, np.nan
+            a, b = a[()], b[()]
+
+        support = (a, b)
+
+        if self.cache_policy != _NO_CACHE:
+            self._support_cache = support
+
+        return support
+
+    def _support(self, **params):
+        # Computes the support given distribution parameters
+        a, b = self._variable.domain.get_numerical_endpoints(params)
+        if len(params):
+            # the parameters should all be of the same dtype and shape at this point
+            vals = list(params.values())
+            shape = vals[0].shape
+            a = np.broadcast_to(a, shape) if a.shape != shape else a
+            b = np.broadcast_to(b, shape) if b.shape != shape else b
+        return self._preserve_type(a), self._preserve_type(b)
+
+    @_set_invalid_nan_property
+    def logentropy(self, *, method=None):
+        return self._logentropy_dispatch(method=method, **self._parameters) + 0j
+
+    @_dispatch
+    def _logentropy_dispatch(self, method=None, **params):
+        if self._overrides('_logentropy_formula'):
+            method = self._logentropy_formula
+        elif self._overrides('_entropy_formula'):
+            method = self._logentropy_logexp_safe
+        else:
+            method = self._logentropy_quadrature
+        return method
+
+    def _logentropy_formula(self, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logentropy_logexp(self, **params):
+        res = np.log(self._entropy_dispatch(**params)+0j)
+        return _log_real_standardize(res)
+
+    def _logentropy_logexp_safe(self, **params):
+        out = self._logentropy_logexp(**params)
+        mask = np.isinf(out.real)
+        if np.any(mask):
+            params_mask = {key:val[mask] for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._logentropy_quadrature(**params_mask)
+        return out[()]
+
+    def _logentropy_quadrature(self, **params):
+        def logintegrand(x, **params):
+            logpdf = self._logpdf_dispatch(x, **params)
+            return logpdf + np.log(0j+logpdf)
+        res = self._quadrature(logintegrand, params=params, log=True)
+        return _log_real_standardize(res + np.pi*1j)
+
+    @_set_invalid_nan_property
+    def entropy(self, *, method=None):
+        return self._entropy_dispatch(method=method, **self._parameters)
+
+    @_dispatch
+    def _entropy_dispatch(self, method=None, **params):
+        if self._overrides('_entropy_formula'):
+            method = self._entropy_formula
+        elif self._overrides('_logentropy_formula'):
+            method = self._entropy_logexp
+        else:
+            method = self._entropy_quadrature
+        return method
+
+    def _entropy_formula(self, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _entropy_logexp(self, **params):
+        return np.real(np.exp(self._logentropy_dispatch(**params)))
+
+    def _entropy_quadrature(self, **params):
+        def integrand(x, **params):
+            pdf = self._pdf_dispatch(x, **params)
+            logpdf = self._logpdf_dispatch(x, **params)
+            return logpdf * pdf
+        return -self._quadrature(integrand, params=params)
+
+    @_set_invalid_nan_property
+    def median(self, *, method=None):
+        return self._median_dispatch(method=method, **self._parameters)
+
+    @_dispatch
+    def _median_dispatch(self, method=None, **params):
+        if self._overrides('_median_formula'):
+            method = self._median_formula
+        else:
+            method = self._median_icdf
+        return method
+
+    def _median_formula(self, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _median_icdf(self, **params):
+        return self._icdf_dispatch(0.5, **params)
+
+    @_set_invalid_nan_property
+    def mode(self, *, method=None):
+        return self._mode_dispatch(method=method, **self._parameters)
+
+    @_dispatch
+    def _mode_dispatch(self, method=None, **params):
+        # We could add a method that looks for a critical point with
+        # differentiation and the root finder
+        if self._overrides('_mode_formula'):
+            method = self._mode_formula
+        else:
+            method = self._mode_optimization
+        return method
+
+    def _mode_formula(self, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _mode_optimization(self, **params):
+        if not self._size:
+            return np.empty(self._shape, dtype=self._dtype)
+
+        a, b = self._support(**params)
+        m = self._median_dispatch(**params)
+
+        f, args = _kwargs2args(lambda x, **params: -self._pdf_dispatch(x, **params),
+                               args=(), kwargs=params)
+        res_b = _bracket_minimum(f, m, xmin=a, xmax=b, args=args)
+        res = _chandrupatla_minimize(f, res_b.xl, res_b.xm, res_b.xr, args=args)
+        mode = np.asarray(res.x)
+        mode_at_boundary = res_b.status == -1
+        mode_at_left = mode_at_boundary & (res_b.fl <= res_b.fm)
+        mode_at_right = mode_at_boundary & (res_b.fr < res_b.fm)
+        mode[mode_at_left] = a[mode_at_left]
+        mode[mode_at_right] = b[mode_at_right]
+        return mode[()]
+
+    def mean(self, *, method=None):
+        return self.moment(1, kind='raw', method=method)
+
+    def variance(self, *, method=None):
+        return self.moment(2, kind='central', method=method)
+
+    def standard_deviation(self, *, method=None):
+        return np.sqrt(self.variance(method=method))
+
+    def skewness(self, *, method=None):
+        return self.moment(3, kind='standardized', method=method)
+
+    def kurtosis(self, *, method=None, convention='non-excess'):
+        conventions = {'non-excess', 'excess'}
+        message = (f'Parameter `convention` of `{self.__class__.__name__}.kurtosis` '
+                   f"must be one of {conventions}.")
+        convention = convention.lower()
+        if convention not in conventions:
+            raise ValueError(message)
+        k = self.moment(4, kind='standardized', method=method)
+        return k - 3 if convention == 'excess' else k
+
+    ### Distribution functions
+    # The following functions related to the distribution PDF and CDF are
+    # exposed via a public method that accepts one positional argument - the
+    # quantile - and keyword options (but not distribution parameters).
+    # logpdf, pdf
+    # logcdf, cdf
+    # logccdf, ccdf
+    # The `logcdf` and `cdf` functions can also be called with two positional
+    # arguments - lower and upper quantiles - and they return the probability
+    # mass (integral of the PDF) between them. The 2-arg versions of `logccdf`
+    # and `ccdf` return the complement of this quantity.
+    # All the (1-arg) cumulative distribution functions have inverse
+    # functions, which accept one positional argument - the percentile.
+    # ilogcdf, icdf
+    # ilogccdf, iccdf
+    # Common keyword options include:
+    # method - a string that indicates which method should be used to compute
+    #          the quantity (e.g. a formula or numerical integration).
+    # Tolerance options should be added.
+    # Input/output validation is provided by the `_set_invalid_nan`
+    # decorator. These are the methods meant to be called by users.
+    #
+    # Each public method calls a private "dispatch" method that
+    # determines which "method" (strategy for calculating the desired quantity)
+    # to use by default and, via the `@_dispatch` decorator, calls the
+    # method and computes the result.
+    # Each dispatch method can designate the responsibility of computing
+    # the required value to any of several "implementation" methods. These
+    # methods accept only `**params`, the parameter dictionary passed from
+    # the public method via the dispatch method.
+    # See the note corresponding with the "Distribution Parameters" for more
+    # information.
+
+    ## Probability Density Functions
+
+    @_set_invalid_nan
+    def logpdf(self, x, /, *, method=None):
+        return self._logpdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _logpdf_dispatch(self, x, *, method=None, **params):
+        if self._overrides('_logpdf_formula'):
+            method = self._logpdf_formula
+        elif _isnull(self.tol):  # ensure that developers override _logpdf
+            method = self._logpdf_logexp
+        return method
+
+    def _logpdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logpdf_logexp(self, x, **params):
+        return np.log(self._pdf_dispatch(x, **params))
+
+    @_set_invalid_nan
+    def pdf(self, x, /, *, method=None):
+        return self._pdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _pdf_dispatch(self, x, *, method=None, **params):
+        if self._overrides('_pdf_formula'):
+            method = self._pdf_formula
+        else:
+            method = self._pdf_logexp
+        return method
+
+    def _pdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _pdf_logexp(self, x, **params):
+        return np.exp(self._logpdf_dispatch(x, **params))
+
+    ## Cumulative Distribution Functions
+
+    def logcdf(self, x, y=None, /, *, method=None):
+        if y is None:
+            return self._logcdf1(x, method=method)
+        else:
+            return self._logcdf2(x, y, method=method)
+
+    @_cdf2_input_validation
+    def _logcdf2(self, x, y, *, method):
+        out = self._logcdf2_dispatch(x, y, method=method, **self._parameters)
+        return (out + 0j) if not np.issubdtype(out.dtype, np.complexfloating) else out
+
+    @_dispatch
+    def _logcdf2_dispatch(self, x, y, *, method=None, **params):
+        # dtype is complex if any x > y, else real
+        # Should revisit this logic.
+        if self._overrides('_logcdf2_formula'):
+            method = self._logcdf2_formula
+        elif (self._overrides('_logcdf_formula')
+              or self._overrides('_logccdf_formula')):
+            method = self._logcdf2_subtraction
+        elif (self._overrides('_cdf_formula')
+              or self._overrides('_ccdf_formula')):
+            method = self._logcdf2_logexp_safe
+        else:
+            method = self._logcdf2_quadrature
+        return method
+
+    def _logcdf2_formula(self, x, y, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logcdf2_subtraction(self, x, y, **params):
+        flip_sign = x > y  # some results will be negative
+        x, y = np.minimum(x, y), np.maximum(x, y)
+        logcdf_x = self._logcdf_dispatch(x, **params)
+        logcdf_y = self._logcdf_dispatch(y, **params)
+        logccdf_x = self._logccdf_dispatch(x, **params)
+        logccdf_y = self._logccdf_dispatch(y, **params)
+        case_left = (logcdf_x < -1) & (logcdf_y < -1)
+        case_right = (logccdf_x < -1) & (logccdf_y < -1)
+        case_central = ~(case_left | case_right)
+        log_mass = _logexpxmexpy(logcdf_y, logcdf_x)
+        log_mass[case_right] = _logexpxmexpy(logccdf_x, logccdf_y)[case_right]
+        log_tail = np.logaddexp(logcdf_x, logccdf_y)[case_central]
+        log_mass[case_central] = _log1mexp(log_tail)
+        log_mass[flip_sign] += np.pi * 1j
+        return log_mass[()] if np.any(flip_sign) else log_mass.real[()]
+
+    def _logcdf2_logexp(self, x, y, **params):
+        expres = self._cdf2_dispatch(x, y, **params)
+        expres = expres + 0j if np.any(x > y) else expres
+        return np.log(expres)
+
+    def _logcdf2_logexp_safe(self, x, y, **params):
+        out = self._logcdf2_logexp(x, y, **params)
+        mask = np.isinf(out.real)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._logcdf2_quadrature(x[mask], y[mask], **params_mask)
+        return out[()]
+
+    def _logcdf2_quadrature(self, x, y, **params):
+        logres = self._quadrature(self._logpdf_dispatch, limits=(x, y),
+                                  log=True, params=params)
+        return logres
+
+    @_set_invalid_nan
+    def _logcdf1(self, x, *, method=None):
+        return self._logcdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _logcdf_dispatch(self, x, *, method=None, **params):
+        if self._overrides('_logcdf_formula'):
+            method = self._logcdf_formula
+        elif self._overrides('_logccdf_formula'):
+            method = self._logcdf_complement
+        elif self._overrides('_cdf_formula'):
+            method = self._logcdf_logexp_safe
+        else:
+            method = self._logcdf_quadrature
+        return method
+
+    def _logcdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logcdf_complement(self, x, **params):
+        return _log1mexp(self._logccdf_dispatch(x, **params))
+
+    def _logcdf_logexp(self, x, **params):
+        return np.log(self._cdf_dispatch(x, **params))
+
+    def _logcdf_logexp_safe(self, x, **params):
+        out = self._logcdf_logexp(x, **params)
+        mask = np.isinf(out)
+        if np.any(mask):
+            params_mask = {key:np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._logcdf_quadrature(x[mask], **params_mask)
+        return out[()]
+
+    def _logcdf_quadrature(self, x, **params):
+        a, _ = self._support(**params)
+        return self._quadrature(self._logpdf_dispatch, limits=(a, x),
+                                params=params, log=True)
+
+    def cdf(self, x, y=None, /, *, method=None):
+        if y is None:
+            return self._cdf1(x, method=method)
+        else:
+            return self._cdf2(x, y, method=method)
+
+    @_cdf2_input_validation
+    def _cdf2(self, x, y, *, method):
+        return self._cdf2_dispatch(x, y, method=method, **self._parameters)
+
+    @_dispatch
+    def _cdf2_dispatch(self, x, y, *, method=None, **params):
+        # Should revisit this logic.
+        if self._overrides('_cdf2_formula'):
+            method = self._cdf2_formula
+        elif (self._overrides('_logcdf_formula')
+              or self._overrides('_logccdf_formula')):
+            method = self._cdf2_logexp
+        elif self._overrides('_cdf_formula') or self._overrides('_ccdf_formula'):
+            method = self._cdf2_subtraction_safe
+        else:
+            method = self._cdf2_quadrature
+        return method
+
+    def _cdf2_formula(self, x, y, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _cdf2_logexp(self, x, y, **params):
+        return np.real(np.exp(self._logcdf2_dispatch(x, y, **params)))
+
+    def _cdf2_subtraction(self, x, y, **params):
+        # Improvements:
+        # Lazy evaluation of cdf/ccdf only where needed
+        # Stack x and y to reduce function calls?
+        cdf_x = self._cdf_dispatch(x, **params)
+        cdf_y = self._cdf_dispatch(y, **params)
+        ccdf_x = self._ccdf_dispatch(x, **params)
+        ccdf_y = self._ccdf_dispatch(y, **params)
+        i = (ccdf_x < 0.5) & (ccdf_y < 0.5)
+        return np.where(i, ccdf_x-ccdf_y, cdf_y-cdf_x)
+
+    def _cdf2_subtraction_safe(self, x, y, **params):
+        cdf_x = self._cdf_dispatch(x, **params)
+        cdf_y = self._cdf_dispatch(y, **params)
+        ccdf_x = self._ccdf_dispatch(x, **params)
+        ccdf_y = self._ccdf_dispatch(y, **params)
+        i = (ccdf_x < 0.5) & (ccdf_y < 0.5)
+        out = np.where(i, ccdf_x-ccdf_y, cdf_y-cdf_x)
+
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+
+        cdf_max = np.maximum(cdf_x, cdf_y)
+        ccdf_max = np.maximum(ccdf_x, ccdf_y)
+        spacing = np.spacing(np.where(i, ccdf_max, cdf_max))
+        mask = np.abs(tol * out) < spacing
+
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._cdf2_quadrature(x[mask], y[mask], *params_mask)
+        return out[()]
+
+    def _cdf2_quadrature(self, x, y, **params):
+        return self._quadrature(self._pdf_dispatch, limits=(x, y), params=params)
+
+    @_set_invalid_nan
+    def _cdf1(self, x, *, method):
+        return self._cdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _cdf_dispatch(self, x, *, method=None, **params):
+        if self._overrides('_cdf_formula'):
+            method = self._cdf_formula
+        elif self._overrides('_logcdf_formula'):
+            method = self._cdf_logexp
+        elif self._overrides('_ccdf_formula'):
+            method = self._cdf_complement_safe
+        else:
+            method = self._cdf_quadrature
+        return method
+
+    def _cdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _cdf_logexp(self, x, **params):
+        return np.exp(self._logcdf_dispatch(x, **params))
+
+    def _cdf_complement(self, x, **params):
+        return 1 - self._ccdf_dispatch(x, **params)
+
+    def _cdf_complement_safe(self, x, **params):
+        ccdf = self._ccdf_dispatch(x, **params)
+        out = 1 - ccdf
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+        mask = tol * out < np.spacing(ccdf)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._cdf_quadrature(x[mask], *params_mask)
+        return out[()]
+
+    def _cdf_quadrature(self, x, **params):
+        a, _ = self._support(**params)
+        return self._quadrature(self._pdf_dispatch, limits=(a, x),
+                                params=params)
+
+    def logccdf(self, x, y=None, /, *, method=None):
+        if y is None:
+            return self._logccdf1(x, method=method)
+        else:
+            return self._logccdf2(x, y, method=method)
+
+    @_cdf2_input_validation
+    def _logccdf2(self, x, y, *, method):
+        return self._logccdf2_dispatch(x, y, method=method, **self._parameters)
+
+    @_dispatch
+    def _logccdf2_dispatch(self, x, y, *, method=None, **params):
+        # if _logccdf2_formula exists, we could use the complement
+        # if _ccdf2_formula exists, we could use log/exp
+        if self._overrides('_logccdf2_formula'):
+            method = self._logccdf2_formula
+        else:
+            method = self._logccdf2_addition
+        return method
+
+    def _logccdf2_formula(self, x, y, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logccdf2_addition(self, x, y, **params):
+        logcdf_x = self._logcdf_dispatch(x, **params)
+        logccdf_y = self._logccdf_dispatch(y, **params)
+        return special.logsumexp([logcdf_x, logccdf_y], axis=0)
+
+    @_set_invalid_nan
+    def _logccdf1(self, x, *, method=None):
+        return self._logccdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _logccdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_logccdf_formula'):
+            method = self._logccdf_formula
+        elif self._overrides('_logcdf_formula'):
+            method = self._logccdf_complement
+        elif self._overrides('_ccdf_formula'):
+            method = self._logccdf_logexp_safe
+        else:
+            method = self._logccdf_quadrature
+        return method
+
+    def _logccdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _logccdf_complement(self, x, **params):
+        return _log1mexp(self._logcdf_dispatch(x, **params))
+
+    def _logccdf_logexp(self, x, **params):
+        return np.log(self._ccdf_dispatch(x, **params))
+
+    def _logccdf_logexp_safe(self, x, **params):
+        out = self._logccdf_logexp(x, **params)
+        mask = np.isinf(out)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._logccdf_quadrature(x[mask], **params_mask)
+        return out[()]
+
+    def _logccdf_quadrature(self, x, **params):
+        _, b = self._support(**params)
+        return self._quadrature(self._logpdf_dispatch, limits=(x, b),
+                                params=params, log=True)
+
+    def ccdf(self, x, y=None, /, *, method=None):
+        if y is None:
+            return self._ccdf1(x, method=method)
+        else:
+            return self._ccdf2(x, y, method=method)
+
+    @_cdf2_input_validation
+    def _ccdf2(self, x, y, *, method):
+        return self._ccdf2_dispatch(x, y, method=method, **self._parameters)
+
+    @_dispatch
+    def _ccdf2_dispatch(self, x, y, *, method=None, **params):
+        if self._overrides('_ccdf2_formula'):
+            method = self._ccdf2_formula
+        else:
+            method = self._ccdf2_addition
+        return method
+
+    def _ccdf2_formula(self, x, y, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _ccdf2_addition(self, x, y, **params):
+        cdf_x = self._cdf_dispatch(x, **params)
+        ccdf_y = self._ccdf_dispatch(y, **params)
+        # even if x > y, cdf(x, y) + ccdf(x,y) sums to 1
+        return cdf_x + ccdf_y
+
+    @_set_invalid_nan
+    def _ccdf1(self, x, *, method):
+        return self._ccdf_dispatch(x, method=method, **self._parameters)
+
+    @_dispatch
+    def _ccdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_ccdf_formula'):
+            method = self._ccdf_formula
+        elif self._overrides('_logccdf_formula'):
+            method = self._ccdf_logexp
+        elif self._overrides('_cdf_formula'):
+            method = self._ccdf_complement_safe
+        else:
+            method = self._ccdf_quadrature
+        return method
+
+    def _ccdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _ccdf_logexp(self, x, **params):
+        return np.exp(self._logccdf_dispatch(x, **params))
+
+    def _ccdf_complement(self, x, **params):
+        return 1 - self._cdf_dispatch(x, **params)
+
+    def _ccdf_complement_safe(self, x, **params):
+        cdf = self._cdf_dispatch(x, **params)
+        out = 1 - cdf
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+        mask = tol * out < np.spacing(cdf)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._ccdf_quadrature(x[mask], **params_mask)
+        return out[()]
+
+    def _ccdf_quadrature(self, x, **params):
+        _, b = self._support(**params)
+        return self._quadrature(self._pdf_dispatch, limits=(x, b),
+                                params=params)
+
+    ## Inverse cumulative distribution functions
+
+    @_set_invalid_nan
+    def ilogcdf(self, logp, /, *, method=None):
+        return self._ilogcdf_dispatch(logp, method=method, **self._parameters)
+
+    @_dispatch
+    def _ilogcdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_ilogcdf_formula'):
+            method = self._ilogcdf_formula
+        elif self._overrides('_ilogccdf_formula'):
+            method = self._ilogcdf_complement
+        else:
+            method = self._ilogcdf_inversion
+        return method
+
+    def _ilogcdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _ilogcdf_complement(self, x, **params):
+        return self._ilogccdf_dispatch(_log1mexp(x), **params)
+
+    def _ilogcdf_inversion(self, x, **params):
+        return self._solve_bounded(self._logcdf_dispatch, x, params=params)
+
+    @_set_invalid_nan
+    def icdf(self, p, /, *, method=None):
+        return self._icdf_dispatch(p, method=method, **self._parameters)
+
+    @_dispatch
+    def _icdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_icdf_formula'):
+            method = self._icdf_formula
+        elif self._overrides('_iccdf_formula'):
+            method = self._icdf_complement_safe
+        else:
+            method = self._icdf_inversion
+        return method
+
+    def _icdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _icdf_complement(self, x, **params):
+        return self._iccdf_dispatch(1 - x, **params)
+
+    def _icdf_complement_safe(self, x, **params):
+        out = self._icdf_complement(x, **params)
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+        mask = tol * x < np.spacing(1 - x)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._icdf_inversion(x[mask], *params_mask)
+        return out[()]
+
+    def _icdf_inversion(self, x, **params):
+        return self._solve_bounded(self._cdf_dispatch, x, params=params)
+
+    @_set_invalid_nan
+    def ilogccdf(self, logp, /, *, method=None):
+        return self._ilogccdf_dispatch(logp, method=method, **self._parameters)
+
+    @_dispatch
+    def _ilogccdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_ilogccdf_formula'):
+            method = self._ilogccdf_formula
+        elif self._overrides('_ilogcdf_formula'):
+            method = self._ilogccdf_complement
+        else:
+            method = self._ilogccdf_inversion
+        return method
+
+    def _ilogccdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _ilogccdf_complement(self, x, **params):
+        return self._ilogcdf_dispatch(_log1mexp(x), **params)
+
+    def _ilogccdf_inversion(self, x, **params):
+        return self._solve_bounded(self._logccdf_dispatch, x, params=params)
+
+    @_set_invalid_nan
+    def iccdf(self, p, /, *, method=None):
+        return self._iccdf_dispatch(p, method=method, **self._parameters)
+
+    @_dispatch
+    def _iccdf_dispatch(self, x, method=None, **params):
+        if self._overrides('_iccdf_formula'):
+            method = self._iccdf_formula
+        elif self._overrides('_icdf_formula'):
+            method = self._iccdf_complement_safe
+        else:
+            method = self._iccdf_inversion
+        return method
+
+    def _iccdf_formula(self, x, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _iccdf_complement(self, x, **params):
+        return self._icdf_dispatch(1 - x, **params)
+
+    def _iccdf_complement_safe(self, x, **params):
+        out = self._iccdf_complement(x, **params)
+        eps = np.finfo(self._dtype).eps
+        tol = self.tol if not _isnull(self.tol) else np.sqrt(eps)
+        mask = tol * x < np.spacing(1 - x)
+        if np.any(mask):
+            params_mask = {key: np.broadcast_to(val, mask.shape)[mask]
+                           for key, val in params.items()}
+            out = np.asarray(out)
+            out[mask] = self._iccdf_inversion(x[mask], *params_mask)
+        return out[()]
+
+    def _iccdf_inversion(self, x, **params):
+        return self._solve_bounded(self._ccdf_dispatch, x, params=params)
+
+    ### Sampling Functions
+    # The following functions for drawing samples from the distribution are
+    # exposed via a public method that accepts one positional argument - the
+    # shape of the sample - and keyword options (but not distribution
+    # parameters).
+    # sample
+    # ~~qmc_sample~~ built into sample now
+    #
+    # Common keyword options include:
+    # method - a string that indicates which method should be used to compute
+    #          the quantity (e.g. a formula or numerical integration).
+    # rng - the NumPy Generator/SciPy QMCEngine object to used for drawing numbers.
+    #
+    # Input/output validation is included in each function, since there is
+    # little code to be shared.
+    # These are the methods meant to be called by users.
+    #
+    # Each public method calls a private "dispatch" method that
+    # determines which "method" (strategy for calculating the desired quantity)
+    # to use by default and, via the `@_dispatch` decorator, calls the
+    # method and computes the result.
+    # Each dispatch method can designate the responsibility of sampling to any
+    # of several "implementation" methods. These methods accept only
+    # `**params`, the parameter dictionary passed from the public method via
+    # the "dispatch" method.
+    # See the note corresponding with the "Distribution Parameters" for more
+    # information.
+
+    # TODO:
+    #  - should we accept a QRNG with `d != 1`?
+    def sample(self, shape=(), *, method=None, rng=None):
+        # needs output validation to ensure that developer returns correct
+        # dtype and shape
+        sample_shape = (shape,) if not np.iterable(shape) else tuple(shape)
+        full_shape = sample_shape + self._shape
+        rng = np.random.default_rng(rng) if not isinstance(rng, qmc.QMCEngine) else rng
+        res = self._sample_dispatch(sample_shape, full_shape, method=method,
+                                    rng=rng, **self._parameters)
+
+        return res.astype(self._dtype, copy=False)
+
+    @_dispatch
+    def _sample_dispatch(self, sample_shape, full_shape, *, method, rng, **params):
+        # make sure that tests catch if sample is 0d array
+        if self._overrides('_sample_formula') and not isinstance(rng, qmc.QMCEngine):
+            method = self._sample_formula
+        else:
+            method = self._sample_inverse_transform
+        return method
+
+    def _sample_formula(self, sample_shape, full_shape, *, rng, **params):
+        raise NotImplementedError(self._not_implemented)
+
+    def _sample_inverse_transform(self, sample_shape, full_shape, *, rng, **params):
+        if isinstance(rng, qmc.QMCEngine):
+            uniform = self._qmc_uniform(sample_shape, full_shape, qrng=rng, **params)
+        else:
+            uniform = rng.random(size=full_shape, dtype=self._dtype)
+        return self._icdf_dispatch(uniform, **params)
+
+    def _qmc_uniform(self, sample_shape, full_shape, *, qrng, **params):
+        # Generate QMC uniform sample(s) on unit interval with specified shape;
+        # if `sample_shape != ()`, then each slice along axis 0 is independent.
+
+        # Determine the number of independent sequences and the length of each.
+        n_low_discrepancy = sample_shape[0] if sample_shape else 1
+        n_independent = math.prod(full_shape[1:] if sample_shape else full_shape)
+
+        # For each independent sequence, we'll need a new QRNG of the appropriate class
+        # with its own RNG. (If scramble=False, we don't really need all the separate
+        # rngs, but I'm not going to add a special code path right now.)
+        rngs = _rng_spawn(qrng.rng, n_independent)
+        qrng_class = qrng.__class__
+        kwargs = dict(d=1, scramble=qrng.scramble, optimization=qrng._optimization)
+        if isinstance(qrng, qmc.Sobol):
+            kwargs['bits'] = qrng.bits
+
+        # Draw uniform low-discrepancy sequences scrambled with each RNG
+        uniforms = []
+        for rng in rngs:
+            qrng = qrng_class(seed=rng, **kwargs)
+            uniform = qrng.random(n_low_discrepancy)
+            uniform = uniform.reshape(n_low_discrepancy if sample_shape else ())[()]
+            uniforms.append(uniform)
+
+        # Reorder the axes and ensure that the shape is correct
+        uniform = np.moveaxis(np.stack(uniforms), -1, 0) if uniforms else np.asarray([])
+        return uniform.reshape(full_shape)
+
+    ### Moments
+    # The `moment` method accepts two positional arguments - the order and kind
+    # (raw, central, or standard) of the moment - and a keyword option:
+    # method - a string that indicates which method should be used to compute
+    #          the quantity (e.g. a formula or numerical integration).
+    # Like the distribution properties, input/output validation is provided by
+    # the `_set_invalid_nan_property` decorator.
+    #
+    # Unlike most public methods above, `moment` dispatches to one of three
+    # private methods - one for each 'kind'. Like most *public* methods above,
+    # each of these private methods calls a private "dispatch" method that
+    # determines which "method" (strategy for calculating the desired quantity)
+    # to use. Also, each dispatch method can designate the responsibility
+    # computing the moment to one of several "implementation" methods.
+    # Unlike the dispatch methods above, however, the `@_dispatch` decorator
+    # is not used, and both logic and method calls are included in the function
+    # itself.
+    # Instead of determining which method will be used based solely on the
+    # implementation methods available and calling only the corresponding
+    # implementation method, *all* the implementation methods are called
+    # in sequence until one returns the desired information. When an
+    # implementation methods cannot provide the requested information, it
+    # returns the object None (which is distinct from arrays with NaNs or infs,
+    # which are valid values of moments).
+    # The reason for this approach is that although formulae for the first
+    # few moments of a distribution may be found, general formulae that work
+    # for all orders are not always easy to find. This approach allows the
+    # developer to write "formula" implementation functions that return the
+    # desired moment when it is available and None otherwise.
+    #
+    # Note that the first implementation method called is a cache. This is
+    # important because lower-order moments are often needed to compute
+    # higher moments from formulae, so we eliminate redundant calculations
+    # when moments of several orders are needed.
+
+    @cached_property
+    def _moment_methods(self):
+        return {'cache', 'formula', 'transform',
+                'normalize', 'general', 'quadrature'}
+
+    @property
+    def _zero(self):
+        return self._constants()[0]
+
+    @property
+    def _one(self):
+        return self._constants()[1]
+
+    def _constants(self):
+        if self._constant_cache is not None:
+            return self._constant_cache
+
+        constants = self._preserve_type([0, 1])
+
+        if self.cache_policy != _NO_CACHE:
+            self._constant_cache = constants
+
+        return constants
+
+    @_set_invalid_nan_property
+    def moment(self, order=1, kind='raw', *, method=None):
+        kinds = {'raw': self._moment_raw,
+                 'central': self._moment_central,
+                 'standardized': self._moment_standardized}
+        order = self._validate_order_kind(order, kind, kinds)
+        moment_kind = kinds[kind]
+        return moment_kind(order, method=method)
+
+    def _moment_raw(self, order=1, *, method=None):
+        """Raw distribution moment about the origin."""
+        # Consider exposing the point about which moments are taken as an
+        # option. This is easy to support, since `_moment_transform_center`
+        # does all the work.
+        methods = self._moment_methods if method is None else {method}
+        return self._moment_raw_dispatch(order, methods=methods, **self._parameters)
+
+    def _moment_raw_dispatch(self, order, *, methods, **params):
+        moment = None
+
+        if 'cache' in methods:
+            moment = self._moment_raw_cache.get(order, None)
+
+        if moment is None and 'formula' in methods:
+            moment = self._moment_raw_formula(order, **params)
+
+        if moment is None and 'transform' in methods and order > 1:
+            moment = self._moment_raw_transform(order, **params)
+
+        if moment is None and 'general' in methods:
+            moment = self._moment_raw_general(order, **params)
+
+        if moment is None and 'quadrature' in methods:
+            moment = self._moment_integrate_pdf(order, center=self._zero, **params)
+
+        if moment is None and 'quadrature_icdf' in methods:
+            moment = self._moment_integrate_icdf(order, center=self._zero, **params)
+
+        if moment is not None and self.cache_policy != _NO_CACHE:
+            self._moment_raw_cache[order] = moment
+
+        return moment
+
+    def _moment_raw_formula(self, order, **params):
+        return None
+
+    def _moment_raw_transform(self, order, **params):
+        central_moments = []
+        for i in range(int(order) + 1):
+            methods = {'cache', 'formula', 'normalize', 'general'}
+            moment_i = self._moment_central_dispatch(order=i, methods=methods, **params)
+            if moment_i is None:
+                return None
+            central_moments.append(moment_i)
+
+        # Doesn't make sense to get the mean by "transform", since that's
+        # how we got here. Questionable whether 'quadrature' should be here.
+        mean_methods = {'cache', 'formula', 'quadrature'}
+        mean = self._moment_raw_dispatch(self._one, methods=mean_methods, **params)
+        if mean is None:
+            return None
+
+        moment = self._moment_transform_center(order, central_moments, mean, self._zero)
+        return moment
+
+    def _moment_raw_general(self, order, **params):
+        # This is the only general formula for a raw moment of a probability
+        # distribution
+        return self._one if order == 0 else None
+
+    def _moment_central(self, order=1, *, method=None):
+        """Distribution moment about the mean."""
+        methods = self._moment_methods if method is None else {method}
+        return self._moment_central_dispatch(order, methods=methods, **self._parameters)
+
+    def _moment_central_dispatch(self, order, *, methods, **params):
+        moment = None
+
+        if 'cache' in methods:
+            moment = self._moment_central_cache.get(order, None)
+
+        if moment is None and 'formula' in methods:
+            moment = self._moment_central_formula(order, **params)
+
+        if moment is None and 'transform' in methods:
+            moment = self._moment_central_transform(order, **params)
+
+        if moment is None and 'normalize' in methods and order > 2:
+            moment = self._moment_central_normalize(order, **params)
+
+        if moment is None and 'general' in methods:
+            moment = self._moment_central_general(order, **params)
+
+        if moment is None and 'quadrature' in methods:
+            mean = self._moment_raw_dispatch(self._one, **params,
+                                             methods=self._moment_methods)
+            moment = self._moment_integrate_pdf(order, center=mean, **params)
+
+        if moment is None and 'quadrature_icdf' in methods:
+            mean = self._moment_raw_dispatch(self._one, **params,
+                                             methods=self._moment_methods)
+            moment = self._moment_integrate_icdf(order, center=mean, **params)
+
+        if moment is not None and self.cache_policy != _NO_CACHE:
+            self._moment_central_cache[order] = moment
+
+        return moment
+
+    def _moment_central_formula(self, order, **params):
+        return None
+
+    def _moment_central_transform(self, order, **params):
+
+        raw_moments = []
+        for i in range(int(order) + 1):
+            methods = {'cache', 'formula', 'general'}
+            moment_i = self._moment_raw_dispatch(order=i, methods=methods, **params)
+            if moment_i is None:
+                return None
+            raw_moments.append(moment_i)
+
+        mean_methods = self._moment_methods
+        mean = self._moment_raw_dispatch(self._one, methods=mean_methods, **params)
+
+        moment = self._moment_transform_center(order, raw_moments, self._zero, mean)
+        return moment
+
+    def _moment_central_normalize(self, order, **params):
+        methods = {'cache', 'formula', 'general'}
+        standard_moment = self._moment_standardized_dispatch(order, **params,
+                                                             methods=methods)
+        if standard_moment is None:
+            return None
+        var = self._moment_central_dispatch(2, methods=self._moment_methods, **params)
+        return standard_moment*var**(order/2)
+
+    def _moment_central_general(self, order, **params):
+        general_central_moments = {0: self._one, 1: self._zero}
+        return general_central_moments.get(order, None)
+
+    def _moment_standardized(self, order=1, *, method=None):
+        """Standardized distribution moment."""
+        methods = self._moment_methods if method is None else {method}
+        return self._moment_standardized_dispatch(order, methods=methods,
+                                                  **self._parameters)
+
+    def _moment_standardized_dispatch(self, order, *, methods, **params):
+        moment = None
+
+        if 'cache' in methods:
+            moment = self._moment_standardized_cache.get(order, None)
+
+        if moment is None and 'formula' in methods:
+            moment = self._moment_standardized_formula(order, **params)
+
+        if moment is None and 'normalize' in methods:
+            moment = self._moment_standardized_normalize(order, False, **params)
+
+        if moment is None and 'general' in methods:
+            moment = self._moment_standardized_general(order, **params)
+
+        if moment is None and 'normalize' in methods:
+            moment = self._moment_standardized_normalize(order, True, **params)
+
+        if moment is not None and self.cache_policy != _NO_CACHE:
+            self._moment_standardized_cache[order] = moment
+
+        return moment
+
+    def _moment_standardized_formula(self, order, **params):
+        return None
+
+    def _moment_standardized_normalize(self, order, use_quadrature, **params):
+        methods = ({'quadrature'} if use_quadrature
+                   else {'cache', 'formula', 'transform'})
+        central_moment = self._moment_central_dispatch(order, **params,
+                                                       methods=methods)
+        if central_moment is None:
+            return None
+        var = self._moment_central_dispatch(2, methods=self._moment_methods,
+                                            **params)
+        return central_moment/var**(order/2)
+
+    def _moment_standardized_general(self, order, **params):
+        general_standard_moments = {0: self._one, 1: self._zero, 2: self._one}
+        return general_standard_moments.get(order, None)
+
+    def _moment_integrate_pdf(self, order, center, **params):
+        def integrand(x, order, center, **params):
+            pdf = self._pdf_dispatch(x, **params)
+            return pdf*(x-center)**order
+        return self._quadrature(integrand, args=(order, center), params=params)
+
+    def _moment_integrate_icdf(self, order, center, **params):
+        def integrand(x, order, center, **params):
+            x = self._icdf_dispatch(x, **params)
+            return (x-center)**order
+        return self._quadrature(integrand, limits=(0., 1.),
+                                args=(order, center), params=params)
+
+    def _moment_transform_center(self, order, moment_as, a, b):
+        a, b, *moment_as = np.broadcast_arrays(a, b, *moment_as)
+        n = order
+        i = np.arange(n+1).reshape([-1]+[1]*a.ndim)  # orthogonal to other axes
+        i = self._preserve_type(i)
+        n_choose_i = special.binom(n, i)
+        with np.errstate(invalid='ignore'):  # can happen with infinite moment
+            moment_b = np.sum(n_choose_i*moment_as*(a-b)**(n-i), axis=0)
+        return moment_b
+
+    def _logmoment(self, order=1, *, logcenter=None, standardized=False):
+        # make this private until it is worked into moment
+        if logcenter is None or standardized is True:
+            logmean = self._logmoment_quad(self._one, -np.inf, **self._parameters)
+        else:
+            logmean = None
+
+        logcenter = logmean if logcenter is None else logcenter
+        res = self._logmoment_quad(order, logcenter, **self._parameters)
+        if standardized:
+            logvar = self._logmoment_quad(2, logmean, **self._parameters)
+            res = res - logvar * (order/2)
+        return res
+
+    def _logmoment_quad(self, order, logcenter, **params):
+        def logintegrand(x, order, logcenter, **params):
+            logpdf = self._logpdf_dispatch(x, **params)
+            return logpdf + order * _logexpxmexpy(np.log(x + 0j), logcenter)
+            ## if logx == logcenter, `_logexpxmexpy` returns (-inf + 0j)
+            ## multiplying by order produces (-inf + nan j) - bad
+            ## We're skipping logmoment tests, so we might don't need to fix
+            ## now, but if we ever do use run them, this might help:
+            # logx = np.log(x+0j)
+            # out = np.asarray(logpdf + order*_logexpxmexpy(logx, logcenter))
+            # i = (logx == logcenter)
+            # out[i] = logpdf[i]
+            # return out
+        return self._quadrature(logintegrand, args=(order, logcenter),
+                                params=params, log=True)
+
+    ### Convenience
+
+    def plot(self, x='x', y='pdf', *, t=('cdf', 0.0005, 0.9995), ax=None):
+        r"""Plot a function of the distribution.
+
+        Convenience function for quick visualization of the distribution
+        underlying the random variable.
+
+        Parameters
+        ----------
+        x, y : str, optional
+            String indicating the quantities to be used as the abscissa and
+            ordinate (horizontal and vertical coordinates), respectively.
+            Defaults are ``'x'`` (the domain of the random variable) and
+            ``'pdf'`` (the probability density function). Valid values are:
+            'x', 'pdf', 'cdf', 'ccdf', 'icdf', 'iccdf', 'logpdf', 'logcdf',
+            'logccdf', 'ilogcdf', 'ilogccdf'.
+        t : 3-tuple of (str, float, float), optional
+            Tuple indicating the limits within which the quantities are plotted.
+            Default is ``('cdf', 0.001, 0.999)`` indicating that the central
+            99.9% of the distribution is to be shown. Valid values are:
+            'x', 'cdf', 'ccdf', 'icdf', 'iccdf', 'logcdf', 'logccdf',
+            'ilogcdf', 'ilogccdf'.
+        ax : `matplotlib.axes`, optional
+            Axes on which to generate the plot. If not provided, use the
+            current axes.
+
+        Returns
+        -------
+        ax : `matplotlib.axes`
+            Axes on which the plot was generated.
+            The plot can be customized by manipulating this object.
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> import matplotlib.pyplot as plt
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Plot the PDF over the central 99.9% of the distribution.
+        Compare against a histogram of a random sample.
+
+        >>> ax = X.plot()
+        >>> sample = X.sample(10000)
+        >>> ax.hist(sample, density=True, bins=50, alpha=0.5)
+        >>> plt.show()
+
+        Plot ``logpdf(x)`` as a function of ``x`` in the left tail,
+        where the log of the CDF is between -10 and ``np.log(0.5)``.
+
+        >>> X.plot('x', 'logpdf', t=('logcdf', -10, np.log(0.5)))
+        >>> plt.show()
+
+        Plot the PDF of the normal distribution as a function of the
+        CDF for various values of the scale parameter.
+
+        >>> X = stats.Normal(mu=0., sigma=[0.5, 1., 2])
+        >>> X.plot('cdf', 'pdf')
+        >>> plt.show()
+
+        """
+
+        # Strategy: given t limits, get quantile limits. Form grid of
+        # quantiles, compute requested x and y at quantiles, and plot.
+        # Currently, the grid of quantiles is always linearly spaced.
+        # Instead of always computing linearly-spaced quantiles, it
+        # would be better to choose:
+        # a) quantiles or probabilities
+        # b) linearly or logarithmically spaced
+        # based on the specified `t`.
+        # TODO:
+        # - smart spacing of points
+        # - when the parameters of the distribution are an array,
+        #   use the full range of abscissae for all curves
+
+        t_is_quantile = {'x', 'icdf', 'iccdf', 'ilogcdf', 'ilogccdf'}
+        t_is_probability = {'cdf', 'ccdf', 'logcdf', 'logccdf'}
+        valid_t = t_is_quantile.union(t_is_probability)
+        valid_xy =  valid_t.union({'pdf', 'logpdf'})
+
+        ndim = self._ndim
+        x_name, y_name = x, y
+        t_name, tlim = t[0], np.asarray(t[1:])
+        tlim = tlim[:, np.newaxis] if ndim else tlim
+
+        # pdf/logpdf are not valid for `t` because we can't easily invert them
+        message = (f'Argument `t` of `{self.__class__.__name__}.plot` "'
+                   f'must be one of {valid_t}')
+        if t_name not in valid_t:
+            raise ValueError(message)
+
+        message = (f'Argument `x` of `{self.__class__.__name__}.plot` "'
+                   f'must be one of {valid_xy}')
+        if x_name not in valid_xy:
+            raise ValueError(message)
+
+        message = (f'Argument `y` of `{self.__class__.__name__}.plot` "'
+                   f'must be one of {valid_xy}')
+        if t_name not in valid_xy:
+            raise ValueError(message)
+
+        # This could just be a warning
+        message = (f'`{self.__class__.__name__}.plot` was called on a random '
+                   'variable with at least one invalid shape parameters. When '
+                   'a parameter is invalid, no plot can be shown.')
+        if self._any_invalid:
+            raise ValueError(message)
+
+        # We could automatically ravel, but do we want to? For now, raise.
+        message = ("To use `plot`, distribution parameters must be "
+                   "scalars or arrays with one or fewer dimensions.")
+        if ndim > 1:
+            raise ValueError(message)
+
+        try:
+            import matplotlib.pyplot as plt  # noqa: F401, E402
+        except ModuleNotFoundError as exc:
+            message = ("`matplotlib` must be installed to use "
+                       f"`{self.__class__.__name__}.plot`.")
+            raise ModuleNotFoundError(message) from exc
+        ax = plt.gca() if ax is None else ax
+
+        # get quantile limits given t limits
+        qlim = tlim if t_name in t_is_quantile else getattr(self, 'i'+t_name)(tlim)
+
+        message = (f"`{self.__class__.__name__}.plot` received invalid input for `t`: "
+                   f"calling {'i'+t_name}({tlim}) produced {qlim}.")
+        if not np.all(np.isfinite(qlim)):
+            raise ValueError(message)
+
+        # form quantile grid
+        grid = np.linspace(0, 1, 300)
+        grid = grid[:, np.newaxis] if ndim else grid
+        q = qlim[0] + (qlim[1] - qlim[0]) * grid
+
+        # compute requested x and y at quantile grid
+        x = q if x_name in t_is_quantile else getattr(self, x_name)(q)
+        y = q if y_name in t_is_quantile else getattr(self, y_name)(q)
+
+        # make plot
+        ax.plot(x, y)
+        ax.set_xlabel(f"${x_name}$")
+        ax.set_ylabel(f"${y_name}$")
+        ax.set_title(str(self))
+
+        # only need a legend if distribution has parameters
+        if len(self._parameters):
+            label = []
+            parameters = self._parameterization.parameters
+            param_names = list(parameters)
+            param_arrays = [np.atleast_1d(self._parameters[pname])
+                            for pname in param_names]
+            for param_vals in zip(*param_arrays):
+                assignments = [f"${parameters[name].symbol}$ = {val:.4g}"
+                               for name, val in zip(param_names, param_vals)]
+                label.append(", ".join(assignments))
+            ax.legend(label)
+
+        return ax
+
+
+    ### Fitting
+    # All methods above treat the distribution parameters as fixed, and the
+    # variable argument may be a quantile or probability. The fitting functions
+    # are fundamentally different because the quantiles (often observations)
+    # are considered to be fixed, and the distribution parameters are the
+    # variables. In a sense, they are like an inverse of the sampling
+    # functions.
+    #
+    # At first glance, it would seem ideal for `fit` to be a classmethod,
+    # called like `LogUniform.fit(sample=sample)`.
+    # I tried this. I insisted on it for a while. But if `fit` is a
+    # classmethod, it cannot call instance methods. If we want to support MLE,
+    # MPS, MoM, MoLM, then we end up with most of the distribution functions
+    # above needing to be classmethods, too. All state information, such as
+    # tolerances and the underlying distribution of `ShiftedScaledDistribution`
+    # and `OrderStatisticDistribution`, would need to be passed into all
+    # methods. And I'm not really sure how we would call `fit` as a
+    # classmethod of a transformed distribution - maybe
+    # ShiftedScaledDistribution.fit would accept the class of the
+    # shifted/scaled distribution as an argument?
+    #
+    # In any case, it was a conscious decision for the infrastructure to
+    # treat the parameters as "fixed" and the quantile/percentile arguments
+    # as "variable". There are a lot of advantages to this structure, and I
+    # don't think the fact that a few methods reverse the fixed and variable
+    # quantities should make us question that choice. It can still accomodate
+    # these methods reasonably efficiently.
+
+
+# Special case the names of some new-style distributions in `make_distribution`
+_distribution_names = {
+    'argus': 'ARGUS',
+    'betaprime': 'BetaPrime',
+    'chi2': 'ChiSquared',
+    'crystalball': 'CrystalBall',
+    'dgamma': 'DoubleGamma',
+    'dweibull': 'DoubleWeibull',
+    'expon': 'Exponential',
+    'exponnorm': 'ExponentiallyModifiedNormal',
+    'exponweib': 'ExponentialWeibull',
+    'exponpow': 'ExponentialPower',
+    'fatiguelife': 'FatigueLife',
+    'foldcauchy': 'FoldedCauchy',
+    'foldnorm': 'FoldedNormal',
+    'genlogistic': 'GeneralizedLogistic',
+    'gennorm': 'GeneralizedNormal',
+    'genpareto': 'GeneralizedPareto',
+    'genexpon': 'GeneralizedExponential',
+    'genextreme': 'GeneralizedExtremeValue',
+    'gausshyper': 'GaussHypergeometric',
+    'gengamma': 'GeneralizedGamma',
+    'genhalflogistic': 'GeneralizedHalfLogistic',
+    'geninvgauss': 'GeneralizedInverseGaussian',
+    'gumbel_r': 'Gumbel',
+    'gumbel_l': 'ReflectedGumbel',
+    'halfcauchy': 'HalfCauchy',
+    'halflogistic': 'HalfLogistic',
+    'halfnorm': 'HalfNormal',
+    'halfgennorm': 'HalfGeneralizedNormal',
+    'hypsecant': 'HyperbolicSecant',
+    'invgamma': 'InverseGammma',
+    'invgauss': 'InverseGaussian',
+    'invweibull': 'InverseWeibull',
+    'irwinhall': 'IrwinHall',
+    'jf_skew_t': 'JonesFaddySkewT',
+    'johnsonsb': 'JohnsonSB',
+    'johnsonsu': 'JohnsonSU',
+    'ksone': 'KSOneSided',
+    'kstwo': 'KSTwoSided',
+    'kstwobign': 'KSTwoSidedAsymptotic',
+    'laplace_asymmetric': 'LaplaceAsymmetric',
+    'levy_l': 'LevyLeft',
+    'levy_stable': 'LevyStable',
+    'loggamma': 'ExpGamma',  # really the Exponential Gamma Distribution
+    'loglaplace': 'LogLaplace',
+    'lognorm': 'LogNormal',
+    'loguniform': 'LogUniform',
+    'ncx2': 'NoncentralChiSquared',
+    'nct': 'NoncentralT',
+    'norm': 'Normal',
+    'norminvgauss': 'NormalInverseGaussian',
+    'powerlaw': 'PowerLaw',
+    'powernorm': 'PowerNormal',
+    'rdist': 'R',
+    'rel_breitwigner': 'RelativisticBreitWigner',
+    'recipinvgauss': 'ReciprocalInverseGaussian',
+    'reciprocal': 'LogUniform',
+    'semicircular': 'SemiCircular',
+    'skewcauchy': 'SkewCauchy',
+    'skewnorm': 'SkewNormal',
+    'studentized_range': 'StudentizedRange',
+    't': 'StudentT',
+    'trapezoid': 'Trapezoidal',
+    'triang': 'Triangular',
+    'truncexpon': 'TruncatedExponential',
+    'truncnorm': 'TruncatedNormal',
+    'truncpareto': 'TruncatedPareto',
+    'truncweibull_min': 'TruncatedWeibull',
+    'tukeylambda': 'TukeyLambda',
+    'vonmises_line': 'VonMisesLine',
+    'weibull_min': 'Weibull',
+    'weibull_max': 'ReflectedWeibull',
+    'wrapcauchy': 'WrappedCauchyLine',
+}
+
+
+# beta, genextreme, gengamma, t, tukeylambda need work for 1D arrays
+def make_distribution(dist):
+    """Generate a `ContinuousDistribution` from an instance of `rv_continuous`
+
+    The returned value is a `ContinuousDistribution` subclass. Like any subclass
+    of `ContinuousDistribution`, it must be instantiated (i.e. by passing all shape
+    parameters as keyword arguments) before use. Once instantiated, the resulting
+    object will have the same interface as any other instance of
+    `ContinuousDistribution`; e.g., `scipy.stats.Normal`.
+
+    .. note::
+
+        `make_distribution` does not work perfectly with all instances of
+        `rv_continuous`. Known failures include `levy_stable` and `vonmises`,
+        and some methods of some distributions will not support array shape
+        parameters.
+
+    Parameters
+    ----------
+    dist : `rv_continuous`
+        Instance of `rv_continuous`.
+
+    Returns
+    -------
+    CustomDistribution : `ContinuousDistribution`
+        A subclass of `ContinuousDistribution` corresponding with `dist`. The
+        initializer requires all shape parameters to be passed as keyword arguments
+        (using the same names as the instance of `rv_continuous`).
+
+    Notes
+    -----
+    The documentation of `ContinuousDistribution` is not rendered. See below for
+    an example of how to instantiate the class (i.e. pass all shape parameters of
+    `dist` to the initializer as keyword arguments). Documentation of all methods
+    is identical to that of `scipy.stats.Normal`. Use ``help`` on the returned
+    class or its methods for more information.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> LogU = stats.make_distribution(stats.loguniform)
+    >>> X = LogU(a=1.0, b=3.0)
+    >>> np.isclose((X + 0.25).median(), stats.loguniform.ppf(0.5, 1, 3, loc=0.25))
+    np.True_
+    >>> X.plot()
+    >>> sample = X.sample(10000, rng=np.random.default_rng())
+    >>> plt.hist(sample, density=True, bins=30)
+    >>> plt.legend(('pdf', 'histogram'))
+    >>> plt.show()
+
+    """
+    if dist in {stats.levy_stable, stats.vonmises}:
+        raise NotImplementedError(f"`{dist.name}` is not supported.")
+
+    if not isinstance(dist, stats.rv_continuous):
+        message = "The argument must be an instance of `rv_continuous`."
+        raise ValueError(message)
+
+    parameters = []
+    names = []
+    support = getattr(dist, '_support', (dist.a, dist.b))
+    for shape_info in dist._shape_info():
+        domain = _RealDomain(endpoints=shape_info.endpoints,
+                             inclusive=shape_info.inclusive)
+        param = _RealParameter(shape_info.name, domain=domain)
+        parameters.append(param)
+        names.append(shape_info.name)
+
+    _x_support = _RealDomain(endpoints=support, inclusive=(True, True))
+    _x_param = _RealParameter('x', domain=_x_support, typical=(-1, 1))
+
+    repr_str = _distribution_names.get(dist.name, dist.name.capitalize())
+
+    class CustomDistribution(ContinuousDistribution):
+        _parameterizations = ([_Parameterization(*parameters)] if parameters
+                              else [])
+        _variable = _x_param
+
+        def __repr__(self):
+            s = super().__repr__()
+            return s.replace('CustomDistribution', repr_str)
+
+        def __str__(self):
+            s = super().__str__()
+            return s.replace('CustomDistribution', repr_str)
+
+    # override the domain's `get_numerical_endpoints` rather than the
+    # distribution's `_support` to ensure that `_support` takes care
+    # of any required broadcasting, etc.
+    def get_numerical_endpoints(parameter_values):
+        a, b = dist._get_support(**parameter_values)
+        return np.asarray(a)[()], np.asarray(b)[()]
+
+    def _sample_formula(self, _, full_shape=(), *, rng=None, **kwargs):
+        return dist._rvs(size=full_shape, random_state=rng, **kwargs)
+
+    def _moment_raw_formula(self, order, **kwargs):
+        return dist._munp(int(order), **kwargs)
+
+    def _moment_raw_formula_1(self, order, **kwargs):
+        if order != 1:
+            return None
+        return dist._stats(**kwargs)[0]
+
+    def _moment_central_formula(self, order, **kwargs):
+        if order != 2:
+            return None
+        return dist._stats(**kwargs)[1]
+
+    def _moment_standard_formula(self, order, **kwargs):
+        if order == 3:
+            if dist._stats_has_moments:
+                kwargs['moments'] = 's'
+            return dist._stats(**kwargs)[int(order - 1)]
+        elif order == 4:
+            if dist._stats_has_moments:
+                kwargs['moments'] = 'k'
+            k = dist._stats(**kwargs)[int(order - 1)]
+            return k if k is None else k + 3
+        else:
+            return None
+
+    methods = {'_logpdf': '_logpdf_formula',
+               '_pdf': '_pdf_formula',
+               '_logcdf': '_logcdf_formula',
+               '_cdf': '_cdf_formula',
+               '_logsf': '_logccdf_formula',
+               '_sf': '_ccdf_formula',
+               '_ppf': '_icdf_formula',
+               '_isf': '_iccdf_formula',
+               '_entropy': '_entropy_formula',
+               '_median': '_median_formula'}
+
+    # These are not desirable overrides for the new infrastructure
+    skip_override = {'norminvgauss': {'_sf', '_isf'}}
+
+    for old_method, new_method in methods.items():
+        if dist.name in skip_override and old_method in skip_override[dist.name]:
+            continue
+        # If method of old distribution overrides generic implementation...
+        method = getattr(dist.__class__, old_method, None)
+        super_method = getattr(stats.rv_continuous, old_method, None)
+        if method is not super_method:
+            # Make it an attribute of the new object with the new name
+            setattr(CustomDistribution, new_method, getattr(dist, old_method))
+
+    def _overrides(method_name):
+        return (getattr(dist.__class__, method_name, None)
+                is not getattr(stats.rv_continuous, method_name, None))
+
+    if _overrides('_get_support'):
+        domain = CustomDistribution._variable.domain
+        domain.get_numerical_endpoints = get_numerical_endpoints
+
+    if _overrides('_munp'):
+        CustomDistribution._moment_raw_formula = _moment_raw_formula
+
+    if _overrides('_rvs'):
+        CustomDistribution._sample_formula = _sample_formula
+
+    if _overrides('_stats'):
+        CustomDistribution._moment_standardized_formula = _moment_standard_formula
+        if not _overrides('_munp'):
+            CustomDistribution._moment_raw_formula = _moment_raw_formula_1
+            CustomDistribution._moment_central_formula = _moment_central_formula
+
+    support_etc = _combine_docs(CustomDistribution, include_examples=False).lstrip()
+    docs = [
+        f"This class represents `scipy.stats.{dist.name}` as a subclass of "
+        "`ContinuousDistribution`.",
+        f"The `repr`/`str` of class instances is `{repr_str}`.",
+        f"The PDF of the distribution is defined {support_etc}"
+    ]
+    CustomDistribution.__doc__ = ("\n".join(docs))
+
+    return CustomDistribution
+
+
+# Rough sketch of how we might shift/scale distributions. The purpose of
+# making it a separate class is for
+# a) simplicity of the ContinuousDistribution class and
+# b) avoiding the requirement that every distribution accept loc/scale.
+# The simplicity of ContinuousDistribution is important, because there are
+# several other distribution transformations to be supported; e.g., truncation,
+# wrapping, folding, and doubling. We wouldn't want to cram all of this
+# into the `ContinuousDistribution` class. Also, the order of the composition
+# matters (e.g. truncate then shift/scale or vice versa). It's easier to
+# accommodate different orders if the transformation is built up from
+# components rather than all built into `ContinuousDistribution`.
+
+def _shift_scale_distribution_function_2arg(func):
+    def wrapped(self, x, y, *args, loc, scale, sign, **kwargs):
+        item = func.__name__
+
+        f = getattr(self._dist, item)
+
+        # Obviously it's possible to get away with half of the work here.
+        # Let's focus on correct results first and optimize later.
+        xt = self._transform(x, loc, scale)
+        yt = self._transform(y, loc, scale)
+        fxy = f(xt, yt, *args, **kwargs)
+        fyx = f(yt, xt, *args, **kwargs)
+        return np.real_if_close(np.where(sign, fxy, fyx))[()]
+
+    return wrapped
+
+def _shift_scale_distribution_function(func):
+    # c is for complementary
+    citem = {'_logcdf_dispatch': '_logccdf_dispatch',
+             '_cdf_dispatch': '_ccdf_dispatch',
+             '_logccdf_dispatch': '_logcdf_dispatch',
+             '_ccdf_dispatch': '_cdf_dispatch'}
+    def wrapped(self, x, *args, loc, scale, sign, **kwargs):
+        item = func.__name__
+
+        f = getattr(self._dist, item)
+        cf = getattr(self._dist, citem[item])
+
+        # Obviously it's possible to get away with half of the work here.
+        # Let's focus on correct results first and optimize later.
+        xt = self._transform(x, loc, scale)
+        fx = f(xt, *args, **kwargs)
+        cfx = cf(xt, *args, **kwargs)
+        return np.where(sign, fx, cfx)[()]
+
+    return wrapped
+
+def _shift_scale_inverse_function(func):
+    citem = {'_ilogcdf_dispatch': '_ilogccdf_dispatch',
+             '_icdf_dispatch': '_iccdf_dispatch',
+             '_ilogccdf_dispatch': '_ilogcdf_dispatch',
+             '_iccdf_dispatch': '_icdf_dispatch'}
+    def wrapped(self, p, *args, loc, scale, sign, **kwargs):
+        item = func.__name__
+
+        f = getattr(self._dist, item)
+        cf = getattr(self._dist, citem[item])
+
+        # Obviously it's possible to get away with half of the work here.
+        # Let's focus on correct results first and optimize later.
+        fx =  self._itransform(f(p, *args, **kwargs), loc, scale)
+        cfx = self._itransform(cf(p, *args, **kwargs), loc, scale)
+        return np.where(sign, fx, cfx)[()]
+
+    return wrapped
+
+
+class TransformedDistribution(ContinuousDistribution):
+    def __init__(self, X, /, *args, **kwargs):
+        self._copy_parameterization()
+        self._variable = X._variable
+        self._dist = X
+        if X._parameterization:
+            # Add standard distribution parameters to our parameterization
+            dist_parameters = X._parameterization.parameters
+            set_params = set(dist_parameters)
+            if not self._parameterizations:
+                self._parameterizations.append(_Parameterization())
+            for parameterization in self._parameterizations:
+                if set_params.intersection(parameterization.parameters):
+                    message = (f"One or more of the parameters of {X} has "
+                               "the same name as a parameter of "
+                               f"{self.__class__.__name__}. Name collisions "
+                               "create ambiguities and are not supported.")
+                    raise ValueError(message)
+                parameterization.parameters.update(dist_parameters)
+        super().__init__(*args, **kwargs)
+
+    def _overrides(self, method_name):
+        return (self._dist._overrides(method_name)
+                or super()._overrides(method_name))
+
+    def reset_cache(self):
+        self._dist.reset_cache()
+        super().reset_cache()
+
+    def _update_parameters(self, *, validation_policy=None, **params):
+        # maybe broadcast everything before processing?
+        parameters = {}
+        # There may be some issues with _original_parameters
+        # We only want to update with _dist._original_parameters during
+        # initialization. Afterward that, we want to start with
+        # self._original_parameters.
+        parameters.update(self._dist._original_parameters)
+        parameters.update(params)
+        super()._update_parameters(validation_policy=validation_policy, **parameters)
+
+    def _process_parameters(self, **params):
+        return self._dist._process_parameters(**params)
+
+    def __repr__(self):
+        raise NotImplementedError()
+
+    def __str__(self):
+        raise NotImplementedError()
+
+
+class TruncatedDistribution(TransformedDistribution):
+    """Truncated distribution."""
+    # TODO:
+    # - consider avoiding catastropic cancellation by using appropriate tail
+    # - if the mode of `_dist` is within the support, it's still the mode
+    # - rejection sampling might be more efficient than inverse transform
+
+    _lb_domain = _RealDomain(endpoints=(-inf, 'ub'), inclusive=(True, False))
+    _lb_param = _RealParameter('lb', symbol=r'b_l',
+                                domain=_lb_domain, typical=(0.1, 0.2))
+
+    _ub_domain = _RealDomain(endpoints=('lb', inf), inclusive=(False, True))
+    _ub_param = _RealParameter('ub', symbol=r'b_u',
+                                  domain=_ub_domain, typical=(0.8, 0.9))
+
+    _parameterizations = [_Parameterization(_lb_param, _ub_param),
+                          _Parameterization(_lb_param),
+                          _Parameterization(_ub_param)]
+
+    def __init__(self, X, /, *args, lb=-np.inf, ub=np.inf, **kwargs):
+        return super().__init__(X, *args, lb=lb, ub=ub, **kwargs)
+
+    def _process_parameters(self, lb=None, ub=None, **params):
+        lb = lb if lb is not None else np.full_like(lb, -np.inf)[()]
+        ub = ub if ub is not None else np.full_like(ub, np.inf)[()]
+        parameters = self._dist._process_parameters(**params)
+        a, b = self._support(lb=lb, ub=ub, **parameters)
+        logmass = self._dist._logcdf2_dispatch(a, b, **parameters)
+        parameters.update(dict(lb=lb, ub=ub, _a=a, _b=b, logmass=logmass))
+        return parameters
+
+    def _support(self, lb, ub, **params):
+        a, b = self._dist._support(**params)
+        return np.maximum(a, lb), np.minimum(b, ub)
+
+    def _overrides(self, method_name):
+        return False
+
+    def _logpdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params):
+        logpdf = self._dist._logpdf_dispatch(x, *args, **params)
+        return logpdf - logmass
+
+    def _logcdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params):
+        logcdf = self._dist._logcdf2_dispatch(_a, x, *args, **params)
+        # of course, if this result is small we could compute with the other tail
+        return logcdf - logmass
+
+    def _logccdf_dispatch(self, x, *args, lb, ub, _a, _b, logmass, **params):
+        logccdf = self._dist._logcdf2_dispatch(x, _b, *args, **params)
+        return logccdf - logmass
+
+    def _logcdf2_dispatch(self, x, y, *args, lb, ub, _a, _b, logmass, **params):
+        logcdf2 = self._dist._logcdf2_dispatch(x, y, *args, **params)
+        return logcdf2 - logmass
+
+    def _ilogcdf_dispatch(self, logp, *args, lb, ub, _a, _b, logmass, **params):
+        log_Fa = self._dist._logcdf_dispatch(_a, *args, **params)
+        logp_adjusted = np.logaddexp(log_Fa, logp + logmass)
+        return self._dist._ilogcdf_dispatch(logp_adjusted, *args, **params)
+
+    def _ilogccdf_dispatch(self, logp, *args, lb, ub, _a, _b, logmass, **params):
+        log_cFb = self._dist._logccdf_dispatch(_b, *args, **params)
+        logp_adjusted = np.logaddexp(log_cFb, logp + logmass)
+        return self._dist._ilogccdf_dispatch(logp_adjusted, *args, **params)
+
+    def _icdf_dispatch(self, p, *args, lb, ub, _a, _b, logmass, **params):
+        Fa = self._dist._cdf_dispatch(_a, *args, **params)
+        p_adjusted = Fa + p*np.exp(logmass)
+        return self._dist._icdf_dispatch(p_adjusted, *args, **params)
+
+    def _iccdf_dispatch(self, p, *args, lb, ub, _a, _b, logmass, **params):
+        cFb = self._dist._ccdf_dispatch(_b, *args, **params)
+        p_adjusted = cFb + p*np.exp(logmass)
+        return self._dist._iccdf_dispatch(p_adjusted, *args, **params)
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            return (f"truncate({repr(self._dist)}, "
+                    f"lb={repr(self.lb)}, ub={repr(self.ub)})")
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            return (f"truncate({str(self._dist)}, "
+                    f"lb={str(self.lb)}, ub={str(self.ub)})")
+
+
+def truncate(X, lb=-np.inf, ub=np.inf):
+    """Truncate the support of a random variable.
+
+    Given a random variable `X`, `truncate` returns a random variable with
+    support truncated to the interval between `lb` and `ub`. The underlying
+    probability density function is normalized accordingly.
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable to be truncated.
+    lb, ub : float array-like
+        The lower and upper truncation points, respectively. Must be
+        broadcastable with one another and the shape of `X`.
+
+    Returns
+    -------
+    X : `ContinuousDistribution`
+        The truncated random variable.
+
+    References
+    ----------
+    .. [1] "Truncated Distribution". *Wikipedia*.
+           https://en.wikipedia.org/wiki/Truncated_distribution
+
+    Examples
+    --------
+    Compare against `scipy.stats.truncnorm`, which truncates a standard normal,
+    *then* shifts and scales it.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> loc, scale, lb, ub = 1, 2, -2, 2
+    >>> X = stats.truncnorm(lb, ub, loc, scale)
+    >>> Y = scale * stats.truncate(stats.Normal(), lb, ub) + loc
+    >>> x = np.linspace(-3, 5, 300)
+    >>> plt.plot(x, X.pdf(x), '-', label='X')
+    >>> plt.plot(x, Y.pdf(x), '--', label='Y')
+    >>> plt.xlabel('x')
+    >>> plt.ylabel('PDF')
+    >>> plt.title('Truncated, then Shifted/Scaled Normal')
+    >>> plt.legend()
+    >>> plt.show()
+
+    However, suppose we wish to shift and scale a normal random variable,
+    then truncate its support to given values. This is straightforward with
+    `truncate`.
+
+    >>> Z = stats.truncate(scale * stats.Normal() + loc, lb, ub)
+    >>> Z.plot()
+    >>> plt.show()
+
+    Furthermore, `truncate` can be applied to any random variable:
+
+    >>> Rayleigh = stats.make_distribution(stats.rayleigh)
+    >>> W = stats.truncate(Rayleigh(), lb=0, ub=3)
+    >>> W.plot()
+    >>> plt.show()
+
+    """
+    return TruncatedDistribution(X, lb=lb, ub=ub)
+
+
+class ShiftedScaledDistribution(TransformedDistribution):
+    """Distribution with a standard shift/scale transformation."""
+    # Unclear whether infinite loc/scale will work reasonably in all cases
+    _loc_domain = _RealDomain(endpoints=(-inf, inf), inclusive=(True, True))
+    _loc_param = _RealParameter('loc', symbol=r'\mu',
+                                domain=_loc_domain, typical=(1, 2))
+
+    _scale_domain = _RealDomain(endpoints=(-inf, inf), inclusive=(True, True))
+    _scale_param = _RealParameter('scale', symbol=r'\sigma',
+                                  domain=_scale_domain, typical=(0.1, 10))
+
+    _parameterizations = [_Parameterization(_loc_param, _scale_param),
+                          _Parameterization(_loc_param),
+                          _Parameterization(_scale_param)]
+
+    def _process_parameters(self, loc=None, scale=None, **params):
+        loc = loc if loc is not None else np.zeros_like(scale)[()]
+        scale = scale if scale is not None else np.ones_like(loc)[()]
+        sign = scale > 0
+        parameters = self._dist._process_parameters(**params)
+        parameters.update(dict(loc=loc, scale=scale, sign=sign))
+        return parameters
+
+    def _transform(self, x, loc, scale, **kwargs):
+        return (x - loc)/scale
+
+    def _itransform(self, x, loc, scale, **kwargs):
+        return x * scale + loc
+
+    def _support(self, loc, scale, sign, **params):
+        # Add shortcut for infinite support?
+        a, b = self._dist._support(**params)
+        a, b = self._itransform(a, loc, scale), self._itransform(b, loc, scale)
+        return np.where(sign, a, b)[()], np.where(sign, b, a)[()]
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            result =  f"{repr(self.scale)}*{repr(self._dist)}"
+            if not self.loc.ndim and self.loc < 0:
+                result += f" - {repr(-self.loc)}"
+            elif (np.any(self.loc != 0)
+                  or not np.can_cast(self.loc.dtype, self.scale.dtype)):
+                # We don't want to hide a zero array loc if it can cause
+                # a type promotion.
+                result += f" + {repr(self.loc)}"
+        return result
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            result =  f"{str(self.scale)}*{str(self._dist)}"
+            if not self.loc.ndim and self.loc < 0:
+                result += f" - {str(-self.loc)}"
+            elif (np.any(self.loc != 0)
+                  or not np.can_cast(self.loc.dtype, self.scale.dtype)):
+                # We don't want to hide a zero array loc if it can cause
+                # a type promotion.
+                result += f" + {str(self.loc)}"
+        return result
+
+    # Here, we override all the `_dispatch` methods rather than the public
+    # methods or _function methods. Why not the public methods?
+    # If we were to override the public methods, then other
+    # TransformedDistribution classes (which could transform a
+    # ShiftedScaledDistribution) would need to call the public methods of
+    # ShiftedScaledDistribution, which would run the input validation again.
+    # Why not the _function methods? For distributions that rely on the
+    # default implementation of methods (e.g. `quadrature`, `inversion`),
+    # the implementation would "see" the location and scale like other
+    # distribution parameters, so they could affect the accuracy of the
+    # calculations. I think it is cleaner if `loc` and `scale` do not affect
+    # the underlying calculations at all.
+
+    def _entropy_dispatch(self, *args, loc, scale, sign, **params):
+        return (self._dist._entropy_dispatch(*args, **params)
+                + np.log(np.abs(scale)))
+
+    def _logentropy_dispatch(self, *args, loc, scale, sign, **params):
+        lH0 = self._dist._logentropy_dispatch(*args, **params)
+        lls = np.log(np.log(np.abs(scale))+0j)
+        return special.logsumexp(np.broadcast_arrays(lH0, lls), axis=0)
+
+    def _median_dispatch(self, *, method, loc, scale, sign, **params):
+        raw = self._dist._median_dispatch(method=method, **params)
+        return self._itransform(raw, loc, scale)
+
+    def _mode_dispatch(self, *, method, loc, scale, sign, **params):
+        raw = self._dist._mode_dispatch(method=method, **params)
+        return self._itransform(raw, loc, scale)
+
+    def _logpdf_dispatch(self, x, *args, loc, scale, sign, **params):
+        x = self._transform(x, loc, scale)
+        logpdf = self._dist._logpdf_dispatch(x, *args, **params)
+        return logpdf - np.log(np.abs(scale))
+
+    def _pdf_dispatch(self, x, *args, loc, scale, sign, **params):
+        x = self._transform(x, loc, scale)
+        pdf = self._dist._pdf_dispatch(x, *args, **params)
+        return pdf / np.abs(scale)
+
+    # Sorry about the magic. This is just a draft to show the behavior.
+    @_shift_scale_distribution_function
+    def _logcdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function
+    def _cdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function
+    def _logccdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function
+    def _ccdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function_2arg
+    def _logcdf2_dispatch(self, x, y, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function_2arg
+    def _cdf2_dispatch(self, x, y, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function_2arg
+    def _logccdf2_dispatch(self, x, y, *, method=None, **params):
+        pass
+
+    @_shift_scale_distribution_function_2arg
+    def _ccdf2_dispatch(self, x, y, *, method=None, **params):
+        pass
+
+    @_shift_scale_inverse_function
+    def _ilogcdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_inverse_function
+    def _icdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_inverse_function
+    def _ilogccdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    @_shift_scale_inverse_function
+    def _iccdf_dispatch(self, x, *, method=None, **params):
+        pass
+
+    def _moment_standardized_dispatch(self, order, *, loc, scale, sign, methods,
+                                      **params):
+        res = (self._dist._moment_standardized_dispatch(
+            order, methods=methods, **params))
+        return None if res is None else res * np.sign(scale)**order
+
+    def _moment_central_dispatch(self, order, *, loc, scale, sign, methods,
+                                 **params):
+        res = (self._dist._moment_central_dispatch(
+            order, methods=methods, **params))
+        return None if res is None else res * scale**order
+
+    def _moment_raw_dispatch(self, order, *, loc, scale, sign, methods,
+                             **params):
+        raw_moments = []
+        methods_highest_order = methods
+        for i in range(int(order) + 1):
+            methods = (self._moment_methods if i < order
+                       else methods_highest_order)
+            raw = self._dist._moment_raw_dispatch(i, methods=methods, **params)
+            if raw is None:
+                return None
+            moment_i = raw * scale**i
+            raw_moments.append(moment_i)
+
+        return self._moment_transform_center(
+            order, raw_moments, loc, self._zero)
+
+    def _sample_dispatch(self, sample_shape, full_shape, *,
+                         rng, loc, scale, sign, method, **params):
+        rvs = self._dist._sample_dispatch(
+            sample_shape, full_shape, method=method, rng=rng, **params)
+        return self._itransform(rvs, loc=loc, scale=scale, sign=sign, **params)
+
+    def __add__(self, loc):
+        return ShiftedScaledDistribution(self._dist, loc=self.loc + loc,
+                                         scale=self.scale)
+
+    def __sub__(self, loc):
+        return ShiftedScaledDistribution(self._dist, loc=self.loc - loc,
+                                         scale=self.scale)
+
+    def __mul__(self, scale):
+        return ShiftedScaledDistribution(self._dist,
+                                         loc=self.loc * scale,
+                                         scale=self.scale * scale)
+
+    def __truediv__(self, scale):
+        return ShiftedScaledDistribution(self._dist,
+                                         loc=self.loc / scale,
+                                         scale=self.scale / scale)
+
+
+class OrderStatisticDistribution(TransformedDistribution):
+    r"""Probability distribution of an order statistic
+
+    An instance of this class represents a random variable that follows the
+    distribution underlying the :math:`r^{\text{th}}` order statistic of a
+    sample of :math:`n` observations of a random variable :math:`X`.
+
+    Parameters
+    ----------
+    dist : `ContinuousDistribution`
+        The random variable :math:`X`
+    n : array_like
+        The (integer) sample size :math:`n`
+    r : array_like
+        The (integer) rank of the order statistic :math:`r`
+
+
+    Notes
+    -----
+    If we make :math:`n` observations of a continuous random variable
+    :math:`X` and sort them in increasing order
+    :math:`X_{(1)}, \dots, X_{(r)}, \dots, X_{(n)}`,
+    :math:`X_{(r)}` is known as the :math:`r^{\text{th}}` order statistic.
+
+    If the PDF, CDF, and CCDF underlying math:`X` are denoted :math:`f`,
+    :math:`F`, and :math:`F'`, respectively, then the PDF underlying
+    math:`X_{(r)}` is given by:
+
+    .. math::
+
+        f_r(x) = \frac{n!}{(r-1)! (n-r)!} f(x) F(x)^{r-1} F'(x)^{n - r}
+
+    The CDF and other methods of the distribution underlying :math:`X_{(r)}`
+    are calculated using the fact that :math:`X = F^{-1}(U)`, where :math:`U` is
+    a standard uniform random variable, and that the order statistics of
+    observations of `U` follow a beta distribution, :math:`B(r, n - r + 1)`.
+
+    References
+    ----------
+    .. [1] Order statistic. *Wikipedia*. https://en.wikipedia.org/wiki/Order_statistic
+
+    Examples
+    --------
+    Suppose we are interested in order statistics of samples of size five drawn
+    from the standard normal distribution. Plot the PDF underlying the fourth
+    order statistic and compare with a normalized histogram from simulation.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> from scipy.stats._distribution_infrastructure import OrderStatisticDistribution
+    >>>
+    >>> X = stats.Normal()
+    >>> data = X.sample(shape=(10000, 5))
+    >>> ranks = np.sort(data, axis=1)
+    >>> Y = OrderStatisticDistribution(X, r=4, n=5)
+    >>>
+    >>> ax = plt.gca()
+    >>> Y.plot(ax=ax)
+    >>> ax.hist(ranks[:, 3], density=True, bins=30)
+    >>> plt.show()
+
+    """
+
+    # These can be restricted to _IntegerDomain/_IntegerParameter in a separate
+    # PR if desired.
+    _r_domain = _RealDomain(endpoints=(1, 'n'), inclusive=(True, True))
+    _r_param = _RealParameter('r', domain=_r_domain, typical=(1, 2))
+
+    _n_domain = _RealDomain(endpoints=(1, np.inf), inclusive=(True, True))
+    _n_param = _RealParameter('n', domain=_n_domain, typical=(1, 4))
+
+    _r_domain.define_parameters(_n_param)
+
+    _parameterizations = [_Parameterization(_r_param, _n_param)]
+
+    def __init__(self, dist, /, *args, r, n, **kwargs):
+        super().__init__(dist, *args, r=r, n=n, **kwargs)
+
+    def _support(self, *args, r, n, **kwargs):
+        return self._dist._support(*args, **kwargs)
+
+    def _process_parameters(self, r=None, n=None, **params):
+        parameters = self._dist._process_parameters(**params)
+        parameters.update(dict(r=r, n=n))
+        return parameters
+
+    def _overrides(self, method_name):
+        return method_name in {'_logpdf_formula', '_pdf_formula',
+                               '_cdf_formula', '_ccdf_formula',
+                               '_icdf_formula', '_iccdf_formula'}
+
+    def _logpdf_formula(self, x, r, n, **kwargs):
+        log_factor = special.betaln(r, n - r + 1)
+        log_fX = self._dist._logpdf_dispatch(x, **kwargs)
+        # log-methods sometimes use complex dtype with 0 imaginary component,
+        # but `_tanhsinh` doesn't accept complex limits of integration; take `real`.
+        log_FX = self._dist._logcdf_dispatch(x.real, **kwargs)
+        log_cFX = self._dist._logccdf_dispatch(x.real, **kwargs)
+        # This can be problematic when (r - 1)|(n-r) = 0 and `log_FX`|log_cFX = -inf
+        # The PDF in these cases is 0^0, so these should be replaced with log(1)=0
+        # return log_fX + (r-1)*log_FX + (n-r)*log_cFX - log_factor
+        rm1_log_FX = np.where((r - 1 == 0) & np.isneginf(log_FX), 0, (r-1)*log_FX)
+        nmr_log_cFX = np.where((n - r == 0) & np.isneginf(log_cFX), 0, (n-r)*log_cFX)
+        return log_fX + rm1_log_FX + nmr_log_cFX - log_factor
+
+    def _pdf_formula(self, x, r, n, **kwargs):
+        # 1 / factor = factorial(n) / (factorial(r-1) * factorial(n-r))
+        factor = special.beta(r, n - r + 1)
+        fX = self._dist._pdf_dispatch(x, **kwargs)
+        FX = self._dist._cdf_dispatch(x, **kwargs)
+        cFX = self._dist._ccdf_dispatch(x, **kwargs)
+        return fX * FX**(r-1) * cFX**(n-r) / factor
+
+    def _cdf_formula(self, x, r, n, **kwargs):
+        x_ = self._dist._cdf_dispatch(x, **kwargs)
+        return special.betainc(r, n-r+1, x_)
+
+    def _ccdf_formula(self, x, r, n, **kwargs):
+        x_ = self._dist._cdf_dispatch(x, **kwargs)
+        return special.betaincc(r, n-r+1, x_)
+
+    def _icdf_formula(self, p, r, n, **kwargs):
+        p_ = special.betaincinv(r, n-r+1, p)
+        return self._dist._icdf_dispatch(p_, **kwargs)
+
+    def _iccdf_formula(self, p, r, n, **kwargs):
+        p_ = special.betainccinv(r, n-r+1, p)
+        return self._dist._icdf_dispatch(p_, **kwargs)
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            return (f"order_statistic({repr(self._dist)}, r={repr(self.r)}, "
+                    f"n={repr(self.n)})")
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            return (f"order_statistic({str(self._dist)}, r={str(self.r)}, "
+                    f"n={str(self.n)})")
+
+
+def order_statistic(X, /, *, r, n):
+    r"""Probability distribution of an order statistic
+
+    Returns a random variable that follows the distribution underlying the
+    :math:`r^{\text{th}}` order statistic of a sample of :math:`n`
+    observations of a random variable :math:`X`.
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`
+    r : array_like
+        The (positive integer) rank of the order statistic :math:`r`
+    n : array_like
+        The (positive integer) sample size :math:`n`
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        A random variable that follows the distribution of the prescribed
+        order statistic.
+
+    Notes
+    -----
+    If we make :math:`n` observations of a continuous random variable
+    :math:`X` and sort them in increasing order
+    :math:`X_{(1)}, \dots, X_{(r)}, \dots, X_{(n)}`,
+    :math:`X_{(r)}` is known as the :math:`r^{\text{th}}` order statistic.
+
+    If the PDF, CDF, and CCDF underlying math:`X` are denoted :math:`f`,
+    :math:`F`, and :math:`F'`, respectively, then the PDF underlying
+    math:`X_{(r)}` is given by:
+
+    .. math::
+
+        f_r(x) = \frac{n!}{(r-1)! (n-r)!} f(x) F(x)^{r-1} F'(x)^{n - r}
+
+    The CDF and other methods of the distribution underlying :math:`X_{(r)}`
+    are calculated using the fact that :math:`X = F^{-1}(U)`, where :math:`U` is
+    a standard uniform random variable, and that the order statistics of
+    observations of `U` follow a beta distribution, :math:`B(r, n - r + 1)`.
+
+    References
+    ----------
+    .. [1] Order statistic. *Wikipedia*. https://en.wikipedia.org/wiki/Order_statistic
+
+    Examples
+    --------
+    Suppose we are interested in order statistics of samples of size five drawn
+    from the standard normal distribution. Plot the PDF underlying each
+    order statistic and compare with a normalized histogram from simulation.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>>
+    >>> X = stats.Normal()
+    >>> data = X.sample(shape=(10000, 5))
+    >>> sorted = np.sort(data, axis=1)
+    >>> Y = stats.order_statistic(X, r=[1, 2, 3, 4, 5], n=5)
+    >>>
+    >>> ax = plt.gca()
+    >>> colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
+    >>> for i in range(5):
+    ...     y = sorted[:, i]
+    ...     ax.hist(y, density=True, bins=30, alpha=0.1, color=colors[i])
+    >>> Y.plot(ax=ax)
+    >>> plt.show()
+
+    """
+    r, n = np.asarray(r), np.asarray(n)
+    if np.any((r != np.floor(r)) | (r < 0)) or np.any((n != np.floor(n)) | (n < 0)):
+        message = "`r` and `n` must contain only positive integers."
+        raise ValueError(message)
+    return OrderStatisticDistribution(X, r=r, n=n)
+
+
+class Mixture(_ProbabilityDistribution):
+    r"""Representation of a mixture distribution.
+
+    A mixture distribution is the distribution of a random variable
+    defined in the following way: first, a random variable is selected
+    from `components` according to the probabilities given by `weights`, then
+    the selected random variable is realized.
+
+    Parameters
+    ----------
+    components : sequence of `ContinuousDistribution`
+        The underlying instances of `ContinuousDistribution`.
+        All must have scalar shape parameters (if any); e.g., the `pdf` evaluated
+        at a scalar argument must return a scalar.
+    weights : sequence of floats, optional
+        The corresponding probabilities of selecting each random variable.
+        Must be non-negative and sum to one. The default behavior is to weight
+        all components equally.
+
+    Attributes
+    ----------
+    components : sequence of `ContinuousDistribution`
+        The underlying instances of `ContinuousDistribution`.
+    weights : ndarray
+        The corresponding probabilities of selecting each random variable.
+
+    Methods
+    -------
+    support
+
+    sample
+
+    moment
+
+    mean
+    median
+    mode
+
+    variance
+    standard_deviation
+
+    skewness
+    kurtosis
+
+    pdf
+    logpdf
+
+    cdf
+    icdf
+    ccdf
+    iccdf
+
+    logcdf
+    ilogcdf
+    logccdf
+    ilogccdf
+
+    entropy
+
+    Notes
+    -----
+    The following abbreviations are used throughout the documentation.
+
+    - PDF: probability density function
+    - CDF: cumulative distribution function
+    - CCDF: complementary CDF
+    - entropy: differential entropy
+    - log-*F*: logarithm of *F* (e.g. log-CDF)
+    - inverse *F*: inverse function of *F* (e.g. inverse CDF)
+
+    References
+    ----------
+    .. [1] Mixture distribution, *Wikipedia*,
+           https://en.wikipedia.org/wiki/Mixture_distribution
+
+    """
+    # Todo:
+    # Add support for array shapes, weights
+
+    def _input_validation(self, components, weights):
+        if len(components) == 0:
+            message = ("`components` must contain at least one random variable.")
+            raise ValueError(message)
+
+        for var in components:
+            # will generalize to other kinds of distributions when there
+            # *are* other kinds of distributions
+            if not isinstance(var, ContinuousDistribution):
+                message = ("Each element of `components` must be an instance of "
+                           "`ContinuousDistribution`.")
+                raise ValueError(message)
+            if not var._shape == ():
+                message = "All elements of `components` must have scalar shapes."
+                raise ValueError(message)
+
+        if weights is None:
+            return components, weights
+
+        weights = np.asarray(weights)
+        if weights.shape != (len(components),):
+            message = "`components` and `weights` must have the same length."
+            raise ValueError(message)
+
+        if not np.issubdtype(weights.dtype, np.inexact):
+            message = "`weights` must have floating point dtype."
+            raise ValueError(message)
+
+        if not np.isclose(np.sum(weights), 1.0):
+            message = "`weights` must sum to 1.0."
+            raise ValueError(message)
+
+        if not np.all(weights >= 0):
+            message = "All `weights` must be non-negative."
+            raise ValueError(message)
+
+        return components, weights
+
+    def __init__(self, components, *, weights=None):
+        components, weights = self._input_validation(components, weights)
+        n = len(components)
+        dtype = np.result_type(*(var._dtype for var in components))
+        self._shape = np.broadcast_shapes(*(var._shape for var in components))
+        self._dtype, self._components = dtype, components
+        self._weights = np.full(n, 1/n, dtype=dtype) if weights is None else weights
+        self.validation_policy = None
+
+    @property
+    def components(self):
+        return list(self._components)
+
+    @property
+    def weights(self):
+        return self._weights.copy()
+
+    def _full(self, val, *args):
+        args = [np.asarray(arg) for arg in args]
+        dtype = np.result_type(self._dtype, *(arg.dtype for arg in args))
+        shape = np.broadcast_shapes(self._shape, *(arg.shape for arg in args))
+        return np.full(shape, val, dtype=dtype)
+
+    def _sum(self, fun, *args):
+        out = self._full(0, *args)
+        for var, weight in zip(self._components, self._weights):
+            out += getattr(var, fun)(*args) * weight
+        return out[()]
+
+    def _logsum(self, fun, *args):
+        out = self._full(-np.inf, *args)
+        for var, log_weight in zip(self._components, np.log(self._weights)):
+            np.logaddexp(out, getattr(var, fun)(*args) + log_weight, out=out)
+        return out[()]
+
+    def support(self):
+        a = self._full(np.inf)
+        b = self._full(-np.inf)
+        for var in self._components:
+            a = np.minimum(a, var.support()[0])
+            b = np.maximum(b, var.support()[1])
+        return a, b
+
+    def _raise_if_method(self, method):
+        if method is not None:
+            raise NotImplementedError("`method` not implemented for this distribution.")
+
+    def logentropy(self, *, method=None):
+        self._raise_if_method(method)
+        def log_integrand(x):
+            # `x` passed by `_tanhsinh` will be of complex dtype because
+            # `log_integrand` returns complex values, but the imaginary
+            # component is always zero. Extract the real part because
+            # `logpdf` uses `logaddexp`, which fails for complex input.
+            return self.logpdf(x.real) + np.log(self.logpdf(x.real) + 0j)
+
+        res = _tanhsinh(log_integrand, *self.support(), log=True).integral
+        return _log_real_standardize(res + np.pi*1j)
+
+    def entropy(self, *, method=None):
+        self._raise_if_method(method)
+        return _tanhsinh(lambda x: -self.pdf(x) * self.logpdf(x),
+                         *self.support()).integral
+
+    def mode(self, *, method=None):
+        self._raise_if_method(method)
+        a, b = self.support()
+        def f(x): return -self.pdf(x)
+        res = _bracket_minimum(f, 1., xmin=a, xmax=b)
+        res = _chandrupatla_minimize(f, res.xl, res.xm, res.xr)
+        return res.x
+
+    def median(self, *, method=None):
+        self._raise_if_method(method)
+        return self.icdf(0.5)
+
+    def mean(self, *, method=None):
+        self._raise_if_method(method)
+        return self._sum('mean')
+
+    def variance(self, *, method=None):
+        self._raise_if_method(method)
+        return self._moment_central(2)
+
+    def standard_deviation(self, *, method=None):
+        self._raise_if_method(method)
+        return self.variance()**0.5
+
+    def skewness(self, *, method=None):
+        self._raise_if_method(method)
+        return self._moment_standardized(3)
+
+    def kurtosis(self, *, method=None):
+        self._raise_if_method(method)
+        return self._moment_standardized(4)
+
+    def moment(self, order=1, kind='raw', *, method=None):
+        self._raise_if_method(method)
+        kinds = {'raw': self._moment_raw,
+                 'central': self._moment_central,
+                 'standardized': self._moment_standardized}
+        order = ContinuousDistribution._validate_order_kind(self, order, kind, kinds)
+        moment_kind = kinds[kind]
+        return moment_kind(order)
+
+    def _moment_raw(self, order):
+        out = self._full(0)
+        for var, weight in zip(self._components, self._weights):
+            out += var.moment(order, kind='raw') * weight
+        return out[()]
+
+    def _moment_central(self, order):
+        order = int(order)
+        out = self._full(0)
+        for var, weight in zip(self._components, self._weights):
+            moment_as = [var.moment(order, kind='central')
+                         for order in range(order + 1)]
+            a, b = var.mean(), self.mean()
+            moment = var._moment_transform_center(order, moment_as, a, b)
+            out += moment * weight
+        return out[()]
+
+    def _moment_standardized(self, order):
+        return self._moment_central(order) / self.standard_deviation()**order
+
+    def pdf(self, x, /, *, method=None):
+        self._raise_if_method(method)
+        return self._sum('pdf', x)
+
+    def logpdf(self, x, /, *, method=None):
+        self._raise_if_method(method)
+        return self._logsum('logpdf', x)
+
+    def cdf(self, x, y=None, /, *, method=None):
+        self._raise_if_method(method)
+        args = (x,) if y is None else (x, y)
+        return self._sum('cdf', *args)
+
+    def logcdf(self, x, y=None, /, *, method=None):
+        self._raise_if_method(method)
+        args = (x,) if y is None else (x, y)
+        return self._logsum('logcdf', *args)
+
+    def ccdf(self, x, y=None, /, *, method=None):
+        self._raise_if_method(method)
+        args = (x,) if y is None else (x, y)
+        return self._sum('ccdf', *args)
+
+    def logccdf(self, x, y=None, /, *, method=None):
+        self._raise_if_method(method)
+        args = (x,) if y is None else (x, y)
+        return self._logsum('logccdf', *args)
+
+    def _invert(self, fun, p):
+        xmin, xmax = self.support()
+        fun = getattr(self, fun)
+        f = lambda x, p: fun(x) - p  # noqa: E731 is silly
+        xl0, xr0 = _guess_bracket(xmin, xmax)
+        res = _bracket_root(f, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, args=(p,))
+        return _chandrupatla(f, a=res.xl, b=res.xr, args=(p,)).x
+
+    def icdf(self, p, /, *, method=None):
+        self._raise_if_method(method)
+        return self._invert('cdf', p)
+
+    def iccdf(self, p, /, *, method=None):
+        self._raise_if_method(method)
+        return self._invert('ccdf', p)
+
+    def ilogcdf(self, p, /, *, method=None):
+        self._raise_if_method(method)
+        return self._invert('logcdf', p)
+
+    def ilogccdf(self, p, /, *, method=None):
+        self._raise_if_method(method)
+        return self._invert('logccdf', p)
+
+    def sample(self, shape=(), *, rng=None, method=None):
+        self._raise_if_method(method)
+        rng = np.random.default_rng(rng)
+        size = np.prod(np.atleast_1d(shape))
+        ns = rng.multinomial(size, self._weights)
+        x = [var.sample(shape=n, rng=rng) for n, var in zip(ns, self._components)]
+        x = np.reshape(rng.permuted(np.concatenate(x)), shape)
+        return x[()]
+
+    def __repr__(self):
+        result = "Mixture(\n"
+        result += "    [\n"
+        with np.printoptions(threshold=10):
+            for component in self.components:
+                result += f"        {repr(component)},\n"
+            result += "    ],\n"
+            result += f"    weights={repr(self.weights)},\n"
+        result += ")"
+        return result
+
+    def __str__(self):
+        result = "Mixture(\n"
+        result += "    [\n"
+        with np.printoptions(threshold=10):
+            for component in self.components:
+                result += f"        {str(component)},\n"
+            result += "    ],\n"
+            result += f"    weights={str(self.weights)},\n"
+        result += ")"
+        return result
+
+
+class MonotonicTransformedDistribution(TransformedDistribution):
+    r"""Distribution underlying a strictly monotonic function of a random variable
+
+    Given a random variable :math:`X`; a strictly monotonic function
+    :math:`g(u)`, its inverse :math:`h(u) = g^{-1}(u)`, and the derivative magnitude
+    :math: `|h'(u)| = \left| \frac{dh(u)}{du} \right|`, define the distribution
+    underlying the random variable :math:`Y = g(X)`.
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`.
+    g, h, dh : callable
+        Elementwise functions representing the mathematical functions
+        :math:`g(u)`, :math:`h(u)`, and :math:`|h'(u)|`
+    logdh : callable, optional
+        Elementwise function representing :math:`\log(h'(u))`.
+        The default is ``lambda u: np.log(dh(u))``, but providing
+        a custom implementation may avoid over/underflow.
+    increasing : bool, optional
+        Whether the function is strictly increasing (True, default)
+        or strictly decreasing (False).
+    repr_pattern : str, optional
+        A string pattern for determining the __repr__. The __repr__
+        for X will be substituted into the position where `***` appears.
+        For example:
+            ``"exp(***)"`` for the repr of an exponentially transformed
+            distribution
+        The default is ``f"{g.__name__}(***)"``.
+    str_pattern : str, optional
+        A string pattern for determining `__str__`. The `__str__`
+        for X will be substituted into the position where `***` appears.
+        For example:
+            ``"exp(***)"`` for the repr of an exponentially transformed
+            distribution
+        The default is the value `repr_pattern` takes.
+    """
+
+    def __init__(self, X, /, *args, g, h, dh, logdh=None,
+                 increasing=True, repr_pattern=None,
+                 str_pattern=None, **kwargs):
+        super().__init__(X, *args, **kwargs)
+        self._g = g
+        self._h = h
+        self._dh = dh
+        self._logdh = (logdh if logdh is not None
+                       else lambda u: np.log(dh(u)))
+        if increasing:
+            self._xdf = self._dist._cdf_dispatch
+            self._cxdf = self._dist._ccdf_dispatch
+            self._ixdf = self._dist._icdf_dispatch
+            self._icxdf = self._dist._iccdf_dispatch
+            self._logxdf = self._dist._logcdf_dispatch
+            self._logcxdf = self._dist._logccdf_dispatch
+            self._ilogxdf = self._dist._ilogcdf_dispatch
+            self._ilogcxdf = self._dist._ilogccdf_dispatch
+        else:
+            self._xdf = self._dist._ccdf_dispatch
+            self._cxdf = self._dist._cdf_dispatch
+            self._ixdf = self._dist._iccdf_dispatch
+            self._icxdf = self._dist._icdf_dispatch
+            self._logxdf = self._dist._logccdf_dispatch
+            self._logcxdf = self._dist._logcdf_dispatch
+            self._ilogxdf = self._dist._ilogccdf_dispatch
+            self._ilogcxdf = self._dist._ilogcdf_dispatch
+        self._increasing = increasing
+        self._repr_pattern = repr_pattern or f"{g.__name__}(***)"
+        self._str_pattern = str_pattern or self._repr_pattern
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            return self._repr_pattern.replace("***", repr(self._dist))
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            return self._str_pattern.replace("***", str(self._dist))
+
+    def _overrides(self, method_name):
+        # Do not use the generic overrides of TransformedDistribution
+        return False
+
+    def _support(self, **params):
+        a, b = self._dist._support(**params)
+        # For reciprocal transformation, we want this zero to become -inf
+        b = np.where(b==0, np.asarray("-0", dtype=b.dtype), b)
+        with np.errstate(divide='ignore'):
+            if self._increasing:
+                return self._g(a), self._g(b)
+            else:
+                return self._g(b), self._g(a)
+
+    def _logpdf_dispatch(self, x, *args, **params):
+        return self._dist._logpdf_dispatch(self._h(x), *args, **params) + self._logdh(x)
+
+    def _pdf_dispatch(self, x, *args, **params):
+        return self._dist._pdf_dispatch(self._h(x), *args, **params) * self._dh(x)
+
+    def _logcdf_dispatch(self, x, *args, **params):
+        return self._logxdf(self._h(x), *args, **params)
+
+    def _cdf_dispatch(self, x, *args, **params):
+        return self._xdf(self._h(x), *args, **params)
+
+    def _logccdf_dispatch(self, x, *args, **params):
+        return self._logcxdf(self._h(x), *args, **params)
+
+    def _ccdf_dispatch(self, x, *args, **params):
+        return self._cxdf(self._h(x), *args, **params)
+
+    def _ilogcdf_dispatch(self, p, *args, **params):
+        return self._g(self._ilogxdf(p, *args, **params))
+
+    def _icdf_dispatch(self, p, *args, **params):
+        return self._g(self._ixdf(p, *args, **params))
+
+    def _ilogccdf_dispatch(self, p, *args, **params):
+        return self._g(self._ilogcxdf(p, *args, **params))
+
+    def _iccdf_dispatch(self, p, *args, **params):
+        return self._g(self._icxdf(p, *args, **params))
+
+    def _sample_dispatch(self, sample_shape, full_shape, *,
+                         method, rng, **params):
+        rvs = self._dist._sample_dispatch(
+            sample_shape, full_shape, method=method, rng=rng, **params)
+        return self._g(rvs)
+
+
+class FoldedDistribution(TransformedDistribution):
+    r"""Distribution underlying the absolute value of a random variable
+
+    Given a random variable :math:`X`; define the distribution
+    underlying the random variable :math:`Y = |X|`.
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`.
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        The random variable :math:`Y = |X|`
+
+    """
+    # Many enhancements are possible if distribution is symmetric. Start
+    # with the general case; enhance later.
+
+    def __init__(self, X, /, *args, **kwargs):
+        super().__init__(X, *args, **kwargs)
+        # I think we need to allow `_support` to define whether the endpoints
+        # are inclusive or not. In the meantime, it's best to ensure that the lower
+        # endpoint (typically 0 for folded distribution) is inclusive so PDF evaluates
+        # correctly at that point.
+        self._variable.domain.inclusive = (True, self._variable.domain.inclusive[1])
+
+    def _overrides(self, method_name):
+        # Do not use the generic overrides of TransformedDistribution
+        return False
+
+    def _support(self, **params):
+        a, b = self._dist._support(**params)
+        a_, b_ = np.abs(a), np.abs(b)
+        a_, b_ = np.minimum(a_, b_), np.maximum(a_, b_)
+        i = (a < 0) & (b > 0)
+        a_ = np.asarray(a_)
+        a_[i] = 0
+        return a_[()], b_[()]
+
+    def _logpdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        right = self._dist._logpdf_dispatch(x, *args, method=method, **params)
+        left = self._dist._logpdf_dispatch(-x, *args, method=method, **params)
+        left = np.asarray(left)
+        right = np.asarray(right)
+        a, b = self._dist._support(**params)
+        left[-x < a] = -np.inf
+        right[x > b] = -np.inf
+        logpdfs = np.stack([left, right])
+        return special.logsumexp(logpdfs, axis=0)
+
+    def _pdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        right = self._dist._pdf_dispatch(x, *args, method=method, **params)
+        left = self._dist._pdf_dispatch(-x, *args, method=method, **params)
+        left = np.asarray(left)
+        right = np.asarray(right)
+        a, b = self._dist._support(**params)
+        left[-x < a] = 0
+        right[x > b] = 0
+        return left + right
+
+    def _logcdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        a, b = self._dist._support(**params)
+        xl = np.maximum(-x, a)
+        xr = np.minimum(x, b)
+        return self._dist._logcdf2_dispatch(xl, xr, *args, method=method, **params).real
+
+    def _cdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        a, b = self._dist._support(**params)
+        xl = np.maximum(-x, a)
+        xr = np.minimum(x, b)
+        return self._dist._cdf2_dispatch(xl, xr, *args, **params)
+
+    def _logccdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        a, b = self._dist._support(**params)
+        xl = np.maximum(-x, a)
+        xr = np.minimum(x, b)
+        return self._dist._logccdf2_dispatch(xl, xr, *args, method=method, 
+                                             **params).real
+
+    def _ccdf_dispatch(self, x, *args, method=None, **params):
+        x = np.abs(x)
+        a, b = self._dist._support(**params)
+        xl = np.maximum(-x, a)
+        xr = np.minimum(x, b)
+        return self._dist._ccdf2_dispatch(xl, xr, *args, method=method, **params)
+
+    def _sample_dispatch(self, sample_shape, full_shape, *,
+                         method, rng, **params):
+        rvs = self._dist._sample_dispatch(
+            sample_shape, full_shape, method=method, rng=rng, **params)
+        return np.abs(rvs)
+
+    def __repr__(self):
+        with np.printoptions(threshold=10):
+            return f"abs({repr(self._dist)})"
+
+    def __str__(self):
+        with np.printoptions(threshold=10):
+            return f"abs({str(self._dist)})"
+
+
+def abs(X, /):
+    r"""Absolute value of a random variable
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`.
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        A random variable :math:`Y = |X|`.
+
+    Examples
+    --------
+    Suppose we have a normally distributed random variable :math:`X`:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> X = stats.Normal()
+
+    We wish to have a random variable :math:`Y` distributed according to
+    the folded normal distribution; that is, a random variable :math:`|X|`.
+
+    >>> Y = stats.abs(X)
+
+    The PDF of the distribution in the left half plane is "folded" over to
+    the right half plane. Because the normal PDF is symmetric, the resulting
+    PDF is zero for negative arguments and doubled for positive arguments.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0, 5, 300)
+    >>> ax = plt.gca()
+    >>> Y.plot(x='x', y='pdf', t=('x', -1, 5), ax=ax)
+    >>> plt.plot(x, 2 * X.pdf(x), '--')
+    >>> plt.legend(('PDF of `Y`', 'Doubled PDF of `X`'))
+    >>> plt.show()
+
+    """
+    return FoldedDistribution(X)
+
+
+def exp(X, /):
+    r"""Natural exponential of a random variable
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X`.
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        A random variable :math:`Y = \exp(X)`.
+
+    Examples
+    --------
+    Suppose we have a normally distributed random variable :math:`X`:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> X = stats.Normal()
+
+    We wish to have a lognormally distributed random variable :math:`Y`,
+    a random variable whose natural logarithm is :math:`X`.
+    If :math:`X` is to be the natural logarithm of :math:`Y`, then we
+    must take :math:`Y` to be the natural exponential of :math:`X`.
+
+    >>> Y = stats.exp(X)
+
+    To demonstrate that ``X`` represents the logarithm of ``Y``,
+    we plot a normalized histogram of the logarithm of observations of
+    ``Y`` against the PDF underlying ``X``.
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng(435383595582522)
+    >>> y = Y.sample(shape=10000, rng=rng)
+    >>> ax = plt.gca()
+    >>> ax.hist(np.log(y), bins=50, density=True)
+    >>> X.plot(ax=ax)
+    >>> plt.legend(('PDF of `X`', 'histogram of `log(y)`'))
+    >>> plt.show()
+
+    """
+    return MonotonicTransformedDistribution(X, g=np.exp, h=np.log, dh=lambda u: 1 / u,
+                                            logdh=lambda u: -np.log(u))
+
+
+def log(X, /):
+    r"""Natural logarithm of a non-negative random variable
+
+    Parameters
+    ----------
+    X : `ContinuousDistribution`
+        The random variable :math:`X` with positive support.
+
+    Returns
+    -------
+    Y : `ContinuousDistribution`
+        A random variable :math:`Y = \exp(X)`.
+
+    Examples
+    --------
+    Suppose we have a gamma distributed random variable :math:`X`:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> Gamma = stats.make_distribution(stats.gamma)
+    >>> X = Gamma(a=1.0)
+
+    We wish to have a exp-gamma distributed random variable :math:`Y`,
+    a random variable whose natural exponential is :math:`X`.
+    If :math:`X` is to be the natural exponential of :math:`Y`, then we
+    must take :math:`Y` to be the natural logarithm of :math:`X`.
+
+    >>> Y = stats.log(X)
+
+    To demonstrate that ``X`` represents the exponential of ``Y``,
+    we plot a normalized histogram of the exponential of observations of
+    ``Y`` against the PDF underlying ``X``.
+
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng(435383595582522)
+    >>> y = Y.sample(shape=10000, rng=rng)
+    >>> ax = plt.gca()
+    >>> ax.hist(np.exp(y), bins=50, density=True)
+    >>> X.plot(ax=ax)
+    >>> plt.legend(('PDF of `X`', 'histogram of `exp(y)`'))
+    >>> plt.show()
+
+    """
+    if np.any(X.support()[0] < 0):
+        message = ("The logarithm of a random variable is only implemented when the "
+                   "support is non-negative.")
+        raise NotImplementedError(message)
+    return MonotonicTransformedDistribution(X, g=np.log, h=np.exp, dh=np.exp,
+                                            logdh=lambda u: u)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_entropy.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_entropy.py
new file mode 100644
index 0000000000000000000000000000000000000000..932c64cf93b1b5dcf7ab07884374c16499098ca3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_entropy.py
@@ -0,0 +1,429 @@
+"""
+Created on Fri Apr  2 09:06:05 2021
+
+@author: matth
+"""
+
+import math
+import numpy as np
+from scipy import special
+from ._axis_nan_policy import _axis_nan_policy_factory, _broadcast_arrays
+from scipy._lib._array_api import array_namespace, xp_moveaxis_to_end
+
+__all__ = ['entropy', 'differential_entropy']
+
+
+@_axis_nan_policy_factory(
+    lambda x: x,
+    n_samples=lambda kwgs: (
+        2 if ("qk" in kwgs and kwgs["qk"] is not None)
+        else 1
+    ),
+    n_outputs=1, result_to_tuple=lambda x: (x,), paired=True,
+    too_small=-1  # entropy doesn't have too small inputs
+)
+def entropy(pk: np.typing.ArrayLike,
+            qk: np.typing.ArrayLike | None = None,
+            base: float | None = None,
+            axis: int = 0
+            ) -> np.number | np.ndarray:
+    """
+    Calculate the Shannon entropy/relative entropy of given distribution(s).
+
+    If only probabilities `pk` are given, the Shannon entropy is calculated as
+    ``H = -sum(pk * log(pk))``.
+
+    If `qk` is not None, then compute the relative entropy
+    ``D = sum(pk * log(pk / qk))``. This quantity is also known
+    as the Kullback-Leibler divergence.
+
+    This routine will normalize `pk` and `qk` if they don't sum to 1.
+
+    Parameters
+    ----------
+    pk : array_like
+        Defines the (discrete) distribution. Along each axis-slice of ``pk``,
+        element ``i`` is the  (possibly unnormalized) probability of event
+        ``i``.
+    qk : array_like, optional
+        Sequence against which the relative entropy is computed. Should be in
+        the same format as `pk`.
+    base : float, optional
+        The logarithmic base to use, defaults to ``e`` (natural logarithm).
+    axis : int, optional
+        The axis along which the entropy is calculated. Default is 0.
+
+    Returns
+    -------
+    S : {float, array_like}
+        The calculated entropy.
+
+    Notes
+    -----
+    Informally, the Shannon entropy quantifies the expected uncertainty
+    inherent in the possible outcomes of a discrete random variable.
+    For example,
+    if messages consisting of sequences of symbols from a set are to be
+    encoded and transmitted over a noiseless channel, then the Shannon entropy
+    ``H(pk)`` gives a tight lower bound for the average number of units of
+    information needed per symbol if the symbols occur with frequencies
+    governed by the discrete distribution `pk` [1]_. The choice of base
+    determines the choice of units; e.g., ``e`` for nats, ``2`` for bits, etc.
+
+    The relative entropy, ``D(pk|qk)``, quantifies the increase in the average
+    number of units of information needed per symbol if the encoding is
+    optimized for the probability distribution `qk` instead of the true
+    distribution `pk`. Informally, the relative entropy quantifies the expected
+    excess in surprise experienced if one believes the true distribution is
+    `qk` when it is actually `pk`.
+
+    A related quantity, the cross entropy ``CE(pk, qk)``, satisfies the
+    equation ``CE(pk, qk) = H(pk) + D(pk|qk)`` and can also be calculated with
+    the formula ``CE = -sum(pk * log(qk))``. It gives the average
+    number of units of information needed per symbol if an encoding is
+    optimized for the probability distribution `qk` when the true distribution
+    is `pk`. It is not computed directly by `entropy`, but it can be computed
+    using two calls to the function (see Examples).
+
+    See [2]_ for more information.
+
+    References
+    ----------
+    .. [1] Shannon, C.E. (1948), A Mathematical Theory of Communication.
+           Bell System Technical Journal, 27: 379-423.
+           https://doi.org/10.1002/j.1538-7305.1948.tb01338.x
+    .. [2] Thomas M. Cover and Joy A. Thomas. 2006. Elements of Information
+           Theory (Wiley Series in Telecommunications and Signal Processing).
+           Wiley-Interscience, USA.
+
+
+    Examples
+    --------
+    The outcome of a fair coin is the most uncertain:
+
+    >>> import numpy as np
+    >>> from scipy.stats import entropy
+    >>> base = 2  # work in units of bits
+    >>> pk = np.array([1/2, 1/2])  # fair coin
+    >>> H = entropy(pk, base=base)
+    >>> H
+    1.0
+    >>> H == -np.sum(pk * np.log(pk)) / np.log(base)
+    True
+
+    The outcome of a biased coin is less uncertain:
+
+    >>> qk = np.array([9/10, 1/10])  # biased coin
+    >>> entropy(qk, base=base)
+    0.46899559358928117
+
+    The relative entropy between the fair coin and biased coin is calculated
+    as:
+
+    >>> D = entropy(pk, qk, base=base)
+    >>> D
+    0.7369655941662062
+    >>> np.isclose(D, np.sum(pk * np.log(pk/qk)) / np.log(base), rtol=4e-16, atol=0)
+    True
+
+    The cross entropy can be calculated as the sum of the entropy and
+    relative entropy`:
+
+    >>> CE = entropy(pk, base=base) + entropy(pk, qk, base=base)
+    >>> CE
+    1.736965594166206
+    >>> CE == -np.sum(pk * np.log(qk)) / np.log(base)
+    True
+
+    """
+    if base is not None and base <= 0:
+        raise ValueError("`base` must be a positive number or `None`.")
+
+    xp = array_namespace(pk) if qk is None else array_namespace(pk, qk)
+
+    pk = xp.asarray(pk)
+    with np.errstate(invalid='ignore'):
+        pk = 1.0*pk / xp.sum(pk, axis=axis, keepdims=True)  # type: ignore[operator]
+    if qk is None:
+        vec = special.entr(pk)
+    else:
+        qk = xp.asarray(qk)
+        pk, qk = _broadcast_arrays((pk, qk), axis=None, xp=xp)  # don't ignore any axes
+        sum_kwargs = dict(axis=axis, keepdims=True)
+        qk = 1.0*qk / xp.sum(qk, **sum_kwargs)  # type: ignore[operator, call-overload]
+        vec = special.rel_entr(pk, qk)
+    S = xp.sum(vec, axis=axis)
+    if base is not None:
+        S /= math.log(base)
+    return S
+
+
+def _differential_entropy_is_too_small(samples, kwargs, axis=-1):
+    values = samples[0]
+    n = values.shape[axis]
+    window_length = kwargs.get("window_length",
+                               math.floor(math.sqrt(n) + 0.5))
+    if not 2 <= 2 * window_length < n:
+        return True
+    return False
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,),
+    too_small=_differential_entropy_is_too_small
+)
+def differential_entropy(
+    values: np.typing.ArrayLike,
+    *,
+    window_length: int | None = None,
+    base: float | None = None,
+    axis: int = 0,
+    method: str = "auto",
+) -> np.number | np.ndarray:
+    r"""Given a sample of a distribution, estimate the differential entropy.
+
+    Several estimation methods are available using the `method` parameter. By
+    default, a method is selected based the size of the sample.
+
+    Parameters
+    ----------
+    values : sequence
+        Sample from a continuous distribution.
+    window_length : int, optional
+        Window length for computing Vasicek estimate. Must be an integer
+        between 1 and half of the sample size. If ``None`` (the default), it
+        uses the heuristic value
+
+        .. math::
+            \left \lfloor \sqrt{n} + 0.5 \right \rfloor
+
+        where :math:`n` is the sample size. This heuristic was originally
+        proposed in [2]_ and has become common in the literature.
+    base : float, optional
+        The logarithmic base to use, defaults to ``e`` (natural logarithm).
+    axis : int, optional
+        The axis along which the differential entropy is calculated.
+        Default is 0.
+    method : {'vasicek', 'van es', 'ebrahimi', 'correa', 'auto'}, optional
+        The method used to estimate the differential entropy from the sample.
+        Default is ``'auto'``.  See Notes for more information.
+
+    Returns
+    -------
+    entropy : float
+        The calculated differential entropy.
+
+    Notes
+    -----
+    This function will converge to the true differential entropy in the limit
+
+    .. math::
+        n \to \infty, \quad m \to \infty, \quad \frac{m}{n} \to 0
+
+    The optimal choice of ``window_length`` for a given sample size depends on
+    the (unknown) distribution. Typically, the smoother the density of the
+    distribution, the larger the optimal value of ``window_length`` [1]_.
+
+    The following options are available for the `method` parameter.
+
+    * ``'vasicek'`` uses the estimator presented in [1]_. This is
+      one of the first and most influential estimators of differential entropy.
+    * ``'van es'`` uses the bias-corrected estimator presented in [3]_, which
+      is not only consistent but, under some conditions, asymptotically normal.
+    * ``'ebrahimi'`` uses an estimator presented in [4]_, which was shown
+      in simulation to have smaller bias and mean squared error than
+      the Vasicek estimator.
+    * ``'correa'`` uses the estimator presented in [5]_ based on local linear
+      regression. In a simulation study, it had consistently smaller mean
+      square error than the Vasiceck estimator, but it is more expensive to
+      compute.
+    * ``'auto'`` selects the method automatically (default). Currently,
+      this selects ``'van es'`` for very small samples (<10), ``'ebrahimi'``
+      for moderate sample sizes (11-1000), and ``'vasicek'`` for larger
+      samples, but this behavior is subject to change in future versions.
+
+    All estimators are implemented as described in [6]_.
+
+    References
+    ----------
+    .. [1] Vasicek, O. (1976). A test for normality based on sample entropy.
+           Journal of the Royal Statistical Society:
+           Series B (Methodological), 38(1), 54-59.
+    .. [2] Crzcgorzewski, P., & Wirczorkowski, R. (1999). Entropy-based
+           goodness-of-fit test for exponentiality. Communications in
+           Statistics-Theory and Methods, 28(5), 1183-1202.
+    .. [3] Van Es, B. (1992). Estimating functionals related to a density by a
+           class of statistics based on spacings. Scandinavian Journal of
+           Statistics, 61-72.
+    .. [4] Ebrahimi, N., Pflughoeft, K., & Soofi, E. S. (1994). Two measures
+           of sample entropy. Statistics & Probability Letters, 20(3), 225-234.
+    .. [5] Correa, J. C. (1995). A new estimator of entropy. Communications
+           in Statistics-Theory and Methods, 24(10), 2439-2449.
+    .. [6] Noughabi, H. A. (2015). Entropy Estimation Using Numerical Methods.
+           Annals of Data Science, 2(2), 231-241.
+           https://link.springer.com/article/10.1007/s40745-015-0045-9
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import differential_entropy, norm
+
+    Entropy of a standard normal distribution:
+
+    >>> rng = np.random.default_rng()
+    >>> values = rng.standard_normal(100)
+    >>> differential_entropy(values)
+    1.3407817436640392
+
+    Compare with the true entropy:
+
+    >>> float(norm.entropy())
+    1.4189385332046727
+
+    For several sample sizes between 5 and 1000, compare the accuracy of
+    the ``'vasicek'``, ``'van es'``, and ``'ebrahimi'`` methods. Specifically,
+    compare the root mean squared error (over 1000 trials) between the estimate
+    and the true differential entropy of the distribution.
+
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>>
+    >>>
+    >>> def rmse(res, expected):
+    ...     '''Root mean squared error'''
+    ...     return np.sqrt(np.mean((res - expected)**2))
+    >>>
+    >>>
+    >>> a, b = np.log10(5), np.log10(1000)
+    >>> ns = np.round(np.logspace(a, b, 10)).astype(int)
+    >>> reps = 1000  # number of repetitions for each sample size
+    >>> expected = stats.expon.entropy()
+    >>>
+    >>> method_errors = {'vasicek': [], 'van es': [], 'ebrahimi': []}
+    >>> for method in method_errors:
+    ...     for n in ns:
+    ...        rvs = stats.expon.rvs(size=(reps, n), random_state=rng)
+    ...        res = stats.differential_entropy(rvs, method=method, axis=-1)
+    ...        error = rmse(res, expected)
+    ...        method_errors[method].append(error)
+    >>>
+    >>> for method, errors in method_errors.items():
+    ...     plt.loglog(ns, errors, label=method)
+    >>>
+    >>> plt.legend()
+    >>> plt.xlabel('sample size')
+    >>> plt.ylabel('RMSE (1000 trials)')
+    >>> plt.title('Entropy Estimator Error (Exponential Distribution)')
+
+    """
+    xp = array_namespace(values)
+    values = xp.asarray(values)
+    if xp.isdtype(values.dtype, "integral"):  # type: ignore[union-attr]
+        values = xp.astype(values, xp.asarray(1.).dtype)
+    values = xp_moveaxis_to_end(values, axis, xp=xp)
+    n = values.shape[-1]  # type: ignore[union-attr]
+
+    if window_length is None:
+        window_length = math.floor(math.sqrt(n) + 0.5)
+
+    if not 2 <= 2 * window_length < n:
+        raise ValueError(
+            f"Window length ({window_length}) must be positive and less "
+            f"than half the sample size ({n}).",
+        )
+
+    if base is not None and base <= 0:
+        raise ValueError("`base` must be a positive number or `None`.")
+
+    sorted_data = xp.sort(values, axis=-1)
+
+    methods = {"vasicek": _vasicek_entropy,
+               "van es": _van_es_entropy,
+               "correa": _correa_entropy,
+               "ebrahimi": _ebrahimi_entropy,
+               "auto": _vasicek_entropy}
+    method = method.lower()
+    if method not in methods:
+        message = f"`method` must be one of {set(methods)}"
+        raise ValueError(message)
+
+    if method == "auto":
+        if n <= 10:
+            method = 'van es'
+        elif n <= 1000:
+            method = 'ebrahimi'
+        else:
+            method = 'vasicek'
+
+    res = methods[method](sorted_data, window_length, xp=xp)
+
+    if base is not None:
+        res /= math.log(base)
+
+    # avoid dtype changes due to data-apis/array-api-compat#152
+    # can be removed when data-apis/array-api-compat#152 is resolved
+    return xp.astype(res, values.dtype)  # type: ignore[union-attr]
+
+
+def _pad_along_last_axis(X, m, *, xp):
+    """Pad the data for computing the rolling window difference."""
+    # scales a  bit better than method in _vasicek_like_entropy
+    shape = X.shape[:-1] + (m,)
+    Xl = xp.broadcast_to(X[..., :1], shape)  # :1 vs 0 to maintain shape
+    Xr = xp.broadcast_to(X[..., -1:], shape)
+    return xp.concat((Xl, X, Xr), axis=-1)
+
+
+def _vasicek_entropy(X, m, *, xp):
+    """Compute the Vasicek estimator as described in [6] Eq. 1.3."""
+    n = X.shape[-1]
+    X = _pad_along_last_axis(X, m, xp=xp)
+    differences = X[..., 2 * m:] - X[..., : -2 * m:]
+    logs = xp.log(n/(2*m) * differences)
+    return xp.mean(logs, axis=-1)
+
+
+def _van_es_entropy(X, m, *, xp):
+    """Compute the van Es estimator as described in [6]."""
+    # No equation number, but referred to as HVE_mn.
+    # Typo: there should be a log within the summation.
+    n = X.shape[-1]
+    difference = X[..., m:] - X[..., :-m]
+    term1 = 1/(n-m) * xp.sum(xp.log((n+1)/m * difference), axis=-1)
+    k = xp.arange(m, n+1, dtype=term1.dtype)
+    return term1 + xp.sum(1/k) + math.log(m) - math.log(n+1)
+
+
+def _ebrahimi_entropy(X, m, *, xp):
+    """Compute the Ebrahimi estimator as described in [6]."""
+    # No equation number, but referred to as HE_mn
+    n = X.shape[-1]
+    X = _pad_along_last_axis(X, m, xp=xp)
+
+    differences = X[..., 2 * m:] - X[..., : -2 * m:]
+
+    i = xp.arange(1, n+1, dtype=X.dtype)
+    ci = xp.ones_like(i)*2
+    ci[i <= m] = 1 + (i[i <= m] - 1)/m
+    ci[i >= n - m + 1] = 1 + (n - i[i >= n-m+1])/m
+
+    logs = xp.log(n * differences / (ci * m))
+    return xp.mean(logs, axis=-1)
+
+
+def _correa_entropy(X, m, *, xp):
+    """Compute the Correa estimator as described in [6]."""
+    # No equation number, but referred to as HC_mn
+    n = X.shape[-1]
+    X = _pad_along_last_axis(X, m, xp=xp)
+
+    i = xp.arange(1, n+1)
+    dj = xp.arange(-m, m+1)[:, None]
+    j = i + dj
+    j0 = j + m - 1  # 0-indexed version of j
+
+    Xibar = xp.mean(X[..., j0], axis=-2, keepdims=True)
+    difference = X[..., j0] - Xibar
+    num = xp.sum(difference*dj, axis=-2)  # dj is d-i
+    den = n*xp.sum(difference**2, axis=-2)
+    return -xp.mean(xp.log(num/den), axis=-1)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_fit.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_fit.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdb10606fdf60eed02790bbf27fe5152293a2b3b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_fit.py
@@ -0,0 +1,1351 @@
+import warnings
+from collections import namedtuple
+import numpy as np
+from scipy import optimize, stats
+from scipy._lib._util import check_random_state, _transition_to_rng
+
+
+def _combine_bounds(name, user_bounds, shape_domain, integral):
+    """Intersection of user-defined bounds and distribution PDF/PMF domain"""
+
+    user_bounds = np.atleast_1d(user_bounds)
+
+    if user_bounds[0] > user_bounds[1]:
+        message = (f"There are no values for `{name}` on the interval "
+                   f"{list(user_bounds)}.")
+        raise ValueError(message)
+
+    bounds = (max(user_bounds[0], shape_domain[0]),
+              min(user_bounds[1], shape_domain[1]))
+
+    if integral and (np.ceil(bounds[0]) > np.floor(bounds[1])):
+        message = (f"There are no integer values for `{name}` on the interval "
+                   f"defined by the user-provided bounds and the domain "
+                   "of the distribution.")
+        raise ValueError(message)
+    elif not integral and (bounds[0] > bounds[1]):
+        message = (f"There are no values for `{name}` on the interval "
+                   f"defined by the user-provided bounds and the domain "
+                   "of the distribution.")
+        raise ValueError(message)
+
+    if not np.all(np.isfinite(bounds)):
+        message = (f"The intersection of user-provided bounds for `{name}` "
+                   f"and the domain of the distribution is not finite. Please "
+                   f"provide finite bounds for shape `{name}` in `bounds`.")
+        raise ValueError(message)
+
+    return bounds
+
+
+class FitResult:
+    r"""Result of fitting a discrete or continuous distribution to data
+
+    Attributes
+    ----------
+    params : namedtuple
+        A namedtuple containing the maximum likelihood estimates of the
+        shape parameters, location, and (if applicable) scale of the
+        distribution.
+    success : bool or None
+        Whether the optimizer considered the optimization to terminate
+        successfully or not.
+    message : str or None
+        Any status message provided by the optimizer.
+
+    """
+
+    def __init__(self, dist, data, discrete, res):
+        self._dist = dist
+        self._data = data
+        self.discrete = discrete
+        self.pxf = getattr(dist, "pmf", None) or getattr(dist, "pdf", None)
+
+        shape_names = [] if dist.shapes is None else dist.shapes.split(", ")
+        if not discrete:
+            FitParams = namedtuple('FitParams', shape_names + ['loc', 'scale'])
+        else:
+            FitParams = namedtuple('FitParams', shape_names + ['loc'])
+
+        self.params = FitParams(*res.x)
+
+        # Optimizer can report success even when nllf is infinite
+        if res.success and not np.isfinite(self.nllf()):
+            res.success = False
+            res.message = ("Optimization converged to parameter values that "
+                           "are inconsistent with the data.")
+        self.success = getattr(res, "success", None)
+        self.message = getattr(res, "message", None)
+
+    def __repr__(self):
+        keys = ["params", "success", "message"]
+        m = max(map(len, keys)) + 1
+        return '\n'.join([key.rjust(m) + ': ' + repr(getattr(self, key))
+                          for key in keys if getattr(self, key) is not None])
+
+    def nllf(self, params=None, data=None):
+        """Negative log-likelihood function
+
+        Evaluates the negative of the log-likelihood function of the provided
+        data at the provided parameters.
+
+        Parameters
+        ----------
+        params : tuple, optional
+            The shape parameters, location, and (if applicable) scale of the
+            distribution as a single tuple. Default is the maximum likelihood
+            estimates (``self.params``).
+        data : array_like, optional
+            The data for which the log-likelihood function is to be evaluated.
+            Default is the data to which the distribution was fit.
+
+        Returns
+        -------
+        nllf : float
+            The negative of the log-likelihood function.
+
+        """
+        params = params if params is not None else self.params
+        data = data if data is not None else self._data
+        return self._dist.nnlf(theta=params, x=data)
+
+    def plot(self, ax=None, *, plot_type="hist"):
+        """Visually compare the data against the fitted distribution.
+
+        Available only if `matplotlib` is installed.
+
+        Parameters
+        ----------
+        ax : `matplotlib.axes.Axes`
+            Axes object to draw the plot onto, otherwise uses the current Axes.
+        plot_type : {"hist", "qq", "pp", "cdf"}
+            Type of plot to draw. Options include:
+
+            - "hist": Superposes the PDF/PMF of the fitted distribution
+              over a normalized histogram of the data.
+            - "qq": Scatter plot of theoretical quantiles against the
+              empirical quantiles. Specifically, the x-coordinates are the
+              values of the fitted distribution PPF evaluated at the
+              percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is the
+              number of data points, and the y-coordinates are the sorted
+              data points.
+            - "pp": Scatter plot of theoretical percentiles against the
+              observed percentiles. Specifically, the x-coordinates are the
+              percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is
+              the number of data points, and the y-coordinates are the values
+              of the fitted distribution CDF evaluated at the sorted
+              data points.
+            - "cdf": Superposes the CDF of the fitted distribution over the
+              empirical CDF. Specifically, the x-coordinates of the empirical
+              CDF are the sorted data points, and the y-coordinates are the
+              percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is
+              the number of data points.
+
+        Returns
+        -------
+        ax : `matplotlib.axes.Axes`
+            The matplotlib Axes object on which the plot was drawn.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> import matplotlib.pyplot as plt  # matplotlib must be installed
+        >>> rng = np.random.default_rng()
+        >>> data = stats.nbinom(5, 0.5).rvs(size=1000, random_state=rng)
+        >>> bounds = [(0, 30), (0, 1)]
+        >>> res = stats.fit(stats.nbinom, data, bounds)
+        >>> ax = res.plot()  # save matplotlib Axes object
+
+        The `matplotlib.axes.Axes` object can be used to customize the plot.
+        See `matplotlib.axes.Axes` documentation for details.
+
+        >>> ax.set_xlabel('number of trials')  # customize axis label
+        >>> ax.get_children()[0].set_linewidth(5)  # customize line widths
+        >>> ax.legend()
+        >>> plt.show()
+        """
+        try:
+            import matplotlib  # noqa: F401
+        except ModuleNotFoundError as exc:
+            message = "matplotlib must be installed to use method `plot`."
+            raise ModuleNotFoundError(message) from exc
+
+        plots = {'histogram': self._hist_plot, 'qq': self._qq_plot,
+                 'pp': self._pp_plot, 'cdf': self._cdf_plot,
+                 'hist': self._hist_plot}
+        if plot_type.lower() not in plots:
+            message = f"`plot_type` must be one of {set(plots.keys())}"
+            raise ValueError(message)
+        plot = plots[plot_type.lower()]
+
+        if ax is None:
+            import matplotlib.pyplot as plt
+            ax = plt.gca()
+
+        fit_params = np.atleast_1d(self.params)
+
+        return plot(ax=ax, fit_params=fit_params)
+
+    def _hist_plot(self, ax, fit_params):
+        from matplotlib.ticker import MaxNLocator
+
+        support = self._dist.support(*fit_params)
+        lb = support[0] if np.isfinite(support[0]) else min(self._data)
+        ub = support[1] if np.isfinite(support[1]) else max(self._data)
+        pxf = "PMF" if self.discrete else "PDF"
+
+        if self.discrete:
+            x = np.arange(lb, ub + 2)
+            y = self.pxf(x, *fit_params)
+            ax.vlines(x[:-1], 0, y[:-1], label='Fitted Distribution PMF',
+                      color='C0')
+            options = dict(density=True, bins=x, align='left', color='C1')
+            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
+            ax.set_xlabel('k')
+            ax.set_ylabel('PMF')
+        else:
+            x = np.linspace(lb, ub, 200)
+            y = self.pxf(x, *fit_params)
+            ax.plot(x, y, '--', label='Fitted Distribution PDF', color='C0')
+            options = dict(density=True, bins=50, align='mid', color='C1')
+            ax.set_xlabel('x')
+            ax.set_ylabel('PDF')
+
+        if len(self._data) > 50 or self.discrete:
+            ax.hist(self._data, label="Histogram of Data", **options)
+        else:
+            ax.plot(self._data, np.zeros_like(self._data), "*",
+                    label='Data', color='C1')
+
+        ax.set_title(rf"Fitted $\tt {self._dist.name}$ {pxf} and Histogram")
+        ax.legend(*ax.get_legend_handles_labels())
+        return ax
+
+    def _qp_plot(self, ax, fit_params, qq):
+        data = np.sort(self._data)
+        ps = self._plotting_positions(len(self._data))
+
+        if qq:
+            qp = "Quantiles"
+            plot_type = 'Q-Q'
+            x = self._dist.ppf(ps, *fit_params)
+            y = data
+        else:
+            qp = "Percentiles"
+            plot_type = 'P-P'
+            x = ps
+            y = self._dist.cdf(data, *fit_params)
+
+        ax.plot(x, y, '.', label=f'Fitted Distribution {plot_type}',
+                color='C0', zorder=1)
+        xlim = ax.get_xlim()
+        ylim = ax.get_ylim()
+        lim = [min(xlim[0], ylim[0]), max(xlim[1], ylim[1])]
+        if not qq:
+            lim = max(lim[0], 0), min(lim[1], 1)
+
+        if self.discrete and qq:
+            q_min, q_max = int(lim[0]), int(lim[1]+1)
+            q_ideal = np.arange(q_min, q_max)
+            # q_ideal = np.unique(self._dist.ppf(ps, *fit_params))
+            ax.plot(q_ideal, q_ideal, 'o', label='Reference', color='k',
+                    alpha=0.25, markerfacecolor='none', clip_on=True)
+        elif self.discrete and not qq:
+            # The intent of this is to match the plot that would be produced
+            # if x were continuous on [0, 1] and y were cdf(ppf(x)).
+            # It can be approximated by letting x = np.linspace(0, 1, 1000),
+            # but this might not look great when zooming in. The vertical
+            # portions are included to indicate where the transition occurs
+            # where the data completely obscures the horizontal portions.
+            p_min, p_max = lim
+            a, b = self._dist.support(*fit_params)
+            p_min = max(p_min, 0 if np.isfinite(a) else 1e-3)
+            p_max = min(p_max, 1 if np.isfinite(b) else 1-1e-3)
+            q_min, q_max = self._dist.ppf([p_min, p_max], *fit_params)
+            qs = np.arange(q_min-1, q_max+1)
+            ps = self._dist.cdf(qs, *fit_params)
+            ax.step(ps, ps, '-', label='Reference', color='k', alpha=0.25,
+                    clip_on=True)
+        else:
+            ax.plot(lim, lim, '-', label='Reference', color='k', alpha=0.25,
+                    clip_on=True)
+
+        ax.set_xlim(lim)
+        ax.set_ylim(lim)
+        ax.set_xlabel(rf"Fitted $\tt {self._dist.name}$ Theoretical {qp}")
+        ax.set_ylabel(f"Data {qp}")
+        ax.set_title(rf"Fitted $\tt {self._dist.name}$ {plot_type} Plot")
+        ax.legend(*ax.get_legend_handles_labels())
+        ax.set_aspect('equal')
+        return ax
+
+    def _qq_plot(self, **kwargs):
+        return self._qp_plot(qq=True, **kwargs)
+
+    def _pp_plot(self, **kwargs):
+        return self._qp_plot(qq=False, **kwargs)
+
+    def _plotting_positions(self, n, a=.5):
+        # See https://en.wikipedia.org/wiki/Q%E2%80%93Q_plot#Plotting_positions
+        k = np.arange(1, n+1)
+        return (k-a) / (n + 1 - 2*a)
+
+    def _cdf_plot(self, ax, fit_params):
+        data = np.sort(self._data)
+        ecdf = self._plotting_positions(len(self._data))
+        ls = '--' if len(np.unique(data)) < 30 else '.'
+        xlabel = 'k' if self.discrete else 'x'
+        ax.step(data, ecdf, ls, label='Empirical CDF', color='C1', zorder=0)
+
+        xlim = ax.get_xlim()
+        q = np.linspace(*xlim, 300)
+        tcdf = self._dist.cdf(q, *fit_params)
+
+        ax.plot(q, tcdf, label='Fitted Distribution CDF', color='C0', zorder=1)
+        ax.set_xlim(xlim)
+        ax.set_ylim(0, 1)
+        ax.set_xlabel(xlabel)
+        ax.set_ylabel("CDF")
+        ax.set_title(rf"Fitted $\tt {self._dist.name}$ and Empirical CDF")
+        handles, labels = ax.get_legend_handles_labels()
+        ax.legend(handles[::-1], labels[::-1])
+        return ax
+
+
+def fit(dist, data, bounds=None, *, guess=None, method='mle',
+        optimizer=optimize.differential_evolution):
+    r"""Fit a discrete or continuous distribution to data
+
+    Given a distribution, data, and bounds on the parameters of the
+    distribution, return maximum likelihood estimates of the parameters.
+
+    Parameters
+    ----------
+    dist : `scipy.stats.rv_continuous` or `scipy.stats.rv_discrete`
+        The object representing the distribution to be fit to the data.
+    data : 1D array_like
+        The data to which the distribution is to be fit. If the data contain
+        any of ``np.nan``, ``np.inf``, or -``np.inf``, the fit method will
+        raise a ``ValueError``.
+    bounds : dict or sequence of tuples, optional
+        If a dictionary, each key is the name of a parameter of the
+        distribution, and the corresponding value is a tuple containing the
+        lower and upper bound on that parameter.  If the distribution is
+        defined only for a finite range of values of that parameter, no entry
+        for that parameter is required; e.g., some distributions have
+        parameters which must be on the interval [0, 1]. Bounds for parameters
+        location (``loc``) and scale (``scale``) are optional; by default,
+        they are fixed to 0 and 1, respectively.
+
+        If a sequence, element *i* is a tuple containing the lower and upper
+        bound on the *i*\ th parameter of the distribution. In this case,
+        bounds for *all* distribution shape parameters must be provided.
+        Optionally, bounds for location and scale may follow the
+        distribution shape parameters.
+
+        If a shape is to be held fixed (e.g. if it is known), the
+        lower and upper bounds may be equal. If a user-provided lower or upper
+        bound is beyond a bound of the domain for which the distribution is
+        defined, the bound of the distribution's domain will replace the
+        user-provided value. Similarly, parameters which must be integral
+        will be constrained to integral values within the user-provided bounds.
+    guess : dict or array_like, optional
+        If a dictionary, each key is the name of a parameter of the
+        distribution, and the corresponding value is a guess for the value
+        of the parameter.
+
+        If a sequence, element *i* is a guess for the *i*\ th parameter of the
+        distribution. In this case, guesses for *all* distribution shape
+        parameters must be provided.
+
+        If `guess` is not provided, guesses for the decision variables will
+        not be passed to the optimizer. If `guess` is provided, guesses for
+        any missing parameters will be set at the mean of the lower and
+        upper bounds. Guesses for parameters which must be integral will be
+        rounded to integral values, and guesses that lie outside the
+        intersection of the user-provided bounds and the domain of the
+        distribution will be clipped.
+    method : {'mle', 'mse'}
+        With ``method="mle"`` (default), the fit is computed by minimizing
+        the negative log-likelihood function. A large, finite penalty
+        (rather than infinite negative log-likelihood) is applied for
+        observations beyond the support of the distribution.
+        With ``method="mse"``, the fit is computed by minimizing
+        the negative log-product spacing function. The same penalty is applied
+        for observations beyond the support. We follow the approach of [1]_,
+        which is generalized for samples with repeated observations.
+    optimizer : callable, optional
+        `optimizer` is a callable that accepts the following positional
+        argument.
+
+        fun : callable
+            The objective function to be optimized. `fun` accepts one argument
+            ``x``, candidate shape parameters of the distribution, and returns
+            the objective function value given ``x``, `dist`, and the provided
+            `data`.
+            The job of `optimizer` is to find values of the decision variables
+            that minimizes `fun`.
+
+        `optimizer` must also accept the following keyword argument.
+
+        bounds : sequence of tuples
+            The bounds on values of the decision variables; each element will
+            be a tuple containing the lower and upper bound on a decision
+            variable.
+
+        If `guess` is provided, `optimizer` must also accept the following
+        keyword argument.
+
+        x0 : array_like
+            The guesses for each decision variable.
+
+        If the distribution has any shape parameters that must be integral or
+        if the distribution is discrete and the location parameter is not
+        fixed, `optimizer` must also accept the following keyword argument.
+
+        integrality : array_like of bools
+            For each decision variable, True if the decision variable
+            must be constrained to integer values and False if the decision
+            variable is continuous.
+
+        `optimizer` must return an object, such as an instance of
+        `scipy.optimize.OptimizeResult`, which holds the optimal values of
+        the decision variables in an attribute ``x``. If attributes
+        ``fun``, ``status``, or ``message`` are provided, they will be
+        included in the result object returned by `fit`.
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.FitResult`
+        An object with the following fields.
+
+        params : namedtuple
+            A namedtuple containing the maximum likelihood estimates of the
+            shape parameters, location, and (if applicable) scale of the
+            distribution.
+        success : bool or None
+            Whether the optimizer considered the optimization to terminate
+            successfully or not.
+        message : str or None
+            Any status message provided by the optimizer.
+
+        The object has the following method:
+
+        nllf(params=None, data=None)
+            By default, the negative log-likelihood function at the fitted
+            `params` for the given `data`. Accepts a tuple containing
+            alternative shapes, location, and scale of the distribution and
+            an array of alternative data.
+
+        plot(ax=None)
+            Superposes the PDF/PMF of the fitted distribution over a normalized
+            histogram of the data.
+
+    See Also
+    --------
+    rv_continuous,  rv_discrete
+
+    Notes
+    -----
+    Optimization is more likely to converge to the maximum likelihood estimate
+    when the user provides tight bounds containing the maximum likelihood
+    estimate. For example, when fitting a binomial distribution to data, the
+    number of experiments underlying each sample may be known, in which case
+    the corresponding shape parameter ``n`` can be fixed.
+
+    References
+    ----------
+    .. [1] Shao, Yongzhao, and Marjorie G. Hahn. "Maximum product of spacings
+           method: a unified formulation with illustration of strong
+           consistency." Illinois Journal of Mathematics 43.3 (1999): 489-499.
+
+    Examples
+    --------
+    Suppose we wish to fit a distribution to the following data.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> dist = stats.nbinom
+    >>> shapes = (5, 0.5)
+    >>> data = dist.rvs(*shapes, size=1000, random_state=rng)
+
+    Suppose we do not know how the data were generated, but we suspect that
+    it follows a negative binomial distribution with parameters *n* and *p*\.
+    (See `scipy.stats.nbinom`.) We believe that the parameter *n* was fewer
+    than 30, and we know that the parameter *p* must lie on the interval
+    [0, 1]. We record this information in a variable `bounds` and pass
+    this information to `fit`.
+
+    >>> bounds = [(0, 30), (0, 1)]
+    >>> res = stats.fit(dist, data, bounds)
+
+    `fit` searches within the user-specified `bounds` for the
+    values that best match the data (in the sense of maximum likelihood
+    estimation). In this case, it found shape values similar to those
+    from which the data were actually generated.
+
+    >>> res.params
+    FitParams(n=5.0, p=0.5028157644634368, loc=0.0)  # may vary
+
+    We can visualize the results by superposing the probability mass function
+    of the distribution (with the shapes fit to the data) over a normalized
+    histogram of the data.
+
+    >>> import matplotlib.pyplot as plt  # matplotlib must be installed to plot
+    >>> res.plot()
+    >>> plt.show()
+
+    Note that the estimate for *n* was exactly integral; this is because
+    the domain of the `nbinom` PMF includes only integral *n*, and the `nbinom`
+    object "knows" that. `nbinom` also knows that the shape *p* must be a
+    value between 0 and 1. In such a case - when the domain of the distribution
+    with respect to a parameter is finite - we are not required to specify
+    bounds for the parameter.
+
+    >>> bounds = {'n': (0, 30)}  # omit parameter p using a `dict`
+    >>> res2 = stats.fit(dist, data, bounds)
+    >>> res2.params
+    FitParams(n=5.0, p=0.5016492009232932, loc=0.0)  # may vary
+
+    If we wish to force the distribution to be fit with *n* fixed at 6, we can
+    set both the lower and upper bounds on *n* to 6. Note, however, that the
+    value of the objective function being optimized is typically worse (higher)
+    in this case.
+
+    >>> bounds = {'n': (6, 6)}  # fix parameter `n`
+    >>> res3 = stats.fit(dist, data, bounds)
+    >>> res3.params
+    FitParams(n=6.0, p=0.5486556076755706, loc=0.0)  # may vary
+    >>> res3.nllf() > res.nllf()
+    True  # may vary
+
+    Note that the numerical results of the previous examples are typical, but
+    they may vary because the default optimizer used by `fit`,
+    `scipy.optimize.differential_evolution`, is stochastic. However, we can
+    customize the settings used by the optimizer to ensure reproducibility -
+    or even use a different optimizer entirely - using the `optimizer`
+    parameter.
+
+    >>> from scipy.optimize import differential_evolution
+    >>> rng = np.random.default_rng(767585560716548)
+    >>> def optimizer(fun, bounds, *, integrality):
+    ...     return differential_evolution(fun, bounds, strategy='best2bin',
+    ...                                   rng=rng, integrality=integrality)
+    >>> bounds = [(0, 30), (0, 1)]
+    >>> res4 = stats.fit(dist, data, bounds, optimizer=optimizer)
+    >>> res4.params
+    FitParams(n=5.0, p=0.5015183149259951, loc=0.0)
+
+    """
+    # --- Input Validation / Standardization --- #
+    user_bounds = bounds
+    user_guess = guess
+
+    # distribution input validation and information collection
+    if hasattr(dist, "pdf"):  # can't use isinstance for types
+        default_bounds = {'loc': (0, 0), 'scale': (1, 1)}
+        discrete = False
+    elif hasattr(dist, "pmf"):
+        default_bounds = {'loc': (0, 0)}
+        discrete = True
+    else:
+        message = ("`dist` must be an instance of `rv_continuous` "
+                   "or `rv_discrete.`")
+        raise ValueError(message)
+
+    try:
+        param_info = dist._param_info()
+    except AttributeError as e:
+        message = (f"Distribution `{dist.name}` is not yet supported by "
+                   "`scipy.stats.fit` because shape information has "
+                   "not been defined.")
+        raise ValueError(message) from e
+
+    # data input validation
+    data = np.asarray(data)
+    if data.ndim != 1:
+        message = "`data` must be exactly one-dimensional."
+        raise ValueError(message)
+    if not (np.issubdtype(data.dtype, np.number)
+            and np.all(np.isfinite(data))):
+        message = "All elements of `data` must be finite numbers."
+        raise ValueError(message)
+
+    # bounds input validation and information collection
+    n_params = len(param_info)
+    n_shapes = n_params - (1 if discrete else 2)
+    param_list = [param.name for param in param_info]
+    param_names = ", ".join(param_list)
+    shape_names = ", ".join(param_list[:n_shapes])
+
+    if user_bounds is None:
+        user_bounds = {}
+
+    if isinstance(user_bounds, dict):
+        default_bounds.update(user_bounds)
+        user_bounds = default_bounds
+        user_bounds_array = np.empty((n_params, 2))
+        for i in range(n_params):
+            param_name = param_info[i].name
+            user_bound = user_bounds.pop(param_name, None)
+            if user_bound is None:
+                user_bound = param_info[i].domain
+            user_bounds_array[i] = user_bound
+        if user_bounds:
+            message = ("Bounds provided for the following unrecognized "
+                       f"parameters will be ignored: {set(user_bounds)}")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+    else:
+        try:
+            user_bounds = np.asarray(user_bounds, dtype=float)
+            if user_bounds.size == 0:
+                user_bounds = np.empty((0, 2))
+        except ValueError as e:
+            message = ("Each element of a `bounds` sequence must be a tuple "
+                       "containing two elements: the lower and upper bound of "
+                       "a distribution parameter.")
+            raise ValueError(message) from e
+        if (user_bounds.ndim != 2 or user_bounds.shape[1] != 2):
+            message = ("Each element of `bounds` must be a tuple specifying "
+                       "the lower and upper bounds of a shape parameter")
+            raise ValueError(message)
+        if user_bounds.shape[0] < n_shapes:
+            message = (f"A `bounds` sequence must contain at least {n_shapes} "
+                       "elements: tuples specifying the lower and upper "
+                       f"bounds of all shape parameters {shape_names}.")
+            raise ValueError(message)
+        if user_bounds.shape[0] > n_params:
+            message = ("A `bounds` sequence may not contain more than "
+                       f"{n_params} elements: tuples specifying the lower and "
+                       "upper bounds of distribution parameters "
+                       f"{param_names}.")
+            raise ValueError(message)
+
+        user_bounds_array = np.empty((n_params, 2))
+        user_bounds_array[n_shapes:] = list(default_bounds.values())
+        user_bounds_array[:len(user_bounds)] = user_bounds
+
+    user_bounds = user_bounds_array
+    validated_bounds = []
+    for i in range(n_params):
+        name = param_info[i].name
+        user_bound = user_bounds_array[i]
+        param_domain = param_info[i].domain
+        integral = param_info[i].integrality
+        combined = _combine_bounds(name, user_bound, param_domain, integral)
+        validated_bounds.append(combined)
+
+    bounds = np.asarray(validated_bounds)
+    integrality = [param.integrality for param in param_info]
+
+    # guess input validation
+
+    if user_guess is None:
+        guess_array = None
+    elif isinstance(user_guess, dict):
+        default_guess = {param.name: np.mean(bound)
+                         for param, bound in zip(param_info, bounds)}
+        unrecognized = set(user_guess) - set(default_guess)
+        if unrecognized:
+            message = ("Guesses provided for the following unrecognized "
+                       f"parameters will be ignored: {unrecognized}")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+        default_guess.update(user_guess)
+
+        message = ("Each element of `guess` must be a scalar "
+                   "guess for a distribution parameter.")
+        try:
+            guess_array = np.asarray([default_guess[param.name]
+                                      for param in param_info], dtype=float)
+        except ValueError as e:
+            raise ValueError(message) from e
+
+    else:
+        message = ("Each element of `guess` must be a scalar "
+                   "guess for a distribution parameter.")
+        try:
+            user_guess = np.asarray(user_guess, dtype=float)
+        except ValueError as e:
+            raise ValueError(message) from e
+        if user_guess.ndim != 1:
+            raise ValueError(message)
+        if user_guess.shape[0] < n_shapes:
+            message = (f"A `guess` sequence must contain at least {n_shapes} "
+                       "elements: scalar guesses for the distribution shape "
+                       f"parameters {shape_names}.")
+            raise ValueError(message)
+        if user_guess.shape[0] > n_params:
+            message = ("A `guess` sequence may not contain more than "
+                       f"{n_params} elements: scalar guesses for the "
+                       f"distribution parameters {param_names}.")
+            raise ValueError(message)
+
+        guess_array = np.mean(bounds, axis=1)
+        guess_array[:len(user_guess)] = user_guess
+
+    if guess_array is not None:
+        guess_rounded = guess_array.copy()
+
+        guess_rounded[integrality] = np.round(guess_rounded[integrality])
+        rounded = np.where(guess_rounded != guess_array)[0]
+        for i in rounded:
+            message = (f"Guess for parameter `{param_info[i].name}` "
+                       f"rounded from {guess_array[i]} to {guess_rounded[i]}.")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+        guess_clipped = np.clip(guess_rounded, bounds[:, 0], bounds[:, 1])
+        clipped = np.where(guess_clipped != guess_rounded)[0]
+        for i in clipped:
+            message = (f"Guess for parameter `{param_info[i].name}` "
+                       f"clipped from {guess_rounded[i]} to "
+                       f"{guess_clipped[i]}.")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+        guess = guess_clipped
+    else:
+        guess = None
+
+    # --- Fitting --- #
+    def nllf(free_params, data=data):  # bind data NOW
+        with np.errstate(invalid='ignore', divide='ignore'):
+            return dist._penalized_nnlf(free_params, data)
+
+    def nlpsf(free_params, data=data):  # bind data NOW
+        with np.errstate(invalid='ignore', divide='ignore'):
+            return dist._penalized_nlpsf(free_params, data)
+
+    methods = {'mle': nllf, 'mse': nlpsf}
+    objective = methods[method.lower()]
+
+    with np.errstate(invalid='ignore', divide='ignore'):
+        kwds = {}
+        if bounds is not None:
+            kwds['bounds'] = bounds
+        if np.any(integrality):
+            kwds['integrality'] = integrality
+        if guess is not None:
+            kwds['x0'] = guess
+        res = optimizer(objective, **kwds)
+
+    return FitResult(dist, data, discrete, res)
+
+
+GoodnessOfFitResult = namedtuple('GoodnessOfFitResult',
+                                 ('fit_result', 'statistic', 'pvalue',
+                                  'null_distribution'))
+
+
+@_transition_to_rng('random_state')
+def goodness_of_fit(dist, data, *, known_params=None, fit_params=None,
+                    guessed_params=None, statistic='ad', n_mc_samples=9999,
+                    rng=None):
+    r"""
+    Perform a goodness of fit test comparing data to a distribution family.
+
+    Given a distribution family and data, perform a test of the null hypothesis
+    that the data were drawn from a distribution in that family. Any known
+    parameters of the distribution may be specified. Remaining parameters of
+    the distribution will be fit to the data, and the p-value of the test
+    is computed accordingly. Several statistics for comparing the distribution
+    to data are available.
+
+    Parameters
+    ----------
+    dist : `scipy.stats.rv_continuous`
+        The object representing the distribution family under the null
+        hypothesis.
+    data : 1D array_like
+        Finite, uncensored data to be tested.
+    known_params : dict, optional
+        A dictionary containing name-value pairs of known distribution
+        parameters. Monte Carlo samples are randomly drawn from the
+        null-hypothesized distribution with these values of the parameters.
+        Before the statistic is evaluated for the observed `data` and each
+        Monte Carlo sample, only remaining unknown parameters of the
+        null-hypothesized distribution family are fit to the samples; the
+        known parameters are held fixed. If all parameters of the distribution
+        family are known, then the step of fitting the distribution family to
+        each sample is omitted.
+    fit_params : dict, optional
+        A dictionary containing name-value pairs of distribution parameters
+        that have already been fit to the data, e.g. using `scipy.stats.fit`
+        or the ``fit`` method of `dist`. Monte Carlo samples are drawn from the
+        null-hypothesized distribution with these specified values of the
+        parameter. However, these and all other unknown parameters of the
+        null-hypothesized distribution family are always fit to the sample,
+        whether that is the observed `data` or a Monte Carlo sample, before
+        the statistic is evaluated.
+    guessed_params : dict, optional
+        A dictionary containing name-value pairs of distribution parameters
+        which have been guessed. These parameters are always considered as
+        free parameters and are fit both to the provided `data` as well as
+        to the Monte Carlo samples drawn from the null-hypothesized
+        distribution. The purpose of these `guessed_params` is to be used as
+        initial values for the numerical fitting procedure.
+    statistic : {"ad", "ks", "cvm", "filliben"} or callable, optional
+        The statistic used to compare data to a distribution after fitting
+        unknown parameters of the distribution family to the data. The
+        Anderson-Darling ("ad") [1]_, Kolmogorov-Smirnov ("ks") [1]_,
+        Cramer-von Mises ("cvm") [1]_, and Filliben ("filliben") [7]_
+        statistics are available.  Alternatively, a callable with signature
+        ``(dist, data, axis)`` may be supplied to compute the statistic. Here
+        ``dist`` is a frozen distribution object (potentially with array
+        parameters), ``data`` is an array of Monte Carlo samples (of
+        compatible shape), and ``axis`` is the axis of ``data`` along which
+        the statistic must be computed.
+    n_mc_samples : int, default: 9999
+        The number of Monte Carlo samples drawn from the null hypothesized
+        distribution to form the null distribution of the statistic. The
+        sample size of each is the same as the given `data`.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    res : GoodnessOfFitResult
+        An object with the following attributes.
+
+        fit_result : `~scipy.stats._result_classes.FitResult`
+            An object representing the fit of the provided `dist` to `data`.
+            This  object includes the values of distribution family parameters
+            that fully define the null-hypothesized distribution, that is,
+            the distribution from which Monte Carlo samples are drawn.
+        statistic : float
+            The value of the statistic comparing provided `data` to the
+            null-hypothesized distribution.
+        pvalue : float
+            The proportion of elements in the null distribution with
+            statistic values at least as extreme as the statistic value of the
+            provided `data`.
+        null_distribution : ndarray
+            The value of the statistic for each Monte Carlo sample
+            drawn from the null-hypothesized distribution.
+
+    Notes
+    -----
+    This is a generalized Monte Carlo goodness-of-fit procedure, special cases
+    of which correspond with various Anderson-Darling tests, Lilliefors' test,
+    etc. The test is described in [2]_, [3]_, and [4]_ as a parametric
+    bootstrap test. This is a Monte Carlo test in which parameters that
+    specify the distribution from which samples are drawn have been estimated
+    from the data. We describe the test using "Monte Carlo" rather than
+    "parametric bootstrap" throughout to avoid confusion with the more familiar
+    nonparametric bootstrap, and describe how the test is performed below.
+
+    *Traditional goodness of fit tests*
+
+    Traditionally, critical values corresponding with a fixed set of
+    significance levels are pre-calculated using Monte Carlo methods. Users
+    perform the test by calculating the value of the test statistic only for
+    their observed `data` and comparing this value to tabulated critical
+    values. This practice is not very flexible, as tables are not available for
+    all distributions and combinations of known and unknown parameter values.
+    Also, results can be inaccurate when critical values are interpolated from
+    limited tabulated data to correspond with the user's sample size and
+    fitted parameter values. To overcome these shortcomings, this function
+    allows the user to perform the Monte Carlo trials adapted to their
+    particular data.
+
+    *Algorithmic overview*
+
+    In brief, this routine executes the following steps:
+
+      1. Fit unknown parameters to the given `data`, thereby forming the
+         "null-hypothesized" distribution, and compute the statistic of
+         this pair of data and distribution.
+      2. Draw random samples from this null-hypothesized distribution.
+      3. Fit the unknown parameters to each random sample.
+      4. Calculate the statistic between each sample and the distribution that
+         has been fit to the sample.
+      5. Compare the value of the statistic corresponding with `data` from (1)
+         against the values of the statistic corresponding with the random
+         samples from (4). The p-value is the proportion of samples with a
+         statistic value greater than or equal to the statistic of the observed
+         data.
+
+    In more detail, the steps are as follows.
+
+    First, any unknown parameters of the distribution family specified by
+    `dist` are fit to the provided `data` using maximum likelihood estimation.
+    (One exception is the normal distribution with unknown location and scale:
+    we use the bias-corrected standard deviation ``np.std(data, ddof=1)`` for
+    the scale as recommended in [1]_.)
+    These values of the parameters specify a particular member of the
+    distribution family referred to as the "null-hypothesized distribution",
+    that is, the distribution from which the data were sampled under the null
+    hypothesis. The `statistic`, which compares data to a distribution, is
+    computed between `data` and the null-hypothesized distribution.
+
+    Next, many (specifically `n_mc_samples`) new samples, each containing the
+    same number of observations as `data`, are drawn from the
+    null-hypothesized distribution. All unknown parameters of the distribution
+    family `dist` are fit to *each resample*, and the `statistic` is computed
+    between each sample and its corresponding fitted distribution. These
+    values of the statistic form the Monte Carlo null distribution (not to be
+    confused with the "null-hypothesized distribution" above).
+
+    The p-value of the test is the proportion of statistic values in the Monte
+    Carlo null distribution that are at least as extreme as the statistic value
+    of the provided `data`. More precisely, the p-value is given by
+
+    .. math::
+
+        p = \frac{b + 1}
+                 {m + 1}
+
+    where :math:`b` is the number of statistic values in the Monte Carlo null
+    distribution that are greater than or equal to the statistic value
+    calculated for `data`, and :math:`m` is the number of elements in the
+    Monte Carlo null distribution (`n_mc_samples`). The addition of :math:`1`
+    to the numerator and denominator can be thought of as including the
+    value of the statistic corresponding with `data` in the null distribution,
+    but a more formal explanation is given in [5]_.
+
+    *Limitations*
+
+    The test can be very slow for some distribution families because unknown
+    parameters of the distribution family must be fit to each of the Monte
+    Carlo samples, and for most distributions in SciPy, distribution fitting
+    performed via numerical optimization.
+
+    *Anti-Pattern*
+
+    For this reason, it may be tempting
+    to treat parameters of the distribution pre-fit to `data` (by the user)
+    as though they were `known_params`, as specification of all parameters of
+    the distribution precludes the need to fit the distribution to each Monte
+    Carlo sample. (This is essentially how the original Kilmogorov-Smirnov
+    test is performed.) Although such a test can provide evidence against the
+    null hypothesis, the test is conservative in the sense that small p-values
+    will tend to (greatly) *overestimate* the probability of making a type I
+    error (that is, rejecting the null hypothesis although it is true), and the
+    power of the test is low (that is, it is less likely to reject the null
+    hypothesis even when the null hypothesis is false).
+    This is because the Monte Carlo samples are less likely to agree with the
+    null-hypothesized distribution as well as `data`. This tends to increase
+    the values of the statistic recorded in the null distribution, so that a
+    larger number of them exceed the value of statistic for `data`, thereby
+    inflating the p-value.
+
+    References
+    ----------
+    .. [1] M. A. Stephens (1974). "EDF Statistics for Goodness of Fit and
+           Some Comparisons." Journal of the American Statistical Association,
+           Vol. 69, pp. 730-737.
+    .. [2] W. Stute, W. G. Manteiga, and M. P. Quindimil (1993).
+           "Bootstrap based goodness-of-fit-tests." Metrika 40.1: 243-256.
+    .. [3] C. Genest, & B Rémillard. (2008). "Validity of the parametric
+           bootstrap for goodness-of-fit testing in semiparametric models."
+           Annales de l'IHP Probabilités et statistiques. Vol. 44. No. 6.
+    .. [4] I. Kojadinovic and J. Yan (2012). "Goodness-of-fit testing based on
+           a weighted bootstrap: A fast large-sample alternative to the
+           parametric bootstrap." Canadian Journal of Statistics 40.3: 480-500.
+    .. [5] B. Phipson and G. K. Smyth (2010). "Permutation P-values Should
+           Never Be Zero: Calculating Exact P-values When Permutations Are
+           Randomly Drawn." Statistical Applications in Genetics and Molecular
+           Biology 9.1.
+    .. [6] H. W. Lilliefors (1967). "On the Kolmogorov-Smirnov test for
+           normality with mean and variance unknown." Journal of the American
+           statistical Association 62.318: 399-402.
+    .. [7] Filliben, James J. "The probability plot correlation coefficient
+           test for normality." Technometrics 17.1 (1975): 111-117.
+
+    Examples
+    --------
+    A well-known test of the null hypothesis that data were drawn from a
+    given distribution is the Kolmogorov-Smirnov (KS) test, available in SciPy
+    as `scipy.stats.ks_1samp`. Suppose we wish to test whether the following
+    data:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = stats.uniform.rvs(size=75, random_state=rng)
+
+    were sampled from a normal distribution. To perform a KS test, the
+    empirical distribution function of the observed data will be compared
+    against the (theoretical) cumulative distribution function of a normal
+    distribution. Of course, to do this, the normal distribution under the null
+    hypothesis must be fully specified. This is commonly done by first fitting
+    the ``loc`` and ``scale`` parameters of the distribution to the observed
+    data, then performing the test.
+
+    >>> loc, scale = np.mean(x), np.std(x, ddof=1)
+    >>> cdf = stats.norm(loc, scale).cdf
+    >>> stats.ks_1samp(x, cdf)
+    KstestResult(statistic=0.1119257570456813,
+                 pvalue=0.2827756409939257,
+                 statistic_location=0.7751845155861765,
+                 statistic_sign=-1)
+
+    An advantage of the KS-test is that the p-value - the probability of
+    obtaining a value of the test statistic under the null hypothesis as
+    extreme as the value obtained from the observed data - can be calculated
+    exactly and efficiently. `goodness_of_fit` can only approximate these
+    results.
+
+    >>> known_params = {'loc': loc, 'scale': scale}
+    >>> res = stats.goodness_of_fit(stats.norm, x, known_params=known_params,
+    ...                             statistic='ks', rng=rng)
+    >>> res.statistic, res.pvalue
+    (0.1119257570456813, 0.2788)
+
+    The statistic matches exactly, but the p-value is estimated by forming
+    a "Monte Carlo null distribution", that is, by explicitly drawing random
+    samples from `scipy.stats.norm` with the provided parameters and
+    calculating the stastic for each. The fraction of these statistic values
+    at least as extreme as ``res.statistic`` approximates the exact p-value
+    calculated by `scipy.stats.ks_1samp`.
+
+    However, in many cases, we would prefer to test only that the data were
+    sampled from one of *any* member of the normal distribution family, not
+    specifically from the normal distribution with the location and scale
+    fitted to the observed sample. In this case, Lilliefors [6]_ argued that
+    the KS test is far too conservative (that is, the p-value overstates
+    the actual probability of rejecting a true null hypothesis) and thus lacks
+    power - the ability to reject the null hypothesis when the null hypothesis
+    is actually false.
+    Indeed, our p-value above is approximately 0.28, which is far too large
+    to reject the null hypothesis at any common significance level.
+
+    Consider why this might be. Note that in the KS test above, the statistic
+    always compares data against the CDF of a normal distribution fitted to the
+    *observed data*. This tends to reduce the value of the statistic for the
+    observed data, but it is "unfair" when computing the statistic for other
+    samples, such as those we randomly draw to form the Monte Carlo null
+    distribution. It is easy to correct for this: whenever we compute the KS
+    statistic of a sample, we use the CDF of a normal distribution fitted
+    to *that sample*. The null distribution in this case has not been
+    calculated exactly and is tyically approximated using Monte Carlo methods
+    as described above. This is where `goodness_of_fit` excels.
+
+    >>> res = stats.goodness_of_fit(stats.norm, x, statistic='ks',
+    ...                             rng=rng)
+    >>> res.statistic, res.pvalue
+    (0.1119257570456813, 0.0196)
+
+    Indeed, this p-value is much smaller, and small enough to (correctly)
+    reject the null hypothesis at common significance levels, including 5% and
+    2.5%.
+
+    However, the KS statistic is not very sensitive to all deviations from
+    normality. The original advantage of the KS statistic was the ability
+    to compute the null distribution theoretically, but a more sensitive
+    statistic - resulting in a higher test power - can be used now that we can
+    approximate the null distribution
+    computationally. The Anderson-Darling statistic [1]_ tends to be more
+    sensitive, and critical values of the this statistic have been tabulated
+    for various significance levels and sample sizes using Monte Carlo methods.
+
+    >>> res = stats.anderson(x, 'norm')
+    >>> print(res.statistic)
+    1.2139573337497467
+    >>> print(res.critical_values)
+    [0.549 0.625 0.75  0.875 1.041]
+    >>> print(res.significance_level)
+    [15.  10.   5.   2.5  1. ]
+
+    Here, the observed value of the statistic exceeds the critical value
+    corresponding with a 1% significance level. This tells us that the p-value
+    of the observed data is less than 1%, but what is it? We could interpolate
+    from these (already-interpolated) values, but `goodness_of_fit` can
+    estimate it directly.
+
+    >>> res = stats.goodness_of_fit(stats.norm, x, statistic='ad',
+    ...                             rng=rng)
+    >>> res.statistic, res.pvalue
+    (1.2139573337497467, 0.0034)
+
+    A further advantage is that use of `goodness_of_fit` is not limited to
+    a particular set of distributions or conditions on which parameters
+    are known versus which must be estimated from data. Instead,
+    `goodness_of_fit` can estimate p-values relatively quickly for any
+    distribution with a sufficiently fast and reliable ``fit`` method. For
+    instance, here we perform a goodness of fit test using the Cramer-von Mises
+    statistic against the Rayleigh distribution with known location and unknown
+    scale.
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.chi(df=2.2, loc=0, scale=2).rvs(size=1000, random_state=rng)
+    >>> res = stats.goodness_of_fit(stats.rayleigh, x, statistic='cvm',
+    ...                             known_params={'loc': 0}, rng=rng)
+
+    This executes fairly quickly, but to check the reliability of the ``fit``
+    method, we should inspect the fit result.
+
+    >>> res.fit_result  # location is as specified, and scale is reasonable
+      params: FitParams(loc=0.0, scale=2.1026719844231243)
+     success: True
+     message: 'The fit was performed successfully.'
+    >>> import matplotlib.pyplot as plt  # matplotlib must be installed to plot
+    >>> res.fit_result.plot()
+    >>> plt.show()
+
+    If the distribution is not fit to the observed data as well as possible,
+    the test may not control the type I error rate, that is, the chance of
+    rejecting the null hypothesis even when it is true.
+
+    We should also look for extreme outliers in the null distribution that
+    may be caused by unreliable fitting. These do not necessarily invalidate
+    the result, but they tend to reduce the test's power.
+
+    >>> _, ax = plt.subplots()
+    >>> ax.hist(np.log10(res.null_distribution))
+    >>> ax.set_xlabel("log10 of CVM statistic under the null hypothesis")
+    >>> ax.set_ylabel("Frequency")
+    >>> ax.set_title("Histogram of the Monte Carlo null distribution")
+    >>> plt.show()
+
+    This plot seems reassuring.
+
+    If ``fit`` method is working reliably, and if the distribution of the test
+    statistic is not particularly sensitive to the values of the fitted
+    parameters, then the p-value provided by `goodness_of_fit` is expected to
+    be a good approximation.
+
+    >>> res.statistic, res.pvalue
+    (0.2231991510248692, 0.0525)
+
+    """
+    args = _gof_iv(dist, data, known_params, fit_params, guessed_params,
+                   statistic, n_mc_samples, rng)
+    (dist, data, fixed_nhd_params, fixed_rfd_params, guessed_nhd_params,
+     guessed_rfd_params, statistic, n_mc_samples_int, rng) = args
+
+    # Fit null hypothesis distribution to data
+    nhd_fit_fun = _get_fit_fun(dist, data, guessed_nhd_params,
+                               fixed_nhd_params)
+    nhd_vals = nhd_fit_fun(data)
+    nhd_dist = dist(*nhd_vals)
+
+    def rvs(size):
+        return nhd_dist.rvs(size=size, random_state=rng)
+
+    # Define statistic
+    fit_fun = _get_fit_fun(dist, data, guessed_rfd_params, fixed_rfd_params)
+    if callable(statistic):
+        compare_fun = statistic
+    else:
+        compare_fun = _compare_dict[statistic]
+    alternative = getattr(compare_fun, 'alternative', 'greater')
+
+    def statistic_fun(data, axis):
+        # Make things simple by always working along the last axis.
+        data = np.moveaxis(data, axis, -1)
+        rfd_vals = fit_fun(data)
+        rfd_dist = dist(*rfd_vals)
+        return compare_fun(rfd_dist, data, axis=-1)
+
+    res = stats.monte_carlo_test(data, rvs, statistic_fun, vectorized=True,
+                                 n_resamples=n_mc_samples, axis=-1,
+                                 alternative=alternative)
+    opt_res = optimize.OptimizeResult()
+    opt_res.success = True
+    opt_res.message = "The fit was performed successfully."
+    opt_res.x = nhd_vals
+    # Only continuous distributions for now, hence discrete=False
+    # There's no fundamental limitation; it's just that we're not using
+    # stats.fit, discrete distributions don't have `fit` method, and
+    # we haven't written any vectorized fit functions for a discrete
+    # distribution yet.
+    return GoodnessOfFitResult(FitResult(dist, data, False, opt_res),
+                               res.statistic, res.pvalue,
+                               res.null_distribution)
+
+
+def _get_fit_fun(dist, data, guessed_params, fixed_params):
+
+    shape_names = [] if dist.shapes is None else dist.shapes.split(", ")
+    param_names = shape_names + ['loc', 'scale']
+    fparam_names = ['f'+name for name in param_names]
+    all_fixed = not set(fparam_names).difference(fixed_params)
+    guessed_shapes = [guessed_params.pop(x, None)
+                      for x in shape_names if x in guessed_params]
+
+    if all_fixed:
+        def fit_fun(data):
+            return [fixed_params[name] for name in fparam_names]
+    # Define statistic, including fitting distribution to data
+    elif dist in _fit_funs:
+        def fit_fun(data):
+            params = _fit_funs[dist](data, **fixed_params)
+            params = np.asarray(np.broadcast_arrays(*params))
+            if params.ndim > 1:
+                params = params[..., np.newaxis]
+            return params
+    else:
+        def fit_fun_1d(data):
+            return dist.fit(data, *guessed_shapes, **guessed_params,
+                            **fixed_params)
+
+        def fit_fun(data):
+            params = np.apply_along_axis(fit_fun_1d, axis=-1, arr=data)
+            if params.ndim > 1:
+                params = params.T[..., np.newaxis]
+            return params
+
+    return fit_fun
+
+
+# Vectorized fitting functions. These are to accept ND `data` in which each
+# row (slice along last axis) is a sample to fit and scalar fixed parameters.
+# They return a tuple of shape parameter arrays, each of shape data.shape[:-1].
+def _fit_norm(data, floc=None, fscale=None):
+    loc = floc
+    scale = fscale
+    if loc is None and scale is None:
+        loc = np.mean(data, axis=-1)
+        scale = np.std(data, ddof=1, axis=-1)
+    elif loc is None:
+        loc = np.mean(data, axis=-1)
+    elif scale is None:
+        scale = np.sqrt(((data - loc)**2).mean(axis=-1))
+    return loc, scale
+
+
+_fit_funs = {stats.norm: _fit_norm}  # type: ignore[attr-defined]
+
+
+# Vectorized goodness of fit statistic functions. These accept a frozen
+# distribution object and `data` in which each row (slice along last axis) is
+# a sample.
+
+
+def _anderson_darling(dist, data, axis):
+    x = np.sort(data, axis=-1)
+    n = data.shape[-1]
+    i = np.arange(1, n+1)
+    Si = (2*i - 1)/n * (dist.logcdf(x) + dist.logsf(x[..., ::-1]))
+    S = np.sum(Si, axis=-1)
+    return -n - S
+
+
+def _compute_dplus(cdfvals):  # adapted from _stats_py before gh-17062
+    n = cdfvals.shape[-1]
+    return (np.arange(1.0, n + 1) / n - cdfvals).max(axis=-1)
+
+
+def _compute_dminus(cdfvals):
+    n = cdfvals.shape[-1]
+    return (cdfvals - np.arange(0.0, n)/n).max(axis=-1)
+
+
+def _kolmogorov_smirnov(dist, data, axis=-1):
+    x = np.sort(data, axis=axis)
+    cdfvals = dist.cdf(x)
+    cdfvals = np.moveaxis(cdfvals, axis, -1)
+    Dplus = _compute_dplus(cdfvals)  # always works along last axis
+    Dminus = _compute_dminus(cdfvals)
+    return np.maximum(Dplus, Dminus)
+
+
+def _corr(X, M):
+    # Correlation coefficient r, simplified and vectorized as we need it.
+    # See [7] Equation (2). Lemma 1/2 are only for distributions symmetric
+    # about 0.
+    Xm = X.mean(axis=-1, keepdims=True)
+    Mm = M.mean(axis=-1, keepdims=True)
+    num = np.sum((X - Xm) * (M - Mm), axis=-1)
+    den = np.sqrt(np.sum((X - Xm)**2, axis=-1) * np.sum((M - Mm)**2, axis=-1))
+    return num/den
+
+
+def _filliben(dist, data, axis):
+    # [7] Section 8 # 1
+    X = np.sort(data, axis=-1)
+
+    # [7] Section 8 # 2
+    n = data.shape[-1]
+    k = np.arange(1, n+1)
+    # Filliben used an approximation for the uniform distribution order
+    # statistic medians.
+    # m = (k - .3175)/(n + 0.365)
+    # m[-1] = 0.5**(1/n)
+    # m[0] = 1 - m[-1]
+    # We can just as easily use the (theoretically) exact values. See e.g.
+    # https://en.wikipedia.org/wiki/Order_statistic
+    # "Order statistics sampled from a uniform distribution"
+    m = stats.beta(k, n + 1 - k).median()
+
+    # [7] Section 8 # 3
+    M = dist.ppf(m)
+
+    # [7] Section 8 # 4
+    return _corr(X, M)
+_filliben.alternative = 'less'  # type: ignore[attr-defined]
+
+
+def _cramer_von_mises(dist, data, axis):
+    x = np.sort(data, axis=-1)
+    n = data.shape[-1]
+    cdfvals = dist.cdf(x)
+    u = (2*np.arange(1, n+1) - 1)/(2*n)
+    w = 1 / (12*n) + np.sum((u - cdfvals)**2, axis=-1)
+    return w
+
+
+_compare_dict = {"ad": _anderson_darling, "ks": _kolmogorov_smirnov,
+                 "cvm": _cramer_von_mises, "filliben": _filliben}
+
+
+def _gof_iv(dist, data, known_params, fit_params, guessed_params, statistic,
+            n_mc_samples, rng):
+
+    if not isinstance(dist, stats.rv_continuous):
+        message = ("`dist` must be a (non-frozen) instance of "
+                   "`stats.rv_continuous`.")
+        raise TypeError(message)
+
+    data = np.asarray(data, dtype=float)
+    if not data.ndim == 1:
+        message = "`data` must be a one-dimensional array of numbers."
+        raise ValueError(message)
+
+    # Leave validation of these key/value pairs to the `fit` method,
+    # but collect these into dictionaries that will be used
+    known_params = known_params or dict()
+    fit_params = fit_params or dict()
+    guessed_params = guessed_params or dict()
+
+    known_params_f = {("f"+key): val for key, val in known_params.items()}
+    fit_params_f = {("f"+key): val for key, val in fit_params.items()}
+
+    # These are the values of parameters of the null distribution family
+    # with which resamples are drawn
+    fixed_nhd_params = known_params_f.copy()
+    fixed_nhd_params.update(fit_params_f)
+
+    # These are fixed when fitting the distribution family to resamples
+    fixed_rfd_params = known_params_f.copy()
+
+    # These are used as guesses when fitting the distribution family to
+    # the original data
+    guessed_nhd_params = guessed_params.copy()
+
+    # These are used as guesses when fitting the distribution family to
+    # resamples
+    guessed_rfd_params = fit_params.copy()
+    guessed_rfd_params.update(guessed_params)
+
+    if not callable(statistic):
+        statistic = statistic.lower()
+        statistics = {'ad', 'ks', 'cvm', 'filliben'}
+        if statistic not in statistics:
+            message = f"`statistic` must be one of {statistics}."
+            raise ValueError(message)
+
+    n_mc_samples_int = int(n_mc_samples)
+    if n_mc_samples_int != n_mc_samples:
+        message = "`n_mc_samples` must be an integer."
+        raise TypeError(message)
+
+    rng = check_random_state(rng)
+
+    return (dist, data, fixed_nhd_params, fixed_rfd_params, guessed_nhd_params,
+            guessed_rfd_params, statistic, n_mc_samples_int, rng)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_hypotests.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_hypotests.py
new file mode 100644
index 0000000000000000000000000000000000000000..3764b96bdcacd38c44cda9aa841103f8cff67a0b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_hypotests.py
@@ -0,0 +1,2027 @@
+from collections import namedtuple
+from dataclasses import dataclass
+from math import comb
+import numpy as np
+import warnings
+from itertools import combinations
+import scipy.stats
+from scipy.optimize import shgo
+from . import distributions
+from ._common import ConfidenceInterval
+from ._continuous_distns import norm
+from scipy.special import gamma, kv, gammaln
+from scipy.fft import ifft
+from ._stats_pythran import _a_ij_Aij_Dij2
+from ._stats_pythran import (
+    _concordant_pairs as _P, _discordant_pairs as _Q
+)
+from ._axis_nan_policy import _axis_nan_policy_factory
+from scipy.stats import _stats_py
+
+__all__ = ['epps_singleton_2samp', 'cramervonmises', 'somersd',
+           'barnard_exact', 'boschloo_exact', 'cramervonmises_2samp',
+           'tukey_hsd', 'poisson_means_test']
+
+Epps_Singleton_2sampResult = namedtuple('Epps_Singleton_2sampResult',
+                                        ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(Epps_Singleton_2sampResult, n_samples=2, too_small=4)
+def epps_singleton_2samp(x, y, t=(0.4, 0.8)):
+    """Compute the Epps-Singleton (ES) test statistic.
+
+    Test the null hypothesis that two samples have the same underlying
+    probability distribution.
+
+    Parameters
+    ----------
+    x, y : array-like
+        The two samples of observations to be tested. Input must not have more
+        than one dimension. Samples can have different lengths, but both
+        must have at least five observations.
+    t : array-like, optional
+        The points (t1, ..., tn) where the empirical characteristic function is
+        to be evaluated. It should be positive distinct numbers. The default
+        value (0.4, 0.8) is proposed in [1]_. Input must not have more than
+        one dimension.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    pvalue : float
+        The associated p-value based on the asymptotic chi2-distribution.
+
+    See Also
+    --------
+    ks_2samp, anderson_ksamp
+
+    Notes
+    -----
+    Testing whether two samples are generated by the same underlying
+    distribution is a classical question in statistics. A widely used test is
+    the Kolmogorov-Smirnov (KS) test which relies on the empirical
+    distribution function. Epps and Singleton introduce a test based on the
+    empirical characteristic function in [1]_.
+
+    One advantage of the ES test compared to the KS test is that is does
+    not assume a continuous distribution. In [1]_, the authors conclude
+    that the test also has a higher power than the KS test in many
+    examples. They recommend the use of the ES test for discrete samples as
+    well as continuous samples with at least 25 observations each, whereas
+    `anderson_ksamp` is recommended for smaller sample sizes in the
+    continuous case.
+
+    The p-value is computed from the asymptotic distribution of the test
+    statistic which follows a `chi2` distribution. If the sample size of both
+    `x` and `y` is below 25, the small sample correction proposed in [1]_ is
+    applied to the test statistic.
+
+    The default values of `t` are determined in [1]_ by considering
+    various distributions and finding good values that lead to a high power
+    of the test in general. Table III in [1]_ gives the optimal values for
+    the distributions tested in that study. The values of `t` are scaled by
+    the semi-interquartile range in the implementation, see [1]_.
+
+    References
+    ----------
+    .. [1] T. W. Epps and K. J. Singleton, "An omnibus test for the two-sample
+       problem using the empirical characteristic function", Journal of
+       Statistical Computation and Simulation 26, p. 177--203, 1986.
+
+    .. [2] S. J. Goerg and J. Kaiser, "Nonparametric testing of distributions
+       - the Epps-Singleton two-sample test using the empirical characteristic
+       function", The Stata Journal 9(3), p. 454--465, 2009.
+
+    """
+    # x and y are converted to arrays by the decorator
+    t = np.asarray(t)
+    # check if x and y are valid inputs
+    nx, ny = len(x), len(y)
+    if (nx < 5) or (ny < 5):
+        raise ValueError('x and y should have at least 5 elements, but len(x) '
+                         f'= {nx} and len(y) = {ny}.')
+    if not np.isfinite(x).all():
+        raise ValueError('x must not contain nonfinite values.')
+    if not np.isfinite(y).all():
+        raise ValueError('y must not contain nonfinite values.')
+    n = nx + ny
+
+    # check if t is valid
+    if t.ndim > 1:
+        raise ValueError(f't must be 1d, but t.ndim equals {t.ndim}.')
+    if np.less_equal(t, 0).any():
+        raise ValueError('t must contain positive elements only.')
+
+    # rescale t with semi-iqr as proposed in [1]; import iqr here to avoid
+    # circular import
+    from scipy.stats import iqr
+    sigma = iqr(np.hstack((x, y))) / 2
+    ts = np.reshape(t, (-1, 1)) / sigma
+
+    # covariance estimation of ES test
+    gx = np.vstack((np.cos(ts*x), np.sin(ts*x))).T  # shape = (nx, 2*len(t))
+    gy = np.vstack((np.cos(ts*y), np.sin(ts*y))).T
+    cov_x = np.cov(gx.T, bias=True)  # the test uses biased cov-estimate
+    cov_y = np.cov(gy.T, bias=True)
+    est_cov = (n/nx)*cov_x + (n/ny)*cov_y
+    est_cov_inv = np.linalg.pinv(est_cov)
+    r = np.linalg.matrix_rank(est_cov_inv)
+    if r < 2*len(t):
+        warnings.warn('Estimated covariance matrix does not have full rank. '
+                      'This indicates a bad choice of the input t and the '
+                      'test might not be consistent.', # see p. 183 in [1]_
+                      stacklevel=2)
+
+    # compute test statistic w distributed asympt. as chisquare with df=r
+    g_diff = np.mean(gx, axis=0) - np.mean(gy, axis=0)
+    w = n*np.dot(g_diff.T, np.dot(est_cov_inv, g_diff))
+
+    # apply small-sample correction
+    if (max(nx, ny) < 25):
+        corr = 1.0/(1.0 + n**(-0.45) + 10.1*(nx**(-1.7) + ny**(-1.7)))
+        w = corr * w
+
+    chi2 = _stats_py._SimpleChi2(r)
+    p = _stats_py._get_pvalue(w, chi2, alternative='greater', symmetric=False, xp=np)
+
+    return Epps_Singleton_2sampResult(w, p)
+
+
+def poisson_means_test(k1, n1, k2, n2, *, diff=0, alternative='two-sided'):
+    r"""
+    Performs the Poisson means test, AKA the "E-test".
+
+    This is a test of the null hypothesis that the difference between means of
+    two Poisson distributions is `diff`. The samples are provided as the
+    number of events `k1` and `k2` observed within measurement intervals
+    (e.g. of time, space, number of observations) of sizes `n1` and `n2`.
+
+    Parameters
+    ----------
+    k1 : int
+        Number of events observed from distribution 1.
+    n1: float
+        Size of sample from distribution 1.
+    k2 : int
+        Number of events observed from distribution 2.
+    n2 : float
+        Size of sample from distribution 2.
+    diff : float, default=0
+        The hypothesized difference in means between the distributions
+        underlying the samples.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+          * 'two-sided': the difference between distribution means is not
+            equal to `diff`
+          * 'less': the difference between distribution means is less than
+            `diff`
+          * 'greater': the difference between distribution means is greater
+            than `diff`
+
+    Returns
+    -------
+    statistic : float
+        The test statistic (see [1]_ equation 3.3).
+    pvalue : float
+        The probability of achieving such an extreme value of the test
+        statistic under the null hypothesis.
+
+    Notes
+    -----
+
+    Let:
+
+    .. math:: X_1 \sim \mbox{Poisson}(\mathtt{n1}\lambda_1)
+
+    be a random variable independent of
+
+    .. math:: X_2  \sim \mbox{Poisson}(\mathtt{n2}\lambda_2)
+
+    and let ``k1`` and ``k2`` be the observed values of :math:`X_1`
+    and :math:`X_2`, respectively. Then `poisson_means_test` uses the number
+    of observed events ``k1`` and ``k2`` from samples of size ``n1`` and
+    ``n2``, respectively, to test the null hypothesis that
+
+    .. math::
+       H_0: \lambda_1 - \lambda_2 = \mathtt{diff}
+
+    A benefit of the E-test is that it has good power for small sample sizes,
+    which can reduce sampling costs [1]_. It has been evaluated and determined
+    to be more powerful than the comparable C-test, sometimes referred to as
+    the Poisson exact test.
+
+    References
+    ----------
+    .. [1]  Krishnamoorthy, K., & Thomson, J. (2004). A more powerful test for
+       comparing two Poisson means. Journal of Statistical Planning and
+       Inference, 119(1), 23-35.
+
+    .. [2]  Przyborowski, J., & Wilenski, H. (1940). Homogeneity of results in
+       testing samples from Poisson series: With an application to testing
+       clover seed for dodder. Biometrika, 31(3/4), 313-323.
+
+    Examples
+    --------
+
+    Suppose that a gardener wishes to test the number of dodder (weed) seeds
+    in a sack of clover seeds that they buy from a seed company. It has
+    previously been established that the number of dodder seeds in clover
+    follows the Poisson distribution.
+
+    A 100 gram sample is drawn from the sack before being shipped to the
+    gardener. The sample is analyzed, and it is found to contain no dodder
+    seeds; that is, `k1` is 0. However, upon arrival, the gardener draws
+    another 100 gram sample from the sack. This time, three dodder seeds are
+    found in the sample; that is, `k2` is 3. The gardener would like to
+    know if the difference is significant and not due to chance. The
+    null hypothesis is that the difference between the two samples is merely
+    due to chance, or that :math:`\lambda_1 - \lambda_2 = \mathtt{diff}`
+    where :math:`\mathtt{diff} = 0`. The alternative hypothesis is that the
+    difference is not due to chance, or :math:`\lambda_1 - \lambda_2 \ne 0`.
+    The gardener selects a significance level of 5% to reject the null
+    hypothesis in favor of the alternative [2]_.
+
+    >>> import scipy.stats as stats
+    >>> res = stats.poisson_means_test(0, 100, 3, 100)
+    >>> res.statistic, res.pvalue
+    (-1.7320508075688772, 0.08837900929018157)
+
+    The p-value is .088, indicating a near 9% chance of observing a value of
+    the test statistic under the null hypothesis. This exceeds 5%, so the
+    gardener does not reject the null hypothesis as the difference cannot be
+    regarded as significant at this level.
+    """
+
+    _poisson_means_test_iv(k1, n1, k2, n2, diff, alternative)
+
+    # "for a given k_1 and k_2, an estimate of \lambda_2 is given by" [1] (3.4)
+    lmbd_hat2 = ((k1 + k2) / (n1 + n2) - diff * n1 / (n1 + n2))
+
+    # "\hat{\lambda_{2k}} may be less than or equal to zero ... and in this
+    # case the null hypothesis cannot be rejected ... [and] it is not necessary
+    # to compute the p-value". [1] page 26 below eq. (3.6).
+    if lmbd_hat2 <= 0:
+        return _stats_py.SignificanceResult(0, 1)
+
+    # The unbiased variance estimate [1] (3.2)
+    var = k1 / (n1 ** 2) + k2 / (n2 ** 2)
+
+    # The _observed_ pivot statistic from the input. It follows the
+    # unnumbered equation following equation (3.3) This is used later in
+    # comparison with the computed pivot statistics in an indicator function.
+    t_k1k2 = (k1 / n1 - k2 / n2 - diff) / np.sqrt(var)
+
+    # Equation (3.5) of [1] is lengthy, so it is broken into several parts,
+    # beginning here. Note that the probability mass function of poisson is
+    # exp^(-\mu)*\mu^k/k!, so and this is called with shape \mu, here noted
+    # here as nlmbd_hat*. The strategy for evaluating the double summation in
+    # (3.5) is to create two arrays of the values of the two products inside
+    # the summation and then broadcast them together into a matrix, and then
+    # sum across the entire matrix.
+
+    # Compute constants (as seen in the first and second separated products in
+    # (3.5).). (This is the shape (\mu) parameter of the poisson distribution.)
+    nlmbd_hat1 = n1 * (lmbd_hat2 + diff)
+    nlmbd_hat2 = n2 * lmbd_hat2
+
+    # Determine summation bounds for tail ends of distribution rather than
+    # summing to infinity. `x1*` is for the outer sum and `x2*` is the inner
+    # sum.
+    x1_lb, x1_ub = distributions.poisson.ppf([1e-10, 1 - 1e-16], nlmbd_hat1)
+    x2_lb, x2_ub = distributions.poisson.ppf([1e-10, 1 - 1e-16], nlmbd_hat2)
+
+    # Construct arrays to function as the x_1 and x_2 counters on the summation
+    # in (3.5). `x1` is in columns and `x2` is in rows to allow for
+    # broadcasting.
+    x1 = np.arange(x1_lb, x1_ub + 1)
+    x2 = np.arange(x2_lb, x2_ub + 1)[:, None]
+
+    # These are the two products in equation (3.5) with `prob_x1` being the
+    # first (left side) and `prob_x2` being the second (right side). (To
+    # make as clear as possible: the 1st contains a "+ d" term, the 2nd does
+    # not.)
+    prob_x1 = distributions.poisson.pmf(x1, nlmbd_hat1)
+    prob_x2 = distributions.poisson.pmf(x2, nlmbd_hat2)
+
+    # compute constants for use in the "pivot statistic" per the
+    # unnumbered equation following (3.3).
+    lmbd_x1 = x1 / n1
+    lmbd_x2 = x2 / n2
+    lmbds_diff = lmbd_x1 - lmbd_x2 - diff
+    var_x1x2 = lmbd_x1 / n1 + lmbd_x2 / n2
+
+    # This is the 'pivot statistic' for use in the indicator of the summation
+    # (left side of "I[.]").
+    with np.errstate(invalid='ignore', divide='ignore'):
+        t_x1x2 = lmbds_diff / np.sqrt(var_x1x2)
+
+    # `[indicator]` implements the "I[.] ... the indicator function" per
+    # the paragraph following equation (3.5).
+    if alternative == 'two-sided':
+        indicator = np.abs(t_x1x2) >= np.abs(t_k1k2)
+    elif alternative == 'less':
+        indicator = t_x1x2 <= t_k1k2
+    else:
+        indicator = t_x1x2 >= t_k1k2
+
+    # Multiply all combinations of the products together, exclude terms
+    # based on the `indicator` and then sum. (3.5)
+    pvalue = np.sum((prob_x1 * prob_x2)[indicator])
+    return _stats_py.SignificanceResult(t_k1k2, pvalue)
+
+
+def _poisson_means_test_iv(k1, n1, k2, n2, diff, alternative):
+    # """check for valid types and values of input to `poisson_mean_test`."""
+    if k1 != int(k1) or k2 != int(k2):
+        raise TypeError('`k1` and `k2` must be integers.')
+
+    count_err = '`k1` and `k2` must be greater than or equal to 0.'
+    if k1 < 0 or k2 < 0:
+        raise ValueError(count_err)
+
+    if n1 <= 0 or n2 <= 0:
+        raise ValueError('`n1` and `n2` must be greater than 0.')
+
+    if diff < 0:
+        raise ValueError('diff must be greater than or equal to 0.')
+
+    alternatives = {'two-sided', 'less', 'greater'}
+    if alternative.lower() not in alternatives:
+        raise ValueError(f"Alternative must be one of '{alternatives}'.")
+
+
+class CramerVonMisesResult:
+    def __init__(self, statistic, pvalue):
+        self.statistic = statistic
+        self.pvalue = pvalue
+
+    def __repr__(self):
+        return (f"{self.__class__.__name__}(statistic={self.statistic}, "
+                f"pvalue={self.pvalue})")
+
+
+def _psi1_mod(x):
+    """
+    psi1 is defined in equation 1.10 in Csörgő, S. and Faraway, J. (1996).
+    This implements a modified version by excluding the term V(x) / 12
+    (here: _cdf_cvm_inf(x) / 12) to avoid evaluating _cdf_cvm_inf(x)
+    twice in _cdf_cvm.
+
+    Implementation based on MAPLE code of Julian Faraway and R code of the
+    function pCvM in the package goftest (v1.1.1), permission granted
+    by Adrian Baddeley. Main difference in the implementation: the code
+    here keeps adding terms of the series until the terms are small enough.
+    """
+
+    def _ed2(y):
+        z = y**2 / 4
+        b = kv(1/4, z) + kv(3/4, z)
+        return np.exp(-z) * (y/2)**(3/2) * b / np.sqrt(np.pi)
+
+    def _ed3(y):
+        z = y**2 / 4
+        c = np.exp(-z) / np.sqrt(np.pi)
+        return c * (y/2)**(5/2) * (2*kv(1/4, z) + 3*kv(3/4, z) - kv(5/4, z))
+
+    def _Ak(k, x):
+        m = 2*k + 1
+        sx = 2 * np.sqrt(x)
+        y1 = x**(3/4)
+        y2 = x**(5/4)
+
+        e1 = m * gamma(k + 1/2) * _ed2((4 * k + 3)/sx) / (9 * y1)
+        e2 = gamma(k + 1/2) * _ed3((4 * k + 1) / sx) / (72 * y2)
+        e3 = 2 * (m + 2) * gamma(k + 3/2) * _ed3((4 * k + 5) / sx) / (12 * y2)
+        e4 = 7 * m * gamma(k + 1/2) * _ed2((4 * k + 1) / sx) / (144 * y1)
+        e5 = 7 * m * gamma(k + 1/2) * _ed2((4 * k + 5) / sx) / (144 * y1)
+
+        return e1 + e2 + e3 + e4 + e5
+
+    x = np.asarray(x)
+    tot = np.zeros_like(x, dtype='float')
+    cond = np.ones_like(x, dtype='bool')
+    k = 0
+    while np.any(cond):
+        z = -_Ak(k, x[cond]) / (np.pi * gamma(k + 1))
+        tot[cond] = tot[cond] + z
+        cond[cond] = np.abs(z) >= 1e-7
+        k += 1
+
+    return tot
+
+
+def _cdf_cvm_inf(x):
+    """
+    Calculate the cdf of the Cramér-von Mises statistic (infinite sample size).
+
+    See equation 1.2 in Csörgő, S. and Faraway, J. (1996).
+
+    Implementation based on MAPLE code of Julian Faraway and R code of the
+    function pCvM in the package goftest (v1.1.1), permission granted
+    by Adrian Baddeley. Main difference in the implementation: the code
+    here keeps adding terms of the series until the terms are small enough.
+
+    The function is not expected to be accurate for large values of x, say
+    x > 4, when the cdf is very close to 1.
+    """
+    x = np.asarray(x)
+
+    def term(x, k):
+        # this expression can be found in [2], second line of (1.3)
+        u = np.exp(gammaln(k + 0.5) - gammaln(k+1)) / (np.pi**1.5 * np.sqrt(x))
+        y = 4*k + 1
+        q = y**2 / (16*x)
+        b = kv(0.25, q)
+        return u * np.sqrt(y) * np.exp(-q) * b
+
+    tot = np.zeros_like(x, dtype='float')
+    cond = np.ones_like(x, dtype='bool')
+    k = 0
+    while np.any(cond):
+        z = term(x[cond], k)
+        tot[cond] = tot[cond] + z
+        cond[cond] = np.abs(z) >= 1e-7
+        k += 1
+
+    return tot
+
+
+def _cdf_cvm(x, n=None):
+    """
+    Calculate the cdf of the Cramér-von Mises statistic for a finite sample
+    size n. If N is None, use the asymptotic cdf (n=inf).
+
+    See equation 1.8 in Csörgő, S. and Faraway, J. (1996) for finite samples,
+    1.2 for the asymptotic cdf.
+
+    The function is not expected to be accurate for large values of x, say
+    x > 2, when the cdf is very close to 1 and it might return values > 1
+    in that case, e.g. _cdf_cvm(2.0, 12) = 1.0000027556716846. Moreover, it
+    is not accurate for small values of n, especially close to the bounds of
+    the distribution's domain, [1/(12*n), n/3], where the value jumps to 0
+    and 1, respectively. These are limitations of the approximation by Csörgő
+    and Faraway (1996) implemented in this function.
+    """
+    x = np.asarray(x)
+    if n is None:
+        y = _cdf_cvm_inf(x)
+    else:
+        # support of the test statistic is [12/n, n/3], see 1.1 in [2]
+        y = np.zeros_like(x, dtype='float')
+        sup = (1./(12*n) < x) & (x < n/3.)
+        # note: _psi1_mod does not include the term _cdf_cvm_inf(x) / 12
+        # therefore, we need to add it here
+        y[sup] = _cdf_cvm_inf(x[sup]) * (1 + 1./(12*n)) + _psi1_mod(x[sup]) / n
+        y[x >= n/3] = 1
+
+    if y.ndim == 0:
+        return y[()]
+    return y
+
+
+def _cvm_result_to_tuple(res):
+    return res.statistic, res.pvalue
+
+
+@_axis_nan_policy_factory(CramerVonMisesResult, n_samples=1, too_small=1,
+                          result_to_tuple=_cvm_result_to_tuple)
+def cramervonmises(rvs, cdf, args=()):
+    """Perform the one-sample Cramér-von Mises test for goodness of fit.
+
+    This performs a test of the goodness of fit of a cumulative distribution
+    function (cdf) :math:`F` compared to the empirical distribution function
+    :math:`F_n` of observed random variates :math:`X_1, ..., X_n` that are
+    assumed to be independent and identically distributed ([1]_).
+    The null hypothesis is that the :math:`X_i` have cumulative distribution
+    :math:`F`.
+
+    Parameters
+    ----------
+    rvs : array_like
+        A 1-D array of observed values of the random variables :math:`X_i`.
+        The sample must contain at least two observations.
+    cdf : str or callable
+        The cumulative distribution function :math:`F` to test the
+        observations against. If a string, it should be the name of a
+        distribution in `scipy.stats`. If a callable, that callable is used
+        to calculate the cdf: ``cdf(x, *args) -> float``.
+    args : tuple, optional
+        Distribution parameters. These are assumed to be known; see Notes.
+
+    Returns
+    -------
+    res : object with attributes
+        statistic : float
+            Cramér-von Mises statistic.
+        pvalue : float
+            The p-value.
+
+    See Also
+    --------
+    kstest, cramervonmises_2samp
+
+    Notes
+    -----
+    .. versionadded:: 1.6.0
+
+    The p-value relies on the approximation given by equation 1.8 in [2]_.
+    It is important to keep in mind that the p-value is only accurate if
+    one tests a simple hypothesis, i.e. the parameters of the reference
+    distribution are known. If the parameters are estimated from the data
+    (composite hypothesis), the computed p-value is not reliable.
+
+    References
+    ----------
+    .. [1] Cramér-von Mises criterion, Wikipedia,
+           https://en.wikipedia.org/wiki/Cram%C3%A9r%E2%80%93von_Mises_criterion
+    .. [2] Csörgő, S. and Faraway, J. (1996). The Exact and Asymptotic
+           Distribution of Cramér-von Mises Statistics. Journal of the
+           Royal Statistical Society, pp. 221-234.
+
+    Examples
+    --------
+
+    Suppose we wish to test whether data generated by ``scipy.stats.norm.rvs``
+    were, in fact, drawn from the standard normal distribution. We choose a
+    significance level of ``alpha=0.05``.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(165417232101553420507139617764912913465)
+    >>> x = stats.norm.rvs(size=500, random_state=rng)
+    >>> res = stats.cramervonmises(x, 'norm')
+    >>> res.statistic, res.pvalue
+    (0.1072085112565724, 0.5508482238203407)
+
+    The p-value exceeds our chosen significance level, so we do not
+    reject the null hypothesis that the observed sample is drawn from the
+    standard normal distribution.
+
+    Now suppose we wish to check whether the same samples shifted by 2.1 is
+    consistent with being drawn from a normal distribution with a mean of 2.
+
+    >>> y = x + 2.1
+    >>> res = stats.cramervonmises(y, 'norm', args=(2,))
+    >>> res.statistic, res.pvalue
+    (0.8364446265294695, 0.00596286797008283)
+
+    Here we have used the `args` keyword to specify the mean (``loc``)
+    of the normal distribution to test the data against. This is equivalent
+    to the following, in which we create a frozen normal distribution with
+    mean 2.1, then pass its ``cdf`` method as an argument.
+
+    >>> frozen_dist = stats.norm(loc=2)
+    >>> res = stats.cramervonmises(y, frozen_dist.cdf)
+    >>> res.statistic, res.pvalue
+    (0.8364446265294695, 0.00596286797008283)
+
+    In either case, we would reject the null hypothesis that the observed
+    sample is drawn from a normal distribution with a mean of 2 (and default
+    variance of 1) because the p-value is less than our chosen
+    significance level.
+
+    """
+    if isinstance(cdf, str):
+        cdf = getattr(distributions, cdf).cdf
+
+    vals = np.sort(np.asarray(rvs))
+
+    if vals.size <= 1:
+        raise ValueError('The sample must contain at least two observations.')
+
+    n = len(vals)
+    cdfvals = cdf(vals, *args)
+
+    u = (2*np.arange(1, n+1) - 1)/(2*n)
+    w = 1/(12*n) + np.sum((u - cdfvals)**2)
+
+    # avoid small negative values that can occur due to the approximation
+    p = np.clip(1. - _cdf_cvm(w, n), 0., None)
+
+    return CramerVonMisesResult(statistic=w, pvalue=p)
+
+
+def _get_wilcoxon_distr(n):
+    """
+    Distribution of probability of the Wilcoxon ranksum statistic r_plus (sum
+    of ranks of positive differences).
+    Returns an array with the probabilities of all the possible ranks
+    r = 0, ..., n*(n+1)/2
+    """
+    c = np.ones(1, dtype=np.float64)
+    for k in range(1, n + 1):
+        prev_c = c
+        c = np.zeros(k * (k + 1) // 2 + 1, dtype=np.float64)
+        m = len(prev_c)
+        c[:m] = prev_c * 0.5
+        c[-m:] += prev_c * 0.5
+    return c
+
+
+def _get_wilcoxon_distr2(n):
+    """
+    Distribution of probability of the Wilcoxon ranksum statistic r_plus (sum
+    of ranks of positive differences).
+    Returns an array with the probabilities of all the possible ranks
+    r = 0, ..., n*(n+1)/2
+    This is a slower reference function
+    References
+    ----------
+    .. [1] 1. Harris T, Hardin JW. Exact Wilcoxon Signed-Rank and Wilcoxon
+        Mann-Whitney Ranksum Tests. The Stata Journal. 2013;13(2):337-343.
+    """
+    ai = np.arange(1, n+1)[:, None]
+    t = n*(n+1)/2
+    q = 2*t
+    j = np.arange(q)
+    theta = 2*np.pi/q*j
+    phi_sp = np.prod(np.cos(theta*ai), axis=0)
+    phi_s = np.exp(1j*theta*t) * phi_sp
+    p = np.real(ifft(phi_s))
+    res = np.zeros(int(t)+1)
+    res[:-1:] = p[::2]
+    res[0] /= 2
+    res[-1] = res[0]
+    return res
+
+
+def _tau_b(A):
+    """Calculate Kendall's tau-b and p-value from contingency table."""
+    # See [2] 2.2 and 4.2
+
+    # contingency table must be truly 2D
+    if A.shape[0] == 1 or A.shape[1] == 1:
+        return np.nan, np.nan
+
+    NA = A.sum()
+    PA = _P(A)
+    QA = _Q(A)
+    Sri2 = (A.sum(axis=1)**2).sum()
+    Scj2 = (A.sum(axis=0)**2).sum()
+    denominator = (NA**2 - Sri2)*(NA**2 - Scj2)
+
+    tau = (PA-QA)/(denominator)**0.5
+
+    numerator = 4*(_a_ij_Aij_Dij2(A) - (PA - QA)**2 / NA)
+    s02_tau_b = numerator/denominator
+    if s02_tau_b == 0:  # Avoid divide by zero
+        return tau, 0
+    Z = tau/s02_tau_b**0.5
+    p = 2*norm.sf(abs(Z))  # 2-sided p-value
+
+    return tau, p
+
+
+def _somers_d(A, alternative='two-sided'):
+    """Calculate Somers' D and p-value from contingency table."""
+    # See [3] page 1740
+
+    # contingency table must be truly 2D
+    if A.shape[0] <= 1 or A.shape[1] <= 1:
+        return np.nan, np.nan
+
+    NA = A.sum()
+    NA2 = NA**2
+    PA = _P(A)
+    QA = _Q(A)
+    Sri2 = (A.sum(axis=1)**2).sum()
+
+    d = (PA - QA)/(NA2 - Sri2)
+
+    S = _a_ij_Aij_Dij2(A) - (PA-QA)**2/NA
+
+    with np.errstate(divide='ignore'):
+        Z = (PA - QA)/(4*(S))**0.5
+
+    norm = _stats_py._SimpleNormal()
+    p = _stats_py._get_pvalue(Z, norm, alternative, xp=np)
+
+    return d, p
+
+
+@dataclass
+class SomersDResult:
+    statistic: float
+    pvalue: float
+    table: np.ndarray
+
+
+def somersd(x, y=None, alternative='two-sided'):
+    r"""Calculates Somers' D, an asymmetric measure of ordinal association.
+
+    Like Kendall's :math:`\tau`, Somers' :math:`D` is a measure of the
+    correspondence between two rankings. Both statistics consider the
+    difference between the number of concordant and discordant pairs in two
+    rankings :math:`X` and :math:`Y`, and both are normalized such that values
+    close  to 1 indicate strong agreement and values close to -1 indicate
+    strong disagreement. They differ in how they are normalized. To show the
+    relationship, Somers' :math:`D` can be defined in terms of Kendall's
+    :math:`\tau_a`:
+
+    .. math::
+        D(Y|X) = \frac{\tau_a(X, Y)}{\tau_a(X, X)}
+
+    Suppose the first ranking :math:`X` has :math:`r` distinct ranks and the
+    second ranking :math:`Y` has :math:`s` distinct ranks. These two lists of
+    :math:`n` rankings can also be viewed as an :math:`r \times s` contingency
+    table in which element :math:`i, j` is the number of rank pairs with rank
+    :math:`i` in ranking :math:`X` and rank :math:`j` in ranking :math:`Y`.
+    Accordingly, `somersd` also allows the input data to be supplied as a
+    single, 2D contingency table instead of as two separate, 1D rankings.
+
+    Note that the definition of Somers' :math:`D` is asymmetric: in general,
+    :math:`D(Y|X) \neq D(X|Y)`. ``somersd(x, y)`` calculates Somers'
+    :math:`D(Y|X)`: the "row" variable :math:`X` is treated as an independent
+    variable, and the "column" variable :math:`Y` is dependent. For Somers'
+    :math:`D(X|Y)`, swap the input lists or transpose the input table.
+
+    Parameters
+    ----------
+    x : array_like
+        1D array of rankings, treated as the (row) independent variable.
+        Alternatively, a 2D contingency table.
+    y : array_like, optional
+        If `x` is a 1D array of rankings, `y` is a 1D array of rankings of the
+        same length, treated as the (column) dependent variable.
+        If `x` is 2D, `y` is ignored.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+        * 'two-sided': the rank correlation is nonzero
+        * 'less': the rank correlation is negative (less than zero)
+        * 'greater':  the rank correlation is positive (greater than zero)
+
+    Returns
+    -------
+    res : SomersDResult
+        A `SomersDResult` object with the following fields:
+
+            statistic : float
+               The Somers' :math:`D` statistic.
+            pvalue : float
+               The p-value for a hypothesis test whose null
+               hypothesis is an absence of association, :math:`D=0`.
+               See notes for more information.
+            table : 2D array
+               The contingency table formed from rankings `x` and `y` (or the
+               provided contingency table, if `x` is a 2D array)
+
+    See Also
+    --------
+    kendalltau : Calculates Kendall's tau, another correlation measure.
+    weightedtau : Computes a weighted version of Kendall's tau.
+    spearmanr : Calculates a Spearman rank-order correlation coefficient.
+    pearsonr : Calculates a Pearson correlation coefficient.
+
+    Notes
+    -----
+    This function follows the contingency table approach of [2]_ and
+    [3]_. *p*-values are computed based on an asymptotic approximation of
+    the test statistic distribution under the null hypothesis :math:`D=0`.
+
+    Theoretically, hypothesis tests based on Kendall's :math:`tau` and Somers'
+    :math:`D` should be identical.
+    However, the *p*-values returned by `kendalltau` are based
+    on the null hypothesis of *independence* between :math:`X` and :math:`Y`
+    (i.e. the population from which pairs in :math:`X` and :math:`Y` are
+    sampled contains equal numbers of all possible pairs), which is more
+    specific than the null hypothesis :math:`D=0` used here. If the null
+    hypothesis of independence is desired, it is acceptable to use the
+    *p*-value returned by `kendalltau` with the statistic returned by
+    `somersd` and vice versa. For more information, see [2]_.
+
+    Contingency tables are formatted according to the convention used by
+    SAS and R: the first ranking supplied (``x``) is the "row" variable, and
+    the second ranking supplied (``y``) is the "column" variable. This is
+    opposite the convention of Somers' original paper [1]_.
+
+    References
+    ----------
+    .. [1] Robert H. Somers, "A New Asymmetric Measure of Association for
+           Ordinal Variables", *American Sociological Review*, Vol. 27, No. 6,
+           pp. 799--811, 1962.
+
+    .. [2] Morton B. Brown and Jacqueline K. Benedetti, "Sampling Behavior of
+           Tests for Correlation in Two-Way Contingency Tables", *Journal of
+           the American Statistical Association* Vol. 72, No. 358, pp.
+           309--315, 1977.
+
+    .. [3] SAS Institute, Inc., "The FREQ Procedure (Book Excerpt)",
+           *SAS/STAT 9.2 User's Guide, Second Edition*, SAS Publishing, 2009.
+
+    .. [4] Laerd Statistics, "Somers' d using SPSS Statistics", *SPSS
+           Statistics Tutorials and Statistical Guides*,
+           https://statistics.laerd.com/spss-tutorials/somers-d-using-spss-statistics.php,
+           Accessed July 31, 2020.
+
+    Examples
+    --------
+    We calculate Somers' D for the example given in [4]_, in which a hotel
+    chain owner seeks to determine the association between hotel room
+    cleanliness and customer satisfaction. The independent variable, hotel
+    room cleanliness, is ranked on an ordinal scale: "below average (1)",
+    "average (2)", or "above average (3)". The dependent variable, customer
+    satisfaction, is ranked on a second scale: "very dissatisfied (1)",
+    "moderately dissatisfied (2)", "neither dissatisfied nor satisfied (3)",
+    "moderately satisfied (4)", or "very satisfied (5)". 189 customers
+    respond to the survey, and the results are cast into a contingency table
+    with the hotel room cleanliness as the "row" variable and customer
+    satisfaction as the "column" variable.
+
+    +-----+-----+-----+-----+-----+-----+
+    |     | (1) | (2) | (3) | (4) | (5) |
+    +=====+=====+=====+=====+=====+=====+
+    | (1) | 27  | 25  | 14  | 7   | 0   |
+    +-----+-----+-----+-----+-----+-----+
+    | (2) | 7   | 14  | 18  | 35  | 12  |
+    +-----+-----+-----+-----+-----+-----+
+    | (3) | 1   | 3   | 2   | 7   | 17  |
+    +-----+-----+-----+-----+-----+-----+
+
+    For example, 27 customers assigned their room a cleanliness ranking of
+    "below average (1)" and a corresponding satisfaction of "very
+    dissatisfied (1)". We perform the analysis as follows.
+
+    >>> from scipy.stats import somersd
+    >>> table = [[27, 25, 14, 7, 0], [7, 14, 18, 35, 12], [1, 3, 2, 7, 17]]
+    >>> res = somersd(table)
+    >>> res.statistic
+    0.6032766111513396
+    >>> res.pvalue
+    1.0007091191074533e-27
+
+    The value of the Somers' D statistic is approximately 0.6, indicating
+    a positive correlation between room cleanliness and customer satisfaction
+    in the sample.
+    The *p*-value is very small, indicating a very small probability of
+    observing such an extreme value of the statistic under the null
+    hypothesis that the statistic of the entire population (from which
+    our sample of 189 customers is drawn) is zero. This supports the
+    alternative hypothesis that the true value of Somers' D for the population
+    is nonzero.
+
+    """
+    x, y = np.array(x), np.array(y)
+    if x.ndim == 1:
+        if x.size != y.size:
+            raise ValueError("Rankings must be of equal length.")
+        table = scipy.stats.contingency.crosstab(x, y)[1]
+    elif x.ndim == 2:
+        if np.any(x < 0):
+            raise ValueError("All elements of the contingency table must be "
+                             "non-negative.")
+        if np.any(x != x.astype(int)):
+            raise ValueError("All elements of the contingency table must be "
+                             "integer.")
+        if x.nonzero()[0].size < 2:
+            raise ValueError("At least two elements of the contingency table "
+                             "must be nonzero.")
+        table = x
+    else:
+        raise ValueError("x must be either a 1D or 2D array")
+    # The table type is converted to a float to avoid an integer overflow
+    d, p = _somers_d(table.astype(float), alternative)
+
+    # add alias for consistency with other correlation functions
+    res = SomersDResult(d, p, table)
+    res.correlation = d
+    return res
+
+
+# This could be combined with `_all_partitions` in `_resampling.py`
+def _all_partitions(nx, ny):
+    """
+    Partition a set of indices into two fixed-length sets in all possible ways
+
+    Partition a set of indices 0 ... nx + ny - 1 into two sets of length nx and
+    ny in all possible ways (ignoring order of elements).
+    """
+    z = np.arange(nx+ny)
+    for c in combinations(z, nx):
+        x = np.array(c)
+        mask = np.ones(nx+ny, bool)
+        mask[x] = False
+        y = z[mask]
+        yield x, y
+
+
+def _compute_log_combinations(n):
+    """Compute all log combination of C(n, k)."""
+    gammaln_arr = gammaln(np.arange(n + 1) + 1)
+    return gammaln(n + 1) - gammaln_arr - gammaln_arr[::-1]
+
+
+@dataclass
+class BarnardExactResult:
+    statistic: float
+    pvalue: float
+
+
+def barnard_exact(table, alternative="two-sided", pooled=True, n=32):
+    r"""Perform a Barnard exact test on a 2x2 contingency table.
+
+    Parameters
+    ----------
+    table : array_like of ints
+        A 2x2 contingency table.  Elements should be non-negative integers.
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes section below.
+
+    pooled : bool, optional
+        Whether to compute score statistic with pooled variance (as in
+        Student's t-test, for example) or unpooled variance (as in Welch's
+        t-test). Default is ``True``.
+
+    n : int, optional
+        Number of sampling points used in the construction of the sampling
+        method. Note that this argument will automatically be converted to
+        the next higher power of 2 since `scipy.stats.qmc.Sobol` is used to
+        select sample points. Default is 32. Must be positive. In most cases,
+        32 points is enough to reach good precision. More points comes at
+        performance cost.
+
+    Returns
+    -------
+    ber : BarnardExactResult
+        A result object with the following attributes.
+
+        statistic : float
+            The Wald statistic with pooled or unpooled variance, depending
+            on the user choice of `pooled`.
+
+        pvalue : float
+            P-value, the probability of obtaining a distribution at least as
+            extreme as the one that was actually observed, assuming that the
+            null hypothesis is true.
+
+    See Also
+    --------
+    chi2_contingency : Chi-square test of independence of variables in a
+        contingency table.
+    fisher_exact : Fisher exact test on a 2x2 contingency table.
+    boschloo_exact : Boschloo's exact test on a 2x2 contingency table,
+        which is an uniformly more powerful alternative to Fisher's exact test.
+
+    Notes
+    -----
+    Barnard's test is an exact test used in the analysis of contingency
+    tables. It examines the association of two categorical variables, and
+    is a more powerful alternative than Fisher's exact test
+    for 2x2 contingency tables.
+
+    Let's define :math:`X_0` a 2x2 matrix representing the observed sample,
+    where each column stores the binomial experiment, as in the example
+    below. Let's also define :math:`p_1, p_2` the theoretical binomial
+    probabilities for  :math:`x_{11}` and :math:`x_{12}`. When using
+    Barnard exact test, we can assert three different null hypotheses :
+
+    - :math:`H_0 : p_1 \geq p_2` versus :math:`H_1 : p_1 < p_2`,
+      with `alternative` = "less"
+
+    - :math:`H_0 : p_1 \leq p_2` versus :math:`H_1 : p_1 > p_2`,
+      with `alternative` = "greater"
+
+    - :math:`H_0 : p_1 = p_2` versus :math:`H_1 : p_1 \neq p_2`,
+      with `alternative` = "two-sided" (default one)
+
+    In order to compute Barnard's exact test, we are using the Wald
+    statistic [3]_ with pooled or unpooled variance.
+    Under the default assumption that both variances are equal
+    (``pooled = True``), the statistic is computed as:
+
+    .. math::
+
+        T(X) = \frac{
+            \hat{p}_1 - \hat{p}_2
+        }{
+            \sqrt{
+                \hat{p}(1 - \hat{p})
+                (\frac{1}{c_1} +
+                \frac{1}{c_2})
+            }
+        }
+
+    with :math:`\hat{p}_1, \hat{p}_2` and :math:`\hat{p}` the estimator of
+    :math:`p_1, p_2` and :math:`p`, the latter being the combined probability,
+    given the assumption that :math:`p_1 = p_2`.
+
+    If this assumption is invalid (``pooled = False``), the statistic is:
+
+    .. math::
+
+        T(X) = \frac{
+            \hat{p}_1 - \hat{p}_2
+        }{
+            \sqrt{
+                \frac{\hat{p}_1 (1 - \hat{p}_1)}{c_1} +
+                \frac{\hat{p}_2 (1 - \hat{p}_2)}{c_2}
+            }
+        }
+
+    The p-value is then computed as:
+
+    .. math::
+
+        \sum
+            \binom{c_1}{x_{11}}
+            \binom{c_2}{x_{12}}
+            \pi^{x_{11} + x_{12}}
+            (1 - \pi)^{t - x_{11} - x_{12}}
+
+    where the sum is over all  2x2 contingency tables :math:`X` such that:
+    * :math:`T(X) \leq T(X_0)` when `alternative` = "less",
+    * :math:`T(X) \geq T(X_0)` when `alternative` = "greater", or
+    * :math:`T(X) \geq |T(X_0)|` when `alternative` = "two-sided".
+    Above, :math:`c_1, c_2` are the sum of the columns 1 and 2,
+    and :math:`t` the total (sum of the 4 sample's element).
+
+    The returned p-value is the maximum p-value taken over the nuisance
+    parameter :math:`\pi`, where :math:`0 \leq \pi \leq 1`.
+
+    This function's complexity is :math:`O(n c_1 c_2)`, where `n` is the
+    number of sample points.
+
+    References
+    ----------
+    .. [1] Barnard, G. A. "Significance Tests for 2x2 Tables". *Biometrika*.
+           34.1/2 (1947): 123-138. :doi:`dpgkg3`
+
+    .. [2] Mehta, Cyrus R., and Pralay Senchaudhuri. "Conditional versus
+           unconditional exact tests for comparing two binomials."
+           *Cytel Software Corporation* 675 (2003): 1-5.
+
+    .. [3] "Wald Test". *Wikipedia*. https://en.wikipedia.org/wiki/Wald_test
+
+    Examples
+    --------
+    An example use of Barnard's test is presented in [2]_.
+
+        Consider the following example of a vaccine efficacy study
+        (Chan, 1998). In a randomized clinical trial of 30 subjects, 15 were
+        inoculated with a recombinant DNA influenza vaccine and the 15 were
+        inoculated with a placebo. Twelve of the 15 subjects in the placebo
+        group (80%) eventually became infected with influenza whereas for the
+        vaccine group, only 7 of the 15 subjects (47%) became infected. The
+        data are tabulated as a 2 x 2 table::
+
+                Vaccine  Placebo
+            Yes     7        12
+            No      8        3
+
+    When working with statistical hypothesis testing, we usually use a
+    threshold probability or significance level upon which we decide
+    to reject the null hypothesis :math:`H_0`. Suppose we choose the common
+    significance level of 5%.
+
+    Our alternative hypothesis is that the vaccine will lower the chance of
+    becoming infected with the virus; that is, the probability :math:`p_1` of
+    catching the virus with the vaccine will be *less than* the probability
+    :math:`p_2` of catching the virus without the vaccine.  Therefore, we call
+    `barnard_exact` with the ``alternative="less"`` option:
+
+    >>> import scipy.stats as stats
+    >>> res = stats.barnard_exact([[7, 12], [8, 3]], alternative="less")
+    >>> res.statistic
+    -1.894
+    >>> res.pvalue
+    0.03407
+
+    Under the null hypothesis that the vaccine will not lower the chance of
+    becoming infected, the probability of obtaining test results at least as
+    extreme as the observed data is approximately 3.4%. Since this p-value is
+    less than our chosen significance level, we have evidence to reject
+    :math:`H_0` in favor of the alternative.
+
+    Suppose we had used Fisher's exact test instead:
+
+    >>> _, pvalue = stats.fisher_exact([[7, 12], [8, 3]], alternative="less")
+    >>> pvalue
+    0.0640
+
+    With the same threshold significance of 5%, we would not have been able
+    to reject the null hypothesis in favor of the alternative. As stated in
+    [2]_, Barnard's test is uniformly more powerful than Fisher's exact test
+    because Barnard's test does not condition on any margin. Fisher's test
+    should only be used when both sets of marginals are fixed.
+
+    """
+    if n <= 0:
+        raise ValueError(
+            "Number of points `n` must be strictly positive, "
+            f"found {n!r}"
+        )
+
+    table = np.asarray(table, dtype=np.int64)
+
+    if not table.shape == (2, 2):
+        raise ValueError("The input `table` must be of shape (2, 2).")
+
+    if np.any(table < 0):
+        raise ValueError("All values in `table` must be nonnegative.")
+
+    if 0 in table.sum(axis=0):
+        # If both values in column are zero, the p-value is 1 and
+        # the score's statistic is NaN.
+        return BarnardExactResult(np.nan, 1.0)
+
+    total_col_1, total_col_2 = table.sum(axis=0)
+
+    x1 = np.arange(total_col_1 + 1, dtype=np.int64).reshape(-1, 1)
+    x2 = np.arange(total_col_2 + 1, dtype=np.int64).reshape(1, -1)
+
+    # We need to calculate the wald statistics for each combination of x1 and
+    # x2.
+    p1, p2 = x1 / total_col_1, x2 / total_col_2
+
+    if pooled:
+        p = (x1 + x2) / (total_col_1 + total_col_2)
+        variances = p * (1 - p) * (1 / total_col_1 + 1 / total_col_2)
+    else:
+        variances = p1 * (1 - p1) / total_col_1 + p2 * (1 - p2) / total_col_2
+
+    # To avoid warning when dividing by 0
+    with np.errstate(divide="ignore", invalid="ignore"):
+        wald_statistic = np.divide((p1 - p2), np.sqrt(variances))
+
+    wald_statistic[p1 == p2] = 0  # Removing NaN values
+
+    wald_stat_obs = wald_statistic[table[0, 0], table[0, 1]]
+
+    if alternative == "two-sided":
+        index_arr = np.abs(wald_statistic) >= abs(wald_stat_obs)
+    elif alternative == "less":
+        index_arr = wald_statistic <= wald_stat_obs
+    elif alternative == "greater":
+        index_arr = wald_statistic >= wald_stat_obs
+    else:
+        msg = (
+            "`alternative` should be one of {'two-sided', 'less', 'greater'},"
+            f" found {alternative!r}"
+        )
+        raise ValueError(msg)
+
+    x1_sum_x2 = x1 + x2
+
+    x1_log_comb = _compute_log_combinations(total_col_1)
+    x2_log_comb = _compute_log_combinations(total_col_2)
+    x1_sum_x2_log_comb = x1_log_comb[x1] + x2_log_comb[x2]
+
+    result = shgo(
+        _get_binomial_log_p_value_with_nuisance_param,
+        args=(x1_sum_x2, x1_sum_x2_log_comb, index_arr),
+        bounds=((0, 1),),
+        n=n,
+        sampling_method="sobol",
+    )
+
+    # result.fun is the negative log pvalue and therefore needs to be
+    # changed before return
+    p_value = np.clip(np.exp(-result.fun), a_min=0, a_max=1)
+    return BarnardExactResult(wald_stat_obs, p_value)
+
+
+@dataclass
+class BoschlooExactResult:
+    statistic: float
+    pvalue: float
+
+
+def boschloo_exact(table, alternative="two-sided", n=32):
+    r"""Perform Boschloo's exact test on a 2x2 contingency table.
+
+    Parameters
+    ----------
+    table : array_like of ints
+        A 2x2 contingency table.  Elements should be non-negative integers.
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes section below.
+
+    n : int, optional
+        Number of sampling points used in the construction of the sampling
+        method. Note that this argument will automatically be converted to
+        the next higher power of 2 since `scipy.stats.qmc.Sobol` is used to
+        select sample points. Default is 32. Must be positive. In most cases,
+        32 points is enough to reach good precision. More points comes at
+        performance cost.
+
+    Returns
+    -------
+    ber : BoschlooExactResult
+        A result object with the following attributes.
+
+        statistic : float
+            The statistic used in Boschloo's test; that is, the p-value
+            from Fisher's exact test.
+
+        pvalue : float
+            P-value, the probability of obtaining a distribution at least as
+            extreme as the one that was actually observed, assuming that the
+            null hypothesis is true.
+
+    See Also
+    --------
+    chi2_contingency : Chi-square test of independence of variables in a
+        contingency table.
+    fisher_exact : Fisher exact test on a 2x2 contingency table.
+    barnard_exact : Barnard's exact test, which is a more powerful alternative
+        than Fisher's exact test for 2x2 contingency tables.
+
+    Notes
+    -----
+    Boschloo's test is an exact test used in the analysis of contingency
+    tables. It examines the association of two categorical variables, and
+    is a uniformly more powerful alternative to Fisher's exact test
+    for 2x2 contingency tables.
+
+    Boschloo's exact test uses the p-value of Fisher's exact test as a
+    statistic, and Boschloo's p-value is the probability under the null
+    hypothesis of observing such an extreme value of this statistic.
+
+    Let's define :math:`X_0` a 2x2 matrix representing the observed sample,
+    where each column stores the binomial experiment, as in the example
+    below. Let's also define :math:`p_1, p_2` the theoretical binomial
+    probabilities for  :math:`x_{11}` and :math:`x_{12}`. When using
+    Boschloo exact test, we can assert three different alternative hypotheses:
+
+    - :math:`H_0 : p_1=p_2` versus :math:`H_1 : p_1 < p_2`,
+      with `alternative` = "less"
+
+    - :math:`H_0 : p_1=p_2` versus :math:`H_1 : p_1 > p_2`,
+      with `alternative` = "greater"
+
+    - :math:`H_0 : p_1=p_2` versus :math:`H_1 : p_1 \neq p_2`,
+      with `alternative` = "two-sided" (default)
+
+    There are multiple conventions for computing a two-sided p-value when the
+    null distribution is asymmetric. Here, we apply the convention that the
+    p-value of a two-sided test is twice the minimum of the p-values of the
+    one-sided tests (clipped to 1.0). Note that `fisher_exact` follows a
+    different convention, so for a given `table`, the statistic reported by
+    `boschloo_exact` may differ from the p-value reported by `fisher_exact`
+    when ``alternative='two-sided'``.
+
+    .. versionadded:: 1.7.0
+
+    References
+    ----------
+    .. [1] R.D. Boschloo. "Raised conditional level of significance for the
+       2 x 2-table when testing the equality of two probabilities",
+       Statistica Neerlandica, 24(1), 1970
+
+    .. [2] "Boschloo's test", Wikipedia,
+       https://en.wikipedia.org/wiki/Boschloo%27s_test
+
+    .. [3] Lise M. Saari et al. "Employee attitudes and job satisfaction",
+       Human Resource Management, 43(4), 395-407, 2004,
+       :doi:`10.1002/hrm.20032`.
+
+    Examples
+    --------
+    In the following example, we consider the article "Employee
+    attitudes and job satisfaction" [3]_
+    which reports the results of a survey from 63 scientists and 117 college
+    professors. Of the 63 scientists, 31 said they were very satisfied with
+    their jobs, whereas 74 of the college professors were very satisfied
+    with their work. Is this significant evidence that college
+    professors are happier with their work than scientists?
+    The following table summarizes the data mentioned above::
+
+                         college professors   scientists
+        Very Satisfied   74                     31
+        Dissatisfied     43                     32
+
+    When working with statistical hypothesis testing, we usually use a
+    threshold probability or significance level upon which we decide
+    to reject the null hypothesis :math:`H_0`. Suppose we choose the common
+    significance level of 5%.
+
+    Our alternative hypothesis is that college professors are truly more
+    satisfied with their work than scientists. Therefore, we expect
+    :math:`p_1` the proportion of very satisfied college professors to be
+    greater than :math:`p_2`, the proportion of very satisfied scientists.
+    We thus call `boschloo_exact` with the ``alternative="greater"`` option:
+
+    >>> import scipy.stats as stats
+    >>> res = stats.boschloo_exact([[74, 31], [43, 32]], alternative="greater")
+    >>> res.statistic
+    0.0483
+    >>> res.pvalue
+    0.0355
+
+    Under the null hypothesis that scientists are happier in their work than
+    college professors, the probability of obtaining test
+    results at least as extreme as the observed data is approximately 3.55%.
+    Since this p-value is less than our chosen significance level, we have
+    evidence to reject :math:`H_0` in favor of the alternative hypothesis.
+
+    """
+    hypergeom = distributions.hypergeom
+
+    if n <= 0:
+        raise ValueError(
+            "Number of points `n` must be strictly positive,"
+            f" found {n!r}"
+        )
+
+    table = np.asarray(table, dtype=np.int64)
+
+    if not table.shape == (2, 2):
+        raise ValueError("The input `table` must be of shape (2, 2).")
+
+    if np.any(table < 0):
+        raise ValueError("All values in `table` must be nonnegative.")
+
+    if 0 in table.sum(axis=0):
+        # If both values in column are zero, the p-value is 1 and
+        # the score's statistic is NaN.
+        return BoschlooExactResult(np.nan, np.nan)
+
+    total_col_1, total_col_2 = table.sum(axis=0)
+    total = total_col_1 + total_col_2
+    x1 = np.arange(total_col_1 + 1, dtype=np.int64).reshape(1, -1)
+    x2 = np.arange(total_col_2 + 1, dtype=np.int64).reshape(-1, 1)
+    x1_sum_x2 = x1 + x2
+
+    if alternative == 'less':
+        pvalues = hypergeom.cdf(x1, total, x1_sum_x2, total_col_1).T
+    elif alternative == 'greater':
+        # Same formula as the 'less' case, but with the second column.
+        pvalues = hypergeom.cdf(x2, total, x1_sum_x2, total_col_2).T
+    elif alternative == 'two-sided':
+        boschloo_less = boschloo_exact(table, alternative="less", n=n)
+        boschloo_greater = boschloo_exact(table, alternative="greater", n=n)
+
+        res = (
+            boschloo_less if boschloo_less.pvalue < boschloo_greater.pvalue
+            else boschloo_greater
+        )
+
+        # Two-sided p-value is defined as twice the minimum of the one-sided
+        # p-values
+        pvalue = np.clip(2 * res.pvalue, a_min=0, a_max=1)
+        return BoschlooExactResult(res.statistic, pvalue)
+    else:
+        msg = (
+            f"`alternative` should be one of {'two-sided', 'less', 'greater'},"
+            f" found {alternative!r}"
+        )
+        raise ValueError(msg)
+
+    fisher_stat = pvalues[table[0, 0], table[0, 1]]
+
+    # fisher_stat * (1+1e-13) guards us from small numerical error. It is
+    # equivalent to np.isclose with relative tol of 1e-13 and absolute tol of 0
+    # For more throughout explanations, see gh-14178
+    index_arr = pvalues <= fisher_stat * (1+1e-13)
+
+    x1, x2, x1_sum_x2 = x1.T, x2.T, x1_sum_x2.T
+    x1_log_comb = _compute_log_combinations(total_col_1)
+    x2_log_comb = _compute_log_combinations(total_col_2)
+    x1_sum_x2_log_comb = x1_log_comb[x1] + x2_log_comb[x2]
+
+    result = shgo(
+        _get_binomial_log_p_value_with_nuisance_param,
+        args=(x1_sum_x2, x1_sum_x2_log_comb, index_arr),
+        bounds=((0, 1),),
+        n=n,
+        sampling_method="sobol",
+    )
+
+    # result.fun is the negative log pvalue and therefore needs to be
+    # changed before return
+    p_value = np.clip(np.exp(-result.fun), a_min=0, a_max=1)
+    return BoschlooExactResult(fisher_stat, p_value)
+
+
+def _get_binomial_log_p_value_with_nuisance_param(
+    nuisance_param, x1_sum_x2, x1_sum_x2_log_comb, index_arr
+):
+    r"""
+    Compute the log pvalue in respect of a nuisance parameter considering
+    a 2x2 sample space.
+
+    Parameters
+    ----------
+    nuisance_param : float
+        nuisance parameter used in the computation of the maximisation of
+        the p-value. Must be between 0 and 1
+
+    x1_sum_x2 : ndarray
+        Sum of x1 and x2 inside barnard_exact
+
+    x1_sum_x2_log_comb : ndarray
+        sum of the log combination of x1 and x2
+
+    index_arr : ndarray of boolean
+
+    Returns
+    -------
+    p_value : float
+        Return the maximum p-value considering every nuisance parameter
+        between 0 and 1
+
+    Notes
+    -----
+
+    Both Barnard's test and Boschloo's test iterate over a nuisance parameter
+    :math:`\pi \in [0, 1]` to find the maximum p-value. To search this
+    maxima, this function return the negative log pvalue with respect to the
+    nuisance parameter passed in params. This negative log p-value is then
+    used in `shgo` to find the minimum negative pvalue which is our maximum
+    pvalue.
+
+    Also, to compute the different combination used in the
+    p-values' computation formula, this function uses `gammaln` which is
+    more tolerant for large value than `scipy.special.comb`. `gammaln` gives
+    a log combination. For the little precision loss, performances are
+    improved a lot.
+    """
+    t1, t2 = x1_sum_x2.shape
+    n = t1 + t2 - 2
+    with np.errstate(divide="ignore", invalid="ignore"):
+        log_nuisance = np.log(
+            nuisance_param,
+            out=np.zeros_like(nuisance_param),
+            where=nuisance_param >= 0,
+        )
+        log_1_minus_nuisance = np.log(
+            1 - nuisance_param,
+            out=np.zeros_like(nuisance_param),
+            where=1 - nuisance_param >= 0,
+        )
+
+        nuisance_power_x1_x2 = log_nuisance * x1_sum_x2
+        nuisance_power_x1_x2[(x1_sum_x2 == 0)[:, :]] = 0
+
+        nuisance_power_n_minus_x1_x2 = log_1_minus_nuisance * (n - x1_sum_x2)
+        nuisance_power_n_minus_x1_x2[(x1_sum_x2 == n)[:, :]] = 0
+
+        tmp_log_values_arr = (
+            x1_sum_x2_log_comb
+            + nuisance_power_x1_x2
+            + nuisance_power_n_minus_x1_x2
+        )
+
+    tmp_values_from_index = tmp_log_values_arr[index_arr]
+
+    # To avoid dividing by zero in log function and getting inf value,
+    # values are centered according to the max
+    max_value = tmp_values_from_index.max()
+
+    # To have better result's precision, the log pvalue is taken here.
+    # Indeed, pvalue is included inside [0, 1] interval. Passing the
+    # pvalue to log makes the interval a lot bigger ([-inf, 0]), and thus
+    # help us to achieve better precision
+    with np.errstate(divide="ignore", invalid="ignore"):
+        log_probs = np.exp(tmp_values_from_index - max_value).sum()
+        log_pvalue = max_value + np.log(
+            log_probs,
+            out=np.full_like(log_probs, -np.inf),
+            where=log_probs > 0,
+        )
+
+    # Since shgo find the minima, minus log pvalue is returned
+    return -log_pvalue
+
+
+def _pval_cvm_2samp_exact(s, m, n):
+    """
+    Compute the exact p-value of the Cramer-von Mises two-sample test
+    for a given value s of the test statistic.
+    m and n are the sizes of the samples.
+
+    [1] Y. Xiao, A. Gordon, and A. Yakovlev, "A C++ Program for
+        the Cramér-Von Mises Two-Sample Test", J. Stat. Soft.,
+        vol. 17, no. 8, pp. 1-15, Dec. 2006.
+    [2] T. W. Anderson "On the Distribution of the Two-Sample Cramer-von Mises
+        Criterion," The Annals of Mathematical Statistics, Ann. Math. Statist.
+        33(3), 1148-1159, (September, 1962)
+    """
+
+    # [1, p. 3]
+    lcm = np.lcm(m, n)
+    # [1, p. 4], below eq. 3
+    a = lcm // m
+    b = lcm // n
+    # Combine Eq. 9 in [2] with Eq. 2 in [1] and solve for $\zeta$
+    # Hint: `s` is $U$ in [2], and $T_2$ in [1] is $T$ in [2]
+    mn = m * n
+    zeta = lcm ** 2 * (m + n) * (6 * s - mn * (4 * mn - 1)) // (6 * mn ** 2)
+
+    # bound maximum value that may appear in `gs` (remember both rows!)
+    zeta_bound = lcm**2 * (m + n)  # bound elements in row 1
+    combinations = comb(m + n, m)  # sum of row 2
+    max_gs = max(zeta_bound, combinations)
+    dtype = np.min_scalar_type(max_gs)
+
+    # the frequency table of $g_{u, v}^+$ defined in [1, p. 6]
+    gs = ([np.array([[0], [1]], dtype=dtype)]
+          + [np.empty((2, 0), dtype=dtype) for _ in range(m)])
+    for u in range(n + 1):
+        next_gs = []
+        tmp = np.empty((2, 0), dtype=dtype)
+        for v, g in enumerate(gs):
+            # Calculate g recursively with eq. 11 in [1]. Even though it
+            # doesn't look like it, this also does 12/13 (all of Algorithm 1).
+            vi, i0, i1 = np.intersect1d(tmp[0], g[0], return_indices=True)
+            tmp = np.concatenate([
+                np.stack([vi, tmp[1, i0] + g[1, i1]]),
+                np.delete(tmp, i0, 1),
+                np.delete(g, i1, 1)
+            ], 1)
+            res = (a * v - b * u) ** 2
+            tmp[0] += res.astype(dtype)
+            next_gs.append(tmp)
+        gs = next_gs
+    value, freq = gs[m]
+    return np.float64(np.sum(freq[value >= zeta]) / combinations)
+
+
+@_axis_nan_policy_factory(CramerVonMisesResult, n_samples=2, too_small=1,
+                          result_to_tuple=_cvm_result_to_tuple)
+def cramervonmises_2samp(x, y, method='auto'):
+    """Perform the two-sample Cramér-von Mises test for goodness of fit.
+
+    This is the two-sample version of the Cramér-von Mises test ([1]_):
+    for two independent samples :math:`X_1, ..., X_n` and
+    :math:`Y_1, ..., Y_m`, the null hypothesis is that the samples
+    come from the same (unspecified) continuous distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        A 1-D array of observed values of the random variables :math:`X_i`.
+        Must contain at least two observations.
+    y : array_like
+        A 1-D array of observed values of the random variables :math:`Y_i`.
+        Must contain at least two observations.
+    method : {'auto', 'asymptotic', 'exact'}, optional
+        The method used to compute the p-value, see Notes for details.
+        The default is 'auto'.
+
+    Returns
+    -------
+    res : object with attributes
+        statistic : float
+            Cramér-von Mises statistic.
+        pvalue : float
+            The p-value.
+
+    See Also
+    --------
+    cramervonmises, anderson_ksamp, epps_singleton_2samp, ks_2samp
+
+    Notes
+    -----
+    .. versionadded:: 1.7.0
+
+    The statistic is computed according to equation 9 in [2]_. The
+    calculation of the p-value depends on the keyword `method`:
+
+    - ``asymptotic``: The p-value is approximated by using the limiting
+      distribution of the test statistic.
+    - ``exact``: The exact p-value is computed by enumerating all
+      possible combinations of the test statistic, see [2]_.
+
+    If ``method='auto'``, the exact approach is used
+    if both samples contain equal to or less than 20 observations,
+    otherwise the asymptotic distribution is used.
+
+    If the underlying distribution is not continuous, the p-value is likely to
+    be conservative (Section 6.2 in [3]_). When ranking the data to compute
+    the test statistic, midranks are used if there are ties.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Cramer-von_Mises_criterion
+    .. [2] Anderson, T.W. (1962). On the distribution of the two-sample
+           Cramer-von-Mises criterion. The Annals of Mathematical
+           Statistics, pp. 1148-1159.
+    .. [3] Conover, W.J., Practical Nonparametric Statistics, 1971.
+
+    Examples
+    --------
+
+    Suppose we wish to test whether two samples generated by
+    ``scipy.stats.norm.rvs`` have the same distribution. We choose a
+    significance level of alpha=0.05.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = stats.norm.rvs(size=100, random_state=rng)
+    >>> y = stats.norm.rvs(size=70, random_state=rng)
+    >>> res = stats.cramervonmises_2samp(x, y)
+    >>> res.statistic, res.pvalue
+    (0.29376470588235293, 0.1412873014573014)
+
+    The p-value exceeds our chosen significance level, so we do not
+    reject the null hypothesis that the observed samples are drawn from the
+    same distribution.
+
+    For small sample sizes, one can compute the exact p-values:
+
+    >>> x = stats.norm.rvs(size=7, random_state=rng)
+    >>> y = stats.t.rvs(df=2, size=6, random_state=rng)
+    >>> res = stats.cramervonmises_2samp(x, y, method='exact')
+    >>> res.statistic, res.pvalue
+    (0.197802197802198, 0.31643356643356646)
+
+    The p-value based on the asymptotic distribution is a good approximation
+    even though the sample size is small.
+
+    >>> res = stats.cramervonmises_2samp(x, y, method='asymptotic')
+    >>> res.statistic, res.pvalue
+    (0.197802197802198, 0.2966041181527128)
+
+    Independent of the method, one would not reject the null hypothesis at the
+    chosen significance level in this example.
+
+    """
+    xa = np.sort(np.asarray(x))
+    ya = np.sort(np.asarray(y))
+
+    if xa.size <= 1 or ya.size <= 1:
+        raise ValueError('x and y must contain at least two observations.')
+    if method not in ['auto', 'exact', 'asymptotic']:
+        raise ValueError('method must be either auto, exact or asymptotic.')
+
+    nx = len(xa)
+    ny = len(ya)
+
+    if method == 'auto':
+        if max(nx, ny) > 20:
+            method = 'asymptotic'
+        else:
+            method = 'exact'
+
+    # get ranks of x and y in the pooled sample
+    z = np.concatenate([xa, ya])
+    # in case of ties, use midrank (see [1])
+    r = scipy.stats.rankdata(z, method='average')
+    rx = r[:nx]
+    ry = r[nx:]
+
+    # compute U (eq. 10 in [2])
+    u = nx * np.sum((rx - np.arange(1, nx+1))**2)
+    u += ny * np.sum((ry - np.arange(1, ny+1))**2)
+
+    # compute T (eq. 9 in [2])
+    k, N = nx*ny, nx + ny
+    t = u / (k*N) - (4*k - 1)/(6*N)
+
+    if method == 'exact':
+        p = _pval_cvm_2samp_exact(u, nx, ny)
+    else:
+        # compute expected value and variance of T (eq. 11 and 14 in [2])
+        et = (1 + 1/N)/6
+        vt = (N+1) * (4*k*N - 3*(nx**2 + ny**2) - 2*k)
+        vt = vt / (45 * N**2 * 4 * k)
+
+        # computed the normalized statistic (eq. 15 in [2])
+        tn = 1/6 + (t - et) / np.sqrt(45 * vt)
+
+        # approximate distribution of tn with limiting distribution
+        # of the one-sample test statistic
+        # if tn < 0.003, the _cdf_cvm_inf(tn) < 1.28*1e-18, return 1.0 directly
+        if tn < 0.003:
+            p = 1.0
+        else:
+            p = max(0, 1. - _cdf_cvm_inf(tn))
+
+    return CramerVonMisesResult(statistic=t, pvalue=p)
+
+
+class TukeyHSDResult:
+    """Result of `scipy.stats.tukey_hsd`.
+
+    Attributes
+    ----------
+    statistic : float ndarray
+        The computed statistic of the test for each comparison. The element
+        at index ``(i, j)`` is the statistic for the comparison between groups
+        ``i`` and ``j``.
+    pvalue : float ndarray
+        The associated p-value from the studentized range distribution. The
+        element at index ``(i, j)`` is the p-value for the comparison
+        between groups ``i`` and ``j``.
+
+    Notes
+    -----
+    The string representation of this object displays the most recently
+    calculated confidence interval, and if none have been previously
+    calculated, it will evaluate ``confidence_interval()``.
+
+    References
+    ----------
+    .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.7.1. Tukey's
+           Method."
+           https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm,
+           28 November 2020.
+    """
+
+    def __init__(self, statistic, pvalue, _nobs, _ntreatments, _stand_err):
+        self.statistic = statistic
+        self.pvalue = pvalue
+        self._ntreatments = _ntreatments
+        self._nobs = _nobs
+        self._stand_err = _stand_err
+        self._ci = None
+        self._ci_cl = None
+
+    def __str__(self):
+        # Note: `__str__` prints the confidence intervals from the most
+        # recent call to `confidence_interval`. If it has not been called,
+        # it will be called with the default CL of .95.
+        if self._ci is None:
+            self.confidence_interval(confidence_level=.95)
+        s = ("Tukey's HSD Pairwise Group Comparisons"
+             f" ({self._ci_cl*100:.1f}% Confidence Interval)\n")
+        s += "Comparison  Statistic  p-value  Lower CI  Upper CI\n"
+        for i in range(self.pvalue.shape[0]):
+            for j in range(self.pvalue.shape[0]):
+                if i != j:
+                    s += (f" ({i} - {j}) {self.statistic[i, j]:>10.3f}"
+                          f"{self.pvalue[i, j]:>10.3f}"
+                          f"{self._ci.low[i, j]:>10.3f}"
+                          f"{self._ci.high[i, j]:>10.3f}\n")
+        return s
+
+    def confidence_interval(self, confidence_level=.95):
+        """Compute the confidence interval for the specified confidence level.
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            Confidence level for the computed confidence interval
+            of the estimated proportion. Default is .95.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` object
+            The object has attributes ``low`` and ``high`` that hold the
+            lower and upper bounds of the confidence intervals for each
+            comparison. The high and low values are accessible for each
+            comparison at index ``(i, j)`` between groups ``i`` and ``j``.
+
+        References
+        ----------
+        .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.7.1.
+               Tukey's Method."
+               https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm,
+               28 November 2020.
+
+        Examples
+        --------
+        >>> from scipy.stats import tukey_hsd
+        >>> group0 = [24.5, 23.5, 26.4, 27.1, 29.9]
+        >>> group1 = [28.4, 34.2, 29.5, 32.2, 30.1]
+        >>> group2 = [26.1, 28.3, 24.3, 26.2, 27.8]
+        >>> result = tukey_hsd(group0, group1, group2)
+        >>> ci = result.confidence_interval()
+        >>> ci.low
+        array([[-3.649159, -8.249159, -3.909159],
+               [ 0.950841, -3.649159,  0.690841],
+               [-3.389159, -7.989159, -3.649159]])
+        >>> ci.high
+        array([[ 3.649159, -0.950841,  3.389159],
+               [ 8.249159,  3.649159,  7.989159],
+               [ 3.909159, -0.690841,  3.649159]])
+        """
+        # check to see if the supplied confidence level matches that of the
+        # previously computed CI.
+        if (self._ci is not None and self._ci_cl is not None and
+                confidence_level == self._ci_cl):
+            return self._ci
+
+        if not 0 < confidence_level < 1:
+            raise ValueError("Confidence level must be between 0 and 1.")
+        # determine the critical value of the studentized range using the
+        # appropriate confidence level, number of treatments, and degrees
+        # of freedom as determined by the number of data less the number of
+        # treatments. ("Confidence limits for Tukey's method")[1]. Note that
+        # in the cases of unequal sample sizes there will be a criterion for
+        # each group comparison.
+        params = (confidence_level, self._nobs, self._ntreatments - self._nobs)
+        srd = distributions.studentized_range.ppf(*params)
+        # also called maximum critical value, the Tukey criterion is the
+        # studentized range critical value * the square root of mean square
+        # error over the sample size.
+        tukey_criterion = srd * self._stand_err
+        # the confidence levels are determined by the
+        # `mean_differences` +- `tukey_criterion`
+        upper_conf = self.statistic + tukey_criterion
+        lower_conf = self.statistic - tukey_criterion
+        self._ci = ConfidenceInterval(low=lower_conf, high=upper_conf)
+        self._ci_cl = confidence_level
+        return self._ci
+
+
+def _tukey_hsd_iv(args):
+    if (len(args)) < 2:
+        raise ValueError("There must be more than 1 treatment.")
+    args = [np.asarray(arg) for arg in args]
+    for arg in args:
+        if arg.ndim != 1:
+            raise ValueError("Input samples must be one-dimensional.")
+        if arg.size <= 1:
+            raise ValueError("Input sample size must be greater than one.")
+        if np.isinf(arg).any():
+            raise ValueError("Input samples must be finite.")
+    return args
+
+
+def tukey_hsd(*args):
+    """Perform Tukey's HSD test for equality of means over multiple treatments.
+
+    Tukey's honestly significant difference (HSD) test performs pairwise
+    comparison of means for a set of samples. Whereas ANOVA (e.g. `f_oneway`)
+    assesses whether the true means underlying each sample are identical,
+    Tukey's HSD is a post hoc test used to compare the mean of each sample
+    to the mean of each other sample.
+
+    The null hypothesis is that the distributions underlying the samples all
+    have the same mean. The test statistic, which is computed for every
+    possible pairing of samples, is simply the difference between the sample
+    means. For each pair, the p-value is the probability under the null
+    hypothesis (and other assumptions; see notes) of observing such an extreme
+    value of the statistic, considering that many pairwise comparisons are
+    being performed. Confidence intervals for the difference between each pair
+    of means are also available.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The sample measurements for each group. There must be at least
+        two arguments.
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.TukeyHSDResult` instance
+        The return value is an object with the following attributes:
+
+        statistic : float ndarray
+            The computed statistic of the test for each comparison. The element
+            at index ``(i, j)`` is the statistic for the comparison between
+            groups ``i`` and ``j``.
+        pvalue : float ndarray
+            The computed p-value of the test for each comparison. The element
+            at index ``(i, j)`` is the p-value for the comparison between
+            groups ``i`` and ``j``.
+
+        The object has the following methods:
+
+        confidence_interval(confidence_level=0.95):
+            Compute the confidence interval for the specified confidence level.
+
+    See Also
+    --------
+    dunnett : performs comparison of means against a control group.
+
+    Notes
+    -----
+    The use of this test relies on several assumptions.
+
+    1. The observations are independent within and among groups.
+    2. The observations within each group are normally distributed.
+    3. The distributions from which the samples are drawn have the same finite
+       variance.
+
+    The original formulation of the test was for samples of equal size [6]_.
+    In case of unequal sample sizes, the test uses the Tukey-Kramer method
+    [4]_.
+
+    References
+    ----------
+    .. [1] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.7.1. Tukey's
+           Method."
+           https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm,
+           28 November 2020.
+    .. [2] Abdi, Herve & Williams, Lynne. (2021). "Tukey's Honestly Significant
+           Difference (HSD) Test."
+           https://personal.utdallas.edu/~herve/abdi-HSD2010-pretty.pdf
+    .. [3] "One-Way ANOVA Using SAS PROC ANOVA & PROC GLM." SAS
+           Tutorials, 2007, www.stattutorials.com/SAS/TUTORIAL-PROC-GLM.htm.
+    .. [4] Kramer, Clyde Young. "Extension of Multiple Range Tests to Group
+           Means with Unequal Numbers of Replications." Biometrics, vol. 12,
+           no. 3, 1956, pp. 307-310. JSTOR, www.jstor.org/stable/3001469.
+           Accessed 25 May 2021.
+    .. [5] NIST/SEMATECH e-Handbook of Statistical Methods, "7.4.3.3.
+           The ANOVA table and tests of hypotheses about means"
+           https://www.itl.nist.gov/div898/handbook/prc/section4/prc433.htm,
+           2 June 2021.
+    .. [6] Tukey, John W. "Comparing Individual Means in the Analysis of
+           Variance." Biometrics, vol. 5, no. 2, 1949, pp. 99-114. JSTOR,
+           www.jstor.org/stable/3001913. Accessed 14 June 2021.
+
+
+    Examples
+    --------
+    Here are some data comparing the time to relief of three brands of
+    headache medicine, reported in minutes. Data adapted from [3]_.
+
+    >>> import numpy as np
+    >>> from scipy.stats import tukey_hsd
+    >>> group0 = [24.5, 23.5, 26.4, 27.1, 29.9]
+    >>> group1 = [28.4, 34.2, 29.5, 32.2, 30.1]
+    >>> group2 = [26.1, 28.3, 24.3, 26.2, 27.8]
+
+    We would like to see if the means between any of the groups are
+    significantly different. First, visually examine a box and whisker plot.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.boxplot([group0, group1, group2])
+    >>> ax.set_xticklabels(["group0", "group1", "group2"]) # doctest: +SKIP
+    >>> ax.set_ylabel("mean") # doctest: +SKIP
+    >>> plt.show()
+
+    From the box and whisker plot, we can see overlap in the interquartile
+    ranges group 1 to group 2 and group 3, but we can apply the ``tukey_hsd``
+    test to determine if the difference between means is significant. We
+    set a significance level of .05 to reject the null hypothesis.
+
+    >>> res = tukey_hsd(group0, group1, group2)
+    >>> print(res)
+    Tukey's HSD Pairwise Group Comparisons (95.0% Confidence Interval)
+    Comparison  Statistic  p-value   Lower CI   Upper CI
+    (0 - 1)     -4.600      0.014     -8.249     -0.951
+    (0 - 2)     -0.260      0.980     -3.909      3.389
+    (1 - 0)      4.600      0.014      0.951      8.249
+    (1 - 2)      4.340      0.020      0.691      7.989
+    (2 - 0)      0.260      0.980     -3.389      3.909
+    (2 - 1)     -4.340      0.020     -7.989     -0.691
+
+    The null hypothesis is that each group has the same mean. The p-value for
+    comparisons between ``group0`` and ``group1`` as well as ``group1`` and
+    ``group2`` do not exceed .05, so we reject the null hypothesis that they
+    have the same means. The p-value of the comparison between ``group0``
+    and ``group2`` exceeds .05, so we accept the null hypothesis that there
+    is not a significant difference between their means.
+
+    We can also compute the confidence interval associated with our chosen
+    confidence level.
+
+    >>> group0 = [24.5, 23.5, 26.4, 27.1, 29.9]
+    >>> group1 = [28.4, 34.2, 29.5, 32.2, 30.1]
+    >>> group2 = [26.1, 28.3, 24.3, 26.2, 27.8]
+    >>> result = tukey_hsd(group0, group1, group2)
+    >>> conf = res.confidence_interval(confidence_level=.99)
+    >>> for ((i, j), l) in np.ndenumerate(conf.low):
+    ...     # filter out self comparisons
+    ...     if i != j:
+    ...         h = conf.high[i,j]
+    ...         print(f"({i} - {j}) {l:>6.3f} {h:>6.3f}")
+    (0 - 1) -9.480  0.280
+    (0 - 2) -5.140  4.620
+    (1 - 0) -0.280  9.480
+    (1 - 2) -0.540  9.220
+    (2 - 0) -4.620  5.140
+    (2 - 1) -9.220  0.540
+    """
+    args = _tukey_hsd_iv(args)
+    ntreatments = len(args)
+    means = np.asarray([np.mean(arg) for arg in args])
+    nsamples_treatments = np.asarray([a.size for a in args])
+    nobs = np.sum(nsamples_treatments)
+
+    # determine mean square error [5]. Note that this is sometimes called
+    # mean square error within.
+    mse = (np.sum([np.var(arg, ddof=1) for arg in args] *
+                  (nsamples_treatments - 1)) / (nobs - ntreatments))
+
+    # The calculation of the standard error differs when treatments differ in
+    # size. See ("Unequal sample sizes")[1].
+    if np.unique(nsamples_treatments).size == 1:
+        # all input groups are the same length, so only one value needs to be
+        # calculated [1].
+        normalize = 2 / nsamples_treatments[0]
+    else:
+        # to compare groups of differing sizes, we must compute a variance
+        # value for each individual comparison. Use broadcasting to get the
+        # resulting matrix. [3], verified against [4] (page 308).
+        normalize = 1 / nsamples_treatments + 1 / nsamples_treatments[None].T
+
+    # the standard error is used in the computation of the tukey criterion and
+    # finding the p-values.
+    stand_err = np.sqrt(normalize * mse / 2)
+
+    # the mean difference is the test statistic.
+    mean_differences = means[None].T - means
+
+    # Calculate the t-statistic to use within the survival function of the
+    # studentized range to get the p-value.
+    t_stat = np.abs(mean_differences) / stand_err
+
+    params = t_stat, ntreatments, nobs - ntreatments
+    pvalues = distributions.studentized_range.sf(*params)
+
+    return TukeyHSDResult(mean_differences, pvalues, ntreatments,
+                          nobs, stand_err)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_kde.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_kde.py
new file mode 100644
index 0000000000000000000000000000000000000000..a967fcf44eedf040fb795618d535d8fe24c33a98
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_kde.py
@@ -0,0 +1,728 @@
+#-------------------------------------------------------------------------------
+#
+#  Define classes for (uni/multi)-variate kernel density estimation.
+#
+#  Currently, only Gaussian kernels are implemented.
+#
+#  Written by: Robert Kern
+#
+#  Date: 2004-08-09
+#
+#  Modified: 2005-02-10 by Robert Kern.
+#              Contributed to SciPy
+#            2005-10-07 by Robert Kern.
+#              Some fixes to match the new scipy_core
+#
+#  Copyright 2004-2005 by Enthought, Inc.
+#
+#-------------------------------------------------------------------------------
+
+# Standard library imports.
+import threading
+import warnings
+
+# SciPy imports.
+from scipy import linalg, special
+from scipy._lib._util import check_random_state
+
+from numpy import (asarray, atleast_2d, reshape, zeros, newaxis, exp, pi,
+                   sqrt, ravel, power, atleast_1d, squeeze, sum, transpose,
+                   ones, cov)
+import numpy as np
+
+# Local imports.
+from . import _mvn
+from ._stats import gaussian_kernel_estimate, gaussian_kernel_estimate_log
+
+
+__all__ = ['gaussian_kde']
+
+MVN_LOCK = threading.Lock()
+
+
+class gaussian_kde:
+    """Representation of a kernel-density estimate using Gaussian kernels.
+
+    Kernel density estimation is a way to estimate the probability density
+    function (PDF) of a random variable in a non-parametric way.
+    `gaussian_kde` works for both uni-variate and multi-variate data.   It
+    includes automatic bandwidth determination.  The estimation works best for
+    a unimodal distribution; bimodal or multi-modal distributions tend to be
+    oversmoothed.
+
+    Parameters
+    ----------
+    dataset : array_like
+        Datapoints to estimate from. In case of univariate data this is a 1-D
+        array, otherwise a 2-D array with shape (# of dims, # of data).
+    bw_method : str, scalar or callable, optional
+        The method used to calculate the estimator bandwidth.  This can be
+        'scott', 'silverman', a scalar constant or a callable.  If a scalar,
+        this will be used directly as `kde.factor`.  If a callable, it should
+        take a `gaussian_kde` instance as only parameter and return a scalar.
+        If None (default), 'scott' is used.  See Notes for more details.
+    weights : array_like, optional
+        weights of datapoints. This must be the same shape as dataset.
+        If None (default), the samples are assumed to be equally weighted
+
+    Attributes
+    ----------
+    dataset : ndarray
+        The dataset with which `gaussian_kde` was initialized.
+    d : int
+        Number of dimensions.
+    n : int
+        Number of datapoints.
+    neff : int
+        Effective number of datapoints.
+
+        .. versionadded:: 1.2.0
+    factor : float
+        The bandwidth factor, obtained from `kde.covariance_factor`. The square
+        of `kde.factor` multiplies the covariance matrix of the data in the kde
+        estimation.
+    covariance : ndarray
+        The covariance matrix of `dataset`, scaled by the calculated bandwidth
+        (`kde.factor`).
+    inv_cov : ndarray
+        The inverse of `covariance`.
+
+    Methods
+    -------
+    evaluate
+    __call__
+    integrate_gaussian
+    integrate_box_1d
+    integrate_box
+    integrate_kde
+    pdf
+    logpdf
+    resample
+    set_bandwidth
+    covariance_factor
+
+    Notes
+    -----
+    Bandwidth selection strongly influences the estimate obtained from the KDE
+    (much more so than the actual shape of the kernel).  Bandwidth selection
+    can be done by a "rule of thumb", by cross-validation, by "plug-in
+    methods" or by other means; see [3]_, [4]_ for reviews.  `gaussian_kde`
+    uses a rule of thumb, the default is Scott's Rule.
+
+    Scott's Rule [1]_, implemented as `scotts_factor`, is::
+
+        n**(-1./(d+4)),
+
+    with ``n`` the number of data points and ``d`` the number of dimensions.
+    In the case of unequally weighted points, `scotts_factor` becomes::
+
+        neff**(-1./(d+4)),
+
+    with ``neff`` the effective number of datapoints.
+    Silverman's Rule [2]_, implemented as `silverman_factor`, is::
+
+        (n * (d + 2) / 4.)**(-1. / (d + 4)).
+
+    or in the case of unequally weighted points::
+
+        (neff * (d + 2) / 4.)**(-1. / (d + 4)).
+
+    Good general descriptions of kernel density estimation can be found in [1]_
+    and [2]_, the mathematics for this multi-dimensional implementation can be
+    found in [1]_.
+
+    With a set of weighted samples, the effective number of datapoints ``neff``
+    is defined by::
+
+        neff = sum(weights)^2 / sum(weights^2)
+
+    as detailed in [5]_.
+
+    `gaussian_kde` does not currently support data that lies in a
+    lower-dimensional subspace of the space in which it is expressed. For such
+    data, consider performing principal component analysis / dimensionality
+    reduction and using `gaussian_kde` with the transformed data.
+
+    References
+    ----------
+    .. [1] D.W. Scott, "Multivariate Density Estimation: Theory, Practice, and
+           Visualization", John Wiley & Sons, New York, Chicester, 1992.
+    .. [2] B.W. Silverman, "Density Estimation for Statistics and Data
+           Analysis", Vol. 26, Monographs on Statistics and Applied Probability,
+           Chapman and Hall, London, 1986.
+    .. [3] B.A. Turlach, "Bandwidth Selection in Kernel Density Estimation: A
+           Review", CORE and Institut de Statistique, Vol. 19, pp. 1-33, 1993.
+    .. [4] D.M. Bashtannyk and R.J. Hyndman, "Bandwidth selection for kernel
+           conditional density estimation", Computational Statistics & Data
+           Analysis, Vol. 36, pp. 279-298, 2001.
+    .. [5] Gray P. G., 1969, Journal of the Royal Statistical Society.
+           Series A (General), 132, 272
+
+    Examples
+    --------
+    Generate some random two-dimensional data:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> def measure(n):
+    ...     "Measurement model, return two coupled measurements."
+    ...     m1 = np.random.normal(size=n)
+    ...     m2 = np.random.normal(scale=0.5, size=n)
+    ...     return m1+m2, m1-m2
+
+    >>> m1, m2 = measure(2000)
+    >>> xmin = m1.min()
+    >>> xmax = m1.max()
+    >>> ymin = m2.min()
+    >>> ymax = m2.max()
+
+    Perform a kernel density estimate on the data:
+
+    >>> X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
+    >>> positions = np.vstack([X.ravel(), Y.ravel()])
+    >>> values = np.vstack([m1, m2])
+    >>> kernel = stats.gaussian_kde(values)
+    >>> Z = np.reshape(kernel(positions).T, X.shape)
+
+    Plot the results:
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r,
+    ...           extent=[xmin, xmax, ymin, ymax])
+    >>> ax.plot(m1, m2, 'k.', markersize=2)
+    >>> ax.set_xlim([xmin, xmax])
+    >>> ax.set_ylim([ymin, ymax])
+    >>> plt.show()
+
+    """
+    def __init__(self, dataset, bw_method=None, weights=None):
+        self.dataset = atleast_2d(asarray(dataset))
+        if not self.dataset.size > 1:
+            raise ValueError("`dataset` input should have multiple elements.")
+
+        self.d, self.n = self.dataset.shape
+
+        if weights is not None:
+            self._weights = atleast_1d(weights).astype(float)
+            self._weights /= sum(self._weights)
+            if self.weights.ndim != 1:
+                raise ValueError("`weights` input should be one-dimensional.")
+            if len(self._weights) != self.n:
+                raise ValueError("`weights` input should be of length n")
+            self._neff = 1/sum(self._weights**2)
+
+        # This can be converted to a warning once gh-10205 is resolved
+        if self.d > self.n:
+            msg = ("Number of dimensions is greater than number of samples. "
+                   "This results in a singular data covariance matrix, which "
+                   "cannot be treated using the algorithms implemented in "
+                   "`gaussian_kde`. Note that `gaussian_kde` interprets each "
+                   "*column* of `dataset` to be a point; consider transposing "
+                   "the input to `dataset`.")
+            raise ValueError(msg)
+
+        try:
+            self.set_bandwidth(bw_method=bw_method)
+        except linalg.LinAlgError as e:
+            msg = ("The data appears to lie in a lower-dimensional subspace "
+                   "of the space in which it is expressed. This has resulted "
+                   "in a singular data covariance matrix, which cannot be "
+                   "treated using the algorithms implemented in "
+                   "`gaussian_kde`. Consider performing principal component "
+                   "analysis / dimensionality reduction and using "
+                   "`gaussian_kde` with the transformed data.")
+            raise linalg.LinAlgError(msg) from e
+
+    def evaluate(self, points):
+        """Evaluate the estimated pdf on a set of points.
+
+        Parameters
+        ----------
+        points : (# of dimensions, # of points)-array
+            Alternatively, a (# of dimensions,) vector can be passed in and
+            treated as a single point.
+
+        Returns
+        -------
+        values : (# of points,)-array
+            The values at each point.
+
+        Raises
+        ------
+        ValueError : if the dimensionality of the input points is different than
+                     the dimensionality of the KDE.
+
+        """
+        points = atleast_2d(asarray(points))
+
+        d, m = points.shape
+        if d != self.d:
+            if d == 1 and m == self.d:
+                # points was passed in as a row vector
+                points = reshape(points, (self.d, 1))
+                m = 1
+            else:
+                msg = (f"points have dimension {d}, "
+                       f"dataset has dimension {self.d}")
+                raise ValueError(msg)
+
+        output_dtype, spec = _get_output_dtype(self.covariance, points)
+        result = gaussian_kernel_estimate[spec](
+            self.dataset.T, self.weights[:, None],
+            points.T, self.cho_cov, output_dtype)
+
+        return result[:, 0]
+
+    __call__ = evaluate
+
+    def integrate_gaussian(self, mean, cov):
+        """
+        Multiply estimated density by a multivariate Gaussian and integrate
+        over the whole space.
+
+        Parameters
+        ----------
+        mean : aray_like
+            A 1-D array, specifying the mean of the Gaussian.
+        cov : array_like
+            A 2-D array, specifying the covariance matrix of the Gaussian.
+
+        Returns
+        -------
+        result : scalar
+            The value of the integral.
+
+        Raises
+        ------
+        ValueError
+            If the mean or covariance of the input Gaussian differs from
+            the KDE's dimensionality.
+
+        """
+        mean = atleast_1d(squeeze(mean))
+        cov = atleast_2d(cov)
+
+        if mean.shape != (self.d,):
+            raise ValueError(f"mean does not have dimension {self.d}")
+        if cov.shape != (self.d, self.d):
+            raise ValueError(f"covariance does not have dimension {self.d}")
+
+        # make mean a column vector
+        mean = mean[:, newaxis]
+
+        sum_cov = self.covariance + cov
+
+        # This will raise LinAlgError if the new cov matrix is not s.p.d
+        # cho_factor returns (ndarray, bool) where bool is a flag for whether
+        # or not ndarray is upper or lower triangular
+        sum_cov_chol = linalg.cho_factor(sum_cov)
+
+        diff = self.dataset - mean
+        tdiff = linalg.cho_solve(sum_cov_chol, diff)
+
+        sqrt_det = np.prod(np.diagonal(sum_cov_chol[0]))
+        norm_const = power(2 * pi, sum_cov.shape[0] / 2.0) * sqrt_det
+
+        energies = sum(diff * tdiff, axis=0) / 2.0
+        result = sum(exp(-energies)*self.weights, axis=0) / norm_const
+
+        return result
+
+    def integrate_box_1d(self, low, high):
+        """
+        Computes the integral of a 1D pdf between two bounds.
+
+        Parameters
+        ----------
+        low : scalar
+            Lower bound of integration.
+        high : scalar
+            Upper bound of integration.
+
+        Returns
+        -------
+        value : scalar
+            The result of the integral.
+
+        Raises
+        ------
+        ValueError
+            If the KDE is over more than one dimension.
+
+        """
+        if self.d != 1:
+            raise ValueError("integrate_box_1d() only handles 1D pdfs")
+
+        stdev = ravel(sqrt(self.covariance))[0]
+
+        normalized_low = ravel((low - self.dataset) / stdev)
+        normalized_high = ravel((high - self.dataset) / stdev)
+
+        value = np.sum(self.weights*(
+                        special.ndtr(normalized_high) -
+                        special.ndtr(normalized_low)))
+        return value
+
+    def integrate_box(self, low_bounds, high_bounds, maxpts=None):
+        """Computes the integral of a pdf over a rectangular interval.
+
+        Parameters
+        ----------
+        low_bounds : array_like
+            A 1-D array containing the lower bounds of integration.
+        high_bounds : array_like
+            A 1-D array containing the upper bounds of integration.
+        maxpts : int, optional
+            The maximum number of points to use for integration.
+
+        Returns
+        -------
+        value : scalar
+            The result of the integral.
+
+        """
+        if maxpts is not None:
+            extra_kwds = {'maxpts': maxpts}
+        else:
+            extra_kwds = {}
+
+        with MVN_LOCK:
+            value, inform = _mvn.mvnun_weighted(low_bounds, high_bounds,
+                                                self.dataset, self.weights,
+                                                self.covariance, **extra_kwds)
+        if inform:
+            msg = f'An integral in _mvn.mvnun requires more points than {self.d * 1000}'
+            warnings.warn(msg, stacklevel=2)
+
+        return value
+
+    def integrate_kde(self, other):
+        """
+        Computes the integral of the product of this  kernel density estimate
+        with another.
+
+        Parameters
+        ----------
+        other : gaussian_kde instance
+            The other kde.
+
+        Returns
+        -------
+        value : scalar
+            The result of the integral.
+
+        Raises
+        ------
+        ValueError
+            If the KDEs have different dimensionality.
+
+        """
+        if other.d != self.d:
+            raise ValueError("KDEs are not the same dimensionality")
+
+        # we want to iterate over the smallest number of points
+        if other.n < self.n:
+            small = other
+            large = self
+        else:
+            small = self
+            large = other
+
+        sum_cov = small.covariance + large.covariance
+        sum_cov_chol = linalg.cho_factor(sum_cov)
+        result = 0.0
+        for i in range(small.n):
+            mean = small.dataset[:, i, newaxis]
+            diff = large.dataset - mean
+            tdiff = linalg.cho_solve(sum_cov_chol, diff)
+
+            energies = sum(diff * tdiff, axis=0) / 2.0
+            result += sum(exp(-energies)*large.weights, axis=0)*small.weights[i]
+
+        sqrt_det = np.prod(np.diagonal(sum_cov_chol[0]))
+        norm_const = power(2 * pi, sum_cov.shape[0] / 2.0) * sqrt_det
+
+        result /= norm_const
+
+        return result
+
+    def resample(self, size=None, seed=None):
+        """Randomly sample a dataset from the estimated pdf.
+
+        Parameters
+        ----------
+        size : int, optional
+            The number of samples to draw.  If not provided, then the size is
+            the same as the effective number of samples in the underlying
+            dataset.
+        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance then
+            that instance is used.
+
+        Returns
+        -------
+        resample : (self.d, `size`) ndarray
+            The sampled dataset.
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        if size is None:
+            size = int(self.neff)
+
+        random_state = check_random_state(seed)
+        norm = transpose(random_state.multivariate_normal(
+            zeros((self.d,), float), self.covariance, size=size
+        ))
+        indices = random_state.choice(self.n, size=size, p=self.weights)
+        means = self.dataset[:, indices]
+
+        return means + norm
+
+    def scotts_factor(self):
+        """Compute Scott's factor.
+
+        Returns
+        -------
+        s : float
+            Scott's factor.
+        """
+        return power(self.neff, -1./(self.d+4))
+
+    def silverman_factor(self):
+        """Compute the Silverman factor.
+
+        Returns
+        -------
+        s : float
+            The silverman factor.
+        """
+        return power(self.neff*(self.d+2.0)/4.0, -1./(self.d+4))
+
+    #  Default method to calculate bandwidth, can be overwritten by subclass
+    covariance_factor = scotts_factor
+    covariance_factor.__doc__ = """Computes the coefficient (`kde.factor`) that
+        multiplies the data covariance matrix to obtain the kernel covariance
+        matrix. The default is `scotts_factor`.  A subclass can overwrite this
+        method to provide a different method, or set it through a call to
+        `kde.set_bandwidth`."""
+
+    def set_bandwidth(self, bw_method=None):
+        """Compute the estimator bandwidth with given method.
+
+        The new bandwidth calculated after a call to `set_bandwidth` is used
+        for subsequent evaluations of the estimated density.
+
+        Parameters
+        ----------
+        bw_method : str, scalar or callable, optional
+            The method used to calculate the estimator bandwidth.  This can be
+            'scott', 'silverman', a scalar constant or a callable.  If a
+            scalar, this will be used directly as `kde.factor`.  If a callable,
+            it should take a `gaussian_kde` instance as only parameter and
+            return a scalar.  If None (default), nothing happens; the current
+            `kde.covariance_factor` method is kept.
+
+        Notes
+        -----
+        .. versionadded:: 0.11
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> import scipy.stats as stats
+        >>> x1 = np.array([-7, -5, 1, 4, 5.])
+        >>> kde = stats.gaussian_kde(x1)
+        >>> xs = np.linspace(-10, 10, num=50)
+        >>> y1 = kde(xs)
+        >>> kde.set_bandwidth(bw_method='silverman')
+        >>> y2 = kde(xs)
+        >>> kde.set_bandwidth(bw_method=kde.factor / 3.)
+        >>> y3 = kde(xs)
+
+        >>> import matplotlib.pyplot as plt
+        >>> fig, ax = plt.subplots()
+        >>> ax.plot(x1, np.full(x1.shape, 1 / (4. * x1.size)), 'bo',
+        ...         label='Data points (rescaled)')
+        >>> ax.plot(xs, y1, label='Scott (default)')
+        >>> ax.plot(xs, y2, label='Silverman')
+        >>> ax.plot(xs, y3, label='Const (1/3 * Silverman)')
+        >>> ax.legend()
+        >>> plt.show()
+
+        """
+        if bw_method is None:
+            pass
+        elif bw_method == 'scott':
+            self.covariance_factor = self.scotts_factor
+        elif bw_method == 'silverman':
+            self.covariance_factor = self.silverman_factor
+        elif np.isscalar(bw_method) and not isinstance(bw_method, str):
+            self._bw_method = 'use constant'
+            self.covariance_factor = lambda: bw_method
+        elif callable(bw_method):
+            self._bw_method = bw_method
+            self.covariance_factor = lambda: self._bw_method(self)
+        else:
+            msg = "`bw_method` should be 'scott', 'silverman', a scalar " \
+                  "or a callable."
+            raise ValueError(msg)
+
+        self._compute_covariance()
+
+    def _compute_covariance(self):
+        """Computes the covariance matrix for each Gaussian kernel using
+        covariance_factor().
+        """
+        self.factor = self.covariance_factor()
+        # Cache covariance and Cholesky decomp of covariance
+        if not hasattr(self, '_data_cho_cov'):
+            self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1,
+                                               bias=False,
+                                               aweights=self.weights))
+            self._data_cho_cov = linalg.cholesky(self._data_covariance,
+                                                 lower=True)
+
+        self.covariance = self._data_covariance * self.factor**2
+        self.cho_cov = (self._data_cho_cov * self.factor).astype(np.float64)
+        self.log_det = 2*np.log(np.diag(self.cho_cov
+                                        * np.sqrt(2*pi))).sum()
+
+    @property
+    def inv_cov(self):
+        # Re-compute from scratch each time because I'm not sure how this is
+        # used in the wild. (Perhaps users change the `dataset`, since it's
+        # not a private attribute?) `_compute_covariance` used to recalculate
+        # all these, so we'll recalculate everything now that this is a
+        # a property.
+        self.factor = self.covariance_factor()
+        self._data_covariance = atleast_2d(cov(self.dataset, rowvar=1,
+                                           bias=False, aweights=self.weights))
+        return linalg.inv(self._data_covariance) / self.factor**2
+
+    def pdf(self, x):
+        """
+        Evaluate the estimated pdf on a provided set of points.
+
+        Notes
+        -----
+        This is an alias for `gaussian_kde.evaluate`.  See the ``evaluate``
+        docstring for more details.
+
+        """
+        return self.evaluate(x)
+
+    def logpdf(self, x):
+        """
+        Evaluate the log of the estimated pdf on a provided set of points.
+        """
+        points = atleast_2d(x)
+
+        d, m = points.shape
+        if d != self.d:
+            if d == 1 and m == self.d:
+                # points was passed in as a row vector
+                points = reshape(points, (self.d, 1))
+                m = 1
+            else:
+                msg = (f"points have dimension {d}, "
+                       f"dataset has dimension {self.d}")
+                raise ValueError(msg)
+
+        output_dtype, spec = _get_output_dtype(self.covariance, points)
+        result = gaussian_kernel_estimate_log[spec](
+            self.dataset.T, self.weights[:, None],
+            points.T, self.cho_cov, output_dtype)
+
+        return result[:, 0]
+
+    def marginal(self, dimensions):
+        """Return a marginal KDE distribution
+
+        Parameters
+        ----------
+        dimensions : int or 1-d array_like
+            The dimensions of the multivariate distribution corresponding
+            with the marginal variables, that is, the indices of the dimensions
+            that are being retained. The other dimensions are marginalized out.
+
+        Returns
+        -------
+        marginal_kde : gaussian_kde
+            An object representing the marginal distribution.
+
+        Notes
+        -----
+        .. versionadded:: 1.10.0
+
+        """
+
+        dims = np.atleast_1d(dimensions)
+
+        if not np.issubdtype(dims.dtype, np.integer):
+            msg = ("Elements of `dimensions` must be integers - the indices "
+                   "of the marginal variables being retained.")
+            raise ValueError(msg)
+
+        n = len(self.dataset)  # number of dimensions
+        original_dims = dims.copy()
+
+        dims[dims < 0] = n + dims[dims < 0]
+
+        if len(np.unique(dims)) != len(dims):
+            msg = ("All elements of `dimensions` must be unique.")
+            raise ValueError(msg)
+
+        i_invalid = (dims < 0) | (dims >= n)
+        if np.any(i_invalid):
+            msg = (f"Dimensions {original_dims[i_invalid]} are invalid "
+                   f"for a distribution in {n} dimensions.")
+            raise ValueError(msg)
+
+        dataset = self.dataset[dims]
+        weights = self.weights
+
+        return gaussian_kde(dataset, bw_method=self.covariance_factor(),
+                            weights=weights)
+
+    @property
+    def weights(self):
+        try:
+            return self._weights
+        except AttributeError:
+            self._weights = ones(self.n)/self.n
+            return self._weights
+
+    @property
+    def neff(self):
+        try:
+            return self._neff
+        except AttributeError:
+            self._neff = 1/sum(self.weights**2)
+            return self._neff
+
+
+def _get_output_dtype(covariance, points):
+    """
+    Calculates the output dtype and the "spec" (=C type name).
+
+    This was necessary in order to deal with the fused types in the Cython
+    routine `gaussian_kernel_estimate`. See gh-10824 for details.
+    """
+    output_dtype = np.common_type(covariance, points)
+    itemsize = np.dtype(output_dtype).itemsize
+    if itemsize == 4:
+        spec = 'float'
+    elif itemsize == 8:
+        spec = 'double'
+    elif itemsize in (12, 16):
+        spec = 'long double'
+    else:
+        raise ValueError(
+                f"{output_dtype} has unexpected item size: {itemsize}"
+            )
+
+    return output_dtype, spec
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_ksstats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_ksstats.py
new file mode 100644
index 0000000000000000000000000000000000000000..a25d07e3233b40d791d4ce5332490f6e74cde290
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_ksstats.py
@@ -0,0 +1,600 @@
+# Compute the two-sided one-sample Kolmogorov-Smirnov Prob(Dn <= d) where:
+#    D_n = sup_x{|F_n(x) - F(x)|},
+#    F_n(x) is the empirical CDF for a sample of size n {x_i: i=1,...,n},
+#    F(x) is the CDF of a probability distribution.
+#
+# Exact methods:
+# Prob(D_n >= d) can be computed via a matrix algorithm of Durbin[1]
+#   or a recursion algorithm due to Pomeranz[2].
+# Marsaglia, Tsang & Wang[3] gave a computation-efficient way to perform
+#   the Durbin algorithm.
+#   D_n >= d <==>  D_n+ >= d or D_n- >= d (the one-sided K-S statistics), hence
+#   Prob(D_n >= d) = 2*Prob(D_n+ >= d) - Prob(D_n+ >= d and D_n- >= d).
+#   For d > 0.5, the latter intersection probability is 0.
+#
+# Approximate methods:
+# For d close to 0.5, ignoring that intersection term may still give a
+#   reasonable approximation.
+# Li-Chien[4] and Korolyuk[5] gave an asymptotic formula extending
+# Kolmogorov's initial asymptotic, suitable for large d. (See
+#   scipy.special.kolmogorov for that asymptotic)
+# Pelz-Good[6] used the functional equation for Jacobi theta functions to
+#   transform the Li-Chien/Korolyuk formula produce a computational formula
+#   suitable for small d.
+#
+# Simard and L'Ecuyer[7] provided an algorithm to decide when to use each of
+#   the above approaches and it is that which is used here.
+#
+# Other approaches:
+# Carvalho[8] optimizes Durbin's matrix algorithm for large values of d.
+# Moscovich and Nadler[9] use FFTs to compute the convolutions.
+
+# References:
+# [1] Durbin J (1968).
+#     "The Probability that the Sample Distribution Function Lies Between Two
+#     Parallel Straight Lines."
+#     Annals of Mathematical Statistics, 39, 398-411.
+# [2] Pomeranz J (1974).
+#     "Exact Cumulative Distribution of the Kolmogorov-Smirnov Statistic for
+#     Small Samples (Algorithm 487)."
+#     Communications of the ACM, 17(12), 703-704.
+# [3] Marsaglia G, Tsang WW, Wang J (2003).
+#     "Evaluating Kolmogorov's Distribution."
+#     Journal of Statistical Software, 8(18), 1-4.
+# [4] LI-CHIEN, C. (1956).
+#     "On the exact distribution of the statistics of A. N. Kolmogorov and
+#     their asymptotic expansion."
+#     Acta Matematica Sinica, 6, 55-81.
+# [5] KOROLYUK, V. S. (1960).
+#     "Asymptotic analysis of the distribution of the maximum deviation in
+#     the Bernoulli scheme."
+#     Theor. Probability Appl., 4, 339-366.
+# [6] Pelz W, Good IJ (1976).
+#     "Approximating the Lower Tail-areas of the Kolmogorov-Smirnov One-sample
+#     Statistic."
+#     Journal of the Royal Statistical Society, Series B, 38(2), 152-156.
+#  [7] Simard, R., L'Ecuyer, P. (2011)
+# 	  "Computing the Two-Sided Kolmogorov-Smirnov Distribution",
+# 	  Journal of Statistical Software, Vol 39, 11, 1-18.
+#  [8] Carvalho, Luis (2015)
+#     "An Improved Evaluation of Kolmogorov's Distribution"
+#     Journal of Statistical Software, Code Snippets; Vol 65(3), 1-8.
+#  [9] Amit Moscovich, Boaz Nadler (2017)
+#     "Fast calculation of boundary crossing probabilities for Poisson
+#     processes",
+#     Statistics & Probability Letters, Vol 123, 177-182.
+
+
+import numpy as np
+import scipy.special
+import scipy.special._ufuncs as scu
+from scipy._lib._finite_differences import _derivative
+
+_E128 = 128
+_EP128 = np.ldexp(np.longdouble(1), _E128)
+_EM128 = np.ldexp(np.longdouble(1), -_E128)
+
+_SQRT2PI = np.sqrt(2 * np.pi)
+_LOG_2PI = np.log(2 * np.pi)
+_MIN_LOG = -708
+_SQRT3 = np.sqrt(3)
+_PI_SQUARED = np.pi ** 2
+_PI_FOUR = np.pi ** 4
+_PI_SIX = np.pi ** 6
+
+# [Lifted from _loggamma.pxd.] If B_m are the Bernoulli numbers,
+# then Stirling coeffs are B_{2j}/(2j)/(2j-1) for j=8,...1.
+_STIRLING_COEFFS = [-2.955065359477124183e-2, 6.4102564102564102564e-3,
+                    -1.9175269175269175269e-3, 8.4175084175084175084e-4,
+                    -5.952380952380952381e-4, 7.9365079365079365079e-4,
+                    -2.7777777777777777778e-3, 8.3333333333333333333e-2]
+
+
+def _log_nfactorial_div_n_pow_n(n):
+    # Computes n! / n**n
+    #    = (n-1)! / n**(n-1)
+    # Uses Stirling's approximation, but removes n*log(n) up-front to
+    # avoid subtractive cancellation.
+    #    = log(n)/2 - n + log(sqrt(2pi)) + sum B_{2j}/(2j)/(2j-1)/n**(2j-1)
+    rn = 1.0/n
+    return np.log(n)/2 - n + _LOG_2PI/2 + rn * np.polyval(_STIRLING_COEFFS, rn/n)
+
+
+def _clip_prob(p):
+    """clips a probability to range 0<=p<=1."""
+    return np.clip(p, 0.0, 1.0)
+
+
+def _select_and_clip_prob(cdfprob, sfprob, cdf=True):
+    """Selects either the CDF or SF, and then clips to range 0<=p<=1."""
+    p = np.where(cdf, cdfprob, sfprob)
+    return _clip_prob(p)
+
+
+def _kolmogn_DMTW(n, d, cdf=True):
+    r"""Computes the Kolmogorov CDF:  Pr(D_n <= d) using the MTW approach to
+    the Durbin matrix algorithm.
+
+    Durbin (1968); Marsaglia, Tsang, Wang (2003). [1], [3].
+    """
+    # Write d = (k-h)/n, where k is positive integer and 0 <= h < 1
+    # Generate initial matrix H of size m*m where m=(2k-1)
+    # Compute k-th row of (n!/n^n) * H^n, scaling intermediate results.
+    # Requires memory O(m^2) and computation O(m^2 log(n)).
+    # Most suitable for small m.
+
+    if d >= 1.0:
+        return _select_and_clip_prob(1.0, 0.0, cdf)
+    nd = n * d
+    if nd <= 0.5:
+        return _select_and_clip_prob(0.0, 1.0, cdf)
+    k = int(np.ceil(nd))
+    h = k - nd
+    m = 2 * k - 1
+
+    H = np.zeros([m, m])
+
+    # Initialize: v is first column (and last row) of H
+    #  v[j] = (1-h^(j+1)/(j+1)!  (except for v[-1])
+    #  w[j] = 1/(j)!
+    # q = k-th row of H (actually i!/n^i*H^i)
+    intm = np.arange(1, m + 1)
+    v = 1.0 - h ** intm
+    w = np.empty(m)
+    fac = 1.0
+    for j in intm:
+        w[j - 1] = fac
+        fac /= j  # This might underflow.  Isn't a problem.
+        v[j - 1] *= fac
+    tt = max(2 * h - 1.0, 0)**m - 2*h**m
+    v[-1] = (1.0 + tt) * fac
+
+    for i in range(1, m):
+        H[i - 1:, i] = w[:m - i + 1]
+    H[:, 0] = v
+    H[-1, :] = np.flip(v, axis=0)
+
+    Hpwr = np.eye(np.shape(H)[0])  # Holds intermediate powers of H
+    nn = n
+    expnt = 0  # Scaling of Hpwr
+    Hexpnt = 0  # Scaling of H
+    while nn > 0:
+        if nn % 2:
+            Hpwr = np.matmul(Hpwr, H)
+            expnt += Hexpnt
+        H = np.matmul(H, H)
+        Hexpnt *= 2
+        # Scale as needed.
+        if np.abs(H[k - 1, k - 1]) > _EP128:
+            H /= _EP128
+            Hexpnt += _E128
+        nn = nn // 2
+
+    p = Hpwr[k - 1, k - 1]
+
+    # Multiply by n!/n^n
+    for i in range(1, n + 1):
+        p = i * p / n
+        if np.abs(p) < _EM128:
+            p *= _EP128
+            expnt -= _E128
+
+    # unscale
+    if expnt != 0:
+        p = np.ldexp(p, expnt)
+
+    return _select_and_clip_prob(p, 1.0-p, cdf)
+
+
+def _pomeranz_compute_j1j2(i, n, ll, ceilf, roundf):
+    """Compute the endpoints of the interval for row i."""
+    if i == 0:
+        j1, j2 = -ll - ceilf - 1, ll + ceilf - 1
+    else:
+        # i + 1 = 2*ip1div2 + ip1mod2
+        ip1div2, ip1mod2 = divmod(i + 1, 2)
+        if ip1mod2 == 0:  # i is odd
+            if ip1div2 == n + 1:
+                j1, j2 = n - ll - ceilf - 1, n + ll + ceilf - 1
+            else:
+                j1, j2 = ip1div2 - 1 - ll - roundf - 1, ip1div2 + ll - 1 + ceilf - 1
+        else:
+            j1, j2 = ip1div2 - 1 - ll - 1, ip1div2 + ll + roundf - 1
+
+    return max(j1 + 2, 0), min(j2, n)
+
+
+def _kolmogn_Pomeranz(n, x, cdf=True):
+    r"""Computes Pr(D_n <= d) using the Pomeranz recursion algorithm.
+
+    Pomeranz (1974) [2]
+    """
+
+    # V is n*(2n+2) matrix.
+    # Each row is convolution of the previous row and probabilities from a
+    #  Poisson distribution.
+    # Desired CDF probability is n! V[n-1, 2n+1]  (final entry in final row).
+    # Only two rows are needed at any given stage:
+    #  - Call them V0 and V1.
+    #  - Swap each iteration
+    # Only a few (contiguous) entries in each row can be non-zero.
+    #  - Keep track of start and end (j1 and j2 below)
+    #  - V0s and V1s track the start in the two rows
+    # Scale intermediate results as needed.
+    # Only a few different Poisson distributions can occur
+    t = n * x
+    ll = int(np.floor(t))
+    f = 1.0 * (t - ll)  # fractional part of t
+    g = min(f, 1.0 - f)
+    ceilf = (1 if f > 0 else 0)
+    roundf = (1 if f > 0.5 else 0)
+    npwrs = 2 * (ll + 1)    # Maximum number of powers needed in convolutions
+    gpower = np.empty(npwrs)  # gpower = (g/n)^m/m!
+    twogpower = np.empty(npwrs)  # twogpower = (2g/n)^m/m!
+    onem2gpower = np.empty(npwrs)  # onem2gpower = ((1-2g)/n)^m/m!
+    # gpower etc are *almost* Poisson probs, just missing normalizing factor.
+
+    gpower[0] = 1.0
+    twogpower[0] = 1.0
+    onem2gpower[0] = 1.0
+    expnt = 0
+    g_over_n, two_g_over_n, one_minus_two_g_over_n = g/n, 2*g/n, (1 - 2*g)/n
+    for m in range(1, npwrs):
+        gpower[m] = gpower[m - 1] * g_over_n / m
+        twogpower[m] = twogpower[m - 1] * two_g_over_n / m
+        onem2gpower[m] = onem2gpower[m - 1] * one_minus_two_g_over_n / m
+
+    V0 = np.zeros([npwrs])
+    V1 = np.zeros([npwrs])
+    V1[0] = 1  # first row
+    V0s, V1s = 0, 0  # start indices of the two rows
+
+    j1, j2 = _pomeranz_compute_j1j2(0, n, ll, ceilf, roundf)
+    for i in range(1, 2 * n + 2):
+        # Preserve j1, V1, V1s, V0s from last iteration
+        k1 = j1
+        V0, V1 = V1, V0
+        V0s, V1s = V1s, V0s
+        V1.fill(0.0)
+        j1, j2 = _pomeranz_compute_j1j2(i, n, ll, ceilf, roundf)
+        if i == 1 or i == 2 * n + 1:
+            pwrs = gpower
+        else:
+            pwrs = (twogpower if i % 2 else onem2gpower)
+        ln2 = j2 - k1 + 1
+        if ln2 > 0:
+            conv = np.convolve(V0[k1 - V0s:k1 - V0s + ln2], pwrs[:ln2])
+            conv_start = j1 - k1  # First index to use from conv
+            conv_len = j2 - j1 + 1  # Number of entries to use from conv
+            V1[:conv_len] = conv[conv_start:conv_start + conv_len]
+            # Scale to avoid underflow.
+            if 0 < np.max(V1) < _EM128:
+                V1 *= _EP128
+                expnt -= _E128
+            V1s = V0s + j1 - k1
+
+    # multiply by n!
+    ans = V1[n - V1s]
+    for m in range(1, n + 1):
+        if np.abs(ans) > _EP128:
+            ans *= _EM128
+            expnt += _E128
+        ans *= m
+
+    # Undo any intermediate scaling
+    if expnt != 0:
+        ans = np.ldexp(ans, expnt)
+    ans = _select_and_clip_prob(ans, 1.0 - ans, cdf)
+    return ans
+
+
+def _kolmogn_PelzGood(n, x, cdf=True):
+    """Computes the Pelz-Good approximation to Prob(Dn <= x) with 0<=x<=1.
+
+    Start with Li-Chien, Korolyuk approximation:
+        Prob(Dn <= x) ~ K0(z) + K1(z)/sqrt(n) + K2(z)/n + K3(z)/n**1.5
+    where z = x*sqrt(n).
+    Transform each K_(z) using Jacobi theta functions into a form suitable
+    for small z.
+    Pelz-Good (1976). [6]
+    """
+    if x <= 0.0:
+        return _select_and_clip_prob(0.0, 1.0, cdf=cdf)
+    if x >= 1.0:
+        return _select_and_clip_prob(1.0, 0.0, cdf=cdf)
+
+    z = np.sqrt(n) * x
+    zsquared, zthree, zfour, zsix = z**2, z**3, z**4, z**6
+
+    qlog = -_PI_SQUARED / 8 / zsquared
+    if qlog < _MIN_LOG:  # z ~ 0.041743441416853426
+        return _select_and_clip_prob(0.0, 1.0, cdf=cdf)
+
+    q = np.exp(qlog)
+
+    # Coefficients of terms in the sums for K1, K2 and K3
+    k1a = -zsquared
+    k1b = _PI_SQUARED / 4
+
+    k2a = 6 * zsix + 2 * zfour
+    k2b = (2 * zfour - 5 * zsquared) * _PI_SQUARED / 4
+    k2c = _PI_FOUR * (1 - 2 * zsquared) / 16
+
+    k3d = _PI_SIX * (5 - 30 * zsquared) / 64
+    k3c = _PI_FOUR * (-60 * zsquared + 212 * zfour) / 16
+    k3b = _PI_SQUARED * (135 * zfour - 96 * zsix) / 4
+    k3a = -30 * zsix - 90 * z**8
+
+    K0to3 = np.zeros(4)
+    # Use a Horner scheme to evaluate sum c_i q^(i^2)
+    # Reduces to a sum over odd integers.
+    maxk = int(np.ceil(16 * z / np.pi))
+    for k in range(maxk, 0, -1):
+        m = 2 * k - 1
+        msquared, mfour, msix = m**2, m**4, m**6
+        qpower = np.power(q, 8 * k)
+        coeffs = np.array([1.0,
+                           k1a + k1b*msquared,
+                           k2a + k2b*msquared + k2c*mfour,
+                           k3a + k3b*msquared + k3c*mfour + k3d*msix])
+        K0to3 *= qpower
+        K0to3 += coeffs
+    K0to3 *= q
+    K0to3 *= _SQRT2PI
+    # z**10 > 0 as z > 0.04
+    K0to3 /= np.array([z, 6 * zfour, 72 * z**7, 6480 * z**10])
+
+    # Now do the other sum over the other terms, all integers k
+    # K_2:  (pi^2 k^2) q^(k^2),
+    # K_3:  (3pi^2 k^2 z^2 - pi^4 k^4)*q^(k^2)
+    # Don't expect much subtractive cancellation so use direct calculation
+    q = np.exp(-_PI_SQUARED / 2 / zsquared)
+    ks = np.arange(maxk, 0, -1)
+    ksquared = ks ** 2
+    sqrt3z = _SQRT3 * z
+    kspi = np.pi * ks
+    qpwers = q ** ksquared
+    k2extra = np.sum(ksquared * qpwers)
+    k2extra *= _PI_SQUARED * _SQRT2PI/(-36 * zthree)
+    K0to3[2] += k2extra
+    k3extra = np.sum((sqrt3z + kspi) * (sqrt3z - kspi) * ksquared * qpwers)
+    k3extra *= _PI_SQUARED * _SQRT2PI/(216 * zsix)
+    K0to3[3] += k3extra
+    powers_of_n = np.power(n * 1.0, np.arange(len(K0to3)) / 2.0)
+    K0to3 /= powers_of_n
+
+    if not cdf:
+        K0to3 *= -1
+        K0to3[0] += 1
+
+    Ksum = sum(K0to3)
+    return Ksum
+
+
+def _kolmogn(n, x, cdf=True):
+    """Computes the CDF(or SF) for the two-sided Kolmogorov-Smirnov statistic.
+
+    x must be of type float, n of type integer.
+
+    Simard & L'Ecuyer (2011) [7].
+    """
+    if np.isnan(n):
+        return n  # Keep the same type of nan
+    if int(n) != n or n <= 0:
+        return np.nan
+    if x >= 1.0:
+        return _select_and_clip_prob(1.0, 0.0, cdf=cdf)
+    if x <= 0.0:
+        return _select_and_clip_prob(0.0, 1.0, cdf=cdf)
+    t = n * x
+    if t <= 1.0:  # Ruben-Gambino: 1/2n <= x <= 1/n
+        if t <= 0.5:
+            return _select_and_clip_prob(0.0, 1.0, cdf=cdf)
+        if n <= 140:
+            prob = np.prod(np.arange(1, n+1) * (1.0/n) * (2*t - 1))
+        else:
+            prob = np.exp(_log_nfactorial_div_n_pow_n(n) + n * np.log(2*t-1))
+        return _select_and_clip_prob(prob, 1.0 - prob, cdf=cdf)
+    if t >= n - 1:  # Ruben-Gambino
+        prob = 2 * (1.0 - x)**n
+        return _select_and_clip_prob(1 - prob, prob, cdf=cdf)
+    if x >= 0.5:  # Exact: 2 * smirnov
+        prob = 2 * scipy.special.smirnov(n, x)
+        return _select_and_clip_prob(1.0 - prob, prob, cdf=cdf)
+
+    nxsquared = t * x
+    if n <= 140:
+        if nxsquared <= 0.754693:
+            prob = _kolmogn_DMTW(n, x, cdf=True)
+            return _select_and_clip_prob(prob, 1.0 - prob, cdf=cdf)
+        if nxsquared <= 4:
+            prob = _kolmogn_Pomeranz(n, x, cdf=True)
+            return _select_and_clip_prob(prob, 1.0 - prob, cdf=cdf)
+        # Now use Miller approximation of 2*smirnov
+        prob = 2 * scipy.special.smirnov(n, x)
+        return _select_and_clip_prob(1.0 - prob, prob, cdf=cdf)
+
+    # Split CDF and SF as they have different cutoffs on nxsquared.
+    if not cdf:
+        if nxsquared >= 370.0:
+            return 0.0
+        if nxsquared >= 2.2:
+            prob = 2 * scipy.special.smirnov(n, x)
+            return _clip_prob(prob)
+        # Fall through and compute the SF as 1.0-CDF
+    if nxsquared >= 18.0:
+        cdfprob = 1.0
+    elif n <= 100000 and n * x**1.5 <= 1.4:
+        cdfprob = _kolmogn_DMTW(n, x, cdf=True)
+    else:
+        cdfprob = _kolmogn_PelzGood(n, x, cdf=True)
+    return _select_and_clip_prob(cdfprob, 1.0 - cdfprob, cdf=cdf)
+
+
+def _kolmogn_p(n, x):
+    """Computes the PDF for the two-sided Kolmogorov-Smirnov statistic.
+
+    x must be of type float, n of type integer.
+    """
+    if np.isnan(n):
+        return n  # Keep the same type of nan
+    if int(n) != n or n <= 0:
+        return np.nan
+    if x >= 1.0 or x <= 0:
+        return 0
+    t = n * x
+    if t <= 1.0:
+        # Ruben-Gambino: n!/n^n * (2t-1)^n -> 2 n!/n^n * n^2 * (2t-1)^(n-1)
+        if t <= 0.5:
+            return 0.0
+        if n <= 140:
+            prd = np.prod(np.arange(1, n) * (1.0 / n) * (2 * t - 1))
+        else:
+            prd = np.exp(_log_nfactorial_div_n_pow_n(n) + (n-1) * np.log(2 * t - 1))
+        return prd * 2 * n**2
+    if t >= n - 1:
+        # Ruben-Gambino : 1-2(1-x)**n -> 2n*(1-x)**(n-1)
+        return 2 * (1.0 - x) ** (n-1) * n
+    if x >= 0.5:
+        return 2 * scipy.stats.ksone.pdf(x, n)
+
+    # Just take a small delta.
+    # Ideally x +/- delta would stay within [i/n, (i+1)/n] for some integer a.
+    # as the CDF is a piecewise degree n polynomial.
+    # It has knots at 1/n, 2/n, ... (n-1)/n
+    # and is not a C-infinity function at the knots
+    delta = x / 2.0**16
+    delta = min(delta, x - 1.0/n)
+    delta = min(delta, 0.5 - x)
+
+    def _kk(_x):
+        return kolmogn(n, _x)
+
+    return _derivative(_kk, x, dx=delta, order=5)
+
+
+def _kolmogni(n, p, q):
+    """Computes the PPF/ISF of kolmogn.
+
+    n of type integer, n>= 1
+    p is the CDF, q the SF, p+q=1
+    """
+    if np.isnan(n):
+        return n  # Keep the same type of nan
+    if int(n) != n or n <= 0:
+        return np.nan
+    if p <= 0:
+        return 1.0/n
+    if q <= 0:
+        return 1.0
+    delta = np.exp((np.log(p) - scipy.special.loggamma(n+1))/n)
+    if delta <= 1.0/n:
+        return (delta + 1.0 / n) / 2
+    x = -np.expm1(np.log(q/2.0)/n)
+    if x >= 1 - 1.0/n:
+        return x
+    x1 = scu._kolmogci(p)/np.sqrt(n)
+    x1 = min(x1, 1.0 - 1.0/n)
+
+    def _f(x):
+        return _kolmogn(n, x) - p
+
+    return scipy.optimize.brentq(_f, 1.0/n, x1, xtol=1e-14)
+
+
+def kolmogn(n, x, cdf=True):
+    """Computes the CDF for the two-sided Kolmogorov-Smirnov distribution.
+
+    The two-sided Kolmogorov-Smirnov distribution has as its CDF Pr(D_n <= x),
+    for a sample of size n drawn from a distribution with CDF F(t), where
+    :math:`D_n &= sup_t |F_n(t) - F(t)|`, and
+    :math:`F_n(t)` is the Empirical Cumulative Distribution Function of the sample.
+
+    Parameters
+    ----------
+    n : integer, array_like
+        the number of samples
+    x : float, array_like
+        The K-S statistic, float between 0 and 1
+    cdf : bool, optional
+        whether to compute the CDF(default=true) or the SF.
+
+    Returns
+    -------
+    cdf : ndarray
+        CDF (or SF it cdf is False) at the specified locations.
+
+    The return value has shape the result of numpy broadcasting n and x.
+    """
+    it = np.nditer([n, x, cdf, None], flags=['zerosize_ok'],
+                   op_dtypes=[None, np.float64, np.bool_, np.float64])
+    for _n, _x, _cdf, z in it:
+        if np.isnan(_n):
+            z[...] = _n
+            continue
+        if int(_n) != _n:
+            raise ValueError(f'n is not integral: {_n}')
+        z[...] = _kolmogn(int(_n), _x, cdf=_cdf)
+    result = it.operands[-1]
+    return result
+
+
+def kolmognp(n, x):
+    """Computes the PDF for the two-sided Kolmogorov-Smirnov distribution.
+
+    Parameters
+    ----------
+    n : integer, array_like
+        the number of samples
+    x : float, array_like
+        The K-S statistic, float between 0 and 1
+
+    Returns
+    -------
+    pdf : ndarray
+        The PDF at the specified locations
+
+    The return value has shape the result of numpy broadcasting n and x.
+    """
+    it = np.nditer([n, x, None])
+    for _n, _x, z in it:
+        if np.isnan(_n):
+            z[...] = _n
+            continue
+        if int(_n) != _n:
+            raise ValueError(f'n is not integral: {_n}')
+        z[...] = _kolmogn_p(int(_n), _x)
+    result = it.operands[-1]
+    return result
+
+
+def kolmogni(n, q, cdf=True):
+    """Computes the PPF(or ISF) for the two-sided Kolmogorov-Smirnov distribution.
+
+    Parameters
+    ----------
+    n : integer, array_like
+        the number of samples
+    q : float, array_like
+        Probabilities, float between 0 and 1
+    cdf : bool, optional
+        whether to compute the PPF(default=true) or the ISF.
+
+    Returns
+    -------
+    ppf : ndarray
+        PPF (or ISF if cdf is False) at the specified locations
+
+    The return value has shape the result of numpy broadcasting n and x.
+    """
+    it = np.nditer([n, q, cdf, None])
+    for _n, _q, _cdf, z in it:
+        if np.isnan(_n):
+            z[...] = _n
+            continue
+        if int(_n) != _n:
+            raise ValueError(f'n is not integral: {_n}')
+        _pcdf, _psf = (_q, 1-_q) if _cdf else (1-_q, _q)
+        z[...] = _kolmogni(int(_n), _pcdf, _psf)
+    result = it.operands[-1]
+    return result
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..96ae567e41429e652f1d4ad61b0512f1bc5c6615
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__init__.py
@@ -0,0 +1,1239 @@
+#
+
+import warnings
+from functools import partial
+
+import numpy as np
+
+from scipy import optimize
+from scipy import integrate
+from scipy.integrate._quadrature import _builtincoeffs
+from scipy import interpolate
+from scipy.interpolate import RectBivariateSpline
+import scipy.special as sc
+from scipy._lib._util import _lazywhere
+from .._distn_infrastructure import rv_continuous, _ShapeInfo, rv_continuous_frozen
+from .._continuous_distns import uniform, expon, _norm_pdf, _norm_cdf
+from .levyst import Nolan
+from scipy._lib.doccer import inherit_docstring_from
+
+
+__all__ = ["levy_stable", "levy_stable_gen", "pdf_from_cf_with_fft"]
+
+# Stable distributions are known for various parameterisations
+# some being advantageous for numerical considerations and others
+# useful due to their location/scale awareness.
+#
+# Here we follow [NO] convention (see the references in the docstring
+# for levy_stable_gen below).
+#
+# S0 / Z0 / x0 (aka Zoleterav's M)
+# S1 / Z1 / x1
+#
+# Where S* denotes parameterisation, Z* denotes standardized
+# version where gamma = 1, delta = 0 and x* denotes variable.
+#
+# Scipy's original Stable was a random variate generator. It
+# uses S1 and unfortunately is not a location/scale aware.
+
+
+# default numerical integration tolerance
+# used for epsrel in piecewise and both epsrel and epsabs in dni
+# (epsabs needed in dni since weighted quad requires epsabs > 0)
+_QUAD_EPS = 1.2e-14
+
+
+def _Phi_Z0(alpha, t):
+    return (
+        -np.tan(np.pi * alpha / 2) * (np.abs(t) ** (1 - alpha) - 1)
+        if alpha != 1
+        else -2.0 * np.log(np.abs(t)) / np.pi
+    )
+
+
+def _Phi_Z1(alpha, t):
+    return (
+        np.tan(np.pi * alpha / 2)
+        if alpha != 1
+        else -2.0 * np.log(np.abs(t)) / np.pi
+    )
+
+
+def _cf(Phi, t, alpha, beta):
+    """Characteristic function."""
+    return np.exp(
+        -(np.abs(t) ** alpha) * (1 - 1j * beta * np.sign(t) * Phi(alpha, t))
+    )
+
+
+_cf_Z0 = partial(_cf, _Phi_Z0)
+_cf_Z1 = partial(_cf, _Phi_Z1)
+
+
+def _pdf_single_value_cf_integrate(Phi, x, alpha, beta, **kwds):
+    """To improve DNI accuracy convert characteristic function in to real
+    valued integral using Euler's formula, then exploit cosine symmetry to
+    change limits to [0, inf). Finally use cosine addition formula to split
+    into two parts that can be handled by weighted quad pack.
+    """
+    quad_eps = kwds.get("quad_eps", _QUAD_EPS)
+
+    def integrand1(t):
+        if t == 0:
+            return 0
+        return np.exp(-(t ** alpha)) * (
+            np.cos(beta * (t ** alpha) * Phi(alpha, t))
+        )
+
+    def integrand2(t):
+        if t == 0:
+            return 0
+        return np.exp(-(t ** alpha)) * (
+            np.sin(beta * (t ** alpha) * Phi(alpha, t))
+        )
+
+    with np.errstate(invalid="ignore"):
+        int1, *ret1 = integrate.quad(
+            integrand1,
+            0,
+            np.inf,
+            weight="cos",
+            wvar=x,
+            limit=1000,
+            epsabs=quad_eps,
+            epsrel=quad_eps,
+            full_output=1,
+        )
+
+        int2, *ret2 = integrate.quad(
+            integrand2,
+            0,
+            np.inf,
+            weight="sin",
+            wvar=x,
+            limit=1000,
+            epsabs=quad_eps,
+            epsrel=quad_eps,
+            full_output=1,
+        )
+
+    return (int1 + int2) / np.pi
+
+
+_pdf_single_value_cf_integrate_Z0 = partial(
+    _pdf_single_value_cf_integrate, _Phi_Z0
+)
+_pdf_single_value_cf_integrate_Z1 = partial(
+    _pdf_single_value_cf_integrate, _Phi_Z1
+)
+
+
+def _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta):
+    """Round x close to zeta for Nolan's method in [NO]."""
+    #   "8. When |x0-beta*tan(pi*alpha/2)| is small, the
+    #   computations of the density and cumulative have numerical problems.
+    #   The program works around this by setting
+    #   z = beta*tan(pi*alpha/2) when
+    #   |z-beta*tan(pi*alpha/2)| < tol(5)*alpha**(1/alpha).
+    #   (The bound on the right is ad hoc, to get reasonable behavior
+    #   when alpha is small)."
+    # where tol(5) = 0.5e-2 by default.
+    #
+    # We seem to have partially addressed this through re-expression of
+    # g(theta) here, but it still needs to be used in some extreme cases.
+    # Perhaps tol(5) = 0.5e-2 could be reduced for our implementation.
+    if np.abs(x0 - zeta) < x_tol_near_zeta * alpha ** (1 / alpha):
+        x0 = zeta
+    return x0
+
+
+def _nolan_round_difficult_input(
+    x0, alpha, beta, zeta, x_tol_near_zeta, alpha_tol_near_one
+):
+    """Round difficult input values for Nolan's method in [NO]."""
+
+    # following Nolan's STABLE,
+    #   "1. When 0 < |alpha-1| < 0.005, the program has numerical problems
+    #   evaluating the pdf and cdf.  The current version of the program sets
+    #   alpha=1 in these cases. This approximation is not bad in the S0
+    #   parameterization."
+    if np.abs(alpha - 1) < alpha_tol_near_one:
+        alpha = 1.0
+
+    #   "2. When alpha=1 and |beta| < 0.005, the program has numerical
+    #   problems.  The current version sets beta=0."
+    # We seem to have addressed this through re-expression of g(theta) here
+
+    x0 = _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta)
+    return x0, alpha, beta
+
+
+def _pdf_single_value_piecewise_Z1(x, alpha, beta, **kwds):
+    # convert from Nolan's S_1 (aka S) to S_0 (aka Zolaterev M)
+    # parameterization
+
+    zeta = -beta * np.tan(np.pi * alpha / 2.0)
+    x0 = x + zeta if alpha != 1 else x
+
+    return _pdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds)
+
+
+def _pdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds):
+
+    quad_eps = kwds.get("quad_eps", _QUAD_EPS)
+    x_tol_near_zeta = kwds.get("piecewise_x_tol_near_zeta", 0.005)
+    alpha_tol_near_one = kwds.get("piecewise_alpha_tol_near_one", 0.005)
+
+    zeta = -beta * np.tan(np.pi * alpha / 2.0)
+    x0, alpha, beta = _nolan_round_difficult_input(
+        x0, alpha, beta, zeta, x_tol_near_zeta, alpha_tol_near_one
+    )
+
+    # some other known distribution pdfs / analytical cases
+    # TODO: add more where possible with test coverage,
+    # eg https://en.wikipedia.org/wiki/Stable_distribution#Other_analytic_cases
+    if alpha == 2.0:
+        # normal
+        return _norm_pdf(x0 / np.sqrt(2)) / np.sqrt(2)
+    elif alpha == 0.5 and beta == 1.0:
+        # levy
+        # since S(1/2, 1, gamma, delta; ) ==
+        # S(1/2, 1, gamma, gamma + delta; ).
+        _x = x0 + 1
+        if _x <= 0:
+            return 0
+
+        return 1 / np.sqrt(2 * np.pi * _x) / _x * np.exp(-1 / (2 * _x))
+    elif alpha == 0.5 and beta == 0.0 and x0 != 0:
+        # analytical solution [HO]
+        S, C = sc.fresnel([1 / np.sqrt(2 * np.pi * np.abs(x0))])
+        arg = 1 / (4 * np.abs(x0))
+        return (
+            np.sin(arg) * (0.5 - S[0]) + np.cos(arg) * (0.5 - C[0])
+        ) / np.sqrt(2 * np.pi * np.abs(x0) ** 3)
+    elif alpha == 1.0 and beta == 0.0:
+        # cauchy
+        return 1 / (1 + x0 ** 2) / np.pi
+
+    return _pdf_single_value_piecewise_post_rounding_Z0(
+        x0, alpha, beta, quad_eps, x_tol_near_zeta
+    )
+
+
+def _pdf_single_value_piecewise_post_rounding_Z0(x0, alpha, beta, quad_eps,
+                                                 x_tol_near_zeta):
+    """Calculate pdf using Nolan's methods as detailed in [NO]."""
+
+    _nolan = Nolan(alpha, beta, x0)
+    zeta = _nolan.zeta
+    xi = _nolan.xi
+    c2 = _nolan.c2
+    g = _nolan.g
+
+    # round x0 to zeta again if needed. zeta was recomputed and may have
+    # changed due to floating point differences.
+    # See https://github.com/scipy/scipy/pull/18133
+    x0 = _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta)
+    # handle Nolan's initial case logic
+    if x0 == zeta:
+        return (
+            sc.gamma(1 + 1 / alpha)
+            * np.cos(xi)
+            / np.pi
+            / ((1 + zeta ** 2) ** (1 / alpha / 2))
+        )
+    elif x0 < zeta:
+        return _pdf_single_value_piecewise_post_rounding_Z0(
+            -x0, alpha, -beta, quad_eps, x_tol_near_zeta
+        )
+
+    # following Nolan, we may now assume
+    #   x0 > zeta when alpha != 1
+    #   beta != 0 when alpha == 1
+
+    # spare calculating integral on null set
+    # use isclose as macos has fp differences
+    if np.isclose(-xi, np.pi / 2, rtol=1e-014, atol=1e-014):
+        return 0.0
+
+    def integrand(theta):
+        # limit any numerical issues leading to g_1 < 0 near theta limits
+        g_1 = g(theta)
+        if not np.isfinite(g_1) or g_1 < 0:
+            g_1 = 0
+        return g_1 * np.exp(-g_1)
+
+    with np.errstate(all="ignore"):
+        peak = optimize.bisect(
+            lambda t: g(t) - 1, -xi, np.pi / 2, xtol=quad_eps
+        )
+
+        # this integrand can be very peaked, so we need to force
+        # QUADPACK to evaluate the function inside its support
+        #
+
+        # lastly, we add additional samples at
+        #   ~exp(-100), ~exp(-10), ~exp(-5), ~exp(-1)
+        # to improve QUADPACK's detection of rapidly descending tail behavior
+        # (this choice is fairly ad hoc)
+        tail_points = [
+            optimize.bisect(lambda t: g(t) - exp_height, -xi, np.pi / 2)
+            for exp_height in [100, 10, 5]
+            # exp_height = 1 is handled by peak
+        ]
+        intg_points = [0, peak] + tail_points
+        intg, *ret = integrate.quad(
+            integrand,
+            -xi,
+            np.pi / 2,
+            points=intg_points,
+            limit=100,
+            epsrel=quad_eps,
+            epsabs=0,
+            full_output=1,
+        )
+
+    return c2 * intg
+
+
+def _cdf_single_value_piecewise_Z1(x, alpha, beta, **kwds):
+    # convert from Nolan's S_1 (aka S) to S_0 (aka Zolaterev M)
+    # parameterization
+
+    zeta = -beta * np.tan(np.pi * alpha / 2.0)
+    x0 = x + zeta if alpha != 1 else x
+
+    return _cdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds)
+
+
+def _cdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds):
+
+    quad_eps = kwds.get("quad_eps", _QUAD_EPS)
+    x_tol_near_zeta = kwds.get("piecewise_x_tol_near_zeta", 0.005)
+    alpha_tol_near_one = kwds.get("piecewise_alpha_tol_near_one", 0.005)
+
+    zeta = -beta * np.tan(np.pi * alpha / 2.0)
+    x0, alpha, beta = _nolan_round_difficult_input(
+        x0, alpha, beta, zeta, x_tol_near_zeta, alpha_tol_near_one
+    )
+
+    # some other known distribution cdfs / analytical cases
+    # TODO: add more where possible with test coverage,
+    # eg https://en.wikipedia.org/wiki/Stable_distribution#Other_analytic_cases
+    if alpha == 2.0:
+        # normal
+        return _norm_cdf(x0 / np.sqrt(2))
+    elif alpha == 0.5 and beta == 1.0:
+        # levy
+        # since S(1/2, 1, gamma, delta; ) ==
+        # S(1/2, 1, gamma, gamma + delta; ).
+        _x = x0 + 1
+        if _x <= 0:
+            return 0
+
+        return sc.erfc(np.sqrt(0.5 / _x))
+    elif alpha == 1.0 and beta == 0.0:
+        # cauchy
+        return 0.5 + np.arctan(x0) / np.pi
+
+    return _cdf_single_value_piecewise_post_rounding_Z0(
+        x0, alpha, beta, quad_eps, x_tol_near_zeta
+    )
+
+
+def _cdf_single_value_piecewise_post_rounding_Z0(x0, alpha, beta, quad_eps,
+                                                 x_tol_near_zeta):
+    """Calculate cdf using Nolan's methods as detailed in [NO]."""
+    _nolan = Nolan(alpha, beta, x0)
+    zeta = _nolan.zeta
+    xi = _nolan.xi
+    c1 = _nolan.c1
+    # c2 = _nolan.c2
+    c3 = _nolan.c3
+    g = _nolan.g
+    # round x0 to zeta again if needed. zeta was recomputed and may have
+    # changed due to floating point differences.
+    # See https://github.com/scipy/scipy/pull/18133
+    x0 = _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta)
+    # handle Nolan's initial case logic
+    if (alpha == 1 and beta < 0) or x0 < zeta:
+        # NOTE: Nolan's paper has a typo here!
+        # He states F(x) = 1 - F(x, alpha, -beta), but this is clearly
+        # incorrect since F(-infty) would be 1.0 in this case
+        # Indeed, the alpha != 1, x0 < zeta case is correct here.
+        return 1 - _cdf_single_value_piecewise_post_rounding_Z0(
+            -x0, alpha, -beta, quad_eps, x_tol_near_zeta
+        )
+    elif x0 == zeta:
+        return 0.5 - xi / np.pi
+
+    # following Nolan, we may now assume
+    #   x0 > zeta when alpha != 1
+    #   beta > 0 when alpha == 1
+
+    # spare calculating integral on null set
+    # use isclose as macos has fp differences
+    if np.isclose(-xi, np.pi / 2, rtol=1e-014, atol=1e-014):
+        return c1
+
+    def integrand(theta):
+        g_1 = g(theta)
+        return np.exp(-g_1)
+
+    with np.errstate(all="ignore"):
+        # shrink supports where required
+        left_support = -xi
+        right_support = np.pi / 2
+        if alpha > 1:
+            # integrand(t) monotonic 0 to 1
+            if integrand(-xi) != 0.0:
+                res = optimize.minimize(
+                    integrand,
+                    (-xi,),
+                    method="L-BFGS-B",
+                    bounds=[(-xi, np.pi / 2)],
+                )
+                left_support = res.x[0]
+        else:
+            # integrand(t) monotonic 1 to 0
+            if integrand(np.pi / 2) != 0.0:
+                res = optimize.minimize(
+                    integrand,
+                    (np.pi / 2,),
+                    method="L-BFGS-B",
+                    bounds=[(-xi, np.pi / 2)],
+                )
+                right_support = res.x[0]
+
+        intg, *ret = integrate.quad(
+            integrand,
+            left_support,
+            right_support,
+            points=[left_support, right_support],
+            limit=100,
+            epsrel=quad_eps,
+            epsabs=0,
+            full_output=1,
+        )
+
+    return c1 + c3 * intg
+
+
+def _rvs_Z1(alpha, beta, size=None, random_state=None):
+    """Simulate random variables using Nolan's methods as detailed in [NO].
+    """
+
+    def alpha1func(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W):
+        return (
+            2
+            / np.pi
+            * (
+                (np.pi / 2 + bTH) * tanTH
+                - beta * np.log((np.pi / 2 * W * cosTH) / (np.pi / 2 + bTH))
+            )
+        )
+
+    def beta0func(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W):
+        return (
+            W
+            / (cosTH / np.tan(aTH) + np.sin(TH))
+            * ((np.cos(aTH) + np.sin(aTH) * tanTH) / W) ** (1.0 / alpha)
+        )
+
+    def otherwise(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W):
+        # alpha is not 1 and beta is not 0
+        val0 = beta * np.tan(np.pi * alpha / 2)
+        th0 = np.arctan(val0) / alpha
+        val3 = W / (cosTH / np.tan(alpha * (th0 + TH)) + np.sin(TH))
+        res3 = val3 * (
+            (
+                np.cos(aTH)
+                + np.sin(aTH) * tanTH
+                - val0 * (np.sin(aTH) - np.cos(aTH) * tanTH)
+            )
+            / W
+        ) ** (1.0 / alpha)
+        return res3
+
+    def alphanot1func(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W):
+        res = _lazywhere(
+            beta == 0,
+            (alpha, beta, TH, aTH, bTH, cosTH, tanTH, W),
+            beta0func,
+            f2=otherwise,
+        )
+        return res
+
+    alpha = np.broadcast_to(alpha, size)
+    beta = np.broadcast_to(beta, size)
+    TH = uniform.rvs(
+        loc=-np.pi / 2.0, scale=np.pi, size=size, random_state=random_state
+    )
+    W = expon.rvs(size=size, random_state=random_state)
+    aTH = alpha * TH
+    bTH = beta * TH
+    cosTH = np.cos(TH)
+    tanTH = np.tan(TH)
+    res = _lazywhere(
+        alpha == 1,
+        (alpha, beta, TH, aTH, bTH, cosTH, tanTH, W),
+        alpha1func,
+        f2=alphanot1func,
+    )
+    return res
+
+
+def _fitstart_S0(data):
+    alpha, beta, delta1, gamma = _fitstart_S1(data)
+
+    # Formulas for mapping parameters in S1 parameterization to
+    # those in S0 parameterization can be found in [NO]. Note that
+    # only delta changes.
+    if alpha != 1:
+        delta0 = delta1 + beta * gamma * np.tan(np.pi * alpha / 2.0)
+    else:
+        delta0 = delta1 + 2 * beta * gamma * np.log(gamma) / np.pi
+
+    return alpha, beta, delta0, gamma
+
+
+def _fitstart_S1(data):
+    # We follow McCullock 1986 method - Simple Consistent Estimators
+    # of Stable Distribution Parameters
+
+    # fmt: off
+    # Table III and IV
+    nu_alpha_range = [2.439, 2.5, 2.6, 2.7, 2.8, 3, 3.2, 3.5, 4,
+                      5, 6, 8, 10, 15, 25]
+    nu_beta_range = [0, 0.1, 0.2, 0.3, 0.5, 0.7, 1]
+
+    # table III - alpha = psi_1(nu_alpha, nu_beta)
+    alpha_table = np.array([
+        [2.000, 2.000, 2.000, 2.000, 2.000, 2.000, 2.000],
+        [1.916, 1.924, 1.924, 1.924, 1.924, 1.924, 1.924],
+        [1.808, 1.813, 1.829, 1.829, 1.829, 1.829, 1.829],
+        [1.729, 1.730, 1.737, 1.745, 1.745, 1.745, 1.745],
+        [1.664, 1.663, 1.663, 1.668, 1.676, 1.676, 1.676],
+        [1.563, 1.560, 1.553, 1.548, 1.547, 1.547, 1.547],
+        [1.484, 1.480, 1.471, 1.460, 1.448, 1.438, 1.438],
+        [1.391, 1.386, 1.378, 1.364, 1.337, 1.318, 1.318],
+        [1.279, 1.273, 1.266, 1.250, 1.210, 1.184, 1.150],
+        [1.128, 1.121, 1.114, 1.101, 1.067, 1.027, 0.973],
+        [1.029, 1.021, 1.014, 1.004, 0.974, 0.935, 0.874],
+        [0.896, 0.892, 0.884, 0.883, 0.855, 0.823, 0.769],
+        [0.818, 0.812, 0.806, 0.801, 0.780, 0.756, 0.691],
+        [0.698, 0.695, 0.692, 0.689, 0.676, 0.656, 0.597],
+        [0.593, 0.590, 0.588, 0.586, 0.579, 0.563, 0.513]]).T
+    # transpose because interpolation with `RectBivariateSpline` is with
+    # `nu_beta` as `x` and `nu_alpha` as `y`
+
+    # table IV - beta = psi_2(nu_alpha, nu_beta)
+    beta_table = np.array([
+        [0, 2.160, 1.000, 1.000, 1.000, 1.000, 1.000],
+        [0, 1.592, 3.390, 1.000, 1.000, 1.000, 1.000],
+        [0, 0.759, 1.800, 1.000, 1.000, 1.000, 1.000],
+        [0, 0.482, 1.048, 1.694, 1.000, 1.000, 1.000],
+        [0, 0.360, 0.760, 1.232, 2.229, 1.000, 1.000],
+        [0, 0.253, 0.518, 0.823, 1.575, 1.000, 1.000],
+        [0, 0.203, 0.410, 0.632, 1.244, 1.906, 1.000],
+        [0, 0.165, 0.332, 0.499, 0.943, 1.560, 1.000],
+        [0, 0.136, 0.271, 0.404, 0.689, 1.230, 2.195],
+        [0, 0.109, 0.216, 0.323, 0.539, 0.827, 1.917],
+        [0, 0.096, 0.190, 0.284, 0.472, 0.693, 1.759],
+        [0, 0.082, 0.163, 0.243, 0.412, 0.601, 1.596],
+        [0, 0.074, 0.147, 0.220, 0.377, 0.546, 1.482],
+        [0, 0.064, 0.128, 0.191, 0.330, 0.478, 1.362],
+        [0, 0.056, 0.112, 0.167, 0.285, 0.428, 1.274]]).T
+
+    # Table V and VII
+    # These are ordered with decreasing `alpha_range`; so we will need to
+    # reverse them as required by RectBivariateSpline.
+    alpha_range = [2, 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1,
+                   1, 0.9, 0.8, 0.7, 0.6, 0.5][::-1]
+    beta_range = [0, 0.25, 0.5, 0.75, 1]
+
+    # Table V - nu_c = psi_3(alpha, beta)
+    nu_c_table = np.array([
+        [1.908, 1.908, 1.908, 1.908, 1.908],
+        [1.914, 1.915, 1.916, 1.918, 1.921],
+        [1.921, 1.922, 1.927, 1.936, 1.947],
+        [1.927, 1.930, 1.943, 1.961, 1.987],
+        [1.933, 1.940, 1.962, 1.997, 2.043],
+        [1.939, 1.952, 1.988, 2.045, 2.116],
+        [1.946, 1.967, 2.022, 2.106, 2.211],
+        [1.955, 1.984, 2.067, 2.188, 2.333],
+        [1.965, 2.007, 2.125, 2.294, 2.491],
+        [1.980, 2.040, 2.205, 2.435, 2.696],
+        [2.000, 2.085, 2.311, 2.624, 2.973],
+        [2.040, 2.149, 2.461, 2.886, 3.356],
+        [2.098, 2.244, 2.676, 3.265, 3.912],
+        [2.189, 2.392, 3.004, 3.844, 4.775],
+        [2.337, 2.634, 3.542, 4.808, 6.247],
+        [2.588, 3.073, 4.534, 6.636, 9.144]])[::-1].T
+    # transpose because interpolation with `RectBivariateSpline` is with
+    # `beta` as `x` and `alpha` as `y`
+
+    # Table VII - nu_zeta = psi_5(alpha, beta)
+    nu_zeta_table = np.array([
+        [0, 0.000, 0.000, 0.000, 0.000],
+        [0, -0.017, -0.032, -0.049, -0.064],
+        [0, -0.030, -0.061, -0.092, -0.123],
+        [0, -0.043, -0.088, -0.132, -0.179],
+        [0, -0.056, -0.111, -0.170, -0.232],
+        [0, -0.066, -0.134, -0.206, -0.283],
+        [0, -0.075, -0.154, -0.241, -0.335],
+        [0, -0.084, -0.173, -0.276, -0.390],
+        [0, -0.090, -0.192, -0.310, -0.447],
+        [0, -0.095, -0.208, -0.346, -0.508],
+        [0, -0.098, -0.223, -0.380, -0.576],
+        [0, -0.099, -0.237, -0.424, -0.652],
+        [0, -0.096, -0.250, -0.469, -0.742],
+        [0, -0.089, -0.262, -0.520, -0.853],
+        [0, -0.078, -0.272, -0.581, -0.997],
+        [0, -0.061, -0.279, -0.659, -1.198]])[::-1].T
+    # fmt: on
+
+    psi_1 = RectBivariateSpline(nu_beta_range, nu_alpha_range,
+                                alpha_table, kx=1, ky=1, s=0)
+
+    def psi_1_1(nu_beta, nu_alpha):
+        return psi_1(nu_beta, nu_alpha) \
+            if nu_beta > 0 else psi_1(-nu_beta, nu_alpha)
+
+    psi_2 = RectBivariateSpline(nu_beta_range, nu_alpha_range,
+                                beta_table, kx=1, ky=1, s=0)
+
+    def psi_2_1(nu_beta, nu_alpha):
+        return psi_2(nu_beta, nu_alpha) \
+            if nu_beta > 0 else -psi_2(-nu_beta, nu_alpha)
+
+    phi_3 = RectBivariateSpline(beta_range, alpha_range, nu_c_table,
+                                kx=1, ky=1, s=0)
+
+    def phi_3_1(beta, alpha):
+        return phi_3(beta, alpha) if beta > 0 else phi_3(-beta, alpha)
+
+    phi_5 = RectBivariateSpline(beta_range, alpha_range, nu_zeta_table,
+                                kx=1, ky=1, s=0)
+
+    def phi_5_1(beta, alpha):
+        return phi_5(beta, alpha) if beta > 0 else -phi_5(-beta, alpha)
+
+    # quantiles
+    p05 = np.percentile(data, 5)
+    p50 = np.percentile(data, 50)
+    p95 = np.percentile(data, 95)
+    p25 = np.percentile(data, 25)
+    p75 = np.percentile(data, 75)
+
+    nu_alpha = (p95 - p05) / (p75 - p25)
+    nu_beta = (p95 + p05 - 2 * p50) / (p95 - p05)
+
+    if nu_alpha >= 2.439:
+        eps = np.finfo(float).eps
+        alpha = np.clip(psi_1_1(nu_beta, nu_alpha)[0, 0], eps, 2.)
+        beta = np.clip(psi_2_1(nu_beta, nu_alpha)[0, 0], -1.0, 1.0)
+    else:
+        alpha = 2.0
+        beta = np.sign(nu_beta)
+    c = (p75 - p25) / phi_3_1(beta, alpha)[0, 0]
+    zeta = p50 + c * phi_5_1(beta, alpha)[0, 0]
+    delta = zeta-beta*c*np.tan(np.pi*alpha/2.) if alpha != 1. else zeta
+
+    return (alpha, beta, delta, c)
+
+
+class levy_stable_gen(rv_continuous):
+    r"""A Levy-stable continuous random variable.
+
+    %(before_notes)s
+
+    See Also
+    --------
+    levy, levy_l, cauchy, norm
+
+    Notes
+    -----
+    The distribution for `levy_stable` has characteristic function:
+
+    .. math::
+
+        \varphi(t, \alpha, \beta, c, \mu) =
+        e^{it\mu -|ct|^{\alpha}(1-i\beta\operatorname{sign}(t)\Phi(\alpha, t))}
+
+    where two different parameterizations are supported. The first :math:`S_1`:
+
+    .. math::
+
+        \Phi = \begin{cases}
+                \tan \left({\frac {\pi \alpha }{2}}\right)&\alpha \neq 1\\
+                -{\frac {2}{\pi }}\log |t|&\alpha =1
+                \end{cases}
+
+    The second :math:`S_0`:
+
+    .. math::
+
+        \Phi = \begin{cases}
+                -\tan \left({\frac {\pi \alpha }{2}}\right)(|ct|^{1-\alpha}-1)
+                &\alpha \neq 1\\
+                -{\frac {2}{\pi }}\log |ct|&\alpha =1
+                \end{cases}
+
+
+    The probability density function for `levy_stable` is:
+
+    .. math::
+
+        f(x) = \frac{1}{2\pi}\int_{-\infty}^\infty \varphi(t)e^{-ixt}\,dt
+
+    where :math:`-\infty < t < \infty`. This integral does not have a known
+    closed form.
+
+    `levy_stable` generalizes several distributions.  Where possible, they
+    should be used instead.  Specifically, when the shape parameters
+    assume the values in the table below, the corresponding equivalent
+    distribution should be used.
+
+    =========  ========  ===========
+    ``alpha``  ``beta``   Equivalent
+    =========  ========  ===========
+     1/2       -1        `levy_l`
+     1/2       1         `levy`
+     1         0         `cauchy`
+     2         any       `norm` (with ``scale=sqrt(2)``)
+    =========  ========  ===========
+
+    Evaluation of the pdf uses Nolan's piecewise integration approach with the
+    Zolotarev :math:`M` parameterization by default. There is also the option
+    to use direct numerical integration of the standard parameterization of the
+    characteristic function or to evaluate by taking the FFT of the
+    characteristic function.
+
+    The default method can changed by setting the class variable
+    ``levy_stable.pdf_default_method`` to one of 'piecewise' for Nolan's
+    approach, 'dni' for direct numerical integration, or 'fft-simpson' for the
+    FFT based approach. For the sake of backwards compatibility, the methods
+    'best' and 'zolotarev' are equivalent to 'piecewise' and the method
+    'quadrature' is equivalent to 'dni'.
+
+    The parameterization can be changed  by setting the class variable
+    ``levy_stable.parameterization`` to either 'S0' or 'S1'.
+    The default is 'S1'.
+
+    To improve performance of piecewise and direct numerical integration one
+    can specify ``levy_stable.quad_eps`` (defaults to 1.2e-14). This is used
+    as both the absolute and relative quadrature tolerance for direct numerical
+    integration and as the relative quadrature tolerance for the piecewise
+    method. One can also specify ``levy_stable.piecewise_x_tol_near_zeta``
+    (defaults to 0.005) for how close x is to zeta before it is considered the
+    same as x [NO]. The exact check is
+    ``abs(x0 - zeta) < piecewise_x_tol_near_zeta*alpha**(1/alpha)``. One can
+    also specify ``levy_stable.piecewise_alpha_tol_near_one`` (defaults to
+    0.005) for how close alpha is to 1 before being considered equal to 1.
+
+    To increase accuracy of FFT calculation one can specify
+    ``levy_stable.pdf_fft_grid_spacing`` (defaults to 0.001) and
+    ``pdf_fft_n_points_two_power`` (defaults to None which means a value is
+    calculated that sufficiently covers the input range).
+
+    Further control over FFT calculation is available by setting
+    ``pdf_fft_interpolation_degree`` (defaults to 3) for spline order and
+    ``pdf_fft_interpolation_level`` for determining the number of points to use
+    in the Newton-Cotes formula when approximating the characteristic function
+    (considered experimental).
+
+    Evaluation of the cdf uses Nolan's piecewise integration approach with the
+    Zolatarev :math:`S_0` parameterization by default. There is also the option
+    to evaluate through integration of an interpolated spline of the pdf
+    calculated by means of the FFT method. The settings affecting FFT
+    calculation are the same as for pdf calculation. The default cdf method can
+    be changed by setting ``levy_stable.cdf_default_method`` to either
+    'piecewise' or 'fft-simpson'.  For cdf calculations the Zolatarev method is
+    superior in accuracy, so FFT is disabled by default.
+
+    Fitting estimate uses quantile estimation method in [MC]. MLE estimation of
+    parameters in fit method uses this quantile estimate initially. Note that
+    MLE doesn't always converge if using FFT for pdf calculations; this will be
+    the case if alpha <= 1 where the FFT approach doesn't give good
+    approximations.
+
+    Any non-missing value for the attribute
+    ``levy_stable.pdf_fft_min_points_threshold`` will set
+    ``levy_stable.pdf_default_method`` to 'fft-simpson' if a valid
+    default method is not otherwise set.
+
+
+
+    .. warning::
+
+        For pdf calculations FFT calculation is considered experimental.
+
+        For cdf calculations FFT calculation is considered experimental. Use
+        Zolatarev's method instead (default).
+
+    The probability density above is defined in the "standardized" form. To
+    shift and/or scale the distribution use the ``loc`` and ``scale``
+    parameters.
+    Generally ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically
+    equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with
+    ``y = (x - loc) / scale``, except in the ``S1`` parameterization if
+    ``alpha == 1``.  In that case ``%(name)s.pdf(x, %(shapes)s, loc, scale)``
+    is identically equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with
+    ``y = (x - loc - 2 * beta * scale * np.log(scale) / np.pi) / scale``.
+    See [NO2]_ Definition 1.8 for more information.
+    Note that shifting the location of a distribution
+    does not make it a "noncentral" distribution.
+
+    References
+    ----------
+    .. [MC] McCulloch, J., 1986. Simple consistent estimators of stable
+        distribution parameters. Communications in Statistics - Simulation and
+        Computation 15, 11091136.
+    .. [WZ] Wang, Li and Zhang, Ji-Hong, 2008. Simpson's rule based FFT method
+        to compute densities of stable distribution.
+    .. [NO] Nolan, J., 1997. Numerical Calculation of Stable Densities and
+        distributions Functions.
+    .. [NO2] Nolan, J., 2018. Stable Distributions: Models for Heavy Tailed
+        Data.
+    .. [HO] Hopcraft, K. I., Jakeman, E., Tanner, R. M. J., 1999. Lévy random
+        walks with fluctuating step number and multiscale behavior.
+
+    %(example)s
+
+    """
+    # Configurable options as class variables
+    # (accessible from self by attribute lookup).
+    parameterization = "S1"
+    pdf_default_method = "piecewise"
+    cdf_default_method = "piecewise"
+    quad_eps = _QUAD_EPS
+    piecewise_x_tol_near_zeta = 0.005
+    piecewise_alpha_tol_near_one = 0.005
+    pdf_fft_min_points_threshold = None
+    pdf_fft_grid_spacing = 0.001
+    pdf_fft_n_points_two_power = None
+    pdf_fft_interpolation_level = 3
+    pdf_fft_interpolation_degree = 3
+
+    def __call__(self, *args, **params):
+        dist = levy_stable_frozen(self, *args, **params)
+        dist.parameterization = self.parameterization
+        return dist
+
+    def _argcheck(self, alpha, beta):
+        return (alpha > 0) & (alpha <= 2) & (beta <= 1) & (beta >= -1)
+
+    def _shape_info(self):
+        ialpha = _ShapeInfo("alpha", False, (0, 2), (False, True))
+        ibeta = _ShapeInfo("beta", False, (-1, 1), (True, True))
+        return [ialpha, ibeta]
+
+    def _parameterization(self):
+        allowed = ("S0", "S1")
+        pz = self.parameterization
+        if pz not in allowed:
+            raise RuntimeError(
+                f"Parameterization '{pz}' in supported list: {allowed}"
+            )
+        return pz
+
+    @inherit_docstring_from(rv_continuous)
+    def rvs(self, *args, **kwds):
+        X1 = super().rvs(*args, **kwds)
+
+        kwds.pop("discrete", None)
+        kwds.pop("random_state", None)
+        (alpha, beta), delta, gamma, size = self._parse_args_rvs(*args, **kwds)
+
+        # shift location for this parameterisation (S1)
+        X1 = np.where(
+            alpha == 1.0, X1 + 2 * beta * gamma * np.log(gamma) / np.pi, X1
+        )
+
+        if self._parameterization() == "S0":
+            return np.where(
+                alpha == 1.0,
+                X1 - (beta * 2 * gamma * np.log(gamma) / np.pi),
+                X1 - gamma * beta * np.tan(np.pi * alpha / 2.0),
+            )
+        elif self._parameterization() == "S1":
+            return X1
+
+    def _rvs(self, alpha, beta, size=None, random_state=None):
+        return _rvs_Z1(alpha, beta, size, random_state)
+
+    @inherit_docstring_from(rv_continuous)
+    def pdf(self, x, *args, **kwds):
+        # override base class version to correct
+        # location for S1 parameterization
+        if self._parameterization() == "S0":
+            return super().pdf(x, *args, **kwds)
+        elif self._parameterization() == "S1":
+            (alpha, beta), delta, gamma = self._parse_args(*args, **kwds)
+            if np.all(np.reshape(alpha, (1, -1))[0, :] != 1):
+                return super().pdf(x, *args, **kwds)
+            else:
+                # correct location for this parameterisation
+                x = np.reshape(x, (1, -1))[0, :]
+                x, alpha, beta = np.broadcast_arrays(x, alpha, beta)
+
+                data_in = np.dstack((x, alpha, beta))[0]
+                data_out = np.empty(shape=(len(data_in), 1))
+                # group data in unique arrays of alpha, beta pairs
+                uniq_param_pairs = np.unique(data_in[:, 1:], axis=0)
+                for pair in uniq_param_pairs:
+                    _alpha, _beta = pair
+                    _delta = (
+                        delta + 2 * _beta * gamma * np.log(gamma) / np.pi
+                        if _alpha == 1.0
+                        else delta
+                    )
+                    data_mask = np.all(data_in[:, 1:] == pair, axis=-1)
+                    _x = data_in[data_mask, 0]
+                    data_out[data_mask] = (
+                        super()
+                        .pdf(_x, _alpha, _beta, loc=_delta, scale=gamma)
+                        .reshape(len(_x), 1)
+                    )
+                output = data_out.T[0]
+                if output.shape == (1,):
+                    return output[0]
+                return output
+
+    def _pdf(self, x, alpha, beta):
+        if self._parameterization() == "S0":
+            _pdf_single_value_piecewise = _pdf_single_value_piecewise_Z0
+            _pdf_single_value_cf_integrate = _pdf_single_value_cf_integrate_Z0
+            _cf = _cf_Z0
+        elif self._parameterization() == "S1":
+            _pdf_single_value_piecewise = _pdf_single_value_piecewise_Z1
+            _pdf_single_value_cf_integrate = _pdf_single_value_cf_integrate_Z1
+            _cf = _cf_Z1
+
+        x = np.asarray(x).reshape(1, -1)[0, :]
+
+        x, alpha, beta = np.broadcast_arrays(x, alpha, beta)
+
+        data_in = np.dstack((x, alpha, beta))[0]
+        data_out = np.empty(shape=(len(data_in), 1))
+
+        pdf_default_method_name = self.pdf_default_method
+        if pdf_default_method_name in ("piecewise", "best", "zolotarev"):
+            pdf_single_value_method = _pdf_single_value_piecewise
+        elif pdf_default_method_name in ("dni", "quadrature"):
+            pdf_single_value_method = _pdf_single_value_cf_integrate
+        elif (
+            pdf_default_method_name == "fft-simpson"
+            or self.pdf_fft_min_points_threshold is not None
+        ):
+            pdf_single_value_method = None
+
+        pdf_single_value_kwds = {
+            "quad_eps": self.quad_eps,
+            "piecewise_x_tol_near_zeta": self.piecewise_x_tol_near_zeta,
+            "piecewise_alpha_tol_near_one": self.piecewise_alpha_tol_near_one,
+        }
+
+        fft_grid_spacing = self.pdf_fft_grid_spacing
+        fft_n_points_two_power = self.pdf_fft_n_points_two_power
+        fft_interpolation_level = self.pdf_fft_interpolation_level
+        fft_interpolation_degree = self.pdf_fft_interpolation_degree
+
+        # group data in unique arrays of alpha, beta pairs
+        uniq_param_pairs = np.unique(data_in[:, 1:], axis=0)
+        for pair in uniq_param_pairs:
+            data_mask = np.all(data_in[:, 1:] == pair, axis=-1)
+            data_subset = data_in[data_mask]
+            if pdf_single_value_method is not None:
+                data_out[data_mask] = np.array(
+                    [
+                        pdf_single_value_method(
+                            _x, _alpha, _beta, **pdf_single_value_kwds
+                        )
+                        for _x, _alpha, _beta in data_subset
+                    ]
+                ).reshape(len(data_subset), 1)
+            else:
+                warnings.warn(
+                    "Density calculations experimental for FFT method."
+                    + " Use combination of piecewise and dni methods instead.",
+                    RuntimeWarning, stacklevel=3,
+                )
+                _alpha, _beta = pair
+                _x = data_subset[:, (0,)]
+
+                if _alpha < 1.0:
+                    raise RuntimeError(
+                        "FFT method does not work well for alpha less than 1."
+                    )
+
+                # need enough points to "cover" _x for interpolation
+                if fft_grid_spacing is None and fft_n_points_two_power is None:
+                    raise ValueError(
+                        "One of fft_grid_spacing or fft_n_points_two_power "
+                        + "needs to be set."
+                    )
+                max_abs_x = np.max(np.abs(_x))
+                h = (
+                    2 ** (3 - fft_n_points_two_power) * max_abs_x
+                    if fft_grid_spacing is None
+                    else fft_grid_spacing
+                )
+                q = (
+                    np.ceil(np.log(2 * max_abs_x / h) / np.log(2)) + 2
+                    if fft_n_points_two_power is None
+                    else int(fft_n_points_two_power)
+                )
+
+                # for some parameters, the range of x can be quite
+                # large, let's choose an arbitrary cut off (8GB) to save on
+                # computer memory.
+                MAX_Q = 30
+                if q > MAX_Q:
+                    raise RuntimeError(
+                        "fft_n_points_two_power has a maximum "
+                        + f"value of {MAX_Q}"
+                    )
+
+                density_x, density = pdf_from_cf_with_fft(
+                    lambda t: _cf(t, _alpha, _beta),
+                    h=h,
+                    q=q,
+                    level=fft_interpolation_level,
+                )
+                f = interpolate.InterpolatedUnivariateSpline(
+                    density_x, np.real(density), k=fft_interpolation_degree
+                )  # patch FFT to use cubic
+                data_out[data_mask] = f(_x)
+
+        return data_out.T[0]
+
+    @inherit_docstring_from(rv_continuous)
+    def cdf(self, x, *args, **kwds):
+        # override base class version to correct
+        # location for S1 parameterization
+        # NOTE: this is near identical to pdf() above
+        if self._parameterization() == "S0":
+            return super().cdf(x, *args, **kwds)
+        elif self._parameterization() == "S1":
+            (alpha, beta), delta, gamma = self._parse_args(*args, **kwds)
+            if np.all(np.reshape(alpha, (1, -1))[0, :] != 1):
+                return super().cdf(x, *args, **kwds)
+            else:
+                # correct location for this parameterisation
+                x = np.reshape(x, (1, -1))[0, :]
+                x, alpha, beta = np.broadcast_arrays(x, alpha, beta)
+
+                data_in = np.dstack((x, alpha, beta))[0]
+                data_out = np.empty(shape=(len(data_in), 1))
+                # group data in unique arrays of alpha, beta pairs
+                uniq_param_pairs = np.unique(data_in[:, 1:], axis=0)
+                for pair in uniq_param_pairs:
+                    _alpha, _beta = pair
+                    _delta = (
+                        delta + 2 * _beta * gamma * np.log(gamma) / np.pi
+                        if _alpha == 1.0
+                        else delta
+                    )
+                    data_mask = np.all(data_in[:, 1:] == pair, axis=-1)
+                    _x = data_in[data_mask, 0]
+                    data_out[data_mask] = (
+                        super()
+                        .cdf(_x, _alpha, _beta, loc=_delta, scale=gamma)
+                        .reshape(len(_x), 1)
+                    )
+                output = data_out.T[0]
+                if output.shape == (1,):
+                    return output[0]
+                return output
+
+    def _cdf(self, x, alpha, beta):
+        if self._parameterization() == "S0":
+            _cdf_single_value_piecewise = _cdf_single_value_piecewise_Z0
+            _cf = _cf_Z0
+        elif self._parameterization() == "S1":
+            _cdf_single_value_piecewise = _cdf_single_value_piecewise_Z1
+            _cf = _cf_Z1
+
+        x = np.asarray(x).reshape(1, -1)[0, :]
+
+        x, alpha, beta = np.broadcast_arrays(x, alpha, beta)
+
+        data_in = np.dstack((x, alpha, beta))[0]
+        data_out = np.empty(shape=(len(data_in), 1))
+
+        cdf_default_method_name = self.cdf_default_method
+        if cdf_default_method_name == "piecewise":
+            cdf_single_value_method = _cdf_single_value_piecewise
+        elif cdf_default_method_name == "fft-simpson":
+            cdf_single_value_method = None
+
+        cdf_single_value_kwds = {
+            "quad_eps": self.quad_eps,
+            "piecewise_x_tol_near_zeta": self.piecewise_x_tol_near_zeta,
+            "piecewise_alpha_tol_near_one": self.piecewise_alpha_tol_near_one,
+        }
+
+        fft_grid_spacing = self.pdf_fft_grid_spacing
+        fft_n_points_two_power = self.pdf_fft_n_points_two_power
+        fft_interpolation_level = self.pdf_fft_interpolation_level
+        fft_interpolation_degree = self.pdf_fft_interpolation_degree
+
+        # group data in unique arrays of alpha, beta pairs
+        uniq_param_pairs = np.unique(data_in[:, 1:], axis=0)
+        for pair in uniq_param_pairs:
+            data_mask = np.all(data_in[:, 1:] == pair, axis=-1)
+            data_subset = data_in[data_mask]
+            if cdf_single_value_method is not None:
+                data_out[data_mask] = np.array(
+                    [
+                        cdf_single_value_method(
+                            _x, _alpha, _beta, **cdf_single_value_kwds
+                        )
+                        for _x, _alpha, _beta in data_subset
+                    ]
+                ).reshape(len(data_subset), 1)
+            else:
+                warnings.warn(
+                    "Cumulative density calculations experimental for FFT"
+                    + " method. Use piecewise method instead.",
+                    RuntimeWarning, stacklevel=3,
+                )
+                _alpha, _beta = pair
+                _x = data_subset[:, (0,)]
+
+                # need enough points to "cover" _x for interpolation
+                if fft_grid_spacing is None and fft_n_points_two_power is None:
+                    raise ValueError(
+                        "One of fft_grid_spacing or fft_n_points_two_power "
+                        + "needs to be set."
+                    )
+                max_abs_x = np.max(np.abs(_x))
+                h = (
+                    2 ** (3 - fft_n_points_two_power) * max_abs_x
+                    if fft_grid_spacing is None
+                    else fft_grid_spacing
+                )
+                q = (
+                    np.ceil(np.log(2 * max_abs_x / h) / np.log(2)) + 2
+                    if fft_n_points_two_power is None
+                    else int(fft_n_points_two_power)
+                )
+
+                density_x, density = pdf_from_cf_with_fft(
+                    lambda t: _cf(t, _alpha, _beta),
+                    h=h,
+                    q=q,
+                    level=fft_interpolation_level,
+                )
+                f = interpolate.InterpolatedUnivariateSpline(
+                    density_x, np.real(density), k=fft_interpolation_degree
+                )
+                data_out[data_mask] = np.array(
+                    [f.integral(self.a, float(x_1.squeeze())) for x_1 in _x]
+                ).reshape(data_out[data_mask].shape)
+
+        return data_out.T[0]
+
+    def _fitstart(self, data):
+        if self._parameterization() == "S0":
+            _fitstart = _fitstart_S0
+        elif self._parameterization() == "S1":
+            _fitstart = _fitstart_S1
+        return _fitstart(data)
+
+    def _stats(self, alpha, beta):
+        mu = 0 if alpha > 1 else np.nan
+        mu2 = 2 if alpha == 2 else np.inf
+        g1 = 0.0 if alpha == 2.0 else np.nan
+        g2 = 0.0 if alpha == 2.0 else np.nan
+        return mu, mu2, g1, g2
+
+
+# cotes numbers - see sequence from http://oeis.org/A100642
+Cotes_table = np.array(
+    [[], [1]] + [v[2] for v in _builtincoeffs.values()], dtype=object
+)
+Cotes = np.array(
+    [
+        np.pad(r, (0, len(Cotes_table) - 1 - len(r)), mode='constant')
+        for r in Cotes_table
+    ]
+)
+
+
+def pdf_from_cf_with_fft(cf, h=0.01, q=9, level=3):
+    """Calculates pdf from characteristic function.
+
+    Uses fast Fourier transform with Newton-Cotes integration following [WZ].
+    Defaults to using Simpson's method (3-point Newton-Cotes integration).
+
+    Parameters
+    ----------
+    cf : callable
+        Single argument function from float -> complex expressing a
+        characteristic function for some distribution.
+    h : Optional[float]
+        Step size for Newton-Cotes integration. Default: 0.01
+    q : Optional[int]
+        Use 2**q steps when performing Newton-Cotes integration.
+        The infinite integral in the inverse Fourier transform will then
+        be restricted to the interval [-2**q * h / 2, 2**q * h / 2]. Setting
+        the number of steps equal to a power of 2 allows the fft to be
+        calculated in O(n*log(n)) time rather than O(n**2).
+        Default: 9
+    level : Optional[int]
+        Calculate integral using n-point Newton-Cotes integration for
+        n = level. The 3-point Newton-Cotes formula corresponds to Simpson's
+        rule. Default: 3
+
+    Returns
+    -------
+    x_l : ndarray
+        Array of points x at which pdf is estimated. 2**q equally spaced
+        points from -pi/h up to but not including pi/h.
+    density : ndarray
+        Estimated values of pdf corresponding to cf at points in x_l.
+
+    References
+    ----------
+    .. [WZ] Wang, Li and Zhang, Ji-Hong, 2008. Simpson's rule based FFT method
+        to compute densities of stable distribution.
+    """
+    n = level
+    N = 2**q
+    steps = np.arange(0, N)
+    L = N * h / 2
+    x_l = np.pi * (steps - N / 2) / L
+    if level > 1:
+        indices = np.arange(n).reshape(n, 1)
+        s1 = np.sum(
+            (-1) ** steps * Cotes[n, indices] * np.fft.fft(
+                (-1)**steps * cf(-L + h * steps + h * indices / (n - 1))
+            ) * np.exp(
+                1j * np.pi * indices / (n - 1)
+                - 2 * 1j * np.pi * indices * steps /
+                (N * (n - 1))
+            ),
+            axis=0
+        )
+    else:
+        s1 = (-1) ** steps * Cotes[n, 0] * np.fft.fft(
+            (-1) ** steps * cf(-L + h * steps)
+        )
+    density = h * s1 / (2 * np.pi * np.sum(Cotes[n]))
+    return (x_l, density)
+
+
+levy_stable = levy_stable_gen(name="levy_stable")
+
+
+class levy_stable_frozen(rv_continuous_frozen):
+    @property
+    def parameterization(self):
+        return self.dist.parameterization
+
+    @parameterization.setter
+    def parameterization(self, value):
+        self.dist.parameterization = value
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19267a088599f91e2cb3b451003520fac6f258d6
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/levyst.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/levyst.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..8707fa7b505a9f3a08c963acea727c15d56b175e
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_levy_stable/levyst.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mannwhitneyu.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mannwhitneyu.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0ab9a427fe78845c880992235a40e034fe7f2dd
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mannwhitneyu.py
@@ -0,0 +1,492 @@
+import threading
+import numpy as np
+from collections import namedtuple
+from scipy import special
+from scipy import stats
+from scipy.stats._stats_py import _rankdata
+from ._axis_nan_policy import _axis_nan_policy_factory
+
+
+def _broadcast_concatenate(x, y, axis):
+    '''Broadcast then concatenate arrays, leaving concatenation axis last'''
+    x = np.moveaxis(x, axis, -1)
+    y = np.moveaxis(y, axis, -1)
+    z = np.broadcast(x[..., 0], y[..., 0])
+    x = np.broadcast_to(x, z.shape + (x.shape[-1],))
+    y = np.broadcast_to(y, z.shape + (y.shape[-1],))
+    z = np.concatenate((x, y), axis=-1)
+    return x, y, z
+
+
+class _MWU:
+    '''Distribution of MWU statistic under the null hypothesis'''
+
+    def __init__(self, n1, n2):
+        self._reset(n1, n2)
+
+    def set_shapes(self, n1, n2):
+        n1, n2 = min(n1, n2), max(n1, n2)
+        if (n1, n2) == (self.n1, self.n2):
+            return
+
+        self.n1 = n1
+        self.n2 = n2
+        self.s_array = np.zeros(0, dtype=int)
+        self.configurations = np.zeros(0, dtype=np.uint64)
+
+    def reset(self):
+        self._reset(self.n1, self.n2)
+
+    def _reset(self, n1, n2):
+        self.n1 = None
+        self.n2 = None
+        self.set_shapes(n1, n2)
+
+    def pmf(self, k):
+
+        # In practice, `pmf` is never called with k > m*n/2.
+        # If it were, we'd exploit symmetry here:
+        # k = np.array(k, copy=True)
+        # k2 = m*n - k
+        # i = k2 < k
+        # k[i] = k2[i]
+
+        pmfs = self.build_u_freqs_array(np.max(k))
+        return pmfs[k]
+
+    def cdf(self, k):
+        '''Cumulative distribution function'''
+
+        # In practice, `cdf` is never called with k > m*n/2.
+        # If it were, we'd exploit symmetry here rather than in `sf`
+        pmfs = self.build_u_freqs_array(np.max(k))
+        cdfs = np.cumsum(pmfs)
+        return cdfs[k]
+
+    def sf(self, k):
+        '''Survival function'''
+        # Note that both CDF and SF include the PMF at k. The p-value is
+        # calculated from the SF and should include the mass at k, so this
+        # is desirable
+
+        # Use the fact that the distribution is symmetric and sum from the left
+        kc = np.asarray(self.n1*self.n2 - k)  # complement of k
+        i = k < kc
+        if np.any(i):
+            kc[i] = k[i]
+            cdfs = np.asarray(self.cdf(kc))
+            cdfs[i] = 1. - cdfs[i] + self.pmf(kc[i])
+        else:
+            cdfs = np.asarray(self.cdf(kc))
+        return cdfs[()]
+
+    # build_sigma_array and build_u_freqs_array adapted from code
+    # by @toobaz with permission. Thanks to @andreasloe for the suggestion.
+    # See https://github.com/scipy/scipy/pull/4933#issuecomment-1898082691
+    def build_sigma_array(self, a):
+        n1, n2 = self.n1, self.n2
+        if a + 1 <= self.s_array.size:
+            return self.s_array[1:a+1]
+
+        s_array = np.zeros(a + 1, dtype=int)
+
+        for d in np.arange(1, n1 + 1):
+            # All multiples of d, except 0:
+            indices = np.arange(d, a + 1, d)
+            # \epsilon_d = 1:
+            s_array[indices] += d
+
+        for d in np.arange(n2 + 1, n2 + n1 + 1):
+            # All multiples of d, except 0:
+            indices = np.arange(d, a + 1, d)
+            # \epsilon_d = -1:
+            s_array[indices] -= d
+
+        # We don't need 0:
+        self.s_array = s_array
+        return s_array[1:]
+
+    def build_u_freqs_array(self, maxu):
+        """
+        Build all the array of frequencies for u from 0 to maxu.
+        Assumptions:
+          n1 <= n2
+          maxu <= n1 * n2 / 2
+        """
+        n1, n2 = self.n1, self.n2
+        total = special.binom(n1 + n2, n1)
+
+        if maxu + 1 <= self.configurations.size:
+            return self.configurations[:maxu + 1] / total
+
+        s_array = self.build_sigma_array(maxu)
+
+        # Start working with ints, for maximum precision and efficiency:
+        configurations = np.zeros(maxu + 1, dtype=np.uint64)
+        configurations_is_uint = True
+        uint_max = np.iinfo(np.uint64).max
+        # How many ways to have U=0? 1
+        configurations[0] = 1
+
+        for u in np.arange(1, maxu + 1):
+            coeffs = s_array[u - 1::-1]
+            new_val = np.dot(configurations[:u], coeffs) / u
+            if new_val > uint_max and configurations_is_uint:
+                # OK, we got into numbers too big for uint64.
+                # So now we start working with floats.
+                # By doing this since the beginning, we would have lost precision.
+                # (And working on python long ints would be unbearably slow)
+                configurations = configurations.astype(float)
+                configurations_is_uint = False
+            configurations[u] = new_val
+
+        self.configurations = configurations
+        return configurations / total
+
+
+# Maintain state for faster repeat calls to `mannwhitneyu`.
+# _MWU() is calculated once per thread and stored as an attribute on
+# this thread-local variable inside mannwhitneyu().
+_mwu_state = threading.local()
+
+
+def _get_mwu_z(U, n1, n2, t, axis=0, continuity=True):
+    '''Standardized MWU statistic'''
+    # Follows mannwhitneyu [2]
+    mu = n1 * n2 / 2
+    n = n1 + n2
+
+    # Tie correction according to [2], "Normal approximation and tie correction"
+    # "A more computationally-efficient form..."
+    tie_term = (t**3 - t).sum(axis=-1)
+    s = np.sqrt(n1*n2/12 * ((n + 1) - tie_term/(n*(n-1))))
+
+    numerator = U - mu
+
+    # Continuity correction.
+    # Because SF is always used to calculate the p-value, we can always
+    # _subtract_ 0.5 for the continuity correction. This always increases the
+    # p-value to account for the rest of the probability mass _at_ q = U.
+    if continuity:
+        numerator -= 0.5
+
+    # no problem evaluating the norm SF at an infinity
+    with np.errstate(divide='ignore', invalid='ignore'):
+        z = numerator / s
+    return z
+
+
+def _mwu_input_validation(x, y, use_continuity, alternative, axis, method):
+    ''' Input validation and standardization for mannwhitneyu '''
+    # Would use np.asarray_chkfinite, but infs are OK
+    x, y = np.atleast_1d(x), np.atleast_1d(y)
+    if np.isnan(x).any() or np.isnan(y).any():
+        raise ValueError('`x` and `y` must not contain NaNs.')
+    if np.size(x) == 0 or np.size(y) == 0:
+        raise ValueError('`x` and `y` must be of nonzero size.')
+
+    bools = {True, False}
+    if use_continuity not in bools:
+        raise ValueError(f'`use_continuity` must be one of {bools}.')
+
+    alternatives = {"two-sided", "less", "greater"}
+    alternative = alternative.lower()
+    if alternative not in alternatives:
+        raise ValueError(f'`alternative` must be one of {alternatives}.')
+
+    axis_int = int(axis)
+    if axis != axis_int:
+        raise ValueError('`axis` must be an integer.')
+
+    if not isinstance(method, stats.PermutationMethod):
+        methods = {"asymptotic", "exact", "auto"}
+        method = method.lower()
+        if method not in methods:
+            raise ValueError(f'`method` must be one of {methods}.')
+
+    return x, y, use_continuity, alternative, axis_int, method
+
+
+def _mwu_choose_method(n1, n2, ties):
+    """Choose method 'asymptotic' or 'exact' depending on input size, ties"""
+
+    # if both inputs are large, asymptotic is OK
+    if n1 > 8 and n2 > 8:
+        return "asymptotic"
+
+    # if there are any ties, asymptotic is preferred
+    if ties:
+        return "asymptotic"
+
+    return "exact"
+
+
+MannwhitneyuResult = namedtuple('MannwhitneyuResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(MannwhitneyuResult, n_samples=2)
+def mannwhitneyu(x, y, use_continuity=True, alternative="two-sided",
+                 axis=0, method="auto"):
+    r'''Perform the Mann-Whitney U rank test on two independent samples.
+
+    The Mann-Whitney U test is a nonparametric test of the null hypothesis
+    that the distribution underlying sample `x` is the same as the
+    distribution underlying sample `y`. It is often used as a test of
+    difference in location between distributions.
+
+    Parameters
+    ----------
+    x, y : array-like
+        N-d arrays of samples. The arrays must be broadcastable except along
+        the dimension given by `axis`.
+    use_continuity : bool, optional
+            Whether a continuity correction (1/2) should be applied.
+            Default is True when `method` is ``'asymptotic'``; has no effect
+            otherwise.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        Let *SX(u)* and *SY(u)* be the survival functions of the
+        distributions underlying `x` and `y`, respectively. Then the following
+        alternative hypotheses are available:
+
+        * 'two-sided': the distributions are not equal, i.e. *SX(u) ≠ SY(u)* for
+          at least one *u*.
+        * 'less': the distribution underlying `x` is stochastically less
+          than the distribution underlying `y`, i.e. *SX(u) < SY(u)* for all *u*.
+        * 'greater': the distribution underlying `x` is stochastically greater
+          than the distribution underlying `y`, i.e. *SX(u) > SY(u)* for all *u*.
+
+        Under a more restrictive set of assumptions, the alternative hypotheses
+        can be expressed in terms of the locations of the distributions;
+        see [5]_ section 5.1.
+    axis : int, optional
+        Axis along which to perform the test. Default is 0.
+    method : {'auto', 'asymptotic', 'exact'} or `PermutationMethod` instance, optional
+        Selects the method used to calculate the *p*-value.
+        Default is 'auto'. The following options are available.
+
+        * ``'asymptotic'``: compares the standardized test statistic
+          against the normal distribution, correcting for ties.
+        * ``'exact'``: computes the exact *p*-value by comparing the observed
+          :math:`U` statistic against the exact distribution of the :math:`U`
+          statistic under the null hypothesis. No correction is made for ties.
+        * ``'auto'``: chooses ``'exact'`` when the size of one of the samples
+          is less than or equal to 8 and there are no ties;
+          chooses ``'asymptotic'`` otherwise.
+        * `PermutationMethod` instance. In this case, the p-value
+          is computed using `permutation_test` with the provided
+          configuration options and other appropriate settings.
+
+    Returns
+    -------
+    res : MannwhitneyuResult
+        An object containing attributes:
+
+        statistic : float
+            The Mann-Whitney U statistic corresponding with sample `x`. See
+            Notes for the test statistic corresponding with sample `y`.
+        pvalue : float
+            The associated *p*-value for the chosen `alternative`.
+
+    Notes
+    -----
+    If ``U1`` is the statistic corresponding with sample `x`, then the
+    statistic corresponding with sample `y` is
+    ``U2 = x.shape[axis] * y.shape[axis] - U1``.
+
+    `mannwhitneyu` is for independent samples. For related / paired samples,
+    consider `scipy.stats.wilcoxon`.
+
+    `method` ``'exact'`` is recommended when there are no ties and when either
+    sample size is less than 8 [1]_. The implementation follows the algorithm
+    reported in [3]_.
+    Note that the exact method is *not* corrected for ties, but
+    `mannwhitneyu` will not raise errors or warnings if there are ties in the
+    data. If there are ties and either samples is small (fewer than ~10
+    observations), consider passing an instance of `PermutationMethod`
+    as the `method` to perform a permutation test.
+
+    The Mann-Whitney U test is a non-parametric version of the t-test for
+    independent samples. When the means of samples from the populations
+    are normally distributed, consider `scipy.stats.ttest_ind`.
+
+    See Also
+    --------
+    scipy.stats.wilcoxon, scipy.stats.ranksums, scipy.stats.ttest_ind
+
+    References
+    ----------
+    .. [1] H.B. Mann and D.R. Whitney, "On a test of whether one of two random
+           variables is stochastically larger than the other", The Annals of
+           Mathematical Statistics, Vol. 18, pp. 50-60, 1947.
+    .. [2] Mann-Whitney U Test, Wikipedia,
+           http://en.wikipedia.org/wiki/Mann-Whitney_U_test
+    .. [3] Andreas Löffler,
+           "Über eine Partition der nat. Zahlen und ihr Anwendung beim U-Test",
+           Wiss. Z. Univ. Halle, XXXII'83 pp. 87-89.
+    .. [4] Rosie Shier, "Statistics: 2.3 The Mann-Whitney U Test", Mathematics
+           Learning Support Centre, 2004.
+    .. [5] Michael P. Fay and Michael A. Proschan. "Wilcoxon-Mann-Whitney
+           or t-test? On assumptions for hypothesis tests and multiple \
+           interpretations of decision rules." Statistics surveys, Vol. 4, pp.
+           1-39, 2010. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2857732/
+
+    Examples
+    --------
+    We follow the example from [4]_: nine randomly sampled young adults were
+    diagnosed with type II diabetes at the ages below.
+
+    >>> males = [19, 22, 16, 29, 24]
+    >>> females = [20, 11, 17, 12]
+
+    We use the Mann-Whitney U test to assess whether there is a statistically
+    significant difference in the diagnosis age of males and females.
+    The null hypothesis is that the distribution of male diagnosis ages is
+    the same as the distribution of female diagnosis ages. We decide
+    that a confidence level of 95% is required to reject the null hypothesis
+    in favor of the alternative that the distributions are different.
+    Since the number of samples is very small and there are no ties in the
+    data, we can compare the observed test statistic against the *exact*
+    distribution of the test statistic under the null hypothesis.
+
+    >>> from scipy.stats import mannwhitneyu
+    >>> U1, p = mannwhitneyu(males, females, method="exact")
+    >>> print(U1)
+    17.0
+
+    `mannwhitneyu` always reports the statistic associated with the first
+    sample, which, in this case, is males. This agrees with :math:`U_M = 17`
+    reported in [4]_. The statistic associated with the second statistic
+    can be calculated:
+
+    >>> nx, ny = len(males), len(females)
+    >>> U2 = nx*ny - U1
+    >>> print(U2)
+    3.0
+
+    This agrees with :math:`U_F = 3` reported in [4]_. The two-sided
+    *p*-value can be calculated from either statistic, and the value produced
+    by `mannwhitneyu` agrees with :math:`p = 0.11` reported in [4]_.
+
+    >>> print(p)
+    0.1111111111111111
+
+    The exact distribution of the test statistic is asymptotically normal, so
+    the example continues by comparing the exact *p*-value against the
+    *p*-value produced using the normal approximation.
+
+    >>> _, pnorm = mannwhitneyu(males, females, method="asymptotic")
+    >>> print(pnorm)
+    0.11134688653314041
+
+    Here `mannwhitneyu`'s reported *p*-value appears to conflict with the
+    value :math:`p = 0.09` given in [4]_. The reason is that [4]_
+    does not apply the continuity correction performed by `mannwhitneyu`;
+    `mannwhitneyu` reduces the distance between the test statistic and the
+    mean :math:`\mu = n_x n_y / 2` by 0.5 to correct for the fact that the
+    discrete statistic is being compared against a continuous distribution.
+    Here, the :math:`U` statistic used is less than the mean, so we reduce
+    the distance by adding 0.5 in the numerator.
+
+    >>> import numpy as np
+    >>> from scipy.stats import norm
+    >>> U = min(U1, U2)
+    >>> N = nx + ny
+    >>> z = (U - nx*ny/2 + 0.5) / np.sqrt(nx*ny * (N + 1)/ 12)
+    >>> p = 2 * norm.cdf(z)  # use CDF to get p-value from smaller statistic
+    >>> print(p)
+    0.11134688653314041
+
+    If desired, we can disable the continuity correction to get a result
+    that agrees with that reported in [4]_.
+
+    >>> _, pnorm = mannwhitneyu(males, females, use_continuity=False,
+    ...                         method="asymptotic")
+    >>> print(pnorm)
+    0.0864107329737
+
+    Regardless of whether we perform an exact or asymptotic test, the
+    probability of the test statistic being as extreme or more extreme by
+    chance exceeds 5%, so we do not consider the results statistically
+    significant.
+
+    Suppose that, before seeing the data, we had hypothesized that females
+    would tend to be diagnosed at a younger age than males.
+    In that case, it would be natural to provide the female ages as the
+    first input, and we would have performed a one-sided test using
+    ``alternative = 'less'``: females are diagnosed at an age that is
+    stochastically less than that of males.
+
+    >>> res = mannwhitneyu(females, males, alternative="less", method="exact")
+    >>> print(res)
+    MannwhitneyuResult(statistic=3.0, pvalue=0.05555555555555555)
+
+    Again, the probability of getting a sufficiently low value of the
+    test statistic by chance under the null hypothesis is greater than 5%,
+    so we do not reject the null hypothesis in favor of our alternative.
+
+    If it is reasonable to assume that the means of samples from the
+    populations are normally distributed, we could have used a t-test to
+    perform the analysis.
+
+    >>> from scipy.stats import ttest_ind
+    >>> res = ttest_ind(females, males, alternative="less")
+    >>> print(res)
+    TtestResult(statistic=-2.239334696520584,
+                pvalue=0.030068441095757924,
+                df=7.0)
+
+    Under this assumption, the *p*-value would be low enough to reject the
+    null hypothesis in favor of the alternative.
+
+    '''
+
+    x, y, use_continuity, alternative, axis_int, method = (
+        _mwu_input_validation(x, y, use_continuity, alternative, axis, method))
+
+    x, y, xy = _broadcast_concatenate(x, y, axis)
+
+    n1, n2 = x.shape[-1], y.shape[-1]
+
+    # Follows [2]
+    ranks, t = _rankdata(xy, 'average', return_ties=True)  # method 2, step 1
+    R1 = ranks[..., :n1].sum(axis=-1)                      # method 2, step 2
+    U1 = R1 - n1*(n1+1)/2                                  # method 2, step 3
+    U2 = n1 * n2 - U1                                      # as U1 + U2 = n1 * n2
+
+    if alternative == "greater":
+        U, f = U1, 1  # U is the statistic to use for p-value, f is a factor
+    elif alternative == "less":
+        U, f = U2, 1  # Due to symmetry, use SF of U2 rather than CDF of U1
+    else:
+        U, f = np.maximum(U1, U2), 2  # multiply SF by two for two-sided test
+
+    if method == "auto":
+        method = _mwu_choose_method(n1, n2, np.any(t > 1))
+
+    if method == "exact":
+        if not hasattr(_mwu_state, 's'):
+            _mwu_state.s = _MWU(0, 0)
+        _mwu_state.s.set_shapes(n1, n2)
+        p = _mwu_state.s.sf(U.astype(int))
+    elif method == "asymptotic":
+        z = _get_mwu_z(U, n1, n2, t, continuity=use_continuity)
+        p = stats.norm.sf(z)
+    else:  # `PermutationMethod` instance (already validated)
+        def statistic(x, y, axis):
+            return mannwhitneyu(x, y, use_continuity=use_continuity,
+                                alternative=alternative, axis=axis,
+                                method="asymptotic").statistic
+
+        res = stats.permutation_test((x, y), statistic, axis=axis,
+                                     **method._asdict(), alternative=alternative)
+        p = res.pvalue
+        f = 1
+
+    p *= f
+
+    # Ensure that test statistic is not greater than 1
+    # This could happen for exact test when U = m*n/2
+    p = np.clip(p, 0, 1)
+
+    return MannwhitneyuResult(U1, p)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mgc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mgc.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ec433c585146fe89a88dfe6e98888b20b886284
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mgc.py
@@ -0,0 +1,550 @@
+import warnings
+import numpy as np
+
+from scipy._lib._util import check_random_state, MapWrapper, rng_integers, _contains_nan
+from scipy._lib._bunch import _make_tuple_bunch
+from scipy.spatial.distance import cdist
+from scipy.ndimage import _measurements
+
+from ._stats import _local_correlations  # type: ignore[import-not-found]
+from . import distributions
+
+__all__ = ['multiscale_graphcorr']
+
+# FROM MGCPY: https://github.com/neurodata/mgcpy
+
+
+class _ParallelP:
+    """Helper function to calculate parallel p-value."""
+
+    def __init__(self, x, y, random_states):
+        self.x = x
+        self.y = y
+        self.random_states = random_states
+
+    def __call__(self, index):
+        order = self.random_states[index].permutation(self.y.shape[0])
+        permy = self.y[order][:, order]
+
+        # calculate permuted stats, store in null distribution
+        perm_stat = _mgc_stat(self.x, permy)[0]
+
+        return perm_stat
+
+
+def _perm_test(x, y, stat, reps=1000, workers=-1, random_state=None):
+    r"""Helper function that calculates the p-value. See below for uses.
+
+    Parameters
+    ----------
+    x, y : ndarray
+        `x` and `y` have shapes ``(n, p)`` and ``(n, q)``.
+    stat : float
+        The sample test statistic.
+    reps : int, optional
+        The number of replications used to estimate the null when using the
+        permutation test. The default is 1000 replications.
+    workers : int or map-like callable, optional
+        If `workers` is an int the population is subdivided into `workers`
+        sections and evaluated in parallel (uses
+        `multiprocessing.Pool `). Supply `-1` to use all cores
+        available to the Process. Alternatively supply a map-like callable,
+        such as `multiprocessing.Pool.map` for evaluating the population in
+        parallel. This evaluation is carried out as `workers(func, iterable)`.
+        Requires that `func` be pickleable.
+    random_state : {None, int, `numpy.random.Generator`,
+                    `numpy.random.RandomState`}, optional
+
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    Returns
+    -------
+    pvalue : float
+        The sample test p-value.
+    null_dist : list
+        The approximated null distribution.
+
+    """
+    # generate seeds for each rep (change to new parallel random number
+    # capabilities in numpy >= 1.17+)
+    random_state = check_random_state(random_state)
+    random_states = [np.random.RandomState(rng_integers(random_state, 1 << 32,
+                     size=4, dtype=np.uint32)) for _ in range(reps)]
+
+    # parallelizes with specified workers over number of reps and set seeds
+    parallelp = _ParallelP(x=x, y=y, random_states=random_states)
+    with MapWrapper(workers) as mapwrapper:
+        null_dist = np.array(list(mapwrapper(parallelp, range(reps))))
+
+    # calculate p-value and significant permutation map through list
+    pvalue = (1 + (null_dist >= stat).sum()) / (1 + reps)
+
+    return pvalue, null_dist
+
+
+def _euclidean_dist(x):
+    return cdist(x, x)
+
+
+MGCResult = _make_tuple_bunch('MGCResult',
+                              ['statistic', 'pvalue', 'mgc_dict'], [])
+
+
+def multiscale_graphcorr(x, y, compute_distance=_euclidean_dist, reps=1000,
+                         workers=1, is_twosamp=False, random_state=None):
+    r"""Computes the Multiscale Graph Correlation (MGC) test statistic.
+
+    Specifically, for each point, MGC finds the :math:`k`-nearest neighbors for
+    one property (e.g. cloud density), and the :math:`l`-nearest neighbors for
+    the other property (e.g. grass wetness) [1]_. This pair :math:`(k, l)` is
+    called the "scale". A priori, however, it is not know which scales will be
+    most informative. So, MGC computes all distance pairs, and then efficiently
+    computes the distance correlations for all scales. The local correlations
+    illustrate which scales are relatively informative about the relationship.
+    The key, therefore, to successfully discover and decipher relationships
+    between disparate data modalities is to adaptively determine which scales
+    are the most informative, and the geometric implication for the most
+    informative scales. Doing so not only provides an estimate of whether the
+    modalities are related, but also provides insight into how the
+    determination was made. This is especially important in high-dimensional
+    data, where simple visualizations do not reveal relationships to the
+    unaided human eye. Characterizations of this implementation in particular
+    have been derived from and benchmarked within in [2]_.
+
+    Parameters
+    ----------
+    x, y : ndarray
+        If ``x`` and ``y`` have shapes ``(n, p)`` and ``(n, q)`` where `n` is
+        the number of samples and `p` and `q` are the number of dimensions,
+        then the MGC independence test will be run.  Alternatively, ``x`` and
+        ``y`` can have shapes ``(n, n)`` if they are distance or similarity
+        matrices, and ``compute_distance`` must be sent to ``None``. If ``x``
+        and ``y`` have shapes ``(n, p)`` and ``(m, p)``, an unpaired
+        two-sample MGC test will be run.
+    compute_distance : callable, optional
+        A function that computes the distance or similarity among the samples
+        within each data matrix. Set to ``None`` if ``x`` and ``y`` are
+        already distance matrices. The default uses the euclidean norm metric.
+        If you are calling a custom function, either create the distance
+        matrix before-hand or create a function of the form
+        ``compute_distance(x)`` where `x` is the data matrix for which
+        pairwise distances are calculated.
+    reps : int, optional
+        The number of replications used to estimate the null when using the
+        permutation test. The default is ``1000``.
+    workers : int or map-like callable, optional
+        If ``workers`` is an int the population is subdivided into ``workers``
+        sections and evaluated in parallel (uses ``multiprocessing.Pool
+        ``). Supply ``-1`` to use all cores available to the
+        Process. Alternatively supply a map-like callable, such as
+        ``multiprocessing.Pool.map`` for evaluating the p-value in parallel.
+        This evaluation is carried out as ``workers(func, iterable)``.
+        Requires that `func` be pickleable. The default is ``1``.
+    is_twosamp : bool, optional
+        If `True`, a two sample test will be run. If ``x`` and ``y`` have
+        shapes ``(n, p)`` and ``(m, p)``, this optional will be overridden and
+        set to ``True``. Set to ``True`` if ``x`` and ``y`` both have shapes
+        ``(n, p)`` and a two sample test is desired. The default is ``False``.
+        Note that this will not run if inputs are distance matrices.
+    random_state : {None, int, `numpy.random.Generator`,
+                    `numpy.random.RandomState`}, optional
+
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    Returns
+    -------
+    res : MGCResult
+        An object containing attributes:
+
+        statistic : float
+            The sample MGC test statistic within ``[-1, 1]``.
+        pvalue : float
+            The p-value obtained via permutation.
+        mgc_dict : dict
+            Contains additional useful results:
+
+                - mgc_map : ndarray
+                    A 2D representation of the latent geometry of the
+                    relationship.
+                - opt_scale : (int, int)
+                    The estimated optimal scale as a ``(x, y)`` pair.
+                - null_dist : list
+                    The null distribution derived from the permuted matrices.
+
+    See Also
+    --------
+    pearsonr : Pearson correlation coefficient and p-value for testing
+               non-correlation.
+    kendalltau : Calculates Kendall's tau.
+    spearmanr : Calculates a Spearman rank-order correlation coefficient.
+
+    Notes
+    -----
+    A description of the process of MGC and applications on neuroscience data
+    can be found in [1]_. It is performed using the following steps:
+
+    #. Two distance matrices :math:`D^X` and :math:`D^Y` are computed and
+       modified to be mean zero columnwise. This results in two
+       :math:`n \times n` distance matrices :math:`A` and :math:`B` (the
+       centering and unbiased modification) [3]_.
+
+    #. For all values :math:`k` and :math:`l` from :math:`1, ..., n`,
+
+       * The :math:`k`-nearest neighbor and :math:`l`-nearest neighbor graphs
+         are calculated for each property. Here, :math:`G_k (i, j)` indicates
+         the :math:`k`-smallest values of the :math:`i`-th row of :math:`A`
+         and :math:`H_l (i, j)` indicates the :math:`l` smallested values of
+         the :math:`i`-th row of :math:`B`
+
+       * Let :math:`\circ` denotes the entry-wise matrix product, then local
+         correlations are summed and normalized using the following statistic:
+
+    .. math::
+
+        c^{kl} = \frac{\sum_{ij} A G_k B H_l}
+                      {\sqrt{\sum_{ij} A^2 G_k \times \sum_{ij} B^2 H_l}}
+
+    #. The MGC test statistic is the smoothed optimal local correlation of
+       :math:`\{ c^{kl} \}`. Denote the smoothing operation as :math:`R(\cdot)`
+       (which essentially set all isolated large correlations) as 0 and
+       connected large correlations the same as before, see [3]_.) MGC is,
+
+    .. math::
+
+        MGC_n (x, y) = \max_{(k, l)} R \left(c^{kl} \left( x_n, y_n \right)
+                                                    \right)
+
+    The test statistic returns a value between :math:`(-1, 1)` since it is
+    normalized.
+
+    The p-value returned is calculated using a permutation test. This process
+    is completed by first randomly permuting :math:`y` to estimate the null
+    distribution and then calculating the probability of observing a test
+    statistic, under the null, at least as extreme as the observed test
+    statistic.
+
+    MGC requires at least 5 samples to run with reliable results. It can also
+    handle high-dimensional data sets.
+    In addition, by manipulating the input data matrices, the two-sample
+    testing problem can be reduced to the independence testing problem [4]_.
+    Given sample data :math:`U` and :math:`V` of sizes :math:`p \times n`
+    :math:`p \times m`, data matrix :math:`X` and :math:`Y` can be created as
+    follows:
+
+    .. math::
+
+        X = [U | V] \in \mathcal{R}^{p \times (n + m)}
+        Y = [0_{1 \times n} | 1_{1 \times m}] \in \mathcal{R}^{(n + m)}
+
+    Then, the MGC statistic can be calculated as normal. This methodology can
+    be extended to similar tests such as distance correlation [4]_.
+
+    .. versionadded:: 1.4.0
+
+    References
+    ----------
+    .. [1] Vogelstein, J. T., Bridgeford, E. W., Wang, Q., Priebe, C. E.,
+           Maggioni, M., & Shen, C. (2019). Discovering and deciphering
+           relationships across disparate data modalities. ELife.
+    .. [2] Panda, S., Palaniappan, S., Xiong, J., Swaminathan, A.,
+           Ramachandran, S., Bridgeford, E. W., ... Vogelstein, J. T. (2019).
+           mgcpy: A Comprehensive High Dimensional Independence Testing Python
+           Package. :arXiv:`1907.02088`
+    .. [3] Shen, C., Priebe, C.E., & Vogelstein, J. T. (2019). From distance
+           correlation to multiscale graph correlation. Journal of the American
+           Statistical Association.
+    .. [4] Shen, C. & Vogelstein, J. T. (2018). The Exact Equivalence of
+           Distance and Kernel Methods for Hypothesis Testing.
+           :arXiv:`1806.05514`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import multiscale_graphcorr
+    >>> x = np.arange(100)
+    >>> y = x
+    >>> res = multiscale_graphcorr(x, y)
+    >>> res.statistic, res.pvalue
+    (1.0, 0.001)
+
+    To run an unpaired two-sample test,
+
+    >>> x = np.arange(100)
+    >>> y = np.arange(79)
+    >>> res = multiscale_graphcorr(x, y)
+    >>> res.statistic, res.pvalue  # doctest: +SKIP
+    (0.033258146255703246, 0.023)
+
+    or, if shape of the inputs are the same,
+
+    >>> x = np.arange(100)
+    >>> y = x
+    >>> res = multiscale_graphcorr(x, y, is_twosamp=True)
+    >>> res.statistic, res.pvalue  # doctest: +SKIP
+    (-0.008021809890200488, 1.0)
+
+    """
+    if not isinstance(x, np.ndarray) or not isinstance(y, np.ndarray):
+        raise ValueError("x and y must be ndarrays")
+
+    # convert arrays of type (n,) to (n, 1)
+    if x.ndim == 1:
+        x = x[:, np.newaxis]
+    elif x.ndim != 2:
+        raise ValueError(f"Expected a 2-D array `x`, found shape {x.shape}")
+    if y.ndim == 1:
+        y = y[:, np.newaxis]
+    elif y.ndim != 2:
+        raise ValueError(f"Expected a 2-D array `y`, found shape {y.shape}")
+
+    nx, px = x.shape
+    ny, py = y.shape
+
+    # check for NaNs
+    _contains_nan(x, nan_policy='raise')
+    _contains_nan(y, nan_policy='raise')
+
+    # check for positive or negative infinity and raise error
+    if np.sum(np.isinf(x)) > 0 or np.sum(np.isinf(y)) > 0:
+        raise ValueError("Inputs contain infinities")
+
+    if nx != ny:
+        if px == py:
+            # reshape x and y for two sample testing
+            is_twosamp = True
+        else:
+            raise ValueError("Shape mismatch, x and y must have shape [n, p] "
+                             "and [n, q] or have shape [n, p] and [m, p].")
+
+    if nx < 5 or ny < 5:
+        raise ValueError("MGC requires at least 5 samples to give reasonable "
+                         "results.")
+
+    # convert x and y to float
+    x = x.astype(np.float64)
+    y = y.astype(np.float64)
+
+    # check if compute_distance_matrix if a callable()
+    if not callable(compute_distance) and compute_distance is not None:
+        raise ValueError("Compute_distance must be a function.")
+
+    # check if number of reps exists, integer, or > 0 (if under 1000 raises
+    # warning)
+    if not isinstance(reps, int) or reps < 0:
+        raise ValueError("Number of reps must be an integer greater than 0.")
+    elif reps < 1000:
+        msg = ("The number of replications is low (under 1000), and p-value "
+               "calculations may be unreliable. Use the p-value result, with "
+               "caution!")
+        warnings.warn(msg, RuntimeWarning, stacklevel=2)
+
+    if is_twosamp:
+        if compute_distance is None:
+            raise ValueError("Cannot run if inputs are distance matrices")
+        x, y = _two_sample_transform(x, y)
+
+    if compute_distance is not None:
+        # compute distance matrices for x and y
+        x = compute_distance(x)
+        y = compute_distance(y)
+
+    # calculate MGC stat
+    stat, stat_dict = _mgc_stat(x, y)
+    stat_mgc_map = stat_dict["stat_mgc_map"]
+    opt_scale = stat_dict["opt_scale"]
+
+    # calculate permutation MGC p-value
+    pvalue, null_dist = _perm_test(x, y, stat, reps=reps, workers=workers,
+                                   random_state=random_state)
+
+    # save all stats (other than stat/p-value) in dictionary
+    mgc_dict = {"mgc_map": stat_mgc_map,
+                "opt_scale": opt_scale,
+                "null_dist": null_dist}
+
+    # create result object with alias for backward compatibility
+    res = MGCResult(stat, pvalue, mgc_dict)
+    res.stat = stat
+    return res
+
+
+def _mgc_stat(distx, disty):
+    r"""Helper function that calculates the MGC stat. See above for use.
+
+    Parameters
+    ----------
+    distx, disty : ndarray
+        `distx` and `disty` have shapes ``(n, p)`` and ``(n, q)`` or
+        ``(n, n)`` and ``(n, n)``
+        if distance matrices.
+
+    Returns
+    -------
+    stat : float
+        The sample MGC test statistic within ``[-1, 1]``.
+    stat_dict : dict
+        Contains additional useful additional returns containing the following
+        keys:
+
+            - stat_mgc_map : ndarray
+                MGC-map of the statistics.
+            - opt_scale : (float, float)
+                The estimated optimal scale as a ``(x, y)`` pair.
+
+    """
+    # calculate MGC map and optimal scale
+    stat_mgc_map = _local_correlations(distx, disty, global_corr='mgc')
+
+    n, m = stat_mgc_map.shape
+    if m == 1 or n == 1:
+        # the global scale at is the statistic calculated at maximal nearest
+        # neighbors. There is not enough local scale to search over, so
+        # default to global scale
+        stat = stat_mgc_map[m - 1][n - 1]
+        opt_scale = m * n
+    else:
+        samp_size = len(distx) - 1
+
+        # threshold to find connected region of significant local correlations
+        sig_connect = _threshold_mgc_map(stat_mgc_map, samp_size)
+
+        # maximum within the significant region
+        stat, opt_scale = _smooth_mgc_map(sig_connect, stat_mgc_map)
+
+    stat_dict = {"stat_mgc_map": stat_mgc_map,
+                 "opt_scale": opt_scale}
+
+    return stat, stat_dict
+
+
+def _threshold_mgc_map(stat_mgc_map, samp_size):
+    r"""
+    Finds a connected region of significance in the MGC-map by thresholding.
+
+    Parameters
+    ----------
+    stat_mgc_map : ndarray
+        All local correlations within ``[-1,1]``.
+    samp_size : int
+        The sample size of original data.
+
+    Returns
+    -------
+    sig_connect : ndarray
+        A binary matrix with 1's indicating the significant region.
+
+    """
+    m, n = stat_mgc_map.shape
+
+    # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
+    # with varying levels of performance. Threshold is based on a beta
+    # approximation.
+    per_sig = 1 - (0.02 / samp_size)  # Percentile to consider as significant
+    threshold = samp_size * (samp_size - 3)/4 - 1/2  # Beta approximation
+    threshold = distributions.beta.ppf(per_sig, threshold, threshold) * 2 - 1
+
+    # the global scale at is the statistic calculated at maximal nearest
+    # neighbors. Threshold is the maximum on the global and local scales
+    threshold = max(threshold, stat_mgc_map[m - 1][n - 1])
+
+    # find the largest connected component of significant correlations
+    sig_connect = stat_mgc_map > threshold
+    if np.sum(sig_connect) > 0:
+        sig_connect, _ = _measurements.label(sig_connect)
+        _, label_counts = np.unique(sig_connect, return_counts=True)
+
+        # skip the first element in label_counts, as it is count(zeros)
+        max_label = np.argmax(label_counts[1:]) + 1
+        sig_connect = sig_connect == max_label
+    else:
+        sig_connect = np.array([[False]])
+
+    return sig_connect
+
+
+def _smooth_mgc_map(sig_connect, stat_mgc_map):
+    """Finds the smoothed maximal within the significant region R.
+
+    If area of R is too small it returns the last local correlation. Otherwise,
+    returns the maximum within significant_connected_region.
+
+    Parameters
+    ----------
+    sig_connect : ndarray
+        A binary matrix with 1's indicating the significant region.
+    stat_mgc_map : ndarray
+        All local correlations within ``[-1, 1]``.
+
+    Returns
+    -------
+    stat : float
+        The sample MGC statistic within ``[-1, 1]``.
+    opt_scale: (float, float)
+        The estimated optimal scale as an ``(x, y)`` pair.
+
+    """
+    m, n = stat_mgc_map.shape
+
+    # the global scale at is the statistic calculated at maximal nearest
+    # neighbors. By default, statistic and optimal scale are global.
+    stat = stat_mgc_map[m - 1][n - 1]
+    opt_scale = [m, n]
+
+    if np.linalg.norm(sig_connect) != 0:
+        # proceed only when the connected region's area is sufficiently large
+        # 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
+        # with varying levels of performance
+        if np.sum(sig_connect) >= np.ceil(0.02 * max(m, n)) * min(m, n):
+            max_corr = max(stat_mgc_map[sig_connect])
+
+            # find all scales within significant_connected_region that maximize
+            # the local correlation
+            max_corr_index = np.where((stat_mgc_map >= max_corr) & sig_connect)
+
+            if max_corr >= stat:
+                stat = max_corr
+
+                k, l = max_corr_index
+                one_d_indices = k * n + l  # 2D to 1D indexing
+                k = np.max(one_d_indices) // n
+                l = np.max(one_d_indices) % n
+                opt_scale = [k+1, l+1]  # adding 1s to match R indexing
+
+    return stat, opt_scale
+
+
+def _two_sample_transform(u, v):
+    """Helper function that concatenates x and y for two sample MGC stat.
+
+    See above for use.
+
+    Parameters
+    ----------
+    u, v : ndarray
+        `u` and `v` have shapes ``(n, p)`` and ``(m, p)``.
+
+    Returns
+    -------
+    x : ndarray
+        Concatenate `u` and `v` along the ``axis = 0``. `x` thus has shape
+        ``(2n, p)``.
+    y : ndarray
+        Label matrix for `x` where 0 refers to samples that comes from `u` and
+        1 refers to samples that come from `v`. `y` thus has shape ``(2n, 1)``.
+
+    """
+    nx = u.shape[0]
+    ny = v.shape[0]
+    x = np.concatenate([u, v], axis=0)
+    y = np.concatenate([np.zeros(nx), np.ones(ny)], axis=0).reshape(-1, 1)
+    return x, y
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_morestats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_morestats.py
new file mode 100644
index 0000000000000000000000000000000000000000..2858a49125998d082280418af338d8f15529c843
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_morestats.py
@@ -0,0 +1,4581 @@
+import math
+import warnings
+import threading
+from collections import namedtuple
+
+import numpy as np
+from numpy import (isscalar, r_, log, around, unique, asarray, zeros,
+                   arange, sort, amin, amax, sqrt, array,
+                   pi, exp, ravel, count_nonzero)
+
+from scipy import optimize, special, interpolate, stats
+from scipy._lib._bunch import _make_tuple_bunch
+from scipy._lib._util import _rename_parameter, _contains_nan, _get_nan
+
+from scipy._lib._array_api import (
+    array_namespace,
+    xp_size,
+    xp_moveaxis_to_end,
+    xp_vector_norm,
+)
+
+from ._ansari_swilk_statistics import gscale, swilk
+from . import _stats_py, _wilcoxon
+from ._fit import FitResult
+from ._stats_py import (find_repeats, _get_pvalue, SignificanceResult,  # noqa:F401
+                        _SimpleNormal, _SimpleChi2)
+from .contingency import chi2_contingency
+from . import distributions
+from ._distn_infrastructure import rv_generic
+from ._axis_nan_policy import _axis_nan_policy_factory, _broadcast_arrays
+
+
+__all__ = ['mvsdist',
+           'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot',
+           'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot',
+           'shapiro', 'anderson', 'ansari', 'bartlett', 'levene',
+           'fligner', 'mood', 'wilcoxon', 'median_test',
+           'circmean', 'circvar', 'circstd', 'anderson_ksamp',
+           'yeojohnson_llf', 'yeojohnson', 'yeojohnson_normmax',
+           'yeojohnson_normplot', 'directional_stats',
+           'false_discovery_control'
+           ]
+
+
+Mean = namedtuple('Mean', ('statistic', 'minmax'))
+Variance = namedtuple('Variance', ('statistic', 'minmax'))
+Std_dev = namedtuple('Std_dev', ('statistic', 'minmax'))
+
+
+def bayes_mvs(data, alpha=0.90):
+    r"""
+    Bayesian confidence intervals for the mean, var, and std.
+
+    Parameters
+    ----------
+    data : array_like
+        Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.
+        Requires 2 or more data points.
+    alpha : float, optional
+        Probability that the returned confidence interval contains
+        the true parameter.
+
+    Returns
+    -------
+    mean_cntr, var_cntr, std_cntr : tuple
+        The three results are for the mean, variance and standard deviation,
+        respectively.  Each result is a tuple of the form::
+
+            (center, (lower, upper))
+
+        with ``center`` the mean of the conditional pdf of the value given the
+        data, and ``(lower, upper)`` a confidence interval, centered on the
+        median, containing the estimate to a probability ``alpha``.
+
+    See Also
+    --------
+    mvsdist
+
+    Notes
+    -----
+    Each tuple of mean, variance, and standard deviation estimates represent
+    the (center, (lower, upper)) with center the mean of the conditional pdf
+    of the value given the data and (lower, upper) is a confidence interval
+    centered on the median, containing the estimate to a probability
+    ``alpha``.
+
+    Converts data to 1-D and assumes all data has the same mean and variance.
+    Uses Jeffrey's prior for variance and std.
+
+    Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))``
+
+    References
+    ----------
+    T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
+    standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278,
+    2006.
+
+    Examples
+    --------
+    First a basic example to demonstrate the outputs:
+
+    >>> from scipy import stats
+    >>> data = [6, 9, 12, 7, 8, 8, 13]
+    >>> mean, var, std = stats.bayes_mvs(data)
+    >>> mean
+    Mean(statistic=9.0, minmax=(7.103650222612533, 10.896349777387467))
+    >>> var
+    Variance(statistic=10.0, minmax=(3.176724206, 24.45910382))
+    >>> std
+    Std_dev(statistic=2.9724954732045084,
+            minmax=(1.7823367265645143, 4.945614605014631))
+
+    Now we generate some normally distributed random data, and get estimates of
+    mean and standard deviation with 95% confidence intervals for those
+    estimates:
+
+    >>> n_samples = 100000
+    >>> data = stats.norm.rvs(size=n_samples)
+    >>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95)
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.hist(data, bins=100, density=True, label='Histogram of data')
+    >>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean')
+    >>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r',
+    ...            alpha=0.2, label=r'Estimated mean (95% limits)')
+    >>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale')
+    >>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2,
+    ...            label=r'Estimated scale (95% limits)')
+
+    >>> ax.legend(fontsize=10)
+    >>> ax.set_xlim([-4, 4])
+    >>> ax.set_ylim([0, 0.5])
+    >>> plt.show()
+
+    """
+    m, v, s = mvsdist(data)
+    if alpha >= 1 or alpha <= 0:
+        raise ValueError(f"0 < alpha < 1 is required, but {alpha=} was given.")
+
+    m_res = Mean(m.mean(), m.interval(alpha))
+    v_res = Variance(v.mean(), v.interval(alpha))
+    s_res = Std_dev(s.mean(), s.interval(alpha))
+
+    return m_res, v_res, s_res
+
+
+def mvsdist(data):
+    """
+    'Frozen' distributions for mean, variance, and standard deviation of data.
+
+    Parameters
+    ----------
+    data : array_like
+        Input array. Converted to 1-D using ravel.
+        Requires 2 or more data-points.
+
+    Returns
+    -------
+    mdist : "frozen" distribution object
+        Distribution object representing the mean of the data.
+    vdist : "frozen" distribution object
+        Distribution object representing the variance of the data.
+    sdist : "frozen" distribution object
+        Distribution object representing the standard deviation of the data.
+
+    See Also
+    --------
+    bayes_mvs
+
+    Notes
+    -----
+    The return values from ``bayes_mvs(data)`` is equivalent to
+    ``tuple((x.mean(), x.interval(0.90)) for x in mvsdist(data))``.
+
+    In other words, calling ``.mean()`` and ``.interval(0.90)``
+    on the three distribution objects returned from this function will give
+    the same results that are returned from `bayes_mvs`.
+
+    References
+    ----------
+    T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
+    standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278,
+    2006.
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> data = [6, 9, 12, 7, 8, 8, 13]
+    >>> mean, var, std = stats.mvsdist(data)
+
+    We now have frozen distribution objects "mean", "var" and "std" that we can
+    examine:
+
+    >>> mean.mean()
+    9.0
+    >>> mean.interval(0.95)
+    (6.6120585482655692, 11.387941451734431)
+    >>> mean.std()
+    1.1952286093343936
+
+    """
+    x = ravel(data)
+    n = len(x)
+    if n < 2:
+        raise ValueError("Need at least 2 data-points.")
+    xbar = x.mean()
+    C = x.var()
+    if n > 1000:  # gaussian approximations for large n
+        mdist = distributions.norm(loc=xbar, scale=math.sqrt(C / n))
+        sdist = distributions.norm(loc=math.sqrt(C), scale=math.sqrt(C / (2. * n)))
+        vdist = distributions.norm(loc=C, scale=math.sqrt(2.0 / n) * C)
+    else:
+        nm1 = n - 1
+        fac = n * C / 2.
+        val = nm1 / 2.
+        mdist = distributions.t(nm1, loc=xbar, scale=math.sqrt(C / nm1))
+        sdist = distributions.gengamma(val, -2, scale=math.sqrt(fac))
+        vdist = distributions.invgamma(val, scale=fac)
+    return mdist, vdist, sdist
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, default_axis=None
+)
+def kstat(data, n=2, *, axis=None):
+    r"""
+    Return the `n` th k-statistic ( ``1<=n<=4`` so far).
+
+    The `n` th k-statistic ``k_n`` is the unique symmetric unbiased estimator of the
+    `n` th cumulant :math:`\kappa_n` [1]_ [2]_.
+
+    Parameters
+    ----------
+    data : array_like
+        Input array.
+    n : int, {1, 2, 3, 4}, optional
+        Default is equal to 2.
+    axis : int or None, default: None
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear
+        in a corresponding element of the output. If ``None``, the input will
+        be raveled before computing the statistic.
+
+    Returns
+    -------
+    kstat : float
+        The `n` th k-statistic.
+
+    See Also
+    --------
+    kstatvar : Returns an unbiased estimator of the variance of the k-statistic
+    moment : Returns the n-th central moment about the mean for a sample.
+
+    Notes
+    -----
+    For a sample size :math:`n`, the first few k-statistics are given by
+
+    .. math::
+
+        k_1 &= \frac{S_1}{n}, \\
+        k_2 &= \frac{nS_2 - S_1^2}{n(n-1)}, \\
+        k_3 &= \frac{2S_1^3 - 3nS_1S_2 + n^2S_3}{n(n-1)(n-2)}, \\
+        k_4 &= \frac{-6S_1^4 + 12nS_1^2S_2 - 3n(n-1)S_2^2 - 4n(n+1)S_1S_3
+        + n^2(n+1)S_4}{n (n-1)(n-2)(n-3)},
+
+    where
+
+    .. math::
+
+        S_r \equiv \sum_{i=1}^n X_i^r,
+
+    and :math:`X_i` is the :math:`i` th data point.
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/k-Statistic.html
+
+    .. [2] http://mathworld.wolfram.com/Cumulant.html
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> from numpy.random import default_rng
+    >>> rng = default_rng()
+
+    As sample size increases, `n`-th moment and `n`-th k-statistic converge to the
+    same number (although they aren't identical). In the case of the normal
+    distribution, they converge to zero.
+
+    >>> for i in range(2,8):
+    ...     x = rng.normal(size=10**i)
+    ...     m, k = stats.moment(x, 3), stats.kstat(x, 3)
+    ...     print(f"{i=}: {m=:.3g}, {k=:.3g}, {(m-k)=:.3g}")
+    i=2: m=-0.631, k=-0.651, (m-k)=0.0194  # random
+    i=3: m=0.0282, k=0.0283, (m-k)=-8.49e-05
+    i=4: m=-0.0454, k=-0.0454, (m-k)=1.36e-05
+    i=6: m=7.53e-05, k=7.53e-05, (m-k)=-2.26e-09
+    i=7: m=0.00166, k=0.00166, (m-k)=-4.99e-09
+    i=8: m=-2.88e-06 k=-2.88e-06, (m-k)=8.63e-13
+    """
+    xp = array_namespace(data)
+    data = xp.asarray(data)
+    if n > 4 or n < 1:
+        raise ValueError("k-statistics only supported for 1<=n<=4")
+    n = int(n)
+    if axis is None:
+        data = xp.reshape(data, (-1,))
+        axis = 0
+
+    N = data.shape[axis]
+
+    S = [None] + [xp.sum(data**k, axis=axis) for k in range(1, n + 1)]
+    if n == 1:
+        return S[1] * 1.0/N
+    elif n == 2:
+        return (N*S[2] - S[1]**2.0) / (N*(N - 1.0))
+    elif n == 3:
+        return (2*S[1]**3 - 3*N*S[1]*S[2] + N*N*S[3]) / (N*(N - 1.0)*(N - 2.0))
+    elif n == 4:
+        return ((-6*S[1]**4 + 12*N*S[1]**2 * S[2] - 3*N*(N-1.0)*S[2]**2 -
+                 4*N*(N+1)*S[1]*S[3] + N*N*(N+1)*S[4]) /
+                (N*(N-1.0)*(N-2.0)*(N-3.0)))
+    else:
+        raise ValueError("Should not be here.")
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, default_axis=None
+)
+def kstatvar(data, n=2, *, axis=None):
+    r"""Return an unbiased estimator of the variance of the k-statistic.
+
+    See `kstat` and [1]_ for more details about the k-statistic.
+
+    Parameters
+    ----------
+    data : array_like
+        Input array.
+    n : int, {1, 2}, optional
+        Default is equal to 2.
+    axis : int or None, default: None
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear
+        in a corresponding element of the output. If ``None``, the input will
+        be raveled before computing the statistic.
+
+    Returns
+    -------
+    kstatvar : float
+        The `n` th k-statistic variance.
+
+    See Also
+    --------
+    kstat : Returns the n-th k-statistic.
+    moment : Returns the n-th central moment about the mean for a sample.
+
+    Notes
+    -----
+    Unbiased estimators of the variances of the first two k-statistics are given by
+
+    .. math::
+
+        \mathrm{var}(k_1) &= \frac{k_2}{n}, \\
+        \mathrm{var}(k_2) &= \frac{2k_2^2n + (n-1)k_4}{n(n - 1)}.
+
+    References
+    ----------
+    .. [1] http://mathworld.wolfram.com/k-Statistic.html
+
+    """  # noqa: E501
+    xp = array_namespace(data)
+    data = xp.asarray(data)
+    if axis is None:
+        data = xp.reshape(data, (-1,))
+        axis = 0
+    N = data.shape[axis]
+
+    if n == 1:
+        return kstat(data, n=2, axis=axis, _no_deco=True) * 1.0/N
+    elif n == 2:
+        k2 = kstat(data, n=2, axis=axis, _no_deco=True)
+        k4 = kstat(data, n=4, axis=axis, _no_deco=True)
+        return (2*N*k2**2 + (N-1)*k4) / (N*(N+1))
+    else:
+        raise ValueError("Only n=1 or n=2 supported.")
+
+
+def _calc_uniform_order_statistic_medians(n):
+    """Approximations of uniform order statistic medians.
+
+    Parameters
+    ----------
+    n : int
+        Sample size.
+
+    Returns
+    -------
+    v : 1d float array
+        Approximations of the order statistic medians.
+
+    References
+    ----------
+    .. [1] James J. Filliben, "The Probability Plot Correlation Coefficient
+           Test for Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
+
+    Examples
+    --------
+    Order statistics of the uniform distribution on the unit interval
+    are marginally distributed according to beta distributions.
+    The expectations of these order statistic are evenly spaced across
+    the interval, but the distributions are skewed in a way that
+    pushes the medians slightly towards the endpoints of the unit interval:
+
+    >>> import numpy as np
+    >>> n = 4
+    >>> k = np.arange(1, n+1)
+    >>> from scipy.stats import beta
+    >>> a = k
+    >>> b = n-k+1
+    >>> beta.mean(a, b)
+    array([0.2, 0.4, 0.6, 0.8])
+    >>> beta.median(a, b)
+    array([0.15910358, 0.38572757, 0.61427243, 0.84089642])
+
+    The Filliben approximation uses the exact medians of the smallest
+    and greatest order statistics, and the remaining medians are approximated
+    by points spread evenly across a sub-interval of the unit interval:
+
+    >>> from scipy.stats._morestats import _calc_uniform_order_statistic_medians
+    >>> _calc_uniform_order_statistic_medians(n)
+    array([0.15910358, 0.38545246, 0.61454754, 0.84089642])
+
+    This plot shows the skewed distributions of the order statistics
+    of a sample of size four from a uniform distribution on the unit interval:
+
+    >>> import matplotlib.pyplot as plt
+    >>> x = np.linspace(0.0, 1.0, num=50, endpoint=True)
+    >>> pdfs = [beta.pdf(x, a[i], b[i]) for i in range(n)]
+    >>> plt.figure()
+    >>> plt.plot(x, pdfs[0], x, pdfs[1], x, pdfs[2], x, pdfs[3])
+
+    """
+    v = np.empty(n, dtype=np.float64)
+    v[-1] = 0.5**(1.0 / n)
+    v[0] = 1 - v[-1]
+    i = np.arange(2, n)
+    v[1:-1] = (i - 0.3175) / (n + 0.365)
+    return v
+
+
+def _parse_dist_kw(dist, enforce_subclass=True):
+    """Parse `dist` keyword.
+
+    Parameters
+    ----------
+    dist : str or stats.distributions instance.
+        Several functions take `dist` as a keyword, hence this utility
+        function.
+    enforce_subclass : bool, optional
+        If True (default), `dist` needs to be a
+        `_distn_infrastructure.rv_generic` instance.
+        It can sometimes be useful to set this keyword to False, if a function
+        wants to accept objects that just look somewhat like such an instance
+        (for example, they have a ``ppf`` method).
+
+    """
+    if isinstance(dist, rv_generic):
+        pass
+    elif isinstance(dist, str):
+        try:
+            dist = getattr(distributions, dist)
+        except AttributeError as e:
+            raise ValueError(f"{dist} is not a valid distribution name") from e
+    elif enforce_subclass:
+        msg = ("`dist` should be a stats.distributions instance or a string "
+               "with the name of such a distribution.")
+        raise ValueError(msg)
+
+    return dist
+
+
+def _add_axis_labels_title(plot, xlabel, ylabel, title):
+    """Helper function to add axes labels and a title to stats plots."""
+    try:
+        if hasattr(plot, 'set_title'):
+            # Matplotlib Axes instance or something that looks like it
+            plot.set_title(title)
+            plot.set_xlabel(xlabel)
+            plot.set_ylabel(ylabel)
+        else:
+            # matplotlib.pyplot module
+            plot.title(title)
+            plot.xlabel(xlabel)
+            plot.ylabel(ylabel)
+    except Exception:
+        # Not an MPL object or something that looks (enough) like it.
+        # Don't crash on adding labels or title
+        pass
+
+
+def probplot(x, sparams=(), dist='norm', fit=True, plot=None, rvalue=False):
+    """
+    Calculate quantiles for a probability plot, and optionally show the plot.
+
+    Generates a probability plot of sample data against the quantiles of a
+    specified theoretical distribution (the normal distribution by default).
+    `probplot` optionally calculates a best-fit line for the data and plots the
+    results using Matplotlib or a given plot function.
+
+    Parameters
+    ----------
+    x : array_like
+        Sample/response data from which `probplot` creates the plot.
+    sparams : tuple, optional
+        Distribution-specific shape parameters (shape parameters plus location
+        and scale).
+    dist : str or stats.distributions instance, optional
+        Distribution or distribution function name. The default is 'norm' for a
+        normal probability plot.  Objects that look enough like a
+        stats.distributions instance (i.e. they have a ``ppf`` method) are also
+        accepted.
+    fit : bool, optional
+        Fit a least-squares regression (best-fit) line to the sample data if
+        True (default).
+    plot : object, optional
+        If given, plots the quantiles.
+        If given and `fit` is True, also plots the least squares fit.
+        `plot` is an object that has to have methods "plot" and "text".
+        The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
+        or a custom object with the same methods.
+        Default is None, which means that no plot is created.
+    rvalue : bool, optional
+        If `plot` is provided and `fit` is True, setting `rvalue` to True
+        includes the coefficient of determination on the plot.
+        Default is False.
+
+    Returns
+    -------
+    (osm, osr) : tuple of ndarrays
+        Tuple of theoretical quantiles (osm, or order statistic medians) and
+        ordered responses (osr).  `osr` is simply sorted input `x`.
+        For details on how `osm` is calculated see the Notes section.
+    (slope, intercept, r) : tuple of floats, optional
+        Tuple  containing the result of the least-squares fit, if that is
+        performed by `probplot`. `r` is the square root of the coefficient of
+        determination.  If ``fit=False`` and ``plot=None``, this tuple is not
+        returned.
+
+    Notes
+    -----
+    Even if `plot` is given, the figure is not shown or saved by `probplot`;
+    ``plt.show()`` or ``plt.savefig('figname.png')`` should be used after
+    calling `probplot`.
+
+    `probplot` generates a probability plot, which should not be confused with
+    a Q-Q or a P-P plot.  Statsmodels has more extensive functionality of this
+    type, see ``statsmodels.api.ProbPlot``.
+
+    The formula used for the theoretical quantiles (horizontal axis of the
+    probability plot) is Filliben's estimate::
+
+        quantiles = dist.ppf(val), for
+
+                0.5**(1/n),                  for i = n
+          val = (i - 0.3175) / (n + 0.365),  for i = 2, ..., n-1
+                1 - 0.5**(1/n),              for i = 1
+
+    where ``i`` indicates the i-th ordered value and ``n`` is the total number
+    of values.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> nsample = 100
+    >>> rng = np.random.default_rng()
+
+    A t distribution with small degrees of freedom:
+
+    >>> ax1 = plt.subplot(221)
+    >>> x = stats.t.rvs(3, size=nsample, random_state=rng)
+    >>> res = stats.probplot(x, plot=plt)
+
+    A t distribution with larger degrees of freedom:
+
+    >>> ax2 = plt.subplot(222)
+    >>> x = stats.t.rvs(25, size=nsample, random_state=rng)
+    >>> res = stats.probplot(x, plot=plt)
+
+    A mixture of two normal distributions with broadcasting:
+
+    >>> ax3 = plt.subplot(223)
+    >>> x = stats.norm.rvs(loc=[0,5], scale=[1,1.5],
+    ...                    size=(nsample//2,2), random_state=rng).ravel()
+    >>> res = stats.probplot(x, plot=plt)
+
+    A standard normal distribution:
+
+    >>> ax4 = plt.subplot(224)
+    >>> x = stats.norm.rvs(loc=0, scale=1, size=nsample, random_state=rng)
+    >>> res = stats.probplot(x, plot=plt)
+
+    Produce a new figure with a loggamma distribution, using the ``dist`` and
+    ``sparams`` keywords:
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> x = stats.loggamma.rvs(c=2.5, size=500, random_state=rng)
+    >>> res = stats.probplot(x, dist=stats.loggamma, sparams=(2.5,), plot=ax)
+    >>> ax.set_title("Probplot for loggamma dist with shape parameter 2.5")
+
+    Show the results with Matplotlib:
+
+    >>> plt.show()
+
+    """
+    x = np.asarray(x)
+    if x.size == 0:
+        if fit:
+            return (x, x), (np.nan, np.nan, 0.0)
+        else:
+            return x, x
+
+    osm_uniform = _calc_uniform_order_statistic_medians(len(x))
+    dist = _parse_dist_kw(dist, enforce_subclass=False)
+    if sparams is None:
+        sparams = ()
+    if isscalar(sparams):
+        sparams = (sparams,)
+    if not isinstance(sparams, tuple):
+        sparams = tuple(sparams)
+
+    osm = dist.ppf(osm_uniform, *sparams)
+    osr = sort(x)
+    if fit:
+        # perform a linear least squares fit.
+        slope, intercept, r, prob, _ = _stats_py.linregress(osm, osr)
+
+    if plot is not None:
+        plot.plot(osm, osr, 'bo')
+        if fit:
+            plot.plot(osm, slope*osm + intercept, 'r-')
+        _add_axis_labels_title(plot, xlabel='Theoretical quantiles',
+                               ylabel='Ordered Values',
+                               title='Probability Plot')
+
+        # Add R^2 value to the plot as text
+        if fit and rvalue:
+            xmin = amin(osm)
+            xmax = amax(osm)
+            ymin = amin(x)
+            ymax = amax(x)
+            posx = xmin + 0.70 * (xmax - xmin)
+            posy = ymin + 0.01 * (ymax - ymin)
+            plot.text(posx, posy, f"$R^2={r ** 2:1.4f}$")
+
+    if fit:
+        return (osm, osr), (slope, intercept, r)
+    else:
+        return osm, osr
+
+
+def ppcc_max(x, brack=(0.0, 1.0), dist='tukeylambda'):
+    """Calculate the shape parameter that maximizes the PPCC.
+
+    The probability plot correlation coefficient (PPCC) plot can be used
+    to determine the optimal shape parameter for a one-parameter family
+    of distributions. ``ppcc_max`` returns the shape parameter that would
+    maximize the probability plot correlation coefficient for the given
+    data to a one-parameter family of distributions.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    brack : tuple, optional
+        Triple (a,b,c) where (a>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> c = 2.5
+    >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng)
+
+    Generate the PPCC plot for this data with the Weibull distribution.
+
+    >>> fig, ax = plt.subplots(figsize=(8, 6))
+    >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax)
+
+    We calculate the value where the shape should reach its maximum and a
+    red line is drawn there. The line should coincide with the highest
+    point in the PPCC graph.
+
+    >>> cmax = stats.ppcc_max(x, brack=(c/2, 2*c), dist='weibull_min')
+    >>> ax.axvline(cmax, color='r')
+    >>> plt.show()
+
+    """
+    dist = _parse_dist_kw(dist)
+    osm_uniform = _calc_uniform_order_statistic_medians(len(x))
+    osr = sort(x)
+
+    # this function computes the x-axis values of the probability plot
+    #  and computes a linear regression (including the correlation)
+    #  and returns 1-r so that a minimization function maximizes the
+    #  correlation
+    def tempfunc(shape, mi, yvals, func):
+        xvals = func(mi, shape)
+        r, prob = _stats_py.pearsonr(xvals, yvals)
+        return 1 - r
+
+    return optimize.brent(tempfunc, brack=brack,
+                          args=(osm_uniform, osr, dist.ppf))
+
+
+def ppcc_plot(x, a, b, dist='tukeylambda', plot=None, N=80):
+    """Calculate and optionally plot probability plot correlation coefficient.
+
+    The probability plot correlation coefficient (PPCC) plot can be used to
+    determine the optimal shape parameter for a one-parameter family of
+    distributions.  It cannot be used for distributions without shape
+    parameters
+    (like the normal distribution) or with multiple shape parameters.
+
+    By default a Tukey-Lambda distribution (`stats.tukeylambda`) is used. A
+    Tukey-Lambda PPCC plot interpolates from long-tailed to short-tailed
+    distributions via an approximately normal one, and is therefore
+    particularly useful in practice.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    a, b : scalar
+        Lower and upper bounds of the shape parameter to use.
+    dist : str or stats.distributions instance, optional
+        Distribution or distribution function name.  Objects that look enough
+        like a stats.distributions instance (i.e. they have a ``ppf`` method)
+        are also accepted.  The default is ``'tukeylambda'``.
+    plot : object, optional
+        If given, plots PPCC against the shape parameter.
+        `plot` is an object that has to have methods "plot" and "text".
+        The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
+        or a custom object with the same methods.
+        Default is None, which means that no plot is created.
+    N : int, optional
+        Number of points on the horizontal axis (equally distributed from
+        `a` to `b`).
+
+    Returns
+    -------
+    svals : ndarray
+        The shape values for which `ppcc` was calculated.
+    ppcc : ndarray
+        The calculated probability plot correlation coefficient values.
+
+    See Also
+    --------
+    ppcc_max, probplot, boxcox_normplot, tukeylambda
+
+    References
+    ----------
+    J.J. Filliben, "The Probability Plot Correlation Coefficient Test for
+    Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
+
+    Examples
+    --------
+    First we generate some random data from a Weibull distribution
+    with shape parameter 2.5, and plot the histogram of the data:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng()
+    >>> c = 2.5
+    >>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng)
+
+    Take a look at the histogram of the data.
+
+    >>> fig1, ax = plt.subplots(figsize=(9, 4))
+    >>> ax.hist(x, bins=50)
+    >>> ax.set_title('Histogram of x')
+    >>> plt.show()
+
+    Now we explore this data with a PPCC plot as well as the related
+    probability plot and Box-Cox normplot.  A red line is drawn where we
+    expect the PPCC value to be maximal (at the shape parameter ``c``
+    used above):
+
+    >>> fig2 = plt.figure(figsize=(12, 4))
+    >>> ax1 = fig2.add_subplot(1, 3, 1)
+    >>> ax2 = fig2.add_subplot(1, 3, 2)
+    >>> ax3 = fig2.add_subplot(1, 3, 3)
+    >>> res = stats.probplot(x, plot=ax1)
+    >>> res = stats.boxcox_normplot(x, -4, 4, plot=ax2)
+    >>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax3)
+    >>> ax3.axvline(c, color='r')
+    >>> plt.show()
+
+    """
+    if b <= a:
+        raise ValueError("`b` has to be larger than `a`.")
+
+    svals = np.linspace(a, b, num=N)
+    ppcc = np.empty_like(svals)
+    for k, sval in enumerate(svals):
+        _, r2 = probplot(x, sval, dist=dist, fit=True)
+        ppcc[k] = r2[-1]
+
+    if plot is not None:
+        plot.plot(svals, ppcc, 'x')
+        _add_axis_labels_title(plot, xlabel='Shape Values',
+                               ylabel='Prob Plot Corr. Coef.',
+                               title=f'({dist}) PPCC Plot')
+
+    return svals, ppcc
+
+
+def _log_mean(logx):
+    # compute log of mean of x from log(x)
+    res = special.logsumexp(logx, axis=0) - math.log(logx.shape[0])
+    return res
+
+
+def _log_var(logx, xp):
+    # compute log of variance of x from log(x)
+    logmean = _log_mean(logx)
+    # get complex dtype with component dtypes same as `logx` dtype;
+    # see data-apis/array-api#841
+    dtype = xp.result_type(logx.dtype, xp.complex64)
+    pij = xp.full(logx.shape, pi * 1j, dtype=dtype)
+    logxmu = special.logsumexp(xp.stack((logx, logmean + pij)), axis=0)
+    res = (xp.real(xp.asarray(special.logsumexp(2 * logxmu, axis=0)))
+           - math.log(logx.shape[0]))
+    return res
+
+
+def boxcox_llf(lmb, data):
+    r"""The boxcox log-likelihood function.
+
+    Parameters
+    ----------
+    lmb : scalar
+        Parameter for Box-Cox transformation.  See `boxcox` for details.
+    data : array_like
+        Data to calculate Box-Cox log-likelihood for.  If `data` is
+        multi-dimensional, the log-likelihood is calculated along the first
+        axis.
+
+    Returns
+    -------
+    llf : float or ndarray
+        Box-Cox log-likelihood of `data` given `lmb`.  A float for 1-D `data`,
+        an array otherwise.
+
+    See Also
+    --------
+    boxcox, probplot, boxcox_normplot, boxcox_normmax
+
+    Notes
+    -----
+    The Box-Cox log-likelihood function is defined here as
+
+    .. math::
+
+        llf = (\lambda - 1) \sum_i(\log(x_i)) -
+              N/2 \log(\sum_i (y_i - \bar{y})^2 / N),
+
+    where ``y`` is the Box-Cox transformed input data ``x``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes
+
+    Generate some random variates and calculate Box-Cox log-likelihood values
+    for them for a range of ``lmbda`` values:
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.loggamma.rvs(5, loc=10, size=1000, random_state=rng)
+    >>> lmbdas = np.linspace(-2, 10)
+    >>> llf = np.zeros(lmbdas.shape, dtype=float)
+    >>> for ii, lmbda in enumerate(lmbdas):
+    ...     llf[ii] = stats.boxcox_llf(lmbda, x)
+
+    Also find the optimal lmbda value with `boxcox`:
+
+    >>> x_most_normal, lmbda_optimal = stats.boxcox(x)
+
+    Plot the log-likelihood as function of lmbda.  Add the optimal lmbda as a
+    horizontal line to check that that's really the optimum:
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(lmbdas, llf, 'b.-')
+    >>> ax.axhline(stats.boxcox_llf(lmbda_optimal, x), color='r')
+    >>> ax.set_xlabel('lmbda parameter')
+    >>> ax.set_ylabel('Box-Cox log-likelihood')
+
+    Now add some probability plots to show that where the log-likelihood is
+    maximized the data transformed with `boxcox` looks closest to normal:
+
+    >>> locs = [3, 10, 4]  # 'lower left', 'center', 'lower right'
+    >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs):
+    ...     xt = stats.boxcox(x, lmbda=lmbda)
+    ...     (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)
+    ...     ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc)
+    ...     ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')
+    ...     ax_inset.set_xticklabels([])
+    ...     ax_inset.set_yticklabels([])
+    ...     ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda)
+
+    >>> plt.show()
+
+    """
+    xp = array_namespace(data)
+    data = xp.asarray(data)
+    N = data.shape[0]
+    if N == 0:
+        return xp.nan
+
+    dt = data.dtype
+    if xp.isdtype(dt, 'integral'):
+        data = xp.asarray(data, dtype=xp.float64)
+        dt = xp.float64
+
+    logdata = xp.log(data)
+
+    # Compute the variance of the transformed data.
+    if lmb == 0:
+        logvar = xp.log(xp.var(logdata, axis=0))
+    else:
+        # Transform without the constant offset 1/lmb.  The offset does
+        # not affect the variance, and the subtraction of the offset can
+        # lead to loss of precision.
+        # Division by lmb can be factored out to enhance numerical stability.
+        logx = lmb * logdata
+        logvar = _log_var(logx, xp) - 2 * math.log(abs(lmb))
+
+    res = (lmb - 1) * xp.sum(logdata, axis=0) - N/2 * logvar
+    res = xp.astype(res, dt)
+    res = res[()] if res.ndim == 0 else res
+    return res
+
+
+def _boxcox_conf_interval(x, lmax, alpha):
+    # Need to find the lambda for which
+    #  f(x,lmbda) >= f(x,lmax) - 0.5*chi^2_alpha;1
+    fac = 0.5 * distributions.chi2.ppf(1 - alpha, 1)
+    target = boxcox_llf(lmax, x) - fac
+
+    def rootfunc(lmbda, data, target):
+        return boxcox_llf(lmbda, data) - target
+
+    # Find positive endpoint of interval in which answer is to be found
+    newlm = lmax + 0.5
+    N = 0
+    while (rootfunc(newlm, x, target) > 0.0) and (N < 500):
+        newlm += 0.1
+        N += 1
+
+    if N == 500:
+        raise RuntimeError("Could not find endpoint.")
+
+    lmplus = optimize.brentq(rootfunc, lmax, newlm, args=(x, target))
+
+    # Now find negative interval in the same way
+    newlm = lmax - 0.5
+    N = 0
+    while (rootfunc(newlm, x, target) > 0.0) and (N < 500):
+        newlm -= 0.1
+        N += 1
+
+    if N == 500:
+        raise RuntimeError("Could not find endpoint.")
+
+    lmminus = optimize.brentq(rootfunc, newlm, lmax, args=(x, target))
+    return lmminus, lmplus
+
+
+def boxcox(x, lmbda=None, alpha=None, optimizer=None):
+    r"""Return a dataset transformed by a Box-Cox power transformation.
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array to be transformed.
+
+        If `lmbda` is not None, this is an alias of
+        `scipy.special.boxcox`.
+        Returns nan if ``x < 0``; returns -inf if ``x == 0 and lmbda < 0``.
+
+        If `lmbda` is None, array must be positive, 1-dimensional, and
+        non-constant.
+
+    lmbda : scalar, optional
+        If `lmbda` is None (default), find the value of `lmbda` that maximizes
+        the log-likelihood function and return it as the second output
+        argument.
+
+        If `lmbda` is not None, do the transformation for that value.
+
+    alpha : float, optional
+        If `lmbda` is None and `alpha` is not None (default), return the
+        ``100 * (1-alpha)%`` confidence  interval for `lmbda` as the third
+        output argument. Must be between 0.0 and 1.0.
+
+        If `lmbda` is not None, `alpha` is ignored.
+    optimizer : callable, optional
+        If `lmbda` is None, `optimizer` is the scalar optimizer used to find
+        the value of `lmbda` that minimizes the negative log-likelihood
+        function. `optimizer` is a callable that accepts one argument:
+
+        fun : callable
+            The objective function, which evaluates the negative
+            log-likelihood function at a provided value of `lmbda`
+
+        and returns an object, such as an instance of
+        `scipy.optimize.OptimizeResult`, which holds the optimal value of
+        `lmbda` in an attribute `x`.
+
+        See the example in `boxcox_normmax` or the documentation of
+        `scipy.optimize.minimize_scalar` for more information.
+
+        If `lmbda` is not None, `optimizer` is ignored.
+
+    Returns
+    -------
+    boxcox : ndarray
+        Box-Cox power transformed array.
+    maxlog : float, optional
+        If the `lmbda` parameter is None, the second returned argument is
+        the `lmbda` that maximizes the log-likelihood function.
+    (min_ci, max_ci) : tuple of float, optional
+        If `lmbda` parameter is None and `alpha` is not None, this returned
+        tuple of floats represents the minimum and maximum confidence limits
+        given `alpha`.
+
+    See Also
+    --------
+    probplot, boxcox_normplot, boxcox_normmax, boxcox_llf
+
+    Notes
+    -----
+    The Box-Cox transform is given by::
+
+        y = (x**lmbda - 1) / lmbda,  for lmbda != 0
+            log(x),                  for lmbda = 0
+
+    `boxcox` requires the input data to be positive.  Sometimes a Box-Cox
+    transformation provides a shift parameter to achieve this; `boxcox` does
+    not.  Such a shift parameter is equivalent to adding a positive constant to
+    `x` before calling `boxcox`.
+
+    The confidence limits returned when `alpha` is provided give the interval
+    where:
+
+    .. math::
+
+        llf(\hat{\lambda}) - llf(\lambda) < \frac{1}{2}\chi^2(1 - \alpha, 1),
+
+    with ``llf`` the log-likelihood function and :math:`\chi^2` the chi-squared
+    function.
+
+    References
+    ----------
+    G.E.P. Box and D.R. Cox, "An Analysis of Transformations", Journal of the
+    Royal Statistical Society B, 26, 211-252 (1964).
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    We generate some random variates from a non-normal distribution and make a
+    probability plot for it, to show it is non-normal in the tails:
+
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(211)
+    >>> x = stats.loggamma.rvs(5, size=500) + 5
+    >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1)
+    >>> ax1.set_xlabel('')
+    >>> ax1.set_title('Probplot against normal distribution')
+
+    We now use `boxcox` to transform the data so it's closest to normal:
+
+    >>> ax2 = fig.add_subplot(212)
+    >>> xt, _ = stats.boxcox(x)
+    >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2)
+    >>> ax2.set_title('Probplot after Box-Cox transformation')
+
+    >>> plt.show()
+
+    """
+    x = np.asarray(x)
+
+    if lmbda is not None:  # single transformation
+        return special.boxcox(x, lmbda)
+
+    if x.ndim != 1:
+        raise ValueError("Data must be 1-dimensional.")
+
+    if x.size == 0:
+        return x
+
+    if np.all(x == x[0]):
+        raise ValueError("Data must not be constant.")
+
+    if np.any(x <= 0):
+        raise ValueError("Data must be positive.")
+
+    # If lmbda=None, find the lmbda that maximizes the log-likelihood function.
+    lmax = boxcox_normmax(x, method='mle', optimizer=optimizer)
+    y = boxcox(x, lmax)
+
+    if alpha is None:
+        return y, lmax
+    else:
+        # Find confidence interval
+        interval = _boxcox_conf_interval(x, lmax, alpha)
+        return y, lmax, interval
+
+
+def _boxcox_inv_lmbda(x, y):
+    # compute lmbda given x and y for Box-Cox transformation
+    num = special.lambertw(-(x ** (-1 / y)) * np.log(x) / y, k=-1)
+    return np.real(-num / np.log(x) - 1 / y)
+
+
+class _BigFloat:
+    def __repr__(self):
+        return "BIG_FLOAT"
+
+
+_BigFloat_singleton = _BigFloat()
+
+
+def boxcox_normmax(
+    x, brack=None, method='pearsonr', optimizer=None, *, ymax=_BigFloat_singleton
+):
+    """Compute optimal Box-Cox transform parameter for input data.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array. All entries must be positive, finite, real numbers.
+    brack : 2-tuple, optional, default (-2.0, 2.0)
+         The starting interval for a downhill bracket search for the default
+         `optimize.brent` solver. Note that this is in most cases not
+         critical; the final result is allowed to be outside this bracket.
+         If `optimizer` is passed, `brack` must be None.
+    method : str, optional
+        The method to determine the optimal transform parameter (`boxcox`
+        ``lmbda`` parameter). Options are:
+
+        'pearsonr'  (default)
+            Maximizes the Pearson correlation coefficient between
+            ``y = boxcox(x)`` and the expected values for ``y`` if `x` would be
+            normally-distributed.
+
+        'mle'
+            Maximizes the log-likelihood `boxcox_llf`.  This is the method used
+            in `boxcox`.
+
+        'all'
+            Use all optimization methods available, and return all results.
+            Useful to compare different methods.
+    optimizer : callable, optional
+        `optimizer` is a callable that accepts one argument:
+
+        fun : callable
+            The objective function to be minimized. `fun` accepts one argument,
+            the Box-Cox transform parameter `lmbda`, and returns the value of
+            the function (e.g., the negative log-likelihood) at the provided
+            argument. The job of `optimizer` is to find the value of `lmbda`
+            that *minimizes* `fun`.
+
+        and returns an object, such as an instance of
+        `scipy.optimize.OptimizeResult`, which holds the optimal value of
+        `lmbda` in an attribute `x`.
+
+        See the example below or the documentation of
+        `scipy.optimize.minimize_scalar` for more information.
+    ymax : float, optional
+        The unconstrained optimal transform parameter may cause Box-Cox
+        transformed data to have extreme magnitude or even overflow.
+        This parameter constrains MLE optimization such that the magnitude
+        of the transformed `x` does not exceed `ymax`. The default is
+        the maximum value of the input dtype. If set to infinity,
+        `boxcox_normmax` returns the unconstrained optimal lambda.
+        Ignored when ``method='pearsonr'``.
+
+    Returns
+    -------
+    maxlog : float or ndarray
+        The optimal transform parameter found.  An array instead of a scalar
+        for ``method='all'``.
+
+    See Also
+    --------
+    boxcox, boxcox_llf, boxcox_normplot, scipy.optimize.minimize_scalar
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    We can generate some data and determine the optimal ``lmbda`` in various
+    ways:
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5
+    >>> y, lmax_mle = stats.boxcox(x)
+    >>> lmax_pearsonr = stats.boxcox_normmax(x)
+
+    >>> lmax_mle
+    2.217563431465757
+    >>> lmax_pearsonr
+    2.238318660200961
+    >>> stats.boxcox_normmax(x, method='all')
+    array([2.23831866, 2.21756343])
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> prob = stats.boxcox_normplot(x, -10, 10, plot=ax)
+    >>> ax.axvline(lmax_mle, color='r')
+    >>> ax.axvline(lmax_pearsonr, color='g', ls='--')
+
+    >>> plt.show()
+
+    Alternatively, we can define our own `optimizer` function. Suppose we
+    are only interested in values of `lmbda` on the interval [6, 7], we
+    want to use `scipy.optimize.minimize_scalar` with ``method='bounded'``,
+    and we want to use tighter tolerances when optimizing the log-likelihood
+    function. To do this, we define a function that accepts positional argument
+    `fun` and uses `scipy.optimize.minimize_scalar` to minimize `fun` subject
+    to the provided bounds and tolerances:
+
+    >>> from scipy import optimize
+    >>> options = {'xatol': 1e-12}  # absolute tolerance on `x`
+    >>> def optimizer(fun):
+    ...     return optimize.minimize_scalar(fun, bounds=(6, 7),
+    ...                                     method="bounded", options=options)
+    >>> stats.boxcox_normmax(x, optimizer=optimizer)
+    6.000000000
+    """
+    x = np.asarray(x)
+
+    if not np.all(np.isfinite(x) & (x >= 0)):
+        message = ("The `x` argument of `boxcox_normmax` must contain "
+                   "only positive, finite, real numbers.")
+        raise ValueError(message)
+
+    end_msg = "exceed specified `ymax`."
+    if ymax is _BigFloat_singleton:
+        dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64
+        # 10000 is a safety factor because `special.boxcox` overflows prematurely.
+        ymax = np.finfo(dtype).max / 10000
+        end_msg = f"overflow in {dtype}."
+    elif ymax <= 0:
+        raise ValueError("`ymax` must be strictly positive")
+
+    # If optimizer is not given, define default 'brent' optimizer.
+    if optimizer is None:
+
+        # Set default value for `brack`.
+        if brack is None:
+            brack = (-2.0, 2.0)
+
+        def _optimizer(func, args):
+            return optimize.brent(func, args=args, brack=brack)
+
+    # Otherwise check optimizer.
+    else:
+        if not callable(optimizer):
+            raise ValueError("`optimizer` must be a callable")
+
+        if brack is not None:
+            raise ValueError("`brack` must be None if `optimizer` is given")
+
+        # `optimizer` is expected to return a `OptimizeResult` object, we here
+        # get the solution to the optimization problem.
+        def _optimizer(func, args):
+            def func_wrapped(x):
+                return func(x, *args)
+            return getattr(optimizer(func_wrapped), 'x', None)
+
+    def _pearsonr(x):
+        osm_uniform = _calc_uniform_order_statistic_medians(len(x))
+        xvals = distributions.norm.ppf(osm_uniform)
+
+        def _eval_pearsonr(lmbda, xvals, samps):
+            # This function computes the x-axis values of the probability plot
+            # and computes a linear regression (including the correlation) and
+            # returns ``1 - r`` so that a minimization function maximizes the
+            # correlation.
+            y = boxcox(samps, lmbda)
+            yvals = np.sort(y)
+            r, prob = _stats_py.pearsonr(xvals, yvals)
+            return 1 - r
+
+        return _optimizer(_eval_pearsonr, args=(xvals, x))
+
+    def _mle(x):
+        def _eval_mle(lmb, data):
+            # function to minimize
+            return -boxcox_llf(lmb, data)
+
+        return _optimizer(_eval_mle, args=(x,))
+
+    def _all(x):
+        maxlog = np.empty(2, dtype=float)
+        maxlog[0] = _pearsonr(x)
+        maxlog[1] = _mle(x)
+        return maxlog
+
+    methods = {'pearsonr': _pearsonr,
+               'mle': _mle,
+               'all': _all}
+    if method not in methods.keys():
+        raise ValueError(f"Method {method} not recognized.")
+
+    optimfunc = methods[method]
+
+    res = optimfunc(x)
+
+    if res is None:
+        message = ("The `optimizer` argument of `boxcox_normmax` must return "
+                   "an object containing the optimal `lmbda` in attribute `x`.")
+        raise ValueError(message)
+    elif not np.isinf(ymax):  # adjust the final lambda
+        # x > 1, boxcox(x) > 0; x < 1, boxcox(x) < 0
+        xmax, xmin = np.max(x), np.min(x)
+        if xmin >= 1:
+            x_treme = xmax
+        elif xmax <= 1:
+            x_treme = xmin
+        else:  # xmin < 1 < xmax
+            indicator = special.boxcox(xmax, res) > abs(special.boxcox(xmin, res))
+            if isinstance(res, np.ndarray):
+                indicator = indicator[1]  # select corresponds with 'mle'
+            x_treme = xmax if indicator else xmin
+
+        mask = abs(special.boxcox(x_treme, res)) > ymax
+        if np.any(mask):
+            message = (
+                f"The optimal lambda is {res}, but the returned lambda is the "
+                f"constrained optimum to ensure that the maximum or the minimum "
+                f"of the transformed data does not " + end_msg
+            )
+            warnings.warn(message, stacklevel=2)
+
+            # Return the constrained lambda to ensure the transformation
+            # does not cause overflow or exceed specified `ymax`
+            constrained_res = _boxcox_inv_lmbda(x_treme, ymax * np.sign(x_treme - 1))
+
+            if isinstance(res, np.ndarray):
+                res[mask] = constrained_res
+            else:
+                res = constrained_res
+    return res
+
+
+def _normplot(method, x, la, lb, plot=None, N=80):
+    """Compute parameters for a Box-Cox or Yeo-Johnson normality plot,
+    optionally show it.
+
+    See `boxcox_normplot` or `yeojohnson_normplot` for details.
+    """
+
+    if method == 'boxcox':
+        title = 'Box-Cox Normality Plot'
+        transform_func = boxcox
+    else:
+        title = 'Yeo-Johnson Normality Plot'
+        transform_func = yeojohnson
+
+    x = np.asarray(x)
+    if x.size == 0:
+        return x
+
+    if lb <= la:
+        raise ValueError("`lb` has to be larger than `la`.")
+
+    if method == 'boxcox' and np.any(x <= 0):
+        raise ValueError("Data must be positive.")
+
+    lmbdas = np.linspace(la, lb, num=N)
+    ppcc = lmbdas * 0.0
+    for i, val in enumerate(lmbdas):
+        # Determine for each lmbda the square root of correlation coefficient
+        # of transformed x
+        z = transform_func(x, lmbda=val)
+        _, (_, _, r) = probplot(z, dist='norm', fit=True)
+        ppcc[i] = r
+
+    if plot is not None:
+        plot.plot(lmbdas, ppcc, 'x')
+        _add_axis_labels_title(plot, xlabel='$\\lambda$',
+                               ylabel='Prob Plot Corr. Coef.',
+                               title=title)
+
+    return lmbdas, ppcc
+
+
+def boxcox_normplot(x, la, lb, plot=None, N=80):
+    """Compute parameters for a Box-Cox normality plot, optionally show it.
+
+    A Box-Cox normality plot shows graphically what the best transformation
+    parameter is to use in `boxcox` to obtain a distribution that is close
+    to normal.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    la, lb : scalar
+        The lower and upper bounds for the ``lmbda`` values to pass to `boxcox`
+        for Box-Cox transformations.  These are also the limits of the
+        horizontal axis of the plot if that is generated.
+    plot : object, optional
+        If given, plots the quantiles and least squares fit.
+        `plot` is an object that has to have methods "plot" and "text".
+        The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
+        or a custom object with the same methods.
+        Default is None, which means that no plot is created.
+    N : int, optional
+        Number of points on the horizontal axis (equally distributed from
+        `la` to `lb`).
+
+    Returns
+    -------
+    lmbdas : ndarray
+        The ``lmbda`` values for which a Box-Cox transform was done.
+    ppcc : ndarray
+        Probability Plot Correlation Coefficient, as obtained from `probplot`
+        when fitting the Box-Cox transformed input `x` against a normal
+        distribution.
+
+    See Also
+    --------
+    probplot, boxcox, boxcox_normmax, boxcox_llf, ppcc_max
+
+    Notes
+    -----
+    Even if `plot` is given, the figure is not shown or saved by
+    `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')``
+    should be used after calling `probplot`.
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Generate some non-normally distributed data, and create a Box-Cox plot:
+
+    >>> x = stats.loggamma.rvs(5, size=500) + 5
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> prob = stats.boxcox_normplot(x, -20, 20, plot=ax)
+
+    Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in
+    the same plot:
+
+    >>> _, maxlog = stats.boxcox(x)
+    >>> ax.axvline(maxlog, color='r')
+
+    >>> plt.show()
+
+    """
+    return _normplot('boxcox', x, la, lb, plot, N)
+
+
+def yeojohnson(x, lmbda=None):
+    r"""Return a dataset transformed by a Yeo-Johnson power transformation.
+
+    Parameters
+    ----------
+    x : ndarray
+        Input array.  Should be 1-dimensional.
+    lmbda : float, optional
+        If ``lmbda`` is ``None``, find the lambda that maximizes the
+        log-likelihood function and return it as the second output argument.
+        Otherwise the transformation is done for the given value.
+
+    Returns
+    -------
+    yeojohnson: ndarray
+        Yeo-Johnson power transformed array.
+    maxlog : float, optional
+        If the `lmbda` parameter is None, the second returned argument is
+        the lambda that maximizes the log-likelihood function.
+
+    See Also
+    --------
+    probplot, yeojohnson_normplot, yeojohnson_normmax, yeojohnson_llf, boxcox
+
+    Notes
+    -----
+    The Yeo-Johnson transform is given by::
+
+        y = ((x + 1)**lmbda - 1) / lmbda,                for x >= 0, lmbda != 0
+            log(x + 1),                                  for x >= 0, lmbda = 0
+            -((-x + 1)**(2 - lmbda) - 1) / (2 - lmbda),  for x < 0, lmbda != 2
+            -log(-x + 1),                                for x < 0, lmbda = 2
+
+    Unlike `boxcox`, `yeojohnson` does not require the input data to be
+    positive.
+
+    .. versionadded:: 1.2.0
+
+
+    References
+    ----------
+    I. Yeo and R.A. Johnson, "A New Family of Power Transformations to
+    Improve Normality or Symmetry", Biometrika 87.4 (2000):
+
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    We generate some random variates from a non-normal distribution and make a
+    probability plot for it, to show it is non-normal in the tails:
+
+    >>> fig = plt.figure()
+    >>> ax1 = fig.add_subplot(211)
+    >>> x = stats.loggamma.rvs(5, size=500) + 5
+    >>> prob = stats.probplot(x, dist=stats.norm, plot=ax1)
+    >>> ax1.set_xlabel('')
+    >>> ax1.set_title('Probplot against normal distribution')
+
+    We now use `yeojohnson` to transform the data so it's closest to normal:
+
+    >>> ax2 = fig.add_subplot(212)
+    >>> xt, lmbda = stats.yeojohnson(x)
+    >>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2)
+    >>> ax2.set_title('Probplot after Yeo-Johnson transformation')
+
+    >>> plt.show()
+
+    """
+    x = np.asarray(x)
+    if x.size == 0:
+        return x
+
+    if np.issubdtype(x.dtype, np.complexfloating):
+        raise ValueError('Yeo-Johnson transformation is not defined for '
+                         'complex numbers.')
+
+    if np.issubdtype(x.dtype, np.integer):
+        x = x.astype(np.float64, copy=False)
+
+    if lmbda is not None:
+        return _yeojohnson_transform(x, lmbda)
+
+    # if lmbda=None, find the lmbda that maximizes the log-likelihood function.
+    lmax = yeojohnson_normmax(x)
+    y = _yeojohnson_transform(x, lmax)
+
+    return y, lmax
+
+
+def _yeojohnson_transform(x, lmbda):
+    """Returns `x` transformed by the Yeo-Johnson power transform with given
+    parameter `lmbda`.
+    """
+    dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64
+    out = np.zeros_like(x, dtype=dtype)
+    pos = x >= 0  # binary mask
+
+    # when x >= 0
+    if abs(lmbda) < np.spacing(1.):
+        out[pos] = np.log1p(x[pos])
+    else:  # lmbda != 0
+        # more stable version of: ((x + 1) ** lmbda - 1) / lmbda
+        out[pos] = np.expm1(lmbda * np.log1p(x[pos])) / lmbda
+
+    # when x < 0
+    if abs(lmbda - 2) > np.spacing(1.):
+        out[~pos] = -np.expm1((2 - lmbda) * np.log1p(-x[~pos])) / (2 - lmbda)
+    else:  # lmbda == 2
+        out[~pos] = -np.log1p(-x[~pos])
+
+    return out
+
+
+def yeojohnson_llf(lmb, data):
+    r"""The yeojohnson log-likelihood function.
+
+    Parameters
+    ----------
+    lmb : scalar
+        Parameter for Yeo-Johnson transformation. See `yeojohnson` for
+        details.
+    data : array_like
+        Data to calculate Yeo-Johnson log-likelihood for. If `data` is
+        multi-dimensional, the log-likelihood is calculated along the first
+        axis.
+
+    Returns
+    -------
+    llf : float
+        Yeo-Johnson log-likelihood of `data` given `lmb`.
+
+    See Also
+    --------
+    yeojohnson, probplot, yeojohnson_normplot, yeojohnson_normmax
+
+    Notes
+    -----
+    The Yeo-Johnson log-likelihood function is defined here as
+
+    .. math::
+
+        llf = -N/2 \log(\hat{\sigma}^2) + (\lambda - 1)
+              \sum_i \text{ sign }(x_i)\log(|x_i| + 1)
+
+    where :math:`\hat{\sigma}^2` is estimated variance of the Yeo-Johnson
+    transformed input data ``x``.
+
+    .. versionadded:: 1.2.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes
+
+    Generate some random variates and calculate Yeo-Johnson log-likelihood
+    values for them for a range of ``lmbda`` values:
+
+    >>> x = stats.loggamma.rvs(5, loc=10, size=1000)
+    >>> lmbdas = np.linspace(-2, 10)
+    >>> llf = np.zeros(lmbdas.shape, dtype=float)
+    >>> for ii, lmbda in enumerate(lmbdas):
+    ...     llf[ii] = stats.yeojohnson_llf(lmbda, x)
+
+    Also find the optimal lmbda value with `yeojohnson`:
+
+    >>> x_most_normal, lmbda_optimal = stats.yeojohnson(x)
+
+    Plot the log-likelihood as function of lmbda.  Add the optimal lmbda as a
+    horizontal line to check that that's really the optimum:
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(lmbdas, llf, 'b.-')
+    >>> ax.axhline(stats.yeojohnson_llf(lmbda_optimal, x), color='r')
+    >>> ax.set_xlabel('lmbda parameter')
+    >>> ax.set_ylabel('Yeo-Johnson log-likelihood')
+
+    Now add some probability plots to show that where the log-likelihood is
+    maximized the data transformed with `yeojohnson` looks closest to normal:
+
+    >>> locs = [3, 10, 4]  # 'lower left', 'center', 'lower right'
+    >>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs):
+    ...     xt = stats.yeojohnson(x, lmbda=lmbda)
+    ...     (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)
+    ...     ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc)
+    ...     ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')
+    ...     ax_inset.set_xticklabels([])
+    ...     ax_inset.set_yticklabels([])
+    ...     ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda)
+
+    >>> plt.show()
+
+    """
+    data = np.asarray(data)
+    n_samples = data.shape[0]
+
+    if n_samples == 0:
+        return np.nan
+
+    trans = _yeojohnson_transform(data, lmb)
+    trans_var = trans.var(axis=0)
+    loglike = np.empty_like(trans_var)
+
+    # Avoid RuntimeWarning raised by np.log when the variance is too low
+    tiny_variance = trans_var < np.finfo(trans_var.dtype).tiny
+    loglike[tiny_variance] = np.inf
+
+    loglike[~tiny_variance] = (
+        -n_samples / 2 * np.log(trans_var[~tiny_variance]))
+    loglike[~tiny_variance] += (
+        (lmb - 1) * (np.sign(data) * np.log1p(np.abs(data))).sum(axis=0))
+    return loglike
+
+
+def yeojohnson_normmax(x, brack=None):
+    """Compute optimal Yeo-Johnson transform parameter.
+
+    Compute optimal Yeo-Johnson transform parameter for input data, using
+    maximum likelihood estimation.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    brack : 2-tuple, optional
+        The starting interval for a downhill bracket search with
+        `optimize.brent`. Note that this is in most cases not critical; the
+        final result is allowed to be outside this bracket. If None,
+        `optimize.fminbound` is used with bounds that avoid overflow.
+
+    Returns
+    -------
+    maxlog : float
+        The optimal transform parameter found.
+
+    See Also
+    --------
+    yeojohnson, yeojohnson_llf, yeojohnson_normplot
+
+    Notes
+    -----
+    .. versionadded:: 1.2.0
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Generate some data and determine optimal ``lmbda``
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5
+    >>> lmax = stats.yeojohnson_normmax(x)
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> prob = stats.yeojohnson_normplot(x, -10, 10, plot=ax)
+    >>> ax.axvline(lmax, color='r')
+
+    >>> plt.show()
+
+    """
+    def _neg_llf(lmbda, data):
+        llf = yeojohnson_llf(lmbda, data)
+        # reject likelihoods that are inf which are likely due to small
+        # variance in the transformed space
+        llf[np.isinf(llf)] = -np.inf
+        return -llf
+
+    with np.errstate(invalid='ignore'):
+        if not np.all(np.isfinite(x)):
+            raise ValueError('Yeo-Johnson input must be finite.')
+        if np.all(x == 0):
+            return 1.0
+        if brack is not None:
+            return optimize.brent(_neg_llf, brack=brack, args=(x,))
+        x = np.asarray(x)
+        dtype = x.dtype if np.issubdtype(x.dtype, np.floating) else np.float64
+        # Allow values up to 20 times the maximum observed value to be safely
+        # transformed without over- or underflow.
+        log1p_max_x = np.log1p(20 * np.max(np.abs(x)))
+        # Use half of floating point's exponent range to allow safe computation
+        # of the variance of the transformed data.
+        log_eps = np.log(np.finfo(dtype).eps)
+        log_tiny_float = (np.log(np.finfo(dtype).tiny) - log_eps) / 2
+        log_max_float = (np.log(np.finfo(dtype).max) + log_eps) / 2
+        # Compute the bounds by approximating the inverse of the Yeo-Johnson
+        # transform on the smallest and largest floating point exponents, given
+        # the largest data we expect to observe. See [1] for further details.
+        # [1] https://github.com/scipy/scipy/pull/18852#issuecomment-1630286174
+        lb = log_tiny_float / log1p_max_x
+        ub = log_max_float / log1p_max_x
+        # Convert the bounds if all or some of the data is negative.
+        if np.all(x < 0):
+            lb, ub = 2 - ub, 2 - lb
+        elif np.any(x < 0):
+            lb, ub = max(2 - ub, lb), min(2 - lb, ub)
+        # Match `optimize.brent`'s tolerance.
+        tol_brent = 1.48e-08
+        return optimize.fminbound(_neg_llf, lb, ub, args=(x,), xtol=tol_brent)
+
+
+def yeojohnson_normplot(x, la, lb, plot=None, N=80):
+    """Compute parameters for a Yeo-Johnson normality plot, optionally show it.
+
+    A Yeo-Johnson normality plot shows graphically what the best
+    transformation parameter is to use in `yeojohnson` to obtain a
+    distribution that is close to normal.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    la, lb : scalar
+        The lower and upper bounds for the ``lmbda`` values to pass to
+        `yeojohnson` for Yeo-Johnson transformations. These are also the
+        limits of the horizontal axis of the plot if that is generated.
+    plot : object, optional
+        If given, plots the quantiles and least squares fit.
+        `plot` is an object that has to have methods "plot" and "text".
+        The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
+        or a custom object with the same methods.
+        Default is None, which means that no plot is created.
+    N : int, optional
+        Number of points on the horizontal axis (equally distributed from
+        `la` to `lb`).
+
+    Returns
+    -------
+    lmbdas : ndarray
+        The ``lmbda`` values for which a Yeo-Johnson transform was done.
+    ppcc : ndarray
+        Probability Plot Correlation Coefficient, as obtained from `probplot`
+        when fitting the Box-Cox transformed input `x` against a normal
+        distribution.
+
+    See Also
+    --------
+    probplot, yeojohnson, yeojohnson_normmax, yeojohnson_llf, ppcc_max
+
+    Notes
+    -----
+    Even if `plot` is given, the figure is not shown or saved by
+    `boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')``
+    should be used after calling `probplot`.
+
+    .. versionadded:: 1.2.0
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    Generate some non-normally distributed data, and create a Yeo-Johnson plot:
+
+    >>> x = stats.loggamma.rvs(5, size=500) + 5
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> prob = stats.yeojohnson_normplot(x, -20, 20, plot=ax)
+
+    Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in
+    the same plot:
+
+    >>> _, maxlog = stats.yeojohnson(x)
+    >>> ax.axvline(maxlog, color='r')
+
+    >>> plt.show()
+
+    """
+    return _normplot('yeojohnson', x, la, lb, plot, N)
+
+
+ShapiroResult = namedtuple('ShapiroResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(ShapiroResult, n_samples=1, too_small=2, default_axis=None)
+def shapiro(x):
+    r"""Perform the Shapiro-Wilk test for normality.
+
+    The Shapiro-Wilk test tests the null hypothesis that the
+    data was drawn from a normal distribution.
+
+    Parameters
+    ----------
+    x : array_like
+        Array of sample data. Must contain at least three observations.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    p-value : float
+        The p-value for the hypothesis test.
+
+    See Also
+    --------
+    anderson : The Anderson-Darling test for normality
+    kstest : The Kolmogorov-Smirnov test for goodness of fit.
+    :ref:`hypothesis_shapiro` : Extended example
+
+    Notes
+    -----
+    The algorithm used is described in [4]_ but censoring parameters as
+    described are not implemented. For N > 5000 the W test statistic is
+    accurate, but the p-value may not be.
+
+    References
+    ----------
+    .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
+           :doi:`10.18434/M32189`
+    .. [2] Shapiro, S. S. & Wilk, M.B, "An analysis of variance test for
+           normality (complete samples)", Biometrika, 1965, Vol. 52,
+           pp. 591-611, :doi:`10.2307/2333709`
+    .. [3] Razali, N. M. & Wah, Y. B., "Power comparisons of Shapiro-Wilk,
+           Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests", Journal
+           of Statistical Modeling and Analytics, 2011, Vol. 2, pp. 21-33.
+    .. [4] Royston P., "Remark AS R94: A Remark on Algorithm AS 181: The
+           W-test for Normality", 1995, Applied Statistics, Vol. 44,
+           :doi:`10.2307/2986146`
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = stats.norm.rvs(loc=5, scale=3, size=100, random_state=rng)
+    >>> shapiro_test = stats.shapiro(x)
+    >>> shapiro_test
+    ShapiroResult(statistic=0.9813305735588074, pvalue=0.16855233907699585)
+    >>> shapiro_test.statistic
+    0.9813305735588074
+    >>> shapiro_test.pvalue
+    0.16855233907699585
+
+    For a more detailed example, see :ref:`hypothesis_shapiro`.
+    """
+    x = np.ravel(x).astype(np.float64)
+
+    N = len(x)
+    if N < 3:
+        raise ValueError("Data must be at least length 3.")
+
+    a = zeros(N//2, dtype=np.float64)
+    init = 0
+
+    y = sort(x)
+    y -= x[N//2]  # subtract the median (or a nearby value); see gh-15777
+
+    w, pw, ifault = swilk(y, a, init)
+    if ifault not in [0, 2]:
+        warnings.warn("scipy.stats.shapiro: Input data has range zero. The"
+                      " results may not be accurate.", stacklevel=2)
+    if N > 5000:
+        warnings.warn("scipy.stats.shapiro: For N > 5000, computed p-value "
+                      f"may not be accurate. Current N is {N}.",
+                      stacklevel=2)
+
+    # `w` and `pw` are always Python floats, which are double precision.
+    # We want to ensure that they are NumPy floats, so until dtypes are
+    # respected, we can explicitly convert each to float64 (faster than
+    # `np.array([w, pw])`).
+    return ShapiroResult(np.float64(w), np.float64(pw))
+
+
+# Values from Stephens, M A, "EDF Statistics for Goodness of Fit and
+#             Some Comparisons", Journal of the American Statistical
+#             Association, Vol. 69, Issue 347, Sept. 1974, pp 730-737
+_Avals_norm = array([0.576, 0.656, 0.787, 0.918, 1.092])
+_Avals_expon = array([0.922, 1.078, 1.341, 1.606, 1.957])
+# From Stephens, M A, "Goodness of Fit for the Extreme Value Distribution",
+#             Biometrika, Vol. 64, Issue 3, Dec. 1977, pp 583-588.
+_Avals_gumbel = array([0.474, 0.637, 0.757, 0.877, 1.038])
+# From Stephens, M A, "Tests of Fit for the Logistic Distribution Based
+#             on the Empirical Distribution Function.", Biometrika,
+#             Vol. 66, Issue 3, Dec. 1979, pp 591-595.
+_Avals_logistic = array([0.426, 0.563, 0.660, 0.769, 0.906, 1.010])
+# From Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of
+#             Fit for the Three-Parameter Weibull Distribution"
+#             Journal of the Royal Statistical Society.Series B(Methodological)
+#             Vol. 56, No. 3 (1994), pp. 491-500, table 1. Keys are c*100
+_Avals_weibull = [[0.292, 0.395, 0.467, 0.522, 0.617, 0.711, 0.836, 0.931],
+                  [0.295, 0.399, 0.471, 0.527, 0.623, 0.719, 0.845, 0.941],
+                  [0.298, 0.403, 0.476, 0.534, 0.631, 0.728, 0.856, 0.954],
+                  [0.301, 0.408, 0.483, 0.541, 0.640, 0.738, 0.869, 0.969],
+                  [0.305, 0.414, 0.490, 0.549, 0.650, 0.751, 0.885, 0.986],
+                  [0.309, 0.421, 0.498, 0.559, 0.662, 0.765, 0.902, 1.007],
+                  [0.314, 0.429, 0.508, 0.570, 0.676, 0.782, 0.923, 1.030],
+                  [0.320, 0.438, 0.519, 0.583, 0.692, 0.802, 0.947, 1.057],
+                  [0.327, 0.448, 0.532, 0.598, 0.711, 0.824, 0.974, 1.089],
+                  [0.334, 0.469, 0.547, 0.615, 0.732, 0.850, 1.006, 1.125],
+                  [0.342, 0.472, 0.563, 0.636, 0.757, 0.879, 1.043, 1.167]]
+_Avals_weibull = np.array(_Avals_weibull)
+_cvals_weibull = np.linspace(0, 0.5, 11)
+_get_As_weibull = interpolate.interp1d(_cvals_weibull, _Avals_weibull.T,
+                                       kind='linear', bounds_error=False,
+                                       fill_value=_Avals_weibull[-1])
+
+
+def _weibull_fit_check(params, x):
+    # Refine the fit returned by `weibull_min.fit` to ensure that the first
+    # order necessary conditions are satisfied. If not, raise an error.
+    # Here, use `m` for the shape parameter to be consistent with [7]
+    # and avoid confusion with `c` as defined in [7].
+    n = len(x)
+    m, u, s = params
+
+    def dnllf_dm(m, u):
+        # Partial w.r.t. shape w/ optimal scale. See [7] Equation 5.
+        xu = x-u
+        return (1/m - (xu**m*np.log(xu)).sum()/(xu**m).sum()
+                + np.log(xu).sum()/n)
+
+    def dnllf_du(m, u):
+        # Partial w.r.t. loc w/ optimal scale. See [7] Equation 6.
+        xu = x-u
+        return (m-1)/m*(xu**-1).sum() - n*(xu**(m-1)).sum()/(xu**m).sum()
+
+    def get_scale(m, u):
+        # Partial w.r.t. scale solved in terms of shape and location.
+        # See [7] Equation 7.
+        return ((x-u)**m/n).sum()**(1/m)
+
+    def dnllf(params):
+        # Partial derivatives of the NLLF w.r.t. parameters, i.e.
+        # first order necessary conditions for MLE fit.
+        return [dnllf_dm(*params), dnllf_du(*params)]
+
+    suggestion = ("Maximum likelihood estimation is known to be challenging "
+                  "for the three-parameter Weibull distribution. Consider "
+                  "performing a custom goodness-of-fit test using "
+                  "`scipy.stats.monte_carlo_test`.")
+
+    if np.allclose(u, np.min(x)) or m < 1:
+        # The critical values provided by [7] don't seem to control the
+        # Type I error rate in this case. Error out.
+        message = ("Maximum likelihood estimation has converged to "
+                   "a solution in which the location is equal to the minimum "
+                   "of the data, the shape parameter is less than 2, or both. "
+                   "The table of critical values in [7] does not "
+                   "include this case. " + suggestion)
+        raise ValueError(message)
+
+    try:
+        # Refine the MLE / verify that first-order necessary conditions are
+        # satisfied. If so, the critical values provided in [7] seem reliable.
+        with np.errstate(over='raise', invalid='raise'):
+            res = optimize.root(dnllf, params[:-1])
+
+        message = ("Solution of MLE first-order conditions failed: "
+                   f"{res.message}. `anderson` cannot continue. " + suggestion)
+        if not res.success:
+            raise ValueError(message)
+
+    except (FloatingPointError, ValueError) as e:
+        message = ("An error occurred while fitting the Weibull distribution "
+                   "to the data, so `anderson` cannot continue. " + suggestion)
+        raise ValueError(message) from e
+
+    m, u = res.x
+    s = get_scale(m, u)
+    return m, u, s
+
+
+AndersonResult = _make_tuple_bunch('AndersonResult',
+                                   ['statistic', 'critical_values',
+                                    'significance_level'], ['fit_result'])
+
+
+def anderson(x, dist='norm'):
+    """Anderson-Darling test for data coming from a particular distribution.
+
+    The Anderson-Darling test tests the null hypothesis that a sample is
+    drawn from a population that follows a particular distribution.
+    For the Anderson-Darling test, the critical values depend on
+    which distribution is being tested against.  This function works
+    for normal, exponential, logistic, weibull_min, or Gumbel (Extreme Value
+    Type I) distributions.
+
+    Parameters
+    ----------
+    x : array_like
+        Array of sample data.
+    dist : {'norm', 'expon', 'logistic', 'gumbel', 'gumbel_l', 'gumbel_r', 'extreme1', 'weibull_min'}, optional
+        The type of distribution to test against.  The default is 'norm'.
+        The names 'extreme1', 'gumbel_l' and 'gumbel' are synonyms for the
+        same distribution.
+
+    Returns
+    -------
+    result : AndersonResult
+        An object with the following attributes:
+
+        statistic : float
+            The Anderson-Darling test statistic.
+        critical_values : list
+            The critical values for this distribution.
+        significance_level : list
+            The significance levels for the corresponding critical values
+            in percents.  The function returns critical values for a
+            differing set of significance levels depending on the
+            distribution that is being tested against.
+        fit_result : `~scipy.stats._result_classes.FitResult`
+            An object containing the results of fitting the distribution to
+            the data.
+
+    See Also
+    --------
+    kstest : The Kolmogorov-Smirnov test for goodness-of-fit.
+
+    Notes
+    -----
+    Critical values provided are for the following significance levels:
+
+    normal/exponential
+        15%, 10%, 5%, 2.5%, 1%
+    logistic
+        25%, 10%, 5%, 2.5%, 1%, 0.5%
+    gumbel_l / gumbel_r
+        25%, 10%, 5%, 2.5%, 1%
+    weibull_min
+        50%, 25%, 15%, 10%, 5%, 2.5%, 1%, 0.5%
+
+    If the returned statistic is larger than these critical values then
+    for the corresponding significance level, the null hypothesis that
+    the data come from the chosen distribution can be rejected.
+    The returned statistic is referred to as 'A2' in the references.
+
+    For `weibull_min`, maximum likelihood estimation is known to be
+    challenging. If the test returns successfully, then the first order
+    conditions for a maximum likelihood estimate have been verified and
+    the critical values correspond relatively well to the significance levels,
+    provided that the sample is sufficiently large (>10 observations [7]).
+    However, for some data - especially data with no left tail - `anderson`
+    is likely to result in an error message. In this case, consider
+    performing a custom goodness of fit test using
+    `scipy.stats.monte_carlo_test`.
+
+    References
+    ----------
+    .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
+    .. [2] Stephens, M. A. (1974). EDF Statistics for Goodness of Fit and
+           Some Comparisons, Journal of the American Statistical Association,
+           Vol. 69, pp. 730-737.
+    .. [3] Stephens, M. A. (1976). Asymptotic Results for Goodness-of-Fit
+           Statistics with Unknown Parameters, Annals of Statistics, Vol. 4,
+           pp. 357-369.
+    .. [4] Stephens, M. A. (1977). Goodness of Fit for the Extreme Value
+           Distribution, Biometrika, Vol. 64, pp. 583-588.
+    .. [5] Stephens, M. A. (1977). Goodness of Fit with Special Reference
+           to Tests for Exponentiality , Technical Report No. 262,
+           Department of Statistics, Stanford University, Stanford, CA.
+    .. [6] Stephens, M. A. (1979). Tests of Fit for the Logistic Distribution
+           Based on the Empirical Distribution Function, Biometrika, Vol. 66,
+           pp. 591-595.
+    .. [7] Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of
+           Fit for the Three-Parameter Weibull Distribution"
+           Journal of the Royal Statistical Society.Series B(Methodological)
+           Vol. 56, No. 3 (1994), pp. 491-500, Table 0.
+
+    Examples
+    --------
+    Test the null hypothesis that a random sample was drawn from a normal
+    distribution (with unspecified mean and standard deviation).
+
+    >>> import numpy as np
+    >>> from scipy.stats import anderson
+    >>> rng = np.random.default_rng()
+    >>> data = rng.random(size=35)
+    >>> res = anderson(data)
+    >>> res.statistic
+    0.8398018749744764
+    >>> res.critical_values
+    array([0.527, 0.6  , 0.719, 0.839, 0.998])
+    >>> res.significance_level
+    array([15. , 10. ,  5. ,  2.5,  1. ])
+
+    The value of the statistic (barely) exceeds the critical value associated
+    with a significance level of 2.5%, so the null hypothesis may be rejected
+    at a significance level of 2.5%, but not at a significance level of 1%.
+
+    """ # numpy/numpydoc#87  # noqa: E501
+    dist = dist.lower()
+    if dist in {'extreme1', 'gumbel'}:
+        dist = 'gumbel_l'
+    dists = {'norm', 'expon', 'gumbel_l',
+             'gumbel_r', 'logistic', 'weibull_min'}
+
+    if dist not in dists:
+        raise ValueError(f"Invalid distribution; dist must be in {dists}.")
+    y = sort(x)
+    xbar = np.mean(x, axis=0)
+    N = len(y)
+    if dist == 'norm':
+        s = np.std(x, ddof=1, axis=0)
+        w = (y - xbar) / s
+        fit_params = xbar, s
+        logcdf = distributions.norm.logcdf(w)
+        logsf = distributions.norm.logsf(w)
+        sig = array([15, 10, 5, 2.5, 1])
+        critical = around(_Avals_norm / (1.0 + 4.0/N - 25.0/N/N), 3)
+    elif dist == 'expon':
+        w = y / xbar
+        fit_params = 0, xbar
+        logcdf = distributions.expon.logcdf(w)
+        logsf = distributions.expon.logsf(w)
+        sig = array([15, 10, 5, 2.5, 1])
+        critical = around(_Avals_expon / (1.0 + 0.6/N), 3)
+    elif dist == 'logistic':
+        def rootfunc(ab, xj, N):
+            a, b = ab
+            tmp = (xj - a) / b
+            tmp2 = exp(tmp)
+            val = [np.sum(1.0/(1+tmp2), axis=0) - 0.5*N,
+                   np.sum(tmp*(1.0-tmp2)/(1+tmp2), axis=0) + N]
+            return array(val)
+
+        sol0 = array([xbar, np.std(x, ddof=1, axis=0)])
+        sol = optimize.fsolve(rootfunc, sol0, args=(x, N), xtol=1e-5)
+        w = (y - sol[0]) / sol[1]
+        fit_params = sol
+        logcdf = distributions.logistic.logcdf(w)
+        logsf = distributions.logistic.logsf(w)
+        sig = array([25, 10, 5, 2.5, 1, 0.5])
+        critical = around(_Avals_logistic / (1.0 + 0.25/N), 3)
+    elif dist == 'gumbel_r':
+        xbar, s = distributions.gumbel_r.fit(x)
+        w = (y - xbar) / s
+        fit_params = xbar, s
+        logcdf = distributions.gumbel_r.logcdf(w)
+        logsf = distributions.gumbel_r.logsf(w)
+        sig = array([25, 10, 5, 2.5, 1])
+        critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3)
+    elif dist == 'gumbel_l':
+        xbar, s = distributions.gumbel_l.fit(x)
+        w = (y - xbar) / s
+        fit_params = xbar, s
+        logcdf = distributions.gumbel_l.logcdf(w)
+        logsf = distributions.gumbel_l.logsf(w)
+        sig = array([25, 10, 5, 2.5, 1])
+        critical = around(_Avals_gumbel / (1.0 + 0.2/sqrt(N)), 3)
+    elif dist == 'weibull_min':
+        message = ("Critical values of the test statistic are given for the "
+                   "asymptotic distribution. These may not be accurate for "
+                   "samples with fewer than 10 observations. Consider using "
+                   "`scipy.stats.monte_carlo_test`.")
+        if N < 10:
+            warnings.warn(message, stacklevel=2)
+        # [7] writes our 'c' as 'm', and they write `c = 1/m`. Use their names.
+        m, loc, scale = distributions.weibull_min.fit(y)
+        m, loc, scale = _weibull_fit_check((m, loc, scale), y)
+        fit_params = m, loc, scale
+        logcdf = stats.weibull_min(*fit_params).logcdf(y)
+        logsf = stats.weibull_min(*fit_params).logsf(y)
+        c = 1 / m  # m and c are as used in [7]
+        sig = array([0.5, 0.75, 0.85, 0.9, 0.95, 0.975, 0.99, 0.995])
+        critical = _get_As_weibull(c)
+        # Goodness-of-fit tests should only be used to provide evidence
+        # _against_ the null hypothesis. Be conservative and round up.
+        critical = np.round(critical + 0.0005, decimals=3)
+
+    i = arange(1, N + 1)
+    A2 = -N - np.sum((2*i - 1.0) / N * (logcdf + logsf[::-1]), axis=0)
+
+    # FitResult initializer expects an optimize result, so let's work with it
+    message = '`anderson` successfully fit the distribution to the data.'
+    res = optimize.OptimizeResult(success=True, message=message)
+    res.x = np.array(fit_params)
+    fit_result = FitResult(getattr(distributions, dist), y,
+                           discrete=False, res=res)
+
+    return AndersonResult(A2, critical, sig, fit_result=fit_result)
+
+
+def _anderson_ksamp_midrank(samples, Z, Zstar, k, n, N):
+    """Compute A2akN equation 7 of Scholz and Stephens.
+
+    Parameters
+    ----------
+    samples : sequence of 1-D array_like
+        Array of sample arrays.
+    Z : array_like
+        Sorted array of all observations.
+    Zstar : array_like
+        Sorted array of unique observations.
+    k : int
+        Number of samples.
+    n : array_like
+        Number of observations in each sample.
+    N : int
+        Total number of observations.
+
+    Returns
+    -------
+    A2aKN : float
+        The A2aKN statistics of Scholz and Stephens 1987.
+
+    """
+    A2akN = 0.
+    Z_ssorted_left = Z.searchsorted(Zstar, 'left')
+    if N == Zstar.size:
+        lj = 1.
+    else:
+        lj = Z.searchsorted(Zstar, 'right') - Z_ssorted_left
+    Bj = Z_ssorted_left + lj / 2.
+    for i in arange(0, k):
+        s = np.sort(samples[i])
+        s_ssorted_right = s.searchsorted(Zstar, side='right')
+        Mij = s_ssorted_right.astype(float)
+        fij = s_ssorted_right - s.searchsorted(Zstar, 'left')
+        Mij -= fij / 2.
+        inner = lj / float(N) * (N*Mij - Bj*n[i])**2 / (Bj*(N - Bj) - N*lj/4.)
+        A2akN += inner.sum() / n[i]
+    A2akN *= (N - 1.) / N
+    return A2akN
+
+
+def _anderson_ksamp_right(samples, Z, Zstar, k, n, N):
+    """Compute A2akN equation 6 of Scholz & Stephens.
+
+    Parameters
+    ----------
+    samples : sequence of 1-D array_like
+        Array of sample arrays.
+    Z : array_like
+        Sorted array of all observations.
+    Zstar : array_like
+        Sorted array of unique observations.
+    k : int
+        Number of samples.
+    n : array_like
+        Number of observations in each sample.
+    N : int
+        Total number of observations.
+
+    Returns
+    -------
+    A2KN : float
+        The A2KN statistics of Scholz and Stephens 1987.
+
+    """
+    A2kN = 0.
+    lj = Z.searchsorted(Zstar[:-1], 'right') - Z.searchsorted(Zstar[:-1],
+                                                              'left')
+    Bj = lj.cumsum()
+    for i in arange(0, k):
+        s = np.sort(samples[i])
+        Mij = s.searchsorted(Zstar[:-1], side='right')
+        inner = lj / float(N) * (N * Mij - Bj * n[i])**2 / (Bj * (N - Bj))
+        A2kN += inner.sum() / n[i]
+    return A2kN
+
+
+Anderson_ksampResult = _make_tuple_bunch(
+    'Anderson_ksampResult',
+    ['statistic', 'critical_values', 'pvalue'], []
+)
+
+
+def anderson_ksamp(samples, midrank=True, *, method=None):
+    """The Anderson-Darling test for k-samples.
+
+    The k-sample Anderson-Darling test is a modification of the
+    one-sample Anderson-Darling test. It tests the null hypothesis
+    that k-samples are drawn from the same population without having
+    to specify the distribution function of that population. The
+    critical values depend on the number of samples.
+
+    Parameters
+    ----------
+    samples : sequence of 1-D array_like
+        Array of sample data in arrays.
+    midrank : bool, optional
+        Type of Anderson-Darling test which is computed. Default
+        (True) is the midrank test applicable to continuous and
+        discrete populations. If False, the right side empirical
+        distribution is used.
+    method : PermutationMethod, optional
+        Defines the method used to compute the p-value. If `method` is an
+        instance of `PermutationMethod`, the p-value is computed using
+        `scipy.stats.permutation_test` with the provided configuration options
+        and other appropriate settings. Otherwise, the p-value is interpolated
+        from tabulated values.
+
+    Returns
+    -------
+    res : Anderson_ksampResult
+        An object containing attributes:
+
+        statistic : float
+            Normalized k-sample Anderson-Darling test statistic.
+        critical_values : array
+            The critical values for significance levels 25%, 10%, 5%, 2.5%, 1%,
+            0.5%, 0.1%.
+        pvalue : float
+            The approximate p-value of the test. If `method` is not
+            provided, the value is floored / capped at 0.1% / 25%.
+
+    Raises
+    ------
+    ValueError
+        If fewer than 2 samples are provided, a sample is empty, or no
+        distinct observations are in the samples.
+
+    See Also
+    --------
+    ks_2samp : 2 sample Kolmogorov-Smirnov test
+    anderson : 1 sample Anderson-Darling test
+
+    Notes
+    -----
+    [1]_ defines three versions of the k-sample Anderson-Darling test:
+    one for continuous distributions and two for discrete
+    distributions, in which ties between samples may occur. The
+    default of this routine is to compute the version based on the
+    midrank empirical distribution function. This test is applicable
+    to continuous and discrete data. If midrank is set to False, the
+    right side empirical distribution is used for a test for discrete
+    data. According to [1]_, the two discrete test statistics differ
+    only slightly if a few collisions due to round-off errors occur in
+    the test not adjusted for ties between samples.
+
+    The critical values corresponding to the significance levels from 0.01
+    to 0.25 are taken from [1]_. p-values are floored / capped
+    at 0.1% / 25%. Since the range of critical values might be extended in
+    future releases, it is recommended not to test ``p == 0.25``, but rather
+    ``p >= 0.25`` (analogously for the lower bound).
+
+    .. versionadded:: 0.14.0
+
+    References
+    ----------
+    .. [1] Scholz, F. W and Stephens, M. A. (1987), K-Sample
+           Anderson-Darling Tests, Journal of the American Statistical
+           Association, Vol. 82, pp. 918-924.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> res = stats.anderson_ksamp([rng.normal(size=50),
+    ... rng.normal(loc=0.5, size=30)])
+    >>> res.statistic, res.pvalue
+    (1.974403288713695, 0.04991293614572478)
+    >>> res.critical_values
+    array([0.325, 1.226, 1.961, 2.718, 3.752, 4.592, 6.546])
+
+    The null hypothesis that the two random samples come from the same
+    distribution can be rejected at the 5% level because the returned
+    test value is greater than the critical value for 5% (1.961) but
+    not at the 2.5% level. The interpolation gives an approximate
+    p-value of 4.99%.
+
+    >>> samples = [rng.normal(size=50), rng.normal(size=30),
+    ...            rng.normal(size=20)]
+    >>> res = stats.anderson_ksamp(samples)
+    >>> res.statistic, res.pvalue
+    (-0.29103725200789504, 0.25)
+    >>> res.critical_values
+    array([ 0.44925884,  1.3052767 ,  1.9434184 ,  2.57696569,  3.41634856,
+      4.07210043, 5.56419101])
+
+    The null hypothesis cannot be rejected for three samples from an
+    identical distribution. The reported p-value (25%) has been capped and
+    may not be very accurate (since it corresponds to the value 0.449
+    whereas the statistic is -0.291).
+
+    In such cases where the p-value is capped or when sample sizes are
+    small, a permutation test may be more accurate.
+
+    >>> method = stats.PermutationMethod(n_resamples=9999, random_state=rng)
+    >>> res = stats.anderson_ksamp(samples, method=method)
+    >>> res.pvalue
+    0.5254
+
+    """
+    k = len(samples)
+    if (k < 2):
+        raise ValueError("anderson_ksamp needs at least two samples")
+
+    samples = list(map(np.asarray, samples))
+    Z = np.sort(np.hstack(samples))
+    N = Z.size
+    Zstar = np.unique(Z)
+    if Zstar.size < 2:
+        raise ValueError("anderson_ksamp needs more than one distinct "
+                         "observation")
+
+    n = np.array([sample.size for sample in samples])
+    if np.any(n == 0):
+        raise ValueError("anderson_ksamp encountered sample without "
+                         "observations")
+
+    if midrank:
+        A2kN_fun = _anderson_ksamp_midrank
+    else:
+        A2kN_fun = _anderson_ksamp_right
+    A2kN = A2kN_fun(samples, Z, Zstar, k, n, N)
+
+    def statistic(*samples):
+        return A2kN_fun(samples, Z, Zstar, k, n, N)
+
+    if method is not None:
+        res = stats.permutation_test(samples, statistic, **method._asdict(),
+                                     alternative='greater')
+
+    H = (1. / n).sum()
+    hs_cs = (1. / arange(N - 1, 1, -1)).cumsum()
+    h = hs_cs[-1] + 1
+    g = (hs_cs / arange(2, N)).sum()
+
+    a = (4*g - 6) * (k - 1) + (10 - 6*g)*H
+    b = (2*g - 4)*k**2 + 8*h*k + (2*g - 14*h - 4)*H - 8*h + 4*g - 6
+    c = (6*h + 2*g - 2)*k**2 + (4*h - 4*g + 6)*k + (2*h - 6)*H + 4*h
+    d = (2*h + 6)*k**2 - 4*h*k
+    sigmasq = (a*N**3 + b*N**2 + c*N + d) / ((N - 1.) * (N - 2.) * (N - 3.))
+    m = k - 1
+    A2 = (A2kN - m) / math.sqrt(sigmasq)
+
+    # The b_i values are the interpolation coefficients from Table 2
+    # of Scholz and Stephens 1987
+    b0 = np.array([0.675, 1.281, 1.645, 1.96, 2.326, 2.573, 3.085])
+    b1 = np.array([-0.245, 0.25, 0.678, 1.149, 1.822, 2.364, 3.615])
+    b2 = np.array([-0.105, -0.305, -0.362, -0.391, -0.396, -0.345, -0.154])
+    critical = b0 + b1 / math.sqrt(m) + b2 / m
+
+    sig = np.array([0.25, 0.1, 0.05, 0.025, 0.01, 0.005, 0.001])
+
+    if A2 < critical.min() and method is None:
+        p = sig.max()
+        msg = (f"p-value capped: true value larger than {p}. Consider "
+               "specifying `method` "
+               "(e.g. `method=stats.PermutationMethod()`.)")
+        warnings.warn(msg, stacklevel=2)
+    elif A2 > critical.max() and method is None:
+        p = sig.min()
+        msg = (f"p-value floored: true value smaller than {p}. Consider "
+               "specifying `method` "
+               "(e.g. `method=stats.PermutationMethod()`.)")
+        warnings.warn(msg, stacklevel=2)
+    elif method is None:
+        # interpolation of probit of significance level
+        pf = np.polyfit(critical, log(sig), 2)
+        p = math.exp(np.polyval(pf, A2))
+    else:
+        p = res.pvalue if method is not None else p
+
+    # create result object with alias for backward compatibility
+    res = Anderson_ksampResult(A2, critical, p)
+    res.significance_level = p
+    return res
+
+
+AnsariResult = namedtuple('AnsariResult', ('statistic', 'pvalue'))
+
+
+class _ABW:
+    """Distribution of Ansari-Bradley W-statistic under the null hypothesis."""
+    # TODO: calculate exact distribution considering ties
+    # We could avoid summing over more than half the frequencies,
+    # but initially it doesn't seem worth the extra complexity
+
+    def __init__(self):
+        """Minimal initializer."""
+        self.m = None
+        self.n = None
+        self.astart = None
+        self.total = None
+        self.freqs = None
+
+    def _recalc(self, n, m):
+        """When necessary, recalculate exact distribution."""
+        if n != self.n or m != self.m:
+            self.n, self.m = n, m
+            # distribution is NOT symmetric when m + n is odd
+            # n is len(x), m is len(y), and ratio of scales is defined x/y
+            astart, a1, _ = gscale(n, m)
+            self.astart = astart  # minimum value of statistic
+            # Exact distribution of test statistic under null hypothesis
+            # expressed as frequencies/counts/integers to maintain precision.
+            # Stored as floats to avoid overflow of sums.
+            self.freqs = a1.astype(np.float64)
+            self.total = self.freqs.sum()  # could calculate from m and n
+            # probability mass is self.freqs / self.total;
+
+    def pmf(self, k, n, m):
+        """Probability mass function."""
+        self._recalc(n, m)
+        # The convention here is that PMF at k = 12.5 is the same as at k = 12,
+        # -> use `floor` in case of ties.
+        ind = np.floor(k - self.astart).astype(int)
+        return self.freqs[ind] / self.total
+
+    def cdf(self, k, n, m):
+        """Cumulative distribution function."""
+        self._recalc(n, m)
+        # Null distribution derived without considering ties is
+        # approximate. Round down to avoid Type I error.
+        ind = np.ceil(k - self.astart).astype(int)
+        return self.freqs[:ind+1].sum() / self.total
+
+    def sf(self, k, n, m):
+        """Survival function."""
+        self._recalc(n, m)
+        # Null distribution derived without considering ties is
+        # approximate. Round down to avoid Type I error.
+        ind = np.floor(k - self.astart).astype(int)
+        return self.freqs[ind:].sum() / self.total
+
+
+# Maintain state for faster repeat calls to ansari w/ method='exact'
+# _ABW() is calculated once per thread and stored as an attribute on
+# this thread-local variable inside ansari().
+_abw_state = threading.local()
+
+
+@_axis_nan_policy_factory(AnsariResult, n_samples=2)
+def ansari(x, y, alternative='two-sided'):
+    """Perform the Ansari-Bradley test for equal scale parameters.
+
+    The Ansari-Bradley test ([1]_, [2]_) is a non-parametric test
+    for the equality of the scale parameter of the distributions
+    from which two samples were drawn. The null hypothesis states that
+    the ratio of the scale of the distribution underlying `x` to the scale
+    of the distribution underlying `y` is 1.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Arrays of sample data.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the ratio of scales is not equal to 1.
+        * 'less': the ratio of scales is less than 1.
+        * 'greater': the ratio of scales is greater than 1.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float
+        The Ansari-Bradley test statistic.
+    pvalue : float
+        The p-value of the hypothesis test.
+
+    See Also
+    --------
+    fligner : A non-parametric test for the equality of k variances
+    mood : A non-parametric test for the equality of two scale parameters
+
+    Notes
+    -----
+    The p-value given is exact when the sample sizes are both less than
+    55 and there are no ties, otherwise a normal approximation for the
+    p-value is used.
+
+    References
+    ----------
+    .. [1] Ansari, A. R. and Bradley, R. A. (1960) Rank-sum tests for
+           dispersions, Annals of Mathematical Statistics, 31, 1174-1189.
+    .. [2] Sprent, Peter and N.C. Smeeton.  Applied nonparametric
+           statistical methods.  3rd ed. Chapman and Hall/CRC. 2001.
+           Section 5.8.2.
+    .. [3] Nathaniel E. Helwig "Nonparametric Dispersion and Equality
+           Tests" at http://users.stat.umn.edu/~helwig/notes/npde-Notes.pdf
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import ansari
+    >>> rng = np.random.default_rng()
+
+    For these examples, we'll create three random data sets.  The first
+    two, with sizes 35 and 25, are drawn from a normal distribution with
+    mean 0 and standard deviation 2.  The third data set has size 25 and
+    is drawn from a normal distribution with standard deviation 1.25.
+
+    >>> x1 = rng.normal(loc=0, scale=2, size=35)
+    >>> x2 = rng.normal(loc=0, scale=2, size=25)
+    >>> x3 = rng.normal(loc=0, scale=1.25, size=25)
+
+    First we apply `ansari` to `x1` and `x2`.  These samples are drawn
+    from the same distribution, so we expect the Ansari-Bradley test
+    should not lead us to conclude that the scales of the distributions
+    are different.
+
+    >>> ansari(x1, x2)
+    AnsariResult(statistic=541.0, pvalue=0.9762532927399098)
+
+    With a p-value close to 1, we cannot conclude that there is a
+    significant difference in the scales (as expected).
+
+    Now apply the test to `x1` and `x3`:
+
+    >>> ansari(x1, x3)
+    AnsariResult(statistic=425.0, pvalue=0.0003087020407974518)
+
+    The probability of observing such an extreme value of the statistic
+    under the null hypothesis of equal scales is only 0.03087%. We take this
+    as evidence against the null hypothesis in favor of the alternative:
+    the scales of the distributions from which the samples were drawn
+    are not equal.
+
+    We can use the `alternative` parameter to perform a one-tailed test.
+    In the above example, the scale of `x1` is greater than `x3` and so
+    the ratio of scales of `x1` and `x3` is greater than 1. This means
+    that the p-value when ``alternative='greater'`` should be near 0 and
+    hence we should be able to reject the null hypothesis:
+
+    >>> ansari(x1, x3, alternative='greater')
+    AnsariResult(statistic=425.0, pvalue=0.0001543510203987259)
+
+    As we can see, the p-value is indeed quite low. Use of
+    ``alternative='less'`` should thus yield a large p-value:
+
+    >>> ansari(x1, x3, alternative='less')
+    AnsariResult(statistic=425.0, pvalue=0.9998643258449039)
+
+    """
+    if alternative not in {'two-sided', 'greater', 'less'}:
+        raise ValueError("'alternative' must be 'two-sided',"
+                         " 'greater', or 'less'.")
+
+    if not hasattr(_abw_state, 'a'):
+        _abw_state.a = _ABW()
+
+    x, y = asarray(x), asarray(y)
+    n = len(x)
+    m = len(y)
+    if m < 1:
+        raise ValueError("Not enough other observations.")
+    if n < 1:
+        raise ValueError("Not enough test observations.")
+
+    N = m + n
+    xy = r_[x, y]  # combine
+    rank = _stats_py.rankdata(xy)
+    symrank = amin(array((rank, N - rank + 1)), 0)
+    AB = np.sum(symrank[:n], axis=0)
+    uxy = unique(xy)
+    repeats = (len(uxy) != len(xy))
+    exact = ((m < 55) and (n < 55) and not repeats)
+    if repeats and (m < 55 or n < 55):
+        warnings.warn("Ties preclude use of exact statistic.", stacklevel=2)
+    if exact:
+        if alternative == 'two-sided':
+            pval = 2.0 * np.minimum(_abw_state.a.cdf(AB, n, m),
+                                    _abw_state.a.sf(AB, n, m))
+        elif alternative == 'greater':
+            # AB statistic is _smaller_ when ratio of scales is larger,
+            # so this is the opposite of the usual calculation
+            pval = _abw_state.a.cdf(AB, n, m)
+        else:
+            pval = _abw_state.a.sf(AB, n, m)
+        return AnsariResult(AB, min(1.0, pval))
+
+    # otherwise compute normal approximation
+    if N % 2:  # N odd
+        mnAB = n * (N+1.0)**2 / 4.0 / N
+        varAB = n * m * (N+1.0) * (3+N**2) / (48.0 * N**2)
+    else:
+        mnAB = n * (N+2.0) / 4.0
+        varAB = m * n * (N+2) * (N-2.0) / 48 / (N-1.0)
+    if repeats:   # adjust variance estimates
+        # compute np.sum(tj * rj**2,axis=0)
+        fac = np.sum(symrank**2, axis=0)
+        if N % 2:  # N odd
+            varAB = m * n * (16*N*fac - (N+1)**4) / (16.0 * N**2 * (N-1))
+        else:  # N even
+            varAB = m * n * (16*fac - N*(N+2)**2) / (16.0 * N * (N-1))
+
+    # Small values of AB indicate larger dispersion for the x sample.
+    # Large values of AB indicate larger dispersion for the y sample.
+    # This is opposite to the way we define the ratio of scales. see [1]_.
+    z = (mnAB - AB) / sqrt(varAB)
+    pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+    return AnsariResult(AB[()], pvalue[()])
+
+
+BartlettResult = namedtuple('BartlettResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(BartlettResult, n_samples=None)
+def bartlett(*samples, axis=0):
+    r"""Perform Bartlett's test for equal variances.
+
+    Bartlett's test tests the null hypothesis that all input samples
+    are from populations with equal variances.  For samples
+    from significantly non-normal populations, Levene's test
+    `levene` is more robust.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        arrays of sample data.  Only 1d arrays are accepted, they may have
+        different lengths.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    pvalue : float
+        The p-value of the test.
+
+    See Also
+    --------
+    fligner : A non-parametric test for the equality of k variances
+    levene : A robust parametric test for equality of k variances
+    :ref:`hypothesis_bartlett` : Extended example
+
+    Notes
+    -----
+    Conover et al. (1981) examine many of the existing parametric and
+    nonparametric tests by extensive simulations and they conclude that the
+    tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
+    superior in terms of robustness of departures from normality and power
+    ([3]_).
+
+    References
+    ----------
+    .. [1]  https://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm
+    .. [2]  Snedecor, George W. and Cochran, William G. (1989), Statistical
+              Methods, Eighth Edition, Iowa State University Press.
+    .. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
+           Hypothesis Testing based on Quadratic Inference Function. Technical
+           Report #99-03, Center for Likelihood Studies, Pennsylvania State
+           University.
+    .. [4] Bartlett, M. S. (1937). Properties of Sufficiency and Statistical
+           Tests. Proceedings of the Royal Society of London. Series A,
+           Mathematical and Physical Sciences, Vol. 160, No.901, pp. 268-282.
+
+    Examples
+    --------
+
+    Test whether the lists `a`, `b` and `c` come from populations
+    with equal variances.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
+    >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
+    >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
+    >>> stat, p = stats.bartlett(a, b, c)
+    >>> p
+    1.1254782518834628e-05
+
+    The very small p-value suggests that the populations do not have equal
+    variances.
+
+    This is not surprising, given that the sample variance of `b` is much
+    larger than that of `a` and `c`:
+
+    >>> [np.var(x, ddof=1) for x in [a, b, c]]
+    [0.007054444444444413, 0.13073888888888888, 0.008890000000000002]
+
+    For a more detailed example, see :ref:`hypothesis_bartlett`.
+    """
+    xp = array_namespace(*samples)
+
+    k = len(samples)
+    if k < 2:
+        raise ValueError("Must enter at least two input sample vectors.")
+
+    samples = _broadcast_arrays(samples, axis=axis, xp=xp)
+    samples = [xp_moveaxis_to_end(sample, axis, xp=xp) for sample in samples]
+
+    Ni = [xp.asarray(sample.shape[-1], dtype=sample.dtype) for sample in samples]
+    Ni = [xp.broadcast_to(N, samples[0].shape[:-1]) for N in Ni]
+    ssq = [xp.var(sample, correction=1, axis=-1) for sample in samples]
+    Ni = [arr[xp.newaxis, ...] for arr in Ni]
+    ssq = [arr[xp.newaxis, ...] for arr in ssq]
+    Ni = xp.concat(Ni, axis=0)
+    ssq = xp.concat(ssq, axis=0)
+    # sum dtype can be removed when 2023.12 rules kick in
+    dtype = Ni.dtype
+    Ntot = xp.sum(Ni, axis=0, dtype=dtype)
+    spsq = xp.sum((Ni - 1)*ssq, axis=0, dtype=dtype) / (Ntot - k)
+    numer = ((Ntot - k) * xp.log(spsq)
+             - xp.sum((Ni - 1)*xp.log(ssq), axis=0, dtype=dtype))
+    denom = (1 + 1/(3*(k - 1))
+             * ((xp.sum(1/(Ni - 1), axis=0, dtype=dtype)) - 1/(Ntot - k)))
+    T = numer / denom
+
+    chi2 = _SimpleChi2(xp.asarray(k-1))
+    pvalue = _get_pvalue(T, chi2, alternative='greater', symmetric=False, xp=xp)
+
+    T = xp.clip(T, min=0., max=xp.inf)
+    T = T[()] if T.ndim == 0 else T
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+
+    return BartlettResult(T, pvalue)
+
+
+LeveneResult = namedtuple('LeveneResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(LeveneResult, n_samples=None)
+def levene(*samples, center='median', proportiontocut=0.05):
+    r"""Perform Levene test for equal variances.
+
+    The Levene test tests the null hypothesis that all input samples
+    are from populations with equal variances.  Levene's test is an
+    alternative to Bartlett's test `bartlett` in the case where
+    there are significant deviations from normality.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The sample data, possibly with different lengths. Only one-dimensional
+        samples are accepted.
+    center : {'mean', 'median', 'trimmed'}, optional
+        Which function of the data to use in the test.  The default
+        is 'median'.
+    proportiontocut : float, optional
+        When `center` is 'trimmed', this gives the proportion of data points
+        to cut from each end. (See `scipy.stats.trim_mean`.)
+        Default is 0.05.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    pvalue : float
+        The p-value for the test.
+
+    See Also
+    --------
+    fligner : A non-parametric test for the equality of k variances
+    bartlett : A parametric test for equality of k variances in normal samples
+    :ref:`hypothesis_levene` : Extended example
+
+    Notes
+    -----
+    Three variations of Levene's test are possible.  The possibilities
+    and their recommended usages are:
+
+    * 'median' : Recommended for skewed (non-normal) distributions>
+    * 'mean' : Recommended for symmetric, moderate-tailed distributions.
+    * 'trimmed' : Recommended for heavy-tailed distributions.
+
+    The test version using the mean was proposed in the original article
+    of Levene ([2]_) while the median and trimmed mean have been studied by
+    Brown and Forsythe ([3]_), sometimes also referred to as Brown-Forsythe
+    test.
+
+    References
+    ----------
+    .. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm
+    .. [2] Levene, H. (1960). In Contributions to Probability and Statistics:
+           Essays in Honor of Harold Hotelling, I. Olkin et al. eds.,
+           Stanford University Press, pp. 278-292.
+    .. [3] Brown, M. B. and Forsythe, A. B. (1974), Journal of the American
+           Statistical Association, 69, 364-367
+
+    Examples
+    --------
+
+    Test whether the lists `a`, `b` and `c` come from populations
+    with equal variances.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
+    >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
+    >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
+    >>> stat, p = stats.levene(a, b, c)
+    >>> p
+    0.002431505967249681
+
+    The small p-value suggests that the populations do not have equal
+    variances.
+
+    This is not surprising, given that the sample variance of `b` is much
+    larger than that of `a` and `c`:
+
+    >>> [np.var(x, ddof=1) for x in [a, b, c]]
+    [0.007054444444444413, 0.13073888888888888, 0.008890000000000002]
+
+    For a more detailed example, see :ref:`hypothesis_levene`.
+    """
+    if center not in ['mean', 'median', 'trimmed']:
+        raise ValueError("center must be 'mean', 'median' or 'trimmed'.")
+
+    k = len(samples)
+    if k < 2:
+        raise ValueError("Must enter at least two input sample vectors.")
+
+    Ni = np.empty(k)
+    Yci = np.empty(k, 'd')
+
+    if center == 'median':
+
+        def func(x):
+            return np.median(x, axis=0)
+
+    elif center == 'mean':
+
+        def func(x):
+            return np.mean(x, axis=0)
+
+    else:  # center == 'trimmed'
+        samples = tuple(_stats_py.trimboth(np.sort(sample), proportiontocut)
+                        for sample in samples)
+
+        def func(x):
+            return np.mean(x, axis=0)
+
+    for j in range(k):
+        Ni[j] = len(samples[j])
+        Yci[j] = func(samples[j])
+    Ntot = np.sum(Ni, axis=0)
+
+    # compute Zij's
+    Zij = [None] * k
+    for i in range(k):
+        Zij[i] = abs(asarray(samples[i]) - Yci[i])
+
+    # compute Zbari
+    Zbari = np.empty(k, 'd')
+    Zbar = 0.0
+    for i in range(k):
+        Zbari[i] = np.mean(Zij[i], axis=0)
+        Zbar += Zbari[i] * Ni[i]
+
+    Zbar /= Ntot
+    numer = (Ntot - k) * np.sum(Ni * (Zbari - Zbar)**2, axis=0)
+
+    # compute denom_variance
+    dvar = 0.0
+    for i in range(k):
+        dvar += np.sum((Zij[i] - Zbari[i])**2, axis=0)
+
+    denom = (k - 1.0) * dvar
+
+    W = numer / denom
+    pval = distributions.f.sf(W, k-1, Ntot-k)  # 1 - cdf
+    return LeveneResult(W, pval)
+
+
+def _apply_func(x, g, func):
+    # g is list of indices into x
+    #  separating x into different groups
+    #  func should be applied over the groups
+    g = unique(r_[0, g, len(x)])
+    output = [func(x[g[k]:g[k+1]]) for k in range(len(g) - 1)]
+
+    return asarray(output)
+
+
+FlignerResult = namedtuple('FlignerResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(FlignerResult, n_samples=None)
+def fligner(*samples, center='median', proportiontocut=0.05):
+    r"""Perform Fligner-Killeen test for equality of variance.
+
+    Fligner's test tests the null hypothesis that all input samples
+    are from populations with equal variances.  Fligner-Killeen's test is
+    distribution free when populations are identical [2]_.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        Arrays of sample data.  Need not be the same length.
+    center : {'mean', 'median', 'trimmed'}, optional
+        Keyword argument controlling which function of the data is used in
+        computing the test statistic.  The default is 'median'.
+    proportiontocut : float, optional
+        When `center` is 'trimmed', this gives the proportion of data points
+        to cut from each end. (See `scipy.stats.trim_mean`.)
+        Default is 0.05.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic.
+    pvalue : float
+        The p-value for the hypothesis test.
+
+    See Also
+    --------
+    bartlett : A parametric test for equality of k variances in normal samples
+    levene : A robust parametric test for equality of k variances
+    :ref:`hypothesis_fligner` : Extended example
+
+    Notes
+    -----
+    As with Levene's test there are three variants of Fligner's test that
+    differ by the measure of central tendency used in the test.  See `levene`
+    for more information.
+
+    Conover et al. (1981) examine many of the existing parametric and
+    nonparametric tests by extensive simulations and they conclude that the
+    tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
+    superior in terms of robustness of departures from normality and power
+    [3]_.
+
+    References
+    ----------
+    .. [1] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
+           Hypothesis Testing based on Quadratic Inference Function. Technical
+           Report #99-03, Center for Likelihood Studies, Pennsylvania State
+           University.
+           https://cecas.clemson.edu/~cspark/cv/paper/qif/draftqif2.pdf
+    .. [2] Fligner, M.A. and Killeen, T.J. (1976). Distribution-free two-sample
+           tests for scale. Journal of the American Statistical Association.
+           71(353), 210-213.
+    .. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
+           Hypothesis Testing based on Quadratic Inference Function. Technical
+           Report #99-03, Center for Likelihood Studies, Pennsylvania State
+           University.
+    .. [4] Conover, W. J., Johnson, M. E. and Johnson M. M. (1981). A
+           comparative study of tests for homogeneity of variances, with
+           applications to the outer continental shelf bidding data.
+           Technometrics, 23(4), 351-361.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+
+    Test whether the lists `a`, `b` and `c` come from populations
+    with equal variances.
+
+    >>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
+    >>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
+    >>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
+    >>> stat, p = stats.fligner(a, b, c)
+    >>> p
+    0.00450826080004775
+
+    The small p-value suggests that the populations do not have equal
+    variances.
+
+    This is not surprising, given that the sample variance of `b` is much
+    larger than that of `a` and `c`:
+
+    >>> [np.var(x, ddof=1) for x in [a, b, c]]
+    [0.007054444444444413, 0.13073888888888888, 0.008890000000000002]
+
+    For a more detailed example, see :ref:`hypothesis_fligner`.
+    """
+    if center not in ['mean', 'median', 'trimmed']:
+        raise ValueError("center must be 'mean', 'median' or 'trimmed'.")
+
+    k = len(samples)
+    if k < 2:
+        raise ValueError("Must enter at least two input sample vectors.")
+
+    # Handle empty input
+    for sample in samples:
+        if sample.size == 0:
+            NaN = _get_nan(*samples)
+            return FlignerResult(NaN, NaN)
+
+    if center == 'median':
+
+        def func(x):
+            return np.median(x, axis=0)
+
+    elif center == 'mean':
+
+        def func(x):
+            return np.mean(x, axis=0)
+
+    else:  # center == 'trimmed'
+        samples = tuple(_stats_py.trimboth(sample, proportiontocut)
+                        for sample in samples)
+
+        def func(x):
+            return np.mean(x, axis=0)
+
+    Ni = asarray([len(samples[j]) for j in range(k)])
+    Yci = asarray([func(samples[j]) for j in range(k)])
+    Ntot = np.sum(Ni, axis=0)
+    # compute Zij's
+    Zij = [abs(asarray(samples[i]) - Yci[i]) for i in range(k)]
+    allZij = []
+    g = [0]
+    for i in range(k):
+        allZij.extend(list(Zij[i]))
+        g.append(len(allZij))
+
+    ranks = _stats_py.rankdata(allZij)
+    sample = distributions.norm.ppf(ranks / (2*(Ntot + 1.0)) + 0.5)
+
+    # compute Aibar
+    Aibar = _apply_func(sample, g, np.sum) / Ni
+    anbar = np.mean(sample, axis=0)
+    varsq = np.var(sample, axis=0, ddof=1)
+    statistic = np.sum(Ni * (asarray(Aibar) - anbar)**2.0, axis=0) / varsq
+    chi2 = _SimpleChi2(k-1)
+    pval = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=np)
+    return FlignerResult(statistic, pval)
+
+
+@_axis_nan_policy_factory(lambda x1: (x1,), n_samples=4, n_outputs=1)
+def _mood_inner_lc(xy, x, diffs, sorted_xy, n, m, N) -> float:
+    # Obtain the unique values and their frequencies from the pooled samples.
+    # "a_j, + b_j, = t_j, for j = 1, ... k" where `k` is the number of unique
+    # classes, and "[t]he number of values associated with the x's and y's in
+    # the jth class will be denoted by a_j, and b_j respectively."
+    # (Mielke, 312)
+    # Reuse previously computed sorted array and `diff` arrays to obtain the
+    # unique values and counts. Prepend `diffs` with a non-zero to indicate
+    # that the first element should be marked as not matching what preceded it.
+    diffs_prep = np.concatenate(([1], diffs))
+    # Unique elements are where the was a difference between elements in the
+    # sorted array
+    uniques = sorted_xy[diffs_prep != 0]
+    # The count of each element is the bin size for each set of consecutive
+    # differences where the difference is zero. Replace nonzero differences
+    # with 1 and then use the cumulative sum to count the indices.
+    t = np.bincount(np.cumsum(np.asarray(diffs_prep != 0, dtype=int)))[1:]
+    k = len(uniques)
+    js = np.arange(1, k + 1, dtype=int)
+    # the `b` array mentioned in the paper is not used, outside of the
+    # calculation of `t`, so we do not need to calculate it separately. Here
+    # we calculate `a`. In plain language, `a[j]` is the number of values in
+    # `x` that equal `uniques[j]`.
+    sorted_xyx = np.sort(np.concatenate((xy, x)))
+    diffs = np.diff(sorted_xyx)
+    diffs_prep = np.concatenate(([1], diffs))
+    diff_is_zero = np.asarray(diffs_prep != 0, dtype=int)
+    xyx_counts = np.bincount(np.cumsum(diff_is_zero))[1:]
+    a = xyx_counts - t
+    # "Define .. a_0 = b_0 = t_0 = S_0 = 0" (Mielke 312) so we shift  `a`
+    # and `t` arrays over 1 to allow a first element of 0 to accommodate this
+    # indexing.
+    t = np.concatenate(([0], t))
+    a = np.concatenate(([0], a))
+    # S is built from `t`, so it does not need a preceding zero added on.
+    S = np.cumsum(t)
+    # define a copy of `S` with a prepending zero for later use to avoid
+    # the need for indexing.
+    S_i_m1 = np.concatenate(([0], S[:-1]))
+
+    # Psi, as defined by the 6th unnumbered equation on page 313 (Mielke).
+    # Note that in the paper there is an error where the denominator `2` is
+    # squared when it should be the entire equation.
+    def psi(indicator):
+        return (indicator - (N + 1)/2)**2
+
+    # define summation range for use in calculation of phi, as seen in sum
+    # in the unnumbered equation on the bottom of page 312 (Mielke).
+    s_lower = S[js - 1] + 1
+    s_upper = S[js] + 1
+    phi_J = [np.arange(s_lower[idx], s_upper[idx]) for idx in range(k)]
+
+    # for every range in the above array, determine the sum of psi(I) for
+    # every element in the range. Divide all the sums by `t`. Following the
+    # last unnumbered equation on page 312.
+    phis = [np.sum(psi(I_j)) for I_j in phi_J] / t[js]
+
+    # `T` is equal to a[j] * phi[j], per the first unnumbered equation on
+    # page 312. `phis` is already in the order based on `js`, so we index
+    # into `a` with `js` as well.
+    T = sum(phis * a[js])
+
+    # The approximate statistic
+    E_0_T = n * (N * N - 1) / 12
+
+    varM = (m * n * (N + 1.0) * (N ** 2 - 4) / 180 -
+            m * n / (180 * N * (N - 1)) * np.sum(
+                t * (t**2 - 1) * (t**2 - 4 + (15 * (N - S - S_i_m1) ** 2))
+            ))
+
+    return ((T - E_0_T) / np.sqrt(varM),)
+
+
+def _mood_too_small(samples, kwargs, axis=-1):
+    x, y = samples
+    n = x.shape[axis]
+    m = y.shape[axis]
+    N = m + n
+    return N < 3
+
+
+@_axis_nan_policy_factory(SignificanceResult, n_samples=2, too_small=_mood_too_small)
+def mood(x, y, axis=0, alternative="two-sided"):
+    """Perform Mood's test for equal scale parameters.
+
+    Mood's two-sample test for scale parameters is a non-parametric
+    test for the null hypothesis that two samples are drawn from the
+    same distribution with the same scale parameter.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Arrays of sample data. There must be at least three observations
+        total.
+    axis : int, optional
+        The axis along which the samples are tested.  `x` and `y` can be of
+        different length along `axis`.
+        If `axis` is None, `x` and `y` are flattened and the test is done on
+        all values in the flattened arrays.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the scales of the distributions underlying `x` and `y`
+          are different.
+        * 'less': the scale of the distribution underlying `x` is less than
+          the scale of the distribution underlying `y`.
+        * 'greater': the scale of the distribution underlying `x` is greater
+          than the scale of the distribution underlying `y`.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : scalar or ndarray
+            The z-score for the hypothesis test.  For 1-D inputs a scalar is
+            returned.
+        pvalue : scalar ndarray
+            The p-value for the hypothesis test.
+
+    See Also
+    --------
+    fligner : A non-parametric test for the equality of k variances
+    ansari : A non-parametric test for the equality of 2 variances
+    bartlett : A parametric test for equality of k variances in normal samples
+    levene : A parametric test for equality of k variances
+
+    Notes
+    -----
+    The data are assumed to be drawn from probability distributions ``f(x)``
+    and ``f(x/s) / s`` respectively, for some probability density function f.
+    The null hypothesis is that ``s == 1``.
+
+    For multi-dimensional arrays, if the inputs are of shapes
+    ``(n0, n1, n2, n3)``  and ``(n0, m1, n2, n3)``, then if ``axis=1``, the
+    resulting z and p values will have shape ``(n0, n2, n3)``.  Note that
+    ``n1`` and ``m1`` don't have to be equal, but the other dimensions do.
+
+    References
+    ----------
+    [1] Mielke, Paul W. "Note on Some Squared Rank Tests with Existing Ties."
+        Technometrics, vol. 9, no. 2, 1967, pp. 312-14. JSTOR,
+        https://doi.org/10.2307/1266427. Accessed 18 May 2022.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x2 = rng.standard_normal((2, 45, 6, 7))
+    >>> x1 = rng.standard_normal((2, 30, 6, 7))
+    >>> res = stats.mood(x1, x2, axis=1)
+    >>> res.pvalue.shape
+    (2, 6, 7)
+
+    Find the number of points where the difference in scale is not significant:
+
+    >>> (res.pvalue > 0.1).sum()
+    78
+
+    Perform the test with different scales:
+
+    >>> x1 = rng.standard_normal((2, 30))
+    >>> x2 = rng.standard_normal((2, 35)) * 10.0
+    >>> stats.mood(x1, x2, axis=1)
+    SignificanceResult(statistic=array([-5.76174136, -6.12650783]),
+                       pvalue=array([8.32505043e-09, 8.98287869e-10]))
+
+    """
+    x = np.asarray(x, dtype=float)
+    y = np.asarray(y, dtype=float)
+
+    if axis < 0:
+        axis = x.ndim + axis
+
+    # Determine shape of the result arrays
+    res_shape = tuple([x.shape[ax] for ax in range(len(x.shape)) if ax != axis])
+    if not (res_shape == tuple([y.shape[ax] for ax in range(len(y.shape)) if
+                                ax != axis])):
+        raise ValueError("Dimensions of x and y on all axes except `axis` "
+                         "should match")
+
+    n = x.shape[axis]
+    m = y.shape[axis]
+    N = m + n
+    if N < 3:
+        raise ValueError("Not enough observations.")
+
+    xy = np.concatenate((x, y), axis=axis)
+    # determine if any of the samples contain ties
+    sorted_xy = np.sort(xy, axis=axis)
+    diffs = np.diff(sorted_xy, axis=axis)
+    if 0 in diffs:
+        z = np.asarray(_mood_inner_lc(xy, x, diffs, sorted_xy, n, m, N,
+                                      axis=axis))
+    else:
+        if axis != 0:
+            xy = np.moveaxis(xy, axis, 0)
+
+        xy = xy.reshape(xy.shape[0], -1)
+        # Generalized to the n-dimensional case by adding the axis argument,
+        # and using for loops, since rankdata is not vectorized.  For improving
+        # performance consider vectorizing rankdata function.
+        all_ranks = np.empty_like(xy)
+        for j in range(xy.shape[1]):
+            all_ranks[:, j] = _stats_py.rankdata(xy[:, j])
+
+        Ri = all_ranks[:n]
+        M = np.sum((Ri - (N + 1.0) / 2) ** 2, axis=0)
+        # Approx stat.
+        mnM = n * (N * N - 1.0) / 12
+        varM = m * n * (N + 1.0) * (N + 2) * (N - 2) / 180
+        z = (M - mnM) / sqrt(varM)
+    pval = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+
+    if res_shape == ():
+        # Return scalars, not 0-D arrays
+        z = z[0]
+        pval = pval[0]
+    else:
+        z.shape = res_shape
+        pval.shape = res_shape
+    return SignificanceResult(z[()], pval[()])
+
+
+WilcoxonResult = _make_tuple_bunch('WilcoxonResult', ['statistic', 'pvalue'])
+
+
+def wilcoxon_result_unpacker(res):
+    if hasattr(res, 'zstatistic'):
+        return res.statistic, res.pvalue, res.zstatistic
+    else:
+        return res.statistic, res.pvalue
+
+
+def wilcoxon_result_object(statistic, pvalue, zstatistic=None):
+    res = WilcoxonResult(statistic, pvalue)
+    if zstatistic is not None:
+        res.zstatistic = zstatistic
+    return res
+
+
+def wilcoxon_outputs(kwds):
+    method = kwds.get('method', 'auto')
+    if method == 'asymptotic':
+        return 3
+    return 2
+
+
+@_rename_parameter("mode", "method")
+@_axis_nan_policy_factory(
+    wilcoxon_result_object, paired=True,
+    n_samples=lambda kwds: 2 if kwds.get('y', None) is not None else 1,
+    result_to_tuple=wilcoxon_result_unpacker, n_outputs=wilcoxon_outputs,
+)
+def wilcoxon(x, y=None, zero_method="wilcox", correction=False,
+             alternative="two-sided", method='auto', *, axis=0):
+    """Calculate the Wilcoxon signed-rank test.
+
+    The Wilcoxon signed-rank test tests the null hypothesis that two
+    related paired samples come from the same distribution. In particular,
+    it tests whether the distribution of the differences ``x - y`` is symmetric
+    about zero. It is a non-parametric version of the paired T-test.
+
+    Parameters
+    ----------
+    x : array_like
+        Either the first set of measurements (in which case ``y`` is the second
+        set of measurements), or the differences between two sets of
+        measurements (in which case ``y`` is not to be specified.)  Must be
+        one-dimensional.
+    y : array_like, optional
+        Either the second set of measurements (if ``x`` is the first set of
+        measurements), or not specified (if ``x`` is the differences between
+        two sets of measurements.)  Must be one-dimensional.
+
+        .. warning::
+            When `y` is provided, `wilcoxon` calculates the test statistic
+            based on the ranks of the absolute values of ``d = x - y``.
+            Roundoff error in the subtraction can result in elements of ``d``
+            being assigned different ranks even when they would be tied with
+            exact arithmetic. Rather than passing `x` and `y` separately,
+            consider computing the difference ``x - y``, rounding as needed to
+            ensure that only truly unique elements are numerically distinct,
+            and passing the result as `x`, leaving `y` at the default (None).
+
+    zero_method : {"wilcox", "pratt", "zsplit"}, optional
+        There are different conventions for handling pairs of observations
+        with equal values ("zero-differences", or "zeros").
+
+        * "wilcox": Discards all zero-differences (default); see [4]_.
+        * "pratt": Includes zero-differences in the ranking process,
+          but drops the ranks of the zeros (more conservative); see [3]_.
+          In this case, the normal approximation is adjusted as in [5]_.
+        * "zsplit": Includes zero-differences in the ranking process and
+          splits the zero rank between positive and negative ones.
+
+    correction : bool, optional
+        If True, apply continuity correction by adjusting the Wilcoxon rank
+        statistic by 0.5 towards the mean value when computing the
+        z-statistic if a normal approximation is used.  Default is False.
+    alternative : {"two-sided", "greater", "less"}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        In the following, let ``d`` represent the difference between the paired
+        samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or
+        ``d = x`` otherwise.
+
+        * 'two-sided': the distribution underlying ``d`` is not symmetric
+          about zero.
+        * 'less': the distribution underlying ``d`` is stochastically less
+          than a distribution symmetric about zero.
+        * 'greater': the distribution underlying ``d`` is stochastically
+          greater than a distribution symmetric about zero.
+
+    method : {"auto", "exact", "asymptotic"} or `PermutationMethod` instance, optional
+        Method to calculate the p-value, see Notes. Default is "auto".
+
+    axis : int or None, default: 0
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear
+        in a corresponding element of the output. If ``None``, the input will
+        be raveled before computing the statistic.
+
+    Returns
+    -------
+    An object with the following attributes.
+
+    statistic : array_like
+        If `alternative` is "two-sided", the sum of the ranks of the
+        differences above or below zero, whichever is smaller.
+        Otherwise the sum of the ranks of the differences above zero.
+    pvalue : array_like
+        The p-value for the test depending on `alternative` and `method`.
+    zstatistic : array_like
+        When ``method = 'asymptotic'``, this is the normalized z-statistic::
+
+            z = (T - mn - d) / se
+
+        where ``T`` is `statistic` as defined above, ``mn`` is the mean of the
+        distribution under the null hypothesis, ``d`` is a continuity
+        correction, and ``se`` is the standard error.
+        When ``method != 'asymptotic'``, this attribute is not available.
+
+    See Also
+    --------
+    kruskal, mannwhitneyu
+
+    Notes
+    -----
+    In the following, let ``d`` represent the difference between the paired
+    samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or ``d = x``
+    otherwise. Assume that all elements of ``d`` are independent and
+    identically distributed observations, and all are distinct and nonzero.
+
+    - When ``len(d)`` is sufficiently large, the null distribution of the
+      normalized test statistic (`zstatistic` above) is approximately normal,
+      and ``method = 'asymptotic'`` can be used to compute the p-value.
+
+    - When ``len(d)`` is small, the normal approximation may not be accurate,
+      and ``method='exact'`` is preferred (at the cost of additional
+      execution time).
+
+    - The default, ``method='auto'``, selects between the two:
+      ``method='exact'`` is used when ``len(d) <= 50``, and
+      ``method='asymptotic'`` is used otherwise.
+
+    The presence of "ties" (i.e. not all elements of ``d`` are unique) or
+    "zeros" (i.e. elements of ``d`` are zero) changes the null distribution
+    of the test statistic, and ``method='exact'`` no longer calculates
+    the exact p-value. If ``method='asymptotic'``, the z-statistic is adjusted
+    for more accurate comparison against the standard normal, but still,
+    for finite sample sizes, the standard normal is only an approximation of
+    the true null distribution of the z-statistic. For such situations, the
+    `method` parameter also accepts instances of `PermutationMethod`. In this
+    case, the p-value is computed using `permutation_test` with the provided
+    configuration options and other appropriate settings.
+
+    The presence of ties and zeros affects the resolution of ``method='auto'``
+    accordingly: exhasutive permutations are performed when ``len(d) <= 13``,
+    and the asymptotic method is used otherwise. Note that they asymptotic
+    method may not be very accurate even for ``len(d) > 14``; the threshold
+    was chosen as a compromise between execution time and accuracy under the
+    constraint that the results must be deterministic. Consider providing an
+    instance of `PermutationMethod` method manually, choosing the
+    ``n_resamples`` parameter to balance time constraints and accuracy
+    requirements.
+
+    Please also note that in the edge case that all elements of ``d`` are zero,
+    the p-value relying on the normal approximaton cannot be computed (NaN)
+    if ``zero_method='wilcox'`` or ``zero_method='pratt'``.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test
+    .. [2] Conover, W.J., Practical Nonparametric Statistics, 1971.
+    .. [3] Pratt, J.W., Remarks on Zeros and Ties in the Wilcoxon Signed
+       Rank Procedures, Journal of the American Statistical Association,
+       Vol. 54, 1959, pp. 655-667. :doi:`10.1080/01621459.1959.10501526`
+    .. [4] Wilcoxon, F., Individual Comparisons by Ranking Methods,
+       Biometrics Bulletin, Vol. 1, 1945, pp. 80-83. :doi:`10.2307/3001968`
+    .. [5] Cureton, E.E., The Normal Approximation to the Signed-Rank
+       Sampling Distribution When Zero Differences are Present,
+       Journal of the American Statistical Association, Vol. 62, 1967,
+       pp. 1068-1069. :doi:`10.1080/01621459.1967.10500917`
+
+    Examples
+    --------
+    In [4]_, the differences in height between cross- and self-fertilized
+    corn plants is given as follows:
+
+    >>> d = [6, 8, 14, 16, 23, 24, 28, 29, 41, -48, 49, 56, 60, -67, 75]
+
+    Cross-fertilized plants appear to be higher. To test the null
+    hypothesis that there is no height difference, we can apply the
+    two-sided test:
+
+    >>> from scipy.stats import wilcoxon
+    >>> res = wilcoxon(d)
+    >>> res.statistic, res.pvalue
+    (24.0, 0.041259765625)
+
+    Hence, we would reject the null hypothesis at a confidence level of 5%,
+    concluding that there is a difference in height between the groups.
+    To confirm that the median of the differences can be assumed to be
+    positive, we use:
+
+    >>> res = wilcoxon(d, alternative='greater')
+    >>> res.statistic, res.pvalue
+    (96.0, 0.0206298828125)
+
+    This shows that the null hypothesis that the median is negative can be
+    rejected at a confidence level of 5% in favor of the alternative that
+    the median is greater than zero. The p-values above are exact. Using the
+    normal approximation gives very similar values:
+
+    >>> res = wilcoxon(d, method='asymptotic')
+    >>> res.statistic, res.pvalue
+    (24.0, 0.04088813291185591)
+
+    Note that the statistic changed to 96 in the one-sided case (the sum
+    of ranks of positive differences) whereas it is 24 in the two-sided
+    case (the minimum of sum of ranks above and below zero).
+
+    In the example above, the differences in height between paired plants are
+    provided to `wilcoxon` directly. Alternatively, `wilcoxon` accepts two
+    samples of equal length, calculates the differences between paired
+    elements, then performs the test. Consider the samples ``x`` and ``y``:
+
+    >>> import numpy as np
+    >>> x = np.array([0.5, 0.825, 0.375, 0.5])
+    >>> y = np.array([0.525, 0.775, 0.325, 0.55])
+    >>> res = wilcoxon(x, y, alternative='greater')
+    >>> res
+    WilcoxonResult(statistic=5.0, pvalue=0.5625)
+
+    Note that had we calculated the differences by hand, the test would have
+    produced different results:
+
+    >>> d = [-0.025, 0.05, 0.05, -0.05]
+    >>> ref = wilcoxon(d, alternative='greater')
+    >>> ref
+    WilcoxonResult(statistic=6.0, pvalue=0.5)
+
+    The substantial difference is due to roundoff error in the results of
+    ``x-y``:
+
+    >>> d - (x-y)
+    array([2.08166817e-17, 6.93889390e-17, 1.38777878e-17, 4.16333634e-17])
+
+    Even though we expected all the elements of ``(x-y)[1:]`` to have the same
+    magnitude ``0.05``, they have slightly different magnitudes in practice,
+    and therefore are assigned different ranks in the test. Before performing
+    the test, consider calculating ``d`` and adjusting it as necessary to
+    ensure that theoretically identically values are not numerically distinct.
+    For example:
+
+    >>> d2 = np.around(x - y, decimals=3)
+    >>> wilcoxon(d2, alternative='greater')
+    WilcoxonResult(statistic=6.0, pvalue=0.5)
+
+    """
+    # replace approx by asymptotic to ensure backwards compatability
+    if method == "approx":
+        method = "asymptotic"
+    return _wilcoxon._wilcoxon_nd(x, y, zero_method, correction, alternative,
+                                  method, axis)
+
+
+MedianTestResult = _make_tuple_bunch(
+    'MedianTestResult',
+    ['statistic', 'pvalue', 'median', 'table'], []
+)
+
+
+def median_test(*samples, ties='below', correction=True, lambda_=1,
+                nan_policy='propagate'):
+    """Perform a Mood's median test.
+
+    Test that two or more samples come from populations with the same median.
+
+    Let ``n = len(samples)`` be the number of samples.  The "grand median" of
+    all the data is computed, and a contingency table is formed by
+    classifying the values in each sample as being above or below the grand
+    median.  The contingency table, along with `correction` and `lambda_`,
+    are passed to `scipy.stats.chi2_contingency` to compute the test statistic
+    and p-value.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The set of samples.  There must be at least two samples.
+        Each sample must be a one-dimensional sequence containing at least
+        one value.  The samples are not required to have the same length.
+    ties : str, optional
+        Determines how values equal to the grand median are classified in
+        the contingency table.  The string must be one of::
+
+            "below":
+                Values equal to the grand median are counted as "below".
+            "above":
+                Values equal to the grand median are counted as "above".
+            "ignore":
+                Values equal to the grand median are not counted.
+
+        The default is "below".
+    correction : bool, optional
+        If True, *and* there are just two samples, apply Yates' correction
+        for continuity when computing the test statistic associated with
+        the contingency table.  Default is True.
+    lambda_ : float or str, optional
+        By default, the statistic computed in this test is Pearson's
+        chi-squared statistic.  `lambda_` allows a statistic from the
+        Cressie-Read power divergence family to be used instead.  See
+        `power_divergence` for details.
+        Default is 1 (Pearson's chi-squared statistic).
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.
+
+    Returns
+    -------
+    res : MedianTestResult
+        An object containing attributes:
+
+        statistic : float
+            The test statistic.  The statistic that is returned is determined
+            by `lambda_`.  The default is Pearson's chi-squared statistic.
+        pvalue : float
+            The p-value of the test.
+        median : float
+            The grand median.
+        table : ndarray
+            The contingency table.  The shape of the table is (2, n), where
+            n is the number of samples.  The first row holds the counts of the
+            values above the grand median, and the second row holds the counts
+            of the values below the grand median.  The table allows further
+            analysis with, for example, `scipy.stats.chi2_contingency`, or with
+            `scipy.stats.fisher_exact` if there are two samples, without having
+            to recompute the table.  If ``nan_policy`` is "propagate" and there
+            are nans in the input, the return value for ``table`` is ``None``.
+
+    See Also
+    --------
+    kruskal : Compute the Kruskal-Wallis H-test for independent samples.
+    mannwhitneyu : Computes the Mann-Whitney rank test on samples x and y.
+
+    Notes
+    -----
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Mood, A. M., Introduction to the Theory of Statistics. McGraw-Hill
+        (1950), pp. 394-399.
+    .. [2] Zar, J. H., Biostatistical Analysis, 5th ed. Prentice Hall (2010).
+        See Sections 8.12 and 10.15.
+
+    Examples
+    --------
+    A biologist runs an experiment in which there are three groups of plants.
+    Group 1 has 16 plants, group 2 has 15 plants, and group 3 has 17 plants.
+    Each plant produces a number of seeds.  The seed counts for each group
+    are::
+
+        Group 1: 10 14 14 18 20 22 24 25 31 31 32 39 43 43 48 49
+        Group 2: 28 30 31 33 34 35 36 40 44 55 57 61 91 92 99
+        Group 3:  0  3  9 22 23 25 25 33 34 34 40 45 46 48 62 67 84
+
+    The following code applies Mood's median test to these samples.
+
+    >>> g1 = [10, 14, 14, 18, 20, 22, 24, 25, 31, 31, 32, 39, 43, 43, 48, 49]
+    >>> g2 = [28, 30, 31, 33, 34, 35, 36, 40, 44, 55, 57, 61, 91, 92, 99]
+    >>> g3 = [0, 3, 9, 22, 23, 25, 25, 33, 34, 34, 40, 45, 46, 48, 62, 67, 84]
+    >>> from scipy.stats import median_test
+    >>> res = median_test(g1, g2, g3)
+
+    The median is
+
+    >>> res.median
+    34.0
+
+    and the contingency table is
+
+    >>> res.table
+    array([[ 5, 10,  7],
+           [11,  5, 10]])
+
+    `p` is too large to conclude that the medians are not the same:
+
+    >>> res.pvalue
+    0.12609082774093244
+
+    The "G-test" can be performed by passing ``lambda_="log-likelihood"`` to
+    `median_test`.
+
+    >>> res = median_test(g1, g2, g3, lambda_="log-likelihood")
+    >>> res.pvalue
+    0.12224779737117837
+
+    The median occurs several times in the data, so we'll get a different
+    result if, for example, ``ties="above"`` is used:
+
+    >>> res = median_test(g1, g2, g3, ties="above")
+    >>> res.pvalue
+    0.063873276069553273
+
+    >>> res.table
+    array([[ 5, 11,  9],
+           [11,  4,  8]])
+
+    This example demonstrates that if the data set is not large and there
+    are values equal to the median, the p-value can be sensitive to the
+    choice of `ties`.
+
+    """
+    if len(samples) < 2:
+        raise ValueError('median_test requires two or more samples.')
+
+    ties_options = ['below', 'above', 'ignore']
+    if ties not in ties_options:
+        raise ValueError(f"invalid 'ties' option '{ties}'; 'ties' must be one "
+                         f"of: {str(ties_options)[1:-1]}")
+
+    data = [np.asarray(sample) for sample in samples]
+
+    # Validate the sizes and shapes of the arguments.
+    for k, d in enumerate(data):
+        if d.size == 0:
+            raise ValueError("Sample %d is empty. All samples must "
+                             "contain at least one value." % (k + 1))
+        if d.ndim != 1:
+            raise ValueError("Sample %d has %d dimensions.  All "
+                             "samples must be one-dimensional sequences." %
+                             (k + 1, d.ndim))
+
+    cdata = np.concatenate(data)
+    contains_nan, nan_policy = _contains_nan(cdata, nan_policy)
+    if contains_nan and nan_policy == 'propagate':
+        return MedianTestResult(np.nan, np.nan, np.nan, None)
+
+    if contains_nan:
+        grand_median = np.median(cdata[~np.isnan(cdata)])
+    else:
+        grand_median = np.median(cdata)
+    # When the minimum version of numpy supported by scipy is 1.9.0,
+    # the above if/else statement can be replaced by the single line:
+    #     grand_median = np.nanmedian(cdata)
+
+    # Create the contingency table.
+    table = np.zeros((2, len(data)), dtype=np.int64)
+    for k, sample in enumerate(data):
+        sample = sample[~np.isnan(sample)]
+
+        nabove = count_nonzero(sample > grand_median)
+        nbelow = count_nonzero(sample < grand_median)
+        nequal = sample.size - (nabove + nbelow)
+        table[0, k] += nabove
+        table[1, k] += nbelow
+        if ties == "below":
+            table[1, k] += nequal
+        elif ties == "above":
+            table[0, k] += nequal
+
+    # Check that no row or column of the table is all zero.
+    # Such a table can not be given to chi2_contingency, because it would have
+    # a zero in the table of expected frequencies.
+    rowsums = table.sum(axis=1)
+    if rowsums[0] == 0:
+        raise ValueError(f"All values are below the grand median ({grand_median}).")
+    if rowsums[1] == 0:
+        raise ValueError(f"All values are above the grand median ({grand_median}).")
+    if ties == "ignore":
+        # We already checked that each sample has at least one value, but it
+        # is possible that all those values equal the grand median.  If `ties`
+        # is "ignore", that would result in a column of zeros in `table`.  We
+        # check for that case here.
+        zero_cols = np.nonzero((table == 0).all(axis=0))[0]
+        if len(zero_cols) > 0:
+            msg = ("All values in sample %d are equal to the grand "
+                   "median (%r), so they are ignored, resulting in an "
+                   "empty sample." % (zero_cols[0] + 1, grand_median))
+            raise ValueError(msg)
+
+    stat, p, dof, expected = chi2_contingency(table, lambda_=lambda_,
+                                              correction=correction)
+    return MedianTestResult(stat, p, grand_median, table)
+
+
+def _circfuncs_common(samples, period, xp=None):
+    xp = array_namespace(samples) if xp is None else xp
+
+    if xp.isdtype(samples.dtype, 'integral'):
+        dtype = xp.asarray(1.).dtype  # get default float type
+        samples = xp.asarray(samples, dtype=dtype)
+
+    # Recast samples as radians that range between 0 and 2 pi and calculate
+    # the sine and cosine
+    scaled_samples = samples * ((2.0 * pi) / period)
+    sin_samp = xp.sin(scaled_samples)
+    cos_samp = xp.cos(scaled_samples)
+
+    return samples, sin_samp, cos_samp
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, default_axis=None,
+    result_to_tuple=lambda x: (x,)
+)
+def circmean(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'):
+    r"""Compute the circular mean of a sample of angle observations.
+
+    Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
+    radians, their *circular mean* is defined by ([1]_, Eq. 2.2.4)
+
+    .. math::
+
+       \mathrm{Arg} \left( \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right)
+
+    where :math:`i` is the imaginary unit and :math:`\mathop{\mathrm{Arg}} z`
+    gives the principal value of the argument of complex number :math:`z`,
+    restricted to the range :math:`[0,2\pi]` by default.  :math:`z` in the
+    above expression is known as the `mean resultant vector`.
+
+    Parameters
+    ----------
+    samples : array_like
+        Input array of angle observations.  The value of a full angle is
+        equal to ``(high - low)``.
+    high : float, optional
+        Upper boundary of the principal value of an angle.  Default is ``2*pi``.
+    low : float, optional
+        Lower boundary of the principal value of an angle.  Default is ``0``.
+
+    Returns
+    -------
+    circmean : float
+        Circular mean, restricted to the range ``[low, high]``.
+
+        If the mean resultant vector is zero, an input-dependent,
+        implementation-defined number between ``[low, high]`` is returned.
+        If the input array is empty, ``np.nan`` is returned.
+
+    See Also
+    --------
+    circstd : Circular standard deviation.
+    circvar : Circular variance.
+
+    References
+    ----------
+    .. [1] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
+           John Wiley & Sons, 1999.
+
+    Examples
+    --------
+    For readability, all angles are printed out in degrees.
+
+    >>> import numpy as np
+    >>> from scipy.stats import circmean
+    >>> import matplotlib.pyplot as plt
+    >>> angles = np.deg2rad(np.array([20, 30, 330]))
+    >>> circmean = circmean(angles)
+    >>> np.rad2deg(circmean)
+    7.294976657784009
+
+    >>> mean = angles.mean()
+    >>> np.rad2deg(mean)
+    126.66666666666666
+
+    Plot and compare the circular mean against the arithmetic mean.
+
+    >>> plt.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
+    ...          np.sin(np.linspace(0, 2*np.pi, 500)),
+    ...          c='k')
+    >>> plt.scatter(np.cos(angles), np.sin(angles), c='k')
+    >>> plt.scatter(np.cos(circmean), np.sin(circmean), c='b',
+    ...             label='circmean')
+    >>> plt.scatter(np.cos(mean), np.sin(mean), c='r', label='mean')
+    >>> plt.legend()
+    >>> plt.axis('equal')
+    >>> plt.show()
+
+    """
+    xp = array_namespace(samples)
+    # Needed for non-NumPy arrays to get appropriate NaN result
+    # Apparently atan2(0, 0) is 0, even though it is mathematically undefined
+    if xp_size(samples) == 0:
+        return xp.mean(samples, axis=axis)
+    period = high - low
+    samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp)
+    sin_sum = xp.sum(sin_samp, axis=axis)
+    cos_sum = xp.sum(cos_samp, axis=axis)
+    res = xp.atan2(sin_sum, cos_sum)
+
+    res = res[()] if res.ndim == 0 else res
+    return (res * (period / (2.0 * pi)) - low) % period + low
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, default_axis=None,
+    result_to_tuple=lambda x: (x,)
+)
+def circvar(samples, high=2*pi, low=0, axis=None, nan_policy='propagate'):
+    r"""Compute the circular variance of a sample of angle observations.
+
+    Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
+    radians, their *circular variance* is defined by ([2]_, Eq. 2.3.3)
+
+    .. math::
+
+       1 - \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right|
+
+    where :math:`i` is the imaginary unit and :math:`|z|` gives the length
+    of the complex number :math:`z`.  :math:`|z|` in the above expression
+    is known as the `mean resultant length`.
+
+    Parameters
+    ----------
+    samples : array_like
+        Input array of angle observations.  The value of a full angle is
+        equal to ``(high - low)``.
+    high : float, optional
+        Upper boundary of the principal value of an angle.  Default is ``2*pi``.
+    low : float, optional
+        Lower boundary of the principal value of an angle.  Default is ``0``.
+
+    Returns
+    -------
+    circvar : float
+        Circular variance.  The returned value is in the range ``[0, 1]``,
+        where ``0`` indicates no variance and ``1`` indicates large variance.
+
+        If the input array is empty, ``np.nan`` is returned.
+
+    See Also
+    --------
+    circmean : Circular mean.
+    circstd : Circular standard deviation.
+
+    Notes
+    -----
+    In the limit of small angles, the circular variance is close to
+    half the 'linear' variance if measured in radians.
+
+    References
+    ----------
+    .. [1] Fisher, N.I. *Statistical analysis of circular data*. Cambridge
+           University Press, 1993.
+    .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
+           John Wiley & Sons, 1999.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import circvar
+    >>> import matplotlib.pyplot as plt
+    >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286,
+    ...                       0.133, -0.473, -0.001, -0.348, 0.131])
+    >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421,
+    ...                       0.104, -0.136, -0.867,  0.012,  0.105])
+    >>> circvar_1 = circvar(samples_1)
+    >>> circvar_2 = circvar(samples_2)
+
+    Plot the samples.
+
+    >>> fig, (left, right) = plt.subplots(ncols=2)
+    >>> for image in (left, right):
+    ...     image.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
+    ...                np.sin(np.linspace(0, 2*np.pi, 500)),
+    ...                c='k')
+    ...     image.axis('equal')
+    ...     image.axis('off')
+    >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15)
+    >>> left.set_title(f"circular variance: {np.round(circvar_1, 2)!r}")
+    >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15)
+    >>> right.set_title(f"circular variance: {np.round(circvar_2, 2)!r}")
+    >>> plt.show()
+
+    """
+    xp = array_namespace(samples)
+    period = high - low
+    samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp)
+    sin_mean = xp.mean(sin_samp, axis=axis)
+    cos_mean = xp.mean(cos_samp, axis=axis)
+    hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5
+    # hypotenuse can go slightly above 1 due to rounding errors
+    R = xp.clip(hypotenuse, max=1.)
+
+    res = 1. - R
+    return res
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, default_axis=None,
+    result_to_tuple=lambda x: (x,)
+)
+def circstd(samples, high=2*pi, low=0, axis=None, nan_policy='propagate', *,
+            normalize=False):
+    r"""
+    Compute the circular standard deviation of a sample of angle observations.
+
+    Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
+    radians, their `circular standard deviation` is defined by
+    ([2]_, Eq. 2.3.11)
+
+    .. math::
+
+       \sqrt{ -2 \log \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right| }
+
+    where :math:`i` is the imaginary unit and :math:`|z|` gives the length
+    of the complex number :math:`z`.  :math:`|z|` in the above expression
+    is known as the `mean resultant length`.
+
+    Parameters
+    ----------
+    samples : array_like
+        Input array of angle observations.  The value of a full angle is
+        equal to ``(high - low)``.
+    high : float, optional
+        Upper boundary of the principal value of an angle.  Default is ``2*pi``.
+    low : float, optional
+        Lower boundary of the principal value of an angle.  Default is ``0``.
+    normalize : boolean, optional
+        If ``False`` (the default), the return value is computed from the
+        above formula with the input scaled by ``(2*pi)/(high-low)`` and
+        the output scaled (back) by ``(high-low)/(2*pi)``.  If ``True``,
+        the output is not scaled and is returned directly.
+
+    Returns
+    -------
+    circstd : float
+        Circular standard deviation, optionally normalized.
+
+        If the input array is empty, ``np.nan`` is returned.
+
+    See Also
+    --------
+    circmean : Circular mean.
+    circvar : Circular variance.
+
+    Notes
+    -----
+    In the limit of small angles, the circular standard deviation is close
+    to the 'linear' standard deviation if ``normalize`` is ``False``.
+
+    References
+    ----------
+    .. [1] Mardia, K. V. (1972). 2. In *Statistics of Directional Data*
+       (pp. 18-24). Academic Press. :doi:`10.1016/C2013-0-07425-7`.
+    .. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
+           John Wiley & Sons, 1999.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import circstd
+    >>> import matplotlib.pyplot as plt
+    >>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286,
+    ...                       0.133, -0.473, -0.001, -0.348, 0.131])
+    >>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421,
+    ...                       0.104, -0.136, -0.867,  0.012,  0.105])
+    >>> circstd_1 = circstd(samples_1)
+    >>> circstd_2 = circstd(samples_2)
+
+    Plot the samples.
+
+    >>> fig, (left, right) = plt.subplots(ncols=2)
+    >>> for image in (left, right):
+    ...     image.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
+    ...                np.sin(np.linspace(0, 2*np.pi, 500)),
+    ...                c='k')
+    ...     image.axis('equal')
+    ...     image.axis('off')
+    >>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15)
+    >>> left.set_title(f"circular std: {np.round(circstd_1, 2)!r}")
+    >>> right.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
+    ...            np.sin(np.linspace(0, 2*np.pi, 500)),
+    ...            c='k')
+    >>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15)
+    >>> right.set_title(f"circular std: {np.round(circstd_2, 2)!r}")
+    >>> plt.show()
+
+    """
+    xp = array_namespace(samples)
+    period = high - low
+    samples, sin_samp, cos_samp = _circfuncs_common(samples, period, xp=xp)
+    sin_mean = xp.mean(sin_samp, axis=axis)  # [1] (2.2.3)
+    cos_mean = xp.mean(cos_samp, axis=axis)  # [1] (2.2.3)
+    hypotenuse = (sin_mean**2. + cos_mean**2.)**0.5
+    # hypotenuse can go slightly above 1 due to rounding errors
+    R = xp.clip(hypotenuse, max=1.)  # [1] (2.2.4)
+
+    res = (-2*xp.log(R))**0.5+0.0  # torch.pow returns -0.0 if R==1
+    if not normalize:
+        res *= (high-low)/(2.*pi)  # [1] (2.3.14) w/ (2.3.7)
+    return res
+
+
+class DirectionalStats:
+    def __init__(self, mean_direction, mean_resultant_length):
+        self.mean_direction = mean_direction
+        self.mean_resultant_length = mean_resultant_length
+
+    def __repr__(self):
+        return (f"DirectionalStats(mean_direction={self.mean_direction},"
+                f" mean_resultant_length={self.mean_resultant_length})")
+
+
+def directional_stats(samples, *, axis=0, normalize=True):
+    """
+    Computes sample statistics for directional data.
+
+    Computes the directional mean (also called the mean direction vector) and
+    mean resultant length of a sample of vectors.
+
+    The directional mean is a measure of "preferred direction" of vector data.
+    It is analogous to the sample mean, but it is for use when the length of
+    the data is irrelevant (e.g. unit vectors).
+
+    The mean resultant length is a value between 0 and 1 used to quantify the
+    dispersion of directional data: the smaller the mean resultant length, the
+    greater the dispersion. Several definitions of directional variance
+    involving the mean resultant length are given in [1]_ and [2]_.
+
+    Parameters
+    ----------
+    samples : array_like
+        Input array. Must be at least two-dimensional, and the last axis of the
+        input must correspond with the dimensionality of the vector space.
+        When the input is exactly two dimensional, this means that each row
+        of the data is a vector observation.
+    axis : int, default: 0
+        Axis along which the directional mean is computed.
+    normalize: boolean, default: True
+        If True, normalize the input to ensure that each observation is a
+        unit vector. It the observations are already unit vectors, consider
+        setting this to False to avoid unnecessary computation.
+
+    Returns
+    -------
+    res : DirectionalStats
+        An object containing attributes:
+
+        mean_direction : ndarray
+            Directional mean.
+        mean_resultant_length : ndarray
+            The mean resultant length [1]_.
+
+    See Also
+    --------
+    circmean: circular mean; i.e. directional mean for 2D *angles*
+    circvar: circular variance; i.e. directional variance for 2D *angles*
+
+    Notes
+    -----
+    This uses a definition of directional mean from [1]_.
+    Assuming the observations are unit vectors, the calculation is as follows.
+
+    .. code-block:: python
+
+        mean = samples.mean(axis=0)
+        mean_resultant_length = np.linalg.norm(mean)
+        mean_direction = mean / mean_resultant_length
+
+    This definition is appropriate for *directional* data (i.e. vector data
+    for which the magnitude of each observation is irrelevant) but not
+    for *axial* data (i.e. vector data for which the magnitude and *sign* of
+    each observation is irrelevant).
+
+    Several definitions of directional variance involving the mean resultant
+    length ``R`` have been proposed, including ``1 - R`` [1]_, ``1 - R**2``
+    [2]_, and ``2 * (1 - R)`` [2]_. Rather than choosing one, this function
+    returns ``R`` as attribute `mean_resultant_length` so the user can compute
+    their preferred measure of dispersion.
+
+    References
+    ----------
+    .. [1] Mardia, Jupp. (2000). *Directional Statistics*
+       (p. 163). Wiley.
+
+    .. [2] https://en.wikipedia.org/wiki/Directional_statistics
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import directional_stats
+    >>> data = np.array([[3, 4],    # first observation, 2D vector space
+    ...                  [6, -8]])  # second observation
+    >>> dirstats = directional_stats(data)
+    >>> dirstats.mean_direction
+    array([1., 0.])
+
+    In contrast, the regular sample mean of the vectors would be influenced
+    by the magnitude of each observation. Furthermore, the result would not be
+    a unit vector.
+
+    >>> data.mean(axis=0)
+    array([4.5, -2.])
+
+    An exemplary use case for `directional_stats` is to find a *meaningful*
+    center for a set of observations on a sphere, e.g. geographical locations.
+
+    >>> data = np.array([[0.8660254, 0.5, 0.],
+    ...                  [0.8660254, -0.5, 0.]])
+    >>> dirstats = directional_stats(data)
+    >>> dirstats.mean_direction
+    array([1., 0., 0.])
+
+    The regular sample mean on the other hand yields a result which does not
+    lie on the surface of the sphere.
+
+    >>> data.mean(axis=0)
+    array([0.8660254, 0., 0.])
+
+    The function also returns the mean resultant length, which
+    can be used to calculate a directional variance. For example, using the
+    definition ``Var(z) = 1 - R`` from [2]_ where ``R`` is the
+    mean resultant length, we can calculate the directional variance of the
+    vectors in the above example as:
+
+    >>> 1 - dirstats.mean_resultant_length
+    0.13397459716167093
+    """
+    xp = array_namespace(samples)
+    samples = xp.asarray(samples)
+
+    if samples.ndim < 2:
+        raise ValueError("samples must at least be two-dimensional. "
+                         f"Instead samples has shape: {tuple(samples.shape)}")
+    samples = xp.moveaxis(samples, axis, 0)
+    if normalize:
+        vectornorms = xp_vector_norm(samples, axis=-1, keepdims=True, xp=xp)
+        samples = samples/vectornorms
+    mean = xp.mean(samples, axis=0)
+    mean_resultant_length = xp_vector_norm(mean, axis=-1, keepdims=True, xp=xp)
+    mean_direction = mean / mean_resultant_length
+    mrl = xp.squeeze(mean_resultant_length, axis=-1)
+    mean_resultant_length = mrl[()] if mrl.ndim == 0 else mrl
+    return DirectionalStats(mean_direction, mean_resultant_length)
+
+
+def false_discovery_control(ps, *, axis=0, method='bh'):
+    """Adjust p-values to control the false discovery rate.
+
+    The false discovery rate (FDR) is the expected proportion of rejected null
+    hypotheses that are actually true.
+    If the null hypothesis is rejected when the *adjusted* p-value falls below
+    a specified level, the false discovery rate is controlled at that level.
+
+    Parameters
+    ----------
+    ps : 1D array_like
+        The p-values to adjust. Elements must be real numbers between 0 and 1.
+    axis : int
+        The axis along which to perform the adjustment. The adjustment is
+        performed independently along each axis-slice. If `axis` is None, `ps`
+        is raveled before performing the adjustment.
+    method : {'bh', 'by'}
+        The false discovery rate control procedure to apply: ``'bh'`` is for
+        Benjamini-Hochberg [1]_ (Eq. 1), ``'by'`` is for Benjaminini-Yekutieli
+        [2]_ (Theorem 1.3). The latter is more conservative, but it is
+        guaranteed to control the FDR even when the p-values are not from
+        independent tests.
+
+    Returns
+    -------
+    ps_adusted : array_like
+        The adjusted p-values. If the null hypothesis is rejected where these
+        fall below a specified level, the false discovery rate is controlled
+        at that level.
+
+    See Also
+    --------
+    combine_pvalues
+    statsmodels.stats.multitest.multipletests
+
+    Notes
+    -----
+    In multiple hypothesis testing, false discovery control procedures tend to
+    offer higher power than familywise error rate control procedures (e.g.
+    Bonferroni correction [1]_).
+
+    If the p-values correspond with independent tests (or tests with
+    "positive regression dependencies" [2]_), rejecting null hypotheses
+    corresponding with Benjamini-Hochberg-adjusted p-values below :math:`q`
+    controls the false discovery rate at a level less than or equal to
+    :math:`q m_0 / m`, where :math:`m_0` is the number of true null hypotheses
+    and :math:`m` is the total number of null hypotheses tested. The same is
+    true even for dependent tests when the p-values are adjusted accorded to
+    the more conservative Benjaminini-Yekutieli procedure.
+
+    The adjusted p-values produced by this function are comparable to those
+    produced by the R function ``p.adjust`` and the statsmodels function
+    `statsmodels.stats.multitest.multipletests`. Please consider the latter
+    for more advanced methods of multiple comparison correction.
+
+    References
+    ----------
+    .. [1] Benjamini, Yoav, and Yosef Hochberg. "Controlling the false
+           discovery rate: a practical and powerful approach to multiple
+           testing." Journal of the Royal statistical society: series B
+           (Methodological) 57.1 (1995): 289-300.
+
+    .. [2] Benjamini, Yoav, and Daniel Yekutieli. "The control of the false
+           discovery rate in multiple testing under dependency." Annals of
+           statistics (2001): 1165-1188.
+
+    .. [3] TileStats. FDR - Benjamini-Hochberg explained - Youtube.
+           https://www.youtube.com/watch?v=rZKa4tW2NKs.
+
+    .. [4] Neuhaus, Karl-Ludwig, et al. "Improved thrombolysis in acute
+           myocardial infarction with front-loaded administration of alteplase:
+           results of the rt-PA-APSAC patency study (TAPS)." Journal of the
+           American College of Cardiology 19.5 (1992): 885-891.
+
+    Examples
+    --------
+    We follow the example from [1]_.
+
+        Thrombolysis with recombinant tissue-type plasminogen activator (rt-PA)
+        and anisoylated plasminogen streptokinase activator (APSAC) in
+        myocardial infarction has been proved to reduce mortality. [4]_
+        investigated the effects of a new front-loaded administration of rt-PA
+        versus those obtained with a standard regimen of APSAC, in a randomized
+        multicentre trial in 421 patients with acute myocardial infarction.
+
+    There were four families of hypotheses tested in the study, the last of
+    which was "cardiac and other events after the start of thrombolitic
+    treatment". FDR control may be desired in this family of hypotheses
+    because it would not be appropriate to conclude that the front-loaded
+    treatment is better if it is merely equivalent to the previous treatment.
+
+    The p-values corresponding with the 15 hypotheses in this family were
+
+    >>> ps = [0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344,
+    ...       0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000]
+
+    If the chosen significance level is 0.05, we may be tempted to reject the
+    null hypotheses for the tests corresponding with the first nine p-values,
+    as the first nine p-values fall below the chosen significance level.
+    However, this would ignore the problem of "multiplicity": if we fail to
+    correct for the fact that multiple comparisons are being performed, we
+    are more likely to incorrectly reject true null hypotheses.
+
+    One approach to the multiplicity problem is to control the family-wise
+    error rate (FWER), that is, the rate at which the null hypothesis is
+    rejected when it is actually true. A common procedure of this kind is the
+    Bonferroni correction [1]_.  We begin by multiplying the p-values by the
+    number of hypotheses tested.
+
+    >>> import numpy as np
+    >>> np.array(ps) * len(ps)
+    array([1.5000e-03, 6.0000e-03, 2.8500e-02, 1.4250e-01, 3.0150e-01,
+           4.1700e-01, 4.4700e-01, 5.1600e-01, 6.8850e-01, 4.8600e+00,
+           6.3930e+00, 8.5785e+00, 9.7920e+00, 1.1385e+01, 1.5000e+01])
+
+    To control the FWER at 5%, we reject only the hypotheses corresponding
+    with adjusted p-values less than 0.05. In this case, only the hypotheses
+    corresponding with the first three p-values can be rejected. According to
+    [1]_, these three hypotheses concerned "allergic reaction" and "two
+    different aspects of bleeding."
+
+    An alternative approach is to control the false discovery rate: the
+    expected fraction of rejected null hypotheses that are actually true. The
+    advantage of this approach is that it typically affords greater power: an
+    increased rate of rejecting the null hypothesis when it is indeed false. To
+    control the false discovery rate at 5%, we apply the Benjamini-Hochberg
+    p-value adjustment.
+
+    >>> from scipy import stats
+    >>> stats.false_discovery_control(ps)
+    array([0.0015    , 0.003     , 0.0095    , 0.035625  , 0.0603    ,
+           0.06385714, 0.06385714, 0.0645    , 0.0765    , 0.486     ,
+           0.58118182, 0.714875  , 0.75323077, 0.81321429, 1.        ])
+
+    Now, the first *four* adjusted p-values fall below 0.05, so we would reject
+    the null hypotheses corresponding with these *four* p-values. Rejection
+    of the fourth null hypothesis was particularly important to the original
+    study as it led to the conclusion that the new treatment had a
+    "substantially lower in-hospital mortality rate."
+
+    """
+    # Input Validation and Special Cases
+    ps = np.asarray(ps)
+
+    ps_in_range = (np.issubdtype(ps.dtype, np.number)
+                   and np.all(ps == np.clip(ps, 0, 1)))
+    if not ps_in_range:
+        raise ValueError("`ps` must include only numbers between 0 and 1.")
+
+    methods = {'bh', 'by'}
+    if method.lower() not in methods:
+        raise ValueError(f"Unrecognized `method` '{method}'."
+                         f"Method must be one of {methods}.")
+    method = method.lower()
+
+    if axis is None:
+        axis = 0
+        ps = ps.ravel()
+
+    axis = np.asarray(axis)[()]
+    if not np.issubdtype(axis.dtype, np.integer) or axis.size != 1:
+        raise ValueError("`axis` must be an integer or `None`")
+
+    if ps.size <= 1 or ps.shape[axis] <= 1:
+        return ps[()]
+
+    ps = np.moveaxis(ps, axis, -1)
+    m = ps.shape[-1]
+
+    # Main Algorithm
+    # Equivalent to the ideas of [1] and [2], except that this adjusts the
+    # p-values as described in [3]. The results are similar to those produced
+    # by R's p.adjust.
+
+    # "Let [ps] be the ordered observed p-values..."
+    order = np.argsort(ps, axis=-1)
+    ps = np.take_along_axis(ps, order, axis=-1)  # this copies ps
+
+    # Equation 1 of [1] rearranged to reject when p is less than specified q
+    i = np.arange(1, m+1)
+    ps *= m / i
+
+    # Theorem 1.3 of [2]
+    if method == 'by':
+        ps *= np.sum(1 / i)
+
+    # accounts for rejecting all null hypotheses i for i < k, where k is
+    # defined in Eq. 1 of either [1] or [2]. See [3]. Starting with the index j
+    # of the second to last element, we replace element j with element j+1 if
+    # the latter is smaller.
+    np.minimum.accumulate(ps[..., ::-1], out=ps[..., ::-1], axis=-1)
+
+    # Restore original order of axes and data
+    np.put_along_axis(ps, order, values=ps.copy(), axis=-1)
+    ps = np.moveaxis(ps, -1, axis)
+
+    return np.clip(ps, 0, 1)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..bce32dcbafcce32fb1511538c06655445c2417bf
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_basic.py
@@ -0,0 +1,3662 @@
+"""
+An extension of scipy.stats._stats_py to support masked arrays
+
+"""
+# Original author (2007): Pierre GF Gerard-Marchant
+
+
+__all__ = ['argstoarray',
+           'count_tied_groups',
+           'describe',
+           'f_oneway', 'find_repeats','friedmanchisquare',
+           'kendalltau','kendalltau_seasonal','kruskal','kruskalwallis',
+           'ks_twosamp', 'ks_2samp', 'kurtosis', 'kurtosistest',
+           'ks_1samp', 'kstest',
+           'linregress',
+           'mannwhitneyu', 'meppf','mode','moment','mquantiles','msign',
+           'normaltest',
+           'obrientransform',
+           'pearsonr','plotting_positions','pointbiserialr',
+           'rankdata',
+           'scoreatpercentile','sem',
+           'sen_seasonal_slopes','skew','skewtest','spearmanr',
+           'siegelslopes', 'theilslopes',
+           'tmax','tmean','tmin','trim','trimboth',
+           'trimtail','trima','trimr','trimmed_mean','trimmed_std',
+           'trimmed_stde','trimmed_var','tsem','ttest_1samp','ttest_onesamp',
+           'ttest_ind','ttest_rel','tvar',
+           'variation',
+           'winsorize',
+           'brunnermunzel',
+           ]
+
+import numpy as np
+from numpy import ndarray
+import numpy.ma as ma
+from numpy.ma import masked, nomask
+import math
+
+import itertools
+import warnings
+from collections import namedtuple
+
+from . import distributions
+from scipy._lib._util import _rename_parameter, _contains_nan
+from scipy._lib._bunch import _make_tuple_bunch
+import scipy.special as special
+import scipy.stats._stats_py
+import scipy.stats._stats_py as _stats_py
+
+from ._stats_mstats_common import (
+        _find_repeats,
+        theilslopes as stats_theilslopes,
+        siegelslopes as stats_siegelslopes
+        )
+
+
+def _chk_asarray(a, axis):
+    # Always returns a masked array, raveled for axis=None
+    a = ma.asanyarray(a)
+    if axis is None:
+        a = ma.ravel(a)
+        outaxis = 0
+    else:
+        outaxis = axis
+    return a, outaxis
+
+
+def _chk2_asarray(a, b, axis):
+    a = ma.asanyarray(a)
+    b = ma.asanyarray(b)
+    if axis is None:
+        a = ma.ravel(a)
+        b = ma.ravel(b)
+        outaxis = 0
+    else:
+        outaxis = axis
+    return a, b, outaxis
+
+
+def _chk_size(a, b):
+    a = ma.asanyarray(a)
+    b = ma.asanyarray(b)
+    (na, nb) = (a.size, b.size)
+    if na != nb:
+        raise ValueError("The size of the input array should match!"
+                         f" ({na} <> {nb})")
+    return (a, b, na)
+
+
+def _ttest_finish(df, t, alternative):
+    """Common code between all 3 t-test functions."""
+    # We use ``stdtr`` directly here to preserve masked arrays
+
+    if alternative == 'less':
+        pval = special._ufuncs.stdtr(df, t)
+    elif alternative == 'greater':
+        pval = special._ufuncs.stdtr(df, -t)
+    elif alternative == 'two-sided':
+        pval = special._ufuncs.stdtr(df, -np.abs(t))*2
+    else:
+        raise ValueError("alternative must be "
+                         "'less', 'greater' or 'two-sided'")
+
+    if t.ndim == 0:
+        t = t[()]
+    if pval.ndim == 0:
+        pval = pval[()]
+
+    return t, pval
+
+
+def argstoarray(*args):
+    """
+    Constructs a 2D array from a group of sequences.
+
+    Sequences are filled with missing values to match the length of the longest
+    sequence.
+
+    Parameters
+    ----------
+    *args : sequences
+        Group of sequences.
+
+    Returns
+    -------
+    argstoarray : MaskedArray
+        A ( `m` x `n` ) masked array, where `m` is the number of arguments and
+        `n` the length of the longest argument.
+
+    Notes
+    -----
+    `numpy.ma.vstack` has identical behavior, but is called with a sequence
+    of sequences.
+
+    Examples
+    --------
+    A 2D masked array constructed from a group of sequences is returned.
+
+    >>> from scipy.stats.mstats import argstoarray
+    >>> argstoarray([1, 2, 3], [4, 5, 6])
+    masked_array(
+     data=[[1.0, 2.0, 3.0],
+           [4.0, 5.0, 6.0]],
+     mask=[[False, False, False],
+           [False, False, False]],
+     fill_value=1e+20)
+
+    The returned masked array filled with missing values when the lengths of
+    sequences are different.
+
+    >>> argstoarray([1, 3], [4, 5, 6])
+    masked_array(
+     data=[[1.0, 3.0, --],
+           [4.0, 5.0, 6.0]],
+     mask=[[False, False,  True],
+           [False, False, False]],
+     fill_value=1e+20)
+
+    """
+    if len(args) == 1 and not isinstance(args[0], ndarray):
+        output = ma.asarray(args[0])
+        if output.ndim != 2:
+            raise ValueError("The input should be 2D")
+    else:
+        n = len(args)
+        m = max([len(k) for k in args])
+        output = ma.array(np.empty((n,m), dtype=float), mask=True)
+        for (k,v) in enumerate(args):
+            output[k,:len(v)] = v
+
+    output[np.logical_not(np.isfinite(output._data))] = masked
+    return output
+
+
+def find_repeats(arr):
+    """Find repeats in arr and return a tuple (repeats, repeat_count).
+
+    The input is cast to float64. Masked values are discarded.
+
+    Parameters
+    ----------
+    arr : sequence
+        Input array. The array is flattened if it is not 1D.
+
+    Returns
+    -------
+    repeats : ndarray
+        Array of repeated values.
+    counts : ndarray
+        Array of counts.
+
+    Examples
+    --------
+    >>> from scipy.stats import mstats
+    >>> mstats.find_repeats([2, 1, 2, 3, 2, 2, 5])
+    (array([2.]), array([4]))
+
+    In the above example, 2 repeats 4 times.
+
+    >>> mstats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
+    (array([4., 5.]), array([2, 2]))
+
+    In the above example, both 4 and 5 repeat 2 times.
+
+    """
+    # Make sure we get a copy. ma.compressed promises a "new array", but can
+    # actually return a reference.
+    compr = np.asarray(ma.compressed(arr), dtype=np.float64)
+    try:
+        need_copy = np.may_share_memory(compr, arr)
+    except AttributeError:
+        # numpy < 1.8.2 bug: np.may_share_memory([], []) raises,
+        # while in numpy 1.8.2 and above it just (correctly) returns False.
+        need_copy = False
+    if need_copy:
+        compr = compr.copy()
+    return _find_repeats(compr)
+
+
+def count_tied_groups(x, use_missing=False):
+    """
+    Counts the number of tied values.
+
+    Parameters
+    ----------
+    x : sequence
+        Sequence of data on which to counts the ties
+    use_missing : bool, optional
+        Whether to consider missing values as tied.
+
+    Returns
+    -------
+    count_tied_groups : dict
+        Returns a dictionary (nb of ties: nb of groups).
+
+    Examples
+    --------
+    >>> from scipy.stats import mstats
+    >>> import numpy as np
+    >>> z = [0, 0, 0, 2, 2, 2, 3, 3, 4, 5, 6]
+    >>> mstats.count_tied_groups(z)
+    {2: 1, 3: 2}
+
+    In the above example, the ties were 0 (3x), 2 (3x) and 3 (2x).
+
+    >>> z = np.ma.array([0, 0, 1, 2, 2, 2, 3, 3, 4, 5, 6])
+    >>> mstats.count_tied_groups(z)
+    {2: 2, 3: 1}
+    >>> z[[1,-1]] = np.ma.masked
+    >>> mstats.count_tied_groups(z, use_missing=True)
+    {2: 2, 3: 1}
+
+    """
+    nmasked = ma.getmask(x).sum()
+    # We need the copy as find_repeats will overwrite the initial data
+    data = ma.compressed(x).copy()
+    (ties, counts) = find_repeats(data)
+    nties = {}
+    if len(ties):
+        nties = dict(zip(np.unique(counts), itertools.repeat(1)))
+        nties.update(dict(zip(*find_repeats(counts))))
+
+    if nmasked and use_missing:
+        try:
+            nties[nmasked] += 1
+        except KeyError:
+            nties[nmasked] = 1
+
+    return nties
+
+
+def rankdata(data, axis=None, use_missing=False):
+    """Returns the rank (also known as order statistics) of each data point
+    along the given axis.
+
+    If some values are tied, their rank is averaged.
+    If some values are masked, their rank is set to 0 if use_missing is False,
+    or set to the average rank of the unmasked values if use_missing is True.
+
+    Parameters
+    ----------
+    data : sequence
+        Input data. The data is transformed to a masked array
+    axis : {None,int}, optional
+        Axis along which to perform the ranking.
+        If None, the array is first flattened. An exception is raised if
+        the axis is specified for arrays with a dimension larger than 2
+    use_missing : bool, optional
+        Whether the masked values have a rank of 0 (False) or equal to the
+        average rank of the unmasked values (True).
+
+    """
+    def _rank1d(data, use_missing=False):
+        n = data.count()
+        rk = np.empty(data.size, dtype=float)
+        idx = data.argsort()
+        rk[idx[:n]] = np.arange(1,n+1)
+
+        if use_missing:
+            rk[idx[n:]] = (n+1)/2.
+        else:
+            rk[idx[n:]] = 0
+
+        repeats = find_repeats(data.copy())
+        for r in repeats[0]:
+            condition = (data == r).filled(False)
+            rk[condition] = rk[condition].mean()
+        return rk
+
+    data = ma.array(data, copy=False)
+    if axis is None:
+        if data.ndim > 1:
+            return _rank1d(data.ravel(), use_missing).reshape(data.shape)
+        else:
+            return _rank1d(data, use_missing)
+    else:
+        return ma.apply_along_axis(_rank1d,axis,data,use_missing).view(ndarray)
+
+
+ModeResult = namedtuple('ModeResult', ('mode', 'count'))
+
+
+def mode(a, axis=0):
+    """
+    Returns an array of the modal (most common) value in the passed array.
+
+    Parameters
+    ----------
+    a : array_like
+        n-dimensional array of which to find mode(s).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    mode : ndarray
+        Array of modal values.
+    count : ndarray
+        Array of counts for each mode.
+
+    Notes
+    -----
+    For more details, see `scipy.stats.mode`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> from scipy.stats import mstats
+    >>> m_arr = np.ma.array([1, 1, 0, 0, 0, 0], mask=[0, 0, 1, 1, 1, 0])
+    >>> mstats.mode(m_arr)  # note that most zeros are masked
+    ModeResult(mode=array([1.]), count=array([2.]))
+
+    """
+    return _mode(a, axis=axis, keepdims=True)
+
+
+def _mode(a, axis=0, keepdims=True):
+    # Don't want to expose `keepdims` from the public `mstats.mode`
+    a, axis = _chk_asarray(a, axis)
+
+    def _mode1D(a):
+        (rep,cnt) = find_repeats(a)
+        if not cnt.ndim:
+            return (0, 0)
+        elif cnt.size:
+            return (rep[cnt.argmax()], cnt.max())
+        else:
+            return (a.min(), 1)
+
+    if axis is None:
+        output = _mode1D(ma.ravel(a))
+        output = (ma.array(output[0]), ma.array(output[1]))
+    else:
+        output = ma.apply_along_axis(_mode1D, axis, a)
+        if keepdims is None or keepdims:
+            newshape = list(a.shape)
+            newshape[axis] = 1
+            slices = [slice(None)] * output.ndim
+            slices[axis] = 0
+            modes = output[tuple(slices)].reshape(newshape)
+            slices[axis] = 1
+            counts = output[tuple(slices)].reshape(newshape)
+            output = (modes, counts)
+        else:
+            output = np.moveaxis(output, axis, 0)
+
+    return ModeResult(*output)
+
+
+def _betai(a, b, x):
+    x = np.asanyarray(x)
+    x = ma.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
+    return special.betainc(a, b, x)
+
+
+def msign(x):
+    """Returns the sign of x, or 0 if x is masked."""
+    return ma.filled(np.sign(x), 0)
+
+
+def pearsonr(x, y):
+    r"""
+    Pearson correlation coefficient and p-value for testing non-correlation.
+
+    The Pearson correlation coefficient [1]_ measures the linear relationship
+    between two datasets.  The calculation of the p-value relies on the
+    assumption that each dataset is normally distributed.  (See Kowalski [3]_
+    for a discussion of the effects of non-normality of the input on the
+    distribution of the correlation coefficient.)  Like other correlation
+    coefficients, this one varies between -1 and +1 with 0 implying no
+    correlation. Correlations of -1 or +1 imply an exact linear relationship.
+
+    Parameters
+    ----------
+    x : (N,) array_like
+        Input array.
+    y : (N,) array_like
+        Input array.
+
+    Returns
+    -------
+    r : float
+        Pearson's correlation coefficient.
+    p-value : float
+        Two-tailed p-value.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Raised if an input is a constant array.  The correlation coefficient
+        is not defined in this case, so ``np.nan`` is returned.
+
+    `~scipy.stats.NearConstantInputWarning`
+        Raised if an input is "nearly" constant.  The array ``x`` is considered
+        nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``.
+        Numerical errors in the calculation ``x - mean(x)`` in this case might
+        result in an inaccurate calculation of r.
+
+    See Also
+    --------
+    spearmanr : Spearman rank-order correlation coefficient.
+    kendalltau : Kendall's tau, a correlation measure for ordinal data.
+
+    Notes
+    -----
+    The correlation coefficient is calculated as follows:
+
+    .. math::
+
+        r = \frac{\sum (x - m_x) (y - m_y)}
+                 {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}}
+
+    where :math:`m_x` is the mean of the vector x and :math:`m_y` is
+    the mean of the vector y.
+
+    Under the assumption that x and y are drawn from
+    independent normal distributions (so the population correlation coefficient
+    is 0), the probability density function of the sample correlation
+    coefficient r is ([1]_, [2]_):
+
+    .. math::
+
+        f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)}
+
+    where n is the number of samples, and B is the beta function.  This
+    is sometimes referred to as the exact distribution of r.  This is
+    the distribution that is used in `pearsonr` to compute the p-value.
+    The distribution is a beta distribution on the interval [-1, 1],
+    with equal shape parameters a = b = n/2 - 1.  In terms of SciPy's
+    implementation of the beta distribution, the distribution of r is::
+
+        dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)
+
+    The p-value returned by `pearsonr` is a two-sided p-value. The p-value
+    roughly indicates the probability of an uncorrelated system
+    producing datasets that have a Pearson correlation at least as extreme
+    as the one computed from these datasets. More precisely, for a
+    given sample with correlation coefficient r, the p-value is
+    the probability that abs(r') of a random sample x' and y' drawn from
+    the population with zero correlation would be greater than or equal
+    to abs(r). In terms of the object ``dist`` shown above, the p-value
+    for a given r and length n can be computed as::
+
+        p = 2*dist.cdf(-abs(r))
+
+    When n is 2, the above continuous distribution is not well-defined.
+    One can interpret the limit of the beta distribution as the shape
+    parameters a and b approach a = b = 0 as a discrete distribution with
+    equal probability masses at r = 1 and r = -1.  More directly, one
+    can observe that, given the data x = [x1, x2] and y = [y1, y2], and
+    assuming x1 != x2 and y1 != y2, the only possible values for r are 1
+    and -1.  Because abs(r') for any sample x' and y' with length 2 will
+    be 1, the two-sided p-value for a sample of length 2 is always 1.
+
+    References
+    ----------
+    .. [1] "Pearson correlation coefficient", Wikipedia,
+           https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
+    .. [2] Student, "Probable error of a correlation coefficient",
+           Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310.
+    .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution
+           of the Sample Product-Moment Correlation Coefficient"
+           Journal of the Royal Statistical Society. Series C (Applied
+           Statistics), Vol. 21, No. 1 (1972), pp. 1-12.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> from scipy.stats import mstats
+    >>> mstats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4])
+    (-0.7426106572325057, 0.1505558088534455)
+
+    There is a linear dependence between x and y if y = a + b*x + e, where
+    a,b are constants and e is a random error term, assumed to be independent
+    of x. For simplicity, assume that x is standard normal, a=0, b=1 and let
+    e follow a normal distribution with mean zero and standard deviation s>0.
+
+    >>> s = 0.5
+    >>> x = stats.norm.rvs(size=500)
+    >>> e = stats.norm.rvs(scale=s, size=500)
+    >>> y = x + e
+    >>> mstats.pearsonr(x, y)
+    (0.9029601878969703, 8.428978827629898e-185) # may vary
+
+    This should be close to the exact value given by
+
+    >>> 1/np.sqrt(1 + s**2)
+    0.8944271909999159
+
+    For s=0.5, we observe a high level of correlation. In general, a large
+    variance of the noise reduces the correlation, while the correlation
+    approaches one as the variance of the error goes to zero.
+
+    It is important to keep in mind that no correlation does not imply
+    independence unless (x, y) is jointly normal. Correlation can even be zero
+    when there is a very simple dependence structure: if X follows a
+    standard normal distribution, let y = abs(x). Note that the correlation
+    between x and y is zero. Indeed, since the expectation of x is zero,
+    cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero
+    by symmetry. The following lines of code illustrate this observation:
+
+    >>> y = np.abs(x)
+    >>> mstats.pearsonr(x, y)
+    (-0.016172891856853524, 0.7182823678751942) # may vary
+
+    A non-zero correlation coefficient can be misleading. For example, if X has
+    a standard normal distribution, define y = x if x < 0 and y = 0 otherwise.
+    A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797...,
+    implying a high level of correlation:
+
+    >>> y = np.where(x < 0, x, 0)
+    >>> mstats.pearsonr(x, y)
+    (0.8537091583771509, 3.183461621422181e-143) # may vary
+
+    This is unintuitive since there is no dependence of x and y if x is larger
+    than zero which happens in about half of the cases if we sample x and y.
+    """
+    (x, y, n) = _chk_size(x, y)
+    (x, y) = (x.ravel(), y.ravel())
+    # Get the common mask and the total nb of unmasked elements
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    n -= m.sum()
+    df = n-2
+    if df < 0:
+        return (masked, masked)
+
+    return scipy.stats._stats_py.pearsonr(
+                ma.masked_array(x, mask=m).compressed(),
+                ma.masked_array(y, mask=m).compressed())
+
+
+def spearmanr(x, y=None, use_ties=True, axis=None, nan_policy='propagate',
+              alternative='two-sided'):
+    """
+    Calculates a Spearman rank-order correlation coefficient and the p-value
+    to test for non-correlation.
+
+    The Spearman correlation is a nonparametric measure of the linear
+    relationship between two datasets. Unlike the Pearson correlation, the
+    Spearman correlation does not assume that both datasets are normally
+    distributed. Like other correlation coefficients, this one varies
+    between -1 and +1 with 0 implying no correlation. Correlations of -1 or
+    +1 imply a monotonic relationship. Positive correlations imply that
+    as `x` increases, so does `y`. Negative correlations imply that as `x`
+    increases, `y` decreases.
+
+    Missing values are discarded pair-wise: if a value is missing in `x`, the
+    corresponding value in `y` is masked.
+
+    The p-value roughly indicates the probability of an uncorrelated system
+    producing datasets that have a Spearman correlation at least as extreme
+    as the one computed from these datasets. The p-values are not entirely
+    reliable but are probably reasonable for datasets larger than 500 or so.
+
+    Parameters
+    ----------
+    x, y : 1D or 2D array_like, y is optional
+        One or two 1-D or 2-D arrays containing multiple variables and
+        observations. When these are 1-D, each represents a vector of
+        observations of a single variable. For the behavior in the 2-D case,
+        see under ``axis``, below.
+    use_ties : bool, optional
+        DO NOT USE.  Does not do anything, keyword is only left in place for
+        backwards compatibility reasons.
+    axis : int or None, optional
+        If axis=0 (default), then each column represents a variable, with
+        observations in the rows. If axis=1, the relationship is transposed:
+        each row represents a variable, while the columns contain observations.
+        If axis=None, then both arrays will be raveled.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the correlation is nonzero
+        * 'less': the correlation is negative (less than zero)
+        * 'greater':  the correlation is positive (greater than zero)
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float or ndarray (2-D square)
+            Spearman correlation matrix or correlation coefficient (if only 2
+            variables are given as parameters). Correlation matrix is square
+            with length equal to total number of variables (columns or rows) in
+            ``a`` and ``b`` combined.
+        pvalue : float
+            The p-value for a hypothesis test whose null hypothesis
+            is that two sets of data are linearly uncorrelated. See
+            `alternative` above for alternative hypotheses. `pvalue` has the
+            same shape as `statistic`.
+
+    References
+    ----------
+    [CRCProbStat2000] section 14.7
+
+    """
+    if not use_ties:
+        raise ValueError("`use_ties=False` is not supported in SciPy >= 1.2.0")
+
+    # Always returns a masked array, raveled if axis=None
+    x, axisout = _chk_asarray(x, axis)
+    if y is not None:
+        # Deal only with 2-D `x` case.
+        y, _ = _chk_asarray(y, axis)
+        if axisout == 0:
+            x = ma.column_stack((x, y))
+        else:
+            x = ma.vstack((x, y))
+
+    if axisout == 1:
+        # To simplify the code that follow (always use `n_obs, n_vars` shape)
+        x = x.T
+
+    if nan_policy == 'omit':
+        x = ma.masked_invalid(x)
+
+    def _spearmanr_2cols(x):
+        # Mask the same observations for all variables, and then drop those
+        # observations (can't leave them masked, rankdata is weird).
+        x = ma.mask_rowcols(x, axis=0)
+        x = x[~x.mask.any(axis=1), :]
+
+        # If either column is entirely NaN or Inf
+        if not np.any(x.data):
+            res = scipy.stats._stats_py.SignificanceResult(np.nan, np.nan)
+            res.correlation = np.nan
+            return res
+
+        m = ma.getmask(x)
+        n_obs = x.shape[0]
+        dof = n_obs - 2 - int(m.sum(axis=0)[0])
+        if dof < 0:
+            raise ValueError("The input must have at least 3 entries!")
+
+        # Gets the ranks and rank differences
+        x_ranked = rankdata(x, axis=0)
+        rs = ma.corrcoef(x_ranked, rowvar=False).data
+
+        # rs can have elements equal to 1, so avoid zero division warnings
+        with np.errstate(divide='ignore'):
+            # clip the small negative values possibly caused by rounding
+            # errors before taking the square root
+            t = rs * np.sqrt((dof / ((rs+1.0) * (1.0-rs))).clip(0))
+
+        t, prob = _ttest_finish(dof, t, alternative)
+
+        # For backwards compatibility, return scalars when comparing 2 columns
+        if rs.shape == (2, 2):
+            res = scipy.stats._stats_py.SignificanceResult(rs[1, 0],
+                                                           prob[1, 0])
+            res.correlation = rs[1, 0]
+            return res
+        else:
+            res = scipy.stats._stats_py.SignificanceResult(rs, prob)
+            res.correlation = rs
+            return res
+
+    # Need to do this per pair of variables, otherwise the dropped observations
+    # in a third column mess up the result for a pair.
+    n_vars = x.shape[1]
+    if n_vars == 2:
+        return _spearmanr_2cols(x)
+    else:
+        rs = np.ones((n_vars, n_vars), dtype=float)
+        prob = np.zeros((n_vars, n_vars), dtype=float)
+        for var1 in range(n_vars - 1):
+            for var2 in range(var1+1, n_vars):
+                result = _spearmanr_2cols(x[:, [var1, var2]])
+                rs[var1, var2] = result.correlation
+                rs[var2, var1] = result.correlation
+                prob[var1, var2] = result.pvalue
+                prob[var2, var1] = result.pvalue
+
+        res = scipy.stats._stats_py.SignificanceResult(rs, prob)
+        res.correlation = rs
+        return res
+
+
+def _kendall_p_exact(n, c, alternative='two-sided'):
+
+    # Use the fact that distribution is symmetric: always calculate a CDF in
+    # the left tail.
+    # This will be the one-sided p-value if `c` is on the side of
+    # the null distribution predicted by the alternative hypothesis.
+    # The two-sided p-value will be twice this value.
+    # If `c` is on the other side of the null distribution, we'll need to
+    # take the complement and add back the probability mass at `c`.
+    in_right_tail = (c >= (n*(n-1))//2 - c)
+    alternative_greater = (alternative == 'greater')
+    c = int(min(c, (n*(n-1))//2 - c))
+
+    # Exact p-value, see Maurice G. Kendall, "Rank Correlation Methods"
+    # (4th Edition), Charles Griffin & Co., 1970.
+    if n <= 0:
+        raise ValueError(f'n ({n}) must be positive')
+    elif c < 0 or 4*c > n*(n-1):
+        raise ValueError(f'c ({c}) must satisfy 0 <= 4c <= n(n-1) = {n*(n-1)}.')
+    elif n == 1:
+        prob = 1.0
+        p_mass_at_c = 1
+    elif n == 2:
+        prob = 1.0
+        p_mass_at_c = 0.5
+    elif c == 0:
+        prob = 2.0/math.factorial(n) if n < 171 else 0.0
+        p_mass_at_c = prob/2
+    elif c == 1:
+        prob = 2.0/math.factorial(n-1) if n < 172 else 0.0
+        p_mass_at_c = (n-1)/math.factorial(n)
+    elif 4*c == n*(n-1) and alternative == 'two-sided':
+        # I'm sure there's a simple formula for p_mass_at_c in this
+        # case, but I don't know it. Use generic formula for one-sided p-value.
+        prob = 1.0
+    elif n < 171:
+        new = np.zeros(c+1)
+        new[0:2] = 1.0
+        for j in range(3,n+1):
+            new = np.cumsum(new)
+            if j <= c:
+                new[j:] -= new[:c+1-j]
+        prob = 2.0*np.sum(new)/math.factorial(n)
+        p_mass_at_c = new[-1]/math.factorial(n)
+    else:
+        new = np.zeros(c+1)
+        new[0:2] = 1.0
+        for j in range(3, n+1):
+            new = np.cumsum(new)/j
+            if j <= c:
+                new[j:] -= new[:c+1-j]
+        prob = np.sum(new)
+        p_mass_at_c = new[-1]/2
+
+    if alternative != 'two-sided':
+        # if the alternative hypothesis and alternative agree,
+        # one-sided p-value is half the two-sided p-value
+        if in_right_tail == alternative_greater:
+            prob /= 2
+        else:
+            prob = 1 - prob/2 + p_mass_at_c
+
+    prob = np.clip(prob, 0, 1)
+
+    return prob
+
+
+def kendalltau(x, y, use_ties=True, use_missing=False, method='auto',
+               alternative='two-sided'):
+    """
+    Computes Kendall's rank correlation tau on two variables *x* and *y*.
+
+    Parameters
+    ----------
+    x : sequence
+        First data list (for example, time).
+    y : sequence
+        Second data list.
+    use_ties : {True, False}, optional
+        Whether ties correction should be performed.
+    use_missing : {False, True}, optional
+        Whether missing data should be allocated a rank of 0 (False) or the
+        average rank (True)
+    method : {'auto', 'asymptotic', 'exact'}, optional
+        Defines which method is used to calculate the p-value [1]_.
+        'asymptotic' uses a normal approximation valid for large samples.
+        'exact' computes the exact p-value, but can only be used if no ties
+        are present. As the sample size increases, the 'exact' computation
+        time may grow and the result may lose some precision.
+        'auto' is the default and selects the appropriate
+        method based on a trade-off between speed and accuracy.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the rank correlation is nonzero
+        * 'less': the rank correlation is negative (less than zero)
+        * 'greater':  the rank correlation is positive (greater than zero)
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+           The tau statistic.
+        pvalue : float
+           The p-value for a hypothesis test whose null hypothesis is
+           an absence of association, tau = 0.
+
+    References
+    ----------
+    .. [1] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
+           Charles Griffin & Co., 1970.
+
+    """
+    (x, y, n) = _chk_size(x, y)
+    (x, y) = (x.flatten(), y.flatten())
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    if m is not nomask:
+        x = ma.array(x, mask=m, copy=True)
+        y = ma.array(y, mask=m, copy=True)
+        # need int() here, otherwise numpy defaults to 32 bit
+        # integer on all Windows architectures, causing overflow.
+        # int() will keep it infinite precision.
+        n -= int(m.sum())
+
+    if n < 2:
+        res = scipy.stats._stats_py.SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    rx = ma.masked_equal(rankdata(x, use_missing=use_missing), 0)
+    ry = ma.masked_equal(rankdata(y, use_missing=use_missing), 0)
+    idx = rx.argsort()
+    (rx, ry) = (rx[idx], ry[idx])
+    C = np.sum([((ry[i+1:] > ry[i]) * (rx[i+1:] > rx[i])).filled(0).sum()
+                for i in range(len(ry)-1)], dtype=float)
+    D = np.sum([((ry[i+1:] < ry[i])*(rx[i+1:] > rx[i])).filled(0).sum()
+                for i in range(len(ry)-1)], dtype=float)
+    xties = count_tied_groups(x)
+    yties = count_tied_groups(y)
+    if use_ties:
+        corr_x = np.sum([v*k*(k-1) for (k,v) in xties.items()], dtype=float)
+        corr_y = np.sum([v*k*(k-1) for (k,v) in yties.items()], dtype=float)
+        denom = ma.sqrt((n*(n-1)-corr_x)/2. * (n*(n-1)-corr_y)/2.)
+    else:
+        denom = n*(n-1)/2.
+    tau = (C-D) / denom
+
+    if method == 'exact' and (xties or yties):
+        raise ValueError("Ties found, exact method cannot be used.")
+
+    if method == 'auto':
+        if (not xties and not yties) and (n <= 33 or min(C, n*(n-1)/2.0-C) <= 1):
+            method = 'exact'
+        else:
+            method = 'asymptotic'
+
+    if not xties and not yties and method == 'exact':
+        prob = _kendall_p_exact(n, C, alternative)
+
+    elif method == 'asymptotic':
+        var_s = n*(n-1)*(2*n+5)
+        if use_ties:
+            var_s -= np.sum([v*k*(k-1)*(2*k+5)*1. for (k,v) in xties.items()])
+            var_s -= np.sum([v*k*(k-1)*(2*k+5)*1. for (k,v) in yties.items()])
+            v1 = (np.sum([v*k*(k-1) for (k, v) in xties.items()], dtype=float) *
+                  np.sum([v*k*(k-1) for (k, v) in yties.items()], dtype=float))
+            v1 /= 2.*n*(n-1)
+            if n > 2:
+                v2 = np.sum([v*k*(k-1)*(k-2) for (k,v) in xties.items()],
+                            dtype=float) * \
+                     np.sum([v*k*(k-1)*(k-2) for (k,v) in yties.items()],
+                            dtype=float)
+                v2 /= 9.*n*(n-1)*(n-2)
+            else:
+                v2 = 0
+        else:
+            v1 = v2 = 0
+
+        var_s /= 18.
+        var_s += (v1 + v2)
+        z = (C-D)/np.sqrt(var_s)
+        prob = scipy.stats._stats_py._get_pvalue(z, distributions.norm, alternative)
+    else:
+        raise ValueError("Unknown method "+str(method)+" specified, please "
+                         "use auto, exact or asymptotic.")
+
+    res = scipy.stats._stats_py.SignificanceResult(tau[()], prob[()])
+    res.correlation = tau
+    return res
+
+
+def kendalltau_seasonal(x):
+    """
+    Computes a multivariate Kendall's rank correlation tau, for seasonal data.
+
+    Parameters
+    ----------
+    x : 2-D ndarray
+        Array of seasonal data, with seasons in columns.
+
+    """
+    x = ma.array(x, subok=True, copy=False, ndmin=2)
+    (n,m) = x.shape
+    n_p = x.count(0)
+
+    S_szn = sum(msign(x[i:]-x[i]).sum(0) for i in range(n))
+    S_tot = S_szn.sum()
+
+    n_tot = x.count()
+    ties = count_tied_groups(x.compressed())
+    corr_ties = sum(v*k*(k-1) for (k,v) in ties.items())
+    denom_tot = ma.sqrt(1.*n_tot*(n_tot-1)*(n_tot*(n_tot-1)-corr_ties))/2.
+
+    R = rankdata(x, axis=0, use_missing=True)
+    K = ma.empty((m,m), dtype=int)
+    covmat = ma.empty((m,m), dtype=float)
+    denom_szn = ma.empty(m, dtype=float)
+    for j in range(m):
+        ties_j = count_tied_groups(x[:,j].compressed())
+        corr_j = sum(v*k*(k-1) for (k,v) in ties_j.items())
+        cmb = n_p[j]*(n_p[j]-1)
+        for k in range(j,m,1):
+            K[j,k] = sum(msign((x[i:,j]-x[i,j])*(x[i:,k]-x[i,k])).sum()
+                         for i in range(n))
+            covmat[j,k] = (K[j,k] + 4*(R[:,j]*R[:,k]).sum() -
+                           n*(n_p[j]+1)*(n_p[k]+1))/3.
+            K[k,j] = K[j,k]
+            covmat[k,j] = covmat[j,k]
+
+        denom_szn[j] = ma.sqrt(cmb*(cmb-corr_j)) / 2.
+
+    var_szn = covmat.diagonal()
+
+    z_szn = msign(S_szn) * (abs(S_szn)-1) / ma.sqrt(var_szn)
+    z_tot_ind = msign(S_tot) * (abs(S_tot)-1) / ma.sqrt(var_szn.sum())
+    z_tot_dep = msign(S_tot) * (abs(S_tot)-1) / ma.sqrt(covmat.sum())
+
+    prob_szn = special.erfc(abs(z_szn.data)/np.sqrt(2))
+    prob_tot_ind = special.erfc(abs(z_tot_ind)/np.sqrt(2))
+    prob_tot_dep = special.erfc(abs(z_tot_dep)/np.sqrt(2))
+
+    chi2_tot = (z_szn*z_szn).sum()
+    chi2_trd = m * z_szn.mean()**2
+    output = {'seasonal tau': S_szn/denom_szn,
+              'global tau': S_tot/denom_tot,
+              'global tau (alt)': S_tot/denom_szn.sum(),
+              'seasonal p-value': prob_szn,
+              'global p-value (indep)': prob_tot_ind,
+              'global p-value (dep)': prob_tot_dep,
+              'chi2 total': chi2_tot,
+              'chi2 trend': chi2_trd,
+              }
+    return output
+
+
+PointbiserialrResult = namedtuple('PointbiserialrResult', ('correlation',
+                                                           'pvalue'))
+
+
+def pointbiserialr(x, y):
+    """Calculates a point biserial correlation coefficient and its p-value.
+
+    Parameters
+    ----------
+    x : array_like of bools
+        Input array.
+    y : array_like
+        Input array.
+
+    Returns
+    -------
+    correlation : float
+        R value
+    pvalue : float
+        2-tailed p-value
+
+    Notes
+    -----
+    Missing values are considered pair-wise: if a value is missing in x,
+    the corresponding value in y is masked.
+
+    For more details on `pointbiserialr`, see `scipy.stats.pointbiserialr`.
+
+    """
+    x = ma.fix_invalid(x, copy=True).astype(bool)
+    y = ma.fix_invalid(y, copy=True).astype(float)
+    # Get rid of the missing data
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    if m is not nomask:
+        unmask = np.logical_not(m)
+        x = x[unmask]
+        y = y[unmask]
+
+    n = len(x)
+    # phat is the fraction of x values that are True
+    phat = x.sum() / float(n)
+    y0 = y[~x]  # y-values where x is False
+    y1 = y[x]  # y-values where x is True
+    y0m = y0.mean()
+    y1m = y1.mean()
+
+    rpb = (y1m - y0m)*np.sqrt(phat * (1-phat)) / y.std()
+
+    df = n-2
+    t = rpb*ma.sqrt(df/(1.0-rpb**2))
+    prob = _betai(0.5*df, 0.5, df/(df+t*t))
+
+    return PointbiserialrResult(rpb, prob)
+
+
+def linregress(x, y=None):
+    r"""
+    Calculate a linear least-squares regression for two sets of measurements.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Two sets of measurements.  Both arrays should have the same length N.  If
+        only `x` is given (and ``y=None``), then it must be a two-dimensional
+        array where one dimension has length 2.  The two sets of measurements
+        are then found by splitting the array along the length-2 dimension. In
+        the case where ``y=None`` and `x` is a 2xN array, ``linregress(x)`` is
+        equivalent to ``linregress(x[0], x[1])``.
+
+    Returns
+    -------
+    result : ``LinregressResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Slope of the regression line.
+        intercept : float
+            Intercept of the regression line.
+        rvalue : float
+            The Pearson correlation coefficient. The square of ``rvalue``
+            is equal to the coefficient of determination.
+        pvalue : float
+            The p-value for a hypothesis test whose null hypothesis is
+            that the slope is zero, using Wald Test with t-distribution of
+            the test statistic. See `alternative` above for alternative
+            hypotheses.
+        stderr : float
+            Standard error of the estimated slope (gradient), under the
+            assumption of residual normality.
+        intercept_stderr : float
+            Standard error of the estimated intercept, under the assumption
+            of residual normality.
+
+    See Also
+    --------
+    scipy.optimize.curve_fit :
+        Use non-linear least squares to fit a function to data.
+    scipy.optimize.leastsq :
+        Minimize the sum of squares of a set of equations.
+
+    Notes
+    -----
+    Missing values are considered pair-wise: if a value is missing in `x`,
+    the corresponding value in `y` is masked.
+
+    For compatibility with older versions of SciPy, the return value acts
+    like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``,
+    ``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write::
+
+        slope, intercept, r, p, se = linregress(x, y)
+
+    With that style, however, the standard error of the intercept is not
+    available.  To have access to all the computed values, including the
+    standard error of the intercept, use the return value as an object
+    with attributes, e.g.::
+
+        result = linregress(x, y)
+        print(result.intercept, result.intercept_stderr)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+
+    Generate some data:
+
+    >>> x = rng.random(10)
+    >>> y = 1.6*x + rng.random(10)
+
+    Perform the linear regression:
+
+    >>> res = stats.mstats.linregress(x, y)
+
+    Coefficient of determination (R-squared):
+
+    >>> print(f"R-squared: {res.rvalue**2:.6f}")
+    R-squared: 0.717533
+
+    Plot the data along with the fitted line:
+
+    >>> plt.plot(x, y, 'o', label='original data')
+    >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line')
+    >>> plt.legend()
+    >>> plt.show()
+
+    Calculate 95% confidence interval on slope and intercept:
+
+    >>> # Two-sided inverse Students t-distribution
+    >>> # p - probability, df - degrees of freedom
+    >>> from scipy.stats import t
+    >>> tinv = lambda p, df: abs(t.ppf(p/2, df))
+
+    >>> ts = tinv(0.05, len(x)-2)
+    >>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}")
+    slope (95%): 1.453392 +/- 0.743465
+    >>> print(f"intercept (95%): {res.intercept:.6f}"
+    ...       f" +/- {ts*res.intercept_stderr:.6f}")
+    intercept (95%): 0.616950 +/- 0.544475
+
+    """
+    if y is None:
+        x = ma.array(x)
+        if x.shape[0] == 2:
+            x, y = x
+        elif x.shape[1] == 2:
+            x, y = x.T
+        else:
+            raise ValueError("If only `x` is given as input, "
+                             "it has to be of shape (2, N) or (N, 2), "
+                             f"provided shape was {x.shape}")
+    else:
+        x = ma.array(x)
+        y = ma.array(y)
+
+    x = x.flatten()
+    y = y.flatten()
+
+    if np.amax(x) == np.amin(x) and len(x) > 1:
+        raise ValueError("Cannot calculate a linear regression "
+                         "if all x values are identical")
+
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y), shrink=False)
+    if m is not nomask:
+        x = ma.array(x, mask=m)
+        y = ma.array(y, mask=m)
+        if np.any(~m):
+            result = _stats_py.linregress(x.data[~m], y.data[~m])
+        else:
+            # All data is masked
+            result = _stats_py.LinregressResult(slope=None, intercept=None,
+                                                rvalue=None, pvalue=None,
+                                                stderr=None,
+                                                intercept_stderr=None)
+    else:
+        result = _stats_py.linregress(x.data, y.data)
+
+    return result
+
+
+def theilslopes(y, x=None, alpha=0.95, method='separate'):
+    r"""
+    Computes the Theil-Sen estimator for a set of points (x, y).
+
+    `theilslopes` implements a method for robust linear regression.  It
+    computes the slope as the median of all slopes between paired values.
+
+    Parameters
+    ----------
+    y : array_like
+        Dependent variable.
+    x : array_like or None, optional
+        Independent variable. If None, use ``arange(len(y))`` instead.
+    alpha : float, optional
+        Confidence degree between 0 and 1. Default is 95% confidence.
+        Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are
+        interpreted as "find the 90% confidence interval".
+    method : {'joint', 'separate'}, optional
+        Method to be used for computing estimate for intercept.
+        Following methods are supported,
+
+            * 'joint': Uses np.median(y - slope * x) as intercept.
+            * 'separate': Uses np.median(y) - slope * np.median(x)
+                          as intercept.
+
+        The default is 'separate'.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    result : ``TheilslopesResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Theil slope.
+        intercept : float
+            Intercept of the Theil line.
+        low_slope : float
+            Lower bound of the confidence interval on `slope`.
+        high_slope : float
+            Upper bound of the confidence interval on `slope`.
+
+    See Also
+    --------
+    siegelslopes : a similar technique using repeated medians
+
+
+    Notes
+    -----
+    For more details on `theilslopes`, see `scipy.stats.theilslopes`.
+
+    """
+    y = ma.asarray(y).flatten()
+    if x is None:
+        x = ma.arange(len(y), dtype=float)
+    else:
+        x = ma.asarray(x).flatten()
+        if len(x) != len(y):
+            raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
+
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    y._mask = x._mask = m
+    # Disregard any masked elements of x or y
+    y = y.compressed()
+    x = x.compressed().astype(float)
+    # We now have unmasked arrays so can use `scipy.stats.theilslopes`
+    return stats_theilslopes(y, x, alpha=alpha, method=method)
+
+
+def siegelslopes(y, x=None, method="hierarchical"):
+    r"""
+    Computes the Siegel estimator for a set of points (x, y).
+
+    `siegelslopes` implements a method for robust linear regression
+    using repeated medians to fit a line to the points (x, y).
+    The method is robust to outliers with an asymptotic breakdown point
+    of 50%.
+
+    Parameters
+    ----------
+    y : array_like
+        Dependent variable.
+    x : array_like or None, optional
+        Independent variable. If None, use ``arange(len(y))`` instead.
+    method : {'hierarchical', 'separate'}
+        If 'hierarchical', estimate the intercept using the estimated
+        slope ``slope`` (default option).
+        If 'separate', estimate the intercept independent of the estimated
+        slope. See Notes for details.
+
+    Returns
+    -------
+    result : ``SiegelslopesResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Estimate of the slope of the regression line.
+        intercept : float
+            Estimate of the intercept of the regression line.
+
+    See Also
+    --------
+    theilslopes : a similar technique without repeated medians
+
+    Notes
+    -----
+    For more details on `siegelslopes`, see `scipy.stats.siegelslopes`.
+
+    """
+    y = ma.asarray(y).ravel()
+    if x is None:
+        x = ma.arange(len(y), dtype=float)
+    else:
+        x = ma.asarray(x).ravel()
+        if len(x) != len(y):
+            raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
+
+    m = ma.mask_or(ma.getmask(x), ma.getmask(y))
+    y._mask = x._mask = m
+    # Disregard any masked elements of x or y
+    y = y.compressed()
+    x = x.compressed().astype(float)
+    # We now have unmasked arrays so can use `scipy.stats.siegelslopes`
+    return stats_siegelslopes(y, x, method=method)
+
+
+SenSeasonalSlopesResult = _make_tuple_bunch('SenSeasonalSlopesResult',
+                                            ['intra_slope', 'inter_slope'])
+
+
+def sen_seasonal_slopes(x):
+    r"""
+    Computes seasonal Theil-Sen and Kendall slope estimators.
+
+    The seasonal generalization of Sen's slope computes the slopes between all
+    pairs of values within a "season" (column) of a 2D array. It returns an
+    array containing the median of these "within-season" slopes for each
+    season (the Theil-Sen slope estimator of each season), and it returns the
+    median of the within-season slopes across all seasons (the seasonal Kendall
+    slope estimator).
+
+    Parameters
+    ----------
+    x : 2D array_like
+        Each column of `x` contains measurements of the dependent variable
+        within a season. The independent variable (usually time) of each season
+        is assumed to be ``np.arange(x.shape[0])``.
+
+    Returns
+    -------
+    result : ``SenSeasonalSlopesResult`` instance
+        The return value is an object with the following attributes:
+
+        intra_slope : ndarray
+            For each season, the Theil-Sen slope estimator: the median of
+            within-season slopes.
+        inter_slope : float
+            The seasonal Kendall slope estimator: the median of within-season
+            slopes *across all* seasons.
+
+    See Also
+    --------
+    theilslopes : the analogous function for non-seasonal data
+    scipy.stats.theilslopes : non-seasonal slopes for non-masked arrays
+
+    Notes
+    -----
+    The slopes :math:`d_{ijk}` within season :math:`i` are:
+
+    .. math::
+
+        d_{ijk} = \frac{x_{ij} - x_{ik}}
+                            {j - k}
+
+    for pairs of distinct integer indices :math:`j, k` of :math:`x`.
+
+    Element :math:`i` of the returned `intra_slope` array is the median of the
+    :math:`d_{ijk}` over all :math:`j < k`; this is the Theil-Sen slope
+    estimator of season :math:`i`. The returned `inter_slope` value, better
+    known as the seasonal Kendall slope estimator, is the median of the
+    :math:`d_{ijk}` over all :math:`i, j, k`.
+
+    References
+    ----------
+    .. [1] Hirsch, Robert M., James R. Slack, and Richard A. Smith.
+           "Techniques of trend analysis for monthly water quality data."
+           *Water Resources Research* 18.1 (1982): 107-121.
+
+    Examples
+    --------
+    Suppose we have 100 observations of a dependent variable for each of four
+    seasons:
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random(size=(100, 4))
+
+    We compute the seasonal slopes as:
+
+    >>> from scipy import stats
+    >>> intra_slope, inter_slope = stats.mstats.sen_seasonal_slopes(x)
+
+    If we define a function to compute all slopes between observations within
+    a season:
+
+    >>> def dijk(yi):
+    ...     n = len(yi)
+    ...     x = np.arange(n)
+    ...     dy = yi - yi[:, np.newaxis]
+    ...     dx = x - x[:, np.newaxis]
+    ...     # we only want unique pairs of distinct indices
+    ...     mask = np.triu(np.ones((n, n), dtype=bool), k=1)
+    ...     return dy[mask]/dx[mask]
+
+    then element ``i`` of ``intra_slope`` is the median of ``dijk[x[:, i]]``:
+
+    >>> i = 2
+    >>> np.allclose(np.median(dijk(x[:, i])), intra_slope[i])
+    True
+
+    and ``inter_slope`` is the median of the values returned by ``dijk`` for
+    all seasons:
+
+    >>> all_slopes = np.concatenate([dijk(x[:, i]) for i in range(x.shape[1])])
+    >>> np.allclose(np.median(all_slopes), inter_slope)
+    True
+
+    Because the data are randomly generated, we would expect the median slopes
+    to be nearly zero both within and across all seasons, and indeed they are:
+
+    >>> intra_slope.data
+    array([ 0.00124504, -0.00277761, -0.00221245, -0.00036338])
+    >>> inter_slope
+    -0.0010511779872922058
+
+    """
+    x = ma.array(x, subok=True, copy=False, ndmin=2)
+    (n,_) = x.shape
+    # Get list of slopes per season
+    szn_slopes = ma.vstack([(x[i+1:]-x[i])/np.arange(1,n-i)[:,None]
+                            for i in range(n)])
+    szn_medslopes = ma.median(szn_slopes, axis=0)
+    medslope = ma.median(szn_slopes, axis=None)
+    return SenSeasonalSlopesResult(szn_medslopes, medslope)
+
+
+Ttest_1sampResult = namedtuple('Ttest_1sampResult', ('statistic', 'pvalue'))
+
+
+def ttest_1samp(a, popmean, axis=0, alternative='two-sided'):
+    """
+    Calculates the T-test for the mean of ONE group of scores.
+
+    Parameters
+    ----------
+    a : array_like
+        sample observation
+    popmean : float or array_like
+        expected value in null hypothesis, if array_like than it must have the
+        same shape as `a` excluding the axis dimension
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        array `a`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the mean of the underlying distribution of the sample
+          is different than the given population mean (`popmean`)
+        * 'less': the mean of the underlying distribution of the sample is
+          less than the given population mean (`popmean`)
+        * 'greater': the mean of the underlying distribution of the sample is
+          greater than the given population mean (`popmean`)
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float or array
+        t-statistic
+    pvalue : float or array
+        The p-value
+
+    Notes
+    -----
+    For more details on `ttest_1samp`, see `scipy.stats.ttest_1samp`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    if a.size == 0:
+        return (np.nan, np.nan)
+
+    x = a.mean(axis=axis)
+    v = a.var(axis=axis, ddof=1)
+    n = a.count(axis=axis)
+    # force df to be an array for masked division not to throw a warning
+    df = ma.asanyarray(n - 1.0)
+    svar = ((n - 1.0) * v) / df
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = (x - popmean) / ma.sqrt(svar / n)
+
+    t, prob = _ttest_finish(df, t, alternative)
+    return Ttest_1sampResult(t, prob)
+
+
+ttest_onesamp = ttest_1samp
+
+
+Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue'))
+
+
+def ttest_ind(a, b, axis=0, equal_var=True, alternative='two-sided'):
+    """
+    Calculates the T-test for the means of TWO INDEPENDENT samples of scores.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must have the same shape, except in the dimension
+        corresponding to `axis` (the first, by default).
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        arrays, `a`, and `b`.
+    equal_var : bool, optional
+        If True, perform a standard independent 2 sample test that assumes equal
+        population variances.
+        If False, perform Welch's t-test, which does not assume equal population
+        variance.
+
+        .. versionadded:: 0.17.0
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          are unequal.
+        * 'less': the mean of the distribution underlying the first sample
+          is less than the mean of the distribution underlying the second
+          sample.
+        * 'greater': the mean of the distribution underlying the first
+          sample is greater than the mean of the distribution underlying
+          the second sample.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float or array
+        The calculated t-statistic.
+    pvalue : float or array
+        The p-value.
+
+    Notes
+    -----
+    For more details on `ttest_ind`, see `scipy.stats.ttest_ind`.
+
+    """
+    a, b, axis = _chk2_asarray(a, b, axis)
+
+    if a.size == 0 or b.size == 0:
+        return Ttest_indResult(np.nan, np.nan)
+
+    (x1, x2) = (a.mean(axis), b.mean(axis))
+    (v1, v2) = (a.var(axis=axis, ddof=1), b.var(axis=axis, ddof=1))
+    (n1, n2) = (a.count(axis), b.count(axis))
+
+    if equal_var:
+        # force df to be an array for masked division not to throw a warning
+        df = ma.asanyarray(n1 + n2 - 2.0)
+        svar = ((n1-1)*v1+(n2-1)*v2) / df
+        denom = ma.sqrt(svar*(1.0/n1 + 1.0/n2))  # n-D computation here!
+    else:
+        vn1 = v1/n1
+        vn2 = v2/n2
+        with np.errstate(divide='ignore', invalid='ignore'):
+            df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1))
+
+        # If df is undefined, variances are zero.
+        # It doesn't matter what df is as long as it is not NaN.
+        df = np.where(np.isnan(df), 1, df)
+        denom = ma.sqrt(vn1 + vn2)
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = (x1-x2) / denom
+
+    t, prob = _ttest_finish(df, t, alternative)
+    return Ttest_indResult(t, prob)
+
+
+Ttest_relResult = namedtuple('Ttest_relResult', ('statistic', 'pvalue'))
+
+
+def ttest_rel(a, b, axis=0, alternative='two-sided'):
+    """
+    Calculates the T-test on TWO RELATED samples of scores, a and b.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must have the same shape.
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        arrays, `a`, and `b`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          are unequal.
+        * 'less': the mean of the distribution underlying the first sample
+          is less than the mean of the distribution underlying the second
+          sample.
+        * 'greater': the mean of the distribution underlying the first
+          sample is greater than the mean of the distribution underlying
+          the second sample.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float or array
+        t-statistic
+    pvalue : float or array
+        two-tailed p-value
+
+    Notes
+    -----
+    For more details on `ttest_rel`, see `scipy.stats.ttest_rel`.
+
+    """
+    a, b, axis = _chk2_asarray(a, b, axis)
+    if len(a) != len(b):
+        raise ValueError('unequal length arrays')
+
+    if a.size == 0 or b.size == 0:
+        return Ttest_relResult(np.nan, np.nan)
+
+    n = a.count(axis)
+    df = ma.asanyarray(n-1.0)
+    d = (a-b).astype('d')
+    dm = d.mean(axis)
+    v = d.var(axis=axis, ddof=1)
+    denom = ma.sqrt(v / n)
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = dm / denom
+
+    t, prob = _ttest_finish(df, t, alternative)
+    return Ttest_relResult(t, prob)
+
+
+MannwhitneyuResult = namedtuple('MannwhitneyuResult', ('statistic',
+                                                       'pvalue'))
+
+
+def mannwhitneyu(x,y, use_continuity=True):
+    """
+    Computes the Mann-Whitney statistic
+
+    Missing values in `x` and/or `y` are discarded.
+
+    Parameters
+    ----------
+    x : sequence
+        Input
+    y : sequence
+        Input
+    use_continuity : {True, False}, optional
+        Whether a continuity correction (1/2.) should be taken into account.
+
+    Returns
+    -------
+    statistic : float
+        The minimum of the Mann-Whitney statistics
+    pvalue : float
+        Approximate two-sided p-value assuming a normal distribution.
+
+    """
+    x = ma.asarray(x).compressed().view(ndarray)
+    y = ma.asarray(y).compressed().view(ndarray)
+    ranks = rankdata(np.concatenate([x,y]))
+    (nx, ny) = (len(x), len(y))
+    nt = nx + ny
+    U = ranks[:nx].sum() - nx*(nx+1)/2.
+    U = max(U, nx*ny - U)
+    u = nx*ny - U
+
+    mu = (nx*ny)/2.
+    sigsq = (nt**3 - nt)/12.
+    ties = count_tied_groups(ranks)
+    sigsq -= sum(v*(k**3-k) for (k,v) in ties.items())/12.
+    sigsq *= nx*ny/float(nt*(nt-1))
+
+    if use_continuity:
+        z = (U - 1/2. - mu) / ma.sqrt(sigsq)
+    else:
+        z = (U - mu) / ma.sqrt(sigsq)
+
+    prob = special.erfc(abs(z)/np.sqrt(2))
+    return MannwhitneyuResult(u, prob)
+
+
+KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue'))
+
+
+def kruskal(*args):
+    """
+    Compute the Kruskal-Wallis H-test for independent samples
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+       Two or more arrays with the sample measurements can be given as
+       arguments.
+
+    Returns
+    -------
+    statistic : float
+       The Kruskal-Wallis H statistic, corrected for ties
+    pvalue : float
+       The p-value for the test using the assumption that H has a chi
+       square distribution
+
+    Notes
+    -----
+    For more details on `kruskal`, see `scipy.stats.kruskal`.
+
+    Examples
+    --------
+    >>> from scipy.stats.mstats import kruskal
+
+    Random samples from three different brands of batteries were tested
+    to see how long the charge lasted. Results were as follows:
+
+    >>> a = [6.3, 5.4, 5.7, 5.2, 5.0]
+    >>> b = [6.9, 7.0, 6.1, 7.9]
+    >>> c = [7.2, 6.9, 6.1, 6.5]
+
+    Test the hypothesis that the distribution functions for all of the brands'
+    durations are identical. Use 5% level of significance.
+
+    >>> kruskal(a, b, c)
+    KruskalResult(statistic=7.113812154696133, pvalue=0.028526948491942164)
+
+    The null hypothesis is rejected at the 5% level of significance
+    because the returned p-value is less than the critical value of 5%.
+
+    """
+    output = argstoarray(*args)
+    ranks = ma.masked_equal(rankdata(output, use_missing=False), 0)
+    sumrk = ranks.sum(-1)
+    ngrp = ranks.count(-1)
+    ntot = ranks.count()
+    H = 12./(ntot*(ntot+1)) * (sumrk**2/ngrp).sum() - 3*(ntot+1)
+    # Tie correction
+    ties = count_tied_groups(ranks)
+    T = 1. - sum(v*(k**3-k) for (k,v) in ties.items())/float(ntot**3-ntot)
+    if T == 0:
+        raise ValueError('All numbers are identical in kruskal')
+
+    H /= T
+    df = len(output) - 1
+    prob = distributions.chi2.sf(H, df)
+    return KruskalResult(H, prob)
+
+
+kruskalwallis = kruskal
+
+
+@_rename_parameter("mode", "method")
+def ks_1samp(x, cdf, args=(), alternative="two-sided", method='auto'):
+    """
+    Computes the Kolmogorov-Smirnov test on one sample of masked values.
+
+    Missing values in `x` are discarded.
+
+    Parameters
+    ----------
+    x : array_like
+        a 1-D array of observations of random variables.
+    cdf : str or callable
+        If a string, it should be the name of a distribution in `scipy.stats`.
+        If a callable, that callable is used to calculate the cdf.
+    args : tuple, sequence, optional
+        Distribution parameters, used if `cdf` is a string.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Indicates the alternative hypothesis.  Default is 'two-sided'.
+    method : {'auto', 'exact', 'asymp'}, optional
+        Defines the method used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : use 'exact' for small size arrays, 'asymp' for large
+          * 'exact' : use approximation to exact distribution of test statistic
+          * 'asymp' : use asymptotic distribution of test statistic
+
+    Returns
+    -------
+    d : float
+        Value of the Kolmogorov Smirnov test
+    p : float
+        Corresponding p-value.
+
+    """
+    alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
+       alternative.lower()[0], alternative)
+    return scipy.stats._stats_py.ks_1samp(
+        x, cdf, args=args, alternative=alternative, method=method)
+
+
+@_rename_parameter("mode", "method")
+def ks_2samp(data1, data2, alternative="two-sided", method='auto'):
+    """
+    Computes the Kolmogorov-Smirnov test on two samples.
+
+    Missing values in `x` and/or `y` are discarded.
+
+    Parameters
+    ----------
+    data1 : array_like
+        First data set
+    data2 : array_like
+        Second data set
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Indicates the alternative hypothesis.  Default is 'two-sided'.
+    method : {'auto', 'exact', 'asymp'}, optional
+        Defines the method used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : use 'exact' for small size arrays, 'asymp' for large
+          * 'exact' : use approximation to exact distribution of test statistic
+          * 'asymp' : use asymptotic distribution of test statistic
+
+    Returns
+    -------
+    d : float
+        Value of the Kolmogorov Smirnov test
+    p : float
+        Corresponding p-value.
+
+    """
+    # Ideally this would be accomplished by
+    # ks_2samp = scipy.stats._stats_py.ks_2samp
+    # but the circular dependencies between _mstats_basic and stats prevent that.
+    alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
+       alternative.lower()[0], alternative)
+    return scipy.stats._stats_py.ks_2samp(data1, data2,
+                                          alternative=alternative,
+                                          method=method)
+
+
+ks_twosamp = ks_2samp
+
+
+@_rename_parameter("mode", "method")
+def kstest(data1, data2, args=(), alternative='two-sided', method='auto'):
+    """
+
+    Parameters
+    ----------
+    data1 : array_like
+    data2 : str, callable or array_like
+    args : tuple, sequence, optional
+        Distribution parameters, used if `data1` or `data2` are strings.
+    alternative : str, as documented in stats.kstest
+    method : str, as documented in stats.kstest
+
+    Returns
+    -------
+    tuple of (K-S statistic, probability)
+
+    """
+    return scipy.stats._stats_py.kstest(data1, data2, args,
+                                        alternative=alternative, method=method)
+
+
+def trima(a, limits=None, inclusive=(True,True)):
+    """
+    Trims an array by masking the data outside some given limits.
+
+    Returns a masked version of the input array.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    limits : {None, tuple}, optional
+        Tuple of (lower limit, upper limit) in absolute values.
+        Values of the input array lower (greater) than the lower (upper) limit
+        will be masked.  A limit is None indicates an open interval.
+    inclusive : (bool, bool) tuple, optional
+        Tuple of (lower flag, upper flag), indicating whether values exactly
+        equal to the lower (upper) limit are allowed.
+
+    Examples
+    --------
+    >>> from scipy.stats.mstats import trima
+    >>> import numpy as np
+
+    >>> a = np.arange(10)
+
+    The interval is left-closed and right-open, i.e., `[2, 8)`.
+    Trim the array by keeping only values in the interval.
+
+    >>> trima(a, limits=(2, 8), inclusive=(True, False))
+    masked_array(data=[--, --, 2, 3, 4, 5, 6, 7, --, --],
+                 mask=[ True,  True, False, False, False, False, False, False,
+                        True,  True],
+           fill_value=999999)
+
+    """
+    a = ma.asarray(a)
+    a.unshare_mask()
+    if (limits is None) or (limits == (None, None)):
+        return a
+
+    (lower_lim, upper_lim) = limits
+    (lower_in, upper_in) = inclusive
+    condition = False
+    if lower_lim is not None:
+        if lower_in:
+            condition |= (a < lower_lim)
+        else:
+            condition |= (a <= lower_lim)
+
+    if upper_lim is not None:
+        if upper_in:
+            condition |= (a > upper_lim)
+        else:
+            condition |= (a >= upper_lim)
+
+    a[condition.filled(True)] = masked
+    return a
+
+
+def trimr(a, limits=None, inclusive=(True, True), axis=None):
+    """
+    Trims an array by masking some proportion of the data on each end.
+    Returns a masked version of the input array.
+
+    Parameters
+    ----------
+    a : sequence
+        Input array.
+    limits : {None, tuple}, optional
+        Tuple of the percentages to cut on each side of the array, with respect
+        to the number of unmasked data, as floats between 0. and 1.
+        Noting n the number of unmasked data before trimming, the
+        (n*limits[0])th smallest data and the (n*limits[1])th largest data are
+        masked, and the total number of unmasked data after trimming is
+        n*(1.-sum(limits)).  The value of one limit can be set to None to
+        indicate an open interval.
+    inclusive : {(True,True) tuple}, optional
+        Tuple of flags indicating whether the number of data being masked on
+        the left (right) end should be truncated (True) or rounded (False) to
+        integers.
+    axis : {None,int}, optional
+        Axis along which to trim. If None, the whole array is trimmed, but its
+        shape is maintained.
+
+    """
+    def _trimr1D(a, low_limit, up_limit, low_inclusive, up_inclusive):
+        n = a.count()
+        idx = a.argsort()
+        if low_limit:
+            if low_inclusive:
+                lowidx = int(low_limit*n)
+            else:
+                lowidx = int(np.round(low_limit*n))
+            a[idx[:lowidx]] = masked
+        if up_limit is not None:
+            if up_inclusive:
+                upidx = n - int(n*up_limit)
+            else:
+                upidx = n - int(np.round(n*up_limit))
+            a[idx[upidx:]] = masked
+        return a
+
+    a = ma.asarray(a)
+    a.unshare_mask()
+    if limits is None:
+        return a
+
+    # Check the limits
+    (lolim, uplim) = limits
+    errmsg = "The proportion to cut from the %s should be between 0. and 1."
+    if lolim is not None:
+        if lolim > 1. or lolim < 0:
+            raise ValueError(errmsg % 'beginning' + f"(got {lolim})")
+    if uplim is not None:
+        if uplim > 1. or uplim < 0:
+            raise ValueError(errmsg % 'end' + f"(got {uplim})")
+
+    (loinc, upinc) = inclusive
+
+    if axis is None:
+        shp = a.shape
+        return _trimr1D(a.ravel(),lolim,uplim,loinc,upinc).reshape(shp)
+    else:
+        return ma.apply_along_axis(_trimr1D, axis, a, lolim,uplim,loinc,upinc)
+
+
+trimdoc = """
+    Parameters
+    ----------
+    a : sequence
+        Input array
+    limits : {None, tuple}, optional
+        If `relative` is False, tuple (lower limit, upper limit) in absolute values.
+        Values of the input array lower (greater) than the lower (upper) limit are
+        masked.
+
+        If `relative` is True, tuple (lower percentage, upper percentage) to cut
+        on each side of the  array, with respect to the number of unmasked data.
+
+        Noting n the number of unmasked data before trimming, the (n*limits[0])th
+        smallest data and the (n*limits[1])th largest data are masked, and the
+        total number of unmasked data after trimming is n*(1.-sum(limits))
+        In each case, the value of one limit can be set to None to indicate an
+        open interval.
+
+        If limits is None, no trimming is performed
+    inclusive : {(bool, bool) tuple}, optional
+        If `relative` is False, tuple indicating whether values exactly equal
+        to the absolute limits are allowed.
+        If `relative` is True, tuple indicating whether the number of data
+        being masked on each side should be rounded (True) or truncated
+        (False).
+    relative : bool, optional
+        Whether to consider the limits as absolute values (False) or proportions
+        to cut (True).
+    axis : int, optional
+        Axis along which to trim.
+"""
+
+
+def trim(a, limits=None, inclusive=(True,True), relative=False, axis=None):
+    """
+    Trims an array by masking the data outside some given limits.
+
+    Returns a masked version of the input array.
+
+    %s
+
+    Examples
+    --------
+    >>> from scipy.stats.mstats import trim
+    >>> z = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10]
+    >>> print(trim(z,(3,8)))
+    [-- -- 3 4 5 6 7 8 -- --]
+    >>> print(trim(z,(0.1,0.2),relative=True))
+    [-- 2 3 4 5 6 7 8 -- --]
+
+    """
+    if relative:
+        return trimr(a, limits=limits, inclusive=inclusive, axis=axis)
+    else:
+        return trima(a, limits=limits, inclusive=inclusive)
+
+
+if trim.__doc__:
+    trim.__doc__ = trim.__doc__ % trimdoc
+
+
+def trimboth(data, proportiontocut=0.2, inclusive=(True,True), axis=None):
+    """
+    Trims the smallest and largest data values.
+
+    Trims the `data` by masking the ``int(proportiontocut * n)`` smallest and
+    ``int(proportiontocut * n)`` largest values of data along the given axis,
+    where n is the number of unmasked values before trimming.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data to trim.
+    proportiontocut : float, optional
+        Percentage of trimming (as a float between 0 and 1).
+        If n is the number of unmasked values before trimming, the number of
+        values after trimming is ``(1 - 2*proportiontocut) * n``.
+        Default is 0.2.
+    inclusive : {(bool, bool) tuple}, optional
+        Tuple indicating whether the number of data being masked on each side
+        should be rounded (True) or truncated (False).
+    axis : int, optional
+        Axis along which to perform the trimming.
+        If None, the input array is first flattened.
+
+    """
+    return trimr(data, limits=(proportiontocut,proportiontocut),
+                 inclusive=inclusive, axis=axis)
+
+
+def trimtail(data, proportiontocut=0.2, tail='left', inclusive=(True,True),
+             axis=None):
+    """
+    Trims the data by masking values from one tail.
+
+    Parameters
+    ----------
+    data : array_like
+        Data to trim.
+    proportiontocut : float, optional
+        Percentage of trimming. If n is the number of unmasked values
+        before trimming, the number of values after trimming is
+        ``(1 - proportiontocut) * n``.  Default is 0.2.
+    tail : {'left','right'}, optional
+        If 'left' the `proportiontocut` lowest values will be masked.
+        If 'right' the `proportiontocut` highest values will be masked.
+        Default is 'left'.
+    inclusive : {(bool, bool) tuple}, optional
+        Tuple indicating whether the number of data being masked on each side
+        should be rounded (True) or truncated (False).  Default is
+        (True, True).
+    axis : int, optional
+        Axis along which to perform the trimming.
+        If None, the input array is first flattened.  Default is None.
+
+    Returns
+    -------
+    trimtail : ndarray
+        Returned array of same shape as `data` with masked tail values.
+
+    """
+    tail = str(tail).lower()[0]
+    if tail == 'l':
+        limits = (proportiontocut,None)
+    elif tail == 'r':
+        limits = (None, proportiontocut)
+    else:
+        raise TypeError("The tail argument should be in ('left','right')")
+
+    return trimr(data, limits=limits, axis=axis, inclusive=inclusive)
+
+
+trim1 = trimtail
+
+
+def trimmed_mean(a, limits=(0.1,0.1), inclusive=(1,1), relative=True,
+                 axis=None):
+    """Returns the trimmed mean of the data along the given axis.
+
+    %s
+
+    """
+    if (not isinstance(limits,tuple)) and isinstance(limits,float):
+        limits = (limits, limits)
+    if relative:
+        return trimr(a,limits=limits,inclusive=inclusive,axis=axis).mean(axis=axis)
+    else:
+        return trima(a,limits=limits,inclusive=inclusive).mean(axis=axis)
+
+
+if trimmed_mean.__doc__:
+    trimmed_mean.__doc__ = trimmed_mean.__doc__ % trimdoc
+
+
+def trimmed_var(a, limits=(0.1,0.1), inclusive=(1,1), relative=True,
+                axis=None, ddof=0):
+    """Returns the trimmed variance of the data along the given axis.
+
+    %s
+    ddof : {0,integer}, optional
+        Means Delta Degrees of Freedom. The denominator used during computations
+        is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un-
+        biased estimate of the variance.
+
+    """
+    if (not isinstance(limits,tuple)) and isinstance(limits,float):
+        limits = (limits, limits)
+    if relative:
+        out = trimr(a,limits=limits, inclusive=inclusive,axis=axis)
+    else:
+        out = trima(a,limits=limits,inclusive=inclusive)
+
+    return out.var(axis=axis, ddof=ddof)
+
+
+if trimmed_var.__doc__:
+    trimmed_var.__doc__ = trimmed_var.__doc__ % trimdoc
+
+
+def trimmed_std(a, limits=(0.1,0.1), inclusive=(1,1), relative=True,
+                axis=None, ddof=0):
+    """Returns the trimmed standard deviation of the data along the given axis.
+
+    %s
+    ddof : {0,integer}, optional
+        Means Delta Degrees of Freedom. The denominator used during computations
+        is (n-ddof). DDOF=0 corresponds to a biased estimate, DDOF=1 to an un-
+        biased estimate of the variance.
+
+    """
+    if (not isinstance(limits,tuple)) and isinstance(limits,float):
+        limits = (limits, limits)
+    if relative:
+        out = trimr(a,limits=limits,inclusive=inclusive,axis=axis)
+    else:
+        out = trima(a,limits=limits,inclusive=inclusive)
+    return out.std(axis=axis,ddof=ddof)
+
+
+if trimmed_std.__doc__:
+    trimmed_std.__doc__ = trimmed_std.__doc__ % trimdoc
+
+
+def trimmed_stde(a, limits=(0.1,0.1), inclusive=(1,1), axis=None):
+    """
+    Returns the standard error of the trimmed mean along the given axis.
+
+    Parameters
+    ----------
+    a : sequence
+        Input array
+    limits : {(0.1,0.1), tuple of float}, optional
+        tuple (lower percentage, upper percentage) to cut  on each side of the
+        array, with respect to the number of unmasked data.
+
+        If n is the number of unmasked data before trimming, the values
+        smaller than ``n * limits[0]`` and the values larger than
+        ``n * `limits[1]`` are masked, and the total number of unmasked
+        data after trimming is ``n * (1.-sum(limits))``.  In each case,
+        the value of one limit can be set to None to indicate an open interval.
+        If `limits` is None, no trimming is performed.
+    inclusive : {(bool, bool) tuple} optional
+        Tuple indicating whether the number of data being masked on each side
+        should be rounded (True) or truncated (False).
+    axis : int, optional
+        Axis along which to trim.
+
+    Returns
+    -------
+    trimmed_stde : scalar or ndarray
+
+    """
+    def _trimmed_stde_1D(a, low_limit, up_limit, low_inclusive, up_inclusive):
+        "Returns the standard error of the trimmed mean for a 1D input data."
+        n = a.count()
+        idx = a.argsort()
+        if low_limit:
+            if low_inclusive:
+                lowidx = int(low_limit*n)
+            else:
+                lowidx = np.round(low_limit*n)
+            a[idx[:lowidx]] = masked
+        if up_limit is not None:
+            if up_inclusive:
+                upidx = n - int(n*up_limit)
+            else:
+                upidx = n - np.round(n*up_limit)
+            a[idx[upidx:]] = masked
+        a[idx[:lowidx]] = a[idx[lowidx]]
+        a[idx[upidx:]] = a[idx[upidx-1]]
+        winstd = a.std(ddof=1)
+        return winstd / ((1-low_limit-up_limit)*np.sqrt(len(a)))
+
+    a = ma.array(a, copy=True, subok=True)
+    a.unshare_mask()
+    if limits is None:
+        return a.std(axis=axis,ddof=1)/ma.sqrt(a.count(axis))
+    if (not isinstance(limits,tuple)) and isinstance(limits,float):
+        limits = (limits, limits)
+
+    # Check the limits
+    (lolim, uplim) = limits
+    errmsg = "The proportion to cut from the %s should be between 0. and 1."
+    if lolim is not None:
+        if lolim > 1. or lolim < 0:
+            raise ValueError(errmsg % 'beginning' + f"(got {lolim})")
+    if uplim is not None:
+        if uplim > 1. or uplim < 0:
+            raise ValueError(errmsg % 'end' + f"(got {uplim})")
+
+    (loinc, upinc) = inclusive
+    if (axis is None):
+        return _trimmed_stde_1D(a.ravel(),lolim,uplim,loinc,upinc)
+    else:
+        if a.ndim > 2:
+            raise ValueError("Array 'a' must be at most two dimensional, "
+                             "but got a.ndim = %d" % a.ndim)
+        return ma.apply_along_axis(_trimmed_stde_1D, axis, a,
+                                   lolim,uplim,loinc,upinc)
+
+
+def _mask_to_limits(a, limits, inclusive):
+    """Mask an array for values outside of given limits.
+
+    This is primarily a utility function.
+
+    Parameters
+    ----------
+    a : array
+    limits : (float or None, float or None)
+    A tuple consisting of the (lower limit, upper limit).  Values in the
+    input array less than the lower limit or greater than the upper limit
+    will be masked out. None implies no limit.
+    inclusive : (bool, bool)
+    A tuple consisting of the (lower flag, upper flag).  These flags
+    determine whether values exactly equal to lower or upper are allowed.
+
+    Returns
+    -------
+    A MaskedArray.
+
+    Raises
+    ------
+    A ValueError if there are no values within the given limits.
+    """
+    lower_limit, upper_limit = limits
+    lower_include, upper_include = inclusive
+    am = ma.MaskedArray(a)
+    if lower_limit is not None:
+        if lower_include:
+            am = ma.masked_less(am, lower_limit)
+        else:
+            am = ma.masked_less_equal(am, lower_limit)
+
+    if upper_limit is not None:
+        if upper_include:
+            am = ma.masked_greater(am, upper_limit)
+        else:
+            am = ma.masked_greater_equal(am, upper_limit)
+
+    if am.count() == 0:
+        raise ValueError("No array values within given limits")
+
+    return am
+
+
+def tmean(a, limits=None, inclusive=(True, True), axis=None):
+    """
+    Compute the trimmed mean.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored.  When limits is None (default), then all
+        values are used.  Either of the limit values in the tuple can also be
+        None representing a half-open interval.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. If None, compute over the
+        whole array. Default is None.
+
+    Returns
+    -------
+    tmean : float
+
+    Notes
+    -----
+    For more details on `tmean`, see `scipy.stats.tmean`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import mstats
+    >>> a = np.array([[6, 8, 3, 0],
+    ...               [3, 9, 1, 2],
+    ...               [8, 7, 8, 2],
+    ...               [5, 6, 0, 2],
+    ...               [4, 5, 5, 2]])
+    ...
+    ...
+    >>> mstats.tmean(a, (2,5))
+    3.3
+    >>> mstats.tmean(a, (2,5), axis=0)
+    masked_array(data=[4.0, 5.0, 4.0, 2.0],
+                 mask=[False, False, False, False],
+           fill_value=1e+20)
+
+    """
+    return trima(a, limits=limits, inclusive=inclusive).mean(axis=axis)
+
+
+def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """
+    Compute the trimmed variance
+
+    This function computes the sample variance of an array of values,
+    while ignoring values which are outside of given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. If None, compute over the
+        whole array. Default is zero.
+    ddof : int, optional
+        Delta degrees of freedom. Default is 1.
+
+    Returns
+    -------
+    tvar : float
+        Trimmed variance.
+
+    Notes
+    -----
+    For more details on `tvar`, see `scipy.stats.tvar`.
+
+    """
+    a = a.astype(float).ravel()
+    if limits is None:
+        n = (~a.mask).sum()  # todo: better way to do that?
+        return np.ma.var(a) * n/(n-1.)
+    am = _mask_to_limits(a, limits=limits, inclusive=inclusive)
+
+    return np.ma.var(am, axis=axis, ddof=ddof)
+
+
+def tmin(a, lowerlimit=None, axis=0, inclusive=True):
+    """
+    Compute the trimmed minimum
+
+    Parameters
+    ----------
+    a : array_like
+        array of values
+    lowerlimit : None or float, optional
+        Values in the input array less than the given limit will be ignored.
+        When lowerlimit is None, then all values are used. The default value
+        is None.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    inclusive : {True, False}, optional
+        This flag determines whether values exactly equal to the lower limit
+        are included.  The default value is True.
+
+    Returns
+    -------
+    tmin : float, int or ndarray
+
+    Notes
+    -----
+    For more details on `tmin`, see `scipy.stats.tmin`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import mstats
+    >>> a = np.array([[6, 8, 3, 0],
+    ...               [3, 2, 1, 2],
+    ...               [8, 1, 8, 2],
+    ...               [5, 3, 0, 2],
+    ...               [4, 7, 5, 2]])
+    ...
+    >>> mstats.tmin(a, 5)
+    masked_array(data=[5, 7, 5, --],
+                 mask=[False, False, False,  True],
+           fill_value=999999)
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    am = trima(a, (lowerlimit, None), (inclusive, False))
+    return ma.minimum.reduce(am, axis)
+
+
+def tmax(a, upperlimit=None, axis=0, inclusive=True):
+    """
+    Compute the trimmed maximum
+
+    This function computes the maximum value of an array along a given axis,
+    while ignoring values larger than a specified upper limit.
+
+    Parameters
+    ----------
+    a : array_like
+        array of values
+    upperlimit : None or float, optional
+        Values in the input array greater than the given limit will be ignored.
+        When upperlimit is None, then all values are used. The default value
+        is None.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    inclusive : {True, False}, optional
+        This flag determines whether values exactly equal to the upper limit
+        are included.  The default value is True.
+
+    Returns
+    -------
+    tmax : float, int or ndarray
+
+    Notes
+    -----
+    For more details on `tmax`, see `scipy.stats.tmax`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import mstats
+    >>> a = np.array([[6, 8, 3, 0],
+    ...               [3, 9, 1, 2],
+    ...               [8, 7, 8, 2],
+    ...               [5, 6, 0, 2],
+    ...               [4, 5, 5, 2]])
+    ...
+    ...
+    >>> mstats.tmax(a, 4)
+    masked_array(data=[4, --, 3, 2],
+                 mask=[False,  True, False, False],
+           fill_value=999999)
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    am = trima(a, (None, upperlimit), (False, inclusive))
+    return ma.maximum.reduce(am, axis)
+
+
+def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """
+    Compute the trimmed standard error of the mean.
+
+    This function finds the standard error of the mean for given
+    values, ignoring values outside the given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        array of values
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. If None, compute over the
+        whole array. Default is zero.
+    ddof : int, optional
+        Delta degrees of freedom. Default is 1.
+
+    Returns
+    -------
+    tsem : float
+
+    Notes
+    -----
+    For more details on `tsem`, see `scipy.stats.tsem`.
+
+    """
+    a = ma.asarray(a).ravel()
+    if limits is None:
+        n = float(a.count())
+        return a.std(axis=axis, ddof=ddof)/ma.sqrt(n)
+
+    am = trima(a.ravel(), limits, inclusive)
+    sd = np.sqrt(am.var(axis=axis, ddof=ddof))
+    return sd / np.sqrt(am.count())
+
+
+def winsorize(a, limits=None, inclusive=(True, True), inplace=False,
+              axis=None, nan_policy='propagate'):
+    """Returns a Winsorized version of the input array.
+
+    The (limits[0])th lowest values are set to the (limits[0])th percentile,
+    and the (limits[1])th highest values are set to the (1 - limits[1])th
+    percentile.
+    Masked values are skipped.
+
+
+    Parameters
+    ----------
+    a : sequence
+        Input array.
+    limits : {None, tuple of float}, optional
+        Tuple of the percentages to cut on each side of the array, with respect
+        to the number of unmasked data, as floats between 0. and 1.
+        Noting n the number of unmasked data before trimming, the
+        (n*limits[0])th smallest data and the (n*limits[1])th largest data are
+        masked, and the total number of unmasked data after trimming
+        is n*(1.-sum(limits)) The value of one limit can be set to None to
+        indicate an open interval.
+    inclusive : {(True, True) tuple}, optional
+        Tuple indicating whether the number of data being masked on each side
+        should be truncated (True) or rounded (False).
+    inplace : {False, True}, optional
+        Whether to winsorize in place (True) or to use a copy (False)
+    axis : {None, int}, optional
+        Axis along which to trim. If None, the whole array is trimmed, but its
+        shape is maintained.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': allows nan values and may overwrite or propagate them
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Notes
+    -----
+    This function is applied to reduce the effect of possibly spurious outliers
+    by limiting the extreme values.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import winsorize
+
+    A shuffled array contains integers from 1 to 10.
+
+    >>> a = np.array([10, 4, 9, 8, 5, 3, 7, 2, 1, 6])
+
+    The 10% of the lowest value (i.e., ``1``) and the 20% of the highest
+    values (i.e., ``9`` and ``10``) are replaced.
+
+    >>> winsorize(a, limits=[0.1, 0.2])
+    masked_array(data=[8, 4, 8, 8, 5, 3, 7, 2, 2, 6],
+                 mask=False,
+           fill_value=999999)
+
+    """
+    def _winsorize1D(a, low_limit, up_limit, low_include, up_include,
+                     contains_nan, nan_policy):
+        n = a.count()
+        idx = a.argsort()
+        if contains_nan:
+            nan_count = np.count_nonzero(np.isnan(a))
+        if low_limit:
+            if low_include:
+                lowidx = int(low_limit * n)
+            else:
+                lowidx = np.round(low_limit * n).astype(int)
+            if contains_nan and nan_policy == 'omit':
+                lowidx = min(lowidx, n-nan_count-1)
+            a[idx[:lowidx]] = a[idx[lowidx]]
+        if up_limit is not None:
+            if up_include:
+                upidx = n - int(n * up_limit)
+            else:
+                upidx = n - np.round(n * up_limit).astype(int)
+            if contains_nan and nan_policy == 'omit':
+                a[idx[upidx:-nan_count]] = a[idx[upidx - 1]]
+            else:
+                a[idx[upidx:]] = a[idx[upidx - 1]]
+        return a
+
+    contains_nan, nan_policy = _contains_nan(a, nan_policy)
+    # We are going to modify a: better make a copy
+    a = ma.array(a, copy=np.logical_not(inplace))
+
+    if limits is None:
+        return a
+    if (not isinstance(limits, tuple)) and isinstance(limits, float):
+        limits = (limits, limits)
+
+    # Check the limits
+    (lolim, uplim) = limits
+    errmsg = "The proportion to cut from the %s should be between 0. and 1."
+    if lolim is not None:
+        if lolim > 1. or lolim < 0:
+            raise ValueError(errmsg % 'beginning' + f"(got {lolim})")
+    if uplim is not None:
+        if uplim > 1. or uplim < 0:
+            raise ValueError(errmsg % 'end' + f"(got {uplim})")
+
+    (loinc, upinc) = inclusive
+
+    if axis is None:
+        shp = a.shape
+        return _winsorize1D(a.ravel(), lolim, uplim, loinc, upinc,
+                            contains_nan, nan_policy).reshape(shp)
+    else:
+        return ma.apply_along_axis(_winsorize1D, axis, a, lolim, uplim, loinc,
+                                   upinc, contains_nan, nan_policy)
+
+
+def moment(a, moment=1, axis=0):
+    """
+    Calculates the nth moment about the mean for a sample.
+
+    Parameters
+    ----------
+    a : array_like
+       data
+    moment : int, optional
+       order of central moment that is returned
+    axis : int or None, optional
+       Axis along which the central moment is computed. Default is 0.
+       If None, compute over the whole array `a`.
+
+    Returns
+    -------
+    n-th central moment : ndarray or float
+       The appropriate moment along the given axis or over all values if axis
+       is None. The denominator for the moment calculation is the number of
+       observations, no degrees of freedom correction is done.
+
+    Notes
+    -----
+    For more details about `moment`, see `scipy.stats.moment`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    if a.size == 0:
+        moment_shape = list(a.shape)
+        del moment_shape[axis]
+        dtype = a.dtype.type if a.dtype.kind in 'fc' else np.float64
+        # empty array, return nan(s) with shape matching `moment`
+        out_shape = (moment_shape if np.isscalar(moment)
+                     else [len(moment)] + moment_shape)
+        if len(out_shape) == 0:
+            return dtype(np.nan)
+        else:
+            return ma.array(np.full(out_shape, np.nan, dtype=dtype))
+
+    # for array_like moment input, return a value for each.
+    if not np.isscalar(moment):
+        mean = a.mean(axis, keepdims=True)
+        mmnt = [_moment(a, i, axis, mean=mean) for i in moment]
+        return ma.array(mmnt)
+    else:
+        return _moment(a, moment, axis)
+
+
+# Moment with optional pre-computed mean, equal to a.mean(axis, keepdims=True)
+def _moment(a, moment, axis, *, mean=None):
+    if np.abs(moment - np.round(moment)) > 0:
+        raise ValueError("All moment parameters must be integers")
+
+    if moment == 0 or moment == 1:
+        # By definition the zeroth moment about the mean is 1, and the first
+        # moment is 0.
+        shape = list(a.shape)
+        del shape[axis]
+        dtype = a.dtype.type if a.dtype.kind in 'fc' else np.float64
+
+        if len(shape) == 0:
+            return dtype(1.0 if moment == 0 else 0.0)
+        else:
+            return (ma.ones(shape, dtype=dtype) if moment == 0
+                    else ma.zeros(shape, dtype=dtype))
+    else:
+        # Exponentiation by squares: form exponent sequence
+        n_list = [moment]
+        current_n = moment
+        while current_n > 2:
+            if current_n % 2:
+                current_n = (current_n-1)/2
+            else:
+                current_n /= 2
+            n_list.append(current_n)
+
+        # Starting point for exponentiation by squares
+        mean = a.mean(axis, keepdims=True) if mean is None else mean
+        a_zero_mean = a - mean
+        if n_list[-1] == 1:
+            s = a_zero_mean.copy()
+        else:
+            s = a_zero_mean**2
+
+        # Perform multiplications
+        for n in n_list[-2::-1]:
+            s = s**2
+            if n % 2:
+                s *= a_zero_mean
+        return s.mean(axis)
+
+
+def variation(a, axis=0, ddof=0):
+    """
+    Compute the coefficient of variation.
+
+    The coefficient of variation is the standard deviation divided by the
+    mean.  This function is equivalent to::
+
+        np.std(x, axis=axis, ddof=ddof) / np.mean(x)
+
+    The default for ``ddof`` is 0, but many definitions of the coefficient
+    of variation use the square root of the unbiased sample variance
+    for the sample standard deviation, which corresponds to ``ddof=1``.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : int or None, optional
+        Axis along which to calculate the coefficient of variation. Default
+        is 0. If None, compute over the whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom.  Default is 0.
+
+    Returns
+    -------
+    variation : ndarray
+        The calculated variation along the requested axis.
+
+    Notes
+    -----
+    For more details about `variation`, see `scipy.stats.variation`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import variation
+    >>> a = np.array([2,8,4])
+    >>> variation(a)
+    0.5345224838248487
+    >>> b = np.array([2,8,3,4])
+    >>> c = np.ma.masked_array(b, mask=[0,0,1,0])
+    >>> variation(c)
+    0.5345224838248487
+
+    In the example above, it can be seen that this works the same as
+    `scipy.stats.variation` except 'stats.mstats.variation' ignores masked
+    array elements.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    return a.std(axis, ddof=ddof)/a.mean(axis)
+
+
+def skew(a, axis=0, bias=True):
+    """
+    Computes the skewness of a data set.
+
+    Parameters
+    ----------
+    a : ndarray
+        data
+    axis : int or None, optional
+        Axis along which skewness is calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    bias : bool, optional
+        If False, then the calculations are corrected for statistical bias.
+
+    Returns
+    -------
+    skewness : ndarray
+        The skewness of values along an axis, returning 0 where all values are
+        equal.
+
+    Notes
+    -----
+    For more details about `skew`, see `scipy.stats.skew`.
+
+    """
+    a, axis = _chk_asarray(a,axis)
+    mean = a.mean(axis, keepdims=True)
+    m2 = _moment(a, 2, axis, mean=mean)
+    m3 = _moment(a, 3, axis, mean=mean)
+    zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2)
+    with np.errstate(all='ignore'):
+        vals = ma.where(zero, 0, m3 / m2**1.5)
+
+    if not bias and zero is not ma.masked and m2 is not ma.masked:
+        n = a.count(axis)
+        can_correct = ~zero & (n > 2)
+        if can_correct.any():
+            n = np.extract(can_correct, n)
+            m2 = np.extract(can_correct, m2)
+            m3 = np.extract(can_correct, m3)
+            nval = ma.sqrt((n-1.0)*n)/(n-2.0)*m3/m2**1.5
+            np.place(vals, can_correct, nval)
+    return vals
+
+
+def kurtosis(a, axis=0, fisher=True, bias=True):
+    """
+    Computes the kurtosis (Fisher or Pearson) of a dataset.
+
+    Kurtosis is the fourth central moment divided by the square of the
+    variance. If Fisher's definition is used, then 3.0 is subtracted from
+    the result to give 0.0 for a normal distribution.
+
+    If bias is False then the kurtosis is calculated using k statistics to
+    eliminate bias coming from biased moment estimators
+
+    Use `kurtosistest` to see if result is close enough to normal.
+
+    Parameters
+    ----------
+    a : array
+        data for which the kurtosis is calculated
+    axis : int or None, optional
+        Axis along which the kurtosis is calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    fisher : bool, optional
+        If True, Fisher's definition is used (normal ==> 0.0). If False,
+        Pearson's definition is used (normal ==> 3.0).
+    bias : bool, optional
+        If False, then the calculations are corrected for statistical bias.
+
+    Returns
+    -------
+    kurtosis : array
+        The kurtosis of values along an axis. If all values are equal,
+        return -3 for Fisher's definition and 0 for Pearson's definition.
+
+    Notes
+    -----
+    For more details about `kurtosis`, see `scipy.stats.kurtosis`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    mean = a.mean(axis, keepdims=True)
+    m2 = _moment(a, 2, axis, mean=mean)
+    m4 = _moment(a, 4, axis, mean=mean)
+    zero = (m2 <= (np.finfo(m2.dtype).resolution * mean.squeeze(axis))**2)
+    with np.errstate(all='ignore'):
+        vals = ma.where(zero, 0, m4 / m2**2.0)
+
+    if not bias and zero is not ma.masked and m2 is not ma.masked:
+        n = a.count(axis)
+        can_correct = ~zero & (n > 3)
+        if can_correct.any():
+            n = np.extract(can_correct, n)
+            m2 = np.extract(can_correct, m2)
+            m4 = np.extract(can_correct, m4)
+            nval = 1.0/(n-2)/(n-3)*((n*n-1.0)*m4/m2**2.0-3*(n-1)**2.0)
+            np.place(vals, can_correct, nval+3.0)
+    if fisher:
+        return vals - 3
+    else:
+        return vals
+
+
+DescribeResult = namedtuple('DescribeResult', ('nobs', 'minmax', 'mean',
+                                               'variance', 'skewness',
+                                               'kurtosis'))
+
+
+def describe(a, axis=0, ddof=0, bias=True):
+    """
+    Computes several descriptive statistics of the passed array.
+
+    Parameters
+    ----------
+    a : array_like
+        Data array
+    axis : int or None, optional
+        Axis along which to calculate statistics. Default 0. If None,
+        compute over the whole array `a`.
+    ddof : int, optional
+        degree of freedom (default 0); note that default ddof is different
+        from the same routine in stats.describe
+    bias : bool, optional
+        If False, then the skewness and kurtosis calculations are corrected for
+        statistical bias.
+
+    Returns
+    -------
+    nobs : int
+        (size of the data (discarding missing values)
+
+    minmax : (int, int)
+        min, max
+
+    mean : float
+        arithmetic mean
+
+    variance : float
+        unbiased variance
+
+    skewness : float
+        biased skewness
+
+    kurtosis : float
+        biased kurtosis
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import describe
+    >>> ma = np.ma.array(range(6), mask=[0, 0, 0, 1, 1, 1])
+    >>> describe(ma)
+    DescribeResult(nobs=np.int64(3), minmax=(masked_array(data=0,
+                 mask=False,
+           fill_value=999999), masked_array(data=2,
+                 mask=False,
+           fill_value=999999)), mean=np.float64(1.0),
+           variance=np.float64(0.6666666666666666),
+           skewness=masked_array(data=0., mask=False, fill_value=1e+20),
+            kurtosis=np.float64(-1.5))
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    n = a.count(axis)
+    mm = (ma.minimum.reduce(a, axis=axis), ma.maximum.reduce(a, axis=axis))
+    m = a.mean(axis)
+    v = a.var(axis, ddof=ddof)
+    sk = skew(a, axis, bias=bias)
+    kurt = kurtosis(a, axis, bias=bias)
+
+    return DescribeResult(n, mm, m, v, sk, kurt)
+
+
+def stde_median(data, axis=None):
+    """Returns the McKean-Schrader estimate of the standard error of the sample
+    median along the given axis. masked values are discarded.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data to trim.
+    axis : {None,int}, optional
+        Axis along which to perform the trimming.
+        If None, the input array is first flattened.
+
+    """
+    def _stdemed_1D(data):
+        data = np.sort(data.compressed())
+        n = len(data)
+        z = 2.5758293035489004
+        k = int(np.round((n+1)/2. - z * np.sqrt(n/4.),0))
+        return ((data[n-k] - data[k-1])/(2.*z))
+
+    data = ma.array(data, copy=False, subok=True)
+    if (axis is None):
+        return _stdemed_1D(data)
+    else:
+        if data.ndim > 2:
+            raise ValueError("Array 'data' must be at most two dimensional, "
+                             "but got data.ndim = %d" % data.ndim)
+        return ma.apply_along_axis(_stdemed_1D, axis, data)
+
+
+SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue'))
+
+
+def skewtest(a, axis=0, alternative='two-sided'):
+    """
+    Tests whether the skew is different from the normal distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        The data to be tested
+    axis : int or None, optional
+       Axis along which statistics are calculated. Default is 0.
+       If None, compute over the whole array `a`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the skewness of the distribution underlying the sample
+          is different from that of the normal distribution (i.e. 0)
+        * 'less': the skewness of the distribution underlying the sample
+          is less than that of the normal distribution
+        * 'greater': the skewness of the distribution underlying the sample
+          is greater than that of the normal distribution
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : array_like
+        The computed z-score for this test.
+    pvalue : array_like
+        A p-value for the hypothesis test
+
+    Notes
+    -----
+    For more details about `skewtest`, see `scipy.stats.skewtest`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    if axis is None:
+        a = a.ravel()
+        axis = 0
+    b2 = skew(a,axis)
+    n = a.count(axis)
+    if np.min(n) < 8:
+        raise ValueError(
+            "skewtest is not valid with less than 8 samples; %i samples"
+            " were given." % np.min(n))
+
+    y = b2 * ma.sqrt(((n+1)*(n+3)) / (6.0*(n-2)))
+    beta2 = (3.0*(n*n+27*n-70)*(n+1)*(n+3)) / ((n-2.0)*(n+5)*(n+7)*(n+9))
+    W2 = -1 + ma.sqrt(2*(beta2-1))
+    delta = 1/ma.sqrt(0.5*ma.log(W2))
+    alpha = ma.sqrt(2.0/(W2-1))
+    y = ma.where(y == 0, 1, y)
+    Z = delta*ma.log(y/alpha + ma.sqrt((y/alpha)**2+1))
+    pvalue = scipy.stats._stats_py._get_pvalue(Z, distributions.norm, alternative)
+
+    return SkewtestResult(Z[()], pvalue[()])
+
+
+KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue'))
+
+
+def kurtosistest(a, axis=0, alternative='two-sided'):
+    """
+    Tests whether a dataset has normal kurtosis
+
+    Parameters
+    ----------
+    a : array_like
+        array of the sample data
+    axis : int or None, optional
+       Axis along which to compute test. Default is 0. If None,
+       compute over the whole array `a`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the kurtosis of the distribution underlying the sample
+          is different from that of the normal distribution
+        * 'less': the kurtosis of the distribution underlying the sample
+          is less than that of the normal distribution
+        * 'greater': the kurtosis of the distribution underlying the sample
+          is greater than that of the normal distribution
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : array_like
+        The computed z-score for this test.
+    pvalue : array_like
+        The p-value for the hypothesis test
+
+    Notes
+    -----
+    For more details about `kurtosistest`, see `scipy.stats.kurtosistest`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    n = a.count(axis=axis)
+    if np.min(n) < 5:
+        raise ValueError(
+            "kurtosistest requires at least 5 observations; %i observations"
+            " were given." % np.min(n))
+    if np.min(n) < 20:
+        warnings.warn(
+            "kurtosistest only valid for n>=20 ... continuing anyway, n=%i" % np.min(n),
+            stacklevel=2,
+        )
+
+    b2 = kurtosis(a, axis, fisher=False)
+    E = 3.0*(n-1) / (n+1)
+    varb2 = 24.0*n*(n-2.)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5))
+    x = (b2-E)/ma.sqrt(varb2)
+    sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * np.sqrt((6.0*(n+3)*(n+5)) /
+                                                        (n*(n-2)*(n-3)))
+    A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + np.sqrt(1+4.0/(sqrtbeta1**2)))
+    term1 = 1 - 2./(9.0*A)
+    denom = 1 + x*ma.sqrt(2/(A-4.0))
+    if np.ma.isMaskedArray(denom):
+        # For multi-dimensional array input
+        denom[denom == 0.0] = masked
+    elif denom == 0.0:
+        denom = masked
+
+    term2 = np.ma.where(denom > 0, ma.power((1-2.0/A)/denom, 1/3.0),
+                        -ma.power(-(1-2.0/A)/denom, 1/3.0))
+    Z = (term1 - term2) / np.sqrt(2/(9.0*A))
+    pvalue = scipy.stats._stats_py._get_pvalue(Z, distributions.norm, alternative)
+
+    return KurtosistestResult(Z[()], pvalue[()])
+
+
+NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue'))
+
+
+def normaltest(a, axis=0):
+    """
+    Tests whether a sample differs from a normal distribution.
+
+    Parameters
+    ----------
+    a : array_like
+        The array containing the data to be tested.
+    axis : int or None, optional
+        Axis along which to compute test. Default is 0. If None,
+        compute over the whole array `a`.
+
+    Returns
+    -------
+    statistic : float or array
+        ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
+        ``k`` is the z-score returned by `kurtosistest`.
+    pvalue : float or array
+       A 2-sided chi squared probability for the hypothesis test.
+
+    Notes
+    -----
+    For more details about `normaltest`, see `scipy.stats.normaltest`.
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    s, _ = skewtest(a, axis)
+    k, _ = kurtosistest(a, axis)
+    k2 = s*s + k*k
+
+    return NormaltestResult(k2, distributions.chi2.sf(k2, 2))
+
+
+def mquantiles(a, prob=(.25, .5, .75), alphap=.4, betap=.4, axis=None,
+               limit=()):
+    """
+    Computes empirical quantiles for a data array.
+
+    Samples quantile are defined by ``Q(p) = (1-gamma)*x[j] + gamma*x[j+1]``,
+    where ``x[j]`` is the j-th order statistic, and gamma is a function of
+    ``j = floor(n*p + m)``, ``m = alphap + p*(1 - alphap - betap)`` and
+    ``g = n*p + m - j``.
+
+    Reinterpreting the above equations to compare to **R** lead to the
+    equation: ``p(k) = (k - alphap)/(n + 1 - alphap - betap)``
+
+    Typical values of (alphap,betap) are:
+        - (0,1)    : ``p(k) = k/n`` : linear interpolation of cdf
+          (**R** type 4)
+        - (.5,.5)  : ``p(k) = (k - 1/2.)/n`` : piecewise linear function
+          (**R** type 5)
+        - (0,0)    : ``p(k) = k/(n+1)`` :
+          (**R** type 6)
+        - (1,1)    : ``p(k) = (k-1)/(n-1)``: p(k) = mode[F(x[k])].
+          (**R** type 7, **R** default)
+        - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``: Then p(k) ~ median[F(x[k])].
+          The resulting quantile estimates are approximately median-unbiased
+          regardless of the distribution of x.
+          (**R** type 8)
+        - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``: Blom.
+          The resulting quantile estimates are approximately unbiased
+          if x is normally distributed
+          (**R** type 9)
+        - (.4,.4)  : approximately quantile unbiased (Cunnane)
+        - (.35,.35): APL, used with PWM
+
+    Parameters
+    ----------
+    a : array_like
+        Input data, as a sequence or array of dimension at most 2.
+    prob : array_like, optional
+        List of quantiles to compute.
+    alphap : float, optional
+        Plotting positions parameter, default is 0.4.
+    betap : float, optional
+        Plotting positions parameter, default is 0.4.
+    axis : int, optional
+        Axis along which to perform the trimming.
+        If None (default), the input array is first flattened.
+    limit : tuple, optional
+        Tuple of (lower, upper) values.
+        Values of `a` outside this open interval are ignored.
+
+    Returns
+    -------
+    mquantiles : MaskedArray
+        An array containing the calculated quantiles.
+
+    Notes
+    -----
+    This formulation is very similar to **R** except the calculation of
+    ``m`` from ``alphap`` and ``betap``, where in **R** ``m`` is defined
+    with each type.
+
+    References
+    ----------
+    .. [1] *R* statistical software: https://www.r-project.org/
+    .. [2] *R* ``quantile`` function:
+            http://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import mquantiles
+    >>> a = np.array([6., 47., 49., 15., 42., 41., 7., 39., 43., 40., 36.])
+    >>> mquantiles(a)
+    array([ 19.2,  40. ,  42.8])
+
+    Using a 2D array, specifying axis and limit.
+
+    >>> data = np.array([[   6.,    7.,    1.],
+    ...                  [  47.,   15.,    2.],
+    ...                  [  49.,   36.,    3.],
+    ...                  [  15.,   39.,    4.],
+    ...                  [  42.,   40., -999.],
+    ...                  [  41.,   41., -999.],
+    ...                  [   7., -999., -999.],
+    ...                  [  39., -999., -999.],
+    ...                  [  43., -999., -999.],
+    ...                  [  40., -999., -999.],
+    ...                  [  36., -999., -999.]])
+    >>> print(mquantiles(data, axis=0, limit=(0, 50)))
+    [[19.2  14.6   1.45]
+     [40.   37.5   2.5 ]
+     [42.8  40.05  3.55]]
+
+    >>> data[:, 2] = -999.
+    >>> print(mquantiles(data, axis=0, limit=(0, 50)))
+    [[19.200000000000003 14.6 --]
+     [40.0 37.5 --]
+     [42.800000000000004 40.05 --]]
+
+    """
+    def _quantiles1D(data,m,p):
+        x = np.sort(data.compressed())
+        n = len(x)
+        if n == 0:
+            return ma.array(np.empty(len(p), dtype=float), mask=True)
+        elif n == 1:
+            return ma.array(np.resize(x, p.shape), mask=nomask)
+        aleph = (n*p + m)
+        k = np.floor(aleph.clip(1, n-1)).astype(int)
+        gamma = (aleph-k).clip(0,1)
+        return (1.-gamma)*x[(k-1).tolist()] + gamma*x[k.tolist()]
+
+    data = ma.array(a, copy=False)
+    if data.ndim > 2:
+        raise TypeError("Array should be 2D at most !")
+
+    if limit:
+        condition = (limit[0] < data) & (data < limit[1])
+        data[~condition.filled(True)] = masked
+
+    p = np.atleast_1d(np.asarray(prob))
+    m = alphap + p*(1.-alphap-betap)
+    # Computes quantiles along axis (or globally)
+    if (axis is None):
+        return _quantiles1D(data, m, p)
+
+    return ma.apply_along_axis(_quantiles1D, axis, data, m, p)
+
+
+def scoreatpercentile(data, per, limit=(), alphap=.4, betap=.4):
+    """Calculate the score at the given 'per' percentile of the
+    sequence a.  For example, the score at per=50 is the median.
+
+    This function is a shortcut to mquantile
+
+    """
+    if (per < 0) or (per > 100.):
+        raise ValueError(f"The percentile should be between 0. and 100. ! (got {per})")
+
+    return mquantiles(data, prob=[per/100.], alphap=alphap, betap=betap,
+                      limit=limit, axis=0).squeeze()
+
+
+def plotting_positions(data, alpha=0.4, beta=0.4):
+    """
+    Returns plotting positions (or empirical percentile points) for the data.
+
+    Plotting positions are defined as ``(i-alpha)/(n+1-alpha-beta)``, where:
+        - i is the rank order statistics
+        - n is the number of unmasked values along the given axis
+        - `alpha` and `beta` are two parameters.
+
+    Typical values for `alpha` and `beta` are:
+        - (0,1)    : ``p(k) = k/n``, linear interpolation of cdf (R, type 4)
+        - (.5,.5)  : ``p(k) = (k-1/2.)/n``, piecewise linear function
+          (R, type 5)
+        - (0,0)    : ``p(k) = k/(n+1)``, Weibull (R type 6)
+        - (1,1)    : ``p(k) = (k-1)/(n-1)``, in this case,
+          ``p(k) = mode[F(x[k])]``. That's R default (R type 7)
+        - (1/3,1/3): ``p(k) = (k-1/3)/(n+1/3)``, then
+          ``p(k) ~ median[F(x[k])]``.
+          The resulting quantile estimates are approximately median-unbiased
+          regardless of the distribution of x. (R type 8)
+        - (3/8,3/8): ``p(k) = (k-3/8)/(n+1/4)``, Blom.
+          The resulting quantile estimates are approximately unbiased
+          if x is normally distributed (R type 9)
+        - (.4,.4)  : approximately quantile unbiased (Cunnane)
+        - (.35,.35): APL, used with PWM
+        - (.3175, .3175): used in scipy.stats.probplot
+
+    Parameters
+    ----------
+    data : array_like
+        Input data, as a sequence or array of dimension at most 2.
+    alpha : float, optional
+        Plotting positions parameter. Default is 0.4.
+    beta : float, optional
+        Plotting positions parameter. Default is 0.4.
+
+    Returns
+    -------
+    positions : MaskedArray
+        The calculated plotting positions.
+
+    """
+    data = ma.array(data, copy=False).reshape(1,-1)
+    n = data.count()
+    plpos = np.empty(data.size, dtype=float)
+    plpos[n:] = 0
+    plpos[data.argsort(axis=None)[:n]] = ((np.arange(1, n+1) - alpha) /
+                                          (n + 1.0 - alpha - beta))
+    return ma.array(plpos, mask=data._mask)
+
+
+meppf = plotting_positions
+
+
+def obrientransform(*args):
+    """
+    Computes a transform on input data (any number of columns).  Used to
+    test for homogeneity of variance prior to running one-way stats.  Each
+    array in ``*args`` is one level of a factor.  If an `f_oneway()` run on
+    the transformed data and found significant, variances are unequal.   From
+    Maxwell and Delaney, p.112.
+
+    Returns: transformed data for use in an ANOVA
+    """
+    data = argstoarray(*args).T
+    v = data.var(axis=0,ddof=1)
+    m = data.mean(0)
+    n = data.count(0).astype(float)
+    # result = ((N-1.5)*N*(a-m)**2 - 0.5*v*(n-1))/((n-1)*(n-2))
+    data -= m
+    data **= 2
+    data *= (n-1.5)*n
+    data -= 0.5*v*(n-1)
+    data /= (n-1.)*(n-2.)
+    if not ma.allclose(v,data.mean(0)):
+        raise ValueError("Lack of convergence in obrientransform.")
+
+    return data
+
+
+def sem(a, axis=0, ddof=1):
+    """
+    Calculates the standard error of the mean of the input array.
+
+    Also sometimes called standard error of measurement.
+
+    Parameters
+    ----------
+    a : array_like
+        An array containing the values for which the standard error is
+        returned.
+    axis : int or None, optional
+        If axis is None, ravel `a` first. If axis is an integer, this will be
+        the axis over which to operate. Defaults to 0.
+    ddof : int, optional
+        Delta degrees-of-freedom. How many degrees of freedom to adjust
+        for bias in limited samples relative to the population estimate
+        of variance. Defaults to 1.
+
+    Returns
+    -------
+    s : ndarray or float
+        The standard error of the mean in the sample(s), along the input axis.
+
+    Notes
+    -----
+    The default value for `ddof` changed in scipy 0.15.0 to be consistent with
+    `scipy.stats.sem` as well as with the most common definition used (like in
+    the R documentation).
+
+    Examples
+    --------
+    Find standard error along the first axis:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.arange(20).reshape(5,4)
+    >>> print(stats.mstats.sem(a))
+    [2.8284271247461903 2.8284271247461903 2.8284271247461903
+     2.8284271247461903]
+
+    Find standard error across the whole array, using n degrees of freedom:
+
+    >>> print(stats.mstats.sem(a, axis=None, ddof=0))
+    1.2893796958227628
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    n = a.count(axis=axis)
+    s = a.std(axis=axis, ddof=ddof) / ma.sqrt(n)
+    return s
+
+
+F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))
+
+
+def f_oneway(*args):
+    """
+    Performs a 1-way ANOVA, returning an F-value and probability given
+    any number of groups.  From Heiman, pp.394-7.
+
+    Usage: ``f_oneway(*args)``, where ``*args`` is 2 or more arrays,
+    one per treatment group.
+
+    Returns
+    -------
+    statistic : float
+        The computed F-value of the test.
+    pvalue : float
+        The associated p-value from the F-distribution.
+
+    """
+    # Construct a single array of arguments: each row is a group
+    data = argstoarray(*args)
+    ngroups = len(data)
+    ntot = data.count()
+    sstot = (data**2).sum() - (data.sum())**2/float(ntot)
+    ssbg = (data.count(-1) * (data.mean(-1)-data.mean())**2).sum()
+    sswg = sstot-ssbg
+    dfbg = ngroups-1
+    dfwg = ntot - ngroups
+    msb = ssbg/float(dfbg)
+    msw = sswg/float(dfwg)
+    f = msb/msw
+    prob = special.fdtrc(dfbg, dfwg, f)  # equivalent to stats.f.sf
+
+    return F_onewayResult(f, prob)
+
+
+FriedmanchisquareResult = namedtuple('FriedmanchisquareResult',
+                                     ('statistic', 'pvalue'))
+
+
+def friedmanchisquare(*args):
+    """Friedman Chi-Square is a non-parametric, one-way within-subjects ANOVA.
+    This function calculates the Friedman Chi-square test for repeated measures
+    and returns the result, along with the associated probability value.
+
+    Each input is considered a given group. Ideally, the number of treatments
+    among each group should be equal. If this is not the case, only the first
+    n treatments are taken into account, where n is the number of treatments
+    of the smallest group.
+    If a group has some missing values, the corresponding treatments are masked
+    in the other groups.
+    The test statistic is corrected for ties.
+
+    Masked values in one group are propagated to the other groups.
+
+    Returns
+    -------
+    statistic : float
+        the test statistic.
+    pvalue : float
+        the associated p-value.
+
+    """
+    data = argstoarray(*args).astype(float)
+    k = len(data)
+    if k < 3:
+        raise ValueError("Less than 3 groups (%i): " % k +
+                         "the Friedman test is NOT appropriate.")
+
+    ranked = ma.masked_values(rankdata(data, axis=0), 0)
+    if ranked._mask is not nomask:
+        ranked = ma.mask_cols(ranked)
+        ranked = ranked.compressed().reshape(k,-1).view(ndarray)
+    else:
+        ranked = ranked._data
+    (k,n) = ranked.shape
+    # Ties correction
+    repeats = [find_repeats(row) for row in ranked.T]
+    ties = np.array([y for x, y in repeats if x.size > 0])
+    tie_correction = 1 - (ties**3-ties).sum()/float(n*(k**3-k))
+
+    ssbg = np.sum((ranked.sum(-1) - n*(k+1)/2.)**2)
+    chisq = ssbg * 12./(n*k*(k+1)) * 1./tie_correction
+
+    return FriedmanchisquareResult(chisq,
+                                   distributions.chi2.sf(chisq, k-1))
+
+
+BrunnerMunzelResult = namedtuple('BrunnerMunzelResult', ('statistic', 'pvalue'))
+
+
+def brunnermunzel(x, y, alternative="two-sided", distribution="t"):
+    """
+    Compute the Brunner-Munzel test on samples x and y.
+
+    Any missing values in `x` and/or `y` are discarded.
+
+    The Brunner-Munzel test is a nonparametric test of the null hypothesis that
+    when values are taken one by one from each group, the probabilities of
+    getting large values in both groups are equal.
+    Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the
+    assumption of equivariance of two groups. Note that this does not assume
+    the distributions are same. This test works on two independent samples,
+    which may have different sizes.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Array of samples, should be one-dimensional.
+    alternative : 'less', 'two-sided', or 'greater', optional
+        Whether to get the p-value for the one-sided hypothesis ('less'
+        or 'greater') or for the two-sided hypothesis ('two-sided').
+        Defaults value is 'two-sided' .
+    distribution : 't' or 'normal', optional
+        Whether to get the p-value by t-distribution or by standard normal
+        distribution.
+        Defaults value is 't' .
+
+    Returns
+    -------
+    statistic : float
+        The Brunner-Munzer W statistic.
+    pvalue : float
+        p-value assuming an t distribution. One-sided or
+        two-sided, depending on the choice of `alternative` and `distribution`.
+
+    See Also
+    --------
+    mannwhitneyu : Mann-Whitney rank test on two samples.
+
+    Notes
+    -----
+    For more details on `brunnermunzel`, see `scipy.stats.brunnermunzel`.
+
+    Examples
+    --------
+    >>> from scipy.stats.mstats import brunnermunzel
+    >>> import numpy as np
+    >>> x1 = [1, 2, np.nan, np.nan, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1]
+    >>> x2 = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4]
+    >>> brunnermunzel(x1, x2)
+    BrunnerMunzelResult(statistic=1.4723186918922935, pvalue=0.15479415300426624)  # may vary
+
+    """  # noqa: E501
+    x = ma.asarray(x).compressed().view(ndarray)
+    y = ma.asarray(y).compressed().view(ndarray)
+    nx = len(x)
+    ny = len(y)
+    if nx == 0 or ny == 0:
+        return BrunnerMunzelResult(np.nan, np.nan)
+    rankc = rankdata(np.concatenate((x,y)))
+    rankcx = rankc[0:nx]
+    rankcy = rankc[nx:nx+ny]
+    rankcx_mean = np.mean(rankcx)
+    rankcy_mean = np.mean(rankcy)
+    rankx = rankdata(x)
+    ranky = rankdata(y)
+    rankx_mean = np.mean(rankx)
+    ranky_mean = np.mean(ranky)
+
+    Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0))
+    Sx /= nx - 1
+    Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0))
+    Sy /= ny - 1
+
+    wbfn = nx * ny * (rankcy_mean - rankcx_mean)
+    wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy)
+
+    if distribution == "t":
+        df_numer = np.power(nx * Sx + ny * Sy, 2.0)
+        df_denom = np.power(nx * Sx, 2.0) / (nx - 1)
+        df_denom += np.power(ny * Sy, 2.0) / (ny - 1)
+        df = df_numer / df_denom
+        p = distributions.t.cdf(wbfn, df)
+    elif distribution == "normal":
+        p = distributions.norm.cdf(wbfn)
+    else:
+        raise ValueError(
+            "distribution should be 't' or 'normal'")
+
+    if alternative == "greater":
+        pass
+    elif alternative == "less":
+        p = 1 - p
+    elif alternative == "two-sided":
+        p = 2 * np.min([p, 1-p])
+    else:
+        raise ValueError(
+            "alternative should be 'less', 'greater' or 'two-sided'")
+
+    return BrunnerMunzelResult(wbfn, p)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_extras.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_extras.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ea1e56a99d530ded03210ee72c3cd4755b15d44
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mstats_extras.py
@@ -0,0 +1,521 @@
+"""
+Additional statistics functions with support for masked arrays.
+
+"""
+
+# Original author (2007): Pierre GF Gerard-Marchant
+
+
+__all__ = ['compare_medians_ms',
+           'hdquantiles', 'hdmedian', 'hdquantiles_sd',
+           'idealfourths',
+           'median_cihs','mjci','mquantiles_cimj',
+           'rsh',
+           'trimmed_mean_ci',]
+
+
+import numpy as np
+from numpy import float64, ndarray
+
+import numpy.ma as ma
+from numpy.ma import MaskedArray
+
+from . import _mstats_basic as mstats
+
+from scipy.stats.distributions import norm, beta, t, binom
+
+
+def hdquantiles(data, prob=(.25, .5, .75), axis=None, var=False,):
+    """
+    Computes quantile estimates with the Harrell-Davis method.
+
+    The quantile estimates are calculated as a weighted linear combination
+    of order statistics.
+
+    Parameters
+    ----------
+    data : array_like
+        Data array.
+    prob : sequence, optional
+        Sequence of probabilities at which to compute the quantiles.
+    axis : int or None, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+    var : bool, optional
+        Whether to return the variance of the estimate.
+
+    Returns
+    -------
+    hdquantiles : MaskedArray
+        A (p,) array of quantiles (if `var` is False), or a (2,p) array of
+        quantiles and variances (if `var` is True), where ``p`` is the
+        number of quantiles.
+
+    See Also
+    --------
+    hdquantiles_sd
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.mstats import hdquantiles
+    >>>
+    >>> # Sample data
+    >>> data = np.array([1.2, 2.5, 3.7, 4.0, 5.1, 6.3, 7.0, 8.2, 9.4])
+    >>>
+    >>> # Probabilities at which to compute quantiles
+    >>> probabilities = [0.25, 0.5, 0.75]
+    >>>
+    >>> # Compute Harrell-Davis quantile estimates
+    >>> quantile_estimates = hdquantiles(data, prob=probabilities)
+    >>>
+    >>> # Display the quantile estimates
+    >>> for i, quantile in enumerate(probabilities):
+    ...     print(f"{int(quantile * 100)}th percentile: {quantile_estimates[i]}")
+    25th percentile: 3.1505820231763066 # may vary
+    50th percentile: 5.194344084883956
+    75th percentile: 7.430626414674935
+
+    """
+    def _hd_1D(data,prob,var):
+        "Computes the HD quantiles for a 1D array. Returns nan for invalid data."
+        xsorted = np.squeeze(np.sort(data.compressed().view(ndarray)))
+        # Don't use length here, in case we have a numpy scalar
+        n = xsorted.size
+
+        hd = np.empty((2,len(prob)), float64)
+        if n < 2:
+            hd.flat = np.nan
+            if var:
+                return hd
+            return hd[0]
+
+        v = np.arange(n+1) / float(n)
+        betacdf = beta.cdf
+        for (i,p) in enumerate(prob):
+            _w = betacdf(v, (n+1)*p, (n+1)*(1-p))
+            w = _w[1:] - _w[:-1]
+            hd_mean = np.dot(w, xsorted)
+            hd[0,i] = hd_mean
+            #
+            hd[1,i] = np.dot(w, (xsorted-hd_mean)**2)
+            #
+        hd[0, prob == 0] = xsorted[0]
+        hd[0, prob == 1] = xsorted[-1]
+        if var:
+            hd[1, prob == 0] = hd[1, prob == 1] = np.nan
+            return hd
+        return hd[0]
+    # Initialization & checks
+    data = ma.array(data, copy=False, dtype=float64)
+    p = np.atleast_1d(np.asarray(prob))
+    # Computes quantiles along axis (or globally)
+    if (axis is None) or (data.ndim == 1):
+        result = _hd_1D(data, p, var)
+    else:
+        if data.ndim > 2:
+            raise ValueError("Array 'data' must be at most two dimensional, "
+                             "but got data.ndim = %d" % data.ndim)
+        result = ma.apply_along_axis(_hd_1D, axis, data, p, var)
+
+    return ma.fix_invalid(result, copy=False)
+
+
+def hdmedian(data, axis=-1, var=False):
+    """
+    Returns the Harrell-Davis estimate of the median along the given axis.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data array.
+    axis : int, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+    var : bool, optional
+        Whether to return the variance of the estimate.
+
+    Returns
+    -------
+    hdmedian : MaskedArray
+        The median values.  If ``var=True``, the variance is returned inside
+        the masked array.  E.g. for a 1-D array the shape change from (1,) to
+        (2,).
+
+    """
+    result = hdquantiles(data,[0.5], axis=axis, var=var)
+    return result.squeeze()
+
+
+def hdquantiles_sd(data, prob=(.25, .5, .75), axis=None):
+    """
+    The standard error of the Harrell-Davis quantile estimates by jackknife.
+
+    Parameters
+    ----------
+    data : array_like
+        Data array.
+    prob : sequence, optional
+        Sequence of quantiles to compute.
+    axis : int, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+
+    Returns
+    -------
+    hdquantiles_sd : MaskedArray
+        Standard error of the Harrell-Davis quantile estimates.
+
+    See Also
+    --------
+    hdquantiles
+
+    """
+    def _hdsd_1D(data, prob):
+        "Computes the std error for 1D arrays."
+        xsorted = np.sort(data.compressed())
+        n = len(xsorted)
+
+        hdsd = np.empty(len(prob), float64)
+        if n < 2:
+            hdsd.flat = np.nan
+
+        vv = np.arange(n) / float(n-1)
+        betacdf = beta.cdf
+
+        for (i,p) in enumerate(prob):
+            _w = betacdf(vv, n*p, n*(1-p))
+            w = _w[1:] - _w[:-1]
+            # cumulative sum of weights and data points if
+            # ith point is left out for jackknife
+            mx_ = np.zeros_like(xsorted)
+            mx_[1:] = np.cumsum(w * xsorted[:-1])
+            # similar but from the right
+            mx_[:-1] += np.cumsum(w[::-1] * xsorted[:0:-1])[::-1]
+            hdsd[i] = np.sqrt(mx_.var() * (n - 1))
+        return hdsd
+
+    # Initialization & checks
+    data = ma.array(data, copy=False, dtype=float64)
+    p = np.atleast_1d(np.asarray(prob))
+    # Computes quantiles along axis (or globally)
+    if (axis is None):
+        result = _hdsd_1D(data, p)
+    else:
+        if data.ndim > 2:
+            raise ValueError("Array 'data' must be at most two dimensional, "
+                             "but got data.ndim = %d" % data.ndim)
+        result = ma.apply_along_axis(_hdsd_1D, axis, data, p)
+
+    return ma.fix_invalid(result, copy=False).ravel()
+
+
+def trimmed_mean_ci(data, limits=(0.2,0.2), inclusive=(True,True),
+                    alpha=0.05, axis=None):
+    """
+    Selected confidence interval of the trimmed mean along the given axis.
+
+    Parameters
+    ----------
+    data : array_like
+        Input data.
+    limits : {None, tuple}, optional
+        None or a two item tuple.
+        Tuple of the percentages to cut on each side of the array, with respect
+        to the number of unmasked data, as floats between 0. and 1. If ``n``
+        is the number of unmasked data before trimming, then
+        (``n * limits[0]``)th smallest data and (``n * limits[1]``)th
+        largest data are masked.  The total number of unmasked data after
+        trimming is ``n * (1. - sum(limits))``.
+        The value of one limit can be set to None to indicate an open interval.
+
+        Defaults to (0.2, 0.2).
+    inclusive : (2,) tuple of boolean, optional
+        If relative==False, tuple indicating whether values exactly equal to
+        the absolute limits are allowed.
+        If relative==True, tuple indicating whether the number of data being
+        masked on each side should be rounded (True) or truncated (False).
+
+        Defaults to (True, True).
+    alpha : float, optional
+        Confidence level of the intervals.
+
+        Defaults to 0.05.
+    axis : int, optional
+        Axis along which to cut. If None, uses a flattened version of `data`.
+
+        Defaults to None.
+
+    Returns
+    -------
+    trimmed_mean_ci : (2,) ndarray
+        The lower and upper confidence intervals of the trimmed data.
+
+    """
+    data = ma.array(data, copy=False)
+    trimmed = mstats.trimr(data, limits=limits, inclusive=inclusive, axis=axis)
+    tmean = trimmed.mean(axis)
+    tstde = mstats.trimmed_stde(data,limits=limits,inclusive=inclusive,axis=axis)
+    df = trimmed.count(axis) - 1
+    tppf = t.ppf(1-alpha/2.,df)
+    return np.array((tmean - tppf*tstde, tmean+tppf*tstde))
+
+
+def mjci(data, prob=(0.25, 0.5, 0.75), axis=None):
+    """
+    Returns the Maritz-Jarrett estimators of the standard error of selected
+    experimental quantiles of the data.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data array.
+    prob : sequence, optional
+        Sequence of quantiles to compute.
+    axis : int or None, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+
+    """
+    def _mjci_1D(data, p):
+        data = np.sort(data.compressed())
+        n = data.size
+        prob = (np.array(p) * n + 0.5).astype(int)
+        betacdf = beta.cdf
+
+        mj = np.empty(len(prob), float64)
+        x = np.arange(1,n+1, dtype=float64) / n
+        y = x - 1./n
+        for (i,m) in enumerate(prob):
+            W = betacdf(x,m-1,n-m) - betacdf(y,m-1,n-m)
+            C1 = np.dot(W,data)
+            C2 = np.dot(W,data**2)
+            mj[i] = np.sqrt(C2 - C1**2)
+        return mj
+
+    data = ma.array(data, copy=False)
+    if data.ndim > 2:
+        raise ValueError("Array 'data' must be at most two dimensional, "
+                         "but got data.ndim = %d" % data.ndim)
+
+    p = np.atleast_1d(np.asarray(prob))
+    # Computes quantiles along axis (or globally)
+    if (axis is None):
+        return _mjci_1D(data, p)
+    else:
+        return ma.apply_along_axis(_mjci_1D, axis, data, p)
+
+
+def mquantiles_cimj(data, prob=(0.25, 0.50, 0.75), alpha=0.05, axis=None):
+    """
+    Computes the alpha confidence interval for the selected quantiles of the
+    data, with Maritz-Jarrett estimators.
+
+    Parameters
+    ----------
+    data : ndarray
+        Data array.
+    prob : sequence, optional
+        Sequence of quantiles to compute.
+    alpha : float, optional
+        Confidence level of the intervals.
+    axis : int or None, optional
+        Axis along which to compute the quantiles.
+        If None, use a flattened array.
+
+    Returns
+    -------
+    ci_lower : ndarray
+        The lower boundaries of the confidence interval.  Of the same length as
+        `prob`.
+    ci_upper : ndarray
+        The upper boundaries of the confidence interval.  Of the same length as
+        `prob`.
+
+    """
+    alpha = min(alpha, 1 - alpha)
+    z = norm.ppf(1 - alpha/2.)
+    xq = mstats.mquantiles(data, prob, alphap=0, betap=0, axis=axis)
+    smj = mjci(data, prob, axis=axis)
+    return (xq - z * smj, xq + z * smj)
+
+
+def median_cihs(data, alpha=0.05, axis=None):
+    """
+    Computes the alpha-level confidence interval for the median of the data.
+
+    Uses the Hettmasperger-Sheather method.
+
+    Parameters
+    ----------
+    data : array_like
+        Input data. Masked values are discarded. The input should be 1D only,
+        or `axis` should be set to None.
+    alpha : float, optional
+        Confidence level of the intervals.
+    axis : int or None, optional
+        Axis along which to compute the quantiles. If None, use a flattened
+        array.
+
+    Returns
+    -------
+    median_cihs
+        Alpha level confidence interval.
+
+    """
+    def _cihs_1D(data, alpha):
+        data = np.sort(data.compressed())
+        n = len(data)
+        alpha = min(alpha, 1-alpha)
+        k = int(binom._ppf(alpha/2., n, 0.5))
+        gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5)
+        if gk < 1-alpha:
+            k -= 1
+            gk = binom.cdf(n-k,n,0.5) - binom.cdf(k-1,n,0.5)
+        gkk = binom.cdf(n-k-1,n,0.5) - binom.cdf(k,n,0.5)
+        I = (gk - 1 + alpha)/(gk - gkk)
+        lambd = (n-k) * I / float(k + (n-2*k)*I)
+        lims = (lambd*data[k] + (1-lambd)*data[k-1],
+                lambd*data[n-k-1] + (1-lambd)*data[n-k])
+        return lims
+    data = ma.array(data, copy=False)
+    # Computes quantiles along axis (or globally)
+    if (axis is None):
+        result = _cihs_1D(data, alpha)
+    else:
+        if data.ndim > 2:
+            raise ValueError("Array 'data' must be at most two dimensional, "
+                             "but got data.ndim = %d" % data.ndim)
+        result = ma.apply_along_axis(_cihs_1D, axis, data, alpha)
+
+    return result
+
+
+def compare_medians_ms(group_1, group_2, axis=None):
+    """
+    Compares the medians from two independent groups along the given axis.
+
+    The comparison is performed using the McKean-Schrader estimate of the
+    standard error of the medians.
+
+    Parameters
+    ----------
+    group_1 : array_like
+        First dataset.  Has to be of size >=7.
+    group_2 : array_like
+        Second dataset.  Has to be of size >=7.
+    axis : int, optional
+        Axis along which the medians are estimated. If None, the arrays are
+        flattened.  If `axis` is not None, then `group_1` and `group_2`
+        should have the same shape.
+
+    Returns
+    -------
+    compare_medians_ms : {float, ndarray}
+        If `axis` is None, then returns a float, otherwise returns a 1-D
+        ndarray of floats with a length equal to the length of `group_1`
+        along `axis`.
+
+    Examples
+    --------
+
+    >>> from scipy import stats
+    >>> a = [1, 2, 3, 4, 5, 6, 7]
+    >>> b = [8, 9, 10, 11, 12, 13, 14]
+    >>> stats.mstats.compare_medians_ms(a, b, axis=None)
+    1.0693225866553746e-05
+
+    The function is vectorized to compute along a given axis.
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> x = rng.random(size=(3, 7))
+    >>> y = rng.random(size=(3, 8))
+    >>> stats.mstats.compare_medians_ms(x, y, axis=1)
+    array([0.36908985, 0.36092538, 0.2765313 ])
+
+    References
+    ----------
+    .. [1] McKean, Joseph W., and Ronald M. Schrader. "A comparison of methods
+       for studentizing the sample median." Communications in
+       Statistics-Simulation and Computation 13.6 (1984): 751-773.
+
+    """
+    (med_1, med_2) = (ma.median(group_1,axis=axis), ma.median(group_2,axis=axis))
+    (std_1, std_2) = (mstats.stde_median(group_1, axis=axis),
+                      mstats.stde_median(group_2, axis=axis))
+    W = np.abs(med_1 - med_2) / ma.sqrt(std_1**2 + std_2**2)
+    return 1 - norm.cdf(W)
+
+
+def idealfourths(data, axis=None):
+    """
+    Returns an estimate of the lower and upper quartiles.
+
+    Uses the ideal fourths algorithm.
+
+    Parameters
+    ----------
+    data : array_like
+        Input array.
+    axis : int, optional
+        Axis along which the quartiles are estimated. If None, the arrays are
+        flattened.
+
+    Returns
+    -------
+    idealfourths : {list of floats, masked array}
+        Returns the two internal values that divide `data` into four parts
+        using the ideal fourths algorithm either along the flattened array
+        (if `axis` is None) or along `axis` of `data`.
+
+    """
+    def _idf(data):
+        x = data.compressed()
+        n = len(x)
+        if n < 3:
+            return [np.nan,np.nan]
+        (j,h) = divmod(n/4. + 5/12.,1)
+        j = int(j)
+        qlo = (1-h)*x[j-1] + h*x[j]
+        k = n - j
+        qup = (1-h)*x[k] + h*x[k-1]
+        return [qlo, qup]
+    data = ma.sort(data, axis=axis).view(MaskedArray)
+    if (axis is None):
+        return _idf(data)
+    else:
+        return ma.apply_along_axis(_idf, axis, data)
+
+
+def rsh(data, points=None):
+    """
+    Evaluates Rosenblatt's shifted histogram estimators for each data point.
+
+    Rosenblatt's estimator is a centered finite-difference approximation to the
+    derivative of the empirical cumulative distribution function.
+
+    Parameters
+    ----------
+    data : sequence
+        Input data, should be 1-D. Masked values are ignored.
+    points : sequence or None, optional
+        Sequence of points where to evaluate Rosenblatt shifted histogram.
+        If None, use the data.
+
+    """
+    data = ma.array(data, copy=False)
+    if points is None:
+        points = data
+    else:
+        points = np.atleast_1d(np.asarray(points))
+
+    if data.ndim != 1:
+        raise AttributeError("The input array should be 1D only !")
+
+    n = data.count()
+    r = idealfourths(data, axis=None)
+    h = 1.2 * (r[-1]-r[0]) / n**(1./5)
+    nhi = (data[:,None] <= points[None,:] + h).sum(0)
+    nlo = (data[:,None] < points[None,:] - h).sum(0)
+    return (nhi-nlo) / (2.*n*h)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_multicomp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_multicomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..164a57650dca442702b45f89168d5b4a747ef030
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_multicomp.py
@@ -0,0 +1,449 @@
+import warnings
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Literal
+
+import numpy as np
+
+from scipy import stats
+from scipy.optimize import minimize_scalar
+from scipy.stats._common import ConfidenceInterval
+from scipy.stats._qmc import check_random_state
+from scipy.stats._stats_py import _var
+from scipy._lib._util import _transition_to_rng, DecimalNumber, SeedType
+
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+
+__all__ = [
+    'dunnett'
+]
+
+
+@dataclass
+class DunnettResult:
+    """Result object returned by `scipy.stats.dunnett`.
+
+    Attributes
+    ----------
+    statistic : float ndarray
+        The computed statistic of the test for each comparison. The element
+        at index ``i`` is the statistic for the comparison between
+        groups ``i`` and the control.
+    pvalue : float ndarray
+        The computed p-value of the test for each comparison. The element
+        at index ``i`` is the p-value for the comparison between
+        group ``i`` and the control.
+    """
+    statistic: np.ndarray
+    pvalue: np.ndarray
+    _alternative: Literal['two-sided', 'less', 'greater'] = field(repr=False)
+    _rho: np.ndarray = field(repr=False)
+    _df: int = field(repr=False)
+    _std: float = field(repr=False)
+    _mean_samples: np.ndarray = field(repr=False)
+    _mean_control: np.ndarray = field(repr=False)
+    _n_samples: np.ndarray = field(repr=False)
+    _n_control: int = field(repr=False)
+    _rng: SeedType = field(repr=False)
+    _ci: ConfidenceInterval | None = field(default=None, repr=False)
+    _ci_cl: DecimalNumber | None = field(default=None, repr=False)
+
+    def __str__(self):
+        # Note: `__str__` prints the confidence intervals from the most
+        # recent call to `confidence_interval`. If it has not been called,
+        # it will be called with the default CL of .95.
+        if self._ci is None:
+            self.confidence_interval(confidence_level=.95)
+        s = (
+            "Dunnett's test"
+            f" ({self._ci_cl*100:.1f}% Confidence Interval)\n"
+            "Comparison               Statistic  p-value  Lower CI  Upper CI\n"
+        )
+        for i in range(self.pvalue.size):
+            s += (f" (Sample {i} - Control) {self.statistic[i]:>10.3f}"
+                  f"{self.pvalue[i]:>10.3f}"
+                  f"{self._ci.low[i]:>10.3f}"
+                  f"{self._ci.high[i]:>10.3f}\n")
+
+        return s
+
+    def _allowance(
+        self, confidence_level: DecimalNumber = 0.95, tol: DecimalNumber = 1e-3
+    ) -> float:
+        """Allowance.
+
+        It is the quantity to add/subtract from the observed difference
+        between the means of observed groups and the mean of the control
+        group. The result gives confidence limits.
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            Confidence level for the computed confidence interval.
+            Default is .95.
+        tol : float, optional
+            A tolerance for numerical optimization: the allowance will produce
+            a confidence within ``10*tol*(1 - confidence_level)`` of the
+            specified level, or a warning will be emitted. Tight tolerances
+            may be impractical due to noisy evaluation of the objective.
+            Default is 1e-3.
+
+        Returns
+        -------
+        allowance : float
+            Allowance around the mean.
+        """
+        alpha = 1 - confidence_level
+
+        def pvalue_from_stat(statistic):
+            statistic = np.array(statistic)
+            sf = _pvalue_dunnett(
+                rho=self._rho, df=self._df,
+                statistic=statistic, alternative=self._alternative,
+                rng=self._rng
+            )
+            return abs(sf - alpha)/alpha
+
+        # Evaluation of `pvalue_from_stat` is noisy due to the use of RQMC to
+        # evaluate `multivariate_t.cdf`. `minimize_scalar` is not designed
+        # to tolerate a noisy objective function and may fail to find the
+        # minimum accurately. We mitigate this possibility with the validation
+        # step below, but implementation of a noise-tolerant root finder or
+        # minimizer would be a welcome enhancement. See gh-18150.
+        res = minimize_scalar(pvalue_from_stat, method='brent', tol=tol)
+        critical_value = res.x
+
+        # validation
+        # tol*10 because tol=1e-3 means we tolerate a 1% change at most
+        if res.success is False or res.fun >= tol*10:
+            warnings.warn(
+                "Computation of the confidence interval did not converge to "
+                "the desired level. The confidence level corresponding with "
+                f"the returned interval is approximately {alpha*(1+res.fun)}.",
+                stacklevel=3
+            )
+
+        # From [1] p. 1101 between (1) and (3)
+        allowance = critical_value*self._std*np.sqrt(
+            1/self._n_samples + 1/self._n_control
+        )
+        return abs(allowance)
+
+    def confidence_interval(
+        self, confidence_level: DecimalNumber = 0.95
+    ) -> ConfidenceInterval:
+        """Compute the confidence interval for the specified confidence level.
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            Confidence level for the computed confidence interval.
+            Default is .95.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` object
+            The object has attributes ``low`` and ``high`` that hold the
+            lower and upper bounds of the confidence intervals for each
+            comparison. The high and low values are accessible for each
+            comparison at index ``i`` for each group ``i``.
+
+        """
+        # check to see if the supplied confidence level matches that of the
+        # previously computed CI.
+        if (self._ci is not None) and (confidence_level == self._ci_cl):
+            return self._ci
+
+        if not (0 < confidence_level < 1):
+            raise ValueError("Confidence level must be between 0 and 1.")
+
+        allowance = self._allowance(confidence_level=confidence_level)
+        diff_means = self._mean_samples - self._mean_control
+
+        low = diff_means-allowance
+        high = diff_means+allowance
+
+        if self._alternative == 'greater':
+            high = [np.inf] * len(diff_means)
+        elif self._alternative == 'less':
+            low = [-np.inf] * len(diff_means)
+
+        self._ci_cl = confidence_level
+        self._ci = ConfidenceInterval(
+            low=low,
+            high=high
+        )
+        return self._ci
+
+
+@_transition_to_rng('random_state', replace_doc=False)
+def dunnett(
+    *samples: "npt.ArrayLike",  # noqa: D417
+    control: "npt.ArrayLike",
+    alternative: Literal['two-sided', 'less', 'greater'] = "two-sided",
+    rng: SeedType = None
+) -> DunnettResult:
+    """Dunnett's test: multiple comparisons of means against a control group.
+
+    This is an implementation of Dunnett's original, single-step test as
+    described in [1]_.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : 1D array_like
+        The sample measurements for each experimental group.
+    control : 1D array_like
+        The sample measurements for the control group.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+
+        The null hypothesis is that the means of the distributions underlying
+        the samples and control are equal. The following alternative
+        hypotheses are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          and control are unequal.
+        * 'less': the means of the distributions underlying the samples
+          are less than the mean of the distribution underlying the control.
+        * 'greater': the means of the distributions underlying the
+          samples are greater than the mean of the distribution underlying
+          the control.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `random_state` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `random_state` keyword will emit warnings. Following a
+            deprecation period, the `random_state` keyword will be removed.
+
+    Returns
+    -------
+    res : `~scipy.stats._result_classes.DunnettResult`
+        An object containing attributes:
+
+        statistic : float ndarray
+            The computed statistic of the test for each comparison. The element
+            at index ``i`` is the statistic for the comparison between
+            groups ``i`` and the control.
+        pvalue : float ndarray
+            The computed p-value of the test for each comparison. The element
+            at index ``i`` is the p-value for the comparison between
+            group ``i`` and the control.
+
+        And the following method:
+
+        confidence_interval(confidence_level=0.95) :
+            Compute the difference in means of the groups
+            with the control +- the allowance.
+
+    See Also
+    --------
+    tukey_hsd : performs pairwise comparison of means.
+    :ref:`hypothesis_dunnett` : Extended example
+
+    Notes
+    -----
+    Like the independent-sample t-test, Dunnett's test [1]_ is used to make
+    inferences about the means of distributions from which samples were drawn.
+    However, when multiple t-tests are performed at a fixed significance level,
+    the "family-wise error rate" - the probability of incorrectly rejecting the
+    null hypothesis in at least one test - will exceed the significance level.
+    Dunnett's test is designed to perform multiple comparisons while
+    controlling the family-wise error rate.
+
+    Dunnett's test compares the means of multiple experimental groups
+    against a single control group. Tukey's Honestly Significant Difference Test
+    is another multiple-comparison test that controls the family-wise error
+    rate, but `tukey_hsd` performs *all* pairwise comparisons between groups.
+    When pairwise comparisons between experimental groups are not needed,
+    Dunnett's test is preferable due to its higher power.
+
+    The use of this test relies on several assumptions.
+
+    1. The observations are independent within and among groups.
+    2. The observations within each group are normally distributed.
+    3. The distributions from which the samples are drawn have the same finite
+       variance.
+
+    References
+    ----------
+    .. [1] Dunnett, Charles W. (1955) "A Multiple Comparison Procedure for
+           Comparing Several Treatments with a Control." Journal of the American
+           Statistical Association, 50:272, 1096-1121,
+           :doi:`10.1080/01621459.1955.10501294`
+    .. [2] Thomson, M. L., & Short, M. D. (1969). Mucociliary function in
+           health, chronic obstructive airway disease, and asbestosis. Journal
+           of applied physiology, 26(5), 535-539.
+           :doi:`10.1152/jappl.1969.26.5.535`
+
+    Examples
+    --------
+    We'll use data from [2]_, Table 1. The null hypothesis is that the means of
+    the distributions underlying the samples and control are equal.
+
+    First, we test that the means of the distributions underlying the samples
+    and control are unequal (``alternative='two-sided'``, the default).
+
+    >>> import numpy as np
+    >>> from scipy.stats import dunnett
+    >>> samples = [[3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]]
+    >>> control = [2.9, 3.0, 2.5, 2.6, 3.2]
+    >>> res = dunnett(*samples, control=control)
+    >>> res.statistic
+    array([ 0.90874545, -0.05007117])
+    >>> res.pvalue
+    array([0.58325114, 0.99819341])
+
+    Now, we test that the means of the distributions underlying the samples are
+    greater than the mean of the distribution underlying the control.
+
+    >>> res = dunnett(*samples, control=control, alternative='greater')
+    >>> res.statistic
+    array([ 0.90874545, -0.05007117])
+    >>> res.pvalue
+    array([0.30230596, 0.69115597])
+
+    For a more detailed example, see :ref:`hypothesis_dunnett`.
+    """
+    samples_, control_, rng = _iv_dunnett(
+        samples=samples, control=control,
+        alternative=alternative, rng=rng
+    )
+
+    rho, df, n_group, n_samples, n_control = _params_dunnett(
+        samples=samples_, control=control_
+    )
+
+    statistic, std, mean_control, mean_samples = _statistic_dunnett(
+        samples_, control_, df, n_samples, n_control
+    )
+
+    pvalue = _pvalue_dunnett(
+        rho=rho, df=df, statistic=statistic, alternative=alternative, rng=rng
+    )
+
+    return DunnettResult(
+        statistic=statistic, pvalue=pvalue,
+        _alternative=alternative,
+        _rho=rho, _df=df, _std=std,
+        _mean_samples=mean_samples,
+        _mean_control=mean_control,
+        _n_samples=n_samples,
+        _n_control=n_control,
+        _rng=rng
+    )
+
+
+def _iv_dunnett(
+    samples: Sequence["npt.ArrayLike"],
+    control: "npt.ArrayLike",
+    alternative: Literal['two-sided', 'less', 'greater'],
+    rng: SeedType
+) -> tuple[list[np.ndarray], np.ndarray, SeedType]:
+    """Input validation for Dunnett's test."""
+    rng = check_random_state(rng)
+
+    if alternative not in {'two-sided', 'less', 'greater'}:
+        raise ValueError(
+            "alternative must be 'less', 'greater' or 'two-sided'"
+        )
+
+    ndim_msg = "Control and samples groups must be 1D arrays"
+    n_obs_msg = "Control and samples groups must have at least 1 observation"
+
+    control = np.asarray(control)
+    samples_ = [np.asarray(sample) for sample in samples]
+
+    # samples checks
+    samples_control: list[np.ndarray] = samples_ + [control]
+    for sample in samples_control:
+        if sample.ndim > 1:
+            raise ValueError(ndim_msg)
+
+        if sample.size < 1:
+            raise ValueError(n_obs_msg)
+
+    return samples_, control, rng
+
+
+def _params_dunnett(
+    samples: list[np.ndarray], control: np.ndarray
+) -> tuple[np.ndarray, int, int, np.ndarray, int]:
+    """Specific parameters for Dunnett's test.
+
+    Degree of freedom is the number of observations minus the number of groups
+    including the control.
+    """
+    n_samples = np.array([sample.size for sample in samples])
+
+    # From [1] p. 1100 d.f. = (sum N)-(p+1)
+    n_sample = n_samples.sum()
+    n_control = control.size
+    n = n_sample + n_control
+    n_groups = len(samples)
+    df = n - n_groups - 1
+
+    # From [1] p. 1103 rho_ij = 1/sqrt((N0/Ni+1)(N0/Nj+1))
+    rho = n_control/n_samples + 1
+    rho = 1/np.sqrt(rho[:, None] * rho[None, :])
+    np.fill_diagonal(rho, 1)
+
+    return rho, df, n_groups, n_samples, n_control
+
+
+def _statistic_dunnett(
+    samples: list[np.ndarray], control: np.ndarray, df: int,
+    n_samples: np.ndarray, n_control: int
+) -> tuple[np.ndarray, float, np.ndarray, np.ndarray]:
+    """Statistic of Dunnett's test.
+
+    Computation based on the original single-step test from [1].
+    """
+    mean_control = np.mean(control)
+    mean_samples = np.array([np.mean(sample) for sample in samples])
+    all_samples = [control] + samples
+    all_means = np.concatenate([[mean_control], mean_samples])
+
+    # Variance estimate s^2 from [1] Eq. 1
+    s2 = np.sum([_var(sample, mean=mean)*sample.size
+                 for sample, mean in zip(all_samples, all_means)]) / df
+    std = np.sqrt(s2)
+
+    # z score inferred from [1] unlabeled equation after Eq. 1
+    z = (mean_samples - mean_control) / np.sqrt(1/n_samples + 1/n_control)
+
+    return z / std, std, mean_control, mean_samples
+
+
+def _pvalue_dunnett(
+    rho: np.ndarray, df: int, statistic: np.ndarray,
+    alternative: Literal['two-sided', 'less', 'greater'],
+    rng: SeedType = None
+) -> np.ndarray:
+    """pvalue from the multivariate t-distribution.
+
+    Critical values come from the multivariate student-t distribution.
+    """
+    statistic = statistic.reshape(-1, 1)
+
+    mvt = stats.multivariate_t(shape=rho, df=df, seed=rng)
+    if alternative == "two-sided":
+        statistic = abs(statistic)
+        pvalue = 1 - mvt.cdf(statistic, lower_limit=-statistic)
+    elif alternative == "greater":
+        pvalue = 1 - mvt.cdf(statistic, lower_limit=-np.inf)
+    else:
+        pvalue = 1 - mvt.cdf(np.inf, lower_limit=statistic)
+
+    return np.atleast_1d(pvalue)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_multivariate.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_multivariate.py
new file mode 100644
index 0000000000000000000000000000000000000000..be303fe087bd45eb63ee0c9c1b4244fafc1adcdc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_multivariate.py
@@ -0,0 +1,7305 @@
+#
+# Author: Joris Vankerschaver 2013
+#
+import math
+import threading
+import numpy as np
+import scipy.linalg
+from scipy._lib import doccer
+from scipy.special import (gammaln, psi, multigammaln, xlogy, entr, betaln,
+                           ive, loggamma)
+from scipy import special
+from scipy._lib._util import check_random_state, _lazywhere
+from scipy.linalg.blas import drot, get_blas_funcs
+from ._continuous_distns import norm, invgamma
+from ._discrete_distns import binom
+from . import _mvn, _covariance, _rcont
+from ._qmvnt import _qmvt
+from ._morestats import directional_stats
+from scipy.optimize import root_scalar
+
+__all__ = ['multivariate_normal',
+           'matrix_normal',
+           'dirichlet',
+           'dirichlet_multinomial',
+           'wishart',
+           'invwishart',
+           'multinomial',
+           'special_ortho_group',
+           'ortho_group',
+           'random_correlation',
+           'unitary_group',
+           'multivariate_t',
+           'multivariate_hypergeom',
+           'random_table',
+           'uniform_direction',
+           'vonmises_fisher',
+           'normal_inverse_gamma']
+
+_LOG_2PI = np.log(2 * np.pi)
+_LOG_2 = np.log(2)
+_LOG_PI = np.log(np.pi)
+MVN_LOCK = threading.Lock()
+
+
+_doc_random_state = """\
+seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+    Used for drawing random variates.
+    If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+    If `seed` is an int, a new ``RandomState`` instance is used, seeded
+    with seed.
+    If `seed` is already a ``RandomState`` or ``Generator`` instance,
+    then that object is used.
+    Default is `None`.
+"""
+
+
+def _squeeze_output(out):
+    """
+    Remove single-dimensional entries from array and convert to scalar,
+    if necessary.
+    """
+    out = out.squeeze()
+    if out.ndim == 0:
+        out = out[()]
+    return out
+
+
+def _eigvalsh_to_eps(spectrum, cond=None, rcond=None):
+    """Determine which eigenvalues are "small" given the spectrum.
+
+    This is for compatibility across various linear algebra functions
+    that should agree about whether or not a Hermitian matrix is numerically
+    singular and what is its numerical matrix rank.
+    This is designed to be compatible with scipy.linalg.pinvh.
+
+    Parameters
+    ----------
+    spectrum : 1d ndarray
+        Array of eigenvalues of a Hermitian matrix.
+    cond, rcond : float, optional
+        Cutoff for small eigenvalues.
+        Singular values smaller than rcond * largest_eigenvalue are
+        considered zero.
+        If None or -1, suitable machine precision is used.
+
+    Returns
+    -------
+    eps : float
+        Magnitude cutoff for numerical negligibility.
+
+    """
+    if rcond is not None:
+        cond = rcond
+    if cond in [None, -1]:
+        t = spectrum.dtype.char.lower()
+        factor = {'f': 1E3, 'd': 1E6}
+        cond = factor[t] * np.finfo(t).eps
+    eps = cond * np.max(abs(spectrum))
+    return eps
+
+
+def _pinv_1d(v, eps=1e-5):
+    """A helper function for computing the pseudoinverse.
+
+    Parameters
+    ----------
+    v : iterable of numbers
+        This may be thought of as a vector of eigenvalues or singular values.
+    eps : float
+        Values with magnitude no greater than eps are considered negligible.
+
+    Returns
+    -------
+    v_pinv : 1d float ndarray
+        A vector of pseudo-inverted numbers.
+
+    """
+    return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float)
+
+
+class _PSD:
+    """
+    Compute coordinated functions of a symmetric positive semidefinite matrix.
+
+    This class addresses two issues.  Firstly it allows the pseudoinverse,
+    the logarithm of the pseudo-determinant, and the rank of the matrix
+    to be computed using one call to eigh instead of three.
+    Secondly it allows these functions to be computed in a way
+    that gives mutually compatible results.
+    All of the functions are computed with a common understanding as to
+    which of the eigenvalues are to be considered negligibly small.
+    The functions are designed to coordinate with scipy.linalg.pinvh()
+    but not necessarily with np.linalg.det() or with np.linalg.matrix_rank().
+
+    Parameters
+    ----------
+    M : array_like
+        Symmetric positive semidefinite matrix (2-D).
+    cond, rcond : float, optional
+        Cutoff for small eigenvalues.
+        Singular values smaller than rcond * largest_eigenvalue are
+        considered zero.
+        If None or -1, suitable machine precision is used.
+    lower : bool, optional
+        Whether the pertinent array data is taken from the lower
+        or upper triangle of M. (Default: lower)
+    check_finite : bool, optional
+        Whether to check that the input matrices contain only finite
+        numbers. Disabling may give a performance gain, but may result
+        in problems (crashes, non-termination) if the inputs do contain
+        infinities or NaNs.
+    allow_singular : bool, optional
+        Whether to allow a singular matrix.  (Default: True)
+
+    Notes
+    -----
+    The arguments are similar to those of scipy.linalg.pinvh().
+
+    """
+
+    def __init__(self, M, cond=None, rcond=None, lower=True,
+                 check_finite=True, allow_singular=True):
+        self._M = np.asarray(M)
+
+        # Compute the symmetric eigendecomposition.
+        # Note that eigh takes care of array conversion, chkfinite,
+        # and assertion that the matrix is square.
+        s, u = scipy.linalg.eigh(M, lower=lower, check_finite=check_finite)
+
+        eps = _eigvalsh_to_eps(s, cond, rcond)
+        if np.min(s) < -eps:
+            msg = "The input matrix must be symmetric positive semidefinite."
+            raise ValueError(msg)
+        d = s[s > eps]
+        if len(d) < len(s) and not allow_singular:
+            msg = ("When `allow_singular is False`, the input matrix must be "
+                   "symmetric positive definite.")
+            raise np.linalg.LinAlgError(msg)
+        s_pinv = _pinv_1d(s, eps)
+        U = np.multiply(u, np.sqrt(s_pinv))
+
+        # Save the eigenvector basis, and tolerance for testing support
+        self.eps = 1e3*eps
+        self.V = u[:, s <= eps]
+
+        # Initialize the eagerly precomputed attributes.
+        self.rank = len(d)
+        self.U = U
+        self.log_pdet = np.sum(np.log(d))
+
+        # Initialize attributes to be lazily computed.
+        self._pinv = None
+
+    def _support_mask(self, x):
+        """
+        Check whether x lies in the support of the distribution.
+        """
+        residual = np.linalg.norm(x @ self.V, axis=-1)
+        in_support = residual < self.eps
+        return in_support
+
+    @property
+    def pinv(self):
+        if self._pinv is None:
+            self._pinv = np.dot(self.U, self.U.T)
+        return self._pinv
+
+
+class multi_rv_generic:
+    """
+    Class which encapsulates common functionality between all multivariate
+    distributions.
+    """
+    def __init__(self, seed=None):
+        super().__init__()
+        self._random_state = check_random_state(seed)
+
+    @property
+    def random_state(self):
+        """ Get or set the Generator object for generating random variates.
+
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+        """
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, seed):
+        self._random_state = check_random_state(seed)
+
+    def _get_random_state(self, random_state):
+        if random_state is not None:
+            return check_random_state(random_state)
+        else:
+            return self._random_state
+
+
+class multi_rv_frozen:
+    """
+    Class which encapsulates common functionality between all frozen
+    multivariate distributions.
+    """
+    @property
+    def random_state(self):
+        return self._dist._random_state
+
+    @random_state.setter
+    def random_state(self, seed):
+        self._dist._random_state = check_random_state(seed)
+
+
+_mvn_doc_default_callparams = """\
+mean : array_like, default: ``[0]``
+    Mean of the distribution.
+cov : array_like or `Covariance`, default: ``[1]``
+    Symmetric positive (semi)definite covariance matrix of the distribution.
+allow_singular : bool, default: ``False``
+    Whether to allow a singular covariance matrix. This is ignored if `cov` is
+    a `Covariance` object.
+"""
+
+_mvn_doc_callparams_note = """\
+Setting the parameter `mean` to `None` is equivalent to having `mean`
+be the zero-vector. The parameter `cov` can be a scalar, in which case
+the covariance matrix is the identity times that value, a vector of
+diagonal entries for the covariance matrix, a two-dimensional array_like,
+or a `Covariance` object.
+"""
+
+_mvn_doc_frozen_callparams = ""
+
+_mvn_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+mvn_docdict_params = {
+    '_mvn_doc_default_callparams': _mvn_doc_default_callparams,
+    '_mvn_doc_callparams_note': _mvn_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+mvn_docdict_noparams = {
+    '_mvn_doc_default_callparams': _mvn_doc_frozen_callparams,
+    '_mvn_doc_callparams_note': _mvn_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class multivariate_normal_gen(multi_rv_generic):
+    r"""A multivariate normal random variable.
+
+    The `mean` keyword specifies the mean. The `cov` keyword specifies the
+    covariance matrix.
+
+    Methods
+    -------
+    pdf(x, mean=None, cov=1, allow_singular=False)
+        Probability density function.
+    logpdf(x, mean=None, cov=1, allow_singular=False)
+        Log of the probability density function.
+    cdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5, lower_limit=None)
+        Cumulative distribution function.
+    logcdf(x, mean=None, cov=1, allow_singular=False, maxpts=1000000*dim, abseps=1e-5, releps=1e-5)
+        Log of the cumulative distribution function.
+    rvs(mean=None, cov=1, size=1, random_state=None)
+        Draw random samples from a multivariate normal distribution.
+    entropy(mean=None, cov=1)
+        Compute the differential entropy of the multivariate normal.
+    fit(x, fix_mean=None, fix_cov=None)
+        Fit a multivariate normal distribution to data.
+
+    Parameters
+    ----------
+    %(_mvn_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_mvn_doc_callparams_note)s
+
+    The covariance matrix `cov` may be an instance of a subclass of
+    `Covariance`, e.g. `scipy.stats.CovViaPrecision`. If so, `allow_singular`
+    is ignored.
+
+    Otherwise, `cov` must be a symmetric positive semidefinite
+    matrix when `allow_singular` is True; it must be (strictly) positive
+    definite when `allow_singular` is False.
+    Symmetry is not checked; only the lower triangular portion is used.
+    The determinant and inverse of `cov` are computed
+    as the pseudo-determinant and pseudo-inverse, respectively, so
+    that `cov` does not need to have full rank.
+
+    The probability density function for `multivariate_normal` is
+
+    .. math::
+
+        f(x) = \frac{1}{\sqrt{(2 \pi)^k \det \Sigma}}
+               \exp\left( -\frac{1}{2} (x - \mu)^T \Sigma^{-1} (x - \mu) \right),
+
+    where :math:`\mu` is the mean, :math:`\Sigma` the covariance matrix,
+    :math:`k` the rank of :math:`\Sigma`. In case of singular :math:`\Sigma`,
+    SciPy extends this definition according to [1]_.
+
+    .. versionadded:: 0.14.0
+
+    References
+    ----------
+    .. [1] Multivariate Normal Distribution - Degenerate Case, Wikipedia,
+           https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Degenerate_case
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import multivariate_normal
+
+    >>> x = np.linspace(0, 5, 10, endpoint=False)
+    >>> y = multivariate_normal.pdf(x, mean=2.5, cov=0.5); y
+    array([ 0.00108914,  0.01033349,  0.05946514,  0.20755375,  0.43939129,
+            0.56418958,  0.43939129,  0.20755375,  0.05946514,  0.01033349])
+    >>> fig1 = plt.figure()
+    >>> ax = fig1.add_subplot(111)
+    >>> ax.plot(x, y)
+    >>> plt.show()
+
+    Alternatively, the object may be called (as a function) to fix the mean
+    and covariance parameters, returning a "frozen" multivariate normal
+    random variable:
+
+    >>> rv = multivariate_normal(mean=None, cov=1, allow_singular=False)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # mean and covariance fixed.
+
+    The input quantiles can be any shape of array, as long as the last
+    axis labels the components.  This allows us for instance to
+    display the frozen pdf for a non-isotropic random variable in 2D as
+    follows:
+
+    >>> x, y = np.mgrid[-1:1:.01, -1:1:.01]
+    >>> pos = np.dstack((x, y))
+    >>> rv = multivariate_normal([0.5, -0.2], [[2.0, 0.3], [0.3, 0.5]])
+    >>> fig2 = plt.figure()
+    >>> ax2 = fig2.add_subplot(111)
+    >>> ax2.contourf(x, y, rv.pdf(pos))
+
+    """  # noqa: E501
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, mvn_docdict_params)
+
+    def __call__(self, mean=None, cov=1, allow_singular=False, seed=None):
+        """Create a frozen multivariate normal distribution.
+
+        See `multivariate_normal_frozen` for more information.
+        """
+        return multivariate_normal_frozen(mean, cov,
+                                          allow_singular=allow_singular,
+                                          seed=seed)
+
+    def _process_parameters(self, mean, cov, allow_singular=True):
+        """
+        Infer dimensionality from mean or covariance matrix, ensure that
+        mean and covariance are full vector resp. matrix.
+        """
+        if isinstance(cov, _covariance.Covariance):
+            return self._process_parameters_Covariance(mean, cov)
+        else:
+            # Before `Covariance` classes were introduced,
+            # `multivariate_normal` accepted plain arrays as `cov` and used the
+            # following input validation. To avoid disturbing the behavior of
+            # `multivariate_normal` when plain arrays are used, we use the
+            # original input validation here.
+            dim, mean, cov = self._process_parameters_psd(None, mean, cov)
+            # After input validation, some methods then processed the arrays
+            # with a `_PSD` object and used that to perform computation.
+            # To avoid branching statements in each method depending on whether
+            # `cov` is an array or `Covariance` object, we always process the
+            # array with `_PSD`, and then use wrapper that satisfies the
+            # `Covariance` interface, `CovViaPSD`.
+            psd = _PSD(cov, allow_singular=allow_singular)
+            cov_object = _covariance.CovViaPSD(psd)
+            return dim, mean, cov_object
+
+    def _process_parameters_Covariance(self, mean, cov):
+        dim = cov.shape[-1]
+        mean = np.array([0.]) if mean is None else mean
+        message = (f"`cov` represents a covariance matrix in {dim} dimensions,"
+                   f"and so `mean` must be broadcastable to shape {(dim,)}")
+        try:
+            mean = np.broadcast_to(mean, dim)
+        except ValueError as e:
+            raise ValueError(message) from e
+        return dim, mean, cov
+
+    def _process_parameters_psd(self, dim, mean, cov):
+        # Try to infer dimensionality
+        if dim is None:
+            if mean is None:
+                if cov is None:
+                    dim = 1
+                else:
+                    cov = np.asarray(cov, dtype=float)
+                    if cov.ndim < 2:
+                        dim = 1
+                    else:
+                        dim = cov.shape[0]
+            else:
+                mean = np.asarray(mean, dtype=float)
+                dim = mean.size
+        else:
+            if not np.isscalar(dim):
+                raise ValueError("Dimension of random variable must be "
+                                 "a scalar.")
+
+        # Check input sizes and return full arrays for mean and cov if
+        # necessary
+        if mean is None:
+            mean = np.zeros(dim)
+        mean = np.asarray(mean, dtype=float)
+
+        if cov is None:
+            cov = 1.0
+        cov = np.asarray(cov, dtype=float)
+
+        if dim == 1:
+            mean = mean.reshape(1)
+            cov = cov.reshape(1, 1)
+
+        if mean.ndim != 1 or mean.shape[0] != dim:
+            raise ValueError("Array 'mean' must be a vector of length %d." %
+                             dim)
+        if cov.ndim == 0:
+            cov = cov * np.eye(dim)
+        elif cov.ndim == 1:
+            cov = np.diag(cov)
+        elif cov.ndim == 2 and cov.shape != (dim, dim):
+            rows, cols = cov.shape
+            if rows != cols:
+                msg = ("Array 'cov' must be square if it is two dimensional,"
+                       f" but cov.shape = {str(cov.shape)}.")
+            else:
+                msg = ("Dimension mismatch: array 'cov' is of shape %s,"
+                       " but 'mean' is a vector of length %d.")
+                msg = msg % (str(cov.shape), len(mean))
+            raise ValueError(msg)
+        elif cov.ndim > 2:
+            raise ValueError("Array 'cov' must be at most two-dimensional,"
+                             " but cov.ndim = %d" % cov.ndim)
+
+        return dim, mean, cov
+
+    def _process_quantiles(self, x, dim):
+        """
+        Adjust quantiles array so that last axis labels the components of
+        each data point.
+        """
+        x = np.asarray(x, dtype=float)
+
+        if x.ndim == 0:
+            x = x[np.newaxis]
+        elif x.ndim == 1:
+            if dim == 1:
+                x = x[:, np.newaxis]
+            else:
+                x = x[np.newaxis, :]
+
+        return x
+
+    def _logpdf(self, x, mean, cov_object):
+        """Log of the multivariate normal probability density function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability
+            density function
+        mean : ndarray
+            Mean of the distribution
+        cov_object : Covariance
+            An object representing the Covariance matrix
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        log_det_cov, rank = cov_object.log_pdet, cov_object.rank
+        dev = x - mean
+        if dev.ndim > 1:
+            log_det_cov = log_det_cov[..., np.newaxis]
+            rank = rank[..., np.newaxis]
+        maha = np.sum(np.square(cov_object.whiten(dev)), axis=-1)
+        return -0.5 * (rank * _LOG_2PI + log_det_cov + maha)
+
+    def logpdf(self, x, mean=None, cov=1, allow_singular=False):
+        """Log of the multivariate normal probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_mvn_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Log of the probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        """
+        params = self._process_parameters(mean, cov, allow_singular)
+        dim, mean, cov_object = params
+        x = self._process_quantiles(x, dim)
+        out = self._logpdf(x, mean, cov_object)
+        if np.any(cov_object.rank < dim):
+            out_of_bounds = ~cov_object._support_mask(x-mean)
+            out[out_of_bounds] = -np.inf
+        return _squeeze_output(out)
+
+    def pdf(self, x, mean=None, cov=1, allow_singular=False):
+        """Multivariate normal probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_mvn_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        """
+        params = self._process_parameters(mean, cov, allow_singular)
+        dim, mean, cov_object = params
+        x = self._process_quantiles(x, dim)
+        out = np.exp(self._logpdf(x, mean, cov_object))
+        if np.any(cov_object.rank < dim):
+            out_of_bounds = ~cov_object._support_mask(x-mean)
+            out[out_of_bounds] = 0.0
+        return _squeeze_output(out)
+
+    def _cdf(self, x, mean, cov, maxpts, abseps, releps, lower_limit):
+        """Multivariate normal cumulative distribution function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the cumulative distribution function.
+        mean : ndarray
+            Mean of the distribution
+        cov : array_like
+            Covariance matrix of the distribution
+        maxpts : integer
+            The maximum number of points to use for integration
+        abseps : float
+            Absolute error tolerance
+        releps : float
+            Relative error tolerance
+        lower_limit : array_like, optional
+            Lower limit of integration of the cumulative distribution function.
+            Default is negative infinity. Must be broadcastable with `x`.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'cdf' instead.
+
+
+        .. versionadded:: 1.0.0
+
+        """
+        lower = (np.full(mean.shape, -np.inf)
+                 if lower_limit is None else lower_limit)
+        # In 2d, _mvn.mvnun accepts input in which `lower` bound elements
+        # are greater than `x`. Not so in other dimensions. Fix this by
+        # ensuring that lower bounds are indeed lower when passed, then
+        # set signs of resulting CDF manually.
+        b, a = np.broadcast_arrays(x, lower)
+        i_swap = b < a
+        signs = (-1)**(i_swap.sum(axis=-1))  # odd # of swaps -> negative
+        a, b = a.copy(), b.copy()
+        a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
+        n = x.shape[-1]
+        limits = np.concatenate((a, b), axis=-1)
+
+        # mvnun expects 1-d arguments, so process points sequentially
+        def func1d(limits):
+            with MVN_LOCK:
+                return _mvn.mvnun(limits[:n], limits[n:], mean, cov,
+                                maxpts, abseps, releps)[0]
+
+        out = np.apply_along_axis(func1d, -1, limits) * signs
+        return _squeeze_output(out)
+
+    def logcdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None,
+               abseps=1e-5, releps=1e-5, *, lower_limit=None):
+        """Log of the multivariate normal cumulative distribution function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_mvn_doc_default_callparams)s
+        maxpts : integer, optional
+            The maximum number of points to use for integration
+            (default ``1000000*dim``)
+        abseps : float, optional
+            Absolute error tolerance (default 1e-5)
+        releps : float, optional
+            Relative error tolerance (default 1e-5)
+        lower_limit : array_like, optional
+            Lower limit of integration of the cumulative distribution function.
+            Default is negative infinity. Must be broadcastable with `x`.
+
+        Returns
+        -------
+        cdf : ndarray or scalar
+            Log of the cumulative distribution function evaluated at `x`
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        .. versionadded:: 1.0.0
+
+        """
+        params = self._process_parameters(mean, cov, allow_singular)
+        dim, mean, cov_object = params
+        cov = cov_object.covariance
+        x = self._process_quantiles(x, dim)
+        if not maxpts:
+            maxpts = 1000000 * dim
+        cdf = self._cdf(x, mean, cov, maxpts, abseps, releps, lower_limit)
+        # the log of a negative real is complex, and cdf can be negative
+        # if lower limit is greater than upper limit
+        cdf = cdf + 0j if np.any(cdf < 0) else cdf
+        out = np.log(cdf)
+        return out
+
+    def cdf(self, x, mean=None, cov=1, allow_singular=False, maxpts=None,
+            abseps=1e-5, releps=1e-5, *, lower_limit=None):
+        """Multivariate normal cumulative distribution function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_mvn_doc_default_callparams)s
+        maxpts : integer, optional
+            The maximum number of points to use for integration
+            (default ``1000000*dim``)
+        abseps : float, optional
+            Absolute error tolerance (default 1e-5)
+        releps : float, optional
+            Relative error tolerance (default 1e-5)
+        lower_limit : array_like, optional
+            Lower limit of integration of the cumulative distribution function.
+            Default is negative infinity. Must be broadcastable with `x`.
+
+        Returns
+        -------
+        cdf : ndarray or scalar
+            Cumulative distribution function evaluated at `x`
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        .. versionadded:: 1.0.0
+
+        """
+        params = self._process_parameters(mean, cov, allow_singular)
+        dim, mean, cov_object = params
+        cov = cov_object.covariance
+        x = self._process_quantiles(x, dim)
+        if not maxpts:
+            maxpts = 1000000 * dim
+        out = self._cdf(x, mean, cov, maxpts, abseps, releps, lower_limit)
+        return out
+
+    def rvs(self, mean=None, cov=1, size=1, random_state=None):
+        """Draw random samples from a multivariate normal distribution.
+
+        Parameters
+        ----------
+        %(_mvn_doc_default_callparams)s
+        size : integer, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `N`), where `N` is the
+            dimension of the random variable.
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        """
+        dim, mean, cov_object = self._process_parameters(mean, cov)
+        random_state = self._get_random_state(random_state)
+
+        if isinstance(cov_object, _covariance.CovViaPSD):
+            cov = cov_object.covariance
+            out = random_state.multivariate_normal(mean, cov, size)
+            out = _squeeze_output(out)
+        else:
+            size = size or tuple()
+            if not np.iterable(size):
+                size = (size,)
+            shape = tuple(size) + (cov_object.shape[-1],)
+            x = random_state.normal(size=shape)
+            out = mean + cov_object.colorize(x)
+        return out
+
+    def entropy(self, mean=None, cov=1):
+        """Compute the differential entropy of the multivariate normal.
+
+        Parameters
+        ----------
+        %(_mvn_doc_default_callparams)s
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the multivariate normal distribution
+
+        Notes
+        -----
+        %(_mvn_doc_callparams_note)s
+
+        """
+        dim, mean, cov_object = self._process_parameters(mean, cov)
+        return 0.5 * (cov_object.rank * (_LOG_2PI + 1) + cov_object.log_pdet)
+
+    def fit(self, x, fix_mean=None, fix_cov=None):
+        """Fit a multivariate normal distribution to data.
+
+        Parameters
+        ----------
+        x : ndarray (m, n)
+            Data the distribution is fitted to. Must have two axes.
+            The first axis of length `m` represents the number of vectors
+            the distribution is fitted to. The second axis of length `n`
+            determines the dimensionality of the fitted distribution.
+        fix_mean : ndarray(n, )
+            Fixed mean vector. Must have length `n`.
+        fix_cov: ndarray (n, n)
+            Fixed covariance matrix. Must have shape ``(n, n)``.
+
+        Returns
+        -------
+        mean : ndarray (n, )
+            Maximum likelihood estimate of the mean vector
+        cov : ndarray (n, n)
+            Maximum likelihood estimate of the covariance matrix
+
+        """
+        # input validation for data to be fitted
+        x = np.asarray(x)
+        if x.ndim != 2:
+            raise ValueError("`x` must be two-dimensional.")
+
+        n_vectors, dim = x.shape
+
+        # parameter estimation
+        # reference: https://home.ttic.edu/~shubhendu/Slides/Estimation.pdf
+        if fix_mean is not None:
+            # input validation for `fix_mean`
+            fix_mean = np.atleast_1d(fix_mean)
+            if fix_mean.shape != (dim, ):
+                msg = ("`fix_mean` must be a one-dimensional array the same "
+                       "length as the dimensionality of the vectors `x`.")
+                raise ValueError(msg)
+            mean = fix_mean
+        else:
+            mean = x.mean(axis=0)
+
+        if fix_cov is not None:
+            # input validation for `fix_cov`
+            fix_cov = np.atleast_2d(fix_cov)
+            # validate shape
+            if fix_cov.shape != (dim, dim):
+                msg = ("`fix_cov` must be a two-dimensional square array "
+                       "of same side length as the dimensionality of the "
+                       "vectors `x`.")
+                raise ValueError(msg)
+            # validate positive semidefiniteness
+            # a trimmed down copy from _PSD
+            s, u = scipy.linalg.eigh(fix_cov, lower=True, check_finite=True)
+            eps = _eigvalsh_to_eps(s)
+            if np.min(s) < -eps:
+                msg = "`fix_cov` must be symmetric positive semidefinite."
+                raise ValueError(msg)
+            cov = fix_cov
+        else:
+            centered_data = x - mean
+            cov = centered_data.T @ centered_data / n_vectors
+        return mean, cov
+
+
+multivariate_normal = multivariate_normal_gen()
+
+
+class multivariate_normal_frozen(multi_rv_frozen):
+    def __init__(self, mean=None, cov=1, allow_singular=False, seed=None,
+                 maxpts=None, abseps=1e-5, releps=1e-5):
+        """Create a frozen multivariate normal distribution.
+
+        Parameters
+        ----------
+        mean : array_like, default: ``[0]``
+            Mean of the distribution.
+        cov : array_like, default: ``[1]``
+            Symmetric positive (semi)definite covariance matrix of the
+            distribution.
+        allow_singular : bool, default: ``False``
+            Whether to allow a singular covariance matrix.
+        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+        maxpts : integer, optional
+            The maximum number of points to use for integration of the
+            cumulative distribution function (default ``1000000*dim``)
+        abseps : float, optional
+            Absolute error tolerance for the cumulative distribution function
+            (default 1e-5)
+        releps : float, optional
+            Relative error tolerance for the cumulative distribution function
+            (default 1e-5)
+
+        Examples
+        --------
+        When called with the default parameters, this will create a 1D random
+        variable with mean 0 and covariance 1:
+
+        >>> from scipy.stats import multivariate_normal
+        >>> r = multivariate_normal()
+        >>> r.mean
+        array([ 0.])
+        >>> r.cov
+        array([[1.]])
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        self._dist = multivariate_normal_gen(seed)
+        self.dim, self.mean, self.cov_object = (
+            self._dist._process_parameters(mean, cov, allow_singular))
+        self.allow_singular = allow_singular or self.cov_object._allow_singular
+        if not maxpts:
+            maxpts = 1000000 * self.dim
+        self.maxpts = maxpts
+        self.abseps = abseps
+        self.releps = releps
+
+    @property
+    def cov(self):
+        return self.cov_object.covariance
+
+    def logpdf(self, x):
+        x = self._dist._process_quantiles(x, self.dim)
+        out = self._dist._logpdf(x, self.mean, self.cov_object)
+        if np.any(self.cov_object.rank < self.dim):
+            out_of_bounds = ~self.cov_object._support_mask(x-self.mean)
+            out[out_of_bounds] = -np.inf
+        return _squeeze_output(out)
+
+    def pdf(self, x):
+        return np.exp(self.logpdf(x))
+
+    def logcdf(self, x, *, lower_limit=None):
+        cdf = self.cdf(x, lower_limit=lower_limit)
+        # the log of a negative real is complex, and cdf can be negative
+        # if lower limit is greater than upper limit
+        cdf = cdf + 0j if np.any(cdf < 0) else cdf
+        out = np.log(cdf)
+        return out
+
+    def cdf(self, x, *, lower_limit=None):
+        x = self._dist._process_quantiles(x, self.dim)
+        out = self._dist._cdf(x, self.mean, self.cov_object.covariance,
+                              self.maxpts, self.abseps, self.releps,
+                              lower_limit)
+        return _squeeze_output(out)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.mean, self.cov_object, size, random_state)
+
+    def entropy(self):
+        """Computes the differential entropy of the multivariate normal.
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the multivariate normal distribution
+
+        """
+        log_pdet = self.cov_object.log_pdet
+        rank = self.cov_object.rank
+        return 0.5 * (rank * (_LOG_2PI + 1) + log_pdet)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multivariate_normal_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'logcdf', 'cdf', 'rvs']:
+    method = multivariate_normal_gen.__dict__[name]
+    method_frozen = multivariate_normal_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(method.__doc__,
+                                             mvn_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, mvn_docdict_params)
+
+_matnorm_doc_default_callparams = """\
+mean : array_like, optional
+    Mean of the distribution (default: `None`)
+rowcov : array_like, optional
+    Among-row covariance matrix of the distribution (default: ``1``)
+colcov : array_like, optional
+    Among-column covariance matrix of the distribution (default: ``1``)
+"""
+
+_matnorm_doc_callparams_note = """\
+If `mean` is set to `None` then a matrix of zeros is used for the mean.
+The dimensions of this matrix are inferred from the shape of `rowcov` and
+`colcov`, if these are provided, or set to ``1`` if ambiguous.
+
+`rowcov` and `colcov` can be two-dimensional array_likes specifying the
+covariance matrices directly. Alternatively, a one-dimensional array will
+be be interpreted as the entries of a diagonal matrix, and a scalar or
+zero-dimensional array will be interpreted as this value times the
+identity matrix.
+"""
+
+_matnorm_doc_frozen_callparams = ""
+
+_matnorm_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+matnorm_docdict_params = {
+    '_matnorm_doc_default_callparams': _matnorm_doc_default_callparams,
+    '_matnorm_doc_callparams_note': _matnorm_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+matnorm_docdict_noparams = {
+    '_matnorm_doc_default_callparams': _matnorm_doc_frozen_callparams,
+    '_matnorm_doc_callparams_note': _matnorm_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class matrix_normal_gen(multi_rv_generic):
+    r"""A matrix normal random variable.
+
+    The `mean` keyword specifies the mean. The `rowcov` keyword specifies the
+    among-row covariance matrix. The 'colcov' keyword specifies the
+    among-column covariance matrix.
+
+    Methods
+    -------
+    pdf(X, mean=None, rowcov=1, colcov=1)
+        Probability density function.
+    logpdf(X, mean=None, rowcov=1, colcov=1)
+        Log of the probability density function.
+    rvs(mean=None, rowcov=1, colcov=1, size=1, random_state=None)
+        Draw random samples.
+    entropy(rowcol=1, colcov=1)
+        Differential entropy.
+
+    Parameters
+    ----------
+    %(_matnorm_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_matnorm_doc_callparams_note)s
+
+    The covariance matrices specified by `rowcov` and `colcov` must be
+    (symmetric) positive definite. If the samples in `X` are
+    :math:`m \times n`, then `rowcov` must be :math:`m \times m` and
+    `colcov` must be :math:`n \times n`. `mean` must be the same shape as `X`.
+
+    The probability density function for `matrix_normal` is
+
+    .. math::
+
+        f(X) = (2 \pi)^{-\frac{mn}{2}}|U|^{-\frac{n}{2}} |V|^{-\frac{m}{2}}
+               \exp\left( -\frac{1}{2} \mathrm{Tr}\left[ U^{-1} (X-M) V^{-1}
+               (X-M)^T \right] \right),
+
+    where :math:`M` is the mean, :math:`U` the among-row covariance matrix,
+    :math:`V` the among-column covariance matrix.
+
+    The `allow_singular` behaviour of the `multivariate_normal`
+    distribution is not currently supported. Covariance matrices must be
+    full rank.
+
+    The `matrix_normal` distribution is closely related to the
+    `multivariate_normal` distribution. Specifically, :math:`\mathrm{Vec}(X)`
+    (the vector formed by concatenating the columns  of :math:`X`) has a
+    multivariate normal distribution with mean :math:`\mathrm{Vec}(M)`
+    and covariance :math:`V \otimes U` (where :math:`\otimes` is the Kronecker
+    product). Sampling and pdf evaluation are
+    :math:`\mathcal{O}(m^3 + n^3 + m^2 n + m n^2)` for the matrix normal, but
+    :math:`\mathcal{O}(m^3 n^3)` for the equivalent multivariate normal,
+    making this equivalent form algorithmically inefficient.
+
+    .. versionadded:: 0.17.0
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.stats import matrix_normal
+
+    >>> M = np.arange(6).reshape(3,2); M
+    array([[0, 1],
+           [2, 3],
+           [4, 5]])
+    >>> U = np.diag([1,2,3]); U
+    array([[1, 0, 0],
+           [0, 2, 0],
+           [0, 0, 3]])
+    >>> V = 0.3*np.identity(2); V
+    array([[ 0.3,  0. ],
+           [ 0. ,  0.3]])
+    >>> X = M + 0.1; X
+    array([[ 0.1,  1.1],
+           [ 2.1,  3.1],
+           [ 4.1,  5.1]])
+    >>> matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)
+    0.023410202050005054
+
+    >>> # Equivalent multivariate normal
+    >>> from scipy.stats import multivariate_normal
+    >>> vectorised_X = X.T.flatten()
+    >>> equiv_mean = M.T.flatten()
+    >>> equiv_cov = np.kron(V,U)
+    >>> multivariate_normal.pdf(vectorised_X, mean=equiv_mean, cov=equiv_cov)
+    0.023410202050005054
+
+    Alternatively, the object may be called (as a function) to fix the mean
+    and covariance parameters, returning a "frozen" matrix normal
+    random variable:
+
+    >>> rv = matrix_normal(mean=None, rowcov=1, colcov=1)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # mean and covariance fixed.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, matnorm_docdict_params)
+
+    def __call__(self, mean=None, rowcov=1, colcov=1, seed=None):
+        """Create a frozen matrix normal distribution.
+
+        See `matrix_normal_frozen` for more information.
+
+        """
+        return matrix_normal_frozen(mean, rowcov, colcov, seed=seed)
+
+    def _process_parameters(self, mean, rowcov, colcov):
+        """
+        Infer dimensionality from mean or covariance matrices. Handle
+        defaults. Ensure compatible dimensions.
+        """
+
+        # Process mean
+        if mean is not None:
+            mean = np.asarray(mean, dtype=float)
+            meanshape = mean.shape
+            if len(meanshape) != 2:
+                raise ValueError("Array `mean` must be two dimensional.")
+            if np.any(meanshape == 0):
+                raise ValueError("Array `mean` has invalid shape.")
+
+        # Process among-row covariance
+        rowcov = np.asarray(rowcov, dtype=float)
+        if rowcov.ndim == 0:
+            if mean is not None:
+                rowcov = rowcov * np.identity(meanshape[0])
+            else:
+                rowcov = rowcov * np.identity(1)
+        elif rowcov.ndim == 1:
+            rowcov = np.diag(rowcov)
+        rowshape = rowcov.shape
+        if len(rowshape) != 2:
+            raise ValueError("`rowcov` must be a scalar or a 2D array.")
+        if rowshape[0] != rowshape[1]:
+            raise ValueError("Array `rowcov` must be square.")
+        if rowshape[0] == 0:
+            raise ValueError("Array `rowcov` has invalid shape.")
+        numrows = rowshape[0]
+
+        # Process among-column covariance
+        colcov = np.asarray(colcov, dtype=float)
+        if colcov.ndim == 0:
+            if mean is not None:
+                colcov = colcov * np.identity(meanshape[1])
+            else:
+                colcov = colcov * np.identity(1)
+        elif colcov.ndim == 1:
+            colcov = np.diag(colcov)
+        colshape = colcov.shape
+        if len(colshape) != 2:
+            raise ValueError("`colcov` must be a scalar or a 2D array.")
+        if colshape[0] != colshape[1]:
+            raise ValueError("Array `colcov` must be square.")
+        if colshape[0] == 0:
+            raise ValueError("Array `colcov` has invalid shape.")
+        numcols = colshape[0]
+
+        # Ensure mean and covariances compatible
+        if mean is not None:
+            if meanshape[0] != numrows:
+                raise ValueError("Arrays `mean` and `rowcov` must have the "
+                                 "same number of rows.")
+            if meanshape[1] != numcols:
+                raise ValueError("Arrays `mean` and `colcov` must have the "
+                                 "same number of columns.")
+        else:
+            mean = np.zeros((numrows, numcols))
+
+        dims = (numrows, numcols)
+
+        return dims, mean, rowcov, colcov
+
+    def _process_quantiles(self, X, dims):
+        """
+        Adjust quantiles array so that last two axes labels the components of
+        each data point.
+        """
+        X = np.asarray(X, dtype=float)
+        if X.ndim == 2:
+            X = X[np.newaxis, :]
+        if X.shape[-2:] != dims:
+            raise ValueError("The shape of array `X` is not compatible "
+                             "with the distribution parameters.")
+        return X
+
+    def _logpdf(self, dims, X, mean, row_prec_rt, log_det_rowcov,
+                col_prec_rt, log_det_colcov):
+        """Log of the matrix normal probability density function.
+
+        Parameters
+        ----------
+        dims : tuple
+            Dimensions of the matrix variates
+        X : ndarray
+            Points at which to evaluate the log of the probability
+            density function
+        mean : ndarray
+            Mean of the distribution
+        row_prec_rt : ndarray
+            A decomposition such that np.dot(row_prec_rt, row_prec_rt.T)
+            is the inverse of the among-row covariance matrix
+        log_det_rowcov : float
+            Logarithm of the determinant of the among-row covariance matrix
+        col_prec_rt : ndarray
+            A decomposition such that np.dot(col_prec_rt, col_prec_rt.T)
+            is the inverse of the among-column covariance matrix
+        log_det_colcov : float
+            Logarithm of the determinant of the among-column covariance matrix
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        numrows, numcols = dims
+        roll_dev = np.moveaxis(X-mean, -1, 0)
+        scale_dev = np.tensordot(col_prec_rt.T,
+                                 np.dot(roll_dev, row_prec_rt), 1)
+        maha = np.sum(np.sum(np.square(scale_dev), axis=-1), axis=0)
+        return -0.5 * (numrows*numcols*_LOG_2PI + numcols*log_det_rowcov
+                       + numrows*log_det_colcov + maha)
+
+    def logpdf(self, X, mean=None, rowcov=1, colcov=1):
+        """Log of the matrix normal probability density function.
+
+        Parameters
+        ----------
+        X : array_like
+            Quantiles, with the last two axes of `X` denoting the components.
+        %(_matnorm_doc_default_callparams)s
+
+        Returns
+        -------
+        logpdf : ndarray
+            Log of the probability density function evaluated at `X`
+
+        Notes
+        -----
+        %(_matnorm_doc_callparams_note)s
+
+        """
+        dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov,
+                                                              colcov)
+        X = self._process_quantiles(X, dims)
+        rowpsd = _PSD(rowcov, allow_singular=False)
+        colpsd = _PSD(colcov, allow_singular=False)
+        out = self._logpdf(dims, X, mean, rowpsd.U, rowpsd.log_pdet, colpsd.U,
+                           colpsd.log_pdet)
+        return _squeeze_output(out)
+
+    def pdf(self, X, mean=None, rowcov=1, colcov=1):
+        """Matrix normal probability density function.
+
+        Parameters
+        ----------
+        X : array_like
+            Quantiles, with the last two axes of `X` denoting the components.
+        %(_matnorm_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Probability density function evaluated at `X`
+
+        Notes
+        -----
+        %(_matnorm_doc_callparams_note)s
+
+        """
+        return np.exp(self.logpdf(X, mean, rowcov, colcov))
+
+    def rvs(self, mean=None, rowcov=1, colcov=1, size=1, random_state=None):
+        """Draw random samples from a matrix normal distribution.
+
+        Parameters
+        ----------
+        %(_matnorm_doc_default_callparams)s
+        size : integer, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `dims`), where `dims` is the
+            dimension of the random matrices.
+
+        Notes
+        -----
+        %(_matnorm_doc_callparams_note)s
+
+        """
+        size = int(size)
+        dims, mean, rowcov, colcov = self._process_parameters(mean, rowcov,
+                                                              colcov)
+        rowchol = scipy.linalg.cholesky(rowcov, lower=True)
+        colchol = scipy.linalg.cholesky(colcov, lower=True)
+        random_state = self._get_random_state(random_state)
+        # We aren't generating standard normal variates with size=(size,
+        # dims[0], dims[1]) directly to ensure random variates remain backwards
+        # compatible. See https://github.com/scipy/scipy/pull/12312 for more
+        # details.
+        std_norm = random_state.standard_normal(
+            size=(dims[1], size, dims[0])
+        ).transpose(1, 2, 0)
+        out = mean + np.einsum('jp,ipq,kq->ijk',
+                               rowchol, std_norm, colchol,
+                               optimize=True)
+        if size == 1:
+            out = out.reshape(mean.shape)
+        return out
+
+    def entropy(self, rowcov=1, colcov=1):
+        """Log of the matrix normal probability density function.
+
+        Parameters
+        ----------
+        rowcov : array_like, optional
+            Among-row covariance matrix of the distribution (default: ``1``)
+        colcov : array_like, optional
+            Among-column covariance matrix of the distribution (default: ``1``)
+
+        Returns
+        -------
+        entropy : float
+            Entropy of the distribution
+
+        Notes
+        -----
+        %(_matnorm_doc_callparams_note)s
+
+        """
+        dummy_mean = np.zeros((rowcov.shape[0], colcov.shape[0]))
+        dims, _, rowcov, colcov = self._process_parameters(dummy_mean,
+                                                           rowcov,
+                                                           colcov)
+        rowpsd = _PSD(rowcov, allow_singular=False)
+        colpsd = _PSD(colcov, allow_singular=False)
+
+        return self._entropy(dims, rowpsd.log_pdet, colpsd.log_pdet)
+
+    def _entropy(self, dims, row_cov_logdet, col_cov_logdet):
+        n, p = dims
+        return (0.5 * n * p * (1 + _LOG_2PI) + 0.5 * p * row_cov_logdet +
+                0.5 * n * col_cov_logdet)
+
+
+matrix_normal = matrix_normal_gen()
+
+
+class matrix_normal_frozen(multi_rv_frozen):
+    """
+    Create a frozen matrix normal distribution.
+
+    Parameters
+    ----------
+    %(_matnorm_doc_default_callparams)s
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is `None` the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import matrix_normal
+
+    >>> distn = matrix_normal(mean=np.zeros((3,3)))
+    >>> X = distn.rvs(); X
+    array([[-0.02976962,  0.93339138, -0.09663178],
+           [ 0.67405524,  0.28250467, -0.93308929],
+           [-0.31144782,  0.74535536,  1.30412916]])
+    >>> distn.pdf(X)
+    2.5160642368346784e-05
+    >>> distn.logpdf(X)
+    -10.590229595124615
+    """
+
+    def __init__(self, mean=None, rowcov=1, colcov=1, seed=None):
+        self._dist = matrix_normal_gen(seed)
+        self.dims, self.mean, self.rowcov, self.colcov = \
+            self._dist._process_parameters(mean, rowcov, colcov)
+        self.rowpsd = _PSD(self.rowcov, allow_singular=False)
+        self.colpsd = _PSD(self.colcov, allow_singular=False)
+
+    def logpdf(self, X):
+        X = self._dist._process_quantiles(X, self.dims)
+        out = self._dist._logpdf(self.dims, X, self.mean, self.rowpsd.U,
+                                 self.rowpsd.log_pdet, self.colpsd.U,
+                                 self.colpsd.log_pdet)
+        return _squeeze_output(out)
+
+    def pdf(self, X):
+        return np.exp(self.logpdf(X))
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.mean, self.rowcov, self.colcov, size,
+                              random_state)
+
+    def entropy(self):
+        return self._dist._entropy(self.dims, self.rowpsd.log_pdet,
+                                   self.colpsd.log_pdet)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# matrix_normal_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'rvs', 'entropy']:
+    method = matrix_normal_gen.__dict__[name]
+    method_frozen = matrix_normal_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(method.__doc__,
+                                             matnorm_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, matnorm_docdict_params)
+
+_dirichlet_doc_default_callparams = """\
+alpha : array_like
+    The concentration parameters. The number of entries determines the
+    dimensionality of the distribution.
+"""
+_dirichlet_doc_frozen_callparams = ""
+
+_dirichlet_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+dirichlet_docdict_params = {
+    '_dirichlet_doc_default_callparams': _dirichlet_doc_default_callparams,
+    '_doc_random_state': _doc_random_state
+}
+
+dirichlet_docdict_noparams = {
+    '_dirichlet_doc_default_callparams': _dirichlet_doc_frozen_callparams,
+    '_doc_random_state': _doc_random_state
+}
+
+
+def _dirichlet_check_parameters(alpha):
+    alpha = np.asarray(alpha)
+    if np.min(alpha) <= 0:
+        raise ValueError("All parameters must be greater than 0")
+    elif alpha.ndim != 1:
+        raise ValueError("Parameter vector 'a' must be one dimensional, "
+                         f"but a.shape = {alpha.shape}.")
+    return alpha
+
+
+def _dirichlet_check_input(alpha, x):
+    x = np.asarray(x)
+
+    if x.shape[0] + 1 != alpha.shape[0] and x.shape[0] != alpha.shape[0]:
+        raise ValueError("Vector 'x' must have either the same number "
+                         "of entries as, or one entry fewer than, "
+                         f"parameter vector 'a', but alpha.shape = {alpha.shape} "
+                         f"and x.shape = {x.shape}.")
+
+    if x.shape[0] != alpha.shape[0]:
+        xk = np.array([1 - np.sum(x, 0)])
+        if xk.ndim == 1:
+            x = np.append(x, xk)
+        elif xk.ndim == 2:
+            x = np.vstack((x, xk))
+        else:
+            raise ValueError("The input must be one dimensional or a two "
+                             "dimensional matrix containing the entries.")
+
+    if np.min(x) < 0:
+        raise ValueError("Each entry in 'x' must be greater than or equal "
+                         "to zero.")
+
+    if np.max(x) > 1:
+        raise ValueError("Each entry in 'x' must be smaller or equal one.")
+
+    # Check x_i > 0 or alpha_i > 1
+    xeq0 = (x == 0)
+    alphalt1 = (alpha < 1)
+    if x.shape != alpha.shape:
+        alphalt1 = np.repeat(alphalt1, x.shape[-1], axis=-1).reshape(x.shape)
+    chk = np.logical_and(xeq0, alphalt1)
+
+    if np.sum(chk):
+        raise ValueError("Each entry in 'x' must be greater than zero if its "
+                         "alpha is less than one.")
+
+    if (np.abs(np.sum(x, 0) - 1.0) > 10e-10).any():
+        raise ValueError("The input vector 'x' must lie within the normal "
+                         f"simplex. but np.sum(x, 0) = {np.sum(x, 0)}.")
+
+    return x
+
+
+def _lnB(alpha):
+    r"""Internal helper function to compute the log of the useful quotient.
+
+    .. math::
+
+        B(\alpha) = \frac{\prod_{i=1}{K}\Gamma(\alpha_i)}
+                         {\Gamma\left(\sum_{i=1}^{K} \alpha_i \right)}
+
+    Parameters
+    ----------
+    %(_dirichlet_doc_default_callparams)s
+
+    Returns
+    -------
+    B : scalar
+        Helper quotient, internal use only
+
+    """
+    return np.sum(gammaln(alpha)) - gammaln(np.sum(alpha))
+
+
+class dirichlet_gen(multi_rv_generic):
+    r"""A Dirichlet random variable.
+
+    The ``alpha`` keyword specifies the concentration parameters of the
+    distribution.
+
+    .. versionadded:: 0.15.0
+
+    Methods
+    -------
+    pdf(x, alpha)
+        Probability density function.
+    logpdf(x, alpha)
+        Log of the probability density function.
+    rvs(alpha, size=1, random_state=None)
+        Draw random samples from a Dirichlet distribution.
+    mean(alpha)
+        The mean of the Dirichlet distribution
+    var(alpha)
+        The variance of the Dirichlet distribution
+    cov(alpha)
+        The covariance of the Dirichlet distribution
+    entropy(alpha)
+        Compute the differential entropy of the Dirichlet distribution.
+
+    Parameters
+    ----------
+    %(_dirichlet_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    Each :math:`\alpha` entry must be positive. The distribution has only
+    support on the simplex defined by
+
+    .. math::
+        \sum_{i=1}^{K} x_i = 1
+
+    where :math:`0 < x_i < 1`.
+
+    If the quantiles don't lie within the simplex, a ValueError is raised.
+
+    The probability density function for `dirichlet` is
+
+    .. math::
+
+        f(x) = \frac{1}{\mathrm{B}(\boldsymbol\alpha)} \prod_{i=1}^K x_i^{\alpha_i - 1}
+
+    where
+
+    .. math::
+
+        \mathrm{B}(\boldsymbol\alpha) = \frac{\prod_{i=1}^K \Gamma(\alpha_i)}
+                                     {\Gamma\bigl(\sum_{i=1}^K \alpha_i\bigr)}
+
+    and :math:`\boldsymbol\alpha=(\alpha_1,\ldots,\alpha_K)`, the
+    concentration parameters and :math:`K` is the dimension of the space
+    where :math:`x` takes values.
+
+    Note that the `dirichlet` interface is somewhat inconsistent.
+    The array returned by the rvs function is transposed
+    with respect to the format expected by the pdf and logpdf.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import dirichlet
+
+    Generate a dirichlet random variable
+
+    >>> quantiles = np.array([0.2, 0.2, 0.6])  # specify quantiles
+    >>> alpha = np.array([0.4, 5, 15])  # specify concentration parameters
+    >>> dirichlet.pdf(quantiles, alpha)
+    0.2843831684937255
+
+    The same PDF but following a log scale
+
+    >>> dirichlet.logpdf(quantiles, alpha)
+    -1.2574327653159187
+
+    Once we specify the dirichlet distribution
+    we can then calculate quantities of interest
+
+    >>> dirichlet.mean(alpha)  # get the mean of the distribution
+    array([0.01960784, 0.24509804, 0.73529412])
+    >>> dirichlet.var(alpha) # get variance
+    array([0.00089829, 0.00864603, 0.00909517])
+    >>> dirichlet.entropy(alpha)  # calculate the differential entropy
+    -4.3280162474082715
+
+    We can also return random samples from the distribution
+
+    >>> dirichlet.rvs(alpha, size=1, random_state=1)
+    array([[0.00766178, 0.24670518, 0.74563305]])
+    >>> dirichlet.rvs(alpha, size=2, random_state=2)
+    array([[0.01639427, 0.1292273 , 0.85437844],
+           [0.00156917, 0.19033695, 0.80809388]])
+
+    Alternatively, the object may be called (as a function) to fix
+    concentration parameters, returning a "frozen" Dirichlet
+    random variable:
+
+    >>> rv = dirichlet(alpha)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # concentration parameters fixed.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, dirichlet_docdict_params)
+
+    def __call__(self, alpha, seed=None):
+        return dirichlet_frozen(alpha, seed=seed)
+
+    def _logpdf(self, x, alpha):
+        """Log of the Dirichlet probability density function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability
+            density function
+        %(_dirichlet_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        lnB = _lnB(alpha)
+        return - lnB + np.sum((xlogy(alpha - 1, x.T)).T, 0)
+
+    def logpdf(self, x, alpha):
+        """Log of the Dirichlet probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Log of the probability density function evaluated at `x`.
+
+        """
+        alpha = _dirichlet_check_parameters(alpha)
+        x = _dirichlet_check_input(alpha, x)
+
+        out = self._logpdf(x, alpha)
+        return _squeeze_output(out)
+
+    def pdf(self, x, alpha):
+        """The Dirichlet probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            The probability density function evaluated at `x`.
+
+        """
+        alpha = _dirichlet_check_parameters(alpha)
+        x = _dirichlet_check_input(alpha, x)
+
+        out = np.exp(self._logpdf(x, alpha))
+        return _squeeze_output(out)
+
+    def mean(self, alpha):
+        """Mean of the Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        mu : ndarray or scalar
+            Mean of the Dirichlet distribution.
+
+        """
+        alpha = _dirichlet_check_parameters(alpha)
+
+        out = alpha / (np.sum(alpha))
+        return _squeeze_output(out)
+
+    def var(self, alpha):
+        """Variance of the Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        v : ndarray or scalar
+            Variance of the Dirichlet distribution.
+
+        """
+
+        alpha = _dirichlet_check_parameters(alpha)
+
+        alpha0 = np.sum(alpha)
+        out = (alpha * (alpha0 - alpha)) / ((alpha0 * alpha0) * (alpha0 + 1))
+        return _squeeze_output(out)
+
+    def cov(self, alpha):
+        """Covariance matrix of the Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        cov : ndarray
+            The covariance matrix of the distribution.
+        """
+
+        alpha = _dirichlet_check_parameters(alpha)
+        alpha0 = np.sum(alpha)
+        a = alpha / alpha0
+
+        cov = (np.diag(a) - np.outer(a, a)) / (alpha0 + 1)
+        return _squeeze_output(cov)
+
+    def entropy(self, alpha):
+        """
+        Differential entropy of the Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the Dirichlet distribution
+
+        """
+
+        alpha = _dirichlet_check_parameters(alpha)
+
+        alpha0 = np.sum(alpha)
+        lnB = _lnB(alpha)
+        K = alpha.shape[0]
+
+        out = lnB + (alpha0 - K) * scipy.special.psi(alpha0) - np.sum(
+            (alpha - 1) * scipy.special.psi(alpha))
+        return _squeeze_output(out)
+
+    def rvs(self, alpha, size=1, random_state=None):
+        """
+        Draw random samples from a Dirichlet distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_doc_default_callparams)s
+        size : int, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `N`), where `N` is the
+            dimension of the random variable.
+
+        """
+        alpha = _dirichlet_check_parameters(alpha)
+        random_state = self._get_random_state(random_state)
+        return random_state.dirichlet(alpha, size=size)
+
+
+dirichlet = dirichlet_gen()
+
+
+class dirichlet_frozen(multi_rv_frozen):
+    def __init__(self, alpha, seed=None):
+        self.alpha = _dirichlet_check_parameters(alpha)
+        self._dist = dirichlet_gen(seed)
+
+    def logpdf(self, x):
+        return self._dist.logpdf(x, self.alpha)
+
+    def pdf(self, x):
+        return self._dist.pdf(x, self.alpha)
+
+    def mean(self):
+        return self._dist.mean(self.alpha)
+
+    def var(self):
+        return self._dist.var(self.alpha)
+
+    def cov(self):
+        return self._dist.cov(self.alpha)
+
+    def entropy(self):
+        return self._dist.entropy(self.alpha)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.alpha, size, random_state)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multivariate_normal_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'rvs', 'mean', 'var', 'cov', 'entropy']:
+    method = dirichlet_gen.__dict__[name]
+    method_frozen = dirichlet_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, dirichlet_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, dirichlet_docdict_params)
+
+
+_wishart_doc_default_callparams = """\
+df : int
+    Degrees of freedom, must be greater than or equal to dimension of the
+    scale matrix
+scale : array_like
+    Symmetric positive definite scale matrix of the distribution
+"""
+
+_wishart_doc_callparams_note = ""
+
+_wishart_doc_frozen_callparams = ""
+
+_wishart_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+wishart_docdict_params = {
+    '_doc_default_callparams': _wishart_doc_default_callparams,
+    '_doc_callparams_note': _wishart_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+wishart_docdict_noparams = {
+    '_doc_default_callparams': _wishart_doc_frozen_callparams,
+    '_doc_callparams_note': _wishart_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class wishart_gen(multi_rv_generic):
+    r"""A Wishart random variable.
+
+    The `df` keyword specifies the degrees of freedom. The `scale` keyword
+    specifies the scale matrix, which must be symmetric and positive definite.
+    In this context, the scale matrix is often interpreted in terms of a
+    multivariate normal precision matrix (the inverse of the covariance
+    matrix). These arguments must satisfy the relationship
+    ``df > scale.ndim - 1``, but see notes on using the `rvs` method with
+    ``df < scale.ndim``.
+
+    Methods
+    -------
+    pdf(x, df, scale)
+        Probability density function.
+    logpdf(x, df, scale)
+        Log of the probability density function.
+    rvs(df, scale, size=1, random_state=None)
+        Draw random samples from a Wishart distribution.
+    entropy()
+        Compute the differential entropy of the Wishart distribution.
+
+    Parameters
+    ----------
+    %(_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Raises
+    ------
+    scipy.linalg.LinAlgError
+        If the scale matrix `scale` is not positive definite.
+
+    See Also
+    --------
+    invwishart, chi2
+
+    Notes
+    -----
+    %(_doc_callparams_note)s
+
+    The scale matrix `scale` must be a symmetric positive definite
+    matrix. Singular matrices, including the symmetric positive semi-definite
+    case, are not supported. Symmetry is not checked; only the lower triangular
+    portion is used.
+
+    The Wishart distribution is often denoted
+
+    .. math::
+
+        W_p(\nu, \Sigma)
+
+    where :math:`\nu` is the degrees of freedom and :math:`\Sigma` is the
+    :math:`p \times p` scale matrix.
+
+    The probability density function for `wishart` has support over positive
+    definite matrices :math:`S`; if :math:`S \sim W_p(\nu, \Sigma)`, then
+    its PDF is given by:
+
+    .. math::
+
+        f(S) = \frac{|S|^{\frac{\nu - p - 1}{2}}}{2^{ \frac{\nu p}{2} }
+               |\Sigma|^\frac{\nu}{2} \Gamma_p \left ( \frac{\nu}{2} \right )}
+               \exp\left( -tr(\Sigma^{-1} S) / 2 \right)
+
+    If :math:`S \sim W_p(\nu, \Sigma)` (Wishart) then
+    :math:`S^{-1} \sim W_p^{-1}(\nu, \Sigma^{-1})` (inverse Wishart).
+
+    If the scale matrix is 1-dimensional and equal to one, then the Wishart
+    distribution :math:`W_1(\nu, 1)` collapses to the :math:`\chi^2(\nu)`
+    distribution.
+
+    The algorithm [2]_ implemented by the `rvs` method may
+    produce numerically singular matrices with :math:`p - 1 < \nu < p`; the
+    user may wish to check for this condition and generate replacement samples
+    as necessary.
+
+
+    .. versionadded:: 0.16.0
+
+    References
+    ----------
+    .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach",
+           Wiley, 1983.
+    .. [2] W.B. Smith and R.R. Hocking, "Algorithm AS 53: Wishart Variate
+           Generator", Applied Statistics, vol. 21, pp. 341-345, 1972.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import wishart, chi2
+    >>> x = np.linspace(1e-5, 8, 100)
+    >>> w = wishart.pdf(x, df=3, scale=1); w[:5]
+    array([ 0.00126156,  0.10892176,  0.14793434,  0.17400548,  0.1929669 ])
+    >>> c = chi2.pdf(x, 3); c[:5]
+    array([ 0.00126156,  0.10892176,  0.14793434,  0.17400548,  0.1929669 ])
+    >>> plt.plot(x, w)
+    >>> plt.show()
+
+    The input quantiles can be any shape of array, as long as the last
+    axis labels the components.
+
+    Alternatively, the object may be called (as a function) to fix the degrees
+    of freedom and scale parameters, returning a "frozen" Wishart random
+    variable:
+
+    >>> rv = wishart(df=1, scale=1)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # degrees of freedom and scale fixed.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, wishart_docdict_params)
+
+    def __call__(self, df=None, scale=None, seed=None):
+        """Create a frozen Wishart distribution.
+
+        See `wishart_frozen` for more information.
+        """
+        return wishart_frozen(df, scale, seed)
+
+    def _process_parameters(self, df, scale):
+        if scale is None:
+            scale = 1.0
+        scale = np.asarray(scale, dtype=float)
+
+        if scale.ndim == 0:
+            scale = scale[np.newaxis, np.newaxis]
+        elif scale.ndim == 1:
+            scale = np.diag(scale)
+        elif scale.ndim == 2 and not scale.shape[0] == scale.shape[1]:
+            raise ValueError("Array 'scale' must be square if it is two dimensional,"
+                             f" but scale.scale = {str(scale.shape)}.")
+        elif scale.ndim > 2:
+            raise ValueError("Array 'scale' must be at most two-dimensional,"
+                             " but scale.ndim = %d" % scale.ndim)
+
+        dim = scale.shape[0]
+
+        if df is None:
+            df = dim
+        elif not np.isscalar(df):
+            raise ValueError("Degrees of freedom must be a scalar.")
+        elif df <= dim - 1:
+            raise ValueError("Degrees of freedom must be greater than the "
+                             "dimension of scale matrix minus 1.")
+
+        return dim, df, scale
+
+    def _process_quantiles(self, x, dim):
+        """
+        Adjust quantiles array so that last axis labels the components of
+        each data point.
+        """
+        x = np.asarray(x, dtype=float)
+
+        if x.ndim == 0:
+            x = x * np.eye(dim)[:, :, np.newaxis]
+        if x.ndim == 1:
+            if dim == 1:
+                x = x[np.newaxis, np.newaxis, :]
+            else:
+                x = np.diag(x)[:, :, np.newaxis]
+        elif x.ndim == 2:
+            if not x.shape[0] == x.shape[1]:
+                raise ValueError(
+                    "Quantiles must be square if they are two dimensional,"
+                    f" but x.shape = {str(x.shape)}.")
+            x = x[:, :, np.newaxis]
+        elif x.ndim == 3:
+            if not x.shape[0] == x.shape[1]:
+                raise ValueError(
+                    "Quantiles must be square in the first two dimensions "
+                    f"if they are three dimensional, but x.shape = {str(x.shape)}.")
+        elif x.ndim > 3:
+            raise ValueError("Quantiles must be at most two-dimensional with"
+                             " an additional dimension for multiple"
+                             "components, but x.ndim = %d" % x.ndim)
+
+        # Now we have 3-dim array; should have shape [dim, dim, *]
+        if not x.shape[0:2] == (dim, dim):
+            raise ValueError('Quantiles have incompatible dimensions: should'
+                             f' be {(dim, dim)}, got {x.shape[0:2]}.')
+
+        return x
+
+    def _process_size(self, size):
+        size = np.asarray(size)
+
+        if size.ndim == 0:
+            size = size[np.newaxis]
+        elif size.ndim > 1:
+            raise ValueError('Size must be an integer or tuple of integers;'
+                 ' thus must have dimension <= 1.'
+                 f' Got size.ndim = {str(tuple(size))}')
+        n = size.prod()
+        shape = tuple(size)
+
+        return n, shape
+
+    def _logpdf(self, x, dim, df, scale, log_det_scale, C):
+        """Log of the Wishart probability density function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability
+            density function
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        scale : ndarray
+            Scale matrix
+        log_det_scale : float
+            Logarithm of the determinant of the scale matrix
+        C : ndarray
+            Cholesky factorization of the scale matrix, lower triangular.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        # log determinant of x
+        # Note: x has components along the last axis, so that x.T has
+        # components alone the 0-th axis. Then since det(A) = det(A'), this
+        # gives us a 1-dim vector of determinants
+
+        # Retrieve tr(scale^{-1} x)
+        log_det_x = np.empty(x.shape[-1])
+        scale_inv_x = np.empty(x.shape)
+        tr_scale_inv_x = np.empty(x.shape[-1])
+        for i in range(x.shape[-1]):
+            _, log_det_x[i] = self._cholesky_logdet(x[:, :, i])
+            scale_inv_x[:, :, i] = scipy.linalg.cho_solve((C, True), x[:, :, i])
+            tr_scale_inv_x[i] = scale_inv_x[:, :, i].trace()
+
+        # Log PDF
+        out = ((0.5 * (df - dim - 1) * log_det_x - 0.5 * tr_scale_inv_x) -
+               (0.5 * df * dim * _LOG_2 + 0.5 * df * log_det_scale +
+                multigammaln(0.5*df, dim)))
+
+        return out
+
+    def logpdf(self, x, df, scale):
+        """Log of the Wishart probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+            Each quantile must be a symmetric positive definite matrix.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Log of the probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        x = self._process_quantiles(x, dim)
+
+        # Cholesky decomposition of scale, get log(det(scale))
+        C, log_det_scale = self._cholesky_logdet(scale)
+
+        out = self._logpdf(x, dim, df, scale, log_det_scale, C)
+        return _squeeze_output(out)
+
+    def pdf(self, x, df, scale):
+        """Wishart probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+            Each quantile must be a symmetric positive definite matrix.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        return np.exp(self.logpdf(x, df, scale))
+
+    def _mean(self, dim, df, scale):
+        """Mean of the Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'mean' instead.
+
+        """
+        return df * scale
+
+    def mean(self, df, scale):
+        """Mean of the Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mean : float
+            The mean of the distribution
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._mean(dim, df, scale)
+        return _squeeze_output(out)
+
+    def _mode(self, dim, df, scale):
+        """Mode of the Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'mode' instead.
+
+        """
+        if df >= dim + 1:
+            out = (df-dim-1) * scale
+        else:
+            out = None
+        return out
+
+    def mode(self, df, scale):
+        """Mode of the Wishart distribution
+
+        Only valid if the degrees of freedom are greater than the dimension of
+        the scale matrix.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mode : float or None
+            The Mode of the distribution
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._mode(dim, df, scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def _var(self, dim, df, scale):
+        """Variance of the Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'var' instead.
+
+        """
+        var = scale**2
+        diag = scale.diagonal()  # 1 x dim array
+        var += np.outer(diag, diag)
+        var *= df
+        return var
+
+    def var(self, df, scale):
+        """Variance of the Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        var : float
+            The variance of the distribution
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._var(dim, df, scale)
+        return _squeeze_output(out)
+
+    def _standard_rvs(self, n, shape, dim, df, random_state):
+        """
+        Parameters
+        ----------
+        n : integer
+            Number of variates to generate
+        shape : iterable
+            Shape of the variates to generate
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'rvs' instead.
+
+        """
+        # Random normal variates for off-diagonal elements
+        n_tril = dim * (dim-1) // 2
+        covariances = random_state.normal(
+            size=n*n_tril).reshape(shape+(n_tril,))
+
+        # Random chi-square variates for diagonal elements
+        variances = (np.r_[[random_state.chisquare(df-(i+1)+1, size=n)**0.5
+                            for i in range(dim)]].reshape((dim,) +
+                                                          shape[::-1]).T)
+
+        # Create the A matri(ces) - lower triangular
+        A = np.zeros(shape + (dim, dim))
+
+        # Input the covariances
+        size_idx = tuple([slice(None, None, None)]*len(shape))
+        tril_idx = np.tril_indices(dim, k=-1)
+        A[size_idx + tril_idx] = covariances
+
+        # Input the variances
+        diag_idx = np.diag_indices(dim)
+        A[size_idx + diag_idx] = variances
+
+        return A
+
+    def _rvs(self, n, shape, dim, df, C, random_state):
+        """Draw random samples from a Wishart distribution.
+
+        Parameters
+        ----------
+        n : integer
+            Number of variates to generate
+        shape : iterable
+            Shape of the variates to generate
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        C : ndarray
+            Cholesky factorization of the scale matrix, lower triangular.
+        %(_doc_random_state)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'rvs' instead.
+
+        """
+        random_state = self._get_random_state(random_state)
+        # Calculate the matrices A, which are actually lower triangular
+        # Cholesky factorizations of a matrix B such that B ~ W(df, I)
+        A = self._standard_rvs(n, shape, dim, df, random_state)
+
+        # Calculate SA = C A A' C', where SA ~ W(df, scale)
+        # Note: this is the product of a (lower) (lower) (lower)' (lower)'
+        #       or, denoting B = AA', it is C B C' where C is the lower
+        #       triangular Cholesky factorization of the scale matrix.
+        #       this appears to conflict with the instructions in [1]_, which
+        #       suggest that it should be D' B D where D is the lower
+        #       triangular factorization of the scale matrix. However, it is
+        #       meant to refer to the Bartlett (1933) representation of a
+        #       Wishart random variate as L A A' L' where L is lower triangular
+        #       so it appears that understanding D' to be upper triangular
+        #       is either a typo in or misreading of [1]_.
+        for index in np.ndindex(shape):
+            CA = np.dot(C, A[index])
+            A[index] = np.dot(CA, CA.T)
+
+        return A
+
+    def rvs(self, df, scale, size=1, random_state=None):
+        """Draw random samples from a Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+        size : integer or iterable of integers, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray
+            Random variates of shape (`size`) + (``dim``, ``dim``), where
+            ``dim`` is the dimension of the scale matrix.
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        n, shape = self._process_size(size)
+        dim, df, scale = self._process_parameters(df, scale)
+
+        # Cholesky decomposition of scale
+        C = scipy.linalg.cholesky(scale, lower=True)
+
+        out = self._rvs(n, shape, dim, df, C, random_state)
+
+        return _squeeze_output(out)
+
+    def _entropy(self, dim, df, log_det_scale):
+        """Compute the differential entropy of the Wishart.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        log_det_scale : float
+            Logarithm of the determinant of the scale matrix
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'entropy' instead.
+
+        """
+        return (
+            0.5 * (dim+1) * log_det_scale +
+            0.5 * dim * (dim+1) * _LOG_2 +
+            multigammaln(0.5*df, dim) -
+            0.5 * (df - dim - 1) * np.sum(
+                [psi(0.5*(df + 1 - (i+1))) for i in range(dim)]
+            ) +
+            0.5 * df * dim
+        )
+
+    def entropy(self, df, scale):
+        """Compute the differential entropy of the Wishart.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the Wishart distribution
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        _, log_det_scale = self._cholesky_logdet(scale)
+        return self._entropy(dim, df, log_det_scale)
+
+    def _cholesky_logdet(self, scale):
+        """Compute Cholesky decomposition and determine (log(det(scale)).
+
+        Parameters
+        ----------
+        scale : ndarray
+            Scale matrix.
+
+        Returns
+        -------
+        c_decomp : ndarray
+            The Cholesky decomposition of `scale`.
+        logdet : scalar
+            The log of the determinant of `scale`.
+
+        Notes
+        -----
+        This computation of ``logdet`` is equivalent to
+        ``np.linalg.slogdet(scale)``.  It is ~2x faster though.
+
+        """
+        c_decomp = scipy.linalg.cholesky(scale, lower=True)
+        logdet = 2 * np.sum(np.log(c_decomp.diagonal()))
+        return c_decomp, logdet
+
+
+wishart = wishart_gen()
+
+
+class wishart_frozen(multi_rv_frozen):
+    """Create a frozen Wishart distribution.
+
+    Parameters
+    ----------
+    df : array_like
+        Degrees of freedom of the distribution
+    scale : array_like
+        Scale matrix of the distribution
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    """
+    def __init__(self, df, scale, seed=None):
+        self._dist = wishart_gen(seed)
+        self.dim, self.df, self.scale = self._dist._process_parameters(
+            df, scale)
+        self.C, self.log_det_scale = self._dist._cholesky_logdet(self.scale)
+
+    def logpdf(self, x):
+        x = self._dist._process_quantiles(x, self.dim)
+
+        out = self._dist._logpdf(x, self.dim, self.df, self.scale,
+                                 self.log_det_scale, self.C)
+        return _squeeze_output(out)
+
+    def pdf(self, x):
+        return np.exp(self.logpdf(x))
+
+    def mean(self):
+        out = self._dist._mean(self.dim, self.df, self.scale)
+        return _squeeze_output(out)
+
+    def mode(self):
+        out = self._dist._mode(self.dim, self.df, self.scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def var(self):
+        out = self._dist._var(self.dim, self.df, self.scale)
+        return _squeeze_output(out)
+
+    def rvs(self, size=1, random_state=None):
+        n, shape = self._dist._process_size(size)
+        out = self._dist._rvs(n, shape, self.dim, self.df,
+                              self.C, random_state)
+        return _squeeze_output(out)
+
+    def entropy(self):
+        return self._dist._entropy(self.dim, self.df, self.log_det_scale)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# Wishart and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'mean', 'mode', 'var', 'rvs', 'entropy']:
+    method = wishart_gen.__dict__[name]
+    method_frozen = wishart_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, wishart_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, wishart_docdict_params)
+
+
+class invwishart_gen(wishart_gen):
+    r"""An inverse Wishart random variable.
+
+    The `df` keyword specifies the degrees of freedom. The `scale` keyword
+    specifies the scale matrix, which must be symmetric and positive definite.
+    In this context, the scale matrix is often interpreted in terms of a
+    multivariate normal covariance matrix.
+
+    Methods
+    -------
+    pdf(x, df, scale)
+        Probability density function.
+    logpdf(x, df, scale)
+        Log of the probability density function.
+    rvs(df, scale, size=1, random_state=None)
+        Draw random samples from an inverse Wishart distribution.
+    entropy(df, scale)
+        Differential entropy of the distribution.
+
+    Parameters
+    ----------
+    %(_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Raises
+    ------
+    scipy.linalg.LinAlgError
+        If the scale matrix `scale` is not positive definite.
+
+    See Also
+    --------
+    wishart
+
+    Notes
+    -----
+    %(_doc_callparams_note)s
+
+    The scale matrix `scale` must be a symmetric positive definite
+    matrix. Singular matrices, including the symmetric positive semi-definite
+    case, are not supported. Symmetry is not checked; only the lower triangular
+    portion is used.
+
+    The inverse Wishart distribution is often denoted
+
+    .. math::
+
+        W_p^{-1}(\nu, \Psi)
+
+    where :math:`\nu` is the degrees of freedom and :math:`\Psi` is the
+    :math:`p \times p` scale matrix.
+
+    The probability density function for `invwishart` has support over positive
+    definite matrices :math:`S`; if :math:`S \sim W^{-1}_p(\nu, \Sigma)`,
+    then its PDF is given by:
+
+    .. math::
+
+        f(S) = \frac{|\Sigma|^\frac{\nu}{2}}{2^{ \frac{\nu p}{2} }
+               |S|^{\frac{\nu + p + 1}{2}} \Gamma_p \left(\frac{\nu}{2} \right)}
+               \exp\left( -tr(\Sigma S^{-1}) / 2 \right)
+
+    If :math:`S \sim W_p^{-1}(\nu, \Psi)` (inverse Wishart) then
+    :math:`S^{-1} \sim W_p(\nu, \Psi^{-1})` (Wishart).
+
+    If the scale matrix is 1-dimensional and equal to one, then the inverse
+    Wishart distribution :math:`W_1(\nu, 1)` collapses to the
+    inverse Gamma distribution with parameters shape = :math:`\frac{\nu}{2}`
+    and scale = :math:`\frac{1}{2}`.
+
+    Instead of inverting a randomly generated Wishart matrix as described in [2],
+    here the algorithm in [4] is used to directly generate a random inverse-Wishart
+    matrix without inversion.
+
+    .. versionadded:: 0.16.0
+
+    References
+    ----------
+    .. [1] M.L. Eaton, "Multivariate Statistics: A Vector Space Approach",
+           Wiley, 1983.
+    .. [2] M.C. Jones, "Generating Inverse Wishart Matrices", Communications
+           in Statistics - Simulation and Computation, vol. 14.2, pp.511-514,
+           1985.
+    .. [3] Gupta, M. and Srivastava, S. "Parametric Bayesian Estimation of
+           Differential Entropy and Relative Entropy". Entropy 12, 818 - 843.
+           2010.
+    .. [4] S.D. Axen, "Efficiently generating inverse-Wishart matrices and
+           their Cholesky factors", :arXiv:`2310.15884v1`. 2023.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import invwishart, invgamma
+    >>> x = np.linspace(0.01, 1, 100)
+    >>> iw = invwishart.pdf(x, df=6, scale=1)
+    >>> iw[:3]
+    array([  1.20546865e-15,   5.42497807e-06,   4.45813929e-03])
+    >>> ig = invgamma.pdf(x, 6/2., scale=1./2)
+    >>> ig[:3]
+    array([  1.20546865e-15,   5.42497807e-06,   4.45813929e-03])
+    >>> plt.plot(x, iw)
+    >>> plt.show()
+
+    The input quantiles can be any shape of array, as long as the last
+    axis labels the components.
+
+    Alternatively, the object may be called (as a function) to fix the degrees
+    of freedom and scale parameters, returning a "frozen" inverse Wishart
+    random variable:
+
+    >>> rv = invwishart(df=1, scale=1)
+    >>> # Frozen object with the same methods but holding the given
+    >>> # degrees of freedom and scale fixed.
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, wishart_docdict_params)
+
+    def __call__(self, df=None, scale=None, seed=None):
+        """Create a frozen inverse Wishart distribution.
+
+        See `invwishart_frozen` for more information.
+
+        """
+        return invwishart_frozen(df, scale, seed)
+
+    def _logpdf(self, x, dim, df, log_det_scale, C):
+        """Log of the inverse Wishart probability density function.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability
+            density function.
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        log_det_scale : float
+            Logarithm of the determinant of the scale matrix
+        C : ndarray
+            Cholesky factorization of the scale matrix, lower triangular.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        # Retrieve tr(scale x^{-1})
+        log_det_x = np.empty(x.shape[-1])
+        tr_scale_x_inv = np.empty(x.shape[-1])
+        trsm = get_blas_funcs(('trsm'), (x,))
+        if dim > 1:
+            for i in range(x.shape[-1]):
+                Cx, log_det_x[i] = self._cholesky_logdet(x[:, :, i])
+                A = trsm(1., Cx, C, side=0, lower=True)
+                tr_scale_x_inv[i] = np.linalg.norm(A)**2
+        else:
+            log_det_x[:] = np.log(x[0, 0])
+            tr_scale_x_inv[:] = C[0, 0]**2 / x[0, 0]
+
+        # Log PDF
+        out = ((0.5 * df * log_det_scale - 0.5 * tr_scale_x_inv) -
+               (0.5 * df * dim * _LOG_2 + 0.5 * (df + dim + 1) * log_det_x) -
+               multigammaln(0.5*df, dim))
+
+        return out
+
+    def logpdf(self, x, df, scale):
+        """Log of the inverse Wishart probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+            Each quantile must be a symmetric positive definite matrix.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Log of the probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        x = self._process_quantiles(x, dim)
+        C, log_det_scale = self._cholesky_logdet(scale)
+        out = self._logpdf(x, dim, df, log_det_scale, C)
+        return _squeeze_output(out)
+
+    def pdf(self, x, df, scale):
+        """Inverse Wishart probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+            Each quantile must be a symmetric positive definite matrix.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : ndarray
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        return np.exp(self.logpdf(x, df, scale))
+
+    def _mean(self, dim, df, scale):
+        """Mean of the inverse Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'mean' instead.
+
+        """
+        if df > dim + 1:
+            out = scale / (df - dim - 1)
+        else:
+            out = None
+        return out
+
+    def mean(self, df, scale):
+        """Mean of the inverse Wishart distribution.
+
+        Only valid if the degrees of freedom are greater than the dimension of
+        the scale matrix plus one.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mean : float or None
+            The mean of the distribution
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._mean(dim, df, scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def _mode(self, dim, df, scale):
+        """Mode of the inverse Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'mode' instead.
+
+        """
+        return scale / (df + dim + 1)
+
+    def mode(self, df, scale):
+        """Mode of the inverse Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mode : float
+            The Mode of the distribution
+
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._mode(dim, df, scale)
+        return _squeeze_output(out)
+
+    def _var(self, dim, df, scale):
+        """Variance of the inverse Wishart distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of the scale matrix
+        %(_doc_default_callparams)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'var' instead.
+
+        """
+        if df > dim + 3:
+            var = (df - dim + 1) * scale**2
+            diag = scale.diagonal()  # 1 x dim array
+            var += (df - dim - 1) * np.outer(diag, diag)
+            var /= (df - dim) * (df - dim - 1)**2 * (df - dim - 3)
+        else:
+            var = None
+        return var
+
+    def var(self, df, scale):
+        """Variance of the inverse Wishart distribution.
+
+        Only valid if the degrees of freedom are greater than the dimension of
+        the scale matrix plus three.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        var : float
+            The variance of the distribution
+        """
+        dim, df, scale = self._process_parameters(df, scale)
+        out = self._var(dim, df, scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def _inv_standard_rvs(self, n, shape, dim, df, random_state):
+        """
+        Parameters
+        ----------
+        n : integer
+            Number of variates to generate
+        shape : iterable
+            Shape of the variates to generate
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+
+        Returns
+        -------
+        A : ndarray
+            Random variates of shape (`shape`) + (``dim``, ``dim``).
+            Each slice `A[..., :, :]` is lower-triangular, and its
+            inverse is the lower Cholesky factor of a draw from
+            `invwishart(df, np.eye(dim))`.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'rvs' instead.
+
+        """
+        A = np.zeros(shape + (dim, dim))
+
+        # Random normal variates for off-diagonal elements
+        tri_rows, tri_cols = np.tril_indices(dim, k=-1)
+        n_tril = dim * (dim-1) // 2
+        A[..., tri_rows, tri_cols] = random_state.normal(
+            size=(*shape, n_tril),
+        )
+
+        # Random chi variates for diagonal elements
+        rows = np.arange(dim)
+        chi_dfs = (df - dim + 1) + rows
+        A[..., rows, rows] = random_state.chisquare(
+            df=chi_dfs, size=(*shape, dim),
+        )**0.5
+
+        return A
+
+    def _rvs(self, n, shape, dim, df, C, random_state):
+        """Draw random samples from an inverse Wishart distribution.
+
+        Parameters
+        ----------
+        n : integer
+            Number of variates to generate
+        shape : iterable
+            Shape of the variates to generate
+        dim : int
+            Dimension of the scale matrix
+        df : int
+            Degrees of freedom
+        C : ndarray
+            Cholesky factorization of the scale matrix, lower triangular.
+        %(_doc_random_state)s
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be
+        called directly; use 'rvs' instead.
+
+        """
+        random_state = self._get_random_state(random_state)
+        # Get random draws A such that inv(A) ~ iW(df, I)
+        A = self._inv_standard_rvs(n, shape, dim, df, random_state)
+
+        # Calculate SA = (CA)'^{-1} (CA)^{-1} ~ iW(df, scale)
+        trsm = get_blas_funcs(('trsm'), (A,))
+        trmm = get_blas_funcs(('trmm'), (A,))
+
+        for index in np.ndindex(A.shape[:-2]):
+            if dim > 1:
+                # Calculate CA
+                # Get CA = C A^{-1} via triangular solver
+                CA = trsm(1., A[index], C, side=1, lower=True)
+                # get SA
+                A[index] = trmm(1., CA, CA, side=1, lower=True, trans_a=True)
+            else:
+                A[index][0, 0] = (C[0, 0] / A[index][0, 0])**2
+
+        return A
+
+    def rvs(self, df, scale, size=1, random_state=None):
+        """Draw random samples from an inverse Wishart distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+        size : integer or iterable of integers, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray
+            Random variates of shape (`size`) + (``dim``, ``dim``), where
+            ``dim`` is the dimension of the scale matrix.
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        """
+        n, shape = self._process_size(size)
+        dim, df, scale = self._process_parameters(df, scale)
+
+        # Cholesky decomposition of scale
+        C = scipy.linalg.cholesky(scale, lower=True)
+
+        out = self._rvs(n, shape, dim, df, C, random_state)
+
+        return _squeeze_output(out)
+
+    def _entropy(self, dim, df, log_det_scale):
+        # reference: eq. (17) from ref. 3
+        psi_eval_points = [0.5 * (df - dim + i) for i in range(1, dim + 1)]
+        psi_eval_points = np.asarray(psi_eval_points)
+        return multigammaln(0.5 * df, dim) + 0.5 * dim * df + \
+            0.5 * (dim + 1) * (log_det_scale - _LOG_2) - \
+            0.5 * (df + dim + 1) * \
+            psi(psi_eval_points, out=psi_eval_points).sum()
+
+    def entropy(self, df, scale):
+        dim, df, scale = self._process_parameters(df, scale)
+        _, log_det_scale = self._cholesky_logdet(scale)
+        return self._entropy(dim, df, log_det_scale)
+
+
+invwishart = invwishart_gen()
+
+
+class invwishart_frozen(multi_rv_frozen):
+    def __init__(self, df, scale, seed=None):
+        """Create a frozen inverse Wishart distribution.
+
+        Parameters
+        ----------
+        df : array_like
+            Degrees of freedom of the distribution
+        scale : array_like
+            Scale matrix of the distribution
+        seed : {None, int, `numpy.random.Generator`}, optional
+            If `seed` is None the `numpy.random.Generator` singleton is used.
+            If `seed` is an int, a new ``Generator`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` instance then that instance is
+            used.
+
+        """
+        self._dist = invwishart_gen(seed)
+        self.dim, self.df, self.scale = self._dist._process_parameters(
+            df, scale
+        )
+
+        # Get the determinant via Cholesky factorization
+        self.C = scipy.linalg.cholesky(self.scale, lower=True)
+        self.log_det_scale = 2 * np.sum(np.log(self.C.diagonal()))
+
+    def logpdf(self, x):
+        x = self._dist._process_quantiles(x, self.dim)
+        out = self._dist._logpdf(x, self.dim, self.df,
+                                 self.log_det_scale, self.C)
+        return _squeeze_output(out)
+
+    def pdf(self, x):
+        return np.exp(self.logpdf(x))
+
+    def mean(self):
+        out = self._dist._mean(self.dim, self.df, self.scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def mode(self):
+        out = self._dist._mode(self.dim, self.df, self.scale)
+        return _squeeze_output(out)
+
+    def var(self):
+        out = self._dist._var(self.dim, self.df, self.scale)
+        return _squeeze_output(out) if out is not None else out
+
+    def rvs(self, size=1, random_state=None):
+        n, shape = self._dist._process_size(size)
+
+        out = self._dist._rvs(n, shape, self.dim, self.df,
+                              self.C, random_state)
+
+        return _squeeze_output(out)
+
+    def entropy(self):
+        return self._dist._entropy(self.dim, self.df, self.log_det_scale)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# inverse Wishart and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'mean', 'mode', 'var', 'rvs']:
+    method = invwishart_gen.__dict__[name]
+    method_frozen = wishart_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, wishart_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, wishart_docdict_params)
+
+_multinomial_doc_default_callparams = """\
+n : int
+    Number of trials
+p : array_like
+    Probability of a trial falling into each category; should sum to 1
+"""
+
+_multinomial_doc_callparams_note = """\
+`n` should be a nonnegative integer. Each element of `p` should be in the
+interval :math:`[0,1]` and the elements should sum to 1. If they do not sum to
+1, the last element of the `p` array is not used and is replaced with the
+remaining probability left over from the earlier elements.
+"""
+
+_multinomial_doc_frozen_callparams = ""
+
+_multinomial_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+multinomial_docdict_params = {
+    '_doc_default_callparams': _multinomial_doc_default_callparams,
+    '_doc_callparams_note': _multinomial_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+multinomial_docdict_noparams = {
+    '_doc_default_callparams': _multinomial_doc_frozen_callparams,
+    '_doc_callparams_note': _multinomial_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class multinomial_gen(multi_rv_generic):
+    r"""A multinomial random variable.
+
+    Methods
+    -------
+    pmf(x, n, p)
+        Probability mass function.
+    logpmf(x, n, p)
+        Log of the probability mass function.
+    rvs(n, p, size=1, random_state=None)
+        Draw random samples from a multinomial distribution.
+    entropy(n, p)
+        Compute the entropy of the multinomial distribution.
+    cov(n, p)
+        Compute the covariance matrix of the multinomial distribution.
+
+    Parameters
+    ----------
+    %(_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_doc_callparams_note)s
+
+    The probability mass function for `multinomial` is
+
+    .. math::
+
+        f(x) = \frac{n!}{x_1! \cdots x_k!} p_1^{x_1} \cdots p_k^{x_k},
+
+    supported on :math:`x=(x_1, \ldots, x_k)` where each :math:`x_i` is a
+    nonnegative integer and their sum is :math:`n`.
+
+    .. versionadded:: 0.19.0
+
+    Examples
+    --------
+
+    >>> from scipy.stats import multinomial
+    >>> rv = multinomial(8, [0.3, 0.2, 0.5])
+    >>> rv.pmf([1, 3, 4])
+    0.042000000000000072
+
+    The multinomial distribution for :math:`k=2` is identical to the
+    corresponding binomial distribution (tiny numerical differences
+    notwithstanding):
+
+    >>> from scipy.stats import binom
+    >>> multinomial.pmf([3, 4], n=7, p=[0.4, 0.6])
+    0.29030399999999973
+    >>> binom.pmf(3, 7, 0.4)
+    0.29030400000000012
+
+    The functions ``pmf``, ``logpmf``, ``entropy``, and ``cov`` support
+    broadcasting, under the convention that the vector parameters (``x`` and
+    ``p``) are interpreted as if each row along the last axis is a single
+    object. For instance:
+
+    >>> multinomial.pmf([[3, 4], [3, 5]], n=[7, 8], p=[.3, .7])
+    array([0.2268945,  0.25412184])
+
+    Here, ``x.shape == (2, 2)``, ``n.shape == (2,)``, and ``p.shape == (2,)``,
+    but following the rules mentioned above they behave as if the rows
+    ``[3, 4]`` and ``[3, 5]`` in ``x`` and ``[.3, .7]`` in ``p`` were a single
+    object, and as if we had ``x.shape = (2,)``, ``n.shape = (2,)``, and
+    ``p.shape = ()``. To obtain the individual elements without broadcasting,
+    we would do this:
+
+    >>> multinomial.pmf([3, 4], n=7, p=[.3, .7])
+    0.2268945
+    >>> multinomial.pmf([3, 5], 8, p=[.3, .7])
+    0.25412184
+
+    This broadcasting also works for ``cov``, where the output objects are
+    square matrices of size ``p.shape[-1]``. For example:
+
+    >>> multinomial.cov([4, 5], [[.3, .7], [.4, .6]])
+    array([[[ 0.84, -0.84],
+            [-0.84,  0.84]],
+           [[ 1.2 , -1.2 ],
+            [-1.2 ,  1.2 ]]])
+
+    In this example, ``n.shape == (2,)`` and ``p.shape == (2, 2)``, and
+    following the rules above, these broadcast as if ``p.shape == (2,)``.
+    Thus the result should also be of shape ``(2,)``, but since each output is
+    a :math:`2 \times 2` matrix, the result in fact has shape ``(2, 2, 2)``,
+    where ``result[0]`` is equal to ``multinomial.cov(n=4, p=[.3, .7])`` and
+    ``result[1]`` is equal to ``multinomial.cov(n=5, p=[.4, .6])``.
+
+    Alternatively, the object may be called (as a function) to fix the `n` and
+    `p` parameters, returning a "frozen" multinomial random variable:
+
+    >>> rv = multinomial(n=7, p=[.3, .7])
+    >>> # Frozen object with the same methods but holding the given
+    >>> # degrees of freedom and scale fixed.
+
+    See also
+    --------
+    scipy.stats.binom : The binomial distribution.
+    numpy.random.Generator.multinomial : Sampling from the multinomial distribution.
+    scipy.stats.multivariate_hypergeom :
+        The multivariate hypergeometric distribution.
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = \
+            doccer.docformat(self.__doc__, multinomial_docdict_params)
+
+    def __call__(self, n, p, seed=None):
+        """Create a frozen multinomial distribution.
+
+        See `multinomial_frozen` for more information.
+        """
+        return multinomial_frozen(n, p, seed)
+
+    def _process_parameters(self, n, p, eps=1e-15):
+        """Returns: n_, p_, npcond.
+
+        n_ and p_ are arrays of the correct shape; npcond is a boolean array
+        flagging values out of the domain.
+        """
+        p = np.array(p, dtype=np.float64, copy=True)
+        p_adjusted = 1. - p[..., :-1].sum(axis=-1)
+        i_adjusted = np.abs(p_adjusted) > eps
+        p[i_adjusted, -1] = p_adjusted[i_adjusted]
+
+        # true for bad p
+        pcond = np.any(p < 0, axis=-1)
+        pcond |= np.any(p > 1, axis=-1)
+
+        n = np.array(n, dtype=int, copy=True)
+
+        # true for bad n
+        ncond = n < 0
+
+        return n, p, ncond | pcond
+
+    def _process_quantiles(self, x, n, p):
+        """Returns: x_, xcond.
+
+        x_ is an int array; xcond is a boolean array flagging values out of the
+        domain.
+        """
+        xx = np.asarray(x, dtype=int)
+
+        if xx.ndim == 0:
+            raise ValueError("x must be an array.")
+
+        if xx.size != 0 and not xx.shape[-1] == p.shape[-1]:
+            raise ValueError("Size of each quantile should be size of p: "
+                             "received %d, but expected %d." %
+                             (xx.shape[-1], p.shape[-1]))
+
+        # true for x out of the domain
+        cond = np.any(xx != x, axis=-1)
+        cond |= np.any(xx < 0, axis=-1)
+        cond = cond | (np.sum(xx, axis=-1) != n)
+
+        return xx, cond
+
+    def _checkresult(self, result, cond, bad_value):
+        result = np.asarray(result)
+
+        if cond.ndim != 0:
+            result[cond] = bad_value
+        elif cond:
+            if result.ndim == 0:
+                return bad_value
+            result[...] = bad_value
+        return result
+
+    def _logpmf(self, x, n, p):
+        return gammaln(n+1) + np.sum(xlogy(x, p) - gammaln(x+1), axis=-1)
+
+    def logpmf(self, x, n, p):
+        """Log of the Multinomial probability mass function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        logpmf : ndarray or scalar
+            Log of the probability mass function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        n, p, npcond = self._process_parameters(n, p)
+        x, xcond = self._process_quantiles(x, n, p)
+
+        result = self._logpmf(x, n, p)
+
+        # replace values for which x was out of the domain; broadcast
+        # xcond to the right shape
+        xcond_ = xcond | np.zeros(npcond.shape, dtype=np.bool_)
+        result = self._checkresult(result, xcond_, -np.inf)
+
+        # replace values bad for n or p; broadcast npcond to the right shape
+        npcond_ = npcond | np.zeros(xcond.shape, dtype=np.bool_)
+        return self._checkresult(result, npcond_, np.nan)
+
+    def pmf(self, x, n, p):
+        """Multinomial probability mass function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pmf : ndarray or scalar
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        return np.exp(self.logpmf(x, n, p))
+
+    def mean(self, n, p):
+        """Mean of the Multinomial distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mean : float
+            The mean of the distribution
+        """
+        n, p, npcond = self._process_parameters(n, p)
+        result = n[..., np.newaxis]*p
+        return self._checkresult(result, npcond, np.nan)
+
+    def cov(self, n, p):
+        """Covariance matrix of the multinomial distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        cov : ndarray
+            The covariance matrix of the distribution
+        """
+        n, p, npcond = self._process_parameters(n, p)
+
+        nn = n[..., np.newaxis, np.newaxis]
+        result = nn * np.einsum('...j,...k->...jk', -p, p)
+
+        # change the diagonal
+        for i in range(p.shape[-1]):
+            result[..., i, i] += n*p[..., i]
+
+        return self._checkresult(result, npcond, np.nan)
+
+    def entropy(self, n, p):
+        r"""Compute the entropy of the multinomial distribution.
+
+        The entropy is computed using this expression:
+
+        .. math::
+
+            f(x) = - \log n! - n\sum_{i=1}^k p_i \log p_i +
+            \sum_{i=1}^k \sum_{x=0}^n \binom n x p_i^x(1-p_i)^{n-x} \log x!
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the Multinomial distribution
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        n, p, npcond = self._process_parameters(n, p)
+
+        x = np.r_[1:np.max(n)+1]
+
+        term1 = n*np.sum(entr(p), axis=-1)
+        term1 -= gammaln(n+1)
+
+        n = n[..., np.newaxis]
+        new_axes_needed = max(p.ndim, n.ndim) - x.ndim + 1
+        x.shape += (1,)*new_axes_needed
+
+        term2 = np.sum(binom.pmf(x, n, p)*gammaln(x+1),
+                       axis=(-1, -1-new_axes_needed))
+
+        return self._checkresult(term1 + term2, npcond, np.nan)
+
+    def rvs(self, n, p, size=None, random_state=None):
+        """Draw random samples from a Multinomial distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+        size : integer or iterable of integers, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of shape (`size`, `len(p)`)
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        n, p, npcond = self._process_parameters(n, p)
+        random_state = self._get_random_state(random_state)
+        return random_state.multinomial(n, p, size)
+
+
+multinomial = multinomial_gen()
+
+
+class multinomial_frozen(multi_rv_frozen):
+    r"""Create a frozen Multinomial distribution.
+
+    Parameters
+    ----------
+    n : int
+        number of trials
+    p: array_like
+        probability of a trial falling into each category; should sum to 1
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+    """
+    def __init__(self, n, p, seed=None):
+        self._dist = multinomial_gen(seed)
+        self.n, self.p, self.npcond = self._dist._process_parameters(n, p)
+
+        # monkey patch self._dist
+        def _process_parameters(n, p):
+            return self.n, self.p, self.npcond
+
+        self._dist._process_parameters = _process_parameters
+
+    def logpmf(self, x):
+        return self._dist.logpmf(x, self.n, self.p)
+
+    def pmf(self, x):
+        return self._dist.pmf(x, self.n, self.p)
+
+    def mean(self):
+        return self._dist.mean(self.n, self.p)
+
+    def cov(self):
+        return self._dist.cov(self.n, self.p)
+
+    def entropy(self):
+        return self._dist.entropy(self.n, self.p)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.n, self.p, size, random_state)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multinomial and fill in default strings in class docstrings
+for name in ['logpmf', 'pmf', 'mean', 'cov', 'rvs']:
+    method = multinomial_gen.__dict__[name]
+    method_frozen = multinomial_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, multinomial_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__,
+                                      multinomial_docdict_params)
+
+
+class special_ortho_group_gen(multi_rv_generic):
+    r"""A Special Orthogonal matrix (SO(N)) random variable.
+
+    Return a random rotation matrix, drawn from the Haar distribution
+    (the only uniform distribution on SO(N)) with a determinant of +1.
+
+    The `dim` keyword specifies the dimension N.
+
+    Methods
+    -------
+    rvs(dim=None, size=1, random_state=None)
+        Draw random samples from SO(N).
+
+    Parameters
+    ----------
+    dim : scalar
+        Dimension of matrices
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Notes
+    -----
+    This class is wrapping the random_rot code from the MDP Toolkit,
+    https://github.com/mdp-toolkit/mdp-toolkit
+
+    Return a random rotation matrix, drawn from the Haar distribution
+    (the only uniform distribution on SO(N)).
+    The algorithm is described in the paper
+    Stewart, G.W., "The efficient generation of random orthogonal
+    matrices with an application to condition estimators", SIAM Journal
+    on Numerical Analysis, 17(3), pp. 403-409, 1980.
+    For more information see
+    https://en.wikipedia.org/wiki/Orthogonal_matrix#Randomization
+
+    See also the similar `ortho_group`. For a random rotation in three
+    dimensions, see `scipy.spatial.transform.Rotation.random`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import special_ortho_group
+    >>> x = special_ortho_group.rvs(3)
+
+    >>> np.dot(x, x.T)
+    array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
+           [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
+           [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])
+
+    >>> import scipy.linalg
+    >>> scipy.linalg.det(x)
+    1.0
+
+    This generates one random matrix from SO(3). It is orthogonal and
+    has a determinant of 1.
+
+    Alternatively, the object may be called (as a function) to fix the `dim`
+    parameter, returning a "frozen" special_ortho_group random variable:
+
+    >>> rv = special_ortho_group(5)
+    >>> # Frozen object with the same methods but holding the
+    >>> # dimension parameter fixed.
+
+    See Also
+    --------
+    ortho_group, scipy.spatial.transform.Rotation.random
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, dim=None, seed=None):
+        """Create a frozen SO(N) distribution.
+
+        See `special_ortho_group_frozen` for more information.
+        """
+        return special_ortho_group_frozen(dim, seed=seed)
+
+    def _process_parameters(self, dim):
+        """Dimension N must be specified; it cannot be inferred."""
+        if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim):
+            raise ValueError("""Dimension of rotation must be specified,
+                                and must be a scalar greater than 1.""")
+
+        return dim
+
+    def rvs(self, dim, size=1, random_state=None):
+        """Draw random samples from SO(N).
+
+        Parameters
+        ----------
+        dim : integer
+            Dimension of rotation space (N).
+        size : integer, optional
+            Number of samples to draw (default 1).
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim)
+
+        """
+        random_state = self._get_random_state(random_state)
+
+        size = int(size)
+        size = (size,) if size > 1 else ()
+
+        dim = self._process_parameters(dim)
+
+        # H represents a (dim, dim) matrix, while D represents the diagonal of
+        # a (dim, dim) diagonal matrix. The algorithm that follows is
+        # broadcasted on the leading shape in `size` to vectorize along
+        # samples.
+        H = np.empty(size + (dim, dim))
+        H[..., :, :] = np.eye(dim)
+        D = np.empty(size + (dim,))
+
+        for n in range(dim-1):
+
+            # x is a vector with length dim-n, xrow and xcol are views of it as
+            # a row vector and column vector respectively. It's important they
+            # are views and not copies because we are going to modify x
+            # in-place.
+            x = random_state.normal(size=size + (dim-n,))
+            xrow = x[..., None, :]
+            xcol = x[..., :, None]
+
+            # This is the squared norm of x, without vectorization it would be
+            # dot(x, x), to have proper broadcasting we use matmul and squeeze
+            # out (convert to scalar) the resulting 1x1 matrix
+            norm2 = np.matmul(xrow, xcol).squeeze((-2, -1))
+
+            x0 = x[..., 0].copy()
+            D[..., n] = np.where(x0 != 0, np.sign(x0), 1)
+            x[..., 0] += D[..., n]*np.sqrt(norm2)
+
+            # In renormalizing x we have to append an additional axis with
+            # [..., None] to broadcast the scalar against the vector x
+            x /= np.sqrt((norm2 - x0**2 + x[..., 0]**2) / 2.)[..., None]
+
+            # Householder transformation, without vectorization the RHS can be
+            # written as outer(H @ x, x) (apart from the slicing)
+            H[..., :, n:] -= np.matmul(H[..., :, n:], xcol) * xrow
+
+        D[..., -1] = (-1)**(dim-1)*D[..., :-1].prod(axis=-1)
+
+        # Without vectorization this could be written as H = diag(D) @ H,
+        # left-multiplication by a diagonal matrix amounts to multiplying each
+        # row of H by an element of the diagonal, so we add a dummy axis for
+        # the column index
+        H *= D[..., :, None]
+        return H
+
+
+special_ortho_group = special_ortho_group_gen()
+
+
+class special_ortho_group_frozen(multi_rv_frozen):
+    def __init__(self, dim=None, seed=None):
+        """Create a frozen SO(N) distribution.
+
+        Parameters
+        ----------
+        dim : scalar
+            Dimension of matrices
+        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+
+        Examples
+        --------
+        >>> from scipy.stats import special_ortho_group
+        >>> g = special_ortho_group(5)
+        >>> x = g.rvs()
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        self._dist = special_ortho_group_gen(seed)
+        self.dim = self._dist._process_parameters(dim)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.dim, size, random_state)
+
+
+class ortho_group_gen(multi_rv_generic):
+    r"""An Orthogonal matrix (O(N)) random variable.
+
+    Return a random orthogonal matrix, drawn from the O(N) Haar
+    distribution (the only uniform distribution on O(N)).
+
+    The `dim` keyword specifies the dimension N.
+
+    Methods
+    -------
+    rvs(dim=None, size=1, random_state=None)
+        Draw random samples from O(N).
+
+    Parameters
+    ----------
+    dim : scalar
+        Dimension of matrices
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Notes
+    -----
+    This class is closely related to `special_ortho_group`.
+
+    Some care is taken to avoid numerical error, as per the paper by Mezzadri.
+
+    References
+    ----------
+    .. [1] F. Mezzadri, "How to generate random matrices from the classical
+           compact groups", :arXiv:`math-ph/0609050v2`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import ortho_group
+    >>> x = ortho_group.rvs(3)
+
+    >>> np.dot(x, x.T)
+    array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
+           [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
+           [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])
+
+    >>> import scipy.linalg
+    >>> np.fabs(scipy.linalg.det(x))
+    1.0
+
+    This generates one random matrix from O(3). It is orthogonal and
+    has a determinant of +1 or -1.
+
+    Alternatively, the object may be called (as a function) to fix the `dim`
+    parameter, returning a "frozen" ortho_group random variable:
+
+    >>> rv = ortho_group(5)
+    >>> # Frozen object with the same methods but holding the
+    >>> # dimension parameter fixed.
+
+    See Also
+    --------
+    special_ortho_group
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, dim=None, seed=None):
+        """Create a frozen O(N) distribution.
+
+        See `ortho_group_frozen` for more information.
+        """
+        return ortho_group_frozen(dim, seed=seed)
+
+    def _process_parameters(self, dim):
+        """Dimension N must be specified; it cannot be inferred."""
+        if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim):
+            raise ValueError("Dimension of rotation must be specified,"
+                             "and must be a scalar greater than 1.")
+
+        return dim
+
+    def rvs(self, dim, size=1, random_state=None):
+        """Draw random samples from O(N).
+
+        Parameters
+        ----------
+        dim : integer
+            Dimension of rotation space (N).
+        size : integer, optional
+            Number of samples to draw (default 1).
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim)
+
+        """
+        random_state = self._get_random_state(random_state)
+
+        size = int(size)
+
+        dim = self._process_parameters(dim)
+
+        size = (size,) if size > 1 else ()
+        z = random_state.normal(size=size + (dim, dim))
+        q, r = np.linalg.qr(z)
+        # The last two dimensions are the rows and columns of R matrices.
+        # Extract the diagonals. Note that this eliminates a dimension.
+        d = r.diagonal(offset=0, axis1=-2, axis2=-1)
+        # Add back a dimension for proper broadcasting: we're dividing
+        # each row of each R matrix by the diagonal of the R matrix.
+        q *= (d/abs(d))[..., np.newaxis, :]  # to broadcast properly
+        return q
+
+
+ortho_group = ortho_group_gen()
+
+
+class ortho_group_frozen(multi_rv_frozen):
+    def __init__(self, dim=None, seed=None):
+        """Create a frozen O(N) distribution.
+
+        Parameters
+        ----------
+        dim : scalar
+            Dimension of matrices
+        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+
+        Examples
+        --------
+        >>> from scipy.stats import ortho_group
+        >>> g = ortho_group(5)
+        >>> x = g.rvs()
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        self._dist = ortho_group_gen(seed)
+        self.dim = self._dist._process_parameters(dim)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.dim, size, random_state)
+
+
+class random_correlation_gen(multi_rv_generic):
+    r"""A random correlation matrix.
+
+    Return a random correlation matrix, given a vector of eigenvalues.
+
+    The `eigs` keyword specifies the eigenvalues of the correlation matrix,
+    and implies the dimension.
+
+    Methods
+    -------
+    rvs(eigs=None, random_state=None)
+        Draw random correlation matrices, all with eigenvalues eigs.
+
+    Parameters
+    ----------
+    eigs : 1d ndarray
+        Eigenvalues of correlation matrix
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance
+        then that instance is used.
+    tol : float, optional
+        Tolerance for input parameter checks
+    diag_tol : float, optional
+        Tolerance for deviation of the diagonal of the resulting
+        matrix. Default: 1e-7
+
+    Raises
+    ------
+    RuntimeError
+        Floating point error prevented generating a valid correlation
+        matrix.
+
+    Returns
+    -------
+    rvs : ndarray or scalar
+        Random size N-dimensional matrices, dimension (size, dim, dim),
+        each having eigenvalues eigs.
+
+    Notes
+    -----
+
+    Generates a random correlation matrix following a numerically stable
+    algorithm spelled out by Davies & Higham. This algorithm uses a single O(N)
+    similarity transformation to construct a symmetric positive semi-definite
+    matrix, and applies a series of Givens rotations to scale it to have ones
+    on the diagonal.
+
+    References
+    ----------
+
+    .. [1] Davies, Philip I; Higham, Nicholas J; "Numerically stable generation
+           of correlation matrices and their factors", BIT 2000, Vol. 40,
+           No. 4, pp. 640 651
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import random_correlation
+    >>> rng = np.random.default_rng()
+    >>> x = random_correlation.rvs((.5, .8, 1.2, 1.5), random_state=rng)
+    >>> x
+    array([[ 1.        , -0.02423399,  0.03130519,  0.4946965 ],
+           [-0.02423399,  1.        ,  0.20334736,  0.04039817],
+           [ 0.03130519,  0.20334736,  1.        ,  0.02694275],
+           [ 0.4946965 ,  0.04039817,  0.02694275,  1.        ]])
+    >>> import scipy.linalg
+    >>> e, v = scipy.linalg.eigh(x)
+    >>> e
+    array([ 0.5,  0.8,  1.2,  1.5])
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, eigs, seed=None, tol=1e-13, diag_tol=1e-7):
+        """Create a frozen random correlation matrix.
+
+        See `random_correlation_frozen` for more information.
+        """
+        return random_correlation_frozen(eigs, seed=seed, tol=tol,
+                                         diag_tol=diag_tol)
+
+    def _process_parameters(self, eigs, tol):
+        eigs = np.asarray(eigs, dtype=float)
+        dim = eigs.size
+
+        if eigs.ndim != 1 or eigs.shape[0] != dim or dim <= 1:
+            raise ValueError("Array 'eigs' must be a vector of length "
+                             "greater than 1.")
+
+        if np.fabs(np.sum(eigs) - dim) > tol:
+            raise ValueError("Sum of eigenvalues must equal dimensionality.")
+
+        for x in eigs:
+            if x < -tol:
+                raise ValueError("All eigenvalues must be non-negative.")
+
+        return dim, eigs
+
+    def _givens_to_1(self, aii, ajj, aij):
+        """Computes a 2x2 Givens matrix to put 1's on the diagonal.
+
+        The input matrix is a 2x2 symmetric matrix M = [ aii aij ; aij ajj ].
+
+        The output matrix g is a 2x2 anti-symmetric matrix of the form
+        [ c s ; -s c ];  the elements c and s are returned.
+
+        Applying the output matrix to the input matrix (as b=g.T M g)
+        results in a matrix with bii=1, provided tr(M) - det(M) >= 1
+        and floating point issues do not occur. Otherwise, some other
+        valid rotation is returned. When tr(M)==2, also bjj=1.
+
+        """
+        aiid = aii - 1.
+        ajjd = ajj - 1.
+
+        if ajjd == 0:
+            # ajj==1, so swap aii and ajj to avoid division by zero
+            return 0., 1.
+
+        dd = math.sqrt(max(aij**2 - aiid*ajjd, 0))
+
+        # The choice of t should be chosen to avoid cancellation [1]
+        t = (aij + math.copysign(dd, aij)) / ajjd
+        c = 1. / math.sqrt(1. + t*t)
+        if c == 0:
+            # Underflow
+            s = 1.0
+        else:
+            s = c*t
+        return c, s
+
+    def _to_corr(self, m):
+        """
+        Given a psd matrix m, rotate to put one's on the diagonal, turning it
+        into a correlation matrix.  This also requires the trace equal the
+        dimensionality. Note: modifies input matrix
+        """
+        # Check requirements for in-place Givens
+        if not (m.flags.c_contiguous and m.dtype == np.float64 and
+                m.shape[0] == m.shape[1]):
+            raise ValueError()
+
+        d = m.shape[0]
+        for i in range(d-1):
+            if m[i, i] == 1:
+                continue
+            elif m[i, i] > 1:
+                for j in range(i+1, d):
+                    if m[j, j] < 1:
+                        break
+            else:
+                for j in range(i+1, d):
+                    if m[j, j] > 1:
+                        break
+
+            c, s = self._givens_to_1(m[i, i], m[j, j], m[i, j])
+
+            # Use BLAS to apply Givens rotations in-place. Equivalent to:
+            # g = np.eye(d)
+            # g[i, i] = g[j,j] = c
+            # g[j, i] = -s; g[i, j] = s
+            # m = np.dot(g.T, np.dot(m, g))
+            mv = m.ravel()
+            drot(mv, mv, c, -s, n=d,
+                 offx=i*d, incx=1, offy=j*d, incy=1,
+                 overwrite_x=True, overwrite_y=True)
+            drot(mv, mv, c, -s, n=d,
+                 offx=i, incx=d, offy=j, incy=d,
+                 overwrite_x=True, overwrite_y=True)
+
+        return m
+
+    def rvs(self, eigs, random_state=None, tol=1e-13, diag_tol=1e-7):
+        """Draw random correlation matrices.
+
+        Parameters
+        ----------
+        eigs : 1d ndarray
+            Eigenvalues of correlation matrix
+        tol : float, optional
+            Tolerance for input parameter checks
+        diag_tol : float, optional
+            Tolerance for deviation of the diagonal of the resulting
+            matrix. Default: 1e-7
+
+        Raises
+        ------
+        RuntimeError
+            Floating point error prevented generating a valid correlation
+            matrix.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim),
+            each having eigenvalues eigs.
+
+        """
+        dim, eigs = self._process_parameters(eigs, tol=tol)
+
+        random_state = self._get_random_state(random_state)
+
+        m = ortho_group.rvs(dim, random_state=random_state)
+        m = np.dot(np.dot(m, np.diag(eigs)), m.T)  # Set the trace of m
+        m = self._to_corr(m)  # Carefully rotate to unit diagonal
+
+        # Check diagonal
+        if abs(m.diagonal() - 1).max() > diag_tol:
+            raise RuntimeError("Failed to generate a valid correlation matrix")
+
+        return m
+
+
+random_correlation = random_correlation_gen()
+
+
+class random_correlation_frozen(multi_rv_frozen):
+    def __init__(self, eigs, seed=None, tol=1e-13, diag_tol=1e-7):
+        """Create a frozen random correlation matrix distribution.
+
+        Parameters
+        ----------
+        eigs : 1d ndarray
+            Eigenvalues of correlation matrix
+        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+        tol : float, optional
+            Tolerance for input parameter checks
+        diag_tol : float, optional
+            Tolerance for deviation of the diagonal of the resulting
+            matrix. Default: 1e-7
+
+        Raises
+        ------
+        RuntimeError
+            Floating point error prevented generating a valid correlation
+            matrix.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim),
+            each having eigenvalues eigs.
+        """ # numpy/numpydoc#87  # noqa: E501
+
+        self._dist = random_correlation_gen(seed)
+        self.tol = tol
+        self.diag_tol = diag_tol
+        _, self.eigs = self._dist._process_parameters(eigs, tol=self.tol)
+
+    def rvs(self, random_state=None):
+        return self._dist.rvs(self.eigs, random_state=random_state,
+                              tol=self.tol, diag_tol=self.diag_tol)
+
+
+class unitary_group_gen(multi_rv_generic):
+    r"""A matrix-valued U(N) random variable.
+
+    Return a random unitary matrix.
+
+    The `dim` keyword specifies the dimension N.
+
+    Methods
+    -------
+    rvs(dim=None, size=1, random_state=None)
+        Draw random samples from U(N).
+
+    Parameters
+    ----------
+    dim : scalar
+        Dimension of matrices, must be greater than 1.
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Notes
+    -----
+    This class is similar to `ortho_group`.
+
+    References
+    ----------
+    .. [1] F. Mezzadri, "How to generate random matrices from the classical
+           compact groups", :arXiv:`math-ph/0609050v2`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import unitary_group
+    >>> x = unitary_group.rvs(3)
+
+    >>> np.dot(x, x.conj().T)
+    array([[  1.00000000e+00,   1.13231364e-17,  -2.86852790e-16],
+           [  1.13231364e-17,   1.00000000e+00,  -1.46845020e-16],
+           [ -2.86852790e-16,  -1.46845020e-16,   1.00000000e+00]])  # may vary
+
+    This generates one random matrix from U(3). The dot product confirms that
+    it is unitary up to machine precision.
+
+    Alternatively, the object may be called (as a function) to fix the `dim`
+    parameter, return a "frozen" unitary_group random variable:
+
+    >>> rv = unitary_group(5)
+
+    See Also
+    --------
+    ortho_group
+
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, dim=None, seed=None):
+        """Create a frozen (U(N)) n-dimensional unitary matrix distribution.
+
+        See `unitary_group_frozen` for more information.
+        """
+        return unitary_group_frozen(dim, seed=seed)
+
+    def _process_parameters(self, dim):
+        """Dimension N must be specified; it cannot be inferred."""
+        if dim is None or not np.isscalar(dim) or dim <= 1 or dim != int(dim):
+            raise ValueError("Dimension of rotation must be specified,"
+                             "and must be a scalar greater than 1.")
+
+        return dim
+
+    def rvs(self, dim, size=1, random_state=None):
+        """Draw random samples from U(N).
+
+        Parameters
+        ----------
+        dim : integer
+            Dimension of space (N).
+        size : integer, optional
+            Number of samples to draw (default 1).
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random size N-dimensional matrices, dimension (size, dim, dim)
+
+        """
+        random_state = self._get_random_state(random_state)
+
+        size = int(size)
+
+        dim = self._process_parameters(dim)
+
+        size = (size,) if size > 1 else ()
+        z = 1/math.sqrt(2)*(random_state.normal(size=size + (dim, dim)) +
+                            1j*random_state.normal(size=size + (dim, dim)))
+        q, r = np.linalg.qr(z)
+        # The last two dimensions are the rows and columns of R matrices.
+        # Extract the diagonals. Note that this eliminates a dimension.
+        d = r.diagonal(offset=0, axis1=-2, axis2=-1)
+        # Add back a dimension for proper broadcasting: we're dividing
+        # each row of each R matrix by the diagonal of the R matrix.
+        q *= (d/abs(d))[..., np.newaxis, :]  # to broadcast properly
+        return q
+
+
+unitary_group = unitary_group_gen()
+
+
+class unitary_group_frozen(multi_rv_frozen):
+    def __init__(self, dim=None, seed=None):
+        """Create a frozen (U(N)) n-dimensional unitary matrix distribution.
+
+        Parameters
+        ----------
+        dim : scalar
+            Dimension of matrices
+        seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+
+        Examples
+        --------
+        >>> from scipy.stats import unitary_group
+        >>> x = unitary_group(3)
+        >>> x.rvs()
+
+        """ # numpy/numpydoc#87  # noqa: E501
+        self._dist = unitary_group_gen(seed)
+        self.dim = self._dist._process_parameters(dim)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.dim, size, random_state)
+
+
+_mvt_doc_default_callparams = """\
+loc : array_like, optional
+    Location of the distribution. (default ``0``)
+shape : array_like, optional
+    Positive semidefinite matrix of the distribution. (default ``1``)
+df : float, optional
+    Degrees of freedom of the distribution; must be greater than zero.
+    If ``np.inf`` then results are multivariate normal. The default is ``1``.
+allow_singular : bool, optional
+    Whether to allow a singular matrix. (default ``False``)
+"""
+
+_mvt_doc_callparams_note = """\
+Setting the parameter `loc` to ``None`` is equivalent to having `loc`
+be the zero-vector. The parameter `shape` can be a scalar, in which case
+the shape matrix is the identity times that value, a vector of
+diagonal entries for the shape matrix, or a two-dimensional array_like.
+"""
+
+_mvt_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+mvt_docdict_params = {
+    '_mvt_doc_default_callparams': _mvt_doc_default_callparams,
+    '_mvt_doc_callparams_note': _mvt_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+mvt_docdict_noparams = {
+    '_mvt_doc_default_callparams': "",
+    '_mvt_doc_callparams_note': _mvt_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class multivariate_t_gen(multi_rv_generic):
+    r"""A multivariate t-distributed random variable.
+
+    The `loc` parameter specifies the location. The `shape` parameter specifies
+    the positive semidefinite shape matrix. The `df` parameter specifies the
+    degrees of freedom.
+
+    In addition to calling the methods below, the object itself may be called
+    as a function to fix the location, shape matrix, and degrees of freedom
+    parameters, returning a "frozen" multivariate t-distribution random.
+
+    Methods
+    -------
+    pdf(x, loc=None, shape=1, df=1, allow_singular=False)
+        Probability density function.
+    logpdf(x, loc=None, shape=1, df=1, allow_singular=False)
+        Log of the probability density function.
+    cdf(x, loc=None, shape=1, df=1, allow_singular=False, *,
+        maxpts=None, lower_limit=None, random_state=None)
+        Cumulative distribution function.
+    rvs(loc=None, shape=1, df=1, size=1, random_state=None)
+        Draw random samples from a multivariate t-distribution.
+    entropy(loc=None, shape=1, df=1)
+        Differential entropy of a multivariate t-distribution.
+
+    Parameters
+    ----------
+    %(_mvt_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_mvt_doc_callparams_note)s
+    The matrix `shape` must be a (symmetric) positive semidefinite matrix. The
+    determinant and inverse of `shape` are computed as the pseudo-determinant
+    and pseudo-inverse, respectively, so that `shape` does not need to have
+    full rank.
+
+    The probability density function for `multivariate_t` is
+
+    .. math::
+
+        f(x) = \frac{\Gamma((\nu + p)/2)}{\Gamma(\nu/2)\nu^{p/2}\pi^{p/2}|\Sigma|^{1/2}}
+               \left[1 + \frac{1}{\nu} (\mathbf{x} - \boldsymbol{\mu})^{\top}
+               \boldsymbol{\Sigma}^{-1}
+               (\mathbf{x} - \boldsymbol{\mu}) \right]^{-(\nu + p)/2},
+
+    where :math:`p` is the dimension of :math:`\mathbf{x}`,
+    :math:`\boldsymbol{\mu}` is the :math:`p`-dimensional location,
+    :math:`\boldsymbol{\Sigma}` the :math:`p \times p`-dimensional shape
+    matrix, and :math:`\nu` is the degrees of freedom.
+
+    .. versionadded:: 1.6.0
+
+    References
+    ----------
+    .. [1] Arellano-Valle et al. "Shannon Entropy and Mutual Information for
+           Multivariate Skew-Elliptical Distributions". Scandinavian Journal
+           of Statistics. Vol. 40, issue 1.
+
+    Examples
+    --------
+    The object may be called (as a function) to fix the `loc`, `shape`,
+    `df`, and `allow_singular` parameters, returning a "frozen"
+    multivariate_t random variable:
+
+    >>> import numpy as np
+    >>> from scipy.stats import multivariate_t
+    >>> rv = multivariate_t([1.0, -0.5], [[2.1, 0.3], [0.3, 1.5]], df=2)
+    >>> # Frozen object with the same methods but holding the given location,
+    >>> # scale, and degrees of freedom fixed.
+
+    Create a contour plot of the PDF.
+
+    >>> import matplotlib.pyplot as plt
+    >>> x, y = np.mgrid[-1:3:.01, -2:1.5:.01]
+    >>> pos = np.dstack((x, y))
+    >>> fig, ax = plt.subplots(1, 1)
+    >>> ax.set_aspect('equal')
+    >>> plt.contourf(x, y, rv.pdf(pos))
+
+    """
+
+    def __init__(self, seed=None):
+        """Initialize a multivariate t-distributed random variable.
+
+        Parameters
+        ----------
+        seed : Random state.
+
+        """
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, mvt_docdict_params)
+        self._random_state = check_random_state(seed)
+
+    def __call__(self, loc=None, shape=1, df=1, allow_singular=False,
+                 seed=None):
+        """Create a frozen multivariate t-distribution.
+
+        See `multivariate_t_frozen` for parameters.
+        """
+        if df == np.inf:
+            return multivariate_normal_frozen(mean=loc, cov=shape,
+                                              allow_singular=allow_singular,
+                                              seed=seed)
+        return multivariate_t_frozen(loc=loc, shape=shape, df=df,
+                                     allow_singular=allow_singular, seed=seed)
+
+    def pdf(self, x, loc=None, shape=1, df=1, allow_singular=False):
+        """Multivariate t-distribution probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the probability density function.
+        %(_mvt_doc_default_callparams)s
+
+        Returns
+        -------
+        pdf : Probability density function evaluated at `x`.
+
+        Examples
+        --------
+        >>> from scipy.stats import multivariate_t
+        >>> x = [0.4, 5]
+        >>> loc = [0, 1]
+        >>> shape = [[1, 0.1], [0.1, 1]]
+        >>> df = 7
+        >>> multivariate_t.pdf(x, loc, shape, df)
+        0.00075713
+
+        """
+        dim, loc, shape, df = self._process_parameters(loc, shape, df)
+        x = self._process_quantiles(x, dim)
+        shape_info = _PSD(shape, allow_singular=allow_singular)
+        logpdf = self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df,
+                              dim, shape_info.rank)
+        return np.exp(logpdf)
+
+    def logpdf(self, x, loc=None, shape=1, df=1):
+        """Log of the multivariate t-distribution probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the log of the probability density
+            function.
+        %(_mvt_doc_default_callparams)s
+
+        Returns
+        -------
+        logpdf : Log of the probability density function evaluated at `x`.
+
+        Examples
+        --------
+        >>> from scipy.stats import multivariate_t
+        >>> x = [0.4, 5]
+        >>> loc = [0, 1]
+        >>> shape = [[1, 0.1], [0.1, 1]]
+        >>> df = 7
+        >>> multivariate_t.logpdf(x, loc, shape, df)
+        -7.1859802
+
+        See Also
+        --------
+        pdf : Probability density function.
+
+        """
+        dim, loc, shape, df = self._process_parameters(loc, shape, df)
+        x = self._process_quantiles(x, dim)
+        shape_info = _PSD(shape)
+        return self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df, dim,
+                            shape_info.rank)
+
+    def _logpdf(self, x, loc, prec_U, log_pdet, df, dim, rank):
+        """Utility method `pdf`, `logpdf` for parameters.
+
+        Parameters
+        ----------
+        x : ndarray
+            Points at which to evaluate the log of the probability density
+            function.
+        loc : ndarray
+            Location of the distribution.
+        prec_U : ndarray
+            A decomposition such that `np.dot(prec_U, prec_U.T)` is the inverse
+            of the shape matrix.
+        log_pdet : float
+            Logarithm of the determinant of the shape matrix.
+        df : float
+            Degrees of freedom of the distribution.
+        dim : int
+            Dimension of the quantiles x.
+        rank : int
+            Rank of the shape matrix.
+
+        Notes
+        -----
+        As this function does no argument checking, it should not be called
+        directly; use 'logpdf' instead.
+
+        """
+        if df == np.inf:
+            return multivariate_normal._logpdf(x, loc, prec_U, log_pdet, rank)
+
+        dev = x - loc
+        maha = np.square(np.dot(dev, prec_U)).sum(axis=-1)
+
+        t = 0.5 * (df + dim)
+        A = gammaln(t)
+        B = gammaln(0.5 * df)
+        C = dim/2. * np.log(df * np.pi)
+        D = 0.5 * log_pdet
+        E = -t * np.log(1 + (1./df) * maha)
+
+        return _squeeze_output(A - B - C - D + E)
+
+    def _cdf(self, x, loc, shape, df, dim, maxpts=None, lower_limit=None,
+             random_state=None):
+
+        # All of this -  random state validation, maxpts, apply_along_axis,
+        # etc. needs to go in this private method unless we want
+        # frozen distribution's `cdf` method to duplicate it or call `cdf`,
+        # which would require re-processing parameters
+        if random_state is not None:
+            rng = check_random_state(random_state)
+        else:
+            rng = self._random_state
+
+        if not maxpts:
+            maxpts = 1000 * dim
+
+        x = self._process_quantiles(x, dim)
+        lower_limit = (np.full(loc.shape, -np.inf)
+                       if lower_limit is None else lower_limit)
+
+        # remove the mean
+        x, lower_limit = x - loc, lower_limit - loc
+
+        b, a = np.broadcast_arrays(x, lower_limit)
+        i_swap = b < a
+        signs = (-1)**(i_swap.sum(axis=-1))  # odd # of swaps -> negative
+        a, b = a.copy(), b.copy()
+        a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
+        n = x.shape[-1]
+        limits = np.concatenate((a, b), axis=-1)
+
+        def func1d(limits):
+            a, b = limits[:n], limits[n:]
+            return _qmvt(maxpts, df, shape, a, b, rng)[0]
+
+        res = np.apply_along_axis(func1d, -1, limits) * signs
+        # Fixing the output shape for existing distributions is a separate
+        # issue. For now, let's keep this consistent with pdf.
+        return _squeeze_output(res)
+
+    def cdf(self, x, loc=None, shape=1, df=1, allow_singular=False, *,
+            maxpts=None, lower_limit=None, random_state=None):
+        """Multivariate t-distribution cumulative distribution function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the cumulative distribution function.
+        %(_mvt_doc_default_callparams)s
+        maxpts : int, optional
+            Maximum number of points to use for integration. The default is
+            1000 times the number of dimensions.
+        lower_limit : array_like, optional
+            Lower limit of integration of the cumulative distribution function.
+            Default is negative infinity. Must be broadcastable with `x`.
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        cdf : ndarray or scalar
+            Cumulative distribution function evaluated at `x`.
+
+        Examples
+        --------
+        >>> from scipy.stats import multivariate_t
+        >>> x = [0.4, 5]
+        >>> loc = [0, 1]
+        >>> shape = [[1, 0.1], [0.1, 1]]
+        >>> df = 7
+        >>> multivariate_t.cdf(x, loc, shape, df)
+        0.64798491
+
+        """
+        dim, loc, shape, df = self._process_parameters(loc, shape, df)
+        shape = _PSD(shape, allow_singular=allow_singular)._M
+
+        return self._cdf(x, loc, shape, df, dim, maxpts,
+                         lower_limit, random_state)
+
+    def _entropy(self, dim, df=1, shape=1):
+        if df == np.inf:
+            return multivariate_normal(None, cov=shape).entropy()
+
+        shape_info = _PSD(shape)
+        shape_term = 0.5 * shape_info.log_pdet
+
+        def regular(dim, df):
+            halfsum = 0.5 * (dim + df)
+            half_df = 0.5 * df
+            return (
+                -gammaln(halfsum) + gammaln(half_df)
+                + 0.5 * dim * np.log(df * np.pi) + halfsum
+                * (psi(halfsum) - psi(half_df))
+                + shape_term
+            )
+
+        def asymptotic(dim, df):
+            # Formula from Wolfram Alpha:
+            # "asymptotic expansion -gammaln((m+d)/2) + gammaln(d/2) + (m*log(d*pi))/2
+            #  + ((m+d)/2) * (digamma((m+d)/2) - digamma(d/2))"
+            return (
+                dim * norm._entropy() + dim / df
+                - dim * (dim - 2) * df**-2.0 / 4
+                + dim**2 * (dim - 2) * df**-3.0 / 6
+                + dim * (-3 * dim**3 + 8 * dim**2 - 8) * df**-4.0 / 24
+                + dim**2 * (3 * dim**3 - 10 * dim**2 + 16) * df**-5.0 / 30
+                + shape_term
+            )[()]
+
+        # preserves ~12 digits accuracy up to at least `dim=1e5`. See gh-18465.
+        threshold = dim * 100 * 4 / (np.log(dim) + 1)
+        return _lazywhere(df >= threshold, (dim, df), f=asymptotic, f2=regular)
+
+    def entropy(self, loc=None, shape=1, df=1):
+        """Calculate the differential entropy of a multivariate
+        t-distribution.
+
+        Parameters
+        ----------
+        %(_mvt_doc_default_callparams)s
+
+        Returns
+        -------
+        h : float
+            Differential entropy
+
+        """
+        dim, loc, shape, df = self._process_parameters(None, shape, df)
+        return self._entropy(dim, df, shape)
+
+    def rvs(self, loc=None, shape=1, df=1, size=1, random_state=None):
+        """Draw random samples from a multivariate t-distribution.
+
+        Parameters
+        ----------
+        %(_mvt_doc_default_callparams)s
+        size : integer, optional
+            Number of samples to draw (default 1).
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `P`), where `P` is the
+            dimension of the random variable.
+
+        Examples
+        --------
+        >>> from scipy.stats import multivariate_t
+        >>> x = [0.4, 5]
+        >>> loc = [0, 1]
+        >>> shape = [[1, 0.1], [0.1, 1]]
+        >>> df = 7
+        >>> multivariate_t.rvs(loc, shape, df)
+        array([[0.93477495, 3.00408716]])
+
+        """
+        # For implementation details, see equation (3):
+        #
+        #    Hofert, "On Sampling from the Multivariatet Distribution", 2013
+        #     http://rjournal.github.io/archive/2013-2/hofert.pdf
+        #
+        dim, loc, shape, df = self._process_parameters(loc, shape, df)
+        if random_state is not None:
+            rng = check_random_state(random_state)
+        else:
+            rng = self._random_state
+
+        if np.isinf(df):
+            x = np.ones(size)
+        else:
+            x = rng.chisquare(df, size=size) / df
+
+        z = rng.multivariate_normal(np.zeros(dim), shape, size=size)
+        samples = loc + z / np.sqrt(x)[..., None]
+        return _squeeze_output(samples)
+
+    def _process_quantiles(self, x, dim):
+        """
+        Adjust quantiles array so that last axis labels the components of
+        each data point.
+        """
+        x = np.asarray(x, dtype=float)
+        if x.ndim == 0:
+            x = x[np.newaxis]
+        elif x.ndim == 1:
+            if dim == 1:
+                x = x[:, np.newaxis]
+            else:
+                x = x[np.newaxis, :]
+        return x
+
+    def _process_parameters(self, loc, shape, df):
+        """
+        Infer dimensionality from location array and shape matrix, handle
+        defaults, and ensure compatible dimensions.
+        """
+        if loc is None and shape is None:
+            loc = np.asarray(0, dtype=float)
+            shape = np.asarray(1, dtype=float)
+            dim = 1
+        elif loc is None:
+            shape = np.asarray(shape, dtype=float)
+            if shape.ndim < 2:
+                dim = 1
+            else:
+                dim = shape.shape[0]
+            loc = np.zeros(dim)
+        elif shape is None:
+            loc = np.asarray(loc, dtype=float)
+            dim = loc.size
+            shape = np.eye(dim)
+        else:
+            shape = np.asarray(shape, dtype=float)
+            loc = np.asarray(loc, dtype=float)
+            dim = loc.size
+
+        if dim == 1:
+            loc = loc.reshape(1)
+            shape = shape.reshape(1, 1)
+
+        if loc.ndim != 1 or loc.shape[0] != dim:
+            raise ValueError("Array 'loc' must be a vector of length %d." %
+                             dim)
+        if shape.ndim == 0:
+            shape = shape * np.eye(dim)
+        elif shape.ndim == 1:
+            shape = np.diag(shape)
+        elif shape.ndim == 2 and shape.shape != (dim, dim):
+            rows, cols = shape.shape
+            if rows != cols:
+                msg = ("Array 'cov' must be square if it is two dimensional,"
+                       f" but cov.shape = {str(shape.shape)}.")
+            else:
+                msg = ("Dimension mismatch: array 'cov' is of shape %s,"
+                       " but 'loc' is a vector of length %d.")
+                msg = msg % (str(shape.shape), len(loc))
+            raise ValueError(msg)
+        elif shape.ndim > 2:
+            raise ValueError("Array 'cov' must be at most two-dimensional,"
+                             " but cov.ndim = %d" % shape.ndim)
+
+        # Process degrees of freedom.
+        if df is None:
+            df = 1
+        elif df <= 0:
+            raise ValueError("'df' must be greater than zero.")
+        elif np.isnan(df):
+            raise ValueError("'df' is 'nan' but must be greater than zero or 'np.inf'.")
+
+        return dim, loc, shape, df
+
+
+class multivariate_t_frozen(multi_rv_frozen):
+
+    def __init__(self, loc=None, shape=1, df=1, allow_singular=False,
+                 seed=None):
+        """Create a frozen multivariate t distribution.
+
+        Parameters
+        ----------
+        %(_mvt_doc_default_callparams)s
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> from scipy.stats import multivariate_t
+        >>> loc = np.zeros(3)
+        >>> shape = np.eye(3)
+        >>> df = 10
+        >>> dist = multivariate_t(loc, shape, df)
+        >>> dist.rvs()
+        array([[ 0.81412036, -1.53612361,  0.42199647]])
+        >>> dist.pdf([1, 1, 1])
+        array([0.01237803])
+
+        """
+        self._dist = multivariate_t_gen(seed)
+        dim, loc, shape, df = self._dist._process_parameters(loc, shape, df)
+        self.dim, self.loc, self.shape, self.df = dim, loc, shape, df
+        self.shape_info = _PSD(shape, allow_singular=allow_singular)
+
+    def logpdf(self, x):
+        x = self._dist._process_quantiles(x, self.dim)
+        U = self.shape_info.U
+        log_pdet = self.shape_info.log_pdet
+        return self._dist._logpdf(x, self.loc, U, log_pdet, self.df, self.dim,
+                                  self.shape_info.rank)
+
+    def cdf(self, x, *, maxpts=None, lower_limit=None, random_state=None):
+        x = self._dist._process_quantiles(x, self.dim)
+        return self._dist._cdf(x, self.loc, self.shape, self.df, self.dim,
+                               maxpts, lower_limit, random_state)
+
+    def pdf(self, x):
+        return np.exp(self.logpdf(x))
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(loc=self.loc,
+                              shape=self.shape,
+                              df=self.df,
+                              size=size,
+                              random_state=random_state)
+
+    def entropy(self):
+        return self._dist._entropy(self.dim, self.df, self.shape)
+
+
+multivariate_t = multivariate_t_gen()
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multivariate_t_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'rvs', 'cdf', 'entropy']:
+    method = multivariate_t_gen.__dict__[name]
+    method_frozen = multivariate_t_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(method.__doc__,
+                                             mvt_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, mvt_docdict_params)
+
+
+_mhg_doc_default_callparams = """\
+m : array_like
+    The number of each type of object in the population.
+    That is, :math:`m[i]` is the number of objects of
+    type :math:`i`.
+n : array_like
+    The number of samples taken from the population.
+"""
+
+_mhg_doc_callparams_note = """\
+`m` must be an array of positive integers. If the quantile
+:math:`i` contains values out of the range :math:`[0, m_i]`
+where :math:`m_i` is the number of objects of type :math:`i`
+in the population or if the parameters are inconsistent with one
+another (e.g. ``x.sum() != n``), methods return the appropriate
+value (e.g. ``0`` for ``pmf``). If `m` or `n` contain negative
+values, the result will contain ``nan`` there.
+"""
+
+_mhg_doc_frozen_callparams = ""
+
+_mhg_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+mhg_docdict_params = {
+    '_doc_default_callparams': _mhg_doc_default_callparams,
+    '_doc_callparams_note': _mhg_doc_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+mhg_docdict_noparams = {
+    '_doc_default_callparams': _mhg_doc_frozen_callparams,
+    '_doc_callparams_note': _mhg_doc_frozen_callparams_note,
+    '_doc_random_state': _doc_random_state
+}
+
+
+class multivariate_hypergeom_gen(multi_rv_generic):
+    r"""A multivariate hypergeometric random variable.
+
+    Methods
+    -------
+    pmf(x, m, n)
+        Probability mass function.
+    logpmf(x, m, n)
+        Log of the probability mass function.
+    rvs(m, n, size=1, random_state=None)
+        Draw random samples from a multivariate hypergeometric
+        distribution.
+    mean(m, n)
+        Mean of the multivariate hypergeometric distribution.
+    var(m, n)
+        Variance of the multivariate hypergeometric distribution.
+    cov(m, n)
+        Compute the covariance matrix of the multivariate
+        hypergeometric distribution.
+
+    Parameters
+    ----------
+    %(_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_doc_callparams_note)s
+
+    The probability mass function for `multivariate_hypergeom` is
+
+    .. math::
+
+        P(X_1 = x_1, X_2 = x_2, \ldots, X_k = x_k) = \frac{\binom{m_1}{x_1}
+        \binom{m_2}{x_2} \cdots \binom{m_k}{x_k}}{\binom{M}{n}}, \\ \quad
+        (x_1, x_2, \ldots, x_k) \in \mathbb{N}^k \text{ with }
+        \sum_{i=1}^k x_i = n
+
+    where :math:`m_i` are the number of objects of type :math:`i`, :math:`M`
+    is the total number of objects in the population (sum of all the
+    :math:`m_i`), and :math:`n` is the size of the sample to be taken
+    from the population.
+
+    .. versionadded:: 1.6.0
+
+    Examples
+    --------
+    To evaluate the probability mass function of the multivariate
+    hypergeometric distribution, with a dichotomous population of size
+    :math:`10` and :math:`20`, at a sample of size :math:`12` with
+    :math:`8` objects of the first type and :math:`4` objects of the
+    second type, use:
+
+    >>> from scipy.stats import multivariate_hypergeom
+    >>> multivariate_hypergeom.pmf(x=[8, 4], m=[10, 20], n=12)
+    0.0025207176631464523
+
+    The `multivariate_hypergeom` distribution is identical to the
+    corresponding `hypergeom` distribution (tiny numerical differences
+    notwithstanding) when only two types (good and bad) of objects
+    are present in the population as in the example above. Consider
+    another example for a comparison with the hypergeometric distribution:
+
+    >>> from scipy.stats import hypergeom
+    >>> multivariate_hypergeom.pmf(x=[3, 1], m=[10, 5], n=4)
+    0.4395604395604395
+    >>> hypergeom.pmf(k=3, M=15, n=4, N=10)
+    0.43956043956044005
+
+    The functions ``pmf``, ``logpmf``, ``mean``, ``var``, ``cov``, and ``rvs``
+    support broadcasting, under the convention that the vector parameters
+    (``x``, ``m``, and ``n``) are interpreted as if each row along the last
+    axis is a single object. For instance, we can combine the previous two
+    calls to `multivariate_hypergeom` as
+
+    >>> multivariate_hypergeom.pmf(x=[[8, 4], [3, 1]], m=[[10, 20], [10, 5]],
+    ...                            n=[12, 4])
+    array([0.00252072, 0.43956044])
+
+    This broadcasting also works for ``cov``, where the output objects are
+    square matrices of size ``m.shape[-1]``. For example:
+
+    >>> multivariate_hypergeom.cov(m=[[7, 9], [10, 15]], n=[8, 12])
+    array([[[ 1.05, -1.05],
+            [-1.05,  1.05]],
+           [[ 1.56, -1.56],
+            [-1.56,  1.56]]])
+
+    That is, ``result[0]`` is equal to
+    ``multivariate_hypergeom.cov(m=[7, 9], n=8)`` and ``result[1]`` is equal
+    to ``multivariate_hypergeom.cov(m=[10, 15], n=12)``.
+
+    Alternatively, the object may be called (as a function) to fix the `m`
+    and `n` parameters, returning a "frozen" multivariate hypergeometric
+    random variable.
+
+    >>> rv = multivariate_hypergeom(m=[10, 20], n=12)
+    >>> rv.pmf(x=[8, 4])
+    0.0025207176631464523
+
+    See Also
+    --------
+    scipy.stats.hypergeom : The hypergeometric distribution.
+    scipy.stats.multinomial : The multinomial distribution.
+
+    References
+    ----------
+    .. [1] The Multivariate Hypergeometric Distribution,
+           http://www.randomservices.org/random/urn/MultiHypergeometric.html
+    .. [2] Thomas J. Sargent and John Stachurski, 2020,
+           Multivariate Hypergeometric Distribution
+           https://python.quantecon.org/multi_hyper.html
+    """
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__, mhg_docdict_params)
+
+    def __call__(self, m, n, seed=None):
+        """Create a frozen multivariate_hypergeom distribution.
+
+        See `multivariate_hypergeom_frozen` for more information.
+        """
+        return multivariate_hypergeom_frozen(m, n, seed=seed)
+
+    def _process_parameters(self, m, n):
+        m = np.asarray(m)
+        n = np.asarray(n)
+        if m.size == 0:
+            m = m.astype(int)
+        if n.size == 0:
+            n = n.astype(int)
+        if not np.issubdtype(m.dtype, np.integer):
+            raise TypeError("'m' must an array of integers.")
+        if not np.issubdtype(n.dtype, np.integer):
+            raise TypeError("'n' must an array of integers.")
+        if m.ndim == 0:
+            raise ValueError("'m' must be an array with"
+                             " at least one dimension.")
+
+        # check for empty arrays
+        if m.size != 0:
+            n = n[..., np.newaxis]
+
+        m, n = np.broadcast_arrays(m, n)
+
+        # check for empty arrays
+        if m.size != 0:
+            n = n[..., 0]
+
+        mcond = m < 0
+
+        M = m.sum(axis=-1)
+
+        ncond = (n < 0) | (n > M)
+        return M, m, n, mcond, ncond, np.any(mcond, axis=-1) | ncond
+
+    def _process_quantiles(self, x, M, m, n):
+        x = np.asarray(x)
+        if not np.issubdtype(x.dtype, np.integer):
+            raise TypeError("'x' must an array of integers.")
+        if x.ndim == 0:
+            raise ValueError("'x' must be an array with"
+                             " at least one dimension.")
+        if not x.shape[-1] == m.shape[-1]:
+            raise ValueError(f"Size of each quantile must be size of 'm': "
+                             f"received {x.shape[-1]}, "
+                             f"but expected {m.shape[-1]}.")
+
+        # check for empty arrays
+        if m.size != 0:
+            n = n[..., np.newaxis]
+            M = M[..., np.newaxis]
+
+        x, m, n, M = np.broadcast_arrays(x, m, n, M)
+
+        # check for empty arrays
+        if m.size != 0:
+            n, M = n[..., 0], M[..., 0]
+
+        xcond = (x < 0) | (x > m)
+        return (x, M, m, n, xcond,
+                np.any(xcond, axis=-1) | (x.sum(axis=-1) != n))
+
+    def _checkresult(self, result, cond, bad_value):
+        result = np.asarray(result)
+        if cond.ndim != 0:
+            result[cond] = bad_value
+        elif cond:
+            return bad_value
+        if result.ndim == 0:
+            return result[()]
+        return result
+
+    def _logpmf(self, x, M, m, n, mxcond, ncond):
+        # This equation of the pmf comes from the relation,
+        # n combine r = beta(n+1, 1) / beta(r+1, n-r+1)
+        num = np.zeros_like(m, dtype=np.float64)
+        den = np.zeros_like(n, dtype=np.float64)
+        m, x = m[~mxcond], x[~mxcond]
+        M, n = M[~ncond], n[~ncond]
+        num[~mxcond] = (betaln(m+1, 1) - betaln(x+1, m-x+1))
+        den[~ncond] = (betaln(M+1, 1) - betaln(n+1, M-n+1))
+        num[mxcond] = np.nan
+        den[ncond] = np.nan
+        num = num.sum(axis=-1)
+        return num - den
+
+    def logpmf(self, x, m, n):
+        """Log of the multivariate hypergeometric probability mass function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        logpmf : ndarray or scalar
+            Log of the probability mass function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        M, m, n, mcond, ncond, mncond = self._process_parameters(m, n)
+        (x, M, m, n, xcond,
+         xcond_reduced) = self._process_quantiles(x, M, m, n)
+        mxcond = mcond | xcond
+        ncond = ncond | np.zeros(n.shape, dtype=np.bool_)
+
+        result = self._logpmf(x, M, m, n, mxcond, ncond)
+
+        # replace values for which x was out of the domain; broadcast
+        # xcond to the right shape
+        xcond_ = xcond_reduced | np.zeros(mncond.shape, dtype=np.bool_)
+        result = self._checkresult(result, xcond_, -np.inf)
+
+        # replace values bad for n or m; broadcast
+        # mncond to the right shape
+        mncond_ = mncond | np.zeros(xcond_reduced.shape, dtype=np.bool_)
+        return self._checkresult(result, mncond_, np.nan)
+
+    def pmf(self, x, m, n):
+        """Multivariate hypergeometric probability mass function.
+
+        Parameters
+        ----------
+        x : array_like
+            Quantiles, with the last axis of `x` denoting the components.
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        pmf : ndarray or scalar
+            Probability density function evaluated at `x`
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+        """
+        out = np.exp(self.logpmf(x, m, n))
+        return out
+
+    def mean(self, m, n):
+        """Mean of the multivariate hypergeometric distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        mean : array_like or scalar
+            The mean of the distribution
+        """
+        M, m, n, _, _, mncond = self._process_parameters(m, n)
+        # check for empty arrays
+        if m.size != 0:
+            M, n = M[..., np.newaxis], n[..., np.newaxis]
+        cond = (M == 0)
+        M = np.ma.masked_array(M, mask=cond)
+        mu = n*(m/M)
+        if m.size != 0:
+            mncond = (mncond[..., np.newaxis] |
+                      np.zeros(mu.shape, dtype=np.bool_))
+        return self._checkresult(mu, mncond, np.nan)
+
+    def var(self, m, n):
+        """Variance of the multivariate hypergeometric distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        array_like
+            The variances of the components of the distribution.  This is
+            the diagonal of the covariance matrix of the distribution
+        """
+        M, m, n, _, _, mncond = self._process_parameters(m, n)
+        # check for empty arrays
+        if m.size != 0:
+            M, n = M[..., np.newaxis], n[..., np.newaxis]
+        cond = (M == 0) & (M-1 == 0)
+        M = np.ma.masked_array(M, mask=cond)
+        output = n * m/M * (M-m)/M * (M-n)/(M-1)
+        if m.size != 0:
+            mncond = (mncond[..., np.newaxis] |
+                      np.zeros(output.shape, dtype=np.bool_))
+        return self._checkresult(output, mncond, np.nan)
+
+    def cov(self, m, n):
+        """Covariance matrix of the multivariate hypergeometric distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+
+        Returns
+        -------
+        cov : array_like
+            The covariance matrix of the distribution
+        """
+        # see [1]_ for the formula and [2]_ for implementation
+        # cov( x_i,x_j ) = -n * (M-n)/(M-1) * (K_i*K_j) / (M**2)
+        M, m, n, _, _, mncond = self._process_parameters(m, n)
+        # check for empty arrays
+        if m.size != 0:
+            M = M[..., np.newaxis, np.newaxis]
+            n = n[..., np.newaxis, np.newaxis]
+        cond = (M == 0) & (M-1 == 0)
+        M = np.ma.masked_array(M, mask=cond)
+        output = (-n * (M-n)/(M-1) *
+                  np.einsum("...i,...j->...ij", m, m) / (M**2))
+        # check for empty arrays
+        if m.size != 0:
+            M, n = M[..., 0, 0], n[..., 0, 0]
+            cond = cond[..., 0, 0]
+        dim = m.shape[-1]
+        # diagonal entries need to be computed differently
+        for i in range(dim):
+            output[..., i, i] = (n * (M-n) * m[..., i]*(M-m[..., i]))
+            output[..., i, i] = output[..., i, i] / (M-1)
+            output[..., i, i] = output[..., i, i] / (M**2)
+        if m.size != 0:
+            mncond = (mncond[..., np.newaxis, np.newaxis] |
+                      np.zeros(output.shape, dtype=np.bool_))
+        return self._checkresult(output, mncond, np.nan)
+
+    def rvs(self, m, n, size=None, random_state=None):
+        """Draw random samples from a multivariate hypergeometric distribution.
+
+        Parameters
+        ----------
+        %(_doc_default_callparams)s
+        size : integer or iterable of integers, optional
+            Number of samples to draw. Default is ``None``, in which case a
+            single variate is returned as an array with shape ``m.shape``.
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : array_like
+            Random variates of shape ``size`` or ``m.shape``
+            (if ``size=None``).
+
+        Notes
+        -----
+        %(_doc_callparams_note)s
+
+        Also note that NumPy's `multivariate_hypergeometric` sampler is not
+        used as it doesn't support broadcasting.
+        """
+        M, m, n, _, _, _ = self._process_parameters(m, n)
+
+        random_state = self._get_random_state(random_state)
+
+        if size is not None and isinstance(size, int):
+            size = (size, )
+
+        if size is None:
+            rvs = np.empty(m.shape, dtype=m.dtype)
+        else:
+            rvs = np.empty(size + (m.shape[-1], ), dtype=m.dtype)
+        rem = M
+
+        # This sampler has been taken from numpy gh-13794
+        # https://github.com/numpy/numpy/pull/13794
+        for c in range(m.shape[-1] - 1):
+            rem = rem - m[..., c]
+            n0mask = n == 0
+            rvs[..., c] = (~n0mask *
+                           random_state.hypergeometric(m[..., c],
+                                                       rem + n0mask,
+                                                       n + n0mask,
+                                                       size=size))
+            n = n - rvs[..., c]
+        rvs[..., m.shape[-1] - 1] = n
+
+        return rvs
+
+
+multivariate_hypergeom = multivariate_hypergeom_gen()
+
+
+class multivariate_hypergeom_frozen(multi_rv_frozen):
+    def __init__(self, m, n, seed=None):
+        self._dist = multivariate_hypergeom_gen(seed)
+        (self.M, self.m, self.n,
+         self.mcond, self.ncond,
+         self.mncond) = self._dist._process_parameters(m, n)
+
+        # monkey patch self._dist
+        def _process_parameters(m, n):
+            return (self.M, self.m, self.n,
+                    self.mcond, self.ncond,
+                    self.mncond)
+        self._dist._process_parameters = _process_parameters
+
+    def logpmf(self, x):
+        return self._dist.logpmf(x, self.m, self.n)
+
+    def pmf(self, x):
+        return self._dist.pmf(x, self.m, self.n)
+
+    def mean(self):
+        return self._dist.mean(self.m, self.n)
+
+    def var(self):
+        return self._dist.var(self.m, self.n)
+
+    def cov(self):
+        return self._dist.cov(self.m, self.n)
+
+    def rvs(self, size=1, random_state=None):
+        return self._dist.rvs(self.m, self.n,
+                              size=size,
+                              random_state=random_state)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# multivariate_hypergeom and fill in default strings in class docstrings
+for name in ['logpmf', 'pmf', 'mean', 'var', 'cov', 'rvs']:
+    method = multivariate_hypergeom_gen.__dict__[name]
+    method_frozen = multivariate_hypergeom_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, mhg_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__,
+                                      mhg_docdict_params)
+
+
+class random_table_gen(multi_rv_generic):
+    r"""Contingency tables from independent samples with fixed marginal sums.
+
+    This is the distribution of random tables with given row and column vector
+    sums. This distribution represents the set of random tables under the null
+    hypothesis that rows and columns are independent. It is used in hypothesis
+    tests of independence.
+
+    Because of assumed independence, the expected frequency of each table
+    element can be computed from the row and column sums, so that the
+    distribution is completely determined by these two vectors.
+
+    Methods
+    -------
+    logpmf(x)
+        Log-probability of table `x` to occur in the distribution.
+    pmf(x)
+        Probability of table `x` to occur in the distribution.
+    mean(row, col)
+        Mean table.
+    rvs(row, col, size=None, method=None, random_state=None)
+        Draw random tables with given row and column vector sums.
+
+    Parameters
+    ----------
+    %(_doc_row_col)s
+    %(_doc_random_state)s
+
+    Notes
+    -----
+    %(_doc_row_col_note)s
+
+    Random elements from the distribution are generated either with Boyett's
+    [1]_ or Patefield's algorithm [2]_. Boyett's algorithm has
+    O(N) time and space complexity, where N is the total sum of entries in the
+    table. Patefield's algorithm has O(K x log(N)) time complexity, where K is
+    the number of cells in the table and requires only a small constant work
+    space. By default, the `rvs` method selects the fastest algorithm based on
+    the input, but you can specify the algorithm with the keyword `method`.
+    Allowed values are "boyett" and "patefield".
+
+    .. versionadded:: 1.10.0
+
+    Examples
+    --------
+    >>> from scipy.stats import random_table
+
+    >>> row = [1, 5]
+    >>> col = [2, 3, 1]
+    >>> random_table.mean(row, col)
+    array([[0.33333333, 0.5       , 0.16666667],
+           [1.66666667, 2.5       , 0.83333333]])
+
+    Alternatively, the object may be called (as a function) to fix the row
+    and column vector sums, returning a "frozen" distribution.
+
+    >>> dist = random_table(row, col)
+    >>> dist.rvs(random_state=123)
+    array([[1, 0, 0],
+           [1, 3, 1]])
+
+    References
+    ----------
+    .. [1] J. Boyett, AS 144 Appl. Statist. 28 (1979) 329-332
+    .. [2] W.M. Patefield, AS 159 Appl. Statist. 30 (1981) 91-97
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+
+    def __call__(self, row, col, *, seed=None):
+        """Create a frozen distribution of tables with given marginals.
+
+        See `random_table_frozen` for more information.
+        """
+        return random_table_frozen(row, col, seed=seed)
+
+    def logpmf(self, x, row, col):
+        """Log-probability of table to occur in the distribution.
+
+        Parameters
+        ----------
+        %(_doc_x)s
+        %(_doc_row_col)s
+
+        Returns
+        -------
+        logpmf : ndarray or scalar
+            Log of the probability mass function evaluated at `x`.
+
+        Notes
+        -----
+        %(_doc_row_col_note)s
+
+        If row and column marginals of `x` do not match `row` and `col`,
+        negative infinity is returned.
+
+        Examples
+        --------
+        >>> from scipy.stats import random_table
+        >>> import numpy as np
+
+        >>> x = [[1, 5, 1], [2, 3, 1]]
+        >>> row = np.sum(x, axis=1)
+        >>> col = np.sum(x, axis=0)
+        >>> random_table.logpmf(x, row, col)
+        -1.6306401200847027
+
+        Alternatively, the object may be called (as a function) to fix the row
+        and column vector sums, returning a "frozen" distribution.
+
+        >>> d = random_table(row, col)
+        >>> d.logpmf(x)
+        -1.6306401200847027
+        """
+        r, c, n = self._process_parameters(row, col)
+        x = np.asarray(x)
+
+        if x.ndim < 2:
+            raise ValueError("`x` must be at least two-dimensional")
+
+        dtype_is_int = np.issubdtype(x.dtype, np.integer)
+        with np.errstate(invalid='ignore'):
+            if not dtype_is_int and not np.all(x.astype(int) == x):
+                raise ValueError("`x` must contain only integral values")
+
+        # x does not contain NaN if we arrive here
+        if np.any(x < 0):
+            raise ValueError("`x` must contain only non-negative values")
+
+        r2 = np.sum(x, axis=-1)
+        c2 = np.sum(x, axis=-2)
+
+        if r2.shape[-1] != len(r):
+            raise ValueError("shape of `x` must agree with `row`")
+
+        if c2.shape[-1] != len(c):
+            raise ValueError("shape of `x` must agree with `col`")
+
+        res = np.empty(x.shape[:-2])
+
+        mask = np.all(r2 == r, axis=-1) & np.all(c2 == c, axis=-1)
+
+        def lnfac(x):
+            return gammaln(x + 1)
+
+        res[mask] = (np.sum(lnfac(r), axis=-1) + np.sum(lnfac(c), axis=-1)
+                     - lnfac(n) - np.sum(lnfac(x[mask]), axis=(-1, -2)))
+        res[~mask] = -np.inf
+
+        return res[()]
+
+    def pmf(self, x, row, col):
+        """Probability of table to occur in the distribution.
+
+        Parameters
+        ----------
+        %(_doc_x)s
+        %(_doc_row_col)s
+
+        Returns
+        -------
+        pmf : ndarray or scalar
+            Probability mass function evaluated at `x`.
+
+        Notes
+        -----
+        %(_doc_row_col_note)s
+
+        If row and column marginals of `x` do not match `row` and `col`,
+        zero is returned.
+
+        Examples
+        --------
+        >>> from scipy.stats import random_table
+        >>> import numpy as np
+
+        >>> x = [[1, 5, 1], [2, 3, 1]]
+        >>> row = np.sum(x, axis=1)
+        >>> col = np.sum(x, axis=0)
+        >>> random_table.pmf(x, row, col)
+        0.19580419580419592
+
+        Alternatively, the object may be called (as a function) to fix the row
+        and column vector sums, returning a "frozen" distribution.
+
+        >>> d = random_table(row, col)
+        >>> d.pmf(x)
+        0.19580419580419592
+        """
+        return np.exp(self.logpmf(x, row, col))
+
+    def mean(self, row, col):
+        """Mean of distribution of conditional tables.
+        %(_doc_mean_params)s
+
+        Returns
+        -------
+        mean: ndarray
+            Mean of the distribution.
+
+        Notes
+        -----
+        %(_doc_row_col_note)s
+
+        Examples
+        --------
+        >>> from scipy.stats import random_table
+
+        >>> row = [1, 5]
+        >>> col = [2, 3, 1]
+        >>> random_table.mean(row, col)
+        array([[0.33333333, 0.5       , 0.16666667],
+               [1.66666667, 2.5       , 0.83333333]])
+
+        Alternatively, the object may be called (as a function) to fix the row
+        and column vector sums, returning a "frozen" distribution.
+
+        >>> d = random_table(row, col)
+        >>> d.mean()
+        array([[0.33333333, 0.5       , 0.16666667],
+               [1.66666667, 2.5       , 0.83333333]])
+        """
+        r, c, n = self._process_parameters(row, col)
+        return np.outer(r, c) / n
+
+    def rvs(self, row, col, *, size=None, method=None, random_state=None):
+        """Draw random tables with fixed column and row marginals.
+
+        Parameters
+        ----------
+        %(_doc_row_col)s
+        size : integer, optional
+            Number of samples to draw (default 1).
+        method : str, optional
+            Which method to use, "boyett" or "patefield". If None (default),
+            selects the fastest method for this input.
+        %(_doc_random_state)s
+
+        Returns
+        -------
+        rvs : ndarray
+            Random 2D tables of shape (`size`, `len(row)`, `len(col)`).
+
+        Notes
+        -----
+        %(_doc_row_col_note)s
+
+        Examples
+        --------
+        >>> from scipy.stats import random_table
+
+        >>> row = [1, 5]
+        >>> col = [2, 3, 1]
+        >>> random_table.rvs(row, col, random_state=123)
+        array([[1., 0., 0.],
+               [1., 3., 1.]])
+
+        Alternatively, the object may be called (as a function) to fix the row
+        and column vector sums, returning a "frozen" distribution.
+
+        >>> d = random_table(row, col)
+        >>> d.rvs(random_state=123)
+        array([[1., 0., 0.],
+               [1., 3., 1.]])
+        """
+        r, c, n = self._process_parameters(row, col)
+        size, shape = self._process_size_shape(size, r, c)
+
+        random_state = self._get_random_state(random_state)
+        meth = self._process_rvs_method(method, r, c, n)
+
+        return meth(r, c, n, size, random_state).reshape(shape)
+
+    @staticmethod
+    def _process_parameters(row, col):
+        """
+        Check that row and column vectors are one-dimensional, that they do
+        not contain negative or non-integer entries, and that the sums over
+        both vectors are equal.
+        """
+        r = np.array(row, dtype=np.int64, copy=True)
+        c = np.array(col, dtype=np.int64, copy=True)
+
+        if np.ndim(r) != 1:
+            raise ValueError("`row` must be one-dimensional")
+        if np.ndim(c) != 1:
+            raise ValueError("`col` must be one-dimensional")
+
+        if np.any(r < 0):
+            raise ValueError("each element of `row` must be non-negative")
+        if np.any(c < 0):
+            raise ValueError("each element of `col` must be non-negative")
+
+        n = np.sum(r)
+        if n != np.sum(c):
+            raise ValueError("sums over `row` and `col` must be equal")
+
+        if not np.all(r == np.asarray(row)):
+            raise ValueError("each element of `row` must be an integer")
+        if not np.all(c == np.asarray(col)):
+            raise ValueError("each element of `col` must be an integer")
+
+        return r, c, n
+
+    @staticmethod
+    def _process_size_shape(size, r, c):
+        """
+        Compute the number of samples to be drawn and the shape of the output
+        """
+        shape = (len(r), len(c))
+
+        if size is None:
+            return 1, shape
+
+        size = np.atleast_1d(size)
+        if not np.issubdtype(size.dtype, np.integer) or np.any(size < 0):
+            raise ValueError("`size` must be a non-negative integer or `None`")
+
+        return np.prod(size), tuple(size) + shape
+
+    @classmethod
+    def _process_rvs_method(cls, method, r, c, n):
+        known_methods = {
+            None: cls._rvs_select(r, c, n),
+            "boyett": cls._rvs_boyett,
+            "patefield": cls._rvs_patefield,
+        }
+        try:
+            return known_methods[method]
+        except KeyError:
+            raise ValueError(f"'{method}' not recognized, "
+                             f"must be one of {set(known_methods)}")
+
+    @classmethod
+    def _rvs_select(cls, r, c, n):
+        fac = 1.0  # benchmarks show that this value is about 1
+        k = len(r) * len(c)  # number of cells
+        # n + 1 guards against failure if n == 0
+        if n > fac * np.log(n + 1) * k:
+            return cls._rvs_patefield
+        return cls._rvs_boyett
+
+    @staticmethod
+    def _rvs_boyett(row, col, ntot, size, random_state):
+        return _rcont.rvs_rcont1(row, col, ntot, size, random_state)
+
+    @staticmethod
+    def _rvs_patefield(row, col, ntot, size, random_state):
+        return _rcont.rvs_rcont2(row, col, ntot, size, random_state)
+
+
+random_table = random_table_gen()
+
+
+class random_table_frozen(multi_rv_frozen):
+    def __init__(self, row, col, *, seed=None):
+        self._dist = random_table_gen(seed)
+        self._params = self._dist._process_parameters(row, col)
+
+        # monkey patch self._dist
+        def _process_parameters(r, c):
+            return self._params
+        self._dist._process_parameters = _process_parameters
+
+    def logpmf(self, x):
+        return self._dist.logpmf(x, None, None)
+
+    def pmf(self, x):
+        return self._dist.pmf(x, None, None)
+
+    def mean(self):
+        return self._dist.mean(None, None)
+
+    def rvs(self, size=None, method=None, random_state=None):
+        # optimisations are possible here
+        return self._dist.rvs(None, None, size=size, method=method,
+                              random_state=random_state)
+
+
+_ctab_doc_row_col = """\
+row : array_like
+    Sum of table entries in each row.
+col : array_like
+    Sum of table entries in each column."""
+
+_ctab_doc_x = """\
+x : array-like
+   Two-dimensional table of non-negative integers, or a
+   multi-dimensional array with the last two dimensions
+   corresponding with the tables."""
+
+_ctab_doc_row_col_note = """\
+The row and column vectors must be one-dimensional, not empty,
+and each sum up to the same value. They cannot contain negative
+or noninteger entries."""
+
+_ctab_doc_mean_params = f"""
+Parameters
+----------
+{_ctab_doc_row_col}"""
+
+_ctab_doc_row_col_note_frozen = """\
+See class definition for a detailed description of parameters."""
+
+_ctab_docdict = {
+    "_doc_random_state": _doc_random_state,
+    "_doc_row_col": _ctab_doc_row_col,
+    "_doc_x": _ctab_doc_x,
+    "_doc_mean_params": _ctab_doc_mean_params,
+    "_doc_row_col_note": _ctab_doc_row_col_note,
+}
+
+_ctab_docdict_frozen = _ctab_docdict.copy()
+_ctab_docdict_frozen.update({
+    "_doc_row_col": "",
+    "_doc_mean_params": "",
+    "_doc_row_col_note": _ctab_doc_row_col_note_frozen,
+})
+
+
+def _docfill(obj, docdict, template=None):
+    obj.__doc__ = doccer.docformat(template or obj.__doc__, docdict)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# random_table and fill in default strings in class docstrings
+_docfill(random_table_gen, _ctab_docdict)
+for name in ['logpmf', 'pmf', 'mean', 'rvs']:
+    method = random_table_gen.__dict__[name]
+    method_frozen = random_table_frozen.__dict__[name]
+    _docfill(method_frozen, _ctab_docdict_frozen, method.__doc__)
+    _docfill(method, _ctab_docdict)
+
+
+class uniform_direction_gen(multi_rv_generic):
+    r"""A vector-valued uniform direction.
+
+    Return a random direction (unit vector). The `dim` keyword specifies
+    the dimensionality of the space.
+
+    Methods
+    -------
+    rvs(dim=None, size=1, random_state=None)
+        Draw random directions.
+
+    Parameters
+    ----------
+    dim : scalar
+        Dimension of directions.
+    seed : {None, int, `numpy.random.Generator`,
+            `numpy.random.RandomState`}, optional
+
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    Notes
+    -----
+    This distribution generates unit vectors uniformly distributed on
+    the surface of a hypersphere. These can be interpreted as random
+    directions.
+    For example, if `dim` is 3, 3D vectors from the surface of :math:`S^2`
+    will be sampled.
+
+    References
+    ----------
+    .. [1] Marsaglia, G. (1972). "Choosing a Point from the Surface of a
+           Sphere". Annals of Mathematical Statistics. 43 (2): 645-646.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import uniform_direction
+    >>> x = uniform_direction.rvs(3)
+    >>> np.linalg.norm(x)
+    1.
+
+    This generates one random direction, a vector on the surface of
+    :math:`S^2`.
+
+    Alternatively, the object may be called (as a function) to return a frozen
+    distribution with fixed `dim` parameter. Here,
+    we create a `uniform_direction` with ``dim=3`` and draw 5 observations.
+    The samples are then arranged in an array of shape 5x3.
+
+    >>> rng = np.random.default_rng()
+    >>> uniform_sphere_dist = uniform_direction(3)
+    >>> unit_vectors = uniform_sphere_dist.rvs(5, random_state=rng)
+    >>> unit_vectors
+    array([[ 0.56688642, -0.1332634 , -0.81294566],
+           [-0.427126  , -0.74779278,  0.50830044],
+           [ 0.3793989 ,  0.92346629,  0.05715323],
+           [ 0.36428383, -0.92449076, -0.11231259],
+           [-0.27733285,  0.94410968, -0.17816678]])
+    """
+
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__)
+
+    def __call__(self, dim=None, seed=None):
+        """Create a frozen n-dimensional uniform direction distribution.
+
+        See `uniform_direction` for more information.
+        """
+        return uniform_direction_frozen(dim, seed=seed)
+
+    def _process_parameters(self, dim):
+        """Dimension N must be specified; it cannot be inferred."""
+        if dim is None or not np.isscalar(dim) or dim < 1 or dim != int(dim):
+            raise ValueError("Dimension of vector must be specified, "
+                             "and must be an integer greater than 0.")
+
+        return int(dim)
+
+    def rvs(self, dim, size=None, random_state=None):
+        """Draw random samples from S(N-1).
+
+        Parameters
+        ----------
+        dim : integer
+            Dimension of space (N).
+        size : int or tuple of ints, optional
+            Given a shape of, for example, (m,n,k), m*n*k samples are
+            generated, and packed in an m-by-n-by-k arrangement.
+            Because each sample is N-dimensional, the output shape
+            is (m,n,k,N). If no shape is specified, a single (N-D)
+            sample is returned.
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            Pseudorandom number generator state used to generate resamples.
+
+            If `random_state` is ``None`` (or `np.random`), the
+            `numpy.random.RandomState` singleton is used.
+            If `random_state` is an int, a new ``RandomState`` instance is
+            used, seeded with `random_state`.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance then that instance is used.
+
+        Returns
+        -------
+        rvs : ndarray
+            Random direction vectors
+
+        """
+        random_state = self._get_random_state(random_state)
+        if size is None:
+            size = np.array([], dtype=int)
+        size = np.atleast_1d(size)
+
+        dim = self._process_parameters(dim)
+
+        samples = _sample_uniform_direction(dim, size, random_state)
+        return samples
+
+
+uniform_direction = uniform_direction_gen()
+
+
+class uniform_direction_frozen(multi_rv_frozen):
+    def __init__(self, dim=None, seed=None):
+        """Create a frozen n-dimensional uniform direction distribution.
+
+        Parameters
+        ----------
+        dim : int
+            Dimension of matrices
+        seed : {None, int, `numpy.random.Generator`,
+                `numpy.random.RandomState`}, optional
+
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+
+        Examples
+        --------
+        >>> from scipy.stats import uniform_direction
+        >>> x = uniform_direction(3)
+        >>> x.rvs()
+
+        """
+        self._dist = uniform_direction_gen(seed)
+        self.dim = self._dist._process_parameters(dim)
+
+    def rvs(self, size=None, random_state=None):
+        return self._dist.rvs(self.dim, size, random_state)
+
+
+def _sample_uniform_direction(dim, size, random_state):
+    """
+    Private method to generate uniform directions
+    Reference: Marsaglia, G. (1972). "Choosing a Point from the Surface of a
+               Sphere". Annals of Mathematical Statistics. 43 (2): 645-646.
+    """
+    samples_shape = np.append(size, dim)
+    samples = random_state.standard_normal(samples_shape)
+    samples /= np.linalg.norm(samples, axis=-1, keepdims=True)
+    return samples
+
+
+_dirichlet_mn_doc_default_callparams = """\
+alpha : array_like
+    The concentration parameters. The number of entries along the last axis
+    determines the dimensionality of the distribution. Each entry must be
+    strictly positive.
+n : int or array_like
+    The number of trials. Each element must be a strictly positive integer.
+"""
+
+_dirichlet_mn_doc_frozen_callparams = ""
+
+_dirichlet_mn_doc_frozen_callparams_note = """\
+See class definition for a detailed description of parameters."""
+
+dirichlet_mn_docdict_params = {
+    '_dirichlet_mn_doc_default_callparams': _dirichlet_mn_doc_default_callparams,
+    '_doc_random_state': _doc_random_state
+}
+
+dirichlet_mn_docdict_noparams = {
+    '_dirichlet_mn_doc_default_callparams': _dirichlet_mn_doc_frozen_callparams,
+    '_doc_random_state': _doc_random_state
+}
+
+
+def _dirichlet_multinomial_check_parameters(alpha, n, x=None):
+
+    alpha = np.asarray(alpha)
+    n = np.asarray(n)
+
+    if x is not None:
+        # Ensure that `x` and `alpha` are arrays. If the shapes are
+        # incompatible, NumPy will raise an appropriate error.
+        try:
+            x, alpha = np.broadcast_arrays(x, alpha)
+        except ValueError as e:
+            msg = "`x` and `alpha` must be broadcastable."
+            raise ValueError(msg) from e
+
+        x_int = np.floor(x)
+        if np.any(x < 0) or np.any(x != x_int):
+            raise ValueError("`x` must contain only non-negative integers.")
+        x = x_int
+
+    if np.any(alpha <= 0):
+        raise ValueError("`alpha` must contain only positive values.")
+
+    n_int = np.floor(n)
+    if np.any(n <= 0) or np.any(n != n_int):
+        raise ValueError("`n` must be a positive integer.")
+    n = n_int
+
+    sum_alpha = np.sum(alpha, axis=-1)
+    sum_alpha, n = np.broadcast_arrays(sum_alpha, n)
+
+    return (alpha, sum_alpha, n) if x is None else (alpha, sum_alpha, n, x)
+
+
+class dirichlet_multinomial_gen(multi_rv_generic):
+    r"""A Dirichlet multinomial random variable.
+
+    The Dirichlet multinomial distribution is a compound probability
+    distribution: it is the multinomial distribution with number of trials
+    `n` and class probabilities ``p`` randomly sampled from a Dirichlet
+    distribution with concentration parameters ``alpha``.
+
+    Methods
+    -------
+    logpmf(x, alpha, n):
+        Log of the probability mass function.
+    pmf(x, alpha, n):
+        Probability mass function.
+    mean(alpha, n):
+        Mean of the Dirichlet multinomial distribution.
+    var(alpha, n):
+        Variance of the Dirichlet multinomial distribution.
+    cov(alpha, n):
+        The covariance of the Dirichlet multinomial distribution.
+
+    Parameters
+    ----------
+    %(_dirichlet_mn_doc_default_callparams)s
+    %(_doc_random_state)s
+
+    See Also
+    --------
+    scipy.stats.dirichlet : The dirichlet distribution.
+    scipy.stats.multinomial : The multinomial distribution.
+
+    References
+    ----------
+    .. [1] Dirichlet-multinomial distribution, Wikipedia,
+           https://www.wikipedia.org/wiki/Dirichlet-multinomial_distribution
+
+    Examples
+    --------
+    >>> from scipy.stats import dirichlet_multinomial
+
+    Get the PMF
+
+    >>> n = 6  # number of trials
+    >>> alpha = [3, 4, 5]  # concentration parameters
+    >>> x = [1, 2, 3]  # counts
+    >>> dirichlet_multinomial.pmf(x, alpha, n)
+    0.08484162895927604
+
+    If the sum of category counts does not equal the number of trials,
+    the probability mass is zero.
+
+    >>> dirichlet_multinomial.pmf(x, alpha, n=7)
+    0.0
+
+    Get the log of the PMF
+
+    >>> dirichlet_multinomial.logpmf(x, alpha, n)
+    -2.4669689491013327
+
+    Get the mean
+
+    >>> dirichlet_multinomial.mean(alpha, n)
+    array([1.5, 2. , 2.5])
+
+    Get the variance
+
+    >>> dirichlet_multinomial.var(alpha, n)
+    array([1.55769231, 1.84615385, 2.01923077])
+
+    Get the covariance
+
+    >>> dirichlet_multinomial.cov(alpha, n)
+    array([[ 1.55769231, -0.69230769, -0.86538462],
+           [-0.69230769,  1.84615385, -1.15384615],
+           [-0.86538462, -1.15384615,  2.01923077]])
+
+    Alternatively, the object may be called (as a function) to fix the
+    `alpha` and `n` parameters, returning a "frozen" Dirichlet multinomial
+    random variable.
+
+    >>> dm = dirichlet_multinomial(alpha, n)
+    >>> dm.pmf(x)
+    0.08484162895927579
+
+    All methods are fully vectorized. Each element of `x` and `alpha` is
+    a vector (along the last axis), each element of `n` is an
+    integer (scalar), and the result is computed element-wise.
+
+    >>> x = [[1, 2, 3], [4, 5, 6]]
+    >>> alpha = [[1, 2, 3], [4, 5, 6]]
+    >>> n = [6, 15]
+    >>> dirichlet_multinomial.pmf(x, alpha, n)
+    array([0.06493506, 0.02626937])
+
+    >>> dirichlet_multinomial.cov(alpha, n).shape  # both covariance matrices
+    (2, 3, 3)
+
+    Broadcasting according to standard NumPy conventions is supported. Here,
+    we have four sets of concentration parameters (each a two element vector)
+    for each of three numbers of trials (each a scalar).
+
+    >>> alpha = [[3, 4], [4, 5], [5, 6], [6, 7]]
+    >>> n = [[6], [7], [8]]
+    >>> dirichlet_multinomial.mean(alpha, n).shape
+    (3, 4, 2)
+
+    """
+    def __init__(self, seed=None):
+        super().__init__(seed)
+        self.__doc__ = doccer.docformat(self.__doc__,
+                                        dirichlet_mn_docdict_params)
+
+    def __call__(self, alpha, n, seed=None):
+        return dirichlet_multinomial_frozen(alpha, n, seed=seed)
+
+    def logpmf(self, x, alpha, n):
+        """The log of the probability mass function.
+
+        Parameters
+        ----------
+        x: ndarray
+            Category counts (non-negative integers). Must be broadcastable
+            with shape parameter ``alpha``. If multidimensional, the last axis
+            must correspond with the categories.
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out: ndarray or scalar
+            Log of the probability mass function.
+
+        """
+
+        a, Sa, n, x = _dirichlet_multinomial_check_parameters(alpha, n, x)
+
+        out = np.asarray(loggamma(Sa) + loggamma(n + 1) - loggamma(n + Sa))
+        out += (loggamma(x + a) - (loggamma(a) + loggamma(x + 1))).sum(axis=-1)
+        np.place(out, n != x.sum(axis=-1), -np.inf)
+        return out[()]
+
+    def pmf(self, x, alpha, n):
+        """Probability mass function for a Dirichlet multinomial distribution.
+
+        Parameters
+        ----------
+        x: ndarray
+            Category counts (non-negative integers). Must be broadcastable
+            with shape parameter ``alpha``. If multidimensional, the last axis
+            must correspond with the categories.
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out: ndarray or scalar
+            Probability mass function.
+
+        """
+        return np.exp(self.logpmf(x, alpha, n))
+
+    def mean(self, alpha, n):
+        """Mean of a Dirichlet multinomial distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out: ndarray
+            Mean of a Dirichlet multinomial distribution.
+
+        """
+        a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n)
+        n, Sa = n[..., np.newaxis], Sa[..., np.newaxis]
+        return n * a / Sa
+
+    def var(self, alpha, n):
+        """The variance of the Dirichlet multinomial distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out: array_like
+            The variances of the components of the distribution. This is
+            the diagonal of the covariance matrix of the distribution.
+
+        """
+        a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n)
+        n, Sa = n[..., np.newaxis], Sa[..., np.newaxis]
+        return n * a / Sa * (1 - a/Sa) * (n + Sa) / (1 + Sa)
+
+    def cov(self, alpha, n):
+        """Covariance matrix of a Dirichlet multinomial distribution.
+
+        Parameters
+        ----------
+        %(_dirichlet_mn_doc_default_callparams)s
+
+        Returns
+        -------
+        out : array_like
+            The covariance matrix of the distribution.
+
+        """
+        a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n)
+        var = dirichlet_multinomial.var(a, n)
+
+        n, Sa = n[..., np.newaxis, np.newaxis], Sa[..., np.newaxis, np.newaxis]
+        aiaj = a[..., :, np.newaxis] * a[..., np.newaxis, :]
+        cov = -n * aiaj / Sa ** 2 * (n + Sa) / (1 + Sa)
+
+        ii = np.arange(cov.shape[-1])
+        cov[..., ii, ii] = var
+        return cov
+
+
+dirichlet_multinomial = dirichlet_multinomial_gen()
+
+
+class dirichlet_multinomial_frozen(multi_rv_frozen):
+    def __init__(self, alpha, n, seed=None):
+        alpha, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n)
+        self.alpha = alpha
+        self.n = n
+        self._dist = dirichlet_multinomial_gen(seed)
+
+    def logpmf(self, x):
+        return self._dist.logpmf(x, self.alpha, self.n)
+
+    def pmf(self, x):
+        return self._dist.pmf(x, self.alpha, self.n)
+
+    def mean(self):
+        return self._dist.mean(self.alpha, self.n)
+
+    def var(self):
+        return self._dist.var(self.alpha, self.n)
+
+    def cov(self):
+        return self._dist.cov(self.alpha, self.n)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# dirichlet_multinomial and fill in default strings in class docstrings.
+for name in ['logpmf', 'pmf', 'mean', 'var', 'cov']:
+    method = dirichlet_multinomial_gen.__dict__[name]
+    method_frozen = dirichlet_multinomial_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(
+        method.__doc__, dirichlet_mn_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__,
+                                      dirichlet_mn_docdict_params)
+
+
+class vonmises_fisher_gen(multi_rv_generic):
+    r"""A von Mises-Fisher variable.
+
+    The `mu` keyword specifies the mean direction vector. The `kappa` keyword
+    specifies the concentration parameter.
+
+    Methods
+    -------
+    pdf(x, mu=None, kappa=1)
+        Probability density function.
+    logpdf(x, mu=None, kappa=1)
+        Log of the probability density function.
+    rvs(mu=None, kappa=1, size=1, random_state=None)
+        Draw random samples from a von Mises-Fisher distribution.
+    entropy(mu=None, kappa=1)
+        Compute the differential entropy of the von Mises-Fisher distribution.
+    fit(data)
+        Fit a von Mises-Fisher distribution to data.
+
+    Parameters
+    ----------
+    mu : array_like
+        Mean direction of the distribution. Must be a one-dimensional unit
+        vector of norm 1.
+    kappa : float
+        Concentration parameter. Must be positive.
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    See Also
+    --------
+    scipy.stats.vonmises : Von-Mises Fisher distribution in 2D on a circle
+    uniform_direction : uniform distribution on the surface of a hypersphere
+
+    Notes
+    -----
+    The von Mises-Fisher distribution is a directional distribution on the
+    surface of the unit hypersphere. The probability density
+    function of a unit vector :math:`\mathbf{x}` is
+
+    .. math::
+
+        f(\mathbf{x}) = \frac{\kappa^{d/2-1}}{(2\pi)^{d/2}I_{d/2-1}(\kappa)}
+               \exp\left(\kappa \mathbf{\mu}^T\mathbf{x}\right),
+
+    where :math:`\mathbf{\mu}` is the mean direction, :math:`\kappa` the
+    concentration parameter, :math:`d` the dimension and :math:`I` the
+    modified Bessel function of the first kind. As :math:`\mu` represents
+    a direction, it must be a unit vector or in other words, a point
+    on the hypersphere: :math:`\mathbf{\mu}\in S^{d-1}`. :math:`\kappa` is a
+    concentration parameter, which means that it must be positive
+    (:math:`\kappa>0`) and that the distribution becomes more narrow with
+    increasing :math:`\kappa`. In that sense, the reciprocal value
+    :math:`1/\kappa` resembles the variance parameter of the normal
+    distribution.
+
+    The von Mises-Fisher distribution often serves as an analogue of the
+    normal distribution on the sphere. Intuitively, for unit vectors, a
+    useful distance measure is given by the angle :math:`\alpha` between
+    them. This is exactly what the scalar product
+    :math:`\mathbf{\mu}^T\mathbf{x}=\cos(\alpha)` in the
+    von Mises-Fisher probability density function describes: the angle
+    between the mean direction :math:`\mathbf{\mu}` and the vector
+    :math:`\mathbf{x}`. The larger the angle between them, the smaller the
+    probability to observe :math:`\mathbf{x}` for this particular mean
+    direction :math:`\mathbf{\mu}`.
+
+    In dimensions 2 and 3, specialized algorithms are used for fast sampling
+    [2]_, [3]_. For dimensions of 4 or higher the rejection sampling algorithm
+    described in [4]_ is utilized. This implementation is partially based on
+    the geomstats package [5]_, [6]_.
+
+    .. versionadded:: 1.11
+
+    References
+    ----------
+    .. [1] Von Mises-Fisher distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Von_Mises%E2%80%93Fisher_distribution
+    .. [2] Mardia, K., and Jupp, P. Directional statistics. Wiley, 2000.
+    .. [3] J. Wenzel. Numerically stable sampling of the von Mises Fisher
+           distribution on S2.
+           https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf
+    .. [4] Wood, A. Simulation of the von mises fisher distribution.
+           Communications in statistics-simulation and computation 23,
+           1 (1994), 157-164. https://doi.org/10.1080/03610919408813161
+    .. [5] geomstats, Github. MIT License. Accessed: 06.01.2023.
+           https://github.com/geomstats/geomstats
+    .. [6] Miolane, N. et al. Geomstats:  A Python Package for Riemannian
+           Geometry in Machine Learning. Journal of Machine Learning Research
+           21 (2020). http://jmlr.org/papers/v21/19-027.html
+
+    Examples
+    --------
+    **Visualization of the probability density**
+
+    Plot the probability density in three dimensions for increasing
+    concentration parameter. The density is calculated by the ``pdf``
+    method.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import vonmises_fisher
+    >>> from matplotlib.colors import Normalize
+    >>> n_grid = 100
+    >>> u = np.linspace(0, np.pi, n_grid)
+    >>> v = np.linspace(0, 2 * np.pi, n_grid)
+    >>> u_grid, v_grid = np.meshgrid(u, v)
+    >>> vertices = np.stack([np.cos(v_grid) * np.sin(u_grid),
+    ...                      np.sin(v_grid) * np.sin(u_grid),
+    ...                      np.cos(u_grid)],
+    ...                     axis=2)
+    >>> x = np.outer(np.cos(v), np.sin(u))
+    >>> y = np.outer(np.sin(v), np.sin(u))
+    >>> z = np.outer(np.ones_like(u), np.cos(u))
+    >>> def plot_vmf_density(ax, x, y, z, vertices, mu, kappa):
+    ...     vmf = vonmises_fisher(mu, kappa)
+    ...     pdf_values = vmf.pdf(vertices)
+    ...     pdfnorm = Normalize(vmin=pdf_values.min(), vmax=pdf_values.max())
+    ...     ax.plot_surface(x, y, z, rstride=1, cstride=1,
+    ...                     facecolors=plt.cm.viridis(pdfnorm(pdf_values)),
+    ...                     linewidth=0)
+    ...     ax.set_aspect('equal')
+    ...     ax.view_init(azim=-130, elev=0)
+    ...     ax.axis('off')
+    ...     ax.set_title(rf"$\kappa={kappa}$")
+    >>> fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9, 4),
+    ...                          subplot_kw={"projection": "3d"})
+    >>> left, middle, right = axes
+    >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0])
+    >>> plot_vmf_density(left, x, y, z, vertices, mu, 5)
+    >>> plot_vmf_density(middle, x, y, z, vertices, mu, 20)
+    >>> plot_vmf_density(right, x, y, z, vertices, mu, 100)
+    >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0, right=1.0, wspace=0.)
+    >>> plt.show()
+
+    As we increase the concentration parameter, the points are getting more
+    clustered together around the mean direction.
+
+    **Sampling**
+
+    Draw 5 samples from the distribution using the ``rvs`` method resulting
+    in a 5x3 array.
+
+    >>> rng = np.random.default_rng()
+    >>> mu = np.array([0, 0, 1])
+    >>> samples = vonmises_fisher(mu, 20).rvs(5, random_state=rng)
+    >>> samples
+    array([[ 0.3884594 , -0.32482588,  0.86231516],
+           [ 0.00611366, -0.09878289,  0.99509023],
+           [-0.04154772, -0.01637135,  0.99900239],
+           [-0.14613735,  0.12553507,  0.98126695],
+           [-0.04429884, -0.23474054,  0.97104814]])
+
+    These samples are unit vectors on the sphere :math:`S^2`. To verify,
+    let us calculate their euclidean norms:
+
+    >>> np.linalg.norm(samples, axis=1)
+    array([1., 1., 1., 1., 1.])
+
+    Plot 20 observations drawn from the von Mises-Fisher distribution for
+    increasing concentration parameter :math:`\kappa`. The red dot highlights
+    the mean direction :math:`\mu`.
+
+    >>> def plot_vmf_samples(ax, x, y, z, mu, kappa):
+    ...     vmf = vonmises_fisher(mu, kappa)
+    ...     samples = vmf.rvs(20)
+    ...     ax.plot_surface(x, y, z, rstride=1, cstride=1, linewidth=0,
+    ...                     alpha=0.2)
+    ...     ax.scatter(samples[:, 0], samples[:, 1], samples[:, 2], c='k', s=5)
+    ...     ax.scatter(mu[0], mu[1], mu[2], c='r', s=30)
+    ...     ax.set_aspect('equal')
+    ...     ax.view_init(azim=-130, elev=0)
+    ...     ax.axis('off')
+    ...     ax.set_title(rf"$\kappa={kappa}$")
+    >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0])
+    >>> fig, axes = plt.subplots(nrows=1, ncols=3,
+    ...                          subplot_kw={"projection": "3d"},
+    ...                          figsize=(9, 4))
+    >>> left, middle, right = axes
+    >>> plot_vmf_samples(left, x, y, z, mu, 5)
+    >>> plot_vmf_samples(middle, x, y, z, mu, 20)
+    >>> plot_vmf_samples(right, x, y, z, mu, 100)
+    >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0,
+    ...                     right=1.0, wspace=0.)
+    >>> plt.show()
+
+    The plots show that with increasing concentration :math:`\kappa` the
+    resulting samples are centered more closely around the mean direction.
+
+    **Fitting the distribution parameters**
+
+    The distribution can be fitted to data using the ``fit`` method returning
+    the estimated parameters. As a toy example let's fit the distribution to
+    samples drawn from a known von Mises-Fisher distribution.
+
+    >>> mu, kappa = np.array([0, 0, 1]), 20
+    >>> samples = vonmises_fisher(mu, kappa).rvs(1000, random_state=rng)
+    >>> mu_fit, kappa_fit = vonmises_fisher.fit(samples)
+    >>> mu_fit, kappa_fit
+    (array([0.01126519, 0.01044501, 0.99988199]), 19.306398751730995)
+
+    We see that the estimated parameters `mu_fit` and `kappa_fit` are
+    very close to the ground truth parameters.
+
+    """
+    def __init__(self, seed=None):
+        super().__init__(seed)
+
+    def __call__(self, mu=None, kappa=1, seed=None):
+        """Create a frozen von Mises-Fisher distribution.
+
+        See `vonmises_fisher_frozen` for more information.
+        """
+        return vonmises_fisher_frozen(mu, kappa, seed=seed)
+
+    def _process_parameters(self, mu, kappa):
+        """
+        Infer dimensionality from mu and ensure that mu is a one-dimensional
+        unit vector and kappa positive.
+        """
+        mu = np.asarray(mu)
+        if mu.ndim > 1:
+            raise ValueError("'mu' must have one-dimensional shape.")
+        if not np.allclose(np.linalg.norm(mu), 1.):
+            raise ValueError("'mu' must be a unit vector of norm 1.")
+        if not mu.size > 1:
+            raise ValueError("'mu' must have at least two entries.")
+        kappa_error_msg = "'kappa' must be a positive scalar."
+        if not np.isscalar(kappa) or kappa < 0:
+            raise ValueError(kappa_error_msg)
+        if float(kappa) == 0.:
+            raise ValueError("For 'kappa=0' the von Mises-Fisher distribution "
+                             "becomes the uniform distribution on the sphere "
+                             "surface. Consider using "
+                             "'scipy.stats.uniform_direction' instead.")
+        dim = mu.size
+
+        return dim, mu, kappa
+
+    def _check_data_vs_dist(self, x, dim):
+        if x.shape[-1] != dim:
+            raise ValueError("The dimensionality of the last axis of 'x' must "
+                             "match the dimensionality of the "
+                             "von Mises Fisher distribution.")
+        if not np.allclose(np.linalg.norm(x, axis=-1), 1.):
+            msg = "'x' must be unit vectors of norm 1 along last dimension."
+            raise ValueError(msg)
+
+    def _log_norm_factor(self, dim, kappa):
+        # normalization factor is given by
+        # c = kappa**(dim/2-1)/((2*pi)**(dim/2)*I[dim/2-1](kappa))
+        #   = kappa**(dim/2-1)*exp(-kappa) /
+        #     ((2*pi)**(dim/2)*I[dim/2-1](kappa)*exp(-kappa)
+        #   = kappa**(dim/2-1)*exp(-kappa) /
+        #     ((2*pi)**(dim/2)*ive[dim/2-1](kappa)
+        # Then the log is given by
+        # log c = 1/2*(dim -1)*log(kappa) - kappa - -1/2*dim*ln(2*pi) -
+        #         ive[dim/2-1](kappa)
+        halfdim = 0.5 * dim
+        return (0.5 * (dim - 2)*np.log(kappa) - halfdim * _LOG_2PI -
+                np.log(ive(halfdim - 1, kappa)) - kappa)
+
+    def _logpdf(self, x, dim, mu, kappa):
+        """Log of the von Mises-Fisher probability density function.
+
+        As this function does no argument checking, it should not be
+        called directly; use 'logpdf' instead.
+
+        """
+        x = np.asarray(x)
+        self._check_data_vs_dist(x, dim)
+        dotproducts = np.einsum('i,...i->...', mu, x)
+        return self._log_norm_factor(dim, kappa) + kappa * dotproducts
+
+    def logpdf(self, x, mu=None, kappa=1):
+        """Log of the von Mises-Fisher probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the log of the probability
+            density function. The last axis of `x` must correspond
+            to unit vectors of the same dimensionality as the distribution.
+        mu : array_like, default: None
+            Mean direction of the distribution. Must be a one-dimensional unit
+            vector of norm 1.
+        kappa : float, default: 1
+            Concentration parameter. Must be positive.
+
+        Returns
+        -------
+        logpdf : ndarray or scalar
+            Log of the probability density function evaluated at `x`.
+
+        """
+        dim, mu, kappa = self._process_parameters(mu, kappa)
+        return self._logpdf(x, dim, mu, kappa)
+
+    def pdf(self, x, mu=None, kappa=1):
+        """Von Mises-Fisher probability density function.
+
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the probability
+            density function. The last axis of `x` must correspond
+            to unit vectors of the same dimensionality as the distribution.
+        mu : array_like
+            Mean direction of the distribution. Must be a one-dimensional unit
+            vector of norm 1.
+        kappa : float
+            Concentration parameter. Must be positive.
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Probability density function evaluated at `x`.
+
+        """
+        dim, mu, kappa = self._process_parameters(mu, kappa)
+        return np.exp(self._logpdf(x, dim, mu, kappa))
+
+    def _rvs_2d(self, mu, kappa, size, random_state):
+        """
+        In 2D, the von Mises-Fisher distribution reduces to the
+        von Mises distribution which can be efficiently sampled by numpy.
+        This method is much faster than the general rejection
+        sampling based algorithm.
+
+        """
+        mean_angle = np.arctan2(mu[1], mu[0])
+        angle_samples = random_state.vonmises(mean_angle, kappa, size=size)
+        samples = np.stack([np.cos(angle_samples), np.sin(angle_samples)],
+                           axis=-1)
+        return samples
+
+    def _rvs_3d(self, kappa, size, random_state):
+        """
+        Generate samples from a von Mises-Fisher distribution
+        with mu = [1, 0, 0] and kappa. Samples then have to be
+        rotated towards the desired mean direction mu.
+        This method is much faster than the general rejection
+        sampling based algorithm.
+        Reference: https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf
+
+        """
+        if size is None:
+            sample_size = 1
+        else:
+            sample_size = size
+
+        # compute x coordinate acc. to equation from section 3.1
+        x = random_state.random(sample_size)
+        x = 1. + np.log(x + (1. - x) * np.exp(-2 * kappa))/kappa
+
+        # (y, z) are random 2D vectors that only have to be
+        # normalized accordingly. Then (x, y z) follow a VMF distribution
+        temp = np.sqrt(1. - np.square(x))
+        uniformcircle = _sample_uniform_direction(2, sample_size, random_state)
+        samples = np.stack([x, temp * uniformcircle[..., 0],
+                            temp * uniformcircle[..., 1]],
+                           axis=-1)
+        if size is None:
+            samples = np.squeeze(samples)
+        return samples
+
+    def _rejection_sampling(self, dim, kappa, size, random_state):
+        """
+        Generate samples from a n-dimensional von Mises-Fisher distribution
+        with mu = [1, 0, ..., 0] and kappa via rejection sampling.
+        Samples then have to be rotated towards the desired mean direction mu.
+        Reference: https://doi.org/10.1080/03610919408813161
+        """
+        dim_minus_one = dim - 1
+        # calculate number of requested samples
+        if size is not None:
+            if not np.iterable(size):
+                size = (size, )
+            n_samples = math.prod(size)
+        else:
+            n_samples = 1
+        # calculate envelope for rejection sampler (eq. 4)
+        sqrt = np.sqrt(4 * kappa ** 2. + dim_minus_one ** 2)
+        envelop_param = (-2 * kappa + sqrt) / dim_minus_one
+        if envelop_param == 0:
+            # the regular formula suffers from loss of precision for high
+            # kappa. This can only be detected by checking for 0 here.
+            # Workaround: expansion for sqrt variable
+            # https://www.wolframalpha.com/input?i=sqrt%284*x%5E2%2Bd%5E2%29
+            # e = (-2 * k + sqrt(k**2 + d**2)) / d
+            #   ~ (-2 * k + 2 * k + d**2/(4 * k) - d**4/(64 * k**3)) / d
+            #   = d/(4 * k) - d**3/(64 * k**3)
+            envelop_param = (dim_minus_one/4 * kappa**-1.
+                             - dim_minus_one**3/64 * kappa**-3.)
+        # reference step 0
+        node = (1. - envelop_param) / (1. + envelop_param)
+        # t = ln(1 - ((1-x)/(1+x))**2)
+        #   = ln(4 * x / (1+x)**2)
+        #   = ln(4) + ln(x) - 2*log1p(x)
+        correction = (kappa * node + dim_minus_one
+                      * (np.log(4) + np.log(envelop_param)
+                      - 2 * np.log1p(envelop_param)))
+        n_accepted = 0
+        x = np.zeros((n_samples, ))
+        halfdim = 0.5 * dim_minus_one
+        # main loop
+        while n_accepted < n_samples:
+            # generate candidates acc. to reference step 1
+            sym_beta = random_state.beta(halfdim, halfdim,
+                                         size=n_samples - n_accepted)
+            coord_x = (1 - (1 + envelop_param) * sym_beta) / (
+                1 - (1 - envelop_param) * sym_beta)
+            # accept or reject: reference step 2
+            # reformulation for numerical stability:
+            # t = ln(1 - (1-x)/(1+x) * y)
+            #   = ln((1 + x - y +x*y)/(1 +x))
+            accept_tol = random_state.random(n_samples - n_accepted)
+            criterion = (
+                kappa * coord_x
+                + dim_minus_one * (np.log((1 + envelop_param - coord_x
+                + coord_x * envelop_param) / (1 + envelop_param)))
+                - correction) > np.log(accept_tol)
+            accepted_iter = np.sum(criterion)
+            x[n_accepted:n_accepted + accepted_iter] = coord_x[criterion]
+            n_accepted += accepted_iter
+        # concatenate x and remaining coordinates: step 3
+        coord_rest = _sample_uniform_direction(dim_minus_one, n_accepted,
+                                               random_state)
+        coord_rest = np.einsum(
+            '...,...i->...i', np.sqrt(1 - x ** 2), coord_rest)
+        samples = np.concatenate([x[..., None], coord_rest], axis=1)
+        # reshape output to (size, dim)
+        if size is not None:
+            samples = samples.reshape(size + (dim, ))
+        else:
+            samples = np.squeeze(samples)
+        return samples
+
+    def _rotate_samples(self, samples, mu, dim):
+        """A QR decomposition is used to find the rotation that maps the
+        north pole (1, 0,...,0) to the vector mu. This rotation is then
+        applied to all samples.
+
+        Parameters
+        ----------
+        samples: array_like, shape = [..., n]
+        mu : array-like, shape=[n, ]
+            Point to parametrise the rotation.
+
+        Returns
+        -------
+        samples : rotated samples
+
+        """
+        base_point = np.zeros((dim, ))
+        base_point[0] = 1.
+        embedded = np.concatenate([mu[None, :], np.zeros((dim - 1, dim))])
+        rotmatrix, _ = np.linalg.qr(np.transpose(embedded))
+        if np.allclose(np.matmul(rotmatrix, base_point[:, None])[:, 0], mu):
+            rotsign = 1
+        else:
+            rotsign = -1
+
+        # apply rotation
+        samples = np.einsum('ij,...j->...i', rotmatrix, samples) * rotsign
+        return samples
+
+    def _rvs(self, dim, mu, kappa, size, random_state):
+        if dim == 2:
+            samples = self._rvs_2d(mu, kappa, size, random_state)
+        elif dim == 3:
+            samples = self._rvs_3d(kappa, size, random_state)
+        else:
+            samples = self._rejection_sampling(dim, kappa, size,
+                                               random_state)
+
+        if dim != 2:
+            samples = self._rotate_samples(samples, mu, dim)
+        return samples
+
+    def rvs(self, mu=None, kappa=1, size=1, random_state=None):
+        """Draw random samples from a von Mises-Fisher distribution.
+
+        Parameters
+        ----------
+        mu : array_like
+            Mean direction of the distribution. Must be a one-dimensional unit
+            vector of norm 1.
+        kappa : float
+            Concentration parameter. Must be positive.
+        size : int or tuple of ints, optional
+            Given a shape of, for example, (m,n,k), m*n*k samples are
+            generated, and packed in an m-by-n-by-k arrangement.
+            Because each sample is N-dimensional, the output shape
+            is (m,n,k,N). If no shape is specified, a single (N-D)
+            sample is returned.
+        random_state : {None, int, np.random.RandomState, np.random.Generator},
+                        optional
+            Used for drawing random variates.
+            If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used, seeded
+            with seed.
+            If `seed` is already a ``RandomState`` or ``Generator`` instance,
+            then that object is used.
+            Default is `None`.
+
+        Returns
+        -------
+        rvs : ndarray
+            Random variates of shape (`size`, `N`), where `N` is the
+            dimension of the distribution.
+
+        """
+        dim, mu, kappa = self._process_parameters(mu, kappa)
+        random_state = self._get_random_state(random_state)
+        samples = self._rvs(dim, mu, kappa, size, random_state)
+        return samples
+
+    def _entropy(self, dim, kappa):
+        halfdim = 0.5 * dim
+        return (-self._log_norm_factor(dim, kappa) - kappa *
+                ive(halfdim, kappa) / ive(halfdim - 1, kappa))
+
+    def entropy(self, mu=None, kappa=1):
+        """Compute the differential entropy of the von Mises-Fisher
+        distribution.
+
+        Parameters
+        ----------
+        mu : array_like, default: None
+            Mean direction of the distribution. Must be a one-dimensional unit
+            vector of norm 1.
+        kappa : float, default: 1
+            Concentration parameter. Must be positive.
+
+        Returns
+        -------
+        h : scalar
+            Entropy of the von Mises-Fisher distribution.
+
+        """
+        dim, _, kappa = self._process_parameters(mu, kappa)
+        return self._entropy(dim, kappa)
+
+    def fit(self, x):
+        """Fit the von Mises-Fisher distribution to data.
+
+        Parameters
+        ----------
+        x : array-like
+            Data the distribution is fitted to. Must be two dimensional.
+            The second axis of `x` must be unit vectors of norm 1 and
+            determine the dimensionality of the fitted
+            von Mises-Fisher distribution.
+
+        Returns
+        -------
+        mu : ndarray
+            Estimated mean direction.
+        kappa : float
+            Estimated concentration parameter.
+
+        """
+        # validate input data
+        x = np.asarray(x)
+        if x.ndim != 2:
+            raise ValueError("'x' must be two dimensional.")
+        if not np.allclose(np.linalg.norm(x, axis=-1), 1.):
+            msg = "'x' must be unit vectors of norm 1 along last dimension."
+            raise ValueError(msg)
+        dim = x.shape[-1]
+
+        # mu is simply the directional mean
+        dirstats = directional_stats(x)
+        mu = dirstats.mean_direction
+        r = dirstats.mean_resultant_length
+
+        # kappa is the solution to the equation:
+        # r = I[dim/2](kappa) / I[dim/2 -1](kappa)
+        #   = I[dim/2](kappa) * exp(-kappa) / I[dim/2 -1](kappa) * exp(-kappa)
+        #   = ive(dim/2, kappa) / ive(dim/2 -1, kappa)
+
+        halfdim = 0.5 * dim
+
+        def solve_for_kappa(kappa):
+            bessel_vals = ive([halfdim, halfdim - 1], kappa)
+            return bessel_vals[0]/bessel_vals[1] - r
+
+        root_res = root_scalar(solve_for_kappa, method="brentq",
+                               bracket=(1e-8, 1e9))
+        kappa = root_res.root
+        return mu, kappa
+
+
+vonmises_fisher = vonmises_fisher_gen()
+
+
+class vonmises_fisher_frozen(multi_rv_frozen):
+    def __init__(self, mu=None, kappa=1, seed=None):
+        """Create a frozen von Mises-Fisher distribution.
+
+        Parameters
+        ----------
+        mu : array_like, default: None
+            Mean direction of the distribution.
+        kappa : float, default: 1
+            Concentration parameter. Must be positive.
+        seed : {None, int, `numpy.random.Generator`,
+                `numpy.random.RandomState`}, optional
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+
+        """
+        self._dist = vonmises_fisher_gen(seed)
+        self.dim, self.mu, self.kappa = (
+            self._dist._process_parameters(mu, kappa)
+        )
+
+    def logpdf(self, x):
+        """
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the log of the probability
+            density function. The last axis of `x` must correspond
+            to unit vectors of the same dimensionality as the distribution.
+
+        Returns
+        -------
+        logpdf : ndarray or scalar
+            Log of probability density function evaluated at `x`.
+
+        """
+        return self._dist._logpdf(x, self.dim, self.mu, self.kappa)
+
+    def pdf(self, x):
+        """
+        Parameters
+        ----------
+        x : array_like
+            Points at which to evaluate the log of the probability
+            density function. The last axis of `x` must correspond
+            to unit vectors of the same dimensionality as the distribution.
+
+        Returns
+        -------
+        pdf : ndarray or scalar
+            Probability density function evaluated at `x`.
+
+        """
+        return np.exp(self.logpdf(x))
+
+    def rvs(self, size=1, random_state=None):
+        """Draw random variates from the Von Mises-Fisher distribution.
+
+        Parameters
+        ----------
+        size : int or tuple of ints, optional
+            Given a shape of, for example, (m,n,k), m*n*k samples are
+            generated, and packed in an m-by-n-by-k arrangement.
+            Because each sample is N-dimensional, the output shape
+            is (m,n,k,N). If no shape is specified, a single (N-D)
+            sample is returned.
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+            singleton is used.
+            If `seed` is an int, a new ``RandomState`` instance is used,
+            seeded with `seed`.
+            If `seed` is already a ``Generator`` or ``RandomState`` instance
+            then that instance is used.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Random variates of size (`size`, `N`), where `N` is the
+            dimension of the distribution.
+
+        """
+        random_state = self._dist._get_random_state(random_state)
+        return self._dist._rvs(self.dim, self.mu, self.kappa, size,
+                               random_state)
+
+    def entropy(self):
+        """
+        Calculate the differential entropy of the von Mises-Fisher
+        distribution.
+
+        Returns
+        -------
+        h: float
+            Entropy of the Von Mises-Fisher distribution.
+
+        """
+        return self._dist._entropy(self.dim, self.kappa)
+
+
+class normal_inverse_gamma_gen(multi_rv_generic):
+    r"""Normal-inverse-gamma distribution.
+
+    The normal-inverse-gamma distribution is the conjugate prior of a normal
+    distribution with unknown mean and variance.
+
+    Methods
+    -------
+    pdf(x, s2, mu=0, lmbda=1, a=1, b=1)
+        Probability density function.
+    logpdf(x, s2, mu=0, lmbda=1, a=1, b=1)
+        Log of the probability density function.
+    mean(mu=0, lmbda=1, a=1, b=1)
+        Distribution mean.
+    var(mu=0, lmbda=1, a=1, b=1)
+        Distribution variance.
+    rvs(mu=0, lmbda=1, a=1, b=1, size=None, random_state=None)
+        Draw random samples.
+
+    Parameters
+    ----------
+    mu, lmbda, a, b  : array_like
+        Shape parameters of the distribution. See notes.
+    seed : {None, int, np.random.RandomState, np.random.Generator}, optional
+        Used for drawing random variates.
+        If `seed` is `None`, the `~np.random.RandomState` singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used, seeded
+        with seed.
+        If `seed` is already a ``RandomState`` or ``Generator`` instance,
+        then that object is used.
+        Default is `None`.
+
+    See Also
+    --------
+    norm
+    invgamma
+
+    Notes
+    -----
+
+    The probability density function of `normal_inverse_gamma` is:
+
+    .. math::
+
+        f(x, \sigma^2; \mu, \lambda, \alpha, \beta) =
+            \frac{\sqrt{\lambda}}{\sqrt{2 \pi \sigma^2}}
+            \frac{\beta^\alpha}{\Gamma(\alpha)}
+            \left( \frac{1}{\sigma^2} \right)^{\alpha + 1}
+            \exp \left(- \frac{2 \beta + \lambda (x - \mu)^2} {2 \sigma^2} \right)
+
+    where all parameters are real and finite, and :math:`\sigma^2 > 0`,
+    :math:`\lambda > 0`, :math:`\alpha > 0`, and :math:`\beta > 0`.
+
+    Methods ``normal_inverse_gamma.pdf`` and ``normal_inverse_gamma.logpdf``
+    accept `x` and `s2` for arguments :math:`x` and :math:`\sigma^2`.
+    All methods accept `mu`, `lmbda`, `a`, and `b` for shape parameters
+    :math:`\mu`, :math:`\lambda`, :math:`\alpha`, and :math:`\beta`,
+    respectively.
+
+    .. versionadded:: 1.15
+
+    References
+    ----------
+    .. [1] Normal-inverse-gamma distribution, Wikipedia,
+           https://en.wikipedia.org/wiki/Normal-inverse-gamma_distribution
+
+    Examples
+    --------
+    Suppose we wish to investigate the relationship between the
+    normal-inverse-gamma distribution and the inverse gamma distribution.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+    >>> rng = np.random.default_rng(527484872345)
+    >>> mu, lmbda, a, b = 0, 1, 20, 20
+    >>> norm_inv_gamma = stats.normal_inverse_gamma(mu, lmbda, a, b)
+    >>> inv_gamma = stats.invgamma(a, scale=b)
+
+    One approach is to compare the distribution of the `s2` elements of
+    random variates against the PDF of an inverse gamma distribution.
+
+    >>> _, s2 = norm_inv_gamma.rvs(size=10000, random_state=rng)
+    >>> bins = np.linspace(s2.min(), s2.max(), 50)
+    >>> plt.hist(s2, bins=bins, density=True, label='Frequency density')
+    >>> s2 = np.linspace(s2.min(), s2.max(), 300)
+    >>> plt.plot(s2, inv_gamma.pdf(s2), label='PDF')
+    >>> plt.xlabel(r'$\sigma^2$')
+    >>> plt.ylabel('Frequency density / PMF')
+    >>> plt.show()
+
+    Similarly, we can compare the marginal distribution of `s2` against
+    an inverse gamma distribution.
+
+    >>> from scipy.integrate import quad_vec
+    >>> from scipy import integrate
+    >>> s2 = np.linspace(0.5, 3, 6)
+    >>> res = quad_vec(lambda x: norm_inv_gamma.pdf(x, s2), -np.inf, np.inf)[0]
+    >>> np.allclose(res, inv_gamma.pdf(s2))
+    True
+
+    The sample mean is comparable to the mean of the distribution.
+
+    >>> x, s2 = norm_inv_gamma.rvs(size=10000, random_state=rng)
+    >>> x.mean(), s2.mean()
+    (np.float64(-0.005254750127304425), np.float64(1.050438111436508))
+    >>> norm_inv_gamma.mean()
+    (np.float64(0.0), np.float64(1.0526315789473684))
+
+    Similarly, for the variance:
+
+    >>> x.var(ddof=1), s2.var(ddof=1)
+    (np.float64(1.0546150578185023), np.float64(0.061829865266330754))
+    >>> norm_inv_gamma.var()
+    (np.float64(1.0526315789473684), np.float64(0.061557402277623886))
+
+    """
+    def rvs(self, mu=0, lmbda=1, a=1, b=1, size=None, random_state=None):
+        """Draw random samples from the distribution.
+
+        Parameters
+        ----------
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda`, `a`, and `b` must be greater
+            than zero.
+        size : int or tuple of ints, optional
+            Shape of samples to draw.
+        random_state : {None, int, np.random.RandomState, np.random.Generator}, optional
+            Used for drawing random variates.
+            If `random_state` is `None`, the `~np.random.RandomState` singleton is used.
+            If `random_state` is an int, a new ``RandomState`` instance is used, seeded
+            with `random_state`.
+            If `random_state` is already a ``RandomState`` or ``Generator`` instance,
+            then that object is used.
+            Default is `None`.
+
+        Returns
+        -------
+        x, s2 : ndarray
+            Random variates.
+
+        """
+        random_state = self._get_random_state(random_state)
+        s2 = invgamma(a, scale=b).rvs(size=size, random_state=random_state)
+        scale = (s2 / lmbda)**0.5
+        x = norm(loc=mu, scale=scale).rvs(size=size, random_state=random_state)
+        dtype = np.result_type(1.0, mu, lmbda, a, b)
+        return x.astype(dtype), s2.astype(dtype)
+
+    def _logpdf(self, x, s2, mu, lmbda, a, b):
+        t1 = 0.5 * (np.log(lmbda) - np.log(2 * np.pi * s2))
+        t2 = a*np.log(b) - special.gammaln(a).astype(a.dtype)
+        t3 = -(a + 1) * np.log(s2)
+        t4 = -(2*b + lmbda*(x - mu)**2) / (2*s2)
+        return t1 + t2 + t3 + t4
+
+    def logpdf(self, x, s2, mu=0, lmbda=1, a=1, b=1):
+        """Log of the probability density function.
+
+        Parameters
+        ----------
+        x, s2 : array_like
+            Arguments. `s2` must be greater than zero.
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda`, `a`, and `b` must be greater
+            than zero.
+
+        Returns
+        -------
+        logpdf : ndarray or scalar
+            Log of the probability density function.
+
+        """
+        invalid, args = self._process_parameters_pdf(x, s2, mu, lmbda, a, b)
+        s2 = args[1]
+        # Keep it simple for now; lazyselect later, perhaps.
+        with np.errstate(all='ignore'):
+            logpdf = np.asarray(self._logpdf(*args))
+        logpdf[s2 <= 0] = -np.inf
+        logpdf[invalid] = np.nan
+        return logpdf[()]
+
+    def _pdf(self, x, s2, mu, lmbda, a, b):
+        t1 = np.sqrt(lmbda / (2 * np.pi * s2))
+        t2 = b**a / special.gamma(a).astype(a.dtype)
+        t3 = (1 / s2)**(a + 1)
+        t4 = np.exp(-(2*b + lmbda*(x - mu)**2) / (2*s2))
+        return t1 * t2 * t3 * t4
+
+    def pdf(self, x, s2, mu=0, lmbda=1, a=1, b=1):
+        """The probability density function.
+
+        Parameters
+        ----------
+        x, s2 : array_like
+            Arguments. `s2` must be greater than zero.
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda`, `a`, and `b` must be greater
+            than zero.
+
+        Returns
+        -------
+        logpdf : ndarray or scalar
+            The probability density function.
+
+        """
+        invalid, args = self._process_parameters_pdf(x, s2, mu, lmbda, a, b)
+        s2 = args[1]
+        # Keep it simple for now; lazyselect later, perhaps.
+        with np.errstate(all='ignore'):
+            pdf = np.asarray(self._pdf(*args))
+        pdf[s2 <= 0] = 0
+        pdf[invalid] = np.nan
+        return pdf[()]
+
+    def mean(self, mu=0, lmbda=1, a=1, b=1):
+        """The mean of the distribution.
+
+        Parameters
+        ----------
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda` and `b` must be greater
+            than zero, and `a` must be greater than one.
+
+        Returns
+        -------
+        x, s2 : ndarray
+            The mean of the distribution.
+
+        """
+        invalid, args = self._process_shapes(mu, lmbda, a, b)
+        mu, lmbda, a, b = args
+        invalid |= ~(a > 1)
+        mean_x = np.asarray(mu).copy()
+        mean_s2 = np.asarray(b / (a - 1))
+        mean_x[invalid] = np.nan
+        mean_s2[invalid] = np.nan
+        return mean_x[()], mean_s2[()]
+
+    def var(self, mu=0, lmbda=1, a=1, b=1):
+        """The variance of the distribution.
+
+        Parameters
+        ----------
+        mu, lmbda, a, b : array_like, optional
+            Shape parameters. `lmbda` and `b` must be greater
+            than zero, and `a` must be greater than two.
+
+        Returns
+        -------
+        x, s2 : ndarray
+            The variance of the distribution.
+
+        """
+        invalid, args = self._process_shapes(mu, lmbda, a, b)
+        mu, lmbda, a, b = args
+        invalid_x = invalid | ~(a > 1)
+        invalid_s2 = invalid | ~(a > 2)
+        var_x = b / ((a - 1) * lmbda)
+        var_s2 = b**2 / ((a - 1)**2 * (a - 2))
+        var_x, var_s2 = np.asarray(var_x), np.asarray(var_s2)
+        var_x[invalid_x] = np.nan
+        var_s2[invalid_s2] = np.nan
+        return var_x[()], var_s2[()]
+
+    def _process_parameters_pdf(self, x, s2, mu, lmbda, a, b):
+        args = np.broadcast_arrays(x, s2, mu, lmbda, a, b)
+        dtype = np.result_type(1.0, *(arg.dtype for arg in args))
+        args = [arg.astype(dtype, copy=False) for arg in args]
+        x, s2, mu, lmbda, a, b = args
+        invalid = ~((lmbda > 0) & (a > 0) & (b > 0))
+        return invalid, args
+
+    def _process_shapes(self, mu, lmbda, a, b):
+        args = np.broadcast_arrays(mu, lmbda, a, b)
+        dtype = np.result_type(1.0, *(arg.dtype for arg in args))
+        args = [arg.astype(dtype, copy=False) for arg in args]
+        mu, lmbda, a, b = args
+        invalid = ~((lmbda > 0) & (a > 0) & (b > 0))
+        return invalid, args
+
+    def __call__(self, mu=0, lmbda=1, a=1, b=1, seed=None):
+        return normal_inverse_gamma_frozen(mu, lmbda, a, b, seed=seed)
+
+
+normal_inverse_gamma = normal_inverse_gamma_gen()
+
+
+class normal_inverse_gamma_frozen(multi_rv_frozen):
+
+    def __init__(self, mu=0, lmbda=1, a=1, b=1, seed=None):
+        self._dist = normal_inverse_gamma_gen(seed)
+        self._shapes = mu, lmbda, a, b
+
+    def logpdf(self, x, s2):
+        return self._dist.logpdf(x, s2, *self._shapes)
+
+    def pdf(self, x, s2):
+        return self._dist.pdf(x, s2, *self._shapes)
+
+    def mean(self):
+        return self._dist.mean(*self._shapes)
+
+    def var(self):
+        return self._dist.var(*self._shapes)
+
+    def rvs(self, size=None, random_state=None):
+        return self._dist.rvs(*self._shapes, size=size, random_state=random_state)
+
+
+# Set frozen generator docstrings from corresponding docstrings in
+# normal_inverse_gamma_gen and fill in default strings in class docstrings
+for name in ['logpdf', 'pdf', 'mean', 'var', 'rvs']:
+    method = normal_inverse_gamma_gen.__dict__[name]
+    method_frozen = normal_inverse_gamma_frozen.__dict__[name]
+    method_frozen.__doc__ = doccer.docformat(method.__doc__,
+                                             mvn_docdict_noparams)
+    method.__doc__ = doccer.docformat(method.__doc__, mvn_docdict_params)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mvn.cpython-310-x86_64-linux-gnu.so b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mvn.cpython-310-x86_64-linux-gnu.so
new file mode 100644
index 0000000000000000000000000000000000000000..8be6c3f0f4be1b734fc308c17dee7facb1cff0ce
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_mvn.cpython-310-x86_64-linux-gnu.so differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_new_distributions.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_new_distributions.py
new file mode 100644
index 0000000000000000000000000000000000000000..894117e295426b29feafc9b3e5afe7cdfaa1a576
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_new_distributions.py
@@ -0,0 +1,375 @@
+import sys
+
+import numpy as np
+from numpy import inf
+
+from scipy import special
+from scipy.stats._distribution_infrastructure import (
+    ContinuousDistribution, _RealDomain, _RealParameter, _Parameterization,
+    _combine_docs)
+
+__all__ = ['Normal', 'Uniform']
+
+
+class Normal(ContinuousDistribution):
+    r"""Normal distribution with prescribed mean and standard deviation.
+
+    The probability density function of the normal distribution is:
+
+    .. math::
+
+        f(x) = \frac{1}{\sigma \sqrt{2 \pi}} \exp {
+            \left( -\frac{1}{2}\left( \frac{x - \mu}{\sigma} \right)^2 \right)}
+
+    """
+    # `ShiftedScaledDistribution` allows this to be generated automatically from
+    # an instance of `StandardNormal`, but the normal distribution is so frequently
+    # used that it's worth a bit of code duplication to get better performance.
+    _mu_domain = _RealDomain(endpoints=(-inf, inf))
+    _sigma_domain = _RealDomain(endpoints=(0, inf))
+    _x_support = _RealDomain(endpoints=(-inf, inf))
+
+    _mu_param = _RealParameter('mu',  symbol=r'\mu', domain=_mu_domain,
+                               typical=(-1, 1))
+    _sigma_param = _RealParameter('sigma', symbol=r'\sigma', domain=_sigma_domain,
+                                  typical=(0.5, 1.5))
+    _x_param = _RealParameter('x', domain=_x_support, typical=(-1, 1))
+
+    _parameterizations = [_Parameterization(_mu_param, _sigma_param)]
+
+    _variable = _x_param
+    _normalization = 1/np.sqrt(2*np.pi)
+    _log_normalization = np.log(2*np.pi)/2
+
+    def __new__(cls, mu=None, sigma=None, **kwargs):
+        if mu is None and sigma is None:
+            return super().__new__(StandardNormal)
+        return super().__new__(cls)
+
+    def __init__(self, *, mu=0., sigma=1., **kwargs):
+        super().__init__(mu=mu, sigma=sigma, **kwargs)
+
+    def _logpdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._logpdf_formula(self, (x - mu)/sigma) - np.log(sigma)
+
+    def _pdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._pdf_formula(self, (x - mu)/sigma) / sigma
+
+    def _logcdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._logcdf_formula(self, (x - mu)/sigma)
+
+    def _cdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._cdf_formula(self, (x - mu)/sigma)
+
+    def _logccdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._logccdf_formula(self, (x - mu)/sigma)
+
+    def _ccdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._ccdf_formula(self, (x - mu)/sigma)
+
+    def _icdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._icdf_formula(self, x) * sigma + mu
+
+    def _ilogcdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._ilogcdf_formula(self, x) * sigma + mu
+
+    def _iccdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._iccdf_formula(self, x) * sigma + mu
+
+    def _ilogccdf_formula(self, x, *, mu, sigma, **kwargs):
+        return StandardNormal._ilogccdf_formula(self, x) * sigma + mu
+
+    def _entropy_formula(self, *, mu, sigma, **kwargs):
+        return StandardNormal._entropy_formula(self) + np.log(abs(sigma))
+
+    def _logentropy_formula(self, *, mu, sigma, **kwargs):
+        lH0 = StandardNormal._logentropy_formula(self)
+        with np.errstate(divide='ignore'):
+            # sigma = 1 -> log(sigma) = 0 -> log(log(sigma)) = -inf
+            # Silence the unnecessary runtime warning
+            lls = np.log(np.log(abs(sigma))+0j)
+        return special.logsumexp(np.broadcast_arrays(lH0, lls), axis=0)
+
+    def _median_formula(self, *, mu, sigma, **kwargs):
+        return mu
+
+    def _mode_formula(self, *, mu, sigma, **kwargs):
+        return mu
+
+    def _moment_raw_formula(self, order, *, mu, sigma, **kwargs):
+        if order == 0:
+            return np.ones_like(mu)
+        elif order == 1:
+            return mu
+        else:
+            return None
+    _moment_raw_formula.orders = [0, 1]  # type: ignore[attr-defined]
+
+    def _moment_central_formula(self, order, *, mu, sigma, **kwargs):
+        if order == 0:
+            return np.ones_like(mu)
+        elif order % 2:
+            return np.zeros_like(mu)
+        else:
+            # exact is faster (and obviously more accurate) for reasonable orders
+            return sigma**order * special.factorial2(int(order) - 1, exact=True)
+
+    def _sample_formula(self, sample_shape, full_shape, rng, *, mu, sigma, **kwargs):
+        return rng.normal(loc=mu, scale=sigma, size=full_shape)[()]
+
+
+def _log_diff(log_p, log_q):
+    return special.logsumexp([log_p, log_q+np.pi*1j], axis=0)
+
+
+class StandardNormal(Normal):
+    r"""Standard normal distribution.
+
+    The probability density function of the standard normal distribution is:
+
+    .. math::
+
+        f(x) = \frac{1}{\sqrt{2 \pi}} \exp \left( -\frac{1}{2} x^2 \right)
+
+    """
+    _x_support = _RealDomain(endpoints=(-inf, inf))
+    _x_param = _RealParameter('x', domain=_x_support, typical=(-5, 5))
+    _variable = _x_param
+    _parameterizations = []
+    _normalization = 1/np.sqrt(2*np.pi)
+    _log_normalization = np.log(2*np.pi)/2
+    mu = np.float64(0.)
+    sigma = np.float64(1.)
+
+    def __init__(self, **kwargs):
+        ContinuousDistribution.__init__(self, **kwargs)
+
+    def _logpdf_formula(self, x, **kwargs):
+        return -(self._log_normalization + x**2/2)
+
+    def _pdf_formula(self, x, **kwargs):
+        return self._normalization * np.exp(-x**2/2)
+
+    def _logcdf_formula(self, x, **kwargs):
+        return special.log_ndtr(x)
+
+    def _cdf_formula(self, x, **kwargs):
+        return special.ndtr(x)
+
+    def _logccdf_formula(self, x, **kwargs):
+        return special.log_ndtr(-x)
+
+    def _ccdf_formula(self, x, **kwargs):
+        return special.ndtr(-x)
+
+    def _icdf_formula(self, x, **kwargs):
+        return special.ndtri(x)
+
+    def _ilogcdf_formula(self, x, **kwargs):
+        return special.ndtri_exp(x)
+
+    def _iccdf_formula(self, x, **kwargs):
+        return -special.ndtri(x)
+
+    def _ilogccdf_formula(self, x, **kwargs):
+        return -special.ndtri_exp(x)
+
+    def _entropy_formula(self, **kwargs):
+        return (1 + np.log(2*np.pi))/2
+
+    def _logentropy_formula(self, **kwargs):
+        return np.log1p(np.log(2*np.pi)) - np.log(2)
+
+    def _median_formula(self, **kwargs):
+        return 0
+
+    def _mode_formula(self, **kwargs):
+        return 0
+
+    def _moment_raw_formula(self, order, **kwargs):
+        raw_moments = {0: 1, 1: 0, 2: 1, 3: 0, 4: 3, 5: 0}
+        return raw_moments.get(order, None)
+
+    def _moment_central_formula(self, order, **kwargs):
+        return self._moment_raw_formula(order, **kwargs)
+
+    def _moment_standardized_formula(self, order, **kwargs):
+        return self._moment_raw_formula(order, **kwargs)
+
+    def _sample_formula(self, sample_shape, full_shape, rng, **kwargs):
+        return rng.normal(size=full_shape)[()]
+
+
+# currently for testing only
+class _LogUniform(ContinuousDistribution):
+    r"""Log-uniform distribution.
+
+    The probability density function of the log-uniform distribution is:
+
+    .. math::
+
+        f(x; a, b) = \frac{1}
+                          {x (\log(b) - \log(a))}
+
+    If :math:`\log(X)` is a random variable that follows a uniform distribution
+    between :math:`\log(a)` and :math:`\log(b)`, then :math:`X` is log-uniformly
+    distributed with shape parameters :math:`a` and :math:`b`.
+
+    """
+
+    _a_domain = _RealDomain(endpoints=(0, inf))
+    _b_domain = _RealDomain(endpoints=('a', inf))
+    _log_a_domain = _RealDomain(endpoints=(-inf, inf))
+    _log_b_domain = _RealDomain(endpoints=('log_a', inf))
+    _x_support = _RealDomain(endpoints=('a', 'b'), inclusive=(True, True))
+
+    _a_param = _RealParameter('a', domain=_a_domain, typical=(1e-3, 0.9))
+    _b_param = _RealParameter('b', domain=_b_domain, typical=(1.1, 1e3))
+    _log_a_param = _RealParameter('log_a', symbol=r'\log(a)',
+                                  domain=_log_a_domain, typical=(-3, -0.1))
+    _log_b_param = _RealParameter('log_b', symbol=r'\log(b)',
+                                  domain=_log_b_domain, typical=(0.1, 3))
+    _x_param = _RealParameter('x', domain=_x_support, typical=('a', 'b'))
+
+    _b_domain.define_parameters(_a_param)
+    _log_b_domain.define_parameters(_log_a_param)
+    _x_support.define_parameters(_a_param, _b_param)
+
+    _parameterizations = [_Parameterization(_log_a_param, _log_b_param),
+                          _Parameterization(_a_param, _b_param)]
+    _variable = _x_param
+
+    def __init__(self, *, a=None, b=None, log_a=None, log_b=None, **kwargs):
+        super().__init__(a=a, b=b, log_a=log_a, log_b=log_b, **kwargs)
+
+    def _process_parameters(self, a=None, b=None, log_a=None, log_b=None, **kwargs):
+        a = np.exp(log_a) if a is None else a
+        b = np.exp(log_b) if b is None else b
+        log_a = np.log(a) if log_a is None else log_a
+        log_b = np.log(b) if log_b is None else log_b
+        kwargs.update(dict(a=a, b=b, log_a=log_a, log_b=log_b))
+        return kwargs
+
+    # def _logpdf_formula(self, x, *, log_a, log_b, **kwargs):
+    #     return -np.log(x) - np.log(log_b - log_a)
+
+    def _pdf_formula(self, x, *, log_a, log_b, **kwargs):
+        return ((log_b - log_a)*x)**-1
+
+    # def _cdf_formula(self, x, *, log_a, log_b, **kwargs):
+    #     return (np.log(x) - log_a)/(log_b - log_a)
+
+    def _moment_raw_formula(self, order, log_a, log_b, **kwargs):
+        if order == 0:
+            return self._one
+        t1 = self._one / (log_b - log_a) / order
+        t2 = np.real(np.exp(_log_diff(order * log_b, order * log_a)))
+        return t1 * t2
+
+
+class Uniform(ContinuousDistribution):
+    r"""Uniform distribution.
+
+    The probability density function of the uniform distribution is:
+
+    .. math::
+
+        f(x; a, b) = \frac{1}
+                          {b - a}
+
+    """
+
+    _a_domain = _RealDomain(endpoints=(-inf, inf))
+    _b_domain = _RealDomain(endpoints=('a', inf))
+    _x_support = _RealDomain(endpoints=('a', 'b'), inclusive=(True, True))
+
+    _a_param = _RealParameter('a', domain=_a_domain, typical=(1e-3, 0.9))
+    _b_param = _RealParameter('b', domain=_b_domain, typical=(1.1, 1e3))
+    _x_param = _RealParameter('x', domain=_x_support, typical=('a', 'b'))
+
+    _b_domain.define_parameters(_a_param)
+    _x_support.define_parameters(_a_param, _b_param)
+
+    _parameterizations = [_Parameterization(_a_param, _b_param)]
+    _variable = _x_param
+
+    def __init__(self, *, a=None, b=None, **kwargs):
+        super().__init__(a=a, b=b, **kwargs)
+
+    def _process_parameters(self, a=None, b=None, ab=None, **kwargs):
+        ab = b - a
+        kwargs.update(dict(a=a, b=b, ab=ab))
+        return kwargs
+
+    def _logpdf_formula(self, x, *, ab, **kwargs):
+        return np.where(np.isnan(x), np.nan, -np.log(ab))
+
+    def _pdf_formula(self, x, *, ab, **kwargs):
+        return np.where(np.isnan(x), np.nan, 1/ab)
+
+    def _logcdf_formula(self, x, *, a, ab, **kwargs):
+        with np.errstate(divide='ignore'):
+            return np.log(x - a) - np.log(ab)
+
+    def _cdf_formula(self, x, *, a, ab, **kwargs):
+        return (x - a) / ab
+
+    def _logccdf_formula(self, x, *, b, ab, **kwargs):
+        with np.errstate(divide='ignore'):
+            return np.log(b - x) - np.log(ab)
+
+    def _ccdf_formula(self, x, *, b, ab, **kwargs):
+        return (b - x) / ab
+
+    def _icdf_formula(self, p, *, a, ab, **kwargs):
+        return a + ab*p
+
+    def _iccdf_formula(self, p, *, b, ab, **kwargs):
+        return b - ab*p
+
+    def _entropy_formula(self, *, ab, **kwargs):
+        return np.log(ab)
+
+    def _mode_formula(self, *, a, b, ab, **kwargs):
+        return a + 0.5*ab
+
+    def _median_formula(self, *, a, b, ab, **kwargs):
+        return a + 0.5*ab
+
+    def _moment_raw_formula(self, order, a, b, ab, **kwargs):
+        np1 = order + 1
+        return (b**np1 - a**np1) / (np1 * ab)
+
+    def _moment_central_formula(self, order, ab, **kwargs):
+        return ab**2/12 if order == 2 else None
+
+    _moment_central_formula.orders = [2]  # type: ignore[attr-defined]
+
+    def _sample_formula(self, sample_shape, full_shape, rng, a, b, ab, **kwargs):
+        try:
+            return rng.uniform(a, b, size=full_shape)[()]
+        except OverflowError:  # happens when there are NaNs
+            return rng.uniform(0, 1, size=full_shape)*ab + a
+
+
+class _Gamma(ContinuousDistribution):
+    # Gamma distribution for testing only
+    _a_domain = _RealDomain(endpoints=(0, inf))
+    _x_support = _RealDomain(endpoints=(0, inf), inclusive=(False, False))
+
+    _a_param = _RealParameter('a', domain=_a_domain, typical=(0.1, 10))
+    _x_param = _RealParameter('x', domain=_x_support, typical=(0.1, 10))
+
+    _parameterizations = [_Parameterization(_a_param)]
+    _variable = _x_param
+
+    def _pdf_formula(self, x, *, a, **kwargs):
+        return x ** (a - 1) * np.exp(-x) / special.gamma(a)
+
+
+# Distribution classes need only define the summary and beginning of the extended
+# summary portion of the class documentation. All other documentation, including
+# examples, is generated automatically.
+_module = sys.modules[__name__].__dict__
+for dist_name in __all__:
+    _module[dist_name].__doc__ = _combine_docs(_module[dist_name])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_odds_ratio.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_odds_ratio.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc593f5adc9a700c618c721b6c37c801809d868b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_odds_ratio.py
@@ -0,0 +1,466 @@
+import numpy as np
+
+from scipy.special import ndtri
+from scipy.optimize import brentq
+from ._discrete_distns import nchypergeom_fisher
+from ._common import ConfidenceInterval
+
+
+def _sample_odds_ratio(table):
+    """
+    Given a table [[a, b], [c, d]], compute a*d/(b*c).
+
+    Return nan if the numerator and denominator are 0.
+    Return inf if just the denominator is 0.
+    """
+    # table must be a 2x2 numpy array.
+    if table[1, 0] > 0 and table[0, 1] > 0:
+        oddsratio = table[0, 0] * table[1, 1] / (table[1, 0] * table[0, 1])
+    elif table[0, 0] == 0 or table[1, 1] == 0:
+        oddsratio = np.nan
+    else:
+        oddsratio = np.inf
+    return oddsratio
+
+
+def _solve(func):
+    """
+    Solve func(nc) = 0.  func must be an increasing function.
+    """
+    # We could just as well call the variable `x` instead of `nc`, but we
+    # always call this function with functions for which nc (the noncentrality
+    # parameter) is the variable for which we are solving.
+    nc = 1.0
+    value = func(nc)
+    if value == 0:
+        return nc
+
+    # Multiplicative factor by which to increase or decrease nc when
+    # searching for a bracketing interval.
+    factor = 2.0
+    # Find a bracketing interval.
+    if value > 0:
+        nc /= factor
+        while func(nc) > 0:
+            nc /= factor
+        lo = nc
+        hi = factor*nc
+    else:
+        nc *= factor
+        while func(nc) < 0:
+            nc *= factor
+        lo = nc/factor
+        hi = nc
+
+    # lo and hi bracket the solution for nc.
+    nc = brentq(func, lo, hi, xtol=1e-13)
+    return nc
+
+
+def _nc_hypergeom_mean_inverse(x, M, n, N):
+    """
+    For the given noncentral hypergeometric parameters x, M, n,and N
+    (table[0,0], total, row 0 sum and column 0 sum, resp., of a 2x2
+    contingency table), find the noncentrality parameter of Fisher's
+    noncentral hypergeometric distribution whose mean is x.
+    """
+    nc = _solve(lambda nc: nchypergeom_fisher.mean(M, n, N, nc) - x)
+    return nc
+
+
+def _hypergeom_params_from_table(table):
+    # The notation M, n and N is consistent with stats.hypergeom and
+    # stats.nchypergeom_fisher.
+    x = table[0, 0]
+    M = table.sum()
+    n = table[0].sum()
+    N = table[:, 0].sum()
+    return x, M, n, N
+
+
+def _ci_upper(table, alpha):
+    """
+    Compute the upper end of the confidence interval.
+    """
+    if _sample_odds_ratio(table) == np.inf:
+        return np.inf
+
+    x, M, n, N = _hypergeom_params_from_table(table)
+
+    # nchypergeom_fisher.cdf is a decreasing function of nc, so we negate
+    # it in the lambda expression.
+    nc = _solve(lambda nc: -nchypergeom_fisher.cdf(x, M, n, N, nc) + alpha)
+    return nc
+
+
+def _ci_lower(table, alpha):
+    """
+    Compute the lower end of the confidence interval.
+    """
+    if _sample_odds_ratio(table) == 0:
+        return 0
+
+    x, M, n, N = _hypergeom_params_from_table(table)
+
+    nc = _solve(lambda nc: nchypergeom_fisher.sf(x - 1, M, n, N, nc) - alpha)
+    return nc
+
+
+def _conditional_oddsratio(table):
+    """
+    Conditional MLE of the odds ratio for the 2x2 contingency table.
+    """
+    x, M, n, N = _hypergeom_params_from_table(table)
+    # Get the bounds of the support.  The support of the noncentral
+    # hypergeometric distribution with parameters M, n, and N is the same
+    # for all values of the noncentrality parameter, so we can use 1 here.
+    lo, hi = nchypergeom_fisher.support(M, n, N, 1)
+
+    # Check if x is at one of the extremes of the support.  If so, we know
+    # the odds ratio is either 0 or inf.
+    if x == lo:
+        # x is at the low end of the support.
+        return 0
+    if x == hi:
+        # x is at the high end of the support.
+        return np.inf
+
+    nc = _nc_hypergeom_mean_inverse(x, M, n, N)
+    return nc
+
+
+def _conditional_oddsratio_ci(table, confidence_level=0.95,
+                              alternative='two-sided'):
+    """
+    Conditional exact confidence interval for the odds ratio.
+    """
+    if alternative == 'two-sided':
+        alpha = 0.5*(1 - confidence_level)
+        lower = _ci_lower(table, alpha)
+        upper = _ci_upper(table, alpha)
+    elif alternative == 'less':
+        lower = 0.0
+        upper = _ci_upper(table, 1 - confidence_level)
+    else:
+        # alternative == 'greater'
+        lower = _ci_lower(table, 1 - confidence_level)
+        upper = np.inf
+
+    return lower, upper
+
+
+def _sample_odds_ratio_ci(table, confidence_level=0.95,
+                          alternative='two-sided'):
+    oddsratio = _sample_odds_ratio(table)
+    log_or = np.log(oddsratio)
+    se = np.sqrt((1/table).sum())
+    if alternative == 'less':
+        z = ndtri(confidence_level)
+        loglow = -np.inf
+        loghigh = log_or + z*se
+    elif alternative == 'greater':
+        z = ndtri(confidence_level)
+        loglow = log_or - z*se
+        loghigh = np.inf
+    else:
+        # alternative is 'two-sided'
+        z = ndtri(0.5*confidence_level + 0.5)
+        loglow = log_or - z*se
+        loghigh = log_or + z*se
+
+    return np.exp(loglow), np.exp(loghigh)
+
+
+class OddsRatioResult:
+    """
+    Result of `scipy.stats.contingency.odds_ratio`.  See the
+    docstring for `odds_ratio` for more details.
+
+    Attributes
+    ----------
+    statistic : float
+        The computed odds ratio.
+
+        * If `kind` is ``'sample'``, this is sample (or unconditional)
+          estimate, given by
+          ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``.
+        * If `kind` is ``'conditional'``, this is the conditional
+          maximum likelihood estimate for the odds ratio. It is
+          the noncentrality parameter of Fisher's noncentral
+          hypergeometric distribution with the same hypergeometric
+          parameters as `table` and whose mean is ``table[0, 0]``.
+
+    Methods
+    -------
+    confidence_interval :
+        Confidence interval for the odds ratio.
+    """
+
+    def __init__(self, _table, _kind, statistic):
+        # for now, no need to make _table and _kind public, since this sort of
+        # information is returned in very few `scipy.stats` results
+        self._table = _table
+        self._kind = _kind
+        self.statistic = statistic
+
+    def __repr__(self):
+        return f"OddsRatioResult(statistic={self.statistic})"
+
+    def confidence_interval(self, confidence_level=0.95,
+                            alternative='two-sided'):
+        """
+        Confidence interval for the odds ratio.
+
+        Parameters
+        ----------
+        confidence_level: float
+            Desired confidence level for the confidence interval.
+            The value must be given as a fraction between 0 and 1.
+            Default is 0.95 (meaning 95%).
+
+        alternative : {'two-sided', 'less', 'greater'}, optional
+            The alternative hypothesis of the hypothesis test to which the
+            confidence interval corresponds. That is, suppose the null
+            hypothesis is that the true odds ratio equals ``OR`` and the
+            confidence interval is ``(low, high)``. Then the following options
+            for `alternative` are available (default is 'two-sided'):
+
+            * 'two-sided': the true odds ratio is not equal to ``OR``. There
+              is evidence against the null hypothesis at the chosen
+              `confidence_level` if ``high < OR`` or ``low > OR``.
+            * 'less': the true odds ratio is less than ``OR``. The ``low`` end
+              of the confidence interval is 0, and there is evidence against
+              the null hypothesis at  the chosen `confidence_level` if
+              ``high < OR``.
+            * 'greater': the true odds ratio is greater than ``OR``.  The
+              ``high`` end of the confidence interval is ``np.inf``, and there
+              is evidence against the null hypothesis at the chosen
+              `confidence_level` if ``low > OR``.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` instance
+            The confidence interval, represented as an object with
+            attributes ``low`` and ``high``.
+
+        Notes
+        -----
+        When `kind` is ``'conditional'``, the limits of the confidence
+        interval are the conditional "exact confidence limits" as described
+        by Fisher [1]_. The conditional odds ratio and confidence interval are
+        also discussed in Section 4.1.2 of the text by Sahai and Khurshid [2]_.
+
+        When `kind` is ``'sample'``, the confidence interval is computed
+        under the assumption that the logarithm of the odds ratio is normally
+        distributed with standard error given by::
+
+            se = sqrt(1/a + 1/b + 1/c + 1/d)
+
+        where ``a``, ``b``, ``c`` and ``d`` are the elements of the
+        contingency table.  (See, for example, [2]_, section 3.1.3.2,
+        or [3]_, section 2.3.3).
+
+        References
+        ----------
+        .. [1] R. A. Fisher (1935), The logic of inductive inference,
+               Journal of the Royal Statistical Society, Vol. 98, No. 1,
+               pp. 39-82.
+        .. [2] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology:
+               Methods, Techniques, and Applications, CRC Press LLC, Boca
+               Raton, Florida.
+        .. [3] Alan Agresti, An Introduction to Categorical Data Analysis
+               (second edition), Wiley, Hoboken, NJ, USA (2007).
+        """
+        if alternative not in ['two-sided', 'less', 'greater']:
+            raise ValueError("`alternative` must be 'two-sided', 'less' or "
+                             "'greater'.")
+
+        if confidence_level < 0 or confidence_level > 1:
+            raise ValueError('confidence_level must be between 0 and 1')
+
+        if self._kind == 'conditional':
+            ci = self._conditional_odds_ratio_ci(confidence_level, alternative)
+        else:
+            ci = self._sample_odds_ratio_ci(confidence_level, alternative)
+        return ci
+
+    def _conditional_odds_ratio_ci(self, confidence_level=0.95,
+                                   alternative='two-sided'):
+        """
+        Confidence interval for the conditional odds ratio.
+        """
+
+        table = self._table
+        if 0 in table.sum(axis=0) or 0 in table.sum(axis=1):
+            # If both values in a row or column are zero, the p-value is 1,
+            # the odds ratio is NaN and the confidence interval is (0, inf).
+            ci = (0, np.inf)
+        else:
+            ci = _conditional_oddsratio_ci(table,
+                                           confidence_level=confidence_level,
+                                           alternative=alternative)
+        return ConfidenceInterval(low=ci[0], high=ci[1])
+
+    def _sample_odds_ratio_ci(self, confidence_level=0.95,
+                              alternative='two-sided'):
+        """
+        Confidence interval for the sample odds ratio.
+        """
+        if confidence_level < 0 or confidence_level > 1:
+            raise ValueError('confidence_level must be between 0 and 1')
+
+        table = self._table
+        if 0 in table.sum(axis=0) or 0 in table.sum(axis=1):
+            # If both values in a row or column are zero, the p-value is 1,
+            # the odds ratio is NaN and the confidence interval is (0, inf).
+            ci = (0, np.inf)
+        else:
+            ci = _sample_odds_ratio_ci(table,
+                                       confidence_level=confidence_level,
+                                       alternative=alternative)
+        return ConfidenceInterval(low=ci[0], high=ci[1])
+
+
+def odds_ratio(table, *, kind='conditional'):
+    r"""
+    Compute the odds ratio for a 2x2 contingency table.
+
+    Parameters
+    ----------
+    table : array_like of ints
+        A 2x2 contingency table.  Elements must be non-negative integers.
+    kind : str, optional
+        Which kind of odds ratio to compute, either the sample
+        odds ratio (``kind='sample'``) or the conditional odds ratio
+        (``kind='conditional'``).  Default is ``'conditional'``.
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.OddsRatioResult` instance
+        The returned object has two computed attributes:
+
+        statistic : float
+            * If `kind` is ``'sample'``, this is sample (or unconditional)
+              estimate, given by
+              ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``.
+            * If `kind` is ``'conditional'``, this is the conditional
+              maximum likelihood estimate for the odds ratio. It is
+              the noncentrality parameter of Fisher's noncentral
+              hypergeometric distribution with the same hypergeometric
+              parameters as `table` and whose mean is ``table[0, 0]``.
+
+        The object has the method `confidence_interval` that computes
+        the confidence interval of the odds ratio.
+
+    See Also
+    --------
+    scipy.stats.fisher_exact
+    relative_risk
+    :ref:`hypothesis_odds_ratio` : Extended example
+
+    Notes
+    -----
+    The conditional odds ratio was discussed by Fisher (see "Example 1"
+    of [1]_).  Texts that cover the odds ratio include [2]_ and [3]_.
+
+    .. versionadded:: 1.10.0
+
+    References
+    ----------
+    .. [1] R. A. Fisher (1935), The logic of inductive inference,
+           Journal of the Royal Statistical Society, Vol. 98, No. 1,
+           pp. 39-82.
+    .. [2] Breslow NE, Day NE (1980). Statistical methods in cancer research.
+           Volume I - The analysis of case-control studies. IARC Sci Publ.
+           (32):5-338. PMID: 7216345. (See section 4.2.)
+    .. [3] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology:
+           Methods, Techniques, and Applications, CRC Press LLC, Boca
+           Raton, Florida.
+
+    Examples
+    --------
+    In epidemiology, individuals are classified as "exposed" or
+    "unexposed" to some factor or treatment. If the occurrence of some
+    illness is under study, those who have the illness are often
+    classified as "cases", and those without it are "noncases".  The
+    counts of the occurrences of these classes gives a contingency
+    table::
+
+                    exposed    unexposed
+        cases          a           b
+        noncases       c           d
+
+    The sample odds ratio may be written ``(a/c) / (b/d)``.  ``a/c`` can
+    be interpreted as the odds of a case occurring in the exposed group,
+    and ``b/d`` as the odds of a case occurring in the unexposed group.
+    The sample odds ratio is the ratio of these odds.  If the odds ratio
+    is greater than 1, it suggests that there is a positive association
+    between being exposed and being a case.
+
+    Interchanging the rows or columns of the contingency table inverts
+    the odds ratio, so it is important to understand the meaning of labels
+    given to the rows and columns of the table when interpreting the
+    odds ratio.
+
+    Consider a hypothetical example where it is hypothesized that exposure to a
+    certain chemical is associated with increased occurrence of a certain
+    disease. Suppose we have the following table for a collection of 410 people::
+
+                exposed unexposed
+        cases        7       15
+        noncases    58      472
+
+    The question we ask is "Is exposure to the chemical associated with
+    increased risk of the disease?"
+
+    Compute the odds ratio:
+
+    >>> from scipy.stats.contingency import odds_ratio
+    >>> res = odds_ratio([[7, 15], [58, 472]])
+    >>> res.statistic
+    3.7836687705553493
+
+    For this sample, the odds of getting the disease for those who have been
+    exposed to the chemical are almost 3.8 times that of those who have not been
+    exposed.
+
+    We can compute the 95% confidence interval for the odds ratio:
+
+    >>> res.confidence_interval(confidence_level=0.95)
+    ConfidenceInterval(low=1.2514829132266785, high=10.363493716701269)
+
+    The 95% confidence interval for the conditional odds ratio is approximately
+    (1.25, 10.4).
+
+    For a more detailed example, see :ref:`hypothesis_odds_ratio`.
+    """
+    if kind not in ['conditional', 'sample']:
+        raise ValueError("`kind` must be 'conditional' or 'sample'.")
+
+    c = np.asarray(table)
+
+    if c.shape != (2, 2):
+        raise ValueError(f"Invalid shape {c.shape}. The input `table` must be "
+                         "of shape (2, 2).")
+
+    if not np.issubdtype(c.dtype, np.integer):
+        raise ValueError("`table` must be an array of integers, but got "
+                         f"type {c.dtype}")
+    c = c.astype(np.int64)
+
+    if np.any(c < 0):
+        raise ValueError("All values in `table` must be nonnegative.")
+
+    if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
+        # If both values in a row or column are zero, the p-value is NaN and
+        # the odds ratio is NaN.
+        result = OddsRatioResult(_table=c, _kind=kind, statistic=np.nan)
+        return result
+
+    if kind == 'sample':
+        oddsratio = _sample_odds_ratio(c)
+    else:  # kind is 'conditional'
+        oddsratio = _conditional_oddsratio(c)
+
+    result = OddsRatioResult(_table=c, _kind=kind, statistic=oddsratio)
+    return result
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_page_trend_test.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_page_trend_test.py
new file mode 100644
index 0000000000000000000000000000000000000000..87a4d0d17c07ce609cc575fc7dc61af75d2b9c51
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_page_trend_test.py
@@ -0,0 +1,479 @@
+from itertools import permutations
+import numpy as np
+import math
+from ._continuous_distns import norm
+import scipy.stats
+from dataclasses import dataclass
+
+
+@dataclass
+class PageTrendTestResult:
+    statistic: float
+    pvalue: float
+    method: str
+
+
+def page_trend_test(data, ranked=False, predicted_ranks=None, method='auto'):
+    r"""
+    Perform Page's Test, a measure of trend in observations between treatments.
+
+    Page's Test (also known as Page's :math:`L` test) is useful when:
+
+    * there are :math:`n \geq 3` treatments,
+    * :math:`m \geq 2` subjects are observed for each treatment, and
+    * the observations are hypothesized to have a particular order.
+
+    Specifically, the test considers the null hypothesis that
+
+    .. math::
+
+        m_1 = m_2 = m_3 \cdots = m_n,
+
+    where :math:`m_j` is the mean of the observed quantity under treatment
+    :math:`j`, against the alternative hypothesis that
+
+    .. math::
+
+        m_1 \leq m_2 \leq m_3 \leq \cdots \leq m_n,
+
+    where at least one inequality is strict.
+
+    As noted by [4]_, Page's :math:`L` test has greater statistical power than
+    the Friedman test against the alternative that there is a difference in
+    trend, as Friedman's test only considers a difference in the means of the
+    observations without considering their order. Whereas Spearman :math:`\rho`
+    considers the correlation between the ranked observations of two variables
+    (e.g. the airspeed velocity of a swallow vs. the weight of the coconut it
+    carries), Page's :math:`L` is concerned with a trend in an observation
+    (e.g. the airspeed velocity of a swallow) across several distinct
+    treatments (e.g. carrying each of five coconuts of different weight) even
+    as the observation is repeated with multiple subjects (e.g. one European
+    swallow and one African swallow).
+
+    Parameters
+    ----------
+    data : array-like
+        A :math:`m \times n` array; the element in row :math:`i` and
+        column :math:`j` is the observation corresponding with subject
+        :math:`i` and treatment :math:`j`. By default, the columns are
+        assumed to be arranged in order of increasing predicted mean.
+
+    ranked : boolean, optional
+        By default, `data` is assumed to be observations rather than ranks;
+        it will be ranked with `scipy.stats.rankdata` along ``axis=1``. If
+        `data` is provided in the form of ranks, pass argument ``True``.
+
+    predicted_ranks : array-like, optional
+        The predicted ranks of the column means. If not specified,
+        the columns are assumed to be arranged in order of increasing
+        predicted mean, so the default `predicted_ranks` are
+        :math:`[1, 2, \dots, n-1, n]`.
+
+    method : {'auto', 'asymptotic', 'exact'}, optional
+        Selects the method used to calculate the *p*-value. The following
+        options are available.
+
+        * 'auto': selects between 'exact' and 'asymptotic' to
+          achieve reasonably accurate results in reasonable time (default)
+        * 'asymptotic': compares the standardized test statistic against
+          the normal distribution
+        * 'exact': computes the exact *p*-value by comparing the observed
+          :math:`L` statistic against those realized by all possible
+          permutations of ranks (under the null hypothesis that each
+          permutation is equally likely)
+
+    Returns
+    -------
+    res : PageTrendTestResult
+        An object containing attributes:
+
+        statistic : float
+            Page's :math:`L` test statistic.
+        pvalue : float
+            The associated *p*-value
+        method : {'asymptotic', 'exact'}
+            The method used to compute the *p*-value
+
+    See Also
+    --------
+    rankdata, friedmanchisquare, spearmanr
+
+    Notes
+    -----
+    As noted in [1]_, "the :math:`n` 'treatments' could just as well represent
+    :math:`n` objects or events or performances or persons or trials ranked."
+    Similarly, the :math:`m` 'subjects' could equally stand for :math:`m`
+    "groupings by ability or some other control variable, or judges doing
+    the ranking, or random replications of some other sort."
+
+    The procedure for calculating the :math:`L` statistic, adapted from
+    [1]_, is:
+
+    1. "Predetermine with careful logic the appropriate hypotheses
+       concerning the predicted ordering of the experimental results.
+       If no reasonable basis for ordering any treatments is known, the
+       :math:`L` test is not appropriate."
+    2. "As in other experiments, determine at what level of confidence
+       you will reject the null hypothesis that there is no agreement of
+       experimental results with the monotonic hypothesis."
+    3. "Cast the experimental material into a two-way table of :math:`n`
+       columns (treatments, objects ranked, conditions) and :math:`m`
+       rows (subjects, replication groups, levels of control variables)."
+    4. "When experimental observations are recorded, rank them across each
+       row", e.g. ``ranks = scipy.stats.rankdata(data, axis=1)``.
+    5. "Add the ranks in each column", e.g.
+       ``colsums = np.sum(ranks, axis=0)``.
+    6. "Multiply each sum of ranks by the predicted rank for that same
+       column", e.g. ``products = predicted_ranks * colsums``.
+    7. "Sum all such products", e.g. ``L = products.sum()``.
+
+    [1]_ continues by suggesting use of the standardized statistic
+
+    .. math::
+
+        \chi_L^2 = \frac{\left[12L-3mn(n+1)^2\right]^2}{mn^2(n^2-1)(n+1)}
+
+    "which is distributed approximately as chi-square with 1 degree of
+    freedom. The ordinary use of :math:`\chi^2` tables would be
+    equivalent to a two-sided test of agreement. If a one-sided test
+    is desired, *as will almost always be the case*, the probability
+    discovered in the chi-square table should be *halved*."
+
+    However, this standardized statistic does not distinguish between the
+    observed values being well correlated with the predicted ranks and being
+    _anti_-correlated with the predicted ranks. Instead, we follow [2]_
+    and calculate the standardized statistic
+
+    .. math::
+
+        \Lambda = \frac{L - E_0}{\sqrt{V_0}},
+
+    where :math:`E_0 = \frac{1}{4} mn(n+1)^2` and
+    :math:`V_0 = \frac{1}{144} mn^2(n+1)(n^2-1)`, "which is asymptotically
+    normal under the null hypothesis".
+
+    The *p*-value for ``method='exact'`` is generated by comparing the observed
+    value of :math:`L` against the :math:`L` values generated for all
+    :math:`(n!)^m` possible permutations of ranks. The calculation is performed
+    using the recursive method of [5].
+
+    The *p*-values are not adjusted for the possibility of ties. When
+    ties are present, the reported  ``'exact'`` *p*-values may be somewhat
+    larger (i.e. more conservative) than the true *p*-value [2]_. The
+    ``'asymptotic'``` *p*-values, however, tend to be smaller (i.e. less
+    conservative) than the ``'exact'`` *p*-values.
+
+    References
+    ----------
+    .. [1] Ellis Batten Page, "Ordered hypotheses for multiple treatments:
+       a significant test for linear ranks", *Journal of the American
+       Statistical Association* 58(301), p. 216--230, 1963.
+
+    .. [2] Markus Neuhauser, *Nonparametric Statistical Test: A computational
+       approach*, CRC Press, p. 150--152, 2012.
+
+    .. [3] Statext LLC, "Page's L Trend Test - Easy Statistics", *Statext -
+       Statistics Study*, https://www.statext.com/practice/PageTrendTest03.php,
+       Accessed July 12, 2020.
+
+    .. [4] "Page's Trend Test", *Wikipedia*, WikimediaFoundation,
+       https://en.wikipedia.org/wiki/Page%27s_trend_test,
+       Accessed July 12, 2020.
+
+    .. [5] Robert E. Odeh, "The exact distribution of Page's L-statistic in
+       the two-way layout", *Communications in Statistics - Simulation and
+       Computation*,  6(1), p. 49--61, 1977.
+
+    Examples
+    --------
+    We use the example from [3]_: 10 students are asked to rate three
+    teaching methods - tutorial, lecture, and seminar - on a scale of 1-5,
+    with 1 being the lowest and 5 being the highest. We have decided that
+    a confidence level of 99% is required to reject the null hypothesis in
+    favor of our alternative: that the seminar will have the highest ratings
+    and the tutorial will have the lowest. Initially, the data have been
+    tabulated with each row representing an individual student's ratings of
+    the three methods in the following order: tutorial, lecture, seminar.
+
+    >>> table = [[3, 4, 3],
+    ...          [2, 2, 4],
+    ...          [3, 3, 5],
+    ...          [1, 3, 2],
+    ...          [2, 3, 2],
+    ...          [2, 4, 5],
+    ...          [1, 2, 4],
+    ...          [3, 4, 4],
+    ...          [2, 4, 5],
+    ...          [1, 3, 4]]
+
+    Because the tutorial is hypothesized to have the lowest ratings, the
+    column corresponding with tutorial rankings should be first; the seminar
+    is hypothesized to have the highest ratings, so its column should be last.
+    Since the columns are already arranged in this order of increasing
+    predicted mean, we can pass the table directly into `page_trend_test`.
+
+    >>> from scipy.stats import page_trend_test
+    >>> res = page_trend_test(table)
+    >>> res
+    PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
+                        method='exact')
+
+    This *p*-value indicates that there is a 0.1819% chance that
+    the :math:`L` statistic would reach such an extreme value under the null
+    hypothesis. Because 0.1819% is less than 1%, we have evidence to reject
+    the null hypothesis in favor of our alternative at a 99% confidence level.
+
+    The value of the :math:`L` statistic is 133.5. To check this manually,
+    we rank the data such that high scores correspond with high ranks, settling
+    ties with an average rank:
+
+    >>> from scipy.stats import rankdata
+    >>> ranks = rankdata(table, axis=1)
+    >>> ranks
+    array([[1.5, 3. , 1.5],
+           [1.5, 1.5, 3. ],
+           [1.5, 1.5, 3. ],
+           [1. , 3. , 2. ],
+           [1.5, 3. , 1.5],
+           [1. , 2. , 3. ],
+           [1. , 2. , 3. ],
+           [1. , 2.5, 2.5],
+           [1. , 2. , 3. ],
+           [1. , 2. , 3. ]])
+
+    We add the ranks within each column, multiply the sums by the
+    predicted ranks, and sum the products.
+
+    >>> import numpy as np
+    >>> m, n = ranks.shape
+    >>> predicted_ranks = np.arange(1, n+1)
+    >>> L = (predicted_ranks * np.sum(ranks, axis=0)).sum()
+    >>> res.statistic == L
+    True
+
+    As presented in [3]_, the asymptotic approximation of the *p*-value is the
+    survival function of the normal distribution evaluated at the standardized
+    test statistic:
+
+    >>> from scipy.stats import norm
+    >>> E0 = (m*n*(n+1)**2)/4
+    >>> V0 = (m*n**2*(n+1)*(n**2-1))/144
+    >>> Lambda = (L-E0)/np.sqrt(V0)
+    >>> p = norm.sf(Lambda)
+    >>> p
+    0.0012693433690751756
+
+    This does not precisely match the *p*-value reported by `page_trend_test`
+    above. The asymptotic distribution is not very accurate, nor conservative,
+    for :math:`m \leq 12` and :math:`n \leq 8`, so `page_trend_test` chose to
+    use ``method='exact'`` based on the dimensions of the table and the
+    recommendations in Page's original paper [1]_. To override
+    `page_trend_test`'s choice, provide the `method` argument.
+
+    >>> res = page_trend_test(table, method="asymptotic")
+    >>> res
+    PageTrendTestResult(statistic=133.5, pvalue=0.0012693433690751756,
+                        method='asymptotic')
+
+    If the data are already ranked, we can pass in the ``ranks`` instead of
+    the ``table`` to save computation time.
+
+    >>> res = page_trend_test(ranks,             # ranks of data
+    ...                       ranked=True,       # data is already ranked
+    ...                       )
+    >>> res
+    PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
+                        method='exact')
+
+    Suppose the raw data had been tabulated in an order different from the
+    order of predicted means, say lecture, seminar, tutorial.
+
+    >>> table = np.asarray(table)[:, [1, 2, 0]]
+
+    Since the arrangement of this table is not consistent with the assumed
+    ordering, we can either rearrange the table or provide the
+    `predicted_ranks`. Remembering that the lecture is predicted
+    to have the middle rank, the seminar the highest, and tutorial the lowest,
+    we pass:
+
+    >>> res = page_trend_test(table,             # data as originally tabulated
+    ...                       predicted_ranks=[2, 3, 1],  # our predicted order
+    ...                       )
+    >>> res
+    PageTrendTestResult(statistic=133.5, pvalue=0.0018191161948127822,
+                        method='exact')
+
+    """
+
+    # Possible values of the method parameter and the corresponding function
+    # used to evaluate the p value
+    methods = {"asymptotic": _l_p_asymptotic,
+               "exact": _l_p_exact,
+               "auto": None}
+    if method not in methods:
+        raise ValueError(f"`method` must be in {set(methods)}")
+
+    ranks = np.asarray(data)
+    if ranks.ndim != 2:  # TODO: relax this to accept 3d arrays?
+        raise ValueError("`data` must be a 2d array.")
+
+    m, n = ranks.shape
+    if m < 2 or n < 3:
+        raise ValueError("Page's L is only appropriate for data with two "
+                         "or more rows and three or more columns.")
+
+    if np.any(np.isnan(data)):
+        raise ValueError("`data` contains NaNs, which cannot be ranked "
+                         "meaningfully")
+
+    # ensure NumPy array and rank the data if it's not already ranked
+    if ranked:
+        # Only a basic check on whether data is ranked. Checking that the data
+        # is properly ranked could take as much time as ranking it.
+        if not (ranks.min() >= 1 and ranks.max() <= ranks.shape[1]):
+            raise ValueError("`data` is not properly ranked. Rank the data or "
+                             "pass `ranked=False`.")
+    else:
+        ranks = scipy.stats.rankdata(data, axis=-1)
+
+    # generate predicted ranks if not provided, ensure valid NumPy array
+    if predicted_ranks is None:
+        predicted_ranks = np.arange(1, n+1)
+    else:
+        predicted_ranks = np.asarray(predicted_ranks)
+        if (predicted_ranks.ndim < 1 or
+                (set(predicted_ranks) != set(range(1, n+1)) or
+                 len(predicted_ranks) != n)):
+            raise ValueError(f"`predicted_ranks` must include each integer "
+                             f"from 1 to {n} (the number of columns in "
+                             f"`data`) exactly once.")
+
+    if not isinstance(ranked, bool):
+        raise TypeError("`ranked` must be boolean.")
+
+    # Calculate the L statistic
+    L = _l_vectorized(ranks, predicted_ranks)
+
+    # Calculate the p-value
+    if method == "auto":
+        method = _choose_method(ranks)
+    p_fun = methods[method]  # get the function corresponding with the method
+    p = p_fun(L, m, n)
+
+    page_result = PageTrendTestResult(statistic=L, pvalue=p, method=method)
+    return page_result
+
+
+def _choose_method(ranks):
+    '''Choose method for computing p-value automatically'''
+    m, n = ranks.shape
+    if n > 8 or (m > 12 and n > 3) or m > 20:  # as in [1], [4]
+        method = "asymptotic"
+    else:
+        method = "exact"
+    return method
+
+
+def _l_vectorized(ranks, predicted_ranks):
+    '''Calculate's Page's L statistic for each page of a 3d array'''
+    colsums = ranks.sum(axis=-2, keepdims=True)
+    products = predicted_ranks * colsums
+    Ls = products.sum(axis=-1)
+    Ls = Ls[0] if Ls.size == 1 else Ls.ravel()
+    return Ls
+
+
+def _l_p_asymptotic(L, m, n):
+    '''Calculate the p-value of Page's L from the asymptotic distribution'''
+    # Using [1] as a reference, the asymptotic p-value would be calculated as:
+    # chi_L = (12*L - 3*m*n*(n+1)**2)**2/(m*n**2*(n**2-1)*(n+1))
+    # p = chi2.sf(chi_L, df=1, loc=0, scale=1)/2
+    # but this is insensitive to the direction of the hypothesized ranking
+
+    # See [2] page 151
+    E0 = (m*n*(n+1)**2)/4
+    V0 = (m*n**2*(n+1)*(n**2-1))/144
+    Lambda = (L-E0)/np.sqrt(V0)
+    # This is a one-sided "greater" test - calculate the probability that the
+    # L statistic under H0 would be greater than the observed L statistic
+    p = norm.sf(Lambda)
+    return p
+
+
+def _l_p_exact(L, m, n):
+    '''Calculate the p-value of Page's L exactly'''
+    # [1] uses m, n; [5] uses n, k.
+    # Switch convention here because exact calculation code references [5].
+    L, n, k = int(L), int(m), int(n)
+    _pagel_state.set_k(k)
+    return _pagel_state.sf(L, n)
+
+
+class _PageL:
+    '''Maintains state between `page_trend_test` executions'''
+
+    def __init__(self):
+        '''Lightweight initialization'''
+        self.all_pmfs = {}
+
+    def set_k(self, k):
+        '''Calculate lower and upper limits of L for single row'''
+        self.k = k
+        # See [5] top of page 52
+        self.a, self.b = (k*(k+1)*(k+2))//6, (k*(k+1)*(2*k+1))//6
+
+    def sf(self, l, n):
+        '''Survival function of Page's L statistic'''
+        ps = [self.pmf(l, n) for l in range(l, n*self.b + 1)]
+        return np.sum(ps)
+
+    def p_l_k_1(self):
+        '''Relative frequency of each L value over all possible single rows'''
+
+        # See [5] Equation (6)
+        ranks = range(1, self.k+1)
+        # generate all possible rows of length k
+        rank_perms = np.array(list(permutations(ranks)))
+        # compute Page's L for all possible rows
+        Ls = (ranks*rank_perms).sum(axis=1)
+        # count occurrences of each L value
+        counts = np.histogram(Ls, np.arange(self.a-0.5, self.b+1.5))[0]
+        # factorial(k) is number of possible permutations
+        return counts/math.factorial(self.k)
+
+    def pmf(self, l, n):
+        '''Recursive function to evaluate p(l, k, n); see [5] Equation 1'''
+
+        if n not in self.all_pmfs:
+            self.all_pmfs[n] = {}
+        if self.k not in self.all_pmfs[n]:
+            self.all_pmfs[n][self.k] = {}
+
+        # Cache results to avoid repeating calculation. Initially this was
+        # written with lru_cache, but this seems faster? Also, we could add
+        # an option to save this for future lookup.
+        if l in self.all_pmfs[n][self.k]:
+            return self.all_pmfs[n][self.k][l]
+
+        if n == 1:
+            ps = self.p_l_k_1()  # [5] Equation 6
+            ls = range(self.a, self.b+1)
+            # not fast, but we'll only be here once
+            self.all_pmfs[n][self.k] = {l: p for l, p in zip(ls, ps)}
+            return self.all_pmfs[n][self.k][l]
+
+        p = 0
+        low = max(l-(n-1)*self.b, self.a)  # [5] Equation 2
+        high = min(l-(n-1)*self.a, self.b)
+
+        # [5] Equation 1
+        for t in range(low, high+1):
+            p1 = self.pmf(l-t, n-1)
+            p2 = self.pmf(t, 1)
+            p += p1*p2
+        self.all_pmfs[n][self.k][l] = p
+        return p
+
+
+# Maintain state for faster repeat calls to page_trend_test w/ method='exact'
+_pagel_state = _PageL()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_probability_distribution.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_probability_distribution.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b092694240e88c226128fae6c0cd42792540058
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_probability_distribution.py
@@ -0,0 +1,1742 @@
+# Temporary file separated from _distribution_infrastructure.py
+# to simplify the diff during PR review.
+from abc import ABC, abstractmethod
+
+class _ProbabilityDistribution(ABC):
+    @abstractmethod
+    def support(self):
+        r"""Support of the random variable
+
+        The support of a random variable is set of all possible outcomes;
+        i.e., the subset of the domain of argument :math:`x` for which
+        the probability density function :math:`f(x)` is nonzero.
+
+        This function returns lower and upper bounds of the support.
+
+        Returns
+        -------
+        out : tuple of Array
+            The lower and upper bounds of the support.
+
+        See Also
+        --------
+        pdf
+
+        References
+        ----------
+        .. [1] Support (mathematics), *Wikipedia*,
+               https://en.wikipedia.org/wiki/Support_(mathematics)
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support ``(l, r)``.
+        The following table summarizes the value returned by methods
+        of ``ContinuousDistribution`` for arguments outside the support.
+
+        +----------------+---------------------+---------------------+
+        | Method         | Value for ``x < l`` | Value for ``x > r`` |
+        +================+=====================+=====================+
+        | ``pdf(x)``     | 0                   | 0                   |
+        +----------------+---------------------+---------------------+
+        | ``logpdf(x)``  | -inf                | -inf                |
+        +----------------+---------------------+---------------------+
+        | ``cdf(x)``     | 0                   | 1                   |
+        +----------------+---------------------+---------------------+
+        | ``logcdf(x)``  | -inf                | 0                   |
+        +----------------+---------------------+---------------------+
+        | ``ccdf(x)``    | 1                   | 0                   |
+        +----------------+---------------------+---------------------+
+        | ``logccdf(x)`` | 0                   | -inf                |
+        +----------------+---------------------+---------------------+
+
+        For the ``cdf`` and related methods, the inequality need not be
+        strict; i.e. the tabulated value is returned when the method is
+        evaluated *at* the corresponding boundary.
+
+        The following table summarizes the value returned by the inverse
+        methods of ``ContinuousDistribution`` for arguments at the boundaries
+        of the domain ``0`` to ``1``.
+
+        +-------------+-----------+-----------+
+        | Method      | ``x = 0`` | ``x = 1`` |
+        +=============+===========+===========+
+        | ``icdf(x)`` | ``l``     | ``r``     |
+        +-------------+-----------+-----------+
+        | ``icdf(x)`` | ``r``     | ``l``     |
+        +-------------+-----------+-----------+
+
+        For the inverse log-functions, the same values are returned for
+        for ``x = log(0)`` and ``x = log(1)``. All inverse functions return
+        ``nan`` when evaluated at an argument outside the domain ``0`` to ``1``.
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Retrieve the support of the distribution:
+
+        >>> X.support()
+        (-0.5, 0.5)
+
+        For a distribution with infinite support,
+
+        >>> X = stats.Normal()
+        >>> X.support()
+        (-inf, inf)
+
+        Due to underflow, the numerical value returned by the PDF may be zero
+        even for arguments within the support, even if the true value is
+        nonzero. In such cases, the log-PDF may be useful.
+
+        >>> X.pdf([-100., 100.])
+        array([0., 0.])
+        >>> X.logpdf([-100., 100.])
+        array([-5000.91893853, -5000.91893853])
+
+        Use cases for the log-CDF and related methods are analogous.
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def sample(self, shape, *, method, rng):
+        r"""Random sample from the distribution.
+
+        Parameters
+        ----------
+        shape : tuple of ints, default: ()
+            The shape of the sample to draw. If the parameters of the distribution
+            underlying the random variable are arrays of shape ``param_shape``,
+            the output array will be of shape ``shape + param_shape``.
+        method : {None, 'formula', 'inverse_transform'}
+            The strategy used to produce the sample. By default (``None``),
+            the infrastructure chooses between the following options,
+            listed in order of precedence.
+
+            - ``'formula'``: an implementation specific to the distribution
+            - ``'inverse_transform'``: generate a uniformly distributed sample and
+              return the inverse CDF at these arguments.
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a `NotImplementedError``
+            will be raised.
+        rng : `numpy.random.Generator` or `scipy.stats.QMCEngine`, optional
+            Pseudo- or quasi-random number generator state. When `rng` is None,
+            a new `numpy.random.Generator` is created using entropy from the
+            operating system. Types other than `numpy.random.Generator` and
+            `scipy.stats.QMCEngine` are passed to `numpy.random.default_rng`
+            to instantiate a ``Generator``.
+
+            If `rng` is an instance of `scipy.stats.QMCEngine` configured to use
+            scrambling and `shape` is not empty, then each slice along the zeroth
+            axis of the result is a "quasi-independent", low-discrepancy sequence;
+            that is, they are distinct sequences that can be treated as statistically
+            independent for most practical purposes. Separate calls to `sample`
+            produce new quasi-independent, low-discrepancy sequences.
+
+        References
+        ----------
+        .. [1] Sampling (statistics), *Wikipedia*,
+               https://en.wikipedia.org/wiki/Sampling_(statistics)
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=0., b=1.)
+
+        Generate a pseudorandom sample:
+
+        >>> x = X.sample((1000, 1))
+        >>> octiles = (np.arange(8) + 1) / 8
+        >>> np.count_nonzero(x <= octiles, axis=0)
+        array([ 148,  263,  387,  516,  636,  751,  865, 1000])  # may vary
+
+        >>> X = stats.Uniform(a=np.zeros((3, 1)), b=np.ones(2))
+        >>> X.a.shape,
+        (3, 2)
+        >>> x = X.sample(shape=(5, 4))
+        >>> x.shape
+        (5, 4, 3, 2)
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def moment(self, order, kind, *, method):
+        r"""Raw, central, or standard moment of positive integer order.
+
+        In terms of probability density function :math:`f(x)` and support
+        :math:`\chi`, the "raw" moment (about the origin) of order :math:`n` of
+        a random variable :math:`X` is:
+
+        .. math::
+
+            \mu'_n(X) = \int_{\chi} x^n f(x) dx
+
+        The "central" moment is the raw moment taken about the mean,
+        :math:`\mu = \mu'_1`:
+
+        .. math::
+
+            \mu_n(X) = \int_{\chi} (x - \mu) ^n f(x) dx
+
+        The "standardized" moment is the central moment normalized by the
+        :math:`n^\text{th}` power of the standard deviation
+        :math:`\sigma = \sqrt{\mu_2}` to produce a scale invariant quantity:
+
+        .. math::
+
+            \tilde{\mu}_n(X) = \frac{\mu_n(X)}
+                                    {\sigma^n}
+
+        Parameters
+        ----------
+        order : int
+            The integer order of the moment; i.e. :math:`n` in the formulae above.
+        kind : {'raw', 'central', 'standardized'}
+            Whether to return the raw (default), central, or standardized moment
+            defined above.
+        method : {None, 'formula', 'general', 'transform', 'normalize', 'quadrature', 'cache'}
+            The strategy used to evaluate the moment. By default (``None``),
+            the infrastructure chooses between the following options,
+            listed in order of precedence.
+
+            - ``'cache'``: use the value of the moment most recently calculated
+              via another method
+            - ``'formula'``: use a formula for the moment itself
+            - ``'general'``: use a general result that is true for all distributions
+              with finite moments; for instance, the zeroth raw moment is
+              identically 1
+            - ``'transform'``: transform a raw moment to a central moment or
+              vice versa (see Notes)
+            - ``'normalize'``: normalize a central moment to get a standardized
+              or vice versa
+            - ``'quadrature'``: numerically integrate according to the definition
+
+            Not all `method` options are available for all orders, kinds, and
+            distributions. If the selected `method` is not available, a
+            ``NotImplementedError`` will be raised.
+
+        Returns
+        -------
+        out : array
+            The moment of the random variable of the specified order and kind.
+
+        See Also
+        --------
+        pdf
+        mean
+        variance
+        standard_deviation
+        skewness
+        kurtosis
+
+        Notes
+        -----
+        Not all distributions have finite moments of all orders; moments of some
+        orders may be undefined or infinite. If a formula for the moment is not
+        specifically implemented for the chosen distribution, SciPy will attempt
+        to compute the moment via a generic method, which may yield a finite
+        result where none exists. This is not a critical bug, but an opportunity
+        for an enhancement.
+
+        The definition of a raw moment in the summary is specific to the raw moment
+        about the origin. The raw moment about any point :math:`a` is:
+
+        .. math::
+
+            E[(X-a)^n] = \int_{\chi} (x-a)^n f(x) dx
+
+        In this notation, a raw moment about the origin is :math:`\mu'_n = E[x^n]`,
+        and a central moment is :math:`\mu_n = E[(x-\mu)^n]`, where :math:`\mu`
+        is the first raw moment; i.e. the mean.
+
+        The ``'transform'`` method takes advantage of the following relationships
+        between moments taken about different points :math:`a` and :math:`b`.
+
+        .. math::
+
+            E[(X-b)^n] =  \sum_{i=0}^n E[(X-a)^i] {n \choose i} (a - b)^{n-i}
+
+        For instance, to transform the raw moment to the central moment, we let
+        :math:`b = \mu` and :math:`a = 0`.
+
+        The distribution infrastructure provides flexibility for distribution
+        authors to implement separate formulas for raw moments, central moments,
+        and standardized moments of any order. By default, the moment of the
+        desired order and kind is evaluated from the formula if such a formula
+        is available; if not, the infrastructure uses any formulas that are
+        available rather than resorting directly to numerical integration.
+        For instance, if formulas for the first three raw moments are
+        available and the third standardized moments is desired, the
+        infrastructure will evaluate the raw moments and perform the transforms
+        and standardization required. The decision tree is somewhat complex,
+        but the strategy for obtaining a moment of a given order and kind
+        (possibly as an intermediate step due to the recursive nature of the
+        transform formula above) roughly follows this order of priority:
+
+        #. Use cache (if order of same moment and kind has been calculated)
+        #. Use formula (if available)
+        #. Transform between raw and central moment and/or normalize to convert
+           between central and standardized moments (if efficient)
+        #. Use a generic result true for most distributions (if available)
+        #. Use quadrature
+
+        References
+        ----------
+        .. [1] Moment, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Moment_(mathematics)
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the first raw moment:
+
+        >>> X.moment(order=1, kind='raw')
+        1.0
+        >>> X.moment(order=1, kind='raw') == X.mean() == X.mu
+        True
+
+        Evaluate the second central moment:
+
+        >>> X.moment(order=2, kind='central')
+        4.0
+        >>> X.moment(order=2, kind='central') == X.variance() == X.sigma**2
+        True
+
+        Evaluate the fourth standardized moment:
+
+        >>> X.moment(order=4, kind='standardized')
+        3.0
+        >>> X.moment(order=4, kind='standardized') == X.kurtosis(convention='non-excess')
+        True
+
+        """  # noqa:E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def mean(self, *, method):
+        r"""Mean (raw first moment about the origin)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'transform', 'quadrature', 'cache'}
+            Method used to calculate the raw first moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+
+        See Also
+        --------
+        moment
+        median
+        mode
+
+        References
+        ----------
+        .. [1] Mean, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Mean#Mean_of_a_probability_distribution
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the variance:
+
+        >>> X.mean()
+        1.0
+        >>> X.mean() == X.moment(order=1, kind='raw') == X.mu
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def median(self, *, method):
+        r"""Median (50th percentil)
+
+        If a continuous random variable :math:`X` has probability :math:`0.5` of
+        taking on a value less than :math:`m`, then :math:`m` is the median.
+        That is, the median is the value :math:`m` for which:
+
+        .. math::
+
+            P(X ≤ m) = 0.5 = P(X ≥ m)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'icdf'}
+            The strategy used to evaluate the median.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the median
+            - ``'icdf'``: evaluate the inverse CDF of 0.5
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The median
+
+        See Also
+        --------
+        mean
+        mode
+        icdf
+
+        References
+        ----------
+        .. [1] Median, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Median#Probability_distributions
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=0., b=10.)
+
+        Compute the median:
+
+        >>> X.median()
+        np.float64(5.0)
+        >>> X.median() == X.icdf(0.5) == X.iccdf(0.5)
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def mode(self, *, method):
+        r"""Mode (most likely value)
+
+        Informally, the mode is a value that a random variable has the highest
+        probability (density) of assuming. That is, the mode is the element of
+        the support :math:`\chi` that maximizes the probability density
+        function :math:`f(x)`:
+
+        .. math::
+
+            \text{mode} = \arg\max_{x \in \chi} f(x)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'optimization'}
+            The strategy used to evaluate the mode.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the median
+            - ``'optimization'``: numerically maximize the PDF
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The mode
+
+        See Also
+        --------
+        mean
+        median
+        pdf
+
+        Notes
+        -----
+        For some distributions
+
+        #. the mode is not unique (e.g. the uniform distribution);
+        #. the PDF has one or more singularities, and it is debateable whether
+           a singularity is considered to be in the domain and called the mode
+           (e.g. the gamma distribution with shape parameter less than 1); and/or
+        #. the probability density function may have one or more local maxima
+           that are not a global maximum (e.g. mixture distributions).
+
+        In such cases, `mode` will
+
+        #. return a single value,
+        #. consider the mode to occur at a singularity, and/or
+        #. return a local maximum which may or may not be a global maximum.
+
+        If a formula for the mode is not specifically implemented for the
+        chosen distribution, SciPy will attempt to compute the mode
+        numerically, which may not meet the user's preferred definition of a
+        mode. In such cases, the user is encouraged to subclass the
+        distribution and override ``mode``.
+
+        References
+        ----------
+        .. [1] Mode (statistics), *Wikipedia*,
+               https://en.wikipedia.org/wiki/Mode_(statistics)
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the mode:
+
+        >>> X.mode()
+        1.0
+
+        If the mode is not uniquely defined, ``mode`` nonetheless returns a
+        single value.
+
+        >>> X = stats.Uniform(a=0., b=1.)
+        >>> X.mode()
+        0.5
+
+        If this choice does not satisfy your requirements, subclass the
+        distribution and override ``mode``:
+
+        >>> class BetterUniform(stats.Uniform):
+        ...     def mode(self):
+        ...         return self.b
+        >>> X = BetterUniform(a=0., b=1.)
+        >>> X.mode()
+        1.0
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def variance(self, *, method):
+        r"""Variance (central second moment)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'transform', 'normalize', 'quadrature', 'cache'}
+            Method used to calculate the central second moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+
+        See Also
+        --------
+        moment
+        standard_deviation
+        mean
+
+        References
+        ----------
+        .. [1] Variance, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Variance#Absolutely_continuous_random_variable
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the variance:
+
+        >>> X.variance()
+        4.0
+        >>> X.variance() == X.moment(order=2, kind='central') == X.sigma**2
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def standard_deviation(self, *, method):
+        r"""Standard deviation (square root of the second central moment)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'transform', 'normalize', 'quadrature', 'cache'}
+            Method used to calculate the central second moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+
+        See Also
+        --------
+        variance
+        mean
+        moment
+
+        References
+        ----------
+        .. [1] Standard deviation, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Standard_deviation#Definition_of_population_values
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the standard deviation:
+
+        >>> X.standard_deviation()
+        2.0
+        >>> X.standard_deviation() == X.moment(order=2, kind='central')**0.5 == X.sigma
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def skewness(self, *, method):
+        r"""Skewness (standardized third moment)
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'general', 'transform', 'normalize', 'cache'}
+            Method used to calculate the standardized third moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+
+        See Also
+        --------
+        moment
+        mean
+        variance
+
+        References
+        ----------
+        .. [1] Skewness, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Skewness
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the skewness:
+
+        >>> X.skewness()
+        0.0
+        >>> X.skewness() == X.moment(order=3, kind='standardized')
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def kurtosis(self, *, method):
+        r"""Kurtosis (standardized fourth moment)
+
+        By default, this is the standardized fourth moment, also known as the
+        "non-excess" or "Pearson" kurtosis (e.g. the kurtosis of the normal
+        distribution is 3). The "excess" or "Fisher" kurtosis (the standardized
+        fourth moment minus 3) is available via the `convention` parameter.
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'general', 'transform', 'normalize', 'cache'}
+            Method used to calculate the standardized fourth moment. Not
+            all methods are available for all distributions. See
+            `moment` for details.
+        convention : {'non-excess', 'excess'}
+            Two distinct conventions are available:
+
+            - ``'non-excess'``: the standardized fourth moment (Pearson's kurtosis)
+            - ``'excess'``: the standardized fourth moment minus 3 (Fisher's kurtosis)
+
+            The default is ``'non-excess'``.
+
+        See Also
+        --------
+        moment
+        mean
+        variance
+
+        References
+        ----------
+        .. [1] Kurtosis, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Kurtosis
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Normal(mu=1., sigma=2.)
+
+        Evaluate the kurtosis:
+
+        >>> X.kurtosis()
+        3.0
+        >>> (X.kurtosis()
+        ...  == X.kurtosis(convention='excess') + 3.
+        ...  == X.moment(order=4, kind='standardized'))
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def pdf(self, x, /, *, method):
+        r"""Probability density function
+
+        The probability density function ("PDF"), denoted :math:`f(x)`, is the
+        probability *per unit length* that the random variable will assume the
+        value :math:`x`. Mathematically, it can be defined as the derivative
+        of the cumulative distribution function :math:`F(x)`:
+
+        .. math::
+
+            f(x) = \frac{d}{dx} F(x)
+
+        `pdf` accepts `x` for :math:`x`.
+
+        Parameters
+        ----------
+        x : array_like
+            The argument of the PDF.
+        method : {None, 'formula', 'logexp'}
+            The strategy used to evaluate the PDF. By default (``None``), the
+            infrastructure chooses between the following options, listed in
+            order of precedence.
+
+            - ``'formula'``: use a formula for the PDF itself
+            - ``'logexp'``: evaluate the log-PDF and exponentiate
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The PDF evaluated at the argument `x`.
+
+        See Also
+        --------
+        cdf
+        logpdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        By definition of the support, the PDF evaluates to its minimum value
+        of :math:`0` outside the support; i.e. for :math:`x < l` or
+        :math:`x > r`. The maximum of the PDF may be less than or greater than
+        :math:`1`; since the valus is a probability *density*, only its integral
+        over the support must equal :math:`1`.
+
+        References
+        ----------
+        .. [1] Probability density function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Probability_density_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-1., b=1.)
+
+        Evaluate the PDF at the desired argument:
+
+        >>> X.pdf(0.25)
+        0.5
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def logpdf(self, x, /, *, method):
+        r"""Log of the probability density function
+
+        The probability density function ("PDF"), denoted :math:`f(x)`, is the
+        probability *per unit length* that the random variable will assume the
+        value :math:`x`. Mathematically, it can be defined as the derivative
+        of the cumulative distribution function :math:`F(x)`:
+
+        .. math::
+
+            f(x) = \frac{d}{dx} F(x)
+
+        `logpdf` computes the logarithm of the probability density function
+        ("log-PDF"), :math:`\log(f(x))`, but it may be numerically favorable
+        compared to the naive implementation (computing :math:`f(x)` and
+        taking the logarithm).
+
+        `logpdf` accepts `x` for :math:`x`.
+
+        Parameters
+        ----------
+        x : array_like
+            The argument of the log-PDF.
+        method : {None, 'formula', 'logexp'}
+            The strategy used to evaluate the log-PDF. By default (``None``), the
+            infrastructure chooses between the following options, listed in order
+            of precedence.
+
+            - ``'formula'``: use a formula for the log-PDF itself
+            - ``'logexp'``: evaluate the PDF and takes its logarithm
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The log-PDF evaluated at the argument `x`.
+
+        See Also
+        --------
+        pdf
+        logcdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        By definition of the support, the log-PDF evaluates to its minimum value
+        of :math:`-\infty` (i.e. :math:`\log(0)`) outside the support; i.e. for
+        :math:`x < l` or :math:`x > r`. The maximum of the log-PDF may be less
+        than or greater than :math:`\log(1) = 0` because the maximum of the PDF
+        can be any positive real.
+
+        For distributions with infinite support, it is common for `pdf` to return
+        a value of ``0`` when the argument is theoretically within the support;
+        this can occur because the true value of the PDF is too small to be
+        represented by the chosen dtype. The log-PDF, however, will often be finite
+        (not ``-inf``) over a much larger domain. Consequently, it may be preferred
+        to work with the logarithms of probabilities and probability densities to
+        avoid underflow.
+
+        References
+        ----------
+        .. [1] Probability density function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Probability_density_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-1.0, b=1.0)
+
+        Evaluate the log-PDF at the desired argument:
+
+        >>> X.logpdf(0.5)
+        -0.6931471805599453
+        >>> np.allclose(X.logpdf(0.5), np.log(X.pdf(0.5)))
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def cdf(self, x, y, /, *, method):
+        r"""Cumulative distribution function
+
+        The cumulative distribution function ("CDF"), denoted :math:`F(x)`, is
+        the probability the random variable :math:`X` will assume a value
+        less than or equal to :math:`x`:
+
+        .. math::
+
+            F(x) = P(X ≤ x)
+
+        A two-argument variant of this function is also defined as the
+        probability the random variable :math:`X` will assume a value between
+        :math:`x` and :math:`y`.
+
+        .. math::
+
+            F(x, y) = P(x ≤ X ≤ y)
+
+        `cdf` accepts `x` for :math:`x` and `y` for :math:`y`.
+
+        Parameters
+        ----------
+        x, y : array_like
+            The arguments of the CDF. `x` is required; `y` is optional.
+        method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'subtraction'}
+            The strategy used to evaluate the CDF.
+            By default (``None``), the one-argument form of the function
+            chooses between the following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the CDF itself
+            - ``'logexp'``: evaluate the log-CDF and exponentiate
+            - ``'complement'``: evaluate the CCDF and take the complement
+            - ``'quadrature'``: numerically integrate the PDF
+
+            In place of ``'complement'``, the two-argument form accepts:
+
+            - ``'subtraction'``: compute the CDF at each argument and take
+              the difference.
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The CDF evaluated at the provided argument(s).
+
+        See Also
+        --------
+        logcdf
+        ccdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The CDF :math:`F(x)` is related to the probability density function
+        :math:`f(x)` by:
+
+        .. math::
+
+            F(x) = \int_l^x f(u) du
+
+        The two argument version is:
+
+        .. math::
+
+            F(x, y) = \int_x^y f(u) du = F(y) - F(x)
+
+        The CDF evaluates to its minimum value of :math:`0` for :math:`x ≤ l`
+        and its maximum value of :math:`1` for :math:`x ≥ r`.
+
+        The CDF is also known simply as the "distribution function".
+
+        References
+        ----------
+        .. [1] Cumulative distribution function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Cumulative_distribution_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the CDF at the desired argument:
+
+        >>> X.cdf(0.25)
+        0.75
+
+        Evaluate the cumulative probability between two arguments:
+
+        >>> X.cdf(-0.25, 0.25) == X.cdf(0.25) - X.cdf(-0.25)
+        True
+
+        """  # noqa: E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def icdf(self, p, /, *, method):
+        r"""Inverse of the cumulative distribution function.
+
+        The inverse of the cumulative distribution function ("inverse CDF"),
+        denoted :math:`F^{-1}(p)`, is the argument :math:`x` for which the
+        cumulative distribution function :math:`F(x)` evaluates to :math:`p`.
+
+        .. math::
+
+            F^{-1}(p) = x \quad \text{s.t.} \quad F(x) = p
+
+        `icdf` accepts `p` for :math:`p \in [0, 1]`.
+
+        Parameters
+        ----------
+        p : array_like
+            The argument of the inverse CDF.
+        method : {None, 'formula', 'complement', 'inversion'}
+            The strategy used to evaluate the inverse CDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the inverse CDF itself
+            - ``'complement'``: evaluate the inverse CCDF at the
+              complement of `p`
+            - ``'inversion'``: solve numerically for the argument at which the
+              CDF is equal to `p`
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The inverse CDF evaluated at the provided argument.
+
+        See Also
+        --------
+        cdf
+        ilogcdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`. The
+        inverse CDF returns its minimum value of :math:`l` at :math:`p = 0`
+        and its maximum value of :math:`r` at :math:`p = 1`. Because the CDF
+        has range :math:`[0, 1]`, the inverse CDF is only defined on the
+        domain :math:`[0, 1]`; for :math:`p < 0` and :math:`p > 1`, `icdf`
+        returns ``nan``.
+
+        The inverse CDF is also known as the quantile function, percentile function,
+        and percent-point function.
+
+        References
+        ----------
+        .. [1] Quantile function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Quantile_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the inverse CDF at the desired argument:
+
+        >>> X.icdf(0.25)
+        -0.25
+        >>> np.allclose(X.cdf(X.icdf(0.25)), 0.25)
+        True
+
+        This function returns NaN when the argument is outside the domain.
+
+        >>> X.icdf([-0.1, 0, 1, 1.1])
+        array([ nan, -0.5,  0.5,  nan])
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def ccdf(self, x, y, /, *, method):
+        r"""Complementary cumulative distribution function
+
+        The complementary cumulative distribution function ("CCDF"), denoted
+        :math:`G(x)`, is the complement of the cumulative distribution function
+        :math:`F(x)`; i.e., probability the random variable :math:`X` will
+        assume a value greater than :math:`x`:
+
+        .. math::
+
+            G(x) = 1 - F(x) = P(X > x)
+
+        A two-argument variant of this function is:
+
+        .. math::
+
+            G(x, y) = 1 - F(x, y) = P(X < x \text{ or } X > y)
+
+        `ccdf` accepts `x` for :math:`x` and `y` for :math:`y`.
+
+        Parameters
+        ----------
+        x, y : array_like
+            The arguments of the CCDF. `x` is required; `y` is optional.
+        method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'addition'}
+            The strategy used to evaluate the CCDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the CCDF itself
+            - ``'logexp'``: evaluate the log-CCDF and exponentiate
+            - ``'complement'``: evaluate the CDF and take the complement
+            - ``'quadrature'``: numerically integrate the PDF
+
+            The two-argument form chooses between:
+
+            - ``'formula'``: use a formula for the CCDF itself
+            - ``'addition'``: compute the CDF at `x` and the CCDF at `y`, then add
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The CCDF evaluated at the provided argument(s).
+
+        See Also
+        --------
+        cdf
+        logccdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The CCDF :math:`G(x)` is related to the probability density function
+        :math:`f(x)` by:
+
+        .. math::
+
+            G(x) = \int_x^r f(u) du
+
+        The two argument version is:
+
+        .. math::
+
+            G(x, y) = \int_l^x f(u) du + \int_y^r f(u) du
+
+        The CCDF returns its minimum value of :math:`0` for :math:`x ≥ r`
+        and its maximum value of :math:`1` for :math:`x ≤ l`.
+
+        The CCDF is also known as the "survival function".
+
+        References
+        ----------
+        .. [1] Cumulative distribution function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Cumulative_distribution_function#Derived_functions
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the CCDF at the desired argument:
+
+        >>> X.ccdf(0.25)
+        0.25
+        >>> np.allclose(X.ccdf(0.25), 1-X.cdf(0.25))
+        True
+
+        Evaluate the complement of the cumulative probability between two arguments:
+
+        >>> X.ccdf(-0.25, 0.25) == X.cdf(-0.25) + X.ccdf(0.25)
+        True
+
+        """  # noqa: E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def iccdf(self, p, /, *, method):
+        r"""Inverse complementary cumulative distribution function.
+
+        The inverse complementary cumulative distribution function ("inverse CCDF"),
+        denoted :math:`G^{-1}(p)`, is the argument :math:`x` for which the
+        complementary cumulative distribution function :math:`G(x)` evaluates to
+        :math:`p`.
+
+        .. math::
+
+            G^{-1}(p) = x \quad \text{s.t.} \quad G(x) = p
+
+        `iccdf` accepts `p` for :math:`p \in [0, 1]`.
+
+        Parameters
+        ----------
+        p : array_like
+            The argument of the inverse CCDF.
+        method : {None, 'formula', 'complement', 'inversion'}
+            The strategy used to evaluate the inverse CCDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the inverse CCDF itself
+            - ``'complement'``: evaluate the inverse CDF at the
+              complement of `p`
+            - ``'inversion'``: solve numerically for the argument at which the
+              CCDF is equal to `p`
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The inverse CCDF evaluated at the provided argument.
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`. The
+        inverse CCDF returns its minimum value of :math:`l` at :math:`p = 1`
+        and its maximum value of :math:`r` at :math:`p = 0`. Because the CCDF
+        has range :math:`[0, 1]`, the inverse CCDF is only defined on the
+        domain :math:`[0, 1]`; for :math:`p < 0` and :math:`p > 1`, ``iccdf``
+        returns ``nan``.
+
+        See Also
+        --------
+        icdf
+        ilogccdf
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the inverse CCDF at the desired argument:
+
+        >>> X.iccdf(0.25)
+        0.25
+        >>> np.allclose(X.iccdf(0.25), X.icdf(1-0.25))
+        True
+
+        This function returns NaN when the argument is outside the domain.
+
+        >>> X.iccdf([-0.1, 0, 1, 1.1])
+        array([ nan,  0.5, -0.5,  nan])
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def logcdf(self, x, y, /, *, method):
+        r"""Log of the cumulative distribution function
+
+        The cumulative distribution function ("CDF"), denoted :math:`F(x)`, is
+        the probability the random variable :math:`X` will assume a value
+        less than or equal to :math:`x`:
+
+        .. math::
+
+            F(x) = P(X ≤ x)
+
+        A two-argument variant of this function is also defined as the
+        probability the random variable :math:`X` will assume a value between
+        :math:`x` and :math:`y`.
+
+        .. math::
+
+            F(x, y) = P(x ≤ X ≤ y)
+
+        `logcdf` computes the logarithm of the cumulative distribution function
+        ("log-CDF"), :math:`\log(F(x))`/:math:`\log(F(x, y))`, but it may be
+        numerically favorable compared to the naive implementation (computing
+        the CDF and taking the logarithm).
+
+        `logcdf` accepts `x` for :math:`x` and `y` for :math:`y`.
+
+        Parameters
+        ----------
+        x, y : array_like
+            The arguments of the log-CDF. `x` is required; `y` is optional.
+        method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'subtraction'}
+            The strategy used to evaluate the log-CDF.
+            By default (``None``), the one-argument form of the function
+            chooses between the following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the log-CDF itself
+            - ``'logexp'``: evaluate the CDF and take the logarithm
+            - ``'complement'``: evaluate the log-CCDF and take the
+              logarithmic complement (see Notes)
+            - ``'quadrature'``: numerically log-integrate the log-PDF
+
+            In place of ``'complement'``, the two-argument form accepts:
+
+            - ``'subtraction'``: compute the log-CDF at each argument and take
+              the logarithmic difference (see Notes)
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The log-CDF evaluated at the provided argument(s).
+
+        See Also
+        --------
+        cdf
+        logccdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The log-CDF evaluates to its minimum value of :math:`\log(0) = -\infty`
+        for :math:`x ≤ l` and its maximum value of :math:`\log(1) = 0` for
+        :math:`x ≥ r`.
+
+        For distributions with infinite support, it is common for
+        `cdf` to return a value of ``0`` when the argument
+        is theoretically within the support; this can occur because the true value
+        of the CDF is too small to be represented by the chosen dtype. `logcdf`,
+        however, will often return a finite (not ``-inf``) result over a much larger
+        domain. Similarly, `logcdf` may provided a strictly negative result with
+        arguments for which `cdf` would return ``1.0``. Consequently, it may be
+        preferred to work with the logarithms of probabilities to avoid underflow
+        and related limitations of floating point numbers.
+
+        The "logarithmic complement" of a number :math:`z` is mathematically
+        equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
+        of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
+        Similarly, the term "logarithmic difference" of :math:`w` and :math:`z`
+        is used here to mean :math:`\log(\exp(w)-\exp(z))`.
+
+        If ``y < x``, the CDF is negative, and therefore the log-CCDF
+        is complex with imaginary part :math:`\pi`. For
+        consistency, the result of this function always has complex dtype
+        when `y` is provided, regardless of the value of the imaginary part.
+
+        References
+        ----------
+        .. [1] Cumulative distribution function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Cumulative_distribution_function
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the log-CDF at the desired argument:
+
+        >>> X.logcdf(0.25)
+        -0.287682072451781
+        >>> np.allclose(X.logcdf(0.), np.log(X.cdf(0.)))
+        True
+
+        """  # noqa: E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def ilogcdf(self, logp, /, *, method):
+        r"""Inverse of the logarithm of the cumulative distribution function.
+
+        The inverse of the logarithm of the cumulative distribution function
+        ("inverse log-CDF") is the argument :math:`x` for which the logarithm
+        of the cumulative distribution function :math:`\log(F(x))` evaluates
+        to :math:`\log(p)`.
+
+        Mathematically, it is equivalent to :math:`F^{-1}(\exp(y))`, where
+        :math:`y = \log(p)`, but it may be numerically favorable compared to
+        the naive implementation (computing :math:`p = \exp(y)`, then
+        :math:`F^{-1}(p)`).
+
+        `ilogcdf` accepts `logp` for :math:`\log(p) ≤ 0`.
+
+        Parameters
+        ----------
+        logp : array_like
+            The argument of the inverse log-CDF.
+        method : {None, 'formula', 'complement', 'inversion'}
+            The strategy used to evaluate the inverse log-CDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the inverse log-CDF itself
+            - ``'complement'``: evaluate the inverse log-CCDF at the
+              logarithmic complement of `logp` (see Notes)
+            - ``'inversion'``: solve numerically for the argument at which the
+              log-CDF is equal to `logp`
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The inverse log-CDF evaluated at the provided argument.
+
+        See Also
+        --------
+        icdf
+        logcdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The inverse log-CDF returns its minimum value of :math:`l` at
+        :math:`\log(p) = \log(0) = -\infty` and its maximum value of :math:`r` at
+        :math:`\log(p) = \log(1) = 0`. Because the log-CDF has range
+        :math:`[-\infty, 0]`, the inverse log-CDF is only defined on the
+        negative reals; for :math:`\log(p) > 0`, `ilogcdf` returns ``nan``.
+
+        Occasionally, it is needed to find the argument of the CDF for which
+        the resulting probability is very close to ``0`` or ``1`` - too close to
+        represent accurately with floating point arithmetic. In many cases,
+        however, the *logarithm* of this resulting probability may be
+        represented in floating point arithmetic, in which case this function
+        may be used to find the argument of the CDF for which the *logarithm*
+        of the resulting probability is :math:`y = \log(p)`.
+
+        The "logarithmic complement" of a number :math:`z` is mathematically
+        equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
+        of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the inverse log-CDF at the desired argument:
+
+        >>> X.ilogcdf(-0.25)
+        0.2788007830714034
+        >>> np.allclose(X.ilogcdf(-0.25), X.icdf(np.exp(-0.25)))
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def logccdf(self, x, y, /, *, method):
+        r"""Log of the complementary cumulative distribution function
+
+        The complementary cumulative distribution function ("CCDF"), denoted
+        :math:`G(x)` is the complement of the cumulative distribution function
+        :math:`F(x)`; i.e., probability the random variable :math:`X` will
+        assume a value greater than :math:`x`:
+
+        .. math::
+
+            G(x) = 1 - F(x) = P(X > x)
+
+        A two-argument variant of this function is:
+
+        .. math::
+
+            G(x, y) = 1 - F(x, y) = P(X < x \quad \text{or} \quad X > y)
+
+        `logccdf` computes the logarithm of the complementary cumulative
+        distribution function ("log-CCDF"), :math:`\log(G(x))`/:math:`\log(G(x, y))`,
+        but it may be numerically favorable compared to the naive implementation
+        (computing the CDF and taking the logarithm).
+
+        `logccdf` accepts `x` for :math:`x` and `y` for :math:`y`.
+
+        Parameters
+        ----------
+        x, y : array_like
+            The arguments of the log-CCDF. `x` is required; `y` is optional.
+        method : {None, 'formula', 'logexp', 'complement', 'quadrature', 'addition'}
+            The strategy used to evaluate the log-CCDF.
+            By default (``None``), the one-argument form of the function
+            chooses between the following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the log CCDF itself
+            - ``'logexp'``: evaluate the CCDF and take the logarithm
+            - ``'complement'``: evaluate the log-CDF and take the
+              logarithmic complement (see Notes)
+            - ``'quadrature'``: numerically log-integrate the log-PDF
+
+            The two-argument form chooses between:
+
+            - ``'formula'``: use a formula for the log CCDF itself
+            - ``'addition'``: compute the log-CDF at `x` and the log-CCDF at `y`,
+              then take the logarithmic sum (see Notes)
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The log-CCDF evaluated at the provided argument(s).
+
+        See Also
+        --------
+        ccdf
+        logcdf
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`.
+        The log-CCDF returns its minimum value of :math:`\log(0)=-\infty` for
+        :math:`x ≥ r` and its maximum value of :math:`\log(1) = 0` for
+        :math:`x ≤ l`.
+
+        For distributions with infinite support, it is common for
+        `ccdf` to return a value of ``0`` when the argument
+        is theoretically within the support; this can occur because the true value
+        of the CCDF is too small to be represented by the chosen dtype. The log
+        of the CCDF, however, will often be finite (not ``-inf``) over a much larger
+        domain. Similarly, `logccdf` may provided a strictly negative result with
+        arguments for which `ccdf` would return ``1.0``. Consequently, it may be
+        preferred to work with the logarithms of probabilities to avoid underflow
+        and related limitations of floating point numbers.
+
+        The "logarithmic complement" of a number :math:`z` is mathematically
+        equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
+        of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
+        Similarly, the term "logarithmic sum" of :math:`w` and :math:`z`
+        is used here to mean the :math:`\log(\exp(w)+\exp(z))`, AKA
+        :math:`\text{LogSumExp}(w, z)`.
+
+        References
+        ----------
+        .. [1] Cumulative distribution function, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Cumulative_distribution_function#Derived_functions
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the log-CCDF at the desired argument:
+
+        >>> X.logccdf(0.25)
+        -1.3862943611198906
+        >>> np.allclose(X.logccdf(0.), np.log(X.ccdf(0.)))
+        True
+
+        """  # noqa: E501
+        raise NotImplementedError()
+
+    @abstractmethod
+    def ilogccdf(self, logp, /, *, method):
+        r"""Inverse of the log of the complementary cumulative distribution function.
+
+        The inverse of the logarithm of the complementary cumulative distribution
+        function ("inverse log-CCDF") is the argument :math:`x` for which the logarithm
+        of the complementary cumulative distribution function :math:`\log(G(x))`
+        evaluates to :math:`\log(p)`.
+
+        Mathematically, it is equivalent to :math:`G^{-1}(\exp(y))`, where
+        :math:`y = \log(p)`, but it may be numerically favorable compared to the naive
+        implementation (computing :math:`p = \exp(y)`, then :math:`G^{-1}(p)`).
+
+        `ilogccdf` accepts `logp` for :math:`\log(p) ≤ 0`.
+
+        Parameters
+        ----------
+        x : array_like
+            The argument of the inverse log-CCDF.
+        method : {None, 'formula', 'complement', 'inversion'}
+            The strategy used to evaluate the inverse log-CCDF.
+            By default (``None``), the infrastructure chooses between the
+            following options, listed in order of precedence.
+
+            - ``'formula'``: use a formula for the inverse log-CCDF itself
+            - ``'complement'``: evaluate the inverse log-CDF at the
+              logarithmic complement of `x` (see Notes)
+            - ``'inversion'``: solve numerically for the argument at which the
+              log-CCDF is equal to `x`
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The inverse log-CCDF evaluated at the provided argument.
+
+        Notes
+        -----
+        Suppose a continuous probability distribution has support :math:`[l, r]`. The
+        inverse log-CCDF returns its minimum value of :math:`l` at
+        :math:`\log(p) = \log(1) = 0` and its maximum value of :math:`r` at
+        :math:`\log(p) = \log(0) = -\infty`. Because the log-CCDF has range
+        :math:`[-\infty, 0]`, the inverse log-CDF is only defined on the
+        negative reals; for :math:`\log(p) > 0`, `ilogccdf` returns ``nan``.
+
+        Occasionally, it is needed to find the argument of the CCDF for which
+        the resulting probability is very close to ``0`` or ``1`` - too close to
+        represent accurately with floating point arithmetic. In many cases,
+        however, the *logarithm* of this resulting probability may be
+        represented in floating point arithmetic, in which case this function
+        may be used to find the argument of the CCDF for which the *logarithm*
+        of the resulting probability is `y = \log(p)`.
+
+        The "logarithmic complement" of a number :math:`z` is mathematically
+        equivalent to :math:`\log(1-\exp(z))`, but it is computed to avoid loss
+        of precision when :math:`\exp(z)` is nearly :math:`0` or :math:`1`.
+
+        See Also
+        --------
+        iccdf
+        ilogccdf
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-0.5, b=0.5)
+
+        Evaluate the inverse log-CCDF at the desired argument:
+
+        >>> X.ilogccdf(-0.25)
+        -0.2788007830714034
+        >>> np.allclose(X.ilogccdf(-0.25), X.iccdf(np.exp(-0.25)))
+        True
+
+        """
+        raise NotImplementedError()
+
+    @abstractmethod
+    def logentropy(self, *, method):
+        r"""Logarithm of the differential entropy
+
+        In terms of probability density function :math:`f(x)` and support
+        :math:`\chi`, the differential entropy (or simply "entropy") of a random
+        variable :math:`X` is:
+
+        .. math::
+
+            h(X) = - \int_{\chi} f(x) \log f(x) dx
+
+        `logentropy` computes the logarithm of the differential entropy
+        ("log-entropy"), :math:`log(h(X))`, but it may be numerically favorable
+        compared to the naive implementation (computing :math:`h(X)` then
+        taking the logarithm).
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'logexp', 'quadrature}
+            The strategy used to evaluate the log-entropy. By default
+            (``None``), the infrastructure chooses between the following options,
+            listed in order of precedence.
+
+            - ``'formula'``: use a formula for the log-entropy itself
+            - ``'logexp'``: evaluate the entropy and take the logarithm
+            - ``'quadrature'``: numerically log-integrate the logarithm of the
+              entropy integrand
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The log-entropy.
+
+        See Also
+        --------
+        entropy
+        logpdf
+
+        Notes
+        -----
+        If the entropy of a distribution is negative, then the log-entropy
+        is complex with imaginary part :math:`\pi`. For
+        consistency, the result of this function always has complex dtype,
+        regardless of the value of the imaginary part.
+
+        References
+        ----------
+        .. [1] Differential entropy, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Differential_entropy
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-1., b=1.)
+
+        Evaluate the log-entropy:
+
+        >>> X.logentropy()
+        (-0.3665129205816642+0j)
+        >>> np.allclose(np.exp(X.logentropy()), X.entropy())
+        True
+
+        For a random variable with negative entropy, the log-entropy has an
+        imaginary part equal to `np.pi`.
+
+        >>> X = stats.Uniform(a=-.1, b=.1)
+        >>> X.entropy(), X.logentropy()
+        (-1.6094379124341007, (0.4758849953271105+3.141592653589793j))
+
+        """
+        raise NotImplementedError()
+        
+    @abstractmethod
+    def entropy(self, *, method):
+        r"""Differential entropy
+
+        In terms of probability density function :math:`f(x)` and support
+        :math:`\chi`, the differential entropy (or simply "entropy") of a
+        continuous random variable :math:`X` is:
+
+        .. math::
+
+            h(X) = - \int_{\chi} f(x) \log f(x) dx
+
+        Parameters
+        ----------
+        method : {None, 'formula', 'logexp', 'quadrature'}
+            The strategy used to evaluate the entropy. By default (``None``),
+            the infrastructure chooses between the following options, listed
+            in order of precedence.
+
+            - ``'formula'``: use a formula for the entropy itself
+            - ``'logexp'``: evaluate the log-entropy and exponentiate
+            - ``'quadrature'``: use numerical integration
+
+            Not all `method` options are available for all distributions.
+            If the selected `method` is not available, a ``NotImplementedError``
+            will be raised.
+
+        Returns
+        -------
+        out : array
+            The entropy of the random variable.
+
+        See Also
+        --------
+        logentropy
+        pdf
+
+        Notes
+        -----
+        This function calculates the entropy using the natural logarithm; i.e.
+        the logarithm with base :math:`e`. Consequently, the value is expressed
+        in (dimensionless) "units" of nats. To convert the entropy to different
+        units (i.e. corresponding with a different base), divide the result by
+        the natural logarithm of the desired base.
+
+        References
+        ----------
+        .. [1] Differential entropy, *Wikipedia*,
+               https://en.wikipedia.org/wiki/Differential_entropy
+
+        Examples
+        --------
+        Instantiate a distribution with the desired parameters:
+
+        >>> from scipy import stats
+        >>> X = stats.Uniform(a=-1., b=1.)
+
+        Evaluate the entropy:
+
+        >>> X.entropy()
+        0.6931471805599454
+
+        """
+        raise NotImplementedError()
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_qmc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_qmc.py
new file mode 100644
index 0000000000000000000000000000000000000000..3287dceaca830b54fc46677fada36a8223d13ef0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_qmc.py
@@ -0,0 +1,2951 @@
+"""Quasi-Monte Carlo engines and helpers."""
+import copy
+import math
+import numbers
+import os
+import warnings
+from abc import ABC, abstractmethod
+from functools import partial
+from typing import (
+    ClassVar,
+    Literal,
+    overload,
+    TYPE_CHECKING,
+)
+from collections.abc import Callable
+
+import numpy as np
+
+from scipy._lib._util import DecimalNumber, GeneratorType, IntNumber, SeedType
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+    
+import scipy.stats as stats
+from scipy._lib._util import rng_integers, _rng_spawn, _transition_to_rng
+from scipy.sparse.csgraph import minimum_spanning_tree
+from scipy.spatial import distance, Voronoi
+from scipy.special import gammainc
+from ._sobol import (
+    _initialize_v, _cscramble, _fill_p_cumulative, _draw, _fast_forward,
+    _categorize, _MAXDIM
+)
+from ._qmc_cy import (
+    _cy_wrapper_centered_discrepancy,
+    _cy_wrapper_wrap_around_discrepancy,
+    _cy_wrapper_mixture_discrepancy,
+    _cy_wrapper_l2_star_discrepancy,
+    _cy_wrapper_update_discrepancy,
+    _cy_van_der_corput_scrambled,
+    _cy_van_der_corput,
+)
+
+
+__all__ = ['scale', 'discrepancy', 'geometric_discrepancy', 'update_discrepancy',
+           'QMCEngine', 'Sobol', 'Halton', 'LatinHypercube', 'PoissonDisk',
+           'MultinomialQMC', 'MultivariateNormalQMC']
+
+
+@overload
+def check_random_state(seed: IntNumber | None = ...) -> np.random.Generator:
+    ...
+
+
+@overload
+def check_random_state(seed: GeneratorType) -> GeneratorType:
+    ...
+
+
+# Based on scipy._lib._util.check_random_state
+# This is going to be removed at the end of the SPEC 7 transition,
+# so I'll just leave the argument name `seed` alone
+def check_random_state(seed=None):
+    """Turn `seed` into a `numpy.random.Generator` instance.
+
+    Parameters
+    ----------
+    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
+        If `seed` is an int or None, a new `numpy.random.Generator` is
+        created using ``np.random.default_rng(seed)``.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance, then
+        the provided instance is used.
+
+    Returns
+    -------
+    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
+        Random number generator.
+
+    """
+    if seed is None or isinstance(seed, (numbers.Integral, np.integer)):
+        return np.random.default_rng(seed)
+    elif isinstance(seed, (np.random.RandomState, np.random.Generator)):
+        return seed
+    else:
+        raise ValueError(f'{seed!r} cannot be used to seed a'
+                         ' numpy.random.Generator instance')
+
+
+def scale(
+    sample: "npt.ArrayLike",
+    l_bounds: "npt.ArrayLike",
+    u_bounds: "npt.ArrayLike",
+    *,
+    reverse: bool = False
+) -> np.ndarray:
+    r"""Sample scaling from unit hypercube to different bounds.
+
+    To convert a sample from :math:`[0, 1)` to :math:`[a, b), b>a`,
+    with :math:`a` the lower bounds and :math:`b` the upper bounds.
+    The following transformation is used:
+
+    .. math::
+
+        (b - a) \cdot \text{sample} + a
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        Sample to scale.
+    l_bounds, u_bounds : array_like (d,)
+        Lower and upper bounds (resp. :math:`a`, :math:`b`) of transformed
+        data. If `reverse` is True, range of the original data to transform
+        to the unit hypercube.
+    reverse : bool, optional
+        Reverse the transformation from different bounds to the unit hypercube.
+        Default is False.
+
+    Returns
+    -------
+    sample : array_like (n, d)
+        Scaled sample.
+
+    Examples
+    --------
+    Transform 3 samples in the unit hypercube to bounds:
+
+    >>> from scipy.stats import qmc
+    >>> l_bounds = [-2, 0]
+    >>> u_bounds = [6, 5]
+    >>> sample = [[0.5 , 0.75],
+    ...           [0.5 , 0.5],
+    ...           [0.75, 0.25]]
+    >>> sample_scaled = qmc.scale(sample, l_bounds, u_bounds)
+    >>> sample_scaled
+    array([[2.  , 3.75],
+           [2.  , 2.5 ],
+           [4.  , 1.25]])
+
+    And convert back to the unit hypercube:
+
+    >>> sample_ = qmc.scale(sample_scaled, l_bounds, u_bounds, reverse=True)
+    >>> sample_
+    array([[0.5 , 0.75],
+           [0.5 , 0.5 ],
+           [0.75, 0.25]])
+
+    """
+    sample = np.asarray(sample)
+
+    # Checking bounds and sample
+    if not sample.ndim == 2:
+        raise ValueError('Sample is not a 2D array')
+
+    lower, upper = _validate_bounds(
+        l_bounds=l_bounds, u_bounds=u_bounds, d=sample.shape[1]
+    )
+
+    if not reverse:
+        # Checking that sample is within the hypercube
+        if (sample.max() > 1.) or (sample.min() < 0.):
+            raise ValueError('Sample is not in unit hypercube')
+
+        return sample * (upper - lower) + lower
+    else:
+        # Checking that sample is within the bounds
+        if not (np.all(sample >= lower) and np.all(sample <= upper)):
+            raise ValueError('Sample is out of bounds')
+
+        return (sample - lower) / (upper - lower)
+
+
+def _ensure_in_unit_hypercube(sample: "npt.ArrayLike") -> np.ndarray:
+    """Ensure that sample is a 2D array and is within a unit hypercube
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        A 2D array of points.
+
+    Returns
+    -------
+    np.ndarray
+        The array interpretation of the input sample
+
+    Raises
+    ------
+    ValueError
+        If the input is not a 2D array or contains points outside of
+        a unit hypercube.
+    """
+    sample = np.asarray(sample, dtype=np.float64, order="C")
+
+    if not sample.ndim == 2:
+        raise ValueError("Sample is not a 2D array")
+
+    if (sample.max() > 1.) or (sample.min() < 0.):
+        raise ValueError("Sample is not in unit hypercube")
+
+    return sample
+
+
+def discrepancy(
+        sample: "npt.ArrayLike",
+        *,
+        iterative: bool = False,
+        method: Literal["CD", "WD", "MD", "L2-star"] = "CD",
+        workers: IntNumber = 1) -> float:
+    """Discrepancy of a given sample.
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample to compute the discrepancy from.
+    iterative : bool, optional
+        Must be False if not using it for updating the discrepancy.
+        Default is False. Refer to the notes for more details.
+    method : str, optional
+        Type of discrepancy, can be ``CD``, ``WD``, ``MD`` or ``L2-star``.
+        Refer to the notes for more details. Default is ``CD``.
+    workers : int, optional
+        Number of workers to use for parallel processing. If -1 is given all
+        CPU threads are used. Default is 1.
+
+    Returns
+    -------
+    discrepancy : float
+        Discrepancy.
+
+    See Also
+    --------
+    geometric_discrepancy
+
+    Notes
+    -----
+    The discrepancy is a uniformity criterion used to assess the space filling
+    of a number of samples in a hypercube. A discrepancy quantifies the
+    distance between the continuous uniform distribution on a hypercube and the
+    discrete uniform distribution on :math:`n` distinct sample points.
+
+    The lower the value is, the better the coverage of the parameter space is.
+
+    For a collection of subsets of the hypercube, the discrepancy is the
+    difference between the fraction of sample points in one of those
+    subsets and the volume of that subset. There are different definitions of
+    discrepancy corresponding to different collections of subsets. Some
+    versions take a root mean square difference over subsets instead of
+    a maximum.
+
+    A measure of uniformity is reasonable if it satisfies the following
+    criteria [1]_:
+
+    1. It is invariant under permuting factors and/or runs.
+    2. It is invariant under rotation of the coordinates.
+    3. It can measure not only uniformity of the sample over the hypercube,
+       but also the projection uniformity of the sample over non-empty
+       subset of lower dimension hypercubes.
+    4. There is some reasonable geometric meaning.
+    5. It is easy to compute.
+    6. It satisfies the Koksma-Hlawka-like inequality.
+    7. It is consistent with other criteria in experimental design.
+
+    Four methods are available:
+
+    * ``CD``: Centered Discrepancy - subspace involves a corner of the
+      hypercube
+    * ``WD``: Wrap-around Discrepancy - subspace can wrap around bounds
+    * ``MD``: Mixture Discrepancy - mix between CD/WD covering more criteria
+    * ``L2-star``: L2-star discrepancy - like CD BUT variant to rotation
+
+    See [2]_ for precise definitions of each method.
+
+    Lastly, using ``iterative=True``, it is possible to compute the
+    discrepancy as if we had :math:`n+1` samples. This is useful if we want
+    to add a point to a sampling and check the candidate which would give the
+    lowest discrepancy. Then you could just update the discrepancy with
+    each candidate using `update_discrepancy`. This method is faster than
+    computing the discrepancy for a large number of candidates.
+
+    References
+    ----------
+    .. [1] Fang et al. "Design and modeling for computer experiments".
+       Computer Science and Data Analysis Series, 2006.
+    .. [2] Zhou Y.-D. et al. "Mixture discrepancy for quasi-random point sets."
+       Journal of Complexity, 29 (3-4) , pp. 283-301, 2013.
+    .. [3] T. T. Warnock. "Computational investigations of low discrepancy
+       point sets." Applications of Number Theory to Numerical
+       Analysis, Academic Press, pp. 319-343, 1972.
+
+    Examples
+    --------
+    Calculate the quality of the sample using the discrepancy:
+
+    >>> import numpy as np
+    >>> from scipy.stats import qmc
+    >>> space = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
+    >>> l_bounds = [0.5, 0.5]
+    >>> u_bounds = [6.5, 6.5]
+    >>> space = qmc.scale(space, l_bounds, u_bounds, reverse=True)
+    >>> space
+    array([[0.08333333, 0.41666667],
+           [0.25      , 0.91666667],
+           [0.41666667, 0.25      ],
+           [0.58333333, 0.75      ],
+           [0.75      , 0.08333333],
+           [0.91666667, 0.58333333]])
+    >>> qmc.discrepancy(space)
+    0.008142039609053464
+
+    We can also compute iteratively the ``CD`` discrepancy by using
+    ``iterative=True``.
+
+    >>> disc_init = qmc.discrepancy(space[:-1], iterative=True)
+    >>> disc_init
+    0.04769081147119336
+    >>> qmc.update_discrepancy(space[-1], space[:-1], disc_init)
+    0.008142039609053513
+
+    """
+    sample = _ensure_in_unit_hypercube(sample)
+
+    workers = _validate_workers(workers)
+
+    methods = {
+        "CD": _cy_wrapper_centered_discrepancy,
+        "WD": _cy_wrapper_wrap_around_discrepancy,
+        "MD": _cy_wrapper_mixture_discrepancy,
+        "L2-star": _cy_wrapper_l2_star_discrepancy,
+    }
+
+    if method in methods:
+        return methods[method](sample, iterative, workers=workers)
+    else:
+        raise ValueError(f"{method!r} is not a valid method. It must be one of"
+                         f" {set(methods)!r}")
+
+
+def geometric_discrepancy(
+        sample: "npt.ArrayLike",
+        method: Literal["mindist", "mst"] = "mindist",
+        metric: str = "euclidean") -> float:
+    """Discrepancy of a given sample based on its geometric properties.
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample to compute the discrepancy from.
+    method : {"mindist", "mst"}, optional
+        The method to use. One of ``mindist`` for minimum distance (default)
+        or ``mst`` for minimum spanning tree.
+    metric : str or callable, optional
+        The distance metric to use. See the documentation
+        for `scipy.spatial.distance.pdist` for the available metrics and
+        the default.
+
+    Returns
+    -------
+    discrepancy : float
+        Discrepancy (higher values correspond to greater sample uniformity).
+
+    See Also
+    --------
+    discrepancy
+
+    Notes
+    -----
+    The discrepancy can serve as a simple measure of quality of a random sample.
+    This measure is based on the geometric properties of the distribution of points
+    in the sample, such as the minimum distance between any pair of points, or
+    the mean edge length in a minimum spanning tree.
+
+    The higher the value is, the better the coverage of the parameter space is.
+    Note that this is different from `scipy.stats.qmc.discrepancy`, where lower
+    values correspond to higher quality of the sample.
+
+    Also note that when comparing different sampling strategies using this function,
+    the sample size must be kept constant.
+
+    It is possible to calculate two metrics from the minimum spanning tree:
+    the mean edge length and the standard deviation of edges lengths. Using
+    both metrics offers a better picture of uniformity than either metric alone,
+    with higher mean and lower standard deviation being preferable (see [1]_
+    for a brief discussion). This function currently only calculates the mean
+    edge length.
+
+    References
+    ----------
+    .. [1] Franco J. et al. "Minimum Spanning Tree: A new approach to assess the quality
+       of the design of computer experiments." Chemometrics and Intelligent Laboratory
+       Systems, 97 (2), pp. 164-169, 2009.
+
+    Examples
+    --------
+    Calculate the quality of the sample using the minimum euclidean distance
+    (the defaults):
+
+    >>> import numpy as np
+    >>> from scipy.stats import qmc
+    >>> rng = np.random.default_rng(191468432622931918890291693003068437394)
+    >>> sample = qmc.LatinHypercube(d=2, rng=rng).random(50)
+    >>> qmc.geometric_discrepancy(sample)
+    0.03708161435687876
+
+    Calculate the quality using the mean edge length in the minimum
+    spanning tree:
+
+    >>> qmc.geometric_discrepancy(sample, method='mst')
+    0.1105149978798376
+
+    Display the minimum spanning tree and the points with
+    the smallest distance:
+
+    >>> import matplotlib.pyplot as plt
+    >>> from matplotlib.lines import Line2D
+    >>> from scipy.sparse.csgraph import minimum_spanning_tree
+    >>> from scipy.spatial.distance import pdist, squareform
+    >>> dist = pdist(sample)
+    >>> mst = minimum_spanning_tree(squareform(dist))
+    >>> edges = np.where(mst.toarray() > 0)
+    >>> edges = np.asarray(edges).T
+    >>> min_dist = np.min(dist)
+    >>> min_idx = np.argwhere(squareform(dist) == min_dist)[0]
+    >>> fig, ax = plt.subplots(figsize=(10, 5))
+    >>> _ = ax.set(aspect='equal', xlabel=r'$x_1$', ylabel=r'$x_2$',
+    ...            xlim=[0, 1], ylim=[0, 1])
+    >>> for edge in edges:
+    ...     ax.plot(sample[edge, 0], sample[edge, 1], c='k')
+    >>> ax.scatter(sample[:, 0], sample[:, 1])
+    >>> ax.add_patch(plt.Circle(sample[min_idx[0]], min_dist, color='red', fill=False))
+    >>> markers = [
+    ...     Line2D([0], [0], marker='o', lw=0, label='Sample points'),
+    ...     Line2D([0], [0], color='k', label='Minimum spanning tree'),
+    ...     Line2D([0], [0], marker='o', lw=0, markerfacecolor='w', markeredgecolor='r',
+    ...            label='Minimum point-to-point distance'),
+    ... ]
+    >>> ax.legend(handles=markers, loc='center left', bbox_to_anchor=(1, 0.5));
+    >>> plt.show()
+
+    """
+    sample = _ensure_in_unit_hypercube(sample)
+    if sample.shape[0] < 2:
+        raise ValueError("Sample must contain at least two points")
+
+    distances = distance.pdist(sample, metric=metric)  # type: ignore[call-overload]
+
+    if np.any(distances == 0.0):
+        warnings.warn("Sample contains duplicate points.", stacklevel=2)
+
+    if method == "mindist":
+        return np.min(distances[distances.nonzero()])
+    elif method == "mst":
+        fully_connected_graph = distance.squareform(distances)
+        mst = minimum_spanning_tree(fully_connected_graph)
+        distances = mst[mst.nonzero()]
+        # TODO consider returning both the mean and the standard deviation
+        # see [1] for a discussion
+        return np.mean(distances)
+    else:
+        raise ValueError(f"{method!r} is not a valid method. "
+                         f"It must be one of {{'mindist', 'mst'}}")
+
+
+def update_discrepancy(
+        x_new: "npt.ArrayLike",
+        sample: "npt.ArrayLike",
+        initial_disc: DecimalNumber) -> float:
+    """Update the centered discrepancy with a new sample.
+
+    Parameters
+    ----------
+    x_new : array_like (1, d)
+        The new sample to add in `sample`.
+    sample : array_like (n, d)
+        The initial sample.
+    initial_disc : float
+        Centered discrepancy of the `sample`.
+
+    Returns
+    -------
+    discrepancy : float
+        Centered discrepancy of the sample composed of `x_new` and `sample`.
+
+    Examples
+    --------
+    We can also compute iteratively the discrepancy by using
+    ``iterative=True``.
+
+    >>> import numpy as np
+    >>> from scipy.stats import qmc
+    >>> space = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
+    >>> l_bounds = [0.5, 0.5]
+    >>> u_bounds = [6.5, 6.5]
+    >>> space = qmc.scale(space, l_bounds, u_bounds, reverse=True)
+    >>> disc_init = qmc.discrepancy(space[:-1], iterative=True)
+    >>> disc_init
+    0.04769081147119336
+    >>> qmc.update_discrepancy(space[-1], space[:-1], disc_init)
+    0.008142039609053513
+
+    """
+    sample = np.asarray(sample, dtype=np.float64, order="C")
+    x_new = np.asarray(x_new, dtype=np.float64, order="C")
+
+    # Checking that sample is within the hypercube and 2D
+    if not sample.ndim == 2:
+        raise ValueError('Sample is not a 2D array')
+
+    if (sample.max() > 1.) or (sample.min() < 0.):
+        raise ValueError('Sample is not in unit hypercube')
+
+    # Checking that x_new is within the hypercube and 1D
+    if not x_new.ndim == 1:
+        raise ValueError('x_new is not a 1D array')
+
+    if not (np.all(x_new >= 0) and np.all(x_new <= 1)):
+        raise ValueError('x_new is not in unit hypercube')
+
+    if x_new.shape[0] != sample.shape[1]:
+        raise ValueError("x_new and sample must be broadcastable")
+
+    return _cy_wrapper_update_discrepancy(x_new, sample, initial_disc)
+
+
+def _perturb_discrepancy(sample: np.ndarray, i1: int, i2: int, k: int,
+                         disc: float):
+    """Centered discrepancy after an elementary perturbation of a LHS.
+
+    An elementary perturbation consists of an exchange of coordinates between
+    two points: ``sample[i1, k] <-> sample[i2, k]``. By construction,
+    this operation conserves the LHS properties.
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample (before permutation) to compute the discrepancy from.
+    i1 : int
+        The first line of the elementary permutation.
+    i2 : int
+        The second line of the elementary permutation.
+    k : int
+        The column of the elementary permutation.
+    disc : float
+        Centered discrepancy of the design before permutation.
+
+    Returns
+    -------
+    discrepancy : float
+        Centered discrepancy of the design after permutation.
+
+    References
+    ----------
+    .. [1] Jin et al. "An efficient algorithm for constructing optimal design
+       of computer experiments", Journal of Statistical Planning and
+       Inference, 2005.
+
+    """
+    n = sample.shape[0]
+
+    z_ij = sample - 0.5
+
+    # Eq (19)
+    c_i1j = (1. / n ** 2.
+             * np.prod(0.5 * (2. + abs(z_ij[i1, :])
+                              + abs(z_ij) - abs(z_ij[i1, :] - z_ij)), axis=1))
+    c_i2j = (1. / n ** 2.
+             * np.prod(0.5 * (2. + abs(z_ij[i2, :])
+                              + abs(z_ij) - abs(z_ij[i2, :] - z_ij)), axis=1))
+
+    # Eq (20)
+    c_i1i1 = (1. / n ** 2 * np.prod(1 + abs(z_ij[i1, :]))
+              - 2. / n * np.prod(1. + 0.5 * abs(z_ij[i1, :])
+                                 - 0.5 * z_ij[i1, :] ** 2))
+    c_i2i2 = (1. / n ** 2 * np.prod(1 + abs(z_ij[i2, :]))
+              - 2. / n * np.prod(1. + 0.5 * abs(z_ij[i2, :])
+                                 - 0.5 * z_ij[i2, :] ** 2))
+
+    # Eq (22), typo in the article in the denominator i2 -> i1
+    num = (2 + abs(z_ij[i2, k]) + abs(z_ij[:, k])
+           - abs(z_ij[i2, k] - z_ij[:, k]))
+    denum = (2 + abs(z_ij[i1, k]) + abs(z_ij[:, k])
+             - abs(z_ij[i1, k] - z_ij[:, k]))
+    gamma = num / denum
+
+    # Eq (23)
+    c_p_i1j = gamma * c_i1j
+    # Eq (24)
+    c_p_i2j = c_i2j / gamma
+
+    alpha = (1 + abs(z_ij[i2, k])) / (1 + abs(z_ij[i1, k]))
+    beta = (2 - abs(z_ij[i2, k])) / (2 - abs(z_ij[i1, k]))
+
+    g_i1 = np.prod(1. + abs(z_ij[i1, :]))
+    g_i2 = np.prod(1. + abs(z_ij[i2, :]))
+    h_i1 = np.prod(1. + 0.5 * abs(z_ij[i1, :]) - 0.5 * (z_ij[i1, :] ** 2))
+    h_i2 = np.prod(1. + 0.5 * abs(z_ij[i2, :]) - 0.5 * (z_ij[i2, :] ** 2))
+
+    # Eq (25), typo in the article g is missing
+    c_p_i1i1 = ((g_i1 * alpha) / (n ** 2) - 2. * alpha * beta * h_i1 / n)
+    # Eq (26), typo in the article n ** 2
+    c_p_i2i2 = ((g_i2 / ((n ** 2) * alpha)) - (2. * h_i2 / (n * alpha * beta)))
+
+    # Eq (26)
+    sum_ = c_p_i1j - c_i1j + c_p_i2j - c_i2j
+
+    mask = np.ones(n, dtype=bool)
+    mask[[i1, i2]] = False
+    sum_ = sum(sum_[mask])
+
+    disc_ep = (disc + c_p_i1i1 - c_i1i1 + c_p_i2i2 - c_i2i2 + 2 * sum_)
+
+    return disc_ep
+
+
+def primes_from_2_to(n: int) -> np.ndarray:
+    """Prime numbers from 2 to *n*.
+
+    Parameters
+    ----------
+    n : int
+        Sup bound with ``n >= 6``.
+
+    Returns
+    -------
+    primes : list(int)
+        Primes in ``2 <= p < n``.
+
+    Notes
+    -----
+    Taken from [1]_ by P.T. Roy, written consent given on 23.04.2021
+    by the original author, Bruno Astrolino, for free use in SciPy under
+    the 3-clause BSD.
+
+    References
+    ----------
+    .. [1] `StackOverflow `_.
+
+    """
+    sieve = np.ones(n // 3 + (n % 6 == 2), dtype=bool)
+    for i in range(1, int(n ** 0.5) // 3 + 1):
+        k = 3 * i + 1 | 1
+        sieve[k * k // 3::2 * k] = False
+        sieve[k * (k - 2 * (i & 1) + 4) // 3::2 * k] = False
+    return np.r_[2, 3, ((3 * np.nonzero(sieve)[0][1:] + 1) | 1)]
+
+
+def n_primes(n: IntNumber) -> list[int]:
+    """List of the n-first prime numbers.
+
+    Parameters
+    ----------
+    n : int
+        Number of prime numbers wanted.
+
+    Returns
+    -------
+    primes : list(int)
+        List of primes.
+
+    """
+    primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
+              61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127,
+              131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
+              197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269,
+              271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
+              353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431,
+              433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
+              509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599,
+              601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673,
+              677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761,
+              769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857,
+              859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947,
+              953, 967, 971, 977, 983, 991, 997][:n]
+
+    if len(primes) < n:
+        big_number = 2000
+        while 'Not enough primes':
+            primes = primes_from_2_to(big_number)[:n]  # type: ignore
+            if len(primes) == n:
+                break
+            big_number += 1000
+
+    return primes
+
+
+def _van_der_corput_permutations(
+    base: IntNumber, *, rng: SeedType = None
+) -> np.ndarray:
+    """Permutations for scrambling a Van der Corput sequence.
+
+    Parameters
+    ----------
+    base : int
+        Base of the sequence.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. During the transition, the behavior documented above is not
+            accurate; see `check_random_state` for actual behavior. After the
+            transition, this admonition can be removed.
+
+    Returns
+    -------
+    permutations : array_like
+        Permutation indices.
+
+    Notes
+    -----
+    In Algorithm 1 of Owen 2017, a permutation of `np.arange(base)` is
+    created for each positive integer `k` such that ``1 - base**-k < 1``
+    using floating-point arithmetic. For double precision floats, the
+    condition ``1 - base**-k < 1`` can also be written as ``base**-k >
+    2**-54``, which makes it more apparent how many permutations we need
+    to create.
+    """
+    rng = check_random_state(rng)
+    count = math.ceil(54 / math.log2(base)) - 1
+    permutations = np.repeat(np.arange(base)[None], count, axis=0)
+    for perm in permutations:
+        rng.shuffle(perm)
+
+    return permutations
+
+
+def van_der_corput(
+        n: IntNumber,
+        base: IntNumber = 2,
+        *,
+        start_index: IntNumber = 0,
+        scramble: bool = False,
+        permutations: "npt.ArrayLike | None" = None,
+        rng: SeedType = None,
+        workers: IntNumber = 1) -> np.ndarray:
+    """Van der Corput sequence.
+
+    Pseudo-random number generator based on a b-adic expansion.
+
+    Scrambling uses permutations of the remainders (see [1]_). Multiple
+    permutations are applied to construct a point. The sequence of
+    permutations has to be the same for all points of the sequence.
+
+    Parameters
+    ----------
+    n : int
+        Number of element of the sequence.
+    base : int, optional
+        Base of the sequence. Default is 2.
+    start_index : int, optional
+        Index to start the sequence from. Default is 0.
+    scramble : bool, optional
+        If True, use Owen scrambling. Otherwise no scrambling is done.
+        Default is True.
+    permutations : array_like, optional
+        Permutations used for scrambling.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+    workers : int, optional
+        Number of workers to use for parallel processing. If -1 is
+        given all CPU threads are used. Default is 1.
+
+    Returns
+    -------
+    sequence : list (n,)
+        Sequence of Van der Corput.
+
+    References
+    ----------
+    .. [1] A. B. Owen. "A randomized Halton algorithm in R",
+       :arxiv:`1706.02808`, 2017.
+
+    """
+    if base < 2:
+        raise ValueError("'base' must be at least 2")
+
+    if scramble:
+        if permutations is None:
+            permutations = _van_der_corput_permutations(
+                base=base, rng=rng
+            )
+        else:
+            permutations = np.asarray(permutations)
+
+        permutations = permutations.astype(np.int64)
+        return _cy_van_der_corput_scrambled(n, base, start_index,
+                                            permutations, workers)
+
+    else:
+        return _cy_van_der_corput(n, base, start_index, workers)
+
+
+class QMCEngine(ABC):
+    """A generic Quasi-Monte Carlo sampler class meant for subclassing.
+
+    QMCEngine is a base class to construct a specific Quasi-Monte Carlo
+    sampler. It cannot be used directly as a sampler.
+
+    Parameters
+    ----------
+    d : int
+        Dimension of the parameter space.
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.10.0
+
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Notes
+    -----
+    By convention samples are distributed over the half-open interval
+    ``[0, 1)``. Instances of the class can access the attributes: ``d`` for
+    the dimension; and ``rng`` for the random number generator.
+
+    **Subclassing**
+
+    When subclassing `QMCEngine` to create a new sampler,  ``__init__`` and
+    ``random`` must be redefined.
+
+    * ``__init__(d, rng=None)``: at least fix the dimension. If the sampler
+      does not take advantage of a ``rng`` (deterministic methods like
+      Halton), this parameter can be omitted.
+    * ``_random(n, *, workers=1)``: draw ``n`` from the engine. ``workers``
+      is used for parallelism. See `Halton` for example.
+
+    Optionally, two other methods can be overwritten by subclasses:
+
+    * ``reset``: Reset the engine to its original state.
+    * ``fast_forward``: If the sequence is deterministic (like Halton
+      sequence), then ``fast_forward(n)`` is skipping the ``n`` first draw.
+
+    Examples
+    --------
+    To create a random sampler based on ``np.random.random``, we would do the
+    following:
+
+    >>> from scipy.stats import qmc
+    >>> class RandomEngine(qmc.QMCEngine):
+    ...     def __init__(self, d, rng=None):
+    ...         super().__init__(d=d, rng=rng)
+    ...
+    ...
+    ...     def _random(self, n=1, *, workers=1):
+    ...         return self.rng.random((n, self.d))
+    ...
+    ...
+    ...     def reset(self):
+    ...         super().__init__(d=self.d, rng=self.rng_seed)
+    ...         return self
+    ...
+    ...
+    ...     def fast_forward(self, n):
+    ...         self.random(n)
+    ...         return self
+
+    After subclassing `QMCEngine` to define the sampling strategy we want to
+    use, we can create an instance to sample from.
+
+    >>> engine = RandomEngine(2)
+    >>> engine.random(5)
+    array([[0.22733602, 0.31675834],  # random
+           [0.79736546, 0.67625467],
+           [0.39110955, 0.33281393],
+           [0.59830875, 0.18673419],
+           [0.67275604, 0.94180287]])
+
+    We can also reset the state of the generator and resample again.
+
+    >>> _ = engine.reset()
+    >>> engine.random(5)
+    array([[0.22733602, 0.31675834],  # random
+           [0.79736546, 0.67625467],
+           [0.39110955, 0.33281393],
+           [0.59830875, 0.18673419],
+           [0.67275604, 0.94180287]])
+
+    """
+
+    @abstractmethod
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self,
+        d: IntNumber,
+        *,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None
+    ) -> None:
+        self._initialize(d, optimization=optimization, rng=rng)
+
+    # During SPEC 7 transition:
+    # `__init__` has to be wrapped with @_transition_to_rng decorator
+    # because it is public. Subclasses previously called `__init__`
+    # directly, but this was problematic because arguments passed to
+    # subclass `__init__` as `seed` would get passed to superclass
+    # `__init__` as `rng`, rejecting `RandomState` arguments.
+    def _initialize(
+        self,
+        d: IntNumber,
+        *,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None
+    ) -> None:
+        if not np.issubdtype(type(d), np.integer) or d < 0:
+            raise ValueError('d must be a non-negative integer value')
+
+        self.d = d
+
+        if isinstance(rng, np.random.Generator):
+            # Spawn a Generator that we can own and reset.
+            self.rng = _rng_spawn(rng, 1)[0]
+        else:
+            # Create our instance of Generator, does not need spawning
+            # Also catch RandomState which cannot be spawned
+            self.rng = check_random_state(rng)
+        self.rng_seed = copy.deepcopy(self.rng)
+
+        self.num_generated = 0
+
+        config = {
+            # random-cd
+            "n_nochange": 100,
+            "n_iters": 10_000,
+            "rng": self.rng,
+
+            # lloyd
+            "tol": 1e-5,
+            "maxiter": 10,
+            "qhull_options": None,
+        }
+        self._optimization = optimization
+        self.optimization_method = _select_optimizer(optimization, config)
+
+    @abstractmethod
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        ...
+
+    def random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        """Draw `n` in the half-open interval ``[0, 1)``.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space.
+            Default is 1.
+        workers : int, optional
+            Only supported with `Halton`.
+            Number of workers to use for parallel processing. If -1 is
+            given all CPU threads are used. Default is 1. It becomes faster
+            than one worker for `n` greater than :math:`10^3`.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        """
+        sample = self._random(n, workers=workers)
+        if self.optimization_method is not None:
+            sample = self.optimization_method(sample)
+
+        self.num_generated += n
+        return sample
+
+    def integers(
+        self,
+        l_bounds: "npt.ArrayLike",
+        *,
+        u_bounds: "npt.ArrayLike | None" = None,
+        n: IntNumber = 1,
+        endpoint: bool = False,
+        workers: IntNumber = 1
+    ) -> np.ndarray:
+        r"""
+        Draw `n` integers from `l_bounds` (inclusive) to `u_bounds`
+        (exclusive), or if endpoint=True, `l_bounds` (inclusive) to
+        `u_bounds` (inclusive).
+
+        Parameters
+        ----------
+        l_bounds : int or array-like of ints
+            Lowest (signed) integers to be drawn (unless ``u_bounds=None``,
+            in which case this parameter is 0 and this value is used for
+            `u_bounds`).
+        u_bounds : int or array-like of ints, optional
+            If provided, one above the largest (signed) integer to be drawn
+            (see above for behavior if ``u_bounds=None``).
+            If array-like, must contain integer values.
+        n : int, optional
+            Number of samples to generate in the parameter space.
+            Default is 1.
+        endpoint : bool, optional
+            If true, sample from the interval ``[l_bounds, u_bounds]`` instead
+            of the default ``[l_bounds, u_bounds)``. Defaults is False.
+        workers : int, optional
+            Number of workers to use for parallel processing. If -1 is
+            given all CPU threads are used. Only supported when using `Halton`
+            Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        Notes
+        -----
+        It is safe to just use the same ``[0, 1)`` to integer mapping
+        with QMC that you would use with MC. You still get unbiasedness,
+        a strong law of large numbers, an asymptotically infinite variance
+        reduction and a finite sample variance bound.
+
+        To convert a sample from :math:`[0, 1)` to :math:`[a, b), b>a`,
+        with :math:`a` the lower bounds and :math:`b` the upper bounds,
+        the following transformation is used:
+
+        .. math::
+
+            \text{floor}((b - a) \cdot \text{sample} + a)
+
+        """
+        if u_bounds is None:
+            u_bounds = l_bounds
+            l_bounds = 0
+
+        u_bounds = np.atleast_1d(u_bounds)
+        l_bounds = np.atleast_1d(l_bounds)
+
+        if endpoint:
+            u_bounds = u_bounds + 1
+
+        if (not np.issubdtype(l_bounds.dtype, np.integer) or
+                not np.issubdtype(u_bounds.dtype, np.integer)):
+            message = ("'u_bounds' and 'l_bounds' must be integers or"
+                       " array-like of integers")
+            raise ValueError(message)
+
+        if isinstance(self, Halton):
+            sample = self.random(n=n, workers=workers)
+        else:
+            sample = self.random(n=n)
+
+        sample = scale(sample, l_bounds=l_bounds, u_bounds=u_bounds)
+        sample = np.floor(sample).astype(np.int64)
+
+        return sample
+
+    def reset(self) -> "QMCEngine":
+        """Reset the engine to base state.
+
+        Returns
+        -------
+        engine : QMCEngine
+            Engine reset to its base state.
+
+        """
+        rng = copy.deepcopy(self.rng_seed)
+        self.rng = check_random_state(rng)
+        self.num_generated = 0
+        return self
+
+    def fast_forward(self, n: IntNumber) -> "QMCEngine":
+        """Fast-forward the sequence by `n` positions.
+
+        Parameters
+        ----------
+        n : int
+            Number of points to skip in the sequence.
+
+        Returns
+        -------
+        engine : QMCEngine
+            Engine reset to its base state.
+
+        """
+        self.random(n=n)
+        return self
+
+
+class Halton(QMCEngine):
+    """Halton sequence.
+
+    Pseudo-random number generator that generalize the Van der Corput sequence
+    for multiple dimensions. The Halton sequence uses the base-two Van der
+    Corput sequence for the first dimension, base-three for its second and
+    base-:math:`n` for its n-dimension.
+
+    Parameters
+    ----------
+    d : int
+        Dimension of the parameter space.
+    scramble : bool, optional
+        If True, use Owen scrambling. Otherwise no scrambling is done.
+        Default is True.
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.10.0
+
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Notes
+    -----
+    The Halton sequence has severe striping artifacts for even modestly
+    large dimensions. These can be ameliorated by scrambling. Scrambling
+    also supports replication-based error estimates and extends
+    applicability to unbounded integrands.
+
+    References
+    ----------
+    .. [1] Halton, "On the efficiency of certain quasi-random sequences of
+       points in evaluating multi-dimensional integrals", Numerische
+       Mathematik, 1960.
+    .. [2] A. B. Owen. "A randomized Halton algorithm in R",
+       :arxiv:`1706.02808`, 2017.
+
+    Examples
+    --------
+    Generate samples from a low discrepancy sequence of Halton.
+
+    >>> from scipy.stats import qmc
+    >>> sampler = qmc.Halton(d=2, scramble=False)
+    >>> sample = sampler.random(n=5)
+    >>> sample
+    array([[0.        , 0.        ],
+           [0.5       , 0.33333333],
+           [0.25      , 0.66666667],
+           [0.75      , 0.11111111],
+           [0.125     , 0.44444444]])
+
+    Compute the quality of the sample using the discrepancy criterion.
+
+    >>> qmc.discrepancy(sample)
+    0.088893711419753
+
+    If some wants to continue an existing design, extra points can be obtained
+    by calling again `random`. Alternatively, you can skip some points like:
+
+    >>> _ = sampler.fast_forward(5)
+    >>> sample_continued = sampler.random(n=5)
+    >>> sample_continued
+    array([[0.3125    , 0.37037037],
+           [0.8125    , 0.7037037 ],
+           [0.1875    , 0.14814815],
+           [0.6875    , 0.48148148],
+           [0.4375    , 0.81481481]])
+
+    Finally, samples can be scaled to bounds.
+
+    >>> l_bounds = [0, 2]
+    >>> u_bounds = [10, 5]
+    >>> qmc.scale(sample_continued, l_bounds, u_bounds)
+    array([[3.125     , 3.11111111],
+           [8.125     , 4.11111111],
+           [1.875     , 2.44444444],
+           [6.875     , 3.44444444],
+           [4.375     , 4.44444444]])
+
+    """
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self, d: IntNumber, *, scramble: bool = True,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None
+    ) -> None:
+        # Used in `scipy.integrate.qmc_quad`
+        self._init_quad = {'d': d, 'scramble': True,
+                           'optimization': optimization}
+        super()._initialize(d=d, optimization=optimization, rng=rng)
+
+        # important to have ``type(bdim) == int`` for performance reason
+        self.base = [int(bdim) for bdim in n_primes(d)]
+        self.scramble = scramble
+
+        self._initialize_permutations()
+
+    def _initialize_permutations(self) -> None:
+        """Initialize permutations for all Van der Corput sequences.
+
+        Permutations are only needed for scrambling.
+        """
+        self._permutations: list = [None] * len(self.base)
+        if self.scramble:
+            for i, bdim in enumerate(self.base):
+                permutations = _van_der_corput_permutations(
+                    base=bdim, rng=self.rng
+                )
+
+                self._permutations[i] = permutations
+
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        """Draw `n` in the half-open interval ``[0, 1)``.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+        workers : int, optional
+            Number of workers to use for parallel processing. If -1 is
+            given all CPU threads are used. Default is 1. It becomes faster
+            than one worker for `n` greater than :math:`10^3`.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        """
+        workers = _validate_workers(workers)
+        # Generate a sample using a Van der Corput sequence per dimension.
+        sample = [van_der_corput(n, bdim, start_index=self.num_generated,
+                                 scramble=self.scramble,
+                                 permutations=self._permutations[i],
+                                 workers=workers)
+                  for i, bdim in enumerate(self.base)]
+
+        return np.array(sample).T.reshape(n, self.d)
+
+
+class LatinHypercube(QMCEngine):
+    r"""Latin hypercube sampling (LHS).
+
+    A Latin hypercube sample [1]_ generates :math:`n` points in
+    :math:`[0,1)^{d}`. Each univariate marginal distribution is stratified,
+    placing exactly one point in :math:`[j/n, (j+1)/n)` for
+    :math:`j=0,1,...,n-1`. They are still applicable when :math:`n << d`.
+
+    Parameters
+    ----------
+    d : int
+        Dimension of the parameter space.
+    scramble : bool, optional
+        When False, center samples within cells of a multi-dimensional grid.
+        Otherwise, samples are randomly placed within cells of the grid.
+
+        .. note::
+            Setting ``scramble=False`` does not ensure deterministic output.
+            For that, use the `rng` parameter.
+
+        Default is True.
+
+        .. versionadded:: 1.10.0
+
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.8.0
+        .. versionchanged:: 1.10.0
+            Add ``lloyd``.
+
+    strength : {1, 2}, optional
+        Strength of the LHS. ``strength=1`` produces a plain LHS while
+        ``strength=2`` produces an orthogonal array based LHS of strength 2
+        [7]_, [8]_. In that case, only ``n=p**2`` points can be sampled,
+        with ``p`` a prime number. It also constrains ``d <= p + 1``.
+        Default is 1.
+
+        .. versionadded:: 1.8.0
+
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    See Also
+    --------
+    :ref:`quasi-monte-carlo`
+
+    Notes
+    -----
+
+    When LHS is used for integrating a function :math:`f` over :math:`n`,
+    LHS is extremely effective on integrands that are nearly additive [2]_.
+    With a LHS of :math:`n` points, the variance of the integral is always
+    lower than plain MC on :math:`n-1` points [3]_. There is a central limit
+    theorem for LHS on the mean and variance of the integral [4]_, but not
+    necessarily for optimized LHS due to the randomization.
+
+    :math:`A` is called an orthogonal array of strength :math:`t` if in each
+    n-row-by-t-column submatrix of :math:`A`: all :math:`p^t` possible
+    distinct rows occur the same number of times. The elements of :math:`A`
+    are in the set :math:`\{0, 1, ..., p-1\}`, also called symbols.
+    The constraint that :math:`p` must be a prime number is to allow modular
+    arithmetic. Increasing strength adds some symmetry to the sub-projections
+    of a sample. With strength 2, samples are symmetric along the diagonals of
+    2D sub-projections. This may be undesirable, but on the other hand, the
+    sample dispersion is improved.
+
+    Strength 1 (plain LHS) brings an advantage over strength 0 (MC) and
+    strength 2 is a useful increment over strength 1. Going to strength 3 is
+    a smaller increment and scrambled QMC like Sobol', Halton are more
+    performant [7]_.
+
+    To create a LHS of strength 2, the orthogonal array :math:`A` is
+    randomized by applying a random, bijective map of the set of symbols onto
+    itself. For example, in column 0, all 0s might become 2; in column 1,
+    all 0s might become 1, etc.
+    Then, for each column :math:`i` and symbol :math:`j`, we add a plain,
+    one-dimensional LHS of size :math:`p` to the subarray where
+    :math:`A^i = j`. The resulting matrix is finally divided by :math:`p`.
+
+    References
+    ----------
+    .. [1] Mckay et al., "A Comparison of Three Methods for Selecting Values
+       of Input Variables in the Analysis of Output from a Computer Code."
+       Technometrics, 1979.
+    .. [2] M. Stein, "Large sample properties of simulations using Latin
+       hypercube sampling." Technometrics 29, no. 2: 143-151, 1987.
+    .. [3] A. B. Owen, "Monte Carlo variance of scrambled net quadrature."
+       SIAM Journal on Numerical Analysis 34, no. 5: 1884-1910, 1997
+    .. [4]  Loh, W.-L. "On Latin hypercube sampling." The annals of statistics
+       24, no. 5: 2058-2080, 1996.
+    .. [5] Fang et al. "Design and modeling for computer experiments".
+       Computer Science and Data Analysis Series, 2006.
+    .. [6] Damblin et al., "Numerical studies of space filling designs:
+       optimization of Latin Hypercube Samples and subprojection properties."
+       Journal of Simulation, 2013.
+    .. [7] A. B. Owen , "Orthogonal arrays for computer experiments,
+       integration and visualization." Statistica Sinica, 1992.
+    .. [8] B. Tang, "Orthogonal Array-Based Latin Hypercubes."
+       Journal of the American Statistical Association, 1993.
+    .. [9] Seaholm, Susan K. et al. (1988). Latin hypercube sampling and the
+       sensitivity analysis of a Monte Carlo epidemic model. Int J Biomed
+       Comput, 23(1-2), 97-112. :doi:`10.1016/0020-7101(88)90067-0`
+
+    Examples
+    --------
+    Generate samples from a Latin hypercube generator.
+
+    >>> from scipy.stats import qmc
+    >>> sampler = qmc.LatinHypercube(d=2)
+    >>> sample = sampler.random(n=5)
+    >>> sample
+    array([[0.1545328 , 0.53664833], # random
+            [0.84052691, 0.06474907],
+            [0.52177809, 0.93343721],
+            [0.68033825, 0.36265316],
+            [0.26544879, 0.61163943]])
+
+    Compute the quality of the sample using the discrepancy criterion.
+
+    >>> qmc.discrepancy(sample)
+    0.0196... # random
+
+    Samples can be scaled to bounds.
+
+    >>> l_bounds = [0, 2]
+    >>> u_bounds = [10, 5]
+    >>> qmc.scale(sample, l_bounds, u_bounds)
+    array([[1.54532796, 3.609945 ], # random
+            [8.40526909, 2.1942472 ],
+            [5.2177809 , 4.80031164],
+            [6.80338249, 3.08795949],
+            [2.65448791, 3.83491828]])
+
+    Below are other examples showing alternative ways to construct LHS with
+    even better coverage of the space.
+
+    Using a base LHS as a baseline.
+
+    >>> sampler = qmc.LatinHypercube(d=2)
+    >>> sample = sampler.random(n=5)
+    >>> qmc.discrepancy(sample)
+    0.0196...  # random
+
+    Use the `optimization` keyword argument to produce a LHS with
+    lower discrepancy at higher computational cost.
+
+    >>> sampler = qmc.LatinHypercube(d=2, optimization="random-cd")
+    >>> sample = sampler.random(n=5)
+    >>> qmc.discrepancy(sample)
+    0.0176...  # random
+
+    Use the `strength` keyword argument to produce an orthogonal array based
+    LHS of strength 2. In this case, the number of sample points must be the
+    square of a prime number.
+
+    >>> sampler = qmc.LatinHypercube(d=2, strength=2)
+    >>> sample = sampler.random(n=9)
+    >>> qmc.discrepancy(sample)
+    0.00526...  # random
+
+    Options could be combined to produce an optimized centered
+    orthogonal array based LHS. After optimization, the result would not
+    be guaranteed to be of strength 2.
+
+    **Real-world example**
+
+    In [9]_, a Latin Hypercube sampling (LHS) strategy was used to sample a
+    parameter space to study the importance of each parameter of an epidemic
+    model. Such analysis is also called a sensitivity analysis.
+
+    Since the dimensionality of the problem is high (6), it is computationally
+    expensive to cover the space. When numerical experiments are costly, QMC
+    enables analysis that may not be possible if using a grid.
+
+    The six parameters of the model represented the probability of illness,
+    the probability of withdrawal, and four contact probabilities. The
+    authors assumed uniform distributions for all parameters and generated
+    50 samples.
+
+    Using `scipy.stats.qmc.LatinHypercube` to replicate the protocol,
+    the first step is to create a sample in the unit hypercube:
+
+    >>> from scipy.stats import qmc
+    >>> sampler = qmc.LatinHypercube(d=6)
+    >>> sample = sampler.random(n=50)
+
+    Then the sample can be scaled to the appropriate bounds:
+
+    >>> l_bounds = [0.000125, 0.01, 0.0025, 0.05, 0.47, 0.7]
+    >>> u_bounds = [0.000375, 0.03, 0.0075, 0.15, 0.87, 0.9]
+    >>> sample_scaled = qmc.scale(sample, l_bounds, u_bounds)
+
+    Such a sample was used to run the model 50 times, and a polynomial
+    response surface was constructed. This allowed the authors to study the
+    relative importance of each parameter across the range of possibilities
+    of every other parameter.
+
+    In this computer experiment, they showed a 14-fold reduction in the
+    number of samples required to maintain an error below 2% on their
+    response surface when compared to a grid sampling.
+
+    """
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self, d: IntNumber, *,
+        scramble: bool = True,
+        strength: int = 1,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None
+    ) -> None:
+        # Used in `scipy.integrate.qmc_quad`
+        self._init_quad = {'d': d, 'scramble': True, 'strength': strength,
+                           'optimization': optimization}
+        super()._initialize(d=d, rng=rng, optimization=optimization)
+        self.scramble = scramble
+
+        lhs_method_strength = {
+            1: self._random_lhs,
+            2: self._random_oa_lhs
+        }
+
+        try:
+            self.lhs_method: Callable = lhs_method_strength[strength]
+        except KeyError as exc:
+            message = (f"{strength!r} is not a valid strength. It must be one"
+                       f" of {set(lhs_method_strength)!r}")
+            raise ValueError(message) from exc
+
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        lhs = self.lhs_method(n)
+        return lhs
+
+    def _random_lhs(self, n: IntNumber = 1) -> np.ndarray:
+        """Base LHS algorithm."""
+        if not self.scramble:
+            samples: np.ndarray | float = 0.5
+        else:
+            samples = self.rng.uniform(size=(n, self.d))
+
+        perms = np.tile(np.arange(1, n + 1),
+                        (self.d, 1))  # type: ignore[arg-type]
+        for i in range(self.d):
+            self.rng.shuffle(perms[i, :])
+        perms = perms.T
+
+        samples = (perms - samples) / n
+        return samples
+
+    def _random_oa_lhs(self, n: IntNumber = 4) -> np.ndarray:
+        """Orthogonal array based LHS of strength 2."""
+        p = np.sqrt(n).astype(int)
+        n_row = p**2
+        n_col = p + 1
+
+        primes = primes_from_2_to(p + 1)
+        if p not in primes or n != n_row:
+            raise ValueError(
+                "n is not the square of a prime number. Close"
+                f" values are {primes[-2:]**2}"
+            )
+        if self.d > p + 1:
+            raise ValueError("n is too small for d. Must be n > (d-1)**2")
+
+        oa_sample = np.zeros(shape=(n_row, n_col), dtype=int)
+
+        # OA of strength 2
+        arrays = np.tile(np.arange(p), (2, 1))
+        oa_sample[:, :2] = np.stack(np.meshgrid(*arrays),
+                                    axis=-1).reshape(-1, 2)
+        for p_ in range(1, p):
+            oa_sample[:, 2+p_-1] = np.mod(oa_sample[:, 0]
+                                          + p_*oa_sample[:, 1], p)
+
+        # scramble the OA
+        oa_sample_ = np.empty(shape=(n_row, n_col), dtype=int)
+        for j in range(n_col):
+            perms = self.rng.permutation(p)
+            oa_sample_[:, j] = perms[oa_sample[:, j]]
+        
+        oa_sample = oa_sample_
+        # following is making a scrambled OA into an OA-LHS
+        oa_lhs_sample = np.zeros(shape=(n_row, n_col))
+        lhs_engine = LatinHypercube(d=1, scramble=self.scramble, strength=1,
+                                    rng=self.rng)  # type: QMCEngine
+        for j in range(n_col):
+            for k in range(p):
+                idx = oa_sample[:, j] == k
+                lhs = lhs_engine.random(p).flatten()
+                oa_lhs_sample[:, j][idx] = lhs + oa_sample[:, j][idx]
+
+        oa_lhs_sample /= p
+
+        return oa_lhs_sample[:, :self.d]
+
+
+class Sobol(QMCEngine):
+    """Engine for generating (scrambled) Sobol' sequences.
+
+    Sobol' sequences are low-discrepancy, quasi-random numbers. Points
+    can be drawn using two methods:
+
+    * `random_base2`: safely draw :math:`n=2^m` points. This method
+      guarantees the balance properties of the sequence.
+    * `random`: draw an arbitrary number of points from the
+      sequence. See warning below.
+
+    Parameters
+    ----------
+    d : int
+        Dimensionality of the sequence. Max dimensionality is 21201.
+    scramble : bool, optional
+        If True, use LMS+shift scrambling. Otherwise, no scrambling is done.
+        Default is True.
+    bits : int, optional
+        Number of bits of the generator. Control the maximum number of points
+        that can be generated, which is ``2**bits``. Maximal value is 64.
+        It does not correspond to the return type, which is always
+        ``np.float64`` to prevent points from repeating themselves.
+        Default is None, which for backward compatibility, corresponds to 30.
+
+        .. versionadded:: 1.9.0
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.10.0
+
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Notes
+    -----
+    Sobol' sequences [1]_ provide :math:`n=2^m` low discrepancy points in
+    :math:`[0,1)^{d}`. Scrambling them [3]_ makes them suitable for singular
+    integrands, provides a means of error estimation, and can improve their
+    rate of convergence. The scrambling strategy which is implemented is a
+    (left) linear matrix scramble (LMS) followed by a digital random shift
+    (LMS+shift) [2]_.
+
+    There are many versions of Sobol' sequences depending on their
+    'direction numbers'. This code uses direction numbers from [4]_. Hence,
+    the maximum number of dimension is 21201. The direction numbers have been
+    precomputed with search criterion 6 and can be retrieved at
+    https://web.maths.unsw.edu.au/~fkuo/sobol/.
+
+    .. warning::
+
+       Sobol' sequences are a quadrature rule and they lose their balance
+       properties if one uses a sample size that is not a power of 2, or skips
+       the first point, or thins the sequence [5]_.
+
+       If :math:`n=2^m` points are not enough then one should take :math:`2^M`
+       points for :math:`M>m`. When scrambling, the number R of independent
+       replicates does not have to be a power of 2.
+
+       Sobol' sequences are generated to some number :math:`B` of bits.
+       After :math:`2^B` points have been generated, the sequence would
+       repeat. Hence, an error is raised.
+       The number of bits can be controlled with the parameter `bits`.
+
+    References
+    ----------
+    .. [1] I. M. Sobol', "The distribution of points in a cube and the accurate
+       evaluation of integrals." Zh. Vychisl. Mat. i Mat. Phys., 7:784-802,
+       1967.
+    .. [2] J. Matousek, "On the L2-discrepancy for anchored boxes."
+       J. of Complexity 14, 527-556, 1998.
+    .. [3] Art B. Owen, "Scrambling Sobol and Niederreiter-Xing points."
+       Journal of Complexity, 14(4):466-489, December 1998.
+    .. [4] S. Joe and F. Y. Kuo, "Constructing sobol sequences with better
+       two-dimensional projections." SIAM Journal on Scientific Computing,
+       30(5):2635-2654, 2008.
+    .. [5] Art B. Owen, "On dropping the first Sobol' point."
+       :arxiv:`2008.08051`, 2020.
+
+    Examples
+    --------
+    Generate samples from a low discrepancy sequence of Sobol'.
+
+    >>> from scipy.stats import qmc
+    >>> sampler = qmc.Sobol(d=2, scramble=False)
+    >>> sample = sampler.random_base2(m=3)
+    >>> sample
+    array([[0.   , 0.   ],
+           [0.5  , 0.5  ],
+           [0.75 , 0.25 ],
+           [0.25 , 0.75 ],
+           [0.375, 0.375],
+           [0.875, 0.875],
+           [0.625, 0.125],
+           [0.125, 0.625]])
+
+    Compute the quality of the sample using the discrepancy criterion.
+
+    >>> qmc.discrepancy(sample)
+    0.013882107204860938
+
+    To continue an existing design, extra points can be obtained
+    by calling again `random_base2`. Alternatively, you can skip some
+    points like:
+
+    >>> _ = sampler.reset()
+    >>> _ = sampler.fast_forward(4)
+    >>> sample_continued = sampler.random_base2(m=2)
+    >>> sample_continued
+    array([[0.375, 0.375],
+           [0.875, 0.875],
+           [0.625, 0.125],
+           [0.125, 0.625]])
+
+    Finally, samples can be scaled to bounds.
+
+    >>> l_bounds = [0, 2]
+    >>> u_bounds = [10, 5]
+    >>> qmc.scale(sample_continued, l_bounds, u_bounds)
+    array([[3.75 , 3.125],
+           [8.75 , 4.625],
+           [6.25 , 2.375],
+           [1.25 , 3.875]])
+
+    """
+
+    MAXDIM: ClassVar[int] = _MAXDIM
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self, d: IntNumber, *, scramble: bool = True,
+        bits: IntNumber | None = None, rng: SeedType = None,
+        optimization: Literal["random-cd", "lloyd"] | None = None
+    ) -> None:
+        # Used in `scipy.integrate.qmc_quad`
+        self._init_quad = {'d': d, 'scramble': True, 'bits': bits,
+                           'optimization': optimization}
+
+        super()._initialize(d=d, optimization=optimization, rng=rng)
+        if d > self.MAXDIM:
+            raise ValueError(
+                f"Maximum supported dimensionality is {self.MAXDIM}."
+            )
+
+        self.bits = bits
+        self.dtype_i: type
+        self.scramble = scramble
+
+        if self.bits is None:
+            self.bits = 30
+
+        if self.bits <= 32:
+            self.dtype_i = np.uint32
+        elif 32 < self.bits <= 64:
+            self.dtype_i = np.uint64
+        else:
+            raise ValueError("Maximum supported 'bits' is 64")
+
+        self.maxn = 2**self.bits
+
+        # v is d x maxbit matrix
+        self._sv: np.ndarray = np.zeros((d, self.bits), dtype=self.dtype_i)
+        _initialize_v(self._sv, dim=d, bits=self.bits)
+
+        if not scramble:
+            self._shift: np.ndarray = np.zeros(d, dtype=self.dtype_i)
+        else:
+            # scramble self._shift and self._sv
+            self._scramble()
+
+        self._quasi = self._shift.copy()
+
+        # normalization constant with the largest possible number
+        # calculate in Python to not overflow int with 2**64
+        self._scale = 1.0 / 2 ** self.bits
+
+        self._first_point = (self._quasi * self._scale).reshape(1, -1)
+        # explicit casting to float64
+        self._first_point = self._first_point.astype(np.float64)
+
+    def _scramble(self) -> None:
+        """Scramble the sequence using LMS+shift."""
+        # Generate shift vector
+        self._shift = np.dot(
+            rng_integers(self.rng, 2, size=(self.d, self.bits),
+                         dtype=self.dtype_i),
+            2 ** np.arange(self.bits, dtype=self.dtype_i),
+        )
+        # Generate lower triangular matrices (stacked across dimensions)
+        ltm = np.tril(rng_integers(self.rng, 2,
+                                   size=(self.d, self.bits, self.bits),
+                                   dtype=self.dtype_i))
+        _cscramble(
+            dim=self.d, bits=self.bits,  # type: ignore[arg-type]
+            ltm=ltm, sv=self._sv
+        )
+
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        """Draw next point(s) in the Sobol' sequence.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            Sobol' sample.
+
+        """
+        sample: np.ndarray = np.empty((n, self.d), dtype=np.float64)
+
+        if n == 0:
+            return sample
+
+        total_n = self.num_generated + n
+        if total_n > self.maxn:
+            msg = (
+                f"At most 2**{self.bits}={self.maxn} distinct points can be "
+                f"generated. {self.num_generated} points have been previously "
+                f"generated, then: n={self.num_generated}+{n}={total_n}. "
+            )
+            if self.bits != 64:
+                msg += "Consider increasing `bits`."
+            raise ValueError(msg)
+
+        if self.num_generated == 0:
+            # verify n is 2**n
+            if not (n & (n - 1) == 0):
+                warnings.warn("The balance properties of Sobol' points require"
+                              " n to be a power of 2.", stacklevel=2)
+
+            if n == 1:
+                sample = self._first_point
+            else:
+                _draw(
+                    n=n - 1, num_gen=self.num_generated, dim=self.d,
+                    scale=self._scale, sv=self._sv, quasi=self._quasi,
+                    sample=sample
+                )
+                sample = np.concatenate(
+                    [self._first_point, sample]
+                )[:n]
+        else:
+            _draw(
+                n=n, num_gen=self.num_generated - 1, dim=self.d,
+                scale=self._scale, sv=self._sv, quasi=self._quasi,
+                sample=sample
+            )
+
+        return sample
+
+    def random_base2(self, m: IntNumber) -> np.ndarray:
+        """Draw point(s) from the Sobol' sequence.
+
+        This function draws :math:`n=2^m` points in the parameter space
+        ensuring the balance properties of the sequence.
+
+        Parameters
+        ----------
+        m : int
+            Logarithm in base 2 of the number of samples; i.e., n = 2^m.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            Sobol' sample.
+
+        """
+        n = 2 ** m
+
+        total_n = self.num_generated + n
+        if not (total_n & (total_n - 1) == 0):
+            raise ValueError('The balance properties of Sobol\' points require '
+                             f'n to be a power of 2. {self.num_generated} points '
+                             'have been previously generated, then: '
+                             f'n={self.num_generated}+2**{m}={total_n}. '
+                             'If you still want to do this, the function '
+                             '\'Sobol.random()\' can be used.'
+                             )
+
+        return self.random(n)
+
+    def reset(self) -> "Sobol":
+        """Reset the engine to base state.
+
+        Returns
+        -------
+        engine : Sobol
+            Engine reset to its base state.
+
+        """
+        super().reset()
+        self._quasi = self._shift.copy()
+        return self
+
+    def fast_forward(self, n: IntNumber) -> "Sobol":
+        """Fast-forward the sequence by `n` positions.
+
+        Parameters
+        ----------
+        n : int
+            Number of points to skip in the sequence.
+
+        Returns
+        -------
+        engine : Sobol
+            The fast-forwarded engine.
+
+        """
+        if self.num_generated == 0:
+            _fast_forward(
+                n=n - 1, num_gen=self.num_generated, dim=self.d,
+                sv=self._sv, quasi=self._quasi
+            )
+        else:
+            _fast_forward(
+                n=n, num_gen=self.num_generated - 1, dim=self.d,
+                sv=self._sv, quasi=self._quasi
+            )
+        self.num_generated += n
+        return self
+
+
+class PoissonDisk(QMCEngine):
+    """Poisson disk sampling.
+
+    Parameters
+    ----------
+    d : int
+        Dimension of the parameter space.
+    radius : float
+        Minimal distance to keep between points when sampling new candidates.
+    hypersphere : {"volume", "surface"}, optional
+        Sampling strategy to generate potential candidates to be added in the
+        final sample. Default is "volume".
+
+        * ``volume``: original Bridson algorithm as described in [1]_.
+          New candidates are sampled *within* the hypersphere.
+        * ``surface``: only sample the surface of the hypersphere.
+    ncandidates : int
+        Number of candidates to sample per iteration. More candidates result
+        in a denser sampling as more candidates can be accepted per iteration.
+    optimization : {None, "random-cd", "lloyd"}, optional
+        Whether to use an optimization scheme to improve the quality after
+        sampling. Note that this is a post-processing step that does not
+        guarantee that all properties of the sample will be conserved.
+        Default is None.
+
+        * ``random-cd``: random permutations of coordinates to lower the
+          centered discrepancy. The best sample based on the centered
+          discrepancy is constantly updated. Centered discrepancy-based
+          sampling shows better space-filling robustness toward 2D and 3D
+          subprojections compared to using other discrepancy measures.
+        * ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
+          The process converges to equally spaced samples.
+
+        .. versionadded:: 1.10.0
+
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    l_bounds, u_bounds : array_like (d,)
+        Lower and upper bounds of target sample data.
+
+    Notes
+    -----
+    Poisson disk sampling is an iterative sampling strategy. Starting from
+    a seed sample, `ncandidates` are sampled in the hypersphere
+    surrounding the seed. Candidates below a certain `radius` or outside the
+    domain are rejected. New samples are added in a pool of sample seed. The
+    process stops when the pool is empty or when the number of required
+    samples is reached.
+
+    The maximum number of point that a sample can contain is directly linked
+    to the `radius`. As the dimension of the space increases, a higher radius
+    spreads the points further and help overcome the curse of dimensionality.
+    See the :ref:`quasi monte carlo tutorial ` for more
+    details.
+
+    .. warning::
+
+       The algorithm is more suitable for low dimensions and sampling size
+       due to its iterative nature and memory requirements.
+       Selecting a small radius with a high dimension would
+       mean that the space could contain more samples than using lower
+       dimension or a bigger radius.
+
+    Some code taken from [2]_, written consent given on 31.03.2021
+    by the original author, Shamis, for free use in SciPy under
+    the 3-clause BSD.
+
+    References
+    ----------
+    .. [1] Robert Bridson, "Fast Poisson Disk Sampling in Arbitrary
+       Dimensions." SIGGRAPH, 2007.
+    .. [2] `StackOverflow `__.
+
+    Examples
+    --------
+    Generate a 2D sample using a `radius` of 0.2.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from matplotlib.collections import PatchCollection
+    >>> from scipy.stats import qmc
+    >>>
+    >>> rng = np.random.default_rng()
+    >>> radius = 0.2
+    >>> engine = qmc.PoissonDisk(d=2, radius=radius, rng=rng)
+    >>> sample = engine.random(20)
+
+    Visualizing the 2D sample and showing that no points are closer than
+    `radius`. ``radius/2`` is used to visualize non-intersecting circles.
+    If two samples are exactly at `radius` from each other, then their circle
+    of radius ``radius/2`` will touch.
+
+    >>> fig, ax = plt.subplots()
+    >>> _ = ax.scatter(sample[:, 0], sample[:, 1])
+    >>> circles = [plt.Circle((xi, yi), radius=radius/2, fill=False)
+    ...            for xi, yi in sample]
+    >>> collection = PatchCollection(circles, match_original=True)
+    >>> ax.add_collection(collection)
+    >>> _ = ax.set(aspect='equal', xlabel=r'$x_1$', ylabel=r'$x_2$',
+    ...            xlim=[0, 1], ylim=[0, 1])
+    >>> plt.show()
+
+    Such visualization can be seen as circle packing: how many circle can
+    we put in the space. It is a np-hard problem. The method `fill_space`
+    can be used to add samples until no more samples can be added. This is
+    a hard problem and parameters may need to be adjusted manually. Beware of
+    the dimension: as the dimensionality increases, the number of samples
+    required to fill the space increases exponentially
+    (curse-of-dimensionality).
+
+    """
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self,
+        d: IntNumber,
+        *,
+        radius: DecimalNumber = 0.05,
+        hypersphere: Literal["volume", "surface"] = "volume",
+        ncandidates: IntNumber = 30,
+        optimization: Literal["random-cd", "lloyd"] | None = None,
+        rng: SeedType = None,
+        l_bounds: "npt.ArrayLike | None" = None,
+        u_bounds: "npt.ArrayLike | None" = None,
+    ) -> None:
+        # Used in `scipy.integrate.qmc_quad`
+        self._init_quad = {'d': d, 'radius': radius,
+                           'hypersphere': hypersphere,
+                           'ncandidates': ncandidates,
+                           'optimization': optimization}
+        super()._initialize(d=d, optimization=optimization, rng=rng)
+
+        hypersphere_sample = {
+            "volume": self._hypersphere_volume_sample,
+            "surface": self._hypersphere_surface_sample
+        }
+
+        try:
+            self.hypersphere_method = hypersphere_sample[hypersphere]
+        except KeyError as exc:
+            message = (
+                f"{hypersphere!r} is not a valid hypersphere sampling"
+                f" method. It must be one of {set(hypersphere_sample)!r}")
+            raise ValueError(message) from exc
+
+        # size of the sphere from which the samples are drawn relative to the
+        # size of a disk (radius)
+        # for the surface sampler, all new points are almost exactly 1 radius
+        # away from at least one existing sample +eps to avoid rejection
+        self.radius_factor = 2 if hypersphere == "volume" else 1.001
+        self.radius = radius
+        self.radius_squared = self.radius**2
+
+        # sample to generate per iteration in the hypersphere around center
+        self.ncandidates = ncandidates
+        
+        if u_bounds is None:
+            u_bounds = np.ones(d)
+        if l_bounds is None:
+            l_bounds = np.zeros(d)
+        self.l_bounds, self.u_bounds = _validate_bounds(
+            l_bounds=l_bounds, u_bounds=u_bounds, d=int(d)
+        )
+
+        with np.errstate(divide='ignore'):
+            self.cell_size = self.radius / np.sqrt(self.d)
+            self.grid_size = (
+                np.ceil((self.u_bounds - self.l_bounds) / self.cell_size)
+            ).astype(int)
+
+        self._initialize_grid_pool()
+
+    def _initialize_grid_pool(self):
+        """Sampling pool and sample grid."""
+        self.sample_pool = []
+        # Positions of cells
+        # n-dim value for each grid cell
+        self.sample_grid = np.empty(
+            np.append(self.grid_size, self.d),
+            dtype=np.float32
+        )
+        # Initialise empty cells with NaNs
+        self.sample_grid.fill(np.nan)
+
+    def _random(
+        self, n: IntNumber = 1, *, workers: IntNumber = 1
+    ) -> np.ndarray:
+        """Draw `n` in the interval ``[l_bounds, u_bounds]``.
+
+        Note that it can return fewer samples if the space is full.
+        See the note section of the class.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        """
+        if n == 0 or self.d == 0:
+            return np.empty((n, self.d))
+
+        def in_limits(sample: np.ndarray) -> bool:
+            for i in range(self.d):
+                if (sample[i] > self.u_bounds[i] or sample[i] < self.l_bounds[i]):
+                    return False
+            return True
+
+        def in_neighborhood(candidate: np.ndarray, n: int = 2) -> bool:
+            """
+            Check if there are samples closer than ``radius_squared`` to the
+            `candidate` sample.
+            """
+            indices = ((candidate - self.l_bounds) / self.cell_size).astype(int)
+            ind_min = np.maximum(indices - n, self.l_bounds.astype(int))
+            ind_max = np.minimum(indices + n + 1, self.grid_size)
+
+            # Check if the center cell is empty
+            if not np.isnan(self.sample_grid[tuple(indices)][0]):
+                return True
+
+            a = [slice(ind_min[i], ind_max[i]) for i in range(self.d)]
+
+            # guards against: invalid value encountered in less as we are
+            # comparing with nan and returns False. Which is wanted.
+            with np.errstate(invalid='ignore'):
+                if np.any(
+                    np.sum(
+                        np.square(candidate - self.sample_grid[tuple(a)]),
+                        axis=self.d
+                    ) < self.radius_squared
+                ):
+                    return True
+
+            return False
+
+        def add_sample(candidate: np.ndarray) -> None:
+            self.sample_pool.append(candidate)
+            indices = ((candidate - self.l_bounds) / self.cell_size).astype(int)
+            self.sample_grid[tuple(indices)] = candidate
+            curr_sample.append(candidate)
+
+        curr_sample: list[np.ndarray] = []
+
+        if len(self.sample_pool) == 0:
+            # the pool is being initialized with a single random sample
+            add_sample(self.rng.uniform(self.l_bounds, self.u_bounds))
+            num_drawn = 1
+        else:
+            num_drawn = 0
+
+        # exhaust sample pool to have up to n sample
+        while len(self.sample_pool) and num_drawn < n:
+            # select a sample from the available pool
+            idx_center = rng_integers(self.rng, len(self.sample_pool))
+            center = self.sample_pool[idx_center]
+            del self.sample_pool[idx_center]
+
+            # generate candidates around the center sample
+            candidates = self.hypersphere_method(
+                center, self.radius * self.radius_factor, self.ncandidates
+            )
+
+            # keep candidates that satisfy some conditions
+            for candidate in candidates:
+                if in_limits(candidate) and not in_neighborhood(candidate):
+                    add_sample(candidate)
+
+                    num_drawn += 1
+                    if num_drawn >= n:
+                        break
+
+        self.num_generated += num_drawn
+        return np.array(curr_sample)
+
+    def fill_space(self) -> np.ndarray:
+        """Draw ``n`` samples in the interval ``[l_bounds, u_bounds]``.
+
+        Unlike `random`, this method will try to add points until
+        the space is full. Depending on ``candidates`` (and to a lesser extent
+        other parameters), some empty areas can still be present in the sample.
+
+        .. warning::
+
+           This can be extremely slow in high dimensions or if the
+           ``radius`` is very small-with respect to the dimensionality.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            QMC sample.
+
+        """
+        return self.random(np.inf)  # type: ignore[arg-type]
+
+    def reset(self) -> "PoissonDisk":
+        """Reset the engine to base state.
+
+        Returns
+        -------
+        engine : PoissonDisk
+            Engine reset to its base state.
+
+        """
+        super().reset()
+        self._initialize_grid_pool()
+        return self
+
+    def _hypersphere_volume_sample(
+        self, center: np.ndarray, radius: DecimalNumber,
+        candidates: IntNumber = 1
+    ) -> np.ndarray:
+        """Uniform sampling within hypersphere."""
+        # should remove samples within r/2
+        x = self.rng.standard_normal(size=(candidates, self.d))
+        ssq = np.sum(x**2, axis=1)
+        fr = radius * gammainc(self.d/2, ssq/2)**(1/self.d) / np.sqrt(ssq)
+        fr_tiled = np.tile(
+            fr.reshape(-1, 1), (1, self.d)  # type: ignore[arg-type]
+        )
+        p = center + np.multiply(x, fr_tiled)
+        return p
+
+    def _hypersphere_surface_sample(
+        self, center: np.ndarray, radius: DecimalNumber,
+        candidates: IntNumber = 1
+    ) -> np.ndarray:
+        """Uniform sampling on the hypersphere's surface."""
+        vec = self.rng.standard_normal(size=(candidates, self.d))
+        vec /= np.linalg.norm(vec, axis=1)[:, None]
+        p = center + np.multiply(vec, radius)
+        return p
+
+
+class MultivariateNormalQMC:
+    r"""QMC sampling from a multivariate Normal :math:`N(\mu, \Sigma)`.
+
+    Parameters
+    ----------
+    mean : array_like (d,)
+        The mean vector. Where ``d`` is the dimension.
+    cov : array_like (d, d), optional
+        The covariance matrix. If omitted, use `cov_root` instead.
+        If both `cov` and `cov_root` are omitted, use the identity matrix.
+    cov_root : array_like (d, d'), optional
+        A root decomposition of the covariance matrix, where ``d'`` may be less
+        than ``d`` if the covariance is not full rank. If omitted, use `cov`.
+    inv_transform : bool, optional
+        If True, use inverse transform instead of Box-Muller. Default is True.
+    engine : QMCEngine, optional
+        Quasi-Monte Carlo engine sampler. If None, `Sobol` is used.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Examples
+    --------
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import qmc
+    >>> dist = qmc.MultivariateNormalQMC(mean=[0, 5], cov=[[1, 0], [0, 1]])
+    >>> sample = dist.random(512)
+    >>> _ = plt.scatter(sample[:, 0], sample[:, 1])
+    >>> plt.show()
+
+    """
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+            self,
+            mean: "npt.ArrayLike",
+            cov: "npt.ArrayLike | None" = None,
+            *,
+            cov_root: "npt.ArrayLike | None" = None,
+            inv_transform: bool = True,
+            engine: QMCEngine | None = None,
+            rng: SeedType = None,
+    ) -> None:
+        mean = np.asarray(np.atleast_1d(mean))
+        d = mean.shape[0]
+        if cov is not None:
+            # covariance matrix provided
+            cov = np.asarray(np.atleast_2d(cov))
+            # check for square/symmetric cov matrix and mean vector has the
+            # same d
+            if not mean.shape[0] == cov.shape[0]:
+                raise ValueError("Dimension mismatch between mean and "
+                                 "covariance.")
+            if not np.allclose(cov, cov.transpose()):
+                raise ValueError("Covariance matrix is not symmetric.")
+            # compute Cholesky decomp; if it fails, do the eigen decomposition
+            try:
+                cov_root = np.linalg.cholesky(cov).transpose()
+            except np.linalg.LinAlgError:
+                eigval, eigvec = np.linalg.eigh(cov)
+                if not np.all(eigval >= -1.0e-8):
+                    raise ValueError("Covariance matrix not PSD.")
+                eigval = np.clip(eigval, 0.0, None)
+                cov_root = (eigvec * np.sqrt(eigval)).transpose()
+        elif cov_root is not None:
+            # root decomposition provided
+            cov_root = np.atleast_2d(cov_root)
+            if not mean.shape[0] == cov_root.shape[0]:
+                raise ValueError("Dimension mismatch between mean and "
+                                 "covariance.")
+        else:
+            # corresponds to identity covariance matrix
+            cov_root = None
+
+        self._inv_transform = inv_transform
+
+        if not inv_transform:
+            # to apply Box-Muller, we need an even number of dimensions
+            engine_dim = 2 * math.ceil(d / 2)
+        else:
+            engine_dim = d
+        if engine is None:
+            # Need this during SPEC 7 transition to prevent `RandomState`
+            # from being passed via `rng`.
+            kwarg = "seed" if isinstance(rng, np.random.RandomState) else "rng"
+            kwargs = {kwarg: rng}
+            self.engine = Sobol(
+                d=engine_dim, scramble=True, bits=30, **kwargs
+            )  # type: QMCEngine
+        elif isinstance(engine, QMCEngine):
+            if engine.d != engine_dim:
+                raise ValueError("Dimension of `engine` must be consistent"
+                                 " with dimensions of mean and covariance."
+                                 " If `inv_transform` is False, it must be"
+                                 " an even number.")
+            self.engine = engine
+        else:
+            raise ValueError("`engine` must be an instance of "
+                             "`scipy.stats.qmc.QMCEngine` or `None`.")
+
+        self._mean = mean
+        self._corr_matrix = cov_root
+
+        self._d = d
+
+    def random(self, n: IntNumber = 1) -> np.ndarray:
+        """Draw `n` QMC samples from the multivariate Normal.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            Sample.
+
+        """
+        base_samples = self._standard_normal_samples(n)
+        return self._correlate(base_samples)
+
+    def _correlate(self, base_samples: np.ndarray) -> np.ndarray:
+        if self._corr_matrix is not None:
+            return base_samples @ self._corr_matrix + self._mean
+        else:
+            # avoid multiplying with identity here
+            return base_samples + self._mean
+
+    def _standard_normal_samples(self, n: IntNumber = 1) -> np.ndarray:
+        """Draw `n` QMC samples from the standard Normal :math:`N(0, I_d)`.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        sample : array_like (n, d)
+            Sample.
+
+        """
+        # get base samples
+        samples = self.engine.random(n)
+        if self._inv_transform:
+            # apply inverse transform
+            # (values to close to 0/1 result in inf values)
+            return stats.norm.ppf(0.5 + (1 - 1e-10) * (samples - 0.5))  # type: ignore[attr-defined]  # noqa: E501
+        else:
+            # apply Box-Muller transform (note: indexes starting from 1)
+            even = np.arange(0, samples.shape[-1], 2)
+            Rs = np.sqrt(-2 * np.log(samples[:, even]))
+            thetas = 2 * math.pi * samples[:, 1 + even]
+            cos = np.cos(thetas)
+            sin = np.sin(thetas)
+            transf_samples = np.stack([Rs * cos, Rs * sin],
+                                      -1).reshape(n, -1)
+            # make sure we only return the number of dimension requested
+            return transf_samples[:, : self._d]
+
+
+class MultinomialQMC:
+    r"""QMC sampling from a multinomial distribution.
+
+    Parameters
+    ----------
+    pvals : array_like (k,)
+        Vector of probabilities of size ``k``, where ``k`` is the number
+        of categories. Elements must be non-negative and sum to 1.
+    n_trials : int
+        Number of trials.
+    engine : QMCEngine, optional
+        Quasi-Monte Carlo engine sampler. If None, `Sobol` is used.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `seed` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `seed` keyword will emit warnings. Following a
+            deprecation period, the `seed` keyword will be removed.
+
+    Examples
+    --------
+    Let's define 3 categories and for a given sample, the sum of the trials
+    of each category is 8. The number of trials per category is determined
+    by the `pvals` associated to each category.
+    Then, we sample this distribution 64 times.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import qmc
+    >>> dist = qmc.MultinomialQMC(
+    ...     pvals=[0.2, 0.4, 0.4], n_trials=10, engine=qmc.Halton(d=1)
+    ... )
+    >>> sample = dist.random(64)
+
+    We can plot the sample and verify that the median of number of trials
+    for each category is following the `pvals`. That would be
+    ``pvals * n_trials = [2, 4, 4]``.
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.yaxis.get_major_locator().set_params(integer=True)
+    >>> _ = ax.boxplot(sample)
+    >>> ax.set(xlabel="Categories", ylabel="Trials")
+    >>> plt.show()
+
+    """
+
+    @_transition_to_rng('seed', replace_doc=False)
+    def __init__(
+        self,
+        pvals: "npt.ArrayLike",
+        n_trials: IntNumber,
+        *,
+        engine: QMCEngine | None = None,
+        rng: SeedType = None,
+    ) -> None:
+        self.pvals = np.atleast_1d(np.asarray(pvals))
+        if np.min(pvals) < 0:
+            raise ValueError('Elements of pvals must be non-negative.')
+        if not np.isclose(np.sum(pvals), 1):
+            raise ValueError('Elements of pvals must sum to 1.')
+        self.n_trials = n_trials
+        if engine is None:
+            # Need this during SPEC 7 transition to prevent `RandomState`
+            # from being passed via `rng`.
+            kwarg = "seed" if isinstance(rng, np.random.RandomState) else "rng"
+            kwargs = {kwarg: rng}
+            self.engine = Sobol(
+                d=1, scramble=True, bits=30, **kwargs
+            )  # type: QMCEngine
+        elif isinstance(engine, QMCEngine):
+            if engine.d != 1:
+                raise ValueError("Dimension of `engine` must be 1.")
+            self.engine = engine
+        else:
+            raise ValueError("`engine` must be an instance of "
+                             "`scipy.stats.qmc.QMCEngine` or `None`.")
+
+    def random(self, n: IntNumber = 1) -> np.ndarray:
+        """Draw `n` QMC samples from the multinomial distribution.
+
+        Parameters
+        ----------
+        n : int, optional
+            Number of samples to generate in the parameter space. Default is 1.
+
+        Returns
+        -------
+        samples : array_like (n, pvals)
+            Sample.
+
+        """
+        sample = np.empty((n, len(self.pvals)))
+        for i in range(n):
+            base_draws = self.engine.random(self.n_trials).ravel()
+            p_cumulative = np.empty_like(self.pvals, dtype=float)
+            _fill_p_cumulative(np.array(self.pvals, dtype=float), p_cumulative)
+            sample_ = np.zeros_like(self.pvals, dtype=np.intp)
+            _categorize(base_draws, p_cumulative, sample_)
+            sample[i] = sample_
+        return sample
+
+
+def _select_optimizer(
+    optimization: Literal["random-cd", "lloyd"] | None, config: dict
+) -> Callable | None:
+    """A factory for optimization methods."""
+    optimization_method: dict[str, Callable] = {
+        "random-cd": _random_cd,
+        "lloyd": _lloyd_centroidal_voronoi_tessellation
+    }
+
+    optimizer: partial | None
+    if optimization is not None:
+        try:
+            optimization = optimization.lower()  # type: ignore[assignment]
+            optimizer_ = optimization_method[optimization]
+        except KeyError as exc:
+            message = (f"{optimization!r} is not a valid optimization"
+                       f" method. It must be one of"
+                       f" {set(optimization_method)!r}")
+            raise ValueError(message) from exc
+
+        # config
+        optimizer = partial(optimizer_, **config)
+    else:
+        optimizer = None
+
+    return optimizer
+
+
+def _random_cd(
+    best_sample: np.ndarray, n_iters: int, n_nochange: int, rng: GeneratorType,
+    **kwargs: dict
+) -> np.ndarray:
+    """Optimal LHS on CD.
+
+    Create a base LHS and do random permutations of coordinates to
+    lower the centered discrepancy.
+    Because it starts with a normal LHS, it also works with the
+    `scramble` keyword argument.
+
+    Two stopping criterion are used to stop the algorithm: at most,
+    `n_iters` iterations are performed; or if there is no improvement
+    for `n_nochange` consecutive iterations.
+    """
+    del kwargs  # only use keywords which are defined, needed by factory
+
+    n, d = best_sample.shape
+
+    if d == 0 or n == 0:
+        return np.empty((n, d))
+
+    if d == 1 or n == 1:
+        # discrepancy measures are invariant under permuting factors and runs
+        return best_sample
+
+    best_disc = discrepancy(best_sample)
+
+    bounds = ([0, d - 1],
+              [0, n - 1],
+              [0, n - 1])
+
+    n_nochange_ = 0
+    n_iters_ = 0
+    while n_nochange_ < n_nochange and n_iters_ < n_iters:
+        n_iters_ += 1
+
+        col = rng_integers(rng, *bounds[0], endpoint=True)  # type: ignore[misc]
+        row_1 = rng_integers(rng, *bounds[1], endpoint=True)  # type: ignore[misc]
+        row_2 = rng_integers(rng, *bounds[2], endpoint=True)  # type: ignore[misc]
+        disc = _perturb_discrepancy(best_sample,
+                                    row_1, row_2, col,
+                                    best_disc)
+        if disc < best_disc:
+            best_sample[row_1, col], best_sample[row_2, col] = (
+                best_sample[row_2, col], best_sample[row_1, col])
+
+            best_disc = disc
+            n_nochange_ = 0
+        else:
+            n_nochange_ += 1
+
+    return best_sample
+
+
+def _l1_norm(sample: np.ndarray) -> float:
+    return distance.pdist(sample, 'cityblock').min()
+
+
+def _lloyd_iteration(
+    sample: np.ndarray,
+    decay: float,
+    qhull_options: str
+) -> np.ndarray:
+    """Lloyd-Max algorithm iteration.
+
+    Based on the implementation of Stéfan van der Walt:
+
+    https://github.com/stefanv/lloyd
+
+    which is:
+
+        Copyright (c) 2021-04-21 Stéfan van der Walt
+        https://github.com/stefanv/lloyd
+        MIT License
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample to iterate on.
+    decay : float
+        Relaxation decay. A positive value would move the samples toward
+        their centroid, and negative value would move them away.
+        1 would move the samples to their centroid.
+    qhull_options : str
+        Additional options to pass to Qhull. See Qhull manual
+        for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and
+        "Qbb Qc Qz Qj" otherwise.)
+
+    Returns
+    -------
+    sample : array_like (n, d)
+        The sample after an iteration of Lloyd's algorithm.
+
+    """
+    new_sample = np.empty_like(sample)
+
+    voronoi = Voronoi(sample, qhull_options=qhull_options)
+
+    for ii, idx in enumerate(voronoi.point_region):
+        # the region is a series of indices into self.voronoi.vertices
+        # remove samples at infinity, designated by index -1
+        region = [i for i in voronoi.regions[idx] if i != -1]
+
+        # get the vertices for this region
+        verts = voronoi.vertices[region]
+
+        # clipping would be wrong, we need to intersect
+        # verts = np.clip(verts, 0, 1)
+
+        # move samples towards centroids:
+        # Centroid in n-D is the mean for uniformly distributed nodes
+        # of a geometry.
+        centroid = np.mean(verts, axis=0)
+        new_sample[ii] = sample[ii] + (centroid - sample[ii]) * decay
+
+    # only update sample to centroid within the region
+    is_valid = np.all(np.logical_and(new_sample >= 0, new_sample <= 1), axis=1)
+    sample[is_valid] = new_sample[is_valid]
+
+    return sample
+
+
+def _lloyd_centroidal_voronoi_tessellation(
+    sample: "npt.ArrayLike",
+    *,
+    tol: DecimalNumber = 1e-5,
+    maxiter: IntNumber = 10,
+    qhull_options: str | None = None,
+    **kwargs: dict
+) -> np.ndarray:
+    """Approximate Centroidal Voronoi Tessellation.
+
+    Perturb samples in N-dimensions using Lloyd-Max algorithm.
+
+    Parameters
+    ----------
+    sample : array_like (n, d)
+        The sample to iterate on. With ``n`` the number of samples and ``d``
+        the dimension. Samples must be in :math:`[0, 1]^d`, with ``d>=2``.
+    tol : float, optional
+        Tolerance for termination. If the min of the L1-norm over the samples
+        changes less than `tol`, it stops the algorithm. Default is 1e-5.
+    maxiter : int, optional
+        Maximum number of iterations. It will stop the algorithm even if
+        `tol` is above the threshold.
+        Too many iterations tend to cluster the samples as a hypersphere.
+        Default is 10.
+    qhull_options : str, optional
+        Additional options to pass to Qhull. See Qhull manual
+        for details. (Default: "Qbb Qc Qz Qj Qx" for ndim > 4 and
+        "Qbb Qc Qz Qj" otherwise.)
+
+    Returns
+    -------
+    sample : array_like (n, d)
+        The sample after being processed by Lloyd-Max algorithm.
+
+    Notes
+    -----
+    Lloyd-Max algorithm is an iterative process with the purpose of improving
+    the dispersion of samples. For given sample: (i) compute a Voronoi
+    Tessellation; (ii) find the centroid of each Voronoi cell; (iii) move the
+    samples toward the centroid of their respective cell. See [1]_, [2]_.
+
+    A relaxation factor is used to control how fast samples can move at each
+    iteration. This factor is starting at 2 and ending at 1 after `maxiter`
+    following an exponential decay.
+
+    The process converges to equally spaced samples. It implies that measures
+    like the discrepancy could suffer from too many iterations. On the other
+    hand, L1 and L2 distances should improve. This is especially true with
+    QMC methods which tend to favor the discrepancy over other criteria.
+
+    .. note::
+
+        The current implementation does not intersect the Voronoi Tessellation
+        with the boundaries. This implies that for a low number of samples,
+        empirically below 20, no Voronoi cell is touching the boundaries.
+        Hence, samples cannot be moved close to the boundaries.
+
+        Further improvements could consider the samples at infinity so that
+        all boundaries are segments of some Voronoi cells. This would fix
+        the computation of the centroid position.
+
+    .. warning::
+
+       The Voronoi Tessellation step is expensive and quickly becomes
+       intractable with dimensions as low as 10 even for a sample
+       of size as low as 1000.
+
+    .. versionadded:: 1.9.0
+
+    References
+    ----------
+    .. [1] Lloyd. "Least Squares Quantization in PCM".
+       IEEE Transactions on Information Theory, 1982.
+    .. [2] Max J. "Quantizing for minimum distortion".
+       IEEE Transactions on Information Theory, 1960.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.spatial import distance
+    >>> from scipy.stats._qmc import _lloyd_centroidal_voronoi_tessellation
+    >>> rng = np.random.default_rng()
+    >>> sample = rng.random((128, 2))
+
+    .. note::
+
+        The samples need to be in :math:`[0, 1]^d`. `scipy.stats.qmc.scale`
+        can be used to scale the samples from their
+        original bounds to :math:`[0, 1]^d`. And back to their original bounds.
+
+    Compute the quality of the sample using the L1 criterion.
+
+    >>> def l1_norm(sample):
+    ...    return distance.pdist(sample, 'cityblock').min()
+
+    >>> l1_norm(sample)
+    0.00161...  # random
+
+    Now process the sample using Lloyd's algorithm and check the improvement
+    on the L1. The value should increase.
+
+    >>> sample = _lloyd_centroidal_voronoi_tessellation(sample)
+    >>> l1_norm(sample)
+    0.0278...  # random
+
+    """
+    del kwargs  # only use keywords which are defined, needed by factory
+
+    sample = np.asarray(sample).copy()
+
+    if not sample.ndim == 2:
+        raise ValueError('`sample` is not a 2D array')
+
+    if not sample.shape[1] >= 2:
+        raise ValueError('`sample` dimension is not >= 2')
+
+    # Checking that sample is within the hypercube
+    if (sample.max() > 1.) or (sample.min() < 0.):
+        raise ValueError('`sample` is not in unit hypercube')
+
+    if qhull_options is None:
+        qhull_options = 'Qbb Qc Qz QJ'
+
+        if sample.shape[1] >= 5:
+            qhull_options += ' Qx'
+
+    # Fit an exponential to be 2 at 0 and 1 at `maxiter`.
+    # The decay is used for relaxation.
+    # analytical solution for y=exp(-maxiter/x) - 0.1
+    root = -maxiter / np.log(0.1)
+    decay = [np.exp(-x / root)+0.9 for x in range(maxiter)]
+
+    l1_old = _l1_norm(sample=sample)
+    for i in range(maxiter):
+        sample = _lloyd_iteration(
+                sample=sample, decay=decay[i],
+                qhull_options=qhull_options,
+        )
+
+        l1_new = _l1_norm(sample=sample)
+
+        if abs(l1_new - l1_old) < tol:
+            break
+        else:
+            l1_old = l1_new
+
+    return sample
+
+
+def _validate_workers(workers: IntNumber = 1) -> IntNumber:
+    """Validate `workers` based on platform and value.
+
+    Parameters
+    ----------
+    workers : int, optional
+        Number of workers to use for parallel processing. If -1 is
+        given all CPU threads are used. Default is 1.
+
+    Returns
+    -------
+    Workers : int
+        Number of CPU used by the algorithm
+
+    """
+    workers = int(workers)
+    if workers == -1:
+        workers = os.cpu_count()  # type: ignore[assignment]
+        if workers is None:
+            raise NotImplementedError(
+                "Cannot determine the number of cpus using os.cpu_count(), "
+                "cannot use -1 for the number of workers"
+            )
+    elif workers <= 0:
+        raise ValueError(f"Invalid number of workers: {workers}, must be -1 "
+                         "or > 0")
+
+    return workers
+
+
+def _validate_bounds(
+    l_bounds: "npt.ArrayLike", u_bounds: "npt.ArrayLike", d: int
+) -> "tuple[npt.NDArray[np.generic], npt.NDArray[np.generic]]":
+    """Bounds input validation.
+
+    Parameters
+    ----------
+    l_bounds, u_bounds : array_like (d,)
+        Lower and upper bounds.
+    d : int
+        Dimension to use for broadcasting.
+
+    Returns
+    -------
+    l_bounds, u_bounds : array_like (d,)
+        Lower and upper bounds.
+
+    """
+    try:
+        lower = np.broadcast_to(l_bounds, d)
+        upper = np.broadcast_to(u_bounds, d)
+    except ValueError as exc:
+        msg = ("'l_bounds' and 'u_bounds' must be broadcastable and respect"
+               " the sample dimension")
+        raise ValueError(msg) from exc
+
+    if not np.all(lower < upper):
+        raise ValueError("Bounds are not consistent 'l_bounds' < 'u_bounds'")
+
+    return lower, upper
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_qmc_cy.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_qmc_cy.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..1006385a43179478a9a4a32ae5f825aa5b8b35c4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_qmc_cy.pyi
@@ -0,0 +1,54 @@
+import numpy as np
+from scipy._lib._util import DecimalNumber, IntNumber
+
+
+def _cy_wrapper_centered_discrepancy(
+        sample: np.ndarray, 
+        iterative: bool, 
+        workers: IntNumber,
+) -> float: ...
+
+
+def _cy_wrapper_wrap_around_discrepancy(
+        sample: np.ndarray,
+        iterative: bool, 
+        workers: IntNumber,
+) -> float: ...
+
+
+def _cy_wrapper_mixture_discrepancy(
+        sample: np.ndarray,
+        iterative: bool, 
+        workers: IntNumber,
+) -> float: ...
+
+
+def _cy_wrapper_l2_star_discrepancy(
+        sample: np.ndarray,
+        iterative: bool,
+        workers: IntNumber,
+) -> float: ...
+
+
+def _cy_wrapper_update_discrepancy(
+        x_new_view: np.ndarray,
+        sample_view: np.ndarray,
+        initial_disc: DecimalNumber,
+) -> float: ...
+
+
+def _cy_van_der_corput(
+        n: IntNumber,
+        base: IntNumber,
+        start_index: IntNumber,
+        workers: IntNumber,
+) -> np.ndarray: ...
+
+
+def _cy_van_der_corput_scrambled(
+        n: IntNumber,
+        base: IntNumber,
+        start_index: IntNumber,
+        permutations: np.ndarray,
+        workers: IntNumber,
+) -> np.ndarray: ...
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_qmvnt.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_qmvnt.py
new file mode 100644
index 0000000000000000000000000000000000000000..55da67a3b7220a5d7216188335273c96e8cf06f8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_qmvnt.py
@@ -0,0 +1,533 @@
+# Integration of multivariate normal and t distributions.
+
+# Adapted from the MATLAB original implementations by Dr. Alan Genz.
+
+#     http://www.math.wsu.edu/faculty/genz/software/software.html
+
+# Copyright (C) 2013, Alan Genz,  All rights reserved.
+# Python implementation is copyright (C) 2022, Robert Kern,  All rights
+# reserved.
+
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided the following conditions are met:
+#   1. Redistributions of source code must retain the above copyright
+#      notice, this list of conditions and the following disclaimer.
+#   2. Redistributions in binary form must reproduce the above copyright
+#      notice, this list of conditions and the following disclaimer in
+#      the documentation and/or other materials provided with the
+#      distribution.
+#   3. The contributor name(s) may not be used to endorse or promote
+#      products derived from this software without specific prior
+#      written permission.
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+import numpy as np
+
+from scipy.fft import fft, ifft
+from scipy.special import gammaincinv, ndtr, ndtri
+from scipy.stats._qmc import primes_from_2_to
+
+
+phi = ndtr
+phinv = ndtri
+
+
+def _factorize_int(n):
+    """Return a sorted list of the unique prime factors of a positive integer.
+    """
+    # NOTE: There are lots faster ways to do this, but this isn't terrible.
+    factors = set()
+    for p in primes_from_2_to(int(np.sqrt(n)) + 1):
+        while not (n % p):
+            factors.add(p)
+            n //= p
+        if n == 1:
+            break
+    if n != 1:
+        factors.add(n)
+    return sorted(factors)
+
+
+def _primitive_root(p):
+    """Compute a primitive root of the prime number `p`.
+
+    Used in the CBC lattice construction.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Primitive_root_modulo_n
+    """
+    # p is prime
+    pm = p - 1
+    factors = _factorize_int(pm)
+    n = len(factors)
+    r = 2
+    k = 0
+    while k < n:
+        d = pm // factors[k]
+        # pow() doesn't like numpy scalar types.
+        rd = pow(int(r), int(d), int(p))
+        if rd == 1:
+            r += 1
+            k = 0
+        else:
+            k += 1
+    return r
+
+
+def _cbc_lattice(n_dim, n_qmc_samples):
+    """Compute a QMC lattice generator using a Fast CBC construction.
+
+    Parameters
+    ----------
+    n_dim : int > 0
+        The number of dimensions for the lattice.
+    n_qmc_samples : int > 0
+        The desired number of QMC samples. This will be rounded down to the
+        nearest prime to enable the CBC construction.
+
+    Returns
+    -------
+    q : float array : shape=(n_dim,)
+        The lattice generator vector. All values are in the open interval
+        ``(0, 1)``.
+    actual_n_qmc_samples : int
+        The prime number of QMC samples that must be used with this lattice,
+        no more, no less.
+
+    References
+    ----------
+    .. [1] Nuyens, D. and Cools, R. "Fast Component-by-Component Construction,
+           a Reprise for Different Kernels", In H. Niederreiter and D. Talay,
+           editors, Monte-Carlo and Quasi-Monte Carlo Methods 2004,
+           Springer-Verlag, 2006, 371-385.
+    """
+    # Round down to the nearest prime number.
+    primes = primes_from_2_to(n_qmc_samples + 1)
+    n_qmc_samples = primes[-1]
+
+    bt = np.ones(n_dim)
+    gm = np.hstack([1.0, 0.8 ** np.arange(n_dim - 1)])
+    q = 1
+    w = 0
+    z = np.arange(1, n_dim + 1)
+    m = (n_qmc_samples - 1) // 2
+    g = _primitive_root(n_qmc_samples)
+    # Slightly faster way to compute perm[j] = pow(g, j, n_qmc_samples)
+    # Shame that we don't have modulo pow() implemented as a ufunc.
+    perm = np.ones(m, dtype=int)
+    for j in range(m - 1):
+        perm[j + 1] = (g * perm[j]) % n_qmc_samples
+    perm = np.minimum(n_qmc_samples - perm, perm)
+    pn = perm / n_qmc_samples
+    c = pn * pn - pn + 1.0 / 6
+    fc = fft(c)
+    for s in range(1, n_dim):
+        reordered = np.hstack([
+            c[:w+1][::-1],
+            c[w+1:m][::-1],
+        ])
+        q = q * (bt[s-1] + gm[s-1] * reordered)
+        w = ifft(fc * fft(q)).real.argmin()
+        z[s] = perm[w]
+    q = z / n_qmc_samples
+    return q, n_qmc_samples
+
+
+# Note: this function is not currently used or tested by any SciPy code. It is
+# included in this file to facilitate the development of a parameter for users
+# to set the desired CDF accuracy, but must be reviewed and tested before use.
+def _qauto(func, covar, low, high, rng, error=1e-3, limit=10_000, **kwds):
+    """Automatically rerun the integration to get the required error bound.
+
+    Parameters
+    ----------
+    func : callable
+        Either :func:`_qmvn` or :func:`_qmvt`.
+    covar, low, high : array
+        As specified in :func:`_qmvn` and :func:`_qmvt`.
+    rng : Generator, optional
+        default_rng(), yada, yada
+    error : float > 0
+        The desired error bound.
+    limit : int > 0:
+        The rough limit of the number of integration points to consider. The
+        integration will stop looping once this limit has been *exceeded*.
+    **kwds :
+        Other keyword arguments to pass to `func`. When using :func:`_qmvt`, be
+        sure to include ``nu=`` as one of these.
+
+    Returns
+    -------
+    prob : float
+        The estimated probability mass within the bounds.
+    est_error : float
+        3 times the standard error of the batch estimates.
+    n_samples : int
+        The number of integration points actually used.
+    """
+    n = len(covar)
+    n_samples = 0
+    if n == 1:
+        prob = phi(high) - phi(low)
+        # More or less
+        est_error = 1e-15
+    else:
+        mi = min(limit, n * 1000)
+        prob = 0.0
+        est_error = 1.0
+        ei = 0.0
+        while est_error > error and n_samples < limit:
+            mi = round(np.sqrt(2) * mi)
+            pi, ei, ni = func(mi, covar, low, high, rng=rng, **kwds)
+            n_samples += ni
+            wt = 1.0 / (1 + (ei / est_error)**2)
+            prob += wt * (pi - prob)
+            est_error = np.sqrt(wt) * ei
+    return prob, est_error, n_samples
+
+
+# Note: this function is not currently used or tested by any SciPy code. It is
+# included in this file to facilitate the resolution of gh-8367, gh-16142, and
+# possibly gh-14286, but must be reviewed and tested before use.
+def _qmvn(m, covar, low, high, rng, lattice='cbc', n_batches=10):
+    """Multivariate normal integration over box bounds.
+
+    Parameters
+    ----------
+    m : int > n_batches
+        The number of points to sample. This number will be divided into
+        `n_batches` batches that apply random offsets of the sampling lattice
+        for each batch in order to estimate the error.
+    covar : (n, n) float array
+        Possibly singular, positive semidefinite symmetric covariance matrix.
+    low, high : (n,) float array
+        The low and high integration bounds.
+    rng : Generator, optional
+        default_rng(), yada, yada
+    lattice : 'cbc' or callable
+        The type of lattice rule to use to construct the integration points.
+    n_batches : int > 0, optional
+        The number of QMC batches to apply.
+
+    Returns
+    -------
+    prob : float
+        The estimated probability mass within the bounds.
+    est_error : float
+        3 times the standard error of the batch estimates.
+    """
+    cho, lo, hi = _permuted_cholesky(covar, low, high)
+    n = cho.shape[0]
+    ct = cho[0, 0]
+    c = phi(lo[0] / ct)
+    d = phi(hi[0] / ct)
+    ci = c
+    dci = d - ci
+    prob = 0.0
+    error_var = 0.0
+    q, n_qmc_samples = _cbc_lattice(n - 1, max(m // n_batches, 1))
+    y = np.zeros((n - 1, n_qmc_samples))
+    i_samples = np.arange(n_qmc_samples) + 1
+    for j in range(n_batches):
+        c = np.full(n_qmc_samples, ci)
+        dc = np.full(n_qmc_samples, dci)
+        pv = dc.copy()
+        for i in range(1, n):
+            # Pseudorandomly-shifted lattice coordinate.
+            z = q[i - 1] * i_samples + rng.random()
+            # Fast remainder(z, 1.0)
+            z -= z.astype(int)
+            # Tent periodization transform.
+            x = abs(2 * z - 1)
+            y[i - 1, :] = phinv(c + x * dc)
+            s = cho[i, :i] @ y[:i, :]
+            ct = cho[i, i]
+            c = phi((lo[i] - s) / ct)
+            d = phi((hi[i] - s) / ct)
+            dc = d - c
+            pv = pv * dc
+        # Accumulate the mean and error variances with online formulations.
+        d = (pv.mean() - prob) / (j + 1)
+        prob += d
+        error_var = (j - 1) * error_var / (j + 1) + d * d
+    # Error bounds are 3 times the standard error of the estimates.
+    est_error = 3 * np.sqrt(error_var)
+    n_samples = n_qmc_samples * n_batches
+    return prob, est_error, n_samples
+
+
+# Note: this function is not currently used or tested by any SciPy code. It is
+# included in this file to facilitate the resolution of gh-8367, gh-16142, and
+# possibly gh-14286, but must be reviewed and tested before use.
+def _mvn_qmc_integrand(covar, low, high, use_tent=False):
+    """Transform the multivariate normal integration into a QMC integrand over
+    a unit hypercube.
+
+    The dimensionality of the resulting hypercube integration domain is one
+    less than the dimensionality of the original integrand. Note that this
+    transformation subsumes the integration bounds in order to account for
+    infinite bounds. The QMC integration one does with the returned integrand
+    should be on the unit hypercube.
+
+    Parameters
+    ----------
+    covar : (n, n) float array
+        Possibly singular, positive semidefinite symmetric covariance matrix.
+    low, high : (n,) float array
+        The low and high integration bounds.
+    use_tent : bool, optional
+        If True, then use tent periodization. Only helpful for lattice rules.
+
+    Returns
+    -------
+    integrand : Callable[[NDArray], NDArray]
+        The QMC-integrable integrand. It takes an
+        ``(n_qmc_samples, ndim_integrand)`` array of QMC samples in the unit
+        hypercube and returns the ``(n_qmc_samples,)`` evaluations of at these
+        QMC points.
+    ndim_integrand : int
+        The dimensionality of the integrand. Equal to ``n-1``.
+    """
+    cho, lo, hi = _permuted_cholesky(covar, low, high)
+    n = cho.shape[0]
+    ndim_integrand = n - 1
+    ct = cho[0, 0]
+    c = phi(lo[0] / ct)
+    d = phi(hi[0] / ct)
+    ci = c
+    dci = d - ci
+
+    def integrand(*zs):
+        ndim_qmc = len(zs)
+        n_qmc_samples = len(np.atleast_1d(zs[0]))
+        assert ndim_qmc == ndim_integrand
+        y = np.zeros((ndim_qmc, n_qmc_samples))
+        c = np.full(n_qmc_samples, ci)
+        dc = np.full(n_qmc_samples, dci)
+        pv = dc.copy()
+        for i in range(1, n):
+            if use_tent:
+                # Tent periodization transform.
+                x = abs(2 * zs[i-1] - 1)
+            else:
+                x = zs[i-1]
+            y[i - 1, :] = phinv(c + x * dc)
+            s = cho[i, :i] @ y[:i, :]
+            ct = cho[i, i]
+            c = phi((lo[i] - s) / ct)
+            d = phi((hi[i] - s) / ct)
+            dc = d - c
+            pv = pv * dc
+        return pv
+
+    return integrand, ndim_integrand
+
+
+def _qmvt(m, nu, covar, low, high, rng, lattice='cbc', n_batches=10):
+    """Multivariate t integration over box bounds.
+
+    Parameters
+    ----------
+    m : int > n_batches
+        The number of points to sample. This number will be divided into
+        `n_batches` batches that apply random offsets of the sampling lattice
+        for each batch in order to estimate the error.
+    nu : float >= 0
+        The shape parameter of the multivariate t distribution.
+    covar : (n, n) float array
+        Possibly singular, positive semidefinite symmetric covariance matrix.
+    low, high : (n,) float array
+        The low and high integration bounds.
+    rng : Generator, optional
+        default_rng(), yada, yada
+    lattice : 'cbc' or callable
+        The type of lattice rule to use to construct the integration points.
+    n_batches : int > 0, optional
+        The number of QMC batches to apply.
+
+    Returns
+    -------
+    prob : float
+        The estimated probability mass within the bounds.
+    est_error : float
+        3 times the standard error of the batch estimates.
+    n_samples : int
+        The number of samples actually used.
+    """
+    sn = max(1.0, np.sqrt(nu))
+    low = np.asarray(low, dtype=np.float64)
+    high = np.asarray(high, dtype=np.float64)
+    cho, lo, hi = _permuted_cholesky(covar, low / sn, high / sn)
+    n = cho.shape[0]
+    prob = 0.0
+    error_var = 0.0
+    q, n_qmc_samples = _cbc_lattice(n, max(m // n_batches, 1))
+    i_samples = np.arange(n_qmc_samples) + 1
+    for j in range(n_batches):
+        pv = np.ones(n_qmc_samples)
+        s = np.zeros((n, n_qmc_samples))
+        for i in range(n):
+            # Pseudorandomly-shifted lattice coordinate.
+            z = q[i] * i_samples + rng.random()
+            # Fast remainder(z, 1.0)
+            z -= z.astype(int)
+            # Tent periodization transform.
+            x = abs(2 * z - 1)
+            # FIXME: Lift the i==0 case out of the loop to make the logic
+            # easier to follow.
+            if i == 0:
+                # We'll use one of the QR variates to pull out the
+                # t-distribution scaling.
+                if nu > 0:
+                    r = np.sqrt(2 * gammaincinv(nu / 2, x))
+                else:
+                    r = np.ones_like(x)
+            else:
+                y = phinv(c + x * dc)  # noqa: F821
+                with np.errstate(invalid='ignore'):
+                    s[i:, :] += cho[i:, i - 1][:, np.newaxis] * y
+            si = s[i, :]
+
+            c = np.ones(n_qmc_samples)
+            d = np.ones(n_qmc_samples)
+            with np.errstate(invalid='ignore'):
+                lois = lo[i] * r - si
+                hiis = hi[i] * r - si
+            c[lois < -9] = 0.0
+            d[hiis < -9] = 0.0
+            lo_mask = abs(lois) < 9
+            hi_mask = abs(hiis) < 9
+            c[lo_mask] = phi(lois[lo_mask])
+            d[hi_mask] = phi(hiis[hi_mask])
+
+            dc = d - c
+            pv *= dc
+
+        # Accumulate the mean and error variances with online formulations.
+        d = (pv.mean() - prob) / (j + 1)
+        prob += d
+        error_var = (j - 1) * error_var / (j + 1) + d * d
+    # Error bounds are 3 times the standard error of the estimates.
+    est_error = 3 * np.sqrt(error_var)
+    n_samples = n_qmc_samples * n_batches
+    return prob, est_error, n_samples
+
+
+def _permuted_cholesky(covar, low, high, tol=1e-10):
+    """Compute a scaled, permuted Cholesky factor, with integration bounds.
+
+    The scaling and permuting of the dimensions accomplishes part of the
+    transformation of the original integration problem into a more numerically
+    tractable form. The lower-triangular Cholesky factor will then be used in
+    the subsequent integration. The integration bounds will be scaled and
+    permuted as well.
+
+    Parameters
+    ----------
+    covar : (n, n) float array
+        Possibly singular, positive semidefinite symmetric covariance matrix.
+    low, high : (n,) float array
+        The low and high integration bounds.
+    tol : float, optional
+        The singularity tolerance.
+
+    Returns
+    -------
+    cho : (n, n) float array
+        Lower Cholesky factor, scaled and permuted.
+    new_low, new_high : (n,) float array
+        The scaled and permuted low and high integration bounds.
+    """
+    # Make copies for outputting.
+    cho = np.array(covar, dtype=np.float64)
+    new_lo = np.array(low, dtype=np.float64)
+    new_hi = np.array(high, dtype=np.float64)
+    n = cho.shape[0]
+    if cho.shape != (n, n):
+        raise ValueError("expected a square symmetric array")
+    if new_lo.shape != (n,) or new_hi.shape != (n,):
+        raise ValueError(
+            "expected integration boundaries the same dimensions "
+            "as the covariance matrix"
+        )
+    # Scale by the sqrt of the diagonal.
+    dc = np.sqrt(np.maximum(np.diag(cho), 0.0))
+    # But don't divide by 0.
+    dc[dc == 0.0] = 1.0
+    new_lo /= dc
+    new_hi /= dc
+    cho /= dc
+    cho /= dc[:, np.newaxis]
+
+    y = np.zeros(n)
+    sqtp = np.sqrt(2 * np.pi)
+    for k in range(n):
+        epk = (k + 1) * tol
+        im = k
+        ck = 0.0
+        dem = 1.0
+        s = 0.0
+        lo_m = 0.0
+        hi_m = 0.0
+        for i in range(k, n):
+            if cho[i, i] > tol:
+                ci = np.sqrt(cho[i, i])
+                if i > 0:
+                    s = cho[i, :k] @ y[:k]
+                lo_i = (new_lo[i] - s) / ci
+                hi_i = (new_hi[i] - s) / ci
+                de = phi(hi_i) - phi(lo_i)
+                if de <= dem:
+                    ck = ci
+                    dem = de
+                    lo_m = lo_i
+                    hi_m = hi_i
+                    im = i
+        if im > k:
+            # Swap im and k
+            cho[im, im] = cho[k, k]
+            _swap_slices(cho, np.s_[im, :k], np.s_[k, :k])
+            _swap_slices(cho, np.s_[im + 1:, im], np.s_[im + 1:, k])
+            _swap_slices(cho, np.s_[k + 1:im, k], np.s_[im, k + 1:im])
+            _swap_slices(new_lo, k, im)
+            _swap_slices(new_hi, k, im)
+        if ck > epk:
+            cho[k, k] = ck
+            cho[k, k + 1:] = 0.0
+            for i in range(k + 1, n):
+                cho[i, k] /= ck
+                cho[i, k + 1:i + 1] -= cho[i, k] * cho[k + 1:i + 1, k]
+            if abs(dem) > tol:
+                y[k] = ((np.exp(-lo_m * lo_m / 2) - np.exp(-hi_m * hi_m / 2)) /
+                        (sqtp * dem))
+            else:
+                y[k] = (lo_m + hi_m) / 2
+                if lo_m < -10:
+                    y[k] = hi_m
+                elif hi_m > 10:
+                    y[k] = lo_m
+            cho[k, :k + 1] /= ck
+            new_lo[k] /= ck
+            new_hi[k] /= ck
+        else:
+            cho[k:, k] = 0.0
+            y[k] = (new_lo[k] + new_hi[k]) / 2
+    return cho, new_lo, new_hi
+
+
+def _swap_slices(x, slc1, slc2):
+    t = x[slc1].copy()
+    x[slc1] = x[slc2].copy()
+    x[slc2] = t
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..25728ead5f7ea277e6e94c359d5a5603b99eeb38
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__init__.py
@@ -0,0 +1,4 @@
+#
+from .rcont import rvs_rcont1, rvs_rcont2
+
+__all__ = ["rvs_rcont1", "rvs_rcont2"]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-310.pyc b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e71b7d0009361730a3424c63d41f87f044f67bb
Binary files /dev/null and b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-310.pyc differ
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_relative_risk.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_relative_risk.py
new file mode 100644
index 0000000000000000000000000000000000000000..51525fd28adb37c72b12106450e4178c786091b2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_relative_risk.py
@@ -0,0 +1,263 @@
+import operator
+from dataclasses import dataclass
+import numpy as np
+from scipy.special import ndtri
+from ._common import ConfidenceInterval
+
+
+def _validate_int(n, bound, name):
+    msg = f'{name} must be an integer not less than {bound}, but got {n!r}'
+    try:
+        n = operator.index(n)
+    except TypeError:
+        raise TypeError(msg) from None
+    if n < bound:
+        raise ValueError(msg)
+    return n
+
+
+@dataclass
+class RelativeRiskResult:
+    """
+    Result of `scipy.stats.contingency.relative_risk`.
+
+    Attributes
+    ----------
+    relative_risk : float
+        This is::
+
+            (exposed_cases/exposed_total) / (control_cases/control_total)
+
+    exposed_cases : int
+        The number of "cases" (i.e. occurrence of disease or other event
+        of interest) among the sample of "exposed" individuals.
+    exposed_total : int
+        The total number of "exposed" individuals in the sample.
+    control_cases : int
+        The number of "cases" among the sample of "control" or non-exposed
+        individuals.
+    control_total : int
+        The total number of "control" individuals in the sample.
+
+    Methods
+    -------
+    confidence_interval :
+        Compute the confidence interval for the relative risk estimate.
+    """
+
+    relative_risk: float
+    exposed_cases: int
+    exposed_total: int
+    control_cases: int
+    control_total: int
+
+    def confidence_interval(self, confidence_level=0.95):
+        """
+        Compute the confidence interval for the relative risk.
+
+        The confidence interval is computed using the Katz method
+        (i.e. "Method C" of [1]_; see also [2]_, section 3.1.2).
+
+        Parameters
+        ----------
+        confidence_level : float, optional
+            The confidence level to use for the confidence interval.
+            Default is 0.95.
+
+        Returns
+        -------
+        ci : ConfidenceInterval instance
+            The return value is an object with attributes ``low`` and
+            ``high`` that hold the confidence interval.
+
+        References
+        ----------
+        .. [1] D. Katz, J. Baptista, S. P. Azen and M. C. Pike, "Obtaining
+               confidence intervals for the risk ratio in cohort studies",
+               Biometrics, 34, 469-474 (1978).
+        .. [2] Hardeo Sahai and Anwer Khurshid, Statistics in Epidemiology,
+               CRC Press LLC, Boca Raton, FL, USA (1996).
+
+
+        Examples
+        --------
+        >>> from scipy.stats.contingency import relative_risk
+        >>> result = relative_risk(exposed_cases=10, exposed_total=75,
+        ...                        control_cases=12, control_total=225)
+        >>> result.relative_risk
+        2.5
+        >>> result.confidence_interval()
+        ConfidenceInterval(low=1.1261564003469628, high=5.549850800541033)
+        """
+        if not 0 <= confidence_level <= 1:
+            raise ValueError('confidence_level must be in the interval '
+                             '[0, 1].')
+
+        # Handle edge cases where either exposed_cases or control_cases
+        # is zero.  We follow the convention of the R function riskratio
+        # from the epitools library.
+        if self.exposed_cases == 0 and self.control_cases == 0:
+            # relative risk is nan.
+            return ConfidenceInterval(low=np.nan, high=np.nan)
+        elif self.exposed_cases == 0:
+            # relative risk is 0.
+            return ConfidenceInterval(low=0.0, high=np.nan)
+        elif self.control_cases == 0:
+            # relative risk is inf
+            return ConfidenceInterval(low=np.nan, high=np.inf)
+
+        alpha = 1 - confidence_level
+        z = ndtri(1 - alpha/2)
+        rr = self.relative_risk
+
+        # Estimate of the variance of log(rr) is
+        # var(log(rr)) = 1/exposed_cases - 1/exposed_total +
+        #                1/control_cases - 1/control_total
+        # and the standard error is the square root of that.
+        se = np.sqrt(1/self.exposed_cases - 1/self.exposed_total +
+                     1/self.control_cases - 1/self.control_total)
+        delta = z*se
+        katz_lo = rr*np.exp(-delta)
+        katz_hi = rr*np.exp(delta)
+        return ConfidenceInterval(low=katz_lo, high=katz_hi)
+
+
+def relative_risk(exposed_cases, exposed_total, control_cases, control_total):
+    """
+    Compute the relative risk (also known as the risk ratio).
+
+    This function computes the relative risk associated with a 2x2
+    contingency table ([1]_, section 2.2.3; [2]_, section 3.1.2). Instead
+    of accepting a table as an argument, the individual numbers that are
+    used to compute the relative risk are given as separate parameters.
+    This is to avoid the ambiguity of which row or column of the contingency
+    table corresponds to the "exposed" cases and which corresponds to the
+    "control" cases.  Unlike, say, the odds ratio, the relative risk is not
+    invariant under an interchange of the rows or columns.
+
+    Parameters
+    ----------
+    exposed_cases : nonnegative int
+        The number of "cases" (i.e. occurrence of disease or other event
+        of interest) among the sample of "exposed" individuals.
+    exposed_total : positive int
+        The total number of "exposed" individuals in the sample.
+    control_cases : nonnegative int
+        The number of "cases" among the sample of "control" or non-exposed
+        individuals.
+    control_total : positive int
+        The total number of "control" individuals in the sample.
+
+    Returns
+    -------
+    result : instance of `~scipy.stats._result_classes.RelativeRiskResult`
+        The object has the float attribute ``relative_risk``, which is::
+
+            rr = (exposed_cases/exposed_total) / (control_cases/control_total)
+
+        The object also has the method ``confidence_interval`` to compute
+        the confidence interval of the relative risk for a given confidence
+        level.
+
+    See Also
+    --------
+    odds_ratio
+
+    Notes
+    -----
+    The R package epitools has the function `riskratio`, which accepts
+    a table with the following layout::
+
+                        disease=0   disease=1
+        exposed=0 (ref)    n00         n01
+        exposed=1          n10         n11
+
+    With a 2x2 table in the above format, the estimate of the CI is
+    computed by `riskratio` when the argument method="wald" is given,
+    or with the function `riskratio.wald`.
+
+    For example, in a test of the incidence of lung cancer among a
+    sample of smokers and nonsmokers, the "exposed" category would
+    correspond to "is a smoker" and the "disease" category would
+    correspond to "has or had lung cancer".
+
+    To pass the same data to ``relative_risk``, use::
+
+        relative_risk(n11, n10 + n11, n01, n00 + n01)
+
+    .. versionadded:: 1.7.0
+
+    References
+    ----------
+    .. [1] Alan Agresti, An Introduction to Categorical Data Analysis
+           (second edition), Wiley, Hoboken, NJ, USA (2007).
+    .. [2] Hardeo Sahai and Anwer Khurshid, Statistics in Epidemiology,
+           CRC Press LLC, Boca Raton, FL, USA (1996).
+
+    Examples
+    --------
+    >>> from scipy.stats.contingency import relative_risk
+
+    This example is from Example 3.1 of [2]_.  The results of a heart
+    disease study are summarized in the following table::
+
+                 High CAT   Low CAT    Total
+                 --------   -------    -----
+        CHD         27         44        71
+        No CHD      95        443       538
+
+        Total      122        487       609
+
+    CHD is coronary heart disease, and CAT refers to the level of
+    circulating catecholamine.  CAT is the "exposure" variable, and
+    high CAT is the "exposed" category. So the data from the table
+    to be passed to ``relative_risk`` is::
+
+        exposed_cases = 27
+        exposed_total = 122
+        control_cases = 44
+        control_total = 487
+
+    >>> result = relative_risk(27, 122, 44, 487)
+    >>> result.relative_risk
+    2.4495156482861398
+
+    Find the confidence interval for the relative risk.
+
+    >>> result.confidence_interval(confidence_level=0.95)
+    ConfidenceInterval(low=1.5836990926700116, high=3.7886786315466354)
+
+    The interval does not contain 1, so the data supports the statement
+    that high CAT is associated with greater risk of CHD.
+    """
+    # Relative risk is a trivial calculation.  The nontrivial part is in the
+    # `confidence_interval` method of the RelativeRiskResult class.
+
+    exposed_cases = _validate_int(exposed_cases, 0, "exposed_cases")
+    exposed_total = _validate_int(exposed_total, 1, "exposed_total")
+    control_cases = _validate_int(control_cases, 0, "control_cases")
+    control_total = _validate_int(control_total, 1, "control_total")
+
+    if exposed_cases > exposed_total:
+        raise ValueError('exposed_cases must not exceed exposed_total.')
+    if control_cases > control_total:
+        raise ValueError('control_cases must not exceed control_total.')
+
+    if exposed_cases == 0 and control_cases == 0:
+        # relative risk is 0/0.
+        rr = np.nan
+    elif exposed_cases == 0:
+        # relative risk is 0/nonzero
+        rr = 0.0
+    elif control_cases == 0:
+        # relative risk is nonzero/0.
+        rr = np.inf
+    else:
+        p1 = exposed_cases / exposed_total
+        p2 = control_cases / control_total
+        rr = p1 / p2
+    return RelativeRiskResult(relative_risk=rr,
+                              exposed_cases=exposed_cases,
+                              exposed_total=exposed_total,
+                              control_cases=control_cases,
+                              control_total=control_total)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_resampling.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_resampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..4314ee353a22606b445288ea0182528777e627a2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_resampling.py
@@ -0,0 +1,2377 @@
+import warnings
+import numpy as np
+from itertools import combinations, permutations, product
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+import inspect
+
+from scipy._lib._util import (check_random_state, _rename_parameter, rng_integers,
+                              _transition_to_rng)
+from scipy._lib._array_api import array_namespace, is_numpy, xp_moveaxis_to_end
+from scipy.special import ndtr, ndtri, comb, factorial
+
+from ._common import ConfidenceInterval
+from ._axis_nan_policy import _broadcast_concatenate, _broadcast_arrays
+from ._warnings_errors import DegenerateDataWarning
+
+__all__ = ['bootstrap', 'monte_carlo_test', 'permutation_test']
+
+
+def _vectorize_statistic(statistic):
+    """Vectorize an n-sample statistic"""
+    # This is a little cleaner than np.nditer at the expense of some data
+    # copying: concatenate samples together, then use np.apply_along_axis
+    def stat_nd(*data, axis=0):
+        lengths = [sample.shape[axis] for sample in data]
+        split_indices = np.cumsum(lengths)[:-1]
+        z = _broadcast_concatenate(data, axis)
+
+        # move working axis to position 0 so that new dimensions in the output
+        # of `statistic` are _prepended_. ("This axis is removed, and replaced
+        # with new dimensions...")
+        z = np.moveaxis(z, axis, 0)
+
+        def stat_1d(z):
+            data = np.split(z, split_indices)
+            return statistic(*data)
+
+        return np.apply_along_axis(stat_1d, 0, z)[()]
+    return stat_nd
+
+
+def _jackknife_resample(sample, batch=None):
+    """Jackknife resample the sample. Only one-sample stats for now."""
+    n = sample.shape[-1]
+    batch_nominal = batch or n
+
+    for k in range(0, n, batch_nominal):
+        # col_start:col_end are the observations to remove
+        batch_actual = min(batch_nominal, n-k)
+
+        # jackknife - each row leaves out one observation
+        j = np.ones((batch_actual, n), dtype=bool)
+        np.fill_diagonal(j[:, k:k+batch_actual], False)
+        i = np.arange(n)
+        i = np.broadcast_to(i, (batch_actual, n))
+        i = i[j].reshape((batch_actual, n-1))
+
+        resamples = sample[..., i]
+        yield resamples
+
+
+def _bootstrap_resample(sample, n_resamples=None, rng=None):
+    """Bootstrap resample the sample."""
+    n = sample.shape[-1]
+
+    # bootstrap - each row is a random resample of original observations
+    i = rng_integers(rng, 0, n, (n_resamples, n))
+
+    resamples = sample[..., i]
+    return resamples
+
+
+def _percentile_of_score(a, score, axis):
+    """Vectorized, simplified `scipy.stats.percentileofscore`.
+    Uses logic of the 'mean' value of percentileofscore's kind parameter.
+
+    Unlike `stats.percentileofscore`, the percentile returned is a fraction
+    in [0, 1].
+    """
+    B = a.shape[axis]
+    return ((a < score).sum(axis=axis) + (a <= score).sum(axis=axis)) / (2 * B)
+
+
+def _percentile_along_axis(theta_hat_b, alpha):
+    """`np.percentile` with different percentile for each slice."""
+    # the difference between _percentile_along_axis and np.percentile is that
+    # np.percentile gets _all_ the qs for each axis slice, whereas
+    # _percentile_along_axis gets the q corresponding with each axis slice
+    shape = theta_hat_b.shape[:-1]
+    alpha = np.broadcast_to(alpha, shape)
+    percentiles = np.zeros_like(alpha, dtype=np.float64)
+    for indices, alpha_i in np.ndenumerate(alpha):
+        if np.isnan(alpha_i):
+            # e.g. when bootstrap distribution has only one unique element
+            msg = (
+                "The BCa confidence interval cannot be calculated."
+                " This problem is known to occur when the distribution"
+                " is degenerate or the statistic is np.min."
+            )
+            warnings.warn(DegenerateDataWarning(msg), stacklevel=3)
+            percentiles[indices] = np.nan
+        else:
+            theta_hat_b_i = theta_hat_b[indices]
+            percentiles[indices] = np.percentile(theta_hat_b_i, alpha_i)
+    return percentiles[()]  # return scalar instead of 0d array
+
+
+def _bca_interval(data, statistic, axis, alpha, theta_hat_b, batch):
+    """Bias-corrected and accelerated interval."""
+    # closely follows [1] 14.3 and 15.4 (Eq. 15.36)
+
+    # calculate z0_hat
+    theta_hat = np.asarray(statistic(*data, axis=axis))[..., None]
+    percentile = _percentile_of_score(theta_hat_b, theta_hat, axis=-1)
+    z0_hat = ndtri(percentile)
+
+    # calculate a_hat
+    theta_hat_ji = []  # j is for sample of data, i is for jackknife resample
+    for j, sample in enumerate(data):
+        # _jackknife_resample will add an axis prior to the last axis that
+        # corresponds with the different jackknife resamples. Do the same for
+        # each sample of the data to ensure broadcastability. We need to
+        # create a copy of the list containing the samples anyway, so do this
+        # in the loop to simplify the code. This is not the bottleneck...
+        samples = [np.expand_dims(sample, -2) for sample in data]
+        theta_hat_i = []
+        for jackknife_sample in _jackknife_resample(sample, batch):
+            samples[j] = jackknife_sample
+            broadcasted = _broadcast_arrays(samples, axis=-1)
+            theta_hat_i.append(statistic(*broadcasted, axis=-1))
+        theta_hat_ji.append(theta_hat_i)
+
+    theta_hat_ji = [np.concatenate(theta_hat_i, axis=-1)
+                    for theta_hat_i in theta_hat_ji]
+
+    n_j = [theta_hat_i.shape[-1] for theta_hat_i in theta_hat_ji]
+
+    theta_hat_j_dot = [theta_hat_i.mean(axis=-1, keepdims=True)
+                       for theta_hat_i in theta_hat_ji]
+
+    U_ji = [(n - 1) * (theta_hat_dot - theta_hat_i)
+            for theta_hat_dot, theta_hat_i, n
+            in zip(theta_hat_j_dot, theta_hat_ji, n_j)]
+
+    nums = [(U_i**3).sum(axis=-1)/n**3 for U_i, n in zip(U_ji, n_j)]
+    dens = [(U_i**2).sum(axis=-1)/n**2 for U_i, n in zip(U_ji, n_j)]
+    a_hat = 1/6 * sum(nums) / sum(dens)**(3/2)
+
+    # calculate alpha_1, alpha_2
+    z_alpha = ndtri(alpha)
+    z_1alpha = -z_alpha
+    num1 = z0_hat + z_alpha
+    alpha_1 = ndtr(z0_hat + num1/(1 - a_hat*num1))
+    num2 = z0_hat + z_1alpha
+    alpha_2 = ndtr(z0_hat + num2/(1 - a_hat*num2))
+    return alpha_1, alpha_2, a_hat  # return a_hat for testing
+
+
+def _bootstrap_iv(data, statistic, vectorized, paired, axis, confidence_level,
+                  alternative, n_resamples, batch, method, bootstrap_result,
+                  rng):
+    """Input validation and standardization for `bootstrap`."""
+
+    if vectorized not in {True, False, None}:
+        raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
+
+    if vectorized is None:
+        vectorized = 'axis' in inspect.signature(statistic).parameters
+
+    if not vectorized:
+        statistic = _vectorize_statistic(statistic)
+
+    axis_int = int(axis)
+    if axis != axis_int:
+        raise ValueError("`axis` must be an integer.")
+
+    n_samples = 0
+    try:
+        n_samples = len(data)
+    except TypeError:
+        raise ValueError("`data` must be a sequence of samples.")
+
+    if n_samples == 0:
+        raise ValueError("`data` must contain at least one sample.")
+
+    message = ("Ignoring the dimension specified by `axis`, arrays in `data` do not "
+               "have the same shape. Beginning in SciPy 1.16.0, `bootstrap` will "
+               "explicitly broadcast elements of `data` to the same shape (ignoring "
+               "`axis`) before performing the calculation. To avoid this warning in "
+               "the meantime, ensure that all samples have the same shape (except "
+               "potentially along `axis`).")
+    data = [np.atleast_1d(sample) for sample in data]
+    reduced_shapes = set()
+    for sample in data:
+        reduced_shape = list(sample.shape)
+        reduced_shape.pop(axis)
+        reduced_shapes.add(tuple(reduced_shape))
+    if len(reduced_shapes) != 1:
+        warnings.warn(message, FutureWarning, stacklevel=3)
+
+    data_iv = []
+    for sample in data:
+        if sample.shape[axis_int] <= 1:
+            raise ValueError("each sample in `data` must contain two or more "
+                             "observations along `axis`.")
+        sample = np.moveaxis(sample, axis_int, -1)
+        data_iv.append(sample)
+
+    if paired not in {True, False}:
+        raise ValueError("`paired` must be `True` or `False`.")
+
+    if paired:
+        n = data_iv[0].shape[-1]
+        for sample in data_iv[1:]:
+            if sample.shape[-1] != n:
+                message = ("When `paired is True`, all samples must have the "
+                           "same length along `axis`")
+                raise ValueError(message)
+
+        # to generate the bootstrap distribution for paired-sample statistics,
+        # resample the indices of the observations
+        def statistic(i, axis=-1, data=data_iv, unpaired_statistic=statistic):
+            data = [sample[..., i] for sample in data]
+            return unpaired_statistic(*data, axis=axis)
+
+        data_iv = [np.arange(n)]
+
+    confidence_level_float = float(confidence_level)
+
+    alternative = alternative.lower()
+    alternatives = {'two-sided', 'less', 'greater'}
+    if alternative not in alternatives:
+        raise ValueError(f"`alternative` must be one of {alternatives}")
+
+    n_resamples_int = int(n_resamples)
+    if n_resamples != n_resamples_int or n_resamples_int < 0:
+        raise ValueError("`n_resamples` must be a non-negative integer.")
+
+    if batch is None:
+        batch_iv = batch
+    else:
+        batch_iv = int(batch)
+        if batch != batch_iv or batch_iv <= 0:
+            raise ValueError("`batch` must be a positive integer or None.")
+
+    methods = {'percentile', 'basic', 'bca'}
+    method = method.lower()
+    if method not in methods:
+        raise ValueError(f"`method` must be in {methods}")
+
+    message = "`bootstrap_result` must have attribute `bootstrap_distribution'"
+    if (bootstrap_result is not None
+            and not hasattr(bootstrap_result, "bootstrap_distribution")):
+        raise ValueError(message)
+
+    message = ("Either `bootstrap_result.bootstrap_distribution.size` or "
+               "`n_resamples` must be positive.")
+    if ((not bootstrap_result or
+         not bootstrap_result.bootstrap_distribution.size)
+            and n_resamples_int == 0):
+        raise ValueError(message)
+
+    rng = check_random_state(rng)
+
+    return (data_iv, statistic, vectorized, paired, axis_int,
+            confidence_level_float, alternative, n_resamples_int, batch_iv,
+            method, bootstrap_result, rng)
+
+
+@dataclass
+class BootstrapResult:
+    """Result object returned by `scipy.stats.bootstrap`.
+
+    Attributes
+    ----------
+    confidence_interval : ConfidenceInterval
+        The bootstrap confidence interval as an instance of
+        `collections.namedtuple` with attributes `low` and `high`.
+    bootstrap_distribution : ndarray
+        The bootstrap distribution, that is, the value of `statistic` for
+        each resample. The last dimension corresponds with the resamples
+        (e.g. ``res.bootstrap_distribution.shape[-1] == n_resamples``).
+    standard_error : float or ndarray
+        The bootstrap standard error, that is, the sample standard
+        deviation of the bootstrap distribution.
+
+    """
+    confidence_interval: ConfidenceInterval
+    bootstrap_distribution: np.ndarray
+    standard_error: float | np.ndarray
+
+
+@_transition_to_rng('random_state')
+def bootstrap(data, statistic, *, n_resamples=9999, batch=None,
+              vectorized=None, paired=False, axis=0, confidence_level=0.95,
+              alternative='two-sided', method='BCa', bootstrap_result=None,
+              rng=None):
+    r"""
+    Compute a two-sided bootstrap confidence interval of a statistic.
+
+    When `method` is ``'percentile'`` and `alternative` is ``'two-sided'``,
+    a bootstrap confidence interval is computed according to the following
+    procedure.
+
+    1. Resample the data: for each sample in `data` and for each of
+       `n_resamples`, take a random sample of the original sample
+       (with replacement) of the same size as the original sample.
+
+    2. Compute the bootstrap distribution of the statistic: for each set of
+       resamples, compute the test statistic.
+
+    3. Determine the confidence interval: find the interval of the bootstrap
+       distribution that is
+
+       - symmetric about the median and
+       - contains `confidence_level` of the resampled statistic values.
+
+    While the ``'percentile'`` method is the most intuitive, it is rarely
+    used in practice. Two more common methods are available, ``'basic'``
+    ('reverse percentile') and ``'BCa'`` ('bias-corrected and accelerated');
+    they differ in how step 3 is performed.
+
+    If the samples in `data` are  taken at random from their respective
+    distributions :math:`n` times, the confidence interval returned by
+    `bootstrap` will contain the true value of the statistic for those
+    distributions approximately `confidence_level`:math:`\, \times \, n` times.
+
+    Parameters
+    ----------
+    data : sequence of array-like
+         Each element of `data` is a sample containing scalar observations from an
+         underlying distribution. Elements of `data` must be broadcastable to the
+         same shape (with the possible exception of the dimension specified by `axis`).
+
+         .. versionchanged:: 1.14.0
+             `bootstrap` will now emit a ``FutureWarning`` if the shapes of the
+             elements of `data` are not the same (with the exception of the dimension
+             specified by `axis`).
+             Beginning in SciPy 1.16.0, `bootstrap` will explicitly broadcast the
+             elements to the same shape (except along `axis`) before performing
+             the calculation.
+
+    statistic : callable
+        Statistic for which the confidence interval is to be calculated.
+        `statistic` must be a callable that accepts ``len(data)`` samples
+        as separate arguments and returns the resulting statistic.
+        If `vectorized` is set ``True``,
+        `statistic` must also accept a keyword argument `axis` and be
+        vectorized to compute the statistic along the provided `axis`.
+    n_resamples : int, default: ``9999``
+        The number of resamples performed to form the bootstrap distribution
+        of the statistic.
+    batch : int, optional
+        The number of resamples to process in each vectorized call to
+        `statistic`. Memory usage is O( `batch` * ``n`` ), where ``n`` is the
+        sample size. Default is ``None``, in which case ``batch = n_resamples``
+        (or ``batch = max(n_resamples, n)`` for ``method='BCa'``).
+    vectorized : bool, optional
+        If `vectorized` is set ``False``, `statistic` will not be passed
+        keyword argument `axis` and is expected to calculate the statistic
+        only for 1D samples. If ``True``, `statistic` will be passed keyword
+        argument `axis` and is expected to calculate the statistic along `axis`
+        when passed an ND sample array. If ``None`` (default), `vectorized`
+        will be set ``True`` if ``axis`` is a parameter of `statistic`. Use of
+        a vectorized statistic typically reduces computation time.
+    paired : bool, default: ``False``
+        Whether the statistic treats corresponding elements of the samples
+        in `data` as paired. If True, `bootstrap` resamples an array of
+        *indices* and uses the same indices for all arrays in `data`; otherwise,
+        `bootstrap` independently resamples the elements of each array.
+    axis : int, default: ``0``
+        The axis of the samples in `data` along which the `statistic` is
+        calculated.
+    confidence_level : float, default: ``0.95``
+        The confidence level of the confidence interval.
+    alternative : {'two-sided', 'less', 'greater'}, default: ``'two-sided'``
+        Choose ``'two-sided'`` (default) for a two-sided confidence interval,
+        ``'less'`` for a one-sided confidence interval with the lower bound
+        at ``-np.inf``, and ``'greater'`` for a one-sided confidence interval
+        with the upper bound at ``np.inf``. The other bound of the one-sided
+        confidence intervals is the same as that of a two-sided confidence
+        interval with `confidence_level` twice as far from 1.0; e.g. the upper
+        bound of a 95% ``'less'``  confidence interval is the same as the upper
+        bound of a 90% ``'two-sided'`` confidence interval.
+    method : {'percentile', 'basic', 'bca'}, default: ``'BCa'``
+        Whether to return the 'percentile' bootstrap confidence interval
+        (``'percentile'``), the 'basic' (AKA 'reverse') bootstrap confidence
+        interval (``'basic'``), or the bias-corrected and accelerated bootstrap
+        confidence interval (``'BCa'``).
+    bootstrap_result : BootstrapResult, optional
+        Provide the result object returned by a previous call to `bootstrap`
+        to include the previous bootstrap distribution in the new bootstrap
+        distribution. This can be used, for example, to change
+        `confidence_level`, change `method`, or see the effect of performing
+        additional resampling without repeating computations.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    res : BootstrapResult
+        An object with attributes:
+
+        confidence_interval : ConfidenceInterval
+            The bootstrap confidence interval as an instance of
+            `collections.namedtuple` with attributes `low` and `high`.
+        bootstrap_distribution : ndarray
+            The bootstrap distribution, that is, the value of `statistic` for
+            each resample. The last dimension corresponds with the resamples
+            (e.g. ``res.bootstrap_distribution.shape[-1] == n_resamples``).
+        standard_error : float or ndarray
+            The bootstrap standard error, that is, the sample standard
+            deviation of the bootstrap distribution.
+
+    Warns
+    -----
+    `~scipy.stats.DegenerateDataWarning`
+        Generated when ``method='BCa'`` and the bootstrap distribution is
+        degenerate (e.g. all elements are identical).
+
+    Notes
+    -----
+    Elements of the confidence interval may be NaN for ``method='BCa'`` if
+    the bootstrap distribution is degenerate (e.g. all elements are identical).
+    In this case, consider using another `method` or inspecting `data` for
+    indications that other analysis may be more appropriate (e.g. all
+    observations are identical).
+
+    References
+    ----------
+    .. [1] B. Efron and R. J. Tibshirani, An Introduction to the Bootstrap,
+       Chapman & Hall/CRC, Boca Raton, FL, USA (1993)
+    .. [2] Nathaniel E. Helwig, "Bootstrap Confidence Intervals",
+       http://users.stat.umn.edu/~helwig/notes/bootci-Notes.pdf
+    .. [3] Bootstrapping (statistics), Wikipedia,
+       https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29
+
+    Examples
+    --------
+    Suppose we have sampled data from an unknown distribution.
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng()
+    >>> from scipy.stats import norm
+    >>> dist = norm(loc=2, scale=4)  # our "unknown" distribution
+    >>> data = dist.rvs(size=100, random_state=rng)
+
+    We are interested in the standard deviation of the distribution.
+
+    >>> std_true = dist.std()      # the true value of the statistic
+    >>> print(std_true)
+    4.0
+    >>> std_sample = np.std(data)  # the sample statistic
+    >>> print(std_sample)
+    3.9460644295563863
+
+    The bootstrap is used to approximate the variability we would expect if we
+    were to repeatedly sample from the unknown distribution and calculate the
+    statistic of the sample each time. It does this by repeatedly resampling
+    values *from the original sample* with replacement and calculating the
+    statistic of each resample. This results in a "bootstrap distribution" of
+    the statistic.
+
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy.stats import bootstrap
+    >>> data = (data,)  # samples must be in a sequence
+    >>> res = bootstrap(data, np.std, confidence_level=0.9, rng=rng)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(res.bootstrap_distribution, bins=25)
+    >>> ax.set_title('Bootstrap Distribution')
+    >>> ax.set_xlabel('statistic value')
+    >>> ax.set_ylabel('frequency')
+    >>> plt.show()
+
+    The standard error quantifies this variability. It is calculated as the
+    standard deviation of the bootstrap distribution.
+
+    >>> res.standard_error
+    0.24427002125829136
+    >>> res.standard_error == np.std(res.bootstrap_distribution, ddof=1)
+    True
+
+    The bootstrap distribution of the statistic is often approximately normal
+    with scale equal to the standard error.
+
+    >>> x = np.linspace(3, 5)
+    >>> pdf = norm.pdf(x, loc=std_sample, scale=res.standard_error)
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(res.bootstrap_distribution, bins=25, density=True)
+    >>> ax.plot(x, pdf)
+    >>> ax.set_title('Normal Approximation of the Bootstrap Distribution')
+    >>> ax.set_xlabel('statistic value')
+    >>> ax.set_ylabel('pdf')
+    >>> plt.show()
+
+    This suggests that we could construct a 90% confidence interval on the
+    statistic based on quantiles of this normal distribution.
+
+    >>> norm.interval(0.9, loc=std_sample, scale=res.standard_error)
+    (3.5442759991341726, 4.3478528599786)
+
+    Due to central limit theorem, this normal approximation is accurate for a
+    variety of statistics and distributions underlying the samples; however,
+    the approximation is not reliable in all cases. Because `bootstrap` is
+    designed to work with arbitrary underlying distributions and statistics,
+    it uses more advanced techniques to generate an accurate confidence
+    interval.
+
+    >>> print(res.confidence_interval)
+    ConfidenceInterval(low=3.57655333533867, high=4.382043696342881)
+
+    If we sample from the original distribution 100 times and form a bootstrap
+    confidence interval for each sample, the confidence interval
+    contains the true value of the statistic approximately 90% of the time.
+
+    >>> n_trials = 100
+    >>> ci_contains_true_std = 0
+    >>> for i in range(n_trials):
+    ...    data = (dist.rvs(size=100, random_state=rng),)
+    ...    res = bootstrap(data, np.std, confidence_level=0.9,
+    ...                    n_resamples=999, rng=rng)
+    ...    ci = res.confidence_interval
+    ...    if ci[0] < std_true < ci[1]:
+    ...        ci_contains_true_std += 1
+    >>> print(ci_contains_true_std)
+    88
+
+    Rather than writing a loop, we can also determine the confidence intervals
+    for all 100 samples at once.
+
+    >>> data = (dist.rvs(size=(n_trials, 100), random_state=rng),)
+    >>> res = bootstrap(data, np.std, axis=-1, confidence_level=0.9,
+    ...                 n_resamples=999, rng=rng)
+    >>> ci_l, ci_u = res.confidence_interval
+
+    Here, `ci_l` and `ci_u` contain the confidence interval for each of the
+    ``n_trials = 100`` samples.
+
+    >>> print(ci_l[:5])
+    [3.86401283 3.33304394 3.52474647 3.54160981 3.80569252]
+    >>> print(ci_u[:5])
+    [4.80217409 4.18143252 4.39734707 4.37549713 4.72843584]
+
+    And again, approximately 90% contain the true value, ``std_true = 4``.
+
+    >>> print(np.sum((ci_l < std_true) & (std_true < ci_u)))
+    93
+
+    `bootstrap` can also be used to estimate confidence intervals of
+    multi-sample statistics. For example, to get a confidence interval
+    for the difference between means, we write a function that accepts
+    two sample arguments and returns only the statistic. The use of the
+    ``axis`` argument ensures that all mean calculations are perform in
+    a single vectorized call, which is faster than looping over pairs
+    of resamples in Python.
+
+    >>> def my_statistic(sample1, sample2, axis=-1):
+    ...     mean1 = np.mean(sample1, axis=axis)
+    ...     mean2 = np.mean(sample2, axis=axis)
+    ...     return mean1 - mean2
+
+    Here, we use the 'percentile' method with the default 95% confidence level.
+
+    >>> sample1 = norm.rvs(scale=1, size=100, random_state=rng)
+    >>> sample2 = norm.rvs(scale=2, size=100, random_state=rng)
+    >>> data = (sample1, sample2)
+    >>> res = bootstrap(data, my_statistic, method='basic', rng=rng)
+    >>> print(my_statistic(sample1, sample2))
+    0.16661030792089523
+    >>> print(res.confidence_interval)
+    ConfidenceInterval(low=-0.29087973240818693, high=0.6371338699912273)
+
+    The bootstrap estimate of the standard error is also available.
+
+    >>> print(res.standard_error)
+    0.238323948262459
+
+    Paired-sample statistics work, too. For example, consider the Pearson
+    correlation coefficient.
+
+    >>> from scipy.stats import pearsonr
+    >>> n = 100
+    >>> x = np.linspace(0, 10, n)
+    >>> y = x + rng.uniform(size=n)
+    >>> print(pearsonr(x, y)[0])  # element 0 is the statistic
+    0.9954306665125647
+
+    We wrap `pearsonr` so that it returns only the statistic, ensuring
+    that we use the `axis` argument because it is available.
+
+    >>> def my_statistic(x, y, axis=-1):
+    ...     return pearsonr(x, y, axis=axis)[0]
+
+    We call `bootstrap` using ``paired=True``.
+
+    >>> res = bootstrap((x, y), my_statistic, paired=True, rng=rng)
+    >>> print(res.confidence_interval)
+    ConfidenceInterval(low=0.9941504301315878, high=0.996377412215445)
+
+    The result object can be passed back into `bootstrap` to perform additional
+    resampling:
+
+    >>> len(res.bootstrap_distribution)
+    9999
+    >>> res = bootstrap((x, y), my_statistic, paired=True,
+    ...                 n_resamples=1000, rng=rng,
+    ...                 bootstrap_result=res)
+    >>> len(res.bootstrap_distribution)
+    10999
+
+    or to change the confidence interval options:
+
+    >>> res2 = bootstrap((x, y), my_statistic, paired=True,
+    ...                  n_resamples=0, rng=rng, bootstrap_result=res,
+    ...                  method='percentile', confidence_level=0.9)
+    >>> np.testing.assert_equal(res2.bootstrap_distribution,
+    ...                         res.bootstrap_distribution)
+    >>> res.confidence_interval
+    ConfidenceInterval(low=0.9941574828235082, high=0.9963781698210212)
+
+    without repeating computation of the original bootstrap distribution.
+
+    """
+    # Input validation
+    args = _bootstrap_iv(data, statistic, vectorized, paired, axis,
+                         confidence_level, alternative, n_resamples, batch,
+                         method, bootstrap_result, rng)
+    (data, statistic, vectorized, paired, axis, confidence_level,
+     alternative, n_resamples, batch, method, bootstrap_result,
+     rng) = args
+
+    theta_hat_b = ([] if bootstrap_result is None
+                   else [bootstrap_result.bootstrap_distribution])
+
+    batch_nominal = batch or n_resamples or 1
+
+    for k in range(0, n_resamples, batch_nominal):
+        batch_actual = min(batch_nominal, n_resamples-k)
+        # Generate resamples
+        resampled_data = []
+        for sample in data:
+            resample = _bootstrap_resample(sample, n_resamples=batch_actual,
+                                           rng=rng)
+            resampled_data.append(resample)
+
+        # Compute bootstrap distribution of statistic
+        theta_hat_b.append(statistic(*resampled_data, axis=-1))
+    theta_hat_b = np.concatenate(theta_hat_b, axis=-1)
+
+    # Calculate percentile interval
+    alpha = ((1 - confidence_level)/2 if alternative == 'two-sided'
+             else (1 - confidence_level))
+    if method == 'bca':
+        interval = _bca_interval(data, statistic, axis=-1, alpha=alpha,
+                                 theta_hat_b=theta_hat_b, batch=batch)[:2]
+        percentile_fun = _percentile_along_axis
+    else:
+        interval = alpha, 1-alpha
+
+        def percentile_fun(a, q):
+            return np.percentile(a=a, q=q, axis=-1)
+
+    # Calculate confidence interval of statistic
+    ci_l = percentile_fun(theta_hat_b, interval[0]*100)
+    ci_u = percentile_fun(theta_hat_b, interval[1]*100)
+    if method == 'basic':  # see [3]
+        theta_hat = statistic(*data, axis=-1)
+        ci_l, ci_u = 2*theta_hat - ci_u, 2*theta_hat - ci_l
+
+    if alternative == 'less':
+        ci_l = np.full_like(ci_l, -np.inf)
+    elif alternative == 'greater':
+        ci_u = np.full_like(ci_u, np.inf)
+
+    return BootstrapResult(confidence_interval=ConfidenceInterval(ci_l, ci_u),
+                           bootstrap_distribution=theta_hat_b,
+                           standard_error=np.std(theta_hat_b, ddof=1, axis=-1))
+
+
+def _monte_carlo_test_iv(data, rvs, statistic, vectorized, n_resamples,
+                         batch, alternative, axis):
+    """Input validation for `monte_carlo_test`."""
+    axis_int = int(axis)
+    if axis != axis_int:
+        raise ValueError("`axis` must be an integer.")
+
+    if vectorized not in {True, False, None}:
+        raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
+
+    if not isinstance(rvs, Sequence):
+        rvs = (rvs,)
+        data = (data,)
+    for rvs_i in rvs:
+        if not callable(rvs_i):
+            raise TypeError("`rvs` must be callable or sequence of callables.")
+
+    # At this point, `data` should be a sequence
+    # If it isn't, the user passed a sequence for `rvs` but not `data`
+    message = "If `rvs` is a sequence, `len(rvs)` must equal `len(data)`."
+    try:
+        len(data)
+    except TypeError as e:
+        raise ValueError(message) from e
+    if not len(rvs) == len(data):
+        raise ValueError(message)
+
+    if not callable(statistic):
+        raise TypeError("`statistic` must be callable.")
+
+    if vectorized is None:
+        try:
+            signature = inspect.signature(statistic).parameters
+        except ValueError as e:
+            message = (f"Signature inspection of {statistic=} failed; "
+                       "pass `vectorize` explicitly.")
+            raise ValueError(message) from e
+        vectorized = 'axis' in signature
+
+    xp = array_namespace(*data)
+
+    if not vectorized:
+        if is_numpy(xp):
+            statistic_vectorized = _vectorize_statistic(statistic)
+        else:
+            message = ("`statistic` must be vectorized (i.e. support an `axis` "
+                       f"argument) when `data` contains {xp.__name__} arrays.")
+            raise ValueError(message)
+    else:
+        statistic_vectorized = statistic
+
+    data = _broadcast_arrays(data, axis, xp=xp)
+    data_iv = []
+    for sample in data:
+        sample = xp.broadcast_to(sample, (1,)) if sample.ndim == 0 else sample
+        sample = xp_moveaxis_to_end(sample, axis_int, xp=xp)
+        data_iv.append(sample)
+
+    n_resamples_int = int(n_resamples)
+    if n_resamples != n_resamples_int or n_resamples_int <= 0:
+        raise ValueError("`n_resamples` must be a positive integer.")
+
+    if batch is None:
+        batch_iv = batch
+    else:
+        batch_iv = int(batch)
+        if batch != batch_iv or batch_iv <= 0:
+            raise ValueError("`batch` must be a positive integer or None.")
+
+    alternatives = {'two-sided', 'greater', 'less'}
+    alternative = alternative.lower()
+    if alternative not in alternatives:
+        raise ValueError(f"`alternative` must be in {alternatives}")
+
+    # Infer the desired p-value dtype based on the input types
+    min_float = getattr(xp, 'float16', xp.float32)
+    dtype = xp.result_type(*data_iv, min_float)
+
+    return (data_iv, rvs, statistic_vectorized, vectorized, n_resamples_int,
+            batch_iv, alternative, axis_int, dtype, xp)
+
+
+@dataclass
+class MonteCarloTestResult:
+    """Result object returned by `scipy.stats.monte_carlo_test`.
+
+    Attributes
+    ----------
+    statistic : float or ndarray
+        The observed test statistic of the sample.
+    pvalue : float or ndarray
+        The p-value for the given alternative.
+    null_distribution : ndarray
+        The values of the test statistic generated under the null
+        hypothesis.
+    """
+    statistic: float | np.ndarray
+    pvalue: float | np.ndarray
+    null_distribution: np.ndarray
+
+
+@_rename_parameter('sample', 'data')
+def monte_carlo_test(data, rvs, statistic, *, vectorized=None,
+                     n_resamples=9999, batch=None, alternative="two-sided",
+                     axis=0):
+    r"""Perform a Monte Carlo hypothesis test.
+
+    `data` contains a sample or a sequence of one or more samples. `rvs`
+    specifies the distribution(s) of the sample(s) in `data` under the null
+    hypothesis. The value of `statistic` for the given `data` is compared
+    against a Monte Carlo null distribution: the value of the statistic for
+    each of `n_resamples` sets of samples generated using `rvs`. This gives
+    the p-value, the probability of observing such an extreme value of the
+    test statistic under the null hypothesis.
+
+    Parameters
+    ----------
+    data : array-like or sequence of array-like
+        An array or sequence of arrays of observations.
+    rvs : callable or tuple of callables
+        A callable or sequence of callables that generates random variates
+        under the null hypothesis. Each element of `rvs` must be a callable
+        that accepts keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and
+        returns an N-d array sample of that shape. If `rvs` is a sequence, the
+        number of callables in `rvs` must match the number of samples in
+        `data`, i.e. ``len(rvs) == len(data)``. If `rvs` is a single callable,
+        `data` is treated as a single sample.
+    statistic : callable
+        Statistic for which the p-value of the hypothesis test is to be
+        calculated. `statistic` must be a callable that accepts a sample
+        (e.g. ``statistic(sample)``) or ``len(rvs)`` separate samples (e.g.
+        ``statistic(samples1, sample2)`` if `rvs` contains two callables and
+        `data` contains two samples) and returns the resulting statistic.
+        If `vectorized` is set ``True``, `statistic` must also accept a keyword
+        argument `axis` and be vectorized to compute the statistic along the
+        provided `axis` of the samples in `data`.
+    vectorized : bool, optional
+        If `vectorized` is set ``False``, `statistic` will not be passed
+        keyword argument `axis` and is expected to calculate the statistic
+        only for 1D samples. If ``True``, `statistic` will be passed keyword
+        argument `axis` and is expected to calculate the statistic along `axis`
+        when passed ND sample arrays. If ``None`` (default), `vectorized`
+        will be set ``True`` if ``axis`` is a parameter of `statistic`. Use of
+        a vectorized statistic typically reduces computation time.
+    n_resamples : int, default: 9999
+        Number of samples drawn from each of the callables of `rvs`.
+        Equivalently, the number statistic values under the null hypothesis
+        used as the Monte Carlo null distribution.
+    batch : int, optional
+        The number of Monte Carlo samples to process in each call to
+        `statistic`. Memory usage is O( `batch` * ``sample.size[axis]`` ). Default
+        is ``None``, in which case `batch` equals `n_resamples`.
+    alternative : {'two-sided', 'less', 'greater'}
+        The alternative hypothesis for which the p-value is calculated.
+        For each alternative, the p-value is defined as follows.
+
+        - ``'greater'`` : the percentage of the null distribution that is
+          greater than or equal to the observed value of the test statistic.
+        - ``'less'`` : the percentage of the null distribution that is
+          less than or equal to the observed value of the test statistic.
+        - ``'two-sided'`` : twice the smaller of the p-values above.
+
+    axis : int, default: 0
+        The axis of `data` (or each sample within `data`) over which to
+        calculate the statistic.
+
+    Returns
+    -------
+    res : MonteCarloTestResult
+        An object with attributes:
+
+        statistic : float or ndarray
+            The test statistic of the observed `data`.
+        pvalue : float or ndarray
+            The p-value for the given alternative.
+        null_distribution : ndarray
+            The values of the test statistic generated under the null
+            hypothesis.
+
+    .. warning::
+        The p-value is calculated by counting the elements of the null
+        distribution that are as extreme or more extreme than the observed
+        value of the statistic. Due to the use of finite precision arithmetic,
+        some statistic functions return numerically distinct values when the
+        theoretical values would be exactly equal. In some cases, this could
+        lead to a large error in the calculated p-value. `monte_carlo_test`
+        guards against this by considering elements in the null distribution
+        that are "close" (within a relative tolerance of 100 times the
+        floating point epsilon of inexact dtypes) to the observed
+        value of the test statistic as equal to the observed value of the
+        test statistic. However, the user is advised to inspect the null
+        distribution to assess whether this method of comparison is
+        appropriate, and if not, calculate the p-value manually.
+
+    References
+    ----------
+
+    .. [1] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be
+       Zero: Calculating Exact P-values When Permutations Are Randomly Drawn."
+       Statistical Applications in Genetics and Molecular Biology 9.1 (2010).
+
+    Examples
+    --------
+
+    Suppose we wish to test whether a small sample has been drawn from a normal
+    distribution. We decide that we will use the skew of the sample as a
+    test statistic, and we will consider a p-value of 0.05 to be statistically
+    significant.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> def statistic(x, axis):
+    ...     return stats.skew(x, axis)
+
+    After collecting our data, we calculate the observed value of the test
+    statistic.
+
+    >>> rng = np.random.default_rng()
+    >>> x = stats.skewnorm.rvs(a=1, size=50, random_state=rng)
+    >>> statistic(x, axis=0)
+    0.12457412450240658
+
+    To determine the probability of observing such an extreme value of the
+    skewness by chance if the sample were drawn from the normal distribution,
+    we can perform a Monte Carlo hypothesis test. The test will draw many
+    samples at random from their normal distribution, calculate the skewness
+    of each sample, and compare our original skewness against this
+    distribution to determine an approximate p-value.
+
+    >>> from scipy.stats import monte_carlo_test
+    >>> # because our statistic is vectorized, we pass `vectorized=True`
+    >>> rvs = lambda size: stats.norm.rvs(size=size, random_state=rng)
+    >>> res = monte_carlo_test(x, rvs, statistic, vectorized=True)
+    >>> print(res.statistic)
+    0.12457412450240658
+    >>> print(res.pvalue)
+    0.7012
+
+    The probability of obtaining a test statistic less than or equal to the
+    observed value under the null hypothesis is ~70%. This is greater than
+    our chosen threshold of 5%, so we cannot consider this to be significant
+    evidence against the null hypothesis.
+
+    Note that this p-value essentially matches that of
+    `scipy.stats.skewtest`, which relies on an asymptotic distribution of a
+    test statistic based on the sample skewness.
+
+    >>> stats.skewtest(x).pvalue
+    0.6892046027110614
+
+    This asymptotic approximation is not valid for small sample sizes, but
+    `monte_carlo_test` can be used with samples of any size.
+
+    >>> x = stats.skewnorm.rvs(a=1, size=7, random_state=rng)
+    >>> # stats.skewtest(x) would produce an error due to small sample
+    >>> res = monte_carlo_test(x, rvs, statistic, vectorized=True)
+
+    The Monte Carlo distribution of the test statistic is provided for
+    further investigation.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(res.null_distribution, bins=50)
+    >>> ax.set_title("Monte Carlo distribution of test statistic")
+    >>> ax.set_xlabel("Value of Statistic")
+    >>> ax.set_ylabel("Frequency")
+    >>> plt.show()
+
+    """
+    args = _monte_carlo_test_iv(data, rvs, statistic, vectorized,
+                                n_resamples, batch, alternative, axis)
+    (data, rvs, statistic, vectorized, n_resamples,
+     batch, alternative, axis, dtype, xp) = args
+
+    # Some statistics return plain floats; ensure they're at least a NumPy float
+    observed = xp.asarray(statistic(*data, axis=-1))
+    observed = observed[()] if observed.ndim == 0 else observed
+
+    n_observations = [sample.shape[-1] for sample in data]
+    batch_nominal = batch or n_resamples
+    null_distribution = []
+    for k in range(0, n_resamples, batch_nominal):
+        batch_actual = min(batch_nominal, n_resamples - k)
+        resamples = [rvs_i(size=(batch_actual, n_observations_i))
+                     for rvs_i, n_observations_i in zip(rvs, n_observations)]
+        null_distribution.append(statistic(*resamples, axis=-1))
+    null_distribution = xp.concat(null_distribution)
+    null_distribution = xp.reshape(null_distribution, [-1] + [1]*observed.ndim)
+
+    # relative tolerance for detecting numerically distinct but
+    # theoretically equal values in the null distribution
+    eps =  (0 if not xp.isdtype(observed.dtype, ('real floating'))
+            else xp.finfo(observed.dtype).eps*100)
+    gamma = xp.abs(eps * observed)
+
+    def less(null_distribution, observed):
+        cmps = null_distribution <= observed + gamma
+        cmps = xp.asarray(cmps, dtype=dtype)
+        pvalues = (xp.sum(cmps, axis=0, dtype=dtype) + 1.) / (n_resamples + 1.)
+        return pvalues
+
+    def greater(null_distribution, observed):
+        cmps = null_distribution >= observed - gamma
+        cmps = xp.asarray(cmps, dtype=dtype)
+        pvalues = (xp.sum(cmps, axis=0, dtype=dtype) + 1.) / (n_resamples + 1.)
+        return pvalues
+
+    def two_sided(null_distribution, observed):
+        pvalues_less = less(null_distribution, observed)
+        pvalues_greater = greater(null_distribution, observed)
+        pvalues = xp.minimum(pvalues_less, pvalues_greater) * 2
+        return pvalues
+
+    compare = {"less": less,
+               "greater": greater,
+               "two-sided": two_sided}
+
+    pvalues = compare[alternative](null_distribution, observed)
+    pvalues = xp.clip(pvalues, 0., 1.)
+
+    return MonteCarloTestResult(observed, pvalues, null_distribution)
+
+
+@dataclass
+class PowerResult:
+    """Result object returned by `scipy.stats.power`.
+
+    Attributes
+    ----------
+    power : float or ndarray
+        The estimated power.
+    pvalues : float or ndarray
+        The simulated p-values.
+    """
+    power: float | np.ndarray
+    pvalues: float | np.ndarray
+
+
+def _wrap_kwargs(fun):
+    """Wrap callable to accept arbitrary kwargs and ignore unused ones"""
+
+    try:
+        keys = set(inspect.signature(fun).parameters.keys())
+    except ValueError:
+        # NumPy Generator methods can't be inspected
+        keys = {'size'}
+
+    # Set keys=keys/fun=fun to avoid late binding gotcha
+    def wrapped_rvs_i(*args, keys=keys, fun=fun, **all_kwargs):
+        kwargs = {key: val for key, val in all_kwargs.items()
+                  if key in keys}
+        return fun(*args, **kwargs)
+    return wrapped_rvs_i
+
+
+def _power_iv(rvs, test, n_observations, significance, vectorized,
+              n_resamples, batch, kwargs):
+    """Input validation for `monte_carlo_test`."""
+
+    if vectorized not in {True, False, None}:
+        raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
+
+    if not isinstance(rvs, Sequence):
+        rvs = (rvs,)
+        n_observations = (n_observations,)
+    for rvs_i in rvs:
+        if not callable(rvs_i):
+            raise TypeError("`rvs` must be callable or sequence of callables.")
+
+    if not len(rvs) == len(n_observations):
+        message = ("If `rvs` is a sequence, `len(rvs)` "
+                   "must equal `len(n_observations)`.")
+        raise ValueError(message)
+
+    significance = np.asarray(significance)[()]
+    if (not np.issubdtype(significance.dtype, np.floating)
+            or np.min(significance) < 0 or np.max(significance) > 1):
+        raise ValueError("`significance` must contain floats between 0 and 1.")
+
+    kwargs = dict() if kwargs is None else kwargs
+    if not isinstance(kwargs, dict):
+        raise TypeError("`kwargs` must be a dictionary that maps keywords to arrays.")
+
+    vals = kwargs.values()
+    keys = kwargs.keys()
+
+    # Wrap callables to ignore unused keyword arguments
+    wrapped_rvs = [_wrap_kwargs(rvs_i) for rvs_i in rvs]
+
+    # Broadcast, then ravel nobs/kwarg combinations. In the end,
+    # `nobs` and `vals` have shape (# of combinations, number of variables)
+    tmp = np.asarray(np.broadcast_arrays(*n_observations, *vals))
+    shape = tmp.shape
+    if tmp.ndim == 1:
+        tmp = tmp[np.newaxis, :]
+    else:
+        tmp = tmp.reshape((shape[0], -1)).T
+    nobs, vals = tmp[:, :len(rvs)], tmp[:, len(rvs):]
+    nobs = nobs.astype(int)
+
+    if not callable(test):
+        raise TypeError("`test` must be callable.")
+
+    if vectorized is None:
+        vectorized = 'axis' in inspect.signature(test).parameters
+
+    if not vectorized:
+        test_vectorized = _vectorize_statistic(test)
+    else:
+        test_vectorized = test
+    # Wrap `test` function to ignore unused kwargs
+    test_vectorized = _wrap_kwargs(test_vectorized)
+
+    n_resamples_int = int(n_resamples)
+    if n_resamples != n_resamples_int or n_resamples_int <= 0:
+        raise ValueError("`n_resamples` must be a positive integer.")
+
+    if batch is None:
+        batch_iv = batch
+    else:
+        batch_iv = int(batch)
+        if batch != batch_iv or batch_iv <= 0:
+            raise ValueError("`batch` must be a positive integer or None.")
+
+    return (wrapped_rvs, test_vectorized, nobs, significance, vectorized,
+            n_resamples_int, batch_iv, vals, keys, shape[1:])
+
+
+def power(test, rvs, n_observations, *, significance=0.01, vectorized=None,
+          n_resamples=10000, batch=None, kwargs=None):
+    r"""Simulate the power of a hypothesis test under an alternative hypothesis.
+
+    Parameters
+    ----------
+    test : callable
+        Hypothesis test for which the power is to be simulated.
+        `test` must be a callable that accepts a sample (e.g. ``test(sample)``)
+        or ``len(rvs)`` separate samples (e.g. ``test(samples1, sample2)`` if
+        `rvs` contains two callables and `n_observations` contains two values)
+        and returns the p-value of the test.
+        If `vectorized` is set to ``True``, `test` must also accept a keyword
+        argument `axis` and be vectorized to perform the test along the
+        provided `axis` of the samples.
+        Any callable from `scipy.stats` with an `axis` argument that returns an
+        object with a `pvalue` attribute is also acceptable.
+    rvs : callable or tuple of callables
+        A callable or sequence of callables that generate(s) random variates
+        under the alternative hypothesis. Each element of `rvs` must accept
+        keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and return an
+        N-d array of that shape. If `rvs` is a sequence, the number of callables
+        in `rvs` must match the number of elements of `n_observations`, i.e.
+        ``len(rvs) == len(n_observations)``. If `rvs` is a single callable,
+        `n_observations` is treated as a single element.
+    n_observations : tuple of ints or tuple of integer arrays
+        If a sequence of ints, each is the sizes of a sample to be passed to `test`.
+        If a sequence of integer arrays, the power is simulated for each
+        set of corresponding sample sizes. See Examples.
+    significance : float or array_like of floats, default: 0.01
+        The threshold for significance; i.e., the p-value below which the
+        hypothesis test results will be considered as evidence against the null
+        hypothesis. Equivalently, the acceptable rate of Type I error under
+        the null hypothesis. If an array, the power is simulated for each
+        significance threshold.
+    kwargs : dict, optional
+        Keyword arguments to be passed to `rvs` and/or `test` callables.
+        Introspection is used to determine which keyword arguments may be
+        passed to each callable.
+        The value corresponding with each keyword must be an array.
+        Arrays must be broadcastable with one another and with each array in
+        `n_observations`. The power is simulated for each set of corresponding
+        sample sizes and arguments. See Examples.
+    vectorized : bool, optional
+        If `vectorized` is set to ``False``, `test` will not be passed keyword
+        argument `axis` and is expected to perform the test only for 1D samples.
+        If ``True``, `test` will be passed keyword argument `axis` and is
+        expected to perform the test along `axis` when passed N-D sample arrays.
+        If ``None`` (default), `vectorized` will be set ``True`` if ``axis`` is
+        a parameter of `test`. Use of a vectorized test typically reduces
+        computation time.
+    n_resamples : int, default: 10000
+        Number of samples drawn from each of the callables of `rvs`.
+        Equivalently, the number tests performed under the alternative
+        hypothesis to approximate the power.
+    batch : int, optional
+        The number of samples to process in each call to `test`. Memory usage is
+        proportional to the product of `batch` and the largest sample size. Default
+        is ``None``, in which case `batch` equals `n_resamples`.
+
+    Returns
+    -------
+    res : PowerResult
+        An object with attributes:
+
+        power : float or ndarray
+            The estimated power against the alternative.
+        pvalues : ndarray
+            The p-values observed under the alternative hypothesis.
+
+    Notes
+    -----
+    The power is simulated as follows:
+
+    - Draw many random samples (or sets of samples), each of the size(s)
+      specified by `n_observations`, under the alternative specified by
+      `rvs`.
+    - For each sample (or set of samples), compute the p-value according to
+      `test`. These p-values are recorded in the ``pvalues`` attribute of
+      the result object.
+    - Compute the proportion of p-values that are less than the `significance`
+      level. This is the power recorded in the ``power`` attribute of the
+      result object.
+
+    Suppose that `significance` is an array with shape ``shape1``, the elements
+    of `kwargs` and `n_observations` are mutually broadcastable to shape ``shape2``,
+    and `test` returns an array of p-values of shape ``shape3``. Then the result
+    object ``power`` attribute will be of shape ``shape1 + shape2 + shape3``, and
+    the ``pvalues`` attribute will be of shape ``shape2 + shape3 + (n_resamples,)``.
+
+    Examples
+    --------
+    Suppose we wish to simulate the power of the independent sample t-test
+    under the following conditions:
+
+    - The first sample has 10 observations drawn from a normal distribution
+      with mean 0.
+    - The second sample has 12 observations drawn from a normal distribution
+      with mean 1.0.
+    - The threshold on p-values for significance is 0.05.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(2549598345528)
+    >>>
+    >>> test = stats.ttest_ind
+    >>> n_observations = (10, 12)
+    >>> rvs1 = rng.normal
+    >>> rvs2 = lambda size: rng.normal(loc=1, size=size)
+    >>> rvs = (rvs1, rvs2)
+    >>> res = stats.power(test, rvs, n_observations, significance=0.05)
+    >>> res.power
+    0.6116
+
+    With samples of size 10 and 12, respectively, the power of the t-test
+    with a significance threshold of 0.05 is approximately 60% under the chosen
+    alternative. We can investigate the effect of sample size on the power
+    by passing sample size arrays.
+
+    >>> import matplotlib.pyplot as plt
+    >>> nobs_x = np.arange(5, 21)
+    >>> nobs_y = nobs_x
+    >>> n_observations = (nobs_x, nobs_y)
+    >>> res = stats.power(test, rvs, n_observations, significance=0.05)
+    >>> ax = plt.subplot()
+    >>> ax.plot(nobs_x, res.power)
+    >>> ax.set_xlabel('Sample Size')
+    >>> ax.set_ylabel('Simulated Power')
+    >>> ax.set_title('Simulated Power of `ttest_ind` with Equal Sample Sizes')
+    >>> plt.show()
+
+    Alternatively, we can investigate the impact that effect size has on the power.
+    In this case, the effect size is the location of the distribution underlying
+    the second sample.
+
+    >>> n_observations = (10, 12)
+    >>> loc = np.linspace(0, 1, 20)
+    >>> rvs2 = lambda size, loc: rng.normal(loc=loc, size=size)
+    >>> rvs = (rvs1, rvs2)
+    >>> res = stats.power(test, rvs, n_observations, significance=0.05,
+    ...                   kwargs={'loc': loc})
+    >>> ax = plt.subplot()
+    >>> ax.plot(loc, res.power)
+    >>> ax.set_xlabel('Effect Size')
+    >>> ax.set_ylabel('Simulated Power')
+    >>> ax.set_title('Simulated Power of `ttest_ind`, Varying Effect Size')
+    >>> plt.show()
+
+    We can also use `power` to estimate the Type I error rate (also referred to by the
+    ambiguous term "size") of a test and assess whether it matches the nominal level.
+    For example, the null hypothesis of `jarque_bera` is that the sample was drawn from
+    a distribution with the same skewness and kurtosis as the normal distribution. To
+    estimate the Type I error rate, we can consider the null hypothesis to be a true
+    *alternative* hypothesis and calculate the power.
+
+    >>> test = stats.jarque_bera
+    >>> n_observations = 10
+    >>> rvs = rng.normal
+    >>> significance = np.linspace(0.0001, 0.1, 1000)
+    >>> res = stats.power(test, rvs, n_observations, significance=significance)
+    >>> size = res.power
+
+    As shown below, the Type I error rate of the test is far below the nominal level
+    for such a small sample, as mentioned in its documentation.
+
+    >>> ax = plt.subplot()
+    >>> ax.plot(significance, size)
+    >>> ax.plot([0, 0.1], [0, 0.1], '--')
+    >>> ax.set_xlabel('nominal significance level')
+    >>> ax.set_ylabel('estimated test size (Type I error rate)')
+    >>> ax.set_title('Estimated test size vs nominal significance level')
+    >>> ax.set_aspect('equal', 'box')
+    >>> ax.legend(('`ttest_1samp`', 'ideal test'))
+    >>> plt.show()
+
+    As one might expect from such a conservative test, the power is quite low with
+    respect to some alternatives. For example, the power of the test under the
+    alternative that the sample was drawn from the Laplace distribution may not
+    be much greater than the Type I error rate.
+
+    >>> rvs = rng.laplace
+    >>> significance = np.linspace(0.0001, 0.1, 1000)
+    >>> res = stats.power(test, rvs, n_observations, significance=0.05)
+    >>> print(res.power)
+    0.0587
+
+    This is not a mistake in SciPy's implementation; it is simply due to the fact
+    that the null distribution of the test statistic is derived under the assumption
+    that the sample size is large (i.e. approaches infinity), and this asymptotic
+    approximation is not accurate for small samples. In such cases, resampling
+    and Monte Carlo methods (e.g. `permutation_test`, `goodness_of_fit`,
+    `monte_carlo_test`) may be more appropriate.
+
+    """
+    tmp = _power_iv(rvs, test, n_observations, significance,
+                    vectorized, n_resamples, batch, kwargs)
+    (rvs, test, nobs, significance,
+     vectorized, n_resamples, batch, args, kwds, shape)= tmp
+
+    batch_nominal = batch or n_resamples
+    pvalues = []  # results of various nobs/kwargs combinations
+    for nobs_i, args_i in zip(nobs, args):
+        kwargs_i = dict(zip(kwds, args_i))
+        pvalues_i = []  # results of batches; fixed nobs/kwargs combination
+        for k in range(0, n_resamples, batch_nominal):
+            batch_actual = min(batch_nominal, n_resamples - k)
+            resamples = [rvs_j(size=(batch_actual, nobs_ij), **kwargs_i)
+                         for rvs_j, nobs_ij in zip(rvs, nobs_i)]
+            res = test(*resamples, **kwargs_i, axis=-1)
+            p = getattr(res, 'pvalue', res)
+            pvalues_i.append(p)
+        # Concatenate results from batches
+        pvalues_i = np.concatenate(pvalues_i, axis=-1)
+        pvalues.append(pvalues_i)
+    # `test` can return result with array of p-values
+    shape += pvalues_i.shape[:-1]
+    # Concatenate results from various nobs/kwargs combinations
+    pvalues = np.concatenate(pvalues, axis=0)
+    # nobs/kwargs arrays were raveled to single axis; unravel
+    pvalues = pvalues.reshape(shape + (-1,))
+    if significance.ndim > 0:
+        newdims = tuple(range(significance.ndim, pvalues.ndim + significance.ndim))
+        significance = np.expand_dims(significance, newdims)
+    powers = np.mean(pvalues < significance, axis=-1)
+
+    return PowerResult(power=powers, pvalues=pvalues)
+
+
+@dataclass
+class PermutationTestResult:
+    """Result object returned by `scipy.stats.permutation_test`.
+
+    Attributes
+    ----------
+    statistic : float or ndarray
+        The observed test statistic of the data.
+    pvalue : float or ndarray
+        The p-value for the given alternative.
+    null_distribution : ndarray
+        The values of the test statistic generated under the null
+        hypothesis.
+    """
+    statistic: float | np.ndarray
+    pvalue: float | np.ndarray
+    null_distribution: np.ndarray
+
+
+def _all_partitions_concatenated(ns):
+    """
+    Generate all partitions of indices of groups of given sizes, concatenated
+
+    `ns` is an iterable of ints.
+    """
+    def all_partitions(z, n):
+        for c in combinations(z, n):
+            x0 = set(c)
+            x1 = z - x0
+            yield [x0, x1]
+
+    def all_partitions_n(z, ns):
+        if len(ns) == 0:
+            yield [z]
+            return
+        for c in all_partitions(z, ns[0]):
+            for d in all_partitions_n(c[1], ns[1:]):
+                yield c[0:1] + d
+
+    z = set(range(np.sum(ns)))
+    for partitioning in all_partitions_n(z, ns[:]):
+        x = np.concatenate([list(partition)
+                            for partition in partitioning]).astype(int)
+        yield x
+
+
+def _batch_generator(iterable, batch):
+    """A generator that yields batches of elements from an iterable"""
+    iterator = iter(iterable)
+    if batch <= 0:
+        raise ValueError("`batch` must be positive.")
+    z = [item for i, item in zip(range(batch), iterator)]
+    while z:  # we don't want StopIteration without yielding an empty list
+        yield z
+        z = [item for i, item in zip(range(batch), iterator)]
+
+
+def _pairings_permutations_gen(n_permutations, n_samples, n_obs_sample, batch,
+                               rng):
+    # Returns a generator that yields arrays of size
+    # `(batch, n_samples, n_obs_sample)`.
+    # Each row is an independent permutation of indices 0 to `n_obs_sample`.
+    batch = min(batch, n_permutations)
+
+    if hasattr(rng, 'permuted'):
+        def batched_perm_generator():
+            indices = np.arange(n_obs_sample)
+            indices = np.tile(indices, (batch, n_samples, 1))
+            for k in range(0, n_permutations, batch):
+                batch_actual = min(batch, n_permutations-k)
+                # Don't permute in place, otherwise results depend on `batch`
+                permuted_indices = rng.permuted(indices, axis=-1)
+                yield permuted_indices[:batch_actual]
+    else:  # RandomState and early Generators don't have `permuted`
+        def batched_perm_generator():
+            for k in range(0, n_permutations, batch):
+                batch_actual = min(batch, n_permutations-k)
+                size = (batch_actual, n_samples, n_obs_sample)
+                x = rng.random(size=size)
+                yield np.argsort(x, axis=-1)[:batch_actual]
+
+    return batched_perm_generator()
+
+
+def _calculate_null_both(data, statistic, n_permutations, batch,
+                         rng=None):
+    """
+    Calculate null distribution for independent sample tests.
+    """
+    n_samples = len(data)
+
+    # compute number of permutations
+    # (distinct partitions of data into samples of these sizes)
+    n_obs_i = [sample.shape[-1] for sample in data]  # observations per sample
+    n_obs_ic = np.cumsum(n_obs_i)
+    n_obs = n_obs_ic[-1]  # total number of observations
+    n_max = np.prod([comb(n_obs_ic[i], n_obs_ic[i-1])
+                     for i in range(n_samples-1, 0, -1)])
+
+    # perm_generator is an iterator that produces permutations of indices
+    # from 0 to n_obs. We'll concatenate the samples, use these indices to
+    # permute the data, then split the samples apart again.
+    if n_permutations >= n_max:
+        exact_test = True
+        n_permutations = n_max
+        perm_generator = _all_partitions_concatenated(n_obs_i)
+    else:
+        exact_test = False
+        # Neither RandomState.permutation nor Generator.permutation
+        # can permute axis-slices independently. If this feature is
+        # added in the future, batches of the desired size should be
+        # generated in a single call.
+        perm_generator = (rng.permutation(n_obs)
+                          for i in range(n_permutations))
+
+    batch = batch or int(n_permutations)
+    null_distribution = []
+
+    # First, concatenate all the samples. In batches, permute samples with
+    # indices produced by the `perm_generator`, split them into new samples of
+    # the original sizes, compute the statistic for each batch, and add these
+    # statistic values to the null distribution.
+    data = np.concatenate(data, axis=-1)
+    for indices in _batch_generator(perm_generator, batch=batch):
+        indices = np.array(indices)
+
+        # `indices` is 2D: each row is a permutation of the indices.
+        # We use it to index `data` along its last axis, which corresponds
+        # with observations.
+        # After indexing, the second to last axis of `data_batch` corresponds
+        # with permutations, and the last axis corresponds with observations.
+        data_batch = data[..., indices]
+
+        # Move the permutation axis to the front: we'll concatenate a list
+        # of batched statistic values along this zeroth axis to form the
+        # null distribution.
+        data_batch = np.moveaxis(data_batch, -2, 0)
+        data_batch = np.split(data_batch, n_obs_ic[:-1], axis=-1)
+        null_distribution.append(statistic(*data_batch, axis=-1))
+    null_distribution = np.concatenate(null_distribution, axis=0)
+
+    return null_distribution, n_permutations, exact_test
+
+
+def _calculate_null_pairings(data, statistic, n_permutations, batch,
+                             rng=None):
+    """
+    Calculate null distribution for association tests.
+    """
+    n_samples = len(data)
+
+    # compute number of permutations (factorial(n) permutations of each sample)
+    n_obs_sample = data[0].shape[-1]  # observations per sample; same for each
+    n_max = factorial(n_obs_sample)**n_samples
+
+    # `perm_generator` is an iterator that produces a list of permutations of
+    # indices from 0 to n_obs_sample, one for each sample.
+    if n_permutations >= n_max:
+        exact_test = True
+        n_permutations = n_max
+        batch = batch or int(n_permutations)
+        # Cartesian product of the sets of all permutations of indices
+        perm_generator = product(*(permutations(range(n_obs_sample))
+                                   for i in range(n_samples)))
+        batched_perm_generator = _batch_generator(perm_generator, batch=batch)
+    else:
+        exact_test = False
+        batch = batch or int(n_permutations)
+        # Separate random permutations of indices for each sample.
+        # Again, it would be nice if RandomState/Generator.permutation
+        # could permute each axis-slice separately.
+        args = n_permutations, n_samples, n_obs_sample, batch, rng
+        batched_perm_generator = _pairings_permutations_gen(*args)
+
+    null_distribution = []
+
+    for indices in batched_perm_generator:
+        indices = np.array(indices)
+
+        # `indices` is 3D: the zeroth axis is for permutations, the next is
+        # for samples, and the last is for observations. Swap the first two
+        # to make the zeroth axis correspond with samples, as it does for
+        # `data`.
+        indices = np.swapaxes(indices, 0, 1)
+
+        # When we're done, `data_batch` will be a list of length `n_samples`.
+        # Each element will be a batch of random permutations of one sample.
+        # The zeroth axis of each batch will correspond with permutations,
+        # and the last will correspond with observations. (This makes it
+        # easy to pass into `statistic`.)
+        data_batch = [None]*n_samples
+        for i in range(n_samples):
+            data_batch[i] = data[i][..., indices[i]]
+            data_batch[i] = np.moveaxis(data_batch[i], -2, 0)
+
+        null_distribution.append(statistic(*data_batch, axis=-1))
+    null_distribution = np.concatenate(null_distribution, axis=0)
+
+    return null_distribution, n_permutations, exact_test
+
+
+def _calculate_null_samples(data, statistic, n_permutations, batch,
+                            rng=None):
+    """
+    Calculate null distribution for paired-sample tests.
+    """
+    n_samples = len(data)
+
+    # By convention, the meaning of the "samples" permutations type for
+    # data with only one sample is to flip the sign of the observations.
+    # Achieve this by adding a second sample - the negative of the original.
+    if n_samples == 1:
+        data = [data[0], -data[0]]
+
+    # The "samples" permutation strategy is the same as the "pairings"
+    # strategy except the roles of samples and observations are flipped.
+    # So swap these axes, then we'll use the function for the "pairings"
+    # strategy to do all the work!
+    data = np.swapaxes(data, 0, -1)
+
+    # (Of course, the user's statistic doesn't know what we've done here,
+    # so we need to pass it what it's expecting.)
+    def statistic_wrapped(*data, axis):
+        data = np.swapaxes(data, 0, -1)
+        if n_samples == 1:
+            data = data[0:1]
+        return statistic(*data, axis=axis)
+
+    return _calculate_null_pairings(data, statistic_wrapped, n_permutations,
+                                    batch, rng)
+
+
+def _permutation_test_iv(data, statistic, permutation_type, vectorized,
+                         n_resamples, batch, alternative, axis, rng):
+    """Input validation for `permutation_test`."""
+
+    axis_int = int(axis)
+    if axis != axis_int:
+        raise ValueError("`axis` must be an integer.")
+
+    permutation_types = {'samples', 'pairings', 'independent'}
+    permutation_type = permutation_type.lower()
+    if permutation_type not in permutation_types:
+        raise ValueError(f"`permutation_type` must be in {permutation_types}.")
+
+    if vectorized not in {True, False, None}:
+        raise ValueError("`vectorized` must be `True`, `False`, or `None`.")
+
+    if vectorized is None:
+        vectorized = 'axis' in inspect.signature(statistic).parameters
+
+    if not vectorized:
+        statistic = _vectorize_statistic(statistic)
+
+    message = "`data` must be a tuple containing at least two samples"
+    try:
+        if len(data) < 2 and permutation_type == 'independent':
+            raise ValueError(message)
+    except TypeError:
+        raise TypeError(message)
+
+    data = _broadcast_arrays(data, axis)
+    data_iv = []
+    for sample in data:
+        sample = np.atleast_1d(sample)
+        if sample.shape[axis] <= 1:
+            raise ValueError("each sample in `data` must contain two or more "
+                             "observations along `axis`.")
+        sample = np.moveaxis(sample, axis_int, -1)
+        data_iv.append(sample)
+
+    n_resamples_int = (int(n_resamples) if not np.isinf(n_resamples)
+                       else np.inf)
+    if n_resamples != n_resamples_int or n_resamples_int <= 0:
+        raise ValueError("`n_resamples` must be a positive integer.")
+
+    if batch is None:
+        batch_iv = batch
+    else:
+        batch_iv = int(batch)
+        if batch != batch_iv or batch_iv <= 0:
+            raise ValueError("`batch` must be a positive integer or None.")
+
+    alternatives = {'two-sided', 'greater', 'less'}
+    alternative = alternative.lower()
+    if alternative not in alternatives:
+        raise ValueError(f"`alternative` must be in {alternatives}")
+
+    rng = check_random_state(rng)
+
+    return (data_iv, statistic, permutation_type, vectorized, n_resamples_int,
+            batch_iv, alternative, axis_int, rng)
+
+
+@_transition_to_rng('random_state')
+def permutation_test(data, statistic, *, permutation_type='independent',
+                     vectorized=None, n_resamples=9999, batch=None,
+                     alternative="two-sided", axis=0, rng=None):
+    r"""
+    Performs a permutation test of a given statistic on provided data.
+
+    For independent sample statistics, the null hypothesis is that the data are
+    randomly sampled from the same distribution.
+    For paired sample statistics, two null hypothesis can be tested:
+    that the data are paired at random or that the data are assigned to samples
+    at random.
+
+    Parameters
+    ----------
+    data : iterable of array-like
+        Contains the samples, each of which is an array of observations.
+        Dimensions of sample arrays must be compatible for broadcasting except
+        along `axis`.
+    statistic : callable
+        Statistic for which the p-value of the hypothesis test is to be
+        calculated. `statistic` must be a callable that accepts samples
+        as separate arguments (e.g. ``statistic(*data)``) and returns the
+        resulting statistic.
+        If `vectorized` is set ``True``, `statistic` must also accept a keyword
+        argument `axis` and be vectorized to compute the statistic along the
+        provided `axis` of the sample arrays.
+    permutation_type : {'independent', 'samples', 'pairings'}, optional
+        The type of permutations to be performed, in accordance with the
+        null hypothesis. The first two permutation types are for paired sample
+        statistics, in which all samples contain the same number of
+        observations and observations with corresponding indices along `axis`
+        are considered to be paired; the third is for independent sample
+        statistics.
+
+        - ``'samples'`` : observations are assigned to different samples
+          but remain paired with the same observations from other samples.
+          This permutation type is appropriate for paired sample hypothesis
+          tests such as the Wilcoxon signed-rank test and the paired t-test.
+        - ``'pairings'`` : observations are paired with different observations,
+          but they remain within the same sample. This permutation type is
+          appropriate for association/correlation tests with statistics such
+          as Spearman's :math:`\rho`, Kendall's :math:`\tau`, and Pearson's
+          :math:`r`.
+        - ``'independent'`` (default) : observations are assigned to different
+          samples. Samples may contain different numbers of observations. This
+          permutation type is appropriate for independent sample hypothesis
+          tests such as the Mann-Whitney :math:`U` test and the independent
+          sample t-test.
+
+          Please see the Notes section below for more detailed descriptions
+          of the permutation types.
+
+    vectorized : bool, optional
+        If `vectorized` is set ``False``, `statistic` will not be passed
+        keyword argument `axis` and is expected to calculate the statistic
+        only for 1D samples. If ``True``, `statistic` will be passed keyword
+        argument `axis` and is expected to calculate the statistic along `axis`
+        when passed an ND sample array. If ``None`` (default), `vectorized`
+        will be set ``True`` if ``axis`` is a parameter of `statistic`. Use
+        of a vectorized statistic typically reduces computation time.
+    n_resamples : int or np.inf, default: 9999
+        Number of random permutations (resamples) used to approximate the null
+        distribution. If greater than or equal to the number of distinct
+        permutations, the exact null distribution will be computed.
+        Note that the number of distinct permutations grows very rapidly with
+        the sizes of samples, so exact tests are feasible only for very small
+        data sets.
+    batch : int, optional
+        The number of permutations to process in each call to `statistic`.
+        Memory usage is O( `batch` * ``n`` ), where ``n`` is the total size
+        of all samples, regardless of the value of `vectorized`. Default is
+        ``None``, in which case ``batch`` is the number of permutations.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        The alternative hypothesis for which the p-value is calculated.
+        For each alternative, the p-value is defined for exact tests as
+        follows.
+
+        - ``'greater'`` : the percentage of the null distribution that is
+          greater than or equal to the observed value of the test statistic.
+        - ``'less'`` : the percentage of the null distribution that is
+          less than or equal to the observed value of the test statistic.
+        - ``'two-sided'`` (default) : twice the smaller of the p-values above.
+
+        Note that p-values for randomized tests are calculated according to the
+        conservative (over-estimated) approximation suggested in [2]_ and [3]_
+        rather than the unbiased estimator suggested in [4]_. That is, when
+        calculating the proportion of the randomized null distribution that is
+        as extreme as the observed value of the test statistic, the values in
+        the numerator and denominator are both increased by one. An
+        interpretation of this adjustment is that the observed value of the
+        test statistic is always included as an element of the randomized
+        null distribution.
+        The convention used for two-sided p-values is not universal;
+        the observed test statistic and null distribution are returned in
+        case a different definition is preferred.
+
+    axis : int, default: 0
+        The axis of the (broadcasted) samples over which to calculate the
+        statistic. If samples have a different number of dimensions,
+        singleton dimensions are prepended to samples with fewer dimensions
+        before `axis` is considered.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    Returns
+    -------
+    res : PermutationTestResult
+        An object with attributes:
+
+        statistic : float or ndarray
+            The observed test statistic of the data.
+        pvalue : float or ndarray
+            The p-value for the given alternative.
+        null_distribution : ndarray
+            The values of the test statistic generated under the null
+            hypothesis.
+
+    Notes
+    -----
+
+    The three types of permutation tests supported by this function are
+    described below.
+
+    **Unpaired statistics** (``permutation_type='independent'``):
+
+    The null hypothesis associated with this permutation type is that all
+    observations are sampled from the same underlying distribution and that
+    they have been assigned to one of the samples at random.
+
+    Suppose ``data`` contains two samples; e.g. ``a, b = data``.
+    When ``1 < n_resamples < binom(n, k)``, where
+
+    * ``k`` is the number of observations in ``a``,
+    * ``n`` is the total number of observations in ``a`` and ``b``, and
+    * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``),
+
+    the data are pooled (concatenated), randomly assigned to either the first
+    or second sample, and the statistic is calculated. This process is
+    performed repeatedly, `permutation` times, generating a distribution of the
+    statistic under the null hypothesis. The statistic of the original
+    data is compared to this distribution to determine the p-value.
+
+    When ``n_resamples >= binom(n, k)``, an exact test is performed: the data
+    are *partitioned* between the samples in each distinct way exactly once,
+    and the exact null distribution is formed.
+    Note that for a given partitioning of the data between the samples,
+    only one ordering/permutation of the data *within* each sample is
+    considered. For statistics that do not depend on the order of the data
+    within samples, this dramatically reduces computational cost without
+    affecting the shape of the null distribution (because the frequency/count
+    of each value is affected by the same factor).
+
+    For ``a = [a1, a2, a3, a4]`` and ``b = [b1, b2, b3]``, an example of this
+    permutation type is ``x = [b3, a1, a2, b2]`` and ``y = [a4, b1, a3]``.
+    Because only one ordering/permutation of the data *within* each sample
+    is considered in an exact test, a resampling like ``x = [b3, a1, b2, a2]``
+    and ``y = [a4, a3, b1]`` would *not* be considered distinct from the
+    example above.
+
+    ``permutation_type='independent'`` does not support one-sample statistics,
+    but it can be applied to statistics with more than two samples. In this
+    case, if ``n`` is an array of the number of observations within each
+    sample, the number of distinct partitions is::
+
+        np.prod([binom(sum(n[i:]), sum(n[i+1:])) for i in range(len(n)-1)])
+
+    **Paired statistics, permute pairings** (``permutation_type='pairings'``):
+
+    The null hypothesis associated with this permutation type is that
+    observations within each sample are drawn from the same underlying
+    distribution and that pairings with elements of other samples are
+    assigned at random.
+
+    Suppose ``data`` contains only one sample; e.g. ``a, = data``, and we
+    wish to consider all possible pairings of elements of ``a`` with elements
+    of a second sample, ``b``. Let ``n`` be the number of observations in
+    ``a``, which must also equal the number of observations in ``b``.
+
+    When ``1 < n_resamples < factorial(n)``, the elements of ``a`` are
+    randomly permuted. The user-supplied statistic accepts one data argument,
+    say ``a_perm``, and calculates the statistic considering ``a_perm`` and
+    ``b``. This process is performed repeatedly, `permutation` times,
+    generating a distribution of the statistic under the null hypothesis.
+    The statistic of the original data is compared to this distribution to
+    determine the p-value.
+
+    When ``n_resamples >= factorial(n)``, an exact test is performed:
+    ``a`` is permuted in each distinct way exactly once. Therefore, the
+    `statistic` is computed for each unique pairing of samples between ``a``
+    and ``b`` exactly once.
+
+    For ``a = [a1, a2, a3]`` and ``b = [b1, b2, b3]``, an example of this
+    permutation type is ``a_perm = [a3, a1, a2]`` while ``b`` is left
+    in its original order.
+
+    ``permutation_type='pairings'`` supports ``data`` containing any number
+    of samples, each of which must contain the same number of observations.
+    All samples provided in ``data`` are permuted *independently*. Therefore,
+    if ``m`` is the number of samples and ``n`` is the number of observations
+    within each sample, then the number of permutations in an exact test is::
+
+        factorial(n)**m
+
+    Note that if a two-sample statistic, for example, does not inherently
+    depend on the order in which observations are provided - only on the
+    *pairings* of observations - then only one of the two samples should be
+    provided in ``data``. This dramatically reduces computational cost without
+    affecting the shape of the null distribution (because the frequency/count
+    of each value is affected by the same factor).
+
+    **Paired statistics, permute samples** (``permutation_type='samples'``):
+
+    The null hypothesis associated with this permutation type is that
+    observations within each pair are drawn from the same underlying
+    distribution and that the sample to which they are assigned is random.
+
+    Suppose ``data`` contains two samples; e.g. ``a, b = data``.
+    Let ``n`` be the number of observations in ``a``, which must also equal
+    the number of observations in ``b``.
+
+    When ``1 < n_resamples < 2**n``, the elements of ``a`` are ``b`` are
+    randomly swapped between samples (maintaining their pairings) and the
+    statistic is calculated. This process is performed repeatedly,
+    `permutation` times,  generating a distribution of the statistic under the
+    null hypothesis. The statistic of the original data is compared to this
+    distribution to determine the p-value.
+
+    When ``n_resamples >= 2**n``, an exact test is performed: the observations
+    are assigned to the two samples in each distinct way (while maintaining
+    pairings) exactly once.
+
+    For ``a = [a1, a2, a3]`` and ``b = [b1, b2, b3]``, an example of this
+    permutation type is ``x = [b1, a2, b3]`` and ``y = [a1, b2, a3]``.
+
+    ``permutation_type='samples'`` supports ``data`` containing any number
+    of samples, each of which must contain the same number of observations.
+    If ``data`` contains more than one sample, paired observations within
+    ``data`` are exchanged between samples *independently*. Therefore, if ``m``
+    is the number of samples and ``n`` is the number of observations within
+    each sample, then the number of permutations in an exact test is::
+
+        factorial(m)**n
+
+    Several paired-sample statistical tests, such as the Wilcoxon signed rank
+    test and paired-sample t-test, can be performed considering only the
+    *difference* between two paired elements. Accordingly, if ``data`` contains
+    only one sample, then the null distribution is formed by independently
+    changing the *sign* of each observation.
+
+    .. warning::
+        The p-value is calculated by counting the elements of the null
+        distribution that are as extreme or more extreme than the observed
+        value of the statistic. Due to the use of finite precision arithmetic,
+        some statistic functions return numerically distinct values when the
+        theoretical values would be exactly equal. In some cases, this could
+        lead to a large error in the calculated p-value. `permutation_test`
+        guards against this by considering elements in the null distribution
+        that are "close" (within a relative tolerance of 100 times the
+        floating point epsilon of inexact dtypes) to the observed
+        value of the test statistic as equal to the observed value of the
+        test statistic. However, the user is advised to inspect the null
+        distribution to assess whether this method of comparison is
+        appropriate, and if not, calculate the p-value manually. See example
+        below.
+
+    References
+    ----------
+
+    .. [1] R. A. Fisher. The Design of Experiments, 6th Ed (1951).
+    .. [2] B. Phipson and G. K. Smyth. "Permutation P-values Should Never Be
+       Zero: Calculating Exact P-values When Permutations Are Randomly Drawn."
+       Statistical Applications in Genetics and Molecular Biology 9.1 (2010).
+    .. [3] M. D. Ernst. "Permutation Methods: A Basis for Exact Inference".
+       Statistical Science (2004).
+    .. [4] B. Efron and R. J. Tibshirani. An Introduction to the Bootstrap
+       (1993).
+
+    Examples
+    --------
+
+    Suppose we wish to test whether two samples are drawn from the same
+    distribution. Assume that the underlying distributions are unknown to us,
+    and that before observing the data, we hypothesized that the mean of the
+    first sample would be less than that of the second sample. We decide that
+    we will use the difference between the sample means as a test statistic,
+    and we will consider a p-value of 0.05 to be statistically significant.
+
+    For efficiency, we write the function defining the test statistic in a
+    vectorized fashion: the samples ``x`` and ``y`` can be ND arrays, and the
+    statistic will be calculated for each axis-slice along `axis`.
+
+    >>> import numpy as np
+    >>> def statistic(x, y, axis):
+    ...     return np.mean(x, axis=axis) - np.mean(y, axis=axis)
+
+    After collecting our data, we calculate the observed value of the test
+    statistic.
+
+    >>> from scipy.stats import norm
+    >>> rng = np.random.default_rng()
+    >>> x = norm.rvs(size=5, random_state=rng)
+    >>> y = norm.rvs(size=6, loc = 3, random_state=rng)
+    >>> statistic(x, y, 0)
+    -3.5411688580987266
+
+    Indeed, the test statistic is negative, suggesting that the true mean of
+    the distribution underlying ``x`` is less than that of the distribution
+    underlying ``y``. To determine the probability of this occurring by chance
+    if the two samples were drawn from the same distribution, we perform
+    a permutation test.
+
+    >>> from scipy.stats import permutation_test
+    >>> # because our statistic is vectorized, we pass `vectorized=True`
+    >>> # `n_resamples=np.inf` indicates that an exact test is to be performed
+    >>> res = permutation_test((x, y), statistic, vectorized=True,
+    ...                        n_resamples=np.inf, alternative='less')
+    >>> print(res.statistic)
+    -3.5411688580987266
+    >>> print(res.pvalue)
+    0.004329004329004329
+
+    The probability of obtaining a test statistic less than or equal to the
+    observed value under the null hypothesis is 0.4329%. This is less than our
+    chosen threshold of 5%, so we consider this to be significant evidence
+    against the null hypothesis in favor of the alternative.
+
+    Because the size of the samples above was small, `permutation_test` could
+    perform an exact test. For larger samples, we resort to a randomized
+    permutation test.
+
+    >>> x = norm.rvs(size=100, random_state=rng)
+    >>> y = norm.rvs(size=120, loc=0.2, random_state=rng)
+    >>> res = permutation_test((x, y), statistic, n_resamples=9999,
+    ...                        vectorized=True, alternative='less',
+    ...                        rng=rng)
+    >>> print(res.statistic)
+    -0.4230459671240913
+    >>> print(res.pvalue)
+    0.0015
+
+    The approximate probability of obtaining a test statistic less than or
+    equal to the observed value under the null hypothesis is 0.0225%. This is
+    again less than our chosen threshold of 5%, so again we have significant
+    evidence to reject the null hypothesis in favor of the alternative.
+
+    For large samples and number of permutations, the result is comparable to
+    that of the corresponding asymptotic test, the independent sample t-test.
+
+    >>> from scipy.stats import ttest_ind
+    >>> res_asymptotic = ttest_ind(x, y, alternative='less')
+    >>> print(res_asymptotic.pvalue)
+    0.0014669545224902675
+
+    The permutation distribution of the test statistic is provided for
+    further investigation.
+
+    >>> import matplotlib.pyplot as plt
+    >>> plt.hist(res.null_distribution, bins=50)
+    >>> plt.title("Permutation distribution of test statistic")
+    >>> plt.xlabel("Value of Statistic")
+    >>> plt.ylabel("Frequency")
+    >>> plt.show()
+
+    Inspection of the null distribution is essential if the statistic suffers
+    from inaccuracy due to limited machine precision. Consider the following
+    case:
+
+    >>> from scipy.stats import pearsonr
+    >>> x = [1, 2, 4, 3]
+    >>> y = [2, 4, 6, 8]
+    >>> def statistic(x, y, axis=-1):
+    ...     return pearsonr(x, y, axis=axis).statistic
+    >>> res = permutation_test((x, y), statistic, vectorized=True,
+    ...                        permutation_type='pairings',
+    ...                        alternative='greater')
+    >>> r, pvalue, null = res.statistic, res.pvalue, res.null_distribution
+
+    In this case, some elements of the null distribution differ from the
+    observed value of the correlation coefficient ``r`` due to numerical noise.
+    We manually inspect the elements of the null distribution that are nearly
+    the same as the observed value of the test statistic.
+
+    >>> r
+    0.7999999999999999
+    >>> unique = np.unique(null)
+    >>> unique
+    array([-1. , -1. , -0.8, -0.8, -0.8, -0.6, -0.4, -0.4, -0.2, -0.2, -0.2,
+        0. ,  0.2,  0.2,  0.2,  0.4,  0.4,  0.6,  0.8,  0.8,  0.8,  1. ,
+        1. ])  # may vary
+    >>> unique[np.isclose(r, unique)].tolist()
+    [0.7999999999999998, 0.7999999999999999, 0.8]  # may vary
+
+    If `permutation_test` were to perform the comparison naively, the
+    elements of the null distribution with value ``0.7999999999999998`` would
+    not be considered as extreme or more extreme as the observed value of the
+    statistic, so the calculated p-value would be too small.
+
+    >>> incorrect_pvalue = np.count_nonzero(null >= r) / len(null)
+    >>> incorrect_pvalue
+    0.14583333333333334  # may vary
+
+    Instead, `permutation_test` treats elements of the null distribution that
+    are within ``max(1e-14, abs(r)*1e-14)`` of the observed value of the
+    statistic ``r`` to be equal to ``r``.
+
+    >>> correct_pvalue = np.count_nonzero(null >= r - 1e-14) / len(null)
+    >>> correct_pvalue
+    0.16666666666666666
+    >>> res.pvalue == correct_pvalue
+    True
+
+    This method of comparison is expected to be accurate in most practical
+    situations, but the user is advised to assess this by inspecting the
+    elements of the null distribution that are close to the observed value
+    of the statistic. Also, consider the use of statistics that can be
+    calculated using exact arithmetic (e.g. integer statistics).
+
+    """
+    args = _permutation_test_iv(data, statistic, permutation_type, vectorized,
+                                n_resamples, batch, alternative, axis,
+                                rng)
+    (data, statistic, permutation_type, vectorized, n_resamples, batch,
+     alternative, axis, rng) = args
+
+    observed = statistic(*data, axis=-1)
+
+    null_calculators = {"pairings": _calculate_null_pairings,
+                        "samples": _calculate_null_samples,
+                        "independent": _calculate_null_both}
+    null_calculator_args = (data, statistic, n_resamples,
+                            batch, rng)
+    calculate_null = null_calculators[permutation_type]
+    null_distribution, n_resamples, exact_test = (
+        calculate_null(*null_calculator_args))
+
+    # See References [2] and [3]
+    adjustment = 0 if exact_test else 1
+
+    # relative tolerance for detecting numerically distinct but
+    # theoretically equal values in the null distribution
+    eps =  (0 if not np.issubdtype(observed.dtype, np.inexact)
+            else np.finfo(observed.dtype).eps*100)
+    gamma = np.abs(eps * observed)
+
+    def less(null_distribution, observed):
+        cmps = null_distribution <= observed + gamma
+        pvalues = (cmps.sum(axis=0) + adjustment) / (n_resamples + adjustment)
+        return pvalues
+
+    def greater(null_distribution, observed):
+        cmps = null_distribution >= observed - gamma
+        pvalues = (cmps.sum(axis=0) + adjustment) / (n_resamples + adjustment)
+        return pvalues
+
+    def two_sided(null_distribution, observed):
+        pvalues_less = less(null_distribution, observed)
+        pvalues_greater = greater(null_distribution, observed)
+        pvalues = np.minimum(pvalues_less, pvalues_greater) * 2
+        return pvalues
+
+    compare = {"less": less,
+               "greater": greater,
+               "two-sided": two_sided}
+
+    pvalues = compare[alternative](null_distribution, observed)
+    pvalues = np.clip(pvalues, 0, 1)
+
+    return PermutationTestResult(observed, pvalues, null_distribution)
+
+
+@dataclass
+class ResamplingMethod:
+    """Configuration information for a statistical resampling method.
+
+    Instances of this class can be passed into the `method` parameter of some
+    hypothesis test functions to perform a resampling or Monte Carlo version
+    of the hypothesis test.
+
+    Attributes
+    ----------
+    n_resamples : int
+        The number of resamples to perform or Monte Carlo samples to draw.
+    batch : int, optional
+        The number of resamples to process in each vectorized call to
+        the statistic. Batch sizes >>1 tend to be faster when the statistic
+        is vectorized, but memory usage scales linearly with the batch size.
+        Default is ``None``, which processes all resamples in a single batch.
+
+    """
+    n_resamples: int = 9999
+    batch: int = None  # type: ignore[assignment]
+
+
+@dataclass
+class MonteCarloMethod(ResamplingMethod):
+    """Configuration information for a Monte Carlo hypothesis test.
+
+    Instances of this class can be passed into the `method` parameter of some
+    hypothesis test functions to perform a Monte Carlo version of the
+    hypothesis tests.
+
+    Attributes
+    ----------
+    n_resamples : int, optional
+        The number of Monte Carlo samples to draw. Default is 9999.
+    batch : int, optional
+        The number of Monte Carlo samples to process in each vectorized call to
+        the statistic. Batch sizes >>1 tend to be faster when the statistic
+        is vectorized, but memory usage scales linearly with the batch size.
+        Default is ``None``, which processes all samples in a single batch.
+    rvs : callable or tuple of callables, optional
+        A callable or sequence of callables that generates random variates
+        under the null hypothesis. Each element of `rvs` must be a callable
+        that accepts keyword argument ``size`` (e.g. ``rvs(size=(m, n))``) and
+        returns an N-d array sample of that shape. If `rvs` is a sequence, the
+        number of callables in `rvs` must match the number of samples passed
+        to the hypothesis test in which the `MonteCarloMethod` is used. Default
+        is ``None``, in which case the hypothesis test function chooses values
+        to match the standard version of the hypothesis test. For example,
+        the null hypothesis of `scipy.stats.pearsonr` is typically that the
+        samples are drawn from the standard normal distribution, so
+        ``rvs = (rng.normal, rng.normal)`` where
+        ``rng = np.random.default_rng()``.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+    """
+    rvs: object = None
+    rng: object = None
+
+    def __init__(self, n_resamples=9999, batch=None, rvs=None, rng=None):
+        if (rvs is not None) and (rng is not None):
+            message = 'Use of `rvs` and `rng` are mutually exclusive.'
+            raise ValueError(message)
+
+        self.n_resamples = n_resamples
+        self.batch = batch
+        self.rvs = rvs
+        self.rng = rng
+
+    def _asdict(self):
+        # `dataclasses.asdict` deepcopies; we don't want that.
+        return dict(n_resamples=self.n_resamples, batch=self.batch,
+                    rvs=self.rvs, rng=self.rng)
+
+
+_rs_deprecation = ("Use of attribute `random_state` is deprecated and replaced by "
+                   "`rng`. Support for `random_state` will be removed in SciPy 1.19.0. "
+                   "To silence this warning and ensure consistent behavior in SciPy "
+                   "1.19.0, control the RNG using attribute `rng`. Values set using "
+                   "attribute `rng` will be validated by `np.random.default_rng`, so "
+                   "the behavior corresponding with a given value may change compared "
+                   "to use of `random_state`. For example, 1) `None` will result in "
+                   "unpredictable random numbers, 2) an integer will result in a "
+                   "different stream of random numbers, (with the same distribution), "
+                   "and 3) `np.random` or `RandomState` instances will result in an "
+                   "error. See the documentation of `default_rng` for more "
+                   "information.")
+
+
+@dataclass
+class PermutationMethod(ResamplingMethod):
+    """Configuration information for a permutation hypothesis test.
+
+    Instances of this class can be passed into the `method` parameter of some
+    hypothesis test functions to perform a permutation version of the
+    hypothesis tests.
+
+    Attributes
+    ----------
+    n_resamples : int, optional
+        The number of resamples to perform. Default is 9999.
+    batch : int, optional
+        The number of resamples to process in each vectorized call to
+        the statistic. Batch sizes >>1 tend to be faster when the statistic
+        is vectorized, but memory usage scales linearly with the batch size.
+        Default is ``None``, which processes all resamples in a single batch.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator used to perform resampling.
+
+        If `rng` is passed by keyword to the initializer or the `rng` attribute is used
+        directly, types other than `numpy.random.Generator` are passed to
+        `numpy.random.default_rng` to instantiate a ``Generator`` before use.
+        If `rng` is already a ``Generator`` instance, then the provided instance is
+        used. Specify `rng` for repeatable behavior.
+
+        If this argument is passed by position, if `random_state` is passed by keyword
+        into the initializer, or if the `random_state` attribute is used directly,
+        legacy behavior for `random_state` applies:
+
+        - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
+          singleton is used.
+        - If `random_state` is an int, a new ``RandomState`` instance is used,
+          seeded with `random_state`.
+        - If `random_state` is already a ``Generator`` or ``RandomState`` instance then
+          that instance is used.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this attribute name was changed from
+            `random_state` to `rng`. For an interim period, both names will continue to
+            work, although only one may be specified at a time. After the interim
+            period, uses of `random_state` will emit warnings. The behavior of both
+            `random_state` and `rng` are outlined above, but only `rng` should be used
+            in new code.
+
+    """
+    rng: object  # type: ignore[misc]
+    _rng: object = field(init=False, repr=False, default=None)  # type: ignore[assignment]
+
+    @property
+    def random_state(self):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, val):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
+        self._random_state = val
+
+    @property  # type: ignore[no-redef]
+    def rng(self):  # noqa: F811
+        return self._rng
+
+    def __init__(self, n_resamples=9999, batch=None, random_state=None, *, rng=None):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation.replace('attribute', 'argument'),
+        #               DeprecationWarning, stacklevel=2)
+        self._rng = rng
+        self._random_state = random_state
+        super().__init__(n_resamples=n_resamples, batch=batch)
+
+    def _asdict(self):
+        # `dataclasses.asdict` deepcopies; we don't want that.
+        d = dict(n_resamples=self.n_resamples, batch=self.batch)
+        if self.rng is not None:
+            d['rng'] = self.rng
+        if self.random_state is not None:
+            d['random_state'] = self.random_state
+        return d
+
+
+@dataclass
+class BootstrapMethod(ResamplingMethod):
+    """Configuration information for a bootstrap confidence interval.
+
+    Instances of this class can be passed into the `method` parameter of some
+    confidence interval methods to generate a bootstrap confidence interval.
+
+    Attributes
+    ----------
+    n_resamples : int, optional
+        The number of resamples to perform. Default is 9999.
+    batch : int, optional
+        The number of resamples to process in each vectorized call to
+        the statistic. Batch sizes >>1 tend to be faster when the statistic
+        is vectorized, but memory usage scales linearly with the batch size.
+        Default is ``None``, which processes all resamples in a single batch.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator used to perform resampling.
+
+        If `rng` is passed by keyword to the initializer or the `rng` attribute is used
+        directly, types other than `numpy.random.Generator` are passed to
+        `numpy.random.default_rng` to instantiate a ``Generator``  before use.
+        If `rng` is already a ``Generator`` instance, then the provided instance is
+        used. Specify `rng` for repeatable behavior.
+
+        If this argument is passed by position, if `random_state` is passed by keyword
+        into the initializer, or if the `random_state` attribute is used directly,
+        legacy behavior for `random_state` applies:
+
+        - If `random_state` is None (or `numpy.random`), the `numpy.random.RandomState`
+          singleton is used.
+        - If `random_state` is an int, a new ``RandomState`` instance is used,
+          seeded with `random_state`.
+        - If `random_state` is already a ``Generator`` or ``RandomState`` instance then
+          that instance is used.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this attribute name was changed from
+            `random_state` to `rng`. For an interim period, both names will continue to
+            work, although only one may be specified at a time. After the interim
+            period, uses of `random_state` will emit warnings. The behavior of both
+            `random_state` and `rng` are outlined above, but only `rng` should be used
+            in new code.
+
+    method : {'BCa', 'percentile', 'basic'}
+        Whether to use the 'percentile' bootstrap ('percentile'), the 'basic'
+        (AKA 'reverse') bootstrap ('basic'), or the bias-corrected and
+        accelerated bootstrap ('BCa', default).
+
+    """
+    rng: object  # type: ignore[misc]
+    _rng: object = field(init=False, repr=False, default=None)  # type: ignore[assignment]
+    method: str = 'BCa'
+
+    @property
+    def random_state(self):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, val):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation, DeprecationWarning, stacklevel=2)
+        self._random_state = val
+
+    @property  # type: ignore[no-redef]
+    def rng(self):  # noqa: F811
+        return self._rng
+
+    def __init__(self, n_resamples=9999, batch=None, random_state=None,
+                 method='BCa', *, rng=None):
+        # Uncomment in SciPy 1.17.0
+        # warnings.warn(_rs_deprecation.replace('attribute', 'argument'),
+        #               DeprecationWarning, stacklevel=2)
+        self._rng = rng  # don't validate with `default_rng`
+        self._random_state = random_state
+        self.method = method
+        super().__init__(n_resamples=n_resamples, batch=batch)
+
+    def _asdict(self):
+        # `dataclasses.asdict` deepcopies; we don't want that.
+        d = dict(n_resamples=self.n_resamples, batch=self.batch,
+                 method=self.method)
+        if self.rng is not None:
+            d['rng'] = self.rng
+        if self.random_state is not None:
+            d['random_state'] = self.random_state
+        return d
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_result_classes.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_result_classes.py
new file mode 100644
index 0000000000000000000000000000000000000000..975af9310efb0c9a414439fd8d531fb95c988951
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_result_classes.py
@@ -0,0 +1,40 @@
+# This module exists only to allow Sphinx to generate docs
+# for the result objects returned by some functions in stats
+# _without_ adding them to the main stats documentation page.
+
+"""
+Result classes
+--------------
+
+.. currentmodule:: scipy.stats._result_classes
+
+.. autosummary::
+   :toctree: generated/
+
+   RelativeRiskResult
+   BinomTestResult
+   TukeyHSDResult
+   DunnettResult
+   PearsonRResult
+   FitResult
+   OddsRatioResult
+   TtestResult
+   ECDFResult
+   EmpiricalDistributionFunction
+
+"""
+
+__all__ = ['BinomTestResult', 'RelativeRiskResult', 'TukeyHSDResult',
+           'PearsonRResult', 'FitResult', 'OddsRatioResult',
+           'TtestResult', 'DunnettResult', 'ECDFResult',
+           'EmpiricalDistributionFunction']
+
+
+from ._binomtest import BinomTestResult
+from ._odds_ratio import OddsRatioResult
+from ._relative_risk import RelativeRiskResult
+from ._hypotests import TukeyHSDResult
+from ._multicomp import DunnettResult
+from ._stats_py import PearsonRResult, TtestResult
+from ._fit import FitResult
+from ._survival import ECDFResult, EmpiricalDistributionFunction
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_sampling.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..44143985a88738c43984347b7787279348fac7f4
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_sampling.py
@@ -0,0 +1,1314 @@
+import math
+import numbers
+import numpy as np
+from scipy import stats
+from scipy import special as sc
+from ._qmc import (check_random_state as check_random_state_qmc,
+                   Halton, QMCEngine)
+from ._unuran.unuran_wrapper import NumericalInversePolynomial
+from scipy._lib._util import check_random_state
+
+
+__all__ = ['FastGeneratorInversion', 'RatioUniforms']
+
+
+# define pdfs and other helper functions to create the generators
+
+def argus_pdf(x, chi):
+    # approach follows Baumgarten/Hoermann: Generating ARGUS random variates
+    # for chi > 5, use relationship of the ARGUS distribution to Gamma(1.5)
+    if chi <= 5:
+        y = 1 - x * x
+        return x * math.sqrt(y) * math.exp(-0.5 * chi**2 * y)
+    return math.sqrt(x) * math.exp(-x)
+
+
+def argus_gamma_trf(x, chi):
+    if chi <= 5:
+        return x
+    return np.sqrt(1.0 - 2 * x / chi**2)
+
+
+def argus_gamma_inv_trf(x, chi):
+    if chi <= 5:
+        return x
+    return 0.5 * chi**2 * (1 - x**2)
+
+
+def betaprime_pdf(x, a, b):
+    if x > 0:
+        logf = (a - 1) * math.log(x) - (a + b) * math.log1p(x) - sc.betaln(a, b)
+        return math.exp(logf)
+    else:
+        # return pdf at x == 0 separately to avoid runtime warnings
+        if a > 1:
+            return 0
+        elif a < 1:
+            return np.inf
+        else:
+            return 1 / sc.beta(a, b)
+
+
+def beta_valid_params(a, b):
+    return (min(a, b) >= 0.1) and (max(a, b) <= 700)
+
+
+def gamma_pdf(x, a):
+    if x > 0:
+        return math.exp(-math.lgamma(a) + (a - 1.0) * math.log(x) - x)
+    else:
+        return 0 if a >= 1 else np.inf
+
+
+def invgamma_pdf(x, a):
+    if x > 0:
+        return math.exp(-(a + 1.0) * math.log(x) - math.lgamma(a) - 1 / x)
+    else:
+        return 0 if a >= 1 else np.inf
+
+
+def burr_pdf(x, cc, dd):
+    # note: we use np.exp instead of math.exp, otherwise an overflow
+    # error can occur in the setup, e.g., for parameters
+    # 1.89128135, 0.30195177, see test test_burr_overflow
+    if x > 0:
+        lx = math.log(x)
+        return np.exp(-(cc + 1) * lx - (dd + 1) * math.log1p(np.exp(-cc * lx)))
+    else:
+        return 0
+
+
+def burr12_pdf(x, cc, dd):
+    if x > 0:
+        lx = math.log(x)
+        logterm = math.log1p(math.exp(cc * lx))
+        return math.exp((cc - 1) * lx - (dd + 1) * logterm + math.log(cc * dd))
+    else:
+        return 0
+
+
+def chi_pdf(x, a):
+    if x > 0:
+        return math.exp(
+            (a - 1) * math.log(x)
+            - 0.5 * (x * x)
+            - (a / 2 - 1) * math.log(2)
+            - math.lgamma(0.5 * a)
+        )
+    else:
+        return 0 if a >= 1 else np.inf
+
+
+def chi2_pdf(x, df):
+    if x > 0:
+        return math.exp(
+            (df / 2 - 1) * math.log(x)
+            - 0.5 * x
+            - (df / 2) * math.log(2)
+            - math.lgamma(0.5 * df)
+        )
+    else:
+        return 0 if df >= 1 else np.inf
+
+
+def alpha_pdf(x, a):
+    if x > 0:
+        return math.exp(-2.0 * math.log(x) - 0.5 * (a - 1.0 / x) ** 2)
+    return 0.0
+
+
+def bradford_pdf(x, c):
+    if 0 <= x <= 1:
+        return 1.0 / (1.0 + c * x)
+    return 0.0
+
+
+def crystalball_pdf(x, b, m):
+    if x > -b:
+        return math.exp(-0.5 * x * x)
+    return math.exp(m * math.log(m / b) - 0.5 * b * b - m * math.log(m / b - b - x))
+
+
+def weibull_min_pdf(x, c):
+    if x > 0:
+        return c * math.exp((c - 1) * math.log(x) - x**c)
+    return 0.0
+
+
+def weibull_max_pdf(x, c):
+    if x < 0:
+        return c * math.exp((c - 1) * math.log(-x) - ((-x) ** c))
+    return 0.0
+
+
+def invweibull_pdf(x, c):
+    if x > 0:
+        return c * math.exp(-(c + 1) * math.log(x) - x ** (-c))
+    return 0.0
+
+
+def wald_pdf(x):
+    if x > 0:
+        return math.exp(-((x - 1) ** 2) / (2 * x)) / math.sqrt(x**3)
+    return 0.0
+
+
+def geninvgauss_mode(p, b):
+    if p > 1:  # equivalent mode formulas numerical more stable versions
+        return (math.sqrt((1 - p) ** 2 + b**2) - (1 - p)) / b
+    return b / (math.sqrt((1 - p) ** 2 + b**2) + (1 - p))
+
+
+def geninvgauss_pdf(x, p, b):
+    m = geninvgauss_mode(p, b)
+    lfm = (p - 1) * math.log(m) - 0.5 * b * (m + 1 / m)
+    if x > 0:
+        return math.exp((p - 1) * math.log(x) - 0.5 * b * (x + 1 / x) - lfm)
+    return 0.0
+
+
+def invgauss_mode(mu):
+    return 1.0 / (math.sqrt(1.5 * 1.5 + 1 / (mu * mu)) + 1.5)
+
+
+def invgauss_pdf(x, mu):
+    m = invgauss_mode(mu)
+    lfm = -1.5 * math.log(m) - (m - mu) ** 2 / (2 * m * mu**2)
+    if x > 0:
+        return math.exp(-1.5 * math.log(x) - (x - mu) ** 2 / (2 * x * mu**2) - lfm)
+    return 0.0
+
+
+def powerlaw_pdf(x, a):
+    if x > 0:
+        return x ** (a - 1)
+    return 0.0
+
+
+# Define a dictionary: for a given distribution (keys), another dictionary
+# (values) specifies the parameters for NumericalInversePolynomial (PINV).
+# The keys of the latter dictionary are:
+# - pdf: the pdf of the distribution (callable). The signature of the pdf
+#   is float -> float (i.e., the function does not have to be vectorized).
+#   If possible, functions like log or exp from the module math should be
+#   preferred over functions from numpy since the PINV setup will be faster
+#   in that case.
+# - check_pinv_params: callable f that returns true if the shape parameters
+#   (args) are recommended parameters for PINV (i.e., the u-error does
+#   not exceed the default tolerance)
+# - center: scalar if the center does not depend on args, otherwise
+#   callable that returns the center as a function of the shape parameters
+# - rvs_transform: a callable that can be used to transform the rvs that
+#   are distributed according to the pdf to the target distribution
+#   (as an example, see the entry for the beta distribution)
+# - rvs_transform_inv: the inverse of rvs_transform (it is required
+#   for the transformed ppf)
+# - mirror_uniform: boolean or a callable that returns true or false
+#   depending on the shape parameters. If True, the ppf is applied
+#   to 1-u instead of u to generate rvs, where u is a uniform rv.
+#   While both u and 1-u are uniform, it can be required to use 1-u
+#   to compute the u-error correctly. This is only relevant for the argus
+#   distribution.
+# The only required keys are "pdf" and "check_pinv_params".
+# All other keys are optional.
+
+PINV_CONFIG = {
+    "alpha": {
+        "pdf": alpha_pdf,
+        "check_pinv_params": lambda a: 1.0e-11 <= a < 2.1e5,
+        "center": lambda a: 0.25 * (math.sqrt(a * a + 8.0) - a),
+    },
+    "anglit": {
+        "pdf": lambda x: math.cos(2 * x) + 1.0e-13,
+        # +1.e-13 is necessary, otherwise PINV has strange problems as
+        # f(upper border) is very close to 0
+        "center": 0,
+    },
+    "argus": {
+        "pdf": argus_pdf,
+        "center": lambda chi: 0.7 if chi <= 5 else 0.5,
+        "check_pinv_params": lambda chi: 1e-20 < chi < 901,
+        "rvs_transform": argus_gamma_trf,
+        "rvs_transform_inv": argus_gamma_inv_trf,
+        "mirror_uniform": lambda chi: chi > 5,
+    },
+    "beta": {
+        "pdf": betaprime_pdf,
+        "center": lambda a, b: max(0.1, (a - 1) / (b + 1)),
+        "check_pinv_params": beta_valid_params,
+        "rvs_transform": lambda x, *args: x / (1 + x),
+        "rvs_transform_inv": lambda x, *args: x / (1 - x) if x < 1 else np.inf,
+    },
+    "betaprime": {
+        "pdf": betaprime_pdf,
+        "center": lambda a, b: max(0.1, (a - 1) / (b + 1)),
+        "check_pinv_params": beta_valid_params,
+    },
+    "bradford": {
+        "pdf": bradford_pdf,
+        "check_pinv_params": lambda a: 1.0e-6 <= a <= 1e9,
+        "center": 0.5,
+    },
+    "burr": {
+        "pdf": burr_pdf,
+        "center": lambda a, b: (2 ** (1 / b) - 1) ** (-1 / a),
+        "check_pinv_params": lambda a, b: (min(a, b) >= 0.3) and (max(a, b) <= 50),
+    },
+    "burr12": {
+        "pdf": burr12_pdf,
+        "center": lambda a, b: (2 ** (1 / b) - 1) ** (1 / a),
+        "check_pinv_params": lambda a, b: (min(a, b) >= 0.2) and (max(a, b) <= 50),
+    },
+    "cauchy": {
+        "pdf": lambda x: 1 / (1 + (x * x)),
+        "center": 0,
+    },
+    "chi": {
+        "pdf": chi_pdf,
+        "check_pinv_params": lambda df: 0.05 <= df <= 1.0e6,
+        "center": lambda a: math.sqrt(a),
+    },
+    "chi2": {
+        "pdf": chi2_pdf,
+        "check_pinv_params": lambda df: 0.07 <= df <= 1e6,
+        "center": lambda a: a,
+    },
+    "cosine": {
+        "pdf": lambda x: 1 + math.cos(x),
+        "center": 0,
+    },
+    "crystalball": {
+        "pdf": crystalball_pdf,
+        "check_pinv_params": lambda b, m: (0.01 <= b <= 5.5)
+        and (1.1 <= m <= 75.1),
+        "center": 0.0,
+    },
+    "expon": {
+        "pdf": lambda x: math.exp(-x),
+        "center": 1.0,
+    },
+    "gamma": {
+        "pdf": gamma_pdf,
+        "check_pinv_params": lambda a: 0.04 <= a <= 1e6,
+        "center": lambda a: a,
+    },
+    "gennorm": {
+        "pdf": lambda x, b: math.exp(-abs(x) ** b),
+        "check_pinv_params": lambda b: 0.081 <= b <= 45.0,
+        "center": 0.0,
+    },
+    "geninvgauss": {
+        "pdf": geninvgauss_pdf,
+        "check_pinv_params": lambda p, b: (abs(p) <= 1200.0)
+        and (1.0e-10 <= b <= 1200.0),
+        "center": geninvgauss_mode,
+    },
+    "gumbel_l": {
+        "pdf": lambda x: math.exp(x - math.exp(x)),
+        "center": -0.6,
+    },
+    "gumbel_r": {
+        "pdf": lambda x: math.exp(-x - math.exp(-x)),
+        "center": 0.6,
+    },
+    "hypsecant": {
+        "pdf": lambda x: 1.0 / (math.exp(x) + math.exp(-x)),
+        "center": 0.0,
+    },
+    "invgamma": {
+        "pdf": invgamma_pdf,
+        "check_pinv_params": lambda a: 0.04 <= a <= 1e6,
+        "center": lambda a: 1 / a,
+    },
+    "invgauss": {
+        "pdf": invgauss_pdf,
+        "check_pinv_params": lambda mu: 1.0e-10 <= mu <= 1.0e9,
+        "center": invgauss_mode,
+    },
+    "invweibull": {
+        "pdf": invweibull_pdf,
+        "check_pinv_params": lambda a: 0.12 <= a <= 512,
+        "center": 1.0,
+    },
+    "laplace": {
+        "pdf": lambda x: math.exp(-abs(x)),
+        "center": 0.0,
+    },
+    "logistic": {
+        "pdf": lambda x: math.exp(-x) / (1 + math.exp(-x)) ** 2,
+        "center": 0.0,
+    },
+    "maxwell": {
+        "pdf": lambda x: x * x * math.exp(-0.5 * x * x),
+        "center": 1.41421,
+    },
+    "moyal": {
+        "pdf": lambda x: math.exp(-(x + math.exp(-x)) / 2),
+        "center": 1.2,
+    },
+    "norm": {
+        "pdf": lambda x: math.exp(-x * x / 2),
+        "center": 0.0,
+    },
+    "pareto": {
+        "pdf": lambda x, b: x ** -(b + 1),
+        "center": lambda b: b / (b - 1) if b > 2 else 1.5,
+        "check_pinv_params": lambda b: 0.08 <= b <= 400000,
+    },
+    "powerlaw": {
+        "pdf": powerlaw_pdf,
+        "center": 1.0,
+        "check_pinv_params": lambda a: 0.06 <= a <= 1.0e5,
+    },
+    "t": {
+        "pdf": lambda x, df: (1 + x * x / df) ** (-0.5 * (df + 1)),
+        "check_pinv_params": lambda a: 0.07 <= a <= 1e6,
+        "center": 0.0,
+    },
+    "rayleigh": {
+        "pdf": lambda x: x * math.exp(-0.5 * (x * x)),
+        "center": 1.0,
+    },
+    "semicircular": {
+        "pdf": lambda x: math.sqrt(1.0 - (x * x)),
+        "center": 0,
+    },
+    "wald": {
+        "pdf": wald_pdf,
+        "center": 1.0,
+    },
+    "weibull_max": {
+        "pdf": weibull_max_pdf,
+        "check_pinv_params": lambda a: 0.25 <= a <= 512,
+        "center": -1.0,
+    },
+    "weibull_min": {
+        "pdf": weibull_min_pdf,
+        "check_pinv_params": lambda a: 0.25 <= a <= 512,
+        "center": 1.0,
+    },
+}
+
+
+def _validate_qmc_input(qmc_engine, d, seed):
+    # Input validation for `qmc_engine` and `d`
+    # Error messages for invalid `d` are raised by QMCEngine
+    # we could probably use a stats.qmc.check_qrandom_state
+    if isinstance(qmc_engine, QMCEngine):
+        if d is not None and qmc_engine.d != d:
+            message = "`d` must be consistent with dimension of `qmc_engine`."
+            raise ValueError(message)
+        d = qmc_engine.d if d is None else d
+    elif qmc_engine is None:
+        d = 1 if d is None else d
+        qmc_engine = Halton(d, seed=seed)
+    else:
+        message = (
+            "`qmc_engine` must be an instance of "
+            "`scipy.stats.qmc.QMCEngine` or `None`."
+        )
+        raise ValueError(message)
+
+    return qmc_engine, d
+
+
+class CustomDistPINV:
+    def __init__(self, pdf, args):
+        self._pdf = lambda x: pdf(x, *args)
+
+    def pdf(self, x):
+        return self._pdf(x)
+
+
+class FastGeneratorInversion:
+    """
+    Fast sampling by numerical inversion of the CDF for a large class of
+    continuous distributions in `scipy.stats`.
+
+    Parameters
+    ----------
+    dist : rv_frozen object
+        Frozen distribution object from `scipy.stats`. The list of supported
+        distributions can be found in the Notes section. The shape parameters,
+        `loc` and `scale` used to create the distributions must be scalars.
+        For example, for the Gamma distribution with shape parameter `p`,
+        `p` has to be a float, and for the beta distribution with shape
+        parameters (a, b), both a and b have to be floats.
+    domain : tuple of floats, optional
+        If one wishes to sample from a truncated/conditional distribution,
+        the domain has to be specified.
+        The default is None. In that case, the random variates are not
+        truncated, and the domain is inferred from the support of the
+        distribution.
+    ignore_shape_range : boolean, optional.
+        If False, shape parameters that are outside of the valid range
+        of values to ensure that the numerical accuracy (see Notes) is
+        high, raise a ValueError. If True, any shape parameters that are valid
+        for the distribution are accepted. This can be useful for testing.
+        The default is False.
+    random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            A NumPy random number generator or seed for the underlying NumPy
+            random number generator used to generate the stream of uniform
+            random numbers.
+            If `random_state` is None, it uses ``self.random_state``.
+            If `random_state` is an int,
+            ``np.random.default_rng(random_state)`` is used.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance then that instance is used.
+
+    Attributes
+    ----------
+    loc : float
+        The location parameter.
+    random_state : {`numpy.random.Generator`, `numpy.random.RandomState`}
+        The random state used in relevant methods like `rvs` (unless
+        another `random_state` is passed as an argument to these methods).
+    scale : float
+        The scale parameter.
+
+    Methods
+    -------
+    cdf
+    evaluate_error
+    ppf
+    qrvs
+    rvs
+    support
+
+    Notes
+    -----
+    The class creates an object for continuous distributions specified
+    by `dist`. The method `rvs` uses a generator from
+    `scipy.stats.sampling` that is created when the object is instantiated.
+    In addition, the methods `qrvs` and `ppf` are added.
+    `qrvs` generate samples based on quasi-random numbers from
+    `scipy.stats.qmc`. `ppf` is the PPF based on the
+    numerical inversion method in [1]_ (`NumericalInversePolynomial`) that is
+    used to generate random variates.
+
+    Supported distributions (`distname`) are:
+    ``alpha``, ``anglit``, ``argus``, ``beta``, ``betaprime``, ``bradford``,
+    ``burr``, ``burr12``, ``cauchy``, ``chi``, ``chi2``, ``cosine``,
+    ``crystalball``, ``expon``, ``gamma``, ``gennorm``, ``geninvgauss``,
+    ``gumbel_l``, ``gumbel_r``, ``hypsecant``, ``invgamma``, ``invgauss``,
+    ``invweibull``, ``laplace``, ``logistic``, ``maxwell``, ``moyal``,
+    ``norm``, ``pareto``, ``powerlaw``, ``t``, ``rayleigh``, ``semicircular``,
+    ``wald``, ``weibull_max``, ``weibull_min``.
+
+    `rvs` relies on the accuracy of the numerical inversion. If very extreme
+    shape parameters are used, the numerical inversion might not work. However,
+    for all implemented distributions, the admissible shape parameters have
+    been tested, and an error will be raised if the user supplies values
+    outside of the allowed range. The u-error should not exceed 1e-10 for all
+    valid parameters. Note that warnings might be raised even if parameters
+    are within the valid range when the object is instantiated.
+    To check numerical accuracy, the method `evaluate_error` can be used.
+
+    Note that all implemented distributions are also part of `scipy.stats`, and
+    the object created by `FastGeneratorInversion` relies on methods like
+    `ppf`, `cdf` and `pdf` from `rv_frozen`. The main benefit of using this
+    class can be summarized as follows: Once the generator to sample random
+    variates is created in the setup step, sampling and evaluation of
+    the PPF using `ppf` are very fast,
+    and performance is essentially independent of the distribution. Therefore,
+    a substantial speed-up can be achieved for many distributions if large
+    numbers of random variates are required. It is important to know that this
+    fast sampling is achieved by inversion of the CDF. Thus, one uniform
+    random variate is transformed into a non-uniform variate, which is an
+    advantage for several simulation methods, e.g., when
+    the variance reduction methods of common random variates or
+    antithetic variates are be used ([2]_).
+
+    In addition, inversion makes it possible to
+    - to use a QMC generator from `scipy.stats.qmc` (method `qrvs`),
+    - to generate random variates truncated to an interval. For example, if
+    one aims to sample standard normal random variates from
+    the interval (2, 4), this can be easily achieved by using the parameter
+    `domain`.
+
+    The location and scale that are initially defined by `dist`
+    can be reset without having to rerun the setup
+    step to create the generator that is used for sampling. The relation
+    of the distribution `Y` with `loc` and `scale` to the standard
+    distribution `X` (i.e., ``loc=0`` and ``scale=1``) is given by
+    ``Y = loc + scale * X``.
+
+    References
+    ----------
+    .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold.
+           "Random variate  generation by numerical inversion when only the
+           density is known." ACM Transactions on Modeling and Computer
+           Simulation (TOMACS) 20.4 (2010): 1-25.
+    .. [2] Hörmann, Wolfgang, Josef Leydold and Gerhard Derflinger.
+           "Automatic nonuniform random number generation."
+           Springer, 2004.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> from scipy.stats.sampling import FastGeneratorInversion
+
+    Let's start with a simple example to illustrate the main features:
+
+    >>> gamma_frozen = stats.gamma(1.5)
+    >>> gamma_dist = FastGeneratorInversion(gamma_frozen)
+    >>> r = gamma_dist.rvs(size=1000)
+
+    The mean should be approximately equal to the shape parameter 1.5:
+
+    >>> r.mean()
+    1.52423591130436  # may vary
+
+    Similarly, we can draw a sample based on quasi-random numbers:
+
+    >>> r = gamma_dist.qrvs(size=1000)
+    >>> r.mean()
+    1.4996639255942914  # may vary
+
+    Compare the PPF against approximation `ppf`.
+
+    >>> q = [0.001, 0.2, 0.5, 0.8, 0.999]
+    >>> np.max(np.abs(gamma_frozen.ppf(q) - gamma_dist.ppf(q)))
+    4.313394796895409e-08
+
+    To confirm that the numerical inversion is accurate, we evaluate the
+    approximation error (u-error), which should be below 1e-10 (for more
+    details, refer to the documentation of `evaluate_error`):
+
+    >>> gamma_dist.evaluate_error()
+    (7.446320551265581e-11, nan)  # may vary
+
+    Note that the location and scale can be changed without instantiating a
+    new generator:
+
+    >>> gamma_dist.loc = 2
+    >>> gamma_dist.scale = 3
+    >>> r = gamma_dist.rvs(size=1000)
+
+    The mean should be approximately 2 + 3*1.5 = 6.5.
+
+    >>> r.mean()
+    6.399549295242894  # may vary
+
+    Let us also illustrate how truncation can be applied:
+
+    >>> trunc_norm = FastGeneratorInversion(stats.norm(), domain=(3, 4))
+    >>> r = trunc_norm.rvs(size=1000)
+    >>> 3 < r.min() < r.max() < 4
+    True
+
+    Check the mean:
+
+    >>> r.mean()
+    3.250433367078603  # may vary
+
+    >>> stats.norm.expect(lb=3, ub=4, conditional=True)
+    3.260454285589997
+
+    In this particular, case, `scipy.stats.truncnorm` could also be used to
+    generate truncated normal random variates.
+
+    """
+
+    def __init__(
+        self,
+        dist,
+        *,
+        domain=None,
+        ignore_shape_range=False,
+        random_state=None,
+    ):
+
+        if isinstance(dist, stats.distributions.rv_frozen):
+            distname = dist.dist.name
+            if distname not in PINV_CONFIG.keys():
+                raise ValueError(
+                    f"Distribution '{distname}' is not supported."
+                    f"It must be one of {list(PINV_CONFIG.keys())}"
+                    )
+        else:
+            raise ValueError("`dist` must be a frozen distribution object")
+
+        loc = dist.kwds.get("loc", 0)
+        scale = dist.kwds.get("scale", 1)
+        args = dist.args
+        if not np.isscalar(loc):
+            raise ValueError("loc must be scalar.")
+        if not np.isscalar(scale):
+            raise ValueError("scale must be scalar.")
+
+        self._frozendist = getattr(stats, distname)(
+            *args,
+            loc=loc,
+            scale=scale,
+        )
+        self._distname = distname
+
+        nargs = np.broadcast_arrays(args)[0].size
+        nargs_expected = self._frozendist.dist.numargs
+        if nargs != nargs_expected:
+            raise ValueError(
+                f"Each of the {nargs_expected} shape parameters must be a "
+                f"scalar, but {nargs} values are provided."
+            )
+
+        self.random_state = random_state
+
+        if domain is None:
+            self._domain = self._frozendist.support()
+            self._p_lower = 0.0
+            self._p_domain = 1.0
+        else:
+            self._domain = domain
+            self._p_lower = self._frozendist.cdf(self._domain[0])
+            _p_domain = self._frozendist.cdf(self._domain[1]) - self._p_lower
+            self._p_domain = _p_domain
+        self._set_domain_adj()
+        self._ignore_shape_range = ignore_shape_range
+
+        # the domain to be passed to NumericalInversePolynomial
+        # define a separate variable since in case of a transformation,
+        # domain_pinv will not be the same as self._domain
+        self._domain_pinv = self._domain
+
+        # get information about the distribution from the config to set up
+        # the generator
+        dist = self._process_config(distname, args)
+
+        if self._rvs_transform_inv is not None:
+            d0 = self._rvs_transform_inv(self._domain[0], *args)
+            d1 = self._rvs_transform_inv(self._domain[1], *args)
+            if d0 > d1:
+                # swap values if transformation if decreasing
+                d0, d1 = d1, d0
+            # only update _domain_pinv and not _domain
+            # _domain refers to the original distribution, _domain_pinv
+            # to the transformed distribution
+            self._domain_pinv = d0, d1
+
+        # self._center has been set by the call self._process_config
+        # check if self._center is inside the transformed domain
+        # _domain_pinv, otherwise move it to the endpoint that is closer
+        if self._center is not None:
+            if self._center < self._domain_pinv[0]:
+                self._center = self._domain_pinv[0]
+            elif self._center > self._domain_pinv[1]:
+                self._center = self._domain_pinv[1]
+
+        self._rng = NumericalInversePolynomial(
+            dist,
+            random_state=self.random_state,
+            domain=self._domain_pinv,
+            center=self._center,
+            )
+
+    @property
+    def random_state(self):
+        return self._random_state
+
+    @random_state.setter
+    def random_state(self, random_state):
+        self._random_state = check_random_state_qmc(random_state)
+
+    @property
+    def loc(self):
+        return self._frozendist.kwds.get("loc", 0)
+
+    @loc.setter
+    def loc(self, loc):
+        if not np.isscalar(loc):
+            raise ValueError("loc must be scalar.")
+        self._frozendist.kwds["loc"] = loc
+        # update the adjusted domain that depends on loc and scale
+        self._set_domain_adj()
+
+    @property
+    def scale(self):
+        return self._frozendist.kwds.get("scale", 0)
+
+    @scale.setter
+    def scale(self, scale):
+        if not np.isscalar(scale):
+            raise ValueError("scale must be scalar.")
+        self._frozendist.kwds["scale"] = scale
+        # update the adjusted domain that depends on loc and scale
+        self._set_domain_adj()
+
+    def _set_domain_adj(self):
+        """ Adjust the domain based on loc and scale. """
+        loc = self.loc
+        scale = self.scale
+        lb = self._domain[0] * scale + loc
+        ub = self._domain[1] * scale + loc
+        self._domain_adj = (lb, ub)
+
+    def _process_config(self, distname, args):
+        cfg = PINV_CONFIG[distname]
+        if "check_pinv_params" in cfg:
+            if not self._ignore_shape_range:
+                if not cfg["check_pinv_params"](*args):
+                    msg = ("No generator is defined for the shape parameters "
+                           f"{args}. Use ignore_shape_range to proceed "
+                           "with the selected values.")
+                    raise ValueError(msg)
+
+        if "center" in cfg.keys():
+            if not np.isscalar(cfg["center"]):
+                self._center = cfg["center"](*args)
+            else:
+                self._center = cfg["center"]
+        else:
+            self._center = None
+        self._rvs_transform = cfg.get("rvs_transform", None)
+        self._rvs_transform_inv = cfg.get("rvs_transform_inv", None)
+        _mirror_uniform = cfg.get("mirror_uniform", None)
+        if _mirror_uniform is None:
+            self._mirror_uniform = False
+        else:
+            self._mirror_uniform = _mirror_uniform(*args)
+
+        return CustomDistPINV(cfg["pdf"], args)
+
+    def rvs(self, size=None):
+        """
+        Sample from the distribution by inversion.
+
+        Parameters
+        ----------
+        size : int or tuple, optional
+            The shape of samples. Default is ``None`` in which case a scalar
+            sample is returned.
+
+        Returns
+        -------
+        rvs : array_like
+            A NumPy array of random variates.
+
+        Notes
+        -----
+        Random variates are generated by numerical inversion of the CDF, i.e.,
+        `ppf` computed by `NumericalInversePolynomial` when the class
+        is instantiated. Note that the
+        default ``rvs`` method of the rv_continuous class is
+        overwritten. Hence, a different stream of random numbers is generated
+        even if the same seed is used.
+        """
+        # note: we cannot use self._rng.rvs directly in case
+        # self._mirror_uniform is true
+        u = self.random_state.uniform(size=size)
+        if self._mirror_uniform:
+            u = 1 - u
+        r = self._rng.ppf(u)
+        if self._rvs_transform is not None:
+            r = self._rvs_transform(r, *self._frozendist.args)
+        return self.loc + self.scale * r
+
+    def ppf(self, q):
+        """
+        Very fast PPF (inverse CDF) of the distribution which
+        is a very close approximation of the exact PPF values.
+
+        Parameters
+        ----------
+        u : array_like
+            Array with probabilities.
+
+        Returns
+        -------
+        ppf : array_like
+            Quantiles corresponding to the values in `u`.
+
+        Notes
+        -----
+        The evaluation of the PPF is very fast but it may have a large
+        relative error in the far tails. The numerical precision of the PPF
+        is controlled by the u-error, that is,
+        ``max |u - CDF(PPF(u))|`` where the max is taken over points in
+        the interval [0,1], see `evaluate_error`.
+
+        Note that this PPF is designed to generate random samples.
+        """
+        q = np.asarray(q)
+        if self._mirror_uniform:
+            x = self._rng.ppf(1 - q)
+        else:
+            x = self._rng.ppf(q)
+        if self._rvs_transform is not None:
+            x = self._rvs_transform(x, *self._frozendist.args)
+        return self.scale * x + self.loc
+
+    def qrvs(self, size=None, d=None, qmc_engine=None):
+        """
+        Quasi-random variates of the given distribution.
+
+        The `qmc_engine` is used to draw uniform quasi-random variates, and
+        these are converted to quasi-random variates of the given distribution
+        using inverse transform sampling.
+
+        Parameters
+        ----------
+        size : int, tuple of ints, or None; optional
+            Defines shape of random variates array. Default is ``None``.
+        d : int or None, optional
+            Defines dimension of uniform quasi-random variates to be
+            transformed. Default is ``None``.
+        qmc_engine : scipy.stats.qmc.QMCEngine(d=1), optional
+            Defines the object to use for drawing
+            quasi-random variates. Default is ``None``, which uses
+            `scipy.stats.qmc.Halton(1)`.
+
+        Returns
+        -------
+        rvs : ndarray or scalar
+            Quasi-random variates. See Notes for shape information.
+
+        Notes
+        -----
+        The shape of the output array depends on `size`, `d`, and `qmc_engine`.
+        The intent is for the interface to be natural, but the detailed rules
+        to achieve this are complicated.
+
+        - If `qmc_engine` is ``None``, a `scipy.stats.qmc.Halton` instance is
+          created with dimension `d`. If `d` is not provided, ``d=1``.
+        - If `qmc_engine` is not ``None`` and `d` is ``None``, `d` is
+          determined from the dimension of the `qmc_engine`.
+        - If `qmc_engine` is not ``None`` and `d` is not ``None`` but the
+          dimensions are inconsistent, a ``ValueError`` is raised.
+        - After `d` is determined according to the rules above, the output
+          shape is ``tuple_shape + d_shape``, where:
+
+              - ``tuple_shape = tuple()`` if `size` is ``None``,
+              - ``tuple_shape = (size,)`` if `size` is an ``int``,
+              - ``tuple_shape = size`` if `size` is a sequence,
+              - ``d_shape = tuple()`` if `d` is ``None`` or `d` is 1, and
+              - ``d_shape = (d,)`` if `d` is greater than 1.
+
+        The elements of the returned array are part of a low-discrepancy
+        sequence. If `d` is 1, this means that none of the samples are truly
+        independent. If `d` > 1, each slice ``rvs[..., i]`` will be of a
+        quasi-independent sequence; see `scipy.stats.qmc.QMCEngine` for
+        details. Note that when `d` > 1, the samples returned are still those
+        of the provided univariate distribution, not a multivariate
+        generalization of that distribution.
+
+        """
+        qmc_engine, d = _validate_qmc_input(qmc_engine, d, self.random_state)
+        # mainly copied from unuran_wrapper.pyx.templ
+        # `rvs` is flexible about whether `size` is an int or tuple, so this
+        # should be, too.
+        try:
+            if size is None:
+                tuple_size = (1,)
+            else:
+                tuple_size = tuple(size)
+        except TypeError:
+            tuple_size = (size,)
+        # we do not use rng.qrvs directly since we need to be
+        # able to apply the ppf to 1 - u
+        N = 1 if size is None else np.prod(size)
+        u = qmc_engine.random(N)
+        if self._mirror_uniform:
+            u = 1 - u
+        qrvs = self._ppf(u)
+        if self._rvs_transform is not None:
+            qrvs = self._rvs_transform(qrvs, *self._frozendist.args)
+        if size is None:
+            qrvs = qrvs.squeeze()[()]
+        else:
+            if d == 1:
+                qrvs = qrvs.reshape(tuple_size)
+            else:
+                qrvs = qrvs.reshape(tuple_size + (d,))
+        return self.loc + self.scale * qrvs
+
+    def evaluate_error(self, size=100000, random_state=None, x_error=False):
+        """
+        Evaluate the numerical accuracy of the inversion (u- and x-error).
+
+        Parameters
+        ----------
+        size : int, optional
+            The number of random points over which the error is estimated.
+            Default is ``100000``.
+        random_state : {None, int, `numpy.random.Generator`,
+                        `numpy.random.RandomState`}, optional
+
+            A NumPy random number generator or seed for the underlying NumPy
+            random number generator used to generate the stream of uniform
+            random numbers.
+            If `random_state` is None, use ``self.random_state``.
+            If `random_state` is an int,
+            ``np.random.default_rng(random_state)`` is used.
+            If `random_state` is already a ``Generator`` or ``RandomState``
+            instance then that instance is used.
+
+        Returns
+        -------
+        u_error, x_error : tuple of floats
+            A NumPy array of random variates.
+
+        Notes
+        -----
+        The numerical precision of the inverse CDF `ppf` is controlled by
+        the u-error. It is computed as follows:
+        ``max |u - CDF(PPF(u))|`` where the max is taken `size` random
+        points in the interval [0,1]. `random_state` determines the random
+        sample. Note that if `ppf` was exact, the u-error would be zero.
+
+        The x-error measures the direct distance between the exact PPF
+        and `ppf`. If ``x_error`` is set to ``True`, it is
+        computed as the maximum of the minimum of the relative and absolute
+        x-error:
+        ``max(min(x_error_abs[i], x_error_rel[i]))`` where
+        ``x_error_abs[i] = |PPF(u[i]) - PPF_fast(u[i])|``,
+        ``x_error_rel[i] = max |(PPF(u[i]) - PPF_fast(u[i])) / PPF(u[i])|``.
+        Note that it is important to consider the relative x-error in the case
+        that ``PPF(u)`` is close to zero or very large.
+
+        By default, only the u-error is evaluated and the x-error is set to
+        ``np.nan``. Note that the evaluation of the x-error will be very slow
+        if the implementation of the PPF is slow.
+
+        Further information about these error measures can be found in [1]_.
+
+        References
+        ----------
+        .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold.
+               "Random variate  generation by numerical inversion when only the
+               density is known." ACM Transactions on Modeling and Computer
+               Simulation (TOMACS) 20.4 (2010): 1-25.
+
+        Examples
+        --------
+
+        >>> import numpy as np
+        >>> from scipy import stats
+        >>> from scipy.stats.sampling import FastGeneratorInversion
+
+        Create an object for the normal distribution:
+
+        >>> d_norm_frozen = stats.norm()
+        >>> d_norm = FastGeneratorInversion(d_norm_frozen)
+
+        To confirm that the numerical inversion is accurate, we evaluate the
+        approximation error (u-error and x-error).
+
+        >>> u_error, x_error = d_norm.evaluate_error(x_error=True)
+
+        The u-error should be below 1e-10:
+
+        >>> u_error
+        8.785783212061915e-11  # may vary
+
+        Compare the PPF against approximation `ppf`:
+
+        >>> q = [0.001, 0.2, 0.4, 0.6, 0.8, 0.999]
+        >>> diff = np.abs(d_norm_frozen.ppf(q) - d_norm.ppf(q))
+        >>> x_error_abs = np.max(diff)
+        >>> x_error_abs
+        1.2937954707581412e-08
+
+        This is the absolute x-error evaluated at the points q. The relative
+        error is given by
+
+        >>> x_error_rel = np.max(diff / np.abs(d_norm_frozen.ppf(q)))
+        >>> x_error_rel
+        4.186725600453555e-09
+
+        The x_error computed above is derived in a very similar way over a
+        much larger set of random values q. At each value q[i], the minimum
+        of the relative and absolute error is taken. The final value is then
+        derived as the maximum of these values. In our example, we get the
+        following value:
+
+        >>> x_error
+        4.507068014335139e-07  # may vary
+
+        """
+        if not isinstance(size, (numbers.Integral, np.integer)):
+            raise ValueError("size must be an integer.")
+        # urng will be used to draw the samples for testing the error
+        # it must not interfere with self.random_state. therefore, do not
+        # call self.rvs, but draw uniform random numbers and apply
+        # self.ppf (note: like in rvs, consider self._mirror_uniform)
+        urng = check_random_state_qmc(random_state)
+        u = urng.uniform(size=size)
+        if self._mirror_uniform:
+            u = 1 - u
+        x = self.ppf(u)
+        uerr = np.max(np.abs(self._cdf(x) - u))
+        if not x_error:
+            return uerr, np.nan
+        ppf_u = self._ppf(u)
+        x_error_abs = np.abs(self.ppf(u)-ppf_u)
+        x_error_rel = x_error_abs / np.abs(ppf_u)
+        x_error_combined = np.array([x_error_abs, x_error_rel]).min(axis=0)
+        return uerr, np.max(x_error_combined)
+
+    def support(self):
+        """Support of the distribution.
+
+        Returns
+        -------
+        a, b : float
+            end-points of the distribution's support.
+
+        Notes
+        -----
+
+        Note that the support of the distribution depends on `loc`,
+        `scale` and `domain`.
+
+        Examples
+        --------
+
+        >>> from scipy import stats
+        >>> from scipy.stats.sampling import FastGeneratorInversion
+
+        Define a truncated normal distribution:
+
+        >>> d_norm = FastGeneratorInversion(stats.norm(), domain=(0, 1))
+        >>> d_norm.support()
+        (0, 1)
+
+        Shift the distribution:
+
+        >>> d_norm.loc = 2.5
+        >>> d_norm.support()
+        (2.5, 3.5)
+
+        """
+        return self._domain_adj
+
+    def _cdf(self, x):
+        """Cumulative distribution function (CDF)
+
+        Parameters
+        ----------
+        x : array_like
+            The values where the CDF is evaluated
+
+        Returns
+        -------
+        y : ndarray
+            CDF evaluated at x
+
+        """
+        y = self._frozendist.cdf(x)
+        if self._p_domain == 1.0:
+            return y
+        return np.clip((y - self._p_lower) / self._p_domain, 0, 1)
+
+    def _ppf(self, q):
+        """Percent point function (inverse of `cdf`)
+
+        Parameters
+        ----------
+        q : array_like
+            lower tail probability
+
+        Returns
+        -------
+        x : array_like
+            quantile corresponding to the lower tail probability q.
+
+        """
+        if self._p_domain == 1.0:
+            return self._frozendist.ppf(q)
+        x = self._frozendist.ppf(self._p_domain * np.array(q) + self._p_lower)
+        return np.clip(x, self._domain_adj[0], self._domain_adj[1])
+
+
+class RatioUniforms:
+    """
+    Generate random samples from a probability density function using the
+    ratio-of-uniforms method.
+
+    Parameters
+    ----------
+    pdf : callable
+        A function with signature `pdf(x)` that is proportional to the
+        probability density function of the distribution.
+    umax : float
+        The upper bound of the bounding rectangle in the u-direction.
+    vmin : float
+        The lower bound of the bounding rectangle in the v-direction.
+    vmax : float
+        The upper bound of the bounding rectangle in the v-direction.
+    c : float, optional.
+        Shift parameter of ratio-of-uniforms method, see Notes. Default is 0.
+    random_state : {None, int, `numpy.random.Generator`,
+                    `numpy.random.RandomState`}, optional
+
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+    Methods
+    -------
+    rvs
+
+    Notes
+    -----
+    Given a univariate probability density function `pdf` and a constant `c`,
+    define the set ``A = {(u, v) : 0 < u <= sqrt(pdf(v/u + c))}``.
+    If ``(U, V)`` is a random vector uniformly distributed over ``A``,
+    then ``V/U + c`` follows a distribution according to `pdf`.
+
+    The above result (see [1]_, [2]_) can be used to sample random variables
+    using only the PDF, i.e. no inversion of the CDF is required. Typical
+    choices of `c` are zero or the mode of `pdf`. The set ``A`` is a subset of
+    the rectangle ``R = [0, umax] x [vmin, vmax]`` where
+
+    - ``umax = sup sqrt(pdf(x))``
+    - ``vmin = inf (x - c) sqrt(pdf(x))``
+    - ``vmax = sup (x - c) sqrt(pdf(x))``
+
+    In particular, these values are finite if `pdf` is bounded and
+    ``x**2 * pdf(x)`` is bounded (i.e. subquadratic tails).
+    One can generate ``(U, V)`` uniformly on ``R`` and return
+    ``V/U + c`` if ``(U, V)`` are also in ``A`` which can be directly
+    verified.
+
+    The algorithm is not changed if one replaces `pdf` by k * `pdf` for any
+    constant k > 0. Thus, it is often convenient to work with a function
+    that is proportional to the probability density function by dropping
+    unnecessary normalization factors.
+
+    Intuitively, the method works well if ``A`` fills up most of the
+    enclosing rectangle such that the probability is high that ``(U, V)``
+    lies in ``A`` whenever it lies in ``R`` as the number of required
+    iterations becomes too large otherwise. To be more precise, note that
+    the expected number of iterations to draw ``(U, V)`` uniformly
+    distributed on ``R`` such that ``(U, V)`` is also in ``A`` is given by
+    the ratio ``area(R) / area(A) = 2 * umax * (vmax - vmin) / area(pdf)``,
+    where `area(pdf)` is the integral of `pdf` (which is equal to one if the
+    probability density function is used but can take on other values if a
+    function proportional to the density is used). The equality holds since
+    the area of ``A`` is equal to ``0.5 * area(pdf)`` (Theorem 7.1 in [1]_).
+    If the sampling fails to generate a single random variate after 50000
+    iterations (i.e. not a single draw is in ``A``), an exception is raised.
+
+    If the bounding rectangle is not correctly specified (i.e. if it does not
+    contain ``A``), the algorithm samples from a distribution different from
+    the one given by `pdf`. It is therefore recommended to perform a
+    test such as `~scipy.stats.kstest` as a check.
+
+    References
+    ----------
+    .. [1] L. Devroye, "Non-Uniform Random Variate Generation",
+       Springer-Verlag, 1986.
+
+    .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian
+       random variates", Statistics and Computing, 24(4), p. 547--557, 2014.
+
+    .. [3] A.J. Kinderman and J.F. Monahan, "Computer Generation of Random
+       Variables Using the Ratio of Uniform Deviates",
+       ACM Transactions on Mathematical Software, 3(3), p. 257--260, 1977.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+
+    >>> from scipy.stats.sampling import RatioUniforms
+    >>> rng = np.random.default_rng()
+
+    Simulate normally distributed random variables. It is easy to compute the
+    bounding rectangle explicitly in that case. For simplicity, we drop the
+    normalization factor of the density.
+
+    >>> f = lambda x: np.exp(-x**2 / 2)
+    >>> v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
+    >>> umax = np.sqrt(f(0))
+    >>> gen = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=rng)
+    >>> r = gen.rvs(size=2500)
+
+    The K-S test confirms that the random variates are indeed normally
+    distributed (normality is not rejected at 5% significance level):
+
+    >>> stats.kstest(r, 'norm')[1]
+    0.250634764150542
+
+    The exponential distribution provides another example where the bounding
+    rectangle can be determined explicitly.
+
+    >>> gen = RatioUniforms(lambda x: np.exp(-x), umax=1, vmin=0,
+    ...                     vmax=2*np.exp(-1), random_state=rng)
+    >>> r = gen.rvs(1000)
+    >>> stats.kstest(r, 'expon')[1]
+    0.21121052054580314
+
+    """
+    
+    def __init__(self, pdf, *, umax, vmin, vmax, c=0, random_state=None):
+        if vmin >= vmax:
+            raise ValueError("vmin must be smaller than vmax.")
+
+        if umax <= 0:
+            raise ValueError("umax must be positive.")
+        
+        self._pdf = pdf
+        self._umax = umax
+        self._vmin = vmin
+        self._vmax = vmax
+        self._c = c
+        self._rng = check_random_state(random_state)
+
+    def rvs(self, size=1):
+        """Sampling of random variates
+
+        Parameters
+        ----------
+        size : int or tuple of ints, optional
+            Number of random variates to be generated (default is 1).
+
+        Returns
+        -------
+        rvs : ndarray
+            The random variates distributed according to the probability
+            distribution defined by the pdf.
+
+        """
+        size1d = tuple(np.atleast_1d(size))
+        N = np.prod(size1d)  # number of rvs needed, reshape upon return
+
+        # start sampling using ratio of uniforms method
+        x = np.zeros(N)
+        simulated, i = 0, 1
+
+        # loop until N rvs have been generated: expected runtime is finite.
+        # to avoid infinite loop, raise exception if not a single rv has been
+        # generated after 50000 tries. even if the expected number of iterations
+        # is 1000, the probability of this event is (1-1/1000)**50000
+        # which is of order 10e-22
+        while simulated < N:
+            k = N - simulated
+            # simulate uniform rvs on [0, umax] and [vmin, vmax]
+            u1 = self._umax * self._rng.uniform(size=k)
+            v1 = self._rng.uniform(self._vmin, self._vmax, size=k)
+            # apply rejection method
+            rvs = v1 / u1 + self._c
+            accept = (u1**2 <= self._pdf(rvs))
+            num_accept = np.sum(accept)
+            if num_accept > 0:
+                x[simulated:(simulated + num_accept)] = rvs[accept]
+                simulated += num_accept
+
+            if (simulated == 0) and (i*N >= 50000):
+                msg = (
+                    f"Not a single random variate could be generated in {i*N} "
+                    "attempts. The ratio of uniforms method does not appear "
+                    "to work for the provided parameters. Please check the "
+                    "pdf and the bounds."
+                )
+                raise RuntimeError(msg)
+            i += 1
+
+        return np.reshape(x, size1d)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_sensitivity_analysis.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_sensitivity_analysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..1eab7f2e266e076f00059d4570e87e5e9befab79
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_sensitivity_analysis.py
@@ -0,0 +1,713 @@
+import inspect
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any
+from collections.abc import Callable
+
+import numpy as np
+
+from scipy.stats._common import ConfidenceInterval
+from scipy.stats._qmc import check_random_state
+from scipy.stats._resampling import BootstrapResult
+from scipy.stats import qmc, bootstrap
+from scipy._lib._util import _transition_to_rng
+
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+    from scipy._lib._util import DecimalNumber, IntNumber
+
+
+__all__ = [
+    'sobol_indices'
+]
+
+
+def f_ishigami(x: "npt.ArrayLike") -> "npt.NDArray[np.inexact[Any]]":
+    r"""Ishigami function.
+
+    .. math::
+
+        Y(\mathbf{x}) = \sin x_1 + 7 \sin^2 x_2 + 0.1 x_3^4 \sin x_1
+
+    with :math:`\mathbf{x} \in [-\pi, \pi]^3`.
+
+    Parameters
+    ----------
+    x : array_like ([x1, x2, x3], n)
+
+    Returns
+    -------
+    f : array_like (n,)
+        Function evaluation.
+
+    References
+    ----------
+    .. [1] Ishigami, T. and T. Homma. "An importance quantification technique
+       in uncertainty analysis for computer models." IEEE,
+       :doi:`10.1109/ISUMA.1990.151285`, 1990.
+    """
+    x = np.atleast_2d(x)
+    f_eval = (
+        np.sin(x[0])
+        + 7 * np.sin(x[1])**2
+        + 0.1 * (x[2]**4) * np.sin(x[0])
+    )
+    return f_eval
+
+
+def sample_A_B(
+    n,
+    dists,
+    rng=None
+):
+    """Sample two matrices A and B.
+
+    Uses a Sobol' sequence with 2`d` columns to have 2 uncorrelated matrices.
+    This is more efficient than using 2 random draw of Sobol'.
+    See sec. 5 from [1]_.
+
+    Output shape is (d, n).
+
+    References
+    ----------
+    .. [1] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
+       S. Tarantola. "Variance based sensitivity analysis of model
+       output. Design and estimator for the total sensitivity index."
+       Computer Physics Communications, 181(2):259-270,
+       :doi:`10.1016/j.cpc.2009.09.018`, 2010.
+    """
+    d = len(dists)
+    A_B = qmc.Sobol(d=2*d, seed=rng, bits=64).random(n).T
+    A_B = A_B.reshape(2, d, -1)
+    try:
+        for d_, dist in enumerate(dists):
+            A_B[:, d_] = dist.ppf(A_B[:, d_])
+    except AttributeError as exc:
+        message = "Each distribution in `dists` must have method `ppf`."
+        raise ValueError(message) from exc
+    return A_B
+
+
+def sample_AB(A: np.ndarray, B: np.ndarray) -> np.ndarray:
+    """AB matrix.
+
+    AB: rows of B into A. Shape (d, d, n).
+    - Copy A into d "pages"
+    - In the first page, replace 1st rows of A with 1st row of B.
+    ...
+    - In the dth page, replace dth row of A with dth row of B.
+    - return the stack of pages
+    """
+    d, n = A.shape
+    AB = np.tile(A, (d, 1, 1))
+    i = np.arange(d)
+    AB[i, i] = B[i]
+    return AB
+
+
+def saltelli_2010(
+    f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray
+) -> tuple[np.ndarray, np.ndarray]:
+    r"""Saltelli2010 formulation.
+
+    .. math::
+
+        S_i = \frac{1}{N} \sum_{j=1}^N
+        f(\mathbf{B})_j (f(\mathbf{AB}^{(i)})_j - f(\mathbf{A})_j)
+
+    .. math::
+
+        S_{T_i} = \frac{1}{N} \sum_{j=1}^N
+        (f(\mathbf{A})_j - f(\mathbf{AB}^{(i)})_j)^2
+
+    Parameters
+    ----------
+    f_A, f_B : array_like (s, n)
+        Function values at A and B, respectively
+    f_AB : array_like (d, s, n)
+        Function values at each of the AB pages
+
+    Returns
+    -------
+    s, st : array_like (s, d)
+        First order and total order Sobol' indices.
+
+    References
+    ----------
+    .. [1] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
+       S. Tarantola. "Variance based sensitivity analysis of model
+       output. Design and estimator for the total sensitivity index."
+       Computer Physics Communications, 181(2):259-270,
+       :doi:`10.1016/j.cpc.2009.09.018`, 2010.
+    """
+    # Empirical variance calculated using output from A and B which are
+    # independent. Output of AB is not independent and cannot be used
+    var = np.var([f_A, f_B], axis=(0, -1))
+
+    # We divide by the variance to have a ratio of variance
+    # this leads to eq. 2
+    s = np.mean(f_B * (f_AB - f_A), axis=-1) / var  # Table 2 (b)
+    st = 0.5 * np.mean((f_A - f_AB) ** 2, axis=-1) / var  # Table 2 (f)
+
+    return s.T, st.T
+
+
+@dataclass
+class BootstrapSobolResult:
+    first_order: BootstrapResult
+    total_order: BootstrapResult
+
+
+@dataclass
+class SobolResult:
+    first_order: np.ndarray
+    total_order: np.ndarray
+    _indices_method: Callable
+    _f_A: np.ndarray
+    _f_B: np.ndarray
+    _f_AB: np.ndarray
+    _A: np.ndarray | None = None
+    _B: np.ndarray | None = None
+    _AB: np.ndarray | None = None
+    _bootstrap_result: BootstrapResult | None = None
+
+    def bootstrap(
+        self,
+        confidence_level: "DecimalNumber" = 0.95,
+        n_resamples: "IntNumber" = 999
+    ) -> BootstrapSobolResult:
+        """Bootstrap Sobol' indices to provide confidence intervals.
+
+        Parameters
+        ----------
+        confidence_level : float, default: ``0.95``
+            The confidence level of the confidence intervals.
+        n_resamples : int, default: ``999``
+            The number of resamples performed to form the bootstrap
+            distribution of the indices.
+
+        Returns
+        -------
+        res : BootstrapSobolResult
+            Bootstrap result containing the confidence intervals and the
+            bootstrap distribution of the indices.
+
+            An object with attributes:
+
+            first_order : BootstrapResult
+                Bootstrap result of the first order indices.
+            total_order : BootstrapResult
+                Bootstrap result of the total order indices.
+            See `BootstrapResult` for more details.
+
+        """
+        def statistic(idx):
+            f_A_ = self._f_A[:, idx]
+            f_B_ = self._f_B[:, idx]
+            f_AB_ = self._f_AB[..., idx]
+            return self._indices_method(f_A_, f_B_, f_AB_)
+
+        n = self._f_A.shape[1]
+
+        res = bootstrap(
+            [np.arange(n)], statistic=statistic, method="BCa",
+            n_resamples=n_resamples,
+            confidence_level=confidence_level,
+            bootstrap_result=self._bootstrap_result
+        )
+        self._bootstrap_result = res
+
+        first_order = BootstrapResult(
+            confidence_interval=ConfidenceInterval(
+                res.confidence_interval.low[0], res.confidence_interval.high[0]
+            ),
+            bootstrap_distribution=res.bootstrap_distribution[0],
+            standard_error=res.standard_error[0],
+        )
+        total_order = BootstrapResult(
+            confidence_interval=ConfidenceInterval(
+                res.confidence_interval.low[1], res.confidence_interval.high[1]
+            ),
+            bootstrap_distribution=res.bootstrap_distribution[1],
+            standard_error=res.standard_error[1],
+        )
+
+        return BootstrapSobolResult(
+            first_order=first_order, total_order=total_order
+        )
+
+@_transition_to_rng('random_state', replace_doc=False)
+def sobol_indices(
+    *,
+    func,
+    n,
+    dists=None,
+    method='saltelli_2010',
+    rng=None
+):
+    r"""Global sensitivity indices of Sobol'.
+
+    Parameters
+    ----------
+    func : callable or dict(str, array_like)
+        If `func` is a callable, function to compute the Sobol' indices from.
+        Its signature must be::
+
+            func(x: ArrayLike) -> ArrayLike
+
+        with ``x`` of shape ``(d, n)`` and output of shape ``(s, n)`` where:
+
+        - ``d`` is the input dimensionality of `func`
+          (number of input variables),
+        - ``s`` is the output dimensionality of `func`
+          (number of output variables), and
+        - ``n`` is the number of samples (see `n` below).
+
+        Function evaluation values must be finite.
+
+        If `func` is a dictionary, contains the function evaluations from three
+        different arrays. Keys must be: ``f_A``, ``f_B`` and ``f_AB``.
+        ``f_A`` and ``f_B`` should have a shape ``(s, n)`` and ``f_AB``
+        should have a shape ``(d, s, n)``.
+        This is an advanced feature and misuse can lead to wrong analysis.
+    n : int
+        Number of samples used to generate the matrices ``A`` and ``B``.
+        Must be a power of 2. The total number of points at which `func` is
+        evaluated will be ``n*(d+2)``.
+    dists : list(distributions), optional
+        List of each parameter's distribution. The distribution of parameters
+        depends on the application and should be carefully chosen.
+        Parameters are assumed to be independently distributed, meaning there
+        is no constraint nor relationship between their values.
+
+        Distributions must be an instance of a class with a ``ppf``
+        method.
+
+        Must be specified if `func` is a callable, and ignored otherwise.
+    method : Callable or str, default: 'saltelli_2010'
+        Method used to compute the first and total Sobol' indices.
+
+        If a callable, its signature must be::
+
+            func(f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray)
+            -> Tuple[np.ndarray, np.ndarray]
+
+        with ``f_A, f_B`` of shape ``(s, n)`` and ``f_AB`` of shape
+        ``(d, s, n)``.
+        These arrays contain the function evaluations from three different sets
+        of samples.
+        The output is a tuple of the first and total indices with
+        shape ``(s, d)``.
+        This is an advanced feature and misuse can lead to wrong analysis.
+    rng : `numpy.random.Generator`, optional
+        Pseudorandom number generator state. When `rng` is None, a new
+        `numpy.random.Generator` is created using entropy from the
+        operating system. Types other than `numpy.random.Generator` are
+        passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+        .. versionchanged:: 1.15.0
+
+            As part of the `SPEC-007 `_
+            transition from use of `numpy.random.RandomState` to
+            `numpy.random.Generator`, this keyword was changed from `random_state` to
+            `rng`. For an interim period, both keywords will continue to work, although
+            only one may be specified at a time. After the interim period, function
+            calls using the `random_state` keyword will emit warnings. Following a
+            deprecation period, the `random_state` keyword will be removed.
+
+    Returns
+    -------
+    res : SobolResult
+        An object with attributes:
+
+        first_order : ndarray of shape (s, d)
+            First order Sobol' indices.
+        total_order : ndarray of shape (s, d)
+            Total order Sobol' indices.
+
+        And method:
+
+        bootstrap(confidence_level: float, n_resamples: int)
+        -> BootstrapSobolResult
+
+            A method providing confidence intervals on the indices.
+            See `scipy.stats.bootstrap` for more details.
+
+            The bootstrapping is done on both first and total order indices,
+            and they are available in `BootstrapSobolResult` as attributes
+            ``first_order`` and ``total_order``.
+
+    Notes
+    -----
+    The Sobol' method [1]_, [2]_ is a variance-based Sensitivity Analysis which
+    obtains the contribution of each parameter to the variance of the
+    quantities of interest (QoIs; i.e., the outputs of `func`).
+    Respective contributions can be used to rank the parameters and
+    also gauge the complexity of the model by computing the
+    model's effective (or mean) dimension.
+
+    .. note::
+
+        Parameters are assumed to be independently distributed. Each
+        parameter can still follow any distribution. In fact, the distribution
+        is very important and should match the real distribution of the
+        parameters.
+
+    It uses a functional decomposition of the variance of the function to
+    explore
+
+    .. math::
+
+        \mathbb{V}(Y) = \sum_{i}^{d} \mathbb{V}_i (Y) + \sum_{i= 2**12``. The more complex the model is,
+        the more samples will be needed.
+
+        Even for a purely additive model, the indices may not sum to 1 due
+        to numerical noise.
+
+    References
+    ----------
+    .. [1] Sobol, I. M.. "Sensitivity analysis for nonlinear mathematical
+       models." Mathematical Modeling and Computational Experiment, 1:407-414,
+       1993.
+    .. [2] Sobol, I. M. (2001). "Global sensitivity indices for nonlinear
+       mathematical models and their Monte Carlo estimates." Mathematics
+       and Computers in Simulation, 55(1-3):271-280,
+       :doi:`10.1016/S0378-4754(00)00270-6`, 2001.
+    .. [3] Saltelli, A. "Making best use of model evaluations to
+       compute sensitivity indices."  Computer Physics Communications,
+       145(2):280-297, :doi:`10.1016/S0010-4655(02)00280-1`, 2002.
+    .. [4] Saltelli, A., M. Ratto, T. Andres, F. Campolongo, J. Cariboni,
+       D. Gatelli, M. Saisana, and S. Tarantola. "Global Sensitivity Analysis.
+       The Primer." 2007.
+    .. [5] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
+       S. Tarantola. "Variance based sensitivity analysis of model
+       output. Design and estimator for the total sensitivity index."
+       Computer Physics Communications, 181(2):259-270,
+       :doi:`10.1016/j.cpc.2009.09.018`, 2010.
+    .. [6] Ishigami, T. and T. Homma. "An importance quantification technique
+       in uncertainty analysis for computer models." IEEE,
+       :doi:`10.1109/ISUMA.1990.151285`, 1990.
+
+    Examples
+    --------
+    The following is an example with the Ishigami function [6]_
+
+    .. math::
+
+        Y(\mathbf{x}) = \sin x_1 + 7 \sin^2 x_2 + 0.1 x_3^4 \sin x_1,
+
+    with :math:`\mathbf{x} \in [-\pi, \pi]^3`. This function exhibits strong
+    non-linearity and non-monotonicity.
+
+    Remember, Sobol' indices assumes that samples are independently
+    distributed. In this case we use a uniform distribution on each marginals.
+
+    >>> import numpy as np
+    >>> from scipy.stats import sobol_indices, uniform
+    >>> rng = np.random.default_rng()
+    >>> def f_ishigami(x):
+    ...     f_eval = (
+    ...         np.sin(x[0])
+    ...         + 7 * np.sin(x[1])**2
+    ...         + 0.1 * (x[2]**4) * np.sin(x[0])
+    ...     )
+    ...     return f_eval
+    >>> indices = sobol_indices(
+    ...     func=f_ishigami, n=1024,
+    ...     dists=[
+    ...         uniform(loc=-np.pi, scale=2*np.pi),
+    ...         uniform(loc=-np.pi, scale=2*np.pi),
+    ...         uniform(loc=-np.pi, scale=2*np.pi)
+    ...     ],
+    ...     rng=rng
+    ... )
+    >>> indices.first_order
+    array([0.31637954, 0.43781162, 0.00318825])
+    >>> indices.total_order
+    array([0.56122127, 0.44287857, 0.24229595])
+
+    Confidence interval can be obtained using bootstrapping.
+
+    >>> boot = indices.bootstrap()
+
+    Then, this information can be easily visualized.
+
+    >>> import matplotlib.pyplot as plt
+    >>> fig, axs = plt.subplots(1, 2, figsize=(9, 4))
+    >>> _ = axs[0].errorbar(
+    ...     [1, 2, 3], indices.first_order, fmt='o',
+    ...     yerr=[
+    ...         indices.first_order - boot.first_order.confidence_interval.low,
+    ...         boot.first_order.confidence_interval.high - indices.first_order
+    ...     ],
+    ... )
+    >>> axs[0].set_ylabel("First order Sobol' indices")
+    >>> axs[0].set_xlabel('Input parameters')
+    >>> axs[0].set_xticks([1, 2, 3])
+    >>> _ = axs[1].errorbar(
+    ...     [1, 2, 3], indices.total_order, fmt='o',
+    ...     yerr=[
+    ...         indices.total_order - boot.total_order.confidence_interval.low,
+    ...         boot.total_order.confidence_interval.high - indices.total_order
+    ...     ],
+    ... )
+    >>> axs[1].set_ylabel("Total order Sobol' indices")
+    >>> axs[1].set_xlabel('Input parameters')
+    >>> axs[1].set_xticks([1, 2, 3])
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    .. note::
+
+        By default, `scipy.stats.uniform` has support ``[0, 1]``.
+        Using the parameters ``loc`` and ``scale``, one obtains the uniform
+        distribution on ``[loc, loc + scale]``.
+
+    This result is particularly interesting because the first order index
+    :math:`S_{x_3} = 0` whereas its total order is :math:`S_{T_{x_3}} = 0.244`.
+    This means that higher order interactions with :math:`x_3` are responsible
+    for the difference. Almost 25% of the observed variance
+    on the QoI is due to the correlations between :math:`x_3` and :math:`x_1`,
+    although :math:`x_3` by itself has no impact on the QoI.
+
+    The following gives a visual explanation of Sobol' indices on this
+    function. Let's generate 1024 samples in :math:`[-\pi, \pi]^3` and
+    calculate the value of the output.
+
+    >>> from scipy.stats import qmc
+    >>> n_dim = 3
+    >>> p_labels = ['$x_1$', '$x_2$', '$x_3$']
+    >>> sample = qmc.Sobol(d=n_dim, seed=rng).random(1024)
+    >>> sample = qmc.scale(
+    ...     sample=sample,
+    ...     l_bounds=[-np.pi, -np.pi, -np.pi],
+    ...     u_bounds=[np.pi, np.pi, np.pi]
+    ... )
+    >>> output = f_ishigami(sample.T)
+
+    Now we can do scatter plots of the output with respect to each parameter.
+    This gives a visual way to understand how each parameter impacts the
+    output of the function.
+
+    >>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4))
+    >>> for i in range(n_dim):
+    ...     xi = sample[:, i]
+    ...     ax[i].scatter(xi, output, marker='+')
+    ...     ax[i].set_xlabel(p_labels[i])
+    >>> ax[0].set_ylabel('Y')
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    Now Sobol' goes a step further:
+    by conditioning the output value by given values of the parameter
+    (black lines), the conditional output mean is computed. It corresponds to
+    the term :math:`\mathbb{E}(Y|x_i)`. Taking the variance of this term gives
+    the numerator of the Sobol' indices.
+
+    >>> mini = np.min(output)
+    >>> maxi = np.max(output)
+    >>> n_bins = 10
+    >>> bins = np.linspace(-np.pi, np.pi, num=n_bins, endpoint=False)
+    >>> dx = bins[1] - bins[0]
+    >>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4))
+    >>> for i in range(n_dim):
+    ...     xi = sample[:, i]
+    ...     ax[i].scatter(xi, output, marker='+')
+    ...     ax[i].set_xlabel(p_labels[i])
+    ...     for bin_ in bins:
+    ...         idx = np.where((bin_ <= xi) & (xi <= bin_ + dx))
+    ...         xi_ = xi[idx]
+    ...         y_ = output[idx]
+    ...         ave_y_ = np.mean(y_)
+    ...         ax[i].plot([bin_ + dx/2] * 2, [mini, maxi], c='k')
+    ...         ax[i].scatter(bin_ + dx/2, ave_y_, c='r')
+    >>> ax[0].set_ylabel('Y')
+    >>> plt.tight_layout()
+    >>> plt.show()
+
+    Looking at :math:`x_3`, the variance
+    of the mean is zero leading to :math:`S_{x_3} = 0`. But we can further
+    observe that the variance of the output is not constant along the parameter
+    values of :math:`x_3`. This heteroscedasticity is explained by higher order
+    interactions. Moreover, an heteroscedasticity is also noticeable on
+    :math:`x_1` leading to an interaction between :math:`x_3` and :math:`x_1`.
+    On :math:`x_2`, the variance seems to be constant and thus null interaction
+    with this parameter can be supposed.
+
+    This case is fairly simple to analyse visually---although it is only a
+    qualitative analysis. Nevertheless, when the number of input parameters
+    increases such analysis becomes unrealistic as it would be difficult to
+    conclude on high-order terms. Hence the benefit of using Sobol' indices.
+
+    """
+    rng = check_random_state(rng)
+
+    n_ = int(n)
+    if not (n_ & (n_ - 1) == 0) or n != n_:
+        raise ValueError(
+            "The balance properties of Sobol' points require 'n' "
+            "to be a power of 2."
+        )
+    n = n_
+
+    if not callable(method):
+        indices_methods = {
+            "saltelli_2010": saltelli_2010,
+        }
+        try:
+            method = method.lower()  # type: ignore[assignment]
+            indices_method_ = indices_methods[method]
+        except KeyError as exc:
+            message = (
+                f"{method!r} is not a valid 'method'. It must be one of"
+                f" {set(indices_methods)!r} or a callable."
+            )
+            raise ValueError(message) from exc
+    else:
+        indices_method_ = method
+        sig = inspect.signature(indices_method_)
+
+        if set(sig.parameters) != {'f_A', 'f_B', 'f_AB'}:
+            message = (
+                "If 'method' is a callable, it must have the following"
+                f" signature: {inspect.signature(saltelli_2010)}"
+            )
+            raise ValueError(message)
+
+    def indices_method(f_A, f_B, f_AB):
+        """Wrap indices method to ensure proper output dimension.
+
+        1D when single output, 2D otherwise.
+        """
+        return np.squeeze(indices_method_(f_A=f_A, f_B=f_B, f_AB=f_AB))
+
+    if callable(func):
+        if dists is None:
+            raise ValueError(
+                "'dists' must be defined when 'func' is a callable."
+            )
+
+        def wrapped_func(x):
+            return np.atleast_2d(func(x))
+
+        A, B = sample_A_B(n=n, dists=dists, rng=rng)
+        AB = sample_AB(A=A, B=B)
+
+        f_A = wrapped_func(A)
+
+        if f_A.shape[1] != n:
+            raise ValueError(
+                "'func' output should have a shape ``(s, -1)`` with ``s`` "
+                "the number of output."
+            )
+
+        def funcAB(AB):
+            d, d, n = AB.shape
+            AB = np.moveaxis(AB, 0, -1).reshape(d, n*d)
+            f_AB = wrapped_func(AB)
+            return np.moveaxis(f_AB.reshape((-1, n, d)), -1, 0)
+
+        f_B = wrapped_func(B)
+        f_AB = funcAB(AB)
+    else:
+        message = (
+            "When 'func' is a dictionary, it must contain the following "
+            "keys: 'f_A', 'f_B' and 'f_AB'."
+            "'f_A' and 'f_B' should have a shape ``(s, n)`` and 'f_AB' "
+            "should have a shape ``(d, s, n)``."
+        )
+        try:
+            f_A, f_B, f_AB = map(lambda arr: arr.copy(), np.atleast_2d(
+                func['f_A'], func['f_B'], func['f_AB']
+            ))
+        except KeyError as exc:
+            raise ValueError(message) from exc
+
+        if f_A.shape[1] != n or f_A.shape != f_B.shape or \
+                f_AB.shape == f_A.shape or f_AB.shape[-1] % n != 0:
+            raise ValueError(message)
+
+    # Normalization by mean
+    # Sobol', I. and Levitan, Y. L. (1999). On the use of variance reducing
+    # multipliers in monte carlo computations of a global sensitivity index.
+    # Computer Physics Communications, 117(1) :52-61.
+    mean = np.mean([f_A, f_B], axis=(0, -1)).reshape(-1, 1)
+    f_A -= mean
+    f_B -= mean
+    f_AB -= mean
+
+    # Compute indices
+    # Filter warnings for constant output as var = 0
+    with np.errstate(divide='ignore', invalid='ignore'):
+        first_order, total_order = indices_method(f_A=f_A, f_B=f_B, f_AB=f_AB)
+
+    # null variance means null indices
+    first_order[~np.isfinite(first_order)] = 0
+    total_order[~np.isfinite(total_order)] = 0
+
+    res = dict(
+        first_order=first_order,
+        total_order=total_order,
+        _indices_method=indices_method,
+        _f_A=f_A,
+        _f_B=f_B,
+        _f_AB=f_AB
+    )
+
+    if callable(func):
+        res.update(
+            dict(
+                _A=A,
+                _B=B,
+                _AB=AB,
+            )
+        )
+
+    return SobolResult(**res)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_sobol.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_sobol.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..7ca5e3a9c1a142b25ac26401e9ab1cb6726c877f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_sobol.pyi
@@ -0,0 +1,54 @@
+import numpy as np
+from scipy._lib._util import IntNumber
+from typing import Literal
+
+def _initialize_v(
+    v : np.ndarray, 
+    dim : IntNumber,
+    bits: IntNumber
+) -> None: ...
+
+def _cscramble (
+    dim : IntNumber,
+    bits: IntNumber,
+    ltm : np.ndarray,
+    sv: np.ndarray
+) -> None: ...
+
+def _fill_p_cumulative(
+    p: np.ndarray,
+    p_cumulative: np.ndarray
+) -> None: ...
+
+def _draw(
+    n : IntNumber,
+    num_gen: IntNumber,
+    dim: IntNumber,
+    scale: float,
+    sv: np.ndarray,
+    quasi: np.ndarray,
+    sample: np.ndarray
+    ) -> None: ...
+
+def _fast_forward(
+    n: IntNumber,
+    num_gen: IntNumber,
+    dim: IntNumber,
+    sv: np.ndarray,
+    quasi: np.ndarray
+    ) -> None: ...
+
+def _categorize(
+    draws: np.ndarray,
+    p_cumulative: np.ndarray,
+    result: np.ndarray
+    ) -> None: ...
+
+_MAXDIM: Literal[21201]
+_MAXDEG: Literal[18]
+
+def _test_find_index(
+    p_cumulative: np.ndarray, 
+    size: int, 
+    value: float
+    ) -> int: ...
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_stats.pxd b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_stats.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..e01565f75fe232446e4b8b0b50fdf645c8506108
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_stats.pxd
@@ -0,0 +1,10 @@
+# destined to be used in a LowLevelCallable
+
+cdef double _geninvgauss_pdf(double x, void *user_data) noexcept nogil
+cdef double _studentized_range_cdf(int n, double[2] x, void *user_data) noexcept nogil
+cdef double _studentized_range_cdf_asymptotic(double z, void *user_data) noexcept nogil
+cdef double _studentized_range_pdf(int n, double[2] x, void *user_data) noexcept nogil
+cdef double _studentized_range_pdf_asymptotic(double z, void *user_data) noexcept nogil
+cdef double _studentized_range_moment(int n, double[3] x_arg, void *user_data) noexcept nogil
+cdef double _genhyperbolic_pdf(double x, void *user_data) noexcept nogil
+cdef double _genhyperbolic_logpdf(double x, void *user_data) noexcept nogil
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_stats_mstats_common.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_stats_mstats_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..6900eba1fa6157c9de956255c49f5cbce0029c11
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_stats_mstats_common.py
@@ -0,0 +1,303 @@
+import warnings
+import numpy as np
+from . import distributions
+from .._lib._bunch import _make_tuple_bunch
+from ._stats_pythran import siegelslopes as siegelslopes_pythran
+
+__all__ = ['_find_repeats', 'theilslopes', 'siegelslopes']
+
+# This is not a namedtuple for backwards compatibility. See PR #12983
+TheilslopesResult = _make_tuple_bunch('TheilslopesResult',
+                                      ['slope', 'intercept',
+                                       'low_slope', 'high_slope'])
+SiegelslopesResult = _make_tuple_bunch('SiegelslopesResult',
+                                       ['slope', 'intercept'])
+
+
+def theilslopes(y, x=None, alpha=0.95, method='separate'):
+    r"""
+    Computes the Theil-Sen estimator for a set of points (x, y).
+
+    `theilslopes` implements a method for robust linear regression.  It
+    computes the slope as the median of all slopes between paired values.
+
+    Parameters
+    ----------
+    y : array_like
+        Dependent variable.
+    x : array_like or None, optional
+        Independent variable. If None, use ``arange(len(y))`` instead.
+    alpha : float, optional
+        Confidence degree between 0 and 1. Default is 95% confidence.
+        Note that `alpha` is symmetric around 0.5, i.e. both 0.1 and 0.9 are
+        interpreted as "find the 90% confidence interval".
+    method : {'joint', 'separate'}, optional
+        Method to be used for computing estimate for intercept.
+        Following methods are supported,
+
+            * 'joint': Uses np.median(y - slope * x) as intercept.
+            * 'separate': Uses np.median(y) - slope * np.median(x)
+                          as intercept.
+
+        The default is 'separate'.
+
+        .. versionadded:: 1.8.0
+
+    Returns
+    -------
+    result : ``TheilslopesResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Theil slope.
+        intercept : float
+            Intercept of the Theil line.
+        low_slope : float
+            Lower bound of the confidence interval on `slope`.
+        high_slope : float
+            Upper bound of the confidence interval on `slope`.
+
+    See Also
+    --------
+    siegelslopes : a similar technique using repeated medians
+
+    Notes
+    -----
+    The implementation of `theilslopes` follows [1]_. The intercept is
+    not defined in [1]_, and here it is defined as ``median(y) -
+    slope*median(x)``, which is given in [3]_. Other definitions of
+    the intercept exist in the literature such as  ``median(y - slope*x)``
+    in [4]_. The approach to compute the intercept can be determined by the
+    parameter ``method``. A confidence interval for the intercept is not
+    given as this question is not addressed in [1]_.
+
+    For compatibility with older versions of SciPy, the return value acts
+    like a ``namedtuple`` of length 4, with fields ``slope``, ``intercept``,
+    ``low_slope``, and ``high_slope``, so one can continue to write::
+
+        slope, intercept, low_slope, high_slope = theilslopes(y, x)
+
+    References
+    ----------
+    .. [1] P.K. Sen, "Estimates of the regression coefficient based on
+           Kendall's tau", J. Am. Stat. Assoc., Vol. 63, pp. 1379-1389, 1968.
+    .. [2] H. Theil, "A rank-invariant method of linear and polynomial
+           regression analysis I, II and III",  Nederl. Akad. Wetensch., Proc.
+           53:, pp. 386-392, pp. 521-525, pp. 1397-1412, 1950.
+    .. [3] W.L. Conover, "Practical nonparametric statistics", 2nd ed.,
+           John Wiley and Sons, New York, pp. 493.
+    .. [4] https://en.wikipedia.org/wiki/Theil%E2%80%93Sen_estimator
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-5, 5, num=150)
+    >>> y = x + np.random.normal(size=x.size)
+    >>> y[11:15] += 10  # add outliers
+    >>> y[-5:] -= 7
+
+    Compute the slope, intercept and 90% confidence interval.  For comparison,
+    also compute the least-squares fit with `linregress`:
+
+    >>> res = stats.theilslopes(y, x, 0.90, method='separate')
+    >>> lsq_res = stats.linregress(x, y)
+
+    Plot the results. The Theil-Sen regression line is shown in red, with the
+    dashed red lines illustrating the confidence interval of the slope (note
+    that the dashed red lines are not the confidence interval of the regression
+    as the confidence interval of the intercept is not included). The green
+    line shows the least-squares fit for comparison.
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, y, 'b.')
+    >>> ax.plot(x, res[1] + res[0] * x, 'r-')
+    >>> ax.plot(x, res[1] + res[2] * x, 'r--')
+    >>> ax.plot(x, res[1] + res[3] * x, 'r--')
+    >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-')
+    >>> plt.show()
+
+    """
+    if method not in ['joint', 'separate']:
+        raise ValueError("method must be either 'joint' or 'separate'."
+                         f"'{method}' is invalid.")
+    # We copy both x and y so we can use _find_repeats.
+    y = np.array(y, dtype=float, copy=True).ravel()
+    if x is None:
+        x = np.arange(len(y), dtype=float)
+    else:
+        x = np.array(x, dtype=float, copy=True).ravel()
+        if len(x) != len(y):
+            raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
+
+    # Compute sorted slopes only when deltax > 0
+    deltax = x[:, np.newaxis] - x
+    deltay = y[:, np.newaxis] - y
+    slopes = deltay[deltax > 0] / deltax[deltax > 0]
+    if not slopes.size:
+        msg = "All `x` coordinates are identical."
+        warnings.warn(msg, RuntimeWarning, stacklevel=2)
+    slopes.sort()
+    medslope = np.median(slopes)
+    if method == 'joint':
+        medinter = np.median(y - medslope * x)
+    else:
+        medinter = np.median(y) - medslope * np.median(x)
+    # Now compute confidence intervals
+    if alpha > 0.5:
+        alpha = 1. - alpha
+
+    z = distributions.norm.ppf(alpha / 2.)
+    # This implements (2.6) from Sen (1968)
+    _, nxreps = _find_repeats(x)
+    _, nyreps = _find_repeats(y)
+    nt = len(slopes)       # N in Sen (1968)
+    ny = len(y)            # n in Sen (1968)
+    # Equation 2.6 in Sen (1968):
+    sigsq = 1/18. * (ny * (ny-1) * (2*ny+5) -
+                     sum(k * (k-1) * (2*k + 5) for k in nxreps) -
+                     sum(k * (k-1) * (2*k + 5) for k in nyreps))
+    # Find the confidence interval indices in `slopes`
+    try:
+        sigma = np.sqrt(sigsq)
+        Ru = min(int(np.round((nt - z*sigma)/2.)), len(slopes)-1)
+        Rl = max(int(np.round((nt + z*sigma)/2.)) - 1, 0)
+        delta = slopes[[Rl, Ru]]
+    except (ValueError, IndexError):
+        delta = (np.nan, np.nan)
+
+    return TheilslopesResult(slope=medslope, intercept=medinter,
+                             low_slope=delta[0], high_slope=delta[1])
+
+
+def _find_repeats(arr):
+    # This function assumes it may clobber its input.
+    if len(arr) == 0:
+        return np.array(0, np.float64), np.array(0, np.intp)
+
+    # XXX This cast was previously needed for the Fortran implementation,
+    # should we ditch it?
+    arr = np.asarray(arr, np.float64).ravel()
+    arr.sort()
+
+    # Taken from NumPy 1.9's np.unique.
+    change = np.concatenate(([True], arr[1:] != arr[:-1]))
+    unique = arr[change]
+    change_idx = np.concatenate(np.nonzero(change) + ([arr.size],))
+    freq = np.diff(change_idx)
+    atleast2 = freq > 1
+    return unique[atleast2], freq[atleast2]
+
+
+def siegelslopes(y, x=None, method="hierarchical"):
+    r"""
+    Computes the Siegel estimator for a set of points (x, y).
+
+    `siegelslopes` implements a method for robust linear regression
+    using repeated medians (see [1]_) to fit a line to the points (x, y).
+    The method is robust to outliers with an asymptotic breakdown point
+    of 50%.
+
+    Parameters
+    ----------
+    y : array_like
+        Dependent variable.
+    x : array_like or None, optional
+        Independent variable. If None, use ``arange(len(y))`` instead.
+    method : {'hierarchical', 'separate'}
+        If 'hierarchical', estimate the intercept using the estimated
+        slope ``slope`` (default option).
+        If 'separate', estimate the intercept independent of the estimated
+        slope. See Notes for details.
+
+    Returns
+    -------
+    result : ``SiegelslopesResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Estimate of the slope of the regression line.
+        intercept : float
+            Estimate of the intercept of the regression line.
+
+    See Also
+    --------
+    theilslopes : a similar technique without repeated medians
+
+    Notes
+    -----
+    With ``n = len(y)``, compute ``m_j`` as the median of
+    the slopes from the point ``(x[j], y[j])`` to all other `n-1` points.
+    ``slope`` is then the median of all slopes ``m_j``.
+    Two ways are given to estimate the intercept in [1]_ which can be chosen
+    via the parameter ``method``.
+    The hierarchical approach uses the estimated slope ``slope``
+    and computes ``intercept`` as the median of ``y - slope*x``.
+    The other approach estimates the intercept separately as follows: for
+    each point ``(x[j], y[j])``, compute the intercepts of all the `n-1`
+    lines through the remaining points and take the median ``i_j``.
+    ``intercept`` is the median of the ``i_j``.
+
+    The implementation computes `n` times the median of a vector of size `n`
+    which can be slow for large vectors. There are more efficient algorithms
+    (see [2]_) which are not implemented here.
+
+    For compatibility with older versions of SciPy, the return value acts
+    like a ``namedtuple`` of length 2, with fields ``slope`` and
+    ``intercept``, so one can continue to write::
+
+        slope, intercept = siegelslopes(y, x)
+
+    References
+    ----------
+    .. [1] A. Siegel, "Robust Regression Using Repeated Medians",
+           Biometrika, Vol. 69, pp. 242-244, 1982.
+
+    .. [2] A. Stein and M. Werman, "Finding the repeated median regression
+           line", Proceedings of the Third Annual ACM-SIAM Symposium on
+           Discrete Algorithms, pp. 409-413, 1992.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> import matplotlib.pyplot as plt
+
+    >>> x = np.linspace(-5, 5, num=150)
+    >>> y = x + np.random.normal(size=x.size)
+    >>> y[11:15] += 10  # add outliers
+    >>> y[-5:] -= 7
+
+    Compute the slope and intercept.  For comparison, also compute the
+    least-squares fit with `linregress`:
+
+    >>> res = stats.siegelslopes(y, x)
+    >>> lsq_res = stats.linregress(x, y)
+
+    Plot the results. The Siegel regression line is shown in red. The green
+    line shows the least-squares fit for comparison.
+
+    >>> fig = plt.figure()
+    >>> ax = fig.add_subplot(111)
+    >>> ax.plot(x, y, 'b.')
+    >>> ax.plot(x, res[1] + res[0] * x, 'r-')
+    >>> ax.plot(x, lsq_res[1] + lsq_res[0] * x, 'g-')
+    >>> plt.show()
+
+    """
+    if method not in ['hierarchical', 'separate']:
+        raise ValueError("method can only be 'hierarchical' or 'separate'")
+    y = np.asarray(y).ravel()
+    if x is None:
+        x = np.arange(len(y), dtype=float)
+    else:
+        x = np.asarray(x, dtype=float).ravel()
+        if len(x) != len(y):
+            raise ValueError(f"Incompatible lengths ! ({len(y)}<>{len(x)})")
+    dtype = np.result_type(x, y, np.float32)  # use at least float32
+    y, x = y.astype(dtype), x.astype(dtype)
+    medslope, medinter = siegelslopes_pythran(y, x, method)
+    return SiegelslopesResult(slope=medslope, intercept=medinter)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_stats_py.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_stats_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b8c1850cd0dad3d654216ae45dad04dafaa983b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_stats_py.py
@@ -0,0 +1,11015 @@
+# Copyright 2002 Gary Strangman.  All rights reserved
+# Copyright 2002-2016 The SciPy Developers
+#
+# The original code from Gary Strangman was heavily adapted for
+# use in SciPy by Travis Oliphant.  The original code came with the
+# following disclaimer:
+#
+# This software is provided "as-is".  There are no expressed or implied
+# warranties of any kind, including, but not limited to, the warranties
+# of merchantability and fitness for a given application.  In no event
+# shall Gary Strangman be liable for any direct, indirect, incidental,
+# special, exemplary or consequential damages (including, but not limited
+# to, loss of use, data or profits, or business interruption) however
+# caused and on any theory of liability, whether in contract, strict
+# liability or tort (including negligence or otherwise) arising in any way
+# out of the use of this software, even if advised of the possibility of
+# such damage.
+
+"""
+A collection of basic statistical functions for Python.
+
+References
+----------
+.. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+   Probability and Statistics Tables and Formulae. Chapman & Hall: New
+   York. 2000.
+
+"""
+import warnings
+import math
+from math import gcd
+from collections import namedtuple
+from collections.abc import Sequence
+
+import numpy as np
+from numpy import array, asarray, ma
+
+from scipy import sparse
+from scipy.spatial import distance_matrix
+
+from scipy.optimize import milp, LinearConstraint
+from scipy._lib._util import (check_random_state, _get_nan,
+                              _rename_parameter, _contains_nan,
+                              AxisError, _lazywhere)
+from scipy._lib.deprecation import _deprecate_positional_args
+
+
+import scipy.special as special
+# Import unused here but needs to stay until end of deprecation periode
+# See https://github.com/scipy/scipy/issues/15765#issuecomment-1875564522
+from scipy import linalg  # noqa: F401
+from . import distributions
+from . import _mstats_basic as mstats_basic
+
+from ._stats_mstats_common import _find_repeats, theilslopes, siegelslopes
+from ._stats import _kendall_dis, _toint64, _weightedrankedtau
+
+from dataclasses import dataclass, field
+from ._hypotests import _all_partitions
+from ._stats_pythran import _compute_outer_prob_inside_method
+from ._resampling import (MonteCarloMethod, PermutationMethod, BootstrapMethod,
+                          monte_carlo_test, permutation_test, bootstrap,
+                          _batch_generator)
+from ._axis_nan_policy import (_axis_nan_policy_factory,
+                               _broadcast_concatenate, _broadcast_shapes,
+                               _broadcast_array_shapes_remove_axis, SmallSampleWarning,
+                               too_small_1d_not_omit, too_small_1d_omit,
+                               too_small_nd_not_omit, too_small_nd_omit)
+from ._binomtest import _binary_search_for_binom_tst as _binary_search
+from scipy._lib._bunch import _make_tuple_bunch
+from scipy import stats
+from scipy.optimize import root_scalar
+from scipy._lib._util import normalize_axis_index
+from scipy._lib._array_api import (
+    _asarray,
+    array_namespace,
+    is_numpy,
+    xp_size,
+    xp_moveaxis_to_end,
+    xp_sign,
+    xp_vector_norm,
+    xp_broadcast_promote,
+)
+from scipy._lib import array_api_extra as xpx
+from scipy._lib.deprecation import _deprecated
+
+
+# Functions/classes in other files should be added in `__init__.py`, not here
+__all__ = ['find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar',
+           'tmin', 'tmax', 'tstd', 'tsem', 'moment',
+           'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
+           'normaltest', 'jarque_bera',
+           'scoreatpercentile', 'percentileofscore',
+           'cumfreq', 'relfreq', 'obrientransform',
+           'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd',
+           'median_abs_deviation',
+           'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
+           'f_oneway', 'pearsonr', 'fisher_exact',
+           'spearmanr', 'pointbiserialr',
+           'kendalltau', 'weightedtau',
+           'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
+           'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
+           'kstest', 'ks_1samp', 'ks_2samp',
+           'chisquare', 'power_divergence',
+           'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
+           'rankdata', 'combine_pvalues', 'quantile_test',
+           'wasserstein_distance', 'wasserstein_distance_nd', 'energy_distance',
+           'brunnermunzel', 'alexandergovern',
+           'expectile', 'lmoment']
+
+
+def _chk_asarray(a, axis, *, xp=None):
+    if xp is None:
+        xp = array_namespace(a)
+
+    if axis is None:
+        a = xp.reshape(a, (-1,))
+        outaxis = 0
+    else:
+        a = xp.asarray(a)
+        outaxis = axis
+
+    if a.ndim == 0:
+        a = xp.reshape(a, (-1,))
+
+    return a, outaxis
+
+
+def _chk2_asarray(a, b, axis):
+    if axis is None:
+        a = np.ravel(a)
+        b = np.ravel(b)
+        outaxis = 0
+    else:
+        a = np.asarray(a)
+        b = np.asarray(b)
+        outaxis = axis
+
+    if a.ndim == 0:
+        a = np.atleast_1d(a)
+    if b.ndim == 0:
+        b = np.atleast_1d(b)
+
+    return a, b, outaxis
+
+
+def _convert_common_float(*arrays, xp=None):
+    xp = array_namespace(*arrays) if xp is None else xp
+    arrays = [_asarray(array, subok=True) for array in arrays]
+    dtypes = [(xp.asarray(1.).dtype if xp.isdtype(array.dtype, 'integral')
+               else array.dtype) for array in arrays]
+    dtype = xp.result_type(*dtypes)
+    arrays = [xp.astype(array, dtype, copy=False) for array in arrays]
+    return arrays[0] if len(arrays)==1 else tuple(arrays)
+
+
+SignificanceResult = _make_tuple_bunch('SignificanceResult',
+                                       ['statistic', 'pvalue'], [])
+
+
+# note that `weights` are paired with `x`
+@_axis_nan_policy_factory(
+        lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
+        result_to_tuple=lambda x: (x,), kwd_samples=['weights'])
+def gmean(a, axis=0, dtype=None, weights=None):
+    r"""Compute the weighted geometric mean along the specified axis.
+
+    The weighted geometric mean of the array :math:`a_i` associated to weights
+    :math:`w_i` is:
+
+    .. math::
+
+        \exp \left( \frac{ \sum_{i=1}^n w_i \ln a_i }{ \sum_{i=1}^n w_i }
+                   \right) \, ,
+
+    and, with equal weights, it gives:
+
+    .. math::
+
+        \sqrt[n]{ \prod_{i=1}^n a_i } \, .
+
+    Parameters
+    ----------
+    a : array_like
+        Input array or object that can be converted to an array.
+    axis : int or None, optional
+        Axis along which the geometric mean is computed. Default is 0.
+        If None, compute over the whole array `a`.
+    dtype : dtype, optional
+        Type to which the input arrays are cast before the calculation is
+        performed.
+    weights : array_like, optional
+        The `weights` array must be broadcastable to the same shape as `a`.
+        Default is None, which gives each value a weight of 1.0.
+
+    Returns
+    -------
+    gmean : ndarray
+        See `dtype` parameter above.
+
+    See Also
+    --------
+    numpy.mean : Arithmetic average
+    numpy.average : Weighted average
+    hmean : Harmonic mean
+
+    Notes
+    -----
+    The sample geometric mean is the exponential of the mean of the natural
+    logarithms of the observations.
+    Negative observations will produce NaNs in the output because the *natural*
+    logarithm (as opposed to the *complex* logarithm) is defined only for
+    non-negative reals.
+
+    References
+    ----------
+    .. [1] "Weighted Geometric Mean", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Weighted_geometric_mean.
+    .. [2] Grossman, J., Grossman, M., Katz, R., "Averages: A New Approach",
+           Archimedes Foundation, 1983
+
+    Examples
+    --------
+    >>> from scipy.stats import gmean
+    >>> gmean([1, 4])
+    2.0
+    >>> gmean([1, 2, 3, 4, 5, 6, 7])
+    3.3800151591412964
+    >>> gmean([1, 4, 7], weights=[3, 1, 3])
+    2.80668351922014
+
+    """
+    xp = array_namespace(a, weights)
+    a = xp.asarray(a, dtype=dtype)
+
+    if weights is not None:
+        weights = xp.asarray(weights, dtype=dtype)
+
+    with np.errstate(divide='ignore'):
+        log_a = xp.log(a)
+
+    return xp.exp(_xp_mean(log_a, axis=axis, weights=weights))
+
+
+@_axis_nan_policy_factory(
+        lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
+        result_to_tuple=lambda x: (x,), kwd_samples=['weights'])
+def hmean(a, axis=0, dtype=None, *, weights=None):
+    r"""Calculate the weighted harmonic mean along the specified axis.
+
+    The weighted harmonic mean of the array :math:`a_i` associated to weights
+    :math:`w_i` is:
+
+    .. math::
+
+        \frac{ \sum_{i=1}^n w_i }{ \sum_{i=1}^n \frac{w_i}{a_i} } \, ,
+
+    and, with equal weights, it gives:
+
+    .. math::
+
+        \frac{ n }{ \sum_{i=1}^n \frac{1}{a_i} } \, .
+
+    Parameters
+    ----------
+    a : array_like
+        Input array, masked array or object that can be converted to an array.
+    axis : int or None, optional
+        Axis along which the harmonic mean is computed. Default is 0.
+        If None, compute over the whole array `a`.
+    dtype : dtype, optional
+        Type of the returned array and of the accumulator in which the
+        elements are summed. If `dtype` is not specified, it defaults to the
+        dtype of `a`, unless `a` has an integer `dtype` with a precision less
+        than that of the default platform integer. In that case, the default
+        platform integer is used.
+    weights : array_like, optional
+        The weights array can either be 1-D (in which case its length must be
+        the size of `a` along the given `axis`) or of the same shape as `a`.
+        Default is None, which gives each value a weight of 1.0.
+
+        .. versionadded:: 1.9
+
+    Returns
+    -------
+    hmean : ndarray
+        See `dtype` parameter above.
+
+    See Also
+    --------
+    numpy.mean : Arithmetic average
+    numpy.average : Weighted average
+    gmean : Geometric mean
+
+    Notes
+    -----
+    The sample harmonic mean is the reciprocal of the mean of the reciprocals
+    of the observations.
+
+    The harmonic mean is computed over a single dimension of the input
+    array, axis=0 by default, or all values in the array if axis=None.
+    float64 intermediate and return values are used for integer inputs.
+
+    The harmonic mean is only defined if all observations are non-negative;
+    otherwise, the result is NaN.
+
+    References
+    ----------
+    .. [1] "Weighted Harmonic Mean", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Harmonic_mean#Weighted_harmonic_mean
+    .. [2] Ferger, F., "The nature and use of the harmonic mean", Journal of
+           the American Statistical Association, vol. 26, pp. 36-40, 1931
+
+    Examples
+    --------
+    >>> from scipy.stats import hmean
+    >>> hmean([1, 4])
+    1.6000000000000001
+    >>> hmean([1, 2, 3, 4, 5, 6, 7])
+    2.6997245179063363
+    >>> hmean([1, 4, 7], weights=[3, 1, 3])
+    1.9029126213592233
+
+    """
+    xp = array_namespace(a, weights)
+    a = xp.asarray(a, dtype=dtype)
+
+    if weights is not None:
+        weights = xp.asarray(weights, dtype=dtype)
+
+    negative_mask = a < 0
+    if xp.any(negative_mask):
+        # `where` avoids having to be careful about dtypes and will work with
+        # JAX. This is the exceptional case, so it's OK to be a little slower.
+        # Won't work for array_api_strict for now, but see data-apis/array-api#807
+        a = xp.where(negative_mask, xp.nan, a)
+        message = ("The harmonic mean is only defined if all elements are "
+                   "non-negative; otherwise, the result is NaN.")
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+    with np.errstate(divide='ignore'):
+        return 1.0 / _xp_mean(1.0 / a, axis=axis, weights=weights)
+
+
+@_axis_nan_policy_factory(
+        lambda x: x, n_samples=1, n_outputs=1, too_small=0, paired=True,
+        result_to_tuple=lambda x: (x,), kwd_samples=['weights'])
+def pmean(a, p, *, axis=0, dtype=None, weights=None):
+    r"""Calculate the weighted power mean along the specified axis.
+
+    The weighted power mean of the array :math:`a_i` associated to weights
+    :math:`w_i` is:
+
+    .. math::
+
+        \left( \frac{ \sum_{i=1}^n w_i a_i^p }{ \sum_{i=1}^n w_i }
+              \right)^{ 1 / p } \, ,
+
+    and, with equal weights, it gives:
+
+    .. math::
+
+        \left( \frac{ 1 }{ n } \sum_{i=1}^n a_i^p \right)^{ 1 / p }  \, .
+
+    When ``p=0``, it returns the geometric mean.
+
+    This mean is also called generalized mean or Hölder mean, and must not be
+    confused with the Kolmogorov generalized mean, also called
+    quasi-arithmetic mean or generalized f-mean [3]_.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array, masked array or object that can be converted to an array.
+    p : int or float
+        Exponent.
+    axis : int or None, optional
+        Axis along which the power mean is computed. Default is 0.
+        If None, compute over the whole array `a`.
+    dtype : dtype, optional
+        Type of the returned array and of the accumulator in which the
+        elements are summed. If `dtype` is not specified, it defaults to the
+        dtype of `a`, unless `a` has an integer `dtype` with a precision less
+        than that of the default platform integer. In that case, the default
+        platform integer is used.
+    weights : array_like, optional
+        The weights array can either be 1-D (in which case its length must be
+        the size of `a` along the given `axis`) or of the same shape as `a`.
+        Default is None, which gives each value a weight of 1.0.
+
+    Returns
+    -------
+    pmean : ndarray, see `dtype` parameter above.
+        Output array containing the power mean values.
+
+    See Also
+    --------
+    numpy.average : Weighted average
+    gmean : Geometric mean
+    hmean : Harmonic mean
+
+    Notes
+    -----
+    The power mean is computed over a single dimension of the input
+    array, ``axis=0`` by default, or all values in the array if ``axis=None``.
+    float64 intermediate and return values are used for integer inputs.
+
+    The power mean is only defined if all observations are non-negative;
+    otherwise, the result is NaN.
+
+    .. versionadded:: 1.9
+
+    References
+    ----------
+    .. [1] "Generalized Mean", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Generalized_mean
+    .. [2] Norris, N., "Convexity properties of generalized mean value
+           functions", The Annals of Mathematical Statistics, vol. 8,
+           pp. 118-120, 1937
+    .. [3] Bullen, P.S., Handbook of Means and Their Inequalities, 2003
+
+    Examples
+    --------
+    >>> from scipy.stats import pmean, hmean, gmean
+    >>> pmean([1, 4], 1.3)
+    2.639372938300652
+    >>> pmean([1, 2, 3, 4, 5, 6, 7], 1.3)
+    4.157111214492084
+    >>> pmean([1, 4, 7], -2, weights=[3, 1, 3])
+    1.4969684896631954
+
+    For p=-1, power mean is equal to harmonic mean:
+
+    >>> pmean([1, 4, 7], -1, weights=[3, 1, 3])
+    1.9029126213592233
+    >>> hmean([1, 4, 7], weights=[3, 1, 3])
+    1.9029126213592233
+
+    For p=0, power mean is defined as the geometric mean:
+
+    >>> pmean([1, 4, 7], 0, weights=[3, 1, 3])
+    2.80668351922014
+    >>> gmean([1, 4, 7], weights=[3, 1, 3])
+    2.80668351922014
+
+    """
+    if not isinstance(p, (int, float)):
+        raise ValueError("Power mean only defined for exponent of type int or "
+                         "float.")
+    if p == 0:
+        return gmean(a, axis=axis, dtype=dtype, weights=weights)
+
+    xp = array_namespace(a, weights)
+    a = xp.asarray(a, dtype=dtype)
+
+    if weights is not None:
+        weights = xp.asarray(weights, dtype=dtype)
+
+    negative_mask = a < 0
+    if xp.any(negative_mask):
+        # `where` avoids having to be careful about dtypes and will work with
+        # JAX. This is the exceptional case, so it's OK to be a little slower.
+        # Won't work for array_api_strict for now, but see data-apis/array-api#807
+        a = xp.where(negative_mask, np.nan, a)
+        message = ("The power mean is only defined if all elements are "
+                   "non-negative; otherwise, the result is NaN.")
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        return _xp_mean(a**float(p), axis=axis, weights=weights)**(1/p)
+
+
+ModeResult = namedtuple('ModeResult', ('mode', 'count'))
+
+
+def _mode_result(mode, count):
+    # When a slice is empty, `_axis_nan_policy` automatically produces
+    # NaN for `mode` and `count`. This is a reasonable convention for `mode`,
+    # but `count` should not be NaN; it should be zero.
+    i = np.isnan(count)
+    if i.shape == ():
+        count = np.asarray(0, dtype=count.dtype)[()] if i else count
+    else:
+        count[i] = 0
+    return ModeResult(mode, count)
+
+
+@_axis_nan_policy_factory(_mode_result, override={'vectorization': True,
+                                                  'nan_propagation': False})
+def mode(a, axis=0, nan_policy='propagate', keepdims=False):
+    r"""Return an array of the modal (most common) value in the passed array.
+
+    If there is more than one such value, only one is returned.
+    The bin-count for the modal bins is also returned.
+
+    Parameters
+    ----------
+    a : array_like
+        Numeric, n-dimensional array of which to find mode(s).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': treats nan as it would treat any other value
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+    keepdims : bool, optional
+        If set to ``False``, the `axis` over which the statistic is taken
+        is consumed (eliminated from the output array). If set to ``True``,
+        the `axis` is retained with size one, and the result will broadcast
+        correctly against the input array.
+
+    Returns
+    -------
+    mode : ndarray
+        Array of modal values.
+    count : ndarray
+        Array of counts for each mode.
+
+    Notes
+    -----
+    The mode  is calculated using `numpy.unique`.
+    In NumPy versions 1.21 and after, all NaNs - even those with different
+    binary representations - are treated as equivalent and counted as separate
+    instances of the same value.
+
+    By convention, the mode of an empty array is NaN, and the associated count
+    is zero.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([[3, 0, 3, 7],
+    ...               [3, 2, 6, 2],
+    ...               [1, 7, 2, 8],
+    ...               [3, 0, 6, 1],
+    ...               [3, 2, 5, 5]])
+    >>> from scipy import stats
+    >>> stats.mode(a, keepdims=True)
+    ModeResult(mode=array([[3, 0, 6, 1]]), count=array([[4, 2, 2, 1]]))
+
+    To get mode of whole array, specify ``axis=None``:
+
+    >>> stats.mode(a, axis=None, keepdims=True)
+    ModeResult(mode=[[3]], count=[[5]])
+    >>> stats.mode(a, axis=None, keepdims=False)
+    ModeResult(mode=3, count=5)
+
+    """
+    # `axis`, `nan_policy`, and `keepdims` are handled by `_axis_nan_policy`
+    if not np.issubdtype(a.dtype, np.number):
+        message = ("Argument `a` is not recognized as numeric. "
+                   "Support for input that cannot be coerced to a numeric "
+                   "array was deprecated in SciPy 1.9.0 and removed in SciPy "
+                   "1.11.0. Please consider `np.unique`.")
+        raise TypeError(message)
+
+    if a.size == 0:
+        NaN = _get_nan(a)
+        return ModeResult(*np.array([NaN, 0], dtype=NaN.dtype))
+
+    vals, cnts = np.unique(a, return_counts=True)
+    modes, counts = vals[cnts.argmax()], cnts.max()
+    return ModeResult(modes[()], counts[()])
+
+
+def _put_val_to_limits(a, limits, inclusive, val=np.nan, xp=None):
+    """Replace elements outside limits with a value.
+
+    This is primarily a utility function.
+
+    Parameters
+    ----------
+    a : array
+    limits : (float or None, float or None)
+        A tuple consisting of the (lower limit, upper limit).  Elements in the
+        input array less than the lower limit or greater than the upper limit
+        will be replaced with `val`. None implies no limit.
+    inclusive : (bool, bool)
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to lower or upper are allowed.
+    val : float, default: NaN
+        The value with which extreme elements of the array are replaced.
+
+    """
+    xp = array_namespace(a) if xp is None else xp
+    mask = xp.zeros(a.shape, dtype=xp.bool)
+    if limits is None:
+        return a, mask
+    lower_limit, upper_limit = limits
+    lower_include, upper_include = inclusive
+    if lower_limit is not None:
+        mask |= (a < lower_limit) if lower_include else a <= lower_limit
+    if upper_limit is not None:
+        mask |= (a > upper_limit) if upper_include else a >= upper_limit
+    if xp.all(mask):
+        raise ValueError("No array values within given limits")
+    if xp.any(mask):
+        # hopefully this (and many other instances of this idiom) are temporary when
+        # data-apis/array-api#807 is resolved
+        dtype = xp.asarray(1.).dtype if xp.isdtype(a.dtype, 'integral') else a.dtype
+        a = xp.where(mask, xp.asarray(val, dtype=dtype), a)
+    return a, mask
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, default_axis=None,
+    result_to_tuple=lambda x: (x,)
+)
+def tmean(a, limits=None, inclusive=(True, True), axis=None):
+    """Compute the trimmed mean.
+
+    This function finds the arithmetic mean of given values, ignoring values
+    outside the given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored.  When limits is None (default), then all
+        values are used.  Either of the limit values in the tuple can also be
+        None representing a half-open interval.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to compute test. Default is None.
+
+    Returns
+    -------
+    tmean : ndarray
+        Trimmed mean.
+
+    See Also
+    --------
+    trim_mean : Returns mean after trimming a proportion from both tails.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tmean(x)
+    9.5
+    >>> stats.tmean(x, (3,17))
+    10.0
+
+    """
+    xp = array_namespace(a)
+    a, mask = _put_val_to_limits(a, limits, inclusive, val=0., xp=xp)
+    # explicit dtype specification required due to data-apis/array-api-compat#152
+    sum = xp.sum(a, axis=axis, dtype=a.dtype)
+    n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis, dtype=a.dtype)
+    mean = _lazywhere(n != 0, (sum, n), xp.divide, xp.nan)
+    return mean[()] if mean.ndim == 0 else mean
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """Compute the trimmed variance.
+
+    This function computes the sample variance of an array of values,
+    while ignoring values which are outside of given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom.  Default is 1.
+
+    Returns
+    -------
+    tvar : float
+        Trimmed variance.
+
+    Notes
+    -----
+    `tvar` computes the unbiased sample variance, i.e. it uses a correction
+    factor ``n / (n - 1)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tvar(x)
+    35.0
+    >>> stats.tvar(x, (3,17))
+    20.0
+
+    """
+    xp = array_namespace(a)
+    a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp)
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", SmallSampleWarning)
+        # Currently, this behaves like nan_policy='omit' for alternative array
+        # backends, but nan_policy='propagate' will be handled for other backends
+        # by the axis_nan_policy decorator shortly.
+        return _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
+    """Compute the trimmed minimum.
+
+    This function finds the minimum value of an array `a` along the
+    specified axis, but only considering values greater than a specified
+    lower limit.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    lowerlimit : None or float, optional
+        Values in the input array less than the given limit will be ignored.
+        When lowerlimit is None, then all values are used. The default value
+        is None.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    inclusive : {True, False}, optional
+        This flag determines whether values exactly equal to the lower limit
+        are included.  The default value is True.
+
+    Returns
+    -------
+    tmin : float, int or ndarray
+        Trimmed minimum.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tmin(x)
+    0
+
+    >>> stats.tmin(x, 13)
+    13
+
+    >>> stats.tmin(x, 13, inclusive=False)
+    14
+
+    """
+    xp = array_namespace(a)
+
+    # remember original dtype; _put_val_to_limits might need to change it
+    dtype = a.dtype
+    a, mask = _put_val_to_limits(a, (lowerlimit, None), (inclusive, None),
+                                 val=xp.inf, xp=xp)
+
+    min = xp.min(a, axis=axis)
+    n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis)
+    res = xp.where(n != 0, min, xp.nan)
+
+    if not xp.any(xp.isnan(res)):
+        # needed if input is of integer dtype
+        res = xp.astype(res, dtype, copy=False)
+
+    return res[()] if res.ndim == 0 else res
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
+    """Compute the trimmed maximum.
+
+    This function computes the maximum value of an array along a given axis,
+    while ignoring values larger than a specified upper limit.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    upperlimit : None or float, optional
+        Values in the input array greater than the given limit will be ignored.
+        When upperlimit is None, then all values are used. The default value
+        is None.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    inclusive : {True, False}, optional
+        This flag determines whether values exactly equal to the upper limit
+        are included.  The default value is True.
+
+    Returns
+    -------
+    tmax : float, int or ndarray
+        Trimmed maximum.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tmax(x)
+    19
+
+    >>> stats.tmax(x, 13)
+    13
+
+    >>> stats.tmax(x, 13, inclusive=False)
+    12
+
+    """
+    xp = array_namespace(a)
+
+    # remember original dtype; _put_val_to_limits might need to change it
+    dtype = a.dtype
+    a, mask = _put_val_to_limits(a, (None, upperlimit), (None, inclusive),
+                                 val=-xp.inf, xp=xp)
+
+    max = xp.max(a, axis=axis)
+    n = xp.sum(xp.asarray(~mask, dtype=a.dtype), axis=axis)
+    res = xp.where(n != 0, max, xp.nan)
+
+    if not xp.any(xp.isnan(res)):
+        # needed if input is of integer dtype
+        res = xp.astype(res, dtype, copy=False)
+
+    return res[()] if res.ndim == 0 else res
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """Compute the trimmed sample standard deviation.
+
+    This function finds the sample standard deviation of given values,
+    ignoring values outside the given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom.  Default is 1.
+
+    Returns
+    -------
+    tstd : float
+        Trimmed sample standard deviation.
+
+    Notes
+    -----
+    `tstd` computes the unbiased sample standard deviation, i.e. it uses a
+    correction factor ``n / (n - 1)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tstd(x)
+    5.9160797830996161
+    >>> stats.tstd(x, (3,17))
+    4.4721359549995796
+
+    """
+    return tvar(a, limits, inclusive, axis, ddof, _no_deco=True)**0.5
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
+    """Compute the trimmed standard error of the mean.
+
+    This function finds the standard error of the mean for given
+    values, ignoring values outside the given `limits`.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of values.
+    limits : None or (lower limit, upper limit), optional
+        Values in the input array less than the lower limit or greater than the
+        upper limit will be ignored. When limits is None, then all values are
+        used. Either of the limit values in the tuple can also be None
+        representing a half-open interval.  The default value is None.
+    inclusive : (bool, bool), optional
+        A tuple consisting of the (lower flag, upper flag).  These flags
+        determine whether values exactly equal to the lower or upper limits
+        are included.  The default value is (True, True).
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over the
+        whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom.  Default is 1.
+
+    Returns
+    -------
+    tsem : float
+        Trimmed standard error of the mean.
+
+    Notes
+    -----
+    `tsem` uses unbiased sample standard deviation, i.e. it uses a
+    correction factor ``n / (n - 1)``.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = np.arange(20)
+    >>> stats.tsem(x)
+    1.3228756555322954
+    >>> stats.tsem(x, (3,17))
+    1.1547005383792515
+
+    """
+    xp = array_namespace(a)
+    a, _ = _put_val_to_limits(a, limits, inclusive, xp=xp)
+
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", SmallSampleWarning)
+        # Currently, this behaves like nan_policy='omit' for alternative array
+        # backends, but nan_policy='propagate' will be handled for other backends
+        # by the axis_nan_policy decorator shortly.
+        sd = _xp_var(a, correction=ddof, axis=axis, nan_policy='omit', xp=xp)**0.5
+
+    n_obs = xp.sum(~xp.isnan(a), axis=axis, dtype=sd.dtype)
+    return sd / n_obs**0.5
+
+
+#####################################
+#              MOMENTS              #
+#####################################
+
+
+def _moment_outputs(kwds, default_order=1):
+    order = np.atleast_1d(kwds.get('order', default_order))
+    message = "`order` must be a scalar or a non-empty 1D array."
+    if order.size == 0 or order.ndim > 1:
+        raise ValueError(message)
+    return len(order)
+
+
+def _moment_result_object(*args):
+    if len(args) == 1:
+        return args[0]
+    return np.asarray(args)
+
+
+# When `order` is array-like with size > 1, moment produces an *array*
+# rather than a tuple, but the zeroth dimension is to be treated like
+# separate outputs. It is important to make the distinction between
+# separate outputs when adding the reduced axes back (`keepdims=True`).
+def _moment_tuple(x, n_out):
+    return tuple(x) if n_out > 1 else (x,)
+
+
+# `moment` fits into the `_axis_nan_policy` pattern, but it is a bit unusual
+# because the number of outputs is variable. Specifically,
+# `result_to_tuple=lambda x: (x,)` may be surprising for a function that
+# can produce more than one output, but it is intended here.
+# When `moment is called to produce the output:
+# - `result_to_tuple` packs the returned array into a single-element tuple,
+# - `_moment_result_object` extracts and returns that single element.
+# However, when the input array is empty, `moment` is never called. Instead,
+# - `_check_empty_inputs` is used to produce an empty array with the
+#   appropriate dimensions.
+# - A list comprehension creates the appropriate number of copies of this
+#   array, depending on `n_outputs`.
+# - This list - which may have multiple elements - is passed into
+#   `_moment_result_object`.
+# - If there is a single output, `_moment_result_object` extracts and returns
+#   the single output from the list.
+# - If there are multiple outputs, and therefore multiple elements in the list,
+#   `_moment_result_object` converts the list of arrays to a single array and
+#   returns it.
+# Currently, this leads to a slight inconsistency: when the input array is
+# empty, there is no distinction between the `moment` function being called
+# with parameter `order=1` and `order=[1]`; the latter *should* produce
+# the same as the former but with a singleton zeroth dimension.
+@_rename_parameter('moment', 'order')
+@_axis_nan_policy_factory(  # noqa: E302
+    _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple,
+    n_outputs=_moment_outputs
+)
+def moment(a, order=1, axis=0, nan_policy='propagate', *, center=None):
+    r"""Calculate the nth moment about the mean for a sample.
+
+    A moment is a specific quantitative measure of the shape of a set of
+    points. It is often used to calculate coefficients of skewness and kurtosis
+    due to its close relationship with them.
+
+    Parameters
+    ----------
+    a : array_like
+       Input array.
+    order : int or 1-D array_like of ints, optional
+       Order of central moment that is returned. Default is 1.
+    axis : int or None, optional
+       Axis along which the central moment is computed. Default is 0.
+       If None, compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    center : float or None, optional
+       The point about which moments are taken. This can be the sample mean,
+       the origin, or any other be point. If `None` (default) compute the
+       center as the sample mean.
+
+    Returns
+    -------
+    n-th moment about the `center` : ndarray or float
+       The appropriate moment along the given axis or over all values if axis
+       is None. The denominator for the moment calculation is the number of
+       observations, no degrees of freedom correction is done.
+
+    See Also
+    --------
+    kurtosis, skew, describe
+
+    Notes
+    -----
+    The k-th moment of a data sample is:
+
+    .. math::
+
+        m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - c)^k
+
+    Where `n` is the number of samples, and `c` is the center around which the
+    moment is calculated. This function uses exponentiation by squares [1]_ for
+    efficiency.
+
+    Note that, if `a` is an empty array (``a.size == 0``), array `moment` with
+    one element (`moment.size == 1`) is treated the same as scalar `moment`
+    (``np.isscalar(moment)``). This might produce arrays of unexpected shape.
+
+    References
+    ----------
+    .. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
+
+    Examples
+    --------
+    >>> from scipy.stats import moment
+    >>> moment([1, 2, 3, 4, 5], order=1)
+    0.0
+    >>> moment([1, 2, 3, 4, 5], order=2)
+    2.0
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    if xp.isdtype(a.dtype, 'integral'):
+        a = xp.asarray(a, dtype=xp.float64)
+    else:
+        a = xp.asarray(a)
+
+    order = xp.asarray(order, dtype=a.dtype)
+    if xp_size(order) == 0:
+        # This is tested by `_moment_outputs`, which is run by the `_axis_nan_policy`
+        # decorator. Currently, the `_axis_nan_policy` decorator is skipped when `a`
+        # is a non-NumPy array, so we need to check again. When the decorator is
+        # updated for array API compatibility, we can remove this second check.
+        raise ValueError("`order` must be a scalar or a non-empty 1D array.")
+    if xp.any(order != xp.round(order)):
+        raise ValueError("All elements of `order` must be integral.")
+    order = order[()] if order.ndim == 0 else order
+
+    # for array_like order input, return a value for each.
+    if order.ndim > 0:
+        # Calculated the mean once at most, and only if it will be used
+        calculate_mean = center is None and xp.any(order > 1)
+        mean = xp.mean(a, axis=axis, keepdims=True) if calculate_mean else None
+        mmnt = []
+        for i in range(order.shape[0]):
+            order_i = order[i]
+            if center is None and order_i > 1:
+                mmnt.append(_moment(a, order_i, axis, mean=mean)[np.newaxis, ...])
+            else:
+                mmnt.append(_moment(a, order_i, axis, mean=center)[np.newaxis, ...])
+        return xp.concat(mmnt, axis=0)
+    else:
+        return _moment(a, order, axis, mean=center)
+
+
+def _demean(a, mean, axis, *, xp, precision_warning=True):
+    # subtracts `mean` from `a` and returns the result,
+    # warning if there is catastrophic cancellation. `mean`
+    # must be the mean of `a` along axis with `keepdims=True`.
+    # Used in e.g. `_moment`, `_zscore`, `_xp_var`. See gh-15905.
+    a_zero_mean = a - mean
+
+    if xp_size(a_zero_mean) == 0:
+        return a_zero_mean
+
+    eps = xp.finfo(mean.dtype).eps * 10
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        rel_diff = xp.max(xp.abs(a_zero_mean), axis=axis,
+                          keepdims=True) / xp.abs(mean)
+    with np.errstate(invalid='ignore'):
+        precision_loss = xp.any(rel_diff < eps)
+    n = (xp_size(a) if axis is None
+         # compact way to deal with axis tuples or ints
+         else np.prod(np.asarray(a.shape)[np.asarray(axis)]))
+
+    if precision_loss and n > 1 and precision_warning:
+        message = ("Precision loss occurred in moment calculation due to "
+                   "catastrophic cancellation. This occurs when the data "
+                   "are nearly identical. Results may be unreliable.")
+        warnings.warn(message, RuntimeWarning, stacklevel=5)
+    return a_zero_mean
+
+
+def _moment(a, order, axis, *, mean=None, xp=None):
+    """Vectorized calculation of raw moment about specified center
+
+    When `mean` is None, the mean is computed and used as the center;
+    otherwise, the provided value is used as the center.
+
+    """
+    xp = array_namespace(a) if xp is None else xp
+
+    if xp.isdtype(a.dtype, 'integral'):
+        a = xp.asarray(a, dtype=xp.float64)
+
+    dtype = a.dtype
+
+    # moment of empty array is the same regardless of order
+    if xp_size(a) == 0:
+        return xp.mean(a, axis=axis)
+
+    if order == 0 or (order == 1 and mean is None):
+        # By definition the zeroth moment is always 1, and the first *central*
+        # moment is 0.
+        shape = list(a.shape)
+        del shape[axis]
+
+        temp = (xp.ones(shape, dtype=dtype) if order == 0
+                else xp.zeros(shape, dtype=dtype))
+        return temp[()] if temp.ndim == 0 else temp
+
+    # Exponentiation by squares: form exponent sequence
+    n_list = [order]
+    current_n = order
+    while current_n > 2:
+        if current_n % 2:
+            current_n = (current_n - 1) / 2
+        else:
+            current_n /= 2
+        n_list.append(current_n)
+
+    # Starting point for exponentiation by squares
+    mean = (xp.mean(a, axis=axis, keepdims=True) if mean is None
+            else xp.asarray(mean, dtype=dtype))
+    mean = mean[()] if mean.ndim == 0 else mean
+    a_zero_mean = _demean(a, mean, axis, xp=xp)
+
+    if n_list[-1] == 1:
+        s = xp.asarray(a_zero_mean, copy=True)
+    else:
+        s = a_zero_mean**2
+
+    # Perform multiplications
+    for n in n_list[-2::-1]:
+        s = s**2
+        if n % 2:
+            s *= a_zero_mean
+    return xp.mean(s, axis=axis)
+
+
+def _var(x, axis=0, ddof=0, mean=None, xp=None):
+    # Calculate variance of sample, warning if precision is lost
+    xp = array_namespace(x) if xp is None else xp
+    var = _moment(x, 2, axis, mean=mean, xp=xp)
+    if ddof != 0:
+        n = x.shape[axis] if axis is not None else xp_size(x)
+        var *= np.divide(n, n-ddof)  # to avoid error on division by zero
+    return var
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1
+)
+# nan_policy handled by `_axis_nan_policy`, but needs to be left
+# in signature to preserve use as a positional argument
+def skew(a, axis=0, bias=True, nan_policy='propagate'):
+    r"""Compute the sample skewness of a data set.
+
+    For normally distributed data, the skewness should be about zero. For
+    unimodal continuous distributions, a skewness value greater than zero means
+    that there is more weight in the right tail of the distribution. The
+    function `skewtest` can be used to determine if the skewness value
+    is close enough to zero, statistically speaking.
+
+    Parameters
+    ----------
+    a : ndarray
+        Input array.
+    axis : int or None, optional
+        Axis along which skewness is calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    bias : bool, optional
+        If False, then the calculations are corrected for statistical bias.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    skewness : ndarray
+        The skewness of values along an axis, returning NaN where all values
+        are equal.
+
+    Notes
+    -----
+    The sample skewness is computed as the Fisher-Pearson coefficient
+    of skewness, i.e.
+
+    .. math::
+
+        g_1=\frac{m_3}{m_2^{3/2}}
+
+    where
+
+    .. math::
+
+        m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i
+
+    is the biased sample :math:`i\texttt{th}` central moment, and
+    :math:`\bar{x}` is
+    the sample mean.  If ``bias`` is False, the calculations are
+    corrected for bias and the value computed is the adjusted
+    Fisher-Pearson standardized moment coefficient, i.e.
+
+    .. math::
+
+        G_1=\frac{k_3}{k_2^{3/2}}=
+            \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}.
+
+    References
+    ----------
+    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+       Probability and Statistics Tables and Formulae. Chapman & Hall: New
+       York. 2000.
+       Section 2.2.24.1
+
+    Examples
+    --------
+    >>> from scipy.stats import skew
+    >>> skew([1, 2, 3, 4, 5])
+    0.0
+    >>> skew([2, 8, 0, 4, 1, 9, 9, 0])
+    0.2650554122698573
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+    n = a.shape[axis]
+
+    mean = xp.mean(a, axis=axis, keepdims=True)
+    mean_reduced = xp.squeeze(mean, axis=axis)  # needed later
+    m2 = _moment(a, 2, axis, mean=mean, xp=xp)
+    m3 = _moment(a, 3, axis, mean=mean, xp=xp)
+    with np.errstate(all='ignore'):
+        eps = xp.finfo(m2.dtype).eps
+        zero = m2 <= (eps * mean_reduced)**2
+        vals = xp.where(zero, xp.asarray(xp.nan), m3 / m2**1.5)
+    if not bias:
+        can_correct = ~zero & (n > 2)
+        if xp.any(can_correct):
+            m2 = m2[can_correct]
+            m3 = m3[can_correct]
+            nval = ((n - 1.0) * n)**0.5 / (n - 2.0) * m3 / m2**1.5
+            vals[can_correct] = nval
+
+    return vals[()] if vals.ndim == 0 else vals
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1
+)
+# nan_policy handled by `_axis_nan_policy`, but needs to be left
+# in signature to preserve use as a positional argument
+def kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate'):
+    """Compute the kurtosis (Fisher or Pearson) of a dataset.
+
+    Kurtosis is the fourth central moment divided by the square of the
+    variance. If Fisher's definition is used, then 3.0 is subtracted from
+    the result to give 0.0 for a normal distribution.
+
+    If bias is False then the kurtosis is calculated using k statistics to
+    eliminate bias coming from biased moment estimators
+
+    Use `kurtosistest` to see if result is close enough to normal.
+
+    Parameters
+    ----------
+    a : array
+        Data for which the kurtosis is calculated.
+    axis : int or None, optional
+        Axis along which the kurtosis is calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    fisher : bool, optional
+        If True, Fisher's definition is used (normal ==> 0.0). If False,
+        Pearson's definition is used (normal ==> 3.0).
+    bias : bool, optional
+        If False, then the calculations are corrected for statistical bias.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.
+
+    Returns
+    -------
+    kurtosis : array
+        The kurtosis of values along an axis, returning NaN where all values
+        are equal.
+
+    References
+    ----------
+    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+       Probability and Statistics Tables and Formulae. Chapman & Hall: New
+       York. 2000.
+
+    Examples
+    --------
+    In Fisher's definition, the kurtosis of the normal distribution is zero.
+    In the following example, the kurtosis is close to zero, because it was
+    calculated from the dataset, not from the continuous distribution.
+
+    >>> import numpy as np
+    >>> from scipy.stats import norm, kurtosis
+    >>> data = norm.rvs(size=1000, random_state=3)
+    >>> kurtosis(data)
+    -0.06928694200380558
+
+    The distribution with a higher kurtosis has a heavier tail.
+    The zero valued kurtosis of the normal distribution in Fisher's definition
+    can serve as a reference point.
+
+    >>> import matplotlib.pyplot as plt
+    >>> import scipy.stats as stats
+    >>> from scipy.stats import kurtosis
+
+    >>> x = np.linspace(-5, 5, 100)
+    >>> ax = plt.subplot()
+    >>> distnames = ['laplace', 'norm', 'uniform']
+
+    >>> for distname in distnames:
+    ...     if distname == 'uniform':
+    ...         dist = getattr(stats, distname)(loc=-2, scale=4)
+    ...     else:
+    ...         dist = getattr(stats, distname)
+    ...     data = dist.rvs(size=1000)
+    ...     kur = kurtosis(data, fisher=True)
+    ...     y = dist.pdf(x)
+    ...     ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3)))
+    ...     ax.legend()
+
+    The Laplace distribution has a heavier tail than the normal distribution.
+    The uniform distribution (which has negative kurtosis) has the thinnest
+    tail.
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    n = a.shape[axis]
+    mean = xp.mean(a, axis=axis, keepdims=True)
+    mean_reduced = xp.squeeze(mean, axis=axis)  # needed later
+    m2 = _moment(a, 2, axis, mean=mean, xp=xp)
+    m4 = _moment(a, 4, axis, mean=mean, xp=xp)
+    with np.errstate(all='ignore'):
+        zero = m2 <= (xp.finfo(m2.dtype).eps * mean_reduced)**2
+        NaN = _get_nan(m4, xp=xp)
+        vals = xp.where(zero, NaN, m4 / m2**2.0)
+
+    if not bias:
+        can_correct = ~zero & (n > 3)
+        if xp.any(can_correct):
+            m2 = m2[can_correct]
+            m4 = m4[can_correct]
+            nval = 1.0/(n-2)/(n-3) * ((n**2-1.0)*m4/m2**2.0 - 3*(n-1)**2.0)
+            vals[can_correct] = nval + 3.0
+
+    vals = vals - 3 if fisher else vals
+    return vals[()] if vals.ndim == 0 else vals
+
+
+DescribeResult = namedtuple('DescribeResult',
+                            ('nobs', 'minmax', 'mean', 'variance', 'skewness',
+                             'kurtosis'))
+
+
+def describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'):
+    """Compute several descriptive statistics of the passed array.
+
+    Parameters
+    ----------
+    a : array_like
+        Input data.
+    axis : int or None, optional
+        Axis along which statistics are calculated. Default is 0.
+        If None, compute over the whole array `a`.
+    ddof : int, optional
+        Delta degrees of freedom (only for variance).  Default is 1.
+    bias : bool, optional
+        If False, then the skewness and kurtosis calculations are corrected
+        for statistical bias.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    nobs : int or ndarray of ints
+        Number of observations (length of data along `axis`).
+        When 'omit' is chosen as nan_policy, the length along each axis
+        slice is counted separately.
+    minmax: tuple of ndarrays or floats
+        Minimum and maximum value of `a` along the given axis.
+    mean : ndarray or float
+        Arithmetic mean of `a` along the given axis.
+    variance : ndarray or float
+        Unbiased variance of `a` along the given axis; denominator is number
+        of observations minus one.
+    skewness : ndarray or float
+        Skewness of `a` along the given axis, based on moment calculations
+        with denominator equal to the number of observations, i.e. no degrees
+        of freedom correction.
+    kurtosis : ndarray or float
+        Kurtosis (Fisher) of `a` along the given axis.  The kurtosis is
+        normalized so that it is zero for the normal distribution.  No
+        degrees of freedom are used.
+
+    Raises
+    ------
+    ValueError
+        If size of `a` is 0.
+
+    See Also
+    --------
+    skew, kurtosis
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.arange(10)
+    >>> stats.describe(a)
+    DescribeResult(nobs=10, minmax=(0, 9), mean=4.5,
+                   variance=9.166666666666666, skewness=0.0,
+                   kurtosis=-1.2242424242424244)
+    >>> b = [[1, 2], [3, 4]]
+    >>> stats.describe(b)
+    DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])),
+                   mean=array([2., 3.]), variance=array([2., 2.]),
+                   skewness=array([0., 0.]), kurtosis=array([-2., -2.]))
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    contains_nan, nan_policy = _contains_nan(a, nan_policy)
+
+    if contains_nan and nan_policy == 'omit':
+        # only NumPy gets here; `_contains_nan` raises error for the rest
+        a = ma.masked_invalid(a)
+        return mstats_basic.describe(a, axis, ddof, bias)
+
+    if xp_size(a) == 0:
+        raise ValueError("The input must not be empty.")
+
+    n = a.shape[axis]
+    mm = (xp.min(a, axis=axis), xp.max(a, axis=axis))
+    m = xp.mean(a, axis=axis)
+    v = _var(a, axis=axis, ddof=ddof, xp=xp)
+    sk = skew(a, axis, bias=bias)
+    kurt = kurtosis(a, axis, bias=bias)
+
+    return DescribeResult(n, mm, m, v, sk, kurt)
+
+#####################################
+#         NORMALITY TESTS           #
+#####################################
+
+
+def _get_pvalue(statistic, distribution, alternative, symmetric=True, xp=None):
+    """Get p-value given the statistic, (continuous) distribution, and alternative"""
+    xp = array_namespace(statistic) if xp is None else xp
+
+    if alternative == 'less':
+        pvalue = distribution.cdf(statistic)
+    elif alternative == 'greater':
+        pvalue = distribution.sf(statistic)
+    elif alternative == 'two-sided':
+        pvalue = 2 * (distribution.sf(xp.abs(statistic)) if symmetric
+                      else xp.minimum(distribution.cdf(statistic),
+                                      distribution.sf(statistic)))
+    else:
+        message = "`alternative` must be 'less', 'greater', or 'two-sided'."
+        raise ValueError(message)
+
+    return pvalue
+
+
+SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(SkewtestResult, n_samples=1, too_small=7)
+# nan_policy handled by `_axis_nan_policy`, but needs to be left
+# in signature to preserve use as a positional argument
+def skewtest(a, axis=0, nan_policy='propagate', alternative='two-sided'):
+    r"""Test whether the skew is different from the normal distribution.
+
+    This function tests the null hypothesis that the skewness of
+    the population that the sample was drawn from is the same
+    as that of a corresponding normal distribution.
+
+    Parameters
+    ----------
+    a : array
+        The data to be tested. Must contain at least eight observations.
+    axis : int or None, optional
+       Axis along which statistics are calculated. Default is 0.
+       If None, compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the skewness of the distribution underlying the sample
+          is different from that of the normal distribution (i.e. 0)
+        * 'less': the skewness of the distribution underlying the sample
+          is less than that of the normal distribution
+        * 'greater': the skewness of the distribution underlying the sample
+          is greater than that of the normal distribution
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float
+        The computed z-score for this test.
+    pvalue : float
+        The p-value for the hypothesis test.
+
+    See Also
+    --------
+    :ref:`hypothesis_skewtest` : Extended example
+
+    Notes
+    -----
+    The sample size must be at least 8.
+
+    References
+    ----------
+    .. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr.,
+            "A suggestion for using powerful and informative tests of
+            normality", American Statistician 44, pp. 316-321, 1990.
+
+    Examples
+    --------
+
+    >>> from scipy.stats import skewtest
+    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8])
+    SkewtestResult(statistic=1.0108048609177787, pvalue=0.3121098361421897)
+    >>> skewtest([2, 8, 0, 4, 1, 9, 9, 0])
+    SkewtestResult(statistic=0.44626385374196975, pvalue=0.6554066631275459)
+    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8000])
+    SkewtestResult(statistic=3.571773510360407, pvalue=0.0003545719905823133)
+    >>> skewtest([100, 100, 100, 100, 100, 100, 100, 101])
+    SkewtestResult(statistic=3.5717766638478072, pvalue=0.000354567720281634)
+    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='less')
+    SkewtestResult(statistic=1.0108048609177787, pvalue=0.8439450819289052)
+    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='greater')
+    SkewtestResult(statistic=1.0108048609177787, pvalue=0.15605491807109484)
+
+    For a more detailed example, see :ref:`hypothesis_skewtest`.
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    b2 = skew(a, axis, _no_deco=True)
+    n = a.shape[axis]
+    if n < 8:
+        message = ("`skewtest` requires at least 8 observations; "
+                   f"only {n=} observations were given.")
+        raise ValueError(message)
+
+    y = b2 * math.sqrt(((n + 1) * (n + 3)) / (6.0 * (n - 2)))
+    beta2 = (3.0 * (n**2 + 27*n - 70) * (n+1) * (n+3) /
+             ((n-2.0) * (n+5) * (n+7) * (n+9)))
+    W2 = -1 + math.sqrt(2 * (beta2 - 1))
+    delta = 1 / math.sqrt(0.5 * math.log(W2))
+    alpha = math.sqrt(2.0 / (W2 - 1))
+    y = xp.where(y == 0, xp.asarray(1, dtype=y.dtype), y)
+    Z = delta * xp.log(y / alpha + xp.sqrt((y / alpha)**2 + 1))
+
+    pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp)
+
+    Z = Z[()] if Z.ndim == 0 else Z
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+    return SkewtestResult(Z, pvalue)
+
+
+KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(KurtosistestResult, n_samples=1, too_small=4)
+def kurtosistest(a, axis=0, nan_policy='propagate', alternative='two-sided'):
+    r"""Test whether a dataset has normal kurtosis.
+
+    This function tests the null hypothesis that the kurtosis
+    of the population from which the sample was drawn is that
+    of the normal distribution.
+
+    Parameters
+    ----------
+    a : array
+        Array of the sample data. Must contain at least five observations.
+    axis : int or None, optional
+       Axis along which to compute test. Default is 0. If None,
+       compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the kurtosis of the distribution underlying the sample
+          is different from that of the normal distribution
+        * 'less': the kurtosis of the distribution underlying the sample
+          is less than that of the normal distribution
+        * 'greater': the kurtosis of the distribution underlying the sample
+          is greater than that of the normal distribution
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float
+        The computed z-score for this test.
+    pvalue : float
+        The p-value for the hypothesis test.
+
+    See Also
+    --------
+    :ref:`hypothesis_kurtosistest` : Extended example
+
+    Notes
+    -----
+    Valid only for n>20. This function uses the method described in [1]_.
+
+    References
+    ----------
+    .. [1] F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis
+       statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy.stats import kurtosistest
+    >>> kurtosistest(list(range(20)))
+    KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.08804338332528348)
+    >>> kurtosistest(list(range(20)), alternative='less')
+    KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.04402169166264174)
+    >>> kurtosistest(list(range(20)), alternative='greater')
+    KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.9559783083373583)
+    >>> rng = np.random.default_rng()
+    >>> s = rng.normal(0, 1, 1000)
+    >>> kurtosistest(s)
+    KurtosistestResult(statistic=-1.475047944490622, pvalue=0.14019965402996987)
+
+    For a more detailed example, see :ref:`hypothesis_kurtosistest`.
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    n = a.shape[axis]
+
+    if n < 5:
+        message = ("`kurtosistest` requires at least 5 observations; "
+                   f"only {n=} observations were given.")
+        raise ValueError(message)
+    if n < 20:
+        message = ("`kurtosistest` p-value may be inaccurate with fewer than 20 "
+                   f"observations; only {n=} observations were given.")
+        warnings.warn(message, stacklevel=2)
+    b2 = kurtosis(a, axis, fisher=False, _no_deco=True)
+
+    E = 3.0*(n-1) / (n+1)
+    varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5))  # [1]_ Eq. 1
+    x = (b2-E) / varb2**0.5  # [1]_ Eq. 4
+    # [1]_ Eq. 2:
+    sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * ((6.0*(n+3)*(n+5))
+                                                 / (n*(n-2)*(n-3)))**0.5
+    # [1]_ Eq. 3:
+    A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + (1+4.0/(sqrtbeta1**2))**0.5)
+    term1 = 1 - 2/(9.0*A)
+    denom = 1 + x * (2/(A-4.0))**0.5
+    NaN = _get_nan(x, xp=xp)
+    term2 = xp_sign(denom) * xp.where(denom == 0.0, NaN,
+                                      ((1-2.0/A)/xp.abs(denom))**(1/3))
+    if xp.any(denom == 0):
+        msg = ("Test statistic not defined in some cases due to division by "
+               "zero. Return nan in that case...")
+        warnings.warn(msg, RuntimeWarning, stacklevel=2)
+
+    Z = (term1 - term2) / (2/(9.0*A))**0.5  # [1]_ Eq. 5
+
+    pvalue = _get_pvalue(Z, _SimpleNormal(), alternative, xp=xp)
+
+    Z = Z[()] if Z.ndim == 0 else Z
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+    return KurtosistestResult(Z, pvalue)
+
+
+NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(NormaltestResult, n_samples=1, too_small=7)
+def normaltest(a, axis=0, nan_policy='propagate'):
+    r"""Test whether a sample differs from a normal distribution.
+
+    This function tests the null hypothesis that a sample comes
+    from a normal distribution.  It is based on D'Agostino and
+    Pearson's [1]_, [2]_ test that combines skew and kurtosis to
+    produce an omnibus test of normality.
+
+    Parameters
+    ----------
+    a : array_like
+        The array containing the sample to be tested. Must contain
+        at least eight observations.
+    axis : int or None, optional
+        Axis along which to compute test. Default is 0. If None,
+        compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+            * 'propagate': returns nan
+            * 'raise': throws an error
+            * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    statistic : float or array
+        ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
+        ``k`` is the z-score returned by `kurtosistest`.
+    pvalue : float or array
+        A 2-sided chi squared probability for the hypothesis test.
+
+    See Also
+    --------
+    :ref:`hypothesis_normaltest` : Extended example
+
+    References
+    ----------
+    .. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for
+            moderate and large sample size", Biometrika, 58, 341-348
+    .. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from
+            normality", Biometrika, 60, 613-622
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> pts = 1000
+    >>> a = rng.normal(0, 1, size=pts)
+    >>> b = rng.normal(2, 1, size=pts)
+    >>> x = np.concatenate((a, b))
+    >>> res = stats.normaltest(x)
+    >>> res.statistic
+    53.619...  # random
+    >>> res.pvalue
+    2.273917413209226e-12  # random
+
+    For a more detailed example, see :ref:`hypothesis_normaltest`.
+    """
+    xp = array_namespace(a)
+
+    s, _ = skewtest(a, axis, _no_deco=True)
+    k, _ = kurtosistest(a, axis, _no_deco=True)
+    statistic = s*s + k*k
+
+    chi2 = _SimpleChi2(xp.asarray(2.))
+    pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp)
+
+    statistic = statistic[()] if statistic.ndim == 0 else statistic
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+
+    return NormaltestResult(statistic, pvalue)
+
+
+@_axis_nan_policy_factory(SignificanceResult, default_axis=None)
+def jarque_bera(x, *, axis=None):
+    r"""Perform the Jarque-Bera goodness of fit test on sample data.
+
+    The Jarque-Bera test tests whether the sample data has the skewness and
+    kurtosis matching a normal distribution.
+
+    Note that this test only works for a large enough number of data samples
+    (>2000) as the test statistic asymptotically has a Chi-squared distribution
+    with 2 degrees of freedom.
+
+    Parameters
+    ----------
+    x : array_like
+        Observations of a random variable.
+    axis : int or None, default: 0
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear in
+        a corresponding element of the output.
+        If ``None``, the input will be raveled before computing the statistic.
+
+    Returns
+    -------
+    result : SignificanceResult
+        An object with the following attributes:
+
+        statistic : float
+            The test statistic.
+        pvalue : float
+            The p-value for the hypothesis test.
+
+    See Also
+    --------
+    :ref:`hypothesis_jarque_bera` : Extended example
+
+    References
+    ----------
+    .. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality,
+           homoscedasticity and serial independence of regression residuals",
+           6 Econometric Letters 255-259.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = rng.normal(0, 1, 100000)
+    >>> jarque_bera_test = stats.jarque_bera(x)
+    >>> jarque_bera_test
+    Jarque_beraResult(statistic=3.3415184718131554, pvalue=0.18810419594996775)
+    >>> jarque_bera_test.statistic
+    3.3415184718131554
+    >>> jarque_bera_test.pvalue
+    0.18810419594996775
+
+    For a more detailed example, see :ref:`hypothesis_jarque_bera`.
+    """
+    xp = array_namespace(x)
+    x = xp.asarray(x)
+    if axis is None:
+        x = xp.reshape(x, (-1,))
+        axis = 0
+
+    n = x.shape[axis]
+    if n == 0:
+        raise ValueError('At least one observation is required.')
+
+    mu = xp.mean(x, axis=axis, keepdims=True)
+    diffx = x - mu
+    s = skew(diffx, axis=axis, _no_deco=True)
+    k = kurtosis(diffx, axis=axis, _no_deco=True)
+    statistic = n / 6 * (s**2 + k**2 / 4)
+
+    chi2 = _SimpleChi2(xp.asarray(2.))
+    pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=xp)
+
+    statistic = statistic[()] if statistic.ndim == 0 else statistic
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+
+    return SignificanceResult(statistic, pvalue)
+
+
+#####################################
+#        FREQUENCY FUNCTIONS        #
+#####################################
+
+
+def scoreatpercentile(a, per, limit=(), interpolation_method='fraction',
+                      axis=None):
+    """Calculate the score at a given percentile of the input sequence.
+
+    For example, the score at ``per=50`` is the median. If the desired quantile
+    lies between two data points, we interpolate between them, according to
+    the value of `interpolation`. If the parameter `limit` is provided, it
+    should be a tuple (lower, upper) of two values.
+
+    Parameters
+    ----------
+    a : array_like
+        A 1-D array of values from which to extract score.
+    per : array_like
+        Percentile(s) at which to extract score.  Values should be in range
+        [0,100].
+    limit : tuple, optional
+        Tuple of two scalars, the lower and upper limits within which to
+        compute the percentile. Values of `a` outside
+        this (closed) interval will be ignored.
+    interpolation_method : {'fraction', 'lower', 'higher'}, optional
+        Specifies the interpolation method to use,
+        when the desired quantile lies between two data points `i` and `j`
+        The following options are available (default is 'fraction'):
+
+          * 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the
+            fractional part of the index surrounded by ``i`` and ``j``
+          * 'lower': ``i``
+          * 'higher': ``j``
+
+    axis : int, optional
+        Axis along which the percentiles are computed. Default is None. If
+        None, compute over the whole array `a`.
+
+    Returns
+    -------
+    score : float or ndarray
+        Score at percentile(s).
+
+    See Also
+    --------
+    percentileofscore, numpy.percentile
+
+    Notes
+    -----
+    This function will become obsolete in the future.
+    For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality
+    that `scoreatpercentile` provides.  And it's significantly faster.
+    Therefore it's recommended to use `numpy.percentile` for users that have
+    numpy >= 1.9.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.arange(100)
+    >>> stats.scoreatpercentile(a, 50)
+    49.5
+
+    """
+    # adapted from NumPy's percentile function.  When we require numpy >= 1.8,
+    # the implementation of this function can be replaced by np.percentile.
+    a = np.asarray(a)
+    if a.size == 0:
+        # empty array, return nan(s) with shape matching `per`
+        if np.isscalar(per):
+            return np.nan
+        else:
+            return np.full(np.asarray(per).shape, np.nan, dtype=np.float64)
+
+    if limit:
+        a = a[(limit[0] <= a) & (a <= limit[1])]
+
+    sorted_ = np.sort(a, axis=axis)
+    if axis is None:
+        axis = 0
+
+    return _compute_qth_percentile(sorted_, per, interpolation_method, axis)
+
+
+# handle sequence of per's without calling sort multiple times
+def _compute_qth_percentile(sorted_, per, interpolation_method, axis):
+    if not np.isscalar(per):
+        score = [_compute_qth_percentile(sorted_, i,
+                                         interpolation_method, axis)
+                 for i in per]
+        return np.array(score)
+
+    if not (0 <= per <= 100):
+        raise ValueError("percentile must be in the range [0, 100]")
+
+    indexer = [slice(None)] * sorted_.ndim
+    idx = per / 100. * (sorted_.shape[axis] - 1)
+
+    if int(idx) != idx:
+        # round fractional indices according to interpolation method
+        if interpolation_method == 'lower':
+            idx = int(np.floor(idx))
+        elif interpolation_method == 'higher':
+            idx = int(np.ceil(idx))
+        elif interpolation_method == 'fraction':
+            pass  # keep idx as fraction and interpolate
+        else:
+            raise ValueError("interpolation_method can only be 'fraction', "
+                             "'lower' or 'higher'")
+
+    i = int(idx)
+    if i == idx:
+        indexer[axis] = slice(i, i + 1)
+        weights = array(1)
+        sumval = 1.0
+    else:
+        indexer[axis] = slice(i, i + 2)
+        j = i + 1
+        weights = array([(j - idx), (idx - i)], float)
+        wshape = [1] * sorted_.ndim
+        wshape[axis] = 2
+        weights.shape = wshape
+        sumval = weights.sum()
+
+    # Use np.add.reduce (== np.sum but a little faster) to coerce data type
+    return np.add.reduce(sorted_[tuple(indexer)] * weights, axis=axis) / sumval
+
+
+def percentileofscore(a, score, kind='rank', nan_policy='propagate'):
+    """Compute the percentile rank of a score relative to a list of scores.
+
+    A `percentileofscore` of, for example, 80% means that 80% of the
+    scores in `a` are below the given score. In the case of gaps or
+    ties, the exact definition depends on the optional keyword, `kind`.
+
+    Parameters
+    ----------
+    a : array_like
+        A 1-D array to which `score` is compared.
+    score : array_like
+        Scores to compute percentiles for.
+    kind : {'rank', 'weak', 'strict', 'mean'}, optional
+        Specifies the interpretation of the resulting score.
+        The following options are available (default is 'rank'):
+
+          * 'rank': Average percentage ranking of score.  In case of multiple
+            matches, average the percentage rankings of all matching scores.
+          * 'weak': This kind corresponds to the definition of a cumulative
+            distribution function.  A percentileofscore of 80% means that 80%
+            of values are less than or equal to the provided score.
+          * 'strict': Similar to "weak", except that only values that are
+            strictly less than the given score are counted.
+          * 'mean': The average of the "weak" and "strict" scores, often used
+            in testing.  See https://en.wikipedia.org/wiki/Percentile_rank
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Specifies how to treat `nan` values in `a`.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan (for each value in `score`).
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    pcos : float
+        Percentile-position of score (0-100) relative to `a`.
+
+    See Also
+    --------
+    numpy.percentile
+    scipy.stats.scoreatpercentile, scipy.stats.rankdata
+
+    Examples
+    --------
+    Three-quarters of the given values lie below a given score:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> stats.percentileofscore([1, 2, 3, 4], 3)
+    75.0
+
+    With multiple matches, note how the scores of the two matches, 0.6
+    and 0.8 respectively, are averaged:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3)
+    70.0
+
+    Only 2/5 values are strictly less than 3:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict')
+    40.0
+
+    But 4/5 values are less than or equal to 3:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak')
+    80.0
+
+    The average between the weak and the strict scores is:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean')
+    60.0
+
+    Score arrays (of any dimensionality) are supported:
+
+    >>> stats.percentileofscore([1, 2, 3, 3, 4], [2, 3])
+    array([40., 70.])
+
+    The inputs can be infinite:
+
+    >>> stats.percentileofscore([-np.inf, 0, 1, np.inf], [1, 2, np.inf])
+    array([75., 75., 100.])
+
+    If `a` is empty, then the resulting percentiles are all `nan`:
+
+    >>> stats.percentileofscore([], [1, 2])
+    array([nan, nan])
+    """
+
+    a = np.asarray(a)
+    n = len(a)
+    score = np.asarray(score)
+
+    # Nan treatment
+    cna, npa = _contains_nan(a, nan_policy)
+    cns, nps = _contains_nan(score, nan_policy)
+
+    if (cna or cns) and nan_policy == 'raise':
+        raise ValueError("The input contains nan values")
+
+    if cns:
+        # If a score is nan, then the output should be nan
+        # (also if nan_policy is "omit", because it only applies to `a`)
+        score = ma.masked_where(np.isnan(score), score)
+
+    if cna:
+        if nan_policy == "omit":
+            # Don't count nans
+            a = ma.masked_where(np.isnan(a), a)
+            n = a.count()
+
+        if nan_policy == "propagate":
+            # All outputs should be nans
+            n = 0
+
+    # Cannot compare to empty list ==> nan
+    if n == 0:
+        perct = np.full_like(score, np.nan, dtype=np.float64)
+
+    else:
+        # Prepare broadcasting
+        score = score[..., None]
+
+        def count(x):
+            return np.count_nonzero(x, -1)
+
+        # Main computations/logic
+        if kind == 'rank':
+            left = count(a < score)
+            right = count(a <= score)
+            plus1 = left < right
+            perct = (left + right + plus1) * (50.0 / n)
+        elif kind == 'strict':
+            perct = count(a < score) * (100.0 / n)
+        elif kind == 'weak':
+            perct = count(a <= score) * (100.0 / n)
+        elif kind == 'mean':
+            left = count(a < score)
+            right = count(a <= score)
+            perct = (left + right) * (50.0 / n)
+        else:
+            raise ValueError(
+                "kind can only be 'rank', 'strict', 'weak' or 'mean'")
+
+    # Re-insert nan values
+    perct = ma.filled(perct, np.nan)
+
+    if perct.ndim == 0:
+        return perct[()]
+    return perct
+
+
+HistogramResult = namedtuple('HistogramResult',
+                             ('count', 'lowerlimit', 'binsize', 'extrapoints'))
+
+
+def _histogram(a, numbins=10, defaultlimits=None, weights=None,
+               printextras=False):
+    """Create a histogram.
+
+    Separate the range into several bins and return the number of instances
+    in each bin.
+
+    Parameters
+    ----------
+    a : array_like
+        Array of scores which will be put into bins.
+    numbins : int, optional
+        The number of bins to use for the histogram. Default is 10.
+    defaultlimits : tuple (lower, upper), optional
+        The lower and upper values for the range of the histogram.
+        If no value is given, a range slightly larger than the range of the
+        values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
+        where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
+    weights : array_like, optional
+        The weights for each value in `a`. Default is None, which gives each
+        value a weight of 1.0
+    printextras : bool, optional
+        If True, if there are extra points (i.e. the points that fall outside
+        the bin limits) a warning is raised saying how many of those points
+        there are.  Default is False.
+
+    Returns
+    -------
+    count : ndarray
+        Number of points (or sum of weights) in each bin.
+    lowerlimit : float
+        Lowest value of histogram, the lower limit of the first bin.
+    binsize : float
+        The size of the bins (all bins have the same size).
+    extrapoints : int
+        The number of points outside the range of the histogram.
+
+    See Also
+    --------
+    numpy.histogram
+
+    Notes
+    -----
+    This histogram is based on numpy's histogram but has a larger range by
+    default if default limits is not set.
+
+    """
+    a = np.ravel(a)
+    if defaultlimits is None:
+        if a.size == 0:
+            # handle empty arrays. Undetermined range, so use 0-1.
+            defaultlimits = (0, 1)
+        else:
+            # no range given, so use values in `a`
+            data_min = a.min()
+            data_max = a.max()
+            # Have bins extend past min and max values slightly
+            s = (data_max - data_min) / (2. * (numbins - 1.))
+            defaultlimits = (data_min - s, data_max + s)
+
+    # use numpy's histogram method to compute bins
+    hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits,
+                                   weights=weights)
+    # hist are not always floats, convert to keep with old output
+    hist = np.array(hist, dtype=float)
+    # fixed width for bins is assumed, as numpy's histogram gives
+    # fixed width bins for int values for 'bins'
+    binsize = bin_edges[1] - bin_edges[0]
+    # calculate number of extra points
+    extrapoints = len([v for v in a
+                       if defaultlimits[0] > v or v > defaultlimits[1]])
+    if extrapoints > 0 and printextras:
+        warnings.warn(f"Points outside given histogram range = {extrapoints}",
+                      stacklevel=3,)
+
+    return HistogramResult(hist, defaultlimits[0], binsize, extrapoints)
+
+
+CumfreqResult = namedtuple('CumfreqResult',
+                           ('cumcount', 'lowerlimit', 'binsize',
+                            'extrapoints'))
+
+
+def cumfreq(a, numbins=10, defaultreallimits=None, weights=None):
+    """Return a cumulative frequency histogram, using the histogram function.
+
+    A cumulative histogram is a mapping that counts the cumulative number of
+    observations in all of the bins up to the specified bin.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    numbins : int, optional
+        The number of bins to use for the histogram. Default is 10.
+    defaultreallimits : tuple (lower, upper), optional
+        The lower and upper values for the range of the histogram.
+        If no value is given, a range slightly larger than the range of the
+        values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``,
+        where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
+    weights : array_like, optional
+        The weights for each value in `a`. Default is None, which gives each
+        value a weight of 1.0
+
+    Returns
+    -------
+    cumcount : ndarray
+        Binned values of cumulative frequency.
+    lowerlimit : float
+        Lower real limit
+    binsize : float
+        Width of each bin.
+    extrapoints : int
+        Extra points.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> x = [1, 4, 2, 1, 3, 1]
+    >>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5))
+    >>> res.cumcount
+    array([ 1.,  2.,  3.,  3.])
+    >>> res.extrapoints
+    3
+
+    Create a normal distribution with 1000 random values
+
+    >>> samples = stats.norm.rvs(size=1000, random_state=rng)
+
+    Calculate cumulative frequencies
+
+    >>> res = stats.cumfreq(samples, numbins=25)
+
+    Calculate space of values for x
+
+    >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size,
+    ...                                  res.cumcount.size)
+
+    Plot histogram and cumulative histogram
+
+    >>> fig = plt.figure(figsize=(10, 4))
+    >>> ax1 = fig.add_subplot(1, 2, 1)
+    >>> ax2 = fig.add_subplot(1, 2, 2)
+    >>> ax1.hist(samples, bins=25)
+    >>> ax1.set_title('Histogram')
+    >>> ax2.bar(x, res.cumcount, width=res.binsize)
+    >>> ax2.set_title('Cumulative histogram')
+    >>> ax2.set_xlim([x.min(), x.max()])
+
+    >>> plt.show()
+
+    """
+    h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
+    cumhist = np.cumsum(h * 1, axis=0)
+    return CumfreqResult(cumhist, l, b, e)
+
+
+RelfreqResult = namedtuple('RelfreqResult',
+                           ('frequency', 'lowerlimit', 'binsize',
+                            'extrapoints'))
+
+
+def relfreq(a, numbins=10, defaultreallimits=None, weights=None):
+    """Return a relative frequency histogram, using the histogram function.
+
+    A relative frequency  histogram is a mapping of the number of
+    observations in each of the bins relative to the total of observations.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    numbins : int, optional
+        The number of bins to use for the histogram. Default is 10.
+    defaultreallimits : tuple (lower, upper), optional
+        The lower and upper values for the range of the histogram.
+        If no value is given, a range slightly larger than the range of the
+        values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
+        where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
+    weights : array_like, optional
+        The weights for each value in `a`. Default is None, which gives each
+        value a weight of 1.0
+
+    Returns
+    -------
+    frequency : ndarray
+        Binned values of relative frequency.
+    lowerlimit : float
+        Lower real limit.
+    binsize : float
+        Width of each bin.
+    extrapoints : int
+        Extra points.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> a = np.array([2, 4, 1, 2, 3, 2])
+    >>> res = stats.relfreq(a, numbins=4)
+    >>> res.frequency
+    array([ 0.16666667, 0.5       , 0.16666667,  0.16666667])
+    >>> np.sum(res.frequency)  # relative frequencies should add up to 1
+    1.0
+
+    Create a normal distribution with 1000 random values
+
+    >>> samples = stats.norm.rvs(size=1000, random_state=rng)
+
+    Calculate relative frequencies
+
+    >>> res = stats.relfreq(samples, numbins=25)
+
+    Calculate space of values for x
+
+    >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size,
+    ...                                  res.frequency.size)
+
+    Plot relative frequency histogram
+
+    >>> fig = plt.figure(figsize=(5, 4))
+    >>> ax = fig.add_subplot(1, 1, 1)
+    >>> ax.bar(x, res.frequency, width=res.binsize)
+    >>> ax.set_title('Relative frequency histogram')
+    >>> ax.set_xlim([x.min(), x.max()])
+
+    >>> plt.show()
+
+    """
+    a = np.asanyarray(a)
+    h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
+    h = h / a.shape[0]
+
+    return RelfreqResult(h, l, b, e)
+
+
+#####################################
+#        VARIABILITY FUNCTIONS      #
+#####################################
+
+def obrientransform(*samples):
+    """Compute the O'Brien transform on input data (any number of arrays).
+
+    Used to test for homogeneity of variance prior to running one-way stats.
+    Each array in ``*samples`` is one level of a factor.
+    If `f_oneway` is run on the transformed data and found significant,
+    the variances are unequal.  From Maxwell and Delaney [1]_, p.112.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        Any number of arrays.
+
+    Returns
+    -------
+    obrientransform : ndarray
+        Transformed data for use in an ANOVA.  The first dimension
+        of the result corresponds to the sequence of transformed
+        arrays.  If the arrays given are all 1-D of the same length,
+        the return value is a 2-D array; otherwise it is a 1-D array
+        of type object, with each element being an ndarray.
+
+    Raises
+    ------
+    ValueError
+        If the mean of the transformed data is not equal to the original
+        variance, indicating a lack of convergence in the O'Brien transform.
+
+    References
+    ----------
+    .. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and
+           Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990.
+
+    Examples
+    --------
+    We'll test the following data sets for differences in their variance.
+
+    >>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10]
+    >>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15]
+
+    Apply the O'Brien transform to the data.
+
+    >>> from scipy.stats import obrientransform
+    >>> tx, ty = obrientransform(x, y)
+
+    Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the
+    transformed data.
+
+    >>> from scipy.stats import f_oneway
+    >>> F, p = f_oneway(tx, ty)
+    >>> p
+    0.1314139477040335
+
+    If we require that ``p < 0.05`` for significance, we cannot conclude
+    that the variances are different.
+
+    """
+    TINY = np.sqrt(np.finfo(float).eps)
+
+    # `arrays` will hold the transformed arguments.
+    arrays = []
+    sLast = None
+
+    for sample in samples:
+        a = np.asarray(sample)
+        n = len(a)
+        mu = np.mean(a)
+        sq = (a - mu)**2
+        sumsq = sq.sum()
+
+        # The O'Brien transform.
+        t = ((n - 1.5) * n * sq - 0.5 * sumsq) / ((n - 1) * (n - 2))
+
+        # Check that the mean of the transformed data is equal to the
+        # original variance.
+        var = sumsq / (n - 1)
+        if abs(var - np.mean(t)) > TINY:
+            raise ValueError('Lack of convergence in obrientransform.')
+
+        arrays.append(t)
+        sLast = a.shape
+
+    if sLast:
+        for arr in arrays[:-1]:
+            if sLast != arr.shape:
+                return np.array(arrays, dtype=object)
+    return np.array(arrays)
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1, too_small=1
+)
+def sem(a, axis=0, ddof=1, nan_policy='propagate'):
+    """Compute standard error of the mean.
+
+    Calculate the standard error of the mean (or standard error of
+    measurement) of the values in the input array.
+
+    Parameters
+    ----------
+    a : array_like
+        An array containing the values for which the standard error is
+        returned. Must contain at least two observations.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    ddof : int, optional
+        Delta degrees-of-freedom. How many degrees of freedom to adjust
+        for bias in limited samples relative to the population estimate
+        of variance. Defaults to 1.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    s : ndarray or float
+        The standard error of the mean in the sample(s), along the input axis.
+
+    Notes
+    -----
+    The default value for `ddof` is different to the default (0) used by other
+    ddof containing routines, such as np.std and np.nanstd.
+
+    Examples
+    --------
+    Find standard error along the first axis:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.arange(20).reshape(5,4)
+    >>> stats.sem(a)
+    array([ 2.8284,  2.8284,  2.8284,  2.8284])
+
+    Find standard error across the whole array, using n degrees of freedom:
+
+    >>> stats.sem(a, axis=None, ddof=0)
+    1.2893796958227628
+
+    """
+    xp = array_namespace(a)
+    if axis is None:
+        a = xp.reshape(a, (-1,))
+        axis = 0
+    a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp)
+    n = a.shape[axis]
+    s = xp.std(a, axis=axis, correction=ddof) / n**0.5
+    return s
+
+
+def _isconst(x):
+    """
+    Check if all values in x are the same.  nans are ignored.
+
+    x must be a 1d array.
+
+    The return value is a 1d array with length 1, so it can be used
+    in np.apply_along_axis.
+    """
+    y = x[~np.isnan(x)]
+    if y.size == 0:
+        return np.array([True])
+    else:
+        return (y[0] == y).all(keepdims=True)
+
+
+def zscore(a, axis=0, ddof=0, nan_policy='propagate'):
+    """
+    Compute the z score.
+
+    Compute the z score of each value in the sample, relative to the
+    sample mean and standard deviation.
+
+    Parameters
+    ----------
+    a : array_like
+        An array like object containing the sample data.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    ddof : int, optional
+        Degrees of freedom correction in the calculation of the
+        standard deviation. Default is 0.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.  Note that when the value is 'omit',
+        nans in the input also propagate to the output, but they do not affect
+        the z-scores computed for the non-nan values.
+
+    Returns
+    -------
+    zscore : array_like
+        The z-scores, standardized by mean and standard deviation of
+        input array `a`.
+
+    See Also
+    --------
+    numpy.mean : Arithmetic average
+    numpy.std : Arithmetic standard deviation
+    scipy.stats.gzscore : Geometric standard score
+
+    Notes
+    -----
+    This function preserves ndarray subclasses, and works also with
+    matrices and masked arrays (it uses `asanyarray` instead of
+    `asarray` for parameters).
+
+    References
+    ----------
+    .. [1] "Standard score", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Standard_score.
+    .. [2] Huck, S. W., Cross, T. L., Clark, S. B, "Overcoming misconceptions
+           about Z-scores", Teaching Statistics, vol. 8, pp. 38-40, 1986
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> a = np.array([ 0.7972,  0.0767,  0.4383,  0.7866,  0.8091,
+    ...                0.1954,  0.6307,  0.6599,  0.1065,  0.0508])
+    >>> from scipy import stats
+    >>> stats.zscore(a)
+    array([ 1.1273, -1.247 , -0.0552,  1.0923,  1.1664, -0.8559,  0.5786,
+            0.6748, -1.1488, -1.3324])
+
+    Computing along a specified axis, using n-1 degrees of freedom
+    (``ddof=1``) to calculate the standard deviation:
+
+    >>> b = np.array([[ 0.3148,  0.0478,  0.6243,  0.4608],
+    ...               [ 0.7149,  0.0775,  0.6072,  0.9656],
+    ...               [ 0.6341,  0.1403,  0.9759,  0.4064],
+    ...               [ 0.5918,  0.6948,  0.904 ,  0.3721],
+    ...               [ 0.0921,  0.2481,  0.1188,  0.1366]])
+    >>> stats.zscore(b, axis=1, ddof=1)
+    array([[-0.19264823, -1.28415119,  1.07259584,  0.40420358],
+           [ 0.33048416, -1.37380874,  0.04251374,  1.00081084],
+           [ 0.26796377, -1.12598418,  1.23283094, -0.37481053],
+           [-0.22095197,  0.24468594,  1.19042819, -1.21416216],
+           [-0.82780366,  1.4457416 , -0.43867764, -0.1792603 ]])
+
+    An example with ``nan_policy='omit'``:
+
+    >>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15],
+    ...               [14.95, 16.06, 121.25, 94.35, 29.81]])
+    >>> stats.zscore(x, axis=1, nan_policy='omit')
+    array([[-1.13490897, -0.37830299,         nan, -0.08718406,  1.60039602],
+           [-0.91611681, -0.89090508,  1.4983032 ,  0.88731639, -0.5785977 ]])
+    """
+    return zmap(a, a, axis=axis, ddof=ddof, nan_policy=nan_policy)
+
+
+def gzscore(a, *, axis=0, ddof=0, nan_policy='propagate'):
+    """
+    Compute the geometric standard score.
+
+    Compute the geometric z score of each strictly positive value in the
+    sample, relative to the geometric mean and standard deviation.
+    Mathematically the geometric z score can be evaluated as::
+
+        gzscore = log(a/gmu) / log(gsigma)
+
+    where ``gmu`` (resp. ``gsigma``) is the geometric mean (resp. standard
+    deviation).
+
+    Parameters
+    ----------
+    a : array_like
+        Sample data.
+    axis : int or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    ddof : int, optional
+        Degrees of freedom correction in the calculation of the
+        standard deviation. Default is 0.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan. 'propagate' returns nan,
+        'raise' throws an error, 'omit' performs the calculations ignoring nan
+        values. Default is 'propagate'.  Note that when the value is 'omit',
+        nans in the input also propagate to the output, but they do not affect
+        the geometric z scores computed for the non-nan values.
+
+    Returns
+    -------
+    gzscore : array_like
+        The geometric z scores, standardized by geometric mean and geometric
+        standard deviation of input array `a`.
+
+    See Also
+    --------
+    gmean : Geometric mean
+    gstd : Geometric standard deviation
+    zscore : Standard score
+
+    Notes
+    -----
+    This function preserves ndarray subclasses, and works also with
+    matrices and masked arrays (it uses ``asanyarray`` instead of
+    ``asarray`` for parameters).
+
+    .. versionadded:: 1.8
+
+    References
+    ----------
+    .. [1] "Geometric standard score", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Geometric_standard_deviation#Geometric_standard_score.
+
+    Examples
+    --------
+    Draw samples from a log-normal distribution:
+
+    >>> import numpy as np
+    >>> from scipy.stats import zscore, gzscore
+    >>> import matplotlib.pyplot as plt
+
+    >>> rng = np.random.default_rng()
+    >>> mu, sigma = 3., 1.  # mean and standard deviation
+    >>> x = rng.lognormal(mu, sigma, size=500)
+
+    Display the histogram of the samples:
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(x, 50)
+    >>> plt.show()
+
+    Display the histogram of the samples standardized by the classical zscore.
+    Distribution is rescaled but its shape is unchanged.
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(zscore(x), 50)
+    >>> plt.show()
+
+    Demonstrate that the distribution of geometric zscores is rescaled and
+    quasinormal:
+
+    >>> fig, ax = plt.subplots()
+    >>> ax.hist(gzscore(x), 50)
+    >>> plt.show()
+
+    """
+    xp = array_namespace(a)
+    a = _convert_common_float(a, xp=xp)
+    log = ma.log if isinstance(a, ma.MaskedArray) else xp.log
+    return zscore(log(a), axis=axis, ddof=ddof, nan_policy=nan_policy)
+
+
+def zmap(scores, compare, axis=0, ddof=0, nan_policy='propagate'):
+    """
+    Calculate the relative z-scores.
+
+    Return an array of z-scores, i.e., scores that are standardized to
+    zero mean and unit variance, where mean and variance are calculated
+    from the comparison array.
+
+    Parameters
+    ----------
+    scores : array_like
+        The input for which z-scores are calculated.
+    compare : array_like
+        The input from which the mean and standard deviation of the
+        normalization are taken; assumed to have the same dimension as
+        `scores`.
+    axis : int or None, optional
+        Axis over which mean and variance of `compare` are calculated.
+        Default is 0. If None, compute over the whole array `scores`.
+    ddof : int, optional
+        Degrees of freedom correction in the calculation of the
+        standard deviation. Default is 0.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle the occurrence of nans in `compare`.
+        'propagate' returns nan, 'raise' raises an exception, 'omit'
+        performs the calculations ignoring nan values. Default is
+        'propagate'. Note that when the value is 'omit', nans in `scores`
+        also propagate to the output, but they do not affect the z-scores
+        computed for the non-nan values.
+
+    Returns
+    -------
+    zscore : array_like
+        Z-scores, in the same shape as `scores`.
+
+    Notes
+    -----
+    This function preserves ndarray subclasses, and works also with
+    matrices and masked arrays (it uses `asanyarray` instead of
+    `asarray` for parameters).
+
+    Examples
+    --------
+    >>> from scipy.stats import zmap
+    >>> a = [0.5, 2.0, 2.5, 3]
+    >>> b = [0, 1, 2, 3, 4]
+    >>> zmap(a, b)
+    array([-1.06066017,  0.        ,  0.35355339,  0.70710678])
+
+    """
+    # The docstring explicitly states that it preserves subclasses.
+    # Let's table deprecating that and just get the array API version
+    # working.
+
+    like_zscore = (scores is compare)
+    xp = array_namespace(scores, compare)
+    scores, compare = _convert_common_float(scores, compare, xp=xp)
+
+    with warnings.catch_warnings():
+        if like_zscore:  # zscore should not emit SmallSampleWarning
+            warnings.simplefilter('ignore', SmallSampleWarning)
+
+        mn = _xp_mean(compare, axis=axis, keepdims=True, nan_policy=nan_policy)
+        std = _xp_var(compare, axis=axis, correction=ddof,
+                      keepdims=True, nan_policy=nan_policy)**0.5
+
+    with np.errstate(invalid='ignore', divide='ignore'):
+        z = _demean(scores, mn, axis, xp=xp, precision_warning=False) / std
+
+    # If we know that scores and compare are identical, we can infer that
+    # some slices should have NaNs.
+    if like_zscore:
+        eps = xp.finfo(z.dtype).eps
+        zero = std <= xp.abs(eps * mn)
+        zero = xp.broadcast_to(zero, z.shape)
+        z[zero] = xp.nan
+
+    return z
+
+
+def gstd(a, axis=0, ddof=1):
+    r"""
+    Calculate the geometric standard deviation of an array.
+
+    The geometric standard deviation describes the spread of a set of numbers
+    where the geometric mean is preferred. It is a multiplicative factor, and
+    so a dimensionless quantity.
+
+    It is defined as the exponential of the standard deviation of the
+    natural logarithms of the observations.
+
+    Parameters
+    ----------
+    a : array_like
+        An array containing finite, strictly positive, real numbers.
+
+        .. deprecated:: 1.14.0
+            Support for masked array input was deprecated in
+            SciPy 1.14.0 and will be removed in version 1.16.0.
+
+    axis : int, tuple or None, optional
+        Axis along which to operate. Default is 0. If None, compute over
+        the whole array `a`.
+    ddof : int, optional
+        Degree of freedom correction in the calculation of the
+        geometric standard deviation. Default is 1.
+
+    Returns
+    -------
+    gstd : ndarray or float
+        An array of the geometric standard deviation. If `axis` is None or `a`
+        is a 1d array a float is returned.
+
+    See Also
+    --------
+    gmean : Geometric mean
+    numpy.std : Standard deviation
+    gzscore : Geometric standard score
+
+    Notes
+    -----
+    Mathematically, the sample geometric standard deviation :math:`s_G` can be
+    defined in terms of the natural logarithms of the observations
+    :math:`y_i = \log(x_i)`:
+
+    .. math::
+
+        s_G = \exp(s), \quad s = \sqrt{\frac{1}{n - d} \sum_{i=1}^n (y_i - \bar y)^2}
+
+    where :math:`n` is the number of observations, :math:`d` is the adjustment `ddof`
+    to the degrees of freedom, and :math:`\bar y` denotes the mean of the natural
+    logarithms of the observations. Note that the default ``ddof=1`` is different from
+    the default value used by similar functions, such as `numpy.std` and `numpy.var`.
+
+    When an observation is infinite, the geometric standard deviation is
+    NaN (undefined). Non-positive observations will also produce NaNs in the
+    output because the *natural* logarithm (as opposed to the *complex*
+    logarithm) is defined and finite only for positive reals.
+    The geometric standard deviation is sometimes confused with the exponential
+    of the standard deviation, ``exp(std(a))``. Instead, the geometric standard
+    deviation is ``exp(std(log(a)))``.
+
+    References
+    ----------
+    .. [1] "Geometric standard deviation", *Wikipedia*,
+           https://en.wikipedia.org/wiki/Geometric_standard_deviation.
+    .. [2] Kirkwood, T. B., "Geometric means and measures of dispersion",
+           Biometrics, vol. 35, pp. 908-909, 1979
+
+    Examples
+    --------
+    Find the geometric standard deviation of a log-normally distributed sample.
+    Note that the standard deviation of the distribution is one; on a
+    log scale this evaluates to approximately ``exp(1)``.
+
+    >>> import numpy as np
+    >>> from scipy.stats import gstd
+    >>> rng = np.random.default_rng()
+    >>> sample = rng.lognormal(mean=0, sigma=1, size=1000)
+    >>> gstd(sample)
+    2.810010162475324
+
+    Compute the geometric standard deviation of a multidimensional array and
+    of a given axis.
+
+    >>> a = np.arange(1, 25).reshape(2, 3, 4)
+    >>> gstd(a, axis=None)
+    2.2944076136018947
+    >>> gstd(a, axis=2)
+    array([[1.82424757, 1.22436866, 1.13183117],
+           [1.09348306, 1.07244798, 1.05914985]])
+    >>> gstd(a, axis=(1,2))
+    array([2.12939215, 1.22120169])
+
+    """
+    a = np.asanyarray(a)
+    if isinstance(a, ma.MaskedArray):
+        message = ("`gstd` support for masked array input was deprecated in "
+                   "SciPy 1.14.0 and will be removed in version 1.16.0.")
+        warnings.warn(message, DeprecationWarning, stacklevel=2)
+        log = ma.log
+    else:
+        log = np.log
+
+    with np.errstate(invalid='ignore', divide='ignore'):
+        res = np.exp(np.std(log(a), axis=axis, ddof=ddof))
+
+    if (a <= 0).any():
+        message = ("The geometric standard deviation is only defined if all elements "
+                   "are greater than or equal to zero; otherwise, the result is NaN.")
+        warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+    return res
+
+# Private dictionary initialized only once at module level
+# See https://en.wikipedia.org/wiki/Robust_measures_of_scale
+_scale_conversions = {'normal': special.erfinv(0.5) * 2.0 * math.sqrt(2.0)}
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, result_to_tuple=lambda x: (x,), n_outputs=1,
+    default_axis=None, override={'nan_propagation': False}
+)
+def iqr(x, axis=None, rng=(25, 75), scale=1.0, nan_policy='propagate',
+        interpolation='linear', keepdims=False):
+    r"""
+    Compute the interquartile range of the data along the specified axis.
+
+    The interquartile range (IQR) is the difference between the 75th and
+    25th percentile of the data. It is a measure of the dispersion
+    similar to standard deviation or variance, but is much more robust
+    against outliers [2]_.
+
+    The ``rng`` parameter allows this function to compute other
+    percentile ranges than the actual IQR. For example, setting
+    ``rng=(0, 100)`` is equivalent to `numpy.ptp`.
+
+    The IQR of an empty array is `np.nan`.
+
+    .. versionadded:: 0.18.0
+
+    Parameters
+    ----------
+    x : array_like
+        Input array or object that can be converted to an array.
+    axis : int or sequence of int, optional
+        Axis along which the range is computed. The default is to
+        compute the IQR for the entire array.
+    rng : Two-element sequence containing floats in range of [0,100] optional
+        Percentiles over which to compute the range. Each must be
+        between 0 and 100, inclusive. The default is the true IQR:
+        ``(25, 75)``. The order of the elements is not important.
+    scale : scalar or str or array_like of reals, optional
+        The numerical value of scale will be divided out of the final
+        result. The following string value is also recognized:
+
+          * 'normal' : Scale by
+            :math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`.
+
+        The default is 1.0.
+        Array-like `scale` of real dtype is also allowed, as long
+        as it broadcasts correctly to the output such that
+        ``out / scale`` is a valid operation. The output dimensions
+        depend on the input array, `x`, the `axis` argument, and the
+        `keepdims` flag.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+    interpolation : str, optional
+
+        Specifies the interpolation method to use when the percentile
+        boundaries lie between two data points ``i`` and ``j``.
+        The following options are available (default is 'linear'):
+
+          * 'linear': ``i + (j - i)*fraction``, where ``fraction`` is the
+            fractional part of the index surrounded by ``i`` and ``j``.
+          * 'lower': ``i``.
+          * 'higher': ``j``.
+          * 'nearest': ``i`` or ``j`` whichever is nearest.
+          * 'midpoint': ``(i + j)/2``.
+
+        For NumPy >= 1.22.0, the additional options provided by the ``method``
+        keyword of `numpy.percentile` are also valid.
+
+    keepdims : bool, optional
+        If this is set to True, the reduced axes are left in the
+        result as dimensions with size one. With this option, the result
+        will broadcast correctly against the original array `x`.
+
+    Returns
+    -------
+    iqr : scalar or ndarray
+        If ``axis=None``, a scalar is returned. If the input contains
+        integers or floats of smaller precision than ``np.float64``, then the
+        output data-type is ``np.float64``. Otherwise, the output data-type is
+        the same as that of the input.
+
+    See Also
+    --------
+    numpy.std, numpy.var
+
+    References
+    ----------
+    .. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range
+    .. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale
+    .. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import iqr
+    >>> x = np.array([[10, 7, 4], [3, 2, 1]])
+    >>> x
+    array([[10,  7,  4],
+           [ 3,  2,  1]])
+    >>> iqr(x)
+    4.0
+    >>> iqr(x, axis=0)
+    array([ 3.5,  2.5,  1.5])
+    >>> iqr(x, axis=1)
+    array([ 3.,  1.])
+    >>> iqr(x, axis=1, keepdims=True)
+    array([[ 3.],
+           [ 1.]])
+
+    """
+    x = asarray(x)
+
+    # This check prevents percentile from raising an error later. Also, it is
+    # consistent with `np.var` and `np.std`.
+    if not x.size:
+        return _get_nan(x)
+
+    # An error may be raised here, so fail-fast, before doing lengthy
+    # computations, even though `scale` is not used until later
+    if isinstance(scale, str):
+        scale_key = scale.lower()
+        if scale_key not in _scale_conversions:
+            raise ValueError(f"{scale} not a valid scale for `iqr`")
+        scale = _scale_conversions[scale_key]
+
+    # Select the percentile function to use based on nans and policy
+    contains_nan, nan_policy = _contains_nan(x, nan_policy)
+
+    if contains_nan and nan_policy == 'omit':
+        percentile_func = np.nanpercentile
+    else:
+        percentile_func = np.percentile
+
+    if len(rng) != 2:
+        raise TypeError("quantile range must be two element sequence")
+
+    if np.isnan(rng).any():
+        raise ValueError("range must not contain NaNs")
+
+    rng = sorted(rng)
+    pct = percentile_func(x, rng, axis=axis, method=interpolation,
+                          keepdims=keepdims)
+    out = np.subtract(pct[1], pct[0])
+
+    if scale != 1.0:
+        out /= scale
+
+    return out
+
+
+def _mad_1d(x, center, nan_policy):
+    # Median absolute deviation for 1-d array x.
+    # This is a helper function for `median_abs_deviation`; it assumes its
+    # arguments have been validated already.  In particular,  x must be a
+    # 1-d numpy array, center must be callable, and if nan_policy is not
+    # 'propagate', it is assumed to be 'omit', because 'raise' is handled
+    # in `median_abs_deviation`.
+    # No warning is generated if x is empty or all nan.
+    isnan = np.isnan(x)
+    if isnan.any():
+        if nan_policy == 'propagate':
+            return np.nan
+        x = x[~isnan]
+    if x.size == 0:
+        # MAD of an empty array is nan.
+        return np.nan
+    # Edge cases have been handled, so do the basic MAD calculation.
+    med = center(x)
+    mad = np.median(np.abs(x - med))
+    return mad
+
+
+def median_abs_deviation(x, axis=0, center=np.median, scale=1.0,
+                         nan_policy='propagate'):
+    r"""
+    Compute the median absolute deviation of the data along the given axis.
+
+    The median absolute deviation (MAD, [1]_) computes the median over the
+    absolute deviations from the median. It is a measure of dispersion
+    similar to the standard deviation but more robust to outliers [2]_.
+
+    The MAD of an empty array is ``np.nan``.
+
+    .. versionadded:: 1.5.0
+
+    Parameters
+    ----------
+    x : array_like
+        Input array or object that can be converted to an array.
+    axis : int or None, optional
+        Axis along which the range is computed. Default is 0. If None, compute
+        the MAD over the entire array.
+    center : callable, optional
+        A function that will return the central value. The default is to use
+        np.median. Any user defined function used will need to have the
+        function signature ``func(arr, axis)``.
+    scale : scalar or str, optional
+        The numerical value of scale will be divided out of the final
+        result. The default is 1.0. The string "normal" is also accepted,
+        and results in `scale` being the inverse of the standard normal
+        quantile function at 0.75, which is approximately 0.67449.
+        Array-like scale is also allowed, as long as it broadcasts correctly
+        to the output such that ``out / scale`` is a valid operation. The
+        output dimensions depend on the input array, `x`, and the `axis`
+        argument.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    mad : scalar or ndarray
+        If ``axis=None``, a scalar is returned. If the input contains
+        integers or floats of smaller precision than ``np.float64``, then the
+        output data-type is ``np.float64``. Otherwise, the output data-type is
+        the same as that of the input.
+
+    See Also
+    --------
+    numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
+    scipy.stats.tstd, scipy.stats.tvar
+
+    Notes
+    -----
+    The `center` argument only affects the calculation of the central value
+    around which the MAD is calculated. That is, passing in ``center=np.mean``
+    will calculate the MAD around the mean - it will not calculate the *mean*
+    absolute deviation.
+
+    The input array may contain `inf`, but if `center` returns `inf`, the
+    corresponding MAD for that data will be `nan`.
+
+    References
+    ----------
+    .. [1] "Median absolute deviation",
+           https://en.wikipedia.org/wiki/Median_absolute_deviation
+    .. [2] "Robust measures of scale",
+           https://en.wikipedia.org/wiki/Robust_measures_of_scale
+
+    Examples
+    --------
+    When comparing the behavior of `median_abs_deviation` with ``np.std``,
+    the latter is affected when we change a single value of an array to have an
+    outlier value while the MAD hardly changes:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
+    >>> x.std()
+    0.9973906394005013
+    >>> stats.median_abs_deviation(x)
+    0.82832610097857
+    >>> x[0] = 345.6
+    >>> x.std()
+    34.42304872314415
+    >>> stats.median_abs_deviation(x)
+    0.8323442311590675
+
+    Axis handling example:
+
+    >>> x = np.array([[10, 7, 4], [3, 2, 1]])
+    >>> x
+    array([[10,  7,  4],
+           [ 3,  2,  1]])
+    >>> stats.median_abs_deviation(x)
+    array([3.5, 2.5, 1.5])
+    >>> stats.median_abs_deviation(x, axis=None)
+    2.0
+
+    Scale normal example:
+
+    >>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456)
+    >>> stats.median_abs_deviation(x)
+    1.3487398527041636
+    >>> stats.median_abs_deviation(x, scale='normal')
+    1.9996446978061115
+
+    """
+    if not callable(center):
+        raise TypeError("The argument 'center' must be callable. The given "
+                        f"value {repr(center)} is not callable.")
+
+    # An error may be raised here, so fail-fast, before doing lengthy
+    # computations, even though `scale` is not used until later
+    if isinstance(scale, str):
+        if scale.lower() == 'normal':
+            scale = 0.6744897501960817  # special.ndtri(0.75)
+        else:
+            raise ValueError(f"{scale} is not a valid scale value.")
+
+    x = asarray(x)
+
+    # Consistent with `np.var` and `np.std`.
+    if not x.size:
+        if axis is None:
+            return np.nan
+        nan_shape = tuple(item for i, item in enumerate(x.shape) if i != axis)
+        if nan_shape == ():
+            # Return nan, not array(nan)
+            return np.nan
+        return np.full(nan_shape, np.nan)
+
+    contains_nan, nan_policy = _contains_nan(x, nan_policy)
+
+    if contains_nan:
+        if axis is None:
+            mad = _mad_1d(x.ravel(), center, nan_policy)
+        else:
+            mad = np.apply_along_axis(_mad_1d, axis, x, center, nan_policy)
+    else:
+        if axis is None:
+            med = center(x, axis=None)
+            mad = np.median(np.abs(x - med))
+        else:
+            # Wrap the call to center() in expand_dims() so it acts like
+            # keepdims=True was used.
+            med = np.expand_dims(center(x, axis=axis), axis)
+            mad = np.median(np.abs(x - med), axis=axis)
+
+    return mad / scale
+
+
+#####################################
+#         TRIMMING FUNCTIONS        #
+#####################################
+
+
+SigmaclipResult = namedtuple('SigmaclipResult', ('clipped', 'lower', 'upper'))
+
+
+def sigmaclip(a, low=4., high=4.):
+    """Perform iterative sigma-clipping of array elements.
+
+    Starting from the full sample, all elements outside the critical range are
+    removed, i.e. all elements of the input array `c` that satisfy either of
+    the following conditions::
+
+        c < mean(c) - std(c)*low
+        c > mean(c) + std(c)*high
+
+    The iteration continues with the updated sample until no
+    elements are outside the (updated) range.
+
+    Parameters
+    ----------
+    a : array_like
+        Data array, will be raveled if not 1-D.
+    low : float, optional
+        Lower bound factor of sigma clipping. Default is 4.
+    high : float, optional
+        Upper bound factor of sigma clipping. Default is 4.
+
+    Returns
+    -------
+    clipped : ndarray
+        Input array with clipped elements removed.
+    lower : float
+        Lower threshold value use for clipping.
+    upper : float
+        Upper threshold value use for clipping.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import sigmaclip
+    >>> a = np.concatenate((np.linspace(9.5, 10.5, 31),
+    ...                     np.linspace(0, 20, 5)))
+    >>> fact = 1.5
+    >>> c, low, upp = sigmaclip(a, fact, fact)
+    >>> c
+    array([  9.96666667,  10.        ,  10.03333333,  10.        ])
+    >>> c.var(), c.std()
+    (0.00055555555555555165, 0.023570226039551501)
+    >>> low, c.mean() - fact*c.std(), c.min()
+    (9.9646446609406727, 9.9646446609406727, 9.9666666666666668)
+    >>> upp, c.mean() + fact*c.std(), c.max()
+    (10.035355339059327, 10.035355339059327, 10.033333333333333)
+
+    >>> a = np.concatenate((np.linspace(9.5, 10.5, 11),
+    ...                     np.linspace(-100, -50, 3)))
+    >>> c, low, upp = sigmaclip(a, 1.8, 1.8)
+    >>> (c == np.linspace(9.5, 10.5, 11)).all()
+    True
+
+    """
+    c = np.asarray(a).ravel()
+    delta = 1
+    while delta:
+        c_std = c.std()
+        c_mean = c.mean()
+        size = c.size
+        critlower = c_mean - c_std * low
+        critupper = c_mean + c_std * high
+        c = c[(c >= critlower) & (c <= critupper)]
+        delta = size - c.size
+
+    return SigmaclipResult(c, critlower, critupper)
+
+
+def trimboth(a, proportiontocut, axis=0):
+    """Slice off a proportion of items from both ends of an array.
+
+    Slice off the passed proportion of items from both ends of the passed
+    array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
+    rightmost 10% of scores). The trimmed values are the lowest and
+    highest ones.
+    Slice off less if proportion results in a non-integer slice index (i.e.
+    conservatively slices off `proportiontocut`).
+
+    Parameters
+    ----------
+    a : array_like
+        Data to trim.
+    proportiontocut : float
+        Proportion (in range 0-1) of total data set to trim of each end.
+    axis : int or None, optional
+        Axis along which to trim data. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    out : ndarray
+        Trimmed version of array `a`. The order of the trimmed content
+        is undefined.
+
+    See Also
+    --------
+    trim_mean
+
+    Examples
+    --------
+    Create an array of 10 values and trim 10% of those values from each end:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+    >>> stats.trimboth(a, 0.1)
+    array([1, 3, 2, 4, 5, 6, 7, 8])
+
+    Note that the elements of the input array are trimmed by value, but the
+    output array is not necessarily sorted.
+
+    The proportion to trim is rounded down to the nearest integer. For
+    instance, trimming 25% of the values from each end of an array of 10
+    values will return an array of 6 values:
+
+    >>> b = np.arange(10)
+    >>> stats.trimboth(b, 1/4).shape
+    (6,)
+
+    Multidimensional arrays can be trimmed along any axis or across the entire
+    array:
+
+    >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
+    >>> d = np.array([a, b, c])
+    >>> stats.trimboth(d, 0.4, axis=0).shape
+    (1, 10)
+    >>> stats.trimboth(d, 0.4, axis=1).shape
+    (3, 2)
+    >>> stats.trimboth(d, 0.4, axis=None).shape
+    (6,)
+
+    """
+    a = np.asarray(a)
+
+    if a.size == 0:
+        return a
+
+    if axis is None:
+        a = a.ravel()
+        axis = 0
+
+    nobs = a.shape[axis]
+    lowercut = int(proportiontocut * nobs)
+    uppercut = nobs - lowercut
+    if (lowercut >= uppercut):
+        raise ValueError("Proportion too big.")
+
+    atmp = np.partition(a, (lowercut, uppercut - 1), axis)
+
+    sl = [slice(None)] * atmp.ndim
+    sl[axis] = slice(lowercut, uppercut)
+    return atmp[tuple(sl)]
+
+
+def trim1(a, proportiontocut, tail='right', axis=0):
+    """Slice off a proportion from ONE end of the passed array distribution.
+
+    If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost'
+    10% of scores. The lowest or highest values are trimmed (depending on
+    the tail).
+    Slice off less if proportion results in a non-integer slice index
+    (i.e. conservatively slices off `proportiontocut` ).
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    proportiontocut : float
+        Fraction to cut off of 'left' or 'right' of distribution.
+    tail : {'left', 'right'}, optional
+        Defaults to 'right'.
+    axis : int or None, optional
+        Axis along which to trim data. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    trim1 : ndarray
+        Trimmed version of array `a`. The order of the trimmed content is
+        undefined.
+
+    Examples
+    --------
+    Create an array of 10 values and trim 20% of its lowest values:
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+    >>> stats.trim1(a, 0.2, 'left')
+    array([2, 4, 3, 5, 6, 7, 8, 9])
+
+    Note that the elements of the input array are trimmed by value, but the
+    output array is not necessarily sorted.
+
+    The proportion to trim is rounded down to the nearest integer. For
+    instance, trimming 25% of the values from an array of 10 values will
+    return an array of 8 values:
+
+    >>> b = np.arange(10)
+    >>> stats.trim1(b, 1/4).shape
+    (8,)
+
+    Multidimensional arrays can be trimmed along any axis or across the entire
+    array:
+
+    >>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
+    >>> d = np.array([a, b, c])
+    >>> stats.trim1(d, 0.8, axis=0).shape
+    (1, 10)
+    >>> stats.trim1(d, 0.8, axis=1).shape
+    (3, 2)
+    >>> stats.trim1(d, 0.8, axis=None).shape
+    (6,)
+
+    """
+    a = np.asarray(a)
+    if axis is None:
+        a = a.ravel()
+        axis = 0
+
+    nobs = a.shape[axis]
+
+    # avoid possible corner case
+    if proportiontocut >= 1:
+        return []
+
+    if tail.lower() == 'right':
+        lowercut = 0
+        uppercut = nobs - int(proportiontocut * nobs)
+
+    elif tail.lower() == 'left':
+        lowercut = int(proportiontocut * nobs)
+        uppercut = nobs
+
+    atmp = np.partition(a, (lowercut, uppercut - 1), axis)
+
+    sl = [slice(None)] * atmp.ndim
+    sl[axis] = slice(lowercut, uppercut)
+    return atmp[tuple(sl)]
+
+
+def trim_mean(a, proportiontocut, axis=0):
+    """Return mean of array after trimming a specified fraction of extreme values
+
+    Removes the specified proportion of elements from *each* end of the
+    sorted array, then computes the mean of the remaining elements.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    proportiontocut : float
+        Fraction of the most positive and most negative elements to remove.
+        When the specified proportion does not result in an integer number of
+        elements, the number of elements to trim is rounded down.
+    axis : int or None, default: 0
+        Axis along which the trimmed means are computed.
+        If None, compute over the raveled array.
+
+    Returns
+    -------
+    trim_mean : ndarray
+        Mean of trimmed array.
+
+    See Also
+    --------
+    trimboth : Remove a proportion of elements from each end of an array.
+    tmean : Compute the mean after trimming values outside specified limits.
+
+    Notes
+    -----
+    For 1-D array `a`, `trim_mean` is approximately equivalent to the following
+    calculation::
+
+        import numpy as np
+        a = np.sort(a)
+        m = int(proportiontocut * len(a))
+        np.mean(a[m: len(a) - m])
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = [1, 2, 3, 5]
+    >>> stats.trim_mean(x, 0.25)
+    2.5
+
+    When the specified proportion does not result in an integer number of
+    elements, the number of elements to trim is rounded down.
+
+    >>> stats.trim_mean(x, 0.24999) == np.mean(x)
+    True
+
+    Use `axis` to specify the axis along which the calculation is performed.
+
+    >>> x2 = [[1, 2, 3, 5],
+    ...       [10, 20, 30, 50]]
+    >>> stats.trim_mean(x2, 0.25)
+    array([ 5.5, 11. , 16.5, 27.5])
+    >>> stats.trim_mean(x2, 0.25, axis=1)
+    array([ 2.5, 25. ])
+
+    """
+    a = np.asarray(a)
+
+    if a.size == 0:
+        return np.nan
+
+    if axis is None:
+        a = a.ravel()
+        axis = 0
+
+    nobs = a.shape[axis]
+    lowercut = int(proportiontocut * nobs)
+    uppercut = nobs - lowercut
+    if (lowercut > uppercut):
+        raise ValueError("Proportion too big.")
+
+    atmp = np.partition(a, (lowercut, uppercut - 1), axis)
+
+    sl = [slice(None)] * atmp.ndim
+    sl[axis] = slice(lowercut, uppercut)
+    return np.mean(atmp[tuple(sl)], axis=axis)
+
+
+F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))
+
+
+def _create_f_oneway_nan_result(shape, axis, samples):
+    """
+    This is a helper function for f_oneway for creating the return values
+    in certain degenerate conditions.  It creates return values that are
+    all nan with the appropriate shape for the given `shape` and `axis`.
+    """
+    axis = normalize_axis_index(axis, len(shape))
+    shp = shape[:axis] + shape[axis+1:]
+    f = np.full(shp, fill_value=_get_nan(*samples))
+    prob = f.copy()
+    return F_onewayResult(f[()], prob[()])
+
+
+def _first(arr, axis):
+    """Return arr[..., 0:1, ...] where 0:1 is in the `axis` position."""
+    return np.take_along_axis(arr, np.array(0, ndmin=arr.ndim), axis)
+
+
+def _f_oneway_is_too_small(samples, kwargs=None, axis=-1):
+    message = f"At least two samples are required; got {len(samples)}."
+    if len(samples) < 2:
+        raise TypeError(message)
+
+    # Check this after forming alldata, so shape errors are detected
+    # and reported before checking for 0 length inputs.
+    if any(sample.shape[axis] == 0 for sample in samples):
+        return True
+
+    # Must have at least one group with length greater than 1.
+    if all(sample.shape[axis] == 1 for sample in samples):
+        msg = ('all input arrays have length 1.  f_oneway requires that at '
+               'least one input has length greater than 1.')
+        warnings.warn(SmallSampleWarning(msg), stacklevel=2)
+        return True
+
+    return False
+
+
+@_axis_nan_policy_factory(
+    F_onewayResult, n_samples=None, too_small=_f_oneway_is_too_small)
+def f_oneway(*samples, axis=0):
+    """Perform one-way ANOVA.
+
+    The one-way ANOVA tests the null hypothesis that two or more groups have
+    the same population mean.  The test is applied to samples from two or
+    more groups, possibly with differing sizes.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The sample measurements for each group.  There must be at least
+        two arguments.  If the arrays are multidimensional, then all the
+        dimensions of the array must be the same except for `axis`.
+    axis : int, optional
+        Axis of the input arrays along which the test is applied.
+        Default is 0.
+
+    Returns
+    -------
+    statistic : float
+        The computed F statistic of the test.
+    pvalue : float
+        The associated p-value from the F distribution.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Emitted if all values within each of the input arrays are identical.
+        In this case the F statistic is either infinite or isn't defined,
+        so ``np.inf`` or ``np.nan`` is returned.
+
+    RuntimeWarning
+        Emitted if the length of any input array is 0, or if all the input
+        arrays have length 1.  ``np.nan`` is returned for the F statistic
+        and the p-value in these cases.
+
+    Notes
+    -----
+    The ANOVA test has important assumptions that must be satisfied in order
+    for the associated p-value to be valid.
+
+    1. The samples are independent.
+    2. Each sample is from a normally distributed population.
+    3. The population standard deviations of the groups are all equal.  This
+       property is known as homoscedasticity.
+
+    If these assumptions are not true for a given set of data, it may still
+    be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`) or
+    the Alexander-Govern test (`scipy.stats.alexandergovern`) although with
+    some loss of power.
+
+    The length of each group must be at least one, and there must be at
+    least one group with length greater than one.  If these conditions
+    are not satisfied, a warning is generated and (``np.nan``, ``np.nan``)
+    is returned.
+
+    If all values in each group are identical, and there exist at least two
+    groups with different values, the function generates a warning and
+    returns (``np.inf``, 0).
+
+    If all values in all groups are the same, function generates a warning
+    and returns (``np.nan``, ``np.nan``).
+
+    The algorithm is from Heiman [2]_, pp.394-7.
+
+    References
+    ----------
+    .. [1] R. Lowry, "Concepts and Applications of Inferential Statistics",
+           Chapter 14, 2014, http://vassarstats.net/textbook/
+
+    .. [2] G.W. Heiman, "Understanding research methods and statistics: An
+           integrated introduction for psychology", Houghton, Mifflin and
+           Company, 2001.
+
+    .. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA.
+           http://www.biostathandbook.com/onewayanova.html
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import f_oneway
+
+    Here are some data [3]_ on a shell measurement (the length of the anterior
+    adductor muscle scar, standardized by dividing by length) in the mussel
+    Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon;
+    Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a
+    much larger data set used in McDonald et al. (1991).
+
+    >>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735,
+    ...              0.0659, 0.0923, 0.0836]
+    >>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835,
+    ...            0.0725]
+    >>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105]
+    >>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764,
+    ...            0.0689]
+    >>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045]
+    >>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne)
+    F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544)
+
+    `f_oneway` accepts multidimensional input arrays.  When the inputs
+    are multidimensional and `axis` is not given, the test is performed
+    along the first axis of the input arrays.  For the following data, the
+    test is performed three times, once for each column.
+
+    >>> a = np.array([[9.87, 9.03, 6.81],
+    ...               [7.18, 8.35, 7.00],
+    ...               [8.39, 7.58, 7.68],
+    ...               [7.45, 6.33, 9.35],
+    ...               [6.41, 7.10, 9.33],
+    ...               [8.00, 8.24, 8.44]])
+    >>> b = np.array([[6.35, 7.30, 7.16],
+    ...               [6.65, 6.68, 7.63],
+    ...               [5.72, 7.73, 6.72],
+    ...               [7.01, 9.19, 7.41],
+    ...               [7.75, 7.87, 8.30],
+    ...               [6.90, 7.97, 6.97]])
+    >>> c = np.array([[3.31, 8.77, 1.01],
+    ...               [8.25, 3.24, 3.62],
+    ...               [6.32, 8.81, 5.19],
+    ...               [7.48, 8.83, 8.91],
+    ...               [8.59, 6.01, 6.07],
+    ...               [3.07, 9.72, 7.48]])
+    >>> F = f_oneway(a, b, c)
+    >>> F.statistic
+    array([1.75676344, 0.03701228, 3.76439349])
+    >>> F.pvalue
+    array([0.20630784, 0.96375203, 0.04733157])
+
+    """
+    if len(samples) < 2:
+        raise TypeError('at least two inputs are required;'
+                        f' got {len(samples)}.')
+
+    # ANOVA on N groups, each in its own array
+    num_groups = len(samples)
+
+    # We haven't explicitly validated axis, but if it is bad, this call of
+    # np.concatenate will raise np.exceptions.AxisError. The call will raise
+    # ValueError if the dimensions of all the arrays, except the axis
+    # dimension, are not the same.
+    alldata = np.concatenate(samples, axis=axis)
+    bign = alldata.shape[axis]
+
+    # Check if the inputs are too small
+    if _f_oneway_is_too_small(samples):
+        return _create_f_oneway_nan_result(alldata.shape, axis, samples)
+
+    # Check if all values within each group are identical, and if the common
+    # value in at least one group is different from that in another group.
+    # Based on https://github.com/scipy/scipy/issues/11669
+
+    # If axis=0, say, and the groups have shape (n0, ...), (n1, ...), ...,
+    # then is_const is a boolean array with shape (num_groups, ...).
+    # It is True if the values within the groups along the axis slice are
+    # identical. In the typical case where each input array is 1-d, is_const is
+    # a 1-d array with length num_groups.
+    is_const = np.concatenate(
+        [(_first(sample, axis) == sample).all(axis=axis,
+                                              keepdims=True)
+         for sample in samples],
+        axis=axis
+    )
+
+    # all_const is a boolean array with shape (...) (see previous comment).
+    # It is True if the values within each group along the axis slice are
+    # the same (e.g. [[3, 3, 3], [5, 5, 5, 5], [4, 4, 4]]).
+    all_const = is_const.all(axis=axis)
+    if all_const.any():
+        msg = ("Each of the input arrays is constant; "
+               "the F statistic is not defined or infinite")
+        warnings.warn(stats.ConstantInputWarning(msg), stacklevel=2)
+
+    # all_same_const is True if all the values in the groups along the axis=0
+    # slice are the same (e.g. [[3, 3, 3], [3, 3, 3, 3], [3, 3, 3]]).
+    all_same_const = (_first(alldata, axis) == alldata).all(axis=axis)
+
+    # Determine the mean of the data, and subtract that from all inputs to a
+    # variance (via sum_of_sq / sq_of_sum) calculation.  Variance is invariant
+    # to a shift in location, and centering all data around zero vastly
+    # improves numerical stability.
+    offset = alldata.mean(axis=axis, keepdims=True)
+    alldata = alldata - offset
+
+    normalized_ss = _square_of_sums(alldata, axis=axis) / bign
+
+    sstot = _sum_of_squares(alldata, axis=axis) - normalized_ss
+
+    ssbn = 0
+    for sample in samples:
+        smo_ss = _square_of_sums(sample - offset, axis=axis)
+        ssbn = ssbn + smo_ss / sample.shape[axis]
+
+    # Naming: variables ending in bn/b are for "between treatments", wn/w are
+    # for "within treatments"
+    ssbn = ssbn - normalized_ss
+    sswn = sstot - ssbn
+    dfbn = num_groups - 1
+    dfwn = bign - num_groups
+    msb = ssbn / dfbn
+    msw = sswn / dfwn
+    with np.errstate(divide='ignore', invalid='ignore'):
+        f = msb / msw
+
+    prob = special.fdtrc(dfbn, dfwn, f)   # equivalent to stats.f.sf
+
+    # Fix any f values that should be inf or nan because the corresponding
+    # inputs were constant.
+    if np.isscalar(f):
+        if all_same_const:
+            f = np.nan
+            prob = np.nan
+        elif all_const:
+            f = np.inf
+            prob = 0.0
+    else:
+        f[all_const] = np.inf
+        prob[all_const] = 0.0
+        f[all_same_const] = np.nan
+        prob[all_same_const] = np.nan
+
+    return F_onewayResult(f, prob)
+
+
+@dataclass
+class AlexanderGovernResult:
+    statistic: float
+    pvalue: float
+
+
+@_axis_nan_policy_factory(
+    AlexanderGovernResult, n_samples=None,
+    result_to_tuple=lambda x: (x.statistic, x.pvalue),
+    too_small=1
+)
+def alexandergovern(*samples, nan_policy='propagate', axis=0):
+    """Performs the Alexander Govern test.
+
+    The Alexander-Govern approximation tests the equality of k independent
+    means in the face of heterogeneity of variance. The test is applied to
+    samples from two or more groups, possibly with differing sizes.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+        The sample measurements for each group.  There must be at least
+        two samples, and each sample must contain at least two observations.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    res : AlexanderGovernResult
+        An object with attributes:
+
+        statistic : float
+            The computed A statistic of the test.
+        pvalue : float
+            The associated p-value from the chi-squared distribution.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Raised if an input is a constant array.  The statistic is not defined
+        in this case, so ``np.nan`` is returned.
+
+    See Also
+    --------
+    f_oneway : one-way ANOVA
+
+    Notes
+    -----
+    The use of this test relies on several assumptions.
+
+    1. The samples are independent.
+    2. Each sample is from a normally distributed population.
+    3. Unlike `f_oneway`, this test does not assume on homoscedasticity,
+       instead relaxing the assumption of equal variances.
+
+    Input samples must be finite, one dimensional, and with size greater than
+    one.
+
+    References
+    ----------
+    .. [1] Alexander, Ralph A., and Diane M. Govern. "A New and Simpler
+           Approximation for ANOVA under Variance Heterogeneity." Journal
+           of Educational Statistics, vol. 19, no. 2, 1994, pp. 91-101.
+           JSTOR, www.jstor.org/stable/1165140. Accessed 12 Sept. 2020.
+
+    Examples
+    --------
+    >>> from scipy.stats import alexandergovern
+
+    Here are some data on annual percentage rate of interest charged on
+    new car loans at nine of the largest banks in four American cities
+    taken from the National Institute of Standards and Technology's
+    ANOVA dataset.
+
+    We use `alexandergovern` to test the null hypothesis that all cities
+    have the same mean APR against the alternative that the cities do not
+    all have the same mean APR. We decide that a significance level of 5%
+    is required to reject the null hypothesis in favor of the alternative.
+
+    >>> atlanta = [13.75, 13.75, 13.5, 13.5, 13.0, 13.0, 13.0, 12.75, 12.5]
+    >>> chicago = [14.25, 13.0, 12.75, 12.5, 12.5, 12.4, 12.3, 11.9, 11.9]
+    >>> houston = [14.0, 14.0, 13.51, 13.5, 13.5, 13.25, 13.0, 12.5, 12.5]
+    >>> memphis = [15.0, 14.0, 13.75, 13.59, 13.25, 12.97, 12.5, 12.25,
+    ...           11.89]
+    >>> alexandergovern(atlanta, chicago, houston, memphis)
+    AlexanderGovernResult(statistic=4.65087071883494,
+                          pvalue=0.19922132490385214)
+
+    The p-value is 0.1992, indicating a nearly 20% chance of observing
+    such an extreme value of the test statistic under the null hypothesis.
+    This exceeds 5%, so we do not reject the null hypothesis in favor of
+    the alternative.
+
+    """
+    samples = _alexandergovern_input_validation(samples, nan_policy, axis)
+
+    # The following formula numbers reference the equation described on
+    # page 92 by Alexander, Govern. Formulas 5, 6, and 7 describe other
+    # tests that serve as the basis for equation (8) but are not needed
+    # to perform the test.
+
+    # precalculate mean and length of each sample
+    lengths = [sample.shape[-1] for sample in samples]
+    means = np.asarray([_xp_mean(sample, axis=-1) for sample in samples])
+
+    # (1) determine standard error of the mean for each sample
+    se2 = [(_xp_var(sample, correction=1, axis=-1) / length)
+           for sample, length in zip(samples, lengths)]
+    standard_errors_squared = np.asarray(se2)
+    standard_errors = standard_errors_squared**0.5
+
+    # Special case: statistic is NaN when variance is zero
+    eps = np.finfo(standard_errors.dtype).eps
+    zero = standard_errors <= np.abs(eps * means)
+    NaN = np.asarray(np.nan, dtype=standard_errors.dtype)
+    standard_errors = np.where(zero, NaN, standard_errors)
+
+    # (2) define a weight for each sample
+    inv_sq_se = 1 / standard_errors_squared
+    weights = inv_sq_se / np.sum(inv_sq_se, axis=0, keepdims=True)
+
+    # (3) determine variance-weighted estimate of the common mean
+    var_w = np.sum(weights * means, axis=0, keepdims=True)
+
+    # (4) determine one-sample t statistic for each group
+    t_stats = _demean(means, var_w, axis=0, xp=np) / standard_errors
+
+    # calculate parameters to be used in transformation
+    v = np.asarray(lengths) - 1
+    # align along 0th axis, which corresponds with separate samples
+    v = np.reshape(v, (-1,) + (1,)*(t_stats.ndim-1))
+    a = v - .5
+    b = 48 * a**2
+    c = (a * np.log(1 + (t_stats ** 2)/v))**.5
+
+    # (8) perform a normalizing transformation on t statistic
+    z = (c + ((c**3 + 3*c)/b) -
+         ((4*c**7 + 33*c**5 + 240*c**3 + 855*c) /
+          (b**2*10 + 8*b*c**4 + 1000*b)))
+
+    # (9) calculate statistic
+    A = np.sum(z**2, axis=0)
+
+    # "[the p value is determined from] central chi-square random deviates
+    # with k - 1 degrees of freedom". Alexander, Govern (94)
+    df = len(samples) - 1
+    chi2 = _SimpleChi2(df)
+    p = _get_pvalue(A, chi2, alternative='greater', symmetric=False, xp=np)
+    return AlexanderGovernResult(A, p)
+
+
+def _alexandergovern_input_validation(samples, nan_policy, axis):
+    if len(samples) < 2:
+        raise TypeError(f"2 or more inputs required, got {len(samples)}")
+
+    for sample in samples:
+        if sample.shape[axis] <= 1:
+            raise ValueError("Input sample size must be greater than one.")
+
+    samples = [np.moveaxis(sample, axis, -1) for sample in samples]
+
+    return samples
+
+
+def _pearsonr_fisher_ci(r, n, confidence_level, alternative):
+    """
+    Compute the confidence interval for Pearson's R.
+
+    Fisher's transformation is used to compute the confidence interval
+    (https://en.wikipedia.org/wiki/Fisher_transformation).
+    """
+    xp = array_namespace(r)
+
+    with np.errstate(divide='ignore'):
+        zr = xp.atanh(r)
+
+    ones = xp.ones_like(r)
+    n = xp.asarray(n, dtype=r.dtype)
+    confidence_level = xp.asarray(confidence_level, dtype=r.dtype)
+    if n > 3:
+        se = xp.sqrt(1 / (n - 3))
+        if alternative == "two-sided":
+            h = special.ndtri(0.5 + confidence_level/2)
+            zlo = zr - h*se
+            zhi = zr + h*se
+            rlo = xp.tanh(zlo)
+            rhi = xp.tanh(zhi)
+        elif alternative == "less":
+            h = special.ndtri(confidence_level)
+            zhi = zr + h*se
+            rhi = xp.tanh(zhi)
+            rlo = -ones
+        else:
+            # alternative == "greater":
+            h = special.ndtri(confidence_level)
+            zlo = zr - h*se
+            rlo = xp.tanh(zlo)
+            rhi = ones
+    else:
+        rlo, rhi = -ones, ones
+
+    rlo = rlo[()] if rlo.ndim == 0 else rlo
+    rhi = rhi[()] if rhi.ndim == 0 else rhi
+    return ConfidenceInterval(low=rlo, high=rhi)
+
+
+def _pearsonr_bootstrap_ci(confidence_level, method, x, y, alternative, axis):
+    """
+    Compute the confidence interval for Pearson's R using the bootstrap.
+    """
+    def statistic(x, y, axis):
+        statistic, _ = pearsonr(x, y, axis=axis)
+        return statistic
+
+    res = bootstrap((x, y), statistic, confidence_level=confidence_level, axis=axis,
+                    paired=True, alternative=alternative, **method._asdict())
+    # for one-sided confidence intervals, bootstrap gives +/- inf on one side
+    res.confidence_interval = np.clip(res.confidence_interval, -1, 1)
+
+    return ConfidenceInterval(*res.confidence_interval)
+
+
+ConfidenceInterval = namedtuple('ConfidenceInterval', ['low', 'high'])
+
+PearsonRResultBase = _make_tuple_bunch('PearsonRResultBase',
+                                       ['statistic', 'pvalue'], [])
+
+
+class PearsonRResult(PearsonRResultBase):
+    """
+    Result of `scipy.stats.pearsonr`
+
+    Attributes
+    ----------
+    statistic : float
+        Pearson product-moment correlation coefficient.
+    pvalue : float
+        The p-value associated with the chosen alternative.
+
+    Methods
+    -------
+    confidence_interval
+        Computes the confidence interval of the correlation
+        coefficient `statistic` for the given confidence level.
+
+    """
+    def __init__(self, statistic, pvalue, alternative, n, x, y, axis):
+        super().__init__(statistic, pvalue)
+        self._alternative = alternative
+        self._n = n
+        self._x = x
+        self._y = y
+        self._axis = axis
+
+        # add alias for consistency with other correlation functions
+        self.correlation = statistic
+
+    def confidence_interval(self, confidence_level=0.95, method=None):
+        """
+        The confidence interval for the correlation coefficient.
+
+        Compute the confidence interval for the correlation coefficient
+        ``statistic`` with the given confidence level.
+
+        If `method` is not provided,
+        The confidence interval is computed using the Fisher transformation
+        F(r) = arctanh(r) [1]_.  When the sample pairs are drawn from a
+        bivariate normal distribution, F(r) approximately follows a normal
+        distribution with standard error ``1/sqrt(n - 3)``, where ``n`` is the
+        length of the original samples along the calculation axis. When
+        ``n <= 3``, this approximation does not yield a finite, real standard
+        error, so we define the confidence interval to be -1 to 1.
+
+        If `method` is an instance of `BootstrapMethod`, the confidence
+        interval is computed using `scipy.stats.bootstrap` with the provided
+        configuration options and other appropriate settings. In some cases,
+        confidence limits may be NaN due to a degenerate resample, and this is
+        typical for very small samples (~6 observations).
+
+        Parameters
+        ----------
+        confidence_level : float
+            The confidence level for the calculation of the correlation
+            coefficient confidence interval. Default is 0.95.
+
+        method : BootstrapMethod, optional
+            Defines the method used to compute the confidence interval. See
+            method description for details.
+
+            .. versionadded:: 1.11.0
+
+        Returns
+        -------
+        ci : namedtuple
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.
+
+        References
+        ----------
+        .. [1] "Pearson correlation coefficient", Wikipedia,
+               https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
+        """
+        if isinstance(method, BootstrapMethod):
+            xp = array_namespace(self._x)
+            message = ('`method` must be `None` if `pearsonr` '
+                       'arguments were not NumPy arrays.')
+            if not is_numpy(xp):
+                raise ValueError(message)
+
+            ci = _pearsonr_bootstrap_ci(confidence_level, method, self._x, self._y,
+                                        self._alternative, self._axis)
+        elif method is None:
+            ci = _pearsonr_fisher_ci(self.statistic, self._n, confidence_level,
+                                     self._alternative)
+        else:
+            message = ('`method` must be an instance of `BootstrapMethod` '
+                       'or None.')
+            raise ValueError(message)
+        return ci
+
+
+def pearsonr(x, y, *, alternative='two-sided', method=None, axis=0):
+    r"""
+    Pearson correlation coefficient and p-value for testing non-correlation.
+
+    The Pearson correlation coefficient [1]_ measures the linear relationship
+    between two datasets. Like other correlation
+    coefficients, this one varies between -1 and +1 with 0 implying no
+    correlation. Correlations of -1 or +1 imply an exact linear relationship.
+    Positive correlations imply that as x increases, so does y. Negative
+    correlations imply that as x increases, y decreases.
+
+    This function also performs a test of the null hypothesis that the
+    distributions underlying the samples are uncorrelated and normally
+    distributed. (See Kowalski [3]_
+    for a discussion of the effects of non-normality of the input on the
+    distribution of the correlation coefficient.)
+    The p-value roughly indicates the probability of an uncorrelated system
+    producing datasets that have a Pearson correlation at least as extreme
+    as the one computed from these datasets.
+
+    Parameters
+    ----------
+    x : array_like
+        Input array.
+    y : array_like
+        Input array.
+    axis : int or None, default
+        Axis along which to perform the calculation. Default is 0.
+        If None, ravel both arrays before performing the calculation.
+
+        .. versionadded:: 1.13.0
+    alternative : {'two-sided', 'greater', 'less'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the correlation is nonzero
+        * 'less': the correlation is negative (less than zero)
+        * 'greater':  the correlation is positive (greater than zero)
+
+        .. versionadded:: 1.9.0
+    method : ResamplingMethod, optional
+        Defines the method used to compute the p-value. If `method` is an
+        instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is
+        computed using
+        `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
+        provided configuration options and other appropriate settings.
+        Otherwise, the p-value is computed as documented in the notes.
+
+        .. versionadded:: 1.11.0
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.PearsonRResult`
+        An object with the following attributes:
+
+        statistic : float
+            Pearson product-moment correlation coefficient.
+        pvalue : float
+            The p-value associated with the chosen alternative.
+
+        The object has the following method:
+
+        confidence_interval(confidence_level, method)
+            This computes the confidence interval of the correlation
+            coefficient `statistic` for the given confidence level.
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`. If `method` is not provided, the
+            confidence interval is computed using the Fisher transformation
+            [1]_. If `method` is an instance of `BootstrapMethod`, the
+            confidence interval is computed using `scipy.stats.bootstrap` with
+            the provided configuration options and other appropriate settings.
+            In some cases, confidence limits may be NaN due to a degenerate
+            resample, and this is typical for very small samples (~6
+            observations).
+
+    Raises
+    ------
+    ValueError
+        If `x` and `y` do not have length at least 2.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Raised if an input is a constant array.  The correlation coefficient
+        is not defined in this case, so ``np.nan`` is returned.
+
+    `~scipy.stats.NearConstantInputWarning`
+        Raised if an input is "nearly" constant.  The array ``x`` is considered
+        nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``.
+        Numerical errors in the calculation ``x - mean(x)`` in this case might
+        result in an inaccurate calculation of r.
+
+    See Also
+    --------
+    spearmanr : Spearman rank-order correlation coefficient.
+    kendalltau : Kendall's tau, a correlation measure for ordinal data.
+
+    Notes
+    -----
+    The correlation coefficient is calculated as follows:
+
+    .. math::
+
+        r = \frac{\sum (x - m_x) (y - m_y)}
+                 {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}}
+
+    where :math:`m_x` is the mean of the vector x and :math:`m_y` is
+    the mean of the vector y.
+
+    Under the assumption that x and y are drawn from
+    independent normal distributions (so the population correlation coefficient
+    is 0), the probability density function of the sample correlation
+    coefficient r is ([1]_, [2]_):
+
+    .. math::
+        f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)}
+
+    where n is the number of samples, and B is the beta function.  This
+    is sometimes referred to as the exact distribution of r.  This is
+    the distribution that is used in `pearsonr` to compute the p-value when
+    the `method` parameter is left at its default value (None).
+    The distribution is a beta distribution on the interval [-1, 1],
+    with equal shape parameters a = b = n/2 - 1.  In terms of SciPy's
+    implementation of the beta distribution, the distribution of r is::
+
+        dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)
+
+    The default p-value returned by `pearsonr` is a two-sided p-value. For a
+    given sample with correlation coefficient r, the p-value is
+    the probability that abs(r') of a random sample x' and y' drawn from
+    the population with zero correlation would be greater than or equal
+    to abs(r). In terms of the object ``dist`` shown above, the p-value
+    for a given r and length n can be computed as::
+
+        p = 2*dist.cdf(-abs(r))
+
+    When n is 2, the above continuous distribution is not well-defined.
+    One can interpret the limit of the beta distribution as the shape
+    parameters a and b approach a = b = 0 as a discrete distribution with
+    equal probability masses at r = 1 and r = -1.  More directly, one
+    can observe that, given the data x = [x1, x2] and y = [y1, y2], and
+    assuming x1 != x2 and y1 != y2, the only possible values for r are 1
+    and -1.  Because abs(r') for any sample x' and y' with length 2 will
+    be 1, the two-sided p-value for a sample of length 2 is always 1.
+
+    For backwards compatibility, the object that is returned also behaves
+    like a tuple of length two that holds the statistic and the p-value.
+
+    References
+    ----------
+    .. [1] "Pearson correlation coefficient", Wikipedia,
+           https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
+    .. [2] Student, "Probable error of a correlation coefficient",
+           Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310.
+    .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution
+           of the Sample Product-Moment Correlation Coefficient"
+           Journal of the Royal Statistical Society. Series C (Applied
+           Statistics), Vol. 21, No. 1 (1972), pp. 1-12.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x, y = [1, 2, 3, 4, 5, 6, 7], [10, 9, 2.5, 6, 4, 3, 2]
+    >>> res = stats.pearsonr(x, y)
+    >>> res
+    PearsonRResult(statistic=-0.828503883588428, pvalue=0.021280260007523286)
+
+    To perform an exact permutation version of the test:
+
+    >>> rng = np.random.default_rng(7796654889291491997)
+    >>> method = stats.PermutationMethod(n_resamples=np.inf, random_state=rng)
+    >>> stats.pearsonr(x, y, method=method)
+    PearsonRResult(statistic=-0.828503883588428, pvalue=0.028174603174603175)
+
+    To perform the test under the null hypothesis that the data were drawn from
+    *uniform* distributions:
+
+    >>> method = stats.MonteCarloMethod(rvs=(rng.uniform, rng.uniform))
+    >>> stats.pearsonr(x, y, method=method)
+    PearsonRResult(statistic=-0.828503883588428, pvalue=0.0188)
+
+    To produce an asymptotic 90% confidence interval:
+
+    >>> res.confidence_interval(confidence_level=0.9)
+    ConfidenceInterval(low=-0.9644331982722841, high=-0.3460237473272273)
+
+    And for a bootstrap confidence interval:
+
+    >>> method = stats.BootstrapMethod(method='BCa', rng=rng)
+    >>> res.confidence_interval(confidence_level=0.9, method=method)
+    ConfidenceInterval(low=-0.9983163756488651, high=-0.22771001702132443)  # may vary
+
+    If N-dimensional arrays are provided, multiple tests are performed in a
+    single call according to the same conventions as most `scipy.stats` functions:
+
+    >>> rng = np.random.default_rng(2348246935601934321)
+    >>> x = rng.standard_normal((8, 15))
+    >>> y = rng.standard_normal((8, 15))
+    >>> stats.pearsonr(x, y, axis=0).statistic.shape  # between corresponding columns
+    (15,)
+    >>> stats.pearsonr(x, y, axis=1).statistic.shape  # between corresponding rows
+    (8,)
+
+    To perform all pairwise comparisons between slices of the arrays,
+    use standard NumPy broadcasting techniques. For instance, to compute the
+    correlation between all pairs of rows:
+
+    >>> stats.pearsonr(x[:, np.newaxis, :], y, axis=-1).statistic.shape
+    (8, 8)
+
+    There is a linear dependence between x and y if y = a + b*x + e, where
+    a,b are constants and e is a random error term, assumed to be independent
+    of x. For simplicity, assume that x is standard normal, a=0, b=1 and let
+    e follow a normal distribution with mean zero and standard deviation s>0.
+
+    >>> rng = np.random.default_rng()
+    >>> s = 0.5
+    >>> x = stats.norm.rvs(size=500, random_state=rng)
+    >>> e = stats.norm.rvs(scale=s, size=500, random_state=rng)
+    >>> y = x + e
+    >>> stats.pearsonr(x, y).statistic
+    0.9001942438244763
+
+    This should be close to the exact value given by
+
+    >>> 1/np.sqrt(1 + s**2)
+    0.8944271909999159
+
+    For s=0.5, we observe a high level of correlation. In general, a large
+    variance of the noise reduces the correlation, while the correlation
+    approaches one as the variance of the error goes to zero.
+
+    It is important to keep in mind that no correlation does not imply
+    independence unless (x, y) is jointly normal. Correlation can even be zero
+    when there is a very simple dependence structure: if X follows a
+    standard normal distribution, let y = abs(x). Note that the correlation
+    between x and y is zero. Indeed, since the expectation of x is zero,
+    cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero
+    by symmetry. The following lines of code illustrate this observation:
+
+    >>> y = np.abs(x)
+    >>> stats.pearsonr(x, y)
+    PearsonRResult(statistic=-0.05444919272687482, pvalue=0.22422294836207743)
+
+    A non-zero correlation coefficient can be misleading. For example, if X has
+    a standard normal distribution, define y = x if x < 0 and y = 0 otherwise.
+    A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797...,
+    implying a high level of correlation:
+
+    >>> y = np.where(x < 0, x, 0)
+    >>> stats.pearsonr(x, y)
+    PearsonRResult(statistic=0.861985781588, pvalue=4.813432002751103e-149)
+
+    This is unintuitive since there is no dependence of x and y if x is larger
+    than zero which happens in about half of the cases if we sample x and y.
+
+    """
+    xp = array_namespace(x, y)
+    x = xp.asarray(x)
+    y = xp.asarray(y)
+
+    if not is_numpy(xp) and method is not None:
+        method = 'invalid'
+
+    if axis is None:
+        x = xp.reshape(x, (-1,))
+        y = xp.reshape(y, (-1,))
+        axis = -1
+
+    axis_int = int(axis)
+    if axis_int != axis:
+        raise ValueError('`axis` must be an integer.')
+    axis = axis_int
+
+    n = x.shape[axis]
+    if n != y.shape[axis]:
+        raise ValueError('`x` and `y` must have the same length along `axis`.')
+
+    if n < 2:
+        raise ValueError('`x` and `y` must have length at least 2.')
+
+    try:
+        x, y = xp.broadcast_arrays(x, y)
+    except (ValueError, RuntimeError) as e:
+        message = '`x` and `y` must be broadcastable.'
+        raise ValueError(message) from e
+
+    # `moveaxis` only recently added to array API, so it's not yey available in
+    # array_api_strict. Replace with e.g. `xp.moveaxis(x, axis, -1)` when available.
+    x = xp_moveaxis_to_end(x, axis, xp=xp)
+    y = xp_moveaxis_to_end(y, axis, xp=xp)
+    axis = -1
+
+    dtype = xp.result_type(x.dtype, y.dtype)
+    if xp.isdtype(dtype, "integral"):
+        dtype = xp.asarray(1.).dtype
+
+    if xp.isdtype(dtype, "complex floating"):
+        raise ValueError('This function does not support complex data')
+
+    x = xp.astype(x, dtype, copy=False)
+    y = xp.astype(y, dtype, copy=False)
+    threshold = xp.finfo(dtype).eps ** 0.75
+
+    # If an input is constant, the correlation coefficient is not defined.
+    const_x = xp.all(x == x[..., 0:1], axis=-1)
+    const_y = xp.all(y == y[..., 0:1], axis=-1)
+    const_xy = const_x | const_y
+    if xp.any(const_xy):
+        msg = ("An input array is constant; the correlation coefficient "
+               "is not defined.")
+        warnings.warn(stats.ConstantInputWarning(msg), stacklevel=2)
+
+    if isinstance(method, PermutationMethod):
+        def statistic(y, axis):
+            statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative)
+            return statistic
+
+        res = permutation_test((y,), statistic, permutation_type='pairings',
+                               axis=axis, alternative=alternative, **method._asdict())
+
+        return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n,
+                              alternative=alternative, x=x, y=y, axis=axis)
+    elif isinstance(method, MonteCarloMethod):
+        def statistic(x, y, axis):
+            statistic, _ = pearsonr(x, y, axis=axis, alternative=alternative)
+            return statistic
+
+        # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng`
+        # If the user specified an `rng`, replace it with the appropriate callables
+        method = method._asdict()
+        if (rng := method.pop('rng', None)) is not None:  # goo-goo g'joob
+            rng = np.random.default_rng(rng)
+            method['rvs'] = rng.normal, rng.normal
+
+        res = monte_carlo_test((x, y,), statistic=statistic, axis=axis,
+                               alternative=alternative, **method)
+
+        return PearsonRResult(statistic=res.statistic, pvalue=res.pvalue, n=n,
+                              alternative=alternative, x=x, y=y, axis=axis)
+    elif method == 'invalid':
+        message = '`method` must be `None` if arguments are not NumPy arrays.'
+        raise ValueError(message)
+    elif method is not None:
+        message = ('`method` must be an instance of `PermutationMethod`,'
+                   '`MonteCarloMethod`, or None.')
+        raise ValueError(message)
+
+    xmean = xp.mean(x, axis=axis, keepdims=True)
+    ymean = xp.mean(y, axis=axis, keepdims=True)
+    xm = x - xmean
+    ym = y - ymean
+
+    # scipy.linalg.norm(xm) avoids premature overflow when xm is e.g.
+    # [-5e210, 5e210, 3e200, -3e200]
+    # but not when `axis` is provided, so scale manually. scipy.linalg.norm
+    # also raises an error with NaN input rather than returning NaN, so
+    # use np.linalg.norm.
+    xmax = xp.max(xp.abs(xm), axis=axis, keepdims=True)
+    ymax = xp.max(xp.abs(ym), axis=axis, keepdims=True)
+    with np.errstate(invalid='ignore', divide='ignore'):
+        normxm = xmax * xp_vector_norm(xm/xmax, axis=axis, keepdims=True)
+        normym = ymax * xp_vector_norm(ym/ymax, axis=axis, keepdims=True)
+
+    nconst_x = xp.any(normxm < threshold*xp.abs(xmean), axis=axis)
+    nconst_y = xp.any(normym < threshold*xp.abs(ymean), axis=axis)
+    nconst_xy = nconst_x | nconst_y
+    if xp.any(nconst_xy & (~const_xy)):
+        # If all the values in x (likewise y) are very close to the mean,
+        # the loss of precision that occurs in the subtraction xm = x - xmean
+        # might result in large errors in r.
+        msg = ("An input array is nearly constant; the computed "
+               "correlation coefficient may be inaccurate.")
+        warnings.warn(stats.NearConstantInputWarning(msg), stacklevel=2)
+
+    with np.errstate(invalid='ignore', divide='ignore'):
+        r = xp.sum(xm/normxm * ym/normym, axis=axis)
+
+    # Presumably, if abs(r) > 1, then it is only some small artifact of
+    # floating point arithmetic.
+    one = xp.asarray(1, dtype=dtype)
+    r = xp.asarray(xp.clip(r, -one, one))
+    r[const_xy] = xp.nan
+
+    # Make sure we return exact 1.0 or -1.0 values for n == 2 case as promised
+    # in the docs.
+    if n == 2:
+        r = xp.round(r)
+        one = xp.asarray(1, dtype=dtype)
+        pvalue = xp.where(xp.asarray(xp.isnan(r)), xp.nan*one, one)
+    else:
+        # As explained in the docstring, the distribution of `r` under the null
+        # hypothesis is the beta distribution on (-1, 1) with a = b = n/2 - 1.
+        ab = xp.asarray(n/2 - 1)
+        dist = _SimpleBeta(ab, ab, loc=-1, scale=2)
+        pvalue = _get_pvalue(r, dist, alternative, xp=xp)
+
+    r = r[()] if r.ndim == 0 else r
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+    return PearsonRResult(statistic=r, pvalue=pvalue, n=n,
+                          alternative=alternative, x=x, y=y, axis=axis)
+
+
+def fisher_exact(table, alternative=None, *, method=None):
+    """Perform a Fisher exact test on a contingency table.
+
+    For a 2x2 table,
+    the null hypothesis is that the true odds ratio of the populations
+    underlying the observations is one, and the observations were sampled
+    from these populations under a condition: the marginals of the
+    resulting table must equal those of the observed table.
+    The statistic is the unconditional maximum likelihood estimate of the odds
+    ratio, and the p-value is the probability under the null hypothesis of
+    obtaining a table at least as extreme as the one that was actually
+    observed.
+
+    For other table sizes, or if `method` is provided, the null hypothesis
+    is that the rows and columns of the tables have fixed sums and are
+    independent; i.e., the table was sampled from a `scipy.stats.random_table`
+    distribution with the observed marginals. The statistic is the
+    probability mass of this distribution evaluated at `table`, and the
+    p-value is the percentage of the population of tables with statistic at
+    least as extreme (small) as that of `table`. There is only one alternative
+    hypothesis available: the rows and columns are not independent.
+
+    There are other possible choices of statistic and two-sided
+    p-value definition associated with Fisher's exact test; please see the
+    Notes for more information.
+
+    Parameters
+    ----------
+    table : array_like of ints
+        A contingency table.  Elements must be non-negative integers.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis for 2x2 tables; unused for other
+        table sizes.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the odds ratio of the underlying population is not one
+        * 'less': the odds ratio of the underlying population is less than one
+        * 'greater': the odds ratio of the underlying population is greater
+          than one
+
+        See the Notes for more details.
+
+    method : ResamplingMethod, optional
+        Defines the method used to compute the p-value.
+        If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`,
+        the p-value is computed using
+        `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
+        provided configuration options and other appropriate settings.
+        Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs``
+        attribute must be left unspecified; Monte Carlo samples are always drawn
+        using the ``rvs`` method of `scipy.stats.random_table`.
+        Otherwise, the p-value is computed as documented in the notes.
+
+        .. versionadded:: 1.15.0
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+            For a 2x2 table with default `method`, this is the odds ratio - the
+            prior odds ratio not a posterior estimate. In all other cases, this
+            is the probability density of obtaining the observed table under the
+            null hypothesis of independence with marginals fixed.
+        pvalue : float
+            The probability under the null hypothesis of obtaining a
+            table at least as extreme as the one that was actually observed.
+
+    Raises
+    ------
+    ValueError
+        If `table` is not two-dimensional or has negative entries.
+
+    See Also
+    --------
+    chi2_contingency : Chi-square test of independence of variables in a
+        contingency table.  This can be used as an alternative to
+        `fisher_exact` when the numbers in the table are large.
+    contingency.odds_ratio : Compute the odds ratio (sample or conditional
+        MLE) for a 2x2 contingency table.
+    barnard_exact : Barnard's exact test, which is a more powerful alternative
+        than Fisher's exact test for 2x2 contingency tables.
+    boschloo_exact : Boschloo's exact test, which is a more powerful
+        alternative than Fisher's exact test for 2x2 contingency tables.
+    :ref:`hypothesis_fisher_exact` : Extended example
+
+    Notes
+    -----
+    *Null hypothesis and p-values*
+
+    The null hypothesis is that the true odds ratio of the populations
+    underlying the observations is one, and the observations were sampled at
+    random from these populations under a condition: the marginals of the
+    resulting table must equal those of the observed table. Equivalently,
+    the null hypothesis is that the input table is from the hypergeometric
+    distribution with parameters (as used in `hypergeom`)
+    ``M = a + b + c + d``, ``n = a + b`` and ``N = a + c``, where the
+    input table is ``[[a, b], [c, d]]``.  This distribution has support
+    ``max(0, N + n - M) <= x <= min(N, n)``, or, in terms of the values
+    in the input table, ``min(0, a - d) <= x <= a + min(b, c)``.  ``x``
+    can be interpreted as the upper-left element of a 2x2 table, so the
+    tables in the distribution have form::
+
+        [  x           n - x     ]
+        [N - x    M - (n + N) + x]
+
+    For example, if::
+
+        table = [6  2]
+                [1  4]
+
+    then the support is ``2 <= x <= 7``, and the tables in the distribution
+    are::
+
+        [2 6]   [3 5]   [4 4]   [5 3]   [6 2]  [7 1]
+        [5 0]   [4 1]   [3 2]   [2 3]   [1 4]  [0 5]
+
+    The probability of each table is given by the hypergeometric distribution
+    ``hypergeom.pmf(x, M, n, N)``.  For this example, these are (rounded to
+    three significant digits)::
+
+        x       2      3      4      5       6        7
+        p  0.0163  0.163  0.408  0.326  0.0816  0.00466
+
+    These can be computed with::
+
+        >>> import numpy as np
+        >>> from scipy.stats import hypergeom
+        >>> table = np.array([[6, 2], [1, 4]])
+        >>> M = table.sum()
+        >>> n = table[0].sum()
+        >>> N = table[:, 0].sum()
+        >>> start, end = hypergeom.support(M, n, N)
+        >>> hypergeom.pmf(np.arange(start, end+1), M, n, N)
+        array([0.01631702, 0.16317016, 0.40792541, 0.32634033, 0.08158508,
+               0.004662  ])
+
+    The two-sided p-value is the probability that, under the null hypothesis,
+    a random table would have a probability equal to or less than the
+    probability of the input table.  For our example, the probability of
+    the input table (where ``x = 6``) is 0.0816.  The x values where the
+    probability does not exceed this are 2, 6 and 7, so the two-sided p-value
+    is ``0.0163 + 0.0816 + 0.00466 ~= 0.10256``::
+
+        >>> from scipy.stats import fisher_exact
+        >>> res = fisher_exact(table, alternative='two-sided')
+        >>> res.pvalue
+        0.10256410256410257
+
+    The one-sided p-value for ``alternative='greater'`` is the probability
+    that a random table has ``x >= a``, which in our example is ``x >= 6``,
+    or ``0.0816 + 0.00466 ~= 0.08626``::
+
+        >>> res = fisher_exact(table, alternative='greater')
+        >>> res.pvalue
+        0.08624708624708627
+
+    This is equivalent to computing the survival function of the
+    distribution at ``x = 5`` (one less than ``x`` from the input table,
+    because we want to include the probability of ``x = 6`` in the sum)::
+
+        >>> hypergeom.sf(5, M, n, N)
+        0.08624708624708627
+
+    For ``alternative='less'``, the one-sided p-value is the probability
+    that a random table has ``x <= a``, (i.e. ``x <= 6`` in our example),
+    or ``0.0163 + 0.163 + 0.408 + 0.326 + 0.0816 ~= 0.9949``::
+
+        >>> res = fisher_exact(table, alternative='less')
+        >>> res.pvalue
+        0.9953379953379957
+
+    This is equivalent to computing the cumulative distribution function
+    of the distribution at ``x = 6``:
+
+        >>> hypergeom.cdf(6, M, n, N)
+        0.9953379953379957
+
+    *Odds ratio*
+
+    The calculated odds ratio is different from the value computed by the
+    R function ``fisher.test``.  This implementation returns the "sample"
+    or "unconditional" maximum likelihood estimate, while ``fisher.test``
+    in R uses the conditional maximum likelihood estimate.  To compute the
+    conditional maximum likelihood estimate of the odds ratio, use
+    `scipy.stats.contingency.odds_ratio`.
+
+    References
+    ----------
+    .. [1] Fisher, Sir Ronald A, "The Design of Experiments:
+           Mathematics of a Lady Tasting Tea." ISBN 978-0-486-41151-4, 1935.
+    .. [2] "Fisher's exact test",
+           https://en.wikipedia.org/wiki/Fisher's_exact_test
+
+    Examples
+    --------
+
+    >>> from scipy.stats import fisher_exact
+    >>> res = fisher_exact([[8, 2], [1, 5]])
+    >>> res.statistic
+    20.0
+    >>> res.pvalue
+    0.034965034965034975
+
+    For tables with shape other than ``(2, 2)``, provide an instance of
+    `scipy.stats.MonteCarloMethod` or `scipy.stats.PermutationMethod` for the
+    `method` parameter:
+
+    >>> import numpy as np
+    >>> from scipy.stats import MonteCarloMethod
+    >>> rng = np.random.default_rng(4507195762371367)
+    >>> method = MonteCarloMethod(rng=rng)
+    >>> fisher_exact([[8, 2, 3], [1, 5, 4]], method=method)
+    SignificanceResult(statistic=np.float64(0.005782), pvalue=np.float64(0.0603))
+
+    For a more detailed example, see :ref:`hypothesis_fisher_exact`.
+    """
+    hypergeom = distributions.hypergeom
+    # int32 is not enough for the algorithm
+    c = np.asarray(table, dtype=np.int64)
+    if not c.ndim == 2:
+        raise ValueError("The input `table` must have two dimensions.")
+
+    if np.any(c < 0):
+        raise ValueError("All values in `table` must be nonnegative.")
+
+    if not c.shape == (2, 2) or method is not None:
+        return _fisher_exact_rxc(c, alternative, method)
+    alternative = 'two-sided' if alternative is None else alternative
+
+    if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
+        # If both values in a row or column are zero, the p-value is 1 and
+        # the odds ratio is NaN.
+        return SignificanceResult(np.nan, 1.0)
+
+    if c[1, 0] > 0 and c[0, 1] > 0:
+        oddsratio = c[0, 0] * c[1, 1] / (c[1, 0] * c[0, 1])
+    else:
+        oddsratio = np.inf
+
+    n1 = c[0, 0] + c[0, 1]
+    n2 = c[1, 0] + c[1, 1]
+    n = c[0, 0] + c[1, 0]
+
+    def pmf(x):
+        return hypergeom.pmf(x, n1 + n2, n1, n)
+
+    if alternative == 'less':
+        pvalue = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
+    elif alternative == 'greater':
+        # Same formula as the 'less' case, but with the second column.
+        pvalue = hypergeom.cdf(c[0, 1], n1 + n2, n1, c[0, 1] + c[1, 1])
+    elif alternative == 'two-sided':
+        mode = int((n + 1) * (n1 + 1) / (n1 + n2 + 2))
+        pexact = hypergeom.pmf(c[0, 0], n1 + n2, n1, n)
+        pmode = hypergeom.pmf(mode, n1 + n2, n1, n)
+
+        epsilon = 1e-14
+        gamma = 1 + epsilon
+
+        if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= epsilon:
+            return SignificanceResult(oddsratio, 1.)
+
+        elif c[0, 0] < mode:
+            plower = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
+            if hypergeom.pmf(n, n1 + n2, n1, n) > pexact * gamma:
+                return SignificanceResult(oddsratio, plower)
+
+            guess = _binary_search(lambda x: -pmf(x), -pexact * gamma, mode, n)
+            pvalue = plower + hypergeom.sf(guess, n1 + n2, n1, n)
+        else:
+            pupper = hypergeom.sf(c[0, 0] - 1, n1 + n2, n1, n)
+            if hypergeom.pmf(0, n1 + n2, n1, n) > pexact * gamma:
+                return SignificanceResult(oddsratio, pupper)
+
+            guess = _binary_search(pmf, pexact * gamma, 0, mode)
+            pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n)
+    else:
+        msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}"
+        raise ValueError(msg)
+
+    pvalue = min(pvalue, 1.0)
+
+    return SignificanceResult(oddsratio, pvalue)
+
+
+def _fisher_exact_rxc(table, alternative, method):
+    if alternative is not None:
+        message = ('`alternative` must be the default (None) unless '
+                  '`table` has shape `(2, 2)` and `method is None`.')
+        raise ValueError(message)
+
+    if table.size == 0:
+        raise ValueError("`table` must have at least one row and one column.")
+
+    if table.shape[0] == 1 or table.shape[1] == 1 or np.all(table == 0):
+        # Only one such table with those marginals
+        return SignificanceResult(1.0, 1.0)
+
+    if method is None:
+        method = stats.MonteCarloMethod()
+
+    if isinstance(method, stats.PermutationMethod):
+        res = _fisher_exact_permutation_method(table, method)
+    elif isinstance(method, stats.MonteCarloMethod):
+        res = _fisher_exact_monte_carlo_method(table, method)
+    else:
+        message = (f'`{method=}` not recognized; if provided, `method` must be an '
+                   'instance of `PermutationMethod` or `MonteCarloMethod`.')
+        raise ValueError(message)
+
+    return SignificanceResult(np.clip(res.statistic, None, 1.0), res.pvalue)
+
+
+def _fisher_exact_permutation_method(table, method):
+    x, y = _untabulate(table)
+    colsums = np.sum(table, axis=0)
+    rowsums = np.sum(table, axis=1)
+    X = stats.random_table(rowsums, colsums)
+
+    # `permutation_test` with `permutation_type='pairings' permutes the order of `x`,
+    # which pairs observations in `x` with different observations in `y`.
+    def statistic(x):
+        # crosstab the resample and compute the statistic
+        table = stats.contingency.crosstab(x, y)[1]
+        return X.pmf(table)
+
+    # tables with *smaller* probability mass are considered to be more extreme
+    return stats.permutation_test((x,), statistic, permutation_type='pairings',
+                                  alternative='less', **method._asdict())
+
+
+def _fisher_exact_monte_carlo_method(table, method):
+    method = method._asdict()
+
+    if method.pop('rvs', None) is not None:
+        message = ('If the `method` argument of `fisher_exact` is an '
+                   'instance of `MonteCarloMethod`, its `rvs` attribute '
+                   'must be unspecified. Use the `MonteCarloMethod` `rng` argument '
+                   'to control the random state.')
+        raise ValueError(message)
+    rng = np.random.default_rng(method.pop('rng', None))
+
+    # `random_table.rvs` produces random contingency tables with the given marginals
+    # under the null hypothesis of independence
+    shape = table.shape
+    colsums = np.sum(table, axis=0)
+    rowsums = np.sum(table, axis=1)
+    totsum = np.sum(table)
+    X = stats.random_table(rowsums, colsums, seed=rng)
+
+    def rvs(size):
+        n_resamples = size[0]
+        return X.rvs(size=n_resamples).reshape(size)
+
+    # axis signals to `monte_carlo_test` that statistic is vectorized, but we know
+    # how it will pass the table(s), so we don't need to use `axis` explicitly.
+    def statistic(table, axis):
+        shape_ = (-1,) + shape if table.size > totsum else shape
+        return X.pmf(table.reshape(shape_))
+
+    # tables with *smaller* probability mass are considered to be more extreme
+    return stats.monte_carlo_test(table.ravel(), rvs, statistic,
+                                  alternative='less', **method)
+
+
+def _untabulate(table):
+    # converts a contingency table to paired samples indicating the
+    # correspondence between row and column indices
+    r, c = table.shape
+    x, y = [], []
+    for i in range(r):
+        for j in range(c):
+            x.append([i] * table[i, j])
+            y.append([j] * table[i, j])
+    return np.concatenate(x), np.concatenate(y)
+
+
+def spearmanr(a, b=None, axis=0, nan_policy='propagate',
+              alternative='two-sided'):
+    r"""Calculate a Spearman correlation coefficient with associated p-value.
+
+    The Spearman rank-order correlation coefficient is a nonparametric measure
+    of the monotonicity of the relationship between two datasets.
+    Like other correlation coefficients,
+    this one varies between -1 and +1 with 0 implying no correlation.
+    Correlations of -1 or +1 imply an exact monotonic relationship. Positive
+    correlations imply that as x increases, so does y. Negative correlations
+    imply that as x increases, y decreases.
+
+    The p-value roughly indicates the probability of an uncorrelated system
+    producing datasets that have a Spearman correlation at least as extreme
+    as the one computed from these datasets. Although calculation of the
+    p-value does not make strong assumptions about the distributions underlying
+    the samples, it is only accurate for very large samples (>500
+    observations). For smaller sample sizes, consider a permutation test (see
+    Examples section below).
+
+    Parameters
+    ----------
+    a, b : 1D or 2D array_like, b is optional
+        One or two 1-D or 2-D arrays containing multiple variables and
+        observations. When these are 1-D, each represents a vector of
+        observations of a single variable. For the behavior in the 2-D case,
+        see under ``axis``, below.
+        Both arrays need to have the same length in the ``axis`` dimension.
+    axis : int or None, optional
+        If axis=0 (default), then each column represents a variable, with
+        observations in the rows. If axis=1, the relationship is transposed:
+        each row represents a variable, while the columns contain observations.
+        If axis=None, then both arrays will be raveled.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the correlation is nonzero
+        * 'less': the correlation is negative (less than zero)
+        * 'greater':  the correlation is positive (greater than zero)
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float or ndarray (2-D square)
+            Spearman correlation matrix or correlation coefficient (if only 2
+            variables are given as parameters). Correlation matrix is square
+            with length equal to total number of variables (columns or rows) in
+            ``a`` and ``b`` combined.
+        pvalue : float
+            The p-value for a hypothesis test whose null hypothesis
+            is that two samples have no ordinal correlation. See
+            `alternative` above for alternative hypotheses. `pvalue` has the
+            same shape as `statistic`.
+
+    Raises
+    ------
+    ValueError
+        If `axis` is not 0, 1 or None, or if the number of dimensions of `a`
+        is greater than 2, or if `b` is None and the number of dimensions of
+        `a` is less than 2.
+
+    Warns
+    -----
+    `~scipy.stats.ConstantInputWarning`
+        Raised if an input is a constant array.  The correlation coefficient
+        is not defined in this case, so ``np.nan`` is returned.
+
+    See Also
+    --------
+    :ref:`hypothesis_spearmanr` : Extended example
+
+    References
+    ----------
+    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+       Probability and Statistics Tables and Formulae. Chapman & Hall: New
+       York. 2000.
+       Section  14.7
+    .. [2] Kendall, M. G. and Stuart, A. (1973).
+       The Advanced Theory of Statistics, Volume 2: Inference and Relationship.
+       Griffin. 1973.
+       Section 31.18
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> res = stats.spearmanr([1, 2, 3, 4, 5], [5, 6, 7, 8, 7])
+    >>> res.statistic
+    0.8207826816681233
+    >>> res.pvalue
+    0.08858700531354381
+
+    >>> rng = np.random.default_rng()
+    >>> x2n = rng.standard_normal((100, 2))
+    >>> y2n = rng.standard_normal((100, 2))
+    >>> res = stats.spearmanr(x2n)
+    >>> res.statistic, res.pvalue
+    (-0.07960396039603959, 0.4311168705769747)
+
+    >>> res = stats.spearmanr(x2n[:, 0], x2n[:, 1])
+    >>> res.statistic, res.pvalue
+    (-0.07960396039603959, 0.4311168705769747)
+
+    >>> res = stats.spearmanr(x2n, y2n)
+    >>> res.statistic
+    array([[ 1. , -0.07960396, -0.08314431, 0.09662166],
+           [-0.07960396, 1. , -0.14448245, 0.16738074],
+           [-0.08314431, -0.14448245, 1. , 0.03234323],
+           [ 0.09662166, 0.16738074, 0.03234323, 1. ]])
+    >>> res.pvalue
+    array([[0. , 0.43111687, 0.41084066, 0.33891628],
+           [0.43111687, 0. , 0.15151618, 0.09600687],
+           [0.41084066, 0.15151618, 0. , 0.74938561],
+           [0.33891628, 0.09600687, 0.74938561, 0. ]])
+
+    >>> res = stats.spearmanr(x2n.T, y2n.T, axis=1)
+    >>> res.statistic
+    array([[ 1. , -0.07960396, -0.08314431, 0.09662166],
+           [-0.07960396, 1. , -0.14448245, 0.16738074],
+           [-0.08314431, -0.14448245, 1. , 0.03234323],
+           [ 0.09662166, 0.16738074, 0.03234323, 1. ]])
+
+    >>> res = stats.spearmanr(x2n, y2n, axis=None)
+    >>> res.statistic, res.pvalue
+    (0.044981624540613524, 0.5270803651336189)
+
+    >>> res = stats.spearmanr(x2n.ravel(), y2n.ravel())
+    >>> res.statistic, res.pvalue
+    (0.044981624540613524, 0.5270803651336189)
+
+    >>> rng = np.random.default_rng()
+    >>> xint = rng.integers(10, size=(100, 2))
+    >>> res = stats.spearmanr(xint)
+    >>> res.statistic, res.pvalue
+    (0.09800224850707953, 0.3320271757932076)
+
+    For small samples, consider performing a permutation test instead of
+    relying on the asymptotic p-value. Note that to calculate the null
+    distribution of the statistic (for all possibly pairings between
+    observations in sample ``x`` and ``y``), only one of the two inputs needs
+    to be permuted.
+
+    >>> x = [1.76405235, 0.40015721, 0.97873798,
+    ... 2.2408932, 1.86755799, -0.97727788]
+    >>> y = [2.71414076, 0.2488, 0.87551913,
+    ... 2.6514917, 2.01160156, 0.47699563]
+
+    >>> def statistic(x): # permute only `x`
+    ...     return stats.spearmanr(x, y).statistic
+    >>> res_exact = stats.permutation_test((x,), statistic,
+    ...     permutation_type='pairings')
+    >>> res_asymptotic = stats.spearmanr(x, y)
+    >>> res_exact.pvalue, res_asymptotic.pvalue # asymptotic pvalue is too low
+    (0.10277777777777777, 0.07239650145772594)
+
+    For a more detailed example, see :ref:`hypothesis_spearmanr`.
+    """
+    if axis is not None and axis > 1:
+        raise ValueError("spearmanr only handles 1-D or 2-D arrays, "
+                         f"supplied axis argument {axis}, please use only "
+                         "values 0, 1 or None for axis")
+
+    a, axisout = _chk_asarray(a, axis)
+    if a.ndim > 2:
+        raise ValueError("spearmanr only handles 1-D or 2-D arrays")
+
+    if b is None:
+        if a.ndim < 2:
+            raise ValueError("`spearmanr` needs at least 2 "
+                             "variables to compare")
+    else:
+        # Concatenate a and b, so that we now only have to handle the case
+        # of a 2-D `a`.
+        b, _ = _chk_asarray(b, axis)
+        if axisout == 0:
+            a = np.column_stack((a, b))
+        else:
+            a = np.vstack((a, b))
+
+    n_vars = a.shape[1 - axisout]
+    n_obs = a.shape[axisout]
+    if n_obs <= 1:
+        # Handle empty arrays or single observations.
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    warn_msg = ("An input array is constant; the correlation coefficient "
+                "is not defined.")
+    if axisout == 0:
+        if (a[:, 0][0] == a[:, 0]).all() or (a[:, 1][0] == a[:, 1]).all():
+            # If an input is constant, the correlation coefficient
+            # is not defined.
+            warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2)
+            res = SignificanceResult(np.nan, np.nan)
+            res.correlation = np.nan
+            return res
+    else:  # case when axisout == 1 b/c a is 2 dim only
+        if (a[0, :][0] == a[0, :]).all() or (a[1, :][0] == a[1, :]).all():
+            # If an input is constant, the correlation coefficient
+            # is not defined.
+            warnings.warn(stats.ConstantInputWarning(warn_msg), stacklevel=2)
+            res = SignificanceResult(np.nan, np.nan)
+            res.correlation = np.nan
+            return res
+
+    a_contains_nan, nan_policy = _contains_nan(a, nan_policy)
+    variable_has_nan = np.zeros(n_vars, dtype=bool)
+    if a_contains_nan:
+        if nan_policy == 'omit':
+            return mstats_basic.spearmanr(a, axis=axis, nan_policy=nan_policy,
+                                          alternative=alternative)
+        elif nan_policy == 'propagate':
+            if a.ndim == 1 or n_vars <= 2:
+                res = SignificanceResult(np.nan, np.nan)
+                res.correlation = np.nan
+                return res
+            else:
+                # Keep track of variables with NaNs, set the outputs to NaN
+                # only for those variables
+                variable_has_nan = np.isnan(a).any(axis=axisout)
+
+    a_ranked = np.apply_along_axis(rankdata, axisout, a)
+    rs = np.corrcoef(a_ranked, rowvar=axisout)
+    dof = n_obs - 2  # degrees of freedom
+
+    # rs can have elements equal to 1, so avoid zero division warnings
+    with np.errstate(divide='ignore'):
+        # clip the small negative values possibly caused by rounding
+        # errors before taking the square root
+        t = rs * np.sqrt((dof/((rs+1.0)*(1.0-rs))).clip(0))
+
+    dist = _SimpleStudentT(dof)
+    prob = _get_pvalue(t, dist, alternative, xp=np)
+
+    # For backwards compatibility, return scalars when comparing 2 columns
+    if rs.shape == (2, 2):
+        res = SignificanceResult(rs[1, 0], prob[1, 0])
+        res.correlation = rs[1, 0]
+        return res
+    else:
+        rs[variable_has_nan, :] = np.nan
+        rs[:, variable_has_nan] = np.nan
+        res = SignificanceResult(rs[()], prob[()])
+        res.correlation = rs
+        return res
+
+
+def pointbiserialr(x, y):
+    r"""Calculate a point biserial correlation coefficient and its p-value.
+
+    The point biserial correlation is used to measure the relationship
+    between a binary variable, x, and a continuous variable, y. Like other
+    correlation coefficients, this one varies between -1 and +1 with 0
+    implying no correlation. Correlations of -1 or +1 imply a determinative
+    relationship.
+
+    This function may be computed using a shortcut formula but produces the
+    same result as `pearsonr`.
+
+    Parameters
+    ----------
+    x : array_like of bools
+        Input array.
+    y : array_like
+        Input array.
+
+    Returns
+    -------
+    res: SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+            The R value.
+        pvalue : float
+            The two-sided p-value.
+
+    Notes
+    -----
+    `pointbiserialr` uses a t-test with ``n-1`` degrees of freedom.
+    It is equivalent to `pearsonr`.
+
+    The value of the point-biserial correlation can be calculated from:
+
+    .. math::
+
+        r_{pb} = \frac{\overline{Y_1} - \overline{Y_0}}
+                      {s_y}
+                 \sqrt{\frac{N_0 N_1}
+                            {N (N - 1)}}
+
+    Where :math:`\overline{Y_{0}}` and :math:`\overline{Y_{1}}` are means
+    of the metric observations coded 0 and 1 respectively; :math:`N_{0}` and
+    :math:`N_{1}` are number of observations coded 0 and 1 respectively;
+    :math:`N` is the total number of observations and :math:`s_{y}` is the
+    standard deviation of all the metric observations.
+
+    A value of :math:`r_{pb}` that is significantly different from zero is
+    completely equivalent to a significant difference in means between the two
+    groups. Thus, an independent groups t Test with :math:`N-2` degrees of
+    freedom may be used to test whether :math:`r_{pb}` is nonzero. The
+    relation between the t-statistic for comparing two independent groups and
+    :math:`r_{pb}` is given by:
+
+    .. math::
+
+        t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}}
+
+    References
+    ----------
+    .. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math.
+           Statist., Vol. 20, no.1, pp. 125-126, 1949.
+
+    .. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous
+           Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25,
+           np. 3, pp. 603-607, 1954.
+
+    .. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef:
+           Statistics Reference Online (eds N. Balakrishnan, et al.), 2014.
+           :doi:`10.1002/9781118445112.stat06227`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> a = np.array([0, 0, 0, 1, 1, 1, 1])
+    >>> b = np.arange(7)
+    >>> stats.pointbiserialr(a, b)
+    (0.8660254037844386, 0.011724811003954652)
+    >>> stats.pearsonr(a, b)
+    (0.86602540378443871, 0.011724811003954626)
+    >>> np.corrcoef(a, b)
+    array([[ 1.       ,  0.8660254],
+           [ 0.8660254,  1.       ]])
+
+    """
+    rpb, prob = pearsonr(x, y)
+    # create result object with alias for backward compatibility
+    res = SignificanceResult(rpb, prob)
+    res.correlation = rpb
+    return res
+
+
+def kendalltau(x, y, *, nan_policy='propagate',
+               method='auto', variant='b', alternative='two-sided'):
+    r"""Calculate Kendall's tau, a correlation measure for ordinal data.
+
+    Kendall's tau is a measure of the correspondence between two rankings.
+    Values close to 1 indicate strong agreement, and values close to -1
+    indicate strong disagreement. This implements two variants of Kendall's
+    tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These
+    differ only in how they are normalized to lie within the range -1 to 1;
+    the hypothesis tests (their p-values) are identical. Kendall's original
+    tau-a is not implemented separately because both tau-b and tau-c reduce
+    to tau-a in the absence of ties.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Arrays of rankings, of the same shape. If arrays are not 1-D, they
+        will be flattened to 1-D.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+        * 'propagate': returns nan
+        * 'raise': throws an error
+        * 'omit': performs the calculations ignoring nan values
+
+    method : {'auto', 'asymptotic', 'exact'}, optional
+        Defines which method is used to calculate the p-value [5]_.
+        The following options are available (default is 'auto'):
+
+        * 'auto': selects the appropriate method based on a trade-off
+          between speed and accuracy
+        * 'asymptotic': uses a normal approximation valid for large samples
+        * 'exact': computes the exact p-value, but can only be used if no ties
+          are present. As the sample size increases, the 'exact' computation
+          time may grow and the result may lose some precision.
+
+    variant : {'b', 'c'}, optional
+        Defines which variant of Kendall's tau is returned. Default is 'b'.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the rank correlation is nonzero
+        * 'less': the rank correlation is negative (less than zero)
+        * 'greater': the rank correlation is positive (greater than zero)
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+           The tau statistic.
+        pvalue : float
+           The p-value for a hypothesis test whose null hypothesis is
+           an absence of association, tau = 0.
+
+    Raises
+    ------
+    ValueError
+        If `nan_policy` is 'omit' and `variant` is not 'b' or
+        if `method` is 'exact' and there are ties between `x` and `y`.
+
+    See Also
+    --------
+    spearmanr : Calculates a Spearman rank-order correlation coefficient.
+    theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
+    weightedtau : Computes a weighted version of Kendall's tau.
+    :ref:`hypothesis_kendalltau` : Extended example
+
+    Notes
+    -----
+    The definition of Kendall's tau that is used is [2]_::
+
+      tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U))
+
+      tau_c = 2 (P - Q) / (n**2 * (m - 1) / m)
+
+    where P is the number of concordant pairs, Q the number of discordant
+    pairs, T the number of ties only in `x`, and U the number of ties only in
+    `y`.  If a tie occurs for the same pair in both `x` and `y`, it is not
+    added to either T or U. n is the total number of samples, and m is the
+    number of unique values in either `x` or `y`, whichever is smaller.
+
+    References
+    ----------
+    .. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika
+           Vol. 30, No. 1/2, pp. 81-93, 1938.
+    .. [2] Maurice G. Kendall, "The treatment of ties in ranking problems",
+           Biometrika Vol. 33, No. 3, pp. 239-251. 1945.
+    .. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John
+           Wiley & Sons, 1967.
+    .. [4] Peter M. Fenwick, "A new data structure for cumulative frequency
+           tables", Software: Practice and Experience, Vol. 24, No. 3,
+           pp. 327-336, 1994.
+    .. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
+           Charles Griffin & Co., 1970.
+
+    Examples
+    --------
+
+    >>> from scipy import stats
+    >>> x1 = [12, 2, 1, 12, 2]
+    >>> x2 = [1, 4, 7, 1, 0]
+    >>> res = stats.kendalltau(x1, x2)
+    >>> res.statistic
+    -0.47140452079103173
+    >>> res.pvalue
+    0.2827454599327748
+
+    For a more detailed example, see :ref:`hypothesis_kendalltau`.
+    """
+    x = np.asarray(x).ravel()
+    y = np.asarray(y).ravel()
+
+    if x.size != y.size:
+        raise ValueError("All inputs to `kendalltau` must be of the same "
+                         f"size, found x-size {x.size} and y-size {y.size}")
+    elif not x.size or not y.size:
+        # Return NaN if arrays are empty
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    # check both x and y
+    cnx, npx = _contains_nan(x, nan_policy)
+    cny, npy = _contains_nan(y, nan_policy)
+    contains_nan = cnx or cny
+    if npx == 'omit' or npy == 'omit':
+        nan_policy = 'omit'
+
+    if contains_nan and nan_policy == 'propagate':
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    elif contains_nan and nan_policy == 'omit':
+        x = ma.masked_invalid(x)
+        y = ma.masked_invalid(y)
+        if variant == 'b':
+            return mstats_basic.kendalltau(x, y, method=method, use_ties=True,
+                                           alternative=alternative)
+        else:
+            message = ("nan_policy='omit' is currently compatible only with "
+                       "variant='b'.")
+            raise ValueError(message)
+
+    def count_rank_tie(ranks):
+        cnt = np.bincount(ranks).astype('int64', copy=False)
+        cnt = cnt[cnt > 1]
+        # Python ints to avoid overflow down the line
+        return (int((cnt * (cnt - 1) // 2).sum()),
+                int((cnt * (cnt - 1.) * (cnt - 2)).sum()),
+                int((cnt * (cnt - 1.) * (2*cnt + 5)).sum()))
+
+    size = x.size
+    perm = np.argsort(y)  # sort on y and convert y to dense ranks
+    x, y = x[perm], y[perm]
+    y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp)
+
+    # stable sort on x and convert x to dense ranks
+    perm = np.argsort(x, kind='mergesort')
+    x, y = x[perm], y[perm]
+    x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp)
+
+    dis = _kendall_dis(x, y)  # discordant pairs
+
+    obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True]
+    cnt = np.diff(np.nonzero(obs)[0]).astype('int64', copy=False)
+
+    ntie = int((cnt * (cnt - 1) // 2).sum())  # joint ties
+    xtie, x0, x1 = count_rank_tie(x)     # ties in x, stats
+    ytie, y0, y1 = count_rank_tie(y)     # ties in y, stats
+
+    tot = (size * (size - 1)) // 2
+
+    if xtie == tot or ytie == tot:
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    # Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie
+    #               = con + dis + xtie + ytie - ntie
+    con_minus_dis = tot - xtie - ytie + ntie - 2 * dis
+    if variant == 'b':
+        tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie)
+    elif variant == 'c':
+        minclasses = min(len(set(x)), len(set(y)))
+        tau = 2*con_minus_dis / (size**2 * (minclasses-1)/minclasses)
+    else:
+        raise ValueError(f"Unknown variant of the method chosen: {variant}. "
+                         "variant must be 'b' or 'c'.")
+
+    # Limit range to fix computational errors
+    tau = np.minimum(1., max(-1., tau))
+
+    # The p-value calculation is the same for all variants since the p-value
+    # depends only on con_minus_dis.
+    if method == 'exact' and (xtie != 0 or ytie != 0):
+        raise ValueError("Ties found, exact method cannot be used.")
+
+    if method == 'auto':
+        if (xtie == 0 and ytie == 0) and (size <= 33 or
+                                          min(dis, tot-dis) <= 1):
+            method = 'exact'
+        else:
+            method = 'asymptotic'
+
+    if xtie == 0 and ytie == 0 and method == 'exact':
+        pvalue = mstats_basic._kendall_p_exact(size, tot-dis, alternative)
+    elif method == 'asymptotic':
+        # con_minus_dis is approx normally distributed with this variance [3]_
+        m = size * (size - 1.)
+        var = ((m * (2*size + 5) - x1 - y1) / 18 +
+               (2 * xtie * ytie) / m + x0 * y0 / (9 * m * (size - 2)))
+        z = con_minus_dis / np.sqrt(var)
+        pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+    else:
+        raise ValueError(f"Unknown method {method} specified.  Use 'auto', "
+                         "'exact' or 'asymptotic'.")
+
+    # create result object with alias for backward compatibility
+    res = SignificanceResult(tau[()], pvalue[()])
+    res.correlation = tau[()]
+    return res
+
+
+def weightedtau(x, y, rank=True, weigher=None, additive=True):
+    r"""Compute a weighted version of Kendall's :math:`\tau`.
+
+    The weighted :math:`\tau` is a weighted version of Kendall's
+    :math:`\tau` in which exchanges of high weight are more influential than
+    exchanges of low weight. The default parameters compute the additive
+    hyperbolic version of the index, :math:`\tau_\mathrm h`, which has
+    been shown to provide the best balance between important and
+    unimportant elements [1]_.
+
+    The weighting is defined by means of a rank array, which assigns a
+    nonnegative rank to each element (higher importance ranks being
+    associated with smaller values, e.g., 0 is the highest possible rank),
+    and a weigher function, which assigns a weight based on the rank to
+    each element. The weight of an exchange is then the sum or the product
+    of the weights of the ranks of the exchanged elements. The default
+    parameters compute :math:`\tau_\mathrm h`: an exchange between
+    elements with rank :math:`r` and :math:`s` (starting from zero) has
+    weight :math:`1/(r+1) + 1/(s+1)`.
+
+    Specifying a rank array is meaningful only if you have in mind an
+    external criterion of importance. If, as it usually happens, you do
+    not have in mind a specific rank, the weighted :math:`\tau` is
+    defined by averaging the values obtained using the decreasing
+    lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the
+    behavior with default parameters. Note that the convention used
+    here for ranking (lower values imply higher importance) is opposite
+    to that used by other SciPy statistical functions.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Arrays of scores, of the same shape. If arrays are not 1-D, they will
+        be flattened to 1-D.
+    rank : array_like of ints or bool, optional
+        A nonnegative rank assigned to each element. If it is None, the
+        decreasing lexicographical rank by (`x`, `y`) will be used: elements of
+        higher rank will be those with larger `x`-values, using `y`-values to
+        break ties (in particular, swapping `x` and `y` will give a different
+        result). If it is False, the element indices will be used
+        directly as ranks. The default is True, in which case this
+        function returns the average of the values obtained using the
+        decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`).
+    weigher : callable, optional
+        The weigher function. Must map nonnegative integers (zero
+        representing the most important element) to a nonnegative weight.
+        The default, None, provides hyperbolic weighing, that is,
+        rank :math:`r` is mapped to weight :math:`1/(r+1)`.
+    additive : bool, optional
+        If True, the weight of an exchange is computed by adding the
+        weights of the ranks of the exchanged elements; otherwise, the weights
+        are multiplied. The default is True.
+
+    Returns
+    -------
+    res: SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+           The weighted :math:`\tau` correlation index.
+        pvalue : float
+           Presently ``np.nan``, as the null distribution of the statistic is
+           unknown (even in the additive hyperbolic case).
+
+    See Also
+    --------
+    kendalltau : Calculates Kendall's tau.
+    spearmanr : Calculates a Spearman rank-order correlation coefficient.
+    theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
+
+    Notes
+    -----
+    This function uses an :math:`O(n \log n)`, mergesort-based algorithm
+    [1]_ that is a weighted extension of Knight's algorithm for Kendall's
+    :math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_
+    between rankings without ties (i.e., permutations) by setting
+    `additive` and `rank` to False, as the definition given in [1]_ is a
+    generalization of Shieh's.
+
+    NaNs are considered the smallest possible score.
+
+    .. versionadded:: 0.19.0
+
+    References
+    ----------
+    .. [1] Sebastiano Vigna, "A weighted correlation index for rankings with
+           ties", Proceedings of the 24th international conference on World
+           Wide Web, pp. 1166-1176, ACM, 2015.
+    .. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with
+           Ungrouped Data", Journal of the American Statistical Association,
+           Vol. 61, No. 314, Part 1, pp. 436-439, 1966.
+    .. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics &
+           Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> x = [12, 2, 1, 12, 2]
+    >>> y = [1, 4, 7, 1, 0]
+    >>> res = stats.weightedtau(x, y)
+    >>> res.statistic
+    -0.56694968153682723
+    >>> res.pvalue
+    nan
+    >>> res = stats.weightedtau(x, y, additive=False)
+    >>> res.statistic
+    -0.62205716951801038
+
+    NaNs are considered the smallest possible score:
+
+    >>> x = [12, 2, 1, 12, 2]
+    >>> y = [1, 4, 7, 1, np.nan]
+    >>> res = stats.weightedtau(x, y)
+    >>> res.statistic
+    -0.56694968153682723
+
+    This is exactly Kendall's tau:
+
+    >>> x = [12, 2, 1, 12, 2]
+    >>> y = [1, 4, 7, 1, 0]
+    >>> res = stats.weightedtau(x, y, weigher=lambda x: 1)
+    >>> res.statistic
+    -0.47140452079103173
+
+    >>> x = [12, 2, 1, 12, 2]
+    >>> y = [1, 4, 7, 1, 0]
+    >>> stats.weightedtau(x, y, rank=None)
+    SignificanceResult(statistic=-0.4157652301037516, pvalue=nan)
+    >>> stats.weightedtau(y, x, rank=None)
+    SignificanceResult(statistic=-0.7181341329699028, pvalue=nan)
+
+    """
+    x = np.asarray(x).ravel()
+    y = np.asarray(y).ravel()
+
+    if x.size != y.size:
+        raise ValueError("All inputs to `weightedtau` must be "
+                         "of the same size, "
+                         f"found x-size {x.size} and y-size {y.size}")
+    if not x.size:
+        # Return NaN if arrays are empty
+        res = SignificanceResult(np.nan, np.nan)
+        res.correlation = np.nan
+        return res
+
+    # If there are NaNs we apply _toint64()
+    if np.isnan(np.sum(x)):
+        x = _toint64(x)
+    if np.isnan(np.sum(y)):
+        y = _toint64(y)
+
+    # Reduce to ranks unsupported types
+    if x.dtype != y.dtype:
+        if x.dtype != np.int64:
+            x = _toint64(x)
+        if y.dtype != np.int64:
+            y = _toint64(y)
+    else:
+        if x.dtype not in (np.int32, np.int64, np.float32, np.float64):
+            x = _toint64(x)
+            y = _toint64(y)
+
+    if rank is True:
+        tau = (
+            _weightedrankedtau(x, y, None, weigher, additive) +
+            _weightedrankedtau(y, x, None, weigher, additive)
+        ) / 2
+        res = SignificanceResult(tau, np.nan)
+        res.correlation = tau
+        return res
+
+    if rank is False:
+        rank = np.arange(x.size, dtype=np.intp)
+    elif rank is not None:
+        rank = np.asarray(rank).ravel()
+        if rank.size != x.size:
+            raise ValueError(
+                "All inputs to `weightedtau` must be of the same size, "
+                f"found x-size {x.size} and rank-size {rank.size}"
+            )
+
+    tau = _weightedrankedtau(x, y, rank, weigher, additive)
+    res = SignificanceResult(tau, np.nan)
+    res.correlation = tau
+    return res
+
+
+#####################################
+#       INFERENTIAL STATISTICS      #
+#####################################
+
+TtestResultBase = _make_tuple_bunch('TtestResultBase',
+                                    ['statistic', 'pvalue'], ['df'])
+
+
+class TtestResult(TtestResultBase):
+    """
+    Result of a t-test.
+
+    See the documentation of the particular t-test function for more
+    information about the definition of the statistic and meaning of
+    the confidence interval.
+
+    Attributes
+    ----------
+    statistic : float or array
+        The t-statistic of the sample.
+    pvalue : float or array
+        The p-value associated with the given alternative.
+    df : float or array
+        The number of degrees of freedom used in calculation of the
+        t-statistic; this is one less than the size of the sample
+        (``a.shape[axis]-1`` if there are no masked elements or omitted NaNs).
+
+    Methods
+    -------
+    confidence_interval
+        Computes a confidence interval around the population statistic
+        for the given confidence level.
+        The confidence interval is returned in a ``namedtuple`` with
+        fields `low` and `high`.
+
+    """
+
+    def __init__(self, statistic, pvalue, df,  # public
+                 alternative, standard_error, estimate,  # private
+                 statistic_np=None, xp=None):  # private
+        super().__init__(statistic, pvalue, df=df)
+        self._alternative = alternative
+        self._standard_error = standard_error  # denominator of t-statistic
+        self._estimate = estimate  # point estimate of sample mean
+        self._statistic_np = statistic if statistic_np is None else statistic_np
+        self._dtype = statistic.dtype
+        self._xp = array_namespace(statistic, pvalue) if xp is None else xp
+
+
+    def confidence_interval(self, confidence_level=0.95):
+        """
+        Parameters
+        ----------
+        confidence_level : float
+            The confidence level for the calculation of the population mean
+            confidence interval. Default is 0.95.
+
+        Returns
+        -------
+        ci : namedtuple
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.
+
+        """
+        low, high = _t_confidence_interval(self.df, self._statistic_np,
+                                           confidence_level, self._alternative,
+                                           self._dtype, self._xp)
+        low = low * self._standard_error + self._estimate
+        high = high * self._standard_error + self._estimate
+        return ConfidenceInterval(low=low, high=high)
+
+
+def pack_TtestResult(statistic, pvalue, df, alternative, standard_error,
+                     estimate):
+    # this could be any number of dimensions (including 0d), but there is
+    # at most one unique non-NaN value
+    alternative = np.atleast_1d(alternative)  # can't index 0D object
+    alternative = alternative[np.isfinite(alternative)]
+    alternative = alternative[0] if alternative.size else np.nan
+    return TtestResult(statistic, pvalue, df=df, alternative=alternative,
+                       standard_error=standard_error, estimate=estimate)
+
+
+def unpack_TtestResult(res):
+    return (res.statistic, res.pvalue, res.df, res._alternative,
+            res._standard_error, res._estimate)
+
+
+@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
+                          result_to_tuple=unpack_TtestResult, n_outputs=6)
+# nan_policy handled by `_axis_nan_policy`, but needs to be left
+# in signature to preserve use as a positional argument
+def ttest_1samp(a, popmean, axis=0, nan_policy="propagate", alternative="two-sided"):
+    """Calculate the T-test for the mean of ONE group of scores.
+
+    This is a test for the null hypothesis that the expected value
+    (mean) of a sample of independent observations `a` is equal to the given
+    population mean, `popmean`.
+
+    Parameters
+    ----------
+    a : array_like
+        Sample observations.
+    popmean : float or array_like
+        Expected value in null hypothesis. If array_like, then its length along
+        `axis` must equal 1, and it must otherwise be broadcastable with `a`.
+    axis : int or None, optional
+        Axis along which to compute test; default is 0. If None, compute over
+        the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the mean of the underlying distribution of the sample
+          is different than the given population mean (`popmean`)
+        * 'less': the mean of the underlying distribution of the sample is
+          less than the given population mean (`popmean`)
+        * 'greater': the mean of the underlying distribution of the sample is
+          greater than the given population mean (`popmean`)
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.TtestResult`
+        An object with the following attributes:
+
+        statistic : float or array
+            The t-statistic.
+        pvalue : float or array
+            The p-value associated with the given alternative.
+        df : float or array
+            The number of degrees of freedom used in calculation of the
+            t-statistic; this is one less than the size of the sample
+            (``a.shape[axis]``).
+
+            .. versionadded:: 1.10.0
+
+        The object also has the following method:
+
+        confidence_interval(confidence_level=0.95)
+            Computes a confidence interval around the population
+            mean for the given confidence level.
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.
+
+            .. versionadded:: 1.10.0
+
+    Notes
+    -----
+    The statistic is calculated as ``(np.mean(a) - popmean)/se``, where
+    ``se`` is the standard error. Therefore, the statistic will be positive
+    when the sample mean is greater than the population mean and negative when
+    the sample mean is less than the population mean.
+
+    Examples
+    --------
+    Suppose we wish to test the null hypothesis that the mean of a population
+    is equal to 0.5. We choose a confidence level of 99%; that is, we will
+    reject the null hypothesis in favor of the alternative if the p-value is
+    less than 0.01.
+
+    When testing random variates from the standard uniform distribution, which
+    has a mean of 0.5, we expect the data to be consistent with the null
+    hypothesis most of the time.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> rvs = stats.uniform.rvs(size=50, random_state=rng)
+    >>> stats.ttest_1samp(rvs, popmean=0.5)
+    TtestResult(statistic=2.456308468440, pvalue=0.017628209047638, df=49)
+
+    As expected, the p-value of 0.017 is not below our threshold of 0.01, so
+    we cannot reject the null hypothesis.
+
+    When testing data from the standard *normal* distribution, which has a mean
+    of 0, we would expect the null hypothesis to be rejected.
+
+    >>> rvs = stats.norm.rvs(size=50, random_state=rng)
+    >>> stats.ttest_1samp(rvs, popmean=0.5)
+    TtestResult(statistic=-7.433605518875, pvalue=1.416760157221e-09, df=49)
+
+    Indeed, the p-value is lower than our threshold of 0.01, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the mean
+    of the population is *not* equal to 0.5.
+
+    However, suppose we were to test the null hypothesis against the
+    one-sided alternative that the mean of the population is *greater* than
+    0.5. Since the mean of the standard normal is less than 0.5, we would not
+    expect the null hypothesis to be rejected.
+
+    >>> stats.ttest_1samp(rvs, popmean=0.5, alternative='greater')
+    TtestResult(statistic=-7.433605518875, pvalue=0.99999999929, df=49)
+
+    Unsurprisingly, with a p-value greater than our threshold, we would not
+    reject the null hypothesis.
+
+    Note that when working with a confidence level of 99%, a true null
+    hypothesis will be rejected approximately 1% of the time.
+
+    >>> rvs = stats.uniform.rvs(size=(100, 50), random_state=rng)
+    >>> res = stats.ttest_1samp(rvs, popmean=0.5, axis=1)
+    >>> np.sum(res.pvalue < 0.01)
+    1
+
+    Indeed, even though all 100 samples above were drawn from the standard
+    uniform distribution, which *does* have a population mean of 0.5, we would
+    mistakenly reject the null hypothesis for one of them.
+
+    `ttest_1samp` can also compute a confidence interval around the population
+    mean.
+
+    >>> rvs = stats.norm.rvs(size=50, random_state=rng)
+    >>> res = stats.ttest_1samp(rvs, popmean=0)
+    >>> ci = res.confidence_interval(confidence_level=0.95)
+    >>> ci
+    ConfidenceInterval(low=-0.3193887540880017, high=0.2898583388980972)
+
+    The bounds of the 95% confidence interval are the
+    minimum and maximum values of the parameter `popmean` for which the
+    p-value of the test would be 0.05.
+
+    >>> res = stats.ttest_1samp(rvs, popmean=ci.low)
+    >>> np.testing.assert_allclose(res.pvalue, 0.05)
+    >>> res = stats.ttest_1samp(rvs, popmean=ci.high)
+    >>> np.testing.assert_allclose(res.pvalue, 0.05)
+
+    Under certain assumptions about the population from which a sample
+    is drawn, the confidence interval with confidence level 95% is expected
+    to contain the true population mean in 95% of sample replications.
+
+    >>> rvs = stats.norm.rvs(size=(50, 1000), loc=1, random_state=rng)
+    >>> res = stats.ttest_1samp(rvs, popmean=0)
+    >>> ci = res.confidence_interval()
+    >>> contains_pop_mean = (ci.low < 1) & (ci.high > 1)
+    >>> contains_pop_mean.sum()
+    953
+
+    """
+    xp = array_namespace(a)
+    a, axis = _chk_asarray(a, axis, xp=xp)
+
+    n = a.shape[axis]
+    df = n - 1
+
+    if n == 0:
+        # This is really only needed for *testing* _axis_nan_policy decorator
+        # It won't happen when the decorator is used.
+        NaN = _get_nan(a)
+        return TtestResult(NaN, NaN, df=NaN, alternative=NaN,
+                           standard_error=NaN, estimate=NaN)
+
+    mean = xp.mean(a, axis=axis)
+    try:
+        popmean = xp.asarray(popmean)
+        popmean = xp.squeeze(popmean, axis=axis) if popmean.ndim > 0 else popmean
+    except ValueError as e:
+        raise ValueError("`popmean.shape[axis]` must equal 1.") from e
+    d = mean - popmean
+    v = _var(a, axis=axis, ddof=1)
+    denom = xp.sqrt(v / n)
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = xp.divide(d, denom)
+        t = t[()] if t.ndim == 0 else t
+
+    dist = _SimpleStudentT(xp.asarray(df, dtype=t.dtype))
+    prob = _get_pvalue(t, dist, alternative, xp=xp)
+    prob = prob[()] if prob.ndim == 0 else prob
+
+    # when nan_policy='omit', `df` can be different for different axis-slices
+    df = xp.broadcast_to(xp.asarray(df), t.shape)
+    df = df[()] if df.ndim == 0 else df
+    # _axis_nan_policy decorator doesn't play well with strings
+    alternative_num = {"less": -1, "two-sided": 0, "greater": 1}[alternative]
+    return TtestResult(t, prob, df=df, alternative=alternative_num,
+                       standard_error=denom, estimate=mean,
+                       statistic_np=xp.asarray(t), xp=xp)
+
+
+def _t_confidence_interval(df, t, confidence_level, alternative, dtype=None, xp=None):
+    # Input validation on `alternative` is already done
+    # We just need IV on confidence_level
+    dtype = t.dtype if dtype is None else dtype
+    xp = array_namespace(t) if xp is None else xp
+
+    # stdtrit not dispatched yet; use NumPy
+    df, t = np.asarray(df), np.asarray(t)
+
+    if confidence_level < 0 or confidence_level > 1:
+        message = "`confidence_level` must be a number between 0 and 1."
+        raise ValueError(message)
+
+    if alternative < 0:  # 'less'
+        p = confidence_level
+        low, high = np.broadcast_arrays(-np.inf, special.stdtrit(df, p))
+    elif alternative > 0:  # 'greater'
+        p = 1 - confidence_level
+        low, high = np.broadcast_arrays(special.stdtrit(df, p), np.inf)
+    elif alternative == 0:  # 'two-sided'
+        tail_probability = (1 - confidence_level)/2
+        p = tail_probability, 1-tail_probability
+        # axis of p must be the zeroth and orthogonal to all the rest
+        p = np.reshape(p, [2] + [1]*np.asarray(df).ndim)
+        low, high = special.stdtrit(df, p)
+    else:  # alternative is NaN when input is empty (see _axis_nan_policy)
+        p, nans = np.broadcast_arrays(t, np.nan)
+        low, high = nans, nans
+
+    low = xp.asarray(low, dtype=dtype)
+    low = low[()] if low.ndim == 0 else low
+    high = xp.asarray(high, dtype=dtype)
+    high = high[()] if high.ndim == 0 else high
+    return low, high
+
+
+def _ttest_ind_from_stats(mean1, mean2, denom, df, alternative, xp=None):
+    xp = array_namespace(mean1, mean2, denom) if xp is None else xp
+
+    d = mean1 - mean2
+    with np.errstate(divide='ignore', invalid='ignore'):
+        t = xp.divide(d, denom)
+
+    t_np = np.asarray(t)
+    df_np = np.asarray(df)
+    prob = _get_pvalue(t_np, distributions.t(df_np), alternative, xp=np)
+    prob = xp.asarray(prob, dtype=t.dtype)
+
+    t = t[()] if t.ndim == 0 else t
+    prob = prob[()] if prob.ndim == 0 else prob
+    return t, prob
+
+
+def _unequal_var_ttest_denom(v1, n1, v2, n2, xp=None):
+    xp = array_namespace(v1, v2) if xp is None else xp
+    vn1 = v1 / n1
+    vn2 = v2 / n2
+    with np.errstate(divide='ignore', invalid='ignore'):
+        df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1))
+
+    # If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).
+    # Hence it doesn't matter what df is as long as it's not NaN.
+    df = xp.where(xp.isnan(df), xp.asarray(1.), df)
+    denom = xp.sqrt(vn1 + vn2)
+    return df, denom
+
+
+def _equal_var_ttest_denom(v1, n1, v2, n2, xp=None):
+    xp = array_namespace(v1, v2) if xp is None else xp
+
+    # If there is a single observation in one sample, this formula for pooled
+    # variance breaks down because the variance of that sample is undefined.
+    # The pooled variance is still defined, though, because the (n-1) in the
+    # numerator should cancel with the (n-1) in the denominator, leaving only
+    # the sum of squared differences from the mean: zero.
+    zero = xp.asarray(0.)
+    v1 = xp.where(xp.asarray(n1 == 1), zero, v1)
+    v2 = xp.where(xp.asarray(n2 == 1), zero, v2)
+
+    df = n1 + n2 - 2.0
+    svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df
+    denom = xp.sqrt(svar * (1.0 / n1 + 1.0 / n2))
+    return df, denom
+
+
+Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue'))
+
+
+def ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2,
+                         equal_var=True, alternative="two-sided"):
+    r"""
+    T-test for means of two independent samples from descriptive statistics.
+
+    This is a test for the null hypothesis that two independent
+    samples have identical average (expected) values.
+
+    Parameters
+    ----------
+    mean1 : array_like
+        The mean(s) of sample 1.
+    std1 : array_like
+        The corrected sample standard deviation of sample 1 (i.e. ``ddof=1``).
+    nobs1 : array_like
+        The number(s) of observations of sample 1.
+    mean2 : array_like
+        The mean(s) of sample 2.
+    std2 : array_like
+        The corrected sample standard deviation of sample 2 (i.e. ``ddof=1``).
+    nobs2 : array_like
+        The number(s) of observations of sample 2.
+    equal_var : bool, optional
+        If True (default), perform a standard independent 2 sample test
+        that assumes equal population variances [1]_.
+        If False, perform Welch's t-test, which does not assume equal
+        population variance [2]_.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions are unequal.
+        * 'less': the mean of the first distribution is less than the
+          mean of the second distribution.
+        * 'greater': the mean of the first distribution is greater than the
+          mean of the second distribution.
+
+        .. versionadded:: 1.6.0
+
+    Returns
+    -------
+    statistic : float or array
+        The calculated t-statistics.
+    pvalue : float or array
+        The two-tailed p-value.
+
+    See Also
+    --------
+    scipy.stats.ttest_ind
+
+    Notes
+    -----
+    The statistic is calculated as ``(mean1 - mean2)/se``, where ``se`` is the
+    standard error. Therefore, the statistic will be positive when `mean1` is
+    greater than `mean2` and negative when `mean1` is less than `mean2`.
+
+    This method does not check whether any of the elements of `std1` or `std2`
+    are negative. If any elements of the `std1` or `std2` parameters are
+    negative in a call to this method, this method will return the same result
+    as if it were passed ``numpy.abs(std1)`` and ``numpy.abs(std2)``,
+    respectively, instead; no exceptions or warnings will be emitted.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
+
+    .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
+
+    Examples
+    --------
+    Suppose we have the summary data for two samples, as follows (with the
+    Sample Variance being the corrected sample variance)::
+
+                         Sample   Sample
+                   Size   Mean   Variance
+        Sample 1    13    15.0     87.5
+        Sample 2    11    12.0     39.0
+
+    Apply the t-test to this data (with the assumption that the population
+    variances are equal):
+
+    >>> import numpy as np
+    >>> from scipy.stats import ttest_ind_from_stats
+    >>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13,
+    ...                      mean2=12.0, std2=np.sqrt(39.0), nobs2=11)
+    Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487)
+
+    For comparison, here is the data from which those summary statistics
+    were taken.  With this data, we can compute the same result using
+    `scipy.stats.ttest_ind`:
+
+    >>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26])
+    >>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21])
+    >>> from scipy.stats import ttest_ind
+    >>> ttest_ind(a, b)
+    TtestResult(statistic=0.905135809331027,
+                pvalue=0.3751996797581486,
+                df=22.0)
+
+    Suppose we instead have binary data and would like to apply a t-test to
+    compare the proportion of 1s in two independent groups::
+
+                          Number of    Sample     Sample
+                    Size    ones        Mean     Variance
+        Sample 1    150      30         0.2        0.161073
+        Sample 2    200      45         0.225      0.175251
+
+    The sample mean :math:`\hat{p}` is the proportion of ones in the sample
+    and the variance for a binary observation is estimated by
+    :math:`\hat{p}(1-\hat{p})`.
+
+    >>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.161073), nobs1=150,
+    ...                      mean2=0.225, std2=np.sqrt(0.175251), nobs2=200)
+    Ttest_indResult(statistic=-0.5627187905196761, pvalue=0.5739887114209541)
+
+    For comparison, we could compute the t statistic and p-value using
+    arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above.
+
+    >>> group1 = np.array([1]*30 + [0]*(150-30))
+    >>> group2 = np.array([1]*45 + [0]*(200-45))
+    >>> ttest_ind(group1, group2)
+    TtestResult(statistic=-0.5627179589855622,
+                pvalue=0.573989277115258,
+                df=348.0)
+
+    """
+    xp = array_namespace(mean1, std1, mean2, std2)
+
+    mean1 = xp.asarray(mean1)
+    std1 = xp.asarray(std1)
+    mean2 = xp.asarray(mean2)
+    std2 = xp.asarray(std2)
+
+    if equal_var:
+        df, denom = _equal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp)
+    else:
+        df, denom = _unequal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2, xp=xp)
+
+    res = _ttest_ind_from_stats(mean1, mean2, denom, df, alternative)
+    return Ttest_indResult(*res)
+
+
+_ttest_ind_dep_msg = "Use ``method`` to perform a permutation test."
+@_deprecate_positional_args(version='1.17.0',
+                            deprecated_args={'permutations', 'random_state'},
+                            custom_message=_ttest_ind_dep_msg)
+@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
+                          result_to_tuple=unpack_TtestResult, n_outputs=6)
+def ttest_ind(a, b, *, axis=0, equal_var=True, nan_policy='propagate',
+              permutations=None, random_state=None, alternative="two-sided",
+              trim=0, method=None):
+    """
+    Calculate the T-test for the means of *two independent* samples of scores.
+
+    This is a test for the null hypothesis that 2 independent samples
+    have identical average (expected) values. This test assumes that the
+    populations have identical variances by default.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must have the same shape, except in the dimension
+        corresponding to `axis` (the first, by default).
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        arrays, `a`, and `b`.
+    equal_var : bool, optional
+        If True (default), perform a standard independent 2 sample test
+        that assumes equal population variances [1]_.
+        If False, perform Welch's t-test, which does not assume equal
+        population variance [2]_.
+
+        .. versionadded:: 0.11.0
+
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+        The 'omit' option is not currently available for permutation tests or
+        one-sided asymptotic tests.
+
+    permutations : non-negative int, np.inf, or None (default), optional
+        If 0 or None (default), use the t-distribution to calculate p-values.
+        Otherwise, `permutations` is  the number of random permutations that
+        will be used to estimate p-values using a permutation test. If
+        `permutations` equals or exceeds the number of distinct partitions of
+        the pooled data, an exact test is performed instead (i.e. each
+        distinct partition is used exactly once). See Notes for details.
+
+        .. deprecated:: 1.17.0
+            `permutations` is deprecated and will be removed in SciPy 1.7.0.
+            Use the `n_resamples` argument of `PermutationMethod`, instead,
+            and pass the instance as the `method` argument.
+
+    random_state : {None, int, `numpy.random.Generator`,
+            `numpy.random.RandomState`}, optional
+
+        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+        singleton is used.
+        If `seed` is an int, a new ``RandomState`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` or ``RandomState`` instance then
+        that instance is used.
+
+        Pseudorandom number generator state used to generate permutations
+        (used only when `permutations` is not None).
+
+        .. deprecated:: 1.17.0
+            `random_state` is deprecated and will be removed in SciPy 1.7.0.
+            Use the `rng` argument of `PermutationMethod`, instead,
+            and pass the instance as the `method` argument.
+
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          are unequal.
+        * 'less': the mean of the distribution underlying the first sample
+          is less than the mean of the distribution underlying the second
+          sample.
+        * 'greater': the mean of the distribution underlying the first
+          sample is greater than the mean of the distribution underlying
+          the second sample.
+
+    trim : float, optional
+        If nonzero, performs a trimmed (Yuen's) t-test.
+        Defines the fraction of elements to be trimmed from each end of the
+        input samples. If 0 (default), no elements will be trimmed from either
+        side. The number of trimmed elements from each tail is the floor of the
+        trim times the number of elements. Valid range is [0, .5).
+    method : ResamplingMethod, optional
+        Defines the method used to compute the p-value. If `method` is an
+        instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is
+        computed using
+        `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
+        provided configuration options and other appropriate settings.
+        Otherwise, the p-value is computed by comparing the test statistic
+        against a theoretical t-distribution.
+
+        .. versionadded:: 1.15.0
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.TtestResult`
+        An object with the following attributes:
+
+        statistic : float or ndarray
+            The t-statistic.
+        pvalue : float or ndarray
+            The p-value associated with the given alternative.
+        df : float or ndarray
+            The number of degrees of freedom used in calculation of the
+            t-statistic. This is always NaN for a permutation t-test.
+
+            .. versionadded:: 1.11.0
+
+        The object also has the following method:
+
+        confidence_interval(confidence_level=0.95)
+            Computes a confidence interval around the difference in
+            population means for the given confidence level.
+            The confidence interval is returned in a ``namedtuple`` with
+            fields ``low`` and ``high``.
+            When a permutation t-test is performed, the confidence interval
+            is not computed, and fields ``low`` and ``high`` contain NaN.
+
+            .. versionadded:: 1.11.0
+
+    Notes
+    -----
+    Suppose we observe two independent samples, e.g. flower petal lengths, and
+    we are considering whether the two samples were drawn from the same
+    population (e.g. the same species of flower or two species with similar
+    petal characteristics) or two different populations.
+
+    The t-test quantifies the difference between the arithmetic means
+    of the two samples. The p-value quantifies the probability of observing
+    as or more extreme values assuming the null hypothesis, that the
+    samples are drawn from populations with the same population means, is true.
+    A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that
+    our observation is not so unlikely to have occurred by chance. Therefore,
+    we do not reject the null hypothesis of equal population means.
+    If the p-value is smaller than our threshold, then we have evidence
+    against the null hypothesis of equal population means.
+
+    By default, the p-value is determined by comparing the t-statistic of the
+    observed data against a theoretical t-distribution.
+
+    (In the following, note that the argument `permutations` itself is
+    deprecated, but a nearly identical test may be performed by creating
+    an instance of `scipy.stats.PermutationMethod` with ``n_resamples=permutuations``
+    and passing it as the `method` argument.)
+    When ``1 < permutations < binom(n, k)``, where
+
+    * ``k`` is the number of observations in `a`,
+    * ``n`` is the total number of observations in `a` and `b`, and
+    * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``),
+
+    the data are pooled (concatenated), randomly assigned to either group `a`
+    or `b`, and the t-statistic is calculated. This process is performed
+    repeatedly (`permutation` times), generating a distribution of the
+    t-statistic under the null hypothesis, and the t-statistic of the observed
+    data is compared to this distribution to determine the p-value.
+    Specifically, the p-value reported is the "achieved significance level"
+    (ASL) as defined in 4.4 of [3]_. Note that there are other ways of
+    estimating p-values using randomized permutation tests; for other
+    options, see the more general `permutation_test`.
+
+    When ``permutations >= binom(n, k)``, an exact test is performed: the data
+    are partitioned between the groups in each distinct way exactly once.
+
+    The permutation test can be computationally expensive and not necessarily
+    more accurate than the analytical test, but it does not make strong
+    assumptions about the shape of the underlying distribution.
+
+    Use of trimming is commonly referred to as the trimmed t-test. At times
+    called Yuen's t-test, this is an extension of Welch's t-test, with the
+    difference being the use of winsorized means in calculation of the variance
+    and the trimmed sample size in calculation of the statistic. Trimming is
+    recommended if the underlying distribution is long-tailed or contaminated
+    with outliers [4]_.
+
+    The statistic is calculated as ``(np.mean(a) - np.mean(b))/se``, where
+    ``se`` is the standard error. Therefore, the statistic will be positive
+    when the sample mean of `a` is greater than the sample mean of `b` and
+    negative when the sample mean of `a` is less than the sample mean of
+    `b`.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
+
+    .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
+
+    .. [3] B. Efron and T. Hastie. Computer Age Statistical Inference. (2016).
+
+    .. [4] Yuen, Karen K. "The Two-Sample Trimmed t for Unequal Population
+           Variances." Biometrika, vol. 61, no. 1, 1974, pp. 165-170. JSTOR,
+           www.jstor.org/stable/2334299. Accessed 30 Mar. 2021.
+
+    .. [5] Yuen, Karen K., and W. J. Dixon. "The Approximate Behaviour and
+           Performance of the Two-Sample Trimmed t." Biometrika, vol. 60,
+           no. 2, 1973, pp. 369-374. JSTOR, www.jstor.org/stable/2334550.
+           Accessed 30 Mar. 2021.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+
+    Test with sample with identical means:
+
+    >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
+    >>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
+    >>> stats.ttest_ind(rvs1, rvs2)
+    TtestResult(statistic=-0.4390847099199348,
+                pvalue=0.6606952038870015,
+                df=998.0)
+    >>> stats.ttest_ind(rvs1, rvs2, equal_var=False)
+    TtestResult(statistic=-0.4390847099199348,
+                pvalue=0.6606952553131064,
+                df=997.4602304121448)
+
+    `ttest_ind` underestimates p for unequal variances:
+
+    >>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500, random_state=rng)
+    >>> stats.ttest_ind(rvs1, rvs3)
+    TtestResult(statistic=-1.6370984482905417,
+                pvalue=0.1019251574705033,
+                df=998.0)
+    >>> stats.ttest_ind(rvs1, rvs3, equal_var=False)
+    TtestResult(statistic=-1.637098448290542,
+                pvalue=0.10202110497954867,
+                df=765.1098655246868)
+
+    When ``n1 != n2``, the equal variance t-statistic is no longer equal to the
+    unequal variance t-statistic:
+
+    >>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100, random_state=rng)
+    >>> stats.ttest_ind(rvs1, rvs4)
+    TtestResult(statistic=-1.9481646859513422,
+                pvalue=0.05186270935842703,
+                df=598.0)
+    >>> stats.ttest_ind(rvs1, rvs4, equal_var=False)
+    TtestResult(statistic=-1.3146566100751664,
+                pvalue=0.1913495266513811,
+                df=110.41349083985212)
+
+    T-test with different means, variance, and n:
+
+    >>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100, random_state=rng)
+    >>> stats.ttest_ind(rvs1, rvs5)
+    TtestResult(statistic=-2.8415950600298774,
+                pvalue=0.0046418707568707885,
+                df=598.0)
+    >>> stats.ttest_ind(rvs1, rvs5, equal_var=False)
+    TtestResult(statistic=-1.8686598649188084,
+                pvalue=0.06434714193919686,
+                df=109.32167496550137)
+
+    Take these two samples, one of which has an extreme tail.
+
+    >>> a = (56, 128.6, 12, 123.8, 64.34, 78, 763.3)
+    >>> b = (1.1, 2.9, 4.2)
+
+    Use the `trim` keyword to perform a trimmed (Yuen) t-test. For example,
+    using 20% trimming, ``trim=.2``, the test will reduce the impact of one
+    (``np.floor(trim*len(a))``) element from each tail of sample `a`. It will
+    have no effect on sample `b` because ``np.floor(trim*len(b))`` is 0.
+
+    >>> stats.ttest_ind(a, b, trim=.2)
+    TtestResult(statistic=3.4463884028073513,
+                pvalue=0.01369338726499547,
+                df=6.0)
+    """
+    xp = array_namespace(a, b)
+
+    default_float = xp.asarray(1.).dtype
+    if xp.isdtype(a.dtype, 'integral'):
+        a = xp.astype(a, default_float)
+    if xp.isdtype(b.dtype, 'integral'):
+        b = xp.astype(b, default_float)
+
+    if not (0 <= trim < .5):
+        raise ValueError("Trimming percentage should be 0 <= `trim` < .5.")
+
+    if not isinstance(method, PermutationMethod | MonteCarloMethod | None):
+        message = ("`method` must be an instance of `PermutationMethod`, an instance "
+                   "of `MonteCarloMethod`, or None (default).")
+        raise ValueError(message)
+
+    if not is_numpy(xp) and method is not None:
+        message = "Use of resampling methods is compatible only with NumPy arrays."
+        raise NotImplementedError(message)
+
+    result_shape = _broadcast_array_shapes_remove_axis((a, b), axis=axis)
+    NaN = xp.full(result_shape, _get_nan(a, b, xp=xp))
+    NaN = NaN[()] if NaN.ndim == 0 else NaN
+    if xp_size(a) == 0 or xp_size(b) == 0:
+        return TtestResult(NaN, NaN, df=NaN, alternative=NaN,
+                           standard_error=NaN, estimate=NaN)
+
+    alternative_nums = {"less": -1, "two-sided": 0, "greater": 1}
+
+    # This probably should be deprecated and replaced with a `method` argument
+    if permutations is not None and permutations != 0:
+        message = "Use of `permutations` is compatible only with NumPy arrays."
+        if not is_numpy(xp):
+            raise NotImplementedError(message)
+
+        message = "Use of `permutations` is incompatible with with use of `trim`."
+        if trim != 0:
+            raise NotImplementedError(message)
+
+        t, prob = _permutation_ttest(a, b, permutations=permutations,
+                                     axis=axis, equal_var=equal_var,
+                                     nan_policy=nan_policy,
+                                     random_state=random_state,
+                                     alternative=alternative)
+        df, denom, estimate = NaN, NaN, NaN
+
+        # _axis_nan_policy decorator doesn't play well with strings
+        return TtestResult(t, prob, df=df, alternative=alternative_nums[alternative],
+                           standard_error=denom, estimate=estimate)
+
+    n1 = xp.asarray(a.shape[axis], dtype=a.dtype)
+    n2 = xp.asarray(b.shape[axis], dtype=b.dtype)
+
+    if trim == 0:
+        with np.errstate(divide='ignore', invalid='ignore'):
+            v1 = _var(a, axis, ddof=1, xp=xp)
+            v2 = _var(b, axis, ddof=1, xp=xp)
+
+        m1 = xp.mean(a, axis=axis)
+        m2 = xp.mean(b, axis=axis)
+    else:
+        message = "Use of `trim` is compatible only with NumPy arrays."
+        if not is_numpy(xp):
+            raise NotImplementedError(message)
+
+        v1, m1, n1 = _ttest_trim_var_mean_len(a, trim, axis)
+        v2, m2, n2 = _ttest_trim_var_mean_len(b, trim, axis)
+
+    if equal_var:
+        df, denom = _equal_var_ttest_denom(v1, n1, v2, n2, xp=xp)
+    else:
+        df, denom = _unequal_var_ttest_denom(v1, n1, v2, n2, xp=xp)
+
+    if method is None:
+        t, prob = _ttest_ind_from_stats(m1, m2, denom, df, alternative)
+    else:
+        # nan_policy is taken care of by axis_nan_policy decorator
+        ttest_kwargs = dict(equal_var=equal_var, trim=trim)
+        t, prob = _ttest_resampling(a, b, axis, alternative, ttest_kwargs, method)
+
+    # when nan_policy='omit', `df` can be different for different axis-slices
+    df = xp.broadcast_to(df, t.shape)
+    df = df[()] if df.ndim ==0 else df
+    estimate = m1 - m2
+
+    return TtestResult(t, prob, df=df, alternative=alternative_nums[alternative],
+                       standard_error=denom, estimate=estimate)
+
+
+def _ttest_resampling(x, y, axis, alternative, ttest_kwargs, method):
+    def statistic(x, y, axis):
+        return ttest_ind(x, y, axis=axis, **ttest_kwargs).statistic
+
+    test = (permutation_test if isinstance(method, PermutationMethod)
+            else monte_carlo_test)
+    method = method._asdict()
+
+    if test is monte_carlo_test:
+        # `monte_carlo_test` accepts an `rvs` tuple of callables, not an `rng`
+        # If the user specified an `rng`, replace it with the default callables
+        if (rng := method.pop('rng', None)) is not None:
+            rng = np.random.default_rng(rng)
+            method['rvs'] = rng.normal, rng.normal
+
+    res = test((x, y,), statistic=statistic, axis=axis,
+               alternative=alternative, **method)
+
+    return res.statistic, res.pvalue
+
+
+def _ttest_trim_var_mean_len(a, trim, axis):
+    """Variance, mean, and length of winsorized input along specified axis"""
+    # for use with `ttest_ind` when trimming.
+    # further calculations in this test assume that the inputs are sorted.
+    # From [4] Section 1 "Let x_1, ..., x_n be n ordered observations..."
+    a = np.sort(a, axis=axis)
+
+    # `g` is the number of elements to be replaced on each tail, converted
+    # from a percentage amount of trimming
+    n = a.shape[axis]
+    g = int(n * trim)
+
+    # Calculate the Winsorized variance of the input samples according to
+    # specified `g`
+    v = _calculate_winsorized_variance(a, g, axis)
+
+    # the total number of elements in the trimmed samples
+    n -= 2 * g
+
+    # calculate the g-times trimmed mean, as defined in [4] (1-1)
+    m = trim_mean(a, trim, axis=axis)
+    return v, m, n
+
+
+def _calculate_winsorized_variance(a, g, axis):
+    """Calculates g-times winsorized variance along specified axis"""
+    # it is expected that the input `a` is sorted along the correct axis
+    if g == 0:
+        return _var(a, ddof=1, axis=axis)
+    # move the intended axis to the end that way it is easier to manipulate
+    a_win = np.moveaxis(a, axis, -1)
+
+    # save where NaNs are for later use.
+    nans_indices = np.any(np.isnan(a_win), axis=-1)
+
+    # Winsorization and variance calculation are done in one step in [4]
+    # (1-3), but here winsorization is done first; replace the left and
+    # right sides with the repeating value. This can be see in effect in (
+    # 1-3) in [4], where the leftmost and rightmost tails are replaced with
+    # `(g + 1) * x_{g + 1}` on the left and `(g + 1) * x_{n - g}` on the
+    # right. Zero-indexing turns `g + 1` to `g`, and `n - g` to `- g - 1` in
+    # array indexing.
+    a_win[..., :g] = a_win[..., [g]]
+    a_win[..., -g:] = a_win[..., [-g - 1]]
+
+    # Determine the variance. In [4], the degrees of freedom is expressed as
+    # `h - 1`, where `h = n - 2g` (unnumbered equations in Section 1, end of
+    # page 369, beginning of page 370). This is converted to NumPy's format,
+    # `n - ddof` for use with `np.var`. The result is converted to an
+    # array to accommodate indexing later.
+    var_win = np.asarray(_var(a_win, ddof=(2 * g + 1), axis=-1))
+
+    # with `nan_policy='propagate'`, NaNs may be completely trimmed out
+    # because they were sorted into the tail of the array. In these cases,
+    # replace computed variances with `np.nan`.
+    var_win[nans_indices] = np.nan
+    return var_win
+
+
+def _permutation_distribution_t(data, permutations, size_a, equal_var,
+                                random_state=None):
+    """Generation permutation distribution of t statistic"""
+
+    random_state = check_random_state(random_state)
+
+    # prepare permutation indices
+    size = data.shape[-1]
+    # number of distinct combinations
+    n_max = special.comb(size, size_a)
+
+    if permutations < n_max:
+        perm_generator = (random_state.permutation(size)
+                          for i in range(permutations))
+    else:
+        permutations = n_max
+        perm_generator = (np.concatenate(z)
+                          for z in _all_partitions(size_a, size-size_a))
+
+    t_stat = []
+    for indices in _batch_generator(perm_generator, batch=50):
+        # get one batch from perm_generator at a time as a list
+        indices = np.array(indices)
+        # generate permutations
+        data_perm = data[..., indices]
+        # move axis indexing permutations to position 0 to broadcast
+        # nicely with t_stat_observed, which doesn't have this dimension
+        data_perm = np.moveaxis(data_perm, -2, 0)
+
+        a = data_perm[..., :size_a]
+        b = data_perm[..., size_a:]
+        t_stat.append(_calc_t_stat(a, b, equal_var))
+
+    t_stat = np.concatenate(t_stat, axis=0)
+
+    return t_stat, permutations, n_max
+
+
+def _calc_t_stat(a, b, equal_var, axis=-1):
+    """Calculate the t statistic along the given dimension."""
+    na = a.shape[axis]
+    nb = b.shape[axis]
+    avg_a = np.mean(a, axis=axis)
+    avg_b = np.mean(b, axis=axis)
+    var_a = _var(a, axis=axis, ddof=1)
+    var_b = _var(b, axis=axis, ddof=1)
+
+    if not equal_var:
+        _, denom = _unequal_var_ttest_denom(var_a, na, var_b, nb)
+    else:
+        _, denom = _equal_var_ttest_denom(var_a, na, var_b, nb)
+
+    return (avg_a-avg_b)/denom
+
+
+def _permutation_ttest(a, b, permutations, axis=0, equal_var=True,
+                       nan_policy='propagate', random_state=None,
+                       alternative="two-sided"):
+    """
+    Calculates the T-test for the means of TWO INDEPENDENT samples of scores
+    using permutation methods.
+
+    This test is similar to `stats.ttest_ind`, except it doesn't rely on an
+    approximate normality assumption since it uses a permutation test.
+    This function is only called from ttest_ind when permutations is not None.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must be broadcastable, except along the dimension
+        corresponding to `axis` (the zeroth, by default).
+    axis : int, optional
+        The axis over which to operate on a and b.
+    permutations : int, optional
+        Number of permutations used to calculate p-value. If greater than or
+        equal to the number of distinct permutations, perform an exact test.
+    equal_var : bool, optional
+        If False, an equal variance (Welch's) t-test is conducted.  Otherwise,
+        an ordinary t-test is conducted.
+    random_state : {None, int, `numpy.random.Generator`}, optional
+        If `seed` is None the `numpy.random.Generator` singleton is used.
+        If `seed` is an int, a new ``Generator`` instance is used,
+        seeded with `seed`.
+        If `seed` is already a ``Generator`` instance then that instance is
+        used.
+        Pseudorandom number generator state used for generating random
+        permutations.
+
+    Returns
+    -------
+    statistic : float or array
+        The calculated t-statistic.
+    pvalue : float or array
+        The p-value.
+
+    """
+    if permutations < 0 or (np.isfinite(permutations) and
+                            int(permutations) != permutations):
+        raise ValueError("Permutations must be a non-negative integer.")
+
+    random_state = check_random_state(random_state)
+
+    t_stat_observed = _calc_t_stat(a, b, equal_var, axis=axis)
+
+    na = a.shape[axis]
+    mat = _broadcast_concatenate((a, b), axis=axis)
+    mat = np.moveaxis(mat, axis, -1)
+
+    t_stat, permutations, n_max = _permutation_distribution_t(
+        mat, permutations, size_a=na, equal_var=equal_var,
+        random_state=random_state)
+
+    compare = {"less": np.less_equal,
+               "greater": np.greater_equal,
+               "two-sided": lambda x, y: (x <= -np.abs(y)) | (x >= np.abs(y))}
+
+    # Calculate the p-values
+    cmps = compare[alternative](t_stat, t_stat_observed)
+    # Randomized test p-value calculation should use biased estimate; see e.g.
+    # https://www.degruyter.com/document/doi/10.2202/1544-6115.1585/
+    adjustment = 1 if n_max > permutations else 0
+    pvalues = (cmps.sum(axis=0) + adjustment) / (permutations + adjustment)
+
+    # nans propagate naturally in statistic calculation, but need to be
+    # propagated manually into pvalues
+    if nan_policy == 'propagate' and np.isnan(t_stat_observed).any():
+        if np.ndim(pvalues) == 0:
+            pvalues = np.float64(np.nan)
+        else:
+            pvalues[np.isnan(t_stat_observed)] = np.nan
+
+    return (t_stat_observed, pvalues)
+
+
+def _get_len(a, axis, msg):
+    try:
+        n = a.shape[axis]
+    except IndexError:
+        raise AxisError(axis, a.ndim, msg) from None
+    return n
+
+
+@_axis_nan_policy_factory(pack_TtestResult, default_axis=0, n_samples=2,
+                          result_to_tuple=unpack_TtestResult, n_outputs=6,
+                          paired=True)
+def ttest_rel(a, b, axis=0, nan_policy='propagate', alternative="two-sided"):
+    """Calculate the t-test on TWO RELATED samples of scores, a and b.
+
+    This is a test for the null hypothesis that two related or
+    repeated samples have identical average (expected) values.
+
+    Parameters
+    ----------
+    a, b : array_like
+        The arrays must have the same shape.
+    axis : int or None, optional
+        Axis along which to compute test. If None, compute over the whole
+        arrays, `a`, and `b`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the means of the distributions underlying the samples
+          are unequal.
+        * 'less': the mean of the distribution underlying the first sample
+          is less than the mean of the distribution underlying the second
+          sample.
+        * 'greater': the mean of the distribution underlying the first
+          sample is greater than the mean of the distribution underlying
+          the second sample.
+
+        .. versionadded:: 1.6.0
+
+    Returns
+    -------
+    result : `~scipy.stats._result_classes.TtestResult`
+        An object with the following attributes:
+
+        statistic : float or array
+            The t-statistic.
+        pvalue : float or array
+            The p-value associated with the given alternative.
+        df : float or array
+            The number of degrees of freedom used in calculation of the
+            t-statistic; this is one less than the size of the sample
+            (``a.shape[axis]``).
+
+            .. versionadded:: 1.10.0
+
+        The object also has the following method:
+
+        confidence_interval(confidence_level=0.95)
+            Computes a confidence interval around the difference in
+            population means for the given confidence level.
+            The confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.
+
+            .. versionadded:: 1.10.0
+
+    Notes
+    -----
+    Examples for use are scores of the same set of student in
+    different exams, or repeated sampling from the same units. The
+    test measures whether the average score differs significantly
+    across samples (e.g. exams). If we observe a large p-value, for
+    example greater than 0.05 or 0.1 then we cannot reject the null
+    hypothesis of identical average scores. If the p-value is smaller
+    than the threshold, e.g. 1%, 5% or 10%, then we reject the null
+    hypothesis of equal averages. Small p-values are associated with
+    large t-statistics.
+
+    The t-statistic is calculated as ``np.mean(a - b)/se``, where ``se`` is the
+    standard error. Therefore, the t-statistic will be positive when the sample
+    mean of ``a - b`` is greater than zero and negative when the sample mean of
+    ``a - b`` is less than zero.
+
+    References
+    ----------
+    https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+
+    >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
+    >>> rvs2 = (stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
+    ...         + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
+    >>> stats.ttest_rel(rvs1, rvs2)
+    TtestResult(statistic=-0.4549717054410304, pvalue=0.6493274702088672, df=499)
+    >>> rvs3 = (stats.norm.rvs(loc=8, scale=10, size=500, random_state=rng)
+    ...         + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
+    >>> stats.ttest_rel(rvs1, rvs3)
+    TtestResult(statistic=-5.879467544540889, pvalue=7.540777129099917e-09, df=499)
+
+    """
+    return ttest_1samp(a - b, popmean=0, axis=axis, alternative=alternative,
+                       _no_deco=True)
+
+
+# Map from names to lambda_ values used in power_divergence().
+_power_div_lambda_names = {
+    "pearson": 1,
+    "log-likelihood": 0,
+    "freeman-tukey": -0.5,
+    "mod-log-likelihood": -1,
+    "neyman": -2,
+    "cressie-read": 2/3,
+}
+
+
+def _m_count(a, *, axis, xp):
+    """Count the number of non-masked elements of an array.
+
+    This function behaves like `np.ma.count`, but is much faster
+    for ndarrays.
+    """
+    if hasattr(a, 'count'):
+        num = a.count(axis=axis)
+        if isinstance(num, np.ndarray) and num.ndim == 0:
+            # In some cases, the `count` method returns a scalar array (e.g.
+            # np.array(3)), but we want a plain integer.
+            num = int(num)
+    else:
+        if axis is None:
+            num = xp_size(a)
+        else:
+            num = a.shape[axis]
+    return num
+
+
+def _m_broadcast_to(a, shape, *, xp):
+    if np.ma.isMaskedArray(a):
+        return np.ma.masked_array(np.broadcast_to(a, shape),
+                                  mask=np.broadcast_to(a.mask, shape))
+    return xp.broadcast_to(a, shape)
+
+
+def _m_sum(a, *, axis, preserve_mask, xp):
+    if np.ma.isMaskedArray(a):
+        sum = a.sum(axis)
+        return sum if preserve_mask else np.asarray(sum)
+    return xp.sum(a, axis=axis)
+
+
+def _m_mean(a, *, axis, keepdims, xp):
+    if np.ma.isMaskedArray(a):
+        return np.asarray(a.mean(axis=axis, keepdims=keepdims))
+    return xp.mean(a, axis=axis, keepdims=keepdims)
+
+
+Power_divergenceResult = namedtuple('Power_divergenceResult',
+                                    ('statistic', 'pvalue'))
+
+
+def power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None):
+    """Cressie-Read power divergence statistic and goodness of fit test.
+
+    This function tests the null hypothesis that the categorical data
+    has the given frequencies, using the Cressie-Read power divergence
+    statistic.
+
+    Parameters
+    ----------
+    f_obs : array_like
+        Observed frequencies in each category.
+
+        .. deprecated:: 1.14.0
+            Support for masked array input was deprecated in
+            SciPy 1.14.0 and will be removed in version 1.16.0.
+
+    f_exp : array_like, optional
+        Expected frequencies in each category.  By default the categories are
+        assumed to be equally likely.
+
+        .. deprecated:: 1.14.0
+            Support for masked array input was deprecated in
+            SciPy 1.14.0 and will be removed in version 1.16.0.
+
+    ddof : int, optional
+        "Delta degrees of freedom": adjustment to the degrees of freedom
+        for the p-value.  The p-value is computed using a chi-squared
+        distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
+        is the number of observed frequencies.  The default value of `ddof`
+        is 0.
+    axis : int or None, optional
+        The axis of the broadcast result of `f_obs` and `f_exp` along which to
+        apply the test.  If axis is None, all values in `f_obs` are treated
+        as a single data set.  Default is 0.
+    lambda_ : float or str, optional
+        The power in the Cressie-Read power divergence statistic.  The default
+        is 1.  For convenience, `lambda_` may be assigned one of the following
+        strings, in which case the corresponding numerical value is used:
+
+        * ``"pearson"`` (value 1)
+            Pearson's chi-squared statistic. In this case, the function is
+            equivalent to `chisquare`.
+        * ``"log-likelihood"`` (value 0)
+            Log-likelihood ratio. Also known as the G-test [3]_.
+        * ``"freeman-tukey"`` (value -1/2)
+            Freeman-Tukey statistic.
+        * ``"mod-log-likelihood"`` (value -1)
+            Modified log-likelihood ratio.
+        * ``"neyman"`` (value -2)
+            Neyman's statistic.
+        * ``"cressie-read"`` (value 2/3)
+            The power recommended in [5]_.
+
+    Returns
+    -------
+    res: Power_divergenceResult
+        An object containing attributes:
+
+        statistic : float or ndarray
+            The Cressie-Read power divergence test statistic.  The value is
+            a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D.
+        pvalue : float or ndarray
+            The p-value of the test.  The value is a float if `ddof` and the
+            return value `stat` are scalars.
+
+    See Also
+    --------
+    chisquare
+
+    Notes
+    -----
+    This test is invalid when the observed or expected frequencies in each
+    category are too small.  A typical rule is that all of the observed
+    and expected frequencies should be at least 5.
+
+    Also, the sum of the observed and expected frequencies must be the same
+    for the test to be valid; `power_divergence` raises an error if the sums
+    do not agree within a relative tolerance of ``eps**0.5``, where ``eps``
+    is the precision of the input dtype.
+
+    When `lambda_` is less than zero, the formula for the statistic involves
+    dividing by `f_obs`, so a warning or error may be generated if any value
+    in `f_obs` is 0.
+
+    Similarly, a warning or error may be generated if any value in `f_exp` is
+    zero when `lambda_` >= 0.
+
+    The default degrees of freedom, k-1, are for the case when no parameters
+    of the distribution are estimated. If p parameters are estimated by
+    efficient maximum likelihood then the correct degrees of freedom are
+    k-1-p. If the parameters are estimated in a different way, then the
+    dof can be between k-1-p and k-1. However, it is also possible that
+    the asymptotic distribution is not a chisquare, in which case this
+    test is not appropriate.
+
+    References
+    ----------
+    .. [1] Lowry, Richard.  "Concepts and Applications of Inferential
+           Statistics". Chapter 8.
+           https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html
+    .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
+    .. [3] "G-test", https://en.wikipedia.org/wiki/G-test
+    .. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and
+           practice of statistics in biological research", New York: Freeman
+           (1981)
+    .. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
+           Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
+           pp. 440-464.
+
+    Examples
+    --------
+    (See `chisquare` for more examples.)
+
+    When just `f_obs` is given, it is assumed that the expected frequencies
+    are uniform and given by the mean of the observed frequencies.  Here we
+    perform a G-test (i.e. use the log-likelihood ratio statistic):
+
+    >>> import numpy as np
+    >>> from scipy.stats import power_divergence
+    >>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood')
+    (2.006573162632538, 0.84823476779463769)
+
+    The expected frequencies can be given with the `f_exp` argument:
+
+    >>> power_divergence([16, 18, 16, 14, 12, 12],
+    ...                  f_exp=[16, 16, 16, 16, 16, 8],
+    ...                  lambda_='log-likelihood')
+    (3.3281031458963746, 0.6495419288047497)
+
+    When `f_obs` is 2-D, by default the test is applied to each column.
+
+    >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
+    >>> obs.shape
+    (6, 2)
+    >>> power_divergence(obs, lambda_="log-likelihood")
+    (array([ 2.00657316,  6.77634498]), array([ 0.84823477,  0.23781225]))
+
+    By setting ``axis=None``, the test is applied to all data in the array,
+    which is equivalent to applying the test to the flattened array.
+
+    >>> power_divergence(obs, axis=None)
+    (23.31034482758621, 0.015975692534127565)
+    >>> power_divergence(obs.ravel())
+    (23.31034482758621, 0.015975692534127565)
+
+    `ddof` is the change to make to the default degrees of freedom.
+
+    >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1)
+    (2.0, 0.73575888234288467)
+
+    The calculation of the p-values is done by broadcasting the
+    test statistic with `ddof`.
+
+    >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
+    (2.0, array([ 0.84914504,  0.73575888,  0.5724067 ]))
+
+    `f_obs` and `f_exp` are also broadcast.  In the following, `f_obs` has
+    shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
+    `f_obs` and `f_exp` has shape (2, 6).  To compute the desired chi-squared
+    statistics, we must use ``axis=1``:
+
+    >>> power_divergence([16, 18, 16, 14, 12, 12],
+    ...                  f_exp=[[16, 16, 16, 16, 16, 8],
+    ...                         [8, 20, 20, 16, 12, 12]],
+    ...                  axis=1)
+    (array([ 3.5 ,  9.25]), array([ 0.62338763,  0.09949846]))
+
+    """
+    return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis, lambda_=lambda_)
+
+
+def _power_divergence(f_obs, f_exp, ddof, axis, lambda_, sum_check=True):
+    xp = array_namespace(f_obs)
+    default_float = xp.asarray(1.).dtype
+
+    # Convert the input argument `lambda_` to a numerical value.
+    if isinstance(lambda_, str):
+        if lambda_ not in _power_div_lambda_names:
+            names = repr(list(_power_div_lambda_names.keys()))[1:-1]
+            raise ValueError(f"invalid string for lambda_: {lambda_!r}. "
+                             f"Valid strings are {names}")
+        lambda_ = _power_div_lambda_names[lambda_]
+    elif lambda_ is None:
+        lambda_ = 1
+
+    def warn_masked(arg):
+        if isinstance(arg, ma.MaskedArray):
+            message = (
+                "`power_divergence` and `chisquare` support for masked array input was "
+                "deprecated in SciPy 1.14.0 and will be removed in version 1.16.0.")
+            warnings.warn(message, DeprecationWarning, stacklevel=2)
+
+    warn_masked(f_obs)
+    f_obs = f_obs if np.ma.isMaskedArray(f_obs) else xp.asarray(f_obs)
+    dtype = default_float if xp.isdtype(f_obs.dtype, 'integral') else f_obs.dtype
+    f_obs = (f_obs.astype(dtype) if np.ma.isMaskedArray(f_obs)
+             else xp.asarray(f_obs, dtype=dtype))
+    f_obs_float = (f_obs.astype(np.float64) if hasattr(f_obs, 'mask')
+                   else xp.asarray(f_obs, dtype=xp.float64))
+
+    if f_exp is not None:
+        warn_masked(f_exp)
+        f_exp = f_exp if np.ma.isMaskedArray(f_obs) else xp.asarray(f_exp)
+        dtype = default_float if xp.isdtype(f_exp.dtype, 'integral') else f_exp.dtype
+        f_exp = (f_exp.astype(dtype) if np.ma.isMaskedArray(f_exp)
+                 else xp.asarray(f_exp, dtype=dtype))
+
+        bshape = _broadcast_shapes((f_obs_float.shape, f_exp.shape))
+        f_obs_float = _m_broadcast_to(f_obs_float, bshape, xp=xp)
+        f_exp = _m_broadcast_to(f_exp, bshape, xp=xp)
+
+        if sum_check:
+            dtype_res = xp.result_type(f_obs.dtype, f_exp.dtype)
+            rtol = xp.finfo(dtype_res).eps**0.5  # to pass existing tests
+            with np.errstate(invalid='ignore'):
+                f_obs_sum = _m_sum(f_obs_float, axis=axis, preserve_mask=False, xp=xp)
+                f_exp_sum = _m_sum(f_exp, axis=axis, preserve_mask=False, xp=xp)
+                relative_diff = (xp.abs(f_obs_sum - f_exp_sum) /
+                                 xp.minimum(f_obs_sum, f_exp_sum))
+                diff_gt_tol = xp.any(relative_diff > rtol, axis=None)
+            if diff_gt_tol:
+                msg = (f"For each axis slice, the sum of the observed "
+                       f"frequencies must agree with the sum of the "
+                       f"expected frequencies to a relative tolerance "
+                       f"of {rtol}, but the percent differences are:\n"
+                       f"{relative_diff}")
+                raise ValueError(msg)
+
+    else:
+        # Ignore 'invalid' errors so the edge case of a data set with length 0
+        # is handled without spurious warnings.
+        with np.errstate(invalid='ignore'):
+            f_exp = _m_mean(f_obs, axis=axis, keepdims=True, xp=xp)
+
+    # `terms` is the array of terms that are summed along `axis` to create
+    # the test statistic.  We use some specialized code for a few special
+    # cases of lambda_.
+    if lambda_ == 1:
+        # Pearson's chi-squared statistic
+        terms = (f_obs - f_exp)**2 / f_exp
+    elif lambda_ == 0:
+        # Log-likelihood ratio (i.e. G-test)
+        terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp)
+    elif lambda_ == -1:
+        # Modified log-likelihood ratio
+        terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs)
+    else:
+        # General Cressie-Read power divergence.
+        terms = f_obs * ((f_obs / f_exp)**lambda_ - 1)
+        terms /= 0.5 * lambda_ * (lambda_ + 1)
+
+    stat = _m_sum(terms, axis=axis, preserve_mask=True, xp=xp)
+
+    num_obs = _m_count(terms, axis=axis, xp=xp)
+    ddof = xp.asarray(ddof)
+
+    df = xp.asarray(num_obs - 1 - ddof)
+    chi2 = _SimpleChi2(df)
+    pvalue = _get_pvalue(stat, chi2 , alternative='greater', symmetric=False, xp=xp)
+
+    stat = stat[()] if stat.ndim == 0 else stat
+    pvalue = pvalue[()] if pvalue.ndim == 0 else pvalue
+
+    return Power_divergenceResult(stat, pvalue)
+
+
+def chisquare(f_obs, f_exp=None, ddof=0, axis=0, *, sum_check=True):
+    """Perform Pearson's chi-squared test.
+
+    Pearson's chi-squared test [1]_ is a goodness-of-fit test for a multinomial
+    distribution with given probabilities; that is, it assesses the null hypothesis
+    that the observed frequencies (counts) are obtained by independent
+    sampling of *N* observations from a categorical distribution with given
+    expected frequencies.
+
+    Parameters
+    ----------
+    f_obs : array_like
+        Observed frequencies in each category.
+    f_exp : array_like, optional
+        Expected frequencies in each category. By default, the categories are
+        assumed to be equally likely.
+    ddof : int, optional
+        "Delta degrees of freedom": adjustment to the degrees of freedom
+        for the p-value.  The p-value is computed using a chi-squared
+        distribution with ``k - 1 - ddof`` degrees of freedom, where ``k``
+        is the number of categories.  The default value of `ddof` is 0.
+    axis : int or None, optional
+        The axis of the broadcast result of `f_obs` and `f_exp` along which to
+        apply the test.  If axis is None, all values in `f_obs` are treated
+        as a single data set.  Default is 0.
+    sum_check : bool, optional
+        Whether to perform a check that ``sum(f_obs) - sum(f_exp) == 0``. If True,
+        (default) raise an error when the relative difference exceeds the square root
+        of the precision of the data type. See Notes for rationale and possible
+        exceptions.
+
+    Returns
+    -------
+    res: Power_divergenceResult
+        An object containing attributes:
+
+        statistic : float or ndarray
+            The chi-squared test statistic.  The value is a float if `axis` is
+            None or `f_obs` and `f_exp` are 1-D.
+        pvalue : float or ndarray
+            The p-value of the test.  The value is a float if `ddof` and the
+            result attribute `statistic` are scalars.
+
+    See Also
+    --------
+    scipy.stats.power_divergence
+    scipy.stats.fisher_exact : Fisher exact test on a 2x2 contingency table.
+    scipy.stats.barnard_exact : An unconditional exact test. An alternative
+        to chi-squared test for small sample sizes.
+    :ref:`hypothesis_chisquare` : Extended example
+
+    Notes
+    -----
+    This test is invalid when the observed or expected frequencies in each
+    category are too small.  A typical rule is that all of the observed
+    and expected frequencies should be at least 5. According to [2]_, the
+    total number of observations is recommended to be greater than 13,
+    otherwise exact tests (such as Barnard's Exact test) should be used
+    because they do not overreject.
+
+    The default degrees of freedom, k-1, are for the case when no parameters
+    of the distribution are estimated. If p parameters are estimated by
+    efficient maximum likelihood then the correct degrees of freedom are
+    k-1-p. If the parameters are estimated in a different way, then the
+    dof can be between k-1-p and k-1. However, it is also possible that
+    the asymptotic distribution is not chi-square, in which case this test
+    is not appropriate.
+
+    For Pearson's chi-squared test, the total observed and expected counts must match
+    for the p-value to accurately reflect the probability of observing such an extreme
+    value of the statistic under the null hypothesis.
+    This function may be used to perform other statistical tests that do not require
+    the total counts to be equal. For instance, to test the null hypothesis that
+    ``f_obs[i]`` is Poisson-distributed with expectation ``f_exp[i]``, set ``ddof=-1``
+    and ``sum_check=False``. This test follows from the fact that a Poisson random
+    variable with mean and variance ``f_exp[i]`` is approximately normal with the
+    same mean and variance; the chi-squared statistic standardizes, squares, and sums
+    the observations; and the sum of ``n`` squared standard normal variables follows
+    the chi-squared distribution with ``n`` degrees of freedom.
+
+    References
+    ----------
+    .. [1] "Pearson's chi-squared test".
+           *Wikipedia*. https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
+    .. [2] Pearson, Karl. "On the criterion that a given system of deviations from the probable
+           in the case of a correlated system of variables is such that it can be reasonably
+           supposed to have arisen from random sampling", Philosophical Magazine. Series 5. 50
+           (1900), pp. 157-175.
+
+    Examples
+    --------
+    When only the mandatory `f_obs` argument is given, it is assumed that the
+    expected frequencies are uniform and given by the mean of the observed
+    frequencies:
+
+    >>> import numpy as np
+    >>> from scipy.stats import chisquare
+    >>> chisquare([16, 18, 16, 14, 12, 12])
+    Power_divergenceResult(statistic=2.0, pvalue=0.84914503608460956)
+
+    The optional `f_exp` argument gives the expected frequencies.
+
+    >>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8])
+    Power_divergenceResult(statistic=3.5, pvalue=0.62338762774958223)
+
+    When `f_obs` is 2-D, by default the test is applied to each column.
+
+    >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
+    >>> obs.shape
+    (6, 2)
+    >>> chisquare(obs)
+    Power_divergenceResult(statistic=array([2.        , 6.66666667]), pvalue=array([0.84914504, 0.24663415]))
+
+    By setting ``axis=None``, the test is applied to all data in the array,
+    which is equivalent to applying the test to the flattened array.
+
+    >>> chisquare(obs, axis=None)
+    Power_divergenceResult(statistic=23.31034482758621, pvalue=0.015975692534127565)
+    >>> chisquare(obs.ravel())
+    Power_divergenceResult(statistic=23.310344827586206, pvalue=0.01597569253412758)
+
+    `ddof` is the change to make to the default degrees of freedom.
+
+    >>> chisquare([16, 18, 16, 14, 12, 12], ddof=1)
+    Power_divergenceResult(statistic=2.0, pvalue=0.7357588823428847)
+
+    The calculation of the p-values is done by broadcasting the
+    chi-squared statistic with `ddof`.
+
+    >>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0, 1, 2])
+    Power_divergenceResult(statistic=2.0, pvalue=array([0.84914504, 0.73575888, 0.5724067 ]))
+
+    `f_obs` and `f_exp` are also broadcast.  In the following, `f_obs` has
+    shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
+    `f_obs` and `f_exp` has shape (2, 6).  To compute the desired chi-squared
+    statistics, we use ``axis=1``:
+
+    >>> chisquare([16, 18, 16, 14, 12, 12],
+    ...           f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]],
+    ...           axis=1)
+    Power_divergenceResult(statistic=array([3.5 , 9.25]), pvalue=array([0.62338763, 0.09949846]))
+
+    For a more detailed example, see :ref:`hypothesis_chisquare`.
+    """  # noqa: E501
+    return _power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis,
+                             lambda_="pearson", sum_check=sum_check)
+
+
+KstestResult = _make_tuple_bunch('KstestResult', ['statistic', 'pvalue'],
+                                 ['statistic_location', 'statistic_sign'])
+
+
+def _compute_dplus(cdfvals, x):
+    """Computes D+ as used in the Kolmogorov-Smirnov test.
+
+    Parameters
+    ----------
+    cdfvals : array_like
+        Sorted array of CDF values between 0 and 1
+    x: array_like
+        Sorted array of the stochastic variable itself
+
+    Returns
+    -------
+    res: Pair with the following elements:
+        - The maximum distance of the CDF values below Uniform(0, 1).
+        - The location at which the maximum is reached.
+
+    """
+    n = len(cdfvals)
+    dplus = (np.arange(1.0, n + 1) / n - cdfvals)
+    amax = dplus.argmax()
+    loc_max = x[amax]
+    return (dplus[amax], loc_max)
+
+
+def _compute_dminus(cdfvals, x):
+    """Computes D- as used in the Kolmogorov-Smirnov test.
+
+    Parameters
+    ----------
+    cdfvals : array_like
+        Sorted array of CDF values between 0 and 1
+    x: array_like
+        Sorted array of the stochastic variable itself
+
+    Returns
+    -------
+    res: Pair with the following elements:
+        - Maximum distance of the CDF values above Uniform(0, 1)
+        - The location at which the maximum is reached.
+    """
+    n = len(cdfvals)
+    dminus = (cdfvals - np.arange(0.0, n)/n)
+    amax = dminus.argmax()
+    loc_max = x[amax]
+    return (dminus[amax], loc_max)
+
+
+def _tuple_to_KstestResult(statistic, pvalue,
+                           statistic_location, statistic_sign):
+    return KstestResult(statistic, pvalue,
+                        statistic_location=statistic_location,
+                        statistic_sign=statistic_sign)
+
+
+def _KstestResult_to_tuple(res):
+    return *res, res.statistic_location, res.statistic_sign
+
+
+@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=1, n_outputs=4,
+                          result_to_tuple=_KstestResult_to_tuple)
+@_rename_parameter("mode", "method")
+def ks_1samp(x, cdf, args=(), alternative='two-sided', method='auto'):
+    """
+    Performs the one-sample Kolmogorov-Smirnov test for goodness of fit.
+
+    This test compares the underlying distribution F(x) of a sample
+    against a given continuous distribution G(x). See Notes for a description
+    of the available null and alternative hypotheses.
+
+    Parameters
+    ----------
+    x : array_like
+        a 1-D array of observations of iid random variables.
+    cdf : callable
+        callable used to calculate the cdf.
+    args : tuple, sequence, optional
+        Distribution parameters, used with `cdf`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes below.
+    method : {'auto', 'exact', 'approx', 'asymp'}, optional
+        Defines the distribution used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : selects one of the other options.
+          * 'exact' : uses the exact distribution of test statistic.
+          * 'approx' : approximates the two-sided probability with twice
+            the one-sided probability
+          * 'asymp': uses asymptotic distribution of test statistic
+
+    Returns
+    -------
+    res: KstestResult
+        An object containing attributes:
+
+        statistic : float
+            KS test statistic, either D+, D-, or D (the maximum of the two)
+        pvalue : float
+            One-tailed or two-tailed p-value.
+        statistic_location : float
+            Value of `x` corresponding with the KS statistic; i.e., the
+            distance between the empirical distribution function and the
+            hypothesized cumulative distribution function is measured at this
+            observation.
+        statistic_sign : int
+            +1 if the KS statistic is the maximum positive difference between
+            the empirical distribution function and the hypothesized cumulative
+            distribution function (D+); -1 if the KS statistic is the maximum
+            negative difference (D-).
+
+
+    See Also
+    --------
+    ks_2samp, kstest
+
+    Notes
+    -----
+    There are three options for the null and corresponding alternative
+    hypothesis that can be selected using the `alternative` parameter.
+
+    - `two-sided`: The null hypothesis is that the two distributions are
+      identical, F(x)=G(x) for all x; the alternative is that they are not
+      identical.
+
+    - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
+      alternative is that F(x) < G(x) for at least one x.
+
+    - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
+      alternative is that F(x) > G(x) for at least one x.
+
+    Note that the alternative hypotheses describe the *CDFs* of the
+    underlying distributions, not the observed values. For example,
+    suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
+    x1 tend to be less than those in x2.
+
+    Examples
+    --------
+    Suppose we wish to test the null hypothesis that a sample is distributed
+    according to the standard normal.
+    We choose a confidence level of 95%; that is, we will reject the null
+    hypothesis in favor of the alternative if the p-value is less than 0.05.
+
+    When testing uniformly distributed data, we would expect the
+    null hypothesis to be rejected.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> stats.ks_1samp(stats.uniform.rvs(size=100, random_state=rng),
+    ...                stats.norm.cdf)
+    KstestResult(statistic=0.5001899973268688,
+                 pvalue=1.1616392184763533e-23,
+                 statistic_location=0.00047625268963724654,
+                 statistic_sign=-1)
+
+    Indeed, the p-value is lower than our threshold of 0.05, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the data
+    are *not* distributed according to the standard normal.
+
+    When testing random variates from the standard normal distribution, we
+    expect the data to be consistent with the null hypothesis most of the time.
+
+    >>> x = stats.norm.rvs(size=100, random_state=rng)
+    >>> stats.ks_1samp(x, stats.norm.cdf)
+    KstestResult(statistic=0.05345882212970396,
+                 pvalue=0.9227159037744717,
+                 statistic_location=-1.2451343873745018,
+                 statistic_sign=1)
+
+    As expected, the p-value of 0.92 is not below our threshold of 0.05, so
+    we cannot reject the null hypothesis.
+
+    Suppose, however, that the random variates are distributed according to
+    a normal distribution that is shifted toward greater values. In this case,
+    the cumulative density function (CDF) of the underlying distribution tends
+    to be *less* than the CDF of the standard normal. Therefore, we would
+    expect the null hypothesis to be rejected with ``alternative='less'``:
+
+    >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
+    >>> stats.ks_1samp(x, stats.norm.cdf, alternative='less')
+    KstestResult(statistic=0.17482387821055168,
+                 pvalue=0.001913921057766743,
+                 statistic_location=0.3713830565352756,
+                 statistic_sign=-1)
+
+    and indeed, with p-value smaller than our threshold, we reject the null
+    hypothesis in favor of the alternative.
+
+    """
+    mode = method
+
+    alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
+        alternative.lower()[0], alternative)
+    if alternative not in ['two-sided', 'greater', 'less']:
+        raise ValueError(f"Unexpected value {alternative=}")
+
+    N = len(x)
+    x = np.sort(x)
+    cdfvals = cdf(x, *args)
+    np_one = np.int8(1)
+
+    if alternative == 'greater':
+        Dplus, d_location = _compute_dplus(cdfvals, x)
+        return KstestResult(Dplus, distributions.ksone.sf(Dplus, N),
+                            statistic_location=d_location,
+                            statistic_sign=np_one)
+
+    if alternative == 'less':
+        Dminus, d_location = _compute_dminus(cdfvals, x)
+        return KstestResult(Dminus, distributions.ksone.sf(Dminus, N),
+                            statistic_location=d_location,
+                            statistic_sign=-np_one)
+
+    # alternative == 'two-sided':
+    Dplus, dplus_location = _compute_dplus(cdfvals, x)
+    Dminus, dminus_location = _compute_dminus(cdfvals, x)
+    if Dplus > Dminus:
+        D = Dplus
+        d_location = dplus_location
+        d_sign = np_one
+    else:
+        D = Dminus
+        d_location = dminus_location
+        d_sign = -np_one
+
+    if mode == 'auto':  # Always select exact
+        mode = 'exact'
+    if mode == 'exact':
+        prob = distributions.kstwo.sf(D, N)
+    elif mode == 'asymp':
+        prob = distributions.kstwobign.sf(D * np.sqrt(N))
+    else:
+        # mode == 'approx'
+        prob = 2 * distributions.ksone.sf(D, N)
+    prob = np.clip(prob, 0, 1)
+    return KstestResult(D, prob,
+                        statistic_location=d_location,
+                        statistic_sign=d_sign)
+
+
+Ks_2sampResult = KstestResult
+
+
+def _compute_prob_outside_square(n, h):
+    """
+    Compute the proportion of paths that pass outside the two diagonal lines.
+
+    Parameters
+    ----------
+    n : integer
+        n > 0
+    h : integer
+        0 <= h <= n
+
+    Returns
+    -------
+    p : float
+        The proportion of paths that pass outside the lines x-y = +/-h.
+
+    """
+    # Compute Pr(D_{n,n} >= h/n)
+    # Prob = 2 * ( binom(2n, n-h) - binom(2n, n-2a) + binom(2n, n-3a) - ... )
+    # / binom(2n, n)
+    # This formulation exhibits subtractive cancellation.
+    # Instead divide each term by binom(2n, n), then factor common terms
+    # and use a Horner-like algorithm
+    # P = 2 * A0 * (1 - A1*(1 - A2*(1 - A3*(1 - A4*(...)))))
+
+    P = 0.0
+    k = int(np.floor(n / h))
+    while k >= 0:
+        p1 = 1.0
+        # Each of the Ai terms has numerator and denominator with
+        # h simple terms.
+        for j in range(h):
+            p1 = (n - k * h - j) * p1 / (n + k * h + j + 1)
+        P = p1 * (1.0 - P)
+        k -= 1
+    return 2 * P
+
+
+def _count_paths_outside_method(m, n, g, h):
+    """Count the number of paths that pass outside the specified diagonal.
+
+    Parameters
+    ----------
+    m : integer
+        m > 0
+    n : integer
+        n > 0
+    g : integer
+        g is greatest common divisor of m and n
+    h : integer
+        0 <= h <= lcm(m,n)
+
+    Returns
+    -------
+    p : float
+        The number of paths that go low.
+        The calculation may overflow - check for a finite answer.
+
+    Notes
+    -----
+    Count the integer lattice paths from (0, 0) to (m, n), which at some
+    point (x, y) along the path, satisfy:
+      m*y <= n*x - h*g
+    The paths make steps of size +1 in either positive x or positive y
+    directions.
+
+    We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
+    Hodges, J.L. Jr.,
+    "The Significance Probability of the Smirnov Two-Sample Test,"
+    Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
+
+    """
+    # Compute #paths which stay lower than x/m-y/n = h/lcm(m,n)
+    # B(x, y) = #{paths from (0,0) to (x,y) without
+    #             previously crossing the boundary}
+    #         = binom(x, y) - #{paths which already reached the boundary}
+    # Multiply by the number of path extensions going from (x, y) to (m, n)
+    # Sum.
+
+    # Probability is symmetrical in m, n.  Computation below assumes m >= n.
+    if m < n:
+        m, n = n, m
+    mg = m // g
+    ng = n // g
+
+    # Not every x needs to be considered.
+    # xj holds the list of x values to be checked.
+    # Wherever n*x/m + ng*h crosses an integer
+    lxj = n + (mg-h)//mg
+    xj = [(h + mg * j + ng-1)//ng for j in range(lxj)]
+    # B is an array just holding a few values of B(x,y), the ones needed.
+    # B[j] == B(x_j, j)
+    if lxj == 0:
+        return special.binom(m + n, n)
+    B = np.zeros(lxj)
+    B[0] = 1
+    # Compute the B(x, y) terms
+    for j in range(1, lxj):
+        Bj = special.binom(xj[j] + j, j)
+        for i in range(j):
+            bin = special.binom(xj[j] - xj[i] + j - i, j-i)
+            Bj -= bin * B[i]
+        B[j] = Bj
+    # Compute the number of path extensions...
+    num_paths = 0
+    for j in range(lxj):
+        bin = special.binom((m-xj[j]) + (n - j), n-j)
+        term = B[j] * bin
+        num_paths += term
+    return num_paths
+
+
+def _attempt_exact_2kssamp(n1, n2, g, d, alternative):
+    """Attempts to compute the exact 2sample probability.
+
+    n1, n2 are the sample sizes
+    g is the gcd(n1, n2)
+    d is the computed max difference in ECDFs
+
+    Returns (success, d, probability)
+    """
+    lcm = (n1 // g) * n2
+    h = int(np.round(d * lcm))
+    d = h * 1.0 / lcm
+    if h == 0:
+        return True, d, 1.0
+    saw_fp_error, prob = False, np.nan
+    try:
+        with np.errstate(invalid="raise", over="raise"):
+            if alternative == 'two-sided':
+                if n1 == n2:
+                    prob = _compute_prob_outside_square(n1, h)
+                else:
+                    prob = _compute_outer_prob_inside_method(n1, n2, g, h)
+            else:
+                if n1 == n2:
+                    # prob = binom(2n, n-h) / binom(2n, n)
+                    # Evaluating in that form incurs roundoff errors
+                    # from special.binom. Instead calculate directly
+                    jrange = np.arange(h)
+                    prob = np.prod((n1 - jrange) / (n1 + jrange + 1.0))
+                else:
+                    with np.errstate(over='raise'):
+                        num_paths = _count_paths_outside_method(n1, n2, g, h)
+                    bin = special.binom(n1 + n2, n1)
+                    if num_paths > bin or np.isinf(bin):
+                        saw_fp_error = True
+                    else:
+                        prob = num_paths / bin
+
+    except (FloatingPointError, OverflowError):
+        saw_fp_error = True
+
+    if saw_fp_error:
+        return False, d, np.nan
+    if not (0 <= prob <= 1):
+        return False, d, prob
+    return True, d, prob
+
+
+@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=2, n_outputs=4,
+                          result_to_tuple=_KstestResult_to_tuple)
+@_rename_parameter("mode", "method")
+def ks_2samp(data1, data2, alternative='two-sided', method='auto'):
+    """
+    Performs the two-sample Kolmogorov-Smirnov test for goodness of fit.
+
+    This test compares the underlying continuous distributions F(x) and G(x)
+    of two independent samples.  See Notes for a description of the available
+    null and alternative hypotheses.
+
+    Parameters
+    ----------
+    data1, data2 : array_like, 1-Dimensional
+        Two arrays of sample observations assumed to be drawn from a continuous
+        distribution, sample sizes can be different.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes below.
+    method : {'auto', 'exact', 'asymp'}, optional
+        Defines the method used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : use 'exact' for small size arrays, 'asymp' for large
+          * 'exact' : use exact distribution of test statistic
+          * 'asymp' : use asymptotic distribution of test statistic
+
+    Returns
+    -------
+    res: KstestResult
+        An object containing attributes:
+
+        statistic : float
+            KS test statistic.
+        pvalue : float
+            One-tailed or two-tailed p-value.
+        statistic_location : float
+            Value from `data1` or `data2` corresponding with the KS statistic;
+            i.e., the distance between the empirical distribution functions is
+            measured at this observation.
+        statistic_sign : int
+            +1 if the empirical distribution function of `data1` exceeds
+            the empirical distribution function of `data2` at
+            `statistic_location`, otherwise -1.
+
+    See Also
+    --------
+    kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp
+
+    Notes
+    -----
+    There are three options for the null and corresponding alternative
+    hypothesis that can be selected using the `alternative` parameter.
+
+    - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
+      alternative is that F(x) < G(x) for at least one x. The statistic
+      is the magnitude of the minimum (most negative) difference between the
+      empirical distribution functions of the samples.
+
+    - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
+      alternative is that F(x) > G(x) for at least one x. The statistic
+      is the maximum (most positive) difference between the empirical
+      distribution functions of the samples.
+
+    - `two-sided`: The null hypothesis is that the two distributions are
+      identical, F(x)=G(x) for all x; the alternative is that they are not
+      identical. The statistic is the maximum absolute difference between the
+      empirical distribution functions of the samples.
+
+    Note that the alternative hypotheses describe the *CDFs* of the
+    underlying distributions, not the observed values of the data. For example,
+    suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
+    x1 tend to be less than those in x2.
+
+    If the KS statistic is large, then the p-value will be small, and this may
+    be taken as evidence against the null hypothesis in favor of the
+    alternative.
+
+    If ``method='exact'``, `ks_2samp` attempts to compute an exact p-value,
+    that is, the probability under the null hypothesis of obtaining a test
+    statistic value as extreme as the value computed from the data.
+    If ``method='asymp'``, the asymptotic Kolmogorov-Smirnov distribution is
+    used to compute an approximate p-value.
+    If ``method='auto'``, an exact p-value computation is attempted if both
+    sample sizes are less than 10000; otherwise, the asymptotic method is used.
+    In any case, if an exact p-value calculation is attempted and fails, a
+    warning will be emitted, and the asymptotic p-value will be returned.
+
+    The 'two-sided' 'exact' computation computes the complementary probability
+    and then subtracts from 1.  As such, the minimum probability it can return
+    is about 1e-16.  While the algorithm itself is exact, numerical
+    errors may accumulate for large sample sizes.   It is most suited to
+    situations in which one of the sample sizes is only a few thousand.
+
+    We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_.
+
+    References
+    ----------
+    .. [1] Hodges, J.L. Jr.,  "The Significance Probability of the Smirnov
+           Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-486.
+
+    Examples
+    --------
+    Suppose we wish to test the null hypothesis that two samples were drawn
+    from the same distribution.
+    We choose a confidence level of 95%; that is, we will reject the null
+    hypothesis in favor of the alternative if the p-value is less than 0.05.
+
+    If the first sample were drawn from a uniform distribution and the second
+    were drawn from the standard normal, we would expect the null hypothesis
+    to be rejected.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> sample1 = stats.uniform.rvs(size=100, random_state=rng)
+    >>> sample2 = stats.norm.rvs(size=110, random_state=rng)
+    >>> stats.ks_2samp(sample1, sample2)
+    KstestResult(statistic=0.5454545454545454,
+                 pvalue=7.37417839555191e-15,
+                 statistic_location=-0.014071496412861274,
+                 statistic_sign=-1)
+
+
+    Indeed, the p-value is lower than our threshold of 0.05, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the data
+    were *not* drawn from the same distribution.
+
+    When both samples are drawn from the same distribution, we expect the data
+    to be consistent with the null hypothesis most of the time.
+
+    >>> sample1 = stats.norm.rvs(size=105, random_state=rng)
+    >>> sample2 = stats.norm.rvs(size=95, random_state=rng)
+    >>> stats.ks_2samp(sample1, sample2)
+    KstestResult(statistic=0.10927318295739348,
+                 pvalue=0.5438289009927495,
+                 statistic_location=-0.1670157701848795,
+                 statistic_sign=-1)
+
+    As expected, the p-value of 0.54 is not below our threshold of 0.05, so
+    we cannot reject the null hypothesis.
+
+    Suppose, however, that the first sample were drawn from
+    a normal distribution shifted toward greater values. In this case,
+    the cumulative density function (CDF) of the underlying distribution tends
+    to be *less* than the CDF underlying the second sample. Therefore, we would
+    expect the null hypothesis to be rejected with ``alternative='less'``:
+
+    >>> sample1 = stats.norm.rvs(size=105, loc=0.5, random_state=rng)
+    >>> stats.ks_2samp(sample1, sample2, alternative='less')
+    KstestResult(statistic=0.4055137844611529,
+                 pvalue=3.5474563068855554e-08,
+                 statistic_location=-0.13249370614972575,
+                 statistic_sign=-1)
+
+    and indeed, with p-value smaller than our threshold, we reject the null
+    hypothesis in favor of the alternative.
+
+    """
+    mode = method
+
+    if mode not in ['auto', 'exact', 'asymp']:
+        raise ValueError(f'Invalid value for mode: {mode}')
+    alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
+        alternative.lower()[0], alternative)
+    if alternative not in ['two-sided', 'less', 'greater']:
+        raise ValueError(f'Invalid value for alternative: {alternative}')
+    MAX_AUTO_N = 10000  # 'auto' will attempt to be exact if n1,n2 <= MAX_AUTO_N
+    if np.ma.is_masked(data1):
+        data1 = data1.compressed()
+    if np.ma.is_masked(data2):
+        data2 = data2.compressed()
+    data1 = np.sort(data1)
+    data2 = np.sort(data2)
+    n1 = data1.shape[0]
+    n2 = data2.shape[0]
+    if min(n1, n2) == 0:
+        raise ValueError('Data passed to ks_2samp must not be empty')
+
+    data_all = np.concatenate([data1, data2])
+    # using searchsorted solves equal data problem
+    cdf1 = np.searchsorted(data1, data_all, side='right') / n1
+    cdf2 = np.searchsorted(data2, data_all, side='right') / n2
+    cddiffs = cdf1 - cdf2
+
+    # Identify the location of the statistic
+    argminS = np.argmin(cddiffs)
+    argmaxS = np.argmax(cddiffs)
+    loc_minS = data_all[argminS]
+    loc_maxS = data_all[argmaxS]
+
+    # Ensure sign of minS is not negative.
+    minS = np.clip(-cddiffs[argminS], 0, 1)
+    maxS = cddiffs[argmaxS]
+
+    if alternative == 'less' or (alternative == 'two-sided' and minS > maxS):
+        d = minS
+        d_location = loc_minS
+        d_sign = -1
+    else:
+        d = maxS
+        d_location = loc_maxS
+        d_sign = 1
+    g = gcd(n1, n2)
+    n1g = n1 // g
+    n2g = n2 // g
+    prob = -np.inf
+    if mode == 'auto':
+        mode = 'exact' if max(n1, n2) <= MAX_AUTO_N else 'asymp'
+    elif mode == 'exact':
+        # If lcm(n1, n2) is too big, switch from exact to asymp
+        if n1g >= np.iinfo(np.int32).max / n2g:
+            mode = 'asymp'
+            warnings.warn(
+                f"Exact ks_2samp calculation not possible with samples sizes "
+                f"{n1} and {n2}. Switching to 'asymp'.", RuntimeWarning,
+                stacklevel=3)
+
+    if mode == 'exact':
+        success, d, prob = _attempt_exact_2kssamp(n1, n2, g, d, alternative)
+        if not success:
+            mode = 'asymp'
+            warnings.warn(f"ks_2samp: Exact calculation unsuccessful. "
+                          f"Switching to method={mode}.", RuntimeWarning,
+                          stacklevel=3)
+
+    if mode == 'asymp':
+        # The product n1*n2 is large.  Use Smirnov's asymptotic formula.
+        # Ensure float to avoid overflow in multiplication
+        # sorted because the one-sided formula is not symmetric in n1, n2
+        m, n = sorted([float(n1), float(n2)], reverse=True)
+        en = m * n / (m + n)
+        if alternative == 'two-sided':
+            prob = distributions.kstwo.sf(d, np.round(en))
+        else:
+            z = np.sqrt(en) * d
+            # Use Hodges' suggested approximation Eqn 5.3
+            # Requires m to be the larger of (n1, n2)
+            expt = -2 * z**2 - 2 * z * (m + 2*n)/np.sqrt(m*n*(m+n))/3.0
+            prob = np.exp(expt)
+
+    prob = np.clip(prob, 0, 1)
+    # Currently, `d` is a Python float. We want it to be a NumPy type, so
+    # float64 is appropriate. An enhancement would be for `d` to respect the
+    # dtype of the input.
+    return KstestResult(np.float64(d), prob, statistic_location=d_location,
+                        statistic_sign=np.int8(d_sign))
+
+
+def _parse_kstest_args(data1, data2, args, N):
+    # kstest allows many different variations of arguments.
+    # Pull out the parsing into a separate function
+    # (xvals, yvals, )  # 2sample
+    # (xvals, cdf function,..)
+    # (xvals, name of distribution, ...)
+    # (name of distribution, name of distribution, ...)
+
+    # Returns xvals, yvals, cdf
+    # where cdf is a cdf function, or None
+    # and yvals is either an array_like of values, or None
+    # and xvals is array_like.
+    rvsfunc, cdf = None, None
+    if isinstance(data1, str):
+        rvsfunc = getattr(distributions, data1).rvs
+    elif callable(data1):
+        rvsfunc = data1
+
+    if isinstance(data2, str):
+        cdf = getattr(distributions, data2).cdf
+        data2 = None
+    elif callable(data2):
+        cdf = data2
+        data2 = None
+
+    data1 = np.sort(rvsfunc(*args, size=N) if rvsfunc else data1)
+    return data1, data2, cdf
+
+
+def _kstest_n_samples(kwargs):
+    cdf = kwargs['cdf']
+    return 1 if (isinstance(cdf, str) or callable(cdf)) else 2
+
+
+@_axis_nan_policy_factory(_tuple_to_KstestResult, n_samples=_kstest_n_samples,
+                          n_outputs=4, result_to_tuple=_KstestResult_to_tuple)
+@_rename_parameter("mode", "method")
+def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', method='auto'):
+    """
+    Performs the (one-sample or two-sample) Kolmogorov-Smirnov test for
+    goodness of fit.
+
+    The one-sample test compares the underlying distribution F(x) of a sample
+    against a given distribution G(x). The two-sample test compares the
+    underlying distributions of two independent samples. Both tests are valid
+    only for continuous distributions.
+
+    Parameters
+    ----------
+    rvs : str, array_like, or callable
+        If an array, it should be a 1-D array of observations of random
+        variables.
+        If a callable, it should be a function to generate random variables;
+        it is required to have a keyword argument `size`.
+        If a string, it should be the name of a distribution in `scipy.stats`,
+        which will be used to generate random variables.
+    cdf : str, array_like or callable
+        If array_like, it should be a 1-D array of observations of random
+        variables, and the two-sample test is performed
+        (and rvs must be array_like).
+        If a callable, that callable is used to calculate the cdf.
+        If a string, it should be the name of a distribution in `scipy.stats`,
+        which will be used as the cdf function.
+    args : tuple, sequence, optional
+        Distribution parameters, used if `rvs` or `cdf` are strings or
+        callables.
+    N : int, optional
+        Sample size if `rvs` is string or callable.  Default is 20.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the null and alternative hypotheses. Default is 'two-sided'.
+        Please see explanations in the Notes below.
+    method : {'auto', 'exact', 'approx', 'asymp'}, optional
+        Defines the distribution used for calculating the p-value.
+        The following options are available (default is 'auto'):
+
+          * 'auto' : selects one of the other options.
+          * 'exact' : uses the exact distribution of test statistic.
+          * 'approx' : approximates the two-sided probability with twice the
+            one-sided probability
+          * 'asymp': uses asymptotic distribution of test statistic
+
+    Returns
+    -------
+    res: KstestResult
+        An object containing attributes:
+
+        statistic : float
+            KS test statistic, either D+, D-, or D (the maximum of the two)
+        pvalue : float
+            One-tailed or two-tailed p-value.
+        statistic_location : float
+            In a one-sample test, this is the value of `rvs`
+            corresponding with the KS statistic; i.e., the distance between
+            the empirical distribution function and the hypothesized cumulative
+            distribution function is measured at this observation.
+
+            In a two-sample test, this is the value from `rvs` or `cdf`
+            corresponding with the KS statistic; i.e., the distance between
+            the empirical distribution functions is measured at this
+            observation.
+        statistic_sign : int
+            In a one-sample test, this is +1 if the KS statistic is the
+            maximum positive difference between the empirical distribution
+            function and the hypothesized cumulative distribution function
+            (D+); it is -1 if the KS statistic is the maximum negative
+            difference (D-).
+
+            In a two-sample test, this is +1 if the empirical distribution
+            function of `rvs` exceeds the empirical distribution
+            function of `cdf` at `statistic_location`, otherwise -1.
+
+    See Also
+    --------
+    ks_1samp, ks_2samp
+
+    Notes
+    -----
+    There are three options for the null and corresponding alternative
+    hypothesis that can be selected using the `alternative` parameter.
+
+    - `two-sided`: The null hypothesis is that the two distributions are
+      identical, F(x)=G(x) for all x; the alternative is that they are not
+      identical.
+
+    - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
+      alternative is that F(x) < G(x) for at least one x.
+
+    - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
+      alternative is that F(x) > G(x) for at least one x.
+
+    Note that the alternative hypotheses describe the *CDFs* of the
+    underlying distributions, not the observed values. For example,
+    suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
+    x1 tend to be less than those in x2.
+
+
+    Examples
+    --------
+    Suppose we wish to test the null hypothesis that a sample is distributed
+    according to the standard normal.
+    We choose a confidence level of 95%; that is, we will reject the null
+    hypothesis in favor of the alternative if the p-value is less than 0.05.
+
+    When testing uniformly distributed data, we would expect the
+    null hypothesis to be rejected.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+    >>> stats.kstest(stats.uniform.rvs(size=100, random_state=rng),
+    ...              stats.norm.cdf)
+    KstestResult(statistic=0.5001899973268688,
+                 pvalue=1.1616392184763533e-23,
+                 statistic_location=0.00047625268963724654,
+                 statistic_sign=-1)
+
+    Indeed, the p-value is lower than our threshold of 0.05, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the data
+    are *not* distributed according to the standard normal.
+
+    When testing random variates from the standard normal distribution, we
+    expect the data to be consistent with the null hypothesis most of the time.
+
+    >>> x = stats.norm.rvs(size=100, random_state=rng)
+    >>> stats.kstest(x, stats.norm.cdf)
+    KstestResult(statistic=0.05345882212970396,
+                 pvalue=0.9227159037744717,
+                 statistic_location=-1.2451343873745018,
+                 statistic_sign=1)
+
+
+    As expected, the p-value of 0.92 is not below our threshold of 0.05, so
+    we cannot reject the null hypothesis.
+
+    Suppose, however, that the random variates are distributed according to
+    a normal distribution that is shifted toward greater values. In this case,
+    the cumulative density function (CDF) of the underlying distribution tends
+    to be *less* than the CDF of the standard normal. Therefore, we would
+    expect the null hypothesis to be rejected with ``alternative='less'``:
+
+    >>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
+    >>> stats.kstest(x, stats.norm.cdf, alternative='less')
+    KstestResult(statistic=0.17482387821055168,
+                 pvalue=0.001913921057766743,
+                 statistic_location=0.3713830565352756,
+                 statistic_sign=-1)
+
+    and indeed, with p-value smaller than our threshold, we reject the null
+    hypothesis in favor of the alternative.
+
+    For convenience, the previous test can be performed using the name of the
+    distribution as the second argument.
+
+    >>> stats.kstest(x, "norm", alternative='less')
+    KstestResult(statistic=0.17482387821055168,
+                 pvalue=0.001913921057766743,
+                 statistic_location=0.3713830565352756,
+                 statistic_sign=-1)
+
+    The examples above have all been one-sample tests identical to those
+    performed by `ks_1samp`. Note that `kstest` can also perform two-sample
+    tests identical to those performed by `ks_2samp`. For example, when two
+    samples are drawn from the same distribution, we expect the data to be
+    consistent with the null hypothesis most of the time.
+
+    >>> sample1 = stats.laplace.rvs(size=105, random_state=rng)
+    >>> sample2 = stats.laplace.rvs(size=95, random_state=rng)
+    >>> stats.kstest(sample1, sample2)
+    KstestResult(statistic=0.11779448621553884,
+                 pvalue=0.4494256912629795,
+                 statistic_location=0.6138814275424155,
+                 statistic_sign=1)
+
+    As expected, the p-value of 0.45 is not below our threshold of 0.05, so
+    we cannot reject the null hypothesis.
+
+    """
+    # to not break compatibility with existing code
+    if alternative == 'two_sided':
+        alternative = 'two-sided'
+    if alternative not in ['two-sided', 'greater', 'less']:
+        raise ValueError(f"Unexpected alternative: {alternative}")
+    xvals, yvals, cdf = _parse_kstest_args(rvs, cdf, args, N)
+    if cdf:
+        return ks_1samp(xvals, cdf, args=args, alternative=alternative,
+                        method=method, _no_deco=True)
+    return ks_2samp(xvals, yvals, alternative=alternative, method=method,
+                    _no_deco=True)
+
+
+def tiecorrect(rankvals):
+    """Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests.
+
+    Parameters
+    ----------
+    rankvals : array_like
+        A 1-D sequence of ranks.  Typically this will be the array
+        returned by `~scipy.stats.rankdata`.
+
+    Returns
+    -------
+    factor : float
+        Correction factor for U or H.
+
+    See Also
+    --------
+    rankdata : Assign ranks to the data
+    mannwhitneyu : Mann-Whitney rank test
+    kruskal : Kruskal-Wallis H test
+
+    References
+    ----------
+    .. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral
+           Sciences.  New York: McGraw-Hill.
+
+    Examples
+    --------
+    >>> from scipy.stats import tiecorrect, rankdata
+    >>> tiecorrect([1, 2.5, 2.5, 4])
+    0.9
+    >>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4])
+    >>> ranks
+    array([ 1. ,  4. ,  2.5,  5.5,  7. ,  8. ,  2.5,  9. ,  5.5])
+    >>> tiecorrect(ranks)
+    0.9833333333333333
+
+    """
+    arr = np.sort(rankvals)
+    idx = np.nonzero(np.r_[True, arr[1:] != arr[:-1], True])[0]
+    cnt = np.diff(idx).astype(np.float64)
+
+    size = np.float64(arr.size)
+    return 1.0 if size < 2 else 1.0 - (cnt**3 - cnt).sum() / (size**3 - size)
+
+
+RanksumsResult = namedtuple('RanksumsResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(RanksumsResult, n_samples=2)
+def ranksums(x, y, alternative='two-sided'):
+    """Compute the Wilcoxon rank-sum statistic for two samples.
+
+    The Wilcoxon rank-sum test tests the null hypothesis that two sets
+    of measurements are drawn from the same distribution.  The alternative
+    hypothesis is that values in one sample are more likely to be
+    larger than the values in the other sample.
+
+    This test should be used to compare two samples from continuous
+    distributions.  It does not handle ties between measurements
+    in x and y.  For tie-handling and an optional continuity correction
+    see `scipy.stats.mannwhitneyu`.
+
+    Parameters
+    ----------
+    x,y : array_like
+        The data from the two samples.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': one of the distributions (underlying `x` or `y`) is
+          stochastically greater than the other.
+        * 'less': the distribution underlying `x` is stochastically less
+          than the distribution underlying `y`.
+        * 'greater': the distribution underlying `x` is stochastically greater
+          than the distribution underlying `y`.
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    statistic : float
+        The test statistic under the large-sample approximation that the
+        rank sum statistic is normally distributed.
+    pvalue : float
+        The p-value of the test.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test
+
+    Examples
+    --------
+    We can test the hypothesis that two independent unequal-sized samples are
+    drawn from the same distribution with computing the Wilcoxon rank-sum
+    statistic.
+
+    >>> import numpy as np
+    >>> from scipy.stats import ranksums
+    >>> rng = np.random.default_rng()
+    >>> sample1 = rng.uniform(-1, 1, 200)
+    >>> sample2 = rng.uniform(-0.5, 1.5, 300) # a shifted distribution
+    >>> ranksums(sample1, sample2)
+    RanksumsResult(statistic=-7.887059,
+                   pvalue=3.09390448e-15) # may vary
+    >>> ranksums(sample1, sample2, alternative='less')
+    RanksumsResult(statistic=-7.750585297581713,
+                   pvalue=4.573497606342543e-15) # may vary
+    >>> ranksums(sample1, sample2, alternative='greater')
+    RanksumsResult(statistic=-7.750585297581713,
+                   pvalue=0.9999999999999954) # may vary
+
+    The p-value of less than ``0.05`` indicates that this test rejects the
+    hypothesis at the 5% significance level.
+
+    """
+    x, y = map(np.asarray, (x, y))
+    n1 = len(x)
+    n2 = len(y)
+    alldata = np.concatenate((x, y))
+    ranked = rankdata(alldata)
+    x = ranked[:n1]
+    s = np.sum(x, axis=0)
+    expected = n1 * (n1+n2+1) / 2.0
+    z = (s - expected) / np.sqrt(n1*n2*(n1+n2+1)/12.0)
+    pvalue = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+
+    return RanksumsResult(z[()], pvalue[()])
+
+
+KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(KruskalResult, n_samples=None)
+def kruskal(*samples, nan_policy='propagate'):
+    """Compute the Kruskal-Wallis H-test for independent samples.
+
+    The Kruskal-Wallis H-test tests the null hypothesis that the population
+    median of all of the groups are equal.  It is a non-parametric version of
+    ANOVA.  The test works on 2 or more independent samples, which may have
+    different sizes.  Note that rejecting the null hypothesis does not
+    indicate which of the groups differs.  Post hoc comparisons between
+    groups are required to determine which groups are different.
+
+    Parameters
+    ----------
+    sample1, sample2, ... : array_like
+       Two or more arrays with the sample measurements can be given as
+       arguments. Samples must be one-dimensional.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    statistic : float
+       The Kruskal-Wallis H statistic, corrected for ties.
+    pvalue : float
+       The p-value for the test using the assumption that H has a chi
+       square distribution. The p-value returned is the survival function of
+       the chi square distribution evaluated at H.
+
+    See Also
+    --------
+    f_oneway : 1-way ANOVA.
+    mannwhitneyu : Mann-Whitney rank test on two samples.
+    friedmanchisquare : Friedman test for repeated measurements.
+
+    Notes
+    -----
+    Due to the assumption that H has a chi square distribution, the number
+    of samples in each group must not be too small.  A typical rule is
+    that each sample must have at least 5 measurements.
+
+    References
+    ----------
+    .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in
+       One-Criterion Variance Analysis", Journal of the American Statistical
+       Association, Vol. 47, Issue 260, pp. 583-621, 1952.
+    .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> x = [1, 3, 5, 7, 9]
+    >>> y = [2, 4, 6, 8, 10]
+    >>> stats.kruskal(x, y)
+    KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895)
+
+    >>> x = [1, 1, 1]
+    >>> y = [2, 2, 2]
+    >>> z = [2, 2]
+    >>> stats.kruskal(x, y, z)
+    KruskalResult(statistic=7.0, pvalue=0.0301973834223185)
+
+    """
+    samples = list(map(np.asarray, samples))
+
+    num_groups = len(samples)
+    if num_groups < 2:
+        raise ValueError("Need at least two groups in stats.kruskal()")
+
+    n = np.asarray(list(map(len, samples)))
+
+    alldata = np.concatenate(samples)
+    ranked = rankdata(alldata)
+    ties = tiecorrect(ranked)
+    if ties == 0:
+        raise ValueError('All numbers are identical in kruskal')
+
+    # Compute sum^2/n for each group and sum
+    j = np.insert(np.cumsum(n), 0, 0)
+    ssbn = 0
+    for i in range(num_groups):
+        ssbn += _square_of_sums(ranked[j[i]:j[i+1]]) / n[i]
+
+    totaln = np.sum(n, dtype=float)
+    h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1)
+    df = num_groups - 1
+    h /= ties
+
+    chi2 = _SimpleChi2(df)
+    pvalue = _get_pvalue(h, chi2, alternative='greater', symmetric=False, xp=np)
+    return KruskalResult(h, pvalue)
+
+
+FriedmanchisquareResult = namedtuple('FriedmanchisquareResult',
+                                     ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(FriedmanchisquareResult, n_samples=None, paired=True)
+def friedmanchisquare(*samples):
+    """Compute the Friedman test for repeated samples.
+
+    The Friedman test tests the null hypothesis that repeated samples of
+    the same individuals have the same distribution.  It is often used
+    to test for consistency among samples obtained in different ways.
+    For example, if two sampling techniques are used on the same set of
+    individuals, the Friedman test can be used to determine if the two
+    sampling techniques are consistent.
+
+    Parameters
+    ----------
+    sample1, sample2, sample3... : array_like
+        Arrays of observations.  All of the arrays must have the same number
+        of elements.  At least three samples must be given.
+
+    Returns
+    -------
+    statistic : float
+        The test statistic, correcting for ties.
+    pvalue : float
+        The associated p-value assuming that the test statistic has a chi
+        squared distribution.
+
+    See Also
+    --------
+    :ref:`hypothesis_friedmanchisquare` : Extended example
+
+    Notes
+    -----
+    Due to the assumption that the test statistic has a chi squared
+    distribution, the p-value is only reliable for n > 10 and more than
+    6 repeated samples.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Friedman_test
+    .. [2] Demsar, J. (2006). Statistical comparisons of classifiers over
+           multiple data sets. Journal of Machine Learning Research, 7, 1-30.
+
+    Examples
+    --------
+
+    >>> import numpy as np
+    >>> rng = np.random.default_rng(seed=18)
+    >>> x = rng.random((6, 10))
+    >>> from scipy.stats import friedmanchisquare
+    >>> res = friedmanchisquare(x[0], x[1], x[2], x[3], x[4], x[5])
+    >>> res.statistic, res.pvalue
+    (11.428571428571416, 0.043514520866727614)
+
+    The p-value is less than 0.05; however, as noted above, the results may not
+    be reliable since we have a small number of repeated samples.
+
+    For a more detailed example, see :ref:`hypothesis_friedmanchisquare`.
+    """
+    k = len(samples)
+    if k < 3:
+        raise ValueError('At least 3 sets of samples must be given '
+                         f'for Friedman test, got {k}.')
+
+    n = len(samples[0])
+    for i in range(1, k):
+        if len(samples[i]) != n:
+            raise ValueError('Unequal N in friedmanchisquare.  Aborting.')
+
+    # Rank data
+    data = np.vstack(samples).T
+    data = data.astype(float)
+    for i in range(len(data)):
+        data[i] = rankdata(data[i])
+
+    # Handle ties
+    ties = 0
+    for d in data:
+        _, repnum = _find_repeats(np.array(d, dtype=np.float64))
+        for t in repnum:
+            ties += t * (t*t - 1)
+    c = 1 - ties / (k*(k*k - 1)*n)
+
+    ssbn = np.sum(data.sum(axis=0)**2)
+    statistic = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c
+
+    chi2 = _SimpleChi2(k - 1)
+    pvalue = _get_pvalue(statistic, chi2, alternative='greater', symmetric=False, xp=np)
+    return FriedmanchisquareResult(statistic, pvalue)
+
+
+BrunnerMunzelResult = namedtuple('BrunnerMunzelResult',
+                                 ('statistic', 'pvalue'))
+
+
+@_axis_nan_policy_factory(BrunnerMunzelResult, n_samples=2)
+def brunnermunzel(x, y, alternative="two-sided", distribution="t",
+                  nan_policy='propagate'):
+    """Compute the Brunner-Munzel test on samples x and y.
+
+    The Brunner-Munzel test is a nonparametric test of the null hypothesis that
+    when values are taken one by one from each group, the probabilities of
+    getting large values in both groups are equal.
+    Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the
+    assumption of equivariance of two groups. Note that this does not assume
+    the distributions are same. This test works on two independent samples,
+    which may have different sizes.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Array of samples, should be one-dimensional.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+          * 'two-sided'
+          * 'less': one-sided
+          * 'greater': one-sided
+    distribution : {'t', 'normal'}, optional
+        Defines how to get the p-value.
+        The following options are available (default is 't'):
+
+          * 't': get the p-value by t-distribution
+          * 'normal': get the p-value by standard normal distribution.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': returns nan
+          * 'raise': throws an error
+          * 'omit': performs the calculations ignoring nan values
+
+    Returns
+    -------
+    statistic : float
+        The Brunner-Munzer W statistic.
+    pvalue : float
+        p-value assuming an t distribution. One-sided or
+        two-sided, depending on the choice of `alternative` and `distribution`.
+
+    See Also
+    --------
+    mannwhitneyu : Mann-Whitney rank test on two samples.
+
+    Notes
+    -----
+    Brunner and Munzel recommended to estimate the p-value by t-distribution
+    when the size of data is 50 or less. If the size is lower than 10, it would
+    be better to use permuted Brunner Munzel test (see [2]_).
+
+    References
+    ----------
+    .. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher
+           problem: Asymptotic theory and a small-sample approximation".
+           Biometrical Journal. Vol. 42(2000): 17-25.
+    .. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the
+           non-parametric Behrens-Fisher problem". Computational Statistics and
+           Data Analysis. Vol. 51(2007): 5192-5204.
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1]
+    >>> x2 = [3,3,4,3,1,2,3,1,1,5,4]
+    >>> w, p_value = stats.brunnermunzel(x1, x2)
+    >>> w
+    3.1374674823029505
+    >>> p_value
+    0.0057862086661515377
+
+    """
+    nx = len(x)
+    ny = len(y)
+
+    rankc = rankdata(np.concatenate((x, y)))
+    rankcx = rankc[0:nx]
+    rankcy = rankc[nx:nx+ny]
+    rankcx_mean = np.mean(rankcx)
+    rankcy_mean = np.mean(rankcy)
+    rankx = rankdata(x)
+    ranky = rankdata(y)
+    rankx_mean = np.mean(rankx)
+    ranky_mean = np.mean(ranky)
+
+    Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0))
+    Sx /= nx - 1
+    Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0))
+    Sy /= ny - 1
+
+    wbfn = nx * ny * (rankcy_mean - rankcx_mean)
+    wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy)
+
+    if distribution == "t":
+        df_numer = np.power(nx * Sx + ny * Sy, 2.0)
+        df_denom = np.power(nx * Sx, 2.0) / (nx - 1)
+        df_denom += np.power(ny * Sy, 2.0) / (ny - 1)
+        df = df_numer / df_denom
+
+        if (df_numer == 0) and (df_denom == 0):
+            message = ("p-value cannot be estimated with `distribution='t' "
+                       "because degrees of freedom parameter is undefined "
+                       "(0/0). Try using `distribution='normal'")
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+        distribution = _SimpleStudentT(df)
+    elif distribution == "normal":
+        distribution = _SimpleNormal()
+    else:
+        raise ValueError(
+            "distribution should be 't' or 'normal'")
+
+    p = _get_pvalue(-wbfn, distribution, alternative, xp=np)
+
+    return BrunnerMunzelResult(wbfn, p)
+
+
+@_axis_nan_policy_factory(SignificanceResult, kwd_samples=['weights'], paired=True)
+def combine_pvalues(pvalues, method='fisher', weights=None, *, axis=0):
+    """
+    Combine p-values from independent tests that bear upon the same hypothesis.
+
+    These methods are intended only for combining p-values from hypothesis
+    tests based upon continuous distributions.
+
+    Each method assumes that under the null hypothesis, the p-values are
+    sampled independently and uniformly from the interval [0, 1]. A test
+    statistic (different for each method) is computed and a combined
+    p-value is calculated based upon the distribution of this test statistic
+    under the null hypothesis.
+
+    Parameters
+    ----------
+    pvalues : array_like
+        Array of p-values assumed to come from independent tests based on
+        continuous distributions.
+    method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'}
+
+        Name of method to use to combine p-values.
+
+        The available methods are (see Notes for details):
+
+        * 'fisher': Fisher's method (Fisher's combined probability test)
+        * 'pearson': Pearson's method
+        * 'mudholkar_george': Mudholkar's and George's method
+        * 'tippett': Tippett's method
+        * 'stouffer': Stouffer's Z-score method
+    weights : array_like, optional
+        Optional array of weights used only for Stouffer's Z-score method.
+        Ignored by other methods.
+
+    Returns
+    -------
+    res : SignificanceResult
+        An object containing attributes:
+
+        statistic : float
+            The statistic calculated by the specified method.
+        pvalue : float
+            The combined p-value.
+
+    Examples
+    --------
+    Suppose we wish to combine p-values from four independent tests
+    of the same null hypothesis using Fisher's method (default).
+
+    >>> from scipy.stats import combine_pvalues
+    >>> pvalues = [0.1, 0.05, 0.02, 0.3]
+    >>> combine_pvalues(pvalues)
+    SignificanceResult(statistic=20.828626352604235, pvalue=0.007616871850449092)
+
+    When the individual p-values carry different weights, consider Stouffer's
+    method.
+
+    >>> weights = [1, 2, 3, 4]
+    >>> res = combine_pvalues(pvalues, method='stouffer', weights=weights)
+    >>> res.pvalue
+    0.009578891494533616
+
+    Notes
+    -----
+    If this function is applied to tests with a discrete statistics such as
+    any rank test or contingency-table test, it will yield systematically
+    wrong results, e.g. Fisher's method will systematically overestimate the
+    p-value [1]_. This problem becomes less severe for large sample sizes
+    when the discrete distributions become approximately continuous.
+
+    The differences between the methods can be best illustrated by their
+    statistics and what aspects of a combination of p-values they emphasise
+    when considering significance [2]_. For example, methods emphasising large
+    p-values are more sensitive to strong false and true negatives; conversely
+    methods focussing on small p-values are sensitive to positives.
+
+    * The statistics of Fisher's method (also known as Fisher's combined
+      probability test) [3]_ is :math:`-2\\sum_i \\log(p_i)`, which is
+      equivalent (as a test statistics) to the product of individual p-values:
+      :math:`\\prod_i p_i`. Under the null hypothesis, this statistics follows
+      a :math:`\\chi^2` distribution. This method emphasises small p-values.
+    * Pearson's method uses :math:`-2\\sum_i\\log(1-p_i)`, which is equivalent
+      to :math:`\\prod_i \\frac{1}{1-p_i}` [2]_.
+      It thus emphasises large p-values.
+    * Mudholkar and George compromise between Fisher's and Pearson's method by
+      averaging their statistics [4]_. Their method emphasises extreme
+      p-values, both close to 1 and 0.
+    * Stouffer's method [5]_ uses Z-scores and the statistic:
+      :math:`\\sum_i \\Phi^{-1} (p_i)`, where :math:`\\Phi` is the CDF of the
+      standard normal distribution. The advantage of this method is that it is
+      straightforward to introduce weights, which can make Stouffer's method
+      more powerful than Fisher's method when the p-values are from studies
+      of different size [6]_ [7]_.
+    * Tippett's method uses the smallest p-value as a statistic.
+      (Mind that this minimum is not the combined p-value.)
+
+    Fisher's method may be extended to combine p-values from dependent tests
+    [8]_. Extensions such as Brown's method and Kost's method are not currently
+    implemented.
+
+    .. versionadded:: 0.15.0
+
+    References
+    ----------
+    .. [1] Kincaid, W. M., "The Combination of Tests Based on Discrete
+           Distributions." Journal of the American Statistical Association 57,
+           no. 297 (1962), 10-19.
+    .. [2] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of
+           combining p-values."  Biometrika 105.1 (2018): 239-246.
+    .. [3] https://en.wikipedia.org/wiki/Fisher%27s_method
+    .. [4] George, E. O., and G. S. Mudholkar. "On the convolution of logistic
+           random variables." Metrika 30.1 (1983): 1-13.
+    .. [5] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method
+    .. [6] Whitlock, M. C. "Combining probability from independent tests: the
+           weighted Z-method is superior to Fisher's approach." Journal of
+           Evolutionary Biology 18, no. 5 (2005): 1368-1373.
+    .. [7] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method
+           for combining probabilities in meta-analysis." Journal of
+           Evolutionary Biology 24, no. 8 (2011): 1836-1841.
+    .. [8] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method
+
+    """
+    xp = array_namespace(pvalues)
+    pvalues = xp.asarray(pvalues)
+    if xp_size(pvalues) == 0:
+        # This is really only needed for *testing* _axis_nan_policy decorator
+        # It won't happen when the decorator is used.
+        NaN = _get_nan(pvalues)
+        return SignificanceResult(NaN, NaN)
+
+    n = pvalues.shape[axis]
+    # used to convert Python scalar to the right dtype
+    one = xp.asarray(1, dtype=pvalues.dtype)
+
+    if method == 'fisher':
+        statistic = -2 * xp.sum(xp.log(pvalues), axis=axis)
+        chi2 = _SimpleChi2(2*n*one)
+        pval = _get_pvalue(statistic, chi2, alternative='greater',
+                           symmetric=False, xp=xp)
+    elif method == 'pearson':
+        statistic = 2 * xp.sum(xp.log1p(-pvalues), axis=axis)
+        chi2 = _SimpleChi2(2*n*one)
+        pval = _get_pvalue(-statistic, chi2, alternative='less', symmetric=False, xp=xp)
+    elif method == 'mudholkar_george':
+        normalizing_factor = math.sqrt(3/n)/xp.pi
+        statistic = (-xp.sum(xp.log(pvalues), axis=axis)
+                     + xp.sum(xp.log1p(-pvalues), axis=axis))
+        nu = 5*n  + 4
+        approx_factor = math.sqrt(nu / (nu - 2))
+        t = _SimpleStudentT(nu*one)
+        pval = _get_pvalue(statistic * normalizing_factor * approx_factor, t,
+                           alternative="greater", xp=xp)
+    elif method == 'tippett':
+        statistic = xp.min(pvalues, axis=axis)
+        beta = _SimpleBeta(one, n*one)
+        pval = _get_pvalue(statistic, beta, alternative='less', symmetric=False, xp=xp)
+    elif method == 'stouffer':
+        if weights is None:
+            weights = xp.ones_like(pvalues, dtype=pvalues.dtype)
+        elif weights.shape[axis] != n:
+            raise ValueError("pvalues and weights must be of the same "
+                             "length along `axis`.")
+
+        norm = _SimpleNormal()
+        Zi = norm.isf(pvalues)
+        # could use `einsum` or clever `matmul` for performance,
+        # but this is the most readable
+        statistic = (xp.sum(weights * Zi, axis=axis)
+                     / xp_vector_norm(weights, axis=axis))
+        pval = _get_pvalue(statistic, norm, alternative="greater", xp=xp)
+
+    else:
+        raise ValueError(
+            f"Invalid method {method!r}. Valid methods are 'fisher', "
+            "'pearson', 'mudholkar_george', 'tippett', and 'stouffer'"
+        )
+
+    return SignificanceResult(statistic, pval)
+
+
+@dataclass
+class QuantileTestResult:
+    r"""
+    Result of `scipy.stats.quantile_test`.
+
+    Attributes
+    ----------
+    statistic: float
+        The statistic used to calculate the p-value; either ``T1``, the
+        number of observations less than or equal to the hypothesized quantile,
+        or ``T2``, the number of observations strictly less than the
+        hypothesized quantile. Two test statistics are required to handle the
+        possibility the data was generated from a discrete or mixed
+        distribution.
+
+    statistic_type : int
+        ``1`` or ``2`` depending on which of ``T1`` or ``T2`` was used to
+        calculate the p-value respectively. ``T1`` corresponds to the
+        ``"greater"`` alternative hypothesis and ``T2`` to the ``"less"``.  For
+        the ``"two-sided"`` case, the statistic type that leads to smallest
+        p-value is used.  For significant tests, ``statistic_type = 1`` means
+        there is evidence that the population quantile is significantly greater
+        than the hypothesized value and ``statistic_type = 2`` means there is
+        evidence that it is significantly less than the hypothesized value.
+
+    pvalue : float
+        The p-value of the hypothesis test.
+    """
+    statistic: float
+    statistic_type: int
+    pvalue: float
+    _alternative: list[str] = field(repr=False)
+    _x : np.ndarray = field(repr=False)
+    _p : float = field(repr=False)
+
+    def confidence_interval(self, confidence_level=0.95):
+        """
+        Compute the confidence interval of the quantile.
+
+        Parameters
+        ----------
+        confidence_level : float, default: 0.95
+            Confidence level for the computed confidence interval
+            of the quantile. Default is 0.95.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval`` object
+            The object has attributes ``low`` and ``high`` that hold the
+            lower and upper bounds of the confidence interval.
+
+        Examples
+        --------
+        >>> import numpy as np
+        >>> import scipy.stats as stats
+        >>> p = 0.75  # quantile of interest
+        >>> q = 0  # hypothesized value of the quantile
+        >>> x = np.exp(np.arange(0, 1.01, 0.01))
+        >>> res = stats.quantile_test(x, q=q, p=p, alternative='less')
+        >>> lb, ub = res.confidence_interval()
+        >>> lb, ub
+        (-inf, 2.293318740264183)
+        >>> res = stats.quantile_test(x, q=q, p=p, alternative='two-sided')
+        >>> lb, ub = res.confidence_interval(0.9)
+        >>> lb, ub
+        (1.9542373206359396, 2.293318740264183)
+        """
+
+        alternative = self._alternative
+        p = self._p
+        x = np.sort(self._x)
+        n = len(x)
+        bd = stats.binom(n, p)
+
+        if confidence_level <= 0 or confidence_level >= 1:
+            message = "`confidence_level` must be a number between 0 and 1."
+            raise ValueError(message)
+
+        low_index = np.nan
+        high_index = np.nan
+
+        if alternative == 'less':
+            p = 1 - confidence_level
+            low = -np.inf
+            high_index = int(bd.isf(p))
+            high = x[high_index] if high_index < n else np.nan
+        elif alternative == 'greater':
+            p = 1 - confidence_level
+            low_index = int(bd.ppf(p)) - 1
+            low = x[low_index] if low_index >= 0 else np.nan
+            high = np.inf
+        elif alternative == 'two-sided':
+            p = (1 - confidence_level) / 2
+            low_index = int(bd.ppf(p)) - 1
+            low = x[low_index] if low_index >= 0 else np.nan
+            high_index = int(bd.isf(p))
+            high = x[high_index] if high_index < n else np.nan
+
+        return ConfidenceInterval(low, high)
+
+
+def quantile_test_iv(x, q, p, alternative):
+
+    x = np.atleast_1d(x)
+    message = '`x` must be a one-dimensional array of numbers.'
+    if x.ndim != 1 or not np.issubdtype(x.dtype, np.number):
+        raise ValueError(message)
+
+    q = np.array(q)[()]
+    message = "`q` must be a scalar."
+    if q.ndim != 0 or not np.issubdtype(q.dtype, np.number):
+        raise ValueError(message)
+
+    p = np.array(p)[()]
+    message = "`p` must be a float strictly between 0 and 1."
+    if p.ndim != 0 or p >= 1 or p <= 0:
+        raise ValueError(message)
+
+    alternatives = {'two-sided', 'less', 'greater'}
+    message = f"`alternative` must be one of {alternatives}"
+    if alternative not in alternatives:
+        raise ValueError(message)
+
+    return x, q, p, alternative
+
+
+def quantile_test(x, *, q=0, p=0.5, alternative='two-sided'):
+    r"""
+    Perform a quantile test and compute a confidence interval of the quantile.
+
+    This function tests the null hypothesis that `q` is the value of the
+    quantile associated with probability `p` of the population underlying
+    sample `x`. For example, with default parameters, it tests that the
+    median of the population underlying `x` is zero. The function returns an
+    object including the test statistic, a p-value, and a method for computing
+    the confidence interval around the quantile.
+
+    Parameters
+    ----------
+    x : array_like
+        A one-dimensional sample.
+    q : float, default: 0
+        The hypothesized value of the quantile.
+    p : float, default: 0.5
+        The probability associated with the quantile; i.e. the proportion of
+        the population less than `q` is `p`. Must be strictly between 0 and
+        1.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+        The following options are available (default is 'two-sided'):
+
+        * 'two-sided': the quantile associated with the probability `p`
+          is not `q`.
+        * 'less': the quantile associated with the probability `p` is less
+          than `q`.
+        * 'greater': the quantile associated with the probability `p` is
+          greater than `q`.
+
+    Returns
+    -------
+    result : QuantileTestResult
+        An object with the following attributes:
+
+        statistic : float
+            One of two test statistics that may be used in the quantile test.
+            The first test statistic, ``T1``, is the proportion of samples in
+            `x` that are less than or equal to the hypothesized quantile
+            `q`. The second test statistic, ``T2``, is the proportion of
+            samples in `x` that are strictly less than the hypothesized
+            quantile `q`.
+
+            When ``alternative = 'greater'``, ``T1`` is used to calculate the
+            p-value and ``statistic`` is set to ``T1``.
+
+            When ``alternative = 'less'``, ``T2`` is used to calculate the
+            p-value and ``statistic`` is set to ``T2``.
+
+            When ``alternative = 'two-sided'``, both ``T1`` and ``T2`` are
+            considered, and the one that leads to the smallest p-value is used.
+
+        statistic_type : int
+            Either `1` or `2` depending on which of ``T1`` or ``T2`` was
+            used to calculate the p-value.
+
+        pvalue : float
+            The p-value associated with the given alternative.
+
+        The object also has the following method:
+
+        confidence_interval(confidence_level=0.95)
+            Computes a confidence interval around the the
+            population quantile associated with the probability `p`. The
+            confidence interval is returned in a ``namedtuple`` with
+            fields `low` and `high`.  Values are `nan` when there are
+            not enough observations to compute the confidence interval at
+            the desired confidence.
+
+    Notes
+    -----
+    This test and its method for computing confidence intervals are
+    non-parametric. They are valid if and only if the observations are i.i.d.
+
+    The implementation of the test follows Conover [1]_. Two test statistics
+    are considered.
+
+    ``T1``: The number of observations in `x` less than or equal to `q`.
+
+        ``T1 = (x <= q).sum()``
+
+    ``T2``: The number of observations in `x` strictly less than `q`.
+
+        ``T2 = (x < q).sum()``
+
+    The use of two test statistics is necessary to handle the possibility that
+    `x` was generated from a discrete or mixed distribution.
+
+    The null hypothesis for the test is:
+
+        H0: The :math:`p^{\mathrm{th}}` population quantile is `q`.
+
+    and the null distribution for each test statistic is
+    :math:`\mathrm{binom}\left(n, p\right)`. When ``alternative='less'``,
+    the alternative hypothesis is:
+
+        H1: The :math:`p^{\mathrm{th}}` population quantile is less than `q`.
+
+    and the p-value is the probability that the binomial random variable
+
+    .. math::
+        Y \sim \mathrm{binom}\left(n, p\right)
+
+    is greater than or equal to the observed value ``T2``.
+
+    When ``alternative='greater'``, the alternative hypothesis is:
+
+        H1: The :math:`p^{\mathrm{th}}` population quantile is greater than `q`
+
+    and the p-value is the probability that the binomial random variable Y
+    is less than or equal to the observed value ``T1``.
+
+    When ``alternative='two-sided'``, the alternative hypothesis is
+
+        H1: `q` is not the :math:`p^{\mathrm{th}}` population quantile.
+
+    and the p-value is twice the smaller of the p-values for the ``'less'``
+    and ``'greater'`` cases. Both of these p-values can exceed 0.5 for the same
+    data, so the value is clipped into the interval :math:`[0, 1]`.
+
+    The approach for confidence intervals is attributed to Thompson [2]_ and
+    later proven to be applicable to any set of i.i.d. samples [3]_. The
+    computation is based on the observation that the probability of a quantile
+    :math:`q` to be larger than any observations :math:`x_m (1\leq m \leq N)`
+    can be computed as
+
+    .. math::
+
+        \mathbb{P}(x_m \leq q) = 1 - \sum_{k=0}^{m-1} \binom{N}{k}
+        q^k(1-q)^{N-k}
+
+    By default, confidence intervals are computed for a 95% confidence level.
+    A common interpretation of a 95% confidence intervals is that if i.i.d.
+    samples are drawn repeatedly from the same population and confidence
+    intervals are formed each time, the confidence interval will contain the
+    true value of the specified quantile in approximately 95% of trials.
+
+    A similar function is available in the QuantileNPCI R package [4]_. The
+    foundation is the same, but it computes the confidence interval bounds by
+    doing interpolations between the sample values, whereas this function uses
+    only sample values as bounds. Thus, ``quantile_test.confidence_interval``
+    returns more conservative intervals (i.e., larger).
+
+    The same computation of confidence intervals for quantiles is included in
+    the confintr package [5]_.
+
+    Two-sided confidence intervals are not guaranteed to be optimal; i.e.,
+    there may exist a tighter interval that may contain the quantile of
+    interest with probability larger than the confidence level.
+    Without further assumption on the samples (e.g., the nature of the
+    underlying distribution), the one-sided intervals are optimally tight.
+
+    References
+    ----------
+    .. [1] W. J. Conover. Practical Nonparametric Statistics, 3rd Ed. 1999.
+    .. [2] W. R. Thompson, "On Confidence Ranges for the Median and Other
+       Expectation Distributions for Populations of Unknown Distribution
+       Form," The Annals of Mathematical Statistics, vol. 7, no. 3,
+       pp. 122-128, 1936, Accessed: Sep. 18, 2019. [Online]. Available:
+       https://www.jstor.org/stable/2957563.
+    .. [3] H. A. David and H. N. Nagaraja, "Order Statistics in Nonparametric
+       Inference" in Order Statistics, John Wiley & Sons, Ltd, 2005, pp.
+       159-170. Available:
+       https://onlinelibrary.wiley.com/doi/10.1002/0471722162.ch7.
+    .. [4] N. Hutson, A. Hutson, L. Yan, "QuantileNPCI: Nonparametric
+       Confidence Intervals for Quantiles," R package,
+       https://cran.r-project.org/package=QuantileNPCI
+    .. [5] M. Mayer, "confintr: Confidence Intervals," R package,
+       https://cran.r-project.org/package=confintr
+
+
+    Examples
+    --------
+
+    Suppose we wish to test the null hypothesis that the median of a population
+    is equal to 0.5. We choose a confidence level of 99%; that is, we will
+    reject the null hypothesis in favor of the alternative if the p-value is
+    less than 0.01.
+
+    When testing random variates from the standard uniform distribution, which
+    has a median of 0.5, we expect the data to be consistent with the null
+    hypothesis most of the time.
+
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(6981396440634228121)
+    >>> rvs = stats.uniform.rvs(size=100, random_state=rng)
+    >>> stats.quantile_test(rvs, q=0.5, p=0.5)
+    QuantileTestResult(statistic=45, statistic_type=1, pvalue=0.36820161732669576)
+
+    As expected, the p-value is not below our threshold of 0.01, so
+    we cannot reject the null hypothesis.
+
+    When testing data from the standard *normal* distribution, which has a
+    median of 0, we would expect the null hypothesis to be rejected.
+
+    >>> rvs = stats.norm.rvs(size=100, random_state=rng)
+    >>> stats.quantile_test(rvs, q=0.5, p=0.5)
+    QuantileTestResult(statistic=67, statistic_type=2, pvalue=0.0008737198369123724)
+
+    Indeed, the p-value is lower than our threshold of 0.01, so we reject the
+    null hypothesis in favor of the default "two-sided" alternative: the median
+    of the population is *not* equal to 0.5.
+
+    However, suppose we were to test the null hypothesis against the
+    one-sided alternative that the median of the population is *greater* than
+    0.5. Since the median of the standard normal is less than 0.5, we would not
+    expect the null hypothesis to be rejected.
+
+    >>> stats.quantile_test(rvs, q=0.5, p=0.5, alternative='greater')
+    QuantileTestResult(statistic=67, statistic_type=1, pvalue=0.9997956114162866)
+
+    Unsurprisingly, with a p-value greater than our threshold, we would not
+    reject the null hypothesis in favor of the chosen alternative.
+
+    The quantile test can be used for any quantile, not only the median. For
+    example, we can test whether the third quartile of the distribution
+    underlying the sample is greater than 0.6.
+
+    >>> rvs = stats.uniform.rvs(size=100, random_state=rng)
+    >>> stats.quantile_test(rvs, q=0.6, p=0.75, alternative='greater')
+    QuantileTestResult(statistic=64, statistic_type=1, pvalue=0.00940696592998271)
+
+    The p-value is lower than the threshold. We reject the null hypothesis in
+    favor of the alternative: the third quartile of the distribution underlying
+    our sample is greater than 0.6.
+
+    `quantile_test` can also compute confidence intervals for any quantile.
+
+    >>> rvs = stats.norm.rvs(size=100, random_state=rng)
+    >>> res = stats.quantile_test(rvs, q=0.6, p=0.75)
+    >>> ci = res.confidence_interval(confidence_level=0.95)
+    >>> ci
+    ConfidenceInterval(low=0.284491604437432, high=0.8912531024914844)
+
+    When testing a one-sided alternative, the confidence interval contains
+    all observations such that if passed as `q`, the p-value of the
+    test would be greater than 0.05, and therefore the null hypothesis
+    would not be rejected. For example:
+
+    >>> rvs.sort()
+    >>> q, p, alpha = 0.6, 0.75, 0.95
+    >>> res = stats.quantile_test(rvs, q=q, p=p, alternative='less')
+    >>> ci = res.confidence_interval(confidence_level=alpha)
+    >>> for x in rvs[rvs <= ci.high]:
+    ...     res = stats.quantile_test(rvs, q=x, p=p, alternative='less')
+    ...     assert res.pvalue > 1-alpha
+    >>> for x in rvs[rvs > ci.high]:
+    ...     res = stats.quantile_test(rvs, q=x, p=p, alternative='less')
+    ...     assert res.pvalue < 1-alpha
+
+    Also, if a 95% confidence interval is repeatedly generated for random
+    samples, the confidence interval will contain the true quantile value in
+    approximately 95% of replications.
+
+    >>> dist = stats.rayleigh() # our "unknown" distribution
+    >>> p = 0.2
+    >>> true_stat = dist.ppf(p) # the true value of the statistic
+    >>> n_trials = 1000
+    >>> quantile_ci_contains_true_stat = 0
+    >>> for i in range(n_trials):
+    ...     data = dist.rvs(size=100, random_state=rng)
+    ...     res = stats.quantile_test(data, p=p)
+    ...     ci = res.confidence_interval(0.95)
+    ...     if ci[0] < true_stat < ci[1]:
+    ...         quantile_ci_contains_true_stat += 1
+    >>> quantile_ci_contains_true_stat >= 950
+    True
+
+    This works with any distribution and any quantile, as long as the samples
+    are i.i.d.
+    """
+    # Implementation carefully follows [1] 3.2
+    # "H0: the p*th quantile of X is x*"
+    # To facilitate comparison with [1], we'll use variable names that
+    # best match Conover's notation
+    X, x_star, p_star, H1 = quantile_test_iv(x, q, p, alternative)
+
+    # "We will use two test statistics in this test. Let T1 equal "
+    # "the number of observations less than or equal to x*, and "
+    # "let T2 equal the number of observations less than x*."
+    T1 = (X <= x_star).sum()
+    T2 = (X < x_star).sum()
+
+    # "The null distribution of the test statistics T1 and T2 is "
+    # "the binomial distribution, with parameters n = sample size, and "
+    # "p = p* as given in the null hypothesis.... Y has the binomial "
+    # "distribution with parameters n and p*."
+    n = len(X)
+    Y = stats.binom(n=n, p=p_star)
+
+    # "H1: the p* population quantile is less than x*"
+    if H1 == 'less':
+        # "The p-value is the probability that a binomial random variable Y "
+        # "is greater than *or equal to* the observed value of T2...using p=p*"
+        pvalue = Y.sf(T2-1)  # Y.pmf(T2) + Y.sf(T2)
+        statistic = T2
+        statistic_type = 2
+    # "H1: the p* population quantile is greater than x*"
+    elif H1 == 'greater':
+        # "The p-value is the probability that a binomial random variable Y "
+        # "is less than or equal to the observed value of T1... using p = p*"
+        pvalue = Y.cdf(T1)
+        statistic = T1
+        statistic_type = 1
+    # "H1: x* is not the p*th population quantile"
+    elif H1 == 'two-sided':
+        # "The p-value is twice the smaller of the probabilities that a
+        # binomial random variable Y is less than or equal to the observed
+        # value of T1 or greater than or equal to the observed value of T2
+        # using p=p*."
+        # Note: both one-sided p-values can exceed 0.5 for the same data, so
+        # `clip`
+        pvalues = [Y.cdf(T1), Y.sf(T2 - 1)]  # [greater, less]
+        sorted_idx = np.argsort(pvalues)
+        pvalue = np.clip(2*pvalues[sorted_idx[0]], 0, 1)
+        if sorted_idx[0]:
+            statistic, statistic_type = T2, 2
+        else:
+            statistic, statistic_type = T1, 1
+
+    return QuantileTestResult(
+        statistic=statistic,
+        statistic_type=statistic_type,
+        pvalue=pvalue,
+        _alternative=H1,
+        _x=X,
+        _p=p_star
+    )
+
+
+#####################################
+#       STATISTICAL DISTANCES       #
+#####################################
+
+
+def wasserstein_distance_nd(u_values, v_values, u_weights=None, v_weights=None):
+    r"""
+    Compute the Wasserstein-1 distance between two N-D discrete distributions.
+
+    The Wasserstein distance, also called the Earth mover's distance or the
+    optimal transport distance, is a similarity metric between two probability
+    distributions [1]_. In the discrete case, the Wasserstein distance can be
+    understood as the cost of an optimal transport plan to convert one
+    distribution into the other. The cost is calculated as the product of the
+    amount of probability mass being moved and the distance it is being moved.
+    A brief and intuitive introduction can be found at [2]_.
+
+    .. versionadded:: 1.13.0
+
+    Parameters
+    ----------
+    u_values : 2d array_like
+        A sample from a probability distribution or the support (set of all
+        possible values) of a probability distribution. Each element along
+        axis 0 is an observation or possible value, and axis 1 represents the
+        dimensionality of the distribution; i.e., each row is a vector
+        observation or possible value.
+
+    v_values : 2d array_like
+        A sample from or the support of a second distribution.
+
+    u_weights, v_weights : 1d array_like, optional
+        Weights or counts corresponding with the sample or probability masses
+        corresponding with the support values. Sum of elements must be positive
+        and finite. If unspecified, each value is assigned the same weight.
+
+    Returns
+    -------
+    distance : float
+        The computed distance between the distributions.
+
+    Notes
+    -----
+    Given two probability mass functions, :math:`u`
+    and :math:`v`, the first Wasserstein distance between the distributions
+    using the Euclidean norm is:
+
+    .. math::
+
+        l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int \| x-y \|_2 \mathrm{d} \pi (x, y)
+
+    where :math:`\Gamma (u, v)` is the set of (probability) distributions on
+    :math:`\mathbb{R}^n \times \mathbb{R}^n` whose marginals are :math:`u` and
+    :math:`v` on the first and second factors respectively. For a given value
+    :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position
+    :math:`x`, and the same for :math:`v(x)`.
+
+    This is also called the optimal transport problem or the Monge problem.
+    Let the finite point sets :math:`\{x_i\}` and :math:`\{y_j\}` denote
+    the support set of probability mass function :math:`u` and :math:`v`
+    respectively. The Monge problem can be expressed as follows,
+
+    Let :math:`\Gamma` denote the transport plan, :math:`D` denote the
+    distance matrix and,
+
+    .. math::
+
+        x = \text{vec}(\Gamma)          \\
+        c = \text{vec}(D)               \\
+        b = \begin{bmatrix}
+                u\\
+                v\\
+            \end{bmatrix}
+
+    The :math:`\text{vec}()` function denotes the Vectorization function
+    that transforms a matrix into a column vector by vertically stacking
+    the columns of the matrix.
+    The transport plan :math:`\Gamma` is a matrix :math:`[\gamma_{ij}]` in
+    which :math:`\gamma_{ij}` is a positive value representing the amount of
+    probability mass transported from :math:`u(x_i)` to :math:`v(y_i)`.
+    Summing over the rows of :math:`\Gamma` should give the source distribution
+    :math:`u` : :math:`\sum_j \gamma_{ij} = u(x_i)` holds for all :math:`i`
+    and summing over the columns of :math:`\Gamma` should give the target
+    distribution :math:`v`: :math:`\sum_i \gamma_{ij} = v(y_j)` holds for all
+    :math:`j`.
+    The distance matrix :math:`D` is a matrix :math:`[d_{ij}]`, in which
+    :math:`d_{ij} = d(x_i, y_j)`.
+
+    Given :math:`\Gamma`, :math:`D`, :math:`b`, the Monge problem can be
+    transformed into a linear programming problem by
+    taking :math:`A x = b` as constraints and :math:`z = c^T x` as minimization
+    target (sum of costs) , where matrix :math:`A` has the form
+
+    .. math::
+
+        \begin{array} {rrrr|rrrr|r|rrrr}
+            1 & 1 & \dots & 1 & 0 & 0 & \dots & 0 & \dots & 0 & 0 & \dots &
+                0 \cr
+            0 & 0 & \dots & 0 & 1 & 1 & \dots & 1 & \dots & 0 & 0 &\dots &
+                0 \cr
+            \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots
+                & \vdots & \vdots & \vdots & \vdots & \ddots & \vdots  \cr
+            0 & 0 & \dots & 0 & 0 & 0 & \dots & 0 & \dots & 1 & 1 & \dots &
+                1 \cr \hline
+
+            1 & 0 & \dots & 0 & 1 & 0 & \dots & \dots & \dots & 1 & 0 & \dots &
+                0 \cr
+            0 & 1 & \dots & 0 & 0 & 1 & \dots & \dots & \dots & 0 & 1 & \dots &
+                0 \cr
+            \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots &
+                \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \cr
+            0 & 0 & \dots & 1 & 0 & 0 & \dots & 1 & \dots & 0 & 0 & \dots & 1
+        \end{array}
+
+    By solving the dual form of the above linear programming problem (with
+    solution :math:`y^*`), the Wasserstein distance :math:`l_1 (u, v)` can
+    be computed as :math:`b^T y^*`.
+
+    The above solution is inspired by Vincent Herrmann's blog [3]_ . For a
+    more thorough explanation, see [4]_ .
+
+    The input distributions can be empirical, therefore coming from samples
+    whose values are effectively inputs of the function, or they can be seen as
+    generalized functions, in which case they are weighted sums of Dirac delta
+    functions located at the specified values.
+
+    References
+    ----------
+    .. [1] "Wasserstein metric",
+           https://en.wikipedia.org/wiki/Wasserstein_metric
+    .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log,
+           https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance.
+    .. [3] Hermann, Vincent. "Wasserstein GAN and the Kantorovich-Rubinstein
+           Duality". https://vincentherrmann.github.io/blog/wasserstein/.
+    .. [4] Peyré, Gabriel, and Marco Cuturi. "Computational optimal
+           transport." Center for Research in Economics and Statistics
+           Working Papers 2017-86 (2017).
+
+    See Also
+    --------
+    wasserstein_distance: Compute the Wasserstein-1 distance between two
+        1D discrete distributions.
+
+    Examples
+    --------
+    Compute the Wasserstein distance between two three-dimensional samples,
+    each with two observations.
+
+    >>> from scipy.stats import wasserstein_distance_nd
+    >>> wasserstein_distance_nd([[0, 2, 3], [1, 2, 5]], [[3, 2, 3], [4, 2, 5]])
+    3.0
+
+    Compute the Wasserstein distance between two two-dimensional distributions
+    with three and two weighted observations, respectively.
+
+    >>> wasserstein_distance_nd([[0, 2.75], [2, 209.3], [0, 0]],
+    ...                      [[0.2, 0.322], [4.5, 25.1808]],
+    ...                      [0.4, 5.2, 0.114], [0.8, 1.5])
+    174.15840245217169
+    """
+    m, n = len(u_values), len(v_values)
+    u_values = asarray(u_values)
+    v_values = asarray(v_values)
+
+    if u_values.ndim > 2 or v_values.ndim > 2:
+        raise ValueError('Invalid input values. The inputs must have either '
+                         'one or two dimensions.')
+    # if dimensions are not equal throw error
+    if u_values.ndim != v_values.ndim:
+        raise ValueError('Invalid input values. Dimensions of inputs must be '
+                         'equal.')
+    # if data is 1D then call the cdf_distance function
+    if u_values.ndim == 1 and v_values.ndim == 1:
+        return _cdf_distance(1, u_values, v_values, u_weights, v_weights)
+
+    u_values, u_weights = _validate_distribution(u_values, u_weights)
+    v_values, v_weights = _validate_distribution(v_values, v_weights)
+    # if number of columns is not equal throw error
+    if u_values.shape[1] != v_values.shape[1]:
+        raise ValueError('Invalid input values. If two-dimensional, '
+                         '`u_values` and `v_values` must have the same '
+                         'number of columns.')
+
+    # if data contains np.inf then return inf or nan
+    if np.any(np.isinf(u_values)) ^ np.any(np.isinf(v_values)):
+        return np.inf
+    elif np.any(np.isinf(u_values)) and np.any(np.isinf(v_values)):
+        return np.nan
+
+    # create constraints
+    A_upper_part = sparse.block_diag((np.ones((1, n)), ) * m)
+    A_lower_part = sparse.hstack((sparse.eye(n), ) * m)
+    # sparse constraint matrix of size (m + n)*(m * n)
+    A = sparse.vstack((A_upper_part, A_lower_part))
+    A = sparse.coo_array(A)
+
+    # get cost matrix
+    D = distance_matrix(u_values, v_values, p=2)
+    cost = D.ravel()
+
+    # create the minimization target
+    p_u = np.full(m, 1/m) if u_weights is None else u_weights/np.sum(u_weights)
+    p_v = np.full(n, 1/n) if v_weights is None else v_weights/np.sum(v_weights)
+    b = np.concatenate((p_u, p_v), axis=0)
+
+    # solving LP
+    constraints = LinearConstraint(A=A.T, ub=cost)
+    opt_res = milp(c=-b, constraints=constraints, bounds=(-np.inf, np.inf))
+    return -opt_res.fun
+
+
+def wasserstein_distance(u_values, v_values, u_weights=None, v_weights=None):
+    r"""
+    Compute the Wasserstein-1 distance between two 1D discrete distributions.
+
+    The Wasserstein distance, also called the Earth mover's distance or the
+    optimal transport distance, is a similarity metric between two probability
+    distributions [1]_. In the discrete case, the Wasserstein distance can be
+    understood as the cost of an optimal transport plan to convert one
+    distribution into the other. The cost is calculated as the product of the
+    amount of probability mass being moved and the distance it is being moved.
+    A brief and intuitive introduction can be found at [2]_.
+
+    .. versionadded:: 1.0.0
+
+    Parameters
+    ----------
+    u_values : 1d array_like
+        A sample from a probability distribution or the support (set of all
+        possible values) of a probability distribution. Each element is an
+        observation or possible value.
+
+    v_values : 1d array_like
+        A sample from or the support of a second distribution.
+
+    u_weights, v_weights : 1d array_like, optional
+        Weights or counts corresponding with the sample or probability masses
+        corresponding with the support values. Sum of elements must be positive
+        and finite. If unspecified, each value is assigned the same weight.
+
+    Returns
+    -------
+    distance : float
+        The computed distance between the distributions.
+
+    Notes
+    -----
+    Given two 1D probability mass functions, :math:`u` and :math:`v`, the first
+    Wasserstein distance between the distributions is:
+
+    .. math::
+
+        l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times
+        \mathbb{R}} |x-y| \mathrm{d} \pi (x, y)
+
+    where :math:`\Gamma (u, v)` is the set of (probability) distributions on
+    :math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and
+    :math:`v` on the first and second factors respectively. For a given value
+    :math:`x`, :math:`u(x)` gives the probability of :math:`u` at position
+    :math:`x`, and the same for :math:`v(x)`.
+
+    If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and
+    :math:`v`, this distance also equals to:
+
+    .. math::
+
+        l_1(u, v) = \int_{-\infty}^{+\infty} |U-V|
+
+    See [3]_ for a proof of the equivalence of both definitions.
+
+    The input distributions can be empirical, therefore coming from samples
+    whose values are effectively inputs of the function, or they can be seen as
+    generalized functions, in which case they are weighted sums of Dirac delta
+    functions located at the specified values.
+
+    References
+    ----------
+    .. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric
+    .. [2] Lili Weng, "What is Wasserstein distance?", Lil'log,
+           https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance.
+    .. [3] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related
+           Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`.
+
+    See Also
+    --------
+    wasserstein_distance_nd: Compute the Wasserstein-1 distance between two N-D
+        discrete distributions.
+
+    Examples
+    --------
+    >>> from scipy.stats import wasserstein_distance
+    >>> wasserstein_distance([0, 1, 3], [5, 6, 8])
+    5.0
+    >>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2])
+    0.25
+    >>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4],
+    ...                      [1.4, 0.9, 3.1, 7.2], [3.2, 3.5])
+    4.0781331438047861
+
+    """
+    return _cdf_distance(1, u_values, v_values, u_weights, v_weights)
+
+
+def energy_distance(u_values, v_values, u_weights=None, v_weights=None):
+    r"""Compute the energy distance between two 1D distributions.
+
+    .. versionadded:: 1.0.0
+
+    Parameters
+    ----------
+    u_values, v_values : array_like
+        Values observed in the (empirical) distribution.
+    u_weights, v_weights : array_like, optional
+        Weight for each value. If unspecified, each value is assigned the same
+        weight.
+        `u_weights` (resp. `v_weights`) must have the same length as
+        `u_values` (resp. `v_values`). If the weight sum differs from 1, it
+        must still be positive and finite so that the weights can be normalized
+        to sum to 1.
+
+    Returns
+    -------
+    distance : float
+        The computed distance between the distributions.
+
+    Notes
+    -----
+    The energy distance between two distributions :math:`u` and :math:`v`, whose
+    respective CDFs are :math:`U` and :math:`V`, equals to:
+
+    .. math::
+
+        D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| -
+        \mathbb E|Y - Y'| \right)^{1/2}
+
+    where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are
+    independent random variables whose probability distribution is :math:`u`
+    (resp. :math:`v`).
+
+    Sometimes the square of this quantity is referred to as the "energy
+    distance" (e.g. in [2]_, [4]_), but as noted in [1]_ and [3]_, only the
+    definition above satisfies the axioms of a distance function (metric).
+
+    As shown in [2]_, for one-dimensional real-valued variables, the energy
+    distance is linked to the non-distribution-free version of the Cramér-von
+    Mises distance:
+
+    .. math::
+
+        D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2
+        \right)^{1/2}
+
+    Note that the common Cramér-von Mises criterion uses the distribution-free
+    version of the distance. See [2]_ (section 2), for more details about both
+    versions of the distance.
+
+    The input distributions can be empirical, therefore coming from samples
+    whose values are effectively inputs of the function, or they can be seen as
+    generalized functions, in which case they are weighted sums of Dirac delta
+    functions located at the specified values.
+
+    References
+    ----------
+    .. [1] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews:
+           Computational Statistics, 8(1):27-38 (2015).
+    .. [2] Szekely "E-statistics: The energy of statistical samples." Bowling
+           Green State University, Department of Mathematics and Statistics,
+           Technical Report 02-16 (2002).
+    .. [3] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance
+    .. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
+           Munos "The Cramer Distance as a Solution to Biased Wasserstein
+           Gradients" (2017). :arXiv:`1705.10743`.
+
+    Examples
+    --------
+    >>> from scipy.stats import energy_distance
+    >>> energy_distance([0], [2])
+    2.0000000000000004
+    >>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2])
+    1.0000000000000002
+    >>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ],
+    ...                 [2.1, 4.2, 7.4, 8. ], [7.6, 8.8])
+    0.88003340976158217
+
+    """
+    return np.sqrt(2) * _cdf_distance(2, u_values, v_values,
+                                      u_weights, v_weights)
+
+
+def _cdf_distance(p, u_values, v_values, u_weights=None, v_weights=None):
+    r"""
+    Compute, between two one-dimensional distributions :math:`u` and
+    :math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the
+    statistical distance that is defined as:
+
+    .. math::
+
+        l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p}
+
+    p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2
+    gives the energy distance.
+
+    Parameters
+    ----------
+    u_values, v_values : array_like
+        Values observed in the (empirical) distribution.
+    u_weights, v_weights : array_like, optional
+        Weight for each value. If unspecified, each value is assigned the same
+        weight.
+        `u_weights` (resp. `v_weights`) must have the same length as
+        `u_values` (resp. `v_values`). If the weight sum differs from 1, it
+        must still be positive and finite so that the weights can be normalized
+        to sum to 1.
+
+    Returns
+    -------
+    distance : float
+        The computed distance between the distributions.
+
+    Notes
+    -----
+    The input distributions can be empirical, therefore coming from samples
+    whose values are effectively inputs of the function, or they can be seen as
+    generalized functions, in which case they are weighted sums of Dirac delta
+    functions located at the specified values.
+
+    References
+    ----------
+    .. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
+           Munos "The Cramer Distance as a Solution to Biased Wasserstein
+           Gradients" (2017). :arXiv:`1705.10743`.
+
+    """
+    u_values, u_weights = _validate_distribution(u_values, u_weights)
+    v_values, v_weights = _validate_distribution(v_values, v_weights)
+
+    u_sorter = np.argsort(u_values)
+    v_sorter = np.argsort(v_values)
+
+    all_values = np.concatenate((u_values, v_values))
+    all_values.sort(kind='mergesort')
+
+    # Compute the differences between pairs of successive values of u and v.
+    deltas = np.diff(all_values)
+
+    # Get the respective positions of the values of u and v among the values of
+    # both distributions.
+    u_cdf_indices = u_values[u_sorter].searchsorted(all_values[:-1], 'right')
+    v_cdf_indices = v_values[v_sorter].searchsorted(all_values[:-1], 'right')
+
+    # Calculate the CDFs of u and v using their weights, if specified.
+    if u_weights is None:
+        u_cdf = u_cdf_indices / u_values.size
+    else:
+        u_sorted_cumweights = np.concatenate(([0],
+                                              np.cumsum(u_weights[u_sorter])))
+        u_cdf = u_sorted_cumweights[u_cdf_indices] / u_sorted_cumweights[-1]
+
+    if v_weights is None:
+        v_cdf = v_cdf_indices / v_values.size
+    else:
+        v_sorted_cumweights = np.concatenate(([0],
+                                              np.cumsum(v_weights[v_sorter])))
+        v_cdf = v_sorted_cumweights[v_cdf_indices] / v_sorted_cumweights[-1]
+
+    # Compute the value of the integral based on the CDFs.
+    # If p = 1 or p = 2, we avoid using np.power, which introduces an overhead
+    # of about 15%.
+    if p == 1:
+        return np.sum(np.multiply(np.abs(u_cdf - v_cdf), deltas))
+    if p == 2:
+        return np.sqrt(np.sum(np.multiply(np.square(u_cdf - v_cdf), deltas)))
+    return np.power(np.sum(np.multiply(np.power(np.abs(u_cdf - v_cdf), p),
+                                       deltas)), 1/p)
+
+
+def _validate_distribution(values, weights):
+    """
+    Validate the values and weights from a distribution input of `cdf_distance`
+    and return them as ndarray objects.
+
+    Parameters
+    ----------
+    values : array_like
+        Values observed in the (empirical) distribution.
+    weights : array_like
+        Weight for each value.
+
+    Returns
+    -------
+    values : ndarray
+        Values as ndarray.
+    weights : ndarray
+        Weights as ndarray.
+
+    """
+    # Validate the value array.
+    values = np.asarray(values, dtype=float)
+    if len(values) == 0:
+        raise ValueError("Distribution can't be empty.")
+
+    # Validate the weight array, if specified.
+    if weights is not None:
+        weights = np.asarray(weights, dtype=float)
+        if len(weights) != len(values):
+            raise ValueError('Value and weight array-likes for the same '
+                             'empirical distribution must be of the same size.')
+        if np.any(weights < 0):
+            raise ValueError('All weights must be non-negative.')
+        if not 0 < np.sum(weights) < np.inf:
+            raise ValueError('Weight array-like sum must be positive and '
+                             'finite. Set as None for an equal distribution of '
+                             'weight.')
+
+        return values, weights
+
+    return values, None
+
+
+#####################################
+#         SUPPORT FUNCTIONS         #
+#####################################
+
+RepeatedResults = namedtuple('RepeatedResults', ('values', 'counts'))
+
+
+@_deprecated("`scipy.stats.find_repeats` is deprecated as of SciPy 1.15.0 "
+             "and will be removed in SciPy 1.17.0. Please use "
+             "`numpy.unique`/`numpy.unique_counts` instead.")
+def find_repeats(arr):
+    """Find repeats and repeat counts.
+
+    .. deprecated:: 1.15.0
+
+        This function is deprecated as of SciPy 1.15.0 and will be removed
+        in SciPy 1.17.0. Please use `numpy.unique` / `numpy.unique_counts` instead.
+
+    Parameters
+    ----------
+    arr : array_like
+        Input array. This is cast to float64.
+
+    Returns
+    -------
+    values : ndarray
+        The unique values from the (flattened) input that are repeated.
+
+    counts : ndarray
+        Number of times the corresponding 'value' is repeated.
+
+    Notes
+    -----
+    In numpy >= 1.9 `numpy.unique` provides similar functionality. The main
+    difference is that `find_repeats` only returns repeated values.
+
+    Examples
+    --------
+    >>> from scipy import stats
+    >>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5])
+    RepeatedResults(values=array([2.]), counts=array([4]))
+
+    >>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
+    RepeatedResults(values=array([4.,  5.]), counts=array([2, 2]))
+
+    """
+    # Note: always copies.
+    return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64)))
+
+
+def _sum_of_squares(a, axis=0):
+    """Square each element of the input array, and return the sum(s) of that.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : int or None, optional
+        Axis along which to calculate. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    sum_of_squares : ndarray
+        The sum along the given axis for (a**2).
+
+    See Also
+    --------
+    _square_of_sums : The square(s) of the sum(s) (the opposite of
+        `_sum_of_squares`).
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    return np.sum(a*a, axis)
+
+
+def _square_of_sums(a, axis=0):
+    """Sum elements of the input array, and return the square(s) of that sum.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : int or None, optional
+        Axis along which to calculate. Default is 0. If None, compute over
+        the whole array `a`.
+
+    Returns
+    -------
+    square_of_sums : float or ndarray
+        The square of the sum over `axis`.
+
+    See Also
+    --------
+    _sum_of_squares : The sum of squares (the opposite of `square_of_sums`).
+
+    """
+    a, axis = _chk_asarray(a, axis)
+    s = np.sum(a, axis)
+    if not np.isscalar(s):
+        return s.astype(float) * s
+    else:
+        return float(s) * s
+
+
+def rankdata(a, method='average', *, axis=None, nan_policy='propagate'):
+    """Assign ranks to data, dealing with ties appropriately.
+
+    By default (``axis=None``), the data array is first flattened, and a flat
+    array of ranks is returned. Separately reshape the rank array to the
+    shape of the data array if desired (see Examples).
+
+    Ranks begin at 1.  The `method` argument controls how ranks are assigned
+    to equal values.  See [1]_ for further discussion of ranking methods.
+
+    Parameters
+    ----------
+    a : array_like
+        The array of values to be ranked.
+    method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional
+        The method used to assign ranks to tied elements.
+        The following methods are available (default is 'average'):
+
+          * 'average': The average of the ranks that would have been assigned to
+            all the tied values is assigned to each value.
+          * 'min': The minimum of the ranks that would have been assigned to all
+            the tied values is assigned to each value.  (This is also
+            referred to as "competition" ranking.)
+          * 'max': The maximum of the ranks that would have been assigned to all
+            the tied values is assigned to each value.
+          * 'dense': Like 'min', but the rank of the next highest element is
+            assigned the rank immediately after those assigned to the tied
+            elements.
+          * 'ordinal': All values are given a distinct rank, corresponding to
+            the order that the values occur in `a`.
+    axis : {None, int}, optional
+        Axis along which to perform the ranking. If ``None``, the data array
+        is first flattened.
+    nan_policy : {'propagate', 'omit', 'raise'}, optional
+        Defines how to handle when input contains nan.
+        The following options are available (default is 'propagate'):
+
+          * 'propagate': propagates nans through the rank calculation
+          * 'omit': performs the calculations ignoring nan values
+          * 'raise': raises an error
+
+        .. note::
+
+            When `nan_policy` is 'propagate', the output is an array of *all*
+            nans because ranks relative to nans in the input are undefined.
+            When `nan_policy` is 'omit', nans in `a` are ignored when ranking
+            the other values, and the corresponding locations of the output
+            are nan.
+
+        .. versionadded:: 1.10
+
+    Returns
+    -------
+    ranks : ndarray
+         An array of size equal to the size of `a`, containing rank
+         scores.
+
+    References
+    ----------
+    .. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import rankdata
+    >>> rankdata([0, 2, 3, 2])
+    array([ 1. ,  2.5,  4. ,  2.5])
+    >>> rankdata([0, 2, 3, 2], method='min')
+    array([ 1,  2,  4,  2])
+    >>> rankdata([0, 2, 3, 2], method='max')
+    array([ 1,  3,  4,  3])
+    >>> rankdata([0, 2, 3, 2], method='dense')
+    array([ 1,  2,  3,  2])
+    >>> rankdata([0, 2, 3, 2], method='ordinal')
+    array([ 1,  2,  4,  3])
+    >>> rankdata([[0, 2], [3, 2]]).reshape(2,2)
+    array([[1. , 2.5],
+          [4. , 2.5]])
+    >>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1)
+    array([[1. , 2.5, 2.5],
+           [2. , 1. , 3. ]])
+    >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="propagate")
+    array([nan, nan, nan, nan, nan, nan])
+    >>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="omit")
+    array([ 2.,  3.,  4., nan,  1., nan])
+
+    """
+    methods = ('average', 'min', 'max', 'dense', 'ordinal')
+    if method not in methods:
+        raise ValueError(f'unknown method "{method}"')
+
+    x = np.asarray(a)
+
+    if axis is None:
+        x = x.ravel()
+        axis = -1
+
+    if x.size == 0:
+        dtype = float if method == 'average' else np.dtype("long")
+        return np.empty(x.shape, dtype=dtype)
+
+    contains_nan, nan_policy = _contains_nan(x, nan_policy)
+
+    x = np.swapaxes(x, axis, -1)
+    ranks = _rankdata(x, method)
+
+    if contains_nan:
+        i_nan = (np.isnan(x) if nan_policy == 'omit'
+                 else np.isnan(x).any(axis=-1))
+        ranks = ranks.astype(float, copy=False)
+        ranks[i_nan] = np.nan
+
+    ranks = np.swapaxes(ranks, axis, -1)
+    return ranks
+
+
+def _order_ranks(ranks, j):
+    # Reorder ascending order `ranks` according to `j`
+    ordered_ranks = np.empty(j.shape, dtype=ranks.dtype)
+    np.put_along_axis(ordered_ranks, j, ranks, axis=-1)
+    return ordered_ranks
+
+
+def _rankdata(x, method, return_ties=False):
+    # Rank data `x` by desired `method`; `return_ties` if desired
+    shape = x.shape
+
+    # Get sort order
+    kind = 'mergesort' if method == 'ordinal' else 'quicksort'
+    j = np.argsort(x, axis=-1, kind=kind)
+    ordinal_ranks = np.broadcast_to(np.arange(1, shape[-1]+1, dtype=int), shape)
+
+    # Ordinal ranks is very easy because ties don't matter. We're done.
+    if method == 'ordinal':
+        return _order_ranks(ordinal_ranks, j)  # never return ties
+
+    # Sort array
+    y = np.take_along_axis(x, j, axis=-1)
+    # Logical indices of unique elements
+    i = np.concatenate([np.ones(shape[:-1] + (1,), dtype=np.bool_),
+                       y[..., :-1] != y[..., 1:]], axis=-1)
+
+    # Integer indices of unique elements
+    indices = np.arange(y.size)[i.ravel()]
+    # Counts of unique elements
+    counts = np.diff(indices, append=y.size)
+
+    # Compute `'min'`, `'max'`, and `'mid'` ranks of unique elements
+    if method == 'min':
+        ranks = ordinal_ranks[i]
+    elif method == 'max':
+        ranks = ordinal_ranks[i] + counts - 1
+    elif method == 'average':
+        ranks = ordinal_ranks[i] + (counts - 1)/2
+    elif method == 'dense':
+        ranks = np.cumsum(i, axis=-1)[i]
+
+    ranks = np.repeat(ranks, counts).reshape(shape)
+    ranks = _order_ranks(ranks, j)
+
+    if return_ties:
+        # Tie information is returned in a format that is useful to functions that
+        # rely on this (private) function. Example:
+        # >>> x = np.asarray([3, 2, 1, 2, 2, 2, 1])
+        # >>> _, t = _rankdata(x, 'average', return_ties=True)
+        # >>> t  # array([2., 0., 4., 0., 0., 0., 1.])  # two 1s, four 2s, and one 3
+        # Unlike ranks, tie counts are *not* reordered to correspond with the order of
+        # the input; e.g. the number of appearances of the lowest rank element comes
+        # first. This is a useful format because:
+        # - The shape of the result is the shape of the input. Different slices can
+        #   have different numbers of tied elements but not result in a ragged array.
+        # - Functions that use `t` usually don't need to which each element of the
+        #   original array is associated with each tie count; they perform a reduction
+        #   over the tie counts onnly. The tie counts are naturally computed in a
+        #   sorted order, so this does not unnecessarily reorder them.
+        # - One exception is `wilcoxon`, which needs the number of zeros. Zeros always
+        #   have the lowest rank, so it is easy to find them at the zeroth index.
+        t = np.zeros(shape, dtype=float)
+        t[i] = counts
+        return ranks, t
+    return ranks
+
+
+def expectile(a, alpha=0.5, *, weights=None):
+    r"""Compute the expectile at the specified level.
+
+    Expectiles are a generalization of the expectation in the same way as
+    quantiles are a generalization of the median. The expectile at level
+    `alpha = 0.5` is the mean (average). See Notes for more details.
+
+    Parameters
+    ----------
+    a : array_like
+        Array containing numbers whose expectile is desired.
+    alpha : float, default: 0.5
+        The level of the expectile; e.g., ``alpha=0.5`` gives the mean.
+    weights : array_like, optional
+        An array of weights associated with the values in `a`.
+        The `weights` must be broadcastable to the same shape as `a`.
+        Default is None, which gives each value a weight of 1.0.
+        An integer valued weight element acts like repeating the corresponding
+        observation in `a` that many times. See Notes for more details.
+
+    Returns
+    -------
+    expectile : ndarray
+        The empirical expectile at level `alpha`.
+
+    See Also
+    --------
+    numpy.mean : Arithmetic average
+    numpy.quantile : Quantile
+
+    Notes
+    -----
+    In general, the expectile at level :math:`\alpha` of a random variable
+    :math:`X` with cumulative distribution function (CDF) :math:`F` is given
+    by the unique solution :math:`t` of:
+
+    .. math::
+
+        \alpha E((X - t)_+) = (1 - \alpha) E((t - X)_+) \,.
+
+    Here, :math:`(x)_+ = \max(0, x)` is the positive part of :math:`x`.
+    This equation can be equivalently written as:
+
+    .. math::
+
+        \alpha \int_t^\infty (x - t)\mathrm{d}F(x)
+        = (1 - \alpha) \int_{-\infty}^t (t - x)\mathrm{d}F(x) \,.
+
+    The empirical expectile at level :math:`\alpha` (`alpha`) of a sample
+    :math:`a_i` (the array `a`) is defined by plugging in the empirical CDF of
+    `a`. Given sample or case weights :math:`w` (the array `weights`), it
+    reads :math:`F_a(x) = \frac{1}{\sum_i w_i} \sum_i w_i 1_{a_i \leq x}`
+    with indicator function :math:`1_{A}`. This leads to the definition of the
+    empirical expectile at level `alpha` as the unique solution :math:`t` of:
+
+    .. math::
+
+        \alpha \sum_{i=1}^n w_i (a_i - t)_+ =
+            (1 - \alpha) \sum_{i=1}^n w_i (t - a_i)_+ \,.
+
+    For :math:`\alpha=0.5`, this simplifies to the weighted average.
+    Furthermore, the larger :math:`\alpha`, the larger the value of the
+    expectile.
+
+    As a final remark, the expectile at level :math:`\alpha` can also be
+    written as a minimization problem. One often used choice is
+
+    .. math::
+
+        \operatorname{argmin}_t
+        E(\lvert 1_{t\geq X} - \alpha\rvert(t - X)^2) \,.
+
+    References
+    ----------
+    .. [1] W. K. Newey and J. L. Powell (1987), "Asymmetric Least Squares
+           Estimation and Testing," Econometrica, 55, 819-847.
+    .. [2] T. Gneiting (2009). "Making and Evaluating Point Forecasts,"
+           Journal of the American Statistical Association, 106, 746 - 762.
+           :doi:`10.48550/arXiv.0912.0902`
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import expectile
+    >>> a = [1, 4, 2, -1]
+    >>> expectile(a, alpha=0.5) == np.mean(a)
+    True
+    >>> expectile(a, alpha=0.2)
+    0.42857142857142855
+    >>> expectile(a, alpha=0.8)
+    2.5714285714285716
+    >>> weights = [1, 3, 1, 1]
+
+    """
+    if alpha < 0 or alpha > 1:
+        raise ValueError(
+            "The expectile level alpha must be in the range [0, 1]."
+        )
+    a = np.asarray(a)
+
+    if weights is not None:
+        weights = np.broadcast_to(weights, a.shape)
+
+    # This is the empirical equivalent of Eq. (13) with identification
+    # function from Table 9 (omitting a factor of 2) in [2] (their y is our
+    # data a, their x is our t)
+    def first_order(t):
+        return np.average(np.abs((a <= t) - alpha) * (t - a), weights=weights)
+
+    if alpha >= 0.5:
+        x0 = np.average(a, weights=weights)
+        x1 = np.amax(a)
+    else:
+        x1 = np.average(a, weights=weights)
+        x0 = np.amin(a)
+
+    if x0 == x1:
+        # a has a single unique element
+        return x0
+
+    # Note that the expectile is the unique solution, so no worries about
+    # finding a wrong root.
+    res = root_scalar(first_order, x0=x0, x1=x1)
+    return res.root
+
+
+def _lmoment_iv(sample, order, axis, sorted, standardize):
+    # input validation/standardization for `lmoment`
+    sample = np.asarray(sample)
+    message = "`sample` must be an array of real numbers."
+    if np.issubdtype(sample.dtype, np.integer):
+        sample = sample.astype(np.float64)
+    if not np.issubdtype(sample.dtype, np.floating):
+        raise ValueError(message)
+
+    message = "`order` must be a scalar or a non-empty array of positive integers."
+    order = np.arange(1, 5) if order is None else np.asarray(order)
+    if not np.issubdtype(order.dtype, np.integer) or np.any(order <= 0):
+        raise ValueError(message)
+
+    axis = np.asarray(axis)[()]
+    message = "`axis` must be an integer."
+    if not np.issubdtype(axis.dtype, np.integer) or axis.ndim != 0:
+        raise ValueError(message)
+
+    sorted = np.asarray(sorted)[()]
+    message = "`sorted` must be True or False."
+    if not np.issubdtype(sorted.dtype, np.bool_) or sorted.ndim != 0:
+        raise ValueError(message)
+
+    standardize = np.asarray(standardize)[()]
+    message = "`standardize` must be True or False."
+    if not np.issubdtype(standardize.dtype, np.bool_) or standardize.ndim != 0:
+        raise ValueError(message)
+
+    sample = np.moveaxis(sample, axis, -1)
+    sample = np.sort(sample, axis=-1) if not sorted else sample
+
+    return sample, order, axis, sorted, standardize
+
+
+def _br(x, *, r=0):
+    n = x.shape[-1]
+    x = np.expand_dims(x, axis=-2)
+    x = np.broadcast_to(x, x.shape[:-2] + (len(r), n))
+    x = np.triu(x)
+    j = np.arange(n, dtype=x.dtype)
+    n = np.asarray(n, dtype=x.dtype)[()]
+    return (np.sum(special.binom(j, r[:, np.newaxis])*x, axis=-1)
+            / special.binom(n-1, r) / n)
+
+
+def _prk(r, k):
+    # Writen to match [1] Equation 27 closely to facilitate review.
+    # This does not protect against overflow, so improvements to
+    # robustness would be a welcome follow-up.
+    return (-1)**(r-k)*special.binom(r, k)*special.binom(r+k, k)
+
+
+@_axis_nan_policy_factory(  # noqa: E302
+    _moment_result_object, n_samples=1, result_to_tuple=_moment_tuple,
+    n_outputs=lambda kwds: _moment_outputs(kwds, [1, 2, 3, 4])
+)
+def lmoment(sample, order=None, *, axis=0, sorted=False, standardize=True):
+    r"""Compute L-moments of a sample from a continuous distribution
+
+    The L-moments of a probability distribution are summary statistics with
+    uses similar to those of conventional moments, but they are defined in
+    terms of the expected values of order statistics.
+    Sample L-moments are defined analogously to population L-moments, and
+    they can serve as estimators of population L-moments. They tend to be less
+    sensitive to extreme observations than conventional moments.
+
+    Parameters
+    ----------
+    sample : array_like
+        The real-valued sample whose L-moments are desired.
+    order : array_like, optional
+        The (positive integer) orders of the desired L-moments.
+        Must be a scalar or non-empty 1D array. Default is [1, 2, 3, 4].
+    axis : int or None, default=0
+        If an int, the axis of the input along which to compute the statistic.
+        The statistic of each axis-slice (e.g. row) of the input will appear
+        in a corresponding element of the output. If None, the input will be
+        raveled before computing the statistic.
+    sorted : bool, default=False
+        Whether `sample` is already sorted in increasing order along `axis`.
+        If False (default), `sample` will be sorted.
+    standardize : bool, default=True
+        Whether to return L-moment ratios for orders 3 and higher.
+        L-moment ratios are analogous to standardized conventional
+        moments: they are the non-standardized L-moments divided
+        by the L-moment of order 2.
+
+    Returns
+    -------
+    lmoments : ndarray
+        The sample L-moments of order `order`.
+
+    See Also
+    --------
+    moment
+
+    References
+    ----------
+    .. [1] D. Bilkova. "L-Moments and TL-Moments as an Alternative Tool of
+           Statistical Data Analysis". Journal of Applied Mathematics and
+           Physics. 2014. :doi:`10.4236/jamp.2014.210104`
+    .. [2] J. R. M. Hosking. "L-Moments: Analysis and Estimation of Distributions
+           Using Linear Combinations of Order Statistics". Journal of the Royal
+           Statistical Society. 1990. :doi:`10.1111/j.2517-6161.1990.tb01775.x`
+    .. [3] "L-moment". *Wikipedia*. https://en.wikipedia.org/wiki/L-moment.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng(328458568356392)
+    >>> sample = rng.exponential(size=100000)
+    >>> stats.lmoment(sample)
+    array([1.00124272, 0.50111437, 0.3340092 , 0.16755338])
+
+    Note that the first four standardized population L-moments of the standard
+    exponential distribution are 1, 1/2, 1/3, and 1/6; the sample L-moments
+    provide reasonable estimates.
+
+    """
+    args = _lmoment_iv(sample, order, axis, sorted, standardize)
+    sample, order, axis, sorted, standardize = args
+
+    n_moments = np.max(order)
+    k = np.arange(n_moments, dtype=sample.dtype)
+    prk = _prk(np.expand_dims(k, tuple(range(1, sample.ndim+1))), k)
+    bk = _br(sample, r=k)
+
+    n = sample.shape[-1]
+    bk[..., n:] = 0  # remove NaNs due to n_moments > n
+
+    lmoms = np.sum(prk * bk, axis=-1)
+    if standardize and n_moments > 2:
+        lmoms[2:] /= lmoms[1]
+
+    lmoms[n:] = np.nan  # add NaNs where appropriate
+    return lmoms[order-1]
+
+
+LinregressResult = _make_tuple_bunch('LinregressResult',
+                                     ['slope', 'intercept', 'rvalue',
+                                      'pvalue', 'stderr'],
+                                     extra_field_names=['intercept_stderr'])
+
+
+def linregress(x, y=None, alternative='two-sided'):
+    """
+    Calculate a linear least-squares regression for two sets of measurements.
+
+    Parameters
+    ----------
+    x, y : array_like
+        Two sets of measurements.  Both arrays should have the same length N.  If
+        only `x` is given (and ``y=None``), then it must be a two-dimensional
+        array where one dimension has length 2.  The two sets of measurements
+        are then found by splitting the array along the length-2 dimension. In
+        the case where ``y=None`` and `x` is a 2xN array, ``linregress(x)`` is
+        equivalent to ``linregress(x[0], x[1])``.
+
+        .. deprecated:: 1.14.0
+            Inference of the two sets of measurements from a single argument `x`
+            is deprecated will result in an error in SciPy 1.16.0; the sets
+            must be specified separately as `x` and `y`.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis. Default is 'two-sided'.
+        The following options are available:
+
+        * 'two-sided': the slope of the regression line is nonzero
+        * 'less': the slope of the regression line is less than zero
+        * 'greater':  the slope of the regression line is greater than zero
+
+        .. versionadded:: 1.7.0
+
+    Returns
+    -------
+    result : ``LinregressResult`` instance
+        The return value is an object with the following attributes:
+
+        slope : float
+            Slope of the regression line.
+        intercept : float
+            Intercept of the regression line.
+        rvalue : float
+            The Pearson correlation coefficient. The square of ``rvalue``
+            is equal to the coefficient of determination.
+        pvalue : float
+            The p-value for a hypothesis test whose null hypothesis is
+            that the slope is zero, using Wald Test with t-distribution of
+            the test statistic. See `alternative` above for alternative
+            hypotheses.
+        stderr : float
+            Standard error of the estimated slope (gradient), under the
+            assumption of residual normality.
+        intercept_stderr : float
+            Standard error of the estimated intercept, under the assumption
+            of residual normality.
+
+    See Also
+    --------
+    scipy.optimize.curve_fit :
+        Use non-linear least squares to fit a function to data.
+    scipy.optimize.leastsq :
+        Minimize the sum of squares of a set of equations.
+
+    Notes
+    -----
+    For compatibility with older versions of SciPy, the return value acts
+    like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``,
+    ``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write::
+
+        slope, intercept, r, p, se = linregress(x, y)
+
+    With that style, however, the standard error of the intercept is not
+    available.  To have access to all the computed values, including the
+    standard error of the intercept, use the return value as an object
+    with attributes, e.g.::
+
+        result = linregress(x, y)
+        print(result.intercept, result.intercept_stderr)
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> from scipy import stats
+    >>> rng = np.random.default_rng()
+
+    Generate some data:
+
+    >>> x = rng.random(10)
+    >>> y = 1.6*x + rng.random(10)
+
+    Perform the linear regression:
+
+    >>> res = stats.linregress(x, y)
+
+    Coefficient of determination (R-squared):
+
+    >>> print(f"R-squared: {res.rvalue**2:.6f}")
+    R-squared: 0.717533
+
+    Plot the data along with the fitted line:
+
+    >>> plt.plot(x, y, 'o', label='original data')
+    >>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line')
+    >>> plt.legend()
+    >>> plt.show()
+
+    Calculate 95% confidence interval on slope and intercept:
+
+    >>> # Two-sided inverse Students t-distribution
+    >>> # p - probability, df - degrees of freedom
+    >>> from scipy.stats import t
+    >>> tinv = lambda p, df: abs(t.ppf(p/2, df))
+
+    >>> ts = tinv(0.05, len(x)-2)
+    >>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}")
+    slope (95%): 1.453392 +/- 0.743465
+    >>> print(f"intercept (95%): {res.intercept:.6f}"
+    ...       f" +/- {ts*res.intercept_stderr:.6f}")
+    intercept (95%): 0.616950 +/- 0.544475
+
+    """
+    TINY = 1.0e-20
+    if y is None:  # x is a (2, N) or (N, 2) shaped array_like
+        message = ('Inference of the two sets of measurements from a single "'
+                   'argument `x` is deprecated will result in an error in "'
+                   'SciPy 1.16.0; the sets must be specified separately as "'
+                   '`x` and `y`.')
+        warnings.warn(message, DeprecationWarning, stacklevel=2)
+        x = np.asarray(x)
+        if x.shape[0] == 2:
+            x, y = x
+        elif x.shape[1] == 2:
+            x, y = x.T
+        else:
+            raise ValueError("If only `x` is given as input, it has to "
+                             "be of shape (2, N) or (N, 2); provided shape "
+                             f"was {x.shape}.")
+    else:
+        x = np.asarray(x)
+        y = np.asarray(y)
+
+    if x.size == 0 or y.size == 0:
+        raise ValueError("Inputs must not be empty.")
+
+    if np.amax(x) == np.amin(x) and len(x) > 1:
+        raise ValueError("Cannot calculate a linear regression "
+                         "if all x values are identical")
+
+    n = len(x)
+    xmean = np.mean(x, None)
+    ymean = np.mean(y, None)
+
+    # Average sums of square differences from the mean
+    #   ssxm = mean( (x-mean(x))^2 )
+    #   ssxym = mean( (x-mean(x)) * (y-mean(y)) )
+    ssxm, ssxym, _, ssym = np.cov(x, y, bias=1).flat
+
+    # R-value
+    #   r = ssxym / sqrt( ssxm * ssym )
+    if ssxm == 0.0 or ssym == 0.0:
+        # If the denominator was going to be 0
+        r = 0.0
+    else:
+        r = ssxym / np.sqrt(ssxm * ssym)
+        # Test for numerical error propagation (make sure -1 < r < 1)
+        if r > 1.0:
+            r = 1.0
+        elif r < -1.0:
+            r = -1.0
+
+    slope = ssxym / ssxm
+    intercept = ymean - slope*xmean
+    if n == 2:
+        # handle case when only two points are passed in
+        if y[0] == y[1]:
+            prob = 1.0
+        else:
+            prob = 0.0
+        slope_stderr = 0.0
+        intercept_stderr = 0.0
+    else:
+        df = n - 2  # Number of degrees of freedom
+        # n-2 degrees of freedom because 2 has been used up
+        # to estimate the mean and standard deviation
+        t = r * np.sqrt(df / ((1.0 - r + TINY)*(1.0 + r + TINY)))
+
+        dist = _SimpleStudentT(df)
+        prob = _get_pvalue(t, dist, alternative, xp=np)
+        prob = prob[()] if prob.ndim == 0 else prob
+
+        slope_stderr = np.sqrt((1 - r**2) * ssym / ssxm / df)
+
+        # Also calculate the standard error of the intercept
+        # The following relationship is used:
+        #   ssxm = mean( (x-mean(x))^2 )
+        #        = ssx - sx*sx
+        #        = mean( x^2 ) - mean(x)^2
+        intercept_stderr = slope_stderr * np.sqrt(ssxm + xmean**2)
+
+    return LinregressResult(slope=slope, intercept=intercept, rvalue=r,
+                            pvalue=prob, stderr=slope_stderr,
+                            intercept_stderr=intercept_stderr)
+
+
+def _xp_mean(x, /, *, axis=None, weights=None, keepdims=False, nan_policy='propagate',
+             dtype=None, xp=None):
+    r"""Compute the arithmetic mean along the specified axis.
+
+    Parameters
+    ----------
+    x : real array
+        Array containing real numbers whose mean is desired.
+    axis : int or tuple of ints, default: None
+        If an int or tuple of ints, the axis or axes of the input along which
+        to compute the statistic. The statistic of each axis-slice (e.g. row)
+        of the input will appear in a corresponding element of the output.
+        If ``None``, the input will be raveled before computing the statistic.
+    weights : real array, optional
+        If specified, an array of weights associated with the values in `x`;
+        otherwise ``1``. If `weights` and `x` do not have the same shape, the
+        arrays will be broadcasted before performing the calculation. See
+        Notes for details.
+    keepdims : boolean, optional
+        If this is set to ``True``, the axes which are reduced are left
+        in the result as dimensions with length one. With this option,
+        the result will broadcast correctly against the input array.
+    nan_policy : {'propagate', 'omit', 'raise'}, default: 'propagate'
+        Defines how to handle input NaNs.
+
+        - ``propagate``: if a NaN is present in the axis slice (e.g. row) along
+          which the statistic is computed, the corresponding entry of the output
+          will be NaN.
+        - ``omit``: NaNs will be omitted when performing the calculation.
+          If insufficient data remains in the axis slice along which the
+          statistic is computed, the corresponding entry of the output will be
+          NaN.
+        - ``raise``: if a NaN is present, a ``ValueError`` will be raised.
+
+    dtype : dtype, optional
+        Type to use in computing the mean. For integer inputs, the default is
+        the default float type of the array library; for floating point inputs,
+        the dtype is that of the input.
+
+    Returns
+    -------
+    out : array
+        The mean of each slice
+
+    Notes
+    -----
+    Let :math:`x_i` represent element :math:`i` of data `x` and let :math:`w_i`
+    represent the corresponding element of `weights` after broadcasting. Then the
+    (weighted) mean :math:`\bar{x}_w` is given by:
+
+    .. math::
+
+        \bar{x}_w = \frac{ \sum_{i=0}^{n-1} w_i x_i }
+                         { \sum_{i=0}^{n-1} w_i }
+
+    where :math:`n` is the number of elements along a slice. Note that this simplifies
+    to the familiar :math:`(\sum_i x_i) / n` when the weights are all ``1`` (default).
+
+    The behavior of this function with respect to weights is somewhat different
+    from that of `np.average`. For instance,
+    `np.average` raises an error when `axis` is not specified and the shapes of `x`
+    and the `weights` array are not the same; `xp_mean` simply broadcasts the two.
+    Also, `np.average` raises an error when weights sum to zero along a slice;
+    `xp_mean` computes the appropriate result. The intent is for this function's
+    interface to be consistent with the rest of `scipy.stats`.
+
+    Note that according to the formula, including NaNs with zero weights is not
+    the same as *omitting* NaNs with ``nan_policy='omit'``; in the former case,
+    the NaNs will continue to propagate through the calculation whereas in the
+    latter case, the NaNs are excluded entirely.
+
+    """
+    # ensure that `x` and `weights` are array-API compatible arrays of identical shape
+    xp = array_namespace(x) if xp is None else xp
+    x = _asarray(x, dtype=dtype, subok=True)
+    weights = xp.asarray(weights, dtype=dtype) if weights is not None else weights
+
+    # to ensure that this matches the behavior of decorated functions when one of the
+    # arguments has size zero, it's easiest to call a similar decorated function.
+    if is_numpy(xp) and (xp_size(x) == 0
+                         or (weights is not None and xp_size(weights) == 0)):
+        return gmean(x, weights=weights, axis=axis, keepdims=keepdims)
+
+    x, weights = xp_broadcast_promote(x, weights, force_floating=True)
+
+    # handle the special case of zero-sized arrays
+    message = (too_small_1d_not_omit if (x.ndim == 1 or axis is None)
+               else too_small_nd_not_omit)
+    if xp_size(x) == 0:
+        with warnings.catch_warnings():
+            warnings.simplefilter("ignore")
+            res = xp.mean(x, axis=axis, keepdims=keepdims)
+        if xp_size(res) != 0:
+            warnings.warn(message, SmallSampleWarning, stacklevel=2)
+        return res
+
+    contains_nan, _ = _contains_nan(x, nan_policy, xp_omit_okay=True, xp=xp)
+    if weights is not None:
+        contains_nan_w, _ = _contains_nan(weights, nan_policy, xp_omit_okay=True, xp=xp)
+        contains_nan = contains_nan | contains_nan_w
+
+    # Handle `nan_policy='omit'` by giving zero weight to NaNs, whether they
+    # appear in `x` or `weights`. Emit warning if there is an all-NaN slice.
+    message = (too_small_1d_omit if (x.ndim == 1 or axis is None)
+               else too_small_nd_omit)
+    if contains_nan and nan_policy == 'omit':
+        nan_mask = xp.isnan(x)
+        if weights is not None:
+            nan_mask |= xp.isnan(weights)
+        if xp.any(xp.all(nan_mask, axis=axis)):
+            warnings.warn(message, SmallSampleWarning, stacklevel=2)
+        weights = xp.ones_like(x) if weights is None else weights
+        x = xp.where(nan_mask, xp.asarray(0, dtype=x.dtype), x)
+        weights = xp.where(nan_mask, xp.asarray(0, dtype=x.dtype), weights)
+
+    # Perform the mean calculation itself
+    if weights is None:
+        return xp.mean(x, axis=axis, keepdims=keepdims)
+
+    norm = xp.sum(weights, axis=axis)
+    wsum = xp.sum(x * weights, axis=axis)
+    with np.errstate(divide='ignore', invalid='ignore'):
+        res = wsum/norm
+
+    # Respect `keepdims` and convert NumPy 0-D arrays to scalars
+    if keepdims:
+
+        if axis is None:
+            final_shape = (1,) * len(x.shape)
+        else:
+            # axis can be a scalar or sequence
+            axes = (axis,) if not isinstance(axis, Sequence) else axis
+            final_shape = list(x.shape)
+            for i in axes:
+                final_shape[i] = 1
+
+        res = xp.reshape(res, final_shape)
+
+    return res[()] if res.ndim == 0 else res
+
+
+def _xp_var(x, /, *, axis=None, correction=0, keepdims=False, nan_policy='propagate',
+            dtype=None, xp=None):
+    # an array-api compatible function for variance with scipy.stats interface
+    # and features (e.g. `nan_policy`).
+    xp = array_namespace(x) if xp is None else xp
+    x = _asarray(x, subok=True)
+
+    # use `_xp_mean` instead of `xp.var` for desired warning behavior
+    # it would be nice to combine this with `_var`, which uses `_moment`
+    # and therefore warns when precision is lost, but that does not support
+    # `axis` tuples or keepdims. Eventually, `_axis_nan_policy` will simplify
+    # `axis` tuples and implement `keepdims` for non-NumPy arrays; then it will
+    # be easy.
+    kwargs = dict(axis=axis, nan_policy=nan_policy, dtype=dtype, xp=xp)
+    mean = _xp_mean(x, keepdims=True, **kwargs)
+    x = _asarray(x, dtype=mean.dtype, subok=True)
+    x_mean = _demean(x, mean, axis, xp=xp)
+    x_mean_conj = (xp.conj(x_mean) if xp.isdtype(x_mean.dtype, 'complex floating')
+                   else x_mean)  # crossref data-apis/array-api#824
+    var = _xp_mean(x_mean * x_mean_conj, keepdims=keepdims, **kwargs)
+
+    if correction != 0:
+        if axis is None:
+            n = xp_size(x)
+        elif np.iterable(axis):  # note: using NumPy on `axis` is OK
+            n = math.prod(x.shape[i] for i in axis)
+        else:
+            n = x.shape[axis]
+        # Or two lines with ternaries : )
+        # axis = range(x.ndim) if axis is None else axis
+        # n = math.prod(x.shape[i] for i in axis) if iterable(axis) else x.shape[axis]
+
+        n = xp.asarray(n, dtype=var.dtype)
+
+        if nan_policy == 'omit':
+            nan_mask = xp.astype(xp.isnan(x), var.dtype)
+            n = n - xp.sum(nan_mask, axis=axis, keepdims=keepdims)
+
+        # Produce NaNs silently when n - correction <= 0
+        factor = _lazywhere(n-correction > 0, (n, n-correction), xp.divide, xp.nan)
+        var *= factor
+
+    return var[()] if var.ndim == 0 else var
+
+
+class _SimpleNormal:
+    # A very simple, array-API compatible normal distribution for use in
+    # hypothesis tests. May be replaced by new infrastructure Normal
+    # distribution in due time.
+
+    def cdf(self, x):
+        return special.ndtr(x)
+
+    def sf(self, x):
+        return special.ndtr(-x)
+
+    def isf(self, x):
+        return -special.ndtri(x)
+
+
+class _SimpleChi2:
+    # A very simple, array-API compatible chi-squared distribution for use in
+    # hypothesis tests. May be replaced by new infrastructure chi-squared
+    # distribution in due time.
+    def __init__(self, df):
+        self.df = df
+
+    def cdf(self, x):
+        return special.chdtr(self.df, x)
+
+    def sf(self, x):
+        return special.chdtrc(self.df, x)
+
+
+class _SimpleBeta:
+    # A very simple, array-API compatible beta distribution for use in
+    # hypothesis tests. May be replaced by new infrastructure beta
+    # distribution in due time.
+    def __init__(self, a, b, *, loc=None, scale=None):
+        self.a = a
+        self.b = b
+        self.loc = loc
+        self.scale = scale
+
+    def cdf(self, x):
+        if self.loc is not None or self.scale is not None:
+            loc = 0 if self.loc is None else self.loc
+            scale = 1 if self.scale is None else self.scale
+            return special.betainc(self.a, self.b, (x - loc)/scale)
+        return special.betainc(self.a, self.b, x)
+
+    def sf(self, x):
+        if self.loc is not None or self.scale is not None:
+            loc = 0 if self.loc is None else self.loc
+            scale = 1 if self.scale is None else self.scale
+            return special.betaincc(self.a, self.b, (x - loc)/scale)
+        return special.betaincc(self.a, self.b, x)
+
+
+class _SimpleStudentT:
+    # A very simple, array-API compatible t distribution for use in
+    # hypothesis tests. May be replaced by new infrastructure t
+    # distribution in due time.
+    def __init__(self, df):
+        self.df = df
+
+    def cdf(self, t):
+        return special.stdtr(self.df, t)
+
+    def sf(self, t):
+        return special.stdtr(self.df, -t)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_survival.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_survival.py
new file mode 100644
index 0000000000000000000000000000000000000000..aeea1645102f35460f3429b077aad9a705d331a2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_survival.py
@@ -0,0 +1,683 @@
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Literal
+import warnings
+
+import numpy as np
+from scipy import special, interpolate, stats
+from scipy.stats._censored_data import CensoredData
+from scipy.stats._common import ConfidenceInterval
+
+if TYPE_CHECKING:
+    import numpy.typing as npt
+
+
+__all__ = ['ecdf', 'logrank']
+
+
+@dataclass
+class EmpiricalDistributionFunction:
+    """An empirical distribution function produced by `scipy.stats.ecdf`
+
+    Attributes
+    ----------
+    quantiles : ndarray
+        The unique values of the sample from which the
+        `EmpiricalDistributionFunction` was estimated.
+    probabilities : ndarray
+        The point estimates of the cumulative distribution function (CDF) or
+        its complement, the survival function (SF), corresponding with
+        `quantiles`.
+    """
+    quantiles: np.ndarray
+    probabilities: np.ndarray
+    # Exclude these from __str__
+    _n: np.ndarray = field(repr=False)  # number "at risk"
+    _d: np.ndarray = field(repr=False)  # number of "deaths"
+    _sf: np.ndarray = field(repr=False)  # survival function for var estimate
+    _kind: str = field(repr=False)  # type of function: "cdf" or "sf"
+
+    def __init__(self, q, p, n, d, kind):
+        self.probabilities = p
+        self.quantiles = q
+        self._n = n
+        self._d = d
+        self._sf = p if kind == 'sf' else 1 - p
+        self._kind = kind
+
+        f0 = 1 if kind == 'sf' else 0  # leftmost function value
+        f1 = 1 - f0
+        # fill_value can't handle edge cases at infinity
+        x = np.insert(q, [0, len(q)], [-np.inf, np.inf])
+        y = np.insert(p, [0, len(p)], [f0, f1])
+        # `or` conditions handle the case of empty x, points
+        self._f = interpolate.interp1d(x, y, kind='previous',
+                                       assume_sorted=True)
+
+    def evaluate(self, x):
+        """Evaluate the empirical CDF/SF function at the input.
+
+        Parameters
+        ----------
+        x : ndarray
+            Argument to the CDF/SF
+
+        Returns
+        -------
+        y : ndarray
+            The CDF/SF evaluated at the input
+        """
+        return self._f(x)
+
+    def plot(self, ax=None, **matplotlib_kwargs):
+        """Plot the empirical distribution function
+
+        Available only if ``matplotlib`` is installed.
+
+        Parameters
+        ----------
+        ax : matplotlib.axes.Axes
+            Axes object to draw the plot onto, otherwise uses the current Axes.
+
+        **matplotlib_kwargs : dict, optional
+            Keyword arguments passed directly to `matplotlib.axes.Axes.step`.
+            Unless overridden, ``where='post'``.
+
+        Returns
+        -------
+        lines : list of `matplotlib.lines.Line2D`
+            Objects representing the plotted data
+        """
+        try:
+            import matplotlib  # noqa: F401
+        except ModuleNotFoundError as exc:
+            message = "matplotlib must be installed to use method `plot`."
+            raise ModuleNotFoundError(message) from exc
+
+        if ax is None:
+            import matplotlib.pyplot as plt
+            ax = plt.gca()
+
+        kwargs = {'where': 'post'}
+        kwargs.update(matplotlib_kwargs)
+
+        delta = np.ptp(self.quantiles)*0.05  # how far past sample edge to plot
+        q = self.quantiles
+        q = [q[0] - delta] + list(q) + [q[-1] + delta]
+
+        return ax.step(q, self.evaluate(q), **kwargs)
+
+    def confidence_interval(self, confidence_level=0.95, *, method='linear'):
+        """Compute a confidence interval around the CDF/SF point estimate
+
+        Parameters
+        ----------
+        confidence_level : float, default: 0.95
+            Confidence level for the computed confidence interval
+
+        method : str, {"linear", "log-log"}
+            Method used to compute the confidence interval. Options are
+            "linear" for the conventional Greenwood confidence interval
+            (default)  and "log-log" for the "exponential Greenwood",
+            log-negative-log-transformed confidence interval.
+
+        Returns
+        -------
+        ci : ``ConfidenceInterval``
+            An object with attributes ``low`` and ``high``, instances of
+            `~scipy.stats._result_classes.EmpiricalDistributionFunction` that
+            represent the lower and upper bounds (respectively) of the
+            confidence interval.
+
+        Notes
+        -----
+        Confidence intervals are computed according to the Greenwood formula
+        (``method='linear'``) or the more recent "exponential Greenwood"
+        formula (``method='log-log'``) as described in [1]_. The conventional
+        Greenwood formula can result in lower confidence limits less than 0
+        and upper confidence limits greater than 1; these are clipped to the
+        unit interval. NaNs may be produced by either method; these are
+        features of the formulas.
+
+        References
+        ----------
+        .. [1] Sawyer, Stanley. "The Greenwood and Exponential Greenwood
+               Confidence Intervals in Survival Analysis."
+               https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf
+
+        """
+        message = ("Confidence interval bounds do not implement a "
+                   "`confidence_interval` method.")
+        if self._n is None:
+            raise NotImplementedError(message)
+
+        methods = {'linear': self._linear_ci,
+                   'log-log': self._loglog_ci}
+
+        message = f"`method` must be one of {set(methods)}."
+        if method.lower() not in methods:
+            raise ValueError(message)
+
+        message = "`confidence_level` must be a scalar between 0 and 1."
+        confidence_level = np.asarray(confidence_level)[()]
+        if confidence_level.shape or not (0 <= confidence_level <= 1):
+            raise ValueError(message)
+
+        method_fun = methods[method.lower()]
+        low, high = method_fun(confidence_level)
+
+        message = ("The confidence interval is undefined at some observations."
+                   " This is a feature of the mathematical formula used, not"
+                   " an error in its implementation.")
+        if np.any(np.isnan(low) | np.isnan(high)):
+            warnings.warn(message, RuntimeWarning, stacklevel=2)
+
+        low, high = np.clip(low, 0, 1), np.clip(high, 0, 1)
+        low = EmpiricalDistributionFunction(self.quantiles, low, None, None,
+                                            self._kind)
+        high = EmpiricalDistributionFunction(self.quantiles, high, None, None,
+                                             self._kind)
+        return ConfidenceInterval(low, high)
+
+    def _linear_ci(self, confidence_level):
+        sf, d, n = self._sf, self._d, self._n
+        # When n == d, Greenwood's formula divides by zero.
+        # When s != 0, this can be ignored: var == inf, and CI is [0, 1]
+        # When s == 0, this results in NaNs. Produce an informative warning.
+        with np.errstate(divide='ignore', invalid='ignore'):
+            var = sf ** 2 * np.cumsum(d / (n * (n - d)))
+
+        se = np.sqrt(var)
+        z = special.ndtri(1 / 2 + confidence_level / 2)
+
+        z_se = z * se
+        low = self.probabilities - z_se
+        high = self.probabilities + z_se
+
+        return low, high
+
+    def _loglog_ci(self, confidence_level):
+        sf, d, n = self._sf, self._d, self._n
+
+        with np.errstate(divide='ignore', invalid='ignore'):
+            var = 1 / np.log(sf) ** 2 * np.cumsum(d / (n * (n - d)))
+
+        se = np.sqrt(var)
+        z = special.ndtri(1 / 2 + confidence_level / 2)
+
+        with np.errstate(divide='ignore'):
+            lnl_points = np.log(-np.log(sf))
+
+        z_se = z * se
+        low = np.exp(-np.exp(lnl_points + z_se))
+        high = np.exp(-np.exp(lnl_points - z_se))
+        if self._kind == "cdf":
+            low, high = 1-high, 1-low
+
+        return low, high
+
+
+@dataclass
+class ECDFResult:
+    """ Result object returned by `scipy.stats.ecdf`
+
+    Attributes
+    ----------
+    cdf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
+        An object representing the empirical cumulative distribution function.
+    sf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
+        An object representing the complement of the empirical cumulative
+        distribution function.
+    """
+    cdf: EmpiricalDistributionFunction
+    sf: EmpiricalDistributionFunction
+
+    def __init__(self, q, cdf, sf, n, d):
+        self.cdf = EmpiricalDistributionFunction(q, cdf, n, d, "cdf")
+        self.sf = EmpiricalDistributionFunction(q, sf, n, d, "sf")
+
+
+def _iv_CensoredData(
+    sample: "npt.ArrayLike | CensoredData", param_name: str = "sample"
+) -> CensoredData:
+    """Attempt to convert `sample` to `CensoredData`."""
+    if not isinstance(sample, CensoredData):
+        try:  # takes care of input standardization/validation
+            sample = CensoredData(uncensored=sample)
+        except ValueError as e:
+            message = str(e).replace('uncensored', param_name)
+            raise type(e)(message) from e
+    return sample
+
+
+def ecdf(sample: "npt.ArrayLike | CensoredData") -> ECDFResult:
+    """Empirical cumulative distribution function of a sample.
+
+    The empirical cumulative distribution function (ECDF) is a step function
+    estimate of the CDF of the distribution underlying a sample. This function
+    returns objects representing both the empirical distribution function and
+    its complement, the empirical survival function.
+
+    Parameters
+    ----------
+    sample : 1D array_like or `scipy.stats.CensoredData`
+        Besides array_like, instances of `scipy.stats.CensoredData` containing
+        uncensored and right-censored observations are supported. Currently,
+        other instances of `scipy.stats.CensoredData` will result in a
+        ``NotImplementedError``.
+
+    Returns
+    -------
+    res : `~scipy.stats._result_classes.ECDFResult`
+        An object with the following attributes.
+
+        cdf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
+            An object representing the empirical cumulative distribution
+            function.
+        sf : `~scipy.stats._result_classes.EmpiricalDistributionFunction`
+            An object representing the empirical survival function.
+
+        The `cdf` and `sf` attributes themselves have the following attributes.
+
+        quantiles : ndarray
+            The unique values in the sample that defines the empirical CDF/SF.
+        probabilities : ndarray
+            The point estimates of the probabilities corresponding with
+            `quantiles`.
+
+        And the following methods:
+
+        evaluate(x) :
+            Evaluate the CDF/SF at the argument.
+
+        plot(ax) :
+            Plot the CDF/SF on the provided axes.
+
+        confidence_interval(confidence_level=0.95) :
+            Compute the confidence interval around the CDF/SF at the values in
+            `quantiles`.
+
+    Notes
+    -----
+    When each observation of the sample is a precise measurement, the ECDF
+    steps up by ``1/len(sample)`` at each of the observations [1]_.
+
+    When observations are lower bounds, upper bounds, or both upper and lower
+    bounds, the data is said to be "censored", and `sample` may be provided as
+    an instance of `scipy.stats.CensoredData`.
+
+    For right-censored data, the ECDF is given by the Kaplan-Meier estimator
+    [2]_; other forms of censoring are not supported at this time.
+
+    Confidence intervals are computed according to the Greenwood formula or the
+    more recent "Exponential Greenwood" formula as described in [4]_.
+
+    References
+    ----------
+    .. [1] Conover, William Jay. Practical nonparametric statistics. Vol. 350.
+           John Wiley & Sons, 1999.
+
+    .. [2] Kaplan, Edward L., and Paul Meier. "Nonparametric estimation from
+           incomplete observations." Journal of the American statistical
+           association 53.282 (1958): 457-481.
+
+    .. [3] Goel, Manish Kumar, Pardeep Khanna, and Jugal Kishore.
+           "Understanding survival analysis: Kaplan-Meier estimate."
+           International journal of Ayurveda research 1.4 (2010): 274.
+
+    .. [4] Sawyer, Stanley. "The Greenwood and Exponential Greenwood Confidence
+           Intervals in Survival Analysis."
+           https://www.math.wustl.edu/~sawyer/handouts/greenwood.pdf
+
+    Examples
+    --------
+    **Uncensored Data**
+
+    As in the example from [1]_ page 79, five boys were selected at random from
+    those in a single high school. Their one-mile run times were recorded as
+    follows.
+
+    >>> sample = [6.23, 5.58, 7.06, 6.42, 5.20]  # one-mile run times (minutes)
+
+    The empirical distribution function, which approximates the distribution
+    function of one-mile run times of the population from which the boys were
+    sampled, is calculated as follows.
+
+    >>> from scipy import stats
+    >>> res = stats.ecdf(sample)
+    >>> res.cdf.quantiles
+    array([5.2 , 5.58, 6.23, 6.42, 7.06])
+    >>> res.cdf.probabilities
+    array([0.2, 0.4, 0.6, 0.8, 1. ])
+
+    To plot the result as a step function:
+
+    >>> import matplotlib.pyplot as plt
+    >>> ax = plt.subplot()
+    >>> res.cdf.plot(ax)
+    >>> ax.set_xlabel('One-Mile Run Time (minutes)')
+    >>> ax.set_ylabel('Empirical CDF')
+    >>> plt.show()
+
+    **Right-censored Data**
+
+    As in the example from [1]_ page 91, the lives of ten car fanbelts were
+    tested. Five tests concluded because the fanbelt being tested broke, but
+    the remaining tests concluded for other reasons (e.g. the study ran out of
+    funding, but the fanbelt was still functional). The mileage driven
+    with the fanbelts were recorded as follows.
+
+    >>> broken = [77, 47, 81, 56, 80]  # in thousands of miles driven
+    >>> unbroken = [62, 60, 43, 71, 37]
+
+    Precise survival times of the fanbelts that were still functional at the
+    end of the tests are unknown, but they are known to exceed the values
+    recorded in ``unbroken``. Therefore, these observations are said to be
+    "right-censored", and the data is represented using
+    `scipy.stats.CensoredData`.
+
+    >>> sample = stats.CensoredData(uncensored=broken, right=unbroken)
+
+    The empirical survival function is calculated as follows.
+
+    >>> res = stats.ecdf(sample)
+    >>> res.sf.quantiles
+    array([37., 43., 47., 56., 60., 62., 71., 77., 80., 81.])
+    >>> res.sf.probabilities
+    array([1.   , 1.   , 0.875, 0.75 , 0.75 , 0.75 , 0.75 , 0.5  , 0.25 , 0.   ])
+
+    To plot the result as a step function:
+
+    >>> ax = plt.subplot()
+    >>> res.sf.plot(ax)
+    >>> ax.set_xlabel('Fanbelt Survival Time (thousands of miles)')
+    >>> ax.set_ylabel('Empirical SF')
+    >>> plt.show()
+
+    """
+    sample = _iv_CensoredData(sample)
+
+    if sample.num_censored() == 0:
+        res = _ecdf_uncensored(sample._uncensor())
+    elif sample.num_censored() == sample._right.size:
+        res = _ecdf_right_censored(sample)
+    else:
+        # Support additional censoring options in follow-up PRs
+        message = ("Currently, only uncensored and right-censored data is "
+                   "supported.")
+        raise NotImplementedError(message)
+
+    t, cdf, sf, n, d = res
+    return ECDFResult(t, cdf, sf, n, d)
+
+
+def _ecdf_uncensored(sample):
+    sample = np.sort(sample)
+    x, counts = np.unique(sample, return_counts=True)
+
+    # [1].81 "the fraction of [observations] that are less than or equal to x
+    events = np.cumsum(counts)
+    n = sample.size
+    cdf = events / n
+
+    # [1].89 "the relative frequency of the sample that exceeds x in value"
+    sf = 1 - cdf
+
+    at_risk = np.concatenate(([n], n - events[:-1]))
+    return x, cdf, sf, at_risk, counts
+
+
+def _ecdf_right_censored(sample):
+    # It is conventional to discuss right-censored data in terms of
+    # "survival time", "death", and "loss" (e.g. [2]). We'll use that
+    # terminology here.
+    # This implementation was influenced by the references cited and also
+    # https://www.youtube.com/watch?v=lxoWsVco_iM
+    # https://en.wikipedia.org/wiki/Kaplan%E2%80%93Meier_estimator
+    # In retrospect it is probably most easily compared against [3].
+    # Ultimately, the data needs to be sorted, so this implementation is
+    # written to avoid a separate call to `unique` after sorting. In hope of
+    # better performance on large datasets, it also computes survival
+    # probabilities at unique times only rather than at each observation.
+    tod = sample._uncensored  # time of "death"
+    tol = sample._right  # time of "loss"
+    times = np.concatenate((tod, tol))
+    died = np.asarray([1]*tod.size + [0]*tol.size)
+
+    # sort by times
+    i = np.argsort(times)
+    times = times[i]
+    died = died[i]
+    at_risk = np.arange(times.size, 0, -1)
+
+    # logical indices of unique times
+    j = np.diff(times, prepend=-np.inf, append=np.inf) > 0
+    j_l = j[:-1]  # first instances of unique times
+    j_r = j[1:]  # last instances of unique times
+
+    # get number at risk and deaths at each unique time
+    t = times[j_l]  # unique times
+    n = at_risk[j_l]  # number at risk at each unique time
+    cd = np.cumsum(died)[j_r]  # cumulative deaths up to/including unique times
+    d = np.diff(cd, prepend=0)  # deaths at each unique time
+
+    # compute survival function
+    sf = np.cumprod((n - d) / n)
+    cdf = 1 - sf
+    return t, cdf, sf, n, d
+
+
+@dataclass
+class LogRankResult:
+    """Result object returned by `scipy.stats.logrank`.
+
+    Attributes
+    ----------
+    statistic : float ndarray
+        The computed statistic (defined below). Its magnitude is the
+        square root of the magnitude returned by most other logrank test
+        implementations.
+    pvalue : float ndarray
+        The computed p-value of the test.
+    """
+    statistic: np.ndarray
+    pvalue: np.ndarray
+
+
+def logrank(
+    x: "npt.ArrayLike | CensoredData",
+    y: "npt.ArrayLike | CensoredData",
+    alternative: Literal['two-sided', 'less', 'greater'] = "two-sided"
+) -> LogRankResult:
+    r"""Compare the survival distributions of two samples via the logrank test.
+
+    Parameters
+    ----------
+    x, y : array_like or CensoredData
+        Samples to compare based on their empirical survival functions.
+    alternative : {'two-sided', 'less', 'greater'}, optional
+        Defines the alternative hypothesis.
+
+        The null hypothesis is that the survival distributions of the two
+        groups, say *X* and *Y*, are identical.
+
+        The following alternative hypotheses [4]_ are available (default is
+        'two-sided'):
+
+        * 'two-sided': the survival distributions of the two groups are not
+          identical.
+        * 'less': survival of group *X* is favored: the group *X* failure rate
+          function is less than the group *Y* failure rate function at some
+          times.
+        * 'greater': survival of group *Y* is favored: the group *X* failure
+          rate function is greater than the group *Y* failure rate function at
+          some times.
+
+    Returns
+    -------
+    res : `~scipy.stats._result_classes.LogRankResult`
+        An object containing attributes:
+
+        statistic : float ndarray
+            The computed statistic (defined below). Its magnitude is the
+            square root of the magnitude returned by most other logrank test
+            implementations.
+        pvalue : float ndarray
+            The computed p-value of the test.
+
+    See Also
+    --------
+    scipy.stats.ecdf
+
+    Notes
+    -----
+    The logrank test [1]_ compares the observed number of events to
+    the expected number of events under the null hypothesis that the two
+    samples were drawn from the same distribution. The statistic is
+
+    .. math::
+
+        Z_i = \frac{\sum_{j=1}^J(O_{i,j}-E_{i,j})}{\sqrt{\sum_{j=1}^J V_{i,j}}}
+        \rightarrow \mathcal{N}(0,1)
+
+    where
+
+    .. math::
+
+        E_{i,j} = O_j \frac{N_{i,j}}{N_j},
+        \qquad
+        V_{i,j} = E_{i,j} \left(\frac{N_j-O_j}{N_j}\right)
+        \left(\frac{N_j-N_{i,j}}{N_j-1}\right),
+
+    :math:`i` denotes the group (i.e. it may assume values :math:`x` or
+    :math:`y`, or it may be omitted to refer to the combined sample)
+    :math:`j` denotes the time (at which an event occurred),
+    :math:`N` is the number of subjects at risk just before an event occurred,
+    and :math:`O` is the observed number of events at that time.
+
+    The ``statistic`` :math:`Z_x` returned by `logrank` is the (signed) square
+    root of the statistic returned by many other implementations. Under the
+    null hypothesis, :math:`Z_x**2` is asymptotically distributed according to
+    the chi-squared distribution with one degree of freedom. Consequently,
+    :math:`Z_x` is asymptotically distributed according to the standard normal
+    distribution. The advantage of using :math:`Z_x` is that the sign
+    information (i.e. whether the observed number of events tends to be less
+    than or greater than the number expected under the null hypothesis) is
+    preserved, allowing `scipy.stats.logrank` to offer one-sided alternative
+    hypotheses.
+
+    References
+    ----------
+    .. [1] Mantel N. "Evaluation of survival data and two new rank order
+           statistics arising in its consideration."
+           Cancer Chemotherapy Reports, 50(3):163-170, PMID: 5910392, 1966
+    .. [2] Bland, Altman, "The logrank test", BMJ, 328:1073,
+           :doi:`10.1136/bmj.328.7447.1073`, 2004
+    .. [3] "Logrank test", Wikipedia,
+           https://en.wikipedia.org/wiki/Logrank_test
+    .. [4] Brown, Mark. "On the choice of variance for the log rank test."
+           Biometrika 71.1 (1984): 65-74.
+    .. [5] Klein, John P., and Melvin L. Moeschberger. Survival analysis:
+           techniques for censored and truncated data. Vol. 1230. New York:
+           Springer, 2003.
+
+    Examples
+    --------
+    Reference [2]_ compared the survival times of patients with two different
+    types of recurrent malignant gliomas. The samples below record the time
+    (number of weeks) for which each patient participated in the study. The
+    `scipy.stats.CensoredData` class is used because the data is
+    right-censored: the uncensored observations correspond with observed deaths
+    whereas the censored observations correspond with the patient leaving the
+    study for another reason.
+
+    >>> from scipy import stats
+    >>> x = stats.CensoredData(
+    ...     uncensored=[6, 13, 21, 30, 37, 38, 49, 50,
+    ...                 63, 79, 86, 98, 202, 219],
+    ...     right=[31, 47, 80, 82, 82, 149]
+    ... )
+    >>> y = stats.CensoredData(
+    ...     uncensored=[10, 10, 12, 13, 14, 15, 16, 17, 18, 20, 24, 24,
+    ...                 25, 28,30, 33, 35, 37, 40, 40, 46, 48, 76, 81,
+    ...                 82, 91, 112, 181],
+    ...     right=[34, 40, 70]
+    ... )
+
+    We can calculate and visualize the empirical survival functions
+    of both groups as follows.
+
+    >>> import numpy as np
+    >>> import matplotlib.pyplot as plt
+    >>> ax = plt.subplot()
+    >>> ecdf_x = stats.ecdf(x)
+    >>> ecdf_x.sf.plot(ax, label='Astrocytoma')
+    >>> ecdf_y = stats.ecdf(y)
+    >>> ecdf_y.sf.plot(ax, label='Glioblastoma')
+    >>> ax.set_xlabel('Time to death (weeks)')
+    >>> ax.set_ylabel('Empirical SF')
+    >>> plt.legend()
+    >>> plt.show()
+
+    Visual inspection of the empirical survival functions suggests that the
+    survival times tend to be different between the two groups. To formally
+    assess whether the difference is significant at the 1% level, we use the
+    logrank test.
+
+    >>> res = stats.logrank(x=x, y=y)
+    >>> res.statistic
+    -2.73799
+    >>> res.pvalue
+    0.00618
+
+    The p-value is less than 1%, so we can consider the data to be evidence
+    against the null hypothesis in favor of the alternative that there is a
+    difference between the two survival functions.
+
+    """
+    # Input validation. `alternative` IV handled in `_get_pvalue` below.
+    x = _iv_CensoredData(sample=x, param_name='x')
+    y = _iv_CensoredData(sample=y, param_name='y')
+
+    # Combined sample. (Under H0, the two groups are identical.)
+    xy = CensoredData(
+        uncensored=np.concatenate((x._uncensored, y._uncensored)),
+        right=np.concatenate((x._right, y._right))
+    )
+
+    # Extract data from the combined sample
+    res = ecdf(xy)
+    idx = res.sf._d.astype(bool)  # indices of observed events
+    times_xy = res.sf.quantiles[idx]  # unique times of observed events
+    at_risk_xy = res.sf._n[idx]  # combined number of subjects at risk
+    deaths_xy = res.sf._d[idx]  # combined number of events
+
+    # Get the number at risk within each sample.
+    # First compute the number at risk in group X at each of the `times_xy`.
+    # Could use `interpolate_1d`, but this is more compact.
+    res_x = ecdf(x)
+    i = np.searchsorted(res_x.sf.quantiles, times_xy)
+    at_risk_x = np.append(res_x.sf._n, 0)[i]  # 0 at risk after last time
+    # Subtract from the combined number at risk to get number at risk in Y
+    at_risk_y = at_risk_xy - at_risk_x
+
+    # Compute the variance.
+    num = at_risk_x * at_risk_y * deaths_xy * (at_risk_xy - deaths_xy)
+    den = at_risk_xy**2 * (at_risk_xy - 1)
+    # Note: when `at_risk_xy == 1`, we would have `at_risk_xy - 1 == 0` in the
+    # numerator and denominator. Simplifying the fraction symbolically, we
+    # would always find the overall quotient to be zero, so don't compute it.
+    i = at_risk_xy > 1
+    sum_var = np.sum(num[i]/den[i])
+
+    # Get the observed and expected number of deaths in group X
+    n_died_x = x._uncensored.size
+    sum_exp_deaths_x = np.sum(at_risk_x * (deaths_xy/at_risk_xy))
+
+    # Compute the statistic. This is the square root of that in references.
+    statistic = (n_died_x - sum_exp_deaths_x)/np.sqrt(sum_var)
+
+    # Equivalent to chi2(df=1).sf(statistic**2) when alternative='two-sided'
+    norm = stats._stats_py._SimpleNormal()
+    pvalue = stats._stats_py._get_pvalue(statistic, norm, alternative, xp=np)
+
+    return LogRankResult(statistic=statistic[()], pvalue=pvalue[()])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_tukeylambda_stats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_tukeylambda_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..b77173c136d80eb57f5c993108b7408653acad13
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_tukeylambda_stats.py
@@ -0,0 +1,199 @@
+import numpy as np
+from numpy import poly1d
+from scipy.special import beta
+
+
+# The following code was used to generate the Pade coefficients for the
+# Tukey Lambda variance function.  Version 0.17 of mpmath was used.
+#---------------------------------------------------------------------------
+# import mpmath as mp
+#
+# mp.mp.dps = 60
+#
+# one   = mp.mpf(1)
+# two   = mp.mpf(2)
+#
+# def mpvar(lam):
+#     if lam == 0:
+#         v = mp.pi**2 / three
+#     else:
+#         v = (two / lam**2) * (one / (one + two*lam) -
+#                               mp.beta(lam + one, lam + one))
+#     return v
+#
+# t = mp.taylor(mpvar, 0, 8)
+# p, q = mp.pade(t, 4, 4)
+# print("p =", [mp.fp.mpf(c) for c in p])
+# print("q =", [mp.fp.mpf(c) for c in q])
+#---------------------------------------------------------------------------
+
+# Pade coefficients for the Tukey Lambda variance function.
+_tukeylambda_var_pc = [3.289868133696453, 0.7306125098871127,
+                       -0.5370742306855439, 0.17292046290190008,
+                       -0.02371146284628187]
+_tukeylambda_var_qc = [1.0, 3.683605511659861, 4.184152498888124,
+                       1.7660926747377275, 0.2643989311168465]
+
+# numpy.poly1d instances for the numerator and denominator of the
+# Pade approximation to the Tukey Lambda variance.
+_tukeylambda_var_p = poly1d(_tukeylambda_var_pc[::-1])
+_tukeylambda_var_q = poly1d(_tukeylambda_var_qc[::-1])
+
+
+def tukeylambda_variance(lam):
+    """Variance of the Tukey Lambda distribution.
+
+    Parameters
+    ----------
+    lam : array_like
+        The lambda values at which to compute the variance.
+
+    Returns
+    -------
+    v : ndarray
+        The variance.  For lam < -0.5, the variance is not defined, so
+        np.nan is returned.  For lam = 0.5, np.inf is returned.
+
+    Notes
+    -----
+    In an interval around lambda=0, this function uses the [4,4] Pade
+    approximation to compute the variance.  Otherwise it uses the standard
+    formula (https://en.wikipedia.org/wiki/Tukey_lambda_distribution).  The
+    Pade approximation is used because the standard formula has a removable
+    discontinuity at lambda = 0, and does not produce accurate numerical
+    results near lambda = 0.
+    """
+    lam = np.asarray(lam)
+    shp = lam.shape
+    lam = np.atleast_1d(lam).astype(np.float64)
+
+    # For absolute values of lam less than threshold, use the Pade
+    # approximation.
+    threshold = 0.075
+
+    # Play games with masks to implement the conditional evaluation of
+    # the distribution.
+    # lambda < -0.5:  var = nan
+    low_mask = lam < -0.5
+    # lambda == -0.5: var = inf
+    neghalf_mask = lam == -0.5
+    # abs(lambda) < threshold:  use Pade approximation
+    small_mask = np.abs(lam) < threshold
+    # else the "regular" case:  use the explicit formula.
+    reg_mask = ~(low_mask | neghalf_mask | small_mask)
+
+    # Get the 'lam' values for the cases where they are needed.
+    small = lam[small_mask]
+    reg = lam[reg_mask]
+
+    # Compute the function for each case.
+    v = np.empty_like(lam)
+    v[low_mask] = np.nan
+    v[neghalf_mask] = np.inf
+    if small.size > 0:
+        # Use the Pade approximation near lambda = 0.
+        v[small_mask] = _tukeylambda_var_p(small) / _tukeylambda_var_q(small)
+    if reg.size > 0:
+        v[reg_mask] = (2.0 / reg**2) * (1.0 / (1.0 + 2 * reg) -
+                                        beta(reg + 1, reg + 1))
+    v.shape = shp
+    return v
+
+
+# The following code was used to generate the Pade coefficients for the
+# Tukey Lambda kurtosis function.  Version 0.17 of mpmath was used.
+#---------------------------------------------------------------------------
+# import mpmath as mp
+#
+# mp.mp.dps = 60
+#
+# one   = mp.mpf(1)
+# two   = mp.mpf(2)
+# three = mp.mpf(3)
+# four  = mp.mpf(4)
+#
+# def mpkurt(lam):
+#     if lam == 0:
+#         k = mp.mpf(6)/5
+#     else:
+#         numer = (one/(four*lam+one) - four*mp.beta(three*lam+one, lam+one) +
+#                  three*mp.beta(two*lam+one, two*lam+one))
+#         denom = two*(one/(two*lam+one) - mp.beta(lam+one,lam+one))**2
+#         k = numer / denom - three
+#     return k
+#
+# # There is a bug in mpmath 0.17: when we use the 'method' keyword of the
+# # taylor function and we request a degree 9 Taylor polynomial, we actually
+# # get degree 8.
+# t = mp.taylor(mpkurt, 0, 9, method='quad', radius=0.01)
+# t = [mp.chop(c, tol=1e-15) for c in t]
+# p, q = mp.pade(t, 4, 4)
+# print("p =", [mp.fp.mpf(c) for c in p])
+# print("q =", [mp.fp.mpf(c) for c in q])
+#---------------------------------------------------------------------------
+
+# Pade coefficients for the Tukey Lambda kurtosis function.
+_tukeylambda_kurt_pc = [1.2, -5.853465139719495, -22.653447381131077,
+                        0.20601184383406815, 4.59796302262789]
+_tukeylambda_kurt_qc = [1.0, 7.171149192233599, 12.96663094361842,
+                        0.43075235247853005, -2.789746758009912]
+
+# numpy.poly1d instances for the numerator and denominator of the
+# Pade approximation to the Tukey Lambda kurtosis.
+_tukeylambda_kurt_p = poly1d(_tukeylambda_kurt_pc[::-1])
+_tukeylambda_kurt_q = poly1d(_tukeylambda_kurt_qc[::-1])
+
+
+def tukeylambda_kurtosis(lam):
+    """Kurtosis of the Tukey Lambda distribution.
+
+    Parameters
+    ----------
+    lam : array_like
+        The lambda values at which to compute the variance.
+
+    Returns
+    -------
+    v : ndarray
+        The variance.  For lam < -0.25, the variance is not defined, so
+        np.nan is returned.  For lam = 0.25, np.inf is returned.
+
+    """
+    lam = np.asarray(lam)
+    shp = lam.shape
+    lam = np.atleast_1d(lam).astype(np.float64)
+
+    # For absolute values of lam less than threshold, use the Pade
+    # approximation.
+    threshold = 0.055
+
+    # Use masks to implement the conditional evaluation of the kurtosis.
+    # lambda < -0.25:  kurtosis = nan
+    low_mask = lam < -0.25
+    # lambda == -0.25: kurtosis = inf
+    negqrtr_mask = lam == -0.25
+    # lambda near 0:  use Pade approximation
+    small_mask = np.abs(lam) < threshold
+    # else the "regular" case:  use the explicit formula.
+    reg_mask = ~(low_mask | negqrtr_mask | small_mask)
+
+    # Get the 'lam' values for the cases where they are needed.
+    small = lam[small_mask]
+    reg = lam[reg_mask]
+
+    # Compute the function for each case.
+    k = np.empty_like(lam)
+    k[low_mask] = np.nan
+    k[negqrtr_mask] = np.inf
+    if small.size > 0:
+        k[small_mask] = _tukeylambda_kurt_p(small) / _tukeylambda_kurt_q(small)
+    if reg.size > 0:
+        numer = (1.0 / (4 * reg + 1) - 4 * beta(3 * reg + 1, reg + 1) +
+                 3 * beta(2 * reg + 1, 2 * reg + 1))
+        denom = 2 * (1.0/(2 * reg + 1) - beta(reg + 1, reg + 1))**2
+        k[reg_mask] = numer / denom - 3
+
+    # The return value will be a numpy array; resetting the shape ensures that
+    # if `lam` was a scalar, the return value is a 0-d array.
+    k.shape = shp
+    return k
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/unuran_wrapper.pyi b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/unuran_wrapper.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..a9fefb77d573156ae7989b656bc1ea9681e877e2
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_unuran/unuran_wrapper.pyi
@@ -0,0 +1,178 @@
+import numpy as np
+from typing import (overload, Callable, NamedTuple, Protocol)
+import numpy.typing as npt
+from scipy._lib._util import SeedType
+import scipy.stats as stats
+
+
+ArrayLike0D = bool | int | float | complex | str | bytes | np.generic
+
+
+__all__: list[str]
+
+
+class UNURANError(RuntimeError):
+    ...
+
+
+class Method:
+    @overload
+    def rvs(self, size: None = ...) -> float | int: ...  # type: ignore[overload-overlap]
+    @overload
+    def rvs(self, size: int | tuple[int, ...] = ...) -> np.ndarray: ...
+    def set_random_state(self, random_state: SeedType) -> None: ...
+
+
+class TDRDist(Protocol):
+    @property
+    def pdf(self) -> Callable[..., float]: ...
+    @property
+    def dpdf(self) -> Callable[..., float]: ...
+    @property
+    def support(self) -> tuple[float, float]: ...
+
+
+class TransformedDensityRejection(Method):
+    def __init__(self,
+                 dist: TDRDist,
+                 *,
+                 mode: None | float = ...,
+                 center: None | float = ...,
+                 domain: None | tuple[float, float] = ...,
+                 c: float = ...,
+                 construction_points: int | npt.ArrayLike = ...,
+                 use_dars: bool = ...,
+                 max_squeeze_hat_ratio: float = ...,
+                 random_state: SeedType = ...) -> None: ...
+    @property
+    def squeeze_hat_ratio(self) -> float: ...
+    @property
+    def squeeze_area(self) -> float: ...
+    @overload
+    def ppf_hat(self, u: ArrayLike0D) -> float: ...  # type: ignore[overload-overlap]
+    @overload
+    def ppf_hat(self, u: npt.ArrayLike) -> np.ndarray: ...
+
+
+class SROUDist(Protocol):
+    @property
+    def pdf(self) -> Callable[..., float]: ...
+    @property
+    def support(self) -> tuple[float, float]: ...
+
+
+class SimpleRatioUniforms(Method):
+    def __init__(self,
+                 dist: SROUDist,
+                 *,
+                 mode: None | float = ...,
+                 pdf_area: float = ...,
+                 domain: None | tuple[float, float] = ...,
+                 cdf_at_mode: float = ...,
+                 random_state: SeedType = ...) -> None: ...
+
+
+class UError(NamedTuple):
+    max_error: float
+    mean_absolute_error: float
+
+class PINVDist(Protocol):
+    @property
+    def pdf(self) -> Callable[..., float]: ...
+    @property
+    def cdf(self) -> Callable[..., float]: ...
+    @property
+    def logpdf(self) -> Callable[..., float]: ...
+
+
+class NumericalInversePolynomial(Method):
+    def __init__(self,
+                 dist: PINVDist,
+                 *,
+                 mode: None | float = ...,
+                 center: None | float = ...,
+                 domain: None | tuple[float, float] = ...,
+                 order: int = ...,
+                 u_resolution: float = ...,
+                 random_state: SeedType = ...) -> None: ...
+    @property
+    def intervals(self) -> int: ...
+    @overload
+    def ppf(self, u: ArrayLike0D) -> float: ...  # type: ignore[overload-overlap]
+    @overload
+    def ppf(self, u: npt.ArrayLike) -> np.ndarray: ...
+    @overload
+    def cdf(self, x: ArrayLike0D) -> float: ...  # type: ignore[overload-overlap]
+    @overload
+    def cdf(self, x: npt.ArrayLike) -> np.ndarray: ...
+    def u_error(self, sample_size: int = ...) -> UError: ...
+    def qrvs(self,
+             size: None | int | tuple[int, ...] = ...,
+             d: None | int = ...,
+             qmc_engine: None | stats.qmc.QMCEngine = ...) -> npt.ArrayLike: ...
+
+
+class HINVDist(Protocol):
+    @property
+    def pdf(self) -> Callable[..., float]: ...
+    @property
+    def cdf(self) -> Callable[..., float]: ...
+    @property
+    def support(self) -> tuple[float, float]: ...
+
+
+class NumericalInverseHermite(Method):
+    def __init__(self,
+                 dist: HINVDist,
+                 *,
+                 domain: None | tuple[float, float] = ...,
+                 order: int= ...,
+                 u_resolution: float = ...,
+                 construction_points: None | npt.ArrayLike = ...,
+                 max_intervals: int = ...,
+                 random_state: SeedType = ...) -> None: ...
+    @property
+    def intervals(self) -> int: ...
+    @overload
+    def ppf(self, u: ArrayLike0D) -> float: ...  # type: ignore[overload-overlap]
+    @overload
+    def ppf(self, u: npt.ArrayLike) -> np.ndarray: ...
+    def qrvs(self,
+             size: None | int | tuple[int, ...] = ...,
+             d: None | int = ...,
+             qmc_engine: None | stats.qmc.QMCEngine = ...) -> npt.ArrayLike: ...
+    def u_error(self, sample_size: int = ...) -> UError: ...
+
+
+class DAUDist(Protocol):
+    @property
+    def pmf(self) -> Callable[..., float]: ...
+    @property
+    def support(self) -> tuple[float, float]: ...
+
+class DiscreteAliasUrn(Method):
+    def __init__(self,
+                 dist: npt.ArrayLike | DAUDist,
+                 *,
+                 domain: None | tuple[float, float] = ...,
+                 urn_factor: float = ...,
+                 random_state: SeedType = ...) -> None: ...
+
+
+class DGTDist(Protocol):
+    @property
+    def pmf(self) -> Callable[..., float]: ...
+    @property
+    def support(self) -> tuple[float, float]: ...
+
+class DiscreteGuideTable(Method):
+    def __init__(self,
+                 dist: npt.ArrayLike | DGTDist,
+                 *,
+                 domain: None | tuple[float, float] = ...,
+                 guide_factor: float = ...,
+                 random_state: SeedType = ...) -> None: ...
+    @overload
+    def ppf(self, u: ArrayLike0D) -> float: ...  # type: ignore[overload-overlap]
+    @overload
+    def ppf(self, u: npt.ArrayLike) -> np.ndarray: ...
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_variation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_variation.py
new file mode 100644
index 0000000000000000000000000000000000000000..9febde9ec8f1ae967634ed799f5f7ba2d817318e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_variation.py
@@ -0,0 +1,128 @@
+import numpy as np
+
+from scipy._lib._util import _get_nan
+from scipy._lib._array_api import array_namespace, xp_copysign
+
+from ._axis_nan_policy import _axis_nan_policy_factory
+
+
+@_axis_nan_policy_factory(
+    lambda x: x, n_outputs=1, result_to_tuple=lambda x: (x,)
+)
+def variation(a, axis=0, nan_policy='propagate', ddof=0, *, keepdims=False):
+    """
+    Compute the coefficient of variation.
+
+    The coefficient of variation is the standard deviation divided by the
+    mean.  This function is equivalent to::
+
+        np.std(x, axis=axis, ddof=ddof) / np.mean(x)
+
+    The default for ``ddof`` is 0, but many definitions of the coefficient
+    of variation use the square root of the unbiased sample variance
+    for the sample standard deviation, which corresponds to ``ddof=1``.
+
+    The function does not take the absolute value of the mean of the data,
+    so the return value is negative if the mean is negative.
+
+    Parameters
+    ----------
+    a : array_like
+        Input array.
+    axis : int or None, optional
+        Axis along which to calculate the coefficient of variation.
+        Default is 0. If None, compute over the whole array `a`.
+    nan_policy : {'propagate', 'raise', 'omit'}, optional
+        Defines how to handle when input contains ``nan``.
+        The following options are available:
+
+          * 'propagate': return ``nan``
+          * 'raise': raise an exception
+          * 'omit': perform the calculation with ``nan`` values omitted
+
+        The default is 'propagate'.
+    ddof : int, optional
+        Gives the "Delta Degrees Of Freedom" used when computing the
+        standard deviation.  The divisor used in the calculation of the
+        standard deviation is ``N - ddof``, where ``N`` is the number of
+        elements.  `ddof` must be less than ``N``; if it isn't, the result
+        will be ``nan`` or ``inf``, depending on ``N`` and the values in
+        the array.  By default `ddof` is zero for backwards compatibility,
+        but it is recommended to use ``ddof=1`` to ensure that the sample
+        standard deviation is computed as the square root of the unbiased
+        sample variance.
+
+    Returns
+    -------
+    variation : ndarray
+        The calculated variation along the requested axis.
+
+    Notes
+    -----
+    There are several edge cases that are handled without generating a
+    warning:
+
+    * If both the mean and the standard deviation are zero, ``nan``
+      is returned.
+    * If the mean is zero and the standard deviation is nonzero, ``inf``
+      is returned.
+    * If the input has length zero (either because the array has zero
+      length, or all the input values are ``nan`` and ``nan_policy`` is
+      ``'omit'``), ``nan`` is returned.
+    * If the input contains ``inf``, ``nan`` is returned.
+
+    References
+    ----------
+    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
+       Probability and Statistics Tables and Formulae. Chapman & Hall: New
+       York. 2000.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats import variation
+    >>> variation([1, 2, 3, 4, 5], ddof=1)
+    0.5270462766947299
+
+    Compute the variation along a given dimension of an array that contains
+    a few ``nan`` values:
+
+    >>> x = np.array([[  10.0, np.nan, 11.0, 19.0, 23.0, 29.0, 98.0],
+    ...               [  29.0,   30.0, 32.0, 33.0, 35.0, 56.0, 57.0],
+    ...               [np.nan, np.nan, 12.0, 13.0, 16.0, 16.0, 17.0]])
+    >>> variation(x, axis=1, ddof=1, nan_policy='omit')
+    array([1.05109361, 0.31428986, 0.146483  ])
+
+    """
+    xp = array_namespace(a)
+    a = xp.asarray(a)
+    # `nan_policy` and `keepdims` are handled by `_axis_nan_policy`
+    # `axis=None` is only handled for NumPy backend
+    if axis is None:
+        a = xp.reshape(a, (-1,))
+        axis = 0
+
+    n = a.shape[axis]
+    NaN = _get_nan(a)
+
+    if a.size == 0 or ddof > n:
+        # Handle as a special case to avoid spurious warnings.
+        # The return values, if any, are all nan.
+        shp = list(a.shape)
+        shp.pop(axis)
+        result = xp.full(shp, fill_value=NaN)
+        return result[()] if result.ndim == 0 else result
+
+    mean_a = xp.mean(a, axis=axis)
+
+    if ddof == n:
+        # Another special case.  Result is either inf or nan.
+        std_a = xp.std(a, axis=axis, correction=0)
+        result = xp.where(std_a > 0, xp_copysign(xp.asarray(xp.inf), mean_a), NaN)
+        return result[()] if result.ndim == 0 else result
+
+    with np.errstate(divide='ignore', invalid='ignore'):
+        std_a = xp.std(a, axis=axis, correction=ddof)
+        result = std_a / mean_a
+
+    return result[()] if result.ndim == 0 else result
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_warnings_errors.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_warnings_errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..38385b862c9d642b41af8d74279f98c6a427208a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_warnings_errors.py
@@ -0,0 +1,38 @@
+# Warnings
+
+
+class DegenerateDataWarning(RuntimeWarning):
+    """Warns when data is degenerate and results may not be reliable."""
+    def __init__(self, msg=None):
+        if msg is None:
+            msg = ("Degenerate data encountered; results may not be reliable.")
+        self.args = (msg,)
+
+
+class ConstantInputWarning(DegenerateDataWarning):
+    """Warns when all values in data are exactly equal."""
+    def __init__(self, msg=None):
+        if msg is None:
+            msg = ("All values in data are exactly equal; "
+                   "results may not be reliable.")
+        self.args = (msg,)
+
+
+class NearConstantInputWarning(DegenerateDataWarning):
+    """Warns when all values in data are nearly equal."""
+    def __init__(self, msg=None):
+        if msg is None:
+            msg = ("All values in data are nearly equal; "
+                   "results may not be reliable.")
+        self.args = (msg,)
+
+
+# Errors
+
+
+class FitError(RuntimeError):
+    """Represents an error condition when fitting a distribution to data."""
+    def __init__(self, msg=None):
+        if msg is None:
+            msg = ("An error occurred when fitting a distribution to data.")
+        self.args = (msg,)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_wilcoxon.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_wilcoxon.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdb475614d7d28edaf3ff04bfbda3f5a18242bef
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/_wilcoxon.py
@@ -0,0 +1,259 @@
+import numpy as np
+
+from scipy import stats
+from ._stats_py import _get_pvalue, _rankdata, _SimpleNormal
+from . import _morestats
+from ._axis_nan_policy import _broadcast_arrays
+from ._hypotests import _get_wilcoxon_distr
+from scipy._lib._util import _lazywhere, _get_nan
+
+
+class WilcoxonDistribution:
+
+    def __init__(self, n):
+        n = np.asarray(n).astype(int, copy=False)
+        self.n = n
+        self._dists = {ni: _get_wilcoxon_distr(ni) for ni in np.unique(n)}
+
+    def _cdf1(self, k, n):
+        pmfs = self._dists[n]
+        return pmfs[:k + 1].sum()
+
+    def _cdf(self, k, n):
+        return np.vectorize(self._cdf1, otypes=[float])(k, n)
+
+    def _sf1(self, k, n):
+        pmfs = self._dists[n]
+        return pmfs[k:].sum()
+
+    def _sf(self, k, n):
+        return np.vectorize(self._sf1, otypes=[float])(k, n)
+
+    def mean(self):
+        return self.n * (self.n + 1) / 4
+
+    def _prep(self, k):
+        k = np.asarray(k).astype(int, copy=False)
+        mn = self.mean()
+        out = np.empty(k.shape, dtype=np.float64)
+        return k, mn, out
+
+    def cdf(self, k):
+        k, mn, out = self._prep(k)
+        return _lazywhere(k <= mn, (k, self.n), self._cdf,
+                          f2=lambda k, n: 1 - self._sf(k+1, n))[()]
+
+    def sf(self, k):
+        k, mn, out = self._prep(k)
+        return _lazywhere(k <= mn, (k, self.n), self._sf,
+                          f2=lambda k, n: 1 - self._cdf(k-1, n))[()]
+
+
+def _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis):
+
+    axis = np.asarray(axis)[()]
+    message = "`axis` must be an integer."
+    if not np.issubdtype(axis.dtype, np.integer) or axis.ndim != 0:
+        raise ValueError(message)
+
+    message = '`axis` must be compatible with the shape(s) of `x` (and `y`)'
+    try:
+        if y is None:
+            x = np.asarray(x)
+            d = x
+        else:
+            x, y = _broadcast_arrays((x, y), axis=axis)
+            d = x - y
+        d = np.moveaxis(d, axis, -1)
+    except np.AxisError as e:
+        raise ValueError(message) from e
+
+    message = "`x` and `y` must have the same length along `axis`."
+    if y is not None and x.shape[axis] != y.shape[axis]:
+        raise ValueError(message)
+
+    message = "`x` (and `y`, if provided) must be an array of real numbers."
+    if np.issubdtype(d.dtype, np.integer):
+        d = d.astype(np.float64)
+    if not np.issubdtype(d.dtype, np.floating):
+        raise ValueError(message)
+
+    zero_method = str(zero_method).lower()
+    zero_methods = {"wilcox", "pratt", "zsplit"}
+    message = f"`zero_method` must be one of {zero_methods}."
+    if zero_method not in zero_methods:
+        raise ValueError(message)
+
+    corrections = {True, False}
+    message = f"`correction` must be one of {corrections}."
+    if correction not in corrections:
+        raise ValueError(message)
+
+    alternative = str(alternative).lower()
+    alternatives = {"two-sided", "less", "greater"}
+    message = f"`alternative` must be one of {alternatives}."
+    if alternative not in alternatives:
+        raise ValueError(message)
+
+    if not isinstance(method, stats.PermutationMethod):
+        methods = {"auto", "asymptotic", "exact"}
+        message = (f"`method` must be one of {methods} or "
+                   "an instance of `stats.PermutationMethod`.")
+        if method not in methods:
+            raise ValueError(message)
+    output_z = True if method == 'asymptotic' else False
+
+    # For small samples, we decide later whether to perform an exact test or a
+    # permutation test. The reason is that the presence of ties is not
+    # known at the input validation stage.
+    n_zero = np.sum(d == 0)
+    if method == "auto" and d.shape[-1] > 50:
+        method = "asymptotic"
+
+    return d, zero_method, correction, alternative, method, axis, output_z, n_zero
+
+
+def _wilcoxon_statistic(d, method, zero_method='wilcox'):
+
+    i_zeros = (d == 0)
+
+    if zero_method == 'wilcox':
+        # Wilcoxon's method for treating zeros was to remove them from
+        # the calculation. We do this by replacing 0s with NaNs, which
+        # are ignored anyway.
+        if not d.flags['WRITEABLE']:
+            d = d.copy()
+        d[i_zeros] = np.nan
+
+    i_nan = np.isnan(d)
+    n_nan = np.sum(i_nan, axis=-1)
+    count = d.shape[-1] - n_nan
+
+    r, t = _rankdata(abs(d), 'average', return_ties=True)
+
+    r_plus = np.sum((d > 0) * r, axis=-1)
+    r_minus = np.sum((d < 0) * r, axis=-1)
+
+    has_ties = (t == 0).any()
+
+    if zero_method == "zsplit":
+        # The "zero-split" method for treating zeros is to add half their contribution
+        # to r_plus and half to r_minus.
+        # See gh-2263 for the origin of this method.
+        r_zero_2 = np.sum(i_zeros * r, axis=-1) / 2
+        r_plus += r_zero_2
+        r_minus += r_zero_2
+
+    mn = count * (count + 1.) * 0.25
+    se = count * (count + 1.) * (2. * count + 1.)
+
+    if zero_method == "pratt":
+        # Pratt's method for treating zeros was just to modify the z-statistic.
+
+        # normal approximation needs to be adjusted, see Cureton (1967)
+        n_zero = i_zeros.sum(axis=-1)
+        mn -= n_zero * (n_zero + 1.) * 0.25
+        se -= n_zero * (n_zero + 1.) * (2. * n_zero + 1.)
+
+        # zeros are not to be included in tie-correction.
+        # any tie counts corresponding with zeros are in the 0th column
+        t[i_zeros.any(axis=-1), 0] = 0
+
+    tie_correct = (t**3 - t).sum(axis=-1)
+    se -= tie_correct/2
+    se = np.sqrt(se / 24)
+
+    # se = 0 means that no non-zero values are left in d. we only need z
+    # if method is asymptotic. however, if method="auto", the switch to
+    # asymptotic might only happen after the statistic is calculated, so z
+    # needs to be computed. in all other cases, avoid division by zero warning
+    # (z is not needed anyways)
+    if method in ["asymptotic", "auto"]:
+        z = (r_plus - mn) / se
+    else:
+        z = np.nan
+
+    return r_plus, r_minus, se, z, count, has_ties
+
+
+def _correction_sign(z, alternative):
+    if alternative == 'greater':
+        return 1
+    elif alternative == 'less':
+        return -1
+    else:
+        return np.sign(z)
+
+
+def _wilcoxon_nd(x, y=None, zero_method='wilcox', correction=True,
+                 alternative='two-sided', method='auto', axis=0):
+
+    temp = _wilcoxon_iv(x, y, zero_method, correction, alternative, method, axis)
+    d, zero_method, correction, alternative, method, axis, output_z, n_zero = temp
+
+    if d.size == 0:
+        NaN = _get_nan(d)
+        res = _morestats.WilcoxonResult(statistic=NaN, pvalue=NaN)
+        if method == 'asymptotic':
+            res.zstatistic = NaN
+        return res
+
+    r_plus, r_minus, se, z, count, has_ties = _wilcoxon_statistic(
+        d, method, zero_method
+    )
+
+    # we only know if there are ties after computing the statistic and not
+    # at the input validation stage. if the original method was auto and
+    # the decision was to use an exact test, we override this to
+    # a permutation test now (since method='exact' is not exact in the
+    # presence of ties)
+    if method == "auto":
+        if not (has_ties or n_zero > 0):
+            method = "exact"
+        elif d.shape[-1] <= 13:
+            # the possible outcomes to be simulated by the permutation test
+            # are 2**n, where n is the sample size.
+            # if n <= 13, the p-value is deterministic since 2**13 is less
+            # than 9999, the default number of n_resamples
+            method = stats.PermutationMethod()
+        else:
+            # if there are ties and the sample size is too large to
+            # run a deterministic permutation test, fall back to asymptotic
+            method = "asymptotic"
+
+    if method == 'asymptotic':
+        if correction:
+            sign = _correction_sign(z, alternative)
+            z -= sign * 0.5 / se
+        p = _get_pvalue(z, _SimpleNormal(), alternative, xp=np)
+    elif method == 'exact':
+        dist = WilcoxonDistribution(count)
+        # The null distribution in `dist` is exact only if there are no ties
+        # or zeros. If there are ties or zeros, the statistic can be non-
+        # integral, but the null distribution is only defined for integral
+        # values of the statistic. Therefore, we're conservative: round
+        # non-integral statistic up before computing CDF and down before
+        # computing SF. This preserves symmetry w.r.t. alternatives and
+        # order of the input arguments. See gh-19872.
+        if alternative == 'less':
+            p = dist.cdf(np.ceil(r_plus))
+        elif alternative == 'greater':
+            p = dist.sf(np.floor(r_plus))
+        else:
+            p = 2 * np.minimum(dist.sf(np.floor(r_plus)),
+                               dist.cdf(np.ceil(r_plus)))
+            p = np.clip(p, 0, 1)
+    else:  # `PermutationMethod` instance (already validated)
+        p = stats.permutation_test(
+            (d,), lambda d: _wilcoxon_statistic(d, method, zero_method)[0],
+            permutation_type='samples', **method._asdict(),
+            alternative=alternative, axis=-1).pvalue
+
+    # for backward compatibility...
+    statistic = np.minimum(r_plus, r_minus) if alternative=='two-sided' else r_plus
+    z = -np.abs(z) if (alternative == 'two-sided' and method == 'asymptotic') else z
+
+    res = _morestats.WilcoxonResult(statistic=statistic, pvalue=p[()])
+    if output_z:
+        res.zstatistic = z[()]
+    return res
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/biasedurn.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/biasedurn.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b1c9f1cf2b3b39acdcaeda97a90e8c11c589d89
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/biasedurn.py
@@ -0,0 +1,16 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="biasedurn",
+                                   private_modules=["_biasedurn"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/contingency.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/contingency.py
new file mode 100644
index 0000000000000000000000000000000000000000..809df62e3cdaa2887fab2164afbe01e496ac6315
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/contingency.py
@@ -0,0 +1,521 @@
+"""
+Contingency table functions (:mod:`scipy.stats.contingency`)
+============================================================
+
+Functions for creating and analyzing contingency tables.
+
+.. currentmodule:: scipy.stats.contingency
+
+.. autosummary::
+   :toctree: generated/
+
+   chi2_contingency
+   relative_risk
+   odds_ratio
+   crosstab
+   association
+
+   expected_freq
+   margins
+
+"""
+
+
+from functools import reduce
+import math
+import numpy as np
+from ._stats_py import power_divergence, _untabulate
+from ._relative_risk import relative_risk
+from ._crosstab import crosstab
+from ._odds_ratio import odds_ratio
+from scipy._lib._bunch import _make_tuple_bunch
+from scipy import stats
+
+
+__all__ = ['margins', 'expected_freq', 'chi2_contingency', 'crosstab',
+           'association', 'relative_risk', 'odds_ratio']
+
+
+def margins(a):
+    """Return a list of the marginal sums of the array `a`.
+
+    Parameters
+    ----------
+    a : ndarray
+        The array for which to compute the marginal sums.
+
+    Returns
+    -------
+    margsums : list of ndarrays
+        A list of length `a.ndim`.  `margsums[k]` is the result
+        of summing `a` over all axes except `k`; it has the same
+        number of dimensions as `a`, but the length of each axis
+        except axis `k` will be 1.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.contingency import margins
+
+    >>> a = np.arange(12).reshape(2, 6)
+    >>> a
+    array([[ 0,  1,  2,  3,  4,  5],
+           [ 6,  7,  8,  9, 10, 11]])
+    >>> m0, m1 = margins(a)
+    >>> m0
+    array([[15],
+           [51]])
+    >>> m1
+    array([[ 6,  8, 10, 12, 14, 16]])
+
+    >>> b = np.arange(24).reshape(2,3,4)
+    >>> m0, m1, m2 = margins(b)
+    >>> m0
+    array([[[ 66]],
+           [[210]]])
+    >>> m1
+    array([[[ 60],
+            [ 92],
+            [124]]])
+    >>> m2
+    array([[[60, 66, 72, 78]]])
+    """
+    margsums = []
+    ranged = list(range(a.ndim))
+    for k in ranged:
+        marg = np.apply_over_axes(np.sum, a, [j for j in ranged if j != k])
+        margsums.append(marg)
+    return margsums
+
+
+def expected_freq(observed):
+    """
+    Compute the expected frequencies from a contingency table.
+
+    Given an n-dimensional contingency table of observed frequencies,
+    compute the expected frequencies for the table based on the marginal
+    sums under the assumption that the groups associated with each
+    dimension are independent.
+
+    Parameters
+    ----------
+    observed : array_like
+        The table of observed frequencies.  (While this function can handle
+        a 1-D array, that case is trivial.  Generally `observed` is at
+        least 2-D.)
+
+    Returns
+    -------
+    expected : ndarray of float64
+        The expected frequencies, based on the marginal sums of the table.
+        Same shape as `observed`.
+
+    Examples
+    --------
+    >>> import numpy as np
+    >>> from scipy.stats.contingency import expected_freq
+    >>> observed = np.array([[10, 10, 20],[20, 20, 20]])
+    >>> expected_freq(observed)
+    array([[ 12.,  12.,  16.],
+           [ 18.,  18.,  24.]])
+
+    """
+    # Typically `observed` is an integer array. If `observed` has a large
+    # number of dimensions or holds large values, some of the following
+    # computations may overflow, so we first switch to floating point.
+    observed = np.asarray(observed, dtype=np.float64)
+
+    # Create a list of the marginal sums.
+    margsums = margins(observed)
+
+    # Create the array of expected frequencies.  The shapes of the
+    # marginal sums returned by apply_over_axes() are just what we
+    # need for broadcasting in the following product.
+    d = observed.ndim
+    expected = reduce(np.multiply, margsums) / observed.sum() ** (d - 1)
+    return expected
+
+
+Chi2ContingencyResult = _make_tuple_bunch(
+    'Chi2ContingencyResult',
+    ['statistic', 'pvalue', 'dof', 'expected_freq'], []
+)
+
+
+def chi2_contingency(observed, correction=True, lambda_=None, *, method=None):
+    """Chi-square test of independence of variables in a contingency table.
+
+    This function computes the chi-square statistic and p-value for the
+    hypothesis test of independence of the observed frequencies in the
+    contingency table [1]_ `observed`.  The expected frequencies are computed
+    based on the marginal sums under the assumption of independence; see
+    `scipy.stats.contingency.expected_freq`.  The number of degrees of
+    freedom is (expressed using numpy functions and attributes)::
+
+        dof = observed.size - sum(observed.shape) + observed.ndim - 1
+
+
+    Parameters
+    ----------
+    observed : array_like
+        The contingency table. The table contains the observed frequencies
+        (i.e. number of occurrences) in each category.  In the two-dimensional
+        case, the table is often described as an "R x C table".
+    correction : bool, optional
+        If True, *and* the degrees of freedom is 1, apply Yates' correction
+        for continuity.  The effect of the correction is to adjust each
+        observed value by 0.5 towards the corresponding expected value.
+    lambda_ : float or str, optional
+        By default, the statistic computed in this test is Pearson's
+        chi-squared statistic [2]_.  `lambda_` allows a statistic from the
+        Cressie-Read power divergence family [3]_ to be used instead.  See
+        `scipy.stats.power_divergence` for details.
+    method : ResamplingMethod, optional
+        Defines the method used to compute the p-value. Compatible only with
+        `correction=False`,  default `lambda_`, and two-way tables.
+        If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`,
+        the p-value is computed using
+        `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
+        provided configuration options and other appropriate settings.
+        Otherwise, the p-value is computed as documented in the notes.
+        Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs``
+        attribute must be left unspecified; Monte Carlo samples are always drawn
+        using the ``rvs`` method of `scipy.stats.random_table`.
+
+        .. versionadded:: 1.15.0
+
+
+    Returns
+    -------
+    res : Chi2ContingencyResult
+        An object containing attributes:
+
+        statistic : float
+            The test statistic.
+        pvalue : float
+            The p-value of the test.
+        dof : int
+            The degrees of freedom. NaN if `method` is not ``None``.
+        expected_freq : ndarray, same shape as `observed`
+            The expected frequencies, based on the marginal sums of the table.
+
+    See Also
+    --------
+    scipy.stats.contingency.expected_freq
+    scipy.stats.fisher_exact
+    scipy.stats.chisquare
+    scipy.stats.power_divergence
+    scipy.stats.barnard_exact
+    scipy.stats.boschloo_exact
+    :ref:`hypothesis_chi2_contingency` : Extended example
+
+    Notes
+    -----
+    An often quoted guideline for the validity of this calculation is that
+    the test should be used only if the observed and expected frequencies
+    in each cell are at least 5.
+
+    This is a test for the independence of different categories of a
+    population. The test is only meaningful when the dimension of
+    `observed` is two or more.  Applying the test to a one-dimensional
+    table will always result in `expected` equal to `observed` and a
+    chi-square statistic equal to 0.
+
+    This function does not handle masked arrays, because the calculation
+    does not make sense with missing values.
+
+    Like `scipy.stats.chisquare`, this function computes a chi-square
+    statistic; the convenience this function provides is to figure out the
+    expected frequencies and degrees of freedom from the given contingency
+    table. If these were already known, and if the Yates' correction was not
+    required, one could use `scipy.stats.chisquare`.  That is, if one calls::
+
+        res = chi2_contingency(obs, correction=False)
+
+    then the following is true::
+
+        (res.statistic, res.pvalue) == stats.chisquare(obs.ravel(),
+                                                       f_exp=ex.ravel(),
+                                                       ddof=obs.size - 1 - dof)
+
+    The `lambda_` argument was added in version 0.13.0 of scipy.
+
+    References
+    ----------
+    .. [1] "Contingency table",
+           https://en.wikipedia.org/wiki/Contingency_table
+    .. [2] "Pearson's chi-squared test",
+           https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
+    .. [3] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
+           Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
+           pp. 440-464.
+
+    Examples
+    --------
+    A two-way example (2 x 3):
+
+    >>> import numpy as np
+    >>> from scipy.stats import chi2_contingency
+    >>> obs = np.array([[10, 10, 20], [20, 20, 20]])
+    >>> res = chi2_contingency(obs)
+    >>> res.statistic
+    2.7777777777777777
+    >>> res.pvalue
+    0.24935220877729619
+    >>> res.dof
+    2
+    >>> res.expected_freq
+    array([[ 12.,  12.,  16.],
+           [ 18.,  18.,  24.]])
+
+    Perform the test using the log-likelihood ratio (i.e. the "G-test")
+    instead of Pearson's chi-squared statistic.
+
+    >>> res = chi2_contingency(obs, lambda_="log-likelihood")
+    >>> res.statistic
+    2.7688587616781319
+    >>> res.pvalue
+    0.25046668010954165
+
+    A four-way example (2 x 2 x 2 x 2):
+
+    >>> obs = np.array(
+    ...     [[[[12, 17],
+    ...        [11, 16]],
+    ...       [[11, 12],
+    ...        [15, 16]]],
+    ...      [[[23, 15],
+    ...        [30, 22]],
+    ...       [[14, 17],
+    ...        [15, 16]]]])
+    >>> res = chi2_contingency(obs)
+    >>> res.statistic
+    8.7584514426741897
+    >>> res.pvalue
+    0.64417725029295503
+
+    When the sum of the elements in a two-way table is small, the p-value
+    produced by the default asymptotic approximation may be inaccurate.
+    Consider passing a `PermutationMethod` or `MonteCarloMethod` as the
+    `method` parameter with `correction=False`.
+
+    >>> from scipy.stats import PermutationMethod
+    >>> obs = np.asarray([[12, 3],
+    ...                   [17, 16]])
+    >>> res = chi2_contingency(obs, correction=False)
+    >>> ref = chi2_contingency(obs, correction=False, method=PermutationMethod())
+    >>> res.pvalue, ref.pvalue
+    (0.0614122539870913, 0.1074)  # may vary
+
+    For a more detailed example, see :ref:`hypothesis_chi2_contingency`.
+
+    """
+    observed = np.asarray(observed)
+    if np.any(observed < 0):
+        raise ValueError("All values in `observed` must be nonnegative.")
+    if observed.size == 0:
+        raise ValueError("No data; `observed` has size 0.")
+
+    expected = expected_freq(observed)
+    if np.any(expected == 0):
+        # Include one of the positions where expected is zero in
+        # the exception message.
+        zeropos = list(zip(*np.nonzero(expected == 0)))[0]
+        raise ValueError("The internally computed table of expected "
+                         f"frequencies has a zero element at {zeropos}.")
+
+    if method is not None:
+        return _chi2_resampling_methods(observed, expected, correction, lambda_, method)
+
+    # The degrees of freedom
+    dof = expected.size - sum(expected.shape) + expected.ndim - 1
+
+    if dof == 0:
+        # Degenerate case; this occurs when `observed` is 1D (or, more
+        # generally, when it has only one nontrivial dimension).  In this
+        # case, we also have observed == expected, so chi2 is 0.
+        chi2 = 0.0
+        p = 1.0
+    else:
+        if dof == 1 and correction:
+            # Adjust `observed` according to Yates' correction for continuity.
+            # Magnitude of correction no bigger than difference; see gh-13875
+            diff = expected - observed
+            direction = np.sign(diff)
+            magnitude = np.minimum(0.5, np.abs(diff))
+            observed = observed + magnitude * direction
+
+        chi2, p = power_divergence(observed, expected,
+                                   ddof=observed.size - 1 - dof, axis=None,
+                                   lambda_=lambda_)
+
+    return Chi2ContingencyResult(chi2, p, dof, expected)
+
+
+def _chi2_resampling_methods(observed, expected, correction, lambda_, method):
+
+    if observed.ndim != 2:
+        message = 'Use of `method` is only compatible with two-way tables.'
+        raise ValueError(message)
+
+    if correction:
+        message = f'`{correction=}` is not compatible with `{method=}.`'
+        raise ValueError(message)
+
+    if lambda_ is not None:
+        message = f'`{lambda_=}` is not compatible with `{method=}.`'
+        raise ValueError(message)
+
+    if isinstance(method, stats.PermutationMethod):
+        res = _chi2_permutation_method(observed, expected, method)
+    elif isinstance(method, stats.MonteCarloMethod):
+        res = _chi2_monte_carlo_method(observed, expected, method)
+    else:
+        message = (f'`{method=}` not recognized; if provided, `method` must be an '
+                   'instance of `PermutationMethod` or `MonteCarloMethod`.')
+        raise ValueError(message)
+
+    return Chi2ContingencyResult(res.statistic, res.pvalue, np.nan, expected)
+
+
+def _chi2_permutation_method(observed, expected, method):
+    x, y = _untabulate(observed)
+    # `permutation_test` with `permutation_type='pairings' permutes the order of `x`,
+    # which pairs observations in `x` with different observations in `y`.
+    def statistic(x):
+        # crosstab the resample and compute the statistic
+        table = crosstab(x, y)[1]
+        return np.sum((table - expected)**2/expected)
+
+    return stats.permutation_test((x,), statistic, permutation_type='pairings',
+                                  alternative='greater', **method._asdict())
+
+
+def _chi2_monte_carlo_method(observed, expected, method):
+    method = method._asdict()
+
+    if method.pop('rvs', None) is not None:
+        message = ('If the `method` argument of `chi2_contingency` is an '
+                   'instance of `MonteCarloMethod`, its `rvs` attribute '
+                   'must be unspecified. Use the `MonteCarloMethod` `rng` argument '
+                   'to control the random state.')
+        raise ValueError(message)
+    rng = np.random.default_rng(method.pop('rng', None))
+
+    # `random_table.rvs` produces random contingency tables with the given marginals
+    # under the null hypothesis of independence
+    rowsums, colsums = stats.contingency.margins(observed)
+    X = stats.random_table(rowsums.ravel(), colsums.ravel(), seed=rng)
+    def rvs(size):
+        n_resamples = size[0]
+        return X.rvs(size=n_resamples).reshape(size)
+
+    expected = expected.ravel()
+    def statistic(table, axis):
+        return np.sum((table - expected)**2/expected, axis=axis)
+
+    return stats.monte_carlo_test(observed.ravel(), rvs, statistic,
+                                  alternative='greater', **method)
+
+
+def association(observed, method="cramer", correction=False, lambda_=None):
+    """Calculates degree of association between two nominal variables.
+
+    The function provides the option for computing one of three measures of
+    association between two nominal variables from the data given in a 2d
+    contingency table: Tschuprow's T, Pearson's Contingency Coefficient
+    and Cramer's V.
+
+    Parameters
+    ----------
+    observed : array-like
+        The array of observed values
+    method : {"cramer", "tschuprow", "pearson"} (default = "cramer")
+        The association test statistic.
+    correction : bool, optional
+        Inherited from `scipy.stats.contingency.chi2_contingency()`
+    lambda_ : float or str, optional
+        Inherited from `scipy.stats.contingency.chi2_contingency()`
+
+    Returns
+    -------
+    statistic : float
+        Value of the test statistic
+
+    Notes
+    -----
+    Cramer's V, Tschuprow's T and Pearson's Contingency Coefficient, all
+    measure the degree to which two nominal or ordinal variables are related,
+    or the level of their association. This differs from correlation, although
+    many often mistakenly consider them equivalent. Correlation measures in
+    what way two variables are related, whereas, association measures how
+    related the variables are. As such, association does not subsume
+    independent variables, and is rather a test of independence. A value of
+    1.0 indicates perfect association, and 0.0 means the variables have no
+    association.
+
+    Both the Cramer's V and Tschuprow's T are extensions of the phi
+    coefficient.  Moreover, due to the close relationship between the
+    Cramer's V and Tschuprow's T the returned values can often be similar
+    or even equivalent.  They are likely to diverge more as the array shape
+    diverges from a 2x2.
+
+    References
+    ----------
+    .. [1] "Tschuprow's T",
+           https://en.wikipedia.org/wiki/Tschuprow's_T
+    .. [2] Tschuprow, A. A. (1939)
+           Principles of the Mathematical Theory of Correlation;
+           translated by M. Kantorowitsch. W. Hodge & Co.
+    .. [3] "Cramer's V", https://en.wikipedia.org/wiki/Cramer's_V
+    .. [4] "Nominal Association: Phi and Cramer's V",
+           http://www.people.vcu.edu/~pdattalo/702SuppRead/MeasAssoc/NominalAssoc.html
+    .. [5] Gingrich, Paul, "Association Between Variables",
+           http://uregina.ca/~gingrich/ch11a.pdf
+
+    Examples
+    --------
+    An example with a 4x2 contingency table:
+
+    >>> import numpy as np
+    >>> from scipy.stats.contingency import association
+    >>> obs4x2 = np.array([[100, 150], [203, 322], [420, 700], [320, 210]])
+
+    Pearson's contingency coefficient
+
+    >>> association(obs4x2, method="pearson")
+    0.18303298140595667
+
+    Cramer's V
+
+    >>> association(obs4x2, method="cramer")
+    0.18617813077483678
+
+    Tschuprow's T
+
+    >>> association(obs4x2, method="tschuprow")
+    0.14146478765062995
+    """
+    arr = np.asarray(observed)
+    if not np.issubdtype(arr.dtype, np.integer):
+        raise ValueError("`observed` must be an integer array.")
+
+    if len(arr.shape) != 2:
+        raise ValueError("method only accepts 2d arrays")
+
+    chi2_stat = chi2_contingency(arr, correction=correction,
+                                 lambda_=lambda_)
+
+    phi2 = chi2_stat.statistic / arr.sum()
+    n_rows, n_cols = arr.shape
+    if method == "cramer":
+        value = phi2 / min(n_cols - 1, n_rows - 1)
+    elif method == "tschuprow":
+        value = phi2 / math.sqrt((n_rows - 1) * (n_cols - 1))
+    elif method == 'pearson':
+        value = phi2 / (1 + phi2)
+    else:
+        raise ValueError("Invalid argument value: 'method' argument must "
+                         "be 'cramer', 'tschuprow', or 'pearson'")
+
+    return math.sqrt(value)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/distributions.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/distributions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac9c37aa98c9545b2616c8d32e8f676d8d49289e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/distributions.py
@@ -0,0 +1,24 @@
+#
+# Author:  Travis Oliphant  2002-2011 with contributions from
+#          SciPy Developers 2004-2011
+#
+# NOTE: To look at history using `git blame`, use `git blame -M -C -C`
+#       instead of `git blame -Lxxx,+x`.
+#
+from ._distn_infrastructure import (rv_discrete, rv_continuous, rv_frozen)  # noqa: F401
+
+from . import _continuous_distns
+from . import _discrete_distns
+
+from ._continuous_distns import *  # noqa: F403
+from ._levy_stable import levy_stable
+from ._discrete_distns import *  # noqa: F403
+from ._entropy import entropy
+
+# For backwards compatibility e.g. pymc expects distributions.__all__.
+__all__ = ['rv_discrete', 'rv_continuous', 'rv_histogram', 'entropy']  # noqa: F405
+
+# Add only the distribution names, not the *_gen names.
+__all__ += _continuous_distns._distn_names
+__all__ += ['levy_stable']
+__all__ += _discrete_distns._distn_names
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/kde.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/kde.py
new file mode 100644
index 0000000000000000000000000000000000000000..4401da5a30f4452ab394232d3928493d0e3b77ec
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/kde.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["gaussian_kde"]  # noqa: F822
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="kde",
+                                   private_modules=["_kde"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/morestats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/morestats.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee8e6f43b7aaf7cb9af0fc1b37fdcee3a63277a3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/morestats.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'mvsdist',
+    'bayes_mvs', 'kstat', 'kstatvar', 'probplot', 'ppcc_max', 'ppcc_plot',
+    'boxcox_llf', 'boxcox', 'boxcox_normmax', 'boxcox_normplot',
+    'shapiro', 'anderson', 'ansari', 'bartlett', 'levene',
+    'fligner', 'mood', 'wilcoxon', 'median_test',
+    'circmean', 'circvar', 'circstd', 'anderson_ksamp',
+    'yeojohnson_llf', 'yeojohnson', 'yeojohnson_normmax',
+    'yeojohnson_normplot', 'find_repeats', 'chi2_contingency', 'distributions',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="morestats",
+                                   private_modules=["_morestats"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mstats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mstats.py
new file mode 100644
index 0000000000000000000000000000000000000000..88016af71803dc5c4ebadba168f22cdcd8273dbb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mstats.py
@@ -0,0 +1,140 @@
+"""
+===================================================================
+Statistical functions for masked arrays (:mod:`scipy.stats.mstats`)
+===================================================================
+
+.. currentmodule:: scipy.stats.mstats
+
+This module contains a large number of statistical functions that can
+be used with masked arrays.
+
+Most of these functions are similar to those in `scipy.stats` but might
+have small differences in the API or in the algorithm used. Since this
+is a relatively new package, some API changes are still possible.
+
+Summary statistics
+==================
+
+.. autosummary::
+   :toctree: generated/
+
+   describe
+   gmean
+   hmean
+   kurtosis
+   mode
+   mquantiles
+   hdmedian
+   hdquantiles
+   hdquantiles_sd
+   idealfourths
+   plotting_positions
+   meppf
+   moment
+   skew
+   tmean
+   tvar
+   tmin
+   tmax
+   tsem
+   variation
+   find_repeats
+   sem
+   trimmed_mean
+   trimmed_mean_ci
+   trimmed_std
+   trimmed_var
+
+Frequency statistics
+====================
+
+.. autosummary::
+   :toctree: generated/
+
+   scoreatpercentile
+
+Correlation functions
+=====================
+
+.. autosummary::
+   :toctree: generated/
+
+   f_oneway
+   pearsonr
+   spearmanr
+   pointbiserialr
+   kendalltau
+   kendalltau_seasonal
+   linregress
+   siegelslopes
+   theilslopes
+   sen_seasonal_slopes
+
+Statistical tests
+=================
+
+.. autosummary::
+   :toctree: generated/
+
+   ttest_1samp
+   ttest_onesamp
+   ttest_ind
+   ttest_rel
+   chisquare
+   kstest
+   ks_2samp
+   ks_1samp
+   ks_twosamp
+   mannwhitneyu
+   rankdata
+   kruskal
+   kruskalwallis
+   friedmanchisquare
+   brunnermunzel
+   skewtest
+   kurtosistest
+   normaltest
+
+Transformations
+===============
+
+.. autosummary::
+   :toctree: generated/
+
+   obrientransform
+   trim
+   trima
+   trimmed_stde
+   trimr
+   trimtail
+   trimboth
+   winsorize
+   zmap
+   zscore
+
+Other
+=====
+
+.. autosummary::
+   :toctree: generated/
+
+   argstoarray
+   count_tied_groups
+   msign
+   compare_medians_ms
+   median_cihs
+   mjci
+   mquantiles_cimj
+   rsh
+
+"""
+from . import _mstats_basic
+from . import _mstats_extras
+from ._mstats_basic import *  # noqa: F403
+from ._mstats_extras import *  # noqa: F403
+# Functions that support masked array input in stats but need to be kept in the
+# mstats namespace for backwards compatibility:
+from scipy.stats import gmean, hmean, zmap, zscore, chisquare
+
+__all__ = _mstats_basic.__all__ + _mstats_extras.__all__
+__all__ += ['gmean', 'hmean', 'zmap', 'zscore', 'chisquare']
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mstats_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mstats_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..19cc67a6acdfa054ffa2b29b6e774dd7aafda263
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mstats_basic.py
@@ -0,0 +1,42 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'argstoarray',
+    'count_tied_groups',
+    'describe',
+    'f_oneway', 'find_repeats','friedmanchisquare',
+    'kendalltau','kendalltau_seasonal','kruskal','kruskalwallis',
+    'ks_twosamp', 'ks_2samp', 'kurtosis', 'kurtosistest',
+    'ks_1samp', 'kstest',
+    'linregress',
+    'mannwhitneyu', 'meppf','mode','moment','mquantiles','msign',
+    'normaltest',
+    'obrientransform',
+    'pearsonr','plotting_positions','pointbiserialr',
+    'rankdata',
+    'scoreatpercentile','sem',
+    'sen_seasonal_slopes','skew','skewtest','spearmanr',
+    'siegelslopes', 'theilslopes',
+    'tmax','tmean','tmin','trim','trimboth',
+    'trimtail','trima','trimr','trimmed_mean','trimmed_std',
+    'trimmed_stde','trimmed_var','tsem','ttest_1samp','ttest_onesamp',
+    'ttest_ind','ttest_rel','tvar',
+    'variation',
+    'winsorize',
+    'brunnermunzel',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="mstats_basic",
+                                   private_modules=["_mstats_basic"], all=__all__,
+                                   attribute=name, correct_module="mstats")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mstats_extras.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mstats_extras.py
new file mode 100644
index 0000000000000000000000000000000000000000..fec695329cf2c2d58a4918cc99e209c0650c3ea6
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mstats_extras.py
@@ -0,0 +1,25 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'compare_medians_ms',
+    'hdquantiles', 'hdmedian', 'hdquantiles_sd',
+    'idealfourths',
+    'median_cihs','mjci','mquantiles_cimj',
+    'rsh',
+    'trimmed_mean_ci',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="mstats_extras",
+                                   private_modules=["_mstats_extras"], all=__all__,
+                                   attribute=name, correct_module="mstats")
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mvn.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mvn.py
new file mode 100644
index 0000000000000000000000000000000000000000..65da9e20f6a4e6d24c1cb206c59821730fb6ab83
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/mvn.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="mvn",
+                                   private_modules=["_mvn"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/qmc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/qmc.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8a08343cf4c759938b31c29e32aaa644bf6e0fd
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/qmc.py
@@ -0,0 +1,236 @@
+r"""
+====================================================
+Quasi-Monte Carlo submodule (:mod:`scipy.stats.qmc`)
+====================================================
+
+.. currentmodule:: scipy.stats.qmc
+
+This module provides Quasi-Monte Carlo generators and associated helper
+functions.
+
+
+Quasi-Monte Carlo
+=================
+
+Engines
+-------
+
+.. autosummary::
+   :toctree: generated/
+
+   QMCEngine
+   Sobol
+   Halton
+   LatinHypercube
+   PoissonDisk
+   MultinomialQMC
+   MultivariateNormalQMC
+
+Helpers
+-------
+
+.. autosummary::
+   :toctree: generated/
+
+   discrepancy
+   geometric_discrepancy
+   update_discrepancy
+   scale
+
+
+Introduction to Quasi-Monte Carlo
+=================================
+
+Quasi-Monte Carlo (QMC) methods [1]_, [2]_, [3]_ provide an
+:math:`n \times d` array of numbers in :math:`[0,1]`. They can be used in
+place of :math:`n` points from the :math:`U[0,1]^{d}` distribution. Compared to
+random points, QMC points are designed to have fewer gaps and clumps. This is
+quantified by discrepancy measures [4]_. From the Koksma-Hlawka
+inequality [5]_ we know that low discrepancy reduces a bound on
+integration error. Averaging a function :math:`f` over :math:`n` QMC points
+can achieve an integration error close to :math:`O(n^{-1})` for well
+behaved functions [2]_.
+
+Most QMC constructions are designed for special values of :math:`n`
+such as powers of 2 or large primes. Changing the sample
+size by even one can degrade their performance, even their
+rate of convergence [6]_. For instance :math:`n=100` points may give less
+accuracy than :math:`n=64` if the method was designed for :math:`n=2^m`.
+
+Some QMC constructions are extensible in :math:`n`: we can find
+another special sample size :math:`n' > n` and often an infinite
+sequence of increasing special sample sizes. Some QMC
+constructions are extensible in :math:`d`: we can increase the dimension,
+possibly to some upper bound, and typically without requiring
+special values of :math:`d`. Some QMC methods are extensible in
+both :math:`n` and :math:`d`.
+
+QMC points are deterministic. That makes it hard to estimate the accuracy of
+integrals estimated by averages over QMC points. Randomized QMC (RQMC) [7]_
+points are constructed so that each point is individually :math:`U[0,1]^{d}`
+while collectively the :math:`n` points retain their low discrepancy.
+One can make :math:`R` independent replications of RQMC points to
+see how stable a computation is. From :math:`R` independent values,
+a t-test (or bootstrap t-test [8]_) then gives approximate confidence
+intervals on the mean value. Some RQMC methods produce a
+root mean squared error that is actually :math:`o(1/n)` and smaller than
+the rate seen in unrandomized QMC. An intuitive explanation is
+that the error is a sum of many small ones and random errors
+cancel in a way that deterministic ones do not. RQMC also
+has advantages on integrands that are singular or, for other
+reasons, fail to be Riemann integrable.
+
+(R)QMC cannot beat Bahkvalov's curse of dimension (see [9]_). For
+any random or deterministic method, there are worst case functions
+that will give it poor performance in high dimensions. A worst
+case function for QMC might be 0 at all n points but very
+large elsewhere. Worst case analyses get very pessimistic
+in high dimensions. (R)QMC can bring a great improvement over
+MC when the functions on which it is used are not worst case.
+For instance (R)QMC can be especially effective on integrands
+that are well approximated by sums of functions of
+some small number of their input variables at a time [10]_, [11]_.
+That property is often a surprising finding about those functions.
+
+Also, to see an improvement over IID MC, (R)QMC requires a bit of smoothness of
+the integrand, roughly the mixed first order derivative in each direction,
+:math:`\partial^d f/\partial x_1 \cdots \partial x_d`, must be integral.
+For instance, a function that is 1 inside the hypersphere and 0 outside of it
+has infinite variation in the sense of Hardy and Krause for any dimension
+:math:`d = 2`.
+
+Scrambled nets are a kind of RQMC that have some valuable robustness
+properties [12]_. If the integrand is square integrable, they give variance
+:math:`var_{SNET} = o(1/n)`. There is a finite upper bound on
+:math:`var_{SNET} / var_{MC}` that holds simultaneously for every square
+integrable integrand. Scrambled nets satisfy a strong law of large numbers
+for :math:`f` in :math:`L^p` when :math:`p>1`. In some
+special cases there is a central limit theorem [13]_. For smooth enough
+integrands they can achieve RMSE nearly :math:`O(n^{-3})`. See [12]_
+for references about these properties.
+
+The main kinds of QMC methods are lattice rules [14]_ and digital
+nets and sequences [2]_, [15]_. The theories meet up in polynomial
+lattice rules [16]_ which can produce digital nets. Lattice rules
+require some form of search for good constructions. For digital
+nets there are widely used default constructions.
+
+The most widely used QMC methods are Sobol' sequences [17]_.
+These are digital nets. They are extensible in both :math:`n` and :math:`d`.
+They can be scrambled. The special sample sizes are powers
+of 2. Another popular method are Halton sequences [18]_.
+The constructions resemble those of digital nets. The earlier
+dimensions have much better equidistribution properties than
+later ones. There are essentially no special sample sizes.
+They are not thought to be as accurate as Sobol' sequences.
+They can be scrambled. The nets of Faure [19]_ are also widely
+used. All dimensions are equally good, but the special sample
+sizes grow rapidly with dimension :math:`d`. They can be scrambled.
+The nets of Niederreiter and Xing [20]_ have the best asymptotic
+properties but have not shown good empirical performance [21]_.
+
+Higher order digital nets are formed by a digit interleaving process
+in the digits of the constructed points. They can achieve higher
+levels of asymptotic accuracy given higher smoothness conditions on :math:`f`
+and they can be scrambled [22]_. There is little or no empirical work
+showing the improved rate to be attained.
+
+Using QMC is like using the entire period of a small random
+number generator. The constructions are similar and so
+therefore are the computational costs [23]_.
+
+(R)QMC is sometimes improved by passing the points through
+a baker's transformation (tent function) prior to using them.
+That function has the form :math:`1-2|x-1/2|`. As :math:`x` goes from 0 to
+1, this function goes from 0 to 1 and then back. It is very
+useful to produce a periodic function for lattice rules [14]_,
+and sometimes it improves the convergence rate [24]_.
+
+It is not straightforward to apply QMC methods to Markov
+chain Monte Carlo (MCMC).  We can think of MCMC as using
+:math:`n=1` point in :math:`[0,1]^{d}` for very large :math:`d`, with
+ergodic results corresponding to :math:`d \to \infty`. One proposal is
+in [25]_ and under strong conditions an improved rate of convergence
+has been shown [26]_.
+
+Returning to Sobol' points: there are many versions depending
+on what are called direction numbers. Those are the result of
+searches and are tabulated. A very widely used set of direction
+numbers come from [27]_. It is extensible in dimension up to
+:math:`d=21201`.
+
+References
+----------
+.. [1] Owen, Art B. "Monte Carlo Book: the Quasi-Monte Carlo parts." 2019.
+.. [2] Niederreiter, Harald. "Random number generation and quasi-Monte Carlo
+   methods." Society for Industrial and Applied Mathematics, 1992.
+.. [3] Dick, Josef, Frances Y. Kuo, and Ian H. Sloan. "High-dimensional
+   integration: the quasi-Monte Carlo way." Acta Numerica no. 22: 133, 2013.
+.. [4] Aho, A. V., C. Aistleitner, T. Anderson, K. Appel, V. Arnol'd, N.
+   Aronszajn, D. Asotsky et al. "W. Chen et al.(eds.), "A Panorama of
+   Discrepancy Theory", Sringer International Publishing,
+   Switzerland: 679, 2014.
+.. [5] Hickernell, Fred J. "Koksma-Hlawka Inequality." Wiley StatsRef:
+   Statistics Reference Online, 2014.
+.. [6] Owen, Art B. "On dropping the first Sobol' point." :arxiv:`2008.08051`,
+   2020.
+.. [7] L'Ecuyer, Pierre, and Christiane Lemieux. "Recent advances in randomized
+   quasi-Monte Carlo methods." In Modeling uncertainty, pp. 419-474. Springer,
+   New York, NY, 2002.
+.. [8] DiCiccio, Thomas J., and Bradley Efron. "Bootstrap confidence
+   intervals." Statistical science: 189-212, 1996.
+.. [9] Dimov, Ivan T. "Monte Carlo methods for applied scientists." World
+   Scientific, 2008.
+.. [10] Caflisch, Russel E., William J. Morokoff, and Art B. Owen. "Valuation
+   of mortgage backed securities using Brownian bridges to reduce effective
+   dimension." Journal of Computational Finance: no. 1 27-46, 1997.
+.. [11] Sloan, Ian H., and Henryk Wozniakowski. "When are quasi-Monte Carlo
+   algorithms efficient for high dimensional integrals?." Journal of Complexity
+   14, no. 1 (1998): 1-33.
+.. [12] Owen, Art B., and Daniel Rudolf, "A strong law of large numbers for
+   scrambled net integration." SIAM Review, to appear.
+.. [13] Loh, Wei-Liem. "On the asymptotic distribution of scrambled net
+   quadrature." The Annals of Statistics 31, no. 4: 1282-1324, 2003.
+.. [14] Sloan, Ian H. and S. Joe. "Lattice methods for multiple integration."
+   Oxford University Press, 1994.
+.. [15] Dick, Josef, and Friedrich Pillichshammer. "Digital nets and sequences:
+   discrepancy theory and quasi-Monte Carlo integration." Cambridge University
+   Press, 2010.
+.. [16] Dick, Josef, F. Kuo, Friedrich Pillichshammer, and I. Sloan.
+   "Construction algorithms for polynomial lattice rules for multivariate
+   integration." Mathematics of computation 74, no. 252: 1895-1921, 2005.
+.. [17] Sobol', Il'ya Meerovich. "On the distribution of points in a cube and
+   the approximate evaluation of integrals." Zhurnal Vychislitel'noi Matematiki
+   i Matematicheskoi Fiziki 7, no. 4: 784-802, 1967.
+.. [18] Halton, John H. "On the efficiency of certain quasi-random sequences of
+   points in evaluating multi-dimensional integrals." Numerische Mathematik 2,
+   no. 1: 84-90, 1960.
+.. [19] Faure, Henri. "Discrepance de suites associees a un systeme de
+   numeration (en dimension s)." Acta arithmetica 41, no. 4: 337-351, 1982.
+.. [20] Niederreiter, Harold, and Chaoping Xing. "Low-discrepancy sequences and
+   global function fields with many rational places." Finite Fields and their
+   applications 2, no. 3: 241-273, 1996.
+.. [21] Hong, Hee Sun, and Fred J. Hickernell. "Algorithm 823: Implementing
+   scrambled digital sequences." ACM Transactions on Mathematical Software
+   (TOMS) 29, no. 2: 95-109, 2003.
+.. [22] Dick, Josef. "Higher order scrambled digital nets achieve the optimal
+   rate of the root mean square error for smooth integrands." The Annals of
+   Statistics 39, no. 3: 1372-1398, 2011.
+.. [23] Niederreiter, Harald. "Multidimensional numerical integration using
+   pseudorandom numbers." In Stochastic Programming 84 Part I, pp. 17-38.
+   Springer, Berlin, Heidelberg, 1986.
+.. [24] Hickernell, Fred J. "Obtaining O (N-2+e) Convergence for Lattice
+   Quadrature Rules." In Monte Carlo and Quasi-Monte Carlo Methods 2000,
+   pp. 274-289. Springer, Berlin, Heidelberg, 2002.
+.. [25] Owen, Art B., and Seth D. Tribble. "A quasi-Monte Carlo Metropolis
+   algorithm." Proceedings of the National Academy of Sciences 102,
+   no. 25: 8844-8849, 2005.
+.. [26] Chen, Su. "Consistency and convergence rate of Markov chain quasi Monte
+   Carlo with examples." PhD diss., Stanford University, 2011.
+.. [27] Joe, Stephen, and Frances Y. Kuo. "Constructing Sobol sequences with
+   better two-dimensional projections." SIAM Journal on Scientific Computing
+   30, no. 5: 2635-2654, 2008.
+
+"""
+from ._qmc import *  # noqa: F403
+from ._qmc import __all__  # noqa: F401
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/sampling.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..12174d9dfb3cb93fa33811ed4b5d233817512e36
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/sampling.py
@@ -0,0 +1,73 @@
+"""
+======================================================
+Random Number Generators (:mod:`scipy.stats.sampling`)
+======================================================
+
+.. currentmodule:: scipy.stats.sampling
+
+This module contains a collection of random number generators to sample
+from univariate continuous and discrete distributions. It uses the
+implementation of a C library called "UNU.RAN". The only exception is
+RatioUniforms, which is a pure Python implementation of the
+Ratio-of-Uniforms method.
+
+Generators Wrapped
+==================
+
+For continuous distributions
+----------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   NumericalInverseHermite
+   NumericalInversePolynomial
+   TransformedDensityRejection
+   SimpleRatioUniforms
+   RatioUniforms
+
+For discrete distributions
+--------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   DiscreteAliasUrn
+   DiscreteGuideTable
+
+Warnings / Errors used in :mod:`scipy.stats.sampling`
+-----------------------------------------------------
+
+.. autosummary::
+   :toctree: generated/
+
+   UNURANError
+
+
+Generators for pre-defined distributions
+========================================
+
+To easily apply the above methods for some of the continuous distributions
+in :mod:`scipy.stats`, the following functionality can be used:
+
+.. autosummary::
+   :toctree: generated/
+
+   FastGeneratorInversion
+
+"""
+from ._sampling import FastGeneratorInversion, RatioUniforms  # noqa: F401
+from ._unuran.unuran_wrapper import (  # noqa: F401
+   TransformedDensityRejection,
+   DiscreteAliasUrn,
+   DiscreteGuideTable,
+   NumericalInversePolynomial,
+   NumericalInverseHermite,
+   SimpleRatioUniforms,
+   UNURANError
+)
+
+__all__ = ["NumericalInverseHermite", "NumericalInversePolynomial",
+           "TransformedDensityRejection", "SimpleRatioUniforms",
+           "RatioUniforms", "DiscreteAliasUrn", "DiscreteGuideTable",
+           "UNURANError", "FastGeneratorInversion"]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/stats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5d278e209ce8d487235ee281620af8520d76d87
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/stats.py
@@ -0,0 +1,41 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.stats` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [  # noqa: F822
+    'find_repeats', 'gmean', 'hmean', 'pmean', 'mode', 'tmean', 'tvar',
+    'tmin', 'tmax', 'tstd', 'tsem', 'moment',
+    'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
+    'normaltest', 'jarque_bera',
+    'scoreatpercentile', 'percentileofscore',
+    'cumfreq', 'relfreq', 'obrientransform',
+    'sem', 'zmap', 'zscore', 'gzscore', 'iqr', 'gstd',
+    'median_abs_deviation',
+    'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
+    'f_oneway',
+    'pearsonr', 'fisher_exact',
+    'spearmanr', 'pointbiserialr',
+    'kendalltau', 'weightedtau', 'multiscale_graphcorr',
+    'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
+    'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
+    'kstest', 'ks_1samp', 'ks_2samp',
+    'chisquare', 'power_divergence',
+    'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
+    'rankdata',
+    'combine_pvalues', 'wasserstein_distance', 'energy_distance',
+    'brunnermunzel', 'alexandergovern', 'distributions',
+    'mstats_basic',
+]
+
+
+def __dir__():
+    return __all__
+
+
+def __getattr__(name):
+    return _sub_module_deprecation(sub_package="stats", module="stats",
+                                   private_modules=["_stats_py", "_mgc"], all=__all__,
+                                   attribute=name)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/__init__.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/common_tests.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/common_tests.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1e5619318bce180357be0c0cd7a93b83edf8523
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/common_tests.py
@@ -0,0 +1,354 @@
+import pickle
+
+import numpy as np
+import numpy.testing as npt
+from numpy.testing import assert_allclose, assert_equal
+from pytest import raises as assert_raises
+
+import numpy.ma.testutils as ma_npt
+
+from scipy._lib._util import (
+    getfullargspec_no_self as _getfullargspec, np_long
+)
+from scipy._lib._array_api_no_0d import xp_assert_equal
+from scipy import stats
+
+
+def check_named_results(res, attributes, ma=False, xp=None):
+    for i, attr in enumerate(attributes):
+        if ma:
+            ma_npt.assert_equal(res[i], getattr(res, attr))
+        elif xp is not None:
+            xp_assert_equal(res[i], getattr(res, attr))
+        else:
+            npt.assert_equal(res[i], getattr(res, attr))
+
+
+def check_normalization(distfn, args, distname):
+    norm_moment = distfn.moment(0, *args)
+    npt.assert_allclose(norm_moment, 1.0)
+
+    if distname == "rv_histogram_instance":
+        atol, rtol = 1e-5, 0
+    else:
+        atol, rtol = 1e-7, 1e-7
+
+    normalization_expect = distfn.expect(lambda x: 1, args=args)
+    npt.assert_allclose(normalization_expect, 1.0, atol=atol, rtol=rtol,
+                        err_msg=distname, verbose=True)
+
+    _a, _b = distfn.support(*args)
+    normalization_cdf = distfn.cdf(_b, *args)
+    npt.assert_allclose(normalization_cdf, 1.0)
+
+
+def check_moment(distfn, arg, m, v, msg):
+    m1 = distfn.moment(1, *arg)
+    m2 = distfn.moment(2, *arg)
+    if not np.isinf(m):
+        npt.assert_almost_equal(m1, m, decimal=10,
+                                err_msg=msg + ' - 1st moment')
+    else:                     # or np.isnan(m1),
+        npt.assert_(np.isinf(m1),
+                    msg + f' - 1st moment -infinite, m1={str(m1)}')
+
+    if not np.isinf(v):
+        npt.assert_almost_equal(m2 - m1 * m1, v, decimal=10,
+                                err_msg=msg + ' - 2ndt moment')
+    else:                     # or np.isnan(m2),
+        npt.assert_(np.isinf(m2), msg + f' - 2nd moment -infinite, {m2=}')
+
+
+def check_mean_expect(distfn, arg, m, msg):
+    if np.isfinite(m):
+        m1 = distfn.expect(lambda x: x, arg)
+        npt.assert_almost_equal(m1, m, decimal=5,
+                                err_msg=msg + ' - 1st moment (expect)')
+
+
+def check_var_expect(distfn, arg, m, v, msg):
+    dist_looser_tolerances = {"rv_histogram_instance" , "ksone"}
+    kwargs = {'rtol': 5e-6} if msg in dist_looser_tolerances else {}
+    if np.isfinite(v):
+        m2 = distfn.expect(lambda x: x*x, arg)
+        npt.assert_allclose(m2, v + m*m, **kwargs)
+
+
+def check_skew_expect(distfn, arg, m, v, s, msg):
+    if np.isfinite(s):
+        m3e = distfn.expect(lambda x: np.power(x-m, 3), arg)
+        npt.assert_almost_equal(m3e, s * np.power(v, 1.5),
+                                decimal=5, err_msg=msg + ' - skew')
+    else:
+        npt.assert_(np.isnan(s))
+
+
+def check_kurt_expect(distfn, arg, m, v, k, msg):
+    if np.isfinite(k):
+        m4e = distfn.expect(lambda x: np.power(x-m, 4), arg)
+        npt.assert_allclose(m4e, (k + 3.) * np.power(v, 2),
+                            atol=1e-5, rtol=1e-5,
+                            err_msg=msg + ' - kurtosis')
+    elif not np.isposinf(k):
+        npt.assert_(np.isnan(k))
+
+
+def check_munp_expect(dist, args, msg):
+    # If _munp is overridden, test a higher moment. (Before gh-18634, some
+    # distributions had issues with moments 5 and higher.)
+    if dist._munp.__func__ != stats.rv_continuous._munp:
+        res = dist.moment(5, *args)  # shouldn't raise an error
+        ref = dist.expect(lambda x: x ** 5, args, lb=-np.inf, ub=np.inf)
+        if not np.isfinite(res):  # could be valid; automated test can't know
+            return
+        # loose tolerance, mostly to see whether _munp returns *something*
+        assert_allclose(res, ref, atol=1e-10, rtol=1e-4,
+                        err_msg=msg + ' - higher moment / _munp')
+
+
+def check_entropy(distfn, arg, msg):
+    ent = distfn.entropy(*arg)
+    npt.assert_(not np.isnan(ent), msg + 'test Entropy is nan')
+
+
+def check_private_entropy(distfn, args, superclass):
+    # compare a generic _entropy with the distribution-specific implementation
+    npt.assert_allclose(distfn._entropy(*args),
+                        superclass._entropy(distfn, *args))
+
+
+def check_entropy_vect_scale(distfn, arg):
+    # check 2-d
+    sc = np.asarray([[1, 2], [3, 4]])
+    v_ent = distfn.entropy(*arg, scale=sc)
+    s_ent = [distfn.entropy(*arg, scale=s) for s in sc.ravel()]
+    s_ent = np.asarray(s_ent).reshape(v_ent.shape)
+    assert_allclose(v_ent, s_ent, atol=1e-14)
+
+    # check invalid value, check cast
+    sc = [1, 2, -3]
+    v_ent = distfn.entropy(*arg, scale=sc)
+    s_ent = [distfn.entropy(*arg, scale=s) for s in sc]
+    s_ent = np.asarray(s_ent).reshape(v_ent.shape)
+    assert_allclose(v_ent, s_ent, atol=1e-14)
+
+
+def check_edge_support(distfn, args):
+    # Make sure that x=self.a and self.b are handled correctly.
+    x = distfn.support(*args)
+    if isinstance(distfn, stats.rv_discrete):
+        x = x[0]-1, x[1]
+
+    npt.assert_equal(distfn.cdf(x, *args), [0.0, 1.0])
+    npt.assert_equal(distfn.sf(x, *args), [1.0, 0.0])
+
+    if distfn.name not in ('skellam', 'dlaplace'):
+        # with a = -inf, log(0) generates warnings
+        npt.assert_equal(distfn.logcdf(x, *args), [-np.inf, 0.0])
+        npt.assert_equal(distfn.logsf(x, *args), [0.0, -np.inf])
+
+    npt.assert_equal(distfn.ppf([0.0, 1.0], *args), x)
+    npt.assert_equal(distfn.isf([0.0, 1.0], *args), x[::-1])
+
+    # out-of-bounds for isf & ppf
+    npt.assert_(np.isnan(distfn.isf([-1, 2], *args)).all())
+    npt.assert_(np.isnan(distfn.ppf([-1, 2], *args)).all())
+
+
+def check_named_args(distfn, x, shape_args, defaults, meths):
+    ## Check calling w/ named arguments.
+
+    # check consistency of shapes, numargs and _parse signature
+    signature = _getfullargspec(distfn._parse_args)
+    npt.assert_(signature.varargs is None)
+    npt.assert_(signature.varkw is None)
+    npt.assert_(not signature.kwonlyargs)
+    npt.assert_(list(signature.defaults) == list(defaults))
+
+    shape_argnames = signature.args[:-len(defaults)]  # a, b, loc=0, scale=1
+    if distfn.shapes:
+        shapes_ = distfn.shapes.replace(',', ' ').split()
+    else:
+        shapes_ = ''
+    npt.assert_(len(shapes_) == distfn.numargs)
+    npt.assert_(len(shapes_) == len(shape_argnames))
+
+    # check calling w/ named arguments
+    shape_args = list(shape_args)
+
+    vals = [meth(x, *shape_args) for meth in meths]
+    npt.assert_(np.all(np.isfinite(vals)))
+
+    names, a, k = shape_argnames[:], shape_args[:], {}
+    while names:
+        k.update({names.pop(): a.pop()})
+        v = [meth(x, *a, **k) for meth in meths]
+        npt.assert_array_equal(vals, v)
+        if 'n' not in k.keys():
+            # `n` is first parameter of moment(), so can't be used as named arg
+            npt.assert_equal(distfn.moment(1, *a, **k),
+                             distfn.moment(1, *shape_args))
+
+    # unknown arguments should not go through:
+    k.update({'kaboom': 42})
+    assert_raises(TypeError, distfn.cdf, x, **k)
+
+
+def check_random_state_property(distfn, args):
+    # check the random_state attribute of a distribution *instance*
+
+    # This test fiddles with distfn.random_state. This breaks other tests,
+    # hence need to save it and then restore.
+    rndm = distfn.random_state
+
+    # baseline: this relies on the global state
+    np.random.seed(1234)
+    distfn.random_state = None
+    r0 = distfn.rvs(*args, size=8)
+
+    # use an explicit instance-level random_state
+    distfn.random_state = 1234
+    r1 = distfn.rvs(*args, size=8)
+    npt.assert_equal(r0, r1)
+
+    distfn.random_state = np.random.RandomState(1234)
+    r2 = distfn.rvs(*args, size=8)
+    npt.assert_equal(r0, r2)
+
+    # check that np.random.Generator can be used (numpy >= 1.17)
+    if hasattr(np.random, 'default_rng'):
+        # obtain a np.random.Generator object
+        rng = np.random.default_rng(1234)
+        distfn.rvs(*args, size=1, random_state=rng)
+
+    # can override the instance-level random_state for an individual .rvs call
+    distfn.random_state = 2
+    orig_state = distfn.random_state.get_state()
+
+    r3 = distfn.rvs(*args, size=8, random_state=np.random.RandomState(1234))
+    npt.assert_equal(r0, r3)
+
+    # ... and that does not alter the instance-level random_state!
+    npt.assert_equal(distfn.random_state.get_state(), orig_state)
+
+    # finally, restore the random_state
+    distfn.random_state = rndm
+
+
+def check_meth_dtype(distfn, arg, meths):
+    q0 = [0.25, 0.5, 0.75]
+    x0 = distfn.ppf(q0, *arg)
+    x_cast = [x0.astype(tp) for tp in (np_long, np.float16, np.float32,
+                                       np.float64)]
+
+    for x in x_cast:
+        # casting may have clipped the values, exclude those
+        distfn._argcheck(*arg)
+        x = x[(distfn.a < x) & (x < distfn.b)]
+        for meth in meths:
+            val = meth(x, *arg)
+            npt.assert_(val.dtype == np.float64)
+
+
+def check_ppf_dtype(distfn, arg):
+    q0 = np.asarray([0.25, 0.5, 0.75])
+    q_cast = [q0.astype(tp) for tp in (np.float16, np.float32, np.float64)]
+    for q in q_cast:
+        for meth in [distfn.ppf, distfn.isf]:
+            val = meth(q, *arg)
+            npt.assert_(val.dtype == np.float64)
+
+
+def check_cmplx_deriv(distfn, arg):
+    # Distributions allow complex arguments.
+    def deriv(f, x, *arg):
+        x = np.asarray(x)
+        h = 1e-10
+        return (f(x + h*1j, *arg)/h).imag
+
+    x0 = distfn.ppf([0.25, 0.51, 0.75], *arg)
+    x_cast = [x0.astype(tp) for tp in (np_long, np.float16, np.float32,
+                                       np.float64)]
+
+    for x in x_cast:
+        # casting may have clipped the values, exclude those
+        distfn._argcheck(*arg)
+        x = x[(distfn.a < x) & (x < distfn.b)]
+
+        pdf, cdf, sf = distfn.pdf(x, *arg), distfn.cdf(x, *arg), distfn.sf(x, *arg)
+        assert_allclose(deriv(distfn.cdf, x, *arg), pdf, rtol=1e-5)
+        assert_allclose(deriv(distfn.logcdf, x, *arg), pdf/cdf, rtol=1e-5)
+
+        assert_allclose(deriv(distfn.sf, x, *arg), -pdf, rtol=1e-5)
+        assert_allclose(deriv(distfn.logsf, x, *arg), -pdf/sf, rtol=1e-5)
+
+        assert_allclose(deriv(distfn.logpdf, x, *arg),
+                        deriv(distfn.pdf, x, *arg) / distfn.pdf(x, *arg),
+                        rtol=1e-5)
+
+
+def check_pickling(distfn, args):
+    # check that a distribution instance pickles and unpickles
+    # pay special attention to the random_state property
+
+    # save the random_state (restore later)
+    rndm = distfn.random_state
+
+    # check unfrozen
+    distfn.random_state = 1234
+    distfn.rvs(*args, size=8)
+    s = pickle.dumps(distfn)
+    r0 = distfn.rvs(*args, size=8)
+
+    unpickled = pickle.loads(s)
+    r1 = unpickled.rvs(*args, size=8)
+    npt.assert_equal(r0, r1)
+
+    # also smoke test some methods
+    medians = [distfn.ppf(0.5, *args), unpickled.ppf(0.5, *args)]
+    npt.assert_equal(medians[0], medians[1])
+    npt.assert_equal(distfn.cdf(medians[0], *args),
+                     unpickled.cdf(medians[1], *args))
+
+    # check frozen pickling/unpickling with rvs
+    frozen_dist = distfn(*args)
+    pkl = pickle.dumps(frozen_dist)
+    unpickled = pickle.loads(pkl)
+
+    r0 = frozen_dist.rvs(size=8)
+    r1 = unpickled.rvs(size=8)
+    npt.assert_equal(r0, r1)
+
+    # check pickling/unpickling of .fit method
+    if hasattr(distfn, "fit"):
+        fit_function = distfn.fit
+        pickled_fit_function = pickle.dumps(fit_function)
+        unpickled_fit_function = pickle.loads(pickled_fit_function)
+        assert fit_function.__name__ == unpickled_fit_function.__name__ == "fit"
+
+    # restore the random_state
+    distfn.random_state = rndm
+
+
+def check_freezing(distfn, args):
+    # regression test for gh-11089: freezing a distribution fails
+    # if loc and/or scale are specified
+    if isinstance(distfn, stats.rv_continuous):
+        locscale = {'loc': 1, 'scale': 2}
+    else:
+        locscale = {'loc': 1}
+
+    rv = distfn(*args, **locscale)
+    assert rv.a == distfn(*args).a
+    assert rv.b == distfn(*args).b
+
+
+def check_rvs_broadcast(distfunc, distname, allargs, shape, shape_only, otype):
+    np.random.seed(123)
+    sample = distfunc.rvs(*allargs)
+    assert_equal(sample.shape, shape, f"{distname}: rvs failed to broadcast")
+    if not shape_only:
+        rvs = np.vectorize(lambda *allargs: distfunc.rvs(*allargs), otypes=otype)
+        np.random.seed(123)
+        expected = rvs(*allargs)
+        assert_allclose(sample, expected, rtol=1e-13)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/_mvt.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/_mvt.py
new file mode 100644
index 0000000000000000000000000000000000000000..c346d0daded4b6e734718742cc8950b84ed333f7
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/_mvt.py
@@ -0,0 +1,171 @@
+import math
+import numpy as np
+from scipy import special
+from scipy.stats._qmc import primes_from_2_to
+
+
+def _primes(n):
+    # Defined to facilitate comparison between translation and source
+    # In Matlab, primes(10.5) -> first four primes, primes(11.5) -> first five
+    return primes_from_2_to(math.ceil(n))
+
+
+def _gaminv(a, b):
+    # Defined to facilitate comparison between translation and source
+    # Matlab's `gaminv` is like `special.gammaincinv` but args are reversed
+    return special.gammaincinv(b, a)
+
+
+def _qsimvtv(m, nu, sigma, a, b, rng):
+    """Estimates the multivariate t CDF using randomized QMC
+
+    Parameters
+    ----------
+    m : int
+        The number of points
+    nu : float
+        Degrees of freedom
+    sigma : ndarray
+        A 2D positive semidefinite covariance matrix
+    a : ndarray
+        Lower integration limits
+    b : ndarray
+        Upper integration limits.
+    rng : Generator
+        Pseudorandom number generator
+
+    Returns
+    -------
+    p : float
+        The estimated CDF.
+    e : float
+        An absolute error estimate.
+
+    """
+    # _qsimvtv is a Python translation of the Matlab function qsimvtv,
+    # semicolons and all.
+    #
+    #   This function uses an algorithm given in the paper
+    #      "Comparison of Methods for the Numerical Computation of
+    #       Multivariate t Probabilities", in
+    #      J. of Computational and Graphical Stat., 11(2002), pp. 950-971, by
+    #          Alan Genz and Frank Bretz
+    #
+    #   The primary references for the numerical integration are
+    #    "On a Number-Theoretical Integration Method"
+    #    H. Niederreiter, Aequationes Mathematicae, 8(1972), pp. 304-11.
+    #    and
+    #    "Randomization of Number Theoretic Methods for Multiple Integration"
+    #     R. Cranley & T.N.L. Patterson, SIAM J Numer Anal, 13(1976), pp. 904-14.
+    #
+    #   Alan Genz is the author of this function and following Matlab functions.
+    #          Alan Genz, WSU Math, PO Box 643113, Pullman, WA 99164-3113
+    #          Email : alangenz@wsu.edu
+    #
+    # Copyright (C) 2013, Alan Genz,  All rights reserved.
+    #
+    # Redistribution and use in source and binary forms, with or without
+    # modification, are permitted provided the following conditions are met:
+    #   1. Redistributions of source code must retain the above copyright
+    #      notice, this list of conditions and the following disclaimer.
+    #   2. Redistributions in binary form must reproduce the above copyright
+    #      notice, this list of conditions and the following disclaimer in
+    #      the documentation and/or other materials provided with the
+    #      distribution.
+    #   3. The contributor name(s) may not be used to endorse or promote
+    #      products derived from this software without specific prior
+    #      written permission.
+    # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+    # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+    # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+    # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+    # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+    # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+    # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+    # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+    # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+    # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF USE
+    # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+    # Initialization
+    sn = max(1, math.sqrt(nu)); ch, az, bz = _chlrps(sigma, a/sn, b/sn)
+    n = len(sigma); N = 10; P = math.ceil(m/N); on = np.ones(P); p = 0; e = 0
+    ps = np.sqrt(_primes(5*n*math.log(n+4)/4)); q = ps[:, np.newaxis]  # Richtmyer gens.
+
+    # Randomization loop for ns samples
+    c = None; dc = None
+    for S in range(N):
+        vp = on.copy(); s = np.zeros((n, P))
+        for i in range(n):
+            x = np.abs(2*np.mod(q[i]*np.arange(1, P+1) + rng.random(), 1)-1)  # periodizing transform
+            if i == 0:
+                r = on
+                if nu > 0:
+                    r = np.sqrt(2*_gaminv(x, nu/2))
+            else:
+                y = _Phinv(c + x*dc)
+                s[i:] += ch[i:, i-1:i] * y
+            si = s[i, :]; c = on.copy(); ai = az[i]*r - si; d = on.copy(); bi = bz[i]*r - si
+            c[ai <= -9] = 0; tl = abs(ai) < 9; c[tl] = _Phi(ai[tl])
+            d[bi <= -9] = 0; tl = abs(bi) < 9; d[tl] = _Phi(bi[tl])
+            dc = d - c; vp = vp * dc
+        d = (np.mean(vp) - p)/(S + 1); p = p + d; e = (S - 1)*e/(S + 1) + d**2
+    e = math.sqrt(e)  # error estimate is 3 times std error with N samples.
+    return p, e
+
+
+#  Standard statistical normal distribution functions
+def _Phi(z):
+    return special.ndtr(z)
+
+
+def _Phinv(p):
+    return special.ndtri(p)
+
+
+def _chlrps(R, a, b):
+    """
+    Computes permuted and scaled lower Cholesky factor c for R which may be
+    singular, also permuting and scaling integration limit vectors a and b.
+    """
+    ep = 1e-10  # singularity tolerance
+    eps = np.finfo(R.dtype).eps
+
+    n = len(R); c = R.copy(); ap = a.copy(); bp = b.copy(); d = np.sqrt(np.maximum(np.diag(c), 0))
+    for i in range(n):
+        if d[i] > 0:
+            c[:, i] /= d[i]; c[i, :] /= d[i]
+            ap[i] /= d[i]; bp[i] /= d[i]
+    y = np.zeros((n, 1)); sqtp = math.sqrt(2*math.pi)
+
+    for k in range(n):
+        im = k; ckk = 0; dem = 1; s = 0
+        for i in range(k, n):
+            if c[i, i] > eps:
+                cii = math.sqrt(max(c[i, i], 0))
+                if i > 0: s = c[i, :k] @ y[:k]
+                ai = (ap[i]-s)/cii; bi = (bp[i]-s)/cii; de = _Phi(bi)-_Phi(ai)
+                if de <= dem:
+                    ckk = cii; dem = de; am = ai; bm = bi; im = i
+        if im > k:
+            ap[[im, k]] = ap[[k, im]]; bp[[im, k]] = bp[[k, im]]; c[im, im] = c[k, k]
+            t = c[im, :k].copy(); c[im, :k] = c[k, :k]; c[k, :k] = t
+            t = c[im+1:, im].copy(); c[im+1:, im] = c[im+1:, k]; c[im+1:, k] = t
+            t = c[k+1:im, k].copy(); c[k+1:im, k] = c[im, k+1:im].T; c[im, k+1:im] = t.T
+        if ckk > ep*(k+1):
+            c[k, k] = ckk; c[k, k+1:] = 0
+            for i in range(k+1, n):
+                c[i, k] = c[i, k]/ckk; c[i, k+1:i+1] = c[i, k+1:i+1] - c[i, k]*c[k+1:i+1, k].T
+            if abs(dem) > ep:
+                y[k] = (np.exp(-am**2/2) - np.exp(-bm**2/2)) / (sqtp*dem)
+            else:
+                y[k] = (am + bm) / 2
+                if am < -10:
+                    y[k] = bm
+                elif bm > 10:
+                    y[k] = am
+            c[k, :k+1] /= ckk; ap[k] /= ckk; bp[k] /= ckk
+        else:
+            c[k:, k] = 0; y[k] = (ap[k] + bp[k])/2
+        pass
+    return c, ap, bp
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/fisher_exact_results_from_r.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/fisher_exact_results_from_r.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7dd8936018eae2f74cc6f5966235a86fa821793
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/fisher_exact_results_from_r.py
@@ -0,0 +1,607 @@
+# DO NOT EDIT THIS FILE!
+# This file was generated by the R script
+#     generate_fisher_exact_results_from_r.R
+# The script was run with R version 3.6.2 (2019-12-12) at 2020-11-09 06:16:09
+
+
+from collections import namedtuple
+import numpy as np
+
+
+Inf = np.inf
+
+Parameters = namedtuple('Parameters',
+                        ['table', 'confidence_level', 'alternative'])
+RResults = namedtuple('RResults',
+                      ['pvalue', 'conditional_odds_ratio',
+                       'conditional_odds_ratio_ci'])
+data = [
+    (Parameters(table=[[100, 2], [1000, 5]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.1300759363430016,
+              conditional_odds_ratio=0.25055839934223,
+              conditional_odds_ratio_ci=(0.04035202926536294,
+                                         2.662846672960251))),
+    (Parameters(table=[[2, 7], [8, 2]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.02301413756522116,
+              conditional_odds_ratio=0.0858623513573622,
+              conditional_odds_ratio_ci=(0.004668988338943325,
+                                         0.895792956493601))),
+    (Parameters(table=[[5, 1], [10, 10]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.1973244147157191,
+              conditional_odds_ratio=4.725646047336587,
+              conditional_odds_ratio_ci=(0.4153910882532168,
+                                         259.2593661129417))),
+    (Parameters(table=[[5, 15], [20, 20]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.09580440012477633,
+              conditional_odds_ratio=0.3394396617440851,
+              conditional_odds_ratio_ci=(0.08056337526385809,
+                                         1.22704788545557))),
+    (Parameters(table=[[5, 16], [16, 25]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.2697004098849359,
+              conditional_odds_ratio=0.4937791394540491,
+              conditional_odds_ratio_ci=(0.1176691231650079,
+                                         1.787463657995973))),
+    (Parameters(table=[[10, 5], [10, 1]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.1973244147157192,
+              conditional_odds_ratio=0.2116112781158479,
+              conditional_odds_ratio_ci=(0.003857141267422399,
+                                         2.407369893767229))),
+    (Parameters(table=[[10, 5], [10, 0]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.06126482213438735,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         1.451643573543705))),
+    (Parameters(table=[[5, 0], [1, 4]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.04761904761904762,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(1.024822256141754,
+                                         Inf))),
+    (Parameters(table=[[0, 5], [1, 4]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         39.00054996869288))),
+    (Parameters(table=[[5, 1], [0, 4]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.04761904761904761,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(1.024822256141754,
+                                         Inf))),
+    (Parameters(table=[[0, 1], [3, 2]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         39.00054996869287))),
+    (Parameters(table=[[200, 7], [8, 300]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=2.005657880389071e-122,
+              conditional_odds_ratio=977.7866978606228,
+              conditional_odds_ratio_ci=(349.2595113327733,
+                                         3630.382605689872))),
+    (Parameters(table=[[28, 21], [6, 1957]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=5.728437460831947e-44,
+              conditional_odds_ratio=425.2403028434684,
+              conditional_odds_ratio_ci=(152.4166024390096,
+                                         1425.700792178893))),
+    (Parameters(table=[[190, 800], [200, 900]],
+                confidence_level=0.95,
+                alternative='two.sided'),
+     RResults(pvalue=0.574111858126088,
+              conditional_odds_ratio=1.068697577856801,
+              conditional_odds_ratio_ci=(0.8520462587912048,
+                                         1.340148950273938))),
+    (Parameters(table=[[100, 2], [1000, 5]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.1300759363430016,
+              conditional_odds_ratio=0.25055839934223,
+              conditional_odds_ratio_ci=(0.02502345007115455,
+                                         6.304424772117853))),
+    (Parameters(table=[[2, 7], [8, 2]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.02301413756522116,
+              conditional_odds_ratio=0.0858623513573622,
+              conditional_odds_ratio_ci=(0.001923034001462487,
+                                         1.53670836950172))),
+    (Parameters(table=[[5, 1], [10, 10]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.1973244147157191,
+              conditional_odds_ratio=4.725646047336587,
+              conditional_odds_ratio_ci=(0.2397970951413721,
+                                         1291.342011095509))),
+    (Parameters(table=[[5, 15], [20, 20]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.09580440012477633,
+              conditional_odds_ratio=0.3394396617440851,
+              conditional_odds_ratio_ci=(0.05127576113762925,
+                                         1.717176678806983))),
+    (Parameters(table=[[5, 16], [16, 25]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.2697004098849359,
+              conditional_odds_ratio=0.4937791394540491,
+              conditional_odds_ratio_ci=(0.07498546954483619,
+                                         2.506969905199901))),
+    (Parameters(table=[[10, 5], [10, 1]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.1973244147157192,
+              conditional_odds_ratio=0.2116112781158479,
+              conditional_odds_ratio_ci=(0.0007743881879531337,
+                                         4.170192301163831))),
+    (Parameters(table=[[10, 5], [10, 0]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.06126482213438735,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         2.642491011905582))),
+    (Parameters(table=[[5, 0], [1, 4]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.04761904761904762,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(0.496935393325443,
+                                         Inf))),
+    (Parameters(table=[[0, 5], [1, 4]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         198.019801980198))),
+    (Parameters(table=[[5, 1], [0, 4]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.04761904761904761,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(0.496935393325443,
+                                         Inf))),
+    (Parameters(table=[[0, 1], [3, 2]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         198.019801980198))),
+    (Parameters(table=[[200, 7], [8, 300]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=2.005657880389071e-122,
+              conditional_odds_ratio=977.7866978606228,
+              conditional_odds_ratio_ci=(270.0334165523604,
+                                         5461.333333326708))),
+    (Parameters(table=[[28, 21], [6, 1957]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=5.728437460831947e-44,
+              conditional_odds_ratio=425.2403028434684,
+              conditional_odds_ratio_ci=(116.7944750275836,
+                                         1931.995993191814))),
+    (Parameters(table=[[190, 800], [200, 900]],
+                confidence_level=0.99,
+                alternative='two.sided'),
+     RResults(pvalue=0.574111858126088,
+              conditional_odds_ratio=1.068697577856801,
+              conditional_odds_ratio_ci=(0.7949398282935892,
+                                         1.436229679394333))),
+    (Parameters(table=[[100, 2], [1000, 5]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.1300759363430016,
+              conditional_odds_ratio=0.25055839934223,
+              conditional_odds_ratio_ci=(0,
+                                         1.797867027270803))),
+    (Parameters(table=[[2, 7], [8, 2]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.0185217259520665,
+              conditional_odds_ratio=0.0858623513573622,
+              conditional_odds_ratio_ci=(0,
+                                         0.6785254803404526))),
+    (Parameters(table=[[5, 1], [10, 10]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.9782608695652173,
+              conditional_odds_ratio=4.725646047336587,
+              conditional_odds_ratio_ci=(0,
+                                         127.8497388102893))),
+    (Parameters(table=[[5, 15], [20, 20]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.05625775074399956,
+              conditional_odds_ratio=0.3394396617440851,
+              conditional_odds_ratio_ci=(0,
+                                         1.032332939718425))),
+    (Parameters(table=[[5, 16], [16, 25]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.1808979350599346,
+              conditional_odds_ratio=0.4937791394540491,
+              conditional_odds_ratio_ci=(0,
+                                         1.502407513296985))),
+    (Parameters(table=[[10, 5], [10, 1]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.1652173913043479,
+              conditional_odds_ratio=0.2116112781158479,
+              conditional_odds_ratio_ci=(0,
+                                         1.820421051562392))),
+    (Parameters(table=[[10, 5], [10, 0]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.0565217391304348,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         1.06224603077045))),
+    (Parameters(table=[[5, 0], [1, 4]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[0, 5], [1, 4]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.5,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         19.00192394479939))),
+    (Parameters(table=[[5, 1], [0, 4]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[0, 1], [3, 2]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.4999999999999999,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         19.00192394479939))),
+    (Parameters(table=[[200, 7], [8, 300]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=977.7866978606228,
+              conditional_odds_ratio_ci=(0,
+                                         3045.460216525746))),
+    (Parameters(table=[[28, 21], [6, 1957]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=425.2403028434684,
+              conditional_odds_ratio_ci=(0,
+                                         1186.440170942579))),
+    (Parameters(table=[[190, 800], [200, 900]],
+                confidence_level=0.95,
+                alternative='less'),
+     RResults(pvalue=0.7416227010368963,
+              conditional_odds_ratio=1.068697577856801,
+              conditional_odds_ratio_ci=(0,
+                                         1.293551891610822))),
+    (Parameters(table=[[100, 2], [1000, 5]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.1300759363430016,
+              conditional_odds_ratio=0.25055839934223,
+              conditional_odds_ratio_ci=(0,
+                                         4.375946050832565))),
+    (Parameters(table=[[2, 7], [8, 2]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.0185217259520665,
+              conditional_odds_ratio=0.0858623513573622,
+              conditional_odds_ratio_ci=(0,
+                                         1.235282118191202))),
+    (Parameters(table=[[5, 1], [10, 10]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.9782608695652173,
+              conditional_odds_ratio=4.725646047336587,
+              conditional_odds_ratio_ci=(0,
+                                         657.2063583945989))),
+    (Parameters(table=[[5, 15], [20, 20]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.05625775074399956,
+              conditional_odds_ratio=0.3394396617440851,
+              conditional_odds_ratio_ci=(0,
+                                         1.498867660683128))),
+    (Parameters(table=[[5, 16], [16, 25]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.1808979350599346,
+              conditional_odds_ratio=0.4937791394540491,
+              conditional_odds_ratio_ci=(0,
+                                         2.186159386716762))),
+    (Parameters(table=[[10, 5], [10, 1]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.1652173913043479,
+              conditional_odds_ratio=0.2116112781158479,
+              conditional_odds_ratio_ci=(0,
+                                         3.335351451901569))),
+    (Parameters(table=[[10, 5], [10, 0]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.0565217391304348,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         2.075407697450433))),
+    (Parameters(table=[[5, 0], [1, 4]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[0, 5], [1, 4]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.5,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         99.00009507969122))),
+    (Parameters(table=[[5, 1], [0, 4]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[0, 1], [3, 2]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.4999999999999999,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         99.00009507969123))),
+    (Parameters(table=[[200, 7], [8, 300]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=977.7866978606228,
+              conditional_odds_ratio_ci=(0,
+                                         4503.078257659934))),
+    (Parameters(table=[[28, 21], [6, 1957]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=425.2403028434684,
+              conditional_odds_ratio_ci=(0,
+                                         1811.766127544222))),
+    (Parameters(table=[[190, 800], [200, 900]],
+                confidence_level=0.99,
+                alternative='less'),
+     RResults(pvalue=0.7416227010368963,
+              conditional_odds_ratio=1.068697577856801,
+              conditional_odds_ratio_ci=(0,
+                                         1.396522811516685))),
+    (Parameters(table=[[100, 2], [1000, 5]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=0.979790445314723,
+              conditional_odds_ratio=0.25055839934223,
+              conditional_odds_ratio_ci=(0.05119649909830196,
+                                         Inf))),
+    (Parameters(table=[[2, 7], [8, 2]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=0.9990149169715733,
+              conditional_odds_ratio=0.0858623513573622,
+              conditional_odds_ratio_ci=(0.007163749169069961,
+                                         Inf))),
+    (Parameters(table=[[5, 1], [10, 10]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=0.1652173913043478,
+              conditional_odds_ratio=4.725646047336587,
+              conditional_odds_ratio_ci=(0.5493234651081089,
+                                         Inf))),
+    (Parameters(table=[[5, 15], [20, 20]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=0.9849086665340765,
+              conditional_odds_ratio=0.3394396617440851,
+              conditional_odds_ratio_ci=(0.1003538933958604,
+                                         Inf))),
+    (Parameters(table=[[5, 16], [16, 25]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=0.9330176609214881,
+              conditional_odds_ratio=0.4937791394540491,
+              conditional_odds_ratio_ci=(0.146507416280863,
+                                         Inf))),
+    (Parameters(table=[[10, 5], [10, 1]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=0.9782608695652174,
+              conditional_odds_ratio=0.2116112781158479,
+              conditional_odds_ratio_ci=(0.007821681994077808,
+                                         Inf))),
+    (Parameters(table=[[10, 5], [10, 0]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[5, 0], [1, 4]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=0.02380952380952382,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(1.487678929918272,
+                                         Inf))),
+    (Parameters(table=[[0, 5], [1, 4]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[5, 1], [0, 4]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=0.0238095238095238,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(1.487678929918272,
+                                         Inf))),
+    (Parameters(table=[[0, 1], [3, 2]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[200, 7], [8, 300]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=2.005657880388915e-122,
+              conditional_odds_ratio=977.7866978606228,
+              conditional_odds_ratio_ci=(397.784359748113,
+                                         Inf))),
+    (Parameters(table=[[28, 21], [6, 1957]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=5.728437460831983e-44,
+              conditional_odds_ratio=425.2403028434684,
+              conditional_odds_ratio_ci=(174.7148056880929,
+                                         Inf))),
+    (Parameters(table=[[190, 800], [200, 900]],
+                confidence_level=0.95,
+                alternative='greater'),
+     RResults(pvalue=0.2959825901308897,
+              conditional_odds_ratio=1.068697577856801,
+              conditional_odds_ratio_ci=(0.8828406663967776,
+                                         Inf))),
+    (Parameters(table=[[100, 2], [1000, 5]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=0.979790445314723,
+              conditional_odds_ratio=0.25055839934223,
+              conditional_odds_ratio_ci=(0.03045407081240429,
+                                         Inf))),
+    (Parameters(table=[[2, 7], [8, 2]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=0.9990149169715733,
+              conditional_odds_ratio=0.0858623513573622,
+              conditional_odds_ratio_ci=(0.002768053063547901,
+                                         Inf))),
+    (Parameters(table=[[5, 1], [10, 10]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=0.1652173913043478,
+              conditional_odds_ratio=4.725646047336587,
+              conditional_odds_ratio_ci=(0.2998184792279909,
+                                         Inf))),
+    (Parameters(table=[[5, 15], [20, 20]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=0.9849086665340765,
+              conditional_odds_ratio=0.3394396617440851,
+              conditional_odds_ratio_ci=(0.06180414342643172,
+                                         Inf))),
+    (Parameters(table=[[5, 16], [16, 25]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=0.9330176609214881,
+              conditional_odds_ratio=0.4937791394540491,
+              conditional_odds_ratio_ci=(0.09037094010066403,
+                                         Inf))),
+    (Parameters(table=[[10, 5], [10, 1]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=0.9782608695652174,
+              conditional_odds_ratio=0.2116112781158479,
+              conditional_odds_ratio_ci=(0.001521592095430679,
+                                         Inf))),
+    (Parameters(table=[[10, 5], [10, 0]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[5, 0], [1, 4]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=0.02380952380952382,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(0.6661157890359722,
+                                         Inf))),
+    (Parameters(table=[[0, 5], [1, 4]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[5, 1], [0, 4]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=0.0238095238095238,
+              conditional_odds_ratio=Inf,
+              conditional_odds_ratio_ci=(0.6661157890359725,
+                                         Inf))),
+    (Parameters(table=[[0, 1], [3, 2]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=1,
+              conditional_odds_ratio=0,
+              conditional_odds_ratio_ci=(0,
+                                         Inf))),
+    (Parameters(table=[[200, 7], [8, 300]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=2.005657880388915e-122,
+              conditional_odds_ratio=977.7866978606228,
+              conditional_odds_ratio_ci=(297.9619252357688,
+                                         Inf))),
+    (Parameters(table=[[28, 21], [6, 1957]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=5.728437460831983e-44,
+              conditional_odds_ratio=425.2403028434684,
+              conditional_odds_ratio_ci=(130.3213490295859,
+                                         Inf))),
+    (Parameters(table=[[190, 800], [200, 900]],
+                confidence_level=0.99,
+                alternative='greater'),
+     RResults(pvalue=0.2959825901308897,
+              conditional_odds_ratio=1.068697577856801,
+              conditional_odds_ratio_ci=(0.8176272148267533,
+                                         Inf))),
+]
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/AtmWtAg.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/AtmWtAg.dat
new file mode 100644
index 0000000000000000000000000000000000000000..30537565fe8c47f74da0e63a39f4b46600f7768f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/AtmWtAg.dat
@@ -0,0 +1,108 @@
+NIST/ITL StRD 
+Dataset Name:   AtmWtAg   (AtmWtAg.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 108) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Powell, L.J., Murphy, T.J. and Gramlich, J.W. (1982).
+                "The Absolute Isotopic Abundance & Atomic Weight
+                of a Reference Sample of Silver".
+                NBS Journal of Research, 87, pp. 9-19.
+
+
+Data:           1 Factor
+                2 Treatments
+                24 Replicates/Cell
+                48 Observations
+                7 Constant Leading Digits
+                Average Level of Difficulty
+                Observed Data
+
+
+Model:          3 Parameters (mu, tau_1, tau_2)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares             F Statistic
+
+
+Between Instrument  1 3.63834187500000E-09 3.63834187500000E-09 1.59467335677930E+01
+Within Instrument  46 1.04951729166667E-08 2.28155932971014E-10
+
+                   Certified R-Squared 2.57426544538321E-01
+
+                   Certified Residual
+                   Standard Deviation  1.51048314446410E-05
+
+
+
+
+
+
+
+
+
+
+
+Data:  Instrument           AgWt
+           1            107.8681568
+           1            107.8681465
+           1            107.8681572
+           1            107.8681785
+           1            107.8681446
+           1            107.8681903
+           1            107.8681526
+           1            107.8681494
+           1            107.8681616
+           1            107.8681587
+           1            107.8681519
+           1            107.8681486
+           1            107.8681419
+           1            107.8681569
+           1            107.8681508
+           1            107.8681672
+           1            107.8681385
+           1            107.8681518
+           1            107.8681662
+           1            107.8681424
+           1            107.8681360
+           1            107.8681333
+           1            107.8681610
+           1            107.8681477
+           2            107.8681079
+           2            107.8681344
+           2            107.8681513
+           2            107.8681197
+           2            107.8681604
+           2            107.8681385
+           2            107.8681642
+           2            107.8681365
+           2            107.8681151
+           2            107.8681082
+           2            107.8681517
+           2            107.8681448
+           2            107.8681198
+           2            107.8681482
+           2            107.8681334
+           2            107.8681609
+           2            107.8681101
+           2            107.8681512
+           2            107.8681469
+           2            107.8681360
+           2            107.8681254
+           2            107.8681261
+           2            107.8681450
+           2            107.8681368
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SiRstv.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SiRstv.dat
new file mode 100644
index 0000000000000000000000000000000000000000..18ea8971fd7a4d67800dafe98ac5ea5acef53025
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SiRstv.dat
@@ -0,0 +1,85 @@
+NIST/ITL StRD 
+Dataset Name:   SiRstv     (SiRstv.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 85) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Ehrstein, James and Croarkin, M. Carroll.
+                Unpublished NIST dataset.
+
+
+Data:           1 Factor
+                5 Treatments
+                5  Replicates/Cell
+                25 Observations
+                3 Constant Leading Digits
+                Lower Level of Difficulty
+                Observed Data
+
+
+Model:          6 Parameters (mu,tau_1, ... , tau_5)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares             F Statistic
+
+Between Instrument  4 5.11462616000000E-02 1.27865654000000E-02 1.18046237440255E+00
+Within Instrument  20 2.16636560000000E-01 1.08318280000000E-02
+
+                   Certified R-Squared 1.90999039051129E-01
+
+                   Certified Residual
+                   Standard Deviation  1.04076068334656E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Instrument   Resistance
+           1         196.3052
+           1         196.1240
+           1         196.1890
+           1         196.2569
+           1         196.3403
+           2         196.3042
+           2         196.3825
+           2         196.1669
+           2         196.3257
+           2         196.0422
+           3         196.1303
+           3         196.2005
+           3         196.2889
+           3         196.0343
+           3         196.1811
+           4         196.2795
+           4         196.1748
+           4         196.1494
+           4         196.1485
+           4         195.9885
+           5         196.2119
+           5         196.1051
+           5         196.1850
+           5         196.0052
+           5         196.2090
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs01.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs01.dat
new file mode 100644
index 0000000000000000000000000000000000000000..945b24bf35422152a5faba73ed054ab78fda1bdf
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs01.dat
@@ -0,0 +1,249 @@
+NIST/ITL StRD 
+Dataset Name:   SmLs01   (SmLs01.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 249) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Simon, Stephen D. and Lesage, James P. (1989).
+                "Assessing the Accuracy of ANOVA Calculations in
+                Statistical Software".
+                Computational Statistics & Data Analysis, 8, pp. 325-332.
+
+
+Data:           1 Factor
+                9 Treatments
+                21 Replicates/Cell
+                189 Observations
+                1 Constant Leading Digit
+                Lower Level of Difficulty
+                Generated Data
+
+
+Model:          10 Parameters (mu,tau_1, ... , tau_9)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares            F Statistic
+
+Between Treatment   8 1.68000000000000E+00 2.10000000000000E-01 2.10000000000000E+01
+Within Treatment  180 1.80000000000000E+00 1.00000000000000E-02
+
+                  Certified R-Squared 4.82758620689655E-01
+
+                  Certified Residual
+                  Standard Deviation  1.00000000000000E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Treatment   Response
+           1         1.4
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           2         1.3
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           3         1.5
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           4         1.3
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           5         1.5
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           6         1.3
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           7         1.5
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           8         1.3
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           9         1.5
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs02.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs02.dat
new file mode 100644
index 0000000000000000000000000000000000000000..ee76633a660a48225064bbb86a25f6a2f36c6d9a
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs02.dat
@@ -0,0 +1,1869 @@
+NIST/ITL StRD 
+Dataset Name:   SmLs02   (SmLs02.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 1869) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Simon, Stephen D. and Lesage, James P. (1989).
+                "Assessing the Accuracy of ANOVA Calculations in
+                Statistical Software".
+                Computational Statistics & Data Analysis, 8, pp. 325-332.
+
+
+Data:           1 Factor
+                9 Treatments
+                201 Replicates/Cell
+                1809 Observations
+                1 Constant Leading Digit
+                Lower Level of Difficulty
+                Generated Data
+
+
+Model:          10 Parameters (mu,tau_1, ... , tau_9)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares             F Statistic
+
+Between Treatment    8 1.60800000000000E+01 2.01000000000000E+00 2.01000000000000E+02
+Within Treatment  1800 1.80000000000000E+01 1.00000000000000E-02
+
+                  Certified R-Squared 4.71830985915493E-01
+
+                  Certified Residual
+                  Standard Deviation  1.00000000000000E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Treatment   Response
+           1         1.4
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           2         1.3
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           3         1.5
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           4         1.3
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           5         1.5
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           6         1.3
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           7         1.5
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           8         1.3
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           9         1.5
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs03.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs03.dat
new file mode 100644
index 0000000000000000000000000000000000000000..55dfa2313ffb152709c58b47c0058567b710d903
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs03.dat
@@ -0,0 +1,18069 @@
+NIST/ITL StRD 
+Dataset Name:   SmLs03   (SmLs03.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 18069) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Simon, Stephen D. and Lesage, James P. (1989).
+                "Assessing the Accuracy of ANOVA Calculations in
+                Statistical Software".
+                Computational Statistics & Data Analysis, 8, pp. 325-332.
+
+
+Data:           1 Factor
+                9 Treatments
+                2001 Replicates/Cell
+                18009 Observations
+                1 Constant Leading Digit
+                Lower Level of Difficulty
+                Generated Data
+
+
+Model:          10 Parameters (mu,tau_1, ... , tau_9)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares             F Statistic
+
+Between Treatment     8 1.60080000000000E+02 2.00100000000000E+01 2.00100000000000E+03
+Within Treatment  18000 1.80000000000000E+02 1.00000000000000E-02
+
+                  Certified R-Squared 4.70712773465067E-01
+
+                  Certified Residual
+                  Standard Deviation  1.00000000000000E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Treatment   Response
+           1         1.4
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           1         1.3
+           1         1.5
+           2         1.3
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           2         1.2
+           2         1.4
+           3         1.5
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           3         1.4
+           3         1.6
+           4         1.3
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           4         1.2
+           4         1.4
+           5         1.5
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           5         1.4
+           5         1.6
+           6         1.3
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           6         1.2
+           6         1.4
+           7         1.5
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           7         1.4
+           7         1.6
+           8         1.3
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           8         1.2
+           8         1.4
+           9         1.5
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
+           9         1.4
+           9         1.6
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs04.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs04.dat
new file mode 100644
index 0000000000000000000000000000000000000000..6a2a9fc935a56989b166de9b23f3df3bc4f64879
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs04.dat
@@ -0,0 +1,249 @@
+NIST/ITL StRD 
+Dataset Name:   SmLs04   (SmLs04.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 249) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Simon, Stephen D. and Lesage, James P. (1989).
+                "Assessing the Accuracy of ANOVA Calculations in
+                Statistical Software".
+                Computational Statistics & Data Analysis, 8, pp. 325-332.
+
+
+Data:           1 Factor
+                9 Treatments
+                21 Replicates/Cell
+                189 Observations
+                7 Constant Leading Digits
+                Average Level of Difficulty
+                Generated Data
+
+
+Model:          10 Parameters (mu,tau_1, ... , tau_9)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares             F Statistic
+
+Between Treatment   8 1.68000000000000E+00 2.10000000000000E-01 2.10000000000000E+01
+Within Treatment  180 1.80000000000000E+00 1.00000000000000E-02
+
+                  Certified R-Squared 4.82758620689655E-01
+
+                  Certified Residual
+                  Standard Deviation  1.00000000000000E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Treatment   Response
+           1       1000000.4
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           2       1000000.3
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           3       1000000.5
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           4       1000000.3
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           5       1000000.5
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           6       1000000.3
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           7       1000000.5
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           8       1000000.3
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           9       1000000.5
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs05.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs05.dat
new file mode 100644
index 0000000000000000000000000000000000000000..fe11c40b5f51aefc81d4d1501a74e627f2b2d992
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs05.dat
@@ -0,0 +1,1869 @@
+NIST/ITL StRD 
+Dataset Name:   SmLs05   (SmLs05.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 1869) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Simon, Stephen D. and Lesage, James P. (1989).
+                "Assessing the Accuracy of ANOVA Calculations in
+                Statistical Software".
+                Computational Statistics & Data Analysis, 8, pp. 325-332.
+
+
+Data:           1 Factor
+                9 Treatments
+                201 Replicates/Cell
+                1809 Observations
+                7 Constant Leading Digits
+                Average Level of Difficulty
+                Generated Data
+
+
+Model:          10 Parameters (mu,tau_1, ... , tau_9)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares            F Statistic
+
+Between Treatment    8 1.60800000000000E+01 2.01000000000000E+00 2.01000000000000E+02
+Within Treatment  1800 1.80000000000000E+01 1.00000000000000E-02
+
+                  Certified R-Squared 4.71830985915493E-01
+
+                  Certified Residual
+                  Standard Deviation  1.00000000000000E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Treatment   Response
+           1       1000000.4
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           2       1000000.3
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           3       1000000.5
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           4       1000000.3
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           5       1000000.5
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           6       1000000.3
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           7       1000000.5
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           8       1000000.3
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           9       1000000.5
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs06.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs06.dat
new file mode 100644
index 0000000000000000000000000000000000000000..602e4fbdaa26bbb8d95ce78d1f48dbbfa883e7e9
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs06.dat
@@ -0,0 +1,18069 @@
+NIST/ITL StRD 
+Dataset Name:   SmLs06   (SmLs06.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 18069) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Simon, Stephen D. and Lesage, James P. (1989).
+                "Assessing the Accuracy of ANOVA Calculations in
+                Statistical Software".
+                Computational Statistics & Data Analysis, 8, pp. 325-332.
+
+
+Data:           1 Factor
+                9 Treatments
+                2001 Replicates/Cell
+                18009 Observations
+                7 Constant Leading Digits
+                Average Level of Difficulty
+                Generated Data
+
+
+Model:          10 Parameters (mu,tau_1, ... , tau_9)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares             F Statistic
+
+Between Treatment     8 1.60080000000000E+02 2.00100000000000E+01 2.00100000000000E+03
+Within Treatment  18000 1.80000000000000E+02 1.00000000000000E-02
+
+                  Certified R-Squared 4.70712773465067E-01
+
+                  Certified Residual
+                  Standard Deviation  1.00000000000000E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Treatment   Response
+           1       1000000.4
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           1       1000000.3
+           1       1000000.5
+           2       1000000.3
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           2       1000000.2
+           2       1000000.4
+           3       1000000.5
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           3       1000000.4
+           3       1000000.6
+           4       1000000.3
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           4       1000000.2
+           4       1000000.4
+           5       1000000.5
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           5       1000000.4
+           5       1000000.6
+           6       1000000.3
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           6       1000000.2
+           6       1000000.4
+           7       1000000.5
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           7       1000000.4
+           7       1000000.6
+           8       1000000.3
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           8       1000000.2
+           8       1000000.4
+           9       1000000.5
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
+           9       1000000.4
+           9       1000000.6
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs07.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs07.dat
new file mode 100644
index 0000000000000000000000000000000000000000..deeac955e65ffaf55838568baa54951efaf2662b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs07.dat
@@ -0,0 +1,249 @@
+NIST/ITL StRD 
+Dataset Name:   SmLs07   (SmLs07.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 249) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Simon, Stephen D. and Lesage, James P. (1989).
+                "Assessing the Accuracy of ANOVA Calculations in
+                Statistical Software".
+                Computational Statistics & Data Analysis, 8, pp. 325-332.
+
+
+Data:           1 Factor
+                9 Treatments
+                21 Replicates/Cell
+                189 Observations
+                13 Constant Leading Digits
+                Higher Level of Difficulty
+                Generated Data
+
+
+Model:          10 Parameters (mu,tau_1, ... , tau_9)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares            F Statistic
+
+Between Treatment   8 1.68000000000000E+00 2.10000000000000E-01 2.10000000000000E+01
+Within Treatment  180 1.80000000000000E+00 1.00000000000000E-02
+
+                  Certified R-Squared 4.82758620689655E-01
+
+                  Certified Residual
+                  Standard Deviation  1.00000000000000E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Treatment   Response
+           1    1000000000000.4
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           2    1000000000000.3
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           3    1000000000000.5
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           4    1000000000000.3
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           5    1000000000000.5
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           6    1000000000000.3
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           7    1000000000000.5
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           8    1000000000000.3
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           9    1000000000000.5
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs08.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs08.dat
new file mode 100644
index 0000000000000000000000000000000000000000..c5ee643fb8c6ef849ab8e34352bc60f15c715a45
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs08.dat
@@ -0,0 +1,1869 @@
+NIST/ITL StRD 
+Dataset Name:   SmLs08   (SmLs08.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 1869) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Simon, Stephen D. and Lesage, James P. (1989).
+                "Assessing the Accuracy of ANOVA Calculations in
+                Statistical Software".
+                Computational Statistics & Data Analysis, 8, pp. 325-332.
+
+
+Data:           1 Factor
+                9 Treatments
+                201 Replicates/Cell
+                1809 Observations
+                13 Constant Leading Digits
+                Higher Level of Difficulty
+                Generated Data
+
+
+Model:          10 Parameters (mu,tau_1, ... , tau_9)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares              F Statistic
+
+Between Treatment    8 1.60800000000000E+01 2.01000000000000E+00 2.01000000000000E+02
+Within Treatment  1800 1.80000000000000E+01 1.00000000000000E-02
+
+                  Certified R-Squared 4.71830985915493E-01
+
+                  Certified Residual
+                  Standard Deviation  1.00000000000000E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Treatment   Response
+           1    1000000000000.4
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           2    1000000000000.3
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           3    1000000000000.5
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           4    1000000000000.3
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           5    1000000000000.5
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           6    1000000000000.3
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           7    1000000000000.5
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           8    1000000000000.3
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           9    1000000000000.5
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs09.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs09.dat
new file mode 100644
index 0000000000000000000000000000000000000000..887905e355a2a13801f1b004187631f2301f7eef
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_anova/SmLs09.dat
@@ -0,0 +1,18069 @@
+NIST/ITL StRD 
+Dataset Name:   SmLs09   (SmLs09.dat)
+
+
+File Format:    ASCII
+                Certified Values   (lines 41 to 47)
+                Data               (lines 61 to 18069) 
+
+
+Procedure:      Analysis of Variance
+
+
+Reference:      Simon, Stephen D. and Lesage, James P. (1989).
+                "Assessing the Accuracy of ANOVA Calculations in
+                Statistical Software".
+                Computational Statistics & Data Analysis, 8, pp. 325-332.
+
+
+Data:           1 Factor
+                9 Treatments
+                2001 Replicates/Cell
+                18009 Observations
+                13 Constant Leading Digits
+                Higher Level of Difficulty
+                Generated Data
+
+
+Model:          10 Parameters (mu,tau_1, ... , tau_9)
+                y_{ij} = mu + tau_i + epsilon_{ij}
+
+
+
+
+
+
+Certified Values:
+
+Source of                  Sums of               Mean               
+Variation          df      Squares              Squares              F Statistic
+
+Between Treatment     8 1.60080000000000E+02 2.00100000000000E+01 2.00100000000000E+03
+Within Treatment  18000 1.80000000000000E+02 1.00000000000000E-02
+
+                  Certified R-Squared 4.70712773465067E-01
+
+                  Certified Residual
+                  Standard Deviation  1.00000000000000E-01
+
+
+
+
+
+
+
+
+
+
+
+
+Data:  Treatment   Response
+           1    1000000000000.4
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           1    1000000000000.3
+           1    1000000000000.5
+           2    1000000000000.3
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           2    1000000000000.2
+           2    1000000000000.4
+           3    1000000000000.5
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           3    1000000000000.4
+           3    1000000000000.6
+           4    1000000000000.3
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           4    1000000000000.2
+           4    1000000000000.4
+           5    1000000000000.5
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           5    1000000000000.4
+           5    1000000000000.6
+           6    1000000000000.3
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           6    1000000000000.2
+           6    1000000000000.4
+           7    1000000000000.5
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           7    1000000000000.4
+           7    1000000000000.6
+           8    1000000000000.3
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           8    1000000000000.2
+           8    1000000000000.4
+           9    1000000000000.5
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
+           9    1000000000000.4
+           9    1000000000000.6
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_linregress/Norris.dat b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_linregress/Norris.dat
new file mode 100644
index 0000000000000000000000000000000000000000..4bf8ed911cae75824b27e5f5d5e444e17fa8eae8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/nist_linregress/Norris.dat
@@ -0,0 +1,97 @@
+NIST/ITL StRD
+Dataset Name:  Norris (Norris.dat)
+
+File Format:   ASCII
+               Certified Values  (lines 31 to 46)
+               Data              (lines 61 to 96)
+
+Procedure:     Linear Least Squares Regression
+
+Reference:     Norris, J., NIST.  
+               Calibration of Ozone Monitors.
+
+Data:          1 Response Variable (y)
+               1 Predictor Variable (x)
+               36 Observations
+               Lower Level of Difficulty
+               Observed Data
+
+Model:         Linear Class
+               2 Parameters (B0,B1)
+
+               y = B0 + B1*x + e
+
+
+
+               Certified Regression Statistics
+
+                                          Standard Deviation
+     Parameter          Estimate             of Estimate
+
+        B0        -0.262323073774029     0.232818234301152
+        B1         1.00211681802045      0.429796848199937E-03
+
+     Residual
+     Standard Deviation   0.884796396144373
+
+     R-Squared            0.999993745883712
+
+
+               Certified Analysis of Variance Table
+
+Source of Degrees of    Sums of             Mean  
+Variation  Freedom      Squares            Squares           F Statistic
+              
+Regression    1     4255954.13232369   4255954.13232369   5436385.54079785
+Residual     34     26.6173985294224   0.782864662630069
+
+                 
+                                          
+                                          
+                                                           
+
+                            
+                                   
+                                                       
+
+
+
+
+Data:       y          x
+           0.1        0.2
+         338.8      337.4
+         118.1      118.2
+         888.0      884.6
+           9.2       10.1
+         228.1      226.5
+         668.5      666.3
+         998.5      996.3
+         449.1      448.6
+         778.9      777.0
+         559.2      558.2
+           0.3        0.4
+           0.1        0.6
+         778.1      775.5
+         668.8      666.9
+         339.3      338.0
+         448.9      447.5
+          10.8       11.6
+         557.7      556.0
+         228.3      228.1
+         998.0      995.8
+         888.8      887.6
+         119.6      120.2
+           0.3        0.3
+           0.6        0.3
+         557.6      556.8
+         339.3      339.1
+         888.0      887.2
+         998.5      999.0
+         778.9      779.0
+          10.2       11.1
+         117.6      118.3
+         228.9      229.2
+         668.4      669.1
+         449.2      448.9
+           0.2        0.5
+                                   
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/studentized_range_mpmath_ref.json b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/studentized_range_mpmath_ref.json
new file mode 100644
index 0000000000000000000000000000000000000000..bb971286cf85b28738a80bacececfb90c2566782
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/data/studentized_range_mpmath_ref.json
@@ -0,0 +1,1499 @@
+{
+  "COMMENT": "!!!!!! THIS FILE WAS AUTOGENERATED BY RUNNING `python studentized_range_mpmath_ref.py` !!!!!!",
+  "moment_data": [
+    {
+      "src_case": {
+        "m": 0,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-09,
+        "expected_rtol": 1e-09
+      },
+      "mp_result": 1.0
+    },
+    {
+      "src_case": {
+        "m": 1,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-09,
+        "expected_rtol": 1e-09
+      },
+      "mp_result": 1.8342745127927962
+    },
+    {
+      "src_case": {
+        "m": 2,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-09,
+        "expected_rtol": 1e-09
+      },
+      "mp_result": 4.567483357831711
+    },
+    {
+      "src_case": {
+        "m": 3,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-09,
+        "expected_rtol": 1e-09
+      },
+      "mp_result": 14.412156886227011
+    },
+    {
+      "src_case": {
+        "m": 4,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-09,
+        "expected_rtol": 1e-09
+      },
+      "mp_result": 56.012250366720444
+    }
+  ],
+  "cdf_data": [
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0027502772229359594
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 2.8544145010066327e-12
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0027520560662338336
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 9.39089126131273e-13
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.002752437649536182
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.0862189999210748e-12
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.002752755744313648
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0027527430186246545
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.002752666667812431
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 2.505275157135514e-24
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 3.8546698113384126e-25
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.7362668562706085e-11
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 5.571947730052616e-26
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 2.032619249089036e-27
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 9.539763646681808e-22
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.618313512511099e-12
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 4.919231733354114e-28
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 9.159348906295542e-13
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.22331624289542043
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.2395624637676257
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.23510918942128056
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.23786536230099864
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.000651656693149116
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.2401356460422021
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.003971273224673166
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0008732969319364606
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.24023154593376422
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.001300816146573152
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.5682573722040226e-07
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0005841098057517027
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 9.2267674885784e-05
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0005731712496327297
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 2.746798012658064e-06
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 5.807700350854172e-07
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 9.147637957472628e-08
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 8.306675539750552e-08
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.8711786295203324
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9818862781476212
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9566506502400175
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9849546621386962
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9731488893573804
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.8450530667988544
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.6164875232404174
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9845292772767739
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.8079691517949077
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.7573606942645745
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.8587525248147736
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.8611036193280976
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.46523135355387657
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.6318042819232383
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.5574947140294286
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.5970517763141937
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.6493671527818267
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.6466699776044968
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9881335633712994
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999999861266821
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.999908236635449
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999978467928313
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999999996690216
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999999993640496
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9570401457077894
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999997977351971
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9991738325963548
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999730883609333
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999999905199205
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999999950566264
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9312318042339768
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999991743904675
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9977643922032399
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999054426012515
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999999602948055
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.9999999792458618
+    }
+  ],
+  "pdf_data": [
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.05487847613526332
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 2.564099684606509e-10
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.05494947290360002
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 8.442593793786411e-11
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.054964710604860405
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 9.764441961563576e-11
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.05497690690332341
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.05497385731702228
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 4.758021225803992e-22
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 3,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.054977415200879516
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.8004731453548083e-19
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.5564176176604816e-09
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 9.342768070688728e-24
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.454372265306114e-10
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 3.9138464398429654e-25
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 5.266341131767418e-23
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 10,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 8.234556126446594e-11
+    },
+    {
+      "src_case": {
+        "q": 0.1,
+        "k": 20,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 9.32929780487562e-26
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.36083736990527154
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.4137959132282269
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.4080239698771056
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.398772020275752
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.4160873922094346
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 3,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.4157583991350054
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.005210720148451848
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.02575314059867804
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.009782573637596617
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.006818708302379005
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0047089182958790715
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 10,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.004627085294166373
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0010886280311369462
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 2.630674470916427e-06
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 4.121713278199428e-05
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 9.319506007252685e-06
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.5585754418789747e-06
+    },
+    {
+      "src_case": {
+        "q": 1,
+        "k": 20,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.4190335899441991e-06
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.07185383302009114
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.050268901219386576
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.03321056847176124
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.04044172384981084
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.030571365659999617
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 3,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.030120779149073032
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.17501664247670937
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.22374394725370736
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.23246597521020534
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.23239043677504484
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.23057775622748988
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 10,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.23012666145240815
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.2073676639537027
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.3245990542431859
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0033733228559870584
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 7.728665739003835e-05
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.38244500549096866
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.45434978340834464
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.43334135870667473
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 2.159522630228393e-09
+    },
+    {
+      "src_case": {
+        "q": 4,
+        "k": 20,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.45807877248528855
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 3.5303467191175695e-08
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 3.121281850105421e-06
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 3,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.1901591191700855e-09
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0006784051704217357
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.011845582636101885
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 3.844183552674918e-05
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 3.215093171597309e-08
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 5.125792577534542e-07
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 10,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.7759015355532446e-08
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 10,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.0017957646258393628
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 3,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.018534407764819284
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 20,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 0.00013316083413164858
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 50,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 2.082489228991225e-06
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 100,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 1.3444226792257012e-07
+    },
+    {
+      "src_case": {
+        "q": 10,
+        "k": 20,
+        "v": 120,
+        "expected_atol": 1e-11,
+        "expected_rtol": 1e-11
+      },
+      "mp_result": 7.446912854228521e-08
+    }
+  ]
+}
\ No newline at end of file
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_axis_nan_policy.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_axis_nan_policy.py
new file mode 100644
index 0000000000000000000000000000000000000000..162e62b813927f03a86e685af7c4a0829575f62d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_axis_nan_policy.py
@@ -0,0 +1,1350 @@
+# Many scipy.stats functions support `axis` and `nan_policy` parameters.
+# When the two are combined, it can be tricky to get all the behavior just
+# right. This file contains a suite of common tests for scipy.stats functions
+# that support `axis` and `nan_policy` and additional tests for some associated
+# functions in stats._util.
+
+from itertools import product, combinations_with_replacement, permutations
+import os
+import re
+import pickle
+import pytest
+import warnings
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+from scipy import stats
+from scipy.stats import norm  # type: ignore[attr-defined]
+from scipy.stats._axis_nan_policy import (_masked_arrays_2_sentinel_arrays,
+                                          SmallSampleWarning,
+                                          too_small_nd_omit, too_small_nd_not_omit,
+                                          too_small_1d_omit, too_small_1d_not_omit)
+from scipy._lib._util import AxisError
+from scipy.conftest import skip_xp_invalid_arg
+
+
+SCIPY_XSLOW = int(os.environ.get('SCIPY_XSLOW', '0'))
+
+
+def unpack_ttest_result(res):
+    low, high = res.confidence_interval()
+    return (res.statistic, res.pvalue, res.df, res._standard_error,
+            res._estimate, low, high)
+
+
+def _get_ttest_ci(ttest):
+    # get a function that returns the CI bounds of provided `ttest`
+    def ttest_ci(*args, **kwargs):
+        res = ttest(*args, **kwargs)
+        return res.confidence_interval()
+    return ttest_ci
+
+
+def xp_mean_1samp(*args, **kwargs):
+    kwargs.pop('_no_deco', None)
+    return stats._stats_py._xp_mean(*args, **kwargs)
+
+
+def xp_mean_2samp(*args, **kwargs):
+    kwargs.pop('_no_deco', None)
+    weights = args[1]
+    return stats._stats_py._xp_mean(args[0], *args[2:], weights=weights, **kwargs)
+
+
+def xp_var(*args, **kwargs):
+    kwargs.pop('_no_deco', None)
+    return stats._stats_py._xp_var(*args, **kwargs)
+
+
+def combine_pvalues_weighted(*args, **kwargs):
+    return stats.combine_pvalues(args[0], *args[2:], weights=args[1],
+                                 method='stouffer', **kwargs)
+
+
+axis_nan_policy_cases = [
+    # function, args, kwds, number of samples, number of outputs,
+    # ... paired, unpacker function
+    # args, kwds typically aren't needed; just showing that they work
+    (stats.kruskal, tuple(), dict(), 3, 2, False, None),  # 4 samples is slow
+    (stats.ranksums, ('less',), dict(), 2, 2, False, None),
+    (stats.mannwhitneyu, tuple(), {'method': 'asymptotic'}, 2, 2, False, None),
+    (stats.wilcoxon, ('pratt',), {'mode': 'auto'}, 2, 2, True,
+     lambda res: (res.statistic, res.pvalue)),
+    (stats.wilcoxon, tuple(), dict(), 1, 2, True,
+     lambda res: (res.statistic, res.pvalue)),
+    (stats.wilcoxon, tuple(), {'method': 'asymptotic'}, 1, 3, True,
+     lambda res: (res.statistic, res.pvalue, res.zstatistic)),
+    (stats.gmean, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.hmean, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.pmean, (1.42,), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.sem, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.iqr, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.kurtosis, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.skew, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.kstat, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.kstatvar, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.moment, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.moment, tuple(), dict(order=[1, 2]), 1, 2, False, None),
+    (stats.jarque_bera, tuple(), dict(), 1, 2, False, None),
+    (stats.ttest_1samp, (np.array([0]),), dict(), 1, 7, False,
+     unpack_ttest_result),
+    (stats.ttest_rel, tuple(), dict(), 2, 7, True, unpack_ttest_result),
+    (stats.ttest_ind, tuple(), dict(), 2, 7, False, unpack_ttest_result),
+    (_get_ttest_ci(stats.ttest_1samp), (0,), dict(), 1, 2, False, None),
+    (_get_ttest_ci(stats.ttest_rel), tuple(), dict(), 2, 2, True, None),
+    (_get_ttest_ci(stats.ttest_ind), tuple(), dict(), 2, 2, False, None),
+    (stats.mode, tuple(), dict(), 1, 2, True, lambda x: (x.mode, x.count)),
+    (stats.differential_entropy, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.variation, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.friedmanchisquare, tuple(), dict(), 3, 2, True, None),
+    (stats.brunnermunzel, tuple(), dict(distribution='normal'), 2, 2, False, None),
+    (stats.mood, tuple(), {}, 2, 2, False, None),
+    (stats.shapiro, tuple(), {}, 1, 2, False, None),
+    (stats.ks_1samp, (norm().cdf,), dict(), 1, 4, False,
+     lambda res: (*res, res.statistic_location, res.statistic_sign)),
+    (stats.ks_2samp, tuple(), dict(), 2, 4, False,
+     lambda res: (*res, res.statistic_location, res.statistic_sign)),
+    (stats.kstest, (norm().cdf,), dict(), 1, 4, False,
+     lambda res: (*res, res.statistic_location, res.statistic_sign)),
+    (stats.kstest, tuple(), dict(), 2, 4, False,
+     lambda res: (*res, res.statistic_location, res.statistic_sign)),
+    (stats.levene, tuple(), {}, 2, 2, False, None),
+    (stats.fligner, tuple(), {'center': 'trimmed', 'proportiontocut': 0.01},
+     2, 2, False, None),
+    (stats.ansari, tuple(), {}, 2, 2, False, None),
+    (stats.entropy, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.entropy, tuple(), dict(), 2, 1, True, lambda x: (x,)),
+    (stats.skewtest, tuple(), dict(), 1, 2, False, None),
+    (stats.kurtosistest, tuple(), dict(), 1, 2, False, None),
+    (stats.normaltest, tuple(), dict(), 1, 2, False, None),
+    (stats.cramervonmises, ("norm",), dict(), 1, 2, False,
+     lambda res: (res.statistic, res.pvalue)),
+    (stats.cramervonmises_2samp, tuple(), dict(), 2, 2, False,
+     lambda res: (res.statistic, res.pvalue)),
+    (stats.epps_singleton_2samp, tuple(), dict(), 2, 2, False, None),
+    (stats.bartlett, tuple(), {}, 2, 2, False, None),
+    (stats.tmean, tuple(), {}, 1, 1, False, lambda x: (x,)),
+    (stats.tvar, tuple(), {}, 1, 1, False, lambda x: (x,)),
+    (stats.tmin, tuple(), {}, 1, 1, False, lambda x: (x,)),
+    (stats.tmax, tuple(), {}, 1, 1, False, lambda x: (x,)),
+    (stats.tstd, tuple(), {}, 1, 1, False, lambda x: (x,)),
+    (stats.tsem, tuple(), {}, 1, 1, False, lambda x: (x,)),
+    (stats.circmean, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.circvar, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.circstd, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.f_oneway, tuple(), {}, 2, 2, False, None),
+    (stats.alexandergovern, tuple(), {}, 2, 2, False,
+     lambda res: (res.statistic, res.pvalue)),
+    (stats.combine_pvalues, tuple(), {}, 1, 2, False, None),
+    (stats.lmoment, tuple(), dict(), 1, 4, False, lambda x: tuple(x)),
+    (combine_pvalues_weighted, tuple(), {}, 2, 2, True, None),
+    (xp_mean_1samp, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (xp_mean_2samp, tuple(), dict(), 2, 1, True, lambda x: (x,)),
+    (xp_var, tuple(), dict(), 1, 1, False, lambda x: (x,)),
+    (stats.chatterjeexi, tuple(), dict(), 2, 2, True,
+     lambda res: (res.statistic, res.pvalue)),
+]
+
+# If the message is one of those expected, put nans in
+# appropriate places of `statistics` and `pvalues`
+too_small_messages = {"Degrees of freedom <= 0 for slice",
+                      "x and y should have at least 5 elements",
+                      "Data must be at least length 3",
+                      "The sample must contain at least two",
+                      "x and y must contain at least two",
+                      "division by zero",
+                      "Mean of empty slice",
+                      "Data passed to ks_2samp must not be empty",
+                      "Not enough test observations",
+                      "Not enough other observations",
+                      "Not enough observations.",
+                      "At least one observation is required",
+                      "zero-size array to reduction operation maximum",
+                      "`x` and `y` must be of nonzero size.",
+                      "The exact distribution of the Wilcoxon test",
+                      "Data input must not be empty",
+                      "Window length (0) must be positive and less",
+                      "Window length (1) must be positive and less",
+                      "Window length (2) must be positive and less",
+                      "`skewtest` requires at least",
+                      "`kurtosistest` requires at least",
+                      "attempt to get argmax of an empty sequence",
+                      "No array values within given limits",
+                      "Input sample size must be greater than one.",
+                      "At least one slice along `axis` has zero length",
+                      "One or more sample arguments is too small",
+                      "invalid value encountered",
+                      "divide by zero encountered",
+}
+
+# If the message is one of these, results of the function may be inaccurate,
+# but NaNs are not to be placed
+inaccuracy_messages = {"Precision loss occurred in moment calculation",
+                       "Sample size too small for normal approximation."}
+
+# For some functions, nan_policy='propagate' should not just return NaNs
+override_propagate_funcs = {stats.mode}
+
+# For some functions, empty arrays produce non-NaN results
+empty_special_case_funcs = {stats.entropy}
+
+# Some functions don't follow the usual "too small" warning rules
+too_small_special_case_funcs = {stats.entropy}
+
+def _mixed_data_generator(n_samples, n_repetitions, axis, rng,
+                          paired=False):
+    # generate random samples to check the response of hypothesis tests to
+    # samples with different (but broadcastable) shapes and various
+    # nan patterns (e.g. all nans, some nans, no nans) along axis-slices
+
+    data = []
+    for i in range(n_samples):
+        n_patterns = 6  # number of distinct nan patterns
+        n_obs = 20 if paired else 20 + i  # observations per axis-slice
+        x = np.ones((n_repetitions, n_patterns, n_obs)) * np.nan
+
+        for j in range(n_repetitions):
+            samples = x[j, :, :]
+
+            # case 0: axis-slice with all nans (0 reals)
+            # cases 1-3: axis-slice with 1-3 reals (the rest nans)
+            # case 4: axis-slice with mostly (all but two) reals
+            # case 5: axis slice with all reals
+            for k, n_reals in enumerate([0, 1, 2, 3, n_obs-2, n_obs]):
+                # for cases 1-3, need paired nansw  to be in the same place
+                indices = rng.permutation(n_obs)[:n_reals]
+                samples[k, indices] = rng.random(size=n_reals)
+
+            # permute the axis-slices just to show that order doesn't matter
+            samples[:] = rng.permutation(samples, axis=0)
+
+        # For multi-sample tests, we want to test broadcasting and check
+        # that nan policy works correctly for each nan pattern for each input.
+        # This takes care of both simultaneously.
+        new_shape = [n_repetitions] + [1]*n_samples + [n_obs]
+        new_shape[1 + i] = 6
+        x = x.reshape(new_shape)
+
+        x = np.moveaxis(x, -1, axis)
+        data.append(x)
+    return data
+
+
+def _homogeneous_data_generator(n_samples, n_repetitions, axis, rng,
+                                paired=False, all_nans=True):
+    # generate random samples to check the response of hypothesis tests to
+    # samples with different (but broadcastable) shapes and homogeneous
+    # data (all nans or all finite)
+    data = []
+    for i in range(n_samples):
+        n_obs = 20 if paired else 20 + i  # observations per axis-slice
+        shape = [n_repetitions] + [1]*n_samples + [n_obs]
+        shape[1 + i] = 2
+        x = np.ones(shape) * np.nan if all_nans else rng.random(shape)
+        x = np.moveaxis(x, -1, axis)
+        data.append(x)
+    return data
+
+
+def nan_policy_1d(hypotest, data1d, unpacker, *args, n_outputs=2,
+                  nan_policy='raise', paired=False, _no_deco=True, **kwds):
+    # Reference implementation for how `nan_policy` should work for 1d samples
+
+    if nan_policy == 'raise':
+        for sample in data1d:
+            if np.any(np.isnan(sample)):
+                raise ValueError("The input contains nan values")
+
+    elif (nan_policy == 'propagate'
+          and hypotest not in override_propagate_funcs):
+        # For all hypothesis tests tested, returning nans is the right thing.
+        # But many hypothesis tests don't propagate correctly (e.g. they treat
+        # np.nan the same as np.inf, which doesn't make sense when ranks are
+        # involved) so override that behavior here.
+        for sample in data1d:
+            if np.any(np.isnan(sample)):
+                return np.full(n_outputs, np.nan)
+
+    elif nan_policy == 'omit':
+        # manually omit nans (or pairs in which at least one element is nan)
+        if not paired:
+            data1d = [sample[~np.isnan(sample)] for sample in data1d]
+        else:
+            nan_mask = np.isnan(data1d[0])
+            for sample in data1d[1:]:
+                nan_mask = np.logical_or(nan_mask, np.isnan(sample))
+            data1d = [sample[~nan_mask] for sample in data1d]
+
+    return unpacker(hypotest(*data1d, *args, _no_deco=_no_deco, **kwds))
+
+
+# These three warnings are intentional
+# For `wilcoxon` when the sample size < 50
+@pytest.mark.filterwarnings('ignore:Sample size too small for normal:UserWarning')
+# `kurtosistest` and `normaltest` when sample size < 20
+@pytest.mark.filterwarnings('ignore:`kurtosistest` p-value may be:UserWarning')
+# `foneway`
+@pytest.mark.filterwarnings('ignore:all input arrays have length 1.:RuntimeWarning')
+
+# The rest of these may or may not be desirable. They need further investigation
+# to determine whether the function's decorator should define `too_small.
+# `bartlett`, `tvar`, `tstd`, `tsem`
+@pytest.mark.filterwarnings('ignore:Degrees of freedom <= 0 for slice:RuntimeWarning')
+# kstat, kstatvar, ttest_1samp, ttest_rel, ttest_ind, ttest_ci, brunnermunzel
+# mood, levene, fligner, bartlett
+@pytest.mark.filterwarnings('ignore:Invalid value encountered in:RuntimeWarning')
+# kstatvar, ttest_1samp, ttest_rel, ttest_ci, brunnermunzel, levene, bartlett
+@pytest.mark.filterwarnings('ignore:divide by zero encountered:RuntimeWarning')
+
+@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs",
+                          "paired", "unpacker"), axis_nan_policy_cases)
+@pytest.mark.parametrize(("nan_policy"), ("propagate", "omit", "raise"))
+@pytest.mark.parametrize(("axis"), (1,))
+@pytest.mark.parametrize(("data_generator"), ("mixed",))
+def test_axis_nan_policy_fast(hypotest, args, kwds, n_samples, n_outputs,
+                              paired, unpacker, nan_policy, axis,
+                              data_generator):
+    if hypotest in {stats.cramervonmises_2samp, stats.kruskal} and not SCIPY_XSLOW:
+        pytest.skip("Too slow.")
+    _axis_nan_policy_test(hypotest, args, kwds, n_samples, n_outputs, paired,
+                          unpacker, nan_policy, axis, data_generator)
+
+
+if SCIPY_XSLOW:
+    # Takes O(1 min) to run, and even skipping with the `xslow` decorator takes
+    # about 3 sec because this is >3,000 tests. So ensure pytest doesn't see
+    # them at all unless `SCIPY_XSLOW` is defined.
+
+    # These three warnings are intentional
+    # For `wilcoxon` when the sample size < 50
+    @pytest.mark.filterwarnings('ignore:Sample size too small for normal:UserWarning')
+    # `kurtosistest` and `normaltest` when sample size < 20
+    @pytest.mark.filterwarnings('ignore:`kurtosistest` p-value may be:UserWarning')
+    # `foneway`
+    @pytest.mark.filterwarnings('ignore:all input arrays have length 1.:RuntimeWarning')
+
+    # The rest of these may or may not be desirable. They need further investigation
+    # to determine whether the function's decorator should define `too_small.
+    # `bartlett`, `tvar`, `tstd`, `tsem`
+    @pytest.mark.filterwarnings('ignore:Degrees of freedom <= 0 for:RuntimeWarning')
+    # kstat, kstatvar, ttest_1samp, ttest_rel, ttest_ind, ttest_ci, brunnermunzel
+    # mood, levene, fligner, bartlett
+    @pytest.mark.filterwarnings('ignore:Invalid value encountered in:RuntimeWarning')
+    # kstatvar, ttest_1samp, ttest_rel, ttest_ci, brunnermunzel, levene, bartlett
+    @pytest.mark.filterwarnings('ignore:divide by zero encountered:RuntimeWarning')
+
+    @pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs",
+                              "paired", "unpacker"), axis_nan_policy_cases)
+    @pytest.mark.parametrize(("nan_policy"), ("propagate", "omit", "raise"))
+    @pytest.mark.parametrize(("axis"), range(-3, 3))
+    @pytest.mark.parametrize(("data_generator"),
+                             ("all_nans", "all_finite", "mixed"))
+    def test_axis_nan_policy_full(hypotest, args, kwds, n_samples, n_outputs,
+                                  paired, unpacker, nan_policy, axis,
+                                  data_generator):
+        _axis_nan_policy_test(hypotest, args, kwds, n_samples, n_outputs, paired,
+                              unpacker, nan_policy, axis, data_generator)
+
+
+def _axis_nan_policy_test(hypotest, args, kwds, n_samples, n_outputs, paired,
+                          unpacker, nan_policy, axis, data_generator):
+    # Tests the 1D and vectorized behavior of hypothesis tests against a
+    # reference implementation (nan_policy_1d with np.ndenumerate)
+
+    # Some hypothesis tests return a non-iterable that needs an `unpacker` to
+    # extract the statistic and p-value. For those that don't:
+    if not unpacker:
+        def unpacker(res):
+            return res
+
+    rng = np.random.default_rng(0)
+
+    # Generate multi-dimensional test data with all important combinations
+    # of patterns of nans along `axis`
+    n_repetitions = 3  # number of repetitions of each pattern
+    data_gen_kwds = {'n_samples': n_samples, 'n_repetitions': n_repetitions,
+                     'axis': axis, 'rng': rng, 'paired': paired}
+    if data_generator == 'mixed':
+        inherent_size = 6  # number of distinct types of patterns
+        data = _mixed_data_generator(**data_gen_kwds)
+    elif data_generator == 'all_nans':
+        inherent_size = 2  # hard-coded in _homogeneous_data_generator
+        data_gen_kwds['all_nans'] = True
+        data = _homogeneous_data_generator(**data_gen_kwds)
+    elif data_generator == 'all_finite':
+        inherent_size = 2  # hard-coded in _homogeneous_data_generator
+        data_gen_kwds['all_nans'] = False
+        data = _homogeneous_data_generator(**data_gen_kwds)
+
+    output_shape = [n_repetitions] + [inherent_size]*n_samples
+
+    # To generate reference behavior to compare against, loop over the axis-
+    # slices in data. Make indexing easier by moving `axis` to the end and
+    # broadcasting all samples to the same shape.
+    data_b = [np.moveaxis(sample, axis, -1) for sample in data]
+    data_b = [np.broadcast_to(sample, output_shape + [sample.shape[-1]])
+              for sample in data_b]
+    res_1d = np.zeros(output_shape + [n_outputs])
+
+    for i, _ in np.ndenumerate(np.zeros(output_shape)):
+        data1d = [sample[i] for sample in data_b]
+        contains_nan = any([np.isnan(sample).any() for sample in data1d])
+
+        # Take care of `nan_policy='raise'`.
+        # Afterward, the 1D part of the test is over
+        message = "The input contains nan values"
+        if nan_policy == 'raise' and contains_nan:
+            with pytest.raises(ValueError, match=message):
+                nan_policy_1d(hypotest, data1d, unpacker, *args,
+                              n_outputs=n_outputs,
+                              nan_policy=nan_policy,
+                              paired=paired, _no_deco=True, **kwds)
+
+            with pytest.raises(ValueError, match=message):
+                hypotest(*data1d, *args, nan_policy=nan_policy, **kwds)
+
+            continue
+
+        # Take care of `nan_policy='propagate'` and `nan_policy='omit'`
+
+        # Get results of simple reference implementation
+        try:
+            res_1da = nan_policy_1d(hypotest, data1d, unpacker, *args,
+                                    n_outputs=n_outputs,
+                                    nan_policy=nan_policy,
+                                    paired=paired, _no_deco=True, **kwds)
+        except (ValueError, RuntimeWarning, ZeroDivisionError) as ea:
+            ea_str = str(ea)
+            if any([str(ea_str).startswith(msg) for msg in too_small_messages]):
+                res_1da = np.full(n_outputs, np.nan)
+            else:
+                raise
+
+        # Get results of public function with 1D slices
+        # Should warn for all slices
+        if (nan_policy == 'omit' and data_generator == "all_nans"
+              and hypotest not in too_small_special_case_funcs):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_omit):
+                res = hypotest(*data1d, *args, nan_policy=nan_policy, **kwds)
+        # warning depends on slice
+        elif (nan_policy == 'omit' and data_generator == "mixed"
+              and hypotest not in too_small_special_case_funcs):
+            with np.testing.suppress_warnings() as sup:
+                sup.filter(SmallSampleWarning, too_small_1d_omit)
+                res = hypotest(*data1d, *args, nan_policy=nan_policy, **kwds)
+        # shouldn't complain if there are no NaNs
+        else:
+            res = hypotest(*data1d, *args, nan_policy=nan_policy, **kwds)
+        res_1db = unpacker(res)
+
+        assert_allclose(res_1db, res_1da, rtol=1e-15)
+        res_1d[i] = res_1db
+
+    res_1d = np.moveaxis(res_1d, -1, 0)
+
+    # Perform a vectorized call to the hypothesis test.
+
+    # If `nan_policy == 'raise'`, check that it raises the appropriate error.
+    # Test is done, so return
+    if nan_policy == 'raise' and not data_generator == "all_finite":
+        message = 'The input contains nan values'
+        with pytest.raises(ValueError, match=message):
+            hypotest(*data, axis=axis, nan_policy=nan_policy, *args, **kwds)
+        return
+
+    # If `nan_policy == 'omit', we might be left with a small sample.
+    # Check for the appropriate warning.
+    if (nan_policy == 'omit' and data_generator in {"all_nans", "mixed"}
+          and hypotest not in too_small_special_case_funcs):
+        with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
+            res = hypotest(*data, axis=axis, nan_policy=nan_policy, *args, **kwds)
+    else:  # otherwise, there should be no warning
+        res = hypotest(*data, axis=axis, nan_policy=nan_policy, *args, **kwds)
+
+    # Compare against the output against looping over 1D slices
+    res_nd = unpacker(res)
+
+    assert_allclose(res_nd, res_1d, rtol=1e-14)
+
+
+@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs",
+                          "paired", "unpacker"), axis_nan_policy_cases)
+@pytest.mark.parametrize(("nan_policy"), ("propagate", "omit", "raise"))
+@pytest.mark.parametrize(("data_generator"),
+                         ("all_nans", "all_finite", "mixed", "empty"))
+def test_axis_nan_policy_axis_is_None(hypotest, args, kwds, n_samples,
+                                      n_outputs, paired, unpacker, nan_policy,
+                                      data_generator):
+    # check for correct behavior when `axis=None`
+    if not unpacker:
+        def unpacker(res):
+            return res
+
+    rng = np.random.default_rng(0)
+
+    if data_generator == "empty":
+        data = [rng.random((2, 0)) for i in range(n_samples)]
+    else:
+        data = [rng.random((2, 20)) for i in range(n_samples)]
+
+    if data_generator == "mixed":
+        masks = [rng.random((2, 20)) > 0.9 for i in range(n_samples)]
+        for sample, mask in zip(data, masks):
+            sample[mask] = np.nan
+    elif data_generator == "all_nans":
+        data = [sample * np.nan for sample in data]
+
+    data_raveled = [sample.ravel() for sample in data]
+
+    if nan_policy == 'raise' and data_generator not in {"all_finite", "empty"}:
+        message = 'The input contains nan values'
+
+        # check for correct behavior whether or not data is 1d to begin with
+        with pytest.raises(ValueError, match=message):
+            hypotest(*data, axis=None, nan_policy=nan_policy,
+                     *args, **kwds)
+        with pytest.raises(ValueError, match=message):
+            hypotest(*data_raveled, axis=None, nan_policy=nan_policy,
+                     *args, **kwds)
+
+        return
+
+    # behavior of reference implementation with 1d input, public function with 1d
+    # input, and public function with Nd input and `axis=None` should be consistent.
+    # This means:
+    # - If the reference version raises an error or emits a warning, it's because
+    #   the sample is too small, so check that the public function emits an
+    #   appropriate "too small" warning
+    # - Any results returned by the three versions should be the same.
+    with warnings.catch_warnings():  # treat warnings as errors
+        warnings.simplefilter("error")
+
+        ea_str, eb_str, ec_str = None, None, None
+        try:
+            res1da = nan_policy_1d(hypotest, data_raveled, unpacker, *args,
+                                   n_outputs=n_outputs, nan_policy=nan_policy,
+                                   paired=paired, _no_deco=True, **kwds)
+        except (RuntimeWarning, ValueError, ZeroDivisionError) as ea:
+            res1da = None
+            ea_str = str(ea)
+
+        try:
+            res1db = hypotest(*data_raveled, *args, nan_policy=nan_policy, **kwds)
+        except SmallSampleWarning as eb:
+            eb_str = str(eb)
+
+        try:
+            res1dc = hypotest(*data, *args, axis=None, nan_policy=nan_policy, **kwds)
+        except SmallSampleWarning as ec:
+            ec_str = str(ec)
+
+    if ea_str or eb_str or ec_str:  # *if* there is some sort of error or warning
+        # If the reference implemented generated an error or warning, make sure the
+        # message was one of the expected "too small" messages. Note that some
+        # functions don't complain at all without the decorator; that's OK, too.
+        ok_msg = any([str(ea_str).startswith(msg) for msg in too_small_messages])
+        assert (ea_str is None) or ok_msg
+
+        # make sure the wrapped function emits the *intended* warning
+        desired_warnings = {too_small_1d_omit, too_small_1d_not_omit}
+        assert str(eb_str) in desired_warnings
+        assert str(ec_str) in desired_warnings
+
+        with warnings.catch_warnings():  # ignore warnings to get return value
+            warnings.simplefilter("ignore")
+            res1db = hypotest(*data_raveled, *args, nan_policy=nan_policy, **kwds)
+            res1dc = hypotest(*data, *args, axis=None, nan_policy=nan_policy, **kwds)
+
+    # Make sure any results returned by reference/public function are identical
+    # and all attributes are *NumPy* scalars
+    res1db, res1dc = unpacker(res1db), unpacker(res1dc)
+    assert_equal(res1dc, res1db)
+    all_results = list(res1db) + list(res1dc)
+
+    if res1da is not None:
+        assert_allclose(res1db, res1da, rtol=1e-15)
+        all_results += list(res1da)
+
+    for item in all_results:
+        assert np.issubdtype(item.dtype, np.number)
+        assert np.isscalar(item)
+
+
+# Test keepdims for:
+#     - Axis negative, positive, None, and tuple
+#     - 1D with no NaNs
+#     - 1D with NaN propagation
+#     - Zero-sized output
+# We're working on making `stats` quieter, but that's not what this test
+# is about. For now, we expect all sorts of warnings here due to small samples.
+@pytest.mark.filterwarnings('ignore::UserWarning')
+@pytest.mark.filterwarnings('ignore::RuntimeWarning')
+@pytest.mark.parametrize("nan_policy", ("omit", "propagate"))
+@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs",
+                          "paired", "unpacker"), axis_nan_policy_cases)
+@pytest.mark.parametrize(
+    ("sample_shape", "axis_cases"),
+    (((2, 3, 3, 4), (None, 0, -1, (0, 2), (1, -1), (3, 1, 2, 0))),
+     ((10, ), (0, -1)),
+     ((20, 0), (0, 1)))
+)
+def test_keepdims(hypotest, args, kwds, n_samples, n_outputs, paired, unpacker,
+                  sample_shape, axis_cases, nan_policy):
+    small_sample_raises = {stats.skewtest, stats.kurtosistest, stats.normaltest,
+                           stats.differential_entropy}
+    if sample_shape == (2, 3, 3, 4) and hypotest in small_sample_raises:
+        pytest.skip("Sample too small; test raises error.")
+    # test if keepdims parameter works correctly
+    if not unpacker:
+        def unpacker(res):
+            return res
+    rng = np.random.default_rng(0)
+    data = [rng.random(sample_shape) for _ in range(n_samples)]
+    nan_data = [sample.copy() for sample in data]
+    nan_mask = [rng.random(sample_shape) < 0.2 for _ in range(n_samples)]
+    for sample, mask in zip(nan_data, nan_mask):
+        sample[mask] = np.nan
+    for axis in axis_cases:
+        expected_shape = list(sample_shape)
+        if axis is None:
+            expected_shape = np.ones(len(sample_shape))
+        else:
+            if isinstance(axis, int):
+                expected_shape[axis] = 1
+            else:
+                for ax in axis:
+                    expected_shape[ax] = 1
+        expected_shape = tuple(expected_shape)
+        res = unpacker(hypotest(*data, *args, axis=axis, keepdims=True,
+                                **kwds))
+        res_base = unpacker(hypotest(*data, *args, axis=axis, keepdims=False,
+                                     **kwds))
+        nan_res = unpacker(hypotest(*nan_data, *args, axis=axis,
+                                    keepdims=True, nan_policy=nan_policy,
+                                    **kwds))
+        nan_res_base = unpacker(hypotest(*nan_data, *args, axis=axis,
+                                         keepdims=False,
+                                         nan_policy=nan_policy, **kwds))
+        for r, r_base, rn, rn_base in zip(res, res_base, nan_res,
+                                          nan_res_base):
+            assert r.shape == expected_shape
+            r = np.squeeze(r, axis=axis)
+            assert_allclose(r, r_base, atol=1e-16)
+            assert rn.shape == expected_shape
+            rn = np.squeeze(rn, axis=axis)
+            # ideally assert_equal, but `combine_pvalues` failed on 32-bit build
+            assert_allclose(rn, rn_base, atol=1e-16)
+
+
+@pytest.mark.parametrize(("fun", "nsamp"),
+                         [(stats.kstat, 1),
+                          (stats.kstatvar, 1)])
+def test_hypotest_back_compat_no_axis(fun, nsamp):
+    m, n = 8, 9
+
+    rng = np.random.default_rng(0)
+    x = rng.random((nsamp, m, n))
+    res = fun(*x)
+    res2 = fun(*x, _no_deco=True)
+    res3 = fun([xi.ravel() for xi in x])
+    assert_equal(res, res2)
+    assert_equal(res, res3)
+
+
+@pytest.mark.parametrize(("axis"), (0, 1, 2))
+def test_axis_nan_policy_decorated_positional_axis(axis):
+    # Test for correct behavior of function decorated with
+    # _axis_nan_policy_decorator whether `axis` is provided as positional or
+    # keyword argument
+
+    shape = (8, 9, 10)
+    rng = np.random.default_rng(0)
+    x = rng.random(shape)
+    y = rng.random(shape)
+    res1 = stats.mannwhitneyu(x, y, True, 'two-sided', axis)
+    res2 = stats.mannwhitneyu(x, y, True, 'two-sided', axis=axis)
+    assert_equal(res1, res2)
+
+    message = "mannwhitneyu() got multiple values for argument 'axis'"
+    with pytest.raises(TypeError, match=re.escape(message)):
+        stats.mannwhitneyu(x, y, True, 'two-sided', axis, axis=axis)
+
+
+def test_axis_nan_policy_decorated_positional_args():
+    # Test for correct behavior of function decorated with
+    # _axis_nan_policy_decorator when function accepts *args
+
+    shape = (3, 8, 9, 10)
+    rng = np.random.default_rng(0)
+    x = rng.random(shape)
+    x[0, 0, 0, 0] = np.nan
+    stats.kruskal(*x)
+
+    message = "kruskal() got an unexpected keyword argument 'samples'"
+    with pytest.raises(TypeError, match=re.escape(message)):
+        stats.kruskal(samples=x)
+
+    with pytest.raises(TypeError, match=re.escape(message)):
+        stats.kruskal(*x, samples=x)
+
+
+def test_axis_nan_policy_decorated_keyword_samples():
+    # Test for correct behavior of function decorated with
+    # _axis_nan_policy_decorator whether samples are provided as positional or
+    # keyword arguments
+
+    shape = (2, 8, 9, 10)
+    rng = np.random.default_rng(0)
+    x = rng.random(shape)
+    x[0, 0, 0, 0] = np.nan
+    res1 = stats.mannwhitneyu(*x)
+    res2 = stats.mannwhitneyu(x=x[0], y=x[1])
+    assert_equal(res1, res2)
+
+    message = "mannwhitneyu() got multiple values for argument"
+    with pytest.raises(TypeError, match=re.escape(message)):
+        stats.mannwhitneyu(*x, x=x[0], y=x[1])
+
+
+@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs",
+                          "paired", "unpacker"), axis_nan_policy_cases)
+def test_axis_nan_policy_decorated_pickled(hypotest, args, kwds, n_samples,
+                                           n_outputs, paired, unpacker):
+    if "ttest_ci" in hypotest.__name__:
+        pytest.skip("Can't pickle functions defined within functions.")
+
+    rng = np.random.default_rng(0)
+
+    # Some hypothesis tests return a non-iterable that needs an `unpacker` to
+    # extract the statistic and p-value. For those that don't:
+    if not unpacker:
+        def unpacker(res):
+            return res
+
+    data = rng.uniform(size=(n_samples, 2, 30))
+    pickled_hypotest = pickle.dumps(hypotest)
+    unpickled_hypotest = pickle.loads(pickled_hypotest)
+    res1 = unpacker(hypotest(*data, *args, axis=-1, **kwds))
+    res2 = unpacker(unpickled_hypotest(*data, *args, axis=-1, **kwds))
+    assert_allclose(res1, res2, rtol=1e-12)
+
+
+def test_check_empty_inputs():
+    # Test that _check_empty_inputs is doing its job, at least for single-
+    # sample inputs. (Multi-sample functionality is tested below.)
+    # If the input sample is not empty, it should return None.
+    # If the input sample is empty, it should return an array of NaNs or an
+    # empty array of appropriate shape. np.mean is used as a reference for the
+    # output because, like the statistics calculated by these functions,
+    # it works along and "consumes" `axis` but preserves the other axes.
+    for i in range(5):
+        for combo in combinations_with_replacement([0, 1, 2], i):
+            for axis in range(len(combo)):
+                samples = (np.zeros(combo),)
+                output = stats._axis_nan_policy._check_empty_inputs(samples,
+                                                                    axis)
+                if output is not None:
+                    with np.testing.suppress_warnings() as sup:
+                        sup.filter(RuntimeWarning, "Mean of empty slice.")
+                        sup.filter(RuntimeWarning, "invalid value encountered")
+                        reference = samples[0].mean(axis=axis)
+                    np.testing.assert_equal(output, reference)
+
+
+def _check_arrays_broadcastable(arrays, axis):
+    # https://numpy.org/doc/stable/user/basics.broadcasting.html
+    # "When operating on two arrays, NumPy compares their shapes element-wise.
+    # It starts with the trailing (i.e. rightmost) dimensions and works its
+    # way left.
+    # Two dimensions are compatible when
+    # 1. they are equal, or
+    # 2. one of them is 1
+    # ...
+    # Arrays do not need to have the same number of dimensions."
+    # (Clarification: if the arrays are compatible according to the criteria
+    #  above and an array runs out of dimensions, it is still compatible.)
+    # Below, we follow the rules above except ignoring `axis`
+
+    n_dims = max([arr.ndim for arr in arrays])
+    if axis is not None:
+        # convert to negative axis
+        axis = (-n_dims + axis) if axis >= 0 else axis
+
+    for dim in range(1, n_dims+1):  # we'll index from -1 to -n_dims, inclusive
+        if -dim == axis:
+            continue  # ignore lengths along `axis`
+
+        dim_lengths = set()
+        for arr in arrays:
+            if dim <= arr.ndim and arr.shape[-dim] != 1:
+                dim_lengths.add(arr.shape[-dim])
+
+        if len(dim_lengths) > 1:
+            return False
+    return True
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs",
+                          "paired", "unpacker"), axis_nan_policy_cases)
+def test_empty(hypotest, args, kwds, n_samples, n_outputs, paired, unpacker):
+    # test for correct output shape when at least one input is empty
+    if hypotest in {stats.kruskal, stats.friedmanchisquare} and not SCIPY_XSLOW:
+        pytest.skip("Too slow.")
+
+    if hypotest in override_propagate_funcs:
+        reason = "Doesn't follow the usual pattern. Tested separately."
+        pytest.skip(reason=reason)
+
+    if unpacker is None:
+        unpacker = lambda res: (res[0], res[1])  # noqa: E731
+
+    def small_data_generator(n_samples, n_dims):
+
+        def small_sample_generator(n_dims):
+            # return all possible "small" arrays in up to n_dim dimensions
+            for i in n_dims:
+                # "small" means with size along dimension either 0 or 1
+                for combo in combinations_with_replacement([0, 1, 2], i):
+                    yield np.zeros(combo)
+
+        # yield all possible combinations of small samples
+        gens = [small_sample_generator(n_dims) for i in range(n_samples)]
+        yield from product(*gens)
+
+    n_dims = [1, 2, 3]
+    for samples in small_data_generator(n_samples, n_dims):
+
+        # this test is only for arrays of zero size
+        if not any(sample.size == 0 for sample in samples):
+            continue
+
+        max_axis = max(sample.ndim for sample in samples)
+
+        # need to test for all valid values of `axis` parameter, too
+        for axis in range(-max_axis, max_axis):
+
+            try:
+                # After broadcasting, all arrays are the same shape, so
+                # the shape of the output should be the same as a single-
+                # sample statistic. Use np.mean as a reference.
+                concat = stats._stats_py._broadcast_concatenate(samples, axis,
+                                                                paired=paired)
+                with np.testing.suppress_warnings() as sup:
+                    sup.filter(RuntimeWarning, "Mean of empty slice.")
+                    sup.filter(RuntimeWarning, "invalid value encountered")
+                    expected = np.mean(concat, axis=axis) * np.nan
+
+                if hypotest in empty_special_case_funcs:
+                    empty_val = hypotest(*([[]]*len(samples)), *args, **kwds)
+                    expected = np.asarray(expected)
+                    mask = np.isnan(expected)
+                    expected[mask] = empty_val
+                    expected = expected[()]
+
+                if expected.size and hypotest not in too_small_special_case_funcs:
+                    message = (too_small_1d_not_omit if max_axis == 1
+                               else too_small_nd_not_omit)
+                    with pytest.warns(SmallSampleWarning, match=message):
+                        res = hypotest(*samples, *args, axis=axis, **kwds)
+                else:
+                    with np.testing.suppress_warnings() as sup:
+                        # f_oneway special case
+                        sup.filter(SmallSampleWarning, "all input arrays have length 1")
+                        res = hypotest(*samples, *args, axis=axis, **kwds)
+                res = unpacker(res)
+
+                for i in range(n_outputs):
+                    assert_equal(res[i], expected)
+
+            except ValueError:
+                # confirm that the arrays truly are not broadcastable
+                assert not _check_arrays_broadcastable(samples,
+                                                       None if paired else axis)
+
+                # confirm that _both_ `_broadcast_concatenate` and `hypotest`
+                # produce this information.
+                message = "Array shapes are incompatible for broadcasting."
+                with pytest.raises(ValueError, match=message):
+                    stats._stats_py._broadcast_concatenate(samples, axis, paired)
+                with pytest.raises(ValueError, match=message):
+                    hypotest(*samples, *args, axis=axis, **kwds)
+
+
+def paired_non_broadcastable_cases():
+    rng = np.random.default_rng(91359824598245)
+    for case in axis_nan_policy_cases:
+        hypotest, args, kwds, n_samples, n_outputs, paired, unpacker = case
+        if n_samples == 1:  # broadcasting only needed with >1 sample
+            continue
+        yield case + (rng,)
+
+
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize(("hypotest", "args", "kwds", "n_samples", "n_outputs",
+                          "paired", "unpacker", "rng"),
+                         paired_non_broadcastable_cases())
+def test_non_broadcastable(hypotest, args, kwds, n_samples, n_outputs, paired,
+                           unpacker, rng, axis):
+    # test for correct error message when shapes are not broadcastable
+
+    get_samples = True
+    while get_samples:
+        samples = [rng.random(size=rng.integers(2, 100, size=2))
+                   for i in range(n_samples)]
+        # if samples are broadcastable, try again
+        get_samples = _check_arrays_broadcastable(samples, axis=axis)
+
+    message = "Array shapes are incompatible for broadcasting."
+    with pytest.raises(ValueError, match=message):
+        hypotest(*samples, *args, **kwds)
+
+    if not paired:  # there's another test for paired-sample statistics
+        return
+
+    # Previously, paired sample statistics did not raise an error
+    # message when the shapes were broadcastable except along `axis`
+    # https://github.com/scipy/scipy/pull/19578#pullrequestreview-1766857165
+    shape = rng.integers(2, 10, size=2)
+    most_samples = [rng.random(size=shape) for i in range(n_samples-1)]
+    shape = list(shape)
+    shape[axis] += 1
+    other_sample = rng.random(size=shape)
+    with pytest.raises(ValueError, match=message):
+        hypotest(other_sample, *most_samples, *args, **kwds)
+
+
+def test_masked_array_2_sentinel_array():
+    # prepare arrays
+    np.random.seed(0)
+    A = np.random.rand(10, 11, 12)
+    B = np.random.rand(12)
+    mask = A < 0.5
+    A = np.ma.masked_array(A, mask)
+
+    # set arbitrary elements to special values
+    # (these values might have been considered for use as sentinel values)
+    max_float = np.finfo(np.float64).max
+    max_float2 = np.nextafter(max_float, -np.inf)
+    max_float3 = np.nextafter(max_float2, -np.inf)
+    A[3, 4, 1] = np.nan
+    A[4, 5, 2] = np.inf
+    A[5, 6, 3] = max_float
+    B[8] = np.nan
+    B[7] = np.inf
+    B[6] = max_float2
+
+    # convert masked A to array with sentinel value, don't modify B
+    out_arrays, sentinel = _masked_arrays_2_sentinel_arrays([A, B])
+    A_out, B_out = out_arrays
+
+    # check that good sentinel value was chosen (according to intended logic)
+    assert (sentinel != max_float) and (sentinel != max_float2)
+    assert sentinel == max_float3
+
+    # check that output arrays are as intended
+    A_reference = A.data
+    A_reference[A.mask] = sentinel
+    np.testing.assert_array_equal(A_out, A_reference)
+    assert B_out is B
+
+
+@skip_xp_invalid_arg
+def test_masked_dtype():
+    # When _masked_arrays_2_sentinel_arrays was first added, it always
+    # upcast the arrays to np.float64. After gh16662, check expected promotion
+    # and that the expected sentinel is found.
+
+    # these are important because the max of the promoted dtype is the first
+    # candidate to be the sentinel value
+    max16 = np.iinfo(np.int16).max
+    max128c = np.finfo(np.complex128).max
+
+    # a is a regular array, b has masked elements, and c has no masked elements
+    a = np.array([1, 2, max16], dtype=np.int16)
+    b = np.ma.array([1, 2, 1], dtype=np.int8, mask=[0, 1, 0])
+    c = np.ma.array([1, 2, 1], dtype=np.complex128, mask=[0, 0, 0])
+
+    # check integer masked -> sentinel conversion
+    out_arrays, sentinel = _masked_arrays_2_sentinel_arrays([a, b])
+    a_out, b_out = out_arrays
+    assert sentinel == max16-1  # not max16 because max16 was in the data
+    assert b_out.dtype == np.int16  # check expected promotion
+    assert_allclose(b_out, [b[0], sentinel, b[-1]])  # check sentinel placement
+    assert a_out is a  # not a masked array, so left untouched
+    assert not isinstance(b_out, np.ma.MaskedArray)  # b became regular array
+
+    # similarly with complex
+    out_arrays, sentinel = _masked_arrays_2_sentinel_arrays([b, c])
+    b_out, c_out = out_arrays
+    assert sentinel == max128c  # max128c was not in the data
+    assert b_out.dtype == np.complex128  # b got promoted
+    assert_allclose(b_out, [b[0], sentinel, b[-1]])  # check sentinel placement
+    assert not isinstance(b_out, np.ma.MaskedArray)  # b became regular array
+    assert not isinstance(c_out, np.ma.MaskedArray)  # c became regular array
+
+    # Also, check edge case when a sentinel value cannot be found in the data
+    min8, max8 = np.iinfo(np.int8).min, np.iinfo(np.int8).max
+    a = np.arange(min8, max8+1, dtype=np.int8)  # use all possible values
+    mask1 = np.zeros_like(a, dtype=bool)
+    mask0 = np.zeros_like(a, dtype=bool)
+
+    # a masked value can be used as the sentinel
+    mask1[1] = True
+    a1 = np.ma.array(a, mask=mask1)
+    out_arrays, sentinel = _masked_arrays_2_sentinel_arrays([a1])
+    assert sentinel == min8+1
+
+    # unless it's the smallest possible; skipped for simiplicity (see code)
+    mask0[0] = True
+    a0 = np.ma.array(a, mask=mask0)
+    message = "This function replaces masked elements with sentinel..."
+    with pytest.raises(ValueError, match=message):
+        _masked_arrays_2_sentinel_arrays([a0])
+
+    # test that dtype is preserved in functions
+    a = np.ma.array([1, 2, 3], mask=[0, 1, 0], dtype=np.float32)
+    assert stats.gmean(a).dtype == np.float32
+
+
+def test_masked_stat_1d():
+    # basic test of _axis_nan_policy_factory with 1D masked sample
+    males = [19, 22, 16, 29, 24]
+    females = [20, 11, 17, 12]
+    res = stats.mannwhitneyu(males, females)
+
+    # same result when extra nan is omitted
+    females2 = [20, 11, 17, np.nan, 12]
+    res2 = stats.mannwhitneyu(males, females2, nan_policy='omit')
+    np.testing.assert_array_equal(res2, res)
+
+    # same result when extra element is masked
+    females3 = [20, 11, 17, 1000, 12]
+    mask3 = [False, False, False, True, False]
+    females3 = np.ma.masked_array(females3, mask=mask3)
+    res3 = stats.mannwhitneyu(males, females3)
+    np.testing.assert_array_equal(res3, res)
+
+    # same result when extra nan is omitted and additional element is masked
+    females4 = [20, 11, 17, np.nan, 1000, 12]
+    mask4 = [False, False, False, False, True, False]
+    females4 = np.ma.masked_array(females4, mask=mask4)
+    res4 = stats.mannwhitneyu(males, females4, nan_policy='omit')
+    np.testing.assert_array_equal(res4, res)
+
+    # same result when extra elements, including nan, are masked
+    females5 = [20, 11, 17, np.nan, 1000, 12]
+    mask5 = [False, False, False, True, True, False]
+    females5 = np.ma.masked_array(females5, mask=mask5)
+    res5 = stats.mannwhitneyu(males, females5, nan_policy='propagate')
+    res6 = stats.mannwhitneyu(males, females5, nan_policy='raise')
+    np.testing.assert_array_equal(res5, res)
+    np.testing.assert_array_equal(res6, res)
+
+
+@pytest.mark.filterwarnings('ignore:After omitting NaNs...')
+@pytest.mark.filterwarnings('ignore:One or more axis-slices of one...')
+@skip_xp_invalid_arg
+@pytest.mark.parametrize(("axis"), range(-3, 3))
+def test_masked_stat_3d(axis):
+    # basic test of _axis_nan_policy_factory with 3D masked sample
+    np.random.seed(0)
+    a = np.random.rand(3, 4, 5)
+    b = np.random.rand(4, 5)
+    c = np.random.rand(4, 1)
+
+    mask_a = a < 0.1
+    mask_c = [False, False, False, True]
+    a_masked = np.ma.masked_array(a, mask=mask_a)
+    c_masked = np.ma.masked_array(c, mask=mask_c)
+
+    a_nans = a.copy()
+    a_nans[mask_a] = np.nan
+    c_nans = c.copy()
+    c_nans[mask_c] = np.nan
+
+    res = stats.kruskal(a_nans, b, c_nans, nan_policy='omit', axis=axis)
+    res2 = stats.kruskal(a_masked, b, c_masked, axis=axis)
+    np.testing.assert_array_equal(res, res2)
+
+
+@pytest.mark.filterwarnings('ignore:After omitting NaNs...')
+@pytest.mark.filterwarnings('ignore:One or more axis-slices of one...')
+@skip_xp_invalid_arg
+def test_mixed_mask_nan_1():
+    # targeted test of _axis_nan_policy_factory with 2D masked sample:
+    # omitting samples with masks and nan_policy='omit' are equivalent
+    # also checks paired-sample sentinel value removal
+    m, n = 3, 20
+    axis = -1
+
+    np.random.seed(0)
+    a = np.random.rand(m, n)
+    b = np.random.rand(m, n)
+    mask_a1 = np.random.rand(m, n) < 0.2
+    mask_a2 = np.random.rand(m, n) < 0.1
+    mask_b1 = np.random.rand(m, n) < 0.15
+    mask_b2 = np.random.rand(m, n) < 0.15
+    mask_a1[2, :] = True
+
+    a_nans = a.copy()
+    b_nans = b.copy()
+    a_nans[mask_a1 | mask_a2] = np.nan
+    b_nans[mask_b1 | mask_b2] = np.nan
+
+    a_masked1 = np.ma.masked_array(a, mask=mask_a1)
+    b_masked1 = np.ma.masked_array(b, mask=mask_b1)
+    a_masked1[mask_a2] = np.nan
+    b_masked1[mask_b2] = np.nan
+
+    a_masked2 = np.ma.masked_array(a, mask=mask_a2)
+    b_masked2 = np.ma.masked_array(b, mask=mask_b2)
+    a_masked2[mask_a1] = np.nan
+    b_masked2[mask_b1] = np.nan
+
+    a_masked3 = np.ma.masked_array(a, mask=(mask_a1 | mask_a2))
+    b_masked3 = np.ma.masked_array(b, mask=(mask_b1 | mask_b2))
+
+    res = stats.wilcoxon(a_nans, b_nans, nan_policy='omit', axis=axis)
+    res1 = stats.wilcoxon(a_masked1, b_masked1, nan_policy='omit', axis=axis)
+    res2 = stats.wilcoxon(a_masked2, b_masked2, nan_policy='omit', axis=axis)
+    res3 = stats.wilcoxon(a_masked3, b_masked3, nan_policy='raise', axis=axis)
+    res4 = stats.wilcoxon(a_masked3, b_masked3,
+                          nan_policy='propagate', axis=axis)
+
+    np.testing.assert_array_equal(res1, res)
+    np.testing.assert_array_equal(res2, res)
+    np.testing.assert_array_equal(res3, res)
+    np.testing.assert_array_equal(res4, res)
+
+
+@pytest.mark.filterwarnings('ignore:After omitting NaNs...')
+@pytest.mark.filterwarnings('ignore:One or more axis-slices of one...')
+@skip_xp_invalid_arg
+def test_mixed_mask_nan_2():
+    # targeted test of _axis_nan_policy_factory with 2D masked sample:
+    # check for expected interaction between masks and nans
+
+    # Cases here are
+    # [mixed nan/mask, all nans, all masked,
+    # unmasked nan, masked nan, unmasked non-nan]
+    a = [[1, np.nan, 2], [np.nan, np.nan, np.nan], [1, 2, 3],
+         [1, np.nan, 3], [1, np.nan, 3], [1, 2, 3]]
+    mask = [[1, 0, 1], [0, 0, 0], [1, 1, 1],
+            [0, 0, 0], [0, 1, 0], [0, 0, 0]]
+    a_masked = np.ma.masked_array(a, mask=mask)
+    b = [[4, 5, 6]]
+    ref1 = stats.ranksums([1, 3], [4, 5, 6])
+    ref2 = stats.ranksums([1, 2, 3], [4, 5, 6])
+
+    # nan_policy = 'omit'
+    # all elements are removed from first three rows
+    # middle element is removed from fourth and fifth rows
+    # no elements removed from last row
+    res = stats.ranksums(a_masked, b, nan_policy='omit', axis=-1)
+    stat_ref = [np.nan, np.nan, np.nan,
+                ref1.statistic, ref1.statistic, ref2.statistic]
+    p_ref = [np.nan, np.nan, np.nan,
+             ref1.pvalue, ref1.pvalue, ref2.pvalue]
+    np.testing.assert_array_equal(res.statistic, stat_ref)
+    np.testing.assert_array_equal(res.pvalue, p_ref)
+
+    # nan_policy = 'propagate'
+    # nans propagate in first, second, and fourth row
+    # all elements are removed by mask from third row
+    # middle element is removed from fifth row
+    # no elements removed from last row
+    res = stats.ranksums(a_masked, b, nan_policy='propagate', axis=-1)
+    stat_ref = [np.nan, np.nan, np.nan,
+                np.nan, ref1.statistic, ref2.statistic]
+    p_ref = [np.nan, np.nan, np.nan,
+             np.nan, ref1.pvalue, ref2.pvalue]
+    np.testing.assert_array_equal(res.statistic, stat_ref)
+    np.testing.assert_array_equal(res.pvalue, p_ref)
+
+
+def test_axis_None_vs_tuple():
+    # `axis` `None` should be equivalent to tuple with all axes
+    shape = (3, 8, 9, 10)
+    rng = np.random.default_rng(0)
+    x = rng.random(shape)
+    res = stats.kruskal(*x, axis=None)
+    res2 = stats.kruskal(*x, axis=(0, 1, 2))
+    np.testing.assert_array_equal(res, res2)
+
+
+def test_axis_None_vs_tuple_with_broadcasting():
+    # `axis` `None` should be equivalent to tuple with all axes,
+    # which should be equivalent to raveling the arrays before passing them
+    rng = np.random.default_rng(0)
+    x = rng.random((5, 1))
+    y = rng.random((1, 5))
+    x2, y2 = np.broadcast_arrays(x, y)
+
+    res0 = stats.mannwhitneyu(x.ravel(), y.ravel())
+    res1 = stats.mannwhitneyu(x, y, axis=None)
+    res2 = stats.mannwhitneyu(x, y, axis=(0, 1))
+    res3 = stats.mannwhitneyu(x2.ravel(), y2.ravel())
+
+    assert res1 == res0
+    assert res2 == res0
+    assert res3 != res0
+
+
+@pytest.mark.parametrize(("axis"),
+                         list(permutations(range(-3, 3), 2)) + [(-4, 1)])
+def test_other_axis_tuples(axis):
+    # Check that _axis_nan_policy_factory treats all `axis` tuples as expected
+    rng = np.random.default_rng(0)
+    shape_x = (4, 5, 6)
+    shape_y = (1, 6)
+    x = rng.random(shape_x)
+    y = rng.random(shape_y)
+    axis_original = axis
+
+    # convert axis elements to positive
+    axis = tuple([(i if i >= 0 else 3 + i) for i in axis])
+    axis = sorted(axis)
+
+    if len(set(axis)) != len(axis):
+        message = "`axis` must contain only distinct elements"
+        with pytest.raises(AxisError, match=re.escape(message)):
+            stats.mannwhitneyu(x, y, axis=axis_original)
+        return
+
+    if axis[0] < 0 or axis[-1] > 2:
+        message = "`axis` is out of bounds for array of dimension 3"
+        with pytest.raises(AxisError, match=re.escape(message)):
+            stats.mannwhitneyu(x, y, axis=axis_original)
+        return
+
+    res = stats.mannwhitneyu(x, y, axis=axis_original)
+
+    # reference behavior
+    not_axis = {0, 1, 2} - set(axis)  # which axis is not part of `axis`
+    not_axis = next(iter(not_axis))  # take it out of the set
+
+    x2 = x
+    shape_y_broadcasted = [1, 1, 6]
+    shape_y_broadcasted[not_axis] = shape_x[not_axis]
+    y2 = np.broadcast_to(y, shape_y_broadcasted)
+
+    m = x2.shape[not_axis]
+    x2 = np.moveaxis(x2, axis, (1, 2))
+    y2 = np.moveaxis(y2, axis, (1, 2))
+    x2 = np.reshape(x2, (m, -1))
+    y2 = np.reshape(y2, (m, -1))
+    res2 = stats.mannwhitneyu(x2, y2, axis=1)
+
+    np.testing.assert_array_equal(res, res2)
+
+
+@pytest.mark.filterwarnings('ignore:After omitting NaNs...')
+@pytest.mark.filterwarnings('ignore:One or more axis-slices of one...')
+@skip_xp_invalid_arg
+@pytest.mark.parametrize(
+    ("weighted_fun_name, unpacker"),
+    [
+        ("gmean", lambda x: x),
+        ("hmean", lambda x: x),
+        ("pmean", lambda x: x),
+        ("combine_pvalues", lambda x: (x.pvalue, x.statistic)),
+    ],
+)
+def test_mean_mixed_mask_nan_weights(weighted_fun_name, unpacker):
+    # targeted test of _axis_nan_policy_factory with 2D masked sample:
+    # omitting samples with masks and nan_policy='omit' are equivalent
+    # also checks paired-sample sentinel value removal
+
+    if weighted_fun_name == 'pmean':
+        def weighted_fun(a, **kwargs):
+            return stats.pmean(a, p=0.42, **kwargs)
+    else:
+        weighted_fun = getattr(stats, weighted_fun_name)
+
+    def func(*args, **kwargs):
+        return unpacker(weighted_fun(*args, **kwargs))
+
+    m, n = 3, 20
+    axis = -1
+
+    rng = np.random.default_rng(6541968121)
+    a = rng.uniform(size=(m, n))
+    b = rng.uniform(size=(m, n))
+    mask_a1 = rng.uniform(size=(m, n)) < 0.2
+    mask_a2 = rng.uniform(size=(m, n)) < 0.1
+    mask_b1 = rng.uniform(size=(m, n)) < 0.15
+    mask_b2 = rng.uniform(size=(m, n)) < 0.15
+    mask_a1[2, :] = True
+
+    a_nans = a.copy()
+    b_nans = b.copy()
+    a_nans[mask_a1 | mask_a2] = np.nan
+    b_nans[mask_b1 | mask_b2] = np.nan
+
+    a_masked1 = np.ma.masked_array(a, mask=mask_a1)
+    b_masked1 = np.ma.masked_array(b, mask=mask_b1)
+    a_masked1[mask_a2] = np.nan
+    b_masked1[mask_b2] = np.nan
+
+    a_masked2 = np.ma.masked_array(a, mask=mask_a2)
+    b_masked2 = np.ma.masked_array(b, mask=mask_b2)
+    a_masked2[mask_a1] = np.nan
+    b_masked2[mask_b1] = np.nan
+
+    a_masked3 = np.ma.masked_array(a, mask=(mask_a1 | mask_a2))
+    b_masked3 = np.ma.masked_array(b, mask=(mask_b1 | mask_b2))
+
+    with np.testing.suppress_warnings() as sup:
+        message = 'invalid value encountered'
+        sup.filter(RuntimeWarning, message)
+        res = func(a_nans, weights=b_nans, nan_policy="omit", axis=axis)
+        res1 = func(a_masked1, weights=b_masked1, nan_policy="omit", axis=axis)
+        res2 = func(a_masked2, weights=b_masked2, nan_policy="omit", axis=axis)
+        res3 = func(a_masked3, weights=b_masked3, nan_policy="raise", axis=axis)
+        res4 = func(a_masked3, weights=b_masked3, nan_policy="propagate", axis=axis)
+
+    np.testing.assert_array_equal(res1, res)
+    np.testing.assert_array_equal(res2, res)
+    np.testing.assert_array_equal(res3, res)
+    np.testing.assert_array_equal(res4, res)
+
+
+def test_raise_invalid_args_g17713():
+    # other cases are handled in:
+    # test_axis_nan_policy_decorated_positional_axis - multiple values for arg
+    # test_axis_nan_policy_decorated_positional_args - unexpected kwd arg
+    message = "got an unexpected keyword argument"
+    with pytest.raises(TypeError, match=message):
+        stats.gmean([1, 2, 3], invalid_arg=True)
+
+    message = " got multiple values for argument"
+    with pytest.raises(TypeError, match=message):
+        stats.gmean([1, 2, 3], a=True)
+
+    message = "missing 1 required positional argument"
+    with pytest.raises(TypeError, match=message):
+        stats.gmean()
+
+    message = "takes from 1 to 4 positional arguments but 5 were given"
+    with pytest.raises(TypeError, match=message):
+        stats.gmean([1, 2, 3], 0, float, [1, 1, 1], 10)
+
+
+@pytest.mark.parametrize('dtype', [np.int16, np.float32, np.complex128])
+def test_array_like_input(dtype):
+    # Check that `_axis_nan_policy`-decorated functions work with custom
+    # containers that are coercible to numeric arrays
+
+    class ArrLike:
+        def __init__(self, x, dtype):
+            self._x = x
+            self._dtype = dtype
+
+        def __array__(self, dtype=None, copy=None):
+            return np.asarray(x, dtype=self._dtype)
+
+    x = [1]*2 + [3, 4, 5]
+    res = stats.mode(ArrLike(x, dtype=dtype))
+    assert res.mode == 1
+    assert res.count == 2
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_binned_statistic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_binned_statistic.py
new file mode 100644
index 0000000000000000000000000000000000000000..932df07f2e489c137b378841fd749272ae0bcc89
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_binned_statistic.py
@@ -0,0 +1,568 @@
+import numpy as np
+from numpy.testing import assert_allclose
+import pytest
+from pytest import raises as assert_raises
+from scipy.stats import (binned_statistic, binned_statistic_2d,
+                         binned_statistic_dd)
+from scipy._lib._util import check_random_state
+
+from .common_tests import check_named_results
+
+
+class TestBinnedStatistic:
+
+    @classmethod
+    def setup_class(cls):
+        rng = check_random_state(9865)
+        cls.x = rng.uniform(size=100)
+        cls.y = rng.uniform(size=100)
+        cls.v = rng.uniform(size=100)
+        cls.X = rng.uniform(size=(100, 3))
+        cls.w = rng.uniform(size=100)
+        cls.u = rng.uniform(size=100) + 1e6
+
+    def test_1d_count(self):
+        x = self.x
+        v = self.v
+
+        count1, edges1, bc = binned_statistic(x, v, 'count', bins=10)
+        count2, edges2 = np.histogram(x, bins=10)
+
+        assert_allclose(count1, count2)
+        assert_allclose(edges1, edges2)
+
+    def test_gh5927(self):
+        # smoke test for gh5927 - binned_statistic was using `is` for string
+        # comparison
+        x = self.x
+        v = self.v
+        statistics = ['mean', 'median', 'count', 'sum']
+        for statistic in statistics:
+            binned_statistic(x, v, statistic, bins=10)
+
+    def test_big_number_std(self):
+        # tests for numerical stability of std calculation
+        # see issue gh-10126 for more
+        x = self.x
+        u = self.u
+        stat1, edges1, bc = binned_statistic(x, u, 'std', bins=10)
+        stat2, edges2, bc = binned_statistic(x, u, np.std, bins=10)
+
+        assert_allclose(stat1, stat2)
+
+    def test_empty_bins_std(self):
+        # tests that std returns gives nan for empty bins
+        x = self.x
+        u = self.u
+        print(binned_statistic(x, u, 'count', bins=1000))
+        stat1, edges1, bc = binned_statistic(x, u, 'std', bins=1000)
+        stat2, edges2, bc = binned_statistic(x, u, np.std, bins=1000)
+
+        assert_allclose(stat1, stat2)
+
+    def test_non_finite_inputs_and_int_bins(self):
+        # if either `values` or `sample` contain np.inf or np.nan throw
+        # see issue gh-9010 for more
+        x = self.x
+        u = self.u
+        orig = u[0]
+        u[0] = np.inf
+        assert_raises(ValueError, binned_statistic, u, x, 'std', bins=10)
+        # need to test for non-python specific ints, e.g. np.int8, np.int64
+        assert_raises(ValueError, binned_statistic, u, x, 'std',
+                      bins=np.int64(10))
+        u[0] = np.nan
+        assert_raises(ValueError, binned_statistic, u, x, 'count', bins=10)
+        # replace original value, u belongs the class
+        u[0] = orig
+
+    def test_1d_result_attributes(self):
+        x = self.x
+        v = self.v
+
+        res = binned_statistic(x, v, 'count', bins=10)
+        attributes = ('statistic', 'bin_edges', 'binnumber')
+        check_named_results(res, attributes)
+
+    def test_1d_sum(self):
+        x = self.x
+        v = self.v
+
+        sum1, edges1, bc = binned_statistic(x, v, 'sum', bins=10)
+        sum2, edges2 = np.histogram(x, bins=10, weights=v)
+
+        assert_allclose(sum1, sum2)
+        assert_allclose(edges1, edges2)
+
+    def test_1d_mean(self):
+        x = self.x
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic(x, v, 'mean', bins=10)
+        stat2, edges2, bc = binned_statistic(x, v, np.mean, bins=10)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_1d_std(self):
+        x = self.x
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic(x, v, 'std', bins=10)
+        stat2, edges2, bc = binned_statistic(x, v, np.std, bins=10)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_1d_min(self):
+        x = self.x
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic(x, v, 'min', bins=10)
+        stat2, edges2, bc = binned_statistic(x, v, np.min, bins=10)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_1d_max(self):
+        x = self.x
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic(x, v, 'max', bins=10)
+        stat2, edges2, bc = binned_statistic(x, v, np.max, bins=10)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_1d_median(self):
+        x = self.x
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic(x, v, 'median', bins=10)
+        stat2, edges2, bc = binned_statistic(x, v, np.median, bins=10)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_1d_bincode(self):
+        x = self.x[:20]
+        v = self.v[:20]
+
+        count1, edges1, bc = binned_statistic(x, v, 'count', bins=3)
+        bc2 = np.array([3, 2, 1, 3, 2, 3, 3, 3, 3, 1, 1, 3, 3, 1, 2, 3, 1,
+                        1, 2, 1])
+
+        bcount = [(bc == i).sum() for i in np.unique(bc)]
+
+        assert_allclose(bc, bc2)
+        assert_allclose(bcount, count1)
+
+    def test_1d_range_keyword(self):
+        # Regression test for gh-3063, range can be (min, max) or [(min, max)]
+        np.random.seed(9865)
+        x = np.arange(30)
+        data = np.random.random(30)
+
+        mean, bins, _ = binned_statistic(x[:15], data[:15])
+        mean_range, bins_range, _ = binned_statistic(x, data, range=[(0, 14)])
+        mean_range2, bins_range2, _ = binned_statistic(x, data, range=(0, 14))
+
+        assert_allclose(mean, mean_range)
+        assert_allclose(bins, bins_range)
+        assert_allclose(mean, mean_range2)
+        assert_allclose(bins, bins_range2)
+
+    def test_1d_multi_values(self):
+        x = self.x
+        v = self.v
+        w = self.w
+
+        stat1v, edges1v, bc1v = binned_statistic(x, v, 'mean', bins=10)
+        stat1w, edges1w, bc1w = binned_statistic(x, w, 'mean', bins=10)
+        stat2, edges2, bc2 = binned_statistic(x, [v, w], 'mean', bins=10)
+
+        assert_allclose(stat2[0], stat1v)
+        assert_allclose(stat2[1], stat1w)
+        assert_allclose(edges1v, edges2)
+        assert_allclose(bc1v, bc2)
+
+    def test_2d_count(self):
+        x = self.x
+        y = self.y
+        v = self.v
+
+        count1, binx1, biny1, bc = binned_statistic_2d(
+            x, y, v, 'count', bins=5)
+        count2, binx2, biny2 = np.histogram2d(x, y, bins=5)
+
+        assert_allclose(count1, count2)
+        assert_allclose(binx1, binx2)
+        assert_allclose(biny1, biny2)
+
+    def test_2d_result_attributes(self):
+        x = self.x
+        y = self.y
+        v = self.v
+
+        res = binned_statistic_2d(x, y, v, 'count', bins=5)
+        attributes = ('statistic', 'x_edge', 'y_edge', 'binnumber')
+        check_named_results(res, attributes)
+
+    def test_2d_sum(self):
+        x = self.x
+        y = self.y
+        v = self.v
+
+        sum1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'sum', bins=5)
+        sum2, binx2, biny2 = np.histogram2d(x, y, bins=5, weights=v)
+
+        assert_allclose(sum1, sum2)
+        assert_allclose(binx1, binx2)
+        assert_allclose(biny1, biny2)
+
+    def test_2d_mean(self):
+        x = self.x
+        y = self.y
+        v = self.v
+
+        stat1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'mean', bins=5)
+        stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.mean, bins=5)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(binx1, binx2)
+        assert_allclose(biny1, biny2)
+
+    def test_2d_mean_unicode(self):
+        x = self.x
+        y = self.y
+        v = self.v
+        stat1, binx1, biny1, bc = binned_statistic_2d(
+            x, y, v, 'mean', bins=5)
+        stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.mean, bins=5)
+        assert_allclose(stat1, stat2)
+        assert_allclose(binx1, binx2)
+        assert_allclose(biny1, biny2)
+
+    def test_2d_std(self):
+        x = self.x
+        y = self.y
+        v = self.v
+
+        stat1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'std', bins=5)
+        stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.std, bins=5)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(binx1, binx2)
+        assert_allclose(biny1, biny2)
+
+    def test_2d_min(self):
+        x = self.x
+        y = self.y
+        v = self.v
+
+        stat1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'min', bins=5)
+        stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.min, bins=5)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(binx1, binx2)
+        assert_allclose(biny1, biny2)
+
+    def test_2d_max(self):
+        x = self.x
+        y = self.y
+        v = self.v
+
+        stat1, binx1, biny1, bc = binned_statistic_2d(x, y, v, 'max', bins=5)
+        stat2, binx2, biny2, bc = binned_statistic_2d(x, y, v, np.max, bins=5)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(binx1, binx2)
+        assert_allclose(biny1, biny2)
+
+    def test_2d_median(self):
+        x = self.x
+        y = self.y
+        v = self.v
+
+        stat1, binx1, biny1, bc = binned_statistic_2d(
+            x, y, v, 'median', bins=5)
+        stat2, binx2, biny2, bc = binned_statistic_2d(
+            x, y, v, np.median, bins=5)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(binx1, binx2)
+        assert_allclose(biny1, biny2)
+
+    def test_2d_bincode(self):
+        x = self.x[:20]
+        y = self.y[:20]
+        v = self.v[:20]
+
+        count1, binx1, biny1, bc = binned_statistic_2d(
+            x, y, v, 'count', bins=3)
+        bc2 = np.array([17, 11, 6, 16, 11, 17, 18, 17, 17, 7, 6, 18, 16,
+                        6, 11, 16, 6, 6, 11, 8])
+
+        bcount = [(bc == i).sum() for i in np.unique(bc)]
+
+        assert_allclose(bc, bc2)
+        count1adj = count1[count1.nonzero()]
+        assert_allclose(bcount, count1adj)
+
+    def test_2d_multi_values(self):
+        x = self.x
+        y = self.y
+        v = self.v
+        w = self.w
+
+        stat1v, binx1v, biny1v, bc1v = binned_statistic_2d(
+            x, y, v, 'mean', bins=8)
+        stat1w, binx1w, biny1w, bc1w = binned_statistic_2d(
+            x, y, w, 'mean', bins=8)
+        stat2, binx2, biny2, bc2 = binned_statistic_2d(
+            x, y, [v, w], 'mean', bins=8)
+
+        assert_allclose(stat2[0], stat1v)
+        assert_allclose(stat2[1], stat1w)
+        assert_allclose(binx1v, binx2)
+        assert_allclose(biny1w, biny2)
+        assert_allclose(bc1v, bc2)
+
+    def test_2d_binnumbers_unraveled(self):
+        x = self.x
+        y = self.y
+        v = self.v
+
+        stat, edgesx, bcx = binned_statistic(x, v, 'mean', bins=20)
+        stat, edgesy, bcy = binned_statistic(y, v, 'mean', bins=10)
+
+        stat2, edgesx2, edgesy2, bc2 = binned_statistic_2d(
+            x, y, v, 'mean', bins=(20, 10), expand_binnumbers=True)
+
+        bcx3 = np.searchsorted(edgesx, x, side='right')
+        bcy3 = np.searchsorted(edgesy, y, side='right')
+
+        # `numpy.searchsorted` is non-inclusive on right-edge, compensate
+        bcx3[x == x.max()] -= 1
+        bcy3[y == y.max()] -= 1
+
+        assert_allclose(bcx, bc2[0])
+        assert_allclose(bcy, bc2[1])
+        assert_allclose(bcx3, bc2[0])
+        assert_allclose(bcy3, bc2[1])
+
+    def test_dd_count(self):
+        X = self.X
+        v = self.v
+
+        count1, edges1, bc = binned_statistic_dd(X, v, 'count', bins=3)
+        count2, edges2 = np.histogramdd(X, bins=3)
+
+        assert_allclose(count1, count2)
+        assert_allclose(edges1, edges2)
+
+    def test_dd_result_attributes(self):
+        X = self.X
+        v = self.v
+
+        res = binned_statistic_dd(X, v, 'count', bins=3)
+        attributes = ('statistic', 'bin_edges', 'binnumber')
+        check_named_results(res, attributes)
+
+    def test_dd_sum(self):
+        X = self.X
+        v = self.v
+
+        sum1, edges1, bc = binned_statistic_dd(X, v, 'sum', bins=3)
+        sum2, edges2 = np.histogramdd(X, bins=3, weights=v)
+        sum3, edges3, bc = binned_statistic_dd(X, v, np.sum, bins=3)
+
+        assert_allclose(sum1, sum2)
+        assert_allclose(edges1, edges2)
+        assert_allclose(sum1, sum3)
+        assert_allclose(edges1, edges3)
+
+    def test_dd_mean(self):
+        X = self.X
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic_dd(X, v, 'mean', bins=3)
+        stat2, edges2, bc = binned_statistic_dd(X, v, np.mean, bins=3)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_dd_std(self):
+        X = self.X
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic_dd(X, v, 'std', bins=3)
+        stat2, edges2, bc = binned_statistic_dd(X, v, np.std, bins=3)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_dd_min(self):
+        X = self.X
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic_dd(X, v, 'min', bins=3)
+        stat2, edges2, bc = binned_statistic_dd(X, v, np.min, bins=3)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_dd_max(self):
+        X = self.X
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic_dd(X, v, 'max', bins=3)
+        stat2, edges2, bc = binned_statistic_dd(X, v, np.max, bins=3)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_dd_median(self):
+        X = self.X
+        v = self.v
+
+        stat1, edges1, bc = binned_statistic_dd(X, v, 'median', bins=3)
+        stat2, edges2, bc = binned_statistic_dd(X, v, np.median, bins=3)
+
+        assert_allclose(stat1, stat2)
+        assert_allclose(edges1, edges2)
+
+    def test_dd_bincode(self):
+        X = self.X[:20]
+        v = self.v[:20]
+
+        count1, edges1, bc = binned_statistic_dd(X, v, 'count', bins=3)
+        bc2 = np.array([63, 33, 86, 83, 88, 67, 57, 33, 42, 41, 82, 83, 92,
+                        32, 36, 91, 43, 87, 81, 81])
+
+        bcount = [(bc == i).sum() for i in np.unique(bc)]
+
+        assert_allclose(bc, bc2)
+        count1adj = count1[count1.nonzero()]
+        assert_allclose(bcount, count1adj)
+
+    def test_dd_multi_values(self):
+        X = self.X
+        v = self.v
+        w = self.w
+
+        for stat in ["count", "sum", "mean", "std", "min", "max", "median",
+                     np.std]:
+            stat1v, edges1v, bc1v = binned_statistic_dd(X, v, stat, bins=8)
+            stat1w, edges1w, bc1w = binned_statistic_dd(X, w, stat, bins=8)
+            stat2, edges2, bc2 = binned_statistic_dd(X, [v, w], stat, bins=8)
+            assert_allclose(stat2[0], stat1v)
+            assert_allclose(stat2[1], stat1w)
+            assert_allclose(edges1v, edges2)
+            assert_allclose(edges1w, edges2)
+            assert_allclose(bc1v, bc2)
+
+    def test_dd_binnumbers_unraveled(self):
+        X = self.X
+        v = self.v
+
+        stat, edgesx, bcx = binned_statistic(X[:, 0], v, 'mean', bins=15)
+        stat, edgesy, bcy = binned_statistic(X[:, 1], v, 'mean', bins=20)
+        stat, edgesz, bcz = binned_statistic(X[:, 2], v, 'mean', bins=10)
+
+        stat2, edges2, bc2 = binned_statistic_dd(
+            X, v, 'mean', bins=(15, 20, 10), expand_binnumbers=True)
+
+        assert_allclose(bcx, bc2[0])
+        assert_allclose(bcy, bc2[1])
+        assert_allclose(bcz, bc2[2])
+
+    def test_dd_binned_statistic_result(self):
+        # NOTE: tests the reuse of bin_edges from previous call
+        x = np.random.random((10000, 3))
+        v = np.random.random(10000)
+        bins = np.linspace(0, 1, 10)
+        bins = (bins, bins, bins)
+
+        result = binned_statistic_dd(x, v, 'mean', bins=bins)
+        stat = result.statistic
+
+        result = binned_statistic_dd(x, v, 'mean',
+                                     binned_statistic_result=result)
+        stat2 = result.statistic
+
+        assert_allclose(stat, stat2)
+
+    def test_dd_zero_dedges(self):
+        x = np.random.random((10000, 3))
+        v = np.random.random(10000)
+        bins = np.linspace(0, 1, 10)
+        bins = np.append(bins, 1)
+        bins = (bins, bins, bins)
+        with assert_raises(ValueError, match='difference is numerically 0'):
+            binned_statistic_dd(x, v, 'mean', bins=bins)
+
+    def test_dd_range_errors(self):
+        # Test that descriptive exceptions are raised as appropriate for bad
+        # values of the `range` argument. (See gh-12996)
+        with assert_raises(ValueError,
+                           match='In range, start must be <= stop'):
+            binned_statistic_dd([self.y], self.v,
+                                range=[[1, 0]])
+        with assert_raises(
+                ValueError,
+                match='In dimension 1 of range, start must be <= stop'):
+            binned_statistic_dd([self.x, self.y], self.v,
+                                range=[[1, 0], [0, 1]])
+        with assert_raises(
+                ValueError,
+                match='In dimension 2 of range, start must be <= stop'):
+            binned_statistic_dd([self.x, self.y], self.v,
+                                range=[[0, 1], [1, 0]])
+        with assert_raises(
+                ValueError,
+                match='range given for 1 dimensions; 2 required'):
+            binned_statistic_dd([self.x, self.y], self.v,
+                                range=[[0, 1]])
+
+    def test_binned_statistic_float32(self):
+        X = np.array([0, 0.42358226], dtype=np.float32)
+        stat, _, _ = binned_statistic(X, None, 'count', bins=5)
+        assert_allclose(stat, np.array([1, 0, 0, 0, 1], dtype=np.float64))
+
+    def test_gh14332(self):
+        # Test the wrong output when the `sample` is close to bin edge
+        x = []
+        size = 20
+        for i in range(size):
+            x += [1-0.1**i]
+
+        bins = np.linspace(0,1,11)
+        sum1, edges1, bc = binned_statistic_dd(x, np.ones(len(x)),
+                                               bins=[bins], statistic='sum')
+        sum2, edges2 = np.histogram(x, bins=bins)
+
+        assert_allclose(sum1, sum2)
+        assert_allclose(edges1[0], edges2)
+
+    @pytest.mark.parametrize("dtype", [np.float64, np.complex128])
+    @pytest.mark.parametrize("statistic", [np.mean, np.median, np.sum, np.std,
+                                           np.min, np.max, 'count',
+                                           lambda x: (x**2).sum(),
+                                           lambda x: (x**2).sum() * 1j])
+    def test_dd_all(self, dtype, statistic):
+        def ref_statistic(x):
+            return len(x) if statistic == 'count' else statistic(x)
+
+        rng = np.random.default_rng(3704743126639371)
+        n = 10
+        x = rng.random(size=n)
+        i = x >= 0.5
+        v = rng.random(size=n)
+        if dtype is np.complex128:
+            v = v + rng.random(size=n)*1j
+
+        stat, _, _ = binned_statistic_dd(x, v, statistic, bins=2)
+        ref = np.array([ref_statistic(v[~i]), ref_statistic(v[i])])
+        assert_allclose(stat, ref)
+        assert stat.dtype == np.result_type(ref.dtype, np.float64)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_censored_data.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_censored_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae71dcfaccf899645051287f8944131ec48a1eee
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_censored_data.py
@@ -0,0 +1,152 @@
+# Tests for the CensoredData class.
+
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_array_equal
+from scipy.stats import CensoredData
+
+
+class TestCensoredData:
+
+    def test_basic(self):
+        uncensored = [1]
+        left = [0]
+        right = [2, 5]
+        interval = [[2, 3]]
+        data = CensoredData(uncensored, left=left, right=right,
+                            interval=interval)
+        assert_equal(data._uncensored, uncensored)
+        assert_equal(data._left, left)
+        assert_equal(data._right, right)
+        assert_equal(data._interval, interval)
+
+        udata = data._uncensor()
+        assert_equal(udata, np.concatenate((uncensored, left, right,
+                                            np.mean(interval, axis=1))))
+
+    def test_right_censored(self):
+        x = np.array([0, 3, 2.5])
+        is_censored = np.array([0, 1, 0], dtype=bool)
+        data = CensoredData.right_censored(x, is_censored)
+        assert_equal(data._uncensored, x[~is_censored])
+        assert_equal(data._right, x[is_censored])
+        assert_equal(data._left, [])
+        assert_equal(data._interval, np.empty((0, 2)))
+
+    def test_left_censored(self):
+        x = np.array([0, 3, 2.5])
+        is_censored = np.array([0, 1, 0], dtype=bool)
+        data = CensoredData.left_censored(x, is_censored)
+        assert_equal(data._uncensored, x[~is_censored])
+        assert_equal(data._left, x[is_censored])
+        assert_equal(data._right, [])
+        assert_equal(data._interval, np.empty((0, 2)))
+
+    def test_interval_censored_basic(self):
+        a = [0.5, 2.0, 3.0, 5.5]
+        b = [1.0, 2.5, 3.5, 7.0]
+        data = CensoredData.interval_censored(low=a, high=b)
+        assert_array_equal(data._interval, np.array(list(zip(a, b))))
+        assert data._uncensored.shape == (0,)
+        assert data._left.shape == (0,)
+        assert data._right.shape == (0,)
+
+    def test_interval_censored_mixed(self):
+        # This is actually a mix of uncensored, left-censored, right-censored
+        # and interval-censored data.  Check that when the `interval_censored`
+        # class method is used, the data is correctly separated into the
+        # appropriate arrays.
+        a = [0.5, -np.inf, -13.0, 2.0, 1.0, 10.0, -1.0]
+        b = [0.5, 2500.0, np.inf, 3.0, 1.0, 11.0, np.inf]
+        data = CensoredData.interval_censored(low=a, high=b)
+        assert_array_equal(data._interval, [[2.0, 3.0], [10.0, 11.0]])
+        assert_array_equal(data._uncensored, [0.5, 1.0])
+        assert_array_equal(data._left, [2500.0])
+        assert_array_equal(data._right, [-13.0, -1.0])
+
+    def test_interval_to_other_types(self):
+        # The interval parameter can represent uncensored and
+        # left- or right-censored data.  Test the conversion of such
+        # an example to the canonical form in which the different
+        # types have been split into the separate arrays.
+        interval = np.array([[0, 1],        # interval-censored
+                             [2, 2],        # not censored
+                             [3, 3],        # not censored
+                             [9, np.inf],   # right-censored
+                             [8, np.inf],   # right-censored
+                             [-np.inf, 0],  # left-censored
+                             [1, 2]])       # interval-censored
+        data = CensoredData(interval=interval)
+        assert_equal(data._uncensored, [2, 3])
+        assert_equal(data._left, [0])
+        assert_equal(data._right, [9, 8])
+        assert_equal(data._interval, [[0, 1], [1, 2]])
+
+    def test_empty_arrays(self):
+        data = CensoredData(uncensored=[], left=[], right=[], interval=[])
+        assert data._uncensored.shape == (0,)
+        assert data._left.shape == (0,)
+        assert data._right.shape == (0,)
+        assert data._interval.shape == (0, 2)
+        assert len(data) == 0
+
+    def test_invalid_constructor_args(self):
+        with pytest.raises(ValueError, match='must be a one-dimensional'):
+            CensoredData(uncensored=[[1, 2, 3]])
+        with pytest.raises(ValueError, match='must be a one-dimensional'):
+            CensoredData(left=[[1, 2, 3]])
+        with pytest.raises(ValueError, match='must be a one-dimensional'):
+            CensoredData(right=[[1, 2, 3]])
+        with pytest.raises(ValueError, match='must be a two-dimensional'):
+            CensoredData(interval=[[1, 2, 3]])
+
+        with pytest.raises(ValueError, match='must not contain nan'):
+            CensoredData(uncensored=[1, np.nan, 2])
+        with pytest.raises(ValueError, match='must not contain nan'):
+            CensoredData(left=[1, np.nan, 2])
+        with pytest.raises(ValueError, match='must not contain nan'):
+            CensoredData(right=[1, np.nan, 2])
+        with pytest.raises(ValueError, match='must not contain nan'):
+            CensoredData(interval=[[1, np.nan], [2, 3]])
+
+        with pytest.raises(ValueError,
+                           match='both values must not be infinite'):
+            CensoredData(interval=[[1, 3], [2, 9], [np.inf, np.inf]])
+
+        with pytest.raises(ValueError,
+                           match='left value must not exceed the right'):
+            CensoredData(interval=[[1, 0], [2, 2]])
+
+    @pytest.mark.parametrize('func', [CensoredData.left_censored,
+                                      CensoredData.right_censored])
+    def test_invalid_left_right_censored_args(self, func):
+        with pytest.raises(ValueError,
+                           match='`x` must be one-dimensional'):
+            func([[1, 2, 3]], [0, 1, 1])
+        with pytest.raises(ValueError,
+                           match='`censored` must be one-dimensional'):
+            func([1, 2, 3], [[0, 1, 1]])
+        with pytest.raises(ValueError, match='`x` must not contain'):
+            func([1, 2, np.nan], [0, 1, 1])
+        with pytest.raises(ValueError, match='must have the same length'):
+            func([1, 2, 3], [0, 0, 1, 1])
+
+    def test_invalid_censored_args(self):
+        with pytest.raises(ValueError,
+                           match='`low` must be a one-dimensional'):
+            CensoredData.interval_censored(low=[[3]], high=[4, 5])
+        with pytest.raises(ValueError,
+                           match='`high` must be a one-dimensional'):
+            CensoredData.interval_censored(low=[3], high=[[4, 5]])
+        with pytest.raises(ValueError, match='`low` must not contain'):
+            CensoredData.interval_censored([1, 2, np.nan], [0, 1, 1])
+        with pytest.raises(ValueError, match='must have the same length'):
+            CensoredData.interval_censored([1, 2, 3], [0, 0, 1, 1])
+
+    def test_count_censored(self):
+        x = [1, 2, 3]
+        # data1 has no censored data.
+        data1 = CensoredData(x)
+        assert data1.num_censored() == 0
+        data2 = CensoredData(uncensored=[2.5], left=[10], interval=[[0, 1]])
+        assert data2.num_censored() == 2
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_contingency.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_contingency.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa83e05d7da6b3d21d5515a332344c2347f0d7eb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_contingency.py
@@ -0,0 +1,294 @@
+import numpy as np
+from numpy.testing import (assert_equal, assert_array_equal,
+                           assert_array_almost_equal, assert_approx_equal,
+                           assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+from scipy import stats
+from scipy.special import xlogy
+from scipy.stats.contingency import (margins, expected_freq,
+                                     chi2_contingency, association)
+
+
+def test_margins():
+    a = np.array([1])
+    m = margins(a)
+    assert_equal(len(m), 1)
+    m0 = m[0]
+    assert_array_equal(m0, np.array([1]))
+
+    a = np.array([[1]])
+    m0, m1 = margins(a)
+    expected0 = np.array([[1]])
+    expected1 = np.array([[1]])
+    assert_array_equal(m0, expected0)
+    assert_array_equal(m1, expected1)
+
+    a = np.arange(12).reshape(2, 6)
+    m0, m1 = margins(a)
+    expected0 = np.array([[15], [51]])
+    expected1 = np.array([[6, 8, 10, 12, 14, 16]])
+    assert_array_equal(m0, expected0)
+    assert_array_equal(m1, expected1)
+
+    a = np.arange(24).reshape(2, 3, 4)
+    m0, m1, m2 = margins(a)
+    expected0 = np.array([[[66]], [[210]]])
+    expected1 = np.array([[[60], [92], [124]]])
+    expected2 = np.array([[[60, 66, 72, 78]]])
+    assert_array_equal(m0, expected0)
+    assert_array_equal(m1, expected1)
+    assert_array_equal(m2, expected2)
+
+
+def test_expected_freq():
+    assert_array_equal(expected_freq([1]), np.array([1.0]))
+
+    observed = np.array([[[2, 0], [0, 2]], [[0, 2], [2, 0]], [[1, 1], [1, 1]]])
+    e = expected_freq(observed)
+    assert_array_equal(e, np.ones_like(observed))
+
+    observed = np.array([[10, 10, 20], [20, 20, 20]])
+    e = expected_freq(observed)
+    correct = np.array([[12., 12., 16.], [18., 18., 24.]])
+    assert_array_almost_equal(e, correct)
+
+
+class TestChi2Contingency:
+    def test_chi2_contingency_trivial(self):
+        # Some very simple tests for chi2_contingency.
+
+        # A trivial case
+        obs = np.array([[1, 2], [1, 2]])
+        chi2, p, dof, expected = chi2_contingency(obs, correction=False)
+        assert_equal(chi2, 0.0)
+        assert_equal(p, 1.0)
+        assert_equal(dof, 1)
+        assert_array_equal(obs, expected)
+
+        # A *really* trivial case: 1-D data.
+        obs = np.array([1, 2, 3])
+        chi2, p, dof, expected = chi2_contingency(obs, correction=False)
+        assert_equal(chi2, 0.0)
+        assert_equal(p, 1.0)
+        assert_equal(dof, 0)
+        assert_array_equal(obs, expected)
+
+    def test_chi2_contingency_R(self):
+        # Some test cases that were computed independently, using R.
+
+        # Rcode = \
+        # """
+        # # Data vector.
+        # data <- c(
+        #   12, 34, 23,     4,  47,  11,
+        #   35, 31, 11,    34,  10,  18,
+        #   12, 32,  9,    18,  13,  19,
+        #   12, 12, 14,     9,  33,  25
+        #   )
+        #
+        # # Create factor tags:r=rows, c=columns, t=tiers
+        # r <- factor(gl(4, 2*3, 2*3*4, labels=c("r1", "r2", "r3", "r4")))
+        # c <- factor(gl(3, 1,   2*3*4, labels=c("c1", "c2", "c3")))
+        # t <- factor(gl(2, 3,   2*3*4, labels=c("t1", "t2")))
+        #
+        # # 3-way Chi squared test of independence
+        # s = summary(xtabs(data~r+c+t))
+        # print(s)
+        # """
+        # Routput = \
+        # """
+        # Call: xtabs(formula = data ~ r + c + t)
+        # Number of cases in table: 478
+        # Number of factors: 3
+        # Test for independence of all factors:
+        #         Chisq = 102.17, df = 17, p-value = 3.514e-14
+        # """
+        obs = np.array(
+            [[[12, 34, 23],
+              [35, 31, 11],
+              [12, 32, 9],
+              [12, 12, 14]],
+             [[4, 47, 11],
+              [34, 10, 18],
+              [18, 13, 19],
+              [9, 33, 25]]])
+        chi2, p, dof, expected = chi2_contingency(obs)
+        assert_approx_equal(chi2, 102.17, significant=5)
+        assert_approx_equal(p, 3.514e-14, significant=4)
+        assert_equal(dof, 17)
+
+        # Rcode = \
+        # """
+        # # Data vector.
+        # data <- c(
+        #     #
+        #     12, 17,
+        #     11, 16,
+        #     #
+        #     11, 12,
+        #     15, 16,
+        #     #
+        #     23, 15,
+        #     30, 22,
+        #     #
+        #     14, 17,
+        #     15, 16
+        #     )
+        #
+        # # Create factor tags:r=rows, c=columns, d=depths(?), t=tiers
+        # r <- factor(gl(2, 2,  2*2*2*2, labels=c("r1", "r2")))
+        # c <- factor(gl(2, 1,  2*2*2*2, labels=c("c1", "c2")))
+        # d <- factor(gl(2, 4,  2*2*2*2, labels=c("d1", "d2")))
+        # t <- factor(gl(2, 8,  2*2*2*2, labels=c("t1", "t2")))
+        #
+        # # 4-way Chi squared test of independence
+        # s = summary(xtabs(data~r+c+d+t))
+        # print(s)
+        # """
+        # Routput = \
+        # """
+        # Call: xtabs(formula = data ~ r + c + d + t)
+        # Number of cases in table: 262
+        # Number of factors: 4
+        # Test for independence of all factors:
+        #         Chisq = 8.758, df = 11, p-value = 0.6442
+        # """
+        obs = np.array(
+            [[[[12, 17],
+               [11, 16]],
+              [[11, 12],
+               [15, 16]]],
+             [[[23, 15],
+               [30, 22]],
+              [[14, 17],
+               [15, 16]]]])
+        chi2, p, dof, expected = chi2_contingency(obs)
+        assert_approx_equal(chi2, 8.758, significant=4)
+        assert_approx_equal(p, 0.6442, significant=4)
+        assert_equal(dof, 11)
+
+    def test_chi2_contingency_g(self):
+        c = np.array([[15, 60], [15, 90]])
+        g, p, dof, e = chi2_contingency(c, lambda_='log-likelihood',
+                                        correction=False)
+        assert_allclose(g, 2*xlogy(c, c/e).sum())
+
+        g, p, dof, e = chi2_contingency(c, lambda_='log-likelihood',
+                                        correction=True)
+        c_corr = c + np.array([[-0.5, 0.5], [0.5, -0.5]])
+        assert_allclose(g, 2*xlogy(c_corr, c_corr/e).sum())
+
+        c = np.array([[10, 12, 10], [12, 10, 10]])
+        g, p, dof, e = chi2_contingency(c, lambda_='log-likelihood')
+        assert_allclose(g, 2*xlogy(c, c/e).sum())
+
+    def test_chi2_contingency_bad_args(self):
+        # Test that "bad" inputs raise a ValueError.
+
+        # Negative value in the array of observed frequencies.
+        obs = np.array([[-1, 10], [1, 2]])
+        assert_raises(ValueError, chi2_contingency, obs)
+
+        # The zeros in this will result in zeros in the array
+        # of expected frequencies.
+        obs = np.array([[0, 1], [0, 1]])
+        assert_raises(ValueError, chi2_contingency, obs)
+
+        # A degenerate case: `observed` has size 0.
+        obs = np.empty((0, 8))
+        assert_raises(ValueError, chi2_contingency, obs)
+
+    def test_chi2_contingency_yates_gh13875(self):
+        # Magnitude of Yates' continuity correction should not exceed difference
+        # between expected and observed value of the statistic; see gh-13875
+        observed = np.array([[1573, 3], [4, 0]])
+        p = chi2_contingency(observed)[1]
+        assert_allclose(p, 1, rtol=1e-12)
+
+    @pytest.mark.parametrize("correction", [False, True])
+    def test_result(self, correction):
+        obs = np.array([[1, 2], [1, 2]])
+        res = chi2_contingency(obs, correction=correction)
+        assert_equal((res.statistic, res.pvalue, res.dof, res.expected_freq), res)
+
+    @pytest.mark.slow
+    def test_exact_permutation(self):
+        table = np.arange(4).reshape(2, 2)
+        ref_statistic = chi2_contingency(table, correction=False).statistic
+        ref_pvalue = stats.fisher_exact(table).pvalue
+        method = stats.PermutationMethod(n_resamples=50000)
+        res = chi2_contingency(table, correction=False, method=method)
+        assert_equal(res.statistic, ref_statistic)
+        assert_allclose(res.pvalue, ref_pvalue, rtol=1e-15)
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize('method', (stats.PermutationMethod,
+                                        stats.MonteCarloMethod))
+    def test_resampling_randomized(self, method):
+        rng = np.random.default_rng(2592340925)
+        # need to have big sum for asymptotic approximation to be good
+        rows = [300, 1000, 800]
+        cols = [200, 400, 800, 700]
+        table = stats.random_table(rows, cols, seed=rng).rvs()
+        res = chi2_contingency(table, correction=False, method=method(rng=rng))
+        ref = chi2_contingency(table, correction=False)
+        assert_equal(res.statistic, ref.statistic)
+        assert_allclose(res.pvalue, ref.pvalue, atol=5e-3)
+        assert_equal(res.dof, np.nan)
+        assert_equal(res.expected_freq, ref.expected_freq)
+
+    def test_resampling_invalid_args(self):
+        table = np.arange(8).reshape(2, 2, 2)
+
+        method = stats.PermutationMethod()
+        message = "Use of `method` is only compatible with two-way tables."
+        with pytest.raises(ValueError, match=message):
+            chi2_contingency(table, correction=False, method=method)
+
+        table = np.arange(4).reshape(2, 2)
+
+        method = stats.PermutationMethod()
+        message = "`correction=True` is not compatible with..."
+        with pytest.raises(ValueError, match=message):
+            chi2_contingency(table, method=method)
+
+        method = stats.MonteCarloMethod()
+        message = "`lambda_=2` is not compatible with..."
+        with pytest.raises(ValueError, match=message):
+            chi2_contingency(table, correction=False, lambda_=2, method=method)
+
+        method = 'herring'
+        message = "`method='herring'` not recognized; if provided, `method`..."
+        with pytest.raises(ValueError, match=message):
+            chi2_contingency(table, correction=False, method=method)
+
+        method = stats.MonteCarloMethod(rvs=stats.norm.rvs)
+        message = "If the `method` argument of `chi2_contingency` is..."
+        with pytest.raises(ValueError, match=message):
+            chi2_contingency(table, correction=False, method=method)
+
+
+def test_bad_association_args():
+    # Invalid Test Statistic
+    assert_raises(ValueError, association, [[1, 2], [3, 4]], "X")
+    # Invalid array shape
+    assert_raises(ValueError, association, [[[1, 2]], [[3, 4]]], "cramer")
+    # chi2_contingency exception
+    assert_raises(ValueError, association, [[-1, 10], [1, 2]], 'cramer')
+    # Invalid Array Item Data Type
+    assert_raises(ValueError, association,
+                  np.array([[1, 2], ["dd", 4]], dtype=object), 'cramer')
+
+
+@pytest.mark.parametrize('stat, expected',
+                         [('cramer', 0.09222412010290792),
+                          ('tschuprow', 0.0775509319944633),
+                          ('pearson', 0.12932925727138758)])
+def test_assoc(stat, expected):
+    # 2d Array
+    obs1 = np.array([[12, 13, 14, 15, 16],
+                     [17, 16, 18, 19, 11],
+                     [9, 15, 14, 12, 11]])
+    a = association(observed=obs1, method=stat)
+    assert_allclose(a, expected)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cf1b45e8d48ab2733a0d434b1174604dd239059
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous.py
@@ -0,0 +1,1879 @@
+import os
+import pickle
+from copy import deepcopy
+
+import numpy as np
+from numpy import inf
+import pytest
+from numpy.testing import assert_allclose, assert_equal
+from hypothesis import strategies, given, reproduce_failure, settings  # noqa: F401
+import hypothesis.extra.numpy as npst
+
+from scipy import stats
+from scipy.stats._fit import _kolmogorov_smirnov
+from scipy.stats._ksstats import kolmogn
+from scipy.stats import qmc
+from scipy.stats._distr_params import distcont
+from scipy.stats._distribution_infrastructure import (
+    _Domain, _RealDomain, _Parameter, _Parameterization, _RealParameter,
+    ContinuousDistribution, ShiftedScaledDistribution, _fiinfo,
+    _generate_domain_support, Mixture)
+from scipy.stats._new_distributions import StandardNormal, _LogUniform, _Gamma
+from scipy.stats import Normal, Uniform
+
+
+class Test_RealDomain:
+    rng = np.random.default_rng(349849812549824)
+
+    def test_iv(self):
+        domain = _RealDomain(endpoints=('a', 'b'))
+        message = "The endpoints of the distribution are defined..."
+        with pytest.raises(TypeError, match=message):
+            domain.get_numerical_endpoints(dict)
+
+
+    @pytest.mark.parametrize('x', [rng.uniform(10, 10, size=(2, 3, 4)),
+                                   -np.inf, np.pi])
+    def test_contains_simple(self, x):
+        # Test `contains` when endpoints are defined by constants
+        a, b = -np.inf, np.pi
+        domain = _RealDomain(endpoints=(a, b), inclusive=(False, True))
+        assert_equal(domain.contains(x), (a < x) & (x <= b))
+
+    @pytest.mark.slow
+    @given(shapes=npst.mutually_broadcastable_shapes(num_shapes=3, min_side=0),
+           inclusive_a=strategies.booleans(),
+           inclusive_b=strategies.booleans(),
+           data=strategies.data())
+    def test_contains(self, shapes, inclusive_a, inclusive_b, data):
+        # Test `contains` when endpoints are defined by parameters
+        input_shapes, result_shape = shapes
+        shape_a, shape_b, shape_x = input_shapes
+
+        # Without defining min and max values, I spent forever trying to set
+        # up a valid test without overflows or similar just drawing arrays.
+        a_elements = dict(allow_nan=False, allow_infinity=False,
+                          min_value=-1e3, max_value=1)
+        b_elements = dict(allow_nan=False, allow_infinity=False,
+                          min_value=2, max_value=1e3)
+        a = data.draw(npst.arrays(npst.floating_dtypes(),
+                                  shape_a, elements=a_elements))
+        b = data.draw(npst.arrays(npst.floating_dtypes(),
+                                  shape_b, elements=b_elements))
+        # ensure some points are to the left, some to the right, and some
+        # are exactly on the boundary
+        d = b - a
+        x = np.concatenate([np.linspace(a-d, a, 10),
+                            np.linspace(a, b, 10),
+                            np.linspace(b, b+d, 10)])
+        # Domain is defined by two parameters, 'a' and 'b'
+        domain = _RealDomain(endpoints=('a', 'b'),
+                             inclusive=(inclusive_a, inclusive_b))
+        domain.define_parameters(_RealParameter('a', domain=_RealDomain()),
+                                 _RealParameter('b', domain=_RealDomain()))
+        # Check that domain and string evaluation give the same result
+        res = domain.contains(x, dict(a=a, b=b))
+
+        # Apparently, `np.float16([2]) < np.float32(2.0009766)` is False
+        # but `np.float16([2]) < np.float32([2.0009766])` is True
+        # dtype = np.result_type(a.dtype, b.dtype, x.dtype)
+        # a, b, x = a.astype(dtype), b.astype(dtype), x.astype(dtype)
+        # unclear whether we should be careful about this, since it will be
+        # fixed with NEP50. Just do what makes the test pass.
+        left_comparison = '<=' if inclusive_a else '<'
+        right_comparison = '<=' if inclusive_b else '<'
+        ref = eval(f'(a {left_comparison} x) & (x {right_comparison} b)')
+        assert_equal(res, ref)
+
+    @pytest.mark.parametrize('case', [
+        (-np.inf, np.pi, False, True, r"(-\infty, \pi]"),
+        ('a', 5, True, False, "[a, 5)")
+    ])
+    def test_str(self, case):
+        domain = _RealDomain(endpoints=case[:2], inclusive=case[2:4])
+        assert str(domain) == case[4]
+
+    @pytest.mark.slow
+    @given(a=strategies.one_of(
+        strategies.decimals(allow_nan=False),
+        strategies.characters(whitelist_categories="L"),  # type: ignore[arg-type]
+        strategies.sampled_from(list(_Domain.symbols))),
+           b=strategies.one_of(
+        strategies.decimals(allow_nan=False),
+        strategies.characters(whitelist_categories="L"),  # type: ignore[arg-type]
+        strategies.sampled_from(list(_Domain.symbols))),
+           inclusive_a=strategies.booleans(),
+           inclusive_b=strategies.booleans(),
+           )
+    def test_str2(self, a, b, inclusive_a, inclusive_b):
+        # I wrote this independently from the implementation of __str__, but
+        # I imagine it looks pretty similar to __str__.
+        a = _Domain.symbols.get(a, a)
+        b = _Domain.symbols.get(b, b)
+        left_bracket = '[' if inclusive_a else '('
+        right_bracket = ']' if inclusive_b else ')'
+        domain = _RealDomain(endpoints=(a, b),
+                             inclusive=(inclusive_a, inclusive_b))
+        ref = f"{left_bracket}{a}, {b}{right_bracket}"
+        assert str(domain) == ref
+
+    def test_symbols_gh22137(self):
+        # `symbols` was accidentally shared between instances originally
+        # Check that this is no longer the case
+        domain1 = _RealDomain(endpoints=(0, 1))
+        domain2 = _RealDomain(endpoints=(0, 1))
+        assert domain1.symbols is not domain2.symbols
+
+
+def draw_distribution_from_family(family, data, rng, proportions, min_side=0):
+    # If the distribution has parameters, choose a parameterization and
+    # draw broadcastable shapes for the parameter arrays.
+    n_parameterizations = family._num_parameterizations()
+    if n_parameterizations > 0:
+        i = data.draw(strategies.integers(0, max_value=n_parameterizations-1))
+        n_parameters = family._num_parameters(i)
+        shapes, result_shape = data.draw(
+            npst.mutually_broadcastable_shapes(num_shapes=n_parameters,
+                                               min_side=min_side))
+        dist = family._draw(shapes, rng=rng, proportions=proportions,
+                            i_parameterization=i)
+    else:
+        dist = family._draw(rng=rng)
+        result_shape = tuple()
+
+    # Draw a broadcastable shape for the arguments, and draw values for the
+    # arguments.
+    x_shape = data.draw(npst.broadcastable_shapes(result_shape,
+                                                  min_side=min_side))
+    x = dist._variable.draw(x_shape, parameter_values=dist._parameters,
+                            proportions=proportions, rng=rng, region='typical')
+    x_result_shape = np.broadcast_shapes(x_shape, result_shape)
+    y_shape = data.draw(npst.broadcastable_shapes(x_result_shape,
+                                                  min_side=min_side))
+    y = dist._variable.draw(y_shape, parameter_values=dist._parameters,
+                            proportions=proportions, rng=rng, region='typical')
+    xy_result_shape = np.broadcast_shapes(y_shape, x_result_shape)
+    p_domain = _RealDomain((0, 1), (True, True))
+    p_var = _RealParameter('p', domain=p_domain)
+    p = p_var.draw(x_shape, proportions=proportions, rng=rng)
+    with np.errstate(divide='ignore', invalid='ignore'):
+        logp = np.log(p)
+
+    return dist, x, y, p, logp, result_shape, x_result_shape, xy_result_shape
+
+
+families = [
+    StandardNormal,
+    Normal,
+    Uniform,
+    _LogUniform
+]
+
+
+class TestDistributions:
+    @pytest.mark.fail_slow(60)  # need to break up check_moment_funcs
+    @settings(max_examples=20)
+    @pytest.mark.parametrize('family', families)
+    @given(data=strategies.data(), seed=strategies.integers(min_value=0))
+    def test_support_moments_sample(self, family, data, seed):
+        rng = np.random.default_rng(seed)
+
+        # relative proportions of valid, endpoint, out of bounds, and NaN params
+        proportions = (0.7, 0.1, 0.1, 0.1)
+        tmp = draw_distribution_from_family(family, data, rng, proportions)
+        dist, x, y, p, logp, result_shape, x_result_shape, xy_result_shape = tmp
+        sample_shape = data.draw(npst.array_shapes(min_dims=0, min_side=0,
+                                                   max_side=20))
+
+        with np.errstate(invalid='ignore', divide='ignore'):
+            check_support(dist)
+            check_moment_funcs(dist, result_shape)  # this needs to get split up
+            check_sample_shape_NaNs(dist, 'sample', sample_shape, result_shape, rng)
+            qrng = qmc.Halton(d=1, seed=rng)
+            check_sample_shape_NaNs(dist, 'sample', sample_shape, result_shape, qrng)
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.parametrize('family', families)
+    @pytest.mark.parametrize('func, methods, arg',
+                             [('entropy', {'log/exp', 'quadrature'}, None),
+                              ('logentropy', {'log/exp', 'quadrature'}, None),
+                              ('median', {'icdf'}, None),
+                              ('mode', {'optimization'}, None),
+                              ('mean', {'cache'}, None),
+                              ('variance', {'cache'}, None),
+                              ('skewness', {'cache'}, None),
+                              ('kurtosis', {'cache'}, None),
+                              ('pdf', {'log/exp'}, 'x'),
+                              ('logpdf', {'log/exp'}, 'x'),
+                              ('logcdf', {'log/exp', 'complement', 'quadrature'}, 'x'),
+                              ('cdf', {'log/exp', 'complement', 'quadrature'}, 'x'),
+                              ('logccdf', {'log/exp', 'complement', 'quadrature'}, 'x'),
+                              ('ccdf', {'log/exp', 'complement', 'quadrature'}, 'x'),
+                              ('ilogccdf', {'complement', 'inversion'}, 'logp'),
+                              ('iccdf', {'complement', 'inversion'}, 'p'),
+                              ])
+    @settings(max_examples=20)
+    @given(data=strategies.data(), seed=strategies.integers(min_value=0))
+    def test_funcs(self, family, data, seed, func, methods, arg):
+        if family == Uniform and func == 'mode':
+            pytest.skip("Mode is not unique; `method`s disagree.")
+
+        rng = np.random.default_rng(seed)
+
+        # relative proportions of valid, endpoint, out of bounds, and NaN params
+        proportions = (0.7, 0.1, 0.1, 0.1)
+        tmp = draw_distribution_from_family(family, data, rng, proportions)
+        dist, x, y, p, logp, result_shape, x_result_shape, xy_result_shape = tmp
+
+        args = {'x': x, 'p': p, 'logp': p}
+        with np.errstate(invalid='ignore', divide='ignore', over='ignore'):
+            if arg is None:
+                check_dist_func(dist, func, None, result_shape, methods)
+            elif arg in args:
+                check_dist_func(dist, func, args[arg], x_result_shape, methods)
+
+        if func == 'variance':
+            assert_allclose(dist.standard_deviation()**2, dist.variance())
+
+        # invalid and divide are to be expected; maybe look into over
+        with np.errstate(invalid='ignore', divide='ignore', over='ignore'):
+            if not isinstance(dist, ShiftedScaledDistribution):
+                if func == 'cdf':
+                    methods = {'quadrature'}
+                    check_cdf2(dist, False, x, y, xy_result_shape, methods)
+                    check_cdf2(dist, True, x, y, xy_result_shape, methods)
+                elif func == 'ccdf':
+                    methods = {'addition'}
+                    check_ccdf2(dist, False, x, y, xy_result_shape, methods)
+                    check_ccdf2(dist, True, x, y, xy_result_shape, methods)
+
+    def test_plot(self):
+        try:
+            import matplotlib.pyplot as plt
+        except ImportError:
+            return
+
+        X = Uniform(a=0., b=1.)
+        ax = X.plot()
+        assert ax == plt.gca()
+
+    @pytest.mark.parametrize('method_name', ['cdf', 'ccdf'])
+    def test_complement_safe(self, method_name):
+        X = stats.Normal()
+        X.tol = 1e-12
+        p = np.asarray([1e-4, 1e-3])
+        func = getattr(X, method_name)
+        ifunc = getattr(X, 'i'+method_name)
+        x = ifunc(p, method='formula')
+        p1 = func(x, method='complement_safe')
+        p2 = func(x, method='complement')
+        assert_equal(p1[1], p2[1])
+        assert p1[0] != p2[0]
+        assert_allclose(p1[0], p[0], rtol=X.tol)
+
+    @pytest.mark.parametrize('method_name', ['cdf', 'ccdf'])
+    def test_icomplement_safe(self, method_name):
+        X = stats.Normal()
+        X.tol = 1e-12
+        p = np.asarray([1e-4, 1e-3])
+        func = getattr(X, method_name)
+        ifunc = getattr(X, 'i'+method_name)
+        x1 = ifunc(p, method='complement_safe')
+        x2 = ifunc(p, method='complement')
+        assert_equal(x1[1], x2[1])
+        assert x1[0] != x2[0]
+        assert_allclose(func(x1[0]), p[0], rtol=X.tol)
+
+    def test_subtraction_safe(self):
+        X = stats.Normal()
+        X.tol = 1e-12
+
+        # Regular subtraction is fine in either tail (and of course, across tails)
+        x = [-11, -10, 10, 11]
+        y = [-10, -11, 11, 10]
+        p0 = X.cdf(x, y, method='quadrature')
+        p1 = X.cdf(x, y, method='subtraction_safe')
+        p2 = X.cdf(x, y, method='subtraction')
+        assert_equal(p2, p1)
+        assert_allclose(p1, p0, rtol=X.tol)
+
+        # Safe subtraction is needed in special cases
+        x = np.asarray([-1e-20, -1e-21, 1e-20, 1e-21, -1e-20])
+        y = np.asarray([-1e-21, -1e-20, 1e-21, 1e-20, 1e-20])
+        p0 = X.pdf(0)*(y-x)
+        p1 = X.cdf(x, y, method='subtraction_safe')
+        p2 = X.cdf(x, y, method='subtraction')
+        assert_equal(p2, 0)
+        assert_allclose(p1, p0, rtol=X.tol)
+
+    def test_logentropy_safe(self):
+        # simulate an `entropy` calculation over/underflowing with extreme parameters
+        class _Normal(stats.Normal):
+            def _entropy_formula(self, **params):
+                out = np.asarray(super()._entropy_formula(**params))
+                out[0] = 0
+                out[-1] = np.inf
+                return out
+
+        X = _Normal(sigma=[1, 2, 3])
+        with np.errstate(divide='ignore'):
+            res1 = X.logentropy(method='logexp_safe')
+            res2 = X.logentropy(method='logexp')
+        ref = X.logentropy(method='quadrature')
+        i_fl = [0, -1]  # first and last
+        assert np.isinf(res2[i_fl]).all()
+        assert res1[1] == res2[1]
+        # quadrature happens to be perfectly accurate on some platforms
+        # assert res1[1] != ref[1]
+        assert_equal(res1[i_fl], ref[i_fl])
+
+    def test_logcdf2_safe(self):
+        # test what happens when 2-arg `cdf` underflows
+        X = stats.Normal(sigma=[1, 2, 3])
+        x = [-301, 1, 300]
+        y = [-300, 2, 301]
+        with np.errstate(divide='ignore'):
+            res1 = X.logcdf(x, y, method='logexp_safe')
+            res2 = X.logcdf(x, y, method='logexp')
+        ref = X.logcdf(x, y, method='quadrature')
+        i_fl = [0, -1]  # first and last
+        assert np.isinf(res2[i_fl]).all()
+        assert res1[1] == res2[1]
+        # quadrature happens to be perfectly accurate on some platforms
+        # assert res1[1] != ref[1]
+        assert_equal(res1[i_fl], ref[i_fl])
+
+    @pytest.mark.parametrize('method_name', ['logcdf', 'logccdf'])
+    def test_logexp_safe(self, method_name):
+        # test what happens when `cdf`/`ccdf` underflows
+        X = stats.Normal(sigma=2)
+        x = [-301, 1] if method_name == 'logcdf' else [301, 1]
+        func = getattr(X, method_name)
+        with np.errstate(divide='ignore'):
+            res1 = func(x, method='logexp_safe')
+            res2 = func(x, method='logexp')
+        ref = func(x, method='quadrature')
+        assert res1[0] == ref[0]
+        assert res1[0] != res2[0]
+        assert res1[1] == res2[1]
+        assert res1[1] != ref[1]
+
+def check_sample_shape_NaNs(dist, fname, sample_shape, result_shape, rng):
+    full_shape = sample_shape + result_shape
+    if fname == 'sample':
+        sample_method = dist.sample
+
+    methods = {'inverse_transform'}
+    if dist._overrides(f'_{fname}_formula') and not isinstance(rng, qmc.QMCEngine):
+        methods.add('formula')
+
+    for method in methods:
+        res = sample_method(sample_shape, method=method, rng=rng)
+        valid_parameters = np.broadcast_to(get_valid_parameters(dist),
+                                           res.shape)
+        assert_equal(res.shape, full_shape)
+        np.testing.assert_equal(res.dtype, dist._dtype)
+
+        if full_shape == ():
+            # NumPy random makes a distinction between a 0d array and a scalar.
+            # In stats, we consistently turn 0d arrays into scalars, so
+            # maintain that behavior here. (With Array API arrays, this will
+            # change.)
+            assert np.isscalar(res)
+        assert np.all(np.isfinite(res[valid_parameters]))
+        assert_equal(res[~valid_parameters], np.nan)
+
+        sample1 = sample_method(sample_shape, method=method, rng=42)
+        sample2 = sample_method(sample_shape, method=method, rng=42)
+        assert not np.any(np.equal(res, sample1))
+        assert_equal(sample1, sample2)
+
+
+def check_support(dist):
+    a, b = dist.support()
+    check_nans_and_edges(dist, 'support', None, a)
+    check_nans_and_edges(dist, 'support', None, b)
+    assert a.shape == dist._shape
+    assert b.shape == dist._shape
+    assert a.dtype == dist._dtype
+    assert b.dtype == dist._dtype
+
+
+def check_dist_func(dist, fname, arg, result_shape, methods):
+    # Check that all computation methods of all distribution functions agree
+    # with one another, effectively testing the correctness of the generic
+    # computation methods and confirming the consistency of specific
+    # distributions with their pdf/logpdf.
+
+    args = tuple() if arg is None else (arg,)
+    methods = methods.copy()
+
+    if "cache" in methods:
+        # If "cache" is specified before the value has been evaluated, it
+        # raises an error. After the value is evaluated, it will succeed.
+        with pytest.raises(NotImplementedError):
+            getattr(dist, fname)(*args, method="cache")
+
+    ref = getattr(dist, fname)(*args)
+    check_nans_and_edges(dist, fname, arg, ref)
+
+    # Remove this after fixing `draw`
+    tol_override = {'atol': 1e-15}
+    # Mean can be 0, which makes logmean -inf.
+    if fname in {'logmean', 'mean', 'logskewness', 'skewness'}:
+        tol_override = {'atol': 1e-15}
+    elif fname in {'mode'}:
+        # can only expect about half of machine precision for optimization
+        # because math
+        tol_override = {'atol': 1e-6}
+    elif fname in {'logcdf'}:  # gh-22276
+        tol_override = {'rtol': 2e-7}
+
+    if dist._overrides(f'_{fname}_formula'):
+        methods.add('formula')
+
+    np.testing.assert_equal(ref.shape, result_shape)
+    # Until we convert to array API, let's do the familiar thing:
+    # 0d things are scalars, not arrays
+    if result_shape == tuple():
+        assert np.isscalar(ref)
+
+    for method in methods:
+        res = getattr(dist, fname)(*args, method=method)
+        if 'log' in fname:
+            np.testing.assert_allclose(np.exp(res), np.exp(ref),
+                                       **tol_override)
+        else:
+            np.testing.assert_allclose(res, ref, **tol_override)
+
+        # for now, make sure dtypes are consistent; later, we can check whether
+        # they are correct.
+        np.testing.assert_equal(res.dtype, ref.dtype)
+        np.testing.assert_equal(res.shape, result_shape)
+        if result_shape == tuple():
+            assert np.isscalar(res)
+
+def check_cdf2(dist, log, x, y, result_shape, methods):
+    # Specialized test for 2-arg cdf since the interface is a bit different
+    # from the other methods. Here, we'll use 1-arg cdf as a reference, and
+    # since we have already checked 1-arg cdf in `check_nans_and_edges`, this
+    # checks the equivalent of both `check_dist_func` and
+    # `check_nans_and_edges`.
+    methods = methods.copy()
+
+    if log:
+        if dist._overrides('_logcdf2_formula'):
+            methods.add('formula')
+        if dist._overrides('_logcdf_formula') or dist._overrides('_logccdf_formula'):
+            methods.add('subtraction')
+        if (dist._overrides('_cdf_formula')
+                or dist._overrides('_ccdf_formula')):
+            methods.add('log/exp')
+    else:
+        if dist._overrides('_cdf2_formula'):
+            methods.add('formula')
+        if dist._overrides('_cdf_formula') or dist._overrides('_ccdf_formula'):
+            methods.add('subtraction')
+        if (dist._overrides('_logcdf_formula')
+                or dist._overrides('_logccdf_formula')):
+            methods.add('log/exp')
+
+    ref = dist.cdf(y) - dist.cdf(x)
+    np.testing.assert_equal(ref.shape, result_shape)
+
+    if result_shape == tuple():
+        assert np.isscalar(ref)
+
+    for method in methods:
+        res = (np.exp(dist.logcdf(x, y, method=method)) if log
+               else dist.cdf(x, y, method=method))
+        np.testing.assert_allclose(res, ref, atol=1e-14)
+        if log:
+            np.testing.assert_equal(res.dtype, (ref + 0j).dtype)
+        else:
+            np.testing.assert_equal(res.dtype, ref.dtype)
+        np.testing.assert_equal(res.shape, result_shape)
+        if result_shape == tuple():
+            assert np.isscalar(res)
+
+
+def check_ccdf2(dist, log, x, y, result_shape, methods):
+    # Specialized test for 2-arg ccdf since the interface is a bit different
+    # from the other methods. Could be combined with check_cdf2 above, but
+    # writing it separately is simpler.
+    methods = methods.copy()
+
+    if dist._overrides(f'_{"log" if log else ""}ccdf2_formula'):
+        methods.add('formula')
+
+    ref = dist.cdf(x) + dist.ccdf(y)
+    np.testing.assert_equal(ref.shape, result_shape)
+
+    if result_shape == tuple():
+        assert np.isscalar(ref)
+
+    for method in methods:
+        res = (np.exp(dist.logccdf(x, y, method=method)) if log
+               else dist.ccdf(x, y, method=method))
+        np.testing.assert_allclose(res, ref, atol=1e-14)
+        np.testing.assert_equal(res.dtype, ref.dtype)
+        np.testing.assert_equal(res.shape, result_shape)
+        if result_shape == tuple():
+            assert np.isscalar(res)
+
+
+def check_nans_and_edges(dist, fname, arg, res):
+
+    valid_parameters = get_valid_parameters(dist)
+    if fname in {'icdf', 'iccdf'}:
+        arg_domain = _RealDomain(endpoints=(0, 1), inclusive=(True, True))
+    elif fname in {'ilogcdf', 'ilogccdf'}:
+        arg_domain = _RealDomain(endpoints=(-inf, 0), inclusive=(True, True))
+    else:
+        arg_domain = dist._variable.domain
+
+    classified_args = classify_arg(dist, arg, arg_domain)
+    valid_parameters, *classified_args = np.broadcast_arrays(valid_parameters,
+                                                             *classified_args)
+    valid_arg, endpoint_arg, outside_arg, nan_arg = classified_args
+    all_valid = valid_arg & valid_parameters
+
+    # Check NaN pattern and edge cases
+    assert_equal(res[~valid_parameters], np.nan)
+    assert_equal(res[nan_arg], np.nan)
+
+    a, b = dist.support()
+    a = np.broadcast_to(a, res.shape)
+    b = np.broadcast_to(b, res.shape)
+
+    outside_arg_minus = (outside_arg == -1) & valid_parameters
+    outside_arg_plus = (outside_arg == 1) & valid_parameters
+    endpoint_arg_minus = (endpoint_arg == -1) & valid_parameters
+    endpoint_arg_plus = (endpoint_arg == 1) & valid_parameters
+    # Writing this independently of how the are set in the distribution
+    # infrastructure. That is very compact; this is very verbose.
+    if fname in {'logpdf'}:
+        assert_equal(res[outside_arg_minus], -np.inf)
+        assert_equal(res[outside_arg_plus], -np.inf)
+        assert_equal(res[endpoint_arg_minus & ~valid_arg], -np.inf)
+        assert_equal(res[endpoint_arg_plus & ~valid_arg], -np.inf)
+    elif fname in {'pdf'}:
+        assert_equal(res[outside_arg_minus], 0)
+        assert_equal(res[outside_arg_plus], 0)
+        assert_equal(res[endpoint_arg_minus & ~valid_arg], 0)
+        assert_equal(res[endpoint_arg_plus & ~valid_arg], 0)
+    elif fname in {'logcdf'}:
+        assert_equal(res[outside_arg_minus], -inf)
+        assert_equal(res[outside_arg_plus], 0)
+        assert_equal(res[endpoint_arg_minus], -inf)
+        assert_equal(res[endpoint_arg_plus], 0)
+    elif fname in {'cdf'}:
+        assert_equal(res[outside_arg_minus], 0)
+        assert_equal(res[outside_arg_plus], 1)
+        assert_equal(res[endpoint_arg_minus], 0)
+        assert_equal(res[endpoint_arg_plus], 1)
+    elif fname in {'logccdf'}:
+        assert_equal(res[outside_arg_minus], 0)
+        assert_equal(res[outside_arg_plus], -inf)
+        assert_equal(res[endpoint_arg_minus], 0)
+        assert_equal(res[endpoint_arg_plus], -inf)
+    elif fname in {'ccdf'}:
+        assert_equal(res[outside_arg_minus], 1)
+        assert_equal(res[outside_arg_plus], 0)
+        assert_equal(res[endpoint_arg_minus], 1)
+        assert_equal(res[endpoint_arg_plus], 0)
+    elif fname in {'ilogcdf', 'icdf'}:
+        assert_equal(res[outside_arg == -1], np.nan)
+        assert_equal(res[outside_arg == 1], np.nan)
+        assert_equal(res[endpoint_arg == -1], a[endpoint_arg == -1])
+        assert_equal(res[endpoint_arg == 1], b[endpoint_arg == 1])
+    elif fname in {'ilogccdf', 'iccdf'}:
+        assert_equal(res[outside_arg == -1], np.nan)
+        assert_equal(res[outside_arg == 1], np.nan)
+        assert_equal(res[endpoint_arg == -1], b[endpoint_arg == -1])
+        assert_equal(res[endpoint_arg == 1], a[endpoint_arg == 1])
+
+    if fname not in {'logmean', 'mean', 'logskewness', 'skewness', 'support'}:
+        assert np.isfinite(res[all_valid & (endpoint_arg == 0)]).all()
+
+
+def check_moment_funcs(dist, result_shape):
+    # Check that all computation methods of all distribution functions agree
+    # with one another, effectively testing the correctness of the generic
+    # computation methods and confirming the consistency of specific
+    # distributions with their pdf/logpdf.
+
+    atol = 1e-9  # make this tighter (e.g. 1e-13) after fixing `draw`
+
+    def check(order, kind, method=None, ref=None, success=True):
+        if success:
+            res = dist.moment(order, kind, method=method)
+            assert_allclose(res, ref, atol=atol*10**order)
+            assert res.shape == ref.shape
+        else:
+            with pytest.raises(NotImplementedError):
+                dist.moment(order, kind, method=method)
+
+    def has_formula(order, kind):
+        formula_name = f'_moment_{kind}_formula'
+        overrides = dist._overrides(formula_name)
+        if not overrides:
+            return False
+        formula = getattr(dist, formula_name)
+        orders = getattr(formula, 'orders', set(range(6)))
+        return order in orders
+
+
+    dist.reset_cache()
+
+    ### Check Raw Moments ###
+    for i in range(6):
+        check(i, 'raw', 'cache', success=False)  # not cached yet
+        ref = dist.moment(i, 'raw', method='quadrature')
+        check_nans_and_edges(dist, 'moment', None, ref)
+        assert ref.shape == result_shape
+        check(i, 'raw','cache', ref, success=True)  # cached now
+        check(i, 'raw', 'formula', ref, success=has_formula(i, 'raw'))
+        check(i, 'raw', 'general', ref, success=(i == 0))
+        if dist.__class__ == stats.Normal:
+            check(i, 'raw', 'quadrature_icdf', ref, success=True)
+
+
+    # Clearing caches to better check their behavior
+    dist.reset_cache()
+
+    # If we have central or standard moment formulas, or if there are
+    # values in their cache, we can use method='transform'
+    dist.moment(0, 'central')  # build up the cache
+    dist.moment(1, 'central')
+    for i in range(2, 6):
+        ref = dist.moment(i, 'raw', method='quadrature')
+        check(i, 'raw', 'transform', ref,
+              success=has_formula(i, 'central') or has_formula(i, 'standardized'))
+        dist.moment(i, 'central')  # build up the cache
+        check(i, 'raw', 'transform', ref)
+
+    dist.reset_cache()
+
+    ### Check Central Moments ###
+
+    for i in range(6):
+        check(i, 'central', 'cache', success=False)
+        ref = dist.moment(i, 'central', method='quadrature')
+        assert ref.shape == result_shape
+        check(i, 'central', 'cache', ref, success=True)
+        check(i, 'central', 'formula', ref, success=has_formula(i, 'central'))
+        check(i, 'central', 'general', ref, success=i <= 1)
+        if dist.__class__ == stats.Normal:
+            check(i, 'central', 'quadrature_icdf', ref, success=True)
+        if not (dist.__class__ == stats.Uniform and i == 5):
+            # Quadrature is not super accurate for 5th central moment when the
+            # support is really big. Skip this one failing test. We need to come
+            # up with a better system of skipping individual failures w/ hypothesis.
+            check(i, 'central', 'transform', ref,
+                  success=has_formula(i, 'raw') or (i <= 1))
+        if not has_formula(i, 'raw'):
+            dist.moment(i, 'raw')
+            check(i, 'central', 'transform', ref)
+
+    dist.reset_cache()
+
+    # If we have standard moment formulas, or if there are
+    # values in their cache, we can use method='normalize'
+    dist.moment(0, 'standardized')  # build up the cache
+    dist.moment(1, 'standardized')
+    dist.moment(2, 'standardized')
+    for i in range(3, 6):
+        ref = dist.moment(i, 'central', method='quadrature')
+        check(i, 'central', 'normalize', ref,
+              success=has_formula(i, 'standardized'))
+        dist.moment(i, 'standardized')  # build up the cache
+        check(i, 'central', 'normalize', ref)
+
+    ### Check Standardized Moments ###
+
+    var = dist.moment(2, 'central', method='quadrature')
+    dist.reset_cache()
+
+    for i in range(6):
+        check(i, 'standardized', 'cache', success=False)
+        ref = dist.moment(i, 'central', method='quadrature') / var ** (i / 2)
+        assert ref.shape == result_shape
+        check(i, 'standardized', 'formula', ref,
+              success=has_formula(i, 'standardized'))
+        check(i, 'standardized', 'general', ref, success=i <= 2)
+        check(i, 'standardized', 'normalize', ref)
+
+    if isinstance(dist, ShiftedScaledDistribution):
+        # logmoment is not fully fleshed out; no need to test
+        # ShiftedScaledDistribution here
+        return
+
+    # logmoment is not very accuate, and it's not public, so skip for now
+    # ### Check Against _logmoment ###
+    # logmean = dist._logmoment(1, logcenter=-np.inf)
+    # for i in range(6):
+    #     ref = np.exp(dist._logmoment(i, logcenter=-np.inf))
+    #     assert_allclose(dist.moment(i, 'raw'), ref, atol=atol*10**i)
+    #
+    #     ref = np.exp(dist._logmoment(i, logcenter=logmean))
+    #     assert_allclose(dist.moment(i, 'central'), ref, atol=atol*10**i)
+    #
+    #     ref = np.exp(dist._logmoment(i, logcenter=logmean, standardized=True))
+    #     assert_allclose(dist.moment(i, 'standardized'), ref, atol=atol*10**i)
+
+
+@pytest.mark.parametrize('family', (Normal,))
+@pytest.mark.parametrize('x_shape', [tuple(), (2, 3)])
+@pytest.mark.parametrize('dist_shape', [tuple(), (4, 1)])
+@pytest.mark.parametrize('fname', ['sample'])
+@pytest.mark.parametrize('rng_type', [np.random.Generator, qmc.Halton, qmc.Sobol])
+def test_sample_against_cdf(family, dist_shape, x_shape, fname, rng_type):
+    rng = np.random.default_rng(842582438235635)
+    num_parameters = family._num_parameters()
+
+    if dist_shape and num_parameters == 0:
+        pytest.skip("Distribution can't have a shape without parameters.")
+
+    dist = family._draw(dist_shape, rng)
+
+    n = 1024
+    sample_size = (n,) + x_shape
+    sample_array_shape = sample_size + dist_shape
+
+    if fname == 'sample':
+        sample_method = dist.sample
+
+    if rng_type != np.random.Generator:
+        rng = rng_type(d=1, seed=rng)
+    x = sample_method(sample_size, rng=rng)
+    assert x.shape == sample_array_shape
+
+    # probably should give `axis` argument to ks_1samp, review that separately
+    statistic = _kolmogorov_smirnov(dist, x, axis=0)
+    pvalue = kolmogn(x.shape[0], statistic, cdf=False)
+    p_threshold = 0.01
+    num_pvalues = pvalue.size
+    num_small_pvalues = np.sum(pvalue < p_threshold)
+    assert num_small_pvalues < p_threshold * num_pvalues
+
+
+def get_valid_parameters(dist):
+    # Given a distribution, return a logical array that is true where all
+    # distribution parameters are within their respective domains. The code
+    # here is probably quite similar to that used to form the `_invalid`
+    # attribute of the distribution, but this was written about a week later
+    # without referring to that code, so it is a somewhat independent check.
+
+    # Get all parameter values and `_Parameter` objects
+    parameter_values = dist._parameters
+    parameters = {}
+    for parameterization in dist._parameterizations:
+        parameters.update(parameterization.parameters)
+
+    all_valid = np.ones(dist._shape, dtype=bool)
+    for name, value in parameter_values.items():
+        if name not in parameters:  # cached value not part of parameterization
+            continue
+        parameter = parameters[name]
+
+        # Check that the numerical endpoints and inclusivity attribute
+        # agree with the `contains` method about which parameter values are
+        # within the domain.
+        a, b = parameter.domain.get_numerical_endpoints(
+            parameter_values=parameter_values)
+        a_included, b_included = parameter.domain.inclusive
+        valid = (a <= value) if a_included else a < value
+        valid &= (value <= b) if b_included else value < b
+        assert_equal(valid, parameter.domain.contains(
+            value, parameter_values=parameter_values))
+
+        # Form `all_valid` mask that is True where *all* parameters are valid
+        all_valid &= valid
+
+    # Check that the `all_valid` mask formed here is the complement of the
+    # `dist._invalid` mask stored by the infrastructure
+    assert_equal(~all_valid, dist._invalid)
+
+    return all_valid
+
+def classify_arg(dist, arg, arg_domain):
+    if arg is None:
+        valid_args = np.ones(dist._shape, dtype=bool)
+        endpoint_args = np.zeros(dist._shape, dtype=bool)
+        outside_args = np.zeros(dist._shape, dtype=bool)
+        nan_args = np.zeros(dist._shape, dtype=bool)
+        return valid_args, endpoint_args, outside_args, nan_args
+
+    a, b = arg_domain.get_numerical_endpoints(
+        parameter_values=dist._parameters)
+
+    a, b, arg = np.broadcast_arrays(a, b, arg)
+    a_included, b_included = arg_domain.inclusive
+
+    inside = (a <= arg) if a_included else a < arg
+    inside &= (arg <= b) if b_included else arg < b
+    # TODO: add `supported` method and check here
+    on = np.zeros(a.shape, dtype=int)
+    on[a == arg] = -1
+    on[b == arg] = 1
+    outside = np.zeros(a.shape, dtype=int)
+    outside[(arg < a) if a_included else arg <= a] = -1
+    outside[(b < arg) if b_included else b <= arg] = 1
+    nan = np.isnan(arg)
+
+    return inside, on, outside, nan
+
+
+def test_input_validation():
+    class Test(ContinuousDistribution):
+        _variable = _RealParameter('x', domain=_RealDomain())
+
+    message = ("The `Test` distribution family does not accept parameters, "
+               "but parameters `{'a'}` were provided.")
+    with pytest.raises(ValueError, match=message):
+        Test(a=1, )
+
+    message = "Attribute `tol` of `Test` must be a positive float, if specified."
+    with pytest.raises(ValueError, match=message):
+        Test(tol=np.asarray([]))
+    with pytest.raises(ValueError, match=message):
+        Test(tol=[1, 2, 3])
+    with pytest.raises(ValueError, match=message):
+        Test(tol=np.nan)
+    with pytest.raises(ValueError, match=message):
+        Test(tol=-1)
+
+    message = ("Argument `order` of `Test.moment` must be a "
+               "finite, positive integer.")
+    with pytest.raises(ValueError, match=message):
+        Test().moment(-1)
+    with pytest.raises(ValueError, match=message):
+        Test().moment(np.inf)
+
+    message = "Argument `kind` of `Test.moment` must be one of..."
+    with pytest.raises(ValueError, match=message):
+        Test().moment(2, kind='coconut')
+
+    class Test2(ContinuousDistribution):
+        _p1 = _RealParameter('c', domain=_RealDomain())
+        _p2 = _RealParameter('d', domain=_RealDomain())
+        _parameterizations = [_Parameterization(_p1, _p2)]
+        _variable = _RealParameter('x', domain=_RealDomain())
+
+    message = ("The provided parameters `{a}` do not match a supported "
+               "parameterization of the `Test2` distribution family.")
+    with pytest.raises(ValueError, match=message):
+        Test2(a=1)
+
+    message = ("The `Test2` distribution family requires parameters, but none "
+               "were provided.")
+    with pytest.raises(ValueError, match=message):
+        Test2()
+
+    message = ("The parameters `{c, d}` provided to the `Test2` "
+               "distribution family cannot be broadcast to the same shape.")
+    with pytest.raises(ValueError, match=message):
+        Test2(c=[1, 2], d=[1, 2, 3])
+
+    message = ("The argument provided to `Test2.pdf` cannot be be broadcast to "
+              "the same shape as the distribution parameters.")
+    with pytest.raises(ValueError, match=message):
+        dist = Test2(c=[1, 2, 3], d=[1, 2, 3])
+        dist.pdf([1, 2])
+
+    message = "Parameter `c` must be of real dtype."
+    with pytest.raises(TypeError, match=message):
+        Test2(c=[1, object()], d=[1, 2])
+
+    message = "Parameter `convention` of `Test2.kurtosis` must be one of..."
+    with pytest.raises(ValueError, match=message):
+        dist = Test2(c=[1, 2, 3], d=[1, 2, 3])
+        dist.kurtosis(convention='coconut')
+
+
+def test_rng_deepcopy_pickle():
+    # test behavior of `rng` attribute and copy behavior
+    kwargs = dict(a=[-1, 2], b=10)
+    dist1 = Uniform(**kwargs)
+    dist2 = deepcopy(dist1)
+    dist3 = pickle.loads(pickle.dumps(dist1))
+
+    res1, res2, res3 = dist1.sample(), dist2.sample(), dist3.sample()
+    assert np.all(res2 != res1)
+    assert np.all(res3 != res1)
+
+    res1, res2, res3 = dist1.sample(rng=42), dist2.sample(rng=42), dist3.sample(rng=42)
+    assert np.all(res2 == res1)
+    assert np.all(res3 == res1)
+
+
+class TestAttributes:
+    def test_cache_policy(self):
+        dist = StandardNormal(cache_policy="no_cache")
+        # make error message more appropriate
+        message = "`StandardNormal` does not provide an accurate implementation of the "
+        with pytest.raises(NotImplementedError, match=message):
+            dist.mean(method='cache')
+        mean = dist.mean()
+        with pytest.raises(NotImplementedError, match=message):
+            dist.mean(method='cache')
+
+        # add to enum
+        dist.cache_policy = None
+        with pytest.raises(NotImplementedError, match=message):
+            dist.mean(method='cache')
+        mean = dist.mean()  # method is 'formula' by default
+        cached_mean = dist.mean(method='cache')
+        assert_equal(cached_mean, mean)
+
+        # cache is overridden by latest evaluation
+        quadrature_mean = dist.mean(method='quadrature')
+        cached_mean = dist.mean(method='cache')
+        assert_equal(cached_mean, quadrature_mean)
+        assert not np.all(mean == quadrature_mean)
+
+        # We can turn the cache off, and it won't change, but the old cache is
+        # still available
+        dist.cache_policy = "no_cache"
+        mean = dist.mean(method='formula')
+        cached_mean = dist.mean(method='cache')
+        assert_equal(cached_mean, quadrature_mean)
+        assert not np.all(mean == quadrature_mean)
+
+        dist.reset_cache()
+        with pytest.raises(NotImplementedError, match=message):
+            dist.mean(method='cache')
+
+        message = "Attribute `cache_policy` of `StandardNormal`..."
+        with pytest.raises(ValueError, match=message):
+            dist.cache_policy = "invalid"
+
+    def test_tol(self):
+        x = 3.
+        X = stats.Normal()
+
+        message = "Attribute `tol` of `StandardNormal` must..."
+        with pytest.raises(ValueError, match=message):
+            X.tol = -1.
+        with pytest.raises(ValueError, match=message):
+            X.tol = (0.1,)
+        with pytest.raises(ValueError, match=message):
+            X.tol = np.nan
+
+        X1 = stats.Normal(tol=1e-1)
+        X2 = stats.Normal(tol=1e-12)
+        ref = X.cdf(x)
+        res1 = X1.cdf(x, method='quadrature')
+        res2 = X2.cdf(x, method='quadrature')
+        assert_allclose(res1, ref, rtol=X1.tol)
+        assert_allclose(res2, ref, rtol=X2.tol)
+        assert abs(res1 - ref) > abs(res2 - ref)
+
+        p = 0.99
+        X1.tol, X2.tol = X2.tol, X1.tol
+        ref = X.icdf(p)
+        res1 = X1.icdf(p, method='inversion')
+        res2 = X2.icdf(p, method='inversion')
+        assert_allclose(res1, ref, rtol=X1.tol)
+        assert_allclose(res2, ref, rtol=X2.tol)
+        assert abs(res2 - ref) > abs(res1 - ref)
+
+    def test_iv_policy(self):
+        X = Uniform(a=0, b=1)
+        assert X.pdf(2) == 0
+
+        X.validation_policy = 'skip_all'
+        assert X.pdf(np.asarray(2.)) == 1
+
+        # Tests _set_invalid_nan
+        a, b = np.asarray(1.), np.asarray(0.)  # invalid parameters
+        X = Uniform(a=a, b=b, validation_policy='skip_all')
+        assert X.pdf(np.asarray(2.)) == -1
+
+        # Tests _set_invalid_nan_property
+        class MyUniform(Uniform):
+            def _entropy_formula(self, *args, **kwargs):
+                return 'incorrect'
+
+            def _moment_raw_formula(self, order, **params):
+                return 'incorrect'
+
+        X = MyUniform(a=a, b=b, validation_policy='skip_all')
+        assert X.entropy() == 'incorrect'
+
+        # Tests _validate_order_kind
+        assert X.moment(kind='raw', order=-1) == 'incorrect'
+
+        # Test input validation
+        message = "Attribute `validation_policy` of `MyUniform`..."
+        with pytest.raises(ValueError, match=message):
+            X.validation_policy = "invalid"
+
+    def test_shapes(self):
+        X = stats.Normal(mu=1, sigma=2)
+        Y = stats.Normal(mu=[2], sigma=3)
+
+        # Check that attributes are available as expected
+        assert X.mu == 1
+        assert X.sigma == 2
+        assert Y.mu[0] == 2
+        assert Y.sigma[0] == 3
+
+        # Trying to set an attribute raises
+        # message depends on Python version
+        with pytest.raises(AttributeError):
+            X.mu = 2
+
+        # Trying to mutate an attribute really mutates a copy
+        Y.mu[0] = 10
+        assert Y.mu[0] == 2
+
+
+class TestMakeDistribution:
+    @pytest.mark.parametrize('i, distdata', enumerate(distcont))
+    def test_make_distribution(self, i, distdata):
+        distname = distdata[0]
+
+        slow = {'argus', 'exponpow', 'exponweib', 'genexpon', 'gompertz', 'halfgennorm',
+                'johnsonsb', 'kappa4', 'ksone', 'kstwo', 'kstwobign', 'powerlognorm',
+                'powernorm', 'recipinvgauss', 'studentized_range', 'vonmises_line'}
+        if not int(os.environ.get('SCIPY_XSLOW', '0')) and distname in slow:
+            pytest.skip('Skipping as XSLOW')
+
+        if distname in {  # skip these distributions
+            'levy_stable',  # private methods seem to require >= 1d args
+            'vonmises',  # circular distribution; shouldn't work
+        }:
+            return
+
+        # skip single test, mostly due to slight disagreement
+        custom_tolerances = {'ksone': 1e-5, 'kstwo': 1e-5}  # discontinuous PDF
+        skip_entropy = {'kstwobign', 'pearson3'}  # tolerance issue
+        skip_skewness = {'exponpow', 'ksone'}  # tolerance issue
+        skip_kurtosis = {'chi', 'exponpow', 'invgamma',  # tolerance issue
+                         'johnsonsb', 'ksone', 'kstwo'}  # tolerance issue
+        skip_logccdf = {'arcsine', 'skewcauchy', 'trapezoid', 'triang'}  # tolerance
+        skip_raw = {2: {'alpha', 'foldcauchy', 'halfcauchy', 'levy', 'levy_l'},
+                    3: {'pareto'},  # stats.pareto is just wrong
+                    4: {'invgamma'}}  # tolerance issue
+        skip_standardized = {'exponpow', 'ksone'}  # tolerances
+
+        dist = getattr(stats, distname)
+        params = dict(zip(dist.shapes.split(', '), distdata[1])) if dist.shapes else {}
+        rng = np.random.default_rng(7548723590230982)
+        CustomDistribution = stats.make_distribution(dist)
+        X = CustomDistribution(**params)
+        Y = dist(**params)
+        x = X.sample(shape=10, rng=rng)
+        p = X.cdf(x)
+        rtol = custom_tolerances.get(distname, 1e-7)
+        atol = 1e-12
+
+        with np.errstate(divide='ignore', invalid='ignore'):
+            m, v, s, k = Y.stats('mvsk')
+            assert_allclose(X.support(), Y.support())
+            if distname not in skip_entropy:
+                assert_allclose(X.entropy(), Y.entropy(), rtol=rtol)
+            assert_allclose(X.median(), Y.median(), rtol=rtol)
+            assert_allclose(X.mean(), m, rtol=rtol, atol=atol)
+            assert_allclose(X.variance(), v, rtol=rtol, atol=atol)
+            if distname not in skip_skewness:
+                assert_allclose(X.skewness(), s, rtol=rtol, atol=atol)
+            if distname not in skip_kurtosis:
+                assert_allclose(X.kurtosis(convention='excess'), k,
+                                rtol=rtol, atol=atol)
+            assert_allclose(X.logpdf(x), Y.logpdf(x), rtol=rtol)
+            assert_allclose(X.pdf(x), Y.pdf(x), rtol=rtol)
+            assert_allclose(X.logcdf(x), Y.logcdf(x), rtol=rtol)
+            assert_allclose(X.cdf(x), Y.cdf(x), rtol=rtol)
+            if distname not in skip_logccdf:
+                assert_allclose(X.logccdf(x), Y.logsf(x), rtol=rtol)
+            assert_allclose(X.ccdf(x), Y.sf(x), rtol=rtol)
+            assert_allclose(X.icdf(p), Y.ppf(p), rtol=rtol)
+            assert_allclose(X.iccdf(p), Y.isf(p), rtol=rtol)
+            for order in range(5):
+                if distname not in skip_raw.get(order, {}):
+                    assert_allclose(X.moment(order, kind='raw'),
+                                    Y.moment(order), rtol=rtol, atol=atol)
+            for order in range(3, 4):
+                if distname not in skip_standardized:
+                    assert_allclose(X.moment(order, kind='standardized'),
+                                    Y.stats('mvsk'[order-1]), rtol=rtol, atol=atol)
+            seed = 845298245687345
+            assert_allclose(X.sample(shape=10, rng=seed),
+                            Y.rvs(size=10, random_state=np.random.default_rng(seed)),
+                            rtol=rtol)
+
+    def test_input_validation(self):
+        message = '`levy_stable` is not supported.'
+        with pytest.raises(NotImplementedError, match=message):
+            stats.make_distribution(stats.levy_stable)
+
+        message = '`vonmises` is not supported.'
+        with pytest.raises(NotImplementedError, match=message):
+            stats.make_distribution(stats.vonmises)
+
+        message = "The argument must be an instance of `rv_continuous`."
+        with pytest.raises(ValueError, match=message):
+            stats.make_distribution(object())
+
+    def test_repr_str_docs(self):
+        from scipy.stats._distribution_infrastructure import _distribution_names
+        for dist in _distribution_names.keys():
+            assert hasattr(stats, dist)
+
+        dist = stats.make_distribution(stats.gamma)
+        assert str(dist(a=2)) == "Gamma(a=2.0)"
+        if np.__version__ >= "2":
+            assert repr(dist(a=2)) == "Gamma(a=np.float64(2.0))"
+        assert 'Gamma' in dist.__doc__
+
+        dist = stats.make_distribution(stats.halfgennorm)
+        assert str(dist(beta=2)) == "HalfGeneralizedNormal(beta=2.0)"
+        if np.__version__ >= "2":
+            assert repr(dist(beta=2)) == "HalfGeneralizedNormal(beta=np.float64(2.0))"
+        assert 'HalfGeneralizedNormal' in dist.__doc__
+
+
+class TestTransforms:
+
+    # putting this at the top to hopefully avoid merge conflicts
+    def test_truncate(self):
+        rng = np.random.default_rng(81345982345826)
+        lb = rng.random((3, 1))
+        ub = rng.random((3, 1))
+        lb, ub = np.minimum(lb, ub), np.maximum(lb, ub)
+
+        Y = stats.truncate(Normal(), lb=lb, ub=ub)
+        Y0 = stats.truncnorm(lb, ub)
+
+        y = Y0.rvs((3, 10), random_state=rng)
+        p = Y0.cdf(y)
+
+        assert_allclose(Y.logentropy(), np.log(Y0.entropy() + 0j))
+        assert_allclose(Y.entropy(), Y0.entropy())
+        assert_allclose(Y.median(), Y0.ppf(0.5))
+        assert_allclose(Y.mean(), Y0.mean())
+        assert_allclose(Y.variance(), Y0.var())
+        assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
+        assert_allclose(Y.skewness(), Y0.stats('s'))
+        assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
+        assert_allclose(Y.support(), Y0.support())
+        assert_allclose(Y.pdf(y), Y0.pdf(y))
+        assert_allclose(Y.cdf(y), Y0.cdf(y))
+        assert_allclose(Y.ccdf(y), Y0.sf(y))
+        assert_allclose(Y.icdf(p), Y0.ppf(p))
+        assert_allclose(Y.iccdf(p), Y0.isf(p))
+        assert_allclose(Y.logpdf(y), Y0.logpdf(y))
+        assert_allclose(Y.logcdf(y), Y0.logcdf(y))
+        assert_allclose(Y.logccdf(y), Y0.logsf(y))
+        assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
+        assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
+        sample = Y.sample(10)
+        assert np.all((sample > lb) & (sample < ub))
+
+    @pytest.mark.fail_slow(10)
+    @given(data=strategies.data(), seed=strategies.integers(min_value=0))
+    def test_loc_scale(self, data, seed):
+        # Need tests with negative scale
+        rng = np.random.default_rng(seed)
+
+        class TransformedNormal(ShiftedScaledDistribution):
+            def __init__(self, *args, **kwargs):
+                super().__init__(StandardNormal(), *args, **kwargs)
+
+        tmp = draw_distribution_from_family(
+            TransformedNormal, data, rng, proportions=(1, 0, 0, 0), min_side=1)
+        dist, x, y, p, logp, result_shape, x_result_shape, xy_result_shape = tmp
+
+        loc = dist.loc
+        scale = dist.scale
+        dist0 = StandardNormal()
+        dist_ref = stats.norm(loc=loc, scale=scale)
+
+        x0 = (x - loc) / scale
+        y0 = (y - loc) / scale
+
+        a, b = dist.support()
+        a0, b0 = dist0.support()
+        assert_allclose(a, a0 + loc)
+        assert_allclose(b, b0 + loc)
+
+        with np.errstate(invalid='ignore', divide='ignore'):
+            assert_allclose(np.exp(dist.logentropy()), dist.entropy())
+            assert_allclose(dist.entropy(), dist_ref.entropy())
+            assert_allclose(dist.median(), dist0.median() + loc)
+            assert_allclose(dist.mode(), dist0.mode() + loc)
+            assert_allclose(dist.mean(), dist0.mean() + loc)
+            assert_allclose(dist.variance(), dist0.variance() * scale**2)
+            assert_allclose(dist.standard_deviation(), dist.variance()**0.5)
+            assert_allclose(dist.skewness(), dist0.skewness() * np.sign(scale))
+            assert_allclose(dist.kurtosis(), dist0.kurtosis())
+            assert_allclose(dist.logpdf(x), dist0.logpdf(x0) - np.log(scale))
+            assert_allclose(dist.pdf(x), dist0.pdf(x0) / scale)
+            assert_allclose(dist.logcdf(x), dist0.logcdf(x0))
+            assert_allclose(dist.cdf(x), dist0.cdf(x0))
+            assert_allclose(dist.logccdf(x), dist0.logccdf(x0))
+            assert_allclose(dist.ccdf(x), dist0.ccdf(x0))
+            assert_allclose(dist.logcdf(x, y), dist0.logcdf(x0, y0))
+            assert_allclose(dist.cdf(x, y), dist0.cdf(x0, y0))
+            assert_allclose(dist.logccdf(x, y), dist0.logccdf(x0, y0))
+            assert_allclose(dist.ccdf(x, y), dist0.ccdf(x0, y0))
+            assert_allclose(dist.ilogcdf(logp), dist0.ilogcdf(logp)*scale + loc)
+            assert_allclose(dist.icdf(p), dist0.icdf(p)*scale + loc)
+            assert_allclose(dist.ilogccdf(logp), dist0.ilogccdf(logp)*scale + loc)
+            assert_allclose(dist.iccdf(p), dist0.iccdf(p)*scale + loc)
+            for i in range(1, 5):
+                assert_allclose(dist.moment(i, 'raw'), dist_ref.moment(i))
+                assert_allclose(dist.moment(i, 'central'),
+                                dist0.moment(i, 'central') * scale**i)
+                assert_allclose(dist.moment(i, 'standardized'),
+                                dist0.moment(i, 'standardized') * np.sign(scale)**i)
+
+        # Transform back to the original distribution using all arithmetic
+        # operations; check that it behaves as expected.
+        dist = (dist - 2*loc) + loc
+        dist = dist/scale**2 * scale
+        z = np.zeros(dist._shape)  # compact broadcasting
+
+        a, b = dist.support()
+        a0, b0 = dist0.support()
+        assert_allclose(a, a0 + z)
+        assert_allclose(b, b0 + z)
+
+        with np.errstate(invalid='ignore', divide='ignore'):
+            assert_allclose(dist.logentropy(), dist0.logentropy() + z)
+            assert_allclose(dist.entropy(), dist0.entropy() + z)
+            assert_allclose(dist.median(), dist0.median() + z)
+            assert_allclose(dist.mode(), dist0.mode() + z)
+            assert_allclose(dist.mean(), dist0.mean() + z)
+            assert_allclose(dist.variance(), dist0.variance() + z)
+            assert_allclose(dist.standard_deviation(), dist0.standard_deviation() + z)
+            assert_allclose(dist.skewness(), dist0.skewness() + z)
+            assert_allclose(dist.kurtosis(), dist0.kurtosis() + z)
+            assert_allclose(dist.logpdf(x), dist0.logpdf(x)+z)
+            assert_allclose(dist.pdf(x), dist0.pdf(x) + z)
+            assert_allclose(dist.logcdf(x), dist0.logcdf(x) + z)
+            assert_allclose(dist.cdf(x), dist0.cdf(x) + z)
+            assert_allclose(dist.logccdf(x), dist0.logccdf(x) + z)
+            assert_allclose(dist.ccdf(x), dist0.ccdf(x) + z)
+            assert_allclose(dist.ilogcdf(logp), dist0.ilogcdf(logp) + z)
+            assert_allclose(dist.icdf(p), dist0.icdf(p) + z)
+            assert_allclose(dist.ilogccdf(logp), dist0.ilogccdf(logp) + z)
+            assert_allclose(dist.iccdf(p), dist0.iccdf(p) + z)
+            for i in range(1, 5):
+                assert_allclose(dist.moment(i, 'raw'), dist0.moment(i, 'raw'))
+                assert_allclose(dist.moment(i, 'central'), dist0.moment(i, 'central'))
+                assert_allclose(dist.moment(i, 'standardized'),
+                                dist0.moment(i, 'standardized'))
+
+            # These are tough to compare because of the way the shape works
+            # rng = np.random.default_rng(seed)
+            # rng0 = np.random.default_rng(seed)
+            # assert_allclose(dist.sample(x_result_shape, rng=rng),
+            #                 dist0.sample(x_result_shape, rng=rng0) * scale + loc)
+            # Should also try to test fit, plot?
+
+    @pytest.mark.fail_slow(5)
+    @pytest.mark.parametrize('exp_pow', ['exp', 'pow'])
+    def test_exp_pow(self, exp_pow):
+        rng = np.random.default_rng(81345982345826)
+        mu = rng.random((3, 1))
+        sigma = rng.random((3, 1))
+
+        X = Normal()*sigma + mu
+        if exp_pow == 'exp':
+            Y = stats.exp(X)
+        else:
+            Y = np.e ** X
+        Y0 = stats.lognorm(sigma, scale=np.exp(mu))
+
+        y = Y0.rvs((3, 10), random_state=rng)
+        p = Y0.cdf(y)
+
+        assert_allclose(Y.logentropy(), np.log(Y0.entropy()))
+        assert_allclose(Y.entropy(), Y0.entropy())
+        assert_allclose(Y.median(), Y0.ppf(0.5))
+        assert_allclose(Y.mean(), Y0.mean())
+        assert_allclose(Y.variance(), Y0.var())
+        assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
+        assert_allclose(Y.skewness(), Y0.stats('s'))
+        assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
+        assert_allclose(Y.support(), Y0.support())
+        assert_allclose(Y.pdf(y), Y0.pdf(y))
+        assert_allclose(Y.cdf(y), Y0.cdf(y))
+        assert_allclose(Y.ccdf(y), Y0.sf(y))
+        assert_allclose(Y.icdf(p), Y0.ppf(p))
+        assert_allclose(Y.iccdf(p), Y0.isf(p))
+        assert_allclose(Y.logpdf(y), Y0.logpdf(y))
+        assert_allclose(Y.logcdf(y), Y0.logcdf(y))
+        assert_allclose(Y.logccdf(y), Y0.logsf(y))
+        assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
+        assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
+        seed = 3984593485
+        assert_allclose(Y.sample(rng=seed), np.exp(X.sample(rng=seed)))
+
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.parametrize('scale', [1, 2, -1])
+    @pytest.mark.xfail_on_32bit("`scale=-1` fails on 32-bit; needs investigation")
+    def test_reciprocal(self, scale):
+        rng = np.random.default_rng(81345982345826)
+        a = rng.random((3, 1))
+
+        # Separate sign from scale. It's easy to scale the resulting
+        # RV with negative scale; we want to test the ability to divide
+        # by a RV with negative support
+        sign, scale = np.sign(scale), abs(scale)
+
+        # Reference distribution
+        InvGamma = stats.make_distribution(stats.invgamma)
+        Y0 = sign * scale * InvGamma(a=a)
+
+        # Test distribution
+        X = _Gamma(a=a) if sign > 0 else -_Gamma(a=a)
+        Y = scale / X
+
+        y = Y0.sample(shape=(3, 10), rng=rng)
+        p = Y0.cdf(y)
+        logp = np.log(p)
+
+        assert_allclose(Y.logentropy(), np.log(Y0.entropy()))
+        assert_allclose(Y.entropy(), Y0.entropy())
+        assert_allclose(Y.median(), Y0.median())
+        # moments are not finite
+        assert_allclose(Y.support(), Y0.support())
+        assert_allclose(Y.pdf(y), Y0.pdf(y))
+        assert_allclose(Y.cdf(y), Y0.cdf(y))
+        assert_allclose(Y.ccdf(y), Y0.ccdf(y))
+        assert_allclose(Y.icdf(p), Y0.icdf(p))
+        assert_allclose(Y.iccdf(p), Y0.iccdf(p))
+        assert_allclose(Y.logpdf(y), Y0.logpdf(y))
+        assert_allclose(Y.logcdf(y), Y0.logcdf(y))
+        assert_allclose(Y.logccdf(y), Y0.logccdf(y))
+        with np.errstate(divide='ignore', invalid='ignore'):
+            assert_allclose(Y.ilogcdf(logp), Y0.ilogcdf(logp))
+            assert_allclose(Y.ilogccdf(logp), Y0.ilogccdf(logp))
+        seed = 3984593485
+        assert_allclose(Y.sample(rng=seed), scale/(X.sample(rng=seed)))
+
+    @pytest.mark.fail_slow(5)
+    def test_log(self):
+        rng = np.random.default_rng(81345982345826)
+        a = rng.random((3, 1))
+
+        X = _Gamma(a=a)
+        Y0 = stats.loggamma(a)
+        Y = stats.log(X)
+        y = Y0.rvs((3, 10), random_state=rng)
+        p = Y0.cdf(y)
+
+        assert_allclose(Y.logentropy(), np.log(Y0.entropy()))
+        assert_allclose(Y.entropy(), Y0.entropy())
+        assert_allclose(Y.median(), Y0.ppf(0.5))
+        assert_allclose(Y.mean(), Y0.mean())
+        assert_allclose(Y.variance(), Y0.var())
+        assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
+        assert_allclose(Y.skewness(), Y0.stats('s'))
+        assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
+        assert_allclose(Y.support(), Y0.support())
+        assert_allclose(Y.pdf(y), Y0.pdf(y))
+        assert_allclose(Y.cdf(y), Y0.cdf(y))
+        assert_allclose(Y.ccdf(y), Y0.sf(y))
+        assert_allclose(Y.icdf(p), Y0.ppf(p))
+        assert_allclose(Y.iccdf(p), Y0.isf(p))
+        assert_allclose(Y.logpdf(y), Y0.logpdf(y))
+        assert_allclose(Y.logcdf(y), Y0.logcdf(y))
+        assert_allclose(Y.logccdf(y), Y0.logsf(y))
+        with np.errstate(invalid='ignore'):
+            assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
+            assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
+        seed = 3984593485
+        assert_allclose(Y.sample(rng=seed), np.log(X.sample(rng=seed)))
+
+    def test_monotonic_transforms(self):
+        # Some tests of monotonic transforms that are better to be grouped or
+        # don't fit well above
+
+        X = Uniform(a=1, b=2)
+        X_str = "Uniform(a=1.0, b=2.0)"
+
+        assert str(stats.log(X)) == f"log({X_str})"
+        assert str(1 / X) == f"1/({X_str})"
+        assert str(stats.exp(X)) == f"exp({X_str})"
+
+        X = Uniform(a=-1, b=2)
+        message = "Division by a random variable is only implemented when the..."
+        with pytest.raises(NotImplementedError, match=message):
+            1 / X
+        message = "The logarithm of a random variable is only implemented when the..."
+        with pytest.raises(NotImplementedError, match=message):
+            stats.log(X)
+        message = "Raising an argument to the power of a random variable is only..."
+        with pytest.raises(NotImplementedError, match=message):
+            (-2) ** X
+        with pytest.raises(NotImplementedError, match=message):
+            1 ** X
+        with pytest.raises(NotImplementedError, match=message):
+            [0.5, 1.5] ** X
+
+        message = "Raising a random variable to the power of an argument is only"
+        with pytest.raises(NotImplementedError, match=message):
+            X ** (-2)
+        with pytest.raises(NotImplementedError, match=message):
+            X ** 0
+        with pytest.raises(NotImplementedError, match=message):
+            X ** [0.5, 1.5]
+
+    def test_arithmetic_operators(self):
+        rng = np.random.default_rng(2348923495832349834)
+
+        a, b, loc, scale = 0.294, 1.34, 0.57, 1.16
+
+        x = rng.uniform(-3, 3, 100)
+        Y = _LogUniform(a=a, b=b)
+
+        X = scale*Y + loc
+        assert_allclose(X.cdf(x), Y.cdf((x - loc) / scale))
+        X = loc + Y*scale
+        assert_allclose(X.cdf(x), Y.cdf((x - loc) / scale))
+
+        X = Y/scale - loc
+        assert_allclose(X.cdf(x), Y.cdf((x + loc) * scale))
+        X = loc -_LogUniform(a=a, b=b)/scale
+        assert_allclose(X.cdf(x), Y.ccdf((-x + loc)*scale))
+
+    def test_abs(self):
+        rng = np.random.default_rng(81345982345826)
+        loc = rng.random((3, 1))
+
+        Y = stats.abs(Normal() + loc)
+        Y0 = stats.foldnorm(loc)
+
+        y = Y0.rvs((3, 10), random_state=rng)
+        p = Y0.cdf(y)
+
+        assert_allclose(Y.logentropy(), np.log(Y0.entropy() + 0j))
+        assert_allclose(Y.entropy(), Y0.entropy())
+        assert_allclose(Y.median(), Y0.ppf(0.5))
+        assert_allclose(Y.mean(), Y0.mean())
+        assert_allclose(Y.variance(), Y0.var())
+        assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
+        assert_allclose(Y.skewness(), Y0.stats('s'))
+        assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
+        assert_allclose(Y.support(), Y0.support())
+        assert_allclose(Y.pdf(y), Y0.pdf(y))
+        assert_allclose(Y.cdf(y), Y0.cdf(y))
+        assert_allclose(Y.ccdf(y), Y0.sf(y))
+        assert_allclose(Y.icdf(p), Y0.ppf(p))
+        assert_allclose(Y.iccdf(p), Y0.isf(p))
+        assert_allclose(Y.logpdf(y), Y0.logpdf(y))
+        assert_allclose(Y.logcdf(y), Y0.logcdf(y))
+        assert_allclose(Y.logccdf(y), Y0.logsf(y))
+        assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
+        assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
+        sample = Y.sample(10)
+        assert np.all(sample > 0)
+
+    def test_abs_finite_support(self):
+        # The original implementation of `FoldedDistribution` might evaluate
+        # the private distribution methods outside the support. Check that this
+        # is resolved.
+        Weibull = stats.make_distribution(stats.weibull_min)
+        X = Weibull(c=2)
+        Y = abs(-X)
+        assert_equal(X.logpdf(1), Y.logpdf(1))
+        assert_equal(X.pdf(1), Y.pdf(1))
+        assert_equal(X.logcdf(1), Y.logcdf(1))
+        assert_equal(X.cdf(1), Y.cdf(1))
+        assert_equal(X.logccdf(1), Y.logccdf(1))
+        assert_equal(X.ccdf(1), Y.ccdf(1))
+
+    def test_pow(self):
+        rng = np.random.default_rng(81345982345826)
+
+        Y = Normal()**2
+        Y0 = stats.chi2(df=1)
+
+        y = Y0.rvs(10, random_state=rng)
+        p = Y0.cdf(y)
+
+        assert_allclose(Y.logentropy(), np.log(Y0.entropy() + 0j), rtol=1e-6)
+        assert_allclose(Y.entropy(), Y0.entropy(), rtol=1e-6)
+        assert_allclose(Y.median(), Y0.median())
+        assert_allclose(Y.mean(), Y0.mean())
+        assert_allclose(Y.variance(), Y0.var())
+        assert_allclose(Y.standard_deviation(), np.sqrt(Y0.var()))
+        assert_allclose(Y.skewness(), Y0.stats('s'))
+        assert_allclose(Y.kurtosis(), Y0.stats('k') + 3)
+        assert_allclose(Y.support(), Y0.support())
+        assert_allclose(Y.pdf(y), Y0.pdf(y))
+        assert_allclose(Y.cdf(y), Y0.cdf(y))
+        assert_allclose(Y.ccdf(y), Y0.sf(y))
+        assert_allclose(Y.icdf(p), Y0.ppf(p))
+        assert_allclose(Y.iccdf(p), Y0.isf(p))
+        assert_allclose(Y.logpdf(y), Y0.logpdf(y))
+        assert_allclose(Y.logcdf(y), Y0.logcdf(y))
+        assert_allclose(Y.logccdf(y), Y0.logsf(y))
+        assert_allclose(Y.ilogcdf(np.log(p)), Y0.ppf(p))
+        assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
+        sample = Y.sample(10)
+        assert np.all(sample > 0)
+
+class TestOrderStatistic:
+    @pytest.mark.fail_slow(20)  # Moments require integration
+    def test_order_statistic(self):
+        rng = np.random.default_rng(7546349802439582)
+        X = Uniform(a=0, b=1)
+        n = 5
+        r = np.asarray([[1], [3], [5]])
+        Y = stats.order_statistic(X, n=n, r=r)
+        Y0 = stats.beta(r, n + 1 - r)
+
+        y = Y0.rvs((3, 10), random_state=rng)
+        p = Y0.cdf(y)
+
+        # log methods need some attention before merge
+        assert_allclose(np.exp(Y.logentropy()), Y0.entropy())
+        assert_allclose(Y.entropy(), Y0.entropy())
+        assert_allclose(Y.mean(), Y0.mean())
+        assert_allclose(Y.variance(), Y0.var())
+        assert_allclose(Y.skewness(), Y0.stats('s'), atol=1e-15)
+        assert_allclose(Y.kurtosis(), Y0.stats('k') + 3, atol=1e-15)
+        assert_allclose(Y.median(), Y0.ppf(0.5))
+        assert_allclose(Y.support(), Y0.support())
+        assert_allclose(Y.pdf(y), Y0.pdf(y))
+        assert_allclose(Y.cdf(y, method='formula'), Y.cdf(y, method='quadrature'))
+        assert_allclose(Y.ccdf(y, method='formula'), Y.ccdf(y, method='quadrature'))
+        assert_allclose(Y.icdf(p, method='formula'), Y.icdf(p, method='inversion'))
+        assert_allclose(Y.iccdf(p, method='formula'), Y.iccdf(p, method='inversion'))
+        assert_allclose(Y.logpdf(y), Y0.logpdf(y))
+        assert_allclose(Y.logcdf(y), Y0.logcdf(y))
+        assert_allclose(Y.logccdf(y), Y0.logsf(y))
+        with np.errstate(invalid='ignore', divide='ignore'):
+            assert_allclose(Y.ilogcdf(np.log(p),), Y0.ppf(p))
+            assert_allclose(Y.ilogccdf(np.log(p)), Y0.isf(p))
+
+        message = "`r` and `n` must contain only positive integers."
+        with pytest.raises(ValueError, match=message):
+            stats.order_statistic(X, n=n, r=-1)
+        with pytest.raises(ValueError, match=message):
+            stats.order_statistic(X, n=-1, r=r)
+        with pytest.raises(ValueError, match=message):
+            stats.order_statistic(X, n=n, r=1.5)
+        with pytest.raises(ValueError, match=message):
+            stats.order_statistic(X, n=1.5, r=r)
+
+    def test_support_gh22037(self):
+        # During review of gh-22037, it was noted that the `support` of
+        # an `OrderStatisticDistribution` returned incorrect results;
+        # this was resolved by overriding `_support`.
+        Uniform = stats.make_distribution(stats.uniform)
+        X = Uniform()
+        Y = X*5 + 2
+        Z = stats.order_statistic(Y, r=3, n=5)
+        assert_allclose(Z.support(), Y.support())
+
+    def test_composition_gh22037(self):
+        # During review of gh-22037, it was noted that an error was
+        # raised when creating an `OrderStatisticDistribution` from
+        # a `TruncatedDistribution`. This was resolved by overriding
+        # `_update_parameters`.
+        Normal = stats.make_distribution(stats.norm)
+        TruncatedNormal = stats.make_distribution(stats.truncnorm)
+        a, b = [-2, -1], 1
+        r, n = 3, [[4], [5]]
+        x = [[[-0.3]], [[0.1]]]
+        X1 = Normal()
+        Y1 = stats.truncate(X1, a, b)
+        Z1 = stats.order_statistic(Y1, r=r, n=n)
+        X2 = TruncatedNormal(a=a, b=b)
+        Z2 = stats.order_statistic(X2, r=r, n=n)
+        np.testing.assert_allclose(Z1.cdf(x), Z2.cdf(x))
+
+
+class TestFullCoverage:
+    # Adds tests just to get to 100% test coverage; this way it's more obvious
+    # if new lines are untested.
+    def test_Domain(self):
+        with pytest.raises(NotImplementedError):
+            _Domain.contains(None, 1.)
+        with pytest.raises(NotImplementedError):
+            _Domain.get_numerical_endpoints(None, 1.)
+        with pytest.raises(NotImplementedError):
+            _Domain.__str__(None)
+
+    def test_Parameter(self):
+        with pytest.raises(NotImplementedError):
+            _Parameter.validate(None, 1.)
+
+    @pytest.mark.parametrize(("dtype_in", "dtype_out"),
+                              [(np.float16, np.float16),
+                               (np.int16, np.float64)])
+    def test_RealParameter_uncommon_dtypes(self, dtype_in, dtype_out):
+        domain = _RealDomain((-1, 1))
+        parameter = _RealParameter('x', domain=domain)
+
+        x = np.asarray([0.5, 2.5], dtype=dtype_in)
+        arr, dtype, valid = parameter.validate(x, parameter_values={})
+        assert_equal(arr, x)
+        assert dtype == dtype_out
+        assert_equal(valid, [True, False])
+
+    def test_ContinuousDistribution_set_invalid_nan(self):
+        # Exercise code paths when formula returns wrong shape and dtype
+        # We could consider making this raise an error to force authors
+        # to return the right shape and dytpe, but this would need to be
+        # configurable.
+        class TestDist(ContinuousDistribution):
+            _variable = _RealParameter('x', domain=_RealDomain(endpoints=(0., 1.)))
+            def _logpdf_formula(self, x, *args, **kwargs):
+                return 0
+
+        X = TestDist()
+        dtype = np.float32
+        X._dtype = dtype
+        x = np.asarray([0.5], dtype=dtype)
+        assert X.logpdf(x).dtype == dtype
+
+    def test_fiinfo(self):
+        assert _fiinfo(np.float64(1.)).max == np.finfo(np.float64).max
+        assert _fiinfo(np.int64(1)).max == np.iinfo(np.int64).max
+
+    def test_generate_domain_support(self):
+        msg = _generate_domain_support(StandardNormal)
+        assert "accepts no distribution parameters" in msg
+
+        msg = _generate_domain_support(Normal)
+        assert "accepts one parameterization" in msg
+
+        msg = _generate_domain_support(_LogUniform)
+        assert "accepts two parameterizations" in msg
+
+    def test_ContinuousDistribution__repr__(self):
+        X = Uniform(a=0, b=1)
+        if np.__version__ < "2":
+            assert repr(X) == "Uniform(a=0.0, b=1.0)"
+        else:
+            assert repr(X) == "Uniform(a=np.float64(0.0), b=np.float64(1.0))"
+        if np.__version__ < "2":
+            assert repr(X*3 + 2) == "3.0*Uniform(a=0.0, b=1.0) + 2.0"
+        else:
+            assert repr(X*3 + 2) == (
+                "np.float64(3.0)*Uniform(a=np.float64(0.0), b=np.float64(1.0))"
+                " + np.float64(2.0)"
+            )
+
+        X = Uniform(a=np.zeros(4), b=1)
+        assert repr(X) == "Uniform(a=array([0., 0., 0., 0.]), b=1)"
+
+        X = Uniform(a=np.zeros(4, dtype=np.float32), b=np.ones(4, dtype=np.float32))
+        assert repr(X) == (
+            "Uniform(a=array([0., 0., 0., 0.], dtype=float32),"
+            " b=array([1., 1., 1., 1.], dtype=float32))"
+        )
+
+
+class TestReprs:
+    U = Uniform(a=0, b=1)
+    V = Uniform(a=np.float32(0.0), b=np.float32(1.0))
+    X = Normal(mu=-1, sigma=1)
+    Y = Normal(mu=1, sigma=1)
+    Z = Normal(mu=np.zeros(1000), sigma=1)
+
+    @pytest.mark.parametrize(
+        "dist",
+        [
+            U,
+            U - np.array([1.0, 2.0]),
+            pytest.param(
+                V,
+                marks=pytest.mark.skipif(
+                    np.__version__ < "2",
+                    reason="numpy 1.x didn't have dtype in repr",
+                )
+            ),
+            pytest.param(
+                np.ones(2, dtype=np.float32)*V + np.zeros(2, dtype=np.float64),
+                marks=pytest.mark.skipif(
+                    np.__version__ < "2",
+                    reason="numpy 1.x didn't have dtype in repr",
+                )
+            ),
+            3*U + 2,
+            U**4,
+            (3*U + 2)**4,
+            (3*U + 2)**3,
+            2**U,
+            2**(3*U + 1),
+            1 / (1 + U),
+            stats.order_statistic(U, r=3, n=5),
+            stats.truncate(U, 0.2, 0.8),
+            stats.Mixture([X, Y], weights=[0.3, 0.7]),
+            abs(U),
+            stats.exp(U),
+            stats.log(1 + U),
+            np.array([1.0, 2.0])*U + np.array([2.0, 3.0]),
+        ]
+    )
+    def test_executable(self, dist):
+        # Test that reprs actually evaluate to proper distribution
+        # provided relevant imports are made.
+        from numpy import array  # noqa: F401
+        from numpy import float32  # noqa: F401
+        from scipy.stats import abs, exp, log, order_statistic, truncate # noqa: F401
+        from scipy.stats import Mixture, Normal # noqa: F401
+        from scipy.stats._new_distributions import Uniform # noqa: F401
+        new_dist = eval(repr(dist))
+        # A basic check that the distributions are the same
+        sample1 = dist.sample(shape=10, rng=1234)
+        sample2 = new_dist.sample(shape=10, rng=1234)
+        assert_equal(sample1, sample2)
+        assert sample1.dtype is sample2.dtype
+
+    @pytest.mark.parametrize(
+        "dist",
+        [
+            Z,
+            np.full(1000, 2.0) * X + 1.0,
+            2.0 * X + np.full(1000, 1.0),
+            np.full(1000, 2.0) * X + 1.0,
+            stats.truncate(Z, -1, 1),
+            stats.truncate(Z, -np.ones(1000), np.ones(1000)),
+            stats.order_statistic(X, r=np.arange(1, 1000), n=1000),
+            Z**2,
+            1.0 / (1 + stats.exp(Z)),
+            2**Z,
+        ]
+    )
+    def test_not_too_long(self, dist):
+        # Tests that array summarization is working to ensure reprs aren't too long.
+        # None of the reprs above will be executable.
+        assert len(repr(dist)) < 250
+
+
+class MixedDist(ContinuousDistribution):
+    _variable = _RealParameter('x', domain=_RealDomain(endpoints=(-np.inf, np.inf)))
+    def _pdf_formula(self, x, *args, **kwargs):
+        return (0.4 * 1/(1.1 * np.sqrt(2*np.pi)) * np.exp(-0.5*((x+0.25)/1.1)**2)
+                + 0.6 * 1/(0.9 * np.sqrt(2*np.pi)) * np.exp(-0.5*((x-0.5)/0.9)**2))
+
+
+class TestMixture:
+    def test_input_validation(self):
+        message = "`components` must contain at least one random variable."
+        with pytest.raises(ValueError, match=message):
+            Mixture([])
+
+        message = "Each element of `components` must be an instance..."
+        with pytest.raises(ValueError, match=message):
+            Mixture((1, 2, 3))
+
+        message = "All elements of `components` must have scalar shapes."
+        with pytest.raises(ValueError, match=message):
+            Mixture([Normal(mu=[1, 2]), Normal()])
+
+        message = "`components` and `weights` must have the same length."
+        with pytest.raises(ValueError, match=message):
+            Mixture([Normal()], weights=[0.5, 0.5])
+
+        message = "`weights` must have floating point dtype."
+        with pytest.raises(ValueError, match=message):
+            Mixture([Normal()], weights=[1])
+
+        message = "`weights` must have floating point dtype."
+        with pytest.raises(ValueError, match=message):
+            Mixture([Normal()], weights=[1])
+
+        message = "`weights` must sum to 1.0."
+        with pytest.raises(ValueError, match=message):
+            Mixture([Normal(), Normal()], weights=[0.5, 1.0])
+
+        message = "All `weights` must be non-negative."
+        with pytest.raises(ValueError, match=message):
+            Mixture([Normal(), Normal()], weights=[1.5, -0.5])
+
+    @pytest.mark.parametrize('shape', [(), (10,)])
+    def test_basic(self, shape):
+        rng = np.random.default_rng(582348972387243524)
+        X = Mixture((Normal(mu=-0.25, sigma=1.1), Normal(mu=0.5, sigma=0.9)),
+                    weights=(0.4, 0.6))
+        Y = MixedDist()
+        x = rng.random(shape)
+
+        def assert_allclose(res, ref, **kwargs):
+            if shape == ():
+                assert np.isscalar(res)
+            np.testing.assert_allclose(res, ref, **kwargs)
+
+        assert_allclose(X.logentropy(), Y.logentropy())
+        assert_allclose(X.entropy(), Y.entropy())
+        assert_allclose(X.mode(), Y.mode())
+        assert_allclose(X.median(), Y.median())
+        assert_allclose(X.mean(), Y.mean())
+        assert_allclose(X.variance(), Y.variance())
+        assert_allclose(X.standard_deviation(), Y.standard_deviation())
+        assert_allclose(X.skewness(), Y.skewness())
+        assert_allclose(X.kurtosis(), Y.kurtosis())
+        assert_allclose(X.logpdf(x), Y.logpdf(x))
+        assert_allclose(X.pdf(x), Y.pdf(x))
+        assert_allclose(X.logcdf(x), Y.logcdf(x))
+        assert_allclose(X.cdf(x), Y.cdf(x))
+        assert_allclose(X.logccdf(x), Y.logccdf(x))
+        assert_allclose(X.ccdf(x), Y.ccdf(x))
+        assert_allclose(X.ilogcdf(x), Y.ilogcdf(x))
+        assert_allclose(X.icdf(x), Y.icdf(x))
+        assert_allclose(X.ilogccdf(x), Y.ilogccdf(x))
+        assert_allclose(X.iccdf(x), Y.iccdf(x))
+        for kind in ['raw', 'central', 'standardized']:
+            for order in range(5):
+                assert_allclose(X.moment(order, kind=kind),
+                                Y.moment(order, kind=kind),
+                                atol=1e-15)
+
+        # weak test of `sample`
+        shape = (10, 20, 5)
+        y = X.sample(shape, rng=rng)
+        assert y.shape == shape
+        assert stats.ks_1samp(y.ravel(), X.cdf).pvalue > 0.05
+
+    def test_default_weights(self):
+        a = 1.1
+        Gamma = stats.make_distribution(stats.gamma)
+        X = Gamma(a=a)
+        Y = stats.Mixture((X, -X))
+        x = np.linspace(-4, 4, 300)
+        assert_allclose(Y.pdf(x), stats.dgamma(a=a).pdf(x))
+
+    def test_properties(self):
+        components = [Normal(mu=-0.25, sigma=1.1), Normal(mu=0.5, sigma=0.9)]
+        weights = (0.4, 0.6)
+        X = Mixture(components, weights=weights)
+
+        # Replacing properties doesn't work
+        # Different version of Python have different messages
+        with pytest.raises(AttributeError):
+            X.components = 10
+        with pytest.raises(AttributeError):
+            X.weights = 10
+
+        # Mutation doesn't work
+        X.components[0] = components[1]
+        assert X.components[0] == components[0]
+        X.weights[0] = weights[1]
+        assert X.weights[0] == weights[0]
+
+    def test_inverse(self):
+        # Originally, inverse relied on the mean to start the bracket search.
+        # This didn't work for distributions with non-finite mean. Check that
+        # this is resolved.
+        rng = np.random.default_rng(24358934657854237863456)
+        Cauchy = stats.make_distribution(stats.cauchy)
+        X0 = Cauchy()
+        X = stats.Mixture([X0, X0])
+        p = rng.random(size=10)
+        np.testing.assert_allclose(X.icdf(p), X0.icdf(p))
+        np.testing.assert_allclose(X.iccdf(p), X0.iccdf(p))
+        np.testing.assert_allclose(X.ilogcdf(p), X0.ilogcdf(p))
+        np.testing.assert_allclose(X.ilogccdf(p), X0.ilogccdf(p))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb3fc6007b1f53e96ea4e8c3d6ad37c065850804
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_basic.py
@@ -0,0 +1,1047 @@
+import sys
+import numpy as np
+import numpy.testing as npt
+import pytest
+from pytest import raises as assert_raises
+from scipy.integrate import IntegrationWarning
+import itertools
+
+from scipy import stats
+from .common_tests import (check_normalization, check_moment,
+                           check_mean_expect,
+                           check_var_expect, check_skew_expect,
+                           check_kurt_expect, check_entropy,
+                           check_private_entropy, check_entropy_vect_scale,
+                           check_edge_support, check_named_args,
+                           check_random_state_property,
+                           check_meth_dtype, check_ppf_dtype,
+                           check_cmplx_deriv,
+                           check_pickling, check_rvs_broadcast,
+                           check_freezing, check_munp_expect,)
+from scipy.stats._distr_params import distcont
+from scipy.stats._distn_infrastructure import rv_continuous_frozen
+
+"""
+Test all continuous distributions.
+
+Parameters were chosen for those distributions that pass the
+Kolmogorov-Smirnov test.  This provides safe parameters for each
+distributions so that we can perform further testing of class methods.
+
+These tests currently check only/mostly for serious errors and exceptions,
+not for numerically exact results.
+"""
+
+# Note that you need to add new distributions you want tested
+# to _distr_params
+
+DECIMAL = 5  # specify the precision of the tests  # increased from 0 to 5
+_IS_32BIT = (sys.maxsize < 2**32)
+
+# Sets of tests to skip.
+# Entries sorted by speed (very slow to slow).
+# xslow took > 1s; slow took > 0.5s
+
+xslow_test_cont_basic = {'studentized_range', 'kstwo', 'ksone', 'vonmises', 'kappa4',
+                         'recipinvgauss', 'vonmises_line', 'gausshyper',
+                         'rel_breitwigner', 'norminvgauss'}
+slow_test_cont_basic = {'crystalball', 'powerlognorm', 'pearson3'}
+
+# test_moments is already marked slow
+xslow_test_moments = {'studentized_range', 'ksone', 'vonmises', 'vonmises_line',
+                      'recipinvgauss', 'kstwo', 'kappa4'}
+
+slow_fit_mle = {'exponweib', 'genexpon', 'genhyperbolic', 'johnsonsb',
+                'kappa4', 'powerlognorm', 'tukeylambda'}
+xslow_fit_mle = {'gausshyper', 'ncf', 'ncx2', 'recipinvgauss', 'vonmises_line'}
+xfail_fit_mle = {'ksone', 'kstwo', 'trapezoid', 'truncpareto', 'irwinhall'}
+skip_fit_mle = {'levy_stable', 'studentized_range'}  # far too slow (>10min)
+slow_fit_mm = {'chi2', 'expon', 'lognorm', 'loguniform', 'powerlaw', 'reciprocal'}
+xslow_fit_mm = {'argus', 'beta', 'exponpow', 'gausshyper', 'gengamma',
+                'genhalflogistic', 'geninvgauss', 'gompertz', 'halfgennorm',
+                'johnsonsb', 'kstwobign', 'ncx2', 'norminvgauss', 'truncnorm',
+                'truncweibull_min', 'wrapcauchy'}
+xfail_fit_mm = {'alpha', 'betaprime', 'bradford', 'burr', 'burr12', 'cauchy',
+                'crystalball', 'dpareto_lognorm', 'exponweib', 'f', 'fisk',
+                'foldcauchy', 'genextreme', 'genpareto', 'halfcauchy', 'invgamma',
+                'irwinhall', 'jf_skew_t', 'johnsonsu', 'kappa3', 'kappa4', 'landau',
+                'levy', 'levy_l', 'loglaplace', 'lomax', 'mielke', 'ncf', 'nct',
+                'pareto', 'powerlognorm', 'powernorm', 'rel_breitwigner',
+                'skewcauchy', 't', 'trapezoid', 'truncexpon', 'truncpareto',
+                'tukeylambda', 'vonmises', 'vonmises_line'}
+skip_fit_mm = {'genexpon', 'genhyperbolic', 'ksone', 'kstwo', 'levy_stable',
+               'recipinvgauss', 'studentized_range'}  # far too slow (>10min)
+
+# These distributions fail the complex derivative test below.
+# Here 'fail' mean produce wrong results and/or raise exceptions, depending
+# on the implementation details of corresponding special functions.
+# cf https://github.com/scipy/scipy/pull/4979 for a discussion.
+fails_cmplx = {'argus', 'beta', 'betaprime', 'cauchy', 'chi', 'chi2', 'cosine',
+               'dgamma', 'dpareto_lognorm', 'dweibull', 'erlang', 'f', 'foldcauchy',
+               'gamma', 'gausshyper', 'gengamma', 'genhyperbolic',
+               'geninvgauss', 'gennorm', 'genpareto',
+               'halfcauchy', 'halfgennorm', 'invgamma', 'irwinhall', 'jf_skew_t',
+               'ksone', 'kstwo', 'kstwobign', 'landau', 'levy_l', 'loggamma',
+               'logistic', 'loguniform', 'maxwell', 'nakagami',
+               'ncf', 'nct', 'ncx2', 'norminvgauss', 'pearson3',
+               'powerlaw', 'rdist', 'reciprocal', 'rice',
+               'skewnorm', 't', 'truncweibull_min',
+               'tukeylambda', 'vonmises', 'vonmises_line',
+               'rv_histogram_instance', 'truncnorm', 'studentized_range',
+               'johnsonsb', 'halflogistic', 'rel_breitwigner'}
+
+# Slow test_method_with_lists
+slow_with_lists = {'studentized_range'}
+
+
+# rv_histogram instances, with uniform and non-uniform bins;
+# stored as (dist, arg) tuples for cases_test_cont_basic
+# and cases_test_moments.
+histogram_test_instances = []
+case1 = {'a': [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
+               6, 6, 6, 7, 7, 7, 8, 8, 9], 'bins': 8}  # equal width bins
+case2 = {'a': [1, 1], 'bins': [0, 1, 10]}  # unequal width bins
+for case, density in itertools.product([case1, case2], [True, False]):
+    _hist = np.histogram(**case, density=density)
+    _rv_hist = stats.rv_histogram(_hist, density=density)
+    histogram_test_instances.append((_rv_hist, tuple()))
+
+
+def cases_test_cont_basic():
+    for distname, arg in distcont[:] + histogram_test_instances:
+        if distname == 'levy_stable':  # fails; tested separately
+            continue
+        if distname in slow_test_cont_basic:
+            yield pytest.param(distname, arg, marks=pytest.mark.slow)
+        elif distname in xslow_test_cont_basic:
+            yield pytest.param(distname, arg, marks=pytest.mark.xslow)
+        else:
+            yield distname, arg
+
+
+@pytest.mark.parametrize('distname,arg', cases_test_cont_basic())
+@pytest.mark.parametrize('sn', [500])
+def test_cont_basic(distname, arg, sn):
+    try:
+        distfn = getattr(stats, distname)
+    except TypeError:
+        distfn = distname
+        distname = 'rv_histogram_instance'
+
+    rng = np.random.RandomState(765456)
+    rvs = distfn.rvs(size=sn, *arg, random_state=rng)
+    m, v = distfn.stats(*arg)
+
+    if distname not in {'laplace_asymmetric'}:
+        check_sample_meanvar_(m, v, rvs)
+    check_cdf_ppf(distfn, arg, distname)
+    check_sf_isf(distfn, arg, distname)
+    check_cdf_sf(distfn, arg, distname)
+    check_ppf_isf(distfn, arg, distname)
+    check_pdf(distfn, arg, distname)
+    check_pdf_logpdf(distfn, arg, distname)
+    check_pdf_logpdf_at_endpoints(distfn, arg, distname)
+    check_cdf_logcdf(distfn, arg, distname)
+    check_sf_logsf(distfn, arg, distname)
+    check_ppf_broadcast(distfn, arg, distname)
+
+    alpha = 0.01
+    if distname == 'rv_histogram_instance':
+        check_distribution_rvs(distfn.cdf, arg, alpha, rvs)
+    elif distname != 'geninvgauss':
+        # skip kstest for geninvgauss since cdf is too slow; see test for
+        # rv generation in TestGenInvGauss in test_distributions.py
+        check_distribution_rvs(distname, arg, alpha, rvs)
+
+    locscale_defaults = (0, 1)
+    meths = [distfn.pdf, distfn.logpdf, distfn.cdf, distfn.logcdf,
+             distfn.logsf]
+    # make sure arguments are within support
+    spec_x = {'weibull_max': -0.5, 'levy_l': -0.5,
+              'pareto': 1.5, 'truncpareto': 3.2, 'tukeylambda': 0.3,
+              'rv_histogram_instance': 5.0}
+    x = spec_x.get(distname, 0.5)
+    if distname == 'invweibull':
+        arg = (1,)
+    elif distname == 'ksone':
+        arg = (3,)
+
+    check_named_args(distfn, x, arg, locscale_defaults, meths)
+    check_random_state_property(distfn, arg)
+
+    if distname in ['rel_breitwigner'] and _IS_32BIT:
+        # gh18414
+        pytest.skip("fails on Linux 32-bit")
+    else:
+        check_pickling(distfn, arg)
+    check_freezing(distfn, arg)
+
+    # Entropy
+    if distname not in ['kstwobign', 'kstwo', 'ncf']:
+        check_entropy(distfn, arg, distname)
+
+    if distfn.numargs == 0:
+        check_vecentropy(distfn, arg)
+
+    if (distfn.__class__._entropy != stats.rv_continuous._entropy
+            and distname != 'vonmises'):
+        check_private_entropy(distfn, arg, stats.rv_continuous)
+
+    with npt.suppress_warnings() as sup:
+        sup.filter(IntegrationWarning, "The occurrence of roundoff error")
+        sup.filter(IntegrationWarning, "Extremely bad integrand")
+        sup.filter(RuntimeWarning, "invalid value")
+        check_entropy_vect_scale(distfn, arg)
+
+    check_retrieving_support(distfn, arg)
+    check_edge_support(distfn, arg)
+
+    check_meth_dtype(distfn, arg, meths)
+    check_ppf_dtype(distfn, arg)
+
+    if distname not in fails_cmplx:
+        check_cmplx_deriv(distfn, arg)
+
+    if distname != 'truncnorm':
+        check_ppf_private(distfn, arg, distname)
+
+
+def cases_test_cont_basic_fit():
+    slow = pytest.mark.slow
+    xslow = pytest.mark.xslow
+    fail = pytest.mark.skip(reason="Test fails and may be slow.")
+    skip = pytest.mark.skip(reason="Test too slow to run to completion (>10m).")
+
+    for distname, arg in distcont[:] + histogram_test_instances:
+        for method in ["MLE", "MM"]:
+            for fix_args in [True, False]:
+                if method == 'MLE' and distname in slow_fit_mle:
+                    yield pytest.param(distname, arg, method, fix_args, marks=slow)
+                    continue
+                if method == 'MLE' and distname in xslow_fit_mle:
+                    yield pytest.param(distname, arg, method, fix_args, marks=xslow)
+                    continue
+                if method == 'MLE' and distname in xfail_fit_mle:
+                    yield pytest.param(distname, arg, method, fix_args, marks=fail)
+                    continue
+                if method == 'MLE' and distname in skip_fit_mle:
+                    yield pytest.param(distname, arg, method, fix_args, marks=skip)
+                    continue
+                if method == 'MM' and distname in slow_fit_mm:
+                    yield pytest.param(distname, arg, method, fix_args, marks=slow)
+                    continue
+                if method == 'MM' and distname in xslow_fit_mm:
+                    yield pytest.param(distname, arg, method, fix_args, marks=xslow)
+                    continue
+                if method == 'MM' and distname in xfail_fit_mm:
+                    yield pytest.param(distname, arg, method, fix_args, marks=fail)
+                    continue
+                if method == 'MM' and distname in skip_fit_mm:
+                    yield pytest.param(distname, arg, method, fix_args, marks=skip)
+                    continue
+
+                yield distname, arg, method, fix_args
+
+
+def test_cont_basic_fit_cases():
+    # Distribution names should not be in multiple MLE or MM sets
+    assert (len(xslow_fit_mle.union(xfail_fit_mle).union(skip_fit_mle)) ==
+            len(xslow_fit_mle) + len(xfail_fit_mle) + len(skip_fit_mle))
+    assert (len(xslow_fit_mm.union(xfail_fit_mm).union(skip_fit_mm)) ==
+            len(xslow_fit_mm) + len(xfail_fit_mm) + len(skip_fit_mm))
+
+
+@pytest.mark.parametrize('distname, arg, method, fix_args',
+                         cases_test_cont_basic_fit())
+@pytest.mark.parametrize('n_fit_samples', [200])
+def test_cont_basic_fit(distname, arg, n_fit_samples, method, fix_args):
+    try:
+        distfn = getattr(stats, distname)
+    except TypeError:
+        distfn = distname
+
+    rng = np.random.RandomState(765456)
+    rvs = distfn.rvs(size=n_fit_samples, *arg, random_state=rng)
+    if fix_args:
+        check_fit_args_fix(distfn, arg, rvs, method)
+    else:
+        check_fit_args(distfn, arg, rvs, method)
+
+@pytest.mark.parametrize('distname,arg', cases_test_cont_basic())
+def test_rvs_scalar(distname, arg):
+    # rvs should return a scalar when given scalar arguments (gh-12428)
+    try:
+        distfn = getattr(stats, distname)
+    except TypeError:
+        distfn = distname
+        distname = 'rv_histogram_instance'
+
+    assert np.isscalar(distfn.rvs(*arg))
+    assert np.isscalar(distfn.rvs(*arg, size=()))
+    assert np.isscalar(distfn.rvs(*arg, size=None))
+
+
+def test_levy_stable_random_state_property():
+    # levy_stable only implements rvs(), so it is skipped in the
+    # main loop in test_cont_basic(). Here we apply just the test
+    # check_random_state_property to levy_stable.
+    check_random_state_property(stats.levy_stable, (0.5, 0.1))
+
+
+def cases_test_moments():
+    fail_normalization = set()
+    fail_higher = {'ncf'}
+    fail_moment = {'johnsonsu'}  # generic `munp` is inaccurate for johnsonsu
+
+    for distname, arg in distcont[:] + histogram_test_instances:
+        if distname == 'levy_stable':
+            continue
+
+        if distname in xslow_test_moments:
+            yield pytest.param(distname, arg, True, True, True, True,
+                               marks=pytest.mark.xslow(reason="too slow"))
+            continue
+
+        cond1 = distname not in fail_normalization
+        cond2 = distname not in fail_higher
+        cond3 = distname not in fail_moment
+
+        marks = list()
+        # Currently unused, `marks` can be used to add a timeout to a test of
+        # a specific distribution.  For example, this shows how a timeout could
+        # be added for the 'skewnorm' distribution:
+        #
+        #     marks = list()
+        #     if distname == 'skewnorm':
+        #         marks.append(pytest.mark.timeout(300))
+
+        yield pytest.param(distname, arg, cond1, cond2, cond3,
+                           False, marks=marks)
+
+        if not cond1 or not cond2 or not cond3:
+            # Run the distributions that have issues twice, once skipping the
+            # not_ok parts, once with the not_ok parts but marked as knownfail
+            yield pytest.param(distname, arg, True, True, True, True,
+                               marks=[pytest.mark.xfail] + marks)
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize('distname,arg,normalization_ok,higher_ok,moment_ok,'
+                         'is_xfailing',
+                         cases_test_moments())
+def test_moments(distname, arg, normalization_ok, higher_ok, moment_ok,
+                 is_xfailing):
+    try:
+        distfn = getattr(stats, distname)
+    except TypeError:
+        distfn = distname
+        distname = 'rv_histogram_instance'
+
+    with npt.suppress_warnings() as sup:
+        sup.filter(IntegrationWarning,
+                   "The integral is probably divergent, or slowly convergent.")
+        sup.filter(IntegrationWarning,
+                   "The maximum number of subdivisions.")
+        sup.filter(IntegrationWarning,
+                   "The algorithm does not converge.")
+
+        if is_xfailing:
+            sup.filter(IntegrationWarning)
+
+        m, v, s, k = distfn.stats(*arg, moments='mvsk')
+
+        with np.errstate(all="ignore"):
+            if normalization_ok:
+                check_normalization(distfn, arg, distname)
+
+            if higher_ok:
+                check_mean_expect(distfn, arg, m, distname)
+                check_skew_expect(distfn, arg, m, v, s, distname)
+                check_var_expect(distfn, arg, m, v, distname)
+                check_kurt_expect(distfn, arg, m, v, k, distname)
+                check_munp_expect(distfn, arg, distname)
+
+        check_loc_scale(distfn, arg, m, v, distname)
+
+        if moment_ok:
+            check_moment(distfn, arg, m, v, distname)
+
+
+@pytest.mark.parametrize('dist,shape_args', distcont)
+def test_rvs_broadcast(dist, shape_args):
+    if dist in ['gausshyper', 'studentized_range']:
+        pytest.skip("too slow")
+
+    if dist in ['rel_breitwigner'] and _IS_32BIT:
+        # gh18414
+        pytest.skip("fails on Linux 32-bit")
+
+    # If shape_only is True, it means the _rvs method of the
+    # distribution uses more than one random number to generate a random
+    # variate.  That means the result of using rvs with broadcasting or
+    # with a nontrivial size will not necessarily be the same as using the
+    # numpy.vectorize'd version of rvs(), so we can only compare the shapes
+    # of the results, not the values.
+    # Whether or not a distribution is in the following list is an
+    # implementation detail of the distribution, not a requirement.  If
+    # the implementation the rvs() method of a distribution changes, this
+    # test might also have to be changed.
+    shape_only = dist in ['argus', 'betaprime', 'dgamma', 'dpareto_lognorm', 'dweibull',
+                          'exponnorm', 'genhyperbolic', 'geninvgauss', 'landau',
+                          'levy_stable', 'nct', 'norminvgauss', 'rice',
+                          'skewnorm', 'semicircular', 'gennorm', 'loggamma']
+
+    distfunc = getattr(stats, dist)
+    loc = np.zeros(2)
+    scale = np.ones((3, 1))
+    nargs = distfunc.numargs
+    allargs = []
+    bshape = [3, 2]
+    # Generate shape parameter arguments...
+    for k in range(nargs):
+        shp = (k + 4,) + (1,)*(k + 2)
+        allargs.append(shape_args[k]*np.ones(shp))
+        bshape.insert(0, k + 4)
+    allargs.extend([loc, scale])
+    # bshape holds the expected shape when loc, scale, and the shape
+    # parameters are all broadcast together.
+
+    check_rvs_broadcast(distfunc, dist, allargs, bshape, shape_only, 'd')
+
+
+# Expected values of the SF, CDF, PDF were computed using
+# mpmath with mpmath.mp.dps = 50 and output at 20:
+#
+# def ks(x, n):
+#     x = mpmath.mpf(x)
+#     logp = -mpmath.power(6.0*n*x+1.0, 2)/18.0/n
+#     sf, cdf = mpmath.exp(logp), -mpmath.expm1(logp)
+#     pdf = (6.0*n*x+1.0) * 2 * sf/3
+#     print(mpmath.nstr(sf, 20), mpmath.nstr(cdf, 20), mpmath.nstr(pdf, 20))
+#
+# Tests use 1/n < x < 1-1/n and n > 1e6 to use the asymptotic computation.
+# Larger x has a smaller sf.
+@pytest.mark.parametrize('x,n,sf,cdf,pdf,rtol',
+                         [(2.0e-5, 1000000000,
+                           0.44932297307934442379, 0.55067702692065557621,
+                           35946.137394996276407, 5e-15),
+                          (2.0e-9, 1000000000,
+                           0.99999999061111115519, 9.3888888448132728224e-9,
+                           8.6666665852962971765, 5e-14),
+                          (5.0e-4, 1000000000,
+                           7.1222019433090374624e-218, 1.0,
+                           1.4244408634752704094e-211, 5e-14)])
+def test_gh17775_regression(x, n, sf, cdf, pdf, rtol):
+    # Regression test for gh-17775. In scipy 1.9.3 and earlier,
+    # these test would fail.
+    #
+    # KS one asymptotic sf ~ e^(-(6nx+1)^2 / 18n)
+    # Given a large 32-bit integer n, 6n will overflow in the c implementation.
+    # Example of broken behaviour:
+    # ksone.sf(2.0e-5, 1000000000) == 0.9374359693473666
+    ks = stats.ksone
+    vals = np.array([ks.sf(x, n), ks.cdf(x, n), ks.pdf(x, n)])
+    expected = np.array([sf, cdf, pdf])
+    npt.assert_allclose(vals, expected, rtol=rtol)
+    # The sf+cdf must sum to 1.0.
+    npt.assert_equal(vals[0] + vals[1], 1.0)
+    # Check inverting the (potentially very small) sf (uses a lower tolerance)
+    npt.assert_allclose([ks.isf(sf, n)], [x], rtol=1e-8)
+
+
+def test_rvs_gh2069_regression():
+    # Regression tests for gh-2069.  In scipy 0.17 and earlier,
+    # these tests would fail.
+    #
+    # A typical example of the broken behavior:
+    # >>> norm.rvs(loc=np.zeros(5), scale=np.ones(5))
+    # array([-2.49613705, -2.49613705, -2.49613705, -2.49613705, -2.49613705])
+    rng = np.random.RandomState(123)
+    vals = stats.norm.rvs(loc=np.zeros(5), scale=1, random_state=rng)
+    d = np.diff(vals)
+    npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!")
+    vals = stats.norm.rvs(loc=0, scale=np.ones(5), random_state=rng)
+    d = np.diff(vals)
+    npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!")
+    vals = stats.norm.rvs(loc=np.zeros(5), scale=np.ones(5), random_state=rng)
+    d = np.diff(vals)
+    npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!")
+    vals = stats.norm.rvs(loc=np.array([[0], [0]]), scale=np.ones(5),
+                          random_state=rng)
+    d = np.diff(vals.ravel())
+    npt.assert_(np.all(d != 0), "All the values are equal, but they shouldn't be!")
+
+    assert_raises(ValueError, stats.norm.rvs, [[0, 0], [0, 0]],
+                  [[1, 1], [1, 1]], 1)
+    assert_raises(ValueError, stats.gamma.rvs, [2, 3, 4, 5], 0, 1, (2, 2))
+    assert_raises(ValueError, stats.gamma.rvs, [1, 1, 1, 1], [0, 0, 0, 0],
+                  [[1], [2]], (4,))
+
+
+def test_nomodify_gh9900_regression():
+    # Regression test for gh-9990
+    # Prior to gh-9990, calls to stats.truncnorm._cdf() use what ever was
+    # set inside the stats.truncnorm instance during stats.truncnorm.cdf().
+    # This could cause issues with multi-threaded code.
+    # Since then, the calls to cdf() are not permitted to modify the global
+    # stats.truncnorm instance.
+    tn = stats.truncnorm
+    # Use the right-half truncated normal
+    # Check that the cdf and _cdf return the same result.
+    npt.assert_almost_equal(tn.cdf(1, 0, np.inf),
+                            0.6826894921370859)
+    npt.assert_almost_equal(tn._cdf([1], [0], [np.inf]),
+                            0.6826894921370859)
+
+    # Now use the left-half truncated normal
+    npt.assert_almost_equal(tn.cdf(-1, -np.inf, 0),
+                            0.31731050786291415)
+    npt.assert_almost_equal(tn._cdf([-1], [-np.inf], [0]),
+                            0.31731050786291415)
+
+    # Check that the right-half truncated normal _cdf hasn't changed
+    npt.assert_almost_equal(tn._cdf([1], [0], [np.inf]),
+                            0.6826894921370859)  # Not 1.6826894921370859
+    npt.assert_almost_equal(tn.cdf(1, 0, np.inf),
+                            0.6826894921370859)
+
+    # Check that the left-half truncated normal _cdf hasn't changed
+    npt.assert_almost_equal(tn._cdf([-1], [-np.inf], [0]),
+                            0.31731050786291415)  # Not -0.6826894921370859
+    npt.assert_almost_equal(tn.cdf(1, -np.inf, 0),
+                            1)  # Not 1.6826894921370859
+    npt.assert_almost_equal(tn.cdf(-1, -np.inf, 0),
+                            0.31731050786291415)  # Not -0.6826894921370859
+
+
+def test_broadcast_gh9990_regression():
+    # Regression test for gh-9990
+    # The x-value 7 only lies within the support of 4 of the supplied
+    # distributions.  Prior to 9990, one array passed to
+    # stats.reciprocal._cdf would have 4 elements, but an array
+    # previously stored by stats.reciprocal_argcheck() would have 6, leading
+    # to a broadcast error.
+    a = np.array([1, 2, 3, 4, 5, 6])
+    b = np.array([8, 16, 1, 32, 1, 48])
+    ans = [stats.reciprocal.cdf(7, _a, _b) for _a, _b in zip(a,b)]
+    npt.assert_array_almost_equal(stats.reciprocal.cdf(7, a, b), ans)
+
+    ans = [stats.reciprocal.cdf(1, _a, _b) for _a, _b in zip(a,b)]
+    npt.assert_array_almost_equal(stats.reciprocal.cdf(1, a, b), ans)
+
+    ans = [stats.reciprocal.cdf(_a, _a, _b) for _a, _b in zip(a,b)]
+    npt.assert_array_almost_equal(stats.reciprocal.cdf(a, a, b), ans)
+
+    ans = [stats.reciprocal.cdf(_b, _a, _b) for _a, _b in zip(a,b)]
+    npt.assert_array_almost_equal(stats.reciprocal.cdf(b, a, b), ans)
+
+
+def test_broadcast_gh7933_regression():
+    # Check broadcast works
+    stats.truncnorm.logpdf(
+        np.array([3.0, 2.0, 1.0]),
+        a=(1.5 - np.array([6.0, 5.0, 4.0])) / 3.0,
+        b=np.inf,
+        loc=np.array([6.0, 5.0, 4.0]),
+        scale=3.0
+    )
+
+
+def test_gh2002_regression():
+    # Add a check that broadcast works in situations where only some
+    # x-values are compatible with some of the shape arguments.
+    x = np.r_[-2:2:101j]
+    a = np.r_[-np.ones(50), np.ones(51)]
+    expected = [stats.truncnorm.pdf(_x, _a, np.inf) for _x, _a in zip(x, a)]
+    ans = stats.truncnorm.pdf(x, a, np.inf)
+    npt.assert_array_almost_equal(ans, expected)
+
+
+def test_gh1320_regression():
+    # Check that the first example from gh-1320 now works.
+    c = 2.62
+    stats.genextreme.ppf(0.5, np.array([[c], [c + 0.5]]))
+    # The other examples in gh-1320 appear to have stopped working
+    # some time ago.
+    # ans = stats.genextreme.moment(2, np.array([c, c + 0.5]))
+    # expected = np.array([25.50105963, 115.11191437])
+    # stats.genextreme.moment(5, np.array([[c], [c + 0.5]]))
+    # stats.genextreme.moment(5, np.array([c, c + 0.5]))
+
+
+def test_method_of_moments():
+    # example from https://en.wikipedia.org/wiki/Method_of_moments_(statistics)
+    np.random.seed(1234)
+    x = [0, 0, 0, 0, 1]
+    a = 1/5 - 2*np.sqrt(3)/5
+    b = 1/5 + 2*np.sqrt(3)/5
+    # force use of method of moments (uniform.fit is overridden)
+    loc, scale = super(type(stats.uniform), stats.uniform).fit(x, method="MM")
+    npt.assert_almost_equal(loc, a, decimal=4)
+    npt.assert_almost_equal(loc+scale, b, decimal=4)
+
+
+def check_sample_meanvar_(popmean, popvar, sample):
+    if np.isfinite(popmean):
+        check_sample_mean(sample, popmean)
+    if np.isfinite(popvar):
+        check_sample_var(sample, popvar)
+
+
+def check_sample_mean(sample, popmean):
+    # Checks for unlikely difference between sample mean and population mean
+    prob = stats.ttest_1samp(sample, popmean).pvalue
+    assert prob > 0.01
+
+
+def check_sample_var(sample, popvar):
+    # check that population mean lies within the CI bootstrapped from the
+    # sample. This used to be a chi-squared test for variance, but there were
+    # too many false positives
+    res = stats.bootstrap(
+        (sample,),
+        lambda x, axis: x.var(ddof=1, axis=axis),
+        confidence_level=0.995,
+    )
+    conf = res.confidence_interval
+    low, high = conf.low, conf.high
+    assert low <= popvar <= high
+
+
+def check_cdf_ppf(distfn, arg, msg):
+    values = [0.001, 0.5, 0.999]
+    npt.assert_almost_equal(distfn.cdf(distfn.ppf(values, *arg), *arg),
+                            values, decimal=DECIMAL, err_msg=msg +
+                            ' - cdf-ppf roundtrip')
+
+
+def check_sf_isf(distfn, arg, msg):
+    npt.assert_almost_equal(distfn.sf(distfn.isf([0.1, 0.5, 0.9], *arg), *arg),
+                            [0.1, 0.5, 0.9], decimal=DECIMAL, err_msg=msg +
+                            ' - sf-isf roundtrip')
+
+
+def check_cdf_sf(distfn, arg, msg):
+    npt.assert_almost_equal(distfn.cdf([0.1, 0.9], *arg),
+                            1.0 - distfn.sf([0.1, 0.9], *arg),
+                            decimal=DECIMAL, err_msg=msg +
+                            ' - cdf-sf relationship')
+
+
+def check_ppf_isf(distfn, arg, msg):
+    p = np.array([0.1, 0.9])
+    npt.assert_almost_equal(distfn.isf(p, *arg), distfn.ppf(1-p, *arg),
+                            decimal=DECIMAL, err_msg=msg +
+                            ' - ppf-isf relationship')
+
+
+def check_pdf(distfn, arg, msg):
+    # compares pdf at median with numerical derivative of cdf
+    median = distfn.ppf(0.5, *arg)
+    eps = 1e-6
+    pdfv = distfn.pdf(median, *arg)
+    if (pdfv < 1e-4) or (pdfv > 1e4):
+        # avoid checking a case where pdf is close to zero or
+        # huge (singularity)
+        median = median + 0.1
+        pdfv = distfn.pdf(median, *arg)
+    cdfdiff = (distfn.cdf(median + eps, *arg) -
+               distfn.cdf(median - eps, *arg))/eps/2.0
+    # replace with better diff and better test (more points),
+    # actually, this works pretty well
+    msg += ' - cdf-pdf relationship'
+    npt.assert_almost_equal(pdfv, cdfdiff, decimal=DECIMAL, err_msg=msg)
+
+
+def check_pdf_logpdf(distfn, args, msg):
+    # compares pdf at several points with the log of the pdf
+    points = np.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
+    vals = distfn.ppf(points, *args)
+    vals = vals[np.isfinite(vals)]
+    pdf = distfn.pdf(vals, *args)
+    logpdf = distfn.logpdf(vals, *args)
+    pdf = pdf[(pdf != 0) & np.isfinite(pdf)]
+    logpdf = logpdf[np.isfinite(logpdf)]
+    msg += " - logpdf-log(pdf) relationship"
+    npt.assert_almost_equal(np.log(pdf), logpdf, decimal=7, err_msg=msg)
+
+
+def check_pdf_logpdf_at_endpoints(distfn, args, msg):
+    # compares pdf with the log of the pdf at the (finite) end points
+    points = np.array([0, 1])
+    vals = distfn.ppf(points, *args)
+    vals = vals[np.isfinite(vals)]
+    pdf = distfn.pdf(vals, *args)
+    logpdf = distfn.logpdf(vals, *args)
+    pdf = pdf[(pdf != 0) & np.isfinite(pdf)]
+    logpdf = logpdf[np.isfinite(logpdf)]
+    msg += " - logpdf-log(pdf) relationship"
+    npt.assert_almost_equal(np.log(pdf), logpdf, decimal=7, err_msg=msg)
+
+
+def check_sf_logsf(distfn, args, msg):
+    # compares sf at several points with the log of the sf
+    points = np.array([0.0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0])
+    vals = distfn.ppf(points, *args)
+    vals = vals[np.isfinite(vals)]
+    sf = distfn.sf(vals, *args)
+    logsf = distfn.logsf(vals, *args)
+    sf = sf[sf != 0]
+    logsf = logsf[np.isfinite(logsf)]
+    msg += " - logsf-log(sf) relationship"
+    npt.assert_almost_equal(np.log(sf), logsf, decimal=7, err_msg=msg)
+
+
+def check_cdf_logcdf(distfn, args, msg):
+    # compares cdf at several points with the log of the cdf
+    points = np.array([0, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0])
+    vals = distfn.ppf(points, *args)
+    vals = vals[np.isfinite(vals)]
+    cdf = distfn.cdf(vals, *args)
+    logcdf = distfn.logcdf(vals, *args)
+    cdf = cdf[cdf != 0]
+    logcdf = logcdf[np.isfinite(logcdf)]
+    msg += " - logcdf-log(cdf) relationship"
+    npt.assert_almost_equal(np.log(cdf), logcdf, decimal=7, err_msg=msg)
+
+
+def check_ppf_broadcast(distfn, arg, msg):
+    # compares ppf for multiple argsets.
+    num_repeats = 5
+    args = [] * num_repeats
+    if arg:
+        args = [np.array([_] * num_repeats) for _ in arg]
+
+    median = distfn.ppf(0.5, *arg)
+    medians = distfn.ppf(0.5, *args)
+    msg += " - ppf multiple"
+    npt.assert_almost_equal(medians, [median] * num_repeats, decimal=7, err_msg=msg)
+
+
+def check_distribution_rvs(dist, args, alpha, rvs):
+    # dist is either a cdf function or name of a distribution in scipy.stats.
+    # args are the args for scipy.stats.dist(*args)
+    # alpha is a significance level, ~0.01
+    # rvs is array_like of random variables
+    # test from scipy.stats.tests
+    # this version reuses existing random variables
+    D, pval = stats.kstest(rvs, dist, args=args, N=1000)
+    if (pval < alpha):
+        # The rvs passed in failed the K-S test, which _could_ happen
+        # but is unlikely if alpha is small enough.
+        # Repeat the test with a new sample of rvs.
+        # Generate 1000 rvs, perform a K-S test that the new sample of rvs
+        # are distributed according to the distribution.
+        D, pval = stats.kstest(dist, dist, args=args, N=1000)
+        npt.assert_(pval > alpha, "D = " + str(D) + "; pval = " + str(pval) +
+                    "; alpha = " + str(alpha) + "\nargs = " + str(args))
+
+
+def check_vecentropy(distfn, args):
+    npt.assert_equal(distfn.vecentropy(*args), distfn._entropy(*args))
+
+
+def check_loc_scale(distfn, arg, m, v, msg):
+    # Make `loc` and `scale` arrays to catch bugs like gh-13580 where
+    # `loc` and `scale` arrays improperly broadcast with shapes.
+    loc, scale = np.array([10.0, 20.0]), np.array([10.0, 20.0])
+    mt, vt = distfn.stats(*arg, loc=loc, scale=scale)
+    npt.assert_allclose(m*scale + loc, mt)
+    npt.assert_allclose(v*scale*scale, vt)
+
+
+def check_ppf_private(distfn, arg, msg):
+    # fails by design for truncnorm self.nb not defined
+    ppfs = distfn._ppf(np.array([0.1, 0.5, 0.9]), *arg)
+    npt.assert_(not np.any(np.isnan(ppfs)), msg + 'ppf private is nan')
+
+
+def check_retrieving_support(distfn, args):
+    loc, scale = 1, 2
+    supp = distfn.support(*args)
+    supp_loc_scale = distfn.support(*args, loc=loc, scale=scale)
+    npt.assert_almost_equal(np.array(supp)*scale + loc,
+                            np.array(supp_loc_scale))
+
+
+def check_fit_args(distfn, arg, rvs, method):
+    with np.errstate(all='ignore'), npt.suppress_warnings() as sup:
+        sup.filter(category=RuntimeWarning,
+                   message="The shape parameter of the erlang")
+        sup.filter(category=RuntimeWarning,
+                   message="floating point number truncated")
+        vals = distfn.fit(rvs, method=method)
+        vals2 = distfn.fit(rvs, optimizer='powell', method=method)
+    # Only check the length of the return; accuracy tested in test_fit.py
+    npt.assert_(len(vals) == 2+len(arg))
+    npt.assert_(len(vals2) == 2+len(arg))
+
+
+def check_fit_args_fix(distfn, arg, rvs, method):
+    with np.errstate(all='ignore'), npt.suppress_warnings() as sup:
+        sup.filter(category=RuntimeWarning,
+                   message="The shape parameter of the erlang")
+
+        vals = distfn.fit(rvs, floc=0, method=method)
+        vals2 = distfn.fit(rvs, fscale=1, method=method)
+        npt.assert_(len(vals) == 2+len(arg))
+        npt.assert_(vals[-2] == 0)
+        npt.assert_(vals2[-1] == 1)
+        npt.assert_(len(vals2) == 2+len(arg))
+        if len(arg) > 0:
+            vals3 = distfn.fit(rvs, f0=arg[0], method=method)
+            npt.assert_(len(vals3) == 2+len(arg))
+            npt.assert_(vals3[0] == arg[0])
+        if len(arg) > 1:
+            vals4 = distfn.fit(rvs, f1=arg[1], method=method)
+            npt.assert_(len(vals4) == 2+len(arg))
+            npt.assert_(vals4[1] == arg[1])
+        if len(arg) > 2:
+            vals5 = distfn.fit(rvs, f2=arg[2], method=method)
+            npt.assert_(len(vals5) == 2+len(arg))
+            npt.assert_(vals5[2] == arg[2])
+
+
+def cases_test_methods_with_lists():
+    for distname, arg in distcont:
+        if distname in slow_with_lists:
+            yield pytest.param(distname, arg, marks=pytest.mark.slow)
+        else:
+            yield distname, arg
+
+
+@pytest.mark.parametrize('method', ['pdf', 'logpdf', 'cdf', 'logcdf',
+                                    'sf', 'logsf', 'ppf', 'isf'])
+@pytest.mark.parametrize('distname, args', cases_test_methods_with_lists())
+def test_methods_with_lists(method, distname, args):
+    # Test that the continuous distributions can accept Python lists
+    # as arguments.
+    dist = getattr(stats, distname)
+    f = getattr(dist, method)
+    if distname == 'invweibull' and method.startswith('log'):
+        x = [1.5, 2]
+    else:
+        x = [0.1, 0.2]
+
+    shape2 = [[a]*2 for a in args]
+    loc = [0, 0.1]
+    scale = [1, 1.01]
+    result = f(x, *shape2, loc=loc, scale=scale)
+    npt.assert_allclose(result,
+                        [f(*v) for v in zip(x, *shape2, loc, scale)],
+                        rtol=1e-14, atol=5e-14)
+
+
+def test_burr_fisk_moment_gh13234_regression():
+    vals0 = stats.burr.moment(1, 5, 4)
+    assert isinstance(vals0, float)
+
+    vals1 = stats.fisk.moment(1, 8)
+    assert isinstance(vals1, float)
+
+
+def test_moments_with_array_gh12192_regression():
+    # array loc and scalar scale
+    vals0 = stats.norm.moment(order=1, loc=np.array([1, 2, 3]), scale=1)
+    expected0 = np.array([1., 2., 3.])
+    npt.assert_equal(vals0, expected0)
+
+    # array loc and invalid scalar scale
+    vals1 = stats.norm.moment(order=1, loc=np.array([1, 2, 3]), scale=-1)
+    expected1 = np.array([np.nan, np.nan, np.nan])
+    npt.assert_equal(vals1, expected1)
+
+    # array loc and array scale with invalid entries
+    vals2 = stats.norm.moment(order=1, loc=np.array([1, 2, 3]),
+                              scale=[-3, 1, 0])
+    expected2 = np.array([np.nan, 2., np.nan])
+    npt.assert_equal(vals2, expected2)
+
+    # (loc == 0) & (scale < 0)
+    vals3 = stats.norm.moment(order=2, loc=0, scale=-4)
+    expected3 = np.nan
+    npt.assert_equal(vals3, expected3)
+    assert isinstance(vals3, expected3.__class__)
+
+    # array loc with 0 entries and scale with invalid entries
+    vals4 = stats.norm.moment(order=2, loc=[1, 0, 2], scale=[3, -4, -5])
+    expected4 = np.array([10., np.nan, np.nan])
+    npt.assert_equal(vals4, expected4)
+
+    # all(loc == 0) & (array scale with invalid entries)
+    vals5 = stats.norm.moment(order=2, loc=[0, 0, 0], scale=[5., -2, 100.])
+    expected5 = np.array([25., np.nan, 10000.])
+    npt.assert_equal(vals5, expected5)
+
+    # all( (loc == 0) & (scale < 0) )
+    vals6 = stats.norm.moment(order=2, loc=[0, 0, 0], scale=[-5., -2, -100.])
+    expected6 = np.array([np.nan, np.nan, np.nan])
+    npt.assert_equal(vals6, expected6)
+
+    # scalar args, loc, and scale
+    vals7 = stats.chi.moment(order=2, df=1, loc=0, scale=0)
+    expected7 = np.nan
+    npt.assert_equal(vals7, expected7)
+    assert isinstance(vals7, expected7.__class__)
+
+    # array args, scalar loc, and scalar scale
+    vals8 = stats.chi.moment(order=2, df=[1, 2, 3], loc=0, scale=0)
+    expected8 = np.array([np.nan, np.nan, np.nan])
+    npt.assert_equal(vals8, expected8)
+
+    # array args, array loc, and array scale
+    vals9 = stats.chi.moment(order=2, df=[1, 2, 3], loc=[1., 0., 2.],
+                             scale=[1., -3., 0.])
+    expected9 = np.array([3.59576912, np.nan, np.nan])
+    npt.assert_allclose(vals9, expected9, rtol=1e-8)
+
+    # (n > 4), all(loc != 0), and all(scale != 0)
+    vals10 = stats.norm.moment(5, [1., 2.], [1., 2.])
+    expected10 = np.array([26., 832.])
+    npt.assert_allclose(vals10, expected10, rtol=1e-13)
+
+    # test broadcasting and more
+    a = [-1.1, 0, 1, 2.2, np.pi]
+    b = [-1.1, 0, 1, 2.2, np.pi]
+    loc = [-1.1, 0, np.sqrt(2)]
+    scale = [-2.1, 0, 1, 2.2, np.pi]
+
+    a = np.array(a).reshape((-1, 1, 1, 1))
+    b = np.array(b).reshape((-1, 1, 1))
+    loc = np.array(loc).reshape((-1, 1))
+    scale = np.array(scale)
+
+    vals11 = stats.beta.moment(order=2, a=a, b=b, loc=loc, scale=scale)
+
+    a, b, loc, scale = np.broadcast_arrays(a, b, loc, scale)
+
+    for i in np.ndenumerate(a):
+        with np.errstate(invalid='ignore', divide='ignore'):
+            i = i[0]  # just get the index
+            # check against same function with scalar input
+            expected = stats.beta.moment(order=2, a=a[i], b=b[i],
+                                         loc=loc[i], scale=scale[i])
+            np.testing.assert_equal(vals11[i], expected)
+
+
+def test_broadcasting_in_moments_gh12192_regression():
+    vals0 = stats.norm.moment(order=1, loc=np.array([1, 2, 3]), scale=[[1]])
+    expected0 = np.array([[1., 2., 3.]])
+    npt.assert_equal(vals0, expected0)
+    assert vals0.shape == expected0.shape
+
+    vals1 = stats.norm.moment(order=1, loc=np.array([[1], [2], [3]]),
+                              scale=[1, 2, 3])
+    expected1 = np.array([[1., 1., 1.], [2., 2., 2.], [3., 3., 3.]])
+    npt.assert_equal(vals1, expected1)
+    assert vals1.shape == expected1.shape
+
+    vals2 = stats.chi.moment(order=1, df=[1., 2., 3.], loc=0., scale=1.)
+    expected2 = np.array([0.79788456, 1.25331414, 1.59576912])
+    npt.assert_allclose(vals2, expected2, rtol=1e-8)
+    assert vals2.shape == expected2.shape
+
+    vals3 = stats.chi.moment(order=1, df=[[1.], [2.], [3.]], loc=[0., 1., 2.],
+                             scale=[-1., 0., 3.])
+    expected3 = np.array([[np.nan, np.nan, 4.39365368],
+                          [np.nan, np.nan, 5.75994241],
+                          [np.nan, np.nan, 6.78730736]])
+    npt.assert_allclose(vals3, expected3, rtol=1e-8)
+    assert vals3.shape == expected3.shape
+
+
+@pytest.mark.slow
+def test_kappa3_array_gh13582():
+    # https://github.com/scipy/scipy/pull/15140#issuecomment-994958241
+    shapes = [0.5, 1.5, 2.5, 3.5, 4.5]
+    moments = 'mvsk'
+    res = np.array([[stats.kappa3.stats(shape, moments=moment)
+                   for shape in shapes] for moment in moments])
+    res2 = np.array(stats.kappa3.stats(shapes, moments=moments))
+    npt.assert_allclose(res, res2)
+
+
+@pytest.mark.xslow
+def test_kappa4_array_gh13582():
+    h = np.array([-0.5, 2.5, 3.5, 4.5, -3])
+    k = np.array([-0.5, 1, -1.5, 0, 3.5])
+    moments = 'mvsk'
+    res = np.array([[stats.kappa4.stats(h[i], k[i], moments=moment)
+                   for i in range(5)] for moment in moments])
+    res2 = np.array(stats.kappa4.stats(h, k, moments=moments))
+    npt.assert_allclose(res, res2)
+
+    # https://github.com/scipy/scipy/pull/15250#discussion_r775112913
+    h = np.array([-1, -1/4, -1/4, 1, -1, 0])
+    k = np.array([1, 1, 1/2, -1/3, -1, 0])
+    res = np.array([[stats.kappa4.stats(h[i], k[i], moments=moment)
+                   for i in range(6)] for moment in moments])
+    res2 = np.array(stats.kappa4.stats(h, k, moments=moments))
+    npt.assert_allclose(res, res2)
+
+    # https://github.com/scipy/scipy/pull/15250#discussion_r775115021
+    h = np.array([-1, -0.5, 1])
+    k = np.array([-1, -0.5, 0, 1])[:, None]
+    res2 = np.array(stats.kappa4.stats(h, k, moments=moments))
+    assert res2.shape == (4, 4, 3)
+
+
+def test_frozen_attributes():
+    # gh-14827 reported that all frozen distributions had both pmf and pdf
+    # attributes; continuous should have pdf and discrete should have pmf.
+    message = "'rv_continuous_frozen' object has no attribute"
+    with pytest.raises(AttributeError, match=message):
+        stats.norm().pmf
+    with pytest.raises(AttributeError, match=message):
+        stats.norm().logpmf
+    stats.norm.pmf = "herring"
+    frozen_norm = stats.norm()
+    assert isinstance(frozen_norm, rv_continuous_frozen)
+    delattr(stats.norm, 'pmf')
+
+
+def test_skewnorm_pdf_gh16038():
+    rng = np.random.default_rng(0)
+    x, a = -np.inf, 0
+    npt.assert_equal(stats.skewnorm.pdf(x, a), stats.norm.pdf(x))
+    x, a = rng.random(size=(3, 3)), rng.random(size=(3, 3))
+    mask = rng.random(size=(3, 3)) < 0.5
+    a[mask] = 0
+    x_norm = x[mask]
+    res = stats.skewnorm.pdf(x, a)
+    npt.assert_equal(res[mask], stats.norm.pdf(x_norm))
+    npt.assert_equal(res[~mask], stats.skewnorm.pdf(x[~mask], a[~mask]))
+
+
+# for scalar input, these functions should return scalar output
+scalar_out = [['rvs', []], ['pdf', [0]], ['logpdf', [0]], ['cdf', [0]],
+              ['logcdf', [0]], ['sf', [0]], ['logsf', [0]], ['ppf', [0]],
+              ['isf', [0]], ['moment', [1]], ['entropy', []], ['expect', []],
+              ['median', []], ['mean', []], ['std', []], ['var', []]]
+scalars_out = [['interval', [0.95]], ['support', []], ['stats', ['mv']]]
+
+
+@pytest.mark.parametrize('case', scalar_out + scalars_out)
+def test_scalar_for_scalar(case):
+    # Some rv_continuous functions returned 0d array instead of NumPy scalar
+    # Guard against regression
+    method_name, args = case
+    method = getattr(stats.norm(), method_name)
+    res = method(*args)
+    if case in scalar_out:
+        assert isinstance(res, np.number)
+    else:
+        assert isinstance(res[0], np.number)
+        assert isinstance(res[1], np.number)
+
+
+def test_scalar_for_scalar2():
+    # test methods that are not attributes of frozen distributions
+    res = stats.norm.fit([1, 2, 3])
+    assert isinstance(res[0], np.number)
+    assert isinstance(res[1], np.number)
+    res = stats.norm.fit_loc_scale([1, 2, 3])
+    assert isinstance(res[0], np.number)
+    assert isinstance(res[1], np.number)
+    res = stats.norm.nnlf((0, 1), [1, 2, 3])
+    assert isinstance(res, np.number)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_fit_censored.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_fit_censored.py
new file mode 100644
index 0000000000000000000000000000000000000000..4508b49712e5bc8975bf2f9b2681ccc6504b0ae0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_continuous_fit_censored.py
@@ -0,0 +1,683 @@
+# Tests for fitting specific distributions to censored data.
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.optimize import fmin
+from scipy.stats import (CensoredData, beta, cauchy, chi2, expon, gamma,
+                         gumbel_l, gumbel_r, invgauss, invweibull, laplace,
+                         logistic, lognorm, nct, ncx2, norm, weibull_max,
+                         weibull_min)
+
+
+# In some tests, we'll use this optimizer for improved accuracy.
+def optimizer(func, x0, args=(), disp=0):
+    return fmin(func, x0, args=args, disp=disp, xtol=1e-12, ftol=1e-12)
+
+
+def test_beta():
+    """
+    Test fitting beta shape parameters to interval-censored data.
+
+    Calculation in R:
+
+    > library(fitdistrplus)
+    > data <- data.frame(left=c(0.10, 0.50, 0.75, 0.80),
+    +                    right=c(0.20, 0.55, 0.90, 0.95))
+    > result = fitdistcens(data, 'beta', control=list(reltol=1e-14))
+
+    > result
+    Fitting of the distribution ' beta ' on censored data by maximum likelihood
+    Parameters:
+           estimate
+    shape1 1.419941
+    shape2 1.027066
+    > result$sd
+       shape1    shape2
+    0.9914177 0.6866565
+    """
+    data = CensoredData(interval=[[0.10, 0.20],
+                                  [0.50, 0.55],
+                                  [0.75, 0.90],
+                                  [0.80, 0.95]])
+
+    # For this test, fit only the shape parameters; loc and scale are fixed.
+    a, b, loc, scale = beta.fit(data, floc=0, fscale=1, optimizer=optimizer)
+
+    assert_allclose(a, 1.419941, rtol=5e-6)
+    assert_allclose(b, 1.027066, rtol=5e-6)
+    assert loc == 0
+    assert scale == 1
+
+
+def test_cauchy_right_censored():
+    """
+    Test fitting the Cauchy distribution to right-censored data.
+
+    Calculation in R, with two values not censored [1, 10] and
+    one right-censored value [30].
+
+    > library(fitdistrplus)
+    > data <- data.frame(left=c(1, 10, 30), right=c(1, 10, NA))
+    > result = fitdistcens(data, 'cauchy', control=list(reltol=1e-14))
+    > result
+    Fitting of the distribution ' cauchy ' on censored data by maximum
+    likelihood
+    Parameters:
+             estimate
+    location 7.100001
+    scale    7.455866
+    """
+    data = CensoredData(uncensored=[1, 10], right=[30])
+    loc, scale = cauchy.fit(data, optimizer=optimizer)
+    assert_allclose(loc, 7.10001, rtol=5e-6)
+    assert_allclose(scale, 7.455866, rtol=5e-6)
+
+
+def test_cauchy_mixed():
+    """
+    Test fitting the Cauchy distribution to data with mixed censoring.
+
+    Calculation in R, with:
+    * two values not censored [1, 10],
+    * one left-censored [1],
+    * one right-censored [30], and
+    * one interval-censored [[4, 8]].
+
+    > library(fitdistrplus)
+    > data <- data.frame(left=c(NA, 1, 4, 10, 30), right=c(1, 1, 8, 10, NA))
+    > result = fitdistcens(data, 'cauchy', control=list(reltol=1e-14))
+    > result
+    Fitting of the distribution ' cauchy ' on censored data by maximum
+    likelihood
+    Parameters:
+             estimate
+    location 4.605150
+    scale    5.900852
+    """
+    data = CensoredData(uncensored=[1, 10], left=[1], right=[30],
+                        interval=[[4, 8]])
+    loc, scale = cauchy.fit(data, optimizer=optimizer)
+    assert_allclose(loc, 4.605150, rtol=5e-6)
+    assert_allclose(scale, 5.900852, rtol=5e-6)
+
+
+def test_chi2_mixed():
+    """
+    Test fitting just the shape parameter (df) of chi2 to mixed data.
+
+    Calculation in R, with:
+    * two values not censored [1, 10],
+    * one left-censored [1],
+    * one right-censored [30], and
+    * one interval-censored [[4, 8]].
+
+    > library(fitdistrplus)
+    > data <- data.frame(left=c(NA, 1, 4, 10, 30), right=c(1, 1, 8, 10, NA))
+    > result = fitdistcens(data, 'chisq', control=list(reltol=1e-14))
+    > result
+    Fitting of the distribution ' chisq ' on censored data by maximum
+    likelihood
+    Parameters:
+             estimate
+    df 5.060329
+    """
+    data = CensoredData(uncensored=[1, 10], left=[1], right=[30],
+                        interval=[[4, 8]])
+    df, loc, scale = chi2.fit(data, floc=0, fscale=1, optimizer=optimizer)
+    assert_allclose(df, 5.060329, rtol=5e-6)
+    assert loc == 0
+    assert scale == 1
+
+
+def test_expon_right_censored():
+    """
+    For the exponential distribution with loc=0, the exact solution for
+    fitting n uncensored points x[0]...x[n-1] and m right-censored points
+    x[n]..x[n+m-1] is
+
+        scale = sum(x)/n
+
+    That is, divide the sum of all the values (not censored and
+    right-censored) by the number of uncensored values.  (See, for example,
+    https://en.wikipedia.org/wiki/Censoring_(statistics)#Likelihood.)
+
+    The second derivative of the log-likelihood function is
+
+        n/scale**2 - 2*sum(x)/scale**3
+
+    from which the estimate of the standard error can be computed.
+
+    -----
+
+    Calculation in R, for reference only. The R results are not
+    used in the test.
+
+    > library(fitdistrplus)
+    > dexps <- function(x, scale) {
+    +     return(dexp(x, 1/scale))
+    + }
+    > pexps <- function(q, scale) {
+    +     return(pexp(q, 1/scale))
+    + }
+    > left <- c(1, 2.5, 3, 6, 7.5, 10, 12, 12, 14.5, 15,
+    +                                     16, 16, 20, 20, 21, 22)
+    > right <- c(1, 2.5, 3, 6, 7.5, 10, 12, 12, 14.5, 15,
+    +                                     NA, NA, NA, NA, NA, NA)
+    > result = fitdistcens(data, 'exps', start=list(scale=mean(data$left)),
+    +                      control=list(reltol=1e-14))
+    > result
+    Fitting of the distribution ' exps ' on censored data by maximum likelihood
+    Parameters:
+          estimate
+    scale    19.85
+    > result$sd
+       scale
+    6.277119
+    """
+    # This data has 10 uncensored values and 6 right-censored values.
+    obs = [1, 2.5, 3, 6, 7.5, 10, 12, 12, 14.5, 15, 16, 16, 20, 20, 21, 22]
+    cens = [False]*10 + [True]*6
+    data = CensoredData.right_censored(obs, cens)
+
+    loc, scale = expon.fit(data, floc=0, optimizer=optimizer)
+
+    assert loc == 0
+    # Use the analytical solution to compute the expected value.  This
+    # is the sum of the observed values divided by the number of uncensored
+    # values.
+    n = len(data) - data.num_censored()
+    total = data._uncensored.sum() + data._right.sum()
+    expected = total / n
+    assert_allclose(scale, expected, 1e-8)
+
+
+def test_gamma_right_censored():
+    """
+    Fit gamma shape and scale to data with one right-censored value.
+
+    Calculation in R:
+
+    > library(fitdistrplus)
+    > data <- data.frame(left=c(2.5, 2.9, 3.8, 9.1, 9.3, 12.0, 23.0, 25.0),
+    +                    right=c(2.5, 2.9, 3.8, 9.1, 9.3, 12.0, 23.0, NA))
+    > result = fitdistcens(data, 'gamma', start=list(shape=1, scale=10),
+    +                      control=list(reltol=1e-13))
+    > result
+    Fitting of the distribution ' gamma ' on censored data by maximum
+      likelihood
+    Parameters:
+          estimate
+    shape 1.447623
+    scale 8.360197
+    > result$sd
+        shape     scale
+    0.7053086 5.1016531
+    """
+    # The last value is right-censored.
+    x = CensoredData.right_censored([2.5, 2.9, 3.8, 9.1, 9.3, 12.0, 23.0,
+                                     25.0],
+                                    [0]*7 + [1])
+
+    a, loc, scale = gamma.fit(x, floc=0, optimizer=optimizer)
+
+    assert_allclose(a, 1.447623, rtol=5e-6)
+    assert loc == 0
+    assert_allclose(scale, 8.360197, rtol=5e-6)
+
+
+def test_gumbel():
+    """
+    Fit gumbel_l and gumbel_r to censored data.
+
+    This R calculation should match gumbel_r.
+
+    > library(evd)
+    > library(fitdistrplus)
+    > data = data.frame(left=c(0, 2, 3, 9, 10, 10),
+    +                   right=c(1, 2, 3, 9, NA, NA))
+    > result = fitdistcens(data, 'gumbel',
+    +                      control=list(reltol=1e-14),
+    +                      start=list(loc=4, scale=5))
+    > result
+    Fitting of the distribution ' gumbel ' on censored data by maximum
+    likelihood
+    Parameters:
+          estimate
+    loc   4.487853
+    scale 4.843640
+    """
+    # First value is interval-censored. Last two are right-censored.
+    uncensored = np.array([2, 3, 9])
+    right = np.array([10, 10])
+    interval = np.array([[0, 1]])
+    data = CensoredData(uncensored, right=right, interval=interval)
+    loc, scale = gumbel_r.fit(data, optimizer=optimizer)
+    assert_allclose(loc, 4.487853, rtol=5e-6)
+    assert_allclose(scale, 4.843640, rtol=5e-6)
+
+    # Negate the data and reverse the intervals, and test with gumbel_l.
+    data2 = CensoredData(-uncensored, left=-right,
+                         interval=-interval[:, ::-1])
+    # Fitting gumbel_l to data2 should give the same result as above, but
+    # with loc negated.
+    loc2, scale2 = gumbel_l.fit(data2, optimizer=optimizer)
+    assert_allclose(loc2, -4.487853, rtol=5e-6)
+    assert_allclose(scale2, 4.843640, rtol=5e-6)
+
+
+def test_invgauss():
+    """
+    Fit just the shape parameter of invgauss to data with one value
+    left-censored and one value right-censored.
+
+    Calculation in R; using a fixed dispersion parameter amounts to fixing
+    the scale to be 1.
+
+    > library(statmod)
+    > library(fitdistrplus)
+    > left <- c(NA, 0.4813096, 0.5571880, 0.5132463, 0.3801414, 0.5904386,
+    +           0.4822340, 0.3478597, 3, 0.7191797, 1.5810902, 0.4442299)
+    > right <- c(0.15, 0.4813096, 0.5571880, 0.5132463, 0.3801414, 0.5904386,
+    +            0.4822340, 0.3478597, NA, 0.7191797, 1.5810902, 0.4442299)
+    > data <- data.frame(left=left, right=right)
+    > result = fitdistcens(data, 'invgauss', control=list(reltol=1e-12),
+    +                      fix.arg=list(dispersion=1), start=list(mean=3))
+    > result
+    Fitting of the distribution ' invgauss ' on censored data by maximum
+      likelihood
+    Parameters:
+         estimate
+    mean 0.853469
+    Fixed parameters:
+               value
+    dispersion     1
+    > result$sd
+        mean
+    0.247636
+
+    Here's the R calculation with the dispersion as a free parameter to
+    be fit.
+
+    > result = fitdistcens(data, 'invgauss', control=list(reltol=1e-12),
+    +                      start=list(mean=3, dispersion=1))
+    > result
+    Fitting of the distribution ' invgauss ' on censored data by maximum
+    likelihood
+    Parameters:
+                estimate
+    mean       0.8699819
+    dispersion 1.2261362
+
+    The parametrization of the inverse Gaussian distribution in the
+    `statmod` package is not the same as in SciPy (see
+        https://arxiv.org/abs/1603.06687
+    for details).  The translation from R to SciPy is
+
+        scale = 1/dispersion
+        mu    = mean * dispersion
+
+    > 1/result$estimate['dispersion']  # 1/dispersion
+    dispersion
+     0.8155701
+    > result$estimate['mean'] * result$estimate['dispersion']
+        mean
+    1.066716
+
+    Those last two values are the SciPy scale and shape parameters.
+    """
+    # One point is left-censored, and one is right-censored.
+    x = [0.4813096, 0.5571880, 0.5132463, 0.3801414,
+         0.5904386, 0.4822340, 0.3478597, 0.7191797,
+         1.5810902, 0.4442299]
+    data = CensoredData(uncensored=x, left=[0.15], right=[3])
+
+    # Fit only the shape parameter.
+    mu, loc, scale = invgauss.fit(data, floc=0, fscale=1, optimizer=optimizer)
+
+    assert_allclose(mu, 0.853469, rtol=5e-5)
+    assert loc == 0
+    assert scale == 1
+
+    # Fit the shape and scale.
+    mu, loc, scale = invgauss.fit(data, floc=0, optimizer=optimizer)
+
+    assert_allclose(mu, 1.066716, rtol=5e-5)
+    assert loc == 0
+    assert_allclose(scale, 0.8155701, rtol=5e-5)
+
+
+def test_invweibull():
+    """
+    Fit invweibull to censored data.
+
+    Here is the calculation in R.  The 'frechet' distribution from the evd
+    package matches SciPy's invweibull distribution.  The `loc` parameter
+    is fixed at 0.
+
+    > library(evd)
+    > library(fitdistrplus)
+    > data = data.frame(left=c(0, 2, 3, 9, 10, 10),
+    +                   right=c(1, 2, 3, 9, NA, NA))
+    > result = fitdistcens(data, 'frechet',
+    +                      control=list(reltol=1e-14),
+    +                      start=list(loc=4, scale=5))
+    > result
+    Fitting of the distribution ' frechet ' on censored data by maximum
+    likelihood
+    Parameters:
+           estimate
+    scale 2.7902200
+    shape 0.6379845
+    Fixed parameters:
+        value
+    loc     0
+    """
+    # In the R data, the first value is interval-censored, and the last
+    # two are right-censored.  The rest are not censored.
+    data = CensoredData(uncensored=[2, 3, 9], right=[10, 10],
+                        interval=[[0, 1]])
+    c, loc, scale = invweibull.fit(data, floc=0, optimizer=optimizer)
+    assert_allclose(c, 0.6379845, rtol=5e-6)
+    assert loc == 0
+    assert_allclose(scale, 2.7902200, rtol=5e-6)
+
+
+def test_laplace():
+    """
+    Fir the Laplace distribution to left- and right-censored data.
+
+    Calculation in R:
+
+    > library(fitdistrplus)
+    > dlaplace <- function(x, location=0, scale=1) {
+    +     return(0.5*exp(-abs((x - location)/scale))/scale)
+    + }
+    > plaplace <- function(q, location=0, scale=1) {
+    +     z <- (q - location)/scale
+    +     s <- sign(z)
+    +     f <- -s*0.5*exp(-abs(z)) + (s+1)/2
+    +     return(f)
+    + }
+    > left <- c(NA, -41.564, 50.0, 15.7384, 50.0, 10.0452, -2.0684,
+    +           -19.5399, 50.0,   9.0005, 27.1227, 4.3113, -3.7372,
+    +           25.3111, 14.7987,  34.0887,  50.0, 42.8496, 18.5862,
+    +           32.8921, 9.0448, -27.4591, NA, 19.5083, -9.7199)
+    > right <- c(-50.0, -41.564,  NA, 15.7384, NA, 10.0452, -2.0684,
+    +            -19.5399, NA, 9.0005, 27.1227, 4.3113, -3.7372,
+    +            25.3111, 14.7987, 34.0887, NA,  42.8496, 18.5862,
+    +            32.8921, 9.0448, -27.4591, -50.0, 19.5083, -9.7199)
+    > data <- data.frame(left=left, right=right)
+    > result <- fitdistcens(data, 'laplace', start=list(location=10, scale=10),
+    +                       control=list(reltol=1e-13))
+    > result
+    Fitting of the distribution ' laplace ' on censored data by maximum
+      likelihood
+    Parameters:
+             estimate
+    location 14.79870
+    scale    30.93601
+    > result$sd
+         location     scale
+    0.1758864 7.0972125
+    """
+    # The value -50 is left-censored, and the value 50 is right-censored.
+    obs = np.array([-50.0, -41.564, 50.0, 15.7384, 50.0, 10.0452, -2.0684,
+                    -19.5399, 50.0, 9.0005, 27.1227, 4.3113, -3.7372,
+                    25.3111, 14.7987, 34.0887, 50.0, 42.8496, 18.5862,
+                    32.8921, 9.0448, -27.4591, -50.0, 19.5083, -9.7199])
+    x = obs[(obs != -50.0) & (obs != 50)]
+    left = obs[obs == -50.0]
+    right = obs[obs == 50.0]
+    data = CensoredData(uncensored=x, left=left, right=right)
+    loc, scale = laplace.fit(data, loc=10, scale=10, optimizer=optimizer)
+    assert_allclose(loc, 14.79870, rtol=5e-6)
+    assert_allclose(scale, 30.93601, rtol=5e-6)
+
+
+def test_logistic():
+    """
+    Fit the logistic distribution to left-censored data.
+
+    Calculation in R:
+    > library(fitdistrplus)
+    > left = c(13.5401, 37.4235, 11.906 , 13.998 ,  NA    ,  0.4023,  NA    ,
+    +          10.9044, 21.0629,  9.6985,  NA    , 12.9016, 39.164 , 34.6396,
+    +          NA    , 20.3665, 16.5889, 18.0952, 45.3818, 35.3306,  8.4949,
+    +          3.4041,  NA    ,  7.2828, 37.1265,  6.5969, 17.6868, 17.4977,
+    +          16.3391, 36.0541)
+    > right = c(13.5401, 37.4235, 11.906 , 13.998 ,  0.    ,  0.4023,  0.    ,
+    +           10.9044, 21.0629,  9.6985,  0.    , 12.9016, 39.164 , 34.6396,
+    +           0.    , 20.3665, 16.5889, 18.0952, 45.3818, 35.3306,  8.4949,
+    +           3.4041,  0.    ,  7.2828, 37.1265,  6.5969, 17.6868, 17.4977,
+    +           16.3391, 36.0541)
+    > data = data.frame(left=left, right=right)
+    > result = fitdistcens(data, 'logis', control=list(reltol=1e-14))
+    > result
+    Fitting of the distribution ' logis ' on censored data by maximum
+      likelihood
+    Parameters:
+              estimate
+    location 14.633459
+    scale     9.232736
+    > result$sd
+    location    scale
+    2.931505 1.546879
+    """
+    # Values that are zero are left-censored; the true values are less than 0.
+    x = np.array([13.5401, 37.4235, 11.906, 13.998, 0.0, 0.4023, 0.0, 10.9044,
+                  21.0629, 9.6985, 0.0, 12.9016, 39.164, 34.6396, 0.0, 20.3665,
+                  16.5889, 18.0952, 45.3818, 35.3306, 8.4949, 3.4041, 0.0,
+                  7.2828, 37.1265, 6.5969, 17.6868, 17.4977, 16.3391,
+                  36.0541])
+    data = CensoredData.left_censored(x, censored=(x == 0))
+    loc, scale = logistic.fit(data, optimizer=optimizer)
+    assert_allclose(loc, 14.633459, rtol=5e-7)
+    assert_allclose(scale, 9.232736, rtol=5e-6)
+
+
+def test_lognorm():
+    """
+    Ref: https://math.montana.edu/jobo/st528/documents/relc.pdf
+
+    The data is the locomotive control time to failure example that starts
+    on page 8.  That's the 8th page in the PDF; the page number shown in
+    the text is 270).
+    The document includes SAS output for the data.
+    """
+    # These are the uncensored measurements.  There are also 59 right-censored
+    # measurements where the lower bound is 135.
+    miles_to_fail = [22.5, 37.5, 46.0, 48.5, 51.5, 53.0, 54.5, 57.5, 66.5,
+                     68.0, 69.5, 76.5, 77.0, 78.5, 80.0, 81.5, 82.0, 83.0,
+                     84.0, 91.5, 93.5, 102.5, 107.0, 108.5, 112.5, 113.5,
+                     116.0, 117.0, 118.5, 119.0, 120.0, 122.5, 123.0, 127.5,
+                     131.0, 132.5, 134.0]
+
+    data = CensoredData.right_censored(miles_to_fail + [135]*59,
+                                       [0]*len(miles_to_fail) + [1]*59)
+    sigma, loc, scale = lognorm.fit(data, floc=0)
+
+    assert loc == 0
+    # Convert the lognorm parameters to the mu and sigma of the underlying
+    # normal distribution.
+    mu = np.log(scale)
+    # The expected results are from the 17th page of the PDF document
+    # (labeled page 279), in the SAS output on the right side of the page.
+    assert_allclose(mu, 5.1169, rtol=5e-4)
+    assert_allclose(sigma, 0.7055, rtol=5e-3)
+
+
+def test_nct():
+    """
+    Test fitting the noncentral t distribution to censored data.
+
+    Calculation in R:
+
+    > library(fitdistrplus)
+    > data <- data.frame(left=c(1, 2, 3, 5, 8, 10, 25, 25),
+    +                    right=c(1, 2, 3, 5, 8, 10, NA, NA))
+    > result = fitdistcens(data, 't', control=list(reltol=1e-14),
+    +                      start=list(df=1, ncp=2))
+    > result
+    Fitting of the distribution ' t ' on censored data by maximum likelihood
+    Parameters:
+         estimate
+    df  0.5432336
+    ncp 2.8893565
+
+    """
+    data = CensoredData.right_censored([1, 2, 3, 5, 8, 10, 25, 25],
+                                       [0, 0, 0, 0, 0, 0, 1, 1])
+    # Fit just the shape parameter df and nc; loc and scale are fixed.
+    with np.errstate(over='ignore'):  # remove context when gh-14901 is closed
+        df, nc, loc, scale = nct.fit(data, floc=0, fscale=1,
+                                     optimizer=optimizer)
+    assert_allclose(df, 0.5432336, rtol=5e-6)
+    assert_allclose(nc, 2.8893565, rtol=5e-6)
+    assert loc == 0
+    assert scale == 1
+
+
+def test_ncx2():
+    """
+    Test fitting the shape parameters (df, ncp) of ncx2 to mixed data.
+
+    Calculation in R, with
+    * 5 not censored values [2.7, 0.2, 6.5, 0.4, 0.1],
+    * 1 interval-censored value [[0.6, 1.0]], and
+    * 2 right-censored values [8, 8].
+
+    > library(fitdistrplus)
+    > data <- data.frame(left=c(2.7, 0.2, 6.5, 0.4, 0.1, 0.6, 8, 8),
+    +                    right=c(2.7, 0.2, 6.5, 0.4, 0.1, 1.0, NA, NA))
+    > result = fitdistcens(data, 'chisq', control=list(reltol=1e-14),
+    +                      start=list(df=1, ncp=2))
+    > result
+    Fitting of the distribution ' chisq ' on censored data by maximum
+    likelihood
+    Parameters:
+        estimate
+    df  1.052871
+    ncp 2.362934
+    """
+    data = CensoredData(uncensored=[2.7, 0.2, 6.5, 0.4, 0.1], right=[8, 8],
+                        interval=[[0.6, 1.0]])
+    with np.errstate(over='ignore'):  # remove context when gh-14901 is closed
+        df, ncp, loc, scale = ncx2.fit(data, floc=0, fscale=1,
+                                       optimizer=optimizer)
+    assert_allclose(df, 1.052871, rtol=5e-6)
+    assert_allclose(ncp, 2.362934, rtol=5e-6)
+    assert loc == 0
+    assert scale == 1
+
+
+def test_norm():
+    """
+    Test fitting the normal distribution to interval-censored data.
+
+    Calculation in R:
+
+    > library(fitdistrplus)
+    > data <- data.frame(left=c(0.10, 0.50, 0.75, 0.80),
+    +                    right=c(0.20, 0.55, 0.90, 0.95))
+    > result = fitdistcens(data, 'norm', control=list(reltol=1e-14))
+
+    > result
+    Fitting of the distribution ' norm ' on censored data by maximum likelihood
+    Parameters:
+          estimate
+    mean 0.5919990
+    sd   0.2868042
+    > result$sd
+         mean        sd
+    0.1444432 0.1029451
+    """
+    data = CensoredData(interval=[[0.10, 0.20],
+                                  [0.50, 0.55],
+                                  [0.75, 0.90],
+                                  [0.80, 0.95]])
+
+    loc, scale = norm.fit(data, optimizer=optimizer)
+
+    assert_allclose(loc, 0.5919990, rtol=5e-6)
+    assert_allclose(scale, 0.2868042, rtol=5e-6)
+
+
+def test_weibull_censored1():
+    # Ref: http://www.ams.sunysb.edu/~zhu/ams588/Lecture_3_likelihood.pdf
+
+    # Survival times; '*' indicates right-censored.
+    s = "3,5,6*,8,10*,11*,15,20*,22,23,27*,29,32,35,40,26,28,33*,21,24*"
+
+    times, cens = zip(*[(float(t[0]), len(t) == 2)
+                        for t in [w.split('*') for w in s.split(',')]])
+    data = CensoredData.right_censored(times, cens)
+
+    c, loc, scale = weibull_min.fit(data, floc=0)
+
+    # Expected values are from the reference.
+    assert_allclose(c, 2.149, rtol=1e-3)
+    assert loc == 0
+    assert_allclose(scale, 28.99, rtol=1e-3)
+
+    # Flip the sign of the data, and make the censored values
+    # left-censored. We should get the same parameters when we fit
+    # weibull_max to the flipped data.
+    data2 = CensoredData.left_censored(-np.array(times), cens)
+
+    c2, loc2, scale2 = weibull_max.fit(data2, floc=0)
+
+    assert_allclose(c2, 2.149, rtol=1e-3)
+    assert loc2 == 0
+    assert_allclose(scale2, 28.99, rtol=1e-3)
+
+
+def test_weibull_min_sas1():
+    # Data and SAS results from
+    #   https://support.sas.com/documentation/cdl/en/qcug/63922/HTML/default/
+    #         viewer.htm#qcug_reliability_sect004.htm
+
+    text = """
+           450 0    460 1   1150 0   1150 0   1560 1
+          1600 0   1660 1   1850 1   1850 1   1850 1
+          1850 1   1850 1   2030 1   2030 1   2030 1
+          2070 0   2070 0   2080 0   2200 1   3000 1
+          3000 1   3000 1   3000 1   3100 0   3200 1
+          3450 0   3750 1   3750 1   4150 1   4150 1
+          4150 1   4150 1   4300 1   4300 1   4300 1
+          4300 1   4600 0   4850 1   4850 1   4850 1
+          4850 1   5000 1   5000 1   5000 1   6100 1
+          6100 0   6100 1   6100 1   6300 1   6450 1
+          6450 1   6700 1   7450 1   7800 1   7800 1
+          8100 1   8100 1   8200 1   8500 1   8500 1
+          8500 1   8750 1   8750 0   8750 1   9400 1
+          9900 1  10100 1  10100 1  10100 1  11500 1
+    """
+
+    life, cens = np.array([int(w) for w in text.split()]).reshape(-1, 2).T
+    life = life/1000.0
+
+    data = CensoredData.right_censored(life, cens)
+
+    c, loc, scale = weibull_min.fit(data, floc=0, optimizer=optimizer)
+    assert_allclose(c, 1.0584, rtol=1e-4)
+    assert_allclose(scale, 26.2968, rtol=1e-5)
+    assert loc == 0
+
+
+def test_weibull_min_sas2():
+    # http://support.sas.com/documentation/cdl/en/ormpug/67517/HTML/default/
+    #      viewer.htm#ormpug_nlpsolver_examples06.htm
+
+    # The last two values are right-censored.
+    days = np.array([143, 164, 188, 188, 190, 192, 206, 209, 213, 216, 220,
+                     227, 230, 234, 246, 265, 304, 216, 244])
+
+    data = CensoredData.right_censored(days, [0]*(len(days) - 2) + [1]*2)
+
+    c, loc, scale = weibull_min.fit(data, 1, loc=100, scale=100,
+                                    optimizer=optimizer)
+
+    assert_allclose(c, 2.7112, rtol=5e-4)
+    assert_allclose(loc, 122.03, rtol=5e-4)
+    assert_allclose(scale, 108.37, rtol=5e-4)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_correlation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_correlation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b1af276de847c2a834c25fa0d3d352097112a13
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_correlation.py
@@ -0,0 +1,80 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy import stats
+from scipy.stats._axis_nan_policy import SmallSampleWarning
+
+
+class TestChatterjeeXi:
+    @pytest.mark.parametrize('case', [
+        dict(y_cont=True, statistic=-0.303030303030303, pvalue=0.9351329808526656),
+        dict(y_cont=False, statistic=0.07407407407407396, pvalue=0.3709859367123997)])
+    def test_against_R_XICOR(self, case):
+        # Test against R package XICOR, e.g.
+        # library(XICOR)
+        # options(digits=16)
+        # x = c(0.11027287231363914, 0.8154770102474279, 0.7073943466920335,
+        #       0.6651317324378386, 0.6905752850115503, 0.06115250587536558,
+        #       0.5209906494474178, 0.3155763519785274, 0.18405731803625924,
+        #       0.8613557911541495)
+        # y = c(0.8402081904493103, 0.5946972833914318, 0.23481606164114155,
+        #       0.49754786197715384, 0.9146460831206026, 0.5848057749217579,
+        #       0.7620801065573549, 0.31410063302647495, 0.7935620302236199,
+        #       0.5423085761365468)
+        # xicor(x, y, ties=FALSE, pvalue=TRUE)
+
+        rng = np.random.default_rng(25982435982346983)
+        x = rng.random(size=10)
+
+        y = (rng.random(size=10) if case['y_cont']
+             else rng.integers(0, 5, size=10))
+        res = stats.chatterjeexi(x, y, y_continuous=case['y_cont'])
+
+        assert_allclose(res.statistic, case['statistic'])
+        assert_allclose(res.pvalue, case['pvalue'])
+
+    @pytest.mark.parametrize('y_continuous', (False, True))
+    def test_permutation_asymptotic(self, y_continuous):
+        # XICOR doesn't seem to perform the permutation test as advertised, so
+        # compare the result of a permutation test against an asymptotic test.
+        rng = np.random.default_rng(2524579827426)
+        n = np.floor(rng.uniform(100, 150)).astype(int)
+        shape = (2, n)
+        x = rng.random(size=shape)
+        y = (rng.random(size=shape) if y_continuous
+             else rng.integers(0, 10, size=shape))
+        method = stats.PermutationMethod(rng=rng)
+        res = stats.chatterjeexi(x, y, method=method,
+                                 y_continuous=y_continuous, axis=-1)
+        ref = stats.chatterjeexi(x, y, y_continuous=y_continuous, axis=-1)
+        np.testing.assert_allclose(res.statistic, ref.statistic, rtol=1e-15)
+        np.testing.assert_allclose(res.pvalue, ref.pvalue, rtol=2e-2)
+
+    def test_input_validation(self):
+        rng = np.random.default_rng(25932435798274926)
+        x, y = rng.random(size=(2, 10))
+
+        message = 'Array shapes are incompatible for broadcasting.'
+        with pytest.raises(ValueError, match=message):
+            stats.chatterjeexi(x, y[:-1])
+
+        message = '...axis 10 is out of bounds for array...'
+        with pytest.raises(ValueError, match=message):
+            stats.chatterjeexi(x, y, axis=10)
+
+        message = '`y_continuous` must be boolean.'
+        with pytest.raises(ValueError, match=message):
+            stats.chatterjeexi(x, y, y_continuous='a herring')
+
+        message = "`method` must be 'asymptotic' or"
+        with pytest.raises(ValueError, match=message):
+            stats.chatterjeexi(x, y, method='ekki ekii')
+
+    def test_special_cases(self):
+        message = 'One or more sample arguments is too small...'
+        with pytest.warns(SmallSampleWarning, match=message):
+            res = stats.chatterjeexi([1], [2])
+
+        assert np.isnan(res.statistic)
+        assert np.isnan(res.pvalue)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_crosstab.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_crosstab.py
new file mode 100644
index 0000000000000000000000000000000000000000..239b3d3f6fa46e53ee90743a6eb6e10174a8c99c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_crosstab.py
@@ -0,0 +1,115 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_array_equal, assert_equal
+from scipy.stats.contingency import crosstab
+
+
+@pytest.mark.parametrize('sparse', [False, True])
+def test_crosstab_basic(sparse):
+    a = [0, 0, 9, 9, 0, 0, 9]
+    b = [2, 1, 3, 1, 2, 3, 3]
+    expected_avals = [0, 9]
+    expected_bvals = [1, 2, 3]
+    expected_count = np.array([[1, 2, 1],
+                               [1, 0, 2]])
+    (avals, bvals), count = crosstab(a, b, sparse=sparse)
+    assert_array_equal(avals, expected_avals)
+    assert_array_equal(bvals, expected_bvals)
+    if sparse:
+        assert_array_equal(count.toarray(), expected_count)
+    else:
+        assert_array_equal(count, expected_count)
+
+
+def test_crosstab_basic_1d():
+    # Verify that a single input sequence works as expected.
+    x = [1, 2, 3, 1, 2, 3, 3]
+    expected_xvals = [1, 2, 3]
+    expected_count = np.array([2, 2, 3])
+    (xvals,), count = crosstab(x)
+    assert_array_equal(xvals, expected_xvals)
+    assert_array_equal(count, expected_count)
+
+
+def test_crosstab_basic_3d():
+    # Verify the function for three input sequences.
+    a = 'a'
+    b = 'b'
+    x = [0, 0, 9, 9, 0, 0, 9, 9]
+    y = [a, a, a, a, b, b, b, a]
+    z = [1, 2, 3, 1, 2, 3, 3, 1]
+    expected_xvals = [0, 9]
+    expected_yvals = [a, b]
+    expected_zvals = [1, 2, 3]
+    expected_count = np.array([[[1, 1, 0],
+                                [0, 1, 1]],
+                               [[2, 0, 1],
+                                [0, 0, 1]]])
+    (xvals, yvals, zvals), count = crosstab(x, y, z)
+    assert_array_equal(xvals, expected_xvals)
+    assert_array_equal(yvals, expected_yvals)
+    assert_array_equal(zvals, expected_zvals)
+    assert_array_equal(count, expected_count)
+
+
+@pytest.mark.parametrize('sparse', [False, True])
+def test_crosstab_levels(sparse):
+    a = [0, 0, 9, 9, 0, 0, 9]
+    b = [1, 2, 3, 1, 2, 3, 3]
+    expected_avals = [0, 9]
+    expected_bvals = [0, 1, 2, 3]
+    expected_count = np.array([[0, 1, 2, 1],
+                               [0, 1, 0, 2]])
+    (avals, bvals), count = crosstab(a, b, levels=[None, [0, 1, 2, 3]],
+                                     sparse=sparse)
+    assert_array_equal(avals, expected_avals)
+    assert_array_equal(bvals, expected_bvals)
+    if sparse:
+        assert_array_equal(count.toarray(), expected_count)
+    else:
+        assert_array_equal(count, expected_count)
+
+
+@pytest.mark.parametrize('sparse', [False, True])
+def test_crosstab_extra_levels(sparse):
+    # The pair of values (-1, 3) will be ignored, because we explicitly
+    # request the counted `a` values to be [0, 9].
+    a = [0, 0, 9, 9, 0, 0, 9, -1]
+    b = [1, 2, 3, 1, 2, 3, 3, 3]
+    expected_avals = [0, 9]
+    expected_bvals = [0, 1, 2, 3]
+    expected_count = np.array([[0, 1, 2, 1],
+                               [0, 1, 0, 2]])
+    (avals, bvals), count = crosstab(a, b, levels=[[0, 9], [0, 1, 2, 3]],
+                                     sparse=sparse)
+    assert_array_equal(avals, expected_avals)
+    assert_array_equal(bvals, expected_bvals)
+    if sparse:
+        assert_array_equal(count.toarray(), expected_count)
+    else:
+        assert_array_equal(count, expected_count)
+
+
+def test_validation_at_least_one():
+    with pytest.raises(TypeError, match='At least one'):
+        crosstab()
+
+
+def test_validation_same_lengths():
+    with pytest.raises(ValueError, match='must have the same length'):
+        crosstab([1, 2], [1, 2, 3, 4])
+
+
+def test_validation_sparse_only_two_args():
+    with pytest.raises(ValueError, match='only two input sequences'):
+        crosstab([0, 1, 1], [8, 8, 9], [1, 3, 3], sparse=True)
+
+
+def test_validation_len_levels_matches_args():
+    with pytest.raises(ValueError, match='number of input sequences'):
+        crosstab([0, 1, 1], [8, 8, 9], levels=([0, 1, 2, 3],))
+
+
+def test_result():
+    res = crosstab([0, 1], [1, 2])
+    assert_equal((res.elements, res.count), res)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f468cf7397af0197f46d7813674feae533d63e3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_basic.py
@@ -0,0 +1,574 @@
+import numpy.testing as npt
+from numpy.testing import assert_allclose
+
+import numpy as np
+import pytest
+
+from scipy import stats
+from .common_tests import (check_normalization, check_moment,
+                           check_mean_expect,
+                           check_var_expect, check_skew_expect,
+                           check_kurt_expect, check_entropy,
+                           check_private_entropy, check_edge_support,
+                           check_named_args, check_random_state_property,
+                           check_pickling, check_rvs_broadcast,
+                           check_freezing,)
+from scipy.stats._distr_params import distdiscrete, invdistdiscrete
+from scipy.stats._distn_infrastructure import rv_discrete_frozen
+
+vals = ([1, 2, 3, 4], [0.1, 0.2, 0.3, 0.4])
+distdiscrete += [[stats.rv_discrete(values=vals), ()]]
+
+# For these distributions, test_discrete_basic only runs with test mode full
+distslow = {'zipfian', 'nhypergeom'}
+
+# Override number of ULPs adjustment for `check_cdf_ppf`
+roundtrip_cdf_ppf_exceptions = {'nbinom': 30}
+
+def cases_test_discrete_basic():
+    seen = set()
+    for distname, arg in distdiscrete:
+        if distname in distslow:
+            yield pytest.param(distname, arg, distname, marks=pytest.mark.slow)
+        else:
+            yield distname, arg, distname not in seen
+        seen.add(distname)
+
+
+@pytest.mark.parametrize('distname,arg,first_case', cases_test_discrete_basic())
+def test_discrete_basic(distname, arg, first_case):
+    try:
+        distfn = getattr(stats, distname)
+    except TypeError:
+        distfn = distname
+        distname = 'sample distribution'
+    np.random.seed(9765456)
+    rvs = distfn.rvs(size=2000, *arg)
+    supp = np.unique(rvs)
+    m, v = distfn.stats(*arg)
+    check_cdf_ppf(distfn, arg, supp, distname + ' cdf_ppf')
+
+    check_pmf_cdf(distfn, arg, distname)
+    check_oth(distfn, arg, supp, distname + ' oth')
+    check_edge_support(distfn, arg)
+
+    alpha = 0.01
+    check_discrete_chisquare(distfn, arg, rvs, alpha,
+                             distname + ' chisquare')
+
+    if first_case:
+        locscale_defaults = (0,)
+        meths = [distfn.pmf, distfn.logpmf, distfn.cdf, distfn.logcdf,
+                 distfn.logsf]
+        # make sure arguments are within support
+        # for some distributions, this needs to be overridden
+        spec_k = {'randint': 11, 'hypergeom': 4, 'bernoulli': 0,
+                  'nchypergeom_wallenius': 6}
+        k = spec_k.get(distname, 1)
+        check_named_args(distfn, k, arg, locscale_defaults, meths)
+        if distname != 'sample distribution':
+            check_scale_docstring(distfn)
+        check_random_state_property(distfn, arg)
+        if distname not in {'poisson_binom'}:  # can't be pickled
+            check_pickling(distfn, arg)
+        check_freezing(distfn, arg)
+
+        # Entropy
+        check_entropy(distfn, arg, distname)
+        if distfn.__class__._entropy != stats.rv_discrete._entropy:
+            check_private_entropy(distfn, arg, stats.rv_discrete)
+
+
+@pytest.mark.parametrize('distname,arg', distdiscrete)
+def test_moments(distname, arg):
+    try:
+        distfn = getattr(stats, distname)
+    except TypeError:
+        distfn = distname
+        distname = 'sample distribution'
+    m, v, s, k = distfn.stats(*arg, moments='mvsk')
+    check_normalization(distfn, arg, distname)
+
+    # compare `stats` and `moment` methods
+    check_moment(distfn, arg, m, v, distname)
+    check_mean_expect(distfn, arg, m, distname)
+    check_var_expect(distfn, arg, m, v, distname)
+    check_skew_expect(distfn, arg, m, v, s, distname)
+    with np.testing.suppress_warnings() as sup:
+        if distname in ['zipf', 'betanbinom']:
+            sup.filter(RuntimeWarning)
+        check_kurt_expect(distfn, arg, m, v, k, distname)
+
+    # frozen distr moments
+    check_moment_frozen(distfn, arg, m, 1)
+    check_moment_frozen(distfn, arg, v+m*m, 2)
+
+
+@pytest.mark.parametrize('dist,shape_args', distdiscrete)
+def test_rvs_broadcast(dist, shape_args):
+    # If shape_only is True, it means the _rvs method of the
+    # distribution uses more than one random number to generate a random
+    # variate.  That means the result of using rvs with broadcasting or
+    # with a nontrivial size will not necessarily be the same as using the
+    # numpy.vectorize'd version of rvs(), so we can only compare the shapes
+    # of the results, not the values.
+    # Whether or not a distribution is in the following list is an
+    # implementation detail of the distribution, not a requirement.  If
+    # the implementation the rvs() method of a distribution changes, this
+    # test might also have to be changed.
+    shape_only = dist in ['betabinom', 'betanbinom', 'skellam', 'yulesimon',
+                          'dlaplace', 'nchypergeom_fisher',
+                          'nchypergeom_wallenius', 'poisson_binom']
+    try:
+        distfunc = getattr(stats, dist)
+    except TypeError:
+        distfunc = dist
+        dist = f'rv_discrete(values=({dist.xk!r}, {dist.pk!r}))'
+    loc = np.zeros(2)
+    nargs = distfunc.numargs
+    allargs = []
+    bshape = []
+
+    if dist == 'poisson_binom':
+        # normal rules apply except the last axis of `p` is ignored
+        p = np.full((3, 1, 10), 0.5)
+        allargs = (p, loc)
+        bshape = (3, 2)
+        check_rvs_broadcast(distfunc, dist, allargs,
+                            bshape, shape_only, [np.dtype(int)])
+        return
+
+    # Generate shape parameter arguments...
+    for k in range(nargs):
+        shp = (k + 3,) + (1,)*(k + 1)
+        param_val = shape_args[k]
+        allargs.append(np.full(shp, param_val))
+        bshape.insert(0, shp[0])
+    allargs.append(loc)
+    bshape.append(loc.size)
+    # bshape holds the expected shape when loc, scale, and the shape
+    # parameters are all broadcast together.
+    check_rvs_broadcast(
+        distfunc, dist, allargs, bshape, shape_only, [np.dtype(int)]
+    )
+
+
+@pytest.mark.parametrize('dist,args', distdiscrete)
+def test_ppf_with_loc(dist, args):
+    try:
+        distfn = getattr(stats, dist)
+    except TypeError:
+        distfn = dist
+    #check with a negative, no and positive relocation.
+    np.random.seed(1942349)
+    re_locs = [np.random.randint(-10, -1), 0, np.random.randint(1, 10)]
+    _a, _b = distfn.support(*args)
+    for loc in re_locs:
+        npt.assert_array_equal(
+            [_a-1+loc, _b+loc],
+            [distfn.ppf(0.0, *args, loc=loc), distfn.ppf(1.0, *args, loc=loc)]
+            )
+
+
+@pytest.mark.parametrize('dist, args', distdiscrete)
+def test_isf_with_loc(dist, args):
+    try:
+        distfn = getattr(stats, dist)
+    except TypeError:
+        distfn = dist
+    # check with a negative, no and positive relocation.
+    np.random.seed(1942349)
+    re_locs = [np.random.randint(-10, -1), 0, np.random.randint(1, 10)]
+    _a, _b = distfn.support(*args)
+    for loc in re_locs:
+        expected = _b + loc, _a - 1 + loc
+        res = distfn.isf(0., *args, loc=loc), distfn.isf(1., *args, loc=loc)
+        npt.assert_array_equal(expected, res)
+    # test broadcasting behaviour
+    re_locs = [np.random.randint(-10, -1, size=(5, 3)),
+               np.zeros((5, 3)),
+               np.random.randint(1, 10, size=(5, 3))]
+    _a, _b = distfn.support(*args)
+    for loc in re_locs:
+        expected = _b + loc, _a - 1 + loc
+        res = distfn.isf(0., *args, loc=loc), distfn.isf(1., *args, loc=loc)
+        npt.assert_array_equal(expected, res)
+
+
+def check_cdf_ppf(distfn, arg, supp, msg):
+    # supp is assumed to be an array of integers in the support of distfn
+    # (but not necessarily all the integers in the support).
+    # This test assumes that the PMF of any value in the support of the
+    # distribution is greater than 1e-8.
+
+    # cdf is a step function, and ppf(q) = min{k : cdf(k) >= q, k integer}
+    cdf_supp = distfn.cdf(supp, *arg)
+    # In very rare cases, the finite precision calculation of ppf(cdf(supp))
+    # can produce an array in which an element is off by one.  We nudge the
+    # CDF values down by a few ULPs help to avoid this.
+    n_ulps = roundtrip_cdf_ppf_exceptions.get(distfn.name, 15)
+    cdf_supp0 = cdf_supp - n_ulps*np.spacing(cdf_supp)
+    npt.assert_array_equal(distfn.ppf(cdf_supp0, *arg),
+                           supp, msg + '-roundtrip')
+    # Repeat the same calculation, but with the CDF values decreased by 1e-8.
+    npt.assert_array_equal(distfn.ppf(distfn.cdf(supp, *arg) - 1e-8, *arg),
+                           supp, msg + '-roundtrip')
+
+    if not hasattr(distfn, 'xk'):
+        _a, _b = distfn.support(*arg)
+        supp1 = supp[supp < _b]
+        npt.assert_array_equal(distfn.ppf(distfn.cdf(supp1, *arg) + 1e-8, *arg),
+                               supp1 + distfn.inc, msg + ' ppf-cdf-next')
+
+
+def check_pmf_cdf(distfn, arg, distname):
+    if hasattr(distfn, 'xk'):
+        index = distfn.xk
+    else:
+        startind = int(distfn.ppf(0.01, *arg) - 1)
+        index = list(range(startind, startind + 10))
+    cdfs = distfn.cdf(index, *arg)
+    pmfs_cum = distfn.pmf(index, *arg).cumsum()
+
+    atol, rtol = 1e-10, 1e-10
+    if distname == 'skellam':    # ncx2 accuracy
+        atol, rtol = 1e-5, 1e-5
+    npt.assert_allclose(cdfs - cdfs[0], pmfs_cum - pmfs_cum[0],
+                        atol=atol, rtol=rtol)
+
+    # also check that pmf at non-integral k is zero
+    k = np.asarray(index)
+    k_shifted = k[:-1] + np.diff(k)/2
+    npt.assert_equal(distfn.pmf(k_shifted, *arg), 0)
+
+    # better check frozen distributions, and also when loc != 0
+    loc = 0.5
+    dist = distfn(loc=loc, *arg)
+    npt.assert_allclose(dist.pmf(k[1:] + loc), np.diff(dist.cdf(k + loc)))
+    npt.assert_equal(dist.pmf(k_shifted + loc), 0)
+
+
+def check_moment_frozen(distfn, arg, m, k):
+    npt.assert_allclose(distfn(*arg).moment(k), m,
+                        atol=1e-10, rtol=1e-10)
+
+
+def check_oth(distfn, arg, supp, msg):
+    # checking other methods of distfn
+    npt.assert_allclose(distfn.sf(supp, *arg), 1. - distfn.cdf(supp, *arg),
+                        atol=1e-10, rtol=1e-10)
+
+    q = np.linspace(0.01, 0.99, 20)
+    npt.assert_allclose(distfn.isf(q, *arg), distfn.ppf(1. - q, *arg),
+                        atol=1e-10, rtol=1e-10)
+
+    median_sf = distfn.isf(0.5, *arg)
+    npt.assert_(distfn.sf(median_sf - 1, *arg) > 0.5)
+    npt.assert_(distfn.cdf(median_sf + 1, *arg) > 0.5)
+
+
+def check_discrete_chisquare(distfn, arg, rvs, alpha, msg):
+    """Perform chisquare test for random sample of a discrete distribution
+
+    Parameters
+    ----------
+    distname : string
+        name of distribution function
+    arg : sequence
+        parameters of distribution
+    alpha : float
+        significance level, threshold for p-value
+
+    Returns
+    -------
+    result : bool
+        0 if test passes, 1 if test fails
+
+    """
+    wsupp = 0.05
+
+    # construct intervals with minimum mass `wsupp`.
+    # intervals are left-half-open as in a cdf difference
+    _a, _b = distfn.support(*arg)
+    lo = int(max(_a, -1000))
+    high = int(min(_b, 1000)) + 1
+    distsupport = range(lo, high)
+    last = 0
+    distsupp = [lo]
+    distmass = []
+    for ii in distsupport:
+        current = distfn.cdf(ii, *arg)
+        if current - last >= wsupp - 1e-14:
+            distsupp.append(ii)
+            distmass.append(current - last)
+            last = current
+            if current > (1 - wsupp):
+                break
+    if distsupp[-1] < _b:
+        distsupp.append(_b)
+        distmass.append(1 - last)
+    distsupp = np.array(distsupp)
+    distmass = np.array(distmass)
+
+    # convert intervals to right-half-open as required by histogram
+    histsupp = distsupp + 1e-8
+    histsupp[0] = _a
+
+    # find sample frequencies and perform chisquare test
+    freq, hsupp = np.histogram(rvs, histsupp)
+    chis, pval = stats.chisquare(np.array(freq), len(rvs)*distmass)
+
+    npt.assert_(
+        pval > alpha,
+        f'chisquare - test for {msg} at arg = {str(arg)} with pval = {str(pval)}'
+    )
+
+
+def check_scale_docstring(distfn):
+    if distfn.__doc__ is not None:
+        # Docstrings can be stripped if interpreter is run with -OO
+        npt.assert_('scale' not in distfn.__doc__)
+
+
+@pytest.mark.parametrize('method', ['pmf', 'logpmf', 'cdf', 'logcdf',
+                                    'sf', 'logsf', 'ppf', 'isf'])
+@pytest.mark.parametrize('distname, args', distdiscrete)
+def test_methods_with_lists(method, distname, args):
+    # Test that the discrete distributions can accept Python lists
+    # as arguments.
+    try:
+        dist = getattr(stats, distname)
+    except TypeError:
+        return
+    dist_method = getattr(dist, method)
+    if method in ['ppf', 'isf']:
+        z = [0.1, 0.2]
+    else:
+        z = [0, 1]
+    p2 = [[p]*2 for p in args]
+    loc = [0, 1]
+    result = dist_method(z, *p2, loc=loc)
+    npt.assert_allclose(result,
+                        [dist_method(*v) for v in zip(z, *p2, loc)],
+                        rtol=1e-15, atol=1e-15)
+
+
+@pytest.mark.parametrize('distname, args', invdistdiscrete)
+def test_cdf_gh13280_regression(distname, args):
+    # Test for nan output when shape parameters are invalid
+    dist = getattr(stats, distname)
+    x = np.arange(-2, 15)
+    vals = dist.cdf(x, *args)
+    expected = np.nan
+    npt.assert_equal(vals, expected)
+
+
+def cases_test_discrete_integer_shapes():
+    # distributions parameters that are only allowed to be integral when
+    # fitting, but are allowed to be real as input to PDF, etc.
+    integrality_exceptions = {'nbinom': {'n'}, 'betanbinom': {'n'}}
+
+    seen = set()
+    for distname, shapes in distdiscrete:
+        if distname in seen:
+            continue
+        seen.add(distname)
+
+        try:
+            dist = getattr(stats, distname)
+        except TypeError:
+            continue
+
+        shape_info = dist._shape_info()
+
+        for i, shape in enumerate(shape_info):
+            if (shape.name in integrality_exceptions.get(distname, set()) or
+                    not shape.integrality):
+                continue
+
+            yield distname, shape.name, shapes
+
+
+@pytest.mark.parametrize('distname, shapename, shapes',
+                         cases_test_discrete_integer_shapes())
+def test_integer_shapes(distname, shapename, shapes):
+    dist = getattr(stats, distname)
+    shape_info = dist._shape_info()
+    shape_names = [shape.name for shape in shape_info]
+    i = shape_names.index(shapename)  # this element of params must be integral
+
+    shapes_copy = list(shapes)
+
+    valid_shape = shapes[i]
+    invalid_shape = valid_shape - 0.5  # arbitrary non-integral value
+    new_valid_shape = valid_shape - 1
+    shapes_copy[i] = [[valid_shape], [invalid_shape], [new_valid_shape]]
+
+    a, b = dist.support(*shapes)
+    x = np.round(np.linspace(a, b, 5))
+
+    pmf = dist.pmf(x, *shapes_copy)
+    assert not np.any(np.isnan(pmf[0, :]))
+    assert np.all(np.isnan(pmf[1, :]))
+    assert not np.any(np.isnan(pmf[2, :]))
+
+
+def test_frozen_attributes():
+    # gh-14827 reported that all frozen distributions had both pmf and pdf
+    # attributes; continuous should have pdf and discrete should have pmf.
+    message = "'rv_discrete_frozen' object has no attribute"
+    with pytest.raises(AttributeError, match=message):
+        stats.binom(10, 0.5).pdf
+    with pytest.raises(AttributeError, match=message):
+        stats.binom(10, 0.5).logpdf
+    stats.binom.pdf = "herring"
+    frozen_binom = stats.binom(10, 0.5)
+    assert isinstance(frozen_binom, rv_discrete_frozen)
+    delattr(stats.binom, 'pdf')
+
+
+@pytest.mark.parametrize('distname, shapes', distdiscrete)
+def test_interval(distname, shapes):
+    # gh-11026 reported that `interval` returns incorrect values when
+    # `confidence=1`. The values were not incorrect, but it was not intuitive
+    # that the left end of the interval should extend beyond the support of the
+    # distribution. Confirm that this is the behavior for all distributions.
+    if isinstance(distname, str):
+        dist = getattr(stats, distname)
+    else:
+        dist = distname
+    a, b = dist.support(*shapes)
+    npt.assert_equal(dist.ppf([0, 1], *shapes), (a-1, b))
+    npt.assert_equal(dist.isf([1, 0], *shapes), (a-1, b))
+    npt.assert_equal(dist.interval(1, *shapes), (a-1, b))
+
+
+@pytest.mark.xfail_on_32bit("Sensible to machine precision")
+def test_rv_sample():
+    # Thoroughly test rv_sample and check that gh-3758 is resolved
+
+    # Generate a random discrete distribution
+    rng = np.random.default_rng(98430143469)
+    xk = np.sort(rng.random(10) * 10)
+    pk = rng.random(10)
+    pk /= np.sum(pk)
+    dist = stats.rv_discrete(values=(xk, pk))
+
+    # Generate points to the left and right of xk
+    xk_left = (np.array([0] + xk[:-1].tolist()) + xk)/2
+    xk_right = (np.array(xk[1:].tolist() + [xk[-1]+1]) + xk)/2
+
+    # Generate points to the left and right of cdf
+    cdf2 = np.cumsum(pk)
+    cdf2_left = (np.array([0] + cdf2[:-1].tolist()) + cdf2)/2
+    cdf2_right = (np.array(cdf2[1:].tolist() + [1]) + cdf2)/2
+
+    # support - leftmost and rightmost xk
+    a, b = dist.support()
+    assert_allclose(a, xk[0])
+    assert_allclose(b, xk[-1])
+
+    # pmf - supported only on the xk
+    assert_allclose(dist.pmf(xk), pk)
+    assert_allclose(dist.pmf(xk_right), 0)
+    assert_allclose(dist.pmf(xk_left), 0)
+
+    # logpmf is log of the pmf; log(0) = -np.inf
+    with np.errstate(divide='ignore'):
+        assert_allclose(dist.logpmf(xk), np.log(pk))
+        assert_allclose(dist.logpmf(xk_right), -np.inf)
+        assert_allclose(dist.logpmf(xk_left), -np.inf)
+
+    # cdf - the cumulative sum of the pmf
+    assert_allclose(dist.cdf(xk), cdf2)
+    assert_allclose(dist.cdf(xk_right), cdf2)
+    assert_allclose(dist.cdf(xk_left), [0]+cdf2[:-1].tolist())
+
+    with np.errstate(divide='ignore'):
+        assert_allclose(dist.logcdf(xk), np.log(dist.cdf(xk)),
+                        atol=1e-15)
+        assert_allclose(dist.logcdf(xk_right), np.log(dist.cdf(xk_right)),
+                        atol=1e-15)
+        assert_allclose(dist.logcdf(xk_left), np.log(dist.cdf(xk_left)),
+                        atol=1e-15)
+
+    # sf is 1-cdf
+    assert_allclose(dist.sf(xk), 1-dist.cdf(xk))
+    assert_allclose(dist.sf(xk_right), 1-dist.cdf(xk_right))
+    assert_allclose(dist.sf(xk_left), 1-dist.cdf(xk_left))
+
+    with np.errstate(divide='ignore'):
+        assert_allclose(dist.logsf(xk), np.log(dist.sf(xk)),
+                        atol=1e-15)
+        assert_allclose(dist.logsf(xk_right), np.log(dist.sf(xk_right)),
+                        atol=1e-15)
+        assert_allclose(dist.logsf(xk_left), np.log(dist.sf(xk_left)),
+                        atol=1e-15)
+
+    # ppf
+    assert_allclose(dist.ppf(cdf2), xk)
+    assert_allclose(dist.ppf(cdf2_left), xk)
+    assert_allclose(dist.ppf(cdf2_right)[:-1], xk[1:])
+    assert_allclose(dist.ppf(0), a - 1)
+    assert_allclose(dist.ppf(1), b)
+
+    # isf
+    sf2 = dist.sf(xk)
+    assert_allclose(dist.isf(sf2), xk)
+    assert_allclose(dist.isf(1-cdf2_left), dist.ppf(cdf2_left))
+    assert_allclose(dist.isf(1-cdf2_right), dist.ppf(cdf2_right))
+    assert_allclose(dist.isf(0), b)
+    assert_allclose(dist.isf(1), a - 1)
+
+    # interval is (ppf(alpha/2), isf(alpha/2))
+    ps = np.linspace(0.01, 0.99, 10)
+    int2 = dist.ppf(ps/2), dist.isf(ps/2)
+    assert_allclose(dist.interval(1-ps), int2)
+    assert_allclose(dist.interval(0), dist.median())
+    assert_allclose(dist.interval(1), (a-1, b))
+
+    # median is simply ppf(0.5)
+    med2 = dist.ppf(0.5)
+    assert_allclose(dist.median(), med2)
+
+    # all four stats (mean, var, skew, and kurtosis) from the definitions
+    mean2 = np.sum(xk*pk)
+    var2 = np.sum((xk - mean2)**2 * pk)
+    skew2 = np.sum((xk - mean2)**3 * pk) / var2**(3/2)
+    kurt2 = np.sum((xk - mean2)**4 * pk) / var2**2 - 3
+    assert_allclose(dist.mean(), mean2)
+    assert_allclose(dist.std(), np.sqrt(var2))
+    assert_allclose(dist.var(), var2)
+    assert_allclose(dist.stats(moments='mvsk'), (mean2, var2, skew2, kurt2))
+
+    # noncentral moment against definition
+    mom3 = np.sum((xk**3) * pk)
+    assert_allclose(dist.moment(3), mom3)
+
+    # expect - check against moments
+    assert_allclose(dist.expect(lambda x: 1), 1)
+    assert_allclose(dist.expect(), mean2)
+    assert_allclose(dist.expect(lambda x: x**3), mom3)
+
+    # entropy is the negative of the expected value of log(p)
+    with np.errstate(divide='ignore'):
+        assert_allclose(-dist.expect(lambda x: dist.logpmf(x)), dist.entropy())
+
+    # RVS is just ppf of uniform random variates
+    rng = np.random.default_rng(98430143469)
+    rvs = dist.rvs(size=100, random_state=rng)
+    rng = np.random.default_rng(98430143469)
+    rvs0 = dist.ppf(rng.random(size=100))
+    assert_allclose(rvs, rvs0)
+
+def test__pmf_float_input():
+    # gh-21272
+    # test that `rvs()` can be computed when `_pmf` requires float input
+    
+    class rv_exponential(stats.rv_discrete):
+        def _pmf(self, i):
+            return (2/3)*3**(1 - i)
+    
+    rv = rv_exponential(a=0.0, b=float('inf'))
+    rvs = rv.rvs(random_state=42)  # should not crash due to integer input to `_pmf`
+    assert_allclose(rvs, 0)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_distns.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_distns.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9b2a40a0acccb78bf2ab2f9a0dab707eb5fea71
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_discrete_distns.py
@@ -0,0 +1,700 @@
+import pytest
+import itertools
+
+from scipy import stats
+from scipy.stats import (betabinom, betanbinom, hypergeom, nhypergeom,
+                         bernoulli, boltzmann, skellam, zipf, zipfian, binom,
+                         nbinom, nchypergeom_fisher, nchypergeom_wallenius,
+                         randint, poisson_binom)
+
+import numpy as np
+from numpy.testing import (
+    assert_almost_equal, assert_equal, assert_allclose, suppress_warnings
+)
+from scipy.special import binom as special_binom
+from scipy.optimize import root_scalar
+from scipy.integrate import quad
+
+
+# The expected values were computed with Wolfram Alpha, using
+# the expression CDF[HypergeometricDistribution[N, n, M], k].
+@pytest.mark.parametrize('k, M, n, N, expected, rtol',
+                         [(3, 10, 4, 5,
+                           0.9761904761904762, 1e-15),
+                          (107, 10000, 3000, 215,
+                           0.9999999997226765, 1e-15),
+                          (10, 10000, 3000, 215,
+                           2.681682217692179e-21, 5e-11)])
+def test_hypergeom_cdf(k, M, n, N, expected, rtol):
+    p = hypergeom.cdf(k, M, n, N)
+    assert_allclose(p, expected, rtol=rtol)
+
+
+# The expected values were computed with Wolfram Alpha, using
+# the expression SurvivalFunction[HypergeometricDistribution[N, n, M], k].
+@pytest.mark.parametrize('k, M, n, N, expected, rtol',
+                         [(25, 10000, 3000, 215,
+                           0.9999999999052958, 1e-15),
+                          (125, 10000, 3000, 215,
+                           1.4416781705752128e-18, 5e-11)])
+def test_hypergeom_sf(k, M, n, N, expected, rtol):
+    p = hypergeom.sf(k, M, n, N)
+    assert_allclose(p, expected, rtol=rtol)
+
+
+def test_hypergeom_logpmf():
+    # symmetries test
+    # f(k,N,K,n) = f(n-k,N,N-K,n) = f(K-k,N,K,N-n) = f(k,N,n,K)
+    k = 5
+    N = 50
+    K = 10
+    n = 5
+    logpmf1 = hypergeom.logpmf(k, N, K, n)
+    logpmf2 = hypergeom.logpmf(n - k, N, N - K, n)
+    logpmf3 = hypergeom.logpmf(K - k, N, K, N - n)
+    logpmf4 = hypergeom.logpmf(k, N, n, K)
+    assert_almost_equal(logpmf1, logpmf2, decimal=12)
+    assert_almost_equal(logpmf1, logpmf3, decimal=12)
+    assert_almost_equal(logpmf1, logpmf4, decimal=12)
+
+    # test related distribution
+    # Bernoulli distribution if n = 1
+    k = 1
+    N = 10
+    K = 7
+    n = 1
+    hypergeom_logpmf = hypergeom.logpmf(k, N, K, n)
+    bernoulli_logpmf = bernoulli.logpmf(k, K/N)
+    assert_almost_equal(hypergeom_logpmf, bernoulli_logpmf, decimal=12)
+
+
+def test_nhypergeom_pmf():
+    # test with hypergeom
+    M, n, r = 45, 13, 8
+    k = 6
+    NHG = nhypergeom.pmf(k, M, n, r)
+    HG = hypergeom.pmf(k, M, n, k+r-1) * (M - n - (r-1)) / (M - (k+r-1))
+    assert_allclose(HG, NHG, rtol=1e-10)
+
+
+def test_nhypergeom_pmfcdf():
+    # test pmf and cdf with arbitrary values.
+    M = 8
+    n = 3
+    r = 4
+    support = np.arange(n+1)
+    pmf = nhypergeom.pmf(support, M, n, r)
+    cdf = nhypergeom.cdf(support, M, n, r)
+    assert_allclose(pmf, [1/14, 3/14, 5/14, 5/14], rtol=1e-13)
+    assert_allclose(cdf, [1/14, 4/14, 9/14, 1.0], rtol=1e-13)
+
+
+def test_nhypergeom_r0():
+    # test with `r = 0`.
+    M = 10
+    n = 3
+    r = 0
+    pmf = nhypergeom.pmf([[0, 1, 2, 0], [1, 2, 0, 3]], M, n, r)
+    assert_allclose(pmf, [[1, 0, 0, 1], [0, 0, 1, 0]], rtol=1e-13)
+
+
+def test_nhypergeom_rvs_shape():
+    # Check that when given a size with more dimensions than the
+    # dimensions of the broadcast parameters, rvs returns an array
+    # with the correct shape.
+    x = nhypergeom.rvs(22, [7, 8, 9], [[12], [13]], size=(5, 1, 2, 3))
+    assert x.shape == (5, 1, 2, 3)
+
+
+def test_nhypergeom_accuracy():
+    # Check that nhypergeom.rvs post-gh-13431 gives the same values as
+    # inverse transform sampling
+    np.random.seed(0)
+    x = nhypergeom.rvs(22, 7, 11, size=100)
+    np.random.seed(0)
+    p = np.random.uniform(size=100)
+    y = nhypergeom.ppf(p, 22, 7, 11)
+    assert_equal(x, y)
+
+
+def test_boltzmann_upper_bound():
+    k = np.arange(-3, 5)
+
+    N = 1
+    p = boltzmann.pmf(k, 0.123, N)
+    expected = k == 0
+    assert_equal(p, expected)
+
+    lam = np.log(2)
+    N = 3
+    p = boltzmann.pmf(k, lam, N)
+    expected = [0, 0, 0, 4/7, 2/7, 1/7, 0, 0]
+    assert_allclose(p, expected, rtol=1e-13)
+
+    c = boltzmann.cdf(k, lam, N)
+    expected = [0, 0, 0, 4/7, 6/7, 1, 1, 1]
+    assert_allclose(c, expected, rtol=1e-13)
+
+
+def test_betabinom_a_and_b_unity():
+    # test limiting case that betabinom(n, 1, 1) is a discrete uniform
+    # distribution from 0 to n
+    n = 20
+    k = np.arange(n + 1)
+    p = betabinom(n, 1, 1).pmf(k)
+    expected = np.repeat(1 / (n + 1), n + 1)
+    assert_almost_equal(p, expected)
+
+
+@pytest.mark.parametrize('dtypes', itertools.product(*[(int, float)]*3))
+def test_betabinom_stats_a_and_b_integers_gh18026(dtypes):
+    # gh-18026 reported that `betabinom` kurtosis calculation fails when some
+    # parameters are integers. Check that this is resolved.
+    n_type, a_type, b_type = dtypes
+    n, a, b = n_type(10), a_type(2), b_type(3)
+    assert_allclose(betabinom.stats(n, a, b, moments='k'), -0.6904761904761907)
+
+
+def test_betabinom_bernoulli():
+    # test limiting case that betabinom(1, a, b) = bernoulli(a / (a + b))
+    a = 2.3
+    b = 0.63
+    k = np.arange(2)
+    p = betabinom(1, a, b).pmf(k)
+    expected = bernoulli(a / (a + b)).pmf(k)
+    assert_almost_equal(p, expected)
+
+
+def test_issue_10317():
+    alpha, n, p = 0.9, 10, 1
+    assert_equal(nbinom.interval(confidence=alpha, n=n, p=p), (0, 0))
+
+
+def test_issue_11134():
+    alpha, n, p = 0.95, 10, 0
+    assert_equal(binom.interval(confidence=alpha, n=n, p=p), (0, 0))
+
+
+def test_issue_7406():
+    np.random.seed(0)
+    assert_equal(binom.ppf(np.random.rand(10), 0, 0.5), 0)
+
+    # Also check that endpoints (q=0, q=1) are correct
+    assert_equal(binom.ppf(0, 0, 0.5), -1)
+    assert_equal(binom.ppf(1, 0, 0.5), 0)
+
+
+def test_issue_5122():
+    p = 0
+    n = np.random.randint(100, size=10)
+
+    x = 0
+    ppf = binom.ppf(x, n, p)
+    assert_equal(ppf, -1)
+
+    x = np.linspace(0.01, 0.99, 10)
+    ppf = binom.ppf(x, n, p)
+    assert_equal(ppf, 0)
+
+    x = 1
+    ppf = binom.ppf(x, n, p)
+    assert_equal(ppf, n)
+
+
+def test_issue_1603():
+    assert_equal(binom(1000, np.logspace(-3, -100)).ppf(0.01), 0)
+
+
+def test_issue_5503():
+    p = 0.5
+    x = np.logspace(3, 14, 12)
+    assert_allclose(binom.cdf(x, 2*x, p), 0.5, atol=1e-2)
+
+
+@pytest.mark.parametrize('x, n, p, cdf_desired', [
+    (300, 1000, 3/10, 0.51559351981411995636),
+    (3000, 10000, 3/10, 0.50493298381929698016),
+    (30000, 100000, 3/10, 0.50156000591726422864),
+    (300000, 1000000, 3/10, 0.50049331906666960038),
+    (3000000, 10000000, 3/10, 0.50015600124585261196),
+    (30000000, 100000000, 3/10, 0.50004933192735230102),
+    (30010000, 100000000, 3/10, 0.98545384016570790717),
+    (29990000, 100000000, 3/10, 0.01455017177985268670),
+    (29950000, 100000000, 3/10, 5.02250963487432024943e-28),
+])
+def test_issue_5503pt2(x, n, p, cdf_desired):
+    assert_allclose(binom.cdf(x, n, p), cdf_desired)
+
+
+def test_issue_5503pt3():
+    # From Wolfram Alpha: CDF[BinomialDistribution[1e12, 1e-12], 2]
+    assert_allclose(binom.cdf(2, 10**12, 10**-12), 0.91969860292869777384)
+
+
+def test_issue_6682():
+    # Reference value from R:
+    # options(digits=16)
+    # print(pnbinom(250, 50, 32/63, lower.tail=FALSE))
+    assert_allclose(nbinom.sf(250, 50, 32./63.), 1.460458510976452e-35)
+
+
+def test_issue_19747():
+    # test that negative k does not raise an error in nbinom.logcdf
+    result = nbinom.logcdf([5, -1, 1], 5, 0.5)
+    reference = [-0.47313352, -np.inf, -2.21297293]
+    assert_allclose(result, reference)
+
+
+def test_boost_divide_by_zero_issue_15101():
+    n = 1000
+    p = 0.01
+    k = 996
+    assert_allclose(binom.pmf(k, n, p), 0.0)
+
+
+def test_skellam_gh11474():
+    # test issue reported in gh-11474 caused by `cdfchn`
+    mu = [1, 10, 100, 1000, 5000, 5050, 5100, 5250, 6000]
+    cdf = skellam.cdf(0, mu, mu)
+    # generated in R
+    # library(skellam)
+    # options(digits = 16)
+    # mu = c(1, 10, 100, 1000, 5000, 5050, 5100, 5250, 6000)
+    # pskellam(0, mu, mu, TRUE)
+    cdf_expected = [0.6542541612768356, 0.5448901559424127, 0.5141135799745580,
+                    0.5044605891382528, 0.5019947363350450, 0.5019848365953181,
+                    0.5019750827993392, 0.5019466621805060, 0.5018209330219539]
+    assert_allclose(cdf, cdf_expected)
+
+
+class TestZipfian:
+    def test_zipfian_asymptotic(self):
+        # test limiting case that zipfian(a, n) -> zipf(a) as n-> oo
+        a = 6.5
+        N = 10000000
+        k = np.arange(1, 21)
+        assert_allclose(zipfian.pmf(k, a, N), zipf.pmf(k, a))
+        assert_allclose(zipfian.cdf(k, a, N), zipf.cdf(k, a))
+        assert_allclose(zipfian.sf(k, a, N), zipf.sf(k, a))
+        assert_allclose(zipfian.stats(a, N, moments='msvk'),
+                        zipf.stats(a, moments='msvk'))
+
+    def test_zipfian_continuity(self):
+        # test that zipfian(0.999999, n) ~ zipfian(1.000001, n)
+        # (a = 1 switches between methods of calculating harmonic sum)
+        alt1, agt1 = 0.99999999, 1.00000001
+        N = 30
+        k = np.arange(1, N + 1)
+        assert_allclose(zipfian.pmf(k, alt1, N), zipfian.pmf(k, agt1, N),
+                        rtol=5e-7)
+        assert_allclose(zipfian.cdf(k, alt1, N), zipfian.cdf(k, agt1, N),
+                        rtol=5e-7)
+        assert_allclose(zipfian.sf(k, alt1, N), zipfian.sf(k, agt1, N),
+                        rtol=5e-7)
+        assert_allclose(zipfian.stats(alt1, N, moments='msvk'),
+                        zipfian.stats(agt1, N, moments='msvk'), rtol=5e-7)
+
+    def test_zipfian_R(self):
+        # test against R VGAM package
+        # library(VGAM)
+        # k <- c(13, 16,  1,  4,  4,  8, 10, 19,  5,  7)
+        # a <- c(1.56712977, 3.72656295, 5.77665117, 9.12168729, 5.79977172,
+        #        4.92784796, 9.36078764, 4.3739616 , 7.48171872, 4.6824154)
+        # n <- c(70, 80, 48, 65, 83, 89, 50, 30, 20, 20)
+        # pmf <- dzipf(k, N = n, shape = a)
+        # cdf <- pzipf(k, N = n, shape = a)
+        # print(pmf)
+        # print(cdf)
+        np.random.seed(0)
+        k = np.random.randint(1, 20, size=10)
+        a = np.random.rand(10)*10 + 1
+        n = np.random.randint(1, 100, size=10)
+        pmf = [8.076972e-03, 2.950214e-05, 9.799333e-01, 3.216601e-06,
+               3.158895e-04, 3.412497e-05, 4.350472e-10, 2.405773e-06,
+               5.860662e-06, 1.053948e-04]
+        cdf = [0.8964133, 0.9998666, 0.9799333, 0.9999995, 0.9998584,
+               0.9999458, 1.0000000, 0.9999920, 0.9999977, 0.9998498]
+        # skip the first point; zipUC is not accurate for low a, n
+        assert_allclose(zipfian.pmf(k, a, n)[1:], pmf[1:], rtol=1e-6)
+        assert_allclose(zipfian.cdf(k, a, n)[1:], cdf[1:], rtol=5e-5)
+
+    np.random.seed(0)
+    naive_tests = np.vstack((np.logspace(-2, 1, 10),
+                             np.random.randint(2, 40, 10))).T
+
+    @pytest.mark.parametrize("a, n", naive_tests)
+    def test_zipfian_naive(self, a, n):
+        # test against bare-bones implementation
+
+        @np.vectorize
+        def Hns(n, s):
+            """Naive implementation of harmonic sum"""
+            return (1/np.arange(1, n+1)**s).sum()
+
+        @np.vectorize
+        def pzip(k, a, n):
+            """Naive implementation of zipfian pmf"""
+            if k < 1 or k > n:
+                return 0.
+            else:
+                return 1 / k**a / Hns(n, a)
+
+        k = np.arange(n+1)
+        pmf = pzip(k, a, n)
+        cdf = np.cumsum(pmf)
+        mean = np.average(k, weights=pmf)
+        var = np.average((k - mean)**2, weights=pmf)
+        std = var**0.5
+        skew = np.average(((k-mean)/std)**3, weights=pmf)
+        kurtosis = np.average(((k-mean)/std)**4, weights=pmf) - 3
+        assert_allclose(zipfian.pmf(k, a, n), pmf)
+        assert_allclose(zipfian.cdf(k, a, n), cdf)
+        assert_allclose(zipfian.stats(a, n, moments="mvsk"),
+                        [mean, var, skew, kurtosis])
+
+    def test_pmf_integer_k(self):
+        k = np.arange(0, 1000)
+        k_int32 = k.astype(np.int32)
+        dist = zipfian(111, 22)
+        pmf = dist.pmf(k)
+        pmf_k_int32 = dist.pmf(k_int32)
+        assert_equal(pmf, pmf_k_int32)
+
+
+class TestNCH:
+    np.random.seed(2)  # seeds 0 and 1 had some xl = xu; randint failed
+    shape = (2, 4, 3)
+    max_m = 100
+    m1 = np.random.randint(1, max_m, size=shape)    # red balls
+    m2 = np.random.randint(1, max_m, size=shape)    # white balls
+    N = m1 + m2                                     # total balls
+    n = randint.rvs(0, N, size=N.shape)             # number of draws
+    xl = np.maximum(0, n-m2)                        # lower bound of support
+    xu = np.minimum(n, m1)                          # upper bound of support
+    x = randint.rvs(xl, xu, size=xl.shape)
+    odds = np.random.rand(*x.shape)*2
+
+    # test output is more readable when function names (strings) are passed
+    @pytest.mark.parametrize('dist_name',
+                             ['nchypergeom_fisher', 'nchypergeom_wallenius'])
+    def test_nch_hypergeom(self, dist_name):
+        # Both noncentral hypergeometric distributions reduce to the
+        # hypergeometric distribution when odds = 1
+        dists = {'nchypergeom_fisher': nchypergeom_fisher,
+                 'nchypergeom_wallenius': nchypergeom_wallenius}
+        dist = dists[dist_name]
+        x, N, m1, n = self.x, self.N, self.m1, self.n
+        assert_allclose(dist.pmf(x, N, m1, n, odds=1),
+                        hypergeom.pmf(x, N, m1, n))
+
+    def test_nchypergeom_fisher_naive(self):
+        # test against a very simple implementation
+        x, N, m1, n, odds = self.x, self.N, self.m1, self.n, self.odds
+
+        @np.vectorize
+        def pmf_mean_var(x, N, m1, n, w):
+            # simple implementation of nchypergeom_fisher pmf
+            m2 = N - m1
+            xl = np.maximum(0, n-m2)
+            xu = np.minimum(n, m1)
+
+            def f(x):
+                t1 = special_binom(m1, x)
+                t2 = special_binom(m2, n - x)
+                return t1 * t2 * w**x
+
+            def P(k):
+                return sum(f(y)*y**k for y in range(xl, xu + 1))
+
+            P0 = P(0)
+            P1 = P(1)
+            P2 = P(2)
+            pmf = f(x) / P0
+            mean = P1 / P0
+            var = P2 / P0 - (P1 / P0)**2
+            return pmf, mean, var
+
+        pmf, mean, var = pmf_mean_var(x, N, m1, n, odds)
+        assert_allclose(nchypergeom_fisher.pmf(x, N, m1, n, odds), pmf)
+        assert_allclose(nchypergeom_fisher.stats(N, m1, n, odds, moments='m'),
+                        mean)
+        assert_allclose(nchypergeom_fisher.stats(N, m1, n, odds, moments='v'),
+                        var)
+
+    def test_nchypergeom_wallenius_naive(self):
+        # test against a very simple implementation
+
+        np.random.seed(2)
+        shape = (2, 4, 3)
+        max_m = 100
+        m1 = np.random.randint(1, max_m, size=shape)
+        m2 = np.random.randint(1, max_m, size=shape)
+        N = m1 + m2
+        n = randint.rvs(0, N, size=N.shape)
+        xl = np.maximum(0, n-m2)
+        xu = np.minimum(n, m1)
+        x = randint.rvs(xl, xu, size=xl.shape)
+        w = np.random.rand(*x.shape)*2
+
+        def support(N, m1, n, w):
+            m2 = N - m1
+            xl = np.maximum(0, n-m2)
+            xu = np.minimum(n, m1)
+            return xl, xu
+
+        @np.vectorize
+        def mean(N, m1, n, w):
+            m2 = N - m1
+            xl, xu = support(N, m1, n, w)
+
+            def fun(u):
+                return u/m1 + (1 - (n-u)/m2)**w - 1
+
+            return root_scalar(fun, bracket=(xl, xu)).root
+
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning,
+                       message="invalid value encountered in mean")
+            assert_allclose(nchypergeom_wallenius.mean(N, m1, n, w),
+                            mean(N, m1, n, w), rtol=2e-2)
+
+        @np.vectorize
+        def variance(N, m1, n, w):
+            m2 = N - m1
+            u = mean(N, m1, n, w)
+            a = u * (m1 - u)
+            b = (n-u)*(u + m2 - n)
+            return N*a*b / ((N-1) * (m1*b + m2*a))
+
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning,
+                       message="invalid value encountered in mean")
+            assert_allclose(
+                nchypergeom_wallenius.stats(N, m1, n, w, moments='v'),
+                variance(N, m1, n, w),
+                rtol=5e-2
+            )
+
+        @np.vectorize
+        def pmf(x, N, m1, n, w):
+            m2 = N - m1
+            xl, xu = support(N, m1, n, w)
+
+            def integrand(t):
+                D = w*(m1 - x) + (m2 - (n-x))
+                res = (1-t**(w/D))**x * (1-t**(1/D))**(n-x)
+                return res
+
+            def f(x):
+                t1 = special_binom(m1, x)
+                t2 = special_binom(m2, n - x)
+                the_integral = quad(integrand, 0, 1,
+                                    epsrel=1e-16, epsabs=1e-16)
+                return t1 * t2 * the_integral[0]
+
+            return f(x)
+
+        pmf0 = pmf(x, N, m1, n, w)
+        pmf1 = nchypergeom_wallenius.pmf(x, N, m1, n, w)
+
+        atol, rtol = 1e-6, 1e-6
+        i = np.abs(pmf1 - pmf0) < atol + rtol*np.abs(pmf0)
+        assert i.sum() > np.prod(shape) / 2  # works at least half the time
+
+        # for those that fail, discredit the naive implementation
+        for N, m1, n, w in zip(N[~i], m1[~i], n[~i], w[~i]):
+            # get the support
+            m2 = N - m1
+            xl, xu = support(N, m1, n, w)
+            x = np.arange(xl, xu + 1)
+
+            # calculate sum of pmf over the support
+            # the naive implementation is very wrong in these cases
+            assert pmf(x, N, m1, n, w).sum() < .5
+            assert_allclose(nchypergeom_wallenius.pmf(x, N, m1, n, w).sum(), 1)
+
+    def test_wallenius_against_mpmath(self):
+        # precompute data with mpmath since naive implementation above
+        # is not reliable. See source code in gh-13330.
+        M = 50
+        n = 30
+        N = 20
+        odds = 2.25
+        # Expected results, computed with mpmath.
+        sup = np.arange(21)
+        pmf = np.array([3.699003068656875e-20,
+                        5.89398584245431e-17,
+                        2.1594437742911123e-14,
+                        3.221458044649955e-12,
+                        2.4658279241205077e-10,
+                        1.0965862603981212e-08,
+                        3.057890479665704e-07,
+                        5.622818831643761e-06,
+                        7.056482841531681e-05,
+                        0.000618899425358671,
+                        0.003854172932571669,
+                        0.01720592676256026,
+                        0.05528844897093792,
+                        0.12772363313574242,
+                        0.21065898367825722,
+                        0.24465958845359234,
+                        0.1955114898110033,
+                        0.10355390084949237,
+                        0.03414490375225675,
+                        0.006231989845775931,
+                        0.0004715577304677075])
+        mean = 14.808018384813426
+        var = 2.6085975877923717
+
+        # nchypergeom_wallenius.pmf returns 0 for pmf(0) and pmf(1), and pmf(2)
+        # has only three digits of accuracy (~ 2.1511e-14).
+        assert_allclose(nchypergeom_wallenius.pmf(sup, M, n, N, odds), pmf,
+                        rtol=1e-13, atol=1e-13)
+        assert_allclose(nchypergeom_wallenius.mean(M, n, N, odds),
+                        mean, rtol=1e-13)
+        assert_allclose(nchypergeom_wallenius.var(M, n, N, odds),
+                        var, rtol=1e-11)
+
+    @pytest.mark.parametrize('dist_name',
+                             ['nchypergeom_fisher', 'nchypergeom_wallenius'])
+    def test_rvs_shape(self, dist_name):
+        # Check that when given a size with more dimensions than the
+        # dimensions of the broadcast parameters, rvs returns an array
+        # with the correct shape.
+        dists = {'nchypergeom_fisher': nchypergeom_fisher,
+                 'nchypergeom_wallenius': nchypergeom_wallenius}
+        dist = dists[dist_name]
+        x = dist.rvs(50, 30, [[10], [20]], [0.5, 1.0, 2.0], size=(5, 1, 2, 3))
+        assert x.shape == (5, 1, 2, 3)
+
+
+@pytest.mark.parametrize("mu, q, expected",
+                         [[10, 120, -1.240089881791596e-38],
+                          [1500, 0, -86.61466680572661]])
+def test_nbinom_11465(mu, q, expected):
+    # test nbinom.logcdf at extreme tails
+    size = 20
+    n, p = size, size/(size+mu)
+    # In R:
+    # options(digits=16)
+    # pnbinom(mu=10, size=20, q=120, log.p=TRUE)
+    assert_allclose(nbinom.logcdf(q, n, p), expected)
+
+
+def test_gh_17146():
+    # Check that discrete distributions return PMF of zero at non-integral x.
+    # See gh-17146.
+    x = np.linspace(0, 1, 11)
+    p = 0.8
+    pmf = bernoulli(p).pmf(x)
+    i = (x % 1 == 0)
+    assert_allclose(pmf[-1], p)
+    assert_allclose(pmf[0], 1-p)
+    assert_equal(pmf[~i], 0)
+
+
+class TestBetaNBinom:
+    @pytest.mark.parametrize('x, n, a, b, ref',
+                            [[5, 5e6, 5, 20, 1.1520944824139114e-107],
+                            [100, 50, 5, 20, 0.002855762954310226],
+                            [10000, 1000, 5, 20, 1.9648515726019154e-05]])
+    def test_betanbinom_pmf(self, x, n, a, b, ref):
+        # test that PMF stays accurate in the distribution tails
+        # reference values computed with mpmath
+        # from mpmath import mp
+        # mp.dps = 500
+        # def betanbinom_pmf(k, n, a, b):
+        #     k = mp.mpf(k)
+        #     a = mp.mpf(a)
+        #     b = mp.mpf(b)
+        #     n = mp.mpf(n)
+        #     return float(mp.binomial(n + k - mp.one, k)
+        #                  * mp.beta(a + n, b + k) / mp.beta(a, b))
+        assert_allclose(betanbinom.pmf(x, n, a, b), ref, rtol=1e-10)
+
+
+    @pytest.mark.parametrize('n, a, b, ref',
+                            [[10000, 5000, 50, 0.12841520515722202],
+                            [10, 9, 9, 7.9224400871459695],
+                            [100, 1000, 10, 1.5849602176622748]])
+    def test_betanbinom_kurtosis(self, n, a, b, ref):
+        # reference values were computed via mpmath
+        # from mpmath import mp
+        # def kurtosis_betanegbinom(n, a, b):
+        #     n = mp.mpf(n)
+        #     a = mp.mpf(a)
+        #     b = mp.mpf(b)
+        #     four = mp.mpf(4.)
+        #     mean = n * b / (a - mp.one)
+        #     var = (n * b * (n + a - 1.) * (a + b - 1.)
+        #            / ((a - 2.) * (a - 1.)**2.))
+        #     def f(k):
+        #         return (mp.binomial(n + k - mp.one, k)
+        #                 * mp.beta(a + n, b + k) / mp.beta(a, b)
+        #                 * (k - mean)**four)
+        #      fourth_moment = mp.nsum(f, [0, mp.inf])
+        #      return float(fourth_moment/var**2 - 3.)
+        assert_allclose(betanbinom.stats(n, a, b, moments="k"),
+                        ref, rtol=3e-15)
+
+
+class TestZipf:
+    def test_gh20692(self):
+        # test that int32 data for k generates same output as double
+        k = np.arange(0, 1000)
+        k_int32 = k.astype(np.int32)
+        dist = zipf(9)
+        pmf = dist.pmf(k)
+        pmf_k_int32 = dist.pmf(k_int32)
+        assert_equal(pmf, pmf_k_int32)
+
+
+def test_gh20048():
+    # gh-20048 reported an infinite loop in _drv2_ppfsingle
+    # check that the one identified is resolved
+    class test_dist_gen(stats.rv_discrete):
+        def _cdf(self, k):
+            return min(k / 100, 0.99)
+
+    test_dist = test_dist_gen(b=np.inf)
+
+    message = "Arguments that bracket..."
+    with pytest.raises(RuntimeError, match=message):
+        test_dist.ppf(0.999)
+
+
+class TestPoissonBinomial:
+    def test_pmf(self):
+        # Test pmf against R `poisbinom` to confirm that this is indeed the Poisson
+        # binomial distribution. Consistency of other methods and all other behavior
+        # should be covered by generic tests. (If not, please add a generic test.)
+        # Like many other distributions, no special attempt is made to be more
+        # accurate than the usual formulas provide, so we use default tolerances.
+        #
+        # library(poisbinom)
+        # options(digits=16)
+        # k = c(0, 1, 2, 3, 4)
+        # p = c(0.9480654803913988, 0.052428488100509374,
+        #       0.25863527358887417, 0.057764076043633206)
+        # dpoisbinom(k, p)
+        rng = np.random.default_rng(259823598254)
+        n = rng.integers(10)  # 4
+        k = np.arange(n + 1)
+        p = rng.random(n)  #  [0.9480654803913988, 0.052428488100509374,
+                           #   0.25863527358887417, 0.057764076043633206]
+        res = poisson_binom.pmf(k, p)
+        ref = [0.0343763443678060318, 0.6435428452689714307, 0.2936345519235536994,
+               0.0277036647503902354, 0.0007425936892786034]
+        assert_allclose(res, ref)
+
+
+class TestRandInt:
+    def test_gh19759(self):
+        # test zero PMF values within the support reported by gh-19759
+        a = -354
+        max_range = abs(a)
+        all_b_1 = [a + 2 ** 31 + i for i in range(max_range)]
+        res = randint.pmf(325, a, all_b_1)
+        assert (res > 0).all()
+        ref = 1 / (np.asarray(all_b_1, dtype=np.float64) - a)
+        assert_allclose(res, ref)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_distributions.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_distributions.py
new file mode 100644
index 0000000000000000000000000000000000000000..d874eb57e1f56fb61a31e12c2204832ff7209c3e
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_distributions.py
@@ -0,0 +1,10380 @@
+"""
+Test functions for stats module
+"""
+import warnings
+import re
+import sys
+import pickle
+from pathlib import Path
+import os
+import json
+import platform
+
+from numpy.testing import (assert_equal, assert_array_equal,
+                           assert_almost_equal, assert_array_almost_equal,
+                           assert_allclose, assert_, assert_warns,
+                           assert_array_less, suppress_warnings,
+                           assert_array_max_ulp, IS_PYPY)
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+from numpy import typecodes, array
+from numpy.lib.recfunctions import rec_append_fields
+from scipy import special
+from scipy._lib._util import check_random_state
+from scipy.integrate import (IntegrationWarning, quad, trapezoid,
+                             cumulative_trapezoid)
+import scipy.stats as stats
+from scipy.stats._distn_infrastructure import argsreduce
+from scipy.stats._constants import _XMAX
+import scipy.stats.distributions
+
+from scipy.special import xlogy, polygamma, entr
+from scipy.stats._distr_params import distcont, invdistcont
+from .test_discrete_basic import distdiscrete, invdistdiscrete
+from scipy.stats._continuous_distns import FitDataError, _argus_phi
+from scipy.optimize import root, fmin, differential_evolution
+from itertools import product
+
+# python -OO strips docstrings
+DOCSTRINGS_STRIPPED = sys.flags.optimize > 1
+
+# Failing on macOS 11, Intel CPUs. See gh-14901
+MACOS_INTEL = (sys.platform == 'darwin') and (platform.machine() == 'x86_64')
+
+
+# distributions to skip while testing the fix for the support method
+# introduced in gh-13294. These distributions are skipped as they
+# always return a non-nan support for every parametrization.
+skip_test_support_gh13294_regression = ['tukeylambda', 'pearson3']
+
+
+def _assert_hasattr(a, b, msg=None):
+    if msg is None:
+        msg = f'{a} does not have attribute {b}'
+    assert_(hasattr(a, b), msg=msg)
+
+
+def test_api_regression():
+    # https://github.com/scipy/scipy/issues/3802
+    _assert_hasattr(scipy.stats.distributions, 'f_gen')
+
+
+def test_distributions_submodule():
+    actual = set(scipy.stats.distributions.__all__)
+    continuous = [dist[0] for dist in distcont]    # continuous dist names
+    discrete = [dist[0] for dist in distdiscrete]  # discrete dist names
+    other = ['rv_discrete', 'rv_continuous', 'rv_histogram',
+             'entropy', 'trapz']
+    expected = continuous + discrete + other
+
+    # need to remove, e.g.,
+    # 
+    expected = set(filter(lambda s: not str(s).startswith('<'), expected))
+
+    assert actual == expected
+
+
+class TestVonMises:
+    @pytest.mark.parametrize('k', [0.1, 1, 101])
+    @pytest.mark.parametrize('x', [0, 1, np.pi, 10, 100])
+    def test_vonmises_periodic(self, k, x):
+        def check_vonmises_pdf_periodic(k, L, s, x):
+            vm = stats.vonmises(k, loc=L, scale=s)
+            assert_almost_equal(vm.pdf(x), vm.pdf(x % (2 * np.pi * s)))
+
+        def check_vonmises_cdf_periodic(k, L, s, x):
+            vm = stats.vonmises(k, loc=L, scale=s)
+            assert_almost_equal(vm.cdf(x) % 1,
+                                vm.cdf(x % (2 * np.pi * s)) % 1)
+
+        check_vonmises_pdf_periodic(k, 0, 1, x)
+        check_vonmises_pdf_periodic(k, 1, 1, x)
+        check_vonmises_pdf_periodic(k, 0, 10, x)
+
+        check_vonmises_cdf_periodic(k, 0, 1, x)
+        check_vonmises_cdf_periodic(k, 1, 1, x)
+        check_vonmises_cdf_periodic(k, 0, 10, x)
+
+    def test_vonmises_line_support(self):
+        assert_equal(stats.vonmises_line.a, -np.pi)
+        assert_equal(stats.vonmises_line.b, np.pi)
+
+    def test_vonmises_numerical(self):
+        vm = stats.vonmises(800)
+        assert_almost_equal(vm.cdf(0), 0.5)
+
+    # Expected values of the vonmises PDF were computed using
+    # mpmath with 50 digits of precision:
+    #
+    # def vmpdf_mp(x, kappa):
+    #     x = mpmath.mpf(x)
+    #     kappa = mpmath.mpf(kappa)
+    #     num = mpmath.exp(kappa*mpmath.cos(x))
+    #     den = 2 * mpmath.pi * mpmath.besseli(0, kappa)
+    #     return num/den
+
+    @pytest.mark.parametrize('x, kappa, expected_pdf',
+                             [(0.1, 0.01, 0.16074242744907072),
+                              (0.1, 25.0, 1.7515464099118245),
+                              (0.1, 800, 0.2073272544458798),
+                              (2.0, 0.01, 0.15849003875385817),
+                              (2.0, 25.0, 8.356882934278192e-16),
+                              (2.0, 800, 0.0)])
+    def test_vonmises_pdf(self, x, kappa, expected_pdf):
+        pdf = stats.vonmises.pdf(x, kappa)
+        assert_allclose(pdf, expected_pdf, rtol=1e-15)
+
+    # Expected values of the vonmises entropy were computed using
+    # mpmath with 50 digits of precision:
+    #
+    # def vonmises_entropy(kappa):
+    #     kappa = mpmath.mpf(kappa)
+    #     return (-kappa * mpmath.besseli(1, kappa) /
+    #             mpmath.besseli(0, kappa) + mpmath.log(2 * mpmath.pi *
+    #             mpmath.besseli(0, kappa)))
+    # >>> float(vonmises_entropy(kappa))
+
+    @pytest.mark.parametrize('kappa, expected_entropy',
+                             [(1, 1.6274014590199897),
+                              (5, 0.6756431570114528),
+                              (100, -0.8811275441649473),
+                              (1000, -2.03468891852547),
+                              (2000, -2.3813876496587847)])
+    def test_vonmises_entropy(self, kappa, expected_entropy):
+        entropy = stats.vonmises.entropy(kappa)
+        assert_allclose(entropy, expected_entropy, rtol=1e-13)
+
+    def test_vonmises_rvs_gh4598(self):
+        # check that random variates wrap around as discussed in gh-4598
+        seed = 30899520
+        rng1 = np.random.default_rng(seed)
+        rng2 = np.random.default_rng(seed)
+        rng3 = np.random.default_rng(seed)
+        rvs1 = stats.vonmises(1, loc=0, scale=1).rvs(random_state=rng1)
+        rvs2 = stats.vonmises(1, loc=2*np.pi, scale=1).rvs(random_state=rng2)
+        rvs3 = stats.vonmises(1, loc=0,
+                              scale=(2*np.pi/abs(rvs1)+1)).rvs(random_state=rng3)
+        assert_allclose(rvs1, rvs2, atol=1e-15)
+        assert_allclose(rvs1, rvs3, atol=1e-15)
+
+    # Expected values of the vonmises LOGPDF were computed
+    # using wolfram alpha:
+    # kappa * cos(x) - log(2*pi*I0(kappa))
+    @pytest.mark.parametrize('x, kappa, expected_logpdf',
+                             [(0.1, 0.01, -1.8279520246003170),
+                              (0.1, 25.0, 0.5604990605420549),
+                              (0.1, 800, -1.5734567947337514),
+                              (2.0, 0.01, -1.8420635346185686),
+                              (2.0, 25.0, -34.7182759850871489),
+                              (2.0, 800, -1130.4942582548682739)])
+    def test_vonmises_logpdf(self, x, kappa, expected_logpdf):
+        logpdf = stats.vonmises.logpdf(x, kappa)
+        assert_allclose(logpdf, expected_logpdf, rtol=1e-15)
+
+    def test_vonmises_expect(self):
+        """
+        Test that the vonmises expectation values are
+        computed correctly.  This test checks that the
+        numeric integration estimates the correct normalization
+        (1) and mean angle (loc).  These expectations are
+        independent of the chosen 2pi interval.
+        """
+        rng = np.random.default_rng(6762668991392531563)
+
+        loc, kappa, lb = rng.random(3) * 10
+        res = stats.vonmises(loc=loc, kappa=kappa).expect(lambda x: 1)
+        assert_allclose(res, 1)
+        assert np.issubdtype(res.dtype, np.floating)
+
+        bounds = lb, lb + 2 * np.pi
+        res = stats.vonmises(loc=loc, kappa=kappa).expect(lambda x: 1, *bounds)
+        assert_allclose(res, 1)
+        assert np.issubdtype(res.dtype, np.floating)
+
+        bounds = lb, lb + 2 * np.pi
+        res = stats.vonmises(loc=loc, kappa=kappa).expect(lambda x: np.exp(1j*x),
+                                                          *bounds, complex_func=1)
+        assert_allclose(np.angle(res), loc % (2*np.pi))
+        assert np.issubdtype(res.dtype, np.complexfloating)
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize("rvs_loc", [0, 2])
+    @pytest.mark.parametrize("rvs_shape", [1, 100, 1e8])
+    @pytest.mark.parametrize('fix_loc', [True, False])
+    @pytest.mark.parametrize('fix_shape', [True, False])
+    def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_shape,
+                                    fix_loc, fix_shape):
+        if fix_shape and fix_loc:
+            pytest.skip("Nothing to fit.")
+
+        rng = np.random.default_rng(6762668991392531563)
+        data = stats.vonmises.rvs(rvs_shape, size=1000, loc=rvs_loc,
+                                  random_state=rng)
+
+        kwds = {'fscale': 1}
+        if fix_loc:
+            kwds['floc'] = rvs_loc
+        if fix_shape:
+            kwds['f0'] = rvs_shape
+
+        _assert_less_or_close_loglike(stats.vonmises, data,
+                                      stats.vonmises.nnlf, **kwds)
+
+    @pytest.mark.slow
+    def test_vonmises_fit_bad_floc(self):
+        data = [-0.92923506, -0.32498224, 0.13054989, -0.97252014, 2.79658071,
+                -0.89110948, 1.22520295, 1.44398065, 2.49163859, 1.50315096,
+                3.05437696, -2.73126329, -3.06272048, 1.64647173, 1.94509247,
+                -1.14328023, 0.8499056, 2.36714682, -1.6823179, -0.88359996]
+        data = np.asarray(data)
+        loc = -0.5 * np.pi
+        kappa_fit, loc_fit, scale_fit = stats.vonmises.fit(data, floc=loc)
+        assert kappa_fit == np.finfo(float).tiny
+        _assert_less_or_close_loglike(stats.vonmises, data,
+                                      stats.vonmises.nnlf, fscale=1, floc=loc)
+
+    @pytest.mark.parametrize('sign', [-1, 1])
+    def test_vonmises_fit_unwrapped_data(self, sign):
+        rng = np.random.default_rng(6762668991392531563)
+        data = stats.vonmises(loc=sign*0.5*np.pi, kappa=10).rvs(100000,
+                                                                random_state=rng)
+        shifted_data = data + 4*np.pi
+        kappa_fit, loc_fit, scale_fit = stats.vonmises.fit(data)
+        kappa_fit_shifted, loc_fit_shifted, _ = stats.vonmises.fit(shifted_data)
+        assert_allclose(loc_fit, loc_fit_shifted)
+        assert_allclose(kappa_fit, kappa_fit_shifted)
+        assert scale_fit == 1
+        assert -np.pi < loc_fit < np.pi
+
+    def test_vonmises_kappa_0_gh18166(self):
+        # Check that kappa = 0 is supported.
+        dist = stats.vonmises(0)
+        assert_allclose(dist.pdf(0), 1 / (2 * np.pi), rtol=1e-15)
+        assert_allclose(dist.cdf(np.pi/2), 0.75, rtol=1e-15)
+        assert_allclose(dist.sf(-np.pi/2), 0.75, rtol=1e-15)
+        assert_allclose(dist.ppf(0.9), np.pi*0.8, rtol=1e-15)
+        assert_allclose(dist.mean(), 0, atol=1e-15)
+        assert_allclose(dist.expect(), 0, atol=1e-15)
+        assert np.all(np.abs(dist.rvs(size=10, random_state=1234)) <= np.pi)
+
+    def test_vonmises_fit_equal_data(self):
+        # When all data are equal, expect kappa = 1e16.
+        kappa, loc, scale = stats.vonmises.fit([0])
+        assert kappa == 1e16 and loc == 0 and scale == 1
+
+    def test_vonmises_fit_bounds(self):
+        # For certain input data, the root bracket is violated numerically.
+        # Test that this situation is handled.  The input data below are
+        # crafted to trigger the bound violation for the current choice of
+        # bounds and the specific way the bounds and the objective function
+        # are computed.
+
+        # Test that no exception is raised when the lower bound is violated.
+        scipy.stats.vonmises.fit([0, 3.7e-08], floc=0)
+
+        # Test that no exception is raised when the upper bound is violated.
+        scipy.stats.vonmises.fit([np.pi/2*(1-4.86e-9)], floc=0)
+
+
+def _assert_less_or_close_loglike(dist, data, func=None, maybe_identical=False,
+                                  **kwds):
+    """
+    This utility function checks that the negative log-likelihood function
+    (or `func`) of the result computed using dist.fit() is less than or equal
+    to the result computed using the generic fit method.  Because of
+    normal numerical imprecision, the "equality" check is made using
+    `np.allclose` with a relative tolerance of 1e-15.
+    """
+    if func is None:
+        func = dist.nnlf
+
+    mle_analytical = dist.fit(data, **kwds)
+    numerical_opt = super(type(dist), dist).fit(data, **kwds)
+
+    # Sanity check that the analytical MLE is actually executed.
+    # Due to floating point arithmetic, the generic MLE is unlikely
+    # to produce the exact same result as the analytical MLE.
+    if not maybe_identical:
+        assert np.any(mle_analytical != numerical_opt)
+
+    ll_mle_analytical = func(mle_analytical, data)
+    ll_numerical_opt = func(numerical_opt, data)
+    assert (ll_mle_analytical <= ll_numerical_opt or
+            np.allclose(ll_mle_analytical, ll_numerical_opt, rtol=1e-15))
+
+    # Ideally we'd check that shapes are correctly fixed, too, but that is
+    # complicated by the many ways of fixing them (e.g. f0, fix_a, fa).
+    if 'floc' in kwds:
+        assert mle_analytical[-2] == kwds['floc']
+    if 'fscale' in kwds:
+        assert mle_analytical[-1] == kwds['fscale']
+
+
+def assert_fit_warnings(dist):
+    param = ['floc', 'fscale']
+    if dist.shapes:
+        nshapes = len(dist.shapes.split(","))
+        param += ['f0', 'f1', 'f2'][:nshapes]
+    all_fixed = dict(zip(param, np.arange(len(param))))
+    data = [1, 2, 3]
+    with pytest.raises(RuntimeError,
+                       match="All parameters fixed. There is nothing "
+                       "to optimize."):
+        dist.fit(data, **all_fixed)
+    with pytest.raises(ValueError,
+                       match="The data contains non-finite values"):
+        dist.fit([np.nan])
+    with pytest.raises(ValueError,
+                       match="The data contains non-finite values"):
+        dist.fit([np.inf])
+    with pytest.raises(TypeError, match="Unknown keyword arguments:"):
+        dist.fit(data, extra_keyword=2)
+    with pytest.raises(TypeError, match="Too many positional arguments."):
+        dist.fit(data, *[1]*(len(param) - 1))
+
+
+@pytest.mark.parametrize('dist',
+                         ['alpha', 'betaprime',
+                          'fatiguelife', 'invgamma', 'invgauss', 'invweibull',
+                          'johnsonsb', 'levy', 'levy_l', 'lognorm', 'gibrat',
+                          'powerlognorm', 'rayleigh', 'wald'])
+def test_support(dist):
+    """gh-6235"""
+    dct = dict(distcont)
+    args = dct[dist]
+
+    dist = getattr(stats, dist)
+
+    assert_almost_equal(dist.pdf(dist.a, *args), 0)
+    assert_equal(dist.logpdf(dist.a, *args), -np.inf)
+    assert_almost_equal(dist.pdf(dist.b, *args), 0)
+    assert_equal(dist.logpdf(dist.b, *args), -np.inf)
+
+
+class TestRandInt:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.randint.rvs(5, 30, size=100)
+        assert_(np.all(vals < 30) & np.all(vals >= 5))
+        assert_(len(vals) == 100)
+        vals = stats.randint.rvs(5, 30, size=(2, 50))
+        assert_(np.shape(vals) == (2, 50))
+        assert_(vals.dtype.char in typecodes['AllInteger'])
+        val = stats.randint.rvs(15, 46)
+        assert_((val >= 15) & (val < 46))
+        assert_(isinstance(val, np.ScalarType), msg=repr(type(val)))
+        val = stats.randint(15, 46).rvs(3)
+        assert_(val.dtype.char in typecodes['AllInteger'])
+
+    def test_pdf(self):
+        k = np.r_[0:36]
+        out = np.where((k >= 5) & (k < 30), 1.0/(30-5), 0)
+        vals = stats.randint.pmf(k, 5, 30)
+        assert_array_almost_equal(vals, out)
+
+    def test_cdf(self):
+        x = np.linspace(0, 36, 100)
+        k = np.floor(x)
+        out = np.select([k >= 30, k >= 5], [1.0, (k-5.0+1)/(30-5.0)], 0)
+        vals = stats.randint.cdf(x, 5, 30)
+        assert_array_almost_equal(vals, out, decimal=12)
+
+
+class TestBinom:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.binom.rvs(10, 0.75, size=(2, 50))
+        assert_(np.all(vals >= 0) & np.all(vals <= 10))
+        assert_(np.shape(vals) == (2, 50))
+        assert_(vals.dtype.char in typecodes['AllInteger'])
+        val = stats.binom.rvs(10, 0.75)
+        assert_(isinstance(val, int))
+        val = stats.binom(10, 0.75).rvs(3)
+        assert_(isinstance(val, np.ndarray))
+        assert_(val.dtype.char in typecodes['AllInteger'])
+
+    def test_pmf(self):
+        # regression test for Ticket #1842
+        vals1 = stats.binom.pmf(100, 100, 1)
+        vals2 = stats.binom.pmf(0, 100, 0)
+        assert_allclose(vals1, 1.0, rtol=1e-15, atol=0)
+        assert_allclose(vals2, 1.0, rtol=1e-15, atol=0)
+
+    def test_entropy(self):
+        # Basic entropy tests.
+        b = stats.binom(2, 0.5)
+        expected_p = np.array([0.25, 0.5, 0.25])
+        expected_h = -sum(xlogy(expected_p, expected_p))
+        h = b.entropy()
+        assert_allclose(h, expected_h)
+
+        b = stats.binom(2, 0.0)
+        h = b.entropy()
+        assert_equal(h, 0.0)
+
+        b = stats.binom(2, 1.0)
+        h = b.entropy()
+        assert_equal(h, 0.0)
+
+    def test_warns_p0(self):
+        # no spurious warnings are generated for p=0; gh-3817
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", RuntimeWarning)
+            assert_equal(stats.binom(n=2, p=0).mean(), 0)
+            assert_equal(stats.binom(n=2, p=0).std(), 0)
+
+    def test_ppf_p1(self):
+        # Check that gh-17388 is resolved: PPF == n when p = 1
+        n = 4
+        assert stats.binom.ppf(q=0.3, n=n, p=1.0) == n
+
+    def test_pmf_poisson(self):
+        # Check that gh-17146 is resolved: binom -> poisson
+        n = 1541096362225563.0
+        p = 1.0477878413173978e-18
+        x = np.arange(3)
+        res = stats.binom.pmf(x, n=n, p=p)
+        ref = stats.poisson.pmf(x, n * p)
+        assert_allclose(res, ref, atol=1e-16)
+
+    def test_pmf_cdf(self):
+        # Check that gh-17809 is resolved: binom.pmf(0) ~ binom.cdf(0)
+        n = 25.0 * 10 ** 21
+        p = 1.0 * 10 ** -21
+        r = 0
+        res = stats.binom.pmf(r, n, p)
+        ref = stats.binom.cdf(r, n, p)
+        assert_allclose(res, ref, atol=1e-16)
+
+    def test_pmf_gh15101(self):
+        # Check that gh-15101 is resolved (no divide warnings when p~1, n~oo)
+        res = stats.binom.pmf(3, 2000, 0.999)
+        assert_allclose(res, 0, atol=1e-16)
+
+
+class TestArcsine:
+
+    def test_endpoints(self):
+        # Regression test for gh-13697.  The following calculation
+        # should not generate a warning.
+        p = stats.arcsine.pdf([0, 1])
+        assert_equal(p, [np.inf, np.inf])
+
+
+class TestBernoulli:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.bernoulli.rvs(0.75, size=(2, 50))
+        assert_(np.all(vals >= 0) & np.all(vals <= 1))
+        assert_(np.shape(vals) == (2, 50))
+        assert_(vals.dtype.char in typecodes['AllInteger'])
+        val = stats.bernoulli.rvs(0.75)
+        assert_(isinstance(val, int))
+        val = stats.bernoulli(0.75).rvs(3)
+        assert_(isinstance(val, np.ndarray))
+        assert_(val.dtype.char in typecodes['AllInteger'])
+
+    def test_entropy(self):
+        # Simple tests of entropy.
+        b = stats.bernoulli(0.25)
+        expected_h = -0.25*np.log(0.25) - 0.75*np.log(0.75)
+        h = b.entropy()
+        assert_allclose(h, expected_h)
+
+        b = stats.bernoulli(0.0)
+        h = b.entropy()
+        assert_equal(h, 0.0)
+
+        b = stats.bernoulli(1.0)
+        h = b.entropy()
+        assert_equal(h, 0.0)
+
+
+class TestBradford:
+    # gh-6216
+    def test_cdf_ppf(self):
+        c = 0.1
+        x = np.logspace(-20, -4)
+        q = stats.bradford.cdf(x, c)
+        xx = stats.bradford.ppf(q, c)
+        assert_allclose(x, xx)
+
+
+class TestCauchy:
+
+    def test_pdf_no_overflow_warning(self):
+        # The argument is large enough that x**2 will overflow to
+        # infinity and 1/(1 + x**2) will be 0.  This should not
+        # trigger a warning.
+        p = stats.cauchy.pdf(1e200)
+        assert p == 0.0
+
+    # Reference values were computed with mpmath.
+    @pytest.mark.parametrize(
+        'x, ref',
+        [(0.0, -1.1447298858494002),
+         (5e-324, -1.1447298858494002),
+         (1e-34, -1.1447298858494002),
+         (2.2e-16, -1.1447298858494002),
+         (2e-8, -1.1447298858494006),
+         (5e-4, -1.144730135849369),
+         (0.1, -1.1546802167025683),
+         (1.5, -2.3233848821910463),
+         (2e18, -85.42408759475494),
+         (1e200, -922.1787670834676),
+         (_XMAX, -1420.7101556726175)])
+    def test_logpdf(self, x, ref):
+        logp = stats.cauchy.logpdf([x, -x])
+        assert_allclose(logp, [ref, ref], rtol=1e-15)
+
+    # Reference values were computed with mpmath.
+    @pytest.mark.parametrize(
+        'x, ref',
+        [(-5e15, 6.366197723675814e-17),
+         (-5, 0.06283295818900118),
+         (-1, 0.25),
+         (0, 0.5),
+         (1, 0.75),
+         (5, 0.9371670418109989),
+         (5e15, 0.9999999999999999)]
+    )
+    @pytest.mark.parametrize(
+        'method, sgn',
+        [(stats.cauchy.cdf, 1),
+         (stats.cauchy.sf, -1)]
+    )
+    def test_cdf_sf(self, x, ref, method, sgn):
+        p = method(sgn*x)
+        assert_allclose(p, ref, rtol=1e-15)
+
+    # Reference values were computed with mpmath.
+    @pytest.mark.parametrize('x, ref',
+                            [(4e250, -7.957747154594767e-252),
+                             (1e25, -3.1830988618379063e-26),
+                             (10.0, -0.03223967552667532),
+                             (0.0, -0.6931471805599453),
+                             (-10.0, -3.4506339556469654),
+                             (-7e45, -106.70696921963678),
+                             (-3e225, -520.3249880981778)])
+    def test_logcdf_logsf(self, x, ref):
+        logcdf = stats.cauchy.logcdf(x)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+        logsf = stats.cauchy.logsf(-x)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+    # Reference values were computed with mpmath.
+    @pytest.mark.parametrize(
+        'p, ref',
+        [(1e-20, -3.1830988618379067e+19),
+         (1e-9, -318309886.1837906),
+         (0.25, -1.0),
+         (0.50, 0.0),
+         (0.75, 1.0),
+         (0.999999, 318309.88617359026),
+         (0.999999999999, 318316927901.77966)]
+    )
+    @pytest.mark.parametrize(
+        'method, sgn',
+        [(stats.cauchy.ppf, 1),
+         (stats.cauchy.isf, -1)])
+    def test_ppf_isf(self, p, ref, method, sgn):
+        x = sgn*method(p)
+        assert_allclose(x, ref, rtol=1e-15)
+
+
+class TestChi:
+
+    # "Exact" value of chi.sf(10, 4), as computed by Wolfram Alpha with
+    #     1 - CDF[ChiDistribution[4], 10]
+    CHI_SF_10_4 = 9.83662422461598e-21
+    # "Exact" value of chi.mean(df=1000) as computed by Wolfram Alpha with
+    #       Mean[ChiDistribution[1000]]
+    CHI_MEAN_1000 = 31.614871896980
+
+    def test_sf(self):
+        s = stats.chi.sf(10, 4)
+        assert_allclose(s, self.CHI_SF_10_4, rtol=1e-15)
+
+    def test_isf(self):
+        x = stats.chi.isf(self.CHI_SF_10_4, 4)
+        assert_allclose(x, 10, rtol=1e-15)
+
+    def test_logcdf(self):
+        x = 10.0
+        df = 15
+        logcdf = stats.chi.logcdf(x, df)
+        # Reference value computed with mpath.
+        assert_allclose(logcdf, -1.304704343625153e-14, rtol=5e-15)
+
+    def test_logsf(self):
+        x = 0.01
+        df = 15
+        logsf = stats.chi.logsf(x, df)
+        # Reference value computed with mpath.
+        assert_allclose(logsf, -3.936060782678026e-37, rtol=5e-15)
+
+    # reference value for 1e14 was computed via mpmath
+    # from mpmath import mp
+    # mp.dps = 500
+    # df = mp.mpf(1e14)
+    # float(mp.rf(mp.mpf(0.5) * df, mp.mpf(0.5)) * mp.sqrt(2.))
+
+    @pytest.mark.parametrize('df, ref',
+                             [(1e3, CHI_MEAN_1000),
+                              (1e14, 9999999.999999976)])
+    def test_mean(self, df, ref):
+        assert_allclose(stats.chi.mean(df), ref, rtol=1e-12)
+
+    # Entropy references values were computed with the following mpmath code
+    # from mpmath import mp
+    # mp.dps = 50
+    # def chi_entropy_mpmath(df):
+    #     df = mp.mpf(df)
+    #     half_df = 0.5 * df
+    #     entropy = mp.log(mp.gamma(half_df)) + 0.5 * \
+    #               (df - mp.log(2) - (df - mp.one) * mp.digamma(half_df))
+    #     return float(entropy)
+
+    @pytest.mark.parametrize('df, ref',
+                             [(1e-4, -9989.7316027504),
+                              (1, 0.7257913526447274),
+                              (1e3, 1.0721981095025448),
+                              (1e10, 1.0723649429080335),
+                              (1e100, 1.0723649429247002)])
+    def test_entropy(self, df, ref):
+        assert_allclose(stats.chi(df).entropy(), ref, rtol=1e-15)
+
+
+class TestCrystalBall:
+
+    def test_pdf(self):
+        """
+        All values are calculated using the independent implementation of the
+        ROOT framework (see https://root.cern.ch/).
+        Corresponding ROOT code is given in the comments.
+        """
+        X = np.linspace(-5.0, 5.0, 21)[:-1]
+
+        # for (double x = -5.0; x < 5.0; x += 0.5) {
+        #     cout << setprecision(16)
+        #          << ROOT::Math::crystalball_pdf(x, 1.0, 2.0, 1.0)
+        #          << ", ";
+        # }
+        calculated = stats.crystalball.pdf(X, beta=1.0, m=2.0)
+        expected = np.array([0.02028666423671257, 0.02414280702550917,
+                             0.02921279650086611, 0.03606518086526679,
+                             0.04564499453260328, 0.05961795204258388,
+                             0.08114665694685029, 0.1168511860034644,
+                             0.1825799781304131, 0.2656523006609301,
+                             0.3010234935475763, 0.2656523006609301,
+                             0.1825799781304131, 0.09772801991305094,
+                             0.0407390997601359, 0.01322604925508607,
+                             0.003344068947749631, 0.0006584862184997063,
+                             0.0001009821322058648, 1.206059579124873e-05])
+        assert_allclose(expected, calculated, rtol=1e-14)
+
+        # for (double x = -5.0; x < 5.0; x += 0.5) {
+        #     cout << setprecision(16)
+        #          << ROOT::Math::crystalball_pdf(x, 2.0, 3.0, 1.0)
+        #          << ", ";
+        # }
+        calculated = stats.crystalball.pdf(X, beta=2.0, m=3.0)
+        expected = np.array([0.00196480373120913, 0.0027975428126005,
+                             0.004175923965164595, 0.006631212592830816,
+                             0.01145873536041165, 0.022380342500804,
+                             0.05304970074264653, 0.1272596164638828,
+                             0.237752264003024, 0.3459275029304401,
+                             0.3919872148188981, 0.3459275029304401,
+                             0.237752264003024, 0.1272596164638828,
+                             0.05304970074264653, 0.01722271623872227,
+                             0.004354584612458383, 0.0008574685508575863,
+                             0.000131497061187334, 1.570508433595375e-05])
+        assert_allclose(expected, calculated, rtol=1e-14)
+
+        # for (double x = -5.0; x < 5.0; x += 0.5) {
+        #   cout << setprecision(16)
+        #        << ROOT::Math::crystalball_pdf(x, 2.0, 3.0, 2.0, 0.5)
+        #        << ", ";
+        # }
+        calculated = stats.crystalball.pdf(X, beta=2.0, m=3.0, loc=0.5, scale=2.0)
+        expected = np.array([0.007859214924836521, 0.011190171250402,
+                             0.01670369586065838, 0.02652485037132326,
+                             0.04238659020399594, 0.06362980823194138,
+                             0.08973241216601403, 0.118876132001512,
+                             0.1479437366093383, 0.17296375146522,
+                             0.1899635180461471, 0.1959936074094491,
+                             0.1899635180461471, 0.17296375146522,
+                             0.1479437366093383, 0.118876132001512,
+                             0.08973241216601403, 0.06362980823194138,
+                             0.04238659020399594, 0.02652485037132326])
+        assert_allclose(expected, calculated, rtol=1e-14)
+
+    def test_cdf(self):
+        """
+        All values are calculated using the independent implementation of the
+        ROOT framework (see https://root.cern.ch/).
+        Corresponding ROOT code is given in the comments.
+        """
+        X = np.linspace(-5.0, 5.0, 21)[:-1]
+
+        # for (double x = -5.0; x < 5.0; x += 0.5) {
+        #     cout << setprecision(16)
+        #          << ROOT::Math::crystalball_cdf(x, 1.0, 2.0, 1.0)
+        #          << ", ";
+        # }
+        calculated = stats.crystalball.cdf(X, beta=1.0, m=2.0)
+        expected = np.array([0.1217199854202754, 0.1327854386403005,
+                             0.1460639825043305, 0.1622933138937006,
+                             0.1825799781304132, 0.2086628321490436,
+                             0.2434399708405509, 0.292127965008661,
+                             0.3651599562608263, 0.4782542338198316,
+                             0.6227229998727213, 0.7671917659256111,
+                             0.8802860434846165, 0.9495903590367718,
+                             0.9828337969321823, 0.9953144721881936,
+                             0.9989814290402977, 0.9998244687978383,
+                             0.9999761023377818, 0.9999974362721522])
+        assert_allclose(expected, calculated, rtol=1e-13)
+
+        # for (double x = -5.0; x < 5.0; x += 0.5) {
+        #     cout << setprecision(16)
+        #          << ROOT::Math::crystalball_cdf(x, 2.0, 3.0, 1.0)
+        #          << ", ";
+        # }
+        calculated = stats.crystalball.cdf(X, beta=2.0, m=3.0)
+        expected = np.array([0.004420808395220632, 0.005595085625200946,
+                             0.007307866939038177, 0.009946818889246312,
+                             0.01432341920051472, 0.02238034250080412,
+                             0.03978727555698502, 0.08307626432678494,
+                             0.1733230597116304, 0.3205923321191123,
+                             0.508716882020547, 0.6968414319219818,
+                             0.8441107043294638, 0.934357499714309,
+                             0.9776464884841091, 0.9938985925142876,
+                             0.9986736357721329, 0.9997714265214375,
+                             0.9999688809071239, 0.9999966615611068])
+        assert_allclose(expected, calculated, rtol=1e-13)
+
+        # for (double x = -5.0; x < 5.0; x += 0.5) {
+        #     cout << setprecision(16)
+        #          << ROOT::Math::crystalball_cdf(x, 2.0, 3.0, 2.0, 0.5);
+        #          << ", ";
+        # }
+        calculated = stats.crystalball.cdf(X, beta=2.0, m=3.0, loc=0.5, scale=2.0)
+        expected = np.array([0.0176832335808822, 0.02238034250080412,
+                             0.02923146775615237, 0.03978727555698502,
+                             0.05679453901646225, 0.08307626432678494,
+                             0.1212416644828466, 0.1733230597116304,
+                             0.2401101486313661, 0.3205923321191123,
+                             0.4117313791289429, 0.508716882020547,
+                             0.6057023849121512, 0.6968414319219818,
+                             0.7773236154097279, 0.8441107043294638,
+                             0.8961920995582476, 0.934357499714309,
+                             0.9606392250246318, 0.9776464884841091])
+        assert_allclose(expected, calculated, rtol=1e-13)
+
+    # Reference value computed with ROOT, e.g.
+    #     cout << setprecision(16)
+    #          << ROOT::Math::crystalball_cdf_c(12.0, 1.0, 2.0, 1.0)
+    #          << endl;
+    @pytest.mark.parametrize(
+        'x, beta, m, rootref',
+        [(12.0, 1.0, 2.0, 1.340451684048897e-33),
+         (9.0, 4.0, 1.25, 1.12843537145273e-19),
+         (20, 0.1, 1.001, 6.929038716892384e-93),
+         (-4.5, 2.0, 3.0, 0.9944049143747991),
+         (-30.0, 0.5, 5.0, 0.9976994814571858),
+         (-1e50, 1.5, 1.1, 0.9999951099570382)]
+    )
+    def test_sf(self, x, beta, m, rootref):
+        sf = stats.crystalball.sf(x, beta=beta, m=m)
+        assert_allclose(sf, rootref, rtol=1e-13)
+
+    def test_moments(self):
+        """
+        All values are calculated using the pdf formula and the integrate function
+        of Mathematica
+        """
+        # The Last two (alpha, n) pairs test the special case n == alpha**2
+        beta = np.array([2.0, 1.0, 3.0, 2.0, 3.0])
+        m = np.array([3.0, 3.0, 2.0, 4.0, 9.0])
+
+        # The distribution should be correctly normalised
+        expected_0th_moment = np.array([1.0, 1.0, 1.0, 1.0, 1.0])
+        calculated_0th_moment = stats.crystalball._munp(0, beta, m)
+        assert_allclose(expected_0th_moment, calculated_0th_moment, rtol=0.001)
+
+        # calculated using wolframalpha.com
+        # e.g. for beta = 2 and m = 3 we calculate the norm like this:
+        #   integrate exp(-x^2/2) from -2 to infinity +
+        #   integrate (3/2)^3*exp(-2^2/2)*(3/2-2-x)^(-3) from -infinity to -2
+        norm = np.array([2.5511, 3.01873, 2.51065, 2.53983, 2.507410455])
+
+        a = np.array([-0.21992, -3.03265, np.inf, -0.135335, -0.003174])
+        expected_1th_moment = a / norm
+        calculated_1th_moment = stats.crystalball._munp(1, beta, m)
+        assert_allclose(expected_1th_moment, calculated_1th_moment, rtol=0.001)
+
+        a = np.array([np.inf, np.inf, np.inf, 3.2616, 2.519908])
+        expected_2th_moment = a / norm
+        calculated_2th_moment = stats.crystalball._munp(2, beta, m)
+        assert_allclose(expected_2th_moment, calculated_2th_moment, rtol=0.001)
+
+        a = np.array([np.inf, np.inf, np.inf, np.inf, -0.0577668])
+        expected_3th_moment = a / norm
+        calculated_3th_moment = stats.crystalball._munp(3, beta, m)
+        assert_allclose(expected_3th_moment, calculated_3th_moment, rtol=0.001)
+
+        a = np.array([np.inf, np.inf, np.inf, np.inf, 7.78468])
+        expected_4th_moment = a / norm
+        calculated_4th_moment = stats.crystalball._munp(4, beta, m)
+        assert_allclose(expected_4th_moment, calculated_4th_moment, rtol=0.001)
+
+        a = np.array([np.inf, np.inf, np.inf, np.inf, -1.31086])
+        expected_5th_moment = a / norm
+        calculated_5th_moment = stats.crystalball._munp(5, beta, m)
+        assert_allclose(expected_5th_moment, calculated_5th_moment, rtol=0.001)
+
+    def test_entropy(self):
+        # regression test for gh-13602
+        cb = stats.crystalball(2, 3)
+        res1 = cb.entropy()
+        # -20000 and 30 are negative and positive infinity, respectively
+        lo, hi, N = -20000, 30, 200000
+        x = np.linspace(lo, hi, N)
+        res2 = trapezoid(entr(cb.pdf(x)), x)
+        assert_allclose(res1, res2, rtol=1e-7)
+
+
+class TestNBinom:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.nbinom.rvs(10, 0.75, size=(2, 50))
+        assert_(np.all(vals >= 0))
+        assert_(np.shape(vals) == (2, 50))
+        assert_(vals.dtype.char in typecodes['AllInteger'])
+        val = stats.nbinom.rvs(10, 0.75)
+        assert_(isinstance(val, int))
+        val = stats.nbinom(10, 0.75).rvs(3)
+        assert_(isinstance(val, np.ndarray))
+        assert_(val.dtype.char in typecodes['AllInteger'])
+
+    def test_pmf(self):
+        # regression test for ticket 1779
+        assert_allclose(np.exp(stats.nbinom.logpmf(700, 721, 0.52)),
+                        stats.nbinom.pmf(700, 721, 0.52))
+        # logpmf(0,1,1) shouldn't return nan (regression test for gh-4029)
+        val = scipy.stats.nbinom.logpmf(0, 1, 1)
+        assert_equal(val, 0)
+
+    def test_logcdf_gh16159(self):
+        # check that gh16159 is resolved.
+        vals = stats.nbinom.logcdf([0, 5, 0, 5], n=4.8, p=0.45)
+        ref = np.log(stats.nbinom.cdf([0, 5, 0, 5], n=4.8, p=0.45))
+        assert_allclose(vals, ref)
+
+
+class TestGenInvGauss:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.slow
+    def test_rvs_with_mode_shift(self):
+        # ratio_unif w/ mode shift
+        gig = stats.geninvgauss(2.3, 1.5)
+        _, p = stats.kstest(gig.rvs(size=1500, random_state=1234), gig.cdf)
+        assert_equal(p > 0.05, True)
+
+    @pytest.mark.slow
+    def test_rvs_without_mode_shift(self):
+        # ratio_unif w/o mode shift
+        gig = stats.geninvgauss(0.9, 0.75)
+        _, p = stats.kstest(gig.rvs(size=1500, random_state=1234), gig.cdf)
+        assert_equal(p > 0.05, True)
+
+    @pytest.mark.slow
+    def test_rvs_new_method(self):
+        # new algorithm of Hoermann / Leydold
+        gig = stats.geninvgauss(0.1, 0.2)
+        _, p = stats.kstest(gig.rvs(size=1500, random_state=1234), gig.cdf)
+        assert_equal(p > 0.05, True)
+
+    @pytest.mark.slow
+    def test_rvs_p_zero(self):
+        def my_ks_check(p, b):
+            gig = stats.geninvgauss(p, b)
+            rvs = gig.rvs(size=1500, random_state=1234)
+            return stats.kstest(rvs, gig.cdf)[1] > 0.05
+        # boundary cases when p = 0
+        assert_equal(my_ks_check(0, 0.2), True)  # new algo
+        assert_equal(my_ks_check(0, 0.9), True)  # ratio_unif w/o shift
+        assert_equal(my_ks_check(0, 1.5), True)  # ratio_unif with shift
+
+    def test_rvs_negative_p(self):
+        # if p negative, return inverse
+        assert_equal(
+                stats.geninvgauss(-1.5, 2).rvs(size=10, random_state=1234),
+                1 / stats.geninvgauss(1.5, 2).rvs(size=10, random_state=1234))
+
+    def test_invgauss(self):
+        # test that invgauss is special case
+        ig = stats.geninvgauss.rvs(size=1500, p=-0.5, b=1, random_state=1234)
+        assert_equal(stats.kstest(ig, 'invgauss', args=[1])[1] > 0.15, True)
+        # test pdf and cdf
+        mu, x = 100, np.linspace(0.01, 1, 10)
+        pdf_ig = stats.geninvgauss.pdf(x, p=-0.5, b=1 / mu, scale=mu)
+        assert_allclose(pdf_ig, stats.invgauss(mu).pdf(x))
+        cdf_ig = stats.geninvgauss.cdf(x, p=-0.5, b=1 / mu, scale=mu)
+        assert_allclose(cdf_ig, stats.invgauss(mu).cdf(x))
+
+    def test_pdf_R(self):
+        # test against R package GIGrvg
+        # x <- seq(0.01, 5, length.out = 10)
+        # GIGrvg::dgig(x, 0.5, 1, 1)
+        vals_R = np.array([2.081176820e-21, 4.488660034e-01, 3.747774338e-01,
+                           2.693297528e-01, 1.905637275e-01, 1.351476913e-01,
+                           9.636538981e-02, 6.909040154e-02, 4.978006801e-02,
+                           3.602084467e-02])
+        x = np.linspace(0.01, 5, 10)
+        assert_allclose(vals_R, stats.geninvgauss.pdf(x, 0.5, 1))
+
+    def test_pdf_zero(self):
+        # pdf at 0 is 0, needs special treatment to avoid 1/x in pdf
+        assert_equal(stats.geninvgauss.pdf(0, 0.5, 0.5), 0)
+        # if x is large and p is moderate, make sure that pdf does not
+        # overflow because of x**(p-1); exp(-b*x) forces pdf to zero
+        assert_equal(stats.geninvgauss.pdf(2e6, 50, 2), 0)
+
+
+class TestGenHyperbolic:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_pdf_r(self):
+        # test against R package GeneralizedHyperbolic
+        # x <- seq(-10, 10, length.out = 10)
+        # GeneralizedHyperbolic::dghyp(
+        #    x = x, lambda = 2, alpha = 2, beta = 1, delta = 1.5, mu = 0.5
+        # )
+        vals_R = np.array([
+            2.94895678275316e-13, 1.75746848647696e-10, 9.48149804073045e-08,
+            4.17862521692026e-05, 0.0103947630463822, 0.240864958986839,
+            0.162833527161649, 0.0374609592899472, 0.00634894847327781,
+            0.000941920705790324
+            ])
+
+        lmbda, alpha, beta = 2, 2, 1
+        mu, delta = 0.5, 1.5
+        args = (lmbda, alpha*delta, beta*delta)
+
+        gh = stats.genhyperbolic(*args, loc=mu, scale=delta)
+        x = np.linspace(-10, 10, 10)
+
+        assert_allclose(gh.pdf(x), vals_R, atol=0, rtol=1e-13)
+
+    def test_cdf_r(self):
+        # test against R package GeneralizedHyperbolic
+        # q <- seq(-10, 10, length.out = 10)
+        # GeneralizedHyperbolic::pghyp(
+        #   q = q, lambda = 2, alpha = 2, beta = 1, delta = 1.5, mu = 0.5
+        # )
+        vals_R = np.array([
+            1.01881590921421e-13, 6.13697274983578e-11, 3.37504977637992e-08,
+            1.55258698166181e-05, 0.00447005453832497, 0.228935323956347,
+            0.755759458895243, 0.953061062884484, 0.992598013917513,
+            0.998942646586662
+            ])
+
+        lmbda, alpha, beta = 2, 2, 1
+        mu, delta = 0.5, 1.5
+        args = (lmbda, alpha*delta, beta*delta)
+
+        gh = stats.genhyperbolic(*args, loc=mu, scale=delta)
+        x = np.linspace(-10, 10, 10)
+
+        assert_allclose(gh.cdf(x), vals_R, atol=0, rtol=1e-6)
+
+    # The reference values were computed by implementing the PDF with mpmath
+    # and integrating it with mp.quad.  The values were computed with
+    # mp.dps=250, and then again with mp.dps=400 to ensure the full 64 bit
+    # precision was computed.
+    @pytest.mark.parametrize(
+        'x, p, a, b, loc, scale, ref',
+        [(-15, 2, 3, 1.5, 0.5, 1.5, 4.770036428808252e-20),
+         (-15, 10, 1.5, 0.25, 1, 5, 0.03282964575089294),
+         (-15, 10, 1.5, 1.375, 0, 1, 3.3711159600215594e-23),
+         (-15, 0.125, 1.5, 1.49995, 0, 1, 4.729401428898605e-23),
+         (-1, 0.125, 1.5, 1.49995, 0, 1, 0.0003565725914786859),
+         (5, -0.125, 1.5, 1.49995, 0, 1, 0.2600651974023352),
+         (5, -0.125, 1000, 999, 0, 1, 5.923270556517253e-28),
+         (20, -0.125, 1000, 999, 0, 1, 0.23452293711665634),
+         (40, -0.125, 1000, 999, 0, 1, 0.9999648749561968),
+         (60, -0.125, 1000, 999, 0, 1, 0.9999999999975475)]
+    )
+    def test_cdf_mpmath(self, x, p, a, b, loc, scale, ref):
+        cdf = stats.genhyperbolic.cdf(x, p, a, b, loc=loc, scale=scale)
+        assert_allclose(cdf, ref, rtol=5e-12)
+
+    # The reference values were computed by implementing the PDF with mpmath
+    # and integrating it with mp.quad.  The values were computed with
+    # mp.dps=250, and then again with mp.dps=400 to ensure the full 64 bit
+    # precision was computed.
+    @pytest.mark.parametrize(
+        'x, p, a, b, loc, scale, ref',
+        [(0, 1e-6, 12, -1, 0, 1, 0.38520358671350524),
+         (-1, 3, 2.5, 2.375, 1, 3, 0.9999901774267577),
+         (-20, 3, 2.5, 2.375, 1, 3, 1.0),
+         (25, 2, 3, 1.5, 0.5, 1.5, 8.593419916523976e-10),
+         (300, 10, 1.5, 0.25, 1, 5, 6.137415609872158e-24),
+         (60, -0.125, 1000, 999, 0, 1, 2.4524915075944173e-12),
+         (75, -0.125, 1000, 999, 0, 1, 2.9435194886214633e-18)]
+    )
+    def test_sf_mpmath(self, x, p, a, b, loc, scale, ref):
+        sf = stats.genhyperbolic.sf(x, p, a, b, loc=loc, scale=scale)
+        assert_allclose(sf, ref, rtol=5e-12)
+
+    def test_moments_r(self):
+        # test against R package GeneralizedHyperbolic
+        # sapply(1:4,
+        #    function(x) GeneralizedHyperbolic::ghypMom(
+        #        order = x, lambda = 2, alpha = 2,
+        #        beta = 1, delta = 1.5, mu = 0.5,
+        #        momType = 'raw')
+        # )
+
+        vals_R = [2.36848366948115, 8.4739346779246,
+                  37.8870502710066, 205.76608511485]
+
+        lmbda, alpha, beta = 2, 2, 1
+        mu, delta = 0.5, 1.5
+        args = (lmbda, alpha*delta, beta*delta)
+
+        vals_us = [
+            stats.genhyperbolic(*args, loc=mu, scale=delta).moment(i)
+            for i in range(1, 5)
+            ]
+
+        assert_allclose(vals_us, vals_R, atol=0, rtol=1e-13)
+
+    def test_rvs(self):
+        # Kolmogorov-Smirnov test to ensure alignment
+        # of analytical and empirical cdfs
+
+        lmbda, alpha, beta = 2, 2, 1
+        mu, delta = 0.5, 1.5
+        args = (lmbda, alpha*delta, beta*delta)
+
+        gh = stats.genhyperbolic(*args, loc=mu, scale=delta)
+        _, p = stats.kstest(gh.rvs(size=1500, random_state=1234), gh.cdf)
+
+        assert_equal(p > 0.05, True)
+
+    def test_pdf_t(self):
+        # Test Against T-Student with 1 - 30 df
+        df = np.linspace(1, 30, 10)
+
+        # in principle alpha should be zero in practice for big lmbdas
+        # alpha cannot be too small else pdf does not integrate
+        alpha, beta = np.float_power(df, 2)*np.finfo(np.float32).eps, 0
+        mu, delta = 0, np.sqrt(df)
+        args = (-df/2, alpha, beta)
+
+        gh = stats.genhyperbolic(*args, loc=mu, scale=delta)
+        x = np.linspace(gh.ppf(0.01), gh.ppf(0.99), 50)[:, np.newaxis]
+
+        assert_allclose(
+            gh.pdf(x), stats.t.pdf(x, df),
+            atol=0, rtol=1e-6
+            )
+
+    def test_pdf_cauchy(self):
+        # Test Against Cauchy distribution
+
+        # in principle alpha should be zero in practice for big lmbdas
+        # alpha cannot be too small else pdf does not integrate
+        lmbda, alpha, beta = -0.5, np.finfo(np.float32).eps, 0
+        mu, delta = 0, 1
+        args = (lmbda, alpha, beta)
+
+        gh = stats.genhyperbolic(*args, loc=mu, scale=delta)
+        x = np.linspace(gh.ppf(0.01), gh.ppf(0.99), 50)[:, np.newaxis]
+
+        assert_allclose(
+            gh.pdf(x), stats.cauchy.pdf(x),
+            atol=0, rtol=1e-6
+            )
+
+    def test_pdf_laplace(self):
+        # Test Against Laplace with location param [-10, 10]
+        loc = np.linspace(-10, 10, 10)
+
+        # in principle delta should be zero in practice for big loc delta
+        # cannot be too small else pdf does not integrate
+        delta = np.finfo(np.float32).eps
+
+        lmbda, alpha, beta = 1, 1, 0
+        args = (lmbda, alpha*delta, beta*delta)
+
+        # ppf does not integrate for scale < 5e-4
+        # therefore using simple linspace to define the support
+        gh = stats.genhyperbolic(*args, loc=loc, scale=delta)
+        x = np.linspace(-20, 20, 50)[:, np.newaxis]
+
+        assert_allclose(
+            gh.pdf(x), stats.laplace.pdf(x, loc=loc, scale=1),
+            atol=0, rtol=1e-11
+            )
+
+    def test_pdf_norminvgauss(self):
+        # Test Against NIG with varying alpha/beta/delta/mu
+
+        alpha, beta, delta, mu = (
+                np.linspace(1, 20, 10),
+                np.linspace(0, 19, 10)*np.float_power(-1, range(10)),
+                np.linspace(1, 1, 10),
+                np.linspace(-100, 100, 10)
+                )
+
+        lmbda = - 0.5
+        args = (lmbda, alpha * delta, beta * delta)
+
+        gh = stats.genhyperbolic(*args, loc=mu, scale=delta)
+        x = np.linspace(gh.ppf(0.01), gh.ppf(0.99), 50)[:, np.newaxis]
+
+        assert_allclose(
+            gh.pdf(x), stats.norminvgauss.pdf(
+                x, a=alpha, b=beta, loc=mu, scale=delta),
+            atol=0, rtol=1e-13
+            )
+
+
+class TestHypSecant:
+
+    # Reference values were computed with the mpmath expression
+    #     float((2/mp.pi)*mp.atan(mp.exp(-x)))
+    # and mp.dps = 50.
+    @pytest.mark.parametrize('x, reference',
+                             [(30, 5.957247804324683e-14),
+                              (50, 1.2278802891647964e-22)])
+    def test_sf(self, x, reference):
+        sf = stats.hypsecant.sf(x)
+        assert_allclose(sf, reference, rtol=5e-15)
+
+    # Reference values were computed with the mpmath expression
+    #     float(-mp.log(mp.tan((mp.pi/2)*p)))
+    # and mp.dps = 50.
+    @pytest.mark.parametrize('p, reference',
+                             [(1e-6, 13.363927852673998),
+                              (1e-12, 27.179438410639094)])
+    def test_isf(self, p, reference):
+        x = stats.hypsecant.isf(p)
+        assert_allclose(x, reference, rtol=5e-15)
+
+    def test_logcdf_logsf(self):
+        x = 50.0
+        # Reference value was computed with mpmath.
+        ref = -1.2278802891647964e-22
+        logcdf = stats.hypsecant.logcdf(x)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+        logsf = stats.hypsecant.logsf(-x)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+
+class TestNormInvGauss:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_cdf_R(self):
+        # test pdf and cdf vals against R
+        # require("GeneralizedHyperbolic")
+        # x_test <- c(-7, -5, 0, 8, 15)
+        # r_cdf <- GeneralizedHyperbolic::pnig(x_test, mu = 0, a = 1, b = 0.5)
+        # r_pdf <- GeneralizedHyperbolic::dnig(x_test, mu = 0, a = 1, b = 0.5)
+        r_cdf = np.array([8.034920282e-07, 2.512671945e-05, 3.186661051e-01,
+                          9.988650664e-01, 9.999848769e-01])
+        x_test = np.array([-7, -5, 0, 8, 15])
+        vals_cdf = stats.norminvgauss.cdf(x_test, a=1, b=0.5)
+        assert_allclose(vals_cdf, r_cdf, atol=1e-9)
+
+    def test_pdf_R(self):
+        # values from R as defined in test_cdf_R
+        r_pdf = np.array([1.359600783e-06, 4.413878805e-05, 4.555014266e-01,
+                          7.450485342e-04, 8.917889931e-06])
+        x_test = np.array([-7, -5, 0, 8, 15])
+        vals_pdf = stats.norminvgauss.pdf(x_test, a=1, b=0.5)
+        assert_allclose(vals_pdf, r_pdf, atol=1e-9)
+
+    @pytest.mark.parametrize('x, a, b, sf, rtol',
+                             [(-1, 1, 0, 0.8759652211005315, 1e-13),
+                              (25, 1, 0, 1.1318690184042579e-13, 1e-4),
+                              (1, 5, -1.5, 0.002066711134653577, 1e-12),
+                              (10, 5, -1.5, 2.308435233930669e-29, 1e-9)])
+    def test_sf_isf_mpmath(self, x, a, b, sf, rtol):
+        # Reference data generated with `reference_distributions.NormInvGauss`,
+        # e.g. `NormInvGauss(alpha=1, beta=0).sf(-1)` with mp.dps = 50
+        s = stats.norminvgauss.sf(x, a, b)
+        assert_allclose(s, sf, rtol=rtol)
+        i = stats.norminvgauss.isf(sf, a, b)
+        assert_allclose(i, x, rtol=rtol)
+
+    def test_sf_isf_mpmath_vectorized(self):
+        x = [-1, 25]
+        a = [1, 1]
+        b = 0
+        sf = [0.8759652211005315, 1.1318690184042579e-13]  # see previous test
+        s = stats.norminvgauss.sf(x, a, b)
+        assert_allclose(s, sf, rtol=1e-13, atol=1e-16)
+        i = stats.norminvgauss.isf(sf, a, b)
+        # Not perfect, but better than it was. See gh-13338.
+        assert_allclose(i, x, rtol=1e-6)
+
+    def test_gh8718(self):
+        # Add test that gh-13338 resolved gh-8718
+        dst = stats.norminvgauss(1, 0)
+        x = np.arange(0, 20, 2)
+        sf = dst.sf(x)
+        isf = dst.isf(sf)
+        assert_allclose(isf, x)
+
+    def test_stats(self):
+        a, b = 1, 0.5
+        gamma = np.sqrt(a**2 - b**2)
+        v_stats = (b / gamma, a**2 / gamma**3, 3.0 * b / (a * np.sqrt(gamma)),
+                   3.0 * (1 + 4 * b**2 / a**2) / gamma)
+        assert_equal(v_stats, stats.norminvgauss.stats(a, b, moments='mvsk'))
+
+    def test_ppf(self):
+        a, b = 1, 0.5
+        x_test = np.array([0.001, 0.5, 0.999])
+        vals = stats.norminvgauss.ppf(x_test, a, b)
+        assert_allclose(x_test, stats.norminvgauss.cdf(vals, a, b))
+
+
+class TestGeom:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.geom.rvs(0.75, size=(2, 50))
+        assert_(np.all(vals >= 0))
+        assert_(np.shape(vals) == (2, 50))
+        assert_(vals.dtype.char in typecodes['AllInteger'])
+        val = stats.geom.rvs(0.75)
+        assert_(isinstance(val, int))
+        val = stats.geom(0.75).rvs(3)
+        assert_(isinstance(val, np.ndarray))
+        assert_(val.dtype.char in typecodes['AllInteger'])
+
+    def test_rvs_9313(self):
+        # previously, RVS were converted to `np.int32` on some platforms,
+        # causing overflow for moderately large integer output (gh-9313).
+        # Check that this is resolved to the extent possible w/ `np.int64`.
+        rng = np.random.default_rng(649496242618848)
+        rvs = stats.geom.rvs(np.exp(-35), size=5, random_state=rng)
+        assert rvs.dtype == np.int64
+        assert np.all(rvs > np.iinfo(np.int32).max)
+
+    def test_pmf(self):
+        vals = stats.geom.pmf([1, 2, 3], 0.5)
+        assert_array_almost_equal(vals, [0.5, 0.25, 0.125])
+
+    def test_logpmf(self):
+        # regression test for ticket 1793
+        vals1 = np.log(stats.geom.pmf([1, 2, 3], 0.5))
+        vals2 = stats.geom.logpmf([1, 2, 3], 0.5)
+        assert_allclose(vals1, vals2, rtol=1e-15, atol=0)
+
+        # regression test for gh-4028
+        val = stats.geom.logpmf(1, 1)
+        assert_equal(val, 0.0)
+
+    def test_cdf_sf(self):
+        vals = stats.geom.cdf([1, 2, 3], 0.5)
+        vals_sf = stats.geom.sf([1, 2, 3], 0.5)
+        expected = array([0.5, 0.75, 0.875])
+        assert_array_almost_equal(vals, expected)
+        assert_array_almost_equal(vals_sf, 1-expected)
+
+    def test_logcdf_logsf(self):
+        vals = stats.geom.logcdf([1, 2, 3], 0.5)
+        vals_sf = stats.geom.logsf([1, 2, 3], 0.5)
+        expected = array([0.5, 0.75, 0.875])
+        assert_array_almost_equal(vals, np.log(expected))
+        assert_array_almost_equal(vals_sf, np.log1p(-expected))
+
+    def test_ppf(self):
+        vals = stats.geom.ppf([0.5, 0.75, 0.875], 0.5)
+        expected = array([1.0, 2.0, 3.0])
+        assert_array_almost_equal(vals, expected)
+
+    def test_ppf_underflow(self):
+        # this should not underflow
+        assert_allclose(stats.geom.ppf(1e-20, 1e-20), 1.0, atol=1e-14)
+
+    def test_entropy_gh18226(self):
+        # gh-18226 reported that `geom.entropy` produced a warning and
+        # inaccurate output for small p. Check that this is resolved.
+        h = stats.geom(0.0146).entropy()
+        assert_allclose(h, 5.219397961962308, rtol=1e-15)
+
+    def test_rvs_gh18372(self):
+        # gh-18372 reported that `geom.rvs` could produce negative numbers,
+        # with `RandomState` PRNG, but the support is positive integers.
+        # Check that this is resolved.
+        random_state = np.random.RandomState(294582935)
+        assert (stats.geom.rvs(1e-30, size=10, random_state=random_state) > 0).all()
+
+class TestPlanck:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_sf(self):
+        vals = stats.planck.sf([1, 2, 3], 5.)
+        expected = array([4.5399929762484854e-05,
+                          3.0590232050182579e-07,
+                          2.0611536224385579e-09])
+        assert_array_almost_equal(vals, expected)
+
+    def test_logsf(self):
+        vals = stats.planck.logsf([1000., 2000., 3000.], 1000.)
+        expected = array([-1001000., -2001000., -3001000.])
+        assert_array_almost_equal(vals, expected)
+
+
+class TestGennorm:
+    def test_laplace(self):
+        # test against Laplace (special case for beta=1)
+        points = [1, 2, 3]
+        pdf1 = stats.gennorm.pdf(points, 1)
+        pdf2 = stats.laplace.pdf(points)
+        assert_almost_equal(pdf1, pdf2)
+
+    def test_norm(self):
+        # test against normal (special case for beta=2)
+        points = [1, 2, 3]
+        pdf1 = stats.gennorm.pdf(points, 2)
+        pdf2 = stats.norm.pdf(points, scale=2**-.5)
+        assert_almost_equal(pdf1, pdf2)
+
+    def test_rvs(self):
+        np.random.seed(0)
+        # 0 < beta < 1
+        dist = stats.gennorm(0.5)
+        rvs = dist.rvs(size=1000)
+        assert stats.kstest(rvs, dist.cdf).pvalue > 0.1
+        # beta = 1
+        dist = stats.gennorm(1)
+        rvs = dist.rvs(size=1000)
+        rvs_laplace = stats.laplace.rvs(size=1000)
+        assert stats.ks_2samp(rvs, rvs_laplace).pvalue > 0.1
+        # beta = 2
+        dist = stats.gennorm(2)
+        rvs = dist.rvs(size=1000)
+        rvs_norm = stats.norm.rvs(scale=1/2**0.5, size=1000)
+        assert stats.ks_2samp(rvs, rvs_norm).pvalue > 0.1
+
+    def test_rvs_broadcasting(self):
+        np.random.seed(0)
+        dist = stats.gennorm([[0.5, 1.], [2., 5.]])
+        rvs = dist.rvs(size=[1000, 2, 2])
+        assert stats.kstest(rvs[:, 0, 0], stats.gennorm(0.5).cdf)[1] > 0.1
+        assert stats.kstest(rvs[:, 0, 1], stats.gennorm(1.0).cdf)[1] > 0.1
+        assert stats.kstest(rvs[:, 1, 0], stats.gennorm(2.0).cdf)[1] > 0.1
+        assert stats.kstest(rvs[:, 1, 1], stats.gennorm(5.0).cdf)[1] > 0.1
+
+
+class TestGibrat:
+
+    # sfx is sf(x).  The values were computed with mpmath:
+    #
+    #   from mpmath import mp
+    #   mp.dps = 100
+    #   def gibrat_sf(x):
+    #       return 1 - mp.ncdf(mp.log(x))
+    #
+    # E.g.
+    #
+    #   >>> float(gibrat_sf(1.5))
+    #   0.3425678305148459
+    #
+    @pytest.mark.parametrize('x, sfx', [(1.5, 0.3425678305148459),
+                                        (5000, 8.173334352522493e-18)])
+    def test_sf_isf(self, x, sfx):
+        assert_allclose(stats.gibrat.sf(x), sfx, rtol=2e-14)
+        assert_allclose(stats.gibrat.isf(sfx), x, rtol=2e-14)
+
+
+class TestGompertz:
+
+    def test_gompertz_accuracy(self):
+        # Regression test for gh-4031
+        p = stats.gompertz.ppf(stats.gompertz.cdf(1e-100, 1), 1)
+        assert_allclose(p, 1e-100)
+
+    # sfx is sf(x).  The values were computed with mpmath:
+    #
+    #   from mpmath import mp
+    #   mp.dps = 100
+    #   def gompertz_sf(x, c):
+    #       return mp.exp(-c*mp.expm1(x))
+    #
+    # E.g.
+    #
+    #   >>> float(gompertz_sf(1, 2.5))
+    #   0.013626967146253437
+    #
+    @pytest.mark.parametrize('x, c, sfx', [(1, 2.5, 0.013626967146253437),
+                                           (3, 2.5, 1.8973243273704087e-21),
+                                           (0.05, 5, 0.7738668242570479),
+                                           (2.25, 5, 3.707795833465481e-19)])
+    def test_sf_isf(self, x, c, sfx):
+        assert_allclose(stats.gompertz.sf(x, c), sfx, rtol=1e-14)
+        assert_allclose(stats.gompertz.isf(sfx, c), x, rtol=1e-14)
+
+    def test_logcdf(self):
+        x = 8.0
+        c = 0.1
+        # Reference value computed with mpmath.
+        ref = -3.820049516821143e-130
+        logcdf = stats.gompertz.logcdf(x, c)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    def test_logsf(self):
+        x = 3e-80
+        c = 12
+        # Reference value computed with mpmath.
+        ref = -3.6e-79
+        logsf = stats.gompertz.logsf(x, c)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+    # reference values were computed with mpmath
+    # from mpmath import mp
+    # mp.dps = 100
+    # def gompertz_entropy(c):
+    #     c = mp.mpf(c)
+    #     return float(mp.one - mp.log(c) - mp.exp(c)*mp.e1(c))
+
+    @pytest.mark.parametrize('c, ref', [(1e-4, 1.5762523017634573),
+                                        (1, 0.4036526376768059),
+                                        (1000, -5.908754280976161),
+                                        (1e10, -22.025850930040455)])
+    def test_entropy(self, c, ref):
+        assert_allclose(stats.gompertz.entropy(c), ref, rtol=1e-14)
+
+
+class TestFoldNorm:
+
+    # reference values were computed with mpmath with 50 digits of precision
+    # from mpmath import mp
+    # mp.dps = 50
+    # mp.mpf(0.5) * (mp.erf((x - c)/mp.sqrt(2)) + mp.erf((x + c)/mp.sqrt(2)))
+
+    @pytest.mark.parametrize('x, c, ref', [(1e-4, 1e-8, 7.978845594730578e-05),
+                                           (1e-4, 1e-4, 7.97884555483635e-05)])
+    def test_cdf(self, x, c, ref):
+        assert_allclose(stats.foldnorm.cdf(x, c), ref, rtol=1e-15)
+
+
+class TestHalfNorm:
+
+    # sfx is sf(x).  The values were computed with mpmath:
+    #
+    #   from mpmath import mp
+    #   mp.dps = 100
+    #   def halfnorm_sf(x):
+    #       return 2*(1 - mp.ncdf(x))
+    #
+    # E.g.
+    #
+    #   >>> float(halfnorm_sf(1))
+    #   0.3173105078629141
+    #
+    @pytest.mark.parametrize('x, sfx', [(1, 0.3173105078629141),
+                                        (10, 1.523970604832105e-23)])
+    def test_sf_isf(self, x, sfx):
+        assert_allclose(stats.halfnorm.sf(x), sfx, rtol=1e-14)
+        assert_allclose(stats.halfnorm.isf(sfx), x, rtol=1e-14)
+
+    #   reference values were computed via mpmath
+    #   from mpmath import mp
+    #   mp.dps = 100
+    #   def halfnorm_cdf_mpmath(x):
+    #       x = mp.mpf(x)
+    #       return float(mp.erf(x/mp.sqrt(2.)))
+
+    @pytest.mark.parametrize('x, ref', [(1e-40, 7.978845608028653e-41),
+                                        (1e-18, 7.978845608028654e-19),
+                                        (8, 0.9999999999999988)])
+    def test_cdf(self, x, ref):
+        assert_allclose(stats.halfnorm.cdf(x), ref, rtol=1e-15)
+
+    @pytest.mark.parametrize("rvs_loc", [1e-5, 1e10])
+    @pytest.mark.parametrize("rvs_scale", [1e-2, 100, 1e8])
+    @pytest.mark.parametrize('fix_loc', [True, False])
+    @pytest.mark.parametrize('fix_scale', [True, False])
+    def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_scale,
+                                    fix_loc, fix_scale):
+
+        rng = np.random.default_rng(6762668991392531563)
+        data = stats.halfnorm.rvs(loc=rvs_loc, scale=rvs_scale, size=1000,
+                                  random_state=rng)
+
+        if fix_loc and fix_scale:
+            error_msg = ("All parameters fixed. There is nothing to "
+                         "optimize.")
+            with pytest.raises(RuntimeError, match=error_msg):
+                stats.halflogistic.fit(data, floc=rvs_loc, fscale=rvs_scale)
+            return
+
+        kwds = {}
+        if fix_loc:
+            kwds['floc'] = rvs_loc
+        if fix_scale:
+            kwds['fscale'] = rvs_scale
+
+        # Numerical result may equal analytical result if the initial guess
+        # computed from moment condition is already optimal.
+        _assert_less_or_close_loglike(stats.halfnorm, data, **kwds,
+                                      maybe_identical=True)
+
+    def test_fit_error(self):
+        # `floc` bigger than the minimal data point
+        with pytest.raises(FitDataError):
+            stats.halfnorm.fit([1, 2, 3], floc=2)
+
+
+class TestHalfCauchy:
+
+    @pytest.mark.parametrize("rvs_loc", [1e-5, 1e10])
+    @pytest.mark.parametrize("rvs_scale", [1e-2, 1e8])
+    @pytest.mark.parametrize('fix_loc', [True, False])
+    @pytest.mark.parametrize('fix_scale', [True, False])
+    def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_scale,
+                                    fix_loc, fix_scale):
+
+        rng = np.random.default_rng(6762668991392531563)
+        data = stats.halfnorm.rvs(loc=rvs_loc, scale=rvs_scale, size=1000,
+                                  random_state=rng)
+
+        if fix_loc and fix_scale:
+            error_msg = ("All parameters fixed. There is nothing to "
+                         "optimize.")
+            with pytest.raises(RuntimeError, match=error_msg):
+                stats.halfcauchy.fit(data, floc=rvs_loc, fscale=rvs_scale)
+            return
+
+        kwds = {}
+        if fix_loc:
+            kwds['floc'] = rvs_loc
+        if fix_scale:
+            kwds['fscale'] = rvs_scale
+
+        _assert_less_or_close_loglike(stats.halfcauchy, data, **kwds)
+
+    def test_fit_error(self):
+        # `floc` bigger than the minimal data point
+        with pytest.raises(FitDataError):
+            stats.halfcauchy.fit([1, 2, 3], floc=2)
+
+
+class TestHalfLogistic:
+    # survival function reference values were computed with mpmath
+    # from mpmath import mp
+    # mp.dps = 50
+    # def sf_mpmath(x):
+    #     x = mp.mpf(x)
+    #     return float(mp.mpf(2.)/(mp.exp(x) + mp.one))
+
+    @pytest.mark.parametrize('x, ref', [(100, 7.440151952041672e-44),
+                                        (200, 2.767793053473475e-87)])
+    def test_sf(self, x, ref):
+        assert_allclose(stats.halflogistic.sf(x), ref, rtol=1e-15)
+
+    # inverse survival function reference values were computed with mpmath
+    # from mpmath import mp
+    # mp.dps = 200
+    # def isf_mpmath(x):
+    #     halfx = mp.mpf(x)/2
+    #     return float(-mp.log(halfx/(mp.one - halfx)))
+
+    @pytest.mark.parametrize('q, ref', [(7.440151952041672e-44, 100),
+                                        (2.767793053473475e-87, 200),
+                                        (1-1e-9, 1.999999943436137e-09),
+                                        (1-1e-15, 1.9984014443252818e-15)])
+    def test_isf(self, q, ref):
+        assert_allclose(stats.halflogistic.isf(q), ref, rtol=1e-15)
+
+    def test_logcdf(self):
+        x = 30.0
+        # Reference value computed with mpmath.
+        ref = -1.871524593768035e-13
+        logcdf = stats.halflogistic.logcdf(x)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    def test_logsf(self):
+        x = 2e-14
+        # Reference value computed with mpmath.
+        ref = -1.000000000000005e-14
+        logsf = stats.halflogistic.logsf(x)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+    @pytest.mark.parametrize("rvs_loc", [1e-5, 1e10])
+    @pytest.mark.parametrize("rvs_scale", [1e-2, 100, 1e8])
+    @pytest.mark.parametrize('fix_loc', [True, False])
+    @pytest.mark.parametrize('fix_scale', [True, False])
+    def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_scale,
+                                    fix_loc, fix_scale):
+
+        rng = np.random.default_rng(6762668991392531563)
+        data = stats.halflogistic.rvs(loc=rvs_loc, scale=rvs_scale, size=1000,
+                                      random_state=rng)
+
+        kwds = {}
+        if fix_loc and fix_scale:
+            error_msg = ("All parameters fixed. There is nothing to "
+                         "optimize.")
+            with pytest.raises(RuntimeError, match=error_msg):
+                stats.halflogistic.fit(data, floc=rvs_loc, fscale=rvs_scale)
+            return
+
+        if fix_loc:
+            kwds['floc'] = rvs_loc
+        if fix_scale:
+            kwds['fscale'] = rvs_scale
+
+        # Numerical result may equal analytical result if the initial guess
+        # computed from moment condition is already optimal.
+        _assert_less_or_close_loglike(stats.halflogistic, data, **kwds,
+                                      maybe_identical=True)
+
+    def test_fit_bad_floc(self):
+        msg = r" Maximum likelihood estimation with 'halflogistic' requires"
+        with assert_raises(FitDataError, match=msg):
+            stats.halflogistic.fit([0, 2, 4], floc=1)
+
+
+class TestHalfgennorm:
+    def test_expon(self):
+        # test against exponential (special case for beta=1)
+        points = [1, 2, 3]
+        pdf1 = stats.halfgennorm.pdf(points, 1)
+        pdf2 = stats.expon.pdf(points)
+        assert_almost_equal(pdf1, pdf2)
+
+    def test_halfnorm(self):
+        # test against half normal (special case for beta=2)
+        points = [1, 2, 3]
+        pdf1 = stats.halfgennorm.pdf(points, 2)
+        pdf2 = stats.halfnorm.pdf(points, scale=2**-.5)
+        assert_almost_equal(pdf1, pdf2)
+
+    def test_gennorm(self):
+        # test against generalized normal
+        points = [1, 2, 3]
+        pdf1 = stats.halfgennorm.pdf(points, .497324)
+        pdf2 = stats.gennorm.pdf(points, .497324)
+        assert_almost_equal(pdf1, 2*pdf2)
+
+
+class TestLaplaceasymmetric:
+    def test_laplace(self):
+        # test against Laplace (special case for kappa=1)
+        points = np.array([1, 2, 3])
+        pdf1 = stats.laplace_asymmetric.pdf(points, 1)
+        pdf2 = stats.laplace.pdf(points)
+        assert_allclose(pdf1, pdf2)
+
+    def test_asymmetric_laplace_pdf(self):
+        # test asymmetric Laplace
+        points = np.array([1, 2, 3])
+        kappa = 2
+        kapinv = 1/kappa
+        pdf1 = stats.laplace_asymmetric.pdf(points, kappa)
+        pdf2 = stats.laplace_asymmetric.pdf(points*(kappa**2), kapinv)
+        assert_allclose(pdf1, pdf2)
+
+    def test_asymmetric_laplace_log_10_16(self):
+        # test asymmetric Laplace
+        points = np.array([-np.log(16), np.log(10)])
+        kappa = 2
+        pdf1 = stats.laplace_asymmetric.pdf(points, kappa)
+        cdf1 = stats.laplace_asymmetric.cdf(points, kappa)
+        sf1 = stats.laplace_asymmetric.sf(points, kappa)
+        pdf2 = np.array([1/10, 1/250])
+        cdf2 = np.array([1/5, 1 - 1/500])
+        sf2 = np.array([4/5, 1/500])
+        ppf1 = stats.laplace_asymmetric.ppf(cdf2, kappa)
+        ppf2 = points
+        isf1 = stats.laplace_asymmetric.isf(sf2, kappa)
+        isf2 = points
+        assert_allclose(np.concatenate((pdf1, cdf1, sf1, ppf1, isf1)),
+                        np.concatenate((pdf2, cdf2, sf2, ppf2, isf2)))
+
+
+class TestTruncnorm:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.parametrize("a, b, ref",
+                             [(0, 100, 0.7257913526447274),
+                             (0.6, 0.7, -2.3027610681852573),
+                             (1e-06, 2e-06, -13.815510557964274)])
+    def test_entropy(self, a, b, ref):
+        # All reference values were calculated with mpmath:
+        # import numpy as np
+        # from mpmath import mp
+        # mp.dps = 50
+        # def entropy_trun(a, b):
+        #     a, b = mp.mpf(a), mp.mpf(b)
+        #     Z = mp.ncdf(b) - mp.ncdf(a)
+        #
+        #     def pdf(x):
+        #         return mp.npdf(x) / Z
+        #
+        #     res = -mp.quad(lambda t: pdf(t) * mp.log(pdf(t)), [a, b])
+        #     return np.float64(res)
+        assert_allclose(stats.truncnorm.entropy(a, b), ref, rtol=1e-10)
+
+    @pytest.mark.parametrize("a, b, ref",
+                             [(1e-11, 10000000000.0, 0.725791352640738),
+                             (1e-100, 1e+100, 0.7257913526447274),
+                             (-1e-100, 1e+100, 0.7257913526447274),
+                             (-1e+100, 1e+100, 1.4189385332046727)])
+    def test_extreme_entropy(self, a, b, ref):
+        # The reference values were calculated with mpmath
+        # import numpy as np
+        # from mpmath import mp
+        # mp.dps = 50
+        # def trunc_norm_entropy(a, b):
+        #     a, b = mp.mpf(a), mp.mpf(b)
+        #     Z = mp.ncdf(b) - mp.ncdf(a)
+        #     A = mp.log(mp.sqrt(2 * mp.pi * mp.e) * Z)
+        #     B = (a * mp.npdf(a) - b * mp.npdf(b)) / (2 * Z)
+        #     return np.float64(A + B)
+        assert_allclose(stats.truncnorm.entropy(a, b), ref, rtol=1e-14)
+
+    def test_ppf_ticket1131(self):
+        vals = stats.truncnorm.ppf([-0.5, 0, 1e-4, 0.5, 1-1e-4, 1, 2], -1., 1.,
+                                   loc=[3]*7, scale=2)
+        expected = np.array([np.nan, 1, 1.00056419, 3, 4.99943581, 5, np.nan])
+        assert_array_almost_equal(vals, expected)
+
+    def test_isf_ticket1131(self):
+        vals = stats.truncnorm.isf([-0.5, 0, 1e-4, 0.5, 1-1e-4, 1, 2], -1., 1.,
+                                   loc=[3]*7, scale=2)
+        expected = np.array([np.nan, 5, 4.99943581, 3, 1.00056419, 1, np.nan])
+        assert_array_almost_equal(vals, expected)
+
+    def test_gh_2477_small_values(self):
+        # Check a case that worked in the original issue.
+        low, high = -11, -10
+        x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
+        assert_(low < x.min() < x.max() < high)
+        # Check a case that failed in the original issue.
+        low, high = 10, 11
+        x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
+        assert_(low < x.min() < x.max() < high)
+
+    def test_gh_2477_large_values(self):
+        # Check a case that used to fail because of extreme tailness.
+        low, high = 100, 101
+        x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
+        assert_(low <= x.min() <= x.max() <= high), str([low, high, x])
+
+        # Check some additional extreme tails
+        low, high = 1000, 1001
+        x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
+        assert_(low < x.min() < x.max() < high)
+
+        low, high = 10000, 10001
+        x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
+        assert_(low < x.min() < x.max() < high)
+
+        low, high = -10001, -10000
+        x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
+        assert_(low < x.min() < x.max() < high)
+
+    def test_gh_9403_nontail_values(self):
+        for low, high in [[3, 4], [-4, -3]]:
+            xvals = np.array([-np.inf, low, high, np.inf])
+            xmid = (high+low)/2.0
+            cdfs = stats.truncnorm.cdf(xvals, low, high)
+            sfs = stats.truncnorm.sf(xvals, low, high)
+            pdfs = stats.truncnorm.pdf(xvals, low, high)
+            expected_cdfs = np.array([0, 0, 1, 1])
+            expected_sfs = np.array([1.0, 1.0, 0.0, 0.0])
+            expected_pdfs = np.array([0, 3.3619772, 0.1015229, 0])
+            if low < 0:
+                expected_pdfs = np.array([0, 0.1015229, 3.3619772, 0])
+            assert_almost_equal(cdfs, expected_cdfs)
+            assert_almost_equal(sfs, expected_sfs)
+            assert_almost_equal(pdfs, expected_pdfs)
+            assert_almost_equal(np.log(expected_pdfs[1]/expected_pdfs[2]),
+                                low + 0.5)
+            pvals = np.array([0, 0.5, 1.0])
+            ppfs = stats.truncnorm.ppf(pvals, low, high)
+            expected_ppfs = np.array([low, np.sign(low)*3.1984741, high])
+            assert_almost_equal(ppfs, expected_ppfs)
+
+            if low < 0:
+                assert_almost_equal(stats.truncnorm.sf(xmid, low, high),
+                                    0.8475544278436675)
+                assert_almost_equal(stats.truncnorm.cdf(xmid, low, high),
+                                    0.1524455721563326)
+            else:
+                assert_almost_equal(stats.truncnorm.cdf(xmid, low, high),
+                                    0.8475544278436675)
+                assert_almost_equal(stats.truncnorm.sf(xmid, low, high),
+                                    0.1524455721563326)
+            pdf = stats.truncnorm.pdf(xmid, low, high)
+            assert_almost_equal(np.log(pdf/expected_pdfs[2]), (xmid+0.25)/2)
+
+    def test_gh_9403_medium_tail_values(self):
+        for low, high in [[39, 40], [-40, -39]]:
+            xvals = np.array([-np.inf, low, high, np.inf])
+            xmid = (high+low)/2.0
+            cdfs = stats.truncnorm.cdf(xvals, low, high)
+            sfs = stats.truncnorm.sf(xvals, low, high)
+            pdfs = stats.truncnorm.pdf(xvals, low, high)
+            expected_cdfs = np.array([0, 0, 1, 1])
+            expected_sfs = np.array([1.0, 1.0, 0.0, 0.0])
+            expected_pdfs = np.array([0, 3.90256074e+01, 2.73349092e-16, 0])
+            if low < 0:
+                expected_pdfs = np.array([0, 2.73349092e-16,
+                                          3.90256074e+01, 0])
+            assert_almost_equal(cdfs, expected_cdfs)
+            assert_almost_equal(sfs, expected_sfs)
+            assert_almost_equal(pdfs, expected_pdfs)
+            assert_almost_equal(np.log(expected_pdfs[1]/expected_pdfs[2]),
+                                low + 0.5)
+            pvals = np.array([0, 0.5, 1.0])
+            ppfs = stats.truncnorm.ppf(pvals, low, high)
+            expected_ppfs = np.array([low, np.sign(low)*39.01775731, high])
+            assert_almost_equal(ppfs, expected_ppfs)
+            cdfs = stats.truncnorm.cdf(ppfs, low, high)
+            assert_almost_equal(cdfs, pvals)
+
+            if low < 0:
+                assert_almost_equal(stats.truncnorm.sf(xmid, low, high),
+                                    0.9999999970389126)
+                assert_almost_equal(stats.truncnorm.cdf(xmid, low, high),
+                                    2.961048103554866e-09)
+            else:
+                assert_almost_equal(stats.truncnorm.cdf(xmid, low, high),
+                                    0.9999999970389126)
+                assert_almost_equal(stats.truncnorm.sf(xmid, low, high),
+                                    2.961048103554866e-09)
+            pdf = stats.truncnorm.pdf(xmid, low, high)
+            assert_almost_equal(np.log(pdf/expected_pdfs[2]), (xmid+0.25)/2)
+
+            xvals = np.linspace(low, high, 11)
+            xvals2 = -xvals[::-1]
+            assert_almost_equal(stats.truncnorm.cdf(xvals, low, high),
+                                stats.truncnorm.sf(xvals2, -high, -low)[::-1])
+            assert_almost_equal(stats.truncnorm.sf(xvals, low, high),
+                                stats.truncnorm.cdf(xvals2, -high, -low)[::-1])
+            assert_almost_equal(stats.truncnorm.pdf(xvals, low, high),
+                                stats.truncnorm.pdf(xvals2, -high, -low)[::-1])
+
+    def test_cdf_tail_15110_14753(self):
+        # Check accuracy issues reported in gh-14753 and gh-155110
+        # Ground truth values calculated using Wolfram Alpha, e.g.
+        # (CDF[NormalDistribution[0,1],83/10]-CDF[NormalDistribution[0,1],8])/
+        #     (1 - CDF[NormalDistribution[0,1],8])
+        assert_allclose(stats.truncnorm(13., 15.).cdf(14.),
+                        0.9999987259565643)
+        assert_allclose(stats.truncnorm(8, np.inf).cdf(8.3),
+                        0.9163220907327540)
+
+    # Test data for the truncnorm stats() method.
+    # The data in each row is:
+    #   a, b, mean, variance, skewness, excess kurtosis. Generated using
+    # https://gist.github.com/WarrenWeckesser/636b537ee889679227d53543d333a720
+    _truncnorm_stats_data = [
+        [-30, 30,
+         0.0, 1.0, 0.0, 0.0],
+        [-10, 10,
+         0.0, 1.0, 0.0, -1.4927521335810455e-19],
+        [-3, 3,
+         0.0, 0.9733369246625415, 0.0, -0.17111443639774404],
+        [-2, 2,
+         0.0, 0.7737413035499232, 0.0, -0.6344632828703505],
+        [0, np.inf,
+         0.7978845608028654,
+         0.3633802276324187,
+         0.995271746431156,
+         0.8691773036059741],
+        [-np.inf, 0,
+         -0.7978845608028654,
+         0.3633802276324187,
+         -0.995271746431156,
+         0.8691773036059741],
+        [-1, 3,
+         0.282786110727154,
+         0.6161417353578293,
+         0.5393018494027877,
+         -0.20582065135274694],
+        [-3, 1,
+         -0.282786110727154,
+         0.6161417353578293,
+         -0.5393018494027877,
+         -0.20582065135274694],
+        [-10, -9,
+         -9.108456288012409,
+         0.011448805821636248,
+         -1.8985607290949496,
+         5.0733461105025075],
+    ]
+    _truncnorm_stats_data = np.array(_truncnorm_stats_data)
+
+    @pytest.mark.parametrize("case", _truncnorm_stats_data)
+    def test_moments(self, case):
+        a, b, m0, v0, s0, k0 = case
+        m, v, s, k = stats.truncnorm.stats(a, b, moments='mvsk')
+        assert_allclose([m, v, s, k], [m0, v0, s0, k0], atol=1e-17)
+
+    def test_9902_moments(self):
+        m, v = stats.truncnorm.stats(0, np.inf, moments='mv')
+        assert_almost_equal(m, 0.79788456)
+        assert_almost_equal(v, 0.36338023)
+
+    def test_gh_1489_trac_962_rvs(self):
+        # Check the original example.
+        low, high = 10, 15
+        x = stats.truncnorm.rvs(low, high, 0, 1, size=10)
+        assert_(low < x.min() < x.max() < high)
+
+    def test_gh_11299_rvs(self):
+        # Arose from investigating gh-11299
+        # Test multiple shape parameters simultaneously.
+        low = [-10, 10, -np.inf, -5, -np.inf, -np.inf, -45, -45, 40, -10, 40]
+        high = [-5, 11, 5, np.inf, 40, -40, 40, -40, 45, np.inf, np.inf]
+        x = stats.truncnorm.rvs(low, high, size=(5, len(low)))
+        assert np.shape(x) == (5, len(low))
+        assert_(np.all(low <= x.min(axis=0)))
+        assert_(np.all(x.max(axis=0) <= high))
+
+    def test_rvs_Generator(self):
+        # check that rvs can use a Generator
+        if hasattr(np.random, "default_rng"):
+            stats.truncnorm.rvs(-10, -5, size=5,
+                                random_state=np.random.default_rng())
+
+    def test_logcdf_gh17064(self):
+        # regression test for gh-17064 - avoid roundoff error for logcdfs ~0
+        a = np.array([-np.inf, -np.inf, -8, -np.inf, 10])
+        b = np.array([np.inf, np.inf, 8, 10, np.inf])
+        x = np.array([10, 7.5, 7.5, 9, 20])
+        expected = [-7.619853024160525e-24, -3.190891672910947e-14,
+                    -3.128682067168231e-14, -1.1285122074235991e-19,
+                    -3.61374964828753e-66]
+        assert_allclose(stats.truncnorm(a, b).logcdf(x), expected)
+        assert_allclose(stats.truncnorm(-b, -a).logsf(-x), expected)
+
+    def test_moments_gh18634(self):
+        # gh-18634 reported that moments 5 and higher didn't work; check that
+        # this is resolved
+        res = stats.truncnorm(-2, 3).moment(5)
+        # From Mathematica:
+        # Moment[TruncatedDistribution[{-2, 3}, NormalDistribution[]], 5]
+        ref = 1.645309620208361
+        assert_allclose(res, ref)
+
+
+class TestGenLogistic:
+
+    # Expected values computed with mpmath with 50 digits of precision.
+    @pytest.mark.parametrize('x, expected', [(-1000, -1499.5945348918917),
+                                             (-125, -187.09453489189184),
+                                             (0, -1.3274028432916989),
+                                             (100, -99.59453489189184),
+                                             (1000, -999.5945348918918)])
+    def test_logpdf(self, x, expected):
+        c = 1.5
+        logp = stats.genlogistic.logpdf(x, c)
+        assert_allclose(logp, expected, rtol=1e-13)
+
+    # Expected values computed with mpmath with 50 digits of precision
+    # from mpmath import mp
+    # mp.dps = 50
+    # def entropy_mp(c):
+    #     c = mp.mpf(c)
+    #     return float(-mp.log(c)+mp.one+mp.digamma(c + mp.one) + mp.euler)
+
+    @pytest.mark.parametrize('c, ref', [(1e-100, 231.25850929940458),
+                                        (1e-4, 10.21050485336338),
+                                        (1e8, 1.577215669901533),
+                                        (1e100, 1.5772156649015328)])
+    def test_entropy(self, c, ref):
+        assert_allclose(stats.genlogistic.entropy(c), ref, rtol=5e-15)
+
+    # Expected values computed with mpmath with 50 digits of precision
+    # from mpmath import mp
+    # mp.dps = 1000
+    #
+    # def genlogistic_cdf_mp(x, c):
+    #     x = mp.mpf(x)
+    #     c = mp.mpf(c)
+    #     return (mp.one + mp.exp(-x)) ** (-c)
+    #
+    # def genlogistic_sf_mp(x, c):
+    #     return mp.one - genlogistic_cdf_mp(x, c)
+    #
+    # x, c, ref = 100, 0.02, -7.440151952041672e-466
+    # print(float(mp.log(genlogistic_cdf_mp(x, c))))
+    # ppf/isf reference values generated by passing in `ref` (`q` is produced)
+
+    @pytest.mark.parametrize('x, c, ref', [(200, 10, 1.3838965267367375e-86),
+                                           (500, 20, 1.424915281348257e-216)])
+    def test_sf(self, x, c, ref):
+        assert_allclose(stats.genlogistic.sf(x, c), ref, rtol=1e-14)
+
+    @pytest.mark.parametrize('q, c, ref', [(0.01, 200, 9.898441467379765),
+                                           (0.001, 2, 7.600152115573173)])
+    def test_isf(self, q, c, ref):
+        assert_allclose(stats.genlogistic.isf(q, c), ref, rtol=5e-16)
+
+    @pytest.mark.parametrize('q, c, ref', [(0.5, 200, 5.6630969187064615),
+                                           (0.99, 20, 7.595630231412436)])
+    def test_ppf(self, q, c, ref):
+        assert_allclose(stats.genlogistic.ppf(q, c), ref, rtol=5e-16)
+
+    @pytest.mark.parametrize('x, c, ref', [(100, 0.02, -7.440151952041672e-46),
+                                           (50, 20, -3.857499695927835e-21)])
+    def test_logcdf(self, x, c, ref):
+        assert_allclose(stats.genlogistic.logcdf(x, c), ref, rtol=1e-15)
+
+
+class TestHypergeom:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.hypergeom.rvs(20, 10, 3, size=(2, 50))
+        assert np.all(vals >= 0) & np.all(vals <= 3)
+        assert np.shape(vals) == (2, 50)
+        assert vals.dtype.char in typecodes['AllInteger']
+        val = stats.hypergeom.rvs(20, 3, 10)
+        assert isinstance(val, int)
+        val = stats.hypergeom(20, 3, 10).rvs(3)
+        assert isinstance(val, np.ndarray)
+        assert val.dtype.char in typecodes['AllInteger']
+
+    def test_precision(self):
+        # comparison number from mpmath
+        M = 2500
+        n = 50
+        N = 500
+        tot = M
+        good = n
+        hgpmf = stats.hypergeom.pmf(2, tot, good, N)
+        assert_almost_equal(hgpmf, 0.0010114963068932233, 11)
+
+    def test_args(self):
+        # test correct output for corner cases of arguments
+        # see gh-2325
+        assert_almost_equal(stats.hypergeom.pmf(0, 2, 1, 0), 1.0, 11)
+        assert_almost_equal(stats.hypergeom.pmf(1, 2, 1, 0), 0.0, 11)
+
+        assert_almost_equal(stats.hypergeom.pmf(0, 2, 0, 2), 1.0, 11)
+        assert_almost_equal(stats.hypergeom.pmf(1, 2, 1, 0), 0.0, 11)
+
+    def test_cdf_above_one(self):
+        # for some values of parameters, hypergeom cdf was >1, see gh-2238
+        assert_(0 <= stats.hypergeom.cdf(30, 13397950, 4363, 12390) <= 1.0)
+
+    def test_precision2(self):
+        # Test hypergeom precision for large numbers.  See #1218.
+        # Results compared with those from R.
+        oranges = 9.9e4
+        pears = 1.1e5
+        fruits_eaten = np.array([3, 3.8, 3.9, 4, 4.1, 4.2, 5]) * 1e4
+        quantile = 2e4
+        res = [stats.hypergeom.sf(quantile, oranges + pears, oranges, eaten)
+               for eaten in fruits_eaten]
+        expected = np.array([0, 1.904153e-114, 2.752693e-66, 4.931217e-32,
+                             8.265601e-11, 0.1237904, 1])
+        assert_allclose(res, expected, atol=0, rtol=5e-7)
+
+        # Test with array_like first argument
+        quantiles = [1.9e4, 2e4, 2.1e4, 2.15e4]
+        res2 = stats.hypergeom.sf(quantiles, oranges + pears, oranges, 4.2e4)
+        expected2 = [1, 0.1237904, 6.511452e-34, 3.277667e-69]
+        assert_allclose(res2, expected2, atol=0, rtol=5e-7)
+
+    def test_entropy(self):
+        # Simple tests of entropy.
+        hg = stats.hypergeom(4, 1, 1)
+        h = hg.entropy()
+        expected_p = np.array([0.75, 0.25])
+        expected_h = -np.sum(xlogy(expected_p, expected_p))
+        assert_allclose(h, expected_h)
+
+        hg = stats.hypergeom(1, 1, 1)
+        h = hg.entropy()
+        assert_equal(h, 0.0)
+
+    def test_logsf(self):
+        # Test logsf for very large numbers. See issue #4982
+        # Results compare with those from R (v3.2.0):
+        # phyper(k, n, M-n, N, lower.tail=FALSE, log.p=TRUE)
+        # -2239.771
+
+        k = 1e4
+        M = 1e7
+        n = 1e6
+        N = 5e4
+
+        result = stats.hypergeom.logsf(k, M, n, N)
+        expected = -2239.771   # From R
+        assert_almost_equal(result, expected, decimal=3)
+
+        k = 1
+        M = 1600
+        n = 600
+        N = 300
+
+        result = stats.hypergeom.logsf(k, M, n, N)
+        expected = -2.566567e-68   # From R
+        assert_almost_equal(result, expected, decimal=15)
+
+    def test_logcdf(self):
+        # Test logcdf for very large numbers. See issue #8692
+        # Results compare with those from R (v3.3.2):
+        # phyper(k, n, M-n, N, lower.tail=TRUE, log.p=TRUE)
+        # -5273.335
+
+        k = 1
+        M = 1e7
+        n = 1e6
+        N = 5e4
+
+        result = stats.hypergeom.logcdf(k, M, n, N)
+        expected = -5273.335   # From R
+        assert_almost_equal(result, expected, decimal=3)
+
+        # Same example as in issue #8692
+        k = 40
+        M = 1600
+        n = 50
+        N = 300
+
+        result = stats.hypergeom.logcdf(k, M, n, N)
+        expected = -7.565148879229e-23    # From R
+        assert_almost_equal(result, expected, decimal=15)
+
+        k = 125
+        M = 1600
+        n = 250
+        N = 500
+
+        result = stats.hypergeom.logcdf(k, M, n, N)
+        expected = -4.242688e-12    # From R
+        assert_almost_equal(result, expected, decimal=15)
+
+        # test broadcasting robustness based on reviewer
+        # concerns in PR 9603; using an array version of
+        # the example from issue #8692
+        k = np.array([40, 40, 40])
+        M = 1600
+        n = 50
+        N = 300
+
+        result = stats.hypergeom.logcdf(k, M, n, N)
+        expected = np.full(3, -7.565148879229e-23)  # filled from R result
+        assert_almost_equal(result, expected, decimal=15)
+
+    def test_mean_gh18511(self):
+        # gh-18511 reported that the `mean` was incorrect for large arguments;
+        # check that this is resolved
+        M = 390_000
+        n = 370_000
+        N = 12_000
+
+        hm = stats.hypergeom.mean(M, n, N)
+        rm = n / M * N
+        assert_allclose(hm, rm)
+
+    @pytest.mark.xslow
+    def test_sf_gh18506(self):
+        # gh-18506 reported that `sf` was incorrect for large population;
+        # check that this is resolved
+        n = 10
+        N = 10**5
+        i = np.arange(5, 15)
+        population_size = 10.**i
+        p = stats.hypergeom.sf(n - 1, population_size, N, n)
+        assert np.all(p > 0)
+        assert np.all(np.diff(p) < 0)
+
+
+class TestLoggamma:
+
+    # Expected cdf values were computed with mpmath. For given x and c,
+    #     x = mpmath.mpf(x)
+    #     c = mpmath.mpf(c)
+    #     cdf = mpmath.gammainc(c, 0, mpmath.exp(x),
+    #                           regularized=True)
+    @pytest.mark.parametrize('x, c, cdf',
+                             [(1, 2, 0.7546378854206702),
+                              (-1, 14, 6.768116452566383e-18),
+                              (-745.1, 0.001, 0.4749605142005238),
+                              (-800, 0.001, 0.44958802911019136),
+                              (-725, 0.1, 3.4301205868273265e-32),
+                              (-740, 0.75, 1.0074360436599631e-241)])
+    def test_cdf_ppf(self, x, c, cdf):
+        p = stats.loggamma.cdf(x, c)
+        assert_allclose(p, cdf, rtol=1e-13)
+        y = stats.loggamma.ppf(cdf, c)
+        assert_allclose(y, x, rtol=1e-13)
+
+    # Expected sf values were computed with mpmath. For given x and c,
+    #     x = mpmath.mpf(x)
+    #     c = mpmath.mpf(c)
+    #     sf = mpmath.gammainc(c, mpmath.exp(x), mpmath.inf,
+    #                          regularized=True)
+    @pytest.mark.parametrize('x, c, sf',
+                             [(4, 1.5, 1.6341528919488565e-23),
+                              (6, 100, 8.23836829202024e-74),
+                              (-800, 0.001, 0.5504119708898086),
+                              (-743, 0.0025, 0.8437131370024089)])
+    def test_sf_isf(self, x, c, sf):
+        s = stats.loggamma.sf(x, c)
+        assert_allclose(s, sf, rtol=1e-13)
+        y = stats.loggamma.isf(sf, c)
+        assert_allclose(y, x, rtol=1e-13)
+
+    def test_logpdf(self):
+        # Test logpdf with x=-500, c=2.  ln(gamma(2)) = 0, and
+        # exp(-500) ~= 7e-218, which is far smaller than the ULP
+        # of c*x=-1000, so logpdf(-500, 2) = c*x - exp(x) - ln(gamma(2))
+        # should give -1000.0.
+        lp = stats.loggamma.logpdf(-500, 2)
+        assert_allclose(lp, -1000.0, rtol=1e-14)
+
+    def test_logcdf(self):
+        x = 4.0
+        c = 4.5
+        logcdf = stats.loggamma.logcdf(x, c)
+        # Reference value computed with mpmath.
+        ref = -2.1429747073164531e-19
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    def test_logsf(self):
+        x = -25.0
+        c = 3.5
+        logsf = stats.loggamma.logsf(x, c)
+        # Reference value computed with mpmath.
+        ref = -8.58200139319556e-40
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+    def test_stats(self):
+        # The following precomputed values are from the table in section 2.2
+        # of "A Statistical Study of Log-Gamma Distribution", by Ping Shing
+        # Chan (thesis, McMaster University, 1993).
+        table = np.array([
+                # c,    mean,   var,    skew,    exc. kurt.
+                0.5, -1.9635, 4.9348, -1.5351, 4.0000,
+                1.0, -0.5772, 1.6449, -1.1395, 2.4000,
+                12.0, 2.4427, 0.0869, -0.2946, 0.1735,
+            ]).reshape(-1, 5)
+        for c, mean, var, skew, kurt in table:
+            computed = stats.loggamma.stats(c, moments='msvk')
+            assert_array_almost_equal(computed, [mean, var, skew, kurt],
+                                      decimal=4)
+
+    @pytest.mark.parametrize('c', [0.1, 0.001])
+    def test_rvs(self, c):
+        # Regression test for gh-11094.
+        x = stats.loggamma.rvs(c, size=100000)
+        # Before gh-11094 was fixed, the case with c=0.001 would
+        # generate many -inf values.
+        assert np.isfinite(x).all()
+        # Crude statistical test.  About half the values should be
+        # less than the median and half greater than the median.
+        med = stats.loggamma.median(c)
+        btest = stats.binomtest(np.count_nonzero(x < med), len(x))
+        ci = btest.proportion_ci(confidence_level=0.999)
+        assert ci.low < 0.5 < ci.high
+
+    @pytest.mark.parametrize("c, ref",
+                             [(1e-8, 19.420680753952364),
+                              (1, 1.5772156649015328),
+                              (1e4, -3.186214986116763),
+                              (1e10, -10.093986931748889),
+                              (1e100, -113.71031611649761)])
+    def test_entropy(self, c, ref):
+
+        # Reference values were calculated with mpmath
+        # from mpmath import mp
+        # mp.dps = 500
+        # def loggamma_entropy_mpmath(c):
+        #     c = mp.mpf(c)
+        #     return float(mp.log(mp.gamma(c)) + c * (mp.one - mp.digamma(c)))
+
+        assert_allclose(stats.loggamma.entropy(c), ref, rtol=1e-14)
+
+
+class TestJohnsonsu:
+    # reference values were computed via mpmath
+    # from mpmath import mp
+    # mp.dps = 50
+    # def johnsonsu_sf(x, a, b):
+    #     x = mp.mpf(x)
+    #     a = mp.mpf(a)
+    #     b = mp.mpf(b)
+    #     return float(mp.ncdf(-(a + b * mp.log(x + mp.sqrt(x*x + 1)))))
+    # Order is x, a, b, sf, isf tol
+    # (Can't expect full precision when the ISF input is very nearly 1)
+    cases = [(-500, 1, 1, 0.9999999982660072, 1e-8),
+             (2000, 1, 1, 7.426351000595343e-21, 5e-14),
+             (100000, 1, 1, 4.046923979269977e-40, 5e-14)]
+
+    @pytest.mark.parametrize("case", cases)
+    def test_sf_isf(self, case):
+        x, a, b, sf, tol = case
+        assert_allclose(stats.johnsonsu.sf(x, a, b), sf, rtol=5e-14)
+        assert_allclose(stats.johnsonsu.isf(sf, a, b), x, rtol=tol)
+
+
+class TestJohnsonb:
+    # reference values were computed via mpmath
+    # from mpmath import mp
+    # mp.dps = 50
+    # def johnsonb_sf(x, a, b):
+    #     x = mp.mpf(x)
+    #     a = mp.mpf(a)
+    #     b = mp.mpf(b)
+    #     return float(mp.ncdf(-(a + b * mp.log(x/(mp.one - x)))))
+    # Order is x, a, b, sf, isf atol
+    # (Can't expect full precision when the ISF input is very nearly 1)
+    cases = [(1e-4, 1, 1, 0.9999999999999999, 1e-7),
+             (0.9999, 1, 1, 8.921114313932308e-25, 5e-14),
+             (0.999999, 1, 1, 5.815197487181902e-50, 5e-14)]
+
+    @pytest.mark.parametrize("case", cases)
+    def test_sf_isf(self, case):
+        x, a, b, sf, tol = case
+        assert_allclose(stats.johnsonsb.sf(x, a, b), sf, rtol=5e-14)
+        assert_allclose(stats.johnsonsb.isf(sf, a, b), x, atol=tol)
+
+
+class TestLogistic:
+    # gh-6226
+    def test_cdf_ppf(self):
+        x = np.linspace(-20, 20)
+        y = stats.logistic.cdf(x)
+        xx = stats.logistic.ppf(y)
+        assert_allclose(x, xx)
+
+    def test_sf_isf(self):
+        x = np.linspace(-20, 20)
+        y = stats.logistic.sf(x)
+        xx = stats.logistic.isf(y)
+        assert_allclose(x, xx)
+
+    def test_extreme_values(self):
+        # p is chosen so that 1 - (1 - p) == p in double precision
+        p = 9.992007221626409e-16
+        desired = 34.53957599234088
+        assert_allclose(stats.logistic.ppf(1 - p), desired)
+        assert_allclose(stats.logistic.isf(p), desired)
+
+    def test_logpdf_basic(self):
+        logp = stats.logistic.logpdf([-15, 0, 10])
+        # Expected values computed with mpmath with 50 digits of precision.
+        expected = [-15.000000611804547,
+                    -1.3862943611198906,
+                    -10.000090797798434]
+        assert_allclose(logp, expected, rtol=1e-13)
+
+    def test_logpdf_extreme_values(self):
+        logp = stats.logistic.logpdf([800, -800])
+        # For such large arguments, logpdf(x) = -abs(x) when computed
+        # with 64 bit floating point.
+        assert_equal(logp, [-800, -800])
+
+    @pytest.mark.parametrize("loc_rvs,scale_rvs", [(0.4484955, 0.10216821),
+                                                   (0.62918191, 0.74367064)])
+    def test_fit(self, loc_rvs, scale_rvs):
+        data = stats.logistic.rvs(size=100, loc=loc_rvs, scale=scale_rvs)
+
+        # test that result of fit method is the same as optimization
+        def func(input, data):
+            a, b = input
+            n = len(data)
+            x1 = np.sum(np.exp((data - a) / b) /
+                        (1 + np.exp((data - a) / b))) - n / 2
+            x2 = np.sum(((data - a) / b) *
+                        ((np.exp((data - a) / b) - 1) /
+                         (np.exp((data - a) / b) + 1))) - n
+            return x1, x2
+
+        expected_solution = root(func, stats.logistic._fitstart(data), args=(
+            data,)).x
+        fit_method = stats.logistic.fit(data)
+
+        # other than computational variances, the fit method and the solution
+        # to this system of equations are equal
+        assert_allclose(fit_method, expected_solution, atol=1e-30)
+
+    def test_fit_comp_optimizer(self):
+        data = stats.logistic.rvs(size=100, loc=0.5, scale=2)
+        _assert_less_or_close_loglike(stats.logistic, data)
+        _assert_less_or_close_loglike(stats.logistic, data, floc=1)
+        _assert_less_or_close_loglike(stats.logistic, data, fscale=1)
+
+    @pytest.mark.parametrize('testlogcdf', [True, False])
+    def test_logcdfsf_tails(self, testlogcdf):
+        # Test either logcdf or logsf.  By symmetry, we can use the same
+        # expected values for both by switching the sign of x for logsf.
+        x = np.array([-10000, -800, 17, 50, 500])
+        if testlogcdf:
+            y = stats.logistic.logcdf(x)
+        else:
+            y = stats.logistic.logsf(-x)
+        # The expected values were computed with mpmath.
+        expected = [-10000.0, -800.0, -4.139937633089748e-08,
+                    -1.9287498479639178e-22, -7.124576406741286e-218]
+        assert_allclose(y, expected, rtol=2e-15)
+
+    def test_fit_gh_18176(self):
+        # logistic.fit returned `scale < 0` for this data. Check that this has
+        # been fixed.
+        data = np.array([-459, 37, 43, 45, 45, 48, 54, 55, 58]
+                        + [59] * 3 + [61] * 9)
+        # If scale were negative, NLLF would be infinite, so this would fail
+        _assert_less_or_close_loglike(stats.logistic, data)
+
+
+class TestLogser:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.logser.rvs(0.75, size=(2, 50))
+        assert np.all(vals >= 1)
+        assert np.shape(vals) == (2, 50)
+        assert vals.dtype.char in typecodes['AllInteger']
+        val = stats.logser.rvs(0.75)
+        assert isinstance(val, int)
+        val = stats.logser(0.75).rvs(3)
+        assert isinstance(val, np.ndarray)
+        assert val.dtype.char in typecodes['AllInteger']
+
+    def test_pmf_small_p(self):
+        m = stats.logser.pmf(4, 1e-20)
+        # The expected value was computed using mpmath:
+        #   >>> import mpmath
+        #   >>> mpmath.mp.dps = 64
+        #   >>> k = 4
+        #   >>> p = mpmath.mpf('1e-20')
+        #   >>> float(-(p**k)/k/mpmath.log(1-p))
+        #   2.5e-61
+        # It is also clear from noticing that for very small p,
+        # log(1-p) is approximately -p, and the formula becomes
+        #    p**(k-1) / k
+        assert_allclose(m, 2.5e-61)
+
+    def test_mean_small_p(self):
+        m = stats.logser.mean(1e-8)
+        # The expected mean was computed using mpmath:
+        #   >>> import mpmath
+        #   >>> mpmath.dps = 60
+        #   >>> p = mpmath.mpf('1e-8')
+        #   >>> float(-p / ((1 - p)*mpmath.log(1 - p)))
+        #   1.000000005
+        assert_allclose(m, 1.000000005)
+
+
+class TestGumbel_r_l:
+    @pytest.fixture(scope='function')
+    def rng(self):
+        return np.random.default_rng(1234)
+
+    @pytest.mark.parametrize("dist", [stats.gumbel_r, stats.gumbel_l])
+    @pytest.mark.parametrize("loc_rvs", [-1, 0, 1])
+    @pytest.mark.parametrize("scale_rvs", [.1, 1, 5])
+    @pytest.mark.parametrize('fix_loc, fix_scale',
+                             ([True, False], [False, True]))
+    def test_fit_comp_optimizer(self, dist, loc_rvs, scale_rvs,
+                                fix_loc, fix_scale, rng):
+        data = dist.rvs(size=100, loc=loc_rvs, scale=scale_rvs,
+                        random_state=rng)
+
+        kwds = dict()
+        # the fixed location and scales are arbitrarily modified to not be
+        # close to the true value.
+        if fix_loc:
+            kwds['floc'] = loc_rvs * 2
+        if fix_scale:
+            kwds['fscale'] = scale_rvs * 2
+
+        # test that the gumbel_* fit method is better than super method
+        _assert_less_or_close_loglike(dist, data, **kwds)
+
+    @pytest.mark.parametrize("dist, sgn", [(stats.gumbel_r, 1),
+                                           (stats.gumbel_l, -1)])
+    def test_fit(self, dist, sgn):
+        z = sgn*np.array([3, 3, 3, 3, 3, 3, 3, 3.00000001])
+        loc, scale = dist.fit(z)
+        # The expected values were computed with mpmath with 60 digits
+        # of precision.
+        assert_allclose(loc, sgn*3.0000000001667906)
+        assert_allclose(scale, 1.2495222465145514e-09, rtol=1e-6)
+
+
+class TestPareto:
+    def test_stats(self):
+        # Check the stats() method with some simple values. Also check
+        # that the calculations do not trigger RuntimeWarnings.
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", RuntimeWarning)
+
+            m, v, s, k = stats.pareto.stats(0.5, moments='mvsk')
+            assert_equal(m, np.inf)
+            assert_equal(v, np.inf)
+            assert_equal(s, np.nan)
+            assert_equal(k, np.nan)
+
+            m, v, s, k = stats.pareto.stats(1.0, moments='mvsk')
+            assert_equal(m, np.inf)
+            assert_equal(v, np.inf)
+            assert_equal(s, np.nan)
+            assert_equal(k, np.nan)
+
+            m, v, s, k = stats.pareto.stats(1.5, moments='mvsk')
+            assert_equal(m, 3.0)
+            assert_equal(v, np.inf)
+            assert_equal(s, np.nan)
+            assert_equal(k, np.nan)
+
+            m, v, s, k = stats.pareto.stats(2.0, moments='mvsk')
+            assert_equal(m, 2.0)
+            assert_equal(v, np.inf)
+            assert_equal(s, np.nan)
+            assert_equal(k, np.nan)
+
+            m, v, s, k = stats.pareto.stats(2.5, moments='mvsk')
+            assert_allclose(m, 2.5 / 1.5)
+            assert_allclose(v, 2.5 / (1.5*1.5*0.5))
+            assert_equal(s, np.nan)
+            assert_equal(k, np.nan)
+
+            m, v, s, k = stats.pareto.stats(3.0, moments='mvsk')
+            assert_allclose(m, 1.5)
+            assert_allclose(v, 0.75)
+            assert_equal(s, np.nan)
+            assert_equal(k, np.nan)
+
+            m, v, s, k = stats.pareto.stats(3.5, moments='mvsk')
+            assert_allclose(m, 3.5 / 2.5)
+            assert_allclose(v, 3.5 / (2.5*2.5*1.5))
+            assert_allclose(s, (2*4.5/0.5)*np.sqrt(1.5/3.5))
+            assert_equal(k, np.nan)
+
+            m, v, s, k = stats.pareto.stats(4.0, moments='mvsk')
+            assert_allclose(m, 4.0 / 3.0)
+            assert_allclose(v, 4.0 / 18.0)
+            assert_allclose(s, 2*(1+4.0)/(4.0-3) * np.sqrt((4.0-2)/4.0))
+            assert_equal(k, np.nan)
+
+            m, v, s, k = stats.pareto.stats(4.5, moments='mvsk')
+            assert_allclose(m, 4.5 / 3.5)
+            assert_allclose(v, 4.5 / (3.5*3.5*2.5))
+            assert_allclose(s, (2*5.5/1.5) * np.sqrt(2.5/4.5))
+            assert_allclose(k, 6*(4.5**3 + 4.5**2 - 6*4.5 - 2)/(4.5*1.5*0.5))
+
+    def test_sf(self):
+        x = 1e9
+        b = 2
+        scale = 1.5
+        p = stats.pareto.sf(x, b, loc=0, scale=scale)
+        expected = (scale/x)**b   # 2.25e-18
+        assert_allclose(p, expected)
+
+    @pytest.fixture(scope='function')
+    def rng(self):
+        return np.random.default_rng(1234)
+
+    @pytest.mark.filterwarnings("ignore:invalid value encountered in "
+                                "double_scalars")
+    @pytest.mark.parametrize("rvs_shape", [1, 2])
+    @pytest.mark.parametrize("rvs_loc", [0, 2])
+    @pytest.mark.parametrize("rvs_scale", [1, 5])
+    def test_fit(self, rvs_shape, rvs_loc, rvs_scale, rng):
+        data = stats.pareto.rvs(size=100, b=rvs_shape, scale=rvs_scale,
+                                loc=rvs_loc, random_state=rng)
+
+        # shape can still be fixed with multiple names
+        shape_mle_analytical1 = stats.pareto.fit(data, floc=0, f0=1.04)[0]
+        shape_mle_analytical2 = stats.pareto.fit(data, floc=0, fix_b=1.04)[0]
+        shape_mle_analytical3 = stats.pareto.fit(data, floc=0, fb=1.04)[0]
+        assert (shape_mle_analytical1 == shape_mle_analytical2 ==
+                shape_mle_analytical3 == 1.04)
+
+        # data can be shifted with changes to `loc`
+        data = stats.pareto.rvs(size=100, b=rvs_shape, scale=rvs_scale,
+                                loc=(rvs_loc + 2), random_state=rng)
+        shape_mle_a, loc_mle_a, scale_mle_a = stats.pareto.fit(data, floc=2)
+        assert_equal(scale_mle_a + 2, data.min())
+
+        data_shift = data - 2
+        ndata = data_shift.shape[0]
+        assert_equal(shape_mle_a,
+                     ndata / np.sum(np.log(data_shift/data_shift.min())))
+        assert_equal(loc_mle_a, 2)
+
+    @pytest.mark.parametrize("rvs_shape", [.1, 2])
+    @pytest.mark.parametrize("rvs_loc", [0, 2])
+    @pytest.mark.parametrize("rvs_scale", [1, 5])
+    @pytest.mark.parametrize('fix_shape, fix_loc, fix_scale',
+                             [p for p in product([True, False], repeat=3)
+                              if False in p])
+    @np.errstate(invalid="ignore")
+    def test_fit_MLE_comp_optimizer(self, rvs_shape, rvs_loc, rvs_scale,
+                                    fix_shape, fix_loc, fix_scale, rng):
+        data = stats.pareto.rvs(size=100, b=rvs_shape, scale=rvs_scale,
+                                loc=rvs_loc, random_state=rng)
+
+        kwds = {}
+        if fix_shape:
+            kwds['f0'] = rvs_shape
+        if fix_loc:
+            kwds['floc'] = rvs_loc
+        if fix_scale:
+            kwds['fscale'] = rvs_scale
+
+        _assert_less_or_close_loglike(stats.pareto, data, **kwds)
+
+    @np.errstate(invalid="ignore")
+    def test_fit_known_bad_seed(self):
+        # Tests a known seed and set of parameters that would produce a result
+        # would violate the support of Pareto if the fit method did not check
+        # the constraint `fscale + floc < min(data)`.
+        shape, location, scale = 1, 0, 1
+        data = stats.pareto.rvs(shape, location, scale, size=100,
+                                random_state=np.random.default_rng(2535619))
+        _assert_less_or_close_loglike(stats.pareto, data)
+
+    def test_fit_warnings(self):
+        assert_fit_warnings(stats.pareto)
+        # `floc` that causes invalid negative data
+        assert_raises(FitDataError, stats.pareto.fit, [1, 2, 3], floc=2)
+        # `floc` and `fscale` combination causes invalid data
+        assert_raises(FitDataError, stats.pareto.fit, [5, 2, 3], floc=1,
+                      fscale=3)
+
+    def test_negative_data(self, rng):
+        data = stats.pareto.rvs(loc=-130, b=1, size=100, random_state=rng)
+        assert_array_less(data, 0)
+        # The purpose of this test is to make sure that no runtime warnings are
+        # raised for all negative data, not the output of the fit method. Other
+        # methods test the output but have to silence warnings from the super
+        # method.
+        _ = stats.pareto.fit(data)
+
+
+class TestGenpareto:
+    def test_ab(self):
+        # c >= 0: a, b = [0, inf]
+        for c in [1., 0.]:
+            c = np.asarray(c)
+            a, b = stats.genpareto._get_support(c)
+            assert_equal(a, 0.)
+            assert_(np.isposinf(b))
+
+        # c < 0: a=0, b=1/|c|
+        c = np.asarray(-2.)
+        a, b = stats.genpareto._get_support(c)
+        assert_allclose([a, b], [0., 0.5])
+
+    def test_c0(self):
+        # with c=0, genpareto reduces to the exponential distribution
+        # rv = stats.genpareto(c=0.)
+        rv = stats.genpareto(c=0.)
+        x = np.linspace(0, 10., 30)
+        assert_allclose(rv.pdf(x), stats.expon.pdf(x))
+        assert_allclose(rv.cdf(x), stats.expon.cdf(x))
+        assert_allclose(rv.sf(x), stats.expon.sf(x))
+
+        q = np.linspace(0., 1., 10)
+        assert_allclose(rv.ppf(q), stats.expon.ppf(q))
+
+    def test_cm1(self):
+        # with c=-1, genpareto reduces to the uniform distr on [0, 1]
+        rv = stats.genpareto(c=-1.)
+        x = np.linspace(0, 10., 30)
+        assert_allclose(rv.pdf(x), stats.uniform.pdf(x))
+        assert_allclose(rv.cdf(x), stats.uniform.cdf(x))
+        assert_allclose(rv.sf(x), stats.uniform.sf(x))
+
+        q = np.linspace(0., 1., 10)
+        assert_allclose(rv.ppf(q), stats.uniform.ppf(q))
+
+        # logpdf(1., c=-1) should be zero
+        assert_allclose(rv.logpdf(1), 0)
+
+    def test_x_inf(self):
+        # make sure x=inf is handled gracefully
+        rv = stats.genpareto(c=0.1)
+        assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.])
+        assert_(np.isneginf(rv.logpdf(np.inf)))
+
+        rv = stats.genpareto(c=0.)
+        assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.])
+        assert_(np.isneginf(rv.logpdf(np.inf)))
+
+        rv = stats.genpareto(c=-1.)
+        assert_allclose([rv.pdf(np.inf), rv.cdf(np.inf)], [0., 1.])
+        assert_(np.isneginf(rv.logpdf(np.inf)))
+
+    def test_c_continuity(self):
+        # pdf is continuous at c=0, -1
+        x = np.linspace(0, 10, 30)
+        for c in [0, -1]:
+            pdf0 = stats.genpareto.pdf(x, c)
+            for dc in [1e-14, -1e-14]:
+                pdfc = stats.genpareto.pdf(x, c + dc)
+                assert_allclose(pdf0, pdfc, atol=1e-12)
+
+            cdf0 = stats.genpareto.cdf(x, c)
+            for dc in [1e-14, 1e-14]:
+                cdfc = stats.genpareto.cdf(x, c + dc)
+                assert_allclose(cdf0, cdfc, atol=1e-12)
+
+    def test_c_continuity_ppf(self):
+        q = np.r_[np.logspace(1e-12, 0.01, base=0.1),
+                  np.linspace(0.01, 1, 30, endpoint=False),
+                  1. - np.logspace(1e-12, 0.01, base=0.1)]
+        for c in [0., -1.]:
+            ppf0 = stats.genpareto.ppf(q, c)
+            for dc in [1e-14, -1e-14]:
+                ppfc = stats.genpareto.ppf(q, c + dc)
+                assert_allclose(ppf0, ppfc, atol=1e-12)
+
+    def test_c_continuity_isf(self):
+        q = np.r_[np.logspace(1e-12, 0.01, base=0.1),
+                  np.linspace(0.01, 1, 30, endpoint=False),
+                  1. - np.logspace(1e-12, 0.01, base=0.1)]
+        for c in [0., -1.]:
+            isf0 = stats.genpareto.isf(q, c)
+            for dc in [1e-14, -1e-14]:
+                isfc = stats.genpareto.isf(q, c + dc)
+                assert_allclose(isf0, isfc, atol=1e-12)
+
+    def test_cdf_ppf_roundtrip(self):
+        # this should pass with machine precision. hat tip @pbrod
+        q = np.r_[np.logspace(1e-12, 0.01, base=0.1),
+                  np.linspace(0.01, 1, 30, endpoint=False),
+                  1. - np.logspace(1e-12, 0.01, base=0.1)]
+        for c in [1e-8, -1e-18, 1e-15, -1e-15]:
+            assert_allclose(stats.genpareto.cdf(stats.genpareto.ppf(q, c), c),
+                            q, atol=1e-15)
+
+    def test_logsf(self):
+        logp = stats.genpareto.logsf(1e10, .01, 0, 1)
+        assert_allclose(logp, -1842.0680753952365)
+
+    # Values in 'expected_stats' are
+    # [mean, variance, skewness, excess kurtosis].
+    @pytest.mark.parametrize(
+        'c, expected_stats',
+        [(0, [1, 1, 2, 6]),
+         (1/4, [4/3, 32/9, 10/np.sqrt(2), np.nan]),
+         (1/9, [9/8, (81/64)*(9/7), (10/9)*np.sqrt(7), 754/45]),
+         (-1, [1/2, 1/12, 0, -6/5])])
+    def test_stats(self, c, expected_stats):
+        result = stats.genpareto.stats(c, moments='mvsk')
+        assert_allclose(result, expected_stats, rtol=1e-13, atol=1e-15)
+
+    def test_var(self):
+        # Regression test for gh-11168.
+        v = stats.genpareto.var(1e-8)
+        assert_allclose(v, 1.000000040000001, rtol=1e-13)
+
+
+class TestPearson3:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.pearson3.rvs(0.1, size=(2, 50))
+        assert np.shape(vals) == (2, 50)
+        assert vals.dtype.char in typecodes['AllFloat']
+        val = stats.pearson3.rvs(0.5)
+        assert isinstance(val, float)
+        val = stats.pearson3(0.5).rvs(3)
+        assert isinstance(val, np.ndarray)
+        assert val.dtype.char in typecodes['AllFloat']
+        assert len(val) == 3
+
+    def test_pdf(self):
+        vals = stats.pearson3.pdf(2, [0.0, 0.1, 0.2])
+        assert_allclose(vals, np.array([0.05399097, 0.05555481, 0.05670246]),
+                        atol=1e-6)
+        vals = stats.pearson3.pdf(-3, 0.1)
+        assert_allclose(vals, np.array([0.00313791]), atol=1e-6)
+        vals = stats.pearson3.pdf([-3, -2, -1, 0, 1], 0.1)
+        assert_allclose(vals, np.array([0.00313791, 0.05192304, 0.25028092,
+                                        0.39885918, 0.23413173]), atol=1e-6)
+
+    def test_cdf(self):
+        vals = stats.pearson3.cdf(2, [0.0, 0.1, 0.2])
+        assert_allclose(vals, np.array([0.97724987, 0.97462004, 0.97213626]),
+                        atol=1e-6)
+        vals = stats.pearson3.cdf(-3, 0.1)
+        assert_allclose(vals, [0.00082256], atol=1e-6)
+        vals = stats.pearson3.cdf([-3, -2, -1, 0, 1], 0.1)
+        assert_allclose(vals, [8.22563821e-04, 1.99860448e-02, 1.58550710e-01,
+                               5.06649130e-01, 8.41442111e-01], atol=1e-6)
+
+    def test_negative_cdf_bug_11186(self):
+        # incorrect CDFs for negative skews in gh-11186; fixed in gh-12640
+        # Also check vectorization w/ negative, zero, and positive skews
+        skews = [-3, -1, 0, 0.5]
+        x_eval = 0.5
+        neg_inf = -30  # avoid RuntimeWarning caused by np.log(0)
+        cdfs = stats.pearson3.cdf(x_eval, skews)
+        int_pdfs = [quad(stats.pearson3(skew).pdf, neg_inf, x_eval)[0]
+                    for skew in skews]
+        assert_allclose(cdfs, int_pdfs)
+
+    def test_return_array_bug_11746(self):
+        # pearson3.moment was returning size 0 or 1 array instead of float
+        # The first moment is equal to the loc, which defaults to zero
+        moment = stats.pearson3.moment(1, 2)
+        assert_equal(moment, 0)
+        assert isinstance(moment, np.number)
+
+        moment = stats.pearson3.moment(1, 0.000001)
+        assert_equal(moment, 0)
+        assert isinstance(moment, np.number)
+
+    def test_ppf_bug_17050(self):
+        # incorrect PPF for negative skews were reported in gh-17050
+        # Check that this is fixed (even in the array case)
+        skews = [-3, -1, 0, 0.5]
+        x_eval = 0.5
+        res = stats.pearson3.ppf(stats.pearson3.cdf(x_eval, skews), skews)
+        assert_allclose(res, x_eval)
+
+        # Negation of the skew flips the distribution about the origin, so
+        # the following should hold
+        skew = np.array([[-0.5], [1.5]])
+        x = np.linspace(-2, 2)
+        assert_allclose(stats.pearson3.pdf(x, skew),
+                        stats.pearson3.pdf(-x, -skew))
+        assert_allclose(stats.pearson3.cdf(x, skew),
+                        stats.pearson3.sf(-x, -skew))
+        assert_allclose(stats.pearson3.ppf(x, skew),
+                        -stats.pearson3.isf(x, -skew))
+
+    def test_sf(self):
+        # reference values were computed via the reference distribution, e.g.
+        # mp.dps = 50; Pearson3(skew=skew).sf(x). Check positive, negative,
+        # and zero skew due to branching.
+        skew = [0.1, 0.5, 1.0, -0.1]
+        x = [5.0, 10.0, 50.0, 8.0]
+        ref = [1.64721926440872e-06, 8.271911573556123e-11,
+               1.3149506021756343e-40, 2.763057937820296e-21]
+        assert_allclose(stats.pearson3.sf(x, skew), ref, rtol=2e-14)
+        assert_allclose(stats.pearson3.sf(x, 0), stats.norm.sf(x), rtol=2e-14)
+
+
+class TestKappa4:
+    def test_cdf_genpareto(self):
+        # h = 1 and k != 0 is generalized Pareto
+        x = [0.0, 0.1, 0.2, 0.5]
+        h = 1.0
+        for k in [-1.9, -1.0, -0.5, -0.2, -0.1, 0.1, 0.2, 0.5, 1.0,
+                  1.9]:
+            vals = stats.kappa4.cdf(x, h, k)
+            # shape parameter is opposite what is expected
+            vals_comp = stats.genpareto.cdf(x, -k)
+            assert_allclose(vals, vals_comp)
+
+    def test_cdf_genextreme(self):
+        # h = 0 and k != 0 is generalized extreme value
+        x = np.linspace(-5, 5, 10)
+        h = 0.0
+        k = np.linspace(-3, 3, 10)
+        vals = stats.kappa4.cdf(x, h, k)
+        vals_comp = stats.genextreme.cdf(x, k)
+        assert_allclose(vals, vals_comp)
+
+    def test_cdf_expon(self):
+        # h = 1 and k = 0 is exponential
+        x = np.linspace(0, 10, 10)
+        h = 1.0
+        k = 0.0
+        vals = stats.kappa4.cdf(x, h, k)
+        vals_comp = stats.expon.cdf(x)
+        assert_allclose(vals, vals_comp)
+
+    def test_cdf_gumbel_r(self):
+        # h = 0 and k = 0 is gumbel_r
+        x = np.linspace(-5, 5, 10)
+        h = 0.0
+        k = 0.0
+        vals = stats.kappa4.cdf(x, h, k)
+        vals_comp = stats.gumbel_r.cdf(x)
+        assert_allclose(vals, vals_comp)
+
+    def test_cdf_logistic(self):
+        # h = -1 and k = 0 is logistic
+        x = np.linspace(-5, 5, 10)
+        h = -1.0
+        k = 0.0
+        vals = stats.kappa4.cdf(x, h, k)
+        vals_comp = stats.logistic.cdf(x)
+        assert_allclose(vals, vals_comp)
+
+    def test_cdf_uniform(self):
+        # h = 1 and k = 1 is uniform
+        x = np.linspace(-5, 5, 10)
+        h = 1.0
+        k = 1.0
+        vals = stats.kappa4.cdf(x, h, k)
+        vals_comp = stats.uniform.cdf(x)
+        assert_allclose(vals, vals_comp)
+
+    def test_integers_ctor(self):
+        # regression test for gh-7416: _argcheck fails for integer h and k
+        # in numpy 1.12
+        stats.kappa4(1, 2)
+
+
+class TestPoisson:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_pmf_basic(self):
+        # Basic case
+        ln2 = np.log(2)
+        vals = stats.poisson.pmf([0, 1, 2], ln2)
+        expected = [0.5, ln2/2, ln2**2/4]
+        assert_allclose(vals, expected)
+
+    def test_mu0(self):
+        # Edge case: mu=0
+        vals = stats.poisson.pmf([0, 1, 2], 0)
+        expected = [1, 0, 0]
+        assert_array_equal(vals, expected)
+
+        interval = stats.poisson.interval(0.95, 0)
+        assert_equal(interval, (0, 0))
+
+    def test_rvs(self):
+        vals = stats.poisson.rvs(0.5, size=(2, 50))
+        assert np.all(vals >= 0)
+        assert np.shape(vals) == (2, 50)
+        assert vals.dtype.char in typecodes['AllInteger']
+        val = stats.poisson.rvs(0.5)
+        assert isinstance(val, int)
+        val = stats.poisson(0.5).rvs(3)
+        assert isinstance(val, np.ndarray)
+        assert val.dtype.char in typecodes['AllInteger']
+
+    def test_stats(self):
+        mu = 16.0
+        result = stats.poisson.stats(mu, moments='mvsk')
+        assert_allclose(result, [mu, mu, np.sqrt(1.0/mu), 1.0/mu])
+
+        mu = np.array([0.0, 1.0, 2.0])
+        result = stats.poisson.stats(mu, moments='mvsk')
+        expected = (mu, mu, [np.inf, 1, 1/np.sqrt(2)], [np.inf, 1, 0.5])
+        assert_allclose(result, expected)
+
+
+class TestKSTwo:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_cdf(self):
+        for n in [1, 2, 3, 10, 100, 1000]:
+            # Test x-values:
+            #  0, 1/2n, where the cdf should be 0
+            #  1/n, where the cdf should be n!/n^n
+            #  0.5, where the cdf should match ksone.cdf
+            # 1-1/n, where cdf = 1-2/n^n
+            # 1, where cdf == 1
+            # (E.g. Exact values given by Eqn 1 in Simard / L'Ecuyer)
+            x = np.array([0, 0.5/n, 1/n, 0.5, 1-1.0/n, 1])
+            v1 = (1.0/n)**n
+            lg = scipy.special.gammaln(n+1)
+            elg = (np.exp(lg) if v1 != 0 else 0)
+            expected = np.array([0, 0, v1 * elg,
+                                 1 - 2*stats.ksone.sf(0.5, n),
+                                 max(1 - 2*v1, 0.0),
+                                 1.0])
+            vals_cdf = stats.kstwo.cdf(x, n)
+            assert_allclose(vals_cdf, expected)
+
+    def test_sf(self):
+        x = np.linspace(0, 1, 11)
+        for n in [1, 2, 3, 10, 100, 1000]:
+            # Same x values as in test_cdf, and use sf = 1 - cdf
+            x = np.array([0, 0.5/n, 1/n, 0.5, 1-1.0/n, 1])
+            v1 = (1.0/n)**n
+            lg = scipy.special.gammaln(n+1)
+            elg = (np.exp(lg) if v1 != 0 else 0)
+            expected = np.array([1.0, 1.0,
+                                 1 - v1 * elg,
+                                 2*stats.ksone.sf(0.5, n),
+                                 min(2*v1, 1.0), 0])
+            vals_sf = stats.kstwo.sf(x, n)
+            assert_allclose(vals_sf, expected)
+
+    def test_cdf_sqrtn(self):
+        # For fixed a, cdf(a/sqrt(n), n) -> kstwobign(a) as n->infinity
+        # cdf(a/sqrt(n), n) is an increasing function of n (and a)
+        # Check that the function is indeed increasing (allowing for some
+        # small floating point and algorithm differences.)
+        x = np.linspace(0, 2, 11)[1:]
+        ns = [50, 100, 200, 400, 1000, 2000]
+        for _x in x:
+            xn = _x / np.sqrt(ns)
+            probs = stats.kstwo.cdf(xn, ns)
+            diffs = np.diff(probs)
+            assert_array_less(diffs, 1e-8)
+
+    def test_cdf_sf(self):
+        x = np.linspace(0, 1, 11)
+        for n in [1, 2, 3, 10, 100, 1000]:
+            vals_cdf = stats.kstwo.cdf(x, n)
+            vals_sf = stats.kstwo.sf(x, n)
+            assert_array_almost_equal(vals_cdf, 1 - vals_sf)
+
+    def test_cdf_sf_sqrtn(self):
+        x = np.linspace(0, 1, 11)
+        for n in [1, 2, 3, 10, 100, 1000]:
+            xn = x / np.sqrt(n)
+            vals_cdf = stats.kstwo.cdf(xn, n)
+            vals_sf = stats.kstwo.sf(xn, n)
+            assert_array_almost_equal(vals_cdf, 1 - vals_sf)
+
+    def test_ppf_of_cdf(self):
+        x = np.linspace(0, 1, 11)
+        for n in [1, 2, 3, 10, 100, 1000]:
+            xn = x[x > 0.5/n]
+            vals_cdf = stats.kstwo.cdf(xn, n)
+            # CDFs close to 1 are better dealt with using the SF
+            cond = (0 < vals_cdf) & (vals_cdf < 0.99)
+            vals = stats.kstwo.ppf(vals_cdf, n)
+            assert_allclose(vals[cond], xn[cond], rtol=1e-4)
+
+    def test_isf_of_sf(self):
+        x = np.linspace(0, 1, 11)
+        for n in [1, 2, 3, 10, 100, 1000]:
+            xn = x[x > 0.5/n]
+            vals_isf = stats.kstwo.isf(xn, n)
+            cond = (0 < vals_isf) & (vals_isf < 1.0)
+            vals = stats.kstwo.sf(vals_isf, n)
+            assert_allclose(vals[cond], xn[cond], rtol=1e-4)
+
+    def test_ppf_of_cdf_sqrtn(self):
+        x = np.linspace(0, 1, 11)
+        for n in [1, 2, 3, 10, 100, 1000]:
+            xn = (x / np.sqrt(n))[x > 0.5/n]
+            vals_cdf = stats.kstwo.cdf(xn, n)
+            cond = (0 < vals_cdf) & (vals_cdf < 1.0)
+            vals = stats.kstwo.ppf(vals_cdf, n)
+            assert_allclose(vals[cond], xn[cond])
+
+    def test_isf_of_sf_sqrtn(self):
+        x = np.linspace(0, 1, 11)
+        for n in [1, 2, 3, 10, 100, 1000]:
+            xn = (x / np.sqrt(n))[x > 0.5/n]
+            vals_sf = stats.kstwo.sf(xn, n)
+            # SFs close to 1 are better dealt with using the CDF
+            cond = (0 < vals_sf) & (vals_sf < 0.95)
+            vals = stats.kstwo.isf(vals_sf, n)
+            assert_allclose(vals[cond], xn[cond])
+
+    def test_ppf(self):
+        probs = np.linspace(0, 1, 11)[1:]
+        for n in [1, 2, 3, 10, 100, 1000]:
+            xn = stats.kstwo.ppf(probs, n)
+            vals_cdf = stats.kstwo.cdf(xn, n)
+            assert_allclose(vals_cdf, probs)
+
+    def test_simard_lecuyer_table1(self):
+        # Compute the cdf for values near the mean of the distribution.
+        # The mean u ~ log(2)*sqrt(pi/(2n))
+        # Compute for x in [u/4, u/3, u/2, u, 2u, 3u]
+        # This is the computation of Table 1 of Simard, R., L'Ecuyer, P. (2011)
+        #  "Computing the Two-Sided Kolmogorov-Smirnov Distribution".
+        # Except that the values below are not from the published table, but
+        # were generated using an independent SageMath implementation of
+        # Durbin's algorithm (with the exponentiation and scaling of
+        # Marsaglia/Tsang/Wang's version) using 500 bit arithmetic.
+        # Some of the values in the published table have relative
+        # errors greater than 1e-4.
+        ns = [10, 50, 100, 200, 500, 1000]
+        ratios = np.array([1.0/4, 1.0/3, 1.0/2, 1, 2, 3])
+        expected = np.array([
+            [1.92155292e-08, 5.72933228e-05, 2.15233226e-02, 6.31566589e-01,
+             9.97685592e-01, 9.99999942e-01],
+            [2.28096224e-09, 1.99142563e-05, 1.42617934e-02, 5.95345542e-01,
+             9.96177701e-01, 9.99998662e-01],
+            [1.00201886e-09, 1.32673079e-05, 1.24608594e-02, 5.86163220e-01,
+             9.95866877e-01, 9.99998240e-01],
+            [4.93313022e-10, 9.52658029e-06, 1.12123138e-02, 5.79486872e-01,
+             9.95661824e-01, 9.99997964e-01],
+            [2.37049293e-10, 6.85002458e-06, 1.01309221e-02, 5.73427224e-01,
+             9.95491207e-01, 9.99997750e-01],
+            [1.56990874e-10, 5.71738276e-06, 9.59725430e-03, 5.70322692e-01,
+             9.95409545e-01, 9.99997657e-01]
+        ])
+        for idx, n in enumerate(ns):
+            x = ratios * np.log(2) * np.sqrt(np.pi/2/n)
+            vals_cdf = stats.kstwo.cdf(x, n)
+            assert_allclose(vals_cdf, expected[idx], rtol=1e-5)
+
+
+class TestZipf:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.zipf.rvs(1.5, size=(2, 50))
+        assert np.all(vals >= 1)
+        assert np.shape(vals) == (2, 50)
+        assert vals.dtype.char in typecodes['AllInteger']
+        val = stats.zipf.rvs(1.5)
+        assert isinstance(val, int)
+        val = stats.zipf(1.5).rvs(3)
+        assert isinstance(val, np.ndarray)
+        assert val.dtype.char in typecodes['AllInteger']
+
+    def test_moments(self):
+        # n-th moment is finite iff a > n + 1
+        m, v = stats.zipf.stats(a=2.8)
+        assert_(np.isfinite(m))
+        assert_equal(v, np.inf)
+
+        s, k = stats.zipf.stats(a=4.8, moments='sk')
+        assert_(not np.isfinite([s, k]).all())
+
+
+class TestDLaplace:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        vals = stats.dlaplace.rvs(1.5, size=(2, 50))
+        assert np.shape(vals) == (2, 50)
+        assert vals.dtype.char in typecodes['AllInteger']
+        val = stats.dlaplace.rvs(1.5)
+        assert isinstance(val, int)
+        val = stats.dlaplace(1.5).rvs(3)
+        assert isinstance(val, np.ndarray)
+        assert val.dtype.char in typecodes['AllInteger']
+        assert stats.dlaplace.rvs(0.8) is not None
+
+    def test_stats(self):
+        # compare the explicit formulas w/ direct summation using pmf
+        a = 1.
+        dl = stats.dlaplace(a)
+        m, v, s, k = dl.stats('mvsk')
+
+        N = 37
+        xx = np.arange(-N, N+1)
+        pp = dl.pmf(xx)
+        m2, m4 = np.sum(pp*xx**2), np.sum(pp*xx**4)
+        assert_equal((m, s), (0, 0))
+        assert_allclose((v, k), (m2, m4/m2**2 - 3.), atol=1e-14, rtol=1e-8)
+
+    def test_stats2(self):
+        a = np.log(2.)
+        dl = stats.dlaplace(a)
+        m, v, s, k = dl.stats('mvsk')
+        assert_equal((m, s), (0., 0.))
+        assert_allclose((v, k), (4., 3.25))
+
+
+class TestInvgauss:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    @pytest.mark.parametrize("rvs_mu,rvs_loc,rvs_scale",
+                             [(2, 0, 1), (4.635, 4.362, 6.303)])
+    def test_fit(self, rvs_mu, rvs_loc, rvs_scale):
+        data = stats.invgauss.rvs(size=100, mu=rvs_mu,
+                                  loc=rvs_loc, scale=rvs_scale)
+        # Analytical MLEs are calculated with formula when `floc` is fixed
+        mu, loc, scale = stats.invgauss.fit(data, floc=rvs_loc)
+
+        data = data - rvs_loc
+        mu_temp = np.mean(data)
+        scale_mle = len(data) / (np.sum(data**(-1) - mu_temp**(-1)))
+        mu_mle = mu_temp/scale_mle
+
+        # `mu` and `scale` match analytical formula
+        assert_allclose(mu_mle, mu, atol=1e-15, rtol=1e-15)
+        assert_allclose(scale_mle, scale, atol=1e-15, rtol=1e-15)
+        assert_equal(loc, rvs_loc)
+        data = stats.invgauss.rvs(size=100, mu=rvs_mu,
+                                  loc=rvs_loc, scale=rvs_scale)
+        # fixed parameters are returned
+        mu, loc, scale = stats.invgauss.fit(data, floc=rvs_loc - 1,
+                                            fscale=rvs_scale + 1)
+        assert_equal(rvs_scale + 1, scale)
+        assert_equal(rvs_loc - 1, loc)
+
+        # shape can still be fixed with multiple names
+        shape_mle1 = stats.invgauss.fit(data, fmu=1.04)[0]
+        shape_mle2 = stats.invgauss.fit(data, fix_mu=1.04)[0]
+        shape_mle3 = stats.invgauss.fit(data, f0=1.04)[0]
+        assert shape_mle1 == shape_mle2 == shape_mle3 == 1.04
+
+    @pytest.mark.parametrize("rvs_mu,rvs_loc,rvs_scale",
+                             [(2, 0, 1), (6.311, 3.225, 4.520)])
+    def test_fit_MLE_comp_optimizer(self, rvs_mu, rvs_loc, rvs_scale):
+        rng = np.random.RandomState(1234)
+        data = stats.invgauss.rvs(size=100, mu=rvs_mu,
+                                  loc=rvs_loc, scale=rvs_scale, random_state=rng)
+
+        super_fit = super(type(stats.invgauss), stats.invgauss).fit
+        # fitting without `floc` uses superclass fit method
+        super_fitted = super_fit(data)
+        invgauss_fit = stats.invgauss.fit(data)
+        assert_equal(super_fitted, invgauss_fit)
+
+        # fitting with `fmu` is uses superclass fit method
+        super_fitted = super_fit(data, floc=0, fmu=2)
+        invgauss_fit = stats.invgauss.fit(data, floc=0, fmu=2)
+        assert_equal(super_fitted, invgauss_fit)
+
+        # fixed `floc` uses analytical formula and provides better fit than
+        # super method
+        _assert_less_or_close_loglike(stats.invgauss, data, floc=rvs_loc)
+
+        # fixed `floc` not resulting in invalid data < 0 uses analytical
+        # formulas and provides a better fit than the super method
+        assert np.all((data - (rvs_loc - 1)) > 0)
+        _assert_less_or_close_loglike(stats.invgauss, data, floc=rvs_loc - 1)
+
+        # fixed `floc` to an arbitrary number, 0, still provides a better fit
+        # than the super method
+        _assert_less_or_close_loglike(stats.invgauss, data, floc=0)
+
+        # fixed `fscale` to an arbitrary number still provides a better fit
+        # than the super method
+        _assert_less_or_close_loglike(stats.invgauss, data, floc=rvs_loc,
+                                      fscale=np.random.rand(1)[0])
+
+    def test_fit_raise_errors(self):
+        assert_fit_warnings(stats.invgauss)
+        # FitDataError is raised when negative invalid data
+        with pytest.raises(FitDataError):
+            stats.invgauss.fit([1, 2, 3], floc=2)
+
+    def test_cdf_sf(self):
+        # Regression tests for gh-13614.
+        # Ground truth from R's statmod library (pinvgauss), e.g.
+        # library(statmod)
+        # options(digits=15)
+        # mu = c(4.17022005e-04, 7.20324493e-03, 1.14374817e-06,
+        #        3.02332573e-03, 1.46755891e-03)
+        # print(pinvgauss(5, mu, 1))
+
+        # make sure a finite value is returned when mu is very small. see
+        # GH-13614
+        mu = [4.17022005e-04, 7.20324493e-03, 1.14374817e-06,
+              3.02332573e-03, 1.46755891e-03]
+        expected = [1, 1, 1, 1, 1]
+        actual = stats.invgauss.cdf(0.4, mu=mu)
+        assert_equal(expected, actual)
+
+        # test if the function can distinguish small left/right tail
+        # probabilities from zero.
+        cdf_actual = stats.invgauss.cdf(0.001, mu=1.05)
+        assert_allclose(cdf_actual, 4.65246506892667e-219)
+        sf_actual = stats.invgauss.sf(110, mu=1.05)
+        assert_allclose(sf_actual, 4.12851625944048e-25)
+
+        # test if x does not cause numerical issues when mu is very small
+        # and x is close to mu in value.
+
+        # slightly smaller than mu
+        actual = stats.invgauss.cdf(0.00009, 0.0001)
+        assert_allclose(actual, 2.9458022894924e-26)
+
+        # slightly bigger than mu
+        actual = stats.invgauss.cdf(0.000102, 0.0001)
+        assert_allclose(actual, 0.976445540507925)
+
+    def test_logcdf_logsf(self):
+        # Regression tests for improvements made in gh-13616.
+        # Ground truth from R's statmod library (pinvgauss), e.g.
+        # library(statmod)
+        # options(digits=15)
+        # print(pinvgauss(0.001, 1.05, 1, log.p=TRUE, lower.tail=FALSE))
+
+        # test if logcdf and logsf can compute values too small to
+        # be represented on the unlogged scale. See: gh-13616
+        logcdf = stats.invgauss.logcdf(0.0001, mu=1.05)
+        assert_allclose(logcdf, -5003.87872590367)
+        logcdf = stats.invgauss.logcdf(110, 1.05)
+        assert_allclose(logcdf, -4.12851625944087e-25)
+        logsf = stats.invgauss.logsf(0.001, mu=1.05)
+        assert_allclose(logsf, -4.65246506892676e-219)
+        logsf = stats.invgauss.logsf(110, 1.05)
+        assert_allclose(logsf, -56.1467092416426)
+
+    # from mpmath import mp
+    # mp.dps = 100
+    # mu = mp.mpf(1e-2)
+    # ref = (1/2 * mp.log(2 * mp.pi * mp.e * mu**3)
+    #        - 3/2* mp.exp(2/mu) * mp.e1(2/mu))
+    @pytest.mark.parametrize("mu, ref", [(2e-8, -25.172361826883957),
+                                         (1e-3, -8.943444010642972),
+                                         (1e-2, -5.4962796152622335),
+                                         (1e8, 3.3244822568873476),
+                                         (1e100, 3.32448280139689)])
+    def test_entropy(self, mu, ref):
+        assert_allclose(stats.invgauss.entropy(mu), ref, rtol=5e-14)
+
+
+class TestLandau:
+    @pytest.mark.parametrize('name', ['pdf', 'cdf', 'sf', 'ppf', 'isf'])
+    def test_landau_levy_agreement(self, name):
+        # Test PDF to confirm that this is the Landau distribution
+        # Test other methods with tighter tolerance than generic tests
+        # Levy entropy is slow and inaccurate, and RVS is tested generically
+        if name in {'ppf', 'isf'}:
+            x = np.linspace(0.1, 0.9, 5),
+        else:
+            x = np.linspace(-2, 5, 10),
+
+        landau_method = getattr(stats.landau, name)
+        levy_method = getattr(stats.levy_stable, name)
+        res = landau_method(*x)
+        ref = levy_method(*x, 1, 1)
+        assert_allclose(res, ref, rtol=1e-14)
+
+    def test_moments(self):
+        # I would test these against Levy above, but Levy says variance is infinite.
+        assert_equal(stats.landau.stats(moments='mvsk'), (np.nan,)*4)
+        assert_equal(stats.landau.moment(5), np.nan)
+
+
+class TestLaplace:
+    @pytest.mark.parametrize("rvs_loc", [-5, 0, 1, 2])
+    @pytest.mark.parametrize("rvs_scale", [1, 2, 3, 10])
+    def test_fit(self, rvs_loc, rvs_scale):
+        # tests that various inputs follow expected behavior
+        # for a variety of `loc` and `scale`.
+        rng = np.random.RandomState(1234)
+        data = stats.laplace.rvs(size=100, loc=rvs_loc, scale=rvs_scale,
+                                 random_state=rng)
+
+        # MLE estimates are given by
+        loc_mle = np.median(data)
+        scale_mle = np.sum(np.abs(data - loc_mle)) / len(data)
+
+        # standard outputs should match analytical MLE formulas
+        loc, scale = stats.laplace.fit(data)
+        assert_allclose(loc, loc_mle, atol=1e-15, rtol=1e-15)
+        assert_allclose(scale, scale_mle, atol=1e-15, rtol=1e-15)
+
+        # fixed parameter should use analytical formula for other
+        loc, scale = stats.laplace.fit(data, floc=loc_mle)
+        assert_allclose(scale, scale_mle, atol=1e-15, rtol=1e-15)
+        loc, scale = stats.laplace.fit(data, fscale=scale_mle)
+        assert_allclose(loc, loc_mle)
+
+        # test with non-mle fixed parameter
+        # create scale with non-median loc
+        loc = rvs_loc * 2
+        scale_mle = np.sum(np.abs(data - loc)) / len(data)
+
+        # fixed loc to non median, scale should match
+        # scale calculation with modified loc
+        loc, scale = stats.laplace.fit(data, floc=loc)
+        assert_equal(scale_mle, scale)
+
+        # fixed scale created with non median loc,
+        # loc output should still be the data median.
+        loc, scale = stats.laplace.fit(data, fscale=scale_mle)
+        assert_equal(loc_mle, loc)
+
+        # error raised when both `floc` and `fscale` are fixed
+        assert_raises(RuntimeError, stats.laplace.fit, data, floc=loc_mle,
+                      fscale=scale_mle)
+
+        # error is raised with non-finite values
+        assert_raises(ValueError, stats.laplace.fit, [np.nan])
+        assert_raises(ValueError, stats.laplace.fit, [np.inf])
+
+    @pytest.mark.parametrize("rvs_loc,rvs_scale", [(-5, 10),
+                                                   (10, 5),
+                                                   (0.5, 0.2)])
+    def test_fit_MLE_comp_optimizer(self, rvs_loc, rvs_scale):
+        rng = np.random.RandomState(1234)
+        data = stats.laplace.rvs(size=1000, loc=rvs_loc, scale=rvs_scale,
+                                 random_state=rng)
+
+        # the log-likelihood function for laplace is given by
+        def ll(loc, scale, data):
+            return -1 * (- (len(data)) * np.log(2*scale) -
+                         (1/scale)*np.sum(np.abs(data - loc)))
+
+        # test that the objective function result of the analytical MLEs is
+        # less than or equal to that of the numerically optimized estimate
+        loc, scale = stats.laplace.fit(data)
+        loc_opt, scale_opt = super(type(stats.laplace),
+                                   stats.laplace).fit(data)
+        ll_mle = ll(loc, scale, data)
+        ll_opt = ll(loc_opt, scale_opt, data)
+        assert ll_mle < ll_opt or np.allclose(ll_mle, ll_opt,
+                                              atol=1e-15, rtol=1e-15)
+
+    def test_fit_simple_non_random_data(self):
+        data = np.array([1.0, 1.0, 3.0, 5.0, 8.0, 14.0])
+        # with `floc` fixed to 6, scale should be 4.
+        loc, scale = stats.laplace.fit(data, floc=6)
+        assert_allclose(scale, 4, atol=1e-15, rtol=1e-15)
+        # with `fscale` fixed to 6, loc should be 4.
+        loc, scale = stats.laplace.fit(data, fscale=6)
+        assert_allclose(loc, 4, atol=1e-15, rtol=1e-15)
+
+    def test_sf_cdf_extremes(self):
+        # These calculations should not generate warnings.
+        x = 1000
+        p0 = stats.laplace.cdf(-x)
+        # The exact value is smaller than can be represented with
+        # 64 bit floating point, so the expected result is 0.
+        assert p0 == 0.0
+        # The closest 64 bit floating point representation of the
+        # exact value is 1.0.
+        p1 = stats.laplace.cdf(x)
+        assert p1 == 1.0
+
+        p0 = stats.laplace.sf(x)
+        # The exact value is smaller than can be represented with
+        # 64 bit floating point, so the expected result is 0.
+        assert p0 == 0.0
+        # The closest 64 bit floating point representation of the
+        # exact value is 1.0.
+        p1 = stats.laplace.sf(-x)
+        assert p1 == 1.0
+
+    def test_sf(self):
+        x = 200
+        p = stats.laplace.sf(x)
+        assert_allclose(p, np.exp(-x)/2, rtol=1e-13)
+
+    def test_isf(self):
+        p = 1e-25
+        x = stats.laplace.isf(p)
+        assert_allclose(x, -np.log(2*p), rtol=1e-13)
+
+    def test_logcdf_logsf(self):
+        x = 40
+        # Reference value computed with mpmath.
+        ref = -2.1241771276457944e-18
+        logcdf = stats.laplace.logcdf(x)
+        assert_allclose(logcdf, ref)
+        logsf = stats.laplace.logsf(-x)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+
+class TestLogLaplace:
+
+    def test_sf(self):
+        # reference values were computed via the reference distribution, e.g.
+        # mp.dps = 100; LogLaplace(c=c).sf(x).
+        c = np.array([2.0, 3.0, 5.0])
+        x = np.array([1e-5, 1e10, 1e15])
+        ref = [0.99999999995, 5e-31, 5e-76]
+        assert_allclose(stats.loglaplace.sf(x, c), ref, rtol=1e-15)
+
+    def test_isf(self):
+        # reference values were computed via the reference distribution, e.g.
+        # mp.dps = 100; LogLaplace(c=c).isf(q).
+        c = 3.25
+        q = [0.8, 0.1, 1e-10, 1e-20, 1e-40]
+        ref = [0.7543222539245642, 1.6408455124660906, 964.4916294395846,
+               1151387.578354072, 1640845512466.0906]
+        assert_allclose(stats.loglaplace.isf(q, c), ref, rtol=1e-14)
+
+    @pytest.mark.parametrize('r', [1, 2, 3, 4])
+    def test_moments_stats(self, r):
+        mom = 'mvsk'[r - 1]
+        c = np.arange(0.5, r + 0.5, 0.5)
+
+        # r-th non-central moment is infinite if |r| >= c.
+        assert_allclose(stats.loglaplace.moment(r, c), np.inf)
+
+        # r-th non-central moment is non-finite (inf or nan) if r >= c.
+        assert not np.any(np.isfinite(stats.loglaplace.stats(c, moments=mom)))
+
+    @pytest.mark.parametrize("c", [0.5, 1.0, 2.0])
+    @pytest.mark.parametrize("loc, scale", [(-1.2, 3.45)])
+    @pytest.mark.parametrize("fix_c", [True, False])
+    @pytest.mark.parametrize("fix_scale", [True, False])
+    def test_fit_analytic_mle(self, c, loc, scale, fix_c, fix_scale):
+        # Test that the analytical MLE produces no worse result than the
+        # generic (numerical) MLE.
+
+        rng = np.random.default_rng(6762668991392531563)
+        data = stats.loglaplace.rvs(c, loc=loc, scale=scale, size=100,
+                                    random_state=rng)
+
+        kwds = {'floc': loc}
+        if fix_c:
+            kwds['fc'] = c
+        if fix_scale:
+            kwds['fscale'] = scale
+        nfree = 3 - len(kwds)
+
+        if nfree == 0:
+            error_msg = "All parameters fixed. There is nothing to optimize."
+            with pytest.raises((RuntimeError, ValueError), match=error_msg):
+                stats.loglaplace.fit(data, **kwds)
+            return
+
+        _assert_less_or_close_loglike(stats.loglaplace, data, **kwds)
+
+
+class TestPowerlaw:
+
+    # In the following data, `sf` was computed with mpmath.
+    @pytest.mark.parametrize('x, a, sf',
+                             [(0.25, 2.0, 0.9375),
+                              (0.99609375, 1/256, 1.528855235208108e-05)])
+    def test_sf(self, x, a, sf):
+        assert_allclose(stats.powerlaw.sf(x, a), sf, rtol=1e-15)
+
+    @pytest.fixture(scope='function')
+    def rng(self):
+        return np.random.default_rng(1234)
+
+    @pytest.mark.parametrize("rvs_shape", [.1, .5, .75, 1, 2])
+    @pytest.mark.parametrize("rvs_loc", [-1, 0, 1])
+    @pytest.mark.parametrize("rvs_scale", [.1, 1, 5])
+    @pytest.mark.parametrize('fix_shape, fix_loc, fix_scale',
+                             [p for p in product([True, False], repeat=3)
+                              if False in p])
+    def test_fit_MLE_comp_optimizer(self, rvs_shape, rvs_loc, rvs_scale,
+                                    fix_shape, fix_loc, fix_scale, rng):
+        data = stats.powerlaw.rvs(size=250, a=rvs_shape, loc=rvs_loc,
+                                  scale=rvs_scale, random_state=rng)
+
+        kwds = dict()
+        if fix_shape:
+            kwds['f0'] = rvs_shape
+        if fix_loc:
+            kwds['floc'] = np.nextafter(data.min(), -np.inf)
+        if fix_scale:
+            kwds['fscale'] = rvs_scale
+
+        # Numerical result may equal analytical result if some code path
+        # of the analytical routine makes use of numerical optimization.
+        _assert_less_or_close_loglike(stats.powerlaw, data, **kwds,
+                                      maybe_identical=True)
+
+    def test_problem_case(self):
+        # An observed problem with the test method indicated that some fixed
+        # scale values could cause bad results, this is now corrected.
+        a = 2.50002862645130604506
+        location = 0.0
+        scale = 35.249023299873095
+
+        data = stats.powerlaw.rvs(a=a, loc=location, scale=scale, size=100,
+                                  random_state=np.random.default_rng(5))
+
+        kwds = {'fscale': np.ptp(data) * 2}
+
+        _assert_less_or_close_loglike(stats.powerlaw, data, **kwds)
+
+    def test_fit_warnings(self):
+        assert_fit_warnings(stats.powerlaw)
+        # test for error when `fscale + floc <= np.max(data)` is not satisfied
+        msg = r" Maximum likelihood estimation with 'powerlaw' requires"
+        with assert_raises(FitDataError, match=msg):
+            stats.powerlaw.fit([1, 2, 4], floc=0, fscale=3)
+
+        # test for error when `data - floc >= 0`  is not satisfied
+        msg = r" Maximum likelihood estimation with 'powerlaw' requires"
+        with assert_raises(FitDataError, match=msg):
+            stats.powerlaw.fit([1, 2, 4], floc=2)
+
+        # test for fixed location not less than `min(data)`.
+        msg = r" Maximum likelihood estimation with 'powerlaw' requires"
+        with assert_raises(FitDataError, match=msg):
+            stats.powerlaw.fit([1, 2, 4], floc=1)
+
+        # test for when fixed scale is less than or equal to range of data
+        msg = r"Negative or zero `fscale` is outside"
+        with assert_raises(ValueError, match=msg):
+            stats.powerlaw.fit([1, 2, 4], fscale=-3)
+
+        # test for when fixed scale is less than or equal to range of data
+        msg = r"`fscale` must be greater than the range of data."
+        with assert_raises(ValueError, match=msg):
+            stats.powerlaw.fit([1, 2, 4], fscale=3)
+
+    def test_minimum_data_zero_gh17801(self):
+        # gh-17801 reported an overflow error when the minimum value of the
+        # data is zero. Check that this problem is resolved.
+        data = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6]
+        dist = stats.powerlaw
+        with np.errstate(over='ignore'):
+            _assert_less_or_close_loglike(dist, data)
+
+
+class TestPowerLogNorm:
+
+    # reference values were computed via mpmath
+    # from mpmath import mp
+    # mp.dps = 80
+    # def powerlognorm_sf_mp(x, c, s):
+    #     x = mp.mpf(x)
+    #     c = mp.mpf(c)
+    #     s = mp.mpf(s)
+    #     return mp.ncdf(-mp.log(x) / s)**c
+    #
+    # def powerlognormal_cdf_mp(x, c, s):
+    #     return mp.one - powerlognorm_sf_mp(x, c, s)
+    #
+    # x, c, s = 100, 20, 1
+    # print(float(powerlognorm_sf_mp(x, c, s)))
+
+    @pytest.mark.parametrize("x, c, s, ref",
+                             [(100, 20, 1, 1.9057100820561928e-114),
+                              (1e-3, 20, 1, 0.9999999999507617),
+                              (1e-3, 0.02, 1, 0.9999999999999508),
+                              (1e22, 0.02, 1, 6.50744044621611e-12)])
+    def test_sf(self, x, c, s, ref):
+        assert_allclose(stats.powerlognorm.sf(x, c, s), ref, rtol=1e-13)
+
+    # reference values were computed via mpmath using the survival
+    # function above (passing in `ref` and getting `q`).
+    @pytest.mark.parametrize("q, c, s, ref",
+                             [(0.9999999587870905, 0.02, 1, 0.01),
+                              (6.690376686108851e-233, 20, 1, 1000)])
+    def test_isf(self, q, c, s, ref):
+        assert_allclose(stats.powerlognorm.isf(q, c, s), ref, rtol=5e-11)
+
+    @pytest.mark.parametrize("x, c, s, ref",
+                             [(1e25, 0.02, 1, 0.9999999999999963),
+                              (1e-6, 0.02, 1, 2.054921078040843e-45),
+                              (1e-6, 200, 1, 2.0549210780408428e-41),
+                              (0.3, 200, 1, 0.9999999999713368)])
+    def test_cdf(self, x, c, s, ref):
+        assert_allclose(stats.powerlognorm.cdf(x, c, s), ref, rtol=3e-14)
+
+    # reference values were computed via mpmath
+    # from mpmath import mp
+    # mp.dps = 50
+    # def powerlognorm_pdf_mpmath(x, c, s):
+    #     x = mp.mpf(x)
+    #     c = mp.mpf(c)
+    #     s = mp.mpf(s)
+    #     res = (c/(x * s) * mp.npdf(mp.log(x)/s) *
+    #            mp.ncdf(-mp.log(x)/s)**(c - mp.one))
+    #     return float(res)
+
+    @pytest.mark.parametrize("x, c, s, ref",
+                             [(1e22, 0.02, 1, 6.5954987852335016e-34),
+                              (1e20, 1e-3, 1, 1.588073750563988e-22),
+                              (1e40, 1e-3, 1, 1.3179391812506349e-43)])
+    def test_pdf(self, x, c, s, ref):
+        assert_allclose(stats.powerlognorm.pdf(x, c, s), ref, rtol=3e-12)
+
+
+class TestPowerNorm:
+
+    # survival function references were computed with mpmath via
+    # from mpmath import mp
+    # x = mp.mpf(x)
+    # c = mp.mpf(x)
+    # float(mp.ncdf(-x)**c)
+
+    @pytest.mark.parametrize("x, c, ref",
+                             [(9, 1, 1.1285884059538405e-19),
+                              (20, 2, 7.582445786569958e-178),
+                              (100, 0.02, 3.330957891903866e-44),
+                              (200, 0.01, 1.3004759092324774e-87)])
+    def test_sf(self, x, c, ref):
+        assert_allclose(stats.powernorm.sf(x, c), ref, rtol=1e-13)
+
+    # inverse survival function references were computed with mpmath via
+    # from mpmath import mp
+    # def isf_mp(q, c):
+    #     q = mp.mpf(q)
+    #     c = mp.mpf(c)
+    #     arg = q**(mp.one / c)
+    #     return float(-mp.sqrt(2) * mp.erfinv(mp.mpf(2.) * arg - mp.one))
+
+    @pytest.mark.parametrize("q, c, ref",
+                             [(1e-5, 20, -0.15690800666514138),
+                              (0.99999, 100, -5.19933666203545),
+                              (0.9999, 0.02, -2.576676052143387),
+                              (5e-2, 0.02, 17.089518110222244),
+                              (1e-18, 2, 5.9978070150076865),
+                              (1e-50, 5, 6.361340902404057)])
+    def test_isf(self, q, c, ref):
+        assert_allclose(stats.powernorm.isf(q, c), ref, rtol=5e-12)
+
+    # CDF reference values were computed with mpmath via
+    # from mpmath import mp
+    # def cdf_mp(x, c):
+    #     x = mp.mpf(x)
+    #     c = mp.mpf(c)
+    #     return float(mp.one - mp.ncdf(-x)**c)
+
+    @pytest.mark.parametrize("x, c, ref",
+                             [(-12, 9, 1.598833900869911e-32),
+                              (2, 9, 0.9999999999999983),
+                              (-20, 9, 2.4782617067456103e-88),
+                              (-5, 0.02, 5.733032242841443e-09),
+                              (-20, 0.02, 5.507248237212467e-91)])
+    def test_cdf(self, x, c, ref):
+        assert_allclose(stats.powernorm.cdf(x, c), ref, rtol=5e-14)
+
+
+class TestInvGamma:
+    def test_invgamma_inf_gh_1866(self):
+        # invgamma's moments are only finite for a>n
+        # specific numbers checked w/ boost 1.54
+        with warnings.catch_warnings():
+            warnings.simplefilter('error', RuntimeWarning)
+            mvsk = stats.invgamma.stats(a=19.31, moments='mvsk')
+            expected = [0.05461496450, 0.0001723162534, 1.020362676,
+                        2.055616582]
+            assert_allclose(mvsk, expected)
+
+            a = [1.1, 3.1, 5.6]
+            mvsk = stats.invgamma.stats(a=a, moments='mvsk')
+            expected = ([10., 0.476190476, 0.2173913043],       # mmm
+                        [np.inf, 0.2061430632, 0.01312749422],  # vvv
+                        [np.nan, 41.95235392, 2.919025532],     # sss
+                        [np.nan, np.nan, 24.51923076])          # kkk
+            for x, y in zip(mvsk, expected):
+                assert_almost_equal(x, y)
+
+    def test_cdf_ppf(self):
+        # gh-6245
+        x = np.logspace(-2.6, 0)
+        y = stats.invgamma.cdf(x, 1)
+        xx = stats.invgamma.ppf(y, 1)
+        assert_allclose(x, xx)
+
+    def test_sf_isf(self):
+        # gh-6245
+        if sys.maxsize > 2**32:
+            x = np.logspace(2, 100)
+        else:
+            # Invgamme roundtrip on 32-bit systems has relative accuracy
+            # ~1e-15 until x=1e+15, and becomes inf above x=1e+18
+            x = np.logspace(2, 18)
+
+        y = stats.invgamma.sf(x, 1)
+        xx = stats.invgamma.isf(y, 1)
+        assert_allclose(x, xx, rtol=1.0)
+
+    def test_logcdf(self):
+        x = 1e7
+        a = 2.25
+        # Reference value computed with mpmath.
+        ref = -6.97567687425534e-17
+        logcdf = stats.invgamma.logcdf(x, a)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    def test_logsf(self):
+        x = 0.01
+        a = 3.5
+        # Reference value computed with mpmath.
+        ref = -1.147781224014262e-39
+        logsf = stats.invgamma.logsf(x, a)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+    @pytest.mark.parametrize("a, ref",
+                             [(100000000.0, -26.21208257605721),
+                              (1e+100, -343.9688254159022)])
+    def test_large_entropy(self, a, ref):
+        # The reference values were calculated with mpmath:
+        # from mpmath import mp
+        # mp.dps = 500
+
+        # def invgamma_entropy(a):
+        #     a = mp.mpf(a)
+        #     h = a + mp.loggamma(a) - (mp.one + a) * mp.digamma(a)
+        #     return float(h)
+        assert_allclose(stats.invgamma.entropy(a), ref, rtol=1e-15)
+
+
+class TestF:
+    def test_endpoints(self):
+        # Compute the pdf at the left endpoint dst.a.
+        data = [[stats.f, (2, 1), 1.0]]
+        for _f, _args, _correct in data:
+            ans = _f.pdf(_f.a, *_args)
+
+        ans = [_f.pdf(_f.a, *_args) for _f, _args, _ in data]
+        correct = [_correct_ for _f, _args, _correct_ in data]
+        assert_array_almost_equal(ans, correct)
+
+    def test_f_moments(self):
+        # n-th moment of F distributions is only finite for n < dfd / 2
+        m, v, s, k = stats.f.stats(11, 6.5, moments='mvsk')
+        assert_(np.isfinite(m))
+        assert_(np.isfinite(v))
+        assert_(np.isfinite(s))
+        assert_(not np.isfinite(k))
+
+    def test_moments_warnings(self):
+        # no warnings should be generated for dfd = 2, 4, 6, 8 (div by zero)
+        with warnings.catch_warnings():
+            warnings.simplefilter('error', RuntimeWarning)
+            stats.f.stats(dfn=[11]*4, dfd=[2, 4, 6, 8], moments='mvsk')
+
+    def test_stats_broadcast(self):
+        dfn = np.array([[3], [11]])
+        dfd = np.array([11, 12])
+        m, v, s, k = stats.f.stats(dfn=dfn, dfd=dfd, moments='mvsk')
+        m2 = [dfd / (dfd - 2)]*2
+        assert_allclose(m, m2)
+        v2 = 2 * dfd**2 * (dfn + dfd - 2) / dfn / (dfd - 2)**2 / (dfd - 4)
+        assert_allclose(v, v2)
+        s2 = ((2*dfn + dfd - 2) * np.sqrt(8*(dfd - 4)) /
+              ((dfd - 6) * np.sqrt(dfn*(dfn + dfd - 2))))
+        assert_allclose(s, s2)
+        k2num = 12 * (dfn * (5*dfd - 22) * (dfn + dfd - 2) +
+                      (dfd - 4) * (dfd - 2)**2)
+        k2den = dfn * (dfd - 6) * (dfd - 8) * (dfn + dfd - 2)
+        k2 = k2num / k2den
+        assert_allclose(k, k2)
+
+
+class TestStudentT:
+    def test_rvgeneric_std(self):
+        # Regression test for #1191
+        assert_array_almost_equal(stats.t.std([5, 6]), [1.29099445, 1.22474487])
+
+    def test_moments_t(self):
+        # regression test for #8786
+        assert_equal(stats.t.stats(df=1, moments='mvsk'),
+                    (np.inf, np.nan, np.nan, np.nan))
+        assert_equal(stats.t.stats(df=1.01, moments='mvsk'),
+                    (0.0, np.inf, np.nan, np.nan))
+        assert_equal(stats.t.stats(df=2, moments='mvsk'),
+                    (0.0, np.inf, np.nan, np.nan))
+        assert_equal(stats.t.stats(df=2.01, moments='mvsk'),
+                    (0.0, 2.01/(2.01-2.0), np.nan, np.inf))
+        assert_equal(stats.t.stats(df=3, moments='sk'), (np.nan, np.inf))
+        assert_equal(stats.t.stats(df=3.01, moments='sk'), (0.0, np.inf))
+        assert_equal(stats.t.stats(df=4, moments='sk'), (0.0, np.inf))
+        assert_equal(stats.t.stats(df=4.01, moments='sk'), (0.0, 6.0/(4.01 - 4.0)))
+
+    def test_t_entropy(self):
+        df = [1, 2, 25, 100]
+        # Expected values were computed with mpmath.
+        expected = [2.5310242469692907, 1.9602792291600821,
+                    1.459327578078393, 1.4289633653182439]
+        assert_allclose(stats.t.entropy(df), expected, rtol=1e-13)
+
+    @pytest.mark.parametrize("v, ref",
+                            [(100, 1.4289633653182439),
+                            (1e+100, 1.4189385332046727)])
+    def test_t_extreme_entropy(self, v, ref):
+        # Reference values were calculated with mpmath:
+        # from mpmath import mp
+        # mp.dps = 500
+        #
+        # def t_entropy(v):
+        #   v = mp.mpf(v)
+        #   C = (v + mp.one) / 2
+        #   A = C * (mp.digamma(C) - mp.digamma(v / 2))
+        #   B = 0.5 * mp.log(v) + mp.log(mp.beta(v / 2, mp.one / 2))
+        #   h = A + B
+        #   return float(h)
+        assert_allclose(stats.t.entropy(v), ref, rtol=1e-14)
+
+    @pytest.mark.parametrize("methname", ["pdf", "logpdf", "cdf",
+                                        "ppf", "sf", "isf"])
+    @pytest.mark.parametrize("df_infmask", [[0, 0], [1, 1], [0, 1],
+                                            [[0, 1, 0], [1, 1, 1]],
+                                            [[1, 0], [0, 1]],
+                                            [[0], [1]]])
+    def test_t_inf_df(self, methname, df_infmask):
+        np.random.seed(0)
+        df_infmask = np.asarray(df_infmask, dtype=bool)
+        df = np.random.uniform(0, 10, size=df_infmask.shape)
+        x = np.random.randn(*df_infmask.shape)
+        df[df_infmask] = np.inf
+        t_dist = stats.t(df=df, loc=3, scale=1)
+        t_dist_ref = stats.t(df=df[~df_infmask], loc=3, scale=1)
+        norm_dist = stats.norm(loc=3, scale=1)
+        t_meth = getattr(t_dist, methname)
+        t_meth_ref = getattr(t_dist_ref, methname)
+        norm_meth = getattr(norm_dist, methname)
+        res = t_meth(x)
+        assert_equal(res[df_infmask], norm_meth(x[df_infmask]))
+        assert_equal(res[~df_infmask], t_meth_ref(x[~df_infmask]))
+
+    @pytest.mark.parametrize("df_infmask", [[0, 0], [1, 1], [0, 1],
+                                            [[0, 1, 0], [1, 1, 1]],
+                                            [[1, 0], [0, 1]],
+                                            [[0], [1]]])
+    def test_t_inf_df_stats_entropy(self, df_infmask):
+        np.random.seed(0)
+        df_infmask = np.asarray(df_infmask, dtype=bool)
+        df = np.random.uniform(0, 10, size=df_infmask.shape)
+        df[df_infmask] = np.inf
+        res = stats.t.stats(df=df, loc=3, scale=1, moments='mvsk')
+        res_ex_inf = stats.norm.stats(loc=3, scale=1, moments='mvsk')
+        res_ex_noinf = stats.t.stats(df=df[~df_infmask], loc=3, scale=1,
+                                    moments='mvsk')
+        for i in range(4):
+            assert_equal(res[i][df_infmask], res_ex_inf[i])
+            assert_equal(res[i][~df_infmask], res_ex_noinf[i])
+
+        res = stats.t.entropy(df=df, loc=3, scale=1)
+        res_ex_inf = stats.norm.entropy(loc=3, scale=1)
+        res_ex_noinf = stats.t.entropy(df=df[~df_infmask], loc=3, scale=1)
+        assert_equal(res[df_infmask], res_ex_inf)
+        assert_equal(res[~df_infmask], res_ex_noinf)
+
+    def test_logpdf_pdf(self):
+        # reference values were computed via the reference distribution, e.g.
+        # mp.dps = 500; StudentT(df=df).logpdf(x), StudentT(df=df).pdf(x)
+        x = [1, 1e3, 10, 1]
+        df = [1e100, 1e50, 1e20, 1]
+        logpdf_ref = [-1.4189385332046727, -500000.9189385332,
+                      -50.918938533204674, -1.8378770664093456]
+        pdf_ref = [0.24197072451914334, 0,
+                   7.69459862670642e-23, 0.15915494309189535]
+        assert_allclose(stats.t.logpdf(x, df), logpdf_ref, rtol=1e-14)
+        assert_allclose(stats.t.pdf(x, df), pdf_ref, rtol=1e-14)
+
+    # Reference values were computed with mpmath, and double-checked with
+    # Wolfram Alpha.
+    @pytest.mark.parametrize('x, df, ref',
+                             [(-75.0, 15, -46.76036184546812),
+                              (0, 15, -0.6931471805599453),
+                              (75.0, 15, -4.9230344937641665e-21)])
+    def test_logcdf_logsf(self, x, df, ref):
+        logcdf = stats.t.logcdf(x, df)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+        # The reference value is logcdf(x, df) == logsf(-x, df).
+        logsf = stats.t.logsf(-x, df)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+
+class TestRvDiscrete:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_rvs(self):
+        states = [-1, 0, 1, 2, 3, 4]
+        probability = [0.0, 0.3, 0.4, 0.0, 0.3, 0.0]
+        samples = 1000
+        r = stats.rv_discrete(name='sample', values=(states, probability))
+        x = r.rvs(size=samples)
+        assert isinstance(x, np.ndarray)
+
+        for s, p in zip(states, probability):
+            assert abs(sum(x == s)/float(samples) - p) < 0.05
+
+        x = r.rvs()
+        assert np.issubdtype(type(x), np.integer)
+
+    def test_entropy(self):
+        # Basic tests of entropy.
+        pvals = np.array([0.25, 0.45, 0.3])
+        p = stats.rv_discrete(values=([0, 1, 2], pvals))
+        expected_h = -sum(xlogy(pvals, pvals))
+        h = p.entropy()
+        assert_allclose(h, expected_h)
+
+        p = stats.rv_discrete(values=([0, 1, 2], [1.0, 0, 0]))
+        h = p.entropy()
+        assert_equal(h, 0.0)
+
+    def test_pmf(self):
+        xk = [1, 2, 4]
+        pk = [0.5, 0.3, 0.2]
+        rv = stats.rv_discrete(values=(xk, pk))
+
+        x = [[1., 4.],
+             [3., 2]]
+        assert_allclose(rv.pmf(x),
+                        [[0.5, 0.2],
+                         [0., 0.3]], atol=1e-14)
+
+    def test_cdf(self):
+        xk = [1, 2, 4]
+        pk = [0.5, 0.3, 0.2]
+        rv = stats.rv_discrete(values=(xk, pk))
+
+        x_values = [-2, 1., 1.1, 1.5, 2.0, 3.0, 4, 5]
+        expected = [0, 0.5, 0.5, 0.5, 0.8, 0.8, 1, 1]
+        assert_allclose(rv.cdf(x_values), expected, atol=1e-14)
+
+        # also check scalar arguments
+        assert_allclose([rv.cdf(xx) for xx in x_values],
+                        expected, atol=1e-14)
+
+    def test_ppf(self):
+        xk = [1, 2, 4]
+        pk = [0.5, 0.3, 0.2]
+        rv = stats.rv_discrete(values=(xk, pk))
+
+        q_values = [0.1, 0.5, 0.6, 0.8, 0.9, 1.]
+        expected = [1, 1, 2, 2, 4, 4]
+        assert_allclose(rv.ppf(q_values), expected, atol=1e-14)
+
+        # also check scalar arguments
+        assert_allclose([rv.ppf(q) for q in q_values],
+                        expected, atol=1e-14)
+
+    def test_cdf_ppf_next(self):
+        # copied and special cased from test_discrete_basic
+        vals = ([1, 2, 4, 7, 8], [0.1, 0.2, 0.3, 0.3, 0.1])
+        rv = stats.rv_discrete(values=vals)
+
+        assert_array_equal(rv.ppf(rv.cdf(rv.xk[:-1]) + 1e-8),
+                           rv.xk[1:])
+
+    def test_multidimension(self):
+        xk = np.arange(12).reshape((3, 4))
+        pk = np.array([[0.1, 0.1, 0.15, 0.05],
+                       [0.1, 0.1, 0.05, 0.05],
+                       [0.1, 0.1, 0.05, 0.05]])
+        rv = stats.rv_discrete(values=(xk, pk))
+
+        assert_allclose(rv.expect(), np.sum(rv.xk * rv.pk), atol=1e-14)
+
+    def test_bad_input(self):
+        xk = [1, 2, 3]
+        pk = [0.5, 0.5]
+        assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
+
+        pk = [1, 2, 3]
+        assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
+
+        xk = [1, 2, 3]
+        pk = [0.5, 1.2, -0.7]
+        assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
+
+        xk = [1, 2, 3, 4, 5]
+        pk = [0.3, 0.3, 0.3, 0.3, -0.2]
+        assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
+
+        xk = [1, 1]
+        pk = [0.5, 0.5]
+        assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
+
+    def test_shape_rv_sample(self):
+        # tests added for gh-9565
+
+        # mismatch of 2d inputs
+        xk, pk = np.arange(4).reshape((2, 2)), np.full((2, 3), 1/6)
+        assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
+
+        # same number of elements, but shapes not compatible
+        xk, pk = np.arange(6).reshape((3, 2)), np.full((2, 3), 1/6)
+        assert_raises(ValueError, stats.rv_discrete, **dict(values=(xk, pk)))
+
+        # same shapes => no error
+        xk, pk = np.arange(6).reshape((3, 2)), np.full((3, 2), 1/6)
+        assert_equal(stats.rv_discrete(values=(xk, pk)).pmf(0), 1/6)
+
+    def test_expect1(self):
+        xk = [1, 2, 4, 6, 7, 11]
+        pk = [0.1, 0.2, 0.2, 0.2, 0.2, 0.1]
+        rv = stats.rv_discrete(values=(xk, pk))
+
+        assert_allclose(rv.expect(), np.sum(rv.xk * rv.pk), atol=1e-14)
+
+    def test_expect2(self):
+        # rv_sample should override _expect. Bug report from
+        # https://stackoverflow.com/questions/63199792
+        y = [200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0,
+             1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
+             1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0,
+             2700.0, 2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0,
+             3500.0, 3600.0, 3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0,
+             4300.0, 4400.0, 4500.0, 4600.0, 4700.0, 4800.0]
+
+        py = [0.0004, 0.0, 0.0033, 0.006500000000000001, 0.0, 0.0,
+              0.004399999999999999, 0.6862, 0.0, 0.0, 0.0,
+              0.00019999999999997797, 0.0006000000000000449,
+              0.024499999999999966, 0.006400000000000072,
+              0.0043999999999999595, 0.019499999999999962,
+              0.03770000000000007, 0.01759999999999995, 0.015199999999999991,
+              0.018100000000000005, 0.04500000000000004, 0.0025999999999999357,
+              0.0, 0.0041000000000001036, 0.005999999999999894,
+              0.0042000000000000925, 0.0050000000000000044,
+              0.0041999999999999815, 0.0004999999999999449,
+              0.009199999999999986, 0.008200000000000096,
+              0.0, 0.0, 0.0046999999999999265, 0.0019000000000000128,
+              0.0006000000000000449, 0.02510000000000001, 0.0,
+              0.007199999999999984, 0.0, 0.012699999999999934, 0.0, 0.0,
+              0.008199999999999985, 0.005600000000000049, 0.0]
+
+        rv = stats.rv_discrete(values=(y, py))
+
+        # check the mean
+        assert_allclose(rv.expect(), rv.mean(), atol=1e-14)
+        assert_allclose(rv.expect(),
+                        sum(v * w for v, w in zip(y, py)), atol=1e-14)
+
+        # also check the second moment
+        assert_allclose(rv.expect(lambda x: x**2),
+                        sum(v**2 * w for v, w in zip(y, py)), atol=1e-14)
+
+
+class TestSkewCauchy:
+    def test_cauchy(self):
+        x = np.linspace(-5, 5, 100)
+        assert_array_almost_equal(stats.skewcauchy.pdf(x, a=0),
+                                  stats.cauchy.pdf(x))
+        assert_array_almost_equal(stats.skewcauchy.cdf(x, a=0),
+                                  stats.cauchy.cdf(x))
+        assert_array_almost_equal(stats.skewcauchy.ppf(x, a=0),
+                                  stats.cauchy.ppf(x))
+
+    def test_skewcauchy_R(self):
+        # options(digits=16)
+        # library(sgt)
+        # # lmbda, x contain the values generated for a, x below
+        # lmbda <- c(0.0976270078546495, 0.430378732744839, 0.2055267521432877,
+        #            0.0897663659937937, -0.15269040132219, 0.2917882261333122,
+        #            -0.12482557747462, 0.7835460015641595, 0.9273255210020589,
+        #            -0.2331169623484446)
+        # x <- c(2.917250380826646, 0.2889491975290444, 0.6804456109393229,
+        #        4.25596638292661, -4.289639418021131, -4.1287070029845925,
+        #        -4.797816025596743, 3.32619845547938, 2.7815675094985046,
+        #        3.700121482468191)
+        # pdf = dsgt(x, mu=0, lambda=lambda, sigma=1, q=1/2, mean.cent=FALSE,
+        #            var.adj = sqrt(2))
+        # cdf = psgt(x, mu=0, lambda=lambda, sigma=1, q=1/2, mean.cent=FALSE,
+        #            var.adj = sqrt(2))
+        # qsgt(cdf, mu=0, lambda=lambda, sigma=1, q=1/2, mean.cent=FALSE,
+        #      var.adj = sqrt(2))
+
+        np.random.seed(0)
+        a = np.random.rand(10) * 2 - 1
+        x = np.random.rand(10) * 10 - 5
+        pdf = [0.039473975217333909, 0.305829714049903223, 0.24140158118994162,
+               0.019585772402693054, 0.021436553695989482, 0.00909817103867518,
+               0.01658423410016873, 0.071083288030394126, 0.103250045941454524,
+               0.013110230778426242]
+        cdf = [0.87426677718213752, 0.37556468910780882, 0.59442096496538066,
+               0.91304659850890202, 0.09631964100300605, 0.03829624330921733,
+               0.08245240578402535, 0.72057062945510386, 0.62826415852515449,
+               0.95011308463898292]
+        assert_allclose(stats.skewcauchy.pdf(x, a), pdf)
+        assert_allclose(stats.skewcauchy.cdf(x, a), cdf)
+        assert_allclose(stats.skewcauchy.ppf(cdf, a), x)
+
+
+class TestJFSkewT:
+    def test_compare_t(self):
+        # Verify that jf_skew_t with a=b recovers the t distribution with 2a
+        # degrees of freedom
+        a = b = 5
+        df = a * 2
+        x = [-1.0, 0.0, 1.0, 2.0]
+        q = [0.0, 0.1, 0.25, 0.75, 0.90, 1.0]
+
+        jf = stats.jf_skew_t(a, b)
+        t = stats.t(df)
+
+        assert_allclose(jf.pdf(x), t.pdf(x))
+        assert_allclose(jf.cdf(x), t.cdf(x))
+        assert_allclose(jf.ppf(q), t.ppf(q))
+        assert_allclose(jf.stats('mvsk'), t.stats('mvsk'))
+
+    @pytest.fixture
+    def gamlss_pdf_data(self):
+        """Sample data points computed using the `ST5` distribution from the
+        GAMLSS package in R. The pdf has been calculated for (a,b)=(2,3),
+        (a,b)=(8,4), and (a,b)=(12,13) for x in `np.linspace(-10, 10, 41)`.
+
+        N.B. the `ST5` distribution in R uses an alternative parameterization
+        in terms of nu and tau, where:
+            - nu = (a - b) / (a * b * (a + b)) ** 0.5
+            - tau = 2 / (a + b)
+        """
+        data = np.load(
+            Path(__file__).parent / "data/jf_skew_t_gamlss_pdf_data.npy"
+        )
+        return np.rec.fromarrays(data, names="x,pdf,a,b")
+
+    @pytest.mark.parametrize("a,b", [(2, 3), (8, 4), (12, 13)])
+    def test_compare_with_gamlss_r(self, gamlss_pdf_data, a, b):
+        """Compare the pdf with a table of reference values. The table of
+        reference values was produced using R, where the Jones and Faddy skew
+        t distribution is available in the GAMLSS package as `ST5`.
+        """
+        data = gamlss_pdf_data[
+            (gamlss_pdf_data["a"] == a) & (gamlss_pdf_data["b"] == b)
+        ]
+        x, pdf = data["x"], data["pdf"]
+        assert_allclose(pdf, stats.jf_skew_t(a, b).pdf(x), rtol=1e-12)
+
+
+# Test data for TestSkewNorm.test_noncentral_moments()
+# The expected noncentral moments were computed by Wolfram Alpha.
+# In Wolfram Alpha, enter
+#    SkewNormalDistribution[0, 1, a] moment
+# with `a` replaced by the desired shape parameter.  In the results, there
+# should be a table of the first four moments. Click on "More" to get more
+# moments.  The expected moments start with the first moment (order = 1).
+_skewnorm_noncentral_moments = [
+    (2, [2*np.sqrt(2/(5*np.pi)),
+         1,
+         22/5*np.sqrt(2/(5*np.pi)),
+         3,
+         446/25*np.sqrt(2/(5*np.pi)),
+         15,
+         2682/25*np.sqrt(2/(5*np.pi)),
+         105,
+         107322/125*np.sqrt(2/(5*np.pi))]),
+    (0.1, [np.sqrt(2/(101*np.pi)),
+           1,
+           302/101*np.sqrt(2/(101*np.pi)),
+           3,
+           (152008*np.sqrt(2/(101*np.pi)))/10201,
+           15,
+           (107116848*np.sqrt(2/(101*np.pi)))/1030301,
+           105,
+           (97050413184*np.sqrt(2/(101*np.pi)))/104060401]),
+    (-3, [-3/np.sqrt(5*np.pi),
+          1,
+          -63/(10*np.sqrt(5*np.pi)),
+          3,
+          -2529/(100*np.sqrt(5*np.pi)),
+          15,
+          -30357/(200*np.sqrt(5*np.pi)),
+          105,
+          -2428623/(2000*np.sqrt(5*np.pi)),
+          945,
+          -242862867/(20000*np.sqrt(5*np.pi)),
+          10395,
+          -29143550277/(200000*np.sqrt(5*np.pi)),
+          135135]),
+]
+
+
+class TestSkewNorm:
+    def setup_method(self):
+        self.rng = check_random_state(1234)
+
+    def test_normal(self):
+        # When the skewness is 0 the distribution is normal
+        x = np.linspace(-5, 5, 100)
+        assert_array_almost_equal(stats.skewnorm.pdf(x, a=0),
+                                  stats.norm.pdf(x))
+
+    def test_rvs(self):
+        shape = (3, 4, 5)
+        x = stats.skewnorm.rvs(a=0.75, size=shape, random_state=self.rng)
+        assert_equal(shape, x.shape)
+
+        x = stats.skewnorm.rvs(a=-3, size=shape, random_state=self.rng)
+        assert_equal(shape, x.shape)
+
+    def test_moments(self):
+        X = stats.skewnorm.rvs(a=4, size=int(1e6), loc=5, scale=2,
+                               random_state=self.rng)
+        expected = [np.mean(X), np.var(X), stats.skew(X), stats.kurtosis(X)]
+        computed = stats.skewnorm.stats(a=4, loc=5, scale=2, moments='mvsk')
+        assert_array_almost_equal(computed, expected, decimal=2)
+
+        X = stats.skewnorm.rvs(a=-4, size=int(1e6), loc=5, scale=2,
+                               random_state=self.rng)
+        expected = [np.mean(X), np.var(X), stats.skew(X), stats.kurtosis(X)]
+        computed = stats.skewnorm.stats(a=-4, loc=5, scale=2, moments='mvsk')
+        assert_array_almost_equal(computed, expected, decimal=2)
+
+    def test_pdf_large_x(self):
+        # Triples are [x, a, logpdf(x, a)].  These values were computed
+        # using Log[PDF[SkewNormalDistribution[0, 1, a], x]] in Wolfram Alpha.
+        logpdfvals = [
+            [40, -1, -1604.834233366398515598970],
+            [40, -1/2, -1004.142946723741991369168],
+            [40, 0, -800.9189385332046727417803],
+            [40, 1/2, -800.2257913526447274323631],
+            [-40, -1/2, -800.2257913526447274323631],
+            [-2, 1e7, -2.000000000000199559727173e14],
+            [2, -1e7, -2.000000000000199559727173e14],
+        ]
+        for x, a, logpdfval in logpdfvals:
+            logp = stats.skewnorm.logpdf(x, a)
+            assert_allclose(logp, logpdfval, rtol=1e-8)
+
+    def test_cdf_large_x(self):
+        # Regression test for gh-7746.
+        # The x values are large enough that the closest 64 bit floating
+        # point representation of the exact CDF is 1.0.
+        p = stats.skewnorm.cdf([10, 20, 30], -1)
+        assert_allclose(p, np.ones(3), rtol=1e-14)
+        p = stats.skewnorm.cdf(25, 2.5)
+        assert_allclose(p, 1.0, rtol=1e-14)
+
+    def test_cdf_sf_small_values(self):
+        # Triples are [x, a, cdf(x, a)].  These values were computed
+        # using CDF[SkewNormalDistribution[0, 1, a], x] in Wolfram Alpha.
+        cdfvals = [
+            [-8, 1, 3.870035046664392611e-31],
+            [-4, 2, 8.1298399188811398e-21],
+            [-2, 5, 1.55326826787106273e-26],
+            [-9, -1, 2.257176811907681295e-19],
+            [-10, -4, 1.523970604832105213e-23],
+        ]
+        for x, a, cdfval in cdfvals:
+            p = stats.skewnorm.cdf(x, a)
+            assert_allclose(p, cdfval, rtol=1e-8)
+            # For the skew normal distribution, sf(-x, -a) = cdf(x, a).
+            p = stats.skewnorm.sf(-x, -a)
+            assert_allclose(p, cdfval, rtol=1e-8)
+
+    @pytest.mark.parametrize('a, moments', _skewnorm_noncentral_moments)
+    def test_noncentral_moments(self, a, moments):
+        for order, expected in enumerate(moments, start=1):
+            mom = stats.skewnorm.moment(order, a)
+            assert_allclose(mom, expected, rtol=1e-14)
+
+    def test_fit(self):
+        rng = np.random.default_rng(4609813989115202851)
+
+        a, loc, scale = -2, 3.5, 0.5  # arbitrary, valid parameters
+        dist = stats.skewnorm(a, loc, scale)
+        rvs = dist.rvs(size=100, random_state=rng)
+
+        # test that MLE still honors guesses and fixed parameters
+        a2, loc2, scale2 = stats.skewnorm.fit(rvs, -1.5, floc=3)
+        a3, loc3, scale3 = stats.skewnorm.fit(rvs, -1.6, floc=3)
+        assert loc2 == loc3 == 3  # fixed parameter is respected
+        assert a2 != a3  # different guess -> (slightly) different outcome
+        # quality of fit is tested elsewhere
+
+        # test that MoM honors fixed parameters, accepts (but ignores) guesses
+        a4, loc4, scale4 = stats.skewnorm.fit(rvs, 3, fscale=3, method='mm')
+        assert scale4 == 3
+        # because scale was fixed, only the mean and skewness will be matched
+        dist4 = stats.skewnorm(a4, loc4, scale4)
+        res = dist4.stats(moments='ms')
+        ref = np.mean(rvs), stats.skew(rvs)
+        assert_allclose(res, ref)
+
+        # Test behavior when skew of data is beyond maximum of skewnorm
+        rvs2 = stats.pareto.rvs(1, size=100, random_state=rng)
+
+        # MLE still works
+        res = stats.skewnorm.fit(rvs2)
+        assert np.all(np.isfinite(res))
+
+        # MoM fits variance and skewness
+        a5, loc5, scale5 = stats.skewnorm.fit(rvs2, method='mm')
+        assert np.isinf(a5)
+        # distribution infrastructure doesn't allow infinite shape parameters
+        # into _stats; it just bypasses it and produces NaNs. Calculate
+        # moments manually.
+        m, v = np.mean(rvs2), np.var(rvs2)
+        assert_allclose(m, loc5 + scale5 * np.sqrt(2/np.pi))
+        assert_allclose(v, scale5**2 * (1 - 2 / np.pi))
+
+        # test that MLE and MoM behave as expected under sign changes
+        a6p, loc6p, scale6p = stats.skewnorm.fit(rvs, method='mle')
+        a6m, loc6m, scale6m = stats.skewnorm.fit(-rvs, method='mle')
+        assert_allclose([a6m, loc6m, scale6m], [-a6p, -loc6p, scale6p])
+        a7p, loc7p, scale7p = stats.skewnorm.fit(rvs, method='mm')
+        a7m, loc7m, scale7m = stats.skewnorm.fit(-rvs, method='mm')
+        assert_allclose([a7m, loc7m, scale7m], [-a7p, -loc7p, scale7p])
+
+    def test_fit_gh19332(self):
+        # When the skewness of the data was high, `skewnorm.fit` fell back on
+        # generic `fit` behavior with a bad guess of the skewness parameter.
+        # Test that this is improved; `skewnorm.fit` is now better at finding
+        # the global optimum when the sample is highly skewed. See gh-19332.
+        x = np.array([-5, -1, 1 / 100_000] + 12 * [1] + [5])
+
+        params = stats.skewnorm.fit(x)
+        res = stats.skewnorm.nnlf(params, x)
+
+        # Compare overridden fit against generic fit.
+        # res should be about 32.01, and generic fit is worse at 32.64.
+        # In case the generic fit improves, remove this assertion (see gh-19333).
+        params_super = stats.skewnorm.fit(x, superfit=True)
+        ref = stats.skewnorm.nnlf(params_super, x)
+        assert res < ref - 0.5
+
+        # Compare overridden fit against stats.fit
+        rng = np.random.default_rng(9842356982345693637)
+        bounds = {'a': (-5, 5), 'loc': (-10, 10), 'scale': (1e-16, 10)}
+
+        def optimizer(fun, bounds):
+            return differential_evolution(fun, bounds, rng=rng)
+
+        fit_result = stats.fit(stats.skewnorm, x, bounds, optimizer=optimizer)
+        np.testing.assert_allclose(params, fit_result.params, rtol=1e-4)
+
+    def test_ppf(self):
+        # gh-20124 reported that Boost's ppf was wrong for high skewness
+        # Reference value was calculated using
+        # N[InverseCDF[SkewNormalDistribution[0, 1, 500], 1/100], 14] in Wolfram Alpha.
+        assert_allclose(stats.skewnorm.ppf(0.01, 500), 0.012533469508013, rtol=1e-13)
+
+
+class TestExpon:
+    def test_zero(self):
+        assert_equal(stats.expon.pdf(0), 1)
+
+    def test_tail(self):  # Regression test for ticket 807
+        assert_equal(stats.expon.cdf(1e-18), 1e-18)
+        assert_equal(stats.expon.isf(stats.expon.sf(40)), 40)
+
+    def test_nan_raises_error(self):
+        # see gh-issue 10300
+        x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan])
+        assert_raises(ValueError, stats.expon.fit, x)
+
+    def test_inf_raises_error(self):
+        # see gh-issue 10300
+        x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf])
+        assert_raises(ValueError, stats.expon.fit, x)
+
+
+class TestNorm:
+    def test_nan_raises_error(self):
+        # see gh-issue 10300
+        x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan])
+        assert_raises(ValueError, stats.norm.fit, x)
+
+    def test_inf_raises_error(self):
+        # see gh-issue 10300
+        x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf])
+        assert_raises(ValueError, stats.norm.fit, x)
+
+    def test_bad_keyword_arg(self):
+        x = [1, 2, 3]
+        assert_raises(TypeError, stats.norm.fit, x, plate="shrimp")
+
+    @pytest.mark.parametrize('loc', [0, 1])
+    def test_delta_cdf(self, loc):
+        # The expected value is computed with mpmath:
+        # >>> import mpmath
+        # >>> mpmath.mp.dps = 60
+        # >>> float(mpmath.ncdf(12) - mpmath.ncdf(11))
+        # 1.910641809677555e-28
+        expected = 1.910641809677555e-28
+        delta = stats.norm._delta_cdf(11+loc, 12+loc, loc=loc)
+        assert_allclose(delta, expected, rtol=1e-13)
+        delta = stats.norm._delta_cdf(-(12+loc), -(11+loc), loc=-loc)
+        assert_allclose(delta, expected, rtol=1e-13)
+
+
+class TestUniform:
+    """gh-10300"""
+    def test_nan_raises_error(self):
+        # see gh-issue 10300
+        x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan])
+        assert_raises(ValueError, stats.uniform.fit, x)
+
+    def test_inf_raises_error(self):
+        # see gh-issue 10300
+        x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf])
+        assert_raises(ValueError, stats.uniform.fit, x)
+
+
+class TestExponNorm:
+    def test_moments(self):
+        # Some moment test cases based on non-loc/scaled formula
+        def get_moms(lam, sig, mu):
+            # See wikipedia for these formulae
+            #  where it is listed as an exponentially modified gaussian
+            opK2 = 1.0 + 1 / (lam*sig)**2
+            exp_skew = 2 / (lam * sig)**3 * opK2**(-1.5)
+            exp_kurt = 6.0 * (1 + (lam * sig)**2)**(-2)
+            return [mu + 1/lam, sig*sig + 1.0/(lam*lam), exp_skew, exp_kurt]
+
+        mu, sig, lam = 0, 1, 1
+        K = 1.0 / (lam * sig)
+        sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk')
+        assert_almost_equal(sts, get_moms(lam, sig, mu))
+        mu, sig, lam = -3, 2, 0.1
+        K = 1.0 / (lam * sig)
+        sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk')
+        assert_almost_equal(sts, get_moms(lam, sig, mu))
+        mu, sig, lam = 0, 3, 1
+        K = 1.0 / (lam * sig)
+        sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk')
+        assert_almost_equal(sts, get_moms(lam, sig, mu))
+        mu, sig, lam = -5, 11, 3.5
+        K = 1.0 / (lam * sig)
+        sts = stats.exponnorm.stats(K, loc=mu, scale=sig, moments='mvsk')
+        assert_almost_equal(sts, get_moms(lam, sig, mu))
+
+    def test_nan_raises_error(self):
+        # see gh-issue 10300
+        x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan])
+        assert_raises(ValueError, stats.exponnorm.fit, x, floc=0, fscale=1)
+
+    def test_inf_raises_error(self):
+        # see gh-issue 10300
+        x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf])
+        assert_raises(ValueError, stats.exponnorm.fit, x, floc=0, fscale=1)
+
+    def test_extremes_x(self):
+        # Test for extreme values against overflows
+        assert_almost_equal(stats.exponnorm.pdf(-900, 1), 0.0)
+        assert_almost_equal(stats.exponnorm.pdf(+900, 1), 0.0)
+        assert_almost_equal(stats.exponnorm.pdf(-900, 0.01), 0.0)
+        assert_almost_equal(stats.exponnorm.pdf(+900, 0.01), 0.0)
+
+    # Expected values for the PDF were computed with mpmath, with
+    # the following function, and with mpmath.mp.dps = 50.
+    #
+    #   def exponnorm_stdpdf(x, K):
+    #       x = mpmath.mpf(x)
+    #       K = mpmath.mpf(K)
+    #       t1 = mpmath.exp(1/(2*K**2) - x/K)
+    #       erfcarg = -(x - 1/K)/mpmath.sqrt(2)
+    #       t2 = mpmath.erfc(erfcarg)
+    #       return t1 * t2 / (2*K)
+    #
+    @pytest.mark.parametrize('x, K, expected',
+                             [(20, 0.01, 6.90010764753618e-88),
+                              (1, 0.01, 0.24438994313247364),
+                              (-1, 0.01, 0.23955149623472075),
+                              (-20, 0.01, 4.6004708690125477e-88),
+                              (10, 1, 7.48518298877006e-05),
+                              (10, 10000, 9.990005048283775e-05)])
+    def test_std_pdf(self, x, K, expected):
+        assert_allclose(stats.exponnorm.pdf(x, K), expected, rtol=5e-12)
+
+    # Expected values for the CDF were computed with mpmath using
+    # the following function and with mpmath.mp.dps = 60:
+    #
+    #   def mp_exponnorm_cdf(x, K, loc=0, scale=1):
+    #       x = mpmath.mpf(x)
+    #       K = mpmath.mpf(K)
+    #       loc = mpmath.mpf(loc)
+    #       scale = mpmath.mpf(scale)
+    #       z = (x - loc)/scale
+    #       return (mpmath.ncdf(z)
+    #               - mpmath.exp((1/(2*K) - z)/K)*mpmath.ncdf(z - 1/K))
+    #
+    @pytest.mark.parametrize('x, K, scale, expected',
+                             [[0, 0.01, 1, 0.4960109760186432],
+                              [-5, 0.005, 1, 2.7939945412195734e-07],
+                              [-1e4, 0.01, 100, 0.0],
+                              [-1e4, 0.01, 1000, 6.920401854427357e-24],
+                              [5, 0.001, 1, 0.9999997118542392]])
+    def test_cdf_small_K(self, x, K, scale, expected):
+        p = stats.exponnorm.cdf(x, K, scale=scale)
+        if expected == 0.0:
+            assert p == 0.0
+        else:
+            assert_allclose(p, expected, rtol=1e-13)
+
+    # Expected values for the SF were computed with mpmath using
+    # the following function and with mpmath.mp.dps = 60:
+    #
+    #   def mp_exponnorm_sf(x, K, loc=0, scale=1):
+    #       x = mpmath.mpf(x)
+    #       K = mpmath.mpf(K)
+    #       loc = mpmath.mpf(loc)
+    #       scale = mpmath.mpf(scale)
+    #       z = (x - loc)/scale
+    #       return (mpmath.ncdf(-z)
+    #               + mpmath.exp((1/(2*K) - z)/K)*mpmath.ncdf(z - 1/K))
+    #
+    @pytest.mark.parametrize('x, K, scale, expected',
+                             [[10, 0.01, 1, 8.474702916146657e-24],
+                              [2, 0.005, 1, 0.02302280664231312],
+                              [5, 0.005, 0.5, 8.024820681931086e-24],
+                              [10, 0.005, 0.5, 3.0603340062892486e-89],
+                              [20, 0.005, 0.5, 0.0],
+                              [-3, 0.001, 1, 0.9986545205566117]])
+    def test_sf_small_K(self, x, K, scale, expected):
+        p = stats.exponnorm.sf(x, K, scale=scale)
+        if expected == 0.0:
+            assert p == 0.0
+        else:
+            assert_allclose(p, expected, rtol=5e-13)
+
+
+class TestGenExpon:
+    def test_pdf_unity_area(self):
+        from scipy.integrate import simpson
+        # PDF should integrate to one
+        p = stats.genexpon.pdf(np.arange(0, 10, 0.01), 0.5, 0.5, 2.0)
+        assert_almost_equal(simpson(p, dx=0.01), 1, 1)
+
+    def test_cdf_bounds(self):
+        # CDF should always be positive
+        cdf = stats.genexpon.cdf(np.arange(0, 10, 0.01), 0.5, 0.5, 2.0)
+        assert np.all((0 <= cdf) & (cdf <= 1))
+
+    # The values of p in the following data were computed with mpmath.
+    # E.g. the script
+    #     from mpmath import mp
+    #     mp.dps = 80
+    #     x = mp.mpf('15.0')
+    #     a = mp.mpf('1.0')
+    #     b = mp.mpf('2.0')
+    #     c = mp.mpf('1.5')
+    #     print(float(mp.exp((-a-b)*x + (b/c)*-mp.expm1(-c*x))))
+    # prints
+    #     1.0859444834514553e-19
+    @pytest.mark.parametrize('x, p, a, b, c',
+                             [(15, 1.0859444834514553e-19, 1, 2, 1.5),
+                              (0.25, 0.7609068232534623, 0.5, 2, 3),
+                              (0.25, 0.09026661397565876, 9.5, 2, 0.5),
+                              (0.01, 0.9753038265071597, 2.5, 0.25, 0.5),
+                              (3.25, 0.0001962824553094492, 2.5, 0.25, 0.5),
+                              (0.125, 0.9508674287164001, 0.25, 5, 0.5)])
+    def test_sf_isf(self, x, p, a, b, c):
+        sf = stats.genexpon.sf(x, a, b, c)
+        assert_allclose(sf, p, rtol=2e-14)
+        isf = stats.genexpon.isf(p, a, b, c)
+        assert_allclose(isf, x, rtol=2e-14)
+
+    # The values of p in the following data were computed with mpmath.
+    @pytest.mark.parametrize('x, p, a, b, c',
+                             [(0.25, 0.2390931767465377, 0.5, 2, 3),
+                              (0.25, 0.9097333860243412, 9.5, 2, 0.5),
+                              (0.01, 0.0246961734928403, 2.5, 0.25, 0.5),
+                              (3.25, 0.9998037175446906, 2.5, 0.25, 0.5),
+                              (0.125, 0.04913257128359998, 0.25, 5, 0.5)])
+    def test_cdf_ppf(self, x, p, a, b, c):
+        cdf = stats.genexpon.cdf(x, a, b, c)
+        assert_allclose(cdf, p, rtol=2e-14)
+        ppf = stats.genexpon.ppf(p, a, b, c)
+        assert_allclose(ppf, x, rtol=2e-14)
+
+
+class TestTruncexpon:
+
+    def test_sf_isf(self):
+        # reference values were computed via the reference distribution, e.g.
+        # mp.dps = 50; TruncExpon(b=b).sf(x)
+        b = [20, 100]
+        x = [19.999999, 99.999999]
+        ref = [2.0611546593828472e-15, 3.7200778266671455e-50]
+        assert_allclose(stats.truncexpon.sf(x, b), ref, rtol=1.5e-10)
+        assert_allclose(stats.truncexpon.isf(ref, b), x, rtol=1e-12)
+
+
+class TestExponpow:
+    def test_tail(self):
+        assert_almost_equal(stats.exponpow.cdf(1e-10, 2.), 1e-20)
+        assert_almost_equal(stats.exponpow.isf(stats.exponpow.sf(5, .8), .8),
+                            5)
+
+
+class TestSkellam:
+    def test_pmf(self):
+        # comparison to R
+        k = np.arange(-10, 15)
+        mu1, mu2 = 10, 5
+        skpmfR = np.array(
+                   [4.2254582961926893e-005, 1.1404838449648488e-004,
+                    2.8979625801752660e-004, 6.9177078182101231e-004,
+                    1.5480716105844708e-003, 3.2412274963433889e-003,
+                    6.3373707175123292e-003, 1.1552351566696643e-002,
+                    1.9606152375042644e-002, 3.0947164083410337e-002,
+                    4.5401737566767360e-002, 6.1894328166820688e-002,
+                    7.8424609500170578e-002, 9.2418812533573133e-002,
+                    1.0139793148019728e-001, 1.0371927988298846e-001,
+                    9.9076583077406091e-002, 8.8546660073089561e-002,
+                    7.4187842052486810e-002, 5.8392772862200251e-002,
+                    4.3268692953013159e-002, 3.0248159818374226e-002,
+                    1.9991434305603021e-002, 1.2516877303301180e-002,
+                    7.4389876226229707e-003])
+
+        assert_almost_equal(stats.skellam.pmf(k, mu1, mu2), skpmfR, decimal=15)
+
+    def test_cdf(self):
+        # comparison to R, only 5 decimals
+        k = np.arange(-10, 15)
+        mu1, mu2 = 10, 5
+        skcdfR = np.array(
+                   [6.4061475386192104e-005, 1.7810985988267694e-004,
+                    4.6790611790020336e-004, 1.1596768997212152e-003,
+                    2.7077485103056847e-003, 5.9489760066490718e-003,
+                    1.2286346724161398e-002, 2.3838698290858034e-002,
+                    4.3444850665900668e-002, 7.4392014749310995e-002,
+                    1.1979375231607835e-001, 1.8168808048289900e-001,
+                    2.6011268998306952e-001, 3.5253150251664261e-001,
+                    4.5392943399683988e-001, 5.5764871387982828e-001,
+                    6.5672529695723436e-001, 7.4527195703032389e-001,
+                    8.1945979908281064e-001, 8.7785257194501087e-001,
+                    9.2112126489802404e-001, 9.5136942471639818e-001,
+                    9.7136085902200120e-001, 9.8387773632530240e-001,
+                    9.9131672394792536e-001])
+
+        assert_almost_equal(stats.skellam.cdf(k, mu1, mu2), skcdfR, decimal=5)
+
+    def test_extreme_mu2(self):
+        # check that crash reported by gh-17916 large mu2 is resolved
+        x, mu1, mu2 = 0, 1, 4820232647677555.0
+        assert_allclose(stats.skellam.pmf(x, mu1, mu2), 0, atol=1e-16)
+        assert_allclose(stats.skellam.cdf(x, mu1, mu2), 1, atol=1e-16)
+
+
+class TestLognorm:
+    def test_pdf(self):
+        # Regression test for Ticket #1471: avoid nan with 0/0 situation
+        # Also make sure there are no warnings at x=0, cf gh-5202
+        with warnings.catch_warnings():
+            warnings.simplefilter('error', RuntimeWarning)
+            pdf = stats.lognorm.pdf([0, 0.5, 1], 1)
+            assert_array_almost_equal(pdf, [0.0, 0.62749608, 0.39894228])
+
+    def test_logcdf(self):
+        # Regression test for gh-5940: sf et al would underflow too early
+        x2, mu, sigma = 201.68, 195, 0.149
+        assert_allclose(stats.lognorm.sf(x2-mu, s=sigma),
+                        stats.norm.sf(np.log(x2-mu)/sigma))
+        assert_allclose(stats.lognorm.logsf(x2-mu, s=sigma),
+                        stats.norm.logsf(np.log(x2-mu)/sigma))
+
+    @pytest.fixture(scope='function')
+    def rng(self):
+        return np.random.default_rng(1234)
+
+    @pytest.mark.parametrize("rvs_shape", [.1, 2])
+    @pytest.mark.parametrize("rvs_loc", [-2, 0, 2])
+    @pytest.mark.parametrize("rvs_scale", [.2, 1, 5])
+    @pytest.mark.parametrize('fix_shape, fix_loc, fix_scale',
+                             [e for e in product((False, True), repeat=3)
+                              if False in e])
+    @np.errstate(invalid="ignore")
+    def test_fit_MLE_comp_optimizer(self, rvs_shape, rvs_loc, rvs_scale,
+                                    fix_shape, fix_loc, fix_scale, rng):
+        data = stats.lognorm.rvs(size=100, s=rvs_shape, scale=rvs_scale,
+                                 loc=rvs_loc, random_state=rng)
+
+        kwds = {}
+        if fix_shape:
+            kwds['f0'] = rvs_shape
+        if fix_loc:
+            kwds['floc'] = rvs_loc
+        if fix_scale:
+            kwds['fscale'] = rvs_scale
+
+        # Numerical result may equal analytical result if some code path
+        # of the analytical routine makes use of numerical optimization.
+        _assert_less_or_close_loglike(stats.lognorm, data, **kwds,
+                                      maybe_identical=True)
+
+    def test_isf(self):
+        # reference values were computed via the reference distribution, e.g.
+        # mp.dps = 100;
+        # LogNormal(s=s).isf(q=0.1, guess=0)
+        # LogNormal(s=s).isf(q=2e-10, guess=100)
+        s = 0.954
+        q = [0.1, 2e-10, 5e-20, 6e-40]
+        ref = [3.3960065375794937, 390.07632793595974, 5830.5020828128445,
+               287872.84087457904]
+        assert_allclose(stats.lognorm.isf(q, s), ref, rtol=1e-14)
+
+
+class TestBeta:
+    def test_logpdf(self):
+        # Regression test for Ticket #1326: avoid nan with 0*log(0) situation
+        logpdf = stats.beta.logpdf(0, 1, 0.5)
+        assert_almost_equal(logpdf, -0.69314718056)
+        logpdf = stats.beta.logpdf(0, 0.5, 1)
+        assert_almost_equal(logpdf, np.inf)
+
+    def test_logpdf_ticket_1866(self):
+        alpha, beta = 267, 1472
+        x = np.array([0.2, 0.5, 0.6])
+        b = stats.beta(alpha, beta)
+        assert_allclose(b.logpdf(x).sum(), -1201.699061824062)
+        assert_allclose(b.pdf(x), np.exp(b.logpdf(x)))
+
+    def test_fit_bad_keyword_args(self):
+        x = [0.1, 0.5, 0.6]
+        assert_raises(TypeError, stats.beta.fit, x, floc=0, fscale=1,
+                      plate="shrimp")
+
+    def test_fit_duplicated_fixed_parameter(self):
+        # At most one of 'f0', 'fa' or 'fix_a' can be given to the fit method.
+        # More than one raises a ValueError.
+        x = [0.1, 0.5, 0.6]
+        assert_raises(ValueError, stats.beta.fit, x, fa=0.5, fix_a=0.5)
+
+    @pytest.mark.skipif(MACOS_INTEL, reason="Overflow, see gh-14901")
+    def test_issue_12635(self):
+        # Confirm that Boost's beta distribution resolves gh-12635.
+        # Check against R:
+        # options(digits=16)
+        # p = 0.9999999999997369
+        # a = 75.0
+        # b = 66334470.0
+        # print(qbeta(p, a, b))
+        p, a, b = 0.9999999999997369, 75.0, 66334470.0
+        assert_allclose(stats.beta.ppf(p, a, b), 2.343620802982393e-06)
+
+    @pytest.mark.skipif(MACOS_INTEL, reason="Overflow, see gh-14901")
+    def test_issue_12794(self):
+        # Confirm that Boost's beta distribution resolves gh-12794.
+        # Check against R.
+        # options(digits=16)
+        # p = 1e-11
+        # count_list = c(10,100,1000)
+        # print(qbeta(1-p, count_list + 1, 100000 - count_list))
+        inv_R = np.array([0.0004944464889611935,
+                          0.0018360586912635726,
+                          0.0122663919942518351])
+        count_list = np.array([10, 100, 1000])
+        p = 1e-11
+        inv = stats.beta.isf(p, count_list + 1, 100000 - count_list)
+        assert_allclose(inv, inv_R)
+        res = stats.beta.sf(inv, count_list + 1, 100000 - count_list)
+        assert_allclose(res, p)
+
+    @pytest.mark.skipif(MACOS_INTEL, reason="Overflow, see gh-14901")
+    def test_issue_12796(self):
+        # Confirm that Boost's beta distribution succeeds in the case
+        # of gh-12796
+        alpha_2 = 5e-6
+        count_ = np.arange(1, 20)
+        nobs = 100000
+        q, a, b = 1 - alpha_2, count_ + 1, nobs - count_
+        inv = stats.beta.ppf(q, a, b)
+        res = stats.beta.cdf(inv, a, b)
+        assert_allclose(res, 1 - alpha_2)
+
+    def test_endpoints(self):
+        # Confirm that boost's beta distribution returns inf at x=1
+        # when b<1
+        a, b = 1, 0.5
+        assert_equal(stats.beta.pdf(1, a, b), np.inf)
+
+        # Confirm that boost's beta distribution returns inf at x=0
+        # when a<1
+        a, b = 0.2, 3
+        assert_equal(stats.beta.pdf(0, a, b), np.inf)
+
+        # Confirm that boost's beta distribution returns 5 at x=0
+        # when a=1, b=5
+        a, b = 1, 5
+        assert_equal(stats.beta.pdf(0, a, b), 5)
+        assert_equal(stats.beta.pdf(1e-310, a, b), 5)
+
+        # Confirm that boost's beta distribution returns 5 at x=1
+        # when a=5, b=1
+        a, b = 5, 1
+        assert_equal(stats.beta.pdf(1, a, b), 5)
+        assert_equal(stats.beta.pdf(1-1e-310, a, b), 5)
+
+    @pytest.mark.xfail(IS_PYPY, reason="Does not convert boost warning")
+    def test_boost_eval_issue_14606(self):
+        q, a, b = 0.995, 1.0e11, 1.0e13
+        with pytest.warns(RuntimeWarning):
+            stats.beta.ppf(q, a, b)
+
+    @pytest.mark.parametrize('method', [stats.beta.ppf, stats.beta.isf])
+    @pytest.mark.parametrize('a, b', [(1e-310, 12.5), (12.5, 1e-310)])
+    def test_beta_ppf_with_subnormal_a_b(self, method, a, b):
+        # Regression test for gh-17444: beta.ppf(p, a, b) and beta.isf(p, a, b)
+        # would result in a segmentation fault if either a or b was subnormal.
+        p = 0.9
+        # Depending on the version of Boost that we have vendored and
+        # our setting of the Boost double promotion policy, the call
+        # `stats.beta.ppf(p, a, b)` might raise an OverflowError or
+        # return a value.  We'll accept either behavior (and not care about
+        # the value), because our goal here is to verify that the call does
+        # not trigger a segmentation fault.
+        try:
+            method(p, a, b)
+        except OverflowError:
+            # The OverflowError exception occurs with Boost 1.80 or earlier
+            # when Boost's double promotion policy is false; see
+            #   https://github.com/boostorg/math/issues/882
+            # and
+            #   https://github.com/boostorg/math/pull/883
+            # Once we have vendored the fixed version of Boost, we can drop
+            # this try-except wrapper and just call the function.
+            pass
+
+    # Reference values computed with mpmath.
+    @pytest.mark.parametrize('x, a, b, ref',
+                             [(0.999, 1.5, 2.5, -6.439838145196121e-08),
+                              (2e-9, 3.25, 2.5, -63.13030939685114)])
+    def test_logcdf(self, x, a, b, ref):
+        logcdf = stats.beta.logcdf(x, a, b)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    # Reference values computed with mpmath.
+    @pytest.mark.parametrize('x, a, b, ref',
+                             [(2e-9, 1.5, 2.5, -3.0368535131140806e-13),
+                              (0.998, 3.25, 2.5, -13.309796070871489)])
+    def test_logsf(self, x, a, b, ref):
+        logsf = stats.beta.logsf(x, a, b)
+        assert_allclose(logsf, ref, 5e-15)
+
+    # entropy accuracy was confirmed using the following mpmath function
+    # from mpmath import mp
+    # mp.dps = 50
+    # def beta_entropy_mpmath(a, b):
+    #     a = mp.mpf(a)
+    #     b = mp.mpf(b)
+    #     entropy = mp.log(mp.beta(a, b)) - (a - 1) * mp.digamma(a) -\
+    #              (b - 1) * mp.digamma(b) + (a + b -2) * mp.digamma(a + b)
+    #     return float(entropy)
+
+    @pytest.mark.parametrize('a, b, ref',
+                             [(0.5, 0.5, -0.24156447527049044),
+                              (0.001, 1, -992.0922447210179),
+                              (1, 10000, -8.210440371976183),
+                              (100000, 100000, -5.377247470132859)])
+    def test_entropy(self, a, b, ref):
+        assert_allclose(stats.beta(a, b).entropy(), ref)
+
+    @pytest.mark.parametrize(
+        "a, b, ref, tol",
+        [
+            (1, 10, -1.4025850929940458, 1e-14),
+            (10, 20, -1.0567887388936708, 1e-13),
+            (4e6, 4e6+20, -7.221686009678741, 1e-9),
+            (5e6, 5e6+10, -7.333257022834638, 1e-8),
+            (1e10, 1e10+20, -11.133707703130474, 1e-11),
+            (1e50, 1e50+20, -57.185409562486385, 1e-15),
+            (2, 1e10, -21.448635265288925, 1e-11),
+            (2, 1e20, -44.47448619497938, 1e-14),
+            (2, 1e50, -113.55203898480075, 1e-14),
+            (5, 1e10, -20.87226777401971, 1e-10),
+            (5, 1e20, -43.89811870326017, 1e-14),
+            (5, 1e50, -112.97567149308153, 1e-14),
+            (10, 1e10, -20.489796752909477, 1e-9),
+            (10, 1e20, -43.51564768139993, 1e-14),
+            (10, 1e50, -112.59320047122131, 1e-14),
+            (1e20, 2, -44.47448619497938, 1e-14),
+            (1e20, 5, -43.89811870326017, 1e-14),
+            (1e50, 10, -112.59320047122131, 1e-14),
+        ]
+    )
+    def test_extreme_entropy(self, a, b, ref, tol):
+        # Reference values were calculated with mpmath:
+        # from mpmath import mp
+        # mp.dps = 500
+        #
+        # def beta_entropy_mpmath(a, b):
+        #     a = mp.mpf(a)
+        #     b = mp.mpf(b)
+        #     entropy = (
+        #       mp.log(mp.beta(a, b)) - (a - 1) * mp.digamma(a)
+        #       - (b - 1) * mp.digamma(b) + (a + b - 2) * mp.digamma(a + b)
+        #     )
+        #     return float(entropy)
+        assert_allclose(stats.beta(a, b).entropy(), ref, rtol=tol)
+
+
+class TestBetaPrime:
+    # the test values are used in test_cdf_gh_17631 / test_ppf_gh_17631
+    # They are computed with mpmath. Example:
+    # from mpmath import mp
+    # mp.dps = 50
+    # a, b = mp.mpf(0.05), mp.mpf(0.1)
+    # x = mp.mpf(1e22)
+    # float(mp.betainc(a, b, 0.0, x/(1+x), regularized=True))
+    # note: we use the values computed by the cdf to test whether
+    # ppf(cdf(x)) == x (up to a small tolerance)
+    # since the ppf can be very sensitive to small variations of the input,
+    # it can be required to generate the test case for the ppf separately,
+    # see self.test_ppf
+    cdf_vals = [
+        (1e22, 100.0, 0.05, 0.8973027435427167),
+        (1e10, 100.0, 0.05, 0.5911548582766262),
+        (1e8, 0.05, 0.1, 0.9467768090820048),
+        (1e8, 100.0, 0.05, 0.4852944858726726),
+        (1e-10, 0.05, 0.1, 0.21238845427095),
+        (1e-10, 1.5, 1.5, 1.697652726007973e-15),
+        (1e-10, 0.05, 100.0, 0.40884514172337383),
+        (1e-22, 0.05, 0.1, 0.053349567649287326),
+        (1e-22, 1.5, 1.5, 1.6976527263135503e-33),
+        (1e-22, 0.05, 100.0, 0.10269725645728331),
+        (1e-100, 0.05, 0.1, 6.7163126421919795e-06),
+        (1e-100, 1.5, 1.5, 1.6976527263135503e-150),
+        (1e-100, 0.05, 100.0, 1.2928818587561651e-05),
+    ]
+
+    def test_logpdf(self):
+        alpha, beta = 267, 1472
+        x = np.array([0.2, 0.5, 0.6])
+        b = stats.betaprime(alpha, beta)
+        assert_(np.isfinite(b.logpdf(x)).all())
+        assert_allclose(b.pdf(x), np.exp(b.logpdf(x)))
+
+    def test_cdf(self):
+        # regression test for gh-4030: Implementation of
+        # scipy.stats.betaprime.cdf()
+        x = stats.betaprime.cdf(0, 0.2, 0.3)
+        assert_equal(x, 0.0)
+
+        alpha, beta = 267, 1472
+        x = np.array([0.2, 0.5, 0.6])
+        cdfs = stats.betaprime.cdf(x, alpha, beta)
+        assert_(np.isfinite(cdfs).all())
+
+        # check the new cdf implementation vs generic one:
+        gen_cdf = stats.rv_continuous._cdf_single
+        cdfs_g = [gen_cdf(stats.betaprime, val, alpha, beta) for val in x]
+        assert_allclose(cdfs, cdfs_g, atol=0, rtol=2e-12)
+
+    # The expected values for test_ppf() were computed with mpmath, e.g.
+    #
+    #   from mpmath import mp
+    #   mp.dps = 125
+    #   p = 0.01
+    #   a, b = 1.25, 2.5
+    #   x = mp.findroot(lambda t: mp.betainc(a, b, x1=0, x2=t/(1+t),
+    #                                        regularized=True) - p,
+    #                   x0=(0.01, 0.011), method='secant')
+    #   print(float(x))
+    #
+    # prints
+    #
+    #   0.01080162700956614
+    #
+    @pytest.mark.parametrize(
+        'p, a, b, expected',
+        [(0.010, 1.25, 2.5, 0.01080162700956614),
+         (1e-12, 1.25, 2.5, 1.0610141996279122e-10),
+         (1e-18, 1.25, 2.5, 1.6815941817974941e-15),
+         (1e-17, 0.25, 7.0, 1.0179194531881782e-69),
+         (0.375, 0.25, 7.0, 0.002036820346115211),
+         (0.9978811466052919, 0.05, 0.1, 1.0000000000001218e22),]
+    )
+    def test_ppf(self, p, a, b, expected):
+        x = stats.betaprime.ppf(p, a, b)
+        assert_allclose(x, expected, rtol=1e-14)
+
+    @pytest.mark.parametrize('x, a, b, p', cdf_vals)
+    def test_ppf_gh_17631(self, x, a, b, p):
+        assert_allclose(stats.betaprime.ppf(p, a, b), x, rtol=2e-14)
+
+    def test__ppf(self):
+        # Verify that _ppf supports scalar arrays.
+        a = np.array(1.0)
+        b = np.array(1.0)
+        p = np.array(0.5)
+        assert_allclose(stats.betaprime._ppf(p, a, b), 1.0, rtol=5e-16)
+
+    @pytest.mark.parametrize(
+        'x, a, b, expected',
+        cdf_vals + [
+            (1e10, 1.5, 1.5, 0.9999999999999983),
+            (1e10, 0.05, 0.1, 0.9664184367890859),
+            (1e22, 0.05, 0.1, 0.9978811466052919),
+        ])
+    def test_cdf_gh_17631(self, x, a, b, expected):
+        assert_allclose(stats.betaprime.cdf(x, a, b), expected, rtol=1e-14)
+
+    @pytest.mark.parametrize(
+        'x, a, b, expected',
+        [(1e50, 0.05, 0.1, 0.9999966641709545),
+         (1e50, 100.0, 0.05, 0.995925162631006)])
+    def test_cdf_extreme_tails(self, x, a, b, expected):
+        # for even more extreme values, we only get a few correct digits
+        # results are still < 1
+        y = stats.betaprime.cdf(x, a, b)
+        assert y < 1.0
+        assert_allclose(y, expected, rtol=2e-5)
+
+    def test_sf(self):
+        # reference values were computed via the reference distribution,
+        # e.g.
+        # mp.dps = 50
+        # a, b = 5, 3
+        # x = 1e10
+        # BetaPrime(a=a, b=b).sf(x); returns 3.4999999979e-29
+        a = [5, 4, 2, 0.05, 0.05, 0.05, 0.05, 100.0, 100.0, 0.05, 0.05,
+             0.05, 1.5, 1.5]
+        b = [3, 2, 1, 0.1, 0.1, 0.1, 0.1, 0.05, 0.05, 100.0, 100.0,
+             100.0, 1.5, 1.5]
+        x = [1e10, 1e20, 1e30, 1e22, 1e-10, 1e-22, 1e-100, 1e22, 1e10,
+             1e-10, 1e-22, 1e-100, 1e10, 1e-10]
+        ref = [3.4999999979e-29, 9.999999999994357e-40, 1.9999999999999998e-30,
+               0.0021188533947081017, 0.78761154572905, 0.9466504323507127,
+               0.9999932836873578, 0.10269725645728331, 0.40884514172337383,
+               0.5911548582766262, 0.8973027435427167, 0.9999870711814124,
+               1.6976527260079727e-15, 0.9999999999999983]
+        sf_values = stats.betaprime.sf(x, a, b)
+        assert_allclose(sf_values, ref, rtol=1e-12)
+
+    def test_logcdf(self):
+        x = 800
+        a = 0.5
+        b = 5.0
+        ref = -7.467307556554531e-16
+        logcdf = stats.betaprime.logcdf(x, a, b)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    def test_logsf(self):
+        x = 1e-8
+        a = 4.5
+        b = 0.5
+        ref = -2.5868992866500915e-37
+        logsf = stats.betaprime.logsf(x, a, b)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+
+    def test_fit_stats_gh18274(self):
+        # gh-18274 reported spurious warning emitted when fitting `betaprime`
+        # to data. Some of these were emitted by stats, too. Check that the
+        # warnings are no longer emitted.
+        stats.betaprime.fit([0.1, 0.25, 0.3, 1.2, 1.6], floc=0, fscale=1)
+        stats.betaprime(a=1, b=1).stats('mvsk')
+
+    def test_moment_gh18634(self):
+        # Testing for gh-18634 revealed that `betaprime` raised a
+        # NotImplementedError for higher moments. Check that this is
+        # resolved. Parameters are arbitrary but lie on either side of the
+        # moment order (5) to test both branches of `_lazywhere`. Reference
+        # values produced with Mathematica, e.g.
+        # `Moment[BetaPrimeDistribution[2,7],5]`
+        ref = [np.inf, 0.867096912929055]
+        res = stats.betaprime(2, [4.2, 7.1]).moment(5)
+        assert_allclose(res, ref)
+
+
+class TestGamma:
+    def test_pdf(self):
+        # a few test cases to compare with R
+        pdf = stats.gamma.pdf(90, 394, scale=1./5)
+        assert_almost_equal(pdf, 0.002312341)
+
+        pdf = stats.gamma.pdf(3, 10, scale=1./5)
+        assert_almost_equal(pdf, 0.1620358)
+
+    def test_logpdf(self):
+        # Regression test for Ticket #1326: cornercase avoid nan with 0*log(0)
+        # situation
+        logpdf = stats.gamma.logpdf(0, 1)
+        assert_almost_equal(logpdf, 0)
+
+    def test_fit_bad_keyword_args(self):
+        x = [0.1, 0.5, 0.6]
+        assert_raises(TypeError, stats.gamma.fit, x, floc=0, plate="shrimp")
+
+    def test_isf(self):
+        # Test cases for when the probability is very small. See gh-13664.
+        # The expected values can be checked with mpmath.  With mpmath,
+        # the survival function sf(x, k) can be computed as
+        #
+        #     mpmath.gammainc(k, x, mpmath.inf, regularized=True)
+        #
+        # Here we have:
+        #
+        # >>> mpmath.mp.dps = 60
+        # >>> float(mpmath.gammainc(1, 39.14394658089878, mpmath.inf,
+        # ...                       regularized=True))
+        # 9.99999999999999e-18
+        # >>> float(mpmath.gammainc(100, 330.6557590436547, mpmath.inf,
+        #                           regularized=True))
+        # 1.000000000000028e-50
+        #
+        assert np.isclose(stats.gamma.isf(1e-17, 1),
+                          39.14394658089878, atol=1e-14)
+        assert np.isclose(stats.gamma.isf(1e-50, 100),
+                          330.6557590436547, atol=1e-13)
+
+    def test_logcdf(self):
+        x = 80
+        a = 7
+        ref = -7.096510270453943e-27
+        logcdf = stats.gamma.logcdf(x, a)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    def test_logsf(self):
+        x = 0.001
+        a = 3.0
+        ref = -1.6654171666664883e-10
+        logsf = stats.gamma.logsf(x, a)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+    @pytest.mark.parametrize('scale', [1.0, 5.0])
+    def test_delta_cdf(self, scale):
+        # Expected value computed with mpmath:
+        #
+        # >>> import mpmath
+        # >>> mpmath.mp.dps = 150
+        # >>> cdf1 = mpmath.gammainc(3, 0, 245, regularized=True)
+        # >>> cdf2 = mpmath.gammainc(3, 0, 250, regularized=True)
+        # >>> float(cdf2 - cdf1)
+        # 1.1902609356171962e-102
+        #
+        delta = stats.gamma._delta_cdf(scale*245, scale*250, 3, scale=scale)
+        assert_allclose(delta, 1.1902609356171962e-102, rtol=1e-13)
+
+    @pytest.mark.parametrize('a, ref, rtol',
+                             [(1e-4, -9990.366610819761, 1e-15),
+                              (2, 1.5772156649015328, 1e-15),
+                              (100, 3.7181819485047463, 1e-13),
+                              (1e4, 6.024075385026086, 1e-15),
+                              (1e18, 22.142204370151084, 1e-15),
+                              (1e100, 116.54819318290696, 1e-15)])
+    def test_entropy(self, a, ref, rtol):
+        # expected value computed with mpmath:
+        # from mpmath import mp
+        # mp.dps = 500
+        # def gamma_entropy_reference(x):
+        #     x = mp.mpf(x)
+        #     return float(mp.digamma(x) * (mp.one - x) + x + mp.loggamma(x))
+
+        assert_allclose(stats.gamma.entropy(a), ref, rtol=rtol)
+
+    @pytest.mark.parametrize("a", [1e-2, 1, 1e2])
+    @pytest.mark.parametrize("loc", [1e-2, 0, 1e2])
+    @pytest.mark.parametrize('scale', [1e-2, 1, 1e2])
+    @pytest.mark.parametrize('fix_a', [True, False])
+    @pytest.mark.parametrize('fix_loc', [True, False])
+    @pytest.mark.parametrize('fix_scale', [True, False])
+    def test_fit_mm(self, a, loc, scale, fix_a, fix_loc, fix_scale):
+        rng = np.random.default_rng(6762668991392531563)
+        data = stats.gamma.rvs(a, loc=loc, scale=scale, size=100,
+                               random_state=rng)
+
+        kwds = {}
+        if fix_a:
+            kwds['fa'] = a
+        if fix_loc:
+            kwds['floc'] = loc
+        if fix_scale:
+            kwds['fscale'] = scale
+        nfree = 3 - len(kwds)
+
+        if nfree == 0:
+            error_msg = "All parameters fixed. There is nothing to optimize."
+            with pytest.raises(ValueError, match=error_msg):
+                stats.gamma.fit(data, method='mm', **kwds)
+            return
+
+        theta = stats.gamma.fit(data, method='mm', **kwds)
+        dist = stats.gamma(*theta)
+        if nfree >= 1:
+            assert_allclose(dist.mean(), np.mean(data))
+        if nfree >= 2:
+            assert_allclose(dist.moment(2), np.mean(data**2))
+        if nfree >= 3:
+            assert_allclose(dist.moment(3), np.mean(data**3))
+
+
+def test_pdf_overflow_gh19616():
+    # Confirm that gh19616 (intermediate over/underflows in PDF) is resolved
+    # Reference value from R GeneralizedHyperbolic library
+    # library(GeneralizedHyperbolic)
+    # options(digits=16)
+    # jitter = 1e-3
+    # dnig(1, a=2**0.5 / jitter**2, b=1 / jitter**2)
+    jitter = 1e-3
+    Z = stats.norminvgauss(2**0.5 / jitter**2, 1 / jitter**2, loc=0, scale=1)
+    assert_allclose(Z.pdf(1.0), 282.0948446666433)
+
+
+class TestDgamma:
+    def test_pdf(self):
+        rng = np.random.default_rng(3791303244302340058)
+        size = 10  # number of points to check
+        x = rng.normal(scale=10, size=size)
+        a = rng.uniform(high=10, size=size)
+        res = stats.dgamma.pdf(x, a)
+        ref = stats.gamma.pdf(np.abs(x), a) / 2
+        assert_allclose(res, ref)
+
+        dist = stats.dgamma(a)
+        # There was an intermittent failure with assert_equal on Linux - 32 bit
+        assert_allclose(dist.pdf(x), res, rtol=5e-16)
+
+    # mpmath was used to compute the expected values.
+    # For x < 0, cdf(x, a) is mp.gammainc(a, -x, mp.inf, regularized=True)/2
+    # For x > 0, cdf(x, a) is (1 + mp.gammainc(a, 0, x, regularized=True))/2
+    # E.g.
+    #    from mpmath import mp
+    #    mp.dps = 50
+    #    print(float(mp.gammainc(1, 20, mp.inf, regularized=True)/2))
+    # prints
+    #    1.030576811219279e-09
+    @pytest.mark.parametrize('x, a, expected',
+                             [(-20, 1, 1.030576811219279e-09),
+                              (-40, 1, 2.1241771276457944e-18),
+                              (-50, 5, 2.7248509914602648e-17),
+                              (-25, 0.125, 5.333071920958156e-14),
+                              (5, 1, 0.9966310265004573)])
+    def test_cdf_ppf_sf_isf_tail(self, x, a, expected):
+        cdf = stats.dgamma.cdf(x, a)
+        assert_allclose(cdf, expected, rtol=5e-15)
+        ppf = stats.dgamma.ppf(expected, a)
+        assert_allclose(ppf, x, rtol=5e-15)
+        sf = stats.dgamma.sf(-x, a)
+        assert_allclose(sf, expected, rtol=5e-15)
+        isf = stats.dgamma.isf(expected, a)
+        assert_allclose(isf, -x, rtol=5e-15)
+
+    @pytest.mark.parametrize("a, ref",
+                             [(1.5, 2.0541199559354117),
+                             (1.3, 1.9357296377121247),
+                             (1.1, 1.7856502333412134)])
+    def test_entropy(self, a, ref):
+        # The reference values were calculated with mpmath:
+        # def entropy_dgamma(a):
+        #    def pdf(x):
+        #        A = mp.one / (mp.mpf(2.) * mp.gamma(a))
+        #        B = mp.fabs(x) ** (a - mp.one)
+        #        C = mp.exp(-mp.fabs(x))
+        #        h = A * B * C
+        #        return h
+        #
+        #    return -mp.quad(lambda t: pdf(t) * mp.log(pdf(t)),
+        #                    [-mp.inf, mp.inf])
+        assert_allclose(stats.dgamma.entropy(a), ref, rtol=1e-14)
+
+    @pytest.mark.parametrize("a, ref",
+                             [(1e-100, -1e+100),
+                             (1e-10, -9999999975.858217),
+                             (1e-5, -99987.37111657023),
+                             (1e4, 6.717222565586032),
+                             (1000000000000000.0, 19.38147391121996),
+                             (1e+100, 117.2413403634669)])
+    def test_entropy_entreme_values(self, a, ref):
+        # The reference values were calculated with mpmath:
+        # from mpmath import mp
+        # mp.dps = 500
+        # def second_dgamma(a):
+        #     a = mp.mpf(a)
+        #     x_1 = a + mp.log(2) + mp.loggamma(a)
+        #     x_2 = (mp.one - a) * mp.digamma(a)
+        #     h = x_1 + x_2
+        #     return h
+        assert_allclose(stats.dgamma.entropy(a), ref, rtol=1e-10)
+
+    def test_entropy_array_input(self):
+        x = np.array([1, 5, 1e20, 1e-5])
+        y = stats.dgamma.entropy(x)
+        for i in range(len(y)):
+            assert y[i] == stats.dgamma.entropy(x[i])
+
+
+class TestChi2:
+
+    # regression tests after precision improvements, ticket:1041, not verified
+    def test_precision(self):
+        assert_almost_equal(stats.chi2.pdf(1000, 1000), 8.919133934753128e-003,
+                            decimal=14)
+        assert_almost_equal(stats.chi2.pdf(100, 100), 0.028162503162596778,
+                            decimal=14)
+
+    # Reference values computed with mpmath.
+    @pytest.mark.parametrize(
+        'x, df, ref',
+        [(750.0, 3, -3.0172957781136564e-162),
+         (120.0, 15, -1.8924849646375648e-18),
+         (15.0, 13, -0.36723446372517876)]
+    )
+    def test_logcdf(self, x, df, ref):
+        logcdf = stats.chi2.logcdf(x, df)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    # Reference values computed with mpmath.
+    @pytest.mark.parametrize(
+        'x, df, ref',
+        [(1e-4, 15, -3.936060782678026e-37),
+         (1.5, 40, -6.384797888313517e-22),
+         (3.0, 10, -0.018750635779926784)]
+    )
+    def test_logsf(self, x, df, ref):
+        logsf = stats.chi2.logsf(x, df)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+    def test_ppf(self):
+        # Expected values computed with mpmath.
+        df = 4.8
+        x = stats.chi2.ppf(2e-47, df)
+        assert_allclose(x, 1.098472479575179840604902808e-19, rtol=1e-10)
+        x = stats.chi2.ppf(0.5, df)
+        assert_allclose(x, 4.15231407598589358660093156, rtol=1e-10)
+
+        df = 13
+        x = stats.chi2.ppf(2e-77, df)
+        assert_allclose(x, 1.0106330688195199050507943e-11, rtol=1e-10)
+        x = stats.chi2.ppf(0.1, df)
+        assert_allclose(x, 7.041504580095461859307179763, rtol=1e-10)
+
+    # Entropy references values were computed with the following mpmath code
+    # from mpmath import mp
+    # mp.dps = 50
+    # def chisq_entropy_mpmath(df):
+    #     df = mp.mpf(df)
+    #     half_df = 0.5 * df
+    #     entropy = (half_df + mp.log(2) + mp.log(mp.gamma(half_df)) +
+    #                (mp.one - half_df) * mp.digamma(half_df))
+    #     return float(entropy)
+
+    @pytest.mark.parametrize('df, ref',
+                             [(1e-4, -19988.980448690163),
+                              (1, 0.7837571104739337),
+                              (100, 4.061397128938114),
+                              (251, 4.525577254045129),
+                              (1e15, 19.034900320939986)])
+    def test_entropy(self, df, ref):
+        assert_allclose(stats.chi2(df).entropy(), ref, rtol=1e-13)
+
+    def test_regression_ticket_1326(self):
+        # adjust to avoid nan with 0*log(0)
+        assert_almost_equal(stats.chi2.pdf(0.0, 2), 0.5, 14)
+
+
+class TestGumbelL:
+    # gh-6228
+    def test_cdf_ppf(self):
+        x = np.linspace(-100, -4)
+        y = stats.gumbel_l.cdf(x)
+        xx = stats.gumbel_l.ppf(y)
+        assert_allclose(x, xx)
+
+    def test_logcdf_logsf(self):
+        x = np.linspace(-100, -4)
+        y = stats.gumbel_l.logcdf(x)
+        z = stats.gumbel_l.logsf(x)
+        u = np.exp(y)
+        v = -special.expm1(z)
+        assert_allclose(u, v)
+
+    def test_sf_isf(self):
+        x = np.linspace(-20, 5)
+        y = stats.gumbel_l.sf(x)
+        xx = stats.gumbel_l.isf(y)
+        assert_allclose(x, xx)
+
+    @pytest.mark.parametrize('loc', [-1, 1])
+    def test_fit_fixed_param(self, loc):
+        # ensure fixed location is correctly reflected from `gumbel_r.fit`
+        # See comments at end of gh-12737.
+        data = stats.gumbel_l.rvs(size=100, loc=loc)
+        fitted_loc, _ = stats.gumbel_l.fit(data, floc=loc)
+        assert_equal(fitted_loc, loc)
+
+
+class TestGumbelR:
+
+    def test_sf(self):
+        # Expected value computed with mpmath:
+        #   >>> import mpmath
+        #   >>> mpmath.mp.dps = 40
+        #   >>> float(mpmath.mp.one - mpmath.exp(-mpmath.exp(-50)))
+        #   1.9287498479639178e-22
+        assert_allclose(stats.gumbel_r.sf(50), 1.9287498479639178e-22,
+                        rtol=1e-14)
+
+    def test_isf(self):
+        # Expected value computed with mpmath:
+        #   >>> import mpmath
+        #   >>> mpmath.mp.dps = 40
+        #   >>> float(-mpmath.log(-mpmath.log(mpmath.mp.one - 1e-17)))
+        #   39.14394658089878
+        assert_allclose(stats.gumbel_r.isf(1e-17), 39.14394658089878,
+                        rtol=1e-14)
+
+
+class TestLevyStable:
+    @pytest.fixture(autouse=True)
+    def reset_levy_stable_params(self):
+        """Setup default parameters for levy_stable generator"""
+        stats.levy_stable.parameterization = "S1"
+        stats.levy_stable.cdf_default_method = "piecewise"
+        stats.levy_stable.pdf_default_method = "piecewise"
+        stats.levy_stable.quad_eps = stats._levy_stable._QUAD_EPS
+
+    @pytest.fixture
+    def nolan_pdf_sample_data(self):
+        """Sample data points for pdf computed with Nolan's stablec
+
+        See - http://fs2.american.edu/jpnolan/www/stable/stable.html
+
+        There's a known limitation of Nolan's executable for alpha < 0.2.
+
+        The data table loaded below is generated from Nolan's stablec
+        with the following parameter space:
+
+            alpha = 0.1, 0.2, ..., 2.0
+            beta = -1.0, -0.9, ..., 1.0
+            p = 0.01, 0.05, 0.1, 0.25, 0.35, 0.5,
+        and the equivalent for the right tail
+
+        Typically inputs for stablec:
+
+            stablec.exe <<
+            1 # pdf
+            1 # Nolan S equivalent to S0 in scipy
+            .25,2,.25 # alpha
+            -1,-1,0 # beta
+            -10,10,1 # x
+            1,0 # gamma, delta
+            2 # output file
+        """
+        data = np.load(
+            Path(__file__).parent /
+            'data/levy_stable/stable-Z1-pdf-sample-data.npy'
+        )
+        data = np.rec.fromarrays(data.T, names='x,p,alpha,beta,pct')
+        return data
+
+    @pytest.fixture
+    def nolan_cdf_sample_data(self):
+        """Sample data points for cdf computed with Nolan's stablec
+
+        See - http://fs2.american.edu/jpnolan/www/stable/stable.html
+
+        There's a known limitation of Nolan's executable for alpha < 0.2.
+
+        The data table loaded below is generated from Nolan's stablec
+        with the following parameter space:
+
+            alpha = 0.1, 0.2, ..., 2.0
+            beta = -1.0, -0.9, ..., 1.0
+            p = 0.01, 0.05, 0.1, 0.25, 0.35, 0.5,
+
+        and the equivalent for the right tail
+
+        Ideally, Nolan's output for CDF values should match the percentile
+        from where they have been sampled from. Even more so as we extract
+        percentile x positions from stablec too. However, we note at places
+        Nolan's stablec will produce absolute errors in order of 1e-5. We
+        compare against his calculations here. In future, once we less
+        reliant on Nolan's paper we might switch to comparing directly at
+        percentiles (those x values being produced from some alternative
+        means).
+
+        Typically inputs for stablec:
+
+            stablec.exe <<
+            2 # cdf
+            1 # Nolan S equivalent to S0 in scipy
+            .25,2,.25 # alpha
+            -1,-1,0 # beta
+            -10,10,1 # x
+            1,0 # gamma, delta
+            2 # output file
+        """
+        data = np.load(
+            Path(__file__).parent /
+            'data/levy_stable/stable-Z1-cdf-sample-data.npy'
+        )
+        data = np.rec.fromarrays(data.T, names='x,p,alpha,beta,pct')
+        return data
+
+    @pytest.fixture
+    def nolan_loc_scale_sample_data(self):
+        """Sample data where loc, scale are different from 0, 1
+
+        Data extracted in similar way to pdf/cdf above using
+        Nolan's stablec but set to an arbitrary location scale of
+        (2, 3) for various important parameters alpha, beta and for
+        parameterisations S0 and S1.
+        """
+        data = np.load(
+            Path(__file__).parent /
+            'data/levy_stable/stable-loc-scale-sample-data.npy'
+        )
+        return data
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize(
+        "sample_size", [
+            pytest.param(50), pytest.param(1500, marks=pytest.mark.slow)
+        ]
+    )
+    @pytest.mark.parametrize("parameterization", ["S0", "S1"])
+    @pytest.mark.parametrize(
+        "alpha,beta", [(1.0, 0), (1.0, -0.5), (1.5, 0), (1.9, 0.5)]
+    )
+    @pytest.mark.parametrize("gamma,delta", [(1, 0), (3, 2)])
+    def test_rvs(
+            self,
+            parameterization,
+            alpha,
+            beta,
+            gamma,
+            delta,
+            sample_size,
+    ):
+        stats.levy_stable.parameterization = parameterization
+        ls = stats.levy_stable(
+            alpha=alpha, beta=beta, scale=gamma, loc=delta
+        )
+        _, p = stats.kstest(
+            ls.rvs(size=sample_size, random_state=1234), ls.cdf
+        )
+        assert p > 0.05
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize('beta', [0.5, 1])
+    def test_rvs_alpha1(self, beta):
+        """Additional test cases for rvs for alpha equal to 1."""
+        np.random.seed(987654321)
+        alpha = 1.0
+        loc = 0.5
+        scale = 1.5
+        x = stats.levy_stable.rvs(alpha, beta, loc=loc, scale=scale,
+                                  size=5000)
+        stat, p = stats.kstest(x, 'levy_stable',
+                               args=(alpha, beta, loc, scale))
+        assert p > 0.01
+
+    def test_fit(self):
+        # construct data to have percentiles that match
+        # example in McCulloch 1986.
+        x = [
+            -.05413, -.05413, 0., 0., 0., 0., .00533, .00533, .00533, .00533,
+            .00533, .03354, .03354, .03354, .03354, .03354, .05309, .05309,
+            .05309, .05309, .05309
+        ]
+        alpha1, beta1, loc1, scale1 = stats.levy_stable._fitstart(x)
+        assert_allclose(alpha1, 1.48, rtol=0, atol=0.01)
+        assert_almost_equal(beta1, -.22, 2)
+        assert_almost_equal(scale1, 0.01717, 4)
+        assert_almost_equal(
+            loc1, 0.00233, 2
+        )  # to 2 dps due to rounding error in McCulloch86
+
+        # cover alpha=2 scenario
+        x2 = x + [.05309, .05309, .05309, .05309, .05309]
+        alpha2, beta2, loc2, scale2 = stats.levy_stable._fitstart(x2)
+        assert_equal(alpha2, 2)
+        assert_equal(beta2, -1)
+        assert_almost_equal(scale2, .02503, 4)
+        assert_almost_equal(loc2, .03354, 4)
+
+    @pytest.mark.xfail(reason="Unknown problem with fitstart.")
+    @pytest.mark.parametrize(
+        "alpha,beta,delta,gamma",
+        [
+            (1.5, 0.4, 2, 3),
+            (1.0, 0.4, 2, 3),
+        ]
+    )
+    @pytest.mark.parametrize(
+        "parametrization", ["S0", "S1"]
+    )
+    def test_fit_rvs(self, alpha, beta, delta, gamma, parametrization):
+        """Test that fit agrees with rvs for each parametrization."""
+        stats.levy_stable.parametrization = parametrization
+        data = stats.levy_stable.rvs(
+            alpha, beta, loc=delta, scale=gamma, size=10000, random_state=1234
+        )
+        fit = stats.levy_stable._fitstart(data)
+        alpha_obs, beta_obs, delta_obs, gamma_obs = fit
+        assert_allclose(
+            [alpha, beta, delta, gamma],
+            [alpha_obs, beta_obs, delta_obs, gamma_obs],
+            rtol=0.01,
+        )
+
+    def test_fit_beta_flip(self):
+        # Confirm that sign of beta affects loc, not alpha or scale.
+        x = np.array([1, 1, 3, 3, 10, 10, 10, 30, 30, 100, 100])
+        alpha1, beta1, loc1, scale1 = stats.levy_stable._fitstart(x)
+        alpha2, beta2, loc2, scale2 = stats.levy_stable._fitstart(-x)
+        assert_equal(beta1, 1)
+        assert loc1 != 0
+        assert_almost_equal(alpha2, alpha1)
+        assert_almost_equal(beta2, -beta1)
+        assert_almost_equal(loc2, -loc1)
+        assert_almost_equal(scale2, scale1)
+
+    def test_fit_delta_shift(self):
+        # Confirm that loc slides up and down if data shifts.
+        SHIFT = 1
+        x = np.array([1, 1, 3, 3, 10, 10, 10, 30, 30, 100, 100])
+        alpha1, beta1, loc1, scale1 = stats.levy_stable._fitstart(-x)
+        alpha2, beta2, loc2, scale2 = stats.levy_stable._fitstart(-x + SHIFT)
+        assert_almost_equal(alpha2, alpha1)
+        assert_almost_equal(beta2, beta1)
+        assert_almost_equal(loc2, loc1 + SHIFT)
+        assert_almost_equal(scale2, scale1)
+
+    def test_fit_loc_extrap(self):
+        # Confirm that loc goes out of sample for alpha close to 1.
+        x = [1, 1, 3, 3, 10, 10, 10, 30, 30, 140, 140]
+        alpha1, beta1, loc1, scale1 = stats.levy_stable._fitstart(x)
+        assert alpha1 < 1, f"Expected alpha < 1, got {alpha1}"
+        assert loc1 < min(x), f"Expected loc < {min(x)}, got {loc1}"
+
+        x2 = [1, 1, 3, 3, 10, 10, 10, 30, 30, 130, 130]
+        alpha2, beta2, loc2, scale2 = stats.levy_stable._fitstart(x2)
+        assert alpha2 > 1, f"Expected alpha > 1, got {alpha2}"
+        assert loc2 > max(x2), f"Expected loc > {max(x2)}, got {loc2}"
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize(
+        "pct_range,alpha_range,beta_range", [
+            pytest.param(
+                [.01, .5, .99],
+                [.1, 1, 2],
+                [-1, 0, .8],
+            ),
+            pytest.param(
+                [.01, .05, .5, .95, .99],
+                [.1, .5, 1, 1.5, 2],
+                [-.9, -.5, 0, .3, .6, 1],
+                marks=pytest.mark.slow
+            ),
+            pytest.param(
+                [.01, .05, .1, .25, .35, .5, .65, .75, .9, .95, .99],
+                np.linspace(0.1, 2, 20),
+                np.linspace(-1, 1, 21),
+                marks=pytest.mark.xslow,
+            ),
+        ]
+    )
+    def test_pdf_nolan_samples(
+            self, nolan_pdf_sample_data, pct_range, alpha_range, beta_range
+    ):
+        """Test pdf values against Nolan's stablec.exe output"""
+        data = nolan_pdf_sample_data
+
+        # some tests break on linux 32 bit
+        uname = platform.uname()
+        is_linux_32 = uname.system == 'Linux' and uname.machine == 'i686'
+        platform_desc = "/".join(
+            [uname.system, uname.machine, uname.processor])
+
+        # fmt: off
+        # There are a number of cases which fail on some but not all platforms.
+        # These are excluded by the filters below. TODO: Rewrite tests so that
+        # the now filtered out test cases are still run but marked in pytest as
+        # expected to fail.
+        tests = [
+            [
+                'dni', 1e-7, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    ~(
+                        (
+                            (r['beta'] == 0) &
+                            (r['pct'] == 0.5)
+                        ) |
+                        (
+                            (r['beta'] >= 0.9) &
+                            (r['alpha'] >= 1.6) &
+                            (r['pct'] == 0.5)
+                        ) |
+                        (
+                            (r['alpha'] <= 0.4) &
+                            np.isin(r['pct'], [.01, .99])
+                        ) |
+                        (
+                            (r['alpha'] <= 0.3) &
+                            np.isin(r['pct'], [.05, .95])
+                        ) |
+                        (
+                            (r['alpha'] <= 0.2) &
+                            np.isin(r['pct'], [.1, .9])
+                        ) |
+                        (
+                            (r['alpha'] == 0.1) &
+                            np.isin(r['pct'], [.25, .75]) &
+                            np.isin(np.abs(r['beta']), [.5, .6, .7])
+                        ) |
+                        (
+                            (r['alpha'] == 0.1) &
+                            np.isin(r['pct'], [.5]) &
+                            np.isin(np.abs(r['beta']), [.1])
+                        ) |
+                        (
+                            (r['alpha'] == 0.1) &
+                            np.isin(r['pct'], [.35, .65]) &
+                            np.isin(np.abs(r['beta']), [-.4, -.3, .3, .4, .5])
+                        ) |
+                        (
+                            (r['alpha'] == 0.2) &
+                            (r['beta'] == 0.5) &
+                            (r['pct'] == 0.25)
+                        ) |
+                        (
+                            (r['alpha'] == 0.2) &
+                            (r['beta'] == -0.3) &
+                            (r['pct'] == 0.65)
+                        ) |
+                        (
+                            (r['alpha'] == 0.2) &
+                            (r['beta'] == 0.3) &
+                            (r['pct'] == 0.35)
+                        ) |
+                        (
+                            (r['alpha'] == 1.) &
+                            np.isin(r['pct'], [.5]) &
+                            np.isin(np.abs(r['beta']), [.1, .2, .3, .4])
+                        ) |
+                        (
+                            (r['alpha'] == 1.) &
+                            np.isin(r['pct'], [.35, .65]) &
+                            np.isin(np.abs(r['beta']), [.8, .9, 1.])
+                        ) |
+                        (
+                            (r['alpha'] == 1.) &
+                            np.isin(r['pct'], [.01, .99]) &
+                            np.isin(np.abs(r['beta']), [-.1, .1])
+                        ) |
+                        # various points ok but too sparse to list
+                        (r['alpha'] >= 1.1)
+                    )
+                )
+            ],
+            # piecewise generally good accuracy
+            [
+                'piecewise', 1e-11, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    (r['alpha'] > 0.2) &
+                    (r['alpha'] != 1.)
+                )
+            ],
+            # for alpha = 1. for linux 32 bit optimize.bisect
+            # has some issues for .01 and .99 percentile
+            [
+                'piecewise', 1e-11, lambda r: (
+                    (r['alpha'] == 1.) &
+                    (not is_linux_32) &
+                    np.isin(r['pct'], pct_range) &
+                    (1. in alpha_range) &
+                    np.isin(r['beta'], beta_range)
+                )
+            ],
+            # for small alpha very slightly reduced accuracy
+            [
+                'piecewise', 2.5e-10, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    (r['alpha'] <= 0.2)
+                )
+            ],
+            # fft accuracy reduces as alpha decreases
+            [
+                'fft-simpson', 1e-5, lambda r: (
+                    (r['alpha'] >= 1.9) &
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range)
+                ),
+            ],
+            [
+                'fft-simpson', 1e-6, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    (r['alpha'] > 1) &
+                    (r['alpha'] < 1.9)
+                )
+            ],
+            # fft relative errors for alpha < 1, will raise if enabled
+            # ['fft-simpson', 1e-4, lambda r: r['alpha'] == 0.9],
+            # ['fft-simpson', 1e-3, lambda r: r['alpha'] == 0.8],
+            # ['fft-simpson', 1e-2, lambda r: r['alpha'] == 0.7],
+            # ['fft-simpson', 1e-1, lambda r: r['alpha'] == 0.6],
+        ]
+        # fmt: on
+        for ix, (default_method, rtol,
+                 filter_func) in enumerate(tests):
+            stats.levy_stable.pdf_default_method = default_method
+            subdata = data[filter_func(data)
+                           ] if filter_func is not None else data
+            with suppress_warnings() as sup:
+                # occurs in FFT methods only
+                sup.record(
+                    RuntimeWarning,
+                    "Density calculations experimental for FFT method.*"
+                )
+                p = stats.levy_stable.pdf(
+                    subdata['x'],
+                    subdata['alpha'],
+                    subdata['beta'],
+                    scale=1,
+                    loc=0
+                )
+                with np.errstate(over="ignore"):
+                    subdata2 = rec_append_fields(
+                        subdata,
+                        ['calc', 'abserr', 'relerr'],
+                        [
+                            p,
+                            np.abs(p - subdata['p']),
+                            np.abs(p - subdata['p']) / np.abs(subdata['p'])
+                        ]
+                    )
+                failures = subdata2[
+                  (subdata2['relerr'] >= rtol) |
+                  np.isnan(p)
+                ]
+                message = (
+                    f"pdf test {ix} failed with method '{default_method}' "
+                    f"[platform: {platform_desc}]\n{failures.dtype.names}\n{failures}"
+                )
+                assert_allclose(
+                    p,
+                    subdata['p'],
+                    rtol,
+                    err_msg=message,
+                    verbose=False
+                )
+
+    @pytest.mark.parametrize(
+        "pct_range,alpha_range,beta_range", [
+            pytest.param(
+                [.01, .5, .99],
+                [.1, 1, 2],
+                [-1, 0, .8],
+            ),
+            pytest.param(
+                [.01, .05, .5, .95, .99],
+                [.1, .5, 1, 1.5, 2],
+                [-.9, -.5, 0, .3, .6, 1],
+                marks=pytest.mark.slow
+            ),
+            pytest.param(
+                [.01, .05, .1, .25, .35, .5, .65, .75, .9, .95, .99],
+                np.linspace(0.1, 2, 20),
+                np.linspace(-1, 1, 21),
+                marks=pytest.mark.xslow,
+            ),
+        ]
+    )
+    def test_cdf_nolan_samples(
+            self, nolan_cdf_sample_data, pct_range, alpha_range, beta_range
+    ):
+        """ Test cdf values against Nolan's stablec.exe output."""
+        data = nolan_cdf_sample_data
+        tests = [
+            # piecewise generally good accuracy
+            [
+                'piecewise', 2e-12, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    ~(
+                        (
+                            (r['alpha'] == 1.) &
+                            np.isin(r['beta'], [-0.3, -0.2, -0.1]) &
+                            (r['pct'] == 0.01)
+                        ) |
+                        (
+                            (r['alpha'] == 1.) &
+                            np.isin(r['beta'], [0.1, 0.2, 0.3]) &
+                            (r['pct'] == 0.99)
+                        )
+                    )
+                )
+            ],
+            # for some points with alpha=1, Nolan's STABLE clearly
+            # loses accuracy
+            [
+                'piecewise', 5e-2, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    (
+                        (r['alpha'] == 1.) &
+                        np.isin(r['beta'], [-0.3, -0.2, -0.1]) &
+                        (r['pct'] == 0.01)
+                    ) |
+                    (
+                        (r['alpha'] == 1.) &
+                        np.isin(r['beta'], [0.1, 0.2, 0.3]) &
+                        (r['pct'] == 0.99)
+                    )
+                )
+            ],
+            # fft accuracy poor, very poor alpha < 1
+            [
+                'fft-simpson', 1e-5, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    (r['alpha'] > 1.7)
+                )
+            ],
+            [
+                'fft-simpson', 1e-4, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    (r['alpha'] > 1.5) &
+                    (r['alpha'] <= 1.7)
+                )
+            ],
+            [
+                'fft-simpson', 1e-3, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    (r['alpha'] > 1.3) &
+                    (r['alpha'] <= 1.5)
+                )
+            ],
+            [
+                'fft-simpson', 1e-2, lambda r: (
+                    np.isin(r['pct'], pct_range) &
+                    np.isin(r['alpha'], alpha_range) &
+                    np.isin(r['beta'], beta_range) &
+                    (r['alpha'] > 1.0) &
+                    (r['alpha'] <= 1.3)
+                )
+            ],
+        ]
+        for ix, (default_method, rtol,
+                 filter_func) in enumerate(tests):
+            stats.levy_stable.cdf_default_method = default_method
+            subdata = data[filter_func(data)
+                           ] if filter_func is not None else data
+            with suppress_warnings() as sup:
+                sup.record(
+                    RuntimeWarning,
+                    'Cumulative density calculations experimental for FFT'
+                    + ' method. Use piecewise method instead.*'
+                )
+                p = stats.levy_stable.cdf(
+                    subdata['x'],
+                    subdata['alpha'],
+                    subdata['beta'],
+                    scale=1,
+                    loc=0
+                )
+                with np.errstate(over="ignore"):
+                    subdata2 = rec_append_fields(
+                        subdata,
+                        ['calc', 'abserr', 'relerr'],
+                        [
+                            p,
+                            np.abs(p - subdata['p']),
+                            np.abs(p - subdata['p']) / np.abs(subdata['p'])
+                        ]
+                    )
+                failures = subdata2[
+                  (subdata2['relerr'] >= rtol) |
+                  np.isnan(p)
+                ]
+                message = (f"cdf test {ix} failed with method '{default_method}'\n"
+                           f"{failures.dtype.names}\n{failures}")
+                assert_allclose(
+                    p,
+                    subdata['p'],
+                    rtol,
+                    err_msg=message,
+                    verbose=False
+                )
+
+    @pytest.mark.parametrize("param", [0, 1])
+    @pytest.mark.parametrize("case", ["pdf", "cdf"])
+    def test_location_scale(
+            self, nolan_loc_scale_sample_data, param, case
+    ):
+        """Tests for pdf and cdf where loc, scale are different from 0, 1
+        """
+
+        uname = platform.uname()
+        is_linux_32 = uname.system == 'Linux' and "32bit" in platform.architecture()[0]
+        # Test seems to be unstable (see gh-17839 for a bug report on Debian
+        # i386), so skip it.
+        if is_linux_32 and case == 'pdf':
+            pytest.skip("Test unstable on some platforms; see gh-17839, 17859")
+
+        data = nolan_loc_scale_sample_data
+        # We only test against piecewise as location/scale transforms
+        # are same for other methods.
+        stats.levy_stable.cdf_default_method = "piecewise"
+        stats.levy_stable.pdf_default_method = "piecewise"
+
+        subdata = data[data["param"] == param]
+        stats.levy_stable.parameterization = f"S{param}"
+
+        assert case in ["pdf", "cdf"]
+        function = (
+            stats.levy_stable.pdf if case == "pdf" else stats.levy_stable.cdf
+        )
+
+        v1 = function(
+            subdata['x'], subdata['alpha'], subdata['beta'], scale=2, loc=3
+        )
+        assert_allclose(v1, subdata[case], 1e-5)
+
+    @pytest.mark.parametrize(
+        "method,decimal_places",
+        [
+            ['dni', 4],
+            ['piecewise', 4],
+        ]
+    )
+    def test_pdf_alpha_equals_one_beta_non_zero(self, method, decimal_places):
+        """ sample points extracted from Tables and Graphs of Stable
+        Probability Density Functions - Donald R Holt - 1973 - p 187.
+        """
+        xs = np.array(
+            [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
+        )
+        density = np.array(
+            [
+                .3183, .3096, .2925, .2622, .1591, .1587, .1599, .1635, .0637,
+                .0729, .0812, .0955, .0318, .0390, .0458, .0586, .0187, .0236,
+                .0285, .0384
+            ]
+        )
+        betas = np.array(
+            [
+                0, .25, .5, 1, 0, .25, .5, 1, 0, .25, .5, 1, 0, .25, .5, 1, 0,
+                .25, .5, 1
+            ]
+        )
+        with np.errstate(all='ignore'), suppress_warnings() as sup:
+            sup.filter(
+                category=RuntimeWarning,
+                message="Density calculation unstable.*"
+            )
+            stats.levy_stable.pdf_default_method = method
+            # stats.levy_stable.fft_grid_spacing = 0.0001
+            pdf = stats.levy_stable.pdf(xs, 1, betas, scale=1, loc=0)
+            assert_almost_equal(
+                pdf, density, decimal_places, method
+            )
+
+    @pytest.mark.parametrize(
+        "params,expected",
+        [
+            [(1.48, -.22, 0, 1), (0, np.inf, np.nan, np.nan)],
+            [(2, .9, 10, 1.5), (10, 4.5, 0, 0)]
+        ]
+    )
+    def test_stats(self, params, expected):
+        observed = stats.levy_stable.stats(
+            params[0], params[1], loc=params[2], scale=params[3],
+            moments='mvsk'
+        )
+        assert_almost_equal(observed, expected)
+
+    @pytest.mark.parametrize('alpha', [0.25, 0.5, 0.75])
+    @pytest.mark.parametrize(
+        'function,beta,points,expected',
+        [
+            (
+                stats.levy_stable.cdf,
+                1.0,
+                np.linspace(-25, 0, 10),
+                0.0,
+            ),
+            (
+                stats.levy_stable.pdf,
+                1.0,
+                np.linspace(-25, 0, 10),
+                0.0,
+            ),
+            (
+                stats.levy_stable.cdf,
+                -1.0,
+                np.linspace(0, 25, 10),
+                1.0,
+            ),
+            (
+                stats.levy_stable.pdf,
+                -1.0,
+                np.linspace(0, 25, 10),
+                0.0,
+            )
+        ]
+    )
+    def test_distribution_outside_support(
+            self, alpha, function, beta, points, expected
+    ):
+        """Ensure the pdf/cdf routines do not return nan outside support.
+
+        This distribution's support becomes truncated in a few special cases:
+            support is [mu, infty) if alpha < 1 and beta = 1
+            support is (-infty, mu] if alpha < 1 and beta = -1
+        Otherwise, the support is all reals. Here, mu is zero by default.
+        """
+        assert 0 < alpha < 1
+        assert_almost_equal(
+            function(points, alpha=alpha, beta=beta),
+            np.full(len(points), expected)
+        )
+
+    @pytest.mark.parametrize(
+        'x,alpha,beta,expected',
+        # Reference values from Matlab
+        # format long
+        # alphas = [1.7720732804618808, 1.9217001522410235, 1.5654806051633634,
+        #           1.7420803447784388, 1.5748002527689913];
+        # betas = [0.5059373136902996, -0.8779442746685926, -0.4016220341911392,
+        #          -0.38180029468259247, -0.25200194914153684];
+        # x0s = [0, 1e-4, -1e-4];
+        # for x0 = x0s
+        #     disp("x0 = " + x0)
+        #     for ii = 1:5
+        #         alpha = alphas(ii);
+        #         beta = betas(ii);
+        #         pd = makedist('Stable','alpha',alpha,'beta',beta,'gam',1,'delta',0);
+        #         % we need to adjust x. It is the same as x = 0 In scipy.
+        #         x = x0 - beta * tan(pi * alpha / 2);
+        #         disp(pd.pdf(x))
+        #     end
+        # end
+        [
+            (0, 1.7720732804618808, 0.5059373136902996, 0.278932636798268),
+            (0, 1.9217001522410235, -0.8779442746685926, 0.281054757202316),
+            (0, 1.5654806051633634, -0.4016220341911392, 0.271282133194204),
+            (0, 1.7420803447784388, -0.38180029468259247, 0.280202199244247),
+            (0, 1.5748002527689913, -0.25200194914153684, 0.280136576218665),
+        ]
+    )
+    def test_x_equal_zeta(
+            self, x, alpha, beta, expected
+    ):
+        """Test pdf for x equal to zeta.
+
+        With S1 parametrization: x0 = x + zeta if alpha != 1 So, for x = 0, x0
+        will be close to zeta.
+
+        When case "x equal zeta" is not handled properly and quad_eps is not
+        low enough: - pdf may be less than 0 - logpdf is nan
+
+        The points from the parametrize block are found randomly so that PDF is
+        less than 0.
+
+        Reference values taken from MATLAB
+        https://www.mathworks.com/help/stats/stable-distribution.html
+        """
+        stats.levy_stable.quad_eps = 1.2e-11
+
+        assert_almost_equal(
+            stats.levy_stable.pdf(x, alpha=alpha, beta=beta),
+            expected,
+        )
+
+    @pytest.mark.xfail
+    @pytest.mark.parametrize(
+        # See comment for test_x_equal_zeta for script for reference values
+        'x,alpha,beta,expected',
+        [
+            (1e-4, 1.7720732804618808, 0.5059373136902996, 0.278929165340670),
+            (1e-4, 1.9217001522410235, -0.8779442746685926, 0.281056564327953),
+            (1e-4, 1.5654806051633634, -0.4016220341911392, 0.271252432161167),
+            (1e-4, 1.7420803447784388, -0.38180029468259247, 0.280205311264134),
+            (1e-4, 1.5748002527689913, -0.25200194914153684, 0.280140965235426),
+            (-1e-4, 1.7720732804618808, 0.5059373136902996, 0.278936106741754),
+            (-1e-4, 1.9217001522410235, -0.8779442746685926, 0.281052948629429),
+            (-1e-4, 1.5654806051633634, -0.4016220341911392, 0.271275394392385),
+            (-1e-4, 1.7420803447784388, -0.38180029468259247, 0.280199085645099),
+            (-1e-4, 1.5748002527689913, -0.25200194914153684, 0.280132185432842),
+        ]
+    )
+    def test_x_near_zeta(
+            self, x, alpha, beta, expected
+    ):
+        """Test pdf for x near zeta.
+
+        With S1 parametrization: x0 = x + zeta if alpha != 1 So, for x = 0, x0
+        will be close to zeta.
+
+        When case "x near zeta" is not handled properly and quad_eps is not
+        low enough: - pdf may be less than 0 - logpdf is nan
+
+        The points from the parametrize block are found randomly so that PDF is
+        less than 0.
+
+        Reference values taken from MATLAB
+        https://www.mathworks.com/help/stats/stable-distribution.html
+        """
+        stats.levy_stable.quad_eps = 1.2e-11
+
+        assert_almost_equal(
+            stats.levy_stable.pdf(x, alpha=alpha, beta=beta),
+            expected,
+        )
+
+    def test_frozen_parameterization_gh20821(self):
+        # gh-20821 reported that frozen distributions ignore the parameterization.
+        # Check that this is resolved and that the frozen distribution's
+        # parameterization can be changed independently of stats.levy_stable
+        rng = np.random.default_rng
+        shapes = dict(alpha=1.9, beta=0.1, loc=0.0, scale=1.0)
+        unfrozen = stats.levy_stable
+        frozen = stats.levy_stable(**shapes)
+
+        unfrozen.parameterization = "S0"
+        frozen.parameterization = "S1"
+        unfrozen_a = unfrozen.rvs(**shapes, size=10, random_state=rng(329823498))
+        frozen_a = frozen.rvs(size=10, random_state=rng(329823498))
+        assert not np.any(frozen_a == unfrozen_a)
+
+        unfrozen.parameterization = "S1"
+        frozen.parameterization = "S0"
+        unfrozen_b = unfrozen.rvs(**shapes, size=10, random_state=rng(329823498))
+        frozen_b = frozen.rvs(size=10, random_state=rng(329823498))
+        assert_equal(frozen_b, unfrozen_a)
+        assert_equal(unfrozen_b, frozen_a)
+
+    def test_frozen_parameterization_gh20821b(self):
+        # Check that the parameterization of the frozen distribution is that of
+        # the unfrozen distribution at the time of freezing
+        rng = np.random.default_rng
+        shapes = dict(alpha=1.9, beta=0.1, loc=0.0, scale=1.0)
+        unfrozen = stats.levy_stable
+
+        unfrozen.parameterization = "S0"
+        frozen = stats.levy_stable(**shapes)
+        unfrozen_a = unfrozen.rvs(**shapes, size=10, random_state=rng(329823498))
+        frozen_a = frozen.rvs(size=10, random_state=rng(329823498))
+        assert_equal(frozen_a, unfrozen_a)
+
+        unfrozen.parameterization = "S1"
+        frozen = stats.levy_stable(**shapes)
+        unfrozen_b = unfrozen.rvs(**shapes, size=10, random_state=rng(329823498))
+        frozen_b = frozen.rvs(size=10, random_state=rng(329823498))
+        assert_equal(frozen_b, unfrozen_b)
+
+
+class TestArrayArgument:  # test for ticket:992
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_noexception(self):
+        rvs = stats.norm.rvs(loc=(np.arange(5)), scale=np.ones(5),
+                             size=(10, 5))
+        assert_equal(rvs.shape, (10, 5))
+
+
+class TestDocstring:
+    def test_docstrings(self):
+        # See ticket #761
+        if stats.rayleigh.__doc__ is not None:
+            assert_("rayleigh" in stats.rayleigh.__doc__.lower())
+        if stats.bernoulli.__doc__ is not None:
+            assert_("bernoulli" in stats.bernoulli.__doc__.lower())
+
+    def test_no_name_arg(self):
+        # If name is not given, construction shouldn't fail.  See #1508.
+        stats.rv_continuous()
+        stats.rv_discrete()
+
+
+def test_args_reduce():
+    a = array([1, 3, 2, 1, 2, 3, 3])
+    b, c = argsreduce(a > 1, a, 2)
+
+    assert_array_equal(b, [3, 2, 2, 3, 3])
+    assert_array_equal(c, [2])
+
+    b, c = argsreduce(2 > 1, a, 2)
+    assert_array_equal(b, a)
+    assert_array_equal(c, [2] * np.size(a))
+
+    b, c = argsreduce(a > 0, a, 2)
+    assert_array_equal(b, a)
+    assert_array_equal(c, [2] * np.size(a))
+
+
+class TestFitMethod:
+    # fitting assumes continuous parameters
+    skip = ['ncf', 'ksone', 'kstwo', 'irwinhall']
+
+    def setup_method(self):
+        np.random.seed(1234)
+
+    # skip these b/c deprecated, or only loc and scale arguments
+    fitSkipNonFinite = ['expon', 'norm', 'uniform', 'irwinhall']
+
+    @pytest.mark.parametrize('dist,args', distcont)
+    def test_fit_w_non_finite_data_values(self, dist, args):
+        """gh-10300"""
+        if dist in self.fitSkipNonFinite:
+            pytest.skip(f"{dist} fit known to fail or deprecated")
+        x = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.nan])
+        y = np.array([1.6483, 2.7169, 2.4667, 1.1791, 3.5433, np.inf])
+        distfunc = getattr(stats, dist)
+        assert_raises(ValueError, distfunc.fit, x, fscale=1)
+        assert_raises(ValueError, distfunc.fit, y, fscale=1)
+
+    def test_fix_fit_2args_lognorm(self):
+        # Regression test for #1551.
+        np.random.seed(12345)
+        with np.errstate(all='ignore'):
+            x = stats.lognorm.rvs(0.25, 0., 20.0, size=20)
+            expected_shape = np.sqrt(((np.log(x) - np.log(20))**2).mean())
+            assert_allclose(np.array(stats.lognorm.fit(x, floc=0, fscale=20)),
+                            [expected_shape, 0, 20], atol=1e-8)
+
+    def test_fix_fit_norm(self):
+        x = np.arange(1, 6)
+
+        loc, scale = stats.norm.fit(x)
+        assert_almost_equal(loc, 3)
+        assert_almost_equal(scale, np.sqrt(2))
+
+        loc, scale = stats.norm.fit(x, floc=2)
+        assert_equal(loc, 2)
+        assert_equal(scale, np.sqrt(3))
+
+        loc, scale = stats.norm.fit(x, fscale=2)
+        assert_almost_equal(loc, 3)
+        assert_equal(scale, 2)
+
+    def test_fix_fit_gamma(self):
+        x = np.arange(1, 6)
+        meanlog = np.log(x).mean()
+
+        # A basic test of gamma.fit with floc=0.
+        floc = 0
+        a, loc, scale = stats.gamma.fit(x, floc=floc)
+        s = np.log(x.mean()) - meanlog
+        assert_almost_equal(np.log(a) - special.digamma(a), s, decimal=5)
+        assert_equal(loc, floc)
+        assert_almost_equal(scale, x.mean()/a, decimal=8)
+
+        # Regression tests for gh-2514.
+        # The problem was that if `floc=0` was given, any other fixed
+        # parameters were ignored.
+        f0 = 1
+        floc = 0
+        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
+        assert_equal(a, f0)
+        assert_equal(loc, floc)
+        assert_almost_equal(scale, x.mean()/a, decimal=8)
+
+        f0 = 2
+        floc = 0
+        a, loc, scale = stats.gamma.fit(x, f0=f0, floc=floc)
+        assert_equal(a, f0)
+        assert_equal(loc, floc)
+        assert_almost_equal(scale, x.mean()/a, decimal=8)
+
+        # loc and scale fixed.
+        floc = 0
+        fscale = 2
+        a, loc, scale = stats.gamma.fit(x, floc=floc, fscale=fscale)
+        assert_equal(loc, floc)
+        assert_equal(scale, fscale)
+        c = meanlog - np.log(fscale)
+        assert_almost_equal(special.digamma(a), c)
+
+    def test_fix_fit_beta(self):
+        # Test beta.fit when both floc and fscale are given.
+
+        def mlefunc(a, b, x):
+            # Zeros of this function are critical points of
+            # the maximum likelihood function.
+            n = len(x)
+            s1 = np.log(x).sum()
+            s2 = np.log(1-x).sum()
+            psiab = special.psi(a + b)
+            func = [s1 - n * (-psiab + special.psi(a)),
+                    s2 - n * (-psiab + special.psi(b))]
+            return func
+
+        # Basic test with floc and fscale given.
+        x = np.array([0.125, 0.25, 0.5])
+        a, b, loc, scale = stats.beta.fit(x, floc=0, fscale=1)
+        assert_equal(loc, 0)
+        assert_equal(scale, 1)
+        assert_allclose(mlefunc(a, b, x), [0, 0], atol=1e-6)
+
+        # Basic test with f0, floc and fscale given.
+        # This is also a regression test for gh-2514.
+        x = np.array([0.125, 0.25, 0.5])
+        a, b, loc, scale = stats.beta.fit(x, f0=2, floc=0, fscale=1)
+        assert_equal(a, 2)
+        assert_equal(loc, 0)
+        assert_equal(scale, 1)
+        da, db = mlefunc(a, b, x)
+        assert_allclose(db, 0, atol=1e-5)
+
+        # Same floc and fscale values as above, but reverse the data
+        # and fix b (f1).
+        x2 = 1 - x
+        a2, b2, loc2, scale2 = stats.beta.fit(x2, f1=2, floc=0, fscale=1)
+        assert_equal(b2, 2)
+        assert_equal(loc2, 0)
+        assert_equal(scale2, 1)
+        da, db = mlefunc(a2, b2, x2)
+        assert_allclose(da, 0, atol=1e-5)
+        # a2 of this test should equal b from above.
+        assert_almost_equal(a2, b)
+
+        # Check for detection of data out of bounds when floc and fscale
+        # are given.
+        assert_raises(ValueError, stats.beta.fit, x, floc=0.5, fscale=1)
+        y = np.array([0, .5, 1])
+        assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1)
+        assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1, f0=2)
+        assert_raises(ValueError, stats.beta.fit, y, floc=0, fscale=1, f1=2)
+
+        # Check that attempting to fix all the parameters raises a ValueError.
+        assert_raises(ValueError, stats.beta.fit, y, f0=0, f1=1,
+                      floc=2, fscale=3)
+
+    def test_expon_fit(self):
+        x = np.array([2, 2, 4, 4, 4, 4, 4, 8])
+
+        loc, scale = stats.expon.fit(x)
+        assert_equal(loc, 2)    # x.min()
+        assert_equal(scale, 2)  # x.mean() - x.min()
+
+        loc, scale = stats.expon.fit(x, fscale=3)
+        assert_equal(loc, 2)    # x.min()
+        assert_equal(scale, 3)  # fscale
+
+        loc, scale = stats.expon.fit(x, floc=0)
+        assert_equal(loc, 0)    # floc
+        assert_equal(scale, 4)  # x.mean() - loc
+
+    def test_lognorm_fit(self):
+        x = np.array([1.5, 3, 10, 15, 23, 59])
+        lnxm1 = np.log(x - 1)
+
+        shape, loc, scale = stats.lognorm.fit(x, floc=1)
+        assert_allclose(shape, lnxm1.std(), rtol=1e-12)
+        assert_equal(loc, 1)
+        assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12)
+
+        shape, loc, scale = stats.lognorm.fit(x, floc=1, fscale=6)
+        assert_allclose(shape, np.sqrt(((lnxm1 - np.log(6))**2).mean()),
+                        rtol=1e-12)
+        assert_equal(loc, 1)
+        assert_equal(scale, 6)
+
+        shape, loc, scale = stats.lognorm.fit(x, floc=1, fix_s=0.75)
+        assert_equal(shape, 0.75)
+        assert_equal(loc, 1)
+        assert_allclose(scale, np.exp(lnxm1.mean()), rtol=1e-12)
+
+    def test_uniform_fit(self):
+        x = np.array([1.0, 1.1, 1.2, 9.0])
+
+        loc, scale = stats.uniform.fit(x)
+        assert_equal(loc, x.min())
+        assert_equal(scale, np.ptp(x))
+
+        loc, scale = stats.uniform.fit(x, floc=0)
+        assert_equal(loc, 0)
+        assert_equal(scale, x.max())
+
+        loc, scale = stats.uniform.fit(x, fscale=10)
+        assert_equal(loc, 0)
+        assert_equal(scale, 10)
+
+        assert_raises(ValueError, stats.uniform.fit, x, floc=2.0)
+        assert_raises(ValueError, stats.uniform.fit, x, fscale=5.0)
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize("method", ["MLE", "MM"])
+    def test_fshapes(self, method):
+        # take a beta distribution, with shapes='a, b', and make sure that
+        # fa is equivalent to f0, and fb is equivalent to f1
+        a, b = 3., 4.
+        x = stats.beta.rvs(a, b, size=100, random_state=1234)
+        res_1 = stats.beta.fit(x, f0=3., method=method)
+        res_2 = stats.beta.fit(x, fa=3., method=method)
+        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)
+
+        res_2 = stats.beta.fit(x, fix_a=3., method=method)
+        assert_allclose(res_1, res_2, atol=1e-12, rtol=1e-12)
+
+        res_3 = stats.beta.fit(x, f1=4., method=method)
+        res_4 = stats.beta.fit(x, fb=4., method=method)
+        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)
+
+        res_4 = stats.beta.fit(x, fix_b=4., method=method)
+        assert_allclose(res_3, res_4, atol=1e-12, rtol=1e-12)
+
+        # cannot specify both positional and named args at the same time
+        assert_raises(ValueError, stats.beta.fit, x, fa=1, f0=2, method=method)
+
+        # check that attempting to fix all parameters raises a ValueError
+        assert_raises(ValueError, stats.beta.fit, x, fa=0, f1=1,
+                      floc=2, fscale=3, method=method)
+
+        # check that specifying floc, fscale and fshapes works for
+        # beta and gamma which override the generic fit method
+        res_5 = stats.beta.fit(x, fa=3., floc=0, fscale=1, method=method)
+        aa, bb, ll, ss = res_5
+        assert_equal([aa, ll, ss], [3., 0, 1])
+
+        # gamma distribution
+        a = 3.
+        data = stats.gamma.rvs(a, size=100)
+        aa, ll, ss = stats.gamma.fit(data, fa=a, method=method)
+        assert_equal(aa, a)
+
+    @pytest.mark.parametrize("method", ["MLE", "MM"])
+    def test_extra_params(self, method):
+        # unknown parameters should raise rather than be silently ignored
+        dist = stats.exponnorm
+        data = dist.rvs(K=2, size=100)
+        dct = dict(enikibeniki=-101)
+        assert_raises(TypeError, dist.fit, data, **dct, method=method)
+
+
+class TestFrozen:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    # Test that a frozen distribution gives the same results as the original
+    # object.
+    #
+    # Only tested for the normal distribution (with loc and scale specified)
+    # and for the gamma distribution (with a shape parameter specified).
+    def test_norm(self):
+        dist = stats.norm
+        frozen = stats.norm(loc=10.0, scale=3.0)
+
+        result_f = frozen.pdf(20.0)
+        result = dist.pdf(20.0, loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.cdf(20.0)
+        result = dist.cdf(20.0, loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.ppf(0.25)
+        result = dist.ppf(0.25, loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.isf(0.25)
+        result = dist.isf(0.25, loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.sf(10.0)
+        result = dist.sf(10.0, loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.median()
+        result = dist.median(loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.mean()
+        result = dist.mean(loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.var()
+        result = dist.var(loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.std()
+        result = dist.std(loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.entropy()
+        result = dist.entropy(loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        result_f = frozen.moment(2)
+        result = dist.moment(2, loc=10.0, scale=3.0)
+        assert_equal(result_f, result)
+
+        assert_equal(frozen.a, dist.a)
+        assert_equal(frozen.b, dist.b)
+
+    def test_gamma(self):
+        a = 2.0
+        dist = stats.gamma
+        frozen = stats.gamma(a)
+
+        result_f = frozen.pdf(20.0)
+        result = dist.pdf(20.0, a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.cdf(20.0)
+        result = dist.cdf(20.0, a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.ppf(0.25)
+        result = dist.ppf(0.25, a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.isf(0.25)
+        result = dist.isf(0.25, a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.sf(10.0)
+        result = dist.sf(10.0, a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.median()
+        result = dist.median(a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.mean()
+        result = dist.mean(a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.var()
+        result = dist.var(a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.std()
+        result = dist.std(a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.entropy()
+        result = dist.entropy(a)
+        assert_equal(result_f, result)
+
+        result_f = frozen.moment(2)
+        result = dist.moment(2, a)
+        assert_equal(result_f, result)
+
+        assert_equal(frozen.a, frozen.dist.a)
+        assert_equal(frozen.b, frozen.dist.b)
+
+    def test_regression_ticket_1293(self):
+        # Create a frozen distribution.
+        frozen = stats.lognorm(1)
+        # Call one of its methods that does not take any keyword arguments.
+        m1 = frozen.moment(2)
+        # Now call a method that takes a keyword argument.
+        frozen.stats(moments='mvsk')
+        # Call moment(2) again.
+        # After calling stats(), the following was raising an exception.
+        # So this test passes if the following does not raise an exception.
+        m2 = frozen.moment(2)
+        # The following should also be true, of course.  But it is not
+        # the focus of this test.
+        assert_equal(m1, m2)
+
+    def test_ab(self):
+        # test that the support of a frozen distribution
+        # (i) remains frozen even if it changes for the original one
+        # (ii) is actually correct if the shape parameters are such that
+        #      the values of [a, b] are not the default [0, inf]
+        # take a genpareto as an example where the support
+        # depends on the value of the shape parameter:
+        # for c > 0: a, b = 0, inf
+        # for c < 0: a, b = 0, -1/c
+
+        c = -0.1
+        rv = stats.genpareto(c=c)
+        a, b = rv.dist._get_support(c)
+        assert_equal([a, b], [0., 10.])
+
+        c = 0.1
+        stats.genpareto.pdf(0, c=c)
+        assert_equal(rv.dist._get_support(c), [0, np.inf])
+
+        c = -0.1
+        rv = stats.genpareto(c=c)
+        a, b = rv.dist._get_support(c)
+        assert_equal([a, b], [0., 10.])
+
+        c = 0.1
+        stats.genpareto.pdf(0, c)  # this should NOT change genpareto.b
+        assert_equal((rv.dist.a, rv.dist.b), stats.genpareto._get_support(c))
+
+        rv1 = stats.genpareto(c=0.1)
+        assert_(rv1.dist is not rv.dist)
+
+        # c >= 0: a, b = [0, inf]
+        for c in [1., 0.]:
+            c = np.asarray(c)
+            rv = stats.genpareto(c=c)
+            a, b = rv.a, rv.b
+            assert_equal(a, 0.)
+            assert_(np.isposinf(b))
+
+            # c < 0: a=0, b=1/|c|
+            c = np.asarray(-2.)
+            a, b = stats.genpareto._get_support(c)
+            assert_allclose([a, b], [0., 0.5])
+
+    def test_rv_frozen_in_namespace(self):
+        # Regression test for gh-3522
+        assert_(hasattr(stats.distributions, 'rv_frozen'))
+
+    def test_random_state(self):
+        # only check that the random_state attribute exists,
+        frozen = stats.norm()
+        assert_(hasattr(frozen, 'random_state'))
+
+        # ... that it can be set,
+        frozen.random_state = 42
+        assert_equal(frozen.random_state.get_state(),
+                     np.random.RandomState(42).get_state())
+
+        # ... and that .rvs method accepts it as an argument
+        rndm = np.random.RandomState(1234)
+        frozen.rvs(size=8, random_state=rndm)
+
+    def test_pickling(self):
+        # test that a frozen instance pickles and unpickles
+        # (this method is a clone of common_tests.check_pickling)
+        beta = stats.beta(2.3098496451481823, 0.62687954300963677)
+        poiss = stats.poisson(3.)
+        sample = stats.rv_discrete(values=([0, 1, 2, 3],
+                                           [0.1, 0.2, 0.3, 0.4]))
+
+        for distfn in [beta, poiss, sample]:
+            distfn.random_state = 1234
+            distfn.rvs(size=8)
+            s = pickle.dumps(distfn)
+            r0 = distfn.rvs(size=8)
+
+            unpickled = pickle.loads(s)
+            r1 = unpickled.rvs(size=8)
+            assert_equal(r0, r1)
+
+            # also smoke test some methods
+            medians = [distfn.ppf(0.5), unpickled.ppf(0.5)]
+            assert_equal(medians[0], medians[1])
+            assert_equal(distfn.cdf(medians[0]),
+                         unpickled.cdf(medians[1]))
+
+    def test_expect(self):
+        # smoke test the expect method of the frozen distribution
+        # only take a gamma w/loc and scale and poisson with loc specified
+        def func(x):
+            return x
+
+        gm = stats.gamma(a=2, loc=3, scale=4)
+        with np.errstate(invalid="ignore", divide="ignore"):
+            gm_val = gm.expect(func, lb=1, ub=2, conditional=True)
+            gamma_val = stats.gamma.expect(func, args=(2,), loc=3, scale=4,
+                                           lb=1, ub=2, conditional=True)
+        assert_allclose(gm_val, gamma_val)
+
+        p = stats.poisson(3, loc=4)
+        p_val = p.expect(func)
+        poisson_val = stats.poisson.expect(func, args=(3,), loc=4)
+        assert_allclose(p_val, poisson_val)
+
+
+class TestExpect:
+    # Test for expect method.
+    #
+    # Uses normal distribution and beta distribution for finite bounds, and
+    # hypergeom for discrete distribution with finite support
+    def test_norm(self):
+        v = stats.norm.expect(lambda x: (x-5)*(x-5), loc=5, scale=2)
+        assert_almost_equal(v, 4, decimal=14)
+
+        m = stats.norm.expect(lambda x: (x), loc=5, scale=2)
+        assert_almost_equal(m, 5, decimal=14)
+
+        lb = stats.norm.ppf(0.05, loc=5, scale=2)
+        ub = stats.norm.ppf(0.95, loc=5, scale=2)
+        prob90 = stats.norm.expect(lambda x: 1, loc=5, scale=2, lb=lb, ub=ub)
+        assert_almost_equal(prob90, 0.9, decimal=14)
+
+        prob90c = stats.norm.expect(lambda x: 1, loc=5, scale=2, lb=lb, ub=ub,
+                                    conditional=True)
+        assert_almost_equal(prob90c, 1., decimal=14)
+
+    def test_beta(self):
+        # case with finite support interval
+        v = stats.beta.expect(lambda x: (x-19/3.)*(x-19/3.), args=(10, 5),
+                              loc=5, scale=2)
+        assert_almost_equal(v, 1./18., decimal=13)
+
+        m = stats.beta.expect(lambda x: x, args=(10, 5), loc=5., scale=2.)
+        assert_almost_equal(m, 19/3., decimal=13)
+
+        ub = stats.beta.ppf(0.95, 10, 10, loc=5, scale=2)
+        lb = stats.beta.ppf(0.05, 10, 10, loc=5, scale=2)
+        prob90 = stats.beta.expect(lambda x: 1., args=(10, 10), loc=5.,
+                                   scale=2., lb=lb, ub=ub, conditional=False)
+        assert_almost_equal(prob90, 0.9, decimal=13)
+
+        prob90c = stats.beta.expect(lambda x: 1, args=(10, 10), loc=5,
+                                    scale=2, lb=lb, ub=ub, conditional=True)
+        assert_almost_equal(prob90c, 1., decimal=13)
+
+    def test_hypergeom(self):
+        # test case with finite bounds
+
+        # without specifying bounds
+        m_true, v_true = stats.hypergeom.stats(20, 10, 8, loc=5.)
+        m = stats.hypergeom.expect(lambda x: x, args=(20, 10, 8), loc=5.)
+        assert_almost_equal(m, m_true, decimal=13)
+
+        v = stats.hypergeom.expect(lambda x: (x-9.)**2, args=(20, 10, 8),
+                                   loc=5.)
+        assert_almost_equal(v, v_true, decimal=14)
+
+        # with bounds, bounds equal to shifted support
+        v_bounds = stats.hypergeom.expect(lambda x: (x-9.)**2,
+                                          args=(20, 10, 8),
+                                          loc=5., lb=5, ub=13)
+        assert_almost_equal(v_bounds, v_true, decimal=14)
+
+        # drop boundary points
+        prob_true = 1-stats.hypergeom.pmf([5, 13], 20, 10, 8, loc=5).sum()
+        prob_bounds = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8),
+                                             loc=5., lb=6, ub=12)
+        assert_almost_equal(prob_bounds, prob_true, decimal=13)
+
+        # conditional
+        prob_bc = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8), loc=5.,
+                                         lb=6, ub=12, conditional=True)
+        assert_almost_equal(prob_bc, 1, decimal=14)
+
+        # check simple integral
+        prob_b = stats.hypergeom.expect(lambda x: 1, args=(20, 10, 8),
+                                        lb=0, ub=8)
+        assert_almost_equal(prob_b, 1, decimal=13)
+
+    def test_poisson(self):
+        # poisson, use lower bound only
+        prob_bounds = stats.poisson.expect(lambda x: 1, args=(2,), lb=3,
+                                           conditional=False)
+        prob_b_true = 1-stats.poisson.cdf(2, 2)
+        assert_almost_equal(prob_bounds, prob_b_true, decimal=14)
+
+        prob_lb = stats.poisson.expect(lambda x: 1, args=(2,), lb=2,
+                                       conditional=True)
+        assert_almost_equal(prob_lb, 1, decimal=14)
+
+    def test_genhalflogistic(self):
+        # genhalflogistic, changes upper bound of support in _argcheck
+        # regression test for gh-2622
+        halflog = stats.genhalflogistic
+        # check consistency when calling expect twice with the same input
+        res1 = halflog.expect(args=(1.5,))
+        halflog.expect(args=(0.5,))
+        res2 = halflog.expect(args=(1.5,))
+        assert_almost_equal(res1, res2, decimal=14)
+
+    def test_rice_overflow(self):
+        # rice.pdf(999, 0.74) was inf since special.i0 silently overflows
+        # check that using i0e fixes it
+        assert_(np.isfinite(stats.rice.pdf(999, 0.74)))
+
+        assert_(np.isfinite(stats.rice.expect(lambda x: 1, args=(0.74,))))
+        assert_(np.isfinite(stats.rice.expect(lambda x: 2, args=(0.74,))))
+        assert_(np.isfinite(stats.rice.expect(lambda x: 3, args=(0.74,))))
+
+    def test_logser(self):
+        # test a discrete distribution with infinite support and loc
+        p, loc = 0.3, 3
+        res_0 = stats.logser.expect(lambda k: k, args=(p,))
+        # check against the correct answer (sum of a geom series)
+        assert_allclose(res_0,
+                        p / (p - 1.) / np.log(1. - p), atol=1e-15)
+
+        # now check it with `loc`
+        res_l = stats.logser.expect(lambda k: k, args=(p,), loc=loc)
+        assert_allclose(res_l, res_0 + loc, atol=1e-15)
+
+    def test_skellam(self):
+        # Use a discrete distribution w/ bi-infinite support. Compute two first
+        # moments and compare to known values (cf skellam.stats)
+        p1, p2 = 18, 22
+        m1 = stats.skellam.expect(lambda x: x, args=(p1, p2))
+        m2 = stats.skellam.expect(lambda x: x**2, args=(p1, p2))
+        assert_allclose(m1, p1 - p2, atol=1e-12)
+        assert_allclose(m2 - m1**2, p1 + p2, atol=1e-12)
+
+    def test_randint(self):
+        # Use a discrete distribution w/ parameter-dependent support, which
+        # is larger than the default chunksize
+        lo, hi = 0, 113
+        res = stats.randint.expect(lambda x: x, (lo, hi))
+        assert_allclose(res,
+                        sum(_ for _ in range(lo, hi)) / (hi - lo), atol=1e-15)
+
+    def test_zipf(self):
+        # Test that there is no infinite loop even if the sum diverges
+        assert_warns(RuntimeWarning, stats.zipf.expect,
+                     lambda x: x**2, (2,))
+
+    def test_discrete_kwds(self):
+        # check that discrete expect accepts keywords to control the summation
+        n0 = stats.poisson.expect(lambda x: 1, args=(2,))
+        n1 = stats.poisson.expect(lambda x: 1, args=(2,),
+                                  maxcount=1001, chunksize=32, tolerance=1e-8)
+        assert_almost_equal(n0, n1, decimal=14)
+
+    def test_moment(self):
+        # test the .moment() method: compute a higher moment and compare to
+        # a known value
+        def poiss_moment5(mu):
+            return mu**5 + 10*mu**4 + 25*mu**3 + 15*mu**2 + mu
+
+        for mu in [5, 7]:
+            m5 = stats.poisson.moment(5, mu)
+            assert_allclose(m5, poiss_moment5(mu), rtol=1e-10)
+
+    def test_challenging_cases_gh8928(self):
+        # Several cases where `expect` failed to produce a correct result were
+        # reported in gh-8928. Check that these cases have been resolved.
+        assert_allclose(stats.norm.expect(loc=36, scale=1.0), 36)
+        assert_allclose(stats.norm.expect(loc=40, scale=1.0), 40)
+        assert_allclose(stats.norm.expect(loc=10, scale=0.1), 10)
+        assert_allclose(stats.gamma.expect(args=(148,)), 148)
+        assert_allclose(stats.logistic.expect(loc=85), 85)
+
+    def test_lb_ub_gh15855(self):
+        # Make sure changes to `expect` made in gh15855 treat lb/ub correctly
+        dist = stats.uniform
+        ref = dist.mean(loc=10, scale=5)  # 12.5
+        # moment over whole distribution
+        assert_allclose(dist.expect(loc=10, scale=5), ref)
+        # moment over whole distribution, lb and ub outside of support
+        assert_allclose(dist.expect(loc=10, scale=5, lb=9, ub=16), ref)
+        # moment over 60% of distribution, [lb, ub] centered within support
+        assert_allclose(dist.expect(loc=10, scale=5, lb=11, ub=14), ref*0.6)
+        # moment over truncated distribution, essentially
+        assert_allclose(dist.expect(loc=10, scale=5, lb=11, ub=14,
+                                    conditional=True), ref)
+        # moment over 40% of distribution, [lb, ub] not centered within support
+        assert_allclose(dist.expect(loc=10, scale=5, lb=11, ub=13), 12*0.4)
+        # moment with lb > ub
+        assert_allclose(dist.expect(loc=10, scale=5, lb=13, ub=11), -12*0.4)
+        # moment with lb > ub, conditional
+        assert_allclose(dist.expect(loc=10, scale=5, lb=13, ub=11,
+                                    conditional=True), 12)
+
+
+class TestNct:
+    def test_nc_parameter(self):
+        # Parameter values c<=0 were not enabled (gh-2402).
+        # For negative values c and for c=0 results of rv.cdf(0) below were nan
+        rv = stats.nct(5, 0)
+        assert_equal(rv.cdf(0), 0.5)
+        rv = stats.nct(5, -1)
+        assert_almost_equal(rv.cdf(0), 0.841344746069, decimal=10)
+
+    def test_broadcasting(self):
+        res = stats.nct.pdf(5, np.arange(4, 7)[:, None],
+                            np.linspace(0.1, 1, 4))
+        expected = array([[0.00321886, 0.00557466, 0.00918418, 0.01442997],
+                          [0.00217142, 0.00395366, 0.00683888, 0.01126276],
+                          [0.00153078, 0.00291093, 0.00525206, 0.00900815]])
+        assert_allclose(res, expected, rtol=1e-5)
+
+    def test_variance_gh_issue_2401(self):
+        # Computation of the variance of a non-central t-distribution resulted
+        # in a TypeError: ufunc 'isinf' not supported for the input types,
+        # and the inputs could not be safely coerced to any supported types
+        # according to the casting rule 'safe'
+        rv = stats.nct(4, 0)
+        assert_equal(rv.var(), 2.0)
+
+    def test_nct_inf_moments(self):
+        # n-th moment of nct only exists for df > n
+        m, v, s, k = stats.nct.stats(df=0.9, nc=0.3, moments='mvsk')
+        assert_equal([m, v, s, k], [np.nan, np.nan, np.nan, np.nan])
+
+        m, v, s, k = stats.nct.stats(df=1.9, nc=0.3, moments='mvsk')
+        assert_(np.isfinite(m))
+        assert_equal([v, s, k], [np.nan, np.nan, np.nan])
+
+        m, v, s, k = stats.nct.stats(df=3.1, nc=0.3, moments='mvsk')
+        assert_(np.isfinite([m, v, s]).all())
+        assert_equal(k, np.nan)
+
+    def test_nct_stats_large_df_values(self):
+        # previously gamma function was used which lost precision at df=345
+        # cf. https://github.com/scipy/scipy/issues/12919 for details
+        nct_mean_df_1000 = stats.nct.mean(1000, 2)
+        nct_stats_df_1000 = stats.nct.stats(1000, 2)
+        # These expected values were computed with mpmath. They were also
+        # verified with the Wolfram Alpha expressions:
+        #     Mean[NoncentralStudentTDistribution[1000, 2]]
+        #     Var[NoncentralStudentTDistribution[1000, 2]]
+        expected_stats_df_1000 = [2.0015015641422464, 1.0040115288163005]
+        assert_allclose(nct_mean_df_1000, expected_stats_df_1000[0],
+                        rtol=1e-10)
+        assert_allclose(nct_stats_df_1000, expected_stats_df_1000,
+                        rtol=1e-10)
+        # and a bigger df value
+        nct_mean = stats.nct.mean(100000, 2)
+        nct_stats = stats.nct.stats(100000, 2)
+        # These expected values were computed with mpmath.
+        expected_stats = [2.0000150001562518, 1.0000400011500288]
+        assert_allclose(nct_mean, expected_stats[0], rtol=1e-10)
+        assert_allclose(nct_stats, expected_stats, rtol=1e-9)
+
+    def test_cdf_large_nc(self):
+        # gh-17916 reported a crash with large `nc` values
+        assert_allclose(stats.nct.cdf(2, 2, float(2**16)), 0)
+
+    # PDF reference values were computed with mpmath
+    # with 100 digits of precision
+
+    # def nct_pdf(x, df, nc):
+    #     x = mp.mpf(x)
+    #     n = mp.mpf(df)
+    #     nc = mp.mpf(nc)
+
+    #     x2 = x*x
+    #     ncx2 = nc*nc*x2
+    #     fac1 = n + x2
+    #     trm1 = (n/2.*mp.log(n) + mp.loggamma(n + mp.one)
+    #             - (n * mp.log(2.) + nc*nc/2 + (n/2)*mp.log(fac1)
+    #                 + mp.loggamma(n/2)))
+    #     Px = mp.exp(trm1)
+    #     valF = ncx2 / (2*fac1)
+    #     trm1 = (mp.sqrt(2)*nc*x*mp.hyp1f1(n/2+1, 1.5, valF)
+    #             / (fac1*mp.gamma((n+1)/2)))
+    #     trm2 = (mp.hyp1f1((n+1)/2, 0.5, valF)
+    #             / (mp.sqrt(fac1)*mp.gamma(n/2 + mp.one)))
+    #     Px *= trm1+trm2
+    #     return float(Px)
+
+    @pytest.mark.parametrize("x, df, nc, expected", [
+        (10000, 10, 16, 3.394646922945872e-30),
+        (-10, 8, 16, 4.282769500264159e-70)
+        ])
+    def test_pdf_large_nc(self, x, df, nc, expected):
+        # gh-#20693 reported zero values for large `nc` values
+        assert_allclose(stats.nct.pdf(x, df, nc), expected, rtol=1e-12)
+
+
+class TestRecipInvGauss:
+
+    def test_pdf_endpoint(self):
+        p = stats.recipinvgauss.pdf(0, 0.6)
+        assert p == 0.0
+
+    def test_logpdf_endpoint(self):
+        logp = stats.recipinvgauss.logpdf(0, 0.6)
+        assert logp == -np.inf
+
+    def test_cdf_small_x(self):
+        # The expected value was computer with mpmath:
+        #
+        # import mpmath
+        #
+        # mpmath.mp.dps = 100
+        #
+        # def recipinvgauss_cdf_mp(x, mu):
+        #     x = mpmath.mpf(x)
+        #     mu = mpmath.mpf(mu)
+        #     trm1 = 1/mu - x
+        #     trm2 = 1/mu + x
+        #     isqx = 1/mpmath.sqrt(x)
+        #     return (mpmath.ncdf(-isqx*trm1)
+        #             - mpmath.exp(2/mu)*mpmath.ncdf(-isqx*trm2))
+        #
+        p = stats.recipinvgauss.cdf(0.05, 0.5)
+        expected = 6.590396159501331e-20
+        assert_allclose(p, expected, rtol=1e-14)
+
+    def test_sf_large_x(self):
+        # The expected value was computed with mpmath; see test_cdf_small.
+        p = stats.recipinvgauss.sf(80, 0.5)
+        expected = 2.699819200556787e-18
+        assert_allclose(p, expected, 5e-15)
+
+
+class TestRice:
+    def test_rice_zero_b(self):
+        # rice distribution should work with b=0, cf gh-2164
+        x = [0.2, 1., 5.]
+        assert_(np.isfinite(stats.rice.pdf(x, b=0.)).all())
+        assert_(np.isfinite(stats.rice.logpdf(x, b=0.)).all())
+        assert_(np.isfinite(stats.rice.cdf(x, b=0.)).all())
+        assert_(np.isfinite(stats.rice.logcdf(x, b=0.)).all())
+
+        q = [0.1, 0.1, 0.5, 0.9]
+        assert_(np.isfinite(stats.rice.ppf(q, b=0.)).all())
+
+        mvsk = stats.rice.stats(0, moments='mvsk')
+        assert_(np.isfinite(mvsk).all())
+
+        # furthermore, pdf is continuous as b\to 0
+        # rice.pdf(x, b\to 0) = x exp(-x^2/2) + O(b^2)
+        # see e.g. Abramovich & Stegun 9.6.7 & 9.6.10
+        b = 1e-8
+        assert_allclose(stats.rice.pdf(x, 0), stats.rice.pdf(x, b),
+                        atol=b, rtol=0)
+
+    def test_rice_rvs(self):
+        rvs = stats.rice.rvs
+        assert_equal(rvs(b=3.).size, 1)
+        assert_equal(rvs(b=3., size=(3, 5)).shape, (3, 5))
+
+    def test_rice_gh9836(self):
+        # test that gh-9836 is resolved; previously jumped to 1 at the end
+
+        cdf = stats.rice.cdf(np.arange(10, 160, 10), np.arange(10, 160, 10))
+        # Generated in R
+        # library(VGAM)
+        # options(digits=16)
+        # x = seq(10, 150, 10)
+        # print(price(x, sigma=1, vee=x))
+        cdf_exp = [0.4800278103504522, 0.4900233218590353, 0.4933500379379548,
+                   0.4950128317658719, 0.4960103776798502, 0.4966753655438764,
+                   0.4971503395812474, 0.4975065620443196, 0.4977836197921638,
+                   0.4980052636649550, 0.4981866072661382, 0.4983377260666599,
+                   0.4984655952615694, 0.4985751970541413, 0.4986701850071265]
+        assert_allclose(cdf, cdf_exp)
+
+        probabilities = np.arange(0.1, 1, 0.1)
+        ppf = stats.rice.ppf(probabilities, 500/4, scale=4)
+        # Generated in R
+        # library(VGAM)
+        # options(digits=16)
+        # p = seq(0.1, .9, by = .1)
+        # print(qrice(p, vee = 500, sigma = 4))
+        ppf_exp = [494.8898762347361, 496.6495690858350, 497.9184315188069,
+                   499.0026277378915, 500.0159999146250, 501.0293721352668,
+                   502.1135684981884, 503.3824312270405, 505.1421247157822]
+        assert_allclose(ppf, ppf_exp)
+
+        ppf = scipy.stats.rice.ppf(0.5, np.arange(10, 150, 10))
+        # Generated in R
+        # library(VGAM)
+        # options(digits=16)
+        # b <- seq(10, 140, 10)
+        # print(qrice(0.5, vee = b, sigma = 1))
+        ppf_exp = [10.04995862522287, 20.02499480078302, 30.01666512465732,
+                   40.01249934924363, 50.00999966676032, 60.00833314046875,
+                   70.00714273568241, 80.00624991862573, 90.00555549840364,
+                   100.00499995833597, 110.00454542324384, 120.00416664255323,
+                   130.00384613488120, 140.00357141338748]
+        assert_allclose(ppf, ppf_exp)
+
+
+class TestErlang:
+    def setup_method(self):
+        np.random.seed(1234)
+
+    def test_erlang_runtimewarning(self):
+        # erlang should generate a RuntimeWarning if a non-integer
+        # shape parameter is used.
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", RuntimeWarning)
+
+            # The non-integer shape parameter 1.3 should trigger a
+            # RuntimeWarning
+            assert_raises(RuntimeWarning,
+                          stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)
+
+            # Calling the fit method with `f0` set to an integer should
+            # *not* trigger a RuntimeWarning.  It should return the same
+            # values as gamma.fit(...).
+            data = [0.5, 1.0, 2.0, 4.0]
+            result_erlang = stats.erlang.fit(data, f0=1)
+            result_gamma = stats.gamma.fit(data, f0=1)
+            assert_allclose(result_erlang, result_gamma, rtol=1e-3)
+
+    def test_gh_pr_10949_argcheck(self):
+        assert_equal(stats.erlang.pdf(0.5, a=[1, -1]),
+                     stats.gamma.pdf(0.5, a=[1, -1]))
+
+
+class TestRayleigh:
+    def setup_method(self):
+        np.random.seed(987654321)
+
+    # gh-6227
+    def test_logpdf(self):
+        y = stats.rayleigh.logpdf(50)
+        assert_allclose(y, -1246.0879769945718)
+
+    def test_logsf(self):
+        y = stats.rayleigh.logsf(50)
+        assert_allclose(y, -1250)
+
+    @pytest.mark.parametrize("rvs_loc,rvs_scale", [(0.85373171, 0.86932204),
+                                                   (0.20558821, 0.61621008)])
+    def test_fit(self, rvs_loc, rvs_scale):
+        data = stats.rayleigh.rvs(size=250, loc=rvs_loc, scale=rvs_scale)
+
+        def scale_mle(data, floc):
+            return (np.sum((data - floc) ** 2) / (2 * len(data))) ** .5
+
+        # when `floc` is provided, `scale` is found with an analytical formula
+        scale_expect = scale_mle(data, rvs_loc)
+        loc, scale = stats.rayleigh.fit(data, floc=rvs_loc)
+        assert_equal(loc, rvs_loc)
+        assert_equal(scale, scale_expect)
+
+        # when `fscale` is fixed, superclass fit is used to determine `loc`.
+        loc, scale = stats.rayleigh.fit(data, fscale=.6)
+        assert_equal(scale, .6)
+
+        # with both parameters free, one dimensional optimization is done
+        # over a new function that takes into account the dependent relation
+        # of `scale` to `loc`.
+        loc, scale = stats.rayleigh.fit(data)
+        # test that `scale` is defined by its relation to `loc`
+        assert_equal(scale, scale_mle(data, loc))
+
+    @pytest.mark.parametrize("rvs_loc,rvs_scale", [[0.74, 0.01],
+                                                   [0.08464463, 0.12069025]])
+    def test_fit_comparison_super_method(self, rvs_loc, rvs_scale):
+        # test that the objective function result of the analytical MLEs is
+        # less than or equal to that of the numerically optimized estimate
+        data = stats.rayleigh.rvs(size=250, loc=rvs_loc, scale=rvs_scale)
+        _assert_less_or_close_loglike(stats.rayleigh, data)
+
+    def test_fit_warnings(self):
+        assert_fit_warnings(stats.rayleigh)
+
+    def test_fit_gh17088(self):
+        # `rayleigh.fit` could return a location that was inconsistent with
+        # the data. See gh-17088.
+        rng = np.random.default_rng(456)
+        loc, scale, size = 50, 600, 500
+        rvs = stats.rayleigh.rvs(loc, scale, size=size, random_state=rng)
+        loc_fit, _ = stats.rayleigh.fit(rvs)
+        assert loc_fit < np.min(rvs)
+        loc_fit, scale_fit = stats.rayleigh.fit(rvs, fscale=scale)
+        assert loc_fit < np.min(rvs)
+        assert scale_fit == scale
+
+
+class TestExponWeib:
+
+    def test_pdf_logpdf(self):
+        # Regression test for gh-3508.
+        x = 0.1
+        a = 1.0
+        c = 100.0
+        p = stats.exponweib.pdf(x, a, c)
+        logp = stats.exponweib.logpdf(x, a, c)
+        # Expected values were computed with mpmath.
+        assert_allclose([p, logp],
+                        [1.0000000000000054e-97, -223.35075402042244])
+
+    def test_a_is_1(self):
+        # For issue gh-3508.
+        # Check that when a=1, the pdf and logpdf methods of exponweib are the
+        # same as those of weibull_min.
+        x = np.logspace(-4, -1, 4)
+        a = 1
+        c = 100
+
+        p = stats.exponweib.pdf(x, a, c)
+        expected = stats.weibull_min.pdf(x, c)
+        assert_allclose(p, expected)
+
+        logp = stats.exponweib.logpdf(x, a, c)
+        expected = stats.weibull_min.logpdf(x, c)
+        assert_allclose(logp, expected)
+
+    def test_a_is_1_c_is_1(self):
+        # When a = 1 and c = 1, the distribution is exponential.
+        x = np.logspace(-8, 1, 10)
+        a = 1
+        c = 1
+
+        p = stats.exponweib.pdf(x, a, c)
+        expected = stats.expon.pdf(x)
+        assert_allclose(p, expected)
+
+        logp = stats.exponweib.logpdf(x, a, c)
+        expected = stats.expon.logpdf(x)
+        assert_allclose(logp, expected)
+
+    # Reference values were computed with mpmath, e.g:
+    #
+    #     from mpmath import mp
+    #
+    #     def mp_sf(x, a, c):
+    #         x = mp.mpf(x)
+    #         a = mp.mpf(a)
+    #         c = mp.mpf(c)
+    #         return -mp.powm1(-mp.expm1(-x**c)), a)
+    #
+    #     mp.dps = 100
+    #     print(float(mp_sf(1, 2.5, 0.75)))
+    #
+    # prints
+    #
+    #     0.6823127476985246
+    #
+    @pytest.mark.parametrize(
+        'x, a, c, ref',
+        [(1, 2.5, 0.75, 0.6823127476985246),
+         (50, 2.5, 0.75, 1.7056666054719663e-08),
+         (125, 2.5, 0.75, 1.4534393150714602e-16),
+         (250, 2.5, 0.75, 1.2391389689773512e-27),
+         (250, 0.03125, 0.75, 1.548923711221689e-29),
+         (3, 0.03125, 3.0,  5.873527551689983e-14),
+         (2e80, 10.0, 0.02, 2.9449084156902135e-17)]
+    )
+    def test_sf(self, x, a, c, ref):
+        sf = stats.exponweib.sf(x, a, c)
+        assert_allclose(sf, ref, rtol=1e-14)
+
+    # Reference values were computed with mpmath, e.g.
+    #
+    #     from mpmath import mp
+    #
+    #     def mp_isf(p, a, c):
+    #         p = mp.mpf(p)
+    #         a = mp.mpf(a)
+    #         c = mp.mpf(c)
+    #         return (-mp.log(-mp.expm1(mp.log1p(-p)/a)))**(1/c)
+    #
+    #     mp.dps = 100
+    #     print(float(mp_isf(0.25, 2.5, 0.75)))
+    #
+    # prints
+    #
+    #     2.8946008178158924
+    #
+    @pytest.mark.parametrize(
+        'p, a, c, ref',
+        [(0.25, 2.5, 0.75, 2.8946008178158924),
+         (3e-16, 2.5, 0.75, 121.77966713102938),
+         (1e-12, 1, 2, 5.256521769756932),
+         (2e-13, 0.03125, 3, 2.953915059484589),
+         (5e-14, 10.0, 0.02, 7.57094886384687e+75)]
+    )
+    def test_isf(self, p, a, c, ref):
+        isf = stats.exponweib.isf(p, a, c)
+        assert_allclose(isf, ref, rtol=5e-14)
+
+    # Reference values computed with mpmath.
+    @pytest.mark.parametrize('x, a, c, ref',
+                             [(2, 3, 8, -1.9848783170128456e-111),
+                              (1000, 0.5, 0.75, -2.946296827524972e-78)])
+    def test_logcdf(self, x, a, c, ref):
+        logcdf = stats.exponweib.logcdf(x, a, c)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    # Reference values computed with mpmath.
+    @pytest.mark.parametrize('x, a, c, ref',
+                             [(1e-65, 1.5, 1.25, -1.333521432163324e-122),
+                              (2e-10, 2, 10, -1.0485760000000007e-194)])
+    def test_logsf(self, x, a, c, ref):
+        logsf = stats.exponweib.logsf(x, a, c)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+
+class TestFatigueLife:
+
+    def test_sf_tail(self):
+        # Expected value computed with mpmath:
+        #     import mpmath
+        #     mpmath.mp.dps = 80
+        #     x = mpmath.mpf(800.0)
+        #     c = mpmath.mpf(2.5)
+        #     s = float(1 - mpmath.ncdf(1/c * (mpmath.sqrt(x)
+        #                                      - 1/mpmath.sqrt(x))))
+        #     print(s)
+        # Output:
+        #     6.593376447038406e-30
+        s = stats.fatiguelife.sf(800.0, 2.5)
+        assert_allclose(s, 6.593376447038406e-30, rtol=1e-13)
+
+    def test_isf_tail(self):
+        # See test_sf_tail for the mpmath code.
+        p = 6.593376447038406e-30
+        q = stats.fatiguelife.isf(p, 2.5)
+        assert_allclose(q, 800.0, rtol=1e-13)
+
+
+class TestWeibull:
+
+    def test_logpdf(self):
+        # gh-6217
+        y = stats.weibull_min.logpdf(0, 1)
+        assert_equal(y, 0)
+
+    def test_with_maxima_distrib(self):
+        # Tests for weibull_min and weibull_max.
+        # The expected values were computed using the symbolic algebra
+        # program 'maxima' with the package 'distrib', which has
+        # 'pdf_weibull' and 'cdf_weibull'.  The mapping between the
+        # scipy and maxima functions is as follows:
+        # -----------------------------------------------------------------
+        # scipy                              maxima
+        # ---------------------------------  ------------------------------
+        # weibull_min.pdf(x, a, scale=b)     pdf_weibull(x, a, b)
+        # weibull_min.logpdf(x, a, scale=b)  log(pdf_weibull(x, a, b))
+        # weibull_min.cdf(x, a, scale=b)     cdf_weibull(x, a, b)
+        # weibull_min.logcdf(x, a, scale=b)  log(cdf_weibull(x, a, b))
+        # weibull_min.sf(x, a, scale=b)      1 - cdf_weibull(x, a, b)
+        # weibull_min.logsf(x, a, scale=b)   log(1 - cdf_weibull(x, a, b))
+        #
+        # weibull_max.pdf(x, a, scale=b)     pdf_weibull(-x, a, b)
+        # weibull_max.logpdf(x, a, scale=b)  log(pdf_weibull(-x, a, b))
+        # weibull_max.cdf(x, a, scale=b)     1 - cdf_weibull(-x, a, b)
+        # weibull_max.logcdf(x, a, scale=b)  log(1 - cdf_weibull(-x, a, b))
+        # weibull_max.sf(x, a, scale=b)      cdf_weibull(-x, a, b)
+        # weibull_max.logsf(x, a, scale=b)   log(cdf_weibull(-x, a, b))
+        # -----------------------------------------------------------------
+        x = 1.5
+        a = 2.0
+        b = 3.0
+
+        # weibull_min
+
+        p = stats.weibull_min.pdf(x, a, scale=b)
+        assert_allclose(p, np.exp(-0.25)/3)
+
+        lp = stats.weibull_min.logpdf(x, a, scale=b)
+        assert_allclose(lp, -0.25 - np.log(3))
+
+        c = stats.weibull_min.cdf(x, a, scale=b)
+        assert_allclose(c, -special.expm1(-0.25))
+
+        lc = stats.weibull_min.logcdf(x, a, scale=b)
+        assert_allclose(lc, np.log(-special.expm1(-0.25)))
+
+        s = stats.weibull_min.sf(x, a, scale=b)
+        assert_allclose(s, np.exp(-0.25))
+
+        ls = stats.weibull_min.logsf(x, a, scale=b)
+        assert_allclose(ls, -0.25)
+
+        # Also test using a large value x, for which computing the survival
+        # function using the CDF would result in 0.
+        s = stats.weibull_min.sf(30, 2, scale=3)
+        assert_allclose(s, np.exp(-100))
+
+        ls = stats.weibull_min.logsf(30, 2, scale=3)
+        assert_allclose(ls, -100)
+
+        # weibull_max
+        x = -1.5
+
+        p = stats.weibull_max.pdf(x, a, scale=b)
+        assert_allclose(p, np.exp(-0.25)/3)
+
+        lp = stats.weibull_max.logpdf(x, a, scale=b)
+        assert_allclose(lp, -0.25 - np.log(3))
+
+        c = stats.weibull_max.cdf(x, a, scale=b)
+        assert_allclose(c, np.exp(-0.25))
+
+        lc = stats.weibull_max.logcdf(x, a, scale=b)
+        assert_allclose(lc, -0.25)
+
+        s = stats.weibull_max.sf(x, a, scale=b)
+        assert_allclose(s, -special.expm1(-0.25))
+
+        ls = stats.weibull_max.logsf(x, a, scale=b)
+        assert_allclose(ls, np.log(-special.expm1(-0.25)))
+
+        # Also test using a value of x close to 0, for which computing the
+        # survival function using the CDF would result in 0.
+        s = stats.weibull_max.sf(-1e-9, 2, scale=3)
+        assert_allclose(s, -special.expm1(-1/9000000000000000000))
+
+        ls = stats.weibull_max.logsf(-1e-9, 2, scale=3)
+        assert_allclose(ls, np.log(-special.expm1(-1/9000000000000000000)))
+
+    @pytest.mark.parametrize('scale', [1.0, 0.1])
+    def test_delta_cdf(self, scale):
+        # Expected value computed with mpmath:
+        #
+        # def weibull_min_sf(x, k, scale):
+        #     x = mpmath.mpf(x)
+        #     k = mpmath.mpf(k)
+        #     scale =mpmath.mpf(scale)
+        #     return mpmath.exp(-(x/scale)**k)
+        #
+        # >>> import mpmath
+        # >>> mpmath.mp.dps = 60
+        # >>> sf1 = weibull_min_sf(7.5, 3, 1)
+        # >>> sf2 = weibull_min_sf(8.0, 3, 1)
+        # >>> float(sf1 - sf2)
+        # 6.053624060118734e-184
+        #
+        delta = stats.weibull_min._delta_cdf(scale*7.5, scale*8, 3,
+                                             scale=scale)
+        assert_allclose(delta, 6.053624060118734e-184)
+
+    def test_fit_min(self):
+        rng = np.random.default_rng(5985959307161735394)
+
+        c, loc, scale = 2, 3.5, 0.5  # arbitrary, valid parameters
+        dist = stats.weibull_min(c, loc, scale)
+        rvs = dist.rvs(size=100, random_state=rng)
+
+        # test that MLE still honors guesses and fixed parameters
+        c2, loc2, scale2 = stats.weibull_min.fit(rvs, 1.5, floc=3)
+        c3, loc3, scale3 = stats.weibull_min.fit(rvs, 1.6, floc=3)
+        assert loc2 == loc3 == 3  # fixed parameter is respected
+        assert c2 != c3  # different guess -> (slightly) different outcome
+        # quality of fit is tested elsewhere
+
+        # test that MoM honors fixed parameters, accepts (but ignores) guesses
+        c4, loc4, scale4 = stats.weibull_min.fit(rvs, 3, fscale=3, method='mm')
+        assert scale4 == 3
+        # because scale was fixed, only the mean and skewness will be matched
+        dist4 = stats.weibull_min(c4, loc4, scale4)
+        res = dist4.stats(moments='ms')
+        ref = np.mean(rvs), stats.skew(rvs)
+        assert_allclose(res, ref)
+
+    # reference values were computed via mpmath
+    # from mpmath import mp
+    # def weibull_sf_mpmath(x, c):
+    #     x = mp.mpf(x)
+    #     c = mp.mpf(c)
+    #     return float(mp.exp(-x**c))
+
+    @pytest.mark.parametrize('x, c, ref', [(50, 1, 1.9287498479639178e-22),
+                                           (1000, 0.8,
+                                            8.131269637872743e-110)])
+    def test_sf_isf(self, x, c, ref):
+        assert_allclose(stats.weibull_min.sf(x, c), ref, rtol=5e-14)
+        assert_allclose(stats.weibull_min.isf(ref, c), x, rtol=5e-14)
+
+
+class TestDweibull:
+    def test_entropy(self):
+        # Test that dweibull entropy follows that of weibull_min.
+        # (Generic tests check that the dweibull entropy is consistent
+        #  with its PDF. As for accuracy, dweibull entropy should be just
+        #  as accurate as weibull_min entropy. Checks of accuracy against
+        #  a reference need only be applied to the fundamental distribution -
+        #  weibull_min.)
+        rng = np.random.default_rng(8486259129157041777)
+        c = 10**rng.normal(scale=100, size=10)
+        res = stats.dweibull.entropy(c)
+        ref = stats.weibull_min.entropy(c) - np.log(0.5)
+        assert_allclose(res, ref, rtol=1e-15)
+
+    def test_sf(self):
+        # test that for positive values the dweibull survival function is half
+        # the weibull_min survival function
+        rng = np.random.default_rng(8486259129157041777)
+        c = 10**rng.normal(scale=1, size=10)
+        x = 10 * rng.uniform()
+        res = stats.dweibull.sf(x, c)
+        ref = 0.5 * stats.weibull_min.sf(x, c)
+        assert_allclose(res, ref, rtol=1e-15)
+
+
+class TestTruncWeibull:
+
+    def test_pdf_bounds(self):
+        # test bounds
+        y = stats.truncweibull_min.pdf([0.1, 2.0], 2.0, 0.11, 1.99)
+        assert_equal(y, [0.0, 0.0])
+
+    def test_logpdf(self):
+        y = stats.truncweibull_min.logpdf(2.0, 1.0, 2.0, np.inf)
+        assert_equal(y, 0.0)
+
+        # hand calculation
+        y = stats.truncweibull_min.logpdf(2.0, 1.0, 2.0, 4.0)
+        assert_allclose(y, 0.14541345786885884)
+
+    def test_ppf_bounds(self):
+        # test bounds
+        y = stats.truncweibull_min.ppf([0.0, 1.0], 2.0, 0.1, 2.0)
+        assert_equal(y, [0.1, 2.0])
+
+    def test_cdf_to_ppf(self):
+        q = [0., 0.1, .25, 0.50, 0.75, 0.90, 1.]
+        x = stats.truncweibull_min.ppf(q, 2., 0., 3.)
+        q_out = stats.truncweibull_min.cdf(x, 2., 0., 3.)
+        assert_allclose(q, q_out)
+
+    def test_sf_to_isf(self):
+        q = [0., 0.1, .25, 0.50, 0.75, 0.90, 1.]
+        x = stats.truncweibull_min.isf(q, 2., 0., 3.)
+        q_out = stats.truncweibull_min.sf(x, 2., 0., 3.)
+        assert_allclose(q, q_out)
+
+    def test_munp(self):
+        c = 2.
+        a = 1.
+        b = 3.
+
+        def xnpdf(x, n):
+            return x**n*stats.truncweibull_min.pdf(x, c, a, b)
+
+        m0 = stats.truncweibull_min.moment(0, c, a, b)
+        assert_equal(m0, 1.)
+
+        m1 = stats.truncweibull_min.moment(1, c, a, b)
+        m1_expected, _ = quad(lambda x: xnpdf(x, 1), a, b)
+        assert_allclose(m1, m1_expected)
+
+        m2 = stats.truncweibull_min.moment(2, c, a, b)
+        m2_expected, _ = quad(lambda x: xnpdf(x, 2), a, b)
+        assert_allclose(m2, m2_expected)
+
+        m3 = stats.truncweibull_min.moment(3, c, a, b)
+        m3_expected, _ = quad(lambda x: xnpdf(x, 3), a, b)
+        assert_allclose(m3, m3_expected)
+
+        m4 = stats.truncweibull_min.moment(4, c, a, b)
+        m4_expected, _ = quad(lambda x: xnpdf(x, 4), a, b)
+        assert_allclose(m4, m4_expected)
+
+    def test_reference_values(self):
+        a = 1.
+        b = 3.
+        c = 2.
+        x_med = np.sqrt(1 - np.log(0.5 + np.exp(-(8. + np.log(2.)))))
+
+        cdf = stats.truncweibull_min.cdf(x_med, c, a, b)
+        assert_allclose(cdf, 0.5)
+
+        lc = stats.truncweibull_min.logcdf(x_med, c, a, b)
+        assert_allclose(lc, -np.log(2.))
+
+        ppf = stats.truncweibull_min.ppf(0.5, c, a, b)
+        assert_allclose(ppf, x_med)
+
+        sf = stats.truncweibull_min.sf(x_med, c, a, b)
+        assert_allclose(sf, 0.5)
+
+        ls = stats.truncweibull_min.logsf(x_med, c, a, b)
+        assert_allclose(ls, -np.log(2.))
+
+        isf = stats.truncweibull_min.isf(0.5, c, a, b)
+        assert_allclose(isf, x_med)
+
+    def test_compare_weibull_min(self):
+        # Verify that the truncweibull_min distribution gives the same results
+        # as the original weibull_min
+        x = 1.5
+        c = 2.0
+        a = 0.0
+        b = np.inf
+        scale = 3.0
+
+        p = stats.weibull_min.pdf(x, c, scale=scale)
+        p_trunc = stats.truncweibull_min.pdf(x, c, a, b, scale=scale)
+        assert_allclose(p, p_trunc)
+
+        lp = stats.weibull_min.logpdf(x, c, scale=scale)
+        lp_trunc = stats.truncweibull_min.logpdf(x, c, a, b, scale=scale)
+        assert_allclose(lp, lp_trunc)
+
+        cdf = stats.weibull_min.cdf(x, c, scale=scale)
+        cdf_trunc = stats.truncweibull_min.cdf(x, c, a, b, scale=scale)
+        assert_allclose(cdf, cdf_trunc)
+
+        lc = stats.weibull_min.logcdf(x, c, scale=scale)
+        lc_trunc = stats.truncweibull_min.logcdf(x, c, a, b, scale=scale)
+        assert_allclose(lc, lc_trunc)
+
+        s = stats.weibull_min.sf(x, c, scale=scale)
+        s_trunc = stats.truncweibull_min.sf(x, c, a, b, scale=scale)
+        assert_allclose(s, s_trunc)
+
+        ls = stats.weibull_min.logsf(x, c, scale=scale)
+        ls_trunc = stats.truncweibull_min.logsf(x, c, a, b, scale=scale)
+        assert_allclose(ls, ls_trunc)
+
+        # # Also test using a large value x, for which computing the survival
+        # # function using the CDF would result in 0.
+        s = stats.truncweibull_min.sf(30, 2, a, b, scale=3)
+        assert_allclose(s, np.exp(-100))
+
+        ls = stats.truncweibull_min.logsf(30, 2, a, b, scale=3)
+        assert_allclose(ls, -100)
+
+    def test_compare_weibull_min2(self):
+        # Verify that the truncweibull_min distribution PDF and CDF results
+        # are the same as those calculated from truncating weibull_min
+        c, a, b = 2.5, 0.25, 1.25
+        x = np.linspace(a, b, 100)
+
+        pdf1 = stats.truncweibull_min.pdf(x, c, a, b)
+        cdf1 = stats.truncweibull_min.cdf(x, c, a, b)
+
+        norm = stats.weibull_min.cdf(b, c) - stats.weibull_min.cdf(a, c)
+        pdf2 = stats.weibull_min.pdf(x, c) / norm
+        cdf2 = (stats.weibull_min.cdf(x, c) - stats.weibull_min.cdf(a, c))/norm
+
+        np.testing.assert_allclose(pdf1, pdf2)
+        np.testing.assert_allclose(cdf1, cdf2)
+
+
+class TestRdist:
+    def test_rdist_cdf_gh1285(self):
+        # check workaround in rdist._cdf for issue gh-1285.
+        distfn = stats.rdist
+        values = [0.001, 0.5, 0.999]
+        assert_almost_equal(distfn.cdf(distfn.ppf(values, 541.0), 541.0),
+                            values, decimal=5)
+
+    def test_rdist_beta(self):
+        # rdist is a special case of stats.beta
+        x = np.linspace(-0.99, 0.99, 10)
+        c = 2.7
+        assert_almost_equal(0.5*stats.beta(c/2, c/2).pdf((x + 1)/2),
+                            stats.rdist(c).pdf(x))
+
+    # reference values were computed via mpmath
+    # from mpmath import mp
+    # mp.dps = 200
+    # def rdist_sf_mpmath(x, c):
+    #     x = mp.mpf(x)
+    #     c = mp.mpf(c)
+    #     return float(mp.betainc(c/2, c/2, (x+1)/2, mp.one, regularized=True))
+    @pytest.mark.parametrize(
+        "x, c, ref",
+        [
+            (0.0001, 541, 0.49907251345565845),
+            (0.1, 241, 0.06000788166249205),
+            (0.5, 441, 1.0655898106047832e-29),
+            (0.8, 341, 6.025478373732215e-78),
+        ]
+    )
+    def test_rdist_sf(self, x, c, ref):
+        assert_allclose(stats.rdist.sf(x, c), ref, rtol=5e-14)
+
+
+class TestTrapezoid:
+    def test_reduces_to_triang(self):
+        modes = [0, 0.3, 0.5, 1]
+        for mode in modes:
+            x = [0, mode, 1]
+            assert_almost_equal(stats.trapezoid.pdf(x, mode, mode),
+                                stats.triang.pdf(x, mode))
+            assert_almost_equal(stats.trapezoid.cdf(x, mode, mode),
+                                stats.triang.cdf(x, mode))
+
+    def test_reduces_to_uniform(self):
+        x = np.linspace(0, 1, 10)
+        assert_almost_equal(stats.trapezoid.pdf(x, 0, 1), stats.uniform.pdf(x))
+        assert_almost_equal(stats.trapezoid.cdf(x, 0, 1), stats.uniform.cdf(x))
+
+    def test_cases(self):
+        # edge cases
+        assert_almost_equal(stats.trapezoid.pdf(0, 0, 0), 2)
+        assert_almost_equal(stats.trapezoid.pdf(1, 1, 1), 2)
+        assert_almost_equal(stats.trapezoid.pdf(0.5, 0, 0.8),
+                            1.11111111111111111)
+        assert_almost_equal(stats.trapezoid.pdf(0.5, 0.2, 1.0),
+                            1.11111111111111111)
+
+        # straightforward case
+        assert_almost_equal(stats.trapezoid.pdf(0.1, 0.2, 0.8), 0.625)
+        assert_almost_equal(stats.trapezoid.pdf(0.5, 0.2, 0.8), 1.25)
+        assert_almost_equal(stats.trapezoid.pdf(0.9, 0.2, 0.8), 0.625)
+
+        assert_almost_equal(stats.trapezoid.cdf(0.1, 0.2, 0.8), 0.03125)
+        assert_almost_equal(stats.trapezoid.cdf(0.2, 0.2, 0.8), 0.125)
+        assert_almost_equal(stats.trapezoid.cdf(0.5, 0.2, 0.8), 0.5)
+        assert_almost_equal(stats.trapezoid.cdf(0.9, 0.2, 0.8), 0.96875)
+        assert_almost_equal(stats.trapezoid.cdf(1.0, 0.2, 0.8), 1.0)
+
+    def test_moments_and_entropy(self):
+        # issue #11795: improve precision of trapezoid stats
+        # Apply formulas from Wikipedia for the following parameters:
+        a, b, c, d = -3, -1, 2, 3  # => 1/3, 5/6, -3, 6
+        p1, p2, loc, scale = (b-a) / (d-a), (c-a) / (d-a), a, d-a
+        h = 2 / (d+c-b-a)
+
+        def moment(n):
+            return (h * ((d**(n+2) - c**(n+2)) / (d-c)
+                         - (b**(n+2) - a**(n+2)) / (b-a)) /
+                    (n+1) / (n+2))
+
+        mean = moment(1)
+        var = moment(2) - mean**2
+        entropy = 0.5 * (d-c+b-a) / (d+c-b-a) + np.log(0.5 * (d+c-b-a))
+        assert_almost_equal(stats.trapezoid.mean(p1, p2, loc, scale),
+                            mean, decimal=13)
+        assert_almost_equal(stats.trapezoid.var(p1, p2, loc, scale),
+                            var, decimal=13)
+        assert_almost_equal(stats.trapezoid.entropy(p1, p2, loc, scale),
+                            entropy, decimal=13)
+
+        # Check boundary cases where scipy d=0 or d=1.
+        assert_almost_equal(stats.trapezoid.mean(0, 0, -3, 6), -1, decimal=13)
+        assert_almost_equal(stats.trapezoid.mean(0, 1, -3, 6), 0, decimal=13)
+        assert_almost_equal(stats.trapezoid.var(0, 1, -3, 6), 3, decimal=13)
+
+    def test_trapezoid_vect(self):
+        # test that array-valued shapes and arguments are handled
+        c = np.array([0.1, 0.2, 0.3])
+        d = np.array([0.5, 0.6])[:, None]
+        x = np.array([0.15, 0.25, 0.9])
+        v = stats.trapezoid.pdf(x, c, d)
+
+        cc, dd, xx = np.broadcast_arrays(c, d, x)
+
+        res = np.empty(xx.size, dtype=xx.dtype)
+        ind = np.arange(xx.size)
+        for i, x1, c1, d1 in zip(ind, xx.ravel(), cc.ravel(), dd.ravel()):
+            res[i] = stats.trapezoid.pdf(x1, c1, d1)
+
+        assert_allclose(v, res.reshape(v.shape), atol=1e-15)
+
+        # Check that the stats() method supports vector arguments.
+        v = np.asarray(stats.trapezoid.stats(c, d, moments="mvsk"))
+        cc, dd = np.broadcast_arrays(c, d)
+        res = np.empty((cc.size, 4))  # 4 stats returned per value
+        ind = np.arange(cc.size)
+        for i, c1, d1 in zip(ind, cc.ravel(), dd.ravel()):
+            res[i] = stats.trapezoid.stats(c1, d1, moments="mvsk")
+
+        assert_allclose(v, res.T.reshape(v.shape), atol=1e-15)
+
+    def test_trapz(self):
+        # Basic test for alias
+        x = np.linspace(0, 1, 10)
+        with pytest.deprecated_call(match="`trapz.pdf` is deprecated"):
+            result = stats.trapz.pdf(x, 0, 1)
+        assert_almost_equal(result, stats.uniform.pdf(x))
+
+    @pytest.mark.parametrize('method', ['pdf', 'logpdf', 'cdf', 'logcdf',
+                                        'sf', 'logsf', 'ppf', 'isf'])
+    def test_trapz_deprecation(self, method):
+        c, d = 0.2, 0.8
+        expected = getattr(stats.trapezoid, method)(1, c, d)
+        with pytest.deprecated_call(
+            match=f"`trapz.{method}` is deprecated",
+        ):
+            result = getattr(stats.trapz, method)(1, c, d)
+        assert result == expected
+
+
+class TestTriang:
+    def test_edge_cases(self):
+        with np.errstate(all='raise'):
+            assert_equal(stats.triang.pdf(0, 0), 2.)
+            assert_equal(stats.triang.pdf(0.5, 0), 1.)
+            assert_equal(stats.triang.pdf(1, 0), 0.)
+
+            assert_equal(stats.triang.pdf(0, 1), 0)
+            assert_equal(stats.triang.pdf(0.5, 1), 1.)
+            assert_equal(stats.triang.pdf(1, 1), 2)
+
+            assert_equal(stats.triang.cdf(0., 0.), 0.)
+            assert_equal(stats.triang.cdf(0.5, 0.), 0.75)
+            assert_equal(stats.triang.cdf(1.0, 0.), 1.0)
+
+            assert_equal(stats.triang.cdf(0., 1.), 0.)
+            assert_equal(stats.triang.cdf(0.5, 1.), 0.25)
+            assert_equal(stats.triang.cdf(1., 1.), 1)
+
+
+class TestMaxwell:
+
+    # reference values were computed with wolfram alpha
+    # erfc(x/sqrt(2)) + sqrt(2/pi) * x * e^(-x^2/2)
+
+    @pytest.mark.parametrize("x, ref",
+                             [(20, 2.2138865931011177e-86),
+                              (0.01, 0.999999734046458435)])
+    def test_sf(self, x, ref):
+        assert_allclose(stats.maxwell.sf(x), ref, rtol=1e-14)
+
+    # reference values were computed with wolfram alpha
+    # sqrt(2) * sqrt(Q^(-1)(3/2, q))
+
+    @pytest.mark.parametrize("q, ref",
+                             [(0.001, 4.033142223656157022),
+                              (0.9999847412109375, 0.0385743284050381),
+                              (2**-55, 8.95564974719481)])
+    def test_isf(self, q, ref):
+        assert_allclose(stats.maxwell.isf(q), ref, rtol=1e-15)
+
+    def test_logcdf(self):
+        # Reference value computed with mpmath.
+        ref = -1.8729310110194814e-17
+        logcdf = stats.maxwell.logcdf(9)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    def test_logsf(self):
+        # Reference value computed with mpmath.
+        ref = -2.6596152026762177e-25
+        logsf = stats.maxwell.logsf(1e-8)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+
+class TestMielke:
+    def test_moments(self):
+        k, s = 4.642, 0.597
+        # n-th moment exists only if n < s
+        assert_equal(stats.mielke(k, s).moment(1), np.inf)
+        assert_equal(stats.mielke(k, 1.0).moment(1), np.inf)
+        assert_(np.isfinite(stats.mielke(k, 1.01).moment(1)))
+
+    def test_burr_equivalence(self):
+        x = np.linspace(0.01, 100, 50)
+        k, s = 2.45, 5.32
+        assert_allclose(stats.burr.pdf(x, s, k/s), stats.mielke.pdf(x, k, s))
+
+
+class TestBurr:
+    def test_endpoints_7491(self):
+        # gh-7491
+        # Compute the pdf at the left endpoint dst.a.
+        data = [
+            [stats.fisk, (1,), 1],
+            [stats.burr, (0.5, 2), 1],
+            [stats.burr, (1, 1), 1],
+            [stats.burr, (2, 0.5), 1],
+            [stats.burr12, (1, 0.5), 0.5],
+            [stats.burr12, (1, 1), 1.0],
+            [stats.burr12, (1, 2), 2.0]]
+
+        ans = [_f.pdf(_f.a, *_args) for _f, _args, _ in data]
+        correct = [_correct_ for _f, _args, _correct_ in data]
+        assert_array_almost_equal(ans, correct)
+
+        ans = [_f.logpdf(_f.a, *_args) for _f, _args, _ in data]
+        correct = [np.log(_correct_) for _f, _args, _correct_ in data]
+        assert_array_almost_equal(ans, correct)
+
+    def test_burr_stats_9544(self):
+        # gh-9544.  Test from gh-9978
+        c, d = 5.0, 3
+        mean, variance = stats.burr(c, d).stats()
+        # mean = sc.beta(3 + 1/5, 1. - 1/5) * 3  = 1.4110263...
+        # var =  sc.beta(3 + 2 / 5, 1. - 2 / 5) * 3 -
+        #        (sc.beta(3 + 1 / 5, 1. - 1 / 5) * 3) ** 2
+        mean_hc, variance_hc = 1.4110263183925857, 0.22879948026191643
+        assert_allclose(mean, mean_hc)
+        assert_allclose(variance, variance_hc)
+
+    def test_burr_nan_mean_var_9544(self):
+        # gh-9544.  Test from gh-9978
+        c, d = 0.5, 3
+        mean, variance = stats.burr(c, d).stats()
+        assert_(np.isnan(mean))
+        assert_(np.isnan(variance))
+        c, d = 1.5, 3
+        mean, variance = stats.burr(c, d).stats()
+        assert_(np.isfinite(mean))
+        assert_(np.isnan(variance))
+
+        c, d = 0.5, 3
+        e1, e2, e3, e4 = stats.burr._munp(np.array([1, 2, 3, 4]), c, d)
+        assert_(np.isnan(e1))
+        assert_(np.isnan(e2))
+        assert_(np.isnan(e3))
+        assert_(np.isnan(e4))
+        c, d = 1.5, 3
+        e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d)
+        assert_(np.isfinite(e1))
+        assert_(np.isnan(e2))
+        assert_(np.isnan(e3))
+        assert_(np.isnan(e4))
+        c, d = 2.5, 3
+        e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d)
+        assert_(np.isfinite(e1))
+        assert_(np.isfinite(e2))
+        assert_(np.isnan(e3))
+        assert_(np.isnan(e4))
+        c, d = 3.5, 3
+        e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d)
+        assert_(np.isfinite(e1))
+        assert_(np.isfinite(e2))
+        assert_(np.isfinite(e3))
+        assert_(np.isnan(e4))
+        c, d = 4.5, 3
+        e1, e2, e3, e4 = stats.burr._munp([1, 2, 3, 4], c, d)
+        assert_(np.isfinite(e1))
+        assert_(np.isfinite(e2))
+        assert_(np.isfinite(e3))
+        assert_(np.isfinite(e4))
+
+    def test_burr_isf(self):
+        # reference values were computed via the reference distribution, e.g.
+        # mp.dps = 100
+        # Burr(c=5, d=3).isf([0.1, 1e-10, 1e-20, 1e-40])
+        c, d = 5.0, 3.0
+        q = [0.1, 1e-10, 1e-20, 1e-40]
+        ref = [1.9469686558286508, 124.57309395989076, 12457.309396155173,
+               124573093.96155174]
+        assert_allclose(stats.burr.isf(q, c, d), ref, rtol=1e-14)
+
+
+class TestBurr12:
+
+    @pytest.mark.parametrize('scale, expected',
+                             [(1.0, 2.3283064359965952e-170),
+                              (3.5, 5.987114417447875e-153)])
+    def test_delta_cdf(self, scale, expected):
+        # Expected value computed with mpmath:
+        #
+        # def burr12sf(x, c, d, scale):
+        #     x = mpmath.mpf(x)
+        #     c = mpmath.mpf(c)
+        #     d = mpmath.mpf(d)
+        #     scale = mpmath.mpf(scale)
+        #     return (mpmath.mp.one + (x/scale)**c)**(-d)
+        #
+        # >>> import mpmath
+        # >>> mpmath.mp.dps = 60
+        # >>> float(burr12sf(2e5, 4, 8, 1) - burr12sf(4e5, 4, 8, 1))
+        # 2.3283064359965952e-170
+        # >>> float(burr12sf(2e5, 4, 8, 3.5) - burr12sf(4e5, 4, 8, 3.5))
+        # 5.987114417447875e-153
+        #
+        delta = stats.burr12._delta_cdf(2e5, 4e5, 4, 8, scale=scale)
+        assert_allclose(delta, expected, rtol=1e-13)
+
+    def test_moments_edge(self):
+        # gh-18838 reported that burr12 moments could be invalid; see above.
+        # Check that this is resolved in an edge case where c*d == n, and
+        # compare the results against those produced by Mathematica, e.g.
+        # `SinghMaddalaDistribution[2, 2, 1]` at Wolfram Alpha.
+        c, d = 2, 2
+        mean = np.pi/4
+        var = 1 - np.pi**2/16
+        skew = np.pi**3/(32*var**1.5)
+        kurtosis = np.nan
+        ref = [mean, var, skew, kurtosis]
+        res = stats.burr12(c, d).stats('mvsk')
+        assert_allclose(res, ref, rtol=1e-14)
+
+    # Reference values were computed with mpmath using mp.dps = 80
+    # and then cast to float.
+    @pytest.mark.parametrize(
+        'p, c, d, ref',
+        [(1e-12, 20, 0.5, 15.848931924611135),
+         (1e-19, 20, 0.5, 79.43282347242815),
+         (1e-12, 0.25, 35, 2.0888618213462466),
+         (1e-80, 0.25, 35, 1360930951.7972188)]
+    )
+    def test_isf_near_zero(self, p, c, d, ref):
+        x = stats.burr12.isf(p, c, d)
+        assert_allclose(x, ref, rtol=1e-14)
+
+
+class TestStudentizedRange:
+    # For alpha = .05, .01, and .001, and for each value of
+    # v = [1, 3, 10, 20, 120, inf], a Q was picked from each table for
+    # k = [2, 8, 14, 20].
+
+    # these arrays are written with `k` as column, and `v` as rows.
+    # Q values are taken from table 3:
+    # https://www.jstor.org/stable/2237810
+    q05 = [17.97, 45.40, 54.33, 59.56,
+           4.501, 8.853, 10.35, 11.24,
+           3.151, 5.305, 6.028, 6.467,
+           2.950, 4.768, 5.357, 5.714,
+           2.800, 4.363, 4.842, 5.126,
+           2.772, 4.286, 4.743, 5.012]
+    q01 = [90.03, 227.2, 271.8, 298.0,
+           8.261, 15.64, 18.22, 19.77,
+           4.482, 6.875, 7.712, 8.226,
+           4.024, 5.839, 6.450, 6.823,
+           3.702, 5.118, 5.562, 5.827,
+           3.643, 4.987, 5.400, 5.645]
+    q001 = [900.3, 2272, 2718, 2980,
+            18.28, 34.12, 39.69, 43.05,
+            6.487, 9.352, 10.39, 11.03,
+            5.444, 7.313, 7.966, 8.370,
+            4.772, 6.039, 6.448, 6.695,
+            4.654, 5.823, 6.191, 6.411]
+    qs = np.concatenate((q05, q01, q001))
+    ps = [.95, .99, .999]
+    vs = [1, 3, 10, 20, 120, np.inf]
+    ks = [2, 8, 14, 20]
+
+    data = list(zip(product(ps, vs, ks), qs))
+
+    # A small selection of large-v cases generated with R's `ptukey`
+    # Each case is in the format (q, k, v, r_result)
+    r_data = [
+        (0.1, 3, 9001, 0.002752818526842),
+        (1, 10, 1000, 0.000526142388912),
+        (1, 3, np.inf, 0.240712641229283),
+        (4, 3, np.inf, 0.987012338626815),
+        (1, 10, np.inf, 0.000519869467083),
+    ]
+
+    @pytest.mark.slow
+    def test_cdf_against_tables(self):
+        for pvk, q in self.data:
+            p_expected, v, k = pvk
+            res_p = stats.studentized_range.cdf(q, k, v)
+            assert_allclose(res_p, p_expected, rtol=1e-4)
+
+    @pytest.mark.xslow
+    def test_ppf_against_tables(self):
+        for pvk, q_expected in self.data:
+            p, v, k = pvk
+            res_q = stats.studentized_range.ppf(p, k, v)
+            assert_allclose(res_q, q_expected, rtol=5e-4)
+
+    path_prefix = os.path.dirname(__file__)
+    relative_path = "data/studentized_range_mpmath_ref.json"
+    with open(os.path.join(path_prefix, relative_path)) as file:
+        pregenerated_data = json.load(file)
+
+    @pytest.mark.parametrize("case_result", pregenerated_data["cdf_data"])
+    def test_cdf_against_mp(self, case_result):
+        src_case = case_result["src_case"]
+        mp_result = case_result["mp_result"]
+        qkv = src_case["q"], src_case["k"], src_case["v"]
+        res = stats.studentized_range.cdf(*qkv)
+
+        assert_allclose(res, mp_result,
+                        atol=src_case["expected_atol"],
+                        rtol=src_case["expected_rtol"])
+
+    @pytest.mark.parametrize("case_result", pregenerated_data["pdf_data"])
+    def test_pdf_against_mp(self, case_result):
+        src_case = case_result["src_case"]
+        mp_result = case_result["mp_result"]
+        qkv = src_case["q"], src_case["k"], src_case["v"]
+        res = stats.studentized_range.pdf(*qkv)
+
+        assert_allclose(res, mp_result,
+                        atol=src_case["expected_atol"],
+                        rtol=src_case["expected_rtol"])
+
+    @pytest.mark.xslow
+    @pytest.mark.xfail_on_32bit("intermittent RuntimeWarning: invalid value.")
+    @pytest.mark.parametrize("case_result", pregenerated_data["moment_data"])
+    def test_moment_against_mp(self, case_result):
+        src_case = case_result["src_case"]
+        mp_result = case_result["mp_result"]
+        mkv = src_case["m"], src_case["k"], src_case["v"]
+
+        # Silence invalid value encountered warnings. Actual problems will be
+        # caught by the result comparison.
+        with np.errstate(invalid='ignore'):
+            res = stats.studentized_range.moment(*mkv)
+
+        assert_allclose(res, mp_result,
+                        atol=src_case["expected_atol"],
+                        rtol=src_case["expected_rtol"])
+
+    @pytest.mark.slow
+    def test_pdf_integration(self):
+        k, v = 3, 10
+        # Test whether PDF integration is 1 like it should be.
+        res = quad(stats.studentized_range.pdf, 0, np.inf, args=(k, v))
+        assert_allclose(res[0], 1)
+
+    @pytest.mark.xslow
+    def test_pdf_against_cdf(self):
+        k, v = 3, 10
+
+        # Test whether the integrated PDF matches the CDF using cumulative
+        # integration. Use a small step size to reduce error due to the
+        # summation. This is slow, but tests the results well.
+        x = np.arange(0, 10, step=0.01)
+
+        y_cdf = stats.studentized_range.cdf(x, k, v)[1:]
+        y_pdf_raw = stats.studentized_range.pdf(x, k, v)
+        y_pdf_cumulative = cumulative_trapezoid(y_pdf_raw, x)
+
+        # Because of error caused by the summation, use a relatively large rtol
+        assert_allclose(y_pdf_cumulative, y_cdf, rtol=1e-4)
+
+    @pytest.mark.parametrize("r_case_result", r_data)
+    def test_cdf_against_r(self, r_case_result):
+        # Test large `v` values using R
+        q, k, v, r_res = r_case_result
+        with np.errstate(invalid='ignore'):
+            res = stats.studentized_range.cdf(q, k, v)
+        assert_allclose(res, r_res)
+
+    @pytest.mark.xslow
+    @pytest.mark.xfail_on_32bit("intermittent RuntimeWarning: invalid value.")
+    def test_moment_vectorization(self):
+        # Test moment broadcasting. Calls `_munp` directly because
+        # `rv_continuous.moment` is broken at time of writing. See gh-12192
+
+        # Silence invalid value encountered warnings. Actual problems will be
+        # caught by the result comparison.
+        with np.errstate(invalid='ignore'):
+            m = stats.studentized_range._munp([1, 2], [4, 5], [10, 11])
+
+        assert_allclose(m.shape, (2,))
+
+        with pytest.raises(ValueError, match="...could not be broadcast..."):
+            stats.studentized_range._munp(1, [4, 5], [10, 11, 12])
+
+    @pytest.mark.xslow
+    def test_fitstart_valid(self):
+        with suppress_warnings() as sup, np.errstate(invalid="ignore"):
+            # the integration warning message may differ
+            sup.filter(IntegrationWarning)
+            k, df, _, _ = stats.studentized_range._fitstart([1, 2, 3])
+        assert_(stats.studentized_range._argcheck(k, df))
+
+    def test_infinite_df(self):
+        # Check that the CDF and PDF infinite and normal integrators
+        # roughly match for a high df case
+        res = stats.studentized_range.pdf(3, 10, np.inf)
+        res_finite = stats.studentized_range.pdf(3, 10, 99999)
+        assert_allclose(res, res_finite, atol=1e-4, rtol=1e-4)
+
+        res = stats.studentized_range.cdf(3, 10, np.inf)
+        res_finite = stats.studentized_range.cdf(3, 10, 99999)
+        assert_allclose(res, res_finite, atol=1e-4, rtol=1e-4)
+
+    def test_df_cutoff(self):
+        # Test that the CDF and PDF properly switch integrators at df=100,000.
+        # The infinite integrator should be different enough that it fails
+        # an allclose assertion. Also sanity check that using the same
+        # integrator does pass the allclose with a 1-df difference, which
+        # should be tiny.
+
+        res = stats.studentized_range.pdf(3, 10, 100000)
+        res_finite = stats.studentized_range.pdf(3, 10, 99999)
+        res_sanity = stats.studentized_range.pdf(3, 10, 99998)
+        assert_raises(AssertionError, assert_allclose, res, res_finite,
+                      atol=1e-6, rtol=1e-6)
+        assert_allclose(res_finite, res_sanity, atol=1e-6, rtol=1e-6)
+
+        res = stats.studentized_range.cdf(3, 10, 100000)
+        res_finite = stats.studentized_range.cdf(3, 10, 99999)
+        res_sanity = stats.studentized_range.cdf(3, 10, 99998)
+        assert_raises(AssertionError, assert_allclose, res, res_finite,
+                      atol=1e-6, rtol=1e-6)
+        assert_allclose(res_finite, res_sanity, atol=1e-6, rtol=1e-6)
+
+    def test_clipping(self):
+        # The result of this computation was -9.9253938401489e-14 on some
+        # systems. The correct result is very nearly zero, but should not be
+        # negative.
+        q, k, v = 34.6413996195345746, 3, 339
+        p = stats.studentized_range.sf(q, k, v)
+        assert_allclose(p, 0, atol=1e-10)
+        assert p >= 0
+
+
+class TestTukeyLambda:
+
+    @pytest.mark.parametrize(
+        'lam',
+        [0.0, -1.0, -2.0, np.array([[-1.0], [0.0], [-2.0]])]
+    )
+    def test_pdf_nonpositive_lambda(self, lam):
+        # Make sure that Tukey-Lambda distribution correctly handles
+        # non-positive lambdas.
+        # This is a crude test--it just checks that all the PDF values
+        # are finite and greater than 0.
+        x = np.linspace(-5.0, 5.0, 101)
+        p = stats.tukeylambda.pdf(x, lam)
+        assert np.isfinite(p).all()
+        assert (p > 0.0).all()
+
+    def test_pdf_mixed_lambda(self):
+        # Another crude test of the behavior of the PDF method.
+        x = np.linspace(-5.0, 5.0, 101)
+        lam = np.array([[-1.0], [0.0], [2.0]])
+        p = stats.tukeylambda.pdf(x, lam)
+        assert np.isfinite(p).all()
+        # For p[0] and p[1], where lam <= 0, the support is (-inf, inf),
+        # so the PDF should be nonzero everywhere (assuming we aren't so
+        # far in the tails that we get underflow).
+        assert (p[:2] > 0.0).all()
+        # For p[2], where lam=2.0, the support is [-0.5, 0.5], so in pdf(x),
+        # some values should be positive and some should be 0.
+        assert (p[2] > 0.0).any()
+        assert (p[2] == 0.0).any()
+
+    def test_support(self):
+        lam = np.array([-1.75, -0.5, 0.0, 0.25, 0.5, 2.0])
+        a, b = stats.tukeylambda.support(lam)
+        expected_b = np.array([np.inf, np.inf, np.inf, 4, 2, 0.5])
+        assert_equal(b, expected_b)
+        assert_equal(a, -expected_b)
+
+    def test_pdf_support_boundary(self):
+        # Verify that tukeylambda.pdf() doesn't generate a
+        # warning when evaluated at the bounds of the support.
+        # For lam=0.5, the support is (-2, 2).
+        p = stats.tukeylambda.pdf([-2.0, 2.0], 0.5)
+        assert_equal(p, [0.0, 0.0])
+
+    def test_tukeylambda_stats_ticket_1545(self):
+        # Some test for the variance and kurtosis of the Tukey Lambda distr.
+        # See test_tukeylamdba_stats.py for more tests.
+
+        mv = stats.tukeylambda.stats(0, moments='mvsk')
+        # Known exact values:
+        expected = [0, np.pi**2/3, 0, 1.2]
+        assert_almost_equal(mv, expected, decimal=10)
+
+        mv = stats.tukeylambda.stats(3.13, moments='mvsk')
+        # 'expected' computed with mpmath.
+        expected = [0, 0.0269220858861465102, 0, -0.898062386219224104]
+        assert_almost_equal(mv, expected, decimal=10)
+
+        mv = stats.tukeylambda.stats(0.14, moments='mvsk')
+        # 'expected' computed with mpmath.
+        expected = [0, 2.11029702221450250, 0, -0.02708377353223019456]
+        assert_almost_equal(mv, expected, decimal=10)
+
+
+class TestLevy:
+
+    def test_levy_cdf_ppf(self):
+        # Test levy.cdf, including small arguments.
+        x = np.array([1000, 1.0, 0.5, 0.1, 0.01, 0.001])
+
+        # Expected values were calculated separately with mpmath.
+        # E.g.
+        # >>> mpmath.mp.dps = 100
+        # >>> x = mpmath.mp.mpf('0.01')
+        # >>> cdf = mpmath.erfc(mpmath.sqrt(1/(2*x)))
+        expected = np.array([0.9747728793699604,
+                             0.3173105078629141,
+                             0.1572992070502851,
+                             0.0015654022580025495,
+                             1.523970604832105e-23,
+                             1.795832784800726e-219])
+
+        y = stats.levy.cdf(x)
+        assert_allclose(y, expected, rtol=1e-10)
+
+        # ppf(expected) should get us back to x.
+        xx = stats.levy.ppf(expected)
+        assert_allclose(xx, x, rtol=1e-13)
+
+    def test_levy_sf(self):
+        # Large values, far into the tail of the distribution.
+        x = np.array([1e15, 1e25, 1e35, 1e50])
+        # Expected values were calculated with mpmath.
+        expected = np.array([2.5231325220201597e-08,
+                             2.52313252202016e-13,
+                             2.52313252202016e-18,
+                             7.978845608028653e-26])
+        y = stats.levy.sf(x)
+        assert_allclose(y, expected, rtol=1e-14)
+
+    # The expected values for levy.isf(p) were calculated with mpmath.
+    # For loc=0 and scale=1, the inverse SF can be computed with
+    #
+    #     import mpmath
+    #
+    #     def levy_invsf(p):
+    #         return 1/(2*mpmath.erfinv(p)**2)
+    #
+    # For example, with mpmath.mp.dps set to 60, float(levy_invsf(1e-20))
+    # returns 6.366197723675814e+39.
+    #
+    @pytest.mark.parametrize('p, expected_isf',
+                             [(1e-20, 6.366197723675814e+39),
+                              (1e-8, 6366197723675813.0),
+                              (0.375, 4.185810119346273),
+                              (0.875, 0.42489442055310134),
+                              (0.999, 0.09235685880262713),
+                              (0.9999999962747097, 0.028766845244146945)])
+    def test_levy_isf(self, p, expected_isf):
+        x = stats.levy.isf(p)
+        assert_allclose(x, expected_isf, atol=5e-15)
+
+    def test_levy_logcdf(self):
+        x = 1e50
+        ref = -7.978845608028653e-26
+        logcdf = stats.levy.logcdf(x)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    def test_levy_logsf(self):
+        x = 5e-3
+        ref = -2.0884875837625492e-45
+        logsf = stats.levy.logsf(x)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+
+def test_540_567():
+    # test for nan returned in tickets 540, 567
+    assert_almost_equal(stats.norm.cdf(-1.7624320982), 0.03899815971089126,
+                        decimal=10, err_msg='test_540_567')
+    assert_almost_equal(stats.norm.cdf(-1.7624320983), 0.038998159702449846,
+                        decimal=10, err_msg='test_540_567')
+    assert_almost_equal(stats.norm.cdf(1.38629436112, loc=0.950273420309,
+                                       scale=0.204423758009),
+                        0.98353464004309321,
+                        decimal=10, err_msg='test_540_567')
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstrings stripped")
+def test_regression_ticket_1421():
+    assert_('pdf(x, mu, loc=0, scale=1)' not in stats.poisson.__doc__)
+    assert_('pmf(x,' in stats.poisson.__doc__)
+
+
+def test_nan_arguments_gh_issue_1362():
+    with np.errstate(invalid='ignore'):
+        assert_(np.isnan(stats.t.logcdf(1, np.nan)))
+        assert_(np.isnan(stats.t.cdf(1, np.nan)))
+        assert_(np.isnan(stats.t.logsf(1, np.nan)))
+        assert_(np.isnan(stats.t.sf(1, np.nan)))
+        assert_(np.isnan(stats.t.pdf(1, np.nan)))
+        assert_(np.isnan(stats.t.logpdf(1, np.nan)))
+        assert_(np.isnan(stats.t.ppf(1, np.nan)))
+        assert_(np.isnan(stats.t.isf(1, np.nan)))
+
+        assert_(np.isnan(stats.bernoulli.logcdf(np.nan, 0.5)))
+        assert_(np.isnan(stats.bernoulli.cdf(np.nan, 0.5)))
+        assert_(np.isnan(stats.bernoulli.logsf(np.nan, 0.5)))
+        assert_(np.isnan(stats.bernoulli.sf(np.nan, 0.5)))
+        assert_(np.isnan(stats.bernoulli.pmf(np.nan, 0.5)))
+        assert_(np.isnan(stats.bernoulli.logpmf(np.nan, 0.5)))
+        assert_(np.isnan(stats.bernoulli.ppf(np.nan, 0.5)))
+        assert_(np.isnan(stats.bernoulli.isf(np.nan, 0.5)))
+
+
+def test_frozen_fit_ticket_1536():
+    np.random.seed(5678)
+    true = np.array([0.25, 0., 0.5])
+    x = stats.lognorm.rvs(true[0], true[1], true[2], size=100)
+
+    with np.errstate(divide='ignore'):
+        params = np.array(stats.lognorm.fit(x, floc=0.))
+
+    assert_almost_equal(params, true, decimal=2)
+
+    params = np.array(stats.lognorm.fit(x, fscale=0.5, loc=0))
+    assert_almost_equal(params, true, decimal=2)
+
+    params = np.array(stats.lognorm.fit(x, f0=0.25, loc=0))
+    assert_almost_equal(params, true, decimal=2)
+
+    params = np.array(stats.lognorm.fit(x, f0=0.25, floc=0))
+    assert_almost_equal(params, true, decimal=2)
+
+    np.random.seed(5678)
+    loc = 1
+    floc = 0.9
+    x = stats.norm.rvs(loc, 2., size=100)
+    params = np.array(stats.norm.fit(x, floc=floc))
+    expected = np.array([floc, np.sqrt(((x-floc)**2).mean())])
+    assert_almost_equal(params, expected, decimal=4)
+
+
+def test_regression_ticket_1530():
+    # Check the starting value works for Cauchy distribution fit.
+    np.random.seed(654321)
+    rvs = stats.cauchy.rvs(size=100)
+    params = stats.cauchy.fit(rvs)
+    expected = (0.045, 1.142)
+    assert_almost_equal(params, expected, decimal=1)
+
+
+def test_gh_pr_4806():
+    # Check starting values for Cauchy distribution fit.
+    np.random.seed(1234)
+    x = np.random.randn(42)
+    for offset in 10000.0, 1222333444.0:
+        loc, scale = stats.cauchy.fit(x + offset)
+        assert_allclose(loc, offset, atol=1.0)
+        assert_allclose(scale, 0.6, atol=1.0)
+
+
+def test_poisson_logpmf_ticket_1436():
+    assert_(np.isfinite(stats.poisson.logpmf(1500, 200)))
+
+
+def test_powerlaw_stats():
+    """Test the powerlaw stats function.
+
+    This unit test is also a regression test for ticket 1548.
+
+    The exact values are:
+    mean:
+        mu = a / (a + 1)
+    variance:
+        sigma**2 = a / ((a + 2) * (a + 1) ** 2)
+    skewness:
+        One formula (see https://en.wikipedia.org/wiki/Skewness) is
+            gamma_1 = (E[X**3] - 3*mu*E[X**2] + 2*mu**3) / sigma**3
+        A short calculation shows that E[X**k] is a / (a + k), so gamma_1
+        can be implemented as
+            n = a/(a+3) - 3*(a/(a+1))*a/(a+2) + 2*(a/(a+1))**3
+            d = sqrt(a/((a+2)*(a+1)**2)) ** 3
+            gamma_1 = n/d
+        Either by simplifying, or by a direct calculation of mu_3 / sigma**3,
+        one gets the more concise formula:
+            gamma_1 = -2.0 * ((a - 1) / (a + 3)) * sqrt((a + 2) / a)
+    kurtosis: (See https://en.wikipedia.org/wiki/Kurtosis)
+        The excess kurtosis is
+            gamma_2 = mu_4 / sigma**4 - 3
+        A bit of calculus and algebra (sympy helps) shows that
+            mu_4 = 3*a*(3*a**2 - a + 2) / ((a+1)**4 * (a+2) * (a+3) * (a+4))
+        so
+            gamma_2 = 3*(3*a**2 - a + 2) * (a+2) / (a*(a+3)*(a+4)) - 3
+        which can be rearranged to
+            gamma_2 = 6 * (a**3 - a**2 - 6*a + 2) / (a*(a+3)*(a+4))
+    """
+    cases = [(1.0, (0.5, 1./12, 0.0, -1.2)),
+             (2.0, (2./3, 2./36, -0.56568542494924734, -0.6))]
+    for a, exact_mvsk in cases:
+        mvsk = stats.powerlaw.stats(a, moments="mvsk")
+        assert_array_almost_equal(mvsk, exact_mvsk)
+
+
+def test_powerlaw_edge():
+    # Regression test for gh-3986.
+    p = stats.powerlaw.logpdf(0, 1)
+    assert_equal(p, 0.0)
+
+
+def test_exponpow_edge():
+    # Regression test for gh-3982.
+    p = stats.exponpow.logpdf(0, 1)
+    assert_equal(p, 0.0)
+
+    # Check pdf and logpdf at x = 0 for other values of b.
+    p = stats.exponpow.pdf(0, [0.25, 1.0, 1.5])
+    assert_equal(p, [np.inf, 1.0, 0.0])
+    p = stats.exponpow.logpdf(0, [0.25, 1.0, 1.5])
+    assert_equal(p, [np.inf, 0.0, -np.inf])
+
+
+def test_gengamma_edge():
+    # Regression test for gh-3985.
+    p = stats.gengamma.pdf(0, 1, 1)
+    assert_equal(p, 1.0)
+
+
+@pytest.mark.parametrize("a, c, ref, tol",
+                         [(1500000.0, 1, 8.529426144018633, 1e-15),
+                          (1e+30, 1, 35.95771492811536, 1e-15),
+                          (1e+100, 1, 116.54819318290696, 1e-15),
+                          (3e3, 1, 5.422011196659015, 1e-13),
+                          (3e6, -1e100, -236.29663213396054, 1e-15),
+                          (3e60, 1e-100, 1.3925371786831085e+102, 1e-15)])
+def test_gengamma_extreme_entropy(a, c, ref, tol):
+    # The reference values were calculated with mpmath:
+    # from mpmath import mp
+    # mp.dps = 500
+    #
+    # def gen_entropy(a, c):
+    #     a, c = mp.mpf(a), mp.mpf(c)
+    #     val = mp.digamma(a)
+    #     h = (a * (mp.one - val) + val/c + mp.loggamma(a) - mp.log(abs(c)))
+    #     return float(h)
+    assert_allclose(stats.gengamma.entropy(a, c), ref, rtol=tol)
+
+
+def test_gengamma_endpoint_with_neg_c():
+    p = stats.gengamma.pdf(0, 1, -1)
+    assert p == 0.0
+    logp = stats.gengamma.logpdf(0, 1, -1)
+    assert logp == -np.inf
+
+
+def test_gengamma_munp():
+    # Regression tests for gh-4724.
+    p = stats.gengamma._munp(-2, 200, 1.)
+    assert_almost_equal(p, 1./199/198)
+
+    p = stats.gengamma._munp(-2, 10, 1.)
+    assert_almost_equal(p, 1./9/8)
+
+
+def test_ksone_fit_freeze():
+    # Regression test for ticket #1638.
+    d = np.array(
+        [-0.18879233, 0.15734249, 0.18695107, 0.27908787, -0.248649,
+         -0.2171497, 0.12233512, 0.15126419, 0.03119282, 0.4365294,
+         0.08930393, -0.23509903, 0.28231224, -0.09974875, -0.25196048,
+         0.11102028, 0.1427649, 0.10176452, 0.18754054, 0.25826724,
+         0.05988819, 0.0531668, 0.21906056, 0.32106729, 0.2117662,
+         0.10886442, 0.09375789, 0.24583286, -0.22968366, -0.07842391,
+         -0.31195432, -0.21271196, 0.1114243, -0.13293002, 0.01331725,
+         -0.04330977, -0.09485776, -0.28434547, 0.22245721, -0.18518199,
+         -0.10943985, -0.35243174, 0.06897665, -0.03553363, -0.0701746,
+         -0.06037974, 0.37670779, -0.21684405])
+
+    with np.errstate(invalid='ignore'):
+        with suppress_warnings() as sup:
+            sup.filter(IntegrationWarning,
+                       "The maximum number of subdivisions .50. has been "
+                       "achieved.")
+            sup.filter(RuntimeWarning,
+                       "floating point number truncated to an integer")
+            stats.ksone.fit(d)
+
+
+def test_norm_logcdf():
+    # Test precision of the logcdf of the normal distribution.
+    # This precision was enhanced in ticket 1614.
+    x = -np.asarray(list(range(0, 120, 4)))
+    # Values from R
+    expected = [-0.69314718, -10.36010149, -35.01343716, -75.41067300,
+                -131.69539607, -203.91715537, -292.09872100, -396.25241451,
+                -516.38564863, -652.50322759, -804.60844201, -972.70364403,
+                -1156.79057310, -1356.87055173, -1572.94460885, -1805.01356068,
+                -2053.07806561, -2317.13866238, -2597.19579746, -2893.24984493,
+                -3205.30112136, -3533.34989701, -3877.39640444, -4237.44084522,
+                -4613.48339520, -5005.52420869, -5413.56342187, -5837.60115548,
+                -6277.63751711, -6733.67260303]
+
+    assert_allclose(stats.norm().logcdf(x), expected, atol=1e-8)
+
+    # also test the complex-valued code path
+    assert_allclose(stats.norm().logcdf(x + 1e-14j).real, expected, atol=1e-8)
+
+    # test the accuracy: d(logcdf)/dx = pdf / cdf \equiv exp(logpdf - logcdf)
+    deriv = (stats.norm.logcdf(x + 1e-10j)/1e-10).imag
+    deriv_expected = np.exp(stats.norm.logpdf(x) - stats.norm.logcdf(x))
+    assert_allclose(deriv, deriv_expected, atol=1e-10)
+
+
+def test_levy_l_sf():
+    # Test levy_l.sf for small arguments.
+    x = np.array([-0.016, -0.01, -0.005, -0.0015])
+    # Expected values were calculated with mpmath.
+    expected = np.array([2.6644463892359302e-15,
+                         1.523970604832107e-23,
+                         2.0884875837625492e-45,
+                         5.302850374626878e-147])
+    y = stats.levy_l.sf(x)
+    assert_allclose(y, expected, rtol=1e-13)
+
+
+def test_levy_l_isf():
+    # Test roundtrip sf(isf(p)), including a small input value.
+    p = np.array([3.0e-15, 0.25, 0.99])
+    x = stats.levy_l.isf(p)
+    q = stats.levy_l.sf(x)
+    assert_allclose(q, p, rtol=5e-14)
+
+
+def test_hypergeom_interval_1802():
+    # these two had endless loops
+    assert_equal(stats.hypergeom.interval(.95, 187601, 43192, 757),
+                 (152.0, 197.0))
+    assert_equal(stats.hypergeom.interval(.945, 187601, 43192, 757),
+                 (152.0, 197.0))
+    # this was working also before
+    assert_equal(stats.hypergeom.interval(.94, 187601, 43192, 757),
+                 (153.0, 196.0))
+
+    # degenerate case .a == .b
+    assert_equal(stats.hypergeom.ppf(0.02, 100, 100, 8), 8)
+    assert_equal(stats.hypergeom.ppf(1, 100, 100, 8), 8)
+
+
+def test_distribution_too_many_args():
+    np.random.seed(1234)
+
+    # Check that a TypeError is raised when too many args are given to a method
+    # Regression test for ticket 1815.
+    x = np.linspace(0.1, 0.7, num=5)
+    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0)
+    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, loc=1.0)
+    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, 4, 5)
+    assert_raises(TypeError, stats.gamma.pdf, x, 2, 3, loc=1.0, scale=0.5)
+    assert_raises(TypeError, stats.gamma.rvs, 2., 3, loc=1.0, scale=0.5)
+    assert_raises(TypeError, stats.gamma.cdf, x, 2., 3, loc=1.0, scale=0.5)
+    assert_raises(TypeError, stats.gamma.ppf, x, 2., 3, loc=1.0, scale=0.5)
+    assert_raises(TypeError, stats.gamma.stats, 2., 3, loc=1.0, scale=0.5)
+    assert_raises(TypeError, stats.gamma.entropy, 2., 3, loc=1.0, scale=0.5)
+    assert_raises(TypeError, stats.gamma.fit, x, 2., 3, loc=1.0, scale=0.5)
+
+    # These should not give errors
+    stats.gamma.pdf(x, 2, 3)  # loc=3
+    stats.gamma.pdf(x, 2, 3, 4)  # loc=3, scale=4
+    stats.gamma.stats(2., 3)
+    stats.gamma.stats(2., 3, 4)
+    stats.gamma.stats(2., 3, 4, 'mv')
+    stats.gamma.rvs(2., 3, 4, 5)
+    stats.gamma.fit(stats.gamma.rvs(2., size=7), 2.)
+
+    # Also for a discrete distribution
+    stats.geom.pmf(x, 2, loc=3)  # no error, loc=3
+    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, 4)
+    assert_raises(TypeError, stats.geom.pmf, x, 2, 3, loc=4)
+
+    # And for distributions with 0, 2 and 3 args respectively
+    assert_raises(TypeError, stats.expon.pdf, x, 3, loc=1.0)
+    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, loc=1.0)
+    assert_raises(TypeError, stats.exponweib.pdf, x, 3, 4, 5, 0.1, 0.1)
+    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, loc=1.0)
+    assert_raises(TypeError, stats.ncf.pdf, x, 3, 4, 5, 6, 1.0, scale=0.5)
+    stats.ncf.pdf(x, 3, 4, 5, 6, 1.0)  # 3 args, plus loc/scale
+
+
+def test_ncx2_tails_ticket_955():
+    # Trac #955 -- check that the cdf computed by special functions
+    # matches the integrated pdf
+    a = stats.ncx2.cdf(np.arange(20, 25, 0.2), 2, 1.07458615e+02)
+    b = stats.ncx2._cdfvec(np.arange(20, 25, 0.2), 2, 1.07458615e+02)
+    assert_allclose(a, b, rtol=1e-3, atol=0)
+
+
+def test_ncx2_tails_pdf():
+    # ncx2.pdf does not return nans in extreme tails(example from gh-1577)
+    # NB: this is to check that nan_to_num is not needed in ncx2.pdf
+    with warnings.catch_warnings():
+        warnings.simplefilter('error', RuntimeWarning)
+        assert_equal(stats.ncx2.pdf(1, np.arange(340, 350), 2), 0)
+        logval = stats.ncx2.logpdf(1, np.arange(340, 350), 2)
+
+    assert_(np.isneginf(logval).all())
+
+    # Verify logpdf has extended precision when pdf underflows to 0
+    with warnings.catch_warnings():
+        warnings.simplefilter('error', RuntimeWarning)
+        assert_equal(stats.ncx2.pdf(10000, 3, 12), 0)
+        assert_allclose(stats.ncx2.logpdf(10000, 3, 12), -4662.444377524883)
+
+
+@pytest.mark.parametrize('method, expected', [
+    ('cdf', np.array([2.497951336e-09, 3.437288941e-10])),
+    ('pdf', np.array([1.238579980e-07, 1.710041145e-08])),
+    ('logpdf', np.array([-15.90413011, -17.88416331])),
+    ('ppf', np.array([4.865182052, 7.017182271]))
+])
+def test_ncx2_zero_nc(method, expected):
+    # gh-5441
+    # ncx2 with nc=0 is identical to chi2
+    # Comparison to R (v3.5.1)
+    # > options(digits=10)
+    # > pchisq(0.1, df=10, ncp=c(0,4))
+    # > dchisq(0.1, df=10, ncp=c(0,4))
+    # > dchisq(0.1, df=10, ncp=c(0,4), log=TRUE)
+    # > qchisq(0.1, df=10, ncp=c(0,4))
+
+    result = getattr(stats.ncx2, method)(0.1, nc=[0, 4], df=10)
+    assert_allclose(result, expected, atol=1e-15)
+
+
+def test_ncx2_zero_nc_rvs():
+    # gh-5441
+    # ncx2 with nc=0 is identical to chi2
+    result = stats.ncx2.rvs(df=10, nc=0, random_state=1)
+    expected = stats.chi2.rvs(df=10, random_state=1)
+    assert_allclose(result, expected, atol=1e-15)
+
+
+def test_ncx2_gh12731():
+    # test that gh-12731 is resolved; previously these were all 0.5
+    nc = 10**np.arange(5, 10)
+    assert_equal(stats.ncx2.cdf(1e4, df=1, nc=nc), 0)
+
+
+def test_ncx2_gh8665():
+    # test that gh-8665 is resolved; previously this tended to nonzero value
+    x = np.array([4.99515382e+00, 1.07617327e+01, 2.31854502e+01,
+                  4.99515382e+01, 1.07617327e+02, 2.31854502e+02,
+                  4.99515382e+02, 1.07617327e+03, 2.31854502e+03,
+                  4.99515382e+03, 1.07617327e+04, 2.31854502e+04,
+                  4.99515382e+04])
+    nu, lam = 20, 499.51538166556196
+
+    sf = stats.ncx2.sf(x, df=nu, nc=lam)
+    # computed in R. Couldn't find a survival function implementation
+    # options(digits=16)
+    # x <- c(4.99515382e+00, 1.07617327e+01, 2.31854502e+01, 4.99515382e+01,
+    #        1.07617327e+02, 2.31854502e+02, 4.99515382e+02, 1.07617327e+03,
+    #        2.31854502e+03, 4.99515382e+03, 1.07617327e+04, 2.31854502e+04,
+    #        4.99515382e+04)
+    # nu <- 20
+    # lam <- 499.51538166556196
+    # 1 - pchisq(x, df = nu, ncp = lam)
+    sf_expected = [1.0000000000000000, 1.0000000000000000, 1.0000000000000000,
+                   1.0000000000000000, 1.0000000000000000, 0.9999999999999888,
+                   0.6646525582135460, 0.0000000000000000, 0.0000000000000000,
+                   0.0000000000000000, 0.0000000000000000, 0.0000000000000000,
+                   0.0000000000000000]
+    assert_allclose(sf, sf_expected, atol=1e-12)
+
+
+def test_ncx2_gh11777():
+    # regression test for gh-11777:
+    # At high values of degrees of freedom df, ensure the pdf of ncx2 does
+    # not get clipped to zero when the non-centrality parameter is
+    # sufficiently less than df
+    df = 6700
+    nc = 5300
+    x = np.linspace(stats.ncx2.ppf(0.001, df, nc),
+                    stats.ncx2.ppf(0.999, df, nc), num=10000)
+    ncx2_pdf = stats.ncx2.pdf(x, df, nc)
+    gauss_approx = stats.norm.pdf(x, df + nc, np.sqrt(2 * df + 4 * nc))
+    # use huge tolerance as we're only looking for obvious discrepancy
+    assert_allclose(ncx2_pdf, gauss_approx, atol=1e-4)
+
+
+# Expected values for foldnorm.sf were computed with mpmath:
+#
+#    from mpmath import mp
+#    mp.dps = 60
+#    def foldcauchy_sf(x, c):
+#        x = mp.mpf(x)
+#        c = mp.mpf(c)
+#        return mp.one - (mp.atan(x - c) + mp.atan(x + c))/mp.pi
+#
+# E.g.
+#
+#    >>> float(foldcauchy_sf(2, 1))
+#    0.35241638234956674
+#
+@pytest.mark.parametrize('x, c, expected',
+                         [(2, 1, 0.35241638234956674),
+                          (2, 2, 0.5779791303773694),
+                          (1e13, 1, 6.366197723675813e-14),
+                          (2e16, 1, 3.183098861837907e-17),
+                          (1e13, 2e11, 6.368745221764519e-14),
+                          (0.125, 200, 0.999998010612169)])
+def test_foldcauchy_sf(x, c, expected):
+    sf = stats.foldcauchy.sf(x, c)
+    assert_allclose(sf, expected, 2e-15)
+
+
+# The same mpmath code shown in the comments above test_foldcauchy_sf()
+# is used to create these expected values.
+@pytest.mark.parametrize('x, expected',
+                         [(2, 0.2951672353008665),
+                          (1e13, 6.366197723675813e-14),
+                          (2e16, 3.183098861837907e-17),
+                          (5e80, 1.2732395447351629e-81)])
+def test_halfcauchy_sf(x, expected):
+    sf = stats.halfcauchy.sf(x)
+    assert_allclose(sf, expected, 2e-15)
+
+
+# Expected value computed with mpmath:
+#     expected = mp.cot(mp.pi*p/2)
+@pytest.mark.parametrize('p, expected',
+                         [(0.9999995, 7.853981633329977e-07),
+                          (0.975, 0.039290107007669675),
+                          (0.5, 1.0),
+                          (0.01, 63.65674116287158),
+                          (1e-14, 63661977236758.13),
+                          (5e-80, 1.2732395447351627e+79)])
+def test_halfcauchy_isf(p, expected):
+    x = stats.halfcauchy.isf(p)
+    assert_allclose(x, expected)
+
+
+def test_foldnorm_zero():
+    # Parameter value c=0 was not enabled, see gh-2399.
+    rv = stats.foldnorm(0, scale=1)
+    assert_equal(rv.cdf(0), 0)  # rv.cdf(0) previously resulted in: nan
+
+
+# Expected values for foldnorm.sf were computed with mpmath:
+#
+#    from mpmath import mp
+#    mp.dps = 60
+#    def foldnorm_sf(x, c):
+#        x = mp.mpf(x)
+#        c = mp.mpf(c)
+#        return mp.ncdf(-x+c) + mp.ncdf(-x-c)
+#
+# E.g.
+#
+#    >>> float(foldnorm_sf(2, 1))
+#    0.16000515196308715
+#
+@pytest.mark.parametrize('x, c, expected',
+                         [(2, 1, 0.16000515196308715),
+                          (20, 1, 8.527223952630977e-81),
+                          (10, 15, 0.9999997133484281),
+                          (25, 15, 7.619853024160525e-24)])
+def test_foldnorm_sf(x, c, expected):
+    sf = stats.foldnorm.sf(x, c)
+    assert_allclose(sf, expected, 1e-14)
+
+
+def test_stats_shapes_argcheck():
+    # stats method was failing for vector shapes if some of the values
+    # were outside of the allowed range, see gh-2678
+    mv3 = stats.invgamma.stats([0.0, 0.5, 1.0], 1, 0.5)  # 0 is not a legal `a`
+    mv2 = stats.invgamma.stats([0.5, 1.0], 1, 0.5)
+    mv2_augmented = tuple(np.r_[np.nan, _] for _ in mv2)
+    assert_equal(mv2_augmented, mv3)
+
+    # -1 is not a legal shape parameter
+    mv3 = stats.lognorm.stats([2, 2.4, -1])
+    mv2 = stats.lognorm.stats([2, 2.4])
+    mv2_augmented = tuple(np.r_[_, np.nan] for _ in mv2)
+    assert_equal(mv2_augmented, mv3)
+
+    # FIXME: this is only a quick-and-dirty test of a quick-and-dirty bugfix.
+    # stats method with multiple shape parameters is not properly vectorized
+    # anyway, so some distributions may or may not fail.
+
+
+# Test subclassing distributions w/ explicit shapes
+
+class _distr_gen(stats.rv_continuous):
+    def _pdf(self, x, a):
+        return 42
+
+
+class _distr2_gen(stats.rv_continuous):
+    def _cdf(self, x, a):
+        return 42 * a + x
+
+
+class _distr3_gen(stats.rv_continuous):
+    def _pdf(self, x, a, b):
+        return a + b
+
+    def _cdf(self, x, a):
+        # Different # of shape params from _pdf, to be able to check that
+        # inspection catches the inconsistency.
+        return 42 * a + x
+
+
+class _distr6_gen(stats.rv_continuous):
+    # Two shape parameters (both _pdf and _cdf defined, consistent shapes.)
+    def _pdf(self, x, a, b):
+        return a*x + b
+
+    def _cdf(self, x, a, b):
+        return 42 * a + x
+
+
+class TestSubclassingExplicitShapes:
+    # Construct a distribution w/ explicit shapes parameter and test it.
+
+    def test_correct_shapes(self):
+        dummy_distr = _distr_gen(name='dummy', shapes='a')
+        assert_equal(dummy_distr.pdf(1, a=1), 42)
+
+    def test_wrong_shapes_1(self):
+        dummy_distr = _distr_gen(name='dummy', shapes='A')
+        assert_raises(TypeError, dummy_distr.pdf, 1, **dict(a=1))
+
+    def test_wrong_shapes_2(self):
+        dummy_distr = _distr_gen(name='dummy', shapes='a, b, c')
+        dct = dict(a=1, b=2, c=3)
+        assert_raises(TypeError, dummy_distr.pdf, 1, **dct)
+
+    def test_shapes_string(self):
+        # shapes must be a string
+        dct = dict(name='dummy', shapes=42)
+        assert_raises(TypeError, _distr_gen, **dct)
+
+    def test_shapes_identifiers_1(self):
+        # shapes must be a comma-separated list of valid python identifiers
+        dct = dict(name='dummy', shapes='(!)')
+        assert_raises(SyntaxError, _distr_gen, **dct)
+
+    def test_shapes_identifiers_2(self):
+        dct = dict(name='dummy', shapes='4chan')
+        assert_raises(SyntaxError, _distr_gen, **dct)
+
+    def test_shapes_identifiers_3(self):
+        dct = dict(name='dummy', shapes='m(fti)')
+        assert_raises(SyntaxError, _distr_gen, **dct)
+
+    def test_shapes_identifiers_nodefaults(self):
+        dct = dict(name='dummy', shapes='a=2')
+        assert_raises(SyntaxError, _distr_gen, **dct)
+
+    def test_shapes_args(self):
+        dct = dict(name='dummy', shapes='*args')
+        assert_raises(SyntaxError, _distr_gen, **dct)
+
+    def test_shapes_kwargs(self):
+        dct = dict(name='dummy', shapes='**kwargs')
+        assert_raises(SyntaxError, _distr_gen, **dct)
+
+    def test_shapes_keywords(self):
+        # python keywords cannot be used for shape parameters
+        dct = dict(name='dummy', shapes='a, b, c, lambda')
+        assert_raises(SyntaxError, _distr_gen, **dct)
+
+    def test_shapes_signature(self):
+        # test explicit shapes which agree w/ the signature of _pdf
+        class _dist_gen(stats.rv_continuous):
+            def _pdf(self, x, a):
+                return stats.norm._pdf(x) * a
+
+        dist = _dist_gen(shapes='a')
+        assert_equal(dist.pdf(0.5, a=2), stats.norm.pdf(0.5)*2)
+
+    def test_shapes_signature_inconsistent(self):
+        # test explicit shapes which do not agree w/ the signature of _pdf
+        class _dist_gen(stats.rv_continuous):
+            def _pdf(self, x, a):
+                return stats.norm._pdf(x) * a
+
+        dist = _dist_gen(shapes='a, b')
+        assert_raises(TypeError, dist.pdf, 0.5, **dict(a=1, b=2))
+
+    def test_star_args(self):
+        # test _pdf with only starargs
+        # NB: **kwargs of pdf will never reach _pdf
+        class _dist_gen(stats.rv_continuous):
+            def _pdf(self, x, *args):
+                extra_kwarg = args[0]
+                return stats.norm._pdf(x) * extra_kwarg
+
+        dist = _dist_gen(shapes='extra_kwarg')
+        assert_equal(dist.pdf(0.5, extra_kwarg=33), stats.norm.pdf(0.5)*33)
+        assert_equal(dist.pdf(0.5, 33), stats.norm.pdf(0.5)*33)
+        assert_raises(TypeError, dist.pdf, 0.5, **dict(xxx=33))
+
+    def test_star_args_2(self):
+        # test _pdf with named & starargs
+        # NB: **kwargs of pdf will never reach _pdf
+        class _dist_gen(stats.rv_continuous):
+            def _pdf(self, x, offset, *args):
+                extra_kwarg = args[0]
+                return stats.norm._pdf(x) * extra_kwarg + offset
+
+        dist = _dist_gen(shapes='offset, extra_kwarg')
+        assert_equal(dist.pdf(0.5, offset=111, extra_kwarg=33),
+                     stats.norm.pdf(0.5)*33 + 111)
+        assert_equal(dist.pdf(0.5, 111, 33),
+                     stats.norm.pdf(0.5)*33 + 111)
+
+    def test_extra_kwarg(self):
+        # **kwargs to _pdf are ignored.
+        # this is a limitation of the framework (_pdf(x, *goodargs))
+        class _distr_gen(stats.rv_continuous):
+            def _pdf(self, x, *args, **kwargs):
+                # _pdf should handle *args, **kwargs itself.  Here "handling"
+                # is ignoring *args and looking for ``extra_kwarg`` and using
+                # that.
+                extra_kwarg = kwargs.pop('extra_kwarg', 1)
+                return stats.norm._pdf(x) * extra_kwarg
+
+        dist = _distr_gen(shapes='extra_kwarg')
+        assert_equal(dist.pdf(1, extra_kwarg=3), stats.norm.pdf(1))
+
+    def test_shapes_empty_string(self):
+        # shapes='' is equivalent to shapes=None
+        class _dist_gen(stats.rv_continuous):
+            def _pdf(self, x):
+                return stats.norm.pdf(x)
+
+        dist = _dist_gen(shapes='')
+        assert_equal(dist.pdf(0.5), stats.norm.pdf(0.5))
+
+
+class TestSubclassingNoShapes:
+    # Construct a distribution w/o explicit shapes parameter and test it.
+
+    def test_only__pdf(self):
+        dummy_distr = _distr_gen(name='dummy')
+        assert_equal(dummy_distr.pdf(1, a=1), 42)
+
+    def test_only__cdf(self):
+        # _pdf is determined from _cdf by taking numerical derivative
+        dummy_distr = _distr2_gen(name='dummy')
+        assert_almost_equal(dummy_distr.pdf(1, a=1), 1)
+
+    @pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstring stripped")
+    def test_signature_inspection(self):
+        # check that _pdf signature inspection works correctly, and is used in
+        # the class docstring
+        dummy_distr = _distr_gen(name='dummy')
+        assert_equal(dummy_distr.numargs, 1)
+        assert_equal(dummy_distr.shapes, 'a')
+        res = re.findall(r'logpdf\(x, a, loc=0, scale=1\)',
+                         dummy_distr.__doc__)
+        assert_(len(res) == 1)
+
+    @pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstring stripped")
+    def test_signature_inspection_2args(self):
+        # same for 2 shape params and both _pdf and _cdf defined
+        dummy_distr = _distr6_gen(name='dummy')
+        assert_equal(dummy_distr.numargs, 2)
+        assert_equal(dummy_distr.shapes, 'a, b')
+        res = re.findall(r'logpdf\(x, a, b, loc=0, scale=1\)',
+                         dummy_distr.__doc__)
+        assert_(len(res) == 1)
+
+    def test_signature_inspection_2args_incorrect_shapes(self):
+        # both _pdf and _cdf defined, but shapes are inconsistent: raises
+        assert_raises(TypeError, _distr3_gen, name='dummy')
+
+    def test_defaults_raise(self):
+        # default arguments should raise
+        class _dist_gen(stats.rv_continuous):
+            def _pdf(self, x, a=42):
+                return 42
+        assert_raises(TypeError, _dist_gen, **dict(name='dummy'))
+
+    def test_starargs_raise(self):
+        # without explicit shapes, *args are not allowed
+        class _dist_gen(stats.rv_continuous):
+            def _pdf(self, x, a, *args):
+                return 42
+        assert_raises(TypeError, _dist_gen, **dict(name='dummy'))
+
+    def test_kwargs_raise(self):
+        # without explicit shapes, **kwargs are not allowed
+        class _dist_gen(stats.rv_continuous):
+            def _pdf(self, x, a, **kwargs):
+                return 42
+        assert_raises(TypeError, _dist_gen, **dict(name='dummy'))
+
+
+@pytest.mark.skipif(DOCSTRINGS_STRIPPED, reason="docstring stripped")
+def test_docstrings():
+    badones = [r',\s*,', r'\(\s*,', r'^\s*:']
+    for distname in stats.__all__:
+        dist = getattr(stats, distname)
+        if isinstance(dist, (stats.rv_discrete | stats.rv_continuous)):
+            for regex in badones:
+                assert_(re.search(regex, dist.__doc__) is None)
+
+
+def test_infinite_input():
+    assert_almost_equal(stats.skellam.sf(np.inf, 10, 11), 0)
+    assert_almost_equal(stats.ncx2._cdf(np.inf, 8, 0.1), 1)
+
+
+def test_lomax_accuracy():
+    # regression test for gh-4033
+    p = stats.lomax.ppf(stats.lomax.cdf(1e-100, 1), 1)
+    assert_allclose(p, 1e-100)
+
+
+def test_truncexpon_accuracy():
+    # regression test for gh-4035
+    p = stats.truncexpon.ppf(stats.truncexpon.cdf(1e-100, 1), 1)
+    assert_allclose(p, 1e-100)
+
+
+def test_rayleigh_accuracy():
+    # regression test for gh-4034
+    p = stats.rayleigh.isf(stats.rayleigh.sf(9, 1), 1)
+    assert_almost_equal(p, 9.0, decimal=15)
+
+
+def test_genextreme_give_no_warnings():
+    """regression test for gh-6219"""
+
+    with warnings.catch_warnings(record=True) as w:
+        warnings.simplefilter("always")
+
+        stats.genextreme.cdf(.5, 0)
+        stats.genextreme.pdf(.5, 0)
+        stats.genextreme.ppf(.5, 0)
+        stats.genextreme.logpdf(-np.inf, 0.0)
+        number_of_warnings_thrown = len(w)
+        assert_equal(number_of_warnings_thrown, 0)
+
+
+def test_moments_gh22400():
+    # Regression test for gh-22400
+    # Check for correct results at c=0 with no warnings. While we're at it,
+    # check that NaN and sufficiently negative input produce NaNs, and output
+    # with `c=1` also agrees with reference values.
+    res = np.asarray(stats.genextreme.stats([0.0, np.nan, 1, -1.5], moments='mvsk'))
+
+    # Reference values for c=0 (Wikipedia)
+    mean = np.euler_gamma
+    var = np.pi**2 / 6
+    skew = 12 * np.sqrt(6) * special.zeta(3) / np.pi**3
+    kurt = 12 / 5
+    ref_0 = [mean, var, skew, kurt]
+    ref_1 = ref_3 = [np.nan]*4
+    ref_2 = [0, 1, -2, 6]  # Wolfram Alpha, MaxStableDistribution[0, 1, -1]
+
+    assert_allclose(res[:, 0], ref_0, rtol=1e-14)
+    assert_equal(res[:, 1], ref_1)
+    assert_allclose(res[:, 2], ref_2, rtol=1e-14)
+    assert_equal(res[:, 3], ref_3)
+
+
+def test_genextreme_entropy():
+    # regression test for gh-5181
+    euler_gamma = 0.5772156649015329
+
+    h = stats.genextreme.entropy(-1.0)
+    assert_allclose(h, 2*euler_gamma + 1, rtol=1e-14)
+
+    h = stats.genextreme.entropy(0)
+    assert_allclose(h, euler_gamma + 1, rtol=1e-14)
+
+    h = stats.genextreme.entropy(1.0)
+    assert_equal(h, 1)
+
+    h = stats.genextreme.entropy(-2.0, scale=10)
+    assert_allclose(h, euler_gamma*3 + np.log(10) + 1, rtol=1e-14)
+
+    h = stats.genextreme.entropy(10)
+    assert_allclose(h, -9*euler_gamma + 1, rtol=1e-14)
+
+    h = stats.genextreme.entropy(-10)
+    assert_allclose(h, 11*euler_gamma + 1, rtol=1e-14)
+
+
+def test_genextreme_sf_isf():
+    # Expected values were computed using mpmath:
+    #
+    #    import mpmath
+    #
+    #    def mp_genextreme_sf(x, xi, mu=0, sigma=1):
+    #        # Formula from wikipedia, which has a sign convention for xi that
+    #        # is the opposite of scipy's shape parameter.
+    #        if xi != 0:
+    #            t = mpmath.power(1 + ((x - mu)/sigma)*xi, -1/xi)
+    #        else:
+    #            t = mpmath.exp(-(x - mu)/sigma)
+    #        return 1 - mpmath.exp(-t)
+    #
+    # >>> mpmath.mp.dps = 1000
+    # >>> s = mp_genextreme_sf(mpmath.mp.mpf("1e8"), mpmath.mp.mpf("0.125"))
+    # >>> float(s)
+    # 1.6777205262585625e-57
+    # >>> s = mp_genextreme_sf(mpmath.mp.mpf("7.98"), mpmath.mp.mpf("-0.125"))
+    # >>> float(s)
+    # 1.52587890625e-21
+    # >>> s = mp_genextreme_sf(mpmath.mp.mpf("7.98"), mpmath.mp.mpf("0"))
+    # >>> float(s)
+    # 0.00034218086528426593
+
+    x = 1e8
+    s = stats.genextreme.sf(x, -0.125)
+    assert_allclose(s, 1.6777205262585625e-57)
+    x2 = stats.genextreme.isf(s, -0.125)
+    assert_allclose(x2, x)
+
+    x = 7.98
+    s = stats.genextreme.sf(x, 0.125)
+    assert_allclose(s, 1.52587890625e-21)
+    x2 = stats.genextreme.isf(s, 0.125)
+    assert_allclose(x2, x)
+
+    x = 7.98
+    s = stats.genextreme.sf(x, 0)
+    assert_allclose(s, 0.00034218086528426593)
+    x2 = stats.genextreme.isf(s, 0)
+    assert_allclose(x2, x)
+
+
+def test_burr12_ppf_small_arg():
+    prob = 1e-16
+    quantile = stats.burr12.ppf(prob, 2, 3)
+    # The expected quantile was computed using mpmath:
+    #   >>> import mpmath
+    #   >>> mpmath.mp.dps = 100
+    #   >>> prob = mpmath.mpf('1e-16')
+    #   >>> c = mpmath.mpf(2)
+    #   >>> d = mpmath.mpf(3)
+    #   >>> float(((1-prob)**(-1/d) - 1)**(1/c))
+    #   5.7735026918962575e-09
+    assert_allclose(quantile, 5.7735026918962575e-09)
+
+
+def test_invweibull_fit():
+    """
+    Test fitting invweibull to data.
+
+    Here is a the same calculation in R:
+
+    > library(evd)
+    > library(fitdistrplus)
+    > x = c(1, 1.25, 2, 2.5, 2.8,  3, 3.8, 4, 5, 8, 10, 12, 64, 99)
+    > result = fitdist(x, 'frechet', control=list(reltol=1e-13),
+    +                  fix.arg=list(loc=0), start=list(shape=2, scale=3))
+    > result
+    Fitting of the distribution ' frechet ' by maximum likelihood
+    Parameters:
+          estimate Std. Error
+    shape 1.048482  0.2261815
+    scale 3.099456  0.8292887
+    Fixed parameters:
+        value
+    loc     0
+
+    """
+
+    def optimizer(func, x0, args=(), disp=0):
+        return fmin(func, x0, args=args, disp=disp, xtol=1e-12, ftol=1e-12)
+
+    x = np.array([1, 1.25, 2, 2.5, 2.8, 3, 3.8, 4, 5, 8, 10, 12, 64, 99])
+    c, loc, scale = stats.invweibull.fit(x, floc=0, optimizer=optimizer)
+    assert_allclose(c, 1.048482, rtol=5e-6)
+    assert loc == 0
+    assert_allclose(scale, 3.099456, rtol=5e-6)
+
+
+# Expected values were computed with mpmath.
+@pytest.mark.parametrize('x, c, expected',
+                         [(3, 1.5, 0.175064510070713299327),
+                          (2000, 1.5, 1.11802773877318715787e-5),
+                          (2000, 9.25, 2.92060308832269637092e-31),
+                          (1e15, 1.5, 3.16227766016837933199884e-23)])
+def test_invweibull_sf(x, c, expected):
+    computed = stats.invweibull.sf(x, c)
+    assert_allclose(computed, expected, rtol=1e-15)
+
+
+# Expected values were computed with mpmath.
+@pytest.mark.parametrize('p, c, expected',
+                         [(0.5, 2.5, 1.15789669836468183976),
+                          (3e-18, 5, 3195.77171838060906447)])
+def test_invweibull_isf(p, c, expected):
+    computed = stats.invweibull.isf(p, c)
+    assert_allclose(computed, expected, rtol=1e-15)
+
+
+@pytest.mark.parametrize(
+    'df1,df2,x',
+    [(2, 2, [-0.5, 0.2, 1.0, 2.3]),
+     (4, 11, [-0.5, 0.2, 1.0, 2.3]),
+     (7, 17, [1, 2, 3, 4, 5])]
+)
+def test_ncf_edge_case(df1, df2, x):
+    # Test for edge case described in gh-11660.
+    # Non-central Fisher distribution when nc = 0
+    # should be the same as Fisher distribution.
+    nc = 0
+    expected_cdf = stats.f.cdf(x, df1, df2)
+    calculated_cdf = stats.ncf.cdf(x, df1, df2, nc)
+    assert_allclose(expected_cdf, calculated_cdf, rtol=1e-14)
+
+    # when ncf_gen._skip_pdf will be used instead of generic pdf,
+    # this additional test will be useful.
+    expected_pdf = stats.f.pdf(x, df1, df2)
+    calculated_pdf = stats.ncf.pdf(x, df1, df2, nc)
+    assert_allclose(expected_pdf, calculated_pdf, rtol=1e-6)
+
+
+def test_ncf_variance():
+    # Regression test for gh-10658 (incorrect variance formula for ncf).
+    # The correct value of ncf.var(2, 6, 4), 42.75, can be verified with, for
+    # example, Wolfram Alpha with the expression
+    #     Variance[NoncentralFRatioDistribution[2, 6, 4]]
+    # or with the implementation of the noncentral F distribution in the C++
+    # library Boost.
+    v = stats.ncf.var(2, 6, 4)
+    assert_allclose(v, 42.75, rtol=1e-14)
+
+
+def test_ncf_cdf_spotcheck():
+    # Regression test for gh-15582 testing against values from R/MATLAB
+    # Generate check_val from R or MATLAB as follows:
+    #          R: pf(20, df1 = 6, df2 = 33, ncp = 30.4) = 0.998921
+    #     MATLAB: ncfcdf(20, 6, 33, 30.4) = 0.998921
+    scipy_val = stats.ncf.cdf(20, 6, 33, 30.4)
+    check_val = 0.998921
+    assert_allclose(check_val, np.round(scipy_val, decimals=6))
+
+
+def test_ncf_ppf_issue_17026():
+    # Regression test for gh-17026
+    x = np.linspace(0, 1, 600)
+    x[0] = 1e-16
+    par = (0.1, 2, 5, 0, 1)
+    q = stats.ncf.ppf(x, *par)
+    q0 = [stats.ncf.ppf(xi, *par) for xi in x]
+    assert_allclose(q, q0)
+
+
+class TestHistogram:
+    def setup_method(self):
+        np.random.seed(1234)
+
+        # We have 8 bins
+        # [1,2), [2,3), [3,4), [4,5), [5,6), [6,7), [7,8), [8,9)
+        # But actually np.histogram will put the last 9 also in the [8,9) bin!
+        # Therefore there is a slight difference below for the last bin, from
+        # what you might have expected.
+        histogram = np.histogram([1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5,
+                                  6, 6, 6, 6, 7, 7, 7, 8, 8, 9], bins=8)
+        self.template = stats.rv_histogram(histogram)
+
+        data = stats.norm.rvs(loc=1.0, scale=2.5, size=10000, random_state=123)
+        norm_histogram = np.histogram(data, bins=50)
+        self.norm_template = stats.rv_histogram(norm_histogram)
+
+    def test_pdf(self):
+        values = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5,
+                           5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5])
+        pdf_values = np.asarray([0.0/25.0, 0.0/25.0, 1.0/25.0, 1.0/25.0,
+                                 2.0/25.0, 2.0/25.0, 3.0/25.0, 3.0/25.0,
+                                 4.0/25.0, 4.0/25.0, 5.0/25.0, 5.0/25.0,
+                                 4.0/25.0, 4.0/25.0, 3.0/25.0, 3.0/25.0,
+                                 3.0/25.0, 3.0/25.0, 0.0/25.0, 0.0/25.0])
+        assert_allclose(self.template.pdf(values), pdf_values)
+
+        # Test explicitly the corner cases:
+        # As stated above the pdf in the bin [8,9) is greater than
+        # one would naively expect because np.histogram putted the 9
+        # into the [8,9) bin.
+        assert_almost_equal(self.template.pdf(8.0), 3.0/25.0)
+        assert_almost_equal(self.template.pdf(8.5), 3.0/25.0)
+        # 9 is outside our defined bins [8,9) hence the pdf is already 0
+        # for a continuous distribution this is fine, because a single value
+        # does not have a finite probability!
+        assert_almost_equal(self.template.pdf(9.0), 0.0/25.0)
+        assert_almost_equal(self.template.pdf(10.0), 0.0/25.0)
+
+        x = np.linspace(-2, 2, 10)
+        assert_allclose(self.norm_template.pdf(x),
+                        stats.norm.pdf(x, loc=1.0, scale=2.5), rtol=0.1)
+
+    def test_cdf_ppf(self):
+        values = np.array([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5,
+                           5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5])
+        cdf_values = np.asarray([0.0/25.0, 0.0/25.0, 0.0/25.0, 0.5/25.0,
+                                 1.0/25.0, 2.0/25.0, 3.0/25.0, 4.5/25.0,
+                                 6.0/25.0, 8.0/25.0, 10.0/25.0, 12.5/25.0,
+                                 15.0/25.0, 17.0/25.0, 19.0/25.0, 20.5/25.0,
+                                 22.0/25.0, 23.5/25.0, 25.0/25.0, 25.0/25.0])
+        assert_allclose(self.template.cdf(values), cdf_values)
+        # First three and last two values in cdf_value are not unique
+        assert_allclose(self.template.ppf(cdf_values[2:-1]), values[2:-1])
+
+        # Test of cdf and ppf are inverse functions
+        x = np.linspace(1.0, 9.0, 100)
+        assert_allclose(self.template.ppf(self.template.cdf(x)), x)
+        x = np.linspace(0.0, 1.0, 100)
+        assert_allclose(self.template.cdf(self.template.ppf(x)), x)
+
+        x = np.linspace(-2, 2, 10)
+        assert_allclose(self.norm_template.cdf(x),
+                        stats.norm.cdf(x, loc=1.0, scale=2.5), rtol=0.1)
+
+    def test_rvs(self):
+        N = 10000
+        sample = self.template.rvs(size=N, random_state=123)
+        assert_equal(np.sum(sample < 1.0), 0.0)
+        assert_allclose(np.sum(sample <= 2.0), 1.0/25.0 * N, rtol=0.2)
+        assert_allclose(np.sum(sample <= 2.5), 2.0/25.0 * N, rtol=0.2)
+        assert_allclose(np.sum(sample <= 3.0), 3.0/25.0 * N, rtol=0.1)
+        assert_allclose(np.sum(sample <= 3.5), 4.5/25.0 * N, rtol=0.1)
+        assert_allclose(np.sum(sample <= 4.0), 6.0/25.0 * N, rtol=0.1)
+        assert_allclose(np.sum(sample <= 4.5), 8.0/25.0 * N, rtol=0.1)
+        assert_allclose(np.sum(sample <= 5.0), 10.0/25.0 * N, rtol=0.05)
+        assert_allclose(np.sum(sample <= 5.5), 12.5/25.0 * N, rtol=0.05)
+        assert_allclose(np.sum(sample <= 6.0), 15.0/25.0 * N, rtol=0.05)
+        assert_allclose(np.sum(sample <= 6.5), 17.0/25.0 * N, rtol=0.05)
+        assert_allclose(np.sum(sample <= 7.0), 19.0/25.0 * N, rtol=0.05)
+        assert_allclose(np.sum(sample <= 7.5), 20.5/25.0 * N, rtol=0.05)
+        assert_allclose(np.sum(sample <= 8.0), 22.0/25.0 * N, rtol=0.05)
+        assert_allclose(np.sum(sample <= 8.5), 23.5/25.0 * N, rtol=0.05)
+        assert_allclose(np.sum(sample <= 9.0), 25.0/25.0 * N, rtol=0.05)
+        assert_allclose(np.sum(sample <= 9.0), 25.0/25.0 * N, rtol=0.05)
+        assert_equal(np.sum(sample > 9.0), 0.0)
+
+    def test_munp(self):
+        for n in range(4):
+            assert_allclose(self.norm_template._munp(n),
+                            stats.norm(1.0, 2.5).moment(n), rtol=0.05)
+
+    def test_entropy(self):
+        assert_allclose(self.norm_template.entropy(),
+                        stats.norm.entropy(loc=1.0, scale=2.5), rtol=0.05)
+
+
+def test_histogram_non_uniform():
+    # Tests rv_histogram works even for non-uniform bin widths
+    counts, bins = ([1, 1], [0, 1, 1001])
+
+    dist = stats.rv_histogram((counts, bins), density=False)
+    np.testing.assert_allclose(dist.pdf([0.5, 200]), [0.5, 0.0005])
+    assert dist.median() == 1
+
+    dist = stats.rv_histogram((counts, bins), density=True)
+    np.testing.assert_allclose(dist.pdf([0.5, 200]), 1/1001)
+    assert dist.median() == 1001/2
+
+    # Omitting density produces a warning for non-uniform bins...
+    message = "Bin widths are not constant. Assuming..."
+    with pytest.warns(RuntimeWarning, match=message):
+        dist = stats.rv_histogram((counts, bins))
+        assert dist.median() == 1001/2  # default is like `density=True`
+
+    # ... but not for uniform bins
+    dist = stats.rv_histogram((counts, [0, 1, 2]))
+    assert dist.median() == 1
+
+
+class TestLogUniform:
+    def test_alias(self):
+        # This test makes sure that "reciprocal" and "loguniform" are
+        # aliases of the same distribution and that both are log-uniform
+        rng = np.random.default_rng(98643218961)
+        rv = stats.loguniform(10 ** -3, 10 ** 0)
+        rvs = rv.rvs(size=10000, random_state=rng)
+
+        rng = np.random.default_rng(98643218961)
+        rv2 = stats.reciprocal(10 ** -3, 10 ** 0)
+        rvs2 = rv2.rvs(size=10000, random_state=rng)
+
+        assert_allclose(rvs2, rvs)
+
+        vals, _ = np.histogram(np.log10(rvs), bins=10)
+        assert 900 <= vals.min() <= vals.max() <= 1100
+        assert np.abs(np.median(vals) - 1000) <= 10
+
+    @pytest.mark.parametrize("method", ['mle', 'mm'])
+    def test_fit_override(self, method):
+        # loguniform is overparameterized, so check that fit override enforces
+        # scale=1 unless fscale is provided by the user
+        rng = np.random.default_rng(98643218961)
+        rvs = stats.loguniform.rvs(0.1, 1, size=1000, random_state=rng)
+
+        a, b, loc, scale = stats.loguniform.fit(rvs, method=method)
+        assert scale == 1
+
+        a, b, loc, scale = stats.loguniform.fit(rvs, fscale=2, method=method)
+        assert scale == 2
+
+    def test_overflow(self):
+        # original formulation had overflow issues; check that this is resolved
+        # Extensive accuracy tests elsewhere, no need to test all methods
+        rng = np.random.default_rng(7136519550773909093)
+        a, b = 1e-200, 1e200
+        dist = stats.loguniform(a, b)
+
+        # test roundtrip error
+        cdf = rng.uniform(0, 1, size=1000)
+        assert_allclose(dist.cdf(dist.ppf(cdf)), cdf)
+        rvs = dist.rvs(size=1000)
+        assert_allclose(dist.ppf(dist.cdf(rvs)), rvs)
+
+        # test a property of the pdf (and that there is no overflow)
+        x = 10.**np.arange(-200, 200)
+        pdf = dist.pdf(x)  # no overflow
+        assert_allclose(pdf[:-1]/pdf[1:], 10)
+
+        # check munp against wikipedia reference
+        mean = (b - a)/(np.log(b) - np.log(a))
+        assert_allclose(dist.mean(), mean)
+
+
+class TestArgus:
+    def test_argus_rvs_large_chi(self):
+        # test that the algorithm can handle large values of chi
+        x = stats.argus.rvs(50, size=500, random_state=325)
+        assert_almost_equal(stats.argus(50).mean(), x.mean(), decimal=4)
+
+    @pytest.mark.parametrize('chi, random_state', [
+            [0.1, 325],   # chi <= 0.5: rejection method case 1
+            [1.3, 155],   # 0.5 < chi <= 1.8: rejection method case 2
+            [3.5, 135]    # chi > 1.8: transform conditional Gamma distribution
+        ])
+    def test_rvs(self, chi, random_state):
+        x = stats.argus.rvs(chi, size=500, random_state=random_state)
+        _, p = stats.kstest(x, "argus", (chi, ))
+        assert_(p > 0.05)
+
+    @pytest.mark.parametrize('chi', [1e-9, 1e-6])
+    def test_rvs_small_chi(self, chi):
+        # test for gh-11699 => rejection method case 1 can even handle chi=0
+        # the CDF of the distribution for chi=0 is 1 - (1 - x**2)**(3/2)
+        # test rvs against distribution of limit chi=0
+        r = stats.argus.rvs(chi, size=500, random_state=890981)
+        _, p = stats.kstest(r, lambda x: 1 - (1 - x**2)**(3/2))
+        assert_(p > 0.05)
+
+    # Expected values were computed with mpmath.
+    @pytest.mark.parametrize('chi, expected_mean',
+                             [(1, 0.6187026683551835),
+                              (10, 0.984805536783744),
+                              (40, 0.9990617659702923),
+                              (60, 0.9995831885165300),
+                              (99, 0.9998469348663028)])
+    def test_mean(self, chi, expected_mean):
+        m = stats.argus.mean(chi, scale=1)
+        assert_allclose(m, expected_mean, rtol=1e-13)
+
+    # Expected values were computed with mpmath.
+    @pytest.mark.parametrize('chi, expected_var, rtol',
+                             [(1, 0.05215651254197807, 1e-13),
+                              (10, 0.00015805472008165595, 1e-11),
+                              (40, 5.877763210262901e-07, 1e-8),
+                              (60, 1.1590179389611416e-07, 1e-8),
+                              (99, 1.5623277006064666e-08, 1e-8)])
+    def test_var(self, chi, expected_var, rtol):
+        v = stats.argus.var(chi, scale=1)
+        assert_allclose(v, expected_var, rtol=rtol)
+
+    # Expected values were computed with mpmath (code: see gh-13370).
+    @pytest.mark.parametrize('chi, expected, rtol',
+                             [(0.9, 0.07646314974436118, 1e-14),
+                              (0.5, 0.015429797891863365, 1e-14),
+                              (0.1, 0.0001325825293278049, 1e-14),
+                              (0.01, 1.3297677078224565e-07, 1e-15),
+                              (1e-3, 1.3298072023958999e-10, 1e-14),
+                              (1e-4, 1.3298075973486862e-13, 1e-14),
+                              (1e-6, 1.32980760133771e-19, 1e-14),
+                              (1e-9, 1.329807601338109e-28, 1e-15)])
+    def test_argus_phi_small_chi(self, chi, expected, rtol):
+        assert_allclose(_argus_phi(chi), expected, rtol=rtol)
+
+    # Expected values were computed with mpmath (code: see gh-13370).
+    @pytest.mark.parametrize(
+        'chi, expected',
+        [(0.5, (0.28414073302940573, 1.2742227939992954, 1.2381254688255896)),
+         (0.2, (0.296172952995264, 1.2951290588110516, 1.1865767100877576)),
+         (0.1, (0.29791447523536274, 1.29806307956989, 1.1793168289857412)),
+         (0.01, (0.2984904104866452, 1.2990283628160553, 1.1769268414080531)),
+         (1e-3, (0.298496172925224, 1.2990380082487925, 1.176902956021053)),
+         (1e-4, (0.29849623054991836, 1.2990381047023793, 1.1769027171686324)),
+         (1e-6, (0.2984962311319278, 1.2990381056765605, 1.1769027147562232)),
+         (1e-9, (0.298496231131986, 1.299038105676658, 1.1769027147559818))])
+    def test_pdf_small_chi(self, chi, expected):
+        x = np.array([0.1, 0.5, 0.9])
+        assert_allclose(stats.argus.pdf(x, chi), expected, rtol=1e-13)
+
+    # Expected values were computed with mpmath (code: see gh-13370).
+    @pytest.mark.parametrize(
+        'chi, expected',
+        [(0.5, (0.9857660526895221, 0.6616565930168475, 0.08796070398429937)),
+         (0.2, (0.9851555052359501, 0.6514666238985464, 0.08362690023746594)),
+         (0.1, (0.9850670974995661, 0.6500061310508574, 0.08302050640683846)),
+         (0.01, (0.9850378582451867, 0.6495239242251358, 0.08282109244852445)),
+         (1e-3, (0.9850375656906663, 0.6495191015522573, 0.08281910005231098)),
+         (1e-4, (0.9850375627651049, 0.6495190533254682, 0.08281908012852317)),
+         (1e-6, (0.9850375627355568, 0.6495190528383777, 0.08281907992729293)),
+         (1e-9, (0.9850375627355538, 0.649519052838329, 0.0828190799272728))])
+    def test_sf_small_chi(self, chi, expected):
+        x = np.array([0.1, 0.5, 0.9])
+        assert_allclose(stats.argus.sf(x, chi), expected, rtol=1e-14)
+
+    # Expected values were computed with mpmath.
+    @pytest.mark.parametrize(
+        'x, chi, expected',
+        [(0.9999999, 0.25, 9.113252974162428e-11),
+         (0.9999999, 3.0, 6.616650419714568e-10),
+         (0.999999999, 2.5, 4.130195911418939e-13),
+         (0.999999999, 10.0, 2.3788319094393724e-11)])
+    def test_sf_near_1(self, x, chi, expected):
+        sf = stats.argus.sf(x, chi)
+        assert_allclose(sf, expected, rtol=5e-15)
+
+    # Expected values were computed with mpmath (code: see gh-13370).
+    @pytest.mark.parametrize(
+        'chi, expected',
+        [(0.5, (0.0142339473104779, 0.3383434069831524, 0.9120392960157007)),
+         (0.2, (0.014844494764049919, 0.34853337610145363, 0.916373099762534)),
+         (0.1, (0.014932902500433911, 0.34999386894914264, 0.9169794935931616)),
+         (0.01, (0.014962141754813293, 0.35047607577486417, 0.9171789075514756)),
+         (1e-3, (0.01496243430933372, 0.35048089844774266, 0.917180899947689)),
+         (1e-4, (0.014962437234895118, 0.3504809466745317, 0.9171809198714769)),
+         (1e-6, (0.01496243726444329, 0.3504809471616223, 0.9171809200727071)),
+         (1e-9, (0.014962437264446245, 0.350480947161671, 0.9171809200727272))])
+    def test_cdf_small_chi(self, chi, expected):
+        x = np.array([0.1, 0.5, 0.9])
+        assert_allclose(stats.argus.cdf(x, chi), expected, rtol=1e-12)
+
+    # Expected values were computed with mpmath (code: see gh-13370).
+    @pytest.mark.parametrize(
+        'chi, expected, rtol',
+        [(0.5, (0.5964284712757741, 0.052890651988588604), 1e-12),
+         (0.101, (0.5893490968089076, 0.053017469847275685), 1e-11),
+         (0.1, (0.5893431757009437, 0.05301755449499372), 1e-13),
+         (0.01, (0.5890515677940915, 0.05302167905837031), 1e-13),
+         (1e-3, (0.5890486520005177, 0.053021719862088104), 1e-13),
+         (1e-4, (0.5890486228426105, 0.0530217202700811), 1e-13),
+         (1e-6, (0.5890486225481156, 0.05302172027420182), 1e-13),
+         (1e-9, (0.5890486225480862, 0.05302172027420224), 1e-13)])
+    def test_stats_small_chi(self, chi, expected, rtol):
+        val = stats.argus.stats(chi, moments='mv')
+        assert_allclose(val, expected, rtol=rtol)
+
+
+class TestNakagami:
+
+    def test_logpdf(self):
+        # Test nakagami logpdf for an input where the PDF is smaller
+        # than can be represented with 64 bit floating point.
+        # The expected value of logpdf was computed with mpmath:
+        #
+        #   def logpdf(x, nu):
+        #       x = mpmath.mpf(x)
+        #       nu = mpmath.mpf(nu)
+        #       return (mpmath.log(2) + nu*mpmath.log(nu) -
+        #               mpmath.loggamma(nu) + (2*nu - 1)*mpmath.log(x) -
+        #               nu*x**2)
+        #
+        nu = 2.5
+        x = 25
+        logp = stats.nakagami.logpdf(x, nu)
+        assert_allclose(logp, -1546.9253055607549)
+
+    def test_sf_isf(self):
+        # Test nakagami sf and isf when the survival function
+        # value is very small.
+        # The expected value of the survival function was computed
+        # with mpmath:
+        #
+        #   def sf(x, nu):
+        #       x = mpmath.mpf(x)
+        #       nu = mpmath.mpf(nu)
+        #       return mpmath.gammainc(nu, nu*x*x, regularized=True)
+        #
+        nu = 2.5
+        x0 = 5.0
+        sf = stats.nakagami.sf(x0, nu)
+        assert_allclose(sf, 2.736273158588307e-25, rtol=1e-13)
+        # Check round trip back to x0.
+        x1 = stats.nakagami.isf(sf, nu)
+        assert_allclose(x1, x0, rtol=1e-13)
+
+    def test_logcdf(self):
+        x = 8
+        nu = 0.5
+        # Reference value computed with mpmath.
+        ref = -1.2441921148543576e-15
+        logcdf = stats.nakagami.logcdf(x, nu)
+        assert_allclose(logcdf, ref, rtol=5e-15)
+
+    def test_logsf(self):
+        x = 0.05
+        nu = 12
+        # Reference value computed with mpmath.
+        ref = -1.0791764722337046e-27
+        logsf = stats.nakagami.logsf(x, nu)
+        assert_allclose(logsf, ref, rtol=5e-15)
+
+    @pytest.mark.parametrize("m, ref",
+        [(5, -0.097341814372152),
+         (0.5, 0.7257913526447274),
+         (10, -0.43426184310934907)])
+    def test_entropy(self, m, ref):
+        # from sympy import *
+        # from mpmath import mp
+        # import numpy as np
+        # v, x = symbols('v, x', real=True, positive=True)
+        # pdf = 2 * v ** v / gamma(v) * x ** (2 * v - 1) * exp(-v * x ** 2)
+        # h = simplify(simplify(integrate(-pdf * log(pdf), (x, 0, oo))))
+        # entropy = lambdify(v, h, 'mpmath')
+        # mp.dps = 200
+        # nu = 5
+        # ref = np.float64(entropy(mp.mpf(nu)))
+        # print(ref)
+        assert_allclose(stats.nakagami.entropy(m), ref, rtol=1.1e-14)
+
+    @pytest.mark.parametrize("m, ref",
+        [(1e-100, -5.0e+99), (1e-10, -4999999965.442979),
+         (9.999e6, -7.333206478668433), (1.001e7, -7.3337562313259825),
+         (1e10, -10.787134112333835), (1e100, -114.40346329705756)])
+    def test_extreme_nu(self, m, ref):
+        assert_allclose(stats.nakagami.entropy(m), ref)
+
+    def test_entropy_overflow(self):
+        assert np.isfinite(stats.nakagami._entropy(1e100))
+        assert np.isfinite(stats.nakagami._entropy(1e-100))
+
+    @pytest.mark.parametrize("nu, ref",
+                             [(1e10, 0.9999999999875),
+                              (1e3, 0.9998750078173821),
+                              (1e-10, 1.772453850659802e-05)])
+    def test_mean(self, nu, ref):
+        # reference values were computed with mpmath
+        # from mpmath import mp
+        # mp.dps = 500
+        # nu = mp.mpf(1e10)
+        # float(mp.rf(nu, mp.mpf(0.5))/mp.sqrt(nu))
+        assert_allclose(stats.nakagami.mean(nu), ref, rtol=1e-12)
+
+    @pytest.mark.xfail(reason="Fit of nakagami not reliable, see gh-10908.")
+    @pytest.mark.parametrize('nu', [1.6, 2.5, 3.9])
+    @pytest.mark.parametrize('loc', [25.0, 10, 35])
+    @pytest.mark.parametrize('scale', [13, 5, 20])
+    def test_fit(self, nu, loc, scale):
+        # Regression test for gh-13396 (21/27 cases failed previously)
+        # The first tuple of the parameters' values is discussed in gh-10908
+        N = 100
+        samples = stats.nakagami.rvs(size=N, nu=nu, loc=loc,
+                                     scale=scale, random_state=1337)
+        nu_est, loc_est, scale_est = stats.nakagami.fit(samples)
+        assert_allclose(nu_est, nu, rtol=0.2)
+        assert_allclose(loc_est, loc, rtol=0.2)
+        assert_allclose(scale_est, scale, rtol=0.2)
+
+        def dlogl_dnu(nu, loc, scale):
+            return ((-2*nu + 1) * np.sum(1/(samples - loc))
+                    + 2*nu/scale**2 * np.sum(samples - loc))
+
+        def dlogl_dloc(nu, loc, scale):
+            return (N * (1 + np.log(nu) - polygamma(0, nu)) +
+                    2 * np.sum(np.log((samples - loc) / scale))
+                    - np.sum(((samples - loc) / scale)**2))
+
+        def dlogl_dscale(nu, loc, scale):
+            return (- 2 * N * nu / scale
+                    + 2 * nu / scale ** 3 * np.sum((samples - loc) ** 2))
+
+        assert_allclose(dlogl_dnu(nu_est, loc_est, scale_est), 0, atol=1e-3)
+        assert_allclose(dlogl_dloc(nu_est, loc_est, scale_est), 0, atol=1e-3)
+        assert_allclose(dlogl_dscale(nu_est, loc_est, scale_est), 0, atol=1e-3)
+
+    @pytest.mark.parametrize('loc', [25.0, 10, 35])
+    @pytest.mark.parametrize('scale', [13, 5, 20])
+    def test_fit_nu(self, loc, scale):
+        # For nu = 0.5, we have analytical values for
+        # the MLE of the loc and the scale
+        nu = 0.5
+        n = 100
+        samples = stats.nakagami.rvs(size=n, nu=nu, loc=loc,
+                                     scale=scale, random_state=1337)
+        nu_est, loc_est, scale_est = stats.nakagami.fit(samples, f0=nu)
+
+        # Analytical values
+        loc_theo = np.min(samples)
+        scale_theo = np.sqrt(np.mean((samples - loc_est) ** 2))
+
+        assert_allclose(nu_est, nu, rtol=1e-7)
+        assert_allclose(loc_est, loc_theo, rtol=1e-7)
+        assert_allclose(scale_est, scale_theo, rtol=1e-7)
+
+
+class TestWrapCauchy:
+
+    def test_cdf_shape_broadcasting(self):
+        # Regression test for gh-13791.
+        # Check that wrapcauchy.cdf broadcasts the shape parameter
+        # correctly.
+        c = np.array([[0.03, 0.25], [0.5, 0.75]])
+        x = np.array([[1.0], [4.0]])
+        p = stats.wrapcauchy.cdf(x, c)
+        assert p.shape == (2, 2)
+        scalar_values = [stats.wrapcauchy.cdf(x1, c1)
+                         for (x1, c1) in np.nditer((x, c))]
+        assert_allclose(p.ravel(), scalar_values, rtol=1e-13)
+
+    def test_cdf_center(self):
+        p = stats.wrapcauchy.cdf(np.pi, 0.03)
+        assert_allclose(p, 0.5, rtol=1e-14)
+
+    def test_cdf(self):
+        x1 = 1.0  # less than pi
+        x2 = 4.0  # greater than pi
+        c = 0.75
+        p = stats.wrapcauchy.cdf([x1, x2], c)
+        cr = (1 + c)/(1 - c)
+        assert_allclose(p[0], np.arctan(cr*np.tan(x1/2))/np.pi)
+        assert_allclose(p[1], 1 - np.arctan(cr*np.tan(np.pi - x2/2))/np.pi)
+
+
+def test_rvs_no_size_error():
+    # _rvs methods must have parameter `size`; see gh-11394
+    class rvs_no_size_gen(stats.rv_continuous):
+        def _rvs(self):
+            return 1
+
+    rvs_no_size = rvs_no_size_gen(name='rvs_no_size')
+
+    with assert_raises(TypeError, match=r"_rvs\(\) got (an|\d) unexpected"):
+        rvs_no_size.rvs()
+
+
+@pytest.mark.parametrize('distname, args', invdistdiscrete + invdistcont)
+def test_support_gh13294_regression(distname, args):
+    if distname in skip_test_support_gh13294_regression:
+        pytest.skip(f"skipping test for the support method for "
+                    f"distribution {distname}.")
+    dist = getattr(stats, distname)
+    # test support method with invalid arguments
+    if isinstance(dist, stats.rv_continuous):
+        # test with valid scale
+        if len(args) != 0:
+            a0, b0 = dist.support(*args)
+            assert_equal(a0, np.nan)
+            assert_equal(b0, np.nan)
+        # test with invalid scale
+        # For some distributions, that take no parameters,
+        # the case of only invalid scale occurs and hence,
+        # it is implicitly tested in this test case.
+        loc1, scale1 = 0, -1
+        a1, b1 = dist.support(*args, loc1, scale1)
+        assert_equal(a1, np.nan)
+        assert_equal(b1, np.nan)
+    else:
+        a, b = dist.support(*args)
+        assert_equal(a, np.nan)
+        assert_equal(b, np.nan)
+
+
+def test_support_broadcasting_gh13294_regression():
+    a0, b0 = stats.norm.support([0, 0, 0, 1], [1, 1, 1, -1])
+    ex_a0 = np.array([-np.inf, -np.inf, -np.inf, np.nan])
+    ex_b0 = np.array([np.inf, np.inf, np.inf, np.nan])
+    assert_equal(a0, ex_a0)
+    assert_equal(b0, ex_b0)
+    assert a0.shape == ex_a0.shape
+    assert b0.shape == ex_b0.shape
+
+    a1, b1 = stats.norm.support([], [])
+    ex_a1, ex_b1 = np.array([]), np.array([])
+    assert_equal(a1, ex_a1)
+    assert_equal(b1, ex_b1)
+    assert a1.shape == ex_a1.shape
+    assert b1.shape == ex_b1.shape
+
+    a2, b2 = stats.norm.support([0, 0, 0, 1], [-1])
+    ex_a2 = np.array(4*[np.nan])
+    ex_b2 = np.array(4*[np.nan])
+    assert_equal(a2, ex_a2)
+    assert_equal(b2, ex_b2)
+    assert a2.shape == ex_a2.shape
+    assert b2.shape == ex_b2.shape
+
+
+def test_stats_broadcasting_gh14953_regression():
+    # test case in gh14953
+    loc = [0., 0.]
+    scale = [[1.], [2.], [3.]]
+    assert_equal(stats.norm.var(loc, scale), [[1., 1.], [4., 4.], [9., 9.]])
+    # test some edge cases
+    loc = np.empty((0, ))
+    scale = np.empty((1, 0))
+    assert stats.norm.var(loc, scale).shape == (1, 0)
+
+
+# Check a few values of the cosine distribution's cdf, sf, ppf and
+# isf methods.  Expected values were computed with mpmath.
+
+@pytest.mark.parametrize('x, expected',
+                         [(-3.14159, 4.956444476505336e-19),
+                          (3.14, 0.9999999998928399)])
+def test_cosine_cdf_sf(x, expected):
+    assert_allclose(stats.cosine.cdf(x), expected)
+    assert_allclose(stats.cosine.sf(-x), expected)
+
+
+@pytest.mark.parametrize('p, expected',
+                         [(1e-6, -3.1080612413765905),
+                          (1e-17, -3.141585429601399),
+                          (0.975, 2.1447547020964923)])
+def test_cosine_ppf_isf(p, expected):
+    assert_allclose(stats.cosine.ppf(p), expected)
+    assert_allclose(stats.cosine.isf(p), -expected)
+
+
+def test_cosine_logpdf_endpoints():
+    logp = stats.cosine.logpdf([-np.pi, np.pi])
+    # reference value calculated using mpmath assuming `np.cos(-1)` is four
+    # floating point numbers too high. See gh-18382.
+    assert_array_less(logp, -37.18838327496655)
+
+
+def test_distr_params_lists():
+    # distribution objects are extra distributions added in
+    # test_discrete_basic. All other distributions are strings (names)
+    # and so we only choose those to compare whether both lists match.
+    discrete_distnames = {name for name, _ in distdiscrete
+                          if isinstance(name, str)}
+    invdiscrete_distnames = {name for name, _ in invdistdiscrete}
+    assert discrete_distnames == invdiscrete_distnames
+
+    cont_distnames = {name for name, _ in distcont}
+    invcont_distnames = {name for name, _ in invdistcont}
+    assert cont_distnames == invcont_distnames
+
+
+def test_moment_order_4():
+    # gh-13655 reported that if a distribution has a `_stats` method that
+    # accepts the `moments` parameter, then if the distribution's `moment`
+    # method is called with `order=4`, the faster/more accurate`_stats` gets
+    # called, but the results aren't used, and the generic `_munp` method is
+    # called to calculate the moment anyway. This tests that the issue has
+    # been fixed.
+    # stats.skewnorm._stats accepts the `moments` keyword
+    stats.skewnorm._stats(a=0, moments='k')  # no failure = has `moments`
+    # When `moment` is called, `_stats` is used, so the moment is very accurate
+    # (exactly equal to Pearson's kurtosis of the normal distribution, 3)
+    assert stats.skewnorm.moment(order=4, a=0) == 3.0
+    # At the time of gh-13655, skewnorm._munp() used the generic method
+    # to compute its result, which was inefficient and not very accurate.
+    # At that time, the following assertion would fail.  skewnorm._munp()
+    # has since been made more accurate and efficient, so now this test
+    # is expected to pass.
+    assert stats.skewnorm._munp(4, 0) == 3.0
+
+
+class TestRelativisticBW:
+    @pytest.fixture
+    def ROOT_pdf_sample_data(self):
+        """Sample data points for pdf computed with CERN's ROOT
+
+        See - https://root.cern/
+
+        Uses ROOT.TMath.BreitWignerRelativistic, available in ROOT
+        versions 6.27+
+
+        pdf calculated for Z0 Boson, W Boson, and Higgs Boson for
+        x in `np.linspace(0, 200, 401)`.
+        """
+        data = np.load(
+            Path(__file__).parent /
+            'data/rel_breitwigner_pdf_sample_data_ROOT.npy'
+        )
+        data = np.rec.fromarrays(data.T, names='x,pdf,rho,gamma')
+        return data
+
+    @pytest.mark.parametrize(
+        "rho,gamma,rtol", [
+            (36.545206797050334, 2.4952, 5e-14),  # Z0 Boson
+            (38.55107913669065, 2.085, 1e-14),  # W Boson
+            (96292.3076923077, 0.0013, 5e-13),  # Higgs Boson
+        ]
+    )
+    def test_pdf_against_ROOT(self, ROOT_pdf_sample_data, rho, gamma, rtol):
+        data = ROOT_pdf_sample_data[
+            (ROOT_pdf_sample_data['rho'] == rho)
+            & (ROOT_pdf_sample_data['gamma'] == gamma)
+        ]
+        x, pdf = data['x'], data['pdf']
+        assert_allclose(
+            pdf, stats.rel_breitwigner.pdf(x, rho, scale=gamma), rtol=rtol
+        )
+
+    @pytest.mark.parametrize("rho, Gamma, rtol", [
+              (36.545206797050334, 2.4952, 5e-13),  # Z0 Boson
+              (38.55107913669065, 2.085, 5e-13),  # W Boson
+              (96292.3076923077, 0.0013, 5e-10),  # Higgs Boson
+          ]
+      )
+    def test_pdf_against_simple_implementation(self, rho, Gamma, rtol):
+        # reference implementation straight from formulas on Wikipedia [1]
+        def pdf(E, M, Gamma):
+            gamma = np.sqrt(M**2 * (M**2 + Gamma**2))
+            k = (2 * np.sqrt(2) * M * Gamma * gamma
+                 / (np.pi * np.sqrt(M**2 + gamma)))
+            return k / ((E**2 - M**2)**2 + M**2*Gamma**2)
+        # get reasonable values at which to evaluate the CDF
+        p = np.linspace(0.05, 0.95, 10)
+        x = stats.rel_breitwigner.ppf(p, rho, scale=Gamma)
+        res = stats.rel_breitwigner.pdf(x, rho, scale=Gamma)
+        ref = pdf(x, rho*Gamma, Gamma)
+        assert_allclose(res, ref, rtol=rtol)
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize(
+        "rho,gamma", [
+            pytest.param(
+                36.545206797050334, 2.4952, marks=pytest.mark.slow
+            ),  # Z0 Boson
+            pytest.param(
+                38.55107913669065, 2.085, marks=pytest.mark.xslow
+            ),  # W Boson
+            pytest.param(
+                96292.3076923077, 0.0013, marks=pytest.mark.xslow
+            ),  # Higgs Boson
+        ]
+    )
+    def test_fit_floc(self, rho, gamma):
+        """Tests fit for cases where floc is set.
+
+        `rel_breitwigner` has special handling for these cases.
+        """
+        seed = 6936804688480013683
+        rng = np.random.default_rng(seed)
+        data = stats.rel_breitwigner.rvs(
+            rho, scale=gamma, size=1000, random_state=rng
+        )
+        fit = stats.rel_breitwigner.fit(data, floc=0)
+        assert_allclose((fit[0], fit[2]), (rho, gamma), rtol=2e-1)
+        assert fit[1] == 0
+        # Check again with fscale set.
+        fit = stats.rel_breitwigner.fit(data, floc=0, fscale=gamma)
+        assert_allclose(fit[0], rho, rtol=1e-2)
+        assert (fit[1], fit[2]) == (0, gamma)
+
+
+class TestJohnsonSU:
+    @pytest.mark.parametrize("case", [  # a, b, loc, scale, m1, m2, g1, g2
+            (-0.01, 1.1, 0.02, 0.0001, 0.02000137427557091,
+             2.1112742956578063e-08, 0.05989781342460999, 20.36324408592951-3),
+            (2.554395574161155, 2.2482281679651965, 0, 1, -1.54215386737391,
+             0.7629882028469993, -1.256656139406788, 6.303058419339775-3)])
+    def test_moment_gh18071(self, case):
+        # gh-18071 reported an IntegrationWarning emitted by johnsonsu.stats
+        # Check that the warning is no longer emitted and that the values
+        # are accurate compared against results from Mathematica.
+        # Reference values from Mathematica, e.g.
+        # Mean[JohnsonDistribution["SU",-0.01, 1.1, 0.02, 0.0001]]
+        res = stats.johnsonsu.stats(*case[:4], moments='mvsk')
+        assert_allclose(res, case[4:], rtol=1e-14)
+
+
+class TestTruncPareto:
+    def test_pdf(self):
+        # PDF is that of the truncated pareto distribution
+        b, c = 1.8, 5.3
+        x = np.linspace(1.8, 5.3)
+        res = stats.truncpareto(b, c).pdf(x)
+        ref = stats.pareto(b).pdf(x) / stats.pareto(b).cdf(c)
+        assert_allclose(res, ref)
+
+    @pytest.mark.parametrize('fix_loc', [True, False])
+    @pytest.mark.parametrize('fix_scale', [True, False])
+    @pytest.mark.parametrize('fix_b', [True, False])
+    @pytest.mark.parametrize('fix_c', [True, False])
+    def test_fit(self, fix_loc, fix_scale, fix_b, fix_c):
+
+        rng = np.random.default_rng(6747363148258237171)
+        b, c, loc, scale = 1.8, 5.3, 1, 2.5
+        dist = stats.truncpareto(b, c, loc=loc, scale=scale)
+        data = dist.rvs(size=500, random_state=rng)
+
+        kwds = {}
+        if fix_loc:
+            kwds['floc'] = loc
+        if fix_scale:
+            kwds['fscale'] = scale
+        if fix_b:
+            kwds['f0'] = b
+        if fix_c:
+            kwds['f1'] = c
+
+        if fix_loc and fix_scale and fix_b and fix_c:
+            message = "All parameters fixed. There is nothing to optimize."
+            with pytest.raises(RuntimeError, match=message):
+                stats.truncpareto.fit(data, **kwds)
+        else:
+            _assert_less_or_close_loglike(stats.truncpareto, data, **kwds)
+
+
+class TestKappa3:
+    def test_sf(self):
+        # During development of gh-18822, we found that the override of
+        # kappa3.sf could experience overflow where the version in main did
+        # not. Check that this does not happen in final implementation.
+        sf0 = 1 - stats.kappa3.cdf(0.5, 1e5)
+        sf1 = stats.kappa3.sf(0.5, 1e5)
+        assert_allclose(sf1, sf0)
+
+
+class TestIrwinHall:
+    unif = stats.uniform(0, 1)
+    ih1 = stats.irwinhall(1)
+    ih10 = stats.irwinhall(10)
+
+    def test_stats_ih10(self):
+        # from Wolfram Alpha "mean variance skew kurtosis UniformSumDistribution[10]"
+        # W|A uses Pearson's definition of kurtosis so subtract 3
+        # should be exact integer division converted to fp64, without any further ops
+        assert_array_max_ulp(self.ih10.stats('mvsk'), (5, 10/12, 0, -3/25))
+
+    def test_moments_ih10(self):
+        # from Wolfram Alpha "values moments UniformSumDistribution[10]"
+        # algo should use integer division converted to fp64, without any further ops
+        # so these should be precise to the ulpm if not exact
+        vals = [5, 155 / 6, 275 / 2, 752, 12650 / 3,
+                677465 / 28, 567325 / 4,
+                15266213 / 18, 10333565 / 2]
+        moments = [self.ih10.moment(n+1) for n in range(len(vals))]
+        assert_array_max_ulp(moments, vals)
+        # also from Wolfram Alpha "50th moment UniformSumDistribution[10]"
+        m50 = self.ih10.moment(50)
+        m50_exact = 17453002755350010529309685557285098151740985685/4862
+        assert_array_max_ulp(m50, m50_exact)
+
+    def test_pdf_ih1_unif(self):
+        # IH(1) PDF is by definition U(0,1)
+        # we should be too, but differences in floating point eval order happen
+        # it's unclear if we can get down to the single ulp for doubles unless
+        # quads are used we're within 6-10 ulps otherwise (across sf/cdf/pdf)
+        # which is pretty good
+
+        pts = np.linspace(0, 1, 100)
+        pdf_unif = self.unif.pdf(pts)
+        pdf_ih1 = self.ih1.pdf(pts)
+        assert_array_max_ulp(pdf_ih1, pdf_unif, maxulp=10)
+
+    def test_pdf_ih2_triangle(self):
+        # IH(2) PDF is a triangle
+        ih2 = stats.irwinhall(2)
+        npts = 101
+        pts = np.linspace(0, 2, npts)
+        expected = np.linspace(0, 2, npts)
+        expected[(npts + 1) // 2:] = 2 - expected[(npts + 1) // 2:]
+        pdf_ih2 = ih2.pdf(pts)
+        assert_array_max_ulp(pdf_ih2, expected, maxulp=10)
+
+    def test_cdf_ih1_unif(self):
+        # CDF of IH(1) should be identical to uniform
+        pts = np.linspace(0, 1, 100)
+        cdf_unif = self.unif.cdf(pts)
+        cdf_ih1 = self.ih1.cdf(pts)
+
+        assert_array_max_ulp(cdf_ih1, cdf_unif, maxulp=10)
+
+    def test_cdf(self):
+        # CDF of IH is symmetric so CDF should be 0.5 at n/2
+        n = np.arange(1, 10)
+        ih = stats.irwinhall(n)
+        ih_cdf = ih.cdf(n / 2)
+        exact = np.repeat(1/2, len(n))
+        # should be identically 1/2 but fp order of eval differences happen
+        assert_array_max_ulp(ih_cdf, exact, maxulp=10)
+
+    def test_cdf_ih10_exact(self):
+        # from Wolfram Alpha "values CDF[UniformSumDistribution[10], x] x=0 to x=10"
+        # symmetric about n/2, i.e., cdf[n-x] = 1-cdf[x] = sf[x]
+        vals = [0, 1 / 3628800, 169 / 604800, 24427 / 1814400,
+                  252023 / 1814400, 1 / 2, 1562377 / 1814400,
+                  1789973 / 1814400, 604631 / 604800,
+                  3628799 / 3628800, 1]
+
+        # essentially a test of bspline evaluation
+        # this and the other ones are mostly to detect regressions
+        assert_array_max_ulp(self.ih10.cdf(np.arange(11)), vals, maxulp=10)
+
+        assert_array_max_ulp(self.ih10.cdf(1/10), 1/36288000000000000, maxulp=10)
+        ref = 36287999999999999/36288000000000000
+        assert_array_max_ulp(self.ih10.cdf(99/10), ref, maxulp=10)
+
+    def test_pdf_ih10_exact(self):
+        # from Wolfram Alpha "values PDF[UniformSumDistribution[10], x] x=0 to x=10"
+        # symmetric about n/2 = 5
+        vals = [0, 1 / 362880, 251 / 181440, 913 / 22680, 44117 / 181440]
+        vals += [15619 / 36288] + vals[::-1]
+        assert_array_max_ulp(self.ih10.pdf(np.arange(11)), vals, maxulp=10)
+
+    def test_sf_ih10_exact(self):
+        assert_allclose(self.ih10.sf(np.arange(11)), 1 - self.ih10.cdf(np.arange(11)))
+        # from Wolfram Alpha "SurvivalFunction[UniformSumDistribution[10],x] at x=1/10"
+        # and symmetry about n/2 = 5
+        # W|A returns 1 for CDF @ x=9.9
+        ref = 36287999999999999/36288000000000000
+        assert_array_max_ulp(self.ih10.sf(1/10), ref, maxulp=10)
+
+
+class TestDParetoLognorm:
+    def test_against_R(self):
+        # Test against R implementation in `distributionsrd`
+        # library(distributionsrd)
+        # options(digits=16)
+        # x = 1.1
+        # b = 2
+        # a = 1.5
+        # m = 3
+        # s = 1.2
+        # ddoubleparetolognormal(x, b, a, m, s)
+        # pdoubleparetolognormal(x, b, a, m, s)
+        x, m, s, a, b = 1.1, 3, 1.2, 1.5, 2
+        dist = stats.dpareto_lognorm(m, s, a, b)
+        np.testing.assert_allclose(dist.pdf(x), 0.02490187219085912)
+        np.testing.assert_allclose(dist.cdf(x), 0.01664024173822796)
+
+
+# Cases are (distribution name, log10 of smallest probability mass to test,
+# log10 of the complement of the largest probability mass to test, atol,
+# rtol). None uses default values.
+@pytest.mark.parametrize("case", [("kappa3", None, None, None, None),
+                                  ("loglaplace", None, None, None, None),
+                                  ("lognorm", None, None, None, None),
+                                  ("lomax", None, None, None, None),
+                                  ("pareto", None, None, None, None),])
+def test_sf_isf_overrides(case):
+    # Test that SF is the inverse of ISF. Supplements
+    # `test_continuous_basic.check_sf_isf` for distributions with overridden
+    # `sf` and `isf` methods.
+    distname, lp1, lp2, atol, rtol = case
+
+    lpm = np.log10(0.5)  # log10 of the probability mass at the median
+    lp1 = lp1 or -290
+    lp2 = lp2 or -14
+    atol = atol or 0
+    rtol = rtol or 1e-12
+    dist = getattr(stats, distname)
+    params = dict(distcont)[distname]
+    dist_frozen = dist(*params)
+
+    # Test (very deep) right tail to median. We can benchmark with random
+    # (loguniform) points, but strictly logspaced points are fine for tests.
+    ref = np.logspace(lp1, lpm)
+    res = dist_frozen.sf(dist_frozen.isf(ref))
+    assert_allclose(res, ref, atol=atol, rtol=rtol)
+
+    # test median to left tail
+    ref = 1 - np.logspace(lp2, lpm, 20)
+    res = dist_frozen.sf(dist_frozen.isf(ref))
+    assert_allclose(res, ref, atol=atol, rtol=rtol)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_entropy.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_entropy.py
new file mode 100644
index 0000000000000000000000000000000000000000..4002b2c52703b0828d2f24bfa6d988b872576d4b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_entropy.py
@@ -0,0 +1,330 @@
+import math
+import pytest
+from pytest import raises as assert_raises
+
+import numpy as np
+
+from scipy import stats
+from scipy.stats import norm, expon  # type: ignore[attr-defined]
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import array_namespace, is_array_api_strict, is_jax
+from scipy._lib._array_api_no_0d import (xp_assert_close, xp_assert_equal,
+                                         xp_assert_less)
+
+class TestEntropy:
+    @array_api_compatible
+    def test_entropy_positive(self, xp):
+        # See ticket #497
+        pk = xp.asarray([0.5, 0.2, 0.3])
+        qk = xp.asarray([0.1, 0.25, 0.65])
+        eself = stats.entropy(pk, pk)
+        edouble = stats.entropy(pk, qk)
+        xp_assert_equal(eself, xp.asarray(0.))
+        xp_assert_less(-edouble, xp.asarray(0.))
+
+    @array_api_compatible
+    def test_entropy_base(self, xp):
+        pk = xp.ones(16)
+        S = stats.entropy(pk, base=2.)
+        xp_assert_less(xp.abs(S - 4.), xp.asarray(1.e-5))
+
+        qk = xp.ones(16)
+        qk = xp.where(xp.arange(16) < 8, xp.asarray(2.), qk)
+        S = stats.entropy(pk, qk)
+        S2 = stats.entropy(pk, qk, base=2.)
+        xp_assert_less(xp.abs(S/S2 - math.log(2.)), xp.asarray(1.e-5))
+
+    @array_api_compatible
+    def test_entropy_zero(self, xp):
+        # Test for PR-479
+        x = xp.asarray([0., 1., 2.])
+        xp_assert_close(stats.entropy(x),
+                        xp.asarray(0.63651416829481278))
+
+    @array_api_compatible
+    def test_entropy_2d(self, xp):
+        pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        qk = xp.asarray([[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]])
+        xp_assert_close(stats.entropy(pk, qk),
+                        xp.asarray([0.1933259, 0.18609809]))
+
+    @array_api_compatible
+    def test_entropy_2d_zero(self, xp):
+        pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        qk = xp.asarray([[0.0, 0.1], [0.3, 0.6], [0.5, 0.3]])
+        xp_assert_close(stats.entropy(pk, qk),
+                        xp.asarray([xp.inf, 0.18609809]))
+
+        pk = xp.asarray([[0.0, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        xp_assert_close(stats.entropy(pk, qk),
+                        xp.asarray([0.17403988, 0.18609809]))
+
+    @array_api_compatible
+    def test_entropy_base_2d_nondefault_axis(self, xp):
+        pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        xp_assert_close(stats.entropy(pk, axis=1),
+                        xp.asarray([0.63651417, 0.63651417, 0.66156324]))
+
+    @array_api_compatible
+    def test_entropy_2d_nondefault_axis(self, xp):
+        pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        qk = xp.asarray([[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]])
+        xp_assert_close(stats.entropy(pk, qk, axis=1),
+                        xp.asarray([0.23104906, 0.23104906, 0.12770641]))
+
+    @array_api_compatible
+    def test_entropy_raises_value_error(self, xp):
+        pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        qk = xp.asarray([[0.1, 0.2], [0.6, 0.3]])
+        message = "Array shapes are incompatible for broadcasting."
+        with pytest.raises(ValueError, match=message):
+            stats.entropy(pk, qk)
+
+    @array_api_compatible
+    def test_base_entropy_with_axis_0_is_equal_to_default(self, xp):
+        pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        xp_assert_close(stats.entropy(pk, axis=0),
+                        stats.entropy(pk))
+
+    @array_api_compatible
+    def test_entropy_with_axis_0_is_equal_to_default(self, xp):
+        pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        qk = xp.asarray([[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]])
+        xp_assert_close(stats.entropy(pk, qk, axis=0),
+                        stats.entropy(pk, qk))
+
+    @array_api_compatible
+    def test_base_entropy_transposed(self, xp):
+        pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        xp_assert_close(stats.entropy(pk.T),
+                        stats.entropy(pk, axis=1))
+
+    @array_api_compatible
+    def test_entropy_transposed(self, xp):
+        pk = xp.asarray([[0.1, 0.2], [0.6, 0.3], [0.3, 0.5]])
+        qk = xp.asarray([[0.2, 0.1], [0.3, 0.6], [0.5, 0.3]])
+        xp_assert_close(stats.entropy(pk.T, qk.T),
+                        stats.entropy(pk, qk, axis=1))
+
+    @array_api_compatible
+    def test_entropy_broadcasting(self, xp):
+        rng = np.random.default_rng(74187315492831452)
+        x = xp.asarray(rng.random(3))
+        y = xp.asarray(rng.random((2, 1)))
+        res = stats.entropy(x, y, axis=-1)
+        xp_assert_equal(res[0], stats.entropy(x, y[0, ...]))
+        xp_assert_equal(res[1], stats.entropy(x, y[1, ...]))
+
+    @array_api_compatible
+    def test_entropy_shape_mismatch(self, xp):
+        x = xp.ones((10, 1, 12))
+        y = xp.ones((11, 2))
+        message = "Array shapes are incompatible for broadcasting."
+        with pytest.raises(ValueError, match=message):
+            stats.entropy(x, y)
+
+    @array_api_compatible
+    def test_input_validation(self, xp):
+        x = xp.ones(10)
+        message = "`base` must be a positive number."
+        with pytest.raises(ValueError, match=message):
+            stats.entropy(x, base=-2)
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+class TestDifferentialEntropy:
+    """
+    Vasicek results are compared with the R package vsgoftest.
+
+    # library(vsgoftest)
+    #
+    # samp <- c()
+    # entropy.estimate(x = samp, window = )
+
+    """
+
+    def test_differential_entropy_vasicek(self, xp):
+
+        random_state = np.random.RandomState(0)
+        values = random_state.standard_normal(100)
+        values = xp.asarray(values.tolist())
+
+        entropy = stats.differential_entropy(values, method='vasicek')
+        xp_assert_close(entropy, xp.asarray(1.342551187000946))
+
+        entropy = stats.differential_entropy(values, window_length=1,
+                                             method='vasicek')
+        xp_assert_close(entropy, xp.asarray(1.122044177725947))
+
+        entropy = stats.differential_entropy(values, window_length=8,
+                                             method='vasicek')
+        xp_assert_close(entropy, xp.asarray(1.349401487550325))
+
+    def test_differential_entropy_vasicek_2d_nondefault_axis(self, xp):
+        random_state = np.random.RandomState(0)
+        values = random_state.standard_normal((3, 100))
+        values = xp.asarray(values.tolist())
+
+        entropy = stats.differential_entropy(values, axis=1, method='vasicek')
+        ref = xp.asarray([1.342551187000946, 1.341825903922332, 1.293774601883585])
+        xp_assert_close(entropy, ref)
+
+        entropy = stats.differential_entropy(values, axis=1, window_length=1,
+                                             method='vasicek')
+        ref = xp.asarray([1.122044177725947, 1.10294413850758, 1.129615790292772])
+        xp_assert_close(entropy, ref)
+
+        entropy = stats.differential_entropy(values, axis=1, window_length=8,
+                                             method='vasicek')
+        ref = xp.asarray([1.349401487550325, 1.338514126301301, 1.292331889365405])
+        xp_assert_close(entropy, ref)
+
+
+    def test_differential_entropy_raises_value_error(self, xp):
+        random_state = np.random.RandomState(0)
+        values = random_state.standard_normal((3, 100))
+        values = xp.asarray(values.tolist())
+
+        error_str = (
+            r"Window length \({window_length}\) must be positive and less "
+            r"than half the sample size \({sample_size}\)."
+        )
+
+        sample_size = values.shape[1]
+
+        for window_length in {-1, 0, sample_size//2, sample_size}:
+
+            formatted_error_str = error_str.format(
+                window_length=window_length,
+                sample_size=sample_size,
+            )
+
+            with assert_raises(ValueError, match=formatted_error_str):
+                stats.differential_entropy(
+                    values,
+                    window_length=window_length,
+                    axis=1,
+                )
+
+    @pytest.mark.skip_xp_backends('jax.numpy',
+                                  reason="JAX doesn't support item assignment")
+    def test_base_differential_entropy_with_axis_0_is_equal_to_default(self, xp):
+        random_state = np.random.RandomState(0)
+        values = random_state.standard_normal((100, 3))
+        values = xp.asarray(values.tolist())
+
+        entropy = stats.differential_entropy(values, axis=0)
+        default_entropy = stats.differential_entropy(values)
+        xp_assert_close(entropy, default_entropy)
+
+    @pytest.mark.skip_xp_backends('jax.numpy',
+                                  reason="JAX doesn't support item assignment")
+    def test_base_differential_entropy_transposed(self, xp):
+        random_state = np.random.RandomState(0)
+        values = random_state.standard_normal((3, 100))
+        values = xp.asarray(values.tolist())
+
+        xp_assert_close(
+            stats.differential_entropy(values.T),
+            stats.differential_entropy(values, axis=1),
+        )
+
+    def test_input_validation(self, xp):
+        x = np.random.rand(10)
+        x = xp.asarray(x.tolist())
+
+        message = "`base` must be a positive number or `None`."
+        with pytest.raises(ValueError, match=message):
+            stats.differential_entropy(x, base=-2)
+
+        message = "`method` must be one of..."
+        with pytest.raises(ValueError, match=message):
+            stats.differential_entropy(x, method='ekki-ekki')
+
+    @pytest.mark.parametrize('method', ['vasicek', 'van es',
+                                        'ebrahimi', 'correa'])
+    def test_consistency(self, method, xp):
+        if is_jax(xp) and method == 'ebrahimi':
+            pytest.xfail("Needs array assignment.")
+        elif is_array_api_strict(xp) and method == 'correa':
+            pytest.xfail("Needs fancy indexing.")
+        # test that method is a consistent estimator
+        n = 10000 if method == 'correa' else 1000000
+        rvs = stats.norm.rvs(size=n, random_state=0)
+        rvs = xp.asarray(rvs.tolist())
+        expected = xp.asarray(float(stats.norm.entropy()))
+        res = stats.differential_entropy(rvs, method=method)
+        xp_assert_close(res, expected, rtol=0.005)
+
+    # values from differential_entropy reference [6], table 1, n=50, m=7
+    norm_rmse_std_cases = {  # method: (RMSE, STD)
+                           'vasicek': (0.198, 0.109),
+                           'van es': (0.212, 0.110),
+                           'correa': (0.135, 0.112),
+                           'ebrahimi': (0.128, 0.109)
+                           }
+
+    # values from differential_entropy reference [6], table 2, n=50, m=7
+    expon_rmse_std_cases = {  # method: (RMSE, STD)
+                            'vasicek': (0.194, 0.148),
+                            'van es': (0.179, 0.149),
+                            'correa': (0.155, 0.152),
+                            'ebrahimi': (0.151, 0.148)
+                            }
+
+    rmse_std_cases = {norm: norm_rmse_std_cases,
+                      expon: expon_rmse_std_cases}
+
+    @pytest.mark.parametrize('method', ['vasicek', 'van es', 'ebrahimi', 'correa'])
+    @pytest.mark.parametrize('dist', [norm, expon])
+    def test_rmse_std(self, method, dist, xp):
+        # test that RMSE and standard deviation of estimators matches values
+        # given in differential_entropy reference [6]. Incidentally, also
+        # tests vectorization.
+        if is_jax(xp) and method == 'ebrahimi':
+            pytest.xfail("Needs array assignment.")
+        elif is_array_api_strict(xp) and method == 'correa':
+            pytest.xfail("Needs fancy indexing.")
+
+        reps, n, m = 10000, 50, 7
+        expected = self.rmse_std_cases[dist][method]
+        rmse_expected, std_expected = xp.asarray(expected[0]), xp.asarray(expected[1])
+        rvs = dist.rvs(size=(reps, n), random_state=0)
+        rvs = xp.asarray(rvs.tolist())
+        true_entropy = xp.asarray(float(dist.entropy()))
+        res = stats.differential_entropy(rvs, window_length=m,
+                                         method=method, axis=-1)
+        xp_assert_close(xp.sqrt(xp.mean((res - true_entropy)**2)),
+                        rmse_expected, atol=0.005)
+        xp_test = array_namespace(res)
+        xp_assert_close(xp_test.std(res, correction=0), std_expected, atol=0.002)
+
+    @pytest.mark.parametrize('n, method', [(8, 'van es'),
+                                           (12, 'ebrahimi'),
+                                           (1001, 'vasicek')])
+    def test_method_auto(self, n, method, xp):
+        if is_jax(xp) and method == 'ebrahimi':
+            pytest.xfail("Needs array assignment.")
+        rvs = stats.norm.rvs(size=(n,), random_state=0)
+        rvs = xp.asarray(rvs.tolist())
+        res1 = stats.differential_entropy(rvs)
+        res2 = stats.differential_entropy(rvs, method=method)
+        xp_assert_equal(res1, res2)
+
+    @pytest.mark.skip_xp_backends('jax.numpy',
+                                  reason="JAX doesn't support item assignment")
+    @pytest.mark.parametrize('method', ["vasicek", "van es", "correa", "ebrahimi"])
+    @pytest.mark.parametrize('dtype', [None, 'float32', 'float64'])
+    def test_dtypes_gh21192(self, xp, method, dtype):
+        # gh-21192 noted a change in the output of method='ebrahimi'
+        # with integer input. Check that the output is consistent regardless
+        # of input dtype.
+        if is_array_api_strict(xp) and method == 'correa':
+            pytest.xfail("Needs fancy indexing.")
+        x = [1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11]
+        dtype_in = getattr(xp, str(dtype), None)
+        dtype_out = getattr(xp, str(dtype), xp.asarray(1.).dtype)
+        res = stats.differential_entropy(xp.asarray(x, dtype=dtype_in), method=method)
+        ref = stats.differential_entropy(xp.asarray(x, dtype=xp.float64), method=method)
+        xp_assert_close(res, xp.asarray(ref, dtype=dtype_out)[()])
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fast_gen_inversion.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fast_gen_inversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..63052f748befc7b30cdf6609490092b1d1d062e0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fast_gen_inversion.py
@@ -0,0 +1,433 @@
+import pytest
+import warnings
+import numpy as np
+from numpy.testing import (assert_array_equal, assert_allclose,
+                           suppress_warnings)
+from copy import deepcopy
+from scipy.stats.sampling import FastGeneratorInversion
+from scipy import stats
+
+
+def test_bad_args():
+    # loc and scale must be scalar
+    with pytest.raises(ValueError, match="loc must be scalar"):
+        FastGeneratorInversion(stats.norm(loc=(1.2, 1.3)))
+    with pytest.raises(ValueError, match="scale must be scalar"):
+        FastGeneratorInversion(stats.norm(scale=[1.5, 5.7]))
+
+    with pytest.raises(ValueError, match="'test' cannot be used to seed"):
+        FastGeneratorInversion(stats.norm(), random_state="test")
+
+    msg = "Each of the 1 shape parameters must be a scalar"
+    with pytest.raises(ValueError, match=msg):
+        FastGeneratorInversion(stats.gamma([1.3, 2.5]))
+
+    with pytest.raises(ValueError, match="`dist` must be a frozen"):
+        FastGeneratorInversion("xy")
+
+    with pytest.raises(ValueError, match="Distribution 'truncnorm' is not"):
+        FastGeneratorInversion(stats.truncnorm(1.3, 4.5))
+
+
+def test_random_state():
+    # fixed seed
+    gen = FastGeneratorInversion(stats.norm(), random_state=68734509)
+    x1 = gen.rvs(size=10)
+    gen.random_state = 68734509
+    x2 = gen.rvs(size=10)
+    assert_array_equal(x1, x2)
+
+    # Generator
+    urng = np.random.default_rng(20375857)
+    gen = FastGeneratorInversion(stats.norm(), random_state=urng)
+    x1 = gen.rvs(size=10)
+    gen.random_state = np.random.default_rng(20375857)
+    x2 = gen.rvs(size=10)
+    assert_array_equal(x1, x2)
+
+    # RandomState
+    urng = np.random.RandomState(2364)
+    gen = FastGeneratorInversion(stats.norm(), random_state=urng)
+    x1 = gen.rvs(size=10)
+    gen.random_state = np.random.RandomState(2364)
+    x2 = gen.rvs(size=10)
+    assert_array_equal(x1, x2)
+
+    # if evaluate_error is called, it must not interfere with the random_state
+    # used by rvs
+    gen = FastGeneratorInversion(stats.norm(), random_state=68734509)
+    x1 = gen.rvs(size=10)
+    _ = gen.evaluate_error(size=5)  # this will generate 5 uniform rvs
+    x2 = gen.rvs(size=10)
+    gen.random_state = 68734509
+    x3 = gen.rvs(size=20)
+    assert_array_equal(x2, x3[10:])
+
+
+dists_with_params = [
+    ("alpha", (3.5,)),
+    ("anglit", ()),
+    ("argus", (3.5,)),
+    ("argus", (5.1,)),
+    ("beta", (1.5, 0.9)),
+    ("cosine", ()),
+    ("betaprime", (2.5, 3.3)),
+    ("bradford", (1.2,)),
+    ("burr", (1.3, 2.4)),
+    ("burr12", (0.7, 1.2)),
+    ("cauchy", ()),
+    ("chi2", (3.5,)),
+    ("chi", (4.5,)),
+    ("crystalball", (0.7, 1.2)),
+    ("expon", ()),
+    ("gamma", (1.5,)),
+    ("gennorm", (2.7,)),
+    ("gumbel_l", ()),
+    ("gumbel_r", ()),
+    ("hypsecant", ()),
+    ("invgauss", (3.1,)),
+    ("invweibull", (1.5,)),
+    ("laplace", ()),
+    ("logistic", ()),
+    ("maxwell", ()),
+    ("moyal", ()),
+    ("norm", ()),
+    ("pareto", (1.3,)),
+    ("powerlaw", (7.6,)),
+    ("rayleigh", ()),
+    ("semicircular", ()),
+    ("t", (5.7,)),
+    ("wald", ()),
+    ("weibull_max", (2.4,)),
+    ("weibull_min", (1.2,)),
+]
+
+
+@pytest.mark.parametrize(("distname, args"), dists_with_params)
+def test_rvs_and_ppf(distname, args):
+    # check sample against rvs generated by rv_continuous
+    urng = np.random.default_rng(9807324628097097)
+    rng1 = getattr(stats, distname)(*args)
+    rvs1 = rng1.rvs(size=500, random_state=urng)
+    rng2 = FastGeneratorInversion(rng1, random_state=urng)
+    rvs2 = rng2.rvs(size=500)
+    assert stats.cramervonmises_2samp(rvs1, rvs2).pvalue > 0.01
+
+    # check ppf
+    q = [0.001, 0.1, 0.5, 0.9, 0.999]
+    assert_allclose(rng1.ppf(q), rng2.ppf(q), atol=1e-10)
+
+
+@pytest.mark.parametrize(("distname, args"), dists_with_params)
+def test_u_error(distname, args):
+    # check sample against rvs generated by rv_continuous
+    dist = getattr(stats, distname)(*args)
+    with suppress_warnings() as sup:
+        # filter the warnings thrown by UNU.RAN
+        sup.filter(RuntimeWarning)
+        rng = FastGeneratorInversion(dist)
+    u_error, x_error = rng.evaluate_error(
+        size=10_000, random_state=9807324628097097, x_error=False
+    )
+    assert u_error <= 1e-10
+
+
+@pytest.mark.xslow
+@pytest.mark.xfail(reason="geninvgauss CDF is not accurate")
+def test_geninvgauss_uerror():
+    dist = stats.geninvgauss(3.2, 1.5)
+    rng = FastGeneratorInversion(dist)
+    err = rng.evaluate_error(size=10_000, random_state=67982)
+    assert err[0] < 1e-10
+
+
+# TODO: add more distributions
+@pytest.mark.fail_slow(5)
+@pytest.mark.parametrize(("distname, args"), [("beta", (0.11, 0.11))])
+def test_error_extreme_params(distname, args):
+    # take extreme parameters where u-error might not be below the tolerance
+    # due to limitations of floating point arithmetic
+    with suppress_warnings() as sup:
+        # filter the warnings thrown by UNU.RAN for such extreme parameters
+        sup.filter(RuntimeWarning)
+        dist = getattr(stats, distname)(*args)
+        rng = FastGeneratorInversion(dist)
+    u_error, x_error = rng.evaluate_error(
+        size=10_000, random_state=980732462809709732623, x_error=True
+    )
+    if u_error >= 2.5 * 1e-10:
+        assert x_error < 1e-9
+
+
+def test_evaluate_error_inputs():
+    gen = FastGeneratorInversion(stats.norm())
+    with pytest.raises(ValueError, match="size must be an integer"):
+        gen.evaluate_error(size=3.5)
+    with pytest.raises(ValueError, match="size must be an integer"):
+        gen.evaluate_error(size=(3, 3))
+
+
+def test_rvs_ppf_loc_scale():
+    loc, scale = 3.5, 2.3
+    dist = stats.norm(loc=loc, scale=scale)
+    rng = FastGeneratorInversion(dist, random_state=1234)
+    r = rng.rvs(size=1000)
+    r_rescaled = (r - loc) / scale
+    assert stats.cramervonmises(r_rescaled, "norm").pvalue > 0.01
+    q = [0.001, 0.1, 0.5, 0.9, 0.999]
+    assert_allclose(rng._ppf(q), rng.ppf(q), atol=1e-10)
+
+
+def test_domain():
+    # only a basic check that the domain argument is passed to the
+    # UNU.RAN generators
+    rng = FastGeneratorInversion(stats.norm(), domain=(-1, 1))
+    r = rng.rvs(size=100)
+    assert -1 <= r.min() < r.max() <= 1
+
+    # if loc and scale are used, new domain is loc + scale*domain
+    loc, scale = 3.5, 1.3
+    dist = stats.norm(loc=loc, scale=scale)
+    rng = FastGeneratorInversion(dist, domain=(-1.5, 2))
+    r = rng.rvs(size=100)
+    lb, ub = loc - scale * 1.5, loc + scale * 2
+    assert lb <= r.min() < r.max() <= ub
+
+
+@pytest.mark.parametrize(("distname, args, expected"),
+                         [("beta", (3.5, 2.5), (0, 1)),
+                          ("norm", (), (-np.inf, np.inf))])
+def test_support(distname, args, expected):
+    # test that the support is updated if truncation and loc/scale are applied
+    # use beta distribution since it is a transformed betaprime distribution,
+    # so it is important that the correct support is considered
+    # (i.e., the support of beta is (0,1), while betaprime is (0, inf))
+    dist = getattr(stats, distname)(*args)
+    rng = FastGeneratorInversion(dist)
+    assert_array_equal(rng.support(), expected)
+    rng.loc = 1
+    rng.scale = 2
+    assert_array_equal(rng.support(), 1 + 2*np.array(expected))
+
+
+@pytest.mark.parametrize(("distname, args"),
+                         [("beta", (3.5, 2.5)), ("norm", ())])
+def test_support_truncation(distname, args):
+    # similar test for truncation
+    dist = getattr(stats, distname)(*args)
+    rng = FastGeneratorInversion(dist, domain=(0.5, 0.7))
+    assert_array_equal(rng.support(), (0.5, 0.7))
+    rng.loc = 1
+    rng.scale = 2
+    assert_array_equal(rng.support(), (1 + 2 * 0.5, 1 + 2 * 0.7))
+
+
+def test_domain_shift_truncation():
+    # center of norm is zero, it should be shifted to the left endpoint of
+    # domain. if this was not the case, PINV in UNURAN would raise a warning
+    # as the center is not inside the domain
+    with warnings.catch_warnings():
+        warnings.simplefilter("error")
+        rng = FastGeneratorInversion(stats.norm(), domain=(1, 2))
+    r = rng.rvs(size=100)
+    assert 1 <= r.min() < r.max() <= 2
+
+
+def test_non_rvs_methods_with_domain():
+    # as a first step, compare truncated normal against stats.truncnorm
+    rng = FastGeneratorInversion(stats.norm(), domain=(2.3, 3.2))
+    trunc_norm = stats.truncnorm(2.3, 3.2)
+    # take values that are inside and outside the domain
+    x = (2.0, 2.4, 3.0, 3.4)
+    p = (0.01, 0.5, 0.99)
+    assert_allclose(rng._cdf(x), trunc_norm.cdf(x))
+    assert_allclose(rng._ppf(p), trunc_norm.ppf(p))
+    loc, scale = 2, 3
+    rng.loc = 2
+    rng.scale = 3
+    trunc_norm = stats.truncnorm(2.3, 3.2, loc=loc, scale=scale)
+    x = np.array(x) * scale + loc
+    assert_allclose(rng._cdf(x), trunc_norm.cdf(x))
+    assert_allclose(rng._ppf(p), trunc_norm.ppf(p))
+
+    # do another sanity check with beta distribution
+    # in that case, it is important to use the correct domain since beta
+    # is a transformation of betaprime which has a different support
+    rng = FastGeneratorInversion(stats.beta(2.5, 3.5), domain=(0.3, 0.7))
+    rng.loc = 2
+    rng.scale = 2.5
+    # the support is 2.75, , 3.75 (2 + 2.5 * 0.3, 2 + 2.5 * 0.7)
+    assert_array_equal(rng.support(), (2.75, 3.75))
+    x = np.array([2.74, 2.76, 3.74, 3.76])
+    # the cdf needs to be zero outside of the domain
+    y_cdf = rng._cdf(x)
+    assert_array_equal((y_cdf[0], y_cdf[3]), (0, 1))
+    assert np.min(y_cdf[1:3]) > 0
+    # ppf needs to map 0 and 1 to the boundaries
+    assert_allclose(rng._ppf(y_cdf), (2.75, 2.76, 3.74, 3.75))
+
+
+def test_non_rvs_methods_without_domain():
+    norm_dist = stats.norm()
+    rng = FastGeneratorInversion(norm_dist)
+    x = np.linspace(-3, 3, num=10)
+    p = (0.01, 0.5, 0.99)
+    assert_allclose(rng._cdf(x), norm_dist.cdf(x))
+    assert_allclose(rng._ppf(p), norm_dist.ppf(p))
+    loc, scale = 0.5, 1.3
+    rng.loc = loc
+    rng.scale = scale
+    norm_dist = stats.norm(loc=loc, scale=scale)
+    assert_allclose(rng._cdf(x), norm_dist.cdf(x))
+    assert_allclose(rng._ppf(p), norm_dist.ppf(p))
+
+@pytest.mark.parametrize(("domain, x"),
+                         [(None, 0.5),
+                         ((0, 1), 0.5),
+                         ((0, 1), 1.5)])
+def test_scalar_inputs(domain, x):
+    """ pdf, cdf etc should map scalar values to scalars. check with and
+    w/o domain since domain impacts pdf, cdf etc
+    Take x inside and outside of domain """
+    rng = FastGeneratorInversion(stats.norm(), domain=domain)
+    assert np.isscalar(rng._cdf(x))
+    assert np.isscalar(rng._ppf(0.5))
+
+
+def test_domain_argus_large_chi():
+    # for large chi, the Gamma distribution is used and the domain has to be
+    # transformed. this is a test to ensure that the transformation works
+    chi, lb, ub = 5.5, 0.25, 0.75
+    rng = FastGeneratorInversion(stats.argus(chi), domain=(lb, ub))
+    rng.random_state = 4574
+    r = rng.rvs(size=500)
+    assert lb <= r.min() < r.max() <= ub
+    # perform goodness of fit test with conditional cdf
+    cdf = stats.argus(chi).cdf
+    prob = cdf(ub) - cdf(lb)
+    assert stats.cramervonmises(r, lambda x: cdf(x) / prob).pvalue > 0.05
+
+
+def test_setting_loc_scale():
+    rng = FastGeneratorInversion(stats.norm(), random_state=765765864)
+    r1 = rng.rvs(size=1000)
+    rng.loc = 3.0
+    rng.scale = 2.5
+    r2 = rng.rvs(1000)
+    # rescaled r2 should be again standard normal
+    assert stats.cramervonmises_2samp(r1, (r2 - 3) / 2.5).pvalue > 0.05
+    # reset values to default loc=0, scale=1
+    rng.loc = 0
+    rng.scale = 1
+    r2 = rng.rvs(1000)
+    assert stats.cramervonmises_2samp(r1, r2).pvalue > 0.05
+
+
+def test_ignore_shape_range():
+    msg = "No generator is defined for the shape parameters"
+    with pytest.raises(ValueError, match=msg):
+        rng = FastGeneratorInversion(stats.t(0.03))
+    rng = FastGeneratorInversion(stats.t(0.03), ignore_shape_range=True)
+    # we can ignore the recommended range of shape parameters
+    # but u-error can be expected to be too large in that case
+    u_err, _ = rng.evaluate_error(size=1000, random_state=234)
+    assert u_err >= 1e-6
+
+@pytest.mark.xfail_on_32bit(
+    "NumericalInversePolynomial.qrvs fails for Win 32-bit"
+)
+class TestQRVS:
+    def test_input_validation(self):
+        gen = FastGeneratorInversion(stats.norm())
+
+        match = "`qmc_engine` must be an instance of..."
+        with pytest.raises(ValueError, match=match):
+            gen.qrvs(qmc_engine=0)
+
+        match = "`d` must be consistent with dimension of `qmc_engine`."
+        with pytest.raises(ValueError, match=match):
+            gen.qrvs(d=3, qmc_engine=stats.qmc.Halton(2))
+
+    qrngs = [None, stats.qmc.Sobol(1, seed=0), stats.qmc.Halton(3, seed=0)]
+    # `size=None` should not add anything to the shape, `size=1` should
+    sizes = [
+        (None, tuple()),
+        (1, (1,)),
+        (4, (4,)),
+        ((4,), (4,)),
+        ((2, 4), (2, 4)),
+    ]
+    # Neither `d=None` nor `d=1` should add anything to the shape
+    ds = [(None, tuple()), (1, tuple()), (3, (3,))]
+
+    @pytest.mark.parametrize("qrng", qrngs)
+    @pytest.mark.parametrize("size_in, size_out", sizes)
+    @pytest.mark.parametrize("d_in, d_out", ds)
+    def test_QRVS_shape_consistency(self, qrng, size_in, size_out,
+                                    d_in, d_out):
+        gen = FastGeneratorInversion(stats.norm())
+
+        # If d and qrng.d are inconsistent, an error is raised
+        if d_in is not None and qrng is not None and qrng.d != d_in:
+            match = "`d` must be consistent with dimension of `qmc_engine`."
+            with pytest.raises(ValueError, match=match):
+                gen.qrvs(size_in, d=d_in, qmc_engine=qrng)
+            return
+
+        # Sometimes d is really determined by qrng
+        if d_in is None and qrng is not None and qrng.d != 1:
+            d_out = (qrng.d,)
+
+        shape_expected = size_out + d_out
+
+        qrng2 = deepcopy(qrng)
+        qrvs = gen.qrvs(size=size_in, d=d_in, qmc_engine=qrng)
+        if size_in is not None:
+            assert qrvs.shape == shape_expected
+
+        if qrng2 is not None:
+            uniform = qrng2.random(np.prod(size_in) or 1)
+            qrvs2 = stats.norm.ppf(uniform).reshape(shape_expected)
+            assert_allclose(qrvs, qrvs2, atol=1e-12)
+
+    def test_QRVS_size_tuple(self):
+        # QMCEngine samples are always of shape (n, d). When `size` is a tuple,
+        # we set `n = prod(size)` in the call to qmc_engine.random, transform
+        # the sample, and reshape it to the final dimensions. When we reshape,
+        # we need to be careful, because the _columns_ of the sample returned
+        # by a QMCEngine are "independent"-ish, but the elements within the
+        # columns are not. We need to make sure that this doesn't get mixed up
+        # by reshaping: qrvs[..., i] should remain "independent"-ish of
+        # qrvs[..., i+1], but the elements within qrvs[..., i] should be
+        # transformed from the same low-discrepancy sequence.
+
+        gen = FastGeneratorInversion(stats.norm())
+
+        size = (3, 4)
+        d = 5
+        qrng = stats.qmc.Halton(d, seed=0)
+        qrng2 = stats.qmc.Halton(d, seed=0)
+
+        uniform = qrng2.random(np.prod(size))
+
+        qrvs = gen.qrvs(size=size, d=d, qmc_engine=qrng)
+        qrvs2 = stats.norm.ppf(uniform)
+
+        for i in range(d):
+            sample = qrvs[..., i]
+            sample2 = qrvs2[:, i].reshape(size)
+            assert_allclose(sample, sample2, atol=1e-12)
+
+
+def test_burr_overflow():
+    # this case leads to an overflow error if math.exp is used
+    # in the definition of the burr pdf instead of np.exp
+    # a direct implementation of the PDF as x**(-c-1) / (1+x**(-c))**(d+1)
+    # also leads to an overflow error in the setup
+    args = (1.89128135, 0.30195177)
+    with suppress_warnings() as sup:
+        # filter potential overflow warning
+        sup.filter(RuntimeWarning)
+        gen = FastGeneratorInversion(stats.burr(*args))
+    u_error, _ = gen.evaluate_error(random_state=4326)
+    assert u_error <= 1e-10
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fit.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fit.py
new file mode 100644
index 0000000000000000000000000000000000000000..320c31cf30394b6edd05026b40c57622555656fc
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_fit.py
@@ -0,0 +1,1089 @@
+import os
+import numpy as np
+import numpy.testing as npt
+from numpy.testing import assert_allclose, assert_equal
+import pytest
+from scipy import stats
+from scipy.optimize import differential_evolution
+
+from .test_continuous_basic import distcont
+from scipy.stats._distn_infrastructure import FitError
+from scipy.stats._distr_params import distdiscrete
+from scipy.stats import goodness_of_fit
+
+
+# this is not a proper statistical test for convergence, but only
+# verifies that the estimate and true values don't differ by too much
+
+fit_sizes = [1000, 5000, 10000]  # sample sizes to try
+
+thresh_percent = 0.25  # percent of true parameters for fail cut-off
+thresh_min = 0.75  # minimum difference estimate - true to fail test
+
+mle_failing_fits = [
+        'dpareto_lognorm',
+        'gausshyper',
+        'genexpon',
+        'gengamma',
+        'irwinhall',
+        'kappa4',
+        'ksone',
+        'kstwo',
+        'ncf',
+        'ncx2',
+        'truncexpon',
+        'tukeylambda',
+        'vonmises',
+        'levy_stable',
+        'trapezoid',
+        'truncweibull_min',
+        'studentized_range',
+]
+
+# these pass but are XSLOW (>1s)
+mle_Xslow_fits = ['betaprime', 'crystalball', 'exponweib', 'f', 'geninvgauss',
+                  'jf_skew_t', 'recipinvgauss', 'rel_breitwigner', 'vonmises_line']
+
+# The MLE fit method of these distributions doesn't perform well when all
+# parameters are fit, so test them with the location fixed at 0.
+mle_use_floc0 = [
+    'burr',
+    'chi',
+    'chi2',
+    'mielke',
+    'pearson3',
+    'genhalflogistic',
+    'rdist',
+    'pareto',
+    'powerlaw',  # distfn.nnlf(est2, rvs) > distfn.nnlf(est1, rvs) otherwise
+    'powerlognorm',
+    'wrapcauchy',
+    'rel_breitwigner',
+]
+
+mm_failing_fits = ['alpha', 'betaprime', 'burr', 'burr12', 'cauchy', 'chi',
+                   'chi2', 'crystalball', 'dgamma', 'dpareto_lognorm', 'dweibull',
+                   'f', 'fatiguelife', 'fisk', 'foldcauchy', 'genextreme',
+                   'gengamma', 'genhyperbolic', 'gennorm', 'genpareto',
+                   'halfcauchy', 'invgamma', 'invweibull', 'irwinhall', 'jf_skew_t',
+                   'johnsonsu', 'kappa3', 'ksone', 'kstwo', 'landau', 'levy', 'levy_l',
+                   'levy_stable', 'loglaplace', 'lomax', 'mielke', 'nakagami',
+                   'ncf', 'nct', 'ncx2', 'pareto', 'powerlognorm', 'powernorm',
+                   'rel_breitwigner', 'skewcauchy', 't', 'trapezoid', 'triang',
+                   'truncpareto', 'truncweibull_min', 'tukeylambda',
+                   'studentized_range']
+
+# not sure if these fail, but they caused my patience to fail
+mm_XXslow_fits = ['argus', 'exponpow', 'exponweib', 'gausshyper', 'genexpon',
+                  'genhalflogistic', 'halfgennorm', 'gompertz', 'johnsonsb',
+                  'kappa4', 'kstwobign', 'recipinvgauss',
+                  'truncexpon', 'vonmises', 'vonmises_line']
+
+# these pass but are XSLOW (>1s)
+mm_Xslow_fits = ['wrapcauchy']
+
+failing_fits = {"MM": mm_failing_fits + mm_XXslow_fits, "MLE": mle_failing_fits}
+xslow_fits = {"MM": mm_Xslow_fits, "MLE": mle_Xslow_fits}
+fail_interval_censored = {"truncpareto"}
+
+# Don't run the fit test on these:
+skip_fit = [
+    'erlang',  # Subclass of gamma, generates a warning.
+    'genhyperbolic', 'norminvgauss',  # too slow
+]
+
+
+def cases_test_cont_fit():
+    # this tests the closeness of the estimated parameters to the true
+    # parameters with fit method of continuous distributions
+    # Note: is slow, some distributions don't converge with sample
+    # size <= 10000
+    for distname, arg in distcont:
+        if distname not in skip_fit:
+            yield distname, arg
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize('distname,arg', cases_test_cont_fit())
+@pytest.mark.parametrize('method', ["MLE", "MM"])
+def test_cont_fit(distname, arg, method):
+    run_xfail = int(os.getenv('SCIPY_XFAIL', default=False))
+    run_xslow = int(os.getenv('SCIPY_XSLOW', default=False))
+
+    if distname in failing_fits[method] and not run_xfail:
+        # The generic `fit` method can't be expected to work perfectly for all
+        # distributions, data, and guesses. Some failures are expected.
+        msg = "Failure expected; set environment variable SCIPY_XFAIL=1 to run."
+        pytest.xfail(msg)
+
+    if distname in xslow_fits[method] and not run_xslow:
+        msg = "Very slow; set environment variable SCIPY_XSLOW=1 to run."
+        pytest.skip(msg)
+
+    distfn = getattr(stats, distname)
+
+    truearg = np.hstack([arg, [0.0, 1.0]])
+    diffthreshold = np.max(np.vstack([truearg*thresh_percent,
+                                      np.full(distfn.numargs+2, thresh_min)]),
+                           0)
+
+    for fit_size in fit_sizes:
+        # Note that if a fit succeeds, the other fit_sizes are skipped
+        np.random.seed(1234)
+
+        with np.errstate(all='ignore'):
+            rvs = distfn.rvs(size=fit_size, *arg)
+            if method == 'MLE' and distfn.name in mle_use_floc0:
+                kwds = {'floc': 0}
+            else:
+                kwds = {}
+            # start with default values
+            est = distfn.fit(rvs, method=method, **kwds)
+            if method == 'MLE':
+                # Trivial test of the use of CensoredData.  The fit() method
+                # will check that data contains no actual censored data, and
+                # do a regular uncensored fit.
+                data1 = stats.CensoredData(rvs)
+                est1 = distfn.fit(data1, **kwds)
+                msg = ('Different results fitting uncensored data wrapped as'
+                       f' CensoredData: {distfn.name}: est={est} est1={est1}')
+                assert_allclose(est1, est, rtol=1e-10, err_msg=msg)
+            if method == 'MLE' and distname not in fail_interval_censored:
+                # Convert the first `nic` values in rvs to interval-censored
+                # values. The interval is small, so est2 should be close to
+                # est.
+                nic = 15
+                interval = np.column_stack((rvs, rvs))
+                interval[:nic, 0] *= 0.99
+                interval[:nic, 1] *= 1.01
+                interval.sort(axis=1)
+                data2 = stats.CensoredData(interval=interval)
+                est2 = distfn.fit(data2, **kwds)
+                msg = ('Different results fitting interval-censored'
+                       f' data: {distfn.name}: est={est} est2={est2}')
+                assert_allclose(est2, est, rtol=0.05, err_msg=msg)
+
+        diff = est - truearg
+
+        # threshold for location
+        diffthreshold[-2] = np.max([np.abs(rvs.mean())*thresh_percent,
+                                    thresh_min])
+
+        if np.any(np.isnan(est)):
+            raise AssertionError('nan returned in fit')
+        else:
+            if np.all(np.abs(diff) <= diffthreshold):
+                break
+    else:
+        txt = f'parameter: {str(truearg)}\n'
+        txt += f'estimated: {str(est)}\n'
+        txt += f'diff     : {str(diff)}\n'
+        raise AssertionError(f'fit not very good in {distfn.name}\n' + txt)
+
+
+def _check_loc_scale_mle_fit(name, data, desired, atol=None):
+    d = getattr(stats, name)
+    actual = d.fit(data)[-2:]
+    assert_allclose(actual, desired, atol=atol,
+                    err_msg=f'poor mle fit of (loc, scale) in {name}')
+
+
+def test_non_default_loc_scale_mle_fit():
+    data = np.array([1.01, 1.78, 1.78, 1.78, 1.88, 1.88, 1.88, 2.00])
+    _check_loc_scale_mle_fit('uniform', data, [1.01, 0.99], 1e-3)
+    _check_loc_scale_mle_fit('expon', data, [1.01, 0.73875], 1e-3)
+
+
+def test_expon_fit():
+    """gh-6167"""
+    data = [0, 0, 0, 0, 2, 2, 2, 2]
+    phat = stats.expon.fit(data, floc=0)
+    assert_allclose(phat, [0, 1.0], atol=1e-3)
+
+
+def test_fit_error():
+    data = np.concatenate([np.zeros(29), np.ones(21)])
+    message = "Optimization converged to parameters that are..."
+    with pytest.raises(FitError, match=message), \
+            pytest.warns(RuntimeWarning):
+        stats.beta.fit(data)
+
+
+@pytest.mark.parametrize("dist, params",
+                         [(stats.norm, (0.5, 2.5)),  # type: ignore[attr-defined]
+                          (stats.binom, (10, 0.3, 2))])  # type: ignore[attr-defined]
+def test_nnlf_and_related_methods(dist, params):
+    rng = np.random.default_rng(983459824)
+
+    if hasattr(dist, 'pdf'):
+        logpxf = dist.logpdf
+    else:
+        logpxf = dist.logpmf
+
+    x = dist.rvs(*params, size=100, random_state=rng)
+    ref = -logpxf(x, *params).sum()
+    res1 = dist.nnlf(params, x)
+    res2 = dist._penalized_nnlf(params, x)
+    assert_allclose(res1, ref)
+    assert_allclose(res2, ref)
+
+
+def cases_test_fit_mle():
+    # These fail default test or hang
+    skip_basic_fit = {'argus', 'irwinhall', 'foldnorm', 'truncpareto',
+                      'truncweibull_min', 'ksone', 'levy_stable',
+                      'studentized_range', 'kstwo',
+                      'beta', 'nakagami', 'truncnorm', # don't meet tolerance
+                      'poisson_binom'}  # vector-valued shape parameter
+
+    # Please keep this list in alphabetical order...
+    slow_basic_fit = {'alpha', 'arcsine', 'betaprime', 'binom', 'bradford', 'burr12',
+                      'chi', 'crystalball', 'dweibull', 'erlang', 'exponnorm',
+                      'exponpow', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'gamma',
+                      'genexpon', 'genextreme', 'gennorm', 'genpareto',
+                      'gompertz', 'halfgennorm', 'invgamma', 'invgauss', 'invweibull',
+                      'jf_skew_t', 'johnsonsb', 'johnsonsu', 'kappa3',
+                      'kstwobign', 'loglaplace', 'lognorm', 'lomax', 'mielke',
+                      'nbinom', 'norminvgauss',
+                      'pareto', 'pearson3', 'powerlaw', 'powernorm',
+                      'randint', 'rdist', 'recipinvgauss', 'rice', 'skewnorm',
+                      't', 'uniform', 'weibull_max', 'weibull_min', 'wrapcauchy'}
+
+    # Please keep this list in alphabetical order...
+    xslow_basic_fit = {'betabinom', 'betanbinom', 'burr', 'dpareto_lognorm',
+                       'exponweib', 'gausshyper', 'gengamma', 'genhalflogistic',
+                       'genhyperbolic', 'geninvgauss',
+                       'hypergeom', 'kappa4', 'loguniform',
+                       'ncf', 'nchypergeom_fisher', 'nchypergeom_wallenius',
+                       'nct', 'ncx2', 'nhypergeom',
+                       'powerlognorm', 'reciprocal', 'rel_breitwigner',
+                       'skellam', 'trapezoid', 'triang',
+                       'tukeylambda', 'vonmises', 'zipfian'}
+
+    for dist in dict(distdiscrete + distcont):
+        if dist in skip_basic_fit or not isinstance(dist, str):
+            reason = "tested separately"
+            yield pytest.param(dist, marks=pytest.mark.skip(reason=reason))
+        elif dist in slow_basic_fit:
+            reason = "too slow (>= 0.25s)"
+            yield pytest.param(dist, marks=pytest.mark.slow(reason=reason))
+        elif dist in xslow_basic_fit:
+            reason = "too slow (>= 1.0s)"
+            yield pytest.param(dist, marks=pytest.mark.xslow(reason=reason))
+        else:
+            yield dist
+
+
+def cases_test_fit_mse():
+    # the first four are so slow that I'm not sure whether they would pass
+    skip_basic_fit = {'levy_stable', 'studentized_range', 'ksone', 'skewnorm',
+                      'irwinhall', # hangs
+                      'norminvgauss',  # super slow (~1 hr) but passes
+                      'kstwo',  # very slow (~25 min) but passes
+                      'geninvgauss',  # quite slow (~4 minutes) but passes
+                      'gausshyper', 'genhyperbolic',  # integration warnings
+                      'tukeylambda',  # close, but doesn't meet tolerance
+                      'vonmises',  # can have negative CDF; doesn't play nice
+                      'arcsine', 'argus', 'powerlaw', 'rdist', # don't meet tolerance
+                      'poisson_binom',  # vector-valued shape parameter
+                      }
+
+    # Please keep this list in alphabetical order...
+    slow_basic_fit = {'alpha', 'anglit', 'betabinom', 'bradford',
+                      'chi', 'chi2', 'crystalball', 'dweibull',
+                      'erlang', 'exponnorm', 'exponpow', 'exponweib',
+                      'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm',
+                      'gamma', 'genexpon', 'genextreme', 'genhalflogistic',
+                      'genlogistic', 'genpareto', 'gompertz',
+                      'hypergeom', 'invweibull',
+                      'johnsonsu', 'kappa3', 'kstwobign',
+                      'laplace_asymmetric', 'loggamma', 'loglaplace',
+                      'lognorm', 'lomax',
+                      'maxwell', 'nhypergeom',
+                      'pareto', 'powernorm', 'randint', 'recipinvgauss',
+                      'semicircular',
+                      't', 'triang', 'truncexpon', 'truncpareto',
+                      'uniform',
+                      'wald', 'weibull_max', 'weibull_min', 'wrapcauchy'}
+
+    # Please keep this list in alphabetical order...
+    xslow_basic_fit = {'argus', 'beta', 'betaprime', 'burr', 'burr12',
+                       'dgamma', 'dpareto_lognorm', 'f', 'gengamma', 'gennorm',
+                       'halfgennorm', 'invgamma', 'invgauss', 'jf_skew_t',
+                       'johnsonsb', 'kappa4', 'loguniform', 'mielke',
+                       'nakagami', 'ncf', 'nchypergeom_fisher',
+                       'nchypergeom_wallenius', 'nct', 'ncx2',
+                       'pearson3', 'powerlognorm',
+                       'reciprocal', 'rel_breitwigner', 'rice',
+                       'trapezoid', 'truncnorm', 'truncweibull_min',
+                       'vonmises_line', 'zipfian'}
+
+    warns_basic_fit = {'skellam'}  # can remove mark after gh-14901 is resolved
+
+    for dist in dict(distdiscrete + distcont):
+        if dist in skip_basic_fit or not isinstance(dist, str):
+            reason = "Fails. Oh well."
+            yield pytest.param(dist, marks=pytest.mark.skip(reason=reason))
+        elif dist in slow_basic_fit:
+            reason = "too slow (>= 0.25s)"
+            yield pytest.param(dist, marks=pytest.mark.slow(reason=reason))
+        elif dist in xslow_basic_fit:
+            reason = "too slow (>= 1.0s)"
+            yield pytest.param(dist, marks=pytest.mark.xslow(reason=reason))
+        elif dist in warns_basic_fit:
+            mark = pytest.mark.filterwarnings('ignore::RuntimeWarning')
+            yield pytest.param(dist, marks=mark)
+        else:
+            yield dist
+
+
+def cases_test_fitstart():
+    for distname, shapes in dict(distcont).items():
+        if (not isinstance(distname, str) or
+                distname in {'studentized_range', 'recipinvgauss'}):  # slow
+            continue
+        yield distname, shapes
+
+
+@pytest.mark.parametrize('distname, shapes', cases_test_fitstart())
+def test_fitstart(distname, shapes):
+    dist = getattr(stats, distname)
+    rng = np.random.default_rng(216342614)
+    data = rng.random(10)
+
+    with np.errstate(invalid='ignore', divide='ignore'):  # irrelevant to test
+        guess = dist._fitstart(data)
+
+    assert dist._argcheck(*guess[:-2])
+
+
+def assert_nlff_less_or_close(dist, data, params1, params0, rtol=1e-7, atol=0,
+                              nlff_name='nnlf'):
+    nlff = getattr(dist, nlff_name)
+    nlff1 = nlff(params1, data)
+    nlff0 = nlff(params0, data)
+    if not (nlff1 < nlff0):
+        np.testing.assert_allclose(nlff1, nlff0, rtol=rtol, atol=atol)
+
+
+class TestFit:
+    dist = stats.binom  # type: ignore[attr-defined]
+    seed = 654634816187
+    rng = np.random.default_rng(seed)
+    data = stats.binom.rvs(5, 0.5, size=100, random_state=rng)  # type: ignore[attr-defined]  # noqa: E501
+    shape_bounds_a = [(1, 10), (0, 1)]
+    shape_bounds_d = {'n': (1, 10), 'p': (0, 1)}
+    atol = 5e-2
+    rtol = 1e-2
+    tols = {'atol': atol, 'rtol': rtol}
+
+    def opt(self, *args, rng=1, **kwds):
+        return differential_evolution(*args, rng=rng, **kwds)
+
+    def test_dist_iv(self):
+        message = "`dist` must be an instance of..."
+        with pytest.raises(ValueError, match=message):
+            stats.fit(10, self.data, self.shape_bounds_a)
+
+    def test_data_iv(self):
+        message = "`data` must be exactly one-dimensional."
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, [[1, 2, 3]], self.shape_bounds_a)
+
+        message = "All elements of `data` must be finite numbers."
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, [1, 2, 3, np.nan], self.shape_bounds_a)
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, [1, 2, 3, np.inf], self.shape_bounds_a)
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, ['1', '2', '3'], self.shape_bounds_a)
+
+    def test_bounds_iv(self):
+        message = "Bounds provided for the following unrecognized..."
+        shape_bounds = {'n': (1, 10), 'p': (0, 1), '1': (0, 10)}
+        with pytest.warns(RuntimeWarning, match=message):
+            stats.fit(self.dist, self.data, shape_bounds)
+
+        message = "Each element of a `bounds` sequence must be a tuple..."
+        shape_bounds = [(1, 10, 3), (0, 1)]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, shape_bounds)
+
+        message = "Each element of `bounds` must be a tuple specifying..."
+        shape_bounds = [(1, 10, 3), (0, 1, 0.5)]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, shape_bounds)
+        shape_bounds = [1, 0]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, shape_bounds)
+
+        message = "A `bounds` sequence must contain at least 2 elements..."
+        shape_bounds = [(1, 10)]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, shape_bounds)
+
+        message = "A `bounds` sequence may not contain more than 3 elements..."
+        bounds = [(1, 10), (1, 10), (1, 10), (1, 10)]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, bounds)
+
+        message = "There are no values for `p` on the interval..."
+        shape_bounds = {'n': (1, 10), 'p': (1, 0)}
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, shape_bounds)
+
+        message = "There are no values for `n` on the interval..."
+        shape_bounds = [(10, 1), (0, 1)]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, shape_bounds)
+
+        message = "There are no integer values for `n` on the interval..."
+        shape_bounds = [(1.4, 1.6), (0, 1)]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, shape_bounds)
+
+        message = "The intersection of user-provided bounds for `n`"
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data)
+        shape_bounds = [(-np.inf, np.inf), (0, 1)]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, shape_bounds)
+
+    def test_guess_iv(self):
+        message = "Guesses provided for the following unrecognized..."
+        guess = {'n': 1, 'p': 0.5, '1': 255}
+        with pytest.warns(RuntimeWarning, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+
+        message = "Each element of `guess` must be a scalar..."
+        guess = {'n': 1, 'p': 'hi'}
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+        guess = [1, 'f']
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+        guess = [[1, 2]]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+
+        message = "A `guess` sequence must contain at least 2..."
+        guess = [1]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+
+        message = "A `guess` sequence may not contain more than 3..."
+        guess = [1, 2, 3, 4]
+        with pytest.raises(ValueError, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+
+        message = "Guess for parameter `n` rounded.*|Guess for parameter `p` clipped.*"
+        guess = {'n': 4.5, 'p': -0.5}
+        with pytest.warns(RuntimeWarning, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+
+        message = "Guess for parameter `loc` rounded..."
+        guess = [5, 0.5, 0.5]
+        with pytest.warns(RuntimeWarning, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+
+        message = "Guess for parameter `p` clipped..."
+        guess = {'n': 5, 'p': -0.5}
+        with pytest.warns(RuntimeWarning, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+
+        message = "Guess for parameter `loc` clipped..."
+        guess = [5, 0.5, 1]
+        with pytest.warns(RuntimeWarning, match=message):
+            stats.fit(self.dist, self.data, self.shape_bounds_d, guess=guess)
+
+    def basic_fit_test(self, dist_name, method, rng=1):
+
+        N = 5000
+        dist_data = dict(distcont + distdiscrete)
+        rng = np.random.default_rng(self.seed)
+        dist = getattr(stats, dist_name)
+        shapes = np.array(dist_data[dist_name])
+        bounds = np.empty((len(shapes) + 2, 2), dtype=np.float64)
+        bounds[:-2, 0] = shapes/10.**np.sign(shapes)
+        bounds[:-2, 1] = shapes*10.**np.sign(shapes)
+        bounds[-2] = (0, 10)
+        bounds[-1] = (1e-16, 10)
+        loc = rng.uniform(*bounds[-2])
+        scale = rng.uniform(*bounds[-1])
+        ref = list(dist_data[dist_name]) + [loc, scale]
+
+        if getattr(dist, 'pmf', False):
+            ref = ref[:-1]
+            ref[-1] = np.floor(loc)
+            data = dist.rvs(*ref, size=N, random_state=rng)
+            bounds = bounds[:-1]
+        if getattr(dist, 'pdf', False):
+            data = dist.rvs(*ref, size=N, random_state=rng)
+
+        with npt.suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "overflow encountered")
+            res = stats.fit(dist, data, bounds, method=method,
+                            optimizer=self.opt)
+
+        nlff_names = {'mle': 'nnlf', 'mse': '_penalized_nlpsf'}
+        nlff_name = nlff_names[method]
+        assert_nlff_less_or_close(dist, data, res.params, ref, **self.tols,
+                                  nlff_name=nlff_name)
+
+    @pytest.mark.parametrize("dist_name", cases_test_fit_mle())
+    def test_basic_fit_mle(self, dist_name):
+        self.basic_fit_test(dist_name, "mle", rng=5)
+
+    @pytest.mark.parametrize("dist_name", cases_test_fit_mse())
+    def test_basic_fit_mse(self, dist_name):
+        self.basic_fit_test(dist_name, "mse", rng=2)
+
+    @pytest.mark.slow
+    def test_arcsine(self):
+        # Can't guarantee that all distributions will fit all data with
+        # arbitrary bounds. This distribution just happens to fail above.
+        # Try something slightly different.
+        N = 1000
+        rng = np.random.default_rng(self.seed)
+        dist = stats.arcsine
+        shapes = (1., 2.)
+        data = dist.rvs(*shapes, size=N, random_state=rng)
+        shape_bounds = {'loc': (0.1, 10), 'scale': (0.1, 10)}
+        res = stats.fit(dist, data, shape_bounds, method='mse', optimizer=self.opt)
+        assert_nlff_less_or_close(dist, data, res.params, shapes,
+                                  nlff_name='_penalized_nlpsf', **self.tols)
+
+    @pytest.mark.parametrize("method", ('mle', 'mse'))
+    def test_argus(self, method):
+        # Can't guarantee that all distributions will fit all data with
+        # arbitrary bounds. This distribution just happens to fail above.
+        # Try something slightly different.
+        N = 1000
+        rng = np.random.default_rng(self.seed)
+        dist = stats.argus
+        shapes = (1., 2., 3.)
+        data = dist.rvs(*shapes, size=N, random_state=rng)
+        shape_bounds = {'chi': (0.1, 10), 'loc': (0.1, 10), 'scale': (0.1, 10)}
+        res = stats.fit(dist, data, shape_bounds, optimizer=self.opt, method=method)
+        nlff_name = {'mle': 'nnlf', 'mse': '_penalized_nlpsf'}[method]
+        assert_nlff_less_or_close(dist, data, res.params, shapes, **self.tols,
+                                  nlff_name=nlff_name)
+
+    @pytest.mark.xslow
+    def test_beta(self):
+        # Can't guarantee that all distributions will fit all data with
+        # arbitrary bounds. This distribution just happens to fail above.
+        # Try something slightly different.
+        N = 1000
+        rng = np.random.default_rng(self.seed)
+        dist = stats.beta
+        shapes = (2.3098496451481823, 0.62687954300963677, 1., 2.)
+        data = dist.rvs(*shapes, size=N, random_state=rng)
+        shape_bounds = {'a': (0.1, 10), 'b':(0.1, 10),
+                        'loc': (0.1, 10), 'scale': (0.1, 10)}
+        res = stats.fit(dist, data, shape_bounds, method='mle', optimizer=self.opt)
+        assert_nlff_less_or_close(dist, data, res.params, shapes,
+                                  nlff_name='nnlf', **self.tols)
+
+    def test_foldnorm(self):
+        # Can't guarantee that all distributions will fit all data with
+        # arbitrary bounds. This distribution just happens to fail above.
+        # Try something slightly different.
+        N = 1000
+        rng = np.random.default_rng(self.seed)
+        dist = stats.foldnorm
+        shapes = (1.952125337355587, 2., 3.)
+        data = dist.rvs(*shapes, size=N, random_state=rng)
+        shape_bounds = {'c': (0.1, 10), 'loc': (0.1, 10), 'scale': (0.1, 10)}
+        res = stats.fit(dist, data, shape_bounds, optimizer=self.opt)
+
+        assert_nlff_less_or_close(dist, data, res.params, shapes, **self.tols)
+
+    def test_nakagami(self):
+        # Can't guarantee that all distributions will fit all data with
+        # arbitrary bounds. This distribution just happens to fail above.
+        # Try something slightly different.
+        N = 1000
+        rng = np.random.default_rng(self.seed)
+        dist = stats.nakagami
+        shapes = (4.9673794866666237, 1., 2.)
+        data = dist.rvs(*shapes, size=N, random_state=rng)
+        shape_bounds = {'nu':(0.1, 10), 'loc': (0.1, 10), 'scale': (0.1, 10)}
+        res = stats.fit(dist, data, shape_bounds, method='mle', optimizer=self.opt)
+        assert_nlff_less_or_close(dist, data, res.params, shapes,
+                                  nlff_name='nnlf', **self.tols)
+
+    @pytest.mark.slow
+    def test_powerlaw(self):
+        # Can't guarantee that all distributions will fit all data with
+        # arbitrary bounds. This distribution just happens to fail above.
+        # Try something slightly different.
+        N = 1000
+        rng = np.random.default_rng(self.seed)
+        dist = stats.powerlaw
+        shapes = (1.6591133289905851, 1., 2.)
+        data = dist.rvs(*shapes, size=N, random_state=rng)
+        shape_bounds = {'a': (0.1, 10), 'loc': (0.1, 10), 'scale': (0.1, 10)}
+        res = stats.fit(dist, data, shape_bounds, method='mse', optimizer=self.opt)
+        assert_nlff_less_or_close(dist, data, res.params, shapes,
+                                  nlff_name='_penalized_nlpsf', **self.tols)
+
+    def test_truncpareto(self):
+        # Can't guarantee that all distributions will fit all data with
+        # arbitrary bounds. This distribution just happens to fail above.
+        # Try something slightly different.
+        N = 1000
+        rng = np.random.default_rng(self.seed)
+        dist = stats.truncpareto
+        shapes = (1.8, 5.3, 2.3, 4.1)
+        data = dist.rvs(*shapes, size=N, random_state=rng)
+        shape_bounds = [(0.1, 10)]*4
+        res = stats.fit(dist, data, shape_bounds, optimizer=self.opt)
+
+        assert_nlff_less_or_close(dist, data, res.params, shapes, **self.tols)
+
+    @pytest.mark.slow
+    def test_truncweibull_min(self):
+        # Can't guarantee that all distributions will fit all data with
+        # arbitrary bounds. This distribution just happens to fail above.
+        # Try something slightly different.
+        N = 1000
+        rng = np.random.default_rng(self.seed)
+        dist = stats.truncweibull_min
+        shapes = (2.5, 0.25, 1.75, 2., 3.)
+        data = dist.rvs(*shapes, size=N, random_state=rng)
+        shape_bounds = [(0.1, 10)]*5
+        res = stats.fit(dist, data, shape_bounds, optimizer=self.opt)
+
+        assert_nlff_less_or_close(dist, data, res.params, shapes, **self.tols)
+
+    def test_missing_shape_bounds(self):
+        # some distributions have a small domain w.r.t. a parameter, e.g.
+        # $p \in [0, 1]$ for binomial distribution
+        # User does not need to provide these because the intersection of the
+        # user's bounds (none) and the distribution's domain is finite
+        N = 1000
+        rng = np.random.default_rng(self.seed)
+
+        dist = stats.binom
+        n, p, loc = 10, 0.65, 0
+        data = dist.rvs(n, p, loc=loc, size=N, random_state=rng)
+        shape_bounds = {'n': np.array([0, 20])}  # check arrays are OK, too
+        res = stats.fit(dist, data, shape_bounds, optimizer=self.opt)
+        assert_allclose(res.params, (n, p, loc), **self.tols)
+
+        dist = stats.bernoulli
+        p, loc = 0.314159, 0
+        data = dist.rvs(p, loc=loc, size=N, random_state=rng)
+        res = stats.fit(dist, data, optimizer=self.opt)
+        assert_allclose(res.params, (p, loc), **self.tols)
+
+    def test_fit_only_loc_scale(self):
+        # fit only loc
+        N = 5000
+        rng = np.random.default_rng(self.seed)
+
+        dist = stats.norm
+        loc, scale = 1.5, 1
+        data = dist.rvs(loc=loc, size=N, random_state=rng)
+        loc_bounds = (0, 5)
+        bounds = {'loc': loc_bounds}
+        res = stats.fit(dist, data, bounds, optimizer=self.opt)
+        assert_allclose(res.params, (loc, scale), **self.tols)
+
+        # fit only scale
+        loc, scale = 0, 2.5
+        data = dist.rvs(scale=scale, size=N, random_state=rng)
+        scale_bounds = (0.01, 5)
+        bounds = {'scale': scale_bounds}
+        res = stats.fit(dist, data, bounds, optimizer=self.opt)
+        assert_allclose(res.params, (loc, scale), **self.tols)
+
+        # fit only loc and scale
+        dist = stats.norm
+        loc, scale = 1.5, 2.5
+        data = dist.rvs(loc=loc, scale=scale, size=N, random_state=rng)
+        bounds = {'loc': loc_bounds, 'scale': scale_bounds}
+        res = stats.fit(dist, data, bounds, optimizer=self.opt)
+        assert_allclose(res.params, (loc, scale), **self.tols)
+
+    def test_everything_fixed(self):
+        N = 5000
+        rng = np.random.default_rng(self.seed)
+
+        dist = stats.norm
+        loc, scale = 1.5, 2.5
+        data = dist.rvs(loc=loc, scale=scale, size=N, random_state=rng)
+
+        # loc, scale fixed to 0, 1 by default
+        res = stats.fit(dist, data)
+        assert_allclose(res.params, (0, 1), **self.tols)
+
+        # loc, scale explicitly fixed
+        bounds = {'loc': (loc, loc), 'scale': (scale, scale)}
+        res = stats.fit(dist, data, bounds)
+        assert_allclose(res.params, (loc, scale), **self.tols)
+
+        # `n` gets fixed during polishing
+        dist = stats.binom
+        n, p, loc = 10, 0.65, 0
+        data = dist.rvs(n, p, loc=loc, size=N, random_state=rng)
+        shape_bounds = {'n': (0, 20), 'p': (0.65, 0.65)}
+        res = stats.fit(dist, data, shape_bounds, optimizer=self.opt)
+        assert_allclose(res.params, (n, p, loc), **self.tols)
+
+    def test_failure(self):
+        N = 5000
+        rng = np.random.default_rng(self.seed)
+
+        dist = stats.nbinom
+        shapes = (5, 0.5)
+        data = dist.rvs(*shapes, size=N, random_state=rng)
+
+        assert data.min() == 0
+        # With lower bounds on location at 0.5, likelihood is zero
+        bounds = [(0, 30), (0, 1), (0.5, 10)]
+        res = stats.fit(dist, data, bounds)
+        message = "Optimization converged to parameter values that are"
+        assert res.message.startswith(message)
+        assert res.success is False
+
+    @pytest.mark.xslow
+    def test_guess(self):
+        # Test that guess helps DE find the desired solution
+        N = 2000
+        # With some seeds, `fit` doesn't need a guess
+        rng = np.random.default_rng(196390444561)
+        dist = stats.nhypergeom
+        params = (20, 7, 12, 0)
+        bounds = [(2, 200), (0.7, 70), (1.2, 120), (0, 10)]
+
+        data = dist.rvs(*params, size=N, random_state=rng)
+
+        res = stats.fit(dist, data, bounds, optimizer=self.opt)
+        assert not np.allclose(res.params, params, **self.tols)
+
+        res = stats.fit(dist, data, bounds, guess=params, optimizer=self.opt)
+        assert_allclose(res.params, params, **self.tols)
+
+    def test_mse_accuracy_1(self):
+        # Test maximum spacing estimation against example from Wikipedia
+        # https://en.wikipedia.org/wiki/Maximum_spacing_estimation#Examples
+        data = [2, 4]
+        dist = stats.expon
+        bounds = {'loc': (0, 0), 'scale': (1e-8, 10)}
+        res_mle = stats.fit(dist, data, bounds=bounds, method='mle')
+        assert_allclose(res_mle.params.scale, 3, atol=1e-3)
+        res_mse = stats.fit(dist, data, bounds=bounds, method='mse')
+        assert_allclose(res_mse.params.scale, 3.915, atol=1e-3)
+
+    def test_mse_accuracy_2(self):
+        # Test maximum spacing estimation against example from Wikipedia
+        # https://en.wikipedia.org/wiki/Maximum_spacing_estimation#Examples
+        rng = np.random.default_rng(9843212616816518964)
+
+        dist = stats.uniform
+        n = 10
+        data = dist(3, 6).rvs(size=n, random_state=rng)
+        bounds = {'loc': (0, 10), 'scale': (1e-8, 10)}
+        res = stats.fit(dist, data, bounds=bounds, method='mse')
+        # (loc=3.608118420015416, scale=5.509323262055043)
+
+        x = np.sort(data)
+        a = (n*x[0] - x[-1])/(n - 1)
+        b = (n*x[-1] - x[0])/(n - 1)
+        ref = a, b-a  # (3.6081133632151503, 5.509328130317254)
+        assert_allclose(res.params, ref, rtol=1e-4)
+
+
+# Data from Matlab: https://www.mathworks.com/help/stats/lillietest.html
+examgrades = [65, 61, 81, 88, 69, 89, 55, 84, 86, 84, 71, 81, 84, 81, 78, 67,
+              96, 66, 73, 75, 59, 71, 69, 63, 79, 76, 63, 85, 87, 88, 80, 71,
+              65, 84, 71, 75, 81, 79, 64, 65, 84, 77, 70, 75, 84, 75, 73, 92,
+              90, 79, 80, 71, 73, 71, 58, 79, 73, 64, 77, 82, 81, 59, 54, 82,
+              57, 79, 79, 73, 74, 82, 63, 64, 73, 69, 87, 68, 81, 73, 83, 73,
+              80, 73, 73, 71, 66, 78, 64, 74, 68, 67, 75, 75, 80, 85, 74, 76,
+              80, 77, 93, 70, 86, 80, 81, 83, 68, 60, 85, 64, 74, 82, 81, 77,
+              66, 85, 75, 81, 69, 60, 83, 72]
+
+
+class TestGoodnessOfFit:
+
+    def test_gof_iv(self):
+        dist = stats.norm
+        x = [1, 2, 3]
+
+        message = r"`dist` must be a \(non-frozen\) instance of..."
+        with pytest.raises(TypeError, match=message):
+            goodness_of_fit(stats.norm(), x)
+
+        message = "`data` must be a one-dimensional array of numbers."
+        with pytest.raises(ValueError, match=message):
+            goodness_of_fit(dist, [[1, 2, 3]])
+
+        message = "`statistic` must be one of..."
+        with pytest.raises(ValueError, match=message):
+            goodness_of_fit(dist, x, statistic='mm')
+
+        message = "`n_mc_samples` must be an integer."
+        with pytest.raises(TypeError, match=message):
+            goodness_of_fit(dist, x, n_mc_samples=1000.5)
+
+        message = "SeedSequence expects int or sequence"
+        with pytest.raises(TypeError, match=message):
+            goodness_of_fit(dist, x, rng='herring')
+
+    def test_against_ks(self):
+        rng = np.random.default_rng(8517426291317196949)
+        x = examgrades
+        known_params = {'loc': np.mean(x), 'scale': np.std(x, ddof=1)}
+        res = goodness_of_fit(stats.norm, x, known_params=known_params,
+                              statistic='ks', rng=rng)
+        ref = stats.kstest(x, stats.norm(**known_params).cdf, method='exact')
+        assert_allclose(res.statistic, ref.statistic)  # ~0.0848
+        assert_allclose(res.pvalue, ref.pvalue, atol=5e-3)  # ~0.335
+
+    def test_against_lilliefors(self):
+        rng = np.random.default_rng(2291803665717442724)
+        x = examgrades
+        # preserve use of old random_state during SPEC 7 transition
+        res = goodness_of_fit(stats.norm, x, statistic='ks', random_state=rng)
+        known_params = {'loc': np.mean(x), 'scale': np.std(x, ddof=1)}
+        ref = stats.kstest(x, stats.norm(**known_params).cdf, method='exact')
+        assert_allclose(res.statistic, ref.statistic)  # ~0.0848
+        assert_allclose(res.pvalue, 0.0348, atol=5e-3)
+
+    def test_against_cvm(self):
+        rng = np.random.default_rng(8674330857509546614)
+        x = examgrades
+        known_params = {'loc': np.mean(x), 'scale': np.std(x, ddof=1)}
+        res = goodness_of_fit(stats.norm, x, known_params=known_params,
+                              statistic='cvm', rng=rng)
+        ref = stats.cramervonmises(x, stats.norm(**known_params).cdf)
+        assert_allclose(res.statistic, ref.statistic)  # ~0.090
+        assert_allclose(res.pvalue, ref.pvalue, atol=5e-3)  # ~0.636
+
+    def test_against_anderson_case_0(self):
+        # "Case 0" is where loc and scale are known [1]
+        rng = np.random.default_rng(7384539336846690410)
+        x = np.arange(1, 101)
+        # loc that produced critical value of statistic found w/ root_scalar
+        known_params = {'loc': 45.01575354024957, 'scale': 30}
+        res = goodness_of_fit(stats.norm, x, known_params=known_params,
+                              statistic='ad', rng=rng)
+        assert_allclose(res.statistic, 2.492)  # See [1] Table 1A 1.0
+        assert_allclose(res.pvalue, 0.05, atol=5e-3)
+
+    def test_against_anderson_case_1(self):
+        # "Case 1" is where scale is known and loc is fit [1]
+        rng = np.random.default_rng(5040212485680146248)
+        x = np.arange(1, 101)
+        # scale that produced critical value of statistic found w/ root_scalar
+        known_params = {'scale': 29.957112639101933}
+        res = goodness_of_fit(stats.norm, x, known_params=known_params,
+                              statistic='ad', rng=rng)
+        assert_allclose(res.statistic, 0.908)  # See [1] Table 1B 1.1
+        assert_allclose(res.pvalue, 0.1, atol=5e-3)
+
+    def test_against_anderson_case_2(self):
+        # "Case 2" is where loc is known and scale is fit [1]
+        rng = np.random.default_rng(726693985720914083)
+        x = np.arange(1, 101)
+        # loc that produced critical value of statistic found w/ root_scalar
+        known_params = {'loc': 44.5680212261933}
+        res = goodness_of_fit(stats.norm, x, known_params=known_params,
+                              statistic='ad', rng=rng)
+        assert_allclose(res.statistic, 2.904)  # See [1] Table 1B 1.2
+        assert_allclose(res.pvalue, 0.025, atol=5e-3)
+
+    def test_against_anderson_case_3(self):
+        # "Case 3" is where both loc and scale are fit [1]
+        rng = np.random.default_rng(6763691329830218206)
+        # c that produced critical value of statistic found w/ root_scalar
+        x = stats.skewnorm.rvs(1.4477847789132101, loc=1, scale=2, size=100,
+                               random_state=rng)
+        res = goodness_of_fit(stats.norm, x, statistic='ad', rng=rng)
+        assert_allclose(res.statistic, 0.559)  # See [1] Table 1B 1.2
+        assert_allclose(res.pvalue, 0.15, atol=5e-3)
+
+    @pytest.mark.xslow
+    def test_against_anderson_gumbel_r(self):
+        rng = np.random.default_rng(7302761058217743)
+        # c that produced critical value of statistic found w/ root_scalar
+        x = stats.genextreme(0.051896837188595134, loc=0.5,
+                             scale=1.5).rvs(size=1000, random_state=rng)
+        res = goodness_of_fit(stats.gumbel_r, x, statistic='ad',
+                              rng=rng)
+        ref = stats.anderson(x, dist='gumbel_r')
+        assert_allclose(res.statistic, ref.critical_values[0])
+        assert_allclose(res.pvalue, ref.significance_level[0]/100, atol=5e-3)
+
+    def test_against_filliben_norm(self):
+        # Test against `stats.fit` ref. [7] Section 8 "Example"
+        rng = np.random.default_rng(8024266430745011915)
+        y = [6, 1, -4, 8, -2, 5, 0]
+        known_params = {'loc': 0, 'scale': 1}
+        res = stats.goodness_of_fit(stats.norm, y, known_params=known_params,
+                                    statistic="filliben", rng=rng)
+        # Slight discrepancy presumably due to roundoff in Filliben's
+        # calculation. Using exact order statistic medians instead of
+        # Filliben's approximation doesn't account for it.
+        assert_allclose(res.statistic, 0.98538, atol=1e-4)
+        assert 0.75 < res.pvalue < 0.9
+
+        # Using R's ppcc library:
+        # library(ppcc)
+        # options(digits=16)
+        # x < - c(6, 1, -4, 8, -2, 5, 0)
+        # set.seed(100)
+        # ppccTest(x, "qnorm", ppos="Filliben")
+        # Discrepancy with
+        assert_allclose(res.statistic, 0.98540957187084, rtol=2e-5)
+        assert_allclose(res.pvalue, 0.8875, rtol=2e-3)
+
+    def test_filliben_property(self):
+        # Filliben's statistic should be independent of data location and scale
+        rng = np.random.default_rng(8535677809395478813)
+        x = rng.normal(loc=10, scale=0.5, size=100)
+        res = stats.goodness_of_fit(stats.norm, x,
+                                    statistic="filliben", rng=rng)
+        known_params = {'loc': 0, 'scale': 1}
+        ref = stats.goodness_of_fit(stats.norm, x, known_params=known_params,
+                                    statistic="filliben", rng=rng)
+        assert_allclose(res.statistic, ref.statistic, rtol=1e-15)
+
+    @pytest.mark.parametrize('case', [(25, [.928, .937, .950, .958, .966]),
+                                      (50, [.959, .965, .972, .977, .981]),
+                                      (95, [.977, .979, .983, .986, .989])])
+    def test_against_filliben_norm_table(self, case):
+        # Test against `stats.fit` ref. [7] Table 1
+        rng = np.random.default_rng(504569995557928957)
+        n, ref = case
+        x = rng.random(n)
+        known_params = {'loc': 0, 'scale': 1}
+        res = stats.goodness_of_fit(stats.norm, x, known_params=known_params,
+                                    statistic="filliben", rng=rng)
+        percentiles = np.array([0.005, 0.01, 0.025, 0.05, 0.1])
+        res = stats.scoreatpercentile(res.null_distribution, percentiles*100)
+        assert_allclose(res, ref, atol=2e-3)
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize('case', [(5, 0.95772790260469, 0.4755),
+                                      (6, 0.95398832257958, 0.3848),
+                                      (7, 0.9432692889277, 0.2328)])
+    def test_against_ppcc(self, case):
+        # Test against R ppcc, e.g.
+        # library(ppcc)
+        # options(digits=16)
+        # x < - c(0.52325412, 1.06907699, -0.36084066, 0.15305959, 0.99093194)
+        # set.seed(100)
+        # ppccTest(x, "qrayleigh", ppos="Filliben")
+        n, ref_statistic, ref_pvalue = case
+        rng = np.random.default_rng(7777775561439803116)
+        x = rng.normal(size=n)
+        res = stats.goodness_of_fit(stats.rayleigh, x, statistic="filliben",
+                                    rng=rng)
+        assert_allclose(res.statistic, ref_statistic, rtol=1e-4)
+        assert_allclose(res.pvalue, ref_pvalue, atol=1.5e-2)
+
+    def test_params_effects(self):
+        # Ensure that `guessed_params`, `fit_params`, and `known_params` have
+        # the intended effects.
+        rng = np.random.default_rng(9121950977643805391)
+        x = stats.skewnorm.rvs(-5.044559778383153, loc=1, scale=2, size=50,
+                               random_state=rng)
+
+        # Show that `guessed_params` don't fit to the guess,
+        # but `fit_params` and `known_params` respect the provided fit
+        guessed_params = {'c': 13.4}
+        fit_params = {'scale': 13.73}
+        known_params = {'loc': -13.85}
+        rng = np.random.default_rng(9121950977643805391)
+        res1 = goodness_of_fit(stats.weibull_min, x, n_mc_samples=2,
+                               guessed_params=guessed_params,
+                               fit_params=fit_params,
+                               known_params=known_params, rng=rng)
+        assert not np.allclose(res1.fit_result.params.c, 13.4)
+        assert_equal(res1.fit_result.params.scale, 13.73)
+        assert_equal(res1.fit_result.params.loc, -13.85)
+
+        # Show that changing the guess changes the parameter that gets fit,
+        # and it changes the null distribution
+        guessed_params = {'c': 2}
+        rng = np.random.default_rng(9121950977643805391)
+        res2 = goodness_of_fit(stats.weibull_min, x, n_mc_samples=2,
+                               guessed_params=guessed_params,
+                               fit_params=fit_params,
+                               known_params=known_params, rng=rng)
+        assert not np.allclose(res2.fit_result.params.c,
+                               res1.fit_result.params.c, rtol=1e-8)
+        assert not np.allclose(res2.null_distribution,
+                               res1.null_distribution, rtol=1e-8)
+        assert_equal(res2.fit_result.params.scale, 13.73)
+        assert_equal(res2.fit_result.params.loc, -13.85)
+
+        # If we set all parameters as fit_params and known_params,
+        # they're all fixed to those values, but the null distribution
+        # varies.
+        fit_params = {'c': 13.4, 'scale': 13.73}
+        rng = np.random.default_rng(9121950977643805391)
+        res3 = goodness_of_fit(stats.weibull_min, x, n_mc_samples=2,
+                               guessed_params=guessed_params,
+                               fit_params=fit_params,
+                               known_params=known_params, rng=rng)
+        assert_equal(res3.fit_result.params.c, 13.4)
+        assert_equal(res3.fit_result.params.scale, 13.73)
+        assert_equal(res3.fit_result.params.loc, -13.85)
+        assert not np.allclose(res3.null_distribution, res1.null_distribution)
+
+    def test_custom_statistic(self):
+        # Test support for custom statistic function.
+
+        # References:
+        # [1] Pyke, R. (1965).  "Spacings".  Journal of the Royal Statistical
+        #     Society: Series B (Methodological), 27(3): 395-436.
+        # [2] Burrows, P. M. (1979).  "Selected Percentage Points of
+        #     Greenwood's Statistics".  Journal of the Royal Statistical
+        #     Society. Series A (General), 142(2): 256-258.
+
+        # Use the Greenwood statistic for illustration; see [1, p.402].
+        def greenwood(dist, data, *, axis):
+            x = np.sort(data, axis=axis)
+            y = dist.cdf(x)
+            d = np.diff(y, axis=axis, prepend=0, append=1)
+            return np.sum(d ** 2, axis=axis)
+
+        # Run the Monte Carlo test with sample size = 5 on a fully specified
+        # null distribution, and compare the simulated quantiles to the exact
+        # ones given in [2, Table 1, column (n = 5)].
+        rng = np.random.default_rng(9121950977643805391)
+        data = stats.expon.rvs(size=5, random_state=rng)
+        result = goodness_of_fit(stats.expon, data,
+                                 known_params={'loc': 0, 'scale': 1},
+                                 statistic=greenwood, rng=rng)
+        p = [.01, .05, .1, .2, .3, .4, .5, .6, .7, .8, .9, .95, .99]
+        exact_quantiles = [
+            .183863, .199403, .210088, .226040, .239947, .253677, .268422,
+            .285293, .306002, .334447, .382972, .432049, .547468]
+        simulated_quantiles = np.quantile(result.null_distribution, p)
+        assert_allclose(simulated_quantiles, exact_quantiles, atol=0.005)
+
+class TestFitResult:
+    def test_plot_iv(self):
+        rng = np.random.default_rng(1769658657308472721)
+        data = stats.norm.rvs(0, 1, size=100, random_state=rng)
+
+        def optimizer(*args, **kwargs):
+            return differential_evolution(*args, **kwargs, rng=rng)
+
+        bounds = [(0, 30), (0, 1)]
+        res = stats.fit(stats.norm, data, bounds, optimizer=optimizer)
+        try:
+            import matplotlib  # noqa: F401
+            message = r"`plot_type` must be one of \{'..."
+            with pytest.raises(ValueError, match=message):
+                res.plot(plot_type='llama')
+        except (ModuleNotFoundError, ImportError):
+            message = r"matplotlib must be installed to use method `plot`."
+            with pytest.raises(ModuleNotFoundError, match=message):
+                res.plot(plot_type='llama')
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_hypotests.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_hypotests.py
new file mode 100644
index 0000000000000000000000000000000000000000..e996f9567248383d96beba09243ad1a1fd977652
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_hypotests.py
@@ -0,0 +1,1862 @@
+from itertools import product
+
+import numpy as np
+import random
+import functools
+import pytest
+from numpy.testing import (assert_, assert_equal, assert_allclose,
+                           assert_almost_equal)  # avoid new uses
+from pytest import raises as assert_raises
+
+import scipy.stats as stats
+from scipy.stats import distributions
+from scipy.stats._hypotests import (epps_singleton_2samp, cramervonmises,
+                                    _cdf_cvm, cramervonmises_2samp,
+                                    _pval_cvm_2samp_exact, barnard_exact,
+                                    boschloo_exact)
+from scipy.stats._mannwhitneyu import mannwhitneyu, _mwu_state, _MWU
+from .common_tests import check_named_results
+from scipy._lib._testutils import _TestPythranFunc
+from scipy.stats._axis_nan_policy import SmallSampleWarning, too_small_1d_not_omit
+
+
+class TestEppsSingleton:
+    def test_statistic_1(self):
+        # first example in Goerg & Kaiser, also in original paper of
+        # Epps & Singleton. Note: values do not match exactly, the
+        # value of the interquartile range varies depending on how
+        # quantiles are computed
+        x = np.array([-0.35, 2.55, 1.73, 0.73, 0.35,
+                      2.69, 0.46, -0.94, -0.37, 12.07])
+        y = np.array([-1.15, -0.15, 2.48, 3.25, 3.71,
+                      4.29, 5.00, 7.74, 8.38, 8.60])
+        w, p = epps_singleton_2samp(x, y)
+        assert_almost_equal(w, 15.14, decimal=1)
+        assert_almost_equal(p, 0.00442, decimal=3)
+
+    def test_statistic_2(self):
+        # second example in Goerg & Kaiser, again not a perfect match
+        x = np.array((0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 10,
+                      10, 10, 10))
+        y = np.array((10, 4, 0, 5, 10, 10, 0, 5, 6, 7, 10, 3, 1, 7, 0, 8, 1,
+                      5, 8, 10))
+        w, p = epps_singleton_2samp(x, y)
+        assert_allclose(w, 8.900, atol=0.001)
+        assert_almost_equal(p, 0.06364, decimal=3)
+
+    def test_epps_singleton_array_like(self):
+        np.random.seed(1234)
+        x, y = np.arange(30), np.arange(28)
+
+        w1, p1 = epps_singleton_2samp(list(x), list(y))
+        w2, p2 = epps_singleton_2samp(tuple(x), tuple(y))
+        w3, p3 = epps_singleton_2samp(x, y)
+
+        assert_(w1 == w2 == w3)
+        assert_(p1 == p2 == p3)
+
+    def test_epps_singleton_size(self):
+        # warns if sample contains fewer than 5 elements
+        x, y = (1, 2, 3, 4), np.arange(10)
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = epps_singleton_2samp(x, y)
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+    def test_epps_singleton_nonfinite(self):
+        # raise error if there are non-finite values
+        x, y = (1, 2, 3, 4, 5, np.inf), np.arange(10)
+        assert_raises(ValueError, epps_singleton_2samp, x, y)
+
+    def test_names(self):
+        x, y = np.arange(20), np.arange(30)
+        res = epps_singleton_2samp(x, y)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes)
+
+
+class TestCvm:
+    # the expected values of the cdfs are taken from Table 1 in
+    # Csorgo / Faraway: The Exact and Asymptotic Distribution of
+    # Cramér-von Mises Statistics, 1996.
+    def test_cdf_4(self):
+        assert_allclose(
+                _cdf_cvm([0.02983, 0.04111, 0.12331, 0.94251], 4),
+                [0.01, 0.05, 0.5, 0.999],
+                atol=1e-4)
+
+    def test_cdf_10(self):
+        assert_allclose(
+                _cdf_cvm([0.02657, 0.03830, 0.12068, 0.56643], 10),
+                [0.01, 0.05, 0.5, 0.975],
+                atol=1e-4)
+
+    def test_cdf_1000(self):
+        assert_allclose(
+                _cdf_cvm([0.02481, 0.03658, 0.11889, 1.16120], 1000),
+                [0.01, 0.05, 0.5, 0.999],
+                atol=1e-4)
+
+    def test_cdf_inf(self):
+        assert_allclose(
+                _cdf_cvm([0.02480, 0.03656, 0.11888, 1.16204]),
+                [0.01, 0.05, 0.5, 0.999],
+                atol=1e-4)
+
+    def test_cdf_support(self):
+        # cdf has support on [1/(12*n), n/3]
+        assert_equal(_cdf_cvm([1/(12*533), 533/3], 533), [0, 1])
+        assert_equal(_cdf_cvm([1/(12*(27 + 1)), (27 + 1)/3], 27), [0, 1])
+
+    def test_cdf_large_n(self):
+        # test that asymptotic cdf and cdf for large samples are close
+        assert_allclose(
+                _cdf_cvm([0.02480, 0.03656, 0.11888, 1.16204, 100], 10000),
+                _cdf_cvm([0.02480, 0.03656, 0.11888, 1.16204, 100]),
+                atol=1e-4)
+
+    def test_large_x(self):
+        # for large values of x and n, the series used to compute the cdf
+        # converges slowly.
+        # this leads to bug in R package goftest and MAPLE code that is
+        # the basis of the implementation in scipy
+        # note: cdf = 1 for x >= 1000/3 and n = 1000
+        assert_(0.99999 < _cdf_cvm(333.3, 1000) < 1.0)
+        assert_(0.99999 < _cdf_cvm(333.3) < 1.0)
+
+    def test_low_p(self):
+        # _cdf_cvm can return values larger than 1. In that case, we just
+        # return a p-value of zero.
+        n = 12
+        res = cramervonmises(np.ones(n)*0.8, 'norm')
+        assert_(_cdf_cvm(res.statistic, n) > 1.0)
+        assert_equal(res.pvalue, 0)
+
+    @pytest.mark.parametrize('x', [(), [1.5]])
+    def test_invalid_input(self, x):
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = cramervonmises(x, "norm")
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+    def test_values_R(self):
+        # compared against R package goftest, version 1.1.1
+        # goftest::cvm.test(c(-1.7, 2, 0, 1.3, 4, 0.1, 0.6), "pnorm")
+        res = cramervonmises([-1.7, 2, 0, 1.3, 4, 0.1, 0.6], "norm")
+        assert_allclose(res.statistic, 0.288156, atol=1e-6)
+        assert_allclose(res.pvalue, 0.1453465, atol=1e-6)
+
+        # goftest::cvm.test(c(-1.7, 2, 0, 1.3, 4, 0.1, 0.6),
+        #                   "pnorm", mean = 3, sd = 1.5)
+        res = cramervonmises([-1.7, 2, 0, 1.3, 4, 0.1, 0.6], "norm", (3, 1.5))
+        assert_allclose(res.statistic, 0.9426685, atol=1e-6)
+        assert_allclose(res.pvalue, 0.002026417, atol=1e-6)
+
+        # goftest::cvm.test(c(1, 2, 5, 1.4, 0.14, 11, 13, 0.9, 7.5), "pexp")
+        res = cramervonmises([1, 2, 5, 1.4, 0.14, 11, 13, 0.9, 7.5], "expon")
+        assert_allclose(res.statistic, 0.8421854, atol=1e-6)
+        assert_allclose(res.pvalue, 0.004433406, atol=1e-6)
+
+    def test_callable_cdf(self):
+        x, args = np.arange(5), (1.4, 0.7)
+        r1 = cramervonmises(x, distributions.expon.cdf)
+        r2 = cramervonmises(x, "expon")
+        assert_equal((r1.statistic, r1.pvalue), (r2.statistic, r2.pvalue))
+
+        r1 = cramervonmises(x, distributions.beta.cdf, args)
+        r2 = cramervonmises(x, "beta", args)
+        assert_equal((r1.statistic, r1.pvalue), (r2.statistic, r2.pvalue))
+
+
+class TestMannWhitneyU:
+
+    # All magic numbers are from R wilcox.test unless otherwise specified
+    # https://rdrr.io/r/stats/wilcox.test.html
+
+    # --- Test Input Validation ---
+
+    @pytest.mark.parametrize('kwargs_update', [{'x': []}, {'y': []},
+                                               {'x': [], 'y': []}])
+    def test_empty(self, kwargs_update):
+        x = np.array([1, 2])  # generic, valid inputs
+        y = np.array([3, 4])
+        kwargs = dict(x=x, y=y)
+        kwargs.update(kwargs_update)
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = mannwhitneyu(**kwargs)
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+    def test_input_validation(self):
+        x = np.array([1, 2])  # generic, valid inputs
+        y = np.array([3, 4])
+        with assert_raises(ValueError, match="`use_continuity` must be one"):
+            mannwhitneyu(x, y, use_continuity='ekki')
+        with assert_raises(ValueError, match="`alternative` must be one of"):
+            mannwhitneyu(x, y, alternative='ekki')
+        with assert_raises(ValueError, match="`axis` must be an integer"):
+            mannwhitneyu(x, y, axis=1.5)
+        with assert_raises(ValueError, match="`method` must be one of"):
+            mannwhitneyu(x, y, method='ekki')
+
+    def test_auto(self):
+        # Test that default method ('auto') chooses intended method
+
+        np.random.seed(1)
+        n = 8  # threshold to switch from exact to asymptotic
+
+        # both inputs are smaller than threshold; should use exact
+        x = np.random.rand(n-1)
+        y = np.random.rand(n-1)
+        auto = mannwhitneyu(x, y)
+        asymptotic = mannwhitneyu(x, y, method='asymptotic')
+        exact = mannwhitneyu(x, y, method='exact')
+        assert auto.pvalue == exact.pvalue
+        assert auto.pvalue != asymptotic.pvalue
+
+        # one input is smaller than threshold; should use exact
+        x = np.random.rand(n-1)
+        y = np.random.rand(n+1)
+        auto = mannwhitneyu(x, y)
+        asymptotic = mannwhitneyu(x, y, method='asymptotic')
+        exact = mannwhitneyu(x, y, method='exact')
+        assert auto.pvalue == exact.pvalue
+        assert auto.pvalue != asymptotic.pvalue
+
+        # other input is smaller than threshold; should use exact
+        auto = mannwhitneyu(y, x)
+        asymptotic = mannwhitneyu(x, y, method='asymptotic')
+        exact = mannwhitneyu(x, y, method='exact')
+        assert auto.pvalue == exact.pvalue
+        assert auto.pvalue != asymptotic.pvalue
+
+        # both inputs are larger than threshold; should use asymptotic
+        x = np.random.rand(n+1)
+        y = np.random.rand(n+1)
+        auto = mannwhitneyu(x, y)
+        asymptotic = mannwhitneyu(x, y, method='asymptotic')
+        exact = mannwhitneyu(x, y, method='exact')
+        assert auto.pvalue != exact.pvalue
+        assert auto.pvalue == asymptotic.pvalue
+
+        # both inputs are smaller than threshold, but there is a tie
+        # should use asymptotic
+        x = np.random.rand(n-1)
+        y = np.random.rand(n-1)
+        y[3] = x[3]
+        auto = mannwhitneyu(x, y)
+        asymptotic = mannwhitneyu(x, y, method='asymptotic')
+        exact = mannwhitneyu(x, y, method='exact')
+        assert auto.pvalue != exact.pvalue
+        assert auto.pvalue == asymptotic.pvalue
+
+    # --- Test Basic Functionality ---
+
+    x = [210.052110, 110.190630, 307.918612]
+    y = [436.08811482466416, 416.37397329768191, 179.96975939463582,
+         197.8118754228619, 34.038757281225756, 138.54220550921517,
+         128.7769351470246, 265.92721427951852, 275.6617533155341,
+         592.34083395416258, 448.73177590617018, 300.61495185038905,
+         187.97508449019588]
+
+    # This test was written for mann_whitney_u in gh-4933.
+    # Originally, the p-values for alternatives were swapped;
+    # this has been corrected and the tests have been refactored for
+    # compactness, but otherwise the tests are unchanged.
+    # R code for comparison, e.g.:
+    # options(digits = 16)
+    # x = c(210.052110, 110.190630, 307.918612)
+    # y = c(436.08811482466416, 416.37397329768191, 179.96975939463582,
+    #       197.8118754228619, 34.038757281225756, 138.54220550921517,
+    #       128.7769351470246, 265.92721427951852, 275.6617533155341,
+    #       592.34083395416258, 448.73177590617018, 300.61495185038905,
+    #       187.97508449019588)
+    # wilcox.test(x, y, alternative="g", exact=TRUE)
+    cases_basic = [[{"alternative": 'two-sided', "method": "asymptotic"},
+                    (16, 0.6865041817876)],
+                   [{"alternative": 'less', "method": "asymptotic"},
+                    (16, 0.3432520908938)],
+                   [{"alternative": 'greater', "method": "asymptotic"},
+                    (16, 0.7047591913255)],
+                   [{"alternative": 'two-sided', "method": "exact"},
+                    (16, 0.7035714285714)],
+                   [{"alternative": 'less', "method": "exact"},
+                    (16, 0.3517857142857)],
+                   [{"alternative": 'greater', "method": "exact"},
+                    (16, 0.6946428571429)]]
+
+    @pytest.mark.parametrize(("kwds", "expected"), cases_basic)
+    def test_basic(self, kwds, expected):
+        res = mannwhitneyu(self.x, self.y, **kwds)
+        assert_allclose(res, expected)
+
+    cases_continuity = [[{"alternative": 'two-sided', "use_continuity": True},
+                         (23, 0.6865041817876)],
+                        [{"alternative": 'less', "use_continuity": True},
+                         (23, 0.7047591913255)],
+                        [{"alternative": 'greater', "use_continuity": True},
+                         (23, 0.3432520908938)],
+                        [{"alternative": 'two-sided', "use_continuity": False},
+                         (23, 0.6377328900502)],
+                        [{"alternative": 'less', "use_continuity": False},
+                         (23, 0.6811335549749)],
+                        [{"alternative": 'greater', "use_continuity": False},
+                         (23, 0.3188664450251)]]
+
+    @pytest.mark.parametrize(("kwds", "expected"), cases_continuity)
+    def test_continuity(self, kwds, expected):
+        # When x and y are interchanged, less and greater p-values should
+        # swap (compare to above). This wouldn't happen if the continuity
+        # correction were applied in the wrong direction. Note that less and
+        # greater p-values do not sum to 1 when continuity correction is on,
+        # which is what we'd expect. Also check that results match R when
+        # continuity correction is turned off.
+        # Note that method='asymptotic' -> exact=FALSE
+        # and use_continuity=False -> correct=FALSE, e.g.:
+        # wilcox.test(x, y, alternative="t", exact=FALSE, correct=FALSE)
+        res = mannwhitneyu(self.y, self.x, method='asymptotic', **kwds)
+        assert_allclose(res, expected)
+
+    def test_tie_correct(self):
+        # Test tie correction against R's wilcox.test
+        # options(digits = 16)
+        # x = c(1, 2, 3, 4)
+        # y = c(1, 2, 3, 4, 5)
+        # wilcox.test(x, y, exact=FALSE)
+        x = [1, 2, 3, 4]
+        y0 = np.array([1, 2, 3, 4, 5])
+        dy = np.array([0, 1, 0, 1, 0])*0.01
+        dy2 = np.array([0, 0, 1, 0, 0])*0.01
+        y = [y0-0.01, y0-dy, y0-dy2, y0, y0+dy2, y0+dy, y0+0.01]
+        res = mannwhitneyu(x, y, axis=-1, method="asymptotic")
+        U_expected = [10, 9, 8.5, 8, 7.5, 7, 6]
+        p_expected = [1, 0.9017048037317, 0.804080657472, 0.7086240584439,
+                      0.6197963884941, 0.5368784563079, 0.3912672792826]
+        assert_equal(res.statistic, U_expected)
+        assert_allclose(res.pvalue, p_expected)
+
+    # --- Test Exact Distribution of U ---
+
+    # These are tabulated values of the CDF of the exact distribution of
+    # the test statistic from pg 52 of reference [1] (Mann-Whitney Original)
+    pn3 = {1: [0.25, 0.5, 0.75], 2: [0.1, 0.2, 0.4, 0.6],
+           3: [0.05, .1, 0.2, 0.35, 0.5, 0.65]}
+    pn4 = {1: [0.2, 0.4, 0.6], 2: [0.067, 0.133, 0.267, 0.4, 0.6],
+           3: [0.028, 0.057, 0.114, 0.2, .314, 0.429, 0.571],
+           4: [0.014, 0.029, 0.057, 0.1, 0.171, 0.243, 0.343, 0.443, 0.557]}
+    pm5 = {1: [0.167, 0.333, 0.5, 0.667],
+           2: [0.047, 0.095, 0.19, 0.286, 0.429, 0.571],
+           3: [0.018, 0.036, 0.071, 0.125, 0.196, 0.286, 0.393, 0.5, 0.607],
+           4: [0.008, 0.016, 0.032, 0.056, 0.095, 0.143,
+               0.206, 0.278, 0.365, 0.452, 0.548],
+           5: [0.004, 0.008, 0.016, 0.028, 0.048, 0.075, 0.111,
+               0.155, 0.21, 0.274, 0.345, .421, 0.5, 0.579]}
+    pm6 = {1: [0.143, 0.286, 0.428, 0.571],
+           2: [0.036, 0.071, 0.143, 0.214, 0.321, 0.429, 0.571],
+           3: [0.012, 0.024, 0.048, 0.083, 0.131,
+               0.19, 0.274, 0.357, 0.452, 0.548],
+           4: [0.005, 0.01, 0.019, 0.033, 0.057, 0.086, 0.129,
+               0.176, 0.238, 0.305, 0.381, 0.457, 0.543],  # the last element
+           # of the previous list, 0.543, has been modified from 0.545;
+           # I assume it was a typo
+           5: [0.002, 0.004, 0.009, 0.015, 0.026, 0.041, 0.063, 0.089,
+               0.123, 0.165, 0.214, 0.268, 0.331, 0.396, 0.465, 0.535],
+           6: [0.001, 0.002, 0.004, 0.008, 0.013, 0.021, 0.032, 0.047,
+               0.066, 0.09, 0.12, 0.155, 0.197, 0.242, 0.294, 0.350,
+               0.409, 0.469, 0.531]}
+
+    def test_exact_distribution(self):
+        # I considered parametrize. I decided against it.
+        setattr(_mwu_state, 's', _MWU(0, 0))
+
+        p_tables = {3: self.pn3, 4: self.pn4, 5: self.pm5, 6: self.pm6}
+        for n, table in p_tables.items():
+            for m, p in table.items():
+                # check p-value against table
+                u = np.arange(0, len(p))
+                _mwu_state.s.set_shapes(m, n)
+                assert_allclose(_mwu_state.s.cdf(k=u), p, atol=1e-3)
+
+                # check identity CDF + SF - PMF = 1
+                # ( In this implementation, SF(U) includes PMF(U) )
+                u2 = np.arange(0, m*n+1)
+                assert_allclose(_mwu_state.s.cdf(k=u2)
+                                + _mwu_state.s.sf(k=u2)
+                                - _mwu_state.s.pmf(k=u2), 1)
+
+                # check symmetry about mean of U, i.e. pmf(U) = pmf(m*n-U)
+                pmf = _mwu_state.s.pmf(k=u2)
+                assert_allclose(pmf, pmf[::-1])
+
+                # check symmetry w.r.t. interchange of m, n
+                _mwu_state.s.set_shapes(n, m)
+                pmf2 = _mwu_state.s.pmf(k=u2)
+                assert_allclose(pmf, pmf2)
+
+    def test_asymptotic_behavior(self):
+        np.random.seed(0)
+
+        # for small samples, the asymptotic test is not very accurate
+        x = np.random.rand(5)
+        y = np.random.rand(5)
+        res1 = mannwhitneyu(x, y, method="exact")
+        res2 = mannwhitneyu(x, y, method="asymptotic")
+        assert res1.statistic == res2.statistic
+        assert np.abs(res1.pvalue - res2.pvalue) > 1e-2
+
+        # for large samples, they agree reasonably well
+        x = np.random.rand(40)
+        y = np.random.rand(40)
+        res1 = mannwhitneyu(x, y, method="exact")
+        res2 = mannwhitneyu(x, y, method="asymptotic")
+        assert res1.statistic == res2.statistic
+        assert np.abs(res1.pvalue - res2.pvalue) < 1e-3
+
+    # --- Test Corner Cases ---
+
+    def test_exact_U_equals_mean(self):
+        # Test U == m*n/2 with exact method
+        # Without special treatment, two-sided p-value > 1 because both
+        # one-sided p-values are > 0.5
+        res_l = mannwhitneyu([1, 2, 3], [1.5, 2.5], alternative="less",
+                             method="exact")
+        res_g = mannwhitneyu([1, 2, 3], [1.5, 2.5], alternative="greater",
+                             method="exact")
+        assert_equal(res_l.pvalue, res_g.pvalue)
+        assert res_l.pvalue > 0.5
+
+        res = mannwhitneyu([1, 2, 3], [1.5, 2.5], alternative="two-sided",
+                           method="exact")
+        assert_equal(res, (3, 1))
+        # U == m*n/2 for asymptotic case tested in test_gh_2118
+        # The reason it's tricky for the asymptotic test has to do with
+        # continuity correction.
+
+    cases_scalar = [[{"alternative": 'two-sided', "method": "asymptotic"},
+                     (0, 1)],
+                    [{"alternative": 'less', "method": "asymptotic"},
+                     (0, 0.5)],
+                    [{"alternative": 'greater', "method": "asymptotic"},
+                     (0, 0.977249868052)],
+                    [{"alternative": 'two-sided', "method": "exact"}, (0, 1)],
+                    [{"alternative": 'less', "method": "exact"}, (0, 0.5)],
+                    [{"alternative": 'greater', "method": "exact"}, (0, 1)]]
+
+    @pytest.mark.parametrize(("kwds", "result"), cases_scalar)
+    def test_scalar_data(self, kwds, result):
+        # just making sure scalars work
+        assert_allclose(mannwhitneyu(1, 2, **kwds), result)
+
+    def test_equal_scalar_data(self):
+        # when two scalars are equal, there is an -0.5/0 in the asymptotic
+        # approximation. R gives pvalue=1.0 for alternatives 'less' and
+        # 'greater' but NA for 'two-sided'. I don't see why, so I don't
+        # see a need for a special case to match that behavior.
+        assert_equal(mannwhitneyu(1, 1, method="exact"), (0.5, 1))
+        assert_equal(mannwhitneyu(1, 1, method="asymptotic"), (0.5, 1))
+
+        # without continuity correction, this becomes 0/0, which really
+        # is undefined
+        assert_equal(mannwhitneyu(1, 1, method="asymptotic",
+                                  use_continuity=False), (0.5, np.nan))
+
+    # --- Test Enhancements / Bug Reports ---
+
+    @pytest.mark.parametrize("method", ["asymptotic", "exact"])
+    def test_gh_12837_11113(self, method):
+        # Test that behavior for broadcastable nd arrays is appropriate:
+        # output shape is correct and all values are equal to when the test
+        # is performed on one pair of samples at a time.
+        # Tests that gh-12837 and gh-11113 (requests for n-d input)
+        # are resolved
+        np.random.seed(0)
+
+        # arrays are broadcastable except for axis = -3
+        axis = -3
+        m, n = 7, 10  # sample sizes
+        x = np.random.rand(m, 3, 8)
+        y = np.random.rand(6, n, 1, 8) + 0.1
+        res = mannwhitneyu(x, y, method=method, axis=axis)
+
+        shape = (6, 3, 8)  # appropriate shape of outputs, given inputs
+        assert res.pvalue.shape == shape
+        assert res.statistic.shape == shape
+
+        # move axis of test to end for simplicity
+        x, y = np.moveaxis(x, axis, -1), np.moveaxis(y, axis, -1)
+
+        x = x[None, ...]  # give x a zeroth dimension
+        assert x.ndim == y.ndim
+
+        x = np.broadcast_to(x, shape + (m,))
+        y = np.broadcast_to(y, shape + (n,))
+        assert x.shape[:-1] == shape
+        assert y.shape[:-1] == shape
+
+        # loop over pairs of samples
+        statistics = np.zeros(shape)
+        pvalues = np.zeros(shape)
+        for indices in product(*[range(i) for i in shape]):
+            xi = x[indices]
+            yi = y[indices]
+            temp = mannwhitneyu(xi, yi, method=method)
+            statistics[indices] = temp.statistic
+            pvalues[indices] = temp.pvalue
+
+        np.testing.assert_equal(res.pvalue, pvalues)
+        np.testing.assert_equal(res.statistic, statistics)
+
+    def test_gh_11355(self):
+        # Test for correct behavior with NaN/Inf in input
+        x = [1, 2, 3, 4]
+        y = [3, 6, 7, 8, 9, 3, 2, 1, 4, 4, 5]
+        res1 = mannwhitneyu(x, y)
+
+        # Inf is not a problem. This is a rank test, and it's the largest value
+        y[4] = np.inf
+        res2 = mannwhitneyu(x, y)
+
+        assert_equal(res1.statistic, res2.statistic)
+        assert_equal(res1.pvalue, res2.pvalue)
+
+        # NaNs should propagate by default.
+        y[4] = np.nan
+        res3 = mannwhitneyu(x, y)
+        assert_equal(res3.statistic, np.nan)
+        assert_equal(res3.pvalue, np.nan)
+
+    cases_11355 = [([1, 2, 3, 4],
+                    [3, 6, 7, 8, np.inf, 3, 2, 1, 4, 4, 5],
+                    10, 0.1297704873477),
+                   ([1, 2, 3, 4],
+                    [3, 6, 7, 8, np.inf, np.inf, 2, 1, 4, 4, 5],
+                    8.5, 0.08735617507695),
+                   ([1, 2, np.inf, 4],
+                    [3, 6, 7, 8, np.inf, 3, 2, 1, 4, 4, 5],
+                    17.5, 0.5988856695752),
+                   ([1, 2, np.inf, 4],
+                    [3, 6, 7, 8, np.inf, np.inf, 2, 1, 4, 4, 5],
+                    16, 0.4687165824462),
+                   ([1, np.inf, np.inf, 4],
+                    [3, 6, 7, 8, np.inf, np.inf, 2, 1, 4, 4, 5],
+                    24.5, 0.7912517950119)]
+
+    @pytest.mark.parametrize(("x", "y", "statistic", "pvalue"), cases_11355)
+    def test_gh_11355b(self, x, y, statistic, pvalue):
+        # Test for correct behavior with NaN/Inf in input
+        res = mannwhitneyu(x, y, method='asymptotic')
+        assert_allclose(res.statistic, statistic, atol=1e-12)
+        assert_allclose(res.pvalue, pvalue, atol=1e-12)
+
+    cases_9184 = [[True, "less", "asymptotic", 0.900775348204],
+                  [True, "greater", "asymptotic", 0.1223118025635],
+                  [True, "two-sided", "asymptotic", 0.244623605127],
+                  [False, "less", "asymptotic", 0.8896643190401],
+                  [False, "greater", "asymptotic", 0.1103356809599],
+                  [False, "two-sided", "asymptotic", 0.2206713619198],
+                  [True, "less", "exact", 0.8967698967699],
+                  [True, "greater", "exact", 0.1272061272061],
+                  [True, "two-sided", "exact", 0.2544122544123]]
+
+    @pytest.mark.parametrize(("use_continuity", "alternative",
+                              "method", "pvalue_exp"), cases_9184)
+    def test_gh_9184(self, use_continuity, alternative, method, pvalue_exp):
+        # gh-9184 might be considered a doc-only bug. Please see the
+        # documentation to confirm that mannwhitneyu correctly notes
+        # that the output statistic is that of the first sample (x). In any
+        # case, check the case provided there against output from R.
+        # R code:
+        # options(digits=16)
+        # x <- c(0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64, 0.73, 1.46)
+        # y <- c(1.15, 0.88, 0.90, 0.74, 1.21)
+        # wilcox.test(x, y, alternative = "less", exact = FALSE)
+        # wilcox.test(x, y, alternative = "greater", exact = FALSE)
+        # wilcox.test(x, y, alternative = "two.sided", exact = FALSE)
+        # wilcox.test(x, y, alternative = "less", exact = FALSE,
+        #             correct=FALSE)
+        # wilcox.test(x, y, alternative = "greater", exact = FALSE,
+        #             correct=FALSE)
+        # wilcox.test(x, y, alternative = "two.sided", exact = FALSE,
+        #             correct=FALSE)
+        # wilcox.test(x, y, alternative = "less", exact = TRUE)
+        # wilcox.test(x, y, alternative = "greater", exact = TRUE)
+        # wilcox.test(x, y, alternative = "two.sided", exact = TRUE)
+        statistic_exp = 35
+        x = (0.80, 0.83, 1.89, 1.04, 1.45, 1.38, 1.91, 1.64, 0.73, 1.46)
+        y = (1.15, 0.88, 0.90, 0.74, 1.21)
+        res = mannwhitneyu(x, y, use_continuity=use_continuity,
+                           alternative=alternative, method=method)
+        assert_equal(res.statistic, statistic_exp)
+        assert_allclose(res.pvalue, pvalue_exp)
+
+    def test_gh_4067(self):
+        # Test for correct behavior with all NaN input - default is propagate
+        a = np.array([np.nan, np.nan, np.nan, np.nan, np.nan])
+        b = np.array([np.nan, np.nan, np.nan, np.nan, np.nan])
+        res = mannwhitneyu(a, b)
+        assert_equal(res.statistic, np.nan)
+        assert_equal(res.pvalue, np.nan)
+
+    # All cases checked against R wilcox.test, e.g.
+    # options(digits=16)
+    # x = c(1, 2, 3)
+    # y = c(1.5, 2.5)
+    # wilcox.test(x, y, exact=FALSE, alternative='less')
+
+    cases_2118 = [[[1, 2, 3], [1.5, 2.5], "greater", (3, 0.6135850036578)],
+                  [[1, 2, 3], [1.5, 2.5], "less", (3, 0.6135850036578)],
+                  [[1, 2, 3], [1.5, 2.5], "two-sided", (3, 1.0)],
+                  [[1, 2, 3], [2], "greater", (1.5, 0.681324055883)],
+                  [[1, 2, 3], [2], "less", (1.5, 0.681324055883)],
+                  [[1, 2, 3], [2], "two-sided", (1.5, 1)],
+                  [[1, 2], [1, 2], "greater", (2, 0.667497228949)],
+                  [[1, 2], [1, 2], "less", (2, 0.667497228949)],
+                  [[1, 2], [1, 2], "two-sided", (2, 1)]]
+
+    @pytest.mark.parametrize(["x", "y", "alternative", "expected"], cases_2118)
+    def test_gh_2118(self, x, y, alternative, expected):
+        # test cases in which U == m*n/2 when method is asymptotic
+        # applying continuity correction could result in p-value > 1
+        res = mannwhitneyu(x, y, use_continuity=True, alternative=alternative,
+                           method="asymptotic")
+        assert_allclose(res, expected, rtol=1e-12)
+
+    def test_gh19692_smaller_table(self):
+        # In gh-19692, we noted that the shape of the cache used in calculating
+        # p-values was dependent on the order of the inputs because the sample
+        # sizes n1 and n2 changed. This was indicative of unnecessary cache
+        # growth and redundant calculation. Check that this is resolved.
+        rng = np.random.default_rng(7600451795963068007)
+        m, n = 5, 11
+        x = rng.random(size=m)
+        y = rng.random(size=n)
+
+        setattr(_mwu_state, 's', _MWU(0, 0))
+        _mwu_state.s.reset()  # reset cache
+
+        res = stats.mannwhitneyu(x, y, method='exact')
+        shape = _mwu_state.s.configurations.shape
+        assert shape[-1] == min(res.statistic, m*n - res.statistic) + 1
+        stats.mannwhitneyu(y, x, method='exact')
+        assert shape == _mwu_state.s.configurations.shape  # same with reversed sizes
+
+        # Also, we weren't exploiting the symmetry of the null distribution
+        # to its full potential. Ensure that the null distribution is not
+        # evaluated explicitly for `k > m*n/2`.
+        _mwu_state.s.reset()  # reset cache
+        stats.mannwhitneyu(x, 0*y, method='exact', alternative='greater')
+        shape = _mwu_state.s.configurations.shape
+        assert shape[-1] == 1  # k is smallest possible
+        stats.mannwhitneyu(0*x, y, method='exact', alternative='greater')
+        assert shape == _mwu_state.s.configurations.shape
+
+    @pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided'])
+    def test_permutation_method(self, alternative):
+        rng = np.random.default_rng(7600451795963068007)
+        x = rng.random(size=(2, 5))
+        y = rng.random(size=(2, 6))
+        res = stats.mannwhitneyu(x, y, method=stats.PermutationMethod(),
+                                 alternative=alternative, axis=1)
+        res2 = stats.mannwhitneyu(x, y, method='exact',
+                                  alternative=alternative, axis=1)
+        assert_allclose(res.statistic, res2.statistic, rtol=1e-15)
+        assert_allclose(res.pvalue, res2.pvalue, rtol=1e-15)
+
+
+class TestSomersD(_TestPythranFunc):
+    def setup_method(self):
+        self.dtypes = self.ALL_INTEGER + self.ALL_FLOAT
+        self.arguments = {0: (np.arange(10),
+                              self.ALL_INTEGER + self.ALL_FLOAT),
+                          1: (np.arange(10),
+                              self.ALL_INTEGER + self.ALL_FLOAT)}
+        input_array = [self.arguments[idx][0] for idx in self.arguments]
+        # In this case, self.partialfunc can simply be stats.somersd,
+        # since `alternative` is an optional argument. If it is required,
+        # we can use functools.partial to freeze the value, because
+        # we only mainly test various array inputs, not str, etc.
+        self.partialfunc = functools.partial(stats.somersd,
+                                             alternative='two-sided')
+        self.expected = self.partialfunc(*input_array)
+
+    def pythranfunc(self, *args):
+        res = self.partialfunc(*args)
+        assert_allclose(res.statistic, self.expected.statistic, atol=1e-15)
+        assert_allclose(res.pvalue, self.expected.pvalue, atol=1e-15)
+
+    def test_pythranfunc_keywords(self):
+        # Not specifying the optional keyword args
+        table = [[27, 25, 14, 7, 0], [7, 14, 18, 35, 12], [1, 3, 2, 7, 17]]
+        res1 = stats.somersd(table)
+        # Specifying the optional keyword args with default value
+        optional_args = self.get_optional_args(stats.somersd)
+        res2 = stats.somersd(table, **optional_args)
+        # Check if the results are the same in two cases
+        assert_allclose(res1.statistic, res2.statistic, atol=1e-15)
+        assert_allclose(res1.pvalue, res2.pvalue, atol=1e-15)
+
+    def test_like_kendalltau(self):
+        # All tests correspond with one in test_stats.py `test_kendalltau`
+
+        # case without ties, con-dis equal zero
+        x = [5, 2, 1, 3, 6, 4, 7, 8]
+        y = [5, 2, 6, 3, 1, 8, 7, 4]
+        # Cross-check with result from SAS FREQ:
+        expected = (0.000000000000000, 1.000000000000000)
+        res = stats.somersd(x, y)
+        assert_allclose(res.statistic, expected[0], atol=1e-15)
+        assert_allclose(res.pvalue, expected[1], atol=1e-15)
+
+        # case without ties, con-dis equal zero
+        x = [0, 5, 2, 1, 3, 6, 4, 7, 8]
+        y = [5, 2, 0, 6, 3, 1, 8, 7, 4]
+        # Cross-check with result from SAS FREQ:
+        expected = (0.000000000000000, 1.000000000000000)
+        res = stats.somersd(x, y)
+        assert_allclose(res.statistic, expected[0], atol=1e-15)
+        assert_allclose(res.pvalue, expected[1], atol=1e-15)
+
+        # case without ties, con-dis close to zero
+        x = [5, 2, 1, 3, 6, 4, 7]
+        y = [5, 2, 6, 3, 1, 7, 4]
+        # Cross-check with result from SAS FREQ:
+        expected = (-0.142857142857140, 0.630326953157670)
+        res = stats.somersd(x, y)
+        assert_allclose(res.statistic, expected[0], atol=1e-15)
+        assert_allclose(res.pvalue, expected[1], atol=1e-15)
+
+        # simple case without ties
+        x = np.arange(10)
+        y = np.arange(10)
+        # Cross-check with result from SAS FREQ:
+        # SAS p value is not provided.
+        expected = (1.000000000000000, 0)
+        res = stats.somersd(x, y)
+        assert_allclose(res.statistic, expected[0], atol=1e-15)
+        assert_allclose(res.pvalue, expected[1], atol=1e-15)
+
+        # swap a couple values and a couple more
+        x = np.arange(10)
+        y = np.array([0, 2, 1, 3, 4, 6, 5, 7, 8, 9])
+        # Cross-check with result from SAS FREQ:
+        expected = (0.911111111111110, 0.000000000000000)
+        res = stats.somersd(x, y)
+        assert_allclose(res.statistic, expected[0], atol=1e-15)
+        assert_allclose(res.pvalue, expected[1], atol=1e-15)
+
+        # same in opposite direction
+        x = np.arange(10)
+        y = np.arange(10)[::-1]
+        # Cross-check with result from SAS FREQ:
+        # SAS p value is not provided.
+        expected = (-1.000000000000000, 0)
+        res = stats.somersd(x, y)
+        assert_allclose(res.statistic, expected[0], atol=1e-15)
+        assert_allclose(res.pvalue, expected[1], atol=1e-15)
+
+        # swap a couple values and a couple more
+        x = np.arange(10)
+        y = np.array([9, 7, 8, 6, 5, 3, 4, 2, 1, 0])
+        # Cross-check with result from SAS FREQ:
+        expected = (-0.9111111111111111, 0.000000000000000)
+        res = stats.somersd(x, y)
+        assert_allclose(res.statistic, expected[0], atol=1e-15)
+        assert_allclose(res.pvalue, expected[1], atol=1e-15)
+
+        # with some ties
+        x1 = [12, 2, 1, 12, 2]
+        x2 = [1, 4, 7, 1, 0]
+        # Cross-check with result from SAS FREQ:
+        expected = (-0.500000000000000, 0.304901788178780)
+        res = stats.somersd(x1, x2)
+        assert_allclose(res.statistic, expected[0], atol=1e-15)
+        assert_allclose(res.pvalue, expected[1], atol=1e-15)
+
+        # with only ties in one or both inputs
+        # SAS will not produce an output for these:
+        # NOTE: No statistics are computed for x * y because x has fewer
+        # than 2 nonmissing levels.
+        # WARNING: No OUTPUT data set is produced for this table because a
+        # row or column variable has fewer than 2 nonmissing levels and no
+        # statistics are computed.
+
+        res = stats.somersd([2, 2, 2], [2, 2, 2])
+        assert_allclose(res.statistic, np.nan)
+        assert_allclose(res.pvalue, np.nan)
+
+        res = stats.somersd([2, 0, 2], [2, 2, 2])
+        assert_allclose(res.statistic, np.nan)
+        assert_allclose(res.pvalue, np.nan)
+
+        res = stats.somersd([2, 2, 2], [2, 0, 2])
+        assert_allclose(res.statistic, np.nan)
+        assert_allclose(res.pvalue, np.nan)
+
+        res = stats.somersd([0], [0])
+        assert_allclose(res.statistic, np.nan)
+        assert_allclose(res.pvalue, np.nan)
+
+        # empty arrays provided as input
+        res = stats.somersd([], [])
+        assert_allclose(res.statistic, np.nan)
+        assert_allclose(res.pvalue, np.nan)
+
+        # test unequal length inputs
+        x = np.arange(10.)
+        y = np.arange(20.)
+        assert_raises(ValueError, stats.somersd, x, y)
+
+    def test_asymmetry(self):
+        # test that somersd is asymmetric w.r.t. input order and that
+        # convention is as described: first input is row variable & independent
+        # data is from Wikipedia:
+        # https://en.wikipedia.org/wiki/Somers%27_D
+        # but currently that example contradicts itself - it says X is
+        # independent yet take D_XY
+
+        x = [1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 1, 2,
+             2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3]
+        y = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2,
+             2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
+        # Cross-check with result from SAS FREQ:
+        d_cr = 0.272727272727270
+        d_rc = 0.342857142857140
+        p = 0.092891940883700  # same p-value for either direction
+        res = stats.somersd(x, y)
+        assert_allclose(res.statistic, d_cr, atol=1e-15)
+        assert_allclose(res.pvalue, p, atol=1e-4)
+        assert_equal(res.table.shape, (3, 2))
+        res = stats.somersd(y, x)
+        assert_allclose(res.statistic, d_rc, atol=1e-15)
+        assert_allclose(res.pvalue, p, atol=1e-15)
+        assert_equal(res.table.shape, (2, 3))
+
+    def test_somers_original(self):
+        # test against Somers' original paper [1]
+
+        # Table 5A
+        # Somers' convention was column IV
+        table = np.array([[8, 2], [6, 5], [3, 4], [1, 3], [2, 3]])
+        # Our convention (and that of SAS FREQ) is row IV
+        table = table.T
+        dyx = 129/340
+        assert_allclose(stats.somersd(table).statistic, dyx)
+
+        # table 7A - d_yx = 1
+        table = np.array([[25, 0], [85, 0], [0, 30]])
+        dxy, dyx = 3300/5425, 3300/3300
+        assert_allclose(stats.somersd(table).statistic, dxy)
+        assert_allclose(stats.somersd(table.T).statistic, dyx)
+
+        # table 7B - d_yx < 0
+        table = np.array([[25, 0], [0, 30], [85, 0]])
+        dyx = -1800/3300
+        assert_allclose(stats.somersd(table.T).statistic, dyx)
+
+    def test_contingency_table_with_zero_rows_cols(self):
+        # test that zero rows/cols in contingency table don't affect result
+
+        N = 100
+        shape = 4, 6
+        size = np.prod(shape)
+
+        np.random.seed(0)
+        s = stats.multinomial.rvs(N, p=np.ones(size)/size).reshape(shape)
+        res = stats.somersd(s)
+
+        s2 = np.insert(s, 2, np.zeros(shape[1]), axis=0)
+        res2 = stats.somersd(s2)
+
+        s3 = np.insert(s, 2, np.zeros(shape[0]), axis=1)
+        res3 = stats.somersd(s3)
+
+        s4 = np.insert(s2, 2, np.zeros(shape[0]+1), axis=1)
+        res4 = stats.somersd(s4)
+
+        # Cross-check with result from SAS FREQ:
+        assert_allclose(res.statistic, -0.116981132075470, atol=1e-15)
+        assert_allclose(res.statistic, res2.statistic)
+        assert_allclose(res.statistic, res3.statistic)
+        assert_allclose(res.statistic, res4.statistic)
+
+        assert_allclose(res.pvalue, 0.156376448188150, atol=1e-15)
+        assert_allclose(res.pvalue, res2.pvalue)
+        assert_allclose(res.pvalue, res3.pvalue)
+        assert_allclose(res.pvalue, res4.pvalue)
+
+    def test_invalid_contingency_tables(self):
+        N = 100
+        shape = 4, 6
+        size = np.prod(shape)
+
+        np.random.seed(0)
+        # start with a valid contingency table
+        s = stats.multinomial.rvs(N, p=np.ones(size)/size).reshape(shape)
+
+        s5 = s - 2
+        message = "All elements of the contingency table must be non-negative"
+        with assert_raises(ValueError, match=message):
+            stats.somersd(s5)
+
+        s6 = s + 0.01
+        message = "All elements of the contingency table must be integer"
+        with assert_raises(ValueError, match=message):
+            stats.somersd(s6)
+
+        message = ("At least two elements of the contingency "
+                   "table must be nonzero.")
+        with assert_raises(ValueError, match=message):
+            stats.somersd([[]])
+
+        with assert_raises(ValueError, match=message):
+            stats.somersd([[1]])
+
+        s7 = np.zeros((3, 3))
+        with assert_raises(ValueError, match=message):
+            stats.somersd(s7)
+
+        s7[0, 1] = 1
+        with assert_raises(ValueError, match=message):
+            stats.somersd(s7)
+
+    def test_only_ranks_matter(self):
+        # only ranks of input data should matter
+        x = [1, 2, 3]
+        x2 = [-1, 2.1, np.inf]
+        y = [3, 2, 1]
+        y2 = [0, -0.5, -np.inf]
+        res = stats.somersd(x, y)
+        res2 = stats.somersd(x2, y2)
+        assert_equal(res.statistic, res2.statistic)
+        assert_equal(res.pvalue, res2.pvalue)
+
+    def test_contingency_table_return(self):
+        # check that contingency table is returned
+        x = np.arange(10)
+        y = np.arange(10)
+        res = stats.somersd(x, y)
+        assert_equal(res.table, np.eye(10))
+
+    def test_somersd_alternative(self):
+        # Test alternative parameter, asymptotic method (due to tie)
+
+        # Based on scipy.stats.test_stats.TestCorrSpearman2::test_alternative
+        x1 = [1, 2, 3, 4, 5]
+        x2 = [5, 6, 7, 8, 7]
+
+        # strong positive correlation
+        expected = stats.somersd(x1, x2, alternative="two-sided")
+        assert expected.statistic > 0
+
+        # rank correlation > 0 -> large "less" p-value
+        res = stats.somersd(x1, x2, alternative="less")
+        assert_equal(res.statistic, expected.statistic)
+        assert_allclose(res.pvalue, 1 - (expected.pvalue / 2))
+
+        # rank correlation > 0 -> small "greater" p-value
+        res = stats.somersd(x1, x2, alternative="greater")
+        assert_equal(res.statistic, expected.statistic)
+        assert_allclose(res.pvalue, expected.pvalue / 2)
+
+        # reverse the direction of rank correlation
+        x2.reverse()
+
+        # strong negative correlation
+        expected = stats.somersd(x1, x2, alternative="two-sided")
+        assert expected.statistic < 0
+
+        # rank correlation < 0 -> large "greater" p-value
+        res = stats.somersd(x1, x2, alternative="greater")
+        assert_equal(res.statistic, expected.statistic)
+        assert_allclose(res.pvalue, 1 - (expected.pvalue / 2))
+
+        # rank correlation < 0 -> small "less" p-value
+        res = stats.somersd(x1, x2, alternative="less")
+        assert_equal(res.statistic, expected.statistic)
+        assert_allclose(res.pvalue, expected.pvalue / 2)
+
+        with pytest.raises(ValueError, match="`alternative` must be..."):
+            stats.somersd(x1, x2, alternative="ekki-ekki")
+
+    @pytest.mark.parametrize("positive_correlation", (False, True))
+    def test_somersd_perfect_correlation(self, positive_correlation):
+        # Before the addition of `alternative`, perfect correlation was
+        # treated as a special case. Now it is treated like any other case, but
+        # make sure there are no divide by zero warnings or associated errors
+
+        x1 = np.arange(10)
+        x2 = x1 if positive_correlation else np.flip(x1)
+        expected_statistic = 1 if positive_correlation else -1
+
+        # perfect correlation -> small "two-sided" p-value (0)
+        res = stats.somersd(x1, x2, alternative="two-sided")
+        assert res.statistic == expected_statistic
+        assert res.pvalue == 0
+
+        # rank correlation > 0 -> large "less" p-value (1)
+        res = stats.somersd(x1, x2, alternative="less")
+        assert res.statistic == expected_statistic
+        assert res.pvalue == (1 if positive_correlation else 0)
+
+        # rank correlation > 0 -> small "greater" p-value (0)
+        res = stats.somersd(x1, x2, alternative="greater")
+        assert res.statistic == expected_statistic
+        assert res.pvalue == (0 if positive_correlation else 1)
+
+    def test_somersd_large_inputs_gh18132(self):
+        # Test that large inputs where potential overflows could occur give
+        # the expected output. This is tested in the case of binary inputs.
+        # See gh-18126.
+
+        # generate lists of random classes 1-2 (binary)
+        classes = [1, 2]
+        n_samples = 10 ** 6
+        random.seed(6272161)
+        x = random.choices(classes, k=n_samples)
+        y = random.choices(classes, k=n_samples)
+
+        # get value to compare with: sklearn output
+        # from sklearn import metrics
+        # val_auc_sklearn = metrics.roc_auc_score(x, y)
+        # # convert to the Gini coefficient (Gini = (AUC*2)-1)
+        # val_sklearn = 2 * val_auc_sklearn - 1
+        val_sklearn = -0.001528138777036947
+
+        # calculate the Somers' D statistic, which should be equal to the
+        # result of val_sklearn until approximately machine precision
+        val_scipy = stats.somersd(x, y).statistic
+        assert_allclose(val_sklearn, val_scipy, atol=1e-15)
+
+
+class TestBarnardExact:
+    """Some tests to show that barnard_exact() works correctly."""
+
+    @pytest.mark.parametrize(
+        "input_sample,expected",
+        [
+            ([[43, 40], [10, 39]], (3.555406779643, 0.000362832367)),
+            ([[100, 2], [1000, 5]], (-1.776382925679, 0.135126970878)),
+            ([[2, 7], [8, 2]], (-2.518474945157, 0.019210815430)),
+            ([[5, 1], [10, 10]], (1.449486150679, 0.156277546306)),
+            ([[5, 15], [20, 20]], (-1.851640199545, 0.066363501421)),
+            ([[5, 16], [20, 25]], (-1.609639949352, 0.116984852192)),
+            ([[10, 5], [10, 1]], (-1.449486150679, 0.177536588915)),
+            ([[5, 0], [1, 4]], (2.581988897472, 0.013671875000)),
+            ([[0, 1], [3, 2]], (-1.095445115010, 0.509667991877)),
+            ([[0, 2], [6, 4]], (-1.549193338483, 0.197019618792)),
+            ([[2, 7], [8, 2]], (-2.518474945157, 0.019210815430)),
+        ],
+    )
+    def test_precise(self, input_sample, expected):
+        """The expected values have been generated by R, using a resolution
+        for the nuisance parameter of 1e-6 :
+        ```R
+        library(Barnard)
+        options(digits=10)
+        barnard.test(43, 40, 10, 39, dp=1e-6, pooled=TRUE)
+        ```
+        """
+        res = barnard_exact(input_sample)
+        statistic, pvalue = res.statistic, res.pvalue
+        assert_allclose([statistic, pvalue], expected)
+
+    @pytest.mark.parametrize(
+        "input_sample,expected",
+        [
+            ([[43, 40], [10, 39]], (3.920362887717, 0.000289470662)),
+            ([[100, 2], [1000, 5]], (-1.139432816087, 0.950272080594)),
+            ([[2, 7], [8, 2]], (-3.079373904042, 0.020172119141)),
+            ([[5, 1], [10, 10]], (1.622375939458, 0.150599922226)),
+            ([[5, 15], [20, 20]], (-1.974771239528, 0.063038448651)),
+            ([[5, 16], [20, 25]], (-1.722122973346, 0.133329494287)),
+            ([[10, 5], [10, 1]], (-1.765469659009, 0.250566655215)),
+            ([[5, 0], [1, 4]], (5.477225575052, 0.007812500000)),
+            ([[0, 1], [3, 2]], (-1.224744871392, 0.509667991877)),
+            ([[0, 2], [6, 4]], (-1.732050807569, 0.197019618792)),
+            ([[2, 7], [8, 2]], (-3.079373904042, 0.020172119141)),
+        ],
+    )
+    def test_pooled_param(self, input_sample, expected):
+        """The expected values have been generated by R, using a resolution
+        for the nuisance parameter of 1e-6 :
+        ```R
+        library(Barnard)
+        options(digits=10)
+        barnard.test(43, 40, 10, 39, dp=1e-6, pooled=FALSE)
+        ```
+        """
+        res = barnard_exact(input_sample, pooled=False)
+        statistic, pvalue = res.statistic, res.pvalue
+        assert_allclose([statistic, pvalue], expected)
+
+    def test_raises(self):
+        # test we raise an error for wrong input number of nuisances.
+        error_msg = (
+            "Number of points `n` must be strictly positive, found 0"
+        )
+        with assert_raises(ValueError, match=error_msg):
+            barnard_exact([[1, 2], [3, 4]], n=0)
+
+        # test we raise an error for wrong shape of input.
+        error_msg = "The input `table` must be of shape \\(2, 2\\)."
+        with assert_raises(ValueError, match=error_msg):
+            barnard_exact(np.arange(6).reshape(2, 3))
+
+        # Test all values must be positives
+        error_msg = "All values in `table` must be nonnegative."
+        with assert_raises(ValueError, match=error_msg):
+            barnard_exact([[-1, 2], [3, 4]])
+
+        # Test value error on wrong alternative param
+        error_msg = (
+            "`alternative` should be one of {'two-sided', 'less', 'greater'},"
+            " found .*"
+        )
+        with assert_raises(ValueError, match=error_msg):
+            barnard_exact([[1, 2], [3, 4]], "not-correct")
+
+    @pytest.mark.parametrize(
+        "input_sample,expected",
+        [
+            ([[0, 0], [4, 3]], (1.0, 0)),
+        ],
+    )
+    def test_edge_cases(self, input_sample, expected):
+        res = barnard_exact(input_sample)
+        statistic, pvalue = res.statistic, res.pvalue
+        assert_equal(pvalue, expected[0])
+        assert_equal(statistic, expected[1])
+
+    @pytest.mark.parametrize(
+        "input_sample,expected",
+        [
+            ([[0, 5], [0, 10]], (1.0, np.nan)),
+            ([[5, 0], [10, 0]], (1.0, np.nan)),
+        ],
+    )
+    def test_row_or_col_zero(self, input_sample, expected):
+        res = barnard_exact(input_sample)
+        statistic, pvalue = res.statistic, res.pvalue
+        assert_equal(pvalue, expected[0])
+        assert_equal(statistic, expected[1])
+
+    @pytest.mark.parametrize(
+        "input_sample,expected",
+        [
+            ([[2, 7], [8, 2]], (-2.518474945157, 0.009886140845)),
+            ([[7, 200], [300, 8]], (-21.320036698460, 0.0)),
+            ([[21, 28], [1957, 6]], (-30.489638143953, 0.0)),
+        ],
+    )
+    @pytest.mark.parametrize("alternative", ["greater", "less"])
+    def test_less_greater(self, input_sample, expected, alternative):
+        """
+        "The expected values have been generated by R, using a resolution
+        for the nuisance parameter of 1e-6 :
+        ```R
+        library(Barnard)
+        options(digits=10)
+        a = barnard.test(2, 7, 8, 2, dp=1e-6, pooled=TRUE)
+        a$p.value[1]
+        ```
+        In this test, we are using the "one-sided" return value `a$p.value[1]`
+        to test our pvalue.
+        """
+        expected_stat, less_pvalue_expect = expected
+
+        if alternative == "greater":
+            input_sample = np.array(input_sample)[:, ::-1]
+            expected_stat = -expected_stat
+
+        res = barnard_exact(input_sample, alternative=alternative)
+        statistic, pvalue = res.statistic, res.pvalue
+        assert_allclose(
+            [statistic, pvalue], [expected_stat, less_pvalue_expect], atol=1e-7
+        )
+
+
+class TestBoschlooExact:
+    """Some tests to show that boschloo_exact() works correctly."""
+
+    ATOL = 1e-7
+
+    @pytest.mark.parametrize(
+        "input_sample,expected",
+        [
+            ([[2, 7], [8, 2]], (0.01852173, 0.009886142)),
+            ([[5, 1], [10, 10]], (0.9782609, 0.9450994)),
+            ([[5, 16], [20, 25]], (0.08913823, 0.05827348)),
+            ([[10, 5], [10, 1]], (0.1652174, 0.08565611)),
+            ([[5, 0], [1, 4]], (1, 1)),
+            ([[0, 1], [3, 2]], (0.5, 0.34375)),
+            ([[2, 7], [8, 2]], (0.01852173, 0.009886142)),
+            ([[7, 12], [8, 3]], (0.06406797, 0.03410916)),
+            ([[10, 24], [25, 37]], (0.2009359, 0.1512882)),
+        ],
+    )
+    def test_less(self, input_sample, expected):
+        """The expected values have been generated by R, using a resolution
+        for the nuisance parameter of 1e-8 :
+        ```R
+        library(Exact)
+        options(digits=10)
+        data <- matrix(c(43, 10, 40, 39), 2, 2, byrow=TRUE)
+        a = exact.test(data, method="Boschloo", alternative="less",
+                       tsmethod="central", np.interval=TRUE, beta=1e-8)
+        ```
+        """
+        res = boschloo_exact(input_sample, alternative="less")
+        statistic, pvalue = res.statistic, res.pvalue
+        assert_allclose([statistic, pvalue], expected, atol=self.ATOL)
+
+    @pytest.mark.parametrize(
+        "input_sample,expected",
+        [
+            ([[43, 40], [10, 39]], (0.0002875544, 0.0001615562)),
+            ([[2, 7], [8, 2]], (0.9990149, 0.9918327)),
+            ([[5, 1], [10, 10]], (0.1652174, 0.09008534)),
+            ([[5, 15], [20, 20]], (0.9849087, 0.9706997)),
+            ([[5, 16], [20, 25]], (0.972349, 0.9524124)),
+            ([[5, 0], [1, 4]], (0.02380952, 0.006865367)),
+            ([[0, 1], [3, 2]], (1, 1)),
+            ([[0, 2], [6, 4]], (1, 1)),
+            ([[2, 7], [8, 2]], (0.9990149, 0.9918327)),
+            ([[7, 12], [8, 3]], (0.9895302, 0.9771215)),
+            ([[10, 24], [25, 37]], (0.9012936, 0.8633275)),
+        ],
+    )
+    def test_greater(self, input_sample, expected):
+        """The expected values have been generated by R, using a resolution
+        for the nuisance parameter of 1e-8 :
+        ```R
+        library(Exact)
+        options(digits=10)
+        data <- matrix(c(43, 10, 40, 39), 2, 2, byrow=TRUE)
+        a = exact.test(data, method="Boschloo", alternative="greater",
+                       tsmethod="central", np.interval=TRUE, beta=1e-8)
+        ```
+        """
+        res = boschloo_exact(input_sample, alternative="greater")
+        statistic, pvalue = res.statistic, res.pvalue
+        assert_allclose([statistic, pvalue], expected, atol=self.ATOL)
+
+    @pytest.mark.parametrize(
+        "input_sample,expected",
+        [
+            ([[43, 40], [10, 39]], (0.0002875544, 0.0003231115)),
+            ([[2, 7], [8, 2]], (0.01852173, 0.01977228)),
+            ([[5, 1], [10, 10]], (0.1652174, 0.1801707)),
+            ([[5, 16], [20, 25]], (0.08913823, 0.116547)),
+            ([[5, 0], [1, 4]], (0.02380952, 0.01373073)),
+            ([[0, 1], [3, 2]], (0.5, 0.6875)),
+            ([[2, 7], [8, 2]], (0.01852173, 0.01977228)),
+            ([[7, 12], [8, 3]], (0.06406797, 0.06821831)),
+        ],
+    )
+    def test_two_sided(self, input_sample, expected):
+        """The expected values have been generated by R, using a resolution
+        for the nuisance parameter of 1e-8 :
+        ```R
+        library(Exact)
+        options(digits=10)
+        data <- matrix(c(43, 10, 40, 39), 2, 2, byrow=TRUE)
+        a = exact.test(data, method="Boschloo", alternative="two.sided",
+                       tsmethod="central", np.interval=TRUE, beta=1e-8)
+        ```
+        """
+        res = boschloo_exact(input_sample, alternative="two-sided", n=64)
+        # Need n = 64 for python 32-bit
+        statistic, pvalue = res.statistic, res.pvalue
+        assert_allclose([statistic, pvalue], expected, atol=self.ATOL)
+
+    def test_raises(self):
+        # test we raise an error for wrong input number of nuisances.
+        error_msg = (
+            "Number of points `n` must be strictly positive, found 0"
+        )
+        with assert_raises(ValueError, match=error_msg):
+            boschloo_exact([[1, 2], [3, 4]], n=0)
+
+        # test we raise an error for wrong shape of input.
+        error_msg = "The input `table` must be of shape \\(2, 2\\)."
+        with assert_raises(ValueError, match=error_msg):
+            boschloo_exact(np.arange(6).reshape(2, 3))
+
+        # Test all values must be positives
+        error_msg = "All values in `table` must be nonnegative."
+        with assert_raises(ValueError, match=error_msg):
+            boschloo_exact([[-1, 2], [3, 4]])
+
+        # Test value error on wrong alternative param
+        error_msg = (
+            r"`alternative` should be one of \('two-sided', 'less', "
+            r"'greater'\), found .*"
+        )
+        with assert_raises(ValueError, match=error_msg):
+            boschloo_exact([[1, 2], [3, 4]], "not-correct")
+
+    @pytest.mark.parametrize(
+        "input_sample,expected",
+        [
+            ([[0, 5], [0, 10]], (np.nan, np.nan)),
+            ([[5, 0], [10, 0]], (np.nan, np.nan)),
+        ],
+    )
+    def test_row_or_col_zero(self, input_sample, expected):
+        res = boschloo_exact(input_sample)
+        statistic, pvalue = res.statistic, res.pvalue
+        assert_equal(pvalue, expected[0])
+        assert_equal(statistic, expected[1])
+
+    def test_two_sided_gt_1(self):
+        # Check that returned p-value does not exceed 1 even when twice
+        # the minimum of the one-sided p-values does. See gh-15345.
+        tbl = [[1, 1], [13, 12]]
+        pl = boschloo_exact(tbl, alternative='less').pvalue
+        pg = boschloo_exact(tbl, alternative='greater').pvalue
+        assert 2*min(pl, pg) > 1
+        pt = boschloo_exact(tbl, alternative='two-sided').pvalue
+        assert pt == 1.0
+
+    @pytest.mark.parametrize("alternative", ("less", "greater"))
+    def test_against_fisher_exact(self, alternative):
+        # Check that the statistic of `boschloo_exact` is the same as the
+        # p-value of `fisher_exact` (for one-sided tests). See gh-15345.
+        tbl = [[2, 7], [8, 2]]
+        boschloo_stat = boschloo_exact(tbl, alternative=alternative).statistic
+        fisher_p = stats.fisher_exact(tbl, alternative=alternative)[1]
+        assert_allclose(boschloo_stat, fisher_p)
+
+
+class TestCvm_2samp:
+    @pytest.mark.parametrize('args', [([], np.arange(5)),
+                                      (np.arange(5), [1])])
+    def test_too_small_input(self, args):
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = cramervonmises_2samp(*args)
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+    def test_invalid_input(self):
+        y = np.arange(5)
+        msg = 'method must be either auto, exact or asymptotic'
+        with pytest.raises(ValueError, match=msg):
+            cramervonmises_2samp(y, y, 'xyz')
+
+    def test_list_input(self):
+        x = [2, 3, 4, 7, 6]
+        y = [0.2, 0.7, 12, 18]
+        r1 = cramervonmises_2samp(x, y)
+        r2 = cramervonmises_2samp(np.array(x), np.array(y))
+        assert_equal((r1.statistic, r1.pvalue), (r2.statistic, r2.pvalue))
+
+    def test_example_conover(self):
+        # Example 2 in Section 6.2 of W.J. Conover: Practical Nonparametric
+        # Statistics, 1971.
+        x = [7.6, 8.4, 8.6, 8.7, 9.3, 9.9, 10.1, 10.6, 11.2]
+        y = [5.2, 5.7, 5.9, 6.5, 6.8, 8.2, 9.1, 9.8, 10.8, 11.3, 11.5, 12.3,
+             12.5, 13.4, 14.6]
+        r = cramervonmises_2samp(x, y)
+        assert_allclose(r.statistic, 0.262, atol=1e-3)
+        assert_allclose(r.pvalue, 0.18, atol=1e-2)
+
+    @pytest.mark.parametrize('statistic, m, n, pval',
+                             [(710, 5, 6, 48./462),
+                              (1897, 7, 7, 117./1716),
+                              (576, 4, 6, 2./210),
+                              (1764, 6, 7, 2./1716)])
+    def test_exact_pvalue(self, statistic, m, n, pval):
+        # the exact values are taken from Anderson: On the distribution of the
+        # two-sample Cramer-von-Mises criterion, 1962.
+        # The values are taken from Table 2, 3, 4 and 5
+        assert_equal(_pval_cvm_2samp_exact(statistic, m, n), pval)
+
+    @pytest.mark.xslow
+    def test_large_sample(self):
+        # for large samples, the statistic U gets very large
+        # do a sanity check that p-value is not 0, 1 or nan
+        np.random.seed(4367)
+        x = distributions.norm.rvs(size=1000000)
+        y = distributions.norm.rvs(size=900000)
+        r = cramervonmises_2samp(x, y)
+        assert_(0 < r.pvalue < 1)
+        r = cramervonmises_2samp(x, y+0.1)
+        assert_(0 < r.pvalue < 1)
+
+    def test_exact_vs_asymptotic(self):
+        np.random.seed(0)
+        x = np.random.rand(7)
+        y = np.random.rand(8)
+        r1 = cramervonmises_2samp(x, y, method='exact')
+        r2 = cramervonmises_2samp(x, y, method='asymptotic')
+        assert_equal(r1.statistic, r2.statistic)
+        assert_allclose(r1.pvalue, r2.pvalue, atol=1e-2)
+
+    def test_method_auto(self):
+        x = np.arange(20)
+        y = [0.5, 4.7, 13.1]
+        r1 = cramervonmises_2samp(x, y, method='exact')
+        r2 = cramervonmises_2samp(x, y, method='auto')
+        assert_equal(r1.pvalue, r2.pvalue)
+        # switch to asymptotic if one sample has more than 20 observations
+        x = np.arange(21)
+        r1 = cramervonmises_2samp(x, y, method='asymptotic')
+        r2 = cramervonmises_2samp(x, y, method='auto')
+        assert_equal(r1.pvalue, r2.pvalue)
+
+    def test_same_input(self):
+        # make sure trivial edge case can be handled
+        # note that _cdf_cvm_inf(0) = nan. implementation avoids nan by
+        # returning pvalue=1 for very small values of the statistic
+        x = np.arange(15)
+        res = cramervonmises_2samp(x, x)
+        assert_equal((res.statistic, res.pvalue), (0.0, 1.0))
+        # check exact p-value
+        res = cramervonmises_2samp(x[:4], x[:4])
+        assert_equal((res.statistic, res.pvalue), (0.0, 1.0))
+
+
+class TestTukeyHSD:
+
+    data_same_size = ([24.5, 23.5, 26.4, 27.1, 29.9],
+                      [28.4, 34.2, 29.5, 32.2, 30.1],
+                      [26.1, 28.3, 24.3, 26.2, 27.8])
+    data_diff_size = ([24.5, 23.5, 26.28, 26.4, 27.1, 29.9, 30.1, 30.1],
+                      [28.4, 34.2, 29.5, 32.2, 30.1],
+                      [26.1, 28.3, 24.3, 26.2, 27.8])
+    extreme_size = ([24.5, 23.5, 26.4],
+                    [28.4, 34.2, 29.5, 32.2, 30.1, 28.4, 34.2, 29.5, 32.2,
+                     30.1],
+                    [26.1, 28.3, 24.3, 26.2, 27.8])
+
+    sas_same_size = """
+    Comparison LowerCL Difference UpperCL Significance
+    2 - 3	0.6908830568	4.34	7.989116943	    1
+    2 - 1	0.9508830568	4.6 	8.249116943 	1
+    3 - 2	-7.989116943	-4.34	-0.6908830568	1
+    3 - 1	-3.389116943	0.26	3.909116943	    0
+    1 - 2	-8.249116943	-4.6	-0.9508830568	1
+    1 - 3	-3.909116943	-0.26	3.389116943	    0
+    """
+
+    sas_diff_size = """
+    Comparison LowerCL Difference UpperCL Significance
+    2 - 1	0.2679292645	3.645	7.022070736	    1
+    2 - 3	0.5934764007	4.34	8.086523599	    1
+    1 - 2	-7.022070736	-3.645	-0.2679292645	1
+    1 - 3	-2.682070736	0.695	4.072070736	    0
+    3 - 2	-8.086523599	-4.34	-0.5934764007	1
+    3 - 1	-4.072070736	-0.695	2.682070736	    0
+    """
+
+    sas_extreme = """
+    Comparison LowerCL Difference UpperCL Significance
+    2 - 3	1.561605075	    4.34	7.118394925	    1
+    2 - 1	2.740784879	    6.08	9.419215121	    1
+    3 - 2	-7.118394925	-4.34	-1.561605075	1
+    3 - 1	-1.964526566	1.74	5.444526566	    0
+    1 - 2	-9.419215121	-6.08	-2.740784879	1
+    1 - 3	-5.444526566	-1.74	1.964526566	    0
+    """
+
+    @pytest.mark.parametrize("data,res_expect_str,atol",
+                             ((data_same_size, sas_same_size, 1e-4),
+                              (data_diff_size, sas_diff_size, 1e-4),
+                              (extreme_size, sas_extreme, 1e-10),
+                              ),
+                             ids=["equal size sample",
+                                  "unequal sample size",
+                                  "extreme sample size differences"])
+    def test_compare_sas(self, data, res_expect_str, atol):
+        '''
+        SAS code used to generate results for each sample:
+        DATA ACHE;
+        INPUT BRAND RELIEF;
+        CARDS;
+        1 24.5
+        ...
+        3 27.8
+        ;
+        ods graphics on;   ODS RTF;ODS LISTING CLOSE;
+           PROC ANOVA DATA=ACHE;
+           CLASS BRAND;
+           MODEL RELIEF=BRAND;
+           MEANS BRAND/TUKEY CLDIFF;
+           TITLE 'COMPARE RELIEF ACROSS MEDICINES  - ANOVA EXAMPLE';
+           ods output  CLDiffs =tc;
+        proc print data=tc;
+            format LowerCL 17.16 UpperCL 17.16 Difference 17.16;
+            title "Output with many digits";
+        RUN;
+        QUIT;
+        ODS RTF close;
+        ODS LISTING;
+        '''
+        res_expect = np.asarray(res_expect_str.replace(" - ", " ").split()[5:],
+                                dtype=float).reshape((6, 6))
+        res_tukey = stats.tukey_hsd(*data)
+        conf = res_tukey.confidence_interval()
+        # loop over the comparisons
+        for i, j, l, s, h, sig in res_expect:
+            i, j = int(i) - 1, int(j) - 1
+            assert_allclose(conf.low[i, j], l, atol=atol)
+            assert_allclose(res_tukey.statistic[i, j], s, atol=atol)
+            assert_allclose(conf.high[i, j], h, atol=atol)
+            assert_allclose((res_tukey.pvalue[i, j] <= .05), sig == 1)
+
+    matlab_sm_siz = """
+        1	2	-8.2491590248597	-4.6	-0.9508409751403	0.0144483269098
+        1	3	-3.9091590248597	-0.26	3.3891590248597	0.9803107240900
+        2	3	0.6908409751403	4.34	7.9891590248597	0.0203311368795
+        """
+
+    matlab_diff_sz = """
+        1	2	-7.02207069748501	-3.645	-0.26792930251500 0.03371498443080
+        1	3	-2.68207069748500	0.695	4.07207069748500 0.85572267328807
+        2	3	0.59347644287720	4.34	8.08652355712281 0.02259047020620
+        """
+
+    @pytest.mark.parametrize("data,res_expect_str,atol",
+                             ((data_same_size, matlab_sm_siz, 1e-12),
+                              (data_diff_size, matlab_diff_sz, 1e-7)),
+                             ids=["equal size sample",
+                                  "unequal size sample"])
+    def test_compare_matlab(self, data, res_expect_str, atol):
+        """
+        vals = [24.5, 23.5,  26.4, 27.1, 29.9, 28.4, 34.2, 29.5, 32.2, 30.1,
+         26.1, 28.3, 24.3, 26.2, 27.8]
+        names = {'zero', 'zero', 'zero', 'zero', 'zero', 'one', 'one', 'one',
+         'one', 'one', 'two', 'two', 'two', 'two', 'two'}
+        [p,t,stats] = anova1(vals,names,"off");
+        [c,m,h,nms] = multcompare(stats, "CType","hsd");
+        """
+        res_expect = np.asarray(res_expect_str.split(),
+                                dtype=float).reshape((3, 6))
+        res_tukey = stats.tukey_hsd(*data)
+        conf = res_tukey.confidence_interval()
+        # loop over the comparisons
+        for i, j, l, s, h, p in res_expect:
+            i, j = int(i) - 1, int(j) - 1
+            assert_allclose(conf.low[i, j], l, atol=atol)
+            assert_allclose(res_tukey.statistic[i, j], s, atol=atol)
+            assert_allclose(conf.high[i, j], h, atol=atol)
+            assert_allclose(res_tukey.pvalue[i, j], p, atol=atol)
+
+    def test_compare_r(self):
+        """
+        Testing against results and p-values from R:
+        from: https://www.rdocumentation.org/packages/stats/versions/3.6.2/
+        topics/TukeyHSD
+        > require(graphics)
+        > summary(fm1 <- aov(breaks ~ tension, data = warpbreaks))
+        > TukeyHSD(fm1, "tension", ordered = TRUE)
+        > plot(TukeyHSD(fm1, "tension"))
+        Tukey multiple comparisons of means
+        95% family-wise confidence level
+        factor levels have been ordered
+        Fit: aov(formula = breaks ~ tension, data = warpbreaks)
+        $tension
+        """
+        str_res = """
+                diff        lwr      upr     p adj
+        2 - 3  4.722222 -4.8376022 14.28205 0.4630831
+        1 - 3 14.722222  5.1623978 24.28205 0.0014315
+        1 - 2 10.000000  0.4401756 19.55982 0.0384598
+        """
+        res_expect = np.asarray(str_res.replace(" - ", " ").split()[5:],
+                                dtype=float).reshape((3, 6))
+        data = ([26, 30, 54, 25, 70, 52, 51, 26, 67,
+                 27, 14, 29, 19, 29, 31, 41, 20, 44],
+                [18, 21, 29, 17, 12, 18, 35, 30, 36,
+                 42, 26, 19, 16, 39, 28, 21, 39, 29],
+                [36, 21, 24, 18, 10, 43, 28, 15, 26,
+                 20, 21, 24, 17, 13, 15, 15, 16, 28])
+
+        res_tukey = stats.tukey_hsd(*data)
+        conf = res_tukey.confidence_interval()
+        # loop over the comparisons
+        for i, j, s, l, h, p in res_expect:
+            i, j = int(i) - 1, int(j) - 1
+            # atols are set to the number of digits present in the r result.
+            assert_allclose(conf.low[i, j], l, atol=1e-7)
+            assert_allclose(res_tukey.statistic[i, j], s, atol=1e-6)
+            assert_allclose(conf.high[i, j], h, atol=1e-5)
+            assert_allclose(res_tukey.pvalue[i, j], p, atol=1e-7)
+
+    def test_engineering_stat_handbook(self):
+        '''
+        Example sourced from:
+        https://www.itl.nist.gov/div898/handbook/prc/section4/prc471.htm
+        '''
+        group1 = [6.9, 5.4, 5.8, 4.6, 4.0]
+        group2 = [8.3, 6.8, 7.8, 9.2, 6.5]
+        group3 = [8.0, 10.5, 8.1, 6.9, 9.3]
+        group4 = [5.8, 3.8, 6.1, 5.6, 6.2]
+        res = stats.tukey_hsd(group1, group2, group3, group4)
+        conf = res.confidence_interval()
+        lower = np.asarray([
+            [0, 0, 0, -2.25],
+            [.29, 0, -2.93, .13],
+            [1.13, 0, 0, .97],
+            [0, 0, 0, 0]])
+        upper = np.asarray([
+            [0, 0, 0, 1.93],
+            [4.47, 0, 1.25, 4.31],
+            [5.31, 0, 0, 5.15],
+            [0, 0, 0, 0]])
+
+        for (i, j) in [(1, 0), (2, 0), (0, 3), (1, 2), (2, 3)]:
+            assert_allclose(conf.low[i, j], lower[i, j], atol=1e-2)
+            assert_allclose(conf.high[i, j], upper[i, j], atol=1e-2)
+
+    def test_rand_symm(self):
+        # test some expected identities of the results
+        np.random.seed(1234)
+        data = np.random.rand(3, 100)
+        res = stats.tukey_hsd(*data)
+        conf = res.confidence_interval()
+        # the confidence intervals should be negated symmetric of each other
+        assert_equal(conf.low, -conf.high.T)
+        # the `high` and `low` center diagonals should be the same since the
+        # mean difference in a self comparison is 0.
+        assert_equal(np.diagonal(conf.high), conf.high[0, 0])
+        assert_equal(np.diagonal(conf.low), conf.low[0, 0])
+        # statistic array should be antisymmetric with zeros on the diagonal
+        assert_equal(res.statistic, -res.statistic.T)
+        assert_equal(np.diagonal(res.statistic), 0)
+        # p-values should be symmetric and 1 when compared to itself
+        assert_equal(res.pvalue, res.pvalue.T)
+        assert_equal(np.diagonal(res.pvalue), 1)
+
+    def test_no_inf(self):
+        with assert_raises(ValueError, match="...must be finite."):
+            stats.tukey_hsd([1, 2, 3], [2, np.inf], [6, 7, 3])
+
+    def test_is_1d(self):
+        with assert_raises(ValueError, match="...must be one-dimensional"):
+            stats.tukey_hsd([[1, 2], [2, 3]], [2, 5], [5, 23, 6])
+
+    def test_no_empty(self):
+        with assert_raises(ValueError, match="...must be greater than one"):
+            stats.tukey_hsd([], [2, 5], [4, 5, 6])
+
+    @pytest.mark.parametrize("nargs", (0, 1))
+    def test_not_enough_treatments(self, nargs):
+        with assert_raises(ValueError, match="...more than 1 treatment."):
+            stats.tukey_hsd(*([[23, 7, 3]] * nargs))
+
+    @pytest.mark.parametrize("cl", [-.5, 0, 1, 2])
+    def test_conf_level_invalid(self, cl):
+        with assert_raises(ValueError, match="must be between 0 and 1"):
+            r = stats.tukey_hsd([23, 7, 3], [3, 4], [9, 4])
+            r.confidence_interval(cl)
+
+    def test_2_args_ttest(self):
+        # that with 2 treatments the `pvalue` is equal to that of `ttest_ind`
+        res_tukey = stats.tukey_hsd(*self.data_diff_size[:2])
+        res_ttest = stats.ttest_ind(*self.data_diff_size[:2])
+        assert_allclose(res_ttest.pvalue, res_tukey.pvalue[0, 1])
+        assert_allclose(res_ttest.pvalue, res_tukey.pvalue[1, 0])
+
+
+class TestPoissonMeansTest:
+    @pytest.mark.parametrize("c1, n1, c2, n2, p_expect", (
+        # example from [1], 6. Illustrative examples: Example 1
+        [0, 100, 3, 100, 0.0884],
+        [2, 100, 6, 100, 0.1749]
+    ))
+    def test_paper_examples(self, c1, n1, c2, n2, p_expect):
+        res = stats.poisson_means_test(c1, n1, c2, n2)
+        assert_allclose(res.pvalue, p_expect, atol=1e-4)
+
+    @pytest.mark.parametrize("c1, n1, c2, n2, p_expect, alt, d", (
+        # These test cases are produced by the wrapped fortran code from the
+        # original authors. Using a slightly modified version of this fortran,
+        # found here, https://github.com/nolanbconaway/poisson-etest,
+        # additional tests were created.
+        [20, 10, 20, 10, 0.9999997568929630, 'two-sided', 0],
+        [10, 10, 10, 10, 0.9999998403241203, 'two-sided', 0],
+        [50, 15, 1, 1, 0.09920321053409643, 'two-sided', .05],
+        [3, 100, 20, 300, 0.12202725450896404, 'two-sided', 0],
+        [3, 12, 4, 20, 0.40416087318539173, 'greater', 0],
+        [4, 20, 3, 100, 0.008053640402974236, 'greater', 0],
+        # publishing paper does not include a `less` alternative,
+        # so it was calculated with switched argument order and
+        # alternative="greater"
+        [4, 20, 3, 10, 0.3083216325432898, 'less', 0],
+        [1, 1, 50, 15, 0.09322998607245102, 'less', 0]
+    ))
+    def test_fortran_authors(self, c1, n1, c2, n2, p_expect, alt, d):
+        res = stats.poisson_means_test(c1, n1, c2, n2, alternative=alt, diff=d)
+        assert_allclose(res.pvalue, p_expect, atol=2e-6, rtol=1e-16)
+
+    def test_different_results(self):
+        # The implementation in Fortran is known to break down at higher
+        # counts and observations, so we expect different results. By
+        # inspection we can infer the p-value to be near one.
+        count1, count2 = 10000, 10000
+        nobs1, nobs2 = 10000, 10000
+        res = stats.poisson_means_test(count1, nobs1, count2, nobs2)
+        assert_allclose(res.pvalue, 1)
+
+    def test_less_than_zero_lambda_hat2(self):
+        # demonstrates behavior that fixes a known fault from original Fortran.
+        # p-value should clearly be near one.
+        count1, count2 = 0, 0
+        nobs1, nobs2 = 1, 1
+        res = stats.poisson_means_test(count1, nobs1, count2, nobs2)
+        assert_allclose(res.pvalue, 1)
+
+    def test_input_validation(self):
+        count1, count2 = 0, 0
+        nobs1, nobs2 = 1, 1
+
+        # test non-integral events
+        message = '`k1` and `k2` must be integers.'
+        with assert_raises(TypeError, match=message):
+            stats.poisson_means_test(.7, nobs1, count2, nobs2)
+        with assert_raises(TypeError, match=message):
+            stats.poisson_means_test(count1, nobs1, .7, nobs2)
+
+        # test negative events
+        message = '`k1` and `k2` must be greater than or equal to 0.'
+        with assert_raises(ValueError, match=message):
+            stats.poisson_means_test(-1, nobs1, count2, nobs2)
+        with assert_raises(ValueError, match=message):
+            stats.poisson_means_test(count1, nobs1, -1, nobs2)
+
+        # test negative sample size
+        message = '`n1` and `n2` must be greater than 0.'
+        with assert_raises(ValueError, match=message):
+            stats.poisson_means_test(count1, -1, count2, nobs2)
+        with assert_raises(ValueError, match=message):
+            stats.poisson_means_test(count1, nobs1, count2, -1)
+
+        # test negative difference
+        message = 'diff must be greater than or equal to 0.'
+        with assert_raises(ValueError, match=message):
+            stats.poisson_means_test(count1, nobs1, count2, nobs2, diff=-1)
+
+        # test invalid alternative
+        message = 'Alternative must be one of ...'
+        with assert_raises(ValueError, match=message):
+            stats.poisson_means_test(1, 2, 1, 2, alternative='error')
+
+
+class TestBWSTest:
+
+    def test_bws_input_validation(self):
+        rng = np.random.default_rng(4571775098104213308)
+
+        x, y = rng.random(size=(2, 7))
+
+        message = '`x` and `y` must be exactly one-dimensional.'
+        with pytest.raises(ValueError, match=message):
+            stats.bws_test([x, x], [y, y])
+
+        message = '`x` and `y` must not contain NaNs.'
+        with pytest.raises(ValueError, match=message):
+            stats.bws_test([np.nan], y)
+
+        message = '`x` and `y` must be of nonzero size.'
+        with pytest.raises(ValueError, match=message):
+            stats.bws_test(x, [])
+
+        message = 'alternative` must be one of...'
+        with pytest.raises(ValueError, match=message):
+            stats.bws_test(x, y, alternative='ekki-ekki')
+
+        message = 'method` must be an instance of...'
+        with pytest.raises(ValueError, match=message):
+            stats.bws_test(x, y, method=42)
+
+
+    def test_against_published_reference(self):
+        # Test against Example 2 in bws_test Reference [1], pg 9
+        # https://link.springer.com/content/pdf/10.1007/BF02762032.pdf
+        x = [1, 2, 3, 4, 6, 7, 8]
+        y = [5, 9, 10, 11, 12, 13, 14]
+        res = stats.bws_test(x, y, alternative='two-sided')
+        assert_allclose(res.statistic, 5.132, atol=1e-3)
+        assert_equal(res.pvalue, 10/3432)
+
+
+    @pytest.mark.parametrize(('alternative', 'statistic', 'pvalue'),
+                             [('two-sided', 1.7510204081633, 0.1264422777777),
+                              ('less', -1.7510204081633, 0.05754662004662),
+                              ('greater', -1.7510204081633, 0.9424533799534)])
+    def test_against_R(self, alternative, statistic, pvalue):
+        # Test against R library BWStest function bws_test
+        # library(BWStest)
+        # options(digits=16)
+        # x = c(...)
+        # y = c(...)
+        # bws_test(x, y, alternative='two.sided')
+        rng = np.random.default_rng(4571775098104213308)
+        x, y = rng.random(size=(2, 7))
+        res = stats.bws_test(x, y, alternative=alternative)
+        assert_allclose(res.statistic, statistic, rtol=1e-13)
+        assert_allclose(res.pvalue, pvalue, atol=1e-2, rtol=1e-1)
+
+    @pytest.mark.parametrize(('alternative', 'statistic', 'pvalue'),
+                             [('two-sided', 1.142629265891, 0.2903950180801),
+                              ('less', 0.99629665877411, 0.8545660222131),
+                              ('greater', 0.99629665877411, 0.1454339777869)])
+    def test_against_R_imbalanced(self, alternative, statistic, pvalue):
+        # Test against R library BWStest function bws_test
+        # library(BWStest)
+        # options(digits=16)
+        # x = c(...)
+        # y = c(...)
+        # bws_test(x, y, alternative='two.sided')
+        rng = np.random.default_rng(5429015622386364034)
+        x = rng.random(size=9)
+        y = rng.random(size=8)
+        res = stats.bws_test(x, y, alternative=alternative)
+        assert_allclose(res.statistic, statistic, rtol=1e-13)
+        assert_allclose(res.pvalue, pvalue, atol=1e-2, rtol=1e-1)
+
+    def test_method(self):
+        # Test that `method` parameter has the desired effect
+        rng = np.random.default_rng(1520514347193347862)
+        x, y = rng.random(size=(2, 10))
+
+        rng = np.random.default_rng(1520514347193347862)
+        method = stats.PermutationMethod(n_resamples=10, rng=rng)
+        res1 = stats.bws_test(x, y, method=method)
+
+        assert len(res1.null_distribution) == 10
+
+        rng = np.random.default_rng(1520514347193347862)
+        method = stats.PermutationMethod(n_resamples=10, rng=rng)
+        res2 = stats.bws_test(x, y, method=method)
+
+        assert_allclose(res1.null_distribution, res2.null_distribution)
+
+        rng = np.random.default_rng(5205143471933478621)
+        method = stats.PermutationMethod(n_resamples=10, rng=rng)
+        res3 = stats.bws_test(x, y, method=method)
+
+        assert not np.allclose(res3.null_distribution, res1.null_distribution)
+
+    def test_directions(self):
+        # Sanity check of the sign of the one-sided statistic
+        rng = np.random.default_rng(1520514347193347862)
+        x = rng.random(size=5)
+        y = x - 1
+
+        res = stats.bws_test(x, y, alternative='greater')
+        assert res.statistic > 0
+        assert_equal(res.pvalue, 1 / len(res.null_distribution))
+
+        res = stats.bws_test(x, y, alternative='less')
+        assert res.statistic > 0
+        assert_equal(res.pvalue, 1)
+
+        res = stats.bws_test(y, x, alternative='less')
+        assert res.statistic < 0
+        assert_equal(res.pvalue, 1 / len(res.null_distribution))
+
+        res = stats.bws_test(y, x, alternative='greater')
+        assert res.statistic < 0
+        assert_equal(res.pvalue, 1)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_kdeoth.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_kdeoth.py
new file mode 100644
index 0000000000000000000000000000000000000000..01aae391dcee1e43e9a51a72e9d6b642b7a24da8
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_kdeoth.py
@@ -0,0 +1,608 @@
+from scipy import stats, linalg, integrate
+import numpy as np
+from numpy.testing import (assert_almost_equal, assert_, assert_equal,
+                           assert_array_almost_equal,
+                           assert_array_almost_equal_nulp, assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+
+
+def test_kde_1d():
+    #some basic tests comparing to normal distribution
+    np.random.seed(8765678)
+    n_basesample = 500
+    xn = np.random.randn(n_basesample)
+    xnmean = xn.mean()
+    xnstd = xn.std(ddof=1)
+
+    # get kde for original sample
+    gkde = stats.gaussian_kde(xn)
+
+    # evaluate the density function for the kde for some points
+    xs = np.linspace(-7,7,501)
+    kdepdf = gkde.evaluate(xs)
+    normpdf = stats.norm.pdf(xs, loc=xnmean, scale=xnstd)
+    intervall = xs[1] - xs[0]
+
+    assert_(np.sum((kdepdf - normpdf)**2)*intervall < 0.01)
+    prob1 = gkde.integrate_box_1d(xnmean, np.inf)
+    prob2 = gkde.integrate_box_1d(-np.inf, xnmean)
+    assert_almost_equal(prob1, 0.5, decimal=1)
+    assert_almost_equal(prob2, 0.5, decimal=1)
+    assert_almost_equal(gkde.integrate_box(xnmean, np.inf), prob1, decimal=13)
+    assert_almost_equal(gkde.integrate_box(-np.inf, xnmean), prob2, decimal=13)
+
+    assert_almost_equal(gkde.integrate_kde(gkde),
+                        (kdepdf**2).sum()*intervall, decimal=2)
+    assert_almost_equal(gkde.integrate_gaussian(xnmean, xnstd**2),
+                        (kdepdf*normpdf).sum()*intervall, decimal=2)
+
+
+def test_kde_1d_weighted():
+    #some basic tests comparing to normal distribution
+    np.random.seed(8765678)
+    n_basesample = 500
+    xn = np.random.randn(n_basesample)
+    wn = np.random.rand(n_basesample)
+    xnmean = np.average(xn, weights=wn)
+    xnstd = np.sqrt(np.average((xn-xnmean)**2, weights=wn))
+
+    # get kde for original sample
+    gkde = stats.gaussian_kde(xn, weights=wn)
+
+    # evaluate the density function for the kde for some points
+    xs = np.linspace(-7,7,501)
+    kdepdf = gkde.evaluate(xs)
+    normpdf = stats.norm.pdf(xs, loc=xnmean, scale=xnstd)
+    intervall = xs[1] - xs[0]
+
+    assert_(np.sum((kdepdf - normpdf)**2)*intervall < 0.01)
+    prob1 = gkde.integrate_box_1d(xnmean, np.inf)
+    prob2 = gkde.integrate_box_1d(-np.inf, xnmean)
+    assert_almost_equal(prob1, 0.5, decimal=1)
+    assert_almost_equal(prob2, 0.5, decimal=1)
+    assert_almost_equal(gkde.integrate_box(xnmean, np.inf), prob1, decimal=13)
+    assert_almost_equal(gkde.integrate_box(-np.inf, xnmean), prob2, decimal=13)
+
+    assert_almost_equal(gkde.integrate_kde(gkde),
+                        (kdepdf**2).sum()*intervall, decimal=2)
+    assert_almost_equal(gkde.integrate_gaussian(xnmean, xnstd**2),
+                        (kdepdf*normpdf).sum()*intervall, decimal=2)
+
+
+@pytest.mark.xslow
+def test_kde_2d():
+    #some basic tests comparing to normal distribution
+    np.random.seed(8765678)
+    n_basesample = 500
+
+    mean = np.array([1.0, 3.0])
+    covariance = np.array([[1.0, 2.0], [2.0, 6.0]])
+
+    # Need transpose (shape (2, 500)) for kde
+    xn = np.random.multivariate_normal(mean, covariance, size=n_basesample).T
+
+    # get kde for original sample
+    gkde = stats.gaussian_kde(xn)
+
+    # evaluate the density function for the kde for some points
+    x, y = np.mgrid[-7:7:500j, -7:7:500j]
+    grid_coords = np.vstack([x.ravel(), y.ravel()])
+    kdepdf = gkde.evaluate(grid_coords)
+    kdepdf = kdepdf.reshape(500, 500)
+
+    normpdf = stats.multivariate_normal.pdf(np.dstack([x, y]),
+                                            mean=mean, cov=covariance)
+    intervall = y.ravel()[1] - y.ravel()[0]
+
+    assert_(np.sum((kdepdf - normpdf)**2) * (intervall**2) < 0.01)
+
+    small = -1e100
+    large = 1e100
+    prob1 = gkde.integrate_box([small, mean[1]], [large, large])
+    prob2 = gkde.integrate_box([small, small], [large, mean[1]])
+
+    assert_almost_equal(prob1, 0.5, decimal=1)
+    assert_almost_equal(prob2, 0.5, decimal=1)
+    assert_almost_equal(gkde.integrate_kde(gkde),
+                        (kdepdf**2).sum()*(intervall**2), decimal=2)
+    assert_almost_equal(gkde.integrate_gaussian(mean, covariance),
+                        (kdepdf*normpdf).sum()*(intervall**2), decimal=2)
+
+
+@pytest.mark.xslow
+def test_kde_2d_weighted():
+    #some basic tests comparing to normal distribution
+    np.random.seed(8765678)
+    n_basesample = 500
+
+    mean = np.array([1.0, 3.0])
+    covariance = np.array([[1.0, 2.0], [2.0, 6.0]])
+
+    # Need transpose (shape (2, 500)) for kde
+    xn = np.random.multivariate_normal(mean, covariance, size=n_basesample).T
+    wn = np.random.rand(n_basesample)
+
+    # get kde for original sample
+    gkde = stats.gaussian_kde(xn, weights=wn)
+
+    # evaluate the density function for the kde for some points
+    x, y = np.mgrid[-7:7:500j, -7:7:500j]
+    grid_coords = np.vstack([x.ravel(), y.ravel()])
+    kdepdf = gkde.evaluate(grid_coords)
+    kdepdf = kdepdf.reshape(500, 500)
+
+    normpdf = stats.multivariate_normal.pdf(np.dstack([x, y]),
+                                            mean=mean, cov=covariance)
+    intervall = y.ravel()[1] - y.ravel()[0]
+
+    assert_(np.sum((kdepdf - normpdf)**2) * (intervall**2) < 0.01)
+
+    small = -1e100
+    large = 1e100
+    prob1 = gkde.integrate_box([small, mean[1]], [large, large])
+    prob2 = gkde.integrate_box([small, small], [large, mean[1]])
+
+    assert_almost_equal(prob1, 0.5, decimal=1)
+    assert_almost_equal(prob2, 0.5, decimal=1)
+    assert_almost_equal(gkde.integrate_kde(gkde),
+                        (kdepdf**2).sum()*(intervall**2), decimal=2)
+    assert_almost_equal(gkde.integrate_gaussian(mean, covariance),
+                        (kdepdf*normpdf).sum()*(intervall**2), decimal=2)
+
+
+def test_kde_bandwidth_method():
+    def scotts_factor(kde_obj):
+        """Same as default, just check that it works."""
+        return np.power(kde_obj.n, -1./(kde_obj.d+4))
+
+    np.random.seed(8765678)
+    n_basesample = 50
+    xn = np.random.randn(n_basesample)
+
+    # Default
+    gkde = stats.gaussian_kde(xn)
+    # Supply a callable
+    gkde2 = stats.gaussian_kde(xn, bw_method=scotts_factor)
+    # Supply a scalar
+    gkde3 = stats.gaussian_kde(xn, bw_method=gkde.factor)
+
+    xs = np.linspace(-7,7,51)
+    kdepdf = gkde.evaluate(xs)
+    kdepdf2 = gkde2.evaluate(xs)
+    assert_almost_equal(kdepdf, kdepdf2)
+    kdepdf3 = gkde3.evaluate(xs)
+    assert_almost_equal(kdepdf, kdepdf3)
+
+    assert_raises(ValueError, stats.gaussian_kde, xn, bw_method='wrongstring')
+
+
+def test_kde_bandwidth_method_weighted():
+    def scotts_factor(kde_obj):
+        """Same as default, just check that it works."""
+        return np.power(kde_obj.neff, -1./(kde_obj.d+4))
+
+    np.random.seed(8765678)
+    n_basesample = 50
+    xn = np.random.randn(n_basesample)
+
+    # Default
+    gkde = stats.gaussian_kde(xn)
+    # Supply a callable
+    gkde2 = stats.gaussian_kde(xn, bw_method=scotts_factor)
+    # Supply a scalar
+    gkde3 = stats.gaussian_kde(xn, bw_method=gkde.factor)
+
+    xs = np.linspace(-7,7,51)
+    kdepdf = gkde.evaluate(xs)
+    kdepdf2 = gkde2.evaluate(xs)
+    assert_almost_equal(kdepdf, kdepdf2)
+    kdepdf3 = gkde3.evaluate(xs)
+    assert_almost_equal(kdepdf, kdepdf3)
+
+    assert_raises(ValueError, stats.gaussian_kde, xn, bw_method='wrongstring')
+
+
+# Subclasses that should stay working (extracted from various sources).
+# Unfortunately the earlier design of gaussian_kde made it necessary for users
+# to create these kinds of subclasses, or call _compute_covariance() directly.
+
+class _kde_subclass1(stats.gaussian_kde):
+    def __init__(self, dataset):
+        self.dataset = np.atleast_2d(dataset)
+        self.d, self.n = self.dataset.shape
+        self.covariance_factor = self.scotts_factor
+        self._compute_covariance()
+
+
+class _kde_subclass2(stats.gaussian_kde):
+    def __init__(self, dataset):
+        self.covariance_factor = self.scotts_factor
+        super().__init__(dataset)
+
+
+class _kde_subclass4(stats.gaussian_kde):
+    def covariance_factor(self):
+        return 0.5 * self.silverman_factor()
+
+
+def test_gaussian_kde_subclassing():
+    x1 = np.array([-7, -5, 1, 4, 5], dtype=float)
+    xs = np.linspace(-10, 10, num=50)
+
+    # gaussian_kde itself
+    kde = stats.gaussian_kde(x1)
+    ys = kde(xs)
+
+    # subclass 1
+    kde1 = _kde_subclass1(x1)
+    y1 = kde1(xs)
+    assert_array_almost_equal_nulp(ys, y1, nulp=10)
+
+    # subclass 2
+    kde2 = _kde_subclass2(x1)
+    y2 = kde2(xs)
+    assert_array_almost_equal_nulp(ys, y2, nulp=10)
+
+    # subclass 3 was removed because we have no obligation to maintain support
+    # for user invocation of private methods
+
+    # subclass 4
+    kde4 = _kde_subclass4(x1)
+    y4 = kde4(x1)
+    y_expected = [0.06292987, 0.06346938, 0.05860291, 0.08657652, 0.07904017]
+
+    assert_array_almost_equal(y_expected, y4, decimal=6)
+
+    # Not a subclass, but check for use of _compute_covariance()
+    kde5 = kde
+    kde5.covariance_factor = lambda: kde.factor
+    kde5._compute_covariance()
+    y5 = kde5(xs)
+    assert_array_almost_equal_nulp(ys, y5, nulp=10)
+
+
+def test_gaussian_kde_covariance_caching():
+    x1 = np.array([-7, -5, 1, 4, 5], dtype=float)
+    xs = np.linspace(-10, 10, num=5)
+    # These expected values are from scipy 0.10, before some changes to
+    # gaussian_kde.  They were not compared with any external reference.
+    y_expected = [0.02463386, 0.04689208, 0.05395444, 0.05337754, 0.01664475]
+
+    # Set the bandwidth, then reset it to the default.
+    kde = stats.gaussian_kde(x1)
+    kde.set_bandwidth(bw_method=0.5)
+    kde.set_bandwidth(bw_method='scott')
+    y2 = kde(xs)
+
+    assert_array_almost_equal(y_expected, y2, decimal=7)
+
+
+def test_gaussian_kde_monkeypatch():
+    """Ugly, but people may rely on this.  See scipy pull request 123,
+    specifically the linked ML thread "Width of the Gaussian in stats.kde".
+    If it is necessary to break this later on, that is to be discussed on ML.
+    """
+    x1 = np.array([-7, -5, 1, 4, 5], dtype=float)
+    xs = np.linspace(-10, 10, num=50)
+
+    # The old monkeypatched version to get at Silverman's Rule.
+    kde = stats.gaussian_kde(x1)
+    kde.covariance_factor = kde.silverman_factor
+    kde._compute_covariance()
+    y1 = kde(xs)
+
+    # The new saner version.
+    kde2 = stats.gaussian_kde(x1, bw_method='silverman')
+    y2 = kde2(xs)
+
+    assert_array_almost_equal_nulp(y1, y2, nulp=10)
+
+
+def test_kde_integer_input():
+    """Regression test for #1181."""
+    x1 = np.arange(5)
+    kde = stats.gaussian_kde(x1)
+    y_expected = [0.13480721, 0.18222869, 0.19514935, 0.18222869, 0.13480721]
+    assert_array_almost_equal(kde(x1), y_expected, decimal=6)
+
+
+_ftypes = ['float32', 'float64', 'float96', 'float128', 'int32', 'int64']
+
+
+@pytest.mark.parametrize("bw_type", _ftypes + ["scott", "silverman"])
+@pytest.mark.parametrize("dtype", _ftypes)
+def test_kde_output_dtype(dtype, bw_type):
+    # Check whether the datatypes are available
+    dtype = getattr(np, dtype, None)
+
+    if bw_type in ["scott", "silverman"]:
+        bw = bw_type
+    else:
+        bw_type = getattr(np, bw_type, None)
+        bw = bw_type(3) if bw_type else None
+
+    if any(dt is None for dt in [dtype, bw]):
+        pytest.skip()
+
+    weights = np.arange(5, dtype=dtype)
+    dataset = np.arange(5, dtype=dtype)
+    k = stats.gaussian_kde(dataset, bw_method=bw, weights=weights)
+    points = np.arange(5, dtype=dtype)
+    result = k(points)
+    # weights are always cast to float64
+    assert result.dtype == np.result_type(dataset, points, np.float64(weights),
+                                          k.factor)
+
+
+def test_pdf_logpdf_validation():
+    rng = np.random.default_rng(64202298293133848336925499069837723291)
+    xn = rng.standard_normal((2, 10))
+    gkde = stats.gaussian_kde(xn)
+    xs = rng.standard_normal((3, 10))
+
+    msg = "points have dimension 3, dataset has dimension 2"
+    with pytest.raises(ValueError, match=msg):
+        gkde.logpdf(xs)
+
+
+def test_pdf_logpdf():
+    np.random.seed(1)
+    n_basesample = 50
+    xn = np.random.randn(n_basesample)
+
+    # Default
+    gkde = stats.gaussian_kde(xn)
+
+    xs = np.linspace(-15, 12, 25)
+    pdf = gkde.evaluate(xs)
+    pdf2 = gkde.pdf(xs)
+    assert_almost_equal(pdf, pdf2, decimal=12)
+
+    logpdf = np.log(pdf)
+    logpdf2 = gkde.logpdf(xs)
+    assert_almost_equal(logpdf, logpdf2, decimal=12)
+
+    # There are more points than data
+    gkde = stats.gaussian_kde(xs)
+    pdf = np.log(gkde.evaluate(xn))
+    pdf2 = gkde.logpdf(xn)
+    assert_almost_equal(pdf, pdf2, decimal=12)
+
+
+def test_pdf_logpdf_weighted():
+    np.random.seed(1)
+    n_basesample = 50
+    xn = np.random.randn(n_basesample)
+    wn = np.random.rand(n_basesample)
+
+    # Default
+    gkde = stats.gaussian_kde(xn, weights=wn)
+
+    xs = np.linspace(-15, 12, 25)
+    pdf = gkde.evaluate(xs)
+    pdf2 = gkde.pdf(xs)
+    assert_almost_equal(pdf, pdf2, decimal=12)
+
+    logpdf = np.log(pdf)
+    logpdf2 = gkde.logpdf(xs)
+    assert_almost_equal(logpdf, logpdf2, decimal=12)
+
+    # There are more points than data
+    gkde = stats.gaussian_kde(xs, weights=np.random.rand(len(xs)))
+    pdf = np.log(gkde.evaluate(xn))
+    pdf2 = gkde.logpdf(xn)
+    assert_almost_equal(pdf, pdf2, decimal=12)
+
+
+def test_marginal_1_axis():
+    rng = np.random.default_rng(6111799263660870475)
+    n_data = 50
+    n_dim = 10
+    dataset = rng.normal(size=(n_dim, n_data))
+    points = rng.normal(size=(n_dim, 3))
+
+    dimensions = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])  # dimensions to keep
+
+    kde = stats.gaussian_kde(dataset)
+    marginal = kde.marginal(dimensions)
+    pdf = marginal.pdf(points[dimensions])
+
+    def marginal_pdf_single(point):
+        def f(x):
+            x = np.concatenate(([x], point[dimensions]))
+            return kde.pdf(x)[0]
+        return integrate.quad(f, -np.inf, np.inf)[0]
+
+    def marginal_pdf(points):
+        return np.apply_along_axis(marginal_pdf_single, axis=0, arr=points)
+
+    ref = marginal_pdf(points)
+
+    assert_allclose(pdf, ref, rtol=1e-6)
+
+
+@pytest.mark.xslow
+def test_marginal_2_axis():
+    rng = np.random.default_rng(6111799263660870475)
+    n_data = 30
+    n_dim = 4
+    dataset = rng.normal(size=(n_dim, n_data))
+    points = rng.normal(size=(n_dim, 3))
+
+    dimensions = np.array([1, 3])  # dimensions to keep
+
+    kde = stats.gaussian_kde(dataset)
+    marginal = kde.marginal(dimensions)
+    pdf = marginal.pdf(points[dimensions])
+
+    def marginal_pdf(points):
+        def marginal_pdf_single(point):
+            def f(y, x):
+                w, z = point[dimensions]
+                x = np.array([x, w, y, z])
+                return kde.pdf(x)[0]
+            return integrate.dblquad(f, -np.inf, np.inf, -np.inf, np.inf)[0]
+
+        return np.apply_along_axis(marginal_pdf_single, axis=0, arr=points)
+
+    ref = marginal_pdf(points)
+
+    assert_allclose(pdf, ref, rtol=1e-6)
+
+
+def test_marginal_iv():
+    # test input validation
+    rng = np.random.default_rng(6111799263660870475)
+    n_data = 30
+    n_dim = 4
+    dataset = rng.normal(size=(n_dim, n_data))
+    points = rng.normal(size=(n_dim, 3))
+
+    kde = stats.gaussian_kde(dataset)
+
+    # check that positive and negative indices are equivalent
+    dimensions1 = [-1, 1]
+    marginal1 = kde.marginal(dimensions1)
+    pdf1 = marginal1.pdf(points[dimensions1])
+
+    dimensions2 = [3, -3]
+    marginal2 = kde.marginal(dimensions2)
+    pdf2 = marginal2.pdf(points[dimensions2])
+
+    assert_equal(pdf1, pdf2)
+
+    # IV for non-integer dimensions
+    message = "Elements of `dimensions` must be integers..."
+    with pytest.raises(ValueError, match=message):
+        kde.marginal([1, 2.5])
+
+    # IV for uniqueness
+    message = "All elements of `dimensions` must be unique."
+    with pytest.raises(ValueError, match=message):
+        kde.marginal([1, 2, 2])
+
+    # IV for non-integer dimensions
+    message = (r"Dimensions \[-5  6\] are invalid for a distribution in 4...")
+    with pytest.raises(ValueError, match=message):
+        kde.marginal([1, -5, 6])
+
+
+@pytest.mark.xslow
+def test_logpdf_overflow():
+    # regression test for gh-12988; testing against linalg instability for
+    # very high dimensionality kde
+    np.random.seed(1)
+    n_dimensions = 2500
+    n_samples = 5000
+    xn = np.array([np.random.randn(n_samples) + (n) for n in range(
+        0, n_dimensions)])
+
+    # Default
+    gkde = stats.gaussian_kde(xn)
+
+    logpdf = gkde.logpdf(np.arange(0, n_dimensions))
+    np.testing.assert_equal(np.isneginf(logpdf[0]), False)
+    np.testing.assert_equal(np.isnan(logpdf[0]), False)
+
+
+def test_weights_intact():
+    # regression test for gh-9709: weights are not modified
+    np.random.seed(12345)
+    vals = np.random.lognormal(size=100)
+    weights = np.random.choice([1.0, 10.0, 100], size=vals.size)
+    orig_weights = weights.copy()
+
+    stats.gaussian_kde(np.log10(vals), weights=weights)
+    assert_allclose(weights, orig_weights, atol=1e-14, rtol=1e-14)
+
+
+def test_weights_integer():
+    # integer weights are OK, cf gh-9709 (comment)
+    np.random.seed(12345)
+    values = [0.2, 13.5, 21.0, 75.0, 99.0]
+    weights = [1, 2, 4, 8, 16]  # a list of integers
+    pdf_i = stats.gaussian_kde(values, weights=weights)
+    pdf_f = stats.gaussian_kde(values, weights=np.float64(weights))
+
+    xn = [0.3, 11, 88]
+    assert_allclose(pdf_i.evaluate(xn),
+                    pdf_f.evaluate(xn), atol=1e-14, rtol=1e-14)
+
+
+def test_seed():
+    # Test the seed option of the resample method
+    def test_seed_sub(gkde_trail):
+        n_sample = 200
+        # The results should be different without using seed
+        samp1 = gkde_trail.resample(n_sample)
+        samp2 = gkde_trail.resample(n_sample)
+        assert_raises(
+            AssertionError, assert_allclose, samp1, samp2, atol=1e-13
+        )
+        # Use integer seed
+        seed = 831
+        samp1 = gkde_trail.resample(n_sample, seed=seed)
+        samp2 = gkde_trail.resample(n_sample, seed=seed)
+        assert_allclose(samp1, samp2, atol=1e-13)
+        # Use RandomState
+        rstate1 = np.random.RandomState(seed=138)
+        samp1 = gkde_trail.resample(n_sample, seed=rstate1)
+        rstate2 = np.random.RandomState(seed=138)
+        samp2 = gkde_trail.resample(n_sample, seed=rstate2)
+        assert_allclose(samp1, samp2, atol=1e-13)
+
+        # check that np.random.Generator can be used (numpy >= 1.17)
+        if hasattr(np.random, 'default_rng'):
+            # obtain a np.random.Generator object
+            rng = np.random.default_rng(1234)
+            gkde_trail.resample(n_sample, seed=rng)
+
+    np.random.seed(8765678)
+    n_basesample = 500
+    wn = np.random.rand(n_basesample)
+    # Test 1D case
+    xn_1d = np.random.randn(n_basesample)
+
+    gkde_1d = stats.gaussian_kde(xn_1d)
+    test_seed_sub(gkde_1d)
+    gkde_1d_weighted = stats.gaussian_kde(xn_1d, weights=wn)
+    test_seed_sub(gkde_1d_weighted)
+
+    # Test 2D case
+    mean = np.array([1.0, 3.0])
+    covariance = np.array([[1.0, 2.0], [2.0, 6.0]])
+    xn_2d = np.random.multivariate_normal(mean, covariance, size=n_basesample).T
+
+    gkde_2d = stats.gaussian_kde(xn_2d)
+    test_seed_sub(gkde_2d)
+    gkde_2d_weighted = stats.gaussian_kde(xn_2d, weights=wn)
+    test_seed_sub(gkde_2d_weighted)
+
+
+def test_singular_data_covariance_gh10205():
+    # When the data lie in a lower-dimensional subspace and this causes
+    # and exception, check that the error message is informative.
+    rng = np.random.default_rng(2321583144339784787)
+    mu = np.array([1, 10, 20])
+    sigma = np.array([[4, 10, 0], [10, 25, 0], [0, 0, 100]])
+    data = rng.multivariate_normal(mu, sigma, 1000)
+    try:  # doesn't raise any error on some platforms, and that's OK
+        stats.gaussian_kde(data.T)
+    except linalg.LinAlgError:
+        msg = "The data appears to lie in a lower-dimensional subspace..."
+        with assert_raises(linalg.LinAlgError, match=msg):
+            stats.gaussian_kde(data.T)
+
+
+def test_fewer_points_than_dimensions_gh17436():
+    # When the number of points is fewer than the number of dimensions, the
+    # the covariance matrix would be singular, and the exception tested in
+    # test_singular_data_covariance_gh10205 would occur. However, sometimes
+    # this occurs when the user passes in the transpose of what `gaussian_kde`
+    # expects. This can result in a huge covariance matrix, so bail early.
+    rng = np.random.default_rng(2046127537594925772)
+    rvs = rng.multivariate_normal(np.zeros(3), np.eye(3), size=5)
+    message = "Number of dimensions is greater than number of samples..."
+    with pytest.raises(ValueError, match=message):
+        stats.gaussian_kde(rvs)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mgc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mgc.py
new file mode 100644
index 0000000000000000000000000000000000000000..320f0b1edf98123555d26c5b501bd90b31847f2c
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mgc.py
@@ -0,0 +1,217 @@
+import pytest
+from pytest import raises as assert_raises, warns as assert_warns
+
+import numpy as np
+from numpy.testing import assert_approx_equal, assert_allclose, assert_equal
+
+from scipy.spatial.distance import cdist
+from scipy import stats
+
+class TestMGCErrorWarnings:
+    """ Tests errors and warnings derived from MGC.
+    """
+    def test_error_notndarray(self):
+        # raises error if x or y is not a ndarray
+        x = np.arange(20)
+        y = [5] * 20
+        assert_raises(ValueError, stats.multiscale_graphcorr, x, y)
+        assert_raises(ValueError, stats.multiscale_graphcorr, y, x)
+
+    def test_error_shape(self):
+        # raises error if number of samples different (n)
+        x = np.arange(100).reshape(25, 4)
+        y = x.reshape(10, 10)
+        assert_raises(ValueError, stats.multiscale_graphcorr, x, y)
+
+    def test_error_lowsamples(self):
+        # raises error if samples are low (< 3)
+        x = np.arange(3)
+        y = np.arange(3)
+        assert_raises(ValueError, stats.multiscale_graphcorr, x, y)
+
+    def test_error_nans(self):
+        # raises error if inputs contain NaNs
+        x = np.arange(20, dtype=float)
+        x[0] = np.nan
+        assert_raises(ValueError, stats.multiscale_graphcorr, x, x)
+
+        y = np.arange(20)
+        assert_raises(ValueError, stats.multiscale_graphcorr, x, y)
+
+    def test_error_wrongdisttype(self):
+        # raises error if metric is not a function
+        x = np.arange(20)
+        compute_distance = 0
+        assert_raises(ValueError, stats.multiscale_graphcorr, x, x,
+                      compute_distance=compute_distance)
+
+    @pytest.mark.parametrize("reps", [
+        -1,    # reps is negative
+        '1',   # reps is not integer
+    ])
+    def test_error_reps(self, reps):
+        # raises error if reps is negative
+        x = np.arange(20)
+        assert_raises(ValueError, stats.multiscale_graphcorr, x, x, reps=reps)
+
+    def test_warns_reps(self):
+        # raises warning when reps is less than 1000
+        x = np.arange(20)
+        reps = 100
+        assert_warns(RuntimeWarning, stats.multiscale_graphcorr, x, x, reps=reps)
+
+    def test_error_infty(self):
+        # raises error if input contains infinities
+        x = np.arange(20)
+        y = np.ones(20) * np.inf
+        assert_raises(ValueError, stats.multiscale_graphcorr, x, y)
+
+
+class TestMGCStat:
+    """ Test validity of MGC test statistic
+    """
+    def _simulations(self, samps=100, dims=1, sim_type=""):
+        # linear simulation
+        if sim_type == "linear":
+            x = np.random.uniform(-1, 1, size=(samps, 1))
+            y = x + 0.3 * np.random.random_sample(size=(x.size, 1))
+
+        # spiral simulation
+        elif sim_type == "nonlinear":
+            unif = np.array(np.random.uniform(0, 5, size=(samps, 1)))
+            x = unif * np.cos(np.pi * unif)
+            y = (unif * np.sin(np.pi * unif) +
+                 0.4*np.random.random_sample(size=(x.size, 1)))
+
+        # independence (tests type I simulation)
+        elif sim_type == "independence":
+            u = np.random.normal(0, 1, size=(samps, 1))
+            v = np.random.normal(0, 1, size=(samps, 1))
+            u_2 = np.random.binomial(1, p=0.5, size=(samps, 1))
+            v_2 = np.random.binomial(1, p=0.5, size=(samps, 1))
+            x = u/3 + 2*u_2 - 1
+            y = v/3 + 2*v_2 - 1
+
+        # raises error if not approved sim_type
+        else:
+            raise ValueError("sim_type must be linear, nonlinear, or "
+                             "independence")
+
+        # add dimensions of noise for higher dimensions
+        if dims > 1:
+            dims_noise = np.random.normal(0, 1, size=(samps, dims-1))
+            x = np.concatenate((x, dims_noise), axis=1)
+
+        return x, y
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize("sim_type, obs_stat, obs_pvalue", [
+        ("linear", 0.97, 1/1000),           # test linear simulation
+        ("nonlinear", 0.163, 1/1000),       # test spiral simulation
+        ("independence", -0.0094, 0.78)     # test independence simulation
+    ])
+    def test_oned(self, sim_type, obs_stat, obs_pvalue):
+        np.random.seed(12345678)
+
+        # generate x and y
+        x, y = self._simulations(samps=100, dims=1, sim_type=sim_type)
+
+        # test stat and pvalue
+        stat, pvalue, _ = stats.multiscale_graphcorr(x, y)
+        assert_approx_equal(stat, obs_stat, significant=1)
+        assert_approx_equal(pvalue, obs_pvalue, significant=1)
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize("sim_type, obs_stat, obs_pvalue", [
+        ("linear", 0.184, 1/1000),           # test linear simulation
+        ("nonlinear", 0.0190, 0.117),        # test spiral simulation
+    ])
+    def test_fived(self, sim_type, obs_stat, obs_pvalue):
+        np.random.seed(12345678)
+
+        # generate x and y
+        x, y = self._simulations(samps=100, dims=5, sim_type=sim_type)
+
+        # test stat and pvalue
+        stat, pvalue, _ = stats.multiscale_graphcorr(x, y)
+        assert_approx_equal(stat, obs_stat, significant=1)
+        assert_approx_equal(pvalue, obs_pvalue, significant=1)
+
+    @pytest.mark.xslow
+    def test_twosamp(self):
+        np.random.seed(12345678)
+
+        # generate x and y
+        x = np.random.binomial(100, 0.5, size=(100, 5))
+        y = np.random.normal(0, 1, size=(80, 5))
+
+        # test stat and pvalue
+        stat, pvalue, _ = stats.multiscale_graphcorr(x, y)
+        assert_approx_equal(stat, 1.0, significant=1)
+        assert_approx_equal(pvalue, 0.001, significant=1)
+
+        # generate x and y
+        y = np.random.normal(0, 1, size=(100, 5))
+
+        # test stat and pvalue
+        stat, pvalue, _ = stats.multiscale_graphcorr(x, y, is_twosamp=True)
+        assert_approx_equal(stat, 1.0, significant=1)
+        assert_approx_equal(pvalue, 0.001, significant=1)
+
+    @pytest.mark.xslow
+    def test_workers(self):
+        np.random.seed(12345678)
+
+        # generate x and y
+        x, y = self._simulations(samps=100, dims=1, sim_type="linear")
+
+        # test stat and pvalue
+        stat, pvalue, _ = stats.multiscale_graphcorr(x, y, workers=2)
+        assert_approx_equal(stat, 0.97, significant=1)
+        assert_approx_equal(pvalue, 0.001, significant=1)
+
+    @pytest.mark.xslow
+    def test_random_state(self):
+        # generate x and y
+        x, y = self._simulations(samps=100, dims=1, sim_type="linear")
+
+        # test stat and pvalue
+        stat, pvalue, _ = stats.multiscale_graphcorr(x, y, random_state=1)
+        assert_approx_equal(stat, 0.97, significant=1)
+        assert_approx_equal(pvalue, 0.001, significant=1)
+
+    @pytest.mark.xslow
+    def test_dist_perm(self):
+        np.random.seed(12345678)
+        # generate x and y
+        x, y = self._simulations(samps=100, dims=1, sim_type="nonlinear")
+        distx = cdist(x, x, metric="euclidean")
+        disty = cdist(y, y, metric="euclidean")
+
+        stat_dist, pvalue_dist, _ = stats.multiscale_graphcorr(distx, disty,
+                                                               compute_distance=None,
+                                                               random_state=1)
+        assert_approx_equal(stat_dist, 0.163, significant=1)
+        assert_approx_equal(pvalue_dist, 0.001, significant=1)
+
+    @pytest.mark.fail_slow(20)  # all other tests are XSLOW; we need at least one to run
+    @pytest.mark.slow
+    def test_pvalue_literature(self):
+        np.random.seed(12345678)
+
+        # generate x and y
+        x, y = self._simulations(samps=100, dims=1, sim_type="linear")
+
+        # test stat and pvalue
+        _, pvalue, _ = stats.multiscale_graphcorr(x, y, random_state=1)
+        assert_allclose(pvalue, 1/1001)
+
+    @pytest.mark.xslow
+    def test_alias(self):
+        np.random.seed(12345678)
+
+        # generate x and y
+        x, y = self._simulations(samps=100, dims=1, sim_type="linear")
+
+        res = stats.multiscale_graphcorr(x, y, random_state=1)
+        assert_equal(res.stat, res.statistic)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_morestats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_morestats.py
new file mode 100644
index 0000000000000000000000000000000000000000..e596ea8aa3786a87e08d88f740f0a5995ad42026
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_morestats.py
@@ -0,0 +1,3227 @@
+# Author:  Travis Oliphant, 2002
+#
+# Further enhancements and tests added by numerous SciPy developers.
+#
+import math
+import warnings
+import sys
+from functools import partial
+
+import numpy as np
+from numpy.random import RandomState
+from numpy.testing import (assert_array_equal, assert_almost_equal,
+                           assert_array_less, assert_array_almost_equal,
+                           assert_, assert_allclose, assert_equal,
+                           suppress_warnings)
+import pytest
+from pytest import raises as assert_raises
+import re
+from scipy import optimize, stats, special
+from scipy.stats._morestats import _abw_state, _get_As_weibull, _Avals_weibull
+from .common_tests import check_named_results
+from .._hypotests import _get_wilcoxon_distr, _get_wilcoxon_distr2
+from scipy.stats._binomtest import _binary_search_for_binom_tst
+from scipy.stats._distr_params import distcont
+from scipy.stats._axis_nan_policy import (SmallSampleWarning, too_small_nd_omit,
+                                          too_small_1d_omit, too_small_1d_not_omit)
+
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import array_namespace, is_numpy
+from scipy._lib._array_api_no_0d import (
+    xp_assert_close,
+    xp_assert_equal,
+    xp_assert_less,
+)
+
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+distcont = dict(distcont)  # type: ignore
+
+# Matplotlib is not a scipy dependency but is optionally used in probplot, so
+# check if it's available
+try:
+    import matplotlib
+    matplotlib.rcParams['backend'] = 'Agg'
+    import matplotlib.pyplot as plt
+    have_matplotlib = True
+except Exception:
+    have_matplotlib = False
+
+
+# test data gear.dat from NIST for Levene and Bartlett test
+# https://www.itl.nist.gov/div898/handbook/eda/section3/eda3581.htm
+g1 = [1.006, 0.996, 0.998, 1.000, 0.992, 0.993, 1.002, 0.999, 0.994, 1.000]
+g2 = [0.998, 1.006, 1.000, 1.002, 0.997, 0.998, 0.996, 1.000, 1.006, 0.988]
+g3 = [0.991, 0.987, 0.997, 0.999, 0.995, 0.994, 1.000, 0.999, 0.996, 0.996]
+g4 = [1.005, 1.002, 0.994, 1.000, 0.995, 0.994, 0.998, 0.996, 1.002, 0.996]
+g5 = [0.998, 0.998, 0.982, 0.990, 1.002, 0.984, 0.996, 0.993, 0.980, 0.996]
+g6 = [1.009, 1.013, 1.009, 0.997, 0.988, 1.002, 0.995, 0.998, 0.981, 0.996]
+g7 = [0.990, 1.004, 0.996, 1.001, 0.998, 1.000, 1.018, 1.010, 0.996, 1.002]
+g8 = [0.998, 1.000, 1.006, 1.000, 1.002, 0.996, 0.998, 0.996, 1.002, 1.006]
+g9 = [1.002, 0.998, 0.996, 0.995, 0.996, 1.004, 1.004, 0.998, 0.999, 0.991]
+g10 = [0.991, 0.995, 0.984, 0.994, 0.997, 0.997, 0.991, 0.998, 1.004, 0.997]
+
+
+# The loggamma RVS stream is changing due to gh-13349; this version
+# preserves the old stream so that tests don't change.
+def _old_loggamma_rvs(*args, **kwargs):
+    return np.log(stats.gamma.rvs(*args, **kwargs))
+
+
+class TestBayes_mvs:
+    def test_basic(self):
+        # Expected values in this test simply taken from the function.  For
+        # some checks regarding correctness of implementation, see review in
+        # gh-674
+        data = [6, 9, 12, 7, 8, 8, 13]
+        mean, var, std = stats.bayes_mvs(data)
+        assert_almost_equal(mean.statistic, 9.0)
+        assert_allclose(mean.minmax, (7.103650222492964, 10.896349777507034),
+                        rtol=1e-6)
+
+        assert_almost_equal(var.statistic, 10.0)
+        assert_allclose(var.minmax, (3.1767242068607087, 24.45910381334018),
+                        rtol=1e-09)
+
+        assert_almost_equal(std.statistic, 2.9724954732045084, decimal=14)
+        assert_allclose(std.minmax, (1.7823367265645145, 4.9456146050146312),
+                        rtol=1e-14)
+
+    def test_empty_input(self):
+        assert_raises(ValueError, stats.bayes_mvs, [])
+
+    def test_result_attributes(self):
+        x = np.arange(15)
+        attributes = ('statistic', 'minmax')
+        res = stats.bayes_mvs(x)
+
+        for i in res:
+            check_named_results(i, attributes)
+
+
+class TestMvsdist:
+    def test_basic(self):
+        data = [6, 9, 12, 7, 8, 8, 13]
+        mean, var, std = stats.mvsdist(data)
+        assert_almost_equal(mean.mean(), 9.0)
+        assert_allclose(mean.interval(0.9), (7.103650222492964,
+                                             10.896349777507034), rtol=1e-14)
+
+        assert_almost_equal(var.mean(), 10.0)
+        assert_allclose(var.interval(0.9), (3.1767242068607087,
+                                            24.45910381334018), rtol=1e-09)
+
+        assert_almost_equal(std.mean(), 2.9724954732045084, decimal=14)
+        assert_allclose(std.interval(0.9), (1.7823367265645145,
+                                            4.9456146050146312), rtol=1e-14)
+
+    def test_empty_input(self):
+        assert_raises(ValueError, stats.mvsdist, [])
+
+    def test_bad_arg(self):
+        # Raise ValueError if fewer than two data points are given.
+        data = [1]
+        assert_raises(ValueError, stats.mvsdist, data)
+
+    def test_warns(self):
+        # regression test for gh-5270
+        # make sure there are no spurious divide-by-zero warnings
+        with warnings.catch_warnings():
+            warnings.simplefilter('error', RuntimeWarning)
+            [x.mean() for x in stats.mvsdist([1, 2, 3])]
+            [x.mean() for x in stats.mvsdist([1, 2, 3, 4, 5])]
+
+
+class TestShapiro:
+    def test_basic(self):
+        x1 = [0.11, 7.87, 4.61, 10.14, 7.95, 3.14, 0.46,
+              4.43, 0.21, 4.75, 0.71, 1.52, 3.24,
+              0.93, 0.42, 4.97, 9.53, 4.55, 0.47, 6.66]
+        w, pw = stats.shapiro(x1)
+        shapiro_test = stats.shapiro(x1)
+        assert_almost_equal(w, 0.90047299861907959, decimal=6)
+        assert_almost_equal(shapiro_test.statistic, 0.90047299861907959, decimal=6)
+        assert_almost_equal(pw, 0.042089745402336121, decimal=6)
+        assert_almost_equal(shapiro_test.pvalue, 0.042089745402336121, decimal=6)
+
+        x2 = [1.36, 1.14, 2.92, 2.55, 1.46, 1.06, 5.27, -1.11,
+              3.48, 1.10, 0.88, -0.51, 1.46, 0.52, 6.20, 1.69,
+              0.08, 3.67, 2.81, 3.49]
+        w, pw = stats.shapiro(x2)
+        shapiro_test = stats.shapiro(x2)
+        assert_almost_equal(w, 0.9590270, decimal=6)
+        assert_almost_equal(shapiro_test.statistic, 0.9590270, decimal=6)
+        assert_almost_equal(pw, 0.52460, decimal=3)
+        assert_almost_equal(shapiro_test.pvalue, 0.52460, decimal=3)
+
+        # Verified against R
+        x3 = stats.norm.rvs(loc=5, scale=3, size=100, random_state=12345678)
+        w, pw = stats.shapiro(x3)
+        shapiro_test = stats.shapiro(x3)
+        assert_almost_equal(w, 0.9772805571556091, decimal=6)
+        assert_almost_equal(shapiro_test.statistic, 0.9772805571556091, decimal=6)
+        assert_almost_equal(pw, 0.08144091814756393, decimal=3)
+        assert_almost_equal(shapiro_test.pvalue, 0.08144091814756393, decimal=3)
+
+        # Extracted from original paper
+        x4 = [0.139, 0.157, 0.175, 0.256, 0.344, 0.413, 0.503, 0.577, 0.614,
+              0.655, 0.954, 1.392, 1.557, 1.648, 1.690, 1.994, 2.174, 2.206,
+              3.245, 3.510, 3.571, 4.354, 4.980, 6.084, 8.351]
+        W_expected = 0.83467
+        p_expected = 0.000914
+        w, pw = stats.shapiro(x4)
+        shapiro_test = stats.shapiro(x4)
+        assert_almost_equal(w, W_expected, decimal=4)
+        assert_almost_equal(shapiro_test.statistic, W_expected, decimal=4)
+        assert_almost_equal(pw, p_expected, decimal=5)
+        assert_almost_equal(shapiro_test.pvalue, p_expected, decimal=5)
+
+    def test_2d(self):
+        x1 = [[0.11, 7.87, 4.61, 10.14, 7.95, 3.14, 0.46,
+              4.43, 0.21, 4.75], [0.71, 1.52, 3.24,
+              0.93, 0.42, 4.97, 9.53, 4.55, 0.47, 6.66]]
+        w, pw = stats.shapiro(x1)
+        shapiro_test = stats.shapiro(x1)
+        assert_almost_equal(w, 0.90047299861907959, decimal=6)
+        assert_almost_equal(shapiro_test.statistic, 0.90047299861907959, decimal=6)
+        assert_almost_equal(pw, 0.042089745402336121, decimal=6)
+        assert_almost_equal(shapiro_test.pvalue, 0.042089745402336121, decimal=6)
+
+        x2 = [[1.36, 1.14, 2.92, 2.55, 1.46, 1.06, 5.27, -1.11,
+              3.48, 1.10], [0.88, -0.51, 1.46, 0.52, 6.20, 1.69,
+              0.08, 3.67, 2.81, 3.49]]
+        w, pw = stats.shapiro(x2)
+        shapiro_test = stats.shapiro(x2)
+        assert_almost_equal(w, 0.9590270, decimal=6)
+        assert_almost_equal(shapiro_test.statistic, 0.9590270, decimal=6)
+        assert_almost_equal(pw, 0.52460, decimal=3)
+        assert_almost_equal(shapiro_test.pvalue, 0.52460, decimal=3)
+
+    @pytest.mark.parametrize('x', ([], [1], [1, 2]))
+    def test_not_enough_values(self, x):
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = stats.shapiro(x)
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+    def test_nan_input(self):
+        x = np.arange(10.)
+        x[9] = np.nan
+
+        w, pw = stats.shapiro(x)
+        shapiro_test = stats.shapiro(x)
+        assert_equal(w, np.nan)
+        assert_equal(shapiro_test.statistic, np.nan)
+        # Originally, shapiro returned a p-value of 1 in this case,
+        # but there is no way to produce a numerical p-value if the
+        # statistic is not a number. NaN is more appropriate.
+        assert_almost_equal(pw, np.nan)
+        assert_almost_equal(shapiro_test.pvalue, np.nan)
+
+    def test_gh14462(self):
+        # shapiro is theoretically location-invariant, but when the magnitude
+        # of the values is much greater than the variance, there can be
+        # numerical issues. Fixed by subtracting median from the data.
+        # See gh-14462.
+
+        trans_val, maxlog = stats.boxcox([122500, 474400, 110400])
+        res = stats.shapiro(trans_val)
+
+        # Reference from R:
+        # options(digits=16)
+        # x = c(0.00000000e+00, 3.39996924e-08, -6.35166875e-09)
+        # shapiro.test(x)
+        ref = (0.86468431705371, 0.2805581751566)
+
+        assert_allclose(res, ref, rtol=1e-5)
+
+    def test_length_3_gh18322(self):
+        # gh-18322 reported that the p-value could be negative for input of
+        # length 3. Check that this is resolved.
+        res = stats.shapiro([0.6931471805599453, 0.0, 0.0])
+        assert res.pvalue >= 0
+
+        # R `shapiro.test` doesn't produce an accurate p-value in the case
+        # above. Check that the formula used in `stats.shapiro` is not wrong.
+        # options(digits=16)
+        # x = c(-0.7746653110021126, -0.4344432067942129, 1.8157053280290931)
+        # shapiro.test(x)
+        x = [-0.7746653110021126, -0.4344432067942129, 1.8157053280290931]
+        res = stats.shapiro(x)
+        assert_allclose(res.statistic, 0.84658770645509)
+        assert_allclose(res.pvalue, 0.2313666489882, rtol=1e-6)
+
+
+class TestAnderson:
+    def test_normal(self):
+        rs = RandomState(1234567890)
+        x1 = rs.standard_exponential(size=50)
+        x2 = rs.standard_normal(size=50)
+        A, crit, sig = stats.anderson(x1)
+        assert_array_less(crit[:-1], A)
+        A, crit, sig = stats.anderson(x2)
+        assert_array_less(A, crit[-2:])
+
+        v = np.ones(10)
+        v[0] = 0
+        A, crit, sig = stats.anderson(v)
+        # The expected statistic 3.208057 was computed independently of scipy.
+        # For example, in R:
+        #   > library(nortest)
+        #   > v <- rep(1, 10)
+        #   > v[1] <- 0
+        #   > result <- ad.test(v)
+        #   > result$statistic
+        #          A
+        #   3.208057
+        assert_allclose(A, 3.208057)
+
+    def test_expon(self):
+        rs = RandomState(1234567890)
+        x1 = rs.standard_exponential(size=50)
+        x2 = rs.standard_normal(size=50)
+        A, crit, sig = stats.anderson(x1, 'expon')
+        assert_array_less(A, crit[-2:])
+        with np.errstate(all='ignore'):
+            A, crit, sig = stats.anderson(x2, 'expon')
+        assert_(A > crit[-1])
+
+    def test_gumbel(self):
+        # Regression test for gh-6306.  Before that issue was fixed,
+        # this case would return a2=inf.
+        v = np.ones(100)
+        v[0] = 0.0
+        a2, crit, sig = stats.anderson(v, 'gumbel')
+        # A brief reimplementation of the calculation of the statistic.
+        n = len(v)
+        xbar, s = stats.gumbel_l.fit(v)
+        logcdf = stats.gumbel_l.logcdf(v, xbar, s)
+        logsf = stats.gumbel_l.logsf(v, xbar, s)
+        i = np.arange(1, n+1)
+        expected_a2 = -n - np.mean((2*i - 1) * (logcdf + logsf[::-1]))
+
+        assert_allclose(a2, expected_a2)
+
+    def test_bad_arg(self):
+        assert_raises(ValueError, stats.anderson, [1], dist='plate_of_shrimp')
+
+    def test_result_attributes(self):
+        rs = RandomState(1234567890)
+        x = rs.standard_exponential(size=50)
+        res = stats.anderson(x)
+        attributes = ('statistic', 'critical_values', 'significance_level')
+        check_named_results(res, attributes)
+
+    def test_gumbel_l(self):
+        # gh-2592, gh-6337
+        # Adds support to 'gumbel_r' and 'gumbel_l' as valid inputs for dist.
+        rs = RandomState(1234567890)
+        x = rs.gumbel(size=100)
+        A1, crit1, sig1 = stats.anderson(x, 'gumbel')
+        A2, crit2, sig2 = stats.anderson(x, 'gumbel_l')
+
+        assert_allclose(A2, A1)
+
+    def test_gumbel_r(self):
+        # gh-2592, gh-6337
+        # Adds support to 'gumbel_r' and 'gumbel_l' as valid inputs for dist.
+        rs = RandomState(1234567890)
+        x1 = rs.gumbel(size=100)
+        x2 = np.ones(100)
+        # A constant array is a degenerate case and breaks gumbel_r.fit, so
+        # change one value in x2.
+        x2[0] = 0.996
+        A1, crit1, sig1 = stats.anderson(x1, 'gumbel_r')
+        A2, crit2, sig2 = stats.anderson(x2, 'gumbel_r')
+
+        assert_array_less(A1, crit1[-2:])
+        assert_(A2 > crit2[-1])
+
+    def test_weibull_min_case_A(self):
+        # data and reference values from `anderson` reference [7]
+        x = np.array([225, 171, 198, 189, 189, 135, 162, 135, 117, 162])
+        res = stats.anderson(x, 'weibull_min')
+        m, loc, scale = res.fit_result.params
+        assert_allclose((m, loc, scale), (2.38, 99.02, 78.23), rtol=2e-3)
+        assert_allclose(res.statistic, 0.260, rtol=1e-3)
+        assert res.statistic < res.critical_values[0]
+
+        c = 1 / m  # ~0.42
+        assert_allclose(c, 1/2.38, rtol=2e-3)
+        # interpolate between rows for c=0.4 and c=0.45, indices -3 and -2
+        As40 = _Avals_weibull[-3]
+        As45 = _Avals_weibull[-2]
+        As_ref = As40 + (c - 0.4)/(0.45 - 0.4) * (As45 - As40)
+        # atol=1e-3 because results are rounded up to the next third decimal
+        assert np.all(res.critical_values > As_ref)
+        assert_allclose(res.critical_values, As_ref, atol=1e-3)
+
+    def test_weibull_min_case_B(self):
+        # From `anderson` reference [7]
+        x = np.array([74, 57, 48, 29, 502, 12, 70, 21,
+                      29, 386, 59, 27, 153, 26, 326])
+        message = "Maximum likelihood estimation has converged to "
+        with pytest.raises(ValueError, match=message):
+            stats.anderson(x, 'weibull_min')
+
+    def test_weibull_warning_error(self):
+        # Check for warning message when there are too few observations
+        # This is also an example in which an error occurs during fitting
+        x = -np.array([225, 75, 57, 168, 107, 12, 61, 43, 29])
+        wmessage = "Critical values of the test statistic are given for the..."
+        emessage = "An error occurred while fitting the Weibull distribution..."
+        wcontext = pytest.warns(UserWarning, match=wmessage)
+        econtext = pytest.raises(ValueError, match=emessage)
+        with wcontext, econtext:
+            stats.anderson(x, 'weibull_min')
+
+    @pytest.mark.parametrize('distname',
+                             ['norm', 'expon', 'gumbel_l', 'extreme1',
+                              'gumbel', 'gumbel_r', 'logistic', 'weibull_min'])
+    def test_anderson_fit_params(self, distname):
+        # check that anderson now returns a FitResult
+        rng = np.random.default_rng(330691555377792039)
+        real_distname = ('gumbel_l' if distname in {'extreme1', 'gumbel'}
+                         else distname)
+        dist = getattr(stats, real_distname)
+        params = distcont[real_distname]
+        x = dist.rvs(*params, size=1000, random_state=rng)
+        res = stats.anderson(x, distname)
+        assert res.fit_result.success
+
+    def test_anderson_weibull_As(self):
+        m = 1  # "when mi < 2, so that c > 0.5, the last line...should be used"
+        assert_equal(_get_As_weibull(1/m), _Avals_weibull[-1])
+        m = np.inf
+        assert_equal(_get_As_weibull(1/m), _Avals_weibull[0])
+
+
+class TestAndersonKSamp:
+    def test_example1a(self):
+        # Example data from Scholz & Stephens (1987), originally
+        # published in Lehmann (1995, Nonparametrics, Statistical
+        # Methods Based on Ranks, p. 309)
+        # Pass a mixture of lists and arrays
+        t1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0]
+        t2 = np.array([39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8])
+        t3 = np.array([34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0])
+        t4 = np.array([34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8])
+
+        Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4), midrank=False)
+
+        assert_almost_equal(Tk, 4.449, 3)
+        assert_array_almost_equal([0.4985, 1.3237, 1.9158, 2.4930, 3.2459],
+                                  tm[0:5], 4)
+        assert_allclose(p, 0.0021, atol=0.00025)
+
+    def test_example1b(self):
+        # Example data from Scholz & Stephens (1987), originally
+        # published in Lehmann (1995, Nonparametrics, Statistical
+        # Methods Based on Ranks, p. 309)
+        # Pass arrays
+        t1 = np.array([38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0])
+        t2 = np.array([39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8])
+        t3 = np.array([34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0])
+        t4 = np.array([34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8])
+        Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4), midrank=True)
+
+        assert_almost_equal(Tk, 4.480, 3)
+        assert_array_almost_equal([0.4985, 1.3237, 1.9158, 2.4930, 3.2459],
+                                  tm[0:5], 4)
+        assert_allclose(p, 0.0020, atol=0.00025)
+
+    @pytest.mark.xslow
+    def test_example2a(self):
+        # Example data taken from an earlier technical report of
+        # Scholz and Stephens
+        # Pass lists instead of arrays
+        t1 = [194, 15, 41, 29, 33, 181]
+        t2 = [413, 14, 58, 37, 100, 65, 9, 169, 447, 184, 36, 201, 118]
+        t3 = [34, 31, 18, 18, 67, 57, 62, 7, 22, 34]
+        t4 = [90, 10, 60, 186, 61, 49, 14, 24, 56, 20, 79, 84, 44, 59, 29,
+              118, 25, 156, 310, 76, 26, 44, 23, 62]
+        t5 = [130, 208, 70, 101, 208]
+        t6 = [74, 57, 48, 29, 502, 12, 70, 21, 29, 386, 59, 27]
+        t7 = [55, 320, 56, 104, 220, 239, 47, 246, 176, 182, 33]
+        t8 = [23, 261, 87, 7, 120, 14, 62, 47, 225, 71, 246, 21, 42, 20, 5,
+              12, 120, 11, 3, 14, 71, 11, 14, 11, 16, 90, 1, 16, 52, 95]
+        t9 = [97, 51, 11, 4, 141, 18, 142, 68, 77, 80, 1, 16, 106, 206, 82,
+              54, 31, 216, 46, 111, 39, 63, 18, 191, 18, 163, 24]
+        t10 = [50, 44, 102, 72, 22, 39, 3, 15, 197, 188, 79, 88, 46, 5, 5, 36,
+               22, 139, 210, 97, 30, 23, 13, 14]
+        t11 = [359, 9, 12, 270, 603, 3, 104, 2, 438]
+        t12 = [50, 254, 5, 283, 35, 12]
+        t13 = [487, 18, 100, 7, 98, 5, 85, 91, 43, 230, 3, 130]
+        t14 = [102, 209, 14, 57, 54, 32, 67, 59, 134, 152, 27, 14, 230, 66,
+               61, 34]
+
+        samples = (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14)
+        Tk, tm, p = stats.anderson_ksamp(samples, midrank=False)
+        assert_almost_equal(Tk, 3.288, 3)
+        assert_array_almost_equal([0.5990, 1.3269, 1.8052, 2.2486, 2.8009],
+                                  tm[0:5], 4)
+        assert_allclose(p, 0.0041, atol=0.00025)
+
+        rng = np.random.default_rng(6989860141921615054)
+        method = stats.PermutationMethod(n_resamples=9999, rng=rng)
+        res = stats.anderson_ksamp(samples, midrank=False, method=method)
+        assert_array_equal(res.statistic, Tk)
+        assert_array_equal(res.critical_values, tm)
+        assert_allclose(res.pvalue, p, atol=6e-4)
+
+    def test_example2b(self):
+        # Example data taken from an earlier technical report of
+        # Scholz and Stephens
+        t1 = [194, 15, 41, 29, 33, 181]
+        t2 = [413, 14, 58, 37, 100, 65, 9, 169, 447, 184, 36, 201, 118]
+        t3 = [34, 31, 18, 18, 67, 57, 62, 7, 22, 34]
+        t4 = [90, 10, 60, 186, 61, 49, 14, 24, 56, 20, 79, 84, 44, 59, 29,
+              118, 25, 156, 310, 76, 26, 44, 23, 62]
+        t5 = [130, 208, 70, 101, 208]
+        t6 = [74, 57, 48, 29, 502, 12, 70, 21, 29, 386, 59, 27]
+        t7 = [55, 320, 56, 104, 220, 239, 47, 246, 176, 182, 33]
+        t8 = [23, 261, 87, 7, 120, 14, 62, 47, 225, 71, 246, 21, 42, 20, 5,
+              12, 120, 11, 3, 14, 71, 11, 14, 11, 16, 90, 1, 16, 52, 95]
+        t9 = [97, 51, 11, 4, 141, 18, 142, 68, 77, 80, 1, 16, 106, 206, 82,
+              54, 31, 216, 46, 111, 39, 63, 18, 191, 18, 163, 24]
+        t10 = [50, 44, 102, 72, 22, 39, 3, 15, 197, 188, 79, 88, 46, 5, 5, 36,
+               22, 139, 210, 97, 30, 23, 13, 14]
+        t11 = [359, 9, 12, 270, 603, 3, 104, 2, 438]
+        t12 = [50, 254, 5, 283, 35, 12]
+        t13 = [487, 18, 100, 7, 98, 5, 85, 91, 43, 230, 3, 130]
+        t14 = [102, 209, 14, 57, 54, 32, 67, 59, 134, 152, 27, 14, 230, 66,
+               61, 34]
+
+        Tk, tm, p = stats.anderson_ksamp((t1, t2, t3, t4, t5, t6, t7, t8,
+                                          t9, t10, t11, t12, t13, t14),
+                                         midrank=True)
+
+        assert_almost_equal(Tk, 3.294, 3)
+        assert_array_almost_equal([0.5990, 1.3269, 1.8052, 2.2486, 2.8009],
+                                  tm[0:5], 4)
+        assert_allclose(p, 0.0041, atol=0.00025)
+
+    def test_R_kSamples(self):
+        # test values generates with R package kSamples
+        # package version 1.2-6 (2017-06-14)
+        # r1 = 1:100
+        # continuous case (no ties) --> version  1
+        # res <- kSamples::ad.test(r1, r1 + 40.5)
+        # res$ad[1, "T.AD"] #  41.105
+        # res$ad[1, " asympt. P-value"] #  5.8399e-18
+        #
+        # discrete case (ties allowed) --> version  2 (here: midrank=True)
+        # res$ad[2, "T.AD"] #  41.235
+        #
+        # res <- kSamples::ad.test(r1, r1 + .5)
+        # res$ad[1, "T.AD"] #  -1.2824
+        # res$ad[1, " asympt. P-value"] #  1
+        # res$ad[2, "T.AD"] #  -1.2944
+        #
+        # res <- kSamples::ad.test(r1, r1 + 7.5)
+        # res$ad[1, "T.AD"] # 1.4923
+        # res$ad[1, " asympt. P-value"] # 0.077501
+        #
+        # res <- kSamples::ad.test(r1, r1 + 6)
+        # res$ad[2, "T.AD"] # 0.63892
+        # res$ad[2, " asympt. P-value"] # 0.17981
+        #
+        # res <- kSamples::ad.test(r1, r1 + 11.5)
+        # res$ad[1, "T.AD"] # 4.5042
+        # res$ad[1, " asympt. P-value"] # 0.00545
+        #
+        # res <- kSamples::ad.test(r1, r1 + 13.5)
+        # res$ad[1, "T.AD"] # 6.2982
+        # res$ad[1, " asympt. P-value"] # 0.00118
+
+        x1 = np.linspace(1, 100, 100)
+        # test case: different distributions;p-value floored at 0.001
+        # test case for issue #5493 / #8536
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning, message='p-value floored')
+            s, _, p = stats.anderson_ksamp([x1, x1 + 40.5], midrank=False)
+        assert_almost_equal(s, 41.105, 3)
+        assert_equal(p, 0.001)
+
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning, message='p-value floored')
+            s, _, p = stats.anderson_ksamp([x1, x1 + 40.5])
+        assert_almost_equal(s, 41.235, 3)
+        assert_equal(p, 0.001)
+
+        # test case: similar distributions --> p-value capped at 0.25
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning, message='p-value capped')
+            s, _, p = stats.anderson_ksamp([x1, x1 + .5], midrank=False)
+        assert_almost_equal(s, -1.2824, 4)
+        assert_equal(p, 0.25)
+
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning, message='p-value capped')
+            s, _, p = stats.anderson_ksamp([x1, x1 + .5])
+        assert_almost_equal(s, -1.2944, 4)
+        assert_equal(p, 0.25)
+
+        # test case: check interpolated p-value in [0.01, 0.25] (no ties)
+        s, _, p = stats.anderson_ksamp([x1, x1 + 7.5], midrank=False)
+        assert_almost_equal(s, 1.4923, 4)
+        assert_allclose(p, 0.0775, atol=0.005, rtol=0)
+
+        # test case: check interpolated p-value in [0.01, 0.25] (w/ ties)
+        s, _, p = stats.anderson_ksamp([x1, x1 + 6])
+        assert_almost_equal(s, 0.6389, 4)
+        assert_allclose(p, 0.1798, atol=0.005, rtol=0)
+
+        # test extended critical values for p=0.001 and p=0.005
+        s, _, p = stats.anderson_ksamp([x1, x1 + 11.5], midrank=False)
+        assert_almost_equal(s, 4.5042, 4)
+        assert_allclose(p, 0.00545, atol=0.0005, rtol=0)
+
+        s, _, p = stats.anderson_ksamp([x1, x1 + 13.5], midrank=False)
+        assert_almost_equal(s, 6.2982, 4)
+        assert_allclose(p, 0.00118, atol=0.0001, rtol=0)
+
+    def test_not_enough_samples(self):
+        assert_raises(ValueError, stats.anderson_ksamp, np.ones(5))
+
+    def test_no_distinct_observations(self):
+        assert_raises(ValueError, stats.anderson_ksamp,
+                      (np.ones(5), np.ones(5)))
+
+    def test_empty_sample(self):
+        assert_raises(ValueError, stats.anderson_ksamp, (np.ones(5), []))
+
+    def test_result_attributes(self):
+        # Pass a mixture of lists and arrays
+        t1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0]
+        t2 = np.array([39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8])
+        res = stats.anderson_ksamp((t1, t2), midrank=False)
+
+        attributes = ('statistic', 'critical_values', 'significance_level')
+        check_named_results(res, attributes)
+
+        assert_equal(res.significance_level, res.pvalue)
+
+
+class TestAnsari:
+
+    def test_small(self):
+        x = [1, 2, 3, 3, 4]
+        y = [3, 2, 6, 1, 6, 1, 4, 1]
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning, "Ties preclude use of exact statistic.")
+            W, pval = stats.ansari(x, y)
+        assert_almost_equal(W, 23.5, 11)
+        assert_almost_equal(pval, 0.13499256881897437, 11)
+
+    def test_approx(self):
+        ramsay = np.array((111, 107, 100, 99, 102, 106, 109, 108, 104, 99,
+                           101, 96, 97, 102, 107, 113, 116, 113, 110, 98))
+        parekh = np.array((107, 108, 106, 98, 105, 103, 110, 105, 104,
+                           100, 96, 108, 103, 104, 114, 114, 113, 108,
+                           106, 99))
+
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning, "Ties preclude use of exact statistic.")
+            W, pval = stats.ansari(ramsay, parekh)
+
+        assert_almost_equal(W, 185.5, 11)
+        assert_almost_equal(pval, 0.18145819972867083, 11)
+
+    def test_exact(self):
+        W, pval = stats.ansari([1, 2, 3, 4], [15, 5, 20, 8, 10, 12])
+        assert_almost_equal(W, 10.0, 11)
+        assert_almost_equal(pval, 0.533333333333333333, 7)
+
+    @pytest.mark.parametrize('args', [([], [1]), ([1], [])])
+    def test_bad_arg(self, args):
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = stats.ansari(*args)
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+    def test_result_attributes(self):
+        x = [1, 2, 3, 3, 4]
+        y = [3, 2, 6, 1, 6, 1, 4, 1]
+        with suppress_warnings() as sup:
+            sup.filter(UserWarning, "Ties preclude use of exact statistic.")
+            res = stats.ansari(x, y)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes)
+
+    def test_bad_alternative(self):
+        # invalid value for alternative must raise a ValueError
+        x1 = [1, 2, 3, 4]
+        x2 = [5, 6, 7, 8]
+        match = "'alternative' must be 'two-sided'"
+        with assert_raises(ValueError, match=match):
+            stats.ansari(x1, x2, alternative='foo')
+
+    def test_alternative_exact(self):
+        x1 = [-5, 1, 5, 10, 15, 20, 25]  # high scale, loc=10
+        x2 = [7.5, 8.5, 9.5, 10.5, 11.5, 12.5]  # low scale, loc=10
+        # ratio of scales is greater than 1. So, the
+        # p-value must be high when `alternative='less'`
+        # and low when `alternative='greater'`.
+        statistic, pval = stats.ansari(x1, x2)
+        pval_l = stats.ansari(x1, x2, alternative='less').pvalue
+        pval_g = stats.ansari(x1, x2, alternative='greater').pvalue
+        assert pval_l > 0.95
+        assert pval_g < 0.05  # level of significance.
+        # also check if the p-values sum up to 1 plus the probability
+        # mass under the calculated statistic.
+        prob = _abw_state.a.pmf(statistic, len(x1), len(x2))
+        assert_allclose(pval_g + pval_l, 1 + prob, atol=1e-12)
+        # also check if one of the one-sided p-value equals half the
+        # two-sided p-value and the other one-sided p-value is its
+        # compliment.
+        assert_allclose(pval_g, pval/2, atol=1e-12)
+        assert_allclose(pval_l, 1+prob-pval/2, atol=1e-12)
+        # sanity check. The result should flip if
+        # we exchange x and y.
+        pval_l_reverse = stats.ansari(x2, x1, alternative='less').pvalue
+        pval_g_reverse = stats.ansari(x2, x1, alternative='greater').pvalue
+        assert pval_l_reverse < 0.05
+        assert pval_g_reverse > 0.95
+
+    @pytest.mark.parametrize(
+        'x, y, alternative, expected',
+        # the tests are designed in such a way that the
+        # if else statement in ansari test for exact
+        # mode is covered.
+        [([1, 2, 3, 4], [5, 6, 7, 8], 'less', 0.6285714285714),
+         ([1, 2, 3, 4], [5, 6, 7, 8], 'greater', 0.6285714285714),
+         ([1, 2, 3], [4, 5, 6, 7, 8], 'less', 0.8928571428571),
+         ([1, 2, 3], [4, 5, 6, 7, 8], 'greater', 0.2857142857143),
+         ([1, 2, 3, 4, 5], [6, 7, 8], 'less', 0.2857142857143),
+         ([1, 2, 3, 4, 5], [6, 7, 8], 'greater', 0.8928571428571)]
+    )
+    def test_alternative_exact_with_R(self, x, y, alternative, expected):
+        # testing with R on arbitrary data
+        # Sample R code used for the third test case above:
+        # ```R
+        # > options(digits=16)
+        # > x <- c(1,2,3)
+        # > y <- c(4,5,6,7,8)
+        # > ansari.test(x, y, alternative='less', exact=TRUE)
+        #
+        #     Ansari-Bradley test
+        #
+        # data:  x and y
+        # AB = 6, p-value = 0.8928571428571
+        # alternative hypothesis: true ratio of scales is less than 1
+        #
+        # ```
+        pval = stats.ansari(x, y, alternative=alternative).pvalue
+        assert_allclose(pval, expected, atol=1e-12)
+
+    def test_alternative_approx(self):
+        # intuitive tests for approximation
+        x1 = stats.norm.rvs(0, 5, size=100, random_state=123)
+        x2 = stats.norm.rvs(0, 2, size=100, random_state=123)
+        # for m > 55 or n > 55, the test should automatically
+        # switch to approximation.
+        pval_l = stats.ansari(x1, x2, alternative='less').pvalue
+        pval_g = stats.ansari(x1, x2, alternative='greater').pvalue
+        assert_allclose(pval_l, 1.0, atol=1e-12)
+        assert_allclose(pval_g, 0.0, atol=1e-12)
+        # also check if one of the one-sided p-value equals half the
+        # two-sided p-value and the other one-sided p-value is its
+        # compliment.
+        x1 = stats.norm.rvs(0, 2, size=60, random_state=123)
+        x2 = stats.norm.rvs(0, 1.5, size=60, random_state=123)
+        pval = stats.ansari(x1, x2).pvalue
+        pval_l = stats.ansari(x1, x2, alternative='less').pvalue
+        pval_g = stats.ansari(x1, x2, alternative='greater').pvalue
+        assert_allclose(pval_g, pval/2, atol=1e-12)
+        assert_allclose(pval_l, 1-pval/2, atol=1e-12)
+
+
+@array_api_compatible
+class TestBartlett:
+    def test_data(self, xp):
+        # https://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm
+        args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10]
+        args = [xp.asarray(arg) for arg in args]
+        T, pval = stats.bartlett(*args)
+        xp_assert_close(T, xp.asarray(20.78587342806484))
+        xp_assert_close(pval, xp.asarray(0.0136358632781))
+
+    def test_too_few_args(self, xp):
+        message = "Must enter at least two input sample vectors."
+        with pytest.raises(ValueError, match=message):
+            stats.bartlett(xp.asarray([1.]))
+
+    def test_result_attributes(self, xp):
+        args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10]
+        args = [xp.asarray(arg) for arg in args]
+        res = stats.bartlett(*args)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, xp=xp)
+
+    @pytest.mark.skip_xp_backends(
+        "jax.numpy", cpu_only=True,
+        reason='`var` incorrect when `correction > n` (google/jax#21330)')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_empty_arg(self, xp):
+        args = (g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, [])
+        args = [xp.asarray(arg) for arg in args]
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = stats.bartlett(*args)
+        else:
+            with np.testing.suppress_warnings() as sup:
+                # torch/array_api_strict
+                sup.filter(RuntimeWarning, "invalid value encountered")
+                sup.filter(UserWarning, r"var\(\): degrees of freedom is <= 0.")
+                sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice")
+                res = stats.bartlett(*args)
+        NaN = xp.asarray(xp.nan)
+        xp_assert_equal(res.statistic, NaN)
+        xp_assert_equal(res.pvalue, NaN)
+
+    def test_negative_pvalue_gh21152(self, xp):
+        a = xp.asarray([10.1, 10.2, 10.3, 10.4], dtype=xp.float32)
+        b = xp.asarray([10.15, 10.25, 10.35, 10.45], dtype=xp.float32)
+        c = xp.asarray([10.05, 10.15, 10.25, 10.35], dtype=xp.float32)
+        res = stats.bartlett(a, b, c)
+        assert xp.all(res.statistic >= 0)
+
+
+class TestLevene:
+
+    def test_data(self):
+        # https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm
+        args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10]
+        W, pval = stats.levene(*args)
+        assert_almost_equal(W, 1.7059176930008939, 7)
+        assert_almost_equal(pval, 0.0990829755522, 7)
+
+    def test_trimmed1(self):
+        # Test that center='trimmed' gives the same result as center='mean'
+        # when proportiontocut=0.
+        W1, pval1 = stats.levene(g1, g2, g3, center='mean')
+        W2, pval2 = stats.levene(g1, g2, g3, center='trimmed',
+                                 proportiontocut=0.0)
+        assert_almost_equal(W1, W2)
+        assert_almost_equal(pval1, pval2)
+
+    def test_trimmed2(self):
+        x = [1.2, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 100.0]
+        y = [0.0, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 200.0]
+        np.random.seed(1234)
+        x2 = np.random.permutation(x)
+
+        # Use center='trimmed'
+        W0, pval0 = stats.levene(x, y, center='trimmed',
+                                 proportiontocut=0.125)
+        W1, pval1 = stats.levene(x2, y, center='trimmed',
+                                 proportiontocut=0.125)
+        # Trim the data here, and use center='mean'
+        W2, pval2 = stats.levene(x[1:-1], y[1:-1], center='mean')
+        # Result should be the same.
+        assert_almost_equal(W0, W2)
+        assert_almost_equal(W1, W2)
+        assert_almost_equal(pval1, pval2)
+
+    def test_equal_mean_median(self):
+        x = np.linspace(-1, 1, 21)
+        np.random.seed(1234)
+        x2 = np.random.permutation(x)
+        y = x**3
+        W1, pval1 = stats.levene(x, y, center='mean')
+        W2, pval2 = stats.levene(x2, y, center='median')
+        assert_almost_equal(W1, W2)
+        assert_almost_equal(pval1, pval2)
+
+    def test_bad_keyword(self):
+        x = np.linspace(-1, 1, 21)
+        assert_raises(TypeError, stats.levene, x, x, portiontocut=0.1)
+
+    def test_bad_center_value(self):
+        x = np.linspace(-1, 1, 21)
+        assert_raises(ValueError, stats.levene, x, x, center='trim')
+
+    def test_too_few_args(self):
+        assert_raises(ValueError, stats.levene, [1])
+
+    def test_result_attributes(self):
+        args = [g1, g2, g3, g4, g5, g6, g7, g8, g9, g10]
+        res = stats.levene(*args)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes)
+
+    # temporary fix for issue #9252: only accept 1d input
+    def test_1d_input(self):
+        x = np.array([[1, 2], [3, 4]])
+        assert_raises(ValueError, stats.levene, g1, x)
+
+
+class TestBinomTest:
+    """Tests for stats.binomtest."""
+
+    # Expected results here are from R binom.test, e.g.
+    # options(digits=16)
+    # binom.test(484, 967, p=0.48)
+    #
+    def test_two_sided_pvalues1(self):
+        # `tol` could be stricter on most architectures, but the value
+        # here is limited by accuracy of `binom.cdf` for large inputs on
+        # Linux_Python_37_32bit_full and aarch64
+        rtol = 1e-10  # aarch64 observed rtol: 1.5e-11
+        res = stats.binomtest(10079999, 21000000, 0.48)
+        assert_allclose(res.pvalue, 1.0, rtol=rtol)
+        res = stats.binomtest(10079990, 21000000, 0.48)
+        assert_allclose(res.pvalue, 0.9966892187965, rtol=rtol)
+        res = stats.binomtest(10080009, 21000000, 0.48)
+        assert_allclose(res.pvalue, 0.9970377203856, rtol=rtol)
+        res = stats.binomtest(10080017, 21000000, 0.48)
+        assert_allclose(res.pvalue, 0.9940754817328, rtol=1e-9)
+
+    def test_two_sided_pvalues2(self):
+        rtol = 1e-10  # no aarch64 failure with 1e-15, preemptive bump
+        res = stats.binomtest(9, n=21, p=0.48)
+        assert_allclose(res.pvalue, 0.6689672431939, rtol=rtol)
+        res = stats.binomtest(4, 21, 0.48)
+        assert_allclose(res.pvalue, 0.008139563452106, rtol=rtol)
+        res = stats.binomtest(11, 21, 0.48)
+        assert_allclose(res.pvalue, 0.8278629664608, rtol=rtol)
+        res = stats.binomtest(7, 21, 0.48)
+        assert_allclose(res.pvalue, 0.1966772901718, rtol=rtol)
+        res = stats.binomtest(3, 10, .5)
+        assert_allclose(res.pvalue, 0.34375, rtol=rtol)
+        res = stats.binomtest(2, 2, .4)
+        assert_allclose(res.pvalue, 0.16, rtol=rtol)
+        res = stats.binomtest(2, 4, .3)
+        assert_allclose(res.pvalue, 0.5884, rtol=rtol)
+
+    def test_edge_cases(self):
+        rtol = 1e-10  # aarch64 observed rtol: 1.33e-15
+        res = stats.binomtest(484, 967, 0.5)
+        assert_allclose(res.pvalue, 1, rtol=rtol)
+        res = stats.binomtest(3, 47, 3/47)
+        assert_allclose(res.pvalue, 1, rtol=rtol)
+        res = stats.binomtest(13, 46, 13/46)
+        assert_allclose(res.pvalue, 1, rtol=rtol)
+        res = stats.binomtest(15, 44, 15/44)
+        assert_allclose(res.pvalue, 1, rtol=rtol)
+        res = stats.binomtest(7, 13, 0.5)
+        assert_allclose(res.pvalue, 1, rtol=rtol)
+        res = stats.binomtest(6, 11, 0.5)
+        assert_allclose(res.pvalue, 1, rtol=rtol)
+
+    def test_binary_srch_for_binom_tst(self):
+        # Test that old behavior of binomtest is maintained
+        # by the new binary search method in cases where d
+        # exactly equals the input on one side.
+        n = 10
+        p = 0.5
+        k = 3
+        # First test for the case where k > mode of PMF
+        i = np.arange(np.ceil(p * n), n+1)
+        d = stats.binom.pmf(k, n, p)
+        # Old way of calculating y, probably consistent with R.
+        y1 = np.sum(stats.binom.pmf(i, n, p) <= d, axis=0)
+        # New way with binary search.
+        ix = _binary_search_for_binom_tst(lambda x1:
+                                          -stats.binom.pmf(x1, n, p),
+                                          -d, np.ceil(p * n), n)
+        y2 = n - ix + int(d == stats.binom.pmf(ix, n, p))
+        assert_allclose(y1, y2, rtol=1e-9)
+        # Now test for the other side.
+        k = 7
+        i = np.arange(np.floor(p * n) + 1)
+        d = stats.binom.pmf(k, n, p)
+        # Old way of calculating y.
+        y1 = np.sum(stats.binom.pmf(i, n, p) <= d, axis=0)
+        # New way with binary search.
+        ix = _binary_search_for_binom_tst(lambda x1:
+                                          stats.binom.pmf(x1, n, p),
+                                          d, 0, np.floor(p * n))
+        y2 = ix + 1
+        assert_allclose(y1, y2, rtol=1e-9)
+
+    # Expected results here are from R 3.6.2 binom.test
+    @pytest.mark.parametrize('alternative, pval, ci_low, ci_high',
+                             [('less', 0.148831050443,
+                               0.0, 0.2772002496709138),
+                              ('greater', 0.9004695898947,
+                               0.1366613252458672, 1.0),
+                              ('two-sided', 0.2983720970096,
+                               0.1266555521019559, 0.2918426890886281)])
+    def test_confidence_intervals1(self, alternative, pval, ci_low, ci_high):
+        res = stats.binomtest(20, n=100, p=0.25, alternative=alternative)
+        assert_allclose(res.pvalue, pval, rtol=1e-12)
+        assert_equal(res.statistic, 0.2)
+        ci = res.proportion_ci(confidence_level=0.95)
+        assert_allclose((ci.low, ci.high), (ci_low, ci_high), rtol=1e-12)
+
+    # Expected results here are from R 3.6.2 binom.test.
+    @pytest.mark.parametrize('alternative, pval, ci_low, ci_high',
+                             [('less',
+                               0.005656361, 0.0, 0.1872093),
+                              ('greater',
+                               0.9987146, 0.008860761, 1.0),
+                              ('two-sided',
+                               0.01191714, 0.006872485, 0.202706269)])
+    def test_confidence_intervals2(self, alternative, pval, ci_low, ci_high):
+        res = stats.binomtest(3, n=50, p=0.2, alternative=alternative)
+        assert_allclose(res.pvalue, pval, rtol=1e-6)
+        assert_equal(res.statistic, 0.06)
+        ci = res.proportion_ci(confidence_level=0.99)
+        assert_allclose((ci.low, ci.high), (ci_low, ci_high), rtol=1e-6)
+
+    # Expected results here are from R 3.6.2 binom.test.
+    @pytest.mark.parametrize('alternative, pval, ci_high',
+                             [('less', 0.05631351, 0.2588656),
+                              ('greater', 1.0, 1.0),
+                              ('two-sided', 0.07604122, 0.3084971)])
+    def test_confidence_interval_exact_k0(self, alternative, pval, ci_high):
+        # Test with k=0, n = 10.
+        res = stats.binomtest(0, 10, p=0.25, alternative=alternative)
+        assert_allclose(res.pvalue, pval, rtol=1e-6)
+        ci = res.proportion_ci(confidence_level=0.95)
+        assert_equal(ci.low, 0.0)
+        assert_allclose(ci.high, ci_high, rtol=1e-6)
+
+    # Expected results here are from R 3.6.2 binom.test.
+    @pytest.mark.parametrize('alternative, pval, ci_low',
+                             [('less', 1.0, 0.0),
+                              ('greater', 9.536743e-07, 0.7411344),
+                              ('two-sided', 9.536743e-07, 0.6915029)])
+    def test_confidence_interval_exact_k_is_n(self, alternative, pval, ci_low):
+        # Test with k = n = 10.
+        res = stats.binomtest(10, 10, p=0.25, alternative=alternative)
+        assert_allclose(res.pvalue, pval, rtol=1e-6)
+        ci = res.proportion_ci(confidence_level=0.95)
+        assert_equal(ci.high, 1.0)
+        assert_allclose(ci.low, ci_low, rtol=1e-6)
+
+    # Expected results are from the prop.test function in R 3.6.2.
+    @pytest.mark.parametrize(
+        'k, alternative, corr, conf, ci_low, ci_high',
+        [[3, 'two-sided', True, 0.95, 0.08094782, 0.64632928],
+         [3, 'two-sided', True, 0.99, 0.0586329, 0.7169416],
+         [3, 'two-sided', False, 0.95, 0.1077913, 0.6032219],
+         [3, 'two-sided', False, 0.99, 0.07956632, 0.6799753],
+         [3, 'less', True, 0.95, 0.0, 0.6043476],
+         [3, 'less', True, 0.99, 0.0, 0.6901811],
+         [3, 'less', False, 0.95, 0.0, 0.5583002],
+         [3, 'less', False, 0.99, 0.0, 0.6507187],
+         [3, 'greater', True, 0.95, 0.09644904, 1.0],
+         [3, 'greater', True, 0.99, 0.06659141, 1.0],
+         [3, 'greater', False, 0.95, 0.1268766, 1.0],
+         [3, 'greater', False, 0.99, 0.08974147, 1.0],
+
+         [0, 'two-sided', True, 0.95, 0.0, 0.3445372],
+         [0, 'two-sided', False, 0.95, 0.0, 0.2775328],
+         [0, 'less', True, 0.95, 0.0, 0.2847374],
+         [0, 'less', False, 0.95, 0.0, 0.212942],
+         [0, 'greater', True, 0.95, 0.0, 1.0],
+         [0, 'greater', False, 0.95, 0.0, 1.0],
+
+         [10, 'two-sided', True, 0.95, 0.6554628, 1.0],
+         [10, 'two-sided', False, 0.95, 0.7224672, 1.0],
+         [10, 'less', True, 0.95, 0.0, 1.0],
+         [10, 'less', False, 0.95, 0.0, 1.0],
+         [10, 'greater', True, 0.95, 0.7152626, 1.0],
+         [10, 'greater', False, 0.95, 0.787058, 1.0]]
+    )
+    def test_ci_wilson_method(self, k, alternative, corr, conf,
+                              ci_low, ci_high):
+        res = stats.binomtest(k, n=10, p=0.1, alternative=alternative)
+        if corr:
+            method = 'wilsoncc'
+        else:
+            method = 'wilson'
+        ci = res.proportion_ci(confidence_level=conf, method=method)
+        assert_allclose((ci.low, ci.high), (ci_low, ci_high), rtol=1e-6)
+
+    def test_estimate_equals_hypothesized_prop(self):
+        # Test the special case where the estimated proportion equals
+        # the hypothesized proportion.  When alternative is 'two-sided',
+        # the p-value is 1.
+        res = stats.binomtest(4, 16, 0.25)
+        assert_equal(res.statistic, 0.25)
+        assert_equal(res.pvalue, 1.0)
+
+    @pytest.mark.parametrize('k, n', [(0, 0), (-1, 2)])
+    def test_invalid_k_n(self, k, n):
+        with pytest.raises(ValueError,
+                           match="must be an integer not less than"):
+            stats.binomtest(k, n)
+
+    def test_invalid_k_too_big(self):
+        with pytest.raises(ValueError,
+                           match=r"k \(11\) must not be greater than n \(10\)."):
+            stats.binomtest(11, 10, 0.25)
+
+    def test_invalid_k_wrong_type(self):
+        with pytest.raises(TypeError,
+                           match="k must be an integer."):
+            stats.binomtest([10, 11], 21, 0.25)
+
+    def test_invalid_p_range(self):
+        message = r'p \(-0.5\) must be in range...'
+        with pytest.raises(ValueError, match=message):
+            stats.binomtest(50, 150, p=-0.5)
+        message = r'p \(1.5\) must be in range...'
+        with pytest.raises(ValueError, match=message):
+            stats.binomtest(50, 150, p=1.5)
+
+    def test_invalid_confidence_level(self):
+        res = stats.binomtest(3, n=10, p=0.1)
+        message = r"confidence_level \(-1\) must be in the interval"
+        with pytest.raises(ValueError, match=message):
+            res.proportion_ci(confidence_level=-1)
+
+    def test_invalid_ci_method(self):
+        res = stats.binomtest(3, n=10, p=0.1)
+        with pytest.raises(ValueError, match=r"method \('plate of shrimp'\) must be"):
+            res.proportion_ci(method="plate of shrimp")
+
+    def test_invalid_alternative(self):
+        with pytest.raises(ValueError, match=r"alternative \('ekki'\) not..."):
+            stats.binomtest(3, n=10, p=0.1, alternative='ekki')
+
+    def test_alias(self):
+        res = stats.binomtest(3, n=10, p=0.1)
+        assert_equal(res.proportion_estimate, res.statistic)
+
+    @pytest.mark.skipif(sys.maxsize <= 2**32, reason="32-bit does not overflow")
+    def test_boost_overflow_raises(self):
+        # Boost.Math error policy should raise exceptions in Python
+        with pytest.raises(OverflowError, match='Error in function...'):
+            stats.binomtest(5, 6, p=sys.float_info.min)
+
+
+class TestFligner:
+
+    def test_data(self):
+        # numbers from R: fligner.test in package stats
+        x1 = np.arange(5)
+        assert_array_almost_equal(stats.fligner(x1, x1**2),
+                                  (3.2282229927203536, 0.072379187848207877),
+                                  11)
+
+    def test_trimmed1(self):
+        # Perturb input to break ties in the transformed data
+        # See https://github.com/scipy/scipy/pull/8042 for more details
+        rs = np.random.RandomState(123)
+
+        def _perturb(g):
+            return (np.asarray(g) + 1e-10 * rs.randn(len(g))).tolist()
+
+        g1_ = _perturb(g1)
+        g2_ = _perturb(g2)
+        g3_ = _perturb(g3)
+        # Test that center='trimmed' gives the same result as center='mean'
+        # when proportiontocut=0.
+        Xsq1, pval1 = stats.fligner(g1_, g2_, g3_, center='mean')
+        Xsq2, pval2 = stats.fligner(g1_, g2_, g3_, center='trimmed',
+                                    proportiontocut=0.0)
+        assert_almost_equal(Xsq1, Xsq2)
+        assert_almost_equal(pval1, pval2)
+
+    def test_trimmed2(self):
+        x = [1.2, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 100.0]
+        y = [0.0, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 200.0]
+        # Use center='trimmed'
+        Xsq1, pval1 = stats.fligner(x, y, center='trimmed',
+                                    proportiontocut=0.125)
+        # Trim the data here, and use center='mean'
+        Xsq2, pval2 = stats.fligner(x[1:-1], y[1:-1], center='mean')
+        # Result should be the same.
+        assert_almost_equal(Xsq1, Xsq2)
+        assert_almost_equal(pval1, pval2)
+
+    # The following test looks reasonable at first, but fligner() uses the
+    # function stats.rankdata(), and in one of the cases in this test,
+    # there are ties, while in the other (because of normal rounding
+    # errors) there are not.  This difference leads to differences in the
+    # third significant digit of W.
+    #
+    #def test_equal_mean_median(self):
+    #    x = np.linspace(-1,1,21)
+    #    y = x**3
+    #    W1, pval1 = stats.fligner(x, y, center='mean')
+    #    W2, pval2 = stats.fligner(x, y, center='median')
+    #    assert_almost_equal(W1, W2)
+    #    assert_almost_equal(pval1, pval2)
+
+    def test_bad_keyword(self):
+        x = np.linspace(-1, 1, 21)
+        assert_raises(TypeError, stats.fligner, x, x, portiontocut=0.1)
+
+    def test_bad_center_value(self):
+        x = np.linspace(-1, 1, 21)
+        assert_raises(ValueError, stats.fligner, x, x, center='trim')
+
+    def test_bad_num_args(self):
+        # Too few args raises ValueError.
+        assert_raises(ValueError, stats.fligner, [1])
+
+    def test_empty_arg(self):
+        x = np.arange(5)
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = stats.fligner(x, x**2, [])
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+
+def mood_cases_with_ties():
+    # Generate random `x` and `y` arrays with ties both between and within the
+    # samples. Expected results are (statistic, pvalue) from SAS.
+    expected_results = [(-1.76658511464992, .0386488678399305),
+                        (-.694031428192304, .2438312498647250),
+                        (-1.15093525352151, .1248794365836150)]
+    seeds = [23453254, 1298352315, 987234597]
+    for si, seed in enumerate(seeds):
+        rng = np.random.default_rng(seed)
+        xy = rng.random(100)
+        # Generate random indices to make ties
+        tie_ind = rng.integers(low=0, high=99, size=5)
+        # Generate a random number of ties for each index.
+        num_ties_per_ind = rng.integers(low=1, high=5, size=5)
+        # At each `tie_ind`, mark the next `n` indices equal to that value.
+        for i, n in zip(tie_ind, num_ties_per_ind):
+            for j in range(i + 1, i + n):
+                xy[j] = xy[i]
+        # scramble order of xy before splitting into `x, y`
+        rng.shuffle(xy)
+        x, y = np.split(xy, 2)
+        yield x, y, 'less', *expected_results[si]
+
+
+class TestMood:
+    @pytest.mark.parametrize("x,y,alternative,stat_expect,p_expect",
+                             mood_cases_with_ties())
+    def test_against_SAS(self, x, y, alternative, stat_expect, p_expect):
+        """
+        Example code used to generate SAS output:
+        DATA myData;
+        INPUT X Y;
+        CARDS;
+        1 0
+        1 1
+        1 2
+        1 3
+        1 4
+        2 0
+        2 1
+        2 4
+        2 9
+        2 16
+        ods graphics on;
+        proc npar1way mood data=myData ;
+           class X;
+            ods output  MoodTest=mt;
+        proc contents data=mt;
+        proc print data=mt;
+          format     Prob1 17.16 Prob2 17.16 Statistic 17.16 Z 17.16 ;
+            title "Mood Two-Sample Test";
+        proc print data=myData;
+            title "Data for above results";
+          run;
+        """
+        statistic, pvalue = stats.mood(x, y, alternative=alternative)
+        assert_allclose(stat_expect, statistic, atol=1e-16)
+        assert_allclose(p_expect, pvalue, atol=1e-16)
+
+    @pytest.mark.parametrize("alternative, expected",
+                             [('two-sided', (1.019938533549930,
+                                             .3077576129778760)),
+                              ('less', (1.019938533549930,
+                                        1 - .1538788064889380)),
+                              ('greater', (1.019938533549930,
+                                           .1538788064889380))])
+    def test_against_SAS_2(self, alternative, expected):
+        # Code to run in SAS in above function
+        x = [111, 107, 100, 99, 102, 106, 109, 108, 104, 99,
+             101, 96, 97, 102, 107, 113, 116, 113, 110, 98]
+        y = [107, 108, 106, 98, 105, 103, 110, 105, 104, 100,
+             96, 108, 103, 104, 114, 114, 113, 108, 106, 99]
+        res = stats.mood(x, y, alternative=alternative)
+        assert_allclose(res, expected)
+
+    def test_mood_order_of_args(self):
+        # z should change sign when the order of arguments changes, pvalue
+        # should not change
+        np.random.seed(1234)
+        x1 = np.random.randn(10, 1)
+        x2 = np.random.randn(15, 1)
+        z1, p1 = stats.mood(x1, x2)
+        z2, p2 = stats.mood(x2, x1)
+        assert_array_almost_equal([z1, p1], [-z2, p2])
+
+    def test_mood_with_axis_none(self):
+        # Test with axis = None, compare with results from R
+        x1 = [-0.626453810742332, 0.183643324222082, -0.835628612410047,
+              1.59528080213779, 0.329507771815361, -0.820468384118015,
+              0.487429052428485, 0.738324705129217, 0.575781351653492,
+              -0.305388387156356, 1.51178116845085, 0.389843236411431,
+              -0.621240580541804, -2.2146998871775, 1.12493091814311,
+              -0.0449336090152309, -0.0161902630989461, 0.943836210685299,
+              0.821221195098089, 0.593901321217509]
+
+        x2 = [-0.896914546624981, 0.184849184646742, 1.58784533120882,
+              -1.13037567424629, -0.0802517565509893, 0.132420284381094,
+              0.707954729271733, -0.23969802417184, 1.98447393665293,
+              -0.138787012119665, 0.417650750792556, 0.981752777463662,
+              -0.392695355503813, -1.03966897694891, 1.78222896030858,
+              -2.31106908460517, 0.878604580921265, 0.035806718015226,
+              1.01282869212708, 0.432265154539617, 2.09081920524915,
+              -1.19992581964387, 1.58963820029007, 1.95465164222325,
+              0.00493777682814261, -2.45170638784613, 0.477237302613617,
+              -0.596558168631403, 0.792203270299649, 0.289636710177348]
+
+        x1 = np.array(x1)
+        x2 = np.array(x2)
+        x1.shape = (10, 2)
+        x2.shape = (15, 2)
+        assert_array_almost_equal(stats.mood(x1, x2, axis=None),
+                                  [-1.31716607555, 0.18778296257])
+
+    def test_mood_2d(self):
+        # Test if the results of mood test in 2-D case are consistent with the
+        # R result for the same inputs.  Numbers from R mood.test().
+        ny = 5
+        np.random.seed(1234)
+        x1 = np.random.randn(10, ny)
+        x2 = np.random.randn(15, ny)
+        z_vectest, pval_vectest = stats.mood(x1, x2)
+
+        for j in range(ny):
+            assert_array_almost_equal([z_vectest[j], pval_vectest[j]],
+                                      stats.mood(x1[:, j], x2[:, j]))
+
+        # inverse order of dimensions
+        x1 = x1.transpose()
+        x2 = x2.transpose()
+        z_vectest, pval_vectest = stats.mood(x1, x2, axis=1)
+
+        for i in range(ny):
+            # check axis handling is self consistent
+            assert_array_almost_equal([z_vectest[i], pval_vectest[i]],
+                                      stats.mood(x1[i, :], x2[i, :]))
+
+    def test_mood_3d(self):
+        shape = (10, 5, 6)
+        np.random.seed(1234)
+        x1 = np.random.randn(*shape)
+        x2 = np.random.randn(*shape)
+
+        for axis in range(3):
+            z_vectest, pval_vectest = stats.mood(x1, x2, axis=axis)
+            # Tests that result for 3-D arrays is equal to that for the
+            # same calculation on a set of 1-D arrays taken from the
+            # 3-D array
+            axes_idx = ([1, 2], [0, 2], [0, 1])  # the two axes != axis
+            for i in range(shape[axes_idx[axis][0]]):
+                for j in range(shape[axes_idx[axis][1]]):
+                    if axis == 0:
+                        slice1 = x1[:, i, j]
+                        slice2 = x2[:, i, j]
+                    elif axis == 1:
+                        slice1 = x1[i, :, j]
+                        slice2 = x2[i, :, j]
+                    else:
+                        slice1 = x1[i, j, :]
+                        slice2 = x2[i, j, :]
+
+                    assert_array_almost_equal([z_vectest[i, j],
+                                               pval_vectest[i, j]],
+                                              stats.mood(slice1, slice2))
+
+    def test_mood_bad_arg(self):
+        # Warns when the sum of the lengths of the args is less than 3
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = stats.mood([1], [])
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+    def test_mood_alternative(self):
+
+        np.random.seed(0)
+        x = stats.norm.rvs(scale=0.75, size=100)
+        y = stats.norm.rvs(scale=1.25, size=100)
+
+        stat1, p1 = stats.mood(x, y, alternative='two-sided')
+        stat2, p2 = stats.mood(x, y, alternative='less')
+        stat3, p3 = stats.mood(x, y, alternative='greater')
+
+        assert stat1 == stat2 == stat3
+        assert_allclose(p1, 0, atol=1e-7)
+        assert_allclose(p2, p1/2)
+        assert_allclose(p3, 1 - p1/2)
+
+        with pytest.raises(ValueError, match="`alternative` must be..."):
+            stats.mood(x, y, alternative='ekki-ekki')
+
+    @pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater'])
+    def test_result(self, alternative):
+        rng = np.random.default_rng(265827767938813079281100964083953437622)
+        x1 = rng.standard_normal((10, 1))
+        x2 = rng.standard_normal((15, 1))
+
+        res = stats.mood(x1, x2, alternative=alternative)
+        assert_equal((res.statistic, res.pvalue), res)
+
+
+class TestProbplot:
+
+    def test_basic(self):
+        x = stats.norm.rvs(size=20, random_state=12345)
+        osm, osr = stats.probplot(x, fit=False)
+        osm_expected = [-1.8241636, -1.38768012, -1.11829229, -0.91222575,
+                        -0.73908135, -0.5857176, -0.44506467, -0.31273668,
+                        -0.18568928, -0.06158146, 0.06158146, 0.18568928,
+                        0.31273668, 0.44506467, 0.5857176, 0.73908135,
+                        0.91222575, 1.11829229, 1.38768012, 1.8241636]
+        assert_allclose(osr, np.sort(x))
+        assert_allclose(osm, osm_expected)
+
+        res, res_fit = stats.probplot(x, fit=True)
+        res_fit_expected = [1.05361841, 0.31297795, 0.98741609]
+        assert_allclose(res_fit, res_fit_expected)
+
+    def test_sparams_keyword(self):
+        x = stats.norm.rvs(size=100, random_state=123456)
+        # Check that None, () and 0 (loc=0, for normal distribution) all work
+        # and give the same results
+        osm1, osr1 = stats.probplot(x, sparams=None, fit=False)
+        osm2, osr2 = stats.probplot(x, sparams=0, fit=False)
+        osm3, osr3 = stats.probplot(x, sparams=(), fit=False)
+        assert_allclose(osm1, osm2)
+        assert_allclose(osm1, osm3)
+        assert_allclose(osr1, osr2)
+        assert_allclose(osr1, osr3)
+        # Check giving (loc, scale) params for normal distribution
+        osm, osr = stats.probplot(x, sparams=(), fit=False)
+
+    def test_dist_keyword(self):
+        x = stats.norm.rvs(size=20, random_state=12345)
+        osm1, osr1 = stats.probplot(x, fit=False, dist='t', sparams=(3,))
+        osm2, osr2 = stats.probplot(x, fit=False, dist=stats.t, sparams=(3,))
+        assert_allclose(osm1, osm2)
+        assert_allclose(osr1, osr2)
+
+        assert_raises(ValueError, stats.probplot, x, dist='wrong-dist-name')
+        assert_raises(AttributeError, stats.probplot, x, dist=[])
+
+        class custom_dist:
+            """Some class that looks just enough like a distribution."""
+            def ppf(self, q):
+                return stats.norm.ppf(q, loc=2)
+
+        osm1, osr1 = stats.probplot(x, sparams=(2,), fit=False)
+        osm2, osr2 = stats.probplot(x, dist=custom_dist(), fit=False)
+        assert_allclose(osm1, osm2)
+        assert_allclose(osr1, osr2)
+
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_plot_kwarg(self):
+        fig = plt.figure()
+        fig.add_subplot(111)
+        x = stats.t.rvs(3, size=100, random_state=7654321)
+        res1, fitres1 = stats.probplot(x, plot=plt)
+        plt.close()
+        res2, fitres2 = stats.probplot(x, plot=None)
+        res3 = stats.probplot(x, fit=False, plot=plt)
+        plt.close()
+        res4 = stats.probplot(x, fit=False, plot=None)
+        # Check that results are consistent between combinations of `fit` and
+        # `plot` keywords.
+        assert_(len(res1) == len(res2) == len(res3) == len(res4) == 2)
+        assert_allclose(res1, res2)
+        assert_allclose(res1, res3)
+        assert_allclose(res1, res4)
+        assert_allclose(fitres1, fitres2)
+
+        # Check that a Matplotlib Axes object is accepted
+        fig = plt.figure()
+        ax = fig.add_subplot(111)
+        stats.probplot(x, fit=False, plot=ax)
+        plt.close()
+
+    def test_probplot_bad_args(self):
+        # Raise ValueError when given an invalid distribution.
+        assert_raises(ValueError, stats.probplot, [1], dist="plate_of_shrimp")
+
+    def test_empty(self):
+        assert_equal(stats.probplot([], fit=False),
+                     (np.array([]), np.array([])))
+        assert_equal(stats.probplot([], fit=True),
+                     ((np.array([]), np.array([])),
+                      (np.nan, np.nan, 0.0)))
+
+    def test_array_of_size_one(self):
+        with np.errstate(invalid='ignore'):
+            assert_equal(stats.probplot([1], fit=True),
+                         ((np.array([0.]), np.array([1])),
+                          (np.nan, np.nan, 0.0)))
+
+
+class TestWilcoxon:
+    def test_wilcoxon_bad_arg(self):
+        # Raise ValueError when two args of different lengths are given or
+        # zero_method is unknown.
+        assert_raises(ValueError, stats.wilcoxon, [1, 2], [1, 2], "dummy")
+        assert_raises(ValueError, stats.wilcoxon, [1, 2], [1, 2],
+                      alternative="dummy")
+        assert_raises(ValueError, stats.wilcoxon, [1]*10, method="xyz")
+
+    def test_zero_diff(self):
+        x = np.arange(20)
+        # pratt and wilcox do not work if x - y == 0 and method == "asymptotic"
+        # => warning may be emitted and p-value is nan
+        with np.errstate(invalid="ignore"):
+            w, p = stats.wilcoxon(x, x, "wilcox", method="asymptotic")
+            assert_equal((w, p), (0.0, np.nan))
+            w, p = stats.wilcoxon(x, x, "pratt", method="asymptotic")
+            assert_equal((w, p), (0.0, np.nan))
+        # ranksum is n*(n+1)/2, split in half if zero_method == "zsplit"
+        assert_equal(stats.wilcoxon(x, x, "zsplit", method="asymptotic"),
+                     (20*21/4, 1.0))
+
+    def test_pratt(self):
+        # regression test for gh-6805: p-value matches value from R package
+        # coin (wilcoxsign_test) reported in the issue
+        x = [1, 2, 3, 4]
+        y = [1, 2, 3, 5]
+        res = stats.wilcoxon(x, y, zero_method="pratt", method="asymptotic",
+                             correction=False)
+        assert_allclose(res, (0.0, 0.31731050786291415))
+
+    def test_wilcoxon_arg_type(self):
+        # Should be able to accept list as arguments.
+        # Address issue 6070.
+        arr = [1, 2, 3, 0, -1, 3, 1, 2, 1, 1, 2]
+
+        _ = stats.wilcoxon(arr, zero_method="pratt", method="asymptotic")
+        _ = stats.wilcoxon(arr, zero_method="zsplit", method="asymptotic")
+        _ = stats.wilcoxon(arr, zero_method="wilcox", method="asymptotic")
+
+    def test_accuracy_wilcoxon(self):
+        freq = [1, 4, 16, 15, 8, 4, 5, 1, 2]
+        nums = range(-4, 5)
+        x = np.concatenate([[u] * v for u, v in zip(nums, freq)])
+        y = np.zeros(x.size)
+
+        T, p = stats.wilcoxon(x, y, "pratt", method="asymptotic",
+                              correction=False)
+        assert_allclose(T, 423)
+        assert_allclose(p, 0.0031724568006762576)
+
+        T, p = stats.wilcoxon(x, y, "zsplit", method="asymptotic",
+                              correction=False)
+        assert_allclose(T, 441)
+        assert_allclose(p, 0.0032145343172473055)
+
+        T, p = stats.wilcoxon(x, y, "wilcox", method="asymptotic",
+                              correction=False)
+        assert_allclose(T, 327)
+        assert_allclose(p, 0.00641346115861)
+
+        # Test the 'correction' option, using values computed in R with:
+        # > wilcox.test(x, y, paired=TRUE, exact=FALSE, correct={FALSE,TRUE})
+        x = np.array([120, 114, 181, 188, 180, 146, 121, 191, 132, 113, 127, 112])
+        y = np.array([133, 143, 119, 189, 112, 199, 198, 113, 115, 121, 142, 187])
+        T, p = stats.wilcoxon(x, y, correction=False, method="asymptotic")
+        assert_equal(T, 34)
+        assert_allclose(p, 0.6948866, rtol=1e-6)
+        T, p = stats.wilcoxon(x, y, correction=True, method="asymptotic")
+        assert_equal(T, 34)
+        assert_allclose(p, 0.7240817, rtol=1e-6)
+
+    def test_approx_mode(self):
+        # Check that `mode` is still an alias of keyword `method`,
+        # and `"approx"` is still an alias of argument `"asymptotic"`
+        x = np.array([3, 5, 23, 7, 243, 58, 98, 2, 8, -3, 9, 11])
+        y = np.array([2, -2, 1, 23, 0, 5, 12, 18, 99, 12, 17, 27])
+        res1 = stats.wilcoxon(x, y, "wilcox", method="approx")
+        res2 = stats.wilcoxon(x, y, "wilcox", method="asymptotic")
+        res3 = stats.wilcoxon(x, y, "wilcox", mode="approx")
+        res4 = stats.wilcoxon(x, y, "wilcox", mode="asymptotic")
+        assert res1 == res2 == res3 == res4
+
+    def test_wilcoxon_result_attributes(self):
+        x = np.array([120, 114, 181, 188, 180, 146, 121, 191, 132, 113, 127, 112])
+        y = np.array([133, 143, 119, 189, 112, 199, 198, 113, 115, 121, 142, 187])
+        res = stats.wilcoxon(x, y, correction=False, method="asymptotic")
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes)
+
+    def test_wilcoxon_has_zstatistic(self):
+        rng = np.random.default_rng(89426135444)
+        x, y = rng.random(15), rng.random(15)
+
+        res = stats.wilcoxon(x, y, method="asymptotic")
+        ref = stats.norm.ppf(res.pvalue/2)
+        assert_allclose(res.zstatistic, ref)
+
+        res = stats.wilcoxon(x, y, method="exact")
+        assert not hasattr(res, 'zstatistic')
+
+        res = stats.wilcoxon(x, y)
+        assert not hasattr(res, 'zstatistic')
+
+    def test_wilcoxon_tie(self):
+        # Regression test for gh-2391.
+        # Corresponding R code is:
+        #   > result = wilcox.test(rep(0.1, 10), exact=FALSE, correct=FALSE)
+        #   > result$p.value
+        #   [1] 0.001565402
+        #   > result = wilcox.test(rep(0.1, 10), exact=FALSE, correct=TRUE)
+        #   > result$p.value
+        #   [1] 0.001904195
+        stat, p = stats.wilcoxon([0.1] * 10, method="asymptotic",
+                                 correction=False)
+        expected_p = 0.001565402
+        assert_equal(stat, 0)
+        assert_allclose(p, expected_p, rtol=1e-6)
+
+        stat, p = stats.wilcoxon([0.1] * 10, correction=True,
+                                 method="asymptotic")
+        expected_p = 0.001904195
+        assert_equal(stat, 0)
+        assert_allclose(p, expected_p, rtol=1e-6)
+
+    def test_onesided(self):
+        # tested against "R version 3.4.1 (2017-06-30)"
+        # x <- c(125, 115, 130, 140, 140, 115, 140, 125, 140, 135)
+        # y <- c(110, 122, 125, 120, 140, 124, 123, 137, 135, 145)
+        # cfg <- list(x = x, y = y, paired = TRUE, exact = FALSE)
+        # do.call(wilcox.test, c(cfg, list(alternative = "less", correct = FALSE)))
+        # do.call(wilcox.test, c(cfg, list(alternative = "less", correct = TRUE)))
+        # do.call(wilcox.test, c(cfg, list(alternative = "greater", correct = FALSE)))
+        # do.call(wilcox.test, c(cfg, list(alternative = "greater", correct = TRUE)))
+        x = [125, 115, 130, 140, 140, 115, 140, 125, 140, 135]
+        y = [110, 122, 125, 120, 140, 124, 123, 137, 135, 145]
+
+        w, p = stats.wilcoxon(x, y, alternative="less", method="asymptotic",
+                              correction=False)
+        assert_equal(w, 27)
+        assert_almost_equal(p, 0.7031847, decimal=6)
+
+        w, p = stats.wilcoxon(x, y, alternative="less", correction=True,
+                              method="asymptotic")
+        assert_equal(w, 27)
+        assert_almost_equal(p, 0.7233656, decimal=6)
+
+        w, p = stats.wilcoxon(x, y, alternative="greater",
+                              method="asymptotic", correction=False)
+        assert_equal(w, 27)
+        assert_almost_equal(p, 0.2968153, decimal=6)
+
+        w, p = stats.wilcoxon(x, y, alternative="greater",
+                              correction=True, method="asymptotic")
+        assert_equal(w, 27)
+        assert_almost_equal(p, 0.3176447, decimal=6)
+
+    def test_exact_basic(self):
+        for n in range(1, 51):
+            pmf1 = _get_wilcoxon_distr(n)
+            pmf2 = _get_wilcoxon_distr2(n)
+            assert_equal(n*(n+1)/2 + 1, len(pmf1))
+            assert_equal(sum(pmf1), 1)
+            assert_array_almost_equal(pmf1, pmf2)
+
+    def test_exact_pval(self):
+        # expected values computed with "R version 3.4.1 (2017-06-30)"
+        x = np.array([1.81, 0.82, 1.56, -0.48, 0.81, 1.28, -1.04, 0.23,
+                      -0.75, 0.14])
+        y = np.array([0.71, 0.65, -0.2, 0.85, -1.1, -0.45, -0.84, -0.24,
+                      -0.68, -0.76])
+        _, p = stats.wilcoxon(x, y, alternative="two-sided", method="exact")
+        assert_almost_equal(p, 0.1054688, decimal=6)
+        _, p = stats.wilcoxon(x, y, alternative="less", method="exact")
+        assert_almost_equal(p, 0.9580078, decimal=6)
+        _, p = stats.wilcoxon(x, y, alternative="greater", method="exact")
+        assert_almost_equal(p, 0.05273438, decimal=6)
+
+        x = np.arange(0, 20) + 0.5
+        y = np.arange(20, 0, -1)
+        _, p = stats.wilcoxon(x, y, alternative="two-sided", method="exact")
+        assert_almost_equal(p, 0.8694878, decimal=6)
+        _, p = stats.wilcoxon(x, y, alternative="less", method="exact")
+        assert_almost_equal(p, 0.4347439, decimal=6)
+        _, p = stats.wilcoxon(x, y, alternative="greater", method="exact")
+        assert_almost_equal(p, 0.5795889, decimal=6)
+
+    # These inputs were chosen to give a W statistic that is either the
+    # center of the distribution (when the length of the support is odd), or
+    # the value to the left of the center (when the length of the support is
+    # even).  Also, the numbers are chosen so that the W statistic is the
+    # sum of the positive values.
+
+    @pytest.mark.parametrize('x', [[-1, -2, 3],
+                                   [-1, 2, -3, -4, 5],
+                                   [-1, -2, 3, -4, -5, -6, 7, 8]])
+    def test_exact_p_1(self, x):
+        w, p = stats.wilcoxon(x)
+        x = np.array(x)
+        wtrue = x[x > 0].sum()
+        assert_equal(w, wtrue)
+        assert_equal(p, 1)
+
+    def test_auto(self):
+        # auto default to exact if there are no ties and n <= 50
+        x = np.arange(0, 50) + 0.5
+        y = np.arange(50, 0, -1)
+        assert_equal(stats.wilcoxon(x, y),
+                     stats.wilcoxon(x, y, method="exact"))
+
+        # n <= 50: if there are zeros in d = x-y, use PermutationMethod
+        pm = stats.PermutationMethod()
+        d = np.arange(-2, 5)
+        w, p = stats.wilcoxon(d)
+        # rerunning the test gives the same results since n_resamples
+        # is large enough to get deterministic results if n <= 13
+        # so we do not need to use a seed. to avoid longer runtimes of the
+        # test, use n=7 only. For n=13, see test_auto_permutation_edge_case
+        assert_equal((w, p), stats.wilcoxon(d, method=pm))
+
+        # for larger vectors (n > 13) with ties/zeros, use asymptotic test
+        d = np.arange(-5, 9)  # zero
+        w, p = stats.wilcoxon(d)
+        assert_equal((w, p), stats.wilcoxon(d, method="asymptotic"))
+
+        d[d == 0] = 1  # tie
+        w, p = stats.wilcoxon(d)
+        assert_equal((w, p), stats.wilcoxon(d, method="asymptotic"))
+
+        # use approximation for samples > 50
+        d = np.arange(1, 52)
+        assert_equal(stats.wilcoxon(d), stats.wilcoxon(d, method="asymptotic"))
+
+    @pytest.mark.xslow
+    def test_auto_permutation_edge_case(self):
+        # Check that `PermutationMethod()` is used and results are deterministic when
+        # `method='auto'`, there are zeros or ties in `d = x-y`, and `len(d) <= 13`.
+        d = np.arange(-5, 8)  # zero
+        res = stats.wilcoxon(d)
+        ref = (27.5, 0.3955078125)  # stats.wilcoxon(d, method=PermutationMethod())
+        assert_equal(res, ref)
+
+        d[d == 0] = 1  # tie
+        res = stats.wilcoxon(d)
+        ref = (32, 0.3779296875)  # stats.wilcoxon(d, method=PermutationMethod())
+        assert_equal(res, ref)
+
+    @pytest.mark.parametrize('size', [3, 5, 10])
+    def test_permutation_method(self, size):
+        rng = np.random.default_rng(92348034828501345)
+        x = rng.random(size=size)
+        res = stats.wilcoxon(x, method=stats.PermutationMethod())
+        ref = stats.wilcoxon(x, method='exact')
+        assert_equal(res.statistic, ref.statistic)
+        assert_equal(res.pvalue, ref.pvalue)
+
+        x = rng.random(size=size*10)
+        rng = np.random.default_rng(59234803482850134)
+        pm = stats.PermutationMethod(n_resamples=99, rng=rng)
+        ref = stats.wilcoxon(x, method=pm)
+        # preserve use of old random_state during SPEC 7 transition
+        rng = np.random.default_rng(59234803482850134)
+        pm = stats.PermutationMethod(n_resamples=99, random_state=rng)
+        res = stats.wilcoxon(x, method=pm)
+
+        assert_equal(np.round(res.pvalue, 2), res.pvalue)  # n_resamples used
+        assert_equal(res.pvalue, ref.pvalue)  # rng/random_state used
+
+    def test_method_auto_nan_propagate_ND_length_gt_50_gh20591(self):
+        # When method!='asymptotic', nan_policy='propagate', and a slice of
+        # a >1 dimensional array input contained NaN, the result object of
+        # `wilcoxon` could (under yet other conditions) return `zstatistic`
+        # for some slices but not others. This resulted in an error because
+        # `apply_along_axis` would have to create a ragged array.
+        # Check that this is resolved.
+        rng = np.random.default_rng(235889269872456)
+        A = rng.normal(size=(51, 2))  # length along slice > exact threshold
+        A[5, 1] = np.nan
+        res = stats.wilcoxon(A)
+        ref = stats.wilcoxon(A, method='asymptotic')
+        assert_allclose(res, ref)
+        assert hasattr(ref, 'zstatistic')
+        assert not hasattr(res, 'zstatistic')
+
+    @pytest.mark.parametrize('method', ['exact', 'asymptotic'])
+    def test_symmetry_gh19872_gh20752(self, method):
+        # Check that one-sided exact tests obey required symmetry. Bug reported
+        # in gh-19872 and again in gh-20752; example from gh-19872 is more concise:
+        var1 = [62, 66, 61, 68, 74, 62, 68, 62, 55, 59]
+        var2 = [71, 71, 69, 61, 75, 71, 77, 72, 62, 65]
+        ref = stats.wilcoxon(var1, var2, alternative='less', method=method)
+        res = stats.wilcoxon(var2, var1, alternative='greater', method=method)
+        max_statistic = len(var1) * (len(var1) + 1) / 2
+        assert int(res.statistic) != res.statistic
+        assert_allclose(max_statistic - res.statistic, ref.statistic, rtol=1e-15)
+        assert_allclose(res.pvalue, ref.pvalue, rtol=1e-15)
+
+    @pytest.mark.parametrize("method", ('exact', stats.PermutationMethod()))
+    def test_all_zeros_exact(self, method):
+        # previously, this raised a RuntimeWarning when calculating Z, even
+        # when the Z value was not needed. Confirm that this no longer
+        # occurs when `method` is 'exact' or a `PermutationMethod`.
+        res = stats.wilcoxon(np.zeros(5), method=method)
+        assert_allclose(res, [0, 1])
+
+
+# data for k-statistics tests from
+# https://cran.r-project.org/web/packages/kStatistics/kStatistics.pdf
+# see nKS "Examples"
+x_kstat = [16.34, 10.76, 11.84, 13.55, 15.85, 18.20, 7.51, 10.22, 12.52, 14.68,
+           16.08, 19.43, 8.12, 11.20, 12.95, 14.77, 16.83, 19.80, 8.55, 11.58,
+           12.10, 15.02, 16.83, 16.98, 19.92, 9.47, 11.68, 13.41, 15.35, 19.11]
+
+
+@array_api_compatible
+class TestKstat:
+    def test_moments_normal_distribution(self, xp):
+        np.random.seed(32149)
+        data = xp.asarray(np.random.randn(12345), dtype=xp.float64)
+        moments = xp.asarray([stats.kstat(data, n) for n in [1, 2, 3, 4]])
+
+        expected = xp.asarray([0.011315, 1.017931, 0.05811052, 0.0754134],
+                              dtype=data.dtype)
+        xp_assert_close(moments, expected, rtol=1e-4)
+
+        # test equivalence with `stats.moment`
+        m1 = stats.moment(data, order=1)
+        m2 = stats.moment(data, order=2)
+        m3 = stats.moment(data, order=3)
+        xp_assert_close(xp.asarray((m1, m2, m3)), expected[:-1], atol=0.02, rtol=1e-2)
+
+    def test_empty_input(self, xp):
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = stats.kstat(xp.asarray([]))
+        else:
+            with np.errstate(invalid='ignore'):  # for array_api_strict
+                res = stats.kstat(xp.asarray([]))
+        xp_assert_equal(res, xp.asarray(xp.nan))
+
+    def test_nan_input(self, xp):
+        data = xp.arange(10.)
+        data = xp.where(data == 6, xp.asarray(xp.nan), data)
+
+        xp_assert_equal(stats.kstat(data), xp.asarray(xp.nan))
+
+    @pytest.mark.parametrize('n', [0, 4.001])
+    def test_kstat_bad_arg(self, n, xp):
+        # Raise ValueError if n > 4 or n < 1.
+        data = xp.arange(10)
+        message = 'k-statistics only supported for 1<=n<=4'
+        with pytest.raises(ValueError, match=message):
+            stats.kstat(data, n=n)
+
+    @pytest.mark.parametrize('case', [(1, 14.02166666666667),
+                                      (2, 12.65006954022974),
+                                      (3, -1.447059503280798),
+                                      (4, -141.6682291883626)])
+    def test_against_R(self, case, xp):
+        # Test against reference values computed with R kStatistics, e.g.
+        # options(digits=16)
+        # library(kStatistics)
+        # data <-c (16.34, 10.76, 11.84, 13.55, 15.85, 18.20, 7.51, 10.22,
+        #           12.52, 14.68, 16.08, 19.43, 8.12, 11.20, 12.95, 14.77,
+        #           16.83, 19.80, 8.55, 11.58, 12.10, 15.02, 16.83, 16.98,
+        #           19.92, 9.47, 11.68, 13.41, 15.35, 19.11)
+        # nKS(4, data)
+        n, ref = case
+        res = stats.kstat(xp.asarray(x_kstat), n)
+        xp_assert_close(res, xp.asarray(ref))
+
+
+@array_api_compatible
+class TestKstatVar:
+    def test_empty_input(self, xp):
+        x = xp.asarray([])
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = stats.kstatvar(x)
+        else:
+            with np.errstate(invalid='ignore'):  # for array_api_strict
+                res = stats.kstatvar(x)
+        xp_assert_equal(res, xp.asarray(xp.nan))
+
+    def test_nan_input(self, xp):
+        data = xp.arange(10.)
+        data = xp.where(data == 6, xp.asarray(xp.nan), data)
+
+        xp_assert_equal(stats.kstat(data), xp.asarray(xp.nan))
+
+    @skip_xp_backends(np_only=True,
+                      reason='input validation of `n` does not depend on backend')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_bad_arg(self):
+        # Raise ValueError is n is not 1 or 2.
+        data = [1]
+        n = 10
+        message = 'Only n=1 or n=2 supported.'
+        with pytest.raises(ValueError, match=message):
+            stats.kstatvar(data, n=n)
+
+    def test_against_R_mathworld(self, xp):
+        # Test against reference values computed using formulas exactly as
+        # they appear at https://mathworld.wolfram.com/k-Statistic.html
+        # This is *really* similar to how they appear in the implementation,
+        # but that could change, and this should not.
+        n = len(x_kstat)
+        k2 = 12.65006954022974  # see source code in TestKstat
+        k4 = -141.6682291883626
+
+        res = stats.kstatvar(xp.asarray(x_kstat), 1)
+        ref = k2 / n
+        xp_assert_close(res, xp.asarray(ref))
+
+        res = stats.kstatvar(xp.asarray(x_kstat), 2)
+        # *unbiased estimator* for var(k2)
+        ref = (2*k2**2*n + (n-1)*k4) / (n * (n+1))
+        xp_assert_close(res, xp.asarray(ref))
+
+
+class TestPpccPlot:
+    def setup_method(self):
+        self.x = _old_loggamma_rvs(5, size=500, random_state=7654321) + 5
+
+    def test_basic(self):
+        N = 5
+        svals, ppcc = stats.ppcc_plot(self.x, -10, 10, N=N)
+        ppcc_expected = [0.21139644, 0.21384059, 0.98766719, 0.97980182,
+                         0.93519298]
+        assert_allclose(svals, np.linspace(-10, 10, num=N))
+        assert_allclose(ppcc, ppcc_expected)
+
+    def test_dist(self):
+        # Test that we can specify distributions both by name and as objects.
+        svals1, ppcc1 = stats.ppcc_plot(self.x, -10, 10, dist='tukeylambda')
+        svals2, ppcc2 = stats.ppcc_plot(self.x, -10, 10,
+                                        dist=stats.tukeylambda)
+        assert_allclose(svals1, svals2, rtol=1e-20)
+        assert_allclose(ppcc1, ppcc2, rtol=1e-20)
+        # Test that 'tukeylambda' is the default dist
+        svals3, ppcc3 = stats.ppcc_plot(self.x, -10, 10)
+        assert_allclose(svals1, svals3, rtol=1e-20)
+        assert_allclose(ppcc1, ppcc3, rtol=1e-20)
+
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_plot_kwarg(self):
+        # Check with the matplotlib.pyplot module
+        fig = plt.figure()
+        ax = fig.add_subplot(111)
+        stats.ppcc_plot(self.x, -20, 20, plot=plt)
+        fig.delaxes(ax)
+
+        # Check that a Matplotlib Axes object is accepted
+        ax = fig.add_subplot(111)
+        stats.ppcc_plot(self.x, -20, 20, plot=ax)
+        plt.close()
+
+    def test_invalid_inputs(self):
+        # `b` has to be larger than `a`
+        assert_raises(ValueError, stats.ppcc_plot, self.x, 1, 0)
+
+        # Raise ValueError when given an invalid distribution.
+        assert_raises(ValueError, stats.ppcc_plot, [1, 2, 3], 0, 1,
+                      dist="plate_of_shrimp")
+
+    def test_empty(self):
+        # For consistency with probplot return for one empty array,
+        # ppcc contains all zeros and svals is the same as for normal array
+        # input.
+        svals, ppcc = stats.ppcc_plot([], 0, 1)
+        assert_allclose(svals, np.linspace(0, 1, num=80))
+        assert_allclose(ppcc, np.zeros(80, dtype=float))
+
+
+class TestPpccMax:
+    def test_ppcc_max_bad_arg(self):
+        # Raise ValueError when given an invalid distribution.
+        data = [1]
+        assert_raises(ValueError, stats.ppcc_max, data, dist="plate_of_shrimp")
+
+    def test_ppcc_max_basic(self):
+        x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000,
+                                  random_state=1234567) + 1e4
+        assert_almost_equal(stats.ppcc_max(x), -0.71215366521264145, decimal=7)
+
+    def test_dist(self):
+        x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000,
+                                  random_state=1234567) + 1e4
+
+        # Test that we can specify distributions both by name and as objects.
+        max1 = stats.ppcc_max(x, dist='tukeylambda')
+        max2 = stats.ppcc_max(x, dist=stats.tukeylambda)
+        assert_almost_equal(max1, -0.71215366521264145, decimal=5)
+        assert_almost_equal(max2, -0.71215366521264145, decimal=5)
+
+        # Test that 'tukeylambda' is the default dist
+        max3 = stats.ppcc_max(x)
+        assert_almost_equal(max3, -0.71215366521264145, decimal=5)
+
+    def test_brack(self):
+        x = stats.tukeylambda.rvs(-0.7, loc=2, scale=0.5, size=10000,
+                                  random_state=1234567) + 1e4
+        assert_raises(ValueError, stats.ppcc_max, x, brack=(0.0, 1.0, 0.5))
+
+        assert_almost_equal(stats.ppcc_max(x, brack=(0, 1)),
+                            -0.71215366521264145, decimal=7)
+
+        assert_almost_equal(stats.ppcc_max(x, brack=(-2, 2)),
+                            -0.71215366521264145, decimal=7)
+
+
+@skip_xp_backends('jax.numpy', reason="JAX arrays do not support item assignment")
+@pytest.mark.usefixtures("skip_xp_backends")
+@array_api_compatible
+class TestBoxcox_llf:
+
+    @pytest.mark.parametrize("dtype", ["float32", "float64"])
+    def test_basic(self, dtype, xp):
+        dt = getattr(xp, dtype)
+        x = stats.norm.rvs(size=10000, loc=10, random_state=54321)
+        lmbda = 1
+        llf = stats.boxcox_llf(lmbda, xp.asarray(x, dtype=dt))
+        llf_expected = -x.size / 2. * np.log(np.sum(x.std()**2))
+        xp_assert_close(llf, xp.asarray(llf_expected, dtype=dt))
+
+    @skip_xp_backends(np_only=True,
+                      reason='array-likes only accepted for NumPy backend.')
+    def test_array_like(self, xp):
+        x = stats.norm.rvs(size=100, loc=10, random_state=54321)
+        lmbda = 1
+        llf = stats.boxcox_llf(lmbda, x)
+        llf2 = stats.boxcox_llf(lmbda, list(x))
+        xp_assert_close(llf, llf2, rtol=1e-12)
+
+    def test_2d_input(self, xp):
+        # Note: boxcox_llf() was already working with 2-D input (sort of), so
+        # keep it like that.  boxcox() doesn't work with 2-D input though, due
+        # to brent() returning a scalar.
+        x = stats.norm.rvs(size=100, loc=10, random_state=54321)
+        lmbda = 1
+        llf = stats.boxcox_llf(lmbda, x)
+        llf2 = stats.boxcox_llf(lmbda, np.vstack([x, x]).T)
+        xp_assert_close(xp.asarray([llf, llf]), xp.asarray(llf2), rtol=1e-12)
+
+    def test_empty(self, xp):
+        assert xp.isnan(xp.asarray(stats.boxcox_llf(1, xp.asarray([]))))
+
+    def test_gh_6873(self, xp):
+        # Regression test for gh-6873.
+        # This example was taken from gh-7534, a duplicate of gh-6873.
+        data = xp.asarray([198.0, 233.0, 233.0, 392.0])
+        llf = stats.boxcox_llf(-8, data)
+        # The expected value was computed with mpmath.
+        xp_assert_close(llf, xp.asarray(-17.93934208579061))
+
+    def test_instability_gh20021(self, xp):
+        data = xp.asarray([2003, 1950, 1997, 2000, 2009])
+        llf = stats.boxcox_llf(1e-8, data)
+        # The expected value was computed with mpsci, set mpmath.mp.dps=100
+        # expect float64 output for integer input
+        xp_assert_close(llf, xp.asarray(-15.32401272869016598, dtype=xp.float64))
+
+
+# This is the data from GitHub user Qukaiyi, given as an example
+# of a data set that caused boxcox to fail.
+_boxcox_data = [
+    15957, 112079, 1039553, 711775, 173111, 307382, 183155, 53366, 760875,
+    207500, 160045, 473714, 40194, 440319, 133261, 265444, 155590, 36660,
+    904939, 55108, 138391, 339146, 458053, 63324, 1377727, 1342632, 41575,
+    68685, 172755, 63323, 368161, 199695, 538214, 167760, 388610, 398855,
+    1001873, 364591, 1320518, 194060, 194324, 2318551, 196114, 64225, 272000,
+    198668, 123585, 86420, 1925556, 695798, 88664, 46199, 759135, 28051,
+    345094, 1977752, 51778, 82746, 638126, 2560910, 45830, 140576, 1603787,
+    57371, 548730, 5343629, 2298913, 998813, 2156812, 423966, 68350, 145237,
+    131935, 1600305, 342359, 111398, 1409144, 281007, 60314, 242004, 113418,
+    246211, 61940, 95858, 957805, 40909, 307955, 174159, 124278, 241193,
+    872614, 304180, 146719, 64361, 87478, 509360, 167169, 933479, 620561,
+    483333, 97416, 143518, 286905, 597837, 2556043, 89065, 69944, 196858,
+    88883, 49379, 916265, 1527392, 626954, 54415, 89013, 2883386, 106096,
+    402697, 45578, 349852, 140379, 34648, 757343, 1305442, 2054757, 121232,
+    606048, 101492, 51426, 1820833, 83412, 136349, 1379924, 505977, 1303486,
+    95853, 146451, 285422, 2205423, 259020, 45864, 684547, 182014, 784334,
+    174793, 563068, 170745, 1195531, 63337, 71833, 199978, 2330904, 227335,
+    898280, 75294, 2011361, 116771, 157489, 807147, 1321443, 1148635, 2456524,
+    81839, 1228251, 97488, 1051892, 75397, 3009923, 2732230, 90923, 39735,
+    132433, 225033, 337555, 1204092, 686588, 1062402, 40362, 1361829, 1497217,
+    150074, 551459, 2019128, 39581, 45349, 1117187, 87845, 1877288, 164448,
+    10338362, 24942, 64737, 769946, 2469124, 2366997, 259124, 2667585, 29175,
+    56250, 74450, 96697, 5920978, 838375, 225914, 119494, 206004, 430907,
+    244083, 219495, 322239, 407426, 618748, 2087536, 2242124, 4736149, 124624,
+    406305, 240921, 2675273, 4425340, 821457, 578467, 28040, 348943, 48795,
+    145531, 52110, 1645730, 1768364, 348363, 85042, 2673847, 81935, 169075,
+    367733, 135474, 383327, 1207018, 93481, 5934183, 352190, 636533, 145870,
+    55659, 146215, 73191, 248681, 376907, 1606620, 169381, 81164, 246390,
+    236093, 885778, 335969, 49266, 381430, 307437, 350077, 34346, 49340,
+    84715, 527120, 40163, 46898, 4609439, 617038, 2239574, 159905, 118337,
+    120357, 430778, 3799158, 3516745, 54198, 2970796, 729239, 97848, 6317375,
+    887345, 58198, 88111, 867595, 210136, 1572103, 1420760, 574046, 845988,
+    509743, 397927, 1119016, 189955, 3883644, 291051, 126467, 1239907, 2556229,
+    411058, 657444, 2025234, 1211368, 93151, 577594, 4842264, 1531713, 305084,
+    479251, 20591, 1466166, 137417, 897756, 594767, 3606337, 32844, 82426,
+    1294831, 57174, 290167, 322066, 813146, 5671804, 4425684, 895607, 450598,
+    1048958, 232844, 56871, 46113, 70366, 701618, 97739, 157113, 865047,
+    194810, 1501615, 1765727, 38125, 2733376, 40642, 437590, 127337, 106310,
+    4167579, 665303, 809250, 1210317, 45750, 1853687, 348954, 156786, 90793,
+    1885504, 281501, 3902273, 359546, 797540, 623508, 3672775, 55330, 648221,
+    266831, 90030, 7118372, 735521, 1009925, 283901, 806005, 2434897, 94321,
+    309571, 4213597, 2213280, 120339, 64403, 8155209, 1686948, 4327743,
+    1868312, 135670, 3189615, 1569446, 706058, 58056, 2438625, 520619, 105201,
+    141961, 179990, 1351440, 3148662, 2804457, 2760144, 70775, 33807, 1926518,
+    2362142, 186761, 240941, 97860, 1040429, 1431035, 78892, 484039, 57845,
+    724126, 3166209, 175913, 159211, 1182095, 86734, 1921472, 513546, 326016,
+    1891609
+]
+
+
+class TestBoxcox:
+
+    def test_fixed_lmbda(self):
+        x = _old_loggamma_rvs(5, size=50, random_state=12345) + 5
+        xt = stats.boxcox(x, lmbda=1)
+        assert_allclose(xt, x - 1)
+        xt = stats.boxcox(x, lmbda=-1)
+        assert_allclose(xt, 1 - 1/x)
+
+        xt = stats.boxcox(x, lmbda=0)
+        assert_allclose(xt, np.log(x))
+
+        # Also test that array_like input works
+        xt = stats.boxcox(list(x), lmbda=0)
+        assert_allclose(xt, np.log(x))
+
+        # test that constant input is accepted; see gh-12225
+        xt = stats.boxcox(np.ones(10), 2)
+        assert_equal(xt, np.zeros(10))
+
+    def test_lmbda_None(self):
+        # Start from normal rv's, do inverse transform to check that
+        # optimization function gets close to the right answer.
+        lmbda = 2.5
+        x = stats.norm.rvs(loc=10, size=50000, random_state=1245)
+        x_inv = (x * lmbda + 1)**(-lmbda)
+        xt, maxlog = stats.boxcox(x_inv)
+
+        assert_almost_equal(maxlog, -1 / lmbda, decimal=2)
+
+    def test_alpha(self):
+        rng = np.random.RandomState(1234)
+        x = _old_loggamma_rvs(5, size=50, random_state=rng) + 5
+
+        # Some regular values for alpha, on a small sample size
+        _, _, interval = stats.boxcox(x, alpha=0.75)
+        assert_allclose(interval, [4.004485780226041, 5.138756355035744])
+        _, _, interval = stats.boxcox(x, alpha=0.05)
+        assert_allclose(interval, [1.2138178554857557, 8.209033272375663])
+
+        # Try some extreme values, see we don't hit the N=500 limit
+        x = _old_loggamma_rvs(7, size=500, random_state=rng) + 15
+        _, _, interval = stats.boxcox(x, alpha=0.001)
+        assert_allclose(interval, [0.3988867, 11.40553131])
+        _, _, interval = stats.boxcox(x, alpha=0.999)
+        assert_allclose(interval, [5.83316246, 5.83735292])
+
+    def test_boxcox_bad_arg(self):
+        # Raise ValueError if any data value is negative.
+        x = np.array([-1, 2])
+        assert_raises(ValueError, stats.boxcox, x)
+        # Raise ValueError if data is constant.
+        assert_raises(ValueError, stats.boxcox, np.array([1]))
+        # Raise ValueError if data is not 1-dimensional.
+        assert_raises(ValueError, stats.boxcox, np.array([[1], [2]]))
+
+    def test_empty(self):
+        assert_(stats.boxcox([]).shape == (0,))
+
+    def test_gh_6873(self):
+        # Regression test for gh-6873.
+        y, lam = stats.boxcox(_boxcox_data)
+        # The expected value of lam was computed with the function
+        # powerTransform in the R library 'car'.  I trust that value
+        # to only about five significant digits.
+        assert_allclose(lam, -0.051654, rtol=1e-5)
+
+    @pytest.mark.parametrize("bounds", [(-1, 1), (1.1, 2), (-2, -1.1)])
+    def test_bounded_optimizer_within_bounds(self, bounds):
+        # Define custom optimizer with bounds.
+        def optimizer(fun):
+            return optimize.minimize_scalar(fun, bounds=bounds,
+                                            method="bounded")
+
+        _, lmbda = stats.boxcox(_boxcox_data, lmbda=None, optimizer=optimizer)
+        assert bounds[0] < lmbda < bounds[1]
+
+    def test_bounded_optimizer_against_unbounded_optimizer(self):
+        # Test whether setting bounds on optimizer excludes solution from
+        # unbounded optimizer.
+
+        # Get unbounded solution.
+        _, lmbda = stats.boxcox(_boxcox_data, lmbda=None)
+
+        # Set tolerance and bounds around solution.
+        bounds = (lmbda + 0.1, lmbda + 1)
+        options = {'xatol': 1e-12}
+
+        def optimizer(fun):
+            return optimize.minimize_scalar(fun, bounds=bounds,
+                                            method="bounded", options=options)
+
+        # Check bounded solution. Lower bound should be active.
+        _, lmbda_bounded = stats.boxcox(_boxcox_data, lmbda=None,
+                                        optimizer=optimizer)
+        assert lmbda_bounded != lmbda
+        assert_allclose(lmbda_bounded, bounds[0])
+
+    @pytest.mark.parametrize("optimizer", ["str", (1, 2), 0.1])
+    def test_bad_optimizer_type_raises_error(self, optimizer):
+        # Check if error is raised if string, tuple or float is passed
+        with pytest.raises(ValueError, match="`optimizer` must be a callable"):
+            stats.boxcox(_boxcox_data, lmbda=None, optimizer=optimizer)
+
+    def test_bad_optimizer_value_raises_error(self):
+        # Check if error is raised if `optimizer` function does not return
+        # `OptimizeResult` object
+
+        # Define test function that always returns 1
+        def optimizer(fun):
+            return 1
+
+        message = "return an object containing the optimal `lmbda`"
+        with pytest.raises(ValueError, match=message):
+            stats.boxcox(_boxcox_data, lmbda=None, optimizer=optimizer)
+
+    @pytest.mark.parametrize(
+            "bad_x", [np.array([1, -42, 12345.6]), np.array([np.nan, 42, 1])]
+        )
+    def test_negative_x_value_raises_error(self, bad_x):
+        """Test boxcox_normmax raises ValueError if x contains non-positive values."""
+        message = "only positive, finite, real numbers"
+        with pytest.raises(ValueError, match=message):
+            stats.boxcox_normmax(bad_x)
+
+    @pytest.mark.parametrize('x', [
+        # Attempt to trigger overflow in power expressions.
+        np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0,
+                  2009.0, 1980.0, 1999.0, 2007.0, 1991.0]),
+        # Attempt to trigger overflow with a large optimal lambda.
+        np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0]),
+        # Attempt to trigger overflow with large data.
+        np.array([2003.0e200, 1950.0e200, 1997.0e200, 2000.0e200, 2009.0e200])
+    ])
+    def test_overflow(self, x):
+        with pytest.warns(UserWarning, match="The optimal lambda is"):
+            xt_bc, lam_bc = stats.boxcox(x)
+            assert np.all(np.isfinite(xt_bc))
+
+
+class TestBoxcoxNormmax:
+    def setup_method(self):
+        self.x = _old_loggamma_rvs(5, size=50, random_state=12345) + 5
+
+    def test_pearsonr(self):
+        maxlog = stats.boxcox_normmax(self.x)
+        assert_allclose(maxlog, 1.804465, rtol=1e-6)
+
+    def test_mle(self):
+        maxlog = stats.boxcox_normmax(self.x, method='mle')
+        assert_allclose(maxlog, 1.758101, rtol=1e-6)
+
+        # Check that boxcox() uses 'mle'
+        _, maxlog_boxcox = stats.boxcox(self.x)
+        assert_allclose(maxlog_boxcox, maxlog)
+
+    def test_all(self):
+        maxlog_all = stats.boxcox_normmax(self.x, method='all')
+        assert_allclose(maxlog_all, [1.804465, 1.758101], rtol=1e-6)
+
+    @pytest.mark.parametrize("method", ["mle", "pearsonr", "all"])
+    @pytest.mark.parametrize("bounds", [(-1, 1), (1.1, 2), (-2, -1.1)])
+    def test_bounded_optimizer_within_bounds(self, method, bounds):
+
+        def optimizer(fun):
+            return optimize.minimize_scalar(fun, bounds=bounds,
+                                            method="bounded")
+
+        maxlog = stats.boxcox_normmax(self.x, method=method,
+                                      optimizer=optimizer)
+        assert np.all(bounds[0] < maxlog)
+        assert np.all(maxlog < bounds[1])
+
+    @pytest.mark.slow
+    def test_user_defined_optimizer(self):
+        # tests an optimizer that is not based on scipy.optimize.minimize
+        lmbda = stats.boxcox_normmax(self.x)
+        lmbda_rounded = np.round(lmbda, 5)
+        lmbda_range = np.linspace(lmbda_rounded-0.01, lmbda_rounded+0.01, 1001)
+
+        class MyResult:
+            pass
+
+        def optimizer(fun):
+            # brute force minimum over the range
+            objs = []
+            for lmbda in lmbda_range:
+                objs.append(fun(lmbda))
+            res = MyResult()
+            res.x = lmbda_range[np.argmin(objs)]
+            return res
+
+        lmbda2 = stats.boxcox_normmax(self.x, optimizer=optimizer)
+        assert lmbda2 != lmbda                 # not identical
+        assert_allclose(lmbda2, lmbda, 1e-5)   # but as close as it should be
+
+    def test_user_defined_optimizer_and_brack_raises_error(self):
+        optimizer = optimize.minimize_scalar
+
+        # Using default `brack=None` with user-defined `optimizer` works as
+        # expected.
+        stats.boxcox_normmax(self.x, brack=None, optimizer=optimizer)
+
+        # Using user-defined `brack` with user-defined `optimizer` is expected
+        # to throw an error. Instead, users should specify
+        # optimizer-specific parameters in the optimizer function itself.
+        with pytest.raises(ValueError, match="`brack` must be None if "
+                                             "`optimizer` is given"):
+
+            stats.boxcox_normmax(self.x, brack=(-2.0, 2.0),
+                                 optimizer=optimizer)
+
+    @pytest.mark.parametrize(
+        'x', ([2003.0, 1950.0, 1997.0, 2000.0, 2009.0],
+              [0.50000471, 0.50004979, 0.50005902, 0.50009312, 0.50001632]))
+    def test_overflow(self, x):
+        message = "The optimal lambda is..."
+        with pytest.warns(UserWarning, match=message):
+            lmbda = stats.boxcox_normmax(x, method='mle')
+        assert np.isfinite(special.boxcox(x, lmbda)).all()
+        # 10000 is safety factor used in boxcox_normmax
+        ymax = np.finfo(np.float64).max / 10000
+        x_treme = np.max(x) if lmbda > 0 else np.min(x)
+        y_extreme = special.boxcox(x_treme, lmbda)
+        assert_allclose(y_extreme, ymax * np.sign(lmbda))
+
+    def test_negative_ymax(self):
+        with pytest.raises(ValueError, match="`ymax` must be strictly positive"):
+            stats.boxcox_normmax(self.x, ymax=-1)
+
+    @pytest.mark.parametrize("x", [
+        # positive overflow in float64
+        np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0],
+                 dtype=np.float64),
+        # negative overflow in float64
+        np.array([0.50000471, 0.50004979, 0.50005902, 0.50009312, 0.50001632],
+                 dtype=np.float64),
+        # positive overflow in float32
+        np.array([200.3, 195.0, 199.7, 200.0, 200.9],
+                 dtype=np.float32),
+        # negative overflow in float32
+        np.array([2e-30, 1e-30, 1e-30, 1e-30, 1e-30, 1e-30],
+                 dtype=np.float32),
+    ])
+    @pytest.mark.parametrize("ymax", [1e10, 1e30, None])
+    # TODO: add method "pearsonr" after fix overflow issue
+    @pytest.mark.parametrize("method", ["mle"])
+    def test_user_defined_ymax_input_float64_32(self, x, ymax, method):
+        # Test the maximum of the transformed data close to ymax
+        with pytest.warns(UserWarning, match="The optimal lambda is"):
+            kwarg = {'ymax': ymax} if ymax is not None else {}
+            lmb = stats.boxcox_normmax(x, method=method, **kwarg)
+            x_treme = [np.min(x), np.max(x)]
+            ymax_res = max(abs(stats.boxcox(x_treme, lmb)))
+            if ymax is None:
+                # 10000 is safety factor used in boxcox_normmax
+                ymax = np.finfo(x.dtype).max / 10000
+            assert_allclose(ymax, ymax_res, rtol=1e-5)
+
+    @pytest.mark.parametrize("x", [
+        # positive overflow in float32 but not float64
+        [200.3, 195.0, 199.7, 200.0, 200.9],
+        # negative overflow in float32 but not float64
+        [2e-30, 1e-30, 1e-30, 1e-30, 1e-30, 1e-30],
+    ])
+    # TODO: add method "pearsonr" after fix overflow issue
+    @pytest.mark.parametrize("method", ["mle"])
+    def test_user_defined_ymax_inf(self, x, method):
+        x_32 = np.asarray(x, dtype=np.float32)
+        x_64 = np.asarray(x, dtype=np.float64)
+
+        # assert overflow with float32 but not float64
+        with pytest.warns(UserWarning, match="The optimal lambda is"):
+            stats.boxcox_normmax(x_32, method=method)
+        stats.boxcox_normmax(x_64, method=method)
+
+        # compute the true optimal lambda then compare them
+        lmb_32 = stats.boxcox_normmax(x_32, ymax=np.inf, method=method)
+        lmb_64 = stats.boxcox_normmax(x_64, ymax=np.inf, method=method)
+        assert_allclose(lmb_32, lmb_64, rtol=1e-2)
+
+
+class TestBoxcoxNormplot:
+    def setup_method(self):
+        self.x = _old_loggamma_rvs(5, size=500, random_state=7654321) + 5
+
+    def test_basic(self):
+        N = 5
+        lmbdas, ppcc = stats.boxcox_normplot(self.x, -10, 10, N=N)
+        ppcc_expected = [0.57783375, 0.83610988, 0.97524311, 0.99756057,
+                         0.95843297]
+        assert_allclose(lmbdas, np.linspace(-10, 10, num=N))
+        assert_allclose(ppcc, ppcc_expected)
+
+    @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+    def test_plot_kwarg(self):
+        # Check with the matplotlib.pyplot module
+        fig = plt.figure()
+        ax = fig.add_subplot(111)
+        stats.boxcox_normplot(self.x, -20, 20, plot=plt)
+        fig.delaxes(ax)
+
+        # Check that a Matplotlib Axes object is accepted
+        ax = fig.add_subplot(111)
+        stats.boxcox_normplot(self.x, -20, 20, plot=ax)
+        plt.close()
+
+    def test_invalid_inputs(self):
+        # `lb` has to be larger than `la`
+        assert_raises(ValueError, stats.boxcox_normplot, self.x, 1, 0)
+        # `x` can not contain negative values
+        assert_raises(ValueError, stats.boxcox_normplot, [-1, 1], 0, 1)
+
+    def test_empty(self):
+        assert_(stats.boxcox_normplot([], 0, 1).size == 0)
+
+
+class TestYeojohnson_llf:
+
+    def test_array_like(self):
+        x = stats.norm.rvs(size=100, loc=0, random_state=54321)
+        lmbda = 1
+        llf = stats.yeojohnson_llf(lmbda, x)
+        llf2 = stats.yeojohnson_llf(lmbda, list(x))
+        assert_allclose(llf, llf2, rtol=1e-12)
+
+    def test_2d_input(self):
+        x = stats.norm.rvs(size=100, loc=10, random_state=54321)
+        lmbda = 1
+        llf = stats.yeojohnson_llf(lmbda, x)
+        llf2 = stats.yeojohnson_llf(lmbda, np.vstack([x, x]).T)
+        assert_allclose([llf, llf], llf2, rtol=1e-12)
+
+    def test_empty(self):
+        assert_(np.isnan(stats.yeojohnson_llf(1, [])))
+
+
+class TestYeojohnson:
+
+    def test_fixed_lmbda(self):
+        rng = np.random.RandomState(12345)
+
+        # Test positive input
+        x = _old_loggamma_rvs(5, size=50, random_state=rng) + 5
+        assert np.all(x > 0)
+        xt = stats.yeojohnson(x, lmbda=1)
+        assert_allclose(xt, x)
+        xt = stats.yeojohnson(x, lmbda=-1)
+        assert_allclose(xt, 1 - 1 / (x + 1))
+        xt = stats.yeojohnson(x, lmbda=0)
+        assert_allclose(xt, np.log(x + 1))
+        xt = stats.yeojohnson(x, lmbda=1)
+        assert_allclose(xt, x)
+
+        # Test negative input
+        x = _old_loggamma_rvs(5, size=50, random_state=rng) - 5
+        assert np.all(x < 0)
+        xt = stats.yeojohnson(x, lmbda=2)
+        assert_allclose(xt, -np.log(-x + 1))
+        xt = stats.yeojohnson(x, lmbda=1)
+        assert_allclose(xt, x)
+        xt = stats.yeojohnson(x, lmbda=3)
+        assert_allclose(xt, 1 / (-x + 1) - 1)
+
+        # test both positive and negative input
+        x = _old_loggamma_rvs(5, size=50, random_state=rng) - 2
+        assert not np.all(x < 0)
+        assert not np.all(x >= 0)
+        pos = x >= 0
+        xt = stats.yeojohnson(x, lmbda=1)
+        assert_allclose(xt[pos], x[pos])
+        xt = stats.yeojohnson(x, lmbda=-1)
+        assert_allclose(xt[pos], 1 - 1 / (x[pos] + 1))
+        xt = stats.yeojohnson(x, lmbda=0)
+        assert_allclose(xt[pos], np.log(x[pos] + 1))
+        xt = stats.yeojohnson(x, lmbda=1)
+        assert_allclose(xt[pos], x[pos])
+
+        neg = ~pos
+        xt = stats.yeojohnson(x, lmbda=2)
+        assert_allclose(xt[neg], -np.log(-x[neg] + 1))
+        xt = stats.yeojohnson(x, lmbda=1)
+        assert_allclose(xt[neg], x[neg])
+        xt = stats.yeojohnson(x, lmbda=3)
+        assert_allclose(xt[neg], 1 / (-x[neg] + 1) - 1)
+
+    @pytest.mark.parametrize('lmbda', [0, .1, .5, 2])
+    def test_lmbda_None(self, lmbda):
+        # Start from normal rv's, do inverse transform to check that
+        # optimization function gets close to the right answer.
+
+        def _inverse_transform(x, lmbda):
+            x_inv = np.zeros(x.shape, dtype=x.dtype)
+            pos = x >= 0
+
+            # when x >= 0
+            if abs(lmbda) < np.spacing(1.):
+                x_inv[pos] = np.exp(x[pos]) - 1
+            else:  # lmbda != 0
+                x_inv[pos] = np.power(x[pos] * lmbda + 1, 1 / lmbda) - 1
+
+            # when x < 0
+            if abs(lmbda - 2) > np.spacing(1.):
+                x_inv[~pos] = 1 - np.power(-(2 - lmbda) * x[~pos] + 1,
+                                           1 / (2 - lmbda))
+            else:  # lmbda == 2
+                x_inv[~pos] = 1 - np.exp(-x[~pos])
+
+            return x_inv
+
+        n_samples = 20000
+        np.random.seed(1234567)
+        x = np.random.normal(loc=0, scale=1, size=(n_samples))
+
+        x_inv = _inverse_transform(x, lmbda)
+        xt, maxlog = stats.yeojohnson(x_inv)
+
+        assert_allclose(maxlog, lmbda, atol=1e-2)
+
+        assert_almost_equal(0, np.linalg.norm(x - xt) / n_samples, decimal=2)
+        assert_almost_equal(0, xt.mean(), decimal=1)
+        assert_almost_equal(1, xt.std(), decimal=1)
+
+    def test_empty(self):
+        assert_(stats.yeojohnson([]).shape == (0,))
+
+    def test_array_like(self):
+        x = stats.norm.rvs(size=100, loc=0, random_state=54321)
+        xt1, _ = stats.yeojohnson(x)
+        xt2, _ = stats.yeojohnson(list(x))
+        assert_allclose(xt1, xt2, rtol=1e-12)
+
+    @pytest.mark.parametrize('dtype', [np.complex64, np.complex128])
+    def test_input_dtype_complex(self, dtype):
+        x = np.arange(6, dtype=dtype)
+        err_msg = ('Yeo-Johnson transformation is not defined for complex '
+                   'numbers.')
+        with pytest.raises(ValueError, match=err_msg):
+            stats.yeojohnson(x)
+
+    @pytest.mark.parametrize('dtype', [np.int8, np.uint8, np.int16, np.int32])
+    def test_input_dtype_integer(self, dtype):
+        x_int = np.arange(8, dtype=dtype)
+        x_float = np.arange(8, dtype=np.float64)
+        xt_int, lmbda_int = stats.yeojohnson(x_int)
+        xt_float, lmbda_float = stats.yeojohnson(x_float)
+        assert_allclose(xt_int, xt_float, rtol=1e-7)
+        assert_allclose(lmbda_int, lmbda_float, rtol=1e-7)
+
+    def test_input_high_variance(self):
+        # non-regression test for gh-10821
+        x = np.array([3251637.22, 620695.44, 11642969.00, 2223468.22,
+                      85307500.00, 16494389.89, 917215.88, 11642969.00,
+                      2145773.87, 4962000.00, 620695.44, 651234.50,
+                      1907876.71, 4053297.88, 3251637.22, 3259103.08,
+                      9547969.00, 20631286.23, 12807072.08, 2383819.84,
+                      90114500.00, 17209575.46, 12852969.00, 2414609.99,
+                      2170368.23])
+        xt_yeo, lam_yeo = stats.yeojohnson(x)
+        xt_box, lam_box = stats.boxcox(x + 1)
+        assert_allclose(xt_yeo, xt_box, rtol=1e-6)
+        assert_allclose(lam_yeo, lam_box, rtol=1e-6)
+
+    @pytest.mark.parametrize('x', [
+        np.array([1.0, float("nan"), 2.0]),
+        np.array([1.0, float("inf"), 2.0]),
+        np.array([1.0, -float("inf"), 2.0]),
+        np.array([-1.0, float("nan"), float("inf"), -float("inf"), 1.0])
+    ])
+    def test_nonfinite_input(self, x):
+        with pytest.raises(ValueError, match='Yeo-Johnson input must be finite'):
+            xt_yeo, lam_yeo = stats.yeojohnson(x)
+
+    @pytest.mark.parametrize('x', [
+        # Attempt to trigger overflow in power expressions.
+        np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0,
+                  2009.0, 1980.0, 1999.0, 2007.0, 1991.0]),
+        # Attempt to trigger overflow with a large optimal lambda.
+        np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0]),
+        # Attempt to trigger overflow with large data.
+        np.array([2003.0e200, 1950.0e200, 1997.0e200, 2000.0e200, 2009.0e200])
+    ])
+    def test_overflow(self, x):
+        # non-regression test for gh-18389
+
+        def optimizer(fun, lam_yeo):
+            out = optimize.fminbound(fun, -lam_yeo, lam_yeo, xtol=1.48e-08)
+            result = optimize.OptimizeResult()
+            result.x = out
+            return result
+
+        with np.errstate(all="raise"):
+            xt_yeo, lam_yeo = stats.yeojohnson(x)
+            xt_box, lam_box = stats.boxcox(
+                x + 1, optimizer=partial(optimizer, lam_yeo=lam_yeo))
+            assert np.isfinite(np.var(xt_yeo))
+            assert np.isfinite(np.var(xt_box))
+            assert_allclose(lam_yeo, lam_box, rtol=1e-6)
+            assert_allclose(xt_yeo, xt_box, rtol=1e-4)
+
+    @pytest.mark.parametrize('x', [
+        np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0,
+                  2009.0, 1980.0, 1999.0, 2007.0, 1991.0]),
+        np.array([2003.0, 1950.0, 1997.0, 2000.0, 2009.0])
+    ])
+    @pytest.mark.parametrize('scale', [1, 1e-12, 1e-32, 1e-150, 1e32, 1e200])
+    @pytest.mark.parametrize('sign', [1, -1])
+    def test_overflow_underflow_signed_data(self, x, scale, sign):
+        # non-regression test for gh-18389
+        with np.errstate(all="raise"):
+            xt_yeo, lam_yeo = stats.yeojohnson(sign * x * scale)
+            assert np.all(np.sign(sign * x) == np.sign(xt_yeo))
+            assert np.isfinite(lam_yeo)
+            assert np.isfinite(np.var(xt_yeo))
+
+    @pytest.mark.parametrize('x', [
+        np.array([0, 1, 2, 3]),
+        np.array([0, -1, 2, -3]),
+        np.array([0, 0, 0])
+    ])
+    @pytest.mark.parametrize('sign', [1, -1])
+    @pytest.mark.parametrize('brack', [None, (-2, 2)])
+    def test_integer_signed_data(self, x, sign, brack):
+        with np.errstate(all="raise"):
+            x_int = sign * x
+            x_float = x_int.astype(np.float64)
+            lam_yeo_int = stats.yeojohnson_normmax(x_int, brack=brack)
+            xt_yeo_int = stats.yeojohnson(x_int, lmbda=lam_yeo_int)
+            lam_yeo_float = stats.yeojohnson_normmax(x_float, brack=brack)
+            xt_yeo_float = stats.yeojohnson(x_float, lmbda=lam_yeo_float)
+            assert np.all(np.sign(x_int) == np.sign(xt_yeo_int))
+            assert np.isfinite(lam_yeo_int)
+            assert np.isfinite(np.var(xt_yeo_int))
+            assert lam_yeo_int == lam_yeo_float
+            assert np.all(xt_yeo_int == xt_yeo_float)
+
+
+class TestYeojohnsonNormmax:
+    def setup_method(self):
+        self.x = _old_loggamma_rvs(5, size=50, random_state=12345) + 5
+
+    def test_mle(self):
+        maxlog = stats.yeojohnson_normmax(self.x)
+        assert_allclose(maxlog, 1.876393, rtol=1e-6)
+
+    def test_darwin_example(self):
+        # test from original paper "A new family of power transformations to
+        # improve normality or symmetry" by Yeo and Johnson.
+        x = [6.1, -8.4, 1.0, 2.0, 0.7, 2.9, 3.5, 5.1, 1.8, 3.6, 7.0, 3.0, 9.3,
+             7.5, -6.0]
+        lmbda = stats.yeojohnson_normmax(x)
+        assert np.allclose(lmbda, 1.305, atol=1e-3)
+
+
+@array_api_compatible
+class TestCircFuncs:
+    # In gh-5747, the R package `circular` was used to calculate reference
+    # values for the circular variance, e.g.:
+    # library(circular)
+    # options(digits=16)
+    # x = c(0, 2*pi/3, 5*pi/3)
+    # var.circular(x)
+    @pytest.mark.parametrize("test_func,expected",
+                             [(stats.circmean, 0.167690146),
+                              (stats.circvar, 0.006455174000787767),
+                              (stats.circstd, 6.520702116)])
+    def test_circfuncs(self, test_func, expected, xp):
+        x = xp.asarray([355., 5., 2., 359., 10., 350.])
+        xp_assert_close(test_func(x, high=360), xp.asarray(expected))
+
+    def test_circfuncs_small(self, xp):
+        # Default tolerances won't work here because the reference values
+        # are approximations. Ensure all array types work in float64 to
+        # avoid needing separate float32 and float64 tolerances.
+        x = xp.asarray([20, 21, 22, 18, 19, 20.5, 19.2], dtype=xp.float64)
+        M1 = xp.mean(x)
+        M2 = stats.circmean(x, high=360)
+        xp_assert_close(M2, M1, rtol=1e-5)
+
+        # plain torch var/std ddof=1, so we need array_api_compat torch
+        xp_test = array_namespace(x)
+        V1 = xp_test.var(x*xp.pi/180, correction=0)
+        # for small variations, circvar is approximately half the
+        # linear variance
+        V1 = V1 / 2.
+        V2 = stats.circvar(x, high=360)
+        xp_assert_close(V2, V1, rtol=1e-4)
+
+        S1 = xp_test.std(x, correction=0)
+        S2 = stats.circstd(x, high=360)
+        xp_assert_close(S2, S1, rtol=1e-4)
+
+    @pytest.mark.parametrize("test_func, numpy_func",
+                             [(stats.circmean, np.mean),
+                              (stats.circvar, np.var),
+                              (stats.circstd, np.std)])
+    def test_circfuncs_close(self, test_func, numpy_func, xp):
+        # circfuncs should handle very similar inputs (gh-12740)
+        x = np.asarray([0.12675364631578953] * 10 + [0.12675365920187928] * 100)
+        circstat = test_func(xp.asarray(x))
+        normal = xp.asarray(numpy_func(x))
+        xp_assert_close(circstat, normal, atol=2e-8)
+
+    @pytest.mark.parametrize('circfunc', [stats.circmean,
+                                          stats.circvar,
+                                          stats.circstd])
+    def test_circmean_axis(self, xp, circfunc):
+        x = xp.asarray([[355, 5, 2, 359, 10, 350],
+                        [351, 7, 4, 352, 9, 349],
+                        [357, 9, 8, 358, 4, 356.]])
+        res = circfunc(x, high=360)
+        ref = circfunc(xp.reshape(x, (-1,)), high=360)
+        xp_assert_close(res, xp.asarray(ref))
+
+        res = circfunc(x, high=360, axis=1)
+        ref = [circfunc(x[i, :], high=360) for i in range(x.shape[0])]
+        xp_assert_close(res, xp.asarray(ref))
+
+        res = circfunc(x, high=360, axis=0)
+        ref = [circfunc(x[:, i], high=360) for i in range(x.shape[1])]
+        xp_assert_close(res, xp.asarray(ref))
+
+    @pytest.mark.parametrize("test_func,expected",
+                             [(stats.circmean, 0.167690146),
+                              (stats.circvar, 0.006455174270186603),
+                              (stats.circstd, 6.520702116)])
+    def test_circfuncs_array_like(self, test_func, expected, xp):
+        x = xp.asarray([355, 5, 2, 359, 10, 350.])
+        xp_assert_close(test_func(x, high=360), xp.asarray(expected))
+
+    @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar,
+                                           stats.circstd])
+    def test_empty(self, test_func, xp):
+        dtype = xp.float64
+        x = xp.asarray([], dtype=dtype)
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = test_func(x)
+        else:
+            with np.testing.suppress_warnings() as sup:
+                # for array_api_strict
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                sup.filter(RuntimeWarning, "invalid value encountered")
+                res = test_func(x)
+        xp_assert_equal(res, xp.asarray(xp.nan, dtype=dtype))
+
+    @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar,
+                                           stats.circstd])
+    def test_nan_propagate(self, test_func, xp):
+        x = xp.asarray([355, 5, 2, 359, 10, 350, np.nan])
+        xp_assert_equal(test_func(x, high=360), xp.asarray(xp.nan))
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.parametrize("test_func,expected",
+                             [(stats.circmean,
+                               {None: np.nan, 0: 355.66582264, 1: 0.28725053}),
+                              (stats.circvar,
+                               {None: np.nan,
+                                0: 0.002570671054089924,
+                                1: 0.005545914017677123}),
+                              (stats.circstd,
+                               {None: np.nan, 0: 4.11093193, 1: 6.04265394})])
+    def test_nan_propagate_array(self, test_func, expected, xp):
+        x = xp.asarray([[355, 5, 2, 359, 10, 350, 1],
+                        [351, 7, 4, 352, 9, 349, np.nan],
+                        [1, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]])
+        for axis in expected.keys():
+            out = test_func(x, high=360, axis=axis)
+            if axis is None:
+                xp_assert_equal(out, xp.asarray(xp.nan))
+            else:
+                xp_assert_close(out[0], xp.asarray(expected[axis]))
+                xp_assert_equal(out[1:], xp.full_like(out[1:], xp.nan))
+
+    def test_circmean_scalar(self, xp):
+        x = xp.asarray(1.)[()]
+        M1 = x
+        M2 = stats.circmean(x)
+        xp_assert_close(M2, M1, rtol=1e-5)
+
+    def test_circmean_range(self, xp):
+        # regression test for gh-6420: circmean(..., high, low) must be
+        # between `high` and `low`
+        m = stats.circmean(xp.arange(0, 2, 0.1), xp.pi, -xp.pi)
+        xp_assert_less(m, xp.asarray(xp.pi))
+        xp_assert_less(-m, xp.asarray(xp.pi))
+
+    def test_circfuncs_uint8(self, xp):
+        # regression test for gh-7255: overflow when working with
+        # numpy uint8 data type
+        x = xp.asarray([150, 10], dtype=xp.uint8)
+        xp_assert_close(stats.circmean(x, high=180), xp.asarray(170.0))
+        xp_assert_close(stats.circvar(x, high=180), xp.asarray(0.2339555554617))
+        xp_assert_close(stats.circstd(x, high=180), xp.asarray(20.91551378))
+
+    def test_circstd_zero(self, xp):
+        # circstd() of a single number should return positive zero.
+        y = stats.circstd(xp.asarray([0]))
+        assert math.copysign(1.0, y) == 1.0
+
+    def test_circmean_accuracy_tiny_input(self, xp):
+        # For tiny x such that sin(x) == x and cos(x) == 1.0 numerically,
+        # circmean(x) should return x because atan2(sin(x), cos(x)) == x.
+        # This test verifies this.
+        #
+        # The purpose of this test is not to show that circmean() is
+        # accurate in the last digit for certain input, because this is
+        # neither guaranteed not particularly useful.  Rather, it is a
+        # "white-box" sanity check that no undue loss of precision is
+        # introduced by conversion between (high - low) and (2 * pi).
+
+        x = xp.linspace(1e-9, 1e-8, 100)
+        assert xp.all(xp.sin(x) == x) and xp.all(xp.cos(x) == 1.0)
+
+        m = (x * (2 * xp.pi) / (2 * xp.pi)) != x
+        assert xp.any(m)
+        x = x[m]
+
+        y = stats.circmean(x[:, None], axis=1)
+        assert xp.all(y == x)
+
+    def test_circmean_accuracy_huge_input(self, xp):
+        # White-box test that circmean() does not introduce undue loss of
+        # numerical accuracy by eagerly rotating the input.  This is detected
+        # by supplying a huge input x such that (x - low) == x numerically.
+        x = xp.asarray(1e17, dtype=xp.float64)
+        y = math.atan2(xp.sin(x), xp.cos(x))  # -2.6584887370946806
+        expected = xp.asarray(y, dtype=xp.float64)
+        actual = stats.circmean(x, high=xp.pi, low=-xp.pi)
+        xp_assert_close(actual, expected, rtol=1e-15, atol=0.0)
+
+
+class TestCircFuncsNanPolicy:
+    # `nan_policy` is implemented by the `_axis_nan_policy` decorator, which is
+    # not yet array-API compatible. When it is array-API compatible, the generic
+    # tests run on every function will be much stronger than these, so these
+    # will not be necessary. So I don't see a need to make these array-API compatible;
+    # when the time comes, they can just be removed.
+    @pytest.mark.parametrize("test_func,expected",
+                             [(stats.circmean,
+                               {None: 359.4178026893944,
+                                0: np.array([353.0, 6.0, 3.0, 355.5, 9.5,
+                                             349.5]),
+                                1: np.array([0.16769015, 358.66510252])}),
+                              (stats.circvar,
+                               {None: 0.008396678483192477,
+                                0: np.array([1.9997969, 0.4999873, 0.4999873,
+                                             6.1230956, 0.1249992, 0.1249992]
+                                            )*(np.pi/180)**2,
+                                1: np.array([0.006455174270186603,
+                                             0.01016767581393285])}),
+                              (stats.circstd,
+                               {None: 7.440570778057074,
+                                0: np.array([2.00020313, 1.00002539, 1.00002539,
+                                             3.50108929, 0.50000317,
+                                             0.50000317]),
+                                1: np.array([6.52070212, 8.19138093])})])
+    def test_nan_omit_array(self, test_func, expected):
+        x = np.array([[355, 5, 2, 359, 10, 350, np.nan],
+                      [351, 7, 4, 352, 9, 349, np.nan],
+                      [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]])
+        for axis in expected.keys():
+            if axis is None:
+                out = test_func(x, high=360, nan_policy='omit', axis=axis)
+                assert_allclose(out, expected[axis], rtol=1e-7)
+            else:
+                with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
+                    out = test_func(x, high=360, nan_policy='omit', axis=axis)
+                    assert_allclose(out[:-1], expected[axis], rtol=1e-7)
+                    assert_(np.isnan(out[-1]))
+
+    @pytest.mark.parametrize("test_func,expected",
+                             [(stats.circmean, 0.167690146),
+                              (stats.circvar, 0.006455174270186603),
+                              (stats.circstd, 6.520702116)])
+    def test_nan_omit(self, test_func, expected):
+        x = [355, 5, 2, 359, 10, 350, np.nan]
+        assert_allclose(test_func(x, high=360, nan_policy='omit'),
+                        expected, rtol=1e-7)
+
+    @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar,
+                                           stats.circstd])
+    def test_nan_omit_all(self, test_func):
+        x = [np.nan, np.nan, np.nan, np.nan, np.nan]
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_omit):
+            assert_(np.isnan(test_func(x, nan_policy='omit')))
+
+    @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar,
+                                           stats.circstd])
+    def test_nan_omit_all_axis(self, test_func):
+        with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
+            x = np.array([[np.nan, np.nan, np.nan, np.nan, np.nan],
+                          [np.nan, np.nan, np.nan, np.nan, np.nan]])
+            out = test_func(x, nan_policy='omit', axis=1)
+            assert_(np.isnan(out).all())
+            assert_(len(out) == 2)
+
+    @pytest.mark.parametrize("x",
+                             [[355, 5, 2, 359, 10, 350, np.nan],
+                              np.array([[355, 5, 2, 359, 10, 350, np.nan],
+                                        [351, 7, 4, 352, np.nan, 9, 349]])])
+    @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar,
+                                           stats.circstd])
+    def test_nan_raise(self, test_func, x):
+        assert_raises(ValueError, test_func, x, high=360, nan_policy='raise')
+
+    @pytest.mark.parametrize("x",
+                             [[355, 5, 2, 359, 10, 350, np.nan],
+                              np.array([[355, 5, 2, 359, 10, 350, np.nan],
+                                        [351, 7, 4, 352, np.nan, 9, 349]])])
+    @pytest.mark.parametrize("test_func", [stats.circmean, stats.circvar,
+                                           stats.circstd])
+    def test_bad_nan_policy(self, test_func, x):
+        assert_raises(ValueError, test_func, x, high=360, nan_policy='foobar')
+
+
+class TestMedianTest:
+
+    def test_bad_n_samples(self):
+        # median_test requires at least two samples.
+        assert_raises(ValueError, stats.median_test, [1, 2, 3])
+
+    def test_empty_sample(self):
+        # Each sample must contain at least one value.
+        assert_raises(ValueError, stats.median_test, [], [1, 2, 3])
+
+    def test_empty_when_ties_ignored(self):
+        # The grand median is 1, and all values in the first argument are
+        # equal to the grand median.  With ties="ignore", those values are
+        # ignored, which results in the first sample being (in effect) empty.
+        # This should raise a ValueError.
+        assert_raises(ValueError, stats.median_test,
+                      [1, 1, 1, 1], [2, 0, 1], [2, 0], ties="ignore")
+
+    def test_empty_contingency_row(self):
+        # The grand median is 1, and with the default ties="below", all the
+        # values in the samples are counted as being below the grand median.
+        # This would result a row of zeros in the contingency table, which is
+        # an error.
+        assert_raises(ValueError, stats.median_test, [1, 1, 1], [1, 1, 1])
+
+        # With ties="above", all the values are counted as above the
+        # grand median.
+        assert_raises(ValueError, stats.median_test, [1, 1, 1], [1, 1, 1],
+                      ties="above")
+
+    def test_bad_ties(self):
+        assert_raises(ValueError, stats.median_test, [1, 2, 3], [4, 5],
+                      ties="foo")
+
+    def test_bad_nan_policy(self):
+        assert_raises(ValueError, stats.median_test, [1, 2, 3], [4, 5],
+                      nan_policy='foobar')
+
+    def test_bad_keyword(self):
+        assert_raises(TypeError, stats.median_test, [1, 2, 3], [4, 5],
+                      foo="foo")
+
+    def test_simple(self):
+        x = [1, 2, 3]
+        y = [1, 2, 3]
+        stat, p, med, tbl = stats.median_test(x, y)
+
+        # The median is floating point, but this equality test should be safe.
+        assert_equal(med, 2.0)
+
+        assert_array_equal(tbl, [[1, 1], [2, 2]])
+
+        # The expected values of the contingency table equal the contingency
+        # table, so the statistic should be 0 and the p-value should be 1.
+        assert_equal(stat, 0)
+        assert_equal(p, 1)
+
+    def test_ties_options(self):
+        # Test the contingency table calculation.
+        x = [1, 2, 3, 4]
+        y = [5, 6]
+        z = [7, 8, 9]
+        # grand median is 5.
+
+        # Default 'ties' option is "below".
+        stat, p, m, tbl = stats.median_test(x, y, z)
+        assert_equal(m, 5)
+        assert_equal(tbl, [[0, 1, 3], [4, 1, 0]])
+
+        stat, p, m, tbl = stats.median_test(x, y, z, ties="ignore")
+        assert_equal(m, 5)
+        assert_equal(tbl, [[0, 1, 3], [4, 0, 0]])
+
+        stat, p, m, tbl = stats.median_test(x, y, z, ties="above")
+        assert_equal(m, 5)
+        assert_equal(tbl, [[0, 2, 3], [4, 0, 0]])
+
+    def test_nan_policy_options(self):
+        x = [1, 2, np.nan]
+        y = [4, 5, 6]
+        mt1 = stats.median_test(x, y, nan_policy='propagate')
+        s, p, m, t = stats.median_test(x, y, nan_policy='omit')
+
+        assert_equal(mt1, (np.nan, np.nan, np.nan, None))
+        assert_allclose(s, 0.31250000000000006)
+        assert_allclose(p, 0.57615012203057869)
+        assert_equal(m, 4.0)
+        assert_equal(t, np.array([[0, 2], [2, 1]]))
+        assert_raises(ValueError, stats.median_test, x, y, nan_policy='raise')
+
+    def test_basic(self):
+        # median_test calls chi2_contingency to compute the test statistic
+        # and p-value.  Make sure it hasn't screwed up the call...
+
+        x = [1, 2, 3, 4, 5]
+        y = [2, 4, 6, 8]
+
+        stat, p, m, tbl = stats.median_test(x, y)
+        assert_equal(m, 4)
+        assert_equal(tbl, [[1, 2], [4, 2]])
+
+        exp_stat, exp_p, dof, e = stats.chi2_contingency(tbl)
+        assert_allclose(stat, exp_stat)
+        assert_allclose(p, exp_p)
+
+        stat, p, m, tbl = stats.median_test(x, y, lambda_=0)
+        assert_equal(m, 4)
+        assert_equal(tbl, [[1, 2], [4, 2]])
+
+        exp_stat, exp_p, dof, e = stats.chi2_contingency(tbl, lambda_=0)
+        assert_allclose(stat, exp_stat)
+        assert_allclose(p, exp_p)
+
+        stat, p, m, tbl = stats.median_test(x, y, correction=False)
+        assert_equal(m, 4)
+        assert_equal(tbl, [[1, 2], [4, 2]])
+
+        exp_stat, exp_p, dof, e = stats.chi2_contingency(tbl, correction=False)
+        assert_allclose(stat, exp_stat)
+        assert_allclose(p, exp_p)
+
+    @pytest.mark.parametrize("correction", [False, True])
+    def test_result(self, correction):
+        x = [1, 2, 3]
+        y = [1, 2, 3]
+
+        res = stats.median_test(x, y, correction=correction)
+        assert_equal((res.statistic, res.pvalue, res.median, res.table), res)
+
+@array_api_compatible
+class TestDirectionalStats:
+    # Reference implementations are not available
+    def test_directional_stats_correctness(self, xp):
+        # Data from Fisher: Dispersion on a sphere, 1953 and
+        # Mardia and Jupp, Directional Statistics.
+        decl = -np.deg2rad(np.array([343.2, 62., 36.9, 27., 359.,
+                                     5.7, 50.4, 357.6, 44.]))
+        incl = -np.deg2rad(np.array([66.1, 68.7, 70.1, 82.1, 79.5,
+                                     73., 69.3, 58.8, 51.4]))
+        data = np.stack((np.cos(incl) * np.cos(decl),
+                         np.cos(incl) * np.sin(decl),
+                         np.sin(incl)),
+                        axis=1)
+        
+        decl = xp.asarray(decl.tolist())
+        incl = xp.asarray(incl.tolist())
+        data = xp.asarray(data.tolist())
+
+        dirstats = stats.directional_stats(data)
+        directional_mean = dirstats.mean_direction
+
+        reference_mean = xp.asarray([0.2984, -0.1346, -0.9449])
+        xp_assert_close(directional_mean, reference_mean, atol=1e-4)
+
+    @pytest.mark.parametrize('angles, ref', [
+        ([-np.pi/2, np.pi/2], 1.),
+        ([0, 2 * np.pi], 0.)
+    ])
+    def test_directional_stats_2d_special_cases(self, angles, ref, xp):
+        angles = xp.asarray(angles)
+        ref = xp.asarray(ref)
+        data = xp.stack([xp.cos(angles), xp.sin(angles)], axis=1)
+        res = 1 - stats.directional_stats(data).mean_resultant_length
+        xp_assert_close(res, ref)
+
+    def test_directional_stats_2d(self, xp):
+        # Test that for circular data directional_stats
+        # yields the same result as circmean/circvar
+        rng = np.random.default_rng(0xec9a6899d5a2830e0d1af479dbe1fd0c)
+        testdata = xp.asarray(2 * xp.pi * rng.random((1000, )))
+        testdata_vector = xp.stack((xp.cos(testdata),
+                                    xp.sin(testdata)),
+                                   axis=1)
+        dirstats = stats.directional_stats(testdata_vector)
+        directional_mean = dirstats.mean_direction
+        xp_test = array_namespace(directional_mean)  # np needs atan2
+        directional_mean_angle = xp_test.atan2(directional_mean[1],
+                                               directional_mean[0])
+        directional_mean_angle = directional_mean_angle % (2 * xp.pi)
+        circmean = stats.circmean(testdata)
+        xp_assert_close(directional_mean_angle, circmean)
+
+        directional_var = 1. - dirstats.mean_resultant_length
+        circular_var = stats.circvar(testdata)
+        xp_assert_close(directional_var, circular_var)
+
+    def test_directional_mean_higher_dim(self, xp):
+        # test that directional_stats works for higher dimensions
+        # here a 4D array is reduced over axis = 2
+        data = xp.asarray([[0.8660254, 0.5, 0.],
+                           [0.8660254, -0.5, 0.]])
+        full_array = xp.asarray(xp.tile(data, (2, 2, 2, 1)))
+        expected = xp.asarray([[[1., 0., 0.],
+                                [1., 0., 0.]],
+                               [[1., 0., 0.],
+                                [1., 0., 0.]]])
+        dirstats = stats.directional_stats(full_array, axis=2)
+        xp_assert_close(dirstats.mean_direction, expected)
+
+    @skip_xp_backends(np_only=True, reason='checking array-like input')
+    def test_directional_stats_list_ndarray_input(self, xp):
+        # test that list and numpy array inputs yield same results
+        data = [[0.8660254, 0.5, 0.], [0.8660254, -0.5, 0]]
+        data_array = xp.asarray(data, dtype=xp.float64)
+        ref = stats.directional_stats(data)
+        res = stats.directional_stats(data_array)
+        xp_assert_close(res.mean_direction,
+                        xp.asarray(ref.mean_direction))
+        xp_assert_close(res.mean_resultant_length,
+                        xp.asarray(res.mean_resultant_length))
+
+    def test_directional_stats_1d_error(self, xp):
+        # test that one-dimensional data raises ValueError
+        data = xp.ones((5, ))
+        message = (r"samples must at least be two-dimensional. "
+                   r"Instead samples has shape: (5,)")
+        with pytest.raises(ValueError, match=re.escape(message)):
+            stats.directional_stats(data)
+
+    @pytest.mark.parametrize("dtype", ["float32", "float64"])
+    def test_directional_stats_normalize(self, dtype, xp):
+        # test that directional stats calculations yield same results
+        # for unnormalized input with normalize=True and normalized
+        # input with normalize=False
+        data = np.array([[0.8660254, 0.5, 0.],
+                         [1.7320508, -1., 0.]], dtype=dtype)
+        res = stats.directional_stats(xp.asarray(data), normalize=True)
+        normalized_data = data / np.linalg.norm(data, axis=-1,
+                                                keepdims=True)
+        ref = stats.directional_stats(normalized_data, normalize=False)
+        xp_assert_close(res.mean_direction,
+                        xp.asarray(ref.mean_direction))
+        xp_assert_close(res.mean_resultant_length,
+                        xp.asarray(ref.mean_resultant_length))
+
+
+class TestFDRControl:
+    def test_input_validation(self):
+        message = "`ps` must include only numbers between 0 and 1"
+        with pytest.raises(ValueError, match=message):
+            stats.false_discovery_control([-1, 0.5, 0.7])
+        with pytest.raises(ValueError, match=message):
+            stats.false_discovery_control([0.5, 0.7, 2])
+        with pytest.raises(ValueError, match=message):
+            stats.false_discovery_control([0.5, 0.7, np.nan])
+
+        message = "Unrecognized `method` 'YAK'"
+        with pytest.raises(ValueError, match=message):
+            stats.false_discovery_control([0.5, 0.7, 0.9], method='YAK')
+
+        message = "`axis` must be an integer or `None`"
+        with pytest.raises(ValueError, match=message):
+            stats.false_discovery_control([0.5, 0.7, 0.9], axis=1.5)
+        with pytest.raises(ValueError, match=message):
+            stats.false_discovery_control([0.5, 0.7, 0.9], axis=(1, 2))
+
+    def test_against_TileStats(self):
+        # See reference [3] of false_discovery_control
+        ps = [0.005, 0.009, 0.019, 0.022, 0.051, 0.101, 0.361, 0.387]
+        res = stats.false_discovery_control(ps)
+        ref = [0.036, 0.036, 0.044, 0.044, 0.082, 0.135, 0.387, 0.387]
+        assert_allclose(res, ref, atol=1e-3)
+
+    @pytest.mark.parametrize("case",
+                             [([0.24617028, 0.01140030, 0.05652047, 0.06841983,
+                                0.07989886, 0.01841490, 0.17540784, 0.06841983,
+                                0.06841983, 0.25464082], 'bh'),
+                              ([0.72102493, 0.03339112, 0.16554665, 0.20039952,
+                                0.23402122, 0.05393666, 0.51376399, 0.20039952,
+                                0.20039952, 0.74583488], 'by')])
+    def test_against_R(self, case):
+        # Test against p.adjust, e.g.
+        # p = c(0.22155325, 0.00114003,..., 0.0364813 , 0.25464082)
+        # p.adjust(p, "BY")
+        ref, method = case
+        rng = np.random.default_rng(6134137338861652935)
+        ps = stats.loguniform.rvs(1e-3, 0.5, size=10, random_state=rng)
+        ps[3] = ps[7]  # force a tie
+        res = stats.false_discovery_control(ps, method=method)
+        assert_allclose(res, ref, atol=1e-6)
+
+    def test_axis_None(self):
+        rng = np.random.default_rng(6134137338861652935)
+        ps = stats.loguniform.rvs(1e-3, 0.5, size=(3, 4, 5), random_state=rng)
+        res = stats.false_discovery_control(ps, axis=None)
+        ref = stats.false_discovery_control(ps.ravel())
+        assert_equal(res, ref)
+
+    @pytest.mark.parametrize("axis", [0, 1, -1])
+    def test_axis(self, axis):
+        rng = np.random.default_rng(6134137338861652935)
+        ps = stats.loguniform.rvs(1e-3, 0.5, size=(3, 4, 5), random_state=rng)
+        res = stats.false_discovery_control(ps, axis=axis)
+        ref = np.apply_along_axis(stats.false_discovery_control, axis, ps)
+        assert_equal(res, ref)
+
+    def test_edge_cases(self):
+        assert_array_equal(stats.false_discovery_control([0.25]), [0.25])
+        assert_array_equal(stats.false_discovery_control(0.25), 0.25)
+        assert_array_equal(stats.false_discovery_control([]), [])
+
+
+@array_api_compatible
+class TestCommonAxis:
+    # More thorough testing of `axis` in `test_axis_nan_policy`,
+    # but those tests aren't run with array API yet. This class
+    # is in `test_morestats` instead of `test_axis_nan_policy`
+    # because there is no reason to run `test_axis_nan_policy`
+    # with the array API CI job right now.
+
+    @pytest.mark.parametrize('case', [(stats.sem, {}),
+                                      (stats.kstat, {'n': 4}),
+                                      (stats.kstat, {'n': 2}),
+                                      (stats.variation, {})])
+    def test_axis(self, case, xp):
+        fun, kwargs = case
+        rng = np.random.default_rng(24598245982345)
+        x = xp.asarray(rng.random((6, 7)))
+
+        res = fun(x, **kwargs, axis=0)
+        ref = xp.asarray([fun(x[:, i], **kwargs) for i in range(x.shape[1])])
+        xp_assert_close(res, ref)
+
+        res = fun(x, **kwargs, axis=1)
+        ref = xp.asarray([fun(x[i, :], **kwargs) for i in range(x.shape[0])])
+        xp_assert_close(res, ref)
+
+        res = fun(x, **kwargs, axis=None)
+        ref = fun(xp.reshape(x, (-1,)), **kwargs)
+        xp_assert_close(res, ref)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_basic.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..789065f088240287882e744509539dc65b4b836f
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_basic.py
@@ -0,0 +1,2071 @@
+"""
+Tests for the stats.mstats module (support for masked arrays)
+"""
+import warnings
+import platform
+
+import numpy as np
+from numpy import nan
+import numpy.ma as ma
+from numpy.ma import masked, nomask
+
+import scipy.stats.mstats as mstats
+from scipy import stats
+from .common_tests import check_named_results
+import pytest
+from pytest import raises as assert_raises
+from numpy.ma.testutils import (assert_equal, assert_almost_equal,
+                                assert_array_almost_equal,
+                                assert_array_almost_equal_nulp, assert_,
+                                assert_allclose, assert_array_equal)
+from numpy.testing import suppress_warnings
+from scipy.stats import _mstats_basic, _stats_py
+from scipy.conftest import skip_xp_invalid_arg
+from scipy.stats._axis_nan_policy import SmallSampleWarning, too_small_1d_not_omit
+
+class TestMquantiles:
+    def test_mquantiles_limit_keyword(self):
+        # Regression test for Trac ticket #867
+        data = np.array([[6., 7., 1.],
+                         [47., 15., 2.],
+                         [49., 36., 3.],
+                         [15., 39., 4.],
+                         [42., 40., -999.],
+                         [41., 41., -999.],
+                         [7., -999., -999.],
+                         [39., -999., -999.],
+                         [43., -999., -999.],
+                         [40., -999., -999.],
+                         [36., -999., -999.]])
+        desired = [[19.2, 14.6, 1.45],
+                   [40.0, 37.5, 2.5],
+                   [42.8, 40.05, 3.55]]
+        quants = mstats.mquantiles(data, axis=0, limit=(0, 50))
+        assert_almost_equal(quants, desired)
+
+
+def check_equal_gmean(array_like, desired, axis=None, dtype=None, rtol=1e-7):
+    # Note this doesn't test when axis is not specified
+    x = mstats.gmean(array_like, axis=axis, dtype=dtype)
+    assert_allclose(x, desired, rtol=rtol)
+    assert_equal(x.dtype, dtype)
+
+
+def check_equal_hmean(array_like, desired, axis=None, dtype=None, rtol=1e-7):
+    x = stats.hmean(array_like, axis=axis, dtype=dtype)
+    assert_allclose(x, desired, rtol=rtol)
+    assert_equal(x.dtype, dtype)
+
+
+@skip_xp_invalid_arg
+class TestGeoMean:
+    def test_1d(self):
+        a = [1, 2, 3, 4]
+        desired = np.power(1*2*3*4, 1./4.)
+        check_equal_gmean(a, desired, rtol=1e-14)
+
+    def test_1d_ma(self):
+        #  Test a 1d masked array
+        a = ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
+        desired = 45.2872868812
+        check_equal_gmean(a, desired)
+
+        a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1])
+        desired = np.power(1*2*3, 1./3.)
+        check_equal_gmean(a, desired, rtol=1e-14)
+
+    def test_1d_ma_value(self):
+        #  Test a 1d masked array with a masked value
+        a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
+                        mask=[0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
+        desired = 41.4716627439
+        check_equal_gmean(a, desired)
+
+    def test_1d_ma0(self):
+        #  Test a 1d masked array with zero element
+        a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 0])
+        desired = 0
+        check_equal_gmean(a, desired)
+
+    def test_1d_ma_inf(self):
+        #  Test a 1d masked array with negative element
+        a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, -1])
+        desired = np.nan
+        with np.errstate(invalid='ignore'):
+            check_equal_gmean(a, desired)
+
+    @pytest.mark.skipif(not hasattr(np, 'float96'),
+                        reason='cannot find float96 so skipping')
+    def test_1d_float96(self):
+        a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1])
+        desired_dt = np.power(1*2*3, 1./3.).astype(np.float96)
+        check_equal_gmean(a, desired_dt, dtype=np.float96, rtol=1e-14)
+
+    def test_2d_ma(self):
+        a = ma.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
+                     mask=[[0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0]])
+        desired = np.array([1, 2, 3, 4])
+        check_equal_gmean(a, desired, axis=0, rtol=1e-14)
+
+        desired = ma.array([np.power(1*2*3*4, 1./4.),
+                            np.power(2*3, 1./2.),
+                            np.power(1*4, 1./2.)])
+        check_equal_gmean(a, desired, axis=-1, rtol=1e-14)
+
+        #  Test a 2d masked array
+        a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = 52.8885199
+        check_equal_gmean(np.ma.array(a), desired)
+
+
+@skip_xp_invalid_arg
+class TestHarMean:
+    def test_1d(self):
+        a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1])
+        desired = 3. / (1./1 + 1./2 + 1./3)
+        check_equal_hmean(a, desired, rtol=1e-14)
+
+        a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
+        desired = 34.1417152147
+        check_equal_hmean(a, desired)
+
+        a = np.ma.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
+                        mask=[0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
+        desired = 31.8137186141
+        check_equal_hmean(a, desired)
+
+    @pytest.mark.skipif(not hasattr(np, 'float96'),
+                        reason='cannot find float96 so skipping')
+    def test_1d_float96(self):
+        a = ma.array([1, 2, 3, 4], mask=[0, 0, 0, 1])
+        desired_dt = np.asarray(3. / (1./1 + 1./2 + 1./3), dtype=np.float96)
+        check_equal_hmean(a, desired_dt, dtype=np.float96)
+
+    def test_2d(self):
+        a = ma.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]],
+                     mask=[[0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0]])
+        desired = ma.array([1, 2, 3, 4])
+        check_equal_hmean(a, desired, axis=0, rtol=1e-14)
+
+        desired = [4./(1/1.+1/2.+1/3.+1/4.), 2./(1/2.+1/3.), 2./(1/1.+1/4.)]
+        check_equal_hmean(a, desired, axis=-1, rtol=1e-14)
+
+        a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = 38.6696271841
+        check_equal_hmean(np.ma.array(a), desired)
+
+
+class TestRanking:
+    def test_ranking(self):
+        x = ma.array([0,1,1,1,2,3,4,5,5,6,])
+        assert_almost_equal(mstats.rankdata(x),
+                            [1,3,3,3,5,6,7,8.5,8.5,10])
+        x[[3,4]] = masked
+        assert_almost_equal(mstats.rankdata(x),
+                            [1,2.5,2.5,0,0,4,5,6.5,6.5,8])
+        assert_almost_equal(mstats.rankdata(x, use_missing=True),
+                            [1,2.5,2.5,4.5,4.5,4,5,6.5,6.5,8])
+        x = ma.array([0,1,5,1,2,4,3,5,1,6,])
+        assert_almost_equal(mstats.rankdata(x),
+                            [1,3,8.5,3,5,7,6,8.5,3,10])
+        x = ma.array([[0,1,1,1,2], [3,4,5,5,6,]])
+        assert_almost_equal(mstats.rankdata(x),
+                            [[1,3,3,3,5], [6,7,8.5,8.5,10]])
+        assert_almost_equal(mstats.rankdata(x, axis=1),
+                            [[1,3,3,3,5], [1,2,3.5,3.5,5]])
+        assert_almost_equal(mstats.rankdata(x,axis=0),
+                            [[1,1,1,1,1], [2,2,2,2,2,]])
+
+
+class TestCorr:
+    def test_pearsonr(self):
+        # Tests some computations of Pearson's r
+        x = ma.arange(10)
+        with warnings.catch_warnings():
+            # The tests in this context are edge cases, with perfect
+            # correlation or anticorrelation, or totally masked data.
+            # None of these should trigger a RuntimeWarning.
+            warnings.simplefilter("error", RuntimeWarning)
+
+            assert_almost_equal(mstats.pearsonr(x, x)[0], 1.0)
+            assert_almost_equal(mstats.pearsonr(x, x[::-1])[0], -1.0)
+
+            x = ma.array(x, mask=True)
+            pr = mstats.pearsonr(x, x)
+            assert_(pr[0] is masked)
+            assert_(pr[1] is masked)
+
+        x1 = ma.array([-1.0, 0.0, 1.0])
+        y1 = ma.array([0, 0, 3])
+        r, p = mstats.pearsonr(x1, y1)
+        assert_almost_equal(r, np.sqrt(3)/2)
+        assert_almost_equal(p, 1.0/3)
+
+        # (x2, y2) have the same unmasked data as (x1, y1).
+        mask = [False, False, False, True]
+        x2 = ma.array([-1.0, 0.0, 1.0, 99.0], mask=mask)
+        y2 = ma.array([0, 0, 3, -1], mask=mask)
+        r, p = mstats.pearsonr(x2, y2)
+        assert_almost_equal(r, np.sqrt(3)/2)
+        assert_almost_equal(p, 1.0/3)
+
+    def test_pearsonr_misaligned_mask(self):
+        mx = np.ma.masked_array([1, 2, 3, 4, 5, 6], mask=[0, 1, 0, 0, 0, 0])
+        my = np.ma.masked_array([9, 8, 7, 6, 5, 9], mask=[0, 0, 1, 0, 0, 0])
+        x = np.array([1, 4, 5, 6])
+        y = np.array([9, 6, 5, 9])
+        mr, mp = mstats.pearsonr(mx, my)
+        r, p = stats.pearsonr(x, y)
+        assert_equal(mr, r)
+        assert_equal(mp, p)
+
+    def test_spearmanr(self):
+        # Tests some computations of Spearman's rho
+        (x, y) = ([5.05,6.75,3.21,2.66], [1.65,2.64,2.64,6.95])
+        assert_almost_equal(mstats.spearmanr(x,y)[0], -0.6324555)
+        (x, y) = ([5.05,6.75,3.21,2.66,np.nan],[1.65,2.64,2.64,6.95,np.nan])
+        (x, y) = (ma.fix_invalid(x), ma.fix_invalid(y))
+        assert_almost_equal(mstats.spearmanr(x,y)[0], -0.6324555)
+
+        x = [2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1,
+             1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7]
+        y = [22.6, 8.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6,
+             0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4]
+        assert_almost_equal(mstats.spearmanr(x,y)[0], 0.6887299)
+        x = [2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1,
+             1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7, np.nan]
+        y = [22.6, 8.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6,
+             0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4, np.nan]
+        (x, y) = (ma.fix_invalid(x), ma.fix_invalid(y))
+        assert_almost_equal(mstats.spearmanr(x,y)[0], 0.6887299)
+        # Next test is to make sure calculation uses sufficient precision.
+        # The denominator's value is ~n^3 and used to be represented as an
+        # int. 2000**3 > 2**32 so these arrays would cause overflow on
+        # some machines.
+        x = list(range(2000))
+        y = list(range(2000))
+        y[0], y[9] = y[9], y[0]
+        y[10], y[434] = y[434], y[10]
+        y[435], y[1509] = y[1509], y[435]
+        # rho = 1 - 6 * (2 * (9^2 + 424^2 + 1074^2))/(2000 * (2000^2 - 1))
+        #     = 1 - (1 / 500)
+        #     = 0.998
+        assert_almost_equal(mstats.spearmanr(x,y)[0], 0.998)
+
+        # test for namedtuple attributes
+        res = mstats.spearmanr(x, y)
+        attributes = ('correlation', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+    def test_spearmanr_alternative(self):
+        # check against R
+        # options(digits=16)
+        # cor.test(c(2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1,
+        #            1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7),
+        #          c(22.6, 8.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6,
+        #            0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4),
+        #          alternative='two.sided', method='spearman')
+        x = [2.0, 47.4, 42.0, 10.8, 60.1, 1.7, 64.0, 63.1,
+             1.0, 1.4, 7.9, 0.3, 3.9, 0.3, 6.7]
+        y = [22.6, 8.3, 44.4, 11.9, 24.6, 0.6, 5.7, 41.6,
+             0.0, 0.6, 6.7, 3.8, 1.0, 1.2, 1.4]
+
+        r_exp = 0.6887298747763864  # from cor.test
+
+        r, p = mstats.spearmanr(x, y)
+        assert_allclose(r, r_exp)
+        assert_allclose(p, 0.004519192910756)
+
+        r, p = mstats.spearmanr(x, y, alternative='greater')
+        assert_allclose(r, r_exp)
+        assert_allclose(p, 0.002259596455378)
+
+        r, p = mstats.spearmanr(x, y, alternative='less')
+        assert_allclose(r, r_exp)
+        assert_allclose(p, 0.9977404035446)
+
+        # intuitive test (with obvious positive correlation)
+        n = 100
+        x = np.linspace(0, 5, n)
+        y = 0.1*x + np.random.rand(n)  # y is positively correlated w/ x
+
+        stat1, p1 = mstats.spearmanr(x, y)
+
+        stat2, p2 = mstats.spearmanr(x, y, alternative="greater")
+        assert_allclose(p2, p1 / 2)  # positive correlation -> small p
+
+        stat3, p3 = mstats.spearmanr(x, y, alternative="less")
+        assert_allclose(p3, 1 - p1 / 2)  # positive correlation -> large p
+
+        assert stat1 == stat2 == stat3
+
+        with pytest.raises(ValueError, match="alternative must be 'less'..."):
+            mstats.spearmanr(x, y, alternative="ekki-ekki")
+
+    @pytest.mark.skipif(platform.machine() == 'ppc64le',
+                        reason="fails/crashes on ppc64le")
+    def test_kendalltau(self):
+        # check case with maximum disorder and p=1
+        x = ma.array(np.array([9, 2, 5, 6]))
+        y = ma.array(np.array([4, 7, 9, 11]))
+        # Cross-check with exact result from R:
+        # cor.test(x,y,method="kendall",exact=1)
+        expected = [0.0, 1.0]
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected)
+
+        # simple case without ties
+        x = ma.array(np.arange(10))
+        y = ma.array(np.arange(10))
+        # Cross-check with exact result from R:
+        # cor.test(x,y,method="kendall",exact=1)
+        expected = [1.0, 5.511463844797e-07]
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected)
+
+        # check exception in case of invalid method keyword
+        assert_raises(ValueError, mstats.kendalltau, x, y, method='banana')
+
+        # swap a couple of values
+        b = y[1]
+        y[1] = y[2]
+        y[2] = b
+        # Cross-check with exact result from R:
+        # cor.test(x,y,method="kendall",exact=1)
+        expected = [0.9555555555555556, 5.511463844797e-06]
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected)
+
+        # swap a couple more
+        b = y[5]
+        y[5] = y[6]
+        y[6] = b
+        # Cross-check with exact result from R:
+        # cor.test(x,y,method="kendall",exact=1)
+        expected = [0.9111111111111111, 2.976190476190e-05]
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected)
+
+        # same in opposite direction
+        x = ma.array(np.arange(10))
+        y = ma.array(np.arange(10)[::-1])
+        # Cross-check with exact result from R:
+        # cor.test(x,y,method="kendall",exact=1)
+        expected = [-1.0, 5.511463844797e-07]
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected)
+
+        # swap a couple of values
+        b = y[1]
+        y[1] = y[2]
+        y[2] = b
+        # Cross-check with exact result from R:
+        # cor.test(x,y,method="kendall",exact=1)
+        expected = [-0.9555555555555556, 5.511463844797e-06]
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected)
+
+        # swap a couple more
+        b = y[5]
+        y[5] = y[6]
+        y[6] = b
+        # Cross-check with exact result from R:
+        # cor.test(x,y,method="kendall",exact=1)
+        expected = [-0.9111111111111111, 2.976190476190e-05]
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, y)), expected)
+
+        # Tests some computations of Kendall's tau
+        x = ma.fix_invalid([5.05, 6.75, 3.21, 2.66, np.nan])
+        y = ma.fix_invalid([1.65, 26.5, -5.93, 7.96, np.nan])
+        z = ma.fix_invalid([1.65, 2.64, 2.64, 6.95, np.nan])
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, y)),
+                            [+0.3333333, 0.75])
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, y, method='asymptotic')),
+                            [+0.3333333, 0.4969059])
+        assert_almost_equal(np.asarray(mstats.kendalltau(x, z)),
+                            [-0.5477226, 0.2785987])
+        #
+        x = ma.fix_invalid([0, 0, 0, 0, 20, 20, 0, 60, 0, 20,
+                            10, 10, 0, 40, 0, 20, 0, 0, 0, 0, 0, np.nan])
+        y = ma.fix_invalid([0, 80, 80, 80, 10, 33, 60, 0, 67, 27,
+                            25, 80, 80, 80, 80, 80, 80, 0, 10, 45, np.nan, 0])
+        result = mstats.kendalltau(x, y)
+        assert_almost_equal(np.asarray(result), [-0.1585188, 0.4128009])
+
+        # test for namedtuple attributes
+        attributes = ('correlation', 'pvalue')
+        check_named_results(result, attributes, ma=True)
+
+    @pytest.mark.skipif(platform.machine() == 'ppc64le',
+                        reason="fails/crashes on ppc64le")
+    @pytest.mark.slow
+    def test_kendalltau_large(self):
+        # make sure internal variable use correct precision with
+        # larger arrays
+        x = np.arange(2000, dtype=float)
+        x = ma.masked_greater(x, 1995)
+        y = np.arange(2000, dtype=float)
+        y = np.concatenate((y[1000:], y[:1000]))
+        assert_(np.isfinite(mstats.kendalltau(x, y)[1]))
+
+    def test_kendalltau_seasonal(self):
+        # Tests the seasonal Kendall tau.
+        x = [[nan, nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1],
+             [4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3],
+             [3, 2, 5, 6, 18, 4, 9, 1, 1, nan, 1, 1, nan],
+             [nan, 6, 11, 4, 17, nan, 6, 1, 1, 2, 5, 1, 1]]
+        x = ma.fix_invalid(x).T
+        output = mstats.kendalltau_seasonal(x)
+        assert_almost_equal(output['global p-value (indep)'], 0.008, 3)
+        assert_almost_equal(output['seasonal p-value'].round(2),
+                            [0.18,0.53,0.20,0.04])
+
+    @pytest.mark.parametrize("method", ("exact", "asymptotic"))
+    @pytest.mark.parametrize("alternative", ("two-sided", "greater", "less"))
+    def test_kendalltau_mstats_vs_stats(self, method, alternative):
+        # Test that mstats.kendalltau and stats.kendalltau with
+        # nan_policy='omit' matches behavior of stats.kendalltau
+        # Accuracy of the alternatives is tested in stats/tests/test_stats.py
+
+        np.random.seed(0)
+        n = 50
+        x = np.random.rand(n)
+        y = np.random.rand(n)
+        mask = np.random.rand(n) > 0.5
+
+        x_masked = ma.array(x, mask=mask)
+        y_masked = ma.array(y, mask=mask)
+        res_masked = mstats.kendalltau(
+            x_masked, y_masked, method=method, alternative=alternative)
+
+        x_compressed = x_masked.compressed()
+        y_compressed = y_masked.compressed()
+        res_compressed = stats.kendalltau(
+            x_compressed, y_compressed, method=method, alternative=alternative)
+
+        x[mask] = np.nan
+        y[mask] = np.nan
+        res_nan = stats.kendalltau(
+            x, y, method=method, nan_policy='omit', alternative=alternative)
+
+        assert_allclose(res_masked, res_compressed)
+        assert_allclose(res_nan, res_compressed)
+
+    def test_kendall_p_exact_medium(self):
+        # Test for the exact method with medium samples (some n >= 171)
+        # expected values generated using SymPy
+        expectations = {(100, 2393): 0.62822615287956040664,
+                        (101, 2436): 0.60439525773513602669,
+                        (170, 0): 2.755801935583541e-307,
+                        (171, 0): 0.0,
+                        (171, 1): 2.755801935583541e-307,
+                        (172, 1): 0.0,
+                        (200, 9797): 0.74753983745929675209,
+                        (201, 9656): 0.40959218958120363618}
+        for nc, expected in expectations.items():
+            res = _mstats_basic._kendall_p_exact(nc[0], nc[1])
+            assert_almost_equal(res, expected)
+
+    @pytest.mark.xslow
+    def test_kendall_p_exact_large(self):
+        # Test for the exact method with large samples (n >= 171)
+        # expected values generated using SymPy
+        expectations = {(400, 38965): 0.48444283672113314099,
+                        (401, 39516): 0.66363159823474837662,
+                        (800, 156772): 0.42265448483120932055,
+                        (801, 157849): 0.53437553412194416236,
+                        (1600, 637472): 0.84200727400323538419,
+                        (1601, 630304): 0.34465255088058593946}
+
+        for nc, expected in expectations.items():
+            res = _mstats_basic._kendall_p_exact(nc[0], nc[1])
+            assert_almost_equal(res, expected)
+
+    @skip_xp_invalid_arg
+    # mstats.pointbiserialr returns a NumPy float for the statistic, but converts
+    # it to a masked array with no masked elements before calling `special.betainc`,
+    # which won't accept masked arrays when `SCIPY_ARRAY_API=1`.
+    def test_pointbiserial(self):
+        x = [1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0,
+             0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, -1]
+        y = [14.8, 13.8, 12.4, 10.1, 7.1, 6.1, 5.8, 4.6, 4.3, 3.5, 3.3, 3.2,
+             3.0, 2.8, 2.8, 2.5, 2.4, 2.3, 2.1, 1.7, 1.7, 1.5, 1.3, 1.3, 1.2,
+             1.2, 1.1, 0.8, 0.7, 0.6, 0.5, 0.2, 0.2, 0.1, np.nan]
+        assert_almost_equal(mstats.pointbiserialr(x, y)[0], 0.36149, 5)
+
+        # test for namedtuple attributes
+        res = mstats.pointbiserialr(x, y)
+        attributes = ('correlation', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+
+@skip_xp_invalid_arg
+class TestTrimming:
+
+    def test_trim(self):
+        a = ma.arange(10)
+        assert_equal(mstats.trim(a), [0,1,2,3,4,5,6,7,8,9])
+        a = ma.arange(10)
+        assert_equal(mstats.trim(a,(2,8)), [None,None,2,3,4,5,6,7,8,None])
+        a = ma.arange(10)
+        assert_equal(mstats.trim(a,limits=(2,8),inclusive=(False,False)),
+                     [None,None,None,3,4,5,6,7,None,None])
+        a = ma.arange(10)
+        assert_equal(mstats.trim(a,limits=(0.1,0.2),relative=True),
+                     [None,1,2,3,4,5,6,7,None,None])
+
+        a = ma.arange(12)
+        a[[0,-1]] = a[5] = masked
+        assert_equal(mstats.trim(a, (2,8)),
+                     [None, None, 2, 3, 4, None, 6, 7, 8, None, None, None])
+
+        x = ma.arange(100).reshape(10, 10)
+        expected = [1]*10 + [0]*70 + [1]*20
+        trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=None)
+        assert_equal(trimx._mask.ravel(), expected)
+        trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=0)
+        assert_equal(trimx._mask.ravel(), expected)
+        trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=-1)
+        assert_equal(trimx._mask.T.ravel(), expected)
+
+        # same as above, but with an extra masked row inserted
+        x = ma.arange(110).reshape(11, 10)
+        x[1] = masked
+        expected = [1]*20 + [0]*70 + [1]*20
+        trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=None)
+        assert_equal(trimx._mask.ravel(), expected)
+        trimx = mstats.trim(x, (0.1,0.2), relative=True, axis=0)
+        assert_equal(trimx._mask.ravel(), expected)
+        trimx = mstats.trim(x.T, (0.1,0.2), relative=True, axis=-1)
+        assert_equal(trimx.T._mask.ravel(), expected)
+
+    def test_trim_old(self):
+        x = ma.arange(100)
+        assert_equal(mstats.trimboth(x).count(), 60)
+        assert_equal(mstats.trimtail(x,tail='r').count(), 80)
+        x[50:70] = masked
+        trimx = mstats.trimboth(x)
+        assert_equal(trimx.count(), 48)
+        assert_equal(trimx._mask, [1]*16 + [0]*34 + [1]*20 + [0]*14 + [1]*16)
+        x._mask = nomask
+        x.shape = (10,10)
+        assert_equal(mstats.trimboth(x).count(), 60)
+        assert_equal(mstats.trimtail(x).count(), 80)
+
+    def test_trimr(self):
+        x = ma.arange(10)
+        result = mstats.trimr(x, limits=(0.15, 0.14), inclusive=(False, False))
+        expected = ma.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
+                            mask=[1, 1, 0, 0, 0, 0, 0, 0, 0, 1])
+        assert_equal(result, expected)
+        assert_equal(result.mask, expected.mask)
+
+    def test_trimmedmean(self):
+        data = ma.array([77, 87, 88,114,151,210,219,246,253,262,
+                         296,299,306,376,428,515,666,1310,2611])
+        assert_almost_equal(mstats.trimmed_mean(data,0.1), 343, 0)
+        assert_almost_equal(mstats.trimmed_mean(data,(0.1,0.1)), 343, 0)
+        assert_almost_equal(mstats.trimmed_mean(data,(0.2,0.2)), 283, 0)
+
+    def test_trimmedvar(self):
+        # Basic test. Additional tests of all arguments, edge cases,
+        # input validation, and proper treatment of masked arrays are needed.
+        rng = np.random.default_rng(3262323289434724460)
+        data_orig = rng.random(size=20)
+        data = np.sort(data_orig)
+        data = ma.array(data, mask=[1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
+                                    0, 0, 0, 0, 0, 0, 0, 0, 1, 1])
+        assert_allclose(mstats.trimmed_var(data_orig, 0.1), data.var())
+
+    def test_trimmedstd(self):
+        # Basic test. Additional tests of all arguments, edge cases,
+        # input validation, and proper treatment of masked arrays are needed.
+        rng = np.random.default_rng(7121029245207162780)
+        data_orig = rng.random(size=20)
+        data = np.sort(data_orig)
+        data = ma.array(data, mask=[1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
+                                    0, 0, 0, 0, 0, 0, 0, 0, 1, 1])
+        assert_allclose(mstats.trimmed_std(data_orig, 0.1), data.std())
+
+    def test_trimmed_stde(self):
+        data = ma.array([77, 87, 88,114,151,210,219,246,253,262,
+                         296,299,306,376,428,515,666,1310,2611])
+        assert_almost_equal(mstats.trimmed_stde(data,(0.2,0.2)), 56.13193, 5)
+        assert_almost_equal(mstats.trimmed_stde(data,0.2), 56.13193, 5)
+
+    def test_winsorization(self):
+        data = ma.array([77, 87, 88,114,151,210,219,246,253,262,
+                         296,299,306,376,428,515,666,1310,2611])
+        assert_almost_equal(mstats.winsorize(data,(0.2,0.2)).var(ddof=1),
+                            21551.4, 1)
+        assert_almost_equal(
+            mstats.winsorize(data, (0.2,0.2),(False,False)).var(ddof=1),
+            11887.3, 1)
+        data[5] = masked
+        winsorized = mstats.winsorize(data)
+        assert_equal(winsorized.mask, data.mask)
+
+    def test_winsorization_nan(self):
+        data = ma.array([np.nan, np.nan, 0, 1, 2])
+        assert_raises(ValueError, mstats.winsorize, data, (0.05, 0.05),
+                      nan_policy='raise')
+        # Testing propagate (default behavior)
+        assert_equal(mstats.winsorize(data, (0.4, 0.4)),
+                     ma.array([2, 2, 2, 2, 2]))
+        assert_equal(mstats.winsorize(data, (0.8, 0.8)),
+                     ma.array([np.nan, np.nan, np.nan, np.nan, np.nan]))
+        assert_equal(mstats.winsorize(data, (0.4, 0.4), nan_policy='omit'),
+                     ma.array([np.nan, np.nan, 2, 2, 2]))
+        assert_equal(mstats.winsorize(data, (0.8, 0.8), nan_policy='omit'),
+                     ma.array([np.nan, np.nan, 2, 2, 2]))
+
+
+@skip_xp_invalid_arg
+class TestMoments:
+    # Comparison numbers are found using R v.1.5.1
+    # note that length(testcase) = 4
+    # testmathworks comes from documentation for the
+    # Statistics Toolbox for Matlab and can be found at both
+    # https://www.mathworks.com/help/stats/kurtosis.html
+    # https://www.mathworks.com/help/stats/skewness.html
+    # Note that both test cases came from here.
+    testcase = [1,2,3,4]
+    testmathworks = ma.fix_invalid([1.165, 0.6268, 0.0751, 0.3516, -0.6965,
+                                    np.nan])
+    testcase_2d = ma.array(
+        np.array([[0.05245846, 0.50344235, 0.86589117, 0.36936353, 0.46961149],
+                  [0.11574073, 0.31299969, 0.45925772, 0.72618805, 0.75194407],
+                  [0.67696689, 0.91878127, 0.09769044, 0.04645137, 0.37615733],
+                  [0.05903624, 0.29908861, 0.34088298, 0.66216337, 0.83160998],
+                  [0.64619526, 0.94894632, 0.27855892, 0.0706151, 0.39962917]]),
+        mask=np.array([[True, False, False, True, False],
+                       [True, True, True, False, True],
+                       [False, False, False, False, False],
+                       [True, True, True, True, True],
+                       [False, False, True, False, False]], dtype=bool))
+
+    def _assert_equal(self, actual, expect, *, shape=None, dtype=None):
+        expect = np.asarray(expect)
+        if shape is not None:
+            expect = np.broadcast_to(expect, shape)
+        assert_array_equal(actual, expect)
+        if dtype is None:
+            dtype = expect.dtype
+        assert actual.dtype == dtype
+
+    def test_moment(self):
+        y = mstats.moment(self.testcase,1)
+        assert_almost_equal(y,0.0,10)
+        y = mstats.moment(self.testcase,2)
+        assert_almost_equal(y,1.25)
+        y = mstats.moment(self.testcase,3)
+        assert_almost_equal(y,0.0)
+        y = mstats.moment(self.testcase,4)
+        assert_almost_equal(y,2.5625)
+
+        # check array_like input for moment
+        y = mstats.moment(self.testcase, [1, 2, 3, 4])
+        assert_allclose(y, [0, 1.25, 0, 2.5625])
+
+        # check moment input consists only of integers
+        y = mstats.moment(self.testcase, 0.0)
+        assert_allclose(y, 1.0)
+        assert_raises(ValueError, mstats.moment, self.testcase, 1.2)
+        y = mstats.moment(self.testcase, [1.0, 2, 3, 4.0])
+        assert_allclose(y, [0, 1.25, 0, 2.5625])
+
+        # test empty input
+        y = mstats.moment([])
+        self._assert_equal(y, np.nan, dtype=np.float64)
+        y = mstats.moment(np.array([], dtype=np.float32))
+        self._assert_equal(y, np.nan, dtype=np.float32)
+        y = mstats.moment(np.zeros((1, 0)), axis=0)
+        self._assert_equal(y, [], shape=(0,), dtype=np.float64)
+        y = mstats.moment([[]], axis=1)
+        self._assert_equal(y, np.nan, shape=(1,), dtype=np.float64)
+        y = mstats.moment([[]], moment=[0, 1], axis=0)
+        self._assert_equal(y, [], shape=(2, 0))
+
+        x = np.arange(10.)
+        x[9] = np.nan
+        assert_equal(mstats.moment(x, 2), ma.masked)  # NaN value is ignored
+
+    def test_variation(self):
+        y = mstats.variation(self.testcase)
+        assert_almost_equal(y,0.44721359549996, 10)
+
+    def test_variation_ddof(self):
+        # test variation with delta degrees of freedom
+        # regression test for gh-13341
+        a = np.array([1, 2, 3, 4, 5])
+        y = mstats.variation(a, ddof=1)
+        assert_almost_equal(y, 0.5270462766947299)
+
+    def test_skewness(self):
+        y = mstats.skew(self.testmathworks)
+        assert_almost_equal(y,-0.29322304336607,10)
+        y = mstats.skew(self.testmathworks,bias=0)
+        assert_almost_equal(y,-0.437111105023940,10)
+        y = mstats.skew(self.testcase)
+        assert_almost_equal(y,0.0,10)
+
+        # test that skew works on multidimensional masked arrays
+        correct_2d = ma.array(
+            np.array([0.6882870394455785, 0, 0.2665647526856708,
+                      0, -0.05211472114254485]),
+            mask=np.array([False, False, False, True, False], dtype=bool)
+        )
+        assert_allclose(mstats.skew(self.testcase_2d, 1), correct_2d)
+        for i, row in enumerate(self.testcase_2d):
+            assert_almost_equal(mstats.skew(row), correct_2d[i])
+
+        correct_2d_bias_corrected = ma.array(
+            np.array([1.685952043212545, 0.0, 0.3973712716070531, 0,
+                      -0.09026534484117164]),
+            mask=np.array([False, False, False, True, False], dtype=bool)
+        )
+        assert_allclose(mstats.skew(self.testcase_2d, 1, bias=False),
+                        correct_2d_bias_corrected)
+        for i, row in enumerate(self.testcase_2d):
+            assert_almost_equal(mstats.skew(row, bias=False),
+                                correct_2d_bias_corrected[i])
+
+        # Check consistency between stats and mstats implementations
+        assert_allclose(mstats.skew(self.testcase_2d[2, :]),
+                        stats.skew(self.testcase_2d[2, :]))
+
+    def test_kurtosis(self):
+        # Set flags for axis = 0 and fisher=0 (Pearson's definition of kurtosis
+        # for compatibility with Matlab)
+        y = mstats.kurtosis(self.testmathworks, 0, fisher=0, bias=1)
+        assert_almost_equal(y, 2.1658856802973, 10)
+        # Note that MATLAB has confusing docs for the following case
+        #  kurtosis(x,0) gives an unbiased estimate of Pearson's skewness
+        #  kurtosis(x) gives a biased estimate of Fisher's skewness (Pearson-3)
+        #  The MATLAB docs imply that both should give Fisher's
+        y = mstats.kurtosis(self.testmathworks, fisher=0, bias=0)
+        assert_almost_equal(y, 3.663542721189047, 10)
+        y = mstats.kurtosis(self.testcase, 0, 0)
+        assert_almost_equal(y, 1.64)
+
+        # test that kurtosis works on multidimensional masked arrays
+        correct_2d = ma.array(np.array([-1.5, -3., -1.47247052385, 0.,
+                                        -1.26979517952]),
+                              mask=np.array([False, False, False, True,
+                                             False], dtype=bool))
+        assert_array_almost_equal(mstats.kurtosis(self.testcase_2d, 1),
+                                  correct_2d)
+        for i, row in enumerate(self.testcase_2d):
+            assert_almost_equal(mstats.kurtosis(row), correct_2d[i])
+
+        correct_2d_bias_corrected = ma.array(
+            np.array([-1.5, -3., -1.88988209538, 0., -0.5234638463918877]),
+            mask=np.array([False, False, False, True, False], dtype=bool))
+        assert_array_almost_equal(mstats.kurtosis(self.testcase_2d, 1,
+                                                  bias=False),
+                                  correct_2d_bias_corrected)
+        for i, row in enumerate(self.testcase_2d):
+            assert_almost_equal(mstats.kurtosis(row, bias=False),
+                                correct_2d_bias_corrected[i])
+
+        # Check consistency between stats and mstats implementations
+        assert_array_almost_equal_nulp(mstats.kurtosis(self.testcase_2d[2, :]),
+                                       stats.kurtosis(self.testcase_2d[2, :]),
+                                       nulp=4)
+
+
+class TestMode:
+    def test_mode(self):
+        a1 = [0,0,0,1,1,1,2,3,3,3,3,4,5,6,7]
+        a2 = np.reshape(a1, (3,5))
+        a3 = np.array([1,2,3,4,5,6])
+        a4 = np.reshape(a3, (3,2))
+        ma1 = ma.masked_where(ma.array(a1) > 2, a1)
+        ma2 = ma.masked_where(a2 > 2, a2)
+        ma3 = ma.masked_where(a3 < 2, a3)
+        ma4 = ma.masked_where(ma.array(a4) < 2, a4)
+        assert_equal(mstats.mode(a1, axis=None), (3,4))
+        assert_equal(mstats.mode(a1, axis=0), (3,4))
+        assert_equal(mstats.mode(ma1, axis=None), (0,3))
+        assert_equal(mstats.mode(a2, axis=None), (3,4))
+        assert_equal(mstats.mode(ma2, axis=None), (0,3))
+        assert_equal(mstats.mode(a3, axis=None), (1,1))
+        assert_equal(mstats.mode(ma3, axis=None), (2,1))
+        assert_equal(mstats.mode(a2, axis=0), ([[0,0,0,1,1]], [[1,1,1,1,1]]))
+        assert_equal(mstats.mode(ma2, axis=0), ([[0,0,0,1,1]], [[1,1,1,1,1]]))
+        assert_equal(mstats.mode(a2, axis=-1), ([[0],[3],[3]], [[3],[3],[1]]))
+        assert_equal(mstats.mode(ma2, axis=-1), ([[0],[1],[0]], [[3],[1],[0]]))
+        assert_equal(mstats.mode(ma4, axis=0), ([[3,2]], [[1,1]]))
+        assert_equal(mstats.mode(ma4, axis=-1), ([[2],[3],[5]], [[1],[1],[1]]))
+
+        a1_res = mstats.mode(a1, axis=None)
+
+        # test for namedtuple attributes
+        attributes = ('mode', 'count')
+        check_named_results(a1_res, attributes, ma=True)
+
+    def test_mode_modifies_input(self):
+        # regression test for gh-6428: mode(..., axis=None) may not modify
+        # the input array
+        im = np.zeros((100, 100))
+        im[:50, :] += 1
+        im[:, :50] += 1
+        cp = im.copy()
+        mstats.mode(im, None)
+        assert_equal(im, cp)
+
+
+class TestPercentile:
+    def setup_method(self):
+        self.a1 = [3, 4, 5, 10, -3, -5, 6]
+        self.a2 = [3, -6, -2, 8, 7, 4, 2, 1]
+        self.a3 = [3., 4, 5, 10, -3, -5, -6, 7.0]
+
+    def test_percentile(self):
+        x = np.arange(8) * 0.5
+        assert_equal(mstats.scoreatpercentile(x, 0), 0.)
+        assert_equal(mstats.scoreatpercentile(x, 100), 3.5)
+        assert_equal(mstats.scoreatpercentile(x, 50), 1.75)
+
+    def test_2D(self):
+        x = ma.array([[1, 1, 1],
+                      [1, 1, 1],
+                      [4, 4, 3],
+                      [1, 1, 1],
+                      [1, 1, 1]])
+        assert_equal(mstats.scoreatpercentile(x, 50), [1, 1, 1])
+
+
+@skip_xp_invalid_arg
+class TestVariability:
+    """  Comparison numbers are found using R v.1.5.1
+         note that length(testcase) = 4
+    """
+    testcase = ma.fix_invalid([1,2,3,4,np.nan])
+
+    def test_sem(self):
+        # This is not in R, so used: sqrt(var(testcase)*3/4) / sqrt(3)
+        y = mstats.sem(self.testcase)
+        assert_almost_equal(y, 0.6454972244)
+        n = self.testcase.count()
+        assert_allclose(mstats.sem(self.testcase, ddof=0) * np.sqrt(n/(n-2)),
+                        mstats.sem(self.testcase, ddof=2))
+
+    def test_zmap(self):
+        # This is not in R, so tested by using:
+        #    (testcase[i]-mean(testcase,axis=0)) / sqrt(var(testcase)*3/4)
+        y = mstats.zmap(self.testcase, self.testcase)
+        desired_unmaskedvals = ([-1.3416407864999, -0.44721359549996,
+                                 0.44721359549996, 1.3416407864999])
+        assert_array_almost_equal(desired_unmaskedvals,
+                                  y.data[y.mask == False], decimal=12)  # noqa: E712
+
+    def test_zscore(self):
+        # This is not in R, so tested by using:
+        #     (testcase[i]-mean(testcase,axis=0)) / sqrt(var(testcase)*3/4)
+        y = mstats.zscore(self.testcase)
+        desired = ma.fix_invalid([-1.3416407864999, -0.44721359549996,
+                                  0.44721359549996, 1.3416407864999, np.nan])
+        assert_almost_equal(desired, y, decimal=12)
+
+
+@skip_xp_invalid_arg
+class TestMisc:
+
+    def test_obrientransform(self):
+        args = [[5]*5+[6]*11+[7]*9+[8]*3+[9]*2+[10]*2,
+                [6]+[7]*2+[8]*4+[9]*9+[10]*16]
+        result = [5*[3.1828]+11*[0.5591]+9*[0.0344]+3*[1.6086]+2*[5.2817]+2*[11.0538],
+                  [10.4352]+2*[4.8599]+4*[1.3836]+9*[0.0061]+16*[0.7277]]
+        assert_almost_equal(np.round(mstats.obrientransform(*args).T, 4),
+                            result, 4)
+
+    def test_ks_2samp(self):
+        x = [[nan,nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1],
+             [4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3],
+             [3, 2, 5, 6, 18, 4, 9, 1, 1, nan, 1, 1, nan],
+             [nan, 6, 11, 4, 17, nan, 6, 1, 1, 2, 5, 1, 1]]
+        x = ma.fix_invalid(x).T
+        (winter, spring, summer, fall) = x.T
+
+        assert_almost_equal(np.round(mstats.ks_2samp(winter, spring), 4),
+                            (0.1818, 0.9628))
+        assert_almost_equal(np.round(mstats.ks_2samp(winter, spring, 'g'), 4),
+                            (0.1469, 0.6886))
+        assert_almost_equal(np.round(mstats.ks_2samp(winter, spring, 'l'), 4),
+                            (0.1818, 0.6011))
+
+    def test_friedmanchisq(self):
+        # No missing values
+        args = ([9.0,9.5,5.0,7.5,9.5,7.5,8.0,7.0,8.5,6.0],
+                [7.0,6.5,7.0,7.5,5.0,8.0,6.0,6.5,7.0,7.0],
+                [6.0,8.0,4.0,6.0,7.0,6.5,6.0,4.0,6.5,3.0])
+        result = mstats.friedmanchisquare(*args)
+        assert_almost_equal(result[0], 10.4737, 4)
+        assert_almost_equal(result[1], 0.005317, 6)
+        # Missing values
+        x = [[nan,nan, 4, 2, 16, 26, 5, 1, 5, 1, 2, 3, 1],
+             [4, 3, 5, 3, 2, 7, 3, 1, 1, 2, 3, 5, 3],
+             [3, 2, 5, 6, 18, 4, 9, 1, 1,nan, 1, 1,nan],
+             [nan, 6, 11, 4, 17,nan, 6, 1, 1, 2, 5, 1, 1]]
+        x = ma.fix_invalid(x)
+        result = mstats.friedmanchisquare(*x)
+        assert_almost_equal(result[0], 2.0156, 4)
+        assert_almost_equal(result[1], 0.5692, 4)
+
+        # test for namedtuple attributes
+        attributes = ('statistic', 'pvalue')
+        check_named_results(result, attributes, ma=True)
+
+
+def test_regress_simple():
+    # Regress a line with sinusoidal noise. Test for #1273.
+    x = np.linspace(0, 100, 100)
+    y = 0.2 * np.linspace(0, 100, 100) + 10
+    y += np.sin(np.linspace(0, 20, 100))
+
+    result = mstats.linregress(x, y)
+
+    # Result is of a correct class and with correct fields
+    lr = _stats_py.LinregressResult
+    assert_(isinstance(result, lr))
+    attributes = ('slope', 'intercept', 'rvalue', 'pvalue', 'stderr')
+    check_named_results(result, attributes, ma=True)
+    assert 'intercept_stderr' in dir(result)
+
+    # Slope and intercept are estimated correctly
+    assert_almost_equal(result.slope, 0.19644990055858422)
+    assert_almost_equal(result.intercept, 10.211269918932341)
+    assert_almost_equal(result.stderr, 0.002395781449783862)
+    assert_almost_equal(result.intercept_stderr, 0.13866936078570702)
+
+
+def test_linregress_identical_x():
+    x = np.zeros(10)
+    y = np.random.random(10)
+    msg = "Cannot calculate a linear regression if all x values are identical"
+    with assert_raises(ValueError, match=msg):
+        mstats.linregress(x, y)
+
+
+class TestTheilslopes:
+    def test_theilslopes(self):
+        # Test for basic slope and intercept.
+        slope, intercept, lower, upper = mstats.theilslopes([0, 1, 1])
+        assert_almost_equal(slope, 0.5)
+        assert_almost_equal(intercept, 0.5)
+
+        slope, intercept, lower, upper = mstats.theilslopes([0, 1, 1],
+                                                            method='joint')
+        assert_almost_equal(slope, 0.5)
+        assert_almost_equal(intercept, 0.0)
+
+        # Test for correct masking.
+        y = np.ma.array([0, 1, 100, 1], mask=[False, False, True, False])
+        slope, intercept, lower, upper = mstats.theilslopes(y)
+        assert_almost_equal(slope, 1./3)
+        assert_almost_equal(intercept, 2./3)
+
+        slope, intercept, lower, upper = mstats.theilslopes(y,
+                                                            method='joint')
+        assert_almost_equal(slope, 1./3)
+        assert_almost_equal(intercept, 0.0)
+
+        # Test of confidence intervals from example in Sen (1968).
+        x = [1, 2, 3, 4, 10, 12, 18]
+        y = [9, 15, 19, 20, 45, 55, 78]
+        slope, intercept, lower, upper = mstats.theilslopes(y, x, 0.07)
+        assert_almost_equal(slope, 4)
+        assert_almost_equal(intercept, 4.0)
+        assert_almost_equal(upper, 4.38, decimal=2)
+        assert_almost_equal(lower, 3.71, decimal=2)
+
+        slope, intercept, lower, upper = mstats.theilslopes(y, x, 0.07,
+                                                            method='joint')
+        assert_almost_equal(slope, 4)
+        assert_almost_equal(intercept, 6.0)
+        assert_almost_equal(upper, 4.38, decimal=2)
+        assert_almost_equal(lower, 3.71, decimal=2)
+
+
+    def test_theilslopes_warnings(self):
+        # Test `theilslopes` with degenerate input; see gh-15943
+        msg = "All `x` coordinates.*|Mean of empty slice.|invalid value encountered.*"
+        with pytest.warns(RuntimeWarning, match=msg):
+            res = mstats.theilslopes([0, 1], [0, 0])
+            assert np.all(np.isnan(res))
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered...")
+            res = mstats.theilslopes([0, 0, 0], [0, 1, 0])
+            assert_allclose(res, (0, 0, np.nan, np.nan))
+
+
+    def test_theilslopes_namedtuple_consistency(self):
+        """
+        Simple test to ensure tuple backwards-compatibility of the returned
+        TheilslopesResult object
+        """
+        y = [1, 2, 4]
+        x = [4, 6, 8]
+        slope, intercept, low_slope, high_slope = mstats.theilslopes(y, x)
+        result = mstats.theilslopes(y, x)
+
+        # note all four returned values are distinct here
+        assert_equal(slope, result.slope)
+        assert_equal(intercept, result.intercept)
+        assert_equal(low_slope, result.low_slope)
+        assert_equal(high_slope, result.high_slope)
+
+    def test_gh19678_uint8(self):
+        # `theilslopes` returned unexpected results when `y` was an unsigned type.
+        # Check that this is resolved.
+        rng = np.random.default_rng(2549824598234528)
+        y = rng.integers(0, 255, size=10, dtype=np.uint8)
+        res = stats.theilslopes(y, y)
+        np.testing.assert_allclose(res.slope, 1)
+
+
+def test_siegelslopes():
+    # method should be exact for straight line
+    y = 2 * np.arange(10) + 0.5
+    assert_equal(mstats.siegelslopes(y), (2.0, 0.5))
+    assert_equal(mstats.siegelslopes(y, method='separate'), (2.0, 0.5))
+
+    x = 2 * np.arange(10)
+    y = 5 * x - 3.0
+    assert_equal(mstats.siegelslopes(y, x), (5.0, -3.0))
+    assert_equal(mstats.siegelslopes(y, x, method='separate'), (5.0, -3.0))
+
+    # method is robust to outliers: brekdown point of 50%
+    y[:4] = 1000
+    assert_equal(mstats.siegelslopes(y, x), (5.0, -3.0))
+
+    # if there are no outliers, results should be comparable to linregress
+    x = np.arange(10)
+    y = -2.3 + 0.3*x + stats.norm.rvs(size=10, random_state=231)
+    slope_ols, intercept_ols, _, _, _ = stats.linregress(x, y)
+
+    slope, intercept = mstats.siegelslopes(y, x)
+    assert_allclose(slope, slope_ols, rtol=0.1)
+    assert_allclose(intercept, intercept_ols, rtol=0.1)
+
+    slope, intercept = mstats.siegelslopes(y, x, method='separate')
+    assert_allclose(slope, slope_ols, rtol=0.1)
+    assert_allclose(intercept, intercept_ols, rtol=0.1)
+
+
+def test_siegelslopes_namedtuple_consistency():
+    """
+    Simple test to ensure tuple backwards-compatibility of the returned
+    SiegelslopesResult object.
+    """
+    y = [1, 2, 4]
+    x = [4, 6, 8]
+    slope, intercept = mstats.siegelslopes(y, x)
+    result = mstats.siegelslopes(y, x)
+
+    # note both returned values are distinct here
+    assert_equal(slope, result.slope)
+    assert_equal(intercept, result.intercept)
+
+
+def test_sen_seasonal_slopes():
+    rng = np.random.default_rng(5765986256978575148)
+    x = rng.random(size=(100, 4))
+    intra_slope, inter_slope = mstats.sen_seasonal_slopes(x)
+
+    # reference implementation from the `sen_seasonal_slopes` documentation
+    def dijk(yi):
+        n = len(yi)
+        x = np.arange(n)
+        dy = yi - yi[:, np.newaxis]
+        dx = x - x[:, np.newaxis]
+        mask = np.triu(np.ones((n, n), dtype=bool), k=1)
+        return dy[mask]/dx[mask]
+
+    for i in range(4):
+        assert_allclose(np.median(dijk(x[:, i])), intra_slope[i])
+
+    all_slopes = np.concatenate([dijk(x[:, i]) for i in range(x.shape[1])])
+    assert_allclose(np.median(all_slopes), inter_slope)
+
+
+def test_plotting_positions():
+    # Regression test for #1256
+    pos = mstats.plotting_positions(np.arange(3), 0, 0)
+    assert_array_almost_equal(pos.data, np.array([0.25, 0.5, 0.75]))
+
+
+@skip_xp_invalid_arg
+class TestNormalitytests:
+
+    def test_vs_nonmasked(self):
+        x = np.array((-2, -1, 0, 1, 2, 3)*4)**2
+        assert_array_almost_equal(mstats.normaltest(x),
+                                  stats.normaltest(x))
+        assert_array_almost_equal(mstats.skewtest(x),
+                                  stats.skewtest(x))
+        assert_array_almost_equal(mstats.kurtosistest(x),
+                                  stats.kurtosistest(x))
+
+        funcs = [stats.normaltest, stats.skewtest, stats.kurtosistest]
+        mfuncs = [mstats.normaltest, mstats.skewtest, mstats.kurtosistest]
+        x = [1, 2, 3, 4]
+        for func, mfunc in zip(funcs, mfuncs):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = func(x)
+                assert np.isnan(res.statistic)
+                assert np.isnan(res.pvalue)
+            assert_raises(ValueError, mfunc, x)
+
+    def test_axis_None(self):
+        # Test axis=None (equal to axis=0 for 1-D input)
+        x = np.array((-2,-1,0,1,2,3)*4)**2
+        assert_allclose(mstats.normaltest(x, axis=None), mstats.normaltest(x))
+        assert_allclose(mstats.skewtest(x, axis=None), mstats.skewtest(x))
+        assert_allclose(mstats.kurtosistest(x, axis=None),
+                        mstats.kurtosistest(x))
+
+    def test_maskedarray_input(self):
+        # Add some masked values, test result doesn't change
+        x = np.array((-2, -1, 0, 1, 2, 3)*4)**2
+        xm = np.ma.array(np.r_[np.inf, x, 10],
+                         mask=np.r_[True, [False] * x.size, True])
+        assert_allclose(mstats.normaltest(xm), stats.normaltest(x))
+        assert_allclose(mstats.skewtest(xm), stats.skewtest(x))
+        assert_allclose(mstats.kurtosistest(xm), stats.kurtosistest(x))
+
+    def test_nd_input(self):
+        x = np.array((-2, -1, 0, 1, 2, 3)*4)**2
+        x_2d = np.vstack([x] * 2).T
+        for func in [mstats.normaltest, mstats.skewtest, mstats.kurtosistest]:
+            res_1d = func(x)
+            res_2d = func(x_2d)
+            assert_allclose(res_2d[0], [res_1d[0]] * 2)
+            assert_allclose(res_2d[1], [res_1d[1]] * 2)
+
+    def test_normaltest_result_attributes(self):
+        x = np.array((-2, -1, 0, 1, 2, 3)*4)**2
+        res = mstats.normaltest(x)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+    def test_kurtosistest_result_attributes(self):
+        x = np.array((-2, -1, 0, 1, 2, 3)*4)**2
+        res = mstats.kurtosistest(x)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+    def test_regression_9033(self):
+        # x clearly non-normal but power of negative denom needs
+        # to be handled correctly to reject normality
+        counts = [128, 0, 58, 7, 0, 41, 16, 0, 0, 167]
+        x = np.hstack([np.full(c, i) for i, c in enumerate(counts)])
+        assert_equal(mstats.kurtosistest(x)[1] < 0.01, True)
+
+    @pytest.mark.parametrize("test", ["skewtest", "kurtosistest"])
+    @pytest.mark.parametrize("alternative", ["less", "greater"])
+    def test_alternative(self, test, alternative):
+        x = stats.norm.rvs(loc=10, scale=2.5, size=30, random_state=123)
+
+        stats_test = getattr(stats, test)
+        mstats_test = getattr(mstats, test)
+
+        z_ex, p_ex = stats_test(x, alternative=alternative)
+        z, p = mstats_test(x, alternative=alternative)
+        assert_allclose(z, z_ex, atol=1e-12)
+        assert_allclose(p, p_ex, atol=1e-12)
+
+        # test with masked arrays
+        x[1:5] = np.nan
+        x = np.ma.masked_array(x, mask=np.isnan(x))
+        z_ex, p_ex = stats_test(x.compressed(), alternative=alternative)
+        z, p = mstats_test(x, alternative=alternative)
+        assert_allclose(z, z_ex, atol=1e-12)
+        assert_allclose(p, p_ex, atol=1e-12)
+
+    def test_bad_alternative(self):
+        x = stats.norm.rvs(size=20, random_state=123)
+        msg = r"`alternative` must be..."
+
+        with pytest.raises(ValueError, match=msg):
+            mstats.skewtest(x, alternative='error')
+
+        with pytest.raises(ValueError, match=msg):
+            mstats.kurtosistest(x, alternative='error')
+
+
+class TestFOneway:
+    def test_result_attributes(self):
+        a = np.array([655, 788], dtype=np.uint16)
+        b = np.array([789, 772], dtype=np.uint16)
+        res = mstats.f_oneway(a, b)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+
+class TestMannwhitneyu:
+    # data from gh-1428
+    x = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 2., 1., 1., 2.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 3., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1.])
+
+    y = np.array([1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1., 1., 1., 1.,
+                  2., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2., 1., 1., 3.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1.,
+                  1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2.,
+                  2., 1., 1., 2., 1., 1., 2., 1., 2., 1., 1., 1., 1., 2.,
+                  2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  1., 2., 1., 1., 1., 1., 1., 2., 2., 2., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                  2., 1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1.,
+                  1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 2., 1., 1.,
+                  1., 1., 1., 1.])
+
+    def test_result_attributes(self):
+        res = mstats.mannwhitneyu(self.x, self.y)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+    def test_against_stats(self):
+        # gh-4641 reported that stats.mannwhitneyu returned half the p-value
+        # of mstats.mannwhitneyu. Default alternative of stats.mannwhitneyu
+        # is now two-sided, so they match.
+        res1 = mstats.mannwhitneyu(self.x, self.y)
+        res2 = stats.mannwhitneyu(self.x, self.y)
+        assert res1.statistic == res2.statistic
+        assert_allclose(res1.pvalue, res2.pvalue)
+
+
+class TestKruskal:
+    def test_result_attributes(self):
+        x = [1, 3, 5, 7, 9]
+        y = [2, 4, 6, 8, 10]
+
+        res = mstats.kruskal(x, y)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+
+# TODO: for all ttest functions, add tests with masked array inputs
+class TestTtest_rel:
+    def test_vs_nonmasked(self):
+        np.random.seed(1234567)
+        outcome = np.random.randn(20, 4) + [0, 0, 1, 2]
+
+        # 1-D inputs
+        res1 = stats.ttest_rel(outcome[:, 0], outcome[:, 1])
+        res2 = mstats.ttest_rel(outcome[:, 0], outcome[:, 1])
+        assert_allclose(res1, res2)
+
+        # 2-D inputs
+        res1 = stats.ttest_rel(outcome[:, 0], outcome[:, 1], axis=None)
+        res2 = mstats.ttest_rel(outcome[:, 0], outcome[:, 1], axis=None)
+        assert_allclose(res1, res2)
+        res1 = stats.ttest_rel(outcome[:, :2], outcome[:, 2:], axis=0)
+        res2 = mstats.ttest_rel(outcome[:, :2], outcome[:, 2:], axis=0)
+        assert_allclose(res1, res2)
+
+        # Check default is axis=0
+        res3 = mstats.ttest_rel(outcome[:, :2], outcome[:, 2:])
+        assert_allclose(res2, res3)
+
+    def test_fully_masked(self):
+        np.random.seed(1234567)
+        outcome = ma.masked_array(np.random.randn(3, 2),
+                                  mask=[[1, 1, 1], [0, 0, 0]])
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in absolute")
+            for pair in [(outcome[:, 0], outcome[:, 1]),
+                         ([np.nan, np.nan], [1.0, 2.0])]:
+                t, p = mstats.ttest_rel(*pair)
+                assert_array_equal(t, (np.nan, np.nan))
+                assert_array_equal(p, (np.nan, np.nan))
+
+    def test_result_attributes(self):
+        np.random.seed(1234567)
+        outcome = np.random.randn(20, 4) + [0, 0, 1, 2]
+
+        res = mstats.ttest_rel(outcome[:, 0], outcome[:, 1])
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+    def test_invalid_input_size(self):
+        assert_raises(ValueError, mstats.ttest_rel,
+                      np.arange(10), np.arange(11))
+        x = np.arange(24)
+        assert_raises(ValueError, mstats.ttest_rel,
+                      x.reshape(2, 3, 4), x.reshape(2, 4, 3), axis=1)
+        assert_raises(ValueError, mstats.ttest_rel,
+                      x.reshape(2, 3, 4), x.reshape(2, 4, 3), axis=2)
+
+    def test_empty(self):
+        res1 = mstats.ttest_rel([], [])
+        assert_(np.all(np.isnan(res1)))
+
+    def test_zero_division(self):
+        t, p = mstats.ttest_ind([0, 0, 0], [1, 1, 1])
+        assert_equal((np.abs(t), p), (np.inf, 0))
+
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in absolute")
+            t, p = mstats.ttest_ind([0, 0, 0], [0, 0, 0])
+            assert_array_equal(t, np.array([np.nan, np.nan]))
+            assert_array_equal(p, np.array([np.nan, np.nan]))
+
+    def test_bad_alternative(self):
+        msg = r"alternative must be 'less', 'greater' or 'two-sided'"
+        with pytest.raises(ValueError, match=msg):
+            mstats.ttest_ind([1, 2, 3], [4, 5, 6], alternative='foo')
+
+    @pytest.mark.parametrize("alternative", ["less", "greater"])
+    def test_alternative(self, alternative):
+        x = stats.norm.rvs(loc=10, scale=5, size=25, random_state=42)
+        y = stats.norm.rvs(loc=8, scale=2, size=25, random_state=42)
+
+        t_ex, p_ex = stats.ttest_rel(x, y, alternative=alternative)
+        t, p = mstats.ttest_rel(x, y, alternative=alternative)
+        assert_allclose(t, t_ex, rtol=1e-14)
+        assert_allclose(p, p_ex, rtol=1e-14)
+
+        # test with masked arrays
+        x[1:10] = np.nan
+        y[1:10] = np.nan
+        x = np.ma.masked_array(x, mask=np.isnan(x))
+        y = np.ma.masked_array(y, mask=np.isnan(y))
+        t, p = mstats.ttest_rel(x, y, alternative=alternative)
+        t_ex, p_ex = stats.ttest_rel(x.compressed(), y.compressed(),
+                                     alternative=alternative)
+        assert_allclose(t, t_ex, rtol=1e-14)
+        assert_allclose(p, p_ex, rtol=1e-14)
+
+
+class TestTtest_ind:
+    def test_vs_nonmasked(self):
+        np.random.seed(1234567)
+        outcome = np.random.randn(20, 4) + [0, 0, 1, 2]
+
+        # 1-D inputs
+        res1 = stats.ttest_ind(outcome[:, 0], outcome[:, 1])
+        res2 = mstats.ttest_ind(outcome[:, 0], outcome[:, 1])
+        assert_allclose(res1, res2)
+
+        # 2-D inputs
+        res1 = stats.ttest_ind(outcome[:, 0], outcome[:, 1], axis=None)
+        res2 = mstats.ttest_ind(outcome[:, 0], outcome[:, 1], axis=None)
+        assert_allclose(res1, res2)
+        res1 = stats.ttest_ind(outcome[:, :2], outcome[:, 2:], axis=0)
+        res2 = mstats.ttest_ind(outcome[:, :2], outcome[:, 2:], axis=0)
+        assert_allclose(res1, res2)
+
+        # Check default is axis=0
+        res3 = mstats.ttest_ind(outcome[:, :2], outcome[:, 2:])
+        assert_allclose(res2, res3)
+
+        # Check equal_var
+        res4 = stats.ttest_ind(outcome[:, 0], outcome[:, 1], equal_var=True)
+        res5 = mstats.ttest_ind(outcome[:, 0], outcome[:, 1], equal_var=True)
+        assert_allclose(res4, res5)
+        res4 = stats.ttest_ind(outcome[:, 0], outcome[:, 1], equal_var=False)
+        res5 = mstats.ttest_ind(outcome[:, 0], outcome[:, 1], equal_var=False)
+        assert_allclose(res4, res5)
+
+    def test_fully_masked(self):
+        np.random.seed(1234567)
+        outcome = ma.masked_array(np.random.randn(3, 2), mask=[[1, 1, 1], [0, 0, 0]])
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in absolute")
+            for pair in [(outcome[:, 0], outcome[:, 1]),
+                         ([np.nan, np.nan], [1.0, 2.0])]:
+                t, p = mstats.ttest_ind(*pair)
+                assert_array_equal(t, (np.nan, np.nan))
+                assert_array_equal(p, (np.nan, np.nan))
+
+    def test_result_attributes(self):
+        np.random.seed(1234567)
+        outcome = np.random.randn(20, 4) + [0, 0, 1, 2]
+
+        res = mstats.ttest_ind(outcome[:, 0], outcome[:, 1])
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+    def test_empty(self):
+        res1 = mstats.ttest_ind([], [])
+        assert_(np.all(np.isnan(res1)))
+
+    def test_zero_division(self):
+        t, p = mstats.ttest_ind([0, 0, 0], [1, 1, 1])
+        assert_equal((np.abs(t), p), (np.inf, 0))
+
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in absolute")
+            t, p = mstats.ttest_ind([0, 0, 0], [0, 0, 0])
+            assert_array_equal(t, (np.nan, np.nan))
+            assert_array_equal(p, (np.nan, np.nan))
+
+        t, p = mstats.ttest_ind([0, 0, 0], [1, 1, 1], equal_var=False)
+        assert_equal((np.abs(t), p), (np.inf, 0))
+        assert_array_equal(mstats.ttest_ind([0, 0, 0], [0, 0, 0],
+                                            equal_var=False), (np.nan, np.nan))
+
+    def test_bad_alternative(self):
+        msg = r"alternative must be 'less', 'greater' or 'two-sided'"
+        with pytest.raises(ValueError, match=msg):
+            mstats.ttest_ind([1, 2, 3], [4, 5, 6], alternative='foo')
+
+    @pytest.mark.parametrize("alternative", ["less", "greater"])
+    def test_alternative(self, alternative):
+        x = stats.norm.rvs(loc=10, scale=2, size=100, random_state=123)
+        y = stats.norm.rvs(loc=8, scale=2, size=100, random_state=123)
+
+        t_ex, p_ex = stats.ttest_ind(x, y, alternative=alternative)
+        t, p = mstats.ttest_ind(x, y, alternative=alternative)
+        assert_allclose(t, t_ex, rtol=1e-14)
+        assert_allclose(p, p_ex, rtol=1e-14)
+
+        # test with masked arrays
+        x[1:10] = np.nan
+        y[80:90] = np.nan
+        x = np.ma.masked_array(x, mask=np.isnan(x))
+        y = np.ma.masked_array(y, mask=np.isnan(y))
+        t_ex, p_ex = stats.ttest_ind(x.compressed(), y.compressed(),
+                                     alternative=alternative)
+        t, p = mstats.ttest_ind(x, y, alternative=alternative)
+        assert_allclose(t, t_ex, rtol=1e-14)
+        assert_allclose(p, p_ex, rtol=1e-14)
+
+
+class TestTtest_1samp:
+    def test_vs_nonmasked(self):
+        np.random.seed(1234567)
+        outcome = np.random.randn(20, 4) + [0, 0, 1, 2]
+
+        # 1-D inputs
+        res1 = stats.ttest_1samp(outcome[:, 0], 1)
+        res2 = mstats.ttest_1samp(outcome[:, 0], 1)
+        assert_allclose(res1, res2)
+
+    def test_fully_masked(self):
+        np.random.seed(1234567)
+        outcome = ma.masked_array(np.random.randn(3), mask=[1, 1, 1])
+        expected = (np.nan, np.nan)
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in absolute")
+            for pair in [((np.nan, np.nan), 0.0), (outcome, 0.0)]:
+                t, p = mstats.ttest_1samp(*pair)
+                assert_array_equal(p, expected)
+                assert_array_equal(t, expected)
+
+    def test_result_attributes(self):
+        np.random.seed(1234567)
+        outcome = np.random.randn(20, 4) + [0, 0, 1, 2]
+
+        res = mstats.ttest_1samp(outcome[:, 0], 1)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+    def test_empty(self):
+        res1 = mstats.ttest_1samp([], 1)
+        assert_(np.all(np.isnan(res1)))
+
+    def test_zero_division(self):
+        t, p = mstats.ttest_1samp([0, 0, 0], 1)
+        assert_equal((np.abs(t), p), (np.inf, 0))
+
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in absolute")
+            t, p = mstats.ttest_1samp([0, 0, 0], 0)
+            assert_(np.isnan(t))
+            assert_array_equal(p, (np.nan, np.nan))
+
+    def test_bad_alternative(self):
+        msg = r"alternative must be 'less', 'greater' or 'two-sided'"
+        with pytest.raises(ValueError, match=msg):
+            mstats.ttest_1samp([1, 2, 3], 4, alternative='foo')
+
+    @pytest.mark.parametrize("alternative", ["less", "greater"])
+    def test_alternative(self, alternative):
+        x = stats.norm.rvs(loc=10, scale=2, size=100, random_state=123)
+
+        t_ex, p_ex = stats.ttest_1samp(x, 9, alternative=alternative)
+        t, p = mstats.ttest_1samp(x, 9, alternative=alternative)
+        assert_allclose(t, t_ex, rtol=1e-14)
+        assert_allclose(p, p_ex, rtol=1e-14)
+
+        # test with masked arrays
+        x[1:10] = np.nan
+        x = np.ma.masked_array(x, mask=np.isnan(x))
+        t_ex, p_ex = stats.ttest_1samp(x.compressed(), 9,
+                                       alternative=alternative)
+        t, p = mstats.ttest_1samp(x, 9, alternative=alternative)
+        assert_allclose(t, t_ex, rtol=1e-14)
+        assert_allclose(p, p_ex, rtol=1e-14)
+
+
+class TestDescribe:
+    """
+    Tests for mstats.describe.
+
+    Note that there are also tests for `mstats.describe` in the
+    class TestCompareWithStats.
+    """
+    def test_basic_with_axis(self):
+        # This is a basic test that is also a regression test for gh-7303.
+        a = np.ma.masked_array([[0, 1, 2, 3, 4, 9],
+                                [5, 5, 0, 9, 3, 3]],
+                               mask=[[0, 0, 0, 0, 0, 1],
+                                     [0, 0, 1, 1, 0, 0]])
+        result = mstats.describe(a, axis=1)
+        assert_equal(result.nobs, [5, 4])
+        amin, amax = result.minmax
+        assert_equal(amin, [0, 3])
+        assert_equal(amax, [4, 5])
+        assert_equal(result.mean, [2.0, 4.0])
+        assert_equal(result.variance, [2.0, 1.0])
+        assert_equal(result.skewness, [0.0, 0.0])
+        assert_allclose(result.kurtosis, [-1.3, -2.0])
+
+
+@skip_xp_invalid_arg
+class TestCompareWithStats:
+    """
+    Class to compare mstats results with stats results.
+
+    It is in general assumed that scipy.stats is at a more mature stage than
+    stats.mstats.  If a routine in mstats results in similar results like in
+    scipy.stats, this is considered also as a proper validation of scipy.mstats
+    routine.
+
+    Different sample sizes are used for testing, as some problems between stats
+    and mstats are dependent on sample size.
+
+    Author: Alexander Loew
+
+    NOTE that some tests fail. This might be caused by
+    a) actual differences or bugs between stats and mstats
+    b) numerical inaccuracies
+    c) different definitions of routine interfaces
+
+    These failures need to be checked. Current workaround is to have disabled these
+    tests, but issuing reports on scipy-dev
+
+    """
+    def get_n(self):
+        """ Returns list of sample sizes to be used for comparison. """
+        return [1000, 100, 10, 5]
+
+    def generate_xy_sample(self, n):
+        # This routine generates numpy arrays and corresponding masked arrays
+        # with the same data, but additional masked values
+        np.random.seed(1234567)
+        x = np.random.randn(n)
+        y = x + np.random.randn(n)
+        xm = np.full(len(x) + 5, 1e16)
+        ym = np.full(len(y) + 5, 1e16)
+        xm[0:len(x)] = x
+        ym[0:len(y)] = y
+        mask = xm > 9e15
+        xm = np.ma.array(xm, mask=mask)
+        ym = np.ma.array(ym, mask=mask)
+        return x, y, xm, ym
+
+    def generate_xy_sample2D(self, n, nx):
+        x = np.full((n, nx), np.nan)
+        y = np.full((n, nx), np.nan)
+        xm = np.full((n+5, nx), np.nan)
+        ym = np.full((n+5, nx), np.nan)
+
+        for i in range(nx):
+            x[:, i], y[:, i], dx, dy = self.generate_xy_sample(n)
+
+        xm[0:n, :] = x[0:n]
+        ym[0:n, :] = y[0:n]
+        xm = np.ma.array(xm, mask=np.isnan(xm))
+        ym = np.ma.array(ym, mask=np.isnan(ym))
+        return x, y, xm, ym
+
+    def test_linregress(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            result1 = stats.linregress(x, y)
+            result2 = stats.mstats.linregress(xm, ym)
+            assert_allclose(np.asarray(result1), np.asarray(result2))
+
+    def test_pearsonr(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            r, p = stats.pearsonr(x, y)
+            rm, pm = stats.mstats.pearsonr(xm, ym)
+
+            assert_almost_equal(r, rm, decimal=14)
+            assert_almost_equal(p, pm, decimal=14)
+
+    def test_spearmanr(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            r, p = stats.spearmanr(x, y)
+            rm, pm = stats.mstats.spearmanr(xm, ym)
+            assert_almost_equal(r, rm, 14)
+            assert_almost_equal(p, pm, 14)
+
+    def test_spearmanr_backcompat_useties(self):
+        # A regression test to ensure we don't break backwards compat
+        # more than we have to (see gh-9204).
+        x = np.arange(6)
+        assert_raises(ValueError, mstats.spearmanr, x, x, False)
+
+    def test_gmean(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            r = stats.gmean(abs(x))
+            rm = stats.mstats.gmean(abs(xm))
+            assert_allclose(r, rm, rtol=1e-13)
+
+            r = stats.gmean(abs(y))
+            rm = stats.mstats.gmean(abs(ym))
+            assert_allclose(r, rm, rtol=1e-13)
+
+    def test_hmean(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+
+            r = stats.hmean(abs(x))
+            rm = stats.mstats.hmean(abs(xm))
+            assert_almost_equal(r, rm, 10)
+
+            r = stats.hmean(abs(y))
+            rm = stats.mstats.hmean(abs(ym))
+            assert_almost_equal(r, rm, 10)
+
+    def test_skew(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+
+            r = stats.skew(x)
+            rm = stats.mstats.skew(xm)
+            assert_almost_equal(r, rm, 10)
+
+            r = stats.skew(y)
+            rm = stats.mstats.skew(ym)
+            assert_almost_equal(r, rm, 10)
+
+    def test_moment(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+
+            r = stats.moment(x)
+            rm = stats.mstats.moment(xm)
+            assert_almost_equal(r, rm, 10)
+
+            r = stats.moment(y)
+            rm = stats.mstats.moment(ym)
+            assert_almost_equal(r, rm, 10)
+
+    def test_zscore(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+
+            # reference solution
+            zx = (x - x.mean()) / x.std()
+            zy = (y - y.mean()) / y.std()
+
+            # validate stats
+            assert_allclose(stats.zscore(x), zx, rtol=1e-10)
+            assert_allclose(stats.zscore(y), zy, rtol=1e-10)
+
+            # compare stats and mstats
+            assert_allclose(stats.zscore(x), stats.mstats.zscore(xm[0:len(x)]),
+                            rtol=1e-10)
+            assert_allclose(stats.zscore(y), stats.mstats.zscore(ym[0:len(y)]),
+                            rtol=1e-10)
+
+    def test_kurtosis(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            r = stats.kurtosis(x)
+            rm = stats.mstats.kurtosis(xm)
+            assert_almost_equal(r, rm, 10)
+
+            r = stats.kurtosis(y)
+            rm = stats.mstats.kurtosis(ym)
+            assert_almost_equal(r, rm, 10)
+
+    def test_sem(self):
+        # example from stats.sem doc
+        a = np.arange(20).reshape(5, 4)
+        am = np.ma.array(a)
+        r = stats.sem(a, ddof=1)
+        rm = stats.mstats.sem(am, ddof=1)
+
+        assert_allclose(r, 2.82842712, atol=1e-5)
+        assert_allclose(rm, 2.82842712, atol=1e-5)
+
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            assert_almost_equal(stats.mstats.sem(xm, axis=None, ddof=0),
+                                stats.sem(x, axis=None, ddof=0), decimal=13)
+            assert_almost_equal(stats.mstats.sem(ym, axis=None, ddof=0),
+                                stats.sem(y, axis=None, ddof=0), decimal=13)
+            assert_almost_equal(stats.mstats.sem(xm, axis=None, ddof=1),
+                                stats.sem(x, axis=None, ddof=1), decimal=13)
+            assert_almost_equal(stats.mstats.sem(ym, axis=None, ddof=1),
+                                stats.sem(y, axis=None, ddof=1), decimal=13)
+
+    def test_describe(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            r = stats.describe(x, ddof=1)
+            rm = stats.mstats.describe(xm, ddof=1)
+            for ii in range(6):
+                assert_almost_equal(np.asarray(r[ii]),
+                                    np.asarray(rm[ii]),
+                                    decimal=12)
+
+    def test_describe_result_attributes(self):
+        actual = mstats.describe(np.arange(5))
+        attributes = ('nobs', 'minmax', 'mean', 'variance', 'skewness',
+                      'kurtosis')
+        check_named_results(actual, attributes, ma=True)
+
+    def test_rankdata(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            r = stats.rankdata(x)
+            rm = stats.mstats.rankdata(x)
+            assert_allclose(r, rm)
+
+    def test_tmean(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            assert_almost_equal(stats.tmean(x),stats.mstats.tmean(xm), 14)
+            assert_almost_equal(stats.tmean(y),stats.mstats.tmean(ym), 14)
+
+    def test_tmax(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            assert_almost_equal(stats.tmax(x,2.),
+                                stats.mstats.tmax(xm,2.), 10)
+            assert_almost_equal(stats.tmax(y,2.),
+                                stats.mstats.tmax(ym,2.), 10)
+
+            assert_almost_equal(stats.tmax(x, upperlimit=3.),
+                                stats.mstats.tmax(xm, upperlimit=3.), 10)
+            assert_almost_equal(stats.tmax(y, upperlimit=3.),
+                                stats.mstats.tmax(ym, upperlimit=3.), 10)
+
+    def test_tmin(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            assert_equal(stats.tmin(x), stats.mstats.tmin(xm))
+            assert_equal(stats.tmin(y), stats.mstats.tmin(ym))
+
+            assert_almost_equal(stats.tmin(x, lowerlimit=-1.),
+                                stats.mstats.tmin(xm, lowerlimit=-1.), 10)
+            assert_almost_equal(stats.tmin(y, lowerlimit=-1.),
+                                stats.mstats.tmin(ym, lowerlimit=-1.), 10)
+
+    def test_zmap(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            z = stats.zmap(x, y)
+            zm = stats.mstats.zmap(xm, ym)
+            assert_allclose(z, zm[0:len(z)], atol=1e-10)
+
+    def test_variation(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            assert_almost_equal(stats.variation(x), stats.mstats.variation(xm),
+                                decimal=12)
+            assert_almost_equal(stats.variation(y), stats.mstats.variation(ym),
+                                decimal=12)
+
+    def test_tvar(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            assert_almost_equal(stats.tvar(x), stats.mstats.tvar(xm),
+                                decimal=12)
+            assert_almost_equal(stats.tvar(y), stats.mstats.tvar(ym),
+                                decimal=12)
+
+    def test_trimboth(self):
+        a = np.arange(20)
+        b = stats.trimboth(a, 0.1)
+        bm = stats.mstats.trimboth(a, 0.1)
+        assert_allclose(np.sort(b), bm.data[~bm.mask])
+
+    def test_tsem(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            assert_almost_equal(stats.tsem(x), stats.mstats.tsem(xm),
+                                decimal=14)
+            assert_almost_equal(stats.tsem(y), stats.mstats.tsem(ym),
+                                decimal=14)
+            assert_almost_equal(stats.tsem(x, limits=(-2., 2.)),
+                                stats.mstats.tsem(xm, limits=(-2., 2.)),
+                                decimal=14)
+
+    def test_skewtest(self):
+        # this test is for 1D data
+        for n in self.get_n():
+            if n > 8:
+                x, y, xm, ym = self.generate_xy_sample(n)
+                r = stats.skewtest(x)
+                rm = stats.mstats.skewtest(xm)
+                assert_allclose(r, rm)
+
+    def test_skewtest_result_attributes(self):
+        x = np.array((-2, -1, 0, 1, 2, 3)*4)**2
+        res = mstats.skewtest(x)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, ma=True)
+
+    def test_skewtest_2D_notmasked(self):
+        # a normal ndarray is passed to the masked function
+        x = np.random.random((20, 2)) * 20.
+        r = stats.skewtest(x)
+        rm = stats.mstats.skewtest(x)
+        assert_allclose(np.asarray(r), np.asarray(rm))
+
+    def test_skewtest_2D_WithMask(self):
+        nx = 2
+        for n in self.get_n():
+            if n > 8:
+                x, y, xm, ym = self.generate_xy_sample2D(n, nx)
+                r = stats.skewtest(x)
+                rm = stats.mstats.skewtest(xm)
+
+                assert_allclose(r[0][0], rm[0][0], rtol=1e-14)
+                assert_allclose(r[0][1], rm[0][1], rtol=1e-14)
+
+    def test_normaltest(self):
+        with np.errstate(over='raise'), suppress_warnings() as sup:
+            sup.filter(UserWarning, "`kurtosistest` p-value may be inaccurate")
+            sup.filter(UserWarning, "kurtosistest only valid for n>=20")
+            for n in self.get_n():
+                if n > 8:
+                    x, y, xm, ym = self.generate_xy_sample(n)
+                    r = stats.normaltest(x)
+                    rm = stats.mstats.normaltest(xm)
+                    assert_allclose(np.asarray(r), np.asarray(rm))
+
+    def test_find_repeats(self):
+        x = np.asarray([1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4]).astype('float')
+        tmp = np.asarray([1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]).astype('float')
+        mask = (tmp == 5.)
+        xm = np.ma.array(tmp, mask=mask)
+        x_orig, xm_orig = x.copy(), xm.copy()
+
+        unique, unique_counts = np.unique(x, return_counts=True)
+        r = unique[unique_counts > 1], unique_counts[unique_counts > 1]
+        rm = stats.mstats.find_repeats(xm)
+
+        assert_equal(r, rm)
+        assert_equal(x, x_orig)
+        assert_equal(xm, xm_orig)
+
+        # This crazy behavior is expected by count_tied_groups, but is not
+        # in the docstring...
+        _, counts = stats.mstats.find_repeats([])
+        assert_equal(counts, np.array(0, dtype=np.intp))
+
+    def test_kendalltau(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            r = stats.kendalltau(x, y)
+            rm = stats.mstats.kendalltau(xm, ym)
+            assert_almost_equal(r[0], rm[0], decimal=10)
+            assert_almost_equal(r[1], rm[1], decimal=7)
+
+    def test_obrientransform(self):
+        for n in self.get_n():
+            x, y, xm, ym = self.generate_xy_sample(n)
+            r = stats.obrientransform(x)
+            rm = stats.mstats.obrientransform(xm)
+            assert_almost_equal(r.T, rm[0:len(x)])
+
+    def test_ks_1samp(self):
+        """Checks that mstats.ks_1samp and stats.ks_1samp agree on masked arrays."""
+        for mode in ['auto', 'exact', 'asymp']:
+            with suppress_warnings():
+                for alternative in ['less', 'greater', 'two-sided']:
+                    for n in self.get_n():
+                        x, y, xm, ym = self.generate_xy_sample(n)
+                        res1 = stats.ks_1samp(x, stats.norm.cdf,
+                                              alternative=alternative, mode=mode)
+                        res2 = stats.mstats.ks_1samp(xm, stats.norm.cdf,
+                                                     alternative=alternative, mode=mode)
+                        assert_equal(np.asarray(res1), np.asarray(res2))
+                        res3 = stats.ks_1samp(xm, stats.norm.cdf,
+                                              alternative=alternative, mode=mode)
+                        assert_equal(np.asarray(res1), np.asarray(res3))
+
+    def test_kstest_1samp(self):
+        """
+        Checks that 1-sample mstats.kstest and stats.kstest agree on masked arrays.
+        """
+        for mode in ['auto', 'exact', 'asymp']:
+            with suppress_warnings():
+                for alternative in ['less', 'greater', 'two-sided']:
+                    for n in self.get_n():
+                        x, y, xm, ym = self.generate_xy_sample(n)
+                        res1 = stats.kstest(x, 'norm',
+                                            alternative=alternative, mode=mode)
+                        res2 = stats.mstats.kstest(xm, 'norm',
+                                                   alternative=alternative, mode=mode)
+                        assert_equal(np.asarray(res1), np.asarray(res2))
+                        res3 = stats.kstest(xm, 'norm',
+                                            alternative=alternative, mode=mode)
+                        assert_equal(np.asarray(res1), np.asarray(res3))
+
+    def test_ks_2samp(self):
+        """Checks that mstats.ks_2samp and stats.ks_2samp agree on masked arrays.
+        gh-8431"""
+        for mode in ['auto', 'exact', 'asymp']:
+            with suppress_warnings() as sup:
+                if mode in ['auto', 'exact']:
+                    message = "ks_2samp: Exact calculation unsuccessful."
+                    sup.filter(RuntimeWarning, message)
+                for alternative in ['less', 'greater', 'two-sided']:
+                    for n in self.get_n():
+                        x, y, xm, ym = self.generate_xy_sample(n)
+                        res1 = stats.ks_2samp(x, y,
+                                              alternative=alternative, mode=mode)
+                        res2 = stats.mstats.ks_2samp(xm, ym,
+                                                     alternative=alternative, mode=mode)
+                        assert_equal(np.asarray(res1), np.asarray(res2))
+                        res3 = stats.ks_2samp(xm, y,
+                                              alternative=alternative, mode=mode)
+                        assert_equal(np.asarray(res1), np.asarray(res3))
+
+    def test_kstest_2samp(self):
+        """
+        Checks that 2-sample mstats.kstest and stats.kstest agree on masked arrays.
+        """
+        for mode in ['auto', 'exact', 'asymp']:
+            with suppress_warnings() as sup:
+                if mode in ['auto', 'exact']:
+                    message = "ks_2samp: Exact calculation unsuccessful."
+                    sup.filter(RuntimeWarning, message)
+                for alternative in ['less', 'greater', 'two-sided']:
+                    for n in self.get_n():
+                        x, y, xm, ym = self.generate_xy_sample(n)
+                        res1 = stats.kstest(x, y,
+                                            alternative=alternative, mode=mode)
+                        res2 = stats.mstats.kstest(xm, ym,
+                                                   alternative=alternative, mode=mode)
+                        assert_equal(np.asarray(res1), np.asarray(res2))
+                        res3 = stats.kstest(xm, y,
+                                            alternative=alternative, mode=mode)
+                        assert_equal(np.asarray(res1), np.asarray(res3))
+
+
+class TestBrunnerMunzel:
+    # Data from (Lumley, 1996)
+    X = np.ma.masked_invalid([1, 2, 1, 1, 1, np.nan, 1, 1,
+                              1, 1, 1, 2, 4, 1, 1, np.nan])
+    Y = np.ma.masked_invalid([3, 3, 4, 3, np.nan, 1, 2, 3, 1, 1, 5, 4])
+    significant = 14
+
+    def test_brunnermunzel_one_sided(self):
+        # Results are compared with R's lawstat package.
+        u1, p1 = mstats.brunnermunzel(self.X, self.Y, alternative='less')
+        u2, p2 = mstats.brunnermunzel(self.Y, self.X, alternative='greater')
+        u3, p3 = mstats.brunnermunzel(self.X, self.Y, alternative='greater')
+        u4, p4 = mstats.brunnermunzel(self.Y, self.X, alternative='less')
+
+        assert_almost_equal(p1, p2, decimal=self.significant)
+        assert_almost_equal(p3, p4, decimal=self.significant)
+        assert_(p1 != p3)
+        assert_almost_equal(u1, 3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(u2, -3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(u3, 3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(u4, -3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(p1, 0.0028931043330757342,
+                            decimal=self.significant)
+        assert_almost_equal(p3, 0.99710689566692423,
+                            decimal=self.significant)
+
+    def test_brunnermunzel_two_sided(self):
+        # Results are compared with R's lawstat package.
+        u1, p1 = mstats.brunnermunzel(self.X, self.Y, alternative='two-sided')
+        u2, p2 = mstats.brunnermunzel(self.Y, self.X, alternative='two-sided')
+
+        assert_almost_equal(p1, p2, decimal=self.significant)
+        assert_almost_equal(u1, 3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(u2, -3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(p1, 0.0057862086661515377,
+                            decimal=self.significant)
+
+    def test_brunnermunzel_default(self):
+        # The default value for alternative is two-sided
+        u1, p1 = mstats.brunnermunzel(self.X, self.Y)
+        u2, p2 = mstats.brunnermunzel(self.Y, self.X)
+
+        assert_almost_equal(p1, p2, decimal=self.significant)
+        assert_almost_equal(u1, 3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(u2, -3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(p1, 0.0057862086661515377,
+                            decimal=self.significant)
+
+    def test_brunnermunzel_alternative_error(self):
+        alternative = "error"
+        distribution = "t"
+        assert_(alternative not in ["two-sided", "greater", "less"])
+        assert_raises(ValueError,
+                      mstats.brunnermunzel,
+                      self.X,
+                      self.Y,
+                      alternative,
+                      distribution)
+
+    def test_brunnermunzel_distribution_norm(self):
+        u1, p1 = mstats.brunnermunzel(self.X, self.Y, distribution="normal")
+        u2, p2 = mstats.brunnermunzel(self.Y, self.X, distribution="normal")
+        assert_almost_equal(p1, p2, decimal=self.significant)
+        assert_almost_equal(u1, 3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(u2, -3.1374674823029505,
+                            decimal=self.significant)
+        assert_almost_equal(p1, 0.0017041417600383024,
+                            decimal=self.significant)
+
+    def test_brunnermunzel_distribution_error(self):
+        alternative = "two-sided"
+        distribution = "error"
+        assert_(alternative not in ["t", "normal"])
+        assert_raises(ValueError,
+                      mstats.brunnermunzel,
+                      self.X,
+                      self.Y,
+                      alternative,
+                      distribution)
+
+    def test_brunnermunzel_empty_imput(self):
+        u1, p1 = mstats.brunnermunzel(self.X, [])
+        u2, p2 = mstats.brunnermunzel([], self.Y)
+        u3, p3 = mstats.brunnermunzel([], [])
+
+        assert_(np.isnan(u1))
+        assert_(np.isnan(p1))
+        assert_(np.isnan(u2))
+        assert_(np.isnan(p2))
+        assert_(np.isnan(u3))
+        assert_(np.isnan(p3))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_extras.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_extras.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b9fd0d80a6e05652c5151f5dfece2c5979dbfe5
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_mstats_extras.py
@@ -0,0 +1,172 @@
+import numpy as np
+import numpy.ma as ma
+import scipy.stats.mstats as ms
+
+from numpy.testing import (assert_equal, assert_almost_equal, assert_,
+                           assert_allclose)
+
+
+def test_compare_medians_ms():
+    x = np.arange(7)
+    y = x + 10
+    assert_almost_equal(ms.compare_medians_ms(x, y), 0)
+
+    y2 = np.linspace(0, 1, num=10)
+    assert_almost_equal(ms.compare_medians_ms(x, y2), 0.017116406778)
+
+
+def test_hdmedian():
+    # 1-D array
+    x = ma.arange(11)
+    assert_allclose(ms.hdmedian(x), 5, rtol=1e-14)
+    x.mask = ma.make_mask(x)
+    x.mask[:7] = False
+    assert_allclose(ms.hdmedian(x), 3, rtol=1e-14)
+
+    # Check that `var` keyword returns a value.  TODO: check whether returned
+    # value is actually correct.
+    assert_(ms.hdmedian(x, var=True).size == 2)
+
+    # 2-D array
+    x2 = ma.arange(22).reshape((11, 2))
+    assert_allclose(ms.hdmedian(x2, axis=0), [10, 11])
+    x2.mask = ma.make_mask(x2)
+    x2.mask[:7, :] = False
+    assert_allclose(ms.hdmedian(x2, axis=0), [6, 7])
+
+
+def test_rsh():
+    np.random.seed(132345)
+    x = np.random.randn(100)
+    res = ms.rsh(x)
+    # Just a sanity check that the code runs and output shape is correct.
+    # TODO: check that implementation is correct.
+    assert_(res.shape == x.shape)
+
+    # Check points keyword
+    res = ms.rsh(x, points=[0, 1.])
+    assert_(res.size == 2)
+
+
+def test_mjci():
+    # Tests the Marits-Jarrett estimator
+    data = ma.array([77, 87, 88,114,151,210,219,246,253,262,
+                     296,299,306,376,428,515,666,1310,2611])
+    assert_almost_equal(ms.mjci(data),[55.76819,45.84028,198.87875],5)
+
+
+def test_trimmed_mean_ci():
+    # Tests the confidence intervals of the trimmed mean.
+    data = ma.array([545,555,558,572,575,576,578,580,
+                     594,605,635,651,653,661,666])
+    assert_almost_equal(ms.trimmed_mean(data,0.2), 596.2, 1)
+    assert_equal(np.round(ms.trimmed_mean_ci(data,(0.2,0.2)),1),
+                 [561.8, 630.6])
+
+
+def test_idealfourths():
+    # Tests ideal-fourths
+    test = np.arange(100)
+    assert_almost_equal(np.asarray(ms.idealfourths(test)),
+                        [24.416667,74.583333],6)
+    test_2D = test.repeat(3).reshape(-1,3)
+    assert_almost_equal(ms.idealfourths(test_2D, axis=0),
+                        [[24.416667,24.416667,24.416667],
+                         [74.583333,74.583333,74.583333]],6)
+    assert_almost_equal(ms.idealfourths(test_2D, axis=1),
+                        test.repeat(2).reshape(-1,2))
+    test = [0, 0]
+    _result = ms.idealfourths(test)
+    assert_(np.isnan(_result).all())
+
+
+class TestQuantiles:
+    data = [0.706560797,0.727229578,0.990399276,0.927065621,0.158953014,
+            0.887764025,0.239407086,0.349638551,0.972791145,0.149789972,
+            0.936947700,0.132359948,0.046041972,0.641675031,0.945530547,
+            0.224218684,0.771450991,0.820257774,0.336458052,0.589113496,
+            0.509736129,0.696838829,0.491323573,0.622767425,0.775189248,
+            0.641461450,0.118455200,0.773029450,0.319280007,0.752229111,
+            0.047841438,0.466295911,0.583850781,0.840581845,0.550086491,
+            0.466470062,0.504765074,0.226855960,0.362641207,0.891620942,
+            0.127898691,0.490094097,0.044882048,0.041441695,0.317976349,
+            0.504135618,0.567353033,0.434617473,0.636243375,0.231803616,
+            0.230154113,0.160011327,0.819464108,0.854706985,0.438809221,
+            0.487427267,0.786907310,0.408367937,0.405534192,0.250444460,
+            0.995309248,0.144389588,0.739947527,0.953543606,0.680051621,
+            0.388382017,0.863530727,0.006514031,0.118007779,0.924024803,
+            0.384236354,0.893687694,0.626534881,0.473051932,0.750134705,
+            0.241843555,0.432947602,0.689538104,0.136934797,0.150206859,
+            0.474335206,0.907775349,0.525869295,0.189184225,0.854284286,
+            0.831089744,0.251637345,0.587038213,0.254475554,0.237781276,
+            0.827928620,0.480283781,0.594514455,0.213641488,0.024194386,
+            0.536668589,0.699497811,0.892804071,0.093835427,0.731107772]
+
+    def test_hdquantiles(self):
+        data = self.data
+        assert_almost_equal(ms.hdquantiles(data,[0., 1.]),
+                            [0.006514031, 0.995309248])
+        hdq = ms.hdquantiles(data,[0.25, 0.5, 0.75])
+        assert_almost_equal(hdq, [0.253210762, 0.512847491, 0.762232442,])
+
+        data = np.array(data).reshape(10,10)
+        hdq = ms.hdquantiles(data,[0.25,0.5,0.75],axis=0)
+        assert_almost_equal(hdq[:,0], ms.hdquantiles(data[:,0],[0.25,0.5,0.75]))
+        assert_almost_equal(hdq[:,-1], ms.hdquantiles(data[:,-1],[0.25,0.5,0.75]))
+        hdq = ms.hdquantiles(data,[0.25,0.5,0.75],axis=0,var=True)
+        assert_almost_equal(hdq[...,0],
+                            ms.hdquantiles(data[:,0],[0.25,0.5,0.75],var=True))
+        assert_almost_equal(hdq[...,-1],
+                            ms.hdquantiles(data[:,-1],[0.25,0.5,0.75], var=True))
+
+    def test_hdquantiles_sd(self):
+        # Standard deviation is a jackknife estimator, so we can check if
+        # the efficient version (hdquantiles_sd) matches a rudimentary,
+        # but clear version here.
+
+        hd_std_errs = ms.hdquantiles_sd(self.data)
+
+        # jacknnife standard error, Introduction to the Bootstrap Eq. 11.5
+        n = len(self.data)
+        jdata = np.broadcast_to(self.data, (n, n))
+        jselector = np.logical_not(np.eye(n))  # leave out one sample each row
+        jdata = jdata[jselector].reshape(n, n-1)
+        jdist = ms.hdquantiles(jdata, axis=1)
+        jdist_mean = np.mean(jdist, axis=0)
+        jstd = ((n-1)/n * np.sum((jdist - jdist_mean)**2, axis=0))**.5
+
+        assert_almost_equal(hd_std_errs, jstd)
+        # Test actual values for good measure
+        assert_almost_equal(hd_std_errs, [0.0379258, 0.0380656, 0.0380013])
+
+        two_data_points = ms.hdquantiles_sd([1, 2])
+        assert_almost_equal(two_data_points, [0.5, 0.5, 0.5])
+
+    def test_mquantiles_cimj(self):
+        # Only test that code runs, implementation not checked for correctness
+        ci_lower, ci_upper = ms.mquantiles_cimj(self.data)
+        assert_(ci_lower.size == ci_upper.size == 3)
+
+
+def test_median_cihs():
+    # Basic test against R library EnvStats function `eqnpar`, e.g.
+    # library(EnvStats)
+    # options(digits=8)
+    # x = c(0.88612955, 0.35242375, 0.66240904, 0.94617974, 0.10929913,
+    #       0.76699506, 0.88550655, 0.62763754, 0.76818588, 0.68506508,
+    #       0.88043148, 0.03911248, 0.93805564, 0.95326961, 0.25291112,
+    #       0.16128487, 0.49784577, 0.24588924, 0.6597, 0.92239679)
+    # eqnpar(x, p=0.5,
+    #        ci.method = "interpolate", approx.conf.level = 0.95, ci = TRUE)
+    rng = np.random.default_rng(8824288259505800535)
+    x = rng.random(size=20)
+    assert_allclose(ms.median_cihs(x), (0.38663198, 0.88431272))
+
+    # SciPy's 90% CI upper limit doesn't match that of EnvStats eqnpar. SciPy
+    # doesn't look wrong, and it agrees with a different reference,
+    # `median_confint_hs` from `hoehleatsu/quantileCI`.
+    # In (e.g.) Colab with R runtime:
+    # devtools::install_github("hoehleatsu/quantileCI")
+    # library(quantileCI)
+    # median_confint_hs(x=x, conf.level=0.90, interpolate=TRUE)
+    assert_allclose(ms.median_cihs(x, 0.1), (0.48319773366, 0.88094268050))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multicomp.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multicomp.py
new file mode 100644
index 0000000000000000000000000000000000000000..2860b142c38a339f96c50af92bd452c6de95e84d
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multicomp.py
@@ -0,0 +1,405 @@
+import copy
+
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose
+
+from scipy import stats
+from scipy.stats._multicomp import _pvalue_dunnett, DunnettResult
+
+
+class TestDunnett:
+    # For the following tests, p-values were computed using Matlab, e.g.
+    #     sample = [18.  15.  18.  16.  17.  15.  14.  14.  14.  15.  15....
+    #               14.  15.  14.  22.  18.  21.  21.  10.  10.  11.  9....
+    #               25.  26.  17.5 16.  15.5 14.5 22.  22.  24.  22.5 29....
+    #               24.5 20.  18.  18.5 17.5 26.5 13.  16.5 13.  13.  13....
+    #               28.  27.  34.  31.  29.  27.  24.  23.  38.  36.  25....
+    #               38. 26.  22.  36.  27.  27.  32.  28.  31....
+    #               24.  27.  33.  32.  28.  19. 37.  31.  36.  36....
+    #               34.  38.  32.  38.  32....
+    #               26.  24.  26.  25.  29. 29.5 16.5 36.  44....
+    #               25.  27.  19....
+    #               25.  20....
+    #               28.];
+    #     j = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
+    #          0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ...
+    #          0 0 0 0...
+    #          1 1 1 1 1 1 1 1 1 1 1 1 1 1 1...
+    #          2 2 2 2 2 2 2 2 2...
+    #          3 3 3...
+    #          4 4...
+    #          5];
+    #     [~, ~, stats] = anova1(sample, j, "off");
+    #     [results, ~, ~, gnames] = multcompare(stats, ...
+    #     "CriticalValueType", "dunnett", ...
+    #     "Approximate", false);
+    #     tbl = array2table(results, "VariableNames", ...
+    #     ["Group", "Control Group", "Lower Limit", ...
+    #     "Difference", "Upper Limit", "P-value"]);
+    #     tbl.("Group") = gnames(tbl.("Group"));
+    #     tbl.("Control Group") = gnames(tbl.("Control Group"))
+
+    # Matlab doesn't report the statistic, so the statistics were
+    # computed using R multcomp `glht`, e.g.:
+    #     library(multcomp)
+    #     options(digits=16)
+    #     control < - c(18.0, 15.0, 18.0, 16.0, 17.0, 15.0, 14.0, 14.0, 14.0,
+    #                   15.0, 15.0, 14.0, 15.0, 14.0, 22.0, 18.0, 21.0, 21.0,
+    #                   10.0, 10.0, 11.0, 9.0, 25.0, 26.0, 17.5, 16.0, 15.5,
+    #                   14.5, 22.0, 22.0, 24.0, 22.5, 29.0, 24.5, 20.0, 18.0,
+    #                   18.5, 17.5, 26.5, 13.0, 16.5, 13.0, 13.0, 13.0, 28.0,
+    #                   27.0, 34.0, 31.0, 29.0, 27.0, 24.0, 23.0, 38.0, 36.0,
+    #                   25.0, 38.0, 26.0, 22.0, 36.0, 27.0, 27.0, 32.0, 28.0,
+    #                   31.0)
+    #     t < - c(24.0, 27.0, 33.0, 32.0, 28.0, 19.0, 37.0, 31.0, 36.0, 36.0,
+    #             34.0, 38.0, 32.0, 38.0, 32.0)
+    #     w < - c(26.0, 24.0, 26.0, 25.0, 29.0, 29.5, 16.5, 36.0, 44.0)
+    #     x < - c(25.0, 27.0, 19.0)
+    #     y < - c(25.0, 20.0)
+    #     z < - c(28.0)
+    #
+    #     groups = factor(rep(c("control", "t", "w", "x", "y", "z"),
+    #                         times=c(length(control), length(t), length(w),
+    #                                 length(x), length(y), length(z))))
+    #     df < - data.frame(response=c(control, t, w, x, y, z),
+    #                       group=groups)
+    #     model < - aov(response
+    #     ~group, data = df)
+    #     test < - glht(model=model,
+    #                   linfct=mcp(group="Dunnett"),
+    #                   alternative="g")
+    #     summary(test)
+    #     confint(test)
+    # p-values agreed with those produced by Matlab to at least atol=1e-3
+
+    # From Matlab's documentation on multcompare
+    samples_1 = [
+        [
+            24.0, 27.0, 33.0, 32.0, 28.0, 19.0, 37.0, 31.0, 36.0, 36.0,
+            34.0, 38.0, 32.0, 38.0, 32.0
+        ],
+        [26.0, 24.0, 26.0, 25.0, 29.0, 29.5, 16.5, 36.0, 44.0],
+        [25.0, 27.0, 19.0],
+        [25.0, 20.0],
+        [28.0]
+    ]
+    control_1 = [
+        18.0, 15.0, 18.0, 16.0, 17.0, 15.0, 14.0, 14.0, 14.0, 15.0, 15.0,
+        14.0, 15.0, 14.0, 22.0, 18.0, 21.0, 21.0, 10.0, 10.0, 11.0, 9.0,
+        25.0, 26.0, 17.5, 16.0, 15.5, 14.5, 22.0, 22.0, 24.0, 22.5, 29.0,
+        24.5, 20.0, 18.0, 18.5, 17.5, 26.5, 13.0, 16.5, 13.0, 13.0, 13.0,
+        28.0, 27.0, 34.0, 31.0, 29.0, 27.0, 24.0, 23.0, 38.0, 36.0, 25.0,
+        38.0, 26.0, 22.0, 36.0, 27.0, 27.0, 32.0, 28.0, 31.0
+    ]
+    pvalue_1 = [4.727e-06, 0.022346, 0.97912, 0.99953, 0.86579]  # Matlab
+    # Statistic, alternative p-values, and CIs computed with R multcomp `glht`
+    p_1_twosided = [1e-4, 0.02237, 0.97913, 0.99953, 0.86583]
+    p_1_greater = [1e-4, 0.011217, 0.768500, 0.896991, 0.577211]
+    p_1_less = [1, 1, 0.99660, 0.98398, .99953]
+    statistic_1 = [5.27356, 2.91270, 0.60831, 0.27002, 0.96637]
+    ci_1_twosided = [[5.3633917835622, 0.7296142201217, -8.3879817106607,
+                      -11.9090753452911, -11.7655021543469],
+                     [15.9709832164378, 13.8936496687672, 13.4556900439941,
+                      14.6434503452911, 25.4998771543469]]
+    ci_1_greater = [5.9036402398526, 1.4000632918725, -7.2754756323636,
+                    -10.5567456382391, -9.8675629499576]
+    ci_1_less = [15.4306165948619, 13.2230539537359, 12.3429406339544,
+                 13.2908248513211, 23.6015228251660]
+    pvalues_1 = dict(twosided=p_1_twosided, less=p_1_less, greater=p_1_greater)
+    cis_1 = dict(twosided=ci_1_twosided, less=ci_1_less, greater=ci_1_greater)
+    case_1 = dict(samples=samples_1, control=control_1, statistic=statistic_1,
+                  pvalues=pvalues_1, cis=cis_1)
+
+    # From Dunnett1955 comparing with R's DescTools: DunnettTest
+    samples_2 = [[9.76, 8.80, 7.68, 9.36], [12.80, 9.68, 12.16, 9.20, 10.55]]
+    control_2 = [7.40, 8.50, 7.20, 8.24, 9.84, 8.32]
+    pvalue_2 = [0.6201, 0.0058]
+    # Statistic, alternative p-values, and CIs computed with R multcomp `glht`
+    p_2_twosided = [0.6201020, 0.0058254]
+    p_2_greater = [0.3249776, 0.0029139]
+    p_2_less = [0.91676, 0.99984]
+    statistic_2 = [0.85703, 3.69375]
+    ci_2_twosided = [[-1.2564116462124, 0.8396273539789],
+                     [2.5564116462124, 4.4163726460211]]
+    ci_2_greater = [-0.9588591188156, 1.1187563667543]
+    ci_2_less = [2.2588591188156, 4.1372436332457]
+    pvalues_2 = dict(twosided=p_2_twosided, less=p_2_less, greater=p_2_greater)
+    cis_2 = dict(twosided=ci_2_twosided, less=ci_2_less, greater=ci_2_greater)
+    case_2 = dict(samples=samples_2, control=control_2, statistic=statistic_2,
+                  pvalues=pvalues_2, cis=cis_2)
+
+    samples_3 = [[55, 64, 64], [55, 49, 52], [50, 44, 41]]
+    control_3 = [55, 47, 48]
+    pvalue_3 = [0.0364, 0.8966, 0.4091]
+    # Statistic, alternative p-values, and CIs computed with R multcomp `glht`
+    p_3_twosided = [0.036407, 0.896539, 0.409295]
+    p_3_greater = [0.018277, 0.521109, 0.981892]
+    p_3_less = [0.99944, 0.90054, 0.20974]
+    statistic_3 = [3.09073, 0.56195, -1.40488]
+    ci_3_twosided = [[0.7529028025053, -8.2470971974947, -15.2470971974947],
+                     [21.2470971974947, 12.2470971974947, 5.2470971974947]]
+    ci_3_greater = [2.4023682323149, -6.5976317676851, -13.5976317676851]
+    ci_3_less = [19.5984402363662, 10.5984402363662, 3.5984402363662]
+    pvalues_3 = dict(twosided=p_3_twosided, less=p_3_less, greater=p_3_greater)
+    cis_3 = dict(twosided=ci_3_twosided, less=ci_3_less, greater=ci_3_greater)
+    case_3 = dict(samples=samples_3, control=control_3, statistic=statistic_3,
+                  pvalues=pvalues_3, cis=cis_3)
+
+    # From Thomson and Short,
+    # Mucociliary function in health, chronic obstructive airway disease,
+    # and asbestosis, Journal of Applied Physiology, 1969. Table 1
+    # Comparing with R's DescTools: DunnettTest
+    samples_4 = [[3.8, 2.7, 4.0, 2.4], [2.8, 3.4, 3.7, 2.2, 2.0]]
+    control_4 = [2.9, 3.0, 2.5, 2.6, 3.2]
+    pvalue_4 = [0.5832, 0.9982]
+    # Statistic, alternative p-values, and CIs computed with R multcomp `glht`
+    p_4_twosided = [0.58317, 0.99819]
+    p_4_greater = [0.30225, 0.69115]
+    p_4_less = [0.91929, 0.65212]
+    statistic_4 = [0.90875, -0.05007]
+    ci_4_twosided = [[-0.6898153448579, -1.0333456251632],
+                     [1.4598153448579, 0.9933456251632]]
+    ci_4_greater = [-0.5186459268412, -0.8719655502147 ]
+    ci_4_less = [1.2886459268412, 0.8319655502147]
+    pvalues_4 = dict(twosided=p_4_twosided, less=p_4_less, greater=p_4_greater)
+    cis_4 = dict(twosided=ci_4_twosided, less=ci_4_less, greater=ci_4_greater)
+    case_4 = dict(samples=samples_4, control=control_4, statistic=statistic_4,
+                  pvalues=pvalues_4, cis=cis_4)
+
+    @pytest.mark.parametrize(
+        'rho, n_groups, df, statistic, pvalue, alternative',
+        [
+            # From Dunnett1955
+            # Tables 1a and 1b pages 1117-1118
+            (0.5, 1, 10, 1.81, 0.05, "greater"),  # different than two-sided
+            (0.5, 3, 10, 2.34, 0.05, "greater"),
+            (0.5, 2, 30, 1.99, 0.05, "greater"),
+            (0.5, 5, 30, 2.33, 0.05, "greater"),
+            (0.5, 4, 12, 3.32, 0.01, "greater"),
+            (0.5, 7, 12, 3.56, 0.01, "greater"),
+            (0.5, 2, 60, 2.64, 0.01, "greater"),
+            (0.5, 4, 60, 2.87, 0.01, "greater"),
+            (0.5, 4, 60, [2.87, 2.21], [0.01, 0.05], "greater"),
+            # Tables 2a and 2b pages 1119-1120
+            (0.5, 1, 10, 2.23, 0.05, "two-sided"),  # two-sided
+            (0.5, 3, 10, 2.81, 0.05, "two-sided"),
+            (0.5, 2, 30, 2.32, 0.05, "two-sided"),
+            (0.5, 3, 20, 2.57, 0.05, "two-sided"),
+            (0.5, 4, 12, 3.76, 0.01, "two-sided"),
+            (0.5, 7, 12, 4.08, 0.01, "two-sided"),
+            (0.5, 2, 60, 2.90, 0.01, "two-sided"),
+            (0.5, 4, 60, 3.14, 0.01, "two-sided"),
+            (0.5, 4, 60, [3.14, 2.55], [0.01, 0.05], "two-sided"),
+        ],
+    )
+    def test_critical_values(
+        self, rho, n_groups, df, statistic, pvalue, alternative
+    ):
+        rng = np.random.default_rng(165250594791731684851746311027739134893)
+        rho = np.full((n_groups, n_groups), rho)
+        np.fill_diagonal(rho, 1)
+
+        statistic = np.array(statistic)
+        res = _pvalue_dunnett(
+            rho=rho, df=df, statistic=statistic,
+            alternative=alternative,
+            rng=rng
+        )
+        assert_allclose(res, pvalue, atol=5e-3)
+
+    @pytest.mark.parametrize(
+        'samples, control, pvalue, statistic',
+        [
+            (samples_1, control_1, pvalue_1, statistic_1),
+            (samples_2, control_2, pvalue_2, statistic_2),
+            (samples_3, control_3, pvalue_3, statistic_3),
+            (samples_4, control_4, pvalue_4, statistic_4),
+        ]
+    )
+    def test_basic(self, samples, control, pvalue, statistic):
+        rng = np.random.default_rng(11681140010308601919115036826969764808)
+
+        res = stats.dunnett(*samples, control=control, rng=rng)
+
+        assert isinstance(res, DunnettResult)
+        assert_allclose(res.statistic, statistic, rtol=5e-5)
+        assert_allclose(res.pvalue, pvalue, rtol=1e-2, atol=1e-4)
+
+    @pytest.mark.parametrize(
+        'alternative',
+        ['two-sided', 'less', 'greater']
+    )
+    def test_ttest_ind(self, alternative):
+        # check that `dunnett` agrees with `ttest_ind`
+        # when there are only two groups
+        rng = np.random.default_rng(114184017807316971636137493526995620351)
+
+        for _ in range(10):
+            sample = rng.integers(-100, 100, size=(10,))
+            control = rng.integers(-100, 100, size=(10,))
+
+            # preserve use of old random_state during SPEC 7 transition
+            res = stats.dunnett(
+                sample, control=control,
+                alternative=alternative, random_state=rng
+            )
+            ref = stats.ttest_ind(
+                sample, control,
+                alternative=alternative
+            )
+
+            assert_allclose(res.statistic, ref.statistic, rtol=1e-3, atol=1e-5)
+            assert_allclose(res.pvalue, ref.pvalue, rtol=1e-3, atol=1e-5)
+
+    @pytest.mark.parametrize(
+        'alternative, pvalue',
+        [
+            ('less', [0, 1]),
+            ('greater', [1, 0]),
+            ('two-sided', [0, 0]),
+        ]
+    )
+    def test_alternatives(self, alternative, pvalue):
+        rng = np.random.default_rng(114184017807316971636137493526995620351)
+
+        # width of 20 and min diff between samples/control is 60
+        # and maximal diff would be 100
+        sample_less = rng.integers(0, 20, size=(10,))
+        control = rng.integers(80, 100, size=(10,))
+        sample_greater = rng.integers(160, 180, size=(10,))
+
+        res = stats.dunnett(
+            sample_less, sample_greater, control=control,
+            alternative=alternative, rng=rng
+        )
+        assert_allclose(res.pvalue, pvalue, atol=1e-7)
+
+        ci = res.confidence_interval()
+        # two-sided is comparable for high/low
+        if alternative == 'less':
+            assert np.isneginf(ci.low).all()
+            assert -100 < ci.high[0] < -60
+            assert 60 < ci.high[1] < 100
+        elif alternative == 'greater':
+            assert -100 < ci.low[0] < -60
+            assert 60 < ci.low[1] < 100
+            assert np.isposinf(ci.high).all()
+        elif alternative == 'two-sided':
+            assert -100 < ci.low[0] < -60
+            assert 60 < ci.low[1] < 100
+            assert -100 < ci.high[0] < -60
+            assert 60 < ci.high[1] < 100
+
+    @pytest.mark.parametrize("case", [case_1, case_2, case_3, case_4])
+    @pytest.mark.parametrize("alternative", ['less', 'greater', 'two-sided'])
+    def test_against_R_multicomp_glht(self, case, alternative):
+        rng = np.random.default_rng(189117774084579816190295271136455278291)
+        samples = case['samples']
+        control = case['control']
+        alternatives = {'less': 'less', 'greater': 'greater',
+                        'two-sided': 'twosided'}
+        p_ref = case['pvalues'][alternative.replace('-', '')]
+
+        res = stats.dunnett(*samples, control=control, alternative=alternative,
+                            rng=rng)
+        # atol can't be tighter because R reports some pvalues as "< 1e-4"
+        assert_allclose(res.pvalue, p_ref, rtol=5e-3, atol=1e-4)
+
+        ci_ref = case['cis'][alternatives[alternative]]
+        if alternative == "greater":
+            ci_ref = [ci_ref, np.inf]
+        elif alternative == "less":
+            ci_ref = [-np.inf, ci_ref]
+        assert res._ci is None
+        assert res._ci_cl is None
+        ci = res.confidence_interval(confidence_level=0.95)
+        assert_allclose(ci.low, ci_ref[0], rtol=5e-3, atol=1e-5)
+        assert_allclose(ci.high, ci_ref[1], rtol=5e-3, atol=1e-5)
+
+        # re-run to use the cached value "is" to check id as same object
+        assert res._ci is ci
+        assert res._ci_cl == 0.95
+        ci_ = res.confidence_interval(confidence_level=0.95)
+        assert ci_ is ci
+
+    @pytest.mark.parametrize('alternative', ["two-sided", "less", "greater"])
+    def test_str(self, alternative):
+        rng = np.random.default_rng(189117774084579816190295271136455278291)
+
+        res = stats.dunnett(
+            *self.samples_3, control=self.control_3, alternative=alternative,
+            rng=rng
+        )
+
+        # check some str output
+        res_str = str(res)
+        assert '(Sample 2 - Control)' in res_str
+        assert '95.0%' in res_str
+
+        if alternative == 'less':
+            assert '-inf' in res_str
+            assert '19.' in res_str
+        elif alternative == 'greater':
+            assert 'inf' in res_str
+            assert '-13.' in res_str
+        else:
+            assert 'inf' not in res_str
+            assert '21.' in res_str
+
+    def test_warnings(self):
+        rng = np.random.default_rng(189117774084579816190295271136455278291)
+
+        res = stats.dunnett(
+            *self.samples_3, control=self.control_3, rng=rng
+        )
+        msg = r"Computation of the confidence interval did not converge"
+        with pytest.warns(UserWarning, match=msg):
+            res._allowance(tol=1e-5)
+
+    def test_raises(self):
+        samples, control = self.samples_3, self.control_3
+
+        # alternative
+        with pytest.raises(ValueError, match="alternative must be"):
+            stats.dunnett(*samples, control=control, alternative='bob')
+
+        # 2D for a sample
+        samples_ = copy.deepcopy(samples)
+        samples_[0] = [samples_[0]]
+        with pytest.raises(ValueError, match="must be 1D arrays"):
+            stats.dunnett(*samples_, control=control)
+
+        # 2D for control
+        control_ = copy.deepcopy(control)
+        control_ = [control_]
+        with pytest.raises(ValueError, match="must be 1D arrays"):
+            stats.dunnett(*samples, control=control_)
+
+        # No obs in a sample
+        samples_ = copy.deepcopy(samples)
+        samples_[1] = []
+        with pytest.raises(ValueError, match="at least 1 observation"):
+            stats.dunnett(*samples_, control=control)
+
+        # No obs in control
+        control_ = []
+        with pytest.raises(ValueError, match="at least 1 observation"):
+            stats.dunnett(*samples, control=control_)
+
+        res = stats.dunnett(*samples, control=control)
+        with pytest.raises(ValueError, match="Confidence level must"):
+            res.confidence_interval(confidence_level=3)
+
+    @pytest.mark.filterwarnings("ignore:Computation of the confidence")
+    @pytest.mark.parametrize('n_samples', [1, 2, 3])
+    def test_shapes(self, n_samples):
+        rng = np.random.default_rng(689448934110805334)
+        samples = rng.normal(size=(n_samples, 10))
+        control = rng.normal(size=10)
+        res = stats.dunnett(*samples, control=control, rng=rng)
+        assert res.statistic.shape == (n_samples,)
+        assert res.pvalue.shape == (n_samples,)
+        ci = res.confidence_interval()
+        assert ci.low.shape == (n_samples,)
+        assert ci.high.shape == (n_samples,)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multivariate.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multivariate.py
new file mode 100644
index 0000000000000000000000000000000000000000..d53a7925b4d6794f7f538647f0288810c163a8a0
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_multivariate.py
@@ -0,0 +1,4030 @@
+"""
+Test functions for multivariate normal distributions.
+
+"""
+import pickle
+
+from numpy.testing import (assert_allclose, assert_almost_equal,
+                           assert_array_almost_equal, assert_equal,
+                           assert_array_less, assert_)
+import pytest
+from pytest import raises as assert_raises
+
+from .test_continuous_basic import check_distribution_rvs
+
+import numpy as np
+
+import scipy.linalg
+
+from scipy.stats._multivariate import (_PSD,
+                                       _lnB,
+                                       multivariate_normal_frozen)
+from scipy.stats import (multivariate_normal, multivariate_hypergeom,
+                         matrix_normal, special_ortho_group, ortho_group,
+                         random_correlation, unitary_group, dirichlet,
+                         beta, wishart, multinomial, invwishart, chi2,
+                         invgamma, norm, uniform, ks_2samp, kstest, binom,
+                         hypergeom, multivariate_t, cauchy, normaltest,
+                         random_table, uniform_direction, vonmises_fisher,
+                         dirichlet_multinomial, vonmises)
+
+from scipy.stats import _covariance, Covariance
+from scipy import stats
+
+from scipy.integrate import tanhsinh
+from scipy.integrate import romb, qmc_quad, dblquad, tplquad
+from scipy.special import multigammaln
+
+from .common_tests import check_random_state_property
+from .data._mvt import _qsimvtv
+
+from unittest.mock import patch
+
+
+def assert_close(res, ref, *args, **kwargs):
+    res, ref = np.asarray(res), np.asarray(ref)
+    assert_allclose(res, ref, *args, **kwargs)
+    assert_equal(res.shape, ref.shape)
+
+
+class TestCovariance:
+
+    def test_input_validation(self):
+
+        message = "The input `precision` must be a square, two-dimensional..."
+        with pytest.raises(ValueError, match=message):
+            _covariance.CovViaPrecision(np.ones(2))
+
+        message = "`precision.shape` must equal `covariance.shape`."
+        with pytest.raises(ValueError, match=message):
+            _covariance.CovViaPrecision(np.eye(3), covariance=np.eye(2))
+
+        message = "The input `diagonal` must be a one-dimensional array..."
+        with pytest.raises(ValueError, match=message):
+            _covariance.CovViaDiagonal("alpaca")
+
+        message = "The input `cholesky` must be a square, two-dimensional..."
+        with pytest.raises(ValueError, match=message):
+            _covariance.CovViaCholesky(np.ones(2))
+
+        message = "The input `eigenvalues` must be a one-dimensional..."
+        with pytest.raises(ValueError, match=message):
+            _covariance.CovViaEigendecomposition(("alpaca", np.eye(2)))
+
+        message = "The input `eigenvectors` must be a square..."
+        with pytest.raises(ValueError, match=message):
+            _covariance.CovViaEigendecomposition((np.ones(2), "alpaca"))
+
+        message = "The shapes of `eigenvalues` and `eigenvectors` must be..."
+        with pytest.raises(ValueError, match=message):
+            _covariance.CovViaEigendecomposition(([1, 2, 3], np.eye(2)))
+
+    _covariance_preprocessing = {"Diagonal": np.diag,
+                                 "Precision": np.linalg.inv,
+                                 "Cholesky": np.linalg.cholesky,
+                                 "Eigendecomposition": np.linalg.eigh,
+                                 "PSD": lambda x:
+                                     _PSD(x, allow_singular=True)}
+    _all_covariance_types = np.array(list(_covariance_preprocessing))
+    _matrices = {"diagonal full rank": np.diag([1, 2, 3]),
+                 "general full rank": [[5, 1, 3], [1, 6, 4], [3, 4, 7]],
+                 "diagonal singular": np.diag([1, 0, 3]),
+                 "general singular": [[5, -1, 0], [-1, 5, 0], [0, 0, 0]]}
+    _cov_types = {"diagonal full rank": _all_covariance_types,
+                  "general full rank": _all_covariance_types[1:],
+                  "diagonal singular": _all_covariance_types[[0, -2, -1]],
+                  "general singular": _all_covariance_types[-2:]}
+
+    @pytest.mark.parametrize("cov_type_name", _all_covariance_types[:-1])
+    def test_factories(self, cov_type_name):
+        A = np.diag([1, 2, 3])
+        x = [-4, 2, 5]
+
+        cov_type = getattr(_covariance, f"CovVia{cov_type_name}")
+        preprocessing = self._covariance_preprocessing[cov_type_name]
+        factory = getattr(Covariance, f"from_{cov_type_name.lower()}")
+
+        res = factory(preprocessing(A))
+        ref = cov_type(preprocessing(A))
+        assert type(res) is type(ref)
+        assert_allclose(res.whiten(x), ref.whiten(x))
+
+    @pytest.mark.parametrize("matrix_type", list(_matrices))
+    @pytest.mark.parametrize("cov_type_name", _all_covariance_types)
+    def test_covariance(self, matrix_type, cov_type_name):
+        message = (f"CovVia{cov_type_name} does not support {matrix_type} "
+                   "matrices")
+        if cov_type_name not in self._cov_types[matrix_type]:
+            pytest.skip(message)
+
+        A = self._matrices[matrix_type]
+        cov_type = getattr(_covariance, f"CovVia{cov_type_name}")
+        preprocessing = self._covariance_preprocessing[cov_type_name]
+
+        psd = _PSD(A, allow_singular=True)
+
+        # test properties
+        cov_object = cov_type(preprocessing(A))
+        assert_close(cov_object.log_pdet, psd.log_pdet)
+        assert_equal(cov_object.rank, psd.rank)
+        assert_equal(cov_object.shape, np.asarray(A).shape)
+        assert_close(cov_object.covariance, np.asarray(A))
+
+        # test whitening/coloring 1D x
+        rng = np.random.default_rng(5292808890472453840)
+        x = rng.random(size=3)
+        res = cov_object.whiten(x)
+        ref = x @ psd.U
+        # res != ref in general; but res @ res == ref @ ref
+        assert_close(res @ res, ref @ ref)
+        if hasattr(cov_object, "_colorize") and "singular" not in matrix_type:
+            # CovViaPSD does not have _colorize
+            assert_close(cov_object.colorize(res), x)
+
+        # test whitening/coloring 3D x
+        x = rng.random(size=(2, 4, 3))
+        res = cov_object.whiten(x)
+        ref = x @ psd.U
+        assert_close((res**2).sum(axis=-1), (ref**2).sum(axis=-1))
+        if hasattr(cov_object, "_colorize") and "singular" not in matrix_type:
+            assert_close(cov_object.colorize(res), x)
+
+        # gh-19197 reported that multivariate normal `rvs` produced incorrect
+        # results when a singular Covariance object was produce using
+        # `from_eigenvalues`. This was due to an issue in `colorize` with
+        # singular covariance matrices. Check this edge case, which is skipped
+        # in the previous tests.
+        if hasattr(cov_object, "_colorize"):
+            res = cov_object.colorize(np.eye(len(A)))
+            assert_close(res.T @ res, A)
+
+    @pytest.mark.parametrize("size", [None, tuple(), 1, (2, 4, 3)])
+    @pytest.mark.parametrize("matrix_type", list(_matrices))
+    @pytest.mark.parametrize("cov_type_name", _all_covariance_types)
+    def test_mvn_with_covariance(self, size, matrix_type, cov_type_name):
+        message = (f"CovVia{cov_type_name} does not support {matrix_type} "
+                   "matrices")
+        if cov_type_name not in self._cov_types[matrix_type]:
+            pytest.skip(message)
+
+        A = self._matrices[matrix_type]
+        cov_type = getattr(_covariance, f"CovVia{cov_type_name}")
+        preprocessing = self._covariance_preprocessing[cov_type_name]
+
+        mean = [0.1, 0.2, 0.3]
+        cov_object = cov_type(preprocessing(A))
+        mvn = multivariate_normal
+        dist0 = multivariate_normal(mean, A, allow_singular=True)
+        dist1 = multivariate_normal(mean, cov_object, allow_singular=True)
+
+        rng = np.random.default_rng(5292808890472453840)
+        x = rng.multivariate_normal(mean, A, size=size)
+        rng = np.random.default_rng(5292808890472453840)
+        x1 = mvn.rvs(mean, cov_object, size=size, random_state=rng)
+        rng = np.random.default_rng(5292808890472453840)
+        x2 = mvn(mean, cov_object, seed=rng).rvs(size=size)
+        if isinstance(cov_object, _covariance.CovViaPSD):
+            assert_close(x1, np.squeeze(x))  # for backward compatibility
+            assert_close(x2, np.squeeze(x))
+        else:
+            assert_equal(x1.shape, x.shape)
+            assert_equal(x2.shape, x.shape)
+            assert_close(x2, x1)
+
+        assert_close(mvn.pdf(x, mean, cov_object), dist0.pdf(x))
+        assert_close(dist1.pdf(x), dist0.pdf(x))
+        assert_close(mvn.logpdf(x, mean, cov_object), dist0.logpdf(x))
+        assert_close(dist1.logpdf(x), dist0.logpdf(x))
+        assert_close(mvn.entropy(mean, cov_object), dist0.entropy())
+        assert_close(dist1.entropy(), dist0.entropy())
+
+    @pytest.mark.parametrize("size", [tuple(), (2, 4, 3)])
+    @pytest.mark.parametrize("cov_type_name", _all_covariance_types)
+    def test_mvn_with_covariance_cdf(self, size, cov_type_name):
+        # This is split from the test above because it's slow to be running
+        # with all matrix types, and there's no need because _mvn.mvnun
+        # does the calculation. All Covariance needs to do is pass is
+        # provide the `covariance` attribute.
+        matrix_type = "diagonal full rank"
+        A = self._matrices[matrix_type]
+        cov_type = getattr(_covariance, f"CovVia{cov_type_name}")
+        preprocessing = self._covariance_preprocessing[cov_type_name]
+
+        mean = [0.1, 0.2, 0.3]
+        cov_object = cov_type(preprocessing(A))
+        mvn = multivariate_normal
+        dist0 = multivariate_normal(mean, A, allow_singular=True)
+        dist1 = multivariate_normal(mean, cov_object, allow_singular=True)
+
+        rng = np.random.default_rng(5292808890472453840)
+        x = rng.multivariate_normal(mean, A, size=size)
+
+        assert_close(mvn.cdf(x, mean, cov_object), dist0.cdf(x))
+        assert_close(dist1.cdf(x), dist0.cdf(x))
+        assert_close(mvn.logcdf(x, mean, cov_object), dist0.logcdf(x))
+        assert_close(dist1.logcdf(x), dist0.logcdf(x))
+
+    def test_covariance_instantiation(self):
+        message = "The `Covariance` class cannot be instantiated directly."
+        with pytest.raises(NotImplementedError, match=message):
+            Covariance()
+
+    @pytest.mark.filterwarnings("ignore::RuntimeWarning")  # matrix not PSD
+    def test_gh9942(self):
+        # Originally there was a mistake in the `multivariate_normal_frozen`
+        # `rvs` method that caused all covariance objects to be processed as
+        # a `_CovViaPSD`. Ensure that this is resolved.
+        A = np.diag([1, 2, -1e-8])
+        n = A.shape[0]
+        mean = np.zeros(n)
+
+        # Error if the matrix is processed as a `_CovViaPSD`
+        with pytest.raises(ValueError, match="The input matrix must be..."):
+            multivariate_normal(mean, A).rvs()
+
+        # No error if it is provided as a `CovViaEigendecomposition`
+        seed = 3562050283508273023
+        rng1 = np.random.default_rng(seed)
+        rng2 = np.random.default_rng(seed)
+        cov = Covariance.from_eigendecomposition(np.linalg.eigh(A))
+        rv = multivariate_normal(mean, cov)
+        res = rv.rvs(random_state=rng1)
+        ref = multivariate_normal.rvs(mean, cov, random_state=rng2)
+        assert_equal(res, ref)
+
+    def test_gh19197(self):
+        # gh-19197 reported that multivariate normal `rvs` produced incorrect
+        # results when a singular Covariance object was produce using
+        # `from_eigenvalues`. Check that this specific issue is resolved;
+        # a more general test is included in `test_covariance`.
+        mean = np.ones(2)
+        cov = Covariance.from_eigendecomposition((np.zeros(2), np.eye(2)))
+        dist = scipy.stats.multivariate_normal(mean=mean, cov=cov)
+        rvs = dist.rvs(size=None)
+        assert_equal(rvs, mean)
+
+        cov = scipy.stats.Covariance.from_eigendecomposition(
+            (np.array([1., 0.]), np.array([[1., 0.], [0., 400.]])))
+        dist = scipy.stats.multivariate_normal(mean=mean, cov=cov)
+        rvs = dist.rvs(size=None)
+        assert rvs[0] != mean[0]
+        assert rvs[1] == mean[1]
+
+
+def _random_covariance(dim, evals, rng, singular=False):
+    # Generates random covariance matrix with dimensionality `dim` and
+    # eigenvalues `evals` using provided Generator `rng`. Randomly sets
+    # some evals to zero if `singular` is True.
+    A = rng.random((dim, dim))
+    A = A @ A.T
+    _, v = np.linalg.eigh(A)
+    if singular:
+        zero_eigs = rng.normal(size=dim) > 0
+        evals[zero_eigs] = 0
+    cov = v @ np.diag(evals) @ v.T
+    return cov
+
+
+def _sample_orthonormal_matrix(n):
+    M = np.random.randn(n, n)
+    u, s, v = scipy.linalg.svd(M)
+    return u
+
+
+class TestMultivariateNormal:
+    def test_input_shape(self):
+        mu = np.arange(3)
+        cov = np.identity(2)
+        assert_raises(ValueError, multivariate_normal.pdf, (0, 1), mu, cov)
+        assert_raises(ValueError, multivariate_normal.pdf, (0, 1, 2), mu, cov)
+        assert_raises(ValueError, multivariate_normal.cdf, (0, 1), mu, cov)
+        assert_raises(ValueError, multivariate_normal.cdf, (0, 1, 2), mu, cov)
+
+    def test_scalar_values(self):
+        np.random.seed(1234)
+
+        # When evaluated on scalar data, the pdf should return a scalar
+        x, mean, cov = 1.5, 1.7, 2.5
+        pdf = multivariate_normal.pdf(x, mean, cov)
+        assert_equal(pdf.ndim, 0)
+
+        # When evaluated on a single vector, the pdf should return a scalar
+        x = np.random.randn(5)
+        mean = np.random.randn(5)
+        cov = np.abs(np.random.randn(5))  # Diagonal values for cov. matrix
+        pdf = multivariate_normal.pdf(x, mean, cov)
+        assert_equal(pdf.ndim, 0)
+
+        # When evaluated on scalar data, the cdf should return a scalar
+        x, mean, cov = 1.5, 1.7, 2.5
+        cdf = multivariate_normal.cdf(x, mean, cov)
+        assert_equal(cdf.ndim, 0)
+
+        # When evaluated on a single vector, the cdf should return a scalar
+        x = np.random.randn(5)
+        mean = np.random.randn(5)
+        cov = np.abs(np.random.randn(5))  # Diagonal values for cov. matrix
+        cdf = multivariate_normal.cdf(x, mean, cov)
+        assert_equal(cdf.ndim, 0)
+
+    def test_logpdf(self):
+        # Check that the log of the pdf is in fact the logpdf
+        np.random.seed(1234)
+        x = np.random.randn(5)
+        mean = np.random.randn(5)
+        cov = np.abs(np.random.randn(5))
+        d1 = multivariate_normal.logpdf(x, mean, cov)
+        d2 = multivariate_normal.pdf(x, mean, cov)
+        assert_allclose(d1, np.log(d2))
+
+    def test_logpdf_default_values(self):
+        # Check that the log of the pdf is in fact the logpdf
+        # with default parameters Mean=None and cov = 1
+        np.random.seed(1234)
+        x = np.random.randn(5)
+        d1 = multivariate_normal.logpdf(x)
+        d2 = multivariate_normal.pdf(x)
+        # check whether default values are being used
+        d3 = multivariate_normal.logpdf(x, None, 1)
+        d4 = multivariate_normal.pdf(x, None, 1)
+        assert_allclose(d1, np.log(d2))
+        assert_allclose(d3, np.log(d4))
+
+    def test_logcdf(self):
+        # Check that the log of the cdf is in fact the logcdf
+        np.random.seed(1234)
+        x = np.random.randn(5)
+        mean = np.random.randn(5)
+        cov = np.abs(np.random.randn(5))
+        d1 = multivariate_normal.logcdf(x, mean, cov)
+        d2 = multivariate_normal.cdf(x, mean, cov)
+        assert_allclose(d1, np.log(d2))
+
+    def test_logcdf_default_values(self):
+        # Check that the log of the cdf is in fact the logcdf
+        # with default parameters Mean=None and cov = 1
+        np.random.seed(1234)
+        x = np.random.randn(5)
+        d1 = multivariate_normal.logcdf(x)
+        d2 = multivariate_normal.cdf(x)
+        # check whether default values are being used
+        d3 = multivariate_normal.logcdf(x, None, 1)
+        d4 = multivariate_normal.cdf(x, None, 1)
+        assert_allclose(d1, np.log(d2))
+        assert_allclose(d3, np.log(d4))
+
+    def test_rank(self):
+        # Check that the rank is detected correctly.
+        np.random.seed(1234)
+        n = 4
+        mean = np.random.randn(n)
+        for expected_rank in range(1, n + 1):
+            s = np.random.randn(n, expected_rank)
+            cov = np.dot(s, s.T)
+            distn = multivariate_normal(mean, cov, allow_singular=True)
+            assert_equal(distn.cov_object.rank, expected_rank)
+
+    def test_degenerate_distributions(self):
+
+        for n in range(1, 5):
+            z = np.random.randn(n)
+            for k in range(1, n):
+                # Sample a small covariance matrix.
+                s = np.random.randn(k, k)
+                cov_kk = np.dot(s, s.T)
+
+                # Embed the small covariance matrix into a larger singular one.
+                cov_nn = np.zeros((n, n))
+                cov_nn[:k, :k] = cov_kk
+
+                # Embed part of the vector in the same way
+                x = np.zeros(n)
+                x[:k] = z[:k]
+
+                # Define a rotation of the larger low rank matrix.
+                u = _sample_orthonormal_matrix(n)
+                cov_rr = np.dot(u, np.dot(cov_nn, u.T))
+                y = np.dot(u, x)
+
+                # Check some identities.
+                distn_kk = multivariate_normal(np.zeros(k), cov_kk,
+                                               allow_singular=True)
+                distn_nn = multivariate_normal(np.zeros(n), cov_nn,
+                                               allow_singular=True)
+                distn_rr = multivariate_normal(np.zeros(n), cov_rr,
+                                               allow_singular=True)
+                assert_equal(distn_kk.cov_object.rank, k)
+                assert_equal(distn_nn.cov_object.rank, k)
+                assert_equal(distn_rr.cov_object.rank, k)
+                pdf_kk = distn_kk.pdf(x[:k])
+                pdf_nn = distn_nn.pdf(x)
+                pdf_rr = distn_rr.pdf(y)
+                assert_allclose(pdf_kk, pdf_nn)
+                assert_allclose(pdf_kk, pdf_rr)
+                logpdf_kk = distn_kk.logpdf(x[:k])
+                logpdf_nn = distn_nn.logpdf(x)
+                logpdf_rr = distn_rr.logpdf(y)
+                assert_allclose(logpdf_kk, logpdf_nn)
+                assert_allclose(logpdf_kk, logpdf_rr)
+
+                # Add an orthogonal component and find the density
+                y_orth = y + u[:, -1]
+                pdf_rr_orth = distn_rr.pdf(y_orth)
+                logpdf_rr_orth = distn_rr.logpdf(y_orth)
+
+                # Ensure that this has zero probability
+                assert_equal(pdf_rr_orth, 0.0)
+                assert_equal(logpdf_rr_orth, -np.inf)
+
+    def test_degenerate_array(self):
+        # Test that we can generate arrays of random variate from a degenerate
+        # multivariate normal, and that the pdf for these samples is non-zero
+        # (i.e. samples from the distribution lie on the subspace)
+        k = 10
+        for n in range(2, 6):
+            for r in range(1, n):
+                mn = np.zeros(n)
+                u = _sample_orthonormal_matrix(n)[:, :r]
+                vr = np.dot(u, u.T)
+                X = multivariate_normal.rvs(mean=mn, cov=vr, size=k)
+
+                pdf = multivariate_normal.pdf(X, mean=mn, cov=vr,
+                                              allow_singular=True)
+                assert_equal(pdf.size, k)
+                assert np.all(pdf > 0.0)
+
+                logpdf = multivariate_normal.logpdf(X, mean=mn, cov=vr,
+                                                    allow_singular=True)
+                assert_equal(logpdf.size, k)
+                assert np.all(logpdf > -np.inf)
+
+    def test_large_pseudo_determinant(self):
+        # Check that large pseudo-determinants are handled appropriately.
+
+        # Construct a singular diagonal covariance matrix
+        # whose pseudo determinant overflows double precision.
+        large_total_log = 1000.0
+        npos = 100
+        nzero = 2
+        large_entry = np.exp(large_total_log / npos)
+        n = npos + nzero
+        cov = np.zeros((n, n), dtype=float)
+        np.fill_diagonal(cov, large_entry)
+        cov[-nzero:, -nzero:] = 0
+
+        # Check some determinants.
+        assert_equal(scipy.linalg.det(cov), 0)
+        assert_equal(scipy.linalg.det(cov[:npos, :npos]), np.inf)
+        assert_allclose(np.linalg.slogdet(cov[:npos, :npos]),
+                        (1, large_total_log))
+
+        # Check the pseudo-determinant.
+        psd = _PSD(cov)
+        assert_allclose(psd.log_pdet, large_total_log)
+
+    def test_broadcasting(self):
+        np.random.seed(1234)
+        n = 4
+
+        # Construct a random covariance matrix.
+        data = np.random.randn(n, n)
+        cov = np.dot(data, data.T)
+        mean = np.random.randn(n)
+
+        # Construct an ndarray which can be interpreted as
+        # a 2x3 array whose elements are random data vectors.
+        X = np.random.randn(2, 3, n)
+
+        # Check that multiple data points can be evaluated at once.
+        desired_pdf = multivariate_normal.pdf(X, mean, cov)
+        desired_cdf = multivariate_normal.cdf(X, mean, cov)
+        for i in range(2):
+            for j in range(3):
+                actual = multivariate_normal.pdf(X[i, j], mean, cov)
+                assert_allclose(actual, desired_pdf[i,j])
+                # Repeat for cdf
+                actual = multivariate_normal.cdf(X[i, j], mean, cov)
+                assert_allclose(actual, desired_cdf[i,j], rtol=1e-3)
+
+    def test_normal_1D(self):
+        # The probability density function for a 1D normal variable should
+        # agree with the standard normal distribution in scipy.stats.distributions
+        x = np.linspace(0, 2, 10)
+        mean, cov = 1.2, 0.9
+        scale = cov**0.5
+        d1 = norm.pdf(x, mean, scale)
+        d2 = multivariate_normal.pdf(x, mean, cov)
+        assert_allclose(d1, d2)
+        # The same should hold for the cumulative distribution function
+        d1 = norm.cdf(x, mean, scale)
+        d2 = multivariate_normal.cdf(x, mean, cov)
+        assert_allclose(d1, d2)
+
+    def test_marginalization(self):
+        # Integrating out one of the variables of a 2D Gaussian should
+        # yield a 1D Gaussian
+        mean = np.array([2.5, 3.5])
+        cov = np.array([[.5, 0.2], [0.2, .6]])
+        n = 2 ** 8 + 1  # Number of samples
+        delta = 6 / (n - 1)  # Grid spacing
+
+        v = np.linspace(0, 6, n)
+        xv, yv = np.meshgrid(v, v)
+        pos = np.empty((n, n, 2))
+        pos[:, :, 0] = xv
+        pos[:, :, 1] = yv
+        pdf = multivariate_normal.pdf(pos, mean, cov)
+
+        # Marginalize over x and y axis
+        margin_x = romb(pdf, delta, axis=0)
+        margin_y = romb(pdf, delta, axis=1)
+
+        # Compare with standard normal distribution
+        gauss_x = norm.pdf(v, loc=mean[0], scale=cov[0, 0] ** 0.5)
+        gauss_y = norm.pdf(v, loc=mean[1], scale=cov[1, 1] ** 0.5)
+        assert_allclose(margin_x, gauss_x, rtol=1e-2, atol=1e-2)
+        assert_allclose(margin_y, gauss_y, rtol=1e-2, atol=1e-2)
+
+    def test_frozen(self):
+        # The frozen distribution should agree with the regular one
+        np.random.seed(1234)
+        x = np.random.randn(5)
+        mean = np.random.randn(5)
+        cov = np.abs(np.random.randn(5))
+        norm_frozen = multivariate_normal(mean, cov)
+        assert_allclose(norm_frozen.pdf(x), multivariate_normal.pdf(x, mean, cov))
+        assert_allclose(norm_frozen.logpdf(x),
+                        multivariate_normal.logpdf(x, mean, cov))
+        assert_allclose(norm_frozen.cdf(x), multivariate_normal.cdf(x, mean, cov))
+        assert_allclose(norm_frozen.logcdf(x),
+                        multivariate_normal.logcdf(x, mean, cov))
+
+    @pytest.mark.parametrize(
+        'covariance',
+        [
+            np.eye(2),
+            Covariance.from_diagonal([1, 1]),
+        ]
+    )
+    def test_frozen_multivariate_normal_exposes_attributes(self, covariance):
+        mean = np.ones((2,))
+        cov_should_be = np.eye(2)
+        norm_frozen = multivariate_normal(mean, covariance)
+        assert np.allclose(norm_frozen.mean, mean)
+        assert np.allclose(norm_frozen.cov, cov_should_be)
+
+    def test_pseudodet_pinv(self):
+        # Make sure that pseudo-inverse and pseudo-det agree on cutoff
+
+        # Assemble random covariance matrix with large and small eigenvalues
+        np.random.seed(1234)
+        n = 7
+        x = np.random.randn(n, n)
+        cov = np.dot(x, x.T)
+        s, u = scipy.linalg.eigh(cov)
+        s = np.full(n, 0.5)
+        s[0] = 1.0
+        s[-1] = 1e-7
+        cov = np.dot(u, np.dot(np.diag(s), u.T))
+
+        # Set cond so that the lowest eigenvalue is below the cutoff
+        cond = 1e-5
+        psd = _PSD(cov, cond=cond)
+        psd_pinv = _PSD(psd.pinv, cond=cond)
+
+        # Check that the log pseudo-determinant agrees with the sum
+        # of the logs of all but the smallest eigenvalue
+        assert_allclose(psd.log_pdet, np.sum(np.log(s[:-1])))
+        # Check that the pseudo-determinant of the pseudo-inverse
+        # agrees with 1 / pseudo-determinant
+        assert_allclose(-psd.log_pdet, psd_pinv.log_pdet)
+
+    def test_exception_nonsquare_cov(self):
+        cov = [[1, 2, 3], [4, 5, 6]]
+        assert_raises(ValueError, _PSD, cov)
+
+    def test_exception_nonfinite_cov(self):
+        cov_nan = [[1, 0], [0, np.nan]]
+        assert_raises(ValueError, _PSD, cov_nan)
+        cov_inf = [[1, 0], [0, np.inf]]
+        assert_raises(ValueError, _PSD, cov_inf)
+
+    def test_exception_non_psd_cov(self):
+        cov = [[1, 0], [0, -1]]
+        assert_raises(ValueError, _PSD, cov)
+
+    def test_exception_singular_cov(self):
+        np.random.seed(1234)
+        x = np.random.randn(5)
+        mean = np.random.randn(5)
+        cov = np.ones((5, 5))
+        e = np.linalg.LinAlgError
+        assert_raises(e, multivariate_normal, mean, cov)
+        assert_raises(e, multivariate_normal.pdf, x, mean, cov)
+        assert_raises(e, multivariate_normal.logpdf, x, mean, cov)
+        assert_raises(e, multivariate_normal.cdf, x, mean, cov)
+        assert_raises(e, multivariate_normal.logcdf, x, mean, cov)
+
+        # Message used to be "singular matrix", but this is more accurate.
+        # See gh-15508
+        cov = [[1., 0.], [1., 1.]]
+        msg = "When `allow_singular is False`, the input matrix"
+        with pytest.raises(np.linalg.LinAlgError, match=msg):
+            multivariate_normal(cov=cov)
+
+    def test_R_values(self):
+        # Compare the multivariate pdf with some values precomputed
+        # in R version 3.0.1 (2013-05-16) on Mac OS X 10.6.
+
+        # The values below were generated by the following R-script:
+        # > library(mnormt)
+        # > x <- seq(0, 2, length=5)
+        # > y <- 3*x - 2
+        # > z <- x + cos(y)
+        # > mu <- c(1, 3, 2)
+        # > Sigma <- matrix(c(1,2,0,2,5,0.5,0,0.5,3), 3, 3)
+        # > r_pdf <- dmnorm(cbind(x,y,z), mu, Sigma)
+        r_pdf = np.array([0.0002214706, 0.0013819953, 0.0049138692,
+                          0.0103803050, 0.0140250800])
+
+        x = np.linspace(0, 2, 5)
+        y = 3 * x - 2
+        z = x + np.cos(y)
+        r = np.array([x, y, z]).T
+
+        mean = np.array([1, 3, 2], 'd')
+        cov = np.array([[1, 2, 0], [2, 5, .5], [0, .5, 3]], 'd')
+
+        pdf = multivariate_normal.pdf(r, mean, cov)
+        assert_allclose(pdf, r_pdf, atol=1e-10)
+
+        # Compare the multivariate cdf with some values precomputed
+        # in R version 3.3.2 (2016-10-31) on Debian GNU/Linux.
+
+        # The values below were generated by the following R-script:
+        # > library(mnormt)
+        # > x <- seq(0, 2, length=5)
+        # > y <- 3*x - 2
+        # > z <- x + cos(y)
+        # > mu <- c(1, 3, 2)
+        # > Sigma <- matrix(c(1,2,0,2,5,0.5,0,0.5,3), 3, 3)
+        # > r_cdf <- pmnorm(cbind(x,y,z), mu, Sigma)
+        r_cdf = np.array([0.0017866215, 0.0267142892, 0.0857098761,
+                          0.1063242573, 0.2501068509])
+
+        cdf = multivariate_normal.cdf(r, mean, cov)
+        assert_allclose(cdf, r_cdf, atol=2e-5)
+
+        # Also test bivariate cdf with some values precomputed
+        # in R version 3.3.2 (2016-10-31) on Debian GNU/Linux.
+
+        # The values below were generated by the following R-script:
+        # > library(mnormt)
+        # > x <- seq(0, 2, length=5)
+        # > y <- 3*x - 2
+        # > mu <- c(1, 3)
+        # > Sigma <- matrix(c(1,2,2,5), 2, 2)
+        # > r_cdf2 <- pmnorm(cbind(x,y), mu, Sigma)
+        r_cdf2 = np.array([0.01262147, 0.05838989, 0.18389571,
+                           0.40696599, 0.66470577])
+
+        r2 = np.array([x, y]).T
+
+        mean2 = np.array([1, 3], 'd')
+        cov2 = np.array([[1, 2], [2, 5]], 'd')
+
+        cdf2 = multivariate_normal.cdf(r2, mean2, cov2)
+        assert_allclose(cdf2, r_cdf2, atol=1e-5)
+
+    def test_multivariate_normal_rvs_zero_covariance(self):
+        mean = np.zeros(2)
+        covariance = np.zeros((2, 2))
+        model = multivariate_normal(mean, covariance, allow_singular=True)
+        sample = model.rvs()
+        assert_equal(sample, [0, 0])
+
+    def test_rvs_shape(self):
+        # Check that rvs parses the mean and covariance correctly, and returns
+        # an array of the right shape
+        N = 300
+        d = 4
+        sample = multivariate_normal.rvs(mean=np.zeros(d), cov=1, size=N)
+        assert_equal(sample.shape, (N, d))
+
+        sample = multivariate_normal.rvs(mean=None,
+                                         cov=np.array([[2, .1], [.1, 1]]),
+                                         size=N)
+        assert_equal(sample.shape, (N, 2))
+
+        u = multivariate_normal(mean=0, cov=1)
+        sample = u.rvs(N)
+        assert_equal(sample.shape, (N, ))
+
+    def test_large_sample(self):
+        # Generate large sample and compare sample mean and sample covariance
+        # with mean and covariance matrix.
+
+        np.random.seed(2846)
+
+        n = 3
+        mean = np.random.randn(n)
+        M = np.random.randn(n, n)
+        cov = np.dot(M, M.T)
+        size = 5000
+
+        sample = multivariate_normal.rvs(mean, cov, size)
+
+        assert_allclose(np.cov(sample.T), cov, rtol=1e-1)
+        assert_allclose(sample.mean(0), mean, rtol=1e-1)
+
+    def test_entropy(self):
+        np.random.seed(2846)
+
+        n = 3
+        mean = np.random.randn(n)
+        M = np.random.randn(n, n)
+        cov = np.dot(M, M.T)
+
+        rv = multivariate_normal(mean, cov)
+
+        # Check that frozen distribution agrees with entropy function
+        assert_almost_equal(rv.entropy(), multivariate_normal.entropy(mean, cov))
+        # Compare entropy with manually computed expression involving
+        # the sum of the logs of the eigenvalues of the covariance matrix
+        eigs = np.linalg.eig(cov)[0]
+        desired = 1 / 2 * (n * (np.log(2 * np.pi) + 1) + np.sum(np.log(eigs)))
+        assert_almost_equal(desired, rv.entropy())
+
+    def test_lnB(self):
+        alpha = np.array([1, 1, 1])
+        desired = .5  # e^lnB = 1/2 for [1, 1, 1]
+
+        assert_almost_equal(np.exp(_lnB(alpha)), desired)
+
+    def test_cdf_with_lower_limit_arrays(self):
+        # test CDF with lower limit in several dimensions
+        rng = np.random.default_rng(2408071309372769818)
+        mean = [0, 0]
+        cov = np.eye(2)
+        a = rng.random((4, 3, 2))*6 - 3
+        b = rng.random((4, 3, 2))*6 - 3
+
+        cdf1 = multivariate_normal.cdf(b, mean, cov, lower_limit=a)
+
+        cdf2a = multivariate_normal.cdf(b, mean, cov)
+        cdf2b = multivariate_normal.cdf(a, mean, cov)
+        ab1 = np.concatenate((a[..., 0:1], b[..., 1:2]), axis=-1)
+        ab2 = np.concatenate((a[..., 1:2], b[..., 0:1]), axis=-1)
+        cdf2ab1 = multivariate_normal.cdf(ab1, mean, cov)
+        cdf2ab2 = multivariate_normal.cdf(ab2, mean, cov)
+        cdf2 = cdf2a + cdf2b - cdf2ab1 - cdf2ab2
+
+        assert_allclose(cdf1, cdf2)
+
+    def test_cdf_with_lower_limit_consistency(self):
+        # check that multivariate normal CDF functions are consistent
+        rng = np.random.default_rng(2408071309372769818)
+        mean = rng.random(3)
+        cov = rng.random((3, 3))
+        cov = cov @ cov.T
+        a = rng.random((2, 3))*6 - 3
+        b = rng.random((2, 3))*6 - 3
+
+        cdf1 = multivariate_normal.cdf(b, mean, cov, lower_limit=a)
+        cdf2 = multivariate_normal(mean, cov).cdf(b, lower_limit=a)
+        cdf3 = np.exp(multivariate_normal.logcdf(b, mean, cov, lower_limit=a))
+        cdf4 = np.exp(multivariate_normal(mean, cov).logcdf(b, lower_limit=a))
+
+        assert_allclose(cdf2, cdf1, rtol=1e-4)
+        assert_allclose(cdf3, cdf1, rtol=1e-4)
+        assert_allclose(cdf4, cdf1, rtol=1e-4)
+
+    def test_cdf_signs(self):
+        # check that sign of output is correct when np.any(lower > x)
+        mean = np.zeros(3)
+        cov = np.eye(3)
+        b = [[1, 1, 1], [0, 0, 0], [1, 0, 1], [0, 1, 0]]
+        a = [[0, 0, 0], [1, 1, 1], [0, 1, 0], [1, 0, 1]]
+        # when odd number of elements of b < a, output is negative
+        expected_signs = np.array([1, -1, -1, 1])
+        cdf = multivariate_normal.cdf(b, mean, cov, lower_limit=a)
+        assert_allclose(cdf, cdf[0]*expected_signs)
+
+    def test_mean_cov(self):
+        # test the interaction between a Covariance object and mean
+        P = np.diag(1 / np.array([1, 2, 3]))
+        cov_object = _covariance.CovViaPrecision(P)
+
+        message = "`cov` represents a covariance matrix in 3 dimensions..."
+        with pytest.raises(ValueError, match=message):
+            multivariate_normal.entropy([0, 0], cov_object)
+
+        with pytest.raises(ValueError, match=message):
+            multivariate_normal([0, 0], cov_object)
+
+        x = [0.5, 0.5, 0.5]
+        ref = multivariate_normal.pdf(x, [0, 0, 0], cov_object)
+        assert_equal(multivariate_normal.pdf(x, cov=cov_object), ref)
+
+        ref = multivariate_normal.pdf(x, [1, 1, 1], cov_object)
+        assert_equal(multivariate_normal.pdf(x, 1, cov=cov_object), ref)
+
+    def test_fit_wrong_fit_data_shape(self):
+        data = [1, 3]
+        error_msg = "`x` must be two-dimensional."
+        with pytest.raises(ValueError, match=error_msg):
+            multivariate_normal.fit(data)
+
+    @pytest.mark.parametrize('dim', (3, 5))
+    def test_fit_correctness(self, dim):
+        rng = np.random.default_rng(4385269356937404)
+        x = rng.random((100, dim))
+        mean_est, cov_est = multivariate_normal.fit(x)
+        mean_ref, cov_ref = np.mean(x, axis=0), np.cov(x.T, ddof=0)
+        assert_allclose(mean_est, mean_ref, atol=1e-15)
+        assert_allclose(cov_est, cov_ref, rtol=1e-15)
+
+    def test_fit_both_parameters_fixed(self):
+        data = np.full((2, 1), 3)
+        mean_fixed = 1.
+        cov_fixed = np.atleast_2d(1.)
+        mean, cov = multivariate_normal.fit(data, fix_mean=mean_fixed,
+                                            fix_cov=cov_fixed)
+        assert_equal(mean, mean_fixed)
+        assert_equal(cov, cov_fixed)
+
+    @pytest.mark.parametrize('fix_mean', [np.zeros((2, 2)),
+                                          np.zeros((3, ))])
+    def test_fit_fix_mean_input_validation(self, fix_mean):
+        msg = ("`fix_mean` must be a one-dimensional array the same "
+                "length as the dimensionality of the vectors `x`.")
+        with pytest.raises(ValueError, match=msg):
+            multivariate_normal.fit(np.eye(2), fix_mean=fix_mean)
+
+    @pytest.mark.parametrize('fix_cov', [np.zeros((2, )),
+                                         np.zeros((3, 2)),
+                                         np.zeros((4, 4))])
+    def test_fit_fix_cov_input_validation_dimension(self, fix_cov):
+        msg = ("`fix_cov` must be a two-dimensional square array "
+                "of same side length as the dimensionality of the "
+                "vectors `x`.")
+        with pytest.raises(ValueError, match=msg):
+            multivariate_normal.fit(np.eye(3), fix_cov=fix_cov)
+
+    def test_fit_fix_cov_not_positive_semidefinite(self):
+        error_msg = "`fix_cov` must be symmetric positive semidefinite."
+        with pytest.raises(ValueError, match=error_msg):
+            fix_cov = np.array([[1., 0.], [0., -1.]])
+            multivariate_normal.fit(np.eye(2), fix_cov=fix_cov)
+
+    def test_fit_fix_mean(self):
+        rng = np.random.default_rng(4385269356937404)
+        loc = rng.random(3)
+        A = rng.random((3, 3))
+        cov = np.dot(A, A.T)
+        samples = multivariate_normal.rvs(mean=loc, cov=cov, size=100,
+                                          random_state=rng)
+        mean_free, cov_free = multivariate_normal.fit(samples)
+        logp_free = multivariate_normal.logpdf(samples, mean=mean_free,
+                                               cov=cov_free).sum()
+        mean_fix, cov_fix = multivariate_normal.fit(samples, fix_mean=loc)
+        assert_equal(mean_fix, loc)
+        logp_fix = multivariate_normal.logpdf(samples, mean=mean_fix,
+                                              cov=cov_fix).sum()
+        # test that fixed parameters result in lower likelihood than free
+        # parameters
+        assert logp_fix < logp_free
+        # test that a small perturbation of the resulting parameters
+        # has lower likelihood than the estimated parameters
+        A = rng.random((3, 3))
+        m = 1e-8 * np.dot(A, A.T)
+        cov_perturbed = cov_fix + m
+        logp_perturbed = (multivariate_normal.logpdf(samples,
+                                                     mean=mean_fix,
+                                                     cov=cov_perturbed)
+                                                     ).sum()
+        assert logp_perturbed < logp_fix
+
+
+    def test_fit_fix_cov(self):
+        rng = np.random.default_rng(4385269356937404)
+        loc = rng.random(3)
+        A = rng.random((3, 3))
+        cov = np.dot(A, A.T)
+        samples = multivariate_normal.rvs(mean=loc, cov=cov,
+                                          size=100, random_state=rng)
+        mean_free, cov_free = multivariate_normal.fit(samples)
+        logp_free = multivariate_normal.logpdf(samples, mean=mean_free,
+                                               cov=cov_free).sum()
+        mean_fix, cov_fix = multivariate_normal.fit(samples, fix_cov=cov)
+        assert_equal(mean_fix, np.mean(samples, axis=0))
+        assert_equal(cov_fix, cov)
+        logp_fix = multivariate_normal.logpdf(samples, mean=mean_fix,
+                                              cov=cov_fix).sum()
+        # test that fixed parameters result in lower likelihood than free
+        # parameters
+        assert logp_fix < logp_free
+        # test that a small perturbation of the resulting parameters
+        # has lower likelihood than the estimated parameters
+        mean_perturbed = mean_fix + 1e-8 * rng.random(3)
+        logp_perturbed = (multivariate_normal.logpdf(samples,
+                                                     mean=mean_perturbed,
+                                                     cov=cov_fix)
+                                                     ).sum()
+        assert logp_perturbed < logp_fix
+
+
+class TestMatrixNormal:
+
+    def test_bad_input(self):
+        # Check that bad inputs raise errors
+        num_rows = 4
+        num_cols = 3
+        M = np.full((num_rows,num_cols), 0.3)
+        U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5)
+        V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3)
+
+        # Incorrect dimensions
+        assert_raises(ValueError, matrix_normal, np.zeros((5,4,3)))
+        assert_raises(ValueError, matrix_normal, M, np.zeros(10), V)
+        assert_raises(ValueError, matrix_normal, M, U, np.zeros(10))
+        assert_raises(ValueError, matrix_normal, M, U, U)
+        assert_raises(ValueError, matrix_normal, M, V, V)
+        assert_raises(ValueError, matrix_normal, M.T, U, V)
+
+        e = np.linalg.LinAlgError
+        # Singular covariance for the rvs method of a non-frozen instance
+        assert_raises(e, matrix_normal.rvs,
+                      M, U, np.ones((num_cols, num_cols)))
+        assert_raises(e, matrix_normal.rvs,
+                      M, np.ones((num_rows, num_rows)), V)
+        # Singular covariance for a frozen instance
+        assert_raises(e, matrix_normal, M, U, np.ones((num_cols, num_cols)))
+        assert_raises(e, matrix_normal, M, np.ones((num_rows, num_rows)), V)
+
+    def test_default_inputs(self):
+        # Check that default argument handling works
+        num_rows = 4
+        num_cols = 3
+        M = np.full((num_rows,num_cols), 0.3)
+        U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5)
+        V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3)
+        Z = np.zeros((num_rows, num_cols))
+        Zr = np.zeros((num_rows, 1))
+        Zc = np.zeros((1, num_cols))
+        Ir = np.identity(num_rows)
+        Ic = np.identity(num_cols)
+        I1 = np.identity(1)
+
+        assert_equal(matrix_normal.rvs(mean=M, rowcov=U, colcov=V).shape,
+                     (num_rows, num_cols))
+        assert_equal(matrix_normal.rvs(mean=M).shape,
+                     (num_rows, num_cols))
+        assert_equal(matrix_normal.rvs(rowcov=U).shape,
+                     (num_rows, 1))
+        assert_equal(matrix_normal.rvs(colcov=V).shape,
+                     (1, num_cols))
+        assert_equal(matrix_normal.rvs(mean=M, colcov=V).shape,
+                     (num_rows, num_cols))
+        assert_equal(matrix_normal.rvs(mean=M, rowcov=U).shape,
+                     (num_rows, num_cols))
+        assert_equal(matrix_normal.rvs(rowcov=U, colcov=V).shape,
+                     (num_rows, num_cols))
+
+        assert_equal(matrix_normal(mean=M).rowcov, Ir)
+        assert_equal(matrix_normal(mean=M).colcov, Ic)
+        assert_equal(matrix_normal(rowcov=U).mean, Zr)
+        assert_equal(matrix_normal(rowcov=U).colcov, I1)
+        assert_equal(matrix_normal(colcov=V).mean, Zc)
+        assert_equal(matrix_normal(colcov=V).rowcov, I1)
+        assert_equal(matrix_normal(mean=M, rowcov=U).colcov, Ic)
+        assert_equal(matrix_normal(mean=M, colcov=V).rowcov, Ir)
+        assert_equal(matrix_normal(rowcov=U, colcov=V).mean, Z)
+
+    def test_covariance_expansion(self):
+        # Check that covariance can be specified with scalar or vector
+        num_rows = 4
+        num_cols = 3
+        M = np.full((num_rows, num_cols), 0.3)
+        Uv = np.full(num_rows, 0.2)
+        Us = 0.2
+        Vv = np.full(num_cols, 0.1)
+        Vs = 0.1
+
+        Ir = np.identity(num_rows)
+        Ic = np.identity(num_cols)
+
+        assert_equal(matrix_normal(mean=M, rowcov=Uv, colcov=Vv).rowcov,
+                     0.2*Ir)
+        assert_equal(matrix_normal(mean=M, rowcov=Uv, colcov=Vv).colcov,
+                     0.1*Ic)
+        assert_equal(matrix_normal(mean=M, rowcov=Us, colcov=Vs).rowcov,
+                     0.2*Ir)
+        assert_equal(matrix_normal(mean=M, rowcov=Us, colcov=Vs).colcov,
+                     0.1*Ic)
+
+    def test_frozen_matrix_normal(self):
+        for i in range(1,5):
+            for j in range(1,5):
+                M = np.full((i,j), 0.3)
+                U = 0.5 * np.identity(i) + np.full((i,i), 0.5)
+                V = 0.7 * np.identity(j) + np.full((j,j), 0.3)
+
+                frozen = matrix_normal(mean=M, rowcov=U, colcov=V)
+
+                rvs1 = frozen.rvs(random_state=1234)
+                rvs2 = matrix_normal.rvs(mean=M, rowcov=U, colcov=V,
+                                         random_state=1234)
+                assert_equal(rvs1, rvs2)
+
+                X = frozen.rvs(random_state=1234)
+
+                pdf1 = frozen.pdf(X)
+                pdf2 = matrix_normal.pdf(X, mean=M, rowcov=U, colcov=V)
+                assert_equal(pdf1, pdf2)
+
+                logpdf1 = frozen.logpdf(X)
+                logpdf2 = matrix_normal.logpdf(X, mean=M, rowcov=U, colcov=V)
+                assert_equal(logpdf1, logpdf2)
+
+    def test_matches_multivariate(self):
+        # Check that the pdfs match those obtained by vectorising and
+        # treating as a multivariate normal.
+        for i in range(1,5):
+            for j in range(1,5):
+                M = np.full((i,j), 0.3)
+                U = 0.5 * np.identity(i) + np.full((i,i), 0.5)
+                V = 0.7 * np.identity(j) + np.full((j,j), 0.3)
+
+                frozen = matrix_normal(mean=M, rowcov=U, colcov=V)
+                X = frozen.rvs(random_state=1234)
+                pdf1 = frozen.pdf(X)
+                logpdf1 = frozen.logpdf(X)
+                entropy1 = frozen.entropy()
+
+                vecX = X.T.flatten()
+                vecM = M.T.flatten()
+                cov = np.kron(V,U)
+                pdf2 = multivariate_normal.pdf(vecX, mean=vecM, cov=cov)
+                logpdf2 = multivariate_normal.logpdf(vecX, mean=vecM, cov=cov)
+                entropy2 = multivariate_normal.entropy(mean=vecM, cov=cov)
+
+                assert_allclose(pdf1, pdf2, rtol=1E-10)
+                assert_allclose(logpdf1, logpdf2, rtol=1E-10)
+                assert_allclose(entropy1, entropy2)
+
+    def test_array_input(self):
+        # Check array of inputs has the same output as the separate entries.
+        num_rows = 4
+        num_cols = 3
+        M = np.full((num_rows,num_cols), 0.3)
+        U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5)
+        V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3)
+        N = 10
+
+        frozen = matrix_normal(mean=M, rowcov=U, colcov=V)
+        X1 = frozen.rvs(size=N, random_state=1234)
+        X2 = frozen.rvs(size=N, random_state=4321)
+        X = np.concatenate((X1[np.newaxis,:,:,:],X2[np.newaxis,:,:,:]), axis=0)
+        assert_equal(X.shape, (2, N, num_rows, num_cols))
+
+        array_logpdf = frozen.logpdf(X)
+        assert_equal(array_logpdf.shape, (2, N))
+        for i in range(2):
+            for j in range(N):
+                separate_logpdf = matrix_normal.logpdf(X[i,j], mean=M,
+                                                       rowcov=U, colcov=V)
+                assert_allclose(separate_logpdf, array_logpdf[i,j], 1E-10)
+
+    def test_moments(self):
+        # Check that the sample moments match the parameters
+        num_rows = 4
+        num_cols = 3
+        M = np.full((num_rows,num_cols), 0.3)
+        U = 0.5 * np.identity(num_rows) + np.full((num_rows, num_rows), 0.5)
+        V = 0.7 * np.identity(num_cols) + np.full((num_cols, num_cols), 0.3)
+        N = 1000
+
+        frozen = matrix_normal(mean=M, rowcov=U, colcov=V)
+        X = frozen.rvs(size=N, random_state=1234)
+
+        sample_mean = np.mean(X,axis=0)
+        assert_allclose(sample_mean, M, atol=0.1)
+
+        sample_colcov = np.cov(X.reshape(N*num_rows,num_cols).T)
+        assert_allclose(sample_colcov, V, atol=0.1)
+
+        sample_rowcov = np.cov(np.swapaxes(X,1,2).reshape(
+                                                        N*num_cols,num_rows).T)
+        assert_allclose(sample_rowcov, U, atol=0.1)
+
+    def test_samples(self):
+        # Regression test to ensure that we always generate the same stream of
+        # random variates.
+        actual = matrix_normal.rvs(
+            mean=np.array([[1, 2], [3, 4]]),
+            rowcov=np.array([[4, -1], [-1, 2]]),
+            colcov=np.array([[5, 1], [1, 10]]),
+            random_state=np.random.default_rng(0),
+            size=2
+        )
+        expected = np.array(
+            [[[1.56228264238181, -1.24136424071189],
+              [2.46865788392114, 6.22964440489445]],
+             [[3.86405716144353, 10.73714311429529],
+              [2.59428444080606, 5.79987854490876]]]
+        )
+        assert_allclose(actual, expected)
+
+
+class TestDirichlet:
+
+    def test_frozen_dirichlet(self):
+        np.random.seed(2846)
+
+        n = np.random.randint(1, 32)
+        alpha = np.random.uniform(10e-10, 100, n)
+
+        d = dirichlet(alpha)
+
+        assert_equal(d.var(), dirichlet.var(alpha))
+        assert_equal(d.mean(), dirichlet.mean(alpha))
+        assert_equal(d.entropy(), dirichlet.entropy(alpha))
+        num_tests = 10
+        for i in range(num_tests):
+            x = np.random.uniform(10e-10, 100, n)
+            x /= np.sum(x)
+            assert_equal(d.pdf(x[:-1]), dirichlet.pdf(x[:-1], alpha))
+            assert_equal(d.logpdf(x[:-1]), dirichlet.logpdf(x[:-1], alpha))
+
+    def test_numpy_rvs_shape_compatibility(self):
+        np.random.seed(2846)
+        alpha = np.array([1.0, 2.0, 3.0])
+        x = np.random.dirichlet(alpha, size=7)
+        assert_equal(x.shape, (7, 3))
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+        dirichlet.pdf(x.T, alpha)
+        dirichlet.pdf(x.T[:-1], alpha)
+        dirichlet.logpdf(x.T, alpha)
+        dirichlet.logpdf(x.T[:-1], alpha)
+
+    def test_alpha_with_zeros(self):
+        np.random.seed(2846)
+        alpha = [1.0, 0.0, 3.0]
+        # don't pass invalid alpha to np.random.dirichlet
+        x = np.random.dirichlet(np.maximum(1e-9, alpha), size=7).T
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_alpha_with_negative_entries(self):
+        np.random.seed(2846)
+        alpha = [1.0, -2.0, 3.0]
+        # don't pass invalid alpha to np.random.dirichlet
+        x = np.random.dirichlet(np.maximum(1e-9, alpha), size=7).T
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_data_with_zeros(self):
+        alpha = np.array([1.0, 2.0, 3.0, 4.0])
+        x = np.array([0.1, 0.0, 0.2, 0.7])
+        dirichlet.pdf(x, alpha)
+        dirichlet.logpdf(x, alpha)
+        alpha = np.array([1.0, 1.0, 1.0, 1.0])
+        assert_almost_equal(dirichlet.pdf(x, alpha), 6)
+        assert_almost_equal(dirichlet.logpdf(x, alpha), np.log(6))
+
+    def test_data_with_zeros_and_small_alpha(self):
+        alpha = np.array([1.0, 0.5, 3.0, 4.0])
+        x = np.array([0.1, 0.0, 0.2, 0.7])
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_data_with_negative_entries(self):
+        alpha = np.array([1.0, 2.0, 3.0, 4.0])
+        x = np.array([0.1, -0.1, 0.3, 0.7])
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_data_with_too_large_entries(self):
+        alpha = np.array([1.0, 2.0, 3.0, 4.0])
+        x = np.array([0.1, 1.1, 0.3, 0.7])
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_data_too_deep_c(self):
+        alpha = np.array([1.0, 2.0, 3.0])
+        x = np.full((2, 7, 7), 1 / 14)
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_alpha_too_deep(self):
+        alpha = np.array([[1.0, 2.0], [3.0, 4.0]])
+        x = np.full((2, 2, 7), 1 / 4)
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_alpha_correct_depth(self):
+        alpha = np.array([1.0, 2.0, 3.0])
+        x = np.full((3, 7), 1 / 3)
+        dirichlet.pdf(x, alpha)
+        dirichlet.logpdf(x, alpha)
+
+    def test_non_simplex_data(self):
+        alpha = np.array([1.0, 2.0, 3.0])
+        x = np.full((3, 7), 1 / 2)
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_data_vector_too_short(self):
+        alpha = np.array([1.0, 2.0, 3.0, 4.0])
+        x = np.full((2, 7), 1 / 2)
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_data_vector_too_long(self):
+        alpha = np.array([1.0, 2.0, 3.0, 4.0])
+        x = np.full((5, 7), 1 / 5)
+        assert_raises(ValueError, dirichlet.pdf, x, alpha)
+        assert_raises(ValueError, dirichlet.logpdf, x, alpha)
+
+    def test_mean_var_cov(self):
+        # Reference values calculated by hand and confirmed with Mathematica, e.g.
+        # `Covariance[DirichletDistribution[{ 1, 0.8, 0.2, 10^-300}]]`
+        alpha = np.array([1., 0.8, 0.2])
+        d = dirichlet(alpha)
+
+        expected_mean = [0.5, 0.4, 0.1]
+        expected_var = [1. / 12., 0.08, 0.03]
+        expected_cov = [
+                [ 1. / 12, -1. / 15, -1. / 60],
+                [-1. / 15,  2. / 25, -1. / 75],
+                [-1. / 60, -1. / 75,  3. / 100],
+        ]
+
+        assert_array_almost_equal(d.mean(), expected_mean)
+        assert_array_almost_equal(d.var(), expected_var)
+        assert_array_almost_equal(d.cov(), expected_cov)
+
+    def test_scalar_values(self):
+        alpha = np.array([0.2])
+        d = dirichlet(alpha)
+
+        # For alpha of length 1, mean and var should be scalar instead of array
+        assert_equal(d.mean().ndim, 0)
+        assert_equal(d.var().ndim, 0)
+
+        assert_equal(d.pdf([1.]).ndim, 0)
+        assert_equal(d.logpdf([1.]).ndim, 0)
+
+    def test_K_and_K_minus_1_calls_equal(self):
+        # Test that calls with K and K-1 entries yield the same results.
+
+        np.random.seed(2846)
+
+        n = np.random.randint(1, 32)
+        alpha = np.random.uniform(10e-10, 100, n)
+
+        d = dirichlet(alpha)
+        num_tests = 10
+        for i in range(num_tests):
+            x = np.random.uniform(10e-10, 100, n)
+            x /= np.sum(x)
+            assert_almost_equal(d.pdf(x[:-1]), d.pdf(x))
+
+    def test_multiple_entry_calls(self):
+        # Test that calls with multiple x vectors as matrix work
+        np.random.seed(2846)
+
+        n = np.random.randint(1, 32)
+        alpha = np.random.uniform(10e-10, 100, n)
+        d = dirichlet(alpha)
+
+        num_tests = 10
+        num_multiple = 5
+        xm = None
+        for i in range(num_tests):
+            for m in range(num_multiple):
+                x = np.random.uniform(10e-10, 100, n)
+                x /= np.sum(x)
+                if xm is not None:
+                    xm = np.vstack((xm, x))
+                else:
+                    xm = x
+            rm = d.pdf(xm.T)
+            rs = None
+            for xs in xm:
+                r = d.pdf(xs)
+                if rs is not None:
+                    rs = np.append(rs, r)
+                else:
+                    rs = r
+            assert_array_almost_equal(rm, rs)
+
+    def test_2D_dirichlet_is_beta(self):
+        np.random.seed(2846)
+
+        alpha = np.random.uniform(10e-10, 100, 2)
+        d = dirichlet(alpha)
+        b = beta(alpha[0], alpha[1])
+
+        num_tests = 10
+        for i in range(num_tests):
+            x = np.random.uniform(10e-10, 100, 2)
+            x /= np.sum(x)
+            assert_almost_equal(b.pdf(x), d.pdf([x]))
+
+        assert_almost_equal(b.mean(), d.mean()[0])
+        assert_almost_equal(b.var(), d.var()[0])
+
+
+def test_multivariate_normal_dimensions_mismatch():
+    # Regression test for GH #3493. Check that setting up a PDF with a mean of
+    # length M and a covariance matrix of size (N, N), where M != N, raises a
+    # ValueError with an informative error message.
+    mu = np.array([0.0, 0.0])
+    sigma = np.array([[1.0]])
+
+    assert_raises(ValueError, multivariate_normal, mu, sigma)
+
+    # A simple check that the right error message was passed along. Checking
+    # that the entire message is there, word for word, would be somewhat
+    # fragile, so we just check for the leading part.
+    try:
+        multivariate_normal(mu, sigma)
+    except ValueError as e:
+        msg = "Dimension mismatch"
+        assert_equal(str(e)[:len(msg)], msg)
+
+
+class TestWishart:
+    def test_scale_dimensions(self):
+        # Test that we can call the Wishart with various scale dimensions
+
+        # Test case: dim=1, scale=1
+        true_scale = np.array(1, ndmin=2)
+        scales = [
+            1,                    # scalar
+            [1],                  # iterable
+            np.array(1),          # 0-dim
+            np.r_[1],             # 1-dim
+            np.array(1, ndmin=2)  # 2-dim
+        ]
+        for scale in scales:
+            w = wishart(1, scale)
+            assert_equal(w.scale, true_scale)
+            assert_equal(w.scale.shape, true_scale.shape)
+
+        # Test case: dim=2, scale=[[1,0]
+        #                          [0,2]
+        true_scale = np.array([[1,0],
+                               [0,2]])
+        scales = [
+            [1,2],             # iterable
+            np.r_[1,2],        # 1-dim
+            np.array([[1,0],   # 2-dim
+                      [0,2]])
+        ]
+        for scale in scales:
+            w = wishart(2, scale)
+            assert_equal(w.scale, true_scale)
+            assert_equal(w.scale.shape, true_scale.shape)
+
+        # We cannot call with a df < dim - 1
+        assert_raises(ValueError, wishart, 1, np.eye(2))
+
+        # But we can call with dim - 1 < df < dim
+        wishart(1.1, np.eye(2))  # no error
+        # see gh-5562
+
+        # We cannot call with a 3-dimension array
+        scale = np.array(1, ndmin=3)
+        assert_raises(ValueError, wishart, 1, scale)
+
+    def test_quantile_dimensions(self):
+        # Test that we can call the Wishart rvs with various quantile dimensions
+
+        # If dim == 1, consider x.shape = [1,1,1]
+        X = [
+            1,                      # scalar
+            [1],                    # iterable
+            np.array(1),            # 0-dim
+            np.r_[1],               # 1-dim
+            np.array(1, ndmin=2),   # 2-dim
+            np.array([1], ndmin=3)  # 3-dim
+        ]
+
+        w = wishart(1,1)
+        density = w.pdf(np.array(1, ndmin=3))
+        for x in X:
+            assert_equal(w.pdf(x), density)
+
+        # If dim == 1, consider x.shape = [1,1,*]
+        X = [
+            [1,2,3],                     # iterable
+            np.r_[1,2,3],                # 1-dim
+            np.array([1,2,3], ndmin=3)   # 3-dim
+        ]
+
+        w = wishart(1,1)
+        density = w.pdf(np.array([1,2,3], ndmin=3))
+        for x in X:
+            assert_equal(w.pdf(x), density)
+
+        # If dim == 2, consider x.shape = [2,2,1]
+        # where x[:,:,*] = np.eye(1)*2
+        X = [
+            2,                    # scalar
+            [2,2],                # iterable
+            np.array(2),          # 0-dim
+            np.r_[2,2],           # 1-dim
+            np.array([[2,0],
+                      [0,2]]),    # 2-dim
+            np.array([[2,0],
+                      [0,2]])[:,:,np.newaxis]  # 3-dim
+        ]
+
+        w = wishart(2,np.eye(2))
+        density = w.pdf(np.array([[2,0],
+                                  [0,2]])[:,:,np.newaxis])
+        for x in X:
+            assert_equal(w.pdf(x), density)
+
+    def test_frozen(self):
+        # Test that the frozen and non-frozen Wishart gives the same answers
+
+        # Construct an arbitrary positive definite scale matrix
+        dim = 4
+        scale = np.diag(np.arange(dim)+1)
+        scale[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim-1) // 2)
+        scale = np.dot(scale.T, scale)
+
+        # Construct a collection of positive definite matrices to test the PDF
+        X = []
+        for i in range(5):
+            x = np.diag(np.arange(dim)+(i+1)**2)
+            x[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim-1) // 2)
+            x = np.dot(x.T, x)
+            X.append(x)
+        X = np.array(X).T
+
+        # Construct a 1D and 2D set of parameters
+        parameters = [
+            (10, 1, np.linspace(0.1, 10, 5)),  # 1D case
+            (10, scale, X)
+        ]
+
+        for (df, scale, x) in parameters:
+            w = wishart(df, scale)
+            assert_equal(w.var(), wishart.var(df, scale))
+            assert_equal(w.mean(), wishart.mean(df, scale))
+            assert_equal(w.mode(), wishart.mode(df, scale))
+            assert_equal(w.entropy(), wishart.entropy(df, scale))
+            assert_equal(w.pdf(x), wishart.pdf(x, df, scale))
+
+    def test_wishart_2D_rvs(self):
+        dim = 3
+        df = 10
+
+        # Construct a simple non-diagonal positive definite matrix
+        scale = np.eye(dim)
+        scale[0,1] = 0.5
+        scale[1,0] = 0.5
+
+        # Construct frozen Wishart random variables
+        w = wishart(df, scale)
+
+        # Get the generated random variables from a known seed
+        np.random.seed(248042)
+        w_rvs = wishart.rvs(df, scale)
+        np.random.seed(248042)
+        frozen_w_rvs = w.rvs()
+
+        # Manually calculate what it should be, based on the Bartlett (1933)
+        # decomposition of a Wishart into D A A' D', where D is the Cholesky
+        # factorization of the scale matrix and A is the lower triangular matrix
+        # with the square root of chi^2 variates on the diagonal and N(0,1)
+        # variates in the lower triangle.
+        np.random.seed(248042)
+        covariances = np.random.normal(size=3)
+        variances = np.r_[
+            np.random.chisquare(df),
+            np.random.chisquare(df-1),
+            np.random.chisquare(df-2),
+        ]**0.5
+
+        # Construct the lower-triangular A matrix
+        A = np.diag(variances)
+        A[np.tril_indices(dim, k=-1)] = covariances
+
+        # Wishart random variate
+        D = np.linalg.cholesky(scale)
+        DA = D.dot(A)
+        manual_w_rvs = np.dot(DA, DA.T)
+
+        # Test for equality
+        assert_allclose(w_rvs, manual_w_rvs)
+        assert_allclose(frozen_w_rvs, manual_w_rvs)
+
+    def test_1D_is_chisquared(self):
+        # The 1-dimensional Wishart with an identity scale matrix is just a
+        # chi-squared distribution.
+        # Test variance, mean, entropy, pdf
+        # Kolgomorov-Smirnov test for rvs
+        np.random.seed(482974)
+
+        sn = 500
+        dim = 1
+        scale = np.eye(dim)
+
+        df_range = np.arange(1, 10, 2, dtype=float)
+        X = np.linspace(0.1,10,num=10)
+        for df in df_range:
+            w = wishart(df, scale)
+            c = chi2(df)
+
+            # Statistics
+            assert_allclose(w.var(), c.var())
+            assert_allclose(w.mean(), c.mean())
+            assert_allclose(w.entropy(), c.entropy())
+
+            # PDF
+            assert_allclose(w.pdf(X), c.pdf(X))
+
+            # rvs
+            rvs = w.rvs(size=sn)
+            args = (df,)
+            alpha = 0.01
+            check_distribution_rvs('chi2', args, alpha, rvs)
+
+    def test_is_scaled_chisquared(self):
+        # The 2-dimensional Wishart with an arbitrary scale matrix can be
+        # transformed to a scaled chi-squared distribution.
+        # For :math:`S \sim W_p(V,n)` and :math:`\lambda \in \mathbb{R}^p` we have
+        # :math:`\lambda' S \lambda \sim \lambda' V \lambda \times \chi^2(n)`
+        np.random.seed(482974)
+
+        sn = 500
+        df = 10
+        dim = 4
+        # Construct an arbitrary positive definite matrix
+        scale = np.diag(np.arange(4)+1)
+        scale[np.tril_indices(4, k=-1)] = np.arange(6)
+        scale = np.dot(scale.T, scale)
+        # Use :math:`\lambda = [1, \dots, 1]'`
+        lamda = np.ones((dim,1))
+        sigma_lamda = lamda.T.dot(scale).dot(lamda).squeeze()
+        w = wishart(df, sigma_lamda)
+        c = chi2(df, scale=sigma_lamda)
+
+        # Statistics
+        assert_allclose(w.var(), c.var())
+        assert_allclose(w.mean(), c.mean())
+        assert_allclose(w.entropy(), c.entropy())
+
+        # PDF
+        X = np.linspace(0.1,10,num=10)
+        assert_allclose(w.pdf(X), c.pdf(X))
+
+        # rvs
+        rvs = w.rvs(size=sn)
+        args = (df,0,sigma_lamda)
+        alpha = 0.01
+        check_distribution_rvs('chi2', args, alpha, rvs)
+
+class TestMultinomial:
+    def test_logpmf(self):
+        vals1 = multinomial.logpmf((3,4), 7, (0.3, 0.7))
+        assert_allclose(vals1, -1.483270127243324, rtol=1e-8)
+
+        vals2 = multinomial.logpmf([3, 4], 0, [.3, .7])
+        assert vals2 == -np.inf
+
+        vals3 = multinomial.logpmf([0, 0], 0, [.3, .7])
+        assert vals3 == 0
+
+        vals4 = multinomial.logpmf([3, 4], 0, [-2, 3])
+        assert_allclose(vals4, np.nan, rtol=1e-8)
+
+    def test_reduces_binomial(self):
+        # test that the multinomial pmf reduces to the binomial pmf in the 2d
+        # case
+        val1 = multinomial.logpmf((3, 4), 7, (0.3, 0.7))
+        val2 = binom.logpmf(3, 7, 0.3)
+        assert_allclose(val1, val2, rtol=1e-8)
+
+        val1 = multinomial.pmf((6, 8), 14, (0.1, 0.9))
+        val2 = binom.pmf(6, 14, 0.1)
+        assert_allclose(val1, val2, rtol=1e-8)
+
+    def test_R(self):
+        # test against the values produced by this R code
+        # (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/Multinom.html)
+        # X <- t(as.matrix(expand.grid(0:3, 0:3))); X <- X[, colSums(X) <= 3]
+        # X <- rbind(X, 3:3 - colSums(X)); dimnames(X) <- list(letters[1:3], NULL)
+        # X
+        # apply(X, 2, function(x) dmultinom(x, prob = c(1,2,5)))
+
+        n, p = 3, [1./8, 2./8, 5./8]
+        r_vals = {(0, 0, 3): 0.244140625, (1, 0, 2): 0.146484375,
+                  (2, 0, 1): 0.029296875, (3, 0, 0): 0.001953125,
+                  (0, 1, 2): 0.292968750, (1, 1, 1): 0.117187500,
+                  (2, 1, 0): 0.011718750, (0, 2, 1): 0.117187500,
+                  (1, 2, 0): 0.023437500, (0, 3, 0): 0.015625000}
+        for x in r_vals:
+            assert_allclose(multinomial.pmf(x, n, p), r_vals[x], atol=1e-14)
+
+    @pytest.mark.parametrize("n", [0, 3])
+    def test_rvs_np(self, n):
+        # test that .rvs agrees w/numpy
+        sc_rvs = multinomial.rvs(n, [1/4.]*3, size=7, random_state=123)
+        rndm = np.random.RandomState(123)
+        np_rvs = rndm.multinomial(n, [1/4.]*3, size=7)
+        assert_equal(sc_rvs, np_rvs)
+
+    def test_pmf(self):
+        vals0 = multinomial.pmf((5,), 5, (1,))
+        assert_allclose(vals0, 1, rtol=1e-8)
+
+        vals1 = multinomial.pmf((3,4), 7, (.3, .7))
+        assert_allclose(vals1, .22689449999999994, rtol=1e-8)
+
+        vals2 = multinomial.pmf([[[3,5],[0,8]], [[-1, 9], [1, 1]]], 8,
+                                (.1, .9))
+        assert_allclose(vals2, [[.03306744, .43046721], [0, 0]], rtol=1e-8)
+
+        x = np.empty((0,2), dtype=np.float64)
+        vals3 = multinomial.pmf(x, 4, (.3, .7))
+        assert_equal(vals3, np.empty([], dtype=np.float64))
+
+        vals4 = multinomial.pmf([1,2], 4, (.3, .7))
+        assert_allclose(vals4, 0, rtol=1e-8)
+
+        vals5 = multinomial.pmf([3, 3, 0], 6, [2/3.0, 1/3.0, 0])
+        assert_allclose(vals5, 0.219478737997, rtol=1e-8)
+
+        vals5 = multinomial.pmf([0, 0, 0], 0, [2/3.0, 1/3.0, 0])
+        assert vals5 == 1
+
+        vals6 = multinomial.pmf([2, 1, 0], 0, [2/3.0, 1/3.0, 0])
+        assert vals6 == 0
+
+    def test_pmf_broadcasting(self):
+        vals0 = multinomial.pmf([1, 2], 3, [[.1, .9], [.2, .8]])
+        assert_allclose(vals0, [.243, .384], rtol=1e-8)
+
+        vals1 = multinomial.pmf([1, 2], [3, 4], [.1, .9])
+        assert_allclose(vals1, [.243, 0], rtol=1e-8)
+
+        vals2 = multinomial.pmf([[[1, 2], [1, 1]]], 3, [.1, .9])
+        assert_allclose(vals2, [[.243, 0]], rtol=1e-8)
+
+        vals3 = multinomial.pmf([1, 2], [[[3], [4]]], [.1, .9])
+        assert_allclose(vals3, [[[.243], [0]]], rtol=1e-8)
+
+        vals4 = multinomial.pmf([[1, 2], [1,1]], [[[[3]]]], [.1, .9])
+        assert_allclose(vals4, [[[[.243, 0]]]], rtol=1e-8)
+
+    @pytest.mark.parametrize("n", [0, 5])
+    def test_cov(self, n):
+        cov1 = multinomial.cov(n, (.2, .3, .5))
+        cov2 = [[n*.2*.8, -n*.2*.3, -n*.2*.5],
+                [-n*.3*.2, n*.3*.7, -n*.3*.5],
+                [-n*.5*.2, -n*.5*.3, n*.5*.5]]
+        assert_allclose(cov1, cov2, rtol=1e-8)
+
+    def test_cov_broadcasting(self):
+        cov1 = multinomial.cov(5, [[.1, .9], [.2, .8]])
+        cov2 = [[[.45, -.45],[-.45, .45]], [[.8, -.8], [-.8, .8]]]
+        assert_allclose(cov1, cov2, rtol=1e-8)
+
+        cov3 = multinomial.cov([4, 5], [.1, .9])
+        cov4 = [[[.36, -.36], [-.36, .36]], [[.45, -.45], [-.45, .45]]]
+        assert_allclose(cov3, cov4, rtol=1e-8)
+
+        cov5 = multinomial.cov([4, 5], [[.3, .7], [.4, .6]])
+        cov6 = [[[4*.3*.7, -4*.3*.7], [-4*.3*.7, 4*.3*.7]],
+                [[5*.4*.6, -5*.4*.6], [-5*.4*.6, 5*.4*.6]]]
+        assert_allclose(cov5, cov6, rtol=1e-8)
+
+    @pytest.mark.parametrize("n", [0, 2])
+    def test_entropy(self, n):
+        # this is equivalent to a binomial distribution with n=2, so the
+        # entropy .77899774929 is easily computed "by hand"
+        ent0 = multinomial.entropy(n, [.2, .8])
+        assert_allclose(ent0, binom.entropy(n, .2), rtol=1e-8)
+
+    def test_entropy_broadcasting(self):
+        ent0 = multinomial.entropy([2, 3], [.2, .3])
+        assert_allclose(ent0, [binom.entropy(2, .2), binom.entropy(3, .2)],
+                        rtol=1e-8)
+
+        ent1 = multinomial.entropy([7, 8], [[.3, .7], [.4, .6]])
+        assert_allclose(ent1, [binom.entropy(7, .3), binom.entropy(8, .4)],
+                        rtol=1e-8)
+
+        ent2 = multinomial.entropy([[7], [8]], [[.3, .7], [.4, .6]])
+        assert_allclose(ent2,
+                        [[binom.entropy(7, .3), binom.entropy(7, .4)],
+                         [binom.entropy(8, .3), binom.entropy(8, .4)]],
+                        rtol=1e-8)
+
+    @pytest.mark.parametrize("n", [0, 5])
+    def test_mean(self, n):
+        mean1 = multinomial.mean(n, [.2, .8])
+        assert_allclose(mean1, [n*.2, n*.8], rtol=1e-8)
+
+    def test_mean_broadcasting(self):
+        mean1 = multinomial.mean([5, 6], [.2, .8])
+        assert_allclose(mean1, [[5*.2, 5*.8], [6*.2, 6*.8]], rtol=1e-8)
+
+    def test_frozen(self):
+        # The frozen distribution should agree with the regular one
+        np.random.seed(1234)
+        n = 12
+        pvals = (.1, .2, .3, .4)
+        x = [[0,0,0,12],[0,0,1,11],[0,1,1,10],[1,1,1,9],[1,1,2,8]]
+        x = np.asarray(x, dtype=np.float64)
+        mn_frozen = multinomial(n, pvals)
+        assert_allclose(mn_frozen.pmf(x), multinomial.pmf(x, n, pvals))
+        assert_allclose(mn_frozen.logpmf(x), multinomial.logpmf(x, n, pvals))
+        assert_allclose(mn_frozen.entropy(), multinomial.entropy(n, pvals))
+
+    def test_gh_11860(self):
+        # gh-11860 reported cases in which the adjustments made by multinomial
+        # to the last element of `p` can cause `nan`s even when the input is
+        # essentially valid. Check that a pathological case returns a finite,
+        # nonzero result. (This would fail in main before the PR.)
+        n = 88
+        rng = np.random.default_rng(8879715917488330089)
+        p = rng.random(n)
+        p[-1] = 1e-30
+        p /= np.sum(p)
+        x = np.ones(n)
+        logpmf = multinomial.logpmf(x, n, p)
+        assert np.isfinite(logpmf)
+
+class TestInvwishart:
+    def test_frozen(self):
+        # Test that the frozen and non-frozen inverse Wishart gives the same
+        # answers
+
+        # Construct an arbitrary positive definite scale matrix
+        dim = 4
+        scale = np.diag(np.arange(dim)+1)
+        scale[np.tril_indices(dim, k=-1)] = np.arange(dim*(dim-1)/2)
+        scale = np.dot(scale.T, scale)
+
+        # Construct a collection of positive definite matrices to test the PDF
+        X = []
+        for i in range(5):
+            x = np.diag(np.arange(dim)+(i+1)**2)
+            x[np.tril_indices(dim, k=-1)] = np.arange(dim*(dim-1)/2)
+            x = np.dot(x.T, x)
+            X.append(x)
+        X = np.array(X).T
+
+        # Construct a 1D and 2D set of parameters
+        parameters = [
+            (10, 1, np.linspace(0.1, 10, 5)),  # 1D case
+            (10, scale, X)
+        ]
+
+        for (df, scale, x) in parameters:
+            iw = invwishart(df, scale)
+            assert_equal(iw.var(), invwishart.var(df, scale))
+            assert_equal(iw.mean(), invwishart.mean(df, scale))
+            assert_equal(iw.mode(), invwishart.mode(df, scale))
+            assert_allclose(iw.pdf(x), invwishart.pdf(x, df, scale))
+
+    def test_1D_is_invgamma(self):
+        # The 1-dimensional inverse Wishart with an identity scale matrix is
+        # just an inverse gamma distribution.
+        # Test variance, mean, pdf, entropy
+        # Kolgomorov-Smirnov test for rvs
+        np.random.seed(482974)
+
+        sn = 500
+        dim = 1
+        scale = np.eye(dim)
+
+        df_range = np.arange(5, 20, 2, dtype=float)
+        X = np.linspace(0.1,10,num=10)
+        for df in df_range:
+            iw = invwishart(df, scale)
+            ig = invgamma(df/2, scale=1./2)
+
+            # Statistics
+            assert_allclose(iw.var(), ig.var())
+            assert_allclose(iw.mean(), ig.mean())
+
+            # PDF
+            assert_allclose(iw.pdf(X), ig.pdf(X))
+
+            # rvs
+            rvs = iw.rvs(size=sn)
+            args = (df/2, 0, 1./2)
+            alpha = 0.01
+            check_distribution_rvs('invgamma', args, alpha, rvs)
+
+            # entropy
+            assert_allclose(iw.entropy(), ig.entropy())
+
+    def test_invwishart_2D_rvs(self):
+        dim = 3
+        df = 10
+
+        # Construct a simple non-diagonal positive definite matrix
+        scale = np.eye(dim)
+        scale[0,1] = 0.5
+        scale[1,0] = 0.5
+
+        # Construct frozen inverse-Wishart random variables
+        iw = invwishart(df, scale)
+
+        # Get the generated random variables from a known seed
+        np.random.seed(608072)
+        iw_rvs = invwishart.rvs(df, scale)
+        np.random.seed(608072)
+        frozen_iw_rvs = iw.rvs()
+
+        # Manually calculate what it should be, based on the decomposition in
+        # https://arxiv.org/abs/2310.15884 of an invers-Wishart into L L',
+        # where L A = D, D is the Cholesky factorization of the scale matrix,
+        # and A is the lower triangular matrix with the square root of chi^2
+        # variates on the diagonal and N(0,1) variates in the lower triangle.
+        # the diagonal chi^2 variates in this A are reversed compared to those
+        # in the Bartlett decomposition A for Wishart rvs.
+        np.random.seed(608072)
+        covariances = np.random.normal(size=3)
+        variances = np.r_[
+            np.random.chisquare(df-2),
+            np.random.chisquare(df-1),
+            np.random.chisquare(df),
+        ]**0.5
+
+        # Construct the lower-triangular A matrix
+        A = np.diag(variances)
+        A[np.tril_indices(dim, k=-1)] = covariances
+
+        # inverse-Wishart random variate
+        D = np.linalg.cholesky(scale)
+        L = np.linalg.solve(A.T, D.T).T
+        manual_iw_rvs = np.dot(L, L.T)
+
+        # Test for equality
+        assert_allclose(iw_rvs, manual_iw_rvs)
+        assert_allclose(frozen_iw_rvs, manual_iw_rvs)
+
+    def test_sample_mean(self):
+        """Test that sample mean consistent with known mean."""
+        # Construct an arbitrary positive definite scale matrix
+        df = 10
+        sample_size = 20_000
+        for dim in [1, 5]:
+            scale = np.diag(np.arange(dim) + 1)
+            scale[np.tril_indices(dim, k=-1)] = np.arange(dim * (dim - 1) / 2)
+            scale = np.dot(scale.T, scale)
+
+            dist = invwishart(df, scale)
+            Xmean_exp = dist.mean()
+            Xvar_exp = dist.var()
+            Xmean_std = (Xvar_exp / sample_size)**0.5  # asymptotic SE of mean estimate
+
+            X = dist.rvs(size=sample_size, random_state=1234)
+            Xmean_est = X.mean(axis=0)
+
+            ntests = dim*(dim + 1)//2
+            fail_rate = 0.01 / ntests  # correct for multiple tests
+            max_diff = norm.ppf(1 - fail_rate / 2)
+            assert np.allclose(
+                (Xmean_est - Xmean_exp) / Xmean_std,
+                0,
+                atol=max_diff,
+            )
+
+    def test_logpdf_4x4(self):
+        """Regression test for gh-8844."""
+        X = np.array([[2, 1, 0, 0.5],
+                      [1, 2, 0.5, 0.5],
+                      [0, 0.5, 3, 1],
+                      [0.5, 0.5, 1, 2]])
+        Psi = np.array([[9, 7, 3, 1],
+                        [7, 9, 5, 1],
+                        [3, 5, 8, 2],
+                        [1, 1, 2, 9]])
+        nu = 6
+        prob = invwishart.logpdf(X, nu, Psi)
+        # Explicit calculation from the formula on wikipedia.
+        p = X.shape[0]
+        sig, logdetX = np.linalg.slogdet(X)
+        sig, logdetPsi = np.linalg.slogdet(Psi)
+        M = np.linalg.solve(X, Psi)
+        expected = ((nu/2)*logdetPsi
+                    - (nu*p/2)*np.log(2)
+                    - multigammaln(nu/2, p)
+                    - (nu + p + 1)/2*logdetX
+                    - 0.5*M.trace())
+        assert_allclose(prob, expected)
+
+
+class TestSpecialOrthoGroup:
+    def test_reproducibility(self):
+        np.random.seed(514)
+        x = special_ortho_group.rvs(3)
+        expected = np.array([[-0.99394515, -0.04527879, 0.10011432],
+                             [0.04821555, -0.99846897, 0.02711042],
+                             [0.09873351, 0.03177334, 0.99460653]])
+        assert_array_almost_equal(x, expected)
+
+        random_state = np.random.RandomState(seed=514)
+        x = special_ortho_group.rvs(3, random_state=random_state)
+        assert_array_almost_equal(x, expected)
+
+    def test_invalid_dim(self):
+        assert_raises(ValueError, special_ortho_group.rvs, None)
+        assert_raises(ValueError, special_ortho_group.rvs, (2, 2))
+        assert_raises(ValueError, special_ortho_group.rvs, 1)
+        assert_raises(ValueError, special_ortho_group.rvs, 2.5)
+
+    def test_frozen_matrix(self):
+        dim = 7
+        frozen = special_ortho_group(dim)
+
+        rvs1 = frozen.rvs(random_state=1234)
+        rvs2 = special_ortho_group.rvs(dim, random_state=1234)
+
+        assert_equal(rvs1, rvs2)
+
+    def test_det_and_ortho(self):
+        xs = [special_ortho_group.rvs(dim)
+              for dim in range(2,12)
+              for i in range(3)]
+
+        # Test that determinants are always +1
+        dets = [np.linalg.det(x) for x in xs]
+        assert_allclose(dets, [1.]*30, rtol=1e-13)
+
+        # Test that these are orthogonal matrices
+        for x in xs:
+            assert_array_almost_equal(np.dot(x, x.T),
+                                      np.eye(x.shape[0]))
+
+    def test_haar(self):
+        # Test that the distribution is constant under rotation
+        # Every column should have the same distribution
+        # Additionally, the distribution should be invariant under another rotation
+
+        # Generate samples
+        dim = 5
+        samples = 1000  # Not too many, or the test takes too long
+        ks_prob = .05
+        np.random.seed(514)
+        xs = special_ortho_group.rvs(dim, size=samples)
+
+        # Dot a few rows (0, 1, 2) with unit vectors (0, 2, 4, 3),
+        #   effectively picking off entries in the matrices of xs.
+        #   These projections should all have the same distribution,
+        #     establishing rotational invariance. We use the two-sided
+        #     KS test to confirm this.
+        #   We could instead test that angles between random vectors
+        #     are uniformly distributed, but the below is sufficient.
+        #   It is not feasible to consider all pairs, so pick a few.
+        els = ((0,0), (0,2), (1,4), (2,3))
+        #proj = {(er, ec): [x[er][ec] for x in xs] for er, ec in els}
+        proj = {(er, ec): sorted([x[er][ec] for x in xs]) for er, ec in els}
+        pairs = [(e0, e1) for e0 in els for e1 in els if e0 > e1]
+        ks_tests = [ks_2samp(proj[p0], proj[p1])[1] for (p0, p1) in pairs]
+        assert_array_less([ks_prob]*len(pairs), ks_tests)
+
+
+class TestOrthoGroup:
+    def test_reproducibility(self):
+        seed = 514
+        np.random.seed(seed)
+        x = ortho_group.rvs(3)
+        x2 = ortho_group.rvs(3, random_state=seed)
+        # Note this matrix has det -1, distinguishing O(N) from SO(N)
+        assert_almost_equal(np.linalg.det(x), -1)
+        expected = np.array([[0.381686, -0.090374, 0.919863],
+                             [0.905794, -0.161537, -0.391718],
+                             [-0.183993, -0.98272, -0.020204]])
+        assert_array_almost_equal(x, expected)
+        assert_array_almost_equal(x2, expected)
+
+    def test_invalid_dim(self):
+        assert_raises(ValueError, ortho_group.rvs, None)
+        assert_raises(ValueError, ortho_group.rvs, (2, 2))
+        assert_raises(ValueError, ortho_group.rvs, 1)
+        assert_raises(ValueError, ortho_group.rvs, 2.5)
+
+    def test_frozen_matrix(self):
+        dim = 7
+        frozen = ortho_group(dim)
+        frozen_seed = ortho_group(dim, seed=1234)
+
+        rvs1 = frozen.rvs(random_state=1234)
+        rvs2 = ortho_group.rvs(dim, random_state=1234)
+        rvs3 = frozen_seed.rvs(size=1)
+
+        assert_equal(rvs1, rvs2)
+        assert_equal(rvs1, rvs3)
+
+    def test_det_and_ortho(self):
+        xs = [[ortho_group.rvs(dim)
+               for i in range(10)]
+              for dim in range(2,12)]
+
+        # Test that abs determinants are always +1
+        dets = np.array([[np.linalg.det(x) for x in xx] for xx in xs])
+        assert_allclose(np.fabs(dets), np.ones(dets.shape), rtol=1e-13)
+
+        # Test that these are orthogonal matrices
+        for xx in xs:
+            for x in xx:
+                assert_array_almost_equal(np.dot(x, x.T),
+                                          np.eye(x.shape[0]))
+
+    @pytest.mark.parametrize("dim", [2, 5, 10, 20])
+    def test_det_distribution_gh18272(self, dim):
+        # Test that positive and negative determinants are equally likely.
+        rng = np.random.default_rng(6796248956179332344)
+        dist = ortho_group(dim=dim)
+        rvs = dist.rvs(size=5000, random_state=rng)
+        dets = scipy.linalg.det(rvs)
+        k = np.sum(dets > 0)
+        n = len(dets)
+        res = stats.binomtest(k, n)
+        low, high = res.proportion_ci(confidence_level=0.95)
+        assert low < 0.5 < high
+
+    def test_haar(self):
+        # Test that the distribution is constant under rotation
+        # Every column should have the same distribution
+        # Additionally, the distribution should be invariant under another rotation
+
+        # Generate samples
+        dim = 5
+        samples = 1000  # Not too many, or the test takes too long
+        ks_prob = .05
+        np.random.seed(518)  # Note that the test is sensitive to seed too
+        xs = ortho_group.rvs(dim, size=samples)
+
+        # Dot a few rows (0, 1, 2) with unit vectors (0, 2, 4, 3),
+        #   effectively picking off entries in the matrices of xs.
+        #   These projections should all have the same distribution,
+        #     establishing rotational invariance. We use the two-sided
+        #     KS test to confirm this.
+        #   We could instead test that angles between random vectors
+        #     are uniformly distributed, but the below is sufficient.
+        #   It is not feasible to consider all pairs, so pick a few.
+        els = ((0,0), (0,2), (1,4), (2,3))
+        #proj = {(er, ec): [x[er][ec] for x in xs] for er, ec in els}
+        proj = {(er, ec): sorted([x[er][ec] for x in xs]) for er, ec in els}
+        pairs = [(e0, e1) for e0 in els for e1 in els if e0 > e1]
+        ks_tests = [ks_2samp(proj[p0], proj[p1])[1] for (p0, p1) in pairs]
+        assert_array_less([ks_prob]*len(pairs), ks_tests)
+
+    @pytest.mark.slow
+    def test_pairwise_distances(self):
+        # Test that the distribution of pairwise distances is close to correct.
+        np.random.seed(514)
+
+        def random_ortho(dim):
+            u, _s, v = np.linalg.svd(np.random.normal(size=(dim, dim)))
+            return np.dot(u, v)
+
+        for dim in range(2, 6):
+            def generate_test_statistics(rvs, N=1000, eps=1e-10):
+                stats = np.array([
+                    np.sum((rvs(dim=dim) - rvs(dim=dim))**2)
+                    for _ in range(N)
+                ])
+                # Add a bit of noise to account for numeric accuracy.
+                stats += np.random.uniform(-eps, eps, size=stats.shape)
+                return stats
+
+            expected = generate_test_statistics(random_ortho)
+            actual = generate_test_statistics(scipy.stats.ortho_group.rvs)
+
+            _D, p = scipy.stats.ks_2samp(expected, actual)
+
+            assert_array_less(.05, p)
+
+
+class TestRandomCorrelation:
+    def test_reproducibility(self):
+        np.random.seed(514)
+        eigs = (.5, .8, 1.2, 1.5)
+        x = random_correlation.rvs(eigs)
+        x2 = random_correlation.rvs(eigs, random_state=514)
+        expected = np.array([[1., -0.184851, 0.109017, -0.227494],
+                             [-0.184851, 1., 0.231236, 0.326669],
+                             [0.109017, 0.231236, 1., -0.178912],
+                             [-0.227494, 0.326669, -0.178912, 1.]])
+        assert_array_almost_equal(x, expected)
+        assert_array_almost_equal(x2, expected)
+
+    def test_invalid_eigs(self):
+        assert_raises(ValueError, random_correlation.rvs, None)
+        assert_raises(ValueError, random_correlation.rvs, 'test')
+        assert_raises(ValueError, random_correlation.rvs, 2.5)
+        assert_raises(ValueError, random_correlation.rvs, [2.5])
+        assert_raises(ValueError, random_correlation.rvs, [[1,2],[3,4]])
+        assert_raises(ValueError, random_correlation.rvs, [2.5, -.5])
+        assert_raises(ValueError, random_correlation.rvs, [1, 2, .1])
+
+    def test_frozen_matrix(self):
+        eigs = (.5, .8, 1.2, 1.5)
+        frozen = random_correlation(eigs)
+        frozen_seed = random_correlation(eigs, seed=514)
+
+        rvs1 = random_correlation.rvs(eigs, random_state=514)
+        rvs2 = frozen.rvs(random_state=514)
+        rvs3 = frozen_seed.rvs()
+
+        assert_equal(rvs1, rvs2)
+        assert_equal(rvs1, rvs3)
+
+    def test_definition(self):
+        # Test the definition of a correlation matrix in several dimensions:
+        #
+        # 1. Det is product of eigenvalues (and positive by construction
+        #    in examples)
+        # 2. 1's on diagonal
+        # 3. Matrix is symmetric
+
+        def norm(i, e):
+            return i*e/sum(e)
+
+        np.random.seed(123)
+
+        eigs = [norm(i, np.random.uniform(size=i)) for i in range(2, 6)]
+        eigs.append([4,0,0,0])
+
+        ones = [[1.]*len(e) for e in eigs]
+        xs = [random_correlation.rvs(e) for e in eigs]
+
+        # Test that determinants are products of eigenvalues
+        #   These are positive by construction
+        # Could also test that the eigenvalues themselves are correct,
+        #   but this seems sufficient.
+        dets = [np.fabs(np.linalg.det(x)) for x in xs]
+        dets_known = [np.prod(e) for e in eigs]
+        assert_allclose(dets, dets_known, rtol=1e-13, atol=1e-13)
+
+        # Test for 1's on the diagonal
+        diags = [np.diag(x) for x in xs]
+        for a, b in zip(diags, ones):
+            assert_allclose(a, b, rtol=1e-13)
+
+        # Correlation matrices are symmetric
+        for x in xs:
+            assert_allclose(x, x.T, rtol=1e-13)
+
+    def test_to_corr(self):
+        # Check some corner cases in to_corr
+
+        # ajj == 1
+        m = np.array([[0.1, 0], [0, 1]], dtype=float)
+        m = random_correlation._to_corr(m)
+        assert_allclose(m, np.array([[1, 0], [0, 0.1]]))
+
+        # Floating point overflow; fails to compute the correct
+        # rotation, but should still produce some valid rotation
+        # rather than infs/nans
+        with np.errstate(over='ignore'):
+            g = np.array([[0, 1], [-1, 0]])
+
+            m0 = np.array([[1e300, 0], [0, np.nextafter(1, 0)]], dtype=float)
+            m = random_correlation._to_corr(m0.copy())
+            assert_allclose(m, g.T.dot(m0).dot(g))
+
+            m0 = np.array([[0.9, 1e300], [1e300, 1.1]], dtype=float)
+            m = random_correlation._to_corr(m0.copy())
+            assert_allclose(m, g.T.dot(m0).dot(g))
+
+        # Zero discriminant; should set the first diag entry to 1
+        m0 = np.array([[2, 1], [1, 2]], dtype=float)
+        m = random_correlation._to_corr(m0.copy())
+        assert_allclose(m[0,0], 1)
+
+        # Slightly negative discriminant; should be approx correct still
+        m0 = np.array([[2 + 1e-7, 1], [1, 2]], dtype=float)
+        m = random_correlation._to_corr(m0.copy())
+        assert_allclose(m[0,0], 1)
+
+
+class TestUniformDirection:
+    @pytest.mark.parametrize("dim", [1, 3])
+    @pytest.mark.parametrize("size", [None, 1, 5, (5, 4)])
+    def test_samples(self, dim, size):
+        # test that samples have correct shape and norm 1
+        rng = np.random.default_rng(2777937887058094419)
+        uniform_direction_dist = uniform_direction(dim, seed=rng)
+        samples = uniform_direction_dist.rvs(size)
+        mean, cov = np.zeros(dim), np.eye(dim)
+        expected_shape = rng.multivariate_normal(mean, cov, size=size).shape
+        assert samples.shape == expected_shape
+        norms = np.linalg.norm(samples, axis=-1)
+        assert_allclose(norms, 1.)
+
+    @pytest.mark.parametrize("dim", [None, 0, (2, 2), 2.5])
+    def test_invalid_dim(self, dim):
+        message = ("Dimension of vector must be specified, "
+                   "and must be an integer greater than 0.")
+        with pytest.raises(ValueError, match=message):
+            uniform_direction.rvs(dim)
+
+    def test_frozen_distribution(self):
+        dim = 5
+        frozen = uniform_direction(dim)
+        frozen_seed = uniform_direction(dim, seed=514)
+
+        rvs1 = frozen.rvs(random_state=514)
+        rvs2 = uniform_direction.rvs(dim, random_state=514)
+        rvs3 = frozen_seed.rvs()
+
+        assert_equal(rvs1, rvs2)
+        assert_equal(rvs1, rvs3)
+
+    @pytest.mark.parametrize("dim", [2, 5, 8])
+    def test_uniform(self, dim):
+        rng = np.random.default_rng(1036978481269651776)
+        spherical_dist = uniform_direction(dim, seed=rng)
+        # generate random, orthogonal vectors
+        v1, v2 = spherical_dist.rvs(size=2)
+        v2 -= v1 @ v2 * v1
+        v2 /= np.linalg.norm(v2)
+        assert_allclose(v1 @ v2, 0, atol=1e-14)  # orthogonal
+        # generate data and project onto orthogonal vectors
+        samples = spherical_dist.rvs(size=10000)
+        s1 = samples @ v1
+        s2 = samples @ v2
+        angles = np.arctan2(s1, s2)
+        # test that angles follow a uniform distribution
+        # normalize angles to range [0, 1]
+        angles += np.pi
+        angles /= 2*np.pi
+        # perform KS test
+        uniform_dist = uniform()
+        kstest_result = kstest(angles, uniform_dist.cdf)
+        assert kstest_result.pvalue > 0.05
+
+
+class TestUnitaryGroup:
+    def test_reproducibility(self):
+        np.random.seed(514)
+        x = unitary_group.rvs(3)
+        x2 = unitary_group.rvs(3, random_state=514)
+
+        expected = np.array(
+            [[0.308771+0.360312j, 0.044021+0.622082j, 0.160327+0.600173j],
+             [0.732757+0.297107j, 0.076692-0.4614j, -0.394349+0.022613j],
+             [-0.148844+0.357037j, -0.284602-0.557949j, 0.607051+0.299257j]]
+        )
+
+        assert_array_almost_equal(x, expected)
+        assert_array_almost_equal(x2, expected)
+
+    def test_invalid_dim(self):
+        assert_raises(ValueError, unitary_group.rvs, None)
+        assert_raises(ValueError, unitary_group.rvs, (2, 2))
+        assert_raises(ValueError, unitary_group.rvs, 1)
+        assert_raises(ValueError, unitary_group.rvs, 2.5)
+
+    def test_frozen_matrix(self):
+        dim = 7
+        frozen = unitary_group(dim)
+        frozen_seed = unitary_group(dim, seed=514)
+
+        rvs1 = frozen.rvs(random_state=514)
+        rvs2 = unitary_group.rvs(dim, random_state=514)
+        rvs3 = frozen_seed.rvs(size=1)
+
+        assert_equal(rvs1, rvs2)
+        assert_equal(rvs1, rvs3)
+
+    def test_unitarity(self):
+        xs = [unitary_group.rvs(dim)
+              for dim in range(2,12)
+              for i in range(3)]
+
+        # Test that these are unitary matrices
+        for x in xs:
+            assert_allclose(np.dot(x, x.conj().T), np.eye(x.shape[0]), atol=1e-15)
+
+    def test_haar(self):
+        # Test that the eigenvalues, which lie on the unit circle in
+        # the complex plane, are uncorrelated.
+
+        # Generate samples
+        dim = 5
+        samples = 1000  # Not too many, or the test takes too long
+        np.random.seed(514)  # Note that the test is sensitive to seed too
+        xs = unitary_group.rvs(dim, size=samples)
+
+        # The angles "x" of the eigenvalues should be uniformly distributed
+        # Overall this seems to be a necessary but weak test of the distribution.
+        eigs = np.vstack([scipy.linalg.eigvals(x) for x in xs])
+        x = np.arctan2(eigs.imag, eigs.real)
+        res = kstest(x.ravel(), uniform(-np.pi, 2*np.pi).cdf)
+        assert_(res.pvalue > 0.05)
+
+
+class TestMultivariateT:
+
+    # These tests were created by running vpa(mvtpdf(...)) in MATLAB. The
+    # function takes no `mu` parameter. The tests were run as
+    #
+    # >> ans = vpa(mvtpdf(x - mu, shape, df));
+    #
+    PDF_TESTS = [(
+        # x
+        [
+            [1, 2],
+            [4, 1],
+            [2, 1],
+            [2, 4],
+            [1, 4],
+            [4, 1],
+            [3, 2],
+            [3, 3],
+            [4, 4],
+            [5, 1],
+        ],
+        # loc
+        [0, 0],
+        # shape
+        [
+            [1, 0],
+            [0, 1]
+        ],
+        # df
+        4,
+        # ans
+        [
+            0.013972450422333741737457302178882,
+            0.0010998721906793330026219646100571,
+            0.013972450422333741737457302178882,
+            0.00073682844024025606101402363634634,
+            0.0010998721906793330026219646100571,
+            0.0010998721906793330026219646100571,
+            0.0020732579600816823488240725481546,
+            0.00095660371505271429414668515889275,
+            0.00021831953784896498569831346792114,
+            0.00037725616140301147447000396084604
+        ]
+
+    ), (
+        # x
+        [
+            [0.9718, 0.1298, 0.8134],
+            [0.4922, 0.5522, 0.7185],
+            [0.3010, 0.1491, 0.5008],
+            [0.5971, 0.2585, 0.8940],
+            [0.5434, 0.5287, 0.9507],
+        ],
+        # loc
+        [-1, 1, 50],
+        # shape
+        [
+            [1.0000, 0.5000, 0.2500],
+            [0.5000, 1.0000, -0.1000],
+            [0.2500, -0.1000, 1.0000],
+        ],
+        # df
+        8,
+        # ans
+        [
+            0.00000000000000069609279697467772867405511133763,
+            0.00000000000000073700739052207366474839369535934,
+            0.00000000000000069522909962669171512174435447027,
+            0.00000000000000074212293557998314091880208889767,
+            0.00000000000000077039675154022118593323030449058,
+        ]
+    )]
+
+    @pytest.mark.parametrize("x, loc, shape, df, ans", PDF_TESTS)
+    def test_pdf_correctness(self, x, loc, shape, df, ans):
+        dist = multivariate_t(loc, shape, df, seed=0)
+        val = dist.pdf(x)
+        assert_array_almost_equal(val, ans)
+
+    @pytest.mark.parametrize("x, loc, shape, df, ans", PDF_TESTS)
+    def test_logpdf_correct(self, x, loc, shape, df, ans):
+        dist = multivariate_t(loc, shape, df, seed=0)
+        val1 = dist.pdf(x)
+        val2 = dist.logpdf(x)
+        assert_array_almost_equal(np.log(val1), val2)
+
+    # https://github.com/scipy/scipy/issues/10042#issuecomment-576795195
+    def test_mvt_with_df_one_is_cauchy(self):
+        x = [9, 7, 4, 1, -3, 9, 0, -3, -1, 3]
+        val = multivariate_t.pdf(x, df=1)
+        ans = cauchy.pdf(x)
+        assert_array_almost_equal(val, ans)
+
+    def test_mvt_with_high_df_is_approx_normal(self):
+        # `normaltest` returns the chi-squared statistic and the associated
+        # p-value. The null hypothesis is that `x` came from a normal
+        # distribution, so a low p-value represents rejecting the null, i.e.
+        # that it is unlikely that `x` came a normal distribution.
+        P_VAL_MIN = 0.1
+
+        dist = multivariate_t(0, 1, df=100000, seed=1)
+        samples = dist.rvs(size=100000)
+        _, p = normaltest(samples)
+        assert (p > P_VAL_MIN)
+
+        dist = multivariate_t([-2, 3], [[10, -1], [-1, 10]], df=100000,
+                              seed=42)
+        samples = dist.rvs(size=100000)
+        _, p = normaltest(samples)
+        assert ((p > P_VAL_MIN).all())
+
+    @patch('scipy.stats.multivariate_normal._logpdf')
+    def test_mvt_with_inf_df_calls_normal(self, mock):
+        dist = multivariate_t(0, 1, df=np.inf, seed=7)
+        assert isinstance(dist, multivariate_normal_frozen)
+        multivariate_t.pdf(0, df=np.inf)
+        assert mock.call_count == 1
+        multivariate_t.logpdf(0, df=np.inf)
+        assert mock.call_count == 2
+
+    def test_shape_correctness(self):
+        # pdf and logpdf should return scalar when the
+        # number of samples in x is one.
+        dim = 4
+        loc = np.zeros(dim)
+        shape = np.eye(dim)
+        df = 4.5
+        x = np.zeros(dim)
+        res = multivariate_t(loc, shape, df).pdf(x)
+        assert np.isscalar(res)
+        res = multivariate_t(loc, shape, df).logpdf(x)
+        assert np.isscalar(res)
+
+        # pdf() and logpdf() should return probabilities of shape
+        # (n_samples,) when x has n_samples.
+        n_samples = 7
+        x = np.random.random((n_samples, dim))
+        res = multivariate_t(loc, shape, df).pdf(x)
+        assert (res.shape == (n_samples,))
+        res = multivariate_t(loc, shape, df).logpdf(x)
+        assert (res.shape == (n_samples,))
+
+        # rvs() should return scalar unless a size argument is applied.
+        res = multivariate_t(np.zeros(1), np.eye(1), 1).rvs()
+        assert np.isscalar(res)
+
+        # rvs() should return vector of shape (size,) if size argument
+        # is applied.
+        size = 7
+        res = multivariate_t(np.zeros(1), np.eye(1), 1).rvs(size=size)
+        assert (res.shape == (size,))
+
+    def test_default_arguments(self):
+        dist = multivariate_t()
+        assert_equal(dist.loc, [0])
+        assert_equal(dist.shape, [[1]])
+        assert (dist.df == 1)
+
+    DEFAULT_ARGS_TESTS = [
+        (None, None, None, 0, 1, 1),
+        (None, None, 7, 0, 1, 7),
+        (None, [[7, 0], [0, 7]], None, [0, 0], [[7, 0], [0, 7]], 1),
+        (None, [[7, 0], [0, 7]], 7, [0, 0], [[7, 0], [0, 7]], 7),
+        ([7, 7], None, None, [7, 7], [[1, 0], [0, 1]], 1),
+        ([7, 7], None, 7, [7, 7], [[1, 0], [0, 1]], 7),
+        ([7, 7], [[7, 0], [0, 7]], None, [7, 7], [[7, 0], [0, 7]], 1),
+        ([7, 7], [[7, 0], [0, 7]], 7, [7, 7], [[7, 0], [0, 7]], 7)
+    ]
+
+    @pytest.mark.parametrize("loc, shape, df, loc_ans, shape_ans, df_ans",
+                             DEFAULT_ARGS_TESTS)
+    def test_default_args(self, loc, shape, df, loc_ans, shape_ans, df_ans):
+        dist = multivariate_t(loc=loc, shape=shape, df=df)
+        assert_equal(dist.loc, loc_ans)
+        assert_equal(dist.shape, shape_ans)
+        assert (dist.df == df_ans)
+
+    ARGS_SHAPES_TESTS = [
+        (-1, 2, 3, [-1], [[2]], 3),
+        ([-1], [2], 3, [-1], [[2]], 3),
+        (np.array([-1]), np.array([2]), 3, [-1], [[2]], 3)
+    ]
+
+    @pytest.mark.parametrize("loc, shape, df, loc_ans, shape_ans, df_ans",
+                             ARGS_SHAPES_TESTS)
+    def test_scalar_list_and_ndarray_arguments(self, loc, shape, df, loc_ans,
+                                               shape_ans, df_ans):
+        dist = multivariate_t(loc, shape, df)
+        assert_equal(dist.loc, loc_ans)
+        assert_equal(dist.shape, shape_ans)
+        assert_equal(dist.df, df_ans)
+
+    def test_argument_error_handling(self):
+        # `loc` should be a one-dimensional vector.
+        loc = [[1, 1]]
+        assert_raises(ValueError,
+                      multivariate_t,
+                      **dict(loc=loc))
+
+        # `shape` should be scalar or square matrix.
+        shape = [[1, 1], [2, 2], [3, 3]]
+        assert_raises(ValueError,
+                      multivariate_t,
+                      **dict(loc=loc, shape=shape))
+
+        # `df` should be greater than zero.
+        loc = np.zeros(2)
+        shape = np.eye(2)
+        df = -1
+        assert_raises(ValueError,
+                      multivariate_t,
+                      **dict(loc=loc, shape=shape, df=df))
+        df = 0
+        assert_raises(ValueError,
+                      multivariate_t,
+                      **dict(loc=loc, shape=shape, df=df))
+
+    def test_reproducibility(self):
+        rng = np.random.RandomState(4)
+        loc = rng.uniform(size=3)
+        shape = np.eye(3)
+        dist1 = multivariate_t(loc, shape, df=3, seed=2)
+        dist2 = multivariate_t(loc, shape, df=3, seed=2)
+        samples1 = dist1.rvs(size=10)
+        samples2 = dist2.rvs(size=10)
+        assert_equal(samples1, samples2)
+
+    def test_allow_singular(self):
+        # Make shape singular and verify error was raised.
+        args = dict(loc=[0,0], shape=[[0,0],[0,1]], df=1, allow_singular=False)
+        assert_raises(np.linalg.LinAlgError, multivariate_t, **args)
+
+    @pytest.mark.parametrize("size", [(10, 3), (5, 6, 4, 3)])
+    @pytest.mark.parametrize("dim", [2, 3, 4, 5])
+    @pytest.mark.parametrize("df", [1., 2., np.inf])
+    def test_rvs(self, size, dim, df):
+        dist = multivariate_t(np.zeros(dim), np.eye(dim), df)
+        rvs = dist.rvs(size=size)
+        assert rvs.shape == size + (dim, )
+
+    def test_cdf_signs(self):
+        # check that sign of output is correct when np.any(lower > x)
+        mean = np.zeros(3)
+        cov = np.eye(3)
+        df = 10
+        b = [[1, 1, 1], [0, 0, 0], [1, 0, 1], [0, 1, 0]]
+        a = [[0, 0, 0], [1, 1, 1], [0, 1, 0], [1, 0, 1]]
+        # when odd number of elements of b < a, output is negative
+        expected_signs = np.array([1, -1, -1, 1])
+        cdf = multivariate_normal.cdf(b, mean, cov, df, lower_limit=a)
+        assert_allclose(cdf, cdf[0]*expected_signs)
+
+    @pytest.mark.parametrize('dim', [1, 2, 5])
+    def test_cdf_against_multivariate_normal(self, dim):
+        # Check accuracy against MVN randomly-generated cases
+        self.cdf_against_mvn_test(dim)
+
+    @pytest.mark.parametrize('dim', [3, 6, 9])
+    def test_cdf_against_multivariate_normal_singular(self, dim):
+        # Check accuracy against MVN for randomly-generated singular cases
+        self.cdf_against_mvn_test(3, True)
+
+    def cdf_against_mvn_test(self, dim, singular=False):
+        # Check for accuracy in the limit that df -> oo and MVT -> MVN
+        rng = np.random.default_rng(413722918996573)
+        n = 3
+
+        w = 10**rng.uniform(-2, 1, size=dim)
+        cov = _random_covariance(dim, w, rng, singular)
+
+        mean = 10**rng.uniform(-1, 2, size=dim) * np.sign(rng.normal(size=dim))
+        a = -10**rng.uniform(-1, 2, size=(n, dim)) + mean
+        b = 10**rng.uniform(-1, 2, size=(n, dim)) + mean
+
+        res = stats.multivariate_t.cdf(b, mean, cov, df=10000, lower_limit=a,
+                                       allow_singular=True, random_state=rng)
+        ref = stats.multivariate_normal.cdf(b, mean, cov, allow_singular=True,
+                                            lower_limit=a)
+        assert_allclose(res, ref, atol=5e-4)
+
+    def test_cdf_against_univariate_t(self):
+        rng = np.random.default_rng(413722918996573)
+        cov = 2
+        mean = 0
+        x = rng.normal(size=10, scale=np.sqrt(cov))
+        df = 3
+
+        res = stats.multivariate_t.cdf(x, mean, cov, df, lower_limit=-np.inf,
+                                       random_state=rng)
+        ref = stats.t.cdf(x, df, mean, np.sqrt(cov))
+        incorrect = stats.norm.cdf(x, mean, np.sqrt(cov))
+
+        assert_allclose(res, ref, atol=5e-4)  # close to t
+        assert np.all(np.abs(res - incorrect) > 1e-3)  # not close to normal
+
+    @pytest.mark.parametrize("dim", [2, 3, 5, 10])
+    @pytest.mark.parametrize("seed", [3363958638, 7891119608, 3887698049,
+                                      5013150848, 1495033423, 6170824608])
+    @pytest.mark.parametrize("singular", [False, True])
+    def test_cdf_against_qsimvtv(self, dim, seed, singular):
+        if singular and seed != 3363958638:
+            pytest.skip('Agreement with qsimvtv is not great in singular case')
+        rng = np.random.default_rng(seed)
+        w = 10**rng.uniform(-2, 2, size=dim)
+        cov = _random_covariance(dim, w, rng, singular)
+        mean = rng.random(dim)
+        a = -rng.random(dim)
+        b = rng.random(dim)
+        df = rng.random() * 5
+
+        # no lower limit
+        res = stats.multivariate_t.cdf(b, mean, cov, df, random_state=rng,
+                                       allow_singular=True)
+        with np.errstate(invalid='ignore'):
+            ref = _qsimvtv(20000, df, cov, np.inf*a, b - mean, rng)[0]
+        assert_allclose(res, ref, atol=2e-4, rtol=1e-3)
+
+        # with lower limit
+        res = stats.multivariate_t.cdf(b, mean, cov, df, lower_limit=a,
+                                       random_state=rng, allow_singular=True)
+        with np.errstate(invalid='ignore'):
+            ref = _qsimvtv(20000, df, cov, a - mean, b - mean, rng)[0]
+        assert_allclose(res, ref, atol=1e-4, rtol=1e-3)
+
+    @pytest.mark.slow
+    def test_cdf_against_generic_integrators(self):
+        # Compare result against generic numerical integrators
+        dim = 3
+        rng = np.random.default_rng(41372291899657)
+        w = 10 ** rng.uniform(-1, 1, size=dim)
+        cov = _random_covariance(dim, w, rng, singular=True)
+        mean = rng.random(dim)
+        a = -rng.random(dim)
+        b = rng.random(dim)
+        df = rng.random() * 5
+
+        res = stats.multivariate_t.cdf(b, mean, cov, df, random_state=rng,
+                                       lower_limit=a)
+
+        def integrand(x):
+            return stats.multivariate_t.pdf(x.T, mean, cov, df)
+
+        ref = qmc_quad(integrand, a, b, qrng=stats.qmc.Halton(d=dim, seed=rng))
+        assert_allclose(res, ref.integral, rtol=1e-3)
+
+        def integrand(*zyx):
+            return stats.multivariate_t.pdf(zyx[::-1], mean, cov, df)
+
+        ref = tplquad(integrand, a[0], b[0], a[1], b[1], a[2], b[2])
+        assert_allclose(res, ref[0], rtol=1e-3)
+
+    def test_against_matlab(self):
+        # Test against matlab mvtcdf:
+        # C = [6.21786909  0.2333667 7.95506077;
+        #      0.2333667 29.67390923 16.53946426;
+        #      7.95506077 16.53946426 19.17725252]
+        # df = 1.9559939787727658
+        # mvtcdf([0, 0, 0], C, df)  % 0.2523
+        rng = np.random.default_rng(2967390923)
+        cov = np.array([[ 6.21786909,  0.2333667 ,  7.95506077],
+                        [ 0.2333667 , 29.67390923, 16.53946426],
+                        [ 7.95506077, 16.53946426, 19.17725252]])
+        df = 1.9559939787727658
+        dist = stats.multivariate_t(shape=cov, df=df)
+        res = dist.cdf([0, 0, 0], random_state=rng)
+        ref = 0.2523
+        assert_allclose(res, ref, rtol=1e-3)
+
+    def test_frozen(self):
+        seed = 4137229573
+        rng = np.random.default_rng(seed)
+        loc = rng.uniform(size=3)
+        x = rng.uniform(size=3) + loc
+        shape = np.eye(3)
+        df = rng.random()
+        args = (loc, shape, df)
+
+        rng_frozen = np.random.default_rng(seed)
+        rng_unfrozen = np.random.default_rng(seed)
+        dist = stats.multivariate_t(*args, seed=rng_frozen)
+        assert_equal(dist.cdf(x),
+                     multivariate_t.cdf(x, *args, random_state=rng_unfrozen))
+
+    def test_vectorized(self):
+        dim = 4
+        n = (2, 3)
+        rng = np.random.default_rng(413722918996573)
+        A = rng.random(size=(dim, dim))
+        cov = A @ A.T
+        mean = rng.random(dim)
+        x = rng.random(n + (dim,))
+        df = rng.random() * 5
+
+        res = stats.multivariate_t.cdf(x, mean, cov, df, random_state=rng)
+
+        def _cdf_1d(x):
+            return _qsimvtv(10000, df, cov, -np.inf*x, x-mean, rng)[0]
+
+        ref = np.apply_along_axis(_cdf_1d, -1, x)
+        assert_allclose(res, ref, atol=1e-4, rtol=1e-3)
+
+    @pytest.mark.parametrize("dim", (3, 7))
+    def test_against_analytical(self, dim):
+        rng = np.random.default_rng(413722918996573)
+        A = scipy.linalg.toeplitz(c=[1] + [0.5] * (dim - 1))
+        res = stats.multivariate_t(shape=A).cdf([0] * dim, random_state=rng)
+        ref = 1 / (dim + 1)
+        assert_allclose(res, ref, rtol=5e-5)
+
+    def test_entropy_inf_df(self):
+        cov = np.eye(3, 3)
+        df = np.inf
+        mvt_entropy = stats.multivariate_t.entropy(shape=cov, df=df)
+        mvn_entropy = stats.multivariate_normal.entropy(None, cov)
+        assert mvt_entropy == mvn_entropy
+
+    @pytest.mark.parametrize("df", [1, 10, 100])
+    def test_entropy_1d(self, df):
+        mvt_entropy = stats.multivariate_t.entropy(shape=1., df=df)
+        t_entropy = stats.t.entropy(df=df)
+        assert_allclose(mvt_entropy, t_entropy, rtol=1e-13)
+
+    # entropy reference values were computed via numerical integration
+    #
+    # def integrand(x, y, mvt):
+    #     vec = np.array([x, y])
+    #     return mvt.logpdf(vec) * mvt.pdf(vec)
+
+    # def multivariate_t_entropy_quad_2d(df, cov):
+    #     dim = cov.shape[0]
+    #     loc = np.zeros((dim, ))
+    #     mvt = stats.multivariate_t(loc, cov, df)
+    #     limit = 100
+    #     return -integrate.dblquad(integrand, -limit, limit, -limit, limit,
+    #                               args=(mvt, ))[0]
+
+    @pytest.mark.parametrize("df, cov, ref, tol",
+                             [(10, np.eye(2, 2), 3.0378770664093313, 1e-14),
+                              (100, np.array([[0.5, 1], [1, 10]]),
+                               3.55102424550609, 1e-8)])
+    def test_entropy_vs_numerical_integration(self, df, cov, ref, tol):
+        loc = np.zeros((2, ))
+        mvt = stats.multivariate_t(loc, cov, df)
+        assert_allclose(mvt.entropy(), ref, rtol=tol)
+
+    @pytest.mark.parametrize(
+        "df, dim, ref, tol",
+        [
+            (10, 1, 1.5212624929756808, 1e-15),
+            (100, 1, 1.4289633653182439, 1e-13),
+            (500, 1, 1.420939531869349, 1e-14),
+            (1e20, 1, 1.4189385332046727, 1e-15),
+            (1e100, 1, 1.4189385332046727, 1e-15),
+            (10, 10, 15.069150450832911, 1e-15),
+            (1000, 10, 14.19936546446673, 1e-13),
+            (1e20, 10, 14.189385332046728, 1e-15),
+            (1e100, 10, 14.189385332046728, 1e-15),
+            (10, 100, 148.28902883192654, 1e-15),
+            (1000, 100, 141.99155538003762, 1e-14),
+            (1e20, 100, 141.8938533204673, 1e-15),
+            (1e100, 100, 141.8938533204673, 1e-15),
+        ]
+    )
+    def test_extreme_entropy(self, df, dim, ref, tol):
+        # Reference values were calculated with mpmath:
+        # from mpmath import mp
+        # mp.dps = 500
+        #
+        # def mul_t_mpmath_entropy(dim, df=1):
+        #     dim = mp.mpf(dim)
+        #     df = mp.mpf(df)
+        #     halfsum = (dim + df)/2
+        #     half_df = df/2
+        #
+        #     return float(
+        #         -mp.loggamma(halfsum) + mp.loggamma(half_df)
+        #         + dim / 2 * mp.log(df * mp.pi)
+        #         + halfsum * (mp.digamma(halfsum) - mp.digamma(half_df))
+        #         + 0.0
+        #     )
+        mvt = stats.multivariate_t(shape=np.eye(dim), df=df)
+        assert_allclose(mvt.entropy(), ref, rtol=tol)
+
+    def test_entropy_with_covariance(self):
+        # Generated using np.randn(5, 5) and then rounding
+        # to two decimal places
+        _A = np.array([
+            [1.42, 0.09, -0.49, 0.17, 0.74],
+            [-1.13, -0.01,  0.71, 0.4, -0.56],
+            [1.07, 0.44, -0.28, -0.44, 0.29],
+            [-1.5, -0.94, -0.67, 0.73, -1.1],
+            [0.17, -0.08, 1.46, -0.32, 1.36]
+        ])
+        # Set cov to be a symmetric positive semi-definite matrix
+        cov = _A @ _A.T
+
+        # Test the asymptotic case. For large degrees of freedom
+        # the entropy approaches the multivariate normal entropy.
+        df = 1e20
+        mul_t_entropy = stats.multivariate_t.entropy(shape=cov, df=df)
+        mul_norm_entropy = multivariate_normal(None, cov=cov).entropy()
+        assert_allclose(mul_t_entropy, mul_norm_entropy, rtol=1e-15)
+
+        # Test the regular case. For a dim of 5 the threshold comes out
+        # to be approximately 766.45. So using slightly
+        # different dfs on each site of the threshold, the entropies
+        # are being compared.
+        df1 = 765
+        df2 = 768
+        _entropy1 = stats.multivariate_t.entropy(shape=cov, df=df1)
+        _entropy2 = stats.multivariate_t.entropy(shape=cov, df=df2)
+        assert_allclose(_entropy1, _entropy2, rtol=1e-5)
+
+
+class TestMultivariateHypergeom:
+    @pytest.mark.parametrize(
+        "x, m, n, expected",
+        [
+            # Ground truth value from R dmvhyper
+            ([3, 4], [5, 10], 7, -1.119814),
+            # test for `n=0`
+            ([3, 4], [5, 10], 0, -np.inf),
+            # test for `x < 0`
+            ([-3, 4], [5, 10], 7, -np.inf),
+            # test for `m < 0` (RuntimeWarning issue)
+            ([3, 4], [-5, 10], 7, np.nan),
+            # test for all `m < 0` and `x.sum() != n`
+            ([[1, 2], [3, 4]], [[-4, -6], [-5, -10]],
+             [3, 7], [np.nan, np.nan]),
+            # test for `x < 0` and `m < 0` (RuntimeWarning issue)
+            ([-3, 4], [-5, 10], 1, np.nan),
+            # test for `x > m`
+            ([1, 11], [10, 1], 12, np.nan),
+            # test for `m < 0` (RuntimeWarning issue)
+            ([1, 11], [10, -1], 12, np.nan),
+            # test for `n < 0`
+            ([3, 4], [5, 10], -7, np.nan),
+            # test for `x.sum() != n`
+            ([3, 3], [5, 10], 7, -np.inf)
+        ]
+    )
+    def test_logpmf(self, x, m, n, expected):
+        vals = multivariate_hypergeom.logpmf(x, m, n)
+        assert_allclose(vals, expected, rtol=1e-6)
+
+    def test_reduces_hypergeom(self):
+        # test that the multivariate_hypergeom pmf reduces to the
+        # hypergeom pmf in the 2d case.
+        val1 = multivariate_hypergeom.pmf(x=[3, 1], m=[10, 5], n=4)
+        val2 = hypergeom.pmf(k=3, M=15, n=4, N=10)
+        assert_allclose(val1, val2, rtol=1e-8)
+
+        val1 = multivariate_hypergeom.pmf(x=[7, 3], m=[15, 10], n=10)
+        val2 = hypergeom.pmf(k=7, M=25, n=10, N=15)
+        assert_allclose(val1, val2, rtol=1e-8)
+
+    def test_rvs(self):
+        # test if `rvs` is unbiased and large sample size converges
+        # to the true mean.
+        rv = multivariate_hypergeom(m=[3, 5], n=4)
+        rvs = rv.rvs(size=1000, random_state=123)
+        assert_allclose(rvs.mean(0), rv.mean(), rtol=1e-2)
+
+    def test_rvs_broadcasting(self):
+        rv = multivariate_hypergeom(m=[[3, 5], [5, 10]], n=[4, 9])
+        rvs = rv.rvs(size=(1000, 2), random_state=123)
+        assert_allclose(rvs.mean(0), rv.mean(), rtol=1e-2)
+
+    @pytest.mark.parametrize('m, n', (
+        ([0, 0, 20, 0, 0], 5), ([0, 0, 0, 0, 0], 0),
+        ([0, 0], 0), ([0], 0)
+    ))
+    def test_rvs_gh16171(self, m, n):
+        res = multivariate_hypergeom.rvs(m, n)
+        m = np.asarray(m)
+        res_ex = m.copy()
+        res_ex[m != 0] = n
+        assert_equal(res, res_ex)
+
+    @pytest.mark.parametrize(
+        "x, m, n, expected",
+        [
+            ([5], [5], 5, 1),
+            ([3, 4], [5, 10], 7, 0.3263403),
+            # Ground truth value from R dmvhyper
+            ([[[3, 5], [0, 8]], [[-1, 9], [1, 1]]],
+             [5, 10], [[8, 8], [8, 2]],
+             [[0.3916084, 0.006993007], [0, 0.4761905]]),
+            # test with empty arrays.
+            (np.array([], dtype=int), np.array([], dtype=int), 0, []),
+            ([1, 2], [4, 5], 5, 0),
+            # Ground truth value from R dmvhyper
+            ([3, 3, 0], [5, 6, 7], 6, 0.01077354)
+        ]
+    )
+    def test_pmf(self, x, m, n, expected):
+        vals = multivariate_hypergeom.pmf(x, m, n)
+        assert_allclose(vals, expected, rtol=1e-7)
+
+    @pytest.mark.parametrize(
+        "x, m, n, expected",
+        [
+            ([3, 4], [[5, 10], [10, 15]], 7, [0.3263403, 0.3407531]),
+            ([[1], [2]], [[3], [4]], [1, 3], [1., 0.]),
+            ([[[1], [2]]], [[3], [4]], [1, 3], [[1., 0.]]),
+            ([[1], [2]], [[[[3]]]], [1, 3], [[[1., 0.]]])
+        ]
+    )
+    def test_pmf_broadcasting(self, x, m, n, expected):
+        vals = multivariate_hypergeom.pmf(x, m, n)
+        assert_allclose(vals, expected, rtol=1e-7)
+
+    def test_cov(self):
+        cov1 = multivariate_hypergeom.cov(m=[3, 7, 10], n=12)
+        cov2 = [[0.64421053, -0.26526316, -0.37894737],
+                [-0.26526316, 1.14947368, -0.88421053],
+                [-0.37894737, -0.88421053, 1.26315789]]
+        assert_allclose(cov1, cov2, rtol=1e-8)
+
+    def test_cov_broadcasting(self):
+        cov1 = multivariate_hypergeom.cov(m=[[7, 9], [10, 15]], n=[8, 12])
+        cov2 = [[[1.05, -1.05], [-1.05, 1.05]],
+                [[1.56, -1.56], [-1.56, 1.56]]]
+        assert_allclose(cov1, cov2, rtol=1e-8)
+
+        cov3 = multivariate_hypergeom.cov(m=[[4], [5]], n=[4, 5])
+        cov4 = [[[0.]], [[0.]]]
+        assert_allclose(cov3, cov4, rtol=1e-8)
+
+        cov5 = multivariate_hypergeom.cov(m=[7, 9], n=[8, 12])
+        cov6 = [[[1.05, -1.05], [-1.05, 1.05]],
+                [[0.7875, -0.7875], [-0.7875, 0.7875]]]
+        assert_allclose(cov5, cov6, rtol=1e-8)
+
+    def test_var(self):
+        # test with hypergeom
+        var0 = multivariate_hypergeom.var(m=[10, 5], n=4)
+        var1 = hypergeom.var(M=15, n=4, N=10)
+        assert_allclose(var0, var1, rtol=1e-8)
+
+    def test_var_broadcasting(self):
+        var0 = multivariate_hypergeom.var(m=[10, 5], n=[4, 8])
+        var1 = multivariate_hypergeom.var(m=[10, 5], n=4)
+        var2 = multivariate_hypergeom.var(m=[10, 5], n=8)
+        assert_allclose(var0[0], var1, rtol=1e-8)
+        assert_allclose(var0[1], var2, rtol=1e-8)
+
+        var3 = multivariate_hypergeom.var(m=[[10, 5], [10, 14]], n=[4, 8])
+        var4 = [[0.6984127, 0.6984127], [1.352657, 1.352657]]
+        assert_allclose(var3, var4, rtol=1e-8)
+
+        var5 = multivariate_hypergeom.var(m=[[5], [10]], n=[5, 10])
+        var6 = [[0.], [0.]]
+        assert_allclose(var5, var6, rtol=1e-8)
+
+    def test_mean(self):
+        # test with hypergeom
+        mean0 = multivariate_hypergeom.mean(m=[10, 5], n=4)
+        mean1 = hypergeom.mean(M=15, n=4, N=10)
+        assert_allclose(mean0[0], mean1, rtol=1e-8)
+
+        mean2 = multivariate_hypergeom.mean(m=[12, 8], n=10)
+        mean3 = [12.*10./20., 8.*10./20.]
+        assert_allclose(mean2, mean3, rtol=1e-8)
+
+    def test_mean_broadcasting(self):
+        mean0 = multivariate_hypergeom.mean(m=[[3, 5], [10, 5]], n=[4, 8])
+        mean1 = [[3.*4./8., 5.*4./8.], [10.*8./15., 5.*8./15.]]
+        assert_allclose(mean0, mean1, rtol=1e-8)
+
+    def test_mean_edge_cases(self):
+        mean0 = multivariate_hypergeom.mean(m=[0, 0, 0], n=0)
+        assert_equal(mean0, [0., 0., 0.])
+
+        mean1 = multivariate_hypergeom.mean(m=[1, 0, 0], n=2)
+        assert_equal(mean1, [np.nan, np.nan, np.nan])
+
+        mean2 = multivariate_hypergeom.mean(m=[[1, 0, 0], [1, 0, 1]], n=2)
+        assert_allclose(mean2, [[np.nan, np.nan, np.nan], [1., 0., 1.]],
+                        rtol=1e-17)
+
+        mean3 = multivariate_hypergeom.mean(m=np.array([], dtype=int), n=0)
+        assert_equal(mean3, [])
+        assert_(mean3.shape == (0, ))
+
+    def test_var_edge_cases(self):
+        var0 = multivariate_hypergeom.var(m=[0, 0, 0], n=0)
+        assert_allclose(var0, [0., 0., 0.], rtol=1e-16)
+
+        var1 = multivariate_hypergeom.var(m=[1, 0, 0], n=2)
+        assert_equal(var1, [np.nan, np.nan, np.nan])
+
+        var2 = multivariate_hypergeom.var(m=[[1, 0, 0], [1, 0, 1]], n=2)
+        assert_allclose(var2, [[np.nan, np.nan, np.nan], [0., 0., 0.]],
+                        rtol=1e-17)
+
+        var3 = multivariate_hypergeom.var(m=np.array([], dtype=int), n=0)
+        assert_equal(var3, [])
+        assert_(var3.shape == (0, ))
+
+    def test_cov_edge_cases(self):
+        cov0 = multivariate_hypergeom.cov(m=[1, 0, 0], n=1)
+        cov1 = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
+        assert_allclose(cov0, cov1, rtol=1e-17)
+
+        cov3 = multivariate_hypergeom.cov(m=[0, 0, 0], n=0)
+        cov4 = [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
+        assert_equal(cov3, cov4)
+
+        cov5 = multivariate_hypergeom.cov(m=np.array([], dtype=int), n=0)
+        cov6 = np.array([], dtype=np.float64).reshape(0, 0)
+        assert_allclose(cov5, cov6, rtol=1e-17)
+        assert_(cov5.shape == (0, 0))
+
+    def test_frozen(self):
+        # The frozen distribution should agree with the regular one
+        np.random.seed(1234)
+        n = 12
+        m = [7, 9, 11, 13]
+        x = [[0, 0, 0, 12], [0, 0, 1, 11], [0, 1, 1, 10],
+             [1, 1, 1, 9], [1, 1, 2, 8]]
+        x = np.asarray(x, dtype=int)
+        mhg_frozen = multivariate_hypergeom(m, n)
+        assert_allclose(mhg_frozen.pmf(x),
+                        multivariate_hypergeom.pmf(x, m, n))
+        assert_allclose(mhg_frozen.logpmf(x),
+                        multivariate_hypergeom.logpmf(x, m, n))
+        assert_allclose(mhg_frozen.var(), multivariate_hypergeom.var(m, n))
+        assert_allclose(mhg_frozen.cov(), multivariate_hypergeom.cov(m, n))
+
+    def test_invalid_params(self):
+        assert_raises(ValueError, multivariate_hypergeom.pmf, 5, 10, 5)
+        assert_raises(ValueError, multivariate_hypergeom.pmf, 5, [10], 5)
+        assert_raises(ValueError, multivariate_hypergeom.pmf, [5, 4], [10], 5)
+        assert_raises(TypeError, multivariate_hypergeom.pmf, [5.5, 4.5],
+                      [10, 15], 5)
+        assert_raises(TypeError, multivariate_hypergeom.pmf, [5, 4],
+                      [10.5, 15.5], 5)
+        assert_raises(TypeError, multivariate_hypergeom.pmf, [5, 4],
+                      [10, 15], 5.5)
+
+
+class TestRandomTable:
+    def get_rng(self):
+        return np.random.default_rng(628174795866951638)
+
+    def test_process_parameters(self):
+        message = "`row` must be one-dimensional"
+        with pytest.raises(ValueError, match=message):
+            random_table([[1, 2]], [1, 2])
+
+        message = "`col` must be one-dimensional"
+        with pytest.raises(ValueError, match=message):
+            random_table([1, 2], [[1, 2]])
+
+        message = "each element of `row` must be non-negative"
+        with pytest.raises(ValueError, match=message):
+            random_table([1, -1], [1, 2])
+
+        message = "each element of `col` must be non-negative"
+        with pytest.raises(ValueError, match=message):
+            random_table([1, 2], [1, -2])
+
+        message = "sums over `row` and `col` must be equal"
+        with pytest.raises(ValueError, match=message):
+            random_table([1, 2], [1, 0])
+
+        message = "each element of `row` must be an integer"
+        with pytest.raises(ValueError, match=message):
+            random_table([2.1, 2.1], [1, 1, 2])
+
+        message = "each element of `col` must be an integer"
+        with pytest.raises(ValueError, match=message):
+            random_table([1, 2], [1.1, 1.1, 1])
+
+        row = [1, 3]
+        col = [2, 1, 1]
+        r, c, n = random_table._process_parameters([1, 3], [2, 1, 1])
+        assert_equal(row, r)
+        assert_equal(col, c)
+        assert n == np.sum(row)
+
+    @pytest.mark.parametrize("scale,method",
+                             ((1, "boyett"), (100, "patefield")))
+    def test_process_rvs_method_on_None(self, scale, method):
+        row = np.array([1, 3]) * scale
+        col = np.array([2, 1, 1]) * scale
+
+        ct = random_table
+        expected = ct.rvs(row, col, method=method, random_state=1)
+        got = ct.rvs(row, col, method=None, random_state=1)
+
+        assert_equal(expected, got)
+
+    def test_process_rvs_method_bad_argument(self):
+        row = [1, 3]
+        col = [2, 1, 1]
+
+        # order of items in set is random, so cannot check that
+        message = "'foo' not recognized, must be one of"
+        with pytest.raises(ValueError, match=message):
+            random_table.rvs(row, col, method="foo")
+
+    @pytest.mark.parametrize('frozen', (True, False))
+    @pytest.mark.parametrize('log', (True, False))
+    def test_pmf_logpmf(self, frozen, log):
+        # The pmf is tested through random sample generation
+        # with Boyett's algorithm, whose implementation is simple
+        # enough to verify manually for correctness.
+        rng = self.get_rng()
+        row = [2, 6]
+        col = [1, 3, 4]
+        rvs = random_table.rvs(row, col, size=1000,
+                               method="boyett", random_state=rng)
+
+        obj = random_table(row, col) if frozen else random_table
+        method = getattr(obj, "logpmf" if log else "pmf")
+        if not frozen:
+            original_method = method
+
+            def method(x):
+                return original_method(x, row, col)
+        pmf = (lambda x: np.exp(method(x))) if log else method
+
+        unique_rvs, counts = np.unique(rvs, axis=0, return_counts=True)
+
+        # rough accuracy check
+        p = pmf(unique_rvs)
+        assert_allclose(p * len(rvs), counts, rtol=0.1)
+
+        # accept any iterable
+        p2 = pmf(list(unique_rvs[0]))
+        assert_equal(p2, p[0])
+
+        # accept high-dimensional input and 2d input
+        rvs_nd = rvs.reshape((10, 100) + rvs.shape[1:])
+        p = pmf(rvs_nd)
+        assert p.shape == (10, 100)
+        for i in range(p.shape[0]):
+            for j in range(p.shape[1]):
+                pij = p[i, j]
+                rvij = rvs_nd[i, j]
+                qij = pmf(rvij)
+                assert_equal(pij, qij)
+
+        # probability is zero if column marginal does not match
+        x = [[0, 1, 1], [2, 1, 3]]
+        assert_equal(np.sum(x, axis=-1), row)
+        p = pmf(x)
+        assert p == 0
+
+        # probability is zero if row marginal does not match
+        x = [[0, 1, 2], [1, 2, 2]]
+        assert_equal(np.sum(x, axis=-2), col)
+        p = pmf(x)
+        assert p == 0
+
+        # response to invalid inputs
+        message = "`x` must be at least two-dimensional"
+        with pytest.raises(ValueError, match=message):
+            pmf([1])
+
+        message = "`x` must contain only integral values"
+        with pytest.raises(ValueError, match=message):
+            pmf([[1.1]])
+
+        message = "`x` must contain only integral values"
+        with pytest.raises(ValueError, match=message):
+            pmf([[np.nan]])
+
+        message = "`x` must contain only non-negative values"
+        with pytest.raises(ValueError, match=message):
+            pmf([[-1]])
+
+        message = "shape of `x` must agree with `row`"
+        with pytest.raises(ValueError, match=message):
+            pmf([[1, 2, 3]])
+
+        message = "shape of `x` must agree with `col`"
+        with pytest.raises(ValueError, match=message):
+            pmf([[1, 2],
+                 [3, 4]])
+
+    @pytest.mark.parametrize("method", ("boyett", "patefield"))
+    def test_rvs_mean(self, method):
+        # test if `rvs` is unbiased and large sample size converges
+        # to the true mean.
+        rng = self.get_rng()
+        row = [2, 6]
+        col = [1, 3, 4]
+        rvs = random_table.rvs(row, col, size=1000, method=method,
+                               random_state=rng)
+        mean = random_table.mean(row, col)
+        assert_equal(np.sum(mean), np.sum(row))
+        assert_allclose(rvs.mean(0), mean, atol=0.05)
+        assert_equal(rvs.sum(axis=-1), np.broadcast_to(row, (1000, 2)))
+        assert_equal(rvs.sum(axis=-2), np.broadcast_to(col, (1000, 3)))
+
+    def test_rvs_cov(self):
+        # test if `rvs` generated with patefield and boyett algorithms
+        # produce approximately the same covariance matrix
+        rng = self.get_rng()
+        row = [2, 6]
+        col = [1, 3, 4]
+        rvs1 = random_table.rvs(row, col, size=10000, method="boyett",
+                                random_state=rng)
+        rvs2 = random_table.rvs(row, col, size=10000, method="patefield",
+                                random_state=rng)
+        cov1 = np.var(rvs1, axis=0)
+        cov2 = np.var(rvs2, axis=0)
+        assert_allclose(cov1, cov2, atol=0.02)
+
+    @pytest.mark.parametrize("method", ("boyett", "patefield"))
+    def test_rvs_size(self, method):
+        row = [2, 6]
+        col = [1, 3, 4]
+
+        # test size `None`
+        rv = random_table.rvs(row, col, method=method,
+                              random_state=self.get_rng())
+        assert rv.shape == (2, 3)
+
+        # test size 1
+        rv2 = random_table.rvs(row, col, size=1, method=method,
+                               random_state=self.get_rng())
+        assert rv2.shape == (1, 2, 3)
+        assert_equal(rv, rv2[0])
+
+        # test size 0
+        rv3 = random_table.rvs(row, col, size=0, method=method,
+                               random_state=self.get_rng())
+        assert rv3.shape == (0, 2, 3)
+
+        # test other valid size
+        rv4 = random_table.rvs(row, col, size=20, method=method,
+                               random_state=self.get_rng())
+        assert rv4.shape == (20, 2, 3)
+
+        rv5 = random_table.rvs(row, col, size=(4, 5), method=method,
+                               random_state=self.get_rng())
+        assert rv5.shape == (4, 5, 2, 3)
+
+        assert_allclose(rv5.reshape(20, 2, 3), rv4, rtol=1e-15)
+
+        # test invalid size
+        message = "`size` must be a non-negative integer or `None`"
+        with pytest.raises(ValueError, match=message):
+            random_table.rvs(row, col, size=-1, method=method,
+                             random_state=self.get_rng())
+
+        with pytest.raises(ValueError, match=message):
+            random_table.rvs(row, col, size=np.nan, method=method,
+                             random_state=self.get_rng())
+
+    @pytest.mark.parametrize("method", ("boyett", "patefield"))
+    def test_rvs_method(self, method):
+        # This test assumes that pmf is correct and checks that random samples
+        # follow this probability distribution. This seems like a circular
+        # argument, since pmf is checked in test_pmf_logpmf with random samples
+        # generated with the rvs method. This test is not redundant, because
+        # test_pmf_logpmf intentionally uses rvs generation with Boyett only,
+        # but here we test both Boyett and Patefield.
+        row = [2, 6]
+        col = [1, 3, 4]
+
+        ct = random_table
+        rvs = ct.rvs(row, col, size=100000, method=method,
+                     random_state=self.get_rng())
+
+        unique_rvs, counts = np.unique(rvs, axis=0, return_counts=True)
+
+        # generated frequencies should match expected frequencies
+        p = ct.pmf(unique_rvs, row, col)
+        assert_allclose(p * len(rvs), counts, rtol=0.02)
+
+    @pytest.mark.parametrize("method", ("boyett", "patefield"))
+    def test_rvs_with_zeros_in_col_row(self, method):
+        row = [0, 1, 0]
+        col = [1, 0, 0, 0]
+        d = random_table(row, col)
+        rv = d.rvs(1000, method=method, random_state=self.get_rng())
+        expected = np.zeros((1000, len(row), len(col)))
+        expected[...] = [[0, 0, 0, 0],
+                         [1, 0, 0, 0],
+                         [0, 0, 0, 0]]
+        assert_equal(rv, expected)
+
+    @pytest.mark.parametrize("method", (None, "boyett", "patefield"))
+    @pytest.mark.parametrize("col", ([], [0]))
+    @pytest.mark.parametrize("row", ([], [0]))
+    def test_rvs_with_edge_cases(self, method, row, col):
+        d = random_table(row, col)
+        rv = d.rvs(10, method=method, random_state=self.get_rng())
+        expected = np.zeros((10, len(row), len(col)))
+        assert_equal(rv, expected)
+
+    @pytest.mark.parametrize('v', (1, 2))
+    def test_rvs_rcont(self, v):
+        # This test checks the internal low-level interface.
+        # It is implicitly also checked by the other test_rvs* calls.
+        import scipy.stats._rcont as _rcont
+
+        row = np.array([1, 3], dtype=np.int64)
+        col = np.array([2, 1, 1], dtype=np.int64)
+
+        rvs = getattr(_rcont, f"rvs_rcont{v}")
+
+        ntot = np.sum(row)
+        result = rvs(row, col, ntot, 1, self.get_rng())
+
+        assert result.shape == (1, len(row), len(col))
+        assert np.sum(result) == ntot
+
+    def test_frozen(self):
+        row = [2, 6]
+        col = [1, 3, 4]
+        d = random_table(row, col, seed=self.get_rng())
+
+        sample = d.rvs()
+
+        expected = random_table.mean(row, col)
+        assert_equal(expected, d.mean())
+
+        expected = random_table.pmf(sample, row, col)
+        assert_equal(expected, d.pmf(sample))
+
+        expected = random_table.logpmf(sample, row, col)
+        assert_equal(expected, d.logpmf(sample))
+
+    @pytest.mark.parametrize("method", ("boyett", "patefield"))
+    def test_rvs_frozen(self, method):
+        row = [2, 6]
+        col = [1, 3, 4]
+        d = random_table(row, col, seed=self.get_rng())
+
+        expected = random_table.rvs(row, col, size=10, method=method,
+                                    random_state=self.get_rng())
+        got = d.rvs(size=10, method=method)
+        assert_equal(expected, got)
+
+
+def check_pickling(distfn, args):
+    # check that a distribution instance pickles and unpickles
+    # pay special attention to the random_state property
+
+    # save the random_state (restore later)
+    rndm = distfn.random_state
+
+    distfn.random_state = 1234
+    distfn.rvs(*args, size=8)
+    s = pickle.dumps(distfn)
+    r0 = distfn.rvs(*args, size=8)
+
+    unpickled = pickle.loads(s)
+    r1 = unpickled.rvs(*args, size=8)
+    assert_equal(r0, r1)
+
+    # restore the random_state
+    distfn.random_state = rndm
+
+
+def test_random_state_property():
+    scale = np.eye(3)
+    scale[0, 1] = 0.5
+    scale[1, 0] = 0.5
+    dists = [
+        [multivariate_normal, ()],
+        [dirichlet, (np.array([1.]), )],
+        [wishart, (10, scale)],
+        [invwishart, (10, scale)],
+        [multinomial, (5, [0.5, 0.4, 0.1])],
+        [ortho_group, (2,)],
+        [special_ortho_group, (2,)]
+    ]
+    for distfn, args in dists:
+        check_random_state_property(distfn, args)
+        check_pickling(distfn, args)
+
+
+class TestVonMises_Fisher:
+    @pytest.mark.parametrize("dim", [2, 3, 4, 6])
+    @pytest.mark.parametrize("size", [None, 1, 5, (5, 4)])
+    def test_samples(self, dim, size):
+        # test that samples have correct shape and norm 1
+        rng = np.random.default_rng(2777937887058094419)
+        mu = np.full((dim, ), 1/np.sqrt(dim))
+        vmf_dist = vonmises_fisher(mu, 1, seed=rng)
+        samples = vmf_dist.rvs(size)
+        mean, cov = np.zeros(dim), np.eye(dim)
+        expected_shape = rng.multivariate_normal(mean, cov, size=size).shape
+        assert samples.shape == expected_shape
+        norms = np.linalg.norm(samples, axis=-1)
+        assert_allclose(norms, 1.)
+
+    @pytest.mark.parametrize("dim", [5, 8])
+    @pytest.mark.parametrize("kappa", [1e15, 1e20, 1e30])
+    def test_sampling_high_concentration(self, dim, kappa):
+        # test that no warnings are encountered for high values
+        rng = np.random.default_rng(2777937887058094419)
+        mu = np.full((dim, ), 1/np.sqrt(dim))
+        vmf_dist = vonmises_fisher(mu, kappa, seed=rng)
+        vmf_dist.rvs(10)
+
+    def test_two_dimensional_mu(self):
+        mu = np.ones((2, 2))
+        msg = "'mu' must have one-dimensional shape."
+        with pytest.raises(ValueError, match=msg):
+            vonmises_fisher(mu, 1)
+
+    def test_wrong_norm_mu(self):
+        mu = np.ones((2, ))
+        msg = "'mu' must be a unit vector of norm 1."
+        with pytest.raises(ValueError, match=msg):
+            vonmises_fisher(mu, 1)
+
+    def test_one_entry_mu(self):
+        mu = np.ones((1, ))
+        msg = "'mu' must have at least two entries."
+        with pytest.raises(ValueError, match=msg):
+            vonmises_fisher(mu, 1)
+
+    @pytest.mark.parametrize("kappa", [-1, (5, 3)])
+    def test_kappa_validation(self, kappa):
+        msg = "'kappa' must be a positive scalar."
+        with pytest.raises(ValueError, match=msg):
+            vonmises_fisher([1, 0], kappa)
+
+    @pytest.mark.parametrize("kappa", [0, 0.])
+    def test_kappa_zero(self, kappa):
+        msg = ("For 'kappa=0' the von Mises-Fisher distribution "
+               "becomes the uniform distribution on the sphere "
+               "surface. Consider using 'scipy.stats.uniform_direction' "
+               "instead.")
+        with pytest.raises(ValueError, match=msg):
+            vonmises_fisher([1, 0], kappa)
+
+
+    @pytest.mark.parametrize("method", [vonmises_fisher.pdf,
+                                        vonmises_fisher.logpdf])
+    def test_invalid_shapes_pdf_logpdf(self, method):
+        x = np.array([1., 0., 0])
+        msg = ("The dimensionality of the last axis of 'x' must "
+               "match the dimensionality of the von Mises Fisher "
+               "distribution.")
+        with pytest.raises(ValueError, match=msg):
+            method(x, [1, 0], 1)
+
+    @pytest.mark.parametrize("method", [vonmises_fisher.pdf,
+                                        vonmises_fisher.logpdf])
+    def test_unnormalized_input(self, method):
+        x = np.array([0.5, 0.])
+        msg = "'x' must be unit vectors of norm 1 along last dimension."
+        with pytest.raises(ValueError, match=msg):
+            method(x, [1, 0], 1)
+
+    # Expected values of the vonmises-fisher logPDF were computed via mpmath
+    # from mpmath import mp
+    # import numpy as np
+    # mp.dps = 50
+    # def logpdf_mpmath(x, mu, kappa):
+    #     dim = mu.size
+    #     halfdim = mp.mpf(0.5 * dim)
+    #     kappa = mp.mpf(kappa)
+    #     const = (kappa**(halfdim - mp.one)/((2*mp.pi)**halfdim * \
+    #              mp.besseli(halfdim -mp.one, kappa)))
+    #     return float(const * mp.exp(kappa*mp.fdot(x, mu)))
+
+    @pytest.mark.parametrize('x, mu, kappa, reference',
+                             [(np.array([1., 0., 0.]), np.array([1., 0., 0.]),
+                               1e-4, 0.0795854295583605),
+                              (np.array([1., 0., 0]), np.array([0., 0., 1.]),
+                               1e-4, 0.07957747141331854),
+                              (np.array([1., 0., 0.]), np.array([1., 0., 0.]),
+                               100, 15.915494309189533),
+                              (np.array([1., 0., 0]), np.array([0., 0., 1.]),
+                               100, 5.920684802611232e-43),
+                              (np.array([1., 0., 0.]),
+                               np.array([np.sqrt(0.98), np.sqrt(0.02), 0.]),
+                               2000, 5.930499050746588e-07),
+                              (np.array([1., 0., 0]), np.array([1., 0., 0.]),
+                               2000, 318.3098861837907),
+                              (np.array([1., 0., 0., 0., 0.]),
+                               np.array([1., 0., 0., 0., 0.]),
+                               2000, 101371.86957712633),
+                              (np.array([1., 0., 0., 0., 0.]),
+                               np.array([np.sqrt(0.98), np.sqrt(0.02), 0.,
+                                         0, 0.]),
+                               2000, 0.00018886808182653578),
+                              (np.array([1., 0., 0., 0., 0.]),
+                               np.array([np.sqrt(0.8), np.sqrt(0.2), 0.,
+                                         0, 0.]),
+                               2000, 2.0255393314603194e-87)])
+    def test_pdf_accuracy(self, x, mu, kappa, reference):
+        pdf = vonmises_fisher(mu, kappa).pdf(x)
+        assert_allclose(pdf, reference, rtol=1e-13)
+
+    # Expected values of the vonmises-fisher logPDF were computed via mpmath
+    # from mpmath import mp
+    # import numpy as np
+    # mp.dps = 50
+    # def logpdf_mpmath(x, mu, kappa):
+    #     dim = mu.size
+    #     halfdim = mp.mpf(0.5 * dim)
+    #     kappa = mp.mpf(kappa)
+    #     two = mp.mpf(2.)
+    #     const = (kappa**(halfdim - mp.one)/((two*mp.pi)**halfdim * \
+    #              mp.besseli(halfdim - mp.one, kappa)))
+    #     return float(mp.log(const * mp.exp(kappa*mp.fdot(x, mu))))
+
+    @pytest.mark.parametrize('x, mu, kappa, reference',
+                             [(np.array([1., 0., 0.]), np.array([1., 0., 0.]),
+                               1e-4, -2.5309242486359573),
+                              (np.array([1., 0., 0]), np.array([0., 0., 1.]),
+                               1e-4, -2.5310242486359575),
+                              (np.array([1., 0., 0.]), np.array([1., 0., 0.]),
+                               100, 2.767293119578746),
+                              (np.array([1., 0., 0]), np.array([0., 0., 1.]),
+                               100, -97.23270688042125),
+                              (np.array([1., 0., 0.]),
+                               np.array([np.sqrt(0.98), np.sqrt(0.02), 0.]),
+                               2000, -14.337987284534103),
+                              (np.array([1., 0., 0]), np.array([1., 0., 0.]),
+                               2000, 5.763025393132737),
+                              (np.array([1., 0., 0., 0., 0.]),
+                               np.array([1., 0., 0., 0., 0.]),
+                               2000, 11.526550911307156),
+                              (np.array([1., 0., 0., 0., 0.]),
+                               np.array([np.sqrt(0.98), np.sqrt(0.02), 0.,
+                                         0, 0.]),
+                               2000, -8.574461766359684),
+                              (np.array([1., 0., 0., 0., 0.]),
+                               np.array([np.sqrt(0.8), np.sqrt(0.2), 0.,
+                                         0, 0.]),
+                               2000, -199.61906708886113)])
+    def test_logpdf_accuracy(self, x, mu, kappa, reference):
+        logpdf = vonmises_fisher(mu, kappa).logpdf(x)
+        assert_allclose(logpdf, reference, rtol=1e-14)
+
+    # Expected values of the vonmises-fisher entropy were computed via mpmath
+    # from mpmath import mp
+    # import numpy as np
+    # mp.dps = 50
+    # def entropy_mpmath(dim, kappa):
+    #     mu = np.full((dim, ), 1/np.sqrt(dim))
+    #     kappa = mp.mpf(kappa)
+    #     halfdim = mp.mpf(0.5 * dim)
+    #     logconstant = (mp.log(kappa**(halfdim - mp.one)
+    #                    /((2*mp.pi)**halfdim
+    #                    * mp.besseli(halfdim -mp.one, kappa)))
+    #     return float(-logconstant - kappa * mp.besseli(halfdim, kappa)/
+    #             mp.besseli(halfdim -1, kappa))
+
+    @pytest.mark.parametrize('dim, kappa, reference',
+                             [(3, 1e-4, 2.531024245302624),
+                              (3, 100, -1.7672931195787458),
+                              (5, 5000, -11.359032310024453),
+                              (8, 1, 3.4189526482545527)])
+    def test_entropy_accuracy(self, dim, kappa, reference):
+        mu = np.full((dim, ), 1/np.sqrt(dim))
+        entropy = vonmises_fisher(mu, kappa).entropy()
+        assert_allclose(entropy, reference, rtol=2e-14)
+
+    @pytest.mark.parametrize("method", [vonmises_fisher.pdf,
+                                        vonmises_fisher.logpdf])
+    def test_broadcasting(self, method):
+        # test that pdf and logpdf values are correctly broadcasted
+        testshape = (2, 2)
+        rng = np.random.default_rng(2777937887058094419)
+        x = uniform_direction(3).rvs(testshape, random_state=rng)
+        mu = np.full((3, ), 1/np.sqrt(3))
+        kappa = 5
+        result_all = method(x, mu, kappa)
+        assert result_all.shape == testshape
+        for i in range(testshape[0]):
+            for j in range(testshape[1]):
+                current_val = method(x[i, j, :], mu, kappa)
+                assert_allclose(current_val, result_all[i, j], rtol=1e-15)
+
+    def test_vs_vonmises_2d(self):
+        # test that in 2D, von Mises-Fisher yields the same results
+        # as the von Mises distribution
+        rng = np.random.default_rng(2777937887058094419)
+        mu = np.array([0, 1])
+        mu_angle = np.arctan2(mu[1], mu[0])
+        kappa = 20
+        vmf = vonmises_fisher(mu, kappa)
+        vonmises_dist = vonmises(loc=mu_angle, kappa=kappa)
+        vectors = uniform_direction(2).rvs(10, random_state=rng)
+        angles = np.arctan2(vectors[:, 1], vectors[:, 0])
+        assert_allclose(vonmises_dist.entropy(), vmf.entropy())
+        assert_allclose(vonmises_dist.pdf(angles), vmf.pdf(vectors))
+        assert_allclose(vonmises_dist.logpdf(angles), vmf.logpdf(vectors))
+
+    @pytest.mark.parametrize("dim", [2, 3, 6])
+    @pytest.mark.parametrize("kappa, mu_tol, kappa_tol",
+                             [(1, 5e-2, 5e-2),
+                              (10, 1e-2, 1e-2),
+                              (100, 5e-3, 2e-2),
+                              (1000, 1e-3, 2e-2)])
+    def test_fit_accuracy(self, dim, kappa, mu_tol, kappa_tol):
+        mu = np.full((dim, ), 1/np.sqrt(dim))
+        vmf_dist = vonmises_fisher(mu, kappa)
+        rng = np.random.default_rng(2777937887058094419)
+        n_samples = 10000
+        samples = vmf_dist.rvs(n_samples, random_state=rng)
+        mu_fit, kappa_fit = vonmises_fisher.fit(samples)
+        angular_error = np.arccos(mu.dot(mu_fit))
+        assert_allclose(angular_error, 0., atol=mu_tol, rtol=0)
+        assert_allclose(kappa, kappa_fit, rtol=kappa_tol)
+
+    def test_fit_error_one_dimensional_data(self):
+        x = np.zeros((3, ))
+        msg = "'x' must be two dimensional."
+        with pytest.raises(ValueError, match=msg):
+            vonmises_fisher.fit(x)
+
+    def test_fit_error_unnormalized_data(self):
+        x = np.ones((3, 3))
+        msg = "'x' must be unit vectors of norm 1 along last dimension."
+        with pytest.raises(ValueError, match=msg):
+            vonmises_fisher.fit(x)
+
+    def test_frozen_distribution(self):
+        mu = np.array([0, 0, 1])
+        kappa = 5
+        frozen = vonmises_fisher(mu, kappa)
+        frozen_seed = vonmises_fisher(mu, kappa, seed=514)
+
+        rvs1 = frozen.rvs(random_state=514)
+        rvs2 = vonmises_fisher.rvs(mu, kappa, random_state=514)
+        rvs3 = frozen_seed.rvs()
+
+        assert_equal(rvs1, rvs2)
+        assert_equal(rvs1, rvs3)
+
+
+class TestDirichletMultinomial:
+    @classmethod
+    def get_params(self, m):
+        rng = np.random.default_rng(28469824356873456)
+        alpha = rng.uniform(0, 100, size=2)
+        x = rng.integers(1, 20, size=(m, 2))
+        n = x.sum(axis=-1)
+        return rng, m, alpha, n, x
+
+    def test_frozen(self):
+        rng = np.random.default_rng(28469824356873456)
+
+        alpha = rng.uniform(0, 100, 10)
+        x = rng.integers(0, 10, 10)
+        n = np.sum(x, axis=-1)
+
+        d = dirichlet_multinomial(alpha, n)
+        assert_equal(d.logpmf(x), dirichlet_multinomial.logpmf(x, alpha, n))
+        assert_equal(d.pmf(x), dirichlet_multinomial.pmf(x, alpha, n))
+        assert_equal(d.mean(), dirichlet_multinomial.mean(alpha, n))
+        assert_equal(d.var(), dirichlet_multinomial.var(alpha, n))
+        assert_equal(d.cov(), dirichlet_multinomial.cov(alpha, n))
+
+    def test_pmf_logpmf_against_R(self):
+        # # Compare PMF against R's extraDistr ddirmnon
+        # # library(extraDistr)
+        # # options(digits=16)
+        # ddirmnom(c(1, 2, 3), 6, c(3, 4, 5))
+        x = np.array([1, 2, 3])
+        n = np.sum(x)
+        alpha = np.array([3, 4, 5])
+        res = dirichlet_multinomial.pmf(x, alpha, n)
+        logres = dirichlet_multinomial.logpmf(x, alpha, n)
+        ref = 0.08484162895927638
+        assert_allclose(res, ref)
+        assert_allclose(logres, np.log(ref))
+        assert res.shape == logres.shape == ()
+
+        # library(extraDistr)
+        # options(digits=16)
+        # ddirmnom(c(4, 3, 2, 0, 2, 3, 5, 7, 4, 7), 37,
+        #          c(45.01025314, 21.98739582, 15.14851365, 80.21588671,
+        #            52.84935481, 25.20905262, 53.85373737, 4.88568118,
+        #            89.06440654, 20.11359466))
+        rng = np.random.default_rng(28469824356873456)
+        alpha = rng.uniform(0, 100, 10)
+        x = rng.integers(0, 10, 10)
+        n = np.sum(x, axis=-1)
+        res = dirichlet_multinomial(alpha, n).pmf(x)
+        logres = dirichlet_multinomial.logpmf(x, alpha, n)
+        ref = 3.65409306285992e-16
+        assert_allclose(res, ref)
+        assert_allclose(logres, np.log(ref))
+
+    def test_pmf_logpmf_support(self):
+        # when the sum of the category counts does not equal the number of
+        # trials, the PMF is zero
+        rng, m, alpha, n, x = self.get_params(1)
+        n += 1
+        assert_equal(dirichlet_multinomial(alpha, n).pmf(x), 0)
+        assert_equal(dirichlet_multinomial(alpha, n).logpmf(x), -np.inf)
+
+        rng, m, alpha, n, x = self.get_params(10)
+        i = rng.random(size=10) > 0.5
+        x[i] = np.round(x[i] * 2)  # sum of these x does not equal n
+        assert_equal(dirichlet_multinomial(alpha, n).pmf(x)[i], 0)
+        assert_equal(dirichlet_multinomial(alpha, n).logpmf(x)[i], -np.inf)
+        assert np.all(dirichlet_multinomial(alpha, n).pmf(x)[~i] > 0)
+        assert np.all(dirichlet_multinomial(alpha, n).logpmf(x)[~i] > -np.inf)
+
+    def test_dimensionality_one(self):
+        # if the dimensionality is one, there is only one possible outcome
+        n = 6  # number of trials
+        alpha = [10]  # concentration parameters
+        x = np.asarray([n])  # counts
+        dist = dirichlet_multinomial(alpha, n)
+
+        assert_equal(dist.pmf(x), 1)
+        assert_equal(dist.pmf(x+1), 0)
+        assert_equal(dist.logpmf(x), 0)
+        assert_equal(dist.logpmf(x+1), -np.inf)
+        assert_equal(dist.mean(), n)
+        assert_equal(dist.var(), 0)
+        assert_equal(dist.cov(), 0)
+
+    @pytest.mark.parametrize('method_name', ['pmf', 'logpmf'])
+    def test_against_betabinom_pmf(self, method_name):
+        rng, m, alpha, n, x = self.get_params(100)
+
+        method = getattr(dirichlet_multinomial(alpha, n), method_name)
+        ref_method = getattr(stats.betabinom(n, *alpha.T), method_name)
+
+        res = method(x)
+        ref = ref_method(x.T[0])
+        assert_allclose(res, ref)
+
+    @pytest.mark.parametrize('method_name', ['mean', 'var'])
+    def test_against_betabinom_moments(self, method_name):
+        rng, m, alpha, n, x = self.get_params(100)
+
+        method = getattr(dirichlet_multinomial(alpha, n), method_name)
+        ref_method = getattr(stats.betabinom(n, *alpha.T), method_name)
+
+        res = method()[:, 0]
+        ref = ref_method()
+        assert_allclose(res, ref)
+
+    def test_moments(self):
+        rng = np.random.default_rng(28469824356873456)
+        dim = 5
+        n = rng.integers(1, 100)
+        alpha = rng.random(size=dim) * 10
+        dist = dirichlet_multinomial(alpha, n)
+
+        # Generate a random sample from the distribution using NumPy
+        m = 100000
+        p = rng.dirichlet(alpha, size=m)
+        x = rng.multinomial(n, p, size=m)
+
+        assert_allclose(dist.mean(), np.mean(x, axis=0), rtol=5e-3)
+        assert_allclose(dist.var(), np.var(x, axis=0), rtol=1e-2)
+        assert dist.mean().shape == dist.var().shape == (dim,)
+
+        cov = dist.cov()
+        assert cov.shape == (dim, dim)
+        assert_allclose(cov, np.cov(x.T), rtol=2e-2)
+        assert_equal(np.diag(cov), dist.var())
+        assert np.all(scipy.linalg.eigh(cov)[0] > 0)  # positive definite
+
+    def test_input_validation(self):
+        # valid inputs
+        x0 = np.array([1, 2, 3])
+        n0 = np.sum(x0)
+        alpha0 = np.array([3, 4, 5])
+
+        text = "`x` must contain only non-negative integers."
+        with assert_raises(ValueError, match=text):
+            dirichlet_multinomial.logpmf([1, -1, 3], alpha0, n0)
+        with assert_raises(ValueError, match=text):
+            dirichlet_multinomial.logpmf([1, 2.1, 3], alpha0, n0)
+
+        text = "`alpha` must contain only positive values."
+        with assert_raises(ValueError, match=text):
+            dirichlet_multinomial.logpmf(x0, [3, 0, 4], n0)
+        with assert_raises(ValueError, match=text):
+            dirichlet_multinomial.logpmf(x0, [3, -1, 4], n0)
+
+        text = "`n` must be a positive integer."
+        with assert_raises(ValueError, match=text):
+            dirichlet_multinomial.logpmf(x0, alpha0, 49.1)
+        with assert_raises(ValueError, match=text):
+            dirichlet_multinomial.logpmf(x0, alpha0, 0)
+
+        x = np.array([1, 2, 3, 4])
+        alpha = np.array([3, 4, 5])
+        text = "`x` and `alpha` must be broadcastable."
+        with assert_raises(ValueError, match=text):
+            dirichlet_multinomial.logpmf(x, alpha, x.sum())
+
+    @pytest.mark.parametrize('method', ['pmf', 'logpmf'])
+    def test_broadcasting_pmf(self, method):
+        alpha = np.array([[3, 4, 5], [4, 5, 6], [5, 5, 7], [8, 9, 10]])
+        n = np.array([[6], [7], [8]])
+        x = np.array([[1, 2, 3], [2, 2, 3]]).reshape((2, 1, 1, 3))
+        method = getattr(dirichlet_multinomial, method)
+        res = method(x, alpha, n)
+        assert res.shape == (2, 3, 4)
+        for i in range(len(x)):
+            for j in range(len(n)):
+                for k in range(len(alpha)):
+                    res_ijk = res[i, j, k]
+                    ref = method(x[i].squeeze(), alpha[k].squeeze(), n[j].squeeze())
+                    assert_allclose(res_ijk, ref)
+
+    @pytest.mark.parametrize('method_name', ['mean', 'var', 'cov'])
+    def test_broadcasting_moments(self, method_name):
+        alpha = np.array([[3, 4, 5], [4, 5, 6], [5, 5, 7], [8, 9, 10]])
+        n = np.array([[6], [7], [8]])
+        method = getattr(dirichlet_multinomial, method_name)
+        res = method(alpha, n)
+        assert res.shape == (3, 4, 3) if method_name != 'cov' else (3, 4, 3, 3)
+        for j in range(len(n)):
+            for k in range(len(alpha)):
+                res_ijk = res[j, k]
+                ref = method(alpha[k].squeeze(), n[j].squeeze())
+                assert_allclose(res_ijk, ref)
+
+
+class TestNormalInverseGamma:
+
+    def test_marginal_x(self):
+        # According to [1], sqrt(a * lmbda / b) * (x - u) should follow a t-distribution
+        # with 2*a degrees of freedom. Test that this is true of the PDF and random
+        # variates.
+        rng = np.random.default_rng(8925849245)
+        mu, lmbda, a, b = rng.random(4)
+
+        norm_inv_gamma = stats.normal_inverse_gamma(mu, lmbda, a, b)
+        t = stats.t(2*a, loc=mu, scale=1/np.sqrt(a * lmbda / b))
+
+        # Test PDF
+        x = np.linspace(-5, 5, 11)
+        res = tanhsinh(lambda s2, x: norm_inv_gamma.pdf(x, s2), 0, np.inf, args=(x,))
+        ref = t.pdf(x)
+        assert_allclose(res.integral, ref)
+
+        # Test RVS
+        res = norm_inv_gamma.rvs(size=10000, random_state=rng)
+        _, pvalue = stats.ks_1samp(res[0], t.cdf)
+        assert pvalue > 0.1
+
+    def test_marginal_s2(self):
+        # According to [1], s2 should follow an inverse gamma distribution with
+        # shapes a, b (where b is the scale in our parameterization). Test that
+        # this is true of the PDF and random variates.
+        rng = np.random.default_rng(8925849245)
+        mu, lmbda, a, b = rng.random(4)
+
+        norm_inv_gamma = stats.normal_inverse_gamma(mu, lmbda, a, b)
+        inv_gamma = stats.invgamma(a, scale=b)
+
+        # Test PDF
+        s2 = np.linspace(0.1, 10, 10)
+        res = tanhsinh(lambda x, s2: norm_inv_gamma.pdf(x, s2),
+                       -np.inf, np.inf, args=(s2,))
+        ref = inv_gamma.pdf(s2)
+        assert_allclose(res.integral, ref)
+
+        # Test RVS
+        res = norm_inv_gamma.rvs(size=10000, random_state=rng)
+        _, pvalue = stats.ks_1samp(res[1], inv_gamma.cdf)
+        assert pvalue > 0.1
+
+    def test_pdf_logpdf(self):
+        # Check that PDF and log-PDF are consistent
+        rng = np.random.default_rng(8925849245)
+        mu, lmbda, a, b = rng.random((4, 20)) - 0.25  # make some invalid
+        x, s2 = rng.random(size=(2, 20)) - 0.25
+        res = stats.normal_inverse_gamma(mu, lmbda, a, b).pdf(x, s2)
+        ref = stats.normal_inverse_gamma.logpdf(x, s2, mu, lmbda, a, b)
+        assert_allclose(res, np.exp(ref))
+
+    def test_invalid_and_special_cases(self):
+        # Test cases that are handled by input validation rather than the formulas
+        rng = np.random.default_rng(8925849245)
+        mu, lmbda, a, b = rng.random(4)
+        x, s2 = rng.random(2)
+
+        res = stats.normal_inverse_gamma(np.nan, lmbda, a, b).pdf(x, s2)
+        assert_equal(res, np.nan)
+
+        res = stats.normal_inverse_gamma(mu, -1, a, b).pdf(x, s2)
+        assert_equal(res, np.nan)
+
+        res = stats.normal_inverse_gamma(mu, lmbda, 0, b).pdf(x, s2)
+        assert_equal(res, np.nan)
+
+        res = stats.normal_inverse_gamma(mu, lmbda, a, -1).pdf(x, s2)
+        assert_equal(res, np.nan)
+
+        res = stats.normal_inverse_gamma(mu, lmbda, a, b).pdf(x, -1)
+        assert_equal(res, 0)
+
+        # PDF with out-of-support s2 is not zero if shape parameter is invalid
+        res = stats.normal_inverse_gamma(mu, [-1, np.nan], a, b).pdf(x, -1)
+        assert_equal(res, np.nan)
+
+        res = stats.normal_inverse_gamma(mu, -1, a, b).mean()
+        assert_equal(res, (np.nan, np.nan))
+
+        res = stats.normal_inverse_gamma(mu, lmbda, -1, b).var()
+        assert_equal(res, (np.nan, np.nan))
+
+        with pytest.raises(ValueError, match="Domain error in arguments..."):
+            stats.normal_inverse_gamma(mu, lmbda, a, -1).rvs()
+
+    def test_broadcasting(self):
+        # Test methods with broadcastable array parameters. Roughly speaking, the
+        # shapes should be the broadcasted shapes of all arguments, and the raveled
+        # outputs should be the same as the outputs with raveled inputs.
+        rng = np.random.default_rng(8925849245)
+        b = rng.random(2)
+        a = rng.random((3, 1)) + 2  # for defined moments
+        lmbda = rng.random((4, 1, 1))
+        mu = rng.random((5, 1, 1, 1))
+        s2 = rng.random((6, 1, 1, 1, 1))
+        x = rng.random((7, 1, 1, 1, 1, 1))
+        dist = stats.normal_inverse_gamma(mu, lmbda, a, b)
+
+        # Test PDF and log-PDF
+        broadcasted = np.broadcast_arrays(x, s2, mu, lmbda, a, b)
+        broadcasted_raveled = [np.ravel(arr) for arr in broadcasted]
+
+        res = dist.pdf(x, s2)
+        assert res.shape == broadcasted[0].shape
+        assert_allclose(res.ravel(),
+                        stats.normal_inverse_gamma.pdf(*broadcasted_raveled))
+
+        res = dist.logpdf(x, s2)
+        assert res.shape == broadcasted[0].shape
+        assert_allclose(res.ravel(),
+                        stats.normal_inverse_gamma.logpdf(*broadcasted_raveled))
+
+        # Test moments
+        broadcasted = np.broadcast_arrays(mu, lmbda, a, b)
+        broadcasted_raveled = [np.ravel(arr) for arr in broadcasted]
+
+        res = dist.mean()
+        assert res[0].shape == broadcasted[0].shape
+        assert_allclose((res[0].ravel(), res[1].ravel()),
+                        stats.normal_inverse_gamma.mean(*broadcasted_raveled))
+
+        res = dist.var()
+        assert res[0].shape == broadcasted[0].shape
+        assert_allclose((res[0].ravel(), res[1].ravel()),
+                        stats.normal_inverse_gamma.var(*broadcasted_raveled))
+
+        # Test RVS
+        size = (6, 5, 4, 3, 2)
+        rng = np.random.default_rng(2348923985324)
+        res = dist.rvs(size=size, random_state=rng)
+        rng = np.random.default_rng(2348923985324)
+        shape = 6, 5*4*3*2
+        ref = stats.normal_inverse_gamma.rvs(*broadcasted_raveled, size=shape,
+                                             random_state=rng)
+        assert_allclose((res[0].reshape(shape), res[1].reshape(shape)), ref)
+
+    @pytest.mark.slow
+    @pytest.mark.fail_slow(10)
+    def test_moments(self):
+        # Test moments against quadrature
+        rng = np.random.default_rng(8925849245)
+        mu, lmbda, a, b = rng.random(4)
+        a += 2  # ensure defined
+
+        dist = stats.normal_inverse_gamma(mu, lmbda, a, b)
+        res = dist.mean()
+
+        ref = dblquad(lambda s2, x: dist.pdf(x, s2) * x, -np.inf, np.inf, 0, np.inf)
+        assert_allclose(res[0], ref[0], rtol=1e-6)
+
+        ref = dblquad(lambda s2, x: dist.pdf(x, s2) * s2, -np.inf, np.inf, 0, np.inf)
+        assert_allclose(res[1], ref[0], rtol=1e-6)
+
+    @pytest.mark.parametrize('dtype', [np.int32, np.float16, np.float32, np.float64])
+    def test_dtype(self, dtype):
+        if np.__version__ < "2":
+            pytest.skip("Scalar dtypes only respected after NEP 50.")
+        rng = np.random.default_rng(8925849245)
+        x, s2, mu, lmbda, a, b = rng.uniform(3, 10, size=6).astype(dtype)
+        dtype_out = np.result_type(1.0, dtype)
+        dist = stats.normal_inverse_gamma(mu, lmbda, a, b)
+        assert dist.rvs()[0].dtype == dtype_out
+        assert dist.rvs()[1].dtype == dtype_out
+        assert dist.mean()[0].dtype == dtype_out
+        assert dist.mean()[1].dtype == dtype_out
+        assert dist.var()[0].dtype == dtype_out
+        assert dist.var()[1].dtype == dtype_out
+        assert dist.logpdf(x, s2).dtype == dtype_out
+        assert dist.pdf(x, s2).dtype == dtype_out
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_odds_ratio.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_odds_ratio.py
new file mode 100644
index 0000000000000000000000000000000000000000..14b5ca88d0fca9edb8c3c161c06e52054d594e62
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_odds_ratio.py
@@ -0,0 +1,148 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+from .._discrete_distns import nchypergeom_fisher, hypergeom
+from scipy.stats._odds_ratio import odds_ratio
+from .data.fisher_exact_results_from_r import data
+
+
+class TestOddsRatio:
+
+    @pytest.mark.parametrize('parameters, rresult', data)
+    def test_results_from_r(self, parameters, rresult):
+        alternative = parameters.alternative.replace('.', '-')
+        result = odds_ratio(parameters.table)
+        # The results computed by R are not very accurate.
+        if result.statistic < 400:
+            or_rtol = 5e-4
+            ci_rtol = 2e-2
+        else:
+            or_rtol = 5e-2
+            ci_rtol = 1e-1
+        assert_allclose(result.statistic,
+                        rresult.conditional_odds_ratio, rtol=or_rtol)
+        ci = result.confidence_interval(parameters.confidence_level,
+                                        alternative)
+        assert_allclose((ci.low, ci.high), rresult.conditional_odds_ratio_ci,
+                        rtol=ci_rtol)
+
+        # Also do a self-check for the conditional odds ratio.
+        # With the computed conditional odds ratio as the noncentrality
+        # parameter of the noncentral hypergeometric distribution with
+        # parameters table.sum(), table[0].sum(), and table[:,0].sum() as
+        # total, ngood and nsample, respectively, the mean of the distribution
+        # should equal table[0, 0].
+        cor = result.statistic
+        table = np.array(parameters.table)
+        total = table.sum()
+        ngood = table[0].sum()
+        nsample = table[:, 0].sum()
+        # nchypergeom_fisher does not allow the edge cases where the
+        # noncentrality parameter is 0 or inf, so handle those values
+        # separately here.
+        if cor == 0:
+            nchg_mean = hypergeom.support(total, ngood, nsample)[0]
+        elif cor == np.inf:
+            nchg_mean = hypergeom.support(total, ngood, nsample)[1]
+        else:
+            nchg_mean = nchypergeom_fisher.mean(total, ngood, nsample, cor)
+        assert_allclose(nchg_mean, table[0, 0], rtol=1e-13)
+
+        # Check that the confidence interval is correct.
+        alpha = 1 - parameters.confidence_level
+        if alternative == 'two-sided':
+            if ci.low > 0:
+                sf = nchypergeom_fisher.sf(table[0, 0] - 1,
+                                           total, ngood, nsample, ci.low)
+                assert_allclose(sf, alpha/2, rtol=1e-11)
+            if np.isfinite(ci.high):
+                cdf = nchypergeom_fisher.cdf(table[0, 0],
+                                             total, ngood, nsample, ci.high)
+                assert_allclose(cdf, alpha/2, rtol=1e-11)
+        elif alternative == 'less':
+            if np.isfinite(ci.high):
+                cdf = nchypergeom_fisher.cdf(table[0, 0],
+                                             total, ngood, nsample, ci.high)
+                assert_allclose(cdf, alpha, rtol=1e-11)
+        else:
+            # alternative == 'greater'
+            if ci.low > 0:
+                sf = nchypergeom_fisher.sf(table[0, 0] - 1,
+                                           total, ngood, nsample, ci.low)
+                assert_allclose(sf, alpha, rtol=1e-11)
+
+    @pytest.mark.parametrize('table', [
+        [[0, 0], [5, 10]],
+        [[5, 10], [0, 0]],
+        [[0, 5], [0, 10]],
+        [[5, 0], [10, 0]],
+    ])
+    def test_row_or_col_zero(self, table):
+        result = odds_ratio(table)
+        assert_equal(result.statistic, np.nan)
+        ci = result.confidence_interval()
+        assert_equal((ci.low, ci.high), (0, np.inf))
+
+    @pytest.mark.parametrize("case",
+                             [[0.95, 'two-sided', 0.4879913, 2.635883],
+                              [0.90, 'two-sided', 0.5588516, 2.301663]])
+    def test_sample_odds_ratio_ci(self, case):
+        # Compare the sample odds ratio confidence interval to the R function
+        # oddsratio.wald from the epitools package, e.g.
+        # > library(epitools)
+        # > table = matrix(c(10, 20, 41, 93), nrow=2, ncol=2, byrow=TRUE)
+        # > result = oddsratio.wald(table)
+        # > result$measure
+        #           odds ratio with 95% C.I.
+        # Predictor  estimate     lower    upper
+        #   Exposed1 1.000000        NA       NA
+        #   Exposed2 1.134146 0.4879913 2.635883
+
+        confidence_level, alternative, ref_low, ref_high = case
+        table = [[10, 20], [41, 93]]
+        result = odds_ratio(table, kind='sample')
+        assert_allclose(result.statistic, 1.134146, rtol=1e-6)
+        ci = result.confidence_interval(confidence_level, alternative)
+        assert_allclose([ci.low, ci.high], [ref_low, ref_high], rtol=1e-6)
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided'])
+    def test_sample_odds_ratio_one_sided_ci(self, alternative):
+        # can't find a good reference for one-sided CI, so bump up the sample
+        # size and compare against the conditional odds ratio CI
+        table = [[1000, 2000], [4100, 9300]]
+        res = odds_ratio(table, kind='sample')
+        ref = odds_ratio(table, kind='conditional')
+        assert_allclose(res.statistic, ref.statistic, atol=1e-5)
+        assert_allclose(res.confidence_interval(alternative=alternative),
+                        ref.confidence_interval(alternative=alternative),
+                        atol=2e-3)
+
+    @pytest.mark.parametrize('kind', ['sample', 'conditional'])
+    @pytest.mark.parametrize('bad_table', [123, "foo", [10, 11, 12]])
+    def test_invalid_table_shape(self, kind, bad_table):
+        with pytest.raises(ValueError, match="Invalid shape"):
+            odds_ratio(bad_table, kind=kind)
+
+    def test_invalid_table_type(self):
+        with pytest.raises(ValueError, match='must be an array of integers'):
+            odds_ratio([[1.0, 3.4], [5.0, 9.9]])
+
+    def test_negative_table_values(self):
+        with pytest.raises(ValueError, match='must be nonnegative'):
+            odds_ratio([[1, 2], [3, -4]])
+
+    def test_invalid_kind(self):
+        with pytest.raises(ValueError, match='`kind` must be'):
+            odds_ratio([[10, 20], [30, 14]], kind='magnetoreluctance')
+
+    def test_invalid_alternative(self):
+        result = odds_ratio([[5, 10], [2, 32]])
+        with pytest.raises(ValueError, match='`alternative` must be'):
+            result.confidence_interval(alternative='depleneration')
+
+    @pytest.mark.parametrize('level', [-0.5, 1.5])
+    def test_invalid_confidence_level(self, level):
+        result = odds_ratio([[5, 10], [2, 32]])
+        with pytest.raises(ValueError, match='must be between 0 and 1'):
+            result.confidence_interval(confidence_level=level)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_qmc.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_qmc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba824e2d122b9abd970fee1e0fdaeeb9e52fbbeb
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_qmc.py
@@ -0,0 +1,1489 @@
+import os
+from collections import Counter
+from itertools import combinations, product
+
+import pytest
+import numpy as np
+from numpy.testing import (assert_allclose, assert_equal, assert_array_equal, 
+    assert_array_less)
+
+from scipy.spatial import distance
+from scipy.stats import shapiro
+from scipy.stats._sobol import _test_find_index
+from scipy.stats import qmc
+from scipy.stats._qmc import (
+    van_der_corput, n_primes, primes_from_2_to,
+    update_discrepancy, QMCEngine, _l1_norm,
+    _perturb_discrepancy, _lloyd_centroidal_voronoi_tessellation
+)
+
+
+class TestUtils:
+    def test_scale(self):
+        # 1d scalar
+        space = [[0], [1], [0.5]]
+        out = [[-2], [6], [2]]
+        scaled_space = qmc.scale(space, l_bounds=-2, u_bounds=6)
+
+        assert_allclose(scaled_space, out)
+
+        # 2d space
+        space = [[0, 0], [1, 1], [0.5, 0.5]]
+        bounds = np.array([[-2, 0], [6, 5]])
+        out = [[-2, 0], [6, 5], [2, 2.5]]
+
+        scaled_space = qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
+
+        assert_allclose(scaled_space, out)
+
+        scaled_back_space = qmc.scale(scaled_space, l_bounds=bounds[0],
+                                      u_bounds=bounds[1], reverse=True)
+        assert_allclose(scaled_back_space, space)
+
+        # broadcast
+        space = [[0, 0, 0], [1, 1, 1], [0.5, 0.5, 0.5]]
+        l_bounds, u_bounds = 0, [6, 5, 3]
+        out = [[0, 0, 0], [6, 5, 3], [3, 2.5, 1.5]]
+
+        scaled_space = qmc.scale(space, l_bounds=l_bounds, u_bounds=u_bounds)
+
+        assert_allclose(scaled_space, out)
+
+    def test_scale_random(self):
+        rng = np.random.default_rng(317589836511269190194010915937762468165)
+        sample = rng.random((30, 10))
+        a = -rng.random(10) * 10
+        b = rng.random(10) * 10
+        scaled = qmc.scale(sample, a, b, reverse=False)
+        unscaled = qmc.scale(scaled, a, b, reverse=True)
+        assert_allclose(unscaled, sample)
+
+    def test_scale_errors(self):
+        with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
+            space = [0, 1, 0.5]
+            qmc.scale(space, l_bounds=-2, u_bounds=6)
+
+        with pytest.raises(ValueError, match=r"Bounds are not consistent"):
+            space = [[0, 0], [1, 1], [0.5, 0.5]]
+            bounds = np.array([[-2, 6], [6, 5]])
+            qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
+
+        with pytest.raises(ValueError, match=r"'l_bounds' and 'u_bounds'"
+                                             r" must be broadcastable"):
+            space = [[0, 0], [1, 1], [0.5, 0.5]]
+            l_bounds, u_bounds = [-2, 0, 2], [6, 5]
+            qmc.scale(space, l_bounds=l_bounds, u_bounds=u_bounds)
+
+        with pytest.raises(ValueError, match=r"'l_bounds' and 'u_bounds'"
+                                             r" must be broadcastable"):
+            space = [[0, 0], [1, 1], [0.5, 0.5]]
+            bounds = np.array([[-2, 0, 2], [6, 5, 5]])
+            qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
+
+        with pytest.raises(ValueError, match=r"Sample is not in unit "
+                                             r"hypercube"):
+            space = [[0, 0], [1, 1.5], [0.5, 0.5]]
+            bounds = np.array([[-2, 0], [6, 5]])
+            qmc.scale(space, l_bounds=bounds[0], u_bounds=bounds[1])
+
+        with pytest.raises(ValueError, match=r"Sample is out of bounds"):
+            out = [[-2, 0], [6, 5], [8, 2.5]]
+            bounds = np.array([[-2, 0], [6, 5]])
+            qmc.scale(out, l_bounds=bounds[0], u_bounds=bounds[1],
+                      reverse=True)
+
+    def test_discrepancy(self):
+        space_1 = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
+        space_1 = (2.0 * space_1 - 1.0) / (2.0 * 6.0)
+        space_2 = np.array([[1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [6, 6]])
+        space_2 = (2.0 * space_2 - 1.0) / (2.0 * 6.0)
+
+        # From Fang et al. Design and modeling for computer experiments, 2006
+        assert_allclose(qmc.discrepancy(space_1), 0.0081, atol=1e-4)
+        assert_allclose(qmc.discrepancy(space_2), 0.0105, atol=1e-4)
+
+        # From Zhou Y.-D. et al. Mixture discrepancy for quasi-random point
+        # sets. Journal of Complexity, 29 (3-4), pp. 283-301, 2013.
+        # Example 4 on Page 298
+        sample = np.array([[2, 1, 1, 2, 2, 2],
+                           [1, 2, 2, 2, 2, 2],
+                           [2, 1, 1, 1, 1, 1],
+                           [1, 1, 1, 1, 2, 2],
+                           [1, 2, 2, 2, 1, 1],
+                           [2, 2, 2, 2, 1, 1],
+                           [2, 2, 2, 1, 2, 2]])
+        sample = (2.0 * sample - 1.0) / (2.0 * 2.0)
+
+        assert_allclose(qmc.discrepancy(sample, method='MD'), 2.5000,
+                        atol=1e-4)
+        assert_allclose(qmc.discrepancy(sample, method='WD'), 1.3680,
+                        atol=1e-4)
+        assert_allclose(qmc.discrepancy(sample, method='CD'), 0.3172,
+                        atol=1e-4)
+
+        # From Tim P. et al. Minimizing the L2 and Linf star discrepancies
+        # of a single point in the unit hypercube. JCAM, 2005
+        # Table 1 on Page 283
+        for dim in [2, 4, 8, 16, 32, 64]:
+            ref = np.sqrt(3**(-dim))
+            assert_allclose(qmc.discrepancy(np.array([[1]*dim]),
+                                            method='L2-star'), ref)
+
+    def test_discrepancy_errors(self):
+        sample = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
+
+        with pytest.raises(
+            ValueError, match=r"Sample is not in unit hypercube"
+        ):
+            qmc.discrepancy(sample)
+
+        with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
+            qmc.discrepancy([1, 3])
+
+        sample = [[0, 0], [1, 1], [0.5, 0.5]]
+        with pytest.raises(ValueError, match=r"'toto' is not a valid ..."):
+            qmc.discrepancy(sample, method="toto")
+
+    def test_discrepancy_parallel(self, monkeypatch):
+        sample = np.array([[2, 1, 1, 2, 2, 2],
+                           [1, 2, 2, 2, 2, 2],
+                           [2, 1, 1, 1, 1, 1],
+                           [1, 1, 1, 1, 2, 2],
+                           [1, 2, 2, 2, 1, 1],
+                           [2, 2, 2, 2, 1, 1],
+                           [2, 2, 2, 1, 2, 2]])
+        sample = (2.0 * sample - 1.0) / (2.0 * 2.0)
+
+        assert_allclose(qmc.discrepancy(sample, method='MD', workers=8),
+                        2.5000,
+                        atol=1e-4)
+        assert_allclose(qmc.discrepancy(sample, method='WD', workers=8),
+                        1.3680,
+                        atol=1e-4)
+        assert_allclose(qmc.discrepancy(sample, method='CD', workers=8),
+                        0.3172,
+                        atol=1e-4)
+
+        # From Tim P. et al. Minimizing the L2 and Linf star discrepancies
+        # of a single point in the unit hypercube. JCAM, 2005
+        # Table 1 on Page 283
+        for dim in [2, 4, 8, 16, 32, 64]:
+            ref = np.sqrt(3 ** (-dim))
+            assert_allclose(qmc.discrepancy(np.array([[1] * dim]),
+                                            method='L2-star', workers=-1), ref)
+
+        monkeypatch.setattr(os, 'cpu_count', lambda: None)
+        with pytest.raises(NotImplementedError, match="Cannot determine the"):
+            qmc.discrepancy(sample, workers=-1)
+
+        with pytest.raises(ValueError, match="Invalid number of workers..."):
+            qmc.discrepancy(sample, workers=-2)
+
+    def test_geometric_discrepancy_errors(self):
+        sample = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
+
+        with pytest.raises(ValueError, match=r"Sample is not in unit hypercube"):
+            qmc.geometric_discrepancy(sample)
+
+        with pytest.raises(ValueError, match=r"Sample is not a 2D array"):
+            qmc.geometric_discrepancy([1, 3])
+
+        sample = [[0, 0], [1, 1], [0.5, 0.5]]
+        with pytest.raises(ValueError, match=r"'toto' is not a valid ..."):
+            qmc.geometric_discrepancy(sample, method="toto")
+
+        sample = np.array([[0, 0], [0, 0], [0, 1]])
+        with pytest.warns(UserWarning, match="Sample contains duplicate points."):
+            qmc.geometric_discrepancy(sample)
+
+        sample = np.array([[0.5, 0.5]])
+        with pytest.raises(ValueError, match="Sample must contain at least two points"):
+            qmc.geometric_discrepancy(sample)
+
+    def test_geometric_discrepancy(self):
+        sample = np.array([[0, 0], [1, 1]])
+        assert_allclose(qmc.geometric_discrepancy(sample), np.sqrt(2))
+        assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), np.sqrt(2))
+
+        sample = np.array([[0, 0], [0, 1], [0.5, 1]])
+        assert_allclose(qmc.geometric_discrepancy(sample), 0.5)
+        assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), 0.75)
+
+        sample = np.array([[0, 0], [0.25, 0.25], [1, 1]])
+        assert_allclose(qmc.geometric_discrepancy(sample), np.sqrt(2) / 4)
+        assert_allclose(qmc.geometric_discrepancy(sample, method="mst"), np.sqrt(2) / 2)
+        assert_allclose(qmc.geometric_discrepancy(sample, metric="chebyshev"), 0.25)
+        assert_allclose(
+            qmc.geometric_discrepancy(sample, method="mst", metric="chebyshev"), 0.5
+        )
+
+        rng = np.random.default_rng(191468432622931918890291693003068437394)
+        sample = qmc.LatinHypercube(d=3, rng=rng).random(50)
+        assert_allclose(qmc.geometric_discrepancy(sample), 0.05106012076093356)
+        assert_allclose(
+            qmc.geometric_discrepancy(sample, method='mst'), 0.19704396643366182
+        )
+
+    @pytest.mark.xfail(
+            reason="minimum_spanning_tree ignores zero distances (#18892)",
+            strict=True,
+    )
+    def test_geometric_discrepancy_mst_with_zero_distances(self):
+        sample = np.array([[0, 0], [0, 0], [0, 1]])
+        assert_allclose(qmc.geometric_discrepancy(sample, method='mst'), 0.5)
+
+    def test_update_discrepancy(self):
+        # From Fang et al. Design and modeling for computer experiments, 2006
+        space_1 = np.array([[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]])
+        space_1 = (2.0 * space_1 - 1.0) / (2.0 * 6.0)
+
+        disc_init = qmc.discrepancy(space_1[:-1], iterative=True)
+        disc_iter = update_discrepancy(space_1[-1], space_1[:-1], disc_init)
+
+        assert_allclose(disc_iter, 0.0081, atol=1e-4)
+
+        # n QMCEngine:
+        # preserve use of `seed` during SPEC 7 transition because
+        # some tests rely on behavior with integer `seed` (which is
+        # different from behavior with integer `rng`)
+        if self.can_scramble:
+            return self.qmce(scramble=scramble, seed=rng, **kwargs)
+        else:
+            if scramble:
+                pytest.skip()
+            else:
+                return self.qmce(seed=rng, **kwargs)
+
+    def reference(self, scramble: bool) -> np.ndarray:
+        return self.scramble_nd if scramble else self.unscramble_nd
+
+    @pytest.mark.parametrize("scramble", scramble, ids=ids)
+    def test_0dim(self, scramble):
+        engine = self.engine(d=0, scramble=scramble)
+        sample = engine.random(4)
+        assert_array_equal(np.empty((4, 0)), sample)
+
+    @pytest.mark.parametrize("scramble", scramble, ids=ids)
+    def test_0sample(self, scramble):
+        engine = self.engine(d=2, scramble=scramble)
+        sample = engine.random(0)
+        assert_array_equal(np.empty((0, 2)), sample)
+
+    @pytest.mark.parametrize("scramble", scramble, ids=ids)
+    def test_1sample(self, scramble):
+        engine = self.engine(d=2, scramble=scramble)
+        sample = engine.random(1)
+        assert (1, 2) == sample.shape
+
+    @pytest.mark.parametrize("scramble", scramble, ids=ids)
+    def test_bounds(self, scramble):
+        engine = self.engine(d=100, scramble=scramble)
+        sample = engine.random(512)
+        assert np.all(sample >= 0)
+        assert np.all(sample <= 1)
+
+    @pytest.mark.parametrize("scramble", scramble, ids=ids)
+    def test_sample(self, scramble):
+        ref_sample = self.reference(scramble=scramble)
+        engine = self.engine(d=2, scramble=scramble)
+        sample = engine.random(n=len(ref_sample))
+
+        assert_allclose(sample, ref_sample, atol=1e-1)
+        assert engine.num_generated == len(ref_sample)
+
+    @pytest.mark.parametrize("scramble", scramble, ids=ids)
+    def test_continuing(self, scramble):
+        engine = self.engine(d=2, scramble=scramble)
+        ref_sample = engine.random(n=8)
+
+        engine = self.engine(d=2, scramble=scramble)
+
+        n_half = len(ref_sample) // 2
+
+        _ = engine.random(n=n_half)
+        sample = engine.random(n=n_half)
+        assert_allclose(sample, ref_sample[n_half:], atol=1e-1)
+
+    @pytest.mark.parametrize("scramble", scramble, ids=ids)
+    @pytest.mark.parametrize(
+        "rng",
+        (
+            170382760648021597650530316304495310428,
+            np.random.default_rng(170382760648021597650530316304495310428),
+            None,
+        ),
+    )
+    def test_reset(self, scramble, rng):
+        engine = self.engine(d=2, scramble=scramble, rng=rng)
+        ref_sample = engine.random(n=8)
+
+        engine.reset()
+        assert engine.num_generated == 0
+
+        sample = engine.random(n=8)
+        assert_allclose(sample, ref_sample)
+
+    @pytest.mark.parametrize("scramble", scramble, ids=ids)
+    def test_fast_forward(self, scramble):
+        engine = self.engine(d=2, scramble=scramble)
+        ref_sample = engine.random(n=8)
+
+        engine = self.engine(d=2, scramble=scramble)
+
+        engine.fast_forward(4)
+        sample = engine.random(n=4)
+
+        assert_allclose(sample, ref_sample[4:], atol=1e-1)
+
+        # alternate fast forwarding with sampling
+        engine.reset()
+        even_draws = []
+        for i in range(8):
+            if i % 2 == 0:
+                even_draws.append(engine.random())
+            else:
+                engine.fast_forward(1)
+        assert_allclose(
+            ref_sample[[i for i in range(8) if i % 2 == 0]],
+            np.concatenate(even_draws),
+            atol=1e-5
+        )
+
+    @pytest.mark.parametrize("scramble", [True])
+    def test_distribution(self, scramble):
+        d = 50
+        engine = self.engine(d=d, scramble=scramble)
+        sample = engine.random(1024)
+        assert_allclose(
+            np.mean(sample, axis=0), np.repeat(0.5, d), atol=1e-2
+        )
+        assert_allclose(
+            np.percentile(sample, 25, axis=0), np.repeat(0.25, d), atol=1e-2
+        )
+        assert_allclose(
+            np.percentile(sample, 75, axis=0), np.repeat(0.75, d), atol=1e-2
+        )
+
+    def test_raises_optimizer(self):
+        message = r"'toto' is not a valid optimization method"
+        with pytest.raises(ValueError, match=message):
+            self.engine(d=1, scramble=False, optimization="toto")
+
+    @pytest.mark.parametrize(
+        "optimization,metric",
+        [
+            ("random-CD", qmc.discrepancy),
+            ("lloyd", lambda sample: -_l1_norm(sample))]
+    )
+    def test_optimizers(self, optimization, metric):
+        engine = self.engine(d=2, scramble=False)
+        sample_ref = engine.random(n=64)
+        metric_ref = metric(sample_ref)
+
+        optimal_ = self.engine(d=2, scramble=False, optimization=optimization)
+        sample_ = optimal_.random(n=64)
+        metric_ = metric(sample_)
+
+        assert metric_ < metric_ref
+
+    def test_consume_prng_state(self):
+        rng = np.random.default_rng(0xa29cabb11cfdf44ff6cac8bec254c2a0)
+        sample = []
+        for i in range(3):
+            engine = self.engine(d=2, scramble=True, rng=rng)
+            sample.append(engine.random(4))
+
+        with pytest.raises(AssertionError, match="Arrays are not equal"):
+            assert_equal(sample[0], sample[1])
+        with pytest.raises(AssertionError, match="Arrays are not equal"):
+            assert_equal(sample[0], sample[2])
+
+
+class TestHalton(QMCEngineTests):
+    qmce = qmc.Halton
+    can_scramble = True
+    # theoretical values known from Van der Corput
+    unscramble_nd = np.array([[0, 0], [1 / 2, 1 / 3],
+                              [1 / 4, 2 / 3], [3 / 4, 1 / 9],
+                              [1 / 8, 4 / 9], [5 / 8, 7 / 9],
+                              [3 / 8, 2 / 9], [7 / 8, 5 / 9]])
+    # theoretical values unknown: convergence properties checked
+    scramble_nd = np.array([[0.50246036, 0.93382481],
+                            [0.00246036, 0.26715815],
+                            [0.75246036, 0.60049148],
+                            [0.25246036, 0.8227137 ],
+                            [0.62746036, 0.15604704],
+                            [0.12746036, 0.48938037],
+                            [0.87746036, 0.71160259],
+                            [0.37746036, 0.04493592]])
+
+    def test_workers(self):
+        ref_sample = self.reference(scramble=True)
+        engine = self.engine(d=2, scramble=True)
+        sample = engine.random(n=len(ref_sample), workers=8)
+
+        assert_allclose(sample, ref_sample, atol=1e-3)
+
+        # worker + integers
+        engine.reset()
+        ref_sample = engine.integers(10)
+        engine.reset()
+        sample = engine.integers(10, workers=8)
+        assert_equal(sample, ref_sample)
+
+
+class TestLHS(QMCEngineTests):
+    qmce = qmc.LatinHypercube
+    can_scramble = True
+
+    def test_continuing(self, *args):
+        pytest.skip("Not applicable: not a sequence.")
+
+    def test_fast_forward(self, *args):
+        pytest.skip("Not applicable: not a sequence.")
+
+    def test_sample(self, *args):
+        pytest.skip("Not applicable: the value of reference sample is"
+                    " implementation dependent.")
+
+    @pytest.mark.parametrize("strength", [1, 2])
+    @pytest.mark.parametrize("scramble", [False, True])
+    @pytest.mark.parametrize("optimization", [None, "random-CD"])
+    def test_sample_stratified(self, optimization, scramble, strength):
+        rng = np.random.default_rng(37511836202578819870665127532742111260)
+        p = 5
+        n = p**2
+        d = 6
+
+        engine = qmc.LatinHypercube(d=d, scramble=scramble,
+                                    strength=strength,
+                                    optimization=optimization,
+                                    rng=rng)
+        sample = engine.random(n=n)
+        assert sample.shape == (n, d)
+        assert engine.num_generated == n
+
+        # centering stratifies samples in the middle of equal segments:
+        # * inter-sample distance is constant in 1D sub-projections
+        # * after ordering, columns are equal
+        expected1d = (np.arange(n) + 0.5) / n
+        expected = np.broadcast_to(expected1d, (d, n)).T
+        assert np.any(sample != expected)
+
+        sorted_sample = np.sort(sample, axis=0)
+        tol = 0.5 / n if scramble else 0
+
+        assert_allclose(sorted_sample, expected, atol=tol)
+        assert np.any(sample - expected > tol)
+
+        if strength == 2 and optimization is None:
+            unique_elements = np.arange(p)
+            desired = set(product(unique_elements, unique_elements))
+
+            for i, j in combinations(range(engine.d), 2):
+                samples_2d = sample[:, [i, j]]
+                res = (samples_2d * p).astype(int)
+                res_set = {tuple(row) for row in res}
+                assert_equal(res_set, desired)
+
+    def test_optimizer_1d(self):
+        # discrepancy measures are invariant under permuting factors and runs
+        engine = self.engine(d=1, scramble=False)
+        sample_ref = engine.random(n=64)
+
+        optimal_ = self.engine(d=1, scramble=False, optimization="random-CD")
+        sample_ = optimal_.random(n=64)
+
+        assert_array_equal(sample_ref, sample_)
+
+    def test_raises(self):
+        message = r"not a valid strength"
+        with pytest.raises(ValueError, match=message):
+            qmc.LatinHypercube(1, strength=3)
+
+        message = r"n is not the square of a prime number"
+        with pytest.raises(ValueError, match=message):
+            engine = qmc.LatinHypercube(d=2, strength=2)
+            engine.random(16)
+
+        message = r"n is not the square of a prime number"
+        with pytest.raises(ValueError, match=message):
+            engine = qmc.LatinHypercube(d=2, strength=2)
+            engine.random(5)  # because int(sqrt(5)) would result in 2
+
+        message = r"n is too small for d"
+        with pytest.raises(ValueError, match=message):
+            engine = qmc.LatinHypercube(d=5, strength=2)
+            engine.random(9)
+
+
+class TestSobol(QMCEngineTests):
+    qmce = qmc.Sobol
+    can_scramble = True
+    # theoretical values from Joe Kuo2010
+    unscramble_nd = np.array([[0., 0.],
+                              [0.5, 0.5],
+                              [0.75, 0.25],
+                              [0.25, 0.75],
+                              [0.375, 0.375],
+                              [0.875, 0.875],
+                              [0.625, 0.125],
+                              [0.125, 0.625]])
+
+    # theoretical values unknown: convergence properties checked
+    scramble_nd = np.array([[0.25331921, 0.41371179],
+                            [0.8654213, 0.9821167],
+                            [0.70097554, 0.03664616],
+                            [0.18027647, 0.60895735],
+                            [0.10521339, 0.21897069],
+                            [0.53019685, 0.66619033],
+                            [0.91122276, 0.34580743],
+                            [0.45337471, 0.78912079]])
+
+    def test_warning(self):
+        with pytest.warns(UserWarning, match=r"The balance properties of "
+                                             r"Sobol' points"):
+            engine = qmc.Sobol(1)
+            engine.random(10)
+
+    def test_random_base2(self):
+        engine = qmc.Sobol(2, scramble=False)
+        sample = engine.random_base2(2)
+        assert_array_equal(self.unscramble_nd[:4], sample)
+
+        # resampling still having N=2**n
+        sample = engine.random_base2(2)
+        assert_array_equal(self.unscramble_nd[4:8], sample)
+
+        # resampling again but leading to N!=2**n
+        with pytest.raises(ValueError, match=r"The balance properties of "
+                                             r"Sobol' points"):
+            engine.random_base2(2)
+
+    def test_raise(self):
+        with pytest.raises(ValueError, match=r"Maximum supported "
+                                             r"dimensionality"):
+            qmc.Sobol(qmc.Sobol.MAXDIM + 1)
+
+        with pytest.raises(ValueError, match=r"Maximum supported "
+                                             r"'bits' is 64"):
+            qmc.Sobol(1, bits=65)
+
+    def test_high_dim(self):
+        engine = qmc.Sobol(1111, scramble=False)
+        count1 = Counter(engine.random().flatten().tolist())
+        count2 = Counter(engine.random().flatten().tolist())
+        assert_equal(count1, Counter({0.0: 1111}))
+        assert_equal(count2, Counter({0.5: 1111}))
+
+    @pytest.mark.parametrize("bits", [2, 3])
+    def test_bits(self, bits):
+        engine = qmc.Sobol(2, scramble=False, bits=bits)
+        ns = 2**bits
+        sample = engine.random(ns)
+        assert_array_equal(self.unscramble_nd[:ns], sample)
+
+        with pytest.raises(ValueError, match="increasing `bits`"):
+            engine.random()
+
+    def test_64bits(self):
+        engine = qmc.Sobol(2, scramble=False, bits=64)
+        sample = engine.random(8)
+        assert_array_equal(self.unscramble_nd, sample)
+
+
+class TestPoisson(QMCEngineTests):
+    qmce = qmc.PoissonDisk
+    can_scramble = False
+
+    def test_bounds(self, *args):
+        pytest.skip("Too costly in memory.")
+
+    def test_fast_forward(self, *args):
+        pytest.skip("Not applicable: recursive process.")
+
+    def test_sample(self, *args):
+        pytest.skip("Not applicable: the value of reference sample is"
+                    " implementation dependent.")
+
+    def test_continuing(self, *args):
+        # can continue a sampling, but will not preserve the same order
+        # because candidates are lost, so we will not select the same center
+        radius = 0.05
+        ns = 6
+        engine = self.engine(d=2, radius=radius, scramble=False)
+
+        sample_init = engine.random(n=ns)
+        assert len(sample_init) <= ns
+        assert l2_norm(sample_init) >= radius
+
+        sample_continued = engine.random(n=ns)
+        assert len(sample_continued) <= ns
+        assert l2_norm(sample_continued) >= radius
+
+        sample = np.concatenate([sample_init, sample_continued], axis=0)
+        assert len(sample) <= ns * 2
+        assert l2_norm(sample) >= radius
+
+    def test_mindist(self):
+        rng = np.random.default_rng(132074951149370773672162394161442690287)
+        ns = 50
+
+        low, high = 0.08, 0.2
+        radii = (high - low) * rng.random(5) + low
+
+        dimensions = [1, 3, 4]
+        hypersphere_methods = ["volume", "surface"]
+
+        gen = product(dimensions, radii, hypersphere_methods)
+
+        for d, radius, hypersphere in gen:
+            engine = self.qmce(
+                d=d, radius=radius, hypersphere=hypersphere, rng=rng
+            )
+            sample = engine.random(ns)
+
+            assert len(sample) <= ns
+            assert l2_norm(sample) >= radius
+
+    def test_fill_space(self):
+        radius = 0.2
+        engine = self.qmce(d=2, radius=radius)
+
+        sample = engine.fill_space()
+        # circle packing problem is np complex
+        assert l2_norm(sample) >= radius
+
+    @pytest.mark.parametrize("l_bounds", [[-1, -2, -1], [1, 2, 1]])
+    def test_sample_inside_lower_bounds(self, l_bounds):
+        radius = 0.2
+        u_bounds=[3, 3, 2]
+        engine = self.qmce(
+            d=3, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds
+        )
+        sample = engine.random(30)
+
+        for point in sample:
+            assert_array_less(point, u_bounds) 
+            assert_array_less(l_bounds, point) 
+
+    @pytest.mark.parametrize("u_bounds", [[-1, -2, -1], [1, 2, 1]])
+    def test_sample_inside_upper_bounds(self, u_bounds):
+        radius = 0.2
+        l_bounds=[-3, -3, -2]
+        engine = self.qmce(
+            d=3, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds
+        )
+        sample = engine.random(30)
+
+        for point in sample:
+            assert_array_less(point, u_bounds) 
+            assert_array_less(l_bounds, point) 
+
+    def test_inconsistent_bound_value(self):
+        radius = 0.2
+        l_bounds=[3, 2, 1]
+        u_bounds=[-1, -2, -1]
+        with pytest.raises(
+            ValueError, 
+            match="Bounds are not consistent 'l_bounds' < 'u_bounds'"):
+            self.qmce(d=3, radius=radius, l_bounds=l_bounds, u_bounds=u_bounds)
+
+    @pytest.mark.parametrize("u_bounds", [[-1, -2, -1], [-1, -2]])
+    @pytest.mark.parametrize("l_bounds", [[3, 2]])
+    def test_inconsistent_bounds(self, u_bounds, l_bounds):
+        radius = 0.2
+        with pytest.raises(
+            ValueError, 
+            match="'l_bounds' and 'u_bounds' must be broadcastable and respect" 
+            " the sample dimension"):
+            self.qmce(
+                d=3, radius=radius, 
+                l_bounds=l_bounds, u_bounds=u_bounds
+            )
+        
+    def test_raises(self):
+        message = r"'toto' is not a valid hypersphere sampling"
+        with pytest.raises(ValueError, match=message):
+            qmc.PoissonDisk(1, hypersphere="toto")
+
+
+class TestMultinomialQMC:
+    def test_validations(self):
+        # negative Ps
+        p = np.array([0.12, 0.26, -0.05, 0.35, 0.22])
+        with pytest.raises(ValueError, match=r"Elements of pvals must "
+                                             r"be non-negative."):
+            qmc.MultinomialQMC(p, n_trials=10)
+
+        # sum of P too large
+        p = np.array([0.12, 0.26, 0.1, 0.35, 0.22])
+        message = r"Elements of pvals must sum to 1."
+        with pytest.raises(ValueError, match=message):
+            qmc.MultinomialQMC(p, n_trials=10)
+
+        p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
+
+        message = r"Dimension of `engine` must be 1."
+        with pytest.raises(ValueError, match=message):
+            qmc.MultinomialQMC(p, n_trials=10, engine=qmc.Sobol(d=2))
+
+        message = r"`engine` must be an instance of..."
+        with pytest.raises(ValueError, match=message):
+            qmc.MultinomialQMC(p, n_trials=10, engine=np.random.default_rng())
+
+    @pytest.mark.filterwarnings('ignore::UserWarning')
+    def test_MultinomialBasicDraw(self):
+        rng = np.random.default_rng(6955663962957011631562466584467607969)
+        p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
+        n_trials = 100
+        expected = np.atleast_2d(n_trials * p).astype(int)
+        # preserve use of legacy keyword during SPEC 7 transition
+        engine = qmc.MultinomialQMC(p, n_trials=n_trials, seed=rng)
+        assert_allclose(engine.random(1), expected, atol=1)
+
+    def test_MultinomialDistribution(self):
+        rng = np.random.default_rng(77797854505813727292048130876699859000)
+        p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
+        engine = qmc.MultinomialQMC(p, n_trials=8192, rng=rng)
+        draws = engine.random(1)
+        assert_allclose(draws / np.sum(draws), np.atleast_2d(p), atol=1e-4)
+
+    def test_FindIndex(self):
+        p_cumulative = np.array([0.1, 0.4, 0.45, 0.6, 0.75, 0.9, 0.99, 1.0])
+        size = len(p_cumulative)
+        assert_equal(_test_find_index(p_cumulative, size, 0.0), 0)
+        assert_equal(_test_find_index(p_cumulative, size, 0.4), 2)
+        assert_equal(_test_find_index(p_cumulative, size, 0.44999), 2)
+        assert_equal(_test_find_index(p_cumulative, size, 0.45001), 3)
+        assert_equal(_test_find_index(p_cumulative, size, 1.0), size - 1)
+
+    @pytest.mark.filterwarnings('ignore::UserWarning')
+    def test_other_engine(self):
+        # same as test_MultinomialBasicDraw with different engine
+        rng = np.random.default_rng(283753519042773243071753037669078065412)
+        p = np.array([0.12, 0.26, 0.05, 0.35, 0.22])
+        n_trials = 100
+        expected = np.atleast_2d(n_trials * p).astype(int)
+        base_engine = qmc.Sobol(1, scramble=True, rng=rng)
+        engine = qmc.MultinomialQMC(p, n_trials=n_trials, engine=base_engine,
+                                    rng=rng)
+        assert_allclose(engine.random(1), expected, atol=1)
+
+
+class TestNormalQMC:
+    def test_NormalQMC(self):
+        # d = 1
+        engine = qmc.MultivariateNormalQMC(mean=np.zeros(1))
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 1))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 1))
+        # d = 2
+        engine = qmc.MultivariateNormalQMC(mean=np.zeros(2))
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 2))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 2))
+
+    def test_NormalQMCInvTransform(self):
+        # d = 1
+        engine = qmc.MultivariateNormalQMC(
+            mean=np.zeros(1), inv_transform=True)
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 1))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 1))
+        # d = 2
+        engine = qmc.MultivariateNormalQMC(
+            mean=np.zeros(2), inv_transform=True)
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 2))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 2))
+
+    def test_NormalQMCSeeded(self):
+        # test even dimension
+        rng = np.random.default_rng(274600237797326520096085022671371676017)
+        # preserve use of legacy keyword during SPEC 7 transition
+        engine = qmc.MultivariateNormalQMC(
+            mean=np.zeros(2), inv_transform=False, seed=rng)
+        samples = engine.random(n=2)
+        samples_expected = np.array([[-0.932001, -0.522923],
+                                     [-1.477655, 0.846851]])
+        assert_allclose(samples, samples_expected, atol=1e-4)
+
+        # test odd dimension
+        rng = np.random.default_rng(274600237797326520096085022671371676017)
+        engine = qmc.MultivariateNormalQMC(
+            mean=np.zeros(3), inv_transform=False, rng=rng)
+        samples = engine.random(n=2)
+        samples_expected = np.array([[-0.932001, -0.522923, 0.036578],
+                                     [-1.778011, 0.912428, -0.065421]])
+        assert_allclose(samples, samples_expected, atol=1e-4)
+
+        # same test with another engine
+        rng = np.random.default_rng(274600237797326520096085022671371676017)
+        base_engine = qmc.Sobol(4, scramble=True, rng=rng)
+        engine = qmc.MultivariateNormalQMC(
+            mean=np.zeros(3), inv_transform=False,
+            engine=base_engine, rng=rng
+        )
+        samples = engine.random(n=2)
+        samples_expected = np.array([[-0.932001, -0.522923, 0.036578],
+                                     [-1.778011, 0.912428, -0.065421]])
+        assert_allclose(samples, samples_expected, atol=1e-4)
+
+    def test_NormalQMCSeededInvTransform(self):
+        # test even dimension
+        rng = np.random.default_rng(288527772707286126646493545351112463929)
+        engine = qmc.MultivariateNormalQMC(
+            mean=np.zeros(2), rng=rng, inv_transform=True)
+        samples = engine.random(n=2)
+        samples_expected = np.array([[-0.913237, -0.964026],
+                                     [0.255904, 0.003068]])
+        assert_allclose(samples, samples_expected, atol=1e-4)
+
+        # test odd dimension
+        rng = np.random.default_rng(288527772707286126646493545351112463929)
+        engine = qmc.MultivariateNormalQMC(
+            mean=np.zeros(3), rng=rng, inv_transform=True)
+        samples = engine.random(n=2)
+        samples_expected = np.array([[-0.913237, -0.964026, 0.355501],
+                                     [0.699261, 2.90213 , -0.6418]])
+        assert_allclose(samples, samples_expected, atol=1e-4)
+
+    def test_other_engine(self):
+        for d in (0, 1, 2):
+            base_engine = qmc.Sobol(d=d, scramble=False)
+            engine = qmc.MultivariateNormalQMC(mean=np.zeros(d),
+                                               engine=base_engine,
+                                               inv_transform=True)
+            samples = engine.random()
+            assert_equal(samples.shape, (1, d))
+
+    def test_NormalQMCShapiro(self):
+        rng = np.random.default_rng(13242)
+        engine = qmc.MultivariateNormalQMC(mean=np.zeros(2), rng=rng)
+        samples = engine.random(n=256)
+        assert all(np.abs(samples.mean(axis=0)) < 1e-2)
+        assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
+        # perform Shapiro-Wilk test for normality
+        for i in (0, 1):
+            _, pval = shapiro(samples[:, i])
+            assert pval > 0.9
+        # make sure samples are uncorrelated
+        cov = np.cov(samples.transpose())
+        assert np.abs(cov[0, 1]) < 1e-2
+
+    def test_NormalQMCShapiroInvTransform(self):
+        rng = np.random.default_rng(32344554)
+        engine = qmc.MultivariateNormalQMC(
+            mean=np.zeros(2), inv_transform=True, rng=rng)
+        samples = engine.random(n=256)
+        assert all(np.abs(samples.mean(axis=0)) < 1e-2)
+        assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
+        # perform Shapiro-Wilk test for normality
+        for i in (0, 1):
+            _, pval = shapiro(samples[:, i])
+            assert pval > 0.9
+        # make sure samples are uncorrelated
+        cov = np.cov(samples.transpose())
+        assert np.abs(cov[0, 1]) < 1e-2
+
+
+class TestMultivariateNormalQMC:
+
+    def test_validations(self):
+
+        message = r"Dimension of `engine` must be consistent"
+        with pytest.raises(ValueError, match=message):
+            qmc.MultivariateNormalQMC([0], engine=qmc.Sobol(d=2))
+
+        message = r"Dimension of `engine` must be consistent"
+        with pytest.raises(ValueError, match=message):
+            qmc.MultivariateNormalQMC([0, 0, 0], engine=qmc.Sobol(d=4))
+
+        message = r"`engine` must be an instance of..."
+        with pytest.raises(ValueError, match=message):
+            qmc.MultivariateNormalQMC([0, 0], engine=np.random.default_rng())
+
+        message = r"Covariance matrix not PSD."
+        with pytest.raises(ValueError, match=message):
+            qmc.MultivariateNormalQMC([0, 0], [[1, 2], [2, 1]])
+
+        message = r"Covariance matrix is not symmetric."
+        with pytest.raises(ValueError, match=message):
+            qmc.MultivariateNormalQMC([0, 0], [[1, 0], [2, 1]])
+
+        message = r"Dimension mismatch between mean and covariance."
+        with pytest.raises(ValueError, match=message):
+            qmc.MultivariateNormalQMC([0], [[1, 0], [0, 1]])
+
+    def test_MultivariateNormalQMCNonPD(self):
+        # try with non-pd but psd cov; should work
+        engine = qmc.MultivariateNormalQMC(
+            [0, 0, 0], [[1, 0, 1], [0, 1, 1], [1, 1, 2]],
+        )
+        assert engine._corr_matrix is not None
+
+    def test_MultivariateNormalQMC(self):
+        # d = 1 scalar
+        engine = qmc.MultivariateNormalQMC(mean=0, cov=5)
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 1))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 1))
+
+        # d = 2 list
+        engine = qmc.MultivariateNormalQMC(mean=[0, 1], cov=[[1, 0], [0, 1]])
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 2))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 2))
+
+        # d = 3 np.array
+        mean = np.array([0, 1, 2])
+        cov = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
+        engine = qmc.MultivariateNormalQMC(mean, cov)
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 3))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 3))
+
+    def test_MultivariateNormalQMCInvTransform(self):
+        # d = 1 scalar
+        engine = qmc.MultivariateNormalQMC(mean=0, cov=5, inv_transform=True)
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 1))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 1))
+
+        # d = 2 list
+        engine = qmc.MultivariateNormalQMC(
+            mean=[0, 1], cov=[[1, 0], [0, 1]], inv_transform=True,
+        )
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 2))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 2))
+
+        # d = 3 np.array
+        mean = np.array([0, 1, 2])
+        cov = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
+        engine = qmc.MultivariateNormalQMC(mean, cov, inv_transform=True)
+        samples = engine.random()
+        assert_equal(samples.shape, (1, 3))
+        samples = engine.random(n=5)
+        assert_equal(samples.shape, (5, 3))
+
+    def test_MultivariateNormalQMCSeeded(self):
+        # test even dimension
+        rng = np.random.default_rng(180182791534511062935571481899241825000)
+        a = rng.standard_normal((2, 2))
+        A = a @ a.transpose() + np.diag(rng.random(2))
+        engine = qmc.MultivariateNormalQMC(np.array([0, 0]), A,
+                                           inv_transform=False, rng=rng)
+        samples = engine.random(n=2)
+        samples_expected = np.array([[-0.64419, -0.882413],
+                                     [0.837199, 2.045301]])
+        assert_allclose(samples, samples_expected, atol=1e-4)
+
+        # test odd dimension
+        rng = np.random.default_rng(180182791534511062935571481899241825000)
+        a = rng.standard_normal((3, 3))
+        A = a @ a.transpose() + np.diag(rng.random(3))
+        engine = qmc.MultivariateNormalQMC(np.array([0, 0, 0]), A,
+                                           inv_transform=False, rng=rng)
+        samples = engine.random(n=2)
+        samples_expected = np.array([[-0.693853, -1.265338, -0.088024],
+                                     [1.620193, 2.679222, 0.457343]])
+        assert_allclose(samples, samples_expected, atol=1e-4)
+
+    def test_MultivariateNormalQMCSeededInvTransform(self):
+        # test even dimension
+        rng = np.random.default_rng(224125808928297329711992996940871155974)
+        a = rng.standard_normal((2, 2))
+        A = a @ a.transpose() + np.diag(rng.random(2))
+        engine = qmc.MultivariateNormalQMC(
+            np.array([0, 0]), A, rng=rng, inv_transform=True
+        )
+        samples = engine.random(n=2)
+        samples_expected = np.array([[0.682171, -3.114233],
+                                     [-0.098463, 0.668069]])
+        assert_allclose(samples, samples_expected, atol=1e-4)
+
+        # test odd dimension
+        rng = np.random.default_rng(224125808928297329711992996940871155974)
+        a = rng.standard_normal((3, 3))
+        A = a @ a.transpose() + np.diag(rng.random(3))
+        engine = qmc.MultivariateNormalQMC(
+            np.array([0, 0, 0]), A, rng=rng, inv_transform=True
+        )
+        samples = engine.random(n=2)
+        samples_expected = np.array([[0.988061, -1.644089, -0.877035],
+                                     [-1.771731, 1.096988, 2.024744]])
+        assert_allclose(samples, samples_expected, atol=1e-4)
+
+    def test_MultivariateNormalQMCShapiro(self):
+        # test the standard case
+        rng = np.random.default_rng(188960007281846377164494575845971640)
+        engine = qmc.MultivariateNormalQMC(
+            mean=[0, 0], cov=[[1, 0], [0, 1]], rng=rng
+        )
+        samples = engine.random(n=256)
+        assert all(np.abs(samples.mean(axis=0)) < 1e-2)
+        assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
+        # perform Shapiro-Wilk test for normality
+        for i in (0, 1):
+            _, pval = shapiro(samples[:, i])
+            assert pval > 0.9
+        # make sure samples are uncorrelated
+        cov = np.cov(samples.transpose())
+        assert np.abs(cov[0, 1]) < 1e-2
+
+        # test the correlated, non-zero mean case
+        engine = qmc.MultivariateNormalQMC(
+            mean=[1.0, 2.0], cov=[[1.5, 0.5], [0.5, 1.5]], rng=rng
+        )
+        samples = engine.random(n=256)
+        assert all(np.abs(samples.mean(axis=0) - [1, 2]) < 1e-2)
+        assert all(np.abs(samples.std(axis=0) - np.sqrt(1.5)) < 1e-2)
+        # perform Shapiro-Wilk test for normality
+        for i in (0, 1):
+            _, pval = shapiro(samples[:, i])
+            assert pval > 0.9
+        # check covariance
+        cov = np.cov(samples.transpose())
+        assert np.abs(cov[0, 1] - 0.5) < 1e-2
+
+    def test_MultivariateNormalQMCShapiroInvTransform(self):
+        # test the standard case
+        rng = np.random.default_rng(200089821034563288698994840831440331329)
+        engine = qmc.MultivariateNormalQMC(
+            mean=[0, 0], cov=[[1, 0], [0, 1]], rng=rng, inv_transform=True
+        )
+        samples = engine.random(n=256)
+        assert all(np.abs(samples.mean(axis=0)) < 1e-2)
+        assert all(np.abs(samples.std(axis=0) - 1) < 1e-2)
+        # perform Shapiro-Wilk test for normality
+        for i in (0, 1):
+            _, pval = shapiro(samples[:, i])
+            assert pval > 0.9
+        # make sure samples are uncorrelated
+        cov = np.cov(samples.transpose())
+        assert np.abs(cov[0, 1]) < 1e-2
+
+        # test the correlated, non-zero mean case
+        engine = qmc.MultivariateNormalQMC(
+            mean=[1.0, 2.0],
+            cov=[[1.5, 0.5], [0.5, 1.5]],
+            rng=rng,
+            inv_transform=True,
+        )
+        samples = engine.random(n=256)
+        assert all(np.abs(samples.mean(axis=0) - [1, 2]) < 1e-2)
+        assert all(np.abs(samples.std(axis=0) - np.sqrt(1.5)) < 1e-2)
+        # perform Shapiro-Wilk test for normality
+        for i in (0, 1):
+            _, pval = shapiro(samples[:, i])
+            assert pval > 0.9
+        # check covariance
+        cov = np.cov(samples.transpose())
+        assert np.abs(cov[0, 1] - 0.5) < 1e-2
+
+    def test_MultivariateNormalQMCDegenerate(self):
+        # X, Y iid standard Normal and Z = X + Y, random vector (X, Y, Z)
+        rng = np.random.default_rng(16320637417581448357869821654290448620)
+        engine = qmc.MultivariateNormalQMC(
+            mean=[0.0, 0.0, 0.0],
+            cov=[[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 2.0]],
+            rng=rng,
+        )
+        samples = engine.random(n=512)
+        assert all(np.abs(samples.mean(axis=0)) < 1e-2)
+        assert np.abs(np.std(samples[:, 0]) - 1) < 1e-2
+        assert np.abs(np.std(samples[:, 1]) - 1) < 1e-2
+        assert np.abs(np.std(samples[:, 2]) - np.sqrt(2)) < 1e-2
+        for i in (0, 1, 2):
+            _, pval = shapiro(samples[:, i])
+            assert pval > 0.8
+        cov = np.cov(samples.transpose())
+        assert np.abs(cov[0, 1]) < 1e-2
+        assert np.abs(cov[0, 2] - 1) < 1e-2
+        # check to see if X + Y = Z almost exactly
+        assert all(np.abs(samples[:, 0] + samples[:, 1] - samples[:, 2])
+                   < 1e-5)
+
+
+class TestLloyd:
+    def test_lloyd(self):
+        # quite sensible seed as it can go up before going further down
+        rng = np.random.RandomState(1809831)
+        sample = rng.uniform(0, 1, size=(128, 2))
+        base_l1 = _l1_norm(sample)
+        base_l2 = l2_norm(sample)
+
+        for _ in range(4):
+            sample_lloyd = _lloyd_centroidal_voronoi_tessellation(
+                    sample, maxiter=1,
+            )
+            curr_l1 = _l1_norm(sample_lloyd)
+            curr_l2 = l2_norm(sample_lloyd)
+
+            # higher is better for the distance measures
+            assert base_l1 < curr_l1
+            assert base_l2 < curr_l2
+
+            base_l1 = curr_l1
+            base_l2 = curr_l2
+
+            sample = sample_lloyd
+
+    def test_lloyd_non_mutating(self):
+        """
+        Verify that the input samples are not mutated in place and that they do
+        not share memory with the output.
+        """
+        sample_orig = np.array([[0.1, 0.1],
+                                [0.1, 0.2],
+                                [0.2, 0.1],
+                                [0.2, 0.2]])
+        sample_copy = sample_orig.copy()
+        new_sample = _lloyd_centroidal_voronoi_tessellation(
+            sample=sample_orig
+        )
+        assert_allclose(sample_orig, sample_copy)
+        assert not np.may_share_memory(sample_orig, new_sample)
+
+    def test_lloyd_errors(self):
+        with pytest.raises(ValueError, match=r"`sample` is not a 2D array"):
+            sample = [0, 1, 0.5]
+            _lloyd_centroidal_voronoi_tessellation(sample)
+
+        msg = r"`sample` dimension is not >= 2"
+        with pytest.raises(ValueError, match=msg):
+            sample = [[0], [0.4], [1]]
+            _lloyd_centroidal_voronoi_tessellation(sample)
+
+        msg = r"`sample` is not in unit hypercube"
+        with pytest.raises(ValueError, match=msg):
+            sample = [[-1.1, 0], [0.1, 0.4], [1, 2]]
+            _lloyd_centroidal_voronoi_tessellation(sample)
+
+
+# mindist
+def l2_norm(sample):
+    return distance.pdist(sample).min()
+
+
+@pytest.mark.parametrize('engine', [qmc.Halton, qmc.Sobol,
+                                    qmc.LatinHypercube, qmc.PoissonDisk])
+def test_deterministic(engine):
+    seed_number = 2359834584
+
+    rng = np.random.RandomState(seed_number)
+    res1 = engine(d=1, seed=rng).random(4)
+    rng = np.random.RandomState(seed_number)
+    res2 = engine(d=1, seed=rng).random(4)
+    assert_equal(res1, res2)
+
+    rng = np.random.default_rng(seed_number)
+    res1 = engine(d=1, seed=rng).random(4)
+    res2 = engine(d=1, rng=seed_number).random(4)
+    assert_equal(res1, res2)
+    rng = np.random.default_rng(seed_number)
+    res3 = engine(d=1, rng=rng).random(4)
+    assert_equal(res2, res1)
+    assert_equal(res3, res1)
+
+    message = "got multiple values for argument now known as `rng`"
+    with pytest.raises(TypeError, match=message):
+        engine(d=1, rng=seed_number, seed=seed_number)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_rank.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_rank.py
new file mode 100644
index 0000000000000000000000000000000000000000..08f6e13585dc61665ec6b6e733de87462e90002b
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_rank.py
@@ -0,0 +1,338 @@
+import numpy as np
+from numpy.testing import assert_equal, assert_array_equal
+import pytest
+
+from scipy.conftest import skip_xp_invalid_arg
+from scipy.stats import rankdata, tiecorrect
+from scipy._lib._util import np_long
+
+
+class TestTieCorrect:
+
+    def test_empty(self):
+        """An empty array requires no correction, should return 1.0."""
+        ranks = np.array([], dtype=np.float64)
+        c = tiecorrect(ranks)
+        assert_equal(c, 1.0)
+
+    def test_one(self):
+        """A single element requires no correction, should return 1.0."""
+        ranks = np.array([1.0], dtype=np.float64)
+        c = tiecorrect(ranks)
+        assert_equal(c, 1.0)
+
+    def test_no_correction(self):
+        """Arrays with no ties require no correction."""
+        ranks = np.arange(2.0)
+        c = tiecorrect(ranks)
+        assert_equal(c, 1.0)
+        ranks = np.arange(3.0)
+        c = tiecorrect(ranks)
+        assert_equal(c, 1.0)
+
+    def test_basic(self):
+        """Check a few basic examples of the tie correction factor."""
+        # One tie of two elements
+        ranks = np.array([1.0, 2.5, 2.5])
+        c = tiecorrect(ranks)
+        T = 2.0
+        N = ranks.size
+        expected = 1.0 - (T**3 - T) / (N**3 - N)
+        assert_equal(c, expected)
+
+        # One tie of two elements (same as above, but tie is not at the end)
+        ranks = np.array([1.5, 1.5, 3.0])
+        c = tiecorrect(ranks)
+        T = 2.0
+        N = ranks.size
+        expected = 1.0 - (T**3 - T) / (N**3 - N)
+        assert_equal(c, expected)
+
+        # One tie of three elements
+        ranks = np.array([1.0, 3.0, 3.0, 3.0])
+        c = tiecorrect(ranks)
+        T = 3.0
+        N = ranks.size
+        expected = 1.0 - (T**3 - T) / (N**3 - N)
+        assert_equal(c, expected)
+
+        # Two ties, lengths 2 and 3.
+        ranks = np.array([1.5, 1.5, 4.0, 4.0, 4.0])
+        c = tiecorrect(ranks)
+        T1 = 2.0
+        T2 = 3.0
+        N = ranks.size
+        expected = 1.0 - ((T1**3 - T1) + (T2**3 - T2)) / (N**3 - N)
+        assert_equal(c, expected)
+
+    def test_overflow(self):
+        ntie, k = 2000, 5
+        a = np.repeat(np.arange(k), ntie)
+        n = a.size  # ntie * k
+        out = tiecorrect(rankdata(a))
+        assert_equal(out, 1.0 - k * (ntie**3 - ntie) / float(n**3 - n))
+
+
+class TestRankData:
+
+    def test_empty(self):
+        """stats.rankdata([]) should return an empty array."""
+        a = np.array([], dtype=int)
+        r = rankdata(a)
+        assert_array_equal(r, np.array([], dtype=np.float64))
+        r = rankdata([])
+        assert_array_equal(r, np.array([], dtype=np.float64))
+
+    @pytest.mark.parametrize("shape", [(0, 1, 2)])
+    @pytest.mark.parametrize("axis", [None, *range(3)])
+    def test_empty_multidim(self, shape, axis):
+        a = np.empty(shape, dtype=int)
+        r = rankdata(a, axis=axis)
+        expected_shape = (0,) if axis is None else shape
+        assert_equal(r.shape, expected_shape)
+        assert_equal(r.dtype, np.float64)
+
+    def test_one(self):
+        """Check stats.rankdata with an array of length 1."""
+        data = [100]
+        a = np.array(data, dtype=int)
+        r = rankdata(a)
+        assert_array_equal(r, np.array([1.0], dtype=np.float64))
+        r = rankdata(data)
+        assert_array_equal(r, np.array([1.0], dtype=np.float64))
+
+    def test_basic(self):
+        """Basic tests of stats.rankdata."""
+        data = [100, 10, 50]
+        expected = np.array([3.0, 1.0, 2.0], dtype=np.float64)
+        a = np.array(data, dtype=int)
+        r = rankdata(a)
+        assert_array_equal(r, expected)
+        r = rankdata(data)
+        assert_array_equal(r, expected)
+
+        data = [40, 10, 30, 10, 50]
+        expected = np.array([4.0, 1.5, 3.0, 1.5, 5.0], dtype=np.float64)
+        a = np.array(data, dtype=int)
+        r = rankdata(a)
+        assert_array_equal(r, expected)
+        r = rankdata(data)
+        assert_array_equal(r, expected)
+
+        data = [20, 20, 20, 10, 10, 10]
+        expected = np.array([5.0, 5.0, 5.0, 2.0, 2.0, 2.0], dtype=np.float64)
+        a = np.array(data, dtype=int)
+        r = rankdata(a)
+        assert_array_equal(r, expected)
+        r = rankdata(data)
+        assert_array_equal(r, expected)
+        # The docstring states explicitly that the argument is flattened.
+        a2d = a.reshape(2, 3)
+        r = rankdata(a2d)
+        assert_array_equal(r, expected)
+
+    @skip_xp_invalid_arg
+    def test_rankdata_object_string(self):
+
+        def min_rank(a):
+            return [1 + sum(i < j for i in a) for j in a]
+
+        def max_rank(a):
+            return [sum(i <= j for i in a) for j in a]
+
+        def ordinal_rank(a):
+            return min_rank([(x, i) for i, x in enumerate(a)])
+
+        def average_rank(a):
+            return [(i + j) / 2.0 for i, j in zip(min_rank(a), max_rank(a))]
+
+        def dense_rank(a):
+            b = np.unique(a)
+            return [1 + sum(i < j for i in b) for j in a]
+
+        rankf = dict(min=min_rank, max=max_rank, ordinal=ordinal_rank,
+                     average=average_rank, dense=dense_rank)
+
+        def check_ranks(a):
+            for method in 'min', 'max', 'dense', 'ordinal', 'average':
+                out = rankdata(a, method=method)
+                assert_array_equal(out, rankf[method](a))
+
+        val = ['foo', 'bar', 'qux', 'xyz', 'abc', 'efg', 'ace', 'qwe', 'qaz']
+        check_ranks(np.random.choice(val, 200))
+        check_ranks(np.random.choice(val, 200).astype('object'))
+
+        val = np.array([0, 1, 2, 2.718, 3, 3.141], dtype='object')
+        check_ranks(np.random.choice(val, 200).astype('object'))
+
+    def test_large_int(self):
+        data = np.array([2**60, 2**60+1], dtype=np.uint64)
+        r = rankdata(data)
+        assert_array_equal(r, [1.0, 2.0])
+
+        data = np.array([2**60, 2**60+1], dtype=np.int64)
+        r = rankdata(data)
+        assert_array_equal(r, [1.0, 2.0])
+
+        data = np.array([2**60, -2**60+1], dtype=np.int64)
+        r = rankdata(data)
+        assert_array_equal(r, [2.0, 1.0])
+
+    def test_big_tie(self):
+        for n in [10000, 100000, 1000000]:
+            data = np.ones(n, dtype=int)
+            r = rankdata(data)
+            expected_rank = 0.5 * (n + 1)
+            assert_array_equal(r, expected_rank * data,
+                               "test failed with n=%d" % n)
+
+    def test_axis(self):
+        data = [[0, 2, 1],
+                [4, 2, 2]]
+        expected0 = [[1., 1.5, 1.],
+                     [2., 1.5, 2.]]
+        r0 = rankdata(data, axis=0)
+        assert_array_equal(r0, expected0)
+        expected1 = [[1., 3., 2.],
+                     [3., 1.5, 1.5]]
+        r1 = rankdata(data, axis=1)
+        assert_array_equal(r1, expected1)
+
+    methods = ["average", "min", "max", "dense", "ordinal"]
+    dtypes = [np.float64] + [np_long]*4
+
+    @pytest.mark.parametrize("axis", [0, 1])
+    @pytest.mark.parametrize("method, dtype", zip(methods, dtypes))
+    def test_size_0_axis(self, axis, method, dtype):
+        shape = (3, 0)
+        data = np.zeros(shape)
+        r = rankdata(data, method=method, axis=axis)
+        assert_equal(r.shape, shape)
+        assert_equal(r.dtype, dtype)
+
+    @pytest.mark.parametrize('axis', range(3))
+    @pytest.mark.parametrize('method', methods)
+    def test_nan_policy_omit_3d(self, axis, method):
+        shape = (20, 21, 22)
+        rng = np.random.RandomState(23983242)
+
+        a = rng.random(size=shape)
+        i = rng.random(size=shape) < 0.4
+        j = rng.random(size=shape) < 0.1
+        k = rng.random(size=shape) < 0.1
+        a[i] = np.nan
+        a[j] = -np.inf
+        a[k] - np.inf
+
+        def rank_1d_omit(a, method):
+            out = np.zeros_like(a)
+            i = np.isnan(a)
+            a_compressed = a[~i]
+            res = rankdata(a_compressed, method)
+            out[~i] = res
+            out[i] = np.nan
+            return out
+
+        def rank_omit(a, method, axis):
+            return np.apply_along_axis(lambda a: rank_1d_omit(a, method),
+                                       axis, a)
+
+        res = rankdata(a, method, axis=axis, nan_policy='omit')
+        res0 = rank_omit(a, method, axis=axis)
+
+        assert_array_equal(res, res0)
+
+    def test_nan_policy_2d_axis_none(self):
+        # 2 2d-array test with axis=None
+        data = [[0, np.nan, 3],
+                [4, 2, np.nan],
+                [1, 2, 2]]
+        assert_array_equal(rankdata(data, axis=None, nan_policy='omit'),
+                           [1., np.nan, 6., 7., 4., np.nan, 2., 4., 4.])
+        assert_array_equal(rankdata(data, axis=None, nan_policy='propagate'),
+                           [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan,
+                            np.nan, np.nan, np.nan])
+
+    def test_nan_policy_raise(self):
+        # 1 1d-array test
+        data = [0, 2, 3, -2, np.nan, np.nan]
+        with pytest.raises(ValueError, match="The input contains nan"):
+            rankdata(data, nan_policy='raise')
+
+        # 2 2d-array test
+        data = [[0, np.nan, 3],
+                [4, 2, np.nan],
+                [np.nan, 2, 2]]
+
+        with pytest.raises(ValueError, match="The input contains nan"):
+            rankdata(data, axis=0, nan_policy="raise")
+
+        with pytest.raises(ValueError, match="The input contains nan"):
+            rankdata(data, axis=1, nan_policy="raise")
+
+    def test_nan_policy_propagate(self):
+        # 1 1d-array test
+        data = [0, 2, 3, -2, np.nan, np.nan]
+        assert_array_equal(rankdata(data, nan_policy='propagate'),
+                           [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan])
+
+        # 2 2d-array test
+        data = [[0, np.nan, 3],
+                [4, 2, np.nan],
+                [1, 2, 2]]
+        assert_array_equal(rankdata(data, axis=0, nan_policy='propagate'),
+                           [[1, np.nan, np.nan],
+                            [3, np.nan, np.nan],
+                            [2, np.nan, np.nan]])
+        assert_array_equal(rankdata(data, axis=1, nan_policy='propagate'),
+                           [[np.nan, np.nan, np.nan],
+                            [np.nan, np.nan, np.nan],
+                            [1, 2.5, 2.5]])
+
+
+_cases = (
+    # values, method, expected
+    ([], 'average', []),
+    ([], 'min', []),
+    ([], 'max', []),
+    ([], 'dense', []),
+    ([], 'ordinal', []),
+    #
+    ([100], 'average', [1.0]),
+    ([100], 'min', [1.0]),
+    ([100], 'max', [1.0]),
+    ([100], 'dense', [1.0]),
+    ([100], 'ordinal', [1.0]),
+    #
+    ([100, 100, 100], 'average', [2.0, 2.0, 2.0]),
+    ([100, 100, 100], 'min', [1.0, 1.0, 1.0]),
+    ([100, 100, 100], 'max', [3.0, 3.0, 3.0]),
+    ([100, 100, 100], 'dense', [1.0, 1.0, 1.0]),
+    ([100, 100, 100], 'ordinal', [1.0, 2.0, 3.0]),
+    #
+    ([100, 300, 200], 'average', [1.0, 3.0, 2.0]),
+    ([100, 300, 200], 'min', [1.0, 3.0, 2.0]),
+    ([100, 300, 200], 'max', [1.0, 3.0, 2.0]),
+    ([100, 300, 200], 'dense', [1.0, 3.0, 2.0]),
+    ([100, 300, 200], 'ordinal', [1.0, 3.0, 2.0]),
+    #
+    ([100, 200, 300, 200], 'average', [1.0, 2.5, 4.0, 2.5]),
+    ([100, 200, 300, 200], 'min', [1.0, 2.0, 4.0, 2.0]),
+    ([100, 200, 300, 200], 'max', [1.0, 3.0, 4.0, 3.0]),
+    ([100, 200, 300, 200], 'dense', [1.0, 2.0, 3.0, 2.0]),
+    ([100, 200, 300, 200], 'ordinal', [1.0, 2.0, 4.0, 3.0]),
+    #
+    ([100, 200, 300, 200, 100], 'average', [1.5, 3.5, 5.0, 3.5, 1.5]),
+    ([100, 200, 300, 200, 100], 'min', [1.0, 3.0, 5.0, 3.0, 1.0]),
+    ([100, 200, 300, 200, 100], 'max', [2.0, 4.0, 5.0, 4.0, 2.0]),
+    ([100, 200, 300, 200, 100], 'dense', [1.0, 2.0, 3.0, 2.0, 1.0]),
+    ([100, 200, 300, 200, 100], 'ordinal', [1.0, 3.0, 5.0, 4.0, 2.0]),
+    #
+    ([10] * 30, 'ordinal', np.arange(1.0, 31.0)),
+)
+
+
+def test_cases():
+    for values, method, expected in _cases:
+        r = rankdata(values, method=method)
+        assert_array_equal(r, expected)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_relative_risk.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_relative_risk.py
new file mode 100644
index 0000000000000000000000000000000000000000..b75e64d929f319465b1f1d62af4fb2096c2ab2ac
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_relative_risk.py
@@ -0,0 +1,95 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+from scipy.stats.contingency import relative_risk
+
+
+# Test just the calculation of the relative risk, including edge
+# cases that result in a relative risk of 0, inf or nan.
+@pytest.mark.parametrize(
+    'exposed_cases, exposed_total, control_cases, control_total, expected_rr',
+    [(1, 4, 3, 8, 0.25 / 0.375),
+     (0, 10, 5, 20, 0),
+     (0, 10, 0, 20, np.nan),
+     (5, 15, 0, 20, np.inf)]
+)
+def test_relative_risk(exposed_cases, exposed_total,
+                       control_cases, control_total, expected_rr):
+    result = relative_risk(exposed_cases, exposed_total,
+                           control_cases, control_total)
+    assert_allclose(result.relative_risk, expected_rr, rtol=1e-13)
+
+
+def test_relative_risk_confidence_interval():
+    result = relative_risk(exposed_cases=16, exposed_total=128,
+                           control_cases=24, control_total=256)
+    rr = result.relative_risk
+    ci = result.confidence_interval(confidence_level=0.95)
+    # The corresponding calculation in R using the epitools package.
+    #
+    # > library(epitools)
+    # > c <- matrix(c(232, 112, 24, 16), nrow=2)
+    # > result <- riskratio(c)
+    # > result$measure
+    #               risk ratio with 95% C.I.
+    # Predictor  estimate     lower    upper
+    #   Exposed1 1.000000        NA       NA
+    #   Exposed2 1.333333 0.7347317 2.419628
+    #
+    # The last line is the result that we want.
+    assert_allclose(rr, 4/3)
+    assert_allclose((ci.low, ci.high), (0.7347317, 2.419628), rtol=5e-7)
+
+
+def test_relative_risk_ci_conflevel0():
+    result = relative_risk(exposed_cases=4, exposed_total=12,
+                           control_cases=5, control_total=30)
+    rr = result.relative_risk
+    assert_allclose(rr, 2.0, rtol=1e-14)
+    ci = result.confidence_interval(0)
+    assert_allclose((ci.low, ci.high), (2.0, 2.0), rtol=1e-12)
+
+
+def test_relative_risk_ci_conflevel1():
+    result = relative_risk(exposed_cases=4, exposed_total=12,
+                           control_cases=5, control_total=30)
+    ci = result.confidence_interval(1)
+    assert_equal((ci.low, ci.high), (0, np.inf))
+
+
+def test_relative_risk_ci_edge_cases_00():
+    result = relative_risk(exposed_cases=0, exposed_total=12,
+                           control_cases=0, control_total=30)
+    assert_equal(result.relative_risk, np.nan)
+    ci = result.confidence_interval()
+    assert_equal((ci.low, ci.high), (np.nan, np.nan))
+
+
+def test_relative_risk_ci_edge_cases_01():
+    result = relative_risk(exposed_cases=0, exposed_total=12,
+                           control_cases=1, control_total=30)
+    assert_equal(result.relative_risk, 0)
+    ci = result.confidence_interval()
+    assert_equal((ci.low, ci.high), (0.0, np.nan))
+
+
+def test_relative_risk_ci_edge_cases_10():
+    result = relative_risk(exposed_cases=1, exposed_total=12,
+                           control_cases=0, control_total=30)
+    assert_equal(result.relative_risk, np.inf)
+    ci = result.confidence_interval()
+    assert_equal((ci.low, ci.high), (np.nan, np.inf))
+
+
+@pytest.mark.parametrize('ec, et, cc, ct', [(0, 0, 10, 20),
+                                            (-1, 10, 1, 5),
+                                            (1, 10, 0, 0),
+                                            (1, 10, -1, 4)])
+def test_relative_risk_bad_value(ec, et, cc, ct):
+    with pytest.raises(ValueError, match="must be an integer not less than"):
+        relative_risk(ec, et, cc, ct)
+
+
+def test_relative_risk_bad_type():
+    with pytest.raises(TypeError, match="must be an integer"):
+        relative_risk(1, 10, 2.0, 40)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_resampling.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_resampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..22d5d4d32c7085e038a7f735a01ae9f07008a3ab
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_resampling.py
@@ -0,0 +1,2009 @@
+import pytest
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, suppress_warnings
+
+from scipy.conftest import array_api_compatible
+from scipy._lib._util import rng_integers
+from scipy._lib._array_api import array_namespace, is_numpy
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal
+from scipy import stats, special
+from scipy.optimize import root
+
+from scipy.stats import bootstrap, monte_carlo_test, permutation_test, power
+import scipy.stats._resampling as _resampling
+
+
+def test_bootstrap_iv():
+
+    message = "`data` must be a sequence of samples."
+    with pytest.raises(ValueError, match=message):
+        bootstrap(1, np.mean)
+
+    message = "`data` must contain at least one sample."
+    with pytest.raises(ValueError, match=message):
+        bootstrap(tuple(), np.mean)
+
+    message = "each sample in `data` must contain two or more observations..."
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3], [1]), np.mean)
+
+    message = ("When `paired is True`, all samples must have the same length ")
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3], [1, 2, 3, 4]), np.mean, paired=True)
+
+    message = "`vectorized` must be `True`, `False`, or `None`."
+    with pytest.raises(ValueError, match=message):
+        bootstrap(1, np.mean, vectorized='ekki')
+
+    message = "`axis` must be an integer."
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, axis=1.5)
+
+    message = "could not convert string to float"
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, confidence_level='ni')
+
+    message = "`n_resamples` must be a non-negative integer."
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, n_resamples=-1000)
+
+    message = "`n_resamples` must be a non-negative integer."
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, n_resamples=1000.5)
+
+    message = "`batch` must be a positive integer or None."
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, batch=-1000)
+
+    message = "`batch` must be a positive integer or None."
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, batch=1000.5)
+
+    message = "`method` must be in"
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, method='ekki')
+
+    message = "`bootstrap_result` must have attribute `bootstrap_distribution'"
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, bootstrap_result=10)
+
+    message = "Either `bootstrap_result.bootstrap_distribution.size`"
+    with pytest.raises(ValueError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, n_resamples=0)
+
+    message = "SeedSequence expects int or sequence of ints"
+    with pytest.raises(TypeError, match=message):
+        bootstrap(([1, 2, 3],), np.mean, rng='herring')
+
+
+@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
+@pytest.mark.parametrize("axis", [0, 1, 2])
+def test_bootstrap_batch(method, axis):
+    # for one-sample statistics, batch size shouldn't affect the result
+    np.random.seed(0)
+
+    x = np.random.rand(10, 11, 12)
+    # SPEC-007 leave one call with random_state to ensure it still works
+    res1 = bootstrap((x,), np.mean, batch=None, method=method,
+                     random_state=0, axis=axis, n_resamples=100)
+    np.random.seed(0)
+    res2 = bootstrap((x,), np.mean, batch=10, method=method,
+                     axis=axis, n_resamples=100)
+
+    assert_equal(res2.confidence_interval.low, res1.confidence_interval.low)
+    assert_equal(res2.confidence_interval.high, res1.confidence_interval.high)
+    assert_equal(res2.standard_error, res1.standard_error)
+
+
+@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
+def test_bootstrap_paired(method):
+    # test that `paired` works as expected
+    np.random.seed(0)
+    n = 100
+    x = np.random.rand(n)
+    y = np.random.rand(n)
+
+    def my_statistic(x, y, axis=-1):
+        return ((x-y)**2).mean(axis=axis)
+
+    def my_paired_statistic(i, axis=-1):
+        a = x[i]
+        b = y[i]
+        res = my_statistic(a, b)
+        return res
+
+    i = np.arange(len(x))
+
+    res1 = bootstrap((i,), my_paired_statistic, rng=0)
+    res2 = bootstrap((x, y), my_statistic, paired=True, rng=0)
+
+    assert_allclose(res1.confidence_interval, res2.confidence_interval)
+    assert_allclose(res1.standard_error, res2.standard_error)
+
+
+@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
+@pytest.mark.parametrize("axis", [0, 1, 2])
+@pytest.mark.parametrize("paired", [True, False])
+def test_bootstrap_vectorized(method, axis, paired):
+    # test that paired is vectorized as expected: when samples are tiled,
+    # CI and standard_error of each axis-slice is the same as those of the
+    # original 1d sample
+
+    np.random.seed(0)
+
+    def my_statistic(x, y, z, axis=-1):
+        return x.mean(axis=axis) + y.mean(axis=axis) + z.mean(axis=axis)
+
+    shape = 10, 11, 12
+    n_samples = shape[axis]
+
+    x = np.random.rand(n_samples)
+    y = np.random.rand(n_samples)
+    z = np.random.rand(n_samples)
+    res1 = bootstrap((x, y, z), my_statistic, paired=paired, method=method,
+                     rng=0, axis=0, n_resamples=100)
+    assert (res1.bootstrap_distribution.shape
+            == res1.standard_error.shape + (100,))
+
+    reshape = [1, 1, 1]
+    reshape[axis] = n_samples
+    x = np.broadcast_to(x.reshape(reshape), shape)
+    y = np.broadcast_to(y.reshape(reshape), shape)
+    z = np.broadcast_to(z.reshape(reshape), shape)
+    res2 = bootstrap((x, y, z), my_statistic, paired=paired, method=method,
+                     rng=0, axis=axis, n_resamples=100)
+
+    assert_allclose(res2.confidence_interval.low,
+                    res1.confidence_interval.low)
+    assert_allclose(res2.confidence_interval.high,
+                    res1.confidence_interval.high)
+    assert_allclose(res2.standard_error, res1.standard_error)
+
+    result_shape = list(shape)
+    result_shape.pop(axis)
+
+    assert_equal(res2.confidence_interval.low.shape, result_shape)
+    assert_equal(res2.confidence_interval.high.shape, result_shape)
+    assert_equal(res2.standard_error.shape, result_shape)
+
+
+@pytest.mark.slow
+@pytest.mark.xfail_on_32bit("MemoryError with BCa observed in CI")
+@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
+def test_bootstrap_against_theory(method):
+    # based on https://www.statology.org/confidence-intervals-python/
+    rng = np.random.default_rng(2442101192988600726)
+    data = stats.norm.rvs(loc=5, scale=2, size=5000, random_state=rng)
+    alpha = 0.95
+    dist = stats.t(df=len(data)-1, loc=np.mean(data), scale=stats.sem(data))
+    expected_interval = dist.interval(confidence=alpha)
+    expected_se = dist.std()
+
+    config = dict(data=(data,), statistic=np.mean, n_resamples=5000,
+                  method=method, rng=rng)
+    res = bootstrap(**config, confidence_level=alpha)
+    assert_allclose(res.confidence_interval, expected_interval, rtol=5e-4)
+    assert_allclose(res.standard_error, expected_se, atol=3e-4)
+
+    config.update(dict(n_resamples=0, bootstrap_result=res))
+    res = bootstrap(**config, confidence_level=alpha, alternative='less')
+    assert_allclose(res.confidence_interval.high, dist.ppf(alpha), rtol=5e-4)
+
+    config.update(dict(n_resamples=0, bootstrap_result=res))
+    res = bootstrap(**config, confidence_level=alpha, alternative='greater')
+    assert_allclose(res.confidence_interval.low, dist.ppf(1-alpha), rtol=5e-4)
+
+
+tests_R = {"basic": (23.77, 79.12),
+           "percentile": (28.86, 84.21),
+           "BCa": (32.31, 91.43)}
+
+
+@pytest.mark.parametrize("method, expected", tests_R.items())
+def test_bootstrap_against_R(method, expected):
+    # Compare against R's "boot" library
+    # library(boot)
+
+    # stat <- function (x, a) {
+    #     mean(x[a])
+    # }
+
+    # x <- c(10, 12, 12.5, 12.5, 13.9, 15, 21, 22,
+    #        23, 34, 50, 81, 89, 121, 134, 213)
+
+    # # Use a large value so we get a few significant digits for the CI.
+    # n = 1000000
+    # bootresult = boot(x, stat, n)
+    # result <- boot.ci(bootresult)
+    # print(result)
+    x = np.array([10, 12, 12.5, 12.5, 13.9, 15, 21, 22,
+                  23, 34, 50, 81, 89, 121, 134, 213])
+    res = bootstrap((x,), np.mean, n_resamples=1000000, method=method,
+                    rng=0)
+    assert_allclose(res.confidence_interval, expected, rtol=0.005)
+
+
+tests_against_itself_1samp = {"basic": 1780,
+                              "percentile": 1784,
+                              "BCa": 1784}
+
+
+def test_multisample_BCa_against_R():
+    # Because bootstrap is stochastic, it's tricky to test against reference
+    # behavior. Here, we show that SciPy's BCa CI matches R wboot's BCa CI
+    # much more closely than the other SciPy CIs do.
+
+    # arbitrary skewed data
+    x = [0.75859206, 0.5910282, -0.4419409, -0.36654601,
+         0.34955357, -1.38835871, 0.76735821]
+    y = [1.41186073, 0.49775975, 0.08275588, 0.24086388,
+         0.03567057, 0.52024419, 0.31966611, 1.32067634]
+
+    # a multi-sample statistic for which the BCa CI tends to be different
+    # from the other CIs
+    def statistic(x, y, axis):
+        s1 = stats.skew(x, axis=axis)
+        s2 = stats.skew(y, axis=axis)
+        return s1 - s2
+
+    # compute confidence intervals using each method
+    rng = np.random.default_rng(468865032284792692)
+
+    res_basic = stats.bootstrap((x, y), statistic, method='basic',
+                                batch=100, rng=rng)
+    res_percent = stats.bootstrap((x, y), statistic, method='percentile',
+                                  batch=100, rng=rng)
+    res_bca = stats.bootstrap((x, y), statistic, method='bca',
+                              batch=100, rng=rng)
+
+    # compute midpoints so we can compare just one number for each
+    mid_basic = np.mean(res_basic.confidence_interval)
+    mid_percent = np.mean(res_percent.confidence_interval)
+    mid_bca = np.mean(res_bca.confidence_interval)
+
+    # reference for BCA CI computed using R wboot package:
+    # library(wBoot)
+    # library(moments)
+
+    # x = c(0.75859206, 0.5910282, -0.4419409, -0.36654601,
+    #       0.34955357, -1.38835871,  0.76735821)
+    # y = c(1.41186073, 0.49775975, 0.08275588, 0.24086388,
+    #       0.03567057, 0.52024419, 0.31966611, 1.32067634)
+
+    # twoskew <- function(x1, y1) {skewness(x1) - skewness(y1)}
+    # boot.two.bca(x, y, skewness, conf.level = 0.95,
+    #              R = 9999, stacked = FALSE)
+    mid_wboot = -1.5519
+
+    # compute percent difference relative to wboot BCA method
+    diff_basic = (mid_basic - mid_wboot)/abs(mid_wboot)
+    diff_percent = (mid_percent - mid_wboot)/abs(mid_wboot)
+    diff_bca = (mid_bca - mid_wboot)/abs(mid_wboot)
+
+    # SciPy's BCa CI midpoint is much closer than that of the other methods
+    assert diff_basic < -0.15
+    assert diff_percent > 0.15
+    assert abs(diff_bca) < 0.03
+
+
+def test_BCa_acceleration_against_reference():
+    # Compare the (deterministic) acceleration parameter for a multi-sample
+    # problem against a reference value. The example is from [1], but Efron's
+    # value seems inaccurate. Straightforward code for computing the
+    # reference acceleration (0.011008228344026734) is available at:
+    # https://github.com/scipy/scipy/pull/16455#issuecomment-1193400981
+
+    y = np.array([10, 27, 31, 40, 46, 50, 52, 104, 146])
+    z = np.array([16, 23, 38, 94, 99, 141, 197])
+
+    def statistic(z, y, axis=0):
+        return np.mean(z, axis=axis) - np.mean(y, axis=axis)
+
+    data = [z, y]
+    res = stats.bootstrap(data, statistic)
+
+    axis = -1
+    alpha = 0.95
+    theta_hat_b = res.bootstrap_distribution
+    batch = 100
+    _, _, a_hat = _resampling._bca_interval(data, statistic, axis, alpha,
+                                            theta_hat_b, batch)
+    assert_allclose(a_hat, 0.011008228344026734)
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize("method, expected",
+                         tests_against_itself_1samp.items())
+def test_bootstrap_against_itself_1samp(method, expected):
+    # The expected values in this test were generated using bootstrap
+    # to check for unintended changes in behavior. The test also makes sure
+    # that bootstrap works with multi-sample statistics and that the
+    # `axis` argument works as expected / function is vectorized.
+    np.random.seed(0)
+
+    n = 100  # size of sample
+    n_resamples = 999  # number of bootstrap resamples used to form each CI
+    confidence_level = 0.9
+
+    # The true mean is 5
+    dist = stats.norm(loc=5, scale=1)
+    stat_true = dist.mean()
+
+    # Do the same thing 2000 times. (The code is fully vectorized.)
+    n_replications = 2000
+    data = dist.rvs(size=(n_replications, n))
+    res = bootstrap((data,),
+                    statistic=np.mean,
+                    confidence_level=confidence_level,
+                    n_resamples=n_resamples,
+                    batch=50,
+                    method=method,
+                    axis=-1)
+    ci = res.confidence_interval
+
+    # ci contains vectors of lower and upper confidence interval bounds
+    ci_contains_true = np.sum((ci[0] < stat_true) & (stat_true < ci[1]))
+    assert ci_contains_true == expected
+
+    # ci_contains_true is not inconsistent with confidence_level
+    pvalue = stats.binomtest(ci_contains_true, n_replications,
+                             confidence_level).pvalue
+    assert pvalue > 0.1
+
+
+tests_against_itself_2samp = {"basic": 892,
+                              "percentile": 890}
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize("method, expected",
+                         tests_against_itself_2samp.items())
+def test_bootstrap_against_itself_2samp(method, expected):
+    # The expected values in this test were generated using bootstrap
+    # to check for unintended changes in behavior. The test also makes sure
+    # that bootstrap works with multi-sample statistics and that the
+    # `axis` argument works as expected / function is vectorized.
+    np.random.seed(0)
+
+    n1 = 100  # size of sample 1
+    n2 = 120  # size of sample 2
+    n_resamples = 999  # number of bootstrap resamples used to form each CI
+    confidence_level = 0.9
+
+    # The statistic we're interested in is the difference in means
+    def my_stat(data1, data2, axis=-1):
+        mean1 = np.mean(data1, axis=axis)
+        mean2 = np.mean(data2, axis=axis)
+        return mean1 - mean2
+
+    # The true difference in the means is -0.1
+    dist1 = stats.norm(loc=0, scale=1)
+    dist2 = stats.norm(loc=0.1, scale=1)
+    stat_true = dist1.mean() - dist2.mean()
+
+    # Do the same thing 1000 times. (The code is fully vectorized.)
+    n_replications = 1000
+    data1 = dist1.rvs(size=(n_replications, n1))
+    data2 = dist2.rvs(size=(n_replications, n2))
+    res = bootstrap((data1, data2),
+                    statistic=my_stat,
+                    confidence_level=confidence_level,
+                    n_resamples=n_resamples,
+                    batch=50,
+                    method=method,
+                    axis=-1)
+    ci = res.confidence_interval
+
+    # ci contains vectors of lower and upper confidence interval bounds
+    ci_contains_true = np.sum((ci[0] < stat_true) & (stat_true < ci[1]))
+    assert ci_contains_true == expected
+
+    # ci_contains_true is not inconsistent with confidence_level
+    pvalue = stats.binomtest(ci_contains_true, n_replications,
+                             confidence_level).pvalue
+    assert pvalue > 0.1
+
+
+@pytest.mark.parametrize("method", ["basic", "percentile"])
+@pytest.mark.parametrize("axis", [0, 1])
+def test_bootstrap_vectorized_3samp(method, axis):
+    def statistic(*data, axis=0):
+        # an arbitrary, vectorized statistic
+        return sum(sample.mean(axis) for sample in data)
+
+    def statistic_1d(*data):
+        # the same statistic, not vectorized
+        for sample in data:
+            assert sample.ndim == 1
+        return statistic(*data, axis=0)
+
+    np.random.seed(0)
+    x = np.random.rand(4, 5)
+    y = np.random.rand(4, 5)
+    z = np.random.rand(4, 5)
+    res1 = bootstrap((x, y, z), statistic, vectorized=True,
+                     axis=axis, n_resamples=100, method=method, rng=0)
+    res2 = bootstrap((x, y, z), statistic_1d, vectorized=False,
+                     axis=axis, n_resamples=100, method=method, rng=0)
+    assert_allclose(res1.confidence_interval, res2.confidence_interval)
+    assert_allclose(res1.standard_error, res2.standard_error)
+
+
+@pytest.mark.xfail_on_32bit("Failure is not concerning; see gh-14107")
+@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
+@pytest.mark.parametrize("axis", [0, 1])
+def test_bootstrap_vectorized_1samp(method, axis):
+    def statistic(x, axis=0):
+        # an arbitrary, vectorized statistic
+        return x.mean(axis=axis)
+
+    def statistic_1d(x):
+        # the same statistic, not vectorized
+        assert x.ndim == 1
+        return statistic(x, axis=0)
+
+    np.random.seed(0)
+    x = np.random.rand(4, 5)
+    res1 = bootstrap((x,), statistic, vectorized=True, axis=axis,
+                     n_resamples=100, batch=None, method=method,
+                     rng=0)
+    res2 = bootstrap((x,), statistic_1d, vectorized=False, axis=axis,
+                     n_resamples=100, batch=10, method=method,
+                     rng=0)
+    assert_allclose(res1.confidence_interval, res2.confidence_interval)
+    assert_allclose(res1.standard_error, res2.standard_error)
+
+
+@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
+def test_bootstrap_degenerate(method):
+    data = 35 * [10000.]
+    if method == "BCa":
+        with np.errstate(invalid='ignore'):
+            msg = "The BCa confidence interval cannot be calculated"
+            with pytest.warns(stats.DegenerateDataWarning, match=msg):
+                res = bootstrap([data, ], np.mean, method=method)
+                assert_equal(res.confidence_interval, (np.nan, np.nan))
+    else:
+        res = bootstrap([data, ], np.mean, method=method)
+        assert_equal(res.confidence_interval, (10000., 10000.))
+    assert_equal(res.standard_error, 0)
+
+
+@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
+def test_bootstrap_gh15678(method):
+    # Check that gh-15678 is fixed: when statistic function returned a Python
+    # float, method="BCa" failed when trying to add a dimension to the float
+    rng = np.random.default_rng(354645618886684)
+    dist = stats.norm(loc=2, scale=4)
+    data = dist.rvs(size=100, random_state=rng)
+    data = (data,)
+    res = bootstrap(data, stats.skew, method=method, n_resamples=100,
+                    rng=np.random.default_rng(9563))
+    # this always worked because np.apply_along_axis returns NumPy data type
+    ref = bootstrap(data, stats.skew, method=method, n_resamples=100,
+                    rng=np.random.default_rng(9563), vectorized=False)
+    assert_allclose(res.confidence_interval, ref.confidence_interval)
+    assert_allclose(res.standard_error, ref.standard_error)
+    assert isinstance(res.standard_error, np.float64)
+
+
+def test_bootstrap_min():
+    # Check that gh-15883 is fixed: percentileofscore should
+    # behave according to the 'mean' behavior and not trigger nan for BCa
+    rng = np.random.default_rng(1891289180021102)
+    dist = stats.norm(loc=2, scale=4)
+    data = dist.rvs(size=100, random_state=rng)
+    true_min = np.min(data)
+    data = (data,)
+    res = bootstrap(data, np.min, method="BCa", n_resamples=100,
+                    rng=np.random.default_rng(3942))
+    assert true_min == res.confidence_interval.low
+    res2 = bootstrap(-np.array(data), np.max, method="BCa", n_resamples=100,
+                     rng=np.random.default_rng(3942))
+    assert_allclose(-res.confidence_interval.low,
+                    res2.confidence_interval.high)
+    assert_allclose(-res.confidence_interval.high,
+                    res2.confidence_interval.low)
+
+
+@pytest.mark.parametrize("additional_resamples", [0, 1000])
+def test_re_bootstrap(additional_resamples):
+    # Test behavior of parameter `bootstrap_result`
+    rng = np.random.default_rng(8958153316228384)
+    x = rng.random(size=100)
+
+    n1 = 1000
+    n2 = additional_resamples
+    n3 = n1 + additional_resamples
+
+    rng = np.random.default_rng(296689032789913033)
+    res = stats.bootstrap((x,), np.mean, n_resamples=n1, rng=rng,
+                          confidence_level=0.95, method='percentile')
+    res = stats.bootstrap((x,), np.mean, n_resamples=n2, rng=rng,
+                          confidence_level=0.90, method='BCa',
+                          bootstrap_result=res)
+
+    rng = np.random.default_rng(296689032789913033)
+    ref = stats.bootstrap((x,), np.mean, n_resamples=n3, rng=rng,
+                          confidence_level=0.90, method='BCa')
+
+    assert_allclose(res.standard_error, ref.standard_error, rtol=1e-14)
+    assert_allclose(res.confidence_interval, ref.confidence_interval,
+                    rtol=1e-14)
+
+
+@pytest.mark.xfail_on_32bit("Sensible to machine precision")
+@pytest.mark.parametrize("method", ['basic', 'percentile', 'BCa'])
+def test_bootstrap_alternative(method):
+    rng = np.random.default_rng(5894822712842015040)
+    dist = stats.norm(loc=2, scale=4)
+    data = (dist.rvs(size=(100), random_state=rng),)
+
+    config = dict(data=data, statistic=np.std, rng=rng, axis=-1)
+    t = stats.bootstrap(**config, confidence_level=0.9)
+
+    config.update(dict(n_resamples=0, bootstrap_result=t))
+    l = stats.bootstrap(**config, confidence_level=0.95, alternative='less')
+    g = stats.bootstrap(**config, confidence_level=0.95, alternative='greater')
+
+    assert_allclose(l.confidence_interval.high, t.confidence_interval.high,
+                    rtol=1e-14)
+    assert_allclose(g.confidence_interval.low, t.confidence_interval.low,
+                    rtol=1e-14)
+    assert np.isneginf(l.confidence_interval.low)
+    assert np.isposinf(g.confidence_interval.high)
+
+    with pytest.raises(ValueError, match='`alternative` must be one of'):
+        stats.bootstrap(**config, alternative='ekki-ekki')
+
+
+def test_jackknife_resample():
+    shape = 3, 4, 5, 6
+    np.random.seed(0)
+    x = np.random.rand(*shape)
+    y = next(_resampling._jackknife_resample(x))
+
+    for i in range(shape[-1]):
+        # each resample is indexed along second to last axis
+        # (last axis is the one the statistic will be taken over / consumed)
+        slc = y[..., i, :]
+        expected = np.delete(x, i, axis=-1)
+
+        assert np.array_equal(slc, expected)
+
+    y2 = np.concatenate(list(_resampling._jackknife_resample(x, batch=2)),
+                        axis=-2)
+    assert np.array_equal(y2, y)
+
+
+@pytest.mark.parametrize("rng_name", ["RandomState", "default_rng"])
+def test_bootstrap_resample(rng_name):
+    rng = getattr(np.random, rng_name, None)
+    if rng is None:
+        pytest.skip(f"{rng_name} not available.")
+    rng1 = rng(0)
+    rng2 = rng(0)
+
+    n_resamples = 10
+    shape = 3, 4, 5, 6
+
+    np.random.seed(0)
+    x = np.random.rand(*shape)
+    y = _resampling._bootstrap_resample(x, n_resamples, rng=rng1)
+
+    for i in range(n_resamples):
+        # each resample is indexed along second to last axis
+        # (last axis is the one the statistic will be taken over / consumed)
+        slc = y[..., i, :]
+
+        js = rng_integers(rng2, 0, shape[-1], shape[-1])
+        expected = x[..., js]
+
+        assert np.array_equal(slc, expected)
+
+
+@pytest.mark.parametrize("score", [0, 0.5, 1])
+@pytest.mark.parametrize("axis", [0, 1, 2])
+def test_percentile_of_score(score, axis):
+    shape = 10, 20, 30
+    np.random.seed(0)
+    x = np.random.rand(*shape)
+    p = _resampling._percentile_of_score(x, score, axis=-1)
+
+    def vectorized_pos(a, score, axis):
+        return np.apply_along_axis(stats.percentileofscore, axis, a, score)
+
+    p2 = vectorized_pos(x, score, axis=-1)/100
+
+    assert_allclose(p, p2, 1e-15)
+
+
+def test_percentile_along_axis():
+    # the difference between _percentile_along_axis and np.percentile is that
+    # np.percentile gets _all_ the qs for each axis slice, whereas
+    # _percentile_along_axis gets the q corresponding with each axis slice
+
+    shape = 10, 20
+    np.random.seed(0)
+    x = np.random.rand(*shape)
+    q = np.random.rand(*shape[:-1]) * 100
+    y = _resampling._percentile_along_axis(x, q)
+
+    for i in range(shape[0]):
+        res = y[i]
+        expected = np.percentile(x[i], q[i], axis=-1)
+        assert_allclose(res, expected, 1e-15)
+
+
+@pytest.mark.parametrize("axis", [0, 1, 2])
+def test_vectorize_statistic(axis):
+    # test that _vectorize_statistic vectorizes a statistic along `axis`
+
+    def statistic(*data, axis):
+        # an arbitrary, vectorized statistic
+        return sum(sample.mean(axis) for sample in data)
+
+    def statistic_1d(*data):
+        # the same statistic, not vectorized
+        for sample in data:
+            assert sample.ndim == 1
+        return statistic(*data, axis=0)
+
+    # vectorize the non-vectorized statistic
+    statistic2 = _resampling._vectorize_statistic(statistic_1d)
+
+    np.random.seed(0)
+    x = np.random.rand(4, 5, 6)
+    y = np.random.rand(4, 1, 6)
+    z = np.random.rand(1, 5, 6)
+
+    res1 = statistic(x, y, z, axis=axis)
+    res2 = statistic2(x, y, z, axis=axis)
+    assert_allclose(res1, res2)
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize("method", ["basic", "percentile", "BCa"])
+def test_vector_valued_statistic(method):
+    # Generate 95% confidence interval around MLE of normal distribution
+    # parameters. Repeat 100 times, each time on sample of size 100.
+    # Check that confidence interval contains true parameters ~95 times.
+    # Confidence intervals are estimated and stochastic; a test failure
+    # does not necessarily indicate that something is wrong. More important
+    # than values of `counts` below is that the shapes of the outputs are
+    # correct.
+
+    rng = np.random.default_rng(2196847219)
+    params = 1, 0.5
+    sample = stats.norm.rvs(*params, size=(100, 100), random_state=rng)
+
+    def statistic(data, axis):
+        return np.asarray([np.mean(data, axis),
+                           np.std(data, axis, ddof=1)])
+
+    res = bootstrap((sample,), statistic, method=method, axis=-1,
+                    n_resamples=9999, batch=200)
+
+    counts = np.sum((res.confidence_interval.low.T < params)
+                    & (res.confidence_interval.high.T > params),
+                    axis=0)
+    assert np.all(counts >= 90)
+    assert np.all(counts <= 100)
+    assert res.confidence_interval.low.shape == (2, 100)
+    assert res.confidence_interval.high.shape == (2, 100)
+    assert res.standard_error.shape == (2, 100)
+    assert res.bootstrap_distribution.shape == (2, 100, 9999)
+
+
+@pytest.mark.slow
+@pytest.mark.filterwarnings('ignore::RuntimeWarning')
+def test_vector_valued_statistic_gh17715():
+    # gh-17715 reported a mistake introduced in the extension of BCa to
+    # multi-sample statistics; a `len` should have been `.shape[-1]`. Check
+    # that this is resolved.
+
+    rng = np.random.default_rng(141921000979291141)
+
+    def concordance(x, y, axis):
+        xm = x.mean(axis)
+        ym = y.mean(axis)
+        cov = ((x - xm[..., None]) * (y - ym[..., None])).mean(axis)
+        return (2 * cov) / (x.var(axis) + y.var(axis) + (xm - ym) ** 2)
+
+    def statistic(tp, tn, fp, fn, axis):
+        actual = tp + fp
+        expected = tp + fn
+        return np.nan_to_num(concordance(actual, expected, axis))
+
+    def statistic_extradim(*args, axis):
+        return statistic(*args, axis)[np.newaxis, ...]
+
+    data = [[4, 0, 0, 2],  # (tp, tn, fp, fn)
+            [2, 1, 2, 1],
+            [0, 6, 0, 0],
+            [0, 6, 3, 0],
+            [0, 8, 1, 0]]
+    data = np.array(data).T
+
+    res = bootstrap(data, statistic_extradim, rng=rng, paired=True)
+    ref = bootstrap(data, statistic, rng=rng, paired=True)
+    assert_allclose(res.confidence_interval.low[0],
+                    ref.confidence_interval.low, atol=1e-15)
+    assert_allclose(res.confidence_interval.high[0],
+                    ref.confidence_interval.high, atol=1e-15)
+
+
+def test_gh_20850():
+    rng = np.random.default_rng(2085020850)
+    x = rng.random((10, 2))
+    y = rng.random((11, 2))
+    def statistic(x, y, axis):
+        return stats.ttest_ind(x, y, axis=axis).statistic
+
+    # The shapes do *not* need to be the same along axis
+    stats.bootstrap((x, y), statistic)
+    stats.bootstrap((x.T, y.T), statistic, axis=1)
+    # But even when the shapes *are* the same along axis, the lengths
+    # along other dimensions have to be the same (or `bootstrap` warns).
+    message = "Ignoring the dimension specified by `axis`..."
+    with pytest.warns(FutureWarning, match=message):
+        stats.bootstrap((x, y[:10, 0]), statistic)  # this won't work after 1.16
+    with pytest.warns(FutureWarning, match=message):
+        stats.bootstrap((x, y[:10, 0:1]), statistic)  # this will
+    with pytest.warns(FutureWarning, match=message):
+        stats.bootstrap((x.T, y.T[0:1, :10]), statistic, axis=1)  # this will
+
+
+# --- Test Monte Carlo Hypothesis Test --- #
+
+class TestMonteCarloHypothesisTest:
+    atol = 2.5e-2  # for comparing p-value
+
+    def get_rvs(self, rvs_in, rs, dtype=None, xp=np):
+        return lambda *args, **kwds: xp.asarray(rvs_in(*args, random_state=rs, **kwds),
+                                                dtype=dtype)
+
+    def get_statistic(self, xp):
+        def statistic(x, axis):
+            m = xp.mean(x, axis=axis)
+            v = xp.var(x, axis=axis, correction=1)
+            n = x.shape[axis]
+            return m / (v/n)**0.5
+            # return stats.ttest_1samp(x, popmean=0., axis=axis).statistic)
+        return statistic
+
+    @array_api_compatible
+    def test_input_validation(self, xp):
+        # test that the appropriate error messages are raised for invalid input
+
+        data = xp.asarray([1., 2., 3.])
+        def stat(x, axis=None):
+            return xp.mean(x, axis=axis)
+
+        message = "Array shapes are incompatible for broadcasting."
+        temp = (xp.zeros((2, 5)), xp.zeros((3, 5)))
+        rvs = (stats.norm.rvs, stats.norm.rvs)
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(temp, rvs, lambda x, y, axis: 1, axis=-1)
+
+        message = "`axis` must be an integer."
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(data, stats.norm.rvs, stat, axis=1.5)
+
+        message = "`vectorized` must be `True`, `False`, or `None`."
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(data, stats.norm.rvs, stat, vectorized=1.5)
+
+        message = "`rvs` must be callable or sequence of callables."
+        with pytest.raises(TypeError, match=message):
+            monte_carlo_test(data, None, stat)
+        with pytest.raises(TypeError, match=message):
+            temp = xp.asarray([[1., 2.], [3., 4.]])
+            monte_carlo_test(temp, [lambda x: x, None], stat)
+
+        message = "If `rvs` is a sequence..."
+        with pytest.raises(ValueError, match=message):
+            temp = xp.asarray([[1., 2., 3.]])
+            monte_carlo_test(temp, [lambda x: x, lambda x: x], stat)
+
+        message = "`statistic` must be callable."
+        with pytest.raises(TypeError, match=message):
+            monte_carlo_test(data, stats.norm.rvs, None)
+
+        message = "`n_resamples` must be a positive integer."
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(data, stats.norm.rvs, stat, n_resamples=-1000)
+
+        message = "`n_resamples` must be a positive integer."
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(data, stats.norm.rvs, stat, n_resamples=1000.5)
+
+        message = "`batch` must be a positive integer or None."
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(data, stats.norm.rvs, stat, batch=-1000)
+
+        message = "`batch` must be a positive integer or None."
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(data, stats.norm.rvs, stat, batch=1000.5)
+
+        message = "`alternative` must be in..."
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(data, stats.norm.rvs, stat, alternative='ekki')
+
+        # *If* this raises a value error, make sure it has the intended message
+        message = "Signature inspection of statistic"
+        def rvs(size):
+            return xp.asarray(stats.norm.rvs(size=size))
+        try:
+            monte_carlo_test(data, rvs, xp.mean)
+        except ValueError as e:
+            assert str(e).startswith(message)
+
+    @array_api_compatible
+    def test_input_validation_xp(self, xp):
+        def non_vectorized_statistic(x):
+            return xp.mean(x)
+
+        message = "`statistic` must be vectorized..."
+        sample = xp.asarray([1., 2., 3.])
+        if is_numpy(xp):
+            monte_carlo_test(sample, stats.norm.rvs, non_vectorized_statistic)
+            return
+
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(sample, stats.norm.rvs, non_vectorized_statistic)
+        with pytest.raises(ValueError, match=message):
+            monte_carlo_test(sample, stats.norm.rvs, xp.mean, vectorized=False)
+
+    @pytest.mark.xslow
+    @array_api_compatible
+    def test_batch(self, xp):
+        # make sure that the `batch` parameter is respected by checking the
+        # maximum batch size provided in calls to `statistic`
+        rng = np.random.default_rng(23492340193)
+        x = xp.asarray(rng.standard_normal(size=10))
+
+        xp_test = array_namespace(x)  # numpy.std doesn't have `correction`
+        def statistic(x, axis):
+            batch_size = 1 if x.ndim == 1 else x.shape[0]
+            statistic.batch_size = max(batch_size, statistic.batch_size)
+            statistic.counter += 1
+            return self.get_statistic(xp_test)(x, axis=axis)
+        statistic.counter = 0
+        statistic.batch_size = 0
+
+        kwds = {'sample': x, 'statistic': statistic,
+                'n_resamples': 1000, 'vectorized': True}
+
+        kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp)
+        res1 = monte_carlo_test(batch=1, **kwds)
+        assert_equal(statistic.counter, 1001)
+        assert_equal(statistic.batch_size, 1)
+
+        kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp)
+        statistic.counter = 0
+        res2 = monte_carlo_test(batch=50, **kwds)
+        assert_equal(statistic.counter, 21)
+        assert_equal(statistic.batch_size, 50)
+
+        kwds['rvs'] = self.get_rvs(stats.norm.rvs, np.random.default_rng(328423), xp=xp)
+        statistic.counter = 0
+        res3 = monte_carlo_test(**kwds)
+        assert_equal(statistic.counter, 2)
+        assert_equal(statistic.batch_size, 1000)
+
+        xp_assert_equal(res1.pvalue, res3.pvalue)
+        xp_assert_equal(res2.pvalue, res3.pvalue)
+
+    @array_api_compatible
+    @pytest.mark.parametrize('axis', range(-3, 3))
+    def test_axis_dtype(self, axis, xp):
+        # test that Nd-array samples are handled correctly for valid values
+        # of the `axis` parameter; also make sure non-default dtype is maintained
+        rng = np.random.default_rng(2389234)
+        size = [2, 3, 4]
+        size[axis] = 100
+
+        # Determine non-default dtype
+        dtype_default = xp.asarray(1.).dtype
+        dtype_str = 'float32'if ("64" in str(dtype_default)) else 'float64'
+        dtype_np = getattr(np, dtype_str)
+        dtype = getattr(xp, dtype_str)
+
+        # ttest_1samp is CPU array-API compatible, but it would be good to
+        # include CuPy in this test. We'll perform ttest_1samp with a
+        # NumPy array, but all the rest with be done with fully array-API
+        # compatible code.
+        x = rng.standard_normal(size=size, dtype=dtype_np)
+        expected = stats.ttest_1samp(x, popmean=0., axis=axis)
+
+        x = xp.asarray(x, dtype=dtype)
+        xp_test = array_namespace(x)  # numpy.std doesn't have `correction`
+        statistic = self.get_statistic(xp_test)
+        rvs = self.get_rvs(stats.norm.rvs, rng, dtype=dtype, xp=xp)
+
+        res = monte_carlo_test(x, rvs, statistic, vectorized=True,
+                               n_resamples=20000, axis=axis)
+
+        ref_statistic = xp.asarray(expected.statistic, dtype=dtype)
+        ref_pvalue = xp.asarray(expected.pvalue, dtype=dtype)
+        xp_assert_close(res.statistic, ref_statistic)
+        xp_assert_close(res.pvalue, ref_pvalue, atol=self.atol)
+
+    @array_api_compatible
+    @pytest.mark.parametrize('alternative', ("two-sided", "less", "greater"))
+    def test_alternative(self, alternative, xp):
+        # test that `alternative` is working as expected
+        rng = np.random.default_rng(65723433)
+
+        x = rng.standard_normal(size=30)
+        ref = stats.ttest_1samp(x, 0., alternative=alternative)
+
+        x = xp.asarray(x)
+        xp_test = array_namespace(x)  # numpy.std doesn't have `correction`
+        statistic = self.get_statistic(xp_test)
+        rvs = self.get_rvs(stats.norm.rvs, rng, xp=xp)
+
+        res = monte_carlo_test(x, rvs, statistic, alternative=alternative)
+
+        xp_assert_close(res.statistic, xp.asarray(ref.statistic))
+        xp_assert_close(res.pvalue, xp.asarray(ref.pvalue), atol=self.atol)
+
+
+    # Tests below involve statistics that are not yet array-API compatible.
+    # They can be converted when the statistics are converted.
+    @pytest.mark.slow
+    @pytest.mark.parametrize('alternative', ("less", "greater"))
+    @pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5))  # skewness
+    def test_against_ks_1samp(self, alternative, a):
+        # test that monte_carlo_test can reproduce pvalue of ks_1samp
+        rng = np.random.default_rng(65723433)
+
+        x = stats.skewnorm.rvs(a=a, size=30, random_state=rng)
+        expected = stats.ks_1samp(x, stats.norm.cdf, alternative=alternative)
+
+        def statistic1d(x):
+            return stats.ks_1samp(x, stats.norm.cdf, mode='asymp',
+                                  alternative=alternative).statistic
+
+        norm_rvs = self.get_rvs(stats.norm.rvs, rng)
+        res = monte_carlo_test(x, norm_rvs, statistic1d,
+                               n_resamples=1000, vectorized=False,
+                               alternative=alternative)
+
+        assert_allclose(res.statistic, expected.statistic)
+        if alternative == 'greater':
+            assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
+        elif alternative == 'less':
+            assert_allclose(1-res.pvalue, expected.pvalue, atol=self.atol)
+
+    @pytest.mark.parametrize('hypotest', (stats.skewtest, stats.kurtosistest))
+    @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
+    @pytest.mark.parametrize('a', np.linspace(-2, 2, 5))  # skewness
+    def test_against_normality_tests(self, hypotest, alternative, a):
+        # test that monte_carlo_test can reproduce pvalue of normality tests
+        rng = np.random.default_rng(85723405)
+
+        x = stats.skewnorm.rvs(a=a, size=150, random_state=rng)
+        expected = hypotest(x, alternative=alternative)
+
+        def statistic(x, axis):
+            return hypotest(x, axis=axis).statistic
+
+        norm_rvs = self.get_rvs(stats.norm.rvs, rng)
+        res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True,
+                               alternative=alternative)
+
+        assert_allclose(res.statistic, expected.statistic)
+        assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
+
+    @pytest.mark.parametrize('a', np.arange(-2, 3))  # skewness parameter
+    def test_against_normaltest(self, a):
+        # test that monte_carlo_test can reproduce pvalue of normaltest
+        rng = np.random.default_rng(12340513)
+
+        x = stats.skewnorm.rvs(a=a, size=150, random_state=rng)
+        expected = stats.normaltest(x)
+
+        def statistic(x, axis):
+            return stats.normaltest(x, axis=axis).statistic
+
+        norm_rvs = self.get_rvs(stats.norm.rvs, rng)
+        res = monte_carlo_test(x, norm_rvs, statistic, vectorized=True,
+                               alternative='greater')
+
+        assert_allclose(res.statistic, expected.statistic)
+        assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize('a', np.linspace(-0.5, 0.5, 5))  # skewness
+    def test_against_cramervonmises(self, a):
+        # test that monte_carlo_test can reproduce pvalue of cramervonmises
+        rng = np.random.default_rng(234874135)
+
+        x = stats.skewnorm.rvs(a=a, size=30, random_state=rng)
+        expected = stats.cramervonmises(x, stats.norm.cdf)
+
+        def statistic1d(x):
+            return stats.cramervonmises(x, stats.norm.cdf).statistic
+
+        norm_rvs = self.get_rvs(stats.norm.rvs, rng)
+        res = monte_carlo_test(x, norm_rvs, statistic1d,
+                               n_resamples=1000, vectorized=False,
+                               alternative='greater')
+
+        assert_allclose(res.statistic, expected.statistic)
+        assert_allclose(res.pvalue, expected.pvalue, atol=self.atol)
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize('dist_name', ('norm', 'logistic'))
+    @pytest.mark.parametrize('i', range(5))
+    def test_against_anderson(self, dist_name, i):
+        # test that monte_carlo_test can reproduce results of `anderson`. Note:
+        # `anderson` does not provide a p-value; it provides a list of
+        # significance levels and the associated critical value of the test
+        # statistic. `i` used to index this list.
+
+        # find the skewness for which the sample statistic matches one of the
+        # critical values provided by `stats.anderson`
+
+        def fun(a):
+            rng = np.random.default_rng(394295467)
+            x = stats.tukeylambda.rvs(a, size=100, random_state=rng)
+            expected = stats.anderson(x, dist_name)
+            return expected.statistic - expected.critical_values[i]
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning)
+            sol = root(fun, x0=0)
+        assert sol.success
+
+        # get the significance level (p-value) associated with that critical
+        # value
+        a = sol.x[0]
+        rng = np.random.default_rng(394295467)
+        x = stats.tukeylambda.rvs(a, size=100, random_state=rng)
+        expected = stats.anderson(x, dist_name)
+        expected_stat = expected.statistic
+        expected_p = expected.significance_level[i]/100
+
+        # perform equivalent Monte Carlo test and compare results
+        def statistic1d(x):
+            return stats.anderson(x, dist_name).statistic
+
+        dist_rvs = self.get_rvs(getattr(stats, dist_name).rvs, rng)
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning)
+            res = monte_carlo_test(x, dist_rvs,
+                                   statistic1d, n_resamples=1000,
+                                   vectorized=False, alternative='greater')
+
+        assert_allclose(res.statistic, expected_stat)
+        assert_allclose(res.pvalue, expected_p, atol=2*self.atol)
+
+    def test_p_never_zero(self):
+        # Use biased estimate of p-value to ensure that p-value is never zero
+        # per monte_carlo_test reference [1]
+        rng = np.random.default_rng(2190176673029737545)
+        x = np.zeros(100)
+        res = monte_carlo_test(x, rng.random, np.mean,
+                               vectorized=True, alternative='less')
+        assert res.pvalue == 0.0001
+
+    def test_against_ttest_ind(self):
+        # test that `monte_carlo_test` can reproduce results of `ttest_ind`.
+        rng = np.random.default_rng(219017667302737545)
+        data = rng.random(size=(2, 5)), rng.random(size=7)  # broadcastable
+        rvs = rng.normal, rng.normal
+        def statistic(x, y, axis):
+            return stats.ttest_ind(x, y, axis=axis).statistic
+
+        res = stats.monte_carlo_test(data, rvs, statistic, axis=-1)
+        ref = stats.ttest_ind(data[0], [data[1]], axis=-1)
+        assert_allclose(res.statistic, ref.statistic)
+        assert_allclose(res.pvalue, ref.pvalue, rtol=2e-2)
+
+    def test_against_f_oneway(self):
+        # test that `monte_carlo_test` can reproduce results of `f_oneway`.
+        rng = np.random.default_rng(219017667302737545)
+        data = (rng.random(size=(2, 100)), rng.random(size=(2, 101)),
+                rng.random(size=(2, 102)), rng.random(size=(2, 103)))
+        rvs = rng.normal, rng.normal, rng.normal, rng.normal
+
+        def statistic(*args, axis):
+            return stats.f_oneway(*args, axis=axis).statistic
+
+        res = stats.monte_carlo_test(data, rvs, statistic, axis=-1,
+                                     alternative='greater')
+        ref = stats.f_oneway(*data, axis=-1)
+
+        assert_allclose(res.statistic, ref.statistic)
+        assert_allclose(res.pvalue, ref.pvalue, atol=1e-2)
+
+    @pytest.mark.fail_slow(2)
+    @pytest.mark.xfail_on_32bit("Statistic may not depend on sample order on 32-bit")
+    def test_finite_precision_statistic(self):
+        # Some statistics return numerically distinct values when the values
+        # should be equal in theory. Test that `monte_carlo_test` accounts
+        # for this in some way.
+        rng = np.random.default_rng(2549824598234528)
+        n_resamples = 9999
+        def rvs(size):
+            return 1. * stats.bernoulli(p=0.333).rvs(size=size, random_state=rng)
+
+        x = rvs(100)
+        res = stats.monte_carlo_test(x, rvs, np.var, alternative='less',
+                                     n_resamples=n_resamples)
+        # show that having a tolerance matters
+        c0 = np.sum(res.null_distribution <= res.statistic)
+        c1 = np.sum(res.null_distribution <= res.statistic*(1+1e-15))
+        assert c0 != c1
+        assert res.pvalue == (c1 + 1)/(n_resamples + 1)
+
+
+class TestPower:
+    def test_input_validation(self):
+        # test that the appropriate error messages are raised for invalid input
+        rng = np.random.default_rng(8519895914314711673)
+
+        test = stats.ttest_ind
+        rvs = (rng.normal, rng.normal)
+        n_observations = (10, 12)
+
+        message = "`vectorized` must be `True`, `False`, or `None`."
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, n_observations, vectorized=1.5)
+
+        message = "`rvs` must be callable or sequence of callables."
+        with pytest.raises(TypeError, match=message):
+            power(test, None, n_observations)
+        with pytest.raises(TypeError, match=message):
+            power(test, (rng.normal, 'ekki'), n_observations)
+
+        message = "If `rvs` is a sequence..."
+        with pytest.raises(ValueError, match=message):
+            power(test, (rng.normal,), n_observations)
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, (10,))
+
+        message = "`significance` must contain floats between 0 and 1."
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, n_observations, significance=2)
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, n_observations, significance=np.linspace(-1, 1))
+
+        message = "`kwargs` must be a dictionary"
+        with pytest.raises(TypeError, match=message):
+            power(test, rvs, n_observations, kwargs=(1, 2, 3))
+
+        message = "shape mismatch: objects cannot be broadcast"
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, ([10, 11], [12, 13, 14]))
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, ([10, 11], [12, 13]), kwargs={'x': [1, 2, 3]})
+
+        message = "`test` must be callable"
+        with pytest.raises(TypeError, match=message):
+            power(None, rvs, n_observations)
+
+        message = "`n_resamples` must be a positive integer"
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, n_observations, n_resamples=-10)
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, n_observations, n_resamples=10.5)
+
+        message = "`batch` must be a positive integer"
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, n_observations, batch=-10)
+        with pytest.raises(ValueError, match=message):
+            power(test, rvs, n_observations, batch=10.5)
+
+    @pytest.mark.slow
+    def test_batch(self):
+        # make sure that the `batch` parameter is respected by checking the
+        # maximum batch size provided in calls to `test`
+        rng = np.random.default_rng(23492340193)
+
+        def test(x, axis):
+            batch_size = 1 if x.ndim == 1 else len(x)
+            test.batch_size = max(batch_size, test.batch_size)
+            test.counter += 1
+            return stats.ttest_1samp(x, 0, axis=axis).pvalue
+        test.counter = 0
+        test.batch_size = 0
+
+        kwds = dict(test=test, n_observations=10, n_resamples=1000)
+
+        rng = np.random.default_rng(23492340193)
+        res1 = power(**kwds, rvs=rng.normal, batch=1)
+        assert_equal(test.counter, 1000)
+        assert_equal(test.batch_size, 1)
+
+        rng = np.random.default_rng(23492340193)
+        test.counter = 0
+        res2 = power(**kwds, rvs=rng.normal, batch=50)
+        assert_equal(test.counter, 20)
+        assert_equal(test.batch_size, 50)
+
+        rng = np.random.default_rng(23492340193)
+        test.counter = 0
+        res3 = power(**kwds, rvs=rng.normal, batch=1000)
+        assert_equal(test.counter, 1)
+        assert_equal(test.batch_size, 1000)
+
+        assert_equal(res1.power, res3.power)
+        assert_equal(res2.power, res3.power)
+
+    @pytest.mark.slow
+    def test_vectorization(self):
+        # Test that `power` is vectorized as expected
+        rng = np.random.default_rng(25495254834552)
+
+        # Single vectorized call
+        popmeans = np.array([0, 0.2])
+        def test(x, alternative, axis=-1):
+            # ensure that popmeans axis is zeroth and orthogonal to the rest
+            popmeans_expanded = np.expand_dims(popmeans, tuple(range(1, x.ndim + 1)))
+            return stats.ttest_1samp(x, popmeans_expanded, alternative=alternative,
+                                     axis=axis)
+
+        # nx and kwargs broadcast against one another
+        nx = np.asarray([10, 15, 20, 50, 100])[:, np.newaxis]
+        kwargs = {'alternative': ['less', 'greater', 'two-sided']}
+
+        # This dimension is added to the beginning
+        significance = np.asarray([0.01, 0.025, 0.05, 0.1])
+        res = stats.power(test, rng.normal, nx, significance=significance,
+                          kwargs=kwargs)
+
+        # Looping over all combinations
+        ref = []
+        for significance_i in significance:
+            for nx_i in nx:
+                for alternative_i in kwargs['alternative']:
+                    for popmean_i in popmeans:
+                        def test2(x, axis=-1):
+                            return stats.ttest_1samp(x, popmean_i, axis=axis,
+                                                     alternative=alternative_i)
+
+                        tmp = stats.power(test2, rng.normal, nx_i,
+                                          significance=significance_i)
+                        ref.append(tmp.power)
+        ref = np.reshape(ref, res.power.shape)
+
+        # Show that results are similar
+        assert_allclose(res.power, ref, rtol=2e-2, atol=1e-2)
+
+    def test_ttest_ind_null(self):
+        # Check that the p-values of `ttest_ind` are uniformly distributed under
+        # the null hypothesis
+        rng = np.random.default_rng(254952548345528)
+
+        test = stats.ttest_ind
+        n_observations = rng.integers(10, 100, size=(2, 10))
+        rvs = rng.normal, rng.normal
+        significance = np.asarray([0.01, 0.05, 0.1])
+        res = stats.power(test, rvs, n_observations, significance=significance)
+        significance = np.broadcast_to(significance[:, np.newaxis], res.power.shape)
+        assert_allclose(res.power, significance, atol=1e-2)
+
+    def test_ttest_1samp_power(self):
+        # Check simulated ttest_1samp power against reference
+        rng = np.random.default_rng(254952548345528)
+
+        # Reference values computed with statmodels
+        # import numpy as np
+        # from statsmodels.stats.power import tt_solve_power
+        # tt_solve_power = np.vectorize(tt_solve_power)
+        # tt_solve_power([0.1, 0.5, 0.9], [[10], [20]], [[[0.01]], [[0.05]]])
+        ref = [[[0.0126515 , 0.10269751, 0.40415802],
+                [0.01657775, 0.29734608, 0.86228288]],
+               [[0.0592903 , 0.29317561, 0.71718121],
+                [0.07094116, 0.56450441, 0.96815163]]]
+
+        kwargs = {'popmean': [0.1, 0.5, 0.9]}
+        n_observations = [[10], [20]]
+        significance = [0.01, 0.05]
+        res = stats.power(stats.ttest_1samp, rng.normal, n_observations,
+                          significance=significance, kwargs=kwargs)
+        assert_allclose(res.power, ref, atol=1e-2)
+
+
+class TestPermutationTest:
+
+    rtol = 1e-14
+
+    def setup_method(self):
+        self.rng = np.random.default_rng(7170559330470561044)
+
+    # -- Input validation -- #
+
+    def test_permutation_test_iv(self):
+
+        def stat(x, y, axis):
+            return stats.ttest_ind((x, y), axis).statistic
+
+        message = "each sample in `data` must contain two or more ..."
+        with pytest.raises(ValueError, match=message):
+            permutation_test(([1, 2, 3], [1]), stat)
+
+        message = "`data` must be a tuple containing at least two samples"
+        with pytest.raises(ValueError, match=message):
+            permutation_test((1,), stat)
+        with pytest.raises(TypeError, match=message):
+            permutation_test(1, stat)
+
+        message = "`axis` must be an integer."
+        with pytest.raises(ValueError, match=message):
+            permutation_test(([1, 2, 3], [1, 2, 3]), stat, axis=1.5)
+
+        message = "`permutation_type` must be in..."
+        with pytest.raises(ValueError, match=message):
+            permutation_test(([1, 2, 3], [1, 2, 3]), stat,
+                             permutation_type="ekki")
+
+        message = "`vectorized` must be `True`, `False`, or `None`."
+        with pytest.raises(ValueError, match=message):
+            permutation_test(([1, 2, 3], [1, 2, 3]), stat, vectorized=1.5)
+
+        message = "`n_resamples` must be a positive integer."
+        with pytest.raises(ValueError, match=message):
+            permutation_test(([1, 2, 3], [1, 2, 3]), stat, n_resamples=-1000)
+
+        message = "`n_resamples` must be a positive integer."
+        with pytest.raises(ValueError, match=message):
+            permutation_test(([1, 2, 3], [1, 2, 3]), stat, n_resamples=1000.5)
+
+        message = "`batch` must be a positive integer or None."
+        with pytest.raises(ValueError, match=message):
+            permutation_test(([1, 2, 3], [1, 2, 3]), stat, batch=-1000)
+
+        message = "`batch` must be a positive integer or None."
+        with pytest.raises(ValueError, match=message):
+            permutation_test(([1, 2, 3], [1, 2, 3]), stat, batch=1000.5)
+
+        message = "`alternative` must be in..."
+        with pytest.raises(ValueError, match=message):
+            permutation_test(([1, 2, 3], [1, 2, 3]), stat, alternative='ekki')
+
+        message = "SeedSequence expects int or sequence of ints"
+        with pytest.raises(TypeError, match=message):
+            permutation_test(([1, 2, 3], [1, 2, 3]), stat, rng='herring')
+
+    # -- Test Parameters -- #
+    # SPEC-007 leave one call with seed to check it still works
+    @pytest.mark.parametrize('random_state', [np.random.RandomState,
+                                              np.random.default_rng])
+    @pytest.mark.parametrize('permutation_type',
+                             ['pairings', 'samples', 'independent'])
+    def test_batch(self, permutation_type, random_state):
+        # make sure that the `batch` parameter is respected by checking the
+        # maximum batch size provided in calls to `statistic`
+        x = self.rng.random(10)
+        y = self.rng.random(10)
+
+        def statistic(x, y, axis):
+            batch_size = 1 if x.ndim == 1 else len(x)
+            statistic.batch_size = max(batch_size, statistic.batch_size)
+            statistic.counter += 1
+            return np.mean(x, axis=axis) - np.mean(y, axis=axis)
+        statistic.counter = 0
+        statistic.batch_size = 0
+
+        kwds = {'n_resamples': 1000, 'permutation_type': permutation_type,
+                'vectorized': True}
+        res1 = stats.permutation_test((x, y), statistic, batch=1,
+                                      random_state=random_state(0), **kwds)
+        assert_equal(statistic.counter, 1001)
+        assert_equal(statistic.batch_size, 1)
+
+        statistic.counter = 0
+        res2 = stats.permutation_test((x, y), statistic, batch=50,
+                                      random_state=random_state(0), **kwds)
+        assert_equal(statistic.counter, 21)
+        assert_equal(statistic.batch_size, 50)
+
+        statistic.counter = 0
+        res3 = stats.permutation_test((x, y), statistic, batch=1000,
+                                      random_state=random_state(0), **kwds)
+        assert_equal(statistic.counter, 2)
+        assert_equal(statistic.batch_size, 1000)
+
+        assert_equal(res1.pvalue, res3.pvalue)
+        assert_equal(res2.pvalue, res3.pvalue)
+
+    # SPEC-007 leave at least one call with seed to check it still works
+    @pytest.mark.parametrize('random_state', [np.random.RandomState,
+                                              np.random.default_rng])
+    @pytest.mark.parametrize('permutation_type, exact_size',
+                             [('pairings', special.factorial(3)**2),
+                              ('samples', 2**3),
+                              ('independent', special.binom(6, 3))])
+    def test_permutations(self, permutation_type, exact_size, random_state):
+        # make sure that the `permutations` parameter is respected by checking
+        # the size of the null distribution
+        x = self.rng.random(3)
+        y = self.rng.random(3)
+
+        def statistic(x, y, axis):
+            return np.mean(x, axis=axis) - np.mean(y, axis=axis)
+
+        kwds = {'permutation_type': permutation_type,
+                'vectorized': True}
+        res = stats.permutation_test((x, y), statistic, n_resamples=3,
+                                     random_state=random_state(0), **kwds)
+        assert_equal(res.null_distribution.size, 3)
+
+        res = stats.permutation_test((x, y), statistic, **kwds)
+        assert_equal(res.null_distribution.size, exact_size)
+
+    # -- Randomized Permutation Tests -- #
+
+    # To get reasonable accuracy, these next three tests are somewhat slow.
+    # Originally, I had them passing for all combinations of permutation type,
+    # alternative, and RNG, but that takes too long for CI. Instead, split
+    # into three tests, each testing a particular combination of the three
+    # parameters.
+
+    def test_randomized_test_against_exact_both(self):
+        # check that the randomized and exact tests agree to reasonable
+        # precision for permutation_type='both
+
+        alternative, rng = 'less', 0
+
+        nx, ny, permutations = 8, 9, 24000
+        assert special.binom(nx + ny, nx) > permutations
+
+        x = stats.norm.rvs(size=nx)
+        y = stats.norm.rvs(size=ny)
+        data = x, y
+
+        def statistic(x, y, axis):
+            return np.mean(x, axis=axis) - np.mean(y, axis=axis)
+
+        kwds = {'vectorized': True, 'permutation_type': 'independent',
+                'batch': 100, 'alternative': alternative, 'rng': rng}
+        res = permutation_test(data, statistic, n_resamples=permutations,
+                               **kwds)
+        res2 = permutation_test(data, statistic, n_resamples=np.inf, **kwds)
+
+        assert res.statistic == res2.statistic
+        assert_allclose(res.pvalue, res2.pvalue, atol=1e-2)
+
+    @pytest.mark.slow()
+    def test_randomized_test_against_exact_samples(self):
+        # check that the randomized and exact tests agree to reasonable
+        # precision for permutation_type='samples'
+
+        alternative, rng = 'greater', None
+
+        nx, ny, permutations = 15, 15, 32000
+        assert 2**nx > permutations
+
+        x = stats.norm.rvs(size=nx)
+        y = stats.norm.rvs(size=ny)
+        data = x, y
+
+        def statistic(x, y, axis):
+            return np.mean(x - y, axis=axis)
+
+        kwds = {'vectorized': True, 'permutation_type': 'samples',
+                'batch': 100, 'alternative': alternative, 'rng': rng}
+        res = permutation_test(data, statistic, n_resamples=permutations,
+                               **kwds)
+        res2 = permutation_test(data, statistic, n_resamples=np.inf, **kwds)
+
+        assert res.statistic == res2.statistic
+        assert_allclose(res.pvalue, res2.pvalue, atol=1e-2)
+
+    def test_randomized_test_against_exact_pairings(self):
+        # check that the randomized and exact tests agree to reasonable
+        # precision for permutation_type='pairings'
+
+        alternative, rng = 'two-sided', self.rng
+
+        nx, ny, permutations = 8, 8, 40000
+        assert special.factorial(nx) > permutations
+
+        x = stats.norm.rvs(size=nx)
+        y = stats.norm.rvs(size=ny)
+        data = [x]
+
+        def statistic1d(x):
+            return stats.pearsonr(x, y)[0]
+
+        statistic = _resampling._vectorize_statistic(statistic1d)
+
+        kwds = {'vectorized': True, 'permutation_type': 'samples',
+                'batch': 100, 'alternative': alternative, 'rng': rng}
+        res = permutation_test(data, statistic, n_resamples=permutations,
+                               **kwds)
+        res2 = permutation_test(data, statistic, n_resamples=np.inf, **kwds)
+
+        assert res.statistic == res2.statistic
+        assert_allclose(res.pvalue, res2.pvalue, atol=1e-2)
+
+    # -- Independent (Unpaired) Sample Tests -- #
+
+    @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
+    def test_against_ks_2samp(self, alternative):
+
+        x = self.rng.normal(size=4, scale=1)
+        y = self.rng.normal(size=5, loc=3, scale=3)
+
+        expected = stats.ks_2samp(x, y, alternative=alternative, mode='exact')
+
+        def statistic1d(x, y):
+            return stats.ks_2samp(x, y, mode='asymp',
+                                  alternative=alternative).statistic
+
+        # ks_2samp is always a one-tailed 'greater' test
+        # it's the statistic that changes (D+ vs D- vs max(D+, D-))
+        res = permutation_test((x, y), statistic1d, n_resamples=np.inf,
+                               alternative='greater', rng=self.rng)
+
+        assert_allclose(res.statistic, expected.statistic, rtol=self.rtol)
+        assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol)
+
+    @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
+    def test_against_ansari(self, alternative):
+
+        x = self.rng.normal(size=4, scale=1)
+        y = self.rng.normal(size=5, scale=3)
+
+        # ansari has a different convention for 'alternative'
+        alternative_correspondence = {"less": "greater",
+                                      "greater": "less",
+                                      "two-sided": "two-sided"}
+        alternative_scipy = alternative_correspondence[alternative]
+        expected = stats.ansari(x, y, alternative=alternative_scipy)
+
+        def statistic1d(x, y):
+            return stats.ansari(x, y).statistic
+
+        res = permutation_test((x, y), statistic1d, n_resamples=np.inf,
+                               alternative=alternative, rng=self.rng)
+
+        assert_allclose(res.statistic, expected.statistic, rtol=self.rtol)
+        assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol)
+
+    @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
+    def test_against_mannwhitneyu(self, alternative):
+
+        x = stats.uniform.rvs(size=(3, 5, 2), loc=0, random_state=self.rng)
+        y = stats.uniform.rvs(size=(3, 5, 2), loc=0.05, random_state=self.rng)
+
+        expected = stats.mannwhitneyu(x, y, axis=1, alternative=alternative)
+
+        def statistic(x, y, axis):
+            return stats.mannwhitneyu(x, y, axis=axis).statistic
+
+        res = permutation_test((x, y), statistic, vectorized=True,
+                               n_resamples=np.inf, alternative=alternative,
+                               axis=1, rng=self.rng)
+
+        assert_allclose(res.statistic, expected.statistic, rtol=self.rtol)
+        assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol)
+
+    def test_against_cvm(self):
+
+        x = stats.norm.rvs(size=4, scale=1, random_state=self.rng)
+        y = stats.norm.rvs(size=5, loc=3, scale=3, random_state=self.rng)
+
+        expected = stats.cramervonmises_2samp(x, y, method='exact')
+
+        def statistic1d(x, y):
+            return stats.cramervonmises_2samp(x, y,
+                                              method='asymptotic').statistic
+
+        # cramervonmises_2samp has only one alternative, greater
+        res = permutation_test((x, y), statistic1d, n_resamples=np.inf,
+                               alternative='greater', rng=self.rng)
+
+        assert_allclose(res.statistic, expected.statistic, rtol=self.rtol)
+        assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol)
+
+    @pytest.mark.xslow()
+    @pytest.mark.parametrize('axis', (-1, 2))
+    def test_vectorized_nsamp_ptype_both(self, axis):
+        # Test that permutation_test with permutation_type='independent' works
+        # properly for a 3-sample statistic with nd array samples of different
+        # (but compatible) shapes and ndims. Show that exact permutation test
+        # and random permutation tests approximate SciPy's asymptotic pvalues
+        # and that exact and random permutation test results are even closer
+        # to one another (than they are to the asymptotic results).
+
+        # Three samples, different (but compatible) shapes with different ndims
+        rng = np.random.default_rng(6709265303529651545)
+        x = rng.random(size=(3))
+        y = rng.random(size=(1, 3, 2))
+        z = rng.random(size=(2, 1, 4))
+        data = (x, y, z)
+
+        # Define the statistic (and pvalue for comparison)
+        def statistic1d(*data):
+            return stats.kruskal(*data).statistic
+
+        def pvalue1d(*data):
+            return stats.kruskal(*data).pvalue
+
+        statistic = _resampling._vectorize_statistic(statistic1d)
+        pvalue = _resampling._vectorize_statistic(pvalue1d)
+
+        # Calculate the expected results
+        x2 = np.broadcast_to(x, (2, 3, 3))  # broadcast manually because
+        y2 = np.broadcast_to(y, (2, 3, 2))  # _vectorize_statistic doesn't
+        z2 = np.broadcast_to(z, (2, 3, 4))
+        expected_statistic = statistic(x2, y2, z2, axis=axis)
+        expected_pvalue = pvalue(x2, y2, z2, axis=axis)
+
+        # Calculate exact and randomized permutation results
+        kwds = {'vectorized': False, 'axis': axis, 'alternative': 'greater',
+                'permutation_type': 'independent', 'rng': self.rng}
+        res = permutation_test(data, statistic1d, n_resamples=np.inf, **kwds)
+        res2 = permutation_test(data, statistic1d, n_resamples=1000, **kwds)
+
+        # Check results
+        assert_allclose(res.statistic, expected_statistic, rtol=self.rtol)
+        assert_allclose(res.statistic, res2.statistic, rtol=self.rtol)
+        assert_allclose(res.pvalue, expected_pvalue, atol=6e-2)
+        assert_allclose(res.pvalue, res2.pvalue, atol=3e-2)
+
+    # -- Paired-Sample Tests -- #
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
+    def test_against_wilcoxon(self, alternative):
+
+        x = stats.uniform.rvs(size=(3, 6, 2), loc=0, random_state=self.rng)
+        y = stats.uniform.rvs(size=(3, 6, 2), loc=0.05, random_state=self.rng)
+
+        # We'll check both 1- and 2-sample versions of the same test;
+        # we expect identical results to wilcoxon in all cases.
+        def statistic_1samp_1d(z):
+            # 'less' ensures we get the same of two statistics every time
+            return stats.wilcoxon(z, alternative='less').statistic
+
+        def statistic_2samp_1d(x, y):
+            return stats.wilcoxon(x, y, alternative='less').statistic
+
+        def test_1d(x, y):
+            return stats.wilcoxon(x, y, alternative=alternative)
+
+        test = _resampling._vectorize_statistic(test_1d)
+
+        expected = test(x, y, axis=1)
+        expected_stat = expected[0]
+        expected_p = expected[1]
+
+        kwds = {'vectorized': False, 'axis': 1, 'alternative': alternative,
+                'permutation_type': 'samples', 'rng': self.rng,
+                'n_resamples': np.inf}
+        res1 = permutation_test((x-y,), statistic_1samp_1d, **kwds)
+        res2 = permutation_test((x, y), statistic_2samp_1d, **kwds)
+
+        # `wilcoxon` returns a different statistic with 'two-sided'
+        assert_allclose(res1.statistic, res2.statistic, rtol=self.rtol)
+        if alternative != 'two-sided':
+            assert_allclose(res2.statistic, expected_stat, rtol=self.rtol)
+
+        assert_allclose(res2.pvalue, expected_p, rtol=self.rtol)
+        assert_allclose(res1.pvalue, res2.pvalue, rtol=self.rtol)
+
+    @pytest.mark.parametrize('alternative', ("less", "greater", "two-sided"))
+    def test_against_binomtest(self, alternative):
+
+        x = self.rng.integers(0, 2, size=10)
+        x[x == 0] = -1
+        # More naturally, the test would flip elements between 0 and one.
+        # However, permutation_test will flip the _signs_ of the elements.
+        # So we have to work with +1/-1 instead of 1/0.
+
+        def statistic(x, axis=0):
+            return np.sum(x > 0, axis=axis)
+
+        k, n, p = statistic(x), 10, 0.5
+        expected = stats.binomtest(k, n, p, alternative=alternative)
+
+        res = stats.permutation_test((x,), statistic, vectorized=True,
+                                     permutation_type='samples',
+                                     n_resamples=np.inf, rng=self.rng,
+                                     alternative=alternative)
+        assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol)
+
+    # -- Exact Association Tests -- #
+
+    def test_against_kendalltau(self):
+
+        x = self.rng.normal(size=6)
+        y = x + self.rng.normal(size=6)
+
+        expected = stats.kendalltau(x, y, method='exact')
+
+        def statistic1d(x):
+            return stats.kendalltau(x, y, method='asymptotic').statistic
+
+        # kendalltau currently has only one alternative, two-sided
+        res = permutation_test((x,), statistic1d, permutation_type='pairings',
+                               n_resamples=np.inf, rng=self.rng)
+
+        assert_allclose(res.statistic, expected.statistic, rtol=self.rtol)
+        assert_allclose(res.pvalue, expected.pvalue, rtol=self.rtol)
+
+    @pytest.mark.parametrize('alternative', ('less', 'greater', 'two-sided'))
+    def test_against_fisher_exact(self, alternative):
+
+        def statistic(x,):
+            return np.sum((x == 1) & (y == 1))
+
+        # x and y are binary random variables with some dependence
+        rng = np.random.default_rng(6235696159000529929)
+        x = (rng.random(7) > 0.6).astype(float)
+        y = (rng.random(7) + 0.25*x > 0.6).astype(float)
+        tab = stats.contingency.crosstab(x, y)[1]
+
+        res = permutation_test((x,), statistic, permutation_type='pairings',
+                               n_resamples=np.inf, alternative=alternative,
+                               rng=rng)
+        res2 = stats.fisher_exact(tab, alternative=alternative)
+
+        assert_allclose(res.pvalue, res2[1])
+
+    @pytest.mark.xslow()
+    @pytest.mark.parametrize('axis', (-2, 1))
+    def test_vectorized_nsamp_ptype_samples(self, axis):
+        # Test that permutation_test with permutation_type='samples' works
+        # properly for a 3-sample statistic with nd array samples of different
+        # (but compatible) shapes and ndims. Show that exact permutation test
+        # reproduces SciPy's exact pvalue and that random permutation test
+        # approximates it.
+
+        x = self.rng.random(size=(2, 4, 3))
+        y = self.rng.random(size=(1, 4, 3))
+        z = self.rng.random(size=(2, 4, 1))
+        x = stats.rankdata(x, axis=axis)
+        y = stats.rankdata(y, axis=axis)
+        z = stats.rankdata(z, axis=axis)
+        y = y[0]  # to check broadcast with different ndim
+        data = (x, y, z)
+
+        def statistic1d(*data):
+            return stats.page_trend_test(data, ranked=True,
+                                         method='asymptotic').statistic
+
+        def pvalue1d(*data):
+            return stats.page_trend_test(data, ranked=True,
+                                         method='exact').pvalue
+
+        statistic = _resampling._vectorize_statistic(statistic1d)
+        pvalue = _resampling._vectorize_statistic(pvalue1d)
+
+        expected_statistic = statistic(*np.broadcast_arrays(*data), axis=axis)
+        expected_pvalue = pvalue(*np.broadcast_arrays(*data), axis=axis)
+
+        # Let's forgive this use of an integer seed, please.
+        kwds = {'vectorized': False, 'axis': axis, 'alternative': 'greater',
+                'permutation_type': 'pairings', 'rng': 0}
+        res = permutation_test(data, statistic1d, n_resamples=np.inf, **kwds)
+        res2 = permutation_test(data, statistic1d, n_resamples=5000, **kwds)
+
+        assert_allclose(res.statistic, expected_statistic, rtol=self.rtol)
+        assert_allclose(res.statistic, res2.statistic, rtol=self.rtol)
+        assert_allclose(res.pvalue, expected_pvalue, rtol=self.rtol)
+        assert_allclose(res.pvalue, res2.pvalue, atol=3e-2)
+
+    # -- Test Against External References -- #
+
+    tie_case_1 = {'x': [1, 2, 3, 4], 'y': [1.5, 2, 2.5],
+                  'expected_less': 0.2000000000,
+                  'expected_2sided': 0.4,  # 2*expected_less
+                  'expected_Pr_gte_S_mean': 0.3428571429,  # see note below
+                  'expected_statistic': 7.5,
+                  'expected_avg': 9.142857, 'expected_std': 1.40698}
+    tie_case_2 = {'x': [111, 107, 100, 99, 102, 106, 109, 108],
+                  'y': [107, 108, 106, 98, 105, 103, 110, 105, 104],
+                  'expected_less': 0.1555738379,
+                  'expected_2sided': 0.3111476758,
+                  'expected_Pr_gte_S_mean': 0.2969971205,  # see note below
+                  'expected_statistic': 32.5,
+                  'expected_avg': 38.117647, 'expected_std': 5.172124}
+
+    @pytest.mark.xslow()  # only the second case is slow, really
+    @pytest.mark.parametrize('case', (tie_case_1, tie_case_2))
+    def test_with_ties(self, case):
+        """
+        Results above from SAS PROC NPAR1WAY, e.g.
+
+        DATA myData;
+        INPUT X Y;
+        CARDS;
+        1 1
+        1 2
+        1 3
+        1 4
+        2 1.5
+        2 2
+        2 2.5
+        ods graphics on;
+        proc npar1way AB data=myData;
+            class X;
+            EXACT;
+        run;
+        ods graphics off;
+
+        Note: SAS provides Pr >= |S-Mean|, which is different from our
+        definition of a two-sided p-value.
+
+        """
+
+        x = case['x']
+        y = case['y']
+
+        expected_statistic = case['expected_statistic']
+        expected_less = case['expected_less']
+        expected_2sided = case['expected_2sided']
+        expected_Pr_gte_S_mean = case['expected_Pr_gte_S_mean']
+        expected_avg = case['expected_avg']
+        expected_std = case['expected_std']
+
+        def statistic1d(x, y):
+            return stats.ansari(x, y).statistic
+
+        with np.testing.suppress_warnings() as sup:
+            sup.filter(UserWarning, "Ties preclude use of exact statistic")
+            res = permutation_test((x, y), statistic1d, n_resamples=np.inf,
+                                   alternative='less')
+            res2 = permutation_test((x, y), statistic1d, n_resamples=np.inf,
+                                    alternative='two-sided')
+
+        assert_allclose(res.statistic, expected_statistic, rtol=self.rtol)
+        assert_allclose(res.pvalue, expected_less, atol=1e-10)
+        assert_allclose(res2.pvalue, expected_2sided, atol=1e-10)
+        assert_allclose(res2.null_distribution.mean(), expected_avg, rtol=1e-6)
+        assert_allclose(res2.null_distribution.std(), expected_std, rtol=1e-6)
+
+        # SAS provides Pr >= |S-Mean|; might as well check against that, too
+        S = res.statistic
+        mean = res.null_distribution.mean()
+        n = len(res.null_distribution)
+        Pr_gte_S_mean = np.sum(np.abs(res.null_distribution-mean)
+                               >= np.abs(S-mean))/n
+        assert_allclose(expected_Pr_gte_S_mean, Pr_gte_S_mean)
+
+    @pytest.mark.slow
+    @pytest.mark.parametrize('alternative, expected_pvalue',
+                             (('less', 0.9708333333333),
+                              ('greater', 0.05138888888889),
+                              ('two-sided', 0.1027777777778)))
+    def test_against_spearmanr_in_R(self, alternative, expected_pvalue):
+        """
+        Results above from R cor.test, e.g.
+
+        options(digits=16)
+        x <- c(1.76405235, 0.40015721, 0.97873798,
+               2.2408932, 1.86755799, -0.97727788)
+        y <- c(2.71414076, 0.2488, 0.87551913,
+               2.6514917, 2.01160156, 0.47699563)
+        cor.test(x, y, method = "spearm", alternative = "t")
+        """
+        # data comes from
+        # np.random.seed(0)
+        # x = stats.norm.rvs(size=6)
+        # y = x + stats.norm.rvs(size=6)
+        x = [1.76405235, 0.40015721, 0.97873798,
+             2.2408932, 1.86755799, -0.97727788]
+        y = [2.71414076, 0.2488, 0.87551913,
+             2.6514917, 2.01160156, 0.47699563]
+        expected_statistic = 0.7714285714285715
+
+        def statistic1d(x):
+            return stats.spearmanr(x, y).statistic
+
+        res = permutation_test((x,), statistic1d, permutation_type='pairings',
+                               n_resamples=np.inf, alternative=alternative)
+
+        assert_allclose(res.statistic, expected_statistic, rtol=self.rtol)
+        assert_allclose(res.pvalue, expected_pvalue, atol=1e-13)
+
+    @pytest.mark.parametrize("batch", (-1, 0))
+    def test_batch_generator_iv(self, batch):
+        with pytest.raises(ValueError, match="`batch` must be positive."):
+            list(_resampling._batch_generator([1, 2, 3], batch))
+
+    batch_generator_cases = [(range(0), 3, []),
+                             (range(6), 3, [[0, 1, 2], [3, 4, 5]]),
+                             (range(8), 3, [[0, 1, 2], [3, 4, 5], [6, 7]])]
+
+    @pytest.mark.parametrize("iterable, batch, expected",
+                             batch_generator_cases)
+    def test_batch_generator(self, iterable, batch, expected):
+        got = list(_resampling._batch_generator(iterable, batch))
+        assert got == expected
+
+    @pytest.mark.fail_slow(2)
+    def test_finite_precision_statistic(self):
+        # Some statistics return numerically distinct values when the values
+        # should be equal in theory. Test that `permutation_test` accounts
+        # for this in some way.
+        x = [1, 2, 4, 3]
+        y = [2, 4, 6, 8]
+
+        def statistic(x, y):
+            return stats.pearsonr(x, y)[0]
+
+        res = stats.permutation_test((x, y), statistic, vectorized=False,
+                                     permutation_type='pairings')
+        r, pvalue, null = res.statistic, res.pvalue, res.null_distribution
+
+        correct_p = 2 * np.sum(null >= r - 1e-14) / len(null)
+        assert pvalue == correct_p == 1/3
+        # Compare against other exact correlation tests using R corr.test
+        # options(digits=16)
+        # x = c(1, 2, 4, 3)
+        # y = c(2, 4, 6, 8)
+        # cor.test(x, y, alternative = "t", method = "spearman")  # 0.333333333
+        # cor.test(x, y, alternative = "t", method = "kendall")  # 0.333333333
+
+
+def test_all_partitions_concatenated():
+    # make sure that _all_paritions_concatenated produces the correct number
+    # of partitions of the data into samples of the given sizes and that
+    # all are unique
+    n = np.array([3, 2, 4], dtype=int)
+    nc = np.cumsum(n)
+
+    all_partitions = set()
+    counter = 0
+    for partition_concatenated in _resampling._all_partitions_concatenated(n):
+        counter += 1
+        partitioning = np.split(partition_concatenated, nc[:-1])
+        all_partitions.add(tuple([frozenset(i) for i in partitioning]))
+
+    expected = np.prod([special.binom(sum(n[i:]), sum(n[i+1:]))
+                        for i in range(len(n)-1)])
+
+    assert_equal(counter, expected)
+    assert_equal(len(all_partitions), expected)
+
+
+@pytest.mark.parametrize('fun_name',
+                         ['bootstrap', 'permutation_test', 'monte_carlo_test'])
+def test_parameter_vectorized(fun_name):
+    # Check that parameter `vectorized` is working as desired for all
+    # resampling functions. Results don't matter; just don't fail asserts.
+    rng = np.random.default_rng(75245098234592)
+    sample = rng.random(size=10)
+
+    def rvs(size):  # needed by `monte_carlo_test`
+        return stats.norm.rvs(size=size, random_state=rng)
+
+    fun_options = {'bootstrap': {'data': (sample,), 'rng': rng,
+                                 'method': 'percentile'},
+                   'permutation_test': {'data': (sample,), 'rng': rng,
+                                        'permutation_type': 'samples'},
+                   'monte_carlo_test': {'sample': sample, 'rvs': rvs}}
+    common_options = {'n_resamples': 100}
+
+    fun = getattr(stats, fun_name)
+    options = fun_options[fun_name]
+    options.update(common_options)
+
+    def statistic(x, axis):
+        assert x.ndim > 1 or np.array_equal(x, sample)
+        return np.mean(x, axis=axis)
+    fun(statistic=statistic, vectorized=None, **options)
+    fun(statistic=statistic, vectorized=True, **options)
+
+    def statistic(x):
+        assert x.ndim == 1
+        return np.mean(x)
+    fun(statistic=statistic, vectorized=None, **options)
+    fun(statistic=statistic, vectorized=False, **options)
+
+
+class TestMonteCarloMethod:
+    def test_rvs_and_random_state(self):
+        message = "Use of `rvs` and `rng` are mutually exclusive."
+        rng = np.random.default_rng(34982345)
+        with pytest.raises(ValueError, match=message):
+            stats.MonteCarloMethod(rvs=rng.random, rng=rng)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sampling.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sampling.py
new file mode 100644
index 0000000000000000000000000000000000000000..978511e09ca34a525f6c39e04a5344bc1cd2f7f3
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sampling.py
@@ -0,0 +1,1445 @@
+import threading
+import pickle
+import pytest
+from copy import deepcopy
+import platform
+import sys
+import math
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, suppress_warnings
+from scipy.stats.sampling import (
+    TransformedDensityRejection,
+    DiscreteAliasUrn,
+    DiscreteGuideTable,
+    NumericalInversePolynomial,
+    NumericalInverseHermite,
+    RatioUniforms,
+    SimpleRatioUniforms,
+    UNURANError
+)
+from pytest import raises as assert_raises
+from scipy import stats
+from scipy import special
+from scipy.stats import chisquare, cramervonmises
+from scipy.stats._distr_params import distdiscrete, distcont
+from scipy._lib._util import check_random_state
+
+
+# common test data: this data can be shared between all the tests.
+
+
+# Normal distribution shared between all the continuous methods
+class StandardNormal:
+    def pdf(self, x):
+        # normalization constant needed for NumericalInverseHermite
+        return 1./np.sqrt(2.*np.pi) * np.exp(-0.5 * x*x)
+
+    def dpdf(self, x):
+        return 1./np.sqrt(2.*np.pi) * -x * np.exp(-0.5 * x*x)
+
+    def cdf(self, x):
+        return special.ndtr(x)
+
+
+all_methods = [
+    ("TransformedDensityRejection", {"dist": StandardNormal()}),
+    ("DiscreteAliasUrn", {"dist": [0.02, 0.18, 0.8]}),
+    ("DiscreteGuideTable", {"dist": [0.02, 0.18, 0.8]}),
+    ("NumericalInversePolynomial", {"dist": StandardNormal()}),
+    ("NumericalInverseHermite", {"dist": StandardNormal()}),
+    ("SimpleRatioUniforms", {"dist": StandardNormal(), "mode": 0})
+]
+
+if (sys.implementation.name == 'pypy'
+        and sys.implementation.version < (7, 3, 10)):
+    # changed in PyPy for v7.3.10
+    floaterr = r"unsupported operand type for float\(\): 'list'"
+else:
+    floaterr = r"must be real number, not list"
+# Make sure an internal error occurs in UNU.RAN when invalid callbacks are
+# passed. Moreover, different generators throw different error messages.
+# So, in case of an `UNURANError`, we do not validate the error message.
+bad_pdfs_common = [
+    # Negative PDF
+    (lambda x: -x, UNURANError, r"..."),
+    # Returning wrong type
+    (lambda x: [], TypeError, floaterr),
+    # Undefined name inside the function
+    (lambda x: foo, NameError, r"name 'foo' is not defined"),  # type: ignore[name-defined]  # noqa: F821, E501
+    # Infinite value returned => Overflow error.
+    (lambda x: np.inf, UNURANError, r"..."),
+    # NaN value => internal error in UNU.RAN
+    (lambda x: np.nan, UNURANError, r"..."),
+    # signature of PDF wrong
+    (lambda: 1.0, TypeError, r"takes 0 positional arguments but 1 was given")
+]
+
+
+# same approach for dpdf
+bad_dpdf_common = [
+    # Infinite value returned.
+    (lambda x: np.inf, UNURANError, r"..."),
+    # NaN value => internal error in UNU.RAN
+    (lambda x: np.nan, UNURANError, r"..."),
+    # Returning wrong type
+    (lambda x: [], TypeError, floaterr),
+    # Undefined name inside the function
+    (lambda x: foo, NameError, r"name 'foo' is not defined"),  # type: ignore[name-defined]  # noqa: F821, E501
+    # signature of dPDF wrong
+    (lambda: 1.0, TypeError, r"takes 0 positional arguments but 1 was given")
+]
+
+
+# same approach for logpdf
+bad_logpdfs_common = [
+    # Returning wrong type
+    (lambda x: [], TypeError, floaterr),
+    # Undefined name inside the function
+    (lambda x: foo, NameError, r"name 'foo' is not defined"),  # type: ignore[name-defined]  # noqa: F821, E501
+    # Infinite value returned => Overflow error.
+    (lambda x: np.inf, UNURANError, r"..."),
+    # NaN value => internal error in UNU.RAN
+    (lambda x: np.nan, UNURANError, r"..."),
+    # signature of logpdf wrong
+    (lambda: 1.0, TypeError, r"takes 0 positional arguments but 1 was given")
+]
+
+
+bad_pv_common = [
+    ([], r"must contain at least one element"),
+    ([[1.0, 0.0]], r"wrong number of dimensions \(expected 1, got 2\)"),
+    ([0.2, 0.4, np.nan, 0.8], r"must contain only finite / non-nan values"),
+    ([0.2, 0.4, np.inf, 0.8], r"must contain only finite / non-nan values"),
+    ([0.0, 0.0], r"must contain at least one non-zero value"),
+]
+
+
+# size of the domains is incorrect
+bad_sized_domains = [
+    # > 2 elements in the domain
+    ((1, 2, 3), ValueError, r"must be a length 2 tuple"),
+    # empty domain
+    ((), ValueError, r"must be a length 2 tuple")
+]
+
+# domain values are incorrect
+bad_domains = [
+    ((2, 1), UNURANError, r"left >= right"),
+    ((1, 1), UNURANError, r"left >= right"),
+]
+
+# infinite and nan values present in domain.
+inf_nan_domains = [
+    # left >= right
+    ((10, 10), UNURANError, r"left >= right"),
+    ((np.inf, np.inf), UNURANError, r"left >= right"),
+    ((-np.inf, -np.inf), UNURANError, r"left >= right"),
+    ((np.inf, -np.inf), UNURANError, r"left >= right"),
+    # Also include nans in some of the domains.
+    ((-np.inf, np.nan), ValueError, r"only non-nan values"),
+    ((np.nan, np.inf), ValueError, r"only non-nan values")
+]
+
+# `nan` values present in domain. Some distributions don't support
+# infinite tails, so don't mix the nan values with infinities.
+nan_domains = [
+    ((0, np.nan), ValueError, r"only non-nan values"),
+    ((np.nan, np.nan), ValueError, r"only non-nan values")
+]
+
+
+# all the methods should throw errors for nan, bad sized, and bad valued
+# domains.
+@pytest.mark.parametrize("domain, err, msg",
+                         bad_domains + bad_sized_domains +
+                         nan_domains)  # type: ignore[operator]
+@pytest.mark.parametrize("method, kwargs", all_methods)
+def test_bad_domain(domain, err, msg, method, kwargs):
+    Method = getattr(stats.sampling, method)
+    with pytest.raises(err, match=msg):
+        Method(**kwargs, domain=domain)
+
+
+@pytest.mark.parametrize("method, kwargs", all_methods)
+def test_random_state(method, kwargs):
+    Method = getattr(stats.sampling, method)
+
+    # simple seed that works for any version of NumPy
+    seed = 123
+    rng1 = Method(**kwargs, random_state=seed)
+    rng2 = Method(**kwargs, random_state=seed)
+    assert_equal(rng1.rvs(100), rng2.rvs(100))
+
+    # global seed
+    np.random.seed(123)
+    rng1 = Method(**kwargs)
+    rvs1 = rng1.rvs(100)
+    np.random.seed(None)
+    rng2 = Method(**kwargs, random_state=123)
+    rvs2 = rng2.rvs(100)
+    assert_equal(rvs1, rvs2)
+
+    # Generator seed for new NumPy
+    # when a RandomState is given, it should take the bitgen_t
+    # member of the class and create a Generator instance.
+    seed1 = np.random.RandomState(np.random.MT19937(123))
+    seed2 = np.random.Generator(np.random.MT19937(123))
+    rng1 = Method(**kwargs, random_state=seed1)
+    rng2 = Method(**kwargs, random_state=seed2)
+    assert_equal(rng1.rvs(100), rng2.rvs(100))
+
+
+def test_set_random_state():
+    rng1 = TransformedDensityRejection(StandardNormal(), random_state=123)
+    rng2 = TransformedDensityRejection(StandardNormal())
+    rng2.set_random_state(123)
+    assert_equal(rng1.rvs(100), rng2.rvs(100))
+    rng = TransformedDensityRejection(StandardNormal(), random_state=123)
+    rvs1 = rng.rvs(100)
+    rng.set_random_state(123)
+    rvs2 = rng.rvs(100)
+    assert_equal(rvs1, rvs2)
+
+
+def test_threading_behaviour():
+    # Test if the API is thread-safe.
+    # This verifies if the lock mechanism and the use of `PyErr_Occurred`
+    # is correct.
+    errors = {"err1": None, "err2": None}
+
+    class Distribution:
+        def __init__(self, pdf_msg):
+            self.pdf_msg = pdf_msg
+
+        def pdf(self, x):
+            if 49.9 < x < 50.0:
+                raise ValueError(self.pdf_msg)
+            return x
+
+        def dpdf(self, x):
+            return 1
+
+    def func1():
+        dist = Distribution('foo')
+        rng = TransformedDensityRejection(dist, domain=(10, 100),
+                                          random_state=12)
+        try:
+            rng.rvs(100000)
+        except ValueError as e:
+            errors['err1'] = e.args[0]
+
+    def func2():
+        dist = Distribution('bar')
+        rng = TransformedDensityRejection(dist, domain=(10, 100),
+                                          random_state=2)
+        try:
+            rng.rvs(100000)
+        except ValueError as e:
+            errors['err2'] = e.args[0]
+
+    t1 = threading.Thread(target=func1)
+    t2 = threading.Thread(target=func2)
+
+    t1.start()
+    t2.start()
+
+    t1.join()
+    t2.join()
+
+    assert errors['err1'] == 'foo'
+    assert errors['err2'] == 'bar'
+
+
+@pytest.mark.parametrize("method, kwargs", all_methods)
+def test_pickle(method, kwargs):
+    Method = getattr(stats.sampling, method)
+    rng1 = Method(**kwargs, random_state=123)
+    obj = pickle.dumps(rng1)
+    rng2 = pickle.loads(obj)
+    assert_equal(rng1.rvs(100), rng2.rvs(100))
+
+
+@pytest.mark.parametrize("size", [None, 0, (0, ), 1, (10, 3), (2, 3, 4, 5),
+                                  (0, 0), (0, 1)])
+def test_rvs_size(size):
+    # As the `rvs` method is present in the base class and shared between
+    # all the classes, we can just test with one of the methods.
+    rng = TransformedDensityRejection(StandardNormal())
+    if size is None:
+        assert np.isscalar(rng.rvs(size))
+    else:
+        if np.isscalar(size):
+            size = (size, )
+        assert rng.rvs(size).shape == size
+
+
+def test_with_scipy_distribution():
+    # test if the setup works with SciPy's rv_frozen distributions
+    dist = stats.norm()
+    urng = np.random.default_rng(0)
+    rng = NumericalInverseHermite(dist, random_state=urng)
+    u = np.linspace(0, 1, num=100)
+    check_cont_samples(rng, dist, dist.stats())
+    assert_allclose(dist.ppf(u), rng.ppf(u))
+    # test if it works with `loc` and `scale`
+    dist = stats.norm(loc=10., scale=5.)
+    rng = NumericalInverseHermite(dist, random_state=urng)
+    check_cont_samples(rng, dist, dist.stats())
+    assert_allclose(dist.ppf(u), rng.ppf(u))
+    # check for discrete distributions
+    dist = stats.binom(10, 0.2)
+    rng = DiscreteAliasUrn(dist, random_state=urng)
+    domain = dist.support()
+    pv = dist.pmf(np.arange(domain[0], domain[1]+1))
+    check_discr_samples(rng, pv, dist.stats())
+
+
+def check_cont_samples(rng, dist, mv_ex, rtol=1e-7, atol=1e-1):
+    rvs = rng.rvs(100000)
+    mv = rvs.mean(), rvs.var()
+    # test the moments only if the variance is finite
+    if np.isfinite(mv_ex[1]):
+        assert_allclose(mv, mv_ex, rtol=rtol, atol=atol)
+    # Cramer Von Mises test for goodness-of-fit
+    rvs = rng.rvs(500)
+    dist.cdf = np.vectorize(dist.cdf)
+    pval = cramervonmises(rvs, dist.cdf).pvalue
+    assert pval > 0.1
+
+
+def check_discr_samples(rng, pv, mv_ex, rtol=1e-3, atol=1e-1):
+    rvs = rng.rvs(100000)
+    # test if the first few moments match
+    mv = rvs.mean(), rvs.var()
+    assert_allclose(mv, mv_ex, rtol=rtol, atol=atol)
+    # normalize
+    pv = pv / pv.sum()
+    # chi-squared test for goodness-of-fit
+    obs_freqs = np.zeros_like(pv)
+    _, freqs = np.unique(rvs, return_counts=True)
+    freqs = freqs / freqs.sum()
+    obs_freqs[:freqs.size] = freqs
+    pval = chisquare(obs_freqs, pv).pvalue
+    assert pval > 0.1
+
+
+def test_warning_center_not_in_domain():
+    # UNURAN will warn if the center provided or the one computed w/o the
+    # domain is outside of the domain
+    msg = "102 : center moved into domain of distribution"
+    with pytest.warns(RuntimeWarning, match=msg):
+        NumericalInversePolynomial(StandardNormal(), center=0, domain=(3, 5))
+    with pytest.warns(RuntimeWarning, match=msg):
+        NumericalInversePolynomial(StandardNormal(), domain=(3, 5))
+
+
+@pytest.mark.parametrize('method', ["SimpleRatioUniforms",
+                                    "NumericalInversePolynomial",
+                                    "TransformedDensityRejection"])
+def test_error_mode_not_in_domain(method):
+    # UNURAN raises an error if the mode is not in the domain
+    # the behavior is different compared to the case that center is not in the
+    # domain. mode is supposed to be the exact value, center can be an
+    # approximate value
+    Method = getattr(stats.sampling, method)
+    msg = "17 : mode not in domain"
+    with pytest.raises(UNURANError, match=msg):
+        Method(StandardNormal(), mode=0, domain=(3, 5))
+
+
+@pytest.mark.parametrize('method', ["NumericalInverseHermite",
+                                    "NumericalInversePolynomial"])
+class TestQRVS:
+    def test_input_validation(self, method):
+        match = "`qmc_engine` must be an instance of..."
+        with pytest.raises(ValueError, match=match):
+            Method = getattr(stats.sampling, method)
+            gen = Method(StandardNormal())
+            gen.qrvs(qmc_engine=0)
+
+        # issues with QMCEngines and old NumPy
+        Method = getattr(stats.sampling, method)
+        gen = Method(StandardNormal())
+
+        match = "`d` must be consistent with dimension of `qmc_engine`."
+        with pytest.raises(ValueError, match=match):
+            gen.qrvs(d=3, qmc_engine=stats.qmc.Halton(2))
+
+    qrngs = [None, stats.qmc.Sobol(1, seed=0), stats.qmc.Halton(3, seed=0)]
+    # `size=None` should not add anything to the shape, `size=1` should
+    sizes = [(None, tuple()), (1, (1,)), (4, (4,)),
+             ((4,), (4,)), ((2, 4), (2, 4))]  # type: ignore
+    # Neither `d=None` nor `d=1` should add anything to the shape
+    ds = [(None, tuple()), (1, tuple()), (3, (3,))]
+
+    @pytest.mark.parametrize('qrng', qrngs)
+    @pytest.mark.parametrize('size_in, size_out', sizes)
+    @pytest.mark.parametrize('d_in, d_out', ds)
+    def test_QRVS_shape_consistency(self, qrng, size_in, size_out,
+                                    d_in, d_out, method):
+        w32 = sys.platform == "win32" and platform.architecture()[0] == "32bit"
+        if w32 and method == "NumericalInversePolynomial":
+            pytest.xfail("NumericalInversePolynomial.qrvs fails for Win "
+                         "32-bit")
+
+        dist = StandardNormal()
+        Method = getattr(stats.sampling, method)
+        gen = Method(dist)
+
+        # If d and qrng.d are inconsistent, an error is raised
+        if d_in is not None and qrng is not None and qrng.d != d_in:
+            match = "`d` must be consistent with dimension of `qmc_engine`."
+            with pytest.raises(ValueError, match=match):
+                gen.qrvs(size_in, d=d_in, qmc_engine=qrng)
+            return
+
+        # Sometimes d is really determined by qrng
+        if d_in is None and qrng is not None and qrng.d != 1:
+            d_out = (qrng.d,)
+
+        shape_expected = size_out + d_out
+
+        qrng2 = deepcopy(qrng)
+        qrvs = gen.qrvs(size=size_in, d=d_in, qmc_engine=qrng)
+        if size_in is not None:
+            assert qrvs.shape == shape_expected
+
+        if qrng2 is not None:
+            uniform = qrng2.random(np.prod(size_in) or 1)
+            qrvs2 = stats.norm.ppf(uniform).reshape(shape_expected)
+            assert_allclose(qrvs, qrvs2, atol=1e-12)
+
+    def test_QRVS_size_tuple(self, method):
+        # QMCEngine samples are always of shape (n, d). When `size` is a tuple,
+        # we set `n = prod(size)` in the call to qmc_engine.random, transform
+        # the sample, and reshape it to the final dimensions. When we reshape,
+        # we need to be careful, because the _columns_ of the sample returned
+        # by a QMCEngine are "independent"-ish, but the elements within the
+        # columns are not. We need to make sure that this doesn't get mixed up
+        # by reshaping: qrvs[..., i] should remain "independent"-ish of
+        # qrvs[..., i+1], but the elements within qrvs[..., i] should be
+        # transformed from the same low-discrepancy sequence.
+
+        dist = StandardNormal()
+        Method = getattr(stats.sampling, method)
+        gen = Method(dist)
+
+        size = (3, 4)
+        d = 5
+        qrng = stats.qmc.Halton(d, seed=0)
+        qrng2 = stats.qmc.Halton(d, seed=0)
+
+        uniform = qrng2.random(np.prod(size))
+
+        qrvs = gen.qrvs(size=size, d=d, qmc_engine=qrng)
+        qrvs2 = stats.norm.ppf(uniform)
+
+        for i in range(d):
+            sample = qrvs[..., i]
+            sample2 = qrvs2[:, i].reshape(size)
+            assert_allclose(sample, sample2, atol=1e-12)
+
+
+class TestTransformedDensityRejection:
+    # Simple Custom Distribution
+    class dist0:
+        def pdf(self, x):
+            return 3/4 * (1-x*x)
+
+        def dpdf(self, x):
+            return 3/4 * (-2*x)
+
+        def cdf(self, x):
+            return 3/4 * (x - x**3/3 + 2/3)
+
+        def support(self):
+            return -1, 1
+
+    # Standard Normal Distribution
+    class dist1:
+        def pdf(self, x):
+            return stats.norm._pdf(x / 0.1)
+
+        def dpdf(self, x):
+            return -x / 0.01 * stats.norm._pdf(x / 0.1)
+
+        def cdf(self, x):
+            return stats.norm._cdf(x / 0.1)
+
+    # pdf with piecewise linear function as transformed density
+    # with T = -1/sqrt with shift. Taken from UNU.RAN test suite
+    # (from file t_tdr_ps.c)
+    class dist2:
+        def __init__(self, shift):
+            self.shift = shift
+
+        def pdf(self, x):
+            x -= self.shift
+            y = 1. / (abs(x) + 1.)
+            return 0.5 * y * y
+
+        def dpdf(self, x):
+            x -= self.shift
+            y = 1. / (abs(x) + 1.)
+            y = y * y * y
+            return y if (x < 0.) else -y
+
+        def cdf(self, x):
+            x -= self.shift
+            if x <= 0.:
+                return 0.5 / (1. - x)
+            else:
+                return 1. - 0.5 / (1. + x)
+
+    dists = [dist0(), dist1(), dist2(0.), dist2(10000.)]
+
+    # exact mean and variance of the distributions in the list dists
+    mv0 = [0., 4./15.]
+    mv1 = [0., 0.01]
+    mv2 = [0., np.inf]
+    mv3 = [10000., np.inf]
+    mvs = [mv0, mv1, mv2, mv3]
+
+    @pytest.mark.parametrize("dist, mv_ex",
+                             zip(dists, mvs))
+    def test_basic(self, dist, mv_ex):
+        with suppress_warnings() as sup:
+            # filter the warnings thrown by UNU.RAN
+            sup.filter(RuntimeWarning)
+            rng = TransformedDensityRejection(dist, random_state=42)
+        check_cont_samples(rng, dist, mv_ex)
+
+    # PDF 0 everywhere => bad construction points
+    bad_pdfs = [(lambda x: 0, UNURANError, r"50 : bad construction points.")]
+    bad_pdfs += bad_pdfs_common  # type: ignore[arg-type]
+
+    @pytest.mark.parametrize("pdf, err, msg", bad_pdfs)
+    def test_bad_pdf(self, pdf, err, msg):
+        class dist:
+            pass
+        dist.pdf = pdf
+        dist.dpdf = lambda x: 1  # an arbitrary dPDF
+        with pytest.raises(err, match=msg):
+            TransformedDensityRejection(dist)
+
+    @pytest.mark.parametrize("dpdf, err, msg", bad_dpdf_common)
+    def test_bad_dpdf(self, dpdf, err, msg):
+        class dist:
+            pass
+        dist.pdf = lambda x: x
+        dist.dpdf = dpdf
+        with pytest.raises(err, match=msg):
+            TransformedDensityRejection(dist, domain=(1, 10))
+
+    # test domains with inf + nan in them. need to write a custom test for
+    # this because not all methods support infinite tails.
+    @pytest.mark.parametrize("domain, err, msg", inf_nan_domains)
+    def test_inf_nan_domains(self, domain, err, msg):
+        with pytest.raises(err, match=msg):
+            TransformedDensityRejection(StandardNormal(), domain=domain)
+
+    @pytest.mark.parametrize("construction_points", [-1, 0, 0.1])
+    def test_bad_construction_points_scalar(self, construction_points):
+        with pytest.raises(ValueError, match=r"`construction_points` must be "
+                                             r"a positive integer."):
+            TransformedDensityRejection(
+                StandardNormal(), construction_points=construction_points
+            )
+
+    def test_bad_construction_points_array(self):
+        # empty array
+        construction_points = []
+        with pytest.raises(ValueError, match=r"`construction_points` must "
+                                             r"either be a "
+                                             r"scalar or a non-empty array."):
+            TransformedDensityRejection(
+                StandardNormal(), construction_points=construction_points
+            )
+
+        # construction_points not monotonically increasing
+        construction_points = [1, 1, 1, 1, 1, 1]
+        with pytest.warns(RuntimeWarning, match=r"33 : starting points not "
+                                                r"strictly monotonically "
+                                                r"increasing"):
+            TransformedDensityRejection(
+                StandardNormal(), construction_points=construction_points
+            )
+
+        # construction_points containing nans
+        construction_points = [np.nan, np.nan, np.nan]
+        with pytest.raises(UNURANError, match=r"50 : bad construction "
+                                              r"points."):
+            TransformedDensityRejection(
+                StandardNormal(), construction_points=construction_points
+            )
+
+        # construction_points out of domain
+        construction_points = [-10, 10]
+        with pytest.warns(RuntimeWarning, match=r"50 : starting point out of "
+                                                r"domain"):
+            TransformedDensityRejection(
+                StandardNormal(), domain=(-3, 3),
+                construction_points=construction_points
+            )
+
+    @pytest.mark.parametrize("c", [-1., np.nan, np.inf, 0.1, 1.])
+    def test_bad_c(self, c):
+        msg = r"`c` must either be -0.5 or 0."
+        with pytest.raises(ValueError, match=msg):
+            TransformedDensityRejection(StandardNormal(), c=-1.)
+
+    u = [np.linspace(0, 1, num=1000), [], [[]], [np.nan],
+         [-np.inf, np.nan, np.inf], 0,
+         [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]]]
+
+    @pytest.mark.parametrize("u", u)
+    def test_ppf_hat(self, u):
+        # Increase the `max_squeeze_hat_ratio` so the ppf_hat is more
+        # accurate.
+        rng = TransformedDensityRejection(StandardNormal(),
+                                          max_squeeze_hat_ratio=0.9999)
+        # Older versions of NumPy throw RuntimeWarnings for comparisons
+        # with nan.
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in greater")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "greater_equal")
+            sup.filter(RuntimeWarning, "invalid value encountered in less")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "less_equal")
+            res = rng.ppf_hat(u)
+            expected = stats.norm.ppf(u)
+        assert_allclose(res, expected, rtol=1e-3, atol=1e-5)
+        assert res.shape == expected.shape
+
+    def test_bad_dist(self):
+        # Empty distribution
+        class dist:
+            ...
+
+        msg = r"`pdf` required but not found."
+        with pytest.raises(ValueError, match=msg):
+            TransformedDensityRejection(dist)
+
+        # dPDF not present in dist
+        class dist:
+            pdf = lambda x: 1-x*x  # noqa: E731
+
+        msg = r"`dpdf` required but not found."
+        with pytest.raises(ValueError, match=msg):
+            TransformedDensityRejection(dist)
+
+
+class TestDiscreteAliasUrn:
+    # DAU fails on these probably because of large domains and small
+    # computation errors in PMF. Mean/SD match but chi-squared test fails.
+    basic_fail_dists = {
+        'nchypergeom_fisher',  # numerical errors on tails
+        'nchypergeom_wallenius',  # numerical errors on tails
+        'randint'  # fails on 32-bit ubuntu
+    }
+
+    @pytest.mark.parametrize("distname, params", distdiscrete)
+    def test_basic(self, distname, params):
+        if distname in self.basic_fail_dists:
+            msg = ("DAU fails on these probably because of large domains "
+                   "and small computation errors in PMF.")
+            pytest.skip(msg)
+        if not isinstance(distname, str):
+            dist = distname
+        else:
+            dist = getattr(stats, distname)
+        dist = dist(*params)
+        domain = dist.support()
+        if not np.isfinite(domain[1] - domain[0]):
+            # DAU only works with finite domain. So, skip the distributions
+            # with infinite tails.
+            pytest.skip("DAU only works with a finite domain.")
+        k = np.arange(domain[0], domain[1]+1)
+        pv = dist.pmf(k)
+        mv_ex = dist.stats('mv')
+        rng = DiscreteAliasUrn(dist, random_state=42)
+        check_discr_samples(rng, pv, mv_ex)
+
+    # Can't use bad_pmf_common here as we evaluate PMF early on to avoid
+    # unhelpful errors from UNU.RAN.
+    bad_pmf = [
+        # inf returned
+        (lambda x: np.inf, ValueError,
+         r"must contain only finite / non-nan values"),
+        # nan returned
+        (lambda x: np.nan, ValueError,
+         r"must contain only finite / non-nan values"),
+        # all zeros
+        (lambda x: 0.0, ValueError,
+         r"must contain at least one non-zero value"),
+        # Undefined name inside the function
+        (lambda x: foo, NameError,  # type: ignore[name-defined]  # noqa: F821
+         r"name 'foo' is not defined"),
+        # Returning wrong type.
+        (lambda x: [], ValueError,
+         r"setting an array element with a sequence."),
+        # probabilities < 0
+        (lambda x: -x, UNURANError,
+         r"50 : probability < 0"),
+        # signature of PMF wrong
+        (lambda: 1.0, TypeError,
+         r"takes 0 positional arguments but 1 was given")
+    ]
+
+    @pytest.mark.parametrize("pmf, err, msg", bad_pmf)
+    def test_bad_pmf(self, pmf, err, msg):
+        class dist:
+            pass
+        dist.pmf = pmf
+        with pytest.raises(err, match=msg):
+            DiscreteAliasUrn(dist, domain=(1, 10))
+
+    @pytest.mark.parametrize("pv", [[0.18, 0.02, 0.8],
+                                    [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]])
+    def test_sampling_with_pv(self, pv):
+        pv = np.asarray(pv, dtype=np.float64)
+        rng = DiscreteAliasUrn(pv, random_state=123)
+        rng.rvs(100_000)
+        pv = pv / pv.sum()
+        variates = np.arange(0, len(pv))
+        # test if the first few moments match
+        m_expected = np.average(variates, weights=pv)
+        v_expected = np.average((variates - m_expected) ** 2, weights=pv)
+        mv_expected = m_expected, v_expected
+        check_discr_samples(rng, pv, mv_expected)
+
+    @pytest.mark.parametrize("pv, msg", bad_pv_common)
+    def test_bad_pv(self, pv, msg):
+        with pytest.raises(ValueError, match=msg):
+            DiscreteAliasUrn(pv)
+
+    # DAU doesn't support infinite tails. So, it should throw an error when
+    # inf is present in the domain.
+    inf_domain = [(-np.inf, np.inf), (np.inf, np.inf), (-np.inf, -np.inf),
+                  (0, np.inf), (-np.inf, 0)]
+
+    @pytest.mark.parametrize("domain", inf_domain)
+    def test_inf_domain(self, domain):
+        with pytest.raises(ValueError, match=r"must be finite"):
+            DiscreteAliasUrn(stats.binom(10, 0.2), domain=domain)
+
+    def test_bad_urn_factor(self):
+        with pytest.warns(RuntimeWarning, match=r"relative urn size < 1."):
+            DiscreteAliasUrn([0.5, 0.5], urn_factor=-1)
+
+    def test_bad_args(self):
+        msg = (r"`domain` must be provided when the "
+               r"probability vector is not available.")
+
+        class dist:
+            def pmf(self, x):
+                return x
+
+        with pytest.raises(ValueError, match=msg):
+            DiscreteAliasUrn(dist)
+
+    def test_gh19359(self):
+        pv = special.softmax(np.ones((1533,)))
+        rng = DiscreteAliasUrn(pv, random_state=42)
+        # check the correctness
+        check_discr_samples(rng, pv, (1532 / 2, (1532**2 - 1) / 12),
+                            rtol=5e-3)
+
+
+class TestNumericalInversePolynomial:
+    # Simple Custom Distribution
+    class dist0:
+        def pdf(self, x):
+            return 3/4 * (1-x*x)
+
+        def cdf(self, x):
+            return 3/4 * (x - x**3/3 + 2/3)
+
+        def support(self):
+            return -1, 1
+
+    # Standard Normal Distribution
+    class dist1:
+        def pdf(self, x):
+            return stats.norm._pdf(x / 0.1)
+
+        def cdf(self, x):
+            return stats.norm._cdf(x / 0.1)
+
+    # Sin 2 distribution
+    #          /  0.05 + 0.45*(1 +sin(2 Pi x))  if |x| <= 1
+    #  f(x) = <
+    #          \  0        otherwise
+    # Taken from UNU.RAN test suite (from file t_pinv.c)
+    class dist2:
+        def pdf(self, x):
+            return 0.05 + 0.45 * (1 + np.sin(2*np.pi*x))
+
+        def cdf(self, x):
+            return (0.05*(x + 1) +
+                    0.9*(1. + 2.*np.pi*(1 + x) - np.cos(2.*np.pi*x)) /
+                    (4.*np.pi))
+
+        def support(self):
+            return -1, 1
+
+    # Sin 10 distribution
+    #          /  0.05 + 0.45*(1 +sin(2 Pi x))  if |x| <= 5
+    #  f(x) = <
+    #          \  0        otherwise
+    # Taken from UNU.RAN test suite (from file t_pinv.c)
+    class dist3:
+        def pdf(self, x):
+            return 0.2 * (0.05 + 0.45 * (1 + np.sin(2*np.pi*x)))
+
+        def cdf(self, x):
+            return x/10. + 0.5 + 0.09/(2*np.pi) * (np.cos(10*np.pi) -
+                                                   np.cos(2*np.pi*x))
+
+        def support(self):
+            return -5, 5
+
+    dists = [dist0(), dist1(), dist2(), dist3()]
+
+    # exact mean and variance of the distributions in the list dists
+    mv0 = [0., 4./15.]
+    mv1 = [0., 0.01]
+    mv2 = [-0.45/np.pi, 2/3*0.5 - 0.45**2/np.pi**2]
+    mv3 = [-0.45/np.pi, 0.2 * 250/3 * 0.5 - 0.45**2/np.pi**2]
+    mvs = [mv0, mv1, mv2, mv3]
+
+    @pytest.mark.parametrize("dist, mv_ex",
+                             zip(dists, mvs))
+    def test_basic(self, dist, mv_ex):
+        rng = NumericalInversePolynomial(dist, random_state=42)
+        check_cont_samples(rng, dist, mv_ex)
+
+    @pytest.mark.xslow
+    @pytest.mark.parametrize("distname, params", distcont)
+    def test_basic_all_scipy_dists(self, distname, params):
+
+        very_slow_dists = ['anglit', 'gausshyper', 'kappa4',
+                           'ksone', 'kstwo', 'levy_l',
+                           'levy_stable', 'studentized_range',
+                           'trapezoid', 'triang', 'vonmises']
+        # for these distributions, some assertions fail due to minor
+        # numerical differences. They can be avoided either by changing
+        # the seed or by increasing the u_resolution.
+        fail_dists = ['chi2', 'fatiguelife', 'gibrat',
+                      'halfgennorm', 'lognorm', 'ncf',
+                      'ncx2', 'pareto', 't']
+        # for these distributions, skip the check for agreement between sample
+        # moments and true moments. We cannot expect them to pass due to the
+        # high variance of sample moments.
+        skip_sample_moment_check = ['rel_breitwigner']
+
+        if distname in very_slow_dists:
+            pytest.skip(f"PINV too slow for {distname}")
+        if distname in fail_dists:
+            pytest.skip(f"PINV fails for {distname}")
+        dist = (getattr(stats, distname)
+                if isinstance(distname, str)
+                else distname)
+        dist = dist(*params)
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning)
+            rng = NumericalInversePolynomial(dist, random_state=42)
+        if distname in skip_sample_moment_check:
+            return
+        check_cont_samples(rng, dist, [dist.mean(), dist.var()])
+
+    @pytest.mark.parametrize("pdf, err, msg", bad_pdfs_common)
+    def test_bad_pdf(self, pdf, err, msg):
+        class dist:
+            pass
+        dist.pdf = pdf
+        with pytest.raises(err, match=msg):
+            NumericalInversePolynomial(dist, domain=[0, 5])
+
+    @pytest.mark.parametrize("logpdf, err, msg", bad_logpdfs_common)
+    def test_bad_logpdf(self, logpdf, err, msg):
+        class dist:
+            pass
+        dist.logpdf = logpdf
+        with pytest.raises(err, match=msg):
+            NumericalInversePolynomial(dist, domain=[0, 5])
+
+    # test domains with inf + nan in them. need to write a custom test for
+    # this because not all methods support infinite tails.
+    @pytest.mark.parametrize("domain, err, msg", inf_nan_domains)
+    def test_inf_nan_domains(self, domain, err, msg):
+        with pytest.raises(err, match=msg):
+            NumericalInversePolynomial(StandardNormal(), domain=domain)
+
+    u = [
+        # test if quantile 0 and 1 return -inf and inf respectively and check
+        # the correctness of the PPF for equidistant points between 0 and 1.
+        np.linspace(0, 1, num=10000),
+        # test the PPF method for empty arrays
+        [], [[]],
+        # test if nans and infs return nan result.
+        [np.nan], [-np.inf, np.nan, np.inf],
+        # test if a scalar is returned for a scalar input.
+        0,
+        # test for arrays with nans, values greater than 1 and less than 0,
+        # and some valid values.
+        [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]]
+    ]
+
+    @pytest.mark.parametrize("u", u)
+    def test_ppf(self, u):
+        dist = StandardNormal()
+        rng = NumericalInversePolynomial(dist, u_resolution=1e-14)
+        # Older versions of NumPy throw RuntimeWarnings for comparisons
+        # with nan.
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in greater")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "greater_equal")
+            sup.filter(RuntimeWarning, "invalid value encountered in less")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "less_equal")
+            res = rng.ppf(u)
+            expected = stats.norm.ppf(u)
+        assert_allclose(res, expected, rtol=1e-11, atol=1e-11)
+        assert res.shape == expected.shape
+
+    x = [np.linspace(-10, 10, num=10000), [], [[]], [np.nan],
+         [-np.inf, np.nan, np.inf], 0,
+         [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-np.inf, 3, 4]]]
+
+    @pytest.mark.parametrize("x", x)
+    def test_cdf(self, x):
+        dist = StandardNormal()
+        rng = NumericalInversePolynomial(dist, u_resolution=1e-14)
+        # Older versions of NumPy throw RuntimeWarnings for comparisons
+        # with nan.
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in greater")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "greater_equal")
+            sup.filter(RuntimeWarning, "invalid value encountered in less")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "less_equal")
+            res = rng.cdf(x)
+            expected = stats.norm.cdf(x)
+        assert_allclose(res, expected, rtol=1e-11, atol=1e-11)
+        assert res.shape == expected.shape
+
+    @pytest.mark.slow
+    def test_u_error(self):
+        dist = StandardNormal()
+        rng = NumericalInversePolynomial(dist, u_resolution=1e-10)
+        max_error, mae = rng.u_error()
+        assert max_error < 1e-10
+        assert mae <= max_error
+        rng = NumericalInversePolynomial(dist, u_resolution=1e-14)
+        max_error, mae = rng.u_error()
+        assert max_error < 1e-14
+        assert mae <= max_error
+
+    bad_orders = [1, 4.5, 20, np.inf, np.nan]
+    bad_u_resolution = [1e-20, 1e-1, np.inf, np.nan]
+
+    @pytest.mark.parametrize("order", bad_orders)
+    def test_bad_orders(self, order):
+        dist = StandardNormal()
+
+        msg = r"`order` must be an integer in the range \[3, 17\]."
+        with pytest.raises(ValueError, match=msg):
+            NumericalInversePolynomial(dist, order=order)
+
+    @pytest.mark.parametrize("u_resolution", bad_u_resolution)
+    def test_bad_u_resolution(self, u_resolution):
+        msg = r"`u_resolution` must be between 1e-15 and 1e-5."
+        with pytest.raises(ValueError, match=msg):
+            NumericalInversePolynomial(StandardNormal(),
+                                       u_resolution=u_resolution)
+
+    def test_bad_args(self):
+
+        class BadDist:
+            def cdf(self, x):
+                return stats.norm._cdf(x)
+
+        dist = BadDist()
+        msg = r"Either of the methods `pdf` or `logpdf` must be specified"
+        with pytest.raises(ValueError, match=msg):
+            rng = NumericalInversePolynomial(dist)
+
+        dist = StandardNormal()
+        rng = NumericalInversePolynomial(dist)
+        msg = r"`sample_size` must be greater than or equal to 1000."
+        with pytest.raises(ValueError, match=msg):
+            rng.u_error(10)
+
+        class Distribution:
+            def pdf(self, x):
+                return np.exp(-0.5 * x*x)
+
+        dist = Distribution()
+        rng = NumericalInversePolynomial(dist)
+        msg = r"Exact CDF required but not found."
+        with pytest.raises(ValueError, match=msg):
+            rng.u_error()
+
+    def test_logpdf_pdf_consistency(self):
+        # 1. check that PINV works with pdf and logpdf only
+        # 2. check that generated ppf is the same (up to a small tolerance)
+
+        class MyDist:
+            pass
+
+        # create generator from dist with only pdf
+        dist_pdf = MyDist()
+        dist_pdf.pdf = lambda x: math.exp(-x*x/2)
+        rng1 = NumericalInversePolynomial(dist_pdf)
+
+        # create dist with only logpdf
+        dist_logpdf = MyDist()
+        dist_logpdf.logpdf = lambda x: -x*x/2
+        rng2 = NumericalInversePolynomial(dist_logpdf)
+
+        q = np.linspace(1e-5, 1-1e-5, num=100)
+        assert_allclose(rng1.ppf(q), rng2.ppf(q))
+
+
+class TestNumericalInverseHermite:
+    #         /  (1 +sin(2 Pi x))/2  if |x| <= 1
+    # f(x) = <
+    #         \  0        otherwise
+    # Taken from UNU.RAN test suite (from file t_hinv.c)
+    class dist0:
+        def pdf(self, x):
+            return 0.5*(1. + np.sin(2.*np.pi*x))
+
+        def dpdf(self, x):
+            return np.pi*np.cos(2.*np.pi*x)
+
+        def cdf(self, x):
+            return (1. + 2.*np.pi*(1 + x) - np.cos(2.*np.pi*x)) / (4.*np.pi)
+
+        def support(self):
+            return -1, 1
+
+    #         /  Max(sin(2 Pi x)),0)Pi/2  if -1 < x <0.5
+    # f(x) = <
+    #         \  0        otherwise
+    # Taken from UNU.RAN test suite (from file t_hinv.c)
+    class dist1:
+        def pdf(self, x):
+            if (x <= -0.5):
+                return np.sin((2. * np.pi) * x) * 0.5 * np.pi
+            if (x < 0.):
+                return 0.
+            if (x <= 0.5):
+                return np.sin((2. * np.pi) * x) * 0.5 * np.pi
+
+        def dpdf(self, x):
+            if (x <= -0.5):
+                return np.cos((2. * np.pi) * x) * np.pi * np.pi
+            if (x < 0.):
+                return 0.
+            if (x <= 0.5):
+                return np.cos((2. * np.pi) * x) * np.pi * np.pi
+
+        def cdf(self, x):
+            if (x <= -0.5):
+                return 0.25 * (1 - np.cos((2. * np.pi) * x))
+            if (x < 0.):
+                return 0.5
+            if (x <= 0.5):
+                return 0.75 - 0.25 * np.cos((2. * np.pi) * x)
+
+        def support(self):
+            return -1, 0.5
+
+    dists = [dist0(), dist1()]
+
+    # exact mean and variance of the distributions in the list dists
+    mv0 = [-1/(2*np.pi), 1/3 - 1/(4*np.pi*np.pi)]
+    mv1 = [-1/4, 3/8-1/(2*np.pi*np.pi) - 1/16]
+    mvs = [mv0, mv1]
+
+    @pytest.mark.parametrize("dist, mv_ex",
+                             zip(dists, mvs))
+    @pytest.mark.parametrize("order", [3, 5])
+    def test_basic(self, dist, mv_ex, order):
+        rng = NumericalInverseHermite(dist, order=order, random_state=42)
+        check_cont_samples(rng, dist, mv_ex)
+
+    # test domains with inf + nan in them. need to write a custom test for
+    # this because not all methods support infinite tails.
+    @pytest.mark.parametrize("domain, err, msg", inf_nan_domains)
+    def test_inf_nan_domains(self, domain, err, msg):
+        with pytest.raises(err, match=msg):
+            NumericalInverseHermite(StandardNormal(), domain=domain)
+
+    def basic_test_all_scipy_dists(self, distname, shapes):
+        slow_dists = {'ksone', 'kstwo', 'levy_stable', 'skewnorm'}
+        fail_dists = {'beta', 'gausshyper', 'geninvgauss', 'ncf', 'nct',
+                      'norminvgauss', 'genhyperbolic', 'studentized_range',
+                      'vonmises', 'kappa4', 'invgauss', 'wald'}
+
+        if distname in slow_dists:
+            pytest.skip("Distribution is too slow")
+        if distname in fail_dists:
+            # specific reasons documented in gh-13319
+            # https://github.com/scipy/scipy/pull/13319#discussion_r626188955
+            pytest.xfail("Fails - usually due to inaccurate CDF/PDF")
+
+        np.random.seed(0)
+
+        dist = getattr(stats, distname)(*shapes)
+        fni = NumericalInverseHermite(dist)
+
+        x = np.random.rand(10)
+        p_tol = np.max(np.abs(dist.ppf(x)-fni.ppf(x))/np.abs(dist.ppf(x)))
+        u_tol = np.max(np.abs(dist.cdf(fni.ppf(x)) - x))
+
+        assert p_tol < 1e-8
+        assert u_tol < 1e-12
+
+    @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+    @pytest.mark.xslow
+    @pytest.mark.parametrize(("distname", "shapes"), distcont)
+    def test_basic_all_scipy_dists(self, distname, shapes):
+        # if distname == "truncnorm":
+        #     pytest.skip("Tested separately")
+        self.basic_test_all_scipy_dists(distname, shapes)
+
+    @pytest.mark.fail_slow(5)
+    @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+    def test_basic_truncnorm_gh17155(self):
+        self.basic_test_all_scipy_dists("truncnorm", (0.1, 2))
+
+    def test_input_validation(self):
+        match = r"`order` must be either 1, 3, or 5."
+        with pytest.raises(ValueError, match=match):
+            NumericalInverseHermite(StandardNormal(), order=2)
+
+        match = "`cdf` required but not found"
+        with pytest.raises(ValueError, match=match):
+            NumericalInverseHermite("norm")
+
+        match = "could not convert string to float"
+        with pytest.raises(ValueError, match=match):
+            NumericalInverseHermite(StandardNormal(),
+                                    u_resolution='ekki')
+
+    rngs = [None, 0, np.random.RandomState(0)]
+    rngs.append(np.random.default_rng(0))  # type: ignore
+    sizes = [(None, tuple()), (8, (8,)), ((4, 5, 6), (4, 5, 6))]
+
+    @pytest.mark.parametrize('rng', rngs)
+    @pytest.mark.parametrize('size_in, size_out', sizes)
+    def test_RVS(self, rng, size_in, size_out):
+        dist = StandardNormal()
+        fni = NumericalInverseHermite(dist)
+
+        rng2 = deepcopy(rng)
+        rvs = fni.rvs(size=size_in, random_state=rng)
+        if size_in is not None:
+            assert rvs.shape == size_out
+
+        if rng2 is not None:
+            rng2 = check_random_state(rng2)
+            uniform = rng2.uniform(size=size_in)
+            rvs2 = stats.norm.ppf(uniform)
+            assert_allclose(rvs, rvs2)
+
+    def test_inaccurate_CDF(self):
+        # CDF function with inaccurate tail cannot be inverted; see gh-13319
+        # https://github.com/scipy/scipy/pull/13319#discussion_r626188955
+        shapes = (2.3098496451481823, 0.6268795430096368)
+        match = ("98 : one or more intervals very short; possibly due to "
+                 "numerical problems with a pole or very flat tail")
+
+        # fails with default tol
+        with pytest.warns(RuntimeWarning, match=match):
+            NumericalInverseHermite(stats.beta(*shapes))
+
+        # no error with coarser tol
+        NumericalInverseHermite(stats.beta(*shapes), u_resolution=1e-8)
+
+    def test_custom_distribution(self):
+        dist1 = StandardNormal()
+        fni1 = NumericalInverseHermite(dist1)
+
+        dist2 = stats.norm()
+        fni2 = NumericalInverseHermite(dist2)
+
+        assert_allclose(fni1.rvs(random_state=0), fni2.rvs(random_state=0))
+
+    u = [
+        # check the correctness of the PPF for equidistant points between
+        # 0.02 and 0.98.
+        np.linspace(0., 1., num=10000),
+        # test the PPF method for empty arrays
+        [], [[]],
+        # test if nans and infs return nan result.
+        [np.nan], [-np.inf, np.nan, np.inf],
+        # test if a scalar is returned for a scalar input.
+        0,
+        # test for arrays with nans, values greater than 1 and less than 0,
+        # and some valid values.
+        [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]]
+    ]
+
+    @pytest.mark.parametrize("u", u)
+    def test_ppf(self, u):
+        dist = StandardNormal()
+        rng = NumericalInverseHermite(dist, u_resolution=1e-12)
+        # Older versions of NumPy throw RuntimeWarnings for comparisons
+        # with nan.
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in greater")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "greater_equal")
+            sup.filter(RuntimeWarning, "invalid value encountered in less")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "less_equal")
+            res = rng.ppf(u)
+            expected = stats.norm.ppf(u)
+        assert_allclose(res, expected, rtol=1e-9, atol=3e-10)
+        assert res.shape == expected.shape
+
+    @pytest.mark.slow
+    def test_u_error(self):
+        dist = StandardNormal()
+        rng = NumericalInverseHermite(dist, u_resolution=1e-10)
+        max_error, mae = rng.u_error()
+        assert max_error < 1e-10
+        assert mae <= max_error
+        with suppress_warnings() as sup:
+            # ignore warning about u-resolution being too small.
+            sup.filter(RuntimeWarning)
+            rng = NumericalInverseHermite(dist, u_resolution=1e-14)
+        max_error, mae = rng.u_error()
+        assert max_error < 1e-14
+        assert mae <= max_error
+
+
+class TestDiscreteGuideTable:
+    basic_fail_dists = {
+        'nchypergeom_fisher',  # numerical errors on tails
+        'nchypergeom_wallenius',  # numerical errors on tails
+        'randint'  # fails on 32-bit ubuntu
+    }
+
+    def test_guide_factor_gt3_raises_warning(self):
+        pv = [0.1, 0.3, 0.6]
+        urng = np.random.default_rng()
+        with pytest.warns(RuntimeWarning):
+            DiscreteGuideTable(pv, random_state=urng, guide_factor=7)
+
+    def test_guide_factor_zero_raises_warning(self):
+        pv = [0.1, 0.3, 0.6]
+        urng = np.random.default_rng()
+        with pytest.warns(RuntimeWarning):
+            DiscreteGuideTable(pv, random_state=urng, guide_factor=0)
+
+    def test_negative_guide_factor_raises_warning(self):
+        # This occurs from the UNU.RAN wrapper automatically.
+        # however it already gives a useful warning
+        # Here we just test that a warning is raised.
+        pv = [0.1, 0.3, 0.6]
+        urng = np.random.default_rng()
+        with pytest.warns(RuntimeWarning):
+            DiscreteGuideTable(pv, random_state=urng, guide_factor=-1)
+
+    @pytest.mark.parametrize("distname, params", distdiscrete)
+    def test_basic(self, distname, params):
+        if distname in self.basic_fail_dists:
+            msg = ("DGT fails on these probably because of large domains "
+                   "and small computation errors in PMF.")
+            pytest.skip(msg)
+
+        if not isinstance(distname, str):
+            dist = distname
+        else:
+            dist = getattr(stats, distname)
+
+        dist = dist(*params)
+        domain = dist.support()
+
+        if not np.isfinite(domain[1] - domain[0]):
+            # DGT only works with finite domain. So, skip the distributions
+            # with infinite tails.
+            pytest.skip("DGT only works with a finite domain.")
+
+        k = np.arange(domain[0], domain[1]+1)
+        pv = dist.pmf(k)
+        mv_ex = dist.stats('mv')
+        rng = DiscreteGuideTable(dist, random_state=42)
+        check_discr_samples(rng, pv, mv_ex)
+
+    u = [
+        # the correctness of the PPF for equidistant points between 0 and 1.
+        np.linspace(0, 1, num=10000),
+        # test the PPF method for empty arrays
+        [], [[]],
+        # test if nans and infs return nan result.
+        [np.nan], [-np.inf, np.nan, np.inf],
+        # test if a scalar is returned for a scalar input.
+        0,
+        # test for arrays with nans, values greater than 1 and less than 0,
+        # and some valid values.
+        [[np.nan, 0.5, 0.1], [0.2, 0.4, np.inf], [-2, 3, 4]]
+    ]
+
+    @pytest.mark.parametrize('u', u)
+    def test_ppf(self, u):
+        n, p = 4, 0.1
+        dist = stats.binom(n, p)
+        rng = DiscreteGuideTable(dist, random_state=42)
+
+        # Older versions of NumPy throw RuntimeWarnings for comparisons
+        # with nan.
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "invalid value encountered in greater")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "greater_equal")
+            sup.filter(RuntimeWarning, "invalid value encountered in less")
+            sup.filter(RuntimeWarning, "invalid value encountered in "
+                                       "less_equal")
+
+            res = rng.ppf(u)
+            expected = stats.binom.ppf(u, n, p)
+        assert_equal(res.shape, expected.shape)
+        assert_equal(res, expected)
+
+    @pytest.mark.parametrize("pv, msg", bad_pv_common)
+    def test_bad_pv(self, pv, msg):
+        with pytest.raises(ValueError, match=msg):
+            DiscreteGuideTable(pv)
+
+    # DGT doesn't support infinite tails. So, it should throw an error when
+    # inf is present in the domain.
+    inf_domain = [(-np.inf, np.inf), (np.inf, np.inf), (-np.inf, -np.inf),
+                  (0, np.inf), (-np.inf, 0)]
+
+    @pytest.mark.parametrize("domain", inf_domain)
+    def test_inf_domain(self, domain):
+        with pytest.raises(ValueError, match=r"must be finite"):
+            DiscreteGuideTable(stats.binom(10, 0.2), domain=domain)
+
+
+class TestSimpleRatioUniforms:
+    # pdf with piecewise linear function as transformed density
+    # with T = -1/sqrt with shift. Taken from UNU.RAN test suite
+    # (from file t_srou.c)
+    class dist:
+        def __init__(self, shift):
+            self.shift = shift
+            self.mode = shift
+
+        def pdf(self, x):
+            x -= self.shift
+            y = 1. / (abs(x) + 1.)
+            return 0.5 * y * y
+
+        def cdf(self, x):
+            x -= self.shift
+            if x <= 0.:
+                return 0.5 / (1. - x)
+            else:
+                return 1. - 0.5 / (1. + x)
+
+    dists = [dist(0.), dist(10000.)]
+
+    # exact mean and variance of the distributions in the list dists
+    mv1 = [0., np.inf]
+    mv2 = [10000., np.inf]
+    mvs = [mv1, mv2]
+
+    @pytest.mark.parametrize("dist, mv_ex",
+                             zip(dists, mvs))
+    def test_basic(self, dist, mv_ex):
+        rng = SimpleRatioUniforms(dist, mode=dist.mode, random_state=42)
+        check_cont_samples(rng, dist, mv_ex)
+        rng = SimpleRatioUniforms(dist, mode=dist.mode,
+                                  cdf_at_mode=dist.cdf(dist.mode),
+                                  random_state=42)
+        check_cont_samples(rng, dist, mv_ex)
+
+    # test domains with inf + nan in them. need to write a custom test for
+    # this because not all methods support infinite tails.
+    @pytest.mark.parametrize("domain, err, msg", inf_nan_domains)
+    def test_inf_nan_domains(self, domain, err, msg):
+        with pytest.raises(err, match=msg):
+            SimpleRatioUniforms(StandardNormal(), domain=domain)
+
+    def test_bad_args(self):
+        # pdf_area < 0
+        with pytest.raises(ValueError, match=r"`pdf_area` must be > 0"):
+            SimpleRatioUniforms(StandardNormal(), mode=0, pdf_area=-1)
+
+
+class TestRatioUniforms:
+    def test_rv_generation(self):
+        # use KS test to check distribution of rvs
+        # normal distribution
+        f = stats.norm.pdf
+        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
+        u = np.sqrt(f(0))
+        gen = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12345)
+        assert_equal(stats.kstest(gen.rvs(2500), 'norm')[1] > 0.25, True)
+
+        # exponential distribution
+        gen = RatioUniforms(lambda x: np.exp(-x), umax=1,
+                            vmin=0, vmax=2*np.exp(-1), random_state=12345)
+        assert_equal(stats.kstest(gen.rvs(1000), 'expon')[1] > 0.25, True)
+
+    def test_shape(self):
+        # test shape of return value depending on size parameter
+        f = stats.norm.pdf
+        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
+        u = np.sqrt(f(0))
+
+        gen1 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
+        gen2 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
+        gen3 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
+        r1, r2, r3 = gen1.rvs(3), gen2.rvs((3,)), gen3.rvs((3, 1))
+        assert_equal(r1, r2)
+        assert_equal(r2, r3.flatten())
+        assert_equal(r1.shape, (3,))
+        assert_equal(r3.shape, (3, 1))
+
+        gen4 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12)
+        gen5 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12)
+        r4, r5 = gen4.rvs(size=(3, 3, 3)), gen5.rvs(size=27)
+        assert_equal(r4.flatten(), r5)
+        assert_equal(r4.shape, (3, 3, 3))
+
+        gen6 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
+        gen7 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
+        gen8 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
+        r6, r7, r8 = gen6.rvs(), gen7.rvs(1), gen8.rvs((1,))
+        assert_equal(r6, r7)
+        assert_equal(r7, r8)
+
+    def test_random_state(self):
+        f = stats.norm.pdf
+        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
+        umax = np.sqrt(f(0))
+        gen1 = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=1234)
+        r1 = gen1.rvs(10)
+        np.random.seed(1234)
+        gen2 = RatioUniforms(f, umax=umax, vmin=-v, vmax=v)
+        r2 = gen2.rvs(10)
+        assert_equal(r1, r2)
+
+    def test_exceptions(self):
+        f = stats.norm.pdf
+        # need vmin < vmax
+        with assert_raises(ValueError, match="vmin must be smaller than vmax"):
+            RatioUniforms(pdf=f, umax=1, vmin=3, vmax=1)
+        with assert_raises(ValueError, match="vmin must be smaller than vmax"):
+            RatioUniforms(pdf=f, umax=1, vmin=1, vmax=1)
+        # need umax > 0
+        with assert_raises(ValueError, match="umax must be positive"):
+            RatioUniforms(pdf=f, umax=-1, vmin=1, vmax=3)
+        with assert_raises(ValueError, match="umax must be positive"):
+            RatioUniforms(pdf=f, umax=0, vmin=1, vmax=3)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sensitivity_analysis.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sensitivity_analysis.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c8d53040380808c03358b905878cc4a8b9b9679
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_sensitivity_analysis.py
@@ -0,0 +1,310 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_less
+import pytest
+
+from scipy import stats
+from scipy.stats import sobol_indices
+from scipy.stats._resampling import BootstrapResult
+from scipy.stats._sensitivity_analysis import (
+    BootstrapSobolResult, f_ishigami, sample_AB, sample_A_B
+)
+
+
+@pytest.fixture(scope='session')
+def ishigami_ref_indices():
+    """Reference values for Ishigami from Saltelli2007.
+
+    Chapter 4, exercise 5 pages 179-182.
+    """
+    a = 7.
+    b = 0.1
+
+    var = 0.5 + a**2/8 + b*np.pi**4/5 + b**2*np.pi**8/18
+    v1 = 0.5 + b*np.pi**4/5 + b**2*np.pi**8/50
+    v2 = a**2/8
+    v3 = 0
+    v12 = 0
+    # v13: mistake in the book, see other derivations e.g. in 10.1002/nme.4856
+    v13 = b**2*np.pi**8*8/225
+    v23 = 0
+
+    s_first = np.array([v1, v2, v3])/var
+    s_second = np.array([
+        [0., 0., v13],
+        [v12, 0., v23],
+        [v13, v23, 0.]
+    ])/var
+    s_total = s_first + s_second.sum(axis=1)
+
+    return s_first, s_total
+
+
+def f_ishigami_vec(x):
+    """Output of shape (2, n)."""
+    res = f_ishigami(x)
+    return res, res
+
+
+class TestSobolIndices:
+
+    dists = [
+        stats.uniform(loc=-np.pi, scale=2*np.pi)  # type: ignore[attr-defined]
+    ] * 3
+
+    def test_sample_AB(self):
+        # (d, n)
+        A = np.array(
+            [[1, 4, 7, 10],
+             [2, 5, 8, 11],
+             [3, 6, 9, 12]]
+        )
+        B = A + 100
+        # (d, d, n)
+        ref = np.array(
+            [[[101, 104, 107, 110],
+              [2, 5, 8, 11],
+              [3, 6, 9, 12]],
+             [[1, 4, 7, 10],
+              [102, 105, 108, 111],
+              [3, 6, 9, 12]],
+             [[1, 4, 7, 10],
+              [2, 5, 8, 11],
+              [103, 106, 109, 112]]]
+        )
+        AB = sample_AB(A=A, B=B)
+        assert_allclose(AB, ref)
+
+    @pytest.mark.xslow
+    @pytest.mark.xfail_on_32bit("Can't create large array for test")
+    @pytest.mark.parametrize(
+        'func',
+        [f_ishigami, pytest.param(f_ishigami_vec, marks=pytest.mark.slow)],
+        ids=['scalar', 'vector']
+    )
+    def test_ishigami(self, ishigami_ref_indices, func):
+        rng = np.random.default_rng(28631265345463262246170309650372465332)
+        res = sobol_indices(
+            func=func, n=4096,
+            dists=self.dists,
+            rng=rng
+        )
+
+        if func.__name__ == 'f_ishigami_vec':
+            ishigami_ref_indices = [
+                    [ishigami_ref_indices[0], ishigami_ref_indices[0]],
+                    [ishigami_ref_indices[1], ishigami_ref_indices[1]]
+            ]
+
+        assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
+        assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-2)
+
+        assert res._bootstrap_result is None
+        bootstrap_res = res.bootstrap(n_resamples=99)
+        assert isinstance(bootstrap_res, BootstrapSobolResult)
+        assert isinstance(res._bootstrap_result, BootstrapResult)
+
+        assert res._bootstrap_result.confidence_interval.low.shape[0] == 2
+        assert res._bootstrap_result.confidence_interval.low[1].shape \
+               == res.first_order.shape
+
+        assert bootstrap_res.first_order.confidence_interval.low.shape \
+               == res.first_order.shape
+        assert bootstrap_res.total_order.confidence_interval.low.shape \
+               == res.total_order.shape
+
+        assert_array_less(
+            bootstrap_res.first_order.confidence_interval.low, res.first_order
+        )
+        assert_array_less(
+            res.first_order, bootstrap_res.first_order.confidence_interval.high
+        )
+        assert_array_less(
+            bootstrap_res.total_order.confidence_interval.low, res.total_order
+        )
+        assert_array_less(
+            res.total_order, bootstrap_res.total_order.confidence_interval.high
+        )
+
+        # call again to use previous results and change a param
+        assert isinstance(
+            res.bootstrap(confidence_level=0.9, n_resamples=99),
+            BootstrapSobolResult
+        )
+        assert isinstance(res._bootstrap_result, BootstrapResult)
+
+    def test_func_dict(self, ishigami_ref_indices):
+        rng = np.random.default_rng(28631265345463262246170309650372465332)
+        n = 4096
+        dists = [
+            stats.uniform(loc=-np.pi, scale=2*np.pi),
+            stats.uniform(loc=-np.pi, scale=2*np.pi),
+            stats.uniform(loc=-np.pi, scale=2*np.pi)
+        ]
+
+        A, B = sample_A_B(n=n, dists=dists, rng=rng)
+        AB = sample_AB(A=A, B=B)
+
+        func = {
+            'f_A': f_ishigami(A).reshape(1, -1),
+            'f_B': f_ishigami(B).reshape(1, -1),
+            'f_AB': f_ishigami(AB).reshape((3, 1, -1))
+        }
+
+        # preserve use of old random_state during SPEC 7 transition
+        res = sobol_indices(
+            func=func, n=n,
+            dists=dists,
+            rng=rng
+        )
+        assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
+
+        res = sobol_indices(
+            func=func, n=n,
+            rng=rng
+        )
+        assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
+        # Ideally should be exactly equal but since f_ishigami
+        # uses floating point operations, so exact equality
+        # might not be possible (due to flakiness in computation).
+        # So, assert_allclose is used with default parameters
+        # Regression test for https://github.com/scipy/scipy/issues/21383
+        assert_allclose(f_ishigami(A).reshape(1, -1), func['f_A'])
+        assert_allclose(f_ishigami(B).reshape(1, -1), func['f_B'])
+        assert_allclose(f_ishigami(AB).reshape((3, 1, -1)), func['f_AB'])
+
+    def test_method(self, ishigami_ref_indices):
+        def jansen_sobol(f_A, f_B, f_AB):
+            """Jansen for S and Sobol' for St.
+
+            From Saltelli2010, table 2 formulations (c) and (e)."""
+            var = np.var([f_A, f_B], axis=(0, -1))
+
+            s = (var - 0.5*np.mean((f_B - f_AB)**2, axis=-1)) / var
+            st = np.mean(f_A*(f_A - f_AB), axis=-1) / var
+
+            return s.T, st.T
+
+        rng = np.random.default_rng(28631265345463262246170309650372465332)
+        res = sobol_indices(
+            func=f_ishigami, n=4096,
+            dists=self.dists,
+            method=jansen_sobol,
+            rng=rng
+        )
+
+        assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
+        assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-2)
+
+        def jansen_sobol_typed(
+            f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray
+        ) -> tuple[np.ndarray, np.ndarray]:
+            return jansen_sobol(f_A, f_B, f_AB)
+
+        _ = sobol_indices(
+            func=f_ishigami, n=8,
+            dists=self.dists,
+            method=jansen_sobol_typed,
+            rng=rng
+        )
+
+    def test_normalization(self, ishigami_ref_indices):
+        rng = np.random.default_rng(28631265345463262246170309650372465332)
+        res = sobol_indices(
+            func=lambda x: f_ishigami(x) + 1000, n=4096,
+            dists=self.dists,
+            rng=rng
+        )
+
+        assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-2)
+        assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-2)
+
+    def test_constant_function(self, ishigami_ref_indices):
+
+        def f_ishigami_vec_const(x):
+            """Output of shape (3, n)."""
+            res = f_ishigami(x)
+            return res, res * 0 + 10, res
+
+        rng = np.random.default_rng(28631265345463262246170309650372465332)
+        res = sobol_indices(
+            func=f_ishigami_vec_const, n=4096,
+            dists=self.dists,
+            rng=rng
+        )
+
+        ishigami_vec_indices = [
+                [ishigami_ref_indices[0], [0, 0, 0], ishigami_ref_indices[0]],
+                [ishigami_ref_indices[1], [0, 0, 0], ishigami_ref_indices[1]]
+        ]
+
+        assert_allclose(res.first_order, ishigami_vec_indices[0], atol=1e-2)
+        assert_allclose(res.total_order, ishigami_vec_indices[1], atol=1e-2)
+
+    @pytest.mark.xfail_on_32bit("Can't create large array for test")
+    def test_more_converged(self, ishigami_ref_indices):
+        rng = np.random.default_rng(28631265345463262246170309650372465332)
+        res = sobol_indices(
+            func=f_ishigami, n=2**19,  # 524288
+            dists=self.dists,
+            rng=rng
+        )
+
+        assert_allclose(res.first_order, ishigami_ref_indices[0], atol=1e-4)
+        assert_allclose(res.total_order, ishigami_ref_indices[1], atol=1e-4)
+
+    def test_raises(self):
+
+        message = r"Each distribution in `dists` must have method `ppf`"
+        with pytest.raises(ValueError, match=message):
+            sobol_indices(n=0, func=f_ishigami, dists="uniform")
+
+        with pytest.raises(ValueError, match=message):
+            sobol_indices(n=0, func=f_ishigami, dists=[lambda x: x])
+
+        message = r"The balance properties of Sobol'"
+        with pytest.raises(ValueError, match=message):
+            sobol_indices(n=7, func=f_ishigami, dists=[stats.uniform()])
+
+        with pytest.raises(ValueError, match=message):
+            sobol_indices(n=4.1, func=f_ishigami, dists=[stats.uniform()])
+
+        message = r"'toto' is not a valid 'method'"
+        with pytest.raises(ValueError, match=message):
+            sobol_indices(n=0, func=f_ishigami, method='toto')
+
+        message = r"must have the following signature"
+        with pytest.raises(ValueError, match=message):
+            sobol_indices(n=0, func=f_ishigami, method=lambda x: x)
+
+        message = r"'dists' must be defined when 'func' is a callable"
+        with pytest.raises(ValueError, match=message):
+            sobol_indices(n=0, func=f_ishigami)
+
+        def func_wrong_shape_output(x):
+            return x.reshape(-1, 1)
+
+        message = r"'func' output should have a shape"
+        with pytest.raises(ValueError, match=message):
+            sobol_indices(
+                n=2, func=func_wrong_shape_output, dists=[stats.uniform()]
+            )
+
+        message = r"When 'func' is a dictionary"
+        with pytest.raises(ValueError, match=message):
+            sobol_indices(
+                n=2, func={'f_A': [], 'f_AB': []}, dists=[stats.uniform()]
+            )
+
+        with pytest.raises(ValueError, match=message):
+            # f_B malformed
+            sobol_indices(
+                n=2,
+                func={'f_A': [1, 2], 'f_B': [3], 'f_AB': [5, 6, 7, 8]},
+            )
+
+        with pytest.raises(ValueError, match=message):
+            # f_AB malformed
+            sobol_indices(
+                n=2,
+                func={'f_A': [1, 2], 'f_B': [3, 4], 'f_AB': [5, 6, 7]},
+            )
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_stats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..9416a69d30ce8f8b7ba628beb2b7a9194fd24101
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_stats.py
@@ -0,0 +1,9847 @@
+""" Test functions for stats module
+
+    WRITTEN BY LOUIS LUANGKESORN  FOR THE STATS MODULE
+    BASED ON WILKINSON'S STATISTICS QUIZ
+    https://www.stanford.edu/~clint/bench/wilk.txt
+
+    Additional tests by a host of SciPy developers.
+"""
+import os
+import re
+import warnings
+from collections import namedtuple
+from itertools import product
+import hypothesis.extra.numpy as npst
+import hypothesis
+import contextlib
+
+from numpy.testing import (assert_, assert_equal,
+                           assert_almost_equal, assert_array_almost_equal,
+                           assert_array_equal, assert_approx_equal,
+                           assert_allclose, suppress_warnings,
+                           assert_array_less)
+import pytest
+from pytest import raises as assert_raises
+import numpy.ma.testutils as mat
+from numpy import array, arange, float32, power
+import numpy as np
+
+import scipy.stats as stats
+import scipy.stats.mstats as mstats
+import scipy.stats._mstats_basic as mstats_basic
+from scipy.stats._ksstats import kolmogn
+from scipy.special._testutils import FuncData
+from scipy.special import binom
+from scipy import optimize
+from .common_tests import check_named_results
+from scipy.stats._axis_nan_policy import (_broadcast_concatenate, SmallSampleWarning,
+                                          too_small_nd_omit, too_small_nd_not_omit,
+                                          too_small_1d_omit, too_small_1d_not_omit)
+from scipy.stats._stats_py import (_permutation_distribution_t, _chk_asarray, _moment,
+                                   LinregressResult, _xp_mean, _xp_var, _SimpleChi2)
+from scipy._lib._util import AxisError
+from scipy.conftest import array_api_compatible, skip_xp_invalid_arg
+from scipy._lib._array_api import (array_namespace, xp_copy, is_numpy,
+                                   is_torch, xp_size, SCIPY_ARRAY_API)
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+""" Numbers in docstrings beginning with 'W' refer to the section numbers
+    and headings found in the STATISTICS QUIZ of Leland Wilkinson.  These are
+    considered to be essential functionality.  True testing and
+    evaluation of a statistics package requires use of the
+    NIST Statistical test data.  See McCoullough(1999) Assessing The Reliability
+    of Statistical Software for a test methodology and its
+    implementation in testing SAS, SPSS, and S-Plus
+"""
+
+#  Datasets
+#  These data sets are from the nasty.dat sets used by Wilkinson
+#  For completeness, I should write the relevant tests and count them as failures
+#  Somewhat acceptable, since this is still beta software.  It would count as a
+#  good target for 1.0 status
+X = array([1,2,3,4,5,6,7,8,9], float)
+ZERO = array([0,0,0,0,0,0,0,0,0], float)
+BIG = array([99999991,99999992,99999993,99999994,99999995,99999996,99999997,
+             99999998,99999999], float)
+LITTLE = array([0.99999991,0.99999992,0.99999993,0.99999994,0.99999995,0.99999996,
+                0.99999997,0.99999998,0.99999999], float)
+HUGE = array([1e+12,2e+12,3e+12,4e+12,5e+12,6e+12,7e+12,8e+12,9e+12], float)
+TINY = array([1e-12,2e-12,3e-12,4e-12,5e-12,6e-12,7e-12,8e-12,9e-12], float)
+ROUND = array([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5,8.5], float)
+
+
+@array_api_compatible
+@skip_xp_backends('jax.numpy', reason="JAX doesn't allow item assignment.")
+@skip_xp_backends('array_api_strict',
+                  reason=("`array_api_strict.where` `fillvalue` doesn't "
+                           "accept Python floats. See data-apis/array-api#807.")
+)
+@pytest.mark.usefixtures("skip_xp_backends")
+class TestTrimmedStats:
+    # TODO: write these tests to handle missing values properly
+    dprec = np.finfo(np.float64).precision
+
+    def test_tmean(self, xp):
+        x = xp.asarray(X.tolist())  # use default dtype of xp
+
+        y = stats.tmean(x, (2, 8), (True, True))
+        xp_assert_close(y, xp.asarray(5.0))
+
+        y1 = stats.tmean(x, limits=(2, 8), inclusive=(False, False))
+        y2 = stats.tmean(x, limits=None)
+        xp_assert_close(y1, y2)
+
+        x_2d = xp.reshape(xp.arange(63.), (9, 7))
+        y = stats.tmean(x_2d, axis=None)
+        xp_assert_close(y, xp.mean(x_2d))
+
+        y = stats.tmean(x_2d, axis=0)
+        xp_assert_close(y, xp.mean(x_2d, axis=0))
+
+        y = stats.tmean(x_2d, axis=1)
+        xp_assert_close(y, xp.mean(x_2d, axis=1))
+
+        y = stats.tmean(x_2d, limits=(2, 61), axis=None)
+        xp_assert_close(y, xp.asarray(31.5))
+
+        y = stats.tmean(x_2d, limits=(2, 21), axis=0)
+        y_true = [14, 11.5, 9, 10, 11, 12, 13]
+        xp_assert_close(y, xp.asarray(y_true))
+
+        y = stats.tmean(x_2d, limits=(2, 21), inclusive=(True, False), axis=0)
+        y_true = [10.5, 11.5, 9, 10, 11, 12, 13]
+        xp_assert_close(y, xp.asarray(y_true))
+
+        x_2d_with_nan = xp_copy(x_2d)
+        x_2d_with_nan[-1, -3:] = xp.nan
+        y = stats.tmean(x_2d_with_nan, limits=(1, 13), axis=0)
+        y_true = [7, 4.5, 5.5, 6.5, xp.nan, xp.nan, xp.nan]
+        xp_assert_close(y, xp.asarray(y_true))
+
+        y = stats.tmean(x_2d, limits=(2, 21), axis=1)
+        y_true = [4, 10, 17, 21, xp.nan, xp.nan, xp.nan, xp.nan, xp.nan]
+        xp_assert_close(y, xp.asarray(y_true))
+
+        y = stats.tmean(x_2d, limits=(2, 21),
+                        inclusive=(False, True), axis=1)
+        y_true = [4.5, 10, 17, 21, xp.nan, xp.nan, xp.nan, xp.nan, xp.nan]
+        xp_assert_close(y, xp.asarray(y_true))
+
+    @skip_xp_backends('cupy',
+                      reason="cupy/cupy#8391")
+    def test_tvar(self, xp):
+        x = xp.asarray(X.tolist())  # use default dtype of xp
+        xp_test = array_namespace(x)  # need array-api-compat var for `correction`
+
+        y = stats.tvar(x, limits=(2, 8), inclusive=(True, True))
+        xp_assert_close(y, xp.asarray(4.6666666666666661))
+
+        y = stats.tvar(x, limits=None)
+        xp_assert_close(y, xp_test.var(x, correction=1))
+
+        x_2d = xp.reshape(xp.arange(63.), (9, 7))
+        y = stats.tvar(x_2d, axis=None)
+        xp_assert_close(y, xp_test.var(x_2d, correction=1))
+
+        y = stats.tvar(x_2d, axis=0)
+        xp_assert_close(y, xp.full((7,), 367.5))
+
+        y = stats.tvar(x_2d, axis=1)
+        xp_assert_close(y, xp.full((9,), 4.66666667))
+
+        # Limiting some values along one axis
+        y = stats.tvar(x_2d, limits=(1, 5), axis=1, inclusive=(True, True))
+        xp_assert_close(y[0], xp.asarray(2.5))
+
+        # Limiting all values along one axis
+        y = stats.tvar(x_2d, limits=(0, 6), axis=1, inclusive=(True, True))
+        xp_assert_close(y[0], xp.asarray(4.666666666666667))
+        xp_assert_equal(y[1], xp.asarray(xp.nan))
+
+    def test_tstd(self, xp):
+        x = xp.asarray(X.tolist())  # use default dtype of xp
+        xp_test = array_namespace(x)  # need array-api-compat std for `correction`
+
+        y = stats.tstd(x, (2, 8), (True, True))
+        xp_assert_close(y, xp.asarray(2.1602468994692865))
+
+        y = stats.tstd(x, limits=None)
+        xp_assert_close(y, xp_test.std(x, correction=1))
+
+    def test_tmin(self, xp):
+        x = xp.arange(10)
+        xp_assert_equal(stats.tmin(x), xp.asarray(0))
+        xp_assert_equal(stats.tmin(x, lowerlimit=0), xp.asarray(0))
+        xp_assert_equal(stats.tmin(x, lowerlimit=0, inclusive=False), xp.asarray(1))
+
+        x = xp.reshape(x, (5, 2))
+        xp_assert_equal(stats.tmin(x, lowerlimit=0, inclusive=False),
+                        xp.asarray([2, 1]))
+        xp_assert_equal(stats.tmin(x, axis=1), xp.asarray([0, 2, 4, 6, 8]))
+        xp_assert_equal(stats.tmin(x, axis=None), xp.asarray(0))
+
+        x = xp.arange(10.)
+        x[9] = xp.nan
+        xp_assert_equal(stats.tmin(x), xp.asarray(xp.nan))
+
+        # check that if a full slice is masked, the output returns a
+        # nan instead of a garbage value.
+        x = xp.arange(16).reshape(4, 4)
+        res = stats.tmin(x, lowerlimit=4, axis=1)
+        xp_assert_equal(res, xp.asarray([np.nan, 4, 8, 12]))
+
+    @skip_xp_backends(np_only=True,
+                      reason="Only NumPy arrays support scalar input/`nan_policy`.")
+    def test_tmin_scalar_and_nanpolicy(self, xp):
+        assert_equal(stats.tmin(4), 4)
+
+        x = np.arange(10.)
+        x[9] = np.nan
+        with suppress_warnings() as sup:
+            sup.record(RuntimeWarning, "invalid value*")
+            assert_equal(stats.tmin(x, nan_policy='omit'), 0.)
+            msg = "The input contains nan values"
+            with assert_raises(ValueError, match=msg):
+                stats.tmin(x, nan_policy='raise')
+            msg = "nan_policy must be one of..."
+            with assert_raises(ValueError, match=msg):
+                stats.tmin(x, nan_policy='foobar')
+
+    def test_tmax(self, xp):
+        x = xp.arange(10)
+        xp_assert_equal(stats.tmax(x), xp.asarray(9))
+        xp_assert_equal(stats.tmax(x, upperlimit=9), xp.asarray(9))
+        xp_assert_equal(stats.tmax(x, upperlimit=9, inclusive=False), xp.asarray(8))
+
+        x = xp.reshape(x, (5, 2))
+        xp_assert_equal(stats.tmax(x, upperlimit=9, inclusive=False),
+                        xp.asarray([8, 7]))
+        xp_assert_equal(stats.tmax(x, axis=1), xp.asarray([1, 3, 5, 7, 9]))
+        xp_assert_equal(stats.tmax(x, axis=None), xp.asarray(9))
+
+        x = xp.arange(10.)
+        x[9] = xp.nan
+        xp_assert_equal(stats.tmax(x), xp.asarray(xp.nan))
+
+        # check that if a full slice is masked, the output returns a
+        # nan instead of a garbage value.
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "All-NaN slice encountered")
+            x = xp.reshape(xp.arange(16), (4, 4))
+            res = stats.tmax(x, upperlimit=11, axis=1)
+            xp_assert_equal(res, xp.asarray([3, 7, 11, np.nan]))
+
+    @skip_xp_backends(np_only=True,
+                      reason="Only NumPy arrays support scalar input/`nan_policy`.")
+    def test_tax_scalar_and_nanpolicy(self, xp):
+        assert_equal(stats.tmax(4), 4)
+
+        x = np.arange(10.)
+        x[6] = np.nan
+        with suppress_warnings() as sup:
+            sup.record(RuntimeWarning, "invalid value*")
+            assert_equal(stats.tmax(x, nan_policy='omit'), 9.)
+            msg = "The input contains nan values"
+            with assert_raises(ValueError, match=msg):
+                stats.tmax(x, nan_policy='raise')
+            msg = "nan_policy must be one of..."
+            with assert_raises(ValueError, match=msg):
+                stats.tmax(x, nan_policy='foobar')
+
+    def test_tsem(self, xp):
+        x = xp.asarray(X.tolist())  # use default dtype of xp
+        xp_test = array_namespace(x)  # need array-api-compat std for `correction`
+
+        y = stats.tsem(x, limits=(3, 8), inclusive=(False, True))
+        y_ref = xp.asarray([4., 5., 6., 7., 8.])
+        xp_assert_close(y, xp_test.std(y_ref, correction=1) / xp_size(y_ref)**0.5)
+        xp_assert_close(stats.tsem(x, limits=[-1, 10]), stats.tsem(x, limits=None))
+
+
+class TestPearsonrWilkinson:
+    """ W.II.D. Compute a correlation matrix on all the variables.
+
+        All the correlations, except for ZERO and MISS, should be exactly 1.
+        ZERO and MISS should have undefined or missing correlations with the
+        other variables.  The same should go for SPEARMAN correlations, if
+        your program has them.
+    """
+
+    def test_pXX(self):
+        y = stats.pearsonr(X,X)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pXBIG(self):
+        y = stats.pearsonr(X,BIG)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pXLITTLE(self):
+        y = stats.pearsonr(X,LITTLE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pXHUGE(self):
+        y = stats.pearsonr(X,HUGE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pXTINY(self):
+        y = stats.pearsonr(X,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pXROUND(self):
+        y = stats.pearsonr(X,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pBIGBIG(self):
+        y = stats.pearsonr(BIG,BIG)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pBIGLITTLE(self):
+        y = stats.pearsonr(BIG,LITTLE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pBIGHUGE(self):
+        y = stats.pearsonr(BIG,HUGE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pBIGTINY(self):
+        y = stats.pearsonr(BIG,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pBIGROUND(self):
+        y = stats.pearsonr(BIG,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pLITTLELITTLE(self):
+        y = stats.pearsonr(LITTLE,LITTLE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pLITTLEHUGE(self):
+        y = stats.pearsonr(LITTLE,HUGE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pLITTLETINY(self):
+        y = stats.pearsonr(LITTLE,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pLITTLEROUND(self):
+        y = stats.pearsonr(LITTLE,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pHUGEHUGE(self):
+        y = stats.pearsonr(HUGE,HUGE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pHUGETINY(self):
+        y = stats.pearsonr(HUGE,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pHUGEROUND(self):
+        y = stats.pearsonr(HUGE,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pTINYTINY(self):
+        y = stats.pearsonr(TINY,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pTINYROUND(self):
+        y = stats.pearsonr(TINY,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_pROUNDROUND(self):
+        y = stats.pearsonr(ROUND,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@skip_xp_backends(cpu_only=True)
+class TestPearsonr:
+    @skip_xp_backends(np_only=True)
+    def test_pearsonr_result_attributes(self):
+        res = stats.pearsonr(X, X)
+        attributes = ('correlation', 'pvalue')
+        check_named_results(res, attributes)
+        assert_equal(res.correlation, res.statistic)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    def test_r_almost_exactly_pos1(self, xp):
+        a = xp.arange(3.0)
+        r, prob = stats.pearsonr(a, a)
+
+        xp_assert_close(r, xp.asarray(1.0), atol=1e-15)
+        # With n = len(a) = 3, the error in prob grows like the
+        # square root of the error in r.
+        xp_assert_close(prob, xp.asarray(0.0), atol=np.sqrt(2*np.spacing(1.0)))
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    def test_r_almost_exactly_neg1(self, xp):
+        a = xp.arange(3.0)
+        r, prob = stats.pearsonr(a, -a)
+
+        xp_assert_close(r, xp.asarray(-1.0), atol=1e-15)
+        # With n = len(a) = 3, the error in prob grows like the
+        # square root of the error in r.
+        xp_assert_close(prob, xp.asarray(0.0), atol=np.sqrt(2*np.spacing(1.0)))
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    def test_basic(self, xp):
+        # A basic test, with a correlation coefficient
+        # that is not 1 or -1.
+        a = xp.asarray([-1, 0, 1])
+        b = xp.asarray([0, 0, 3])
+        r, prob = stats.pearsonr(a, b)
+        xp_assert_close(r, xp.asarray(3**0.5/2))
+        xp_assert_close(prob, xp.asarray(1/3))
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment',
+                      )
+    def test_constant_input(self, xp):
+        # Zero variance input
+        # See https://github.com/scipy/scipy/issues/3728
+        msg = "An input array is constant"
+        with pytest.warns(stats.ConstantInputWarning, match=msg):
+            x = xp.asarray([0.667, 0.667, 0.667])
+            y = xp.asarray([0.123, 0.456, 0.789])
+            r, p = stats.pearsonr(x, y)
+            xp_assert_close(r, xp.asarray(xp.nan))
+            xp_assert_close(p, xp.asarray(xp.nan))
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment',
+                      )
+    @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+    def test_near_constant_input(self, xp, dtype):
+        npdtype = getattr(np, dtype)
+        dtype = getattr(xp, dtype)
+        # Near constant input (but not constant):
+        x = xp.asarray([2, 2, 2 + np.spacing(2, dtype=npdtype)], dtype=dtype)
+        y = xp.asarray([3, 3, 3 + 6*np.spacing(3, dtype=npdtype)], dtype=dtype)
+        msg = "An input array is nearly constant; the computed"
+        with pytest.warns(stats.NearConstantInputWarning, match=msg):
+            # r and p are garbage, so don't bother checking them in this case.
+            # (The exact value of r would be 1.)
+            stats.pearsonr(x, y)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment',
+                      )
+    def test_very_small_input_values(self, xp):
+        # Very small values in an input.  A naive implementation will
+        # suffer from underflow.
+        # See https://github.com/scipy/scipy/issues/9353
+        x = xp.asarray([0.004434375, 0.004756007, 0.003911996, 0.0038005, 0.003409971],
+                       dtype=xp.float64)
+        y = xp.asarray([2.48e-188, 7.41e-181, 4.09e-208, 2.08e-223, 2.66e-245],
+                       dtype=xp.float64)
+        r, p = stats.pearsonr(x, y)
+
+        # The expected values were computed using mpmath with 80 digits
+        # of precision.
+        xp_assert_close(r, xp.asarray(0.7272930540750450, dtype=xp.float64))
+        xp_assert_close(p, xp.asarray(0.1637805429533202, dtype=xp.float64))
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment',
+                      )
+    def test_very_large_input_values(self, xp):
+        # Very large values in an input.  A naive implementation will
+        # suffer from overflow.
+        # See https://github.com/scipy/scipy/issues/8980
+        x = 1e90*xp.asarray([0, 0, 0, 1, 1, 1, 1], dtype=xp.float64)
+        y = 1e90*xp.arange(7, dtype=xp.float64)
+
+        r, p = stats.pearsonr(x, y)
+
+        # The expected values were computed using mpmath with 80 digits
+        # of precision.
+        xp_assert_close(r, xp.asarray(0.8660254037844386, dtype=xp.float64))
+        xp_assert_close(p, xp.asarray(0.011724811003954638, dtype=xp.float64))
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    def test_extremely_large_input_values(self, xp):
+        # Extremely large values in x and y.  These values would cause the
+        # product sigma_x * sigma_y to overflow if the two factors were
+        # computed independently.
+        x = xp.asarray([2.3e200, 4.5e200, 6.7e200, 8e200], dtype=xp.float64)
+        y = xp.asarray([1.2e199, 5.5e200, 3.3e201, 1.0e200], dtype=xp.float64)
+        r, p = stats.pearsonr(x, y)
+
+        # The expected values were computed using mpmath with 80 digits
+        # of precision.
+        xp_assert_close(r, xp.asarray(0.351312332103289, dtype=xp.float64))
+        xp_assert_close(p, xp.asarray(0.648687667896711, dtype=xp.float64))
+
+    @skip_xp_backends('jax.numpy', reason="JAX doesn't allow item assignment.")
+    def test_length_two_pos1(self, xp):
+        # Inputs with length 2.
+        # See https://github.com/scipy/scipy/issues/7730
+        x = xp.asarray([1., 2.])
+        y = xp.asarray([3., 5.])
+        res = stats.pearsonr(x, y)
+        r, p = res
+        one = xp.asarray(1.)
+        xp_assert_equal(r, one)
+        xp_assert_equal(p, one)
+        low, high = res.confidence_interval()
+        xp_assert_equal(low, -one)
+        xp_assert_equal(high, one)
+
+    @skip_xp_backends('jax.numpy', reason="JAX doesn't allow item assignment.")
+    def test_length_two_neg1(self, xp):
+        # Inputs with length 2.
+        # See https://github.com/scipy/scipy/issues/7730
+        x = xp.asarray([2., 1.])
+        y = xp.asarray([3., 5.])
+        res = stats.pearsonr(x, y)
+        r, p = res
+        one = xp.asarray(1.)
+        xp_assert_equal(r, -one)
+        xp_assert_equal(p, one)
+        low, high = res.confidence_interval()
+        xp_assert_equal(low, -one)
+        xp_assert_equal(high, one)
+
+    @skip_xp_backends('jax.numpy', reason="JAX doesn't allow item assignment.")
+    def test_length_two_constant_input(self, xp):
+        # Zero variance input
+        # See https://github.com/scipy/scipy/issues/3728
+        # and https://github.com/scipy/scipy/issues/7730
+        msg = "An input array is constant"
+        with pytest.warns(stats.ConstantInputWarning, match=msg):
+            x = xp.asarray([0.667, 0.667])
+            y = xp.asarray([0.123, 0.456])
+            r, p = stats.pearsonr(x, y)
+            xp_assert_close(r, xp.asarray(xp.nan))
+            xp_assert_close(p, xp.asarray(xp.nan))
+
+    # Expected values computed with R 3.6.2 cor.test, e.g.
+    # options(digits=16)
+    # x <- c(1, 2, 3, 4)
+    # y <- c(0, 1, 0.5, 1)
+    # cor.test(x, y, method = "pearson", alternative = "g")
+    # correlation coefficient and p-value for alternative='two-sided'
+    # calculated with mpmath agree to 16 digits.
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.parametrize('alternative, pval, rlow, rhigh, sign',
+            [('two-sided', 0.325800137536, -0.814938968841, 0.99230697523, 1),
+             ('less', 0.8370999312316, -1, 0.985600937290653, 1),
+             ('greater', 0.1629000687684, -0.6785654158217636, 1, 1),
+             ('two-sided', 0.325800137536, -0.992306975236, 0.81493896884, -1),
+             ('less', 0.1629000687684, -1.0, 0.6785654158217636, -1),
+             ('greater', 0.8370999312316, -0.985600937290653, 1.0, -1)])
+    def test_basic_example(self, alternative, pval, rlow, rhigh, sign):
+        x = [1, 2, 3, 4]
+        y = np.array([0, 1, 0.5, 1]) * sign
+        result = stats.pearsonr(x, y, alternative=alternative)
+        assert_allclose(result.statistic, 0.6741998624632421*sign, rtol=1e-12)
+        assert_allclose(result.pvalue, pval, rtol=1e-6)
+        ci = result.confidence_interval()
+        assert_allclose(ci, (rlow, rhigh), rtol=1e-6)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    def test_negative_correlation_pvalue_gh17795(self, xp):
+        x = xp.arange(10.)
+        y = -x
+        test_greater = stats.pearsonr(x, y, alternative='greater')
+        test_less = stats.pearsonr(x, y, alternative='less')
+        xp_assert_close(test_greater.pvalue, xp.asarray(1.))
+        xp_assert_close(test_less.pvalue, xp.asarray(0.), atol=1e-20)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    def test_length3_r_exactly_negative_one(self, xp):
+        x = xp.asarray([1., 2., 3.])
+        y = xp.asarray([5., -4., -13.])
+        res = stats.pearsonr(x, y)
+
+        # The expected r and p are exact.
+        r, p = res
+        one = xp.asarray(1.0)
+        xp_assert_close(r, -one)
+        xp_assert_close(p, 0*one, atol=1e-7)
+        low, high = res.confidence_interval()
+        xp_assert_equal(low, -one)
+        xp_assert_equal(high, one)
+
+    @pytest.mark.skip_xp_backends(np_only=True)
+    def test_input_validation(self):
+        x = [1, 2, 3]
+        y = [4, 5]
+        message = '`x` and `y` must have the same length along `axis`.'
+        with pytest.raises(ValueError, match=message):
+            stats.pearsonr(x, y)
+
+        x = [1]
+        y = [2]
+        message = '`x` and `y` must have length at least 2.'
+        with pytest.raises(ValueError, match=message):
+            stats.pearsonr(x, y)
+
+        x = [-1j, -2j, -3.0j]
+        y = [-1j, -2j, -3.0j]
+        message = 'This function does not support complex data'
+        with pytest.raises(ValueError, match=message):
+            stats.pearsonr(x, y)
+
+        message = "`method` must be an instance of..."
+        with pytest.raises(ValueError, match=message):
+            stats.pearsonr([1, 2], [3, 4], method="asymptotic")
+
+        res = stats.pearsonr([1, 2], [3, 4])
+        with pytest.raises(ValueError, match=message):
+            res.confidence_interval(method="exact")
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.xfail_on_32bit("Monte Carlo method needs > a few kB of memory")
+    @pytest.mark.parametrize('alternative', ('less', 'greater', 'two-sided'))
+    @pytest.mark.parametrize('method_name',
+                             ('permutation', 'monte_carlo', 'monte_carlo2'))
+    def test_resampling_pvalue(self, method_name, alternative):
+        rng = np.random.default_rng(24623935790378923)
+        size = (2, 100) if method_name == 'permutation' else (2, 1000)
+        x = rng.normal(size=size)
+        y = rng.normal(size=size)
+        methods = {'permutation': stats.PermutationMethod(rng=rng),
+                   'monte_carlo': stats.MonteCarloMethod(rvs=(rng.normal,)*2),
+                   'monte_carlo2': stats.MonteCarloMethod(rng=1294)}
+        method = methods[method_name]
+        res = stats.pearsonr(x, y, alternative=alternative, method=method, axis=-1)
+        ref = stats.pearsonr(x, y, alternative=alternative, axis=-1)
+        assert_allclose(res.statistic, ref.statistic, rtol=1e-15)
+        assert_allclose(res.pvalue, ref.pvalue, rtol=1e-2, atol=1e-3)
+
+        if method_name == 'monte_carlo2':
+            method = stats.MonteCarloMethod(rng=1294)
+            res2 = stats.pearsonr(x, y, alternative=alternative, method=method, axis=-1)
+            assert_equal(res2.statistic, res.statistic)
+            assert_equal(res2.pvalue, res.pvalue)
+
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.parametrize('alternative', ('less', 'greater', 'two-sided'))
+    def test_bootstrap_ci(self, alternative):
+        rng = np.random.default_rng(2462935790378923)
+        x = rng.normal(size=(2, 100))
+        y = rng.normal(size=(2, 100))
+        res = stats.pearsonr(x, y, alternative=alternative, axis=-1)
+
+        # preserve use of old random_state during SPEC 7 transition
+        rng = np.random.default_rng(724358723498249852)
+        method = stats.BootstrapMethod(random_state=rng)
+        res_ci = res.confidence_interval(method=method)
+        ref_ci = res.confidence_interval()
+        assert_allclose(res_ci, ref_ci, atol=1.5e-2)
+
+        # `rng` is the new argument name`
+        rng = np.random.default_rng(724358723498249852)
+        method = stats.BootstrapMethod(rng=rng)
+        res_ci2 = res.confidence_interval(method=method)
+        assert_allclose(res_ci2, res_ci)
+
+    @pytest.mark.skip_xp_backends(np_only=True)
+    @pytest.mark.parametrize('axis', [0, 1])
+    def test_axis01(self, axis, xp):
+        rng = np.random.default_rng(38572345825)
+        shape = (9, 10)
+        x, y = rng.normal(size=(2,) + shape)
+        res = stats.pearsonr(x, y, axis=axis)
+        ci = res.confidence_interval()
+        if axis == 0:
+            x, y = x.T, y.T
+        for i in range(x.shape[0]):
+            res_i = stats.pearsonr(x[i], y[i])
+            ci_i = res_i.confidence_interval()
+            assert_allclose(res.statistic[i], res_i.statistic)
+            assert_allclose(res.pvalue[i], res_i.pvalue)
+            assert_allclose(ci.low[i], ci_i.low)
+            assert_allclose(ci.high[i], ci_i.high)
+
+    @pytest.mark.skip_xp_backends(np_only=True)
+    def test_axis_None(self, xp):
+        rng = np.random.default_rng(38572345825)
+        shape = (9, 10)
+        x, y = rng.normal(size=(2,) + shape)
+        res = stats.pearsonr(x, y, axis=None)
+        ci = res.confidence_interval()
+        ref = stats.pearsonr(x.ravel(), y.ravel())
+        ci_ref = ref.confidence_interval()
+        assert_allclose(res.statistic, ref.statistic)
+        assert_allclose(res.pvalue, ref.pvalue)
+        assert_allclose(ci, ci_ref)
+
+    def test_nd_input_validation(self, xp):
+        x = y = xp.ones((2, 5))
+        message = '`axis` must be an integer.'
+        with pytest.raises(ValueError, match=message):
+            stats.pearsonr(x, y, axis=1.5)
+
+        message = '`x` and `y` must have the same length along `axis`'
+        with pytest.raises(ValueError, match=message):
+            stats.pearsonr(x, xp.ones((2, 1)), axis=1)
+
+        message = '`x` and `y` must have length at least 2.'
+        with pytest.raises(ValueError, match=message):
+            stats.pearsonr(xp.ones((2, 1)), xp.ones((2, 1)), axis=1)
+
+        message = '`x` and `y` must be broadcastable.'
+        with pytest.raises(ValueError, match=message):
+            stats.pearsonr(x, xp.ones((3, 5)), axis=1)
+
+        message = '`method` must be `None` if arguments are not NumPy arrays.'
+        if not is_numpy(xp):
+            x = xp.arange(10)
+            with pytest.raises(ValueError, match=message):
+                stats.pearsonr(x, x, method=stats.PermutationMethod())
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    def test_nd_special_cases(self, xp):
+        rng = np.random.default_rng(34989235492245)
+        x0 = xp.asarray(rng.random((3, 5)))
+        y0 = xp.asarray(rng.random((3, 5)))
+
+        message = 'An input array is constant'
+        with pytest.warns(stats.ConstantInputWarning, match=message):
+            x = xp_copy(x0)
+            x[0, ...] = 1
+            res = stats.pearsonr(x, y0, axis=1)
+            ci = res.confidence_interval()
+            nan = xp.asarray(xp.nan, dtype=xp.float64)
+            xp_assert_equal(res.statistic[0], nan)
+            xp_assert_equal(res.pvalue[0], nan)
+            xp_assert_equal(ci.low[0], nan)
+            xp_assert_equal(ci.high[0], nan)
+            assert not xp.any(xp.isnan(res.statistic[1:]))
+            assert not xp.any(xp.isnan(res.pvalue[1:]))
+            assert not xp.any(xp.isnan(ci.low[1:]))
+            assert not xp.any(xp.isnan(ci.high[1:]))
+
+        message = 'An input array is nearly constant'
+        with pytest.warns(stats.NearConstantInputWarning, match=message):
+            x[0, 0] = 1 + 1e-15
+            stats.pearsonr(x, y0, axis=1)
+
+        # length 2 along axis
+        x = xp.asarray([[1, 2], [1, 2], [2, 1], [2, 1.]])
+        y = xp.asarray([[1, 2], [2, 1], [1, 2], [2, 1.]])
+        ones = xp.ones(4)
+        res = stats.pearsonr(x, y, axis=-1)
+        ci = res.confidence_interval()
+        xp_assert_close(res.statistic, xp.asarray([1, -1, -1, 1.]))
+        xp_assert_close(res.pvalue, ones)
+        xp_assert_close(ci.low, -ones)
+        xp_assert_close(ci.high, ones)
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    @pytest.mark.parametrize('axis', [0, 1, None])
+    @pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided'])
+    def test_array_api(self, xp, axis, alternative):
+        x, y = rng.normal(size=(2, 10, 11))
+        res = stats.pearsonr(xp.asarray(x), xp.asarray(y),
+                             axis=axis, alternative=alternative)
+        ref = stats.pearsonr(x, y, axis=axis, alternative=alternative)
+        xp_assert_close(res.statistic, xp.asarray(ref.statistic))
+        xp_assert_close(res.pvalue, xp.asarray(ref.pvalue))
+
+        res_ci = res.confidence_interval()
+        ref_ci = ref.confidence_interval()
+        xp_assert_close(res_ci.low, xp.asarray(ref_ci.low))
+        xp_assert_close(res_ci.high, xp.asarray(ref_ci.high))
+
+
+class TestFisherExact:
+    """Some tests to show that fisher_exact() works correctly.
+
+    Note that in SciPy 0.9.0 this was not working well for large numbers due to
+    inaccuracy of the hypergeom distribution (see #1218). Fixed now.
+
+    Also note that R and SciPy have different argument formats for their
+    hypergeometric distribution functions.
+
+    R:
+    > phyper(18999, 99000, 110000, 39000, lower.tail = FALSE)
+    [1] 1.701815e-09
+    """
+
+    def test_basic(self):
+        fisher_exact = stats.fisher_exact
+
+        res = fisher_exact([[14500, 20000], [30000, 40000]])[1]
+        assert_approx_equal(res, 0.01106, significant=4)
+        res = fisher_exact([[100, 2], [1000, 5]])[1]
+        assert_approx_equal(res, 0.1301, significant=4)
+        res = fisher_exact([[2, 7], [8, 2]])[1]
+        assert_approx_equal(res, 0.0230141, significant=6)
+        res = fisher_exact([[5, 1], [10, 10]])[1]
+        assert_approx_equal(res, 0.1973244, significant=6)
+        res = fisher_exact([[5, 15], [20, 20]])[1]
+        assert_approx_equal(res, 0.0958044, significant=6)
+        res = fisher_exact([[5, 16], [20, 25]])[1]
+        assert_approx_equal(res, 0.1725862, significant=6)
+        res = fisher_exact([[10, 5], [10, 1]])[1]
+        assert_approx_equal(res, 0.1973244, significant=6)
+        res = fisher_exact([[5, 0], [1, 4]])[1]
+        assert_approx_equal(res, 0.04761904, significant=6)
+        res = fisher_exact([[0, 1], [3, 2]])[1]
+        assert_approx_equal(res, 1.0)
+        res = fisher_exact([[0, 2], [6, 4]])[1]
+        assert_approx_equal(res, 0.4545454545)
+        res = fisher_exact([[2, 7], [8, 2]])
+        assert_approx_equal(res[1], 0.0230141, significant=6)
+        assert_approx_equal(res[0], 4.0 / 56)
+
+    def test_precise(self):
+        # results from R
+        #
+        # R defines oddsratio differently (see Notes section of fisher_exact
+        # docstring), so those will not match.  We leave them in anyway, in
+        # case they will be useful later on. We test only the p-value.
+        tablist = [
+            ([[100, 2], [1000, 5]], (2.505583993422285e-001, 1.300759363430016e-001)),
+            ([[2, 7], [8, 2]], (8.586235135736206e-002, 2.301413756522114e-002)),
+            ([[5, 1], [10, 10]], (4.725646047336584e+000, 1.973244147157190e-001)),
+            ([[5, 15], [20, 20]], (3.394396617440852e-001, 9.580440012477637e-002)),
+            ([[5, 16], [20, 25]], (3.960558326183334e-001, 1.725864953812994e-001)),
+            ([[10, 5], [10, 1]], (2.116112781158483e-001, 1.973244147157190e-001)),
+            ([[10, 5], [10, 0]], (0.000000000000000e+000, 6.126482213438734e-002)),
+            ([[5, 0], [1, 4]], (np.inf, 4.761904761904762e-002)),
+            ([[0, 5], [1, 4]], (0.000000000000000e+000, 1.000000000000000e+000)),
+            ([[5, 1], [0, 4]], (np.inf, 4.761904761904758e-002)),
+            ([[0, 1], [3, 2]], (0.000000000000000e+000, 1.000000000000000e+000))
+            ]
+        for table, res_r in tablist:
+            res = stats.fisher_exact(np.asarray(table))
+            np.testing.assert_almost_equal(res[1], res_r[1], decimal=11,
+                                           verbose=True)
+
+    def test_gh4130(self):
+        # Previously, a fudge factor used to distinguish between theoretically
+        # and numerically different probability masses was 1e-4; it has been
+        # tightened to fix gh4130. Accuracy checked against R fisher.test.
+        # options(digits=16)
+        # table <- matrix(c(6, 108, 37, 200), nrow = 2)
+        # fisher.test(table, alternative = "t")
+        x = [[6, 37], [108, 200]]
+        res = stats.fisher_exact(x)
+        assert_allclose(res[1], 0.005092697748126)
+
+        # case from https://github.com/brentp/fishers_exact_test/issues/27
+        # That package has an (absolute?) fudge factor of 1e-6; too big
+        x = [[22, 0], [0, 102]]
+        res = stats.fisher_exact(x)
+        assert_allclose(res[1], 7.175066786244549e-25)
+
+        # case from https://github.com/brentp/fishers_exact_test/issues/1
+        x = [[94, 48], [3577, 16988]]
+        res = stats.fisher_exact(x)
+        assert_allclose(res[1], 2.069356340993818e-37)
+
+    def test_gh9231(self):
+        # Previously, fisher_exact was extremely slow for this table
+        # As reported in gh-9231, the p-value should be very nearly zero
+        x = [[5829225, 5692693], [5760959, 5760959]]
+        res = stats.fisher_exact(x)
+        assert_allclose(res[1], 0, atol=1e-170)
+
+    @pytest.mark.slow
+    def test_large_numbers(self):
+        # Test with some large numbers. Regression test for #1401
+        pvals = [5.56e-11, 2.666e-11, 1.363e-11]  # from R
+        for pval, num in zip(pvals, [75, 76, 77]):
+            res = stats.fisher_exact([[17704, 496], [1065, num]])[1]
+            assert_approx_equal(res, pval, significant=4)
+
+        res = stats.fisher_exact([[18000, 80000], [20000, 90000]])[1]
+        assert_approx_equal(res, 0.2751, significant=4)
+
+    def test_raises(self):
+        # test we raise an error for wrong number of dimensions.
+        message = "The input `table` must have two dimensions."
+        with pytest.raises(ValueError, match=message):
+            stats.fisher_exact(np.arange(6))
+
+    def test_row_or_col_zero(self):
+        tables = ([[0, 0], [5, 10]],
+                  [[5, 10], [0, 0]],
+                  [[0, 5], [0, 10]],
+                  [[5, 0], [10, 0]])
+        for table in tables:
+            oddsratio, pval = stats.fisher_exact(table)
+            assert_equal(pval, 1.0)
+            assert_equal(oddsratio, np.nan)
+
+    def test_less_greater(self):
+        tables = (
+            # Some tables to compare with R:
+            [[2, 7], [8, 2]],
+            [[200, 7], [8, 300]],
+            [[28, 21], [6, 1957]],
+            [[190, 800], [200, 900]],
+            # Some tables with simple exact values
+            # (includes regression test for ticket #1568):
+            [[0, 2], [3, 0]],
+            [[1, 1], [2, 1]],
+            [[2, 0], [1, 2]],
+            [[0, 1], [2, 3]],
+            [[1, 0], [1, 4]],
+            )
+        pvals = (
+            # from R:
+            [0.018521725952066501, 0.9990149169715733],
+            [1.0, 2.0056578803889148e-122],
+            [1.0, 5.7284374608319831e-44],
+            [0.7416227, 0.2959826],
+            # Exact:
+            [0.1, 1.0],
+            [0.7, 0.9],
+            [1.0, 0.3],
+            [2./3, 1.0],
+            [1.0, 1./3],
+            )
+        for table, pval in zip(tables, pvals):
+            res = []
+            res.append(stats.fisher_exact(table, alternative="less")[1])
+            res.append(stats.fisher_exact(table, alternative="greater")[1])
+            assert_allclose(res, pval, atol=0, rtol=1e-7)
+
+    def test_gh3014(self):
+        # check if issue #3014 has been fixed.
+        # before, this would have risen a ValueError
+        odds, pvalue = stats.fisher_exact([[1, 2], [9, 84419233]])
+
+    @pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater'])
+    def test_result(self, alternative):
+        table = np.array([[14500, 20000], [30000, 40000]])
+        res = stats.fisher_exact(table, alternative=alternative)
+        assert_equal((res.statistic, res.pvalue), res)
+
+    def test_input_validation_edge_cases_rxc(self):
+        rng = np.random.default_rng(2345783457834572345)
+        table = np.asarray([[2, 7], [8, 2]])
+
+        message = r"`alternative` must be the default \(None\) unless..."
+        with pytest.raises(ValueError, match=message):
+            method = stats.PermutationMethod(rng=rng)
+            stats.fisher_exact(table, method=method, alternative='less')
+
+        message = "...not recognized; if provided, `method` must be an..."
+        with pytest.raises(ValueError, match=message):
+            method = stats.BootstrapMethod(rng=rng)
+            stats.fisher_exact(table, method=method)
+
+        message = "If the `method` argument of `fisher_exact` is an..."
+        with pytest.raises(ValueError, match=message):
+            method = stats.MonteCarloMethod(rvs=stats.norm.rvs)
+            stats.fisher_exact(table, method=method)
+
+        message = "`table` must have at least one row and one column."
+        with pytest.raises(ValueError, match=message):
+            stats.fisher_exact(np.zeros((0, 1)))
+
+        # Specical case: when there is only one table with given marginals, the
+        # PMF of that case is 1.0, so the p-value is 1.0
+        np.testing.assert_equal(stats.fisher_exact([[1, 2, 3]]), (1, 1))
+        np.testing.assert_equal(stats.fisher_exact([[1], [2], [3]]), (1, 1))
+        np.testing.assert_equal(stats.fisher_exact(np.zeros((2, 3))), (1, 1))
+
+
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.slow()
+    def test_resampling_2x2(self):
+        rng = np.random.default_rng(2345783457834572345)
+        table = np.asarray([[2, 7], [8, 2]])
+        ref = stats.fisher_exact(table)
+        ref_pvalue = ref.pvalue
+        ref_stat = stats.random_table(table.sum(axis=1), table.sum(axis=0)).pmf(table)
+
+        method = stats.MonteCarloMethod(rng=rng)
+        res = stats.fisher_exact(table, method=method)
+        assert_allclose(res.pvalue, ref_pvalue, atol=0.0025)
+        assert_equal(res.statistic, ref_stat)
+
+        method = stats.PermutationMethod(rng=rng)
+        res = stats.fisher_exact(table, method=method)
+        assert_allclose(res.pvalue, ref.pvalue, atol=0.0025)
+        assert_equal(res.statistic, ref_stat)
+
+    @pytest.mark.fail_slow(10)
+    @pytest.mark.slow()
+    def test_resampling_rxc(self):
+        # Compare against R fisher.exact
+        # options(digits=16)
+        # MP6 < - rbind(
+        #     c(1, 2, 2, 1, 1, 0, 1),
+        #     c(2, 0, 0, 2, 3, 0, 0),
+        #     c(0, 1, 1, 1, 2, 7, 3),
+        #     c(1, 1, 2, 0, 0, 0, 1),
+        #     c(0, 1, 1, 1, 1, 0, 0))
+        # fisher.test(MP6)
+
+        table = [[1, 2, 2, 1, 1, 0, 1],
+                 [2, 0, 0, 2, 3, 0, 0],
+                 [0, 1, 1, 1, 2, 7, 3],
+                 [1, 1, 2, 0, 0, 0, 1],
+                 [0, 1, 1, 1, 1, 0, 0]]
+        table = np.asarray(table)
+
+        ref_pvalue = 0.03928964365533
+        rng = np.random.default_rng(3928964365533)
+
+        method = stats.PermutationMethod(rng=rng)
+        res = stats.fisher_exact(table, method=method)
+        assert_allclose(res.pvalue, ref_pvalue, atol=5e-4)
+
+        method = stats.MonteCarloMethod(rng=rng, n_resamples=99999)
+        res = stats.fisher_exact(table, method=method)
+        assert_allclose(res.pvalue, ref_pvalue, atol=5e-4)
+
+    @pytest.mark.xslow()
+    def test_resampling_exact_2x2(self):
+        # Test that exact permutation p-value matches result of `fisher_exact`
+        rng = np.random.default_rng(2345783457834572345)
+        method = stats.PermutationMethod(rng=rng)
+
+        for a in range(1, 3):
+            for b in range(1, 3):
+                for c in range(1, 3):
+                    for d in range(1, 4):
+                        table = np.asarray([[a, b], [c, d]])
+                        ref = stats.fisher_exact(table)
+                        res = stats.fisher_exact(table, method=method)
+                        assert_allclose(res.pvalue, ref.pvalue, atol=1e-14)
+
+
+class TestCorrSpearmanr:
+    """ W.II.D. Compute a correlation matrix on all the variables.
+
+        All the correlations, except for ZERO and MISS, should be exactly 1.
+        ZERO and MISS should have undefined or missing correlations with the
+        other variables.  The same should go for SPEARMAN correlations, if
+        your program has them.
+    """
+
+    def test_scalar(self):
+        y = stats.spearmanr(4., 2.)
+        assert_(np.isnan(y).all())
+
+    def test_uneven_lengths(self):
+        assert_raises(ValueError, stats.spearmanr, [1, 2, 1], [8, 9])
+        assert_raises(ValueError, stats.spearmanr, [1, 2, 1], 8)
+
+    def test_uneven_2d_shapes(self):
+        # Different number of columns should work - those just get concatenated.
+        np.random.seed(232324)
+        x = np.random.randn(4, 3)
+        y = np.random.randn(4, 2)
+        assert stats.spearmanr(x, y).statistic.shape == (5, 5)
+        assert stats.spearmanr(x.T, y.T, axis=1).pvalue.shape == (5, 5)
+
+        assert_raises(ValueError, stats.spearmanr, x, y, axis=1)
+        assert_raises(ValueError, stats.spearmanr, x.T, y.T)
+
+    def test_ndim_too_high(self):
+        np.random.seed(232324)
+        x = np.random.randn(4, 3, 2)
+        assert_raises(ValueError, stats.spearmanr, x)
+        assert_raises(ValueError, stats.spearmanr, x, x)
+        assert_raises(ValueError, stats.spearmanr, x, None, None)
+        # But should work with axis=None (raveling axes) for two input arrays
+        assert_allclose(stats.spearmanr(x, x, axis=None),
+                        stats.spearmanr(x.flatten(), x.flatten(), axis=0))
+
+    def test_nan_policy(self):
+        x = np.arange(10.)
+        x[9] = np.nan
+        assert_array_equal(stats.spearmanr(x, x), (np.nan, np.nan))
+        assert_array_equal(stats.spearmanr(x, x, nan_policy='omit'),
+                           (1.0, 0.0))
+        assert_raises(ValueError, stats.spearmanr, x, x, nan_policy='raise')
+        assert_raises(ValueError, stats.spearmanr, x, x, nan_policy='foobar')
+
+    def test_nan_policy_bug_12458(self):
+        np.random.seed(5)
+        x = np.random.rand(5, 10)
+        k = 6
+        x[:, k] = np.nan
+        y = np.delete(x, k, axis=1)
+        corx, px = stats.spearmanr(x, nan_policy='omit')
+        cory, py = stats.spearmanr(y)
+        corx = np.delete(np.delete(corx, k, axis=1), k, axis=0)
+        px = np.delete(np.delete(px, k, axis=1), k, axis=0)
+        assert_allclose(corx, cory, atol=1e-14)
+        assert_allclose(px, py, atol=1e-14)
+
+    def test_nan_policy_bug_12411(self):
+        np.random.seed(5)
+        m = 5
+        n = 10
+        x = np.random.randn(m, n)
+        x[1, 0] = np.nan
+        x[3, -1] = np.nan
+        corr, pvalue = stats.spearmanr(x, axis=1, nan_policy="propagate")
+        res = [[stats.spearmanr(x[i, :], x[j, :]).statistic for i in range(m)]
+               for j in range(m)]
+        assert_allclose(corr, res)
+
+    def test_sXX(self):
+        y = stats.spearmanr(X,X)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sXBIG(self):
+        y = stats.spearmanr(X,BIG)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sXLITTLE(self):
+        y = stats.spearmanr(X,LITTLE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sXHUGE(self):
+        y = stats.spearmanr(X,HUGE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sXTINY(self):
+        y = stats.spearmanr(X,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sXROUND(self):
+        y = stats.spearmanr(X,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sBIGBIG(self):
+        y = stats.spearmanr(BIG,BIG)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sBIGLITTLE(self):
+        y = stats.spearmanr(BIG,LITTLE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sBIGHUGE(self):
+        y = stats.spearmanr(BIG,HUGE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sBIGTINY(self):
+        y = stats.spearmanr(BIG,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sBIGROUND(self):
+        y = stats.spearmanr(BIG,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sLITTLELITTLE(self):
+        y = stats.spearmanr(LITTLE,LITTLE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sLITTLEHUGE(self):
+        y = stats.spearmanr(LITTLE,HUGE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sLITTLETINY(self):
+        y = stats.spearmanr(LITTLE,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sLITTLEROUND(self):
+        y = stats.spearmanr(LITTLE,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sHUGEHUGE(self):
+        y = stats.spearmanr(HUGE,HUGE)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sHUGETINY(self):
+        y = stats.spearmanr(HUGE,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sHUGEROUND(self):
+        y = stats.spearmanr(HUGE,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sTINYTINY(self):
+        y = stats.spearmanr(TINY,TINY)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sTINYROUND(self):
+        y = stats.spearmanr(TINY,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_sROUNDROUND(self):
+        y = stats.spearmanr(ROUND,ROUND)
+        r = y[0]
+        assert_approx_equal(r,1.0)
+
+    def test_spearmanr_result_attributes(self):
+        res = stats.spearmanr(X, X)
+        attributes = ('correlation', 'pvalue')
+        check_named_results(res, attributes)
+        assert_equal(res.correlation, res.statistic)
+
+    def test_1d_vs_2d(self):
+        x1 = [1, 2, 3, 4, 5, 6]
+        x2 = [1, 2, 3, 4, 6, 5]
+        res1 = stats.spearmanr(x1, x2)
+        res2 = stats.spearmanr(np.asarray([x1, x2]).T)
+        assert_allclose(res1, res2)
+
+    def test_1d_vs_2d_nans(self):
+        # Now the same with NaNs present.  Regression test for gh-9103.
+        for nan_policy in ['propagate', 'omit']:
+            x1 = [1, np.nan, 3, 4, 5, 6]
+            x2 = [1, 2, 3, 4, 6, np.nan]
+            res1 = stats.spearmanr(x1, x2, nan_policy=nan_policy)
+            res2 = stats.spearmanr(np.asarray([x1, x2]).T, nan_policy=nan_policy)
+            assert_allclose(res1, res2)
+
+    def test_3cols(self):
+        x1 = np.arange(6)
+        x2 = -x1
+        x3 = np.array([0, 1, 2, 3, 5, 4])
+        x = np.asarray([x1, x2, x3]).T
+        actual = stats.spearmanr(x)
+        expected_corr = np.array([[1, -1, 0.94285714],
+                                  [-1, 1, -0.94285714],
+                                  [0.94285714, -0.94285714, 1]])
+        expected_pvalue = np.zeros((3, 3), dtype=float)
+        expected_pvalue[2, 0:2] = 0.00480466472
+        expected_pvalue[0:2, 2] = 0.00480466472
+
+        assert_allclose(actual.statistic, expected_corr)
+        assert_allclose(actual.pvalue, expected_pvalue)
+
+    def test_gh_9103(self):
+        # Regression test for gh-9103.
+        x = np.array([[np.nan, 3.0, 4.0, 5.0, 5.1, 6.0, 9.2],
+                      [5.0, np.nan, 4.1, 4.8, 4.9, 5.0, 4.1],
+                      [0.5, 4.0, 7.1, 3.8, 8.0, 5.1, 7.6]]).T
+        corr = np.array([[np.nan, np.nan, np.nan],
+                         [np.nan, np.nan, np.nan],
+                         [np.nan, np.nan, 1.]])
+        assert_allclose(stats.spearmanr(x, nan_policy='propagate').statistic,
+                        corr)
+
+        res = stats.spearmanr(x, nan_policy='omit').statistic
+        assert_allclose((res[0][1], res[0][2], res[1][2]),
+                        (0.2051957, 0.4857143, -0.4707919), rtol=1e-6)
+
+    def test_gh_8111(self):
+        # Regression test for gh-8111 (different result for float/int/bool).
+        n = 100
+        np.random.seed(234568)
+        x = np.random.rand(n)
+        m = np.random.rand(n) > 0.7
+
+        # bool against float, no nans
+        a = (x > .5)
+        b = np.array(x)
+        res1 = stats.spearmanr(a, b, nan_policy='omit').statistic
+
+        # bool against float with NaNs
+        b[m] = np.nan
+        res2 = stats.spearmanr(a, b, nan_policy='omit').statistic
+
+        # int against float with NaNs
+        a = a.astype(np.int32)
+        res3 = stats.spearmanr(a, b, nan_policy='omit').statistic
+
+        expected = [0.865895477, 0.866100381, 0.866100381]
+        assert_allclose([res1, res2, res3], expected)
+
+
+class TestCorrSpearmanr2:
+    """Some further tests of the spearmanr function."""
+
+    def test_spearmanr_vs_r(self):
+        # Cross-check with R:
+        # cor.test(c(1,2,3,4,5),c(5,6,7,8,7),method="spearmanr")
+        x1 = [1, 2, 3, 4, 5]
+        x2 = [5, 6, 7, 8, 7]
+        expected = (0.82078268166812329, 0.088587005313543798)
+        res = stats.spearmanr(x1, x2)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    def test_empty_arrays(self):
+        assert_equal(stats.spearmanr([], []), (np.nan, np.nan))
+
+    def test_normal_draws(self):
+        np.random.seed(7546)
+        x = np.array([np.random.normal(loc=1, scale=1, size=500),
+                      np.random.normal(loc=1, scale=1, size=500)])
+        corr = [[1.0, 0.3],
+                [0.3, 1.0]]
+        x = np.dot(np.linalg.cholesky(corr), x)
+        expected = (0.28659685838743354, 6.579862219051161e-11)
+        res = stats.spearmanr(x[0], x[1])
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    def test_corr_1(self):
+        assert_approx_equal(stats.spearmanr([1, 1, 2], [1, 1, 2])[0], 1.0)
+
+    def test_nan_policies(self):
+        x = np.arange(10.)
+        x[9] = np.nan
+        assert_array_equal(stats.spearmanr(x, x), (np.nan, np.nan))
+        assert_allclose(stats.spearmanr(x, x, nan_policy='omit'),
+                        (1.0, 0))
+        assert_raises(ValueError, stats.spearmanr, x, x, nan_policy='raise')
+        assert_raises(ValueError, stats.spearmanr, x, x, nan_policy='foobar')
+
+    def test_unequal_lengths(self):
+        x = np.arange(10.)
+        y = np.arange(20.)
+        assert_raises(ValueError, stats.spearmanr, x, y)
+
+    def test_omit_paired_value(self):
+        x1 = [1, 2, 3, 4]
+        x2 = [8, 7, 6, np.nan]
+        res1 = stats.spearmanr(x1, x2, nan_policy='omit')
+        res2 = stats.spearmanr(x1[:3], x2[:3], nan_policy='omit')
+        assert_equal(res1, res2)
+
+    def test_gh_issue_6061_windows_overflow(self):
+        x = list(range(2000))
+        y = list(range(2000))
+        y[0], y[9] = y[9], y[0]
+        y[10], y[434] = y[434], y[10]
+        y[435], y[1509] = y[1509], y[435]
+        # rho = 1 - 6 * (2 * (9^2 + 424^2 + 1074^2))/(2000 * (2000^2 - 1))
+        #     = 1 - (1 / 500)
+        #     = 0.998
+        x.append(np.nan)
+        y.append(3.0)
+        assert_almost_equal(stats.spearmanr(x, y, nan_policy='omit')[0], 0.998)
+
+    def test_tie0(self):
+        # with only ties in one or both inputs
+        warn_msg = "An input array is constant"
+        with pytest.warns(stats.ConstantInputWarning, match=warn_msg):
+            r, p = stats.spearmanr([2, 2, 2], [2, 2, 2])
+            assert_equal(r, np.nan)
+            assert_equal(p, np.nan)
+            r, p = stats.spearmanr([2, 0, 2], [2, 2, 2])
+            assert_equal(r, np.nan)
+            assert_equal(p, np.nan)
+            r, p = stats.spearmanr([2, 2, 2], [2, 0, 2])
+            assert_equal(r, np.nan)
+            assert_equal(p, np.nan)
+
+    def test_tie1(self):
+        # Data
+        x = [1.0, 2.0, 3.0, 4.0]
+        y = [1.0, 2.0, 2.0, 3.0]
+        # Ranks of the data, with tie-handling.
+        xr = [1.0, 2.0, 3.0, 4.0]
+        yr = [1.0, 2.5, 2.5, 4.0]
+        # Result of spearmanr should be the same as applying
+        # pearsonr to the ranks.
+        sr = stats.spearmanr(x, y)
+        pr = stats.pearsonr(xr, yr)
+        assert_almost_equal(sr, pr)
+
+    def test_tie2(self):
+        # Test tie-handling if inputs contain nan's
+        # Data without nan's
+        x1 = [1, 2, 2.5, 2]
+        y1 = [1, 3, 2.5, 4]
+        # Same data with nan's
+        x2 = [1, 2, 2.5, 2, np.nan]
+        y2 = [1, 3, 2.5, 4, np.nan]
+
+        # Results for two data sets should be the same if nan's are ignored
+        sr1 = stats.spearmanr(x1, y1)
+        sr2 = stats.spearmanr(x2, y2, nan_policy='omit')
+        assert_almost_equal(sr1, sr2)
+
+    def test_ties_axis_1(self):
+        z1 = np.array([[1, 1, 1, 1], [1, 2, 3, 4]])
+        z2 = np.array([[1, 2, 3, 4], [1, 1, 1, 1]])
+        z3 = np.array([[1, 1, 1, 1], [1, 1, 1, 1]])
+        warn_msg = "An input array is constant"
+        with pytest.warns(stats.ConstantInputWarning, match=warn_msg):
+            r, p = stats.spearmanr(z1, axis=1)
+            assert_equal(r, np.nan)
+            assert_equal(p, np.nan)
+            r, p = stats.spearmanr(z2, axis=1)
+            assert_equal(r, np.nan)
+            assert_equal(p, np.nan)
+            r, p = stats.spearmanr(z3, axis=1)
+            assert_equal(r, np.nan)
+            assert_equal(p, np.nan)
+
+    def test_gh_11111(self):
+        x = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
+        y = np.array([0, 0.009783728115345005, 0, 0, 0.0019759230121848587,
+                      0.0007535430349118562, 0.0002661781514710257, 0, 0,
+                      0.0007835762419683435])
+        warn_msg = "An input array is constant"
+        with pytest.warns(stats.ConstantInputWarning, match=warn_msg):
+            r, p = stats.spearmanr(x, y)
+            assert_equal(r, np.nan)
+            assert_equal(p, np.nan)
+
+    def test_index_error(self):
+        x = np.array([1.0, 7.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])
+        y = np.array([0, 0.009783728115345005, 0, 0, 0.0019759230121848587,
+                      0.0007535430349118562, 0.0002661781514710257, 0, 0,
+                      0.0007835762419683435])
+        assert_raises(ValueError, stats.spearmanr, x, y, axis=2)
+
+    def test_alternative(self):
+        # Test alternative parameter
+
+        # Simple test - Based on the above ``test_spearmanr_vs_r``
+        x1 = [1, 2, 3, 4, 5]
+        x2 = [5, 6, 7, 8, 7]
+
+        # strong positive correlation
+        expected = (0.82078268166812329, 0.088587005313543798)
+
+        # correlation > 0 -> large "less" p-value
+        res = stats.spearmanr(x1, x2, alternative="less")
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], 1 - (expected[1] / 2))
+
+        # correlation > 0 -> small "less" p-value
+        res = stats.spearmanr(x1, x2, alternative="greater")
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1] / 2)
+
+        with pytest.raises(ValueError, match="`alternative` must be 'less'..."):
+            stats.spearmanr(x1, x2, alternative="ekki-ekki")
+
+    @pytest.mark.parametrize("alternative", ('two-sided', 'less', 'greater'))
+    def test_alternative_nan_policy(self, alternative):
+        # Test nan policies
+        x1 = [1, 2, 3, 4, 5]
+        x2 = [5, 6, 7, 8, 7]
+        x1nan = x1 + [np.nan]
+        x2nan = x2 + [np.nan]
+
+        # test nan_policy="propagate"
+        assert_array_equal(stats.spearmanr(x1nan, x2nan), (np.nan, np.nan))
+
+        # test nan_policy="omit"
+        res_actual = stats.spearmanr(x1nan, x2nan, nan_policy='omit',
+                                     alternative=alternative)
+        res_expected = stats.spearmanr(x1, x2, alternative=alternative)
+        assert_allclose(res_actual, res_expected)
+
+        # test nan_policy="raise"
+        message = 'The input contains nan values'
+        with pytest.raises(ValueError, match=message):
+            stats.spearmanr(x1nan, x2nan, nan_policy='raise',
+                            alternative=alternative)
+
+        # test invalid nan_policy
+        message = "nan_policy must be one of..."
+        with pytest.raises(ValueError, match=message):
+            stats.spearmanr(x1nan, x2nan, nan_policy='ekki-ekki',
+                            alternative=alternative)
+
+
+#    W.II.E.  Tabulate X against X, using BIG as a case weight.  The values
+#    should appear on the diagonal and the total should be 899999955.
+#    If the table cannot hold these values, forget about working with
+#    census data.  You can also tabulate HUGE against TINY.  There is no
+#    reason a tabulation program should not be able to distinguish
+#    different values regardless of their magnitude.
+
+# I need to figure out how to do this one.
+
+
+def test_kendalltau():
+    # For the cases without ties, both variants should give the same
+    # result.
+    variants = ('b', 'c')
+
+    # case without ties, con-dis equal zero
+    x = [5, 2, 1, 3, 6, 4, 7, 8]
+    y = [5, 2, 6, 3, 1, 8, 7, 4]
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (0.0, 1.0)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # case without ties, con-dis equal zero
+    x = [0, 5, 2, 1, 3, 6, 4, 7, 8]
+    y = [5, 2, 0, 6, 3, 1, 8, 7, 4]
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (0.0, 1.0)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # case without ties, con-dis close to zero
+    x = [5, 2, 1, 3, 6, 4, 7]
+    y = [5, 2, 6, 3, 1, 7, 4]
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (-0.14285714286, 0.77261904762)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # case without ties, con-dis close to zero
+    x = [2, 1, 3, 6, 4, 7, 8]
+    y = [2, 6, 3, 1, 8, 7, 4]
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (0.047619047619, 1.0)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # simple case without ties
+    x = np.arange(10)
+    y = np.arange(10)
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (1.0, 5.511463844797e-07)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # swap a couple of values
+    b = y[1]
+    y[1] = y[2]
+    y[2] = b
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (0.9555555555555556, 5.511463844797e-06)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # swap a couple more
+    b = y[5]
+    y[5] = y[6]
+    y[6] = b
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (0.9111111111111111, 2.976190476190e-05)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # same in opposite direction
+    x = np.arange(10)
+    y = np.arange(10)[::-1]
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (-1.0, 5.511463844797e-07)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # swap a couple of values
+    b = y[1]
+    y[1] = y[2]
+    y[2] = b
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (-0.9555555555555556, 5.511463844797e-06)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # swap a couple more
+    b = y[5]
+    y[5] = y[6]
+    y[6] = b
+    # Cross-check with exact result from R:
+    # cor.test(x,y,method="kendall",exact=1)
+    expected = (-0.9111111111111111, 2.976190476190e-05)
+    for taux in variants:
+        res = stats.kendalltau(x, y, variant=taux)
+        assert_approx_equal(res[0], expected[0])
+        assert_approx_equal(res[1], expected[1])
+
+    # Check a case where variants are different
+    # Example values found from Kendall (1970).
+    # P-value is the same for the both variants
+    x = array([1, 2, 2, 4, 4, 6, 6, 8, 9, 9])
+    y = array([1, 2, 4, 4, 4, 4, 8, 8, 8, 10])
+    expected = 0.85895569
+    assert_approx_equal(stats.kendalltau(x, y, variant='b')[0], expected)
+    expected = 0.825
+    assert_approx_equal(stats.kendalltau(x, y, variant='c')[0], expected)
+
+    # check exception in case of ties and method='exact' requested
+    y[2] = y[1]
+    assert_raises(ValueError, stats.kendalltau, x, y, method='exact')
+
+    # check exception in case of invalid method keyword
+    assert_raises(ValueError, stats.kendalltau, x, y, method='banana')
+
+    # check exception in case of invalid variant keyword
+    assert_raises(ValueError, stats.kendalltau, x, y, variant='rms')
+
+    # tau-b with some ties
+    # Cross-check with R:
+    # cor.test(c(12,2,1,12,2),c(1,4,7,1,0),method="kendall",exact=FALSE)
+    x1 = [12, 2, 1, 12, 2]
+    x2 = [1, 4, 7, 1, 0]
+    expected = (-0.47140452079103173, 0.28274545993277478)
+    res = stats.kendalltau(x1, x2)
+    assert_approx_equal(res[0], expected[0])
+    assert_approx_equal(res[1], expected[1])
+
+    # test for namedtuple attribute results
+    attributes = ('correlation', 'pvalue')
+    for taux in variants:
+        res = stats.kendalltau(x1, x2, variant=taux)
+        check_named_results(res, attributes)
+        assert_equal(res.correlation, res.statistic)
+
+    # with only ties in one or both inputs in tau-b or tau-c
+    for taux in variants:
+        assert_equal(stats.kendalltau([2, 2, 2], [2, 2, 2], variant=taux),
+                     (np.nan, np.nan))
+        assert_equal(stats.kendalltau([2, 0, 2], [2, 2, 2], variant=taux),
+                     (np.nan, np.nan))
+        assert_equal(stats.kendalltau([2, 2, 2], [2, 0, 2], variant=taux),
+                     (np.nan, np.nan))
+
+    # empty arrays provided as input
+    assert_equal(stats.kendalltau([], []), (np.nan, np.nan))
+
+    # check with larger arrays
+    np.random.seed(7546)
+    x = np.array([np.random.normal(loc=1, scale=1, size=500),
+                  np.random.normal(loc=1, scale=1, size=500)])
+    corr = [[1.0, 0.3],
+            [0.3, 1.0]]
+    x = np.dot(np.linalg.cholesky(corr), x)
+    expected = (0.19291382765531062, 1.1337095377742629e-10)
+    res = stats.kendalltau(x[0], x[1])
+    assert_approx_equal(res[0], expected[0])
+    assert_approx_equal(res[1], expected[1])
+
+    # this should result in 1 for taub but not tau-c
+    assert_approx_equal(stats.kendalltau([1, 1, 2], [1, 1, 2], variant='b')[0],
+                        1.0)
+    assert_approx_equal(stats.kendalltau([1, 1, 2], [1, 1, 2], variant='c')[0],
+                        0.88888888)
+
+    # test nan_policy
+    x = np.arange(10.)
+    x[9] = np.nan
+    assert_array_equal(stats.kendalltau(x, x), (np.nan, np.nan))
+    assert_allclose(stats.kendalltau(x, x, nan_policy='omit'),
+                    (1.0, 5.5114638e-6), rtol=1e-06)
+    assert_allclose(stats.kendalltau(x, x, nan_policy='omit', method='asymptotic'),
+                    (1.0, 0.00017455009626808976), rtol=1e-06)
+    assert_raises(ValueError, stats.kendalltau, x, x, nan_policy='raise')
+    assert_raises(ValueError, stats.kendalltau, x, x, nan_policy='foobar')
+
+    # test unequal length inputs
+    x = np.arange(10.)
+    y = np.arange(20.)
+    assert_raises(ValueError, stats.kendalltau, x, y)
+
+    # test all ties
+    tau, p_value = stats.kendalltau([], [])
+    assert_equal(np.nan, tau)
+    assert_equal(np.nan, p_value)
+    tau, p_value = stats.kendalltau([0], [0])
+    assert_equal(np.nan, tau)
+    assert_equal(np.nan, p_value)
+
+    # Regression test for GitHub issue #6061 - Overflow on Windows
+    x = np.arange(2000, dtype=float)
+    x = np.ma.masked_greater(x, 1995)
+    y = np.arange(2000, dtype=float)
+    y = np.concatenate((y[1000:], y[:1000]))
+    assert_(np.isfinite(stats.kendalltau(x,y)[1]))
+
+
+def test_kendalltau_vs_mstats_basic():
+    np.random.seed(42)
+    for s in range(2,10):
+        a = []
+        # Generate rankings with ties
+        for i in range(s):
+            a += [i]*i
+        b = list(a)
+        np.random.shuffle(a)
+        np.random.shuffle(b)
+        expected = mstats_basic.kendalltau(a, b)
+        actual = stats.kendalltau(a, b)
+        assert_approx_equal(actual[0], expected[0])
+        assert_approx_equal(actual[1], expected[1])
+
+
+def test_kendalltau_nan_2nd_arg():
+    # regression test for gh-6134: nans in the second arg were not handled
+    x = [1., 2., 3., 4.]
+    y = [np.nan, 2.4, 3.4, 3.4]
+
+    r1 = stats.kendalltau(x, y, nan_policy='omit')
+    r2 = stats.kendalltau(x[1:], y[1:])
+    assert_allclose(r1.statistic, r2.statistic, atol=1e-15)
+
+
+def test_kendalltau_gh18139_overflow():
+    # gh-18139 reported an overflow in `kendalltau` that appeared after
+    # SciPy 0.15.1. Check that this particular overflow does not occur.
+    # (Test would fail if warning were emitted.)
+    import random
+    random.seed(6272161)
+    classes = [1, 2, 3, 4, 5, 6, 7]
+    n_samples = 2 * 10 ** 5
+    x = random.choices(classes, k=n_samples)
+    y = random.choices(classes, k=n_samples)
+    res = stats.kendalltau(x, y)
+    # Reference value from SciPy 0.15.1
+    assert_allclose(res.statistic, 0.0011816493905730343)
+    # Reference p-value from `permutation_test` w/ n_resamples=9999 (default).
+    # Expected to be accurate to at least two digits.
+    assert_allclose(res.pvalue, 0.4894, atol=2e-3)
+
+
+class TestKendallTauAlternative:
+    def test_kendalltau_alternative_asymptotic(self):
+        # Test alternative parameter, asymptotic method (due to tie)
+
+        # Based on TestCorrSpearman2::test_alternative
+        x1 = [1, 2, 3, 4, 5]
+        x2 = [5, 6, 7, 8, 7]
+
+        # strong positive correlation
+        expected = stats.kendalltau(x1, x2, alternative="two-sided")
+        assert expected[0] > 0
+
+        # rank correlation > 0 -> large "less" p-value
+        res = stats.kendalltau(x1, x2, alternative="less")
+        assert_equal(res[0], expected[0])
+        assert_allclose(res[1], 1 - (expected[1] / 2))
+
+        # rank correlation > 0 -> small "greater" p-value
+        res = stats.kendalltau(x1, x2, alternative="greater")
+        assert_equal(res[0], expected[0])
+        assert_allclose(res[1], expected[1] / 2)
+
+        # reverse the direction of rank correlation
+        x2.reverse()
+
+        # strong negative correlation
+        expected = stats.kendalltau(x1, x2, alternative="two-sided")
+        assert expected[0] < 0
+
+        # rank correlation < 0 -> large "greater" p-value
+        res = stats.kendalltau(x1, x2, alternative="greater")
+        assert_equal(res[0], expected[0])
+        assert_allclose(res[1], 1 - (expected[1] / 2))
+
+        # rank correlation < 0 -> small "less" p-value
+        res = stats.kendalltau(x1, x2, alternative="less")
+        assert_equal(res[0], expected[0])
+        assert_allclose(res[1], expected[1] / 2)
+
+        with pytest.raises(ValueError, match="`alternative` must be 'less'..."):
+            stats.kendalltau(x1, x2, alternative="ekki-ekki")
+
+    # There are a lot of special cases considered in the calculation of the
+    # exact p-value, so we test each separately. We also need to test
+    # separately when the observed statistic is in the left tail vs the right
+    # tail because the code leverages symmetry of the null distribution; to
+    # do that we use the same test case but negate one of the samples.
+    # Reference values computed using R cor.test, e.g.
+    # options(digits=16)
+    # x <- c(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1)
+    # y <- c( 2.6,  3.1,  2.5,  5.0,  3.6,  4.0,  5.2,  2.8,  3.8)
+    # cor.test(x, y, method = "kendall", alternative = "g")
+
+    alternatives = ('less', 'two-sided', 'greater')
+    p_n1 = [np.nan, np.nan, np.nan]
+    p_n2 = [1, 1, 0.5]
+    p_c0 = [1, 0.3333333333333, 0.1666666666667]
+    p_c1 = [0.9583333333333, 0.3333333333333, 0.1666666666667]
+    p_no_correlation = [0.5916666666667, 1, 0.5916666666667]
+    p_no_correlationb = [0.5475694444444, 1, 0.5475694444444]
+    p_n_lt_171 = [0.9624118165785, 0.1194389329806, 0.0597194664903]
+    p_n_lt_171b = [0.246236925303, 0.4924738506059, 0.755634083327]
+    p_n_lt_171c = [0.9847475308925, 0.03071385306533, 0.01535692653267]
+
+    def exact_test(self, x, y, alternative, rev, stat_expected, p_expected):
+        if rev:
+            y = -np.asarray(y)
+            stat_expected *= -1
+        res = stats.kendalltau(x, y, method='exact', alternative=alternative)
+        res_expected = stat_expected, p_expected
+        assert_allclose(res, res_expected)
+
+    case_R_n1 = (list(zip(alternatives, p_n1, [False]*3))
+                 + list(zip(alternatives, reversed(p_n1), [True]*3)))
+
+    @pytest.mark.parametrize("alternative, p_expected, rev", case_R_n1)
+    def test_against_R_n1(self, alternative, p_expected, rev):
+        x, y = [1], [2]
+        stat_expected = np.nan
+        self.exact_test(x, y, alternative, rev, stat_expected, p_expected)
+
+    case_R_n2 = (list(zip(alternatives, p_n2, [False]*3))
+                 + list(zip(alternatives, reversed(p_n2), [True]*3)))
+
+    @pytest.mark.parametrize("alternative, p_expected, rev", case_R_n2)
+    def test_against_R_n2(self, alternative, p_expected, rev):
+        x, y = [1, 2], [3, 4]
+        stat_expected = 0.9999999999999998
+        self.exact_test(x, y, alternative, rev, stat_expected, p_expected)
+
+    case_R_c0 = (list(zip(alternatives, p_c0, [False]*3))
+                 + list(zip(alternatives, reversed(p_c0), [True]*3)))
+
+    @pytest.mark.parametrize("alternative, p_expected, rev", case_R_c0)
+    def test_against_R_c0(self, alternative, p_expected, rev):
+        x, y = [1, 2, 3], [1, 2, 3]
+        stat_expected = 1
+        self.exact_test(x, y, alternative, rev, stat_expected, p_expected)
+
+    case_R_c1 = (list(zip(alternatives, p_c1, [False]*3))
+                 + list(zip(alternatives, reversed(p_c1), [True]*3)))
+
+    @pytest.mark.parametrize("alternative, p_expected, rev", case_R_c1)
+    def test_against_R_c1(self, alternative, p_expected, rev):
+        x, y = [1, 2, 3, 4], [1, 2, 4, 3]
+        stat_expected = 0.6666666666666667
+        self.exact_test(x, y, alternative, rev, stat_expected, p_expected)
+
+    case_R_no_corr = (list(zip(alternatives, p_no_correlation, [False]*3))
+                      + list(zip(alternatives, reversed(p_no_correlation),
+                                 [True]*3)))
+
+    @pytest.mark.parametrize("alternative, p_expected, rev", case_R_no_corr)
+    def test_against_R_no_correlation(self, alternative, p_expected, rev):
+        x, y = [1, 2, 3, 4, 5], [1, 5, 4, 2, 3]
+        stat_expected = 0
+        self.exact_test(x, y, alternative, rev, stat_expected, p_expected)
+
+    case_no_cor_b = (list(zip(alternatives, p_no_correlationb, [False]*3))
+                     + list(zip(alternatives, reversed(p_no_correlationb),
+                                [True]*3)))
+
+    @pytest.mark.parametrize("alternative, p_expected, rev", case_no_cor_b)
+    def test_against_R_no_correlationb(self, alternative, p_expected, rev):
+        x, y = [1, 2, 3, 4, 5, 6, 7, 8], [8, 6, 1, 3, 2, 5, 4, 7]
+        stat_expected = 0
+        self.exact_test(x, y, alternative, rev, stat_expected, p_expected)
+
+    case_R_lt_171 = (list(zip(alternatives, p_n_lt_171, [False]*3))
+                     + list(zip(alternatives, reversed(p_n_lt_171), [True]*3)))
+
+    @pytest.mark.parametrize("alternative, p_expected, rev", case_R_lt_171)
+    def test_against_R_lt_171(self, alternative, p_expected, rev):
+        # Data from Hollander & Wolfe (1973), p. 187f.
+        # Used from https://rdrr.io/r/stats/cor.test.html
+        x = [44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1]
+        y = [2.6, 3.1, 2.5, 5.0, 3.6, 4.0, 5.2, 2.8, 3.8]
+        stat_expected = 0.4444444444444445
+        self.exact_test(x, y, alternative, rev, stat_expected, p_expected)
+
+    case_R_lt_171b = (list(zip(alternatives, p_n_lt_171b, [False]*3))
+                      + list(zip(alternatives, reversed(p_n_lt_171b),
+                                 [True]*3)))
+
+    @pytest.mark.parametrize("alternative, p_expected, rev", case_R_lt_171b)
+    def test_against_R_lt_171b(self, alternative, p_expected, rev):
+        np.random.seed(0)
+        x = np.random.rand(100)
+        y = np.random.rand(100)
+        stat_expected = -0.04686868686868687
+        self.exact_test(x, y, alternative, rev, stat_expected, p_expected)
+
+    case_R_lt_171c = (list(zip(alternatives, p_n_lt_171c, [False]*3))
+                      + list(zip(alternatives, reversed(p_n_lt_171c),
+                                 [True]*3)))
+
+    @pytest.mark.parametrize("alternative, p_expected, rev", case_R_lt_171c)
+    def test_against_R_lt_171c(self, alternative, p_expected, rev):
+        np.random.seed(0)
+        x = np.random.rand(170)
+        y = np.random.rand(170)
+        stat_expected = 0.1115906717716673
+        self.exact_test(x, y, alternative, rev, stat_expected, p_expected)
+
+    case_gt_171 = (list(zip(alternatives, [False]*3)) +
+                   list(zip(alternatives, [True]*3)))
+
+    @pytest.mark.parametrize("alternative, rev", case_gt_171)
+    def test_gt_171(self, alternative, rev):
+        np.random.seed(0)
+        x = np.random.rand(400)
+        y = np.random.rand(400)
+        res0 = stats.kendalltau(x, y, method='exact',
+                                alternative=alternative)
+        res1 = stats.kendalltau(x, y, method='asymptotic',
+                                alternative=alternative)
+        assert_equal(res0[0], res1[0])
+        assert_allclose(res0[1], res1[1], rtol=1e-3)
+
+    @pytest.mark.parametrize("method", ('exact', 'asymptotic'))
+    @pytest.mark.parametrize("alternative", ('two-sided', 'less', 'greater'))
+    def test_nan_policy(self, method, alternative):
+        # Test nan policies
+        x1 = [1, 2, 3, 4, 5]
+        x2 = [5, 6, 7, 8, 9]
+        x1nan = x1 + [np.nan]
+        x2nan = x2 + [np.nan]
+
+        # test nan_policy="propagate"
+        res_actual = stats.kendalltau(x1nan, x2nan,
+                                      method=method, alternative=alternative)
+        res_expected = (np.nan, np.nan)
+        assert_allclose(res_actual, res_expected)
+
+        # test nan_policy="omit"
+        res_actual = stats.kendalltau(x1nan, x2nan, nan_policy='omit',
+                                      method=method, alternative=alternative)
+        res_expected = stats.kendalltau(x1, x2, method=method,
+                                        alternative=alternative)
+        assert_allclose(res_actual, res_expected)
+
+        # test nan_policy="raise"
+        message = 'The input contains nan values'
+        with pytest.raises(ValueError, match=message):
+            stats.kendalltau(x1nan, x2nan, nan_policy='raise',
+                             method=method, alternative=alternative)
+
+        # test invalid nan_policy
+        message = "nan_policy must be one of..."
+        with pytest.raises(ValueError, match=message):
+            stats.kendalltau(x1nan, x2nan, nan_policy='ekki-ekki',
+                             method=method, alternative=alternative)
+
+
+def test_weightedtau():
+    x = [12, 2, 1, 12, 2]
+    y = [1, 4, 7, 1, 0]
+    tau, p_value = stats.weightedtau(x, y)
+    assert_approx_equal(tau, -0.56694968153682723)
+    assert_equal(np.nan, p_value)
+    tau, p_value = stats.weightedtau(x, y, additive=False)
+    assert_approx_equal(tau, -0.62205716951801038)
+    assert_equal(np.nan, p_value)
+    # This must be exactly Kendall's tau
+    tau, p_value = stats.weightedtau(x, y, weigher=lambda x: 1)
+    assert_approx_equal(tau, -0.47140452079103173)
+    assert_equal(np.nan, p_value)
+
+    # test for namedtuple attribute results
+    res = stats.weightedtau(x, y)
+    attributes = ('correlation', 'pvalue')
+    check_named_results(res, attributes)
+    assert_equal(res.correlation, res.statistic)
+
+    # Asymmetric, ranked version
+    tau, p_value = stats.weightedtau(x, y, rank=None)
+    assert_approx_equal(tau, -0.4157652301037516)
+    assert_equal(np.nan, p_value)
+    tau, p_value = stats.weightedtau(y, x, rank=None)
+    assert_approx_equal(tau, -0.7181341329699029)
+    assert_equal(np.nan, p_value)
+    tau, p_value = stats.weightedtau(x, y, rank=None, additive=False)
+    assert_approx_equal(tau, -0.40644850966246893)
+    assert_equal(np.nan, p_value)
+    tau, p_value = stats.weightedtau(y, x, rank=None, additive=False)
+    assert_approx_equal(tau, -0.83766582937355172)
+    assert_equal(np.nan, p_value)
+    tau, p_value = stats.weightedtau(x, y, rank=False)
+    assert_approx_equal(tau, -0.51604397940261848)
+    assert_equal(np.nan, p_value)
+    # This must be exactly Kendall's tau
+    tau, p_value = stats.weightedtau(x, y, rank=True, weigher=lambda x: 1)
+    assert_approx_equal(tau, -0.47140452079103173)
+    assert_equal(np.nan, p_value)
+    tau, p_value = stats.weightedtau(y, x, rank=True, weigher=lambda x: 1)
+    assert_approx_equal(tau, -0.47140452079103173)
+    assert_equal(np.nan, p_value)
+    # Test argument conversion
+    tau, p_value = stats.weightedtau(np.asarray(x, dtype=np.float64), y)
+    assert_approx_equal(tau, -0.56694968153682723)
+    tau, p_value = stats.weightedtau(np.asarray(x, dtype=np.int16), y)
+    assert_approx_equal(tau, -0.56694968153682723)
+    tau, p_value = stats.weightedtau(np.asarray(x, dtype=np.float64),
+                                     np.asarray(y, dtype=np.float64))
+    assert_approx_equal(tau, -0.56694968153682723)
+    # All ties
+    tau, p_value = stats.weightedtau([], [])
+    assert_equal(np.nan, tau)
+    assert_equal(np.nan, p_value)
+    tau, p_value = stats.weightedtau([0], [0])
+    assert_equal(np.nan, tau)
+    assert_equal(np.nan, p_value)
+    # Size mismatches
+    assert_raises(ValueError, stats.weightedtau, [0, 1], [0, 1, 2])
+    assert_raises(ValueError, stats.weightedtau, [0, 1], [0, 1], [0])
+    # NaNs
+    x = [12, 2, 1, 12, 2]
+    y = [1, 4, 7, 1, np.nan]
+    tau, p_value = stats.weightedtau(x, y)
+    assert_approx_equal(tau, -0.56694968153682723)
+    x = [12, 2, np.nan, 12, 2]
+    tau, p_value = stats.weightedtau(x, y)
+    assert_approx_equal(tau, -0.56694968153682723)
+    # NaNs when the dtype of x and y are all np.float64
+    x = [12.0, 2.0, 1.0, 12.0, 2.0]
+    y = [1.0, 4.0, 7.0, 1.0, np.nan]
+    tau, p_value = stats.weightedtau(x, y)
+    assert_approx_equal(tau, -0.56694968153682723)
+    x = [12.0, 2.0, np.nan, 12.0, 2.0]
+    tau, p_value = stats.weightedtau(x, y)
+    assert_approx_equal(tau, -0.56694968153682723)
+    # NaNs when there are more than one NaN in x or y
+    x = [12.0, 2.0, 1.0, 12.0, 1.0]
+    y = [1.0, 4.0, 7.0, 1.0, 1.0]
+    tau, p_value = stats.weightedtau(x, y)
+    assert_approx_equal(tau, -0.6615242347139803)
+    x = [12.0, 2.0, np.nan, 12.0, np.nan]
+    tau, p_value = stats.weightedtau(x, y)
+    assert_approx_equal(tau, -0.6615242347139803)
+    y = [np.nan, 4.0, 7.0, np.nan, np.nan]
+    tau, p_value = stats.weightedtau(x, y)
+    assert_approx_equal(tau, -0.6615242347139803)
+
+
+def test_segfault_issue_9710():
+    # https://github.com/scipy/scipy/issues/9710
+    # This test was created to check segfault
+    # In issue SEGFAULT only repros in optimized builds after calling the function twice
+    stats.weightedtau([1], [1.0])
+    stats.weightedtau([1], [1.0])
+    # The code below also caused SEGFAULT
+    stats.weightedtau([np.nan], [52])
+
+
+def test_kendall_tau_large():
+    n = 172
+    # Test omit policy
+    x = np.arange(n + 1).astype(float)
+    y = np.arange(n + 1).astype(float)
+    y[-1] = np.nan
+    _, pval = stats.kendalltau(x, y, method='exact', nan_policy='omit')
+    assert_equal(pval, 0.0)
+
+
+def test_weightedtau_vs_quadratic():
+    # Trivial quadratic implementation, all parameters mandatory
+    def wkq(x, y, rank, weigher, add):
+        tot = conc = disc = u = v = 0
+        for (i, j) in product(range(len(x)), range(len(x))):
+            w = weigher(rank[i]) + weigher(rank[j]) if add \
+                else weigher(rank[i]) * weigher(rank[j])
+            tot += w
+            if x[i] == x[j]:
+                u += w
+            if y[i] == y[j]:
+                v += w
+            if x[i] < x[j] and y[i] < y[j] or x[i] > x[j] and y[i] > y[j]:
+                conc += w
+            elif x[i] < x[j] and y[i] > y[j] or x[i] > x[j] and y[i] < y[j]:
+                disc += w
+        return (conc - disc) / np.sqrt(tot - u) / np.sqrt(tot - v)
+
+    def weigher(x):
+        return 1. / (x + 1)
+
+    np.random.seed(42)
+    for s in range(3,10):
+        a = []
+        # Generate rankings with ties
+        for i in range(s):
+            a += [i]*i
+        b = list(a)
+        np.random.shuffle(a)
+        np.random.shuffle(b)
+        # First pass: use element indices as ranks
+        rank = np.arange(len(a), dtype=np.intp)
+        for _ in range(2):
+            for add in [True, False]:
+                expected = wkq(a, b, rank, weigher, add)
+                actual = stats.weightedtau(a, b, rank, weigher, add).statistic
+                assert_approx_equal(expected, actual)
+            # Second pass: use a random rank
+            np.random.shuffle(rank)
+
+
+class TestFindRepeats:
+
+    def test_basic(self):
+        a = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 5]
+        message = "`scipy.stats.find_repeats` is deprecated..."
+        with pytest.deprecated_call(match=message):
+            res, nums = stats.find_repeats(a)
+        assert_array_equal(res, [1, 2, 3, 4])
+        assert_array_equal(nums, [3, 3, 2, 2])
+
+    def test_empty_result(self):
+        # Check that empty arrays are returned when there are no repeats.
+        for a in [[10, 20, 50, 30, 40], []]:
+            message = "`scipy.stats.find_repeats` is deprecated..."
+            with pytest.deprecated_call(match=message):
+                repeated, counts = stats.find_repeats(a)
+            assert_array_equal(repeated, [])
+            assert_array_equal(counts, [])
+
+
+class TestRegression:
+
+    def test_one_arg_deprecation(self):
+        x = np.arange(20).reshape((2, 10))
+        message = "Inference of the two sets..."
+        with pytest.deprecated_call(match=message):
+            stats.linregress(x)
+        stats.linregress(x[0], x[1])
+
+    def test_linregressBIGX(self):
+        # W.II.F.  Regress BIG on X.
+        result = stats.linregress(X, BIG)
+        assert_almost_equal(result.intercept, 99999990)
+        assert_almost_equal(result.rvalue, 1.0)
+        # The uncertainty ought to be almost zero
+        # since all points lie on a line
+        assert_almost_equal(result.stderr, 0.0)
+        assert_almost_equal(result.intercept_stderr, 0.0)
+
+    def test_regressXX(self):
+        # W.IV.B.  Regress X on X.
+        # The constant should be exactly 0 and the regression coefficient
+        # should be 1.  This is a perfectly valid regression and the
+        # program should not complain.
+        result = stats.linregress(X, X)
+        assert_almost_equal(result.intercept, 0.0)
+        assert_almost_equal(result.rvalue, 1.0)
+        # The uncertainly on regression through two points ought to be 0
+        assert_almost_equal(result.stderr, 0.0)
+        assert_almost_equal(result.intercept_stderr, 0.0)
+
+        # W.IV.C. Regress X on BIG and LITTLE (two predictors).  The program
+        # should tell you that this model is "singular" because BIG and
+        # LITTLE are linear combinations of each other.  Cryptic error
+        # messages are unacceptable here.  Singularity is the most
+        # fundamental regression error.
+        #
+        # Need to figure out how to handle multiple linear regression.
+        # This is not obvious
+
+    def test_regressZEROX(self):
+        # W.IV.D. Regress ZERO on X.
+        # The program should inform you that ZERO has no variance or it should
+        # go ahead and compute the regression and report a correlation and
+        # total sum of squares of exactly 0.
+        result = stats.linregress(X, ZERO)
+        assert_almost_equal(result.intercept, 0.0)
+        assert_almost_equal(result.rvalue, 0.0)
+
+    def test_regress_simple(self):
+        # Regress a line with sinusoidal noise.
+        x = np.linspace(0, 100, 100)
+        y = 0.2 * np.linspace(0, 100, 100) + 10
+        y += np.sin(np.linspace(0, 20, 100))
+
+        result = stats.linregress(x, y)
+        lr = LinregressResult
+        assert_(isinstance(result, lr))
+        assert_almost_equal(result.stderr, 2.3957814497838803e-3)
+
+    def test_regress_alternative(self):
+        # test alternative parameter
+        x = np.linspace(0, 100, 100)
+        y = 0.2 * np.linspace(0, 100, 100) + 10  # slope is greater than zero
+        y += np.sin(np.linspace(0, 20, 100))
+
+        with pytest.raises(ValueError, match="`alternative` must be 'less'..."):
+            stats.linregress(x, y, alternative="ekki-ekki")
+
+        res1 = stats.linregress(x, y, alternative="two-sided")
+
+        # slope is greater than zero, so "less" p-value should be large
+        res2 = stats.linregress(x, y, alternative="less")
+        assert_allclose(res2.pvalue, 1 - (res1.pvalue / 2))
+
+        # slope is greater than zero, so "greater" p-value should be small
+        res3 = stats.linregress(x, y, alternative="greater")
+        assert_allclose(res3.pvalue, res1.pvalue / 2)
+
+        assert res1.rvalue == res2.rvalue == res3.rvalue
+
+    def test_regress_against_R(self):
+        # test against R `lm`
+        # options(digits=16)
+        # x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
+        # y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
+        # relation <- lm(y~x)
+        # print(summary(relation))
+
+        x = [151, 174, 138, 186, 128, 136, 179, 163, 152, 131]
+        y = [63, 81, 56, 91, 47, 57, 76, 72, 62, 48]
+        res = stats.linregress(x, y, alternative="two-sided")
+        # expected values from R's `lm` above
+        assert_allclose(res.slope, 0.6746104491292)
+        assert_allclose(res.intercept, -38.4550870760770)
+        assert_allclose(res.rvalue, np.sqrt(0.95478224775))
+        assert_allclose(res.pvalue, 1.16440531074e-06)
+        assert_allclose(res.stderr, 0.0519051424731)
+        assert_allclose(res.intercept_stderr, 8.0490133029927)
+
+    # TODO: remove this test once single-arg support is dropped;
+    # deprecation warning tested in `test_one_arg_deprecation`
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_regress_simple_onearg_rows(self):
+        # Regress a line w sinusoidal noise,
+        # with a single input of shape (2, N)
+        x = np.linspace(0, 100, 100)
+        y = 0.2 * np.linspace(0, 100, 100) + 10
+        y += np.sin(np.linspace(0, 20, 100))
+        rows = np.vstack((x, y))
+
+        result = stats.linregress(rows)
+        assert_almost_equal(result.stderr, 2.3957814497838803e-3)
+        assert_almost_equal(result.intercept_stderr, 1.3866936078570702e-1)
+
+    # TODO: remove this test once single-arg support is dropped;
+    # deprecation warning tested in `test_one_arg_deprecation`
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_regress_simple_onearg_cols(self):
+        x = np.linspace(0, 100, 100)
+        y = 0.2 * np.linspace(0, 100, 100) + 10
+        y += np.sin(np.linspace(0, 20, 100))
+        columns = np.hstack((np.expand_dims(x, 1), np.expand_dims(y, 1)))
+
+        result = stats.linregress(columns)
+        assert_almost_equal(result.stderr, 2.3957814497838803e-3)
+        assert_almost_equal(result.intercept_stderr, 1.3866936078570702e-1)
+
+    # TODO: remove this test once single-arg support is dropped;
+    # deprecation warning tested in `test_one_arg_deprecation`
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_regress_shape_error(self):
+        # Check that a single input argument to linregress with wrong shape
+        # results in a ValueError.
+        assert_raises(ValueError, stats.linregress, np.ones((3, 3)))
+
+    def test_linregress(self):
+        # compared with multivariate ols with pinv
+        x = np.arange(11)
+        y = np.arange(5, 16)
+        y[[(1), (-2)]] -= 1
+        y[[(0), (-1)]] += 1
+
+        result = stats.linregress(x, y)
+
+        # This test used to use 'assert_array_almost_equal' but its
+        # formulation got confusing since LinregressResult became
+        # _lib._bunch._make_tuple_bunch instead of namedtuple
+        # (for backwards compatibility, see PR #12983)
+        def assert_ae(x, y):
+            return assert_almost_equal(x, y, decimal=14)
+        assert_ae(result.slope, 1.0)
+        assert_ae(result.intercept, 5.0)
+        assert_ae(result.rvalue, 0.98229948625750)
+        assert_ae(result.pvalue, 7.45259691e-008)
+        assert_ae(result.stderr, 0.063564172616372733)
+        assert_ae(result.intercept_stderr, 0.37605071654517686)
+
+    def test_regress_simple_negative_cor(self):
+        # If the slope of the regression is negative the factor R tend
+        # to -1 not 1.  Sometimes rounding errors makes it < -1
+        # leading to stderr being NaN.
+        a, n = 1e-71, 100000
+        x = np.linspace(a, 2 * a, n)
+        y = np.linspace(2 * a, a, n)
+        result = stats.linregress(x, y)
+
+        # Make sure propagated numerical errors
+        # did not bring rvalue below -1 (or were coerced)
+        assert_(result.rvalue >= -1)
+        assert_almost_equal(result.rvalue, -1)
+
+        # slope and intercept stderror should stay numeric
+        assert_(not np.isnan(result.stderr))
+        assert_(not np.isnan(result.intercept_stderr))
+
+    def test_linregress_result_attributes(self):
+        x = np.linspace(0, 100, 100)
+        y = 0.2 * np.linspace(0, 100, 100) + 10
+        y += np.sin(np.linspace(0, 20, 100))
+        result = stats.linregress(x, y)
+
+        # Result is of a correct class
+        lr = LinregressResult
+        assert_(isinstance(result, lr))
+
+        # LinregressResult elements have correct names
+        attributes = ('slope', 'intercept', 'rvalue', 'pvalue', 'stderr')
+        check_named_results(result, attributes)
+        # Also check that the extra attribute (intercept_stderr) is present
+        assert 'intercept_stderr' in dir(result)
+
+    def test_regress_two_inputs(self):
+        # Regress a simple line formed by two points.
+        x = np.arange(2)
+        y = np.arange(3, 5)
+        result = stats.linregress(x, y)
+
+        # Non-horizontal line
+        assert_almost_equal(result.pvalue, 0.0)
+
+        # Zero error through two points
+        assert_almost_equal(result.stderr, 0.0)
+        assert_almost_equal(result.intercept_stderr, 0.0)
+
+    def test_regress_two_inputs_horizontal_line(self):
+        # Regress a horizontal line formed by two points.
+        x = np.arange(2)
+        y = np.ones(2)
+        result = stats.linregress(x, y)
+
+        # Horizontal line
+        assert_almost_equal(result.pvalue, 1.0)
+
+        # Zero error through two points
+        assert_almost_equal(result.stderr, 0.0)
+        assert_almost_equal(result.intercept_stderr, 0.0)
+
+    def test_nist_norris(self):
+        # If this causes a lint failure in the future, please note the history of
+        # requests to allow extra whitespace in table formatting (e.g. gh-12367).
+        # Also see https://github.com/scipy/scipy/wiki/Why-do-we-not-use-an-auto%E2%80%90formatter%3F  # noqa: E501 
+        x = [  0.2, 337.4, 118.2, 884.6, 10.1,  226.5,
+             666.3, 996.3, 448.6, 777.0, 558.2,   0.4,
+               0.6, 775.5, 666.9, 338.0, 447.5,  11.6,
+             556.0, 228.1, 995.8, 887.6, 120.2,   0.3,
+               0.3, 556.8, 339.1, 887.2, 999.0, 779.0,
+              11.1, 118.3, 229.2, 669.1, 448.9,   0.5]
+
+        y = [  0.1, 338.8, 118.1, 888.0, 9.2,   228.1,
+             668.5, 998.5, 449.1, 778.9, 559.2,   0.3,
+               0.1, 778.1, 668.8, 339.3, 448.9,  10.8,
+             557.7, 228.3, 998.0, 888.8, 119.6,   0.3,
+               0.6, 557.6, 339.3, 888.0, 998.5, 778.9,
+              10.2, 117.6, 228.9, 668.4, 449.2,   0.2]
+
+        result = stats.linregress(x, y)
+
+        assert_almost_equal(result.slope, 1.00211681802045)
+        assert_almost_equal(result.intercept, -0.262323073774029)
+        assert_almost_equal(result.rvalue**2, 0.999993745883712)
+        assert_almost_equal(result.pvalue, 0.0)
+        assert_almost_equal(result.stderr, 0.00042979684820)
+        assert_almost_equal(result.intercept_stderr, 0.23281823430153)
+
+    def test_compare_to_polyfit(self):
+        x = np.linspace(0, 100, 100)
+        y = 0.2 * np.linspace(0, 100, 100) + 10
+        y += np.sin(np.linspace(0, 20, 100))
+        result = stats.linregress(x, y)
+        poly = np.polyfit(x, y, 1)  # Fit 1st degree polynomial
+
+        # Make sure linear regression slope and intercept
+        # match with results from numpy polyfit
+        assert_almost_equal(result.slope, poly[0])
+        assert_almost_equal(result.intercept, poly[1])
+
+    def test_empty_input(self):
+        assert_raises(ValueError, stats.linregress, [], [])
+
+    def test_nan_input(self):
+        x = np.arange(10.)
+        x[9] = np.nan
+
+        with np.errstate(invalid="ignore"):
+            result = stats.linregress(x, x)
+
+        # Make sure the result still comes back as `LinregressResult`
+        lr = LinregressResult
+        assert_(isinstance(result, lr))
+        assert_array_equal(result, (np.nan,)*5)
+        assert_equal(result.intercept_stderr, np.nan)
+
+    def test_identical_x(self):
+        x = np.zeros(10)
+        y = np.random.random(10)
+        msg = "Cannot calculate a linear regression"
+        with assert_raises(ValueError, match=msg):
+            stats.linregress(x, y)
+
+
+def test_theilslopes():
+    # Basic slope test.
+    slope, intercept, lower, upper = stats.theilslopes([0,1,1])
+    assert_almost_equal(slope, 0.5)
+    assert_almost_equal(intercept, 0.5)
+
+    msg = ("method must be either 'joint' or 'separate'."
+           "'joint_separate' is invalid.")
+    with pytest.raises(ValueError, match=msg):
+        stats.theilslopes([0, 1, 1], method='joint_separate')
+
+    slope, intercept, lower, upper = stats.theilslopes([0, 1, 1],
+                                                       method='joint')
+    assert_almost_equal(slope, 0.5)
+    assert_almost_equal(intercept, 0.0)
+
+    # Test of confidence intervals.
+    x = [1, 2, 3, 4, 10, 12, 18]
+    y = [9, 15, 19, 20, 45, 55, 78]
+    slope, intercept, lower, upper = stats.theilslopes(y, x, 0.07,
+                                                       method='separate')
+    assert_almost_equal(slope, 4)
+    assert_almost_equal(intercept, 4.0)
+    assert_almost_equal(upper, 4.38, decimal=2)
+    assert_almost_equal(lower, 3.71, decimal=2)
+
+    slope, intercept, lower, upper = stats.theilslopes(y, x, 0.07,
+                                                       method='joint')
+    assert_almost_equal(slope, 4)
+    assert_almost_equal(intercept, 6.0)
+    assert_almost_equal(upper, 4.38, decimal=2)
+    assert_almost_equal(lower, 3.71, decimal=2)
+
+
+def test_cumfreq():
+    x = [1, 4, 2, 1, 3, 1]
+    cumfreqs, lowlim, binsize, extrapoints = stats.cumfreq(x, numbins=4)
+    assert_array_almost_equal(cumfreqs, np.array([3., 4., 5., 6.]))
+    cumfreqs, lowlim, binsize, extrapoints = stats.cumfreq(
+        x, numbins=4, defaultreallimits=(1.5, 5))
+    assert_(extrapoints == 3)
+
+    # test for namedtuple attribute results
+    attributes = ('cumcount', 'lowerlimit', 'binsize', 'extrapoints')
+    res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5))
+    check_named_results(res, attributes)
+
+
+def test_relfreq():
+    a = np.array([1, 4, 2, 1, 3, 1])
+    relfreqs, lowlim, binsize, extrapoints = stats.relfreq(a, numbins=4)
+    assert_array_almost_equal(relfreqs,
+                              array([0.5, 0.16666667, 0.16666667, 0.16666667]))
+
+    # test for namedtuple attribute results
+    attributes = ('frequency', 'lowerlimit', 'binsize', 'extrapoints')
+    res = stats.relfreq(a, numbins=4)
+    check_named_results(res, attributes)
+
+    # check array_like input is accepted
+    relfreqs2, lowlim, binsize, extrapoints = stats.relfreq([1, 4, 2, 1, 3, 1],
+                                                            numbins=4)
+    assert_array_almost_equal(relfreqs, relfreqs2)
+
+
+class TestScoreatpercentile:
+    def setup_method(self):
+        self.a1 = [3, 4, 5, 10, -3, -5, 6]
+        self.a2 = [3, -6, -2, 8, 7, 4, 2, 1]
+        self.a3 = [3., 4, 5, 10, -3, -5, -6, 7.0]
+
+    def test_basic(self):
+        x = arange(8) * 0.5
+        assert_equal(stats.scoreatpercentile(x, 0), 0.)
+        assert_equal(stats.scoreatpercentile(x, 100), 3.5)
+        assert_equal(stats.scoreatpercentile(x, 50), 1.75)
+
+    def test_fraction(self):
+        scoreatperc = stats.scoreatpercentile
+
+        # Test defaults
+        assert_equal(scoreatperc(list(range(10)), 50), 4.5)
+        assert_equal(scoreatperc(list(range(10)), 50, (2,7)), 4.5)
+        assert_equal(scoreatperc(list(range(100)), 50, limit=(1, 8)), 4.5)
+        assert_equal(scoreatperc(np.array([1, 10,100]), 50, (10,100)), 55)
+        assert_equal(scoreatperc(np.array([1, 10,100]), 50, (1,10)), 5.5)
+
+        # explicitly specify interpolation_method 'fraction' (the default)
+        assert_equal(scoreatperc(list(range(10)), 50, interpolation_method='fraction'),
+                     4.5)
+        assert_equal(scoreatperc(list(range(10)), 50, limit=(2, 7),
+                                 interpolation_method='fraction'),
+                     4.5)
+        assert_equal(scoreatperc(list(range(100)), 50, limit=(1, 8),
+                                 interpolation_method='fraction'),
+                     4.5)
+        assert_equal(scoreatperc(np.array([1, 10,100]), 50, (10, 100),
+                                 interpolation_method='fraction'),
+                     55)
+        assert_equal(scoreatperc(np.array([1, 10,100]), 50, (1,10),
+                                 interpolation_method='fraction'),
+                     5.5)
+
+    def test_lower_higher(self):
+        scoreatperc = stats.scoreatpercentile
+
+        # interpolation_method 'lower'/'higher'
+        assert_equal(scoreatperc(list(range(10)), 50,
+                                 interpolation_method='lower'), 4)
+        assert_equal(scoreatperc(list(range(10)), 50,
+                                 interpolation_method='higher'), 5)
+        assert_equal(scoreatperc(list(range(10)), 50, (2,7),
+                                 interpolation_method='lower'), 4)
+        assert_equal(scoreatperc(list(range(10)), 50, limit=(2,7),
+                                 interpolation_method='higher'), 5)
+        assert_equal(scoreatperc(list(range(100)), 50, (1,8),
+                                 interpolation_method='lower'), 4)
+        assert_equal(scoreatperc(list(range(100)), 50, (1,8),
+                                 interpolation_method='higher'), 5)
+        assert_equal(scoreatperc(np.array([1, 10, 100]), 50, (10, 100),
+                                 interpolation_method='lower'), 10)
+        assert_equal(scoreatperc(np.array([1, 10, 100]), 50, limit=(10, 100),
+                                 interpolation_method='higher'), 100)
+        assert_equal(scoreatperc(np.array([1, 10, 100]), 50, (1, 10),
+                                 interpolation_method='lower'), 1)
+        assert_equal(scoreatperc(np.array([1, 10, 100]), 50, limit=(1, 10),
+                                 interpolation_method='higher'), 10)
+
+    def test_sequence_per(self):
+        x = arange(8) * 0.5
+        expected = np.array([0, 3.5, 1.75])
+        res = stats.scoreatpercentile(x, [0, 100, 50])
+        assert_allclose(res, expected)
+        assert_(isinstance(res, np.ndarray))
+        # Test with ndarray.  Regression test for gh-2861
+        assert_allclose(stats.scoreatpercentile(x, np.array([0, 100, 50])),
+                        expected)
+        # Also test combination of 2-D array, axis not None and array-like per
+        res2 = stats.scoreatpercentile(np.arange(12).reshape((3,4)),
+                                       np.array([0, 1, 100, 100]), axis=1)
+        expected2 = array([[0, 4, 8],
+                           [0.03, 4.03, 8.03],
+                           [3, 7, 11],
+                           [3, 7, 11]])
+        assert_allclose(res2, expected2)
+
+    def test_axis(self):
+        scoreatperc = stats.scoreatpercentile
+        x = arange(12).reshape(3, 4)
+
+        assert_equal(scoreatperc(x, (25, 50, 100)), [2.75, 5.5, 11.0])
+
+        r0 = [[2, 3, 4, 5], [4, 5, 6, 7], [8, 9, 10, 11]]
+        assert_equal(scoreatperc(x, (25, 50, 100), axis=0), r0)
+
+        r1 = [[0.75, 4.75, 8.75], [1.5, 5.5, 9.5], [3, 7, 11]]
+        assert_equal(scoreatperc(x, (25, 50, 100), axis=1), r1)
+
+        x = array([[1, 1, 1],
+                   [1, 1, 1],
+                   [4, 4, 3],
+                   [1, 1, 1],
+                   [1, 1, 1]])
+        score = stats.scoreatpercentile(x, 50)
+        assert_equal(score.shape, ())
+        assert_equal(score, 1.0)
+        score = stats.scoreatpercentile(x, 50, axis=0)
+        assert_equal(score.shape, (3,))
+        assert_equal(score, [1, 1, 1])
+
+    def test_exception(self):
+        assert_raises(ValueError, stats.scoreatpercentile, [1, 2], 56,
+                      interpolation_method='foobar')
+        assert_raises(ValueError, stats.scoreatpercentile, [1], 101)
+        assert_raises(ValueError, stats.scoreatpercentile, [1], -1)
+
+    def test_empty(self):
+        assert_equal(stats.scoreatpercentile([], 50), np.nan)
+        assert_equal(stats.scoreatpercentile(np.array([[], []]), 50), np.nan)
+        assert_equal(stats.scoreatpercentile([], [50, 99]), [np.nan, np.nan])
+
+
+class TestMode:
+
+    def test_empty(self):
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            vals, counts = stats.mode([])
+        assert_equal(vals, np.array([]))
+        assert_equal(counts, np.array([]))
+
+    def test_scalar(self):
+        vals, counts = stats.mode(4.)
+        assert_equal(vals, np.array([4.]))
+        assert_equal(counts, np.array([1]))
+
+    def test_basic(self):
+        data1 = [3, 5, 1, 10, 23, 3, 2, 6, 8, 6, 10, 6]
+        vals = stats.mode(data1)
+        assert_equal(vals[0], 6)
+        assert_equal(vals[1], 3)
+
+    def test_axes(self):
+        data1 = [10, 10, 30, 40]
+        data2 = [10, 10, 10, 10]
+        data3 = [20, 10, 20, 20]
+        data4 = [30, 30, 30, 30]
+        data5 = [40, 30, 30, 30]
+        arr = np.array([data1, data2, data3, data4, data5])
+
+        vals = stats.mode(arr, axis=None, keepdims=True)
+        assert_equal(vals[0], np.array([[30]]))
+        assert_equal(vals[1], np.array([[8]]))
+
+        vals = stats.mode(arr, axis=0, keepdims=True)
+        assert_equal(vals[0], np.array([[10, 10, 30, 30]]))
+        assert_equal(vals[1], np.array([[2, 3, 3, 2]]))
+
+        vals = stats.mode(arr, axis=1, keepdims=True)
+        assert_equal(vals[0], np.array([[10], [10], [20], [30], [30]]))
+        assert_equal(vals[1], np.array([[2], [4], [3], [4], [3]]))
+
+    @pytest.mark.parametrize('axis', np.arange(-4, 0))
+    def test_negative_axes_gh_15375(self, axis):
+        np.random.seed(984213899)
+        a = np.random.rand(10, 11, 12, 13)
+        res0 = stats.mode(a, axis=a.ndim+axis)
+        res1 = stats.mode(a, axis=axis)
+        np.testing.assert_array_equal(res0, res1)
+
+    def test_mode_result_attributes(self):
+        data1 = [3, 5, 1, 10, 23, 3, 2, 6, 8, 6, 10, 6]
+        data2 = []
+        actual = stats.mode(data1)
+        attributes = ('mode', 'count')
+        check_named_results(actual, attributes)
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            actual2 = stats.mode(data2)
+        check_named_results(actual2, attributes)
+
+    def test_mode_nan(self):
+        data1 = [3, np.nan, 5, 1, 10, 23, 3, 2, 6, 8, 6, 10, 6]
+        actual = stats.mode(data1)
+        assert_equal(actual, (6, 3))
+
+        actual = stats.mode(data1, nan_policy='omit')
+        assert_equal(actual, (6, 3))
+        assert_raises(ValueError, stats.mode, data1, nan_policy='raise')
+        assert_raises(ValueError, stats.mode, data1, nan_policy='foobar')
+
+    @pytest.mark.parametrize("data", [
+        [3, 5, 1, 1, 3],
+        [3, np.nan, 5, 1, 1, 3],
+        [3, 5, 1],
+        [3, np.nan, 5, 1],
+    ])
+    @pytest.mark.parametrize('keepdims', [False, True])
+    def test_smallest_equal(self, data, keepdims):
+        result = stats.mode(data, nan_policy='omit', keepdims=keepdims)
+        if keepdims:
+            assert_equal(result[0][0], 1)
+        else:
+            assert_equal(result[0], 1)
+
+    @pytest.mark.parametrize('axis', np.arange(-3, 3))
+    def test_mode_shape_gh_9955(self, axis, dtype=np.float64):
+        rng = np.random.default_rng(984213899)
+        a = rng.uniform(size=(3, 4, 5)).astype(dtype)
+        res = stats.mode(a, axis=axis, keepdims=False)
+        reference_shape = list(a.shape)
+        reference_shape.pop(axis)
+        np.testing.assert_array_equal(res.mode.shape, reference_shape)
+        np.testing.assert_array_equal(res.count.shape, reference_shape)
+
+    def test_nan_policy_propagate_gh_9815(self):
+        # mode should treat np.nan as it would any other object when
+        # nan_policy='propagate'
+        a = [2, np.nan, 1, np.nan]
+        res = stats.mode(a)
+        assert np.isnan(res.mode) and res.count == 2
+
+    def test_keepdims(self):
+        # test empty arrays (handled by `np.mean`)
+        a = np.zeros((1, 2, 3, 0))
+
+        res = stats.mode(a, axis=1, keepdims=False)
+        assert res.mode.shape == res.count.shape == (1, 3, 0)
+
+        res = stats.mode(a, axis=1, keepdims=True)
+        assert res.mode.shape == res.count.shape == (1, 1, 3, 0)
+
+        # test nan_policy='propagate'
+        a = [[1, 3, 3, np.nan], [1, 1, np.nan, 1]]
+
+        res = stats.mode(a, axis=1, keepdims=False)
+        assert_array_equal(res.mode, [3, 1])
+        assert_array_equal(res.count, [2, 3])
+
+        res = stats.mode(a, axis=1, keepdims=True)
+        assert_array_equal(res.mode, [[3], [1]])
+        assert_array_equal(res.count, [[2], [3]])
+
+        a = np.array(a)
+        res = stats.mode(a, axis=None, keepdims=False)
+        ref = stats.mode(a.ravel(), keepdims=False)
+        assert_array_equal(res, ref)
+        assert res.mode.shape == ref.mode.shape == ()
+
+        res = stats.mode(a, axis=None, keepdims=True)
+        ref = stats.mode(a.ravel(), keepdims=True)
+        assert_equal(res.mode.ravel(), ref.mode.ravel())
+        assert res.mode.shape == (1, 1)
+        assert_equal(res.count.ravel(), ref.count.ravel())
+        assert res.count.shape == (1, 1)
+
+        # test nan_policy='omit'
+        a = [[1, np.nan, np.nan, np.nan, 1],
+             [np.nan, np.nan, np.nan, np.nan, 2],
+             [1, 2, np.nan, 5, 5]]
+
+        res = stats.mode(a, axis=1, keepdims=False, nan_policy='omit')
+        assert_array_equal(res.mode, [1, 2, 5])
+        assert_array_equal(res.count, [2, 1, 2])
+
+        res = stats.mode(a, axis=1, keepdims=True, nan_policy='omit')
+        assert_array_equal(res.mode, [[1], [2], [5]])
+        assert_array_equal(res.count, [[2], [1], [2]])
+
+        a = np.array(a)
+        res = stats.mode(a, axis=None, keepdims=False, nan_policy='omit')
+        ref = stats.mode(a.ravel(), keepdims=False, nan_policy='omit')
+        assert_array_equal(res, ref)
+        assert res.mode.shape == ref.mode.shape == ()
+
+        res = stats.mode(a, axis=None, keepdims=True, nan_policy='omit')
+        ref = stats.mode(a.ravel(), keepdims=True, nan_policy='omit')
+        assert_equal(res.mode.ravel(), ref.mode.ravel())
+        assert res.mode.shape == (1, 1)
+        assert_equal(res.count.ravel(), ref.count.ravel())
+        assert res.count.shape == (1, 1)
+
+    @pytest.mark.parametrize("nan_policy", ['propagate', 'omit'])
+    def test_gh16955(self, nan_policy):
+        # Check that bug reported in gh-16955 is resolved
+        shape = (4, 3)
+        data = np.ones(shape)
+        data[0, 0] = np.nan
+        res = stats.mode(a=data, axis=1, keepdims=False, nan_policy=nan_policy)
+        assert_array_equal(res.mode, [1, 1, 1, 1])
+        assert_array_equal(res.count, [2, 3, 3, 3])
+
+        # Test with input from gh-16595. Support for non-numeric input
+        # was deprecated, so check for the appropriate error.
+        my_dtype = np.dtype([('asdf', np.uint8), ('qwer', np.float64, (3,))])
+        test = np.zeros(10, dtype=my_dtype)
+        message = "Argument `a` is not....|An argument has dtype..."
+        with pytest.raises(TypeError, match=message):
+            stats.mode(test, nan_policy=nan_policy)
+
+    def test_gh9955(self):
+        # The behavior of mode with empty slices (whether the input was empty
+        # or all elements were omitted) was inconsistent. Test that this is
+        # resolved: the mode of an empty slice is NaN and the count is zero.
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = stats.mode([])
+        ref = (np.nan, 0)
+        assert_equal(res, ref)
+
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_omit):
+            res = stats.mode([np.nan], nan_policy='omit')
+        assert_equal(res, ref)
+
+        a = [[10., 20., 20.], [np.nan, np.nan, np.nan]]
+        with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
+            res = stats.mode(a, axis=1, nan_policy='omit')
+        ref = ([20, np.nan], [2, 0])
+        assert_equal(res, ref)
+
+        res = stats.mode(a, axis=1, nan_policy='propagate')
+        ref = ([20, np.nan], [2, 3])
+        assert_equal(res, ref)
+
+        z = np.array([[], []])
+        with pytest.warns(SmallSampleWarning, match=too_small_nd_not_omit):
+            res = stats.mode(z, axis=1)
+        ref = ([np.nan, np.nan], [0, 0])
+        assert_equal(res, ref)
+
+    @pytest.mark.filterwarnings('ignore::RuntimeWarning')  # np.mean warns
+    @pytest.mark.parametrize('z', [np.empty((0, 1, 2)), np.empty((1, 1, 2))])
+    def test_gh17214(self, z):
+        if z.size == 0:
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = stats.mode(z, axis=None, keepdims=True)
+        else:
+            res = stats.mode(z, axis=None, keepdims=True)
+        ref = np.mean(z, axis=None, keepdims=True)
+        assert res[0].shape == res[1].shape == ref.shape == (1, 1, 1)
+
+    def test_raise_non_numeric_gh18254(self):
+        message = ("...only boolean and numerical dtypes..." if SCIPY_ARRAY_API
+                   else "Argument `a` is not recognized as numeric.")
+
+        class ArrLike:
+            def __init__(self, x):
+                self._x = x
+
+            def __array__(self, dtype=None, copy=None):
+                return self._x.astype(object)
+
+        with pytest.raises(TypeError, match=message):
+            stats.mode(ArrLike(np.arange(3)))
+        with pytest.raises(TypeError, match=message):
+            stats.mode(np.arange(3, dtype=object))
+
+
+@array_api_compatible
+class TestSEM:
+
+    testcase = [1., 2., 3., 4.]
+    scalar_testcase = 4.
+
+    def test_sem_scalar(self, xp):
+        # This is not in R, so used:
+        #     sqrt(var(testcase)*3/4)/sqrt(3)
+
+        # y = stats.sem(self.shoes[0])
+        # assert_approx_equal(y,0.775177399)
+        scalar_testcase = xp.asarray(self.scalar_testcase)[()]
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                y = stats.sem(scalar_testcase)
+        else:
+            # Other array types can emit a variety of warnings.
+            with np.testing.suppress_warnings() as sup:
+                sup.filter(UserWarning)
+                sup.filter(RuntimeWarning)
+                y = stats.sem(scalar_testcase)
+        assert xp.isnan(y)
+
+    def test_sem(self, xp):
+        testcase = xp.asarray(self.testcase)
+        y = stats.sem(testcase)
+        xp_assert_close(y, xp.asarray(0.6454972244))
+        n = len(self.testcase)
+        xp_assert_close(stats.sem(testcase, ddof=0) * (n/(n-2))**0.5,
+                        stats.sem(testcase, ddof=2))
+
+        x = xp.arange(10.)
+        x = xp.where(x == 9, xp.asarray(xp.nan), x)
+        xp_assert_equal(stats.sem(x), xp.asarray(xp.nan))
+
+    @skip_xp_backends(np_only=True,
+                      reason='`nan_policy` only supports NumPy backend')
+    def test_sem_nan_policy(self, xp):
+        x = np.arange(10.)
+        x[9] = np.nan
+        assert_equal(stats.sem(x, nan_policy='omit'), 0.9128709291752769)
+        assert_raises(ValueError, stats.sem, x, nan_policy='raise')
+        assert_raises(ValueError, stats.sem, x, nan_policy='foobar')
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@skip_xp_backends('jax.numpy', reason="JAX can't do item assignment")
+class TestZmapZscore:
+
+    @pytest.mark.parametrize(
+        'x, y',
+        [([1., 2., 3., 4.], [1., 2., 3., 4.]),
+         ([1., 2., 3.], [0., 1., 2., 3., 4.])]
+    )
+    def test_zmap(self, x, y, xp):
+        # For these simple cases, calculate the expected result directly
+        # by using the formula for the z-score.
+        x, y = xp.asarray(x), xp.asarray(y)
+        xp_test = array_namespace(x, y)  # std needs correction
+        expected = (x - xp.mean(y)) / xp_test.std(y, correction=0)
+        z = stats.zmap(x, y)
+        xp_assert_close(z, expected)
+
+    def test_zmap_axis(self, xp):
+        # Test use of 'axis' keyword in zmap.
+        x = np.array([[0.0, 0.0, 1.0, 1.0],
+                      [1.0, 1.0, 1.0, 2.0],
+                      [2.0, 0.0, 2.0, 0.0]])
+
+        t1 = 1.0/(2.0/3)**0.5
+        t2 = 3.**0.5/3
+        t3 = 2.**0.5
+
+        z0 = stats.zmap(x, x, axis=0)
+        z1 = stats.zmap(x, x, axis=1)
+
+        z0_expected = [[-t1, -t3/2, -t3/2, 0.0],
+                       [0.0, t3, -t3/2, t1],
+                       [t1, -t3/2, t3, -t1]]
+        z1_expected = [[-1.0, -1.0, 1.0, 1.0],
+                       [-t2, -t2, -t2, 3.**0.5],
+                       [1.0, -1.0, 1.0, -1.0]]
+
+        xp_assert_close(z0, z0_expected)
+        xp_assert_close(z1, z1_expected)
+
+    def test_zmap_ddof(self, xp):
+        # Test use of 'ddof' keyword in zmap.
+        x = xp.asarray([[0.0, 0.0, 1.0, 1.0],
+                        [0.0, 1.0, 2.0, 3.0]])
+
+        z = stats.zmap(x, x, axis=1, ddof=1)
+
+        z0_expected = xp.asarray([-0.5, -0.5, 0.5, 0.5])/(1.0/3**0.5)
+        z1_expected = xp.asarray([-1.5, -0.5, 0.5, 1.5])/(5./3)**0.5
+        xp_assert_close(z[0, :], z0_expected)
+        xp_assert_close(z[1, :], z1_expected)
+
+    @pytest.mark.parametrize('ddof', [0, 2])
+    def test_zmap_nan_policy_omit(self, ddof, xp):
+        # nans in `scores` are propagated, regardless of `nan_policy`.
+        # `nan_policy` only affects how nans in `compare` are handled.
+        scores = xp.asarray([-3, -1, 2, np.nan])
+        compare = xp.asarray([-8, -3, 2, 7, 12, np.nan])
+        z = stats.zmap(scores, compare, ddof=ddof, nan_policy='omit')
+        ref = stats.zmap(scores, compare[~xp.isnan(compare)], ddof=ddof)
+        xp_assert_close(z, ref)
+
+    @pytest.mark.parametrize('ddof', [0, 2])
+    def test_zmap_nan_policy_omit_with_axis(self, ddof, xp):
+        scores = xp.reshape(xp.arange(-5.0, 9.0), (2, -1))
+        compare = xp.reshape(xp.linspace(-8, 6, 24), (2, -1))
+        compare[0, 4] = xp.nan
+        compare[0, 6] = xp.nan
+        compare[1, 1] = xp.nan
+        z = stats.zmap(scores, compare, nan_policy='omit', axis=1, ddof=ddof)
+        res0 = stats.zmap(scores[0, :], compare[0, :][~xp.isnan(compare[0, :])],
+                          ddof=ddof)
+        res1 = stats.zmap(scores[1, :], compare[1, :][~xp.isnan(compare[1, :])],
+                          ddof=ddof)
+        expected = xp.stack((res0, res1))
+        xp_assert_close(z, expected)
+
+    def test_zmap_nan_policy_raise(self, xp):
+        scores = xp.asarray([1, 2, 3])
+        compare = xp.asarray([-8, -3, 2, 7, 12, xp.nan])
+        with pytest.raises(ValueError, match='input contains nan'):
+            stats.zmap(scores, compare, nan_policy='raise')
+
+    def test_zscore(self, xp):
+        # not in R, so tested by using:
+        #    (testcase[i] - mean(testcase, axis=0)) / sqrt(var(testcase) * 3/4)
+        y = stats.zscore(xp.asarray([1, 2, 3, 4]))
+        desired = [-1.3416407864999, -0.44721359549996,
+                   0.44721359549996, 1.3416407864999]
+        xp_assert_close(y, xp.asarray(desired))
+
+    def test_zscore_axis(self, xp):
+        # Test use of 'axis' keyword in zscore.
+        x = xp.asarray([[0.0, 0.0, 1.0, 1.0],
+                        [1.0, 1.0, 1.0, 2.0],
+                        [2.0, 0.0, 2.0, 0.0]])
+
+        t1 = 1.0/(2.0/3)**0.5
+        t2 = 3**0.5/3
+        t3 = 2**0.5
+
+        z0 = stats.zscore(x, axis=0)
+        z1 = stats.zscore(x, axis=1)
+
+        z0_expected = [[-t1, -t3/2, -t3/2, 0.0],
+                       [0.0, t3, -t3/2, t1],
+                       [t1, -t3/2, t3, -t1]]
+        z1_expected = [[-1.0, -1.0, 1.0, 1.0],
+                       [-t2, -t2, -t2, 3**0.5],
+                       [1.0, -1.0, 1.0, -1.0]]
+
+        xp_assert_close(z0, xp.asarray(z0_expected))
+        xp_assert_close(z1, xp.asarray(z1_expected))
+
+    def test_zscore_ddof(self, xp):
+        # Test use of 'ddof' keyword in zscore.
+        x = xp.asarray([[0.0, 0.0, 1.0, 1.0],
+                        [0.0, 1.0, 2.0, 3.0]])
+
+        z = stats.zscore(x, axis=1, ddof=1)
+
+        z0_expected = xp.asarray([-0.5, -0.5, 0.5, 0.5])/(1.0/3**0.5)
+        z1_expected = xp.asarray([-1.5, -0.5, 0.5, 1.5])/((5./3)**0.5)
+        xp_assert_close(z[0, :], z0_expected)
+        xp_assert_close(z[1, :], z1_expected)
+
+    @skip_xp_backends('cupy', reason="cupy/cupy#8391")
+    def test_zscore_nan_propagate(self, xp):
+        x = xp.asarray([1, 2, np.nan, 4, 5])
+        z = stats.zscore(x, nan_policy='propagate')
+        xp_assert_equal(z, xp.full(x.shape, xp.nan))
+
+    def test_zscore_nan_omit(self, xp):
+        x = xp.asarray([1, 2, xp.nan, 4, 5])
+
+        z = stats.zscore(x, nan_policy='omit')
+
+        expected = xp.asarray([-1.2649110640673518,
+                               -0.6324555320336759,
+                               xp.nan,
+                               0.6324555320336759,
+                               1.2649110640673518
+                               ])
+        xp_assert_close(z, expected)
+
+    def test_zscore_nan_omit_with_ddof(self, xp):
+        x = xp.asarray([xp.nan, 1.0, 3.0, 5.0, 7.0, 9.0])
+        xp_test = array_namespace(x)  # numpy needs concat
+        z = stats.zscore(x, ddof=1, nan_policy='omit')
+        expected = xp_test.concat([xp.asarray([xp.nan]), stats.zscore(x[1:], ddof=1)])
+        xp_assert_close(z, expected)
+
+    def test_zscore_nan_raise(self, xp):
+        x = xp.asarray([1, 2, xp.nan, 4, 5])
+        with pytest.raises(ValueError, match="The input contains nan..."):
+            stats.zscore(x, nan_policy='raise')
+
+    @skip_xp_backends('cupy', reason="cupy/cupy#8391")
+    def test_zscore_constant_input_1d(self, xp):
+        x = xp.asarray([-0.087] * 3)
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            z = stats.zscore(x)
+        xp_assert_equal(z, xp.full(x.shape, xp.nan))
+
+    def test_zscore_constant_input_2d(self, xp):
+        x = xp.asarray([[10.0, 10.0, 10.0, 10.0],
+                        [10.0, 11.0, 12.0, 13.0]])
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            z0 = stats.zscore(x, axis=0)
+        xp_assert_close(z0, xp.asarray([[xp.nan, -1.0, -1.0, -1.0],
+                                        [xp.nan, 1.0, 1.0, 1.0]]))
+
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            z1 = stats.zscore(x, axis=1)
+        xp_assert_equal(z1, xp.stack([xp.asarray([xp.nan, xp.nan, xp.nan, xp.nan]),
+                                      stats.zscore(x[1, :])]))
+
+        z = stats.zscore(x, axis=None)
+        xp_assert_equal(z, xp.reshape(stats.zscore(xp.reshape(x, (-1,))), x.shape))
+
+        y = xp.ones((3, 6))
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            z = stats.zscore(y, axis=None)
+        xp_assert_equal(z, xp.full(y.shape, xp.asarray(xp.nan)))
+
+    def test_zscore_constant_input_2d_nan_policy_omit(self, xp):
+        x = xp.asarray([[10.0, 10.0, 10.0, 10.0],
+                        [10.0, 11.0, 12.0, xp.nan],
+                        [10.0, 12.0, xp.nan, 10.0]])
+        s = (3/2)**0.5
+        s2 = 2**0.5
+
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            z0 = stats.zscore(x, nan_policy='omit', axis=0)
+        xp_assert_close(z0, xp.asarray([[xp.nan, -s, -1.0, xp.nan],
+                                        [xp.nan, 0, 1.0, xp.nan],
+                                        [xp.nan, s, xp.nan, xp.nan]]))
+
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            z1 = stats.zscore(x, nan_policy='omit', axis=1)
+        xp_assert_close(z1, xp.asarray([[xp.nan, xp.nan, xp.nan, xp.nan],
+                                        [-s, 0, s, xp.nan],
+                                        [-s2/2, s2, xp.nan, -s2/2]]))
+
+    def test_zscore_2d_all_nan_row(self, xp):
+        # A row is all nan, and we use axis=1.
+        x = xp.asarray([[np.nan, np.nan, np.nan, np.nan],
+                        [10.0, 10.0, 12.0, 12.0]])
+        z = stats.zscore(x, nan_policy='omit', axis=1)
+        xp_assert_close(z, xp.asarray([[np.nan, np.nan, np.nan, np.nan],
+                                       [-1.0, -1.0, 1.0, 1.0]]))
+
+    @skip_xp_backends('cupy', reason="cupy/cupy#8391")
+    def test_zscore_2d_all_nan(self, xp):
+        # The entire 2d array is nan, and we use axis=None.
+        y = xp.full((2, 3), xp.nan)
+        z = stats.zscore(y, nan_policy='omit', axis=None)
+        xp_assert_equal(z, y)
+
+    @pytest.mark.parametrize('x', [np.array([]), np.zeros((3, 0, 5))])
+    def test_zscore_empty_input(self, x, xp):
+        x = xp.asarray(x)
+        z = stats.zscore(x)
+        xp_assert_equal(z, x)
+
+    def test_gzscore_normal_array(self, xp):
+        x = np.asarray([1, 2, 3, 4])
+        z = stats.gzscore(xp.asarray(x))
+        desired = np.log(x / stats.gmean(x)) / np.log(stats.gstd(x, ddof=0))
+        xp_assert_close(z, xp.asarray(desired, dtype=xp.asarray(1.).dtype))
+
+    @skip_xp_invalid_arg
+    def test_gzscore_masked_array(self, xp):
+        x = np.array([1, 2, -1, 3, 4])
+        mask = [0, 0, 1, 0, 0]
+        mx = np.ma.masked_array(x, mask=mask)
+        z = stats.gzscore(mx)
+        desired = ([-1.526072095151, -0.194700599824, np.inf, 0.584101799472,
+                    1.136670895503])
+        desired = np.ma.masked_array(desired, mask=mask)
+        assert_allclose(z.compressed(), desired.compressed())
+        assert_allclose(z.mask, desired.mask)
+        assert isinstance(z, np.ma.MaskedArray)
+
+    @skip_xp_invalid_arg
+    def test_zscore_masked_element_0_gh19039(self, xp):
+        # zscore returned all NaNs when 0th element was masked. See gh-19039.
+        rng = np.random.default_rng(8675309)
+        x = rng.standard_normal(10)
+        mask = np.zeros_like(x)
+        y = np.ma.masked_array(x, mask)
+        y.mask[0] = True
+
+        ref = stats.zscore(x[1:])  # compute reference from non-masked elements
+        assert not np.any(np.isnan(ref))
+        res = stats.zscore(y)
+        assert_allclose(res[1:], ref)
+        res = stats.zscore(y, axis=None)
+        assert_allclose(res[1:], ref)
+
+        y[1:] = y[1]  # when non-masked elements are identical, result is nan
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            res = stats.zscore(y)
+        assert_equal(res[1:], np.nan)
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            res = stats.zscore(y, axis=None)
+        assert_equal(res[1:], np.nan)
+
+    def test_degenerate_input(self, xp):
+        scores = xp.arange(3)
+        compare = xp.ones(3)
+        ref = xp.asarray([-xp.inf, xp.nan, xp.inf])
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            res = stats.zmap(scores, compare)
+        xp_assert_equal(res, ref)
+
+    @pytest.mark.skip_xp_backends('array_api_strict', reason='needs array-api#850')
+    def test_complex_gh22404(self, xp):
+        res = stats.zmap(xp.asarray([1, 2, 3, 4]), xp.asarray([1, 1j, -1, -1j]))
+        ref = xp.asarray([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j])
+        xp_assert_close(res, ref)
+
+
+class TestMedianAbsDeviation:
+    def setup_class(self):
+        self.dat_nan = np.array([2.20, 2.20, 2.4, 2.4, 2.5, 2.7, 2.8, 2.9,
+                                 3.03, 3.03, 3.10, 3.37, 3.4, 3.4, 3.4, 3.5,
+                                 3.6, 3.7, 3.7, 3.7, 3.7, 3.77, 5.28, np.nan])
+        self.dat = np.array([2.20, 2.20, 2.4, 2.4, 2.5, 2.7, 2.8, 2.9, 3.03,
+                             3.03, 3.10, 3.37, 3.4, 3.4, 3.4, 3.5, 3.6, 3.7,
+                             3.7, 3.7, 3.7, 3.77, 5.28, 28.95])
+
+    def test_median_abs_deviation(self):
+        assert_almost_equal(stats.median_abs_deviation(self.dat, axis=None),
+                            0.355)
+        dat = self.dat.reshape(6, 4)
+        mad = stats.median_abs_deviation(dat, axis=0)
+        mad_expected = np.asarray([0.435, 0.5, 0.45, 0.4])
+        assert_array_almost_equal(mad, mad_expected)
+
+    def test_mad_nan_omit(self):
+        mad = stats.median_abs_deviation(self.dat_nan, nan_policy='omit')
+        assert_almost_equal(mad, 0.34)
+
+    def test_axis_and_nan(self):
+        x = np.array([[1.0, 2.0, 3.0, 4.0, np.nan],
+                      [1.0, 4.0, 5.0, 8.0, 9.0]])
+        mad = stats.median_abs_deviation(x, axis=1)
+        assert_equal(mad, np.array([np.nan, 3.0]))
+
+    def test_nan_policy_omit_with_inf(self):
+        z = np.array([1, 3, 4, 6, 99, np.nan, np.inf])
+        mad = stats.median_abs_deviation(z, nan_policy='omit')
+        assert_equal(mad, 3.0)
+
+    @pytest.mark.parametrize('axis', [0, 1, 2, None])
+    def test_size_zero_with_axis(self, axis):
+        x = np.zeros((3, 0, 4))
+        mad = stats.median_abs_deviation(x, axis=axis)
+        assert_equal(mad, np.full_like(x.sum(axis=axis), fill_value=np.nan))
+
+    @pytest.mark.parametrize('nan_policy, expected',
+                             [('omit', np.array([np.nan, 1.5, 1.5])),
+                              ('propagate', np.array([np.nan, np.nan, 1.5]))])
+    def test_nan_policy_with_axis(self, nan_policy, expected):
+        x = np.array([[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
+                      [1, 5, 3, 6, np.nan, np.nan],
+                      [5, 6, 7, 9, 9, 10]])
+        mad = stats.median_abs_deviation(x, nan_policy=nan_policy, axis=1)
+        assert_equal(mad, expected)
+
+    @pytest.mark.parametrize('axis, expected',
+                             [(1, [2.5, 2.0, 12.0]), (None, 4.5)])
+    def test_center_mean_with_nan(self, axis, expected):
+        x = np.array([[1, 2, 4, 9, np.nan],
+                      [0, 1, 1, 1, 12],
+                      [-10, -10, -10, 20, 20]])
+        mad = stats.median_abs_deviation(x, center=np.mean, nan_policy='omit',
+                                         axis=axis)
+        assert_allclose(mad, expected, rtol=1e-15, atol=1e-15)
+
+    def test_center_not_callable(self):
+        with pytest.raises(TypeError, match='callable'):
+            stats.median_abs_deviation([1, 2, 3, 5], center=99)
+
+
+def _check_warnings(warn_list, expected_type, expected_len):
+    """
+    Checks that all of the warnings from a list returned by
+    `warnings.catch_all(record=True)` are of the required type and that the list
+    contains expected number of warnings.
+    """
+    assert_equal(len(warn_list), expected_len, "number of warnings")
+    for warn_ in warn_list:
+        assert_(warn_.category is expected_type)
+
+
+class TestIQR:
+
+    def test_basic(self):
+        x = np.arange(8) * 0.5
+        np.random.shuffle(x)
+        assert_equal(stats.iqr(x), 1.75)
+
+    def test_api(self):
+        d = np.ones((5, 5))
+        stats.iqr(d)
+        stats.iqr(d, None)
+        stats.iqr(d, 1)
+        stats.iqr(d, (0, 1))
+        stats.iqr(d, None, (10, 90))
+        stats.iqr(d, None, (30, 20), 1.0)
+        stats.iqr(d, None, (25, 75), 1.5, 'propagate')
+        stats.iqr(d, None, (50, 50), 'normal', 'raise', 'linear')
+        stats.iqr(d, None, (25, 75), -0.4, 'omit', 'lower', True)
+
+    @pytest.mark.parametrize('x', [[], np.arange(0)])
+    def test_empty(self, x):
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            assert_equal(stats.iqr(x), np.nan)
+
+    def test_constant(self):
+        # Constant array always gives 0
+        x = np.ones((7, 4))
+        assert_equal(stats.iqr(x), 0.0)
+        assert_array_equal(stats.iqr(x, axis=0), np.zeros(4))
+        assert_array_equal(stats.iqr(x, axis=1), np.zeros(7))
+        assert_equal(stats.iqr(x, interpolation='linear'), 0.0)
+        assert_equal(stats.iqr(x, interpolation='midpoint'), 0.0)
+        assert_equal(stats.iqr(x, interpolation='nearest'), 0.0)
+        assert_equal(stats.iqr(x, interpolation='lower'), 0.0)
+        assert_equal(stats.iqr(x, interpolation='higher'), 0.0)
+
+        # 0 only along constant dimensions
+        # This also tests much of `axis`
+        y = np.ones((4, 5, 6)) * np.arange(6)
+        assert_array_equal(stats.iqr(y, axis=0), np.zeros((5, 6)))
+        assert_array_equal(stats.iqr(y, axis=1), np.zeros((4, 6)))
+        assert_array_equal(stats.iqr(y, axis=2), np.full((4, 5), 2.5))
+        assert_array_equal(stats.iqr(y, axis=(0, 1)), np.zeros(6))
+        assert_array_equal(stats.iqr(y, axis=(0, 2)), np.full(5, 3.))
+        assert_array_equal(stats.iqr(y, axis=(1, 2)), np.full(4, 3.))
+
+    def test_scalarlike(self):
+        x = np.arange(1) + 7.0
+        assert_equal(stats.iqr(x[0]), 0.0)
+        assert_equal(stats.iqr(x), 0.0)
+        assert_array_equal(stats.iqr(x, keepdims=True), [0.0])
+
+    def test_2D(self):
+        x = np.arange(15).reshape((3, 5))
+        assert_equal(stats.iqr(x), 7.0)
+        assert_array_equal(stats.iqr(x, axis=0), np.full(5, 5.))
+        assert_array_equal(stats.iqr(x, axis=1), np.full(3, 2.))
+        assert_array_equal(stats.iqr(x, axis=(0, 1)), 7.0)
+        assert_array_equal(stats.iqr(x, axis=(1, 0)), 7.0)
+
+    def test_axis(self):
+        # The `axis` keyword is also put through its paces in `test_keepdims`.
+        o = np.random.normal(size=(71, 23))
+        x = np.dstack([o] * 10)                 # x.shape = (71, 23, 10)
+        q = stats.iqr(o)
+
+        assert_equal(stats.iqr(x, axis=(0, 1)), q)
+        x = np.moveaxis(x, -1, 0)               # x.shape = (10, 71, 23)
+        assert_equal(stats.iqr(x, axis=(2, 1)), q)
+        x = x.swapaxes(0, 1)                    # x.shape = (71, 10, 23)
+        assert_equal(stats.iqr(x, axis=(0, 2)), q)
+        x = x.swapaxes(0, 1)                    # x.shape = (10, 71, 23)
+
+        assert_equal(stats.iqr(x, axis=(0, 1, 2)),
+                     stats.iqr(x, axis=None))
+        assert_equal(stats.iqr(x, axis=(0,)),
+                     stats.iqr(x, axis=0))
+
+        d = np.arange(3 * 5 * 7 * 11)
+        # Older versions of numpy only shuffle along axis=0.
+        # Not sure about newer, don't care.
+        np.random.shuffle(d)
+        d = d.reshape((3, 5, 7, 11))
+        assert_equal(stats.iqr(d, axis=(0, 1, 2))[0],
+                     stats.iqr(d[:,:,:, 0].ravel()))
+        assert_equal(stats.iqr(d, axis=(0, 1, 3))[1],
+                     stats.iqr(d[:,:, 1,:].ravel()))
+        assert_equal(stats.iqr(d, axis=(3, 1, -4))[2],
+                     stats.iqr(d[:,:, 2,:].ravel()))
+        assert_equal(stats.iqr(d, axis=(3, 1, 2))[2],
+                     stats.iqr(d[2,:,:,:].ravel()))
+        assert_equal(stats.iqr(d, axis=(3, 2))[2, 1],
+                     stats.iqr(d[2, 1,:,:].ravel()))
+        assert_equal(stats.iqr(d, axis=(1, -2))[2, 1],
+                     stats.iqr(d[2, :, :, 1].ravel()))
+        assert_equal(stats.iqr(d, axis=(1, 3))[2, 2],
+                     stats.iqr(d[2, :, 2,:].ravel()))
+
+        assert_raises(AxisError, stats.iqr, d, axis=4)
+        assert_raises(ValueError, stats.iqr, d, axis=(0, 0))
+
+    def test_rng(self):
+        x = np.arange(5)
+        assert_equal(stats.iqr(x), 2)
+        assert_equal(stats.iqr(x, rng=(25, 87.5)), 2.5)
+        assert_equal(stats.iqr(x, rng=(12.5, 75)), 2.5)
+        assert_almost_equal(stats.iqr(x, rng=(10, 50)), 1.6)  # 3-1.4
+
+        assert_raises(ValueError, stats.iqr, x, rng=(0, 101))
+        assert_raises(ValueError, stats.iqr, x, rng=(np.nan, 25))
+        assert_raises(TypeError, stats.iqr, x, rng=(0, 50, 60))
+
+    def test_interpolation(self):
+        x = np.arange(5)
+        y = np.arange(4)
+        # Default
+        assert_equal(stats.iqr(x), 2)
+        assert_equal(stats.iqr(y), 1.5)
+        # Linear
+        assert_equal(stats.iqr(x, interpolation='linear'), 2)
+        assert_equal(stats.iqr(y, interpolation='linear'), 1.5)
+        # Higher
+        assert_equal(stats.iqr(x, interpolation='higher'), 2)
+        assert_equal(stats.iqr(x, rng=(25, 80), interpolation='higher'), 3)
+        assert_equal(stats.iqr(y, interpolation='higher'), 2)
+        # Lower (will generally, but not always be the same as higher)
+        assert_equal(stats.iqr(x, interpolation='lower'), 2)
+        assert_equal(stats.iqr(x, rng=(25, 80), interpolation='lower'), 2)
+        assert_equal(stats.iqr(y, interpolation='lower'), 2)
+        # Nearest
+        assert_equal(stats.iqr(x, interpolation='nearest'), 2)
+        assert_equal(stats.iqr(y, interpolation='nearest'), 1)
+        # Midpoint
+        assert_equal(stats.iqr(x, interpolation='midpoint'), 2)
+        assert_equal(stats.iqr(x, rng=(25, 80), interpolation='midpoint'), 2.5)
+        assert_equal(stats.iqr(y, interpolation='midpoint'), 2)
+
+        # Check all method= values new in numpy 1.22.0 are accepted
+        for method in ('inverted_cdf', 'averaged_inverted_cdf',
+                       'closest_observation', 'interpolated_inverted_cdf',
+                       'hazen', 'weibull', 'median_unbiased',
+                       'normal_unbiased'):
+            stats.iqr(y, interpolation=method)
+
+        assert_raises(ValueError, stats.iqr, x, interpolation='foobar')
+
+    def test_keepdims(self):
+        # Also tests most of `axis`
+        x = np.ones((3, 5, 7, 11))
+        assert_equal(stats.iqr(x, axis=None, keepdims=False).shape, ())
+        assert_equal(stats.iqr(x, axis=2, keepdims=False).shape, (3, 5, 11))
+        assert_equal(stats.iqr(x, axis=(0, 1), keepdims=False).shape, (7, 11))
+        assert_equal(stats.iqr(x, axis=(0, 3), keepdims=False).shape, (5, 7))
+        assert_equal(stats.iqr(x, axis=(1,), keepdims=False).shape, (3, 7, 11))
+        assert_equal(stats.iqr(x, (0, 1, 2, 3), keepdims=False).shape, ())
+        assert_equal(stats.iqr(x, axis=(0, 1, 3), keepdims=False).shape, (7,))
+
+        assert_equal(stats.iqr(x, axis=None, keepdims=True).shape, (1, 1, 1, 1))
+        assert_equal(stats.iqr(x, axis=2, keepdims=True).shape, (3, 5, 1, 11))
+        assert_equal(stats.iqr(x, axis=(0, 1), keepdims=True).shape, (1, 1, 7, 11))
+        assert_equal(stats.iqr(x, axis=(0, 3), keepdims=True).shape, (1, 5, 7, 1))
+        assert_equal(stats.iqr(x, axis=(1,), keepdims=True).shape, (3, 1, 7, 11))
+        assert_equal(stats.iqr(x, (0, 1, 2, 3), keepdims=True).shape, (1, 1, 1, 1))
+        assert_equal(stats.iqr(x, axis=(0, 1, 3), keepdims=True).shape, (1, 1, 7, 1))
+
+    def test_nanpolicy(self):
+        x = np.arange(15.0).reshape((3, 5))
+
+        # No NaNs
+        assert_equal(stats.iqr(x, nan_policy='propagate'), 7)
+        assert_equal(stats.iqr(x, nan_policy='omit'), 7)
+        assert_equal(stats.iqr(x, nan_policy='raise'), 7)
+
+        # Yes NaNs
+        x[1, 2] = np.nan
+        with warnings.catch_warnings(record=True):
+            warnings.simplefilter("always")
+            assert_equal(stats.iqr(x, nan_policy='propagate'),
+                         np.nan)
+            assert_equal(stats.iqr(x, axis=0, nan_policy='propagate'),
+                         [5, 5, np.nan, 5, 5])
+            assert_equal(stats.iqr(x, axis=1, nan_policy='propagate'),
+                         [2, np.nan, 2])
+
+        with warnings.catch_warnings(record=True):
+            warnings.simplefilter("always")
+            assert_equal(stats.iqr(x, nan_policy='omit'), 7.5)
+            assert_equal(stats.iqr(x, axis=0, nan_policy='omit'), np.full(5, 5))
+            assert_equal(stats.iqr(x, axis=1, nan_policy='omit'), [2, 2.5, 2])
+
+        assert_raises(ValueError, stats.iqr, x, nan_policy='raise')
+        assert_raises(ValueError, stats.iqr, x, axis=0, nan_policy='raise')
+        assert_raises(ValueError, stats.iqr, x, axis=1, nan_policy='raise')
+
+        # Bad policy
+        assert_raises(ValueError, stats.iqr, x, nan_policy='barfood')
+
+    def test_scale(self):
+        x = np.arange(15.0).reshape((3, 5))
+
+        # No NaNs
+        assert_equal(stats.iqr(x, scale=1.0), 7)
+        assert_almost_equal(stats.iqr(x, scale='normal'), 7 / 1.3489795)
+        assert_equal(stats.iqr(x, scale=2.0), 3.5)
+
+        # Yes NaNs
+        x[1, 2] = np.nan
+        with warnings.catch_warnings(record=True):
+            warnings.simplefilter("always")
+            assert_equal(stats.iqr(x, scale=1.0, nan_policy='propagate'), np.nan)
+            assert_equal(stats.iqr(x, scale='normal', nan_policy='propagate'), np.nan)
+            assert_equal(stats.iqr(x, scale=2.0, nan_policy='propagate'), np.nan)
+            # axis=1 chosen to show behavior with both nans and without
+            assert_equal(stats.iqr(x, axis=1, scale=1.0,
+                                   nan_policy='propagate'), [2, np.nan, 2])
+            assert_almost_equal(stats.iqr(x, axis=1, scale='normal',
+                                          nan_policy='propagate'),
+                                np.array([2, np.nan, 2]) / 1.3489795)
+            assert_equal(stats.iqr(x, axis=1, scale=2.0, nan_policy='propagate'),
+                         [1, np.nan, 1])
+            # Since NumPy 1.17.0.dev, warnings are no longer emitted by
+            # np.percentile with nans, so we don't check the number of
+            # warnings here. See https://github.com/numpy/numpy/pull/12679.
+
+        assert_equal(stats.iqr(x, scale=1.0, nan_policy='omit'), 7.5)
+        assert_almost_equal(stats.iqr(x, scale='normal', nan_policy='omit'),
+                            7.5 / 1.3489795)
+        assert_equal(stats.iqr(x, scale=2.0, nan_policy='omit'), 3.75)
+
+        # Bad scale
+        assert_raises(ValueError, stats.iqr, x, scale='foobar')
+
+
+class TestMoments:
+    """
+        Comparison numbers are found using R v.1.5.1
+        note that length(testcase) = 4
+        testmathworks comes from documentation for the
+        Statistics Toolbox for Matlab and can be found at both
+        https://www.mathworks.com/help/stats/kurtosis.html
+        https://www.mathworks.com/help/stats/skewness.html
+        Note that both test cases came from here.
+    """
+    testcase = [1., 2., 3., 4.]
+    scalar_testcase = 4.
+    np.random.seed(1234)
+    testcase_moment_accuracy = np.random.rand(42)
+
+    def _assert_equal(self, actual, expect, *, shape=None, dtype=None):
+        expect = np.asarray(expect)
+        if shape is not None:
+            expect = np.broadcast_to(expect, shape)
+        assert_array_equal(actual, expect)
+        if dtype is None:
+            dtype = expect.dtype
+        assert actual.dtype == dtype
+
+    @array_api_compatible
+    @pytest.mark.parametrize('size', [10, (10, 2)])
+    @pytest.mark.parametrize('m, c', product((0, 1, 2, 3), (None, 0, 1)))
+    def test_moment_center_scalar_moment(self, size, m, c, xp):
+        rng = np.random.default_rng(6581432544381372042)
+        x = xp.asarray(rng.random(size=size))
+        res = stats.moment(x, m, center=c)
+        c = xp.mean(x, axis=0) if c is None else c
+        ref = xp.sum((x - c)**m, axis=0)/x.shape[0]
+        xp_assert_close(res, ref, atol=1e-16)
+
+    @array_api_compatible
+    @pytest.mark.parametrize('size', [10, (10, 2)])
+    @pytest.mark.parametrize('c', (None, 0, 1))
+    def test_moment_center_array_moment(self, size, c, xp):
+        rng = np.random.default_rng(1706828300224046506)
+        x = xp.asarray(rng.random(size=size))
+        m = [0, 1, 2, 3]
+        res = stats.moment(x, m, center=c)
+        xp_test = array_namespace(x)  # no `concat` in np < 2.0; no `newaxis` in torch
+        ref = xp_test.concat([stats.moment(x, i, center=c)[xp_test.newaxis, ...]
+                              for i in m])
+        xp_assert_equal(res, ref)
+
+    @array_api_compatible
+    def test_moment(self, xp):
+        # mean((testcase-mean(testcase))**power,axis=0),axis=0))**power))
+        testcase = xp.asarray(self.testcase)
+
+        y = stats.moment(xp.asarray(self.scalar_testcase))
+        xp_assert_close(y, xp.asarray(0.0))
+
+        y = stats.moment(testcase, 0)
+        xp_assert_close(y, xp.asarray(1.0))
+        y = stats.moment(testcase, 1)
+        xp_assert_close(y, xp.asarray(0.0))
+        y = stats.moment(testcase, 2)
+        xp_assert_close(y, xp.asarray(1.25))
+        y = stats.moment(testcase, 3)
+        xp_assert_close(y, xp.asarray(0.0))
+        y = stats.moment(testcase, 4)
+        xp_assert_close(y, xp.asarray(2.5625))
+
+        # check array_like input for moment
+        y = stats.moment(testcase, [1, 2, 3, 4])
+        xp_assert_close(y, xp.asarray([0, 1.25, 0, 2.5625]))
+
+        # check moment input consists only of integers
+        y = stats.moment(testcase, 0.0)
+        xp_assert_close(y, xp.asarray(1.0))
+        message = 'All elements of `order` must be integral.'
+        with pytest.raises(ValueError, match=message):
+            stats.moment(testcase, 1.2)
+        y = stats.moment(testcase, [1.0, 2, 3, 4.0])
+        xp_assert_close(y, xp.asarray([0, 1.25, 0, 2.5625]))
+
+        def test_cases():
+            y = stats.moment(xp.asarray([]))
+            xp_assert_equal(y, xp.asarray(xp.nan))
+            y = stats.moment(xp.asarray([], dtype=xp.float32))
+            xp_assert_equal(y, xp.asarray(xp.nan, dtype=xp.float32))
+            y = stats.moment(xp.zeros((1, 0)), axis=0)
+            xp_assert_equal(y, xp.empty((0,)))
+            y = stats.moment(xp.asarray([[]]), axis=1)
+            xp_assert_equal(y, xp.asarray([xp.nan]))
+            y = stats.moment(xp.asarray([[]]), order=[0, 1], axis=0)
+            xp_assert_equal(y, xp.empty((2, 0)))
+
+        # test empty input
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match="See documentation for..."):
+                test_cases()
+        else:
+            with np.testing.suppress_warnings() as sup:  # needed by array_api_strict
+                sup.filter(RuntimeWarning, "Mean of empty slice.")
+                sup.filter(RuntimeWarning, "invalid value")
+                test_cases()
+
+    def test_nan_policy(self):
+        x = np.arange(10.)
+        x[9] = np.nan
+        assert_equal(stats.moment(x, 2), np.nan)
+        assert_almost_equal(stats.moment(x, nan_policy='omit'), 0.0)
+        assert_raises(ValueError, stats.moment, x, nan_policy='raise')
+        assert_raises(ValueError, stats.moment, x, nan_policy='foobar')
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    @pytest.mark.parametrize('dtype', ['float32', 'float64', 'complex128'])
+    @pytest.mark.parametrize('expect, order', [(0, 1), (1, 0)])
+    def test_constant_moments(self, dtype, expect, order, xp):
+        if dtype=='complex128' and is_torch(xp):
+            pytest.skip()
+        dtype = getattr(xp, dtype)
+        x = xp.asarray(np.random.rand(5), dtype=dtype)
+        y = stats.moment(x, order=order)
+        xp_assert_equal(y, xp.asarray(expect, dtype=dtype))
+
+        y = stats.moment(xp.broadcast_to(x, (6, 5)), axis=0, order=order)
+        xp_assert_equal(y, xp.full((5,), expect, dtype=dtype))
+
+        y = stats.moment(xp.broadcast_to(x, (1, 2, 3, 4, 5)), axis=2,
+                         order=order)
+        xp_assert_equal(y, xp.full((1, 2, 4, 5), expect, dtype=dtype))
+
+        y = stats.moment(xp.broadcast_to(x, (1, 2, 3, 4, 5)), axis=None,
+                         order=order)
+        xp_assert_equal(y, xp.full((), expect, dtype=dtype))
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_moment_propagate_nan(self, xp):
+        # Check that the shape of the result is the same for inputs
+        # with and without nans, cf gh-5817
+        a = xp.reshape(xp.arange(8.), (2, -1))
+        a[1, 0] = np.nan
+        mm = stats.moment(a, 2, axis=1)
+        xp_assert_close(mm, xp.asarray([1.25, np.nan]), atol=1e-15)
+
+    @array_api_compatible
+    def test_moment_empty_order(self, xp):
+        # tests moment with empty `order` list
+        with pytest.raises(ValueError, match=r"`order` must be a scalar or a"
+                                             r" non-empty 1D array."):
+            stats.moment(xp.asarray([1, 2, 3, 4]), order=[])
+
+    @array_api_compatible
+    def test_rename_moment_order(self, xp):
+        # Parameter 'order' was formerly known as 'moment'. The old name
+        # has not been deprecated, so it must continue to work.
+        x = xp.arange(10)
+        res = stats.moment(x, moment=3)
+        ref = stats.moment(x, order=3)
+        xp_assert_equal(res, ref)
+
+    def test_moment_accuracy(self):
+        # 'moment' must have a small enough error compared to the slower
+        #  but very accurate numpy.power() implementation.
+        tc_no_mean = (self.testcase_moment_accuracy
+                      - np.mean(self.testcase_moment_accuracy))
+        assert_allclose(np.power(tc_no_mean, 42).mean(),
+                        stats.moment(self.testcase_moment_accuracy, 42))
+
+    @array_api_compatible
+    @pytest.mark.parametrize('order', [0, 1, 2, 3])
+    @pytest.mark.parametrize('axis', [-1, 0, 1])
+    @pytest.mark.parametrize('center', [None, 0])
+    def test_moment_array_api(self, xp, order, axis, center):
+        rng = np.random.default_rng(34823589259425)
+        x = rng.random(size=(5, 6, 7))
+        res = stats.moment(xp.asarray(x), order, axis=axis, center=center)
+        ref = xp.asarray(_moment(x, order, axis, mean=center))
+        xp_assert_close(res, ref)
+
+
+class SkewKurtosisTest:
+    scalar_testcase = 4.
+    testcase = [1., 2., 3., 4.]
+    testmathworks = [1.165, 0.6268, 0.0751, 0.3516, -0.6965]
+
+
+class TestSkew(SkewKurtosisTest):
+    @array_api_compatible
+    @pytest.mark.parametrize('stat_fun', [stats.skew, stats.kurtosis])
+    def test_empty_1d(self, stat_fun, xp):
+        x = xp.asarray([])
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = stat_fun(x)
+        else:
+            with np.testing.suppress_warnings() as sup:
+                # array_api_strict produces these
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                sup.filter(RuntimeWarning, "invalid value encountered")
+                res = stat_fun(x)
+        xp_assert_equal(res, xp.asarray(xp.nan))
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_skewness(self, xp):
+        # Scalar test case
+        y = stats.skew(xp.asarray(self.scalar_testcase))
+        xp_assert_close(y, xp.asarray(xp.nan))
+        # sum((testmathworks-mean(testmathworks,axis=0))**3,axis=0) /
+        #     ((sqrt(var(testmathworks)*4/5))**3)/5
+        y = stats.skew(xp.asarray(self.testmathworks))
+        xp_assert_close(y, xp.asarray(-0.29322304336607), atol=1e-10)
+        y = stats.skew(xp.asarray(self.testmathworks), bias=0)
+        xp_assert_close(y, xp.asarray(-0.437111105023940), atol=1e-10)
+        y = stats.skew(xp.asarray(self.testcase))
+        xp_assert_close(y, xp.asarray(0.0), atol=1e-10)
+
+    def test_nan_policy(self):
+        # initially, nan_policy is ignored with alternative backends
+        x = np.arange(10.)
+        x[9] = np.nan
+        with np.errstate(invalid='ignore'):
+            assert_equal(stats.skew(x), np.nan)
+        assert_equal(stats.skew(x, nan_policy='omit'), 0.)
+        assert_raises(ValueError, stats.skew, x, nan_policy='raise')
+        assert_raises(ValueError, stats.skew, x, nan_policy='foobar')
+
+    def test_skewness_scalar(self):
+        # `skew` must return a scalar for 1-dim input (only for NumPy arrays)
+        assert_equal(stats.skew(arange(10)), 0.0)
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_skew_propagate_nan(self, xp):
+        # Check that the shape of the result is the same for inputs
+        # with and without nans, cf gh-5817
+        a = xp.arange(8.)
+        a = xp.reshape(a, (2, -1))
+        a[1, 0] = xp.nan
+        with np.errstate(invalid='ignore'):
+            s = stats.skew(a, axis=1)
+        xp_assert_equal(s, xp.asarray([0, xp.nan]))
+
+    @array_api_compatible
+    def test_skew_constant_value(self, xp):
+        # Skewness of a constant input should be NaN (gh-16061)
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred"):
+            a = xp.asarray([-0.27829495]*10)  # xp.repeat not currently available
+            xp_assert_equal(stats.skew(a), xp.asarray(xp.nan))
+            xp_assert_equal(stats.skew(a*2.**50), xp.asarray(xp.nan))
+            xp_assert_equal(stats.skew(a/2.**50), xp.asarray(xp.nan))
+            xp_assert_equal(stats.skew(a, bias=False), xp.asarray(xp.nan))
+
+            # # similarly, from gh-11086:
+            a = xp.asarray([14.3]*7)
+            xp_assert_equal(stats.skew(a), xp.asarray(xp.nan))
+            a = 1. + xp.arange(-3., 4)*1e-16
+            xp_assert_equal(stats.skew(a), xp.asarray(xp.nan))
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_precision_loss_gh15554(self, xp):
+        # gh-15554 was one of several issues that have reported problems with
+        # constant or near-constant input. We can't always fix these, but
+        # make sure there's a warning.
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred"):
+            rng = np.random.default_rng(34095309370)
+            a = xp.asarray(rng.random(size=(100, 10)))
+            a[:, 0] = 1.01
+            stats.skew(a)
+
+    @skip_xp_backends('jax.numpy',
+                      reason="JAX arrays do not support item assignment")
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    @pytest.mark.parametrize('axis', [-1, 0, 2, None])
+    @pytest.mark.parametrize('bias', [False, True])
+    def test_vectorization(self, xp, axis, bias):
+        # Behavior with array input is barely tested above. Compare
+        # against naive implementation.
+        rng = np.random.default_rng(1283413549926)
+        x = xp.asarray(rng.random((3, 4, 5)))
+
+        def skewness(a, axis, bias):
+            # Simple implementation of skewness
+            if axis is None:
+                a = xp.reshape(a, (-1,))
+                axis = 0
+            xp_test = array_namespace(a)  # plain torch ddof=1 by default
+            mean = xp_test.mean(a, axis=axis, keepdims=True)
+            mu3 = xp_test.mean((a - mean)**3, axis=axis)
+            std = xp_test.std(a, axis=axis)
+            res = mu3 / std ** 3
+            if not bias:
+                n = a.shape[axis]
+                res *= ((n - 1.0) * n) ** 0.5 / (n - 2.0)
+            return res
+
+        res = stats.skew(x, axis=axis, bias=bias)
+        ref = skewness(x, axis=axis, bias=bias)
+        xp_assert_close(res, ref)
+
+
+class TestKurtosis(SkewKurtosisTest):
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_kurtosis(self, xp):
+        # Scalar test case
+        y = stats.kurtosis(xp.asarray(self.scalar_testcase))
+        assert xp.isnan(y)
+
+        #   sum((testcase-mean(testcase,axis=0))**4,axis=0)
+        #   / ((sqrt(var(testcase)*3/4))**4)
+        #   / 4
+        #
+        #   sum((test2-mean(testmathworks,axis=0))**4,axis=0)
+        #   / ((sqrt(var(testmathworks)*4/5))**4)
+        #   / 5
+        #
+        #   Set flags for axis = 0 and
+        #   fisher=0 (Pearson's defn of kurtosis for compatibility with Matlab)
+        y = stats.kurtosis(xp.asarray(self.testmathworks), 0, fisher=0, bias=1)
+        xp_assert_close(y, xp.asarray(2.1658856802973))
+
+        # Note that MATLAB has confusing docs for the following case
+        #  kurtosis(x,0) gives an unbiased estimate of Pearson's skewness
+        #  kurtosis(x)  gives a biased estimate of Fisher's skewness (Pearson-3)
+        #  The MATLAB docs imply that both should give Fisher's
+        y = stats.kurtosis(xp.asarray(self.testmathworks), fisher=0, bias=0)
+        xp_assert_close(y, xp.asarray(3.663542721189047))
+        y = stats.kurtosis(xp.asarray(self.testcase), 0, 0)
+        xp_assert_close(y, xp.asarray(1.64))
+
+        x = xp.arange(10.)
+        x = xp.where(x == 8, xp.asarray(xp.nan), x)
+        xp_assert_equal(stats.kurtosis(x), xp.asarray(xp.nan))
+
+    def test_kurtosis_nan_policy(self):
+        # nan_policy only for NumPy right now
+        x = np.arange(10.)
+        x[9] = np.nan
+        assert_almost_equal(stats.kurtosis(x, nan_policy='omit'), -1.230000)
+        assert_raises(ValueError, stats.kurtosis, x, nan_policy='raise')
+        assert_raises(ValueError, stats.kurtosis, x, nan_policy='foobar')
+
+    def test_kurtosis_array_scalar(self):
+        # "array scalars" do not exist in other backends
+        assert_equal(type(stats.kurtosis([1, 2, 3])), np.float64)
+
+    def test_kurtosis_propagate_nan(self):
+        # nan_policy only for NumPy right now
+        # Check that the shape of the result is the same for inputs
+        # with and without nans, cf gh-5817
+        a = np.arange(8).reshape(2, -1).astype(float)
+        a[1, 0] = np.nan
+        k = stats.kurtosis(a, axis=1, nan_policy="propagate")
+        np.testing.assert_allclose(k, [-1.36, np.nan], atol=1e-15)
+
+    @array_api_compatible
+    def test_kurtosis_constant_value(self, xp):
+        # Kurtosis of a constant input should be NaN (gh-16061)
+        a = xp.asarray([-0.27829495]*10)
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred"):
+            assert xp.isnan(stats.kurtosis(a, fisher=False))
+            assert xp.isnan(stats.kurtosis(a * float(2**50), fisher=False))
+            assert xp.isnan(stats.kurtosis(a / float(2**50), fisher=False))
+            assert xp.isnan(stats.kurtosis(a, fisher=False, bias=False))
+
+    @skip_xp_backends('jax.numpy',
+                      reason='JAX arrays do not support item assignment')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    @pytest.mark.parametrize('axis', [-1, 0, 2, None])
+    @pytest.mark.parametrize('bias', [False, True])
+    @pytest.mark.parametrize('fisher', [False, True])
+    def test_vectorization(self, xp, axis, bias, fisher):
+        # Behavior with array input is not tested above. Compare
+        # against naive implementation.
+        rng = np.random.default_rng(1283413549926)
+        x = xp.asarray(rng.random((4, 5, 6)))
+
+        def kurtosis(a, axis, bias, fisher):
+            # Simple implementation of kurtosis
+            if axis is None:
+                a = xp.reshape(a, (-1,))
+                axis = 0
+            xp_test = array_namespace(a)  # plain torch ddof=1 by default
+            mean = xp_test.mean(a, axis=axis, keepdims=True)
+            mu4 = xp_test.mean((a - mean)**4, axis=axis)
+            mu2 = xp_test.var(a, axis=axis, correction=0)
+            if bias:
+                res = mu4 / mu2**2 - 3
+            else:
+                n = a.shape[axis]
+                # https://en.wikipedia.org/wiki/Kurtosis#Standard_unbiased_estimator
+                res = (n-1) / ((n-2) * (n-3)) * ((n + 1) * mu4/mu2**2 - 3*(n-1))
+
+            # I know it looks strange to subtract then add 3,
+            # but it is simpler than the alternatives
+            return res if fisher else res + 3
+
+        res = stats.kurtosis(x, axis=axis, bias=bias, fisher=fisher)
+        ref = kurtosis(x, axis=axis, bias=bias, fisher=fisher)
+        xp_assert_close(res, ref)
+
+
+@hypothesis.strategies.composite
+def ttest_data_axis_strategy(draw):
+    # draw an array under shape and value constraints
+    elements = dict(allow_nan=False, allow_infinity=False)
+    shape = npst.array_shapes(min_dims=1, min_side=2)
+    # The test that uses this, `test_pvalue_ci`, uses `float64` to test
+    # extreme `alpha`. It could be adjusted to test a dtype-dependent
+    # range of `alpha` if this strategy is needed to generate other floats.
+    data = draw(npst.arrays(dtype=np.float64, elements=elements, shape=shape))
+
+    # determine axes over which nonzero variance can be computed accurately
+    ok_axes = []
+    # Locally, I don't need catch_warnings or simplefilter, and I can just
+    # suppress RuntimeWarning. I include all that in hope of getting the same
+    # behavior on CI.
+    with warnings.catch_warnings():
+        warnings.simplefilter("error")
+        for axis in range(len(data.shape)):
+            with contextlib.suppress(Exception):
+                var = stats.moment(data, order=2, axis=axis)
+                if np.all(var > 0) and np.all(np.isfinite(var)):
+                    ok_axes.append(axis)
+    # if there are no valid axes, tell hypothesis to try a different example
+    hypothesis.assume(ok_axes)
+
+    # draw one of the valid axes
+    axis = draw(hypothesis.strategies.sampled_from(ok_axes))
+
+    return data, axis
+
+
+@pytest.mark.skip_xp_backends(cpu_only=True,
+                              reason='Uses NumPy for pvalue, CI')
+@pytest.mark.usefixtures("skip_xp_backends")
+@array_api_compatible
+class TestStudentTest:
+    # Preserving original test cases.
+    # Recomputed statistics and p-values with R t.test, e.g.
+    # options(digits=16)
+    # t.test(c(-1., 0., 1.), mu=2)
+    X1 = [-1., 0., 1.]
+    X2 = [0., 1., 2.]
+    T1_0 = 0.
+    P1_0 = 1.
+    T1_1 = -1.7320508075689
+    P1_1 = 0.2254033307585
+    T1_2 = -3.4641016151378
+    P1_2 = 0.07417990022745
+    T2_0 = 1.7320508075689
+    P2_0 = 0.2254033307585
+    P1_1_l = P1_1 / 2
+    P1_1_g = 1 - (P1_1 / 2)
+
+    def test_onesample(self, xp):
+        with suppress_warnings() as sup, \
+                np.errstate(invalid="ignore", divide="ignore"):
+            sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice")
+            a = xp.asarray(4.) if not is_numpy(xp) else 4.
+            t, p = stats.ttest_1samp(a, 3.)
+        xp_assert_equal(t, xp.asarray(xp.nan))
+        xp_assert_equal(p, xp.asarray(xp.nan))
+
+        t, p = stats.ttest_1samp(xp.asarray(self.X1), 0.)
+        xp_assert_close(t, xp.asarray(self.T1_0))
+        xp_assert_close(p, xp.asarray(self.P1_0))
+
+        res = stats.ttest_1samp(xp.asarray(self.X1), 0.)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, xp=xp)
+
+        t, p = stats.ttest_1samp(xp.asarray(self.X2), 0.)
+
+        xp_assert_close(t, xp.asarray(self.T2_0))
+        xp_assert_close(p, xp.asarray(self.P2_0))
+
+        t, p = stats.ttest_1samp(xp.asarray(self.X1), 1.)
+
+        xp_assert_close(t, xp.asarray(self.T1_1))
+        xp_assert_close(p, xp.asarray(self.P1_1))
+
+        t, p = stats.ttest_1samp(xp.asarray(self.X1), 2.)
+
+        xp_assert_close(t, xp.asarray(self.T1_2))
+        xp_assert_close(p, xp.asarray(self.P1_2))
+
+    def test_onesample_nan_policy(self, xp):
+        # check nan policy
+        if not is_numpy(xp):
+            x = xp.asarray([1., 2., 3., xp.nan])
+            message = "Use of `nan_policy` and `keepdims`..."
+            with pytest.raises(NotImplementedError, match=message):
+                stats.ttest_1samp(x, 1., nan_policy='omit')
+            return
+
+        x = stats.norm.rvs(loc=5, scale=10, size=51, random_state=7654567)
+        x[50] = np.nan
+        with np.errstate(invalid="ignore"):
+            assert_array_equal(stats.ttest_1samp(x, 5.0), (np.nan, np.nan))
+
+            assert_array_almost_equal(stats.ttest_1samp(x, 5.0, nan_policy='omit'),
+                                      (-1.6412624074367159, 0.107147027334048005))
+            assert_raises(ValueError, stats.ttest_1samp, x, 5.0, nan_policy='raise')
+            assert_raises(ValueError, stats.ttest_1samp, x, 5.0,
+                          nan_policy='foobar')
+
+    def test_1samp_alternative(self, xp):
+        message = "`alternative` must be 'less', 'greater', or 'two-sided'."
+        with pytest.raises(ValueError, match=message):
+            stats.ttest_1samp(xp.asarray(self.X1), 0., alternative="error")
+
+        t, p = stats.ttest_1samp(xp.asarray(self.X1), 1., alternative="less")
+        xp_assert_close(p, xp.asarray(self.P1_1_l))
+        xp_assert_close(t, xp.asarray(self.T1_1))
+
+        t, p = stats.ttest_1samp(xp.asarray(self.X1), 1., alternative="greater")
+        xp_assert_close(p, xp.asarray(self.P1_1_g))
+        xp_assert_close(t, xp.asarray(self.T1_1))
+
+    @pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater'])
+    def test_1samp_ci_1d(self, xp, alternative):
+        # test confidence interval method against reference values
+        rng = np.random.default_rng(8066178009154342972)
+        n = 10
+        x = rng.normal(size=n, loc=1.5, scale=2)
+        popmean = rng.normal()  # this shouldn't affect confidence interval
+        # Reference values generated with R t.test:
+        # options(digits=16)
+        # x = c(2.75532884,  0.93892217,  0.94835861,  1.49489446, -0.62396595,
+        #      -1.88019867, -1.55684465,  4.88777104,  5.15310979,  4.34656348)
+        # t.test(x, conf.level=0.85, alternative='l')
+        dtype = xp.float32 if is_torch(xp) else xp.float64  # use default dtype
+        x = xp.asarray(x, dtype=dtype)
+        popmean = xp.asarray(popmean, dtype=dtype)
+
+        ref = {'two-sided': [0.3594423211709136, 2.9333455028290860],
+               'greater': [0.7470806207371626, np.inf],
+               'less': [-np.inf, 2.545707203262837]}
+        res = stats.ttest_1samp(x, popmean=popmean, alternative=alternative)
+        ci = res.confidence_interval(confidence_level=0.85)
+        xp_assert_close(ci.low, xp.asarray(ref[alternative][0]))
+        xp_assert_close(ci.high, xp.asarray(ref[alternative][1]))
+        xp_assert_equal(res.df, xp.asarray(n-1))
+
+    def test_1samp_ci_iv(self, xp):
+        # test `confidence_interval` method input validation
+        res = stats.ttest_1samp(xp.arange(10.), 0.)
+        message = '`confidence_level` must be a number between 0 and 1.'
+        with pytest.raises(ValueError, match=message):
+            res.confidence_interval(confidence_level=10)
+
+    @pytest.mark.xslow
+    @hypothesis.given(alpha=hypothesis.strategies.floats(1e-15, 1-1e-15),
+                      data_axis=ttest_data_axis_strategy())
+    @pytest.mark.parametrize('alternative', ['less', 'greater'])
+    def test_pvalue_ci(self, alpha, data_axis, alternative, xp):
+        # test relationship between one-sided p-values and confidence intervals
+        data, axis = data_axis
+        data = xp.asarray(data)
+        res = stats.ttest_1samp(data, 0.,
+                                alternative=alternative, axis=axis)
+        l, u = res.confidence_interval(confidence_level=alpha)
+        popmean = l if alternative == 'greater' else u
+        xp_test = array_namespace(l)  # torch needs `expand_dims`
+        popmean = xp_test.expand_dims(popmean, axis=axis)
+        res = stats.ttest_1samp(data, popmean, alternative=alternative, axis=axis)
+        shape = list(data.shape)
+        shape.pop(axis)
+        # `float64` is used to correspond with extreme range of `alpha`
+        ref = xp.broadcast_to(xp.asarray(1-alpha, dtype=xp.float64), shape)
+        xp_assert_close(res.pvalue, ref)
+
+
+class TestPercentileOfScore:
+
+    def f(self, *args, **kwargs):
+        return stats.percentileofscore(*args, **kwargs)
+
+    @pytest.mark.parametrize("kind, result", [("rank", 40),
+                                              ("mean", 35),
+                                              ("strict", 30),
+                                              ("weak", 40)])
+    def test_unique(self, kind, result):
+        a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+        assert_equal(self.f(a, 4, kind=kind), result)
+
+    @pytest.mark.parametrize("kind, result", [("rank", 45),
+                                              ("mean", 40),
+                                              ("strict", 30),
+                                              ("weak", 50)])
+    def test_multiple2(self, kind, result):
+        a = [1, 2, 3, 4, 4, 5, 6, 7, 8, 9]
+        assert_equal(self.f(a, 4, kind=kind), result)
+
+    @pytest.mark.parametrize("kind, result", [("rank", 50),
+                                              ("mean", 45),
+                                              ("strict", 30),
+                                              ("weak", 60)])
+    def test_multiple3(self, kind, result):
+        a = [1, 2, 3, 4, 4, 4, 5, 6, 7, 8]
+        assert_equal(self.f(a, 4, kind=kind), result)
+
+    @pytest.mark.parametrize("kind, result", [("rank", 30),
+                                              ("mean", 30),
+                                              ("strict", 30),
+                                              ("weak", 30)])
+    def test_missing(self, kind, result):
+        a = [1, 2, 3, 5, 6, 7, 8, 9, 10, 11]
+        assert_equal(self.f(a, 4, kind=kind), result)
+
+    @pytest.mark.parametrize("kind, result", [("rank", 40),
+                                              ("mean", 35),
+                                              ("strict", 30),
+                                              ("weak", 40)])
+    def test_large_numbers(self, kind, result):
+        a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
+        assert_equal(self.f(a, 40, kind=kind), result)
+
+    @pytest.mark.parametrize("kind, result", [("rank", 50),
+                                              ("mean", 45),
+                                              ("strict", 30),
+                                              ("weak", 60)])
+    def test_large_numbers_multiple3(self, kind, result):
+        a = [10, 20, 30, 40, 40, 40, 50, 60, 70, 80]
+        assert_equal(self.f(a, 40, kind=kind), result)
+
+    @pytest.mark.parametrize("kind, result", [("rank", 30),
+                                              ("mean", 30),
+                                              ("strict", 30),
+                                              ("weak", 30)])
+    def test_large_numbers_missing(self, kind, result):
+        a = [10, 20, 30, 50, 60, 70, 80, 90, 100, 110]
+        assert_equal(self.f(a, 40, kind=kind), result)
+
+    @pytest.mark.parametrize("kind, result", [("rank", [0, 10, 100, 100]),
+                                              ("mean", [0, 5, 95, 100]),
+                                              ("strict", [0, 0, 90, 100]),
+                                              ("weak", [0, 10, 100, 100])])
+    def test_boundaries(self, kind, result):
+        a = [10, 20, 30, 50, 60, 70, 80, 90, 100, 110]
+        assert_equal(self.f(a, [0, 10, 110, 200], kind=kind), result)
+
+    @pytest.mark.parametrize("kind, result", [("rank", [0, 10, 100]),
+                                              ("mean", [0, 5, 95]),
+                                              ("strict", [0, 0, 90]),
+                                              ("weak", [0, 10, 100])])
+    def test_inf(self, kind, result):
+        a = [1, 2, 3, 4, 5, 6, 7, 8, 9, +np.inf]
+        assert_equal(self.f(a, [-np.inf, 1, +np.inf], kind=kind), result)
+
+    cases = [("propagate", [], 1, np.nan),
+             ("propagate", [np.nan], 1, np.nan),
+             ("propagate", [np.nan], [0, 1, 2], [np.nan, np.nan, np.nan]),
+             ("propagate", [1, 2], [1, 2, np.nan], [50, 100, np.nan]),
+             ("omit", [1, 2, np.nan], [0, 1, 2], [0, 50, 100]),
+             ("omit", [1, 2], [0, 1, np.nan], [0, 50, np.nan]),
+             ("omit", [np.nan, np.nan], [0, 1, 2], [np.nan, np.nan, np.nan])]
+
+    @pytest.mark.parametrize("policy, a, score, result", cases)
+    def test_nans_ok(self, policy, a, score, result):
+        assert_equal(self.f(a, score, nan_policy=policy), result)
+
+    cases = [
+        ("raise", [1, 2, 3, np.nan], [1, 2, 3],
+         "The input contains nan values"),
+        ("raise", [1, 2, 3], [1, 2, 3, np.nan],
+         "The input contains nan values"),
+    ]
+
+    @pytest.mark.parametrize("policy, a, score, message", cases)
+    def test_nans_fail(self, policy, a, score, message):
+        with assert_raises(ValueError, match=message):
+            self.f(a, score, nan_policy=policy)
+
+    @pytest.mark.parametrize("shape", [
+        (6, ),
+        (2, 3),
+        (2, 1, 3),
+        (2, 1, 1, 3),
+    ])
+    def test_nd(self, shape):
+        a = np.array([0, 1, 2, 3, 4, 5])
+        scores = a.reshape(shape)
+        results = scores*10
+        a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+        assert_equal(self.f(a, scores, kind="rank"), results)
+
+
+PowerDivCase = namedtuple('Case',  # type: ignore[name-match]
+                          ['f_obs', 'f_exp', 'ddof', 'axis',
+                           'chi2',     # Pearson's
+                           'log',      # G-test (log-likelihood)
+                           'mod_log',  # Modified log-likelihood
+                           'cr',       # Cressie-Read (lambda=2/3)
+                           ])
+
+# The details of the first two elements in power_div_1d_cases are used
+# in a test in TestPowerDivergence.  Check that code before making
+# any changes here.
+power_div_1d_cases = [
+    # Use the default f_exp.
+    PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=None, ddof=0, axis=None,
+                 chi2=4,
+                 log=2*(4*np.log(4/8) + 12*np.log(12/8)),
+                 mod_log=2*(8*np.log(8/4) + 8*np.log(8/12)),
+                 cr=(4*((4/8)**(2/3) - 1) + 12*((12/8)**(2/3) - 1))/(5/9)),
+    # Give a non-uniform f_exp.
+    PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=[2, 16, 12, 2], ddof=0, axis=None,
+                 chi2=24,
+                 log=2*(4*np.log(4/2) + 8*np.log(8/16) + 8*np.log(8/2)),
+                 mod_log=2*(2*np.log(2/4) + 16*np.log(16/8) + 2*np.log(2/8)),
+                 cr=(4*((4/2)**(2/3) - 1) + 8*((8/16)**(2/3) - 1) +
+                     8*((8/2)**(2/3) - 1))/(5/9)),
+    # f_exp is a scalar.
+    PowerDivCase(f_obs=[4, 8, 12, 8], f_exp=8, ddof=0, axis=None,
+                 chi2=4,
+                 log=2*(4*np.log(4/8) + 12*np.log(12/8)),
+                 mod_log=2*(8*np.log(8/4) + 8*np.log(8/12)),
+                 cr=(4*((4/8)**(2/3) - 1) + 12*((12/8)**(2/3) - 1))/(5/9)),
+    # f_exp equal to f_obs.
+    PowerDivCase(f_obs=[3, 5, 7, 9], f_exp=[3, 5, 7, 9], ddof=0, axis=0,
+                 chi2=0, log=0, mod_log=0, cr=0),
+]
+
+
+power_div_empty_cases = [
+    # Shape is (0,)--a data set with length 0.  The computed
+    # test statistic should be 0.
+    PowerDivCase(f_obs=[],
+                 f_exp=None, ddof=0, axis=0,
+                 chi2=0, log=0, mod_log=0, cr=0),
+    # Shape is (0, 3).  This is 3 data sets, but each data set has
+    # length 0, so the computed test statistic should be [0, 0, 0].
+    PowerDivCase(f_obs=np.array([[],[],[]]).T,
+                 f_exp=None, ddof=0, axis=0,
+                 chi2=[0, 0, 0],
+                 log=[0, 0, 0],
+                 mod_log=[0, 0, 0],
+                 cr=[0, 0, 0]),
+    # Shape is (3, 0).  This represents an empty collection of
+    # data sets in which each data set has length 3.  The test
+    # statistic should be an empty array.
+    PowerDivCase(f_obs=np.array([[],[],[]]),
+                 f_exp=None, ddof=0, axis=0,
+                 chi2=[],
+                 log=[],
+                 mod_log=[],
+                 cr=[]),
+]
+
+
+@array_api_compatible
+class TestPowerDivergence:
+
+    def check_power_divergence(self, f_obs, f_exp, ddof, axis, lambda_,
+                               expected_stat, xp):
+        dtype = xp.asarray(1.).dtype
+
+        f_obs = xp.asarray(f_obs, dtype=dtype)
+        f_exp = xp.asarray(f_exp, dtype=dtype) if f_exp is not None else f_exp
+
+        if axis is None:
+            num_obs = xp_size(f_obs)
+        else:
+            xp_test = array_namespace(f_obs)  # torch needs broadcast_arrays
+            arrays = (xp_test.broadcast_arrays(f_obs, f_exp) if f_exp is not None
+                      else (f_obs,))
+            num_obs = arrays[0].shape[axis]
+
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "Mean of empty slice")
+            stat, p = stats.power_divergence(
+                                f_obs=f_obs, f_exp=f_exp, ddof=ddof,
+                                axis=axis, lambda_=lambda_)
+            xp_assert_close(stat, xp.asarray(expected_stat, dtype=dtype))
+
+            if lambda_ == 1 or lambda_ == "pearson":
+                # Also test stats.chisquare.
+                stat, p = stats.chisquare(f_obs=f_obs, f_exp=f_exp, ddof=ddof,
+                                          axis=axis)
+                xp_assert_close(stat, xp.asarray(expected_stat, dtype=dtype))
+
+        ddof = np.asarray(ddof)
+        expected_p = stats.distributions.chi2.sf(expected_stat,
+                                                 num_obs - 1 - ddof)
+        xp_assert_close(p, xp.asarray(expected_p, dtype=dtype))
+
+    @pytest.mark.parametrize('case', power_div_1d_cases)
+    @pytest.mark.parametrize('lambda_stat',
+        [(None, 'chi2'), ('pearson', 'chi2'), (1, 'chi2'),
+         ('log-likelihood', 'log'), ('mod-log-likelihood', 'mod_log'),
+         ('cressie-read', 'cr'), (2/3, 'cr')])
+    def test_basic(self, case, lambda_stat, xp):
+        lambda_, attr = lambda_stat
+        expected_stat = getattr(case, attr)
+        self.check_power_divergence(case.f_obs, case.f_exp, case.ddof, case.axis,
+                                    lambda_, expected_stat, xp)
+
+    def test_axis(self, xp):
+        case0 = power_div_1d_cases[0]
+        case1 = power_div_1d_cases[1]
+        f_obs = np.vstack((case0.f_obs, case1.f_obs))
+        f_exp = np.vstack((np.ones_like(case0.f_obs)*np.mean(case0.f_obs),
+                           case1.f_exp))
+        # Check the four computational code paths in power_divergence
+        # using a 2D array with axis=1.
+        f_obs = xp.asarray(f_obs)
+        f_exp = xp.asarray(f_exp) if f_exp is not None else f_exp
+        self.check_power_divergence(
+               f_obs, f_exp, 0, 1,
+               "pearson", [case0.chi2, case1.chi2], xp=xp)
+        self.check_power_divergence(
+               f_obs, f_exp, 0, 1,
+               "log-likelihood", [case0.log, case1.log], xp=xp)
+        self.check_power_divergence(
+               f_obs, f_exp, 0, 1,
+               "mod-log-likelihood", [case0.mod_log, case1.mod_log], xp=xp)
+        self.check_power_divergence(
+               f_obs, f_exp, 0, 1,
+               "cressie-read", [case0.cr, case1.cr], xp=xp)
+        # Reshape case0.f_obs to shape (2,2), and use axis=None.
+        # The result should be the same.
+        f_obs_reshape = xp.reshape(xp.asarray(case0.f_obs), (2, 2))
+        self.check_power_divergence(
+               f_obs_reshape, None, 0, None,
+               "pearson", case0.chi2, xp=xp)
+
+    def test_ddof_broadcasting(self, xp):
+        # Test that ddof broadcasts correctly.
+        # ddof does not affect the test statistic.  It is broadcast
+        # with the computed test statistic for the computation of
+        # the p value.
+
+        case0 = power_div_1d_cases[0]
+        case1 = power_div_1d_cases[1]
+        # Create 4x2 arrays of observed and expected frequencies.
+        f_obs = np.vstack((case0.f_obs, case1.f_obs)).T
+        f_exp = np.vstack((np.ones_like(case0.f_obs)*np.mean(case0.f_obs),
+                           case1.f_exp)).T
+
+        expected_chi2 = [case0.chi2, case1.chi2]
+
+        dtype = xp.asarray(1.).dtype
+        f_obs = xp.asarray(f_obs, dtype=dtype)
+        f_exp = xp.asarray(f_exp, dtype=dtype)
+        expected_chi2 = xp.asarray(expected_chi2, dtype=dtype)
+
+        # ddof has shape (2, 1).  This is broadcast with the computed
+        # statistic, so p will have shape (2,2).
+        ddof = xp.asarray([[0], [1]])
+
+        stat, p = stats.power_divergence(f_obs, f_exp, ddof=ddof)
+        xp_assert_close(stat, expected_chi2)
+
+        # Compute the p values separately, passing in scalars for ddof.
+        stat0, p0 = stats.power_divergence(f_obs, f_exp, ddof=ddof[0, 0])
+        stat1, p1 = stats.power_divergence(f_obs, f_exp, ddof=ddof[1, 0])
+
+        xp_test = array_namespace(f_obs)  # needs `concat`, `newaxis`
+        expected_p = xp_test.concat((p0[xp_test.newaxis, :],
+                                     p1[xp_test.newaxis, :]),
+                                    axis=0)
+        xp_assert_close(p, expected_p)
+
+    @pytest.mark.parametrize('case', power_div_empty_cases)
+    @pytest.mark.parametrize('lambda_stat',
+        [('pearson', 'chi2'), ('log-likelihood', 'log'),
+         ('mod-log-likelihood', 'mod_log'),
+         ('cressie-read', 'cr'), (2/3, 'cr')])
+    def test_empty_cases(self, case, lambda_stat, xp):
+        lambda_, attr = lambda_stat
+        expected_stat = getattr(case, attr)
+        with warnings.catch_warnings():
+            self.check_power_divergence(
+                case.f_obs, case.f_exp, case.ddof, case.axis,
+                lambda_, expected_stat, xp)
+
+    def test_power_divergence_result_attributes(self, xp):
+        f_obs = power_div_1d_cases[0].f_obs
+        f_exp = power_div_1d_cases[0].f_exp
+        ddof = power_div_1d_cases[0].ddof
+        axis = power_div_1d_cases[0].axis
+        dtype = xp.asarray(1.).dtype
+        f_obs = xp.asarray(f_obs, dtype=dtype)
+        # f_exp is None
+
+        res = stats.power_divergence(f_obs=f_obs, f_exp=f_exp, ddof=ddof,
+                                     axis=axis, lambda_="pearson")
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes, xp=xp)
+
+    def test_power_divergence_gh_12282(self, xp):
+        # The sums of observed and expected frequencies must match
+        f_obs = xp.asarray([[10., 20.], [30., 20.]])
+        f_exp = xp.asarray([[5., 15.], [35., 25.]])
+        message = 'For each axis slice...'
+        with pytest.raises(ValueError, match=message):
+            stats.power_divergence(f_obs=f_obs, f_exp=xp.asarray([30., 60.]))
+        with pytest.raises(ValueError, match=message):
+            stats.power_divergence(f_obs=f_obs, f_exp=f_exp, axis=1)
+        stat, pval = stats.power_divergence(f_obs=f_obs, f_exp=f_exp)
+        xp_assert_close(stat, xp.asarray([5.71428571, 2.66666667]))
+        xp_assert_close(pval, xp.asarray([0.01682741, 0.10247043]))
+
+    def test_power_divergence_against_cressie_read_data(self, xp):
+        # Test stats.power_divergence against tables 4 and 5 from
+        # Cressie and Read, "Multimonial Goodness-of-Fit Tests",
+        # J. R. Statist. Soc. B (1984), Vol 46, No. 3, pp. 440-464.
+        # This tests the calculation for several values of lambda.
+
+        # Table 4 data recalculated for greater precision according to:
+        # Shelby J. Haberman, Analysis of Qualitative Data: Volume 1
+        # Introductory Topics, Academic Press, New York, USA (1978).
+        obs = xp.asarray([15., 11., 14., 17., 5., 11., 10., 4., 8.,
+                          10., 7., 9., 11., 3., 6., 1., 1., 4.])
+        beta = -0.083769  # Haberman (1978), p. 15
+        i = xp.arange(1., obs.shape[0] + 1.)
+        alpha = xp.log(xp.sum(obs) / xp.sum(xp.exp(beta*i)))
+        expected_counts = xp.exp(alpha + beta*i)
+
+        # `table4` holds just the second and third columns from Table 4.
+        xp_test = array_namespace(obs)  # NumPy needs concat, torch needs newaxis
+        table4 = xp_test.concat((obs[xp_test.newaxis, :],
+                                 expected_counts[xp_test.newaxis, :])).T
+
+        table5 = xp.asarray([
+            # lambda, statistic
+            -10.0, 72.2e3,
+            -5.0, 28.9e1,
+            -3.0, 65.6,
+            -2.0, 40.6,
+            -1.5, 34.0,
+            -1.0, 29.5,
+            -0.5, 26.5,
+            0.0, 24.6,
+            0.5, 23.4,
+            0.67, 23.1,
+            1.0, 22.7,
+            1.5, 22.6,
+            2.0, 22.9,
+            3.0, 24.8,
+            5.0, 35.5,
+            10.0, 21.4e1,
+            ])
+        table5 = xp.reshape(table5, (-1, 2))
+
+        for i in range(table5.shape[0]):
+            lambda_, expected_stat = table5[i, 0], table5[i, 1]
+            stat, p = stats.power_divergence(table4[:,0], table4[:,1],
+                                             lambda_=lambda_)
+            xp_assert_close(stat, expected_stat, rtol=5e-3)
+
+
+@array_api_compatible
+class TestChisquare:
+    def test_chisquare_12282a(self, xp):
+        # Currently `chisquare` is implemented via power_divergence
+        # in case that ever changes, perform a basic test like
+        # test_power_divergence_gh_12282
+        with assert_raises(ValueError, match='For each axis slice...'):
+            f_obs = xp.asarray([10., 20.])
+            f_exp = xp.asarray([30., 60.])
+            stats.chisquare(f_obs=f_obs, f_exp=f_exp)
+
+    def test_chisquare_12282b(self, xp):
+        # Check that users can now disable the sum check tested in
+        # test_chisquare_12282a. Also, confirm that statistic and p-value
+        # are as expected.
+        rng = np.random.default_rng(3843874358728234)
+        n = 10
+        lam = rng.uniform(1000, 2000, size=n)
+        x = rng.poisson(lam)
+        lam = xp.asarray(lam)
+        x = xp.asarray(x, dtype=lam.dtype)
+        res = stats.chisquare(f_obs=x, f_exp=lam, ddof=-1, sum_check=False)
+        # Poisson is approximately normal with mean and variance lam
+        z = (x - lam) / xp.sqrt(lam)
+        statistic = xp.sum(z**2)
+        xp_assert_close(res.statistic, statistic)
+        # Sum of `n` squared standard normal variables follows chi2 with `n` DoF
+        X2 = _SimpleChi2(xp.asarray(n, dtype=statistic.dtype))
+        xp_assert_close(res.pvalue, X2.sf(statistic))
+
+    @pytest.mark.parametrize("n, dtype", [(200, 'uint8'), (1000000, 'int32')])
+    def test_chiquare_data_types_attributes(self, n, dtype, xp):
+        # Regression test for gh-10159 and gh-18368
+        dtype = getattr(xp, dtype)
+        obs = xp.asarray([n, 0], dtype=dtype)
+        exp = xp.asarray([n // 2, n // 2], dtype=dtype)
+        res = stats.chisquare(obs, exp)
+        stat, p = res
+        xp_assert_close(stat, xp.asarray(n, dtype=xp.asarray(1.).dtype), rtol=1e-13)
+        # check that attributes are identical to unpacked outputs - see gh-18368
+        xp_assert_equal(res.statistic, stat)
+        xp_assert_equal(res.pvalue, p)
+
+
+@skip_xp_invalid_arg
+class TestChisquareMA:
+    @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+    def test_chisquare_masked_arrays(self):
+        # Test masked arrays.
+        obs = np.array([[8, 8, 16, 32, -1], [-1, -1, 3, 4, 5]]).T
+        mask = np.array([[0, 0, 0, 0, 1], [1, 1, 0, 0, 0]]).T
+        mobs = np.ma.masked_array(obs, mask)
+        expected_chisq = np.array([24.0, 0.5])
+        expected_g = np.array([2*(2*8*np.log(0.5) + 32*np.log(2.0)),
+                               2*(3*np.log(0.75) + 5*np.log(1.25))])
+
+        chi2 = stats.distributions.chi2
+
+        chisq, p = stats.chisquare(mobs)
+        mat.assert_array_equal(chisq, expected_chisq)
+        mat.assert_array_almost_equal(p, chi2.sf(expected_chisq,
+                                                 mobs.count(axis=0) - 1))
+
+        g, p = stats.power_divergence(mobs, lambda_='log-likelihood')
+        mat.assert_array_almost_equal(g, expected_g, decimal=15)
+        mat.assert_array_almost_equal(p, chi2.sf(expected_g,
+                                                 mobs.count(axis=0) - 1))
+
+        chisq, p = stats.chisquare(mobs.T, axis=1)
+        mat.assert_array_equal(chisq, expected_chisq)
+        mat.assert_array_almost_equal(p, chi2.sf(expected_chisq,
+                                                 mobs.T.count(axis=1) - 1))
+        g, p = stats.power_divergence(mobs.T, axis=1, lambda_="log-likelihood")
+        mat.assert_array_almost_equal(g, expected_g, decimal=15)
+        mat.assert_array_almost_equal(p, chi2.sf(expected_g,
+                                                 mobs.count(axis=0) - 1))
+
+        obs1 = np.ma.array([3, 5, 6, 99, 10], mask=[0, 0, 0, 1, 0])
+        exp1 = np.ma.array([2, 4, 8, 10, 99], mask=[0, 0, 0, 0, 1])
+        chi2, p = stats.chisquare(obs1, f_exp=exp1)
+        # Because of the mask at index 3 of obs1 and at index 4 of exp1,
+        # only the first three elements are included in the calculation
+        # of the statistic.
+        mat.assert_array_equal(chi2, 1/2 + 1/4 + 4/8)
+
+        # When axis=None, the two values should have type np.float64.
+        chisq, p = stats.chisquare(np.ma.array([1,2,3]), axis=None)
+        assert_(isinstance(chisq, np.float64))
+        assert_(isinstance(p, np.float64))
+        assert_equal(chisq, 1.0)
+        assert_almost_equal(p, stats.distributions.chi2.sf(1.0, 2))
+
+        # Empty arrays:
+        # A data set with length 0 returns a masked scalar.
+        with np.errstate(invalid='ignore'):
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                chisq, p = stats.chisquare(np.ma.array([]))
+        assert_(isinstance(chisq, np.ma.MaskedArray))
+        assert_equal(chisq.shape, ())
+        assert_(chisq.mask)
+
+        empty3 = np.ma.array([[],[],[]])
+
+        # empty3 is a collection of 0 data sets (whose lengths would be 3, if
+        # there were any), so the return value is an array with length 0.
+        chisq, p = stats.chisquare(empty3)
+        assert_(isinstance(chisq, np.ma.MaskedArray))
+        mat.assert_array_equal(chisq, [])
+
+        # empty3.T is an array containing 3 data sets, each with length 0,
+        # so an array of size (3,) is returned, with all values masked.
+        with np.errstate(invalid='ignore'):
+            with suppress_warnings() as sup:
+                sup.filter(RuntimeWarning, "Mean of empty slice")
+                chisq, p = stats.chisquare(empty3.T)
+
+        assert_(isinstance(chisq, np.ma.MaskedArray))
+        assert_equal(chisq.shape, (3,))
+        assert_(np.all(chisq.mask))
+
+    def test_deprecation_warning(self):
+        a = np.asarray([1., 2., 3.])
+        ma = np.ma.masked_array(a)
+        message = "`power_divergence` and `chisquare` support for masked..."
+        with pytest.warns(DeprecationWarning, match=message):
+            stats.chisquare(ma)
+        with pytest.warns(DeprecationWarning, match=message):
+            stats.chisquare(a, ma)
+
+
+def test_friedmanchisquare():
+    # see ticket:113
+    # verified with matlab and R
+    # From Demsar "Statistical Comparisons of Classifiers over Multiple Data Sets"
+    # 2006, Xf=9.28 (no tie handling, tie corrected Xf >=9.28)
+    x1 = [array([0.763, 0.599, 0.954, 0.628, 0.882, 0.936, 0.661, 0.583,
+                 0.775, 1.0, 0.94, 0.619, 0.972, 0.957]),
+          array([0.768, 0.591, 0.971, 0.661, 0.888, 0.931, 0.668, 0.583,
+                 0.838, 1.0, 0.962, 0.666, 0.981, 0.978]),
+          array([0.771, 0.590, 0.968, 0.654, 0.886, 0.916, 0.609, 0.563,
+                 0.866, 1.0, 0.965, 0.614, 0.9751, 0.946]),
+          array([0.798, 0.569, 0.967, 0.657, 0.898, 0.931, 0.685, 0.625,
+                 0.875, 1.0, 0.962, 0.669, 0.975, 0.970])]
+
+    # From "Bioestadistica para las ciencias de la salud" Xf=18.95 p<0.001:
+    x2 = [array([4,3,5,3,5,3,2,5,4,4,4,3]),
+          array([2,2,1,2,3,1,2,3,2,1,1,3]),
+          array([2,4,3,3,4,3,3,4,4,1,2,1]),
+          array([3,5,4,3,4,4,3,3,3,4,4,4])]
+
+    # From Jerrorl H. Zar, "Biostatistical Analysis"(example 12.6),
+    # Xf=10.68, 0.005 < p < 0.01:
+    # Probability from this example is inexact
+    # using Chisquare approximation of Friedman Chisquare.
+    x3 = [array([7.0,9.9,8.5,5.1,10.3]),
+          array([5.3,5.7,4.7,3.5,7.7]),
+          array([4.9,7.6,5.5,2.8,8.4]),
+          array([8.8,8.9,8.1,3.3,9.1])]
+
+    assert_array_almost_equal(stats.friedmanchisquare(x1[0],x1[1],x1[2],x1[3]),
+                              (10.2283464566929, 0.0167215803284414))
+    assert_array_almost_equal(stats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]),
+                              (18.9428571428571, 0.000280938375189499))
+    assert_array_almost_equal(stats.friedmanchisquare(x3[0],x3[1],x3[2],x3[3]),
+                              (10.68, 0.0135882729582176))
+    assert_raises(ValueError, stats.friedmanchisquare,x3[0],x3[1])
+
+    # test for namedtuple attribute results
+    attributes = ('statistic', 'pvalue')
+    res = stats.friedmanchisquare(*x1)
+    check_named_results(res, attributes)
+
+    # test using mstats
+    assert_array_almost_equal(mstats.friedmanchisquare(x1[0], x1[1],
+                                                       x1[2], x1[3]),
+                              (10.2283464566929, 0.0167215803284414))
+    # the following fails
+    # assert_array_almost_equal(mstats.friedmanchisquare(x2[0],x2[1],x2[2],x2[3]),
+    #                           (18.9428571428571, 0.000280938375189499))
+    assert_array_almost_equal(mstats.friedmanchisquare(x3[0], x3[1],
+                                                       x3[2], x3[3]),
+                              (10.68, 0.0135882729582176))
+    assert_raises(ValueError, mstats.friedmanchisquare,x3[0],x3[1])
+
+
+class TestKSTest:
+    """Tests kstest and ks_1samp agree with K-S various sizes, alternatives, modes."""
+
+    def _testOne(self, x, alternative, expected_statistic, expected_prob,
+                 mode='auto', decimal=14):
+        result = stats.kstest(x, 'norm', alternative=alternative, mode=mode)
+        expected = np.array([expected_statistic, expected_prob])
+        assert_array_almost_equal(np.array(result), expected, decimal=decimal)
+
+    def _test_kstest_and_ks1samp(self, x, alternative, mode='auto', decimal=14):
+        result = stats.kstest(x, 'norm', alternative=alternative, mode=mode)
+        result_1samp = stats.ks_1samp(x, stats.norm.cdf,
+                                      alternative=alternative, mode=mode)
+        assert_array_almost_equal(np.array(result), result_1samp, decimal=decimal)
+
+    def test_namedtuple_attributes(self):
+        x = np.linspace(-1, 1, 9)
+        # test for namedtuple attribute results
+        attributes = ('statistic', 'pvalue')
+        res = stats.kstest(x, 'norm')
+        check_named_results(res, attributes)
+
+    def test_agree_with_ks_1samp(self):
+        x = np.linspace(-1, 1, 9)
+        self._test_kstest_and_ks1samp(x, 'two-sided')
+
+        x = np.linspace(-15, 15, 9)
+        self._test_kstest_and_ks1samp(x, 'two-sided')
+
+        x = [-1.23, 0.06, -0.60, 0.17, 0.66, -0.17, -0.08, 0.27, -0.98, -0.99]
+        self._test_kstest_and_ks1samp(x, 'two-sided')
+        self._test_kstest_and_ks1samp(x, 'greater', mode='exact')
+        self._test_kstest_and_ks1samp(x, 'less', mode='exact')
+
+    def test_pm_inf_gh20386(self):
+        # Check that gh-20386 is resolved - `kstest` does not
+        # return NaNs when both -inf and inf are in sample.
+        vals = [-np.inf, 0, 1, np.inf]
+        res = stats.kstest(vals, stats.cauchy.cdf)
+        ref = stats.kstest(vals, stats.cauchy.cdf, _no_deco=True)
+        assert np.all(np.isfinite(res))
+        assert_equal(res, ref)
+        assert not np.isnan(res.statistic)
+        assert not np.isnan(res.pvalue)
+
+    # missing: no test that uses *args
+
+
+class TestKSOneSample:
+    """
+    Tests kstest and ks_samp 1-samples with K-S various sizes, alternatives, modes.
+    """
+
+    def _testOne(self, x, alternative, expected_statistic, expected_prob,
+                 mode='auto', decimal=14):
+        result = stats.ks_1samp(x, stats.norm.cdf, alternative=alternative, mode=mode)
+        expected = np.array([expected_statistic, expected_prob])
+        assert_array_almost_equal(np.array(result), expected, decimal=decimal)
+
+    def test_namedtuple_attributes(self):
+        x = np.linspace(-1, 1, 9)
+        # test for namedtuple attribute results
+        attributes = ('statistic', 'pvalue')
+        res = stats.ks_1samp(x, stats.norm.cdf)
+        check_named_results(res, attributes)
+
+    def test_agree_with_r(self):
+        # comparing with some values from R
+        x = np.linspace(-1, 1, 9)
+        self._testOne(x, 'two-sided', 0.15865525393145705, 0.95164069201518386)
+
+        x = np.linspace(-15, 15, 9)
+        self._testOne(x, 'two-sided', 0.44435602715924361, 0.038850140086788665)
+
+        x = [-1.23, 0.06, -0.60, 0.17, 0.66, -0.17, -0.08, 0.27, -0.98, -0.99]
+        self._testOne(x, 'two-sided', 0.293580126801961, 0.293408463684361)
+        self._testOne(x, 'greater', 0.293580126801961, 0.146988835042376, mode='exact')
+        self._testOne(x, 'less', 0.109348552425692, 0.732768892470675, mode='exact')
+
+    def test_known_examples(self):
+        # the following tests rely on deterministically replicated rvs
+        x = stats.norm.rvs(loc=0.2, size=100, random_state=987654321)
+        self._testOne(x, 'two-sided', 0.12464329735846891, 0.089444888711820769,
+                      mode='asymp')
+        self._testOne(x, 'less', 0.12464329735846891, 0.040989164077641749)
+        self._testOne(x, 'greater', 0.0072115233216310994, 0.98531158590396228)
+
+    def test_ks1samp_allpaths(self):
+        # Check NaN input, output.
+        assert_(np.isnan(kolmogn(np.nan, 1, True)))
+        with assert_raises(ValueError, match='n is not integral: 1.5'):
+            kolmogn(1.5, 1, True)
+        assert_(np.isnan(kolmogn(-1, 1, True)))
+
+        dataset = np.asarray([
+            # Check x out of range
+            (101, 1, True, 1.0),
+            (101, 1.1, True, 1.0),
+            (101, 0, True, 0.0),
+            (101, -0.1, True, 0.0),
+
+            (32, 1.0 / 64, True, 0.0),  # Ruben-Gambino
+            (32, 1.0 / 64, False, 1.0),  # Ruben-Gambino
+
+            # Miller
+            (32, 0.5, True, 0.9999999363163307),
+            # Miller 2 * special.smirnov(32, 0.5)
+            (32, 0.5, False, 6.368366937916623e-08),
+
+            # Check some other paths
+            (32, 1.0 / 8, True, 0.34624229979775223),
+            (32, 1.0 / 4, True, 0.9699508336558085),
+            (1600, 0.49, False, 0.0),
+            # 2 * special.smirnov(1600, 1/16.0)
+            (1600, 1 / 16.0, False, 7.0837876229702195e-06),
+            # _kolmogn_DMTW
+            (1600, 14 / 1600, False, 0.99962357317602),
+            # _kolmogn_PelzGood
+            (1600, 1 / 32, False, 0.08603386296651416),
+        ])
+        FuncData(kolmogn, dataset, (0, 1, 2), 3).check(dtypes=[int, float, bool])
+
+    @pytest.mark.parametrize("ksfunc", [stats.kstest, stats.ks_1samp])
+    @pytest.mark.parametrize("alternative, x6val, ref_location, ref_sign",
+                             [('greater', 6, 6, +1),
+                              ('less', 7, 7, -1),
+                              ('two-sided', 6, 6, +1),
+                              ('two-sided', 7, 7, -1)])
+    def test_location_sign(self, ksfunc, alternative,
+                           x6val, ref_location, ref_sign):
+        # Test that location and sign corresponding with statistic are as
+        # expected. (Test is designed to be easy to predict.)
+        x = np.arange(10) + 0.5
+        x[6] = x6val
+        cdf = stats.uniform(scale=10).cdf
+        res = ksfunc(x, cdf, alternative=alternative)
+        assert_allclose(res.statistic, 0.1, rtol=1e-15)
+        assert res.statistic_location == ref_location
+        assert res.statistic_sign == ref_sign
+
+    # missing: no test that uses *args
+
+
+class TestKSTwoSamples:
+    """Tests 2-samples with K-S various sizes, alternatives, modes."""
+
+    def _testOne(self, x1, x2, alternative, expected_statistic, expected_prob,
+                 mode='auto'):
+        result = stats.ks_2samp(x1, x2, alternative, mode=mode)
+        expected = np.array([expected_statistic, expected_prob])
+        assert_array_almost_equal(np.array(result), expected)
+
+    def testSmall(self):
+        self._testOne([0], [1], 'two-sided', 1.0/1, 1.0)
+        self._testOne([0], [1], 'greater', 1.0/1, 0.5)
+        self._testOne([0], [1], 'less', 0.0/1, 1.0)
+        self._testOne([1], [0], 'two-sided', 1.0/1, 1.0)
+        self._testOne([1], [0], 'greater', 0.0/1, 1.0)
+        self._testOne([1], [0], 'less', 1.0/1, 0.5)
+
+    def testTwoVsThree(self):
+        data1 = np.array([1.0, 2.0])
+        data1p = data1 + 0.01
+        data1m = data1 - 0.01
+        data2 = np.array([1.0, 2.0, 3.0])
+        self._testOne(data1p, data2, 'two-sided', 1.0 / 3, 1.0)
+        self._testOne(data1p, data2, 'greater', 1.0 / 3, 0.7)
+        self._testOne(data1p, data2, 'less', 1.0 / 3, 0.7)
+        self._testOne(data1m, data2, 'two-sided', 2.0 / 3, 0.6)
+        self._testOne(data1m, data2, 'greater', 2.0 / 3, 0.3)
+        self._testOne(data1m, data2, 'less', 0, 1.0)
+
+    def testTwoVsFour(self):
+        data1 = np.array([1.0, 2.0])
+        data1p = data1 + 0.01
+        data1m = data1 - 0.01
+        data2 = np.array([1.0, 2.0, 3.0, 4.0])
+        self._testOne(data1p, data2, 'two-sided', 2.0 / 4, 14.0/15)
+        self._testOne(data1p, data2, 'greater', 2.0 / 4, 8.0/15)
+        self._testOne(data1p, data2, 'less', 1.0 / 4, 12.0/15)
+
+        self._testOne(data1m, data2, 'two-sided', 3.0 / 4, 6.0/15)
+        self._testOne(data1m, data2, 'greater', 3.0 / 4, 3.0/15)
+        self._testOne(data1m, data2, 'less', 0, 1.0)
+
+    def test100_100(self):
+        x100 = np.linspace(1, 100, 100)
+        x100_2_p1 = x100 + 2 + 0.1
+        x100_2_m1 = x100 + 2 - 0.1
+        self._testOne(x100, x100_2_p1, 'two-sided', 3.0 / 100, 0.9999999999962055)
+        self._testOne(x100, x100_2_p1, 'greater', 3.0 / 100, 0.9143290114276248)
+        self._testOne(x100, x100_2_p1, 'less', 0, 1.0)
+        self._testOne(x100, x100_2_m1, 'two-sided', 2.0 / 100, 1.0)
+        self._testOne(x100, x100_2_m1, 'greater', 2.0 / 100, 0.960978450786184)
+        self._testOne(x100, x100_2_m1, 'less', 0, 1.0)
+
+    def test100_110(self):
+        x100 = np.linspace(1, 100, 100)
+        x110 = np.linspace(1, 100, 110)
+        x110_20_p1 = x110 + 20 + 0.1
+        x110_20_m1 = x110 + 20 - 0.1
+        # 100, 110
+        self._testOne(x100, x110_20_p1, 'two-sided', 232.0 / 1100, 0.015739183865607353)
+        self._testOne(x100, x110_20_p1, 'greater', 232.0 / 1100, 0.007869594319053203)
+        self._testOne(x100, x110_20_p1, 'less', 0, 1)
+        self._testOne(x100, x110_20_m1, 'two-sided', 229.0 / 1100, 0.017803803861026313)
+        self._testOne(x100, x110_20_m1, 'greater', 229.0 / 1100, 0.008901905958245056)
+        self._testOne(x100, x110_20_m1, 'less', 0.0, 1.0)
+
+    def testRepeatedValues(self):
+        x2233 = np.array([2] * 3 + [3] * 4 + [5] * 5 + [6] * 4, dtype=int)
+        x3344 = x2233 + 1
+        x2356 = np.array([2] * 3 + [3] * 4 + [5] * 10 + [6] * 4, dtype=int)
+        x3467 = np.array([3] * 10 + [4] * 2 + [6] * 10 + [7] * 4, dtype=int)
+        self._testOne(x2233, x3344, 'two-sided', 5.0/16, 0.4262934613454952)
+        self._testOne(x2233, x3344, 'greater', 5.0/16, 0.21465428276573786)
+        self._testOne(x2233, x3344, 'less', 0.0/16, 1.0)
+        self._testOne(x2356, x3467, 'two-sided', 190.0/21/26, 0.0919245790168125)
+        self._testOne(x2356, x3467, 'greater', 190.0/21/26, 0.0459633806858544)
+        self._testOne(x2356, x3467, 'less', 70.0/21/26, 0.6121593130022775)
+
+    def testEqualSizes(self):
+        data2 = np.array([1.0, 2.0, 3.0])
+        self._testOne(data2, data2+1, 'two-sided', 1.0/3, 1.0)
+        self._testOne(data2, data2+1, 'greater', 1.0/3, 0.75)
+        self._testOne(data2, data2+1, 'less', 0.0/3, 1.)
+        self._testOne(data2, data2+0.5, 'two-sided', 1.0/3, 1.0)
+        self._testOne(data2, data2+0.5, 'greater', 1.0/3, 0.75)
+        self._testOne(data2, data2+0.5, 'less', 0.0/3, 1.)
+        self._testOne(data2, data2-0.5, 'two-sided', 1.0/3, 1.0)
+        self._testOne(data2, data2-0.5, 'greater', 0.0/3, 1.0)
+        self._testOne(data2, data2-0.5, 'less', 1.0/3, 0.75)
+
+    @pytest.mark.slow
+    def testMiddlingBoth(self):
+        # 500, 600
+        n1, n2 = 500, 600
+        delta = 1.0/n1/n2/2/2
+        x = np.linspace(1, 200, n1) - delta
+        y = np.linspace(2, 200, n2)
+        self._testOne(x, y, 'two-sided', 2000.0 / n1 / n2, 1.0,
+                      mode='auto')
+        self._testOne(x, y, 'two-sided', 2000.0 / n1 / n2, 1.0,
+                      mode='asymp')
+        self._testOne(x, y, 'greater', 2000.0 / n1 / n2, 0.9697596024683929,
+                      mode='asymp')
+        self._testOne(x, y, 'less', 500.0 / n1 / n2, 0.9968735843165021,
+                      mode='asymp')
+        with suppress_warnings() as sup:
+            message = "ks_2samp: Exact calculation unsuccessful."
+            sup.filter(RuntimeWarning, message)
+            self._testOne(x, y, 'greater', 2000.0 / n1 / n2, 0.9697596024683929,
+                          mode='exact')
+            self._testOne(x, y, 'less', 500.0 / n1 / n2, 0.9968735843165021,
+                          mode='exact')
+        with warnings.catch_warnings(record=True) as w:
+            warnings.simplefilter("always")
+            self._testOne(x, y, 'less', 500.0 / n1 / n2, 0.9968735843165021,
+                          mode='exact')
+            _check_warnings(w, RuntimeWarning, 1)
+
+    @pytest.mark.slow
+    def testMediumBoth(self):
+        # 1000, 1100
+        n1, n2 = 1000, 1100
+        delta = 1.0/n1/n2/2/2
+        x = np.linspace(1, 200, n1) - delta
+        y = np.linspace(2, 200, n2)
+        self._testOne(x, y, 'two-sided', 6600.0 / n1 / n2, 1.0,
+                      mode='asymp')
+        self._testOne(x, y, 'two-sided', 6600.0 / n1 / n2, 1.0,
+                      mode='auto')
+        self._testOne(x, y, 'greater', 6600.0 / n1 / n2, 0.9573185808092622,
+                      mode='asymp')
+        self._testOne(x, y, 'less', 1000.0 / n1 / n2, 0.9982410869433984,
+                      mode='asymp')
+
+        with suppress_warnings() as sup:
+            message = "ks_2samp: Exact calculation unsuccessful."
+            sup.filter(RuntimeWarning, message)
+            self._testOne(x, y, 'greater', 6600.0 / n1 / n2, 0.9573185808092622,
+                          mode='exact')
+            self._testOne(x, y, 'less', 1000.0 / n1 / n2, 0.9982410869433984,
+                          mode='exact')
+        with warnings.catch_warnings(record=True) as w:
+            warnings.simplefilter("always")
+            self._testOne(x, y, 'less', 1000.0 / n1 / n2, 0.9982410869433984,
+                          mode='exact')
+            _check_warnings(w, RuntimeWarning, 1)
+
+    def testLarge(self):
+        # 10000, 110
+        n1, n2 = 10000, 110
+        lcm = n1*11.0
+        delta = 1.0/n1/n2/2/2
+        x = np.linspace(1, 200, n1) - delta
+        y = np.linspace(2, 100, n2)
+        self._testOne(x, y, 'two-sided', 55275.0 / lcm, 4.2188474935755949e-15)
+        self._testOne(x, y, 'greater', 561.0 / lcm, 0.99115454582047591)
+        self._testOne(x, y, 'less', 55275.0 / lcm, 3.1317328311518713e-26)
+
+    def test_gh11184(self):
+        # 3000, 3001, exact two-sided
+        np.random.seed(123456)
+        x = np.random.normal(size=3000)
+        y = np.random.normal(size=3001) * 1.5
+        self._testOne(x, y, 'two-sided', 0.11292880151060758, 2.7755575615628914e-15,
+                      mode='asymp')
+        self._testOne(x, y, 'two-sided', 0.11292880151060758, 2.7755575615628914e-15,
+                      mode='exact')
+
+    @pytest.mark.xslow
+    def test_gh11184_bigger(self):
+        # 10000, 10001, exact two-sided
+        np.random.seed(123456)
+        x = np.random.normal(size=10000)
+        y = np.random.normal(size=10001) * 1.5
+        self._testOne(x, y, 'two-sided', 0.10597913208679133, 3.3149311398483503e-49,
+                      mode='asymp')
+        self._testOne(x, y, 'two-sided', 0.10597913208679133, 2.7755575615628914e-15,
+                      mode='exact')
+        self._testOne(x, y, 'greater', 0.10597913208679133, 2.7947433906389253e-41,
+                      mode='asymp')
+        self._testOne(x, y, 'less', 0.09658002199780022, 2.7947433906389253e-41,
+                      mode='asymp')
+
+    @pytest.mark.xslow
+    def test_gh12999(self):
+        np.random.seed(123456)
+        for x in range(1000, 12000, 1000):
+            vals1 = np.random.normal(size=(x))
+            vals2 = np.random.normal(size=(x + 10), loc=0.5)
+            exact = stats.ks_2samp(vals1, vals2, mode='exact').pvalue
+            asymp = stats.ks_2samp(vals1, vals2, mode='asymp').pvalue
+            # these two p-values should be in line with each other
+            assert_array_less(exact, 3 * asymp)
+            assert_array_less(asymp, 3 * exact)
+
+    @pytest.mark.slow
+    def testLargeBoth(self):
+        # 10000, 11000
+        n1, n2 = 10000, 11000
+        lcm = n1*11.0
+        delta = 1.0/n1/n2/2/2
+        x = np.linspace(1, 200, n1) - delta
+        y = np.linspace(2, 200, n2)
+        self._testOne(x, y, 'two-sided', 563.0 / lcm, 0.9990660108966576,
+                      mode='asymp')
+        self._testOne(x, y, 'two-sided', 563.0 / lcm, 0.9990456491488628,
+                      mode='exact')
+        self._testOne(x, y, 'two-sided', 563.0 / lcm, 0.9990660108966576,
+                      mode='auto')
+        self._testOne(x, y, 'greater', 563.0 / lcm, 0.7561851877420673)
+        self._testOne(x, y, 'less', 10.0 / lcm, 0.9998239693191724)
+        with suppress_warnings() as sup:
+            message = "ks_2samp: Exact calculation unsuccessful."
+            sup.filter(RuntimeWarning, message)
+            self._testOne(x, y, 'greater', 563.0 / lcm, 0.7561851877420673,
+                          mode='exact')
+            self._testOne(x, y, 'less', 10.0 / lcm, 0.9998239693191724,
+                          mode='exact')
+
+    def testNamedAttributes(self):
+        # test for namedtuple attribute results
+        attributes = ('statistic', 'pvalue')
+        res = stats.ks_2samp([1, 2], [3])
+        check_named_results(res, attributes)
+
+    @pytest.mark.slow
+    def test_some_code_paths(self):
+        # Check that some code paths are executed
+        from scipy.stats._stats_py import (
+            _count_paths_outside_method,
+            _compute_outer_prob_inside_method
+        )
+
+        _compute_outer_prob_inside_method(1, 1, 1, 1)
+        _count_paths_outside_method(1000, 1, 1, 1001)
+
+        with np.errstate(invalid='raise'):
+            assert_raises(FloatingPointError, _count_paths_outside_method,
+                          1100, 1099, 1, 1)
+            assert_raises(FloatingPointError, _count_paths_outside_method,
+                          2000, 1000, 1, 1)
+
+    @pytest.mark.parametrize('case', (([], [1]), ([1], []), ([], [])))
+    def test_argument_checking(self, case):
+        # Check that an empty array warns
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = stats.ks_2samp(*case)
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+    @pytest.mark.xslow
+    def test_gh12218(self):
+        """Ensure gh-12218 is fixed."""
+        # gh-1228 triggered a TypeError calculating sqrt(n1*n2*(n1+n2)).
+        # n1, n2 both large integers, the product exceeded 2^64
+        np.random.seed(12345678)
+        n1 = 2097152  # 2*^21
+        rvs1 = stats.uniform.rvs(size=n1, loc=0., scale=1)
+        rvs2 = rvs1 + 1  # Exact value of rvs2 doesn't matter.
+        stats.ks_2samp(rvs1, rvs2, alternative='greater', mode='asymp')
+        stats.ks_2samp(rvs1, rvs2, alternative='less', mode='asymp')
+        stats.ks_2samp(rvs1, rvs2, alternative='two-sided', mode='asymp')
+
+    def test_warnings_gh_14019(self):
+        # Check that RuntimeWarning is raised when method='auto' and exact
+        # p-value calculation fails. See gh-14019.
+        rng = np.random.RandomState(seed=23493549)
+        # random samples of the same size as in the issue
+        data1 = rng.random(size=881) + 0.5
+        data2 = rng.random(size=369)
+        message = "ks_2samp: Exact calculation unsuccessful"
+        with pytest.warns(RuntimeWarning, match=message):
+            res = stats.ks_2samp(data1, data2, alternative='less')
+            assert_allclose(res.pvalue, 0, atol=1e-14)
+
+    @pytest.mark.parametrize("ksfunc", [stats.kstest, stats.ks_2samp])
+    @pytest.mark.parametrize("alternative, x6val, ref_location, ref_sign",
+                             [('greater', 5.9, 5.9, +1),
+                              ('less', 6.1, 6.0, -1),
+                              ('two-sided', 5.9, 5.9, +1),
+                              ('two-sided', 6.1, 6.0, -1)])
+    def test_location_sign(self, ksfunc, alternative,
+                           x6val, ref_location, ref_sign):
+        # Test that location and sign corresponding with statistic are as
+        # expected. (Test is designed to be easy to predict.)
+        x = np.arange(10, dtype=np.float64)
+        y = x.copy()
+        x[6] = x6val
+        res = stats.ks_2samp(x, y, alternative=alternative)
+        assert res.statistic == 0.1
+        assert res.statistic_location == ref_location
+        assert res.statistic_sign == ref_sign
+
+
+def test_ttest_rel():
+    # regression test
+    tr,pr = 0.81248591389165692, 0.41846234511362157
+    tpr = ([tr,-tr],[pr,pr])
+
+    rvs1 = np.linspace(1,100,100)
+    rvs2 = np.linspace(1.01,99.989,100)
+    rvs1_2D = np.array([np.linspace(1,100,100), np.linspace(1.01,99.989,100)])
+    rvs2_2D = np.array([np.linspace(1.01,99.989,100), np.linspace(1,100,100)])
+
+    t,p = stats.ttest_rel(rvs1, rvs2, axis=0)
+    assert_array_almost_equal([t,p],(tr,pr))
+    t,p = stats.ttest_rel(rvs1_2D.T, rvs2_2D.T, axis=0)
+    assert_array_almost_equal([t,p],tpr)
+    t,p = stats.ttest_rel(rvs1_2D, rvs2_2D, axis=1)
+    assert_array_almost_equal([t,p],tpr)
+
+    # test scalars
+    with suppress_warnings() as sup, \
+            np.errstate(invalid="ignore", divide="ignore"):
+        sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice")
+        t, p = stats.ttest_rel(4., 3.)
+    assert_(np.isnan(t))
+    assert_(np.isnan(p))
+
+    # test for namedtuple attribute results
+    attributes = ('statistic', 'pvalue')
+    res = stats.ttest_rel(rvs1, rvs2, axis=0)
+    check_named_results(res, attributes)
+
+    # test on 3 dimensions
+    rvs1_3D = np.dstack([rvs1_2D,rvs1_2D,rvs1_2D])
+    rvs2_3D = np.dstack([rvs2_2D,rvs2_2D,rvs2_2D])
+    t,p = stats.ttest_rel(rvs1_3D, rvs2_3D, axis=1)
+    assert_array_almost_equal(np.abs(t), tr)
+    assert_array_almost_equal(np.abs(p), pr)
+    assert_equal(t.shape, (2, 3))
+
+    t, p = stats.ttest_rel(np.moveaxis(rvs1_3D, 2, 0),
+                           np.moveaxis(rvs2_3D, 2, 0),
+                           axis=2)
+    assert_array_almost_equal(np.abs(t), tr)
+    assert_array_almost_equal(np.abs(p), pr)
+    assert_equal(t.shape, (3, 2))
+
+    # test alternative parameter
+    assert_raises(ValueError, stats.ttest_rel, rvs1, rvs2, alternative="error")
+
+    t, p = stats.ttest_rel(rvs1, rvs2, axis=0, alternative="less")
+    assert_allclose(p, 1 - pr/2)
+    assert_allclose(t, tr)
+
+    t, p = stats.ttest_rel(rvs1, rvs2, axis=0, alternative="greater")
+    assert_allclose(p, pr/2)
+    assert_allclose(t, tr)
+
+    # check nan policy
+    rng = np.random.RandomState(12345678)
+    x = stats.norm.rvs(loc=5, scale=10, size=501, random_state=rng)
+    x[500] = np.nan
+    y = (stats.norm.rvs(loc=5, scale=10, size=501, random_state=rng) +
+         stats.norm.rvs(scale=0.2, size=501, random_state=rng))
+    y[500] = np.nan
+
+    with np.errstate(invalid="ignore"):
+        assert_array_equal(stats.ttest_rel(x, x), (np.nan, np.nan))
+
+    assert_array_almost_equal(stats.ttest_rel(x, y, nan_policy='omit'),
+                              (0.25299925303978066, 0.8003729814201519))
+    assert_raises(ValueError, stats.ttest_rel, x, y, nan_policy='raise')
+    assert_raises(ValueError, stats.ttest_rel, x, y, nan_policy='foobar')
+
+    # test zero division problem
+    with pytest.warns(RuntimeWarning, match="Precision loss occurred"):
+        t, p = stats.ttest_rel([0, 0, 0], [1, 1, 1])
+    assert_equal((np.abs(t), p), (np.inf, 0))
+    with np.errstate(invalid="ignore"):
+        assert_equal(stats.ttest_rel([0, 0, 0], [0, 0, 0]), (np.nan, np.nan))
+
+        # check that nan in input array result in nan output
+        anan = np.array([[1, np.nan], [-1, 1]])
+        assert_equal(stats.ttest_rel(anan, np.zeros((2, 2))),
+                     ([0, np.nan], [1, np.nan]))
+
+    # test incorrect input shape raise an error
+    x = np.arange(24)
+    assert_raises(ValueError, stats.ttest_rel, x.reshape((8, 3)),
+                  x.reshape((2, 3, 4)))
+
+    # Convert from two-sided p-values to one sided using T result data.
+    def convert(t, p, alt):
+        if (t < 0 and alt == "less") or (t > 0 and alt == "greater"):
+            return p / 2
+        return 1 - (p / 2)
+    converter = np.vectorize(convert)
+
+    rvs1_2D[:, 20:30] = np.nan
+    rvs2_2D[:, 15:25] = np.nan
+
+    with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
+        tr, pr = stats.ttest_rel(rvs1_2D, rvs2_2D, 0, nan_policy='omit')
+
+    with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
+        t, p = stats.ttest_rel(rvs1_2D, rvs2_2D, 0,
+                               nan_policy='omit', alternative='less')
+    assert_allclose(t, tr, rtol=1e-14)
+    with np.errstate(invalid='ignore'):
+        assert_allclose(p, converter(tr, pr, 'less'), rtol=1e-14)
+
+    with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
+        t, p = stats.ttest_rel(rvs1_2D, rvs2_2D, 0,
+                               nan_policy='omit', alternative='greater')
+    assert_allclose(t, tr, rtol=1e-14)
+    with np.errstate(invalid='ignore'):
+        assert_allclose(p, converter(tr, pr, 'greater'), rtol=1e-14)
+
+
+def test_ttest_rel_nan_2nd_arg():
+    # regression test for gh-6134: nans in the second arg were not handled
+    x = [np.nan, 2.0, 3.0, 4.0]
+    y = [1.0, 2.0, 1.0, 2.0]
+
+    r1 = stats.ttest_rel(x, y, nan_policy='omit')
+    r2 = stats.ttest_rel(y, x, nan_policy='omit')
+    assert_allclose(r2.statistic, -r1.statistic, atol=1e-15)
+    assert_allclose(r2.pvalue, r1.pvalue, atol=1e-15)
+
+    # NB: arguments are paired when NaNs are dropped
+    r3 = stats.ttest_rel(y[1:], x[1:])
+    assert_allclose(r2, r3, atol=1e-15)
+
+    # .. and this is consistent with R. R code:
+    # x = c(NA, 2.0, 3.0, 4.0)
+    # y = c(1.0, 2.0, 1.0, 2.0)
+    # t.test(x, y, paired=TRUE)
+    assert_allclose(r2, (-2, 0.1835), atol=1e-4)
+
+
+def test_ttest_rel_empty_1d_returns_nan():
+    # Two empty inputs should return a TtestResult containing nan
+    # for both values.
+    with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+        result = stats.ttest_rel([], [])
+    assert isinstance(result, stats._stats_py.TtestResult)
+    assert_equal(result, (np.nan, np.nan))
+
+
+@pytest.mark.parametrize('b, expected_shape',
+                         [(np.empty((1, 5, 0)), (3, 5)),
+                          (np.empty((1, 0, 0)), (3, 0))])
+def test_ttest_rel_axis_size_zero(b, expected_shape):
+    # In this test, the length of the axis dimension is zero.
+    # The results should be arrays containing nan with shape
+    # given by the broadcast nonaxis dimensions.
+    a = np.empty((3, 1, 0))
+    with np.testing.suppress_warnings() as sup:
+        # first case should warn, second shouldn't?
+        sup.filter(SmallSampleWarning, too_small_nd_not_omit)
+        result = stats.ttest_rel(a, b, axis=-1)
+    assert isinstance(result, stats._stats_py.TtestResult)
+    expected_value = np.full(expected_shape, fill_value=np.nan)
+    assert_equal(result.statistic, expected_value)
+    assert_equal(result.pvalue, expected_value)
+
+
+def test_ttest_rel_nonaxis_size_zero():
+    # In this test, the length of the axis dimension is nonzero,
+    # but one of the nonaxis dimensions has length 0.  Check that
+    # we still get the correctly broadcast shape, which is (5, 0)
+    # in this case.
+    a = np.empty((1, 8, 0))
+    b = np.empty((5, 8, 1))
+    result = stats.ttest_rel(a, b, axis=1)
+    assert isinstance(result, stats._stats_py.TtestResult)
+    assert_equal(result.statistic.shape, (5, 0))
+    assert_equal(result.pvalue.shape, (5, 0))
+
+
+@pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater'])
+def test_ttest_rel_ci_1d(alternative):
+    # test confidence interval method against reference values
+    rng = np.random.default_rng(3749065329432213059)
+    n = 10
+    x = rng.normal(size=n, loc=1.5, scale=2)
+    y = rng.normal(size=n, loc=2, scale=2)
+    # Reference values generated with R t.test:
+    # options(digits=16)
+    # x = c(1.22825792,  1.63950485,  4.39025641,  0.68609437,  2.03813481,
+    #       -1.20040109,  1.81997937,  1.86854636,  2.94694282,  3.94291373)
+    # y = c(3.49961496, 1.53192536, 5.53620083, 2.91687718, 0.04858043,
+    #       3.78505943, 3.3077496 , 2.30468892, 3.42168074, 0.56797592)
+    # t.test(x, y, paired=TRUE, conf.level=0.85, alternative='l')
+
+    ref = {'two-sided': [-1.912194489914035, 0.400169725914035],
+           'greater': [-1.563944820311475, np.inf],
+           'less': [-np.inf, 0.05192005631147523]}
+    res = stats.ttest_rel(x, y, alternative=alternative)
+    ci = res.confidence_interval(confidence_level=0.85)
+    assert_allclose(ci, ref[alternative])
+    assert_equal(res.df, n-1)
+
+
+@pytest.mark.parametrize("test_fun, args",
+                         [(stats.ttest_1samp, (np.arange(10), 0)),
+                          (stats.ttest_rel, (np.arange(10), np.arange(10)))])
+def test_ttest_ci_iv(test_fun, args):
+    # test `confidence_interval` method input validation
+    res = test_fun(*args)
+    message = '`confidence_level` must be a number between 0 and 1.'
+    with pytest.raises(ValueError, match=message):
+        res.confidence_interval(confidence_level=10)
+
+
+def _desc_stats(x1, x2, axis=0, *, xp=None):
+    xp = array_namespace(x1, x2) if xp is None else xp
+
+    def _stats(x, axis=0):
+        x = xp.asarray(x)
+        mu = xp.mean(x, axis=axis)
+        std = xp.std(x, axis=axis, correction=1)
+        nobs = x.shape[axis]
+        return mu, std, nobs
+
+    return _stats(x1, axis) + _stats(x2, axis)
+
+
+@array_api_compatible
+@pytest.mark.skip_xp_backends(cpu_only=True,
+                              reason='Uses NumPy for pvalue, CI')
+@pytest.mark.usefixtures("skip_xp_backends")
+def test_ttest_ind(xp):
+    # regression test
+    tr = xp.asarray(1.0912746897927283)
+    pr = xp.asarray(0.27647818616351882)
+    tr_2D = xp.asarray([tr, -tr])
+    pr_2D = xp.asarray([pr, pr])
+
+    rvs1 = xp.linspace(5, 105, 100)
+    rvs2 = xp.linspace(1, 100, 100)
+    rvs1_2D = xp.stack([rvs1, rvs2])
+    rvs2_2D = xp.stack([rvs2, rvs1])
+
+    res = stats.ttest_ind(rvs1, rvs2, axis=0)
+    t, p = res  # check that result object can be unpacked
+    xp_assert_close(t, tr)
+    xp_assert_close(p, pr)
+
+    res = stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs2))
+    t, p = res  # check that result object can be unpacked
+    xp_assert_close(t, tr)
+    xp_assert_close(p, pr)
+
+    res = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0)
+    xp_assert_close(res.statistic, tr_2D)
+    xp_assert_close(res.pvalue, pr_2D)
+
+    res = stats.ttest_ind_from_stats(*_desc_stats(rvs1_2D.T, rvs2_2D.T))
+    xp_assert_close(res.statistic, tr_2D)
+    xp_assert_close(res.pvalue, pr_2D)
+
+    res = stats.ttest_ind(rvs1_2D, rvs2_2D, axis=1)
+    xp_assert_close(res.statistic, tr_2D)
+    xp_assert_close(res.pvalue, pr_2D)
+
+    res = stats.ttest_ind_from_stats(*_desc_stats(rvs1_2D, rvs2_2D, axis=1))
+    xp_assert_close(res.statistic, tr_2D)
+    xp_assert_close(res.pvalue, pr_2D)
+
+    # test on 3 dimensions removed because generic tests in
+    # test_axis_nan_policy are much stronger
+
+    # test alternative parameter
+    message = "`alternative` must be 'less', 'greater', or 'two-sided'."
+    with pytest.raises(ValueError, match=message):
+        stats.ttest_ind(rvs1, rvs2, alternative = "error")
+
+    args = _desc_stats(rvs1_2D.T, rvs2_2D.T)
+    with pytest.raises(ValueError, match=message):
+        stats.ttest_ind_from_stats(*args, alternative = "error")
+
+    t, p = stats.ttest_ind(rvs1, rvs2, alternative="less")
+    xp_assert_close(p, 1 - (pr/2))
+    xp_assert_close(t, tr)
+
+    t, p = stats.ttest_ind(rvs1, rvs2, alternative="greater")
+    xp_assert_close(p, pr/2)
+    xp_assert_close(t, tr)
+
+    # Check that ttest_ind_from_stats agrees with ttest_ind
+    res1 = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0, alternative="less")
+    args = _desc_stats(rvs1_2D.T, rvs2_2D.T)
+    res2 = stats.ttest_ind_from_stats(*args, alternative="less")
+    xp_assert_close(res1.statistic, res2.statistic)
+    xp_assert_close(res1.pvalue, res2.pvalue)
+
+    res1 = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0, alternative="less")
+    args = _desc_stats(rvs1_2D.T, rvs2_2D.T)
+    res2 = stats.ttest_ind_from_stats(*args, alternative="less")
+    xp_assert_close(res1.statistic, res2.statistic)
+    xp_assert_close(res1.pvalue, res2.pvalue)
+
+    # test NaNs
+    NaN = xp.asarray(xp.nan)
+    rvs1 = xp.where(xp.arange(rvs1.shape[0]) == 0, NaN, rvs1)
+
+    res = stats.ttest_ind(rvs1, rvs2, axis=0)
+    xp_assert_equal(res.statistic, NaN)
+    xp_assert_equal(res.pvalue, NaN)
+
+    res = stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs2))
+    xp_assert_equal(res.statistic, NaN)
+    xp_assert_equal(res.pvalue, NaN)
+
+
+def test_ttest_ind_nan_policy():
+    rvs1 = np.linspace(5, 105, 100)
+    rvs2 = np.linspace(1, 100, 100)
+    rvs1_2D = np.array([rvs1, rvs2])
+    rvs2_2D = np.array([rvs2, rvs1])
+    rvs1_3D = np.dstack([rvs1_2D, rvs1_2D, rvs1_2D])
+    rvs2_3D = np.dstack([rvs2_2D, rvs2_2D, rvs2_2D])
+
+    # check nan policy
+    rng = np.random.RandomState(12345678)
+    x = stats.norm.rvs(loc=5, scale=10, size=501, random_state=rng)
+    x[500] = np.nan
+    y = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
+
+    with np.errstate(invalid="ignore"):
+        assert_array_equal(stats.ttest_ind(x, y), (np.nan, np.nan))
+
+    assert_array_almost_equal(stats.ttest_ind(x, y, nan_policy='omit'),
+                              (0.24779670949091914, 0.80434267337517906))
+    assert_raises(ValueError, stats.ttest_ind, x, y, nan_policy='raise')
+    assert_raises(ValueError, stats.ttest_ind, x, y, nan_policy='foobar')
+
+    # test zero division problem
+    with pytest.warns(RuntimeWarning, match="Precision loss occurred"):
+        t, p = stats.ttest_ind([0, 0, 0], [1, 1, 1])
+    assert_equal((np.abs(t), p), (np.inf, 0))
+
+    with np.errstate(invalid="ignore"):
+        assert_equal(stats.ttest_ind([0, 0, 0], [0, 0, 0]), (np.nan, np.nan))
+
+        # check that nan in input array result in nan output
+        anan = np.array([[1, np.nan], [-1, 1]])
+        assert_equal(stats.ttest_ind(anan, np.zeros((2, 2))),
+                     ([0, np.nan], [1, np.nan]))
+
+    rvs1_3D[:, :, 10:15] = np.nan
+    rvs2_3D[:, :, 6:12] = np.nan
+
+    # Convert from two-sided p-values to one sided using T result data.
+    def convert(t, p, alt):
+        if (t < 0 and alt == "less") or (t > 0 and alt == "greater"):
+            return p / 2
+        return 1 - (p / 2)
+    converter = np.vectorize(convert)
+
+    tr, pr = stats.ttest_ind(rvs1_3D, rvs2_3D, axis=0, nan_policy='omit')
+
+    t, p = stats.ttest_ind(rvs1_3D, rvs2_3D, axis=0, nan_policy='omit',
+                           alternative='less')
+    assert_allclose(t, tr, rtol=1e-14)
+    assert_allclose(p, converter(tr, pr, 'less'), rtol=1e-14)
+
+    t, p = stats.ttest_ind(rvs1_3D, rvs2_3D, axis=0, nan_policy='omit',
+                           alternative='greater')
+    assert_allclose(t, tr, rtol=1e-14)
+    assert_allclose(p, converter(tr, pr, 'greater'), rtol=1e-14)
+
+
+def test_ttest_ind_scalar():
+    # test scalars
+    with suppress_warnings() as sup, np.errstate(invalid="ignore"):
+        sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice")
+        t, p = stats.ttest_ind(4., 3.)
+    assert np.isnan(t)
+    assert np.isnan(p)
+
+
+@pytest.mark.filterwarnings("ignore:Arguments...:DeprecationWarning")
+class Test_ttest_ind_permutations:
+    N = 20
+
+    # data for most tests
+    np.random.seed(0)
+    a = np.vstack((np.arange(3*N//4), np.random.random(3*N//4)))
+    b = np.vstack((np.arange(N//4) + 100, np.random.random(N//4)))
+
+    # data for equal variance tests
+    a2 = np.arange(10)
+    b2 = np.arange(10) + 100
+
+    # data for exact test
+    a3 = [1, 2]
+    b3 = [3, 4]
+
+    # data for bigger test
+    np.random.seed(0)
+    rvs1 = stats.norm.rvs(loc=5, scale=10,  # type: ignore
+                          size=500).reshape(100, 5).T
+    rvs2 = stats.norm.rvs(loc=8, scale=20, size=100)  # type: ignore
+
+    p_d = [1/1001, (676+1)/1001]  # desired pvalues
+    p_d_gen = [1/1001, (672 + 1)/1001]  # desired pvalues for Generator seed
+    p_d_big = [(993+1)/1001, (685+1)/1001, (840+1)/1001,
+               (955+1)/1001, (255+1)/1001]
+
+    params = [
+        (a, b, {"axis": 1}, p_d),                     # basic test
+        (a.T, b.T, {'axis': 0}, p_d),                 # along axis 0
+        (a[0, :], b[0, :], {'axis': None}, p_d[0]),   # 1d data
+        (a[0, :].tolist(), b[0, :].tolist(), {'axis': None}, p_d[0]),
+        # different seeds
+        (a, b, {'random_state': 0, "axis": 1}, p_d),
+        (a, b, {'random_state': np.random.RandomState(0), "axis": 1}, p_d),
+        (a2, b2, {'equal_var': True}, 1/1001),  # equal variances
+        (rvs1, rvs2, {'axis': -1, 'random_state': 0}, p_d_big),  # bigger test
+        (a3, b3, {}, 1/3),  # exact test
+        (a, b, {'random_state': np.random.default_rng(0), "axis": 1}, p_d_gen),
+        ]
+
+    @pytest.mark.parametrize("a,b,update,p_d", params)
+    def test_ttest_ind_permutations(self, a, b, update, p_d):
+        options_a = {'axis': None, 'equal_var': False}
+        options_p = {'axis': None, 'equal_var': False,
+                     'permutations': 1000, 'random_state': 0}
+        options_a.update(update)
+        options_p.update(update)
+
+        stat_a, _ = stats.ttest_ind(a, b, **options_a)
+        stat_p, pvalue = stats.ttest_ind(a, b, **options_p)
+        assert_array_almost_equal(stat_a, stat_p, 5)
+        assert_array_almost_equal(pvalue, p_d)
+
+    def test_ttest_ind_exact_alternative(self):
+        np.random.seed(0)
+        N = 3
+        a = np.random.rand(2, N, 2)
+        b = np.random.rand(2, N, 2)
+
+        options_p = {'axis': 1, 'permutations': 1000}
+
+        options_p.update(alternative="greater")
+        res_g_ab = stats.ttest_ind(a, b, **options_p)
+        res_g_ba = stats.ttest_ind(b, a, **options_p)
+
+        options_p.update(alternative="less")
+        res_l_ab = stats.ttest_ind(a, b, **options_p)
+        res_l_ba = stats.ttest_ind(b, a, **options_p)
+
+        options_p.update(alternative="two-sided")
+        res_2_ab = stats.ttest_ind(a, b, **options_p)
+        res_2_ba = stats.ttest_ind(b, a, **options_p)
+
+        # Alternative doesn't affect the statistic
+        assert_equal(res_g_ab.statistic, res_l_ab.statistic)
+        assert_equal(res_g_ab.statistic, res_2_ab.statistic)
+
+        # Reversing order of inputs negates statistic
+        assert_equal(res_g_ab.statistic, -res_g_ba.statistic)
+        assert_equal(res_l_ab.statistic, -res_l_ba.statistic)
+        assert_equal(res_2_ab.statistic, -res_2_ba.statistic)
+
+        # Reversing order of inputs does not affect p-value of 2-sided test
+        assert_equal(res_2_ab.pvalue, res_2_ba.pvalue)
+
+        # In exact test, distribution is perfectly symmetric, so these
+        # identities are exactly satisfied.
+        assert_equal(res_g_ab.pvalue, res_l_ba.pvalue)
+        assert_equal(res_l_ab.pvalue, res_g_ba.pvalue)
+        mask = res_g_ab.pvalue <= 0.5
+        assert_equal(res_g_ab.pvalue[mask] + res_l_ba.pvalue[mask],
+                     res_2_ab.pvalue[mask])
+        assert_equal(res_l_ab.pvalue[~mask] + res_g_ba.pvalue[~mask],
+                     res_2_ab.pvalue[~mask])
+
+    def test_ttest_ind_exact_selection(self):
+        # test the various ways of activating the exact test
+        np.random.seed(0)
+        N = 3
+        a = np.random.rand(N)
+        b = np.random.rand(N)
+        res0 = stats.ttest_ind(a, b)
+        res1 = stats.ttest_ind(a, b, permutations=1000)
+        res2 = stats.ttest_ind(a, b, permutations=0)
+        res3 = stats.ttest_ind(a, b, permutations=np.inf)
+        assert res1.pvalue != res0.pvalue
+        assert res2.pvalue == res0.pvalue
+        assert res3.pvalue == res1.pvalue
+
+    def test_ttest_ind_exact_distribution(self):
+        # the exact distribution of the test statistic should have
+        # binom(na + nb, na) elements, all unique. This was not always true
+        # in gh-4824; fixed by gh-13661.
+        np.random.seed(0)
+        a = np.random.rand(3)
+        b = np.random.rand(4)
+
+        data = np.concatenate((a, b))
+        na, nb = len(a), len(b)
+
+        permutations = 100000
+        t_stat, _, _ = _permutation_distribution_t(data, permutations, na,
+                                                   True)
+
+        n_unique = len(set(t_stat))
+        assert n_unique == binom(na + nb, na)
+        assert len(t_stat) == n_unique
+
+    def test_ttest_ind_randperm_alternative(self):
+        np.random.seed(0)
+        N = 50
+        a = np.random.rand(2, 3, N)
+        b = np.random.rand(3, N)
+        options_p = {'axis': -1, 'permutations': 1000, "random_state": 0}
+
+        options_p.update(alternative="greater")
+        res_g_ab = stats.ttest_ind(a, b, **options_p)
+        res_g_ba = stats.ttest_ind(b, a, **options_p)
+
+        options_p.update(alternative="less")
+        res_l_ab = stats.ttest_ind(a, b, **options_p)
+        res_l_ba = stats.ttest_ind(b, a, **options_p)
+
+        # Alternative doesn't affect the statistic
+        assert_equal(res_g_ab.statistic, res_l_ab.statistic)
+
+        # Reversing order of inputs negates statistic
+        assert_equal(res_g_ab.statistic, -res_g_ba.statistic)
+        assert_equal(res_l_ab.statistic, -res_l_ba.statistic)
+
+        # For random permutations, the chance of ties between the observed
+        # test statistic and the population is small, so:
+        assert_equal(res_g_ab.pvalue + res_l_ab.pvalue,
+                     1 + 1/(options_p['permutations'] + 1))
+        assert_equal(res_g_ba.pvalue + res_l_ba.pvalue,
+                     1 + 1/(options_p['permutations'] + 1))
+
+    @pytest.mark.slow()
+    def test_ttest_ind_randperm_alternative2(self):
+        np.random.seed(0)
+        N = 50
+        a = np.random.rand(N, 4)
+        b = np.random.rand(N, 4)
+        options_p = {'permutations': 20000, "random_state": 0}
+
+        options_p.update(alternative="greater")
+        res_g_ab = stats.ttest_ind(a, b, **options_p)
+
+        options_p.update(alternative="less")
+        res_l_ab = stats.ttest_ind(a, b, **options_p)
+
+        options_p.update(alternative="two-sided")
+        res_2_ab = stats.ttest_ind(a, b, **options_p)
+
+        # For random permutations, the chance of ties between the observed
+        # test statistic and the population is small, so:
+        assert_equal(res_g_ab.pvalue + res_l_ab.pvalue,
+                     1 + 1/(options_p['permutations'] + 1))
+
+        # For for large sample sizes, the distribution should be approximately
+        # symmetric, so these identities should be approximately satisfied
+        mask = res_g_ab.pvalue <= 0.5
+        assert_allclose(2 * res_g_ab.pvalue[mask],
+                        res_2_ab.pvalue[mask], atol=2e-2)
+        assert_allclose(2 * (1-res_g_ab.pvalue[~mask]),
+                        res_2_ab.pvalue[~mask], atol=2e-2)
+        assert_allclose(2 * res_l_ab.pvalue[~mask],
+                        res_2_ab.pvalue[~mask], atol=2e-2)
+        assert_allclose(2 * (1-res_l_ab.pvalue[mask]),
+                        res_2_ab.pvalue[mask], atol=2e-2)
+
+    def test_ttest_ind_permutation_nanpolicy(self):
+        np.random.seed(0)
+        N = 50
+        a = np.random.rand(N, 5)
+        b = np.random.rand(N, 5)
+        a[5, 1] = np.nan
+        b[8, 2] = np.nan
+        a[9, 3] = np.nan
+        b[9, 3] = np.nan
+        options_p = {'permutations': 1000, "random_state": 0}
+
+        # Raise
+        options_p.update(nan_policy="raise")
+        with assert_raises(ValueError, match="The input contains nan values"):
+            res = stats.ttest_ind(a, b, **options_p)
+
+        # Propagate
+        with suppress_warnings() as sup:
+            sup.record(RuntimeWarning, "invalid value*")
+            options_p.update(nan_policy="propagate")
+            res = stats.ttest_ind(a, b, **options_p)
+
+            mask = np.isnan(a).any(axis=0) | np.isnan(b).any(axis=0)
+            res2 = stats.ttest_ind(a[:, ~mask], b[:, ~mask], **options_p)
+
+            assert_equal(res.pvalue[mask], np.nan)
+            assert_equal(res.statistic[mask], np.nan)
+
+            assert_allclose(res.pvalue[~mask], res2.pvalue)
+            assert_allclose(res.statistic[~mask], res2.statistic)
+
+            # Propagate 1d
+            res = stats.ttest_ind(a.ravel(), b.ravel(), **options_p)
+            assert np.isnan(res.pvalue)  # assert makes sure it's a scalar
+            assert np.isnan(res.statistic)
+
+    def test_ttest_ind_permutation_check_inputs(self):
+        with assert_raises(ValueError, match="Permutations must be"):
+            stats.ttest_ind(self.a2, self.b2, permutations=-3)
+        with assert_raises(ValueError, match="Permutations must be"):
+            stats.ttest_ind(self.a2, self.b2, permutations=1.5)
+        with assert_raises(ValueError, match="'hello' cannot be used"):
+            stats.ttest_ind(self.a, self.b, permutations=1,
+                            random_state='hello', axis=1)
+
+    def test_ttest_ind_permutation_check_p_values(self):
+        # p-values should never be exactly zero
+        N = 10
+        a = np.random.rand(N, 20)
+        b = np.random.rand(N, 20)
+        p_values = stats.ttest_ind(a, b, permutations=1).pvalue
+        print(0.0 not in p_values)
+        assert 0.0 not in p_values
+
+    @pytest.mark.parametrize("alternative", ['less', 'greater', 'two-sided'])
+    @pytest.mark.parametrize("shape", [(12,), (2, 12)])
+    def test_permutation_method(self, alternative, shape):
+        rng = np.random.default_rng(2348934579834565)
+        x = rng.random(size=shape)
+        y = rng.random(size=13)
+
+        kwargs = dict(n_resamples=999)
+
+        # Use ttest_ind with `method`
+        rng = np.random.default_rng(348934579834565)
+        method = stats.PermutationMethod(rng=rng, **kwargs)
+        res = stats.ttest_ind(x, y, axis=-1, alternative=alternative, method=method)
+
+        # Use `permutation_test` directly
+        def statistic(x, y, axis): return stats.ttest_ind(x, y, axis=axis).statistic
+        rng =  np.random.default_rng(348934579834565)
+        ref = stats.permutation_test((x, y), statistic, axis=-1, rng=rng,
+                                     alternative=alternative, **kwargs)
+
+        assert_equal(res.statistic, ref.statistic)
+        assert_equal(res.pvalue, ref.pvalue)
+
+        # Sanity check against theoretical t-test
+        ref = stats.ttest_ind(x, y, axis=-1, alternative=alternative)
+        assert_equal(res.statistic, ref.statistic)
+        assert_allclose(res.pvalue, ref.pvalue, rtol=3e-2)
+
+    @pytest.mark.parametrize("alternative", ['less', 'greater', 'two-sided'])
+    @pytest.mark.parametrize("shape", [(12,), (2, 12)])
+    def test_monte_carlo_method(self, alternative, shape):
+        rng = np.random.default_rng(2348934579834565)
+        x = rng.random(size=shape)
+        y = rng.random(size=13)
+
+        kwargs = dict(n_resamples=999)
+
+        # Use `monte_carlo` directly
+        def statistic(x, y, axis): return stats.ttest_ind(x, y, axis=axis).statistic
+        rng = np.random.default_rng(348934579834565)
+        rvs = [rng.standard_normal, rng.standard_normal]
+        ref = stats.monte_carlo_test((x, y), rvs=rvs, statistic=statistic, axis=-1,
+                                     alternative=alternative, **kwargs)
+
+        # Use ttest_ind with `method`
+        rng = np.random.default_rng(348934579834565)
+        rvs = [rng.standard_normal, rng.standard_normal]
+        method = stats.MonteCarloMethod(rvs=rvs, **kwargs)
+        res = stats.ttest_ind(x, y, axis=-1, alternative=alternative, method=method)
+        assert_equal(res.statistic, ref.statistic)
+        assert_equal(res.pvalue, ref.pvalue)
+
+        # Passing `rng` instead of `rvs`
+        method = stats.MonteCarloMethod(rng=348934579834565, **kwargs)
+        res = stats.ttest_ind(x, y, axis=-1, alternative=alternative, method=method)
+        assert_equal(res.statistic, ref.statistic)
+        assert_equal(res.pvalue, ref.pvalue)
+
+        # Sanity check against theoretical t-test
+        ref = stats.ttest_ind(x, y, axis=-1, alternative=alternative)
+        assert_equal(res.statistic, ref.statistic)
+        assert_allclose(res.pvalue, ref.pvalue, rtol=6e-2)
+
+    def test_resampling_input_validation(self):
+        message = "`method` must be an instance of `PermutationMethod`, an instance..."
+        with pytest.raises(ValueError, match=message):
+            stats.ttest_ind([1, 2, 3], [4, 5, 6], method='migratory')
+
+    @array_api_compatible
+    @pytest.mark.skip_xp_backends(cpu_only=True,
+                                  reason='Uses NumPy for pvalue, CI')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_permutation_not_implement_for_xp(self, xp):
+        a2, b2 = xp.asarray(self.a2), xp.asarray(self.b2)
+
+        message = "Use of `permutations` is compatible only with NumPy arrays."
+        if is_numpy(xp):  # no error
+            stats.ttest_ind(a2, b2, permutations=10)
+        else:  # NotImplementedError
+            with pytest.raises(NotImplementedError, match=message):
+                stats.ttest_ind(a2, b2, permutations=10)
+
+        message = "Use of resampling methods is compatible only with NumPy arrays."
+        rng = np.random.default_rng(7457345872572348)
+        method = stats.PermutationMethod(rng=rng)
+        if is_numpy(xp):  # no error
+            stats.ttest_ind(a2, b2, method=method)
+        else:  # NotImplementedError
+            with pytest.raises(NotImplementedError, match=message):
+                stats.ttest_ind(a2, b2, method=method)
+
+
+@pytest.mark.filterwarnings("ignore:Arguments...:DeprecationWarning")
+class Test_ttest_ind_common:
+    # for tests that are performed on variations of the t-test such as
+    # permutations and trimming
+    @pytest.mark.xslow()
+    @pytest.mark.parametrize("kwds", [{'permutations': 200, 'random_state': 0},
+                                      {'trim': .2}, {}],
+                             ids=["permutations", "trim", "basic"])
+    @pytest.mark.parametrize('equal_var', [True, False],
+                             ids=['equal_var', 'unequal_var'])
+    def test_ttest_many_dims(self, kwds, equal_var):
+        # Test that test works on many-dimensional arrays
+        np.random.seed(0)
+        a = np.random.rand(5, 4, 4, 7, 1, 6)
+        b = np.random.rand(4, 1, 8, 2, 6)
+        res = stats.ttest_ind(a, b, axis=-3, **kwds)
+
+        # compare fully-vectorized t-test against t-test on smaller slice
+        i, j, k = 2, 3, 1
+        a2 = a[i, :, j, :, 0, :]
+        b2 = b[:, 0, :, k, :]
+        res2 = stats.ttest_ind(a2, b2, axis=-2, **kwds)
+        assert_equal(res.statistic[i, :, j, k, :],
+                     res2.statistic)
+        assert_equal(res.pvalue[i, :, j, k, :],
+                     res2.pvalue)
+
+        # compare against t-test on one axis-slice at a time
+
+        # manually broadcast with tile; move axis to end to simplify
+        x = np.moveaxis(np.tile(a, (1, 1, 1, 1, 2, 1)), -3, -1)
+        y = np.moveaxis(np.tile(b, (5, 1, 4, 1, 1, 1)), -3, -1)
+        shape = x.shape[:-1]
+        statistics = np.zeros(shape)
+        pvalues = np.zeros(shape)
+        for indices in product(*(range(i) for i in shape)):
+            xi = x[indices]  # use tuple to index single axis slice
+            yi = y[indices]
+            res3 = stats.ttest_ind(xi, yi, axis=-1, **kwds)
+            statistics[indices] = res3.statistic
+            pvalues[indices] = res3.pvalue
+
+        assert_allclose(statistics, res.statistic)
+        assert_allclose(pvalues, res.pvalue)
+
+    @pytest.mark.parametrize("kwds", [{'permutations': 200, 'random_state': 0},
+                                      {'trim': .2}, {}],
+                             ids=["trim", "permutations", "basic"])
+    @pytest.mark.parametrize("axis", [-1, 0])
+    def test_nans_on_axis(self, kwds, axis):
+        # confirm that with `nan_policy='propagate'`, NaN results are returned
+        # on the correct location
+        a = np.random.randint(10, size=(5, 3, 10)).astype('float')
+        b = np.random.randint(10, size=(5, 3, 10)).astype('float')
+        # set some indices in `a` and `b` to be `np.nan`.
+        a[0][2][3] = np.nan
+        b[2][0][6] = np.nan
+
+        # arbitrarily use `np.sum` as a baseline for which indices should be
+        # NaNs
+        expected = np.isnan(np.sum(a + b, axis=axis))
+        # multidimensional inputs to `t.sf(np.abs(t), df)` with NaNs on some
+        # indices throws an warning. See issue gh-13844
+        with suppress_warnings() as sup, np.errstate(invalid="ignore"):
+            sup.filter(RuntimeWarning,
+                       "invalid value encountered in less_equal")
+            sup.filter(RuntimeWarning, "Precision loss occurred")
+            res = stats.ttest_ind(a, b, axis=axis, **kwds)
+        p_nans = np.isnan(res.pvalue)
+        assert_array_equal(p_nans, expected)
+        statistic_nans = np.isnan(res.statistic)
+        assert_array_equal(statistic_nans, expected)
+
+
+class Test_ttest_trim:
+    params = [
+        [[1, 2, 3], [1.1, 2.9, 4.2], 0.53619490753126731, -0.6864951273557258,
+         .2],
+        [[56, 128.6, 12, 123.8, 64.34, 78, 763.3], [1.1, 2.9, 4.2],
+         0.00998909252078421, 4.591598691181999, .2],
+        [[56, 128.6, 12, 123.8, 64.34, 78, 763.3], [1.1, 2.9, 4.2],
+         0.10512380092302633, 2.832256715395378, .32],
+        [[2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9],
+         [6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1],
+         0.002878909511344, -4.2461168970325, .2],
+        [[-0.84504783, 0.13366078, 3.53601757, -0.62908581, 0.54119466,
+          -1.16511574, -0.08836614, 1.18495416, 2.48028757, -1.58925028,
+          -1.6706357, 0.3090472, -2.12258305, 0.3697304, -1.0415207,
+          -0.57783497, -0.90997008, 1.09850192, 0.41270579, -1.4927376],
+         [1.2725522, 1.1657899, 2.7509041, 1.2389013, -0.9490494, -1.0752459,
+          1.1038576, 2.9912821, 3.5349111, 0.4171922, 1.0168959, -0.7625041,
+          -0.4300008, 3.0431921, 1.6035947, 0.5285634, -0.7649405, 1.5575896,
+          1.3670797, 1.1726023], 0.005293305834235, -3.0983317739483, .2]]
+
+    @pytest.mark.parametrize("a,b,pr,tr,trim", params)
+    def test_ttest_compare_r(self, a, b, pr, tr, trim):
+        '''
+        Using PairedData's yuen.t.test method. Something to note is that there
+        are at least 3 R packages that come with a trimmed t-test method, and
+        comparisons were made between them. It was found that PairedData's
+        method's results match this method, SAS, and one of the other R
+        methods. A notable discrepancy was the DescTools implementation of the
+        function, which only sometimes agreed with SAS, WRS2, PairedData and
+        this implementation. For this reason, most comparisons in R are made
+        against PairedData's method.
+
+        Rather than providing the input and output for all evaluations, here is
+        a representative example:
+        > library(PairedData)
+        > a <- c(1, 2, 3)
+        > b <- c(1.1, 2.9, 4.2)
+        > options(digits=16)
+        > yuen.t.test(a, b, tr=.2)
+
+            Two-sample Yuen test, trim=0.2
+
+        data:  x and y
+        t = -0.68649512735573, df = 3.4104431643464, p-value = 0.5361949075313
+        alternative hypothesis: true difference in trimmed means is not equal
+        to 0
+        95 percent confidence interval:
+         -3.912777195645217  2.446110528978550
+        sample estimates:
+        trimmed mean of x trimmed mean of y
+        2.000000000000000 2.73333333333333
+        '''
+        statistic, pvalue = stats.ttest_ind(a, b, trim=trim, equal_var=False)
+        assert_allclose(statistic, tr, atol=1e-15)
+        assert_allclose(pvalue, pr, atol=1e-15)
+
+    def test_compare_SAS(self):
+        # Source of the data used in this test:
+        # https://support.sas.com/resources/papers/proceedings14/1660-2014.pdf
+        a = [12, 14, 18, 25, 32, 44, 12, 14, 18, 25, 32, 44]
+        b = [17, 22, 14, 12, 30, 29, 19, 17, 22, 14, 12, 30, 29, 19]
+        # In this paper, a trimming percentage of 5% is used. However,
+        # in their implementation, the number of values trimmed is rounded to
+        # the nearest whole number. However, consistent with
+        # `scipy.stats.trimmed_mean`, this test truncates to the lower
+        # whole number. In this example, the paper notes that 1 value is
+        # trimmed off of each side. 9% replicates this amount of trimming.
+        statistic, pvalue = stats.ttest_ind(a, b, trim=.09, equal_var=False)
+        assert_allclose(pvalue, 0.514522, atol=1e-6)
+        assert_allclose(statistic, 0.669169, atol=1e-6)
+
+    def test_equal_var(self):
+        '''
+        The PairedData library only supports unequal variances. To compare
+        samples with equal variances, the multicon library is used.
+        > library(multicon)
+        > a <- c(2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9)
+        > b <- c(6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1)
+        > dv = c(a,b)
+        > iv = c(rep('a', length(a)), rep('b', length(b)))
+        > yuenContrast(dv~ iv, EQVAR = TRUE)
+        $Ms
+           N                 M wgt
+        a 11 2.442857142857143   1
+        b 11 5.385714285714286  -1
+
+        $test
+                              stat df              crit                   p
+        results -4.246116897032513 12 2.178812829667228 0.00113508833897713
+        '''
+        a = [2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9]
+        b = [6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1]
+        # `equal_var=True` is default
+        statistic, pvalue = stats.ttest_ind(a, b, trim=.2)
+        assert_allclose(pvalue, 0.00113508833897713, atol=1e-10)
+        assert_allclose(statistic, -4.246116897032513, atol=1e-10)
+
+    @pytest.mark.parametrize('alt,pr,tr',
+                             (('greater', 0.9985605452443, -4.2461168970325),
+                              ('less', 0.001439454755672, -4.2461168970325),),
+                             )
+    def test_alternatives(self, alt, pr, tr):
+        '''
+        > library(PairedData)
+        > a <- c(2.7,2.7,1.1,3.0,1.9,3.0,3.8,3.8,0.3,1.9,1.9)
+        > b <- c(6.5,5.4,8.1,3.5,0.5,3.8,6.8,4.9,9.5,6.2,4.1)
+        > options(digits=16)
+        > yuen.t.test(a, b, alternative = 'greater')
+        '''
+        a = [2.7, 2.7, 1.1, 3.0, 1.9, 3.0, 3.8, 3.8, 0.3, 1.9, 1.9]
+        b = [6.5, 5.4, 8.1, 3.5, 0.5, 3.8, 6.8, 4.9, 9.5, 6.2, 4.1]
+
+        statistic, pvalue = stats.ttest_ind(a, b, trim=.2, equal_var=False,
+                                            alternative=alt)
+        assert_allclose(pvalue, pr, atol=1e-10)
+        assert_allclose(statistic, tr, atol=1e-10)
+
+    def test_errors_unsupported(self):
+        # confirm that attempting to trim with permutations raises an error
+        match = "Use of `permutations` is incompatible with with use of `trim`."
+        with assert_raises(NotImplementedError, match=match):
+            message = "Arguments {'permutations'} are deprecated, whether..."
+            with pytest.warns(DeprecationWarning, match=message):
+                stats.ttest_ind([1, 2], [2, 3], trim=.2, permutations=2)
+
+        with assert_raises(NotImplementedError, match=match):
+            message = "Arguments {.*'random_state'.*} are deprecated, whether..."
+            with pytest.warns(DeprecationWarning, match=message):
+                stats.ttest_ind([1, 2], [2, 3], trim=.2, permutations=2,
+                                random_state=2)
+
+    @array_api_compatible
+    @pytest.mark.skip_xp_backends(cpu_only=True,
+                                  reason='Uses NumPy for pvalue, CI')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_permutation_not_implement_for_xp(self, xp):
+        message = "Use of `trim` is compatible only with NumPy arrays."
+        a, b = xp.arange(10), xp.arange(10)+1
+        if is_numpy(xp):  # no error
+            stats.ttest_ind(a, b, trim=0.1)
+        else:  # NotImplementedError
+            with pytest.raises(NotImplementedError, match=message):
+                stats.ttest_ind(a, b, trim=0.1)
+
+    @pytest.mark.parametrize("trim", [-.2, .5, 1])
+    def test_trim_bounds_error(self, trim):
+        match = "Trimming percentage should be 0 <= `trim` < .5."
+        with assert_raises(ValueError, match=match):
+            stats.ttest_ind([1, 2], [2, 1], trim=trim)
+
+
+@array_api_compatible
+@pytest.mark.skip_xp_backends(cpu_only=True,
+                              reason='Uses NumPy for pvalue, CI')
+@pytest.mark.usefixtures("skip_xp_backends")
+class Test_ttest_CI:
+    # indices in order [alternative={two-sided, less, greater},
+    #                   equal_var={False, True}, trim={0, 0.2}]
+    # reference values in order `statistic, df, pvalue, low, high`
+    # equal_var=False reference values computed with R PairedData yuen.t.test:
+    #
+    # library(PairedData)
+    # options(digits=16)
+    # a < - c(0.88236329, 0.97318744, 0.4549262, 0.97893335, 0.0606677,
+    #         0.44013366, 0.55806018, 0.40151434, 0.14453315, 0.25860601,
+    #         0.20202162)
+    # b < - c(0.93455277, 0.42680603, 0.49751939, 0.14152846, 0.711435,
+    #         0.77669667, 0.20507578, 0.78702772, 0.94691855, 0.32464958,
+    #         0.3873582, 0.35187468, 0.21731811)
+    # yuen.t.test(a, b, tr=0, conf.level = 0.9, alternative = 'l')
+    #
+    # equal_var=True reference values computed with R multicon yuenContrast:
+    #
+    # library(multicon)
+    # options(digits=16)
+    # a < - c(0.88236329, 0.97318744, 0.4549262, 0.97893335, 0.0606677,
+    #         0.44013366, 0.55806018, 0.40151434, 0.14453315, 0.25860601,
+    #         0.20202162)
+    # b < - c(0.93455277, 0.42680603, 0.49751939, 0.14152846, 0.711435,
+    #         0.77669667, 0.20507578, 0.78702772, 0.94691855, 0.32464958,
+    #         0.3873582, 0.35187468, 0.21731811)
+    # dv = c(a, b)
+    # iv = c(rep('a', length(a)), rep('b', length(b)))
+    # yuenContrast(dv~iv, EQVAR = FALSE, alternative = 'unequal', tr = 0.2)
+    r = np.empty(shape=(3, 2, 2, 5))
+    r[0, 0, 0] = [-0.2314607, 19.894435, 0.8193209, -0.247220294, 0.188729943]
+    r[1, 0, 0] = [-0.2314607, 19.894435, 0.40966045, -np.inf, 0.1382426469]
+    r[2, 0, 0] = [-0.2314607, 19.894435, 0.5903395, -0.1967329982, np.inf]
+    r[0, 0, 1] = [-0.2452886, 11.427896, 0.8105823, -0.34057446, 0.25847383]
+    r[1, 0, 1] = [-0.2452886, 11.427896, 0.40529115, -np.inf, 0.1865829074]
+    r[2, 0, 1] = [-0.2452886, 11.427896, 0.5947089, -0.268683541, np.inf]
+    # confidence interval not available for equal_var=True
+    r[0, 1, 0] = [-0.2345625322555006, 22, 0.8167175905643815, np.nan, np.nan]
+    r[1, 1, 0] = [-0.2345625322555006, 22, 0.4083587952821908, np.nan, np.nan]
+    r[2, 1, 0] = [-0.2345625322555006, 22, 0.5916412047178092, np.nan, np.nan]
+    r[0, 1, 1] = [-0.2505369406507428, 14, 0.8058115135702835, np.nan, np.nan]
+    r[1, 1, 1] = [-0.2505369406507428, 14, 0.4029057567851417, np.nan, np.nan]
+    r[2, 1, 1] = [-0.2505369406507428, 14, 0.5970942432148583, np.nan, np.nan]
+    @pytest.mark.parametrize('alternative', ['two-sided', 'less', 'greater'])
+    @pytest.mark.parametrize('equal_var', [False, True])
+    @pytest.mark.parametrize('trim', [0, 0.2])
+    def test_confidence_interval(self, alternative, equal_var, trim, xp):
+        if equal_var and trim:
+            pytest.xfail('Discrepancy in `main`; needs further investigation.')
+
+        if trim and not is_numpy(xp):
+            pytest.skip('`trim` is only compatible with NumPy input')
+
+        rng = np.random.default_rng(3810954496107292580)
+        x = xp.asarray(rng.random(11))
+        y = xp.asarray(rng.random(13))
+
+        res = stats.ttest_ind(x, y, alternative=alternative,
+                              equal_var=equal_var, trim=trim)
+
+        alternatives = {'two-sided': 0, 'less': 1, 'greater': 2}
+        ref = self.r[alternatives[alternative], int(equal_var), int(np.ceil(trim))]
+        statistic, df, pvalue, low, high = ref
+
+        rtol = 1e-7  # only 7 digits in reference
+        xp_assert_close(res.statistic, xp.asarray(statistic), rtol=rtol)
+        xp_assert_close(res.df, xp.asarray(df), rtol=rtol)
+        xp_assert_close(res.pvalue, xp.asarray(pvalue), rtol=rtol)
+
+        if not equal_var:  # CI not available when `equal_var is True`
+            ci = res.confidence_interval(0.9)
+            xp_assert_close(ci.low, xp.asarray(low), rtol=rtol)
+            xp_assert_close(ci.high, xp.asarray(high), rtol=rtol)
+
+
+def test__broadcast_concatenate():
+    # test that _broadcast_concatenate properly broadcasts arrays along all
+    # axes except `axis`, then concatenates along axis
+    np.random.seed(0)
+    a = np.random.rand(5, 4, 4, 3, 1, 6)
+    b = np.random.rand(4, 1, 8, 2, 6)
+    c = _broadcast_concatenate((a, b), axis=-3)
+    # broadcast manually as an independent check
+    a = np.tile(a, (1, 1, 1, 1, 2, 1))
+    b = np.tile(b[None, ...], (5, 1, 4, 1, 1, 1))
+    for index in product(*(range(i) for i in c.shape)):
+        i, j, k, l, m, n = index
+        if l < a.shape[-3]:
+            assert a[i, j, k, l, m, n] == c[i, j, k, l, m, n]
+        else:
+            assert b[i, j, k, l - a.shape[-3], m, n] == c[i, j, k, l, m, n]
+
+
+@array_api_compatible
+@pytest.mark.skip_xp_backends(cpu_only=True,
+                              reason='Uses NumPy for pvalue, CI')
+@pytest.mark.usefixtures("skip_xp_backends")
+def test_ttest_ind_with_uneq_var(xp):
+    # check vs. R `t.test`, e.g.
+    # options(digits=20)
+    # a = c(1., 2., 3.)
+    # b = c(1.1, 2.9, 4.2)
+    # t.test(a, b, equal.var=FALSE)
+
+    a = xp.asarray([1., 2., 3.])
+    b = xp.asarray([1.1, 2.9, 4.2])
+    pr = xp.asarray(0.53619490753126686)
+    tr = xp.asarray(-0.686495127355726265)
+
+    t, p = stats.ttest_ind(a, b, equal_var=False)
+    xp_assert_close(t, tr)
+    xp_assert_close(p, pr)
+
+    t, p = stats.ttest_ind_from_stats(*_desc_stats(a, b), equal_var=False)
+    xp_assert_close(t, tr)
+    xp_assert_close(p, pr)
+
+    a = xp.asarray([1., 2., 3., 4.])
+    pr = xp.asarray(0.84354139131608252)
+    tr = xp.asarray(-0.210866331595072315)
+
+    t, p = stats.ttest_ind(a, b, equal_var=False)
+    xp_assert_close(t, tr)
+    xp_assert_close(p, pr)
+
+    t, p = stats.ttest_ind_from_stats(*_desc_stats(a, b), equal_var=False)
+    xp_assert_close(t, tr)
+    xp_assert_close(p, pr)
+
+    # regression test
+    tr = xp.asarray(1.0912746897927283)
+    tr_uneq_n = xp.asarray(0.66745638708050492)
+    pr = xp.asarray(0.27647831993021388)
+    pr_uneq_n = xp.asarray(0.50873585065616544)
+    tr_2D = xp.asarray([tr, -tr])
+    pr_2D = xp.asarray([pr, pr])
+
+    rvs3 = xp.linspace(1, 100, 25)
+    rvs2 = xp.linspace(1, 100, 100)
+    rvs1 = xp.linspace(5, 105, 100)
+    rvs1_2D = xp.stack([rvs1, rvs2])
+    rvs2_2D = xp.stack([rvs2, rvs1])
+
+    t, p = stats.ttest_ind(rvs1, rvs2, axis=0, equal_var=False)
+    xp_assert_close(t, tr)
+    xp_assert_close(p, pr)
+
+    t, p = stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs2), equal_var=False)
+    xp_assert_close(t, tr)
+    xp_assert_close(p, pr)
+
+    t, p = stats.ttest_ind(rvs1, rvs3, axis=0, equal_var=False)
+    xp_assert_close(t, tr_uneq_n)
+    xp_assert_close(p, pr_uneq_n)
+
+    t, p = stats.ttest_ind_from_stats(*_desc_stats(rvs1, rvs3), equal_var=False)
+    xp_assert_close(t, tr_uneq_n)
+    xp_assert_close(p, pr_uneq_n)
+
+    res = stats.ttest_ind(rvs1_2D.T, rvs2_2D.T, axis=0, equal_var=False)
+    xp_assert_close(res.statistic, tr_2D)
+    xp_assert_close(res.pvalue, pr_2D)
+
+    args = _desc_stats(rvs1_2D.T, rvs2_2D.T)
+    res = stats.ttest_ind_from_stats(*args, equal_var=False)
+    xp_assert_close(res.statistic, tr_2D)
+    xp_assert_close(res.pvalue, pr_2D)
+
+    res = stats.ttest_ind(rvs1_2D, rvs2_2D, axis=1, equal_var=False)
+    xp_assert_close(res.statistic, tr_2D)
+    xp_assert_close(res.pvalue, pr_2D)
+
+    args = _desc_stats(rvs1_2D, rvs2_2D, axis=1)
+    res = stats.ttest_ind_from_stats(*args, equal_var=False)
+    xp_assert_close(res.statistic, tr_2D)
+    xp_assert_close(res.pvalue, pr_2D)
+
+
+@array_api_compatible
+@pytest.mark.skip_xp_backends(cpu_only=True,
+                              reason='Uses NumPy for pvalue, CI')
+@pytest.mark.usefixtures("skip_xp_backends")
+def test_ttest_ind_zero_division(xp):
+    # test zero division problem
+    x = xp.zeros(3)
+    y = xp.ones(3)
+    with pytest.warns(RuntimeWarning, match="Precision loss occurred"):
+        t, p = stats.ttest_ind(x, y, equal_var=False)
+    xp_assert_equal(t, xp.asarray(-xp.inf))
+    xp_assert_equal(p, xp.asarray(0.))
+
+    with np.errstate(all='ignore'):
+        t, p = stats.ttest_ind(x, x, equal_var=False)
+        xp_assert_equal(t, xp.asarray(xp.nan))
+        xp_assert_equal(p, xp.asarray(xp.nan))
+
+        # check that nan in input array result in nan output
+        anan = xp.asarray([[1, xp.nan], [-1, 1]])
+        t, p = stats.ttest_ind(anan, xp.zeros((2, 2)), equal_var=False)
+        xp_assert_equal(t, xp.asarray([0., np.nan]))
+        xp_assert_equal(p, xp.asarray([1., np.nan]))
+
+
+def test_ttest_ind_nan_2nd_arg():
+    # regression test for gh-6134: nans in the second arg were not handled
+    x = [np.nan, 2.0, 3.0, 4.0]
+    y = [1.0, 2.0, 1.0, 2.0]
+
+    r1 = stats.ttest_ind(x, y, nan_policy='omit')
+    r2 = stats.ttest_ind(y, x, nan_policy='omit')
+    assert_allclose(r2.statistic, -r1.statistic, atol=1e-15)
+    assert_allclose(r2.pvalue, r1.pvalue, atol=1e-15)
+
+    # NB: arguments are not paired when NaNs are dropped
+    r3 = stats.ttest_ind(y, x[1:])
+    assert_allclose(r2, r3, atol=1e-15)
+
+    # .. and this is consistent with R. R code:
+    # x = c(NA, 2.0, 3.0, 4.0)
+    # y = c(1.0, 2.0, 1.0, 2.0)
+    # t.test(x, y, var.equal=TRUE)
+    assert_allclose(r2, (-2.5354627641855498, 0.052181400457057901),
+                    atol=1e-15)
+
+
+@array_api_compatible
+def test_ttest_ind_empty_1d_returns_nan(xp):
+    # Two empty inputs should return a TtestResult containing nan
+    # for both values.
+    if is_numpy(xp):
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = stats.ttest_ind(xp.asarray([]), xp.asarray([]))
+    else:
+        res = stats.ttest_ind(xp.asarray([]), xp.asarray([]))
+    assert isinstance(res, stats._stats_py.TtestResult)
+    NaN = xp.asarray(xp.nan)[()]
+    xp_assert_equal(res.statistic, NaN)
+    xp_assert_equal(res.pvalue, NaN)
+
+
+@skip_xp_backends('cupy', reason='cupy/cupy#8391')
+@pytest.mark.usefixtures("skip_xp_backends")
+@array_api_compatible
+@pytest.mark.parametrize('b, expected_shape',
+                         [(np.empty((1, 5, 0)), (3, 5)),
+                          (np.empty((1, 0, 0)), (3, 0))])
+def test_ttest_ind_axis_size_zero(b, expected_shape, xp):
+    # In this test, the length of the axis dimension is zero.
+    # The results should be arrays containing nan with shape
+    # given by the broadcast nonaxis dimensions.
+    a = xp.empty((3, 1, 0))
+    b = xp.asarray(b)
+    with np.testing.suppress_warnings() as sup:
+        # first case should warn, second shouldn't?
+        sup.filter(SmallSampleWarning, too_small_nd_not_omit)
+        res = stats.ttest_ind(a, b, axis=-1)
+    assert isinstance(res, stats._stats_py.TtestResult)
+    expected_value = xp.full(expected_shape, fill_value=xp.nan)
+    xp_assert_equal(res.statistic, expected_value)
+    xp_assert_equal(res.pvalue, expected_value)
+
+
+@array_api_compatible
+def test_ttest_ind_nonaxis_size_zero(xp):
+    # In this test, the length of the axis dimension is nonzero,
+    # but one of the nonaxis dimensions has length 0.  Check that
+    # we still get the correctly broadcast shape, which is (5, 0)
+    # in this case.
+    a = xp.empty((1, 8, 0))
+    b = xp.empty((5, 8, 1))
+    res = stats.ttest_ind(a, b, axis=1)
+    assert isinstance(res, stats._stats_py.TtestResult)
+    assert res.statistic.shape ==(5, 0)
+    assert res.pvalue.shape == (5, 0)
+
+
+@array_api_compatible
+def test_ttest_ind_nonaxis_size_zero_different_lengths(xp):
+    # In this test, the length of the axis dimension is nonzero,
+    # and that size is different in the two inputs,
+    # and one of the nonaxis dimensions has length 0.  Check that
+    # we still get the correctly broadcast shape, which is (5, 0)
+    # in this case.
+    a = xp.empty((1, 7, 0))
+    b = xp.empty((5, 8, 1))
+    res = stats.ttest_ind(a, b, axis=1)
+    assert isinstance(res, stats._stats_py.TtestResult)
+    assert res.statistic.shape ==(5, 0)
+    assert res.pvalue.shape == (5, 0)
+
+
+@array_api_compatible
+@pytest.mark.skip_xp_backends(np_only=True,
+                              reason="Other backends don't like integers")
+@pytest.mark.usefixtures("skip_xp_backends")
+def test_gh5686(xp):
+    mean1, mean2 = xp.asarray([1, 2]), xp.asarray([3, 4])
+    std1, std2 = xp.asarray([5, 3]), xp.asarray([4, 5])
+    nobs1, nobs2 = xp.asarray([130, 140]), xp.asarray([100, 150])
+    # This will raise a TypeError unless gh-5686 is fixed.
+    stats.ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2)
+
+
+@array_api_compatible
+@pytest.mark.skip_xp_backends(cpu_only=True,
+                              reason='Uses NumPy for pvalue, CI')
+@pytest.mark.usefixtures("skip_xp_backends")
+def test_ttest_ind_from_stats_inputs_zero(xp):
+    # Regression test for gh-6409.
+    zero = xp.asarray(0.)
+    six = xp.asarray(6.)
+    NaN = xp.asarray(xp.nan)
+    res = stats.ttest_ind_from_stats(zero, zero, six, zero, zero, six, equal_var=False)
+    xp_assert_equal(res.statistic, NaN)
+    xp_assert_equal(res.pvalue, NaN)
+
+
+@array_api_compatible
+@pytest.mark.skip_xp_backends(cpu_only=True,
+                              reason='Uses NumPy for pvalue, CI')
+@pytest.mark.usefixtures("skip_xp_backends")
+def test_ttest_uniform_pvalues(xp):
+    # test that p-values are uniformly distributed under the null hypothesis
+    rng = np.random.default_rng(246834602926842)
+    x = xp.asarray(rng.normal(size=(10000, 2)))
+    y = xp.asarray(rng.normal(size=(10000, 1)))
+    q = rng.uniform(size=100)
+
+    res = stats.ttest_ind(x, y, equal_var=True, axis=-1)
+    pvalue = np.asarray(res.pvalue)
+    assert stats.ks_1samp(pvalue, stats.uniform().cdf).pvalue > 0.1
+    assert_allclose(np.quantile(pvalue, q), q, atol=1e-2)
+
+    res = stats.ttest_ind(y, x, equal_var=True, axis=-1)
+    pvalue = np.asarray(res.pvalue)
+    assert stats.ks_1samp(pvalue, stats.uniform().cdf).pvalue > 0.1
+    assert_allclose(np.quantile(pvalue, q), q, atol=1e-2)
+
+    # reference values from R:
+    # options(digits=16)
+    # t.test(c(2, 3, 5), c(1.5), var.equal=TRUE)
+    x, y = xp.asarray([2, 3, 5]), xp.asarray([1.5])
+
+    res = stats.ttest_ind(x, y, equal_var=True)
+    rtol = 1e-6 if is_torch(xp) else 1e-10
+    xp_assert_close(res.statistic, xp.asarray(1.0394023007754), rtol=rtol)
+    xp_assert_close(res.pvalue, xp.asarray(0.407779907736), rtol=rtol)
+
+
+def _convert_pvalue_alternative(t, p, alt, xp):
+    # test alternative parameter
+    # Convert from two-sided p-values to one sided using T result data.
+    less = xp.asarray(alt == "less")
+    greater = xp.asarray(alt == "greater")
+    i = ((t < 0) & less) | ((t > 0) & greater)
+    return xp.where(i, p/2, 1 - p/2)
+
+
+@pytest.mark.slow
+@pytest.mark.skip_xp_backends(cpu_only=True,
+                              reason='Uses NumPy for pvalue, CI')
+@pytest.mark.usefixtures("skip_xp_backends")
+@array_api_compatible
+def test_ttest_1samp_new(xp):
+    n1, n2, n3 = (10, 15, 20)
+    rvn1 = stats.norm.rvs(loc=5, scale=10, size=(n1, n2, n3))
+    rvn1 = xp.asarray(rvn1)
+
+    # check multidimensional array and correct axis handling
+    # deterministic rvn1 and rvn2 would be better as in test_ttest_rel
+    popmean = xp.ones((1, n2, n3))
+    t1, p1 = stats.ttest_1samp(rvn1, popmean, axis=0)
+    t2, p2 = stats.ttest_1samp(rvn1, 1., axis=0)
+    t3, p3 = stats.ttest_1samp(rvn1[:, 0, 0], 1.)
+    xp_assert_close(t1, t2, rtol=1e-14)
+    xp_assert_close(t1[0, 0], t3, rtol=1e-14)
+    assert_equal(t1.shape, (n2, n3))
+
+    popmean = xp.ones((n1, 1, n3))
+    t1, p1 = stats.ttest_1samp(rvn1, popmean, axis=1)
+    t2, p2 = stats.ttest_1samp(rvn1, 1., axis=1)
+    t3, p3 = stats.ttest_1samp(rvn1[0, :, 0], 1.)
+    xp_assert_close(t1, t2, rtol=1e-14)
+    xp_assert_close(t1[0, 0], t3, rtol=1e-14)
+    assert_equal(t1.shape, (n1, n3))
+
+    popmean = xp.ones((n1, n2, 1))
+    t1, p1 = stats.ttest_1samp(rvn1, popmean, axis=2)
+    t2, p2 = stats.ttest_1samp(rvn1, 1., axis=2)
+    t3, p3 = stats.ttest_1samp(rvn1[0, 0, :], 1.)
+    xp_assert_close(t1, t2, rtol=1e-14)
+    xp_assert_close(t1[0, 0], t3, rtol=1e-14)
+    assert_equal(t1.shape, (n1, n2))
+
+    # test zero division problem
+    t, p = stats.ttest_1samp(xp.asarray([0., 0., 0.]), 1.)
+    xp_assert_equal(xp.abs(t), xp.asarray(xp.inf))
+    xp_assert_equal(p, xp.asarray(0.))
+
+    tr, pr = stats.ttest_1samp(rvn1[:, :, :], 1.)
+
+    t, p = stats.ttest_1samp(rvn1[:, :, :], 1., alternative="greater")
+    pc = _convert_pvalue_alternative(tr, pr, "greater", xp)
+    xp_assert_close(p, pc)
+    xp_assert_close(t, tr)
+
+    t, p = stats.ttest_1samp(rvn1[:, :, :], 1., alternative="less")
+    pc = _convert_pvalue_alternative(tr, pr, "less", xp)
+    xp_assert_close(p, pc)
+    xp_assert_close(t, tr)
+
+    with np.errstate(all='ignore'):
+        res = stats.ttest_1samp(xp.asarray([0., 0., 0.]), 0.)
+        xp_assert_equal(res.statistic, xp.asarray(xp.nan))
+        xp_assert_equal(res.pvalue, xp.asarray(xp.nan))
+
+        # check that nan in input array result in nan output
+        anan = xp.asarray([[1., np.nan], [-1., 1.]])
+        res = stats.ttest_1samp(anan, 0.)
+        xp_assert_equal(res.statistic, xp.asarray([0., xp.nan]))
+        xp_assert_equal(res.pvalue, xp.asarray([1., xp.nan]))
+
+
+@pytest.mark.skip_xp_backends(np_only=True,
+                              reason="Only NumPy has nan_policy='omit' for now")
+@pytest.mark.usefixtures("skip_xp_backends")
+@array_api_compatible
+def test_ttest_1samp_new_omit(xp):
+    n1, n2, n3 = (5, 10, 15)
+    rvn1 = stats.norm.rvs(loc=5, scale=10, size=(n1, n2, n3))
+    rvn1 = xp.asarray(rvn1)
+
+    rvn1[0:2, 1:3, 4:8] = xp.nan
+
+    tr, pr = stats.ttest_1samp(rvn1[:, :, :], 1., nan_policy='omit')
+
+    t, p = stats.ttest_1samp(rvn1[:, :, :], 1., nan_policy='omit',
+                             alternative="greater")
+    pc = _convert_pvalue_alternative(tr, pr, "greater", xp)
+    xp_assert_close(p, pc)
+    xp_assert_close(t, tr)
+
+    t, p = stats.ttest_1samp(rvn1[:, :, :], 1., nan_policy='omit',
+                             alternative="less")
+    pc = _convert_pvalue_alternative(tr, pr, "less", xp)
+    xp_assert_close(p, pc)
+    xp_assert_close(t, tr)
+
+
+@pytest.mark.skip_xp_backends(cpu_only=True,
+                              reason='Uses NumPy for pvalue, CI')
+@pytest.mark.usefixtures("skip_xp_backends")
+@array_api_compatible
+def test_ttest_1samp_popmean_array(xp):
+    # when popmean.shape[axis] != 1, raise an error
+    # if the user wants to test multiple null hypotheses simultaneously,
+    # use standard broadcasting rules
+    rng = np.random.default_rng(2913300596553337193)
+    x = rng.random(size=(1, 15, 20))
+    x = xp.asarray(x)
+
+    message = r"`popmean.shape\[axis\]` must equal 1."
+    popmean = xp.asarray(rng.random(size=(5, 2, 20)))
+    with pytest.raises(ValueError, match=message):
+        stats.ttest_1samp(x, popmean=popmean, axis=-2)
+
+    popmean = xp.asarray(rng.random(size=(5, 1, 20)))
+    res = stats.ttest_1samp(x, popmean=popmean, axis=-2)
+    assert res.statistic.shape == (5, 20)
+
+    xp_test = array_namespace(x)  # torch needs expand_dims
+    l, u = res.confidence_interval()
+    l = xp_test.expand_dims(l, axis=-2)
+    u = xp_test.expand_dims(u, axis=-2)
+
+    res = stats.ttest_1samp(x, popmean=l, axis=-2)
+    ref = xp.broadcast_to(xp.asarray(0.05, dtype=xp.float64), res.pvalue.shape)
+    xp_assert_close(res.pvalue, ref)
+
+    res = stats.ttest_1samp(x, popmean=u, axis=-2)
+    xp_assert_close(res.pvalue, ref)
+
+
+class TestDescribe:
+    @array_api_compatible
+    def test_describe_scalar(self, xp):
+        with suppress_warnings() as sup, \
+              np.errstate(invalid="ignore", divide="ignore"):
+            sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice")
+            n, mm, m, v, sk, kurt = stats.describe(xp.asarray(4.)[()])
+        assert n == 1
+        xp_assert_equal(mm[0], xp.asarray(4.0))
+        xp_assert_equal(mm[1], xp.asarray(4.0))
+        xp_assert_equal(m, xp.asarray(4.0))
+        xp_assert_equal(v ,xp.asarray(xp.nan))
+        xp_assert_equal(sk, xp.asarray(xp.nan))
+        xp_assert_equal(kurt, xp.asarray(xp.nan))
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_describe_numbers(self, xp):
+        xp_test = array_namespace(xp.asarray(1.))  # numpy needs `concat`
+        x = xp_test.concat((xp.ones((3, 4)), xp.full((2, 4), 2.)))
+        nc = 5
+        mmc = (xp.asarray([1., 1., 1., 1.]), xp.asarray([2., 2., 2., 2.]))
+        mc = xp.asarray([1.4, 1.4, 1.4, 1.4])
+        vc = xp.asarray([0.3, 0.3, 0.3, 0.3])
+        skc = xp.asarray([0.40824829046386357] * 4)
+        kurtc = xp.asarray([-1.833333333333333] * 4)
+        n, mm, m, v, sk, kurt = stats.describe(x)
+        assert n == nc
+        xp_assert_equal(mm[0], mmc[0])
+        xp_assert_equal(mm[1], mmc[1])
+        xp_assert_close(m, mc, rtol=4 * xp.finfo(m.dtype).eps)
+        xp_assert_close(v, vc, rtol=4 * xp.finfo(m.dtype).eps)
+        xp_assert_close(sk, skc)
+        xp_assert_close(kurt, kurtc)
+
+        n, mm, m, v, sk, kurt = stats.describe(x.T, axis=1)
+        assert n == nc
+        xp_assert_equal(mm[0], mmc[0])
+        xp_assert_equal(mm[1], mmc[1])
+        xp_assert_close(m, mc, rtol=4 * xp.finfo(m.dtype).eps)
+        xp_assert_close(v, vc, rtol=4 * xp.finfo(m.dtype).eps)
+        xp_assert_close(sk, skc)
+        xp_assert_close(kurt, kurtc)
+
+    def describe_nan_policy_omit_test(self):
+        x = np.arange(10.)
+        x[9] = np.nan
+
+        nc, mmc = (9, (0.0, 8.0))
+        mc = 4.0
+        vc = 7.5
+        skc = 0.0
+        kurtc = -1.2300000000000002
+        n, mm, m, v, sk, kurt = stats.describe(x, nan_policy='omit')
+        assert_equal(n, nc)
+        assert_equal(mm, mmc)
+        assert_equal(m, mc)
+        assert_equal(v, vc)
+        assert_array_almost_equal(sk, skc)
+        assert_array_almost_equal(kurt, kurtc, decimal=13)
+
+    @array_api_compatible
+    def test_describe_nan_policy_other(self, xp):
+        x = xp.arange(10.)
+        x = xp.where(x==9, xp.asarray(xp.nan), x)
+
+        message = 'The input contains nan values'
+        with pytest.raises(ValueError, match=message):
+            stats.describe(x, nan_policy='raise')
+
+        n, mm, m, v, sk, kurt = stats.describe(x, nan_policy='propagate')
+        ref = xp.asarray(xp.nan)[()]
+        assert n == 10
+        xp_assert_equal(mm[0], ref)
+        xp_assert_equal(mm[1], ref)
+        xp_assert_equal(m, ref)
+        xp_assert_equal(v, ref)
+        xp_assert_equal(sk, ref)
+        xp_assert_equal(kurt, ref)
+
+        if is_numpy(xp):
+            self.describe_nan_policy_omit_test()
+        else:
+            message = "`nan_policy='omit' is incompatible with non-NumPy arrays."
+            with pytest.raises(ValueError, match=message):
+                stats.describe(x, nan_policy='omit')
+
+        message = 'nan_policy must be one of...'
+        with pytest.raises(ValueError, match=message):
+            stats.describe(x, nan_policy='foobar')
+
+    def test_describe_result_attributes(self):
+        # some result attributes are tuples, which aren't meant to be compared
+        # with `xp_assert_close`
+        actual = stats.describe(np.arange(5.))
+        attributes = ('nobs', 'minmax', 'mean', 'variance', 'skewness', 'kurtosis')
+        check_named_results(actual, attributes)
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_describe_ddof(self, xp):
+        xp_test = array_namespace(xp.asarray(1.))  # numpy needs `concat`
+        x = xp_test.concat((xp.ones((3, 4)), xp.full((2, 4), 2.)))
+        nc = 5
+        mmc = (xp.asarray([1., 1., 1., 1.]), xp.asarray([2., 2., 2., 2.]))
+        mc = xp.asarray([1.4, 1.4, 1.4, 1.4])
+        vc = xp.asarray([0.24, 0.24, 0.24, 0.24])
+        skc = xp.asarray([0.40824829046386357] * 4)
+        kurtc = xp.asarray([-1.833333333333333] * 4)
+        n, mm, m, v, sk, kurt = stats.describe(x, ddof=0)
+        assert n == nc
+        xp_assert_equal(mm[0], mmc[0])
+        xp_assert_equal(mm[1], mmc[1])
+        xp_assert_close(m, mc)
+        xp_assert_close(v, vc)
+        xp_assert_close(sk, skc)
+        xp_assert_close(kurt, kurtc)
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @array_api_compatible
+    def test_describe_axis_none(self, xp):
+        xp_test = array_namespace(xp.asarray(1.))  # numpy needs `concat`
+        x = xp_test.concat((xp.ones((3, 4)), xp.full((2, 4), 2.)))
+
+        # expected values
+        nc = 20
+        mmc = (xp.asarray(1.0), xp.asarray(2.0))
+        mc = xp.asarray(1.3999999999999999)
+        vc = xp.asarray(0.25263157894736848)
+        skc = xp.asarray(0.4082482904638634)
+        kurtc = xp.asarray(-1.8333333333333333)
+
+        # actual values
+        n, mm, m, v, sk, kurt = stats.describe(x, axis=None)
+
+        assert n == nc
+        xp_assert_equal(mm[0], mmc[0])
+        xp_assert_equal(mm[1], mmc[1])
+        xp_assert_close(m, mc)
+        xp_assert_close(v, vc)
+        xp_assert_close(sk, skc)
+        xp_assert_close(kurt, kurtc)
+
+    @array_api_compatible
+    def test_describe_empty(self, xp):
+        message = "The input must not be empty."
+        with pytest.raises(ValueError, match=message):
+            stats.describe(xp.asarray([]))
+
+
+@array_api_compatible
+class NormalityTests:
+    def test_too_small(self, xp):
+        # 1D sample has too few observations -> warning/error
+        test_fun = getattr(stats, self.test_name)
+        x = xp.asarray(4.)
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = test_fun(x)
+                NaN = xp.asarray(xp.nan)
+                xp_assert_equal(res.statistic, NaN)
+                xp_assert_equal(res.pvalue, NaN)
+        else:
+            message = "...requires at least..."
+            with pytest.raises(ValueError, match=message):
+                test_fun(x)
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    @pytest.mark.parametrize("alternative", ['two-sided', 'less', 'greater'])
+    def test_against_R(self, alternative, xp):
+        # testa against R `dagoTest` from package `fBasics`
+        # library(fBasics)
+        # options(digits=16)
+        # x = c(-2, -1, 0, 1, 2, 3)**2
+        # x = rep(x, times=4)
+        # test_result <- dagoTest(x)
+        # test_result@test$statistic
+        # test_result@test$p.value
+        test_name = self.test_name
+        test_fun = getattr(stats, test_name)
+        ref_statistic= xp.asarray(self.case_ref[0])
+        ref_pvalue = xp.asarray(self.case_ref[1])
+
+        kwargs = {}
+        if alternative in {'less', 'greater'}:
+            if test_name in {'skewtest', 'kurtosistest'}:
+                ref_pvalue = ref_pvalue/2 if alternative == "less" else 1-ref_pvalue/2
+                ref_pvalue = 1-ref_pvalue if test_name == 'skewtest' else ref_pvalue
+                kwargs['alternative'] = alternative
+            else:
+                pytest.skip('`alternative` not available for `normaltest`')
+
+        x = xp.asarray((-2, -1, 0, 1, 2, 3.)*4)**2
+        res = test_fun(x, **kwargs)
+        res_statistic, res_pvalue = res
+        xp_assert_close(res_statistic, ref_statistic)
+        xp_assert_close(res_pvalue, ref_pvalue)
+        check_named_results(res, ('statistic', 'pvalue'), xp=xp)
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_nan(self, xp):
+        # nan in input -> nan output (default nan_policy='propagate')
+        test_fun = getattr(stats, self.test_name)
+        x = xp.arange(30.)
+        NaN = xp.asarray(xp.nan, dtype=x.dtype)
+        x = xp.where(x == 29, NaN, x)
+        with np.errstate(invalid="ignore"):
+            res = test_fun(x)
+            xp_assert_equal(res.statistic, NaN)
+            xp_assert_equal(res.pvalue, NaN)
+
+class TestSkewTest(NormalityTests):
+    test_name = 'skewtest'
+    case_ref = (1.98078826090875881, 0.04761502382843208)  # statistic, pvalue
+
+    def test_intuitive(self, xp):
+        # intuitive tests; see gh-13549. skewnorm with parameter 1 has skew > 0
+        a1 = stats.skewnorm.rvs(a=1, size=10000, random_state=123)
+        a1_xp = xp.asarray(a1)
+        pval = stats.skewtest(a1_xp, alternative='greater').pvalue
+        xp_assert_close(pval, xp.asarray(0.0, dtype=a1_xp.dtype), atol=9e-6)
+
+    def test_skewtest_too_few_observations(self, xp):
+        # Regression test for ticket #1492.
+        # skewtest requires at least 8 observations; 7 should raise a ValueError.
+        stats.skewtest(xp.arange(8.0))
+
+        x = xp.arange(7.0)
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = stats.skewtest(x)
+                NaN = xp.asarray(xp.nan)
+                xp_assert_equal(res.statistic, NaN)
+                xp_assert_equal(res.pvalue, NaN)
+        else:
+            message = "`skewtest` requires at least 8 observations"
+            with pytest.raises(ValueError, match=message):
+                stats.skewtest(x)
+
+
+class TestKurtosisTest(NormalityTests):
+    test_name = 'kurtosistest'
+    case_ref = (-0.01403734404759738, 0.98880018772590561)  # statistic, pvalue
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_intuitive(self, xp):
+        # intuitive tests; see gh-13549. excess kurtosis of laplace is 3 > 0
+        a2 = stats.laplace.rvs(size=10000, random_state=123)
+        a2_xp = xp.asarray(a2)
+        pval = stats.kurtosistest(a2_xp, alternative='greater').pvalue
+        xp_assert_close(pval, xp.asarray(0.0, dtype=a2_xp.dtype), atol=1e-15)
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_gh9033_regression(self, xp):
+        # regression test for issue gh-9033: x clearly non-normal but power of
+        # negative denom needs to be handled correctly to reject normality
+        counts = [128, 0, 58, 7, 0, 41, 16, 0, 0, 167]
+        x = np.hstack([np.full(c, i) for i, c in enumerate(counts)])
+        x = xp.asarray(x, dtype=xp.float64)
+        assert stats.kurtosistest(x)[1] < 0.01
+
+    @skip_xp_backends('cupy', reason='cupy/cupy#8391')
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_kurtosistest_too_few_observations(self, xp):
+        # kurtosistest requires at least 5 observations; 4 should raise a ValueError.
+        # At least 20 are needed to avoid warning
+        # Regression test for ticket #1425.
+        stats.kurtosistest(xp.arange(20.0))
+
+        message = "`kurtosistest` p-value may be inaccurate..."
+        with pytest.warns(UserWarning, match=message):
+            stats.kurtosistest(xp.arange(5.0))
+        with pytest.warns(UserWarning, match=message):
+            stats.kurtosistest(xp.arange(19.0))
+
+        x = xp.arange(4.0)
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = stats.skewtest(x)
+                NaN = xp.asarray(xp.nan)
+                xp_assert_equal(res.statistic, NaN)
+                xp_assert_equal(res.pvalue, NaN)
+        else:
+            message = "`kurtosistest` requires at least 5 observations"
+            with pytest.raises(ValueError, match=message):
+                stats.kurtosistest(x)
+
+
+class TestNormalTest(NormalityTests):
+    test_name = 'normaltest'
+    case_ref = (3.92371918158185551, 0.14059672529747502)  # statistic, pvalue
+
+
+class TestRankSums:
+
+    np.random.seed(0)
+    x, y = np.random.rand(2, 10)
+
+    @pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided'])
+    def test_ranksums_result_attributes(self, alternative):
+        # ranksums pval = mannwhitneyu pval w/out continuity or tie correction
+        res1 = stats.ranksums(self.x, self.y,
+                              alternative=alternative).pvalue
+        res2 = stats.mannwhitneyu(self.x, self.y, use_continuity=False,
+                                  alternative=alternative).pvalue
+        assert_allclose(res1, res2)
+
+    def test_ranksums_named_results(self):
+        res = stats.ranksums(self.x, self.y)
+        check_named_results(res, ('statistic', 'pvalue'))
+
+    def test_input_validation(self):
+        with assert_raises(ValueError, match="`alternative` must be 'less'"):
+            stats.ranksums(self.x, self.y, alternative='foobar')
+
+
+@array_api_compatible
+class TestJarqueBera:
+    def test_jarque_bera_against_R(self, xp):
+        # library(tseries)
+        # options(digits=16)
+        # x < - rnorm(5)
+        # jarque.bera.test(x)
+        x = [-0.160104223201523288,  1.131262000934478040, -0.001235254523709458,
+             -0.776440091309490987, -2.072959999533182884]
+        x = xp.asarray(x)
+        ref = xp.asarray([0.17651605223752, 0.9155246169805])
+        res = stats.jarque_bera(x)
+        xp_assert_close(res.statistic, ref[0])
+        xp_assert_close(res.pvalue, ref[1])
+
+    @skip_xp_backends(np_only=True)
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_jarque_bera_array_like(self):
+        # array-like only relevant for NumPy
+        np.random.seed(987654321)
+        x = np.random.normal(0, 1, 100000)
+
+        jb_test1 = JB1, p1 = stats.jarque_bera(list(x))
+        jb_test2 = JB2, p2 = stats.jarque_bera(tuple(x))
+        jb_test3 = JB3, p3 = stats.jarque_bera(x.reshape(2, 50000))
+
+        assert JB1 == JB2 == JB3 == jb_test1.statistic == jb_test2.statistic == jb_test3.statistic  # noqa: E501
+        assert p1 == p2 == p3 == jb_test1.pvalue == jb_test2.pvalue == jb_test3.pvalue
+
+    def test_jarque_bera_size(self, xp):
+        x = xp.asarray([])
+        if is_numpy(xp):
+            with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+                res = stats.jarque_bera(x)
+            NaN = xp.asarray(xp.nan)
+            xp_assert_equal(res.statistic, NaN)
+            xp_assert_equal(res.pvalue, NaN)
+        else:
+            message = "At least one observation is required."
+            with pytest.raises(ValueError, match=message):
+                res = stats.jarque_bera(x)
+
+    def test_axis(self, xp):
+        rng = np.random.RandomState(seed=122398129)
+        x = xp.asarray(rng.random(size=(2, 45)))
+
+        res = stats.jarque_bera(x, axis=None)
+        ref = stats.jarque_bera(xp.reshape(x, (-1,)))
+        xp_assert_equal(res.statistic, ref.statistic)
+        xp_assert_equal(res.pvalue, ref.pvalue)
+
+        res = stats.jarque_bera(x, axis=1)
+        s0, p0 = stats.jarque_bera(x[0, :])
+        s1, p1 = stats.jarque_bera(x[1, :])
+        xp_assert_close(res.statistic, xp.asarray([s0, s1]))
+        xp_assert_close(res.pvalue, xp.asarray([p0, p1]))
+
+        resT = stats.jarque_bera(x.T, axis=0)
+        xp_assert_close(res.statistic, resT.statistic)
+        xp_assert_close(res.pvalue, resT.pvalue)
+
+
+class TestMannWhitneyU:
+    X = [19.8958398126694, 19.5452691647182, 19.0577309166425, 21.716543054589,
+         20.3269502208702, 20.0009273294025, 19.3440043632957, 20.4216806548105,
+         19.0649894736528, 18.7808043120398, 19.3680942943298, 19.4848044069953,
+         20.7514611265663, 19.0894948874598, 19.4975522356628, 18.9971170734274,
+         20.3239606288208, 20.6921298083835, 19.0724259532507, 18.9825187935021,
+         19.5144462609601, 19.8256857844223, 20.5174677102032, 21.1122407995892,
+         17.9490854922535, 18.2847521114727, 20.1072217648826, 18.6439891962179,
+         20.4970638083542, 19.5567594734914]
+
+    Y = [19.2790668029091, 16.993808441865, 18.5416338448258, 17.2634018833575,
+         19.1577183624616, 18.5119655377495, 18.6068455037221, 18.8358343362655,
+         19.0366413269742, 18.1135025515417, 19.2201873866958, 17.8344909022841,
+         18.2894380745856, 18.6661374133922, 19.9688601693252, 16.0672254617636,
+         19.00596360572, 19.201561539032, 19.0487501090183, 19.0847908674356]
+
+    significant = 14
+
+    def test_mannwhitneyu_one_sided(self):
+        u1, p1 = stats.mannwhitneyu(self.X, self.Y, alternative='less')
+        u2, p2 = stats.mannwhitneyu(self.Y, self.X, alternative='greater')
+        u3, p3 = stats.mannwhitneyu(self.X, self.Y, alternative='greater')
+        u4, p4 = stats.mannwhitneyu(self.Y, self.X, alternative='less')
+
+        assert_equal(p1, p2)
+        assert_equal(p3, p4)
+        assert_(p1 != p3)
+        assert_equal(u1, 498)
+        assert_equal(u2, 102)
+        assert_equal(u3, 498)
+        assert_equal(u4, 102)
+        assert_approx_equal(p1, 0.999957683256589, significant=self.significant)
+        assert_approx_equal(p3, 4.5941632666275e-05, significant=self.significant)
+
+    def test_mannwhitneyu_two_sided(self):
+        u1, p1 = stats.mannwhitneyu(self.X, self.Y, alternative='two-sided')
+        u2, p2 = stats.mannwhitneyu(self.Y, self.X, alternative='two-sided')
+
+        assert_equal(p1, p2)
+        assert_equal(u1, 498)
+        assert_equal(u2, 102)
+        assert_approx_equal(p1, 9.188326533255e-05,
+                            significant=self.significant)
+
+    def test_mannwhitneyu_no_correct_one_sided(self):
+        u1, p1 = stats.mannwhitneyu(self.X, self.Y, False,
+                                    alternative='less')
+        u2, p2 = stats.mannwhitneyu(self.Y, self.X, False,
+                                    alternative='greater')
+        u3, p3 = stats.mannwhitneyu(self.X, self.Y, False,
+                                    alternative='greater')
+        u4, p4 = stats.mannwhitneyu(self.Y, self.X, False,
+                                    alternative='less')
+
+        assert_equal(p1, p2)
+        assert_equal(p3, p4)
+        assert_(p1 != p3)
+        assert_equal(u1, 498)
+        assert_equal(u2, 102)
+        assert_equal(u3, 498)
+        assert_equal(u4, 102)
+        assert_approx_equal(p1, 0.999955905990004, significant=self.significant)
+        assert_approx_equal(p3, 4.40940099958089e-05, significant=self.significant)
+
+    def test_mannwhitneyu_no_correct_two_sided(self):
+        u1, p1 = stats.mannwhitneyu(self.X, self.Y, False,
+                                    alternative='two-sided')
+        u2, p2 = stats.mannwhitneyu(self.Y, self.X, False,
+                                    alternative='two-sided')
+
+        assert_equal(p1, p2)
+        assert_equal(u1, 498)
+        assert_equal(u2, 102)
+        assert_approx_equal(p1, 8.81880199916178e-05,
+                            significant=self.significant)
+
+    def test_mannwhitneyu_ones(self):
+        # test for gh-1428
+        x = np.array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 2., 1., 1., 2.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 3., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1.])
+
+        y = np.array([1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1., 1., 1., 1.,
+                      2., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2., 1., 1., 3.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 1., 2., 1.,
+                      1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1., 2.,
+                      2., 1., 1., 2., 1., 1., 2., 1., 2., 1., 1., 1., 1., 2.,
+                      2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      1., 2., 1., 1., 1., 1., 1., 2., 2., 2., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+                      2., 1., 1., 2., 1., 1., 1., 1., 2., 1., 1., 1., 1., 1.,
+                      1., 1., 1., 1., 1., 1., 1., 2., 1., 1., 1., 2., 1., 1.,
+                      1., 1., 1., 1.])
+
+        # checked against R wilcox.test
+        assert_allclose(stats.mannwhitneyu(x, y, alternative='less'),
+                        (16980.5, 2.8214327656317373e-005))
+        # p-value from R, e.g. wilcox.test(x, y, alternative="g")
+        assert_allclose(stats.mannwhitneyu(x, y, alternative='greater'),
+                        (16980.5, 0.9999719954296))
+        assert_allclose(stats.mannwhitneyu(x, y, alternative='two-sided'),
+                        (16980.5, 5.642865531266e-05))
+
+    def test_mannwhitneyu_result_attributes(self):
+        # test for namedtuple attribute results
+        attributes = ('statistic', 'pvalue')
+        res = stats.mannwhitneyu(self.X, self.Y, alternative="less")
+        check_named_results(res, attributes)
+
+
+def test_pointbiserial():
+    # same as mstats test except for the nan
+    # Test data: https://web.archive.org/web/20060504220742/https://support.sas.com/ctx/samples/index.jsp?sid=490&tab=output
+    x = [1,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0,
+         0,0,0,0,1]
+    y = [14.8,13.8,12.4,10.1,7.1,6.1,5.8,4.6,4.3,3.5,3.3,3.2,3.0,
+         2.8,2.8,2.5,2.4,2.3,2.1,1.7,1.7,1.5,1.3,1.3,1.2,1.2,1.1,
+         0.8,0.7,0.6,0.5,0.2,0.2,0.1]
+    assert_almost_equal(stats.pointbiserialr(x, y)[0], 0.36149, 5)
+
+    # test for namedtuple attribute results
+    attributes = ('correlation', 'pvalue')
+    res = stats.pointbiserialr(x, y)
+    check_named_results(res, attributes)
+    assert_equal(res.correlation, res.statistic)
+
+
+def test_obrientransform():
+    # A couple tests calculated by hand.
+    x1 = np.array([0, 2, 4])
+    t1 = stats.obrientransform(x1)
+    expected = [7, -2, 7]
+    assert_allclose(t1[0], expected)
+
+    x2 = np.array([0, 3, 6, 9])
+    t2 = stats.obrientransform(x2)
+    expected = np.array([30, 0, 0, 30])
+    assert_allclose(t2[0], expected)
+
+    # Test two arguments.
+    a, b = stats.obrientransform(x1, x2)
+    assert_equal(a, t1[0])
+    assert_equal(b, t2[0])
+
+    # Test three arguments.
+    a, b, c = stats.obrientransform(x1, x2, x1)
+    assert_equal(a, t1[0])
+    assert_equal(b, t2[0])
+    assert_equal(c, t1[0])
+
+    # This is a regression test to check np.var replacement.
+    # The author of this test didn't separately verify the numbers.
+    x1 = np.arange(5)
+    result = np.array(
+      [[5.41666667, 1.04166667, -0.41666667, 1.04166667, 5.41666667],
+       [21.66666667, 4.16666667, -1.66666667, 4.16666667, 21.66666667]])
+    assert_array_almost_equal(stats.obrientransform(x1, 2*x1), result, decimal=8)
+
+    # Example from "O'Brien Test for Homogeneity of Variance"
+    # by Herve Abdi.
+    values = range(5, 11)
+    reps = np.array([5, 11, 9, 3, 2, 2])
+    data = np.repeat(values, reps)
+    transformed_values = np.array([3.1828, 0.5591, 0.0344,
+                                   1.6086, 5.2817, 11.0538])
+    expected = np.repeat(transformed_values, reps)
+    result = stats.obrientransform(data)
+    assert_array_almost_equal(result[0], expected, decimal=4)
+
+
+def check_equal_xmean(*args, xp, mean_fun, axis=None, dtype=None,
+                      rtol=1e-7, weights=None):
+    # Note this doesn't test when axis is not specified
+    dtype = dtype or xp.float64
+    if len(args) == 2:
+        array_like, desired = args
+    else:
+        array_like, p, desired = args
+    array_like = xp.asarray(array_like, dtype=dtype)
+    desired = xp.asarray(desired, dtype=dtype)
+    weights = xp.asarray(weights, dtype=dtype) if weights is not None else weights
+    args = (array_like,) if len(args) == 2 else (array_like, p)
+    x = mean_fun(*args, axis=axis, dtype=dtype, weights=weights)
+    xp_assert_close(x, desired, rtol=rtol)
+
+
+def check_equal_gmean(*args, **kwargs):
+    return check_equal_xmean(*args, mean_fun=stats.gmean, **kwargs)
+
+
+def check_equal_hmean(*args, **kwargs):
+    return check_equal_xmean(*args, mean_fun=stats.hmean, **kwargs)
+
+
+def check_equal_pmean(*args, **kwargs):
+    return check_equal_xmean(*args, mean_fun=stats.pmean, **kwargs)
+
+
+@array_api_compatible
+class TestHMean:
+    def test_0(self, xp):
+        a = [1, 0, 2]
+        desired = 0
+        check_equal_hmean(a, desired, xp=xp)
+
+    def test_1d(self, xp):
+        #  Test a 1d case
+        a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
+        desired = 34.1417152147
+        check_equal_hmean(a, desired, xp=xp)
+
+        a = [1, 2, 3, 4]
+        desired = 4. / (1. / 1 + 1. / 2 + 1. / 3 + 1. / 4)
+        check_equal_hmean(a, desired, xp=xp)
+
+    def test_1d_with_zero(self, xp):
+        a = np.array([1, 0])
+        desired = 0.0
+        check_equal_hmean(a, desired, xp=xp, rtol=0.0)
+
+    @skip_xp_backends('array_api_strict',
+                      reason=("`array_api_strict.where` `fillvalue` doesn't "
+                               "accept Python scalars. See data-apis/array-api#807."))
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_1d_with_negative_value(self, xp):
+        # Won't work for array_api_strict for now, but see data-apis/array-api#807
+        a = np.array([1, 0, -1])
+        message = "The harmonic mean is only defined..."
+        with pytest.warns(RuntimeWarning, match=message):
+            check_equal_hmean(a, xp.nan, xp=xp, rtol=0.0)
+
+    # Note the next tests use axis=None as default, not axis=0
+    def test_2d(self, xp):
+        #  Test a 2d case
+        a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = 38.6696271841
+        check_equal_hmean(np.array(a), desired, xp=xp)
+
+    def test_2d_axis0(self, xp):
+        #  Test a 2d case with axis=0
+        a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = np.array([22.88135593, 39.13043478, 52.90076336, 65.45454545])
+        check_equal_hmean(a, desired, axis=0, xp=xp)
+
+    def test_2d_axis0_with_zero(self, xp):
+        a = [[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = np.array([22.88135593, 0.0, 52.90076336, 65.45454545])
+        check_equal_hmean(a, desired, axis=0, xp=xp)
+
+    def test_2d_axis1(self, xp):
+        #  Test a 2d case with axis=1
+        a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = np.array([19.2, 63.03939962, 103.80078637])
+        check_equal_hmean(a, desired, axis=1, xp=xp)
+
+    def test_2d_axis1_with_zero(self, xp):
+        a = [[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = np.array([0.0, 63.03939962, 103.80078637])
+        check_equal_hmean(a, desired, axis=1, xp=xp)
+
+    @pytest.mark.skip_xp_backends(
+        np_only=True,
+        reason='array-likes only supported for NumPy backend',
+    )
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_weights_1d_list(self, xp):
+        # Desired result from:
+        # https://www.hackmath.net/en/math-problem/35871
+        a = [2, 10, 6]
+        weights = [10, 5, 3]
+        desired = 3.
+        # all the other tests use `check_equal_hmean`, which now converts
+        # the input to an xp-array before calling `hmean`. This time, check
+        # that the function still accepts the lists of ints.
+        res = stats.hmean(a, weights=weights)
+        xp_assert_close(res, np.asarray(desired), rtol=1e-5)
+
+    def test_weights_1d(self, xp):
+        # Desired result from:
+        # https://www.hackmath.net/en/math-problem/35871
+        a = np.asarray([2, 10, 6])
+        weights = np.asarray([10, 5, 3])
+        desired = 3
+        check_equal_hmean(a, desired, weights=weights, rtol=1e-5, xp=xp)
+
+    def test_weights_2d_axis0(self, xp):
+        # Desired result from:
+        # https://www.hackmath.net/en/math-problem/35871
+        a = np.array([[2, 5], [10, 5], [6, 5]])
+        weights = np.array([[10, 1], [5, 1], [3, 1]])
+        desired = np.array([3, 5])
+        check_equal_hmean(a, desired, axis=0, weights=weights, rtol=1e-5, xp=xp)
+
+    def test_weights_2d_axis1(self, xp):
+        # Desired result from:
+        # https://www.hackmath.net/en/math-problem/35871
+        a = np.array([[2, 10, 6], [7, 7, 7]])
+        weights = np.array([[10, 5, 3], [1, 1, 1]])
+        desired = np.array([3, 7])
+        check_equal_hmean(a, desired, axis=1, weights=weights, rtol=1e-5, xp=xp)
+
+    @skip_xp_invalid_arg
+    def test_weights_masked_1d_array(self, xp):
+        # Desired result from:
+        # https://www.hackmath.net/en/math-problem/35871
+        a = np.array([2, 10, 6, 42])
+        weights = np.ma.array([10, 5, 3, 42], mask=[0, 0, 0, 1])
+        desired = 3
+        xp = np.ma  # check_equal_hmean uses xp.asarray; this will preserve the mask
+        check_equal_hmean(a, desired, weights=weights, rtol=1e-5,
+                          dtype=np.float64, xp=xp)
+
+
+@array_api_compatible
+class TestGMean:
+    def test_0(self, xp):
+        a = [1, 0, 2]
+        desired = 0
+        check_equal_gmean(a, desired, xp=xp)
+
+    def test_1d(self, xp):
+        #  Test a 1d case
+        a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
+        desired = 45.2872868812
+        check_equal_gmean(a, desired, xp=xp)
+
+        a = [1, 2, 3, 4]
+        desired = power(1 * 2 * 3 * 4, 1. / 4.)
+        check_equal_gmean(a, desired, rtol=1e-14, xp=xp)
+
+        a = array([1, 2, 3, 4], float32)
+        desired = power(1 * 2 * 3 * 4, 1. / 4.)
+        check_equal_gmean(a, desired, dtype=xp.float32, xp=xp)
+
+    # Note the next tests use axis=None as default, not axis=0
+    def test_2d(self, xp):
+        #  Test a 2d case
+        a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = 52.8885199
+        check_equal_gmean(a, desired, xp=xp)
+
+    def test_2d_axis0(self, xp):
+        #  Test a 2d case with axis=0
+        a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = np.array([35.56893304, 49.32424149, 61.3579244, 72.68482371])
+        check_equal_gmean(a, desired, axis=0, xp=xp)
+
+        a = array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
+        desired = array([1, 2, 3, 4])
+        check_equal_gmean(a, desired, axis=0, rtol=1e-14, xp=xp)
+
+    def test_2d_axis1(self, xp):
+        #  Test a 2d case with axis=1
+        a = [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]
+        desired = np.array([22.13363839, 64.02171746, 104.40086817])
+        check_equal_gmean(a, desired, axis=1, xp=xp)
+
+        a = array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
+        v = power(1 * 2 * 3 * 4, 1. / 4.)
+        desired = array([v, v, v])
+        check_equal_gmean(a, desired, axis=1, rtol=1e-14, xp=xp)
+
+    def test_large_values(self, xp):
+        a = array([1e100, 1e200, 1e300])
+        desired = 1e200
+        check_equal_gmean(a, desired, rtol=1e-13, xp=xp)
+
+    def test_1d_with_0(self, xp):
+        #  Test a 1d case with zero element
+        a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 0]
+        desired = 0.0  # due to exp(-inf)=0
+        with np.errstate(all='ignore'):
+            check_equal_gmean(a, desired, xp=xp)
+
+    def test_1d_neg(self, xp):
+        #  Test a 1d case with negative element
+        a = [10, 20, 30, 40, 50, 60, 70, 80, 90, -1]
+        desired = np.nan  # due to log(-1) = nan
+        with np.errstate(invalid='ignore'):
+            check_equal_gmean(a, desired, xp=xp)
+
+    @pytest.mark.skip_xp_backends(
+        np_only=True,
+        reason='array-likes only supported for NumPy backend',
+    )
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_weights_1d_list(self, xp):
+        # Desired result from:
+        # https://www.dummies.com/education/math/business-statistics/how-to-find-the-weighted-geometric-mean-of-a-data-set/
+        a = [1, 2, 3, 4, 5]
+        weights = [2, 5, 6, 4, 3]
+        desired = 2.77748
+
+        # all the other tests use `check_equal_gmean`, which now converts
+        # the input to an xp-array before calling `gmean`. This time, check
+        # that the function still accepts the lists of ints.
+        res = stats.gmean(a, weights=weights)
+        xp_assert_close(res, np.asarray(desired), rtol=1e-5)
+
+    def test_weights_1d(self, xp):
+        # Desired result from:
+        # https://www.dummies.com/education/math/business-statistics/how-to-find-the-weighted-geometric-mean-of-a-data-set/
+        a = np.array([1, 2, 3, 4, 5])
+        weights = np.array([2, 5, 6, 4, 3])
+        desired = 2.77748
+        check_equal_gmean(a, desired, weights=weights, rtol=1e-5, xp=xp)
+
+    @skip_xp_invalid_arg
+    def test_weights_masked_1d_array(self, xp):
+        # Desired result from:
+        # https://www.dummies.com/education/math/business-statistics/how-to-find-the-weighted-geometric-mean-of-a-data-set/
+        a = np.array([1, 2, 3, 4, 5, 6])
+        weights = np.ma.array([2, 5, 6, 4, 3, 5], mask=[0, 0, 0, 0, 0, 1])
+        desired = 2.77748
+        xp = np.ma  # check_equal_gmean uses xp.asarray; this will preserve the mask
+        check_equal_gmean(a, desired, weights=weights, rtol=1e-5,
+                          dtype=np.float64, xp=xp)
+
+
+@array_api_compatible
+class TestPMean:
+
+    def pmean_reference(a, p):
+        return (np.sum(a**p) / a.size)**(1/p)
+
+    def wpmean_reference(a, p, weights):
+        return (np.sum(weights * a**p) / np.sum(weights))**(1/p)
+
+    def test_bad_exponent(self, xp):
+        with pytest.raises(ValueError, match='Power mean only defined for'):
+            stats.pmean(xp.asarray([1, 2, 3]), xp.asarray([0]))
+        with pytest.raises(ValueError, match='Power mean only defined for'):
+            stats.pmean(xp.asarray([1, 2, 3]), xp.asarray([0]))
+
+    def test_1d(self, xp):
+        a, p = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], 3.5
+        desired = TestPMean.pmean_reference(np.array(a), p)
+        check_equal_pmean(a, p, desired, xp=xp)
+
+        a, p = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], -2.5
+        desired = TestPMean.pmean_reference(np.array(a), p)
+        check_equal_pmean(a, p, desired, xp=xp)
+
+        a, p = [1, 2, 3, 4], 2
+        desired = np.sqrt((1**2 + 2**2 + 3**2 + 4**2) / 4)
+        check_equal_pmean(a, p, desired, xp=xp)
+
+    def test_1d_with_zero(self, xp):
+        a, p = np.array([1, 0]), -1
+        desired = 0.0
+        check_equal_pmean(a, p, desired, rtol=0.0, xp=xp)
+
+    @skip_xp_backends('array_api_strict',
+                      reason=("`array_api_strict.where` `fillvalue` doesn't "
+                              "accept Python scalars. See data-apis/array-api#807."))
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_1d_with_negative_value(self, xp):
+        a, p = np.array([1, 0, -1]), 1.23
+        message = "The power mean is only defined..."
+        with pytest.warns(RuntimeWarning, match=message):
+            check_equal_pmean(a, p, xp.nan, xp=xp)
+
+    @pytest.mark.parametrize(
+        ("a", "p"),
+        [([[10, 20], [50, 60], [90, 100]], -0.5),
+         (np.array([[10, 20], [50, 60], [90, 100]]), 0.5)]
+    )
+    def test_2d_axisnone(self, a, p, xp):
+        desired = TestPMean.pmean_reference(np.array(a), p)
+        check_equal_pmean(a, p, desired, xp=xp)
+
+    @pytest.mark.parametrize(
+        ("a", "p"),
+        [([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], -0.5),
+         ([[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], 0.5)]
+    )
+    def test_2d_axis0(self, a, p, xp):
+        desired = [
+            TestPMean.pmean_reference(
+                np.array([a[i][j] for i in range(len(a))]), p
+            )
+            for j in range(len(a[0]))
+        ]
+        check_equal_pmean(a, p, desired, axis=0, xp=xp)
+
+    @pytest.mark.parametrize(
+        ("a", "p"),
+        [([[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], -0.5),
+         ([[10, 0, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]], 0.5)]
+    )
+    def test_2d_axis1(self, a, p, xp):
+        desired = [TestPMean.pmean_reference(np.array(a_), p) for a_ in a]
+        check_equal_pmean(a, p, desired, axis=1, xp=xp)
+
+    def test_weights_1d(self, xp):
+        a, p = [2, 10, 6], -1.23456789
+        weights = [10, 5, 3]
+        desired = TestPMean.wpmean_reference(np.array(a), p, weights)
+        check_equal_pmean(a, p, desired, weights=weights, rtol=1e-5, xp=xp)
+
+    @pytest.mark.skip_xp_backends(
+        np_only=True,
+        reason='array-likes only supported for NumPy backend',
+    )
+    @pytest.mark.usefixtures("skip_xp_backends")
+    def test_weights_1d_list(self, xp):
+        a, p = [2, 10, 6], -1.23456789
+        weights = [10, 5, 3]
+        desired = TestPMean.wpmean_reference(np.array(a), p, weights)
+        # all the other tests use `check_equal_pmean`, which now converts
+        # the input to an xp-array before calling `pmean`. This time, check
+        # that the function still accepts the lists of ints.
+        res = stats.pmean(a, p, weights=weights)
+        xp_assert_close(res, np.asarray(desired), rtol=1e-5)
+
+    @skip_xp_invalid_arg
+    def test_weights_masked_1d_array(self, xp):
+        a, p = np.array([2, 10, 6, 42]), 1
+        weights = np.ma.array([10, 5, 3, 42], mask=[0, 0, 0, 1])
+        desired = np.average(a, weights=weights)
+        xp = np.ma  # check_equal_pmean uses xp.asarray; this will preserve the mask
+        check_equal_pmean(a, p, desired, weights=weights, rtol=1e-5,
+                          dtype=np.float64, xp=xp)
+
+    @pytest.mark.parametrize(
+        ("axis", "fun_name", "p"),
+        [(None, "wpmean_reference", 9.87654321),
+         (0, "gmean", 0),
+         (1, "hmean", -1)]
+    )
+    def test_weights_2d(self, axis, fun_name, p, xp):
+        if fun_name == 'wpmean_reference':
+            def fun(a, axis, weights):
+                return TestPMean.wpmean_reference(a, p, weights)
+        else:
+            fun = getattr(stats, fun_name)
+        a = np.array([[2, 5], [10, 5], [6, 5]])
+        weights = np.array([[10, 1], [5, 1], [3, 1]])
+        desired = fun(a, axis=axis, weights=weights)
+        check_equal_pmean(a, p, desired, axis=axis, weights=weights, rtol=1e-5, xp=xp)
+
+
+class TestGSTD:
+    # must add 1 as `gstd` is only defined for positive values
+    array_1d = np.arange(2 * 3 * 4) + 1
+    gstd_array_1d = 2.294407613602
+    array_3d = array_1d.reshape(2, 3, 4)
+
+    def test_1d_array(self):
+        gstd_actual = stats.gstd(self.array_1d)
+        assert_allclose(gstd_actual, self.gstd_array_1d)
+
+    def test_1d_numeric_array_like_input(self):
+        gstd_actual = stats.gstd(tuple(self.array_1d))
+        assert_allclose(gstd_actual, self.gstd_array_1d)
+
+    def test_raises_value_error_non_numeric_input(self):
+        # this is raised by NumPy, but it's quite interpretable
+        with pytest.raises(TypeError, match="ufunc 'log' not supported"):
+            stats.gstd('You cannot take the logarithm of a string.')
+
+    @pytest.mark.parametrize('bad_value', (0, -1, np.inf, np.nan))
+    def test_returns_nan_invalid_value(self, bad_value):
+        x = np.append(self.array_1d, [bad_value])
+        if np.isfinite(bad_value):
+            message = "The geometric standard deviation is only defined..."
+            with pytest.warns(RuntimeWarning, match=message):
+                res = stats.gstd(x)
+        else:
+            res = stats.gstd(x)
+        assert_equal(res, np.nan)
+
+    def test_propagates_nan_values(self):
+        a = array([[1, 1, 1, 16], [np.nan, 1, 2, 3]])
+        gstd_actual = stats.gstd(a, axis=1)
+        assert_allclose(gstd_actual, np.array([4, np.nan]))
+
+    def test_ddof_equal_to_number_of_observations(self):
+        with pytest.warns(RuntimeWarning, match='Degrees of freedom <= 0'):
+            assert_equal(stats.gstd(self.array_1d, ddof=self.array_1d.size), np.inf)
+
+    def test_3d_array(self):
+        gstd_actual = stats.gstd(self.array_3d, axis=None)
+        assert_allclose(gstd_actual, self.gstd_array_1d)
+
+    def test_3d_array_axis_type_tuple(self):
+        gstd_actual = stats.gstd(self.array_3d, axis=(1,2))
+        assert_allclose(gstd_actual, [2.12939215, 1.22120169])
+
+    def test_3d_array_axis_0(self):
+        gstd_actual = stats.gstd(self.array_3d, axis=0)
+        gstd_desired = np.array([
+            [6.1330555493918, 3.958900210120, 3.1206598248344, 2.6651441426902],
+            [2.3758135028411, 2.174581428192, 2.0260062829505, 1.9115518327308],
+            [1.8205343606803, 1.746342404566, 1.6846557065742, 1.6325269194382]
+        ])
+        assert_allclose(gstd_actual, gstd_desired)
+
+    def test_3d_array_axis_1(self):
+        gstd_actual = stats.gstd(self.array_3d, axis=1)
+        gstd_desired = np.array([
+            [3.118993630946, 2.275985934063, 1.933995977619, 1.742896469724],
+            [1.271693593916, 1.254158641801, 1.238774141609, 1.225164057869]
+        ])
+        assert_allclose(gstd_actual, gstd_desired)
+
+    def test_3d_array_axis_2(self):
+        gstd_actual = stats.gstd(self.array_3d, axis=2)
+        gstd_desired = np.array([
+            [1.8242475707664, 1.2243686572447, 1.1318311657788],
+            [1.0934830582351, 1.0724479791887, 1.0591498540749]
+        ])
+        assert_allclose(gstd_actual, gstd_desired)
+
+    def test_masked_3d_array(self):
+        ma = np.ma.masked_where(self.array_3d > 16, self.array_3d)
+        message = "`gstd` support for masked array input was deprecated in..."
+        with pytest.warns(DeprecationWarning, match=message):
+            gstd_actual = stats.gstd(ma, axis=2)
+        gstd_desired = stats.gstd(self.array_3d, axis=2)
+        mask = [[0, 0, 0], [0, 1, 1]]
+        assert_allclose(gstd_actual, gstd_desired)
+        assert_equal(gstd_actual.mask, mask)
+
+
+def test_binomtest():
+    # precision tests compared to R for ticket:986
+    pp = np.concatenate((np.linspace(0.1, 0.2, 5),
+                         np.linspace(0.45, 0.65, 5),
+                         np.linspace(0.85, 0.95, 5)))
+    n = 501
+    x = 450
+    results = [0.0, 0.0, 1.0159969301994141e-304,
+               2.9752418572150531e-275, 7.7668382922535275e-250,
+               2.3381250925167094e-099, 7.8284591587323951e-081,
+               9.9155947819961383e-065, 2.8729390725176308e-050,
+               1.7175066298388421e-037, 0.0021070691951093692,
+               0.12044570587262322, 0.88154763174802508, 0.027120993063129286,
+               2.6102587134694721e-006]
+
+    for p, res in zip(pp, results):
+        assert_approx_equal(stats.binomtest(x, n, p).pvalue, res,
+                            significant=12, err_msg=f'fail forp={p}')
+    assert_approx_equal(stats.binomtest(50, 100, 0.1).pvalue,
+                        5.8320387857343647e-024,
+                        significant=12)
+
+
+def test_binomtest2():
+    # test added for issue #2384
+    res2 = [
+        [1.0, 1.0],
+        [0.5, 1.0, 0.5],
+        [0.25, 1.00, 1.00, 0.25],
+        [0.125, 0.625, 1.000, 0.625, 0.125],
+        [0.0625, 0.3750, 1.0000, 1.0000, 0.3750, 0.0625],
+        [0.03125, 0.21875, 0.68750, 1.00000, 0.68750, 0.21875, 0.03125],
+        [0.015625, 0.125000, 0.453125, 1.000000, 1.000000, 0.453125, 0.125000,
+         0.015625],
+        [0.0078125, 0.0703125, 0.2890625, 0.7265625, 1.0000000, 0.7265625,
+         0.2890625, 0.0703125, 0.0078125],
+        [0.00390625, 0.03906250, 0.17968750, 0.50781250, 1.00000000,
+         1.00000000, 0.50781250, 0.17968750, 0.03906250, 0.00390625],
+        [0.001953125, 0.021484375, 0.109375000, 0.343750000, 0.753906250,
+         1.000000000, 0.753906250, 0.343750000, 0.109375000, 0.021484375,
+         0.001953125]
+    ]
+    for k in range(1, 11):
+        res1 = [stats.binomtest(v, k, 0.5).pvalue for v in range(k + 1)]
+        assert_almost_equal(res1, res2[k-1], decimal=10)
+
+
+def test_binomtest3():
+    # test added for issue #2384
+    # test when x == n*p and neighbors
+    res3 = [stats.binomtest(v, v*k, 1./k).pvalue
+            for v in range(1, 11) for k in range(2, 11)]
+    assert_equal(res3, np.ones(len(res3), int))
+
+    # > bt=c()
+    # > for(i in as.single(1:10)) {
+    # +     for(k in as.single(2:10)) {
+    # +         bt = c(bt, binom.test(i-1, k*i,(1/k))$p.value);
+    # +         print(c(i+1, k*i,(1/k)))
+    # +     }
+    # + }
+    binom_testm1 = np.array([
+         0.5, 0.5555555555555556, 0.578125, 0.5904000000000003,
+         0.5981224279835393, 0.603430543396034, 0.607304096221924,
+         0.610255656871054, 0.612579511000001, 0.625, 0.670781893004115,
+         0.68853759765625, 0.6980101120000006, 0.703906431368616,
+         0.70793209416498, 0.7108561134173507, 0.713076544331419,
+         0.714820192935702, 0.6875, 0.7268709038256367, 0.7418963909149174,
+         0.74986110468096, 0.7548015520398076, 0.7581671424768577,
+         0.760607984787832, 0.762459425024199, 0.7639120677676575, 0.7265625,
+         0.761553963657302, 0.774800934828818, 0.7818005980538996,
+         0.78613491480358, 0.789084353140195, 0.7912217659828884,
+         0.79284214559524, 0.794112956558801, 0.75390625, 0.7856929451142176,
+         0.7976688481430754, 0.8039848974727624, 0.807891868948366,
+         0.8105487660137676, 0.812473307174702, 0.8139318233591120,
+         0.815075399104785, 0.7744140625, 0.8037322594985427,
+         0.814742863657656, 0.8205425178645808, 0.8241275984172285,
+         0.8265645374416, 0.8283292196088257, 0.829666291102775,
+         0.8307144686362666, 0.7905273437499996, 0.8178712053954738,
+         0.828116983756619, 0.833508948940494, 0.8368403871552892,
+         0.839104213210105, 0.840743186196171, 0.84198481438049,
+         0.8429580531563676, 0.803619384765625, 0.829338573944648,
+         0.8389591907548646, 0.84401876783902, 0.84714369697889,
+         0.8492667010581667, 0.850803474598719, 0.851967542858308,
+         0.8528799045949524, 0.8145294189453126, 0.838881732845347,
+         0.847979024541911, 0.852760894015685, 0.8557134656773457,
+         0.8577190131799202, 0.85917058278431, 0.860270010472127,
+         0.861131648404582, 0.823802947998047, 0.846984756807511,
+         0.855635653643743, 0.860180994825685, 0.86298688573253,
+         0.864892525675245, 0.866271647085603, 0.867316125625004,
+         0.8681346531755114
+        ])
+
+    # > bt=c()
+    # > for(i in as.single(1:10)) {
+    # +     for(k in as.single(2:10)) {
+    # +         bt = c(bt, binom.test(i+1, k*i,(1/k))$p.value);
+    # +         print(c(i+1, k*i,(1/k)))
+    # +     }
+    # + }
+
+    binom_testp1 = np.array([
+         0.5, 0.259259259259259, 0.26171875, 0.26272, 0.2632244513031551,
+         0.2635138663069203, 0.2636951804161073, 0.2638162407564354,
+         0.2639010709000002, 0.625, 0.4074074074074074, 0.42156982421875,
+         0.4295746560000003, 0.43473045988554, 0.4383309503172684,
+         0.4409884859402103, 0.4430309389962837, 0.444649849401104, 0.6875,
+         0.4927602499618962, 0.5096031427383425, 0.5189636628480,
+         0.5249280070771274, 0.5290623300865124, 0.5320974248125793,
+         0.5344204730474308, 0.536255847400756, 0.7265625, 0.5496019313526808,
+         0.5669248746708034, 0.576436455045805, 0.5824538812831795,
+         0.5866053321547824, 0.589642781414643, 0.5919618019300193,
+         0.593790427805202, 0.75390625, 0.590868349763505, 0.607983393277209,
+         0.617303847446822, 0.623172512167948, 0.627208862156123,
+         0.6301556891501057, 0.632401894928977, 0.6341708982290303,
+         0.7744140625, 0.622562037497196, 0.639236102912278, 0.648263335014579,
+         0.65392850011132, 0.657816519817211, 0.660650782947676,
+         0.662808780346311, 0.6645068560246006, 0.7905273437499996,
+         0.6478843304312477, 0.6640468318879372, 0.6727589686071775,
+         0.6782129857784873, 0.681950188903695, 0.684671508668418,
+         0.686741824999918, 0.688369886732168, 0.803619384765625,
+         0.668716055304315, 0.684360013879534, 0.6927642396829181,
+         0.6980155964704895, 0.701609591890657, 0.7042244320992127,
+         0.7062125081341817, 0.707775152962577, 0.8145294189453126,
+         0.686243374488305, 0.7013873696358975, 0.709501223328243,
+         0.714563595144314, 0.718024953392931, 0.7205416252126137,
+         0.722454130389843, 0.723956813292035, 0.823802947998047,
+         0.701255953767043, 0.715928221686075, 0.723772209289768,
+         0.7286603031173616, 0.7319999279787631, 0.7344267920995765,
+         0.736270323773157, 0.737718376096348
+        ])
+
+    res4_p1 = [stats.binomtest(v+1, v*k, 1./k).pvalue
+               for v in range(1, 11) for k in range(2, 11)]
+    res4_m1 = [stats.binomtest(v-1, v*k, 1./k).pvalue
+               for v in range(1, 11) for k in range(2, 11)]
+
+    assert_almost_equal(res4_p1, binom_testp1, decimal=13)
+    assert_almost_equal(res4_m1, binom_testm1, decimal=13)
+
+
+class TestTrim:
+    # test trim functions
+    def test_trim1(self):
+        a = np.arange(11)
+        assert_equal(np.sort(stats.trim1(a, 0.1)), np.arange(10))
+        assert_equal(np.sort(stats.trim1(a, 0.2)), np.arange(9))
+        assert_equal(np.sort(stats.trim1(a, 0.2, tail='left')),
+                     np.arange(2, 11))
+        assert_equal(np.sort(stats.trim1(a, 3/11., tail='left')),
+                     np.arange(3, 11))
+        assert_equal(stats.trim1(a, 1.0), [])
+        assert_equal(stats.trim1(a, 1.0, tail='left'), [])
+
+        # empty input
+        assert_equal(stats.trim1([], 0.1), [])
+        assert_equal(stats.trim1([], 3/11., tail='left'), [])
+        assert_equal(stats.trim1([], 4/6.), [])
+
+        # test axis
+        a = np.arange(24).reshape(6, 4)
+        ref = np.arange(4, 24).reshape(5, 4)  # first row trimmed
+
+        axis = 0
+        trimmed = stats.trim1(a, 0.2, tail='left', axis=axis)
+        assert_equal(np.sort(trimmed, axis=axis), ref)
+
+        axis = 1
+        trimmed = stats.trim1(a.T, 0.2, tail='left', axis=axis)
+        assert_equal(np.sort(trimmed, axis=axis), ref.T)
+
+    def test_trimboth(self):
+        a = np.arange(11)
+        assert_equal(np.sort(stats.trimboth(a, 3/11.)), np.arange(3, 8))
+        assert_equal(np.sort(stats.trimboth(a, 0.2)),
+                     np.array([2, 3, 4, 5, 6, 7, 8]))
+        assert_equal(np.sort(stats.trimboth(np.arange(24).reshape(6, 4), 0.2)),
+                     np.arange(4, 20).reshape(4, 4))
+        assert_equal(np.sort(stats.trimboth(np.arange(24).reshape(4, 6).T,
+                                            2/6.)),
+                     np.array([[2, 8, 14, 20], [3, 9, 15, 21]]))
+        assert_raises(ValueError, stats.trimboth,
+                      np.arange(24).reshape(4, 6).T, 4/6.)
+
+        # empty input
+        assert_equal(stats.trimboth([], 0.1), [])
+        assert_equal(stats.trimboth([], 3/11.), [])
+        assert_equal(stats.trimboth([], 4/6.), [])
+
+    def test_trim_mean(self):
+        # don't use pre-sorted arrays
+        a = np.array([4, 8, 2, 0, 9, 5, 10, 1, 7, 3, 6])
+        idx = np.array([3, 5, 0, 1, 2, 4])
+        a2 = np.arange(24).reshape(6, 4)[idx, :]
+        a3 = np.arange(24).reshape(6, 4, order='F')[idx, :]
+        assert_equal(stats.trim_mean(a3, 2/6.),
+                     np.array([2.5, 8.5, 14.5, 20.5]))
+        assert_equal(stats.trim_mean(a2, 2/6.),
+                     np.array([10., 11., 12., 13.]))
+        idx4 = np.array([1, 0, 3, 2])
+        a4 = np.arange(24).reshape(4, 6)[idx4, :]
+        assert_equal(stats.trim_mean(a4, 2/6.),
+                     np.array([9., 10., 11., 12., 13., 14.]))
+        # shuffled arange(24) as array_like
+        a = [7, 11, 12, 21, 16, 6, 22, 1, 5, 0, 18, 10, 17, 9, 19, 15, 23,
+             20, 2, 14, 4, 13, 8, 3]
+        assert_equal(stats.trim_mean(a, 2/6.), 11.5)
+        assert_equal(stats.trim_mean([5,4,3,1,2,0], 2/6.), 2.5)
+
+        # check axis argument
+        np.random.seed(1234)
+        a = np.random.randint(20, size=(5, 6, 4, 7))
+        for axis in [0, 1, 2, 3, -1]:
+            res1 = stats.trim_mean(a, 2/6., axis=axis)
+            res2 = stats.trim_mean(np.moveaxis(a, axis, 0), 2/6.)
+            assert_equal(res1, res2)
+
+        res1 = stats.trim_mean(a, 2/6., axis=None)
+        res2 = stats.trim_mean(a.ravel(), 2/6.)
+        assert_equal(res1, res2)
+
+        assert_raises(ValueError, stats.trim_mean, a, 0.6)
+
+        # empty input
+        assert_equal(stats.trim_mean([], 0.0), np.nan)
+        assert_equal(stats.trim_mean([], 0.6), np.nan)
+
+
+class TestSigmaClip:
+    def test_sigmaclip1(self):
+        a = np.concatenate((np.linspace(9.5, 10.5, 31), np.linspace(0, 20, 5)))
+        fact = 4  # default
+        c, low, upp = stats.sigmaclip(a)
+        assert_(c.min() > low)
+        assert_(c.max() < upp)
+        assert_equal(low, c.mean() - fact*c.std())
+        assert_equal(upp, c.mean() + fact*c.std())
+        assert_equal(c.size, a.size)
+
+    def test_sigmaclip2(self):
+        a = np.concatenate((np.linspace(9.5, 10.5, 31), np.linspace(0, 20, 5)))
+        fact = 1.5
+        c, low, upp = stats.sigmaclip(a, fact, fact)
+        assert_(c.min() > low)
+        assert_(c.max() < upp)
+        assert_equal(low, c.mean() - fact*c.std())
+        assert_equal(upp, c.mean() + fact*c.std())
+        assert_equal(c.size, 4)
+        assert_equal(a.size, 36)  # check original array unchanged
+
+    def test_sigmaclip3(self):
+        a = np.concatenate((np.linspace(9.5, 10.5, 11),
+                            np.linspace(-100, -50, 3)))
+        fact = 1.8
+        c, low, upp = stats.sigmaclip(a, fact, fact)
+        assert_(c.min() > low)
+        assert_(c.max() < upp)
+        assert_equal(low, c.mean() - fact*c.std())
+        assert_equal(upp, c.mean() + fact*c.std())
+        assert_equal(c, np.linspace(9.5, 10.5, 11))
+
+    def test_sigmaclip_result_attributes(self):
+        a = np.concatenate((np.linspace(9.5, 10.5, 11),
+                            np.linspace(-100, -50, 3)))
+        fact = 1.8
+        res = stats.sigmaclip(a, fact, fact)
+        attributes = ('clipped', 'lower', 'upper')
+        check_named_results(res, attributes)
+
+    def test_std_zero(self):
+        # regression test #8632
+        x = np.ones(10)
+        assert_equal(stats.sigmaclip(x)[0], x)
+
+
+class TestAlexanderGovern:
+    def test_compare_dtypes(self):
+        args = [[13, 13, 13, 13, 13, 13, 13, 12, 12],
+                [14, 13, 12, 12, 12, 12, 12, 11, 11],
+                [14, 14, 13, 13, 13, 13, 13, 12, 12],
+                [15, 14, 13, 13, 13, 12, 12, 12, 11]]
+        args_int16 = [np.asarray(arg, dtype=np.int16) for arg in args]
+        args_int32 = [np.asarray(arg, dtype=np.int32) for arg in args]
+        args_uint8 = [np.asarray(arg, dtype=np.uint8) for arg in args]
+        args_float64 = [np.asarray(arg, dtype=np.float64) for arg in args]
+
+        res_int16 = stats.alexandergovern(*args_int16)
+        res_int32 = stats.alexandergovern(*args_int32)
+        res_uint8 = stats.alexandergovern(*args_uint8)
+        res_float64 = stats.alexandergovern(*args_float64)
+
+        assert (res_int16.pvalue == res_int32.pvalue ==
+                res_uint8.pvalue == res_float64.pvalue)
+        assert (res_int16.statistic == res_int32.statistic ==
+                res_uint8.statistic == res_float64.statistic)
+
+    @pytest.mark.parametrize('case',[([1, 2], []), ([1, 2], 2), ([1, 2], [2])])
+    def test_too_small_inputs(self, case):
+        # input array is of size zero or too small
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            res = stats.alexandergovern(*case)
+            assert_equal(res.statistic, np.nan)
+            assert_equal(res.pvalue, np.nan)
+
+    def test_bad_inputs(self):
+        # inputs are not finite (infinity)
+        with np.errstate(invalid='ignore'):
+            res = stats.alexandergovern([1, 2], [np.inf, np.inf])
+        assert_equal(res.statistic, np.nan)
+        assert_equal(res.pvalue, np.nan)
+
+    def test_compare_r(self):
+        '''
+        Data generated in R with
+        > set.seed(1)
+        > library("onewaytests")
+        > library("tibble")
+        > y <- c(rnorm(40, sd=10),
+        +        rnorm(30, sd=15),
+        +        rnorm(20, sd=20))
+        > x <- c(rep("one", times=40),
+        +        rep("two", times=30),
+        +        rep("eight", times=20))
+        > x <- factor(x)
+        > ag.test(y ~ x, tibble(y,x))
+
+        Alexander-Govern Test (alpha = 0.05)
+        -------------------------------------------------------------
+        data : y and x
+
+        statistic  : 1.359941
+        parameter  : 2
+        p.value    : 0.5066321
+
+        Result     : Difference is not statistically significant.
+        -------------------------------------------------------------
+        Example adapted from:
+        https://eval-serv2.metpsy.uni-jena.de/wiki-metheval-hp/index.php/R_FUN_Alexander-Govern
+
+        '''
+        one = [-6.264538107423324, 1.8364332422208225, -8.356286124100471,
+               15.952808021377916, 3.295077718153605, -8.204683841180152,
+               4.874290524284853, 7.383247051292173, 5.757813516534923,
+               -3.0538838715635603, 15.11781168450848, 3.898432364114311,
+               -6.2124058054180376, -22.146998871774997, 11.249309181431082,
+               -0.4493360901523085, -0.16190263098946087, 9.438362106852992,
+               8.212211950980885, 5.939013212175088, 9.189773716082183,
+               7.821363007310671, 0.745649833651906, -19.89351695863373,
+               6.198257478947102, -0.5612873952900078, -1.557955067053293,
+               -14.707523838992744, -4.781500551086204, 4.179415601997024,
+               13.58679551529044, -1.0278772734299553, 3.876716115593691,
+               -0.5380504058290512, -13.770595568286065, -4.149945632996798,
+               -3.942899537103493, -0.5931339671118566, 11.000253719838831,
+               7.631757484575442]
+
+        two = [-2.4678539438038034, -3.8004252020476135, 10.454450631071062,
+               8.34994798010486, -10.331335418242798, -10.612427354431794,
+               5.468729432052455, 11.527993867731237, -1.6851931822534207,
+               13.216615896813222, 5.971588205506021, -9.180395898761569,
+               5.116795371366372, -16.94044644121189, 21.495355525515556,
+               29.7059984775879, -5.508322146997636, -15.662019394747961,
+               8.545794411636193, -2.0258190582123654, 36.024266407571645,
+               -0.5886000409975387, 10.346090436761651, 0.4200323817099909,
+               -11.14909813323608, 2.8318844927151434, -27.074379433365568,
+               21.98332292344329, 2.2988000731784655, 32.58917505543229]
+
+        eight = [9.510190577993251, -14.198928618436291, 12.214527069781099,
+                 -18.68195263288503, -25.07266800478204, 5.828924710349257,
+                 -8.86583746436866, 0.02210703263248262, 1.4868264830332811,
+                 -11.79041892376144, -11.37337465637004, -2.7035723024766414,
+                 23.56173993146409, -30.47133600859524, 11.878923752568431,
+                 6.659007424270365, 21.261996745527256, -6.083678472686013,
+                 7.400376198325763, 5.341975815444621]
+
+        one, two, eight = np.asarray(one), np.asarray(two), np.asarray(eight)
+        soln = stats.alexandergovern(one, two, eight)
+        assert_allclose(soln.statistic, 1.3599405447999450836)
+        assert_allclose(soln.pvalue, 0.50663205309676440091)
+
+    def test_compare_scholar(self):
+        '''
+        Data taken from 'The Modification and Evaluation of the
+        Alexander-Govern Test in Terms of Power' by Kingsley Ochuko, T.,
+        Abdullah, S., Binti Zain, Z., & Soaad Syed Yahaya, S. (2015).
+        '''
+        young = [482.43, 484.36, 488.84, 495.15, 495.24, 502.69, 504.62,
+                 518.29, 519.1, 524.1, 524.12, 531.18, 548.42, 572.1, 584.68,
+                 609.09, 609.53, 666.63, 676.4]
+        middle = [335.59, 338.43, 353.54, 404.27, 437.5, 469.01, 485.85,
+                  487.3, 493.08, 494.31, 499.1, 886.41]
+        old = [519.01, 528.5, 530.23, 536.03, 538.56, 538.83, 557.24, 558.61,
+               558.95, 565.43, 586.39, 594.69, 629.22, 645.69, 691.84]
+        young, middle, old = np.asarray(young), np.asarray(middle), np.asarray(old)
+        soln = stats.alexandergovern(young, middle, old)
+        assert_allclose(soln.statistic, 5.3237, atol=1e-3)
+        assert_allclose(soln.pvalue, 0.06982, atol=1e-4)
+
+        # verify with ag.test in r
+        '''
+        > library("onewaytests")
+        > library("tibble")
+        > young <- c(482.43, 484.36, 488.84, 495.15, 495.24, 502.69, 504.62,
+        +                  518.29, 519.1, 524.1, 524.12, 531.18, 548.42, 572.1,
+        +                  584.68, 609.09, 609.53, 666.63, 676.4)
+        > middle <- c(335.59, 338.43, 353.54, 404.27, 437.5, 469.01, 485.85,
+        +                   487.3, 493.08, 494.31, 499.1, 886.41)
+        > old <- c(519.01, 528.5, 530.23, 536.03, 538.56, 538.83, 557.24,
+        +                   558.61, 558.95, 565.43, 586.39, 594.69, 629.22,
+        +                   645.69, 691.84)
+        > young_fct <- c(rep("young", times=19))
+        > middle_fct <-c(rep("middle", times=12))
+        > old_fct <- c(rep("old", times=15))
+        > ag.test(a ~ b, tibble(a=c(young, middle, old), b=factor(c(young_fct,
+        +                                              middle_fct, old_fct))))
+
+        Alexander-Govern Test (alpha = 0.05)
+        -------------------------------------------------------------
+        data : a and b
+
+        statistic  : 5.324629
+        parameter  : 2
+        p.value    : 0.06978651
+
+        Result     : Difference is not statistically significant.
+        -------------------------------------------------------------
+
+        '''
+        assert_allclose(soln.statistic, 5.324629)
+        assert_allclose(soln.pvalue, 0.06978651)
+
+    def test_compare_scholar3(self):
+        '''
+        Data taken from 'Robustness And Comparative Power Of WelchAspin,
+        Alexander-Govern And Yuen Tests Under Non-Normality And Variance
+        Heteroscedasticity', by Ayed A. Almoied. 2017. Page 34-37.
+        https://digitalcommons.wayne.edu/cgi/viewcontent.cgi?article=2775&context=oa_dissertations
+        '''
+        x1 = [-1.77559, -1.4113, -0.69457, -0.54148, -0.18808, -0.07152,
+              0.04696, 0.051183, 0.148695, 0.168052, 0.422561, 0.458555,
+              0.616123, 0.709968, 0.839956, 0.857226, 0.929159, 0.981442,
+              0.999554, 1.642958]
+        x2 = [-1.47973, -1.2722, -0.91914, -0.80916, -0.75977, -0.72253,
+              -0.3601, -0.33273, -0.28859, -0.09637, -0.08969, -0.01824,
+              0.260131, 0.289278, 0.518254, 0.683003, 0.877618, 1.172475,
+              1.33964, 1.576766]
+        x1, x2 = np.asarray(x1), np.asarray(x2)
+        soln = stats.alexandergovern(x1, x2)
+        assert_allclose(soln.statistic, 0.713526, atol=1e-5)
+        assert_allclose(soln.pvalue, 0.398276, atol=1e-5)
+
+        '''
+        tested in ag.test in R:
+        > library("onewaytests")
+        > library("tibble")
+        > x1 <- c(-1.77559, -1.4113, -0.69457, -0.54148, -0.18808, -0.07152,
+        +          0.04696, 0.051183, 0.148695, 0.168052, 0.422561, 0.458555,
+        +          0.616123, 0.709968, 0.839956, 0.857226, 0.929159, 0.981442,
+        +          0.999554, 1.642958)
+        > x2 <- c(-1.47973, -1.2722, -0.91914, -0.80916, -0.75977, -0.72253,
+        +         -0.3601, -0.33273, -0.28859, -0.09637, -0.08969, -0.01824,
+        +         0.260131, 0.289278, 0.518254, 0.683003, 0.877618, 1.172475,
+        +         1.33964, 1.576766)
+        > x1_fact <- c(rep("x1", times=20))
+        > x2_fact <- c(rep("x2", times=20))
+        > a <- c(x1, x2)
+        > b <- factor(c(x1_fact, x2_fact))
+        > ag.test(a ~ b, tibble(a, b))
+        Alexander-Govern Test (alpha = 0.05)
+        -------------------------------------------------------------
+        data : a and b
+
+        statistic  : 0.7135182
+        parameter  : 1
+        p.value    : 0.3982783
+
+        Result     : Difference is not statistically significant.
+        -------------------------------------------------------------
+        '''
+        assert_allclose(soln.statistic, 0.7135182)
+        assert_allclose(soln.pvalue, 0.3982783)
+
+    def test_nan_policy_propagate(self):
+        args = np.asarray([1, 2, 3, 4]), np.asarray([1, np.nan])
+        # default nan_policy is 'propagate'
+        res = stats.alexandergovern(*args)
+        assert_equal(res.pvalue, np.nan)
+        assert_equal(res.statistic, np.nan)
+
+    def test_nan_policy_raise(self):
+        args = np.asarray([1, 2, 3, 4]), np.asarray([1, np.nan])
+        with assert_raises(ValueError, match="The input contains nan values"):
+            stats.alexandergovern(*args, nan_policy='raise')
+
+    def test_nan_policy_omit(self):
+        args_nan = np.asarray([1, 2, 3, np.nan, 4]), np.asarray([1, np.nan, 19, 25])
+        args_no_nan = np.asarray([1, 2, 3, 4]), np.asarray([1, 19, 25])
+        res_nan = stats.alexandergovern(*args_nan, nan_policy='omit')
+        res_no_nan = stats.alexandergovern(*args_no_nan)
+        assert_equal(res_nan.pvalue, res_no_nan.pvalue)
+        assert_equal(res_nan.statistic, res_no_nan.statistic)
+
+    def test_constant_input(self):
+        # Zero variance input, consistent with `stats.pearsonr`
+        x1 = np.asarray([0.667, 0.667, 0.667])
+        x2 = np.asarray([0.123, 0.456, 0.789])
+        with pytest.warns(RuntimeWarning, match="Precision loss occurred..."):
+            res = stats.alexandergovern(x1, x2)
+        assert_equal(res.statistic, np.nan)
+        assert_equal(res.pvalue, np.nan)
+
+
+class TestFOneWay:
+
+    def test_trivial(self):
+        # A trivial test of stats.f_oneway, with F=0.
+        F, p = stats.f_oneway([0, 2], [0, 2])
+        assert_equal(F, 0.0)
+        assert_equal(p, 1.0)
+
+    def test_basic(self):
+        # Despite being a floating point calculation, this data should
+        # result in F being exactly 2.0.
+        F, p = stats.f_oneway([0, 2], [2, 4])
+        assert_equal(F, 2.0)
+        assert_allclose(p, 1 - np.sqrt(0.5), rtol=1e-14)
+
+    def test_known_exact(self):
+        # Another trivial dataset for which the exact F and p can be
+        # calculated.
+        F, p = stats.f_oneway([2], [2], [2, 3, 4])
+        # The use of assert_equal might be too optimistic, but the calculation
+        # in this case is trivial enough that it is likely to go through with
+        # no loss of precision.
+        assert_equal(F, 3/5)
+        assert_equal(p, 5/8)
+
+    def test_large_integer_array(self):
+        a = np.array([655, 788], dtype=np.uint16)
+        b = np.array([789, 772], dtype=np.uint16)
+        F, p = stats.f_oneway(a, b)
+        # The expected value was verified by computing it with mpmath with
+        # 40 digits of precision.
+        assert_allclose(F, 0.77450216931805540, rtol=1e-14)
+
+    def test_result_attributes(self):
+        a = np.array([655, 788], dtype=np.uint16)
+        b = np.array([789, 772], dtype=np.uint16)
+        res = stats.f_oneway(a, b)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes)
+
+    def test_nist(self):
+        # These are the nist ANOVA files. They can be found at:
+        # https://www.itl.nist.gov/div898/strd/anova/anova.html
+        filenames = ['SiRstv.dat', 'SmLs01.dat', 'SmLs02.dat', 'SmLs03.dat',
+                     'AtmWtAg.dat', 'SmLs04.dat', 'SmLs05.dat', 'SmLs06.dat',
+                     'SmLs07.dat', 'SmLs08.dat', 'SmLs09.dat']
+
+        for test_case in filenames:
+            rtol = 1e-7
+            fname = os.path.abspath(os.path.join(os.path.dirname(__file__),
+                                                 'data/nist_anova', test_case))
+            with open(fname) as f:
+                content = f.read().split('\n')
+            certified = [line.split() for line in content[40:48]
+                         if line.strip()]
+            dataf = np.loadtxt(fname, skiprows=60)
+            y, x = dataf.T
+            y = y.astype(int)
+            caty = np.unique(y)
+            f = float(certified[0][-1])
+
+            xlist = [x[y == i] for i in caty]
+            res = stats.f_oneway(*xlist)
+
+            # With the hard test cases we relax the tolerance a bit.
+            hard_tc = ('SmLs07.dat', 'SmLs08.dat', 'SmLs09.dat')
+            if test_case in hard_tc:
+                rtol = 1e-4
+
+            assert_allclose(res[0], f, rtol=rtol,
+                            err_msg=f'Failing testcase: {test_case}')
+
+    @pytest.mark.parametrize("a, b, expected", [
+        (np.array([42, 42, 42]), np.array([7, 7, 7]), (np.inf, 0)),
+        (np.array([42, 42, 42]), np.array([42, 42, 42]), (np.nan, np.nan))
+        ])
+    def test_constant_input(self, a, b, expected):
+        # For more details, look on https://github.com/scipy/scipy/issues/11669
+        msg = "Each of the input arrays is constant;"
+        with pytest.warns(stats.ConstantInputWarning, match=msg):
+            f, p = stats.f_oneway(a, b)
+            assert f, p == expected
+
+    @pytest.mark.parametrize('axis', [-2, -1, 0, 1])
+    def test_2d_inputs(self, axis):
+        a = np.array([[1, 4, 3, 3],
+                      [2, 5, 3, 3],
+                      [3, 6, 3, 3],
+                      [2, 3, 3, 3],
+                      [1, 4, 3, 3]])
+        b = np.array([[3, 1, 5, 3],
+                      [4, 6, 5, 3],
+                      [4, 3, 5, 3],
+                      [1, 5, 5, 3],
+                      [5, 5, 5, 3],
+                      [2, 3, 5, 3],
+                      [8, 2, 5, 3],
+                      [2, 2, 5, 3]])
+        c = np.array([[4, 3, 4, 3],
+                      [4, 2, 4, 3],
+                      [5, 4, 4, 3],
+                      [5, 4, 4, 3]])
+
+        if axis in [-1, 1]:
+            a = a.T
+            b = b.T
+            c = c.T
+            take_axis = 0
+        else:
+            take_axis = 1
+
+        warn_msg = "Each of the input arrays is constant;"
+        with pytest.warns(stats.ConstantInputWarning, match=warn_msg):
+            f, p = stats.f_oneway(a, b, c, axis=axis)
+
+        # Verify that the result computed with the 2d arrays matches
+        # the result of calling f_oneway individually on each slice.
+        for j in [0, 1]:
+            fj, pj = stats.f_oneway(np.take(a, j, take_axis),
+                                    np.take(b, j, take_axis),
+                                    np.take(c, j, take_axis))
+            assert_allclose(f[j], fj, rtol=1e-14)
+            assert_allclose(p[j], pj, rtol=1e-14)
+        for j in [2, 3]:
+            with pytest.warns(stats.ConstantInputWarning, match=warn_msg):
+                fj, pj = stats.f_oneway(np.take(a, j, take_axis),
+                                        np.take(b, j, take_axis),
+                                        np.take(c, j, take_axis))
+                assert_equal(f[j], fj)
+                assert_equal(p[j], pj)
+
+    def test_3d_inputs(self):
+        # Some 3-d arrays. (There is nothing special about the values.)
+        a = 1/np.arange(1.0, 4*5*7 + 1).reshape(4, 5, 7)
+        b = 2/np.arange(1.0, 4*8*7 + 1).reshape(4, 8, 7)
+        c = np.cos(1/np.arange(1.0, 4*4*7 + 1).reshape(4, 4, 7))
+
+        f, p = stats.f_oneway(a, b, c, axis=1)
+
+        assert f.shape == (4, 7)
+        assert p.shape == (4, 7)
+
+        for i in range(a.shape[0]):
+            for j in range(a.shape[2]):
+                fij, pij = stats.f_oneway(a[i, :, j], b[i, :, j], c[i, :, j])
+                assert_allclose(fij, f[i, j])
+                assert_allclose(pij, p[i, j])
+
+    def test_length0_1d_error(self):
+        # Require at least one value in each group.
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            result = stats.f_oneway([1, 2, 3], [], [4, 5, 6, 7])
+            assert_equal(result, (np.nan, np.nan))
+
+    def test_length0_2d_error(self):
+        with pytest.warns(SmallSampleWarning, match=too_small_nd_not_omit):
+            ncols = 3
+            a = np.ones((4, ncols))
+            b = np.ones((0, ncols))
+            c = np.ones((5, ncols))
+            f, p = stats.f_oneway(a, b, c)
+            nans = np.full((ncols,), fill_value=np.nan)
+            assert_equal(f, nans)
+            assert_equal(p, nans)
+
+    def test_all_length_one(self):
+        with pytest.warns(SmallSampleWarning):
+            result = stats.f_oneway([10], [11], [12], [13])
+            assert_equal(result, (np.nan, np.nan))
+
+    @pytest.mark.parametrize('args', [(), ([1, 2, 3],)])
+    def test_too_few_inputs(self, args):
+        message = "At least two samples are required..."
+        with assert_raises(TypeError, match=message):
+            stats.f_oneway(*args)
+
+    def test_axis_error(self):
+        a = np.ones((3, 4))
+        b = np.ones((5, 4))
+        with assert_raises(AxisError):
+            stats.f_oneway(a, b, axis=2)
+
+    def test_bad_shapes(self):
+        a = np.ones((3, 4))
+        b = np.ones((5, 4))
+        with assert_raises(ValueError):
+            stats.f_oneway(a, b, axis=1)
+
+
+class TestKruskal:
+    def test_simple(self):
+        x = [1]
+        y = [2]
+        h, p = stats.kruskal(x, y)
+        assert_equal(h, 1.0)
+        assert_approx_equal(p, stats.distributions.chi2.sf(h, 1))
+        h, p = stats.kruskal(np.array(x), np.array(y))
+        assert_equal(h, 1.0)
+        assert_approx_equal(p, stats.distributions.chi2.sf(h, 1))
+
+    def test_basic(self):
+        x = [1, 3, 5, 7, 9]
+        y = [2, 4, 6, 8, 10]
+        h, p = stats.kruskal(x, y)
+        assert_approx_equal(h, 3./11, significant=10)
+        assert_approx_equal(p, stats.distributions.chi2.sf(3./11, 1))
+        h, p = stats.kruskal(np.array(x), np.array(y))
+        assert_approx_equal(h, 3./11, significant=10)
+        assert_approx_equal(p, stats.distributions.chi2.sf(3./11, 1))
+
+    def test_simple_tie(self):
+        x = [1]
+        y = [1, 2]
+        h_uncorr = 1.5**2 + 2*2.25**2 - 12
+        corr = 0.75
+        expected = h_uncorr / corr   # 0.5
+        h, p = stats.kruskal(x, y)
+        # Since the expression is simple and the exact answer is 0.5, it
+        # should be safe to use assert_equal().
+        assert_equal(h, expected)
+
+    def test_another_tie(self):
+        x = [1, 1, 1, 2]
+        y = [2, 2, 2, 2]
+        h_uncorr = (12. / 8. / 9.) * 4 * (3**2 + 6**2) - 3 * 9
+        corr = 1 - float(3**3 - 3 + 5**3 - 5) / (8**3 - 8)
+        expected = h_uncorr / corr
+        h, p = stats.kruskal(x, y)
+        assert_approx_equal(h, expected)
+
+    def test_three_groups(self):
+        # A test of stats.kruskal with three groups, with ties.
+        x = [1, 1, 1]
+        y = [2, 2, 2]
+        z = [2, 2]
+        h_uncorr = (12. / 8. / 9.) * (3*2**2 + 3*6**2 + 2*6**2) - 3 * 9  # 5.0
+        corr = 1 - float(3**3 - 3 + 5**3 - 5) / (8**3 - 8)
+        expected = h_uncorr / corr  # 7.0
+        h, p = stats.kruskal(x, y, z)
+        assert_approx_equal(h, expected)
+        assert_approx_equal(p, stats.distributions.chi2.sf(h, 2))
+
+    def test_empty(self):
+        # A test of stats.kruskal with three groups, with ties.
+        x = [1, 1, 1]
+        y = [2, 2, 2]
+        z = []
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            assert_equal(stats.kruskal(x, y, z), (np.nan, np.nan))
+
+    def test_kruskal_result_attributes(self):
+        x = [1, 3, 5, 7, 9]
+        y = [2, 4, 6, 8, 10]
+        res = stats.kruskal(x, y)
+        attributes = ('statistic', 'pvalue')
+        check_named_results(res, attributes)
+
+    def test_nan_policy(self):
+        x = np.arange(10.)
+        x[9] = np.nan
+        assert_equal(stats.kruskal(x, x), (np.nan, np.nan))
+        assert_almost_equal(stats.kruskal(x, x, nan_policy='omit'), (0.0, 1.0))
+        assert_raises(ValueError, stats.kruskal, x, x, nan_policy='raise')
+        assert_raises(ValueError, stats.kruskal, x, x, nan_policy='foobar')
+
+    def test_large_no_samples(self):
+        # Test to see if large samples are handled correctly.
+        n = 50000
+        x = np.random.randn(n)
+        y = np.random.randn(n) + 50
+        h, p = stats.kruskal(x, y)
+        expected = 0
+        assert_approx_equal(p, expected)
+
+    def test_no_args_gh20661(self):
+        message = r"Need at least two groups in stats.kruskal\(\)"
+        with pytest.raises(ValueError, match=message):
+            stats.kruskal()
+
+
+@skip_xp_backends(cpu_only=True,
+                  exceptions=['cupy', 'jax.numpy'],
+                  reason=('Delegation for `special.stdtr` only implemented '
+                          'for CuPy and JAX.'))
+@pytest.mark.usefixtures("skip_xp_backends")
+@array_api_compatible
+class TestCombinePvalues:
+    # Reference values computed using the following R code:
+    # options(digits=16)
+    # library(metap)
+    # x = c(0.01, 0.2, 0.3)
+    # sumlog(x)  # fisher
+    # sumz(x)  # stouffer
+    # sumlog(1-x)  # pearson (negative statistic and complement of p-value)
+    # minimump(x)  # tippett
+    @pytest.mark.parametrize(
+        "method, expected_statistic, expected_pvalue",
+        [("fisher", 14.83716180549625 , 0.02156175132483465),
+         ("stouffer", 2.131790594240385, 0.01651203260896294),
+         ("pearson", -1.179737662212887, 1-0.9778736999143087),
+         ("tippett", 0.01, 0.02970100000000002),
+         # mudholkar_george: library(transite); p_combine(x, method="MG")
+         ("mudholkar_george", 6.828712071641684, 0.01654551838539527)])
+    def test_reference_values(self, xp, method, expected_statistic, expected_pvalue):
+        x = [.01, .2, .3]
+        res = stats.combine_pvalues(xp.asarray(x), method=method)
+        xp_assert_close(res.statistic, xp.asarray(expected_statistic))
+        xp_assert_close(res.pvalue, xp.asarray(expected_pvalue))
+
+    @pytest.mark.parametrize(
+        # Reference values computed using R `metap` `sumz`:
+        # options(digits=16)
+        # library(metap)
+        # x = c(0.01, 0.2, 0.3)
+        # sumz(x, weights=c(1., 1., 1.))
+        # sumz(x, weights=c(1., 4., 9.))
+        "weights, expected_statistic, expected_pvalue",
+        [([1., 1., 1.], 2.131790594240385, 0.01651203260896294),
+         ([1., 4., 9.], 1.051815015753598, 0.1464422142261314)])
+    def test_weighted_stouffer(self, xp, weights, expected_statistic, expected_pvalue):
+        x = xp.asarray([.01, .2, .3])
+        res = stats.combine_pvalues(x, method='stouffer', weights=xp.asarray(weights))
+        xp_assert_close(res.statistic, xp.asarray(expected_statistic))
+        xp_assert_close(res.pvalue, xp.asarray(expected_pvalue))
+
+    methods = ["fisher", "pearson", "tippett", "stouffer", "mudholkar_george"]
+
+    @pytest.mark.parametrize("variant", ["single", "all", "random"])
+    @pytest.mark.parametrize("method", methods)
+    def test_monotonicity(self, variant, method, xp):
+        xp_test = array_namespace(xp.asarray(1))
+        # Test that result increases monotonically with respect to input.
+        m, n = 10, 7
+        rng = np.random.default_rng(278448169958891062669391462690811630763)
+
+        # `pvaluess` is an m × n array of p values. Each row corresponds to
+        # a set of p values to be combined with p values increasing
+        # monotonically down one column (single), simultaneously down each
+        # column (all), or independently down each column (random).
+        if variant == "single":
+            pvaluess = xp.broadcast_to(xp.asarray(rng.random(n)), (m, n))
+            pvaluess = xp_test.concat([xp.reshape(xp.linspace(0.1, 0.9, m), (-1, 1)),
+                                       pvaluess[:, 1:]], axis=1)
+        elif variant == "all":
+            pvaluess = xp.broadcast_to(xp.linspace(0.1, 0.9, m), (n, m)).T
+        elif variant == "random":
+            pvaluess = xp_test.sort(xp.asarray(rng.uniform(0, 1, size=(m, n))), axis=0)
+
+        combined_pvalues = xp.asarray([
+            stats.combine_pvalues(pvaluess[i, :], method=method)[1]
+            for i in range(pvaluess.shape[0])
+        ])
+        assert xp.all(combined_pvalues[1:] - combined_pvalues[:-1] >= 0)
+
+    @pytest.mark.parametrize("method", methods)
+    def test_result(self, method, xp):
+        res = stats.combine_pvalues(xp.asarray([.01, .2, .3]), method=method)
+        xp_assert_equal(res.statistic, res[0])
+        xp_assert_equal(res.pvalue, res[1])
+
+    @pytest.mark.parametrize("method", methods)
+    # axis=None is currently broken for array API; will be handled when
+    # axis_nan_policy decorator is updated
+    @pytest.mark.parametrize("axis", [0, 1])
+    def test_axis(self, method, axis, xp):
+        rng = np.random.default_rng(234892349810482)
+        x = xp.asarray(rng.random(size=(2, 10)))
+        x = x.T if (axis == 0) else x
+        res = stats.combine_pvalues(x, axis=axis, method=method)
+
+        if axis is None:
+            x = xp.reshape(x, (-1,))
+            ref = stats.combine_pvalues(x, method=method)
+            xp_assert_close(res.statistic, ref.statistic)
+            xp_assert_close(res.pvalue, ref.pvalue)
+            return
+
+        x = x.T if (axis == 0) else x
+        x0, x1 = x[0, :], x[1, :]
+        ref0 = stats.combine_pvalues(x0, method=method)
+        ref1 = stats.combine_pvalues(x1, method=method)
+
+        xp_assert_close(res.statistic[0], ref0.statistic)
+        xp_assert_close(res.statistic[1], ref1.statistic)
+        xp_assert_close(res.pvalue[0], ref0.pvalue)
+        xp_assert_close(res.pvalue[1], ref1.pvalue)
+
+
+class TestCdfDistanceValidation:
+    """
+    Test that _cdf_distance() (via wasserstein_distance()) raises ValueErrors
+    for bad inputs.
+    """
+
+    def test_distinct_value_and_weight_lengths(self):
+        # When the number of weights does not match the number of values,
+        # a ValueError should be raised.
+        assert_raises(ValueError, stats.wasserstein_distance,
+                      [1], [2], [4], [3, 1])
+        assert_raises(ValueError, stats.wasserstein_distance, [1], [2], [1, 0])
+
+    def test_zero_weight(self):
+        # When a distribution is given zero weight, a ValueError should be
+        # raised.
+        assert_raises(ValueError, stats.wasserstein_distance,
+                      [0, 1], [2], [0, 0])
+        assert_raises(ValueError, stats.wasserstein_distance,
+                      [0, 1], [2], [3, 1], [0])
+
+    def test_negative_weights(self):
+        # A ValueError should be raised if there are any negative weights.
+        assert_raises(ValueError, stats.wasserstein_distance,
+                      [0, 1], [2, 2], [1, 1], [3, -1])
+
+    def test_empty_distribution(self):
+        # A ValueError should be raised when trying to measure the distance
+        # between something and nothing.
+        assert_raises(ValueError, stats.wasserstein_distance, [], [2, 2])
+        assert_raises(ValueError, stats.wasserstein_distance, [1], [])
+
+    def test_inf_weight(self):
+        # An inf weight is not valid.
+        assert_raises(ValueError, stats.wasserstein_distance,
+                      [1, 2, 1], [1, 1], [1, np.inf, 1], [1, 1])
+
+
+class TestWassersteinDistanceND:
+    """ Tests for wasserstein_distance_nd() output values.
+    """
+
+    def test_published_values(self):
+        # Compare against published values and manually computed results.
+        # The values and computed result are posted at James D. McCaffrey's blog,
+        # https://jamesmccaffrey.wordpress.com/2018/03/05/earth-mover-distance
+        # -wasserstein-metric-example-calculation/
+        u = [(1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1), (1,1),
+             (4,2), (6,1), (6,1)]
+        v = [(2,1), (2,1), (3,2), (3,2), (3,2), (5,1), (5,1), (5,1), (5,1), (5,1),
+             (5,1), (5,1), (7,1)]
+
+        res = stats.wasserstein_distance_nd(u, v)
+        # In original post, the author kept two decimal places for ease of calculation.
+        # This test uses the more precise value of distance to get the precise results.
+        # For comparison, please see the table and figure in the original blog post.
+        flow = np.array([2., 3., 5., 1., 1., 1.])
+        dist = np.array([1.00, 5**0.5, 4.00, 2**0.5, 1.00, 1.00])
+        ref = np.sum(flow * dist)/np.sum(flow)
+        assert_allclose(res, ref)
+
+    @pytest.mark.parametrize('n_value', (4, 15, 35))
+    @pytest.mark.parametrize('ndim', (3, 4, 7))
+    @pytest.mark.parametrize('max_repeats', (5, 10))
+    def test_same_distribution_nD(self, ndim, n_value, max_repeats):
+        # Any distribution moved to itself should have a Wasserstein distance
+        # of zero.
+        rng = np.random.default_rng(363836384995579937222333)
+        repeats = rng.integers(1, max_repeats, size=n_value, dtype=int)
+
+        u_values = rng.random(size=(n_value, ndim))
+        v_values = np.repeat(u_values, repeats, axis=0)
+        v_weights = rng.random(np.sum(repeats))
+        range_repeat = np.repeat(np.arange(len(repeats)), repeats)
+        u_weights = np.bincount(range_repeat, weights=v_weights)
+        index = rng.permutation(len(v_weights))
+        v_values, v_weights = v_values[index], v_weights[index]
+
+        res = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights)
+        assert_allclose(res, 0, atol=1e-15)
+
+    @pytest.mark.parametrize('nu', (8, 9, 38))
+    @pytest.mark.parametrize('nv', (8, 12, 17))
+    @pytest.mark.parametrize('ndim', (3, 5, 23))
+    def test_collapse_nD(self, nu, nv, ndim):
+        # test collapse for n dimensional values
+        # Collapsing a n-D distribution to a point distribution at zero
+        # is equivalent to taking the average of the norm of data.
+        rng = np.random.default_rng(38573488467338826109)
+        u_values = rng.random(size=(nu, ndim))
+        v_values = np.zeros((nv, ndim))
+        u_weights = rng.random(size=nu)
+        v_weights = rng.random(size=nv)
+        ref = np.average(np.linalg.norm(u_values, axis=1), weights=u_weights)
+        res = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights)
+        assert_allclose(res, ref)
+
+    @pytest.mark.parametrize('nu', (8, 16, 32))
+    @pytest.mark.parametrize('nv', (8, 16, 32))
+    @pytest.mark.parametrize('ndim', (1, 2, 6))
+    def test_zero_weight_nD(self, nu, nv, ndim):
+        # Values with zero weight have no impact on the Wasserstein distance.
+        rng = np.random.default_rng(38573488467338826109)
+        u_values = rng.random(size=(nu, ndim))
+        v_values = rng.random(size=(nv, ndim))
+        u_weights = rng.random(size=nu)
+        v_weights = rng.random(size=nv)
+        ref = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights)
+
+        add_row, nrows = rng.integers(0, nu, size=2)
+        add_value = rng.random(size=(nrows, ndim))
+        u_values = np.insert(u_values, add_row, add_value, axis=0)
+        u_weights = np.insert(u_weights, add_row, np.zeros(nrows), axis=0)
+        res = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights)
+        assert_allclose(res, ref)
+
+    def test_inf_values(self):
+        # Inf values can lead to an inf distance or trigger a RuntimeWarning
+        # (and return NaN) if the distance is undefined.
+        uv, vv, uw = [[1, 1], [2, 1]], [[np.inf, -np.inf]], [1, 1]
+        distance = stats.wasserstein_distance_nd(uv, vv, uw)
+        assert_equal(distance, np.inf)
+        with np.errstate(invalid='ignore'):
+            uv, vv = [[np.inf, np.inf]], [[np.inf, -np.inf]]
+            distance = stats.wasserstein_distance_nd(uv, vv)
+            assert_equal(distance, np.nan)
+
+    @pytest.mark.parametrize('nu', (10, 15, 20))
+    @pytest.mark.parametrize('nv', (10, 15, 20))
+    @pytest.mark.parametrize('ndim', (1, 3, 5))
+    def test_multi_dim_nD(self, nu, nv, ndim):
+        # Adding dimension on distributions do not affect the result
+        rng = np.random.default_rng(2736495738494849509)
+        u_values = rng.random(size=(nu, ndim))
+        v_values = rng.random(size=(nv, ndim))
+        u_weights = rng.random(size=nu)
+        v_weights = rng.random(size=nv)
+        ref = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights)
+
+        add_dim = rng.integers(0, ndim)
+        add_value = rng.random()
+
+        u_values = np.insert(u_values, add_dim, add_value, axis=1)
+        v_values = np.insert(v_values, add_dim, add_value, axis=1)
+        res = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights)
+        assert_allclose(res, ref)
+
+    @pytest.mark.parametrize('nu', (7, 13, 19))
+    @pytest.mark.parametrize('nv', (7, 13, 19))
+    @pytest.mark.parametrize('ndim', (2, 4, 7))
+    def test_orthogonal_nD(self, nu, nv, ndim):
+        # orthogonal transformations do not affect the result of the
+        # wasserstein_distance
+        rng = np.random.default_rng(34746837464536)
+        u_values = rng.random(size=(nu, ndim))
+        v_values = rng.random(size=(nv, ndim))
+        u_weights = rng.random(size=nu)
+        v_weights = rng.random(size=nv)
+        ref = stats.wasserstein_distance_nd(u_values, v_values, u_weights, v_weights)
+
+        dist = stats.ortho_group(ndim)
+        transform = dist.rvs(random_state=rng)
+        shift = rng.random(size=ndim)
+        res = stats.wasserstein_distance_nd(u_values @ transform + shift,
+                                         v_values @ transform + shift,
+                                         u_weights, v_weights)
+        assert_allclose(res, ref)
+
+    def test_error_code(self):
+        rng = np.random.default_rng(52473644737485644836320101)
+        with pytest.raises(ValueError, match='Invalid input values. The inputs'):
+            u_values = rng.random(size=(4, 10, 15))
+            v_values = rng.random(size=(6, 2, 7))
+            _ = stats.wasserstein_distance_nd(u_values, v_values)
+        with pytest.raises(ValueError, match='Invalid input values. Dimensions'):
+            u_values = rng.random(size=(15,))
+            v_values = rng.random(size=(3, 15))
+            _ = stats.wasserstein_distance_nd(u_values, v_values)
+        with pytest.raises(ValueError,
+            match='Invalid input values. If two-dimensional'):
+            u_values = rng.random(size=(2, 10))
+            v_values = rng.random(size=(2, 2))
+            _ = stats.wasserstein_distance_nd(u_values, v_values)
+
+    @pytest.mark.parametrize('u_size', [1, 10, 50])
+    @pytest.mark.parametrize('v_size', [1, 10, 50])
+    def test_optimization_vs_analytical(self, u_size, v_size):
+        rng = np.random.default_rng(45634745675)
+        # Test when u_weights = None, v_weights = None
+        u_values = rng.random(size=(u_size, 1))
+        v_values = rng.random(size=(v_size, 1))
+        u_values_flat = u_values.ravel()
+        v_values_flat = v_values.ravel()
+        # These three calculations are done using different backends
+        # but they must be equal
+        d1 = stats.wasserstein_distance(u_values_flat, v_values_flat)
+        d2 = stats.wasserstein_distance_nd(u_values, v_values)
+        d3 = stats.wasserstein_distance_nd(u_values_flat, v_values_flat)
+        assert_allclose(d2, d1)
+        assert_allclose(d3, d1)
+        # Test with u_weights and v_weights specified.
+        u_weights = rng.random(size=u_size)
+        v_weights = rng.random(size=v_size)
+        d1 = stats.wasserstein_distance(u_values_flat, v_values_flat,
+                                        u_weights, v_weights)
+        d2 = stats.wasserstein_distance_nd(u_values, v_values,
+                                        u_weights, v_weights)
+        d3 = stats.wasserstein_distance_nd(u_values_flat, v_values_flat,
+                                        u_weights, v_weights)
+        assert_allclose(d2, d1)
+        assert_allclose(d3, d1)
+
+
+class TestWassersteinDistance:
+    """ Tests for wasserstein_distance() output values.
+    """
+
+    def test_simple(self):
+        # For basic distributions, the value of the Wasserstein distance is
+        # straightforward.
+        assert_allclose(
+            stats.wasserstein_distance([0, 1], [0], [1, 1], [1]),
+            .5)
+        assert_allclose(stats.wasserstein_distance(
+            [0, 1], [0], [3, 1], [1]),
+            .25)
+        assert_allclose(stats.wasserstein_distance(
+            [0, 2], [0], [1, 1], [1]),
+            1)
+        assert_allclose(stats.wasserstein_distance(
+            [0, 1, 2], [1, 2, 3]),
+            1)
+
+    def test_same_distribution(self):
+        # Any distribution moved to itself should have a Wasserstein distance
+        # of zero.
+        assert_equal(stats.wasserstein_distance([1, 2, 3], [2, 1, 3]), 0)
+        assert_equal(
+            stats.wasserstein_distance([1, 1, 1, 4], [4, 1],
+                                       [1, 1, 1, 1], [1, 3]),
+            0)
+
+    def test_shift(self):
+        # If the whole distribution is shifted by x, then the Wasserstein
+        # distance should be the norm of x.
+        assert_allclose(stats.wasserstein_distance([0], [1]), 1)
+        assert_allclose(stats.wasserstein_distance([-5], [5]), 10)
+        assert_allclose(
+            stats.wasserstein_distance([1, 2, 3, 4, 5], [11, 12, 13, 14, 15]),
+            10)
+        assert_allclose(
+            stats.wasserstein_distance([4.5, 6.7, 2.1], [4.6, 7, 9.2],
+                                       [3, 1, 1], [1, 3, 1]),
+            2.5)
+
+    def test_combine_weights(self):
+        # Assigning a weight w to a value is equivalent to including that value
+        # w times in the value array with weight of 1.
+        assert_allclose(
+            stats.wasserstein_distance(
+                [0, 0, 1, 1, 1, 1, 5], [0, 3, 3, 3, 3, 4, 4],
+                [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]),
+            stats.wasserstein_distance([5, 0, 1], [0, 4, 3],
+                                       [1, 2, 4], [1, 2, 4]))
+
+    def test_collapse(self):
+        # Collapsing a distribution to a point distribution at zero is
+        # equivalent to taking the average of the absolute values of the
+        # values.
+        u = np.arange(-10, 30, 0.3)
+        v = np.zeros_like(u)
+        assert_allclose(
+            stats.wasserstein_distance(u, v),
+            np.mean(np.abs(u)))
+
+        u_weights = np.arange(len(u))
+        v_weights = u_weights[::-1]
+        assert_allclose(
+            stats.wasserstein_distance(u, v, u_weights, v_weights),
+            np.average(np.abs(u), weights=u_weights))
+
+    def test_zero_weight(self):
+        # Values with zero weight have no impact on the Wasserstein distance.
+        assert_allclose(
+            stats.wasserstein_distance([1, 2, 100000], [1, 1],
+                                       [1, 1, 0], [1, 1]),
+            stats.wasserstein_distance([1, 2], [1, 1], [1, 1], [1, 1]))
+
+    def test_inf_values(self):
+        # Inf values can lead to an inf distance or trigger a RuntimeWarning
+        # (and return NaN) if the distance is undefined.
+        assert_equal(
+            stats.wasserstein_distance([1, 2, np.inf], [1, 1]),
+            np.inf)
+        assert_equal(
+            stats.wasserstein_distance([1, 2, np.inf], [-np.inf, 1]),
+            np.inf)
+        assert_equal(
+            stats.wasserstein_distance([1, -np.inf, np.inf], [1, 1]),
+            np.inf)
+        with suppress_warnings() as sup:
+            sup.record(RuntimeWarning, "invalid value*")
+            assert_equal(
+                stats.wasserstein_distance([1, 2, np.inf], [np.inf, 1]),
+                np.nan)
+
+
+class TestEnergyDistance:
+    """ Tests for energy_distance() output values.
+    """
+
+    def test_simple(self):
+        # For basic distributions, the value of the energy distance is
+        # straightforward.
+        assert_almost_equal(
+            stats.energy_distance([0, 1], [0], [1, 1], [1]),
+            np.sqrt(2) * .5)
+        assert_almost_equal(stats.energy_distance(
+            [0, 1], [0], [3, 1], [1]),
+            np.sqrt(2) * .25)
+        assert_almost_equal(stats.energy_distance(
+            [0, 2], [0], [1, 1], [1]),
+            2 * .5)
+        assert_almost_equal(
+            stats.energy_distance([0, 1, 2], [1, 2, 3]),
+            np.sqrt(2) * (3*(1./3**2))**.5)
+
+    def test_same_distribution(self):
+        # Any distribution moved to itself should have a energy distance of
+        # zero.
+        assert_equal(stats.energy_distance([1, 2, 3], [2, 1, 3]), 0)
+        assert_equal(
+            stats.energy_distance([1, 1, 1, 4], [4, 1], [1, 1, 1, 1], [1, 3]),
+            0)
+
+    def test_shift(self):
+        # If a single-point distribution is shifted by x, then the energy
+        # distance should be sqrt(2) * sqrt(x).
+        assert_almost_equal(stats.energy_distance([0], [1]), np.sqrt(2))
+        assert_almost_equal(
+            stats.energy_distance([-5], [5]),
+            np.sqrt(2) * 10**.5)
+
+    def test_combine_weights(self):
+        # Assigning a weight w to a value is equivalent to including that value
+        # w times in the value array with weight of 1.
+        assert_almost_equal(
+            stats.energy_distance([0, 0, 1, 1, 1, 1, 5], [0, 3, 3, 3, 3, 4, 4],
+                                  [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]),
+            stats.energy_distance([5, 0, 1], [0, 4, 3], [1, 2, 4], [1, 2, 4]))
+
+    def test_zero_weight(self):
+        # Values with zero weight have no impact on the energy distance.
+        assert_almost_equal(
+            stats.energy_distance([1, 2, 100000], [1, 1], [1, 1, 0], [1, 1]),
+            stats.energy_distance([1, 2], [1, 1], [1, 1], [1, 1]))
+
+    def test_inf_values(self):
+        # Inf values can lead to an inf distance or trigger a RuntimeWarning
+        # (and return NaN) if the distance is undefined.
+        assert_equal(stats.energy_distance([1, 2, np.inf], [1, 1]), np.inf)
+        assert_equal(
+            stats.energy_distance([1, 2, np.inf], [-np.inf, 1]),
+            np.inf)
+        assert_equal(
+            stats.energy_distance([1, -np.inf, np.inf], [1, 1]),
+            np.inf)
+        with suppress_warnings() as sup:
+            sup.record(RuntimeWarning, "invalid value*")
+            assert_equal(
+                stats.energy_distance([1, 2, np.inf], [np.inf, 1]),
+                np.nan)
+
+
+class TestBrunnerMunzel:
+    # Data from (Lumley, 1996)
+    X = [1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1]
+    Y = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4]
+    significant = 13
+
+    def test_brunnermunzel_one_sided(self):
+        # Results are compared with R's lawstat package.
+        u1, p1 = stats.brunnermunzel(self.X, self.Y, alternative='less')
+        u2, p2 = stats.brunnermunzel(self.Y, self.X, alternative='greater')
+        u3, p3 = stats.brunnermunzel(self.X, self.Y, alternative='greater')
+        u4, p4 = stats.brunnermunzel(self.Y, self.X, alternative='less')
+
+        assert_approx_equal(p1, p2, significant=self.significant)
+        assert_approx_equal(p3, p4, significant=self.significant)
+        assert_(p1 != p3)
+        assert_approx_equal(u1, 3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(u2, -3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(u3, 3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(u4, -3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(p1, 0.0028931043330757342,
+                            significant=self.significant)
+        assert_approx_equal(p3, 0.99710689566692423,
+                            significant=self.significant)
+
+    def test_brunnermunzel_two_sided(self):
+        # Results are compared with R's lawstat package.
+        u1, p1 = stats.brunnermunzel(self.X, self.Y, alternative='two-sided')
+        u2, p2 = stats.brunnermunzel(self.Y, self.X, alternative='two-sided')
+
+        assert_approx_equal(p1, p2, significant=self.significant)
+        assert_approx_equal(u1, 3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(u2, -3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(p1, 0.0057862086661515377,
+                            significant=self.significant)
+
+    def test_brunnermunzel_default(self):
+        # The default value for alternative is two-sided
+        u1, p1 = stats.brunnermunzel(self.X, self.Y)
+        u2, p2 = stats.brunnermunzel(self.Y, self.X)
+
+        assert_approx_equal(p1, p2, significant=self.significant)
+        assert_approx_equal(u1, 3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(u2, -3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(p1, 0.0057862086661515377,
+                            significant=self.significant)
+
+    def test_brunnermunzel_alternative_error(self):
+        alternative = "error"
+        distribution = "t"
+        nan_policy = "propagate"
+        assert_(alternative not in ["two-sided", "greater", "less"])
+        assert_raises(ValueError,
+                      stats.brunnermunzel,
+                      self.X,
+                      self.Y,
+                      alternative,
+                      distribution,
+                      nan_policy)
+
+    def test_brunnermunzel_distribution_norm(self):
+        u1, p1 = stats.brunnermunzel(self.X, self.Y, distribution="normal")
+        u2, p2 = stats.brunnermunzel(self.Y, self.X, distribution="normal")
+        assert_approx_equal(p1, p2, significant=self.significant)
+        assert_approx_equal(u1, 3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(u2, -3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(p1, 0.0017041417600383024,
+                            significant=self.significant)
+
+    def test_brunnermunzel_distribution_error(self):
+        alternative = "two-sided"
+        distribution = "error"
+        nan_policy = "propagate"
+        assert_(alternative not in ["t", "normal"])
+        assert_raises(ValueError,
+                      stats.brunnermunzel,
+                      self.X,
+                      self.Y,
+                      alternative,
+                      distribution,
+                      nan_policy)
+
+    @pytest.mark.parametrize("kwarg_update", [{'y': []}, {'x': []},
+                                              {'x': [], 'y': []}])
+    def test_brunnermunzel_empty_imput(self, kwarg_update):
+        kwargs = {'x': self.X, 'y': self.Y}
+        kwargs.update(kwarg_update)
+        with pytest.warns(SmallSampleWarning, match=too_small_1d_not_omit):
+            statistic, pvalue = stats.brunnermunzel(**kwargs)
+        assert_equal(statistic, np.nan)
+        assert_equal(pvalue, np.nan)
+
+    def test_brunnermunzel_nan_input_propagate(self):
+        X = [1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1, np.nan]
+        Y = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4]
+        u1, p1 = stats.brunnermunzel(X, Y, nan_policy="propagate")
+        u2, p2 = stats.brunnermunzel(Y, X, nan_policy="propagate")
+
+        assert_equal(u1, np.nan)
+        assert_equal(p1, np.nan)
+        assert_equal(u2, np.nan)
+        assert_equal(p2, np.nan)
+
+    def test_brunnermunzel_nan_input_raise(self):
+        X = [1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1, np.nan]
+        Y = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4]
+        alternative = "two-sided"
+        distribution = "t"
+        nan_policy = "raise"
+
+        assert_raises(ValueError,
+                      stats.brunnermunzel,
+                      X,
+                      Y,
+                      alternative,
+                      distribution,
+                      nan_policy)
+        assert_raises(ValueError,
+                      stats.brunnermunzel,
+                      Y,
+                      X,
+                      alternative,
+                      distribution,
+                      nan_policy)
+
+    def test_brunnermunzel_nan_input_omit(self):
+        X = [1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 1, 1, np.nan]
+        Y = [3, 3, 4, 3, 1, 2, 3, 1, 1, 5, 4]
+        u1, p1 = stats.brunnermunzel(X, Y, nan_policy="omit")
+        u2, p2 = stats.brunnermunzel(Y, X, nan_policy="omit")
+
+        assert_approx_equal(p1, p2, significant=self.significant)
+        assert_approx_equal(u1, 3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(u2, -3.1374674823029505,
+                            significant=self.significant)
+        assert_approx_equal(p1, 0.0057862086661515377,
+                            significant=self.significant)
+
+    def test_brunnermunzel_return_nan(self):
+        """ tests that a warning is emitted when p is nan
+        p-value with t-distributions can be nan (0/0) (see gh-15843)
+        """
+        x = [1, 2, 3]
+        y = [5, 6, 7, 8, 9]
+
+        msg = "p-value cannot be estimated|divide by zero|invalid value encountered"
+        with pytest.warns(RuntimeWarning, match=msg):
+            stats.brunnermunzel(x, y, distribution="t")
+
+    def test_brunnermunzel_normal_dist(self):
+        """ tests that a p is 0 for datasets that cause p->nan
+        when t-distribution is used (see gh-15843)
+        """
+        x = [1, 2, 3]
+        y = [5, 6, 7, 8, 9]
+
+        with pytest.warns(RuntimeWarning, match='divide by zero'):
+            _, p = stats.brunnermunzel(x, y, distribution="normal")
+        assert_equal(p, 0)
+
+
+class TestQuantileTest:
+    r""" Test the non-parametric quantile test,
+    including the computation of confidence intervals
+    """
+
+    def test_quantile_test_iv(self):
+        x = [1, 2, 3]
+
+        message = "`x` must be a one-dimensional array of numbers."
+        with pytest.raises(ValueError, match=message):
+            stats.quantile_test([x])
+
+        message = "`q` must be a scalar."
+        with pytest.raises(ValueError, match=message):
+            stats.quantile_test(x, q=[1, 2])
+
+        message = "`p` must be a float strictly between 0 and 1."
+        with pytest.raises(ValueError, match=message):
+            stats.quantile_test(x, p=[0.5, 0.75])
+        with pytest.raises(ValueError, match=message):
+            stats.quantile_test(x, p=2)
+        with pytest.raises(ValueError, match=message):
+            stats.quantile_test(x, p=-0.5)
+
+        message = "`alternative` must be one of..."
+        with pytest.raises(ValueError, match=message):
+            stats.quantile_test(x, alternative='one-sided')
+
+        message = "`confidence_level` must be a number between 0 and 1."
+        with pytest.raises(ValueError, match=message):
+            stats.quantile_test(x).confidence_interval(1)
+
+    @pytest.mark.parametrize(
+        'p, alpha, lb, ub, alternative',
+        [[0.3, 0.95, 1.221402758160170, 1.476980793882643, 'two-sided'],
+         [0.5, 0.9, 1.506817785112854, 1.803988415397857, 'two-sided'],
+         [0.25, 0.95, -np.inf, 1.39096812846378, 'less'],
+         [0.8, 0.9, 2.117000016612675, np.inf, 'greater']]
+    )
+    def test_R_ci_quantile(self, p, alpha, lb, ub, alternative):
+        # Test against R library `confintr` function `ci_quantile`, e.g.
+        # library(confintr)
+        # options(digits=16)
+        # x <- exp(seq(0, 1, by = 0.01))
+        # ci_quantile(x, q = 0.3)$interval
+        # ci_quantile(x, q = 0.5, probs = c(0.05, 0.95))$interval
+        # ci_quantile(x, q = 0.25, probs = c(0, 0.95))$interval
+        # ci_quantile(x, q = 0.8, probs = c(0.1, 1))$interval
+        x = np.exp(np.arange(0, 1.01, 0.01))
+        res = stats.quantile_test(x, p=p, alternative=alternative)
+        assert_allclose(res.confidence_interval(alpha), [lb, ub], rtol=1e-15)
+
+    @pytest.mark.parametrize(
+        'q, p, alternative, ref',
+        [[1.2, 0.3, 'two-sided', 0.01515567517648],
+         [1.8, 0.5, 'two-sided', 0.1109183496606]]
+    )
+    def test_R_pvalue(self, q, p, alternative, ref):
+        # Test against R library `snpar` function `quant.test`, e.g.
+        # library(snpar)
+        # options(digits=16)
+        # x < - exp(seq(0, 1, by=0.01))
+        # quant.test(x, q=1.2, p=0.3, exact=TRUE, alternative='t')
+        x = np.exp(np.arange(0, 1.01, 0.01))
+        res = stats.quantile_test(x, q=q, p=p, alternative=alternative)
+        assert_allclose(res.pvalue, ref, rtol=1e-12)
+
+    @pytest.mark.parametrize('case', ['continuous', 'discrete'])
+    @pytest.mark.parametrize('alternative', ['less', 'greater'])
+    @pytest.mark.parametrize('alpha', [0.9, 0.95])
+    def test_pval_ci_match(self, case, alternative, alpha):
+        # Verify that the following statement holds:
+
+        # The 95% confidence interval corresponding with alternative='less'
+        # has -inf as its lower bound, and the upper bound `xu` is the greatest
+        # element from the sample `x` such that:
+        # `stats.quantile_test(x, q=xu, p=p, alternative='less').pvalue``
+        # will be greater than 5%.
+
+        # And the corresponding statement for the alternative='greater' case.
+
+        seed = int((7**len(case) + len(alternative))*alpha)
+        rng = np.random.default_rng(seed)
+        if case == 'continuous':
+            p, q = rng.random(size=2)
+            rvs = rng.random(size=100)
+        else:
+            rvs = rng.integers(1, 11, size=100)
+            p = rng.random()
+            q = rng.integers(1, 11)
+
+        res = stats.quantile_test(rvs, q=q, p=p, alternative=alternative)
+        ci = res.confidence_interval(confidence_level=alpha)
+
+        # select elements inside the confidence interval based on alternative
+        if alternative == 'less':
+            i_inside = rvs <= ci.high
+        else:
+            i_inside = rvs >= ci.low
+
+        for x in rvs[i_inside]:
+            res = stats.quantile_test(rvs, q=x, p=p, alternative=alternative)
+            assert res.pvalue > 1 - alpha
+
+        for x in rvs[~i_inside]:
+            res = stats.quantile_test(rvs, q=x, p=p, alternative=alternative)
+            assert res.pvalue < 1 - alpha
+
+    def test_match_conover_examples(self):
+        # Test against the examples in [1] (Conover Practical Nonparametric
+        # Statistics Third Edition) pg 139
+
+        # Example 1
+        # Data is [189, 233, 195, 160, 212, 176, 231, 185, 199, 213, 202, 193,
+        # 174, 166, 248]
+        # Two-sided test of whether the upper quartile (p=0.75) equals 193
+        # (q=193). Conover shows that 7 of the observations are less than or
+        # equal to 193, and "for the binomial random variable Y, P(Y<=7) =
+        # 0.0173", so the two-sided p-value is twice that, 0.0346.
+        x = [189, 233, 195, 160, 212, 176, 231, 185, 199, 213, 202, 193,
+             174, 166, 248]
+        pvalue_expected = 0.0346
+        res = stats.quantile_test(x, q=193, p=0.75, alternative='two-sided')
+        assert_allclose(res.pvalue, pvalue_expected, rtol=1e-5)
+
+        # Example 2
+        # Conover doesn't give explicit data, just that 8 out of 112
+        # observations are 60 or less. The test is whether the median time is
+        # equal to 60 against the alternative that the median is greater than
+        # 60. The p-value is calculated as P(Y<=8), where Y is again a binomial
+        # distributed random variable, now with p=0.5 and n=112. Conover uses a
+        # normal approximation, but we can easily calculate the CDF of the
+        # binomial distribution.
+        x = [59]*8 + [61]*(112-8)
+        pvalue_expected = stats.binom(p=0.5, n=112).pmf(k=8)
+        res = stats.quantile_test(x, q=60, p=0.5, alternative='greater')
+        assert_allclose(res.pvalue, pvalue_expected, atol=1e-10)
+
+
+class TestPageTrendTest:
+    # expected statistic and p-values generated using R at
+    # https://rdrr.io/cran/cultevo/, e.g.
+    # library(cultevo)
+    # data = rbind(c(72, 47, 73, 35, 47, 96, 30, 59, 41, 36, 56, 49, 81, 43,
+    #                   70, 47, 28, 28, 62, 20, 61, 20, 80, 24, 50),
+    #              c(68, 52, 60, 34, 44, 20, 65, 88, 21, 81, 48, 31, 31, 67,
+    #                69, 94, 30, 24, 40, 87, 70, 43, 50, 96, 43),
+    #              c(81, 13, 85, 35, 79, 12, 92, 86, 21, 64, 16, 64, 68, 17,
+    #                16, 89, 71, 43, 43, 36, 54, 13, 66, 51, 55))
+    # result = page.test(data, verbose=FALSE)
+    # Most test cases generated to achieve common critical p-values so that
+    # results could be checked (to limited precision) against tables in
+    # scipy.stats.page_trend_test reference [1]
+
+    np.random.seed(0)
+    data_3_25 = np.random.rand(3, 25)
+    data_10_26 = np.random.rand(10, 26)
+
+    ts = [
+          (12805, 0.3886487053947608, False, 'asymptotic', data_3_25),
+          (49140, 0.02888978556179862, False, 'asymptotic', data_10_26),
+          (12332, 0.7722477197436702, False, 'asymptotic',
+           [[72, 47, 73, 35, 47, 96, 30, 59, 41, 36, 56, 49, 81,
+             43, 70, 47, 28, 28, 62, 20, 61, 20, 80, 24, 50],
+            [68, 52, 60, 34, 44, 20, 65, 88, 21, 81, 48, 31, 31,
+             67, 69, 94, 30, 24, 40, 87, 70, 43, 50, 96, 43],
+            [81, 13, 85, 35, 79, 12, 92, 86, 21, 64, 16, 64, 68,
+             17, 16, 89, 71, 43, 43, 36, 54, 13, 66, 51, 55]]),
+          (266, 4.121656378600823e-05, False, 'exact',
+           [[1.5, 4., 8.3, 5, 19, 11],
+            [5, 4, 3.5, 10, 20, 21],
+            [8.4, 3.2, 10, 12, 14, 15]]),
+          (332, 0.9566400920502488, True, 'exact',
+           [[4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1],
+            [4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1], [4, 3, 2, 1],
+            [3, 4, 1, 2], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4],
+            [1, 2, 3, 4], [1, 2, 3, 4]]),
+          (241, 0.9622210164861476, True, 'exact',
+           [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1],
+            [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1],
+            [3, 2, 1], [2, 1, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3],
+            [1, 2, 3], [1, 2, 3], [1, 2, 3]]),
+          (197, 0.9619432897162209, True, 'exact',
+           [[6, 5, 4, 3, 2, 1], [6, 5, 4, 3, 2, 1], [1, 3, 4, 5, 2, 6]]),
+          (423, 0.9590458306880073, True, 'exact',
+           [[5, 4, 3, 2, 1], [5, 4, 3, 2, 1], [5, 4, 3, 2, 1],
+            [5, 4, 3, 2, 1], [5, 4, 3, 2, 1], [5, 4, 3, 2, 1],
+            [4, 1, 3, 2, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5],
+            [1, 2, 3, 4, 5]]),
+          (217, 0.9693058575034678, True, 'exact',
+           [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1],
+            [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1],
+            [2, 1, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3],
+            [1, 2, 3]]),
+          (395, 0.991530289351305, True, 'exact',
+           [[7, 6, 5, 4, 3, 2, 1], [7, 6, 5, 4, 3, 2, 1],
+            [6, 5, 7, 4, 3, 2, 1], [1, 2, 3, 4, 5, 6, 7]]),
+          (117, 0.9997817843373017, True, 'exact',
+           [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1],
+            [3, 2, 1], [3, 2, 1], [3, 2, 1], [2, 1, 3], [1, 2, 3]]),
+         ]
+
+    @pytest.mark.parametrize("L, p, ranked, method, data", ts)
+    def test_accuracy(self, L, p, ranked, method, data):
+        np.random.seed(42)
+        res = stats.page_trend_test(data, ranked=ranked, method=method)
+        assert_equal(L, res.statistic)
+        assert_allclose(p, res.pvalue)
+        assert_equal(method, res.method)
+
+    ts2 = [
+           (542, 0.9481266260876332, True, 'exact',
+            [[10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
+             [1, 8, 4, 7, 6, 5, 9, 3, 2, 10]]),
+           (1322, 0.9993113928199309, True, 'exact',
+            [[10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],
+             [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [9, 2, 8, 7, 6, 5, 4, 3, 10, 1],
+             [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]),
+           (2286, 0.9908688345484833, True, 'exact',
+            [[8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1],
+             [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1],
+             [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1],
+             [8, 7, 6, 5, 4, 3, 2, 1], [8, 7, 6, 5, 4, 3, 2, 1],
+             [8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6, 4, 7, 2, 8],
+             [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8],
+             [1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8],
+             [1, 2, 3, 4, 5, 6, 7, 8]]),
+          ]
+
+    # only the first of these appears slow because intermediate data are
+    # cached and used on the rest
+    @pytest.mark.parametrize("L, p, ranked, method, data", ts)
+    @pytest.mark.slow()
+    def test_accuracy2(self, L, p, ranked, method, data):
+        np.random.seed(42)
+        res = stats.page_trend_test(data, ranked=ranked, method=method)
+        assert_equal(L, res.statistic)
+        assert_allclose(p, res.pvalue)
+        assert_equal(method, res.method)
+
+    def test_options(self):
+        np.random.seed(42)
+        m, n = 10, 20
+        predicted_ranks = np.arange(1, n+1)
+        perm = np.random.permutation(np.arange(n))
+        data = np.random.rand(m, n)
+        ranks = stats.rankdata(data, axis=1)
+        res1 = stats.page_trend_test(ranks)
+        res2 = stats.page_trend_test(ranks, ranked=True)
+        res3 = stats.page_trend_test(data, ranked=False)
+        res4 = stats.page_trend_test(ranks, predicted_ranks=predicted_ranks)
+        res5 = stats.page_trend_test(ranks[:, perm],
+                                     predicted_ranks=predicted_ranks[perm])
+        assert_equal(res1.statistic, res2.statistic)
+        assert_equal(res1.statistic, res3.statistic)
+        assert_equal(res1.statistic, res4.statistic)
+        assert_equal(res1.statistic, res5.statistic)
+
+    def test_Ames_assay(self):
+        # test from _page_trend_test.py [2] page 151; data on page 144
+        np.random.seed(42)
+
+        data = [[101, 117, 111], [91, 90, 107], [103, 133, 121],
+                [136, 140, 144], [190, 161, 201], [146, 120, 116]]
+        data = np.array(data).T
+        predicted_ranks = np.arange(1, 7)
+
+        res = stats.page_trend_test(data, ranked=False,
+                                    predicted_ranks=predicted_ranks,
+                                    method="asymptotic")
+        assert_equal(res.statistic, 257)
+        assert_almost_equal(res.pvalue, 0.0035, decimal=4)
+
+        res = stats.page_trend_test(data, ranked=False,
+                                    predicted_ranks=predicted_ranks,
+                                    method="exact")
+        assert_equal(res.statistic, 257)
+        assert_almost_equal(res.pvalue, 0.0023, decimal=4)
+
+    def test_input_validation(self):
+        # test data not a 2d array
+        with assert_raises(ValueError, match="`data` must be a 2d array."):
+            stats.page_trend_test(None)
+        with assert_raises(ValueError, match="`data` must be a 2d array."):
+            stats.page_trend_test([])
+        with assert_raises(ValueError, match="`data` must be a 2d array."):
+            stats.page_trend_test([1, 2])
+        with assert_raises(ValueError, match="`data` must be a 2d array."):
+            stats.page_trend_test([[[1]]])
+
+        # test invalid dimensions
+        with assert_raises(ValueError, match="Page's L is only appropriate"):
+            stats.page_trend_test(np.random.rand(1, 3))
+        with assert_raises(ValueError, match="Page's L is only appropriate"):
+            stats.page_trend_test(np.random.rand(2, 2))
+
+        # predicted ranks must include each integer [1, 2, 3] exactly once
+        message = "`predicted_ranks` must include each integer"
+        with assert_raises(ValueError, match=message):
+            stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]],
+                                  predicted_ranks=[0, 1, 2])
+        with assert_raises(ValueError, match=message):
+            stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]],
+                                  predicted_ranks=[1.1, 2, 3])
+        with assert_raises(ValueError, match=message):
+            stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]],
+                                  predicted_ranks=[1, 2, 3, 3])
+        with assert_raises(ValueError, match=message):
+            stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]],
+                                  predicted_ranks="invalid")
+
+        # test improperly ranked data
+        with assert_raises(ValueError, match="`data` is not properly ranked"):
+            stats.page_trend_test([[0, 2, 3], [1, 2, 3]], True)
+        with assert_raises(ValueError, match="`data` is not properly ranked"):
+            stats.page_trend_test([[1, 2, 3], [1, 2, 4]], True)
+
+        # various
+        with assert_raises(ValueError, match="`data` contains NaNs"):
+            stats.page_trend_test([[1, 2, 3], [1, 2, np.nan]],
+                                  ranked=False)
+        with assert_raises(ValueError, match="`method` must be in"):
+            stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]],
+                                  method="ekki")
+        with assert_raises(TypeError, match="`ranked` must be boolean."):
+            stats.page_trend_test(data=[[1, 2, 3], [1, 2, 3]],
+                                  ranked="ekki")
+
+
+rng = np.random.default_rng(902340982)
+x = rng.random(10)
+y = rng.random(10)
+
+
+@pytest.mark.parametrize("fun, args",
+                         [(stats.wilcoxon, (x,)),
+                          (stats.ks_1samp, (x, stats.norm.cdf)),  # type: ignore[attr-defined]  # noqa: E501
+                          (stats.ks_2samp, (x, y)),
+                          (stats.kstest, (x, y)),
+                          ])
+def test_rename_mode_method(fun, args):
+
+    res = fun(*args, method='exact')
+    res2 = fun(*args, mode='exact')
+    assert_equal(res, res2)
+
+    err = rf"{fun.__name__}() got multiple values for argument"
+    with pytest.raises(TypeError, match=re.escape(err)):
+        fun(*args, method='exact', mode='exact')
+
+
+class TestExpectile:
+    def test_same_as_mean(self):
+        rng = np.random.default_rng(42)
+        x = rng.random(size=20)
+        assert_allclose(stats.expectile(x, alpha=0.5), np.mean(x))
+
+    def test_minimum(self):
+        rng = np.random.default_rng(42)
+        x = rng.random(size=20)
+        assert_allclose(stats.expectile(x, alpha=0), np.amin(x))
+
+    def test_maximum(self):
+        rng = np.random.default_rng(42)
+        x = rng.random(size=20)
+        assert_allclose(stats.expectile(x, alpha=1), np.amax(x))
+
+    def test_weights(self):
+        # expectile should minimize `fun` defined below; see
+        # F. Sobotka and T. Kneib, "Geoadditive expectile regression",
+        # Computational Statistics and Data Analysis 56 (2012) 755-767
+        # :doi:`10.1016/j.csda.2010.11.015`
+        rng = np.random.default_rng(1856392524598679138)
+
+        def fun(u, a, alpha, weights):
+            w = np.full_like(a, fill_value=alpha)
+            w[a <= u] = 1 - alpha
+            return np.sum(w * weights * (a - u)**2)
+
+        def expectile2(a, alpha, weights):
+            bracket = np.min(a), np.max(a)
+            return optimize.minimize_scalar(fun, bracket=bracket,
+                                            args=(a, alpha, weights)).x
+
+        n = 10
+        a = rng.random(n)
+        alpha = rng.random()
+        weights = rng.random(n)
+
+        res = stats.expectile(a, alpha, weights=weights)
+        ref = expectile2(a, alpha, weights)
+        assert_allclose(res, ref)
+
+    @pytest.mark.parametrize(
+        "alpha", [0.2, 0.5 - 1e-12, 0.5, 0.5 + 1e-12, 0.8]
+    )
+    @pytest.mark.parametrize("n", [20, 2000])
+    def test_expectile_properties(self, alpha, n):
+        """
+        See Section 6 of
+        I. Steinwart, C. Pasin, R.C. Williamson & S. Zhang (2014).
+        "Elicitation and Identification of Properties". COLT.
+        http://proceedings.mlr.press/v35/steinwart14.html
+
+        and
+
+        Propositions 5, 6, 7 of
+        F. Bellini, B. Klar, and A. Müller and E. Rosazza Gianin (2013).
+        "Generalized Quantiles as Risk Measures"
+        http://doi.org/10.2139/ssrn.2225751
+        """
+        rng = np.random.default_rng(42)
+        x = rng.normal(size=n)
+
+        # 0. definite / constancy
+        # Let T(X) denote the expectile of rv X ~ F.
+        # T(c) = c for constant c
+        for c in [-5, 0, 0.5]:
+            assert_allclose(
+                stats.expectile(np.full(shape=n, fill_value=c), alpha=alpha),
+                c
+            )
+
+        # 1. translation equivariance
+        # T(X + c) = T(X) + c
+        c = rng.exponential()
+        assert_allclose(
+            stats.expectile(x + c, alpha=alpha),
+            stats.expectile(x, alpha=alpha) + c,
+        )
+        assert_allclose(
+            stats.expectile(x - c, alpha=alpha),
+            stats.expectile(x, alpha=alpha) - c,
+        )
+
+        # 2. positively homogeneity
+        # T(cX) = c * T(X) for c > 0
+        assert_allclose(
+            stats.expectile(c * x, alpha=alpha),
+            c * stats.expectile(x, alpha=alpha),
+        )
+
+        # 3. subadditivity
+        # Note that subadditivity holds for alpha >= 0.5.
+        # T(X + Y) <= T(X) + T(Y)
+        # For alpha = 0.5, i.e. the mean, strict equality holds.
+        # For alpha < 0.5, one can use property 6. to show
+        # T(X + Y) >= T(X) + T(Y)
+        y = rng.logistic(size=n, loc=10)  # different distribution than x
+        if alpha == 0.5:
+            def assert_op(a, b):
+                assert_allclose(a, b)
+
+        elif alpha > 0.5:
+            def assert_op(a, b):
+                assert a < b
+
+        else:
+            def assert_op(a, b):
+                assert a > b
+
+        assert_op(
+            stats.expectile(np.r_[x + y], alpha=alpha),
+            stats.expectile(x, alpha=alpha)
+            + stats.expectile(y, alpha=alpha)
+        )
+
+        # 4. monotonicity
+        # This holds for first order stochastic dominance X:
+        # X >= Y whenever P(X <= x) < P(Y <= x)
+        # T(X) <= T(Y) whenever X <= Y
+        y = rng.normal(size=n, loc=5)
+        assert (
+            stats.expectile(x, alpha=alpha) <= stats.expectile(y, alpha=alpha)
+        )
+
+        # 5. convexity for alpha > 0.5, concavity for alpha < 0.5
+        # convexity is
+        # T((1 - c) X + c Y) <= (1 - c) T(X) + c T(Y) for 0 <= c <= 1
+        y = rng.logistic(size=n, loc=10)
+        for c in [0.1, 0.5, 0.8]:
+            assert_op(
+                stats.expectile((1-c)*x + c*y, alpha=alpha),
+                (1-c) * stats.expectile(x, alpha=alpha) +
+                c * stats.expectile(y, alpha=alpha)
+            )
+
+        # 6. negative argument
+        # T_{alpha}(-X) = -T_{1-alpha}(X)
+        assert_allclose(
+            stats.expectile(-x, alpha=alpha),
+            -stats.expectile(x, alpha=1-alpha),
+        )
+
+    @pytest.mark.parametrize("n", [20, 2000])
+    def test_monotonicity_in_alpha(self, n):
+        rng = np.random.default_rng(42)
+        x = rng.pareto(a=2, size=n)
+        e_list = []
+        alpha_seq = np.logspace(-15, np.log10(0.5), 100)
+        # sorted list of unique alpha values in interval (0, 1)
+        for alpha in np.r_[0, alpha_seq, 1 - alpha_seq[:-1:-1], 1]:
+            e_list.append(stats.expectile(x, alpha=alpha))
+        assert np.all(np.diff(e_list) > 0)
+
+
+class TestLMoment:
+    # data from https://github.com/scipy/scipy/issues/19460
+    data = [0.87, 0.87, 1.29, 1.5, 1.7, 0.66, 1.5, 0.5, 1., 1.25, 2.3,
+            1.03, 2.85, 0.68, 1.74, 1.94, 0.63, 2.04, 1.2, 0.64, 2.05, 0.97,
+            2.81, 1.02, 2.76, 0.86, 1.36, 1.29, 1.68, 0.72, 1.67, 1.15, 3.26,
+            0.93, 0.83, 0.91, 0.92, 2.32, 1.12, 3.21, 1.23, 1.22, 1.29, 2.08,
+            0.64, 2.83, 2.68, 1.77, 0.69, 1.69, 0.7, 1.83, 2.25, 1.23, 1.17,
+            0.94, 1.22, 0.76, 0.69, 0.48, 1.04, 2.49, 1.38, 1.57, 1.79, 1.59,
+            1.3, 1.54, 1.07, 1.03, 0.76, 2.35, 2.05, 2.02, 2.36, 1.59, 0.97,
+            1.63, 1.66, 0.94, 1.45, 1.26, 1.25, 0.68, 2.96, 0.8, 1.16, 0.82,
+            0.64, 0.87, 1.33, 1.28, 1.26, 1.19, 1.24, 1.12, 1.45, 1.03, 1.37,
+            1.4, 1.35, 1.28, 1.04, 1.31, 0.87, 0.96, 2.55, 1.72, 1.05, 1.15,
+            1.73, 1.03, 1.53, 2.41, 1.36, 2.08, 0.92, 0.73, 1.56, 1.94, 0.78]
+
+    not_integers = [1.5, [1, 2, 3.5], np.nan, np.inf, 'a duck']
+
+    def test_dtype_iv(self):
+        message = '`sample` must be an array of real numbers.'
+        with pytest.raises(ValueError, match=message):
+            stats.lmoment(np.array(self.data, dtype=np.complex128))
+
+    @skip_xp_invalid_arg
+    def test_dtype_iv_non_numeric(self):
+        message = '`sample` must be an array of real numbers.'
+        with pytest.raises(ValueError, match=message):
+            stats.lmoment(np.array(self.data, dtype=object))
+
+    @pytest.mark.parametrize('order', not_integers + [0, -1, [], [[1, 2, 3]]])
+    def test_order_iv(self, order):
+        message = '`order` must be a scalar or a non-empty...'
+        with pytest.raises(ValueError, match=message):
+            stats.lmoment(self.data, order=order)
+
+    @pytest.mark.parametrize('axis', not_integers)
+    def test_axis_iv(self, axis):
+        message = '`axis` must be an integer, a tuple'
+        with pytest.raises(ValueError, match=message):
+            stats.lmoment(self.data, axis=axis)
+
+    @pytest.mark.parametrize('sorted', not_integers)
+    def test_sorted_iv(self, sorted):
+        message = '`sorted` must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            stats.lmoment(self.data, sorted=sorted)
+
+    @pytest.mark.parametrize('standardize', not_integers)
+    def test_standardize_iv(self, standardize):
+        message = '`standardize` must be True or False.'
+        with pytest.raises(ValueError, match=message):
+            stats.lmoment(self.data, standardize=standardize)
+
+    @pytest.mark.parametrize('order', [1, 4, [1, 2, 3, 4]])
+    @pytest.mark.parametrize('standardize', [False, True])
+    @pytest.mark.parametrize('sorted', [False, True])
+    def test_lmoment(self, order, standardize, sorted):
+        # Reference values from R package `lmom`
+        # options(digits=16)
+        # library(lmom)
+        # data= c(0.87, 0.87,..., 1.94, 0.78)
+        # samlmu(data)
+        ref = np.asarray([1.4087603305785130, 0.3415936639118458,
+                          0.2189964482831403, 0.1328186463415905])
+
+        if not standardize:
+            ref[2:] *= ref[1]
+
+        data = np.sort(self.data) if sorted else self.data
+
+        res = stats.lmoment(data, order, standardize=standardize, sorted=sorted)
+        assert_allclose(res, ref[np.asarray(order)-1])
+
+    def test_dtype(self):
+        dtype = np.float32
+        sample = np.asarray(self.data)
+        res = stats.lmoment(sample.astype(dtype))
+        ref = stats.lmoment(sample)
+        assert res.dtype.type == dtype
+        assert_allclose(res, ref, rtol=1e-4)
+
+        dtype = np.int64
+        sample = np.asarray([1, 2, 3, 4, 5])
+        res = stats.lmoment(sample.astype(dtype))
+        ref = stats.lmoment(sample.astype(np.float64))
+        assert res.dtype.type == np.float64
+        assert_allclose(res, ref, rtol=1e-15)
+
+
+@array_api_compatible
+class TestXP_Mean:
+    @pytest.mark.parametrize('axis', [None, 1, -1, (-2, 2)])
+    @pytest.mark.parametrize('weights', [None, True])
+    @pytest.mark.parametrize('keepdims', [False, True])
+    def test_xp_mean_basic(self, xp, axis, weights, keepdims):
+        rng = np.random.default_rng(90359458245906)
+        x = rng.random((3, 4, 5))
+        x_xp = xp.asarray(x)
+        w = w_xp = None
+
+        if weights:
+            w = rng.random((1, 5))
+            w_xp = xp.asarray(w)
+            x, w = np.broadcast_arrays(x, w)
+
+        res = _xp_mean(x_xp, weights=w_xp, axis=axis, keepdims=keepdims)
+        ref = np.average(x, weights=w, axis=axis, keepdims=keepdims)
+
+        xp_assert_close(res, xp.asarray(ref))
+
+    def test_non_broadcastable(self, xp):
+        # non-broadcastable x and weights
+        x, w = xp.arange(10.), xp.zeros(5)
+        message = "Array shapes are incompatible for broadcasting."
+        with pytest.raises(ValueError, match=message):
+            _xp_mean(x, weights=w)
+
+    def test_special_cases(self, xp):
+        # weights sum to zero
+        weights = xp.asarray([-1., 0., 1.])
+
+        res = _xp_mean(xp.asarray([1., 1., 1.]), weights=weights)
+        xp_assert_close(res, xp.asarray(xp.nan))
+
+        res = _xp_mean(xp.asarray([2., 1., 1.]), weights=weights)
+        xp_assert_close(res, xp.asarray(-np.inf))
+
+        res = _xp_mean(xp.asarray([1., 1., 2.]), weights=weights)
+        xp_assert_close(res, xp.asarray(np.inf))
+
+    def test_nan_policy(self, xp):
+        x = xp.arange(10.)
+        mask = (x == 3)
+        x = xp.where(mask, xp.asarray(xp.nan), x)
+
+        # nan_policy='raise' raises an error
+        message = 'The input contains nan values'
+        with pytest.raises(ValueError, match=message):
+            _xp_mean(x, nan_policy='raise')
+
+        # `nan_policy='propagate'` is the default, and the result is NaN
+        res1 = _xp_mean(x)
+        res2 = _xp_mean(x, nan_policy='propagate')
+        ref = xp.asarray(xp.nan)
+        xp_assert_equal(res1, ref)
+        xp_assert_equal(res2, ref)
+
+        # `nan_policy='omit'` omits NaNs in `x`
+        res = _xp_mean(x, nan_policy='omit')
+        ref = xp.mean(x[~mask])
+        xp_assert_close(res, ref)
+
+        # `nan_policy='omit'` omits NaNs in `weights`, too
+        weights = xp.ones(10)
+        weights = xp.where(mask, xp.asarray(xp.nan), weights)
+        res = _xp_mean(xp.arange(10.), weights=weights, nan_policy='omit')
+        ref = xp.mean(x[~mask])
+        xp_assert_close(res, ref)
+
+        # Check for warning if omitting NaNs causes empty slice
+        message = 'After omitting NaNs...'
+        with pytest.warns(RuntimeWarning, match=message):
+            res = _xp_mean(x * np.nan, nan_policy='omit')
+            ref = xp.asarray(xp.nan)
+            xp_assert_equal(res, ref)
+
+    def test_empty(self, xp):
+        message = 'One or more sample arguments is too small...'
+        with pytest.warns(SmallSampleWarning, match=message):
+            res = _xp_mean(xp.asarray([]))
+            ref = xp.asarray(xp.nan)
+            xp_assert_equal(res, ref)
+
+        message = "All axis-slices of one or more sample arguments..."
+        with pytest.warns(SmallSampleWarning, match=message):
+            res = _xp_mean(xp.asarray([[]]), axis=1)
+            ref = xp.asarray([xp.nan])
+            xp_assert_equal(res, ref)
+
+        res = _xp_mean(xp.asarray([[]]), axis=0)
+        ref = xp.asarray([])
+        xp_assert_equal(res, ref)
+
+    def test_dtype(self, xp):
+        max = xp.finfo(xp.float32).max
+        x_np = np.asarray([max, max], dtype=np.float32)
+        x_xp = xp.asarray(x_np)
+
+        # Overflow occurs for float32 input
+        with np.errstate(over='ignore'):
+            res = _xp_mean(x_xp)
+            ref = np.mean(x_np)
+            np.testing.assert_equal(ref, np.inf)
+            xp_assert_close(res, xp.asarray(ref))
+
+        # correct result is returned if `float64` is used
+        res = _xp_mean(x_xp, dtype=xp.float64)
+        ref = xp.asarray(np.mean(np.asarray(x_np, dtype=np.float64)))
+        xp_assert_close(res, ref)
+
+    def test_integer(self, xp):
+        # integer inputs are converted to the appropriate float
+        x = xp.arange(10)
+        y = xp.arange(10.)
+        xp_assert_equal(_xp_mean(x), _xp_mean(y))
+        xp_assert_equal(_xp_mean(y, weights=x), _xp_mean(y, weights=y))
+
+    def test_complex_gh22404(self, xp):
+        rng = np.random.default_rng(90359458245906)
+        x, y, wx, wy = rng.random((4, 20))
+        res = _xp_mean(xp.asarray(x + y*1j), weights=xp.asarray(wx + wy*1j))
+        ref = np.average(x + y*1j, weights=wx + wy*1j)
+        xp_assert_close(res, xp.asarray(ref))
+
+
+@array_api_compatible
+@pytest.mark.usefixtures("skip_xp_backends")
+@skip_xp_backends('jax.numpy', reason='JAX arrays do not support item assignment')
+class TestXP_Var:
+    @pytest.mark.parametrize('axis', [None, 1, -1, (-2, 2)])
+    @pytest.mark.parametrize('keepdims', [False, True])
+    @pytest.mark.parametrize('correction', [0, 1])
+    @pytest.mark.parametrize('nan_policy', ['propagate', 'omit'])
+    def test_xp_var_basic(self, xp, axis, keepdims, correction, nan_policy):
+        rng = np.random.default_rng(90359458245906)
+        x = rng.random((3, 4, 5))
+        var_ref = np.var
+
+        if nan_policy == 'omit':
+            nan_mask = rng.random(size=x.shape) > 0.5
+            x[nan_mask] = np.nan
+            var_ref = np.nanvar
+
+        x_xp = xp.asarray(x)
+
+        res = _xp_var(x_xp, axis=axis, keepdims=keepdims, correction=correction,
+                      nan_policy=nan_policy)
+
+        with suppress_warnings() as sup:
+            sup.filter(RuntimeWarning, "Degrees of freedom <= 0 for slice")
+            ref = var_ref(x, axis=axis, keepdims=keepdims, ddof=correction)
+
+        xp_assert_close(res, xp.asarray(ref))
+
+    def test_special_cases(self, xp):
+        # correction too big
+        res = _xp_var(xp.asarray([1., 2.]), correction=3)
+        xp_assert_close(res, xp.asarray(xp.nan))
+
+    def test_nan_policy(self, xp):
+        x = xp.arange(10.)
+        mask = (x == 3)
+        x = xp.where(mask, xp.asarray(xp.nan), x)
+
+        # nan_policy='raise' raises an error
+        message = 'The input contains nan values'
+        with pytest.raises(ValueError, match=message):
+            _xp_var(x, nan_policy='raise')
+
+        # `nan_policy='propagate'` is the default, and the result is NaN
+        res1 = _xp_var(x)
+        res2 = _xp_var(x, nan_policy='propagate')
+        ref = xp.asarray(xp.nan)
+        xp_assert_equal(res1, ref)
+        xp_assert_equal(res2, ref)
+
+        # `nan_policy='omit'` omits NaNs in `x`
+        res = _xp_var(x, nan_policy='omit')
+        xp_test = array_namespace(x)  # torch has different default correction
+        ref = xp_test.var(x[~mask])
+        xp_assert_close(res, ref)
+
+        # Check for warning if omitting NaNs causes empty slice
+        message = 'After omitting NaNs...'
+        with pytest.warns(RuntimeWarning, match=message):
+            res = _xp_var(x * np.nan, nan_policy='omit')
+            ref = xp.asarray(xp.nan)
+            xp_assert_equal(res, ref)
+
+    def test_empty(self, xp):
+        message = 'One or more sample arguments is too small...'
+        with pytest.warns(SmallSampleWarning, match=message):
+            res = _xp_var(xp.asarray([]))
+            ref = xp.asarray(xp.nan)
+            xp_assert_equal(res, ref)
+
+        message = "All axis-slices of one or more sample arguments..."
+        with pytest.warns(SmallSampleWarning, match=message):
+            res = _xp_var(xp.asarray([[]]), axis=1)
+            ref = xp.asarray([xp.nan])
+            xp_assert_equal(res, ref)
+
+        res = _xp_var(xp.asarray([[]]), axis=0)
+        ref = xp.asarray([])
+        xp_assert_equal(res, ref)
+
+    def test_dtype(self, xp):
+        max = xp.finfo(xp.float32).max
+        x_np = np.asarray([max, max/2], dtype=np.float32)
+        x_xp = xp.asarray(x_np)
+
+        # Overflow occurs for float32 input
+        with np.errstate(over='ignore'):
+            res = _xp_var(x_xp)
+            ref = np.var(x_np)
+            np.testing.assert_equal(ref, np.inf)
+            xp_assert_close(res, xp.asarray(ref))
+
+        # correct result is returned if `float64` is used
+        res = _xp_var(x_xp, dtype=xp.float64)
+        ref = xp.asarray(np.var(np.asarray(x_np, dtype=np.float64)))
+        xp_assert_close(res, ref)
+
+    def test_integer(self, xp):
+        # integer inputs are converted to the appropriate float
+        x = xp.arange(10)
+        y = xp.arange(10.)
+        xp_assert_equal(_xp_var(x), _xp_var(y))
+
+    @pytest.mark.skip_xp_backends('array_api_strict', reason='needs array-api#850')
+    def test_complex_gh22404(self, xp):
+        rng = np.random.default_rng(90359458245906)
+        x, y = rng.random((2, 20))
+        res = _xp_var(xp.asarray(x + y*1j))
+        ref = np.var(x + y*1j)
+        xp_assert_close(res, xp.asarray(ref), check_dtype=False)
+
+
+@array_api_compatible
+def test_chk_asarray(xp):
+    rng = np.random.default_rng(2348923425434)
+    x0 = rng.random(size=(2, 3, 4))
+    x = xp.asarray(x0)
+
+    axis = 1
+    x_out, axis_out = _chk_asarray(x, axis=axis, xp=xp)
+    xp_assert_equal(x_out, xp.asarray(x0))
+    assert_equal(axis_out, axis)
+
+    axis = None
+    x_out, axis_out = _chk_asarray(x, axis=axis, xp=xp)
+    xp_assert_equal(x_out, xp.asarray(x0.ravel()))
+    assert_equal(axis_out, 0)
+
+    axis = 2
+    x_out, axis_out = _chk_asarray(x[0, 0, 0], axis=axis, xp=xp)
+    xp_assert_equal(x_out, xp.asarray(np.atleast_1d(x0[0, 0, 0])))
+    assert_equal(axis_out, axis)
+
+
+@pytest.mark.skip_xp_backends('numpy',
+                              reason='These parameters *are* compatible with NumPy')
+@pytest.mark.usefixtures("skip_xp_backends")
+@array_api_compatible
+def test_axis_nan_policy_keepdims_nanpolicy(xp):
+    # this test does not need to be repeated for every function
+    # using the _axis_nan_policy decorator. The test is here
+    # rather than in `test_axis_nanpolicy.py` because there is
+    # no reason to run those tests on an array API CI job.
+    x = xp.asarray([1, 2, 3, 4])
+    message = "Use of `nan_policy` and `keepdims`..."
+    with pytest.raises(NotImplementedError, match=message):
+        stats.skew(x, nan_policy='omit')
+    with pytest.raises(NotImplementedError, match=message):
+        stats.skew(x, keepdims=True)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_survival.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_survival.py
new file mode 100644
index 0000000000000000000000000000000000000000..60a5fef27ae281c028ade8af523bdf1f62f8f664
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_survival.py
@@ -0,0 +1,466 @@
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose
+from scipy import stats
+from scipy.stats import _survival
+
+
+def _kaplan_meier_reference(times, censored):
+    # This is a very straightforward implementation of the Kaplan-Meier
+    # estimator that does almost everything differently from the implementation
+    # in stats.ecdf.
+
+    # Begin by sorting the raw data. Note that the order of death and loss
+    # at a given time matters: death happens first. See [2] page 461:
+    # "These conventions may be paraphrased by saying that deaths recorded as
+    # of an age t are treated as if they occurred slightly before t, and losses
+    # recorded as of an age t are treated as occurring slightly after t."
+    # We implement this by sorting the data first by time, then by `censored`,
+    # (which is 0 when there is a death and 1 when there is only a loss).
+    dtype = [('time', float), ('censored', int)]
+    data = np.array([(t, d) for t, d in zip(times, censored)], dtype=dtype)
+    data = np.sort(data, order=('time', 'censored'))
+    times = data['time']
+    died = np.logical_not(data['censored'])
+
+    m = times.size
+    n = np.arange(m, 0, -1)  # number at risk
+    sf = np.cumprod((n - died) / n)
+
+    # Find the indices of the *last* occurrence of unique times. The
+    # corresponding entries of `times` and `sf` are what we want.
+    _, indices = np.unique(times[::-1], return_index=True)
+    ref_times = times[-indices - 1]
+    ref_sf = sf[-indices - 1]
+    return ref_times, ref_sf
+
+
+class TestSurvival:
+
+    @staticmethod
+    def get_random_sample(rng, n_unique):
+        # generate random sample
+        unique_times = rng.random(n_unique)
+        # convert to `np.int32` to resolve `np.repeat` failure in 32-bit CI
+        repeats = rng.integers(1, 4, n_unique).astype(np.int32)
+        times = rng.permuted(np.repeat(unique_times, repeats))
+        censored = rng.random(size=times.size) > rng.random()
+        sample = stats.CensoredData.right_censored(times, censored)
+        return sample, times, censored
+
+    def test_input_validation(self):
+        message = '`sample` must be a one-dimensional sequence.'
+        with pytest.raises(ValueError, match=message):
+            stats.ecdf([[1]])
+        with pytest.raises(ValueError, match=message):
+            stats.ecdf(1)
+
+        message = '`sample` must not contain nan'
+        with pytest.raises(ValueError, match=message):
+            stats.ecdf([np.nan])
+
+        message = 'Currently, only uncensored and right-censored data...'
+        with pytest.raises(NotImplementedError, match=message):
+            stats.ecdf(stats.CensoredData.left_censored([1], censored=[True]))
+
+        message = 'method` must be one of...'
+        res = stats.ecdf([1, 2, 3])
+        with pytest.raises(ValueError, match=message):
+            res.cdf.confidence_interval(method='ekki-ekki')
+        with pytest.raises(ValueError, match=message):
+            res.sf.confidence_interval(method='shrubbery')
+
+        message = 'confidence_level` must be a scalar between 0 and 1'
+        with pytest.raises(ValueError, match=message):
+            res.cdf.confidence_interval(-1)
+        with pytest.raises(ValueError, match=message):
+            res.sf.confidence_interval([0.5, 0.6])
+
+        message = 'The confidence interval is undefined at some observations.'
+        with pytest.warns(RuntimeWarning, match=message):
+            ci = res.cdf.confidence_interval()
+
+        message = 'Confidence interval bounds do not implement...'
+        with pytest.raises(NotImplementedError, match=message):
+            ci.low.confidence_interval()
+        with pytest.raises(NotImplementedError, match=message):
+            ci.high.confidence_interval()
+
+    def test_edge_cases(self):
+        res = stats.ecdf([])
+        assert_equal(res.cdf.quantiles, [])
+        assert_equal(res.cdf.probabilities, [])
+
+        res = stats.ecdf([1])
+        assert_equal(res.cdf.quantiles, [1])
+        assert_equal(res.cdf.probabilities, [1])
+
+    def test_unique(self):
+        # Example with unique observations; `stats.ecdf` ref. [1] page 80
+        sample = [6.23, 5.58, 7.06, 6.42, 5.20]
+        res = stats.ecdf(sample)
+        ref_x = np.sort(np.unique(sample))
+        ref_cdf = np.arange(1, 6) / 5
+        ref_sf = 1 - ref_cdf
+        assert_equal(res.cdf.quantiles, ref_x)
+        assert_equal(res.cdf.probabilities, ref_cdf)
+        assert_equal(res.sf.quantiles, ref_x)
+        assert_equal(res.sf.probabilities, ref_sf)
+
+    def test_nonunique(self):
+        # Example with non-unique observations; `stats.ecdf` ref. [1] page 82
+        sample = [0, 2, 1, 2, 3, 4]
+        res = stats.ecdf(sample)
+        ref_x = np.sort(np.unique(sample))
+        ref_cdf = np.array([1/6, 2/6, 4/6, 5/6, 1])
+        ref_sf = 1 - ref_cdf
+        assert_equal(res.cdf.quantiles, ref_x)
+        assert_equal(res.cdf.probabilities, ref_cdf)
+        assert_equal(res.sf.quantiles, ref_x)
+        assert_equal(res.sf.probabilities, ref_sf)
+
+    def test_evaluate_methods(self):
+        # Test CDF and SF `evaluate` methods
+        rng = np.random.default_rng(1162729143302572461)
+        sample, _, _ = self.get_random_sample(rng, 15)
+        res = stats.ecdf(sample)
+        x = res.cdf.quantiles
+        xr = x + np.diff(x, append=x[-1]+1)/2  # right shifted points
+
+        assert_equal(res.cdf.evaluate(x), res.cdf.probabilities)
+        assert_equal(res.cdf.evaluate(xr), res.cdf.probabilities)
+        assert_equal(res.cdf.evaluate(x[0]-1), 0)  # CDF starts at 0
+        assert_equal(res.cdf.evaluate([-np.inf, np.inf]), [0, 1])
+
+        assert_equal(res.sf.evaluate(x), res.sf.probabilities)
+        assert_equal(res.sf.evaluate(xr), res.sf.probabilities)
+        assert_equal(res.sf.evaluate(x[0]-1), 1)  # SF starts at 1
+        assert_equal(res.sf.evaluate([-np.inf, np.inf]), [1, 0])
+
+    # ref. [1] page 91
+    t1 = [37, 43, 47, 56, 60, 62, 71, 77, 80, 81]  # times
+    d1 = [0, 0, 1, 1, 0, 0, 0, 1, 1, 1]  # 1 means deaths (not censored)
+    r1 = [1, 1, 0.875, 0.75, 0.75, 0.75, 0.75, 0.5, 0.25, 0]  # reference SF
+
+    # https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/BS704_Survival5.html
+    t2 = [8, 12, 26, 14, 21, 27, 8, 32, 20, 40]
+    d2 = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0]
+    r2 = [0.9, 0.788, 0.675, 0.675, 0.54, 0.405, 0.27, 0.27, 0.27]
+    t3 = [33, 28, 41, 48, 48, 25, 37, 48, 25, 43]
+    d3 = [1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
+    r3 = [1, 0.875, 0.75, 0.75, 0.6, 0.6, 0.6]
+
+    # https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/bs704_survival4.html
+    t4 = [24, 3, 11, 19, 24, 13, 14, 2, 18, 17,
+          24, 21, 12, 1, 10, 23, 6, 5, 9, 17]
+    d4 = [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1]
+    r4 = [0.95, 0.95, 0.897, 0.844, 0.844, 0.844, 0.844, 0.844, 0.844,
+          0.844, 0.76, 0.676, 0.676, 0.676, 0.676, 0.507, 0.507]
+
+    # https://www.real-statistics.com/survival-analysis/kaplan-meier-procedure/confidence-interval-for-the-survival-function/
+    t5 = [3, 5, 8, 10, 5, 5, 8, 12, 15, 14, 2, 11, 10, 9, 12, 5, 8, 11]
+    d5 = [1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1]
+    r5 = [0.944, 0.889, 0.722, 0.542, 0.542, 0.542, 0.361, 0.181, 0.181, 0.181]
+
+    @pytest.mark.parametrize("case", [(t1, d1, r1), (t2, d2, r2), (t3, d3, r3),
+                                      (t4, d4, r4), (t5, d5, r5)])
+    def test_right_censored_against_examples(self, case):
+        # test `ecdf` against other implementations on example problems
+        times, died, ref = case
+        sample = stats.CensoredData.right_censored(times, np.logical_not(died))
+        res = stats.ecdf(sample)
+        assert_allclose(res.sf.probabilities, ref, atol=1e-3)
+        assert_equal(res.sf.quantiles, np.sort(np.unique(times)))
+
+        # test reference implementation against other implementations
+        res = _kaplan_meier_reference(times, np.logical_not(died))
+        assert_equal(res[0], np.sort(np.unique(times)))
+        assert_allclose(res[1], ref, atol=1e-3)
+
+    @pytest.mark.parametrize('seed', [182746786639392128, 737379171436494115,
+                                      576033618403180168, 308115465002673650])
+    def test_right_censored_against_reference_implementation(self, seed):
+        # test `ecdf` against reference implementation on random problems
+        rng = np.random.default_rng(seed)
+        n_unique = rng.integers(10, 100)
+        sample, times, censored = self.get_random_sample(rng, n_unique)
+        res = stats.ecdf(sample)
+        ref = _kaplan_meier_reference(times, censored)
+        assert_allclose(res.sf.quantiles, ref[0])
+        assert_allclose(res.sf.probabilities, ref[1])
+
+        # If all observations are uncensored, the KM estimate should match
+        # the usual estimate for uncensored data
+        sample = stats.CensoredData(uncensored=times)
+        res = _survival._ecdf_right_censored(sample)  # force Kaplan-Meier
+        ref = stats.ecdf(times)
+        assert_equal(res[0], ref.sf.quantiles)
+        assert_allclose(res[1], ref.cdf.probabilities, rtol=1e-14)
+        assert_allclose(res[2], ref.sf.probabilities, rtol=1e-14)
+
+    def test_right_censored_ci(self):
+        # test "greenwood" confidence interval against example 4 (URL above).
+        times, died = self.t4, self.d4
+        sample = stats.CensoredData.right_censored(times, np.logical_not(died))
+        res = stats.ecdf(sample)
+        ref_allowance = [0.096, 0.096, 0.135, 0.162, 0.162, 0.162, 0.162,
+                         0.162, 0.162, 0.162, 0.214, 0.246, 0.246, 0.246,
+                         0.246, 0.341, 0.341]
+
+        sf_ci = res.sf.confidence_interval()
+        cdf_ci = res.cdf.confidence_interval()
+        allowance = res.sf.probabilities - sf_ci.low.probabilities
+
+        assert_allclose(allowance, ref_allowance, atol=1e-3)
+        assert_allclose(sf_ci.low.probabilities,
+                        np.clip(res.sf.probabilities - allowance, 0, 1))
+        assert_allclose(sf_ci.high.probabilities,
+                        np.clip(res.sf.probabilities + allowance, 0, 1))
+        assert_allclose(cdf_ci.low.probabilities,
+                        np.clip(res.cdf.probabilities - allowance, 0, 1))
+        assert_allclose(cdf_ci.high.probabilities,
+                        np.clip(res.cdf.probabilities + allowance, 0, 1))
+
+        # test "log-log" confidence interval against Mathematica
+        # e = {24, 3, 11, 19, 24, 13, 14, 2, 18, 17, 24, 21, 12, 1, 10, 23, 6, 5,
+        #      9, 17}
+        # ci = {1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0}
+        # R = EventData[e, ci]
+        # S = SurvivalModelFit[R]
+        # S["PointwiseIntervals", ConfidenceLevel->0.95,
+        #   ConfidenceTransform->"LogLog"]
+
+        ref_low = [0.694743, 0.694743, 0.647529, 0.591142, 0.591142, 0.591142,
+                   0.591142, 0.591142, 0.591142, 0.591142, 0.464605, 0.370359,
+                   0.370359, 0.370359, 0.370359, 0.160489, 0.160489]
+        ref_high = [0.992802, 0.992802, 0.973299, 0.947073, 0.947073, 0.947073,
+                    0.947073, 0.947073, 0.947073, 0.947073, 0.906422, 0.856521,
+                    0.856521, 0.856521, 0.856521, 0.776724, 0.776724]
+        sf_ci = res.sf.confidence_interval(method='log-log')
+        assert_allclose(sf_ci.low.probabilities, ref_low, atol=1e-6)
+        assert_allclose(sf_ci.high.probabilities, ref_high, atol=1e-6)
+
+    def test_right_censored_ci_example_5(self):
+        # test "exponential greenwood" confidence interval against example 5
+        times, died = self.t5, self.d5
+        sample = stats.CensoredData.right_censored(times, np.logical_not(died))
+        res = stats.ecdf(sample)
+        lower = np.array([0.66639, 0.624174, 0.456179, 0.287822, 0.287822,
+                          0.287822, 0.128489, 0.030957, 0.030957, 0.030957])
+        upper = np.array([0.991983, 0.970995, 0.87378, 0.739467, 0.739467,
+                          0.739467, 0.603133, 0.430365, 0.430365, 0.430365])
+
+        sf_ci = res.sf.confidence_interval(method='log-log')
+        cdf_ci = res.cdf.confidence_interval(method='log-log')
+
+        assert_allclose(sf_ci.low.probabilities, lower, atol=1e-5)
+        assert_allclose(sf_ci.high.probabilities, upper, atol=1e-5)
+        assert_allclose(cdf_ci.low.probabilities, 1-upper, atol=1e-5)
+        assert_allclose(cdf_ci.high.probabilities, 1-lower, atol=1e-5)
+
+        # Test against R's `survival` library `survfit` function, 90%CI
+        # library(survival)
+        # options(digits=16)
+        # time = c(3, 5, 8, 10, 5, 5, 8, 12, 15, 14, 2, 11, 10, 9, 12, 5, 8, 11)
+        # status = c(1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1)
+        # res = survfit(Surv(time, status)
+        # ~1, conf.type = "log-log", conf.int = 0.90)
+        # res$time; res$lower; res$upper
+        low = [0.74366748406861172, 0.68582332289196246, 0.50596835651480121,
+               0.32913131413336727, 0.32913131413336727, 0.32913131413336727,
+               0.15986912028781664, 0.04499539918147757, 0.04499539918147757,
+               0.04499539918147757]
+        high = [0.9890291867238429, 0.9638835422144144, 0.8560366823086629,
+                0.7130167643978450, 0.7130167643978450, 0.7130167643978450,
+                0.5678602982997164, 0.3887616766886558, 0.3887616766886558,
+                0.3887616766886558]
+        sf_ci = res.sf.confidence_interval(method='log-log',
+                                           confidence_level=0.9)
+        assert_allclose(sf_ci.low.probabilities, low)
+        assert_allclose(sf_ci.high.probabilities, high)
+
+        # And with conf.type = "plain"
+        low = [0.8556383113628162, 0.7670478794850761, 0.5485720663578469,
+               0.3441515412527123, 0.3441515412527123, 0.3441515412527123,
+               0.1449184105424544, 0., 0., 0.]
+        high = [1., 1., 0.8958723780865975, 0.7391817920806210,
+                0.7391817920806210, 0.7391817920806210, 0.5773038116797676,
+                0.3642270254596720, 0.3642270254596720, 0.3642270254596720]
+        sf_ci = res.sf.confidence_interval(confidence_level=0.9)
+        assert_allclose(sf_ci.low.probabilities, low)
+        assert_allclose(sf_ci.high.probabilities, high)
+
+    def test_right_censored_ci_nans(self):
+        # test `ecdf` confidence interval on a problem that results in NaNs
+        times, died = self.t1, self.d1
+        sample = stats.CensoredData.right_censored(times, np.logical_not(died))
+        res = stats.ecdf(sample)
+
+        # Reference values generated with Matlab
+        # format long
+        # t = [37 43 47 56 60 62 71 77 80 81];
+        # d = [0 0 1 1 0 0 0 1 1 1];
+        # censored = ~d1;
+        # [f, x, flo, fup] = ecdf(t, 'Censoring', censored, 'Alpha', 0.05);
+        x = [37, 47, 56, 77, 80, 81]
+        flo = [np.nan, 0, 0, 0.052701464070711, 0.337611126231790, np.nan]
+        fup = [np.nan, 0.35417230377, 0.5500569798, 0.9472985359, 1.0, np.nan]
+        i = np.searchsorted(res.cdf.quantiles, x)
+
+        message = "The confidence interval is undefined at some observations"
+        with pytest.warns(RuntimeWarning, match=message):
+            ci = res.cdf.confidence_interval()
+
+        # Matlab gives NaN as the first element of the CIs. Mathematica agrees,
+        # but R's survfit does not. It makes some sense, but it's not what the
+        # formula gives, so skip that element.
+        assert_allclose(ci.low.probabilities[i][1:], flo[1:])
+        assert_allclose(ci.high.probabilities[i][1:], fup[1:])
+
+        # [f, x, flo, fup] = ecdf(t, 'Censoring', censored, 'Function',
+        #                        'survivor', 'Alpha', 0.05);
+        flo = [np.nan, 0.64582769623, 0.449943020228, 0.05270146407, 0, np.nan]
+        fup = [np.nan, 1.0, 1.0, 0.947298535929289, 0.662388873768210, np.nan]
+        i = np.searchsorted(res.cdf.quantiles, x)
+
+        with pytest.warns(RuntimeWarning, match=message):
+            ci = res.sf.confidence_interval()
+
+        assert_allclose(ci.low.probabilities[i][1:], flo[1:])
+        assert_allclose(ci.high.probabilities[i][1:], fup[1:])
+
+        # With the same data, R's `survival` library `survfit` function
+        # doesn't produce the leading NaN
+        # library(survival)
+        # options(digits=16)
+        # time = c(37, 43, 47, 56, 60, 62, 71, 77, 80, 81)
+        # status = c(0, 0, 1, 1, 0, 0, 0, 1, 1, 1)
+        # res = survfit(Surv(time, status)
+        # ~1, conf.type = "plain", conf.int = 0.95)
+        # res$time
+        # res$lower
+        # res$upper
+        low = [1., 1., 0.64582769623233816, 0.44994302022779326,
+               0.44994302022779326, 0.44994302022779326, 0.44994302022779326,
+               0.05270146407071086, 0., np.nan]
+        high = [1., 1., 1., 1., 1., 1., 1., 0.9472985359292891,
+                0.6623888737682101, np.nan]
+        assert_allclose(ci.low.probabilities, low)
+        assert_allclose(ci.high.probabilities, high)
+
+        # It does with conf.type="log-log", as do we
+        with pytest.warns(RuntimeWarning, match=message):
+            ci = res.sf.confidence_interval(method='log-log')
+        low = [np.nan, np.nan, 0.38700001403202522, 0.31480711370551911,
+               0.31480711370551911, 0.31480711370551911, 0.31480711370551911,
+               0.08048821148507734, 0.01049958986680601, np.nan]
+        high = [np.nan, np.nan, 0.9813929658789660, 0.9308983170906275,
+                0.9308983170906275, 0.9308983170906275, 0.9308983170906275,
+                0.8263946341076415, 0.6558775085110887, np.nan]
+        assert_allclose(ci.low.probabilities, low)
+        assert_allclose(ci.high.probabilities, high)
+
+    def test_right_censored_against_uncensored(self):
+        rng = np.random.default_rng(7463952748044886637)
+        sample = rng.integers(10, 100, size=1000)
+        censored = np.zeros_like(sample)
+        censored[np.argmax(sample)] = True
+        res = stats.ecdf(sample)
+        ref = stats.ecdf(stats.CensoredData.right_censored(sample, censored))
+        assert_equal(res.sf.quantiles, ref.sf.quantiles)
+        assert_equal(res.sf._n, ref.sf._n)
+        assert_equal(res.sf._d[:-1], ref.sf._d[:-1])  # difference @ [-1]
+        assert_allclose(res.sf._sf[:-1], ref.sf._sf[:-1], rtol=1e-14)
+
+    def test_plot_iv(self):
+        rng = np.random.default_rng(1769658657308472721)
+        n_unique = rng.integers(10, 100)
+        sample, _, _ = self.get_random_sample(rng, n_unique)
+        res = stats.ecdf(sample)
+
+        try:
+            import matplotlib.pyplot as plt  # noqa: F401
+            res.sf.plot()  # no other errors occur
+        except (ModuleNotFoundError, ImportError):
+            message = r"matplotlib must be installed to use method `plot`."
+            with pytest.raises(ModuleNotFoundError, match=message):
+                res.sf.plot()
+
+
+class TestLogRank:
+
+    @pytest.mark.parametrize(
+        "x, y, statistic, pvalue",
+        # Results validate with R
+        # library(survival)
+        # options(digits=16)
+        #
+        # futime_1 <- c(8, 12, 26, 14, 21, 27, 8, 32, 20, 40)
+        # fustat_1 <- c(1, 1, 1, 1, 1, 1, 0, 0, 0, 0)
+        # rx_1 <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
+        #
+        # futime_2 <- c(33, 28, 41, 48, 48, 25, 37, 48, 25, 43)
+        # fustat_2 <- c(1, 1, 1, 0, 0, 0, 0, 0, 0, 0)
+        # rx_2 <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
+        #
+        # futime <- c(futime_1, futime_2)
+        # fustat <- c(fustat_1, fustat_2)
+        # rx <- c(rx_1, rx_2)
+        #
+        # survdiff(formula = Surv(futime, fustat) ~ rx)
+        #
+        # Also check against another library which handle alternatives
+        # library(nph)
+        # logrank.test(futime, fustat, rx, alternative = "two.sided")
+        # res["test"]
+        [(
+              # https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/BS704_Survival5.html
+              # uncensored, censored
+              [[8, 12, 26, 14, 21, 27], [8, 32, 20, 40]],
+              [[33, 28, 41], [48, 48, 25, 37, 48, 25, 43]],
+              # chi2, ["two-sided", "less", "greater"]
+              6.91598157449,
+              [0.008542873404, 0.9957285632979385, 0.004271436702061537]
+         ),
+         (
+              # https://sphweb.bumc.bu.edu/otlt/mph-modules/bs/bs704_survival/BS704_Survival5.html
+              [[19, 6, 5, 4], [20, 19, 17, 14]],
+              [[16, 21, 7], [21, 15, 18, 18, 5]],
+              0.835004855038,
+              [0.3608293039, 0.8195853480676912, 0.1804146519323088]
+         ),
+         (
+              # Bland, Altman, "The logrank test", BMJ, 2004
+              # https://www.bmj.com/content/328/7447/1073.short
+              [[6, 13, 21, 30, 37, 38, 49, 50, 63, 79, 86, 98, 202, 219],
+               [31, 47, 80, 82, 82, 149]],
+              [[10, 10, 12, 13, 14, 15, 16, 17, 18, 20, 24, 24, 25, 28, 30,
+                33, 35, 37, 40, 40, 46, 48, 76, 81, 82, 91, 112, 181],
+               [34, 40, 70]],
+              7.49659416854,
+              [0.006181578637, 0.003090789318730882, 0.9969092106812691]
+         )]
+    )
+    def test_log_rank(self, x, y, statistic, pvalue):
+        x = stats.CensoredData(uncensored=x[0], right=x[1])
+        y = stats.CensoredData(uncensored=y[0], right=y[1])
+
+        for i, alternative in enumerate(["two-sided", "less", "greater"]):
+            res = stats.logrank(x=x, y=y, alternative=alternative)
+
+            # we return z and use the normal distribution while other framework
+            # return z**2. The p-value are directly comparable, but we have to
+            # square the statistic
+            assert_allclose(res.statistic**2, statistic, atol=1e-10)
+            assert_allclose(res.pvalue, pvalue[i], atol=1e-10)
+
+    def test_raises(self):
+        sample = stats.CensoredData([1, 2])
+
+        msg = r"`y` must be"
+        with pytest.raises(ValueError, match=msg):
+            stats.logrank(x=sample, y=[[1, 2]])
+
+        msg = r"`x` must be"
+        with pytest.raises(ValueError, match=msg):
+            stats.logrank(x=[[1, 2]], y=sample)
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_tukeylambda_stats.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_tukeylambda_stats.py
new file mode 100644
index 0000000000000000000000000000000000000000..8041658599a6ed5b2cd70def1a92bffe0d851792
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_tukeylambda_stats.py
@@ -0,0 +1,85 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+
+from scipy.stats._tukeylambda_stats import (tukeylambda_variance,
+                                            tukeylambda_kurtosis)
+
+
+def test_tukeylambda_stats_known_exact():
+    """Compare results with some known exact formulas."""
+    # Some exact values of the Tukey Lambda variance and kurtosis:
+    # lambda   var      kurtosis
+    #   0     pi**2/3     6/5     (logistic distribution)
+    #  0.5    4 - pi    (5/3 - pi/2)/(pi/4 - 1)**2 - 3
+    #   1      1/3       -6/5     (uniform distribution on (-1,1))
+    #   2      1/12      -6/5     (uniform distribution on (-1/2, 1/2))
+
+    # lambda = 0
+    var = tukeylambda_variance(0)
+    assert_allclose(var, np.pi**2 / 3, atol=1e-12)
+    kurt = tukeylambda_kurtosis(0)
+    assert_allclose(kurt, 1.2, atol=1e-10)
+
+    # lambda = 0.5
+    var = tukeylambda_variance(0.5)
+    assert_allclose(var, 4 - np.pi, atol=1e-12)
+    kurt = tukeylambda_kurtosis(0.5)
+    desired = (5./3 - np.pi/2) / (np.pi/4 - 1)**2 - 3
+    assert_allclose(kurt, desired, atol=1e-10)
+
+    # lambda = 1
+    var = tukeylambda_variance(1)
+    assert_allclose(var, 1.0 / 3, atol=1e-12)
+    kurt = tukeylambda_kurtosis(1)
+    assert_allclose(kurt, -1.2, atol=1e-10)
+
+    # lambda = 2
+    var = tukeylambda_variance(2)
+    assert_allclose(var, 1.0 / 12, atol=1e-12)
+    kurt = tukeylambda_kurtosis(2)
+    assert_allclose(kurt, -1.2, atol=1e-10)
+
+
+def test_tukeylambda_stats_mpmath():
+    """Compare results with some values that were computed using mpmath."""
+    a10 = dict(atol=1e-10, rtol=0)
+    a12 = dict(atol=1e-12, rtol=0)
+    data = [
+        # lambda        variance              kurtosis
+        [-0.1, 4.78050217874253547, 3.78559520346454510],
+        [-0.0649, 4.16428023599895777, 2.52019675947435718],
+        [-0.05, 3.93672267890775277, 2.13129793057777277],
+        [-0.001, 3.30128380390964882, 1.21452460083542988],
+        [0.001, 3.27850775649572176, 1.18560634779287585],
+        [0.03125, 2.95927803254615800, 0.804487555161819980],
+        [0.05, 2.78281053405464501, 0.611604043886644327],
+        [0.0649, 2.65282386754100551, 0.476834119532774540],
+        [1.2, 0.242153920578588346, -1.23428047169049726],
+        [10.0, 0.00095237579757703597, 2.37810697355144933],
+        [20.0, 0.00012195121951131043, 7.37654321002709531],
+    ]
+
+    for lam, var_expected, kurt_expected in data:
+        var = tukeylambda_variance(lam)
+        assert_allclose(var, var_expected, **a12)
+        kurt = tukeylambda_kurtosis(lam)
+        assert_allclose(kurt, kurt_expected, **a10)
+
+    # Test with vector arguments (most of the other tests are for single
+    # values).
+    lam, var_expected, kurt_expected = zip(*data)
+    var = tukeylambda_variance(lam)
+    assert_allclose(var, var_expected, **a12)
+    kurt = tukeylambda_kurtosis(lam)
+    assert_allclose(kurt, kurt_expected, **a10)
+
+
+def test_tukeylambda_stats_invalid():
+    """Test values of lambda outside the domains of the functions."""
+    lam = [-1.0, -0.5]
+    var = tukeylambda_variance(lam)
+    assert_equal(var, np.array([np.nan, np.inf]))
+
+    lam = [-1.0, -0.25]
+    kurt = tukeylambda_kurtosis(lam)
+    assert_equal(kurt, np.array([np.nan, np.inf]))
diff --git a/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_variation.py b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_variation.py
new file mode 100644
index 0000000000000000000000000000000000000000..789f393e28c3961261f0f53ef26ec21335b28f71
--- /dev/null
+++ b/Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/scipy/stats/tests/test_variation.py
@@ -0,0 +1,214 @@
+import math
+
+import numpy as np
+import pytest
+from numpy.testing import suppress_warnings
+
+from scipy.stats import variation
+from scipy._lib._util import AxisError
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import is_numpy
+from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close
+from scipy.stats._axis_nan_policy import (too_small_nd_omit, too_small_nd_not_omit,
+                                          SmallSampleWarning)
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+class TestVariation:
+    """
+    Test class for scipy.stats.variation
+    """
+
+    def test_ddof(self, xp):
+        x = xp.arange(9.0)
+        xp_assert_close(variation(x, ddof=1), xp.asarray(math.sqrt(60/8)/4))
+
+    @pytest.mark.parametrize('sgn', [1, -1])
+    def test_sign(self, sgn, xp):
+        x = xp.asarray([1., 2., 3., 4., 5.])
+        v = variation(sgn*x)
+        expected = xp.asarray(sgn*math.sqrt(2)/3)
+        xp_assert_close(v, expected, rtol=1e-10)
+
+    def test_scalar(self, xp):
+        # A scalar is treated like a 1-d sequence with length 1.
+        xp_assert_equal(variation(4.0), 0.0)
+
+    @pytest.mark.parametrize('nan_policy, expected',
+                             [('propagate', np.nan),
+                              ('omit', np.sqrt(20/3)/4)])
+    @skip_xp_backends(np_only=True,
+                      reason='`nan_policy` only supports NumPy backend')
+    def test_variation_nan(self, nan_policy, expected, xp):
+        x = xp.arange(10.)
+        x[9] = xp.nan
+        xp_assert_close(variation(x, nan_policy=nan_policy), expected)
+
+    @skip_xp_backends(np_only=True,
+                      reason='`nan_policy` only supports NumPy backend')
+    def test_nan_policy_raise(self, xp):
+        x = xp.asarray([1.0, 2.0, xp.nan, 3.0])
+        with pytest.raises(ValueError, match='input contains nan'):
+            variation(x, nan_policy='raise')
+
+    @skip_xp_backends(np_only=True,
+                      reason='`nan_policy` only supports NumPy backend')
+    def test_bad_nan_policy(self, xp):
+        with pytest.raises(ValueError, match='must be one of'):
+            variation([1, 2, 3], nan_policy='foobar')
+
+    @skip_xp_backends(np_only=True,
+                      reason='`keepdims` only supports NumPy backend')
+    def test_keepdims(self, xp):
+        x = xp.reshape(xp.arange(10), (2, 5))
+        y = variation(x, axis=1, keepdims=True)
+        expected = np.array([[np.sqrt(2)/2],
+                             [np.sqrt(2)/7]])
+        xp_assert_close(y, expected)
+
+    @skip_xp_backends(np_only=True,
+                      reason='`keepdims` only supports NumPy backend')
+    @pytest.mark.parametrize('axis, expected',
+                             [(0, np.empty((1, 0))),
+                              (1, np.full((5, 1), fill_value=np.nan))])
+    def test_keepdims_size0(self, axis, expected, xp):
+        x = xp.zeros((5, 0))
+        if axis == 1:
+            with pytest.warns(SmallSampleWarning, match=too_small_nd_not_omit):
+                y = variation(x, axis=axis, keepdims=True)
+        else:
+            y = variation(x, axis=axis, keepdims=True)
+        xp_assert_equal(y, expected)
+
+    @skip_xp_backends(np_only=True,
+                      reason='`keepdims` only supports NumPy backend')
+    @pytest.mark.parametrize('incr, expected_fill', [(0, np.inf), (1, np.nan)])
+    def test_keepdims_and_ddof_eq_len_plus_incr(self, incr, expected_fill, xp):
+        x = xp.asarray([[1, 1, 2, 2], [1, 2, 3, 3]])
+        y = variation(x, axis=1, ddof=x.shape[1] + incr, keepdims=True)
+        xp_assert_equal(y, xp.full((2, 1), fill_value=expected_fill))
+
+    @skip_xp_backends(np_only=True,
+                      reason='`nan_policy` only supports NumPy backend')
+    def test_propagate_nan(self, xp):
+        # Check that the shape of the result is the same for inputs
+        # with and without nans, cf gh-5817
+        a = xp.reshape(xp.arange(8, dtype=float), (2, -1))
+        a[1, 0] = xp.nan
+        v = variation(a, axis=1, nan_policy="propagate")
+        xp_assert_close(v, [math.sqrt(5/4)/1.5, xp.nan], atol=1e-15)
+
+    @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+    def test_axis_none(self, xp):
+        # Check that `variation` computes the result on the flattened
+        # input when axis is None.
+        y = variation([[0, 1], [2, 3]], axis=None)
+        xp_assert_close(y, math.sqrt(5/4)/1.5)
+
+    def test_bad_axis(self, xp):
+        # Check that an invalid axis raises np.exceptions.AxisError.
+        x = xp.asarray([[1, 2, 3], [4, 5, 6]])
+        with pytest.raises((AxisError, IndexError)):
+            variation(x, axis=10)
+
+    def test_mean_zero(self, xp):
+        # Check that `variation` returns inf for a sequence that is not
+        # identically zero but whose mean is zero.
+        x = xp.asarray([10., -3., 1., -4., -4.])
+        y = variation(x)
+        xp_assert_equal(y, xp.asarray(xp.inf))
+
+        x2 = xp.stack([x, -10.*x])
+        y2 = variation(x2, axis=1)
+        xp_assert_equal(y2, xp.asarray([xp.inf, xp.inf]))
+
+    @pytest.mark.parametrize('x', [[0.]*5, [1, 2, np.inf, 9]])
+    def test_return_nan(self, x, xp):
+        x = xp.asarray(x)
+        # Test some cases where `variation` returns nan.
+        y = variation(x)
+        xp_assert_equal(y, xp.asarray(xp.nan, dtype=x.dtype))
+
+    @pytest.mark.parametrize('axis, expected',
+                             [(0, []), (1, [np.nan]*3), (None, np.nan)])
+    def test_2d_size_zero_with_axis(self, axis, expected, xp):
+        x = xp.empty((3, 0))
+        with suppress_warnings() as sup:
+            # torch
+            sup.filter(UserWarning, "std*")
+            if axis != 0:
+                if is_numpy(xp):
+                    with pytest.warns(SmallSampleWarning, match="See documentation..."):
+                        y = variation(x, axis=axis)
+                else:
+                    y = variation(x, axis=axis)
+            else:
+                y = variation(x, axis=axis)
+        xp_assert_equal(y, xp.asarray(expected))
+
+    def test_neg_inf(self, xp):
+        # Edge case that produces -inf: ddof equals the number of non-nan
+        # values, the values are not constant, and the mean is negative.
+        x1 = xp.asarray([-3., -5.])
+        xp_assert_equal(variation(x1, ddof=2), xp.asarray(-xp.inf))
+
+    @skip_xp_backends(np_only=True,
+                      reason='`nan_policy` only supports NumPy backend')
+    def test_neg_inf_nan(self, xp):
+        x2 = xp.asarray([[xp.nan, 1, -10, xp.nan],
+                         [-20, -3, xp.nan, xp.nan]])
+        xp_assert_equal(variation(x2, axis=1, ddof=2, nan_policy='omit'),
+                        [-xp.inf, -xp.inf])
+
+    @skip_xp_backends(np_only=True,
+                      reason='`nan_policy` only supports NumPy backend')
+    @pytest.mark.parametrize("nan_policy", ['propagate', 'omit'])
+    def test_combined_edge_cases(self, nan_policy, xp):
+        x = xp.array([[0, 10, xp.nan, 1],
+                      [0, -5, xp.nan, 2],
+                      [0, -5, xp.nan, 3]])
+        if nan_policy == 'omit':
+            with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
+                y = variation(x, axis=0, nan_policy=nan_policy)
+        else:
+            y = variation(x, axis=0, nan_policy=nan_policy)
+        xp_assert_close(y, [xp.nan, xp.inf, xp.nan, math.sqrt(2/3)/2])
+
+    @skip_xp_backends(np_only=True,
+                      reason='`nan_policy` only supports NumPy backend')
+    @pytest.mark.parametrize(
+        'ddof, expected',
+        [(0, [np.sqrt(1/6), np.sqrt(5/8), np.inf, 0, np.nan, 0.0, np.nan]),
+         (1, [0.5, np.sqrt(5/6), np.inf, 0, np.nan, 0, np.nan]),
+         (2, [np.sqrt(0.5), np.sqrt(5/4), np.inf, np.nan, np.nan, 0, np.nan])]
+    )
+    def test_more_nan_policy_omit_tests(self, ddof, expected, xp):
+        # The slightly strange formatting in the follow array is my attempt to
+        # maintain a clean tabular arrangement of the data while satisfying
+        # the demands of pycodestyle.  Currently, E201 and E241 are not
+        # disabled by the `noqa` annotation.
+        nan = xp.nan
+        x = xp.asarray([[1.0, 2.0, nan, 3.0],
+                        [0.0, 4.0, 3.0, 1.0],
+                        [nan, -.5, 0.5, nan],
+                        [nan, 9.0, 9.0, nan],
+                        [nan, nan, nan, nan],
+                        [3.0, 3.0, 3.0, 3.0],
+                        [0.0, 0.0, 0.0, 0.0]])
+        with pytest.warns(SmallSampleWarning, match=too_small_nd_omit):
+            v = variation(x, axis=1, ddof=ddof, nan_policy='omit')
+        xp_assert_close(v, expected)
+
+    @skip_xp_backends(np_only=True,
+                      reason='`nan_policy` only supports NumPy backend')
+    def test_variation_ddof(self, xp):
+        # test variation with delta degrees of freedom
+        # regression test for gh-13341
+        a = xp.asarray([1., 2., 3., 4., 5.])
+        nan_a = xp.asarray([1, 2, 3, xp.nan, 4, 5, xp.nan])
+        y = variation(a, ddof=1)
+        nan_y = variation(nan_a, nan_policy="omit", ddof=1)
+        xp_assert_close(y, math.sqrt(5/2)/3)
+        assert y == nan_y